Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save realityexpander/88974340fb60333c0de50f2feb7991bf to your computer and use it in GitHub Desktop.
Save realityexpander/88974340fb60333c0de50f2feb7991bf to your computer and use it in GitHub Desktop.
/*
Problem:
['Tokyo', 'London', 'Rome', 'Donlon', 'Kyoto', 'Paris']
// YOUR ALGORITHM
[
[ 'Tokyo', 'Kyoto' ],
[ 'London', 'Donlon' ],
[ 'Rome' ],
[ 'Paris' ]
]
*/
const getWordRotations = word =>
[...word].reduce(
acc => [acc[0].substring(1) + acc[0].substring(0, 1), ...acc],
[word]
);
const groupCitiesByRotatedNames = cities =>
cities.reduce((acc, city) => {
const cityGroup = acc.find(item =>
getWordRotations(city.toLowerCase()).includes(item[0].toLowerCase())
);
cityGroup
? acc.splice(acc.indexOf(cityGroup), 1, [...cityGroup, city])
: acc.push([city]);
return acc;
}, []);
const test = groupCitiesByRotatedNames([
"Tokyo",
"London",
"Rome",
"Donlon",
"Kyoto",
"Paris"
]);
console.log("test", test);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment