I'm really stumped trying to find the index of the largest and smallest numbers of a 5x5 array with random numbers up to 1000 generated into them. Here my code:
import java.util.Random;
public class MaxMinArray {
public static void main (String args[]) {
int x=0, y=0, max=0, min=1000;;
int[][] numbers = new int[5][5];
for (x=0; x<numbers.length; x++) { //outer for
for(y=0; y<numbers.length; y++) { //inner for
numbers[x][y]= (int)(Math.random()*1000); //random generator
if(max < numbers[x][y]) //max number
max = numbers[x][y];
if(min>numbers[x][y]) //min number
min = numbers[x][y];
int maxIndex = 0;
for(int index = 1; index<numbers.length; index++)
if(numbers[maxIndex]< numbers[index])
maxIndex = index;
}
}
System.out.println("Max number in array:" + max + " ");
System.out.println("Max number is in" + maxIndex + " ");
System.out.println("Min number in array:" + min + " ");
}
}
You should keep track of both the x and y index of the maximum/minimum element. No need to post-process, it's just a matter of bookkeeping:
if(max < numbers[x][y]) {
max = numbers[x][y];
maxX = x;
maxY = y;
}
Use a Point to keep track of your indices.
Point min = new Point(0, 0);
Point max = new Point(0, 0);
for(int[] row: numbers) {
for(int col= 0; col < row.length; col++) {
if(numbers[row][col] < numbers[min.X][min.Y])
{max.X = row; min.Y = col;}
if(numbers[row][col] > numbers[max.X][max.Y])
{max.X = row; max.Y = col;}
}
}
if(numbers.length > 0) {
System.out.println(numbers[min.X][min.Y] + " is the minimum.");
System.out.println(numbers[max.X][max.Y] + " is the maximum.");
}
for something of this small of scale, a simple double for loop should be the simplest to understand and utilize.
int n=5;
int min = array[0][0];
int[] minIndex = {0,0};
int max = array[0][0];
int[] maxIndex = {0,0};
for (int i=0; i<n; i++)
{
for (int j=0; j<n; j++)
{
if (array[i][j] < min)
{
min = array[i][j];
minIndex[0] = i;
minIndex[1] = j;
}
if (array[i][j] > max) {
max = array[i][j];
maxIndex[0] = i;
maxIndex[1] = j;
}
}
}
For non-trivial dimensions this might be a slow method, but for this size matrix n^2 complexity is fine.
EDIT: WOW, I missed the part about the indices.
Related
I have complex task to differently sort two dimensional array manually.
So far I get done those tasks:
User needs to input row size from 10 - 20,
Generate 2D array where row size is user input and column size is randomly generated from 10-50,
Each array is filled with randomly generated numbers from 100 - 999,
Output each array row by its descending value,
Output average value of each array line,
Output on screen array with biggest average value,
So far I can't solve task Nr. 7. Output sorted two dimensional array by each lines average value.
Tried to implement new arrayAverage in loop to sort lines it didn't work.
Array just need to be sorted without creating new array.
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
public class SortArray2D {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Sorting two dimensional arrays!!!");
System.out.print("Enter arrays 1st dimension size 10 - 20: ");
int array1stDsize = sc.nextInt();
int array2ndDsize = new Random().nextInt(40) + 10;
System.out.println();
sc.close();
if (array1stDsize > 20 || array1stDsize < 10) {
System.out.println("The number you entered is too big or too small!!!");
} else {
//initializing array
int[][] array = new int[array1stDsize][array2ndDsize];
for (int i = 0; i < array.length; i = i + 1) {
for (int j = 0; j < array[i].length; j = j + 1) {
int input = new Random().nextInt(900) + 100;
array[i][j] = input;
}
}
System.out.println("Array element output: ");
arrayOutput(array);
// array element sorting from biggest to smallest
for (int k = 0; k < array.length; k++) {
for (int i = 1; i < array[k].length; i++) {
for (int j = i; j > 0; j--) {
if (array[k][j] > array[k][j - 1]) {
int element = array[k][j];
array[k][j] = array[k][j - 1];
array[k][j - 1] = element;
}
}
}
}
System.out.println();
System.out.println("Descending Array element output: ");
arrayOutput(array);
System.out.println();
System.out.println("Average value output by array: ");
float[] arrayAverage = new float[array1stDsize];
float average = 0;
for (int i = 0; i < array.length; i = i + 1) {
for (int j = 0; j < array[i].length; j = j + 1) {
average = average + array[i][j];
}
average = (float) (Math.round((average / array[i].length) * 100.0) / 100.0);
System.out.println(i + ". array average value: " + average);
arrayAverage[i] = average;
}
System.out.println();
System.out.println("New array from average values: ");
System.out.println(Arrays.toString(arrayAverage));
System.out.println();
System.out.println("Most valuest array is: ");
double max = 100;
int row = 0;
for (int i = 0; i < arrayAverage.length; i++) {
if (max < arrayAverage[i]) {
max = arrayAverage[i];
row = i;
}
}
System.out.print("Its founded " + row + ". row and it's value is: ");
for (int j = 0; j < array[row].length; j = j + 1) {
System.out.print(" " + array[row][j]);
}
System.out.println();
System.out.println();
//2D array sorting by average values
}
}
public static int[][] arrayOutput(int[][] array) {
for (int i = 0; i < array.length; i = i + 1) {
for (int j = 0; j < array[i].length; j = j + 1) {
if (j == 0) {
System.out.print("{ " + array[i][j]);
} else {
System.out.print(", " + array[i][j]);
}
}
System.out.print(" }");
System.out.println();
}
return array;
}
}
The part of your code that calculates the average:
float[] arrayAverage = new float[array1stDsize];
float average = 0;
for (int i = 0; i < array.length; i = i + 1) {
for (int j = 0; j < array[i].length; j = j + 1) {
average = average + array[i][j];
}
average = (float) (Math.round((average / array[i].length) * 100.0) / 100.0);
System.out.println(i + ". array average value: " + average);
arrayAverage[i] = average;
}
is slightly wrong, you need to set the average variable to zero before calculating the average of the next rows:
...
arrayAverage[i] = average;
average = 0;
With the Java Streams one can get the matrix sorted by average of rows pretty elegantly, namely:
Arrays.sort(array, comparingDouble(row -> IntStream.of(row)
.average()
.getAsDouble()));
To sort the array one uses the method Arrays.sort, and then for each row one gets its average as a double value IntStream.of(row).average().getAsDouble(), and used as the sorting parameter comparingDouble(....).
A running example:
import java.util.Arrays;
import java.util.Comparator;
import java.util.stream.IntStream;
import static java.util.Comparator.comparingDouble;
public class Test {
public static void main(String[] args) {
int array[][] = {{10, 20, 30},{40, 50, 60}, {1,2,3} };
Arrays.sort(array, comparingDouble(row -> IntStream.of(row).average().getAsDouble()));
Arrays.stream(array).map(Arrays::toString).forEach(System.out::println);
}
}
The output:
[1, 2, 3]
[10, 20, 30]
[40, 50, 60]
For the reverse order use instead:
Arrays.sort(array, comparing(row -> IntStream.of(row).average().getAsDouble(), reverseOrder()));
The output:
[40, 50, 60]
[10, 20, 30]
[1, 2, 3]
EDIT: WITH NO STREAMS
Without using streams what you can do is the following:
1 - Get the array with the averages of the matrix rows:
float[] arrayAverage = average(matrix);
You already know how to calculate the average, therefore you just need to extract a method out of the code that you have created, namely:
private static float[]average(int[][] array) {
float[] arrayAverage = new float[array.length];
float sum = 0;
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
sum += array[i][j];
}
arrayAverage[i] = (float) (Math.round((sum / array[i].length) * 100.0) / 100.0);
sum = 0;
}
return arrayAverage;
}
2 - Create an array that will represent the rows and initialized as the following:
int [] row_position = new int [arrayAverage.length];
for(int i = 0; i < row_position.length; i++)
row_position[i] = i;
3 - Sort the arrayAverage using the easiest sort, the bubble sort. While sorting that array update accordingly the positions stored on the row_position:
for(int i=0; i < arrayAverage.length; i++){
for(int j=1; j < (arrayAverage.length-i); j++){
if(arrayAverage[j-1] > arrayAverage[j]){
float temp = arrayAverage[j-1];
arrayAverage[j-1] = arrayAverage[j];
arrayAverage[j] = temp;
int temp_pos = row_position[j-1];
row_position[j-1] = row_position[j];
row_position[j] = temp_pos;
}
}
}
4 - Now that you have the row_positions array that tells you how the sorted rows should be rearranged, you just need to swap the rows accordingly:
int[][] tmp_matrix = new int [matrix.lenght][];
for (int i = 0; i < tmp_matrix.length; i++) {
tmp_matrix[i] = matrix[row_position[i]];
}
matrix = new_matrix;
Bear in mind, however, that for simplicity-sake I have assumed a quadratic matrix of NxN, and the above solution can be improved performance-wise.
At last, made it to work, looks like this.
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
public class SortArray2D {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Sorting two dimensional arrays!!!");
System.out.print("Enter arrays 1st dimension size 10 - 20: ");
int array1stDsize = sc.nextInt();
System.out.println();
sc.close();
if (array1stDsize > 20 || array1stDsize < 10) {
System.out.println("The number you enteraed is too big or too small!!!");
} else {
int[][] array = new int[array1stDsize][];
Random random = new Random();
for (int i = 0; i < array.length; i++) {
array[i] = new int[random.nextInt(31) + 10];
for (int j = 0; j < array[i].length; j++) {
int input = new Random().nextInt(900) + 100;
array[i][j] = input;
}
}
System.out.println("Array element output: ");
arrayOutput(array);
// array element sorting from biggest to smallest
for (int k = 0; k < array.length; k++) {
for (int i = 1; i < array[k].length; i++) {
for (int j = i; j > 0; j--) {
if (array[k][j] > array[k][j - 1]) {
int element = array[k][j];
array[k][j] = array[k][j - 1];
array[k][j - 1] = element;
}
}
}
}
System.out.println();
System.out.println("Descending Array element output: ");
arrayOutput(array);
System.out.println();
System.out.println("Average value output by array: ");
float[] arrayAverage = new float[array1stDsize];
for (int i = 0; i < array.length; i = i + 1) {
float sum = 0;
for (int j = 0; j < array[i].length; j = j + 1) {
sum = sum + array[i][j];
}
float average = (float) (Math.round((sum / array[i].length) * 100.0) / 100.0);
System.out.println(i + ". array average value: " + average);
arrayAverage[i] = average;
}
// array lines sorting from by average value increasing
for (int i = 0; i < arrayAverage.length; i = i + 1) {
for (int j = i; j > 0; j--) {
if (arrayAverage[j] < arrayAverage[j - 1]) {
float tmpor = arrayAverage[j];
arrayAverage[j] = arrayAverage[j - 1];
arrayAverage[j - 1] = tmpor;
int[] tmp = array[j];
array[j] = array[j - 1];
array[j - 1] = tmp;
}
}
}
System.out.println();
System.out.print("Array from average values sorted: ");
System.out.println(Arrays.toString(arrayAverage));
System.out.println();
System.out.println("Incerasing Array line output: ");
arrayOutput(array);
System.out.println();
System.out.print("Most valuest array is array: ");
double max = 100;
int row = 0;
for (int i = 0; i < arrayAverage.length; i++) {
if (max < arrayAverage[i]) {
max = arrayAverage[i];
row = i;
}
}
for (int j = 0; j < array[row].length; j = j + 1) {
System.out.print(" " + array[row][j]);
}
}
}
public static int[][] arrayOutput(int[][] array) {
for (int i = 0; i < array.length; i = i + 1) {
for (int j = 0; j < array[i].length; j = j + 1) {
if (j == 0) {
System.out.print("{ " + array[i][j]);
} else {
System.out.print(", " + array[i][j]);
}
}
System.out.print(" }");
System.out.println();
}
return array;
}
}
Output sorted 2d array in ascending order:
int[][] arr = {
{12, 54, 87}, // avg 51
{98, 56, 32}, // avg 62
{19, 73, 46}}; // avg 46
Arrays.stream(arr)
// sort an array by the
// average value of the row
.sorted(Comparator.comparingDouble(row ->
// get the average value or 0 if the row is empty {}
Arrays.stream(row).average().orElse(0)))
// string representation
// of the row content
.map(Arrays::toString)
// output line by line
.forEach(System.out::println);
Output:
[19, 73, 46]
[12, 54, 87]
[98, 56, 32]
My code is supposed to take the random number generated in the random method and sort them but it's only giving me one number.
My program is a random number generator that is supposed to make 1000 numbers that I can sort but my code only inserts one number into the array.
public static void main(String[] args) {
// write
int max = 1000;
int min=0;
int range = max - min + 1;
// generate random numbers within 1 to 10
for (int i = 0; i < 1000; i++) {
int rand = (int) (Math.random () * range) + min;
System.out.println ( rand );
int array[] = {rand};
int size = array.length;
for ( i = 0; i < size - 1; i++) {
int min1 = i;
for (int j = i + 1; j < size; j++) {
if (array[j] < array[min1]) {
min = j;
}
}
int temp = array[min1];
array[min1] = array[i];
array[i] = temp;
}
for (int k = 0; k < size; i++) {
System.out.print(" " + array[i]);
}
}
}
You need to break your program into separate steps:
Insert all the random numbers into the array
Sort the array
Print the contents of the array
Few problems I noticed:
Since you want to generate 1000 numbers from 1-10, max and min should have values of 10 and 1, respectively.
array should be declared before you start inserting values. It should also have a fixed size of 1000.
Your bubble sort algorithm also had some errors which led to incorrect output. If you wish to sort the array from greatest to least instead, simply change the > to < in the condition of the if statement.
I also decided to use Arrays.toString() to print the array instead of the loop.
public static void main(String[] args) {
int max = 10;
int min = 1;
int range = max - min + 1;
int size = 1000;
int[] array = new int[size];
for (int i = 0; i < size; i++) {
int rand = (int) (Math.random() * range + min);
array[i] = rand;
}
int temp = 0;
for (int i = 0; i < size; i++) {
for (int j = 1; j < size - i; j++) {
if (array[j - 1] > array[j]) {
temp = array[j - 1];
array[j - 1] = array[j];
array[j] = temp;
}
}
}
System.out.println(Arrays.toString(array));
}
your code will result an ArrayIndexOutException. below is the code change from your code ,i dont change too much so you can compare them and find your mistakes,wish good :D
public static void main(String[] args) {
int max = 1000;
int min=0;
int range = max - min + 1;
int[] array = new int[range];
// generate random numbers within 1 to 10
for (int i = 0; i < 1000; i++) {
int rand = (int) (Math.random () * range) + min;
array[i] = rand;
}
int size = array.length;
for (int i = 0; i < size; i++) {
int min1 = i;
for (int j = i + 1; j < size; j++) {
if (array[j] < array[min1]) {
min1 = j;//here min1
}
}
int temp = array[min1];
array[min1] = array[i];
array[i] = temp;
}
for (int k = 0; k < size; k++) {
System.out.print(" " + array[k]);
}
}
let me explain it more clearly,in the OP's code there has some questions,two majors:
one:
for ( i = 0; i < size - 1; i++) {
int min1 = i;
for (int j = i + 1; j < size; j++) {
if (array[j] < array[min1]) {
min = j;
}
}
int temp = array[min1];
array[min1] = array[i];
array[i] = temp;
}
will never run,because the array size is 1 ,so the for loop phrase will be ignore without running(mean for(int i = 0; i < 0; i++){....}).
two:
for (int k = 0; k < size; i++) {
System.out.print(" " + array[i]);
}
beacause the array size is 1,so when array[1] will throw index out exception.so the outermost loop will just run once then throw a exception.
:D
Hi in my program I want to display the average number, largest number, lowest number, and the mode in the array. So far only my average works and my methods for min and max both = the first number I enter. For example if I say I want to enter 3 numbers and I put 12, 15,and 6. The min and max will both output 12 since it's the first number entered and that's wrong so please help. Here's my code.
int amount;
System.out.println(" Enter the amount of numbers you would like to enter: ");
amount = scan.nextInt();
int [] arr = new int [amount];
int outcome = 1;
for (int i = 0; i < arr.length; i++){
System.out.println("Enter a number 1 through 50");
outcome = scan.nextInt();
arr [i] = outcome;
}
System.out.println(" ");
System.out.println( " The average is" );
System.out.println(average(arr));
System.out.println(" ");
System.out.println( " The lowest value in the array is " );
System.out.println(min(arr));
System.out.println(" ");
System.out.println( " The largest value in the array is " );
System.out.println(max(arr));
System.out.println(" ");
}
public static double average ( int [] arr) {
double sum = 0;
int value = arr.length;
for ( int i = 0; i < arr.length; i++){
sum += arr [i];
}
sum = sum / value;
return sum;
}
public static int min (int [] arr) {
int shortest = 0;
int smallest = 100;
int length = arr.length;
for ( int i = 0; i < arr.length; i ++ ) {
if ( length < smallest)
shortest += arr[i];
smallest = arr.length;
}
return shortest;
}
public static int max (int [] arr) {
int largest = 0;
int biggest = 0;
int length = arr.length;
for ( int i = 0; i < arr.length; i ++ ) {
if ( length > largest)
biggest += arr[i];
largest = arr.length;
}
return biggest;
}
}
This would be pretty straightforward. The reason both your min and max methods return 12 is because you set both largest and smallest to arr.length and thus immediately stop the for-loop after only one run. Also, there are far easier implementations for this kind of problem. Try doing something along these lines:
public int getMax(int[] arr)
{
int max = arr[0]; //To have a baseline
for(int i = 1; i < arr.length; i++)
{
if(arr[i] > max)
{
max = arr[i];
}
}
return max;
}
public int getMin(int[] arr)
{
int min = arr[0]; //To have a baseline
for(int i = 1; i < arr.length; i++)
{
if(arr[i] < min)
{
min = arr[i];
}
}
return min;
}
This is both far more readable and easier to execute. Just ask if you have any questions :-)
I'm trying to create a program that asks the user to input a number which is how many random numbers between 1-100 will be generated in an array. Then I want the largest number to be swapped with the last number and the smallest number to be swapped with the first number. Here is my code so far:
import java.util.Scanner;
import java.util.Random;
public class smallbig
{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Random randomGenerator = new Random();
int num = scan.nextInt();
int[] myArray = new int[num];
for (int i = 0; i < myArray.length; ++i) {
int randomInt = randomGenerator.nextInt(100);
myArray[i] = randomInt;
}
int smallest = myArray[0];
int largest = myArray[0];
for (int i = 1; i < myArray.length; i++) {
if (myArray[i] > largest) {
largest = myArray[i];
}
if (myArray[i] < smallest) {
smallest = myArray[i];
}
}
for (int j = 1; j < myArray.length; j++) {
int first = myArray[0];
myArray[0] = smallest;
smallest = first;
int temp = largest;
int last = myArray.length;
myArray[last - 1] = largest;
temp = myArray[last - 1];
System.out.print(myArray[j] + " ");
}
}
}
I can't seem to get the numbers to properly swap. I created a loop which determines the smallest and largest numbers from the ones generated and these are stored. Then I create a loop which performs the necessary swaps but I can't seem to get it to work properly. It works fine for swapping the largest number with the last number but most of the time(not always) the outputted last number is also present somewhere else in the array. Here is what I mean:
input: 10
output: 62 48 34 0 91 14 64 60 91
I know there is a swapper method that I could use but I want to do it by manually swapping the numbers. Any help is appreciated, thanks.
you have one simple mistake, your loop should start from '0' when you perform the swap
for (int j = 0; j < myArray.length; j++) {
int first = myArray[0];
myArray[0] = smallest;
smallest = first;
int temp = largest;
int last = myArray.length;
myArray[last - 1] = largest;
temp = myArray[last - 1];
System.out.print(myArray[j] + " ");
Instead of a loop do
//find and stores poition of small
int smallPos = myArray.indexOf(small);
//stores tge values at 0
int tempSmall = myArray[0];
//swaps the values
myArray[0] = small;
myArray[smallPos] = smallTemp;
Just repeat this with the largest value and print it using a for loop. Tell me if it works.
I just tried this. Hope this helps.
public class App {
static int[] a = new int[100];
public static void main(String[] args) {
int i;
for(i = 0; i<a.length;i++)
a[i] = (int)(java.lang.Math.random() * 100);
int smallest = 0, largest = 0;
for(i =1; i<a.length; i++){
if(a[i] < a[smallest])
smallest = i;
if(a[i] > a[largest])
largest = i;
}
swap(0,smallest);
swap(a.length-1,largest);
for(i =0; i<a.length;i++)
System.out.print(a[i] + " ");
}
public static void swap(int i, int j){
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
Your last loop doesn't do anything loopy. It just does the same thing over and over. And what it does is not correct. It is swapping the smallest into the first element but it's not moving the first element anywhere: it's gone.
You need to keep track of where the largest and smallest elements were. Your swap logic doesn't take that into consideration.
Write this code
import java.util.Scanner;
import java.util.Random;
public class smallbig
{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Random randomGenerator = new Random();
int num = scan.nextInt();
int[] myArray = new int[num];
for (int i = 0; i < myArray.length; ++i) {
int randomInt = randomGenerator.nextInt(100);
myArray[i] = randomInt;
}
int smallest = myArray[0];
int largest = myArray[0];
int pos1,pos2;
for (int i = 1; i < myArray.length; i++) {
if (myArray[i] > largest) {
largest = myArray[i];
pos1=i;
}
if (myArray[i] < smallest) {
smallest = myArray[i];
pos2=i;
}
}
myArray[pos1]=myArray[myArray.length-1];
myArray[myArray.length-1]=largest;
myArray[pos2]=myArray[0];
myArray[0]=smallest;
for (int j = 1; j < myArray.length; j++) {
System.out.print(myArray[j] + " ");
}
}
}
i would advise against using a scanner or random values for testing since the result cannot be reproduced (at least not in an easy way). Be careful with what is an arrays index and what is the value at a specific index. This can lead to confusion very quickly. ^^
import java.util.Scanner;
import java.util.Random;
public class smallbig
{
private static int[] myArray;
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Random randomGenerator = new Random();
//int num = scan.nextInt(); //skip this for testing ^^-d
int num = 10;
myArray = new int[num];
for (int i = myArray.length-1; i > 0; i--) {
//int randomInt = randomGenerator.nextInt(100);
int randomInt = i; //use test condition that can be reproduced!
myArray[i] = myArray.length-i;
}
int smallest = 0;
int largest = 0;
int smallestIndex = 0;
int largestIndex = 0;
for (int i = 0; i < myArray.length; i++) {
if (myArray[i] > largest) {
largest = myArray[i];
largestIndex = i;
}
if (myArray[i] < smallest) {
smallest = myArray[i];
smallestIndex = i;
}
}
switchIndexOfmyArray(0, smallestIndex);
switchIndexOfmyArray(myArray.length-1, largestIndex);
for (int j = 0; j < myArray.length; j++) {
System.out.print(myArray[j] + " ");
}
}
public static void switchIndexOfmyArray(int index, int switchWithIndex){
int temp = myArray[index];
myArray[index] = myArray[switchWithIndex];
myArray[switchWithIndex] = temp;
}
}
Yielding
0 1 8 7 6 5 4 3 2 9
I admit i was slow on this one since i am hungry and tired xD
Happy coding! ^^
You did well by finding smallest and largest. Issue was in swap. I refactor the swap method. May be it works.
import java.util.Scanner;
import java.util.Random;
public class smallbig
{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Random randomGenerator = new Random();
int num = scan.nextInt();
int[] myArray = new int[num];
for (int i = 0; i < myArray.length; ++i) {
int randomInt = randomGenerator.nextInt(100);
myArray[i] = randomInt;
}
for(int k=0; k < myArray.length; k++)
{
System.out.print(myArray[k] + " ");
}
System.out.println();
int smallest = myArray[0];
int largest = myArray[0];
int sIndx = 0;
int lIndx = 0;
for (int i = 1; i < myArray.length; i++) {
if (myArray[i] > largest) {
largest = myArray[i];
lIndx = i;
}
if (myArray[i] < smallest) {
smallest = myArray[i];
sIndx = i;
}
}
System.out.println();
System.out.println("Smallest = "+smallest);
System.out.println("largest = "+largest);
System.out.println("Smallest Index = "+sIndx);
System.out.println("largest Index = "+lIndx);
swapSmallAndLargest(num, myArray, sIndx, lIndx);
for(int k=0; k < myArray.length; k++)
{
System.out.print(myArray[k] + " ");
}
}
private static void swapSmallAndLargest(int num, int[] myArray, int sIndx, int lIndx) {
int temp = 0;
temp = myArray[sIndx];
myArray[sIndx] = myArray[0];
myArray[0] = temp;
temp = myArray[lIndx];
myArray[lIndx] = myArray[num-1];
myArray[num-1] = temp;
}
}
First of all I'm sorry if there is any mistake in the title of this question. I just don't know how to put it in a question. The following code rolls a dice thousand times and displays how many times a number on the dice is rolled. I want to print the index of the largest number not the element.
import java.util.Random;
public class apples {
public static void main(String args[]){
Random rand = new Random();
int a[] = new int[7];
for(int i = 1; i<1001; i++){
++a[rand.nextInt(6) + 1];
}
System.out.println("Roll\tTimes");
for(int j=1; j<a.length; j++){
System.out.println(j + "\t\t" + a[j]);
}
int max = a[0];
for (int i : a) {
if (max < i) {
max = i;
}
}
System.out.println("The winning number is " + max);
}
}
EDIT:
I figured how to get the index but is there an easier way to do it?
import java.util.Random;
public class apples {
public static void main(String args[]){
Random rand = new Random();
int a[] = new int[7];
int winner = 0;
for(int i = 1; i<1001; i++){
++a[rand.nextInt(6) + 1];
}
System.out.println("Roll\tTimes");
for(int j=1; j<a.length; j++){
System.out.println(j + "\t\t" + a[j]);
}
int max = a[0];
for (int i : a) {
if (max < i) {
max = i;
}
}
for(int j=0; j<a.length; j++){
if(max==a[j]){
winner = j;
}
}
System.out.println("The winning number is " + winner);
}
}
You will not be able to get the index of the array (directly) if you use for-each loop (like how you did), rather you need to use normal for loop as shown below in the code with comments:
int max = a[0];
int maxIndex = 0;//take a variable & Initialize to 0th index
for (int i=0; i<a.length;i++) {//normal for loop, not for each
if (max < a[i]) {
max = a[i];
maxIndex = i;//capture the maxIndex
}
}
System.out.println(": maxIndex :"+maxIndex);//print the maxIndex
You have to change your foreach to indexed for loop and keep a track of index of largest number.
Change this part to
int max = a[0];
for (int i : a) {
if (max < i) {
max = i;
}
}
Change it with
int max = a[0];
int index = 0;
for (int j = 0, aLength = a.length; j < aLength; j++) {
int i = a[j];
if (max < i) {
max = i;
index = j;
}
}
System.out.println("The winning number is " + max);
System.out.println("The winning index is " + index);
This will print the lasrgest number in which roll it was achieved.