Maximum repeated String in an array - java

The problem is
how to get the maximum repeated String in an array using only operations on the arrays in java?
so i got into this question in a test and couldn't figure it out.
lets suppose we have an array of string.
str1[] = { "abbey", "bob", "caley", "caley", "zeeman", "abbey", "bob", "abbey" }
str2[] = { "abbey", "bob", "caley", "caley", "zeeman", "abbey", "bob", "abbey", "caley" }
in str1 abbey was maximum repeated, so abbey should be returned and
in str2 abbey and caley both have same number of repetitions and hence we take maximum alphabet as the winner and is returned(caley here).
c > a
so i tried till
import java.util.*;
public class test {
static String highestRepeated(String[] str) {
int n = str.length, num = 0;
String temp;
String str2[] = new String[n / 2];
for (int k = 0;k < n; k++) { // outer comparision
for (int l = k + 1; l < n; l++) { // inner comparision
if (str[k].equals(str[l])) {
// if matched, increase count
num++;
}
}
// I'm stuck here
}
return result;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("enter how many votes");
int n = sc.nextInt();
String[] str = new String[n];
for (int i = 0; i < n; i++) {
Str[i] = sc.nextLine();
}
String res = highestRepeated(str);
System.out.println(res + " is the winner");
}
}
so, how should i take the count of occurrence of each string with and attach it with the string itself.
All this, without using a map and any hashing but just by using arrays?

Here is a (unpolished) solution:
static String highestRepeated(String[] str) {
String[] sorted = Arrays.copyOf(str, str.length);
Arrays.sort(sorted, 0, sorted.length, Comparator.reverseOrder());
String currentString = sorted[0];
String bestString = sorted[0];
int maxCount = 1;
int currentCount = 1;
for (int i = 1 ; i < sorted.length ; i++) {
if (currentString.equals(sorted[i])) {
currentCount++;
} else {
if (maxCount < currentCount) {
maxCount = currentCount;
bestString = currentString;
}
currentString = sorted[i];
currentCount = 1;
}
}
if (currentCount > maxCount) {
return currentString;
}
return bestString;
}
Explanation:
Sort the array from highest to lowest lexicographically. That's what Arrays.sort(sorted, 0, sorted.length, Comparator.reverseOrder()); does. we sort in this order because you want the largest string if there are multiple strings with the same number of repeats.
Now we can just count the strings by looping through the array. We don't need a hash map or anything because we know that there will be no more of a string in the rest of the array when we encounter a different string.
currentString is the string that we are currently counting the number of repeats of, using currentCount. maxCount is the number of occurrence of the most repeated string - bestString - that we have currently counted.
The if statement is pretty self-explanatory: if it is the same string, count it, otherwise see if the previous string we counted (currentCount) appears more times than the current max.
At the end, I check if the last string being counted is more than max. If the last string in the array happens to be the most repeated one, bestString won't be assigned to it because bestString is only assigned when a different string is encountered.
Note that this algorithm does not handle edge cases like empty arrays or only one element arrays. I'm sure you will figure that out yourself.

another version
static String lastMostFrequent(String ... strs) {
if (strs.length == 0) return null;
Arrays.sort(strs);
String str = strs[0];
for (int longest=0, l=1, i=1; i<strs.length; i++) {
if (!strs[i-1].equals(strs[i])) { l=1; continue; }
if (++l < longest) continue;
longest = l;
str = strs[i];
}
return str;
}
change in
if (++l <= longest) continue;
for firstMostFrequent

you can't use == to check if two strings are the same.
try using this instead:
if (str[k].equals(str[l])) {
// if matched, increase count
num++;
}

Related

Speed up the comparison time of two strings

