Spaces:
Running
Running
File size: 2,042 Bytes
59719c2 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 |
Write the method
ArrayList<Integer> createList(int start, int end)
...which takes as parameters the start and end values of the list.
The method generates a new list containing, in order, all the elements between the given points, one step apart.
As usual, the START sub-item is INCLUDED in the list, but the END sub-item IS NOT.
Note that the list must be created BACKWARDS IF the STARTING sub-item is GREATER than the ending sub-item.
See the sample performances for an example.
Examples on method calls:
public static void main(String[] parameters){
System.out.println(createList(1,10));
System.out.println(createList(10,1));
}
Program outputs:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[10, 9, 8, 7, 6, 5, 4, 3, 2]
===============================
import java.util.Random;
import java.util.ArrayList;
public class Test{
public static void main(String[] args){
final Random r = new Random();
Object[][] p = {{1,4}, {100,106}, {5,0}, {90,80}};
for (Object[] pa : p) {
System.out.print("Testing with parameters ");
System.out.println(pa[0] + ", " + pa[1]);
System.out.println(createList((Integer) pa[0], (Integer) pa[1]));
System.out.println("");
}
}
public static ArrayList<Integer> createList(int start, int end) {
ArrayList<Integer> list = new ArrayList<>();
// ascending order
if (start < end) {
for (int i = start; i < end; i++) {
list.add(i);
}
}
// start > end
// descending order
// start >> start-1 >> ... >> (excluding) 'end'
else {
for (int i = start; i > end; i--) {
list.add(i);
}
}
return list;
}
}
Testing with parameters 1, 4
[1, 2, 3]
Testing with parameters 100, 106
[100, 101, 102, 103, 104, 105]
Testing with parameters 5, 0
[5, 4, 3, 2, 1]
Testing with parameters 90, 80
[90, 89, 88, 87, 86, 85, 84, 83, 82, 81]
|