Related
I am learning Javascript and currently found myself with the following problem. I need to get each individual 3x3 block of a 9x9 2d array as a string, separated by commas.
What I mean is, for example, let's say I have the following array:
var 2dArray = [
[5, 3, 5, 6, 7, 8, 9, 1, 2],
[6, 7, 1, 1, 9, 5, 3, 4, 8],
[1, 9, 2, 3, 4, 2, 5, 6, 7],
[8, 5, 9, 7, 6, 1, 4, 2, 3],
[4, 2, 6, 5, 5, 3, 7, 9, 1],
[7, 1, 3, 1, 2, 4, 8, 5, 6],
[9, 6, 1, 5, 3, 7, 2, 8, 4],
[2, 8, 7, 5, 1, 9, 6, 3, 5],
[3, 4, 5, 6, 8, 6, 1, 7, 9] ]
The result should be something like 535671192,678195342, 912348657, ... and so on, until the string is made of all the 3x3 blocks.
I thought that making nested for loops would be the best approach, but got confused along the way and I would appreciate your help.
Thank you.
You can use two loops to iterate over the positions of all the possible top left corners and another two loops to get all the elements in that square.
var arr = [
[5, 3, 5, 6, 7, 8, 9, 1, 2],
[6, 7, 1, 1, 9, 5, 3, 4, 8],
[1, 9, 2, 3, 4, 2, 5, 6, 7],
[8, 5, 9, 7, 6, 1, 4, 2, 3],
[4, 2, 6, 5, 5, 3, 7, 9, 1],
[7, 1, 3, 1, 2, 4, 8, 5, 6],
[9, 6, 1, 5, 3, 7, 2, 8, 4],
[2, 8, 7, 5, 1, 9, 6, 3, 5],
[3, 4, 5, 6, 8, 6, 1, 7, 9]
];
let res = [];
for (let i = 0; i < 9; i += 3) {
for (let j = 0; j < 9; j += 3) {
let curr = "";
for (let k = 0; k < 3; k++) {
for (let l = 0; l < 3; l++) {
curr += arr[i + k][j + l];
}
}
res.push(curr);
}
}
console.log(res);
The issue can also be solved by loops but it's good practice to solve it using the Array.map() function.
let arrayRow = "";
const resultArray = Array2d.map((element, index) => {
return arrayRow + element.map((element, i) => {
return element.toString();
});
});
you should try like this too.
var arr = [
[5, 3, 5, 6, 7, 8, 9, 1, 2],
[6, 7, 1, 1, 9, 5, 3, 4, 8],
[1, 9, 2, 3, 4, 2, 5, 6, 7],
[8, 5, 9, 7, 6, 1, 4, 2, 3],
[4, 2, 6, 5, 5, 3, 7, 9, 1],
[7, 1, 3, 1, 2, 4, 8, 5, 6],
[9, 6, 1, 5, 3, 7, 2, 8, 4],
[2, 8, 7, 5, 1, 9, 6, 3, 5],
[3, 4, 5, 6, 8, 6, 1, 7, 9]
];
let res = [];
let i = 0,j = 0;
let justOneStr = "";
while(i < 9 && j < 9){
justOneStr += arr[i][j];
if(i % 3 == 2 && j % 3 == 2){
res.push(justOneStr);
justOneStr="";
}
if((j % 9 == 8 || j % 3 == 2) && i % 3 != 2){
j -= 3;
i += 1;
}
else if(j % 9 == 8 && i % 3 == 2){
j -= 9;
i += 1;
}
else if(i % 3 == 2 && j % 3 == 2){
i -= 2;
}
j++;
}
console.log(res);
Here's a fairly straightforward nested reduce() that returns an array of matrices of the specified size. It touches each element once, and uses the coordinates in the passed matrix to determine which sub-matrix and sub-matrix row to accumulate into.
const
matrix = [
[5, 3, 5, 6, 7, 8, 9, 1, 2],
[6, 7, 1, 1, 9, 5, 3, 4, 8],
[1, 9, 2, 3, 4, 2, 5, 6, 7],
[8, 5, 9, 7, 6, 1, 4, 2, 3],
[4, 2, 6, 5, 5, 3, 7, 9, 1],
[7, 1, 3, 1, 2, 4, 8, 5, 6],
[9, 6, 1, 5, 3, 7, 2, 8, 4],
[2, 8, 7, 5, 1, 9, 6, 3, 5],
[3, 4, 5, 6, 8, 6, 1, 7, 9]],
subdivide = (matrix, width, height) => {
return matrix.reduce((acc, row, i) => {
row.reduce((_acc, x, j, row) => {
const grid = Math.floor(j / width) + Math.floor(i / height) * (Math.ceil(row.length / width));
const gridRow = i % height;
_acc[grid] ??= [];
(_acc[grid][gridRow] ??= []).push(x);
return _acc;
}, acc)
return acc;
}, [])
},
subdividedmatrix = subdivide(matrix, 3, 3);
// log submatrices
subdividedmatrix.forEach(m => console.log(JSON.stringify(m)));
// map to strings
console.log(subdividedmatrix.map(submatrix => submatrix.flat().join('')))
.as-console-wrapper { max-height: 100% !important; top: 0; }
This is the Python code which I want to convert to Javascript!
y[i] = x[i][:j] + x[i][j] + x[i][j + 1:]
I tried using the slice function but I cannot correctly implement it for a 2d array.
So that's just some python fancy work for list comprehension but I believe you could accomplish such a thing with:
const x = [
[1, 2, 3, 4, 5, 6, 7, 8, 9],
[1, 2, 3, 4, 5, 6, 7, 8, 9],
[1, 2, 3, 4, 5, 6, 7, 8, 9],
[1, 2, 3, 4, 5, 6, 7, 8, 9],
[1, 2, 3, 4, 5, 6, 7, 8, 9],
[1, 2, 3, 4, 5, 6, 7, 8, 9],
[1, 2, 3, 4, 5, 6, 7, 8, 9],
[1, 2, 3, 4, 5, 6, 7, 8, 9],
[1, 2, 3, 4, 5, 6, 7, 8, 9]
];
var y = new Array(81);
for (i = 0; i < x.length; i++) {
var row = new Array(20);
for (j = 0; j < x.length; j++) {
row.push(x[i].slice(j).concat(x[i][j]).concat(x[i].slice(0, j+1)))
}
y.push(row);
}
for(k = 0; k < y.length; k++) {
console.log(y[k]);
}
I'm not exceptionally good with javascript, but let me know if that helps.
-Or-
provide some more input/output so I can test with, any additional code, what you've tried or what you're expected output may look like.
We have an array of arrays like this:
const arrays = [
[0, 1, 2, 3, 4, 4, 4, 4],
[5, 6, 7, 8, 9, 10, 11, 11],
[2, 7, 10, 12],
[0, 7, 10, 14]
];
There may be duplicate elements in each array and that's fine.
But I'm after a proper solution to remove duplicate elements in each set comparing to lower sets!
So as we have a 0 in the first array and the last array, we should consider the 0 in last one a duplication and remove it...
the desired result would be:
[0, 1, 2, 3, 4, 4, 4, 4],
[5, 6, 7, 8, 9, 10, 11, 11],
[12],
[14]
It's a confusing issue for me please help...
You could collect the values in an object with index as value, and filter for values who are at the same index.
const
arrays = [[0, 1, 2, 3, 4, 4, 4, 4], [5, 6, 7, 8, 9, 10, 11, 11], [2, 7, 10, 12], [0, 7, 10, 14]],
seen = {},
result = arrays.map((array, i) => array.filter(v => (seen[v] ??= i) === i));
result.forEach(a => console.log(...a));
const arrays = [
[0, 1, 2, 3, 4, 4, 4, 4],
[4, 4, 5, 6, 7, 8, 9, 10, 11, 11],
[2, 7, 10, 12],
[0, 7, 10, 14]
]
let filtered = arrays.map((row, i) => {
// concat all previous arrays
let prev = [].concat(...arrays.slice(0, i))
// filter out duplicates from prev arrays
return row.filter(r => !prev.includes(r))
})
console.log(filtered)
We can do this using Array#reduce and maintain a seen Set, which will have all visited numbers from each array.
Once you iterate over an array you push all visited elements in the seen Set, then push a new array filtered by the elements not in the seen Set:
const arrays = [
[0, 1, 2, 3, 4, 4, 4, 4],
[5, 6, 7, 8, 9, 10, 11, 11],
[2, 7, 10, 12],
[0, 7, 10, 14]
];
const removeDupsInSibling = (arr) => {
let seen = new Set();
return arr.reduce((acc, a)=> {
const f = a.filter(v => !seen.has(v));
seen = new Set([...seen, ...a]);
acc.push(f);
return acc;
}, []);
}
console.log(removeDupsInSibling(arrays));
There are plenty of inefficient ways to do this, but if you want to do this in O(n), then we can make the observation that what we want to know is "which array a number is in". If we know that, we can run our algorithm in O(n):
for every element e in array at index i:
if index(e) == i:
this is fine
if index(e) < i:
remove this e
So let's just do literally that: we allocate an object to act as our lookup, and then we run through all elements:
const lookup = {};
const arrays = [
[0, 1, 2, 3, 4, 4, 4, 4],
[5, 6, 7, 8, 9, 10, 11, 11],
[2, 7, 10, 12],
[0, 7, 10, 14]
];
const reduced = arrays.map((array, index) => {
// run through the elements in reverse, so that we can
// safely remove bad elements without affecting the loop:
for(let i=array.length-1; i>=0; i--) {
let value = array[i];
let knownIndex = (lookup[value] ??= index);
if (knownIndex < index) {
// removing from "somewhere" in the array
// uses the splice function:
array.splice(i,1);
}
}
return array;
});
console.log(reduced);
For an alternative, where the loop+splice is taken care of using filter, see Nina's answer.
Simple, clean and high performance solution:
const arrays = [
[0, 1, 2, 3, 4, 4, 4, 4],
[5, 6, 7, 8, 9, 10, 11, 11],
[2, 7, 10, 12],
[0, 7, 10, 14]
];
const duplicates = {};
const answer = arrays.map( (array, level) => {
return array.filter( el => {
if ( duplicates[el] < level ) {
// return nothing; fine
} else {
duplicates[el] = level;
return el
}
})
});
console.log(JSON.stringify(answer))
here is on-liner and less-readable form:
const d = {}, arrays = [ [0, 1, 2, 3, 4, 4, 4, 4], [5, 6, 7, 8, 9, 10, 11, 11], [2, 7, 10, 12], [0, 7, 10, 14]];
const answer = arrays.map((a,l)=> a.filter(el=> d[el]<l ? 0 : (d[el]=l,el)));
console.log(JSON.stringify(answer))
const arrays = [
[0, 1, 2, 3, 4, 4, 4, 4],
[5, 6, 7, 8, 9, 10, 11, 11],
[2, 7, 10, 12],
[0, 7, 10, 14],
];
const output = arrays.reduce(
({ output, set }, current, i) => {
output[i] = current.filter((num) => !set.has(num));
[...new Set(output[i])].forEach((num) => set.add(num));
return { output, set };
},
{ output: [], set: new Set() }
).output;
console.log(output);
Gets the exact output you want:
[
[
0, 1, 2, 3,
4, 4, 4, 4
],
[
5, 6, 7, 8,
9, 10, 11, 11
],
[ 12 ],
[ 14 ]
]
Okay, so I have a multidimensional array that itself contains 9 arrays. Each of these nested arrays contains 10 numeric values. For sake of simplicity, let's say it all looks like this:
var MyArray = [
[1,2,3,4,5,6,7,8,9,10],
[1,2,3,4,5,6,7,8,9,10],
[1,2,3,4,5,6,7,8,9,10],
[1,2,3,4,5,6,7,8,9,10],
[1,2,3,4,5,6,7,8,9,10],
[1,2,3,4,5,6,7,8,9,10],
[1,2,3,4,5,6,7,8,9,10],
[1,2,3,4,5,6,7,8,9,10],
[1,2,3,4,5,6,7,8,9,10]
]
I am trying to write a function that will take the first index of each nested array (in this case, all 1's) and add them together, pushing this value either to an array or an object. Then, I need this function to continue on, adding all the values of the next index, and the next, and so on and so forth. In the end, I should have an array of 10 values (or an object works here as well). The values would be:
1+1+1+1+1+1+1+1+1,
2+2+2+2+2+2+2+2+2,
3+3+3+3+3+3+3+3+3...
...and so on so forth, so that the actual values of the new array would be this:
[9, 18, 27, 36, 45, 54, 63, 72, 81]
The catch here is that I need this to by flexible/dynamic, so that it will work in case MyArray has only 6 arrays, or maybe the nested arrays have only 4 values each. It should work with any amount of nested arrays, each with their own amount of values (though each nested array will contain the SAME amount of values as one another!).
What would be the best way to accomplish this via JavaScript and/or jQuery? Note that I could also have the values output to an object, in this fashion:
{1:9, 2:18, 3:27, 4:36, 5:45, 6:54, 7:63, 8:72, 9:81}
I tried using similar code to this from another StackOverflow thread to get an object, but it is returning
{1:NaN, 2:NaN, 3:NaN, etc.}
That thread can be found here:
Javascript Multidimensional Array: Add Values
I'm using the "underscore" method and the jQuery $.each part of it provided by Otto.
Anyone able to help here??
Something like this
var myData = [
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
];
var summed = [];
myData[0].forEach(function (arr, index) {
var sum = myData.reduce(function (a, b) {
return a + b[index];
}, 0);
summed.push(sum);
});
console.log(summed);
On jsfiddle
Here is another solution:
var MyArray = [
[1,2,3,4,5,6,7,8,9,10],
[1,2,3,4,5,6,7,8,9,10],
[1,2,3,4,5,6,7,8,9,10],
[1,2,3,4,5,6,7,8,9,10],
[1,2,3,4,5,6,7,8,9,10],
[1,2,3,4,5,6,7,8,9,10],
[1,2,3,4,5,6,7,8,9,10],
[1,2,3,4,5,6,7,8,9,10],
[1,2,3,4,5,6,7,8,9,10]
]
var results= [];
MyArray.map(function(a){
for(var i=0;i<a.length;i++){
if(results.length === a.length){
results[i] = results[i] + a[i];
}else{
results.push(a[i]);
}
}
});
http://jsfiddle.net/uMPAA/
A simple array solution would be the following :
var results= [];
for (var i=0;i<MyArray.length;i++) {
for(var j=0; j<MyArray[i].length; j++) {
if(results[j] == undefined) { results[j] = 0; }
results[j] = results[j]+data[i][j];
}
}
Note the if(results[j]==undefined) line -- this is probably what you didn't do. If you omit that, you get NaN on all lines, since you're adding an undefined value to a number.
Another approach to sum columns in multi-dimensional arrays (based on Lodash 4).
var arrays = [
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
];
function sum_col(arrays) {
return _.map(_.unzip(arrays), _.sum);
}
console.log(sum_col(arrays));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>
In javascript I have an array as follows:
var foo = [2, 2, 4, 4, 128, 2, 2, 1, 4, 18, 27, 16, 2, 1, 18, 21, 5, 1, 128, 1, 2, 2, 1, 18, 12, 60, 2, 28, 1, 17, 2, 3, 4, 2, 2, 2, 1, 27, 2, 17, 7, 2, 2, 2, 5, 1, 2, 4, 7, 1, 2, 1, 1, 1, 2, 1, 5, 7, 2, 7, 6, 1, 7, 1, 5, 8, 4];
And I am interested in finding a way (within one loop, not multiple) to derive a subset array of the highest 10 values, where the previous position of the value is the 'key' (so simulating a Map object):
eg:
var fooTopTen = [[4, 128], [18, 128], [25, 60], [27, 28], [10, 27], [37, 27], [15, 21], [9, 18], [14, 18], [23, 18]];
My previous answer used a reverse index table, but contained some bugs - which are now fixed - and was harder to understand than the following code.
This is actually the slowest of all solutions given in the answers - for maximum performance, check my other answer.
var foo = [2, 2, 4, 4, 128, 2, 2, 1, 4, 18, 27, 16, 2, 1, 18, 21, 5, 1, 128, 1, 2, 2, 1, 18, 12, 60, 2, 28, 1, 17, 2, 3, 4, 2, 2, 2, 1, 27, 2, 17, 7, 2, 2, 2, 5, 1, 2, 4, 7, 1, 2, 1, 1, 1, 2, 1, 5, 7, 2, 7, 6, 1, 7, 1, 5, 8, 4];
var fooTopTen = [];
// add index to values
for(var i = 0, len = foo.length; i < len; ++i)
fooTopTen.push([i, foo[i]]);
// sort first by value (descending order), then by index (ascending order)
fooTopTen.sort(function(t1, t2) {
return t2[1] - t1[1] || t1[0] - t2[0];
});
// shorten array to correct size
fooTopTen.length = 10;
// output top ten to check result
document.writeln('[[' + fooTopTen.join('], [') + ']]');
The second part of the comparison function (the one comparing the indices) is not needed, as sort() is stable in most implementations (this isn't required by ECMA according to MDC). I'll leave it in as an example to how sorting with multiple requirements can be done...
This runs once through the main array it searches, inserting items at the appropriate place in the results array:
function top10(arr) {
var results = [[0,Number.MAX_VALUE],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0]];
for (var i=0; i<arr.length; i++) {
// search from back to front
for (var j=9; j>=0; j--) {
if (arr[i] <= results[j][1]) {
if (j==9)
break;
results.splice(j+1, 0, [i, arr[i]]);
results.pop();
break;
}
}
}
return results.slice(1);
}
For large arrays this should even be rather fast, since most times the inner loop should only do one iteration.
Here's the de-bugged version of my previous answer using an index table. I did a little benchmarking and for the input given in the question, this solition will be faster than anything else which has been suggested in this thread till now:
var foo = [2, 2, 4, 4, 128, 2, 2, 1, 4, 18, 27, 16, 2, 1, 18, 21, 5, 1, 128, 1, 2, 2, 1, 18, 12, 60, 2, 28, 1, 17, 2, 3, 4, 2, 2, 2, 1, 27, 2, 17, 7, 2, 2, 2, 5, 1, 2, 4, 7, 1, 2, 1, 1, 1, 2, 1, 5, 7, 2, 7, 6, 1, 7, 1, 5, 8, 4];
var indexTable = {}, uniqueValues = [];
// --- build reverse index table, find unique values
for(var i = foo.length; i--; ) {
var value = foo[i];
if(indexTable.hasOwnProperty(value))
indexTable[value].push(i);
else {
indexTable[value] = [i];
uniqueValues.push(value);
}
}
// --- sort unique values in ascending order
uniqueValues.sort(function(i1, i2) {
return i1 - i2;
});
// --- find ten greatest values
var fooTopTen = [], k = 0;
for(var i = uniqueValues.length; k < 10 && i--; ) {
var value = uniqueValues[i],
indices = indexTable[value];
for(var j = indices.length; k < 10 && j--; )
fooTopTen[k++] = [indices[j], value];
}
// --- output result
document.writeln('[[' + fooTopTen.join('], [') + ']]');
var foo = [2, 2, 4, 4, 128, 2, 2, 1, 4, 18, 27, 16, 2, 1, 18, 21, 5, 1, 128, 1, 2, 2, 1, 18, 12, 60, 2, 28, 1, 17, 2, 3, 4, 2, 2, 2, 1, 27, 2, 17, 7, 2, 2, 2, 5, 1, 2, 4, 7, 1, 2, 1, 1, 1, 2, 1, 5, 7, 2, 7, 6, 1, 7, 1, 5, 8, 4];
var index = 0;
var result = foo.map( function(a){ return [index++, a]; } )
.sort( function(a,b){ return (a[1] < b[1]); } )
.splice( 0, 10 );
document.write(result.join( ' ' ));
If foo is very large compared to the size of result required, it may be quicker to iterate over foo insertion-sorting each element into result as we come across it.
// Sorting method
function sortNumber(a, b) {
return a - b;
}
// Find the offset of an element in array
function findOffset(element, array) {
for (var i = 0; i < array.length; i++) {
if (array[i] == element) {
// Make sure we don't find it again
array[i] = null;
return i;
}
}
}
var foo = [2, 2, 4, 4, 128, 2, 2, 1, 4, 18, 27, 16, 2, 1, 18, 21, 5, 1, 128, 1, 2, 2, 1, 18, 12, 60, 2, 28, 1, 17, 2, 3, 4, 2, 2, 2, 1, 27, 2, 17, 7, 2, 2, 2, 5, 1, 2, 4, 7, 1, 2, 1, 1, 1, 2, 1, 5, 7, 2, 7, 6, 1, 7, 1, 5, 8, 4];
// Copies
var bar = foo.slice();
var baz = foo.slice();
var fooTopTen = new Array(10);
// Sort
bar.sort(sortNumber).reverse();
// Create the results
for (var i = 0; i < 10; i++) {
fooTopTen[i] = new Array(2);
fooTopTen[i][0] = findOffset(bar[i], baz);
fooTopTen[i][1] = bar[i];
}
computer-science-y answer:
problem statement: Given a large array X of length N, and a small number m < N (here m=10), produce an array Y of length m where each element of Y contains the pair {i,X[i]} such that the set of X{i} are the m largest elements of X.
If m is much smaller than N, then loop over elements of X and sort them into Y, discarding pairs to maintain at most m elements. (i.e. as moonshadow mentioned)
Sorting X will cost you O(N log N) elements. Iterating over X and sorting into Y should cost you only O(N log m) elements.