Lesson 3 Hacks
public void drawLine(int n) {
for (int i = 1; i <= n; i++) {
System.out.print("* ");
// System.out.print();
// drawLine(n - 1);
}
System.out.println();
if (n>1) {
drawLine(n-1);
}
}
drawLine(10);
public ArrayList<Character> alphabet(ArrayList<Character> myArr) {
int originalSize = myArr.size();
myArr.clear();
for (char c = 'a'; c < 'a' + originalSize; c++) {
myArr.add(c);
}
return myArr;
}
ArrayList<Character> old = new ArrayList<Character>(Arrays.asList('j','l','k','a','s','d'));
alphabet(old);
public ArrayList<Integer> remove(ArrayList<Integer> myArr) {
for (int i = 1; i < myArr.size(); i++) {
myArr.remove(i);
}
return myArr;
}
ArrayList<Integer> newArr= new ArrayList<Integer>(Arrays.asList(1,2,3,4,5,6,7,8,9,10));
remove(newArr);
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("Brazil", 8515767));
countries.add(new Country("India", 3287263));
countries.add(new Country("Australia", 7692024));
countries.add(new Country("China", 9596961));
countries.add(new Country("Canada", 9984670));
countries.add(new Country("Russia", 17098246));
countries.add(new Country("Argentina", 2780400));
countries.add(new Country("United States", 9372610));
// 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);