Home >Web Front-end >JS Tutorial >JavaScript Fun Question: Water Crisis

JavaScript Fun Question: Water Crisis

黄舟
黄舟Original
2017-02-15 14:23:571331browse

Dear residents:

I am the village chief and I want to tell you some bad news. The village is facing a water shortage problem recently.

Here is a list with the age information of the villagers.

Different age groups have different daily water consumption: those under 18 years old are about 1 liters per day, 18 to 50 Those under the age of are 2 liters per day, and those aged 50 and above are 1.5 liters per day.

Now the village's water reserve is N liters. In order to prevent problems before they occur, we ask for help from everyone.

How long can we sustain it at the current consumption rate?

The task is here:

Write a function that receives 2 parameters. The first one represents the reserve amount N's water, the second one is ageOfDwellerArray representing the age list.

Returns a positive integer representing the number of days, returns -1 if there are no residents in the village (ageOfDwellerArray is empty).

Idea:

First of all, according to the words of the village chief, make the configuration and divide it into three levels: minors, adults, and the elderly.


var info = {
  child : {consume : 1,range : [0,18]},
  adult : {consume : 2,range : [18,50]},
  old : {consume : 1.5,range : [50,200]},
};

Then, based on the age list and the configuration object above, calculate the total daily consumption.

Finally, divide the total reserve by the daily consumption to calculate the number of days of maintenance.


function thirstyIn(water, ageOfDwellerArray) {
  var consumePerDay = 0;
  for(var i=0;i<ageOfDwellerArray.length;i++){
    for(var j in info){
      var type = info[j];
      var range = type.range;
      if(ageOfDwellerArray[i] >= range[0] && ageOfDwellerArray[i] < range[1]){
        consumePerDay += type.consume;
        break;
      }
    }
  }
  return consumePerDay ? Math.floor(water / consumePerDay) : -1;
}


The above is the content of JavaScript interesting question: water shortage crisis. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Magical rotate functionNext article:Magical rotate function