Calculate moves in random dialer

by Génesis García Morilla

HTML

<div id="code"></div>
<div id="dial"></div>
<div id="layout"></div>
<div id="moves"></div>

CSS

body {
  font-family: roboto arial;
  font-weight: bold;
  text-align: center;
}

div {
  margin: 10px;
  display: inline-flex;
  padding: 10px;
  border-radius: 10px;
}

#code {
  color: white;
  background-color: #ED6A5A;
}

#dial {
  color: #77928e;
  background-color: #F4F1BB;
}

#layout {
  color: #E6EBE0;
  background-color: #9BC1BC;
}

#moves {
  border: 3px solid #ccc;
  color: #607D8B;
  background-color: #E6EBE0;
}

JavaScript

// Random number between min and max
const random = (min, max) => 
  Math.floor(Math.random() * (max - min + 1) + min)


// Randomize an array
function randomize(a) {
  for (let i = a.length - 1; i > 0; i--) {
    const j = random(0, i);
    [a[i], a[j]] = [a[j], a[i]]
  }
}


// Get the exact position of the number on the deal
function getPosition(num, dial) {
  for (let i = 0; i < dial.length; i++)
    for (let j = 0; j < dial[i].length; j++) {
      if (dial[i][j] == num) return [i, j]
    }
}


// Get dealing code
const length = random(1, 5)
let code = []
for (let i = 0; i < length; i++) code.push(random(1, 9))
code = code.join('')
document.querySelector('#code').textContent = `Code: ${code}` 


// Get dial
let dial = [1, 2, 3, 4, 5, 6, 7, 8, 9]
randomize(dial)
dial = dial.join('')
document.querySelector('#dial').textContent = `Dial: ${dial}`


// Show dial layout
dial = dial.split(/(\d{3})/).filter(d => d)
document.querySelector('#layout').innerHTML = 
  dial.reduce((acc, tree) => acc += `<br>${tree}`)


// Moves (starting point counts 0)
let moves = 0
for (let i = 1; i < code.length; i++) {
  const a = getPosition(code[i - 1], dial)
  const b = getPosition(code[i], dial)
  moves += Math.max(Math.abs(a[0] - b[0]), Math.abs(a[1] - b[1]))
}
document.querySelector('#moves').textContent = `Moves: ${moves}`