bernard
bernard

Reputation: 51

freecodecamp counting cards exercise issue

I know how to solve this issue with simple switch statements. However, I would like to solve it using arrays and if/else statements. I seem to only get 0 hold for all of my inputs.

Instructions for exercise

var count = 0;
var arr = [[2,3,4,5,6],[7,8,9],[10,'J','Q','K','A']]
var answer = "";
function cc(card) {
  // Only change code below this line
  if (card == arr[0]){
    count ++;
    answer = count + " " + "Bet"
  }else if(arr[1]){
    answer = count + " " + "Hold"
  }else{
    count --;
    answer = count + " " + "Hold"
  }


  return answer;
  // Only change code above this line
}

Upvotes: 2

Views: 172

Answers (1)

Sash Sinha
Sash Sinha

Reputation: 22418

You could use three Arrays:

const positveChange = [2, 3, 4, 5, 6];
const negativeChange = [10, 'J', 'Q', 'K', 'A'];
const noChange = [7, 8, 9];

let count = 0;
const cc = (card) => {
    if (positveChange.includes(card)) {
        count++;
    } else if (negativeChange.includes(card)) {
        count--;
    } else if (!noChange.includes(card)) {
        throw 'card is not valid';
    }
    return count <= 0 ? `${count} Hold` : `${count} Bet`;
}

console.log(cc(2));
console.log(cc(3));
console.log(cc(7));
console.log(cc('K'));
console.log(cc('A'));

But I would recommend using three Sets instead:

const positveChange = new Set([2, 3, 4, 5, 6]);
const negativeChange = new Set([10, 'J', 'Q', 'K', 'A']);
const noChange = new Set([7, 8, 9]);

let count = 0;
const cc = (card) => {
    if (positveChange.has(card)) {
        count++;
    } else if (negativeChange.has(card)) {
        count--;
    } else if (!noChange.has(card)) {
        throw 'card is not valid';
    }
    return count <= 0 ? `${count} Hold` : `${count} Bet`;
}

console.log(cc(2));
console.log(cc(3));
console.log(cc(7));
console.log(cc('K'));
console.log(cc('A'));

Because Array.includes has a time-complexity of O(N), where N is the number of elements of in the array, i.e. linear time, while Set.has is O(1), i.e. constant time.

Upvotes: 1

Related Questions