DEV Community

Seek-Help!

nnguyen52 on September 20, 2019

hi everyone and have a nice day! im pretty new to javascript as well as propramming. (been for only 1 month) im practicing this question...
Collapse
 
arrlancore profile image
arrlancores • Edited

Hi, maybe I can help, you can check the live version here codesandbox

function randomNumber() {
  const generateRandom = () => Math.floor(Math.random() * 50)
  const number = generateRandom();
  return number > 10 ? number : number + 10
}

function getLowerNumber (num) {
  let getGreaterNumber = randomNumber()
  while(getGreaterNumber >= num && getGreaterNumber !== 0) {
    getGreaterNumber = randomNumber()
  }
  return getGreaterNumber
}

const cakeMade = randomNumber()
const cakeEat = getLowerNumber(cakeMade)

document.getElementById("app").innerHTML = `
<h1>Q: I made ${cakeMade} cupcakes and ate ${cakeEat ? cakeEat : 'none'} of them. How many am i left with?</h1>
<h1>A: ${cakeEat === 0 ? 'I don`t need to do any calculations.' : cakeMade - cakeEat}</h1>
`;
Collapse
 
avalander profile image
Avalander • Edited

Using a while loop to generate a number of eaten cupcakes smaller than the amount made is unnecessary, it's better to generate the amount of cupcakes and then use that number as the ceiling for the amount of eaten cupcakes.

function randInt(start, end) {
  return Math.floor(Math.random() * (end - start)) + start
}

const made = randInt(0, 50)
const eaten = randInt(0, made)
Collapse
 
arrlancore profile image
arrlancores • Edited

Yes it's make sense to use start-end range for eaten and or made cakes and should be better. Already updated my code on sandbox

Collapse
 
Sloan, the sloth mascot
Comment deleted
Collapse
 
nnguyen52 profile image
nnguyen52

Hi Sir, i checked the code you guided me, it seems not working somehow. and im just getting to While-operation and i have not known about $, then i got confused. can you make it simplified ?

Thread Thread
 
arrlancore profile image
arrlancores

It's "template literal string in javascript" if you want to look at it. But you can simply change with + for join string like this:

"Q: I made " + cakeMade + " cupcakes "