by CodeChum Admin
Did you know that you can also reverse lists and group them according to your liking with proper code? Let's try it to believe it.
Instructions:
Input
The first line contains an odd positive integer.
The next lines contains an integer.
5
1
3
4
5
2
Output
A line containing a list.
[2,5]-[4]-[3,1]
SOLUTION TO THE ABOVE QUESTION
SOLUTION CODE
package com.company;
import java.util.ArrayList;
import java.util.*;
class Main{
public static void main(String arg[])
{
//propmt the user to enter a positive odd integer
Scanner sc = new Scanner(System.in);
System.out.print("Enter a positive odd integer: ");
int odd_integer = sc.nextInt();
//lets create an array of the odd integer size
ArrayList<Integer> my_integers_array = new ArrayList<Integer>();
//Lets put rando integers in the array
for(int i = 0; i < odd_integer; i++)
{
System.out.print("Enter integer "+(i+1)+": ");
int my_integer = sc.nextInt();
my_integers_array.add(my_integer);
}
//Lets reverse the array
ArrayList<Integer> reverse_my_integers_array = new ArrayList<Integer>();
for(int i = 0; i<odd_integer; i++)
{
reverse_my_integers_array.add(my_integers_array.get(((odd_integer-i)-1)));
}
System.out.println("\nour original array is: "+my_integers_array);
System.out.println("\nOur original array is: "+reverse_my_integers_array);
//Now let us get the sublist and print them
List <Integer> first_half = reverse_my_integers_array.subList(0, odd_integer/2);
List <Integer> middle = reverse_my_integers_array.subList(odd_integer/2, (odd_integer/2+1));
List <Integer> second_half = reverse_my_integers_array.subList((odd_integer/2+1), odd_integer);
System.out.println("The sub list divided as first half, middle and second half are: \n");
System.out.printf(String.valueOf(first_half)+"-"+String.valueOf(middle)+"-"+String.valueOf(second_half));
}
SAMPLE PROGRAM OUTPUT
Comments
Leave a comment