Variable or method

Now I know what this error message really means…

NameError: undefined local variable or method `xxx' for main:Object
[1] pry(main)> foo = 7
=> 7
[2] pry(main)> def foo
[2] pry(main)*   5
[2] pry(main)* end
=> :foo
[3] pry(main)> foo
=> 7

equals

shoot in foot

Turns out, the ‘foo’ method is just a shorthand for ‘self.foo’ so it is still accessible, but a little bit hidden:

[4] pry(main)> self.foo
=> 5

 

Advertisements

Surprising benchmark on Ruby’s STDIN.gets versus #each + #gets

I have accidentally run into some benchmark data on CodeChef with STDIN.each which, with large enough input data showed a 2x speedup against a simple #each + #gets.

#1:

n, k = STDIN.gets.chomp.split(' ').map {|x| x.to_i}
count = 0
(1..n).each do |i|
    x = gets.chomp.to_i
    count +=1 if x % k == 0
end
puts count

#2:

n, k = STDIN.gets.chomp.split(' ').map {|x| x.to_i}
count = 0
STDIN.each do |x|
    count +=1 if x.to_i % k == 0
end
puts count

The difference is minor:

(1..n).each do |i|
    x = gets.chomp.to_i

vs.

STDIN.each do |x|

If the dataset is 10^7 lines (each is an Integer, not larger than 10^9) then:

  • #1 runs in 44 seconds,
  • #2 runs in 20 seconds.

This might be a big issue for those who write code for such sites as: HackerRank, CodeChef, Interviewstreet or Codility. While the former two offers a place to practice coding, so this error can be addressed, the latter two are used for hiring candidates where Time Limit is often a factor of success and it is not possible to correct an entry once it has been submitted.

I need to go deeper on this issue, a wild guess would be that the #each loop that encapsulates the #gets could be opening-closing file handles, and that presents a serious overhead (multiplied 10^7 times).

Installing Haskell platform on Xubuntu 13.04? NFW.

Very nice functional programming sites (like FP Complete) are popping up on the Internet, making me wish to try out this magic (growing up on Assembly, not sure how it will work).

Problem is, I’m on Xubuntu 13.04 in VirtualBox. And Xubuntu 13.04 does not have haskell-platform in its repository, due to a bug (Launchpad link maybe later), however this bug is fixed in Xubuntu 13.10.

The obvious logical step would be upgrading Xubuntu to the recent version, but as every Xubuntu release since 11.04 failed me on the upgrading process – leaving me a totally FUBARd black screen – I should take precautions, VirtualBox Snapshot to the rescue.

Aaaand, the upgrading process obviously screws up this time as well and the snapshot saves the day, no Haskell for me today.

I even read a post where a user’s clean 13.04 install failed to upgrade to 13.10. What is happening at Canonical?