Codelingo Hacks
Hacks for Codelingo
public void drawLine(int n) {
if (n < 1) {
return;
}
for (int i = 1; i <= n; i++) {
System.out.print("*");
}
System.out.println();
drawLine(n - 1);
}
drawLine(10);
public class Country {
private String name;
private int population;
public Country(String name, int population) {
this.name = name;
this.population = population;
}
public String getName() { return name; }
public int getPopulation() { return population; }
public int compareCountry(Country c) {
if (this.getPopulation() > c.getPopulation()) {
return 1;
} else if (this.getPopulation() < c.getPopulation()) {
return -1;
} else {
return 0;
}
}
}
public class SelectionSort {
public void sort(Country[] arr) {
for (int i = 0; i < arr.length-1; i++) {
int min_idx = i;
for (int j = i+1; j < arr.length; j++) {
// use compare country, only set min_idx if -1 (smaller pop)
if (arr[j].compareCountry(arr[min_idx]) == -1)
min_idx = j;
}
// assign temp country to swap
Country temp = arr[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp;
}
}
public static void main(String[] args) {
Country[] countries = new Country[5];
countries[0] = new Country("USA", 100);
countries[1] = new Country("China", 200);
countries[2] = new Country("Japan", 50);
countries[3] = new Country("Korea", 75);
countries[4] = new Country("India", 150);
SelectionSort ss = new SelectionSort();
ss.sort(countries);
for (int i = 0; i < countries.length; i++) {
System.out.println(countries[i].getName() + " " + countries[i].getPopulation());
}
}
}
SelectionSort.main(null);
public class CompareArrays {
public Boolean compare(ArrayList<Integer> arr1, ArrayList<Integer> arr2) {
if (arr1.size() != arr2.size()) {
return false;
}
for (int i = 0; i < arr1.size(); i++) {
if (arr1.get(i) != arr2.get(arr2.size() - i - 1)) {
return false;
}
}
return true;
}
public static void main(String[] args) {
ArrayList<Integer> arr1 = new ArrayList<Integer>();
arr1.add(1);
arr1.add(2);
arr1.add(3);
ArrayList<Integer> arr2 = new ArrayList<Integer>();
arr2.add(3);
arr2.add(2);
arr2.add(1);
CompareArrays ca = new CompareArrays();
System.out.println(arr1);
System.out.println(arr2);
System.out.println("Are they the same array reversed? " + ca.compare(arr1, arr2));
}
}
CompareArrays.main(null);
public class Remove {
public void remove(ArrayList<Integer> arr) {
for (int i = 0; i < arr.size(); i++) {
if (arr.get(i) % 2 == 0)
arr.remove(i);
}
}
public static void main(String[] args) {
ArrayList<Integer> arr = new ArrayList<Integer>();
arr.add(1);
arr.add(2);
arr.add(3);
arr.add(4);
arr.add(5);
arr.add(6);
Remove r = new Remove();
System.out.println(arr);
r.remove(arr);
System.out.println(arr);
}
}
Remove.main(null);