1#  The Computer Language Benchmarks Game
2#  http://shootout.alioth.debian.org/
3#
4#  contributed by Karl von Laudermann
5#  modified by Jeremy Echols
6
7size = 600 # ARGV[0].to_i
8
9puts "P4\n#{size} #{size}"
10
11ITER = 49                           # Iterations - 1 for easy for..in looping
12LIMIT_SQUARED = 4.0                 # Presquared limit
13
14byte_acc = 0
15bit_num = 0
16
17count_size = size - 1               # Precomputed size for easy for..in looping
18
19# For..in loops are faster than .upto, .downto, .times, etc.
20for y in 0..count_size
21  for x in 0..count_size
22    zr = 0.0
23    zi = 0.0
24    cr = (2.0*x/size)-1.5
25    ci = (2.0*y/size)-1.0
26    escape = false
27
28    # To make use of the for..in code, we use a dummy variable,
29    # like one would in C
30    for dummy in 0..ITER
31      tr = zr*zr - zi*zi + cr
32      ti = 2*zr*zi + ci
33      zr, zi = tr, ti
34
35      if (zr*zr+zi*zi) > LIMIT_SQUARED
36        escape = true
37        break
38      end
39    end
40
41    byte_acc = (byte_acc << 1) | (escape ? 0b0 : 0b1)
42    bit_num += 1
43
44    # Code is very similar for these cases, but using separate blocks
45    # ensures we skip the shifting when it's unnecessary, which is most cases.
46    if (bit_num == 8)
47      print byte_acc.chr
48      byte_acc = 0
49      bit_num = 0
50    elsif (x == count_size)
51      byte_acc <<= (8 - bit_num)
52      print byte_acc.chr
53      byte_acc = 0
54      bit_num = 0
55    end
56  end
57end
58