Home > Software design >  For-loop, return N times X in given range
For-loop, return N times X in given range

Time:10-03

const array = [];

const times = 3;
const count = 5;

for (let i = 0; i < times * count * 2; i  ) {
  const a = i - (i % times);
  const b = a % count;
  array.push(b);
}

console.log(array);
// expected output [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 0, 0, 0 ...]

Hello guys, how can I get the expected result? I need to, use single loop, only math operators, find the value needs to be pushed with using only (i)ndex. Thank you.

CodePudding user response:

I think this is it, one loop, only math:

const array = [];

const times = 3;
const count = 5;

for (let i = 0; i < times * count * 2; i  ) {
  array.push(Math.abs(i % times - i) / times % count);
}

console.log(array);
// expected output [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 0, 0, 0 ...]

CodePudding user response:

There's a lot of ways to achieve the output you require. You could use two loops:

let array = [];
const times = 3;
const count = 5;

for (let i = 0; i < times * count * 2; i  ) {
  for (let n = 1; n <= times; n  ) {
    array.push(i % count);
  }
}

console.log(array);

Or alternatively you can use a single loop and use Array.fill() to populate a child array which you flatten before concatenating:

let array = [];
const times = 3;
const count = 5;

for (let i = 0; i < times * count * 2; i  ) {
  array = array.concat((new Array(times)).fill(i % count).flat());
}

console.log(array);

CodePudding user response:

You can compute the required value for each entry in the output using

Math.floor(i % (times*count) / times)

Here's a solution using a for loop and also a one-liner using Array.from:

const times = 3
const count = 5
const repeats = 2

function counter1(times, count, repeats) {
  const result = []
  for (i = 0; i < times * count * repeats; i  ) {
    result.push(Math.floor(i % (times * count) / times))
  }
  return result
}

console.log(counter1(times, count, repeats))

const counter2 = (times, count, repeats) =>
  Array.from({ length: times * count * repeats },
    (_, i) => Math.floor(i % (times * count) / times))

console.log(counter2(times, count, repeats))

CodePudding user response:

const array = [];

const times = 3;
const count = 5;

// it repeats everything 3 times
for (let i = 0; i < times; i  ) {
    // count from 0 to 4 // do 5 times
    // it repeat loop while but with increased value every time
    // 0,0,0
    // 1,1,1
    // 2,2,2
    // 3,3,3
    // 4,4,4
    for (let i2 = 0; i2 < count; i2  ) {
        // it push the same number while i3 is not equal to variable times
        // so 0 will be pushed 3 times 
        // 0,0,0
        let i3 = 0;
        while (i3 != times) {
            array.push(i2);
            i3  ;
        }
    }
}

console.log(array);
// expected output [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 0, 0, 0 ...]

CodePudding user response:

The simplest way to do this as destructuring the array .

let firstarray=[]
let array = [];

const times = 3;
const count = 5;

for (let i = 0; i < count ; i  ) {
    for(let j=0;j<times;j  ){
        firstarray.push(i)
    }
}
array=[...firstarray,...firstarray]
console.log(array)

CodePudding user response:

Note: This answer was started before last edit of question -- so no it's not a loop with a modulus %. It's a function that is Array-centric so with a slight modification can be used with other types as well.

I added an additional parameter: iterations which is the number of times the series of numbers should be repeated.

If @params were times = 3, count = 5, and iterations = 15

Working backwards since each set of arrays are blank:

[...Array(5)] // is ['','','','','']
.flatMap((_, i) => // will return the following for each ''...
Array(3).fill(i) // is [i, i, i]

result is [[0, 0, 0], [1, 1, 1], ...] returned as [0, 0, 0, 1, 1, 1,...] since .flatMap() flattens one level of arrays.

[...Array(15)] // is ['','','','','', '','','','','', '','','','','']
.flatMap(_ => // will return the previous array of 15 numbers for each '' 

Final return is 15 sub-arrays flattened to an array of 225 numbers in the desired pattern of:

[0, 0, 0, 1, 1, 1,... 4, 4, 4, /* 15 times */]

/**
 * Given a range 0 to a given number (count), repeat consecutively each number
 * within the range a given number of times (times). Repeat the process a given
 * number of times (iterations). 
 * @param {number} times - The number of repeats of each number ex. 0, 0, 0
 * @param {number} count - The total of numbers within a range starting from 0
 * @param {number} iterations - The total number of times the entire series
 * of numbers are repeated.
 * @return {array<number>} - An array of numbers in the following pattern
 * if times = 5, count = 5, and iterations = 15:
 *         [(0, 0, 0, 1, 1, 1,... 4, 4, 4) repeated 15 times]
 */
function repeatRange(times, count, iterations) {
  return [...Array(iterations)].flatMap(_ => [...Array(count)].flatMap((_, i) =>
    Array(times).fill(i)));
}

const t = 3;
const c = 5;
const i = 15;
console.log(JSON.stringify(repeatRange(t, c, i)));
.as-console-row::after { width: 0; font-size: 0; }
.as-console-row-code { width: 100%; word-break: break-word; }

  • Related