Vasya - Clerk

The new "Avengers" movie has just been released! There are a lot of people at the cinema box office standing in a huge line. Each of them has a single100,50or25dollars bill. A "Avengers" ticket costs25 dollars.

Vasya is currently working as a clerk. He wants to sell a ticket to every single person in this line.

Can Vasya sell a ticket to each person and give the change if he initially has no money and sells the tickets strictly in the order people follow in the line?

ReturnYES, if Vasya can sell a ticket to each person and give the change. Otherwise returnNO.

Examples:

tickets([25, 25, 50]) // => YES 
tickets([25, 100])    
        // => NO. Vasya will not have enough money to give change to 100 dollars

tickets([25,50,25,100,25,25,25,100,25,25,50,100,50,25]); // NO

Solution:

function tickets(peopleInLine){
  var deposit = [0,0,0];

  function updateDeposit(paid) {
    for(var i=0; i<deposit.length; i++) {
      deposit[i] = deposit[i] + paid[i];
    }
  }

  for (var index in peopleInLine) {

    if(peopleInLine[index] === 25) {
      updateDeposit([1,0,0])
    }

    else if(peopleInLine[index] === 50) {
      updateDeposit([-1,1,0])
    }

    else {// pay 100
      if (deposit[0] >=1 && deposit[1] >=1){
          updateDeposit([-1,-1,1]);}
      else if (deposit[0] >=3 && deposit[1] == 0){
          updateDeposit([-3, 0, 1]);}
      else {
          updateDeposit([-3, 0, 1]);}
    }

    if (deposit[0] < 0 || deposit[1] < 0 || deposit[2] < 0 ) {
      return 'NO';
    }
  }
  return 'YES';
}

Better Solution =>

function Clerk(name) {
  this.name = name;

  this.money = {
    25 : 0,
    50 : 0,
    100: 0 
  };

  this.sell = function(element, index, array) {
    this.money[element]++;

    switch (element) {
      case 25:
        return true;
      case 50:
        this.money[25]--;
        break;
      case 100:
        this.money[50] ? this.money[50]-- : this.money[25] -= 2;
        this.money[25]--;
        break;
    }
    return this.money[25] >= 0;
  };
}

function tickets(peopleInLine){
  var vasya = new Clerk("Vasya");
  return peopleInLine.every(vasya.sell.bind(vasya)) ? "YES" : "NO";
}

results matching ""

    No results matching ""