What is the most efficient way to check for a sequence of numbers in a JavaScript array?

Background

For a technical interview, I was instructed to implement the missing algorithm in JavaScript. The interviewer provided me with some code and 18 failed unit tests, which, as soon as the algorithm is successfully implemented, will pass. I am sure there is a more efficient way to solve this problem, since I tried several different approaches during my allotted time. This way is the first way I have to work, which was enough for a technical test, but I would like to know the best way to solve the problem.

Problem

Work out if the cards in the poker hand form a straight line. (I already ordered the hand in ascending order.)

My decision

PokerHand.prototype._check_straight_function = function(arr) {
    var isStraight = false;
    for (var j = i = 4; i >= 0 && j > 1; i--)
        if (arr[i].value() - 1 == arr[--j].value()) {
            isStraight = true;
        } else {
            isStraight = false;
        }
    };
    return isStraight;
};

Other approaches

, , , -, , , - , .

  • arr.pop().value - 1 == arr.pop().value()
  • filter , , (arr[++i]) + 1, , .
  • a for loop break / continue , .
+4
6

[] , isStraight ( ) . , " " .

" " - :

for (var i = 0; i < 4; i++) {
    var a = arr[i];   // arr[0..3]
    var b = arr[i+1]; // arr[1..4]
    if (!(a.value() + 1 == b.value())) {
        return false; // Not sequential
    }
};
return true;

zip,

arr.zip(function (a, b) { return [a.value(), b.value()] })
   .every(function (x) { return x[0] + 1 === x[1] })

zip .

+1

isStraight .

PokerHand.prototype._check_straight_function = function(arr) {
    for (var i = i = 4; i++) {        
        if (arr[i].value() - 1 != arr[i-1].value()) {
            return false;
        }
    };

    return true;
};
+2

, , (3), "" , , , .

    var last = arr.pop().value(), popped;
    while ((popped = arr.pop().value()) === --last);
    return popped === undefined;
+2

var isOrdered=true;
[5,6,8,9].sort(function(a, b) {
  (b-a != 1)?isOrdered=false:true;
});
alert(isOrdered);

DEMO

+2

( java, )

    boolean isStraight = true;
    for (int i = 0; i < 4; i++) {
        if (arr[i] + 1 != arr[i+1]) {
            isStraight = false;
            break;
        }
    };
+1

Well, that might be a little more neat. I don’t see a ninja way: (As for comparing solutions, I am an employer, and for my part, I would prefer the answer to be clean and elegant, which is several nanoseconds faster :)

for (var i = 0; i < 5; i++) {
  if (a[i].value() != i + a[0].value())
    return false;
}
return true;
+1
source

Source: https://habr.com/ru/post/1610525/


All Articles