在数组中搜索增加整数的序列

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

这是任务:

创建一个程序,查看200-element随机生成的整数数组,其值介于25225之间。该程序应该查找保持非递减值的n连续索引 - 例如:

28, 57, 88, 153, 201被认为是成功的

28, 57, 32, 153, 201被认为是失败的。

输出应该类似于:

An increasing consecutive run of 5 elements found at:

Index 41 contains 28
Index 42 contains 57
Index 43 contains 88
Index 44 contains 153
Index 45 contains 201

有很多方法可以完成这项任务。我在下面提供了一个有效的分步解决方案。

java arrays random iteration
1个回答
0
投票

首先,应用给定的信息(下限,上限,数组大小)。

    int min = 25;
    int max = 225;
    int set[] = new int[200];

n设置为任意值。我将使用5作为演示目的。

    int n = 5;

创建一个counter变量来记录找到的连续整数的数量。此外,我们将添加逻辑以在每次数字序列不起作用时重置计数器。

    int counter = 0;

开始迭代。创建一个for循环,用指定边界之间的'200'元素填充数组。

    for(int i = 0; i < set.length; i++){
        set[i] = (int)(Math.random() * (max - min + 1) + min);

打印出每个索引的内容。

        System.out.println((i + 1) +") " + "Index " + i + " contains " + set[i]);

第一个if语句:每次序列符合模式时,这将使'counter'递增1,但在比较失败时将其重置为0。

   if(i > 0){   
        if(set[i] >= set[i-1]){counter++;}
        else{counter = 0;}  
    }// End if

现在创建一个while语句,当counter的值等于n的值时激活。这将打印出语句An increasing consecutive run of 5 elements found at:,然后导致for循环。

    while(counter == n){

           System.out.println("An increasing consecutive run of " + n + " elements found at:");

现在设置此循环以简单地打印出成功的n行。

    for(int j = i - n; j < i; j++){
        System.out.println("Index " + j + " contains " + set[j]);
    } //End for

告知代码在满足所有条件后停止运行。

       return;

只需关闭while和for循环,程序就完成了。

        } //End while

    } //End for
© www.soinside.com 2019 - 2024. All rights reserved.