The task is to write the logic of checking the magnitude of the coincidence of the player's attempt with the hidden word.
More formally, let there be a string S — a hidden word and a string Q — a player's attempt.
Both strings have the same length N. For each position 1 ≤ i ≤ N of string Q, we need to calculate the type of match in this position with string S.
If Q[i] = S[i], then at position i the match type should be equal to "correct".
If Q[i]≠S[i], but there is another position 1 ≤ j≤ N such that Q[i] = S[j], then in position i the match type must be equal to "present".
Each letter of the string S can be used in no more than one match of
the type "correct" or "present".
Priority is always given to the "correct" type.
Of all possible use cases in the "present" type, the program selects
the leftmost position in the Q string.
In other positions, the match type must be equal to "absent".
Input format:
The first line contains the string S (1≤ S ≤ 10^6) — the hidden word.
The second line contains the string Q ( Q = S) — the player's attempt.
It is guaranteed that the strings S and Q contain only uppercase Latin letters.
Example:
input:
COVER
CLEAR
output:
correct
absent
present
absent
correct
My program does this very slowly, how can I speed it up?
import java.util.*;
public class Task1 {
private final static String cor = "correct";
private final static String abs = "absent";
private final static String pre = "present";
static String[] stringArr;
static java.util.Map<Integer, Integer> map = new HashMap<>();
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String a = sc.nextLine();
String b = sc.nextLine();
stringArr = new String[a.length()];
int length1 = a.length();
char[] arr1 = a.toCharArray();
char[] arr2 = b.toCharArray();
for (int i = 0; i < length1; i++) {
if (arr2[i] == arr1[i]) {
stringArr[i] = cor;
map.put(i, i);
}
}
for (int i = 0; i < length1; i++) {
if (arr2[i] != arr1[i]) {
while (stringArr[i] == null) {
boolean finded = false;
for (int j = 0; j < arr1.length; j++) {
if (arr2[i] == arr1[j] && !map.containsKey(j)) {
stringArr[i] = pre;
finded = true;
map.put(j, j);
break;
}
}
if (!finded) stringArr[i] = abs;
}
}
}
for (String s : stringArr) {
System.out.println(s);
}
}
}
You can use an int array (or a HashMap<Char, Integer>) count to store those "presented" characters.
We need two for loops. The first loop will set all "correct" positions (if arr1[i] == arr2[i], then stringArr[i] = cor); and for those unmatched positions (arr1[i] != arr2[i]), we count the number of occurrences for those characters in the hidden word (count[arr1[i] - 'A']++).
Then in the second for loop, we check those unmatched positions with the help of count.
If count[arr2[i] - 'A'] > 0, it means that the hidden word contains the character arr2[i], so we can set stringArr[i] = pre and decrement count[arr2[i] - 'A'] (since each letter can be used once)
Otherwise, there's no matching letter in the hidden word, stringArr[i] should be set to abs.
import java.util.Scanner;
public class Task1 {
private final static String cor = "correct";
private final static String abs = "absent";
private final static String pre = "present";
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String a = sc.nextLine();
String b = sc.nextLine();
String[] stringArr = new String[a.length()];
int length1 = a.length();
char[] arr1 = a.toCharArray();
char[] arr2 = b.toCharArray();
int[] count = new int[26];
for (int i = 0; i < length1; i++) {
if (arr2[i] == arr1[i]) {
stringArr[i] = cor;
}
else {
count[arr1[i] - 'A']++;
}
}
for (int i = 0; i < length1; i++) {
if (arr1[i] != arr2[i]) {
if (count[arr2[i] - 'A'] > 0) {
stringArr[i] = pre;
count[arr2[i] - 'A']--;
}
else {
stringArr[i] = abs;
}
}
}
for (String s : stringArr) {
System.out.println(s);
}
}
}
This can be done using hashmaps and taking advantage of the o(1) insert/delete time.
I'm assuming that each word is exactly the same length. Consequently, to get the answer, we need to check each letter in each word. If they have a length of n, then that means at a minimum it will take o(2n) == o(n) to find the answer.
[1] Then, if you're able to use extra space, I would just use a hashmap as an index, where the key is a character in secret, and the value is the set of indices that letter occurs in secret. So it would look something like this:
//cover
c:<0>
o:<1>
etx...
[2] Then check each letter in guess against the index.
If there is no key for a letter, the put absent
If there is a key, then look in the set of indices to see if there is a matching index. Since I used a hashset, that's another o(1) lookup
So sum total, you walk through secret and guess once each which is o(n) runtime. That, plus o(1) for each index lookup produces o(n) runtime.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
public class Task1 {
public static void main(String[] args)
{
ArrayList<String> res = solve("COVER", "CLEAR");
System.out.println(res);
}
public static ArrayList<String> solve(String secret, String guess){
ArrayList<String> result = new ArrayList<>();
HashMap<Character, HashSet<Integer>> index = new HashMap<>();
//shortcut
if(secret.equals(guess)){
for(int i = 0; i < secret.length(); i++) result.add("correct");
return result;
}
//make the index of char:<indices> for the chars in "secret"
for(int i = 0; i < secret.length(); i++){
char c = secret.charAt(i);
HashSet<Integer> bucket = index.get(c);
if(bucket == null){
bucket = new HashSet<>();
index.put(c, bucket);
}
bucket.add(i);
}
//check each char in "guess" against the index and tally the result
for(int i = 0; i < guess.length(); i++){
char c = guess.charAt(i);
HashSet<Integer> bucket = index.get(c);
if(bucket == null) result.add("absent");
else if(bucket.contains(i)) result.add("correct");
else result.add("present");
}
return result;
}
}

