DM550 Introduction to Programming part 2. Jan Baumbach.

Similar documents
Data Structures in the Java API

Class 32: The Java Collections Framework

Working with Java Collections

Collections in Java. Arrays. Iterators. Collections (also called containers) Has special language support. Iterator (i) Collection (i) Set (i),

JAVA COLLECTIONS FRAMEWORK

Per imparare a programmare bisogna programmare

The Java Collections Framework

D06 PROGRAMMING with JAVA

Java Map and Set collections

Generic Types in Java. Example. Another Example. Type Casting. An Aside: Autoboxing 4/16/2013 GENERIC TYPES AND THE JAVA COLLECTIONS FRAMEWORK.

Java Software Structures

Chapter 8: Bags and Sets

Data Structures and Algorithms Lists

1.00 Lecture 35. Data Structures: Introduction Stacks, Queues. Reading for next time: Big Java: Data Structures

CSE 2123 Collections: Sets and Iterators (Hash functions and Trees) Jeremy Morris

Java Collection Framework hierarchy. What is Data Structure? Chapter 20 Lists, Stacks, Queues, and Priority Queues

API for java.util.iterator. ! hasnext() Are there more items in the list? ! next() Return the next item in the list.

Universidad Carlos III de Madrid

Data Structures and Algorithms

Big O and Limits Abstract Data Types Data Structure Grand Tour.

Basic Programming and PC Skills: Basic Programming and PC Skills:

1. The memory address of the first element of an array is called A. floor address B. foundation addressc. first address D.

Java Coding Practices for Improved Application Performance

Lecture 2: Data Structures Steven Skiena. skiena

Principles of Software Construction: Objects, Design and Concurrency. Java Collections. toad Fall 2013

Outline. Computer Science 331. Stack ADT. Definition of a Stack ADT. Stacks. Parenthesis Matching. Mike Jacobson

STACKS,QUEUES, AND LINKED LISTS

Practical Session 4 Java Collections

What is a Stack? Stacks and Queues. Stack Abstract Data Type. Java Interface for Stack ADT. Array-based Implementation

LINKED DATA STRUCTURES

Sequential Data Structures

This lecture. Abstract data types Stacks Queues. ADTs, Stacks, Queues Goodrich, Tamassia

Analysis of a Search Algorithm

CompSci-61B, Data Structures Final Exam

Ordered Lists and Binary Trees

1 of 1 24/05/ :23 AM

Last not not Last Last Next! Next! Line Line Forms Forms Here Here Last In, First Out Last In, First Out not Last Next! Call stack: Worst line ever!

Linked Lists, Stacks, Queues, Deques. It s time for a chainge!

Course: Programming II - Abstract Data Types. The ADT Stack. A stack. The ADT Stack and Recursion Slide Number 1

CS 2112 Spring Instructions. Assignment 3 Data Structures and Web Filtering. 0.1 Grading. 0.2 Partners. 0.3 Restrictions

DATA STRUCTURE - STACK

Hash Tables. Computer Science E-119 Harvard Extension School Fall 2012 David G. Sullivan, Ph.D. Data Dictionary Revisited

1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++

cs2010: algorithms and data structures

Programming with Data Structures

DATA STRUCTURES USING C

CMSC 202H. ArrayList, Multidimensional Arrays

Queues Outline and Required Reading: Queues ( 4.2 except 4.2.4) COSC 2011, Fall 2003, Section A Instructor: N. Vlajic

Course: Programming II - Abstract Data Types. The ADT Queue. (Bobby, Joe, Sue, Ellen) Add(Ellen) Delete( ) The ADT Queues Slide Number 1

Data Structures and Algorithms Written Examination

dictionary find definition word definition book index find relevant pages term list of page numbers

Stacks and queues. Algorithms and Data Structures, Fall Rasmus Pagh. Based on slides by Kevin Wayne, Princeton

Collections Classes for Real-Time and High-Performance Applications. July 4, 2005 Jean-Marie Dautelle

CSE373: Data Structures and Algorithms Lecture 1: Introduction; ADTs; Stacks/Queues. Linda Shapiro Spring 2016

Sorting revisited. Build the binary search tree: O(n^2) Traverse the binary tree: O(n) Total: O(n^2) + O(n) = O(n^2)

CompuScholar, Inc. Alignment to Utah's Computer Programming II Standards

Abstract Data Type. EECS 281: Data Structures and Algorithms. The Foundation: Data Structures and Abstract Data Types

Data Structures and Algorithms

Arrays. Atul Prakash Readings: Chapter 10, Downey Sun s Java tutorial on Arrays:

Quiz 4 Solutions EECS 211: FUNDAMENTALS OF COMPUTER PROGRAMMING II. 1 Q u i z 4 S o l u t i o n s

A binary search tree or BST is a binary tree that is either empty or in which the data element of each node has a key, and:

