Any thoughts on speeding up the execution of this program - java

For the record this isn't my code found an tested it out and took forever to complete.
The first letter takes forever to get to letters farther down in the alphabet.
Any thoughts are greatly appreciated thanks in advance.
public class BruteForce {
public static void main (String[] args) {
System.out.println ("write your password (5 character only)");
String password = TextIO.getlnString ();
String word = "";
char letters[] = new char [5];
letters [0] = 'a';
letters [1] = 'a';
letters [2] = 'a'; //starts all the 5 letters with 'a'
letters [3] = 'a';
letters [4] = 'a';
while (word != password) {
//This seems like it would stop the program, but it's telling me that the variable(word) hasn't been initialized
for (letters [0] = 'a' ; letters [0] <= 'y' ; letters [0]++) {
word = new String (letters);
System.out.println (word);
for (letters [1] = 'a' ; letters [1] <= 'y' ; letters [1]++) {
word = new String (letters);
System.out.println (word);
for (letters [2] = 'a' ; letters [2] <= 'y' ; letters [2]++) {
word = new String (letters); //nested for loops
System.out.println (word);
for (letters [3] = 'a' ; letters [3] <= 'y' ; letters [3]++) {
word = new String (letters);
System.out.println (word);
for (letters [4] = 'a' ; letters [4] <= 'y' ; letters [4]++) {
word = new String (letters);
System.out.println (word);
}
}
}
}
}
}
}
}

I suggest you try something like,
StringBuilder sb = new StringBuilder();
loop: for (char i = 'a'; i <= 'z'; i++) {
for (char j = 'a'; j <= 'z'; j++) {
for (char k = 'a'; k <= 'z'; k++) {
for (char l = 'a'; l <= 'z'; l++) {
for (char m = 'a'; m <= 'z'; m++) {
sb.append(i).append(j).append(k).append(l).append(m);
System.out.println(sb.toString());
if (sb.toString().equals(password)) {
break loop;
}
sb.setLength(0);
}
}
}
}
}

Related

How to fix: Number of occurrences of a letter in a string

I'm trying to count the number of occurrences of letters that are in string. The code that I have written technically does what I want, but not the way I want to do it. For example, if I input "Hello World", I want my code to return "a=0 b=0 c=0 d=0 e=1 etc...." with the code I have written it returns "H=1, e=1, l=2 etc...."
Also how would I make sure that it is not case sensitive and it doesn't count spaces.
Code:
import java.util.Scanner;
public class Sequence {
private static Scanner scan = null;
public static void main(String[] args) {
scan = new Scanner(System.in);
String str = null;
System.out.print("Type text: ");
str = scan.nextLine();
int[] count = new int[255];
int length = str.length();
for (int i = 0; i < length; i++)
{
count[str.charAt(i)]++;
}
char[] ch = new char[str.length()];
for (int i = 0; i < length; i++)
{
ch[i] = str.charAt(i);
int find = 0;
for (int j = 0; j <= i; j++)
{
if (str.charAt(i) == ch[j])
find++;
}
if (find == 1)
{
System.out.print(str.charAt(i) + "=" + count[str.charAt(i)] + " ");
}
}
}
}
As I hinted in my original comment you only need an array of 26 int(s) because there are only 26 letters in the alphabet. Before I share the code, it is important to note that Java char is an integral type (and, for example, 'a' + 1 == 'b'). That property is important, because it allows you to determine the correct offset in an array (especially if you force the input to lower case). Something like,
Scanner scan = new Scanner(System.in);
System.out.print("Type text: ");
String str = scan.nextLine();
int[] count = new int[26];
for (int i = 0; i < str.length(); i++) {
char ch = Character.toLowerCase(str.charAt(i)); // not case sensitive
if (ch >= 'a' && ch <= 'z') { // don't count "spaces" (or anything non-letter)
count[ch - 'a']++; // as 'a' + 1 == 'b', so 'b' - 'a' == 1
}
}
for (int i = 0; i < count.length; i++) {
if (count[i] != 0) {
System.out.printf("%c=%d ", 'a' + i, count[i]);
}
}
System.out.println();
If you really want to see all of the letters that have counts of zero (seems pointless to me), change
if (count[i] != 0) {
System.out.printf("%c=%d ", 'a' + i, count[i]);
}
to remove the if and just
System.out.printf("%c=%d ", 'a' + i, count[i]);
Change str = scan.nextLine(); to str = scan.nextLine().toLowerCase().replaceAll("\\s+","");
.toLowerCase() is a method which makes every char in the string lowercase.
.replaceAll() is a method which replaces one char with another. In this case, it replaces whitespaces with nothing.

How to find out which char in string is a number?

How to find out if the char in string is a letter or a number?
I.e I have a string "abc2e4", I need to find the ints, square them, and put the answer back in the string (no extra operations with the letters), so the new string would be "abc4e16".
Im incredibly lost with this exercise, so any help would be great :D
You can do it using Regular Expression
public static String update(String str) {
final Pattern pattern = Pattern.compile("\\D+|\\d+");
final Matcher matcher = pattern.matcher(str);
StringBuilder buf = new StringBuilder();
int pos = 0;
while (matcher.find(pos)) {
str = matcher.group();
buf.append(Character.isDigit(str.charAt(0)) ? (int)Math.pow(Integer.parseInt(str), 2) : str);
pos = matcher.end();
}
return buf.toString();
}
Java provides a method to check whether a character is a digit. For this you can use Character.isDigit(char).
public static String squareNumbers(String input) {
StringBuilder output = new StringBuilder();
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i); // get char at index
if (Character.isDigit(c)) // check if the char is a digit between 0-9
output.append((int) Math.pow(Character.digit(c, 10), 2)); // square the numerical value
else
output.append(c); // keep if not a digit
}
return output.toString();
}
This will iterate any passed string character by character and square each digit it finds. If for example 2 digits are right next to each other they will be seen as individual numbers and squared each and not as one number with multiple digits.
squareNumbers("10") -> "10"
squareNumbers("12") -> "14"
squareNumbers("abc2e4") -> "abc4e16"
My logic only squares single digit numbers.
For eg - if you provide input he13llo, the output would be he19llo and not he169llo.
Scanner in = new Scanner(System.in) ;
String str = in.next() ;
String ans = str ;
for (int i = 0 ; i < str.length() ; i++)
{
char ch = str.charAt(i) ;
if((ch - '0' >= 0) && (ch - '9' <= 0))
{
int index = i ;
int num = ch - '0' ;
int square = num * num ;
ans = ans.substring(0 ,index) + square + ans.substring(index+1) ;
}
}
System.out.println(ans) ;
}

Euler059: How to choose a valid message out of decrypted possibilities?

