Friday, May 23, 2008

Treasure Hunt 2

Caveman style java implementation of the 2nd Treasure Hunt no-brainer-teaser.

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

public class TreasureHunt2 {

private List getFileListFromPath(String path, String pattern,
String ext){
List result = new LinkedList();
File file = new File(path);
if (file.isDirectory()){
for(File innerFile : file.listFiles()){
result.addAll(getFileListFromPath(innerFile.getPath(),
pattern, ext));
}
} else {
if ((file.getName().endsWith(ext))
&& (file.getPath().indexOf(pattern) > -1)){
result.add(file);
}
}
return result;
}

private Long getNumFromFile(File file, int linNumber) throws IOException {
Long result = 0l;
BufferedReader in = new BufferedReader(new FileReader(file));
String str;
int i = 0;
while ((str = in.readLine()) != null) {
i++;
if (i == linNumber){
if (str.length()>1){
result = new Long(str);
break;
}
}
}
in.close();
return result;
}

private Long sumFiles(List list, int linNumber) throws IOException{
Long sum = 0l;
for (File file : list){
Long add = getNumFromFile(file, linNumber);
sum += add;
}
return sum;
}

class TreasureHuntPattern{
public String namePattern;
public String extension;
public int lineNumber;
public TreasureHuntPattern(String namePattern, String extension,
int lineNumber){
this.namePattern = namePattern;
this.extension = extension;
this.lineNumber = lineNumber;
}
}

final TreasureHuntPattern[] patterns = {
new TreasureHuntPattern("mno", ".xml", 5),
new TreasureHuntPattern("foo", ".pdf", 5)
};
static final String sumFilesPath =
"F:/GoogleTreasureHunt08_17428357331831084502";

public void hunt() throws IOException{
Long prod = 1l;
for (TreasureHuntPattern pattern : patterns){
prod *= sumFiles(
getFileListFromPath(sumFilesPath, pattern.namePattern,
pattern.extension),
pattern.lineNumber);
}
System.out.println("prod:"+prod);
}

public static void main(String[] args) throws IOException{
TreasureHunt2 hunter = new TreasureHunt2();
hunter.hunt();
}

}

Caveman style bash implementation:
sum.sh
summ=0
find $1 | grep $2".*\."$3$ |
(while read
do
f=`cat "./$REPLY"`
num=`echo $f | cut -f$4 -d" "`
let summ=summ+num
done
echo $summ)

prod.sh
sum1=`./sum.sh "./files/GoogleTreasureHunt08_17428357331831084502" mno xml 5`
sum2=`./sum.sh "./files/GoogleTreasureHunt08_17428357331831084502" foo pdf 5`
echo $sum1
echo $sum2
let prod=sum1*sum2
echo $prod

1 comment:

aatiis said...

I like Java, but the Bash implementations just seem to be clearer for me. Although I don't really know much shell scripting...