2011-04-11

Project Euler problem 158 - Solved

You can find the statement of this problem here.

As in many of the posts you can find here, the solution for this problem is using DP.

I used a top-down approach with memoization. The dp dictionary will be indexed by three things: length, number of numbers which are greater than the previous and the number of times that the a[i] < a[i+1].

The base cases are:

• (0, 0, 0) = 0: Meaning we finished choosing the strings but no a[i] < a[i+1] so its not valid.
• (0, 0, 1) = 1: Meaning we finished choosing the strings and there’s only one occurrence where a[i] < a[i+1] so its valid and there’s only one possibility.
• (,,2) = 0: Any case where there is more than one occurrence where a[i] > a[i+1] is not valid so 0 is returned.

In my python code I implemented a method get_num that receives the 3 indexes. It first checks if the result is in the dp dictionary, in that case returns the saved value; if the 3rd index is greater than 1 it returns 0. If none applies it calls recursively for each case that we could pick from, adds them all up and stores the value for not recalculating it.

It is important to notice that we don’t need to take the 26 possible characters to calculate the different number of ways of generating different strings of length x. We just calculate from the base that we have x characters and then multiply the result by the number of combinations we can take x from 26.

factorial = {0:1}
for i in range(1, 27):
factorial[i] = factorial[i-1] * i

dp = {
(0, 0, 0) : 0,
(0, 0, 1) : 1
}
def get_num(*args):
if args in dp:
return dp[args]

length, num_greater, count = args
if count > 1:
return 0
result = sum(get_num(length-1, i, count + ((i < num_greater) and 1 or 0)) for i in range(length))
dp[args] = result
return result

p = lambda n: sum(get_num(n-1, i, 0) for i in range(n)) * (factorial[26] // (factorial[n] * factorial[26 - n]))

if __name__ == '__main__':
max_pn, max_n = max((p(n), n) for n in range(2, 27))
print("The result is:", max_pn, "found at n:", max_n)


And the equivalent in Haskell problem158.hs:

import Data.Map
import Data.Maybe

factorial n = factorial' n 1
where
factorial' n res
| n < 2 = res
| n >= 2 = factorial' (n-1) (res * n)

comb x y = ((factorial x) div ((factorial y) * (factorial (x-y))))

getValue :: (Integer, Integer, Integer) -> Map (Integer, Integer, Integer) Integer -> (Integer, Map (Integer, Integer, Integer) Integer )
getValue (length, greater, count) dp
| count > 1 = (0, dp)
| member (length, greater, count) dp = (fromJust (Data.Map.lookup (length, greater, count) dp), dp)
| notMember (length, greater, count) dp = getValue' (length, greater, count) dp 0 0
where
getValue' (length, greater, count) dp i res
| i == length = (res, insert (length, greater, count) res dp)
| i < length = getValue' (length, greater, count) nDp (i+1) (res + nRes)
where
nCount = if i < greater then count+1 else count
(nRes, upDp) = getValue ((length -1), i, nCount) dp
nDp = insert ((length -1), i, nCount) nRes dp

p :: Integer -> Map (Integer, Integer, Integer) Integer -> (Integer, Map (Integer, Integer, Integer) Integer)
p n dp = p' 0 dp 0
where
p' x dp res
| x == n = (res * (comb 26 n), dp)
| x < n  = p' (x + 1) nDp (res + nRes)
where
(nRes, nDp) = getValue ((n-1), x, 0) dp

initialDp = fromList [((0,0,0), 0), ((0,0,1), 1)]

main = print ("The result is: " ++ (show (first (foldl f (0, initialDp) [1..26]))))
where
first (x, y) = x
f (r, dp) n =
let
(nRes, nDp) = p n dp
maxR = max r nRes
in
(maxR, nDp)


2011-03-27

I stumbled across this problem when I decided to switch completely to this fantastic window manager called Xmonad.

I use SSH a lot and I also use Ubuntu’s cloud service(UbuntuOne). I use public key logins in most of the hosts I SSH into, so in order not to unlock my key each time I wanted to SSH or SCP to another host I used the GNOME keyring to store the unlocked key. And UbuntuOne uses the keyring to store the password to use to login to the service.

When I started using Xmonad I lost the keyring and I was becoming mad. So I started searching on how I could enable it in my Xmonad session. I couldn’t find a definite guide so I investigated a little bit of how the keyring worked and I’m explaining here what to do in order to have the gnome keyring start after the login and having it fully functional with the ssh.

First of all you need to change the file in /usr/share/xsessions/xmonad.desktop in order to execute a script of ours instead of the xmonad. It will look like this:

[Desktop Entry]
Encoding=UTF-8
Comment=Lightweight tiling window manager
Type=XSession


Now we are going to have the script (with executable privileges) somewhere in the path, a correct place to have it is /usr/local/bin. So a simple /usr/local/bin/xmonad.start script would be:

#!/bin/bash

#most basic xmodmap stuff
xmodmap -e 'remove Lock = Caps_Lock'
xmodmap -e 'keysym Caps_Lock = Control_L'
xmodmap -e 'add Control = Control_L'
xmodmap -e 'keycode 166 = Hyper_R'
xmodmap -e 'add mod5 = Hyper_R'



Basically what this file does is mapping some keys and executing a script .xmonadrc in the home of the user. This is done in order to allow different users set different settings. In that script is where the magic will happen, but with that magic won’t be enough. Here’s what you have to include in that file in order to start the keyring. In my file I set up a trayer and launch some other programs.

eval $(gnome-keyring-daemon --start) export GNOME_KEYRING_SOCKET export GNOME_KEYRING_PID  Those three commands will launch the keyring daemon and set up the environmental variables needed to make it work. This will work perfectly with the stored passwords but ssh’s keyring overrides this gnome keyring and the unlocking of the ssh key won’t work (don’t know why yet). In order to correct this it is necessary to update the .profile in the home of your user. You need to append the following line: export SSH_AUTH_SOCK="$GNOME_KEYRING_CONTROL/ssh"


With that the ssh will use the keyring daemon and we are ready to use it for everything. Just restart gdm or re-log into the user.

Hope it was useful.

2011-03-22

Project Euler problem 329 - Solved

You can find the statement of this problem here.

The solution to this problem is really an easy one. It’s just straightforward dynamic programming.

The DP approach I used is top-down with memoization. The DP dictionary will be indexed by a 2-tuple of the starting cell and the string of the expected sequence. And it’s initialized for all the numbers for the strings ‘N’ and ‘P’.

The function which calculates the probability of a sequence from a determined cell first checks if it’s already in the DP dictionary, if it’s not there are three cases:

1. The cell is number 1: in that case the probability of the sequence is the probability of hearing the first letter of the string in that position multiplied by listening the rest of the string from cell 2.
2. The cell is number 500: in that case the probability of the sequence is the probability of hearing the first letter of the string in that position multiplied by listening the rest of the string from cell 499.
3. Rest of the cells: the probability of listening a sequence is: the probability of hearing the first letter of the string in that position multiplied by (p + q) where p stands for the probability of listening to the rest of the string from the previous cell divided by 2 (the probability of choosing the previous cell is 0.5) and q stands for the probability of listening to the rest of the string from the next cell divided by 2 (the probability of choosing the next cell is 0.5).

The result is the sum of the probability of listening to the sequence from each cell and then divided by 500. There’s a probability of 1/500 to start in each cell.

The python code is available problem329.py:

from CommonFunctions import find_primes_less_than
from fractions import Fraction

d = {}

primes = set(find_primes_less_than(501))
for i in range(1, 501):
if i in primes:
d[(i, 'P')] = Fraction(2, 3)
d[(i, 'N')] = Fraction(1, 3)
else:
d[(i, 'P')] = Fraction(1, 3)
d[(i, 'N')] = Fraction(2, 3)

def calc_prob(i, string):
if (i, string) in d:
return d[(i, string)]

if (i == 1):
prob = d[(i, string[0])] * calc_prob(i + 1, string[1:])
elif (i == 500):
prob = d[(i, string[0])] * calc_prob(i - 1, string[1:])
else:
prob = d[(i, string[0])] * (calc_prob(i + 1, string[1:]) * Fraction(1, 2) + calc_prob(i - 1, string[1:]) * Fraction(1, 2))

d[(i, string)] = prob
return prob

if __name__ == '__main__':
result = Fraction(0, 1)
for i in range(1, 501):
result += calc_prob(i, 'PPPPNNPPPNPPNPN')
print("The result is:", result / 500)