Last active
January 4, 2022 02:24
-
-
Save greghelton/d350938bf7f586d0dc9fb00c0816475c to your computer and use it in GitHub Desktop.
This is my first solution to the snowflake problem given in the book Algorithmic Thinking. I am not a C programmer so read or use with caution.
This file contains 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 <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <time.h> | |
#include <stdbool.h> | |
const int SIZEOFFLAKESARRAY = 2000; | |
static int flakes[SIZEOFFLAKESARRAY][6]; | |
void makeSnowflakes() { | |
time_t t; | |
srand((unsigned) time(&t)); | |
for (int i = 0; i < SIZEOFFLAKESARRAY; i++) { | |
for (int j = 0; j < 6; j++) { | |
int num = 1 + rand() % (6); | |
flakes[i][j] = num; | |
} | |
} | |
} | |
bool identifyIdentical(int a, int b) { | |
bool allSixArmsMatch = true; | |
for (int secondArmOffset = 0; secondArmOffset < 6; secondArmOffset++) { | |
allSixArmsMatch = true; | |
for (int armIndex = 0; armIndex < 6; armIndex++) { | |
int totalOffset = armIndex + secondArmOffset; | |
if (totalOffset > 5) { | |
totalOffset -= 6; | |
} | |
if (flakes[a][armIndex] != flakes[b][totalOffset]) { | |
allSixArmsMatch = false; | |
break; | |
} | |
} | |
if (allSixArmsMatch) break; | |
} | |
if (allSixArmsMatch) printf("\nmatch %d %d \n%d %d %d %d %d %d \n%d %d %d %d %d %d", a, b, | |
flakes[a][0], flakes[a][1], flakes[a][2], flakes[a][3], flakes[a][4], flakes[a][5], | |
flakes[b][0], flakes[b][1], flakes[b][2], flakes[b][3], flakes[b][4], flakes[b][5]); | |
return allSixArmsMatch; | |
} | |
int searchArrayForMatches() { | |
bool matched = false; | |
int nbrMatched = 0; | |
for (int firstSnowflake = 0; firstSnowflake < SIZEOFFLAKESARRAY - 1; firstSnowflake++) { | |
for (int secondSnowflake = firstSnowflake + 1; secondSnowflake < SIZEOFFLAKESARRAY; secondSnowflake++) { | |
matched = identifyIdentical(firstSnowflake, secondSnowflake); | |
if (matched) nbrMatched += 1; | |
} | |
} | |
return nbrMatched; | |
} | |
int main() { | |
makeSnowflakes(); | |
// create match for test case | |
for (int x=0; x<6; x++) { | |
int offset = x + 2; if (offset > 5) offset -= 6; | |
flakes[SIZEOFFLAKESARRAY - 1][offset] = flakes[SIZEOFFLAKESARRAY - 2][x]; | |
} | |
int nbrMatched = searchArrayForMatches(); | |
printf("\nNumber Matched %d\n", nbrMatched); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment