correctErrors.js (8kyu 35)

Codewars 알고리즘 풀이


Description

  • Your task is correct the errors in the digitised text.
    • 디지털 텍스트의 에러를 수정한다.
  • O is misinterpreted as 0.
    • O가 0으로 잘못 해석되었다.
  • I is misinterpreted as 1.
    • I가 1로 잘못 해석되었다.
  • S is misinterpreted as 5.
    • S가 5로 잘못 해석되었다.



Solution 01

function correctErrors(str) {
  let result = '';
  
  for (let i = 0; i < str.length; i++) {
    if (str[i] === '0') result += 'O';
    else if (str[i] === '1') result += 'I';
    else if (str[i] === '5') result += 'S';
    else result += str[i];
  }
  
  return result;
}

correctErrors('L0ND0N');    // LONDON
correctErrors('PAR15');     // PARIS
correctErrors('C0DEWAR5');  // CODEWARS


Solution 02

function correctErrors(str) {
  return str.replace(/0/g, 'O').replace(/1/g, 'I').replace(/5/g, 'S');
}

correctErrors('L0ND0N');    // LONDON
correctErrors('PAR15');     // PARIS
correctErrors('C0DEWAR5');  // CODEWARS


Solution 03

function correctErrors(str) {
  const obj = {
    0: 'O',
    1: 'I',
    5: 'S'
  };
  
  return str.replace(/[015]/g, i => obj[i]);
}

correctErrors('L0ND0N');    // LONDON
correctErrors('PAR15');     // PARIS
correctErrors('C0DEWAR5');  // CODEWARS


Solution 04

function correctErrors(str) {
  const obj = {
    0: 'O',
    1: 'I',
    5: 'S'
  };
  
  return str.replace(/./g, i => obj[i] || i);
}

correctErrors('L0ND0N');    // LONDON
correctErrors('PAR15');     // PARIS
correctErrors('C0DEWAR5');  // CODEWARS


Solution 05

function correctErrors(str) {
  return [...str].map(i => ({ '0': 'O', '1': 'I', '5': 'S' }[i] || i)).join('');
}

correctErrors('L0ND0N');    // LONDON
correctErrors('PAR15');     // PARIS
correctErrors('C0DEWAR5');  // CODEWARS