Adding elements in an array every 12 items - javascript

How would you best turn [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1] into [12,12]
Basically reducing an array into an aggregate every 12 items.
This is my not so elegant attempt:
let arr = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1];
let result = 0;
let finalArr = [];
arr.forEach((item,index) => {
result += item;
if((index+1) % 12 === 0) {
finalArr.push(result)
result = 0
}
})
Can this be done a bit more elegantly? Perhaps using reduce()? I haven't used js in a while so I am a bit rusty! Thanks in advance.

function reduceGroupByN(arr, count, fn) {
const out = []
if (count <= 1) throw new Error("Grouping must be greater than 1")
for (var last = 0; last < arr.length; last += count) {
out.push(arr.slice(last, last + count).reduce(fn))
}
return out
}
const arr = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]
const result = reduceGroupByN(arr, 12, (a, b) => a + b)

For a more general solution, consider using a function that chunks an array into slices. (This sort of utility function is relatively common already.) Then call that function and add up the resulting subarrays with .map:
const arr = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1];
const chunk = (arr, length) => arr.reduce((a, num, i) => {
const chunkIndex = Math.floor(i / length);
if (!a[chunkIndex]) {
a[chunkIndex] = [];
}
a[chunkIndex].push(num);
return a;
}, []);
const finalArr = chunk(arr, 12)
.map(
subarr => subarr.reduce((a, b) => a + b)
);
console.log(finalArr);

At the risk of angering the modern JS gods, there is still something to be said for the performance and simplicity of a classic solution.
On my machine this runs two to three times faster compared to the other answers.
let arr =[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1];
let finalArr=[]
let chunkSize=12
for (n=0; n < arr.length;)
{
for( result=0, m=0; m < chunkSize; m++, n++)
{
result+=arr[n]
}
finalArr.push(result)
}
console.log(finalArr)

Related

Find all the Subarrays in O(nlog(n)) time complexity JavaScript

how to get all the subarrays in O(nlog(n)) time complexity using javaScript
I try with a nested loop but the time complexity is in O(n*n). I heard about some prefix solutions but have no information
try this code :
fetechArray = (array) => {
for ( let subarray of array ){
// ur code here
fetechArray(subarray);
}
}
Use the "divide & conquer" approach. You first divide the original array into two halves, then combine the results from both halves to get all subarrays.
function subArrays(arr) {
if (arr.length === 1) {
return [arr];
}
const mid = Math.floor(arr.length / 2);
const left = arr.slice(0, mid);
const right = arr.slice(mid);
const leftSubArrays = subArrays(left);
const rightSubArrays = subArrays(right);
return merge(leftSubArrays, rightSubArrays);
}
function merge(left, right) {
const result = [];
for (let i = 0; i < left.length; i++) {
for (let j = 0; j < right.length; j++) {
result.push(left[i].concat(right[j]));
}
}
return result;
}

Algorithm to find all possible arrays of max size L that sum up to N or less

