mardi 10 avril 2018

Reducing a triangular number into its respective values using an array

I have an assignment in which I need to start with a total of 45 "cards" separated into a random amount of piles (represented by an array of values), then reduce and redistribute those piles step-by-step until I have an array of 9 values, {1,2,3,4,5,6,7,8,9}, which add up to 45.

Each step involves taking a card from each pile and creating a new pile of the amount of cards taken. I need to output the number of cards in each pile for each step until the desired output is reached. The output should look something like this:

34   7   3   1
33   6   4   2
32   5   4   3  1
31   5   4   3  2
...
...
11   8   7   6  5  4  3  1
10   8   7   6  5  4  3  2 
9    8   7   6  5  4  3  2  1
-----------------------------
Number of rounds: 28

So far I'm stuck on figuring out how to even properly divide and assign the cards in a random fashion. So far I have:

#include <iostream>
#include <iomanip>
#include <cstdlib>

using namespace std;

bool IsFinished();

int main() {
  srand(time(NULL));
  int randomInteger = rand() % 45 + 1;
  int stackCount [randomInteger];
  int tempCounter = 0;
  int sum = 0;

  for (size_t i = 0; i < randomInteger; i++) {
    while (sum < 45) {
      tempCounter = rand() % 15 + 1;
      if (sum + tempCounter <= 45) {
        stackCount[i] = tempCounter;
      }
      else {
        stackCount[i] = 45 - sum;
      }
    sum += stackCount[i];
    }
  }
}

bool IsFinished(int stackCount[]) {
  int finishCheck[] = {1,2,3,4,5,6,7,8,9};
  int counter = 0;

  for (size_t i = 0; i < 8; i++) {
    if (finishCheck[i] == stackCount[i]) {
      counter++;
    }
  }

  if (counter == 9) {
    return true;
  }
  else {
    return false;
  }
}

(The IsFinished function is the one that will be called to check for completion)

I'm fairly sure I'm not using the most concise method for this problem... I'm also wondering how I'll be able to dynamically add or remove indices from the array as I change the sizes of the piles. Could any of you C++ wizards point me in the right direction?




Aucun commentaire:

Enregistrer un commentaire