RosettaCodeData/Task/Evolutionary-algorithm/PureBasic/evolutionary-algorithm.purebasic

72 lines
1.9 KiB
Text
Raw Normal View History

2016-12-05 22:15:40 +01:00
Define population = 100, mutationRate = 6
Define.s target$ = "METHINKS IT IS LIKE A WEASEL"
Define.s charSet$ = "ABCDEFGHIJKLMNOPQRSTUVWXYZ "
2013-04-10 22:43:41 -07:00
2016-12-05 22:15:40 +01:00
Procedure.i fitness(Array aspirant.c(1), Array target.c(1))
Protected i, len, fit
2013-04-10 22:43:41 -07:00
len = ArraySize(aspirant())
2016-12-05 22:15:40 +01:00
For i = 0 To len
If aspirant(i) = target(i): fit +1: EndIf
2013-04-10 22:43:41 -07:00
Next
ProcedureReturn fit
EndProcedure
2016-12-05 22:15:40 +01:00
Procedure mutatae(Array parent.c(1), Array child.c(1), Array charSetA.c(1), rate.i)
Protected i, L, maxC
2013-04-10 22:43:41 -07:00
L = ArraySize(child())
2016-12-05 22:15:40 +01:00
maxC = ArraySize(charSetA())
2013-04-10 22:43:41 -07:00
For i = 0 To L
If Random(100) < rate
2016-12-05 22:15:40 +01:00
child(i) = charSetA(Random(maxC))
2013-04-10 22:43:41 -07:00
Else
2016-12-05 22:15:40 +01:00
child(i) = parent(i)
2013-04-10 22:43:41 -07:00
EndIf
Next
EndProcedure
2016-12-05 22:15:40 +01:00
Procedure.s cArray2string(Array A.c(1))
Protected S.s, len
len = ArraySize(A())+1 : S = Space(len)
CopyMemory(@A(0), @S, len * SizeOf(Character))
2013-04-10 22:43:41 -07:00
ProcedureReturn S
EndProcedure
2016-12-05 22:15:40 +01:00
Define mutationRate, maxChar, target_len, i, maxfit, gen, fit, bestfit
Dim targetA.c(Len(target$) - 1)
CopyMemory(@target$, @targetA(0), StringByteLength(target$))
2013-04-10 22:43:41 -07:00
2016-12-05 22:15:40 +01:00
Dim charSetA.c(Len(charSet$) - 1)
CopyMemory(@charSet$, @charSetA(0), StringByteLength(charSet$))
2013-04-10 22:43:41 -07:00
2016-12-05 22:15:40 +01:00
maxChar = Len(charSet$) - 1
maxfit = Len(target$)
target_len = Len(target$) - 1
Dim parent.c(target_len)
Dim child.c(target_len)
Dim Bestchild.c(target_len)
2013-04-10 22:43:41 -07:00
2016-12-05 22:15:40 +01:00
For i = 0 To target_len
parent(i) = charSetA(Random(maxChar))
2013-04-10 22:43:41 -07:00
Next
2016-12-05 22:15:40 +01:00
fit = fitness (parent(), targetA())
2013-04-10 22:43:41 -07:00
OpenConsole()
2016-12-05 22:15:40 +01:00
PrintN(Str(gen) + ": " + cArray2string(parent()) + ": Fitness= " + Str(fit) + "/" + Str(maxfit))
2013-04-10 22:43:41 -07:00
While bestfit <> maxfit
2016-12-05 22:15:40 +01:00
gen + 1
For i = 1 To population
mutatae(parent(),child(),charSetA(), mutationRate)
fit = fitness (child(), targetA())
2013-04-10 22:43:41 -07:00
If fit > bestfit
2016-12-05 22:15:40 +01:00
bestfit = fit: CopyArray(child(), Bestchild())
2013-04-10 22:43:41 -07:00
EndIf
Next
2016-12-05 22:15:40 +01:00
CopyArray(Bestchild(), parent())
PrintN(Str(gen) + ": " + cArray2string(parent()) + ": Fitness= " + Str(bestfit) + "/" + Str(maxfit))
2013-04-10 22:43:41 -07:00
Wend
2016-12-05 22:15:40 +01:00
2013-04-10 22:43:41 -07:00
PrintN("Press any key to exit"): Repeat: Until Inkey() <> ""