Random() return 1 or -1 - javascript

I'm working on After Effetcs expressions. I'm trying to use random function to return 1 or -1 but never 0.
I need to return integers range between 10 to 20 or between -20 to -10.
It seems to be simple, but I dont find how to do that. Any idea ?
Thanks for your help !

You could take a factor of two and replace zero with -1.
function random() {
return Math.floor(Math.random() * 2) || -1;
}
var i = 10;
while (i--) console.log(random());

I stole some inspiration from Getting a random value from a JavaScript array
var myArray = [1, -1]
var rand = myArray[Math.floor(Math.random() * myArray.length)];
console.log(rand);
Put whatever number you want into that array.

All answers to this point are good but I thought I might still add this :)
console.log("1 or -1: ", (()=>{if(Math.random() > 0.5) return 1; else return -1})())
console.log("Between 10 and 20: ", Math.floor(Math.random()*11+10));
console.log("Between -10 and -20: ", Math.floor(Math.random()*11+10) * -1);

Thanks a lot for those answers. I used something like this and it's working, but maybe it's not perfect :
random(10,20)*(Math.round(random())-0.5)*2
I'm not sure that the probability of getting 1 or -1 is exactly 1 in 2.

Related

Why does the output of the function 0 even though 0 isn't in the range?

I am a python developer learning javascript and NODE.js. I was practicing some javascript and one of the things I miss in python is the random.randint() function. I have tried to code my own randint function using Math.random(). The function is working great but the problem is that sometimes it outputs a value that isn't within the range given.
function true_round(num){
if (Number.isInteger(num)) { return num; }
let [before, after] = String(num).split(".");
if (Number(after.slice(0, 1)) >= 5) { return Number(before) + 1; }
else { return Number(before); }
}
function randint(lowerbound, upperbound){
if (upperbound > 0){
let rand = lowerbound + true_round(upperbound * Math.random());
if (rand > upperbound){ return upperbound; }
return rand;
}
else if (upperbound <= 0){
let rand = upperbound + true_round(lowerbound * Math.random())
if (rand < lowerbound){ return lowerbound; }
return rand;
}
}
for (i = 0; i < 100000; i++){ console.log(randint(-2, -1)); }
I expect all the outputs to be within the range given but it gives me 0 sometimes.
It's your true_round function.
Try true_round(-1.9) and you'll get 0. This is because in your round up case you always adds 1, even though in the case of -1.9 you need to subtract 1.
Your true_round() has issues with rounding negative Numbers.
See here: .
Because when its -0.6, your Programm will say 0 + 1 because its higher than 5 right?
To fix this you can either use Math.round() or instead of adding 1, make a check if its a negative number and then subtract one.
Also if you want some great and short examples for random Numbers in a range have a look at MDN great examples here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random ( eg.: getRandomIntInclusive(min, max) getRandomInt(min, max) )

Reduce a multi-digit to one-digit -guidance not answer please

goal: take a number like 54321, add the numbers together (5+4+3+2+1 = 15), then take that number (15) add the digits (1+5 = 6), so return 6;
here is my code:
function digital_root(n) {
if (n >=10) {
var digits = n.toString().split('').map(function(item, index) {return parseInt(item)}).reduce(function(a,b){ return a+b});
console.log(digits);
}
}
digital_root(1632)
Can't figure out: How to get that function to repeat over and over until digits is just one number (i.e. less than 10). I have tried a variety of nested functions, but can't seem to get it right.
If possible please point me in the direction to the solution ("try a nesting in a while... or read up on..."), but don't give me the complete code solution ("Use this code chunk:...."). I've developed a bad habit of just reading and copying...
Thank you!
Try this: reference HERE
function digital_root(n) {
var singlesum = 0;
while (n >= 10 ) {
singlesum=0;
while (n > 0) {
var rem;
rem = n % 10;
singlesum = singlesum + rem;
n = parseInt(n / 10);
}
n = singlesum;
}
console.log(singlesum);
}
digital_root(1632)
You can use recursion to solve this.
Write a function makeSingleDigit, which argument will be your number.
You need a base condition with the base step, which in your case stops the recursion when received number is one-digit and returns the number.
If condition is not true, you just need to get another digit from the number by n%10 and sum it with the makeSingleDigit(Math.floor(n/10)). By this, you repeatedly sum digits of new numbers, until function receives one-digit number.
Mathematical solution just for your information: the number, which you want to find is n % 9 === 0 ? 9 : n % 9, thus it is the remainder of the division by 9 if it is not 0, otherwise it is 9.
Here is a very optimal solution to the problem:
function digital_root(n) {
return (n - 1) % 9 + 1;
}
const result = digital_root(1632);
console.log(result);
Well, not a very good solution but you can give a hit.
function digital_root(n) {
if (n >=10) {
var digits = n.toString().split('').map(function(item, index) {return parseInt(item)}).reduce(function(a,b){ return a+b});
console.log(digits);
return(digits);
}
}
var num = 1632;
do{
num = digital_root(num);
}while(num>10);

Javascript random right answer

I would like to generate wrong number randomly between other slots.
Eg: the right answer is 4, but I want to make other slots give the wrong answer between the right answer.
Can anyone gives me a clue to achieve this? Thanks you in advance!
Sorry for my bad English, If you don't get my question.
var operators = {
"signOne": [
{
sign: "+",
method: function(a,b) {return a+b}
},
{
sign: "-",
method: function(a,b) { return a-b}
}
]};
var selectedOperatorA = Math.floor(Math.random()*operators.signOne.length);
this.hiddenTotalValue = operators.signOne[selectedOperatorA].method(this.valueA, this.valueB);
here is the output of my right answer.
You can:
Build a list containing the right answer, a smaller wrong answer and a bigger wrong answer
Sort the list with a custom random function
Code:
var answer = 9 - 5,
list = [
answer,
answer - 1 - ((Math.random() * 10) | 0),
answer + 1 + ((Math.random() * 10) | 0)
];
list.sort(function(a, b) { return Math.random() - 0.5; });
console.log(list);
Example output:
[2, 8, 4]
If needed, the position of the correct answer in the list would be given by list.indexOf(answer);.
You can calculate the real answer calcAnswer() and then create a function to create random numbers that is calcOtherAnswers() less than the real answer where as long as the result < answer (4 or whatever in your case) then generate a number.
Try using Math.random(); function to generate random numbers.
HTML
<div id="first"></div>
<div id="second"></div>
<div id="third"></div>
JS
var first = Math.floor((Math.random() * 10) + 1);
var second = Math.floor((Math.random() * 10) + 1);
while( second === first ){
second = Math.floor((Math.random() * 10) + 1);
}
var third = Math.floor((Math.random() * 10) + 1);
while( third === first || third === second ){
third = Math.floor((Math.random() * 10) + 1);
}
$("#first").html(first);
$("#second").html(second);
$("#third").html(third);
I see you posted the question for javascript, and I am posting an answer assuming that language.
From the documentation at Mozilla you can choose your max and min using a function.
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
put in the proper values of min and max
A simple way to do this would be having an array. You push the correct value into it, then have a loop that creates random numbers and adds them if they are not inside the array yet - until the array has the required size/length.
var operators = {
"signOne": [
{
sign: "+",
method: function(a,b) {return a+b}
},
{
sign: "-",
method: function(a,b) { return a-b}
}
]};
var selectedOperatorA = Math.floor(Math.random()*operators.signOne.length);
this.hiddenTotalValue = operators.signOne[selectedOperatorA].method(this.valueA, this.valueB);
here is the output of my right answer.

Need an explanation of this javascript

