Created
March 27, 2011 16:32
-
-
Save janisozaur/889350 to your computer and use it in GitHub Desktop.
generator.cpp
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdlib.h> | |
#include <vector> | |
#include <string.h> | |
#include <stack> | |
#include <stdio.h> | |
#include <queue> | |
#include <time.h> | |
int *start; | |
int sx; | |
int sy; | |
int iterations; | |
int seed; | |
char moves[4] = {'P', 'L', 'G', 'D'}; | |
int FindBlankPlace() | |
{ | |
for (int i = 0; i < sx * sy; i++) { | |
if (start[i] == 0) { | |
return i; | |
} | |
} | |
return -1; | |
} | |
bool CheckMove(int x, int y, char move) | |
{ | |
switch (move) { | |
case 'D': | |
return (y != (sy - 1)); | |
case 'G': | |
return (y != 0); | |
case 'L': | |
return (x != 0); | |
case 'P': | |
return (x != (sx - 1)); | |
default: | |
fprintf(stderr, "Invalid move: %c\n", move); | |
return false; | |
} | |
} | |
int main(int argc, char **argv) { | |
if (argc < 4) { | |
fprintf(stderr, "Usage: %s height width iterations [seed]\n", argv[0]); | |
return -1; | |
} | |
sy = atoi(argv[1]); | |
sx = atoi(argv[2]); | |
iterations = atoi(argv[3]); | |
if (argc == 5) { | |
seed = atoi(argv[4]); | |
} else { | |
seed = time(NULL); | |
fprintf(stderr, "Random seed: %d\n", seed); | |
} | |
srand(seed); | |
start = new int[sx * sy]; | |
for (int i = 0; i < sx * sy; i++) { | |
start[i] = i + 1; | |
} | |
start[sx * sy - 1] = 0; | |
for (int i = 0; i < iterations; i++) { | |
int move = rand() % 4; | |
int x, y; | |
int blank = FindBlankPlace(); | |
x = blank % sx; | |
y = blank / sx; | |
if (CheckMove(x, y, moves[move])) { | |
if (moves[move] == 'D') { | |
int swap = blank + sx; | |
start[blank] = start[swap]; | |
start[swap] = 0; | |
} else if (moves[move] == 'G') { | |
int swap = blank - sx; | |
start[blank] = start[swap]; | |
start[swap] = 0; | |
} else if (moves[move] == 'L') { | |
int swap = blank - 1; | |
start[blank] = start[swap]; | |
start[swap] = 0; | |
} else if (moves[move] == 'P') { | |
int swap = blank + 1; | |
start[blank] = start[swap]; | |
start[swap] = 0; | |
} | |
fprintf(stderr, "%c", moves[move]); | |
} | |
} | |
fprintf(stderr, "\n"); | |
printf("%i %i\n", sy, sx); | |
for (int i = 0; i < sy; i++) { | |
for (int j = 0; j < sx; j++) { | |
printf("%i ", start[sx * i + j]); | |
} | |
printf("\n"); | |
} | |
delete[] start; | |
return (EXIT_SUCCESS); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment