(Java ) Finding the largest number in an array and it's location - java

I'm currently learning Java and while I'm able to find the largest number I'm stuck on how to find it's location. Any help would be greatly appreciated!
import java.util.Random;
public class FindingLargestValueInAnArray {
public static void main(String[] args) {
Random number = new Random();
int[] array_1 = new int[10];
int i = 0;
for (i = 0; i < array_1.length; i++) {
int randNum = 1 + number.nextInt(99);
array_1[i] = randNum;
}
System.out.print("Array:");
for (i = 0; i < array_1.length; i++) {
System.out.print(" " + array_1[i]);
}
int largeNumb = 0;
for (i = 0; i < array_1.length; i++) {
if (array_1[i] > largeNumb) {
largeNumb = array_1[i];
}
}
System.out.println("\n\nThe largest value is
"+largeNumb);
}
}

public class FindingLargestValueInAnArray {
public static void main(String[] args) {
Random number = new Random();
int[] array_1 = new int[10];
int i = 0;
for (i = 0; i < array_1.length; i++) {
int randNum = 1 + number.nextInt(99);
array_1[i] = randNum;
}
System.out.print("Array:");
for (i = 0; i < array_1.length; i++) {
System.out.print(" " + array_1[i]);
}
int largeNumb = 0;
int index = 0;
for (i = 0; i < array_1.length; i++) {
if (array_1[i] > largeNumb) {
largeNumb = array_1[i];
index = i;
}
}
System.out.println("The largest value is " + largeNumb + " and it's location is" + index);
}
}

You should get an another variable for the index = 0 and then put it inside the if statement and make it equal to index = i;. After the loop ends the largest value index would be stored here.

you can make an int index=0
in the loop where you check if the number is bigger in the body of the if make infex=i. This way you will always have both the value and the index of the largest numnber.

import java.util.Random;
public class FindingLargestValueInAnArray {
public static void main(String[] args) {
Random number = new Random();
int[] array_1 = new int[10];
int i = 0;
for (i = 0; i < array_1.length; i++) {
int randNum = 1 + number.nextInt(99);
array_1[i] = randNum;
}
System.out.print("Array:");
for (i = 0; i < array_1.length; i++) {
System.out.print(" " + array_1[i]);
}
int largeNumb = array_1[0];
int index = 0;
for (i = 1; i < array_1.length; i++) {
if (array_1[i] > largeNumb) {
largeNumb = array_1[i];
index = i;
}
}
System.out.println("\n\nThe largest value is :" + largeNumb + " and it's index is: " + index);
}
}

Related

I need to find the first maximum element in a 2D matrix using java but the code doesn't seem to work like i wanted it to. Can anyone help me?

I need the maximum elements position if there is more than one maximum element then the first one is to be printed.
My code prints the position of the maximum element but not the first one.
I don't understand why the last iteration is not working as I intend it to.
Please solve it using only Java.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
// put your code here
Scanner sc = new Scanner(System.in);
// define lengths
int n = sc.nextInt();
int m = sc.nextInt();
// add length to matrix
int[][] matrix = new int[n][m];
// insert elements
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
matrix[i][j] = sc.nextInt();
}
}
// define max
int max = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (matrix[i][j] > max) {
max = matrix[i][j];
}
}
// System.out.print(i + " " + j);
}
// System.out.print(max + " ");
// print index of highest element
// int pos1 = 0;
// int pos2 = 0;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
if (matrix[i][j] == max) {
System.out.print(i + " " + j);
break;
}
// pos2 += 1;
break;
}
// pos1 += 1;
// break;
}
}
}
There is no need to go through the matrix twice. When you are searching for the max, store also the coordinates of the matrix where that max was found. A code example:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
// put your code here
Scanner sc = new Scanner(System.in);
// define lengths
int n = sc.nextInt();
int m = sc.nextInt();
// add length to matrix
int[][] matrix = new int[n][m];
// insert elements
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
matrix[i][j] = sc.nextInt();
}
}
// define max
int max = Integer.MIN_VALUE, row=0, col=0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (matrix[i][j] > max) {
max = matrix[i][j];
row=i;
col=j;
}
}
}
System.out.print("max: "+max + " is at: ");
System.out.print(col + " " + row); //indexes starting from zero
}
}
Create a new variable to hold the position of the max value and set it in the current loop
int max = matrix[0][0];
int[] maxPos = new int[2];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (matrix[i][j] > max) {
max = matrix[i][j];
maxPos[0] = i;
maxPos[1] = j;
}
}
}
and then remove the rest of the code and print the result
System.out.printf("Max is %d and is found at [%d, %d]\n", max, maxPos[0], maxPos[1]);

Sort random array in ascending order without arrays.sort

I am trying to sort an array of random numbers without using the arrays.sort. I have the code, but it doesn't work. not sure where is the error. Any kind of help is appreciated.
import java.util.*;
public class Sort
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.print("How many numbers do you want? ");
int howMany = in.nextInt();
int [] myArray = getRandomArray(howMany);
}
/* public static int bsearch(int[] arr, int key)
{
}*/
public static int[] getRandomArray(int howMany) {
int[] returnMe = new int[howMany]; // Assume size >= 0
Random rand = new Random();
for (int i = 0; i < howMany ; i++)
returnMe[i] = rand.nextInt(Integer.MAX_VALUE) + 1;
//System.out.print(returnMe[i] + " ");
for (int i = 1; i <= (howMany - 1); i++)
{
for (int j = 0; j < howMany - i -1; j++)
{
int tmp = 0;
if (returnMe[j] > returnMe[j+1])
{
tmp = returnMe[j];
returnMe[j] = returnMe[j + 1];
returnMe[j + 1] = tmp;
}
}
}
for ( int i = 0; i < howMany; i++)
System.out.println(returnMe[i] + " ");
return returnMe;
}
}
Your line
for (int j = 0; j < howMany - i -1; j++)
should be
for (int j = 0; j <= howMany - i -1; j++)
or alternatively, remove the "-1" and keep "<". Otherwise, you will ignore the last number in the array. Everything else looks fine to me.

Sorting multidimensional array without sort method?

I was tasked with creating a 2D array (10-by-10), filling it with random numbers (from 10 to 99), and other tasks. I am, however, having difficulty sorting each row of this array in ascending order without using the array sort() method.
My sorting method does not sort. Instead, it prints out values diagonally, from the top leftmost corner to the bottom right corner. What should I do to sort the numbers?
Here is my code:
public class Program3
{
public static void main(String args[])
{
int[][] arrayOne = new int[10][10];
int[][] arrayTwo = new int[10][10];
arrayTwo = fillArray(arrayOne);
System.out.println("");
looper(arrayTwo);
System.out.println("");
sorter(arrayTwo);
}
public static int randomRange(int min, int max)
{
// Where (int)(Math.random() * ((upperbound - lowerbound) + 1) + lowerbound);
return (int)(Math.random()* ((max - min) + 1) + min);
}
public static int[][] fillArray(int x[][])
{
for (int row = 0; row < x.length; row++)
{
for (int column = 0; column < x[row].length; column++)
{
x[row][column] = randomRange(10,99);
System.out.print(x[row][column] + "\t");
}
System.out.println();
}
return x;
}
public static void looper(int y[][])
{
for (int row = 0; row < y.length; row++)
{
for (int column = 0; column < y[row].length; column++)
{
if (y[row][column]%2 == 0)
{
y[row][column] = 2 * y[row][column];
if (y[row][column]%10 == 0)
{
y[row][column] = y[row][column]/10;
}
}
else if (y[row][column] == 59)
{
y[row][column] = 99;
}
System.out.print(y[row][column] + "\t");
}
System.out.println();
}
//return y;
}
public static void sorter(int[][] z)
{
int temp = 0;
int tempTwo = 0;
int lowest;
int bravo = 0;
int bravoBefore = -1;
for (int alpha = 0; alpha < z.length; alpha++)
{
//System.out.println(alpha + "a");
lowest = z[alpha][bravoBefore + 1];
bravoBefore++;
for (bravo = alpha + 1; bravo < z[alpha].length; bravo++)
{
//System.out.println(alpha + "b");
temp = bravo;
if((z[alpha][bravo]) < lowest)
{
temp = bravo;
lowest = z[alpha][bravo];
//System.out.println(lowest + " " + temp);
//System.out.println(alpha + "c" + temp);
tempTwo = z[alpha][bravo];
z[alpha][bravo] = z[alpha][temp];
z[alpha][temp] = tempTwo;
//System.out.println(alpha + "d" + temp);
}
}
System.out.print(z[alpha][bravoBefore] + "\t");
}
/*
for (int alpha = 0; alpha < z.length; alpha++)
{
for (int bravo = 0; bravo < z.length - 1; bravo++)
{
if(Integer.valueOf(z[alpha][bravo]) < Integer.valueOf(z[alpha - 1][bravo]))
{
int[][] temp = z[alpha - 1][bravo];
z[alpha-1][bravo] = z[alpha][bravo];
z[alpha][bravo] = temp;
}
}
}
*/
}
}
for(int k = 0; k < arr.length; k++)
{
for(int p = 0; p < arr[k].length; p++)
{
least = arr[k][p];
for(int i = k; i < arr.length; i++)
{
if(i == k)
z = p + 1;
else
z = 0;
for(;z < arr[i].length; z++)
{
if(arr[i][z] <= small)
{
least = array[i][z];
row = i;
col = z;
}
}
}
arr[row][col] = arr[k][p];
arr[k][p] = least;
System.out.print(arr[k][p] + " ");
}
System.out.println();
}
Hope this code helps . Happy coding
let x is our unsorted array;
int t1=0;
int i1=0;
int j1=0;
int n=0;
boolean f1=false;
for(int i=0;i<x.length;i++){
for(int j=0;j<x[i].length;j++){
t1=x[i][j];
for(int m=i;m<x.length;m++){
if(m==i)n=j+1;
else n=0;
for(;n<x[m].length;n++){
if(x[m][n]<=t1){
t1=x[m][n];
i1=m;
j1=n;
f1=true;
}
}
}
if(f1){
x[i1][j1]=x[i][j];
x[i][j]=t1;
f1=false;
}
}
}
//now x is sorted; "-";

Checking For Repeats

I'm trying to write code that checks for repeat numbers in an array. If numbers repeat within the same row, it should generate another random number to replace the number. This is my class/method that is meant to accomplish this goal:
import java.util.*;
public class NoRepeats
{
public static void clean(int ticks[][])
{
for(int i = 0; i < ticks.length; i++)
{
for(int j = 0; j < ticks[0].length; j++)
{
nums[j] = ticks[i][j];
}
for(int k = 0; k < nums.length; k++)
{
for(int count = k + 1; count < nums.length; count++)
{
int othNums = nums[count];
while(true)
{
if(nums[k] == othNums)
{
System.out.print("\n\n Repeat:" + nums[k] + k + " " + othNums + "\tTicket Number: " + (i+1) +"\n\n\n");
nums[k] = 1 + rndm.nextInt(48);
for(int counter = count; counter < nums.length; counter++)
{
int othNums2 = nums[count];
if(nums[k] == othNums2)
{
System.out.print("\n\n Repeat NUM2:" + nums[k] + " " + othNums2 + "\tTicket Number: " + (i+1) +"\n\n\n");
nums[k] = 1 + rndm.nextInt(48);
}
}
for(int l = 0; l < k; l++)
{
int othNums3 = nums[l];
if(nums[k] == othNums3)
{
System.out.print("\n\n RepeatNUM2: " + nums[k] + " " + othNums3 + "\tTicket Number: " + (i+1) +"\n\n\n");
nums[k] = 1 + rndm.nextInt(48);
}
}
}
else
{
break;
}
}
count++;
}
}
for(int q = 0; q < nums.length; q++)
{
ticks[i][q] = nums[q];
}
count = 0;
}
}
public static int nums[] = new int[6];
public static int count = 1;
public static Random rndm = new Random();
public static int numsMatched[] = new int[100];
}
For some reason, there are still matches and I don't know why. Can anyone find what I've done wrong?
You're incrementing count twice and thus skip entries:
for(int count = k + 1; count < nums.length; count++) //<- increment 1
{
int othNums = nums[count];
while(true)
{
//snip
}
count++; //<- increment 2
}
The problem probably originates from the fact that you have a static variable which is also called count and which will be shadowed by the count defined in the loop:
public static int count = 1;
So either remove the second increment or rename one of the variables.

Array Index Out of Bounds Error in Java

package test1;
import java.util.Scanner;
public class Question2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int traincars;
int maxweight;
int count = 0;
int total = 0;
maxweight = input.nextInt();
traincars = input.nextInt();
int[] trains = new int[traincars];
for(int i = 0; i < traincars; i++)
{
trains[i] = input.nextInt();
}
if (total < maxweight)
{
for(int i = 0; i < traincars; i++)
{
total = trains[i] + trains[i+1] + trains[i+2] + trains[i+3];
count++;
}
}else
{
count = count + 3;
}
System.out.println("count");
}
}
this is a really simple program but for some reason, the array for the traincars goes out of bounds..
Why is this happening?
The problem is here:
for(int i = 0; i < traincars; i++)
{
total = trains[i] + trains[i+1] + trains[i+2] + trains[i+3];
count++;
}
When i equals traincars-1 you will be accessing elements i+1, i+2. and i+3 which are out of bounds of your trains array.
If your logic is calling for calculating totals of 4 consecutive elements of the array then your for loop should stop earlier:
for(int i = 0; i < traincars - 3; i++) {...}
In the last iteration of
for(int i = 0; i < traincars; i++)
{
total = trains[i] + trains[i+1] + trains[i+2] + trains[i+3];
count++;
}
You try to access trains[i+1] and this is bigger than the length of your trains array.
To make this for loop matter you should just do the following:
for(int i = 0; i < traincars; i++)
{
total += trains[i]; //unless of course you need something else...
count++;
}

Categories