Не проходит проверку по всем пунктам кроме одного. Не понимаю почему, так, как решение верно. По первому пункту "Сумма денег, полученная от показов, должна быть максимальной из всех возможных вариантов." есть рекомендация от ментора: "Проверь, что при отображении рекламных роликов, нет никаких лишних выводов на экран." public class AdvertisementManager { final AdvertisementStorage storage = AdvertisementStorage.getInstance(); private int timeSeconds; private List<advertisement> storageList = storage.list();

public AdvertisementManager(int timeSeconds) {
    this.timeSeconds = timeSeconds;
}

public void processVideos(){

    List<Advertisement> resultList = getVideos(timeSeconds, storageList.size() - 1);

    if (resultList.size() == 0) {
        throw new NoVideoAvailableException();
    }

    Collections.sort(resultList, (ad1, ad2) -> {
        int result = (int) (ad2.getAmountPerOneDisplaying() - ad1.getAmountPerOneDisplaying());
        if (result == 0) {
            result = (int) ((ad1.getAmountPerOneDisplaying() * 1000 / ad1.getDuration())
                    - (ad2.getAmountPerOneDisplaying() * 100 / ad2.getDuration()));
        }
        return result;
    });

    resultList.forEach(advertisement -> {

        advertisement.revalidate();
        ConsoleHelper.writeMessage(String.format("%s is displaying... %d, %d", advertisement.getName()
                , advertisement.getAmountPerOneDisplaying()
                , advertisement.getAmountPerOneDisplaying()* 1000/advertisement.getDuration()));

    });

}

private List<Advertisement> getVideos(int maxDuration, int adCount){

    if (maxDuration <= 0 || adCount < 0) {
        return new ArrayList<>();
    }
    Advertisement adElement = storageList.get(adCount);
    List<Advertisement> withoutAddingAd = getVideos(maxDuration, adCount - 1);
    if (adElement.getDuration() <= maxDuration){
        List<Advertisement> withAddingAd = getVideos(maxDuration - adElement.getDuration()
                , adCount - 1);
        withAddingAd.add(adElement);
        return compareLists(withAddingAd, withoutAddingAd);
    }else {
        return withoutAddingAd;
    }
}

private List<Advertisement> compareLists(List<Advertisement> withAddingAd, List<Advertisement> withoutAddingAd){
    List<List<Advertisement>> lists = Arrays.asList(withAddingAd, withoutAddingAd);
    return Collections.max(lists, (list1, list2) -> {
        int result = (int) (getListProfit(list1) - getListProfit(list2));
        if (result == 0) {
            result = getListDuration(list1) - getListDuration(list2);
        }
        if (result == 0) {
            result = list2.size() - list1.size();
        }
        return result;
    });
}

private int getListDuration(List<Advertisement> advertisementList){
    return advertisementList.stream().mapToInt(Advertisement::getDuration).sum();
}

private long getListProfit(List<Advertisement> advertisementList){
    return advertisementList.stream().mapToLong(Advertisement::getAmountPerOneDisplaying).sum();
}

}

public class Advertisement {
private Object content;
private String name;
private long initialAmount;
private int hits;
private int duration;
private long amountPerOneDisplaying;

public Advertisement(Object content, String name, long initialAmount, int hits, int duration) {
    this.content = content;
    this.name = name;
    this.initialAmount = initialAmount;
    this.hits = hits;
    this.duration = duration;
    this.amountPerOneDisplaying = hits <= 0 ? 0 : initialAmount / hits;
}

public String getName() {
    return name;
}

public int getDuration() {
    return duration;
}

public long getAmountPerOneDisplaying() {
    return amountPerOneDisplaying;
}

public void revalidate(){

    initialAmount -= amountPerOneDisplaying;
    hits--;

    if (hits <= 0){
        throw new UnsupportedOperationException();
    }
}

}

