0

I am a beginner and I am quite interested in AI, and I wanted to give it a shot. My target was to build an algorithm that is able to find a path up a hill to the highest point. I wanted something simple to start with, so I used a Matrix with values from 1 to 10 where the number corresponds to the value (1 is the lowest, 10 is the highest).

Here is the code:

#!/usr/bin/env python3

import numpy
import random

#Setting the Matrix
Matrix = numpy.zeros((5,5))

#Defining home co-ordinates
x = 0
y = 0

#The Initial Value
Matrix[x][y] = 1
home = Matrix[x][y]

#Setting the next 3 Matrices
Matrix[1][0] = random.randint(1,2)
Matrix[1][1] = random.randint(1,2)
Matrix[0][1] = random.randint(1,2)

###Setting the other Matrices:

#Top Right Group
Matrix[2][0] = random.randint(3,4)
Matrix[3][0] = random.randint(3,5)
Matrix[4][0] = random.randint(3,5)
Matrix[2][1] = random.randint(3,4)
Matrix[3][1] = random.randint(3,5)
Matrix[4][1] = random.randint(3,5)

#Bottom Left Group
Matrix[0][2] = random.randint(3,4)
Matrix[0][3] = random.randint(3,5)
Matrix[0][4] = random.randint(3,5)
Matrix[1][2] = random.randint(3,4)
Matrix[1][3] = random.randint(3,5)
Matrix[1][4] = random.randint(3,5)

#Middle Right
Matrix[2][2] = random.randint(6,8)
Matrix[3][2] = random.randint(7,9)
Matrix[4][2] = random.randint(8,10)

#Lower Middle Right
Matrix[2][3] = random.randint(6,8)
Matrix[3][3] = random.randint(7,9)
Matrix[4][3] = random.randint(8,10)

#Bottom Right
Matrix[2][4] = random.randint(6,8)
Matrix[3][4] = random.randint(7,9)
Matrix[4][4] = random.randint(8,10)

#Setting up the amount of tries
tries = 0

while tries != 8:
    #Making the program choose random x and y values
    new_x = random.randint((x-1),(x+1))
    new_y = random.randint((y-1),(y+1))

    def correction():
        if new_x < 0:
            new_x = 0
        if new_y < 0:
            new_y = 0
        if new_x > 4:
            new_x = 4
        if new_y > 4:
            new_y = 4

    #Making a new home
    def new_home():
        if Matrix[new_x][new_y] > home:
            home = Matrix[new_x][new_y]
        elif Matrix[new_x][new_y] == home:
            home = Matrix[new_x][new_y]
            tries = tries+1
        elif Matrix[new_x][new_y] < home:
            home = home
            tries = tries+1

    correction()
    new_home()


print Matrix

print home

The Matrix generation works, as I tried it out. However, the problem comes when I launch the code as I get an error:

  File "/home/lukindo/Documents/Dropbox/Python/HillClimbingAlgorithm3.py", line 83, in <module>
  new_home()

and

File "/home/lukindo/Documents/Dropbox/Python/HillClimbingAlgorithm3.py", line 74, in new_home
if Matrix[new_x][new_y] > home:
UnboundLocalError: local variable 'home' referenced before assignment

I would really like to finish this. Do you guys have any suggestions?

Thanks :)

0 Answers0