Leetcode Question - First Missing Positive - javascript

Given an array of integers, find the first missing positive integer in linear time and constant space. In other words, find the lowest positive integer that does not exist in the array. The array can contain duplicates and negative numbers as well.
For example, the input [3, 4, -1, 1] should give 2. The input [1, 2, 0] should give 3.
I did this but not able to find what is the error in my logic when taking input as 1. it is giving output as undefined instead of 2.
var firstMissingPositive = function(nums) {
nums.sort(compare);
var arr = [];
for (let i = 0; i < nums.length; i++) {
if (nums[i] > 0)
arr.push(nums[i]);
}
if (arr.length == 0)
return 1;
else {
for (let i = 0; i < arr.length; i++) {
if (!(arr[0] == 1))
return 1;
else if (i > 0)
if (!(arr[i - 1] + 1 == arr[i]))
return i + 1;
else if ((i + 1) == arr.length)
return arr[i] + 1;
else if ((arr[i] == i + 1)) // && (arr[i+1] == arr[i]+1 ))
continue;
else
return i + 1;
}
}
};
function compare(a, b) {
return a - b;
}
Output:

Since O(n) is a requirement, we'll have to prepare some hash table of possible numbers. It will just be the length of the input array (+2 why not), containing possible number 1..n. We iterate the input array and for each number we match (if applicable) it's position = value in the array of possible numbers. We set it to -1 so we won't choose it. Finally, we iterate the possible numbers that are left and pick the first one.
var firstMissingPositive = function(nums) {
var possible = [];
for (var i = 0; i < nums.length + 2; i++) {
possible.push(i);
}
for (var i = 0; i < nums.length; i++) {
var number = nums[i];
if (number <= nums.length && number > 0) {
possible[number] = -1;
}
}
for (var i = 0; i < possible.length; i++) {
if (possible[i] > 0) {
return possible[i]
}
}
};
console.log(firstMissingPositive([3, 4, -1, 1]))
console.log(firstMissingPositive([0, 1, 2]))
console.log(firstMissingPositive([1]))

Related

Fast Algorithm That Can Create Ulam Sequence of n Elements

I've been trying to solve this kata on codewars.
I've got an algorithm, but it's apparently too slow to pass the test. It can create sequence of 2450 numbers in just under 1.6 seconds. I don't need the solution but the hint or something to help me to make my algorithm faster.
function ulamSequence(u0, u1, n) {
// create an array with first two elements in it
const seq = [u0, u1];
// create a loop that checks if next number is valid and if it is, push it in seq
num: for (let i = u1 + 1; seq.length < n; i++) {
let sumCount = 0;
for (let k = 0; k < seq.length - 1; k++) {
if (seq.indexOf(i - seq[k]) > k && ++sumCount === 2) { continue num; }
}
sumCount === 1 ? seq.push(i) : "";
}
return seq;
}
Here's an idea: have an array sums so that sums[N] keeps the number of possible summations for N. For example, for U(1,2) sums[3] will be 1 and sums[5] will be 2 (1+4, 2+3). On each step, locate the minimal N so that N > last item and sums[N] == 1. Add N to the result, then sum it with all previous items and update sums accordingly.
function ulam(u0, u1, len) {
let seq = [u0, u1]
let sums = []
let last = u1
sums[u0 + u1] = 1
while (seq.length < len) {
last += 1
while (sums[last] !== 1) {
last += 1
}
for (let n of seq) {
let s = n + last
sums[s] = (sums[s] || 0) + 1
}
seq.push(last)
}
return seq
}
console.time()
ulam(1, 2, 2450)
console.timeEnd()
function ulamSequence(u0, u1, n) {
const seq = [u0, u1];
const set = new Set(seq);
for (let i = u1 + 2; seq.length < n; i++) {
let sumCount = 0;
for (let k = 0; k < seq.length - 1; k++) {
if (set.has(i - seq[k])) {
sumCount++;
if (sumCount === 2) {
continue;
}
}
}
if (sumCount === 1) {
seq.push(i);
set.add(i);
}
}
return seq;
}

Loop the array, and add values to start Javascript

What i need to do - simple task - I am looping the array. When array[i] === 0;
i want to +1 to start, it will be the same for array[i] === 1.
But when array[i] will go back (be back where it was a moment ago) i don't want to +1 to start, and i did that code :
var start = 0;
var array = [0,1,0,0,1,0,0,1];
for (i=0; i < array.length; i ++) {
if (array[i] === 0) {
start += 1;
if (array[i + 1] === 1) {
start -= 1;
}
}
else if (array[i] === 1) {
start += 1;
if (array[i + 1] === 0) {
start -= 1;
}
}
}
console.log(start)
But what if array = [0,1,1,1,0,0,0,1,0,0,0,1]; , if array[i] will go back where it was a long time ago? I dont want then +1 to start.
Imagine 0 and 1 like -1 and +1 on chart, so console.log(start) from array = [0,1,1,1,0,0,0,1,0,0,0,1] should be 5.
My code is some kind of hard coding, have you any ideas how to fix that?
Thanks for answers in advance!
Example from comments
[0,1,1,1,0,0,0,1,0,0,0,1] should produce a result of 5; you need to imagine 0 == -1 and 1 == +1.
Then the array looks like [-1,+1,+1,+1,-1,-1,-1,+1,-1,-1,-1,+1] and begins this from 0 we have 5 positions where i was only 1 time.
As it looks like, you need to count the changes of the values in the array. You need to store the last value for checking the next value. If the last value and the actual value is different, you got a change and need to count.
function getChanges(array) {
var count = 0,
last = array[0],
i;
for (i = 1; i < array.length; i++) {
if (last !== array[i]) {
count++;
last = array[i];
}
}
return count;
}
console.log(getChanges([0, 1, 0, 0, 1, 0, 0, 1]));
console.log(getChanges([0, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1]));
As #nurdyguy has pointed out, your call for array[i+1] will be out of bounds for the last element. I have flipped the comparison to the previous element and started the loop on the second element to counter this.
You seem to be calculating +=1 regardless of the binary result then only -=1 when the next element in the array differs so essentially i think you have the opposite of what you are looking for :
var start = 0;
var array = [0,1,0,0,1,0,0,1];
for (i=1; i < array.length; i++) {
if (array[i] === array[i-1]) {
start++;
}
}
Now if you want to calculate the times the element changes from each step then you can just flip the logical:
var start = 0;
var array = [0,1,0,0,1,0,0,1];
for (i=1; i < array.length; i++) {
if (array[i] !== array[i-1]) {
start++;
}
}
console.log("The result is: " + start) // The result is: 5
I think this is what you are after, please elaborate if not.
Edit:
Apologies, I did test your other array and the result was also 5.
What you are looking for is this then:
var start = 0;
var array = [0,1,1,1,0,0,0,1,0,0,0,1];
for (i=0; i < array.length; i++) {
start += array[i];
}
console.log("The result is: " + start) // The result is: 5
If the array of 0 and 1 is only as an example then use a logical:
var start = 0;
var array = [0,1,1,1,0,0,0,1,0,0,0,1];
for (i=0; i < array.length; i++) {
array[i] == 1 ? ++start : +-start;
}
console.log("The result is: " + start) // The result is: 5
or:
var start = 0;
var array = [0,1,1,1,0,0,0,1,0,0,0,1];
for (i=0; i < array.length; i++) {
if (array[i] == 1) {
++start
}
}
console.log("The result is: " + start) // The result is: 5
If the array becomes [-1,1,1,1,-1,-1,-1,1,-1,-1,-1,1] like you said then the result is not 5, it's -3?

Find first missing number in a sequence of numbers

