Created
October 14, 2020 07:46
-
-
Save kenduigraha/cb19a3427034d8b17539a26148dc086a 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
// switchWordByIndex | |
// return new string switched by index | |
const switchWordByIndex = (words, index, wordSwitched) => (words.substr(0, index) + wordSwitched + words.substr(index + 1)); | |
// swapWordBasedOnIndex | |
// return new string swaped | |
const swapStringBasedOnIndex = (words, indexWord, indexComparedWord) => { | |
// switch first word as temporary words | |
const switchFirstWord = switchWordByIndex(words, indexWord, words[indexComparedWord]); | |
// switch second word and get the result | |
return switchWordByIndex(switchFirstWord,indexComparedWord,words[indexWord]); | |
} | |
// sortAlphabet | |
// return sorted ascending by alphabet | |
const sortAlphabet = unsortedString => { | |
let sorted = unsortedString.toLowerCase(); | |
for (let i = 0 ; i < sorted.length ; i++) { | |
for(let j = i+1 ; j < sorted.length ; j++) { | |
if (sorted[i] > sorted[j]) { | |
sorted = swapStringBasedOnIndex(sorted, i, j); | |
} | |
} | |
} | |
return sorted; | |
} | |
// grouping anagram based of list data | |
const groupAnagram = listAnagram => { | |
let result = {}; | |
for (let word of listAnagram) { | |
const sortedWordAlphabet = sortAlphabet(word); | |
if (result[sortedWordAlphabet]) { | |
result[sortedWordAlphabet].push(word); | |
} else { | |
result[sortedWordAlphabet] = [word]; | |
} | |
} | |
return Object.values(result); | |
} | |
const words = ['kita', 'atik', 'tika', 'aku', 'kia', 'makan', 'kua']; | |
// assumed anagram Upper Case = Lower Case | |
// A,a = true | BB,Bb = true | |
// Test Case Function groupAnagram | |
// Result: [["kita", "atik", "tika"], ["aku", "kua"], ["kia"], ["makan"]] | |
console.log(groupAnagram(words)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment