Static variables ================ a. If a black cell has 2 or 3 black neighbors, it stays black. b. If a black cell has less than 2 or more than 3 black neighbors it becomes white. c. If a white cell has 3 black neighbors, it becomes black. 1) How to represent cells in Conway's game of life? import java.util.List; import java.util.ArrayList; public class Cell { private List neighbors; private boolean isBlack = false; private boolean nextIsBlack = false; public Cell (boolean startState) { isBlack = startState; neighbors = new ArrayList(); } public void setNeighbor(Cell c) { neighbors.add(c); } public void computeNextState() { int numBlack = 0; for (Cell c : neighbors) { if (c.isBlack()) { numBlack++; } } if (isBlack) { if (numBlack < 2 || numBlack > 3) { nextIsBlack = false; } else { nextIsBlack = true; } } else if (numBlack == 3) { nextIsBlack = true; } } public boolean isBlack() { return isBlack; } public void nextState() { isBlack = nextIsBlack; } } 2) How to count the number of black spores? Introduction to data structures =============================== 1) What is a data structure? - It is a way to store data efficiently. 2) How many data structures do you know? 3) There are two basic ways to organize software: - Libraries: the client calls the methods of the provider. - Frameworks: the client implements interfaces that the provider calls. 3.1) Examples? 3.2) Data structures are organized in libraries or frameworks? 4) Many languages provide libraries where data structures are nicely organized. Can you give examples? 5) What are the advantages of having these classes? * Java Collections are based in seven interfaces: Collection - Set - SortedSet - List - Queue Map - SortedMap * They are all generic: public interface Collection 5.1) Difference between Set and List/Queue? 5.2) Difference between Queue and List? 5.3) Difference between Collection and Map? 6) Which methods we would normally find in a Collection? 7) How to convert an array to a collection? public static Collection toCollection(T[] a) { Collection c = new LinkedList(); for (T s : a) { c.add(s); } return c; } 8) How to access all the elements in the collection public static void iterate1(Collection c) { Iterator i = c.iterator(); while (i.hasNext()) { System.out.print(i.next() + " "); } System.out.println(); } public static void iterate2(Collection c) { for (T s : c) { System.out.print(s + " "); } System.out.println(); } 9) When to use iterators? Use Iterator instead of the for-each construct when you need to: -Remove the current element. The for-each construct hides the iterator, so you cannot call remove. - Iterate over multiple collections in parallel. 10) How to remove elements from an array? public static void remove(Collection c, T s) { Iterator i = c.iterator(); while (i.hasNext()) { T aux = i.next(); if (aux.equals(s)) { i.remove(); } } } public static void main(String args[]) { Collection c = toCollection(args); iterate1(c); iterate2(c); remove(c, "a"); iterate1(c); } 11) Why can't I use == instead of equals? 12) How to remove duplicates from a collection? public static Collection removeDups(Collection c) { Collection noDups = new LinkedHashSet(c); return noDups; } public static void main(String args[]) { Collection c = toCollection(args); iterate2(c); c = removeDups(c); iterate1(c); } * Sets contain three implementations: HashSet, TreeSet, and LinkedHashSet. 13) What is the difference between them? 14) Write a method that finds all the duplicates in a collection: public static Collection findDups(Collection c) { Set elements = new HashSet(); Collection dups = new LinkedList(); for (T e : c) { if (!elements.add(e)) { dups.add(e); } } return dups; } 15) Why I use Set to refer to the data, instead of HashSet? 16) How to see if the words in the result of findDups are in alphabetical order? for (T e : elements) { System.out.println("- " + e); } 17) And how to guarantee this ordering? Set elements = new TreeSet(); 18) Write a program that finds all the unique words, and store them in a collection in alphabetical order: public static Collection findUnique(Collection c) { Set elements = new TreeSet(c); Collection dups = findDups(c); elements.removeAll(dups); return elements; } public static void main(String args[]) { Collection c = toCollection(args); System.out.println("List of unique words:"); iterate2(findUnique(c)); } 19) Which operations we would find in lists, that are not in Collections? Positional access, search to index, range view 20) How to add one list to another? list1.addAll(list2); 21) How to code a method that swaps two elements of a list? public static void swap(List a, int i, int j) { E tmp = a.get(i); a.set(i, a.get(j)); a.set(j, tmp); } 22) How to shuffle the elements in a list? public static void shuffle(List list, Random rnd) { for (int i = list.size(); i > 1; i--) swap(list, i - 1, rnd.nextInt(i)); } 23) A curious thing is happening here: I said before that we cannot insert elements into a collection of , but is this not what shuffle is doing? 24) Would it be possible? public static void insert(List list) { list.set(1, list.get(1)); } 25) The shuffle method is part of the utility class Collections. How to shuffle the words in the input command line? import java.util.*; public class Shuffle { public static void main(String[] args) { List list = new ArrayList(); for (String a : args) list.add(a); Collections.shuffle(list, new Random()); System.out.println(list); } } - or - import java.util.*; public class Shuffle { public static void main(String[] args) { List list = Arrays.asList(args); Collections.shuffle(list); System.out.println(list); } } * There is an iterator proper to lists, called ListIterator 26) Which methods we would find in ListIterator? boolean hasNext(); E next(); boolean hasPrevious(); E previous(); int nextIndex(); int previousIndex(); void remove(); //optional void set(E e); //optional void add(E e); //optional 27) What does each of these methods do? 28) How to iterate backwards? for (ListIterator it = list.listIterator(list.size()); it.hasPrevious(); ) { Type t = it.previous(); ... } 29) How to code a method that replaces all the occurrences of a value in a list for another value? public static void replace(List list, E val, E newVal) { for (ListIterator it = list.listIterator(); it.hasNext(); ) if (val.equals(it.next())) it.set(newVal); } 30) How to replace a value by a sequence of values? public static void replace(List list, E val, List newVals) { for (ListIterator it = list.listIterator(); it.hasNext(); ){ if (val.equals(it.next())) { it.remove(); for (E e : newVals) it.add(e); } } } 31) How to test the replace's? // Testing the mono-replace: replace(l1, l1.get(0), l1.get(l1.size() - 1)); iterate2(l1); // Testing the multi-replace: replace(l1, l1.get(0), l2); iterate2(l1); 32) What would happen if we did: replace(l1, l1.get(0), l1); iterate2(l1); 33) How to remove a range of elements from a list? list.subList(fromIndex, toIndex).clear(); 34) How to code a program that deals a deck of cards? That is, this program receives a list of cards plus a hand size n, removes n elements from the deck, and returns these n elements: public static List dealHand(List deck, int n) { int deckSize = deck.size(); List handView = deck.subList(deckSize - n, deckSize); List hand = new ArrayList(handView); handView.clear(); return hand; } 35) How to code a program that builds a deck of cards, and deal hands of size n, where n is specified at command line? import java.util.*; class Deal { public static void main(String[] args) { int numHands = Integer.parseInt(args[0]); int cardsPerHand = Integer.parseInt(args[1]); // Make a normal 52-card deck. String[] suit = new String[] {"spades", "hearts", "diamonds", "clubs"}; String[] rank = new String[] {"ace","2","3","4","5","6","7","8", "9","10","jack","queen","king"}; List deck = new ArrayList(); for (int i = 0; i < suit.length; i++) for (int j = 0; j < rank.length; j++) deck.add(rank[j] + " of " + suit[i]); Collections.shuffle(deck); for (int i=0; i < numHands; i++) System.out.println(dealHand(deck, cardsPerHand)); } } Ex.: java Deal 4 5 36) The Collections library provides a number of algorithm on lists. Which algorithms are we likely to find there? http://java.sun.com/j2se/1.5.0/docs/api/java/util/Collections.html 37) What is the difference between a queue and a list again? 37.1) What kinds of lists are we going to find out there? 38) How to implement a heap sort using a priority queue? static List heapSort(Collection c) { Queue queue = new PriorityQueue(c); List result = new ArrayList(); while (!queue.isEmpty()) result.add(queue.remove()); return result; } 39) What is the comparison criterion that our priority queue uses? 40) How to implement a program that counts the number of words in the argument line? import java.util.*; public class Freq { public static void main(String[] args) { Map m = new HashMap(); // Initialize frequency table from command line for (String a : args) { Integer freq = m.get(a); m.put(a, (freq == null) ? 1 : freq + 1); } System.out.println(m.size() + " distinct words:"); System.out.println(m); } } 41) What if I want to see the frequency list in alphabetical order? Map m = new TreeMap(); 42) What if I want the order in which words appeared in the command line? Map m = new LinkedHashMap(); 43) How to iterate over the keys used in the map? for (KeyType key : m.keySet()) System.out.println(key); // An implementation of a data structure that is iterable: import java.util.ArrayList; import java.util.Iterator; public class MyList implements Iterable { private class Node { public E e; Node next; Node prev; public Node(E e, Node n, Node p) { this.e = e; next = n; prev = p; } } private Node first = null; private Node last = null; public MyList() { first = new Node(null, null, null); last = new Node(null, null, null); first.next = last; last.prev = first; } private Node getNode(int i) { int counter = 0; Node aux = first.next; for (; counter < i; aux = aux.next) { counter++; } return aux; } public void add(E e) { Node aux = last; aux.e = e; last = new Node(null, null, aux); aux.next = last; } public void set(int i, E e) { Node aux = getNode(i); aux.e = e; } public E get(int i) { return getNode(i).e; } private class MyIterator implements Iterator { Node current; Node first; Node end; public MyIterator(Node first, Node last) { this.first = first; current = first.next; end = last; } public boolean hasNext() { return current != end; } public E next() { E e = current.e; current = current.next; return e; } public void remove() { current.prev = current.prev.prev; current.prev.next = current; } } public Iterator iterator() { return new MyIterator(first, last); } }