Last active
April 10, 2017 16:17
-
-
Save Rosuav/9c43bd978e2a794470436e9c3e3769c4 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
//NOTE: These functions are NOT reliable if there are astral characters | |
//in the input! Use with UCS-2 strings only. | |
//Python implementations of the same algorithms for comparison: | |
// https://gist.github.com/Rosuav/d02bf71f8bb5354327ee8a8e5fb54e3f | |
//Write an algorithm to check whether any permutation of a string is a | |
//palindrome (a string which reads the same forwards and backwards). | |
//Note that this does not use the HashMap class due to a lack of useful | |
//features such as iteration. The core algorithm would work the same way | |
//though. | |
function any_palindromes(word) { | |
var letter_count = {}; | |
for (var i = 0; i < word.length; ++i) { | |
letter_count[word[i]] = (letter_count[word[i]]|0) + 1; | |
} | |
var have_odd = false; | |
for (var ltr in letter_count) { | |
if (letter_count[ltr] % 2) { | |
//There are an odd number of this letter. A | |
//palindrome is possible with one such letter, but | |
//no more, so flag and carry on. | |
if (have_odd) return false; | |
have_odd = true; | |
} | |
} | |
return true; | |
} | |
//Write an algorithm to group a list of words into anagrams. | |
function _sortword(word) { | |
//Helper function: sort a word into some form of canonical order. | |
//The exact order is insignificant and need not be lexicographical, | |
//as long as it is utterly consistent: any two anagrams of the same | |
//letter sequence must return the same string. | |
return word.split('').sort().join('') | |
} | |
function group_into_anagrams(words) { | |
//Slightly sneaky use of double referencing here. The hashmap and | |
//return array contain references to all the same arrays - one is | |
//keyed based on the sorted forms, and the other is a simple array. | |
var anagrams = {}, ret = []; | |
for (var word of words) { | |
var key = _sortword(word); | |
if (anagrams[key]) anagrams[key].push(word); | |
else ret.push(anagrams[key] = [word]); | |
} | |
return ret; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment