for some reason the mailing list server rejected this post, so i'll
paste it in here:
One way is:
0. If there are more than 26 entries, return an error and exit - you
clearly can't assign a unique letter to each
1. Go through the whole array, counting how many times you see each
letter (use a hash that starts off with {"a" => 0, "b" => 0, ...}
2. Iterate through the hash, examining each letter and its count
- if the count is exactly 1, ignore it
- if the count is 0, add it to an "unused" array
- if the count is 2 or more, add it to a "duplicates" hash, along with
the count
3. You should now have the following two structures:
unused = ["e", "h", "l", p", ...]
duplicates = { "a" => 2, "f" => 3, "q" => 2, ...}
4. Now iterate through your original array again. For each entry,
check to see if it is in the duplicates hash. If it is, remove one
letter from unused (see the array.pop method) and use it as a
replacement. Decrease the original letter's count in the duplicates
hash by 1, and if its count is now 1 remove it from the hash
So for instance if your original array was
["&f", "&a", "&f", "&q", ... ]
you'd see the first "&f", note that it was in duplicates with a count
of 3, replace it by "e" (the first letter from unused) and reduce its
count. you would now have
array = ["&e", "&a", "&f", "&q", ...]
unused = ["h", "l", "p", ...]
duplicates = { "a" => 2, "f" => 2, "q" => 2, ...}
When you are done, all the duplicates will have been replaced by unused
letters.
martin
···
--
Posted via http://www.ruby-forum.com/.