Efficient Data Structures for Decision Diagrams

CS104: Data Structures and Object-Oriented Design (Fall 2013) October 24, 2013: Priority Queues Scribes: CS 104 Teaching Team

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming

CmpSci 187: Programming with Data Structures Spring 2015

recursion, O(n), linked lists 6/14

ECE 250 Data Structures and Algorithms MIDTERM EXAMINATION /5:15-6:45 REC-200, EVI-350, RCH-106, HH-139

Algorithms and Data Structures

CHAPTER 4 ESSENTIAL DATA STRUCTRURES

Queues and Stacks. Atul Prakash Downey: Chapter 15 and 16

4.5 Symbol Table Applications

Java Interview Questions and Answers

1. Define: (a) Variable, (b) Constant, (c) Type, (d) Enumerated Type, (e) Identifier.

Introduction to Stacks

Software Development with UML and Java 2 SDJ I2, Spring 2010

Chapter 3: Restricted Structures Page 1

Data Types. Abstract Data Types. ADTs as Design Tool. Abstract Data Types. Integer ADT. Principle of Abstraction

TESTING WITH JUNIT. Lab 3 : Testing

STORM. Simulation TOol for Real-time Multiprocessor scheduling. Designer Guide V3.3.1 September 2009

Data Structures in Java. Session 15 Instructor: Bert Huang

Introduction to Object-Oriented Programming

Singly linked lists (continued...)

22c:31 Algorithms. Ch3: Data Structures. Hantao Zhang Computer Science Department

Stacks. Stacks (and Queues) Stacks. q Stack: what is it? q ADT. q Applications. q Implementation(s) CSCU9A3 1

Getting Started with the Internet Communications Engine

Introduction to Data Structures

Class Overview. CSE 326: Data Structures. Goals. Goals. Data Structures. Goals. Introduction

Introduction to Programming System Design. CSCI 455x (4 Units)

Java SE 8 Programming

Lecture Notes on Binary Search Trees

Stacks. Data Structures and Data Types. Collections

Algorithms and Data S tructures Structures Stack, Queues, and Applications Applications Ulf Leser

Java the UML Way: Integrating Object-Oriented Design and Programming

Algorithms and Data Structures Written Exam Proposed SOLUTION

Transcription:

DM550 Introduction to Programming part 2 Jan Baumbach jan.baumbach@imada.sdu.dk http://www.baumbachlab.net

PROJECT 2

Organizational Details The project has to be passed to pass the course It has to be done individually. No co-operation! You may talk about the problem, however, and share ideas on how to solve it. Deliverables: Written 4-page report as specified in the project description Deadline: January 12, 2016, 23:59 ENOUGH - now for the ABSTRACT part 3

Sudoku solving Pen & paper game played on a 9 x 3 x 3 grid Goal: Distribute the numbers from 1-9 in each of the 3x3 fields such that in each 3x3-field, as well as in each 9er-row and each 9er-column every number occurs exactly once Task I: Implement ADT solving a given input game Task II: Implement a GUI 4

Sudoku solving http://en.wikipedia.org/wiki/sudoku 5

Sudoku solving http://en.wikipedia.org/wiki/sudoku 6

Sudoku solving X X 8 1 X X 5 X X 9 6 X X 8 X X X X X 5 X X 3 6 X 9 8 X X 7 X 6 9 X 1 2 X X 6 8 X 7 3 X X 8 1 X 4 5 X 6 X X 4 2 X 6 7 X X 8 X X X X X 4 X X 6 3 X X 5 X X 8 7 X X http://en.wikipedia.org/wiki/sudoku 7

Sudoku solving X X 8 1 X X 5 X X 9 6 X X 8 X X X X X 5 X X 3 6 X 9 8 X X 7 X 6 9 X 1 2 X X 6 8 X 7 3 X X 8 1 X 4 5 X 6 X X 4 2 X 6 7 X X 8 X X X X X 4 X X 6 3 X X 5 X X 8 7 X X +-------+-------+-------+ 3 7 8 1 9 4 5 2 6 9 6 4 2 8 5 1 3 7 1 5 2 7 3 6 4 9 8 +-------+-------+-------+ 5 4 7 3 6 9 8 1 2 2 9 6 8 1 7 3 5 4 8 1 3 4 5 2 6 7 9 +-------+-------+-------+ 4 2 1 6 7 3 9 8 5 7 8 9 5 4 1 2 6 3 6 3 5 9 2 8 7 4 1 +-------+-------+-------+ http://en.wikipedia.org/wiki/sudoku 8

Sudoku solving Find the project description at http://www.imada.sdu.dk/~jbaumbac/download/teaching/ws16-17/dm505/project/introduction_to_programming_java_project.p df Task I: Implement ADT solving a given input game Task II: Implement a GUI Additional challenge: Use recursions in the solver! Hint: Use Java s SWING library when possible 9

