回答編集履歴

2

シャッフル改善

2022/09/17 17:26

投稿

jimbe
jimbe

スコア12545

test CHANGED
@@ -24,8 +24,8 @@
24
24
  stock->cards[i].n = i % 13 + 1;
25
25
  stock->cards[i].suit = SUITS[i / 13];
26
26
  }
27
- for(int i = 0; i < stock->left; i++) {
27
+ for(int i = stock->left - 1; i > 0; i--) {
28
- int j = rand() % stock->left;
28
+ int j = rand() % i;
29
29
  CARD t = stock->cards[i];
30
30
  stock->cards[i] = stock->cards[j];
31
31
  stock->cards[j] = t;

1

追加

2022/09/17 17:07

投稿

jimbe
jimbe

スコア12545

test CHANGED
@@ -1,6 +1,11 @@
1
1
  例えば、以下のような構造・関数を用いると 13*4 枚のカードを無くなるまで
2
2
  ドローできます。
3
3
  ```c
4
+ #include <stdio.h>
5
+ #include <stdlib.h>
6
+ #include <time.h>
7
+ #include <unistd.h>
8
+
4
9
  char *SUITS[] = { "♥", "♠", "♣", "♦" };
5
10
 
6
11
  typedef struct {
@@ -31,4 +36,33 @@
31
36
  if(stock->left == 0) return NULL;
32
37
  return &stock->cards[--stock->left];
33
38
  }
39
+
40
+ int main(void) {
41
+ STOCK stock;
42
+
43
+ srand(time(NULL));
44
+ initStock(&stock);
45
+ printf("left=%d\n", stock.left);
46
+
47
+ for(int i=0; i<10; i++) {
48
+ CARD *card = drawFromStock(&stock);
49
+ printf("%s %d\n", card->suit, card->n);
50
+ }
51
+ printf("left=%d\n", stock.left);
52
+ }
34
53
  ```
54
+ 実行結果
55
+ ```plain
56
+ left=52
57
+ ♦ 4
58
+ ♠ 3
59
+ ♣ 9
60
+ ♠ 7
61
+ ♣ 12
62
+ ♥ 7
63
+ ♣ 13
64
+ ♠ 12
65
+ ♦ 6
66
+ ♣ 11
67
+ left=42
68
+ ```