Archive for April, 2007

Fibonacci number

Tuesday, April 24th, 2007

One-liner to find nth Fibonacci number:

ruby -e "p Hash.new{|h,n| n<2 ? 1 : h[n-1]+h[n-2]}[ARGV[0].to_i]"   [number]

Regexp and Prime numbers

Tuesday, April 24th, 2007

There is one-liner script that will tell you if a given number is prime.
It checks for primality with a regexp.

Original perl code:
Abigail’s code:

perl -wle 'print "Prime" if (1 x shift) !~ /^1?$|^(11+?)\1+$/'

Full explanation:
http://montreal.pm.org/tech/neil_kandalgaonkar.shtml

Ruby version:

ruby -wle 'puts "Prime" unless ("1" * ARGV[0].to_i) =~ /^1$|^(11+?)\1+$/' [number]

http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/244371
http://snippets.dzone.com/posts/show/3691

Python version:
http://jtauber.com/blog/2007/03/18/python_primality_regex



I couldn’t resist porting it to Java, so here is my Java version (It is not one-liner, but maybe one statement?) :

public class PrimeTester {
  public static void main(String[] args) {
    System.out.println(String.format("%0" + args[0] + "d", 0).matches("^0$|^(00+?)\\1+$") ? "Not prime" : "Prime");
  }
}

public class PrimeTester {

  public static boolean isPrime(int number) {
    return !String.format("%0" + number + "d", 0).matches("^0$|^(00+?)\\1+$");
  }

  public static void main(String[] args) {
    System.out.println(isPrime(Integer.parseInt(args[0])) ? "Prime" : "Not prime");
  }
}

Ruby Quiz (#119) Getting to 100

Tuesday, April 10th, 2007

My solution for the Ruby Quiz (#119) Getting to 100.
(posted on Ruby-talk mailing list here.)


# Reuse permutations method on my Ruby Quiz (#106) Chess960 solution.
def permutations(elements)
  return [elements] if elements.size <= 1
  result = []
  elements.uniq.each do |p|
    _elements = elements.dup
    _elements.delete_at(elements.index(p))
    permutations(_elements).each do |perm|
      result << (perm << p)
    end
  end
  result
end

def find(digits, operators, target)
  raise "Error: More operators than digits." if (digits.size <= operators.size)
  operators[digits.size - 2] = nil if (operators.size != digits.size - 1)
  found = 0
  stars = "*" * 25
  perm = permutations(operators)
  perm.each do |operator|
    expression = digits.zip(operator).flatten.join
    value = eval(expression)
    if value == target
      found += 1
      puts stars
      puts "#{expression} = #{value}"
      puts stars
    else
      puts "#{expression} = #{value}"
    end
  end
  puts "#{perm.size} possible equations tested."
  puts "#{found} equations satisfied."
end

if ($0 == __FILE__)
  digits    = ARGV[0] || "123456789"
  operators = ARGV[1] || "+--"
  target    = ARGV[2] || "100"

  if (digits =~ /[^1-9]/ || operators =~ /[^-+*\/]/)
    puts "Usage: #$0  digits  operators  target"
    exit
  end

  find(digits.split(//), operators.split(//).map{|e| " #{e} "}, target.to_i)
end