Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I am writing some JS and I can't seem to figure out how to write a function that will give a true or false statement back.
The way I want to write it is:
Loop function 5 times
on each loop give 1 of 8 random prizes
then check the probability of getting the prize, e.g 1 out of 10,000.
One of the loops has to provide with 1 as true
Any help is appreciated.
This is what I have tried, in terms of getting the probability
function prob(n) {
var old = n - 1;
var val = (n += 1);
return Math.floor(Math.random() * val) == old;
}
console.log(prob(2));
I generally use these helper functions if I need random
const chance = (percentage) => Math.random() * 100 < percentage;
const getRandomInt = (min, max) =>
Math.floor(Math.random() * (max - min + 1)) + min;
const getRandomArbitrary = (min, max) =>
Math.random() * (max - min) + min;
console.log(chance(50));
console.log(getRandomInt(1, 10));
console.log(getRandomArbitrary(0, 5));
// Full code
const prizes = [{
name: 'Bear',
probability: 5,
},
{
name: 'Car',
probability: 0.02,
},
{
name: 'Poster',
probability: 90,
},
];
let count = 5;
while (count--) {
const prize = prizes[getRandomInt(0, prizes.length - 1)];
const win = chance(prize.probability);
console.log(`Prize: ${prize.name} - Won: ${win}`);
}
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
I make a site where the color of the div is randomly generating compared to this array:
let pastelColor = [
'ffaacc','ffbbcc','ffcccc','ffddcc','ffeecc','ffffcc','ffaadd','ffbbdd','ffccdd','ffdddd','ffeedd','ffffdd',
'ffaaee','ffbbee','ffccee','ffddee','ffeeee','ffffee','ffaaff','ffbbff','ffccff','ffddff','ffeeff','ffffff',
'ccaaff','ccbbff','ccccff','ccddff','cceeff','ccffff','ccaaee','ccbbee','ccccee','ccddee','cceeee','ccffee',
'ccaadd','ccbbdd','ccccdd','ccdddd','cceedd','ccffdd','ccaacc','ccbbcc','cccccc','ccddcc','cceecc','ccffcc'
]
I tried several Algo with Case Switch but the function took too much room, I was wondering in curiosity if an algo would be able to generate this array ?
Thank you in advance for those who answer
if an algo would be able to generate this array ?
Sure. If you need that array in that exact order:
let pastelColor = Array.from("abcdef".repeat(8), (ch, i) =>
(([a,...r]) => a+a+ch+ch+r[~~(i/6)%4].repeat(2))(i<24 ? "fcdef" : "cfedc")
);
console.log(pastelColor);
If you are not really interested in the array with color codes, but only in the generation of a random color from it, then:
let pick = str => str[Math.floor(Math.random() * str.length)].repeat(2);
let pastelColor = pick("cf") + pick("abcdef") + pick("cdef");
console.log(pastelColor);
You need to fill the array with the converted hexadecimal color with randomly generated integers ranging from 0 to 255 like this:
const getRandomInt = (min, max) => {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min) + min);
}
const getRandomColorUnit = () => {
const color = getRandomInt(0, 256).toString(16);
if (color.length < 2) return '0' + color;
return color;
};
const getRandomColor = () => `#${getRandomColorUnit()}${getRandomColorUnit()}${getRandomColorUnit()}`;
const colors = new Array(100).fill(0).map(getRandomColor);
console.log(colors);
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I am trying to create code that if we generate number between 20 and 120 and the generated number is >= than 100 then we want to reduce by 20. I dont want to create multiple random numbers..Can someone help ??
my basic math.rand function -
function randomNumber(min, max) {
return Math.random() * (max - min) + min;
}
the code i tried to make
randomNumber(20,120);
if(randomNumber >= 100){
return randomNumber - 20;
}
message.reply(randomNumber);
In messages it display function randomNumber(min, max) { etc...
Store the result of the randomNumber function in a variable like this:
let number = randomNumber(20,120);
if(number >= 100){
number -= 20;
}
message.reply(number);
In JavaScript, you add () to run a function. Without those parentheses, you are just returning the code itself. When you state if(randomNumber >= 100), you aren't comparing the value that the function returns, rather the function itself.
When you call randomNumber(20,120) it returns a number, but you don’t put that number in any variable, so it just gets lost. And then you return randomNumber, which is a function, that’s why it prints out the content of the function.
To avoid that, create a variable containing the random number, like so:
let x = randomNumber(20,120);
if(x >= 100){
x -= 20;
}
message.reply(x);
Just save the result of your function in a variable and then check if that variable is >= 100 and if it is reduce it by 20 using a simple ternary operator.
function randomNumber(min, max) {
return Math.random() * (max - min) + min;
}
number = randomNumber(20,120);
number = (number < 100) ? number : number -20;
console.log(number);
I have static questions such as below. I'm using these questions for my quiz in my blog.
var quiz = {
"data": [
{
"question": "What is 10 + 5 ?",
"answer": "15",
},
{
"question": "What is 10 - 5 ?",
"answer": "5",
},
{
"question": "What is 10 + (- 5) ?",
"answer": "5",
},
{
"question": "What is -10 + 5 ?",
"answer": "-5",
},
{
"question": "What is -6 + (-6) ?",
"answer": "-12",
},
]
}
How can i make the questions & answer dynamic? In other words, each of the numbers will take a value between 1 and 20. The answer will be calculated based on the question.
thanks
function generateQuestion(template, min, max){
// Generate first random number
var numOne = Math.floor(Math.random() * (max - min) ) + min;
// Generate second random number
var numTwo = Math.floor(Math.random() * (max - min) ) + min;
// append first question part
var question = template[0];
// check if first number is negative to put brackets around the string
if(numOne < 0 )
question += "(" + numOne + ")";
else
question += numOne;
// append operator
question += " + ";
// check if second number is negative to put brackets around the string
if(numTwo < 0 )
question += "(" + numTwo + ")";
else
question += numTwo;
// append last part of question
question += template[1];
// return your object
return {
question: question,
answer: numOne + numTwo
};
}
var numberOfQuestions = 4;
var questions = [];
for(var i = 0; i < numberOfQuestions; i++)
questions.push(generateQuestion(["What is ", "?"], -20, 20))
console.log(questions);
I find the expr-eval package to be quite useful for use cases such as yours.
A simplified example:
const { Parser } = exprEval;
const randomNumber = (min, max) => Math.floor(Math.random() * max) + min;
const quiz = {
equation: `${randomNumber(1, 20)} + ${randomNumber(1, 20)}`,
get question() {
return `What is ${this.equation.toString()}`;
},
get answer() {
return `The answer is: ${Parser.evaluate(this.equation)} 👩🎓`;
},
};
console.log(quiz.question);
console.log(quiz.answer)
<script src="https://cdnjs.cloudflare.com/ajax/libs/expr-eval/2.0.2/bundle.js"></script>
You can use template literal and Math.random
// define all the airthmeatic operation
let operations = ["+","-","*","/"]
// map airthmeatic sign to related function
let funcs = {
"+" : (a,b)=> a+b,
"-" : (a,b)=> a-b,
"*": (a,b)=> a*b,
"/" : (a,b)=> a/b
}
// function to build random question
let randomQuizBuilder = (a,b,operation) =>{
let val = prompt(`what is ${a} ${operation} ${b}`)
console.log(+val === funcs[operation](a,b))
}
let i=2
// a loop to build a fix number of question
while(i--){
// get random value in range of 20
let a = Math.floor(Math.random() * 20)
let b = Math.floor(Math.random() * 20)
// select a random operation
let operation =operations[Math.floor(Math.random() * (operations.length))]
// call quizBuilder to build a random question
randomQuizBuilder(a,b, operation)
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
My Javascript formula is
total = parseFloat(unit * rate) +
parseFloat(rateamount) +
parseFloat(((unit * rate) +
(rateamount)) * (tax/100));
values are:
unit = 5, rate = 10, rateamount = 10, tax = 10.
The answer it is giving me is 561, which is wrong.
Any help is welcome.
Your problem is that you are concatenating strings with this part:
parseFloat(((unit * rate) + (rateamount))
You forgot to parse rateamount which is a string of '10'.
So this Code:
var unit = '5',
rate = '10',
rateamount = '10',
tax = '10';
var total = parseFloat(unit * rate) + parseFloat(rateamount) + parseFloat(((unit * rate) + (rateamount)) * (tax / 100));
console.log(total);
should be like that:
var unit = '5',
rate = '10',
rateamount = '10',
tax = '10'
var total = parseFloat(unit * rate) + parseFloat(rateamount) + parseFloat(((unit * rate) + parseFloat(rateamount)) * (tax / 100));
console.log(total);
Though i wouldn't use parseFloat like that, i would just do it once before any calculations, in order to stay away from bugs like this one.
var unit = '5',
rate = '10',
rateamount = '10',
tax = '10';
var parsedUnit = parseFloat(unit),
parseRate = parseFloat(rate),
parsedRateamount = parseFloat(rateamount),
parsedTax = parseFloat(tax);
var total = parsedUnit * parseRate + parsedRateamount + ((parsedUnit * parseRate) + (parsedRateamount)) * (parsedTax / 100);
console.log(total);
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
The problem is not complicated. Log randomly a name from an array of names.
My solution comes as this.
var names = [ 'nick', 'rock', 'danieel' ];
function randPicker(names) {
var randNum = Math.floor((Math.random() * 10));
var name = randNum <= (names.length - 1) ? console.log(names[randNum]) : randPicker(arguments[0]);
};
It seems to me that this code is not that beautiful, because im quite sure that there are better ways that perform much faster. Is that true?
The better way is make the function return random element of the array and fix its getting:
function randPicker(a) {
return a[Math.random() * a.length | 0];
}
And the test:
function randPicker(a) {
return a[Math.random() * a.length | 0];
}
var names = ['nick', 'rock', 'danieel'];
for (var q=0; q<16; ++q) {
console.log(randPicker(names));
}
You can get your randNum straight away to retrieve a name:
var names = [ 'nick', 'rock', 'danieel' ];
function randPicker(names) {
var randNum = Math.floor((Math.random() * names.length));
var name = console.log(names[randNum]);
};
You can use
var names = [ 'nick', 'rock', 'danieel' ];
function randomPicker(names) {
return names[Math.floor(Math.random() * (names.length+1))];
}
Explanation:
Math.random() returns a number in range [0,1]
Multiply it by the length of array + 1 to get numbers in range [0,length] with decimals.
Finally use Math.floor to round it to interger.