The following is what I was able to complete:
import java.util.ArrayList; public class MyClass { public void setBlockDates() { } public ArrayList<Integer> getAvailableDates() { } public static void main(String[] args) { // create an arraylist with all the dates in it ArrayList<Integer> dateRange = new ArrayList<Integer>(); for (int i = 1; i < 32; i++) { dateRange.add(i); } System.out.println(dateRange); } }
For the setBlockDates() method: write a method to block multiple ranges of dates from the dateRange ArrayList. Here I should be able to enter multiple ranges to block, such as ([1,4], [8,11], [17,24])
For the getAvailableDates() method: write a method to return the available dates in the dateRange ArrayList created below. the return should be an ArrayList like the following if the date ranges ([1,4], [8,11], [17,24]) were blocked on the calendar:
[5, 6, 7, 12, 13, 14, 15, 16, 25, 26, 27, 28, 29, 30, 31]
Any help would be appreciated!
Advertisement
Answer
I’ll assume the input parameter for the setBlockDates()
to be a two-dimensional int array.
import java.util.stream.Collectors; //for conversion to List import java.util.stream.IntStream; //for ranges import java.util.ArrayList; public class MyClass { static ArrayList<Integer> dates = new ArrayList<>( IntStream.rangeClosed(1, 31) .boxed() .collect(Collectors.toList()) ); ArrayList<Integer> blockedDates = new ArrayList<>(); public void setBlockDates(int[][] arr) { for (int[] i : arr) { this.blockedDates.addAll( IntStream .rangeClosed(i[0], i[1]) .boxed() .collect(Collectors.toList()) ); //adds a range from i[0] to i[1] to blockedDates } } public ArrayList<Integer> getAvailableDates() { return new ArrayList( dates .stream() .filter(i -> !blockedDates.contains(i)) .collect(Collectors.toList()) ); } public static void main(String[] args) { //example MyClass calendar = new MyClass(); calendar.setBlockDates(new int[][] {{1, 5}, {10, 12}}); calendar.getAvailableDates(); //returns 6-9 and 13-31 } }
The setBlockDates()
takes a two-dimensional array as input, and adds a range of each array to blockedDates
. The getAvailableDates()
returns an ArrayList<Integer>
that doesn’t include all the ints in blockedDates
.