'How to check if a variable value is increasing or decreasing and show the number with what it increased or decreased
This is a dumb question, And I can't believe I asked for a solution, Well now that I am pretty good I answered it. So, Firstly I create the variable number then I add two properties to it's prototype called oldValue and randomize then I set randomize to a random decimal number between 0 and 1 using Math.random(), I store the value of the number variable before any further changes, In the property I added to the prototype called oldValue, After that I check if the randomize is less than 0.5 or more than 0.5 if less then I decrement a random number between 50-100 else I increment with a number between 50-100, At last I console.log() the changes.
let number = 0;
number.__proto__.oldValue = number;
number.__proto__.randomize = 0;
let interval = setInterval(() => {
number.__proto__.randomize = Math.random();
let randomNumber = Math.floor(Math.random() * (100 - 50) + 50);
number.__proto__.oldValue = number;
if (number.randomize > 0.5) number += randomNumber;
else number -= randomNumber;
console.log((number - number.oldValue) < 0 ? `decrement: ${number} ${number.oldValue}` : `increment: ${number} ${number.oldValue}`);
}, 100)
Solution 1:[1]
You can store the delta in a variable. Additionally, to generate a random boolean, you only need to check if Math.random() is greater than 0.5.
var number = 0;
setInterval(() => {
let delta = Math.floor(Math.random() * 100) * (Math.random() > .5 ? 1 : -1);
console.log('Delta:', delta);
number += delta;
}, 100)
Solution 2:[2]
When you are creating random number you can store it. Math.floor(Math.random() * 100)
Like this:
var number = 0;
var randomize = 0;
setInterval(() => {
randomize = 0;
randomize += Math.floor(Math.random() * 100);
if (randomize > 50) {
let newRandomise = Math.floor(Math.random() * 100);
number += newRandomise
console.log("increased by", newRandomise)
}
else {
console.log("deccreased by", randomize)
number -= Math.floor(Math.random() * 100)
}
}, 100)
Solution 3:[3]
Just add some console.log s that will help you
var number = 0;
var randomize = 0;
setInterval(() => {
randomize = 0;
randomize += Math.floor(Math.random() * 100);
if (randomize > 50) {
const incrementer = Math.floor(Math.random() * 100);
console.log('Increased by', incrementer);
number += incrementer;
}
else {
const decrementer = Math.floor(Math.random() * 100);
console.log('Decreased by', decrementer);
number -= decrementer;
}
}, 100)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Unmitigated |
| Solution 2 | Alireza Ahmadi |
| Solution 3 | Nitheesh |
