The White Blog A blog for technology, life, and food Fri, 19 May 2017 11:49:24 +0000 en-US hourly 1 Solving Sudoku With a Functional Language Sun, 17 Nov 2013 02:52:54 +0000 Solving Sudoku puzzles is usually considered a basic computer solving problem. While the task is not trivial there are a few complexities that have to be addressed. In this post I wanted to explore my first, and probably crude, attempt to solve the problem functionally using Mathematica. It should be noted that I am new to both Mathematica and functional languages in general. Also, my syntax highlighting doesn’t support Mathematica’s language.

First, let’s define the problem space as a 9×9 grid of digits but lets index them using a four coordinate system using [puzzle-row, puzzle-col, cell-row, cell-col]. So, a coordinate of [1,2,1,1] would mean the top-center grid and the top-left most cell in that grid. With that we can define all possible coordinates as…

allCoordinates = Tuples[Array[Range@3 &, 4]];

Next define all “related” coordinates. By this I mean all coordinates affected by the value in a particular cell. So, all cells in the same sub puzzle plus any along the target row or column; note the use of “memoization” for performance…

relatedCoordinates[{pr_, pc_, cr_, cc_}] := 
 relatedCoordinates[{pr, pc, cr, cc}] =
  Level[#, {-2}] &@({{pr, pc, #1, #2}, {pr, #1, cr, #2}, {#1, pc, #2, 
        cc}} & @@@ Tuples[Array[Range@3 &, 2]])

I approached this problem by taking a blank puzzle and applying my test puzzle to it one cell at a time. I define a cell as having two possible type of values: lists of possible values, or a single assigned value. Therefor a blank puzzle is nothing but a set of cells containing all possible digits…

blankPuzzle[{pr_, pc_, cr_, cc_}] := Range[9];

Now for the functional magic. Handling state has been a challenge to me but this solution seems elegant. The applyValue method simply takes a function that reads a puzzle, along with a coordinate and a new value to assign. From that it creates a new function that mostly just refers to the passed in function for values, but with two key differences. First, the coordinate passed in is “hard wired” to the new value. Second, all “related coordinates” that are lists have the passed in value removed from their list of possible values…

