简体   繁体   中英

Generating a random array in Java

someone who just started here. Trying to create a program to generate an array full with numbers in specific range but in random order. I compile this, everything seems okay, but doesn't work. Anyone can clarify why?

EDIT: I want values from 1 to 10 to appear in the array in random order. Problem is, the main for loop keeps looping and I can not get result. And please don't offer any better or somehow advanced solutions. It's not about the solution, I am trying to learn and would like to know where the problem is with this code.

import java.util.*;
public class CustomSorter
{
    public static void main(String[] args)
    {
        int reqemlerinSayi = 10;
        int[] esasSiyahi= new int[reqemlerinSayi];
        Random random = new Random();
        int reqem;
        boolean toqqushur = false;

        for (int i = 0; i < esasSiyahi.length; i++)
        {
            reqem = random.nextInt(reqemlerinSayi-1)+1;
            for (int j = 0; j < esasSiyahi.length; j++)
            {
                if (esasSiyahi[j] == reqem)
                    toqqushur = true;
            }

            if (toqqushur)
                i--;
            else
                esasSiyahi[i] = reqem;

            toqqushur = false;
        }
        for (int i = 0; i < esasSiyahi.length; i++)
        {
            System.out.println(esasSiyahi[i]);
        }
    }
}

The expression random.nextInt(reqemlerinSayi-1) will generate only reqemlerinSayi-1 values, while you try to populate an array of length reqemlerinSayi . Remove the -1 .

A much easier way to populate an array of ints with numbers 1 - 10 is:

List<Integer> list = new ArrayList<>();
for (int num = 1; num <= 10; num++) list.add(num);
Collections.shuffle(list);
int[] array = new int[list.size()];
for (int idx = 0; idx < list.size(); idx++) array[idx] = list.get(idx);

And if you are happy with an array of Integers do:

    List<Integer> list = new ArrayList<>();
    for (int num = 1; num <= 10; num++) list.add(num);
    Collections.shuffle(list);
    Integer[] array = list.toArray(new Integer[list.size()]);

You could do this the following way in Java 8:

int lowInclusive = 5;
int highExcusive = 10;
List<Integer> randomList = new Random().ints(10, lowInclusive, highExcusive)
        .boxed()
        .collect(Collectors.toList());

This will do the following:

  1. Create an IntStream consisting of 10 random integers between 5 incusive and 10 exclusive.
  2. Maps all primitive int s to boxed Integer s.
  3. Collects the element in an ArrayList<Integer> via Collectors.toList() .

After having received more input over the requirements, it appears that you want all unique numbers, then consider the following:

int lowInclusive = 5;
int highExclusive = 10;
List<Integer> shuffledList = IntStream.range(lowInclusive, highExclusive)
        .limit(10)
        .boxed()
        .collect(Collectors.toList());
Collections.shuffle(shuffledList);

This does:

  • Create an IntStream of 5 to 10.
  • Limits the stream to 10 elements.
  • Boxes the elements to Integer .
  • Collects them in shuffledList .
  • Shuffles the list via Collections.shuffle() .
public class CustomSorter {
   public static void main(String[] args) {

      int min = 0;
      int max = 100;
      int sizeOfArray = 10;
      int[] anArray = new int[sizeOfArray];

      for(int x = 0; x < anArray.length(); x++) {
         anArray[x] = min + (int)(Math.random() * ((max - min) + 1));
      }
   }
}

For random numbers in a range, making a function would help a lot

Then you just have to iterate for the total number of random numbers to be found

class NewClass {

    public static void main(String[] args) {

        int startRange = 500;
        int endRange = 600;

       // create 50 random variable between 500 600

        double random[]= new double[50];

        for (int i = 0; i < random.length; i++) {

            random[i] = findRandomNumber(startRange, endRange);
            System.out.println(random[i]);

        }


    }

    public static double findRandomNumber(double aStart, double aEnd) {
        Random aRandom = new Random();
        if (aStart > aEnd) {
            throw new IllegalArgumentException("Start cannot exceed End.");
        }
        //get the range, casting to long to avoid overflow problems
        double range = aEnd - aStart + 1;
        // compute a fraction of the range, 0 <= frac < range
        double fraction = range * aRandom.nextDouble();
        double randomNumber = (fraction + aStart);
        return (randomNumber);
    }
}

OUTPUT

579.0386837850086
578.4240926611131
531.3635427714237
.
.  
.
538.4404995544475
510.7875548059947
582.3107995045374
557.5918170571055

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM