Question: So I am struggling with thid assignment. basically I need to create an array of any length given by the user and fill it with

So I am struggling with thid assignment. basically I need to create an array of any length given by the user and fill it with random numbers. The catch is you cannot use the same number twice, which is when i am required to create a used array. However, I cannot seem to figure out how to accomplish this because when you assign a value into the array, you need to also mark it as used and I thought I have already done that, but apparently not. Btw this is java.

import java.util.Random; import java.util.Scanner;

public class permutation_2 {

public static void main(String args[]) {

System.out.println("Enter the array size: "); Scanner scan = new Scanner(System.in); int size = scan.nextInt(); int a[] = new int[size]; System.out.println("Entered size: "+size); boolean used[] = new boolean[size]; // start loop for (int i = 0; i < size; i++) { used[i] = false; // for loop end } int low = 1; int high = size + 1; int ran;

Random r = new Random(); for (int i = 0; i < size; i++) { do { ran = r.nextInt(high - low) + low; if (used[ran - 1] == false) { a[i] = ran; break; }// end of if }// end of do while (used[ran - 1] == true);

}//end for 1 for (int i = 0; i < size; i++) { System.out.println(a[i]); }// end for 2 }// end main

}// end of class

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!