Arrange words according to their length [duplicate]

This question already has answers here:
How to sort String array by length using Arrays.sort()
(10 answers)
Closed 10 months ago.
INPUT: this is my string
OUTPUT: is my this string
I have to arrange words in a sentence according to their length and if two words have the same length then print them alphabetically (the first priority is length).
My incorrect code:
import java.util.Scanner;
class accordingtolength
{
void main()
{
String result="";
Scanner sc=new Scanner(System.in);
System.out.println("Enter the String");
String str=sc.nextLine();
String arr[]=str.split(" ");
int l=arr.length;
for(int i=0;i<l-1;i++)
{
String temp=arr[i]+" ";
String temp1=arr[i+1]+" ";
int a=temp.length();
int b=temp1.length();
if(a==b)
{
int c=temp.compareTo(temp1);
if(c>0)
result=temp1.concat(temp);
else
result=temp.concat(temp1);
}
else if(a>b)
result=temp1.concat(temp);
else
result=temp.concat(temp1);
}
System.out.println(result);
}
}
I know my code is incorrect so there is no need to attach the output.
Please help.
Perhaps this is what you were looking for. Using minimal external classes, this simply sorts the array of words in ascending order based on their length first and then alphabetically if those lengths are equal It uses a variant of what is known as a selection sort. It is a basic sort and quite often used as an introduction to sorting. But it is not very efficient.
read in the string and split based on spaces (I modified your regex to allow 1 or more spaces).
then use nested loops to iterate thru the list, comparing lengths.
if the word indexed by the outer loop (i) is longer than the word indexed by the inner loop (j), swap the words.
else if equal length compare words to each other and sort alphabetically (the String class implements the Comparable interface).
when both loops are finished, the array will be sorted in
then you can just iterate over the result building a string of words separated by spaces.
public class AccordingToLength {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the String:");
String str = sc.nextLine();
String arr[] = str.split("\\s+");
for (int i = 0; i < arr.length-1; i++) {
int outer = arr[i].length();
for (int j = i + 1; j < arr.length; j++) {
int inner = arr[j].length();
if (outer > inner || outer == inner && arr[i].compareTo(arr[j]) > 0) {
String temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
outer = inner; // outer has new length (what was just swapped)
}
}
}
String result = "";
for (String word : arr) {
result += word + " ";
}
System.out.println(result);
}
}
for input = "if a day now any easy when new test is done do den deed none"; this prints
a do if is any day den new now deed done easy none test when
There are multiple ways to solve this problem. The two most convenient ways are.
If you are allowed to use streams and comparator, then you can achieve it in a single line.
Arrays.stream(arr)
.sorted(Comparator
.comparing(String::length)
.thenComparing(Function.identity()))
.forEach(System.out::println);
Using Arrays.sort() to sort the actual array elements.
Arrays.sort(arr, (o1, o2) -> {
if (o1.length() > o2.length()) {
return 1;
} else if (o2.length() > o1.length()) {
return -1;
} else {
return o1.compareTo(o2);
}
});
System.out.println(Arrays.toString(arr));
If you don't want to use java provided APIs and data structures, you can implement a different version of bubble sort.
boolean isSwapped;
for (int i = 0; i < arr.length - 1; i++) {
isSwapped = false;
for (int j = 0; j < arr.length - i - 1; j++) {
if (arr[j].length() > arr[j + 1].length()
|| arr[j].length() == arr[j + 1].length() && arr[j].compareTo(arr[j + 1]) > 0) {
swap(arr, j, j + 1);
isSwapped = true;
}
}
if (!isSwapped)
break;
}

Is there any way to sort the digits of an Integer without any ARRAY in JAVA?

