Recursion, Sorting, and Arraylists - Group 3
public void drawLine(int n) {
for (int i = 1; i <= n; i++) {
System.out.print("*");
}
if (n>0){
System.out.println();
drawLine(n - 1);
}
}
drawLine(10);
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class Main {
public static void main(String[] args) {
ArrayList<Country> countries = new ArrayList<Country>();
countries.add(new Country("Russia", 17098246));
countries.add(new Country("Australia", 7692024));
countries.add(new Country("Argentina", 2780400));
countries.add(new Country("United States", 9372610));
countries.add(new Country("Canada", 9984670));
countries.add(new Country("China", 9596961));
countries.add(new Country("Brazil", 8515767));
countries.add(new Country("India", 3287263));
// Sort the countries in decreasing order of size using a selection sort algorithm and a Comparator
Comparator<Country> sizeComparator = new Comparator<Country>() {
@Override
public int compare(Country c1, Country c2) {
return c1.getSize() - c2.getSize();
}
};
for (int i = 0; i < countries.size() - 1; i++) {
int maxIndex = i;
for (int j = i + 1; j < countries.size(); j++) {
if (sizeComparator.compare(countries.get(j), countries.get(maxIndex)) > 0) {
maxIndex = j;
}
}
if (maxIndex != i) {
Collections.swap(countries, i, maxIndex);
}
}
// Print the sorted countries
for (Country country : countries) {
System.out.println(country.getName() + " (" + country.getSize() + ")");
}
}
}
class Country {
private String name;
private int size;
public Country(String name, int size) {
this.name = name;
this.size = size;
}
public String getName() {
return name;
}
public int getSize() {
return size;
}
}
Main.main(null);
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(3);
list.add(6);
list.add(9);
list.add(10);
list.add(2);
list.add(1);
public ArrayList<Integer> everyOther(ArrayList<Integer> list) {
for (int i = list.size() - 1; i >= 0; i--) {
if (i % 2 == 0) {
list.remove(i);
}
}
return list;
}
System.out.println(everyOther(list));
ArrayList<Character> list = new ArrayList<Character>();
list.add('k');
list.add('m');
list.add('s');
list.add('l');
list.add('o');
list.add('j');
public ArrayList<Character> overwrite(ArrayList<Character> list) {
int originalSize = list.size();
list.clear();
for (char c = 'a'; c < 'a' + originalSize; c++) {
list.add(c);
}
return list;
}
System.out.println(overwrite(list));