Как рассчитать индивидуальные цены на автомобили (с условием, что один и тот же компонент не добавляется дважды к одному и тому же автомобилю) - PullRequest
0 голосов
/ 14 октября 2019

У меня есть консольное приложение, которое рассчитывает цену автомобиля. Базовая конфигурация стоит 1000 долларов и может быть расширена дополнительными 6 опциями (можно найти в комментариях в коде). Каждая машина имеет уникальный идентификатор. Машину можно покрасить в один или несколько цветов.

ПРИМЕЧАНИЕ! Должны быть выбраны дополнительные параметры (вы просто не можете рассчитать базовую конфигурацию без параметров). Не разрешается повторять один и тот же компонент дважды для одной и той же машины.

Ввод: ID (1-е место) 1 из 6 вариантов (2-е место) ... до -1 .

Вывод: отсортированные цены автомобилей в порядке возрастания идентификаторов автомобилей ... до -1

Подробнее см. Здесь: Таблица калькуляции цен для идентификаторов и опций (для пользовательской автоматической конфигурации)

Мое решение:

using System;
using System.Collections.Generic;
using System.Linq;

namespace CarFactory
{
    class Program
    {
        static void Main(string[] args)
        {
            // input numbers
            var numbers = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
            // step
            int i = 0;

            List<Car> cars = new List<Car>();

            // check while step not equils termination number
            while (numbers[i] != -1)
            {
                // check if value == null
                // then, create an item with unique ID
                // and add one or more options for car configuration
                if (cars.Where(x => x.id == numbers[i]).FirstOrDefault() == null)
                {
                    Car c = new Car();
                    c.id = numbers[i];
                    c.cDetails[numbers[i + 1] - 1] = true;
                    cars.Add(c);
                }
                else
                {
                    // if not null
                    Car c = cars.Where(x => x.id == numbers[i]).FirstOrDefault();
                    c.cDetails[numbers[i + 1] - 1] = true;
                }

                i += 2; // increase step by 2
            }

            // sorting car prices in ascending order of car ids
            var sortedCarId = from x in cars orderby x.id select x;

            foreach (var carPrice in sortedCarId)
            {
                Console.Write(carPrice.GetCarPrice() + " ");
            }
            Console.Write(-1);
        }
    }

    class Car
    {
        public int id;
        public bool[] cDetails = new bool[6];

        // calculate the cost of each car with custom configuration
        public int GetCarPrice()
        {
            int[] el = new int[6];
            el[0] = Convert.ToInt32(cDetails[0]) * 150;     // Air conditioning for $150
            el[1] = Convert.ToInt32(cDetails[1]) * 50;      // Power windows for $50
            el[2] = Convert.ToInt32(cDetails[2]) * 125;     // Parking assistance for $125
            el[3] = Convert.ToInt32(cDetails[3]) * 25;      // Black paint for $25
            el[4] = Convert.ToInt32(cDetails[4]) * 20;      // Green paint for $20
            el[5] = Convert.ToInt32(cDetails[5]) * 30;      // Pink paint for $30

            // basic car configuration costs $1000 + sum of options
            return el.Sum() + 1000;
        }
    }
}

// Input:   1 2 1 1 2 2 1 5 2 5 3 1 3 6 2 4 3 3 5 1 -1
// Output:  1220 1095 1305 1150 -1

Программа считает хорошо, но не все тесты пройдены: только 6/10. У меня 4 случая - НЕПРАВИЛЬНЫЙ РЕЗУЛЬТАТ.

Почему этот код не проходит все тестовые случаи? Понятия не имею. Помогите кому-нибудь, алгоритм или код) Спасибо всем!

1 Ответ

0 голосов
/ 18 октября 2019

Кодовое решение на C #, 10/10

using System;
using System.Collections.Generic;
using System.Linq;

namespace CarFactory
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] numbers = Console.ReadLine().Split().Select(int.Parse).ToArray();

            Console.Write(String.Join(" ", BlackBox(numbers)) + " " + -1);
        }

        private static int[] BlackBox(int[] numbers)
        {
            Dictionary<int, int> carPrices = new Dictionary<int, int>();
            carPrices.Add(0, 0);
            carPrices.Add(1, 150);
            carPrices.Add(2, 50);
            carPrices.Add(3, 125);
            carPrices.Add(4, 25);
            carPrices.Add(5, 20);
            carPrices.Add(6, 30);

            Dictionary<int, int> totals = new Dictionary<int, int>();

            for (int i = 0; i < numbers.Length; i += 2)
            {
                int key = numbers[i];

                if (key == -1)
                    break;

                int priceKey = numbers[i + 1];

                if (totals.ContainsKey(key))
                    totals[key] += carPrices[priceKey];
                else
                    totals[key] = carPrices[priceKey];
            }
            return new SortedDictionary<int, int>(totals)
                .Select(e => 1000 + e.Value)
                .TakeWhile(x => x != -1)
                .ToArray();
        }
    }
}
...