Jan 31, 2008

Simple AI (Neural network) program by Ruby.

Neural network is an algorithm of AI (Artificial intelligence).

I wrote a symple Neural network program by Ruby.

This program judge if the total price of three candies are under the limit.


class Unit
def initialize(count=3)
@cells = []
(count + 1).times { @cells << rand(9) }
end

def learn(patterns)
while !ok ||= false
ok = true
result = []
patterns.values.each do |pattern|
ans = answer(pattern)
chk = patterns.check(pattern)
if ans == chk
result << 'OK'
elsif ans && !chk
result << 'NG'
ok = false
penalize(pattern, -1)
elsif !ans && chk
result << 'NG'
ok = false
penalize(pattern, 1)
end
end
yield(ok, result, @cells)
end
end

def answer(pattern)
sum = 0
@cells.length.times { |i| sum += @cells[i + 1] if pattern[i] == 1 }
@cells[0] <= sum
end

def penalize(pattern, direction)
@cells[0] -= direction
@cells.length.times { |i| @cells[i + 1] += direction if pattern[i] == 1 }
end
end

class Patterns
def initialize
@limit = 500
@prices = [310,220,70]
@values = [[0, 0, 0],
[0, 0, 1],
[0, 1, 0],
[0, 1, 1],
[1, 0, 0],
[1, 0, 1],
[1, 1, 0],
[1, 1, 1]]
end

attr_reader :values

def check(pattern)
sum = 0
pattern.length.times { |i| sum += @prices[i] * pattern[i] }
sum <= @limit
end
end

#--------------------------------
unit = Unit.new
pat = Patterns.new
unit.learn(pat) do |ok, result, cells|
p result
break if gets =~ /x/
end

Jan 30, 2008

Simple AI (Generic Algorithm) program by Ruby.

Generic Algorithm is an algorithm of AI (Artificial intelligence).

I wrote a symple Generic Algorithm program by Ruby.

It answers multiple-choice questions.


class Genes
def initialize(gene_count=10, quiz_count=10)
@generation = 1
@quiz = Quiz.new(quiz_count)
while max == quiz_count
@genes = []
gene_count.times { |i| @genes << Gene.new(quiz_count) }
mark()
sort()
end
end

def start
while max < @quiz.count
yield(@generation, @genes, max, min, average)
next_genration()
mark()
sort()
end
yield(@generation, @genes, max, min, average)
end

def mark
@genes.length.times { |i| @genes[i].score = @quiz.mark(@genes[i].ans) }
end

def sort
@genes.sort! { |a, b| a.score <=> b.score }.reverse!
end

def next_genration
@generation += 1
pair = []
pair << @genes[0]
pair << @genes[1]
pair = breed(pair)
@genes[@genes.length - 2] = pair[0]
@genes[@genes.length - 1] = pair[1]
end

def breed(parents)
c = parents[0].count
children = [Gene.new(c), Gene.new(c)]
cross = rand(c - 1)
c.times do |i|
n = (i < cross) ? 0 : 1
children[0].ans[i] = parents[(0+n)%2].ans[i]
children[1].ans[i] = parents[(1+n)%2].ans[i]
end

mutation = rand(c)
children[0].ans[mutation] = rand(3) if mutation < c
mutation = rand(c)
children[1].ans[mutation] = rand(3) if mutation < c
children
end

def max
@genes ? @genes[0].score : @quiz.count
end

def min
@genes ? @genes[(@genes.length - 1)].score : 0
end

def average
sum = 0
@genes.each { |x| sum += x.score }
sum / @genes.length
end
end

class Gene
def initialize(count)
@count = count
@ans = []
@count.times { |i| @ans << rand(3) }
end

attr_accessor :score
attr_reader :ans
attr_reader :count
end

class Quiz < Gene
def mark(ans)
score = 0
@count.times { |i| score += 1 if @ans[i] == ans[i] }
score
end
end

#--------------------------------
g = Genes.new
g.start do |generation, genes, max, min, average|
p generation
p max
10.times do |i|
p genes[i].ans
end
break if gets =~ /x/
end

Jan 29, 2008

Currying of a function with unfixed argument.

Some examples of Function Currying.


(define (curried+ a)
(lambda (b) (+ a b)))

((curried+ 1) 2)



(define (curried-mean a)
(lambda (b)
(lambda (c) (/ (+ (+ a b) c) 3))))

(((curried-mean 1) 2) 3)



When the function has arguments with which the number is unfixed.


(define (append lst x)
(if (null? lst)
(list x)
(let ((l (if (list? lst) lst (list lst))))
(cons (car l) (append (cdr l) x)))))

(define (curried-list x)
(lambda (y)
(if (null? y)
x
(curried-list (append x y)))))

