Reputation: 23
Each card has a weighted value. Cards 2 through 6 are worth one point; 7, 8 and 9 are worth zero; and 10s, face cards and Aces are worth negative one. This type of card-counting system is called the HiLo count. When counting down a standard deck of 52 cards, you'll notice the count will go up and down, and always end at zero if you counted correctly. The cardCounter function is supposed to take an array of card objects and return the count (weighted value) of the cards. It doesn't seem to be producing accurate results and I can't figure why.
function cardCounter(array) {
var count = 0;
for (var i = 1; i < array.length; i++) {
var card = array[i];
if (card.card + i >= 2 && card.card + i <= 6) {
count++;
} else if (card.card + i >= 10 || card.card + i === 'face or ace') {
count--;
}
return count;
}
}
console.log(cardCounter([ { 'card 0': 2 }, { 'card 1': 6 }, { 'card 2': 8 }, { 'card 3': 'face or ace' } ]));
//output: 1
console.log(cardCounter([ { 'card 0': 'face or ace' }, { 'card 1': 9 }, { 'card 2': 8 }, { 'card 3': 'face or ace' } ]));
//output: -2
Upvotes: 2
Views: 409
Reputation: 12629
var card = array[i]["card " + i];
not card.card + i
.i=0
inside for
and add condition as if (!isNaN(card))
which will be true
when value is number
. If it is number then check whether value is between 2-6
or >=10
.number
then compare it with face or ace
.return count;
outside for
loop.Try complete code as below.
function cardCounter(array) {
var count = 0;
for (var i = 0; i < array.length; i++) {
var card = array[i]["card " + i];
if (!isNaN(card)) {
if (card >= 2 && card <= 6) {
count++;
} else if (card >= 10) {
count--;
}
} else if (card === 'face or ace') {
count--;
}
}
return count;
}
console.log(cardCounter([ { 'card 0': 2 }, { 'card 1': 6 }, { 'card 2': 8 }, { 'card 3': 'face or ace' } ]));
//output: 1
console.log(cardCounter([ { 'card 0': 'face or ace' }, { 'card 1': 9 }, { 'card 2': 8 }, { 'card 3': 'face or ace' } ]));
//output: -2
Upvotes: 2