Created
December 28, 2011 10:50
-
-
Save amadamala/1527549 to your computer and use it in GitHub Desktop.
Java code to get all words with character sum = 100 in a dictionary
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.io.BufferedReader; | |
import java.io.FileReader; | |
import java.io.IOException; | |
public class WordTotal100 { | |
public static void main(String[] args) { | |
// read big.txt file | |
try { | |
String fileStr = readFileAsString("words.txt"); | |
String[] words = fileStr.split("\\r?\\n"); | |
int count = 0; | |
for(String s: words) { | |
if(stringToInt2(s.trim()) == 100) { | |
System.out.println(s); | |
count++; | |
} | |
} | |
System.out.println("number of words with 100 sum: " + count); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
// convert file into string | |
private static String readFileAsString(String filePath) | |
throws java.io.IOException{ | |
StringBuffer fileData = new StringBuffer(1000); | |
BufferedReader reader = new BufferedReader( | |
new FileReader(filePath)); | |
char[] buf = new char[1024]; | |
int numRead=0; | |
while((numRead=reader.read(buf)) != -1){ | |
String readData = String.valueOf(buf, 0, numRead); | |
fileData.append(readData); | |
buf = new char[1024]; | |
} | |
reader.close(); | |
return fileData.toString(); | |
} | |
public static int stringToInt2(String word) { | |
int sum = 0; | |
char[] chars = word.toLowerCase().toCharArray(); | |
for(char c: chars) | |
sum += (int)c; | |
return sum - (96 * chars.length); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment