This question already has answers here:
How can I pad a value with leading zeros?
(76 answers)
Closed 12 days ago.
I want to output 0 to 999 (but I need to display 0 like 000).
it seems like this.
000, 001, 002, 003 ... 300, 301, 302... 997, 998, 999
Please try to create this number with a given number 'N'.
if N = 5,
func(5) = [00000, 00001, ... 99997, 99998, 99999]
Since it's for a blockchain, I need to deal with Big Numbers.
0000 it should be string, because to avoid number limitation
I tried to get this using like this.
for (let i = 0; i<10;i++){
for (let j = 0; j<10; j++) {
for (let k = 0; k<10; k++){
console.log(`${i}${j}${k}`);
}
}
}
If you need to print from 00000 to 99999, do you have to use for 5 times in this case?
Is there any other way?
Yes, you can use padStart
If N is the max number to reach
const N = 1000;
const stringLength = (N - 1).toString().length;
for (let i = 0; i < N; i++) {
const paddedString = i
.toString()
.padStart(stringLength, '0');
console.log(paddedString);
}
If N is the number of digits the numbers should have
const N = 4;
// create the max number with N digits;
const maxNumber = BigInt(''.padStart(N, '9'));
for (let i = 0n; i <= maxNumber; i++) {
const paddedString = i
.toString()
.padStart(N, '0');
console.log(paddedString);
}
Related
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
In response I want all 3 digit numbers whose sum is 11 and also gives module 1 and
also want to know how can I push 000 in array in js.
For example number = 128, sum = 11 and module(remainder) = 1.
Like this I want all that numbers in array.
Can anyone share the logic for the same.
Thanx in advance.
I'm not sure what the second check is supposed to be (the modulus of something has to be 1). If that is supposed to be that the modulus of all digits of the number has to be 1, here is how you could do it:
var results = [];
for (let i = 1; i < 10; i++) {
for (let j = 0; j < 10; j++) {
for (let k = 0; k < 10; k++) {
if (i + j + k === 11 && i % j % k === 1) {
results.push(i.toString() + j.toString() + k.toString());
}
}
}
}
console.log(results);
OR:
var results = [];
for (let i = 100; i < 1000; i++) {
const [one, two, three] = i.toString().split('').map(i => +i);
if (one + two + three === 11 && one % two % three === 1) {
results.push(i.toString());
}
}
console.log(results);
Basically just go through all the possible combination and do the checks on each number.
Is this what you want?
var arr=[1,128,15];
var remainder = 127;
var result = arr.filter(function(i) {
var str=i.toString().split('');
var sum=0;
str.forEach(function(c) { return sum+=Number(c); });
return sum===11 && (i%remainder)===1;
});
and more fancy and ES6:
const arr=[1,128,15];
const remainder = 127;
const result = arr.filter(i=>{
const sum=i.toString().split('').reduce((s,v)=>(+v)+s,0);
return sum===11 && (i%remainder)===1;
});
You could take a brute force approach and check the sum with eleven. A check with the remainder is not necessary, because 11 has always a rest of one, if divided by ten.
const
getSum = v => [...v.toString()].reduce((a, b) => a + +b, 0),
values = [];
for (let i = 1; i < 1000; i++) {
if (getSum(i) === 11) values.push(i);
}
console.log(values);
.as-console-wrapper { max-height: 100% !important; top: 0; }
I'm trying to calculate the number of rolls of material that I could have if I cut a bigger size roll into multiple size smaller rolls.
For instance, if I have 1 25m roll I could cut that into 1 15m roll, 2 10m rolls and have 5 5m rolls. So I would want my quantities to look like:
1 25m
1 15m
2 10m
5 5m
Now, I could also have existing quantities of any of the other ones like 1 roll 25m, 1 roll 15m and 1 roll 5m. Then it would look like:
1 25m
2 15m
3 10m
9 5m
for (let i = 0; i < this.sizes.length; i++) {
const size = this.sizes[i];
for (let j = 0; j < this.cart.items.length; j++) {
const item = this.cart.items[j];
if (item.sizeId === size.id) {
size.quantity -= item.quantity;
}
size.amountOfMaterial = size.quantity * size.length;
}
}
I setup the first loop to get the correct quantity and amount of material based on what's already in their cart. I'm stuck on the next part.
Edit: The answer below eventually allowed me to come up with this:
calculateQuantities() {
let quantities = {};
for (let i = 0; i < this.sizes.length; i++) {
const size = this.sizes[i];
for (let j = 0; j < this.cart.items.length; j++) {
const item = this.cart.items[j];
if (item.sizeId === size.id) {
size.quantity -= item.quantity;
}
}
size.actualQuantity = size.quantity;
let counter = 0;
for (let j = 0; j < this.sizes.length; j++) {
const otherSize = this.sizes[j];
counter += Math.floor(otherSize.length * otherSize.quantity / size.length)
}
console.log(`${counter} ${size.length}m`);
quantities[size.length] = counter;
}
for (let i = 0; i < this.sizes.length; i++) {
this.sizes[i].quantity = quantities[this.sizes[i].length];
}
}
If I misunderstood the question, please let me know where I went wrong.
I am assuming the 25, 15, 10 and 5 are predefined. Is this correct? I didnt see this specified in your question.
// Defined lengths
const lengths = [25, 15, 10, 5];
// Some example cart corresponding to how many of each length customer has (this is from your example)
const cart = {25: 1, 15: 1, 5: 1}
for (let length of lengths) {
//Check for each length in lengths array
let counter = 0;
for (let item in cart) {
// Add the counter if there is enough in cart
counter += Math.floor(item * cart[item] / length);
}
// I am console logging like you showed, but you can do whatever
console.log(`${counter} ${length}m`)
}
Output:
1 25m
2 15m
3 10m
9 5m
How can I find the number of multiple for N numbers(as an array input) for a range 1 to K, where 1 < K < 10⁸ and 3 ≤ N < 25.
function findNumberOfMultiples(inputArray, maxSize) {
var count = 0;
var tempArray = [];
for (var i=0; i<maxSize; i++){
tempArray[i] = 0;
}
for (var j=0; j<inputArray.length; j++) {
for (var i=1; i<=maxSize; i++) {
if (i % inputArray[j]) {
tempArray[i-1] = 1;
}
}
}
for (var i=0; i<maxSize; i++) {
if (tempArray[i]==1) {
count++;
}
}
return count;
}
The above program fails for large number K. For example, if inputArray = [2,3,4] and maxSize(k) is 5,
Multiple of 2 is 2,4
Multiple of 3 is 3
multiple of 4 is 4
so total number of mutiple of 2 or 3 or 4 is 3 in range 1 to 5
You can solve this in O(N^2) where N is the number of elements in your array.
let us say you have two element in your array [a1,a2] and the range is K
your answer will be = >
K/a1 + K/a2 - K/lcm(a1,a2) // because you added them in both a1 and a2
So If you have a1,.....ax elements, your answer would be
K/a1+.....K/ax - K/lcm(ai,aj) (you have to replace i,j by (n*n-1)/2 combinations.
You will have to do K/lcm(ai,aj) O(N^2) times ((n*n-1)/2 time to be precise). So the algorithm complexity will be O(N^2) (There will be a Log(min(ai,aj)) factor but that would not make much difference to the overall complexity).
This will work any K as it only depends on your innput array size.
public int combinations(int K, int[] input){
int total = 0;
for(int i=0;i<input.length;i++){
total = total + Math.floor(K/input[i]);
}
for(int i=0;i<input.length;i++){
for(int j=i+1;j<input.length;j++){
if(i!=j){
int lcm =lcmFind(input[i], input[j]);
total = total - Math.floor(K/lcm);
}
}
}
return total;
}
The test case you have provided:
This function seems to do the trick :
var findMultiplesLength = function(arrayInput, max) {
var globalMultiples = [];
for (var j = 0; j < arrayInput.length; j++) {
var x = arrayInput[j];
var n = max / x;
for (var i=1; i < n; i++) {
mult = i * x;
if (globalMultiples.indexOf(mult) === -1) {
globalMultiples.push(mult);
}
}
}
return globalMultiples.length;
};
EDIT : You won't have any stack error but choosing big values for the range may hang your browser.
In JavaScript, is there a more efficient way of calculating perfect squares working from odd numbers than this (the last perfect square stored in the array perfectSqrs is console.logged):
let n = 999,
oddNums = [],
i;
for (i = 3; i < n; i += 1) {
if (i % 2 !== 0) {
oddNums.push(i);
}
}
let oddLength = oddNums.length;
let perfectSqrs = [1],
j = 0;
while (j < oddLength - 1) {
perfectSqrs[j + 1] = perfectSqrs[j] + oddNums[j];
j += 1;
}
console.log(perfectSqrs[perfectSqrs.length - 1]);
Looks like you just want to generate an array of perfect squares? Perhaps you can do something like this:
var squares = [1];
var numSquares = 100;
for (var i=3; i<numSquares*2; i+=2) {
squares.push(squares[squares.length - 1] + i);
}
console.log(squares);
For people unclear about this algorithm, basically:
1
4 (1+3)
9 (1+3+5)
16 (1+3+5+7)
25 (1+3+5+7+9)
Perfect square is essentially the sum of odd numbers
Nothing to do with JS more with algorithms and logic. You can totally avoid the first loop and also avoid storing (memory efficiency) odd numbers. Start your second loop with 1 and iterate by incrementing by 2 instead of 1 (1,3,5,7,...).
Let's say you have an array of length 20. You want to access 3 equally spaced indices: 0, 9, 19.
How can you do this with any length of array and any number of sections?
I feel like there must be an elegant way of doing it, but the only way I can think of is finding the section size (var len = 20 / (3 -1)), iterating over the total number of sections (for (var i = 0; i < 3; i++) { var row = data[len * i]; }), and then subtracting one for non-zero indices.
You could try something like this (where console.log is used now you can call your array):
var amount = 3;
var total = 20;
var size = (total - 1) / (amount - 1);
for(var i = 0; i < amount; i++) {
console.log(Math.floor(size * i));
}
There isn't realy a more elegant solution.