Created
July 20, 2010 15:57
-
-
Save jonbro/483153 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Solves the following problem | |
Given a dictionary, output all word pairs where both words share all their letters except the last two, which are distinct and reversed. | |
Notes: | |
- Use a reasonable dictionary of your choice | |
- Potential word pairs are: "ear, era" ; "revies, revise" ; "burglaries, burglarise" | |
- "shear, era" is not a valid pair because "she" != "e" | |
- "bell, bell" is not a valid pair because the last two letters are not distinct | |
- This will be benchmarked | |
- Work on this problem in C, C++, Java, Perl, PHP, Python or a similar language. | |
- Don't e-mail to ask for clarifications on this question. Make reasonable assumptions and justify them in a README if you feel the need | |
*/ | |
var log = require("ringo/logging").getLogger(module.id); | |
var fs = require('fs'); | |
var file = fs.open('a-e.dict'); | |
var lines = [line for (line in file)]; | |
var stemmed = Array(); | |
lines.forEach(function(currentValue, index, array){ | |
if(currentValue.length > 2){ | |
// split off all the letters but the last two and sort them | |
var sorted = currentValue.slice(0, currentValue.length-2).split('').sort().reduce(function(prev, current){return prev+current}, ''); | |
var last = currentValue.slice(-2); | |
var last_rev = last[1]+last[0]; | |
if(last != last_rev){ | |
// place the word in the current array | |
var key = sorted +'_'+last; | |
if(typeof(stemmed[key]) != "object"){ | |
stemmed[key] = Array(); | |
} | |
if(typeof(stemmed[key]['match']) != 'object'){ | |
stemmed[key]['match'] = Array(); | |
} | |
var revKey = sorted + '_' +last_rev; | |
if(typeof(stemmed[revKey]) != "object"){ | |
stemmed[revKey] = Array(); | |
} | |
if(typeof(stemmed[revKey]['revMatch']) != 'object'){ | |
stemmed[revKey]['revMatch'] = Array(); | |
} | |
stemmed[key]['match'].push(currentValue); | |
stemmed[revKey]['revMatch'].push(currentValue); | |
} | |
} | |
}); | |
var removeDupes = Array(); | |
for (var key in stemmed) { | |
if(typeof(stemmed[key].match) == "object" && typeof(stemmed[key].revMatch) == "object"){ | |
stemmed[key].match.forEach(function(val, i, array){ | |
stemmed[key].revMatch.forEach(function(valR, iR, array){ | |
if(typeof(removeDupes[val]) != "string"){ | |
removeDupes[valR] = val; | |
} | |
}); | |
}); | |
} | |
} | |
for (var key in removeDupes) { | |
log.info("{}, {}", key, removeDupes[key]); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment