Divide a 2D array into multiple arrays using a separator - javascript

I have converted a JavaScript spritesheet to a 2D integer array, and now I'm trying to split a 2D array of integers into multiple 2D arrays, using 1 as the "separator" number.
Is there any way to separate a 2D JavaScript array like the following into multiple arrays using a separator number, as shown below?
function separate2DArray(arrToSeparate, separator){
//separate the 2D array into multiple 2D arrays, using a
//specific number as the separator
}
//array to separate:
[
[5, 5, 5, 1, 5, 4, 5],
[5, 5, 4, 1, 4, 3, 4],
[1, 1, 1, 1, 1, 1, 1], //1 is the "separator number", which splits the array
[9, 2, 1, 4, 2, 4, 5], //horizontally and vertically
]
//The array above would produce the following 2D arrays:
5 5 5
5 5 4
5 4 5
4 3 4
9 2
4 2 4 5
The main application for this algorithm that I have in mind is spritesheet image separation.

Given that the separated areas are rectangular, this will work:
function separate2DArray(array, sep){
//separate the 2D array into multiple 2D arrays, using a
//specific number as the separator
var result = [],
currentSubs = {}; // using x coordinate as key
for (var y=0; y<array.length; y++) {
var line = array[y],
subBegin = 0;
for (var x=0; x<=line.length; x++) {
if (x == line.length || line[x] == sep) {
if (subBegin < x) {
var sub = line.slice(subBegin, x);
if (subBegin in currentSubs)
currentSubs[subBegin].push(sub);
else
currentSubs[subBegin] = [sub];
} else { // a line of separators, subBegin == x
if (subBegin in currentSubs) {
result.push(currentSubs[subBegin]);
delete currentSubs[subBegin];
}
}
subBegin = x+1;
}
}
}
for (var begin in currentSubs)
result.push(currentSubs[begin]);
return result;
}
The result here is just a very simple array of the subareas, without any information about their position in the original area. Improved version:
function separate2DArray(array, sep){
var result = [],
currentSubs = {};
for (var y=0; y<array.length; y++) {
var line = array[y],
subBegin = 0;
for (var x=0; x<=line.length; x++) {
if (x == line.length || line[x] == sep) {
if (subBegin < x) {
var subline = line.slice(subBegin, x);
if (! (subBegin in currentSubs)) {
var subarea = [];
result.push({x:x, y:y, area:subarea});
currentSubs[subBegin] = subarea;
}
currentSubs[subBegin].push(subline);
} else {
if (subBegin in currentSubs)
delete currentSubs[subBegin];
}
subBegin = x+1;
}
}
}
return result;
}

You would have to iterate through the array, capturing the preview entries into a sub array whenever you find a 1
http://jsfiddle.net/cWYpr/10/
var arr = [[5, 5, 5, 1, 5, 4, 5], [5, 5, 4, 1, 4, 3, 4], [1, 1, 1, 1, 1, 1, 1], [9, 2, 1, 4, 2, 4, 5]];
var twoD = [];
for (var x = 0; x < arr.length; x++) {
var row = arr[x];
var subArray = [], subArrays=[];
for (var y = 0; y < row.length; y++) {
if (row[y] == 1) {
if (subArray.length) subArrays.push(subArray.slice(0));
subArray = [];
}
else {
subArray.push(row[y]);
}
}
if (subArray.length) subArrays.push(subArray);
if(subArrays.length) twoD.push(subArrays);
}
console.log(twoD);
document.write(JSON.stringify(twoD));

Related

How to find the same values next to each other in multidimensional array?

