I made a code that gives me every possible 4 character combination of a String.
Now I need to make a program that chooses 1 random combination as a Password and then goes over every possible combination till it finds the chosen one and then tells me how many guesses it took to find the right one. This is what I have so far:
String alphabet = "ABCabc012!";
char pw[] = alphabet.toCharArray();
for (int i = 0; i < pw.length ; i++) {
for (int j = 0; j < pw.length ; j++) {
for (int k = 0; k < pw.length ; k++) {
for (int l = 0; l < pw.length ; l++) {
System.out.println(pw[i] + " " + pw[j] + " " + pw[k] + " " + pw[l]);
}
}
}
}
I tried to store the pw[] in an array but I dont know exactly how to do it.
Do you really need to store the values in a list beforehand?
Do you need to generate each value exactly once, or it does not matter?
If you can just generate random passwords of size 4 N times, you could try something like this:
public class RandomPass {
static Random random = new Random();
public static void main(String[] args) {
String alphabet = "ABCabc012!";
String password = generatePassword(4, alphabet);
System.out.println("PW is: " + password);
int counter = 0;
while (!generatePassword(4, alphabet).equals(password)) {
counter++;
}
System.out.println("It took: " + counter + " times.");
}
private static String generatePassword(int size, String alphabet) {
StringBuilder pw = new StringBuilder();
for (int i = 0; i < size; i++) {
pw.append(alphabet.charAt(random.nextInt(0, alphabet.length())));
}
return pw.toString();
}
}
If you really need to store them, so do it inside an ArrayList, instead of printing them as you are doing in your code.
After that, you can just traverse the ArrayList and search for your password in there.
You're actually pretty close!
Here's how to build the combinations, add them to the ArrayList, output them, pick a random password from the list, then randomly generate passwords until you get a match:
public static void main(String[] args) {
String alphabet = "ABCabc012!";
char pw[] = alphabet.toCharArray();
// generate the combinations
ArrayList<String> combos = new ArrayList<>();
for (int i = 0; i < pw.length ; i++) {
for (int j = 0; j < pw.length ; j++) {
for (int k = 0; k < pw.length ; k++) {
for (int l = 0; l < pw.length ; l++) {
String pwCombo = "" + pw[i] + pw[j] + pw[k] + pw[l];
combos.add(pwCombo);
}
}
}
}
// output the combinations
for(String password : combos) {
System.out.println(password);
}
// pick a random passwrod
Random r = new Random();
int index = r.nextInt(combos.size());
String pwToGuess = combos.get(index);
System.out.println("Password to guess: " + pwToGuess);
// randomly generate a password until it matches
int tries = 0;
String pwGuess = "";
do {
tries++;
pwGuess = "" + pw[r.nextInt(pw.length)] + pw[r.nextInt(pw.length)] + pw[r.nextInt(pw.length)] + pw[r.nextInt(pw.length)];
} while (!pwGuess.equals(pwToGuess));
System.out.println("It took " + tries + " tries to guess the password!");
}
Related
I need to make a program that will take string inputs from user and store it in an array. I will then need to make a function that first: sorts each String {character by character} in descending order and second: will sort all String input in descending order {Strings}.
package com.company;
import java.util.Arrays;
import java.util.Scanner;
public class Main {
static String sortString(String str)
{
char[] chArr = str.toCharArray();
String SortString = "";
// For sorting each individual strings character by character
for (int i = 0; i< chArr.length; i++)
{
for (int j = 0; j < chArr.length; j++)
{
if(chArr[i] > chArr[j])
{
char temp = chArr[i];
chArr[i] = chArr[j];
chArr[j] = temp;
}
}
}
//converting all of the character into a single string
for (int k = 0; k<chArr.length;k++)
{
SortString = SortString + chArr[k];
}
//Assigning the current String Sortstring to an array
String[] OldArray = new String[5];
for (int counter = 0; counter<5; counter++)
{
OldArray[counter] = SortString;
}
//sorting all of the strings in descending order
for (int i = 0; i< OldArray.length;i++)
{
for (int j = i+1; j< OldArray.length;j++)
{
if(OldArray[i].compareTo(OldArray[j]) > 0)
{
String temp = OldArray[i];
OldArray[i] = OldArray[j];
OldArray[j] = temp;
}
}
}
return OldArray[0];
}
public static void main(String[] args)
{
Scanner UserInput = new Scanner (System.in);
String[] names = new String[5];
// will take a String user input from a user and store it in an arra
for (int counter = 0; counter<5; counter++)
{
do
{
System.out.print("Input String #" + (counter+1) + ": ") ;
names[counter] = UserInput.next().toLowerCase();
}while(names[counter].length() > 25);
}
//will print the assorted array
for(int i = 4; i >= 0; i--)
{
System.out.println((sortString(names[i])));
}
}
}
Input:
Input String #1: Stackoverflow
Input String #2: Java
Input String #3: ZZrot
Input String #4: coding
Input String #5: sorting
Output
tsronig
onigdc
zztro
vjaa
wvtsroolkfeca
Expected Output:
zztro
wvtsroolkfeca
vjaa
tsronig
onigdc
Sorry for the question I honestly don't know what to do
You're very close to the solution.
It's impossible to sort the array of strings in sortString because it only has access to the one string you pass in. Move the array sorting code to a separate method, and then you can call it while passing it the entire array:
static String sortString(String str) {
char[] chArr = str.toCharArray();
String SortString = "";
// For sorting each individual strings character by character
for (int i = 0; i < chArr.length; i++) {
for (int j = 0; j < chArr.length; j++) {
if (chArr[i] > chArr[j]) {
char temp = chArr[i];
chArr[i] = chArr[j];
chArr[j] = temp;
}
}
}
//converting all of the character into a single string
for (int k = 0; k < chArr.length; k++) {
SortString = SortString + chArr[k];
}
return SortString;
}
static void sortArray(String[] OldArray) {
//sorting all of the strings in descending order
for (int i = 0; i< OldArray.length;i++)
{
for (int j = i+1; j< OldArray.length;j++)
{
if(OldArray[i].compareTo(OldArray[j]) > 0)
{
String temp = OldArray[i];
OldArray[i] = OldArray[j];
OldArray[j] = temp;
}
}
}
}
The main method needs a small change too: the characters in the strings have to be sorted before you sort the array. Here, the characters are sorted while reading the input, and then the array is sorted with one call to sortArray:
public static void main(String[] args)
{
Scanner UserInput = new Scanner (System.in);
String[] names = new String[5];
// will take a String user input from a user and store it in an arra
for (int counter = 0; counter<5; counter++)
{
do
{
System.out.print("Input String #" + (counter+1) + ": ") ;
names[counter] = sortString(UserInput.next().toLowerCase());
}while(names[counter].length() > 25);
}
sortArray(names);
//will print the assorted array
for(int i = 4; i >= 0; i--)
{
System.out.println(names[i]);
}
}
Just made some changes to your code. sortString() was working fine.
Made only changes to main() method:
Got expected output, Try this:
public static void main(String[] args)
{
Scanner UserInput = new Scanner (System.in);
String[] names = new String[5];
// will take a String user input from a user and store it in an arra
for (int counter = 0; counter<5; counter++)
{
do
{
System.out.print("Input String #" + (counter+1) + ": ") ;
names[counter] = UserInput.next().toLowerCase();
}while(names[counter].length() > 25);
}
//will print the assorted array
String[] namesReversed = new String[names.length];
for(int i=0;i<names.length;i++){
namesReversed[i]=sortString(names[i]);
}
Arrays.sort(namesReversed, String::compareToIgnoreCase);
for(int i = namesReversed.length-1; i>=0; i--)
{
System.out.println(namesReversed[i]);
}
}
I have written a Java program to find duplicate characters in a string without Hashmap and set.
Below is the program,
package practice;
public class Duplicate {
public static void main(String[] args) {
String src= "abcad";
char[] srcChar= src.toLowerCase().toCharArray();
int len=srcChar.length;
int j=0;
boolean flag=false;
char ch;
// System.out.println("Length of the String is "+len1);
// System.out.println("Length of the character array is "+len);
int k=0;
for(int i=0;i<len;i++)
{
// System.out.println("i-----> "+i + " and character is "+srcChar[i]);
for(j=0;j<len;j++)
{
// System.out.println("j-----> "+j + " and character is "+srcChar[j]);
if(srcChar[i]==srcChar[j])
{
k++;
}
}
if(k>1)
{
if(srcChar[i]>1)
{
System.out.println("This character "+srcChar[i]+" has repeated "+k+ " time");
}
else
{
System.out.println("There are no characters repeated in the given string");
}
}
k=0;
}
}
}
Output here is:
This character a has repeated 2 time
This character a has repeated 2 time
Here, I want the output like
This character a has repeated 2 time
i.e. not repeating the output twice. Since the character "a" is repeated twice, the output is also repeated twice.
kindly help me to get the output once instead of twice.
Thank you,
class PrintDuplicateCharacter
{
public static void main(String[] args)
{
String str = "HelloJava";
char[] ch = str.toCharArray();
int i=0,j=0;
for(i=0;i<ch.length;i++)
{
int count = 0 ;
for( j = i+1;j<ch.length;j++)
{// 4 6 , 8 , 10
if(ch[i] == ch[j] )
{
count++;
}
}
if(count != 0)
{
System.out.print(str.charAt(i) + " Occured " + count + " time");
}
}
}
}
private static void duplicateChar(String str){
char[] arr1 = str.toUpperCase().toCharArray();
int length = str.length();
int count = 1;
String s = "";
char c1 = '\u0000';
for(int i=0;i<length;i++){
count = 1;
for(int j=i+1;j<length;j++){
if(arr1[i] == arr1[j]){
count++;
c1 = arr1[i];
}
if(j == (length-1) && c1 != '\u0000' && !s.contains(String.valueOf(c1))){
s = s+" "+String.valueOf(c1)+" No of times: "+count+"\n";
}
}
}
System.out.println("\nDuplicate char are:\n"+s);
}
You can make a 2 dimensional array, 2 wide, the source strings height. In this array you store a character when it gets replaced and add one to the amount of times it has been replaced.
Something like(I don't know if these counters are correct):
replacements[j][0] = charAt(j);
replacements[j][1] += 1;
You would have to check if the character you are replacing already exists in this array and you can only print elements of the array if they aren't null.
You print this after the original loop.
All you need to fix is to start the second loop from i instead of 0.
for (int i = 0; i < len; i++) {
for (j = i; j < len; j++) {
...
}
...
}
Imports:
import java.util.ArrayList;
import java.util.List;
Code:
public static void main(String args[]) {
String input = "abcad"; // Input value
char[] chars = input.toLowerCase().toCharArray(); // Creates ArrayList
// of all characters
// in the String
List<Character> charR = new ArrayList<>(); // Creates a List used to
// saving the Characters it
// has saved
List<Integer> valR = new ArrayList<>(); // Creates a List that will
// store how many times a
// character is repeated
for (int i = 0; i < chars.length; i++) { // Loop through items in the
// ArrayList
char c = chars[i]; // Create Character value containing the value of
// the item at the "i" index of the ArrayList
if (charR.contains(c)) { // If the List contains item...
for (int i2 = 0; i2 < charR.size(); i2++) { // Loop through its
// items
if (charR.get(i2).equals(c)) { // If you find a match...
valR.set(i2, valR.get(i2) + 1); // Increase repeated
// value by 1
i2 = charR.size(); // Stop loop
} else { // Else...
i2++; // Increase index by 1
}
}
} else { // Else...
charR.add(c); // Add the Character to the List
valR.add(1); // Add the value 1 to the List (Meaning that the
// Character repeated once)
}
}
for (int i = 0; i < charR.size(); i++) { // Loop through all the items
// in the List
System.out.println("'" + charR.get(i) + "' : " + valR.get(i)); // Display
// what
// the
// character
// is
// and
// how
// many
// times
// it
// was
// repeated
}
}
Output:
'a' : 2
'b' : 1
'c' : 1
'd' : 1
char[] array=value.toCharArray();
int count=0;
char ch;
for(int i=0;i<array.length-1;i++)
{
ch=array[i];
count=1;
if(ch!='#'){
for(int j=i+1;j<array.length;j++)
{
if(ch==array[j]){
count++;
array[j]='#';
}
}
if(count>1)
{
System.out.println("char is " + ch + "count" + count);
}
}
}
You can also solve this problem with this code like :
public static void main(String[] args) {
String src = "abcad";
char[] srcChar = src.toLowerCase().toCharArray();
int len = srcChar.length;
int j = 0;
boolean flag = false;
char ch;
// System.out.println("Length of the String is "+len1);
// System.out.println("Length of the character array is "+len);
int k = 0;
for (int i = 0; i < len; i++) {
// System.out.println("i-----> "+i + " and character is "+srcChar[i]);
for (j = 0 + i; j < len; j++) {
// System.out.println("j-----> "+j + " and character is "+srcChar[j]);
if (srcChar[i] == srcChar[j]) {
k++;
}
}
if (k > 1) {
if (srcChar[i] > 1) {
System.out.println("This character " + srcChar[i] + " has repeated " + k + " time");
} else {
System.out.println("There are no characters repeated in the given string");
}
}
k = 0;
}
}
just we need to start the inner loop with j=0+i ;
for (j = 0 + i; j < len; j++)
This will you can observe above code;
I have a program that takes in a file list of bands and albums. I need to determine the number of album each band makes and then print out a list of the the bands and the number of albums they made in descending order. I have looked around and seen it done using mapping and collections. I want to know how to do it without either. Here is what I have so far:
public static void processFile(String filename)
{
String bandname = "";
String[][] data = read_spreadsheet(filename);
//takes the file and converts it to a 2d array
ArrayList<String> bands = new ArrayList<String>();
for(int rows = 0; rows < data.length; rows++)
{
bands.add(data[rows][0]);
}
for(int i = 0; i<bands.size()-1;i++)
{
int albumcount = 0;
for(int j = i+1; j<bands.size();j++)
{
if(bands.get(i).equals(bands.get(j)))
{
albumcount++;
}
}
}
}
input example:
band1 -album
band2 -album
band1 -album
band3 -album
band1 -album
band2 -album
output example:
band1: 3
band2: 2
band3: 1
Without collections? You want to use arrays?
String [] names = new String[data.length];
int [] counts = new int[data.length];
int j = 0;
for (int i = 0; i < data.lenght; i++ ) {
while (j < data.length) {
if (data[i][0].equals(names[j])) {
found = true;
counts[j]++;
break;
} else if (names[j] == null) {
names[j] = data[i][0];
counts[j]=1;
break;
}
j++;
}
}
// find max count
// println
// nullify element
// repeat
for (int i = 0; i < j; i++) {
int max = -1;
int k = i;
int pos = -1;
while ( k < j ) {
if ( counts[k] > max ) {
pos = k;
max = counts[k];
}
k++;
}
if ( pos != -1 ) { // we found
System.out.println ( names[pos] + ": " + counts[pos]);
counts[pos] = -1;
}
}
If you sort the list of band names (with duplicates) and then count how many of each band name is in the list, you will get the album count for each band:
public static void processFile(String filename)
{
//takes the file and converts it to a 2d array
String[][] data = read_spreadsheet(filename);
// get all the bands (with duplicates)
ArrayList<String> bands = new ArrayList<String>();
for(int rows = 0; rows < data.length; rows++) {
bands.add(data[rows][0]);
}
// sort the bands alphabetically
Collections.sort(bands);
int albumCount = 1;
String currentBand = bands.remove(0);
while(bands.size() > 0) {
String nextBand = bands.remove(0);
if(currentBand.equals(nextBand)) {
albumCount++;
} else {
// print the current band album count and setup for the next band
System.out.println(currentBand + ": " + albumCount);
currentBand = nextBand;
albumCount = 1;
}
};
// print the final band album count
System.out.println(currentBand + ": " + albumCount);
}
I am developing a program that will search through my array for how many times my single random # appears and then print how many times or that it was not found. I have been researching ways to do this and cannot seem to get it figured out. This is what I have so far and thanks in advance.
My code:
import java.util.Scanner;
import java.util.Random;
class Main {
public static final Random RND_GEN = new Random();
public void createNum(int[] randomNumbers) {
for (int i = 0; i < randomNumbers.length; i++) {
randomNumbers[i] = RND_GEN.nextInt(10) + 1;
}
for (int i = 0; i < 1; i++) {
randomNumbers[i] = RND_GEN.nextInt(10) + 1;
}
}
public void printNum(int[] randomNumbers){
for (int i = 0; i < randomNumbers.length; i++) {
System.out.println("Number " + i + " : " + randomNumbers[i]);
}
for (int i = 0; i < 1; i++) {
System.out.println("Single Random # " + i + " : " + randomNumbers[i]);
}
}
public void run() {
Scanner inputReader = new Scanner(System.in);
int x = 1;
do {
int[] number = new int[20];
createNum(number);
printNum(number);
System.out.print("Restart Program?, Enter 1 for YES, 2 for NO: ");
x = inputReader.nextInt();
} while (x == 1);
}
public static void main(String[] args) {
Main go = new Main();
go.run();
}
}
import java.util.Random;
import java.util.Scanner;
public class Main {
private static final Random RND_GEN = new Random();
public int[] createNum(int[] randomNumbers) {
for (int i = 0; i < randomNumbers.length; i++) {
randomNumbers[i] = RND_GEN.nextInt(10) + 1;
}
return randomNumbers;
}
public void printNum(int[] randomNumbers){
for (int i = 0; i < randomNumbers.length; i++) {
System.out.println("Number " + i + " : " + randomNumbers[i]);
}
}
public int findNumInstancesInArray(int[] array, int numLookingFor) {
int count = 0;
for(int i : array) {
if (i == numLookingFor) {
count++;
}
}
return count;
}
public void run() {
Scanner inputReader = new Scanner(System.in);
int x;
do {
int[] numbers = new int[20];
numbers = createNum(numbers);
printNum(numbers);
int numLookingFor = RND_GEN.nextInt(10) + 1;
System.out.println("Number of instances of " + numLookingFor + " is: " + findNumInstancesInArray(numbers, numLookingFor));
System.out.print("Restart Program?, Enter 1 for YES, 2 for NO: ");
x = inputReader.nextInt();
} while (x == 1);
}
public static void main(String[] args) {
Main go = new Main();
go.run();
}
}
This is how you can count an element in an int array:
public int countOccurrences(int[] array, int needle) {
int count = 0;
for (int index = 0; index < array.length; array[++index] == needle ? count++ : count);
return count;
}
It seems as if this is the search part of your other question posted here: Random number and array search
There, you were suggested to learn about linear search and binary search. If you did, it shouldn't be too hard to translate linear search into code (binary search won't help you here). You simply have to loop through the array (you're code proves you know how to do that) and check every value if it equals the one you're searching for. Of course, if you want to count the hits, you have to increase a counter every time the value matches.
I am using this code, and for some reason, I'm getting a No Such Element Exception...
numCompanies is being imported from the keyboard and is showing up right and portfolio is an array with [numCompanies][4].
Can anyone figure out why?
for(int i = 0; i < numCompanies; i++)
{
System.out.print("Stock #" + (i+1) + ": ");
String stockData = kbReader.nextLine();
System.out.print("\n\n hi" + stockData);
Scanner stockLine = new Scanner(stockData);
for(int j = 0; j < 4; j++)
{
portfolio[i][j] = stockLine.next();
}
}
I have not tested this but probably stockLine.next(); is called even though there is no element left. So maybe this could help:
for(int j = 0; j < 4; j++)
{
if( stockLine.hasNext() ) {
portfolio[i][j] = stockLine.next();
}
else
{
portfolio[i][j] = 0; // or whatever you want it to be by default
}
}
This will solve the error message but not the fault.
You're passing a single string to a Scanner object, but I would say there's a better way of doing this.
If you want to simply read in the input for each value in the string, separated by spaces, then use split():
String stockData = kbReader.nextLine();
String[] data = stockData.split(" ");
if (data.length != 4) {
System.err.println("Bad data value found!");
} else {
//run your loop
}