2014-09-12 19 views
0

我有一個二維整數數組,代表我用來追蹤遊戲中物體位置的地圖。它被一個程序系統修改,它將改變那裏的數字來放置不同的對象。我會設置每個Int的值作爲0,1或2看起來是這樣的:由於程序上的步驟很大程度上依賴於隨機有一個更清晰的方法來留在數組的邊界內嗎?

00010 
00100 
02120 
21200 
12000 

,我想提出幾個檢查到位,如果陣列位置我試圖寫入數組的範圍之外,它會回落到地圖的邊緣而不是導致錯誤。例如我嘗試在[0,10]中輸入一個條目,它將默認爲[0,4]。 是的,我知道我應該小心確保我永遠不會試圖在數組邊界之外進行寫入,但給出了其他每次都不會發生的元素。理智檢查似乎是謹慎的。

我提出的解決方案的工作,但它似乎過分冗長和冗長。有沒有我不知道的更清潔的解決方案?

下面的代碼示例:

//Example of something randomly being written to the array 
random r = new Random(); 
int xMax = field.GetLength(0); 
field[mid(r.next(0,5), 0, xMax), 0] = 1; 

//Method for sanity bounds. 
private static int mid(int target, int min, int max) 
{ 
    //Target is the value we want 
    //Min is the smallest possible value 
    //Max is the largest possible value. 

    if (target == min) 
    { 
     return min; 
    } 
    if (target == max) 
    { 
     return max; 
    } 
    if (target < max && target > min) 
    { 
     return target; 
    } 
    else if (target > max && target > min) 
    { 
     return max; 
    } 
    else if (target < min && target < max) 
    { 
     return min; 
    } 
    return min; //This shouldn't ever get trigger. In here so compiler won't complain. 
} 
+0

我沒有回答你的問題,但也許你在你的方法最後一行 - '回報min' - 如果它應該拋出一個異常未定義/意外的行爲。 – 2014-09-12 16:14:51

+0

如果你正在訪問一個無效的索引,你應該*想讓你的程序崩潰,這樣你就會意識到你有一個bug並且可以修復它,而不是簡單地訪問錯誤的數組值並且隱藏問題,將難以發現和診斷。 – Servy 2014-09-12 16:17:02

+0

@DanPantry他不需要那樣做。在這種情況下,他可以刪除整個事物,只需讓數組索引器拋出一個超出綁定異常的索引即可。 – Servy 2014-09-12 16:17:30

回答

4

你可以這樣做:

public int mid(int target, int min, int max) 
{ 
    return Math.max(min, Math.min(max, target)); 
} 

該函數返回的最大預期值和綁定的最大的較小值,以確保有效值將被返回。


您還可以,如果你使用的是長方形的2維數組使用您的訪問%

array[index1 % array.length][index2 % array[0].length] = /* somevar */; 
+0

這真的很漂亮。謝謝。 – EtanSivad 2014-09-12 16:32:15

1

如果你想爲你描述的陣列周圍索引「包裝」,這應工作:

public void GetValidIndexForArrayFromRandomIndex(int index, string[] myArray) 
{ 
    var upperBound = myArray.GetUpperBound(0); 
    var lowerBound = myArray.GetLowerBound(0); 

    while (index > upperBound) 
    { 
     index -= upperBound + 1; 
    } 
    while (index < lowerBound) 
    { 
     index += upperBound; 
    } 

    return index; 
} 

或者這應該做你的代碼上面做:

// We really only need to test the upper and lower bounds. 
// If target is greater than max or less than min, then return the bound that it crossed 
if (target > max) return max; 
if (target < min) return min; 

// Otherwise, it's within the bounds, so just return target. 
return target; 

或者你可以做一個行:

return (target > max) ? max : (target < min) ? min : target; 
相關問題