My First q Program
I recently wrote my first q program as part of the US Constitution Word Count challenge!
It was cool seeing how much terser the q program was than my Java program that did the same thing.
4 lines and 188 characters of q...
When I timed the whole Java program (including startup time), it took 503 milliseconds:
When I timed my q program in terminal with time q program.q, it took 47 milliseconds:
All code in this post is available at https://github.com/lizziew/playground/tree/master/kdb_constitution
It was cool seeing how much terser the q program was than my Java program that did the same thing.
4 lines and 188 characters of q...
strip:{x except "[]():,;.-0123456789"}
us: strip each lower raze " " vs/: read0`:input.txt
s: desc count each group us except enlist ""
`:solution.txt 0: (key s) ,' "|" ,' (string value s)
and 50 lines and 1067 characters of Java...
I used the system timer to time the Java code itself, which took 131 milliseconds. import java.io.*;
import java.util.*;
public class wordfreq {
static class word {
String w;
int c;
public word(String w, int c) {
this.w = w;
this.c = c;
}
public String toString() {
return w + "|" + c;
}
}
public static void main(String[] args) throws Exception {
HashMap<String, Integer> freq = new HashMap<String, Integer>();
Scanner s = new Scanner(new File("input.txt"));
while (s.hasNext()){
String str = s.next().replaceAll("[^a-zA-Z ]", "").toLowerCase();
if(!str.equals("")) {
if(freq.containsKey(str)) {
freq.put(str, freq.get(str)+1);
}
else {
freq.put(str, 1);
}
}
}
List<word> list = new ArrayList<word>();
for (String w: freq.keySet()) {
list.add(new word(w, freq.get(w)));
}
Collections.sort(list, new Comparator<word>() {
public int compare(word w, word o) {
return o.c - w.c;
}
});
PrintStream out = new PrintStream(new FileOutputStream("solution.txt"));
for(int i = 0; i < list.size(); i++) out.println(list.get(i));
}
}
When I timed the whole Java program (including startup time), it took 503 milliseconds:
real 0m0.245s
user 0m0.451s
sys 0m0.052sI then ran \t \l program.q to time my q program and found that it took 33 milliseconds!
When I timed my q program in terminal with time q program.q, it took 47 milliseconds:
real 0m0.063s
user 0m0.040s
sys 0m0.007sThis shows that the Java program is both slower and takes more time to load.
All code in this post is available at https://github.com/lizziew/playground/tree/master/kdb_constitution