CodeWars 코딩 문제 2021/01/24 - Coloured Triangles

이호현·2021년 1월 24일
0

Algorithm

목록 보기
63/138

[문제]

If you finish this kata, you can try Insane Coloured Triangles by Bubbler, which is a much harder version of this one.

A coloured triangle is created from a row of colours, each of which is red, green or blue. Successive rows, each containing one fewer colour than the last, are generated by considering the two touching colours in the previous row. If these colours are identical, the same colour is used in the new row. If they are different, the missing colour is used in the new row. This is continued until the final row, with only a single colour, is generated.

The different possibilities are:

With a bigger example:

You will be given the first row of the triangle as a string and its your job to return the final colour which would appear in the bottom row as a string. In the case of the example above, you would the given RRGBRGBB you should return G.

  • The input string will only contain the uppercase letters R, G, B and there will be at least one letter so you do not have to test for invalid input.
  • If you are only given one colour as the input, return that colour.

(요약) 색을 합쳐서 나오는 결과 값을 반복해 하나가 남으면 그 값을 return.

[풀이]

function triangle(row) {
  while(row.length > 1) {
    let tempStr = '';

    for(let i = 0; i < row.length - 1; i++) {
      tempStr += color(row[i], row[i + 1]);
    }

    row = tempStr;
  }

  return row
}

function color(c1, c2) {
  const colors = ['B', 'G', 'R'];

  if(c1 === c2) {
    return c1;
  }
  else {
    return colors.filter(c => (c !== c1) && (c !== c2))[0];
  }
}

색 두개를 조합하는 함수 color를 만들고, 주어진 문자열을 순회하면서 색을 섞는걸 반복.
두개가 같으면 그대로 reutrn하고, 다르면 3가지 색이 있는 배열을 filter로 둘 다 해당하지 않는 색을 return하게 함.
하나씩 줄여나가다가 마지막에는 하나만 남은 문자를 return.

profile
평생 개발자로 살고싶습니다

0개의 댓글