This article introduces the example of C + + imitation Huarong road games to achieve code, to share with you for your reference, the specific contents are as follows
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <stdbool.h> #define MAXNUM 16
#define COLNUM 4 bool numexists (int *numbers, int length, int num);
int getnumber (int **numbers, int randindex, int *length);
int* initnumbers (void);
void swap (int **a, int **b);
int main (int argc, char *argv[]) {int *tempnumbers = Initnumbers ();
int *randnumbers = Initnumbers ();
int **numbers;
Numbers = malloc (maxnum * sizeof (int*));
BOOL A = numexists (numbers, 16, 3);
printf ("a=%d\n", a);
int length = Maxnum;
Srand ((unsigned) time (NULL));
for (int i = 0; i < maxnum i++) {int temp = GetNumber (&tempnumbers, rand ()% length, &length);
Randnumbers[i] = temp;
Numbers[temp] = &randnumbers[i]; printf ("%d%c", temp, (i + 1)% Colnum = = 0?
\ n ': ' \ t ');
} if (tempnumbers!= NULL) free (tempnumbers);
while (true) {System (' clear '); for (int i = 0; i < maxnum i++) printf ("%d%c", RandnuMbers[i], (i + 1)% Colnum = = 0? '
\ n ': ' \ t ');
printf ("Move number/invalid num==exit:");
int i;
if (!scanf ("%d", &i)) {printf ("Game over\n");
Break
} if (I >= maxnum | | I <0) {printf ("Sorry, I can ' t find%d\n", i);
Break
} unsigned char sign = ABS (Numbers[i]-numbers[0]);
Switch (sign) {case 1:case 4:swap (&numbers[0], &numbers[i]);
} if (numbers!= NULL) free (numbers);
if (randnumbers!= NULL) free (randnumbers);
} void Swap (int **a, int **b) {int *templocation = *a;
int tempvalue = **a;
**a = **b;
**b = Tempvalue;
*a = *b;
*b = templocation;
} int* initnumbers (void) {int *numbers = malloc (maxnum * sizeof (int));
for (int i = 0; i < maxnum i++) numbers[i] = i;
return numbers;
int getnumber (int **numbers, int randindex, int *length) {int result = (*numbers) [Randindex]; (*numbers) [Randindex] = (*numbers) [--(*length)];
int *temp = ReAlloc (*numbers, (*length) * sizeof (int));
*numbers = temp;
return result; BOOL _numexists (int *numbers, int start, int end, int num) {printf (' Start:%d, end:%d, num:%d\n ', start, end, num
);
if (start = = end) return Numbers[start] = = num;
else {int middle = (start+end)/2;
if (numbers[middle] = num) return true;
else if (Numbers[middle] > num) return _numexists (Numbers, start, middle-1, num);
else return _numexists (numbers, middle+1, end, num);
} bool Numexists (int *numbers, int length, int num) {return _numexists (numbers, 0, length-1, num);
}
I hope this article will help you learn the C + + program.