如何从一组随机数中计算0和1的最短组合?

问题描述 投票:-3回答:1

我需要将L&N作为输入,将N作为0-1之间的随机数组的长度运行,并计算阵列中L 1的最短组合,然后打印答案。我如何用Java做到这一点?

int L = Integer.parseInt(args[0]);
int N = Integer.parseInt(args[1]);
int bArr [] = new int [N]; 
int countZeros = 0;
int countOnes = 0;
for(int i = 0 ; i < N; i++){
  int r = (int)(Math.random()* (2));
  bArr [i] = r;
java arrays loops
1个回答
0
投票

你可以计算你一起看过多少个,也就是你在看到1时增加计数,并在看到0时将计数重置为零。

在重置为0之前,最后,如果计数不是0,那么它是1的连胜的长度。如果那是你到目前为止看到的最短的1-streak,你还记得另一个变量。

伪代码:

shortestStreak = very high value, e.g. length of array + 1, or MAX_VALUE
streak = 0
for each value:
    if value = 1:
        streak++
    else:
        if streak > 0 and streak < shortestStreak:
            shortestStreak = streak
        streak = 0
if streak > 0 and streak < shortestStreak:
    shortestStreak = streak
if shortestStreak > length of array:
    print 'No ones found'
else:
    print shortestStreak
© www.soinside.com 2019 - 2024. All rights reserved.