Lab 5: Spinning inside of this one

Lab 5: Spinning inside of this one

Â

Â

Â

JUnit: OutputStreamSplitterTest.java TranslateWriterTest.java

Â

This fifth lab continues on the theme of byte and text I/O, with two classes to write.

Â

First, so far all the decorators that we have seen have had exactly one underlying object given to them as a constructor parameter, but this is not a law of either nature or man. A decorator can be designed to store an entire list or array of underlying objects to which is passes the method calls. We can use this simple idea to make our streams branch to several directions instead of being just linear pipelines between two endpoints. The same stream of data could then be simultaneously written into a file, into a string, and onto the console, as a generalization of the old tee utility of Unix.

Â

Create a class OutputStreamSplitter that extends OutputStream, and that contains a private field private List streams. This class should have the method

Â

public OutputStreamSplitter addStream(OutputStream os)

Â

that adds the given OutputStream parameter to this list, returning the object this as result. (Returning this in methods that would otherwise return void is a handy general trick that allows method calls to be chained.) Then, override the five methods of the OutputStream superclass so that each subclass version simply loops through streams and performs the same call for each stream stored in this list.

Â

Second, we write a decorator for Writer that sort of simulates the behaviour of the tr utility of Unix command line. Your class TranslateWriter should extend Writer and contain the underlying Writer field, initialized from the constructor parameter the same way as decorators always do. Then, this class should contain a field Map that stores a map of translation rules from characters to strings. This map is initially empty (choose a suitable concrete Map implementation for yourself), and the class should have a method public void addRule(char c, String s) to add the given translation rule from c to s to it.

Â

Override only the methods close, flush and write(char[] a, int off, int len) since the remaining methods of Writer will always internally call these, so you don’t need to override any other methods (unless you feel like doing it for some reason). This write method should loop through the characters in the given subarray from position off to off + len – 1. If there is a translation rule for that character stored in the map, write the corresponding string of the rule. Otherwise just write that same character as is.

Â

Just like the original tr utility of Unix, this method could, for example, be used to convert between the different newline characters of PC, Mac and Unix.

Lab 6: Attention to the irrelevant

Â

Â

Â

This sixth lab is intended to teach you the basics of how to create and use concurrent execution threads, and how to synchronize their behaviour using semaphores.

Â

First, to start out simple, write a class LearningThreads that contains two fields: Semaphore maySleep with the initial value 1, and boolean running, initially true. Inside this class, write an inner class SleepyHead that implements Runnable and, just like the inner class SimpleWaiter of the ConcurrencyDemo.java class example, contains two private fields int id and int n initialized in the constructor.

Â

Write the method public void run inside your SleepyHead inner class to contain a loop that runs n rounds. The body of this loop should first acquire a permit from the semaphore maySleep. Having acquired this permit, the method outputs “Thread id has acquired a permit to sleep” and goes to sleep for two seconds. After waking up from its slumber, the method outputs “Thread id has woken up”, releases the permit back to the semaphore, and goes to the next round of the loop Once loop terminates, the method should output “Thread id has completed its execution” and return.

Â

In the constructor of LearningThreads, launch five threads using five SleepyHead objects numbered from 1 to 5 with the parameter n set to 5, followed by the message “Constructor of LearningThreads is completed.” Remember to override the method public void finalize of the class LearningThreads so that it assigns running to be false, which then allows you to interactively terminate your threads in BlueJ by calling this method.

Â

Try to predict how this code will behave before creating a LearningThreads object to see the result yourself. Also, does it make any difference if the semaphore is set to fair ? What happens if the initial value of semaphore maySleep is set to two instead of one?

Â

Second, we will use concurrency to create a real-time animation of a particle swarm. Create a class Particle that has two double fields x and y, a constructor that initializes these fields to random values between 0 and 500, and the accessor methods getX and getY that return these values. This class should also have a static field Random rng shared by all particles. The class Particle should have an instance method void move() that adds a small random value received from the call rng.nextGaussian(). A separate such random value should be added to each field x and y, so that the particle can move to any direction.

Â

(Technically, adding to x and y independently of each other biases the random movement towards the directions of the main axes: a correct way to move to a random direction would be to choose a random angle from 0 to Math.PI, and then use some trig to calculate the unbiased direction vector. But we shall leave this as an extra exercise for the reader, and is not required in this lab.)

Â

Next, create a class ParticleField that extends JPanel. This class should prefer to be 500 * 500 pixels in size. Its constructor should first fill the field ArrayList particles with a thousand new Particle objects. The paintComponent method of ParticleField should loop through the particles list and draw each individual particle as a 3*3 rectangle. Write a main method for this class to open one instance of ParticleField inside a JFrame, to see your particles sitting still.

Â

Third, create a subclass ParticleFieldWithTimer that extends ParticleField. The constructor of this class should start a Swing Timer that ticks 25 times a second. At each tick, the action listener associated with this timer should first call the move method of each particle, and after this loop, call repaint to redraw the entire component. Make sure that your timer stops when the user closes the surrounding frame that contains your particle fields: use the BouncingBalls.java example as a model of how to write the main method to ensure this, and have the method output a message “Timer terminated” on the console to verify this. Try out your class and watch your swarm of particles wiggle around in their random motion.

Â

Finally, write another Swing component ParticleFieldWithThread that also extends ParticleField. This class should behave exactly like the previous class ParticleFieldWithTimer, but internally use one explicit Thread launched in the constructor. The method run of this background thread should consist of a while(running) loop whose body first sleeps for 40 milliseconds, then calls the move method of each Particle stored in the particles list, and then repaints the component. As in the previous question, make sure that your thread will terminate when the user closes the surrounding frame, with the message “Thread terminated” printed on the console.

Lab 7: The building blocks of modern human age

Â

Â

Â

JUnit: IntegerProblemsTest.java

Â

In this lab, you get to practice the bitwise arithmetic operations done with integers by implementing three methods into a new class IntegerProblems. The first of these practice methods is an old final exam question of mine, while the other two are utility methods already available in the class Integer. However, so that this lab wouldn’t be completely trivial, of course you are not allowed to call any methods of Integer from your methods, but you have to write each method from scratch by doing all necessary bitwise arithmetic explicitly. You should only use raw integer arithmetic to solve these problems: converting to String or some other representation and performing to operation there is not allowed.

Â

First, write a method public int swapMiddleBytes(int a) that computes and returns an int constructed by swapping the contents of the middle two bytes of its parameter a. For example, when called with an int whose value in hexadecimal is the famous hex literal 0xDEADBEEF (for example, see the Wikipedia page Hexspeak) this method would return an int whose value in hexadecimal is 0xDEBEADEF.

Â

Second, write a method public int bitCount(int a) that counts how many bits are on in the parameter a, and returns this count. This method should thus behave exactly like the utility method bitCount in Integer.

Â

Third, write a method public int rotateLeft(int a, int k) that computes and returns an int constructed by rotating the bits of the parameter a total of k steps to the left, so that the bits that “fall off” the left edge “come back in” from the right edge.  This method should thus behave exactly like the utility method rotateLeft in Integer, except that for simplicity, here you are allowed to assume that k cannot be negative. However, k could potentially be as large as two billion, and your method has to work efficiently even in such extreme cases. (Use the integer remainder operator % to speed things up.)

Lab 8: The machine of a thousand faces

JUnit: StreamExercisesTest.java

Â

In this last lab, you get to practice Java 8 computation streams and the use of lambda expressions to quickly define anonymous function objects. To force you to really learn this stuff, in this lab you are forbidden to use any conditional statements (either if or switch) or loops or recursion, but all computation logic must be implemented using only computation streams and their operations! (Using the boolean connectives && and || is acceptable, since of course decisions still have to be made somehow, but the truly hardcore functional programming enthusiasts can challenge themselves by not using even those!) Write all of the following methods in a single class called StreamExercises.

Â

First, just to practice the fundamentals and basic operations of computational streams, write a method int sumOfSquares(Collection c, int thres) that computes and returns the sum of squares of those elements in the parameter collection c whose absolute value is greater than the given threshold value thres.

Â

Second, to practice writing your own stateful predicates and functions, define a private inner class Increasing that implements java.util.function.DoublePredicate. (Stateful functions cannot be written as lambda expressions, for the simple reason that anonymous classes defined using lambdas cannot have fields that are needed to represent and store the internal state of the function!) Override the method public boolean test(double x) in this class so that if this is the first time that this method is called, or if the parameter x is greater than the argument that was passed to this method the previous time that this method was called, the method returns true, otherwise it returns false.

Â

Having defined this custom predicate class, write a method int countAscensions(Random rng, int len) that creates a DoubleStream from this random number generator. Write a stream that takes the first len elements of this stream, and then uses your Increasing class to filter those that are greater than their previous element in the stream. The consumer of that stream should count how many elements reach the end of that stream, and return that count as the result of this method.

Â

Third, it’s time to do some text manipulation, and check out the “Java New I/O” libraries with their improved handling of files and paths with the important utility classes Files and Paths. Write a method int countLines(Path path, int thres) throws IOException that first uses the static utility method Files.lines to convert the given path into an instance of Stream that produces the lines of this file one line at the time. You should then filter these lines to keep only those whose length is greater or equal to thres, and return a count how many such lines there are in the file.

Â

Fourth, to wrap up this course before the final exam, write a method public List collectWords(Path path) throws IOException that similarly uses Files.lines to turn its parameter Path object into a Stream. Each line should be converted to lowercase and broken down to individual words that are then passed down the stream as separate strings (the stream operation flatMap will be handy here). Split each line into its individual words using the separator regex [^a-z]+ for the method split in String. In the next stage of the computation stream, filter out all empty words, and sort the remaining nonempty words in alphabetical order. The multiple consecutive occurrences of the same word should then be removed (use the stream operation distinct), and to finish up this pipeline, collected into a List returned as the answer.

Â

Â

                                                                                                                                  Order Now

Place Order