input: have arrays, like:
1, 2, 3, 4, 5 2, 1, 3, 4, 5 3, 2, 5, 4, 1 5, 4, 3, 1, 2 .....
all of them non repeating permutations of 5 digits - 5c5. rows can repeat, digit in row unique.
aim: count how many arrays of each type (permutation) in input data.
my thoughts: 5c5 says there's 120 unique rows can be. can store counters in int[120]
array. , increment them while reading input.
my question: there efficient algorithm convert (hash) array array index?
preferable language c, it's pointers , manual memory management. in perfect, i'm trying like:
file *f; int counters[120] = {0}; char seq[20]; parse_line(f, seq); #scans , parses string array counters[hash(seq)]++;
ps: inspired question solving "uva 157 - recycling". later saw solutions , understood misunderstood task, question left unanswered.
do base conversion. first digit in base 5, second in base 4, base 3, , base 2. so, example:
1, 2, 3, 4, 5 -> 0 * 4*3*2*1 + 0 * 3*2*1 + 0 * 2*1 + 0 * 1 -> 0 2, 1, 3, 4, 5 -> 1 * 4*3*2*1 + 0 * 3*2*1 + 0 * 2*1 + 0 * 1 -> 24 3, 2, 5, 4, 1 -> 2 * 4*3*2*1 + 1 * 3*2*1 + 2 * 2*1 + 1 * 1 -> 59 5, 4, 3, 1, 2 -> 4 * 4*3*2*1 + 3 * 3*2*1 + 2 * 2*1 + 0 * 1 -> 118 5, 4, 3, 2, 1 -> 4 * 4*3*2*1 + 3 * 3*2*1 + 2 * 2*1 + 1 * 1 -> 119
remember count numbers haven't seen when choosing digit! walking through third row of above:
3, 2, 5, 4, 1
at first, have following mapping of numbers digits:
1 2 3 4 5 0 1 2 3 4
since first number 3
, first digit 2
. delete 3
numbers, giving
1 2 4 5 0 1 2 3
the next number 2
, next digit 1
. mapping now
1 4 5 0 1 2
the next number 5
, next digit 2
. mapping now
1 4 0 1
the next number 4
, next digit 1
. last digit 0
though won't contribute sum -- last digit in unary, 0
. numbers 32541
correspond digits 21210
.
to calculate value of number in base 10, use usual base conversion routine: multiply "column value" current column's base, add in value of current digit times column value. so:
0 * 1 + 1 * (1*1) + 2 * (2*1*1) + 1 * (3*2*1*1) + 2 * (4*3*2*1*1) ----------------- 59
see wikipedia page on factorial number systems.
Comments
Post a Comment