-
Notifications
You must be signed in to change notification settings - Fork 3
/
fannkuch.c
107 lines (89 loc) · 2.14 KB
/
fannkuch.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
99
100
101
102
103
104
105
106
#if defined(__LCC__) && !defined(__EDG__)
typedef unsigned long size_t;
int atoi(const char*);
int printf(const char*, ...);
int calloc(size_t, size_t);
void free(void*);
typedef long time_t;
typedef long suseconds_t;
struct timeval {
time_t tv_sec;
suseconds_t tv_usec;
};
int gettimeofday(struct timeval*, void*);
#define NULL ((void*)0)
#else
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <sys/time.h>
#endif
static long long get_time_usec() {
struct timeval time;
gettimeofday(&time, NULL);
return time.tv_sec * (long long)1000000 + time.tv_usec;
}
/* The Computer Language Benchmarks Game
* https://salsa.debian.org/benchmarksgame-team/benchmarksgame/
*
* converted to C by Joseph Piché
* from Java version by Oleg Mazurov and Isaac Gouy
*
*/
int fannkuchredux(int n, int *check) {
int *perm, *perm1, *count;
int flipsMax = 0, permCount = 0, checksum = 0;
int i, k, r = n, flips;
perm = (int*)calloc(n*3, sizeof(*perm));
perm1 = perm + n;
count = perm1 + n;
for (i = 0; i < n; i++) perm1[i] = i; // initial (trivial) permu
for (;;) {
for (; r != 1; r--) count[r-1] = r;
for (i = 0; i < n; i++) perm[i] = perm1[i];
flips = 0;
while ((k = perm[0]) != 0) {
int k2 = (k + 1) >> 1;
for (i = 0; i < k2; i++) {
int temp = perm[i]; perm[i] = perm[k-i]; perm[k-i] = temp;
}
flips++;
}
if (flipsMax < flips) flipsMax = flips;
checksum += permCount & 1 ? -flips : flips;
/* Use incremental change to generate another permutation */
for (;;) {
int perm0;
if (r == n) {
*check = checksum;
free(perm);
return flipsMax;
}
perm0 = perm1[0];
i = 0;
while (i < r) {
k = i + 1;
perm1[i] = perm1[k];
i = k;
}
perm1[r] = perm0;
if ((count[r] -= 1) > 0) break;
r++;
}
permCount++;
}
}
int main(int argc, char **argv) {
long long time; int i;
for (i = 1; i < argc; i++) {
int n = atoi(argv[i]);
int result, check = 0;
time = get_time_usec();
result = fannkuchredux(n, &check);
time = get_time_usec() - time;
printf("%d\nPfannkuchen(%d) = %d\n", check, n, result);
printf("time = %.3fms\n", time * 0.001);
}
return 0;
}