Archive for the ‘Programming’ Category

Tsukasa’s PyGolf Challenge

Posted on December 6th, 2008 in Programming, Ruby | No Comments »

Greg recently offered a challenge: Python Golf. The idea, to create a parser for Apache's Common Log Format, to aggregate the amount of data sent to each IP address. The challenge being to do it with the least amount of characters. Soon after this challenge was issued, Sam and Greg were both convinced (before even talking to me) that I would attempt a Ruby solution. How could I dissapoint them? :) .

I tried a number of things, however I eventually settled on this solution (63 chars):

m=Hash.new(0);STDIN.map{|l|m[l[/^\\S+/]]+=l[/\\d+\\s+$/].to_i};p m


A slightly longer version, with a slightly prettier printing can be accomplished with inject (78 chars):

STDIN.inject(Hash.new(0)){|m,l|m[l[/^\\S+/]]+=l[/\\d+\\s+$/].to_i;m}.each{|v|p v}


Not to brag, but the winning Python entry was 121 characters. So the Ruby solution managed to be almost half this count!

Some things for the debugging toolbox

Posted on October 10th, 2008 in JavaScript, Programming, Ruby | 2 Comments »

Reading Steve's blog today I saw his post on accessing the current functions name in python. This could end up being a useful thing to know if you are playing with some unfamiliar code and need this sort of information, or are doing something nasty. So without anymore fuss here's how to do the same thing in Ruby and JavaScript! Read the rest of this entry »

Ruby & the Hex value of a number

Posted on October 1st, 2008 in Programming, Ruby | No Comments »

Sure you could use
sprintf "0x%X" % v
but isnt this snippet I put together more fun?
(-7..0).inject("0x"){|h,i|h<<"0123456789ABCDEF"[(v>>(i.abs*4))&0x0F].chr}
Something to note here is that Ruby's range Object does not support a range going backwards i.e. from 7 to 0, so I use a range from -7 to 0 and take the abs value of those numbers.

Modular Exponentiation and a lesson in Ruby

Posted on October 1st, 2008 in Math, Programming, Ruby | 1 Comment »

 

Today someone asked me if I knew of a large number class in C++. Specifically they wanted to be able to hold the value 558 in a variable. I was suspicious of why they would want to do this and asked what their ultimate goal was. It turned out they wanted to calculate nx mod p for arbitrary values of n,x and p, their ultimate goal being an implementation of Diffie Hellman key exchange.

 

Now, Calculating nx then taking the modulus p of it is a valid way of solving the problem, but it has a few nagging problems. The first is that you must be able to handle large numbers in whatever environment you are doing these calculations in, and the second is that you must be able to calculate these large numbers and take them modulo some value. To begin with, I remembered back to my early days at University when we covered something called Modular Arithmetic. Consider this example: Read the rest of this entry »