Skip to content

Instantly share code, notes, and snippets.

@karenpeng
Last active January 19, 2016 01:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save karenpeng/b8d11375c72a4732e813 to your computer and use it in GitHub Desktop.
Save karenpeng/b8d11375c72a4732e813 to your computer and use it in GitHub Desktop.
//1
// This is the text editor interface.
// Anything you type or change here will be seen by the other person in real time.
// An "expression" is either a number, or a list (AKA vector/array) with the first element one of '+', '-', '*', '/' ,
// and then other expressions.
// Write a function "evaluate" that gets an expression and returns its value
console.log(calculate(['+', 1, 2])) // --> 3
console.log(calculate(['*', 3, ['+', 1, 10]]))// --> 33
console.log(calculate(['+', 1000, 1200]))// --> 2200
console.log(calculate(['/', 6, ['+', 1, ['*', 1, 1]]]))// --> 3
console.log(calculate(['+', 1, 2, 3]))// --> 6
console.log(calculate(['+', ['*', 1, 2], 3]))// --> 5
console.log(calculate(['-', ['*', 5, 5], ['*', 2, 2, 2]]))// --> 17
// Assume - / -- only take two operands8 {3 y( A# [$ ~4 p
// + * take any number of operands
function calculate(arr){
if(arr.length < 3) return null
var o = arr[0]
var first
var result
if(typeof arr[1] === 'number') first = arr[1]
else{
first = calculate(arr[1])
}
for(var i = 2; i < arr.length; i++){
var second
if(typeof arr[i] === 'number') second = arr[i]
else{
second = calculate(arr[i])
}
result = eval(first + o + second)
first = result
}
return result
}
//2
var input = [
['A', 'B'],
['C', 'B'],
['D', 'A'],
['B', 'E']
]
main(input, 'B')
// print:
// '-A',
// '--D',
// '-C'
function Node(name){
this.name = name
this.children = []
}
function main(arr, manager){
var hash = generateTree(arr)
var root = hash[manager]
root.children.forEach(function(child){
dfs(child, '')
})
}
function dfs(root, str){
if(root === null) return;
str += '-'
console.log(str + root.name)
root.children.forEach(function(child){
dfs(child, str)
})
}
function generateTree(arr){
var hash = {}
arr.forEach(function(path){
var current = null
for(var i = path.length - 1; i >= 0; i--){
var key = path[i];
if(!hash.hasOwnProperty(key)){
var node = new Node(key)
hash[key] = node
}else{
var node = hash[key]
}
if(current){
current.children.push(node);
}
current = node
}
})
return hash
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment