Luke_A_Somers comments on Less Wrong Polls in Comments - Less Wrong

79 Post author: jimrandomh 19 September 2012 04:19PM

You are viewing a comment permalink. View the original post to see all comments and the full post content.

Comments (302)

You are viewing a single comment's thread. Show more comments above.

Comment author: Luke_A_Somers 20 September 2012 01:22:34PM *  2 points [-]

awk is made for this, but it took me a few minutes to whip this up in java. I figured if numeric polls are used in the future, this can be used as a code-base. The indentation isn't coming through, but any IDE will fix that for you.

This doesn't work on arbitrary numeric entry polls, but for those, you can gather the statistics as you go along, putting it in the GATHER loop

EDITED to fix serious bug.

usage: paste this into PollStat.java, compile it. then run

java PollStat < poll.csv.txt

So far, the winners are endoself and army1987. I wasn't far off.

~~~~~~~~~

import java.io.*;
import java.util.*;
public class PollStat {
public static void main(String[] args) {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();
int[] counts = new int[12]; // PUT NUMBER OF POLL OPTIONS HERE
int end, begin;
int linen = 0;
while (line != null && line.charAt(0) == '#') {
line = br.readLine();
linen++;
}
while (line != null) { // GATHER LOOP
linen++;
end = line.lastIndexOf("\",\"");
begin = line.lastIndexOf("\",\"", end-1);
try {
line = line.substring(begin+3, end);
} catch (Exception e) {
System.out.println("At line number "+linen+":");
e.printStackTrace();
System.exit(1);
}
Integer c = Integer.parseInt(line);
counts[c]++;
// For arbitrary numeric responses, don't use counts.
// just continuously gather your statistics. Alternately, make a list of Doubles or something.
line = br.readLine();
}
br.close();
int total = 0;
int resp = 0;
int[] numbers = new int[]{100, 64, 41, 26, 17, 11, 7, 4, 3, 2, 1, 0}; // PUT POLL OPTIONS HERE
for (int i = 0; i < c.length; i++) {
System.out.println(numbers[i]+": "+counts[i]);
total += numbers[i] * counts[i];
resp += counts[i];
}
System.out.println("total: "+total);
System.out.println("average: "+((double)total)/resp);
} catch (IOException ioe) {
ioe.printStackTrace();
System.exit(2);
}
}
}