Sunteți pe pagina 1din 26

Check for anagrams degree of difficulty: 2 A anagrom is a word or a phrase that can be created by rearranging the letters o f another

given word or phrase. We ignore white spaces and letter case. The all letters of "Desperation" can be rearranged to the phrase "A Rope Ends It". Implement a Java program that checks to given Strings whether one is an anagram of the other. Hint: Objects s of type String can be converted to lower case with s.toLowerCase (). s.toCharArray() returns the content of the String as an char-array. Note tha t char values can be used in Java everywhere where an int value is allowed. Solution -------------------------------------------------------------------------------Overview Package Class Use Tree PREV CLASS NEXT CLASS FRAMES SUMMARY: NESTED FIELD CONSTR NO FRAMES All Classes METHOD DETAIL: FIELD CONSTR METHOD

-------------------------------------------------------------------------------de.hska.java.exercises.arrays Class Anagram java.lang.Object de.hska.java.exercises.arrays.Anagram -------------------------------------------------------------------------------public class Anagramextends java.lang.Object Anagram is responsible to check two given Strings whether one is an anagram of t he other. White spaces and letter case is ignored. Examples of anagrams are: "Desperation" -> "A Rope Ends It" "Eleven plus two" -> "Twelve plus one"

Author: pape -------------------------------------------------------------------------------Constructor Summary Anagram() Method Summary boolean isAnagram(java.lang.String phrase, java.lang.String anagram) Retruns true if the letters of phrase can be rearranged to the given S tring anagram. Methods inherited from class java.lang.Object equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait Constructor Detail Anagram public Anagram()Method Detail

isAnagram public boolean isAnagram(java.lang.String phrase, java.lang.String anagram)Retruns true if the letters of phrase can be rearranged to the given String anagram. White spaces and letter c ase are ignored. -------------------------------------------------------------------------------Overview Package Class Use Tree PREV CLASS NEXT CLASS FRAMES SUMMARY: NESTED FIELD CONSTR NO FRAMES All Classes METHOD DETAIL: FIELD CONSTR METHOD

-------------------------------------------------------------------------------Prof. Dr. Christian Pape

Find the sum of digits for a sequence of digits degree of difficulty: 3 Implement a Java function that calculates the sum of digits for a given char arr ay consisting of the digits '0' to '9'. The function should return the digit sum as a long value. Hint: you can do arithmetic with char-values like int-values in Java: the charac ter's unicode is treated as an int-value. The digits '0' to '9' have a consecuti ve binary encoding without gaps. The expression '1' == '0' + 1, for instance, is true. Solution -------------------------------------------------------------------------------Overview Package Class Use Tree PREV CLASS NEXT CLASS FRAMES SUMMARY: NESTED FIELD CONSTR NO FRAMES All Classes METHOD DETAIL: FIELD CONSTR METHOD

-------------------------------------------------------------------------------de.hska.java.exercises.arrays Class DigitSum java.lang.Object de.hska.java.exercises.arrays.DigitSum -------------------------------------------------------------------------------public class DigitSumextends java.lang.ObjectDigitSum is responisble for calcula tion the sum of digits for a given character sequence.

Author: pape -------------------------------------------------------------------------------Constructor Summary DigitSum()

Method Summary long getDigitSum(char[] number) Returns the digit sum from the given sequence of digits number ('0' to '9'). Methods inherited from class java.lang.Object equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait Constructor Detail DigitSum public DigitSum()Method Detail getDigitSum public long getDigitSum(char[] number)Returns the digit sum from the given seque nce of digits number ('0' to '9'). number must only consists of digit characters . -------------------------------------------------------------------------------Overview Package Class Use Tree PREV CLASS NEXT CLASS FRAMES SUMMARY: NESTED FIELD CONSTR NO FRAMES All Classes METHOD DETAIL: FIELD CONSTR METHOD

-------------------------------------------------------------------------------Prof. Dr. Christian Pape Find the smallest distance between two neighbouring numbers in an array degree of difficulty: 2 Implement a Java function that finds two neighbouring numbers in an array with t he smallest distance to each other. The function should return the index of the first number. In the sequence 4 8 6 1 2 9 4 the minimum distance is 1 (between 1 and 2). The f unction should return the index 3 (of number 1). Hint: Use Math.abs() to calculate the distance of two numbers. Solution -------------------------------------------------------------------------------Overview Package Class Use Tree PREV CLASS NEXT CLASS FRAMES SUMMARY: NESTED FIELD CONSTR NO FRAMES All Classes METHOD DETAIL: FIELD CONSTR METHOD

-------------------------------------------------------------------------------de.hska.java.exercises.arrays Class MinimumDistance java.lang.Object de.hska.java.exercises.arrays.MinimumDistance -------------------------------------------------------------------------------public class MinimumDistanceextends java.lang.ObjectContains a method that finds the minimum distance of two neighbouring numbers in a int array.

Author:

pape -------------------------------------------------------------------------------Constructor Summary MinimumDistance() Method Summary int getIndexOfMinimumDistance(int[] numbers) Returns the index of the first number of two neighbouring numbers with minimum distance to each others. Methods inherited from class java.lang.Object equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait Constructor Detail MinimumDistance public MinimumDistance()Method Detail getIndexOfMinimumDistance public int getIndexOfMinimumDistance(int[] numbers)Returns the index of the firs t number of two neighbouring numbers with minimum distance to each others. -------------------------------------------------------------------------------Overview Package Class Use Tree PREV CLASS NEXT CLASS FRAMES SUMMARY: NESTED FIELD CONSTR NO FRAMES All Classes METHOD DETAIL: FIELD CONSTR METHOD

-------------------------------------------------------------------------------Prof. Dr. Christian Pape Implement a simple calculator degree of difficulty: 1 Implement a simple calculator which evaluates arithmetic expressions given as a String. The expression should only consists of numbers 0 to 9, parenthesis, and the binary and unary operators + and -. White spaces are ignored. Implement a re cursive descent parser for reading in the String. The syntax is given as the following EBNF: expression = term, [ "+" "-" , term ] ; term = "(", term, ")" "0" "1" ... "9" ; The follwing strings are valid: "1", "((2))", "2 + 3", "( (4) - 5 +7)". Inspect the methods of a String and the class Character Solution -------------------------------------------------------------------------------Overview Package Class Use Tree PREV CLASS NEXT CLASS FRAMES SUMMARY: NESTED FIELD CONSTR NO FRAMES All Classes METHOD DETAIL: FIELD CONSTR METHOD

-------------------------------------------------------------------------------de.hska.java.exercises.recursion Class Calculator java.lang.Object de.hska.java.exercises.recursion.Calculator -------------------------------------------------------------------------------public class Calculatorextends java.lang.ObjectImplements a simple calculator wi th a recursive descendant parser. The synax of the expression in EBNF is: expression = term, [ "+" "-" , term ] ; term = "(", term, ")" "0" "1" ... "9" ; Author: pape -------------------------------------------------------------------------------Constructor Summary Calculator(java.lang.String expression) Creates a new Calculator with the given expression. Method Summary int evaluateExpression() Returns the value of the expression. Methods inherited from class java.lang.Object equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait Constructor Detail Calculator public Calculator(java.lang.String expression)Creates a new Calculator with the given expression. Method Detail evaluateExpression public int evaluateExpression()Returns the value of the expression. -------------------------------------------------------------------------------Overview Package Class Use Tree PREV CLASS NEXT CLASS FRAMES SUMMARY: NESTED FIELD CONSTR NO FRAMES All Classes METHOD DETAIL: FIELD CONSTR METHOD

-------------------------------------------------------------------------------Prof. Dr. Christian Pape Euclids algorithm degree of difficulty: 2 Implement Euclids algorithm recursivly. For flow control use the if-statement on ly. Euclids algorithm to calculate the greates common divisor of two positive intege r numbers a and b (gcd(a,b)) is recursivly defined as:

gcd(a,b) := a if a = b gcd(a,b) := gcd(a - b, b) if a > b gcd(a,b) := gcd(a, b - a) if b > a Solution -------------------------------------------------------------------------------Overview Package Class Use Tree PREV CLASS NEXT CLASS FRAMES SUMMARY: NESTED FIELD CONSTR NO FRAMES All Classes METHOD DETAIL: FIELD CONSTR METHOD

-------------------------------------------------------------------------------de.hska.java.exercises.recursion Class GreatestCommonDivisor java.lang.Object de.hska.java.exercises.recursion.GreatestCommonDivisor -------------------------------------------------------------------------------public class GreatestCommonDivisorextends java.lang.ObjectRecursive implementati on of Euclids algorithms.

Author: pape -------------------------------------------------------------------------------Constructor Summary GreatestCommonDivisor() Method Summary int getGcd(int a, int b) Returns the greates common divisor of a and b. Methods inherited from class java.lang.Object equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait Constructor Detail GreatestCommonDivisor public GreatestCommonDivisor()Method Detail getGcd public int getGcd(int a, int b)Returns the greates common divisor of a and b. -------------------------------------------------------------------------------Overview Package Class Use Tree PREV CLASS NEXT CLASS FRAMES SUMMARY: NESTED FIELD CONSTR NO FRAMES All Classes METHOD DETAIL: FIELD CONSTR METHOD

-------------------------------------------------------------------------------Prof. Dr. Christian Pape

Implement a backtracking algorithmus to solve Sudokus degree of difficulty: 1 Sudoku is a mathematical puzzle based on a 9 x 9 matrix. This matrix is subdivid ed into 3 x 3 submatrices. The aim of the game is to complete a partial filled m atrix with numbers from 1 to 9 such that every number occurs exactly once in eve ry row, column und 3 x 3 submatrix. With backtracking all combinations can be sy stematically found. To decide efficiently whether a new number is allowed to place in a field, you s hould think of an data structure with which for a given row r and column c the n ubmer z can be placed into the field or not. This data structure is similiar to the one used for the eight queens problem. Solution -------------------------------------------------------------------------------Overview Package Class Use Tree PREV CLASS NEXT CLASS FRAMES SUMMARY: NESTED FIELD CONSTR NO FRAMES All Classes METHOD DETAIL: FIELD CONSTR METHOD

-------------------------------------------------------------------------------de.hska.java.exercises.backtracking Class Sudoku java.lang.Object de.hska.java.exercises.backtracking.Sudoku -------------------------------------------------------------------------------public class Sudokuextends java.lang.Object Sudoku is responsible for finding a solution to a Sudoku puzzle.

Author: pape -------------------------------------------------------------------------------Field Summary static int EMPTY_FIELD Constructor Summary Sudoku(int[][] partialSudoku) Creates a new Sudoku with the given partial Sudoku. Method Summary void createSudoku(int n) Creates a new Sudoku with n random numbers (1-9). static void main(java.lang.String[] argv) void print() Prints out the Sudoku boolean solve(int counter) Uses recursive backtracking to solve this Sudoku puzzle. Methods inherited from class java.lang.Object equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail EMPTY_FIELD public static final int EMPTY_FIELDSee Also: Constant Field Values Constructor Detail Sudoku public Sudoku(int[][] partialSudoku)Creates a new Sudoku with the given partial Sudoku. Method Detail print public void print()Prints out the Sudoku -------------------------------------------------------------------------------solve public boolean solve(int counter)Uses recursive backtracking to solve this Sudok u puzzle. Parameters: counter - identifies each of the 81 fields - initial value is 0 -------------------------------------------------------------------------------createSudoku public void createSudoku(int n)Creates a new Sudoku with n random numbers (1-9).

-------------------------------------------------------------------------------main public static void main(java.lang.String[] argv) -------------------------------------------------------------------------------Overview Package Class Use Tree PREV CLASS NEXT CLASS FRAMES SUMMARY: NESTED FIELD CONSTR NO FRAMES All Classes METHOD DETAIL: FIELD CONSTR METHOD

-------------------------------------------------------------------------------Prof. Dr. Christian Pape

Generate new random Sudokus degree of difficulty: 2 Before solving this Java programming exercises you should have finished the Java backtracking algorithm to solve Sudokus. You can create new Sudoku puzzles by inserting n random numbers in the range fro m 1 - 9 and checking for each new number, whether the rules of the game still ap ply or not. After that, you can call the backtracking algorithm to solve the new Sudoku: if a solution have been found, your Java programm has created a new Sud oku puzzle; if not, you start the whole process again. This method is able to create new Sudoku puzzles with a certain probability 0 < p < 1. It is unlikly, but possible, that your algorithm never terminates. But wh en it terminates, the result is always correct. Such algorithms based on randomi ze creation of problem solutions are called .

Add a Java method that creates new Sudoku puzzles with n numbers to the existing backtracking algorithm. Solution -------------------------------------------------------------------------------Overview Package Class Use Tree PREV CLASS NEXT CLASS FRAMES SUMMARY: NESTED FIELD CONSTR NO FRAMES All Classes METHOD DETAIL: FIELD CONSTR METHOD

-------------------------------------------------------------------------------de.hska.java.exercises.backtracking Class Sudoku java.lang.Object de.hska.java.exercises.backtracking.Sudoku -------------------------------------------------------------------------------public class Sudokuextends java.lang.Object Sudoku is responsible for finding a solution to a Sudoku puzzle.

Author: pape -------------------------------------------------------------------------------Field Summary static int EMPTY_FIELD Constructor Summary Sudoku(int[][] partialSudoku) Creates a new Sudoku with the given partial Sudoku. Method Summary void createSudoku(int n) Creates a new Sudoku with n random numbers (1-9). static void main(java.lang.String[] argv) void print() Prints out the Sudoku boolean solve(int counter) Uses recursive backtracking to solve this Sudoku puzzle. Methods inherited from class java.lang.Object equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait Field Detail EMPTY_FIELD public static final int EMPTY_FIELDSee Also: Constant Field Values Constructor Detail Sudoku public Sudoku(int[][] partialSudoku)Creates a new Sudoku with the given partial Sudoku. Method Detail print

public void print()Prints out the Sudoku -------------------------------------------------------------------------------solve public boolean solve(int counter)Uses recursive backtracking to solve this Sudok u puzzle. Parameters: counter - identifies each of the 81 fields - initial value is 0 -------------------------------------------------------------------------------createSudoku public void createSudoku(int n)Creates a new Sudoku with n random numbers (1-9).

-------------------------------------------------------------------------------main public static void main(java.lang.String[] argv) -------------------------------------------------------------------------------Overview Package Class Use Tree PREV CLASS NEXT CLASS FRAMES SUMMARY: NESTED FIELD CONSTR NO FRAMES All Classes METHOD DETAIL: FIELD CONSTR METHOD

-------------------------------------------------------------------------------Prof. Dr. Christian Pape

Solve English peg solitaire with backtracking degree of difficulty: 1 English peg solitare is a puzzle where the board has the form of a cross. It con sists of 32 fields. 31 of these fields contain a peg. The single field in the mi ddle of the board is empty. (We mark a peg with X and an empty field with O in t he following examples) The rules of this game a simple: you can take a peg and jump over another neighbouring peg the peg you jumped over is removed from the board you solved the puzzle if at the end only on peg exists and is located in the mid dle of the board At the start there are only a few possible moves, but the choices are increasing during the game. The following tables give the initial position of the pegs and subsequent moves. X X X X X X X X X X X X X X X X X X X O X X X X X X X

