recursively finding two elements with the smallest difference in an array - java

I'm trying to recursively find two elements in an array with the smallest difference (assume the array is already sorted in an increasing order).
I've been trying to get my code to just return the smallest sum, but something seems to be not working right with the recursion.
public class SmallestDiff {
public static void main (String [] args){
int [] x = {1,3,6,9,126};
System.out.println(smallestDiff(x,4));
}
public static int smallestDiff (int [] array, int index){
int result;
if (index>0){
int diff = Math.abs((array[index]-array[index-1]));
result = Math.min (diff, smallestDiff(array,index-1));
}
else {
return array[0];
}
return result;
}
}

Your mistake is
return array[0];
array[0] is not a difference between values so should not be returned. The simplest way to fix your program is to replace this line with
return array[1] - array[0];

Try this :
public class SmallestDiff {
public static void main(String[] args) {
int[] x = { 1, 3, 6, 9, 126 };
int result;
if (x.length < 2) {
result = x[0];
}
else{
result = smallestDiff(x, x.length-1);
}
System.out.println(result);
}
public static int smallestDiff(int[] array, int index) {
if (index == 0) {
return Integer.MAX_VALUE;
}
int diff = (array[index] - array[index - 1]);
return Math.min(diff, smallestDiff(array, index - 1));
}
}
This solution prints the first element in case there is only one element in the array. Otherwise, it will always result the smallest difference between two elements.

If your array is sorted no need for recursion.
The code below solves the problem with iteration.
public class SmallestDiff {
public static void main(String[] args) {
int[] x = {1, 3, 6, 9, 126};
System.out.println(smallestDiff(x));
}
public static int smallestDiff(int[] array) {
int result = Integer.MAX_VALUE;
for (int i = 0; i < array.length - 1; i++) {
int diff = Math.abs((array[i] - array[i + 1]));
if (diff < result) {
result = diff;
}
}
return result;
}
}

Related

How would i rewrite this method recursivly? [duplicate]

I have a program that I'm trying to make for class that returns the sum of all the integers in an array using recursion. Here is my program thus far:
public class SumOfArray {
private int[] a;
private int n;
private int result;
public int sumOfArray(int[] a) {
this.a = a;
n = a.length;
if (n == 0) // base case
result = 0;
else
result = a[n] + sumOfArray(a[n-1]);
return result;
} // End SumOfArray method
} // End SumOfArray Class
But I'm getting three error which are all related, I believe, but I can't figure out why it is finding a type of null:
SumOfArray.java:25: sumOfArray(int[]) in SumOfArray cannot be applied to (int)
result = a[n] + sumOfArray(a[n-1]);
^
SumOfArray.java:25: operator + cannot be applied to int,sumOfArray
result = a[n] + sumOfArray(a[n-1]);
^
SumOfArray.java:25: incompatible types
found : <nulltype>
required: int
result = a[n] + sumOfArray(a[n-1]);
^
3 errors
The solution is simpler than it looks, try this (assuming an array with non-zero length):
public int sumOfArray(int[] a, int n) {
if (n == 0)
return a[n];
else
return a[n] + sumOfArray(a, n-1);
}
Call it like this:
int[] a = { 1, 2, 3, 4, 5 };
int sum = sumOfArray(a, a.length-1);
The issue is that a[n-1] is an int, whereas sumOfArray expects an array of int.
Hint: you can simplify things by making sumOfArray take the array and the starting (or ending) index.
a[n-1]
is getting the int at n-1, not the array from 0 to n-1.
try using
Arrays.copyOf(a, a.length-1);
instead
How about this recursive solution? You make a smaller sub-array which contains elements from the second to the end. This recursion continues until the array size becomes 1.
import java.util.Arrays;
public class Sum {
public static void main(String[] args){
int[] arr = {1,2,3,4,5};
System.out.println(sum(arr)); // 15
}
public static int sum(int[] array){
if(array.length == 1){
return array[0];
}
int[] subArr = Arrays.copyOfRange(array, 1, array.length);
return array[0] + sum(subArr);
}
}
a is an int array. Thus a[n-1] is an int. You are passing an int to sumOfArray which expects an array and not an int.
Try this if you don't want to pass the length of the array :
private static int sumOfArray(int[] array) {
if (1 == array.length) {
return array[array.length - 1];
}
return array[0] + sumOfArray(Arrays.copyOfRange(array, 1, array.length));
}
Offcourse you need to check if the array is empty or not.
This is the one recursive solution with complexity O(N).and with input parameter A[] only.
You can handle null and empty(0 length) case specifically as Its returning 0 in this solution. You throw Exception as well in this case.
/*
* Complexity is O(N)
*/
public int recursiveSum2(int A[])
{
if(A == null || A.length==0)
{
return 0;
}
else
{
return recursiveSum2Internal(A,A.length-1);
}
}
private int recursiveSum2Internal(int A[],int length)
{
if(length ==0 )
{
return A[length];
}
else
{
return A[length]+recursiveSum2Internal(A, length-1);
}
}
without any predefined function.
public static int sum(int input[]) {
int n = input.length;
if (n == 0) // base case
return 0;
int small[]=new int[n-1];
for(int i=1;i<n;i++)
{
small[i-1]=input[i];
}
return input[0]+sum(small);
}
private static int sum(int[] arr) {
// TODO Auto-generated method stub
int n = arr.length;
if(n==1)
{
return arr[n-1];
}
int ans = arr[0]+sum(Arrays.copyOf(arr, n-1));
return ans;
}
Simplified version:
//acc -> result accumlator, len - current length of array
public static int sum(int[] arr, int len, int acc) {
return len == 0 ? acc : sum(arr, len-1, arr[len-1]+ acc);
}
public static void main(String[] args) {
int[] arr= { 5, 1, 6, 2};
System.out.println(sum(arr, arr.length, 0));
}

Print last occurrence (printing mistake)

public class TestForMatch2
{
public static void main(String[] args)
{
int[] numbers1 = {0,2,4,6,7,11,0};
int[] numbers2 = {-7,5,9,10,5,0};
System.out.println(findTarget(numbers1,5));
System.out.println(findTarget(numbers1,0));
System.out.println(findTarget(numbers2,5));
System.out.println(findTarget(numbers1,-1));
}
public static int findTarget(int[] arr, int target)
{
if (arr == null) {
return -1;
}
int y = 0;
int g = 0;
for(int i = 0; i <= arr.length-1; i++) {
if (target == arr[i]) {
y = i;
//return y;
}
}
System.out.println(y);
return -1;
}
}
Output:
0
-1
6
-1
4
-1
0
-1
As you can see, there is a -1 that is being printed. If I remove the return -1, it gives me an error. How to remove the -1 without the error?
This is what is to be done.
Write a Java method to test if an array of integers contains a specific value.
If the value is in the array, returns the index of the element. If the value is more than once the method will return the index of the last occurrence of the value.
If the value is not in the array, returns -1.
Copy and paste the following code. Then complete the method.
public class Main
{
public static void main(String[] args)
{
int[] numbers1 = {0,2,4,6,7,11,0};
int[] numbers2 = {-7,5,9,10,5,0};
System.out.println(findTarget(numbers1,5));
System.out.println(findTarget(numbers1,0));
System.out.println(findTarget(numbers2,5));
System.out.println(findTarget(numbers1,-1));
}
public static int findTarget(int[] arr, int target)
{
//Type your code here
}
}
This is the desired result. Ignore the numbers on the left. I put it there to emphasise on the space on number 5. Thank you for your time.
1 -1
2 6
3 4
4 -1
5
public static void main(String[] args)
{
int[] numbers1 = {0,2,4,6,7,11,0};
int[] numbers2 = {-7,5,9,10,5,0};
System.out.println(findTarget(numbers1,5));
System.out.println(findTarget(numbers1,0));
System.out.println(findTarget(numbers2,5));
System.out.println(findTarget(numbers1,-1));
}
public static int findTarget(int[] arr, int target)
{
if (arr == null) {
return -1;
}
int targetIndex = -1;
for(int i = 0; i <= arr.length-1; i++) {
if (target == arr[i]) {
targetIndex = i;
}
}
return targetIndex;
}
Create a variable targetIndex which will keep the index of the target element, initially it is -1, if we find target element at index i, then our targetIndex becomes i, then we return it.
Here is the solution.
public static void main(String[] args)
{
int[] numbers1 = {0,2,4,6,7,11,0};
int[] numbers2 = {-7,5,9,10,5,0};
System.out.println(findTarget(numbers1,5));
System.out.println(findTarget(numbers1,0));
System.out.println(findTarget(numbers2,5));
System.out.println(findTarget(numbers1,-1));
}
public static int findTarget(int[] arr, int target)
{
int index = -1;
if(null != arr) {
for(int i=0;i<arr.length;i++) {
if(arr[i] == target) {
index = i;
}
}
}
return index;
}
You did System.out twice per iteration. Do you know why?
You always print what y is - first System.out():
System.out.println(y);
Then you always return -1:
return -1;
What gets printed too - second System.out():
System.out.println(findTarget(numbers1,5));
You said: "If I remove the return -1, it gives me an error.".
--> You have to return an integer, since your method says "public static int findTarget(int[] arr, int target)". So it compiles if you return -1, since -1 is an integer, but also if you return y, because you also assigned an integer to y.
So change the findTarget() to the following:
public static int findTarget(int[] arr, int target)
{
if (arr == null) {
return -1;
}
int y = -1;
for(int i = 0; i <= arr.length-1; i++) {
if (target == arr[i]) {
y = i;
}
}
return y;
}
Initialize y = -1 and return y, you're returning -1 no matter what you feed into the function.

Making a multiple choice quiz using Java : How can I randomize the order the questions are asked? [duplicate]

