Project Euler #17: Number to Words

  • + 0 comments

    Here's what I came up with using Javascript:

    let numbers = {
      1: 'One', 2: 'Two', 3: 'Three', 4: 'Four', 5: 'Five', 6: 'Six', 7: 'Seven', 8: 'Eight', 9: 'Nine', 10: 'Ten', 11: 'Eleven', 12: 'Twelve', 13: 'Thirteen', 14: 'Fourteen', 15: 'Fifteen', 16: 'Sixteen', 17: 'Seventeen', 18: 'Eighteen', 19: 'Nineteen', 20: 'Twenty', 30: 'Thirty', 40: 'Forty', 50: 'Fifty', 60: 'Sixty', 70: 'Seventy', 80: 'Eighty', 90: 'Ninety', 100: 'Hundred', 1000: 'Thousand', 1000000: 'Million', 1000000000: 'Billion', 1000000000000: 'Trillion'
    }
    
    let convertTriplet = str => {
      let rtn = [];
      let num = parseInt(str);
      if (isNaN(num) || num === 0) return [];
      if (num > 100) {
        rtn.push(numbers[Math.floor(num/100)], 'Hundred');
        num %= 100;
      }
      if (num <= 20) {
        rtn.push(numbers[num]);
      } else {
        if (Math.floor(num/10) > 0) {
          rtn.push(numbers[Math.floor(num/10) * 10]);
          num %= 10
        }
        if (num > 0) {
          rtn.push(numbers[num]);
        }
      }
      return rtn;
    }
    
    function processData(input) {
      let data = input.split('\n');
      for (let i = 1; i < data.length; i++) {
        let number = [];
        for (let j = 0; j < Math.ceil(data[i].length / 3); j++) {
          let triplet = convertTriplet(data[i].substring(data[i].length - 3 * (j+1), data[i].length - 3 * (j+1) + 3));
          if (triplet.length > 0 && j > 0) triplet.push(numbers[Math.pow(10, j*3)]);
          number.unshift(...triplet);
        }
        console.log(number.join(' '));
      }
    }