我正在嘗試掃描一個陣列,它跟在索引后面,里面有數字,我不明白為什么它會給我這個例外。我不能添加更多細節,這是一個非常直截了當的問題。

using System;
public class Program
{
public static bool IsPerfect(int[] arr)
{
int next=0, done=0,i;
while (done == 0)
{
i = arr[next];
arr[next] = 10;
next = arr[i];
if (i == 0)
done = 1;
}
for(int j = 0; j < arr.Length; j )
if (arr[j] != 10)
return false;
return true;
}
public static void Main()
{
int[] arr = { 3, 0, 1, 4, 2 };
if (IsPerfect(arr) == true)
Console.WriteLine("is perfect");
if (IsPerfect(arr) == false)
Console.WriteLine("boooo");
}
}
uj5u.com熱心網友回復:
您沒有指定重復項的功能...使用一種方法檢查重復項,一旦遇到重復元素退出回圈...它將正常作業!??
uj5u.com熱心網友回復:
好的,對于任何感興趣的人來說,問題在于第二個 if,以及“next = arr[i];” 第一個我改變了,因為它更有意義,第二個也是主要問題是另一個如果。因為我有第二個條件,所以它運行了兩次該方法,并且更改了值,它回傳了一個錯誤。解決方案是把 else 代替。
uj5u.com熱心網友回復:
逆向工程:我們標記訪問過的專案,如果所有專案都被訪問過,那么我們就有一個“完美”陣列。
問題:我們標記10可以作為索引的專案(如果陣列有15專案怎么辦)?
解決方案:讓我們標記-1(絕對不是索引 - 陣列可以有負數的專案)并檢查專案是否已被標記:
棘手的時刻:我們應該分配-1給當前arr[i]專案,但使用它的初始值分配給i。當然,我們可以保存i并把它作為
for (int i = 0; i >= 0 && i < arr.Length; ) {
int nextI = arr[i];
arr[i] = i;
i = nextI;
}
但讓我們以一種簡短的現代方式說:(i, arr[i]) = (arr[i], -1);
代碼:
public static bool IsPerfect(int[] arr) {
// In public method we must be ready for any input; null included
if (arr == null)
return false; // or throw new ArgumentNullException(nameof(arr));
// Do we have a valid array?
for (int i = 0; i < arr.Length; i)
if (arr[i] < 0 || arr[i] >= arr.Length)
return false;
// Note the condition: we read the next item - arr[i] -
// if and only if i is within range
// Note, that we have nothing to increment / decrement
for (int i = 0; i >= 0 && i < arr.Length; )
(i, arr[i]) = (arr[i], -1); // note the assignment: both i and arr[i] in one go
// We have marked all that we could.
// Do we have unmarked items?
for (int i = 0; i < arr.Length; i)
if (arr[i] != -1) // ... yes, we have and thus
return false; // arr is not perfect
return true;
}
請拉小提琴
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/526161.html
