フロントエンドデベロッパーのメモ

スキル: HTML/Jade/Jinja2, CSS/SCSS, JavaScript(ES6), Angular, React,Next, Redux, Node, Express, Python, Flask, Postgres, Redis, MongoDB, Kafka, Knex, SQLAlchemy, React Native, EXPO, GraphQL/Apollo, REST, AWS, Heroku, Docker, CircleCI, SCRUM, XP, Vim, TDD

国名しりとり countries' name caterpiller

頭の体操という事でしりとりしました。 問題の条件は以下です。 与えられた国名リストでしりとりをします。最長を求めよ。

const list = [
  "Brazil",
  "Cameroon",
  "Chile",
  "Greece",
  "Uruguay",
  "Italy",
  "France",
  "Bosnia and Herzegovia",
  "Germany",
  "USA",
  "Russia",
  "Croatia",
  "Spain",
  "Australia",
  "Cote D'Ivoire",
  "Costa RIca",
  "Switzerland",
  "Honduras",
  "Iran",
  "Portugal",
  "Belgium",
  "Korea Republic",
  "Mexico",
  "Netherlands",
  "Colombia",
  "Japan",
  "England",
  "Ecuador",
  "Argentina",
  "Nigeria",
  "Ghana",
  "Algeria"
];

function makeLowerCase(countries) {
  return countries.map((elem) => elem.toLowerCase());
}
// make a loop to connect each tale of a word and beginning of a next word as long as possible, if it is not possible to connect from the rest of the list, then finish and push into the empty array.
function findMaximumLength(countries) {
  const result = [];
  const countriesList = makeLowerCase(countries);
  for (let i = 0; i < countriesList.length; i++) {
    const copyList = countriesList.slice();
    copyList.splice(i, 1);
    result.push(search([countriesList[i]], copyList));
  }
  // look for result array and find a maximum
  const sortedlist = result.sort((first, second) => second - first);
  return sortedlist[0];
}

const search = (currentList, candidateList) => {
  for (let i = 0; i < candidateList.length; i++) {
    if (
      currentList.slice(-1)[0][currentList.slice(-1)[0].length - 1] ===
      candidateList[i][0]
    ) {
      currentList.push(candidateList[i]);
      candidateList.splice(i, 1);
      search(currentList, candidateList);
    }
  }
  return currentList.length;
};

console.log(findMaximumLength(list));

答えは8です。 他にもっと簡単に解く方法があるのかもしれませんが、とりあえずこれが思いついたアプローチです。

Exercise time! The restrictions are below. Find the longest length of a caterpillar. I found a recursive way that always iterates through the rest of the countries which have never been selected. However, if there might have other approaches, and in that case please share with me. In addition, the answer is 8.