0

Написать функцию, которая принимает массив товаров и массив магазинов. Функция должна возвращать для каждого товара, лучшую цену и соответствующий магазин. Товары должны идти в том же порядке, что и в исходном массиве товаров. Гарантируется, что: каждый товар будет присутствовать хотя бы в одном магазине будет. в магазине присутствуют только повторяющиеся товары

Решаю эту задачу, но не уверена в правильности алгоритма. Обращаюсь с просьбой к профессионалам посмотреть, что я написала. и сказать что делаю верно. а что нет. Вот мой код:

public static class Item{           // товары
        public int id;                  // id товара
        public  String name;            // наименование товара
    }
    public static class Shop{           //магазин
        public String name;             //название магазина
        public Price [] prices;         // массив цен товаров
    }
    public static class Price{          // Цены
        public int itemId;              // id  товара
        public int price;               // цена
    }
    public static class ItemWithBestPrice{  // лучший прайс
        public Item item;                   // товар
        public String shopName;             // наименование лучшего товара
        public int bestPrice;               // лучшая цена

        public ItemWithBestPrice(Item item, String shopName, int bestPrice){
            this.item = item;
            this.shopName = shopName;
            this.bestPrice = bestPrice;
        }
        public ItemWithBestPrice(){

        }
    }
public static ItemWithBestPrice[] findBestPrices(Item[] items, Shop[] shops){
        Price [] price = new Price[]{};
      //  ItemWithBestPrice newPrice = new ItemWithBestPrice();
        Shop shopsNew = new Shop();
        Item itemsNew = new Item();
        Price priceNew = new Price();
        int minPrice = Integer.MAX_VALUE;

        for (int i = 0; i < shops.length; i++){
            for (int j = 0; j < items.length; j ++){
                for (int p = 0; p < price.length; p++){
                    if (price[p].price < minPrice){
                        itemsNew = items[j];
                        shopsNew = shops[i];
                        priceNew = price[p];
                    }
                }
            }
        }
        ItemWithBestPrice newPrice = new ItemWithBestPrice();
        newPrice.item = itemsNew;
        newPrice.shopName.equals(shopsNew);
        newPrice.bestPrice = priceNew[];

        return newPrice;
    }

У меня вопрос по return Получается после того как я создала объект ItemWithBestPrice newPrice = new ItemWithBestPrice(); Как мне правильно присвоить получившиеся параметры вот здесь: newPrice.bestPrice = priceNew; учитывая, что bestPrice - это int а priceNew это объект класса priceNew?

Помогите пожалуйста ))

1 ответ 1

1

т.к. Вы "обратились с просьбой к профессионалам посмотреть", приведу пример "профессионального" ревью :)

public static class Item{           // товары
    public int id;                  // id товара
    public  String name;            // наименование товара
}
public static class Shop{           //магазин
    public String name;             //название магазина
    public Price [] prices;         // массив цен товаров
}
public static class Price{          // Цены
    public int itemId;              // id  товара
    public int price;               // цена
}
public static class ItemWithBestPrice{  // лучший прайс
    public Item item;                   // товар
    // TODO review: misleading comment "наименование лучшего товара"
    public String shopName;             // наименование лучшего товара
    public int bestPrice;               // лучшая цена

    public ItemWithBestPrice(Item item, String shopName, int bestPrice){
        this.item = item;
        this.shopName = shopName;
        this.bestPrice = bestPrice;
    }
    public ItemWithBestPrice(){

    }
}

public static ItemWithBestPrice[] findBestPrices(Item[] items, Shop[] shops){
    Price [] price = new Price[]{};
  //  ItemWithBestPrice newPrice = new ItemWithBestPrice();
    // TODO review: readability: name does not reflect variable purpose,
    // consider other naming, e.g. "bestPriceShop"
    // TODO review: unnecessary object instantiation. 
    // Obviously variables are declared too early / too far away from actual usage.
    Shop shopsNew = new Shop();
    Item itemsNew = new Item();
    Price priceNew = new Price();
    // TODO review: actually we need best price per item, 
    // that is, single variable "minPrice" will be not enough. 
    // Consider tracking min prices within a map indexed by item id.
    int minPrice = Integer.MAX_VALUE;

    for (int i = 0; i < shops.length; i++){
        for (int j = 0; j < items.length; j ++){
            // TODO review: array price is empty (see declaration),
            // thus, this loop will complete without any iteration.
            // Obviously intention was something else, 
            // e.g. to iterate trough prices array of the shop[i]
            for (int p = 0; p < price.length; p++){
                if (price[p].price < minPrice){
                    itemsNew = items[j];
                    shopsNew = shops[i];
                    priceNew = price[p];
                }
            }
        }
    }

    ItemWithBestPrice newPrice = new ItemWithBestPrice();
    newPrice.item = itemsNew;
    // TODO review: result of "equals" comparison is ignored. 
    // It seems like the code does not what it was intended to do.
    newPrice.shopName.equals(shopsNew);
    // TODO review: invalid syntax. did you ever tried to compile your code? :)
    newPrice.bestPrice = priceNew[];
    // TODO review: wrong variable type. it should be array of
    // ItemWithBestPrice according to function declaration.
    return newPrice;
}
2
  • ого спасибо))) развернутый ответ... 31 авг 2022 в 9:13
  • пока что не за что. :) рекомендую повторить раздел про работу с массивами и начать исправлять код с двух последних комментариев, так чтобы код компилировался, а затем уже разруливать вложенные циклы.
    – Ramiz
    1 сен 2022 в 17:24

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.