I am trying to figure out how to find the first missing number of a sequence of numbers like this (1,2,3,5,6,9,10,15)
I want to put the first missing number, #4, into an variable for later use but don't know how to do so?
I have tried this but this only gives me the last number:
var mynumbers=new Array(1,2,3,6,9,10);
for(var i = 1; i < 32; i++) {
if(mynumbers[i] - mynumbers[i-1] != 1) {
alert("First missing number id: "+mynumbers[i]);
break;
}
}
First of all it gives me the first number after an "hole" in the numbersequence, secondly it continues to alert all numbers comming after an "hole" if I don't insert an break. I only want the first missing number of an numbersequence from 1 - 32. How do i do so?
Hoping for help and thanks in advance ;-)
How about this
var mynumbers = new Array(1,2,3,6,9,10);
var missing;
for(var i=1;i<=32;i++)
{
if(mynumbers[i-1] != i){
missing = i;
alert(missing);
break;
}
}
The O(n) solutions are easy , but this is a common interview question and often we look for O(log n) time solution. Here is the javascript code. It's basically a modified binary search.
function misingNumInSeq(source, min = 0, max = source.length - 1){
if(min >= max){
return min + 1;
}
let pivot = Math.floor((min + max)/2);
// problem is in right side. Only look at right sub array
if(source[pivot] === pivot + 1){
return misingNumInSeq(source, pivot + 1, max);
} else {
return misingNumInSeq(source, min , pivot);
}
}
Output
misingNumInSeq([1,2,3,5,6,9,10,15])
4
By if(mynumbers[i] - mynumbers[i-1] != 1), you mean to say the series will always be incrementing by 1?
var missing = (function (arr) {
var i;
for (i = 0; i < arr.length; ++i) {
if (i + arr[0] !== arr[i]) return i + arr[0];
}
if (i < 32) // if none missing inside array and not yet 32nd
return i + arr[0]; // return next
}([1,2,3,6,9,10])); // 4
alert(missing);
You're going to need the break no matter what. That's what it's there for; to stop the loop from continuing on to the end. And you should use the length of the array instead of hardcoding 32 as the end condition, because your numbers only go up to 32, but there are possibly holes in the list so there will not be 32 elements in the array.
Since you know that each element should be 1 more than the previous element, then the number in the hole is clearly mynumbers[i - 1] + 1.
var mynumbers = new Array(1,2,3,6,9,10);
for(var i = 1; i < mynumbers.length; i++) {
if(mynumbers[i] - mynumbers[i-1] != 1) {
alert("First missing number id: " + (mynumbers[i - 1] + 1));
break;
}
}
EDIT: This only holds true for the missing number not being 1. To catch that, you will need to check if (mynumbers[0] != 1)
Edit:
function findFirstMissing(array) {
for (var i = 0; i < array.length; i++) {
if (i+1 !== array[i]) {
return i+1;
}
}
}
function findFirstMissing(array) {
for (var i = 0; i < array.length; i++) {
if (array[i+1] - array[i] !== 1) {
return array[i] + 1;
}
}
}
If you do it this way then storing it in a variable is easy:
var missing = findFirstMissing(array);
const firstNonConsecutive = arr => arr.find((el, i, arr) => (arr[i] - arr[i-1]) !== 1 && i !== 0)
this solution work for an array of positive numbers.
A solution using array.reduce to find the first positive missing integer.
function solution(A) {
return [...A].sort().reduce((acc, curr, i, arr) => {
if (acc > curr) {
arr.splice(1);
return acc;
}
else if (arr[i + 1] - curr > 1 || arr.length === i + 1) {
arr.splice(1);
return curr + 1;
}
return acc;
}, 1);
}
And here are few test cases:
console.log('solution([1, 3, 6, 4, 1, 2])', solution([1, 3, 6, 4, 1, 2]) === 5)
console.log('solution([1, 3, 2, 8, 4])', solution([1, 3, 2, 8, 4]) === 5)
console.log('solution([1])', solution([1]) === 2)
console.log('solution([-1])', solution([-1]) === 1)
console.log('solution([0])', solution([0]) === 1)
console.log('solution([-1, -4, -5, -6, -190343])', solution([-1, -4, -5, -6, -190343]) === 1)
Sometimes you just want simple if you know it's a small array:
let numbers = [1,2,3,6,9,10]
let m = 0
for (const i of numbers) if (i > ++m) break
console.log(m) // 4
Works if you remove 1 from start of array:
numbers = [2,3,6,9,10]
m = 0
for (const i of numbers) if (i > ++m) break
console.log(m) // 1
If the array can be contiguous, and if so you want the next highest number, then:
numbers = [1,2,3,4,5,6,7,8,9]
m = 0
for (const i of numbers) if (i > ++m) break
if (m == Math.max(...numbers)) m++
console.log(m) // 10
Short and sweet!
//Find the missing number in a series
//output must be 12 in a table of 3 given in below series
let abc = [3, 6, 9, 15, 18, 21, 24];
var def = [],
ghi = [];
for (var i = 1; i <= abc.length; i++) {
if (i !== abc.length) {
var diff = abc[i] - abc[i - 1];
if (def.includes(diff) === false) {
def.push(diff);
} else {
ghi.push(diff);
}
}
}
var finalArr = [];
if (ghi.length > def.length) finalArr = ghi;
else finalArr = def;
var finaldiff = finalArr[0];
var finalVal = abc.find((e, i) => {
if (e !== abc.length) {
var diff = abc[i] - abc[i - 1];
return diff > finaldiff;
}
})
console.log(finalVal - diff);
for(var i = 1; i < mynumbers.length; i++) {
if(mynumbers[i] - mynumbers[i-1] != 1) {
alert("First missing number id: "+mynumbers[i-1]+1);
i = mynumbers.length; // Replace the break
}
}
If you want you can add an initial check : if (mynumbers[0] != 1) { ... }
I think this is the simplest and optimum form of just a 2-step solution.
I think no better solution can be possible for this problem than this one.
This code uses minimum no. of variables, loops, conditionals, built-in functions and all the shitty, sloppy, unnecessary code.
This code can handle array of any length.
var mynumbers = new Array(76,77,78,79,80,81,82,83,84,125);
if(mynumbers.length > 1) {
for(var i=0; i<=mynumbers.length-1; i++) {
if(mynumbers[i+1] - 1 !== mynumbers[i]) {
alert("First Missing Term is : "+parseInt(mynumbers[i]+1));
break;
}
}
}

determine if array is arithmetic or geometric progression (from Coderbyte)

Here is my functional code, as far as coderbyte is concerned.
But I have a feeling it shouldn't be this complicated.
Am I missing a simple trick?
function ArithGeo(arr)
{
var array_type = -1;
if (arr.length <= 2) return true;
var a = arr[1], r = a/arr[0], i;
for (i = 2; i < arr.length; ++i) {
if ((a *= r) == arr[i]){
array_type = "Geometric";
}
else{
array_type = -1;
break;
}
}
if (array_type == "Geometric")
return array_type;
a = arr[1], d = a - arr[0], i;
for (i = 2; i < arr.length; ++i) {
if ((a += d) == arr[i]){
array_type = "Arithmetic";
}
else {
array_type = -1;
break;
}
}
return array_type;
}
ArithGeo([3,9,15,21,27, 28]);
function ArithGeo(arr) {
var diff = arr[1] - arr[0];
var ratio = arr[1] / arr[0];
var arith = true;
var geo = true;
for(var i = 0; i < arr.length - 1; i++)
{
if( arr[i + 1] - arr[i] !== diff )
arith = false;
if(arr[i + 1] / ratio !== arr[i])
geo = false;
}
if(arith === true)
return "arithmetic";
else if(geo === true)
return" geometric";
else
return -1;
}
Here's a simple solution as well. I'm either looking for a geometric pattern, where a given element will be divisible by the previous element, or an arithmetic pattern, where each element increases by a constant amount. Two variables, diff and ratio, contain each pattern to search for throughout the array.
I start by assuming that arith and geo are true, and if I find an example where one is not true, I set its value to false. Note that your code has two for loops, with the exact same conditions. This is a good indication that your code can be condensed into one loop.
With each pass through the loop, I test whether the conditions are present to set either arith or geo to false. Finally, after the loop exits, I will determine if either arith or geo remained true throughout the loop. If not, I return - 1 as the problem from Coderbyte requests.
edit: quick note on my for loop condition. Since I am checking the value of i + 1 with each pass, I make sure that I don't reach out of bounds by setting my exit condition to arr.length - 1. This way, i + 1 can still reach the last element, and will be sure not to overreach.
For arithmetic progression, subtract each element from previous element; their difference should be equal; for geometric, divide each element by the previous element, the ratio should stay the same. As for divide by zero when you meet 0, javascript gives you Inf (and it certainly is not a geometric progression). Because floats are inaccurate, maybe you'd want to store the min and max of these values and then see if they are close enough to each other.
function arithGeo(arr) {
var minRatio = 1/0,
maxRatio = -1/0,
minDiff = 1/0,
maxDiff = -1/0,
epsilon = 0.000001,
i,
ratio,
diff;
if (arr.length <= 2) {
return;
}
for (i = 1; i < arr.length; ++i) {
diff = arr[i] - arr[i - 1];
ratio = arr[i] / arr[i - 1];
minDiff = Math.min(diff, minDiff);
maxDiff = Math.max(diff, maxDiff);
minRatio = Math.min(ratio, minRatio);
maxRatio = Math.max(ratio, maxRatio);
}
if (Math.abs(minDiff - maxDiff) < epsilon) {
return "Arithmetic";
}
if (Math.abs(minRatio - maxRatio) < epsilon) {
return "Geometric";
}
return;
}
alert(arithGeo([3,9,15,21,27,28]));
alert(arithGeo([3,9,15,21,27]));
alert(arithGeo([4,2,1,0.5]));
It might not be the most efficient way to solve the problem, and it doesn't address the epsilon Problem, that Antti Haapala mentioned, but this is my solution to the problem:
function sequenceMatches(arr, fn) {
var compare = fn(arr[0], arr[1]);
for (var i = 2; i < arr.length; i++) {
if (fn(arr[i - 1], arr[i]) !== compare) return false;
}
return true;
}
function ArithGeo(arr) {
if (sequenceMatches(arr, function(a, b) { return b - a; })) return 'Arithemetic';
if (sequenceMatches(arr, function(a, b) { return b / a; })) return 'Geometric';
return -1;
}
I choose to solve that in two different functions, as that helps to clean up the code imho.
function ArithGeo(arr) {
var apCnt = 1;
var gpCnt = 1;
var diff = arr[1] - arr[0]; //ap difference
var div = arr[1]/arr[0]; //gp difference
for(var i=1;i<arr.length-1;i++){ //traverse array
if(arr[i+1] - arr[i] == diff) { //check for ap
apCnt+=1;
}
else if(arr[i+1]/arr[i] == div) { //check for gp
gpCnt+=1;
}
else{
break; //break if not ap or gp
}
}
return apCnt == arr.length-1 ? "Arithmetic": gpCnt == arr.length-1 ? "Geometric": -1; //return if its ap or gp
}
function ArithGeo(arr){
if(arr == null || !Array.isArray(arr)){
return "error";
}
var length = arr.length;
if(length === 0){
return "neither";
}
if(length === 1){
return "both";
}
var arithCount = 0,
geoCount = 0,
d = arr[1] - arr[0],
q = arr[1] / arr[0];
for(var i = length - 1; i > 0; i--){
if((arr[i] - arr[i-1]) === d){
arithCount++;
}
if((arr[i] / arr[i-1]) === q){
geoCount++;
}
}
if(arithCount === length - 1){
return "Arithmetic";
}else if (geoCount === length - 1){
return "Geometric";
}else if((arithCount === length - 1) && (geoCount === length - 1)){
return "both";
}else{
return "neither";
}
}
Sorry, only considered the integer sequence. #Antti Haapala's answer is correct.
Extremely late but I pretty much did the same on my own (novice javascript user).
It calculates the difference between i + 1 and i (or i + 1 / i) and pushes it into a new array. I then use a function to check if every element in the array is the same.
function numberCheck(array) {
var arithResult = null;
var geoResult = null;
var arithCounter = [];
var geoCounter = [];
Array.prototype.allValuesSame = function() {
for(var i = 1; i < this.length; i++) {
if(this[i] !== this[0])
return false;
} return true;
}
for (var b = 0; b < array.length - 1; b++) {
arithCounter.push(array[b + 1] - array[b]);
}
for (var i = 0; i < array.length - 1; i++) {
geoCounter.push(array[i + 1] / array[i])
}
arithResult = arithCounter.allValuesSame();
geoResult = geoCounter.allValuesSame();
if (arithResult === true) { return "Arithmetic";}
else if (geoResult === true) { return "Geometric";}
else { return "-1";}
}
numberCheck([1,2,4,8])

Variable amount of nested for loops

Edit: I'm sorry, but I forgot to mention that I'll need the values of the counter variables. So making one loop isn't a solution I'm afraid.
I'm not sure if this is possible at all, but I would like to do the following.
To a function, an array of numbers is passed. Each number is the upper limit of a for loop, for example, if the array is [2, 3, 5], the following code should be executed:
for(var a = 0; a < 2; a++) {
for(var b = 0; b < 3; b++) {
for(var c = 0; c < 5; c++) {
doSomething([a, b, c]);
}
}
}
So the amount of nested for loops is equal to the length of the array. Would there be any way to make this work? I was thinking of creating a piece of code which adds each for loop to a string, and then evaluates it through eval. I've read however that eval should not be one's first choice as it can have dangerous results too.
What technique might be appropriate here?
Recursion can solve this problem neatly:
function callManyTimes(maxIndices, func) {
doCallManyTimes(maxIndices, func, [], 0);
}
function doCallManyTimes(maxIndices, func, args, index) {
if (maxIndices.length == 0) {
func(args);
} else {
var rest = maxIndices.slice(1);
for (args[index] = 0; args[index] < maxIndices[0]; ++args[index]) {
doCallManyTimes(rest, func, args, index + 1);
}
}
}
Call it like this:
callManyTimes([2,3,5], doSomething);
Recursion is overkill here. You can use generators:
function* allPossibleCombinations(lengths) {
const n = lengths.length;
let indices = [];
for (let i = n; --i >= 0;) {
if (lengths[i] === 0) { return; }
if (lengths[i] !== (lengths[i] & 0x7fffffff)) { throw new Error(); }
indices[i] = 0;
}
while (true) {
yield indices;
// Increment indices.
++indices[n - 1];
for (let j = n; --j >= 0 && indices[j] === lengths[j];) {
if (j === 0) { return; }
indices[j] = 0;
++indices[j - 1];
}
}
}
for ([a, b, c] of allPossibleCombinations([3, 2, 2])) {
console.log(`${a}, ${b}, ${c}`);
}
The intuition here is that we keep a list of indices that are always less than the corresponding length.
The second loop handles carry. As when incrementing a decimal number 199, we go to (1, 9, 10), and then carry to get (1, 10, 0) and finally (2, 0, 0). If we don't have enough digits to carry into, we're done.
Set up an array of counters with the same length as the limit array. Use a single loop, and increment the last item in each iteration. When it reaches it's limit you restart it and increment the next item.
function loop(limits) {
var cnt = new Array(limits.length);
for (var i = 0; i < cnt.length; i++) cnt[i] = 0;
var pos;
do {
doSomething(cnt);
pos = cnt.length - 1;
cnt[pos]++;
while (pos >= 0 && cnt[pos] >= limits[pos]) {
cnt[pos] = 0;
pos--;
if (pos >= 0) cnt[pos]++;
}
} while (pos >= 0);
}
One solution that works without getting complicated programatically would be to take the integers and multiply them all. Since you're only nesting the ifs, and only the innermost one has functionality, this should work:
var product = 0;
for(var i = 0; i < array.length; i++){
product *= array[i];
}
for(var i = 0; i < product; i++){
doSomething();
}
Alternatively:
for(var i = 0; i < array.length; i++){
for(var j = 0; j < array[i]; j++){
doSomething();
}
}
Instead of thinking in terms of nested for loops, think about recursive function invocations. To do your iteration, you'd make the following decision (pseudo code):
if the list of counters is empty
then "doSomething()"
else
for (counter = 0 to first counter limit in the list)
recurse with the tail of the list
That might look something like this:
function forEachCounter(counters, fn) {
function impl(counters, curCount) {
if (counters.length === 0)
fn(curCount);
else {
var limit = counters[0];
curCount.push(0);
for (var i = 0; i < limit; ++i) {
curCount[curCount.length - 1] = i;
impl(counters.slice(1), curCount);
}
curCount.length--;
}
}
impl(counters, []);
}
You'd call the function with an argument that's your list of count limits, and an argument that's your function to execute for each effective count array (the "doSomething" part). The main function above does all the real work in an inner function. In that inner function, the first argument is the counter limit list, which will be "whittled down" as the function is called recursively. The second argument is used to hold the current set of counter values, so that "doSomething" can know that it's on an iteration corresponding to a particular list of actual counts.
Calling the function would look like this:
forEachCounter([4, 2, 5], function(c) { /* something */ });
This is my attempt at simplifying the non-recursive solution by Mike Samuel. I also add the ability to set a range (not just maximum) for every integer argument.
function everyPermutation(args, fn) {
var indices = args.map(a => a.min);
for (var j = args.length; j >= 0;) {
fn.apply(null, indices);
// go through indices from right to left setting them to 0
for (j = args.length; j--;) {
// until we find the last index not at max which we increment
if (indices[j] < args[j].max) {
++indices[j];
break;
}
indices[j] = args[j].min;
}
}
}
everyPermutation([
{min:4, max:6},
{min:2, max:3},
{min:0, max:1}
], function(a, b, c) {
console.log(a + ',' + b + ',' + c);
});
There's no difference between doing three loops of 2, 3, 5, and one loop of 30 (2*3*5).
function doLots (howMany, what) {
var amount = 0;
// Aggregate amount
for (var i=0; i<howMany.length;i++) {
amount *= howMany[i];
};
// Execute that many times.
while(i--) {
what();
};
}
Use:
doLots([2,3,5], doSomething);
You can use the greedy algorithm to enumerate all elements of the cartesian product 0:2 x 0:3 x 0:5. This algorithm is performed by my function greedy_backward below. I am not an expert in Javascript and maybe this function could be improved.
function greedy_backward(sizes, n) {
for (var G = [1], i = 0; i<sizes.length; i++) G[i+1] = G[i] * sizes[i];
if (n>=_.last(G)) throw new Error("n must be <" + _.last(G));
for (i = 0; i<sizes.length; i++) if (sizes[i]!=parseInt(sizes[i]) || sizes[i]<1){ throw new Error("sizes must be a vector of integers be >1"); };
for (var epsilon=[], i=0; i < sizes.length; i++) epsilon[i]=0;
while(n > 0){
var k = _.findIndex(G, function(x){ return n < x; }) - 1;
var e = (n/G[k])>>0;
epsilon[k] = e;
n = n-e*G[k];
}
return epsilon;
}
It enumerates the elements of the Cartesian product in the anti-lexicographic order (you will see the full enumeration in the doSomething example):
~ var sizes = [2, 3, 5];
~ greedy_backward(sizes,0);
0,0,0
~ greedy_backward(sizes,1);
1,0,0
~ greedy_backward(sizes,2);
0,1,0
~ greedy_backward(sizes,3);
1,1,0
~ greedy_backward(sizes,4);
0,2,0
~ greedy_backward(sizes,5);
1,2,0
This is a generalization of the binary representation (the case when sizes=[2,2,2,...]).
Example:
~ function doSomething(v){
for (var message = v[0], i = 1; i<v.length; i++) message = message + '-' + v[i].toString();
console.log(message);
}
~ doSomething(["a","b","c"])
a-b-c
~ for (var max = [1], i = 0; i<sizes.length; i++) max = max * sizes[i];
30
~ for(i=0; i<max; i++){
doSomething(greedy_backward(sizes,i));
}
0-0-0
1-0-0
0-1-0
1-1-0
0-2-0
1-2-0
0-0-1
1-0-1
0-1-1
1-1-1
0-2-1
1-2-1
0-0-2
1-0-2
0-1-2
1-1-2
0-2-2
1-2-2
0-0-3
1-0-3
0-1-3
1-1-3
0-2-3
1-2-3
0-0-4
1-0-4
0-1-4
1-1-4
0-2-4
1-2-4
If needed, the reverse operation is simple:
function greedy_forward(sizes, epsilon) {
if (sizes.length!=epsilon.length) throw new Error("sizes and epsilon must have the same length");
for (i = 0; i<sizes.length; i++) if (epsilon[i] <0 || epsilon[i] >= sizes[i]){ throw new Error("condition `0 <= epsilon[i] < sizes[i]` not fulfilled for all i"); };
for (var G = [1], i = 0; i<sizes.length-1; i++) G[i+1] = G[i] * sizes[i];
for (var n = 0, i = 0; i<sizes.length; i++) n += G[i] * epsilon[i];
return n;
}
Example :
~ epsilon = greedy_backward(sizes, 29)
1,2,4
~ greedy_forward(sizes, epsilon)
29
One could also use a generator for that:
function loop(...times) {
function* looper(times, prev = []) {
if(!times.length) {
yield prev;
return;
}
const [max, ...rest] = times;
for(let current = 0; current < max; current++) {
yield* looper(rest, [...prev, current]);
}
}
return looper(times);
}
That can then be used as:
for(const [j, k, l, m] of loop(1, 2, 3, 4)) {
//...
}

Categories