2012-10-22 37 views
1

有沒有一種方法可以在不使用bruteforcing的情況下在一個2d的bool數組(bool [,])中選擇一個具有負值的隨機位置?在數組中選擇一個隨機位置

+6

在這種情況下,你算什麼「蠻力」? –

+0

@Jon我猜*這意味着:繼續挑選點,直到發現一個「假」(我們希望至少有一個) –

+0

做隨機操作,直到找到二維數組中具有負值的位置。 – Max0999

回答

2

下面是一個非窮舉法,但它涉及到整個表的初始掃描:

int[] negOffsets = new int[data.Length]; 
int dataOffset = 0, count = 0; 
foreach(bool x in data) 
{ 
    if(!x) negOffsets[count++] = dataOffset; 
    dataOffset++; 
} 
if(count == 0) { 
    // nothing to pick 
} else { 
    int index = negOffsets[rand.Next(0, count)]; 

    int x = index/data.GetLength(1), 
     y = index % data.GetLength(0); 
    // assertion: the following should be false 
    bool b = data[x, y]; 
} 

此外,你可能會想保留offsets各地和迭代之間重新使用它。

0

是的,這是完全有可能:

var random = new Random(); 
int xBound = 100; 
int yBound = 100; 
var values = new bool[xBound, yBound]; 

// Fill the values array 
for (int y = 0; y < yBound; y++) 
{ 
    for (int x = 0; x < xBound; x++) 
    { 
     values[x, y] = random.Next(0, 2) == 1; 
    } 
} 

// Find the value at a random position that's false 
bool foundFalse = false; 
int probeX, probeY; 

while (!foundFalse) 
{ 
    probeX = random.Next(0, xBound); 
    probeY = random.Next(0, yBound); 

    if (values[probeX, probeY] == false) 
    { 
     // Do something with your probeX, probeY values perhaps 
     foundFalse = true; 
    } 
} 

Hoewever,它可能是明智的,問這是否有用。爲什麼你想在多維陣列中隨機探測,直到找到一個特定的值?是不是有一些潛在的問題可以以不同的方式解決,而且更重要,更有效?

請注意,例如,使用此方法,while()循環永遠不會完成。

您可以嘗試預先遍歷數組,以找到存在false的[x,y]索引,並將這些座標存儲在單獨的列表中,例如Tuple<int,int>(或使用更優雅解決方案由@MarcGravell發佈)。

然後,您可以從該列表中選擇一個隨機項目,然後您將有一個隨機[x,y],其中values[x,y]將爲false

+0

這正是我不想要的,我不希望任何探測/暴力破壞參與找到價值。 – Max0999

+0

@ Max0999然後更好地解釋你自己。您想做什麼?如果你只是簡單地選擇一個隨機的X和Y,並看看這些索引中的values數組,你可能會發現一個「true」而不是你想找到的「false」。那又怎麼樣? – CodeCaster

+0

我想從數組中選擇一個隨機的probeX,probeY,其中的值爲false,但沒有從數組中讀取數組的次數的可能性(這是必要的) – Max0999

1

希望你能從代碼中獲得想法。顯然它需要一些調整,但是概念是使用TestClass作爲數組的封面。不需要任何掃描和它的相當容易使用;)

public class TestClass 
    { 
     public bool[,] BoolArray 
     { 
      get; 
      private set; 
     } 
     private List<Tuple<int, int>> negativeValues; 

     public TestClass(int x, int y) 
     { 
      this.negativeValues = new List<Tuple<int, int>>(); 
      this.BoolArray = new bool[x, y]; 
     } 

     public Tuple<int, int> GetPosition() 
     { 
      if (this.negativeValues.Count > 0) 
      { 
       Random rand = new Random(); 
       return this.negativeValues[rand.Next(this.negativeValues.Count - 1)]; 
      } 
      else 
       return null; 
     } 



     public bool this[int x, int y] 
     { 
      get 
      { 
       return this.BoolArray[x, y]; 
      } 

      set 
      { 
       if (!value) 
        negativeValues.Add(new Tuple<int, int>(x, y)); 

       this.BoolArray[x][y] = value; 
      } 
     } 
    } 
+0

只要以前的「false」條目設置爲「true」,一定要刪除它們。 – CodeCaster