Java Random Int randomArray(int min, int max, int n)

Here you can find the source of randomArray(int min, int max, int n)

Description

Generate n random and different numbers within specified non-negative integer range

License

Apache License

Parameter

Parameter Description
min minimum of the range
max maximum of the range
n number to be generated

Declaration

public static int[] randomArray(int min, int max, int n) 

Method Source Code

//package com.java2s;
/**//from w  w w  .jav a  2  s.c  om
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

public class Main {
    /**
     * Generate n random and different numbers within
     * specified non-negative integer range
     * @param min minimum of the range
     * @param max maximum of the range
     * @param n number to be generated
     */
    public static int[] randomArray(int min, int max, int n) {
        if (n > (max - min + 1) || max < min || min < 0 || max < 0) {
            return null;
        }
        int[] result = new int[n];
        for (int i = 0; i < n; i++) {
            result[i] = -1;
        }

        int count = 0;
        while (count < n) {
            int num = (int) (Math.random() * (max - min)) + min;
            boolean flag = true;
            for (int j = 0; j < n; j++) {
                if (num == result[j]) {
                    flag = false;
                    break;
                }
            }
            if (flag) {
                result[count] = num;
                count++;
            }
        }
        return result;
    }
}

Related

  1. randomAlphaNum(int length)
  2. randomAlphanumeric(int count)
  3. randomAlphanumericString(int length)
  4. randomAlphaString(int length)
  5. randomArray(int len)
  6. randomBases(int n)
  7. randomBlock(byte[] block, int off, int len)
  8. randomByteArray(int length)
  9. randomByteArray(int size, byte from, byte to)