I am trying to sort the digits of an Integer in descending order in JAVA but I am not allowed to use any array.
This was given to me as an assignment in class and below is a code that I tried but failed.
import java.util.Scanner;
class descend
{
public static void main(String args[])
{
int a=0,loc=0,parse=0,temp=0,big=0;
Scanner scan = new Scanner(System.in);
System.out.print("Enter a number");
a=scan.nextInt();
String s=Integer.toString(a);
int l=s.length();
for(int i=0;i<l;i++)
{
big=(int)(s.charAt(i));
loc=i;
for(int j=i+1;j<l;j++)
{
parse=(int)(s.charAt(j));
if(parse>big)
{
big = parse;
loc=j;
}
}
temp=parse;
s.charAt(i)=s.charAt(loc);
s.charAt(loc)=temp
}
System.out.print(s);
}
}
Here I get a syntax error at s.charAt(i)=s.charAt(loc); and s.charAt(loc)=temp; that a variable is required but a value is given.
Please help me out with this and I shall always be grateful to you.
Maybe the teacher want to test your knowledge about the new stream API. Or maybe he wants you to test your knowledge about Collections.sort() and LinkedList (which does not contain an internal array).
1.) Here is a solution with stream API:
int number = 52214;
String.valueOf(number).chars()
.sorted()
.map(Character::getNumericValue).forEach(System.out::print);
This will print out:
12245
2.) Here is a solution with collections:
List<Integer> list = new LinkedList<Integer>();
StringCharacterIterator iterator = new StringCharacterIterator(String.valueOf(number));
for (char c = iterator.first(); c != CharacterIterator.DONE; c = iterator.next())
{
list.add(Character.getNumericValue(c));
}
Collections.sort(list);
System.out.println("list=" + list);
This will print out:
list=[1, 2, 2, 4, 5]
String cannot be changed, only replaced, hence a = b; f(b); will never change a.
With 10 digits only, you could iterate, step through, from 0 upto 9 to have the sorting:
int number = ... // or String number
if (number == 0) { // or < 10
System.out.println(number);
} else {
for (int digit = 0; digit <= 9; ++digit) {
// While being able to remove the current digit:
for (;;) {
int scrapedNumber = numberWithoutDigitOnce(number, digit);
if (scrapedNumber == number) {
break;
}
number = scrapedNumber;
System.out.print(digit);
}
}
System.out.println();
}
int numberWithoutDigitOnce(int number, int digit) {
if (number % 10 == digit) {
return number / 10;
}
int n = numberWithoutDigitOnce(number/10, digit)*10 + (number % 10);
}
Zero is a special case.
A recursive solution, you find the highest digit in the String, add it to your output String, and remove it from your input String.
Repeat until your input String is empty.
Removing the character at a given index in a String can be achieve by concatenating the characters before the index and the ones after the index. (Or with a StringBuilder but I agree with the comments on the OP that it would be cheating to use a StringBuilder)
private static String sort(String digitsLeftToSort, String sortedString) {
if(digitsLeftToSort.length() == 0) { // no more character to sort
return sortedString;
} else {
// find the index of the highest digit
int index = findIndexOfHighestDigit(digitsLeftToSort);
// add the character at that index to your output String
sortedString += digitsLeftToSort.charAt(index);
// Remove it from your input String
digitsLeftToSort = digitsLeftToSort.substring(0, index) + digitsLeftToSort.substring(index+1);
// Recursive call with your new Strings
return sort(digitsLeftToSort, sortedString);
}
}
// This finds the index of the highest digit in the given String
private static int findIndexOfHighestDigit(String s) {
int highestDigitValue = -1;
int highestDigitIndex = -1;
int integerValue;
for(int i = 0; i< s.length(); i++) {
integerValue = Character.getNumericValue(s.charAt(i));
if(integerValue > highestDigitValue) {
highestDigitValue = integerValue;
highestDigitIndex = i;
}
}
return highestDigitIndex;
}
Then
String sortedString = sort("462375623478142", "");
System.out.println(sortedString);
Outputs
877665444332221
Sorry, But after applying so much effort, I figured it out.
int n=54321;char ch;
String s=Integer.toString(n);
int l= s.length();
for(int i=48;i<=57;i++) //ascii values from 0 - 9
{
for(int j=0;j<l;j++)
{
ch=s.charAt(j);
if(ch==(char)i) // checking if a digit equals a number
{
System.out.print(ch);
}
}
}
It sorts the digits in ascending order. To sort in descending order we should use
for(int i=57;i>=48;i--)

comparing string arrays in java

I am working on a simple Java program where we have sorted string array named arr
I am trying to compare two adjacent string and calculate frequency for each string present in that array
for(j1=0;j1<arr.length;j1++){
if(j1+1 < arr.length){ // To prevent arrayOutofBoundsException
if(arr[j1].equals(arr[j1+1])){
counter++;
}
else {
System.out.println(arr[j1]+" "+counter);
counter=1;
}
But it's not working right , what's wrong ?
edit:problem is not in comparing , it's not calculating frequency as desired
OK, besides the equals fix, you want to keep the original order of words:
String orig = "hellow hello hello how how he ho" ;
//String orig = "how are you how do you do";
String[] arr = orig.split(" ");
//Arrays.sort(arr);
for(int j1 = 0; j1 < arr.length; j1++){
if (arr[j1] != null) {
int counter = 1;
for(int j2 = j1+1; j2 < arr.length; j2++) {
if(arr[j2] != null && arr[j1].equals(arr[j2])){
counter++;
arr[j2] = null;
}
}
System.out.println(arr[j1]+" "+counter);
}
}
The trick is that I run through the array, count all occurrences, null the occurrences, so they don't count again, and print the count. No need to sort the array.
== compares object identity in terms of memory address - to compare objects in terms of equality, use the equals-method.
This should work:
public static void main(String[] args)
{
String text = "how are you how do you do";
String[] keys = {"how", "are", "you", "how", "do", "you", "do"};
Arrays.sort(keys);
String[] uniqueKeys;
int count = 0;
System.out.println(text);
uniqueKeys = getUniqueKeys(keys);
for(String key: uniqueKeys)
{
if(null == key)
{
break;
}
for(String s : keys)
{
if(key.equals(s))
{
count++;
}
}
System.out.println("Count of ["+key+"] is : "+count);
count=0;
}
}
private static String[] getUniqueKeys(String[] keys)
{
String[] uniqueKeys = new String[keys.length];
uniqueKeys[0] = keys[0];
int uniqueKeyIndex = 1;
boolean keyAlreadyExists = false;
for(int i=1; i<keys.length ; i++)
{
for(int j=0; j<=uniqueKeyIndex; j++)
{
if(keys[i].equals(uniqueKeys[j]))
{
keyAlreadyExists = true;
}
}
if(!keyAlreadyExists)
{
uniqueKeys[uniqueKeyIndex] = keys[i];
uniqueKeyIndex++;
}
keyAlreadyExists = false;
}
return uniqueKeys;
}
Output:
how are you how do you do
Count of [how] is : 2
Count of [are] is : 1
Count of [you] is : 2
Count of [do] is : 2
Are you looking some sort of this
public static void main(String[] args){
String[] arr = new String[5];
arr[0] = "One";
arr[1] = "Two";
arr[2] = "One";
arr[3] = "Three";
arr[4] = "Two";
List<String> lstString = Arrays.asList(arr);
Collections.sort(lstString);
for(String eachString : arr){
System.out.println("Frequency of " + eachString + " is " + getFrequency(eachString,lstString));
}
}
private static int getFrequency(String word, List lstOfString){
int frequency = 1;
if(lstOfString != null && lstOfString.size() > 0){
int firstIndex = lstOfString.indexOf(word);
int lastIndex = lstOfString.lastIndexOf(word);
frequency += lastIndex - firstIndex;
}
return frequency;
}
Result :
Frequency of One is 2
Frequency of One is 2
Frequency of Three is 1
Frequency of Two is 2
Frequency of Two is 2

Random password generation

I have written a code for random password generation.There are a string from where i have to make the password.so i try to categorize the string according to uppercase array , lower case array and digit array. but here comes a problem when..
for(int k=0;k<Length;k++){
if(asc[k]>=65 && asc[k]<=90){
UpperCase[k]=(char)asc[k];
}
else if(asc[k]>=48 && asc[k]<=57){
Digit[k]=(char)asc[k];
}
else {
Mixed[k]=(char)asc[k];
}
}
is executed it counts some space which i don't want.coding looks like ugly sry for my poor coding.i know there is a lot more way to solve it but i want to go through this.here is my code. here is my code
import java.util.Random;
public class Randompassgeneration
{
final int MAX_LENGTH = 20;
final int MIN_LENGTH = 3;
char[] password=new char[25];
int [] asc=new int[18];
char[] UpperCase=new char[25];
char[] Digit=new char[25];
char[] Mixed=new char[25];
public void generate(String allowedCharacters)
{
int Length=allowedCharacters.length();
for (int i=0;i<Length;i++)
{
asc[i]=(int)allowedCharacters.charAt(i);
}
for (int k=0;k<Length;k++)
{
if (asc[k]>=65 && asc[k]<=90)
{
UpperCase[k]=(char)asc[k];
}
else if (asc[k]>=48 && asc[k]<=57)
{
Digit[k]=(char)asc[k];
}
else
{
Mixed[k]=(char)asc[k];
}
}
String rp=null;
StringBuilder Strbld=new StringBuilder();
Random rnd=new Random();
int ranStrLen=rnd.nextInt(MAX_LENGTH - MIN_LENGTH + 1) + MIN_LENGTH;
Strbld.append(UpperCase[rnd.nextInt(UpperCase.length)]);
Strbld.append(Digit[rnd.nextInt(Digit.length)]);
for (int m=0; m<ranStrLen-2; m++)
{
Strbld.append(Mixed[rnd.nextInt(Mixed.length)]);
}
System.out.print(ranStrLen +"->"+ Strbld.toString());
}
public static void main(String[] args)
{
String allowedCharacters = "weakPasSWorD1234$*";
Randompassgeneration t=new Randompassgeneration();
t.generate(allowedCharacters);
}
}
Any kind of suggestion?
I would generate the minimum number of characters, digits and symbols. Fill the other characters randomly and shuffle the result. This way it will comply with your minimum requirements with a minimum of effort.
public static String passwordGenerator() {
List<Character> chars = new ArrayList<>();
Random rand = new Random();
// min number of digits
for (int i = 0; i < 1; i++) chars.add((char) ('0' + rand.nextInt(10)));
// min number of lower case
for (int i = 0; i < 2; i++) chars.add((char) ('a' + rand.nextInt(26)));
// min number of upper case
for (int i = 0; i < 1; i++) chars.add((char) ('A' + rand.nextInt(26)));
// min number of symbols
String symbols = "!\"$%^&*()_+{}:#~<>?,./;'#][=-\\|'";
for (int i = 0; i < 1; i++) chars.add(symbols.charAt(rand.nextInt(symbols.length())));
// fill in the rest
while (chars.size() < 8) chars.add((char) ('!' + rand.nextInt(93)));
// appear in a random order
Collections.shuffle(chars);
// turn into a String
char[] arr = new char[chars.size()];
for (int i = 0; i < chars.size(); i++) arr[i] = chars.get(i);
return new String(arr);
}
public static void main(String... args) {
for (int i = 0; i < 100; i++)
System.out.println(passwordGenerator());
}
"is executed it counts some space which i don't want"
The white space is beacuse of your For loop
You were using the variable k for all the arrays,which resulted into the incremented value of k each time.So,this was making "gaps" between your arrays.
Change it to:
int point1=0,point2=0,point3=0;
for (int k=0;k<Length;k++)
{
if (asc[k]>=65 && asc[k]<=90)
{
UpperCase[point1]=(char)asc[k];point1++;
continue;
}
else if (asc[k]>=48 && asc[k]<=57)
{
Digit[point2]=(char)asc[k];point2++;
continue;
}
else
{
Mixed[point3]=(char)asc[k];point3++;
}
}
System.out.println(UpperCase);
System.out.println(Digit);
System.out.println(Mixed);
OutPut:
PSWD
1234
weakasor$*
Ok if not mistaken you want to parse the password generated and want put them in separate array. Here is the snippet for uppercase.
ArrayList<Character> uppercase = new ArrayList<Character>();
char pass[] = password.toCharArray();
for(char c: pass){
if(Character.isUpperCase(c))
uppercase.add(c);
}
If you want a random string, you could do:
public String getRandomString(){
return UUID.randomUUID().toString();
}
If you want to make it consistent with some source String, you could do:
public String getConsistentHash(String source){
return UUID.nameUUIDFromBytes(source.getBytes()).toString();
}
This latter method will return the same String for the same source String.
If there is a only a limited set of characters you want to use, you could just replace the unwanted chars. Suppose you have have created "randomString" as above, you create "randomString1" with:
randomString1 = UUID.fromString(randomString);
Now replace the unwanted chars in "randomString" with the chars in "randomString1". You could repeat this if necessary.
If you do not care for a minimum size/spread, you could just remove the chars.
Good luck.

Categories

Resources