Post Reply 
 
Thread Rating:
  • 0 Votes - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Java] String randomization example
02-16-2010, 11:34 PM (This post was last modified: 02-16-2010 11:46 PM by Alphablend.)
Post: #1
[Java] String randomization example
The task was to make a program which requires user's input of length of the array. Elements of that array are strings which are randomly generated. The length of every string is a random value from range 0-20. The probability of getting the upper case letter is twice bigger than the lower case letter.

I did a similar example in Python:
[Python] Function for random String

Code:
import java.util.Random;
import cs1.*;
public class example{
    //Function which generates the length (up to 20) and the elemengs of string
    static String randString(){
        String word="";
        Random rand=new Random();
        int length=rand.nextInt(20);
            for (int i=0;i<length;i++){
                int BS_letter=rand.nextInt(2);
                int n=rand.nextInt(25);
                char S_letter=(char)(97+n);
                char B_letter=(char)(65+n);
                if (BS_letter==0)
                    word+=S_letter;
                else
                    word+=B_letter;
        }
        return word;
    }
    //Regular function to print an array, which you can use in similar programs
    static void printArray(String[] a, int n){
        for (int i=0;i<n;i++)
        System.out.print(a[i]+"\t");
        System.out.println();
    }
    public static void main(String[]args){
        System.out.println("Enter length of the array: ");
        int n=Keyboard.readInt();
        String[] a=new String[n];
        for (int i=0;i<n;i++)
            a[i]=randString();
        printArray(a,n);
    }
}

This is what you get when you try out the program:
Code:
Enter length of the array:
5
efmXncKvLYQcOHjDT   nePUEA  IAjX    NcR QrIXpI

.rar  example.rar (Size: 565 bytes / Downloads: 0)
Find all posts by this user
Quote this message in a reply
02-16-2010, 11:47 PM
Post: #2
RE: [Java] String randomization example
Very good task and interesting solution. It is good to see a task with probability !

There's a fine line between genius and insanity. I have erased this line.
Oscar Levant
There's a fine line between an administrator and black hat hacker. I have erased this line.
Dr DEBCOL
Visit this user's website Find all posts by this user
Quote this message in a reply
Post Reply 


Forum Jump:


 Quick Theme: