make an algorithm with taking a deck of cards and alternating between red and black [C++]

Viewed 51

My current idea is to have two arrays for red and one for black adn just have another for loop with an if that will just add alternating black and red to a third array. I was told this was overcomplicated and I was missing a simpler solution, any guidance here? Im pretty sure I'd use a for loop with an if inside of it, but Im not sure how to do this with an unsorted deck

1 Answers

There is a simpler way that avoids copying to two separate 'red' and 'black' arrays. Here's an illustration that demonstrates with an unsorted deck of 4 black and 4 red cards.

An illustration of an unsorted array with elements that are randomly black or red. Below is an array with sorted interleaved pairs of black and red elements.

  1. Treat red / black cards as 'even' or 'odd'.
  2. Walk the input array element by element.
  3. If it is red (odd), insert into the next available odd slot in the output array.
  4. If it is black (even), insert into the next available even slot in the output array.

Once you've looped through all the input elements, the output array will have cards of alternating color.

Related