ppsolutions
This is an old revision of the document!
Table of Contents
Solutions for assignments in Parallele Programmierung.
See ETH. ParallelPrefix
Assignment 1
/** * * @author Moritz Hoffmann * */ public class Assignment1 { /** * Main method * * @param args * List of numbers. */ public static void main(String[] args) { int max = (1 << 16) - 1; int min = (-1 ^ (1 << 16)) + 1; for (String str : args) { try { int i = Integer.parseInt(str); if (i >= min && i <= max) { System.out.println(i + 1); } else { System.out.println("Number " + i + " out of range."); } } catch (NumberFormatException e) { System.out.println("Failed to convert to number: " + str); } } } }
Assignment 2
/** * * @author Moritz Hoffmann * */ public class Assignment2 { private final class MyException extends Exception { public MyException() { super(); } public MyException(String message) { super(message); } public MyException(String message, Throwable cause) { super(message, cause); } public MyException(Throwable cause) { super(cause); } } /** * Main method * * @param args * List of numbers. */ public static void main(String[] args) { new Assignment2().process(args); } /** * Process the string array. * * @param args * Same as from {@link Assignment1#main(String[])} */ private void process(String[] args) { for (String str : args) { try { int i = Integer.parseInt(str); try { if (i < 0) { throw new MyException(Integer.toString(i)); } System.out.println(i + 1); } catch (MyException e) { System.err.println("Negative value " + e.getMessage() + " -- bailing out."); break; } } catch (NumberFormatException e) { System.out.println("Failed to convert to number: " + str); } } } }
Bounded buffer for assignment 3:
package hw03; public class BoundedBuffer implements Buffer { private static final int SIZE = 5; private final int[] buffer = new int[SIZE]; private int pos = -1; public int read() throws BufferEmptyException { return get(); } public void write(int i) throws BufferFullException { set(i); } private synchronized int get() { while (pos == -1) { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } // the first element int v = buffer[0]; System.arraycopy(buffer, 1, buffer, 0, pos); pos = pos - 1; this.notifyAll(); return v; } private synchronized void set(int v) { System.out.println(pos); while (pos >= SIZE - 1) { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } pos = pos + 1; buffer[pos] = v; this.notifyAll(); } }
ppsolutions.1236349476.txt.gz · Last modified: 2009/03/06 14:24 by moritz