0

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?

4
  • Does the index of the value changed back to true have to be randomly selected, or can it just be the value which has been false longest? Commented Apr 17, 2015 at 19:46
  • Would be preferable to be the one being false longest Commented Apr 17, 2015 at 19:47
  • If you just want to find all indices whose value is false, do var falseIndices = Enumerable.Range(0, isAvailable.Length).Select(i => !isAvailable[i]);. Commented Apr 17, 2015 at 19:47
  • But there's nothing in the code you've shown that indicates which has been false longest. Commented Apr 17, 2015 at 19:47

1 Answer 1

4

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) + "]");
}
Sign up to request clarification or add additional context in comments.

1 Comment

Haven't used Queue before. So thanks alot for showing me and it worked perfectly

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.