0

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]);
        }
    }
}
3
  • 2
    Do you get some error? What is the problem? Also it would be nice to name variables in english. Commented Mar 20, 2014 at 12:45
  • Unique random numbers it seems. Just use a Set, keep putting into it until it has the right size. Commented Mar 20, 2014 at 12:46
  • 3
    "everything seems okay, but doesn't work" could you please clarify ? What does not work ? What do you want exactly ? Do the numbers from 0 to 9 have to appear exactly once, randomly sorted ? Or do you want random numbers between 0 and 9 in your array ? Commented Mar 20, 2014 at 12:49

4 Answers 4

4

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()]);
Sign up to request clarification or add additional context in comments.

Comments

1

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 ints to boxed Integers.
  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().

Comments

0
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));
      }
   }
}

Comments

0

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

2 Comments

I guess the OP wants integers, to start with ;)
Ya i was using that to find random indices for an array forgot to replace it :P

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.