[QUIZ] Fractals (#125)

R

Ruby Quiz

The three rules of Ruby Quiz:

1. Please do not post any solutions or spoiler discussion for this quiz until
48 hours have passed from the time on this message.

2. Support Ruby Quiz by submitting ideas as often as you can:

http://www.rubyquiz.com/

3. Enjoy!

Suggestion: A [QUIZ] in the subject of emails about the problem helps everyone
on Ruby Talk follow the discussion. Please reply to the original quiz message,
if you can.

-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

by Drew Olson

When I learned about fractals in high school math class, I immediately found
them fascinating. For those of you unfamiliar with the concept, the definition
from Wikipedia is as follows: a fractal is "a rough or fragmented geometric
shape that can be subdivided in parts, each of which is (at least approximately)
a reduced-size copy of the whole".

At the end of the unit in which we were taught them, the fractal below was a
test question. In subsequent years, I began drawing it freehand to higher and
higher levels. The details and patterns that emerge are fascinating.

The goal is to create a ruby program which takes the level as an argument and
then draws the fractal shown below to the specified level. The fractal is
created by drawing the first level, then repeating the pattern such that each
base piece is replaced with the fractal from the higher level. Thus, to move
from level 1 to level 2, we replace each line with the shape at level 1. Notice
that the position changes as well, meaning if the line is vertical we replace it
with a vertically positioned shape of level 1 (right and left facing also
matter). I have shown the first 3 levels below (including the base component at
level 0). Feel free to use the console for output or get fancy with RMagick or
something similar.

_ <-- Level 0
_
_| |_ <-- Level 1
_
_| |_
_| |_ <-- Level 2
_|_ _|_
_| |_| |_| |_

_
_| |_
_| |_
_|_ _|_
_| |_| |_| |_
_| |_
_|_ _|_
_| |_| |_| |_ <-- Level 3
_| |_
_|_ _|_
_| |_|_ _ _ _|_| |_
_| |_|_|_| |_|_|_| |_
_|_ _|_|_ _|_|_ _|_
_| |_| |_| |_| |_| |_| |_| |_
 
K

Kyle Schmitt

If you want to create an image to view instead of on the console,
RMagic/RScience may be convenient, but never forget how plain old easy
it is to make a PPM image :)
You just write it out as text! This may be the easiest way to create
an image file from any language.

The header is 4 lines long, the data is written as r g b color values

Header:
First line is "P3"
Second line is a comment line that starts with "#" and goes however long
Third line contains two integers with a space between them, they
represent the size of the image
Fourth line is the maximum any color channel can be for any pixel.
For instance 7 will mean any pixel can have a red value 0-7, green
value of 0-7 and a blue value of 0-7. If you use 255 you're getting 8
bits of color per channel, which is what were used to now days.

The data itself:
Everything now is just an integer, separated by a \n or a space.
Every triplet of integers represents a pixel, with each integer in the
triplet representing a different channel: Red, Green, Blue.
The triplets are written in order, with no particular formatting, no
indication that a new line is starting, and no indication that the
file or data has ended. You just write them out, and it's up to the
viewer to read the header and know when the new line is, how many
integers to read, etc.
(There is a max length for any given line, and I don't remember what
it is, so be on the safe side and put in a \n after each pixel)

So this is a valid image file (1x3 pixels, one red one green one blue!)

P3
# comment line
1 3
255
255 0 0
0 255 0
0 0 255

Hope this helps some of you who want to write images, but don't want
to use a library (for some reason or another), or just don't want to
use something they don't understand.

--Kyle

PS:
http://netpbm.sourceforge.net has more info than I possibly can, and
probably describes it better, but longer.
 
K

Kyle Schmitt

ACK!
"which is what were used to now days."
Sorry
Please read that as
"which is what we're used to now days."
 
J

James Edward Gray II

If you want to create an image to view instead of on the console,
RMagic/RScience may be convenient, but never forget how plain old easy
it is to make a PPM image :)

I wrote pretty much the same thing in my summary to this previous quiz:

http://www.rubyquiz.com/quiz117.html

I used a more compact PPM format though.

James Edward Gray II
 
M

Morton Goldberg

-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
=-=-=-=-=-=-=

by Drew Olson

When I learned about fractals in high school math class, I
immediately found
them fascinating. For those of you unfamiliar with the concept, the
definition
from Wikipedia is as follows: a fractal is "a rough or fragmented
geometric
shape that can be subdivided in parts, each of which is (at least
approximately)
a reduced-size copy of the whole".

