计算java

时间:2017-04-28 01:27:59

标签: java arrays

我想计算这个数字的模式

int data[] = new[24, 26, 28, 29, 30, 32, 32, 35, 37, 38, 38, 40, 41, 42, 43, 44, 44, 45, 45, 46, 47, 47, 47, 48, 48, 48, 48, 49, 49, 50, 50, 50, 51, 52, 52, 53, 53, 53, 53, 53, 54, 54, 56, 56, 56, 57, 57, 57, 57, 58, 58, 58, 59, 60, 60, 60, 60, 61, 61, 61, 61, 62, 62, 62, 62, 62, 63, 64, 64, 64, 65, 65, 65, 66, 66, 66, 67, 67, 67, 67, 67, 68, 70, 71, 71, 72, 72, 72, 73, 73, 73, 75, 76, 76, 76, 76, 77, 77, 77, 77, 77, 78, 78, 78, 78, 78, 80, 80, 80, 81, 82, 83, 84, 85, 85, 85, 85, 85, 88, 89, 91, 91, 93, 96, 97]

我已经做了一些编码来找到这里的数字模式是代码

public static void Mode(int numbers[]) {
    IntStream.range(0, numbers.length).forEach(i -> {
        IntStream.range(0, numbers.length).forEach(j -> {
            if (numbers[j] == numbers[i]) {
                ++count;
            }
            if (count > maxCount) {
                maxCount = count;
                mode = numbers[i];
            }
        });
    });
    System.out.println(String.format("%s %s", "Mode is :  ", mode));
}

上述方法仅返回一个值为模式53

然而,根据数学逻辑,模式应 53,62,67,77,78,85 。我想在不使用keyvalue对(没有Hashmap)的情况下获得上述模式

请告诉我如何实现这个目标

1 个答案:

答案 0 :(得分:1)

假设输入数据中的最大数字是一个合理的数字,此代码将找到模式。我确信有一种方法可以使它成为所有Java 8流,但我仍然在努力掌握它们。

    public static void main(String[] args)
{
    final int data[] = new int[] {24, 26, 28, 29, 30, 32, 32, 35, 37, 38, 38, 40, 41, 42, 43, 44, 44, 45, 45, 46, 47, 47, 47, 48, 48, 48, 48, 49, 49, 50, 50, 50, 51, 52, 52, 53, 53, 53, 53, 53, 54, 54, 56, 56, 56, 57, 57, 57, 57, 58, 58, 58, 59, 60, 60, 60, 60, 61, 61, 61, 61, 62, 62, 62, 62, 62, 63, 64, 64, 64, 65, 65, 65, 66, 66, 66, 67, 67, 67, 67, 67, 68, 70, 71, 71, 72, 72, 72, 73, 73, 73, 75, 76, 76, 76, 76, 77, 77, 77, 77, 77, 78, 78, 78, 78, 78, 80, 80, 80, 81, 82, 83, 84, 85, 85, 85, 85, 85, 88, 89, 91, 91, 93, 96, 97};
    final int MAX = 100;

    final int[] counts = new int[MAX];

    for (int i = 0; i < data.length; ++i) {
        int num = data[i];
        counts[num]++;
    }

    OptionalInt oi = Arrays.stream(counts).max();
    int cnt = oi.getAsInt();

    System.out.println("Modes for input data");
    for (int i = 0; i < counts.length; ++i) {
        if (counts[i] == cnt) {
            System.out.print(String.format("%3d", i));
        }
    }
    System.out.println();
   }

测试输出:

  

输入数据的模式

     

53 62 67 77 78 85

编辑:通过执行类似于以下操作的动态可以找到MAX。同样,假设这个最大值是合理的,但OP的问题限制了使用Map或类似对象的能力。

final int MAX = Arrays.stream(data).max().getAsInt();

final int[] counts = new int[MAX+1];