How can I programatically calculate quantities based on length of material? - javascript

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

Related

How to get result from 000~999 [duplicate]

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);
}

Construct 2/3: Continuous Loop Function?

Using Construct 3 to build a game.
I want to change this function in the code below (which just randomly assigns a frame count in an array) to something that isn't random, but instead loops in order from indexes 0 to 10 and then back to 0 and then to 10 in order again and loop like that continuously.
random(1,Self.AnimationFrameCount)
Is there a random() equivalent for non-random?
// generator function - yields multiple times, maybe forever
function* oneToTenAndBack(N: number): Generator<number> {
while(true) {
for (let i = 0; i < N; i++) yield i;
for (let j = N; j > 0; j--) yield j;
}
}
let k = 0;
for (let num of oneToTenAndBack(4)) {
console.log(num) // 0 1 2 3 4 3 2 1 0 1 2
if (++k>10) break;
}
let gen = oneToTenAndBack(3);
for (let k = 0; k < 10; k++)
console.log(gen.next()) // {value: number, done: false}
Playground Link

Print sequence of numbers in javascript

I'm sure this is quite a simple programming question however, I cant seem to understand it...
I'm trying to make the console.log print out numbers like this - 1 1 1 1 2 2 2 2 3 3 3 3 4 4 4 4 - one for each line. I thought modulo could be used to make this happen, however, I cant seem to figure out how to use it.
Here is the code:
iteration = 16;
for (var i = 0; i < iteration; i++) {
if(i == iteration%4 )
console.log(i);
}
Yes, you need a single loop.
No, you do not need the remainder operator %. This would give you
0 1 2 3 0 1 2 3 ...
But instead you could divide the actual value by 4 and take the integer value for console.log.
const iteration = 16;
for (let i = 0; i < iteration; i++) {
console.log(Math.floor(i / 4) + 1); // offset for starting with 1
}
I suggest that you use two nested for loops, one for the rows and another one for the columns.
Here's an example of how i would do it:
const columns = 4;
const rows = 4;
//if you want to just console.log each number on a different line
for (let i = 1; i <= rows; i++) {
for (let j = 1; j <= columns; j++) {
console.log(i);
}
console.log("\n");
}
//if you want to add each number to an array, and then log the array
for (let i = 1; i <= rows; i++) {
let columnsArray = [];
columnsArray.length = columns;
columnsArray.fill(i);
console.log(columnsArray);
}
//if you want to just log the numbers, you can spread the array
for (let i = 1; i <= rows; i++) {
let columnsArray = [];
columnsArray.length = columns;
columnsArray.fill(i);
console.log(...columnsArray);
}
//or you could push the arrays in another one, and get a matrix!
const matrix = [];
for (let i = 1; i <= rows; i++) {
let columnsArray = [];
columnsArray.length = columns;
columnsArray.fill(i);
matrix.push(columnsArray);
}
console.log(matrix);
It was not clear the output that you wanted, so i got a little sidetracked and made an example for the different cases that came to my mind.

Find the multiple of n numbers within given range

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.

Get index of array at equal points

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.

Categories