shlomi-fish-homepage / t2 / MathVentures / check_codes.c

 ``` 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 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98``` ```/* check_codes.c This program calculates the number of possible binary codes of length n, so that if the code is broadcasted continously, it can be verified without knowing where it's start is. I.e: 0100 is essentially the same as 0010 because when broadcasted they both become: 0100010001000100010001000... and cannot be distinguished. */ #include /* A typedef for an integer that can hold a whole code. */ typedef unsigned long Mytype; /* This function calculates the number of codes for a given number by enumerating all possible codes and counting them. */ Mytype stupid_get_num_codes (int number) { Mytype code, perm, num_codes, max_code; int shift; num_codes = 0; max_code = 1 << number; for (code = 0; code < max_code; code++) { /* The code is counted only if none of its permutations was already taken into account */ perm = code; for (shift = 0; shift < number - 1; shift++) { perm = ((perm & 1) << (number - 1)) + (perm >> 1); if (perm < code) /* If the permutation is lower then */ break; /* it was already scanned by this loop. */ } if (shift == number - 1) { num_codes++; } } return num_codes; } #define T(n) ((1<<(n)) - 2) Mytype unique_codes(int number) { int div; Mytype codes_num; if (number == 1) return 2; codes_num = T(number); for(div=2;div