public class AdvertisementStorage {
private static AdvertisementStorage ourInstance = new AdvertisementStorage();

private final List<Advertisement> videos = new ArrayList<>();

public static AdvertisementStorage getInstance() {
    return ourInstance;
}

private AdvertisementStorage() {
    Object someContent = new Object();

    videos.addAll(Arrays.asList(
            new Advertisement(someContent, "First Video", 5000, 100, 3 * 60)
            , new Advertisement(someContent, "Second Video", 100, 10, 15 * 60)
            , new Advertisement(someContent, "Third Video", 400, 2, 10 * 60)
    ));
}

public List<Advertisement> list(){
    List<Advertisement> advertisements = new ArrayList<>();
    videos.forEach(advertisement -> {
        if (advertisement.getAmountPerOneDisplaying() > 0) {
            advertisements.add(advertisement);
        }
    });
    return advertisements;
}

public void add(Advertisement advertisement){
    videos.add(advertisement);
}

}

public class Restaurant {
public static void main(String[] args) {
    Tablet tablet5 = new Tablet(5);

    Cook cookJohny = new Cook("Johny");

    tablet5.addObserver(cookJohny);
    cookJohny.addObserver(new Waiter());

    tablet5.createOrder();

}

}

public class Cook extends Observable implements Observer{
String name;

public Cook(String name) {
    this.name = name;
}

@Override
public void update(Observable o, Object order) {
    ConsoleHelper.writeMessage(String.format("Start cooking - %s, cooking time %smin", order, ((Order) order).getTotalCookingTime()));
    setChanged();
    notifyObservers(order);
}

@Override
public String toString() {
    return name;
}

}

public class Order {
private final Tablet tablet;
protected List<Dish> dishes;

public Order(Tablet tablet) throws IOException{
    this.tablet = tablet;
    this.dishes = ConsoleHelper.getAllDishesForOrder();
}

public int getTotalCookingTime(){
    int result = 0;
    for (Dish dish : dishes) {
        result += dish.getDuration();
    }
    return result;
}

public boolean isEmpty(){
    return dishes.isEmpty();
}

@Override
public String toString() {
    StringBuilder resultStringBuilder = new StringBuilder("");
    for (int i = 0; i < dishes.size(); i++) {
        resultStringBuilder.append(dishes.get(i));
        if (i != dishes.size() - 1){
            resultStringBuilder.append(", ");
        }
    }
    return String.format("Your order: [%s] of %s", resultStringBuilder.toString(), tablet);
}

}

public class Tablet extends Observable{
final int number;
private static Logger logger = Logger.getLogger(Tablet.class.getName());

public Tablet(int number) {
    this.number = number;
}

public Order createOrder(){
    Order order = null;
    try {
        order = new Order(this);
        if (!order.isEmpty()){
            ConsoleHelper.writeMessage(order.toString());
            new AdvertisementManager(order.getTotalCookingTime() * 60).processVideos();
            setChanged();
            notifyObservers(order);
        }
    } catch (IOException e) {
        logger.log(Level.SEVERE, "Console is unavailable.");
    } catch (Throwable throwable) {
        logger.log(Level.INFO, "No video is available for the order " + order);
    }
    return order;
}

@Override
public String toString() {
    return String.format("Tablet{number=%d}", number);
}

}

Этот вопрос отмечен как пост "community wiki".

задан 05 Фев, 03:43

OlehBiloholovka's gravatar image

OlehBiloholovka
11
одобрено: 0%

изменено 05 Фев, 03:47

Ваш ответ будет первым!
включить просмотр

Следить за вопросом

По Email:

После авторизации вы сможете подписаться на любые обновления здесь

Основы Markdown

  • *italic* or _italic_
  • **bold** or __bold__
  • ссылка:[текст](http://url.com/ "заголовок")
  • изображение?![alt текст](/path/img.jpg "заголовок")
  • нумерованный список: 1. Foo 2. Bar
  • Для того чтобы добавить разрыв строки просто добавьте два пробела.
  • основные HTML тэги, также поддерживаются

Тэги:

×48
×22

Задан: 05 Фев, 03:43

Просмотров: 159 раз

Отредактирован: 05 Фев, 03:47