Learn A New Language

June 25, 2010

I chose Lua as my target language. I have studied Lua a few times in the past, and I like some of its ideas, but I’ve never written any Lua code, except perhaps for a few small toy exercises several years ago. I also chose the Sieve of Eratosthenes exercise. Here’s what I came up with:

function primes (n)

    max_index = math.floor((n-1)/2)

    v = {}
    for i = 1, max_index do
        v[i] = true
    end

    p = 3
    while p*p <= n do
        i = math.floor(p/2)
        if v[i] then
            for j = 2*i*(i+1), max_index, p do
                v[j] = false
            end
        end
        p = p + 2
    end

    ps = {2}
    for i = 1, max_index do
        if v[i] then
            table.insert(ps, 2*i+1)
        end
    end

    return ps

end

The algorithm is exactly the same as the Scheme version, except that I changed the positions of i and p in the central loop to avoid a break out of the loop. The biggest change was the “bit” vector, which is zero-based in Scheme but one-based in Lua, causing the calculations involving the i and j variables to change. Here is how the function looks in use:

> print(#(primes(15485863)))
1000000

The Lua version of the program is noticeably slower than the Scheme version; I didn’t do any formal timings, but it seems to take about three times as long to run, and the sample function-call times out at codepad.org. Even when I removed the code to accumulate the result and instead just counted the true bits, the Lua version timed out. I don’t know enough about Lua to know if the interpreter is generally slow or if I have done something bad in my function.

You can run the code at http://programmingpraxis.codepad.org/IWI7F58z.

Advertisement

Pages: 1 2

4 Responses to “Learn A New Language”

  1. […] Praxis – Learn A New Language By Remco Niemeijer The goal in today’s Programming Praxis exercise is to solve a previous exercise in a language you’re not […]

  2. Remco Niemeijer said

    Steve Yegge’s Phone-Screen Coding Exercises using Ruby (see http://bonsaicode.wordpress.com/2010/06/25/programming-praxis-learn-a-new-language/ for a version with comments):

    def reverse(s)
        s.chars.inject {|rev, x| x + rev }
    end
    
    def fib(n)
        (2..n).inject([0,1]) {|fs, i| [fs[1], fs[0] + fs[1]]} [[1, n].min]
    end
    
    def timestable
        (1..12).map {|r| puts (1..12).map {|c| "%4d" % (r * c)}.join}
    end
    
    def sum_from_file(file)
        File.open(file) {|f| f.readlines.map(&:to_i).inject(:+)}
    end
    
    def odd_numbers
        p (1..99).find_all(&:odd?)
    end
    
    def maximum(array)
        array.inject {|max, i| i > max ? i : max}
    end
    
    def to_rgb(r, g, b)
        sprintf("%02x%02x%02x", r, g, b)
    end
    
  3. Bill B said

    I did the Texas Hold’Em problem in Ruby. For the rest of the code go to http://codingjunkie.net

    require ‘deck’
    require ‘card’
    require ‘player’

    card_deck = Deck.new
    keep_running = true

    while keep_running
    results = {}
    card_deck.shuffle
    seven_cards = card_deck.deal
    seven_cards.sort!
    copy = Array.new(seven_cards)

    puts “Press enter to deal cards..”
    line = gets

    if line.chop == “quit”
    keep_running = false
    else
    for i in 0..5
    for j in i..5
    copy.delete_at(i)
    copy.delete_at(j)
    hand = Player.check_hand(copy,0,0,nil)
    if results[hand]
    copy = Player.compare_hands(copy, results[hand], 4)
    end
    results[hand] = copy
    copy = Array.new(seven_cards)
    end
    copy = Array.new(seven_cards)
    end

    max_score = -1
    winning_hand = nil
    best_cards = nil
    results.each do |hand, cards|
    score = Player.ranks[hand]
    score = score.nil? ? cards[4].value : score
    if score > max_score
    max_score = score
    score = Player.ranks[hand]
    best_cards = cards
    winning_hand = hand
    end
    end
    puts “Best hand from #{seven_cards.join(“, “)} ”
    puts “\n\t #{winning_hand} : #{best_cards.join(“, “)}”
    end

    end

  4. Jebb said

    The golden ratio exercise from July 10 2009 in Scheme, recursively:

    (define (golden_r n)
      (if (= 0 n)
          1
          (+ 1 (/ 1 (golden (- n 1))))))
    

    and iteratively (I’ve started working my way through SICP as you can probably tell…):

    (define (golden_i n)
      (define (golden-iter n result count)
        (if (= count n)
            result
            (golden-iter n
                         (+ 1 (/ 1 result))
                         (+ count 1))))
      (golden-iter n 1 0))
    

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: