I have an alright understanding of how Heap's Algorithm works, but I can't figure out how to add each unique permutation into an array and return it based on the recursive nature of the algo.
why is it only adding the same permutation but the console log prints out the different ones?
var swap = function (array, pos1, pos2) {
var temp = array[pos1];
array[pos1] = array[pos2];
array[pos2] = temp;
};
var heapsPermute = function (array, n, results = []) {
n = n || array.length;
if (n === 1) {
results.push(array);
console.log(array);
} else {
for (var i = 1; i <= n; i += 1) {
heapsPermute(array, n - 1, results);
if (n % 2) {
var j = 1;
} else {
var j = i;
}
swap(array, j - 1, n - 1);
}
}
return results;
};
console.log(heapsPermute(['a', 'b', 'c', 'd']));
You need to add a copy of the array, instead of the array and it's object reference.
results.push(array.slice());
// ^^^^^^^^
var swap = function (array, pos1, pos2) {
var temp = array[pos1];
array[pos1] = array[pos2];
array[pos2] = temp;
};
var heapsPermute = function (array, n, results = []) {
n = n || array.length;
if (n === 1) {
results.push(array.slice());
} else {
for (var i = 1; i <= n; i += 1) {
heapsPermute(array, n - 1, results);
if (n % 2) {
var j = 1;
} else {
var j = i;
}
swap(array, j - 1, n - 1);
}
}
return results;
};
console.log(heapsPermute(['a', 'b', 'c', 'd']).map(a => a.join(' ')));
.as-console-wrapper { max-height: 100% !important; top: 0; }
Related
I wrote the code, but for some reason it displays the index 1, 2, 3, while 3 + 4 will in no way be equal to target (6).
var twoSum = function(nums, target) {
let sum = [];
var n = 2;
for(let i = 0; i < nums.length; i++) {
for(let a = 1; a < nums.length; a++) {
if(nums[i] + nums[a] == target) {
sum.push(i);
sum.push(a);
}
}
}
let unique = sum.filter((e, i) => sum.indexOf(e) === i )
return unique/* .slice(0, n); */
};
console.log(twoSum([1,3,4,2],6))
Input
[1,3,4,2]
6
Output
[1,2]
Expected
[2,3]
As per my comment, start the inner loop at a = i + 1 to avoid summing numbers with themselves as well as to avoid checking the same combination twice, e.g (1, 2) and (2, 1):
var twoSum = function(nums, target) {
let sum = [];
let n = 2;
for (let i = 0; i < nums.length; i++) {
for (let a = i + 1; a < nums.length; a++) {
if (nums[i] + nums[a] === target) {
sum.push(i);
sum.push(a);
}
}
}
let unique = sum.filter((e, i) => sum.indexOf(e) === i )
return unique/* .slice(0, n); */
};
I am trying to solve the fibonacci in recrusive way and I think i got a bug in my code.I can't figurer out where it is.
Example:
fib(4) === 3
function fib(n, array = [0, 1], count = 0) {
if (n == 0) {
return 0;
}
if (n == 1) {
return 1;
}
array.push(array[count] + array[count + 1]);
console.log(array)
if (n === array.length-1) {
return array.pop()
}
fib(n, array, count + 1);
}
let ans=fib(2)
console.log(ans)
you can do by this way using recursion
var i = 0, a = 0, b = 1, c = 0;
var out = "";
function fibonacci(n){
i = 0;
if(i < n){
out += a + ",";
c = a + b;
a = b;
b = c;
i++;
console.log(out);
fibonacci(n - i);
}
}
fibonacci(10);
I am trying to debug one online coding platform problem. The problem I am facing is to return element occurring most often in array. I am interested in correcting my current code than trying other methods.
function findMostOccured(M, A) { //value of elements in A should not be greater than M
var N = A.length;
var count = new Array(M + 1);
var i;
for (i = 0; i <= M; i++)
count[i] = 0;
var maxOccurence = 1;
var index = -1;
for (i = 0; i < N; i++) {
if (count[A[i]] > 0) {
var tmp = count[A[i]];
if (tmp > maxOccurence) {
maxOccurence = tmp;
index = i;
}
count[A[i]] = tmp + 1;
} else {
count[A[i]] = 1;
}
}
return A[index];
}
Given M = 3 and A = [1, 2, 3, 3, 1, 3, 1]. It should return 3 or 1.
var arr = [1, 2, 3, 3, 1, 3, 1];
var M = 3;
function findMostOccured(M, arr) {
var obj = {};
var result = [];
for (let i = 0; i < arr.length; i++) {
if (obj[arr[i]]) {
obj[arr[i]] = obj[arr[i]] + 1;
} else {
obj[arr[i]] = 1;
}
}
for (var key in obj) {
if (obj[key] === M) {
result.push(parseInt(key));
}
}
return result;
}
console.log(findMostOccured(3, arr));
I've got the following function:
var object = [12,23,14,35,24];
//debugger;
function f(objects, sum){
var curSum = objects[0];
var maxSum = 0;
var start = 0;
for (var i = 1; i < objects.length; i++) {
while(curSum > sum && start < i){
curSum -= objects[start];
start++
}
maxSum = Math.max(maxSum, curSum);
curSum += objects[i];
if(curSum <= sum){
maxSum = Math.max(curSum, maxSum);
}
}
return maxSum;
}
console.log(f(object,50));
I'd expect the highest possible sum to be 50, due to elements 12,14,24
However, I can only manage to get to 49. What am I missing here?
You could take a recursive approach by iterating the array and check if the temporary array has the right sum and check against the result for eiter replaceinf smaller sums or push to same sum parts.
function combine(array, sum) {
function fork(i, p) {
var s = p.reduce((a, b) => a + b, 0),
l = (result[0] || []).reduce((a, b) => a + b, 0);
if (i === array.length) {
if (s <= sum) {
if (l < s) {
result = [p];
}
if (l === s) {
result.push(p);
}
}
return;
}
fork(i + 1, p.concat(array[i]));
fork(i + 1, p);
}
var result = [];
fork(0, []);
return result;
}
console.log(combine([12, 23, 14, 35, 24], 50));
.as-console-wrapper { max-height: 100% !important; top: 0; }
This function will receive an array of positive integers and it should return a new array with the factorial of each number.
So far I came up with this but it doesn't work and I don't know where is the problem, any ideas?
function getFactorials (nums) {
let arr = [];
for(let i = 0; i < nums.length; i++) {
if(nums[i] <= 1) {
return 1;
} else {
arr.push(nums[i] * getFactorials(nums[i] - 1));
}
}
return arr;
}
try this use map
var a = [1, 2, 3, 4, 5];
function fact(x) {
return (x == 0) ? 1 : x * fact(x-1);
}
console.log(a.map(fact));
Try the following:
function getFactorials (nums) {
let arr = [];
for(let i = 0; i < nums.length; i++) {
let j, fact;
fact=1;
for(let j=1; j<=nums[i]; j++)
{
fact= fact*j;
}
arr.push(fact);
}
return arr;
}
let res = getFactorials([5,9])
console.log(res);
Try this way:
function factorial(n) {
if (n === 0) {
return 1;
}
return n * factorial(n - 1);
}
function getFactorials (nums) {
let arr = [];
for(let i = 0; i < nums.length; i++) {
arr.push(factorial(nums[i]));
}
return arr;
}
getFactorials([6,5,3])
const factorial = (n) => {
let res = [];
while(n != 0){
//get all integers less than or equal to n
res.push(n);
n--;
}
return res.reduce((x, y) => {
return x * y;
//reduce the array of integers into a single number via multiplication
});
}
const nums = [1, 2, 3, 4, 5];
const factorialArr = (arr) => {
return arr.map(n => {
//iterate through a list of numbers and return the factorial of each
return factorial(n);
});
}
const result = factorialArr(nums);
console.log(result) -> // Array [ 1, 2, 6, 24, 120 ]
function getFactorials(nums) {
const factNums = nums.map(
function factorial (num) {
return (num == 0 ? 1 : num * factorial(num -1));
}
)
return factNums;
}
#include <stdio.h>
int iFactorial(int iCount)
{
int iProduct = 1;
int iNumber = 1;
while (iNumber <= iCount)
{
iProduct *= iNumber;
iNumber++;
}
return iProduct;
}
int main(void)
{
int iFac[10] = {0};
int iCount = 0;
for (iCount = 0; iCount < 9; iCount++)
iFac[iCount] = iFactorial(iCount);
for (iCount = 0; iCount < 9; iCount++)
printf("\nThe value of the factorial is %d\n", iFac[iCount]);
return 0;
}