I tried to write a function that would find in a multidimensional array (with values from 3 to 7) repeating values for at least 3 times next to each other (vertical and horizontal). And if it finds that, change it for a different value. Let's say 1.
I tried to do this by loops but it doesn't seem to be a good way to solve that or I messed it up. Because for some array it works, for some it does not.
Here's my code:
function searching(array) {
for (i = 0; i < array.length; i++) {
let horizontal = array[i][0];
let howMany = 1;
for (j = 1; j < array[i].length; j++) {
if (horizontal === array[i][j]) {
howMany += 1;
horizontal = array[i][j];
if (howMany >= 3) {
for (d = j; d > j - howMany; d--) {
array[i][d] = 0;
}
}
} else {
horizontal = array[i][j];
howMany = 1;
}
}
}
for (v = 0; v < array.length; v++) {
let vertical = array[0][v];
let howMany = 1;
for (x = 1; x < array.length; x++) {
if (vertical === array[x][v]) {
howMany++;
vertical = array[x][v];
if (howMany >= 3) {
for (d = x; d > x - howMany; d--) {
array[d][v] = 0;
}
}
} else {
vertical = array[x][v];
howMany = 1;
}
}
}
}
The idea is to for example give array:
let array = [
[3, 4, 5, 6, 7],
[3, 4, 5, 6, 7],
[3, 4, 5, 5, 5],
[3, 5, 6, 7, 4]
]
And the result should be:
let result = [
[1, 1, 1, 6, 7],
[1, 1, 1, 6, 7],
[1, 1, 1, 1, 1],
[1, 5, 6, 7, 4]
]
Thanks in advance for any ideas how to solve it :) Greetings!
The problems with your current code are
(1) You're only checking individual rows and columns, when you need to be checking them both (eg, with [[2, 2], [2, 5]], when at the starting position [0][0], you need to look at both [0][1] (and its neighbors, if matching) as well as [1][0] (and its neighbors, if matching).
(2) You're not actually checking for adjacency at the moment, you're just counting up the total number of matching elements in a particular row or column.
Iterate over all indicies of the array. If an index has already been checked, return early. Recursively search for neighbors to that index, and if at least 3 matching in total are found, set them all to 1. Put all matching neighbors in the checked set to avoid checking them again (even if there were less than 2 adjacent matches found total).
setAllAdjacentToOne([
[3, 4, 5, 6, 7],
[3, 4, 5, 6, 7],
[3, 4, 5, 5, 5],
[3, 5, 6, 7, 4]
]);
// all 9s stay, the rest get set to 1:
setAllAdjacentToOne([
[2, 2, 9, 7, 7],
[2, 9, 9, 9, 7],
[3, 4, 4, 5, 5],
[9, 4, 5, 5, 9]
]);
function setAllAdjacentToOne(input) {
const output = input.map(subarr => subarr.slice());
const checked = new Set();
const getKey = (x, y) => `${x}_${y}`;
const width = input[0].length;
const height = input.length;
const getAllAdjacent = (x, y, numToFind, matches = []) => {
if (x >= width || x < 0 || y >= height || y < 0) {
return matches;
}
const key = getKey(x, y);
if (!checked.has(key) && input[y][x] === numToFind) {
checked.add(key);
matches.push({ x, y });
getAllAdjacent(x + 1, y, numToFind, matches);
getAllAdjacent(x - 1, y, numToFind, matches);
getAllAdjacent(x, y + 1, numToFind, matches);
getAllAdjacent(x, y - 1, numToFind, matches);
}
return matches;
};
output.forEach((innerRowArr, y) => {
innerRowArr.forEach((num, x) => {
const allAdjacent = getAllAdjacent(x, y, num);
if (allAdjacent.length <= 2) {
return;
}
allAdjacent.forEach(({ x, y }) => {
output[y][x] = 1;
});
});
});
console.log(JSON.stringify(output));
}
I didn't understand the question at first...
So this is my code:
let array = [
[3, 4, 5, 6, 7],
[3, 4, 5, 6, 7],
[3, 4, 5, 5, 5],
[3, 5, 6, 7, 4]
];
function replace(arr, target = 1) {
let needToChange = []; // save the index to change
const numbers = [3, 4, 5, 6, 7];
const m = arr.length; // m rows
const n = arr[0].length; // n columns
let mi = 0;
let ni = 0;
// search in row
for (mi = 0; mi < m; mi++) {
for (let x = 0; x < numbers.length; x++) {
const num = numbers[x]; // number to search
let counter = 0; // counter for this number in row mi
let tempArr = [];
for (ni = 0; ni < n; ni++) {
const currentNum = arr[mi][ni];
if (currentNum === num) {
counter++;
tempArr.push([mi, ni]);
}
}
if (counter >= 3) {
needToChange = needToChange.concat(tempArr);
}
}
}
// search in column
for (ni = 0; ni < n; ni++) {
for (let x = 0; x < numbers.length; x++) {
const num = numbers[x]; // number to search
let counter = 0; // counter for this number in row mi
let tempArr = [];
for (mi = 0; mi < m; mi++) {
const currentNum = arr[mi][ni];
if (currentNum === num) {
counter++;
tempArr.push([mi, ni]);
}
}
if (counter >= 3) {
needToChange = needToChange.concat(tempArr);
}
}
}
// replace
needToChange.forEach(([i, j]) => {
array[i][j] = target;
});
}
replace(array);
array.forEach(row => {
console.log(row.join(', '));
})

Find a group of objects in an array with javascript

Question has been moved to CodeReview: https://codereview.stackexchange.com/questions/154804/find-a-list-of-objects-in-an-array-with-javascript
Having an array of objects - such as numbers - what would be the most optimal (Memory and CPU efficiency) way if finding a sub group of objects? As an example:
demoArray = [1,2,3,4,5,6,7]
Finding [3,4,5] would return 2, while looking for 60 would return -1.
The function must allow for wrapping, so finding [6,7,1,2] would return 5
I have a current working solution, but I'd like to know if it could be optimized in any way.
var arr = [
1,
5,2,6,8,2,
3,4,3,10,9,
1,5,7,10,3,
5,6,2,3,8,
9,1]
var idx = -1
var group = []
var groupSize = 0
function findIndexOfGroup(g){
group = g
groupSize = g.length
var beginIndex = -2
while(beginIndex === -2){
beginIndex = get()
}
return beginIndex
}
function get(){
idx = arr.indexOf(group[0], idx+1);
if(idx === -1 || groupSize === 1){
return idx;
}
var prevIdx = idx
for(var i = 1; i < groupSize; i++){
idx++
if(arr[getIdx(idx)] !== group[i]){
idx = prevIdx
break
}
if(i === groupSize - 1){
return idx - groupSize + 1
}
}
return -2
}
function getIdx(idx){
if(idx >= arr.length){
return idx - arr.length
}
return idx
}
console.log(findIndexOfGroup([4,3,10])) // Normal
console.log(findIndexOfGroup([9,1,1,5])) // Wrapping
You could use the reminder operator % for keeping the index in the range of the array with a check for each element of the search array with Array#every.
function find(search, array) {
var index = array.indexOf(search[0]);
while (index !== -1) {
if (search.every(function (a, i) { return a === array[(index + i) % array.length]; })) {
return index;
}
index = array.indexOf(search[0], index + 1);
}
return -1;
}
console.log(find([3, 4, 5], [1, 2, 3, 4, 5, 6, 7])); // 2
console.log(find([6, 7, 1, 2], [1, 2, 3, 4, 5, 6, 7])); // 5
console.log(find([60], [1, 2, 3, 4, 5, 6, 7])); // -1
console.log(find([3, 4, 5], [1, 2, 3, 4, 6, 7, 3, 4, 5, 9])); // 6
.as-console-wrapper { max-height: 100% !important; top: 0; }
My take on the problem is to use slice() and compare each subarray of length equal to the group's length to the actual group array. Might take a bit long, but the code is short enough:
// The array to run the tests on
var arr = [
1,
5, 2, 6, 8, 2,
3, 4, 3, 10, 9,
1, 5, 7, 10, 3,
5, 6, 2, 3, 8,
9, 1
];
// Check arrays for equality, provided that both arrays are of the same length
function arraysEqual(array1, array2) {
for (var i = array1.length; i--;) {
if (array1[i] !== array2[i])
return false;
}
return true;
}
// Returns the first index of a subarray matching the given group of objects
function findIndexOfGroup(array, group) {
// Get the length of both arrays
var arrayLength = array.length;
var groupLength = group.length;
// Extend array to check for wrapping
array = array.concat(array);
var i = 0;
// Loop, slice, test, return if found
while (i < arrayLength) {
if (arraysEqual(array.slice(i, i + groupLength), group))
return i;
i++;
}
// No index found
return -1;
}
// Tests
console.log(findIndexOfGroup(arr,[4,3,10])); // Normal
console.log(findIndexOfGroup(arr,[9,1,1,5])); // Wrapping
console.log(findIndexOfGroup(arr,[9,2,1,5])); // Not found
If the group is longer than the array, some errors might occur, but I leave it up to you to extend the method to deal with such situations.

Array truncation with splice method

I need to delete occurrences of an element if it occurs more than n times.
For example, there is this array:
[20,37,20,21]
And the output should be:
[20,37,21]
I thought one way of solving this could be with the splice method
First I sort the array it order to make it like this:
[20,20,37,21]
Then I check if the current element is not equal to the next and split the array into chunks, so it should look like:
[20, 20],[37],[21]
Later I can edit the chunk longer than 1 and join it all again.
This is what the code looks like in my head but didn't work in real life
var array = [20, 37, 20, 21];
var chunk = [];
for(i = 0; i < array.length; i++) {
if(array[i] !== array[i + 1]) {
var index = array.indexOf(array[i]);
chunk.push = array.splice(0, index) // cut from zero to last duplicate element
} else
var index2 = a.indexOf(a[i]);
chunk.push(a.splice(0, index));
}
with this code the output is
[[], [20, 20]]
I think It's something in the 'else' but can't figure it out what to fix.
As the logic you want to achieve is to delete n occurrences of element in an array, your code could be as follow:
var array = [1, 1, 3, 3, 7, 2, 2, 2, 2];
var n = 2;
var removeMultipleOccurences = function(array, n) {
var filteredArray = [];
var counts = {};
for(var i = 0; i < array.length; i++) {
var x = array[i];
counts[x] = counts[x] ? counts[x] + 1 : 1;
if (counts[x] <= n) filteredArray.push(array[i])
}
return filteredArray;
}
console.log(removeMultipleOccurences(array, n));
I came up with this one, based on array filter checking repeated values up to a limit, but I can see #Basim's function does the same.
function removeDuplicatesAbove(arr, max) {
if (max > arr.length) {max = arr.length;}
if (!max) {return arr;}
return arr.filter(function (v, i) {
var under = true, base = -1;
for (var n = 0; n < max; n++) {
base = arr.indexOf(v, base+1); if (base == -1) {break;}
}
if (base != -1 && base < i) {under = false;}
return under;
});
}
var exampleArray = [20, 37, 20, 20, 20, 37, 22, 37, 20, 21, 37];
console.log(removeDuplicatesAbove(exampleArray, 3)); // [20, 37, 20, 20, 37, 22, 37, 21]
Always when you use splice() you truncate the array. Truncate the array with the length of same values from the start with the help of lastIndexOf(). It always starts from 0.
[ 1, 1, 1, 2, 2, 2, 3, 4, 4, 5 ] // splice(0, 3)
[ 2, 2, 2, 3, 4, 4, 5 ] // splice(0, 3)
[ 3, 4, 4, 5 ] // splice(0, 1)
[ 4, 4, 5 ] // splice(0, 2)
[ 5 ] // splice(0, 1)
Do this as long as the array length is greater than 0.
var arr = [1, 1, 1, 2, 2, 2, 3, 4, 4, 5];
var res = [];
while (arr.length > 0) {
var n = arr[0];
var last = arr.lastIndexOf(n) + 1;
res.push(n);
arr.splice(0, last);
}
console.log(res);
You can use Array.prototype.reduce(), Array.prototype.filter() to check if n previous elements are the same as current element
let cull = (arr, n) => arr.reduce((res, curr) => [...res
, res.filter(v => v === curr).length === n
? !1 : curr].filter(Boolean), []);
let arrays = [[20,37,20,21], [1,1,3,3,7,2,2,2,2]];
let cullone = cull(arrays[0], 1);
let cullthree = cull(arrays[1], 3);
console.log(cullone // [20, 37, 21]
, cullthree // [1, 1, 3, 3, 7, 2, 2, 2]
);

Convert a 1D array to 2D array [duplicate]

This question already has answers here:
Convert simple array into two-dimensional array (matrix)
(19 answers)
Closed 8 years ago.
I am working on a program where I have to read the values from a textfile into an 1D array.I have been succesfull in getting the numbers in that 1D array.
m1=[1,2,3,4,5,6,7,8,9]
but I want the array to be
m1=[[1,2,3],[4,5,6],[7,8,9]]
You can use this code :
const arr = [1,2,3,4,5,6,7,8,9];
const newArr = [];
while(arr.length) newArr.push(arr.splice(0,3));
console.log(newArr);
http://jsfiddle.net/JbL3p/
Array.prototype.reshape = function(rows, cols) {
var copy = this.slice(0); // Copy all elements.
this.length = 0; // Clear out existing array.
for (var r = 0; r < rows; r++) {
var row = [];
for (var c = 0; c < cols; c++) {
var i = r * cols + c;
if (i < copy.length) {
row.push(copy[i]);
}
}
this.push(row);
}
};
m1 = [1, 2, 3, 4, 5, 6, 7, 8, 9];
m1.reshape(3, 3); // Reshape array in-place.
console.log(m1);
.as-console-wrapper { top:0; max-height:100% !important; }
Output:
[
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
JSFiddle DEMO
I suppose you could do something like this... Just iterate over the array in chunks.
m1=[1,2,3,4,5,6,7,8,9];
// array = input array
// part = size of the chunk
function splitArray(array, part) {
var tmp = [];
for(var i = 0; i < array.length; i += part) {
tmp.push(array.slice(i, i + part));
}
return tmp;
}
console.log(splitArray(m1, 3)); // [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ]
Obviously there is no error checking, but you can easily add that.
DEMO
There are so many ways to do the same thing:
var m = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var n = [];
var i = 0;
for (l = m.length + 1; (i + 3) < l; i += 3) {
n.push(m.slice(i, i + 3));
}
// n will be the new array with the subarrays
The above is just one.

how to find longest common subarray

here is my problem: I have 5 arrays of integer like these in javascript:
array1 = [0, 1, 2, 3, 4];
array2 = [9, 1, 2, 3, 4];
array3 = [10, 1, 2, 11, 4];
array4 = [12, 1, 2, 13, 4];
array5 = [14, 1, 2, 15, 4];
I have to find the longest common subarray. In this case I have to retrieve the following subarray: [1, 2, 4].
For the records, I won't find repetitions inside arrays and my main goal is not execution speed.
thanks
here is the solution using Set in Javascript
var myArray = [array1 , array2 ,array3 , array4 ,array5];
let keys = new Set();
myArray.forEach(arr => arr.forEach(el => keys.add(el) ))
var common = [...keys].filter(key => myArray.every(arr => arr.includes(key)))
console.log(common);
#define MAX(a,b) a>b?a:b
int main(int argc, char* argv[])
{
if(argc < 2)
return -1;
int x = strlen(argv[1])+1;
int y = strlen(argv[2])+1;
int i,j,k,l;
int longest =0;
char* LCS = (char*)malloc(sizeof(char)*MAX(x,y));
int** arr = (int**)malloc(sizeof(int*)*x);
for(i=0;i<=y;i++)
arr[i] =(int*) malloc(sizeof(int)*y);
for(i=0;i<=x;i++)
for(j=0;j<=y;j++)
{
arr[i][j] = 0;
}
for(i=0;i<x;i++)
for(j=0;j<y;j++)
{
if(argv[1][i] == argv[2][j])
arr[i+1][j+1] = arr[i][j]+1;
if(arr[i+1][j+1] > longest)
{
longest =arr[i+1][j+1];
memset(LCS,0,MAX(x,y));
for( k=0,l=i;k<=longest;k++,l--)
LCS[k] = argv[1][l];
}
}
printf(" %s",argv[2]);
for(i=0;i<x;i++)
{
printf("\n%c",argv[1][i]);
for(j=0;j<y;j++)
{
printf("%d",arr[i][j]);
}
}
printf("\nLongest Common Subarray : %s\n",LCS);
return 0;
}
Try this:
var array1 = [0, 1, 2, 3, 4];
var array2 = [9, 1, 2, 3, 4];
var array3 = [10, 1, 2, 11, 4];
var array4 = [12, 1, 2, 13, 4];
var array5 = [14, 1, 2, 15, 4];
// join everything into one array
var all = array1.join(',')+','+array2.join(',')+','+array3.join(',')+','+array4.join(',')+','+array5.join(',');
all = all.split(',');
// get an object with all unique numbers as keys
var keys = {};
for(var i=0; i<all.length; i++) keys[all[i]] = 1;
console.log(keys);
// generate an array with values present in all arrays
var common = [];
for(var x in keys) {
if(array1.indexOf(parseInt(x)) != -1 && array2.indexOf(parseInt(x)) != -1 && array3.indexOf(parseInt(x)) != -1 && array4.indexOf(parseInt(x)) != -1 && array5.indexOf(parseInt(x)) != -1) {
common.push(x);
}
}
console.log(common);
I guess this can give you a good start:
My script will return you an object with the count of each elements. But for now, it takes the first array as base.
var array1 = [0, 1, 2, 3, 4];
var array2 = [9, 1, 2, 3, 4];
var array3 = [10, 1, 2, 11, 4];
var array4 = [12, 1, 2, 13, 4];
var array5 = [14, 1, 2, 15, 4];
var array6 = [13, 1, 2, 18, 4];
var mainArr = [array1, array2, array3, array4, array5, array6]
function getCommonElement(arr){
var subLength = arr[0].length;
var resultArr = new Array();
var ret = new Object();
for(var k=0;k<subLength;k++){
var temp = new Array();
for(var i=0;i<arr.length;i++){
temp.push(arr[i][k]);
}
resultArr.push(temp);
}
for(var i=0;i<arr[0].length;i++){
ret[arr[0][i]+''] = resultArr[i].join('').split(arr[0][i]+'').length - 1;
}
return ret;
}
Cheers.
/**
longest common subarray b/w 2 arrays
a = [2,3,4,5,6,7,8], b = [6,7,8,4,5,2,3]
ans = 6,7,8
basically create a 2d arr and if elements match dp[i][j] = 1 + dp[i-1][j-1];
if dp[i][j] > maxLen, update maxLen and store the index
Now that we have the maxLen, subarray will be from (index - maxLen) till index.
*/
int[] finMaxCommon(int[] a, int[] b){
int m = a.length, n = b.length, maxLen = 0;
int[][] dp = new int[m+1][n+1];
// i want a 0th row why? m->out of bounds; comparing i-1; i->1 then i-1 will be 0
for (int i = 1; i<=m; i++){
for(int j = 1; j<=n; j++){
if(a[i-1] == b[j-1]) {
dp[i][j] = 1 + dp[i-1][j-1];
maxLen = Math.max(maxLen, dp[i][j]);
}
}
}
// endIndex = 6, 3, a[6-3+1], a[6]
return new int[]{a[endIndex-maxLen+1], [endIndex]};
}
dry run
0,6,7,8,4,5,2,3
0, 0 //
2, 1 // (2,2) i = 1, j = 6 1 + dp[0][5]
3, 2 // (3,3) i = 2, j = 7 1 + dp[1][6]
4,
5,
6, 1
7, 2
8, 3

Categories