Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #
- # Write a Fibonacci program...
- #
- Proto := Object clone
- # ...recursive version
- Proto fib := method(n, if (n<=2, return 1, return (fib(n-2)+fib(n-1))))
- # ...iterative version
- Proto fib := method(n,
- numbers := list(1,1)
- if (n <= 2,
- return numbers at(n-1),
- for(i, 2, n, numbers := numbers append (numbers at(i-2) + numbers at(i-1)))
- numbers at(n-1)
- )
- )
- Proto fib(4)
- ==> 3
- #
- # Change / to return 0 if denominator 0
- #
- # save old method
- Io> Number div := Number getSlot("/")
- ==> Number_/()
- # write "delegate"
- Io> Number / := method(if (call evalArgAt(0) == 0, 0, self div (call evalArgAt(0))))
- #
- # Write a programm to add up all numbers in a two-dimensional array
- #
- Proto := Object clone
- Proto liste := list(list())
- Proto liste at(0) append(2)
- Proto liste at(0) append(3)
- Proto liste append(list())
- Proto liste at(1) append(4)
- Proto liste at(1) append(5)
- Proto sum := method(
- self val := 0
- for(i, 0, liste size - 1, for(j, 0, liste at(0) size - 1, self val := self val + (liste at(i) at(j))))
- )
- #
- # Add a slot called myAverage to List which computes the average of all elements
- #
- # this is even empty list-safe
- List myAverage := method(if (sum, sum / size, 0))
- #
- # Prototype for a two-dimensional list. dim(x,y) allocates list of lists, get(x,y) gets element at list(y) list(x), set(x,y,value) sets it
- #
- 2dim := List clone
- 2dim dim := method(y, x, removeAll for (i, 0, x-1, append(list()) for (j, 0, y-1, at(i) append(nil))))
- 2dim set := method(y, x, value, if (value, at(x) atPut(y, value)))
- 2dim get := method(y, x, if (at(x), at(x) at(y)))
- #
- # Write a transpose method
- #
- 2dim transpose := method(transpose := self clone
- transpose dim(size, at(0) size)
- for (x, 0, size, for (y, 0, at(0) size, transpose set(x, y, get(y, x))))
- return transpose)
- #
- # Write the matrix to a file
- #
- 2dim write := method(file,
- f := File with(file)
- f remove
- f openForUpdating
- f write(self serialized)
- f close
- )
- 2dim read := method(file,
- cnt := doFile(file)
- cnt foreach (v, append(v))
- )
- #
- # 10 tries to guess a number between 1 and 100 with hints...
- #
- input := File standardInput
- rand := (Random value(99) + 1) floor
- last := 0
- cnt := 0
- while((cnt < 10) and (last != rand),
- write("guess" .. rand .. "? ")
- num := input readLine asNumber
- if (num == rand, writeln("~ YOU GOT IT ~"), write("nope... ")
- if (cnt > 0, if ((last - rand) abs > (num - rand) abs, writeln("but warmer..."), writeln("and even cooler or equally bad...")), writeln))
- last = num
- cnt = cnt + 1
- )
- if ((cnt == 10) and (last != rand), writeln("Looser! The number was " .. rand), writeln ("and with only " .. cnt .. " tries."))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement