alphabetWar.js (7kyu 53)

Codewars 알고리즘 풀이


Problem

  • There are two groups of hostile letters.
    • 적대하는 두 문자 그룹이 있다.
  • Write a function that accepts fight string consists of only small letters and return who wins the fight.
    • fight 문자열은 소문자로만 구성되며, 누가 이기는지를 반환한다.
  • When the left side wins return ‘Left side wins!’, when the right side wins return ‘Right side wins!’, in other case return ‘Let’s fight again!’.
    • left side가 이긴다면: ‘Left side wins!’
    • right side가 이긴다면: ‘Right side wins!’
    • 그 외의 경우에는: ‘Let’s fight again!’


Left side power:

w: 4

p: 3

b: 2

s: 1

Right side power:

m: 4

q: 3

d: 2

z: 1


Solution 01

function alphabetWar(fight) {
  const leftPower = {
    w: 4,
    p: 3,
    b: 2,
    s: 1
  };
  
  const rightPower = {
    m: 4,
    q: 3,
    d: 2,
    z: 1
  };
  
  let leftScore = 0;
  let rightScore = 0;
  let arr = fight.split('');
  
  for (let i = 0; i < arr.length; i++) {
    if (leftPower[arr[i]]) {
      leftScore += leftPower[arr[i]];
    }
    
    if (rightPower[arr[i]]) {
      rightScore += rightPower[arr[i]];
    }
  }
  
  if (leftScore > rightScore) return `Left side wins!`;
  else if (leftScore < rightScore) return `Right side wins!`;
  else return `Let's fight again!`;
}

alphabetWar('wwqq');  // Left side wins!
alphabetWar('mmpp');  // Right side wins!
alphabetWar('wwmm');  // Let's fight again!

split(): 문자열을 부분 문자열로 분할하고, 새 배열로 반환한다.


Solution 02

function alphabetWar(fight) {
  const powers = {
    w: 4,
    p: 3,
    b: 2,
    s: 1,
    m: -4,
    q: -3,
    d: -2,
    z: -1
  };
  
  const result = fight.split('').reduce((sum, i) => sum + (powers[i] || 0), 0);
  
  return result > 0 ? `Left side wins!` : result < 0 ? `Right side wins!` : `Let's fight again!`;
}

alphabetWar('wwqq');  // Left side wins!
alphabetWar('mmpp');  // Right side wins!
alphabetWar('wwmm');  // Let's fight again!

reduce(): 배열을 하나의 값으로 줄이고, 그 값을 반환한다.