-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsp_nim.c
More file actions
executable file
·83 lines (71 loc) · 1.58 KB
/
Copy pathsp_nim.c
File metadata and controls
executable file
·83 lines (71 loc) · 1.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include "main_aux.h"
int isEmpty(int arr[], int len);
void user_move(int heaps[], int numOfHeaps);
void comp_move(int heaps[], int len);
int isEmpty(int arr[], int len)
{
int i = 0;
for (i = 0; i < len; i++)
{
if (arr[i] != 0)
return 0;
}
return 1;
}
void user_move(int heaps[], int numOfHeaps) {
int userWhichHeap = 0;
int userToTake = 0;
printf("Your turn: please enter the heap index and the number of removed objects.\n");
while (1) {
scanf("%d %d", &userWhichHeap, &userToTake);
if ((userWhichHeap < 1) || (userWhichHeap - 1 >= numOfHeaps) || (userToTake < 1) || (heaps[userWhichHeap - 1] < userToTake))
printf("Error: Invalid input.\nPlease enter again the heap index and the number of removed objects.\n");
else
break;
}
printf("You take %d objects from heap %d.\n", userToTake, userWhichHeap);
heaps[userWhichHeap - 1] -= userToTake;
}
void comp_move(int heaps[], int len)
{
int i = 0;
int s_tNim = 0;
int numToTake = 0;
int heapToTake = 0;
int nimSum = 0;
for (i = 0; i < len; i++)
{
s_tNim ^= (heaps)[i];
}
if (s_tNim == 0)
{
for (i = 0; i < len; i++)
{
if (heaps[i] > 0)
{
heapToTake = i;
break;
}
}
heaps[heapToTake]--;
numToTake = 1;
}
else
{
for (i = 0; i < len; i++)
{
nimSum = (heaps)[i] ^ s_tNim;
if (nimSum < (heaps)[i])
{
heapToTake = i;
numToTake = (heaps)[i] - nimSum;
(heaps)[i] = nimSum;
break;
}
}
}
printf("Computer takes %d objects from heap %d.\n", numToTake, heapToTake + 1);
}