//This program is a basic scrabble game with some error checking.
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define num_letters 7
#define tiles_max 100
//value 1 and 2 are the same, they were passed from a generate letter set if statement to determine the max
//value of things to add up
int sum_array (int value1, int letter_set[], int value2, int tile_set[]){
  int counter2, sum_of_array;
  sum_of_array = 0;
  for(counter2 = 0; counter2 < value1; counter2++){
    sum_of_array += tile_set[counter2] - letter_set[counter2];
  }
  return sum_of_array;
}

void generate_letter_set (int letter_set[], int size_letter_set, int lettersbgood){
  const int tile_set[] = {9, 2, 2, 4, 12, 2, 3, 2, 9, 1, 1, 4, 2, 6, 8, 2, 1, 6, 4, 6, 4, 2, 2, 1, 2, 1, 2};
  int counter1, counter3, chargen;
  srand((unsigned) time(NULL));
  for(counter1 = 0; counter1 < lettersbgood; counter1++){
    chargen = rand() % (tiles_max - counter1);
    for(counter3 = 0; counter3 < 27; counter3++){
      if(chargen >= sum_array(counter3, letter_set, counter3, tile_set) && chargen < (sum_array(counter3, letter_set, counter3, tile_set)+(tile_set[counter3]-letter_set[counter3]))){
    letter_set[counter3] += 1;
      }
    }
  }
}

int main()
{
  int size_letter_set = 27, counter4;
  int letter_set[27] = {0};
  printf("This program plays a game of scrabble.\n");
  generate_letter_set(letter_set, size_letter_set, num_letters);
  printf("Your letters are: \n");
  for(counter4 = 0; counter4 < size_letter_set; counter4++){
    printf("%d ", letter_set[counter4]);
  }
  return 0;
}

我希望它最多打印出7个非零字符,加起来是7,至少打印出1个非零字符,加起来是7,其余为零。
取而代之的是不同数量的非零字符,总计超过7个。
示例输出:0 0 0 1 0 0 0 0 1 1 1 1 0 0 0 0 1 1 1 1 0 0 1 1 0 1 1 0 1 1 1 0 0
有时也有2或3。这个程序使用c99标准。
我想知道为什么它产生了太多的输入(我认为它通过循环的次数太多了)。提前谢谢你的帮助。

最佳答案

主要问题是使用模中值为100的tiles_max将索引放入一个数组[27]。这简化了选择。

//This program is a basic scrabble game with some error checking.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define NUM_LETTERS 7
#define LETTER_SET 27

void generate_letter_set (int letter_set[], int lettersbgood){
    const int tile_set[LETTER_SET] = {9, 2, 2, 4, 12, 2, 3, 2, 9, 1, 1, 4, 2, 6, 8, 2, 1, 6, 4, 6, 4, 2, 2, 1, 2, 1, 2};
    int counter1, chargen;

    counter1 = lettersbgood;
    do {
        chargen = rand() % (LETTER_SET);
        if ( tile_set[chargen] > letter_set[chargen]){
            letter_set[chargen] += 1;
            counter1--;
            printf("%d\n", letter_set[chargen]);
        }
    } while ( counter1);
}

int main()
{
    int counter4;
    int letter_set[LETTER_SET] = {0};

    srand((unsigned) time(NULL));
    printf("This program plays a game of scrabble.\n");
    generate_letter_set(letter_set, NUM_LETTERS);
    printf("Your letters are: \n");
    for(counter4 = 0; counter4 < LETTER_SET; counter4++){
        printf("%d ", letter_set[counter4]);
    }
    printf("\n");
    return 0;
}

07-28 04:47