Java分组基于位置数组的坐标

时间:2016-02-21 08:00:07

标签: java arrays

我有一个x数组,其中包含一些双数组,如下所示:

 double x[] = {2, 4, 1, 1};

我还有3个数组,用于定义每个组中x值的位置:

 int[] cluster1 = {1}; //which means that first value in x array belongs to cluster 1
 int[] cluster2 = {2}; //second value in x array belongs to cluster 2
 int[] cluster3 = {3, 4}; //third value & forth value in x array belongs to cluster 3.

如何获得下面的输出?

Cluster 1: (2)
Cluster 2: (4)
Cluster 3: (1), (1)

值得注意的是,有时相同的值可能会在不同的群集中出现两次。谢谢你的帮助!

1 个答案:

答案 0 :(得分:1)

这是一种方法:

public static void main (String[] args)
{
    /* Values Array */
    double x[] = {2, 4, 1, 1};
    double y[] = {1, 3, 1, 9};

    /* Clusters Array */
    Double[] cluster1 = {1.0};
    Double[] cluster2 = {2.0};
    Double[] cluster3 = {3.0, 4.0};

    /* Print Cluster 1 Values */
    System.out.print("Cluster 1:");
    for(int i = 0; i < cluster1.length; i++) {
        System.out.print(" (" + x[cluster1[i].intValue() - 1] + "," + y[cluster1[i].intValue() - 1] + ")");
    }

    /* Print Cluster 2 Values */
    System.out.print("\nCluster 2:");
    for(int i = 0; i < cluster2.length; i++) {
        System.out.print(" (" + x[cluster2[i].intValue() - 1] + "," + y[cluster2[i].intValue() - 1] + ")");
    }

    /* Print Cluster 3 Values */
    System.out.print("\nCluster 3:");
    for(int i = 0; i < cluster3.length; i++) {
        System.out.print(" (" + x[cluster3[i].intValue() - 1] + "," + y[cluster3[i].intValue() - 1] + ")");
    }
}

输出:

Cluster 1: (2.0,1.0)
Cluster 2: (4.0,3.0)
Cluster 3: (1.0,1.0) (1.0,9.0)