I want to find all possible arrays -of non-negative numbers- that sum up to -at most- N in JavaScript:
function findArrays(maxSize, maxSum){}
Example input: findArrays(3, 10)
Some acceptable outputs: (not writing all as it would be too long)
[[0], [0,0,0], [10,0,0], [1,9], [1,2,3] /*, ... */]
What I tried so far:
I know it looks like homework but it's not :) I can think of a solution that simply generates all (size*maxSum) possible arrays of acceptable sizes and then iterate through them to check if sum is greater than maxSum. However, I think this solution is very bad in terms of performance as maxSum gets bigger. I'm looking for a more efficient implementation but I just don't know where to start.
My "bad" solution
function getNextArray(r,maxVal){
for(var i=r.length-1;i>=0;i--){
if(r[i]<maxVal){
r[i]++;
if(i<r.length-1){
r[i+1]=0;
}
break;
}
}
return r;
}
function getAllArraysOfSize(size, maxVal){
var arrays=[],r=[],i;
for(i=0;i<size;i++){
r[i]=0;
}
while(r.reduce((a, b) => a + b, 0) < (maxVal*size)){
r = getNextArray(r.slice(),maxVal);
arrays.push(r);
}
return arrays;
};
function findArrays(maxSize, maxSum){
var allArrays=[],arraysOfFixedSize=[],acceptableArrays=[],i,j;
for(i=1; i<=maxSize; i++){
arraysOfFixedSize=getAllArraysOfSize(i,maxSum);
for(j=0; j<arraysOfFixedSize.length; j++){
allArrays.push(arraysOfFixedSize[j]);
}
}
for(i=0; i<allArrays.length; i++){
if(allArrays[i].reduce((a, b) => a + b, 0) <= maxSum){
acceptableArrays.push(allArrays[i]);
}
}
return acceptableArrays;
};
You can use recursion and a generator. The number of outputs grows quickly for higher valued arguments, so I keep them low here:
function * findArrays(maxSize, maxSum) {
let arr = [];
function * recur(maxSum) {
let k = arr.length;
yield [...arr]; // or: if (k) yield [...arr]
if (k === maxSize) return;
for (let i = 0; i <= maxSum; i++) {
arr[k] = i;
yield * recur(maxSum - i);
}
arr.length = k;
}
yield * recur(maxSum);
}
// demo
for (let arr of findArrays(2, 4))
console.log(JSON.stringify(arr));
NB: this also produces the empty array, which makes sense. If you want to avoid this, then just check that you don't yield an empty array.
If you prefer working with plain functions instead of generators, then translate the innermost yield expression to a push unto a result array, as follows:
function findArrays(maxSize, maxSum) {
let arr = [];
let result = []; // <--- will collect all the subarrays
function recur(maxSum) {
let k = arr.length;
result.push([...arr]);
if (k === maxSize) return;
for (let i = 0; i <= maxSum; i++) {
arr[k] = i;
recur(maxSum - i);
}
arr.length = k;
}
recur(maxSum);
return result;
}
// demo
for (let arr of findArrays(2, 4))
console.log(JSON.stringify(arr));
i hope this is helpful
const data = [[0],[0,0,0],[10,0,0],[1,9],[1,2,3]];
function findArrays(maxSize, maxSum){
return data.reduce(
(acc, value) => {
if (value.length <= maxSize) {
const tempValue = value;
const sum = tempValue.reduce((acc, val) => val >= 0 ? acc + val : 0, 0);
if (sum <= maxSum && sum > 0) acc.push(value);
}
return acc
}, []
)
}
console.log(findArrays(3, 10));

How do i compare with the rest of the elements in the array

I am working on a leetcode question and I cant quite think of a way to compare the rest of the elements in the array with one another. I figured out for the biggest and smallest numbers but to compare with the rest of them is something I am having trouble with. Below you will find the question and my work with it:
How Many Numbers Are Smaller Than the Current Number?
Given the array nums, for each nums[i] find out how many numbers in the array are smaller than it. That is, for each nums[i] you have to count the number of valid j's such that j != i and nums[j] < nums[i].
Return the answer in an array.
Example 1:
Input: nums = [8,1,2,2,3]
Output: [4,0,1,1,3]
Explanation:
For nums[0]=8 there exist four smaller numbers than it (1, 2, 2 and 3).
For nums[1]=1 does not exist any smaller number than it.
For nums[2]=2 there exist one smaller number than it (1).
For nums[3]=2 there exist one smaller number than it (1).
For nums[4]=3 there exist three smaller numbers than it (1, 2 and 2).
My work:
var smallerNumbersThanCurrent = (nums) => {
const output = []
const max = nums.reduce(function(a, b) {
return Math.max(a, b);
});
const min = nums.reduce(function(a, b) {
return Math.min(a, b);
});
for(let i = 0; i < nums.length; i++){
if(nums[i] === max){
output.push(nums.length - 1)
} else if (nums[i] === min){
output.push(0)
}
else if (nums[i] < max && nums[i] > min){
//how do i compare with rest of the elements in the array?
}
}
}
Use a nested loop.
nums = [8,1,2,2,3];
answer = [];
for (let i = 0; i < nums.length; i++) {
let count = 0;
for (let j = 0; j < nums.length; j++) {
if (nums[j] < nums[i]) {
count++;
}
}
answer.push(count);
console.log(`For nums[${i}]=${nums[i]} there are ${count} lower numbers`);
}
console.log(`Answer: ${answer}`);
It's not necessary to test i != j since a number will never be lower than itself.
A much easier way would be to simply sort the array, and then the index of the element will tell you how many are less than it:
const nums = [8,1,2,2,3]
const sorted = [...nums].sort();
const result = nums.map((i) => {
return sorted.findIndex(s => s === i);
});
console.log(result);
This has the added benefit that you don't have to search the entire array for each number.
I'd do like:
function rankZero(array){
const s = [...array], r = [];
s.sort((a, b)=>{
return a - b;
});
for(let n of array){
r.push(s.indexOf(n));
}
return r;
}
console.log(rankZero([8, 1, 2, 2, 3]));
One way to do this is to filter the array on the condition that the value is less than the current one and then count the number of values in the filtered array:
const nums = [8,1,2,2,3];
const smallerNums = nums.map(v => nums.filter(n => n < v).length);
console.log(smallerNums); // [4,0,1,1,3]
Alternatively you can do a count in reduce, which should be significantly faster:
const nums = [8, 1, 2, 2, 3];
const smallerNums = nums.map(v => nums.reduce((c, n) => c += (n < v), 0));
console.log(smallerNums); // [4,0,1,1,3]
Inspired by #tao I did performance testing of each solution. On my computer (an Intel Core I9-9900 with 64GB RAM) #StackSlave's solution is consistently the fastest, followed by the other sorting solution, the reduce solution, the basic iteration and the filter. You can run the tests yourself below:
const datalength = 1000;
const iterations = 100;
const getRandom = (min, max) => Math.random() * (max - min) + min;
const data = Array.from({
length: datalength
}, () => getRandom(1, 100));
const mapper = arr => arr.map(i => arr.filter(n => n < i).length);
const sorter = nums => {
const sorted = [...nums].sort();
const result = nums.map((i) => {
return sorted.findIndex(s => s === i);
});
};
const iterator = arr => {
const answer = [];
for (let i = 0; i < arr.length; i++) {
let count = 0;
for (let j = 0; j < arr.length; j++) {
if (arr[j] < arr[i]) {
count++;
}
}
answer.push(count);
}
return answer;
};
const rankZero = array => {
const s = [...array],
r = [];
s.sort((a, b) => {
return a - b;
});
for (let n of array) {
r.push(s.indexOf(n));
}
return r;
}
const reducer = arr => arr.map(v => arr.reduce((c, n) => c += (n < v), 0));
let fns = {
'iterator': iterator,
'mapper': mapper,
'sorter': sorter,
'reducer': reducer,
'rankZero': rankZero
}
for (let [name, fn] of Object.entries(fns)) {
let total = 0;
for (i = 0; i < iterations; i++) {
let t0 = performance.now();
fn(data);
let t1 = performance.now();
total += t1 - t0;
}
console.log(name, (total / iterations).toFixed(2));
}

