Random Shuffling an array of integers in Java [duplicate] - java

This question already has answers here:
Random shuffling of an array
(31 answers)
Closed 6 years ago.
This is my first time with arrays.
I should prompt the user to enter 5 array values and then display them in random order.
I am quite confused, since it's my first time doing this.
Anyway, my code is here.
import java.util.*;
public class Test {
public static void main(String[] args) {
int myArray[] = new int[5];
System.out.println("Please enter 5 numbers: ");
Scanner input = new Scanner(System.in);
for (int i = 0; i < myArray.length - 1; i--) {
int j = (int) (Math.random() * (i + 1));
myArray[i] = input.nextInt();
System.out.println("The numbers are: ");
System.out.println(myArray[0]);
System.out.println(myArray[1]);
System.out.println(myArray[2]);
System.out.println(myArray[3]);
System.out.println(myArray[4]);
int temp = myArray[i];
myArray[i] = myArray[j];
myArray[j] = temp;
System.out.println("The numbers, shuffled, are: ");
System.out.println(myArray[0]);
System.out.println(myArray[1]);
System.out.println(myArray[2]);
System.out.println(myArray[3]);
System.out.println(myArray[4]);
}
}
}
Thank you everyone for your support.

A - Explanation
Let's say you take the input values in order as {'1','2','3','4','5'}. What shuffling is corrupting the order randomly, so you have to change the position of elements randomly.
In the demo code,
swapArrayElement swaps the elements those that positions are passed as parameters.
getRandom returns a random value between 0 and the range which passed to the method as a parameter.
shuffleArray shuffles the array by changing the positions of elements randomly. Please notify that there is an additional boolean isShuffled[] array and it is boolean because we have to keep the track of positions whether they are shuffled or not.
isArrayShuffled method, checks that if all positions are shuffled or not.
B - Demo Code
import java.util.Scanner;
public class Test {
public static final int ARRAY_LENGTH = 5;
public static void main(String[] args) {
int myArray[] = new int[ARRAY_LENGTH];
Scanner input = new Scanner(System.in);
System.out.println("Please enter 5 numbers: ");
for(int i = 0; i < myArray.length; i++)
myArray[i] = input.nextInt();
System.out.println("\nThe numbers are: ");
printIntArray(myArray);
shuffleArray(myArray);
System.out.println("\nThe numbers, shuffled, are: ");
printIntArray(myArray);
input.close(); // no memory leaks!
}
// method for printing array
public static void printIntArray(int[] array) {
for(int i = 0; i < array.length; i++)
System.out.printf("%2d ", array[i]);
System.out.printf("%n"); // use %n for os-agnostic new-line
}
// method for shuffling array
public static void shuffleArray(int[] array) {
int range = array.length;
boolean isShuffled[] = new boolean[range]; // store which positions are shuffled
while(!isArrayShuffled(isShuffled)) {
int positionSrc = getRandom(range);
int positionDst = getRandom(range);
swapArrayElement(array, positionSrc, positionDst);
isShuffled[positionSrc] = true;
isShuffled[positionDst] = true;
}
}
public static int getRandom(int maxRange) {
return (int)(Math.random()*maxRange);
}
public static void swapArrayElement(int[] array, int i, int j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
public static boolean isArrayShuffled(boolean[] isShuffled) {
for(int i = 0; i < isShuffled.length; i++)
if(isShuffled[i] == false)
return false;
return true;
}
}
C - Demo Output
Please enter 5 numbers:
1 2 3 4 5
The numbers are:
1 2 3 4 5
The numbers, shuffled, are:
4 2 5 1 3

import java.util.Random;
import java.util.Scanner;
import java.util.concurrent.ThreadLocalRandom;
public class Test {
public static void shuffle(int[] arr) {
Random rnd = ThreadLocalRandom.current();
for (int i = arr.length - 1; i > 0; i--) {
int index = rnd.nextInt(i + 1);
int t = arr[index];
arr[index] = arr[i];
arr[i] = t;
}
}
public static void main(String[] args) {
int myArray[] = new int[5];
System.out.println("Please enter 5 numbers: ");
Scanner input = new Scanner(System.in);
for (int i = 0; i < myArray.length; i++) {
System.out.println("Enter " + (i + 1) + ". number: ");
myArray[i] = input.nextInt();
}
System.out.println("The numbers are: ");
for (int j2 = 0; j2 < myArray.length; j2++) {
System.out.println(myArray[j2]);
}
shuffle(myArray);
System.out.println("The numbers, shuffled, are: ");
for (int j2 = 0; j2 < myArray.length; j2++) {
System.out.println(myArray[j2]);
}
}
}

Related

How to find the min and max values with number of occurances for each

I'm having trouble solving this homework problem. The problem wants me to create a program that reads user input of numbers and get the minimum and maximum values of those numbers.
Basically, the output should be as follows:
Enter number count: 10
Enter 10 numbers separated by space and press ENTER: 1 2 3 1 2 3 4 5 6 3
Min is 1 and has 2 occurrences
Max is 6 and has 1 occurrences
I was able to create methods to get the min and max. I don't know how to get the number of occurrences for the min and max with what I have. I also don't know how to get the scanner to read an input of integers on the same line.
import java.util.Scanner;
public class homework2
{
public int min(int[] array)
{
int min = array[0];
for (int i = 0; i < array.length; i++)
{
if (array[i] < min)
{
min = array[i];
}
}
return min;
}
public int max(int[] array)
{
int max = 0;
for (int i = 0; i < array.length; i++)
{
if (array[i] > max)
{
max = array[i];
}
}
return max;
}
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.println("Enter the length of the array:");
int length = s.nextInt();
int[] myArray = new int[length];
System.out.println("Enter the elements of the array:");
for (int i = 0; i < length; i++)
{
myArray[i] = s.nextInt();
}
}
}
Here's a simple program to do what you need:
public static void main(String[] args) {
int[] array = {1, 2, 3, 1, 2, 3, 4, 5, 6, 3}; // get your actual array
int first = array[0];
// initial values
int min = first;
int minOccurs = 1;
int max = first;
int maxOccurs = 1;
for(int i = 1; i < array.length; i++) {
int current = array[i];
if(current == min) {
minOccurs++;
} else if (current < min) {
min = current;
minOccurs = 1;
}
if(current == max) {
maxOccurs++;
} else if (current > max) {
max = current;
maxOccurs = 1;
}
}
System.out.println("Min is " + min + " and has " + minOccurs + " occurrences");
System.out.println("Max is " + max + " and has " + maxOccurs + " occurrences");
// prints: "Min is 1 and has 2 occurrences"
// prints: "Max is 6 and has 1 occurrences"
}
One way is to store counts of each one of the numbers you see using a HashMap. The number itself can be the key and the value can be the count that you are incrementing.
You can also use a Math lib to output a min and max from the set of keys (numbers)
https://www.geeksforgeeks.org/java-math-min-method-examples/
https://www.geeksforgeeks.org/count-occurrences-elements-list-java/
Good luck!
Once you know what the maximum is, just count how many times that occurs in the array.
However, as #Babyburger points out, you don't need an array to compute either the maximum or how many times it occurs.
Here is one way to parse a line of space separated integer numbers into int array:
int[] array = Arrays
.stream(scanner.nextLine().trim().split("\\s+"))
.mapToInt(Integer::parseInt)
.toArray();
This should work for you. Let me know if you have questions:
import java.util.Scanner;
public class homework2 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter the length of the array:");
int length = s.nextInt();
System.out.println("Enter the elements of the array:");
int[] numbers = new int[length];
for (int i = 0; i < length; i++) {
numbers[i] = Integer.parseInt(s.next());
}
// take first element as max and min
int max = numbers[0];
int min = numbers[0];
// max and min exists so occurs at least once
int maxOcc = 1;
int minOcc = 1;
// start from i = 1; because we assigned the first element before
for (int i = 1; i < length; i++) {
int number = numbers[i];
if (number > max) {
max = number;
// start counting again
maxOcc = 1;
} else if (number == max) {
maxOcc++;
}
if (number < min) {
min = number;
// start counting again
minOcc = 1;
} else if (number == min) {
minOcc++;
}
}
System.out.println("max: " + max);
System.out.println("maxOcc: " + maxOcc);
System.out.println("min: " + min);
System.out.println("minOcc: " + minOcc);
}
}
Here is a solution to your problem. This takes a single string with numbers and spaces in-between, adds them to a dynamic array(ArrayList) and uses the min,max functions.
Do not initialize min and max=0 because we have to pick an integer from the provided list to start our comparison and that has to be the first element [0].
Code
import java.util.ArrayList;
import java.util.Scanner;
public class homework2 {
//Using static with functions because of the function calls in the Static
//main function
//Find the maximum number
public static int max(ArrayList<Integer> array) {
int max=array.get(0);
for(int i=0; i<array.size(); i++ ){
if(array.get(i)>max)
max = array.get(i);
}
return max;
}
//Calculate Maximum number's occurences
public static int maxOccur(int max,ArrayList<Integer> array){
int maxOccur=0;
for(int i=0; i<array.size(); i++ )
if(max==array.get(i)) maxOccur++;
return maxOccur;
}
//Find the minimum number
public static int min(ArrayList<Integer> array) {
int min=array.get(0);
for(int i=0; i<array.size(); i++ ){
if(array.get(i)<min)
min = array.get(i);
}
return min;
}
//Calculate Minimum number's occurences
public static int minOccur(int min,ArrayList<Integer> array){
int minOccur=0;
for(int i=0; i<array.size(); i++ )
if(min==array.get(i)) minOccur++;
return minOccur;
}
public static void main(String args[])
{
int minNum,maxNum;
Scanner in = new Scanner(System.in);
System.out.print("Enter the numbers separated by a space: ");
String number = in.nextLine();
//Separate the string by spaces in-between
String[] separatedNums = number.split(" ");
//Create a dynamic ArrayList to store any amount of integers
ArrayList<Integer> arrayList = new ArrayList<Integer>();
//Save the above string in the ArrayList after parsing into integer
for (String a : separatedNums)
arrayList.add(Integer.parseInt(a));
minNum=min(arrayList);
maxNum=max(arrayList);
//Output the results
System.out.println("Minimum Number="+minNum+" has
"+minOccur(minNum,arrayList)+" occurances");
System.out.println("Maximum Number="+maxNum+" has
"+maxOccur(maxNum,arrayList)+" occurances");
//Close the scanner
in.close();
}
}

I have to take integers in an array and output them in random order

This is the output i need (
Input Array: 1 2 3 4 5 6 7
Random Output: 7 2 3 6 1 5 4)
this is what i get
Input size of the Array
5
Input Value
1
Input Value
2
Input Value
3
Input Value
4
Input Value
5
Random Output: 2
Random Output: 0
Random Output: 0
Random Output: 0
Random Output: 0
The problem is with line 23 and im not sure how to fix it
import java.util.Random;
import java.util.Scanner;
public class problem_2 {
public static void main(String args[]){
Random r = new Random();
Scanner m = new Scanner(System.in);
System.out.println("Input size of the Array");
int size = m.nextInt();
int a[] = new int[size];
int b[] = new int[size];
for(int i = 0;i<a.length;i++) {
System.out.println("Input Value " +(i+1));
a[i] = m.nextInt();
}
int cell = 0;
int x = r.nextInt(size);
int value = a[x];
while(cell<size) {
for(int i =0; i<= size;i++) {
if (b[i]==value) {
cell++;
}
if(cell==0) {
b[cell] = value;
cell++;
}
System.out.println("Random Output: "+b[i]);
}
}
}
}
The problem is your code is going one too many indexes in the following for loop:
for(int i =0; i<= size;i++)
That's because you have to remember an array with say 5 elements has indexes 0-4. So while the size is the number of elements in the array the largest index is always (the number of elements) - 1.
So you should write the for loop like so:
for(int i = 0; i < size;i++)
Even then your code doesn't quite randomize correctly. The easiest way to randomize an array would be to swap out each element with another random element, like this:
//Randomize the array
for(int i = 0; i < size;i++) {
//lets get a random index in the array
int randIndex = (int)(Math.random()*size);
//then we will store the index we are swapping because its going to be overwritten
int temp = a[i];
//set our index equal to the random one
a[i] = a[randIndex];
//put our index's original value into the random index, so its not lost
a[randIndex] = temp;
}
thanks everyone for the help but i didnt learn any of the things in the others so
i found a easier way to do it
import java.util.Random;
import java.util.Scanner;
public class random{
public static void main(String args[]){
Random r = new Random();
Scanner m = new Scanner(System.in);
System.out.println("Input size of the Array");
int size = m.nextInt();
int a[] = new int[size];
int b[] = new int[size];
for(int i = 0;i<a.length;i++) {
System.out.println("Input Value ");
a[i] = m.nextInt();
}
int cell = 0;
while(cell<size) {
int n = r.nextInt(size);
int value = a[n];
int count = 0;
for(int i =0; i< size;i++) {
if (b[i]== value) {
count++;
}
}
if(count==0) {
b[cell] = value;
cell++;
}
}
System.out.println ("\n");
System.out.println("Input Array: ");
for (int i = 0; i<size; i++){
System.out.print(a[i] + " ");
}
System.out.println ("\n");
System.out.println("Random Output: ");
for (int i = 0; i<size; i++){
System.out.print(b[i] + " ");
}
}
}

Searching for a value in an array, and storing it if it doesn't exist

I am looking to input an integer between 10 and 100 into a one dimensional array, and if the value already exists anywhere in the array, do not insert it into the array, but notify user and resume input until 5 unique numbers are added.
Here is my code. I know it's not right, but you can see that what I am trying to do is use simple for loops and a search method to get the numbers, store them into the array and search for a duplicate. My problem in my code is that I can't seem to set the number I just entered as the variable 'key' which I need to send to the method 'search'.
// input an integer between 10 and 100, add to array and print results. if value is already in array, notify user, print array. keep adding to array until 5 unique values have been entered
import java.util.Scanner;
public class ArraySearch {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] list = new int[5];
for (int i = 0; i < list.length; i++) {
System.out.println("Enter number: ");
list[i] = input.nextInt();
}
int count = search(list, key);
System.out.println("It has been entered.");
}
public static int search(int[] list, int key) {
int count = 0;
for (int i = 0; i < list.length; i++) {
if (list[i].equals(key)) {
;
}
count++;
}
return (count);
}
}
Simple example with array. Could improve with alternate data structure list set.
The search() method is essentially included within the while() loop, namely the for() loop examples the search for a target number already being included.
int c = 0; is declared before the loops and makes sure to find 5 unique numbers.
import java.util.Arrays;
import java.util.Scanner;
public class ArraySearch {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int[] list = new int[5];
int c = 0;
System.out.println("Enter number: ");
while (c < 5 && s.hasNext()) {
int n = s.nextInt();
boolean has = n >= 10 && n <= 100;
for (int i = 0; i <= c && !has; ++i)
if (list[i] == n)
has = true;
if (!has) {
System.out.println("It has been entered.");
list[c++] = n;
}
}
System.out.println("Result = " + Arrays.toString(list));
s.close();
}
}
Alternate version:
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class ArraySearch {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
Set<Integer> set = new HashSet<Integer>(5);
int c = 0;
System.out.println("Enter number: ");
while (c < 5 && s.hasNext()) {
int n = s.nextInt();
if ((n < 10) || (n > 100) || !set.add(n))
continue;
else {
System.out.println("It has been entered.");
c++;
}
}
System.out.println("Result = " + set);
s.close();
}
}
additionally, using search()
public class App {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int[] list = new int[5];
for (int i = 0; i < 5; i++) {
System.out.println("Enter number: ");
int n = s.nextInt();
if ((n >= 10 && n <= 100) && search(list, n) == 0) {
list[i] = n;
System.out.println("It has been entered.");
} else
i--;
}
System.out.println("Result = " + Arrays.toString(list));
s.close();
}
public static int search(int[] list, int key) {
int count = 0;
for (int i = 0; i < list.length; i++) {
if (list[i] == key) {
count++;
}
}
return count;
}
}
Edit: also added the 10-100 spec
edit2: using your approach with search() method
You are saving the input directly in the array.
Save the input in a temporal variable which you'll pass to search. And based on result of search you add to the array or prompt for another input.
int[] list = new int[5];
for (int i = 0; i < list.length; i++) {
System.out.println("Enter number: ");
int temp = input.nextInt();
if(search(list,temp) == 0)
list[i] = temp;
}else{
System.out.println("It has been entered.");
i--;
}
}

Java scanner output array values and output after sort method [duplicate]

This question already has answers here:
Need Java array help using scanner class to output an average and sort method
(4 answers)
Closed 6 years ago.
I have other code that outputs values such as min, max and average. I don't see how to output values in sorted arrays that user inputs through scanner.
import java.util.Scanner;
public class Arrayassignment {
public static void main(String[] args) {
Scanner keyboard=new Scanner(System.in);
System.out.println("Enter an integer for array size.");
int number= keyboard.nextInt();
int array[]=new int[number];
System.out.println("Array size " + number + " initiated.\n");
System.out.println("Now enter the array integers.");
for (int index = 0; index < number; index++)
{
array[index]=keyboard.nextInt();
}
keyboard.close();
System.out.println ( "Sorting " );
sort(array);
}
public static void sort(int[] arg) {
int arrange;
for (int i = 0; i < arg.length - 1; i++)
for (int j = i + 1; j < arg.length; j++) {
if (arg[i] > arg[j]) {
arrange = arg[i];
arg[i] = arg[j];
arg[j] = arrange;
System.out.println( arrange);
}
}
}
}
}
The question is bit unclear. I think what you want is to output and print the sorted array.
import java.util.Scanner;
import java.util.Arrays;
public class Arrayassignment {
public static void main(String[] args) {
Scanner keyboard=new Scanner(System.in);
System.out.println("Enter an intiger for array size.");
int number= keyboard.nextInt();
int array[]=new int[number];
System.out.println("Array size " + number + " initiated.\n");
System.out.println("Now enter the array intigers.");
for (int index = 0; index < number; index++)
{
array[index]=keyboard.nextInt();
}
keyboard.close();
System.out.println ( "Sorting " );
//call the sort mthod and get the returned sorted array
int[] sortedArray=sort(array);
//printing the sorted array
System.out.println(Arrays.toString(sortedArray));
}
public static int[] sort(int[] arg) {
int arrange;
for (int i = 0; i < arg.length - 1; i++){
for (int j = i + 1; j < arg.length; j++) {
if (arg[i] > arg[j]) {
arrange = arg[i];
arg[i] = arg[j];
arg[j] = arrange;
}
}
}
//return the sorted array
return arg;
}
}