X X X X --> X X X X X X O O X X X X X X X --> X X X X X X O X X X O O X X X --> X X X X X X O X X X X O X X X more O O O O O O O O O O O O O O O

X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X O O X X X X moves ... --> O O O O O X O O O O O O O O O

O O O

Implement a recusive backtracking algorithm in Java, that finds a solution to th is puzzle. The solution can be stored as a sequence of boards: one for each move . The board should be implemented as a Java class with an internal 7x7 matrix. I n the backtracking algorithm you must compute all possible jumps for a given sit uation. With a 2.2 Ghz Athlon 64 I found a solution within 200 ms. Without heuristics or optimizations to the code. A solution can be found with brute-force. Solution -------------------------------------------------------------------------------Overview Package Class Use Tree PREV CLASS NEXT CLASS FRAMES SUMMARY: NESTED FIELD CONSTR NO FRAMES All Classes METHOD DETAIL: FIELD CONSTR METHOD

-------------------------------------------------------------------------------de.hska.java.exercises.backtracking Class Solitaer java.lang.Object de.hska.java.exercises.backtracking.Solitaer -------------------------------------------------------------------------------public class Solitaerextends java.lang.ObjectSolves English peg solitare with 32

field and 31 pegs with the help of a recursive backtring algorithm. I have not checked every move of the solution: only the first few and last few moves. I hop e all other are valid moves as well.

Author: pape -------------------------------------------------------------------------------Constructor Summary Solitaer() creates a new solitare instance with empty solution and initial start position of all pegs Method Summary boolean findSolution(int move) Backtracking algorithm to solve the solitare puzzle static void main(java.lang.String[] args) Starts the backtracking algorithm and prints out the solution as the s equence of all resulting intermediate board situation Methods inherited from class java.lang.Object equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait Constructor Detail Solitaer public Solitaer()creates a new solitare instance with empty solution and initial start position of all pegs Method Detail main public static void main(java.lang.String[] args)Starts the backtracking algorith m and prints out the solution as the sequence of all resulting intermediate boar d situation -------------------------------------------------------------------------------findSolution public boolean findSolution(int move)Backtracking algorithm to solve the solitar e puzzle Parameters: move - current number of move, first move must be 1 -------------------------------------------------------------------------------Overview Package Class Use Tree PREV CLASS NEXT CLASS FRAMES SUMMARY: NESTED FIELD CONSTR NO FRAMES All Classes METHOD DETAIL: FIELD CONSTR METHOD

-------------------------------------------------------------------------------Prof. Dr. Christian Pape Find zeros of continueous functions degree of difficulty: 2

If zeros exists for a continueous function f: R -> R then at least to real numbe rs a and b exists such that f(a)f(b) < 0 holds: Exact one of both values is nega tiv the other positive. Because f is continueous, there must be a zero between a und b. Implement a binary partition algorithm, that finds the zero of a continueous fun ction f in the given intervall [a, b] with a certain precision. f can be a fixed coded Java function. Test your programm with f(x) = 2x3 - 5x2 + 7x + 2, a = -1, b = 1 ( f(1) = 2 - 5 + 7 = 6, f(-1) = -2 - 5 - 7 = -14). Solution. In my solution the function is given as an abstract data type (interfa ce) to be more flexible in the choice of f. Implement Newton's method -------------------------------------------------------------------------------Overview Package Class Use Tree PREV CLASS NEXT CLASS FRAMES SUMMARY: NESTED FIELD CONSTR NO FRAMES All Classes METHOD DETAIL: FIELD CONSTR METHOD

-------------------------------------------------------------------------------de.hska.java.exercises.searching Class FindZero java.lang.Object de.hska.java.exercises.searching.FindZero -------------------------------------------------------------------------------public class FindZeroextends java.lang.ObjectSearches for a zero of a continueou s function f : R -> R with a binary partition algorithm.

Author: pape -------------------------------------------------------------------------------Constructor Summary FindZero(Function function, double precision) Creates a new instance of FindZero to find a zero for the given contin ueous function f and desired precision of the zero. Method Summary double searchZero(double left, double right) Searches for a zero in the given intervall [left, right]. Methods inherited from class java.lang.Object equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait Constructor Detail FindZero public FindZero(Function function, double precision)Creates a new instance of FindZero to find a ze ro for the given continueous function f and desired precision of the zero. Parameters: function - a continueous function

Method Detail searchZero public double searchZero(double left, double right)Searches for a zero in the given intervall [left, right]. If f(left)f(right) < 0 holds a zero is found and returned. -------------------------------------------------------------------------------Overview Package Class Use Tree PREV CLASS NEXT CLASS FRAMES SUMMARY: NESTED FIELD CONSTR NO FRAMES All Classes METHOD DETAIL: FIELD CONSTR METHOD

