Skip to content

Instantly share code, notes, and snippets.

@achudars
Created November 5, 2013 10:37
Show Gist options
  • Save achudars/7317083 to your computer and use it in GitHub Desktop.
Save achudars/7317083 to your computer and use it in GitHub Desktop.
Weak Hill Climbing
#[Q1] Weak hill climbing, OneMax
import random
from random import randrange
# returns a modified array with one bit flipped
def randomBitFlip(array):
random_index = randrange(0,len(array))
random_bit = array[random_index]
if random_bit == 0:
array[random_index] = 1
elif random_bit == 1:
array[random_index] = 0
return array
# fitness function
def fit(array):
counter = 0
max_bits = 0
for longest in array:
if longest == 1:
counter += 1
if max_bits < counter:
max_bits += 1
else:
counter = 0
print "Longest sequence of 1s in " + str(array) + ": " + str(max_bits)
# iterate over N lists of 0 and 1 bits
N = 10
while N > 0:
s0 = [random.randint(0,1) for _ in range(N)]
#print "Before: " + str(s0)
s1 = randomBitFlip(s0)
fit(s1)
#print "After: " + str(s1)
N -= 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment