DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

+ Reply to Thread
Results 1 to 2 of 2

Thread: Random numbers

  1. #1
    Join Date
    Oct 2004
    Posts
    4

    Random numbers

    I'm doing a java program using random numbers.
    I would like to avoid that each generated number, besides unique, is different from its index in array - for instance, the first number in array is not number 1, the second is not number 2, the third not number 3, and so one.
    Can someone help ?
    Thatīs my relevant code :


    boolean isRepeated = false;
    int [] rNums = new int [t1];

    for (int x = 0 ; x < t1 ; x++)
    {

    do
    {
    isRepeated = false;
    rNums [x] = (int) ((Math.random () * t1) + 1);
    for (int y = 0 ; y < x ; y++)
    {
    if (rNums [x] == rNums [y])
    {
    isRepeated = true;
    break;
    }
    }
    }
    while (isRepeated);

  2. #2
    Join Date
    Aug 2003
    Posts
    313
    Java arrays are indexed starting at 0, so is it that you don't want the first element in an array to be 0 or you don't want it to be 1?
    You could just do something like this:
    Code:
    public static int randNotNum(int max, int num) {
      do {
        int res = (int) ((Math.random () * max) + 1);
        if( res != num ) return res;
      } while( true );
    }
    Then just make calls and pass in the maximum number and the number that you don't want to get back.

    Hope this helps.
    ~evlich

Similar Threads

  1. Random Numbers on button
    By daina in forum Java
    Replies: 3
    Last Post: 10-12-2005, 01:35 AM
  2. Database & Random Numbers
    By Suze in forum VB Classic
    Replies: 2
    Last Post: 05-10-2005, 03:41 PM
  3. generating unique random numbers
    By Dave in forum Java
    Replies: 3
    Last Post: 05-14-2002, 08:04 PM
  4. random numbers
    By max in forum Java
    Replies: 2
    Last Post: 04-30-2001, 03:08 PM
  5. Replies: 0
    Last Post: 08-25-2000, 07:54 PM

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


Top DevX Stories

Easy Web Services with SQL Server 2005 HTTP Endpoints
JavaOne 2005: Java Platform Roadmap Focuses on Ease of Development, Sun Focuses on the "Free" in F.O.S.S.
Wed Yourself to UML with the Power of Associations
Microsoft to Add AJAX Capabilities to ASP.NET
IBM's Cloudscape Versus MySQL


Sponsored Links