COLLECTION CLASSES & GENERIC PROGRAMMING 10

Java Collections Framework Java comes with a wide library of collection classes Examples: ArrayList TreeSet HashMap idea is to provide well-implemented standard ADTs your own ADTs can build upon this foundation collection classes store arbitrary objects all collection classes implement Collection or Map thus, simple and standardized interface across different classes 11

Generic Types (revisited) type casts for accessing elements are unsafe! solution is to use generic types instead of using an array of objects, use array of some type E Example: public class MyArrayList<E> implements List<E> { private E[] data; public E get(int i) { return this.data[i]; } } 12

Generic Programming the use of generic types is referred to as generic programming generic types can and should be used: by the user of collection classes Example: List<String> list = new ArrayList<String>(); when implementing ADTs Example: public class MyCollection<E> when implementing constructors and methods Example: public E getelement(int index) { } 13 when implementing static functions Example: public <E> void add(listnode<e> n, E elem);

Generic Programming when a class has parameter type <E>, E is used like normal type instances of the class are defined by substituting concrete type Example: public class Mine<E> Mine<String> mine = more than one parameter is possible Example: public interface Map<K,V> when defining static function, prefix return type by parameter <E> inside function, E is used like normal type Example: public <E> void add(listnode<e> n, E elem); 14

Generic Programming we can define that a parameter type extends some interface/class Example: public interface BinTree<E extends Comparable> { } then all types E are usable, that implement Comparable using? we can define wildcard types Example: public boolean addall(collection<? extends E> c) { } here, elements can be any type that extends E 15

Collection ADT: Specification interface Collection<E> specifies standard operations boolean isempty(); // true, if there are no elements int size(); // returns number of elements boolean contains(object o); // is object element? boolean add(e e); // add an element; true if modified boolean remove(object o); // remove an element Iterator<E> iterator(); // iterate over all elements boolean addall(collection<? extends E> c); // add all clear, containsall, removeall, retainall, toarray, operations make sense both for lists, queues, stacks, sets, next: interface Iterator<E> 16

Iterator ADT: Specification iterate over elements of collections (= data) operations defined by interface Iterator<E>: public interface Iterator<E> { public boolean hasnext(); // is there another element? public E next(); // get next element public void remove(); // remove current element } can be used to access all elements of the collection order is determined by specification or implementation 17

Iterator ADT: Example 1 Example (iterate over all elements of an ArrayList): ArrayList<String> list = new ArrayList<String>(); list.add("hej"); list.add("med"); list.add("dig"); Iterator<String> iter = list.iterator(); while (iter.hasnext()) { String str = iter.next(); System.out.println(str); } no need to iterative over indices 0, 1,, list.size()-1 18

Extended for Loop also called for each loop iterative over each element of an array or a collection Example 1 (summing elements of an array): int[] numbers = new int[] {1, 2, 3, 5, 7, 11, 13}; int sum = 0; for (int n : numbers) { sum += n; } Example 2 (multiplying elements of a list): List<Integer> list = new ArrayList(Arrays.asList(numbers)); int prod = 1; for (int i : list) { prod *= i; } 19

List ADT: Usage interface List<E> extends Collection<E> additional operation that make no sense for non-lists (e.g. get) can be sorted by static method in class Collections Example: int[] numbers = new int[] {1, 2, 3, 5, 7, 11, 13}; List<Integer> list = new ArrayList(Arrays.asList(numbers)); Collections.sort(list); requires that elements implement Comparable full signature: public static <T extends Comparable<? super T>> void sort(list<t> list); 20

List ADT: Implementations ArrayList based on dynamic arrays very good first choice in >90% of applications LinkedList based on doubly-linked lists has prev member variable pointing to previous list node useful when adding and removing a lot in the middle do not use for Queue use ArrayDeque instead! Vector based on dynamic arrays old implementation, not synchronized use ArrayList! Stack based on Vector do not use for Stack use ArrayDeque instead! 21

Queue ADT: Specification & Implem. interface Queue<E> extends Collection<E> data are arbitrary objects of type E defines additional operations over Collection<E>: public boolean offer(e e); // alternative name to add public E peek(); // return head public E element(); // alternative name to peek public E poll(); // remove and return head extended again by interface Deque<E> providing support for adding AND removing at both ends Implementations: ArrayDeque with offer == offerlast and poll == pollfirst LinkedList only useful, when not a pure Queue 22

Stack ADT: Specification & Implem. class Stack<E> implements Collection<E> data are arbitrary objects of type E defines additional operations over Collection<E>: public E push(e e); // add on top of stack public E peek(); // return top element public E pop(); // remove and return top public int search(object o); // return 1-based index superseded by interface Deque<E> providing support for adding AND removing at both ends Alternative Implementations: ArrayDeque with push == addfirst and pop == removefirst 23

Deque ADT: Specification & Implem. interface Deque<E> extends Collection<E> data are arbitrary objects of type E defines additional operations over Collection<E>: addfirst, offerfirst, addlast, offerlast removefirst, pollfirst, removelast, polllast getfirst, peekfirst, getlast, peeklast add*, remove*, get* throw exceptions offer*, poll*, peek* return special value Implementations: ArrayDeque fast and preferred LinkedList only use when more than Deque needed 24

Set ADT: Specification interface List<E> extends Collection<E> unordered sequences of objects without duplicates no additional operations, as Collection<E> already specifies isempty, size, contains, add, remove, no index-based access to elements, as order undefined elements MUST implement equals and hashcode correctly: 1. for two elements e1 and e2 that are equal, both e1.equals(e2) and e2.equals(e1) must return true 2. for two elements e1 and e2 that are equal, we must have e1.hashcode() == e2.hashcode() 3. for two elements e1 and e2 that are NOT equal, both e1.equals(e2) and e2.equals(e1) must return false 25

Set ADT: Example Example (intersecting two sets): int[] n1 = new int[] {1, 2, 3, 5, 7, 11, 13}; Set<Integer> set1 = new HashSet<Integer>(Arrays.asList(n1)); int[] n2 = new int[] {1, 3, 5, 7, 9}; Set<Integer> set2 = new HashSet<Integer>(Arrays.asList(n2)); Set<Integer> set3 = new HashSet<Integer>(set1); set3.retainall(set2); retainall modifies set3, thus we have (informally): set1 == {1, 2, 3, 5, 7, 11, 13} set2 == {1, 3, 5, 7, 9} set3 == {1, 3, 5, 7} 26

Iterator ADT: Example 2 Example (iterate over all elements of a HashSet): Set<String> set = new HashSet<String>(); set.add("hej"); set.add("hej"); set.add("hej"); Iterator<String> iter = set.iterator(); while (iter.hasnext()) { String str = iter.next(); System.out.println(str); } prints the two strings ( Hej, hej ) in some undefined order 27

Interface Comparator allows to specify how to compare elements public interface Comparator<E> { public int compare(e o1, E o2); // compare o1 and o2 public boolean equals(object obj); // equals other Comparator? } compare behaves like o1.compareto(o2) from Comparable<E> < 0 for o1 less than o2 ==0 for o1 equals o2 > 0 for o1 greater than o2 Comparable defines natural ordering Comparator can define additional orderings 28

Set ADT: Implementations HashSet based on hash tables very good choice if order really does not matter LinkedHashSet based on hash tables + linked list in addition to hash table keeps track of insertion order useful for keeping algorithms deterministic TreeSet based on special sort trees implements the SortedSet<E> interface useful for ordered sequences without duplicates can use Comparators for different orderings also useful when e.g. hash code not available 29

Map ADT: Specification 30 maps work like dictionaries in Python interface Map<K,V> specifies standard operations boolean isempty(); // true, if there are no mappings int size(); // returns number of mappings boolean containskey(object key); // is key mapped? boolean containsvalue(object value); // is value mapped? V get(object key); // return mapped value or null V put(k key, V value); // add mapping from key to value Set<K> keyset(); // set of all keys Collection<V> values(); // collection of all values Set<Map.Entry<K,V>> entryset(); // (key,value) pairs clear, putall, remove,

Map ADT: Example Example (using and modifying a phone directory): Map<String,Integer> dir = new HashMap<String,Integer>(); dir.put( janb", 65502327); dir.put("bwillis", 55555555); for (String key : dir.keyset()) { System.out.println(key+" -> "+dir.get(key)); } for (Map.Entry<String,Integer> entry : dir.entryset()) { System.out.println(entry.getKey()+" -> +entry.getvalue()); entry.setvalue(12345678); } dir.keyset().remove("bwillis"); // removes billis from map as well System.out.println(dir); // only janb is mapped 31

Hash Table a hash table uses the hashcode method to map objects to ints objects are stored in an array the position of the object is determined by its hash code modulo the length of the array Example: if o has hash code 10 and array has length 7, o is stored at position 10 % 7 == 3 more in DM507 Algorithms and Data Structures efficient for get and put assuming that hashcode is implemented in a useful way if two or more objects have the same hash code, the array stores a list of objects in that position 32

Map ADT: Implementations HashMap based on hash tables very good choice if order does not matter LinkedHashMap based on hash tables + linked list in addition to hash table keeps track of insertion order useful for keeping algorithms deterministic TreeMap based on special sort trees implements the SortedMap<K,V> interface useful for ordered mappings can use Comparators for different orderings also useful when e.g. hash code not available Hashtable based on hash tables old implementation only use for synchronization 33

THANKS! 34