K
K
Kseniia Bloshkina2021-01-08 15:25:38
Java
Kseniia Bloshkina, 2021-01-08 15:25:38

How to print all indexes of an array that match a condition?

A service has been created that determines the number of the month with the largest number of sales.

public class StatsService {

    public int monthOfTopSales(long[] sales) {
        long topSale = sales [0];
        int month = 0;
        int numTopMonth = 0;
        for (long sale : sales) {
            month ++;
            if (topSale < sale) {
                topSale = (int) sale;
                numTopMonth=month;
            }
        }
        return numTopMonth;
    }

}


And a test to it with an array of data and an output.

class StatsServiceTest {

    @Test
    void shouldFindTopMonth() {
        StatsService service = new StatsService();

        long[] sales = {8, 15, 13, 15, 17, 20, 19, 20, 7, 14, 14, 18};
        long topMonth = service.monthOfTopSales(sales);

        System.out.println(topMonth);
    }
}


Thus, the output of the first index of the maximum value is obtained. How can the existing code be supplemented so that the indexes of all the maximum values ​​\u200b\u200bare displayed if there are several of them?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Miron, 2021-01-11
@Miron11

public class StatsService {

    public ArrayList<Integer> monthsOfTopSales(long[] sales) {

        long topSale = sales[0];
        Integer month = 0;
        ArrayList<Integer> topMonths = new ArrayList<Integer>();

        for (long sale : sales) {
            month ++;
            if (topSale < sale) {
                topSale = sale;
                topMonths.clear();
                topMonths.add(month);
            } else if ( topSale == sale ) {
                topMonths.add(month);                
            }
        }
        return topMonths;
    }

}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question