Monday, March 16, 2009

Shuffling numbers

One of the tiresome things about computers in general is the difficulty they have with recognising numbers. If you say to a child "add two and two" they will add the two numbers and give you four. If you say to the child "write two and two" they will write the string "two and two" or "2+2". If you subsequently asked them to solve, they will convert the string back to an equation and give you four again.

My first instinct after writing code which successfully shuffles strings was to extract numbers from them. Java has various methods for converting strings to numbers. A problem with all of them in my experience is that they are fussy about the string you pass to them for conversion. Accidentally appending non-numeric characters, like commas or brackets, usually generates exceptions. Coding to handle these exceptions is fraught with problems and messy.

After much thought I decided that rather than shuffling strings and converting them to number I would be better shuffling numbers, or more specifically number arrays. My code then became:

import java.util.*;

public class itemlist {
public static void main(String[] args) {
Integer[][] items = {{1,5,6},{5,2,7},{1,1,2}};
List<Integer[]> list = Arrays.asList(items);
Collections.shuffle(list);
System.out.println("First item: " + items[0][0]
+ " + " + items[0][1] + " = ");
System.out.println("Answer: " + items[0][2]);
}
}

It took a lot of fiddling to get this, not least because I didn't know how to assign the list type. Integer didn't work, Array didn't work, but Integer Array, written as Integer[], did.

Now I'll have to weave this into my app, and eventually perhaps post something on my web.

No comments: