[英]Searching an array for a sequence of increasing integers
這是任務:
創建一個程序,該程序查看200
元素的隨機生成整數數組,其值介於25
和225
之間。 程序應該尋找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
有很多方法可以完成這項任務。 我在下面提供了一個工作分步解決方案。
解決方案
首先,應用給定的信息(下限、上限、數組大小)。
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.