Skip to content

Instantly share code, notes, and snippets.

@pajuey
Created February 7, 2013 21:40
Show Gist options
  • Save pajuey/4734502 to your computer and use it in GitHub Desktop.
Save pajuey/4734502 to your computer and use it in GitHub Desktop.
Bored, practicing java. I think i'm using random right to scramble letters, I don't think my probability math is right tho.
/**
* WordProbability.java
* Created with IntelliJ IDEA.
* User: stev
* Date: 2/7/13
*/
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
public class WordProbability {
private static Random random = new Random();
private static Scanner sc = new Scanner(System.in);
private static final String abcStr = "abcdefghijklmnopqrstuvwxyz";
private static String word;
private static char[] abc;
private static boolean go = true;
public static void main(String[] args) {
// convert abc's String to char array
abc = strToChar(abcStr);
// scan word String, convertToChar, print out
System.out.print("To play game, please enter a word: ");
word = sc.next();
char [] w = strToChar(word);
int size = w.length;
System.out.print("Your word of length "+size+" has been saved: ");
for( int i = 0 ; i < w.length; i++)
System.out.print(w[i]);
randomize(w, size);
}
// strToChar()
// converts string to char array.
public static char[] strToChar(String s) {
char[] c = s.toCharArray();
return c;
}
// charToStr()
// converts char array to String
public static String charToStr(char c[]){
word = new String(c);
return word;
}
// randomize()
// takes abc array, word array and size of word array, randomizes letters
// of new array and matches it to our word array, prints this out, with probability
public static void randomize(char[] w, int size) {
System.out.println("\nArray is now size " + size);
char[] c2 = new char[size];
int count = 0;
while (go) {
for (int d = 0; d < size; d++) {
c2[d] = abc[random.nextInt(25)];
System.out.print(c2[d]);
}
if(Arrays.equals(c2, w)) {
word = charToStr(c2);
float prob = (22f / 26f) / (float) (count % 100);
System.out.println("\n @ Place " + count + " We just found the word " +word);
System.out.println("\nThe probablity of finding "+word+" is " + prob);
go = false;
}
System.out.println();
count++;
} // end while
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment