J's maths homework

node v8.17.0
version: 1.0.0
endpointsharetweet
The code below solves the following mathematical problem: From the digits 2, 3, 4, 5, 6, 7 Find the solution to [ ] x [ ] [ ] = [ ] [ ] [ ] Place each of the digits into one of the slots to make the equation valid. Each digit can be used only once.
const numbers = [ 2, 3, 4, 5, 6, 7 ] // pick a random number from the list. Remove the // selected number from the list and return the number. const pick = (list) => { const index = Math.floor(Math.random()*list.length) return list.splice(index, 1)[0] } // count the number of calculations we make let iterations = 0 // repeat this loop until we've found the answer do { // counter iterations++ // make a fresh copy of the digits const digits = numbers.slice() // pick the single digit number randomly from the list const singleDigit = pick(digits) // pick units and tens digits of the second number // from the remaining numbers in the list const units = pick(digits) const tens = pick(digits) // calculate the two digit number from the tens & units const twoDigits = tens * 10 + units // find the product of the single digit number // and the two digit number const product = singleDigit * twoDigits // split the product into an array of digis const productStr = product.toString().split('') // the answer must have // - 3 digits // - contain all three remaining numbers if (productStr.length === 3 && productStr.includes(digits[0].toString()) && productStr.includes(digits[1].toString()) && productStr.includes(digits[2].toString()) ) { console.log('Answer found!') console.log(`${singleDigit} x ${twoDigits} = ${product}`) console.log(`It took ${iterations} attempts to find the answer.`) break; } } while(true)
Loading…

no comments

    sign in to comment