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.
Related
so I have task to double number of letter "a" every time it occurs in a string.
For example sentence "a cat walked on the road" , at the end must be "aa caaaat waaaaaaaalked on the roaaaaaaaaaaaaaaaa" . I had something like this on my mind but it doubles every charachter, not only "a".
public static void main(String[] args) {
String s = "a bear walked on the road";
String result = "";
int i = 0;
while(i<s.length()){
char a = s.charAt(i);
result = result + a + a;
i++;
}
System.out.println(result);
}
You need to check what the char a is (in your case, 'a'). Additionally, you do not repeat the characters more than twice in your code, hence not getting the answer you expected: result = result + a + a only adds 'a' twice, not giving you: "aa caaaat waaaaaaaalked...".
Here is the solution:
public static void main(String[] args) {
String s = "a bear walked on the road";
String result = "";
char lookingFor = 'a'; // Can change this to whatever is needed
int counter = 2;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == lookingFor) { // The current character is what we need to be repeated.
// Repeat the character as many times as counter is (each loop: 2, 4, 6, 8, ...)
for (int j = 0; j < counter; j++) {
result += lookingFor;
}
counter *= 2; // Double counter at every instance of 'a'
}
else { // The current char is not what we are looking for, so we just add it to our result.
result += s.charAt(i);
}
}
System.out.println(result);
}
The problems are:
you are doubling every character because you are not testing if it is an 'a' or not.
and you are not doubling the substitution each time.
Here is a modified version of your solution.
String s = "a bear walked on the road";
String result = "";
String sub = "aa";
int i = 0;
while(i<s.length()){
// get the character
char ch = s.charAt(i++);
//if it an a, append sub to result
// and double sub.
if (ch == 'a') {
result += sub;
sub += sub;
} else {
// otherwise, just append the character
result += ch;
}
}
Here is another way.
check each character and double the replacement each time an a is encountered.
String str = "a cat walked on the road";
StringBuilder sb = new StringBuilder();
String sub = "a";
for (String s : str.split("")) {
sb.append(s.equals("a") ? (sub += sub) : s);
}
System.out.println(sb);
prints
aa caaaat waaaaaaaalked on the roaaaaaaaaaaaaaaaad
Try this out:
public static void main(String[] args) {
char letterToSearch = 'a'
String myString = "a bear walked on the road";
StringBuilder result = new StringBuilder();
int occurrance = 0;
for (int i = 0; i < myString.length(); i++){
char currChar = myString.charAt(i);
if (currChar == letterToSearch){
occurrance+=1;
for (int j = 0; j < 2*occurrance; j++){
result.append(currChar);
}
} else {
result.append(currChar);
}
}
System.out.println(result);
}
The variable occurrance keeps track of how many as you have.
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++;
}
I am trying to create a program that outputs ten lowercase letter characters - five vowels and five consonants. In order to do this, I have started by creating a char array with a range between 'a' and 'z' called letters[] with size 10. Once the array is filled, I will print the output with the use of a format string containing everything in the array.
My question is, how would I make the program output exactly five of each type (and keep the order of the characters printed completely random)? I have considered using the switch statement with a case each for consonants and vowels, but my ideas so far seem over-complicated and inelegant.
Code so far:
char letters[] = new char[10];
for(int i = 0; i < letters.length; i++){ //Open for
letters[i] = (char)(97 + Math.random() * 26);
char idx = letters[i];
System.out.printf("%s",idx);
} //End for
If you don't mind a somewhat more String-related solution, here is one. I am assuming that you don't want any consonant or vowel repeated in the output string, so this algorithm removes letters for consideration once they've been used. It also provides a bit more of a generic letter picker routine that's not really limited to vowels and consonants.
import java.lang.StringBuilder;
public class Shuffler {
public static String CONSONANTS = "bcdfghjklmnpqrstvwxyz";
public static String VOWELS = "aeiou";
/*
* Returns a new string that is a combination of the current string and 'count'
* characters from the source string (using any character in the source string
* no more than one time).
*/
public static String shuffleIntoString(String current, String source, int count) {
if (current == null || source == null || count < 0 || count > source.length()) {
System.out.println("Error in parameters to shuffleIntoString");
return null;
}
StringBuilder retval = new StringBuilder(current); // build up by inserting at random locations
StringBuilder depletedSource = new StringBuilder(source); // remove characters as they are used
for (int i = 0; i < count; i++) {
int pick = (int) (Math.random() * depletedSource.length());
int whereToInsert = (int) (Math.random() * retval.length());
retval = retval.insert(whereToInsert, depletedSource.charAt(pick));
depletedSource.deleteCharAt(pick);
}
return retval.toString();
}
public static void main(String[] args) {
Shuffler shuf = new Shuffler();
for (int i = 0; i < 10; i++) {
String result = shuf.shuffleIntoString("", shuf.CONSONANTS, 5);
result = shuf.shuffleIntoString(result, shuf.VOWELS, 5);
System.out.println(result);
}
}
}
And the output looks like this:
kqoibauzed
uhcawoerib
afdzoemius
yuagocibej
eiuhaokcyq
ouveiawrxn
uyaiveomxn
ruxeoalhij
uraliwfeoc
afoutiesmr
This will achieve what you desire if you are content with using ArrayLists. To generate the random chars you could generate a number within the index of the corresponding char Strings and add the value to the ArrayList. Collections is a helpful Class that you can use to shuffle the list.
List<Character> list = new ArrayList<>();
String consonants = "bcdfghjklmnpqrstvwxyz";
String vowels = "aeiou";
Random r = new Random();
for (int i = 0; i < 5; i++) {
list.add(consonants.charAt(r.nextInt(consonants.length()))); // Add consonant
list.add(vowels.charAt(r.nextInt(vowels.length()))); // Add vowel
}
Collections.shuffle(list);
for (Character c : list) {
System.out.println(c);
}
I don't seen any rules about duplicated but if you want you can remove latters from arrays after selection.
List<Character> vowels = Arrays.asList('a', 'e', 'i', 'o', 'u');
List<Character> consonants = new ArrayList<>();
for (char latter = 'a'; latter <= 'z'; latter++) {
if(!vowels.contains(latter)) {
consonants.add(latter);
}
}
final Random random = new Random();
int vowelsRemain = 5;
int consonantsRemain = 5;
List<Character> result = new ArrayList<>();
while (vowelsRemain > 0 && consonantsRemain > 0) {
final boolean generateVowel = random.nextBoolean();
final char randomLatter;
if(generateVowel) {
randomLatter = vowels.get(random.nextInt(vowels.size()));
vowelsRemain--;
} else {
randomLatter = consonants.get(random.nextInt(consonants.size()));
consonantsRemain--;
}
result.add(randomLatter);
}
while (vowelsRemain > 0) {
final Character randomVowel = vowels.get(random.nextInt(vowels.size()));
result.add(randomVowel);
vowelsRemain--;
}
while (consonantsRemain > 0) {
final Character randomConsonant = consonants.get(random.nextInt(consonants.size()));
result.add(randomConsonant);
consonantsRemain--;
}
System.out.println(result);
I have to make a program which needs to generate three words of 10 letters, with each having 1st letter as UpperCase. Afterwards, I have to combine those three words into one word and that word again should have only its 1st letter as UpperCase.
So far I managed do to this:
public static void main(String[] args) {
new DZ05();
}
public DZ05() {
Random word = new Random();
for(int i = 0; i<= 10; i++) {
int x = word.nextInt(25)+97;
if(i==0) {
tekst1+= Character.toUpperCase((char) (x));
} else {
tekst1+= (char) (x);
}
}
for(int i = 0; i<= 10; i++) {
int x = word.nextInt(25)+97;
if(i==0) {
tekst2+= Character.toUpperCase((char) (x));
} else {
tekst2+= (char) (x);
}
}
for(int i = 0; i<= 10; i++) {
int x = word.nextInt(25)+97;
if(i==0) {
tekst3+= Character.toUpperCase((char) (x));
} else {
tekst3+= (char) (x);
}
}
System.out.println(tekst1);
System.out.println(tekst2);
System.out.println(tekst3);
And thats where I dont know what else to do
You should consider breaking the problem down into multiple methods, and have your main program call those methods.
For example, you could build something like:
private String randomWord(int length) { ... }
private String titleCase(String word) { ... }
Your main program could call them and be easier to follow:
String fiveLetterWord = randomWord(5);
String titleCasedWord = titleCase("threeConcatenatedWords");
I will make the assumption that tekst1, tekst2 and tekst3 are Strings, as this is not shown in the provided code.
Firstly, your for loops generate words with 11 not 10 letters. It should be:
for (int i = 0; i < 10; i++)
Now, there are various methods from the String class that you can use to achieve your goal. You can use String concatenation to combine the words:
String combinedWords = tekst1 + tekst2 + tekst3;
Use the String methods toLowerCase and substring to get all the letters except the first in lower case:
String lowerCaseChars = combinedWords.toLowerCase().substring(1);
Use the String method charAt to get the first letter:
char upperChar = combinedWords.charAt(0);
Finally, combining upperCharand lowerCaseChars gives you your desired result:
String result = upperChar + lowerCaseChars
I have a homework assignment to count specific chars in string.
For example: string = "America"
The output should be = a appear 2 times, m appear 1 time, e appear 1 time, r appear 1 time, i appear 1 time and c appear 1 time
public class switchbobo {
/**
* #param args
*/ // TODO Auto-generated method stub
public static void main(String[] args){
String s = "BUNANA";
String lower = s.toLowerCase();
char[] c = lower.toCharArray(); // converting to a char array
int freq =0, freq2 = 0,freq3 = 0,freq4=0,freq5 = 0;
for(int i = 0; i< c.length;i++) {
if(c[i]=='a') // looking for 'a' only
freq++;
if(c[i]=='b')
freq2++;
if (c[i]=='c') {
freq3++;
}
if (c[i]=='d') {
freq4++;
}
}
System.out.println("Total chars "+c.length);
if (freq > 0) {
System.out.println("Number of 'a' are "+freq);
}
}
}
code above is what I have done, but I think it is not make sense to have 26 variables (one for each letter). Do you guys have alternative result?
Obviously your intuition of having a variable for each letter is correct.
The problem is that you don't have any automated way to do the same work on different variables, you don't have any trivial syntax which helps you doing the same work (counting a single char frequency) for 26 different variables.
So what could you do? I'll hint you toward two solutions:
you can use an array (but you will have to find a way to map character a-z to indices 0-25, which is somehow trivial is you reason about ASCII encoding)
you can use a HashMap<Character, Integer> which is an associative container that, in this situation, allows you to have numbers mapped to specific characters so it perfectly fits your needs
You can use HashMap of Character key and Integer value.
HashMap<Character,Integer>
iterate through the string
-if the character exists in the map get the Integer value and increment it.
-if not then insert it to map and set the integer value for 0
This is a pseudo code and you have to try coding it
I am using a HashMap for the solution.
import java.util.*;
public class Sample2 {
/**
* #param args
*/
public static void main(String[] args)
{
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
String test = "BUNANA";
char[] chars = test.toCharArray();
for(int i=0; i<chars.length;i++)
{
if(!map.containsKey(chars[i]))
{
map.put(chars[i], 1);
}
map.put(chars[i], map.get(chars[i])+1);
}
System.out.println(map.toString());
}
}
Produced Output -
{U=2, A=3, B=2, N=3}
In continuation to Jack's answer the following code could be your solution. It uses the an array to store the frequency of characters.
public class SwitchBobo
{
public static void main(String[] args)
{
String s = "BUNANA";
String lower = s.toLowerCase();
char[] c = lower.toCharArray();
int[] freq = new int[26];
for(int i = 0; i< c.length;i++)
{
if(c[i] <= 122)
{
if(c[i] >= 97)
{
freq[(c[i]-97)]++;
}
}
}
System.out.println("Total chars " + c.length);
for(int i = 0; i < 26; i++)
{
if(freq[i] != 0)
System.out.println(((char)(i+97)) + "\t" + freq[i]);
}
}
}
It will give the following output:
Total chars 6
a 2
b 1
n 2
u 1
int a[]=new int[26];//default with count as 0
for each chars at string
if (String having uppercase)
a[chars-'A' ]++
if lowercase
then a[chars-'a']++
public class TestCharCount {
public static void main(String args[]) {
String s = "america";
int len = s.length();
char[] c = s.toCharArray();
int ct = 0;
for (int i = 0; i < len; i++) {
ct = 1;
for (int j = i + 1; j < len; j++) {
if (c[i] == ' ')
break;
if (c[i] == c[j]) {
ct++;
c[j] = ' ';
}
}
if (c[i] != ' ')
System.out.println("number of occurance(s) of " + c[i] + ":"
+ ct);
}
}
}
maybe you can use this
public static int CountInstanceOfChar(String text, char character ) {
char[] listOfChars = text.toCharArray();
int total = 0 ;
for(int charIndex = 0 ; charIndex < listOfChars.length ; charIndex++)
if(listOfChars[charIndex] == character)
total++;
return total;
}
for example:
String text = "america";
char charToFind = 'a';
System.out.println(charToFind +" appear " + CountInstanceOfChar(text,charToFind) +" times");
Count char 'l' in the string.
String test = "Hello";
int count=0;
for(int i=0;i<test.length();i++){
if(test.charAt(i)== 'l'){
count++;
}
}
or
int count= StringUtils.countMatches("Hello", "l");