How to split an array into even length chunks? [duplicate]

This question already has answers here:
Splitting a JS array into N arrays
(23 answers)
Closed 3 years ago.
I want to split an array in even (or as even as possible) chunks.
The input of the function should be the array and the size of the chunks.
Say you have the array
[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17]
If you put it in the function below, with 5 as chunk size, it will result in the following
[[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15],[16,17]
However, I want the result to be
[[1,2,3,4,5],[6,7,8,9],[10,11,12,13],[14,15,16,17]
Which means sacrificing the length of the arrays before to make them only differ one in length.
The function I'm currently using is stated below. I've tried various things with modulo but I can't figure it out.
function chunkArray(myArray, chunkSize){
var arrayLength = myArray.length;
var tempArray = [];
for (index = 0; index < arrayLength; index += chunkSize) {
myChunk = myArray.slice(index, index+chunkSize);
// Do something if you want with the group
tempArray.push(myChunk);
}
return tempArray;
}
With this solution you get evenly split array items until the last item which incorporates any left over items (collection of items that's length is less than the chunk size.)
const a = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17]
const chunk = 4
const chunk_array = (a, c) => {
let arr = []
a.forEach((_, i) => {
if (i%chunk === 0) arr.push(a.slice(i, i+chunk))
})
const [left_overs] = arr.filter(a => a.length < chunk)
arr = arr.filter(a => a.length >= chunk)
arr[arr.length-1] = [...arr[arr.length-1], ...left_overs]
return arr
}
console.log(
chunk_array(a, chunk)
)
My solution!
const chunk = (arr, chunkSize) => {
let chunked = [];
for (let i = 0; i< arr.length; i+=chunkSize){
chunked.push(
arr.slice(i, (i + chunkSize))
);
}
return chunked;
};
const data = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17];
console.log(chunk(data, 5));
// returns [[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15],[16,17]]
You could check with a modulo if your array length is odd :
let MY_CHUNK_CONST = 5
let first_chunk_size = MY_CHUNK_CONST,
other_chunk_size = MY_CHUNK_CONST;
let myArray = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17];
modulo_res = myArray.length % 2; // 0 if even 1 if odd
if(modulo_res){
other_chunk_size = first_chunk_size - 1;
}
var tempArray = [];
myChunk = myArray.slice(0, 0+first_chunk_size);
tempArray.push(myChunk);
for (index = 1; index < myArray.length; index += other_chunk_size) {
myChunk = myArray.slice(index, index+other_chunk_size);
// Do something if you want with the group
tempArray.push(myChunk);
}
console.log(tempArray)
// [[1,2,3,4,5],[6,7,8,9],[10,11,12,13],[14,15,16,17]
Hope it helps.

JavaScript - Generating combinations from n arrays with m elements [duplicate]

This question already has answers here:
Cartesian product of multiple arrays in JavaScript
(35 answers)
Closed 1 year ago.
I'm having trouble coming up with code to generate combinations from n number of arrays with m number of elements in them, in JavaScript. I've seen similar questions about this for other languages, but the answers incorporate syntactic or library magic that I'm unsure how to translate.
Consider this data:
[[0,1], [0,1,2,3], [0,1,2]]
3 arrays, with a different number of elements in them. What I want to do is get all combinations by combining an item from each array.
For example:
0,0,0 // item 0 from array 0, item 0 from array 1, item 0 from array 2
0,0,1
0,0,2
0,1,0
0,1,1
0,1,2
0,2,0
0,2,1
0,2,2
And so on.
If the number of arrays were fixed, it would be easy to make a hard coded implementation. But the number of arrays may vary:
[[0,1], [0,1]]
[[0,1,3,4], [0,1], [0], [0,1]]
Any help would be much appreciated.
Here is a quite simple and short one using a recursive helper function:
function cartesian(...args) {
var r = [], max = args.length-1;
function helper(arr, i) {
for (var j=0, l=args[i].length; j<l; j++) {
var a = arr.slice(0); // clone arr
a.push(args[i][j]);
if (i==max)
r.push(a);
else
helper(a, i+1);
}
}
helper([], 0);
return r;
}
Usage:
cartesian([0,1], [0,1,2,3], [0,1,2]);
To make the function take an array of arrays, just change the signature to function cartesian(args) instead of using rest parameter syntax.
I suggest a simple recursive generator function:
// JS
function* cartesianIterator(head, ...tail) {
const remainder = tail.length ? cartesianIterator(...tail) : [[]];
for (let r of remainder) for (let h of head) yield [h, ...r];
}
// get values:
const cartesian = items => [...cartesianIterator(items)];
console.log(cartesian(input));
// TS
function* cartesianIterator<T>(items: T[][]): Generator<T[]> {
const remainder = items.length > 1 ? cartesianIterator(items.slice(1)) : [[]];
for (let r of remainder) for (let h of items.at(0)!) yield [h, ...r];
}
// get values:
const cartesian = <T>(items: T[][]) => [...cartesianIterator(items)];
console.log(cartesian(input));
You could take an iterative approach by building sub arrays.
var parts = [[0, 1], [0, 1, 2, 3], [0, 1, 2]],
result = parts.reduce((a, b) => a.reduce((r, v) => r.concat(b.map(w => [].concat(v, w))), []));
console.log(result.map(a => a.join(', ')));
.as-console-wrapper { max-height: 100% !important; top: 0; }
After doing a little research I discovered a previous related question:
Finding All Combinations of JavaScript array values
I've adapted some of the code from there so that it returns an array of arrays containing all of the permutations:
function(arraysToCombine) {
var divisors = [];
for (var i = arraysToCombine.length - 1; i >= 0; i--) {
divisors[i] = divisors[i + 1] ? divisors[i + 1] * arraysToCombine[i + 1].length : 1;
}
function getPermutation(n, arraysToCombine) {
var result = [],
curArray;
for (var i = 0; i < arraysToCombine.length; i++) {
curArray = arraysToCombine[i];
result.push(curArray[Math.floor(n / divisors[i]) % curArray.length]);
}
return result;
}
var numPerms = arraysToCombine[0].length;
for(var i = 1; i < arraysToCombine.length; i++) {
numPerms *= arraysToCombine[i].length;
}
var combinations = [];
for(var i = 0; i < numPerms; i++) {
combinations.push(getPermutation(i, arraysToCombine));
}
return combinations;
}
I've put a working copy at http://jsfiddle.net/7EakX/ that takes the array you gave earlier ([[0,1], [0,1,2,3], [0,1,2]]) and outputs the result to the browser console.
const charSet = [["A", "B"],["C", "D", "E"],["F", "G", "H", "I"]];
console.log(charSet.reduce((a,b)=>a.flatMap(x=>b.map(y=>x+y)),['']))
Just for fun, here's a more functional variant of the solution in my first answer:
function cartesian() {
var r = [], args = Array.from(arguments);
args.reduceRight(function(cont, factor, i) {
return function(arr) {
for (var j=0, l=factor.length; j<l; j++) {
var a = arr.slice(); // clone arr
a[i] = factor[j];
cont(a);
}
};
}, Array.prototype.push.bind(r))(new Array(args.length));
return r;
}
Alternative, for full speed we can dynamically compile our own loops:
function cartesian() {
return (cartesian.cache[arguments.length] || cartesian.compile(arguments.length)).apply(null, arguments);
}
cartesian.cache = [];
cartesian.compile = function compile(n) {
var args = [],
indent = "",
up = "",
down = "";
for (var i=0; i<n; i++) {
var arr = "$"+String.fromCharCode(97+i),
ind = String.fromCharCode(105+i);
args.push(arr);
up += indent+"for (var "+ind+"=0, l"+arr+"="+arr+".length; "+ind+"<l"+arr+"; "+ind+"++) {\n";
down = indent+"}\n"+down;
indent += " ";
up += indent+"arr["+i+"] = "+arr+"["+ind+"];\n";
}
var body = "var res=[],\n arr=[];\n"+up+indent+"res.push(arr.slice());\n"+down+"return res;";
return cartesian.cache[n] = new Function(args, body);
}
var f = function(arr){
if(typeof arr !== 'object'){
return false;
}
arr = arr.filter(function(elem){ return (elem !== null); }); // remove empty elements - make sure length is correct
var len = arr.length;
var nextPerm = function(){ // increase the counter(s)
var i = 0;
while(i < len)
{
arr[i].counter++;
if(arr[i].counter >= arr[i].length){
arr[i].counter = 0;
i++;
}else{
return false;
}
}
return true;
};
var getPerm = function(){ // get the current permutation
var perm_arr = [];
for(var i = 0; i < len; i++)
{
perm_arr.push(arr[i][arr[i].counter]);
}
return perm_arr;
};
var new_arr = [];
for(var i = 0; i < len; i++) // set up a counter property inside the arrays
{
arr[i].counter = 0;
}
while(true)
{
new_arr.push(getPerm()); // add current permutation to the new array
if(nextPerm() === true){ // get next permutation, if returns true, we got them all
break;
}
}
return new_arr;
};
Here's another way of doing it. I treat the indices of all of the arrays like a number whose digits are all different bases (like time and dates), using the length of the array as the radix.
So, using your first set of data, the first digit is base 2, the second is base 4, and the third is base 3. The counter starts 000, then goes 001, 002, then 010. The digits correspond to indices in the arrays, and since order is preserved, this is no problem.
I have a fiddle with it working here: http://jsfiddle.net/Rykus0/DS9Ea/1/
and here is the code:
// Arbitrary base x number class
var BaseX = function(initRadix){
this.radix = initRadix ? initRadix : 1;
this.value = 0;
this.increment = function(){
return( (this.value = (this.value + 1) % this.radix) === 0);
}
}
function combinations(input){
var output = [], // Array containing the resulting combinations
counters = [], // Array of counters corresponding to our input arrays
remainder = false, // Did adding one cause the previous digit to rollover?
temp; // Holds one combination to be pushed into the output array
// Initialize the counters
for( var i = input.length-1; i >= 0; i-- ){
counters.unshift(new BaseX(input[i].length));
}
// Get all possible combinations
// Loop through until the first counter rolls over
while( !remainder ){
temp = []; // Reset the temporary value collection array
remainder = true; // Always increment the last array counter
// Process each of the arrays
for( i = input.length-1; i >= 0; i-- ){
temp.unshift(input[i][counters[i].value]); // Add this array's value to the result
// If the counter to the right rolled over, increment this one.
if( remainder ){
remainder = counters[i].increment();
}
}
output.push(temp); // Collect the results.
}
return output;
}
// Input is an array of arrays
console.log(combinations([[0,1], [0,1,2,3], [0,1,2]]));
You can use a recursive function to get all combinations
const charSet = [["A", "B"],["C", "D", "E"],["F", "G", "H", "I"]];
let loopOver = (arr, str = '', final = []) => {
if (arr.length > 1) {
arr[0].forEach(v => loopOver(arr.slice(1), str + v, final))
} else {
arr[0].forEach(v => final.push(str + v))
}
return final
}
console.log(loopOver(charSet))
This code can still be shorten using ternary but i prefer the first version for readability 😊
const charSet = [["A", "B"],["C", "D", "E"],["F", "G", "H", "I"]];
let loopOver = (arr, str = '') => arr[0].map(v => arr.length > 1 ? loopOver(arr.slice(1), str + v) : str + v).flat()
console.log(loopOver(charSet))
Another implementation with ES6 recursive style
Array.prototype.cartesian = function(a,...as){
return a ? this.reduce((p,c) => (p.push(...a.cartesian(...as).map(e => as.length ? [c,...e] : [c,e])),p),[])
: this;
};
console.log(JSON.stringify([0,1].cartesian([0,1,2,3], [[0],[1],[2]])));

Categories