Skip to content

Instantly share code, notes, and snippets.

Created March 14, 2017 02:32
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 anonymous/8ae73c6d0225f73f903dc57181abf633 to your computer and use it in GitHub Desktop.
Save anonymous/8ae73c6d0225f73f903dc57181abf633 to your computer and use it in GitHub Desktop.
Given:
1) Map<String, List<String>> dependentMap that provides the mapping for a given column to its dependents (if any). For example:
[E -> A]
[A -> B, C]
[B -> A, C, D]
[C -> E]
In this case B and C are dependents of A, and E is a dependent of C. You can assume that a column cannot depend on itself.
2) Method setValue (String column, int value) that associates a column to the specified value.
================================================================================
Goal: implement method setDependentValues (String column, int value) using RECURSION with the following conditions:
- Set starting column with provided value
- Set all column’s dependents with value+1. Apply the same logic to their dependents (if any).
- Each dependent column found must be set only the first time it is encountered.
Example:
Calling setDependentValues (A, 1) with the map above results in these values:
A 1
B 2
C 2
D 3
E 3
HashSet<String tempSet = new HashSet<String>();
HashSet<String> setAlreadyPassed = new HashSet<String>();
public void setDependentValues (String column, int value) {
//base case
//solve simplest subproblem
//go to the next case
if(setAlreadyPassed.contains(column){
return; //base case
}
setAlreadyPassed.add(column);//add to already visted set
setValue(column,value);//set value of current column
ArrayList<String> dStrings= new ArrayList<String>();//make a new arraylist (deleting is easier)
for(String x: get(column)){ // put all values of current key in arraylist
dStrings.add(x);
}
for(String x :tempSet){ //check if arraylist has any values from the previous key's values
if(dStrings.contains(x)){ // if so, delete them from current arraylist
dStrings.remove(x);
}
}
for(String x: get(col)){ //put values of current key into tempset, to check in the next recursive call
tempSet.add(x);
}
for (String dependent : dStrings ) {
setDependentValues(dependent,value+1); //recursive call
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment