skip to main | skip to sidebar

Java Programs and Examples with Output

Pages

▼
 
  • RSS
  • Twitter
Showing posts with label Random Function. Show all posts
Showing posts with label Random Function. Show all posts
Sunday, October 14, 2012

Java Random Alpha Numeric string generation

Posted by Raju Gupta at 10:00 PM – 0 comments
 
Generate a random alpha numeric string whose length is the number of characters specified. Characters will be chosen from the set of alpha-numeric characters. Count is the length of random string to create.

private static final String ALPHA_NUMERIC_STRING = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; 
public static String randomAlphaNumeric(int count) { 
 StringBuilder builder = new StringBuilder(); 
 while (count-- != 0) { 
  int character = (int)(Math.random()*ALPHA_NUMERIC_STRING.length()); 
  builder.append(ALPHA_NUMERIC_STRING.charAt(character)); 
 } 
 return builder.toString(); 
}


[ Read More ]
Read more...
Thursday, September 13, 2012

Generate Random Number in Java

Posted by Admin at 2:18 PM – 0 comments
 

import java.util.Random;   
  
/** Generate random integers in a certain range. */  
  
public final class RandomNumbersRange    
{   
     
    public static final void main(String aArgs[])   
    {         
                  int START = 1;   
                  int END = 10;   
                  Random random = new Random();   
       
                 for (int count = 1; count <= 10; ++count)   
                {   
                     showRandomInteger(START, END, random);   
                }       
     }   
     
  private static void showRandomInteger(int aStart, int aEnd, Random aRandom){   
    if ( aStart > aEnd ) {   
      throw new IllegalArgumentException("Start cannot exceed End.");   
    }   
    //get the range, casting to long to avoid overflow problems   
    long range = (long)aEnd - (long)aStart + 1;   
    // compute a fraction of the range, 0 <= frac < range   
    long fraction = (long)(range * aRandom.nextDouble());   
    int randomNumber =  (int)(fraction + aStart);       
    log("Generated : " + randomNumber);   
  }   
     
  private static void log(String aMessage){   
    System.out.println(aMessage);   
  }   
}

[ Read More ]
Read more...
Saturday, February 18, 2012

Demonstrate Random Gaussian values

Posted by Admin at 4:13 AM – 0 comments
 
Here is a Java Program to Demonstrate random Gaussian values.

import java.util.Random;

class RandDemo {
  public static void main(String args[]) {
    Random r = new Random();
    double val;
    double sum = 0;
    int bell[] = new int[10];

    for(int i=0; i<100; i++) {
      val = r.nextGaussian();
      sum += val;
      double t = -2;
      for(int x=0; x<10; x++, t += 0.5)
        if(val < t) {
          bell[x]++;
          break;
        }
    }
    System.out.println("Average of values: " +
                        (sum/100));

    // display bell curve, sideways
    for(int i=0; i<10; i++) {
      for(int x=bell[i]; x>0; x--)
        System.out.print("*");
      System.out.println();
    }
  }
}

Output of Above Java Program
Average of values: 0.13714951059857725
*
*********
****
************
*****************
*****************
***********************
*********
*****
*

[ Read More ]
Read more...
Tuesday, January 17, 2012

Java Program to Store a deck of 52 cards in a Linked List

Posted by Admin at 8:14 AM – 0 comments
 
Write a program to store a deck of 52 cards in a linked list in random sequence using a Random class object. You can represent a card as a two-character string "1C" for the ace of clubs, "JD" for the jack of diamonds, and so on. Output the cards from the linked list as four hands of 13 cards.

import java.util.Vector;
import java.util.LinkedList;
import java.util.Random;
import java.util.ListIterator;

public class DealCards {
  public static void main(String[] args) {
    String[] suits = {"C", "D", "H", "S"};
    String[] cardValues = { "1","2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"};

    int cardsInDeck = 52;
    Vector<String> deck = new Vector<String>(cardsInDeck);
    LinkedList<String> shuffledDeck = new LinkedList<String>();
    Random chooser = new Random();                                     // Card chooser

    // Load the deck
    for(String suit : suits) {
      for(String cardValue : cardValues) {
        deck.add(cardValue + suit);
      }
  }

    // Select cards at random from the deck to transfer to shuffled deck
    int selection = 0;                                                 // Selected card index
    for(int i = 0 ; i < cardsInDeck ; ++i) {
      selection = chooser.nextInt(deck.size());
      shuffledDeck.add(deck.remove(selection));
    }

    // Deal the cards from the shuffled deck into four hands
    StringBuffer[] hands = { new StringBuffer("Hand 1:"), new StringBuffer("Hand 2:"),
                             new StringBuffer("Hand 3:"), new StringBuffer("Hand 4:")};
    ListIterator<String> cards = shuffledDeck.listIterator();

    while(cards.hasNext()) {
      for(StringBuffer hand : hands) {
        hand.append(' ').append(cards.next());
      }
    }

    // Display the hands
    for(StringBuffer hand : hands) {
      System.out.println(hand);
    }
  }
}

