ブルートフォースなしで負の値を持つブール値 (bool[,]) の 2 次元配列でランダムな位置を選択する方法はありますか?
1670 次
3 に答える
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
また、おそらく保持して、反復間で再利用したいと思うでしょう。
于 2012-10-22T12:41:39.353 に答える
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;
}
}
}
于 2012-10-22T12:46:11.637 に答える
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;
}
}
ただし、これが役立つかどうかを尋ねるのはおそらく賢明です。特定の値が見つかるまで、多次元配列でランダムにプローブしたいのはなぜですか?別の方法で、より重要に、より効率的に解決できる根本的な問題はありませんか?
たとえば、この方法を使用すると、while()
ループが終了しない可能性があることに注意してください。
事前に配列をループして、aが存在する[x、y]インデックスを見つけ、false
それらの座標をたとえば別のリストに格納するTuple<int,int>
ことができます(または、@ MarcGravellによって投稿されたより洗練されたソリューションを使用します) 。
次に、そのリストからランダムなアイテムを選択すると、ランダムな[x,y]
場所values[x,y]
が表示されますfalse
。
于 2012-10-22T12:37:41.853 に答える