-------------------------------------------------------------------------------Prof. Dr. Christian Pape Implement Newton's method Schwierigkeit 2 Implement a method that calculates a zero of a continous, derivable function f w ith Newton's method. Newton's method starts with an arbitrary value x0 and calculates the sequence xn +1 := xn - f(xn)/f'(xn). This sequence converges (in most cases) to a zero of f. If you alreay solved the exercise to implement polynomials, then you can use you r implementation to test Newton's method. If not, then define and implement a cl ass (or interface) with two methods: one for calculating f(x) and one for the fi rst derivation of f with value x. Solution -------------------------------------------------------------------------------Overview Package Class Use Tree PREV CLASS NEXT CLASS FRAMES SUMMARY: NESTED FIELD CONSTR NO FRAMES All Classes METHOD DETAIL: FIELD CONSTR METHOD

-------------------------------------------------------------------------------de.hska.java.exercises.searching Class NewtonsMethod java.lang.Object de.hska.java.exercises.searching.NewtonsMethod -------------------------------------------------------------------------------public class NewtonsMethodextends java.lang.ObjectImplements Newton's method to find a zero of a given polynomial.

Author: pape -------------------------------------------------------------------------------Constructor Summary NewtonsMethod(Polynomial polynomial)

Creates a new NewtonsMethod to find a zero for the given polynomial. Method Summary double getZero(double x, double epsilon) Searches and returns an approximation of a zero with Newton's method. Methods inherited from class java.lang.Object equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait Constructor Detail NewtonsMethod public NewtonsMethod(Polynomial polynomial)Creates a new NewtonsMethod to find a zero for the given polynomial. Method Detail getZero public double getZero(double x, double epsilon)Searches and returns an approximation of a zero with Newton's method. epsilon specifies the accuracy of the approximation. This method may not terminate for every x and polynomial. -------------------------------------------------------------------------------Overview Package Class Use Tree PREV CLASS NEXT CLASS FRAMES SUMMARY: NESTED FIELD CONSTR NO FRAMES All Classes METHOD DETAIL: FIELD CONSTR METHOD

-------------------------------------------------------------------------------Prof. Dr. Christian Pape Implement bottom-up mergesort degree of difficulty: 2 (only if you already have implemented the merge step) Bottom-up mergesort is a non recursiv mergesort variant. In the first pass all 1-1-pairs of consecutive elements are merged together. In the next pass all 2-2-pairs of consecutive elements are merged, and so on, until in the last pass all elements are merged into one sorted sequence: 2 2 2 1 0 5 5 2 2 1 9 2 5 2 2 2 9 9 3 2 1 1 1 5 2 5 5 3 5 3 3 3 5 7 5 7 7 7 9 5 9 0 0 0 7 0 9 2 2 9 2 2 9 9 9 after first pass after second pass third pass last pass

Solution -------------------------------------------------------------------------------Overview Package Class Use Tree PREV CLASS NEXT CLASS FRAMES SUMMARY: NESTED FIELD CONSTR NO FRAMES All Classes METHOD DETAIL: FIELD CONSTR METHOD

-------------------------------------------------------------------------------de.hska.java.exercises.sorting Class BottomUpMergesort java.lang.Object

de.hska.java.exercises.sorting.BottomUpMergesort All Implemented Interfaces: Sorting -------------------------------------------------------------------------------public class BottomUpMergesortextends java.lang.Objectimplements SortingBottomUp Mergesort is a non recursive implementation of mergesort. In a first pass all 11-pairs of numbers are merged together, then all 2-2-pairs, and so on, until the array is sorted. 7 4 6 3 1 2 8 4 7 3 6 1 2 5 4 7 3 6 1 2 5 3 4 6 7 1 2 5 3 4 6 7 1 2 5 1 2 3 4 5 6 7 5

8 8 8 8 8

Author: pape -------------------------------------------------------------------------------Constructor Summary BottomUpMergesort() Method Summary void sort(int[] a) Sorts the elements in a in ascending order. Methods inherited from class java.lang.Object equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait Constructor Detail BottomUpMergesort public BottomUpMergesort()Method Detail sort public void sort(int[] a)Sorts the elements in a in ascending order. Specified by: sort in interface Sorting -------------------------------------------------------------------------------Overview Package Class Use Tree PREV CLASS NEXT CLASS FRAMES SUMMARY: NESTED FIELD CONSTR NO FRAMES All Classes METHOD DETAIL: FIELD CONSTR METHOD

-------------------------------------------------------------------------------Prof. Dr. Christian Pape Implement Shell sort

degree of difficulty: 1 Shell sort is a refinement of insertion sort. It was published 1959 by D. L. She ll. Shell sort applies insertion sort multiple times with decreasing gap size k. In the last pass k always is one. For instance, in the first pass k = 4: insert ion sort is applied to every fourth element of the array. There are four such su bsequence (starting at position 0, 1, 2, and 3). For a given k, this pass of ins ertion sort is called k-sorting. The next pass might by a 2-sorting and finaly a 1-sorting which is an ordinary insertion sort. Lets have a look at an example with eight numbers. We apply a 4-, 2-, and finall y a 1-sorting on the array. The subsequences are emphasized by colors. 5 1 1 1 1 8 8 6 6 6 3 3 3 2 2 7 7 7 7 4 1 5 5 5 5 6 6 8 8 8 2 2 2 3 3 4 4 4 4 7 Unsorted array with gaps of four Insertion sort on the yellow subsequence Sorting cyan" subsequnce Sorting all "white" elements Sorting all "orangen" elements

We always had the worst case of insertion sort: the elements of the colored sequ ences have been ordered in descending order. For each subsequnce four comparisio n have been necessary to sort them. However, smaller numbers have been exchanged by larger numbers via the gap size 4. In the result, smaller numbers now tend t o be in the first half of the array, larger number in the second half: a step to the best case of insertion sort. We now apply a 2-sorting. 1 6 2 4 5 8 3 7 Array after the 4-sorting step 1 6 2 4 3 8 5 7 1 4 2 6 3 7 5 8 Note that due to the first 4-sorting step only few comparision and exchanges hav e been made by the 2-sorting step. The final step is a normal insertion sort (1sorting): 1 1 1 1 1 1 1 1 4 4 2 2 2 2 2 2 2 2 4 4 3 3 3 3 6 6 6 6 4 4 4 4 3 3 3 3 6 6 5 5 7 7 7 7 7 7 6 6 5 5 5 5 5 5 7 7 8 Start 8 8 8 8 8 8 8

In the last pass only 9 comparisions have been necessary to sort the array. In t he worst case insertion sort needs 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 = 36 comparisio ns. Shell sort systematically rearranges the order in the array such that for su bsequent k-sorting steps the worst case becomes less likely. The overall running time depends of the choice of the k-sorting steps. For the sequence k = 2log2n, ..., 63, 31, 15, 7, 3, 1 shell sort performes with O(n1,5) comparisions in the worst case. Currently the best known sequence leads to O(n(log2n)2) running time . Implementt Shell sort for the above sequence. Note that the last sorting always is insertion sort: even if your program has bugs in k-sorting steps, the final c orrect insertion sort leads to a sorted array, but the performance may still be O(n2) or worse. Implement the k-sorting step as a public methode (due to it woul d be private) and test it thorougly. Solution

-------------------------------------------------------------------------------Overview Package Class Use Tree PREV CLASS NEXT CLASS FRAMES SUMMARY: NESTED FIELD CONSTR NO FRAMES All Classes METHOD DETAIL: FIELD CONSTR METHOD

-------------------------------------------------------------------------------de.hska.java.exercises.sorting Class ShellSort java.lang.Object de.hska.java.exercises.sorting.ShellSort All Implemented Interfaces: Sorting -------------------------------------------------------------------------------public class ShellSortextends java.lang.Objectimplements SortingShell sort with the gap sequence 1, 3, 7, 15, ..., 2log2(n) (in reverse order).

Author: pape -------------------------------------------------------------------------------Constructor Summary ShellSort() Method Summary void kSort(int[] a, int k) Insertion sort with gaps (k-sorting). void sort(int[] a) Sorts the elements of a in ascending order void sort(int[] a, int k) Sorts the elements with Shell sort and the gap sequence 1, 3, 7, ..., 2log2(n) (in reverse order). Methods inherited from class java.lang.Object equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait Constructor Detail ShellSort public ShellSort()Method Detail sort public void sort(int[] a)Sorts the elements of a in ascending order Specified by: sort in interface Sorting -------------------------------------------------------------------------------sort public void sort(int[] a, int k)Sorts the elements with Shell sort and the gap sequence 1 , 3, 7, ..., 2log2(n) (in reverse order). This methode is public for testing onl y. --------------------------------------------------------------------------------

kSort public void kSort(int[] a, int k)Insertion sort with gaps (k-sorting). In case of k = 1 t his algorithms performs an ordinary insertion sort. -------------------------------------------------------------------------------Overview Package Class Use Tree PREV CLASS NEXT CLASS FRAMES SUMMARY: NESTED FIELD CONSTR NO FRAMES All Classes METHOD DETAIL: FIELD CONSTR METHOD

-------------------------------------------------------------------------------Prof. Dr. Christian Pape Natural Mergesort degree of difficulty: 1 Implement Natural Mergesort in Java Natural mergesort is an improved variant of bottom-up merge sort. Instead of mer ging first 1-1-pairs, the 2-2-pairs and so on, natural mergesort merges two alre ady sorted paired subsequences. Lets consider 7 4 6 3 1 2 8 5 as an example. This sequence already contains sort ed subsequences. We indicate these with : 7 4 6 3 1 2 8 5 . Natural me rgesort has to find these subsequence and all pairs of these sequence are merged . Then again pairs of sorted subsequences are merged together until the whole ar ray is sorted. 7 4 6 3 1 2 8 5 4 6 7 3 1 2 8 5 4 6 7 1 2 3 8 5 4 6 7 1 2 3 5 8 <-- after first pass 4 6 7 1 2 3 5 8 1 2 3 4 6 7 5 8 <-- after second pass 1 2 3 4 5 6 7 8 <-- after third pass

Give the running time in the worst and best case? Solution -------------------------------------------------------------------------------Overview Package Class Use Tree PREV CLASS NEXT CLASS FRAMES SUMMARY: NESTED FIELD CONSTR NO FRAMES All Classes METHOD DETAIL: FIELD CONSTR METHOD