Output of Above Java Program
Hand 1: 3D KS 8C 9S 10D 4D 5C JC 8D 1C 5S 10C 7C
Hand 2: 5D 1H 6H 7H 5H 3H KH 6D 10S QC 9D 7S 3C
Hand 3: 1D 9C QH 2S QD 2C 6C JH 8H KD JD 4H 7D
Hand 4: 9H 1S 4C 3S 10H KC 2H 4S QS 8S 2D 6S JS
[ Read More ]
Read more...
Monday, January 16, 2012

Use a Formatter object to format 20 random values of type double between –50 and +50

Posted by Admin at 9:13 AM – 0 comments
 
Use a Formatter object to format 20 random values of type double between –50 and +50 and output the entire set of 20 in a single call of System.out.print() or System.out.println().

import java.util.Formatter;
import static java.lang.Math.random;

public class FormatToString {
  public static void main(String[] args) {
    double[] data = new double[20];

    for (int i = 0 ; i < data.length ; ++i) {
      data[i] = 100.0*random() - 50.0;
    }

    StringBuilder buf = new StringBuilder();          // Buffer to hold output
    Formatter formatter = new Formatter(buf);         // Formatter to format data into buf
    int i = 0;
    for(double x : data) {
      formatter.format("%4d)%+7.2f", ++i, x);
      if(i%5 == 0) {
        formatter.format("%n");
      }
    }
    System.out.println(buf);                          // Output all the values in one go
  }
}


Output of Above Java Program


   1) +46.53   2)  -5.14   3)  -3.81   4) -45.54   5) +32.27
   6) -23.71   7) +47.19   8) +44.52   9) -19.52  10) -35.47
  11)  -9.32  12) -28.05  13) +44.03  14) -46.65  15)  -5.68
  16) +46.42  17)  -8.72  18) -13.47  19) -44.96  20) +46.57

[ Read More ]
Read more...

Write a program to generate 20 random values of type double between -50 and +50

Posted by Admin at 9:11 AM – 0 comments
 
Write a program to generate 20 random values of type double between -50 and +50 and use the printf() method for System.out to display them with two decimal places in the following form:

   1) +35.93   2) -46.94   3) +42.27   4) +32.09   5) +29.21
   6) +13.87   7) -47.87   8) +30.67   9) -25.20  10) +29.67
  11) +48.62  12)  +6.70  13) +28.97  14) -41.64  15) +16.67
  16) +17.01  17)  +9.62  18) -15.21  19)  +7.46  20)  +4.09
 
import static java.lang.Math.random;

public class FormatDoubleData {
  public static void main(String[] args) {
    double[] data = new double[20];

    for (int i = 0 ; i < data.length ; ++i) {
      data[i] = 100.0*random() - 50.0;
    }
    int i = 0;
    for(double x : data) {
      System.out.printf("%4d)%+7.2f", ++i, x);
      if(i%5 == 0) {
        System.out.println();
      }
    }
  }
}


Output of Above Java Program


   1) +20.79   2) +34.37   3) -49.38   4) +15.51   5) -23.63
   6) +41.13   7)  -3.22   8) +48.90   9)  +1.98  10)  -9.97
  11)  -0.05  12) +27.93  13) +22.23  14) -15.53  15) -11.51
  16) -32.27  17) +34.89  18) +49.76  19) +31.99  20) -25.20
[ Read More ]
Read more...
Saturday, January 7, 2012

Generate Random Number Using Math.Random Function in JAVA

Posted by Admin at 1:18 AM – 0 comments
 
Here is Program to Get a Random Number between 0 to Passed Argument
public class RandomInt { 
    public static void main(String[] args) { 
        int N = Integer.parseInt(args[0]);

        // a pseudo-random real between 0.0 and 1.0
        double r = Math.random(); 

        // a pseudo-random integer between 0 and N-1
        int n = (int) (r * N);

        System.out.println("Your random integer is: " + n);
    }
}

/*************************************
 *  % java RandomInt 100
 *  Your random integer is: 55
 *
 *  % java RandomInt 100
 *  Your random integer is: 3
 *
 *************************************/


Explanation of Random Number Program:
In this Java Random Program, we have one argument for number and then we are generating random number using Math.random() function.
Math.random() function always generate the value between 0 to 1 so if you want to generate the value different than this then you should multiply your number to Random Generated Value.
 After multiplying the number with Generated Random number we will get the our Random Number.
[ Read More ]
Read more...
Older Posts
Subscribe to: Posts ( Atom )
  • Popular
  • Recent
  • Archives
Powered by Blogger.
 
 
 
© 2011 Java Programs and Examples with Output | Designs by Web2feel & Fab Themes

Bloggerized by DheTemplate.com - Main Blogger