Taking User Input for an Array

A link to the assignment:
http://i.imgur.com/fc86hG9.png
I'm having a bit of trouble discerning how to take a series of numbers and apply them to an array without a loop. Not only that, but I'm having a bit of trouble comparing them. What I have written so far is:
import java.util.Scanner;
public class Lottery {
public static void main(String[] args) {
int userInputs[] = new int[5];
int lotteryNumbers [] = new int[5];
int matchedNumbers =0;
char repeatLottery = '\0';
Scanner in = new Scanner (System.in);
do{
System.out.println("Enter your 5 single-digit lottery numbers.\n (Use the spacebar to separate digits): ");
for(int i = 0; i <5; i++ )
userInputs[i] = in.nextInt();
System.out.println("Your inputs: ");
printArray(userInputs);
System.out.println("\nLottery Numbers: ");
readIn(lotteryNumbers);
for(int i=0; i<5; i++) {
System.out.print(lotteryNumbers[i] + " ");
}
matchedNumbers = compareArr(userInputs, lotteryNumbers);
System.out.println("\n\nYou matched " + matchedNumbers + " numbers");
System.out.println("\nDo you wish to play again?(Enter Y or N): ");
repeatLottery = in.next().charAt(0);
}
while (repeatLottery == 'Y' || repeatLottery == 'y');
}
public static void printArray(int arr[]){
int n = arr.length;
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
}
public static void readIn(int[] List) {
for(int j=0; j<List.length; j++) {
List[j] = (int) (Math.random()*10);
}
}
public static int compareArr (int[] list1, int[] list2) {
int same = 0;
for (int i = 0; i <= list1.length-1; i++) {
for(int j = 0; j <= list2.length-1; j++) {
if (list1[i] == list2[j]) {
same++;
}
}
}
return same;
}
}
As you'll notice, I commented out the input line because I'm not quite sure how to handle it. If I have them in an array, I should be able to compare them fairly easily I think. This is our first assignment handling arrays, and I think it seems a bit in-depth for only having one class-period on it; So, please forgive my ignorance. :P
Edit:
I added a new method at the end to compare the digits, but the problem is it compares them in-general and not from position to position. That seems to be the major issue now.
your question isn't 100% clear but i will try my best.
1- i don't see any problems with reading input from user
int[] userInput = new int[5]; // maybe here you had a mistake
int[] lotterryArray = new int[5]; // and here you were declaring your arrays in a wrong way
Scanner scanner = new Scanner(system.in);
for ( int i = 0 ; i < 5 ; i++)
{
userInput[i] = scanner.nextInt();
} // this will populate your array try to print it to make sure
Edit : important in the link you shared about the assignment the compare need to check the value and location so if there are two 5 one in input one in loterry array they need to be in the same location check the assignment again
// to compare
int result = 0 ; // this will be the number of matched digits
for ( int i = 0 ; i < 5 ; i++)
{
if ( userInput[i] == loterryArray[i] )
result++
}
// in this comparsion if the digits are equale in value and location result will be incremented

Categories