(((((curried-list 1) 2) 3) 4) '())


"'()" is unwanted...

Jan 28, 2008

Tail recursion of Scheme.

Ruby program for Fibonacci number.


def fib(n)
if n < 2
n
else
fib(n - 2) + fib(n - 1)
end
end



Scheme program for Fibonacci number.


(define (fib n)
(if (< n 2)
n
(+ (fib (- n 1)) (fib (- n 2)))))



Tail recursion version.


(define (fib n)
(define (fib-iter n a b)
(if (zero? n)
a
(fib-iter (- n 1) b (+ a b))))
(fib-iter n 0 1))


Scheme has "tail recursion optimization".
Then Scheme is faster than Ruby with optimization.

Jan 27, 2008

The one line C#3.0 program for Fibonacci numbers.

I wrote one line Ruby program for Fibonacci numbers.
The one line Ruby program for Fibonacci numbers.

And I wrote one line C#2.0 program for it.
The one line C#2.0 program for Fibonacci numbers.


C#3.0 program is more elegant than C#2.0 program.

Let's write one line C#3.0 program for Fibonacci numbers.

This is the result.

1
1
2
3
5
8
13
21
34
55

This is the one line C#2.0 program.

new EventHandler(delegate(object s,EventArgs e){while(((int[])s)[2]++<10)if(Console.WriteLine(((int[])s)[1]=(((int[])s)[0]=((int[])s)[0]+((int[])s)[1])-((int[])s)[1])is Object){}}).Invoke(new int[]{1,0,0},null);


And this is the one line C#3.0 program.

Enumerable.Repeat(new[]{1,0},10).All(x=>!(Console.WriteLine(x[1]=((x[0]=x[0]+x[1])-x[1]))is Object));


More elegant!

Jan 26, 2008

The one line C#2.0 program for Fibonacci numbers.

I wrote one line Ruby program for Fibonacci numbers.
The one line Ruby program for Fibonacci numbers.

Ruby is a dynamically-typed programming language.
C# is a statically-typed programming language.

Let's write one line C#2.0 program for Fibonacci numbers.

This is the result.

1
1
2
3
5
8
13
21
34
55

This is the one line program.

new EventHandler(delegate(object s,EventArgs e){while(((int[])s)[2]++<10)if(Console.WriteLine(((int[])s)[1]=(((int[])s)[0]=((int[])s)[0]+((int[])s)[1])-((int[])s)[1])is Object){}}).Invoke(new int[]{1,0,0},null);


This is the statically-typed programming language.

Jan 25, 2008

"Jobs Hacks" are not for sale.



I made this "O'Reilly Maker".
O'Reilly Maker - Create a funny book cover!
O'Reilly Maker - Jobs hacks


From Steve Jobs Stanford Commencement Speech 2005.

"Keep looking. Don't settle."

"Your time is limited, so don't waste it living someone else's life."

"Stay Hungry. Stay Foolish."

Jan 24, 2008

The one line Ruby program for Fibonacci numbers.

Let's write one line Ruby program for Fibonacci numbers.

This is the result.

1
1
2
3
5
8
13
21
34
55

This is the one line program.

lambda{|a,b|10.times{p b=(a=a+b)-b}}.call(1,0)


Smart?

Jan 23, 2008

Can't use "document.body" on Safari.

It's impossible to use "document.body" on Safari when the web page is XHTML.
Then this code return "undefined".

alert(typeof(document.body));



But it comes no always.
What is the condition?


"document.documentElement" is OK.

Jan 22, 2008

Read Offline for iPhone/iPod touch

I made a bookmarklet for iPhone/iPod touch.
You can read web pages on iPhone/iPod touch when you are offline.

Read Offline for iPhone/iPod touch

I'm glad to read web pages offline.

Jan 21, 2008

JavaScript Shell for iPhone/iPod touch

JavaScript Shell for iPhone/iPod touch was released.

You can write and execute JavaScript programs on iPhone/iPod touch even if you are offline.


This is bookmarklet version.
JavaScript Shell for iPhone/iPod touch

It's posible to save your script with ver.2.
JavaScript Shell for iPhone/iPod touch (ver.2)


Sample code:

Show messagebox.

alert("Hello, world");



Calculate fibonacci.

function fib(n) {
if (n < 2) {
return n;
} else {
return fib(n - 1) + fib(n - 2);
}
}
fib(10);


Operate DOM.

document.getElementById("area").style.color = "blue";
document.getElementById("result").style.color = "red";
document.getElementById("exec").innerHTML = "Execute!!!!";
document.getElementById("save").innerHTML = "Save!!!!";



Let's enjoy programming on iPhone/iPod touch.

Jan 20, 2008

iPod touch firmware update to 1.1.3

I updated my iPod touch firmware to 1.1.3.

The information about the firmware 1.1.3 and the software update is mixed.
The firmware 1.1.3 is free.
Software update is nonfree ($20).

The firmware is good for Japanese users.
Because of the improvement of Japanese keybord.

I'm looking forward to the SDK for iPhone/iPod touch released next month.

Jan 17, 2008

The one line Ruby program for the factorial of n (n!)

Write a program that calculates the facctorial of n (n!).

result = n * (n - 1) * (n - 2) * ... * 2 * 1


I write a Ruby program.
n = gets.to_i
k = 1
n.times do |i|
k *= i.next
end
puts k
This is a normal program.
Let's write in one line.

k = 1
gets.to_i.times { |i| k *= i.next }
puts k
It's easy so far.


A little device.
k = 1
puts k if gets.to_i.times { |i| k *= i.next }

The key point is the initialization of a variable.
lambda { |k| puts k if gets.to_i.times { |i| k *= i.next } }.call(1)
Completion!

Jan 16, 2008

My iPod touch can't access WiFi.

I want to jailbreak for my iPod touch.
But my iPod touch can't access WiFi.
The wireless connection is unstable.

Should I buy other wireless router?

Jan 15, 2008

Trying iPod touch

I got an iPod touch.
And got a case for it.

But the case is not good.
I will buy a new case.

Jan 14, 2008

From Japanese programmer.

I use C# at office and Ruby at home.
Now I'm interested in JavaScript.

I've just been reading "The Pragmatic Programmer" written by Andrew Hunt and David Thomas.