No. 1 - Logic Test
let words = ['cook', 'save', 'taste', 'aves', 'vase', 'state', 'map']
function alphabeticalSort(str) {
let charArray = []
for (let i = 0; i < str.length; i++) {
charArray.push(str[i])
}
for (let i = 0; i < charArray.length; i++) {
for (let j = 0; j < charArray.length-1; j++) {
if (charArray[j] > charArray[j+1]) {
let tempArray = charArray[j]
charArray[j] = charArray[j+1]
charArray[j+1] = tempArray
}
}
}
let sortedStr = ""
for (let i = 0; i < charArray.length; i++) {
sortedStr += charArray[i]
}
// console.log(sortedStr)
return sortedStr
}
function group(words) {
let anagrams = {}
for (let i = 0; i < words.length; i++) {
let word = words[i]
let sortedWord = alphabeticalSort(word)
if (!anagrams[sortedWord]) {
anagrams[sortedWord] = []
}
anagrams[sortedWord].push(word)
}
let result = []
for (let key in anagrams) {
result.push(anagrams[key])
}
// console.log(result)
return result
}
console.log(group(words))
No. 2 - Query Test
-- PostgreSQL
select b.id, b.name, a.name as parent_name
from test a
right join test b
on a.id = b.parent_id