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.
Related
I am taking 10 elements and performing a bubble sort on them. I want to add an algorithm that repeats the sort until no swaps are needed to make this more efficient.
Essentially I want to:
repeat until no swaps done in a pass
For elements 1 to (n-1)
compare contents of element value 1 with the contents of the next value
if value 1 is greater than value 2
then swap the values
This is what I have done so far :
{
//create array
int[] iList = new int[10];
Scanner sc = new Scanner(System.in);
//takes in array input for 10 numbers
System.out.println("Enter a array of numbers ");
for(int i = 0; i< 10; i++ )
{
int num = i + 1;
System.out.println("Enter number " + num);
iList[i] = sc.nextInt();
}
//Bubble sorts the array
System.out.println("The array =");
for(int a = 0; a < iList.length; a++ )
{
for(int b = a+1; b < iList.length; b++)
{
if(iList[a] > iList[b])
{
int iTemp = iList[a];
iList[a] = iList[b];
iList[b] = iTemp;
}
System.out.println("Progress = " + Arrays.toString(iList) );
}
}
} ```
Here is my implementation :
public static void sort(int[] nums) {
boolean isSwapped;
int size = nums.length - 1;
for (int i = 0; i < size; i++) {
isSwapped = false;
for (int j = 0; j < size - i; j++) {
if (nums[j] > nums[j+1]) {
int temp = nums[j];
nums[j] = nums[j + 1];
nums[j + 1] = temp;
isSwapped = true;
}
}
if (!isSwapped) break;
}
System.out.println("Sorted Array: " + Arrays.toString(nums));
}
I'm struggling to finalize a project and I would appreciate anyone's help. Thanks in advance.
Requirements:
1. Print a list with 10 random numbers in a range from (1-100), Done.
2. Print the generated list in a crescent order;
3. Print the largest number from the generated list.
Below is what I have done and where I am stuck:
import java.util.Arrays;
import java.util.Random;
public class Project {
public static void main(String[] args) {
list(0, 0);
printMax(0);
//bubbleSort();
System.out.print("The sorted list is: "); //???
}
private static void list(int min, int max) {
int[] numbers = new int[10];
// Generates 10 Random Numbers in the range 1 -100
for (int i = 0; i<numbers.length; i++) {
numbers[i] = (int)(Math.random() * 100 + 1);
}
System.out.println("The unsorted list is: " + Arrays.toString(numbers));
return;
}
private static void printMax(int...numbers) {
int result = numbers[0];
for (int i = 1; i<numbers.length; i++) {
if (numbers[i] > result)
result = numbers[i];
}
System.out.println("The largest value is " + numbers);
return;
}
public static void bubbleSort(int[] list) {
int temp;
for (int i = list.length - 1; i > 0; i--) {
for (int j = 0; j<i; j++) {
if (list[j] > list[j + 1]) {
temp = list[j];
list[j] = list[j + 1];
list[j + 1] = temp;
}
}
}
}
}
//Moises Isaias da Silva
public class Project_chapter_7 {
public static void main(String[] args) {
int[] my_list = generateRandomNumbers(1, 100);
printMax(my_list);
bubbleSort(my_list);
}
/*The function random of the class Math generate an random double number between 0 and 1.0.
* So, if we want an number between 1 and 100, we just multiply the value for 100
* (to get the maximum of random numbers) and add 1 at the end,
* to exclude the 0 case
* */
private static int[] generateRandomNumbers(int min, int max) {
int[] numbers = new int[10];
// Generates 10 Random Numbers in the range 1 -100
for (int i = 0; i < numbers.length; i++) {
numbers[i] = (int) (Math.random() * max + min);
}
System.out.print("The unsorted list is: ");
printValuesFromArray(numbers);
return numbers;
}
private static void printValuesFromArray(int[] numbers) {
for (int i = 0; i < numbers.length; i++) {
System.out.print(numbers[i] + " ");
}
}
//Now we find the largest number, comparing each number of the list (generateRandomNumbers)
private static void printMax(int... numbers) {
int result = numbers[0];
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] > result) {
result = numbers[i];
}
}
System.out.println("\nThe largest value is " + result);
return;
}
public static void bubbleSort(int[] list) {
int temp;
//The first value of i is the last value of the array, for this case, the first i will be 9
//(because the index of the last number on array is 9)
//i represent the outside loop, and will be decrement every time until reach the 0 value
for (int i = list.length - 1; i > 0; i--) {
for (int j = 0; j < i; j++) {
if (list[j] > list[j + 1]) {
temp = list[j];
list[j] = list[j + 1];
list[j + 1] = temp;
}
}
}
System.out.print("The sorted list is: ");
printValuesFromArray(list);
}
}
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;
}
}
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.