U
U
Uncle Bogdan2021-09-13 19:42:30
C++ / C#
Uncle Bogdan, 2021-09-13 19:42:30

How to improve the algorithm?

There is such a task:

"There are 54 seats in a reserved seat car, which are located in nine compartments. Seats from 1 to 36 are basic and they are located four in a compartment (1 - 4 in the first, ..., 33 - 36 in the ninth), from 37 up to 54 - side, divided into two, but the location of the compartment is reversed: places 37, 38 are in the ninth compartment, 39 and 40 in the eighth, ..., 53 and 54 in the first. Determine the compartment number by the seat number.

I solved it like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        private static int _placesCount;
        private static int _roomCount = 18;

        private static int _mainRoomPlacesCount = 4;
        private static int _sideRoomPlacesCount = 2;

        static void Main(string[] args)
        {
            _placesCount = (_roomCount / 2 * _mainRoomPlacesCount) + (_roomCount / 2 * _sideRoomPlacesCount);

            while(true)
            {
                var number = 0;

                Console.WriteLine("\n\nВведите номер места:");

                var ParceResult = int.TryParse(Console.ReadLine(), out number);

                if (ParceResult)
                {
                    if(number <= _placesCount && number > 0)
                    {
                        var result = FindRoomByPlace(number);

                        Console.WriteLine("Вывод: " + result);
                    }
                    else
                    {
                        Console.WriteLine("Такого места не существует!");
                    }
                }
                else
                {
                    Console.WriteLine("Ошибка. Не удалось преобразовать строку в число.");
                }
            }
        }

        private static double FindRoomByPlace(int placeNumber)
        {
            var mainPlacesCount = _roomCount / 2 * _mainRoomPlacesCount;

            if(placeNumber <= mainPlacesCount)
            {
                return Math.Ceiling((double)placeNumber / _mainRoomPlacesCount);
            }
            else
            {
                return Math.Ceiling((double)(_placesCount - placeNumber + 0.5f) / _sideRoomPlacesCount);
            }
        }
    }
}


Is there any better option?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Developer, 2021-09-13
@motkot

if (n < 37)
  return (int)((n-1) >> 2)+1;
else
  return (int)((54-n+1) >> 1)+1;

Something like this
Why is your FindRoomByPlace double?
Are there fractional compartments?
What is RoomCount and why are there 18 of them?
The code is disgusting

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question