Created
February 7, 2013 21:44
-
-
Save pajuey/4734529 to your computer and use it in GitHub Desktop.
Bored, practicing java. Enter word, randomizes a bunch of chars to match word.
Prints probability.
I dunno if i'm using random in the right way, but it works, yet the probability math doesn't seem right,
cause chances seem so infinitesimally small in getting a match on the word.
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
/** | |
* 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