Как решить такую задачу на JavaScript?

Задача:

Дано расстояние между городами А и Б. Определить стоимость билета, если:

1. До 999 км каждый 1 км стоит 0.5 TJS.

2. От 1000 до 1999 км 10% скидки стоимости 1 км

3. Более 2000 км 20% скидки

Примечание: Каждый из отрезков рассчитывается отдельно!
  • Вопрос задан
  • 439 просмотров
Пригласить эксперта
Ответы на вопрос 3
Ni55aN
@Ni55aN
function calculateTotalPrice(distance, rates) {
  let sum = 0;
  let lastCheckpoint = 0;

  for(let [boundDistance, pricePerKm] of rates) {
    if (distance < boundDistance) return sum + (distance - lastCheckpoint) * pricePerKm;
    
    sum += (boundDistance - lastCheckpoint) * pricePerKm;
    lastCheckpoint = boundDistance;
  }
}


var pricePerKm = 0.5;

calculateTotalPrice(2100, [[1000, pricePerKm ], [2000, pricePerKm *0.9], [Infinity, pricePerKm*0.8]])
Ответ написан
Комментировать
dimastik1986
@dimastik1986
учусь
циклом который будет создавать объекты (т.е. ваши отрезки) и записывать значения каждого отдельным свойством, на выходе получите отрезки и их стоимость и тд...
Ответ написан
Комментировать
@MaxwellDev
"use strict";
class City {
    constructor(name, point = 0) {
        this.point = point;
        this.name = name;
    }

    go(to) {
        const full = Math.abs(to.point - this.point);
        let steps = [
            { 'step': 999, 'price': 0.5, 'discount': 0, },
            { 'step': 1999, 'price': 0.5, 'discount': 10 },
            { 'step': 2000, 'price': 0.5, 'discount': 20 },
        ];

        let prices = [0, 0, 0];
        for (var i = 0; i < full; i++) {
 
            if (i < steps[0].step) {
                prices[0] = steps[0].discount === 0 ? prices[0] + steps[0].price : prices[0] + (steps[0].price - ((steps[0].price / 100) * steps[0].discount));
            }
            else if (i < steps[1].step) {
                prices[1] = steps[1].discount === 0 ? prices[1] + steps[1].price : prices[1] + (steps[1].price - ((steps[1].price / 100) * steps[1].discount));
            }
            else {
                prices[2] = steps[2].discount === 0 ? prices[2] + steps[2].price : prices[2] + (steps[2].price - ((steps[1].price / 100) * steps[2].discount));
            }
        }
        console.log(prices); //Для проверки каждого отрезка
         
        return  (prices[0] + prices[1] + prices[2]).toFixed(2);
    }
}
const a = new City('A');
const b = new City('Б', 1100);
console.log(a.go(b));
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы