81 lines
2.4 KiB
Plaintext
81 lines
2.4 KiB
Plaintext
include "NSLog.incl"
|
|
|
|
begin globals
|
|
CFStringRef target
|
|
CFStringRef alphabet
|
|
NSInteger c
|
|
CGFloat p
|
|
end globals
|
|
|
|
target = @"METHINKS IT IS LIKE A WEASEL"
|
|
alphabet = @"ABCDEFGHIJKLMNOPQRSTUVWXYZ "
|
|
c = 100
|
|
p = 0.06
|
|
|
|
toolbox fn arc4random_uniform( UInt32 upperbound ) = UInt32
|
|
|
|
local fn Fitness( s as CFStringRef ) as NSInteger
|
|
NSInteger score = len(target)
|
|
for NSInteger i = 0 to len(target) -1
|
|
if ( ucc(s,i) == ucc(target,i) ) then score--
|
|
next
|
|
end fn = score
|
|
|
|
local fn Mutate( s as CFStringRef, rate as CGFloat ) as CFStringRef
|
|
CFMutableStringRef result = fn MutableStringWithString( @"" )
|
|
for NSInteger i = 0 to len(s) -1
|
|
if ( ( fn arc4random_uniform(100) / 100.0) < rate )
|
|
NSInteger idx = fn arc4random_uniform( (UInt32)len(alphabet) )
|
|
MutableStringAppendFormat( result, @"%C", ucc( alphabet, idx ) )
|
|
else
|
|
MutableStringAppendFormat( result, @"%C", ucc( s, i ) )
|
|
end if
|
|
next
|
|
end fn = result
|
|
|
|
local fn RandomString( length as NSInteger ) as CFStringRef
|
|
CFMutableStringRef result = fn MutableStringWithString( @"" )
|
|
for NSInteger i = 0 to length -1
|
|
NSInteger idx = fn arc4random_uniform( (UInt32)len(alphabet) )
|
|
MutableStringAppendFormat( result, @"%C", ucc( alphabet, idx ) )
|
|
next
|
|
end fn = result
|
|
|
|
void local fn PrintStep( stepNum as NSInteger, s as CFStringRef, fit as NSInteger, result as CFMutableStringRef )
|
|
MutableStringAppendFormat( result, @"%3ld: %@ Distance: %ld\n", (long)stepNum, s, (long)fit )
|
|
end fn
|
|
|
|
local fn EvolveString as CFStringRef
|
|
CFMutableStringRef result = fn MutableStringNew
|
|
CFStringRef parent = fn RandomString( len(target) )
|
|
fn PrintStep( 0, parent, fn Fitness(parent), result )
|
|
|
|
NSInteger stepNum = 0
|
|
while ( fn StringIsEqual( parent, target ) == NO )
|
|
NSInteger bestFitness = len(target) + 1
|
|
CFStringRef bestChild = @""
|
|
CFStringRef child
|
|
NSInteger fit
|
|
|
|
for NSInteger i = 0 to c -1
|
|
child = fn Mutate( parent, p )
|
|
fit = fn Fitness( child )
|
|
if ( fit < bestFitness )
|
|
bestFitness = fit
|
|
bestChild = child
|
|
end if
|
|
next
|
|
parent = bestChild
|
|
stepNum++
|
|
fn PrintStep( stepNum, parent, bestFitness, result )
|
|
wend
|
|
end fn = result
|
|
|
|
CFTimeInterval t : t = fn CACurrentMediaTime
|
|
CFStringRef result : result = fn EvolveString
|
|
NSLog( @"\nCompute time: %.3f ms\n",(fn CACurrentMediaTime-t)*1000 )
|
|
NSLog( @"%@", result )
|
|
NSLogScrollToTop
|
|
|
|
HandleEvents
|