Find nearest next even 100 - javascript

In javascript what's the simplest way to find the next even 100 ("even 100" = 200, 400, etc.) that's closest to the given number. For ex: 1723 should return 1800, 1402 should return 1600, 21 should return 200, 17659 should return 17800 etc. I have the following that finds the nearest 100 next to the given_num but not the even 100
(parseInt(((given_num + 99) / 100 )) * 100 )
I can think of one way of getting the number without zeroes and checking if its odd/even to figure out next even number if its odd.But more curious to see if there's some simple/elegant way.

Based on bmb's comment, it sounds like you want granularity of 200, not 100. If so:
Divide by 200, round up, multiply by 200:
var tests = [
{value: 1723, expect: 1800},
{value: 1402, expect: 1600},
{value: 21, expect: 200},
{value: 17659, expect: 17800}
];
tests.forEach(test);
function test(entry) {
var result = Math.ceil(entry.value / 200) * 200;
console.log({
value: entry.value,
expect: entry.expect,
result: result
});
}
If you really want to work by rounding up to the "next 100," then the result for 1723 must be 1900 if the result for 1402 is 1600, and you do it by dividing by 100, rounding up, multplying by 100, and adding 100 (or dividing by 100, rounding up, adding 1, and multiplying by 100, which is the same thing):
var tests = [
{value: 1723, expect: 1800},
{value: 1402, expect: 1600},
{value: 21, expect: 200},
{value: 17659, expect: 17800}
];
tests.forEach(test);
function test(entry) {
var result = Math.ceil(entry.value / 100) * 100 + 100;
console.log({
value: entry.value,
expect: entry.expect,
result: result
});
}

Call recursively if not even, add 1 to go the next 100 etc
function closestEven(n) {
var x = Math.ceil(n / 100 ), y = x * 100;
return x % 2 === 0 ? y : closestEven(y+1);
}
console.log( closestEven(1723) ); // 1800
console.log( closestEven(1402) ); // 1600
console.log( closestEven(21) ); // 200
console.log( closestEven(17659)); // 17800

Try this:
var given_num = 1723;
var result = (given_num) + (100 - ((given_num + 100) % 100));
alert(result);

Related

Is there any function or method for finding the answer

find total number of elements in between the numbers 0 t0 10, 10 to 20, 20 to 30 and so on in an array.
say the array [23,14,67,17,87]
so there are 0 numbers from 0 to 10, 2 numbers from 10 to 20, and so on.
This crux of the logic:
const data = [23,14,67,17,87];
console.log(
data.reduce((results, entry) => {
// We only are interested in the 10s unit; the 1s don't matter.
// This discards the 1s unit, and homologates numbers of the same multiple
// of 10, e.g.
// 14 → 1
// 17 → 1
const factor = Math.floor(entry / 10);
// Create a human readable key, i.e 10 to 20
const key = `${factor * 10} to ${(factor * 10) + 10}`
return {
...results,
// If the group has not already been added to the results,
// this will set the value to 1, otherwise increment by 1.
[key]: (results[key] ?? 0) + 1,
};
}, {})
);
You can always sort the groups if needed.

Least amount of coins to use given an amount

I'm trying to create a function in javascript/jquery to work out what the minimum number of coins it would take to add up to a total inputed amount.
So I have an object array of the coins:
var coins = [
{
pennies: 200,
print: '£2'
},
{
pennies: 100,
print: '£1'
},
{
pennies: 50,
print: '50p'
},
{
pennies: 20,
print: '20p'},
{
pennies: 10,
print: '10p'
},
{
pennies: 5,
print: '5p'},
{
pennies: 2,
print: '2p'
},
{
pennies: 1,
print: '1p'
}
];
var $input = $('input');
$input.keypress(function(e) {
if (e.which == 13) {
// do something
}
});
And an input field in my HTML.
So if someone enters 123p I would like the form to return 1 x £1, 1 x 20p, 1 x 2p and 1 x 1p.
I'm struggling to figure out where to start. If anyone could help it would be much appreciated.
Thanks
It sounds like you just need to iterate over the coins array, starting from the highest denomination:
const coins=[{pennies:200,print:'£2'},{pennies:100,print:'£1'},{pennies:50,print:'50p'},{pennies:20,print:'20p'},{pennies:10,print:'10p'},{pennies:5,print:'5p'},{pennies:2,print:'2p'},{pennies:1,print:'1p'}];
const getCoins = penniesToGo => coins.reduce((coinCountStr, { pennies, print }) => {
const numCoins = Math.floor(penniesToGo / pennies);
if (numCoins < 1) return coinCountStr;
penniesToGo -= numCoins * pennies;
const thisCoinStr = `${numCoins}x ${print}`;
return coinCountStr ? coinCountStr + ', ' + thisCoinStr : thisCoinStr;
}, '');
console.log(getCoins(201));
console.log(getCoins(333));
console.log(getCoins(6));

How do I split a number into chunks of max 100 in JavaScript?

I have a number (let's say 525). I would like to take this number and split it into an array of chunks with a max of 100 each value. If I took 525 and split it into an array, it would look like:
[
100,
100,
100,
100,
100,
25
]
Here's what I've tried so far:
var number = 525;
var array = [];
while (number > 0) {
number = number - 100;
array.push(Math.min(number, 100));
}
That doesn't get me far. It just returns [ 100, 100, 100, 100, 25, -75 ]. I know that using while isn't the best way to go, but that is what I could think of off the top of my head. Does anyone have any other way that improve my code and be more efficient?
You can figure the number of times that number is divisible by 100 then programmatically create an array of that length:
var number = 525;
var array = new Array(Math.floor(number / 100)).fill(100).concat(number % 100))
// [ 100, 100, 100, 100, 100, 25 ]
You can extend this to chunk by any number:
function chunkBy(number, n) {
var chunks = Array(Math.floor(number / n)).fill(n);
var remainder = number % n;
if (remainder > 0) {
chunks.append(remainder);
}
return chunks;
}
Alternatively, simply push the element before performing your subtraction:
var number = 525;
var array = [];
while (number > 0) {
array.push(Math.min(number, 100));
number = number - 100;
}
// [ 100, 100, 100, 100, 100, 25 ]
Using ES6 with arrow functions:
const chunkBy = (n) => number => {
var chunks = new Array(Math.floor(number / n)).fill(n);
var remainder = number % n;
console.log('CHUNKS = ', chunks);
if (remainder > 0) {
chunks.push(remainder);
}
return chunks;
};
const chunkBy50 = chunkBy(50);
const chunkBy100 = chunkBy(100);
const chunkBy77 = chunkBy(77);
console.log(chunkBy50(500));
// [ 50, 50, 50, 50, 50, 50, 50, 50, 50, 50 ]
console.log(chunkBy100(500));
// [ 100, 100, 100, 100, 100 ]
console.log(chunkBy77(500));
// [ 77, 77, 77, 77, 77, 77, 38 ]
Alternatively, you could use integer division to get the number of occurrences for the "max" divisor and then use the "mod" operation to get the final chunk or remainder.
const number = 525;
const max = 100;
const maxCount = Math.floor(number / max); // 5
const remainder = 525 % max; // 25
You should move the line number = number - 100; after you push the number, so it will count the 1st 100, and stop before pushing the -75:
var number = 525;
var array = [];
while (number > 0) {
array.push(Math.min(number, 100));
number = number - 100; // remove number after pushing
}
console.log(array);
And a fancy one using Array#from:
const number = 525;
const get100s = (number) => Array.from({ length: Math.ceil(number / 100) }, (_, i) => {
const leftover = number - i * 100;
return leftover > 100 ? 100 : leftover;
});
console.log('525: ', get100s(525));
console.log('500: ', get100s(500));
console.log('10: ', get100s(10));
The problem here is that you are substracting 100 to the number after adding it to the array.
The code should be like this:
var number = 525;
var array = [];
while (number > 0) {
array.push(Math.min(number, 100));
number = number - 100;
}
Apparently I think completely different about this kind of problem. I would have divided the number by the section size and rounded down/truncated to get the number of sections, added that many sections to the final array, and then added the modulus of the section size and the number as the final value.
var value = 525;
function splitValue(val, sectionSize)
{
var sections = Math.floor(val/sectionSize);
var finalValue = val%sectionSize;
var splitValues = [];
for (var i = 0; i < sections; i++) {
splitValues.push(sectionSize);
}
splitValues.push(finalValue);
return splitValues;
}
var valueArray = splitValue(value, 100);
console.log(valueArray);
You can also use modulus.
let x = 556;
let mod = 100;
let res = [];
for (let i = 0; i < parseInt(x / mod); i++) res.push(mod);
res.push(x % mod);

JavaScript array find fitting range

I have the following array with two objects:
var myArr = [{
id: 3,
licences: 100
new_value_pr_licence: 40
}, {
id: 4,
licences: 200
new_value_pr_licence: 25
}]
A user wish to buy 150 licences. This means that they fall into the category 100 because they are above 100 licences but below 200 which means they pay $40 per licence.
Note that the array object values varies.
Order your plans by the price per licence:
myArr.sort(function (a, b) {
return a.new_value_pr_licence - b.new_value_pr_licence;
})
then starting from the start of the array, take as many of that plan as you can without going over the number the user wants to buy:
var numUserWants = 150;
var purchases = {};
var cheapestAvailableProduct = myArr.shift();
while (numUserWants > 0 && cheapestAvailableProduct) {
if (numUserWants <= cheapestAvailableProduct.licences) {
purchases[cheapestAvailableProduct.id] = Math.floor(cheapestAvailableProduct.licences / numUserWants);
numUserWants = cheapestAvailableProduct.licences % numUserWants;
}
cheapestAvailableProduct = myArr.shift();
}
At this point, purchases will now be a map of plan id to number:
purchases => {
3: 3
4: 1
}
This doesn't handle the case where over-purchasing is the cheapest option (eg: it's cheaper to buy 160 at 4x40, instead of 150 at 3x40 + 1x25 + 1x5), but it's probably a good start for you to tweaking.
Just a simple forEach here. Take the number requested, begin calculating/mutating total based on option limits, and once the number requested is less than the option limit you have your final total, which wont be mutated any longer and returned from the function.
function calculateDiscountedTotal(numberRequested, myArr){
var total;
// loop, compare, calculate
myArr.forEach(function(option) {
if(numberRequested >= option.licenses){
total = numberRequested * option.new_value_pr_licence
}
}
if(total != undefined){
return total;
} else {
// user never had enough for initial discount
return "no discount price";
}
}
Sort the array first in terms of number of licenses and then get the object in which number of licenses is less than number of licenses to be bought (just less than the next item in the array which is greater than number of licenses to be bought)
var myArr = [
{
id: 3,
licences: 100
new_value_pr_licence: 40,
},
{
id: 4,
licences: 200,
new_value_pr_licence: 25
},
];
var numOfLic = 150;
myArr.sort( function(a,b){ return a.licences - b.licences } );
var selectedObj = myArr.reduce( function(prev,current){
if ( current.licences > numOfLic )
{
return prev;
}
});
console.log ( "pricing should be " + ( selectedObj.new_value_pr_licence * numOfLic ) );

Making a random number that's a multiple of 10

I'm looking to create a random number between two ranges that is a multiple of 10.
For example, if I fed the function the parameters 0, 100 it would return one of these numbers:
0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100
but nothing like 63 or 55.
And yes I'm aware this defeats the point of true "randomness", but I just need a quick easy way to get a number that's a multiple of 10 between two ranges.
Thanks. :)
I guess it can help:
var randomnumber=Math.floor(Math.random()*11)*10
it's just one line:
function rand_10(min, max){
return Math.round((Math.random()*(max-min)+min)/10)*10;
}
var a = 67;
var b = 124;
var lo = a + 10 - (a % 10)
var hi = b - (b % 10)
var r = lo + 10 * parseInt(Math.random() * ((hi - lo)/10 + 1));
function rand(maxNum, factorial) {
return Math.floor(Math.floor(Math.random() * (maxNum + factorial)) / factorial) * factorial;
};
Takes two parameter
maxNum Maximum number to be generated in random
factorial The factorial/incremental number
multiplies the random number generated to the maxNum.
Rounds down the result.
Divides by the factorial.
Rounds down the result.
then multiplies again by the factorial.
Use a normal random number function like this one:
function GetRandom( min, max ) {
if( min > max ) {
return( -1 );
}
if( min == max ) {
return( min );
}
return( min + parseInt( Math.random() * ( max-min+1 ) ) );
}
As this will only return integers ("multiples of 1"), you can multiply by 10 and get only multiples of 10.
randomNumberMultipleOfTen = GetRandom(0,10) * 10;
Of course you can merge both into one function if you want to, I'll leave this as an exercise to you.
This seems to do the work
Math.floor(Math.random() * 10) * 10
If you modify that a little you can easily make it between any two numbers.
Take the difference of the two parameters.
Divide the difference by 10.
Generate a random number from 0 to the result of the division.
Multiply that by 10.

Categories

Resources