Skip to content

Instantly share code, notes, and snippets.

@oalee
Created November 30, 2016 17:15
Show Gist options
  • Save oalee/e01077c2bd60effacc295452662de128 to your computer and use it in GitHub Desktop.
Save oalee/e01077c2bd60effacc295452662de128 to your computer and use it in GitHub Desktop.
UCS, BFS, DFS search in js
var tree = {
'A': ['B', 'C', 'D', 'E'],
'B': ['A', 'F', 'G'],
'C': ['A', 'H'],
'D': ['A', 'I', 'J'],
'E': ['A', 'K', 'L'],
'F': ['B', 'G', 'M', 'N', 'O'],
'G': ['B', 'F', 'P', 'Q', 'R'],
'H': ['C', 'S'],
'I': ['D'],
'J': ['D', 'T', 'U'],
'K': ['E'],
'L': ['E', 'V'],
'M': ['F'],
'N': ['F'],
'O': ['F'],
'P': ['G'],
'Q': ['G'],
'R': ['G'],
'S': ['H', 'W', 'X'],
'T': ['J'],
'U': ['J', 'Y', 'Z'],
'V': ['L'],
'W': ['S'],
'X': ['S'],
'Y': ['U'],
'Z': ['U']
}
function addToArray(item , node){
i = item.slice(); i.push(node) ; return i
}
function exists(array, node){
return array.filter( (n) => n === node ).length > 0
}
function search(controller){
console.log('------------------------\n', controller.name)
var visited = [ startNode ]
var list = []
list.push( {node : startNode , history : [startNode]})
while(list.length > 0){
var node = controller.remove(list)
var history = node.history
console.log(history)
node = node.node
if (node === endNode){
return true
}
for (let child of tree[node].filter( (node ) => !exists(visited, node )) ){
visited.push(child)
controller.add(list, {node : child ,history : addToArray(history, child) })
}
}
}
var startNode = 'A'
var endNode = 'Y'
// dfs()
search({
name : 'depth first search',
remove : (stack) => stack.pop(),
add : (stack, child) => stack.push(child)
})
// bfs
search({
name : 'breadth first search' ,
remove : (queue) => queue.shift(),
add : (queue, child) => queue.push(child)
})
// ucs
search({
name : 'uniform cost search' ,
remove : (stack) => stack.pop(),
add : (stack , child ) => {
stack.push(child)
stack.sort( (lhs, rhs) => 1 )
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment