1

i am getting an unexpected output to generate lower case random letters - my code is

public class CountLettersInArrayDemo {

public static void main(String[] args) {
    // TODO Auto-generated method stub

    CountLettersInArray ca = new CountLetterInArray();

    char [] chars;

    chars = ca.setCreateArray();
    System.out.println(chars);

public class CountLettersInArray {

CountLettersInArray()
{}
//method to create an array
public char[] setCreateArray()
{
    //declare an array
    char [] chars = new char[100];
    //initialize an array with random characters

    for (int i=0;i<chars.length;i++)
    {
        chars[i]=(char)('a' + Math.random() * ('z' + 'a' -1));          
    }
    return chars;
}
}

output is -

uěýyĬõĒēÕø»İäĂº±«Ċþÿd¢¼Ęÿuìăi±vÞ´Ĥč°ĩĒôĵ¶âþĂđďäÄĮÝă¤yÎĪÊíÆĭ××môÓâ¢ÓġÓÙĊïĺv×ĺî÷dĤĸt

Q: any ideas where the mistake is ? thanks

kasper_341
  • 85
  • 1
  • 9
  • `Math.random()` eventually use `Random.next()` internally, so don't use `Math.random()` since not only the performance is much worse but also the result's quality will not be as `Random.next()` or `Random.nextDouble()` http://stackoverflow.com/a/738651/995714 – phuclv Dec 17 '13 at 13:34
  • @luu - I keep your advise in mind. – kasper_341 Dec 17 '13 at 20:00

6 Answers6

1

try this

  chars[i]=(char)('a' + Math.random() * ('z' - 'a'));

or simply

  chars[i]=(char)('a' + Math.random() * 26);
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
  • What was his mistake? – Sachin Dec 17 '13 at 12:27
  • 1
    'z' - 'a' is 25, so the top line will never produce a 'z'. – Keppil Dec 17 '13 at 12:31
  • Sorry, I am not strong in math or Java but I noticed your second idea seems to generate results that may not be "nicely" random. I am getting a lot of repeating chars, like "bb" or even "sss" - I imagine the probability of 3 letters repeating is 1:26*26*26 but I seem to be able to always reproduce those if I try 40 times... – DraxDomax Jan 20 '20 at 19:40
  • (char)('a' + myRandom.nextInt(26)) - on the other hand, never seems to repeat (also suspicious!) – DraxDomax Jan 20 '20 at 19:41
1

There is small problem associated with your code,
You are using chars[i]=(char)('a' + Math.random() * ('z' + 'a' -1));

Instead try this,

for (int i=0;i<chars.length;i++)
{
    chars[i]=(char)('a' + Math.random() * ('z' - 'a') );          
}

or a little faster way,

char Diff = 'z' - 'a';
for (int i=0;i<chars.length;i++)
{
    chars[i]=(char)('a' + Math.random() * Diff);          
}

Just EXPLANATION You are trying to generate integers between a range using the simple formula,

Min + (int)(Math.random() * ((Max - Min) + 1))

But in your code you have made a small mistake Max + Min instead of Max - Min

Deepak Bhatia
  • 6,230
  • 2
  • 24
  • 58
  • i have tried the solution, but the output is between 1-5 not random lower case letters '1 2 3 4 5' – kasper_341 Dec 17 '13 at 12:56
  • @kasper_341 I have added `Min + (int)(Math.random() * ((Max - Min) + 1))` as just pointer what were you trying to achieve, buddy use `chars[i]=(char)('a' + Math.random() * ('z' - 'a') );` instead of `chars[i]=(char)('a' + Math.random() * ('z' + 'a' -1));` – Deepak Bhatia Dec 17 '13 at 13:14
  • @kasper_341 I have double checked the output it gives me correct result, have you made changes in `for-loop` of `setCreateArray` function – Deepak Bhatia Dec 17 '13 at 13:26
  • I have made changes but still same results - only changes were made as you suggested: `public char[] setCreateArray() { //declare an array char [] chars = new char[100]; //initialize an array with random characters for (int i=0;i – kasper_341 Dec 17 '13 at 13:45
  • @kasper_341 remove `+ 1` from `'z' + 'a' + 1` i.e. use `'z' - 'a'` instead – Deepak Bhatia Dec 17 '13 at 14:31
  • I fixed it..I had my eclipse settings messed up .. I tested both ways i.e. `('z' - 'a')` `e o q r u u k i g t h o c l q d v v v s n e a r k j o t t v x l p g l j o e r x h c a r x e q m v n p y r v d w s b l w s d f i g o q p n j t o a d d b t r i q d j k g p j b s q t q h p a s w r h h y ` and `('z' - 'a' +1)` -> `p i y x w k g a u r d z m h c u w z d h z r n b f t c z l u m z m b o b k l r k l f b d o y r s c a y l t k m c u l b k r i j t b t k h z z p e n w g x c r l y v k m d c v y c k o t u b i y d d t s a` it works now. adios – kasper_341 Dec 17 '13 at 19:51
  • @kasper_341 can you elaborate what settings were messed up – Deepak Bhatia Dec 18 '13 at 05:03
  • I mistakenly created a `.java` file in different project location, then manually copied class file to current working project i.e. CountLettersInArray.java, I noticed that I could not create new method to `dispayArray();` ERROR - `the method is undefined java` at this point I realized that there must something wrong with the project that I was working on. Re-creating the project solved the problem. – kasper_341 Dec 18 '13 at 10:26
0

What you could try is the following:

Random random = new Random();
for(int i = 0; i<chars.length;i++){
    chars[i] = (char)(random.nextInt('z'-'a') + 'a');
}
Toon Borgers
  • 3,638
  • 1
  • 14
  • 22
0

try this.it will generate 8 characters random String

public String randomString() {
    int len = 8;
    String alphaNumericString = "abcdefghijklmnopqrstuvwxyz1234567890";

    // creating the object for string builder
    StringBuilder sb = new StringBuilder(len);


    try {

        String PASSSTRING = alphaNumericString;
        // creating the object of Random class
        Random rnd = new Random();
        for (int i = 0; i < len; i++) {
            // generating random string
            sb.append(PASSSTRING.charAt(rnd.nextInt(PASSSTRING.length())));
        }
    } catch (Exception e) {
    e.printStackTrace();
    }

    // returning the random string
    return sb.toString();
}// randomString()
KhAn SaAb
  • 5,248
  • 5
  • 31
  • 52
0

don't reinvent the wheel. use commons-lang3

import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
...
randomAlphabetic(length).toLowerCase()
piotrek
  • 13,982
  • 13
  • 79
  • 165
0

How about this option: ( a+ Math.random() * b) - return a random number between a and a+b, excluding a+b 'a'to'z' Decimal value: 97 to 122;

Random rand = new Random();
char a  = (char) (97+(int)(Math.random()*25));
System.out.println(a);
Zoran Janjic
  • 111
  • 4