Solved Problems

Output a string to the console

Write the string "Hello World!" to STDOUT
java
System.out.println("Hello World!");
System.out.printf("Hello World!\n");

Retrieve a string containing ampersands from the variables in a url

My PHP script first does a query to obtain customer info for a form. The form has first name and last name fields among others. The customer has put entries such as "Ron & Jean" in the first name field in the database. Then the edit form script is called with variables such as

"http://myserver.com/custinfo/edit.php?mode=view&fname=Ron & Jean&lname=Smith".

The script variable for first name $_REQUEST['firstname'] never gets beyond the "Ron" value because of the ampersand in the data.

I have tried various functions like urldecode but all to no avail. I even tried encoding the url before the view screen is painted so that the url looks like "http://myserver/custinfo/edit.php?mode=view&fname="Ronxxnbsp;xxamp;xxnbsp;Jean"&lname=SMITH". (sorry I had to add the xx to replace the ampersand or it didn't display meaningful url contents the browser sees.)

Of course this fails for the same reasons. What is a better approach?
java
Map<String, String> params = new HashMap<String, String>();
params.put("mode", "view");
params.put("fname", "Ron & Jean");
params.put("lname", "Smith");

StringBuilder buffer = new StringBuilder();
for (Map.Entry<String, String> entry : params.entrySet()) {
buffer.append(URLEncoder.encode(entry.getKey(), "UTF-8"))
.append("=")
.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
System.out.println(buffer.toString());

string-wrap

Wrap the string "The quick brown fox jumps over the lazy dog. " repeated ten times to a max width of 78 chars, starting each line with "> "

Expected output:
> The quick brown fox jumps over the lazy dog. The quick brown fox jumps over t
> he lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox
> jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The qui
> ck brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy
> dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps o
> ver the lazy dog. The quick brown fox jumps over the lazy dog.
java
public class SolutionXX {
public static void main(String[] args) {
StringBuilder builder = new StringBuilder();
String words = "The quick brown fox jumps over the lazy dog. ";

for (int i = 0; i < 10; i++)
{
builder.append(words);
}

String toWrap = builder.toString();
int width = 76;
while (toWrap!=null && toWrap.length()>0)
{
String first = toWrap.length() > width ? toWrap.substring(0, width+1) : toWrap;
toWrap = (!toWrap.equals(first)) ? toWrap.substring(width + 1).trim() : null;
System.out.println("> " + first);
}

}
}
public class PangramWrapper {
public static void main(String[] args) {
int lineLimit = 78;
String newLine = "\n> ";
String pangram = "The quick brown fox jumps over the lazy dog. ";
String repeated = new String(new char[10]).replace("\0", pangram);

StringBuffer all = new StringBuffer(newLine + repeated);
for(int count = 1; count*lineLimit < all.length(); count++) {
all.insert(count * lineLimit, newLine);
}
System.out.println(all);
}
}
public class PangramWrapperViaRegexAndJoin {
public static void main(String[] args) {
String newLine = "\n> ",
pangram = "The quick brown fox jumps over the lazy dog. ",
repeated = new String(new char[10]).replace("\0", pangram);

final String[] splitted = repeated.split("(?<=\\G.{78})"); // worse performance than substring in for-loop
System.out.println("> "+ String.join(newLine, Arrays.asList(splitted)));
}
}

Define a string containing special characters

Define the literal string "\#{'}${"}/"
java
String special = "\\#{'}${\"}/";

Define a multiline string

Define the string:
"This
Is
A
Multiline
String"
java
String text = "This\nIs\nA\nMultiline\nString";
String text =
"This\n" +
"Is\n" +
"A\n" +
"Multiline\n" +
"String"

Define a string containing variables and expressions

Given variables a=3 and b=4 output "3+4=7"
java
System.out.println(a + "+" + b + "=" + (a+b));
System.out.printf("%d+%d=%d\n", a, b, a + b);

Reverse the characters in a string

Given the string "reverse me", produce the string "em esrever"
java
String reverse = new StringBuffer("reverse me").reverse().toString();
String reverse = new StringBuilder("reverse me").reverse().toString();
String reverse = StringUtils.reverse("reverse me");

Reverse the words in a string

Given the string "This is a end, my only friend!", produce the string "friend! only my end, the is This"
java
List list = new ArrayList();
StringTokenizer st = new StringTokenizer(text, " ");
while(st.hasMoreTokens()) {
list.add(0, st.nextToken());
}
StringBuffer sb = new StringBuffer();
for (Iterator iterator = list.iterator(); iterator.hasNext();) {
String word = (String) iterator.next();
sb.append(word);
if (iterator.hasNext()) {
sb.append(" ");
}
}
String reversed = sb.toString();
List<String> ls = Arrays.asList("This is the end, my only friend!".split("\\s"));
Collections.reverse(ls);
StringBuilder sb = new StringBuilder(32); for (String s : ls) sb.append(" ").append(s);
String reversed = sb.toString().trim();
String reversed = StringUtils.reverseDelimited("This is the end, my only friend!", ' ');

Text wrapping

Wrap the string "The quick brown fox jumps over the lazy dog. " repeated ten times to a max width of 78 chars, starting each line with "> ", yielding this result:

> The quick brown fox jumps over the lazy dog. The quick brown fox jumps
> over the lazy dog. The quick brown fox jumps over the lazy dog. The
> quick brown fox jumps over the lazy dog. The quick brown fox jumps
> over the lazy dog. The quick brown fox jumps over the lazy dog. The
> quick brown fox jumps over the lazy dog. The quick brown fox jumps
> over the lazy dog. The quick brown fox jumps over the lazy dog. The
> quick brown fox jumps over the lazy dog.
java
String prefix = "> "; String input = "The quick brown fox jumps over the lazy dog.";

String[] lines = WordUtils.wrap(StringUtils.repeat(input, 10), 72 - prefix.length()).split("\n");

for (String line : lines) System.out.printf("%s%s\n", prefix, line);

Remove leading and trailing whitespace from a string

Given the string "  hello    " return the string "hello".
java
String s = " hello "; String trimmed = s.trim();

Simple substitution cipher

Take a string and return the ROT13 and ROT47 (Check Wikipedia) version of the string.
For example:
String is: Hello World #123
ROT13 returns: Uryyb Jbeyq #123
ROT47 returns: w6==@ (@C=5 R`ab
java
CharArrayWriter rot13 = new CharArrayWriter() ;
for (char c : i ) {
char lc = Character.toLowerCase(c) ;
rot13.append( c += ( (lc >= 'a' && lc <= 'm') ? 13 : ( (lc >= 'n' && lc <= 'z') ? -13 : 0 ) )) ;
}

CharArrayWriter rot47 = new CharArrayWriter() ;
for (char c : i )
rot47.append( c += ( (c >= '!' && c <= 'O') ? 47 : ( (c >= 'P' && c <= '~') ? -47 : 0 ) )) ;

Make a string uppercase

Transform "Space Monkey" into "SPACE MONKEY"
java
String upper = text.toUpperCase();

Make a string lowercase

Transform "Caps ARE overRated" into "caps are overrated"
java
"Caps ARE overRated".toLowerCase();

Capitalise the first letter of each word

Transform "man OF stEEL" into "Man Of Steel"
java
String input = "man OF stEEL";
StringTokenizer tokenizer = new StringTokenizer(input);
StringBuffer sb = new StringBuffer();
while (tokenizer.hasMoreTokens()) {
String word = tokenizer.nextToken();
sb.append(word.substring(0, 1).toUpperCase());
sb.append(word.substring(1).toLowerCase());
sb.append(' ');
}
String text = sb.toString();
StringBuilder sb = new StringBuilder("man OF stEEL"); String s = sb.toString();
int last = s.length() - 1;

for (int i = 0; i <= last; ++i)
if (Character.isSpaceChar(s.charAt(i)) && i < last) { ++i; sb.setCharAt(i, Character.toUpperCase(s.charAt(i))); }
else if (i == 0) sb.setCharAt(i, Character.toUpperCase(s.charAt(i)));
else sb.setCharAt(i, Character.toLowerCase(s.charAt(i)));
Matcher m = Pattern.compile("(\\w+)").matcher("man OF stEEL"); StringBuffer sb = new StringBuffer(32), rsb = new StringBuffer(8);

while (m.find())
{
rsb.replace(0, rsb.length(), m.group().toLowerCase()); rsb.setCharAt(0, Character.toUpperCase(rsb.charAt(0)));
m.appendReplacement(sb, rsb.toString());
}
m.appendTail(sb);
String text = WordUtils.capitalizeFully("man OF stEEL");

Find the distance between two points

java
double distance = Point2D.distance(x1, y1, x2, y2);
Point2D point1 = new Point2D.Double(x1, y1);
Point2D point2 = new Point2D.Double(x2, y2);
double distance = point1.distance(point2);
double distance = Math.hypot(x2-x1, y2-y1);

Zero pad a number

Given the number 42, pad it to 8 characters like 00000042
java
String formatted = new DecimalFormat("00000000").format(42);
String formatted = String.format("%08d", 42);

Right Space pad a number

Given the number 1024 right pad it to 6 characters "1024  "
java
private static String spaces(int spaces) {
StringBuffer sb = new StringBuffer();
for(int i=0; i<spaces; i++) {
sb.append(' ');
}
return sb.toString();
}

private static String rightPad(int number, int spaces) {
String numberString = String.valueOf(number);
return numberString + spaces(spaces - numberString.length());
}
String text = StringUtils.rightPad(String.valueOf(1024), 6)
String formatted = String.format("%-6d", 1024);

Format a decimal number

Format the number 7/8 as a decimal with 2 places: 0.88
java
String formatted = String.format("%3.2f", 7./8.);

Left Space pad a number

Given the number 73 left pad it to 10 characters "        73"
java
private static String spaces(int spaces) {
StringBuffer sb = new StringBuffer();
for(int i=0; i<spaces; i++) {
sb.append(' ');
}
return sb.toString();
}

private static String leftPad(int number, int spaces) {
String numberString = String.valueOf(number);
return spaces(spaces - numberString.length()) + numberString;
}
String formatted = String.format("%10d", 73);

Generate a random integer in a given range

Produce a random integer between 100 and 200 inclusive
java
Random random = new Random();
int randomInt = random.nextInt(200-100+1)+100;

Generate a repeatable random number sequence

Initialise a random number generator with a seed and generate five decimal values. Reset the seed and produce the same values.
java
int[] arr1 = genFillRand(new int[5], new Random(12345), 100, 200);
int[] arr2 = genFillRand(new int[5], new Random(12345), 100, 200);

for (int[] arr : new int[][]{ arr1, arr2 }) { for (int i : arr) System.out.printf("%d ", i); System.out.println(); }

Check if a string matches a regular expression

Display "ok" if "Hello" matches /[A-Z][a-z]+/
java
if ("Hello".matches("[A-Z][a-z]+")) {
System.out.println("ok");
}

Check if a string matches with groups

Display "two" if "one two three" matches /one (.*) three/
java
Pattern pattern = Pattern.compile("one (.*) three");
Matcher matcher = pattern.matcher("one two three");
if (matcher.matches()) {
System.out.println(matcher.group(1));
}

Check if a string contains a match to a regular expression

Display "ok" if "abc 123 @#$" matches /\d+/
java
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher(text);
if (matcher.find()) {
System.out.println("ok");
}

Loop through a string matching a regex and performing an action for each match

Create a list [fish1,cow3,boat4] when matching "(fish):1 sausage (cow):3 tree (boat):4" with regex /\((\w+)\):(\d+)/
java
List list = new ArrayList();
Pattern pattern = Pattern.compile("\\((\\w+)\\):(\\d+)");
Matcher matcher = pattern.matcher(text);
while(matcher.find()) {
list.add(matcher.group(1)+matcher.group(2));
}

Replace the first regex match in a string with a static string

Transform "Red Green Blue" into "R*d Green Blue" by replacing /e/ with "*"
java
String replaced = "Red Green Blue".replaceFirst("e", "*");

Replace all regex matches in a string with a static string

Transform "She sells sea shells" into "She X X shells" by replacing /se\w+/ with "X"
java
String replaced = text.replaceAll("se\\w+", "X");

Replace all regex matches in a string with a dynamic string

Transform "The {Quick} Brown {Fox}" into "The kciuQ Brown xoF" by reversing words in braces using the regex /\{(\w+)\}/.
java
Matcher m = Pattern.compile("\\{(\\w+)\\}").matcher("The {Quick} Brown {Fox}");
StringBuffer sb = new StringBuffer(32), rsb = new StringBuffer(8);

while (m.find())
{
rsb.replace(0, rsb.length(), m.group(1)); rsb.reverse(); m.appendReplacement(sb, rsb.toString());
}
m.appendTail(sb);

Define an empty list

Assign the variable "list" to a list with no elements
java
List list = Collections.emptyList();
String[] list = {};

Define a static list

Define the list [One, Two, Three, Four, Five]
java
List<String> numbers = new ArrayList<String>();
Collections.addAll(numbers, "One", "Two", "Three", "Four", "Five");
List numbers = new ArrayList();
numbers.add("One");
numbers.add("Two");
numbers.add("Three");
numbers.add("Four");
numbers.add("Five");
List numbers = Arrays.asList(new String[]{"One", "Two", "Three", "Four", "Five"});
String[] numbers = {"One", "Two", "Three", "Four", "Five"};
List numbers = new ArrayList(){{put("One"); put("Two"); put("Three"); put("Four"); put("Five"); }};

Join the elements of a list, separated by commas

Given the list [Apple, Banana, Carrot] produce "Apple, Banana, Carrot"
java
StringBuffer sb = new StringBuffer();
for (Iterator it = fruit.iterator(); it.hasNext();) {
sb.append(it.next());
if (it.hasNext()) {
sb.append(", ");
}
}
String result = sb.toString();
StringBuilder sb = new StringBuilder(fruit.get(0));
for (String item : fruit.subList(1, fruit.size())) sb.append(", ").append(item);
String result = sb.toString();
String result = StringUtils.join(fruit, ", ");

Join the elements of a list, in correct english

Create a function join that takes a List and produces a string containing an english language concatenation of the list. It should work with the following examples:
join([Apple, Banana, Carrot]) = "Apple, Banana, and Carrot"
join([One, Two]) = "One and Two"
join([Lonely]) = "Lonely"
join([]) = ""
java
private String join(List elements) {
if (elements == null || elements.size() == 0) {
return "";
} else if (elements.size() == 1) {
return elements.get(0).toString();
} else if (elements.size() == 2) {
return elements.get(0) + " and " + elements.get(1);
}
StringBuffer sb = new StringBuffer();
for (Iterator it = elements.iterator(); it.hasNext();) {
String next = (String) it.next();
if (sb.length() > 0) {
if (it.hasNext()) {
sb.append(", ");
} else {
sb.append(", and ");
}
}
sb.append(next);
}
return sb.toString();
}
System.out.println(join(fruit));

Produce the combinations from two lists

Given two lists, produce the list of tuples formed by taking the combinations from the individual lists. E.g. given the letters ["a", "b", "c"] and the numbers [4, 5], produce the list: [["a", 4], ["b", 4], ["c", 4], ["a", 5], ["b", 5], ["c", 5]]
java
List<String> combinations = new ArrayList<String>();

for (int number : numbers)
for (String letter : letters)
combinations.add(letter + ":" + Integer.toString(number));
SortedSet<AbstractMap.SimpleImmutableEntry<String, Integer> > combinations =
new TreeSet<AbstractMap.SimpleImmutableEntry<String, Integer> >(new CombinationComparator());

for (int number : numbers)
for (String letter : letters)
combinations.add(new AbstractMap.SimpleImmutableEntry<String, Integer>(letter, Integer.valueOf(number)));

From a List Produce a List of Duplicate Entries

Taking a list:
["andrew", "bob", "chris", "bob"]

Write the code to produce a list of duplicates in the list:
["bob"]
java
List listOfDuplicates = new ArrayList(Arrays.asList(new String[]{"andrew", "bob", "chris", "bob"}));

Set set = new HashSet(listOfDuplicates);
for (Object element : set)
listOfDuplicates.remove(element);

Fetch an element of a list by index

Given the list [One, Two, Three, Four, Five], fetch the third element ('Three')
java
String result = list.get(2);

Fetch the last element of a list

Given the list [Red, Green, Blue], access the last element ('Blue')
java
String result = list.get(list.size() - 1);

Find the common items in two lists

Given two lists, find the common items. E.g. given beans = ['broad', 'mung', 'black', 'red', 'white'] and colors = ['black', 'red', 'blue', 'green'], what are the bean varieties that are also color names?
java
List beans = Arrays.asList(new String[]{"broad", "mung", "black", "red", "white"});
List colors = Arrays.asList(new String[]{"black", "red", "blue", "green"});

List common = ListUtils.intersection(beans, colors);

Display the unique items in a list

Display the unique items in a list, e.g. given ages = [18, 16, 17, 18, 16, 19, 14, 17, 19, 18], display the unique elements, i.e. with duplicates removed.
java
Set<Integer> ages = new TreeSet<Integer>(Arrays.asList(new Integer[]{18, 16, 17, 18, 16, 19, 14, 17, 19, 18}));

System.out.println(ages);

Remove an element from a list by index

Given the list [Apple, Banana, Carrot], remove the first element to produce the list [Banana, Carrot]
java
list.remove(0);

Remove the last element of a list

java
list.remove(list.size() - 1);

Rotate a list

Given a list ["apple", "orange", "grapes", "bananas"], rotate it by removing the first item and placing it on the end to yield ["orange", "grapes", "bananas", "apple"]
java
list.add(list.remove(0));
Collections.rotate(list, -1);

Gather together corresponding elements from multiple lists

Given several lists, gather together the first element from every list, the second element from every list, and so on for all corresponding index values in the lists. E.g. for these three lists, first = ['Bruce', 'Tommy Lee', 'Bruce'], last = ['Willis', 'Jones', 'Lee'], years = [1955, 1946, 1940] the result should produce 3 actors. The middle actor should be Tommy Lee Jones.
java
String[] first = new String[]{"Bruce", "Tommy Lee", "Bruce"};
String[] last = new String[]{"Willis", "Jones", "Lee"};
String[] years = new String[]{"1955", "1946", "1940"};

List<String[]> list = new ArrayList<String[]>(); list.add(first); list.add(last); list.add(years);

String[] result = zip(",", list);

List Combinations

Given two source lists (or sets), generate a list (or set) of all the pairs derived by combining elements from the individual lists (sets). E.g. given suites = ['H', 'D', 'C', 'S'] and faces = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'], generate the deck of 52 cards, confirm the deck size and check it contains an expected card, say 'Ace of Hearts'.
java
SortedSet<AbstractMap.SimpleImmutableEntry<String, String> > cards =
new TreeSet<AbstractMap.SimpleImmutableEntry<String, String> >(new CardComparator());

for (String suite : suites)
for (String face : faces)
cards.add(new AbstractMap.SimpleImmutableEntry<String, String>(suite, face));

Boolean containsEntry = cards.contains(new AbstractMap.SimpleImmutableEntry<String, String>("h", "A"));

if (containsEntry) System.out.println("Deck contains 'Ace of Hearts'");
else System.out.println("'Ace of Hearts' not in deck");

Perform an operation on every item of a list

Perform an operation on every item of a list, e.g.
for the list ["ox", "cat", "deer", "whale"] calculate
the list of sizes of the strings, e.g. [2, 3, 4, 5]
java
public class SolutionXX {
public static void main(String[] args) {
String[] list = {"ox", "cat", "deer", "whale"};
for (String str : list) {
System.out.println(str.length() + " ");
}
}
}

Split a list of things into numbers and non-numbers

Given a list that might contain e.g. a string, an integer, a float and a date,
split the list into numbers and non-numbers.
java
public class NumbersSolution {
public static void main(String[] args) {
List<Object> items = Arrays.asList(new Object[] { new Date(), 12L, 15.4, 99, "x" } ) ;
List<Object> numbers = new ArrayList<Object>() ;
List<Object> nonNumbers = new ArrayList<Object>() ;
for (Object item : items )
(item instanceof Number ? numbers : nonNumbers).add(item) ;
}
}
public class NumbersSolution {
public static void main() {
List<Object> numbers = new ArrayList<Object>() ;
List<Object> nonNumbers = new ArrayList<Object>() ;
for (Object item : new Object[] { new Date(), 12L, 15.4, 99, "x" } )
(item instanceof Number ? numbers : nonNumbers).add(item) ;
}
}

Test if a condition holds for all items of a list

Given a list, test if a certain logical condition (i.e. predicate) holds for all items of the list.
java
List<String> la = Arrays.asList("a", "b", "", "c");// listWithEmptyValues
List<String> lb = Arrays.asList("a", null, "", "c");// listWithNullValues
List<String> lc = Arrays.asList("a", "b", "d", "c");// listWithNonEmptyValues

Predicate<String> correctValue = (String s) -> s != null && !s.isEmpty();

System.out.println(la.stream().allMatch(correctValue)); // false
System.out.println(lb.stream().allMatch(correctValue)); // false
System.out.println(lc.stream().allMatch(correctValue)); // true
int[] array = {1, 2, 3}; Arrays.stream(array).anyMatch((x) -> x > 1);

Define an empty map

java
Map map = new HashMap();

Define an unmodifiable empty map

java
Map empty = Collections.EMPTY_MAP;
SortedMap empty = MapUtils.EMPTY_SORTED_MAP;

Define an initial map

Define the map {circle:1, triangle:3, square:4}
java
Map shapes = new HashMap();
shapes.put("circle", 1);
shapes.put("triangle", 3);
shapes.put("square", 4);
Map shapes = new HashMap() {{ put("circle",1); put("triangle",3); put("square",4); }}

Check if a key exists in a map

Given a map pets {joe:cat,mary:turtle,bill:canary} print "ok" if an pet exists for "mary"
java
if (pets.containsKey("mary")) System.out.println("ok");

Retrieve a value from a map

Given a map pets {joe:cat,mary:turtle,bill:canary} print the pet for "joe" ("cat")
java
String pet = pets.get("joe");

Add an entry to a map

Given an empty pets map, add the mapping from "rob" to "dog"
java
pets.put("rob", "dog");

Remove an entry from a map

Given a map pets {joe:cat,mary:turtle,bill:canary} remove the mapping for "bill" and print "canary"
java
System.out.println(pets.remove("bill"))

Create a histogram map from a list

Given the list [a,b,a,c,b,b], produce a map {a:2, b:3, c:1} which contains the count of each unique item in the list
java
Map map = new HashMap();
for (Iterator it = list.iterator(); it.hasNext();) {
String s = (String) it.next();
if (!map.containsKey(s)) {
map.put(s, new Integer(1));
} else {
map.put(s, new Integer(((Integer)map.get(s)).intValue() + 1));
}
}
LinkedMap histogram = new LinkedMap();

for (Object letter : list)
histogram.put(letter, !histogram.containsKey(letter) ? 1 : MapUtils.getIntValue(histogram, letter) + 1);

Categorise a list

Given the list [one, two, three, four, five] produce a map {3:[one, two], 4:[four, five], 5:[three]} which sorts elements into map entries based on their length
java
SortedMap<Integer, List<String> > map = new TreeMap<Integer, List<String> >(); int key; List<String> vlist;

for (String item : list)
{
key = item.length(); vlist = map.containsKey(key) ? map.get(key) : new ArrayList<String>();
vlist.add(item); map.put(key, vlist);
}
MultiValueMap map = new MultiValueMap();
for (Object item : list) map.put(((String) item).length(), item);

Perform an action if a condition is true (IF .. THEN)

Given a variable name, if the value is "Bob", display the string "Hello, Bob!". Perform no action if the name is not equal.
java
if (name.equals("Bob")) {
System.out.println("Hello, Bob!");
}

Perform different actions depending on a boolean condition (IF .. THEN .. ELSE)

Given a variable age, if the value is greater than 42 display "You are old", otherwise display "You are young"
java
if (age > 42) {
System.out.println("You are old");
} else {
System.out.println("You are young");
}
System.out.println("You are " + ((age>42)?"old":"young"));

Perform different actions depending on several boolean conditions (IF .. THEN .. ELSIF .. ELSE)

java
if (age > 84) System.out.println("You are really ancient");
else if (age > 30) System.out.println("You are middle-aged");
else System.out.println("You are young");

Replacing a conditional with many branches with a switch/case statement

Many languages support more compact forms of branching than just if ... then ... else such as switch or case or match. Use such a form to add an appropriate placing suffix to the numbers 1..40, e.g. 1st, 2nd, 3rd, 4th, ..., 11th, 12th, ... 39th, 40th
java
String[] array = new String[40];
for(int n = 1; n <= array.length; n++)
array[n-1] = Integer.toString(n);
for(int n = 0; n < array.length; n++)
{
int y = Integer.parseInt(array[n]);
if(array[n].length() > 1)
y = Integer.parseInt(array[n].substring(1));
switch(y)
{
case 1: {array[n] += "st"; break;}
case 2: {array[n] += "nd"; break;}
case 3: {array[n] += "rd"; break;}
default: array[n] += "th";
}
}

Perform an action multiple times based on a boolean condition, checked before the first action (WHILE .. DO)

Starting with a variable x=1, Print the sequence "1,2,4,8,16,32,64,128," by doubling x and checking that x is less than 150.
java
int x = 1;
while (x < 150) {
System.out.println(x+",");
x*=2;
}

Perform an action multiple times based on a boolean condition, checked after the first action (DO .. WHILE)

Simulate rolling a die until you get a six. Produce random numbers, printing them until a six is rolled. An example output might be "4,2,1,2,6"
java
int rnd;
do {
rnd = (int)(Math.random()*6)+1;
System.out.print(rnd);
if (rnd!=6) {
System.out.print(",");
}
} while(rnd!=6);

Perform an action a fixed number of times (FOR)

Display the string "Hello" five times like "HelloHelloHelloHelloHello"
java
for(int i=0;i<5;i++) {
System.out.print("Hello");
}

Perform an action a fixed number of times with a counter

Display the string "10 .. 9 .. 8 .. 7 .. 6 .. 5 .. 4 .. 3 .. 2 .. 1 .. Liftoff!"
java
for(int i=10; i>=1; i--) {
System.out.print(i + " .. ");
}
System.out.print("Liftoff!");

Read the contents of a file into a string

java
String text = FileUtils.readFileToString(new File("Solution109.java"), "UTF-8");
RandomAccessFile raf = null; byte[] buffer; String text = null;

try
{
raf = new RandomAccessFile("Solution399.java", "r");
buffer = new byte[(int)raf.length()]; raf.read(buffer);
text = new String(buffer);
}

Process a file one line at a time

Open the source file to your solution and print each line in the file, prefixed by the line number, like:
1> First line of file
2> Second line of file
3> Third line of file
java
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("Solution104.java"));
String line = null;
int lineNumber = 1;
while ((line=br.readLine())!=null) {
System.out.println(lineNumber + "> " + line);
lineNumber++;
}
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if (br!=null) {
try {
br.close();
} catch (Exception e) {
// ok
}
}
}
LineNumberReader lnr = null; PrintWriter pw = null; String line;

try
{
lnr = new LineNumberReader(new FileReader("Solution400.java"));
pw = new PrintWriter(System.out);
while ((line = lnr.readLine()) != null) pw.printf("%d> %s\n", lnr.getLineNumber(), line);
}

Write a string to a file

java
FileWriter fw = null;

try
{
fw = new FileWriter("test.txt");
fw.write("This line overwites file contents!");
}
PrintWriter pw = null;

try
{
pw = new PrintWriter(new BufferedWriter(new FileWriter("test.txt")));
pw.print("This line overwites file contents!");
}

Append to a file

java
FileWriter fw = null;

try
{
fw = new FileWriter("test.txt", true);
fw.write("This line appended to file!");
}
PrintWriter pw = null;

try
{
pw = new PrintWriter(new BufferedWriter(new FileWriter("test.txt", true)));
pw.print("This line appended to file!");
}

Process each file in a directory

java
for (File file : (new File("c:\\")).listFiles()) process(file);

Process each file in a directory recursively

java
processDirectory(new File("c:\\"));

Parse a date and time from a string

Given the string "2008-05-06 13:29", parse it as a date representing 6th March, 2008 1:29:00pm in the local time zone.
java
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
Date date = df.parse("2008-05-06 13:29");
DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm");
DateTime dt = fmt.parseDateTime("2008-05-06 13:29");

Display information about a date

Display the day of month, day of year, month name and day name of the day 8 days from now.
java
Calendar cal = Calendar.getInstance();
cal.add(DAY_OF_YEAR, 8);
System.out.println(cal.get(DAY_OF_MONTH));
System.out.println(cal.get(DAY_OF_YEAR));
System.out.println(new SimpleDateFormat("MMMM").format(cal.getTime()));
System.out.println(new SimpleDateFormat("EEEE").format(cal.getTime()));

Display a date in different locales

Display a language/locale friendly version of New Year's Day for 2009 for several languages/locales. E.g. for languages English, French, German, Italian, Dutch the output might be something like:

Thursday, January 1, 2009
jeudi 1 janvier 2009
giovedì 1 gennaio 2009
Donnerstag, 1. Januar 2009
donderdag 1 januari 2009

(Indicate in comments where possible if any language specific or operating system configuration needs to be in place.)
java
Calendar cal = Calendar.getInstance();
cal.set(2009, Calendar.JANUARY, 1);
Locale[] locales = { ENGLISH, FRENCH, ITALIAN, GERMAN, new Locale("nl") };

for (Locale l : locales) {
System.out.println(getDateInstance(FULL, l).format(cal.getTime()));
}

Display the current date and time

Create a Date object representing the current date and time. Print it out.
If you can also do this without creating a Date object you can show that too.
java
import java.util.Date;

public class SolutionXX {
public static void main(String[] args) {
Date now = new Date();
System.out.println(now.toString());
}
}
OOP

Define a class

Declare a class named Greeter that takes a string on creation and greets using this string if you call the "greet" method.
java
class Greeter
{
public Greeter(String whom) { this.whom = whom; }
public void greet() { System.out.printf("Hello, %s\n", whom); }
private String whom;
}

public class Solution381 {
public static void main(String[] args) {
(new Greeter("world")).greet();
}
}

Instantiate object with mutable state

Reimplement the Greeter class so that the 'whom' property or data member remains private but is mutable, and is provided with getter and setter methods. Invoke the setter to change the greetee, invoke 'greet', then use the getter in displaying the line, "I have just greeted {whom}.".

For example, if the greetee is changed to 'Tommy' using the setter, the 'greet' method would display:

Hello, Tommy!

The getter would then be used to display the line:

I have just greeted Tommy.
java
class Greeter {
private String whom;

public Greeter(String whom) {
this.whom = whom;
}

public String getWhom() {
return whom;
}

public void setWhom(String whom) {
this.whom = whom;
}

public void greet() {
System.out.println("Hello " + whom + "!");
}
}
Greeter greeter = new Greeter("World");
greeter.greet();
greeter.setWhom("Tommy");
greeter.greet();
System.out.println("I have just greeted " + greeter.getWhom() + ".");

Implement Inheritance Heirarchy

Implement a Shape abstract class which will form the base of an inheritance hierarchy that models 2D geometric shapes. It will have:

* A non-mutable 'name' property or data member set by derived or descendant classes at construction time
* A 'area' method intended to be overridden by derived or descendant classes ( double precision floating point return value)
* A 'print' method (also for overriding) will display the shape's name, area, and all shape-specific values

Two derived or descendant classes will be created:
* Circle    -> Constructor requires a '
radius' argument, and a 'circumference' method to be implemented  
* Rectangle -> Constructor requires '
length' and 'breadth' arguments, and a 'perimeter' method to be implemented 

Instantiate an object of each class, and invoke each objects '
print' method to show relevant details.
java
/*
* Will work with version 1.4 if you remove the @Override annotation
* and declare floating point numbers using the primitive "double"
*/
abstract class Shape {
protected final String name;
public Shape(String name) {
this.name = name;
}
public abstract Double area();
public abstract void print();
}
class Circle extends Shape {
private Double radius;
public Circle(Double radius) {
super("circle");
this.radius = radius;
}
@Override
public Double area() {
return Math.PI * Math.pow(radius, 2);
}
@Override
public void print() {
System.out.println("A " + name + " with radius " + radius
+ ", area " + area() + " and circumference "
+ circumference() + ".");
}
public Double circumference() {
return 2 * Math.PI * radius;
}
}
class Rectangle extends Shape {
private Double length, breadth;
public Rectangle(Double length, Double breadth) {
super("Rectangle");
this.length = length;
this.breadth = breadth;
}
@Override
public Double area() {
return length * breadth;
}
public Double perimeter() {
return 2 * length + 2 * breadth;
}
@Override
public void print() {
System.out.println("A " + name + " with length " + length
+ ", breadth " + breadth + ", area " + area()
+ " and perimeter " + perimeter() + ".");
}
}
Circle circle = new Circle(4d);
circle.print();
Rectangle rectangle = new Rectangle(2d, 5.5);
rectangle.print();

Implement and use an Interface

Create a Serializable interface consisting of 'save' and 'restore' methods, each of which:

* Accept a stream or handle or descriptor argument for the source or destination
* Save to destination or restore from source the properties or data members of the implementing class (restrict yourself to the primitive types 'int' and 'string')

Next, create a Person class which has 'name' and 'age' properties or data members and implements this interface. Instantiate a Person object, save it to a serial stream, and instantiate a new Person object by restoring it from the serial stream.
java
// Serialization to a file
class Person implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private int age;
public void setAge(int age) {
this.age = age;
}
public int getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public boolean equals(Object obj) {
if(obj == this) return true;
if(obj instanceof Person) {
Person p = (Person) obj;
return (p.getName().equals(this.getName())
& p.getAge() == this.getAge());
}
return false;
}
public String toString() {
return "Name: " + name + ", age: " + age;
}
}
Person person = new Person();
person.setName("Gaylord Focker");
person.setAge(21);

try {
File file = new File("ser.obj");
FileOutputStream fos = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(person);
oos.close();
FileInputStream fis = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fis);
Person deserializedPerson = (Person) ois.readObject();
ois.close();
System.out.println(deserializedPerson);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}

Check your language appears on the langref.org site

Your language name should appear within the HTML found at the http://langreg.org main page.
java
String url = "http://langref.org/", language = "java", line = null, regexp = ".*" + url + language + ".*";

BufferedReader in = new BufferedReader(new InputStreamReader((new URL(url)).openStream()));
while ((line = in.readLine()) != null)
if (line.matches(regexp)) { System.out.printf("Language %s exists @ %s\n", language, url); break; }

in.close();

Send an email

Use library functions, classes or objects to create a short email addressed to your own email address. The subject should be, "Greetings from langref.org", and the user should be prompted for the message body, and whether to cancel or proceed with sending the email.
java
// requires Java Mail API (mail.jar), which must be in classpath
try {
Properties props = System.getProperties();
props.put("mail.smtp.host", "smtp.sampledomain.com");
Session session = Session.getDefaultInstance(props, null);
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("gaylord.focker@hollywood.com"));
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse("father@family.com"));
msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse("mother@family.com"));
msg.setSubject("subject");
msg.setText("message body");
msg.setHeader("X-Mailer", "jAVAmAILER");
msg.setSentDate(new Date());
Transport.send(msg);
} catch (AddressException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
XML

Process an XML document

Given the XML Document:

<shopping>
  <item name="bread" quantity="3" price="2.50"/>
  <item name="milk" quantity="2" price="3.50"/>
</shopping>

Print out the total cost of the items, e.g. $14.50
java
// solution uses JAXP and SAX included in Java API since version >= 1.5
class ShoppingContentHandler extends DefaultHandler {
Double priceSum = 0d;
@Override
public void startElement(String uri, String localName, String name,
Attributes attributes) throws SAXException {
if(name.equals("item")) {
String quantityString = attributes.getValue(attributes.getIndex("quantity"));
String priceString = attributes.getValue(attributes.getIndex("price"));
Integer quantity = Integer.parseInt(quantityString);
Double price = Double.parseDouble(priceString);
priceSum += (quantity * price);
}
}
public Double getPriceSum() {
return priceSum;
}
}

SAXParserFactory parserFactory = SAXParserFactory.newInstance();
try {
SAXParser parser = parserFactory.newSAXParser();
XMLReader reader = parser.getXMLReader();
ShoppingContentHandler contentHandler = new ShoppingContentHandler();
reader.setContentHandler(contentHandler);
reader.parse(new InputSource(new FileReader("shopping.xml")));
System.out.printf("$%.2f", contentHandler.getPriceSum());

} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

create some XML programmatically

Given the following CSV:

bread,3,2.50
milk,2,3.50

Produce the equivalent information in XML, e.g.:

<shopping>
  <item name="bread" quantity="3" price="2.50" />
  <item name="milk" quantity="2" price="3.50" />
</shopping>
java
// In this solution JAXB is used to created the xml output.
// JAXB is included in Java 1.6. Runs with 1.5 if you include JAXB Jars
// in the classpath.
class Item {
// Of course you use getters and setters and declare attributes private.
// In this sample a "dirty" way is chosen to keep LOC low.
@XmlAttribute
String name;
@XmlAttribute
Integer quantity;
@XmlAttribute
Double price;
}

@XmlRootElement
class Shopping {
@XmlElement
Set<Item> items = new HashSet<Item>();
}

String line = null;
Shopping shopping = new Shopping();
try {
BufferedReader reader = new BufferedReader(new FileReader("shopping.csv"));
while ((line = reader.readLine()) != null) {
String[] parts = line.split(",");
Item item = new Item();
item.name = parts[0];
item.quantity = Integer.parseInt(parts[1]);
item.price = Double.parseDouble(parts[2]);
shopping.items.add(item);

}
JAXB.marshal(shopping, "D:" + File.separatorChar + "shopping.auto.xml");
} catch (IOException e) {
e.printStackTrace();
}

Find all Pythagorean triangles with length or height less than or equal to 20

Pythagorean triangles are right angle triangles whose sides comply with the following equation:

a * a + b * b = c * c

where c represents the length of the hypotenuse, and a and b represent the lengths of the other two sides. Find all such triangles where a, b and c are non-zero integers with a and b less than or equal to 20. Sort your results by the size of the hypotenuse. The expected answer is:

[3, 4, 5]
[6, 8, 10]
[5, 12, 13]
[9, 12, 15]
[8, 15, 17]
[12, 16, 20]
[15, 20, 25]
java
SortedSet<List<Integer>> results = new TreeSet<List<Integer>>(new Comparator<List<Integer>>() {
public int compare(List<Integer> o1, List<Integer> o2) {
return o1.get(2).compareTo(o2.get(2));
}
});
for (int x = 1; x <= 20; x++) {
for (int y = 1; y <= 20; y++) {
double z = Math.hypot(x, y) ;
if ((int) z == z)
results.add(Arrays.asList( new Integer[] { x, y, (int) z }));
}
}

Greatest Common Divisor

Find the largest positive integer that divides two given numbers without a remainder. For example, the GCD of 8 and 12 is 4.

java
static int gcd(int a, int b) {
if (Math.min(a, b) == 0)
return Math.max(a, b);
else
return gcd(Math.min(a, b), Math.abs(a - b));
}
Fun

produces a copy of its own source code

In computing, a quine is a computer program which produces a copy of its own source code as its only output.
java
public class Quine {public static void main(String[] args) {String s = "public class Quine {public static void main(String[] args) {String s = %c%s%c;System.out.printf(s, 34, s, 34);}}";System.out.printf(s, 34, s, 34);}}
public class Quine {
public static void main(String[] args) {
Character cq = (char) 34;
Character cn = (char) 10;
Character cs = (char) 92;
String s = "public class Quine {\n public static void main(String[] args) {\n Character cq = (char) 34;\n Character cn = (char) 10;\n Character cs = (char) 92;\n String s = %c%s%c;\n System.out.printf(s, cq, s.replace(cn.toString(), cs.toString() + 'n'), cq);\n }\n}";
System.out.printf(s, cq, s.replace(cn.toString(), cs.toString() + 'n'), cq);
}
}

Subdivide A Problem To A Pool Of Workers (No Shared Data)

Take a hard to compute problem and split it up between multiple worker threads. In your solution, try to fully utilize available cores or processors. (I'm looking at you, Python!)

Note: In this question, there should be no need for shared state between worker threads while the problem is being solved. Only after every thread completes computation are the answers recombined into a single output.

Example:

-Input-

(In python syntax)

["ab", "we", "tfe", "aoj"]

In other words, a list of random strings.

-Output-

(In python syntax)

[ ["ab", "ba", "aa", "bb", "a", "b"], ["we", "ew", "ww", "ee", "w", "e"], ...

In other words, all possible permutations of each input string are computed.
java
public class ParallelPermutations {

final AtomicInteger cnt = new AtomicInteger(0);

final List<Set<String>> permutations = new ArrayList<Set<String>>();

public static void main(String[] args) {
new ParallelPermutations(Arrays.asList(args));
}

public ParallelPermutations(List<String> words) {
for (final String word : words) {
new Thread(new Runnable() {
public void run() {
cnt.incrementAndGet() ;
Set<String> permutationSet = new HashSet<String>();
for (int i = 0; i < word.length(); i++)
for (int j = i + 1; j <= word.length(); j++)
permutations("", word.substring(i, j),
permutationSet);
permutations.add(permutationSet);
if (cnt.decrementAndGet() == 0)
synchronized (ParallelPermutations.this) {
ParallelPermutations.this.notify();
}
}
private void permutations(String prefix, String word, Set<String> permutations) {
int N = word.length();
if (N == 0)
permutations.add(prefix);
else
for (int i = 0; i < N; i++)
permutations(
prefix + word.charAt(i),
word.substring(0, i) + word.substring(i + 1, N),
permutations);
}
}).start();
}

synchronized (this) {
try {
wait();
} catch (InterruptedException e) {
Thread.currentThread().isInterrupted();
}
}

System.out.println(permutations);
}

}
public class ParallelPermutations {
public static void main(String[] words) throws Exception {
if(words.length==0)
words = new String[] {"ab", "we", "tfe", "aoj"};

ParallelPermutations permutations = new ParallelPermutations();
Map<String,Set<String>> wordPermutationSet =
permutations.calculate(words);

for(Map.Entry<String,Set<String>> e : wordPermutationSet.entrySet())
System.out.println(e.getKey()+" > "+e.getValue());

System.out.println(permutations.getNumberOfJobSpawned ()+" job(s) have been spawned");
}

private AtomicInteger jobSpawnedCounter = new AtomicInteger();
private ExecutorService workers ;
private ConcurrentLinkedQueue<Future<PermutationTask>> jobSpawned = newQueue();

public ParallelPermutations () {
int availableProcessors = Runtime.getRuntime().availableProcessors();
// create a thread pool according to the number of proc.
workers = Executors.newFixedThreadPool(availableProcessors);
}

private void spawn(PermutationTask task) {
Future<PermutationTask> spawned = workers.submit(task);
jobSpawnedCounter.incrementAndGet();
jobSpawned.add(spawned);
}
public int getNumberOfJobSpawned () {
return jobSpawnedCounter.get();
}

public Map<String,Set<String>> calculate (String[] words)
throws InterruptedException, ExecutionException
{
// submit all tasks, they will spawn sub-tasks by themselves
for(String word:words)
spawn(new PermutationTask(word));

Map<String,Set<String>> wordPermutationSet = newMap ();
Future<PermutationTask> spawned;
while( (spawned=jobSpawned.poll()) != null) {
// this will wait until the result is available
// this should also handle the fact that a sub-task is spawn
// and then added in the 'jobSpawned' before its parent is done
PermutationTask task = spawned.get();

String word = task.getWord();
Set<String> founds = task.getPermutationSet();
Set<String> alreadyFounds = wordPermutationSet.get(word);
if(alreadyFounds!=null)
alreadyFounds.addAll(founds);
else
wordPermutationSet.put(word, founds);
}
return wordPermutationSet;
}

private class PermutationTask implements Callable<PermutationTask> {
private final Set<String> permutationSet = new HashSet<String>();
private final String word;
private final int initialPos;
private final Stack<Integer> indicesUsed;
public PermutationTask(String word) {
this(word, 0, new Stack<Integer>());
}

/** sub task entry point */
public PermutationTask(String word,
int initialPos,
Stack<Integer> indicesUsed) {
this.word = word;
this.initialPos = 0;
this.indicesUsed = indicesUsed;
}

/** the word this task is working on*/
public String getWord() {
return word;
}

/** permutations set of this task */
public Set<String> getPermutationSet() {
return permutationSet;
}

/**
* perform the task specific calculation
* @see Callable
*/
public PermutationTask call() throws Exception {
calculatePermutation(initialPos, indicesUsed);
return this;
}

/**
* The algorithm part of the problem. The main interest is the sub-task
* spawning. When Java 7 will be available there would be a better
* alternative with the built-in fork/join framework.
*/
private void calculatePermutation(int currentPos, Stack<Integer> indicesUsed) {
final int maxLetterPerWord = word.length();
if(indicesUsed.size()>=maxLetterPerWord) {
return;
}

final StringBuilder builder = new StringBuilder();
for (int i = 0, length = word.length(); i < length; i++) {
if(indicesUsed.contains(i) && distinctIndices)
continue;
indicesUsed.push(i);
if(indicesUsed.size()>=MIN_LETTER_PER_WORD) {
builder.setLength(0);
for(Integer index: indicesUsed)
builder.append(word.charAt(index));
permutationSet.add(builder.toString());
}
// spawn a sub task to perform the next pos. calculation
spawn(new PermutationTask(word, currentPos+1, copy(indicesUsed)));
indicesUsed.pop();
}
}
}

/* algorithm parameters : the minimum number of letter per word */
private static int MIN_LETTER_PER_WORD = 1;
/* allow duplicated letters in the word found */
private static boolean distinctIndices = true;

/* factory method */
private static <T> ConcurrentLinkedQueue<T> newQueue () {
return new ConcurrentLinkedQueue<T>();
}
/* factory method */
private static <K,V> Map<K,V> newMap () {
return new HashMap<K,V>();
}
/* factory method */
private static Stack<Integer> copy(Stack<Integer> stack) {
Stack<Integer> copy = new Stack<Integer>();
copy.addAll(stack);
return copy;
}
}

Subdivide A Problem To A Pool Of Workers (Shared Data)

Take a hard to compute problem and split it up between multiple worker threads. In your solution, try to fully utilize available cores or processors. (I'm looking at you, Python!)

Note: In this question, there should be a need for shared state between worker threads while the problem is being solved.

Example:

-Conway Game of Life-

From Wikipedia:

The universe of the Game of Life is an infinite two-dimensional orthogonal grid of square cells, each of which is in one of two possible states, live or dead. Every cell interacts with its eight neighbors, which are the cells that are directly horizontally, vertically, or diagonally adjacent. At each step in time, the following transitions occur:

1. Any live cell with fewer than two live neighbours dies, as if caused by underpopulation.
2. Any live cell with more than three live neighbours dies, as if by overcrowding.
3. Any live cell with two or three live neighbours lives on to the next generation.
4. Any dead cell with exactly three live neighbours becomes a live cell.

The initial pattern constitutes the seed of the system. The first generation is created by applying the above rules simultaneously to every cell in the seed—births and deaths happen simultaneously, and the discrete moment at which this happens is sometimes called a tick (in other words, each generation is a pure function of the one before). The rules continue to be applied repeatedly to create further generations.


--However, for our purposes, we will assign a size to the game "board": 2^k * 2^k . That is, the board should be easy to subdivide.

Notice that in this problem, at each step or "tick", each thread/process will need to share data with its neighborhood.
java
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class Life {
private static final int K = 4;
private static final int ITERATIONS = 10;

private static final boolean ALIVE = true;
private static final boolean DEAD = false;

private static final Board SEED = new Board(new boolean[][] {
{ DEAD, DEAD, DEAD, DEAD, DEAD, ALIVE, DEAD, ALIVE },
{ DEAD, ALIVE, ALIVE, DEAD, DEAD, DEAD, ALIVE, ALIVE },
{ DEAD, ALIVE, ALIVE, DEAD, DEAD, DEAD, ALIVE, DEAD },
{ DEAD, DEAD, DEAD, DEAD, ALIVE, DEAD, DEAD, DEAD },
{ DEAD, DEAD, DEAD, DEAD, ALIVE, ALIVE, DEAD, DEAD },
{ DEAD, DEAD, DEAD, DEAD, DEAD, ALIVE, ALIVE, ALIVE },
{ DEAD, DEAD, DEAD, DEAD, ALIVE, ALIVE, DEAD, DEAD },
{ DEAD, DEAD, DEAD, DEAD, ALIVE, DEAD, DEAD, DEAD } });

public static void main(String[] args) {
Life life = new Life(K, SEED);

System.out.println(life);

for (int i = 0; i < ITERATIONS; i++) {
life.tick();
System.out.println(life);
}
}

private final Board board, oldBoard;

public Life(int k, Board seed) {
int width = 1 << k;
int height = 1 << k;
board = new Board(width, height);
oldBoard = new Board(width, height);

seed.copyTo(board);
}

private void tick() {
board.copyTo(oldBoard);

ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

for (int y = 0; y < board.height; y++)
for (int x = 0; x < board.width; x++)
executor.execute(new Evaluator(x, y));

executor.shutdown();

try {
executor.awaitTermination(30, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

public Board getBoard() {
return board;
}

@Override
public String toString() {
return getBoard().toString();
}

private class Evaluator implements Runnable {
private final int x, y;

Evaluator(int x, int y) {
this.x = x;
this.y = y;
}

@Override
public void run() {
boolean state = DEAD;

int neighbors = oldBoard.countNeighbors(x, y);

switch (neighbors) {
case 2:
if (oldBoard.get(x, y) == DEAD)
break;
case 3:
state = ALIVE;
}

board.set(x, y, state);
}
}

public static class Board {
private final boolean[][] data;
private final int width, height;

public Board(boolean[][] data) {
this.data = data;
height = data.length;
width = data[0].length;
}

public Board(int width, int height) {
this.width = width;
this.height = height;
data = new boolean[height][width];
clear();
}

public void clear() {
for (int y = 0; y < height; y++)
for (int x = 0; x < width; x++)
set(x, y, DEAD);
}

public void copyTo(Board target) {
int yo = (target.height - height) / 2;
int xo = (target.width - width) / 2;

for (int y = 0; y < height; y++)
for (int x = 0; x < width; x++) {
int dx = x + xo;
int dy = y + yo;

if (0 <= dx && dx < target.width && 0 <= dy && dy < target.height)
target.set(dx, dy, get(x, y));
}
}

public void set(int x, int y, boolean state) {
data[y][x] = state;
}

public boolean get(int x, int y) {
return data[y][x];
}

public int countNeighbors(int x, int y) {
int count = 0;

for (int y1 = Math.max(y - 1, 0), y2 = Math.min(y + 1, height - 1); y1 <= y2; y1++)
for (int x1 = Math.max(x - 1, 0), x2 = Math.min(x + 1, width - 1); x1 <= x2; x1++)
if (((y1 != y) || (x1 != x)) && get(x1, y1) == ALIVE)
count++;

return count;
}

@Override
public String toString() {
StringBuilder sb = new StringBuilder();

for (int x = 0; x < width + 2; x++)
sb.append('#');

sb.append('\n');

for (int y = 0; y < height; y++) {
sb.append('#');

for (int x = 0; x < width; x++)
sb.append(get(x, y) == ALIVE ? '*' : ' ');

sb.append("#\n");
}

for (int x = 0; x < width + 2; x++)
sb.append('#');

return sb.toString();
}

public int getWidth() {
return width;
}

public int getHeight() {
return height;
}
}
}

Create a multithreaded "Hello World"

Create a program which outputs the string "Hello World" to the console, multiple times, using separate threads or processes.

Example:

-Output-

Thread one says Hello World!
Thread two says Hello World!
Thread four says Hello World!
Thread three says Hello World!

-Notice that the threads can print in any order.
java
for (int i = 0; i < 4; i++) {
final int nr = i ;
new Thread(new Runnable() {
public void run() {
System.out.println("Thread " + new String[] { "one", "two", "three", "four" }[nr] + " says Hello World!");
}
}).start();
}

Create read/write lock on a shared resource.

Create multiple threads or processes who are either readers or writers. There should be more readers then writers.

(From Wikipedia):

Multiple readers can read the data in parallel but an exclusive lock is needed while writing the data. When a writer is writing the data, readers will be blocked until the writer is finished writing.

Example:

-Output-

Thread one says that the value is 8.
Thread three says that the value is 8.
Thread two is taking the lock.
Thread four tried to read the value, but could not.
Thread five tried to write to the value, but could not.
Thread two is changing the value to 9.
Thread two is releasing the lock.
Thread four says that the value is 9.
...

--Notice that when a needed resource is locked, a thread can set a timer and try again in the future, or wait to be notified that the resource is no longer locked.
java
public class ParallelPermutations {

Lock lock = new ReentrantLock();

Integer value = 8;

public static void main(String[] args) {
new ParallelPermutations(Arrays.asList(args));
}

public ParallelPermutations(List<String> words) {
for (int i = 0; i < 20; i++) {
final Integer cnt = i ;
if ( i % 3 == 0) {
new Thread(new Runnable() {
public void run() {
if ( ! lock.tryLock() ) {
System.out.println("Thread " + cnt + " tried to write the value, but could not.") ;
lock.lock();
}
value = (int) (Math.random() * 10);
System.out.println("Thread " + cnt + " is changing the value to " + value ) ;
lock.unlock();
System.out.println("Thread " + cnt + " is releasing the lock.") ;
}
}).start();
} else {
new Thread(new Runnable() {
public void run() {
if ( ! lock.tryLock() ) {
System.out.println("Thread " + cnt + " tried to read the value, but could not.") ;
lock.lock() ;
}
System.out.println("Thread " + cnt + " says that the value is " + value + ".") ;
lock.unlock();
}
}).start();
}
}
}
}

Separate user interaction and computation.

Allow your program to accept user interaction while conducting a long running computation.

Example:

Hello user! Please input a string to permute: (input thread)
abcdef
Passing on abcdef... (input thread)
Please input another string to permute: (input thread)
lol
Passing on lol... (input thread)
Done Work On abcdef! (worker thread)
["abcdef", "abcefd", ... ] (worker thread)
Please input another string to permute: (input thread)
EXIT
Quitting, I'll let my worker thread know... (input thread)
We'
re quitting! Alright! (worker thread)

--Notice, that this could be accomplished on the command line or within a GUI. The point is that computation and user interaction should take place on separate threads of control.
java
public class BackgroundComputation {

final protected Queue<Thread> threads = new ConcurrentLinkedQueue<Thread>() ;

public BackgroundComputation() {
BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
try {
while (true) {
System.out.print("Enter string to permutate: ");
final String word = r.readLine();
if ("EXIT".equals(word) ) {
System.out.println("I'll let my worker thread know... (input thread)") ;
while (! threads.isEmpty())
threads.poll().stop(new ThreadDeath()) ;
break ;
}
Thread t = new Thread(new Runnable() {
public void run() {
try {
Set<String> permutationSet = new HashSet<String>();
for (int i = 0; i < word.length(); i++)
for (int j = i + 1; j <= word.length(); j++)
permutations("", word.substring(i, j), permutationSet);
System.out.println();
System.out.println("Received results: " + permutationSet);
System.out.print("Enter string to permutate: ");
} catch (ThreadDeath e) {
System.out.println("We're quitting! Alright!");
}
}

private void permutations(String prefix, String word, Set<String> permutations) {
int N = word.length();
if (N == 0)
permutations.add(prefix);
else
for (int i = 0; i < N; i++)
permutations(
prefix + word.charAt(i),
word.substring(0, i) + word.substring(i + 1, N),
permutations
);
}
});
t.start();
threads.add(t);
}
} catch (IOException ioe) {
System.out.println("IO error trying to read your name!");
System.exit(1);
}
}


public static void main(String[] args) {
new BackgroundComputation() ;
}
}