At the end of the unit in which we were taught them, the fractal
below was a
test question. In subsequent years, I began drawing it freehand to
higher and
higher levels. The details and patterns that emerge are fascinating.

The goal is to create a ruby program which takes the level as an
argument and
then draws the fractal shown below to the specified level. The
fractal is
created by drawing the first level, then repeating the pattern such
that each
base piece is replaced with the fractal from the higher level.
Thus, to move
from level 1 to level 2, we replace each line with the shape at
level 1. Notice
that the position changes as well, meaning if the line is vertical
we replace it
with a vertically positioned shape of level 1 (right and left
facing also
matter). I have shown the first 3 levels below (including the base
component at
level 0). Feel free to use the console for output or get fancy with
RMagick or
something similar.

_ <-- Level 0
_
_| |_ <-- Level 1
_
_| |_
_| |_ <-- Level 2
_|_ _|_
_| |_| |_| |_

_
_| |_
_| |_
_|_ _|_
_| |_| |_| |_
_| |_
_|_ _|_
_| |_| |_| |_ <-- Level 3
_| |_
_|_ _|_
_| |_|_ _ _ _|_| |_
_| |_|_|_| |_|_|_| |_
_|_ _|_|_ _|_|_ _|_
_| |_| |_| |_| |_| |_| |_| |_

I'm confused about the intent of this quiz. Is the main focus writing
code that will re-create the ASCII art shown above, or is it just to
draw the required fractal by any means of the solver's choice (for
example, using the turtle geometry classes developed in Quiz 104)? If
the latter is permitted, a simple, recursive turtle program will do
the job.

Regards, Morton
 
J

James Edward Gray II

I'm confused about the intent of this quiz. Is the main focus
writing code that will re-create the ASCII art shown above, or is
it just to draw the required fractal by any means of the solver's
choice (for example, using the turtle geometry classes developed in
Quiz 104)? If the latter is permitted, a simple, recursive turtle
program will do the job.

You guys should know by now that I'm pretty light on rules.
Officially, the "intent of this quiz" is to learn something and/or
have some fun. ;)

I say, if you can solve it simply with turtle graphics, show us. I
doubt everyone will try that so it certainly has a unique edge.

James Edward Gray II
 
M

Morton Goldberg

You guys should know by now that I'm pretty light on rules.
Officially, the "intent of this quiz" is to learn something and/or
have some fun. ;)

I say, if you can solve it simply with turtle graphics, show us. I
doubt everyone will try that so it certainly has a unique edge.

James, given the way the quiz is currently formulated, I do realize
_you_ would never dump on a turtle graphics solution. However, I
wonder whether or not the quiz author would welcome such a solution.
I suspect he thinks providing ASCII output is an integral part of his
quiz. I seek clarification because I think the quiz author's point of
view should be respected.

Regards, Morton
 
J

James Edward Gray II

James, given the way the quiz is currently formulated, I do realize
_you_ would never dump on a turtle graphics solution. However, I
wonder whether or not the quiz author would welcome such a
solution. I suspect he thinks providing ASCII output is an integral
part of his quiz. I seek clarification because I think the quiz
author's point of view should be respected.

Well, he did invite graphic solutions in the quiz description...

James Edward Gray II
 
D

Drew Olson

Morton said:
James, given the way the quiz is currently formulated, I do realize
_you_ would never dump on a turtle graphics solution. However, I
wonder whether or not the quiz author would welcome such a solution.
I suspect he thinks providing ASCII output is an integral part of his
quiz. I seek clarification because I think the quiz author's point of
view should be respected.

Regards, Morton

Morton -

I'm with James here. The spirit of the quiz is the display the output in
any way you see fit. I wrote the quiz based on ASCII output as it would
allow those who didn't want to use any external libraries or tools the
opportunity to participate. I wrote my solution based on the ASCII, but
I would be excited to see you solve it using the turtle solution. In
short, I say use whatever tool you feel provides the best solution!

- Drew
 
K

Ken Bloom

The three rules of Ruby Quiz:

1. Please do not post any solutions or spoiler discussion for this quiz
until 48 hours have passed from the time on this message.

2. Support Ruby Quiz by submitting ideas as often as you can:

http://www.rubyquiz.com/

3. Enjoy!

Suggestion: A [QUIZ] in the subject of emails about the problem helps
everyone on Ruby Talk follow the discussion. Please reply to the
original quiz message, if you can.

-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- =-=-=-=-=

by Drew Olson

When I learned about fractals in high school math class, I immediately
found them fascinating. For those of you unfamiliar with the concept,
the definition from Wikipedia is as follows: a fractal is "a rough or
fragmented geometric shape that can be subdivided in parts, each of
which is (at least approximately) a reduced-size copy of the whole".

At the end of the unit in which we were taught them, the fractal below
was a test question. In subsequent years, I began drawing it freehand to
higher and higher levels. The details and patterns that emerge are
fascinating.

The goal is to create a ruby program which takes the level as an
argument and then draws the fractal shown below to the specified level.
The fractal is created by drawing the first level, then repeating the
pattern such that each base piece is replaced with the fractal from the
higher level. Thus, to move from level 1 to level 2, we replace each
line with the shape at level 1. Notice that the position changes as
well, meaning if the line is vertical we replace it with a vertically
positioned shape of level 1 (right and left facing also matter). I have
shown the first 3 levels below (including the base component at level
0). Feel free to use the console for output or get fancy with RMagick or
something similar.

_ <-- Level 0
_
_| |_ <-- Level 1
_
_| |_
_| |_ <-- Level 2
_|_ _|_
_| |_| |_| |_

_
_| |_
_| |_
_|_ _|_
_| |_| |_| |_
_| |_
_|_ _|_
_| |_| |_| |_ <-- Level 3
_| |_
_|_ _|_
_| |_|_ _ _ _|_| |_
_| |_|_|_| |_|_|_| |_
_|_ _|_|_ _|_|_ _|_
_| |_| |_| |_| |_| |_| |_| |_

#this is my second solution. it builds on my first solution
#but reimplements the turtle graphics in ASCII art.
class Fractal
#rotate the turtle 90 degrees to the :left or the :right
def rotate whichway
#lots of special cases to deal with the nature of the
#characters used.
case [@direction,whichway]
when [:left,:left],[:right,:right]
@y+=1
@direction=:down
when [:right,:left],[:left,:right]
@direction=:up
when [:down,:right]
@x-=1
@y-=1
@direction=:left
when [:up,:left]
@x-=1
@direction=:left
when [:up,:right]
@x+=1
@direction=:right
when [:down,:left]
@x+=1
@y-=1
@direction=:right
end
self
end

#creates a blank canvas of the specified size, with the turtle in the
#lower left corner, facing right
def initialize width=80,height=24
@x=0
@y=height-1
@direction=:right
@matrix=Array.new(height){Array.new(width){" "}}
end

#move the turtle forward
def forward
case @direction
when :left
@matrix[@y][@x]="_"
@x-=1
when :right
@matrix[@y][@x]="_"
@x+=1
when :up
@matrix[@y][@x]="|"
@y-=1
when :down
@matrix[@y][@x]="|"
@y+=1
end
self
end

#draw a segment of the fractal
def segment depth
if depth==0
forward
else
segment depth-1
rotate :left
segment depth-1
rotate :right
segment depth-1
rotate :right
segment depth-1
rotate :left
segment depth-1
end
self
end

#convert the matrix to a string suitable for printing
def to_s
@matrix.map{|row| row.join}.join("\n")
end
end

puts Fractal.new.segment(3)
 
M

Morton Goldberg

Here is my solution to Quiz 125.

Since the required fractal is a recursive turtle path, the Turtle
Geometry kit developed for Quiz 104 can be used to provide a short
and simple solution to this quiz.

<code>
# Created by Morton Goldberg on May 26, 2007.
# quiz_125_fractal.rb

def fractal(n, s)
if n == 0
forward s
else
fractal(n-1, s/3.0)
left 90
fractal(n-1, s/3.0)
right 90
fractal(n-1, s/3.0)
right 90
fractal(n-1, s/3.0)
left 90
fractal(n-1, s/3.0)
end
end

USAGE = <<MSG
Usage: turtle_viewer.rb quiz_125_fractal.rb [level]
\twhere level is a single digit integer
\trecommend level be less than 6
MSG

n = case ARGV[0]
when nil then 3 # show level 3 if no argument given
when /^\d$/ then ARGV[0].to_i
else
puts USAGE
exit
end
go [-190, -100]
right 90
pen_down
fractal(n, 380)
</code>

The turtle_viewer.rb script, also developed for Quiz 104 can run the
above turtle program and produce the desired graphic output. But
there is a problem. The turtle program wants a command line parameter
and turtle_viewer.rb, without modification, doesn't make provision
for this. Not to worry -- changing one line in turtle_viewer.rb fixes
it up.

