I have an array and i want to get all combination of sums of its number.
let arr=[1,2,3,4,5];
1st iteration : 1+2=3,1+3=4, 1+4=5, 1+5=6
and array becomes arr[1,2,3,4,5,6]
2nd iteration : 2+1=3,2+3=5, 2+4=6, 2+5=7
and array becomes arr[1,2,3,4,5,6,7]......
and 1+2+3=6, 1+2+4=7
.
.
.
and 1+2+3+4=10
.
.
.
and 1+2+3+4+5=15
and final array becomes =[1,2,3,4,5,6,7,8,9,10,11,15]
Can anyone help me to build an algo for this?
Here is what i have tried so far, I tried to prepare array of possible sub arrays of arr but could not get all combination.
let arr=[1,2,3,4,5];
let a=[];
for(let i=0; i < arr.length; i++){
for(let j=0; j < arr.length; j++){
let b=[];
for( let k=i; k<=j; k++ ){
b.push(arr[k]);
}
a.push(b);
}
}
console.log(a);
You can use a dictionary or associative array (which JavaScript's arrays are) to store which sums can be made, by using the sum as the index and setting the element to 'true', similar to creating a sieve; you can then iterate over this sparse array efficiently with for in.
function sums(values) {
var dictionary = [];
for (var i in values) {
var temp = [values[i]]; // start with value by itself
for (var j in dictionary) {
temp.push(values[i] + Number(j)); // sum of value and values already in dictionary
}
for (var k in temp) {
dictionary[temp[k]] = true; // transfer values to dictionary
}
}
var output = [];
for (var i in dictionary) {
output.push(Number(i)); // convert dictionary to array of values
}
return output;
}
document.write(sums([2,5,11,16]));
Related
I have a 2D array and two 1D arrays. I have to compare the 1D array with the 2D array in JavaScript. I have written the following code but it is not working. Any help would be appreciated.
<!DOCTYPE html>
<html>
<body>
<script>
var arr = [
['Cat', 'Brown', 2],
['Parrot', 'Brown', 1]
];
var col = [0,1];
var key = ['Parrot','Brown'];
for (var i = 0; i < arr.length; i++){
for (var j = 0; j < col.length; j++){
var isMatched = arr[i][col[j]] == key[j];
if (isMatched){
// write arr index
document.write(i);
// it should write 1 but writing 001
}
}
}
</script>
</body>
</html>
I am using 'col' array to store index of columns to be compared like in this case 0 for first column with values cat, parrot and so on. What I need is if all elements of 'key' array matches with any array of 'arr' then it should print true and index of matching array in 'arr'
Based on what you've mentioned in the comments, if you just want to check whether all the values in key array are contained in the other list of arrays arr. Then you don't necessarily need a col array and the following script should work.
var arr = [
["Cat", "Brown", 2],
["Parrot", "Brown", 1],
];
var key = ["Parrot", "Brown"];
for (let i = 0; i < arr.length; i++) {
// Current array from array of arrays, which you want to search
let array_to_be_searched = arr[i];
// Let's initially assume that all the elements of the key are included in this one
let isMatched = true;
for (let j = 0; j < key.length; j++) {
if (!array_to_be_searched.includes(key[j])) {
isMatched = false;
break;
}
}
// If our assumption is correct
if (isMatched) {
document.write(true); // Write true :)
document.write(i); // Index of current array
}
}
The output you are getting is "011" and not "001" are the index of "parrot" in key and then two time the index of "brown" in key.
After reading you comment I understood that you meant that "parrot" and "brown" should be found as a set in on of arr sub arrays.
So you have made the wrong comparisons - check this answerer to do the right one -
Check if an array contains any element of another array in JavaScript
and them make one loop to make the comparison.
I try to return a multidimensional array into a function to iterate it but I'm not sure what's wrong with my logic
const arr = [[1,2], [3,4],[5,6]]
for(let i = 0; i < thirdInterval.length-1; i++){
getNumbers(thirdInterval[i], thirdInterval[i+1])
}
The result that I want to achieve is return the first element into the first argument of the function and the second element of the array into the second argument of the function.
What you are doing here is looping through the array and getting only the array at the index i, e.g arr[0] which is [1,2]. and (thirdInterval[i], thirdInterval[i+1]) is actually equals to ([1,2], [3,4])
to access the first and second elements you should address them like the following:
for(let i = 0; i < thirdInterval.length-1; i++){
getNumbers(thirdInterval[i][0], thirdInterval[i][1])
}
const arr = [[1,2][3,4][5,6]];
for (var i = 0; i < arr.length; i++;) {
func(arr[i][0], arr[i][1];
}
You are iterating an array with sub-arrays, which means that thirdInterval[i] contains two items. You can get the items using the indexes thirdInterval[i][0] and thirdInterval[i][1], but since you're calling a function with those values, you can use spread instead - getNumbers(...thirdInterval[i]).
In addition, the loop's condition should be i < thirdInterval.length if you don't want to skip the last item.
Demo:
const thirdInterval = [[1,2],[3,4],[5,6]]
const getNumbers = console.log // mock getNumbers
for (let i = 0; i < thirdInterval.length; i++) {
getNumbers(...thirdInterval[i])
}
Say that I have a data structure of n elements and a function check(element1, element2) which performs some kind of checkup on two elements. I need to check exactly all possible pairs of elements. Using combinatorics it is easy to deduce that we need to perform exactly 'n choose 2' binomial coefficient iterations ( n*(n-1)/2 iterations)
So if my data structure is an array, the following nested loops would work:
for(let i = 0; i < elements.length; i++) {
for(let j = i + 1; j < elements.length; j++) {
check(elements[i], elements[j]);
}
}
This way we check the first element with all the others, the second element with elements 3 to n (since we already checked it with the first one), the third with elements 4 to n and so on and so forth. However if 'elements' was a JSON where the key to each element is not an integer, how can we achieve this effect? Obviously we can ensure that we perform all checkups with the following code:
for(var key1 in elements) {
for(var key2 in elements) {
if(key1 != key2) {
check(elements[key1], elements[key2]);
}
}
}
However obviously we are doing a lot of checkups more than once resulting in n^2 iterations.
What method can I use to achieve the same result as in the example with the array?
If you put all the keys you're going to be looping into an array using Object.keys() then you can use your standard for loop to "skip" over previously seen keys like so:
const keys = Object.keys(elements);
for(let i = 0; i < keys.length; i++) {
const key1 = keys[i];
for(let j = i + 1; j < keys.length; j++) {
const key2 = keys[j];
check(elements[key1], elements[key2]);
}
}
Perhaps you could get the list of keys in an array:
let elements = { a: 1, b: 2, c: 3 };
let keys = Object.keys(elements).sort(); // Sorts the keys array alphabetically, and thus simulating the numbers example and be sure you're not repeating "lower" order key after passing it
for(let i = 0; i < keys.length; i++) {
for(let j = i + 1; j < keys.length; j++) {
// check(elements[keys[i]], elements[keys[j]]);
console.log(elements[keys[i]], elements[keys[j]])
}
}
output:
1 2
1 3
2 3
I want to display an array without showing of indexes. The for loop returns the array indexes which is not showing in usual declaration.
I want to send an array like [1,2,3 ...] but after retrieving from for loop, I haven't the above format. How can I store my values as above.
var a = [];
for (var i = 1; i < 8; i++) {
a[i] = i;
};
console.log(a);
Outputs:
[1: 1, 2: 2 ...]
Desired output:
[1,2,3]// same as console.log([1,2,3])
Array indices start at zero, your loop starts at 1, with index 0 missing you have a sparse array that's why you get that output, you can use push to add values to an array without using the index.
var a = [];
for (var i = 1; i < 8; i++) {
a.push(i);
};
console.log(a);
The problem is that you start your array with 1 index, making initial 0 position being empty (so called "hole" in array). Basically you treat array as normal object (which you can do of course but it defeats the purpose of array structure) - and because of this browser console.log decides to shows you keys, as it thinks that you want to see object keys as well as its values.
You need to push values to array:
var a = [];
for (var i = 1; i < 8; i++) {
a.push(i);
};
I have to disagree with the answers provided here. The best way to do something like this is:
var a = new Array(7);
for (var i = 0; i < a.length; i++) {
a[i] = i + 1;
}
console.log(a);
Your code is making each index equal to i, so use it this way
var a = [];
for (var i = 1; i < 8; i++) {
a.push(i);
};
console.log(a);
I have already first column sorted 2D Javascript Array
var arr = [[12.485019620906078, 236.90974767017053|166.7059999999991|244.15878139435978|156.54100000000025],
[12.735148445872, 238.038907254076|203.3000000000006|245.7107245706185|213.46500000000034],
[47.15778769718685, 238.038907254076|203.3000000000006|244.15878139435978|156.54100000000025],
[47.580051233708595, 236.90974767017053|166.7059999999991|245.7107245706185|213.46500000000034]
];
I am trying to remove the duplicates based on the last two values in the [i][1] part of array
244.15878139435978|156.54100000000025
245.7107245706185|213.46500000000034
using following function which is not giving correct output
function remDupes(arr)
{
for(var i=0; i<arr.length-1; i++)
{
var i1 = arr[i][1].split("|");
var item1 = i1[2]+"|"+i1[3];
for(var j=i+1; j<arr.length; j++)
{
var i2 = arr[j][1].split("|");
var item2 = i2[2]+"|"+i2[3];
if(item1 == item2)
{
arr.splice(j,1);
}
}
}
return arr;
}
I am looking for final array like this.
[
[12.485019620906078, 236.90974767017053|166.7059999999991|244.15878139435978|156.54100000000025],
[12.735148445872, 238.038907254076|203.3000000000006|245.7107245706185|213.46500000000034]
]