applyValue[p_, {c_, 0}] := p;
applyValue[p_, {c_, v_}] := Module[{f},
   f[t_] := p[t];
   f[c] = v;
   (f[#] = Select[ p[#], # != v &]) & /@ 
    Select[relatedCoordinates[c], (Head[p[#]] == List && # != c) &];

Now the process is fairly simple. First, take a blank puzzle and apply all known values recursively. Note that 0’s don’t get applied in the above applyValue logic. In this case 0 simply represents a blank cell…

primePuzzle[p_] := Module[{},
    blankPuzzle, {#, p[[Sequence @@ #]]} & /@ allCoordinates]

Finally, the solve puzzle method is rather similar to the procedural solution. First, if there are no unknowns then the puzzle is solved. Next, find any unknowns and attempt solve the cell with the least set of possibilities. If any cell has no possible values then of no solutions are found by substitution, backtrack and try again…

solvePuzzle[p_] := 
  Module[{unknowns = 
     Select[#, Head[Last[#]] == List &] &@({#, p[#]} & /@ 
        allCoordinates), target, solutions},
   If[Length[unknowns] == 0, Return[p]];
   target = unknowns[[First[Ordering[Length[Last[#]] & /@ unknowns]]]];
   If[Length[Last@target] == 0, Return[Null]];
   solutions = 
    Select[solvePuzzle[applyValue[p, {First@target, #}]] & /@ 
      Last@target, ! (# === Null) &, 1];
   If[Length[solutions] == 1, First[solutions], Null]

Solving a puzzle is then simply…

Remembering Merlin Sun, 10 Mar 2013 02:17:14 +0000 The loss of a pet is one of the most difficult topics for me to write about. Yet, I feel it is necessary to help capture the memory. Merlin certainly deserves at least that much. There is so much worth remembering. Certainly more than I can fit into a single post.

Merlin was a rescue kitten that was supposed to stay around until he got better. The running joke is that he never did get better since he stayed around anyway. His sneezing fits where certainly something to see. Later we discovered Merlin also had asthma and needed a daily inhaler.  Most people can’t imagine giving a cat an inhaler, but he took it very well.

Merlin had a pretty unique personality, but he was still a cat. I think it took him a while to figure that out though. Not many kittens will chase a dog around the house. At some point, the idea of being a cat settle in and he acquired an obsession with cat nip and cardboard boxes. He even went as far as creating hidden stashes of his favorite Nepeta.

A friend of our described the loss the best when he said “[we] had a loss in the family.”  Merlin was part of our daily routine.  Just like with the loss of Rose, this loss left a large gap in our lives. Merlin was well loved cat and we will never forget him. You will be missed Merlin.

[See image gallery at]

Returning and Accepting Interfaces with CXF/JAX-WS Sun, 03 Jun 2012 00:35:16 +0000 JAXB doesn’t support interfaces directly, plain and simple. Why? Interfaces are method level contracts and JAXB is designed around data level contracts. The most common source for working around these limitations is documented on the Unofficial JAXB Guide. While these techniques work most of time, they fail to cover certain edge cases in CXF with JAX-WS.

In short I recommend a combination of two tricks: use of an XmlAdapter and setting the jaxb.additionalContextClasses property. The second half of this post points out pitfalls and problems I ran into along with some general advice.

The XmlAdapter Trick

If you have an interface that is only implemented by one class, you can use the XmlAdapter as outlined in the Unofficial Guide with one exception. I do NOT recommend using the AnyTypeAdapter that comes with JAXB (see pitfalls section for more on why).

Here is the GenericAdapter class I use.

public class GenericAdapter<ValueType, BoundType> extends XmlAdapter{
    public BoundType unmarshal(ValueType valueType) throws Exception {
        return (BoundType) valueType;

    public ValueType marshal(BoundType boundType) throws Exception {
        return (ValueType) boundType;

To use this adapter correctly, create a public static inner class in the implementation that extends the GenericAdapter and provides the appropriate generic types. Then point the interface’s @XmlTypeAdapter to the static inner adapter.

Add Classes to the ‘jaxb.additionalContextClasses’ Property

If you are using Spring  then you need to setup your server like so, noting the properties tag…

    <jaxws:server id="myServiceId"
            <entry key="jaxb.additionalContextClasses">
                <bean class="com.mycompany.ServiceImpl.ClassArrayFactoryBean">
                    <property name="classNames">

I also needed to build a ClassArrayFactoryBean since one didn’t seem to be shipped by default…

public class ClassArrayFactoryBean implements FactoryBean<Object> {

    private List<String> classNames;

    public Object getObject() throws Exception {

        final Class<?>[] classes = new Class<?>[classNames.size()];
        for (int i = 0; i < classNames.size(); i++) {
            classes[i] = Class.forName(classNames.get(i));
        return classes;

    public Class<?> getObjectType() {
        return Class[].class;

    public boolean isSingleton() {
        return true;

    public List<String> getClassNames() {
        return classNames;

    public void setClassNames(List<String> classNames) {
        this.classNames = classNames;

You may be able to get away with creating a jaxb.index file but I never did get this to work as expected.

Avoid Interfaces on @WebService Classes

One could argue pretty strongly that the WSDL provides the interface contract and that your web service class need not worry about interface contracts at the Java level. In many cases an abstract class can provide the one-to-many polymorphic design needed without having to jump through hoops to make JAXB work with interfaces.

Pitfalls and Traps

This is a collections of things I tried and they failed at the time. These techniques may work just fine with newer versions of CXF and JAXB or under difference conditions. Your mileage may very.

  • Using the AnyTypeAdapter caused CXF to generate a WSDL that accepted an xs:anyType which got transformed into just a plain Object by WSDL2java on the client side.
  • Using @XmlSeeAlso never seems to do what I expected. In particular, it seems to always be ignored.
  • Do not expect JAXB annotations on the @WebService interface to work as you would normally. Most of those annotations are for giving JAXB directions on serializing the class that they are in, and you are not serializing your web service implementation.


You may be better off avoiding interfaces on the actual web service interface and implementation. If you must use them then be aware that it’s tricky to get right and I hope the notes above are of some use.

LEGO Dice Tower Wed, 30 May 2012 01:20:12 +0000 I play lots of board games. Some of these games are quite complex and have very large and intricate setups with lots of dice. One of the more frustrating side effects of these games is trying roll dice without disrupting the game pieces. So, I built a dice tower.

The tower is mostly made from pieces from the Harry Potter Hogwart’s Castle.  It uses three main tumblers and a series of smaller tumblers to ensure randomness. The bottom tray detaches and can be mounted to the front for portability.  The design is simple and meant to be aesthetically pleasing while still functional. I have been fairly impressed with its performance, and so I thought I would share the concept. Enjoy.

Truthfulness of the 2012 Presidential Political Candidates Sat, 31 Mar 2012 19:26:37 +0000

I recently became interested in certain claims made by politicians and their perception among the public. In particular, I want to know how trustworthy a candidate is. Furthermore, I want to be able to back up or refute claims made by people about one candidate being more “honest” or “trustworthy”.

Methods and Bias

My methods are simple. I compiled statistics based on each candidate from PolitiFact and graphed the results below while also calculating a Trustworthiness Grade Point Average (TGPA). The pie chart is a simple breakdown of each category that Politfact assigned to a particular statement. The TGPA is a simple weighted average of each statement on a standard academic 4.0 scale system where “true” was assigned a value of 4.0 and “Pants On Fire” got a 0.0 and all other values where equally distributed in the range [0.0-4.0].

There is also the chance of bias from PolitiFact. For that I refer you to the PolitiFact Bias Blog where you can form your own opinion. This data also represents a rather small sample size, in particular for Ron Paul who does not receive nearly as much press coverage as other candidates. It should also be noted that PolitiFact does not rate every statement but rather statements that can be fact checked and that have some “boldness” or public interest. Therefore, I wouldn’t use this as a measurement of their personal character but rather how well they present themselves relative to known or verifiable facts in a political landscape.

Ron Paul TPGA 2.33 (C+)

Mitt Romney TPGA 2.21 (C+)

Rick Santorum TPGA 1.89 (C-)

Newt Gingrich TPGA 1.73 (C-)

Barack Obama TPGA 2.58 (B-)


Being a Ron Paul supporter, I was not too surprised to see he ranked among the top of the field. Newt’s record was anticipated, but I did expect Romney and Satorum to be reversed. Obama’s record was not what I predicted until I realized that he doesn’t make bold claims of fact as much as bold promises. In particular, Obama seems very good at avoiding outlandish remarks that would earn him a “Pants On Fire” ruling. Overall I was disappointed that the best republican rating was a C+ and best overall was a B-.

Slider Solver for Klotski Puzzles Sat, 03 Mar 2012 03:05:16 +0000

I hate slider puzzles aka Klotski puzzles. The key move is usually a subtle block placement nested halfway between the starting setup and the ending solution. Since even the more basic puzzles require a minimum of 20+ moves to solve, I end up using trial and error which inevitably results in me repeating positions several times before frustration sets in.

Solving one puzzle is nice, but if I can solve every puzzle then I feel like I have truly conquered the problem. As such, I wrote a small Java command line application that can solve most compact sliders quickly.  It uses a breadth first searching algorithm to find the shortest solution assuming moving one block one space counts as a move.

Using the solver

Warning, this is more of a developer/geek friendly application. Download and unzip either the .zip or .tar.gz files from below. The program is meant to be run from the command line so jump to the console. Change directories to where you extracted the download and then you can run…

$bin/SliderSolver /path/to/puzzle /path/to/goal

See the download section for example puzzles, goals, and outputs. When creating the puzzle and goal files note that the only reserved character is the ‘#’ which is the wall symbol. There is very little error checking so be sure the puzzle is enclosed and “small”. At some point I might wrap this in a GUI but for now it is just a self exercise in solving a puzzle.

How it works

The algorithm is pretty straight forward:

  1. Read puzzle and goal files
  2. Generate shape equivalence mappings
  3. Try possible moves and store the current puzzle state if we have not seen the state before
  4. If the state matches the goal then print the solution else go to step 3

The only complex part is generating shape equivalence. In practice, this optimization reduces the memory needed and time required by a factor equal to the number of duplicate shapes in the puzzle. Without this trick the original Klostki puzzle will consume over 4GB of RAM and take several hours to solve. With the optimization, the puzzle can be solved in under a minute with under 2GB of RAM.

Below is a snip of the core solve method which uses a breadth first algorithm to find solutions.

public Solution solve() {
    Queue<StateNode> nextStates = new ArrayDeque<StateNode>();
    Set<String>      seenStates = new HashSet<String>();

    nextStates.offer(new StateNode(new Puzzle(this.sourcePuzzle), ROOT_MOVE, NO_PARENT));

    while (!nextStates.isEmpty()) {
	final StateNode currentState = nextStates.poll();
	final String puzzleString = this.generateEquivalentPuzzleString(currentState.puzzle);

	if (seenStates.contains(puzzleString)) {

	if (this.targetGoal.matches(currentState.puzzle)) {
	    return this.buildSolution(currentState);

	this.offerNextStates(nextStates, currentState);

    return null;


This isn’t the most user friendly app but I never really intended to release it anyway. It could probably be future optimized by adding an AI that could do path trimming or algorithm selection based on certain puzzle metrics. Error handling and usability could certainly be improved on. I found the exercise to be a good refresher on performance aware Java application development and a good reminder that my algorithms class in college does still hold some use for me.


Slider Solver Source Code
Slider Solver Source Code
28.8 KiB

Slider Solver (zip)
Slider Solver (zip)
1.1 MiB

Slider Solver (tar.gz)
Slider Solver (tar.gz)
1.1 MiB

Klotski Puzzle
Klotski Puzzle
56.0 B

Klotski Goal
Klotski Goal
56.0 B

Klotski Solution
Klotski Solution
1.7 KiB

]]> 1
Pet Pictures Sun, 26 Feb 2012 15:43:00 +0000 I was recently reminded that I have not updated my pictures in a while and, in particular, my pet album was missing a few. So, for the friends and family readers, I give you Green, Yellow, and Orange the hermit crabs and some Faye pup pictures. Our other hermit crab, Red, is probably molting right now so we didn’t dig him up for a photo shoot.

LEGO iPad Stand Wed, 11 Jan 2012 02:30:06 +0000 I’ve always loved LEGOs and this year for Christmas I got The LEGO Ideas Book. It has an entire chapter dedicated to practical applications of LEGOs such as card and pen holders. I also got this handy portable Bluetooth keyboard but our iPad’s case lacks the stand that some have. So, until we get one, I decided to build one and here are the results…

From a structural standpoint, the stand is fairly sturdy. It is mostly made from parts of an old LEGO fort from the Pirate series. This  project was particularly interesting due to the engineering challenge of supporting and balancing the iPad’s weight while not shearing the bricks from their bases.

Unexpected empty JList model with IntelliJ’s GUI builder (Solved) Mon, 09 Jan 2012 13:15:07 +0000 When working with IntelliJ’s GUI builder it is possible for custom implantations of  JList to mysteriously be empty when using a custom model that was defined and set in the constructor. This can be very confusion and non trivial to track down. This can be caused by accidentally setting the model property in the GUI Builder. The solution is to right click and select “Restore Default Value.”

This appears to be an issue because IntelliJ’s GUI builder uses instrumentation to inject the component properties at runtime. Furthermore, this occurs after the constructor of the components are finished. So, in a custom JList implementation, great care must be taken not to override any properties in the GUI builder that are going to be defined in code.

Disable System Beeps for Non-KDE Applications (Eclipse) While Running KDE Sun, 27 Mar 2011 05:32:24 +0000 If you have tried everything to get those annoying system beeps in KDE to stop but can’t, here is something to try.

  1. Launch gnome-control-center
    1. Can be done by typing “gnome-control-center” in a console while in KDE
    2. Log in to a Gnome session and launch the Control Center
  2. Find the “Sound” item
  3. Click the “Mute” checkbox next to “Alert Volume”

I noticed this issue when I was running Ubuntu and I updated to Kubuntu and I was running some non-KDE apps such as Eclipse. I had tried everything else from setting the system bell to mute to setting the “Beep Channel” to 0%/Mute and updating various settings in the System Notifications configuration. Finally I concluding that certain applications must still be pulling configurations from Gnome.

]]> 2