I have a question about this script I found and used. It works but I don't get why. The exercise was to make a list with random numbers from -50 to 50. The function below uses Math.floor(Math.random() * (the part i dont understand).
If I put this calculation on google I got as answer 151 and Math.random()*151 does not do from -50 to 50.
Can someone give me a clear explanation about this function below because I am sure that I am missing something.
this script works but I only want a clear explanation how
for (i = 0; i <= 100; i++)
{
Rnumber[i] = randomFromTo(-50,50);
}
function randomFromTo(from, to)
{
return Math.floor(Math.random() * (to - from + 1) + from);
}
to - from + 1 = 50 - (-50) + 1 = 101
Math.random() * 101 = number in range [0,101[
Math.floor([0,101[) = integer in range [0,100]
[0,100] + from = [0,100] + (-50) = integer in range [-50,50]
Which is exactly what is asked for.
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Math/random
Math.random returns a floating-point, pseudo-random number in the
range [0, 1) that is, from 0 (inclusive) up to but not including 1
(exclusive), which you can then scale to your desired range.
which when multiplied with a number > 1 and floored gives you an integer
Math.random() - get only value between 0 and 1.
Math.floor( number ) get integer down rounded value from number.
You should:
function randomFromTo(from, to)
{
// you can use doubled bitwise NOT operator which also as Math.floor get integer value from number but is much faster.
// ~1 == -2 , ~-2 == 1 and ~1.5 == -2 :)
return ~~( --from + ( Math.random() * ( ++to - from )) )
}

Positive Number to Negative Number in JavaScript?

Basically, the reverse of abs. If I have:
if ($this.find('.pdxslide-activeSlide').index() < slideNum - 1) {
slideNum = -slideNum
}
console.log(slideNum)
No matter what console always returns a positive number. How do I fix this?
If I do:
if ($this.find('.pdxslide-activeSlide').index() < slideNum - 1) {
_selector.animate({
left: (-slideNum * sizes.images.width) + 'px'
}, 750, 'InOutPDX')
} else {
_selector.animate({
left: (slideNum * sizes.images.width) + 'px'
}, 750, 'InOutPDX')
}
it works tho, but it's not "DRY" and just stupid to have an entire block of code JUST for a -.
Math.abs(num) => Always positive
-Math.abs(num) => Always negative
You do realize however, that for your code
if($this.find('.pdxslide-activeSlide').index() < slideNum-1){ slideNum = -slideNum }
console.log(slideNum)
If the index found is 3 and slideNum is 3,
then 3 < 3-1 => false
so slideNum remains positive??
It looks more like a logic error to me.
The reverse of abs is Math.abs(num) * -1.
The basic formula to reverse positive to negative or negative to positive:
i - (i * 2)
Javascript has a dedicated operator for this: unary negation.
TL;DR: It's the minus sign!
To negate a number, simply prefix it with - in the most intuitive possible way. No need to write a function, use Math.abs() multiply by -1 or use the bitwise operator.
Unary negation works on number literals:
let a = 10; // a is `10`
let b = -10; // b is `-10`
It works with variables too:
let x = 50;
x = -x; // x is now `-50`
let y = -6;
y = -y; // y is now `6`
You can even use it multiple times if you use the grouping operator (a.k.a. parentheses:
l = 10; // l is `10`
m = -10; // m is `-10`
n = -(10); // n is `-10`
o = -(-(10)); // o is `10`
p = -(-10); // p is `10` (double negative makes a positive)
All of the above works with a variable as well.
To get a negative version of a number in JavaScript you can always use the ~ bitwise operator.
For example, if you have a = 1000 and you need to convert it to a negative, you could do the following:
a = ~a + 1;
Which would result in a being -1000.
var x = 100;
var negX = ( -x ); // => -100
num * -1
This would do it for you.
Are you sure that control is going into the body of the if? As in does the condition in the if ever hold true? Because if it doesn't, the body of the if will never get executed and slideNum will remain positive. I'm going to hazard a guess that this is probably what you're seeing.
If I try the following in Firebug, it seems to work:
>>> i = 5; console.log(i); i = -i; console.log(i);
5
-5
slideNum *= -1 should also work. As should Math.abs(slideNum) * -1.
If you don't feel like using Math.Abs * -1 you can you this simple if statement :P
if (x > 0) {
x = -x;
}
Of course you could make this a function like this
function makeNegative(number) {
if (number > 0) {
number = -number;
}
}
makeNegative(-3) => -3
makeNegative(5) => -5
Hope this helps! Math.abs will likely work for you but if it doesn't this little
var i = 10;
i = i / -1;
Result: -10
var i = -10;
i = i / -1;
Result: 10
If you divide by negative 1, it will always flip your number either way.
Use 0 - x
x being the number you want to invert
It will convert negative array to positive or vice versa
function negateOrPositive(arr) {
arr.map(res => -res)
};
In vanilla javascript
if(number > 0)
return -1*number;
Where number above is the positive number you intend to convert
This code will convert just positive numbers to negative numbers simple by multiplying by -1

Categories