Project Euler problem 323 - Solved


You can find the statement of this problem here.

To solve this problem I used, as usual, dynamic programming as top-down approach with memoization.

The DP dictionary will be indexed by a tuple consisting of the number of tries left and the number of bits still in 0.

The base cases are:

  • remaining tries > 0 and bits in 0 = 0: Then I already have all bits in 1 so it doesn’t count, thus the probability is 0.
  • remaining tries = 0 and bits in 0 > 0: I have no or operations left to do, so I couldn’t complete it, thus the probability is 0.
  • remaining tries = 0 and bits in 0 = 0: I have all bits in 1 and finished with the or operations, so this is a good case, probability of 1.

If what we are dealing with is not one of the base cases and it’s not stored in the DP dictionary then we calculate the probability of finishing with all bits in 1 using exactly remaining tries or operations.  This will calculate the probabilities by using the probabilities stored in the DP.

In order to calculate the result we use the function that retrieves the probability of fulfilling all the bits in exactly i or operations to calculate the weight of that i in the total(this is done by multiplying i to that probaility), we add up the sum for i from 1 to 50, and we get the correct result.

The python code is problem323.py:

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

bits = 32

comb = lambda n, k: factorial[n] // (factorial[k] * factorial[n-k])

dp = {
    (0, 0) : 1

def get_value(*args):
    if args in dp:
        return dp[args]

    length, rem = args
    if length > 0 and rem == 0:
        return 0
    if length == 0 and rem > 0:
        return 0
    result = 0
    for i in range(bits+1):
        for overlooked in range(max(0, i-rem), min(i, bits-rem)+1):
            result += get_value(length-1, rem-i+overlooked) * ((comb(bits-rem, overlooked) * comb(rem, i-overlooked) / (2 ** bits)))

    dp[args] = result
    return result

iters = 50

if __name__ == '__main__':
    result = 0
    for i in range(1, iters+1):
        result += get_value(i, bits) * i
    print("The result is:", result)

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.

The Python code can be downloaded problem158.py:

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
        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
            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)
                    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
        p' x dp res 
            | x == n = (res * (comb 26 n), dp)         
            | x < n  = p' (x + 1) nDp (res + nRes)
                (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]))))
        first (x, y) = x
        f (r, dp) n = 
                (nRes, nDp) = p n dp
                maxR = max r nRes
                (maxR, nDp)


Using gnome keyring in xmonad


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]
Comment=Lightweight tiling window manager

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:


#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'


exec xmonad

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)

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:


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.