This question already has answers here:
Permutations in JavaScript?
(41 answers)
Closed 6 years ago.
I have different arrays, all with numbers, but with different number of elements:
var ar1 = [2, 5];
var ar2 = [1, 2, 3];
I need to get all permutations for each array. The length of the output elements should always be the same as the input array.
This result should be an array of arrays, like this:
for ar1:
[2, 5]
[5, 2]
for ar2:
[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, 3, 1]
[3, 1, 2]
[3, 2, 1]
I don't want a cartesian product, each array should be processed on its own.
All solutions I found so far are creating only order independent arrays, so the result for ar1 is only one array and not two.
The Solution should work for any number of elements in the input array. We can assume that there are no duplicate values in the input array.
You could use for a permutation an iterative and recursive approach until not more elements are to distribute.
function permutation(array) {
function p(array, temp) {
var i, x;
if (!array.length) {
result.push(temp);
}
for (i = 0; i < array.length; i++) {
x = array.splice(i, 1)[0];
p(array, temp.concat(x));
array.splice(i, 0, x);
}
}
var result = [];
p(array, []);
return result;
}
console.log('something bigger [1,2,3,4,5,6,7]');
console.time('t1');
permutation([1, 2, 3, 4, 5, 6, 7]);
console.timeEnd('t1');
console.log(permutation([2, 5]));
console.log(permutation([1, 2, 3]));
.as-console-wrapper { max-height: 100% !important; top: 0; }
Not sure if this is the best way, but it seems to work.
#Nina's solution looks good, but it does a fair bit of array concat & slice, so this might work better for larger sets as it avoids that. I do use an object for duplicate checking, but hashmaps are super fast in JS.
Just curious, so did a performance test.
Doing [1,2,3,4,5,6,7], using #Nina's solution take's 38.8 seconds,.
Doing mine toke 175ms.. So the array concat / slice is a massive performance hit, and the marked duplicate will have the same issue. Just something to be aware off.
var ar1 = [2, 5];
var ar2 = [1, 2, 3];
function combo(c) {
var r = [],
len = c.length;
tmp = [];
function nodup() {
var got = {};
for (var l = 0; l < tmp.length; l++) {
if (got[tmp[l]]) return false;
got[tmp[l]] = true;
}
return true;
}
function iter(col,done) {
var l, rr;
if (col === len) {
if (nodup()) {
rr = [];
for (l = 0; l < tmp.length; l++)
rr.push(c[tmp[l]]);
r.push(rr);
}
} else {
for (l = 0; l < len; l ++) {
tmp[col] = l;
iter(col +1);
}
}
}
iter(0);
return r;
}
console.log(JSON.stringify(combo(ar1)));
console.log(JSON.stringify(combo(ar2)));
console.log('something bigger [1,2,3,4,5,6,7]');
console.time('t1');
combo([1,2,3,4,5,6,7]);
console.timeEnd('t1');
Related
DISCLAIMER
I am well aware of the duplicate questions, however this one is asking to remove duplicates without making a new array and wants us to mutate the original array.
INSTRUCTIONS
Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
EXAMPLE
Given nums = [1,1,2],
Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively.
It doesn't matter what you leave beyond the returned length.
ATTEMPT
const removeDuplicates = function(nums) {
for(let i of nums){
if(nums[i] === nums[i]){
nums.splice(i, 1)
}
}
return nums.length;
};
console.log(removeDuplicates([1, 1, 2]));
console.log(removeDuplicates([1, 2]));
// [1, 1, 2] => [1, 2] (Correct)
// [1, 2] => [1] (Incorrect - should be [1, 2])
Am I mutating the array correctly with splice and what do I need to do to correct the 2nd argument?
Also, in leetcode, when I run the first argument, it says it's correct and returns the array of the leftover elements, but the instructions were asking for the length of the new array. Not sure if I'm missing something but why is it not returning the length?
https://imgur.com/5cuhFYf
Here you are:
const removeDuplicates = function(nums) {
for(let i = 0; i < nums.length;){
if(nums[i] === nums[++i]){
nums.splice(i, 1)
}
}
return nums.length;
};
console.log(removeDuplicates([1, 1, 2]));
console.log(removeDuplicates([1, 2]));
let nums = [1,1,2];
nums = [...new Set(nums)].length;
console.log(nums);
nums = [1,1,2];
nums = nums.filter(function(item, pos, self) {
return self.indexOf(item) == pos;
})
console.log(nums)
For each element of the array you need to iterate through all remaining elements of that array, to check for all duplicates. Not sure if this is more performant then making a copy.
const removeDuplicates = function (nums) {
let i = 0;
while (i < nums.length) {
let j = i + 1;
while (j < nums.length) {
if (nums[i] === nums[j]) {
nums.splice(j, 1);
}
else {
j++;
}
}
i++;
}
return nums.length;
};
console.log(removeDuplicates([1, 1, 2]));
console.log(removeDuplicates([1, 2]));
console.log(removeDuplicates([1, 2, 1, 3, 4, 3, 2, 1]));
// [1, 1, 2] => [1, 2] (Correct)
// [1, 2] => [1] (Incorrect - should be [1, 2])
// [1, 2, 1, 3, 4, 3, 2, 1] => [1, 2, 3, 4]
The hint is in the line: It doesn't matter what you leave beyond the returned length.
Whoever is asking you this wants you to move through the array keeping track of 2 pointers: 1) The end of the output array and 2) the current index in the input array.
If you do this, and copy the input to the output pointer only when they're different, you will end up with the correct output, the correct length (from the output pointer) and a little bit of garbage at the end of the array.
const unique = (arr) => {
let output = 0;
for (let input = 0; input < arr.length; input++) {
if (arr[output] !== arr[input]) {
output++;
arr[output] = arr[input];
}
}
return output + 1;
}
const arr = [1, 1, 2, 3, 3, 3, 4, 5, 5, 6, 8, 8, 8, 9, 11];
const length = unique(arr);
console.log(arr, length);
I believe this solution will pass more test cases (at least in my personal testing)
const removeDups = (nums) => {
// since mutating arrays I like to start at the end of the array so when the index is removed it doesn't impact the loop
let i = nums.length - 1;
while(i > 0){
// --i decrements then evaluates (i.e 5 === 4), i-- decriments after the evaluation (i.e 5 === 5 then decrements the last 5 to 4)
if(nums[i] === nums[--i]){
// remove the current index (i=current index, 1=number of indexes to remove including itself)
nums.splice(i,1);
}
}
console.log(nums);
return nums.length;
};
// Test Cases
console.log(removeDups([1,1,2])); // 2
console.log(removeDups([0,0,1,1,1,2,2,3,3,4])); // 5
console.log(removeDups([0,0,0,2,3,3,4,4,5,5])); // 5
Tried the solution provided by Kosh above, but it failed for bigger array [0,0,1, 1, 1, 2, 2, 3, 3, 4]. So ended up writing my own. Seems to work for all tests.
var removeDuplicates = function(nums) {
var i;
for (i = 0; i <= nums.length; i++) {
const tempNum = nums[i];
var j;
var tempIndex = [];
for (j = i+1; j <= nums.length; j++) {
if (tempNum === nums[j]) {
tempIndex.push(j)
}
}
nums.splice(tempIndex[0], tempIndex.length)
}
return (nums.length);
};
I am attempting to do this Kata - https://www.codewars.com/kata/organize-a-round-robin-tournament/train/javascript.
The task is to create a function that organizes a round robin tournament.
Example:
buildMatchesTable(4)
Should return a matrix like:
[
[[1,2], [3, 4]], // first round: 1 vs 2, 3 vs 4
[[1,3], [2, 4]], // second round: 1 vs 3, 2 vs 4
[[1,4], [2, 3]] // third round: 1 vs 4, 2 vs 3
]
I have created a very clunky solution that works up until the last hurdle. I am left with an array (arr6) that is an array listing all the matchups in the correct order, but as a simple array, not subarrays designating the various rounds. So I tried to create a function cut to produce an array in the correct format and it tells me arr7 is not defined.
My solution is poorly written as I am new to this, but I think the fix should be relatively simple, something to do with not returning values correctly in functions, or functions called in the wrong order. Thanks.
function buildMatchesTable(numberOfTeams) {
let n = numberOfTeams; let h = n/2; let arr = []; let arr2 = [[],[]];
let arr3 = [...Array(n-1)].map(v => v); let arr4 = [];
//create array
for (var i = 1; i <= n; i++) {arr.push(i)} //[1, 2, 3, 4]
//split array
arr2[0] = arr.splice(0, arr.length/2);
arr2[1] = arr.splice(0, arr.length); //[[1, 2], [3, 4]]
//create a function that produces matches in a round from array[i]
function round (arr2) {
for (var i = 0; i < arr2[0].length; i++){
arr4.push([arr2[0][i], arr2[1][i]]);
}
arr2 = arr4;
return arr2; // [[1 v 3], [2 v 4]] etc.
}
//create a function that tranforms the arr to gameweek +1 (rotate everything clockwise apart from team 1
function trans(arr2){
//create new arr5 that is the same as arr2
arr5 = [[],[]];
for (var i = 0; i < arr2[0].length; i++) {
arr5[0].push(arr2[0][i])
arr5[1].push(arr2[1][i])
}
//rotate every element apart from arr2[0,0] : [[1, 3], [4, 2]]
let h = arr2[0].length - 1;
arr2[0][1] = arr5[1][0];
arr2[1][h] = arr5[0][h];
for (var i = 2; i <= h; i++){
arr2[0][i] = arr5[0][i-1];}
for (var i = 0; i <= h-1; i++){
arr2[1][i] = arr5[1][i+1];}
return arr2;
}
function final (n, arr2, arr3){ //putting all the functions together
for (var i = 0; i < n-1; i++){
arr3[i] = (round(arr2));
trans(arr2);
}
return arr3; // [[1, 3], [2, 4, [1, 4], [3, 2], [1, 2], [4, 3]] X 3
}
final(n, arr2, arr3)
let arr6 = arr3[0]; // arr6 = [[1, 3], [2, 4, [1, 4], [3, 2], [1, 2], [4, 3]]
function cut(arr6, n) {
let arr7 = [];
let index = 0;
while (index < arr6.length) {
arr7.push(arr6.slice(index, n/2+index));
index += n/2;
}
return arr7;
}
cut(arr6, n);
console.log(n);
console.log(arr);
console.log(arr2);
console.log(arr3[0]);
console.log(arr4);
console.log(arr6);
console.log(arr7);//not working!
//return arr7
}
buildMatchesTable(6)
No wonder, you are declaring let arr7 = []; inside a function. Get it out of the function, on the same level as arr6, arr4, etc.
i have a problem and i need help for this question.
My reverse function doesn't work the way I want it to.
function reverseArrayInPlace(array){
let old = array;
for (let i = 0; i < old.length; i++){
array[i] = old[old.length - 1 - i];
};
};
let arrayValue = [1, 2, 3, 4, 5];
reverseArrayInPlace(arrayValue);
console.log(arrayValue);
I expect on [5, 4, 3, 2, 1] but i have [5, 4, 3, 4, 5].
Why does it work this way? Please help me understand.
P.S I know about the reverse method.
Variable, with assigned object (array, which is a modified object in fact) - stores just a link to that object, but not the actual object. So, let old = array; here you just created a new link to the same array. Any changes with both variables will cause the change of array.
(demo)
let arr = [0,0,0,0,0];
let bubu = arr;
bubu[0] = 999
console.log( arr );
The simplest way to create an array clone:
function reverseArrayInPlace(array){
let old = array.slice(0); // <<<
for (let i = 0; i < old.length; i++){
array[i] = old[old.length - 1 - i];
};
return array;
};
console.log( reverseArrayInPlace( [1, 2, 3, 4, 5] ) );
P.s. just for fun:
function reverseArrayInPlace(array){
let len = array.length;
let half = (len / 2) ^ 0; // XOR with 0 <==> Math.trunc()
for( let i = 0; i < half; i++ ){
[ array[i], array[len - i-1] ] = [ array[len - i-1], array[i] ]
}
return array;
};
console.log( reverseArrayInPlace( [1, 2, 3, 4, 5] ) );
If you're writing a true in place algorithm, it's wasteful from both a speed and memory standpoint to make an unnecessary copy (as other answers point out--array and old are aliases in the original code).
A better approach is to iterate over half of the array, swapping each element with its length - 1 - i compliment. This has 1/4 of the iterations of the slice approach, is more intuitive and uses constant time memory.
const reverseArrayInPlace = a => {
for (let i = 0; i < a.length / 2; i++) {
[a[i], a[a.length-1-i]] = [a[a.length-1-i], a[i]];
}
};
const a = [1, 2, 3, 4, 5];
reverseArrayInPlace(a);
console.log(a);
Since this is a hot loop, making two array objects on the heap just to toss them out is inefficient, so if you're not transpiling this, you might want to use a traditional swap with a temporary variable.
function reverseArrayInPlace(a) {
for (var i = 0; i < a.length / 2; i++) {
var temp = a[i];
a[i] = a[a.length-i-1];
a[a.length-i-1] = temp;
}
};
var a = [1, 2, 3, 4];
reverseArrayInPlace(a);
console.log(a);
You have in old variable the same array (not by value, but by reference), so if you change any of them you'll have changes in both.
So you should create new array, make whatever you want with them and return it (or just copy values back to your origin array if you don't want to return anything from your function).
It happend like that because:
1) arr[0] = arr[4] (5,2,3,4,5)
2) arr[1] = arr[3] (5,4,3,4,5)
....
n) arr[n] = arr[0] (5,4,3,4,5)
So you can just make a copy (let old = array.slice()) and it'll be woking as you'd expect.
Here is the question:
Compare two arrays and return a new array with any items only found in one of the two given arrays, but not both. In other words, return the symmetric difference of the two arrays.
And here is my code:
function diffArray(arr1, arr2) {
var newArr = [];
// Same, same; but different.
for (i = 0; i < arr1.length; i++) {
for (j = 0; j < arr2.length; j++)
while (arr1[i] === arr2[j])
delete arr2[j];
newArr = arr2;
}
return newArr;
}
console.log(diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]));
Please, tell me my mistakes.
If you work using indices as references which you delete, you'll leave those indices undefined.
You have to use push to add an item and splice to remove one.
The time complexity of the following code should be: O(nm) where n and m are the lengths of the arr1 and arr2 arrays respectively.
function diffArray(arr1, arr2) {
var newArr = [];
for (i = 0; i < arr1.length; i++) {
for (j = 0; j < arr2.length; j++)
while (arr1[i] === arr2[j])
arr2.splice(j, 1);
newArr = arr2;
}
return newArr;
}
console.log(diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]));
This should work, but I've found a different way that is a bit slower for short arrays but much faster for longer array.
The time complexity of the following code should be: O(3(n + m)), which is reduced to O(n + m) where n and m are the lengths of the arr1 and arr2 arrays respectively.
Look at this fiddle.
Here's it:
function diffArray(arr1, arr2) {
let obj1 = {}, obj2 = {};
for (let l = arr1.length, i = 0; i < l; i++)
obj1[arr1[i]] = undefined;
for (let l = arr2.length, i = 0; i < l; i++)
obj2[arr2[i]] = undefined;
let a = [];
for (let arr = arr1.concat(arr2), l = arr.length, i = 0, item = arr[0]; i < l; i++, item = arr[i])
if (item in obj1 !== item in obj2)
a.push(item);
return a;
}
console.log(diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]));
The task you are trying to complete asks you to create a new array, but instead you modify arr2. It would probably be easiest to just copy all elements not included in the other array to a new array, like this:
function diffArray(arr1, arr2) {
var newArray = [];
arr1.forEach(function(el) {
if (!arr2.includes(el)) {
newArray.push(el);
}
});
arr2.forEach(function(el) {
if (!arr1.includes(el)) {
newArray.push(el);
}
});
return newArray;
}
If you would rather try and fix your code instead, I can try to have another look at it.
I've used Array.prototype.filter method:
function diffArray(arr1, arr2) {
var dif01 = arr1.filter(function (t) {
return arr2.indexOf(t) === -1;
});
var dif02 = arr2.filter(function (t) {
return arr1.indexOf(t) === -1;
});
return (dif01).concat(dif02);
}
alert(diffArray([1, 2, 3, 6, 5], [1, 2, 3, 4, 7, 5]));
If you still want to use your code and delete the common elements, try to use Array.prototype.splice method instead of delete: the latter deletes the value, but keeps the index empty, while Array.prototype.splice will remove those whole indices within the given range and will reindex the items next to the range.
You can use Array.prototype.filter:
var array1 = [1, 2, 3, 5];
var array2 = [1, 2, 3, 4, 5];
var filteredArray = filter(array1, array2).concat(filter(array2, array1));
function filter(arr1, arr2) {
return arr1.filter(function(el) { return arr2.indexOf(el) < 0; });
}
Here is a working JSFiddle.
Try this:
function diffArray(arr1, arr2) {
var ret = [];
function checkElem(arrFrom, arrIn) {
for (var i = 0; i < arrFrom.length; ++i) {
var elem = arrFrom[i];
if (arrIn.indexOf(elem) === -1)
ret.push(elem);
}
}
checkElem(arr1, arr2);
checkElem(arr2, arr1);
return ret;
}
I hope this can solve your problem.
I'm working on some quiz and I have an array which is looking like this one: let a = [1, 3, 4, 2]
Now I'm wondering how do I create a loop that returns three new arrays with 2 swapped values i.e: (a[i] swapped with a[i+1])
I'm expecting to get 3 following arrays like below:
[3, 1, 4, 2]
[1, 4, 3, 2]
[1, 3, 2, 4]
What would be the approach creating the loop for this? I have been trying to loop through the array with map function and swapping values but found that I'm just confusing myself. Any constructive approach/solution with an explanation to this quiz would be appreciated.
map in a loop is all you should need
let a = [1, 3, 4, 2];
let r = [];
for (let i = 0; i < a.length - 1; i++) {
r[i] = a.map((v, index) => {
if(index == i) return a[i+1];
if(index == i + 1) return a[i];
return v;
});
}
console.log(r);
Using a simple for loop:
let a = [1, 3, 4, 2],
result = [];
for(let i = 0; i < a.length - 1; i++) { // notice that the loop ends at 1 before the last element
let copy = a.slice(0); // copy the array
let temp = copy[i]; // do the swaping
copy[i] = copy[i + 1];
copy[i + 1] = temp;
result.push(copy); // add the array to result
}
console.log(result);