possible combinations get a targetTotal counting itself as a case - javascript

Trying to count possible combinations to get a targetTotal. Using powerSet returns the sum without adding itself. E.g [1,2,3,5] returns [3+1] for a targetSum of 4, whereas I expect to get [1+1+1+1], [2+2], [3+1].
Do you have any ideas how I could make it count itself first as a case?
function powerset(arr) {
var ps = [[]];
for (var i=0; i < arr.length; i++) {
for (var j = 0, len = ps.length; j < len; j++) {
ps.push(ps[j].concat(arr[i]));
}
}
return ps;
}
function sum(arr) {
var total = 0;
for (var i = 0; i < arr.length; i++)
total += arr[i];
return total
}
function findSums(numbers, targetSum) {
var sumSets = [];
var numberSets = powerset(numbers);
for (var i=0; i < numberSets.length; i++) {
var numberSet = numberSets[i];
if (sum(numberSet) == targetSum)
sumSets.push(numberSet);
}
return sumSets;
}
Example invocation:
findSums([1,2,3,4,5],6); [[2,3], [1,4], [5], [1,1,1,1,1,1], [2,2,2], [3,3]]

Related

Processing error "Syntax error expected ; but found i"

I am trying to write a matrix library in processing using javascript but keep getting the error above on line 5. I can't seem to spot what is causing the error so any help would be appreciated.
The goal is to implement the matrix product function.
function Matrix(rows,cols){
this.rows = rows;
this.cols = cols;
this.data = [];
for(var i = 0; i < this.rows; i++){
//assign every row an array
this.data[i] = [];
for (var j = 0; j < this.cols; j++){
//assign every column an array
this.data[i][j] = 0;
}
}
}
Matrix.prototype.multiply = function(n){
if(n instanceof Matrix){
// Matrix product
if (this.cols !== n.rows) {
console.log('Columns of A must match rows of B.');
return undefined;
}
let result = new Matrix(this.rows, n.cols);
for (let i = 0; i < result.rows; i++) {
for (let j = 0; j < result.cols; j++) {
// Dot product of values in col
let sum = 0;
for (let k = 0; k < this.cols; k++) {
sum += this.data[i][k] * n.data[k][j];
}
result.data[i][j] = sum;
}
}
return result;
}
else{
for(var i = 0; i < this.rows; i++){
for (var j = 0; j < this.cols; j++){
//multiply scalar
this.data[i][j] *= n;
}
}
}
}
I found the error it was just a curly bracket in the wrong place!

Arrays with elements less or equal to the elements in given array

What is the most JS-style way to solve the following problem?
Given an array A, find all arrays B, such that for i <= A.length: B[i] <= A[i]. Example of what I expect:
#Input
A = [1,2,0]
#Output
B = [[0,0,0],
[1,0,0],
[1,1,0],
[1,2,0],
[0,1,0],
[0,2,0]]
In Python I used:
B = [[]];
for t in [range(e+1) for e in A]:
B = [x+[y] for x in B for y in t]
Thanks in advance!
Use the following code (any loop for one item of the array a):
var a = [1, 2, 0], b = [];
for (var i = 0; i < a[0]; i++) {
for (var j = 0; j < a[1]; j++) {
for (var k = 0; k <= a[2]; k++) {
b.push([i, j, k]);
}
}
}
If you know the numebr of items in the array a only on runtime, use the following recursive function:
function fillArray(source, dest, recursionLevel, tempArr) {
if (recursionLevel >= source.length) {
dest.push(tempArr);
return;
}
for (var i = 0; i <= source[recursionLevel]; i++) {
var tempArr2 = tempArr.slice(); // Copy tempArr
tempArr2.push(i);
fillArray(source, dest, recursionLevel + 1, tempArr2);
}
}
fillArray(a, b, 0, []);
I found this solution. I'm sure it can be coded in a much nicer way. However, it works and I hope you find it useful
all_combinations(A){
var B = [];
for (var i = 0; i < A[0] + 1; i++) {
B.push([i]);
}
for (var i = 1; i < A.length; i++) {
var _tmp_array = [];
for (var j = 0; j < A[i] + 1; j++) {
for (var k = 0; k < B.length; k++) {
var _new_element = B[k].concat([j]);
_tmp_array.push(_new_element);
}
}
B = _tmp_array;
}
return B;
}

Array by Reference vs Array by Value in Javascript

I'm reading Data Structures and Algorithms with Javascript by O'reily and it states the following:
Shallow copy (two arrays point to the same location in memory):
var nums = [];
for (var i = 0; i < 100; ++i) {
nums[i] = i+1;
}
var samenums = nums;
nums[0] = 400;
print(samenums[0]); // displays 400
Deep copy:
function copy(arr1, arr2) {
for (var i = 0; i < arr1.length; ++i) {
arr2[i] = arr1[i];
}
}
Now the following code fragment produces the expected result:
var nums = [];
for (var i = 0; i < 100; ++i) {
nums[i] = i+1;
}
var samenums = [];
copy(nums, samenums);
nums[0] = 400;
print(samenums[0]); // displays 1
Why is a function required in order to create deep copies?
As stated in the comments, the function is purely for aesthetics and reusability, and is not strictly necessary.
You could refactor your example:
function copy(arr1, arr2) {
for (var i = 0; i < arr1.length; ++i) {
arr2[i] = arr1[i];
}
}
var nums = [];
for (var i = 0; i < 100; ++i) {
nums[i] = i+1;
}
var samenums = [];
copy(nums, samenums);
nums[0] = 400;
print(samenums[0]); // displays 1
into this equivalent function-less example:
var nums = [];
for (var i = 0; i < 100; ++i) {
nums[i] = i+1;
}
var samenums = [];
for (var i = 0; i < nums.length; ++i) {
samenums[i] = nums[i];
}
nums[0] = 400;
print(samenums[0]); // displays 1

JavaScript arrays - Finding the number of combinations of 2 elements

I come from a Ruby background, which features an enumerable class. In Ruby, I can easily find combinations of array elements.
array.combination(2).count
I know that JavaScript doesn't feature such built in functions, so I was wondering how I could implement this in JS. I was thinking something like
I have an array as follows
var numbers = [9,7,12]
var combos = []
for (var i = 0; i < numbers.length; i++) {
combos.push([numbers[i], numbers[i+1])
}
By the way, the possible combos are
[9,7], [9,12] and [7,12]
so by calling the length function on this array, 3 would be returned.
Any ideas?
How about:
for (var i = 0; i < numbers.length; i++)
for (var j = i + 1; j < numbers.length; j++)
combos.push([numbers[i], numbers[j]]);
Are you strictly talking about 2-combinations of the array or are you interested in a k-combinations solution?
Found this in this gist
function k_combinations(set, k) {
var i, j, combs, head, tailcombs;
if (k > set.length || k <= 0) {
return [];
}
if (k == set.length) {
return [set];
}
if (k == 1) {
combs = [];
for (i = 0; i < set.length; i++) {
combs.push([set[i]]);
}
return combs;
}
// Assert {1 < k < set.length}
combs = [];
for (i = 0; i < set.length - k + 1; i++) {
head = set.slice(i, i+1);
tailcombs = k_combinations(set.slice(i + 1), k - 1);
for (j = 0; j < tailcombs.length; j++) {
combs.push(head.concat(tailcombs[j]));
}
}
return combs;
}
Here's a recursive function, which should work for any number:
function combination(arr, num) {
var r= [];
for(var i = 0 ; i < arr.length ; i++) {
if(num===1) r.push([arr[i]]);
else {
combination(arr.slice(i+1), num-1).forEach(function(val) {
r.push([].concat(arr[i], val));
});
}
}
return r;
} //combination
Working Fiddle

Undefined Array

i am trying to make a for loop out of a var variable but it doesn't work. For some reason tempArray.length is always undefined, it never return anything different. Can anyone help ?
for (i = 0; i < arr.length; i++) {
tempArray = arr[i];
for (k = 0; k <= tempArray.length; i++) {
if (tempArray[k] != /[0-9]+/) {
countinue;
}
var tempArray = [];
for (i = 0; i < arr.length; i++) {
tempArray = arr[i];
}
for (k = 0; k <= tempArray.length; i++) {
if (tempArray[k] != /[0-9]+/) {
countinue;
}
}
Temp array needs to be set to an array.
Loop through and build tempArray first, then loop through the temp array and do what ever you need to.

Categories