-------------------------------------------------------------------------------de.hska.java.exercises.sorting Class NaturalMergeSort java.lang.Object de.hska.java.exercises.sorting.NaturalMergeSort All Implemented Interfaces: Sorting

-------------------------------------------------------------------------------public class NaturalMergeSortextends java.lang.Objectimplements SortingNatural m ergesort is a improved version of bottom-up mergesort. It finds and merges pairs of subsequence that are already ordered. In the sequence 7 4 6 3 1 2 8 5 first all pairs of sorted subsequences are merged: 7 with 4 6 , 3 with 1 2 8, an d 5 is not merged. We use for seperating the sorted subsequences: 7 4 6 3 1 2 8 5 4 6 7 3 1 2 8 5 4 6 7 1 2 3 8 5 4 6 7 1 2 3 5 8 4 6 7 1 2 3 5 8 1 2 3 4 6 7 5 8 1 2 3 4 5 6 7 8 The best case for natural merge sort is a sorted array, the running time is O(n ). The worst case still is O(n log2n).

Author: pape -------------------------------------------------------------------------------Constructor Summary NaturalMergeSort() Method Summary void sort(int[] a) Sorts the elements of a in ascending order. Methods inherited from class java.lang.Object equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait Constructor Detail NaturalMergeSort public NaturalMergeSort()Method Detail sort public void sort(int[] a)Sorts the elements of a in ascending order. Specified by: sort in interface Sorting -------------------------------------------------------------------------------Overview Package Class Use Tree PREV CLASS NEXT CLASS FRAMES SUMMARY: NESTED FIELD CONSTR NO FRAMES All Classes METHOD DETAIL: FIELD CONSTR METHOD

-------------------------------------------------------------------------------Prof. Dr. Christian Pape

Design and implement a queue degree of difficulty: 1 A queue is an abstract data type for adding and removing elements. The first ele ment added to a queue ist the first element that is removed (first-in-first-out, FIFO). Queues can be used, for instance, to manage processes of an operating sy stem: the first process added to the waiting queue is reactivated prior to all o ther processes (with the same priority). Design an interface Queue, with methods to add and remove elements (integers). F urthermore, a methode to check whether the queue is empty or not should exist. Implement the queue with an array. If the array becomes to small to hold all add ed elements, create a new larger (double the size of instance) array and copy al l elements of the small array to the new one. Thoroughly test your implementation with small and large queues. Solution -------------------------------------------------------------------------------Overview Package Class Use Tree PREV CLASS NEXT CLASS FRAMES SUMMARY: NESTED FIELD CONSTR NO FRAMES All Classes METHOD DETAIL: FIELD CONSTR METHOD

-------------------------------------------------------------------------------de.hska.java.exercises.interfaces Class ArrayQueue java.lang.Object de.hska.java.exercises.interfaces.ArrayQueue All Implemented Interfaces: Queue -------------------------------------------------------------------------------public class ArrayQueueextends java.lang.Objectimplements QueueImplements a Queu e with an array. If the number of elements added to this queue exceeds the capac ity of the array, then a new array of double size is created and used for storin g all elements.

Author: pape -------------------------------------------------------------------------------Constructor Summary ArrayQueue() creates a new queue with the initial capacity of 100 elements ArrayQueue(int capacity) creates a new queue with the inital capacity Method Summary void add(int element) Adds the given value to this queue. boolean isEmpty()

Returns true if this queue contains one value at least. int remove() Removes and returns the value of the element that has be added to this queue at first. Methods inherited from class java.lang.Object equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait Constructor Detail ArrayQueue public ArrayQueue(int capacity)creates a new queue with the inital capacity -------------------------------------------------------------------------------ArrayQueue public ArrayQueue()creates a new queue with the initial capacity of 100 elements Method Detail add public void add(int element)Description copied from interface: Queue Adds the given value to this queue. Specified by: add in interface Queue -------------------------------------------------------------------------------isEmpty public boolean isEmpty()Description copied from interface: Queue Returns true if this queue contains one value at least. Specified by: isEmpty in interface Queue -------------------------------------------------------------------------------remove public int remove()Description copied from interface: Queue Removes and returns the value of the element that has be added to this queue at first. If the queue was empty some arbitrary value is returned. Specified by: remove in interface Queue -------------------------------------------------------------------------------Overview Package Class Use Tree PREV CLASS NEXT CLASS FRAMES SUMMARY: NESTED FIELD CONSTR NO FRAMES All Classes METHOD DETAIL: FIELD CONSTR METHOD

-------------------------------------------------------------------------------Prof. Dr. Christian Pape Convert hexadecimal numbers to their decimal representation degree of difficulty: 2 The goal of this exercise is, to measure and compare the performance of if-lese, switch and a map of values. The following abstract data type HexadecimalDigit that encapsulates one hexadeci

