I am writing a javascript code which gives output of a X which always divisible by Y
For example if I have 7 which is not divisible by 4 but I want the code to add number up to 8
This is the code I did, it works for 7, but it should work for value 8
var x = 7
var y = 4
x = x + (y - x%y)
console.log(x)
I get the output 8 which is correct, but
var x = 8
var y = 4
x = x + (y - x%y)
console.log(x)
I am getting 12 which is not correct, I want the same 8
My question is, without putting an if condition how I will make this formula work?
If I understood correctly, you're probably looking for something like this:
Math.ceil(x / y) * y;
function toNearestMultiple(x, y) {
return Math.ceil(x / y) * y;
}
console.log(toNearestMultiple(7, 4));
console.log(toNearestMultiple(8, 4));
console.log(toNearestMultiple(9, 4));
This should also do it:
var x = 8
var y = 4
x = x+y-(x-1)%y-1
console.log(x)
Related
So I have some numbers x = 320232 y = 2301 z = 12020305. I want to round these numbers off using JavaScript so that they become x = 320000 y = 2300 z = 12000000.
I tried Math.round and Math.floor but turns out that they only work with decimal values like
a = 3.1; Math.round(a); // Outputs 3 and not whole numbers.
So my question is can we round of whole numbers using JavaScript and If yes then how?
Edit: I want it to the round of to the starting 3 digit places as seen in the variables above. Like If there was another variable called c = 423841 It should round off to become c = 424000.
You could work with the logarithm of ten and adjust the digits.
const
format = n => v => {
if (!v) return 0;
const l = Math.floor(Math.log10(Math.abs(v))) - n + 1;
return Math.round(v / 10 ** l) * 10 ** l;
};
console.log([0, -9876, 320232, 2301, 12020305, 123456789].map(format(3)));
The solution is to first calculate how many numbers need to be rounded away, and then use that in a round.
Math.round(1234/100)*100 would round to 1200 so we can use this to round. We then only need to determan what to replace 100 with in this example.
That is that would be a 1 followed by LENGTH - 3 zeros. That number can be calculated as it is 10 to the power of LENGTH - 3, in JS: 10 ** (length - 3).
var x = 320232;
var y = 2301;
var z = 12020305;
function my_round(number){
var org_number = number;
// calculate integer number
var count = 0;
if (number >= 1) ++count;
while (number / 10 >= 1) {
number /= 10;
++count;
}
// length - 3
count = Math.round(count) - 3;
if (count < 0){
count = 0;
}
// 10 to the power of (length - 3)
var helper = 10 ** count;
return Math.round(org_number/helper)*helper;
}
alert(my_round(x));
alert(my_round(y));
alert(my_round(z));
It is not the prettiest code, though I tried to make it explainable code.
This should work:
function roundToNthPlace(input, n) {
let powerOfTen = 10 ** n
return Math.round(input/powerOfTen) * powerOfTen;
}
console.log([320232, 2301,12020305, 423841].map(input => roundToNthPlace(input, 3)));
Output: [320000, 2000, 12020000, 424000]
This is part of a bigger problem I try to solve in an exercise. It looks like this:
x is 10 times more likely to appear than y.
z appears 2x less often than y.
I solved this by calculating a single unit like this:
const x = 100;
const y = 10;
const z = 5;
const unit = 100 / (x + y + z);
unit equals 0.87
So when I do (0.87) + (0.87 * 10) + (0.87 * 5) I get 100%(almost)
Then I generate a random number between 0 and 1.
const randomNumber = Math.random();
function getValue() {
if (randomNumber <= 0.87) {
console.log('x');
} else if (randomNumber > 0.87 && randomNumber < 95.7) {
console.log('y');
} else console.log('z');
}
getValue();
If value<0.87 then I log out x, if value < 0.87+(0.087*10) I log y etc
Can anyone recommend a more logical and elegant way than this?
Your way looks clean for me except the fact that randomNumber > 0.87 is redundant.
if you store the value x, y and z in an array, you can probably write some cleaner code for example:
let prob = [100, 10, 5];
let sum = prob.reduce((a, b) => a + b, 0);
let normalizedProb = prob.map(p => p / sum);
let cummulativeProb = normalizedProb.map((cummulative => p => cummulative += p)(0));
for (let i = 0; i <= 50; i++) {
let r = Math.random();
console.log(cummulativeProb.filter(p => r >= p).length);
}
Also, you may want to read this post for faster implementation (in python though). However, the code will be more complicated for sure.
Since the weights are small integers, you can duplicate the x, y and z in an array, and just pick one random cell of the array:
let choices = "zyyxxxxxxxxxxxxxxxxxxxx";
console.log(choices[Math.floor(Math.random() * 23)]);
Here the magic number 23 is the number of choices, 1+2+20; and Math.floor(Math.random() * 23) is a random integer uniformly at random in range [0, 22] (both bounds included). See also:
Generating random whole numbers in JavaScript in a specific range?
3√(9) = 2.0800838231, or Y√x
is there any Math function in vanilla js for calculation above the formula ?
Can you try this:
console.log(Math.pow(9, 1/3)); // replace "3" with the root
// "9" with your number
This is what i think will work:
document.write(Math.pow(9, 1 / 3));
pow raises the second argument to the power of first argument.
Now from basic math we know 3√(9) = (9)^(1/3)
The Math.cbrt() function returns the cube root of a number.
Math.cbrt(x) returns y where x is a number and y * y * y = x.
For example, cube root of 27 = 3 , cube root of 8 = 2.
Math.cbrt(27) = 3.
Here x = 27 and y = 3. So, y * y * y = x. So, 3 * 3 * 3 = 27.
console.log(Math.cbrt(8),2);
console.log(Math.cbrt(27),3);
console.log(Math.cbrt(9),2.080083823051904);
I have hard time wrapping my head around how to get this to work so I came to ask the help of the brilliant minds in here.
The thing is, I want to reverse the process of the below equation so that I get X from the given Y and Z.
Z = [ ( X * 30 ) % Y ]
For the use-case, a user inputs number Y and then presses ENTER, the system get's the current server time and then multiplies that by 30. The user will then be given the remainder of the server time in format HHMMssxxx, (hmm, xxx here is the millisecond.. I don't know the format letter for millisecond.. hehe..), divided by Y - that is (X*30) % Y where X is the current server time converted to int.
How can I do this in reverse?
The catch is, X should not be greater than 2359999 -> (23:59:59.999) the maximum time value for a 24-hour clock.
Supposedly I have Z = 32, Y = 400, how can I find X?
I know that it's possible to have multiple answers. Here's what I came up so far but I think this is not very optimal in terms of performance.
function getTimeIDx(rem, codeIndexer) {
var times = [];
for(var i = 0; i < 2400000; i++) {
if((i * 30) % codeIndexer == rem) {
var str = i.toString(),
l = str.length;
if(l < 9)
str = '000000000'.substr(0, 9 - l) + str;
str = str.substr(0, 2) + ':' + str.substr(2, 2) + ':' + str.substr(4, 2) + '.' + str.substr(6);
if(/^(?:[0-1]?\d|2[0-3]):(?:[0-5]?\d):(?:[0-5]+\d)/.test(str))
times.push(str);
}
}
return times;
}
Is there some way to do this more efficiently? Is there something like a inverse modulo?
EDIT:
Updated code to check if the string is a valid time.
You cannot reverse it. Modulo is the remainder from a division operation.
Simplifying your equation. Z = Y % 2
Z is 0 for half of the values and 1 for the rest.
You can not solve for the dividend with just the remainder and the divisor.
Lets fill it into the equation:
32 = ( X * 30 ) % 400
Then this means that X * 30 is a multiple of 400 plus 32:
32
432
832
...
Now we could divide that by 30 to get x. That could be done in js like this:
function* reverse(Z, Y) {
for(let n = 0; ; n++)
yield (Z + Y * n) / 30;
}
Usable as:
for(let X of reverse(32, 400))
console.log(X);
Note that this loop will run forever as there are infinite results. Try it
In javascript I get two numbers let's call them x & y and an array of integers with random int's from 0 - 10 arrayints.
x is the number I'm trying to get by combining y with any of the numbers in arrayints.
for example: lets say x = 8 and y = 3 and arrayints consists of numbers arrayints(1,7,2,7,4,5)
so x could equal = y + 5
or
x = y + 1 + 4
All the values in x, y and arrayints will be random and always <= 10.
Please advise if more information is needed and everything will be in javascript or jquery no fuss as far as my code goes I will copy and paste but it will just be one blob of incromprehensible letters which are giving me an headache.
function makex(x,y) {
//this is how I get the array of random ints <=10
$("#div").children().each(function(n, i) {
var id = parseInt(this.id+"");
});
}
Here's a recursive solution that returns an array of the integers that add up to x, including y (or an empty array if it doesn't exist). If you want to exclude y, then feel free to make a wrapper for this.
function make(x, y, intOptions) {
var z = x - y
if (intOptions.indexOf(z) !== -1) {
return [y, z];
} else if (intOptions.length > 1){
var i = intOptions.length;
var ans;
while (i--) {
ans = make(z, intOptions[i], intOptions.slice(0, i))
if (ans.length) {
return [y].concat(ans);
}
}
}
return [];
}