Reputation: 1373
bool[] isAvailable = new boolean[5];
Initially im setting all values in the array to true.
I'm now changing (one at a time) the values (randomly chosen) to false and I need a way to turn one of the false values back to true if there exists more than 3 false values. Furthermore it must not be the last changed value that becomes true.
I'm using LinQ and C#:
void checkArray() {
if (isAvailable.Where (c => !c).Count () > 3) {
int posOpen = ???;
}
}
Scenario:
[true,true,true,true,true] -> [true,true,true,true,false] ->
[true,true,false,true,false] -> [false,true,false,true,false] ->
[false,true,true,true,false] -> [false,false,true,true,false] etc..
Can anyone explain how-to?
Upvotes: 0
Views: 925
Reputation: 156524
Rather than changing the index values directly, you would do well to wrap the changes in a helper method, which can then respond to changes. You can keep track of the order in which items were made false using a Queue, and then change them back once the Queue hits a certain size.
void Main()
{
ShowArray(); //[True, True, True, True, True]
ChangeValue(1);
ShowArray(); //[True, False, True, True, True]
ChangeValue(4);
ShowArray(); //[True, False, True, True, False]
ChangeValue(3);
ShowArray(); //[True, False, True, False, False]
ChangeValue(0);
ShowArray(); //[False, True, True, False, False]
}
bool[] _array = {true,true,true,true,true};
Queue<int> _changed = new Queue<int>();
void ChangeValue(int index)
{
if(_array[index]) // do nothing if it was already false
{
_array[index] = false;
_changed.Enqueue(index);
if(_changed.Count() > 3)
{
_array[_changed.Dequeue()] = true;
}
}
}
void ShowArray()
{
Console.WriteLine("[" + string.Join(", ", _array) + "]");
}
Upvotes: 4