mal digit is given: public void setDigit(char digit): set the digit to a new digit from the value ra nge '0'-'9', 'a'-'f', or 'A'-'F' public int getDecimalValue(): returns the decimal value of the digit: 0 to 15. T he digits are not case sensitive. If the digit is not in the correct range, -1 i s returned. Implement three different variants of this interface: The method getDecimalValue () must be implemented efficiently with if-else, with a switch statement, and an array that maps a hexadecimal digit directly to its decimal value. Recall tha t char-values can be used as indices. For the performance measurement the implementation have to recalculate the decim al value for each call. The array should be declared and initialized static in t he implementation class. Its size is 65536 (maximum number of unicode characters in Java). Implement all three variants efficiently without sacrifycing readabil ity. Implement a Java class to measure the average running time of the getDecimalValu e() method for random digits. Use System.nanoTime() for this. Make sure that obj ect creation and initialization is not part of the time measuring. Solution -------------------------------------------------------------------------------Overview Package Class Use Tree PREV CLASS NEXT CLASS FRAMES SUMMARY: NESTED FIELD CONSTR NO FRAMES All Classes METHOD DETAIL: FIELD CONSTR METHOD

-------------------------------------------------------------------------------de.hska.java.exercises.misc Class HexadecimalDigitPerformanceMeasure java.lang.Object de.hska.java.exercises.misc.HexadecimalDigitPerformanceMeasure -------------------------------------------------------------------------------public class HexadecimalDigitPerformanceMeasureextends java.lang.ObjectContains a main-Methode to measure the average execution time in nano seconds of calls to getDecimalValue(). My average measures with JDK 1.6, no optimization during compiling on a Athlon 6 4 3500+: switch: 11.996048504545454 if: 17.546552072727273 array: 14.882158081818181

Author: pape --------------------------------------------------------------------------------

Constructor Summary HexadecimalDigitPerformanceMeasure() Method Summary static void main(java.lang.String[] args) performance measure Methods inherited from class java.lang.Object equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait Constructor Detail HexadecimalDigitPerformanceMeasure public HexadecimalDigitPerformanceMeasure()Method Detail main public static void main(java.lang.String[] args)performance measure -------------------------------------------------------------------------------Overview Package Class Use Tree PREV CLASS NEXT CLASS FRAMES SUMMARY: NESTED FIELD CONSTR NO FRAMES All Classes METHOD DETAIL: FIELD CONSTR METHOD

-------------------------------------------------------------------------------Prof. Dr. Christian Pape Implement the periodic table of the chemical elements by loading the elements va lues from a text file degree of difficulty: 2 Before starting this exercises, please design and implement chemical elements fi rst. The chemical elements are arranged as a two dimensional matrix in the periodic s ystem of chemical elements: The horizontal rows (periods 1 to 7) are alle chemic al elements with identical numbers of atomic orbits in the electron sheath. The vertical columns classifies chemical elements into groups (1 to 18) with identic al chemical properties. Design and implement a Java-class PeriodicTable with a method, that returns the chemical element for a given period and group. In case of lanthanoids or actinoi ds, only the first chemical element of this group must be returned. In reality the periodic system exists only once. Therefore, only one object of t his class may exist. Classes for which only one object can be constructed are si ngletons. Make every constructor of your class private. Implement a static metho d that returns the single instance of the class. The data of the periodic system have to be read from this text file. It has to b e copied to the root folder of your Java project. The data in this file have bee n taken from the english Wikipedia. The text file is ASCII encoded (and therefor e UTF-8, too). Use FileReader and BufferedReader to read in the text line by line. The data in each line is seperated by a comma (CSV, comma seperated values). Use the String method split(). Use try-catch-finally for IOExceptions and make sure that in any case the file is closed.

Solution -------------------------------------------------------------------------------Overview Package Class Use Tree PREV CLASS NEXT CLASS FRAMES SUMMARY: NESTED FIELD CONSTR NO FRAMES All Classes METHOD DETAIL: FIELD CONSTR METHOD

-------------------------------------------------------------------------------de.hska.java.exercises.misc Class PeriodicTable java.lang.Object de.hska.java.exercises.misc.PeriodicTable -------------------------------------------------------------------------------public class PeriodicTableextends java.lang.ObjectThe periodic system for chemic al elements. It is a singleton. Use getPeriodicTable() to get the single instanc e of this class. The data of the chemical elements is taken from a text file.

Author: pape -------------------------------------------------------------------------------Method Summary ChemicalElement getChemicalElement(int period, int group) Returns the chemical element for the given period (1 to 7) and group ( 1 to 18). static PeriodicTable getPeriodicTable() Retruns the single instance of the periodic table. Methods inherited from class java.lang.Object equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait Method Detail getPeriodicTable public static PeriodicTable getPeriodicTable()Retruns the single instance of the periodic table. -------------------------------------------------------------------------------getChemicalElement public ChemicalElement getChemicalElement(int period, int group)Returns the chemical element for the given period (1 to 7) and group (1 to 18). If no such element exists, t hen null is returend. -------------------------------------------------------------------------------Overview Package Class Use Tree PREV CLASS NEXT CLASS FRAMES SUMMARY: NESTED FIELD CONSTR NO FRAMES All Classes METHOD DETAIL: FIELD CONSTR METHOD

--------------------------------------------------------------------------------

Prof. Dr. Christian Pape

S-ar putea să vă placă și