Theoritical run times
|
|
- Deirdre O’Neal’
- 5 years ago
- Views:
Transcription
1 Touches of n Theoritical run times 2.5E+11 2E E+11 1E+11 5E Array length (n) Figure 1
2 cities A data structure containing all cities result list of cities in order to be visited initialsize = cities.size() Get number of cities currentcity = cities.get(randomnum) Get an initial city at random cities.remove(randomnum) Remove city from list Repeat until all cities have been added While (cities.size!= initialsize) Add current city to the result result.add(currentcity) distance = Infinity
3 Find the closest city to the current city and add it For (city possible in cities) If (getdistance(currentcity, possible) < distance closest = possible distance = getdistance(currentcity, possible) End if End for Remove the closest city so we don t consider it again cities.remove(closest) The closest city is now the current city currentcity = closest End while Figure 2 Begin TwoOpt repeats = 1 skip = Round(tour.Size/1000) If (skip <= 1) repeats = 2 End If While (improve < repeats)
4 distance = tour.routelength() For (i = 0; i < tour.size() - 1; i++) For (k = i + 1; k < tour.size() - 1; i++) newtour = twooptswap(tour, i, k) newdistance = newtour.routelength() If (newdistance < distance) tour = newtour distance = newdistance End If End For i += skip End For improve++ End While End TwoOpt Begin TwoOptSwap take route[0] to route[i-1] and add them in order to newroute take route[i] to route[k] and add them in reverse order to newroute take route[k+1] to end and add them in order to newroute return newroute End TwoOptSwap Begin checktour originaltour The tour that is created when loading in a TSPLib instance newtour The tour that is created when nearest neighbor algorithm or 2- opt swap are finished. If (originaltour.size()!= newtour.size()) return false The tour does not contain the correct amount of cities. End If tourset = new HashSet<City>(tour) Create a new tour that holds the city as a HashSet instead of an ArrayList, a hashset has no duplicates. If (tourset.size() < newtour.size()) return false There are duplicated cities in the tour End If return true The tour is valid End checktour
5
6 Run time (seconds) Average run times Size Figure 3 Figure 4
7 Figure 5 Figure 6
8 Figure 7
9 main.java import java.awt.color; import java.awt.graphics; import javax.swing.jcomponent; import javax.swing.jframe; class MyCanvas extends JComponent Tour list; public MyCanvas(Tour list) this.list = list; public void paint(graphics g) int[] x = new int[list.size()]; int[] y = new int[list.size()]; int count = 0; g.setcolor(color.red); for(city instance:list.cities) x[count] = (int)(instance.getx()/20); y[count] = (int)(instance.gety()/20); g.drawoval(x[count]-3, y[count]-3, 6, 6); g.filloval(x[count]-3, y[count]-3, 6, 6); count++; g.setcolor(color.blue); g.drawpolygon(x, y, x.length); public class main public static void main(string[] args) final String berlin52 = "./TSP Tours/berlin52.tsp"; final String rl1304 = "./TSP Tours/rl1304.tsp"; final String rl1323 = "./TSP Tours/rl1323.tsp"; final String rl1889 = "./TSP Tours/rl1889.tsp"; final String rl5915 = "./TSP Tours/rl5915.tsp"; final String rl5934 = "./TSP Tours/rl5934.tsp"; final String rl11849= "./TSP Tours/rl11849.tsp";
10 double start = System.currentTimeMillis(); Tour originallist = new Tour(); originallist = Tour.LoadTSPLib(berlin52); // Get cities array int originaltoursize = originallist.size(); System.out.println("Checking Original tour..."); originallist.checktour(originaltoursize); double tourlength = originallist.routelength(); // Calculate tour length Tour nearestneighbourlist = originallist.nearestneighboursort(); System.out.println("Checking NN tour..."); nearestneighbourlist.checktour(originaltoursize); double rearrangedtourlength = (nearestneighbourlist.routelength()); // Calculate tour length if (rearrangedtourlength < tourlength) System.out.println("Nearest neighbour tour is shorter"); else if (rearrangedtourlength > tourlength) System.out.println("Original tour is shorter"); System.out.println("Original : " + tourlength); System.out.println("Neighbour: " + rearrangedtourlength); System.out.println("Started calculating 2-opt..."); Tour twooptlist = nearestneighbourlist.twoopt(); double twoopttourlength = (twooptlist.routelength()); System.out.println("Checking 2Opt tour..."); twooptlist.checktour(originaltoursize); System.out.println("2-opt : " + twoopttourlength); double time = System.currentTimeMillis() - start; System.out.println("Solved in: " + time * " seconds"); JFrame window = new JFrame(); window.getcontentpane().setbackground(color.white); window.settitle("nearest Neighbour Route"); window.setbounds(30, 30, 1000, 1000); window.getcontentpane().add(new MyCanvas(nearestNeighbourList)); window.setvisible(true); JFrame window2 = new JFrame(); window2.getcontentpane().setbackground(color.white); window2.settitle("2-opt Route"); window2.setbounds(30, 30, 1000, 1000); window2.getcontentpane().add(new MyCanvas(twoOptList)); window2.setvisible(true); City.java import java.awt.geom.point2d; public class City
11 Point2D coordinates; int id; // Creates a city at given coordinates public City(float x, float y, int id) this.coordinates = new Point2D.Float(x, y); this.id = id; // Gets city's x coordinate public double getx() return this.coordinates.getx(); // Gets city's y coordinate public double gety() return this.coordinates.gety(); // Calculates distance between 2 cities public double getdistance(city city) // Distance formula double xdistance = Math.abs(this.getX() - city.getx()); double ydistance = Math.abs(this.getY() - city.gety()); double distance = Math.sqrt( (xdistance*xdistance) + (ydistance*ydistance) ); return public String tostring() return getx()+", "+gety(); Tour.java import java.io.bufferedreader; import java.io.filereader; import java.io.ioexception; import java.util.arraylist; import java.util.hashset; import java.util.set; import java.util.concurrent.threadlocalrandom; public class Tour public ArrayList<City> cities; // Default constructor public Tour() cities = new ArrayList<City>(); // Constructor with parameter public Tour(ArrayList<City> cities) this.cities = new ArrayList<City>(cities); // Constructor with parameter
12 public Tour(Tour cities) this.cities = new ArrayList<City>(cities.cities); // Constructor from filename // Load in TSPLib Instance. public static Tour LoadTSPLib (String fname) Tour result = new Tour(); BufferedReader br = null; try String currentline; int dimension = 0; // Dimension of problem boolean readingnodes = false; br = new BufferedReader(new FileReader(fName)); while ((currentline = br.readline())!= null) if (currentline.contains("eof")) // Read until end of file readingnodes = false; // Check to see if expected number of cities have been loaded if (result.size()!= dimension) System.out.println("Error loading cities"); System.exit(-1); // If reading in the node data if (readingnodes) String[] tokens = currentline.split(" "); // Split by spaces // Get city id int id = Integer.parseInt(tokens[0].trim()); // Get x and y coordinates float x = Float.parseFloat(tokens[1].trim()); float y = Float.parseFloat(tokens[2].trim()); City city = new City(x, y, id); // Hold city result.cities.add(city); // Add city to arraylist if (currentline.contains("dimension")) String[] tokens = currentline.split(":"); dimension = Integer.parseInt(tokens[1].trim()); if (currentline.contains("node_coord_section")) readingnodes = true; catch (IOException e)
13 e.printstacktrace(); finally try if (br!= null)br.close(); catch (IOException ex) ex.printstacktrace(); return result; // Calculate length of a TSP route public double RouteLength() double result = 0; // Route length City prev = cities.get(cities.size() - 1); // Get previous city // Go through each city in turn for(city city: cities) result += prev.getdistance(city); // Get distance from previous city prev = city; // set current city to previous return result; // Returns a city from the tour, with the given index public City GetCity(int index) return cities.get(index); // Adds a city to the tour public void AddCity(City city) cities.add(city); // Check if a city is contained in the tour public boolean ContainsCity(City city) if (cities.contains(city)) return true; return false; // Removes a city from the tour by given index public void RemoveCity(int index) cities.remove(index); // Removes a city from Tour public void RemoveCity(City city) cities.remove(city);
14 // Tour size (Number of cities) public int Size() return cities.size(); // Sort the tour by Nearest Neighbour public Tour nearestneighboursort() int initialsize = this.size(); Tour cities = new Tour(this); Tour result = new Tour(); int randomnum = ThreadLocalRandom.current().nextInt(0, cities.size()); City currentcity = cities.getcity(randomnum); cities.removecity(randomnum); City closest = cities.getcity(randomnum); // Repeat until all cities have been added while(result.size()!= initialsize) if (!(result.containscity(currentcity))) result.addcity(currentcity); // Add current city to result double distance = Double.POSITIVE_INFINITY; for(city possible:cities.cities) double currentdistance = currentcity.getdistance(possible); if (currentdistance == 0) System.out.println(possible); if (currentdistance < distance) closest = possible; // Closest city is possible city distance = currentdistance; // Get distance between current city and possible closest city cities.removecity(closest); currentcity = closest; return result; // 2-opt swap private Tour TwoOptSwap(Tour tour, int i, int k) Tour newtour = new Tour(); int size = tour.size(); // 1. take route[0] to route[i-1] and add them in order to new_route for (int j = 0; j <= i - 1; ++j) newtour.addcity(tour.getcity(j)); // 2. take route[i] to route[k] and add them in reverse order to new_route int count = 0; for (int j = i; j <= k; ++j)
15 newtour.addcity((tour.getcity(k - count))); count++; // 3. take route[k+1] to end and add them in order to new_route for (int j = k + 1; j < size; ++j) newtour.addcity(tour.getcity(j)); return newtour; // 2-opt swap handling public Tour TwoOpt() Tour tour = this; // Copy the tour to temp variable double distance = tour.routelength(); // Current tour length Tour newtour = new Tour(); int repeats = 1; double size = tour.size(); // Size of tour int skip = (int) Math.round((size/1000)); // Decides how many nodes to skip while performing 2-opt switch // If list is small repeat through whole list twice if (skip <= 1) repeats = 2; System.out.println("Will skip: " + skip); // Most outer loop count int loop = 0; while ( loop < repeats ) distance = tour.routelength(); // Get tour length // Loop through all nodes for (int i = 0; i < size - 1; i++) for (int k = i + 1; k < size; k++) newtour = TwoOptSwap(tour, i, k); // Perform 2-opt swap double newdistance = newtour.routelength(); // Get tour length // Check if new tour is shorter, if it is, keep it if (newdistance < distance) tour = newtour; distance = newdistance; i+=skip; // Skip nodes depending on skip value loop++; // Looped through entire list return tour;
16 // Check if a TSP route is valid public boolean checktour(int noofcities) if (noofcities!= this.size()) System.out.println("Invalid no of cities, " + (noofcities - this.size()) + " cities missing."); return false; Set<City> cityset = new HashSet<City>(this.cities); if(cityset.size() < this.size()) /* There are duplicates */ System.out.println("Duplication of cities detected. No of unique cities: " + cityset.size() + ", should be: " + this.size()); return false; System.out.println("Tour is valid"); return true;
CPS109 Lab 7. Source: Big Java, Chapter 7 Preparation: read Chapter 7 and the lecture notes for this week.
1 CPS109 Lab 7 Source: Big Java, Chapter 7 Preparation: read Chapter 7 and the lecture notes for this week. Objectives: 1. To practice using one- and two-dimensional arrays 2. To practice using partially
More informationCN208 Introduction to Computer Programming
CN208 Introduction to Computer Programming Lecture #11 Streams (Continued) Pimarn Apipattanamontre Email: pimarn@pimarn.com 1 The Object Class The Object class is the direct or indirect superclass of every
More informationpublic class Q1 { public int x; public static void main(string[] args) { Q1 a = new Q1(17); Q1 b = new Q1(39); public Q1(int x) { this.
CS 201, Fall 2013 Oct 2nd Exam 1 Name: Question 1. [5 points] What output is printed by the following program (which begins on the left and continues on the right)? public class Q1 { public int x; public
More informationA sample print out is: is is -11 key entered was: w
Lab 9 Lesson 9-2: Exercise 1, 2 and 3: Note: when you run this you may need to maximize the window. The modified buttonhandler is: private static class ButtonListener implements ActionListener public void
More informationList.java. Printed by Tom Smedsaas. Maj 23, 16 19:11 List.java. Tisdag Maj 24, 2016 List.java
1 import java.util.arraylist; 3 public class List { private static class Node { 5 int data; 6 Node next; 7 8 Node(int data, Node next) { 9 this.data = data; 10 this.next = next; 11 } 1 13 public String
More informationpackage As7BattleShip;
package As7BattleShip; Program: BattleshipBoard.java Author: Kevin Nider Date: 11/18/12 Description: Assignment 7: Runs the battleship game Input: ship placement board files and computer player type Output:
More informationANN exercise session
ANN exercise session In this exercise session, you will read an external file with Iris flowers and create an internal database in Java as it was done in previous exercise session. A new file contains
More informationInput from Files. Buffered Reader
Input from Files Buffered Reader Input from files is always text. You can convert it to ints using Integer.parseInt() We use BufferedReaders to minimize the number of reads to the file. The Buffer reads
More informationBBM 102 Introduction to Programming II Spring Exceptions
BBM 102 Introduction to Programming II Spring 2018 Exceptions 1 Today What is an exception? What is exception handling? Keywords of exception handling try catch finally Throwing exceptions throw Custom
More information!"# $ %&# %####' #&() % # # # #&* # ## +, # -
By Pep Jorge @joseplluisjorge Steema Software July 213!"# $ %&# %####' #&() % # # # #&* # ## +, # -. / " - $- * 11 1 1$ 2 11 1 3 4 / $ 5 5,+67 +68$ Copyright 213 Steema Software SL. Copyright Information.
More informationLecture 4: Exceptions. I/O
Lecture 4: Exceptions. I/O Outline Access control. Class scope Exceptions I/O public class Malicious { public static void main(string[] args) { maliciousmethod(new CreditCard()); } static void maliciousmethod(creditcard
More informationECM1406. Answer Sheet Lists
ECM1406 Answer Sheet Lists These questions are based on those found in Chapters 3 and 4 of the core text Data Structures Using Java by Malik and Nair. The source code for the ArrayListClass, UnorderedArrayList,
More informationSubmit your solution to the Desire2Learn drop box. You may submit as many versions as you like the last one will be graded.
CS46A Exam 2 Exam Rules You may use any books, notes, files, web sites of your choice, except as noted below. It is a good idea to compile and run your programs if you have the time to do it. You may NOT
More informationName:... ID:... class A { public A() { System.out.println( "The default constructor of A is invoked"); } }
KSU/CCIS/CS CSC 113 Final exam - Fall 12-13 Time allowed: 3:00 Name:... ID:... EXECRICE 1 (15 marks) 1.1 Write the output of the following program. Output (6 Marks): class A public A() System.out.println(
More informationNetworking Code CSCI 201 Principles of Software Development
Networking Code CSCI 201 Principles of Software Development Jeffrey Miller, Ph.D. jeffrey.miller@usc.edu Server Networking Client Networking Program Outline USC CSCI 201L Server Software A server application
More informationCS 201, Fall 2016 Sep 28th Exam 1
CS 201, Fall 2016 Sep 28th Exam 1 Name: Question 1. [5 points] Write code to prompt the user to enter her age, and then based on the age entered, print one of the following messages. If the age is greater
More informationpublic static void main(string[] args) { GTest mywindow = new GTest(); // Title This program creates the following window and makes it visible:
Basics of Drawing Lines, Shapes, Reading Images To draw some simple graphics, we first need to create a window. The easiest way to do this in the current version of Java is to create a JFrame object which
More informationG51PGP Programming Paradigms. Lecture OO-4 Aggregation
G51PGP Programming Paradigms Lecture OO-4 Aggregation 1 The story so far We saw that C code can be converted into Java code Note real object oriented code though Hopefully shows you how much you already
More informationException Handling CSCI 201 Principles of Software Development
Exception Handling CSCI 201 Principles of Software Development Jeffrey Miller, Ph.D. jeffrey.miller@usc.edu Outline Program USC CSCI 201L 2/19 Exception Handling An exception is an indication of a problem
More informationEXAMINATIONS 2011 Trimester 2, MID-TERM TEST. COMP103 Introduction to Data Structures and Algorithms SOLUTIONS
T E W H A R E W Ā N A N G A O T E Ū P O K O O T E I K A A M Ā U I VUW V I C T O R I A UNIVERSITY OF WELLINGTON Student ID:....................... EXAMINATIONS 2011 Trimester 2, MID-TERM TEST COMP103 Introduction
More informationCourse overview: Introduction to programming concepts
Course overview: Introduction to programming concepts What is a program? The Java programming language First steps in programming Program statements and data Designing programs. This part will give an
More information23 Sorting a text file using an ArrayList 24 The SortList class? 26 The SortList class? 27 Collections API: Collections class 30 The SortList class? 3
List of Slides 1 Title 2 Chapter 21: Collections 3 Chapter aims 4 Section 2: Example:Reversing a text file 5 Aim 6 Reversing a text file 7 Collections API 8 Collections API: Lists 9 Collections API: Lists:
More informationCS Week 11. Jim Williams, PhD
CS 200 - Week 11 Jim Williams, PhD This Week 1. Exam 2 - Thursday 2. Team Lab: Exceptions, Paths, Command Line 3. Review: Muddiest Point 4. Lecture: File Input and Output Objectives 1. Describe a text
More information4. Finding & Displaying Record of Salesman with minimum net income. 5. Finding & Displaying Record of Salesman with maximum net income.
Solution of problem#55 of Lab Assignment Problem Statement: Design & Implement a java program that can handle salesmen records of ABC Company. Each salesman has unique 4 digit id #, name, salary, monthly
More informationLab 11. A sample of the class is:
Lab 11 Lesson 11-2: Exercise 1 Exercise 2 A sample of the class is: public class List // Methods public void store(int item) values[length] = item; length++; public void printlist() // Post: If the list
More information2018/2/5 话费券企业客户接入文档 语雀
1 2 2 1 2 1 1 138999999999 2 1 2 https:lark.alipay.com/kaidi.hwf/hsz6gg/ppesyh#2.4-%e4%bc%81%e4%b8%9a%e5%ae%a2%e6%88%b7%e6%8e%a5%e6%94%b6%e5%85%85%e5 1/8 2 1 3 static IAcsClient client = null; public static
More informationFILE I/O IN JAVA. Prof. Chris Jermaine
FILE I/O IN JAVA Prof. Chris Jermaine cmj4@cs.rice.edu 1 Our Simple Java Programs So Far Aside from screen I/O......when they are done, they are gone They have no lasting effect on the world When the program
More information13: Error Handling with Exceptions. The basic philosophy of Java is that "badly formed code will not be run."
13: Error Handling with Exceptions The basic philosophy of Java is that "badly formed code will not be run." 1 Error Handling in Java C++/Java: Badly-formed code will not compile. Java: Badly-formed code,
More informationSimple Data Source Crawler Plugin to Set the Document Title
Simple Data Source Crawler Plugin to Set the Document Title IBM Content Analytics 1 Contents Introduction... 4 Basic FS Crawler behavior.... 8 Using the Customizer Filter to Modify the title Field... 13
More informationSteps: First install hadoop (if not installed yet) by, https://sl6it.wordpress.com/2015/12/04/1-study-and-configure-hadoop-for-big-data/
SL-V BE IT EXP 7 Aim: Design and develop a distributed application to find the coolest/hottest year from the available weather data. Use weather data from the Internet and process it using MapReduce. Steps:
More informationPROGRAMMING FUNDAMENTALS
PROGRAMMING FUNDAMENTALS Q1. Name any two Object Oriented Programming languages? Q2. Why is java called a platform independent language? Q3. Elaborate the java Compilation process. Q4. Why do we write
More informationFIFO PAGE REPLACEMENT : import java.io.*; public class FIFO {
FIFO PAGE REPLACEMENT : import java.io.*; public class FIFO public static void main(string[] args) throws IOException BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int frames,
More informationCSci 1103 Final. Name: Student ID:
CSci 1103 Final Name: Student ID: Instructions: Please pick and answer any 10 of the 12 problems for a total of 100 points. If you answer more than 10 problems, only the first 10 will be graded. The time
More informationBirkbeck (University of London) Software and Programming 1 In-class Test Mar 2018
Birkbeck (University of London) Software and Programming 1 In-class Test 2.1 22 Mar 2018 Student Name Student Number Answer ALL Questions 1. What output is produced when the following Java program fragment
More informationCPSC 441 Tutorial TCP Server. Department of Computer Science University of Calgary
CPSC 441 Tutorial TCP Server Department of Computer Science University of Calgary TCP Socket Client Server Connection Request Server Listening on welcoming socket Client Socket Server Socket Data Simple
More informationCS1092: Tutorial Sheet: No 3 Exceptions and Files. Tutor s Guide
CS1092: Tutorial Sheet: No 3 Exceptions and Files Tutor s Guide Preliminary This tutorial sheet requires that you ve read Chapter 15 on Exceptions (CS1081 lectured material), and followed the recent CS1092
More informationDo not turn to the next page until the start of the exam.
Principles of Java Language with Applications, PIC20a E. Ryu Winter 2017 Final Exam Monday, March 20, 2017 3 hours, 8 questions, 100 points, 11 pages While we don t expect you will need more space than
More informationCS163/164 Final Exam Study Session
CS163/164 Final Exam Study Session Review What is printed? public static void main (String [] args){ String s = "Winter Break"; System.out.println(s.indexOf('c')); System.out.println(s.indexOf('e')); System.out.println(s.charAt(2));
More informationASSIGNMENT 4. COMP-202C, Summer Due: Monday June 29th, 2015 (23:30)
ASSIGNMENT 4 COMP-202C, Summer 2015 Due: Monday June 29th, 2015 (23:30) Please read the entire pdf before starting. You must do this assignment individually and, unless otherwise specified, you must follow
More informationPage 1 of 16. Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.
Page 1 of 16 HAND IN Answers Are Recorded on Question Paper QUEEN'S UNIVERSITY SCHOOL OF COMPUTING CISC212, FALL TERM, 2005 FINAL EXAMINATION 9am to 12noon, 19 DECEMBER 2005 Instructor: Alan McLeod If
More informationInheritance Systems. Merchandise. Television Camcorder Shirt Shoe Dress 9.1.1
Merchandise Inheritance Systems Electronics Clothing Television Camcorder Shirt Shoe Dress Digital Analog 9.1.1 Another AcademicDisciplines Hierarchy Mathematics Engineering Algebra Probability Geometry
More informationGeneral Certificate of Education Advanced Subsidiary Examination June 2010
General Certificate of Education Advanced Subsidiary Examination June 2010 Computing COMP1/PM/JA Unit 1 Problem Solving, Programming, Data Representation and Practical Exercise Preliminary Material A copy
More informationCOT 3530: Data Structures. Giri Narasimhan. ECS 389; Phone: x3748
COT 3530: Data Structures Giri Narasimhan ECS 389; Phone: x3748 giri@cs.fiu.edu www.cs.fiu.edu/~giri/teach/3530spring04.html Evaluation Midterm & Final Exams Programming Assignments Class Participation
More informationStudying software design patterns is an effective way to learn from the experience of others
Studying software design patterns is an effective way to learn from the experience of others Design Pattern allows the requester of a particular action to be decoupled from the object that performs the
More informationF I N A L E X A M I N A T I O N
Faculty Of Computer Studies M257 Putting Java to Work F I N A L E X A M I N A T I O N Number of Exam Pages: (including this cover sheet( Spring 2011 April 4, 2011 ( 5 ) Time Allowed: ( 1.5 ) Hours Student
More informationBBM 102 Introduction to Programming II Spring 2017
BBM 102 Introduction to Programming II Spring 2017 Exceptions Instructors: Ayça Tarhan, Fuat Akal, Gönenç Ercan, Vahid Garousi Today What is an exception? What is exception handling? Keywords of exception
More informationCS314 Software Engineering Sprint 3
CS314 Software Engineering Sprint 3 Dave Matthews Sprint 3 Summary Use Level 2 and 3 software engineering processes/tools Clean Code, Coverage, White Box Testing, Code Climate Learn some additional technologies
More informationProgramming Problems 22nd Annual Computer Science Programming Contest
Programming Problems 22nd Annual Computer Science Programming Contest Department of Mathematics and Computer Science Western Carolina University 5 April 2011 Problem One: Add Times Represent a time by
More informationBinghamton University. CS-140 Fall Problem Solving. Creating a class from scratch
Problem Solving Creating a class from scratch 1 Recipe for Writing a Class 1. Write the class boilerplate stuff 2. Declare Fields 3. Write Creator(s) 4. Write accessor methods 5. Write mutator methods
More informationAPPENDIX. public void cekroot() { System.out.println("nilai root : "+root.data); }
APPENDIX CLASS NODE AS TREE OBJECT public class Node public int data; public Node left; public Node right; public Node parent; public Node(int i) data=i; PROCEDURE BUILDING TREE public class Tree public
More informationPage 1 of 16. Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.
Page 1 of 16 SOLUTION HAND IN Answers Are Recorded on Question Paper QUEEN'S UNIVERSITY SCHOOL OF COMPUTING CISC212, FALL TERM, 2005 FINAL EXAMINATION 9am to 12noon, 19 DECEMBER 2005 Instructor: Alan McLeod
More informationSample Solution A10 R6.2 R6.3 R6.5. for (i = 10; i >= 0; i++)... never ends. for (i = -10; i <= 10; i = i + 3)... 6 times
Sample Solution A10 R6.2 0000000000 0123456789 0246802468 0369258147 0482604826 0505050505 0628406284 0741852963 0864208642 0987654321 R6.3 for (i = 10; i >= 0; i++)... never ends for (i = -10; i
More informationLecture 4: The class hierarchy; static components
1 CS/ENGRD 2110 FALL2017 Lecture 4: The class hierarchy; static components http://cs.cornell.edu/courses/cs2110 Announcements 2 A1 Due Thursday A2 Out Today Where am I? Big ideas so far. 3 Java variables
More informationMidterm assessment - MAKEUP Fall 2010
M257 MTA Faculty of Computer Studies Information Technology and Computing Date: /1/2011 Duration: 60 minutes 1-Version 1 M 257: Putting Java to Work Midterm assessment - MAKEUP Fall 2010 Student Name:
More informationCSPP : Introduction to Object-Oriented Programming
CSPP 511-01: Introduction to Object-Oriented Programming Harri Hakula Ryerson 256, tel. 773-702-8584 hhakula@cs.uchicago.edu August 7, 2000 CSPP 511-01: Lecture 15, August 7, 2000 1 Exceptions Files: Text
More information1.00 Introduction to Computers and Engineering Problem Solving. Quiz 1 March 7, 2003
1.00 Introduction to Computers and Engineering Problem Solving Quiz 1 March 7, 2003 Name: Email Address: TA: Section: You have 90 minutes to complete this exam. For coding questions, you do not need to
More informationJava Review Outline. basics exceptions variables arrays modulo operator if statements, booleans, comparisons loops: while and for
Java Review Outline basics exceptions variables arrays modulo operator if statements, booleans, comparisons loops: while and for Java basics write a simple program, e.g. hello world http://www2.hawaii.edu/~esb/2017fall.ics211/helloworl
More informationI/O STREAM (REQUIRED IN THE FINAL)
I/O STREAM (REQUIRED IN THE FINAL) STREAM A stream is a communication channel that a program has with the outside world. It is used to transfer data items in succession. An Input/Output (I/O) Stream represents
More informationObject Oriented Design. Object-Oriented Design. Inheritance & Polymorphism. Class Hierarchy. Goals Robustness Adaptability Flexible code reuse
Object-Oriented Design Object Oriented Design Goals Robustness Adaptability Flexible code reuse Principles Abstraction Encapsulation Modularity March 2005 Object Oriented Design 1 March 2005 Object Oriented
More informationCS Week 14. Jim Williams, PhD
CS 200 - Week 14 Jim Williams, PhD This Week 1. Final Exam: Conflict Alternatives Emailed 2. Team Lab: Object Oriented Space Game 3. BP2 Milestone 3: Strategy 4. Lecture: More Classes and Additional Topics
More informationWeek 12. Streams and File I/O. Overview of Streams and File I/O Text File I/O
Week 12 Streams and File I/O Overview of Streams and File I/O Text File I/O 1 I/O Overview I/O = Input/Output In this context it is input to and output from programs Input can be from keyboard or a file
More informationCS 200 File Input and Output Jim Williams, PhD
CS 200 File Input and Output Jim Williams, PhD This Week 1. WaTor Change Log 2. Monday Appts - may be interrupted. 3. Optional Lab: Create a Personal Webpage a. demonstrate to TA for same credit as other
More informationCalling and Returning From a Method. Control Flow
Calling and Returning From a Method Program execution normally proceeds from one statement to the next. When the call instruction executes, it causes the method body to begin executing. (transfer of )
More informationEJB - INTERCEPTORS. Interceptor methods can be applied or bound at three levels
http://www.tutorialspoint.com/ejb/ejb_interceptors.htm EJB - INTERCEPTORS Copyright tutorialspoint.com EJB 3.0 provides specification to intercept business methods calls using methods annotated with @AroundInvoke
More informationObject-Oriented Design. March 2005 Object Oriented Design 1
Object-Oriented Design March 2005 Object Oriented Design 1 Object Oriented Design Goals Robustness Adaptability Flexible code reuse Principles Abstraction Encapsulation Modularity March 2005 Object Oriented
More informationObject-oriented Programming and Software Engineering CITS1001. Multiple-choice Mid-semester Test
Object-oriented Programming and Software Engineering CITS1001 Multiple-choice Mid-semester Test Semester 1, 2015 Mark your solutions on the provided answer page, by filling in the appropriate circles.
More informationCS/ENGRD 2110 FALL2017. Lecture 4: The class hierarchy; static components
1 CS/ENGRD 2110 FALL2017 Lecture 4: The class hierarchy; static components http://cs.cornell.edu/courses/cs2110 Announcements 2 A0, HW1 due tonight Next week s recitation: loop invariants for ( ) { You
More informationTechniques of Java Programming: Streams in Java
Techniques of Java Programming: Streams in Java Manuel Oriol May 8, 2006 1 Introduction Streams are a way of transferring and filtering information. Streams are directed pipes that transfer information
More informationLecture 14: Design Patterns
2. Structural Patterns 2.2. Decorator Pattern Lecture 14: Design Patterns In object-oriented programming, the decorator pattern is a design pattern that allows behaviour to be added to an existing object
More informationCS 2113 Software Engineering
CS 2113 Software Engineering Java 6: File and Network IO https://github.com/cs2113f18/template-j-6-io.git Professor Tim Wood - The George Washington University Project 2 Zombies Basic GUI interactions
More informationInstalling Java. Tradition. DP Computer Science Unit 4.3: Intro to programming 1/17/2018. Software & websites
DP Computer Science Unit 4.3: Intro to programming Installing Java Software & websites JDK (Java development kit) download: http://www.oracle.com/technetwork/java/javase/ Tradition For a full IDE (integrated
More information엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED
엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED Outline - Interfaces - An Instrument interface - Multiple Inheritance
More informationGive one example where you might wish to use a three dimensional array
CS 110: INTRODUCTION TO COMPUTER SCIENCE SAMPLE TEST 3 TIME ALLOWED: 60 MINUTES Student s Name: MAXIMUM MARK 100 NOTE: Unless otherwise stated, the questions are with reference to the Java Programming
More informationJava code(assembler) ******************************************************************* package A1;
Java code(assembler) ******************************************************************* package A1; import java.io.bufferedreader; import java.io.fileinputstream; import java.io.filewriter; import java.io.inputstreamreader;
More information1.Which four options describe the correct default values for array elements of the types indicated?
1.Which four options describe the correct default values for array elements of the types indicated? 1. int -> 0 2. String -> "null" 3. Dog -> null 4. char -> '\u0000' 5. float -> 0.0f 6. boolean -> true
More informationCSC 172 Data Structures and Algorithms. Lecture #9 Spring 2018
CSC 172 Data Structures and Algorithms Lecture #9 Spring 2018 SINGLY LINKED LIST 3.1.3 Linked lists We will consider these for Singly linked lists Doubly linked lists Basic Singly Linked List class Node
More informationCommunication.java 1
19.07.17 Communication.java 1 package framework.tracking; import java.io.ioexception; import java.net.datagrampacket; import java.net.inetaddress; import java.net.multicastsocket; import java.util.concurrent.concurrenthashmap;
More informationLists. CSC212 Lecture 8 D. Thiebaut, Fall 2014
Lists CSC212 Lecture 8 D. Thiebaut, Fall 2014 Review List = Organization of Data in a Linear Fashion, where Order is Important Set of actions that can be carried out efficiently on the data. Typical Actions
More informationCS 231 Data Structures and Algorithms Fall 2018
CS 231 Data Structures and Algorithms Fall 2018 Interface, Node Based Stack, Exception Handling, Class BufferedReader Lecture 12 October 1, 2018 Prof. Zadia Codabux 1 Agenda Node based implementation of
More informationMore Java Basics. class Vector { Object[] myarray;... //insert x in the array void insert(object x) {...} Then we can use Vector to hold any objects.
More Java Basics 1. INHERITANCE AND DYNAMIC TYPE-CASTING Java performs automatic type conversion from a sub-type to a super-type. That is, if a method requires a parameter of type A, we can call the method
More informationIntroduction to Software Engineering in Java. Exceptions, I/O, and you++
6.092 - Introduction to Software Engineering in Java Lecture 8: Exceptions, I/O, and you++ Thursday, January 31 IAP 2008 Cite as: Evan Jones, Olivier Koch, and Usman Akeju, course materials for 6.092 Introduction
More informationpublic static boolean isoutside(int min, int max, int value)
See the 2 APIs attached at the end of this worksheet. 1. Methods: Javadoc Complete the Javadoc comments for the following two methods from the API: (a) / @param @param @param @return @pre. / public static
More informationProject #1 Computer Science 2334 Fall 2008
Project #1 Computer Science 2334 Fall 2008 User Request: Create a Word Verification System. Milestones: 1. Use program arguments to specify a file name. 10 points 2. Use simple File I/O to read a file.
More informationToday. Book-keeping. File I/O. Subscribe to sipb-iap-java-students. Inner classes. Debugging tools
Today Book-keeping File I/O Subscribe to sipb-iap-java-students Inner classes http://sipb.mit.edu/iap/java/ Debugging tools Problem set 1 questions? Problem set 2 released tomorrow 1 2 So far... Reading
More informationCSE143 - Project 3A Turn-in Receipt
1 of 9 11/24/2003 4:24 PM CSE143 - Project 3A Turn-in Receipt Prins, Ryan Michael (rprins@u.washington.edu) Section AD Daniel Wyatt Turn-in logged at 16:24:36 PST, Monday, Nov 24, 2003 Your program compiled
More informationCIS 265 Exam 2 First Name Last Name
CIS 265 Exam 2 First Name Last Name MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question. 1) Which of the data types below does not allow duplicates? 1)
More informationSection Solutions 8. /* The separator used to delimit the start and end of a flight. */ private static final String FLIGHT_DELIMITER = " -> ";
CS106A Winter 2015 Handout #24S March 2, 2015 Section Solutions 8 import acm.program.; import acm.util.; import java.util.; import java.io.; public class FlightPlanner extends ConsoleProgram { / The name
More informationCPSC 211. SOLUTIONS to PRACTICE EXERCISES II
CPSC 211 SOLUTIONS to PRACTICE EXERCISES II Recursion 1. The output of cheers(3) is: Hip Hip Hurrah 2. public static void cheers(int n) { if ( n
More informationTools : The Java Compiler. The Java Interpreter. The Java Debugger
Tools : The Java Compiler javac [ options ] filename.java... -depend: Causes recompilation of class files on which the source files given as command line arguments recursively depend. -O: Optimizes code,
More informationCS 455 Midterm Exam 2 Fall 2016 [Bono] November 8, 2016
Name: USC NetID (e.g., ttrojan): CS 455 Midterm Exam 2 Fall 2016 [Bono] November 8, 2016 There are 7 problems on the exam, with 50 points total available. There are 8 pages to the exam (4 pages double-sided),
More informationAssignment 8B SOLUTIONS
CSIS 10A Assignment 8B SOLUTIONS Read: Chapter 8 Choose and complete any 10 points from the problems below, which are all included in the download file on the website. Use BlueJ to complete the assignment,
More informationBufferedReader bufferedreader = new BufferedReader(fileReader); persons.tail.obj = new Person(data[1], data[2], data[3], data[4],
package EFile; import java.util.scanner; import java.io.bufferedreader; import java.io.filereader; import java.io.ioexception; import java.io.filenotfoundexception; public class EFileClient { public static
More informationOverview. Lecture 7: Inheritance and GUIs. Inheritance. Example 9/30/2008
Overview Lecture 7: Inheritance and GUIs Written by: Daniel Dalevi Inheritance Subclasses and superclasses Java keywords Interfaces and inheritance The JComponent class Casting The cosmic superclass Object
More informationJava for Interfaces and Networks (DT3010, HT11)
Java for Interfaces and Networks (DT3010, HT11) Networking with Threads and Federico Pecora School of Science and Technology Örebro University federico.pecora@oru.se Federico Pecora Java for Interfaces
More informationProject #1 rev 2 Computer Science 2334 Fall 2013 This project is individual work. Each student must complete this assignment independently.
Project #1 rev 2 Computer Science 2334 Fall 2013 This project is individual work. Each student must complete this assignment independently. User Request: Create a simple magazine data system. Milestones:
More informationChapter 12: Inheritance
Chapter 12: Inheritance Objectives Students should Understand the concept and role of inheritance. Be able to design appropriate class inheritance hierarchies. Be able to make use of inheritance to create
More information1.00 Introduction to Computers and Engineering Problem Solving. Final Examination - May 18, 2005
1.00 Introduction to Computers and Engineering Problem Solving Final Examination - May 18, 2005 Name: E-mail Address: TA: Section: You have 3 hours to complete this exam. For coding questions, you do not
More informationArrays. COMS W1007 Introduction to Computer Science. Christopher Conway 10 June 2003
Arrays COMS W1007 Introduction to Computer Science Christopher Conway 10 June 2003 Arrays An array is a list of values. In Java, the components of an array can be of any type, basic or object. An array
More informationImplementation. Learn how to implement the List interface Understand the efficiency trade-offs between the ArrayList and LinkedList implementations
Readings List Implementations Chapter 20.2 Objectives Learn how to implement the List interface Understand the efficiency trade-offs between the ArrayList and LinkedList implementations Additional references:
More information1 If you want to store a letter grade (like a course grade) which variable type would you use? a. int b. String c. char d. boolean
Practice Final Quiz 1 If you want to store a letter grade (like a course grade) which variable type would you use? a. int b. String c. char d. boolean 2 If you wanted to divide two numbers precisely, which
More information