Skip to content

Instantly share code, notes, and snippets.

@larryprice
Created June 13, 2018 13:31
Show Gist options
  • Save larryprice/08e30cbdf49c547b800d78ffcdcd61fc to your computer and use it in GitHub Desktop.
Save larryprice/08e30cbdf49c547b800d78ffcdcd61fc to your computer and use it in GitHub Desktop.
const cities = ['Tokyo', 'London', 'Rome', 'Donlon', 'Kyoto', 'Paris']
// Initially I misunderstood the problem and assumed that the letters
// could be reconfigured in any order to be a match
function sameLetters(city1, city2) {
if (city1.length !== city2.length) return false
for (let i = 0; i < city1.length; ++i) {
if (!city2.includes(city1[i])) return false
city2 = city2.replace(city1[i], '')
}
return city2.length === 0
}
// But as I continued to read the blog post I learned that it
// is just a rotation instead
function isRotated(city1, city2) {
if (city1.length !== city2.length) return false
let rotated = city2
for (let i = 0; i < city2.length; ++i) {
if (city1 === rotated) return true
rotated = rotated.slice(1) + rotated[0]
}
return false
}
const matches = []
let remaining = cities
while (remaining.length > 0) {
matches[matches.length] = []
const currentCity = remaining[0].toLowerCase()
remaining.forEach(city => {
if (isRotated(currentCity, city.toLowerCase())) matches[matches.length-1].push(city)
})
remaining = remaining.filter(city => !matches[matches.length-1].includes(city))
}
console.log(matches)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment