-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathA-star.js
104 lines (84 loc) · 2.76 KB
/
A-star.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
let allBoxes = document.querySelectorAll('.box')
let startBoxNo = null
let endBoxNo = null
allBoxes.forEach((box,boxNo)=>{
if(box.innerHTML=='I'){startBoxNo = boxNo}
else if(box.innerHTML=='G'){endBoxNo = boxNo}
//box.innerHTML += boxNo
})
let startState = Result('no state needed',startBoxNo)
let endState = Result('no state needed',endBoxNo)
//Algorithm starts here
let state = {marginLeft:`${startState.marginLeft}`, marginTop:`${startState.marginTop}`}
let parentNode = null
let parentAction = null
let pathCost = 0
let firstNode = {state:state, parentAction:parentAction, parentNode:parentNode, pathCost:pathCost}
let frontier = []
let explored = []
let goalState = false
let frontierLen = true
let heuristicValues = []
let gValues = []
let sumValues = []
let starIndex = null
frontier.push(firstNode)
while(!goalState){
if(!frontier.length){frontierLen = false; break}
frontier.forEach((node)=>{
heuristicValues.push(heuristic(node.state))
gValues.push(node.pathCost)
})
for(let i=0; i<frontier.length; i++){
let sum = heuristicValues[i] + gValues[i]
sumValues.push(sum)
}
starIndex = sumValues.indexOf(Math.min(...sumValues))
goalState = checkGoalState(frontier[starIndex].state,endState)
if(goalState){break}
let possibleBoxNos = Actions(frontier[starIndex].state)
let temp = []
possibleBoxNos.forEach((boxNo)=>{
let state = Result('no state needed',boxNo)
let parentAction = boxNo
let parentNode = frontier[starIndex]
let pathCost = g(parentNode)
let node = {state:state, parentAction:parentAction, parentNode:parentNode, pathCost:pathCost}
let alreadyDone = false
let combinedArr = frontier.concat(explored)
combinedArr.forEach((cnode)=>{
if(cnode.state.marginLeft==node.state.marginLeft && cnode.state.marginTop==node.state.marginTop){
alreadyDone = true
}
})
if(!alreadyDone){
temp.push(node)
}
})
explored.push(frontier[starIndex])
frontier.splice(starIndex,1)
temp.forEach((node)=>{
frontier.push(node)
})
heuristicValues = []
gValues = []
sumValues = []
}
if(frontierLen){
let cellsArr = []
let actionsArr = []
let State = frontier[starIndex].state
let Node = frontier[starIndex]
while(State != state){
cellsArr.push(Node.state)
actionsArr.push(Node.parentAction)
Node = Node.parentNode
State = Node.state
}
cellsArr.reverse()
actionsArr.reverse()
show=='S' ? showSol(actionsArr) : showExp()
}
else{
alert('No solution possible!')
}