Created
December 1, 2012 16:35
-
-
Save iladriano/4183140 to your computer and use it in GitHub Desktop.
Loop log entries
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.*; | |
/** | |
* Created with IntelliJ IDEA. | |
* User: afernand | |
* Date: 11/30/12 | |
* Time: 2:21 PM | |
* To change this template use File | Settings | File Templates. | |
*/ | |
public class LogTable { | |
public static void main(String[] arg) { | |
LogTable test = new LogTable(); | |
test.add("foo", 100, true); // foo: 50 - 10 - 10 = 30 | |
test.add("bar", 120, true); // +-- bar: 10 - 0 - 5 = 5 | |
test.add("boo", 125, true); // \ +-- boo: 0 | |
test.add("boo", 125, false); // \ | | |
test.add("bah", 125, true); // \ +-- bah: 5 | |
test.add("bah", 130, false); // \ | |
test.add("bar", 130, false); // \ | |
test.add("baz", 135, true); // +-- baz: 10 | |
test.add("baz", 145, false); // | |
test.add("foo", 150, false); | |
Map<String, Row> output = test.timetable(); | |
System.out.println(output); | |
} | |
public Map<String, Row> timetable() { | |
for(Entry curr: entries) { | |
curr.analyze(); | |
} | |
return timetable; | |
} | |
class Entry { | |
void analyze() { | |
if(status) { // tag starts | |
stack.push(id); | |
timetable.put(id, new Row(time)); | |
} else { // tag ends | |
stack.pop(); | |
int diff = timetable.get(id).mark(time); // tag ends | |
if(!stack.empty()) { | |
timetable.get(stack.peek()).adjust(diff); // adjust parent | |
} | |
} | |
} | |
Entry(String id, int time, boolean status) { | |
this.id = id; | |
this.time = time; | |
this.status = status; | |
} | |
final String id; | |
final int time; | |
final boolean status; | |
} | |
public static class Row { | |
@Override | |
public String toString() { | |
return String.valueOf(delta); | |
} | |
// skip default constructor and getters/setters | |
int mark(int time) { | |
delta += time; | |
return time - start; | |
} | |
void adjust(int time) { | |
delta -= time; | |
} | |
Row(int start) { | |
this.start = start; | |
this.delta = -start; | |
} | |
private int start; | |
private int delta; | |
} | |
public void add(String id, int time, boolean status) { | |
entries.add(new Entry(id, time, status)); | |
} | |
private Map<String, Row> timetable = new HashMap<String, Row>(); | |
private Stack<String> stack = new Stack<String>(); | |
private List<Entry> entries = new ArrayList<Entry>(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment