Anonymous user
Best shuffle: Difference between revisions
Removed some casts from C version
(→{{header|Ursala}}: Omit bc, dc.) |
(Removed some casts from C version) |
||
Line 126:
#define DEBUG
void best_shuffle(const
const
if (len == 0)
return;
Line 133:
#ifdef DEBUG
// txt and result must have the same length
assert(len ==
#endif
// how many of each character?
memset(counts, '\0', UCHAR_MAX * sizeof(int));
for (
counts[(unsigned char)txt[i]]++;
const
if (fmax < fnew)
fmax = fnew;
}
assert(fmax > 0 && fmax <= len);
// how long can our cyclic groups be?▼
const int grp = 1 + (len - 1) / fmax;▼
// how many of them are full length?▼
const int lng = 1 + (len - 1) % fmax;▼
// all character positions, grouped by character
if (ndx1 == NULL)
exit(EXIT_FAILURE);
for (
if (counts[ch])
for (
if (ch == (unsigned char)txt[j]) {
ndx1[i] = j;
i++;
Line 167 ⟶ 161:
// regroup them for cycles
if (ndx2 == NULL)
exit(EXIT_FAILURE);
for (
ndx2[i] = ndx1[n];
n += fmax;
Line 178 ⟶ 172:
}
}
▲ // how long can our cyclic groups be?
assert(grp > 0 && grp <= len);
▲ // how many of them are full length?
assert(lng > 0 && lng <= len);
// rotate each group
for (
for (
ndx1[j + k - 1] = ndx2[j + k];
ndx1[j + glen - 1] = first;
Line 191 ⟶ 193:
// result is original permuted according to our cyclic groups
result[len] = '\0';
for (
result[ndx2[i]] = txt[ndx1[i]];
Line 198 ⟶ 200:
}
void display(const char* txt1, const char* txt2) {
assert(len ==
int score = 0;
for (
if (txt1[i] == txt2[i])
score++;
(void)printf("%s, %s, (%
}
Line 211 ⟶ 213:
char* data[] = {"abracadabra", "seesaw", "elk", "grrrrrr",
"up", "a", "aabbbbaa", "", "xxxxx"};
const
for (
const
#ifdef DEBUG
memset(shuf, 0xFF, shuf_len * sizeof(
shuf[shuf_len - 1] = '\0';
#endif
best_shuffle(
display(data[i],
}
|