Algorithm simulation of taximeter

Asked

Viewed 156 times

2

I’m creating a Javascript algorithm to make the calculation similar to that of a taximeter, where you have the time of flag 1 and of flag 2.

function test(hora,bandeira1, bandeira2) {
  if (hora >= bandeira1 && hora < bandeira2) {
    console.log("calculou como bandeira 1");
  } else {
  console.log("calculou como bandeira 2");
  } 
}

// Retorna: "calculou como bandeira 2"
test(23,1,7);

If I perform a test passing test(23,8,1) the algorithm will not work correctly, it should point to flag 1, but point to flag 2.

Could help me make an algorithm where any combination I pass prevails the normal order of a taximeter?

2 answers

2

The correct is

Hora é maior ou igual que bandeira1 ? && Hora é menor que a bandeira2 ?
   console.log("calculou como bandeira 1");
Não
   console.log("calculou como bandeira 2");

Behold

function test(hora,bandeira1, bandeira2) {
  if (hora >= bandeira1 && hora < bandeira2) {
    console.log("calculou como bandeira 1");
  } else {
    console.log("calculou como bandeira 2");
  } 
}

// Retorna: "calculou como bandeira 2"
test(23,1,7);
// Retorna: "calculou como bandeira 1"
test(1,1,7);
// Retorna: "calculou como bandeira 2"
test(7,1,7);

  • It does not work for all combinations.. if you test: test(23,8,0) will give as flag 2, while should be flag 1..

1

If the night time is between 1 and 7 then you have to isolate that period with &&:

hora >= bandeira1 && hora < bandeira2

Suggestion:

const taximetro = function( /* N bandeiras */ ) {
  const bandeiras = arguments;
  return function(hora) {
    var match = -1;
    for (var i = 0; i < bandeiras.length; i++) {
      var bnd = bandeiras[i];
      if (bnd.inicio <= hora) match = i;
    }
    var res = match !== -1 ? bandeiras[match] : bandeiras[bandeiras.length - 1];
    return "calculou como bandeira " + res.tipo;
  }
};

const taximetroA = taximetro({
  inicio: 2,
  tipo: 'Bandeira Madrugada'
}, {
  inicio: 7,
  tipo: 'Bandeira Dia'
}, {
  inicio: 22,
  tipo: 'Bandeira Noite'
});

for (let i = 1; i <= 24; i++) {
  console.log(i, taximetroA(i));
}

  • It doesn’t work for all tests... If you pass 8am as flag 1 and 1pm as flag 2 and for 23hrs you will miscalculate. @Rgio

  • @Mateuscarvalho in this case the answer would not be bandeira 2?

  • sorry I said 1pm as flag 2, but it would be 1am, in this case should still give flag 1, but ends up giving flag 2, understood?

  • @Mateuscarvalho I am at work but I can improve the answer later with possibility for N flags, without being so specific to the example of the question.

  • I appreciate your help, as soon as you can, thank you!

  • @Mateuscarvalho take a look.

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.