I need to randomly shuffle the following Array:
int[] solutionArray = {1, 2, 3, 4, 5, 6, 6, 5, 4, 3, 2, 1};
Is there any function to do that?
Using Collections to shuffle an array of primitive types is a bit of an overkill...
It is simple enough to implement the function yourself, using for example the Fisher–Yates shuffle:
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
class Test
{
public static void main(String args[])
{
int[] solutionArray = { 1, 2, 3, 4, 5, 6, 16, 15, 14, 13, 12, 11 };
shuffleArray(solutionArray);
for (int i = 0; i < solutionArray.length; i++)
{
System.out.print(solutionArray[i] + " ");
}
System.out.println();
}
// Implementing Fisher–Yates shuffle
static void shuffleArray(int[] ar)
{
// If running on Java 6 or older, use `new Random()` on RHS here
Random rnd = ThreadLocalRandom.current();
for (int i = ar.length - 1; i > 0; i--)
{
int index = rnd.nextInt(i + 1);
// Simple swap
int a = ar[index];
ar[index] = ar[i];
ar[i] = a;
}
}
}
Here is a simple way using an ArrayList:
List<Integer> solution = new ArrayList<>();
for (int i = 1; i <= 6; i++) {
solution.add(i);
}
Collections.shuffle(solution);
Here is a working and efficient Fisher–Yates shuffle array function:
private static void shuffleArray(int[] array)
{
int index;
Random random = new Random();
for (int i = array.length - 1; i > 0; i--)
{
index = random.nextInt(i + 1);
if (index != i)
{
array[index] ^= array[i];
array[i] ^= array[index];
array[index] ^= array[i];
}
}
}
or
private static void shuffleArray(int[] array)
{
int index, temp;
Random random = new Random();
for (int i = array.length - 1; i > 0; i--)
{
index = random.nextInt(i + 1);
temp = array[index];
array[index] = array[i];
array[i] = temp;
}
}
Collections class has an efficient method for shuffling, that can be copied, so as not to depend on it:
/**
* Usage:
* int[] array = {1, 2, 3};
* Util.shuffle(array);
*/
public class Util {
private static Random random;
/**
* Code from method java.util.Collections.shuffle();
*/
public static void shuffle(int[] array) {
if (random == null) random = new Random();
int count = array.length;
for (int i = count; i > 1; i--) {
swap(array, i - 1, random.nextInt(i));
}
}
private static void swap(int[] array, int i, int j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
Look at the Collections class, specifically shuffle(...).
You have a couple options here. A list is a bit different than an array when it comes to shuffling.
As you can see below, an array is faster than a list, and a primitive array is faster than an object array.
Sample Durations
List<Integer> Shuffle: 43133ns
Integer[] Shuffle: 31884ns
int[] Shuffle: 25377ns
Below, are three different implementations of a shuffle. You should only use Collections.shuffle if you are dealing with a collection. There is no need to wrap your array into a collection just to sort it. The methods below are very simple to implement.
ShuffleUtil Class
import java.lang.reflect.Array;
import java.util.*;
public class ShuffleUtil<T> {
private static final int[] EMPTY_INT_ARRAY = new int[0];
private static final int SHUFFLE_THRESHOLD = 5;
private static Random rand;
Main Method
public static void main(String[] args) {
List<Integer> list = null;
Integer[] arr = null;
int[] iarr = null;
long start = 0;
int cycles = 1000;
int n = 1000;
// Shuffle List<Integer>
start = System.nanoTime();
list = range(n);
for (int i = 0; i < cycles; i++) {
ShuffleUtil.shuffle(list);
}
System.out.printf("%22s: %dns%n", "List<Integer> Shuffle", (System.nanoTime() - start) / cycles);
// Shuffle Integer[]
start = System.nanoTime();
arr = toArray(list);
for (int i = 0; i < cycles; i++) {
ShuffleUtil.shuffle(arr);
}
System.out.printf("%22s: %dns%n", "Integer[] Shuffle", (System.nanoTime() - start) / cycles);
// Shuffle int[]
start = System.nanoTime();
iarr = toPrimitive(arr);
for (int i = 0; i < cycles; i++) {
ShuffleUtil.shuffle(iarr);
}
System.out.printf("%22s: %dns%n", "int[] Shuffle", (System.nanoTime() - start) / cycles);
}
Shuffling a Generic List
// ================================================================
// Shuffle List<T> (java.lang.Collections)
// ================================================================
#SuppressWarnings("unchecked")
public static <T> void shuffle(List<T> list) {
if (rand == null) {
rand = new Random();
}
int size = list.size();
if (size < SHUFFLE_THRESHOLD || list instanceof RandomAccess) {
for (int i = size; i > 1; i--) {
swap(list, i - 1, rand.nextInt(i));
}
} else {
Object arr[] = list.toArray();
for (int i = size; i > 1; i--) {
swap(arr, i - 1, rand.nextInt(i));
}
ListIterator<T> it = list.listIterator();
int i = 0;
while (it.hasNext()) {
it.next();
it.set((T) arr[i++]);
}
}
}
public static <T> void swap(List<T> list, int i, int j) {
final List<T> l = list;
l.set(i, l.set(j, l.get(i)));
}
public static <T> List<T> shuffled(List<T> list) {
List<T> copy = copyList(list);
shuffle(copy);
return copy;
}
Shuffling a Generic Array
// ================================================================
// Shuffle T[]
// ================================================================
public static <T> void shuffle(T[] arr) {
if (rand == null) {
rand = new Random();
}
for (int i = arr.length - 1; i > 0; i--) {
swap(arr, i, rand.nextInt(i + 1));
}
}
public static <T> void swap(T[] arr, int i, int j) {
T tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
public static <T> T[] shuffled(T[] arr) {
T[] copy = Arrays.copyOf(arr, arr.length);
shuffle(copy);
return copy;
}
Shuffling a Primitive Array
// ================================================================
// Shuffle int[]
// ================================================================
public static <T> void shuffle(int[] arr) {
if (rand == null) {
rand = new Random();
}
for (int i = arr.length - 1; i > 0; i--) {
swap(arr, i, rand.nextInt(i + 1));
}
}
public static <T> void swap(int[] arr, int i, int j) {
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
public static int[] shuffled(int[] arr) {
int[] copy = Arrays.copyOf(arr, arr.length);
shuffle(copy);
return copy;
}
Utility Methods
Simple utility methods to copy and convert arrays to lists and vice-versa.
// ================================================================
// Utility methods
// ================================================================
protected static <T> List<T> copyList(List<T> list) {
List<T> copy = new ArrayList<T>(list.size());
for (T item : list) {
copy.add(item);
}
return copy;
}
protected static int[] toPrimitive(Integer[] array) {
if (array == null) {
return null;
} else if (array.length == 0) {
return EMPTY_INT_ARRAY;
}
final int[] result = new int[array.length];
for (int i = 0; i < array.length; i++) {
result[i] = array[i].intValue();
}
return result;
}
protected static Integer[] toArray(List<Integer> list) {
return toArray(list, Integer.class);
}
protected static <T> T[] toArray(List<T> list, Class<T> clazz) {
#SuppressWarnings("unchecked")
final T[] arr = list.toArray((T[]) Array.newInstance(clazz, list.size()));
return arr;
}
Range Class
Generates a range of values, similar to Python's range function.
// ================================================================
// Range class for generating a range of values.
// ================================================================
protected static List<Integer> range(int n) {
return toList(new Range(n), new ArrayList<Integer>());
}
protected static <T> List<T> toList(Iterable<T> iterable) {
return toList(iterable, new ArrayList<T>());
}
protected static <T> List<T> toList(Iterable<T> iterable, List<T> destination) {
addAll(destination, iterable.iterator());
return destination;
}
protected static <T> void addAll(Collection<T> collection, Iterator<T> iterator) {
while (iterator.hasNext()) {
collection.add(iterator.next());
}
}
private static class Range implements Iterable<Integer> {
private int start;
private int stop;
private int step;
private Range(int n) {
this(0, n, 1);
}
private Range(int start, int stop) {
this(start, stop, 1);
}
private Range(int start, int stop, int step) {
this.start = start;
this.stop = stop;
this.step = step;
}
#Override
public Iterator<Integer> iterator() {
final int min = start;
final int max = stop / step;
return new Iterator<Integer>() {
private int current = min;
#Override
public boolean hasNext() {
return current < max;
}
#Override
public Integer next() {
if (hasNext()) {
return current++ * step;
} else {
throw new NoSuchElementException("Range reached the end");
}
}
#Override
public void remove() {
throw new UnsupportedOperationException("Can't remove values from a Range");
}
};
}
}
}
Here is a complete solution using the Collections.shuffle approach:
public static void shuffleArray(int[] array) {
List<Integer> list = new ArrayList<>();
for (int i : array) {
list.add(i);
}
Collections.shuffle(list);
for (int i = 0; i < list.size(); i++) {
array[i] = list.get(i);
}
}
Note that it suffers due to Java's inability to smoothly translate between int[] and Integer[] (and thus int[] and List<Integer>).
Using ArrayList<Integer> can help you solving the problem of shuffling without applying much of logic and consuming less time. Here is what I suggest:
ArrayList<Integer> x = new ArrayList<Integer>();
for(int i=1; i<=add.length(); i++)
{
x.add(i);
}
Collections.shuffle(x);
The following code will achieve a random ordering on the array.
// Shuffle the elements in the array
Collections.shuffle(Arrays.asList(array));
from: http://www.programcreek.com/2012/02/java-method-to-shuffle-an-int-array-with-random-order/
You can use java 8 now:
Collections.addAll(list, arr);
Collections.shuffle(list);
cardsList.toArray(arr);
Random rnd = new Random();
for (int i = ar.length - 1; i > 0; i--)
{
int index = rnd.nextInt(i + 1);
// Simple swap
int a = ar[index];
ar[index] = ar[i];
ar[i] = a;
}
By the way, I've noticed that this code returns a ar.length - 1 number of elements, so if your array has 5 elements, the new shuffled array will have 4 elements. This happens because the for loop says i>0. If you change to i>=0, you get all elements shuffled.
Here is a solution using Apache Commons Math 3.x (for int[] arrays only):
MathArrays.shuffle(array);
http://commons.apache.org/proper/commons-math/javadocs/api-3.6.1/org/apache/commons/math3/util/MathArrays.html#shuffle(int[])
Alternatively, Apache Commons Lang 3.6 introduced new shuffle methods to the ArrayUtils class (for objects and any primitive type).
ArrayUtils.shuffle(array);
http://commons.apache.org/proper/commons-lang/javadocs/api-release/org/apache/commons/lang3/ArrayUtils.html#shuffle-int:A-
Here is a Generics version for arrays:
import java.util.Random;
public class Shuffle<T> {
private final Random rnd;
public Shuffle() {
rnd = new Random();
}
/**
* Fisher–Yates shuffle.
*/
public void shuffle(T[] ar) {
for (int i = ar.length - 1; i > 0; i--) {
int index = rnd.nextInt(i + 1);
T a = ar[index];
ar[index] = ar[i];
ar[i] = a;
}
}
}
Considering that ArrayList is basically just an array, it may be advisable to work with an ArrayList instead of the explicit array and use Collections.shuffle(). Performance tests however, do not show any significant difference between the above and Collections.sort():
Shuffe<Integer>.shuffle(...) performance: 576084 shuffles per second
Collections.shuffle(ArrayList<Integer>) performance: 629400 shuffles per second
MathArrays.shuffle(int[]) performance: 53062 shuffles per second
The Apache Commons implementation MathArrays.shuffle is limited to int[] and the performance penalty is likely due to the random number generator being used.
I saw some miss information in some answers so i decided to add a new one.
Java collections Arrays.asList takes var-arg of type T (T ...). If you pass a primitive array (int array), asList method will infer and generate a List<int[]>, which is a one element list (the one element is the primitive array). if you shuffle this one element list, it won`t change any thing.
So, first you have to convert you primitive array to Wrapper object array. for this you can use ArrayUtils.toObject method from apache.commons.lang. then pass the generated array to a List and finaly shuffle that.
int[] intArr = {1,2,3};
List<Integer> integerList = Arrays.asList(ArrayUtils.toObject(array));
Collections.shuffle(integerList);
//now! elements in integerList are shuffled!
Here's another way to shuffle a list
public List<Integer> shuffleArray(List<Integer> a) {
List<Integer> b = new ArrayList<Integer>();
while (a.size() != 0) {
int arrayIndex = (int) (Math.random() * (a.size()));
b.add(a.get(arrayIndex));
a.remove(a.get(arrayIndex));
}
return b;
}
Pick a random number from the original list and save it in another list.Then remove the number from the original list.The size of the original list will keep decreasing by one until all elements are moved to the new list.
A simple solution for Groovy:
solutionArray.sort{ new Random().nextInt() }
This will sort all elements of the array list randomly which archives the desired result of shuffling all elements.
Using Guava's Ints.asList() it is as simple as:
Collections.shuffle(Ints.asList(array));
Using the Random Class
public static void randomizeArray(int[] arr) {
Random rGenerator = new Random(); // Create an instance of the random class
for (int i =0; i< arr.length;i++ ) {
//Swap the positions...
int rPosition = rGenerator.nextInt(arr.length); // Generates an integer within the range (Any number from 0 - arr.length)
int temp = arr[i]; // variable temp saves the value of the current array index;
arr[i] = arr[rPosition]; // array at the current position (i) get the value of the random generated
arr[rPosition] = temp; // the array at the position of random generated gets the value of temp
}
for(int i = 0; i<arr.length; i++) {
System.out.print(arr[i]); //Prints out the array
}
}
I'm weighing in on this very popular question because nobody has written a shuffle-copy version. Style is borrowed heavily from Arrays.java, because who isn't pillaging Java technology these days? Generic and int implementations included.
/**
* Shuffles elements from {#code original} into a newly created array.
*
* #param original the original array
* #return the new, shuffled array
* #throws NullPointerException if {#code original == null}
*/
#SuppressWarnings("unchecked")
public static <T> T[] shuffledCopy(T[] original) {
int originalLength = original.length; // For exception priority compatibility.
Random random = new Random();
T[] result = (T[]) Array.newInstance(original.getClass().getComponentType(), originalLength);
for (int i = 0; i < originalLength; i++) {
int j = random.nextInt(i+1);
result[i] = result[j];
result[j] = original[i];
}
return result;
}
/**
* Shuffles elements from {#code original} into a newly created array.
*
* #param original the original array
* #return the new, shuffled array
* #throws NullPointerException if {#code original == null}
*/
public static int[] shuffledCopy(int[] original) {
int originalLength = original.length;
Random random = new Random();
int[] result = new int[originalLength];
for (int i = 0; i < originalLength; i++) {
int j = random.nextInt(i+1);
result[i] = result[j];
result[j] = original[i];
}
return result;
}
This is knuth shuffle algorithm.
public class Knuth {
// this class should not be instantiated
private Knuth() { }
/**
* Rearranges an array of objects in uniformly random order
* (under the assumption that <tt>Math.random()</tt> generates independent
* and uniformly distributed numbers between 0 and 1).
* #param a the array to be shuffled
*/
public static void shuffle(Object[] a) {
int n = a.length;
for (int i = 0; i < n; i++) {
// choose index uniformly in [i, n-1]
int r = i + (int) (Math.random() * (n - i));
Object swap = a[r];
a[r] = a[i];
a[i] = swap;
}
}
/**
* Reads in a sequence of strings from standard input, shuffles
* them, and prints out the results.
*/
public static void main(String[] args) {
// read in the data
String[] a = StdIn.readAllStrings();
// shuffle the array
Knuth.shuffle(a);
// print results.
for (int i = 0; i < a.length; i++)
StdOut.println(a[i]);
}
}
There is another way also, not post yet
//that way, send many object types diferentes
public anotherWayToReciveParameter(Object... objects)
{
//ready with array
final int length =objects.length;
System.out.println(length);
//for ready same list
Arrays.asList(objects);
}
that way more easy, depended of the context
The most simple solution for this Random Shuffling in an Array.
String location[] = {"delhi","banglore","mathura","lucknow","chandigarh","mumbai"};
int index;
String temp;
Random random = new Random();
for(int i=1;i<location.length;i++)
{
index = random.nextInt(i+1);
temp = location[index];
location[index] = location[i];
location[i] = temp;
System.out.println("Location Based On Random Values :"+location[i]);
}
Simplest code to shuffle:
import java.util.*;
public class ch {
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
ArrayList<Integer> l=new ArrayList<Integer>(10);
for(int i=0;i<10;i++)
l.add(sc.nextInt());
Collections.shuffle(l);
for(int j=0;j<10;j++)
System.out.println(l.get(j));
}
}
Box from int[] to List<Integer>
Shuffle with Collections.shuffle method
int[] solutionArray = { 1, 2, 3, 4, 5, 6, 6, 5, 4, 3, 2, 1 };
List<Integer> list = Arrays.stream(solutionArray).boxed().collect(Collectors.toList());
Collections.shuffle(list);
System.out.println(list.toString());
// [1, 5, 5, 4, 2, 6, 1, 3, 3, 4, 2, 6]
You should use Collections.shuffle(). However, you can't directly manipulate an array of primitive types, so you need to create a wrapper class.
Try this.
public static void shuffle(int[] array) {
Collections.shuffle(new AbstractList<Integer>() {
#Override public Integer get(int index) { return array[index]; }
#Override public int size() { return array.length; }
#Override public Integer set(int index, Integer element) {
int result = array[index];
array[index] = element;
return result;
}
});
}
And
int[] solutionArray = {1, 2, 3, 4, 5, 6, 6, 5, 4, 3, 2, 1};
shuffle(solutionArray);
System.out.println(Arrays.toString(solutionArray));
output:
[3, 3, 4, 1, 6, 2, 2, 1, 5, 6, 5, 4]
public class ShuffleArray {
public static void shuffleArray(int[] a) {
int n = a.length;
Random random = new Random();
random.nextInt();
for (int i = 0; i < n; i++) {
int change = i + random.nextInt(n - i);
swap(a, i, change);
}
}
private static void swap(int[] a, int i, int change) {
int helper = a[i];
a[i] = a[change];
a[change] = helper;
}
public static void main(String[] args) {
int[] a = new int[] { 1, 2, 3, 4, 5, 6, 6, 5, 4, 3, 2, 1 };
shuffleArray(a);
for (int i : a) {
System.out.println(i);
}
}
}
import java.util.ArrayList;
import java.util.Random;
public class shuffle {
public static void main(String[] args) {
int a[] = {1,2,3,4,5,6,7,8,9};
ArrayList b = new ArrayList();
int i=0,q=0;
Random rand = new Random();
while(a.length!=b.size())
{
int l = rand.nextInt(a.length);
//this is one option to that but has a flaw on 0
// if(a[l] !=0)
// {
// b.add(a[l]);
// a[l]=0;
//
// }
//
// this works for every no.
if(!(b.contains(a[l])))
{
b.add(a[l]);
}
}
// for (int j = 0; j <b.size(); j++) {
// System.out.println(b.get(j));
//
// }
System.out.println(b);
}
}
One of the solution is using the permutation to pre-compute all the permutations and stored in the ArrayList
Java 8 introduced a new method, ints(), in the java.util.Random class. The ints() method returns an unlimited stream of pseudorandom int values. You can limit the random numbers between a specified range by providing the minimum and the maximum values.
Random genRandom = new Random();
int num = genRandom.nextInt(arr.length);
With the help of generating the random number, You can iterate through the loop and swap with the current index with the random number..
That's how you can generate a random number with O(1) space complexity.
Without Random solution:
static void randomArrTimest(int[] some){
long startTime = System.currentTimeMillis();
for (int i = 0; i < some.length; i++) {
long indexToSwap = startTime%(i+1);
long tmp = some[(int) indexToSwap];
some[(int) indexToSwap] = some[i];
some[i] = (int) tmp;
}
System.out.println(Arrays.toString(some));
}
In Java we can use Collections.shuffle method to randomly reorder items in a list.
Groovy 3.0.0 adds the shuffle and shuffled methods to a List or array directly.

java smallest integer in an array recursive method

I need to write a recursive method which looks through an array and finds the smallest index, however I am having a bizarre issue, for some reason my given test array seems to return a result of 10. I have tried debugging in eclipse and something very odd happens, my findMinAux method does indeed find -10 to be the smallest value and when I press the "step into" button it does seem as if it is about to return -10 but then it goes into some weird loop and startIndex starts increasing for some reason. If anyone has any advice as to where I am going wrong it would be greatly appreciated, thank you.
Here is my code:
public class Q1 {
public static void main(String[] args) {
int[] testArr = {12,32,45,435,-1,345,0,564,-10,234,25};
findMin(testArr);
}
public static int findMin(int[] arr) {
int result = findMinAux(arr,arr.length-1,arr.length-1);
System.out.println(result);
return result;
}
public static int findMinAux(int[] arr, int startIndex, int smallest) {
if(arr[startIndex]<smallest) {
smallest = arr[startIndex];
}
startIndex--;
if(startIndex>=0) {
findMinAux(arr,startIndex,smallest);
}
return smallest;
}
}
Two problems:
First, you should initiate smallest with the last element if you want to search from the end of array:
int result = findMinAux(arr,arr.length-1,arr[arr.length - 1]);
Secondly, you should reassign smallest:
if(startIndex>=0) {
smallest = findMinAux(arr,startIndex,smallest);
}
class Minimum {
int minelem;
int minindex;
Minimum() {
minelem = Integer.MAX_VALUE;
minindex = -1;
}
}
public class Q1 {
public static void main(String[] args) {
int[] testArr = {12,32,45,435,-1,345,0,564,-10,234,25};
findMin(testArr);
}
public static int findMin(int[] arr) {
Minimum m = new Minimum();
m = findMinAux(arr,arr.length-1,m);
System.out.println(m.minindex);
return m.minindex;
}
public static Minimum findMinAux(int[] arr, int lastindex, Minimum m) {
if(lastindex < 0) {
return m;
}
if(m.minelem > arr[lastindex]) {
m.minelem = arr[lastindex];
m.minindex = lastindex;
}
return findMinAux(arr,lastindex - 1, m);
}
}
I have used another class here for simplification. Please check if this solved your problem meanwhile I am explaining why and how it is working.
Actually, this implementation works fine
public static int findMinAux(int[] arr, int startIndex, int smallest) {
if(startIndex < 0)
return smallest;
if(arr[startIndex] < smallest){
smallest = arr[startIndex];
}
return findMinAux(arr, startIndex - 1, smallest);
}
And also you has a typo in calling this funtion, the last parameter must be an value from array, in your case the last value, not the last index.
int result = findMinAux(arr,arr.length-1, arr.length - 1);
change to
int result = findMinAux(arr,arr.length-2, arr[arr.length - 1]);
This approach works with a single method and an overloaded version so you don't have to pass the initial values
public static int findMin(int[] arr) {
int index = 0;
int min = Integer.MAX_VALUE;
min = Math.min(arr[index], min);
return findMin(arr,index+1,min);
}
private static int findMin(int[] arr, int index, int min) {
if(index < arr.length)
{
min = Math.min(arr[index], min);
return findMin(arr,index+1,min);
}
System.out.println(min);
return min;
}
The second method is private so from outside the class, only the first/default method can be called.
See this code. In every iteration, elements are compared with current element and index in increased on the basis of comparison. This is tail recursive as well. So it can be used in large arrays as well.
public class Q1 {
public static void main(String[] args) {
int[] testArr = {12, 32, 45, 435, -1, 345, 0, 564, -10, 234, 25};
System.out.println();
System.out.println(find(testArr, 0, testArr.length - 1, testArr[0]));
}
public static int find(int[] arr, int currPos, int lastPos, int elem) {
if (currPos == lastPos) {
return elem;
} else {
if (elem < arr[currPos]) {
return find(arr, currPos + 1, lastPos, elem);
} else {
return find(arr, currPos + 1, lastPos, arr[currPos]);
}
}
}
}

How can I 'un-sort' an array of randomly generated values? [duplicate]

I need to randomly shuffle the following Array:
int[] solutionArray = {1, 2, 3, 4, 5, 6, 6, 5, 4, 3, 2, 1};
Is there any function to do that?
Using Collections to shuffle an array of primitive types is a bit of an overkill...
It is simple enough to implement the function yourself, using for example the Fisher–Yates shuffle:
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
class Test
{
public static void main(String args[])
{
int[] solutionArray = { 1, 2, 3, 4, 5, 6, 16, 15, 14, 13, 12, 11 };
shuffleArray(solutionArray);
for (int i = 0; i < solutionArray.length; i++)
{
System.out.print(solutionArray[i] + " ");
}
System.out.println();
}
// Implementing Fisher–Yates shuffle
static void shuffleArray(int[] ar)
{
// If running on Java 6 or older, use `new Random()` on RHS here
Random rnd = ThreadLocalRandom.current();
for (int i = ar.length - 1; i > 0; i--)
{
int index = rnd.nextInt(i + 1);
// Simple swap
int a = ar[index];
ar[index] = ar[i];
ar[i] = a;
}
}
}
Here is a simple way using an ArrayList:
List<Integer> solution = new ArrayList<>();
for (int i = 1; i <= 6; i++) {
solution.add(i);
}
Collections.shuffle(solution);
Here is a working and efficient Fisher–Yates shuffle array function:
private static void shuffleArray(int[] array)
{
int index;
Random random = new Random();
for (int i = array.length - 1; i > 0; i--)
{
index = random.nextInt(i + 1);
if (index != i)
{
array[index] ^= array[i];
array[i] ^= array[index];
array[index] ^= array[i];
}
}
}
or
private static void shuffleArray(int[] array)
{
int index, temp;
Random random = new Random();
for (int i = array.length - 1; i > 0; i--)
{
index = random.nextInt(i + 1);
temp = array[index];
array[index] = array[i];
array[i] = temp;
}
}
Collections class has an efficient method for shuffling, that can be copied, so as not to depend on it:
/**
* Usage:
* int[] array = {1, 2, 3};
* Util.shuffle(array);
*/
public class Util {
private static Random random;
/**
* Code from method java.util.Collections.shuffle();
*/
public static void shuffle(int[] array) {
if (random == null) random = new Random();
int count = array.length;
for (int i = count; i > 1; i--) {
swap(array, i - 1, random.nextInt(i));
}
}
private static void swap(int[] array, int i, int j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
Look at the Collections class, specifically shuffle(...).
You have a couple options here. A list is a bit different than an array when it comes to shuffling.
As you can see below, an array is faster than a list, and a primitive array is faster than an object array.
Sample Durations
List<Integer> Shuffle: 43133ns
Integer[] Shuffle: 31884ns
int[] Shuffle: 25377ns
Below, are three different implementations of a shuffle. You should only use Collections.shuffle if you are dealing with a collection. There is no need to wrap your array into a collection just to sort it. The methods below are very simple to implement.
ShuffleUtil Class
import java.lang.reflect.Array;
import java.util.*;
public class ShuffleUtil<T> {
private static final int[] EMPTY_INT_ARRAY = new int[0];
private static final int SHUFFLE_THRESHOLD = 5;
private static Random rand;
Main Method
public static void main(String[] args) {
List<Integer> list = null;
Integer[] arr = null;
int[] iarr = null;
long start = 0;
int cycles = 1000;
int n = 1000;
// Shuffle List<Integer>
start = System.nanoTime();
list = range(n);
for (int i = 0; i < cycles; i++) {
ShuffleUtil.shuffle(list);
}
System.out.printf("%22s: %dns%n", "List<Integer> Shuffle", (System.nanoTime() - start) / cycles);
// Shuffle Integer[]
start = System.nanoTime();
arr = toArray(list);
for (int i = 0; i < cycles; i++) {
ShuffleUtil.shuffle(arr);
}
System.out.printf("%22s: %dns%n", "Integer[] Shuffle", (System.nanoTime() - start) / cycles);
// Shuffle int[]
start = System.nanoTime();
iarr = toPrimitive(arr);
for (int i = 0; i < cycles; i++) {
ShuffleUtil.shuffle(iarr);
}
System.out.printf("%22s: %dns%n", "int[] Shuffle", (System.nanoTime() - start) / cycles);
}
Shuffling a Generic List
// ================================================================
// Shuffle List<T> (java.lang.Collections)
// ================================================================
#SuppressWarnings("unchecked")
public static <T> void shuffle(List<T> list) {
if (rand == null) {
rand = new Random();
}
int size = list.size();
if (size < SHUFFLE_THRESHOLD || list instanceof RandomAccess) {
for (int i = size; i > 1; i--) {
swap(list, i - 1, rand.nextInt(i));
}
} else {
Object arr[] = list.toArray();
for (int i = size; i > 1; i--) {
swap(arr, i - 1, rand.nextInt(i));
}
ListIterator<T> it = list.listIterator();
int i = 0;
while (it.hasNext()) {
it.next();
it.set((T) arr[i++]);
}
}
}
public static <T> void swap(List<T> list, int i, int j) {
final List<T> l = list;
l.set(i, l.set(j, l.get(i)));
}
public static <T> List<T> shuffled(List<T> list) {
List<T> copy = copyList(list);
shuffle(copy);
return copy;
}
Shuffling a Generic Array
// ================================================================
// Shuffle T[]
// ================================================================
public static <T> void shuffle(T[] arr) {
if (rand == null) {
rand = new Random();
}
for (int i = arr.length - 1; i > 0; i--) {
swap(arr, i, rand.nextInt(i + 1));
}
}
public static <T> void swap(T[] arr, int i, int j) {
T tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
public static <T> T[] shuffled(T[] arr) {
T[] copy = Arrays.copyOf(arr, arr.length);
shuffle(copy);
return copy;
}
Shuffling a Primitive Array
// ================================================================
// Shuffle int[]
// ================================================================
public static <T> void shuffle(int[] arr) {
if (rand == null) {
rand = new Random();
}
for (int i = arr.length - 1; i > 0; i--) {
swap(arr, i, rand.nextInt(i + 1));
}
}
public static <T> void swap(int[] arr, int i, int j) {
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
public static int[] shuffled(int[] arr) {
int[] copy = Arrays.copyOf(arr, arr.length);
shuffle(copy);
return copy;
}
Utility Methods
Simple utility methods to copy and convert arrays to lists and vice-versa.
// ================================================================
// Utility methods
// ================================================================
protected static <T> List<T> copyList(List<T> list) {
List<T> copy = new ArrayList<T>(list.size());
for (T item : list) {
copy.add(item);
}
return copy;
}
protected static int[] toPrimitive(Integer[] array) {
if (array == null) {
return null;
} else if (array.length == 0) {
return EMPTY_INT_ARRAY;
}
final int[] result = new int[array.length];
for (int i = 0; i < array.length; i++) {
result[i] = array[i].intValue();
}
return result;
}
protected static Integer[] toArray(List<Integer> list) {
return toArray(list, Integer.class);
}
protected static <T> T[] toArray(List<T> list, Class<T> clazz) {
#SuppressWarnings("unchecked")
final T[] arr = list.toArray((T[]) Array.newInstance(clazz, list.size()));
return arr;
}
Range Class
Generates a range of values, similar to Python's range function.
// ================================================================
// Range class for generating a range of values.
// ================================================================
protected static List<Integer> range(int n) {
return toList(new Range(n), new ArrayList<Integer>());
}
protected static <T> List<T> toList(Iterable<T> iterable) {
return toList(iterable, new ArrayList<T>());
}
protected static <T> List<T> toList(Iterable<T> iterable, List<T> destination) {
addAll(destination, iterable.iterator());
return destination;
}
protected static <T> void addAll(Collection<T> collection, Iterator<T> iterator) {
while (iterator.hasNext()) {
collection.add(iterator.next());
}
}
private static class Range implements Iterable<Integer> {
private int start;
private int stop;
private int step;
private Range(int n) {
this(0, n, 1);
}
private Range(int start, int stop) {
this(start, stop, 1);
}
private Range(int start, int stop, int step) {
this.start = start;
this.stop = stop;
this.step = step;
}
#Override
public Iterator<Integer> iterator() {
final int min = start;
final int max = stop / step;
return new Iterator<Integer>() {
private int current = min;
#Override
public boolean hasNext() {
return current < max;
}
#Override
public Integer next() {
if (hasNext()) {
return current++ * step;
} else {
throw new NoSuchElementException("Range reached the end");
}
}
#Override
public void remove() {
throw new UnsupportedOperationException("Can't remove values from a Range");
}
};
}
}
}
Here is a complete solution using the Collections.shuffle approach:
public static void shuffleArray(int[] array) {
List<Integer> list = new ArrayList<>();
for (int i : array) {
list.add(i);
}
Collections.shuffle(list);
for (int i = 0; i < list.size(); i++) {
array[i] = list.get(i);
}
}
Note that it suffers due to Java's inability to smoothly translate between int[] and Integer[] (and thus int[] and List<Integer>).
Using ArrayList<Integer> can help you solving the problem of shuffling without applying much of logic and consuming less time. Here is what I suggest:
ArrayList<Integer> x = new ArrayList<Integer>();
for(int i=1; i<=add.length(); i++)
{
x.add(i);
}
Collections.shuffle(x);
The following code will achieve a random ordering on the array.
// Shuffle the elements in the array
Collections.shuffle(Arrays.asList(array));
from: http://www.programcreek.com/2012/02/java-method-to-shuffle-an-int-array-with-random-order/
You can use java 8 now:
Collections.addAll(list, arr);
Collections.shuffle(list);
cardsList.toArray(arr);
Random rnd = new Random();
for (int i = ar.length - 1; i > 0; i--)
{
int index = rnd.nextInt(i + 1);
// Simple swap
int a = ar[index];
ar[index] = ar[i];
ar[i] = a;
}
By the way, I've noticed that this code returns a ar.length - 1 number of elements, so if your array has 5 elements, the new shuffled array will have 4 elements. This happens because the for loop says i>0. If you change to i>=0, you get all elements shuffled.
Here is a solution using Apache Commons Math 3.x (for int[] arrays only):
MathArrays.shuffle(array);
http://commons.apache.org/proper/commons-math/javadocs/api-3.6.1/org/apache/commons/math3/util/MathArrays.html#shuffle(int[])
Alternatively, Apache Commons Lang 3.6 introduced new shuffle methods to the ArrayUtils class (for objects and any primitive type).
ArrayUtils.shuffle(array);
http://commons.apache.org/proper/commons-lang/javadocs/api-release/org/apache/commons/lang3/ArrayUtils.html#shuffle-int:A-
Here is a Generics version for arrays:
import java.util.Random;
public class Shuffle<T> {
private final Random rnd;
public Shuffle() {
rnd = new Random();
}
/**
* Fisher–Yates shuffle.
*/
public void shuffle(T[] ar) {
for (int i = ar.length - 1; i > 0; i--) {
int index = rnd.nextInt(i + 1);
T a = ar[index];
ar[index] = ar[i];
ar[i] = a;
}
}
}
Considering that ArrayList is basically just an array, it may be advisable to work with an ArrayList instead of the explicit array and use Collections.shuffle(). Performance tests however, do not show any significant difference between the above and Collections.sort():
Shuffe<Integer>.shuffle(...) performance: 576084 shuffles per second
Collections.shuffle(ArrayList<Integer>) performance: 629400 shuffles per second
MathArrays.shuffle(int[]) performance: 53062 shuffles per second
The Apache Commons implementation MathArrays.shuffle is limited to int[] and the performance penalty is likely due to the random number generator being used.
I saw some miss information in some answers so i decided to add a new one.
Java collections Arrays.asList takes var-arg of type T (T ...). If you pass a primitive array (int array), asList method will infer and generate a List<int[]>, which is a one element list (the one element is the primitive array). if you shuffle this one element list, it won`t change any thing.
So, first you have to convert you primitive array to Wrapper object array. for this you can use ArrayUtils.toObject method from apache.commons.lang. then pass the generated array to a List and finaly shuffle that.
int[] intArr = {1,2,3};
List<Integer> integerList = Arrays.asList(ArrayUtils.toObject(array));
Collections.shuffle(integerList);
//now! elements in integerList are shuffled!
Here's another way to shuffle a list
public List<Integer> shuffleArray(List<Integer> a) {
List<Integer> b = new ArrayList<Integer>();
while (a.size() != 0) {
int arrayIndex = (int) (Math.random() * (a.size()));
b.add(a.get(arrayIndex));
a.remove(a.get(arrayIndex));
}
return b;
}
Pick a random number from the original list and save it in another list.Then remove the number from the original list.The size of the original list will keep decreasing by one until all elements are moved to the new list.
A simple solution for Groovy:
solutionArray.sort{ new Random().nextInt() }
This will sort all elements of the array list randomly which archives the desired result of shuffling all elements.
Using Guava's Ints.asList() it is as simple as:
Collections.shuffle(Ints.asList(array));
Using the Random Class
public static void randomizeArray(int[] arr) {
Random rGenerator = new Random(); // Create an instance of the random class
for (int i =0; i< arr.length;i++ ) {
//Swap the positions...
int rPosition = rGenerator.nextInt(arr.length); // Generates an integer within the range (Any number from 0 - arr.length)
int temp = arr[i]; // variable temp saves the value of the current array index;
arr[i] = arr[rPosition]; // array at the current position (i) get the value of the random generated
arr[rPosition] = temp; // the array at the position of random generated gets the value of temp
}
for(int i = 0; i<arr.length; i++) {
System.out.print(arr[i]); //Prints out the array
}
}
I'm weighing in on this very popular question because nobody has written a shuffle-copy version. Style is borrowed heavily from Arrays.java, because who isn't pillaging Java technology these days? Generic and int implementations included.
/**
* Shuffles elements from {#code original} into a newly created array.
*
* #param original the original array
* #return the new, shuffled array
* #throws NullPointerException if {#code original == null}
*/
#SuppressWarnings("unchecked")
public static <T> T[] shuffledCopy(T[] original) {
int originalLength = original.length; // For exception priority compatibility.
Random random = new Random();
T[] result = (T[]) Array.newInstance(original.getClass().getComponentType(), originalLength);
for (int i = 0; i < originalLength; i++) {
int j = random.nextInt(i+1);
result[i] = result[j];
result[j] = original[i];
}
return result;
}
/**
* Shuffles elements from {#code original} into a newly created array.
*
* #param original the original array
* #return the new, shuffled array
* #throws NullPointerException if {#code original == null}
*/
public static int[] shuffledCopy(int[] original) {
int originalLength = original.length;
Random random = new Random();
int[] result = new int[originalLength];
for (int i = 0; i < originalLength; i++) {
int j = random.nextInt(i+1);
result[i] = result[j];
result[j] = original[i];
}
return result;
}
This is knuth shuffle algorithm.
public class Knuth {
// this class should not be instantiated
private Knuth() { }
/**
* Rearranges an array of objects in uniformly random order
* (under the assumption that <tt>Math.random()</tt> generates independent
* and uniformly distributed numbers between 0 and 1).
* #param a the array to be shuffled
*/
public static void shuffle(Object[] a) {
int n = a.length;
for (int i = 0; i < n; i++) {
// choose index uniformly in [i, n-1]
int r = i + (int) (Math.random() * (n - i));
Object swap = a[r];
a[r] = a[i];
a[i] = swap;
}
}
/**
* Reads in a sequence of strings from standard input, shuffles
* them, and prints out the results.
*/
public static void main(String[] args) {
// read in the data
String[] a = StdIn.readAllStrings();
// shuffle the array
Knuth.shuffle(a);
// print results.
for (int i = 0; i < a.length; i++)
StdOut.println(a[i]);
}
}
There is another way also, not post yet
//that way, send many object types diferentes
public anotherWayToReciveParameter(Object... objects)
{
//ready with array
final int length =objects.length;
System.out.println(length);
//for ready same list
Arrays.asList(objects);
}
that way more easy, depended of the context
The most simple solution for this Random Shuffling in an Array.
String location[] = {"delhi","banglore","mathura","lucknow","chandigarh","mumbai"};
int index;
String temp;
Random random = new Random();
for(int i=1;i<location.length;i++)
{
index = random.nextInt(i+1);
temp = location[index];
location[index] = location[i];
location[i] = temp;
System.out.println("Location Based On Random Values :"+location[i]);
}
Simplest code to shuffle:
import java.util.*;
public class ch {
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
ArrayList<Integer> l=new ArrayList<Integer>(10);
for(int i=0;i<10;i++)
l.add(sc.nextInt());
Collections.shuffle(l);
for(int j=0;j<10;j++)
System.out.println(l.get(j));
}
}
Box from int[] to List<Integer>
Shuffle with Collections.shuffle method
int[] solutionArray = { 1, 2, 3, 4, 5, 6, 6, 5, 4, 3, 2, 1 };
List<Integer> list = Arrays.stream(solutionArray).boxed().collect(Collectors.toList());
Collections.shuffle(list);
System.out.println(list.toString());
// [1, 5, 5, 4, 2, 6, 1, 3, 3, 4, 2, 6]
You should use Collections.shuffle(). However, you can't directly manipulate an array of primitive types, so you need to create a wrapper class.
Try this.
public static void shuffle(int[] array) {
Collections.shuffle(new AbstractList<Integer>() {
#Override public Integer get(int index) { return array[index]; }
#Override public int size() { return array.length; }
#Override public Integer set(int index, Integer element) {
int result = array[index];
array[index] = element;
return result;
}
});
}
And
int[] solutionArray = {1, 2, 3, 4, 5, 6, 6, 5, 4, 3, 2, 1};
shuffle(solutionArray);
System.out.println(Arrays.toString(solutionArray));
output:
[3, 3, 4, 1, 6, 2, 2, 1, 5, 6, 5, 4]
public class ShuffleArray {
public static void shuffleArray(int[] a) {
int n = a.length;
Random random = new Random();
random.nextInt();
for (int i = 0; i < n; i++) {
int change = i + random.nextInt(n - i);
swap(a, i, change);
}
}
private static void swap(int[] a, int i, int change) {
int helper = a[i];
a[i] = a[change];
a[change] = helper;
}
public static void main(String[] args) {
int[] a = new int[] { 1, 2, 3, 4, 5, 6, 6, 5, 4, 3, 2, 1 };
shuffleArray(a);
for (int i : a) {
System.out.println(i);
}
}
}
import java.util.ArrayList;
import java.util.Random;
public class shuffle {
public static void main(String[] args) {
int a[] = {1,2,3,4,5,6,7,8,9};
ArrayList b = new ArrayList();
int i=0,q=0;
Random rand = new Random();
while(a.length!=b.size())
{
int l = rand.nextInt(a.length);
//this is one option to that but has a flaw on 0
// if(a[l] !=0)
// {
// b.add(a[l]);
// a[l]=0;
//
// }
//
// this works for every no.
if(!(b.contains(a[l])))
{
b.add(a[l]);
}
}
// for (int j = 0; j <b.size(); j++) {
// System.out.println(b.get(j));
//
// }
System.out.println(b);
}
}
One of the solution is using the permutation to pre-compute all the permutations and stored in the ArrayList
Java 8 introduced a new method, ints(), in the java.util.Random class. The ints() method returns an unlimited stream of pseudorandom int values. You can limit the random numbers between a specified range by providing the minimum and the maximum values.
Random genRandom = new Random();
int num = genRandom.nextInt(arr.length);
With the help of generating the random number, You can iterate through the loop and swap with the current index with the random number..
That's how you can generate a random number with O(1) space complexity.
Without Random solution:
static void randomArrTimest(int[] some){
long startTime = System.currentTimeMillis();
for (int i = 0; i < some.length; i++) {
long indexToSwap = startTime%(i+1);
long tmp = some[(int) indexToSwap];
some[(int) indexToSwap] = some[i];
some[i] = (int) tmp;
}
System.out.println(Arrays.toString(some));
}
In Java we can use Collections.shuffle method to randomly reorder items in a list.
Groovy 3.0.0 adds the shuffle and shuffled methods to a List or array directly.

Categories