我有一个List< KeyValuePair < int,int >>。(我之所以选择这种方式而不是字典,是因为多个键将是相同的(尽管连续的键不会相同);还因为我希望在顺序输入中输出它们)。
所有密钥都等于1-5 (含)之间的randNum。(关键字与我的问题并不重要)。
所有值都是默认值0。
我希望将其中1/4的值更改为等于1(其他值仍然等于0)。value=1在每个范围4中的位置是随机选择的。
我想要的输出示例,打印列表中的KVP:
[5,0]
[3,1]
[2,0]
[5,0]
[1,0]
[4,0]
[2,0]
[3,1]
[1,0]
[5,0]
[4,1]
[2,0]因此,在4个组中,值为: 0100 | 0001 | 0010。
这是我到目前为止一直尝试做的事情:(序列已经用所有的键设置好了)
List<KeyValuePair<int,int>> sequence = new List<KeyValuePair<int,int>>();
// Populate keys in sequence with random numbers 1-5
// ...
public static void SetSequenceValues()
{
Random randNum = new Random();
bool allValuesSet = false;
// count is the max (non-inclusive) in each range of 4
// i.e. first loop is 1-4
// then count += 4
// second loop is 5-8, etc.
int count = 5;
while (allValuesSet == false)
{
int randPos = randNum.Next(count - 4, count);
// If changing the first key in the range,
// the desired key index = count-4
if (randPos == count - 4)
{
var oldKVP = sequence[count - 4];
sequence[count - 4] = new KeyValuePair<int, int>(oldKVP.Key, 1);
}
else if (randPos == count -3)
{
var oldKVP = sequence[count - 3];
sequence[count -3] = new KeyValuePair<int, int>(oldKVP.Key, 1);
}
else if (randPos == count - 2)
{
var oldKVP = sequence[count - 2];
sequence[count - 2] = new KeyValuePair<int, int>(oldKVP.Key, 1);
}
else if (randPos == count - 1)
{
var oldKVP = sequence[count - 1];
sequence[count - 1] = new KeyValuePair<int, int>(oldKVP.Key, 1);
}
// Increase count by 4, so on the next loop, e.g. the range looked at will be 4-8 (not including 8, i.e. 4-7)
count += 4;
if (count >= sequence.Count)
allValuesSet = true;
}
}目前,输出有点接近,但偶尔每组中会有几个1。另外,我认为它可能是使用5人组而不是4人组?尽管这似乎也不是完全正确的。
https://stackoverflow.com/questions/47732365
复制相似问题