<code>
#! /usr/bin/env ruby -w
# Created by Morton Goldberg on November 02, 2006.
# Modified on November 17, 2006
# Modified on May 26, 2007
# turtle_viewer.rb

ROOT_DIR = File.dirname(__FILE__)
$LOAD_PATH << File.join(ROOT_DIR, "lib")

require 'tk'
require 'turtle_view'
require 'turtle'

# A simple Ruby/Tk script for viewing turtle graphics.
#
# If a file path is supplied as the first command line argument, the
# file is taken as the source for the turtle program to be run. If no
# argument is given, a default turtle program (CIRCLE_DESIGN -- see
# below) is run.

class TurtleViewer
def initialize(code)
@code = code
# Create and lay out the viewer. Its only widget is a canvas.
root = TkRoot.new {
bg "DodgerBlue2"
title "Turtle Graphics Viewer"
}
@canvas = TkCanvas.new(root) {
relief :solid
borderwidth 1
}
@canvas.pack:)fill=>:both, :expand=>true, :padx=>20, :pady=>20)
# Run turtle commands when the canvas is mapped by Tk.
@canvas.bind('Map') { run_code }
# Set the window geometry; i.e., size and placement.
win_w, win_h = 440, 440
win_x = (root.winfo_screenwidth - win_w) / 2
root.geometry("#{win_w}x#{win_h}+#{win_x}+50")
root.resizable(false, false)
# Make Cmnd+Q work as expected on Moc OS X.
root.bind('Command-q') { Tk.root.destroy }
end

def run_code
turtle = Turtle.new
view = TurtleView.new(turtle, @canvas)
view.handle_map_event(TkWinfo.width(@canvas),
TkWinfo.height(@canvas))
turtle.run(@code)
view.draw
end
end

# Commands to be run if no command line argument is given.
CIRCLE_DESIGN = <<CODE
def circle
pd; 90.times { fd 6; rt 4 }; pu
end
18.times { circle; rt 20 }
CODE

if ARGV.size > 0
code = open(ARGV.shift) { |f| f.read } # **** modified ****
else
code = CIRCLE_DESIGN
end
TurtleViewer.new(code)
Tk.mainloop
</code>

Regards, Morton
 
P

philip

Hi,
here is my solution. The fractal-part is straight forward, the ascii-art
was harder.

thanks,
Philip

--------------------------------

#!/usr/bin/ruby -w

class Fractal

def initialize n
@steps={:up =>[:up, :left, :up, :right, :up],
:down=>[:down, :right, :down, :left, :down],
:left=>[:left, :down, :left, :up, :left],
:right=>[:right, :up, :right, :down, :right] }
@n=n
@moves=(0..n).to_a.inject([]) {|result, ignore| one_step(result) }
end

def to_s
x=0
y=0

width = 3 ** @n
height= (1+width)/2
screen= (1.. height).collect { " " *(2* width-1) }

@moves.each {|item|
case item
when :up
y+=1
(screen[y-1])[x-1]="|"
when :down
y-=1
(screen[y])[x-1]="|"
when :left
x-=2
(screen[y])[x]="_"
when :right
x+=2
(screen[y])[x-2]="_"
end
}
screen.reverse.join("\n")
end

private

def one_step x
x.empty? ? [:right] : (x.collect {|item| @steps[item] }).flatten
end

end

n=ARGV[0].to_i

if (ARGV.length < 1 || n<0)
puts "Usage: quizz_125.rb level"
puts "-> level: non-negative integer"
else
puts Fractal.new(n)
end
 
D

Drew Olson

Here's my solution. It's a combination of iteration and recursion.
Drawing the fractal is itself iterative, but the rotate method is
recursive. The -f option writes output to a file rather than the
console. My program displays the output in simple ASCII and I did not
use the turtle graphics approach.

# file: fractal.rb
# author: Drew Olson

# Fractal class holds our fractal representation
class Fractal
def initialize level
raise ArgumentError if level<0
@fractal = build_fractal level
end

# to print the fractal, we flip the array (to print with base of the
# triangle on the bottom), format the fields so we get a space for
nils
# in the array, and join all the array rows together with new lines
def to_s
@fractal.reverse.map do |row|
row.map{|char| "%1s" % char}.join("")
end.join("\n")
end

private

