DEV Community

Discussion on: Daily Challenge #41 - Greed is Good

Collapse
 
hoffmann profile image
Peter Hoffmann • Edited

I love functional programming and feel the whole day like it's Friday

// create random rolls
const roll = () => Array(5)
  .fill()
  .map(() => Math.floor(Math.random() * 6) + 1)

// score a roll
const score = roll => roll
  .reduce((a, v) => a + Math.pow(10, v - 1), 0)
  .toString()
  .padStart(6, "0")
  .split("")
  .reduce((a, v, i) => a + [
     v > 2 ?  600 : 0,
    (v > 2 ?  500 : 0) + v % 3 * 50,
     v > 2 ?  400 : 0,
     v > 2 ?  300 : 0,
     v > 2 ?  200 : 0,
    (v > 2 ? 1000 : 0) + v % 3 * 100
  ][i], 0)

// example scoring
test = (iRoll, iScore) =>
    `${iRoll.join(' ')} = ${score(iRoll)} (${score(iRoll) == iScore ? 'success' : 'fail'})`
console.log(
    test([5, 1, 3, 4, 1], 250),
    test([1, 1, 1, 3, 1], 1100),
    test([2, 4, 4, 5, 4], 450)
)
5 1 3 4 1 = 250 (success)
1 1 1 3 1 = 1100 (success)
2 4 4 5 4 = 450 (success)