I'm going through Project Euler Problem 059.
How to find a valid message out of decrypted possibilities from that textfile?
After turning the input into an array, performing XOR with the three-letter key and casting (char) on the results, none of the messages can get past the isLegible check.
try {
// Read the contents of the provided text file
// and convert them into an int[] array of encrypted ASCII codes
Scanner fileRead = new Scanner(new File("p059_cipher.txt"));
StringBuilder input = new StringBuilder();
while (fileRead.hasNext()) {
input.append(fileRead.next());
}
String[] parts = input.toString().split("[,]");
int[] elements = new int[parts.length];
for (int i = 0; i < parts.length; i++)
elements[i] = Integer.parseInt(parts[i]);
char[] key;
char[] convertedParts;
// Loop through possible keys,
// from ['a', 'a', 'a'] to ['z', 'z', 'z']
for (char lc1 = 'a'; lc1 <= 'z'; lc1++) {
for (char lc2 = 'a'; lc2 <= 'z'; lc2++) {
for (char lc3 = 'a'; lc3 <= 'z'; lc3++) {
key = new char[]{lc1, lc2, lc3};
// XOR each of the ASCII code chars,
// using the appropriate key letter
convertedParts = new char[elements.length];
for (int done = 0; done < elements.length; done++) {
convertedParts[done] =
(char) (elements[done] ^ key[done%3]);
}
// If the decrypted message counts as an answer,
// print out the sum of ASCII values
// of decrypted characters
if (isLegible(convertedParts))
System.out.println(getAsciiSum(convertedParts));
}
}
}
} catch (java.io.FileNotFoundException e) {
e.printStackTrace();
}
}
// Check whether or not the decoded message
// consists only of valid characters
private static boolean isLegible(char[] characters) {
// 32-34: SPACE, '!', '"'
// 40-41: '(', ')'
// 44-46: '.', '-', ','
// 48-59: '0'-'9', ':', ';'
// 63: '?'
// 65-90: 'A'-'Z'
for (char character : characters) {
int value = (int) character;
if ( ! ( (value >= 32 && value <= 34)
|| (value >= 40 && value <= 41)
|| (value >= 44 && value <= 46)
|| (value >= 48 && value <= 59)
|| (value == 63)
|| (value >= 65 && value <= 90) ) ) {
return false;
}
}
return true;
}
// Sums up the ASCII values of characters
private static long getAsciiSum(char[] characters) {
long sum = 0;
for (char character : characters)
sum += (int)(character);
return sum;
}
I expect the output in the form of legible text, but none can be found when looping through the decryptions.

customize the number of digits when shown the alphabet

The code for displaying all combinations 5 letters is:
for(char alphabet = 'A'; alphabet <= 'Z';alphabet++)
for(char s = 'A'; s <= 'Z';s++)
for(char b = 'A' ; b <= 'Z';b++)
for(char f = 'A'; f <= 'Z'; f++)
for (char d = 'A'; d <= 'Z'; d++)
System.out.println(alphabet+""+s+""+b+""+f+ ""+d );
But my boss wants a version in which you could customize which number of letters is displayed for example if he enters "3" it should display "aaa" and if he enters 5 it should display "aaaaa" and that for all combinations of a to z.
Recursion!:
public static class Main {
public static void main() {
printAll("",3);
}
static void printAll(String prefix, int n) {
if( n==0 ) {
System.out.println(prefix);
} else {
for(char c='A'; c<= 'Z'; c++) {
printAll(prefix+c, n-1);
}
}
}
}
Beware! Only run with small values of n!

How to use ASCII in array

I want to write a program that takes a string text, counts the appearances of every letter in English and stores them inside an array.and print the result like this:
java test abaacc
a:***
b:*
c:**
* - As many time the letter appears.
public static void main (String[] args) {
String input = args[0];
char [] letters = input.toCharArray();
System.out.println((char)97);
String a = "a:";
for (int i=0; i<letters.length; i++) {
int temp = letters[i];
i = i+97;
if (temp == (char)i) {
temp = temp + "*";
}
i = i - 97;
}
System.out.println(temp);
}
Writing (char)97 makes the code less readable. Use 'a'.
As 3kings said in a comment, you need an array of 26 counters, one for each letter of the English alphabet.
Your code should also handle both uppercase and lowercase letters.
private static void printLetterCounts(String text) {
int[] letterCount = new int[26];
for (char c : text.toCharArray())
if (c >= 'a' && c <= 'z')
letterCount[c - 'a']++;
else if (c >= 'A' && c <= 'Z')
letterCount[c - 'A']++;
for (int i = 0; i < 26; i++)
if (letterCount[i] > 0) {
char[] stars = new char[letterCount[i]];
Arrays.fill(stars, '*');
System.out.println((char)('a' + i) + ":" + new String(stars));
}
}
Test
printLetterCounts("abaacc");
System.out.println();
printLetterCounts("This is a test of the letter counting logic");
Output
a:***
b:*
c:**
a:*
c:**
e:****
f:*
g:**
h:**
i:****
l:**
n:**
o:***
r:*
s:***
t:*******
u:*

Categories