# the height of the fractal can be calculated using the sum
# below
def get_height level
(1..level).inject(1){|sum,i| sum+3**(i-1)}
end

# this method tells us which direction to turn after drawing
# character i. if i%5 is 0..3, we make our standard move, dictated
# by the shape of the fractal, every time. if i%5 is 4, we make a
# move that is resursively defined by the fractal, hence we recal
# get_dir after dividing i by 5.
# cc - counter-clockwise
# c - clockwise
def get_dir i
if i%5 == 4
get_dir(i/5)
elsif i%5 == 0 || i%5 == 3
:cc
elsif i%5 == 1 || i%5 == 2
:c
end
end

# here we define the direction that results when rotating
# from the current direction either clockwise or counter-clockwise
def rotate heading,dir
if heading == :n
dir == :cc ? :w : :e
elsif heading == :s
dir == :cc ? :e : :w
elsif heading == :e
dir == :cc ? :n : :s
elsif heading == :w
dir == :cc ? :s : :n
end
end

# builds the fractal, given a level
def build_fractal level
# initialize heading and coordinates
heading = :e
x,y = 0,0

# build a 2D array initialized to the correct height. i represents
the
# index of the current character we are drawing.
(0...5**level).inject(Array.new(get_height(level)){[]}) do
|fractal,i|
# store character in array based on heading, then update
# x y coordinates
if heading == :n
fractal[y][x] = "|"
x += 1
y += 1
elsif heading == :s
y -= 1
fractal[y][x] = "|"
x += 1
elsif heading == :e
fractal[y][x] = "_"
x += 1
elsif heading == :w
x -= 2
fractal[y][x] = "_"
x -= 1
end
# determine new heading
heading = rotate(heading,get_dir(i))
fractal
end
end
end

# handles IO. the -f flag takes a file name and writes the
# output to a file. if the flag is excluded, the output is
# printed to the console
# Usage:
# ruby fractal.rb 3 -> prints level 3 fractal to the console
# ruby fractal.rb 6 -f level6.txt -> prints level 6 fractal to file
if __FILE__ == $0
if ARGV[1] == "-f"
file_name = ARGV[2]
File.open(file_name,"w") do |out|
Fractal.new(ARGV[0].to_i).to_s.each do |line|
out << line
end
end
else
puts Fractal.new(ARGV[0].to_i)
end
end
 
M

Matthew Moss

Here's my solution... It's the bare minimum of what I wanted to do.
I've been wanting to do some L-System type stuff for a while, so I
focused a bit on that. There's lots more I want to put into it, like
fractional levels, and support for contextual grammars (this is
context-free).

The design was inspired by Dennis Ranke's second solution to the dice
rolling quiz (#61). I had intended to reuse parts of the turtle
graphics quiz, but seeing as how I've also got "learn SVG" on my to-do
list, I did some quick and dirty SVG output. (Mozilla should be able
to open the file.)



class LSystem

def initialize(&block)
@rules = {}
instance_eval(&block)
end

def rule(var)
raise "Rule for #{var} must be unique!" if @rules.include?(var.to_sym)
@rules[var.to_sym] = yield.map { |x| x.to_sym }
end

def start(var)
@start = var.to_sym
end

def evaluate(n)
product = [@start]
n.to_i.times do |i|
product.map! do |s|
@rules[s.to_sym] || s.to_sym
end.flatten!
end

product.each do |p|
send(p)
end
end

end


koch = LSystem.new do
start :F
rule:)F) { %w(F + F - F - F + F) }


def F
nx, ny = @x + @dx, @y + @dy
puts <<-LINE
<line x1="#{@x}" y1="#{@y}" x2="#{nx}" y2="#{ny}" stroke="black" />
LINE
@x, @y = nx, ny
end

def +
@dx, @dy = -@dy, @dx
end

def -
@dx, @dy = @dy, -@dx
end

def evaluate(n)
raise "N must be non-negative" if n < 0
@x, @y = 0, 0
@dx, @dy = 900 / (3 ** n), 0

puts <<-HEADER
<?xml version="1.0" encoding="ISO-8859-1" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 20010904//EN"
"http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">
<svg xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink" xml:space="preserve"
width="900px" height="450px" viewBox="0 0 900 450" >
HEADER

super

puts <<-FOOTER
</svg>
FOOTER
end
end


koch.evaluate(ARGV[0].to_i)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,982
Messages
2,570,185
Members
46,736
Latest member
AdolphBig6

Latest Threads

Top