I like to use zsh as my shell, but that’s easy enough to install via apt-get and so can be added to an automated build script. The fastest way to get a good configuration installed is via Oh My Zsh!, it uses the fairly horrible curl | sh
installation style, so I don’t like to add it to an automated script, but it’s easy enough to check and run manually:
$ curl -L http://install.ohmyz.sh | sh
The other thing is to get a decent vim setup, for this I use SPF-13 which installs in a similar manner:
$ curl http://j.mp/spf13-vim3 -L -o - | sh
Then I usually set up a couple of aliases based on what the machine will be used for, and I’m done.
]]>Probably the most common means of solving this kind of probability problem is the Monte Carlo method, which uses randomization and statistical sampling to estimate probabilities. Luckiy for me, the problem space for Bingo is small enough that it is possible completely analyze the game and present exact numbers.
The individual functions are all pretty short so I’ll walk through the maths and code at the same time.
Now, some of the numbers are going to get pretty big so primitive math won’t cut it. I’m going to define a few helper functions to make working with arbitrary-precision maths easier. I’m also gong to specify a limited precision context to use for division operations, as I’d rather lose a small amount of precision that get an ArithmeticException
if we hit any irrational numbers.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
|
To show how these work let’s define a factorial function, which is need in a moment anyway.
1 2 3 4 5 6 7 |
|
We’re also going to need a combination function, which will return the number of distinct combinations of k values drawn from a set S. Formally this is known as the binomial coefficient and is described by:
\begin{equation} c(S,k) = {S! \over k!\space (S - k)!} \label{combine} \end{equation}
The code that implements this is pretty much a literal translation of the equation, with a little data conversion and a shortcut for the case where we want to select no items or the entire set.
1 2 3 4 5 6 7 |
|
There are faster algorithms than this, but this is easy to understand and sufficient for our needs.
A Bingo board is comprised of a set of squares S, each with a number n chosen at random from the set N. Typically S comprises a 5x5 grid and N is the set of integers from 1 to 75. As an added wrinkle the centre square in the grid is a free space which is always assumed to be hit, this means that a 5x5 grid is actually a 24 element set.
To keep things simple I’m going to assume that we are using a typical board and number set, so I’ll just use constants to hold the cardinalities (sizes) of the two sets.
1 2 |
|
The first thing we need to figure out is the cumulative probabity of winning after n numbers have been called (i.e. the probability of winning when the 4th number is called, when the 5th number is called, and so on). This can be found by looking at the probability of there being 4 hits and those 4 forming a Bingo, plus the probability of there being 5 hits and those 5 forming a Bingo, and so on up to the number of calls made so far. Note that we start at 4 as this is the minimum number of calls needed for a Bingo.
Assuming that we have a function p(n) which returns the probability of there being a Bingo when there are n hits, the cumulative probability of winning after n calls is given by:
\begin{equation} w(n) = \sum _ {i=4}^n {c(|S|, i)\space c(|N| - |S|, n - i) \over c(|N|, n)} p(i) \label{cumulative} \end{equation}
Substituting in the values for the sizes of the board and number set simplifies this to:
\begin{equation} w(n) = \sum _ {i=4}^n {c(24, i)\space c(51, n - i) \over c(75, n)} p(i) \label{cumulative-simple} \end{equation}
But we still need to define p(n), this is where the small problem space comes in handy…
The probability of a Bingo given n hits on the board is the number of possible Bingo positions divided by the total number of positions, so before we can work out the probability we need to get the number of Bingo positions for each hit count.
As I mentioned earlier will use a brute force method of calculating the probability of a Bingo given n hits on the board. To do this we first need to come up with a representation of a board, as it only takes a single bit to represent the state of each square and there are only 24 squares, we can just use an int for this.
Here’s how we do that: number the squares from 0–23 left-to-right and top-to-bottom like so (FS represents the free space in the centre):
0 | 1 | 2 | 3 | 4 |
---|---|---|---|---|
5 | 6 | 7 | 8 | 9 |
10 | 11 | FS | 12 | 13 |
14 | 15 | 16 | 17 | 18 |
19 | 20 | 21 | 22 | 23 |
Then starting from the least significant bit we can use a 1 to represent a hit square and a 0 to represent an empty square. So a Bingo across the top row, with all other squares being empty is represented by 0b111110000000000000000000
; this and the remaining 11 possible Bingo positions (5 rows, 5 columns, and the 2 diagonals) can be represented like so:
1 2 3 4 5 6 7 8 |
|
To create the array of Bingo combinations (indexed by number of hits, so a 25 element array) we will just loop through every possible board layout (i.e. the integers 0 through 0b11111111111111111111111
) and check each of them against the list of Bingo positions, if there is a match we can use the Integer.bitCount()
method to count the number of hits on the board and then increment the counter there. The full code for this is:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
Given this we can now calculate the probability of a Bingo at each hit count as described above, the code for this is:
1 2 3 4 5 6 7 8 9 10 11 12 |
|
The last thing we need before moving on to calculate the actual chances of winning is a function to determine the probability of there being k hits hits on the board after n numbers have been called (the bit in equation \eqref{cumulative} that is being multiplied by p(n) and then summed). It’s just a literal translation of the equation:
1 2 3 4 |
|
We’ve now got everything we need to write the code for equation \eqref{cumulative}, given the previous function and the pre-computed array of proabilities the code to do this is simple:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
This is fine for a single board, but what about the odds for a real game, with many players? The odds of finding a winner when there are k boards is given by:
\begin{equation} m(n,k) = 1 - (1 - w(n))^k \label{many} \end{equation}
Armed with this we can implement a function to return the probability of a winning board for any number of boards and numbers called like so:
1 2 3 4 5 6 |
|
And that’s everything! All that’s left to add is a main method to print out some stats and that’s it.
1 2 3 4 5 |
|
If you want to play with this some more, an interesting excercise would be to generalize this for any size of board and token (number) set. To do that you’ll need to get rid of the static BINGOS
array and calculate id dynamically, based on the size of the square, other than that and a coupl of constants that need to be replaced by variables everything else should work as is.
The full code, including the implementations of the print methods can be found on GitHub.
]]>I’ve got solutions to the first couple of problems ready to go, and all of my solutions can be found in this project on GitHub.
This is trivial to implement in Java using the built in Console
class, the complete implementation (sans class boilerplace and imports) is:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
|
Compared with other solutions the only interesting things are the use of BigDecimal
instead of primitive types, this means that the calculator supports a wider range of numbers and input formats, and the use of a Deque
as the stack, this is a more modern class than the old Java 1.0 vintage Stack
class.
The full class is here.
This classic algotrithm is a bit more interesting: my first thought was to lazily create the list of primes using modulo checks to filter out non-prime numbers. Technically this isn’t the Sieve of Eratosthenes, but it’s logically the same. Well, it performed terribly taking several seconds to compute the first million primes.
It turns out that one of the reasons the actual sieve is so fast is that it only uses addition rather than the more expensive modulo operations. This, plus the memory saving gained from using a BitSet
instead of a list of Integer
s gave me a nice, zippy, implementation. The relevant method is:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
And of course in a real implementation this would be a good candidate for memoization giving you O(1) performance in the common case.
The full class is here.
]]>The post isn’t bad, but I think that Marcin is getting the builder and factory patterns a little mixed up. To recap:
The intent of the Builder Pattern is to separate out the construction of an object from it’s final representation. Doing this makes it easier to enforce preconditions and invariants, and also makes the object construction easier to read in languages without keyword arguments.
The intent of the Factory Pattern on the other hand, is to delegate responsibility for creating an object to somebody else. It is commonly used in dependency injection frameworks.
A concrete example should serve to illustrate the differences.
Assume that we have an interface for a simple Pojo:
1 2 3 4 5 6 7 |
|
and a default implementation (shown here as a separae class, but it could also be a static inner class in the interface):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
|
Even with just a few fields like this invoking the constructor becomes somewhat ugly:
1 2 |
|
Without referring to the docs or source code how do you know what all of those strings mean? How do you know that you have them in the correct order? And if it seems reasonable clear in this example imaging if your Pojo was mainly non-string data!
1
|
|
Clear as mud, right?
Other languages don’t have this problem, for example in Objective-C we would write something like:
1 2 |
|
which is much clearer. Ruby, Python, and other languages all have similar constructs. Adding a builder allows us to gain the same level of clarity in Java, and it provides a good place for us to perform any additional checks before creating the object. Here’s a typical implementation and an example of calling it:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
|
Again, all pretty clear now, and HotSpot will inline all of those method calls no there should be no additional overhead once the JVM is up and running.
Factories are different, but it would be common for a factory to use a builder to create the objects that it vends. For example, here is a factory for employee objects (it doesn’t need to have the word Factory in it’s name):
1 2 3 4 |
|
We can then have different implementations of this, maybe one that loads data from a CSV or JSON file for testing purposes, and one that loads data via JDBC for production use.
Aside: if you’re familiar with domain-driven design you’ll be forgiven for noticing a lot of overlap between the factory pattern and DDD’s concept of repositories, they’re very similar concepts. One difference being that factories are often able to create new objects ex nihilo while repositories usually retreive objects from external sources. Compare the findById()
method with the newInstance()
methods employed by many of the factory classes in the JDK.
Hopefully you can see from this post that the two patterns have different—if complementary—aims.
A complete example project with all of this code, as well as test cases and a CSV based implementation the the factory are available on Github.
]]>Despite my excesses, my appetite and my love of life, I remain a free man
Well said sir, well said indeed!
]]>]]>I don’t have a problem with being searched at all – in fact, if you guys think it’s necessary, I’d be the first to admit that I look a little bit suspicious before I’ve had my first cup of coffee in the morning – but if you’re going to stroke me gently in front of hundreds of people, you’d better buy me a fucking drink first, is all I am saying.
Not only is this a profound increase in responsibility for all three of these top executives, it’s a profound change in Apple’s organization going as far back as I can remember. There’s a long-standing pattern of separating watershed products important to the company’s future. The Mac and Apple teams. Mac OS X and Classic. The iPod division. iOS and Mac OS X. Suddenly, Tim Cook has pulled the reins in. Federighi owns software. Ive owns design. Cue owns services. Period.
While it looks like this is something that asn’t exactly planned in advance, it seems like some people at Apple have been hoping for it for a while now. According to Om Malik:
Forstall’s firing was met with a sense of quiet jubilation, especially among people who worked in the engineering groups.
For my part, I’m mainly interested in seeing what happens to the UI now that Jony Ive is in charge of it, hopefully the misguided move towards skeuomorphic interfaces will be taken out back and shot.
]]>VLC media player 2.0.4
This is a major update that fixes a lot of regressions of the 2.0.x branch of VLC.
We are introducing an important number of fixes and improvements for all playback, notably for Blu-Ray, DVD, HLS, Ogg and MKV files; but also for Youtube, Vimeo, Koreus and Soundcloud.
New support for the OPUS audio codec, including multichannel and streams. …
How the fuck is going from 2.0.3 to 2.0.4 the correct version bump for a major upgrade?
Jeez…
]]>1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
|
Just add this to the end of your OctoPress Rakefile and you’re good to go.
]]>There are a number of options out there, including:
JSR-296 is basically dead in the water at this point, and while there are a few forks doing the rounds I’m not really confident enough in any of them to want to move a reasonably sized codebase to it.
Eclipse uses a different UI toolkit altogether so it’s really a nonpstarter for this excercise, although it would be a good option if starting a new project from scratch.
Jide is a swing component vendor and a relatively new entrant into the RCP space. JDAF has some things going for it: it has the best platform integration of any framework, with much better native fidelity (e.g. message dialogs look OK on Mac OS X and Gnome) than either Eclipse or NetBeans. It also has some handy built-in support for document-centric apps. The downsides are that unlike the other offerings here it’s a commercial product, and it’s much less ambitious in scope than either Eclipse or NetBeans, presumably as many of the other features that these offer are also Jide products (e.g. their docking framework). I also found myself fighting to work with it’s limited data model support.
NetBeans seems to e a good fit for the apps that I’m converting, and it plays well with standard Swing idioms so it should be quite easy to port the code over. Recent releases have extensive support for annotation based configuration as well, which should ease the learning curve.
One downside is that most of the tutorials and documentation assume that you will also be using NetBeans as an IDE, which I won’t be (I use IntelliJ), still, NetBeans RCP has pretty good Maven support so it shouldn’t matter too much.
Here’s how to create a project and add a module to it:
You can then open this up in IntelliJ as a Maven based project and start editing away.
Adding additional modules (e.g. myviews, &c.) is as simple as rerunning the last command and re-importing the maven model (or enabling auto-import in IntelliJ).
]]>Wow, that really is a lot of packaging for probably the world’s smallest connector. Also, reading the post about it, was anybody else reminded of this?
]]>This looks like a fascinating piece of technology provided it works as advertised. Check out the video on their, it looks pretty slick.
The company behind it make some pretty bold claims about the technology:
Just about the size of a flash drive, the Leap can distinguish your individual fingers and track your movements down to a 1/100th of a millimeter. … Setup is just as intuitive. Plug the LEAP into a USB port. Load the Leap Motion software. Do a quick wave to calibrate. That’s it.
Of course if you were to use it as a main input device I expect that you’d get tired pretty quickly, but for short sprints of use in specialist applications it looks neat.
And I’d love to see it paired with one the new sets of VR displays that are hitting the market right now.
]]>Good design. From eBay. Think about that.
Beautiful turn of phrase from John Gruber over at Daring Fireball.
Posted as part of my new effort to improve my writing.
]]>So, all of the cool kids have been talking about Laurent Sansonetti’s next project: RubyMotion, a port of MacRuby targeted at iOS. On the whole I’m pretty impressed with what you can already do with it. One of the issues that people having been mentioning though, is that you lose the ability to use Interface Builder with it, but this isn’t actually true!
Here I’m going to show you how to work with Interface Builder, I’ll base the project off the one used in the Pragmatic Studio screencast (the icon and background images come from there as well, by the way).
Update: the images don’t dome from there any more! The images used in the screencast are from iStockPhoto, so I’ve replaced the background image with a different one. Needless to say this doesn;t affect any of the code.
All of the code for this project can be found on GitHub.
Start off as normal: motion create MagicBallDemo
. In the project folder create a new subfolder called interfaces, this is where all of the .xib
files will be saved.
Next create a model class called MagicBall
and a view controller called MagicViewController
which extends UIViewController
, also create a file to store some small helper methods called helpers.rb
. Don’t worry about the contents of these files for now, I’ll come back to them, but you should have the following:
1 2 3 4 5 6 |
|
The next thing to do is create the UI using interface builder.
Open Xcode and hit ⌘-N to create a new file, select the Empty template and save the file into the folder you just created. Now add a View Controller
from the object library and set the custom class to MagicViewController
; you can’t edit this field directly but you can paste into it, so select the class name from app/magic_view_controller.rb
.
The next step is to add the view to it’s controller, normally this would just mean dragging a UIImageView
on top of the controller but that won’t work here. There is a problem with interface builder in that you can’t add subviews to UIImageView
s, which is a pain in the ass. A simple workaround is described in this Stack Overflow question, and that’s what we’ll do here. So, add a UIView
to the view controller and set it’s custom class to be UIImageView
(which should be available in the pick-list). You can’t set the image here, that will need to be done in code.
Finally add the label and configure it as desired. Save your changes and close XCode.
You can compile this into a .nib
using ibtool
, this script will compile all of the interfaces in your project (just one in this case):
1 2 3 4 5 |
|
Update: as of RubyMotion 1.3 this happens automatically, no need to compile your nibs by hand and more!
The first thing we need to do is make sure our app delegate loads the interface from the nib that we’ve created, and we set our @window
ivar from the loaded nib.
1 2 3 4 5 6 7 |
|
The nib loading process will create an instance of our view controllor for us, but we need to wire up a few connections add add some behaviour, here’s a simplified version of the code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|
I know that there is only 1 subview so it’s easy to grab a reference to the label and store it in an ivar, a more realisic example could select
the label based on a tag.
As mentioned above, I need to explicitly set the image and this happens here as well.
Finally, set up the gesture recognizer. This is one place that Ruby shines, it’s trivial for us to add helper methods like this, have a look in app/helpers.rb
for the code that enabled this.
It’s a good idea to add resources/*.nib
to the .gitignore
file as compiled resources don;t need to be committed to Git. I also add doc/app
then I can use rocco to generate some documentation.
Take a look at the full project on GitHub and let me know what you think!
Update: clarified the wording around adding the UIImageView
.
Apple’s approach to security in general is a bit worrying: one the one hand they seem to have the right approach to securing the OS with App Store entitlements (although these aren’t without issues) and Gatekeeper, but their timeliness in shipping security fixes leaves a lot to be desired. Note from the article that this flaw was pointed out to them 3 months ago!
]]>source/_posts
folder through the following one-liner:
1 2 3 4 5 |
|
Here’s what each line does:
Maybe this will be useful to somebody out there…
Update: I’ve written a version that’s integrated with rake as well.
]]>