【问题标题】:How do I count the shortest combination of 0's and 1's from an array of random numbers?如何从随机数数组中计算 0 和 1 的最短组合?
【发布时间】:2017-12-17 16:29:00
【问题描述】:

我需要获得 LN 作为输入,以运行 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;

【问题讨论】:

  • “最短组合”是什么意思?你能提供一个示例输入和你期望得到的输出吗?
  • 刚刚改了
  • 到目前为止你做了什么?向我们展示你的代码,让我们看看你做错了什么。
  • 欢迎来到 Stack Overflow!不幸的是,您的问题仅包含要求 - 它没有显示您自己为解决此问题所做的任何努力。请在此问题中添加您的尝试 - 因为该站点不是免费的“我们为您提供(家庭)工作”服务。除此之外:请转至help center 了解如何/在这里问什么。谢谢!
  • 临近圣诞节还在做作业吗?

标签: java arrays loops


【解决方案1】:

您会记录一起看到的数量,即当看到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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-22
    相关资源
    最近更新 更多