`

Zenefits Interview - Javascript library dependency

 
阅读更多

写一个程序, 把package dependency的关系找出來, 面试官是用javascript当例子, 解释题目给我听, 基本上就是用topological sort去解

如下

package dependency
// HTML
<script src='foo.js'></script>

 

// code for foo.js
require('bar.js')
require('main.js')

 

// code for bar.js
require('lib.js')

 

output 就是 ["lib.js", "bar.js", "main.js", "foo.js"]

 

foo.deps = [bar, main]
bar.deps = [lib]

 

getOrder(foo) => [lib, bar, main, foo]
                 [main, lib, bar, foo]  
                 [lib, main, bar, foo]
以上三種output, 任一種都可
Also, you have to check whether the overall package dependency contains a cycle or not (directed graph cycle checking)

然後還要做有向圖環的checking, 有環就直接return,啥都不做!

 

public class JSLibDependency {

	public static class DiGraph {
		Set<String> libs;
		Map<String, Set<String>> map = new HashMap<>();
		
		public DiGraph(Set<String> libs) {
			this.libs = libs;
			for(String lib:libs) {
				map.put(lib, new HashSet<>());
			}
		}
		
		public int V() {
			return libs.size();
		}
		
		public void addDependency(String lib, String dependentLib) {
			map.get(lib).add(dependentLib);
		}
		
		public Set<String> depends(String lib) {
			return map.get(lib);
		}
	}
	
	public static List<String> toposort(DiGraph g, String lib) {
		List<String> result = new ArrayList<>();
		Stack<String> stack = new Stack<>();
		Set<String> visited = new HashSet<>();
//		toposortUtil(g, lib, stack, visited);
		if(toposortCycle(g, lib, stack, visited)) {
			stack.clear();
		}
		while(!stack.isEmpty()) {
			result.add(0, stack.pop());
		}
		return result;
	}
	
	public static void toposortUtil(DiGraph g, String lib, Stack<String> stack, Set<String> visited) {
		visited.add(lib);
		for(String parentLib:g.depends(lib)) {
			if(!visited.contains(parentLib)) {
				toposortUtil(g, parentLib, stack, visited);
			}
		}
		stack.push(lib);
	}
	
	public static boolean toposortCycle(DiGraph g, String lib, Stack<String> stack, Set<String> visited) {
		visited.add(lib);
		for(String parentLib:g.depends(lib)) {
			if(visited.contains(parentLib) || toposortCycle(g, parentLib, stack, visited)) {
				return true;
			}
		}
		stack.push(lib);
		return false;
	}
	
	public static void main(String[] args) {
		Set<String> libs = new HashSet<>();
		libs.add("alex.js");
		libs.add("lib.js");
		libs.add("foo.js");
		libs.add("bar.js");
		libs.add("main.js");
		DiGraph g = new DiGraph(libs);
		g.addDependency("foo.js", "bar.js");
		g.addDependency("foo.js", "main.js");
		g.addDependency("bar.js", "lib.js");
		// add cycle here
		g.addDependency("lib.js", "alex.js");
		g.addDependency("alex.js", "foo.js");
		List<String> result = toposort(g, "alex.js");
		System.out.println(result);
	}
}

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics