How can I get the smallest number, not in an array, in a functional programming fashion with lo-dash?

StackOverflow https://stackoverflow.com/questions/22111619

I have an array...

[8, 2, 5, 3, 0, 9, 1, 6, 7]

How do I get the smallest number, not listed in the array? 4 in this case.

The only thing I can think of is, but I would like to get rid of the while loop if I could.

var list = [8, 2, 5, 3, 9, 1, 6, 7];
var num = -1;
var done = false;
while (!done) {
  num++;
  if(!_.contains(list, num)) {
    done = true;
  }
}

没有正确的解决方案

其他提示

You could sort the array in n lg n time and start at the beginning and find the first gap.

This solution solves for the lowest number between the min and max. Otherwise, computationally, yours Is the best.

Try this:

function findLowest(n, xs) {
    return xs.indexOf(n) < 0 ? n : findLowest(n + 1, xs);
}

Now all you need to do is:

var n = findLowest(0, [8, 2, 5, 3, 0, 9, 1, 6, 7]);

alert(n); // 4

See the demo for yourself: http://jsfiddle.net/9pXGR/

The findLowest function will find the lowest number not in the list starting from a given number n.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top