I am writing a program using a method that returns the location of the largest element in a two dimensional array.
Example:
Enter the number of rows and columns of the array:
3 4
Enter the array:
23.5 35 2 10
4.5 3 45 3.5
35 44 5.5 9.6
the location of the largest element is at (1, 2)
My code is working, but I'm getting the output wrong. Instead of numbers I am getting some weird output with letters and numbers. How can I fix it? Thanks!
My code
import java.util.Scanner;
public class homework1a {
public static int[] locateLargest(double[][] a)
{
int total = 0;
int maxRow = 0;
int maxColumn = 0;
for (int i = 0; i < a.length; i++)
{
for (int j = 0; j < a[i].length; j++)
{
maxRow = i;
maxColumn = j;
}
}
int[] largest = new int[2];
largest[0] = maxRow;
largest[1] = maxColumn;
return largest;
}
public static void main(String[] args)
{
//Create Scanner
Scanner input = new Scanner(System.in);
double b = 0;
//User input rows and columns
System.out.println("Enter the number of rows and columns in the array: ");
int numberOfRows = input.nextInt();
int numberOfColumns = input.nextInt();
//User input data in array
System.out.println("Enter numbers into array: ");
//Create array
double[][] a = new double[numberOfRows][numberOfColumns];
for (int i = 0; i < a.length; i++)
{
for (int j = 0; j < a[i].length; j++)
{
a[i][j] = input.nextDouble();
}
}
System.out.println("The location of the largest element is at "+ locateLargest(a));
}
}
Your method locateLargest() returns an int-array, which you are implicitly converting to string while printing it.
I think you want to display the row and cell numbers inside the array:
int[] largest = locateLargest(a);
System.out.println(String.format("The location of the largest element is at %d,%d", largest[0], largest[1]));
locateLargest(a) returns an int[2]. Arrays cannot be converted to strings natively, so the default toString() implementation is invoked on the array. The returned string representation does not contain the array elements.
This question might help you to print a helpful representation of the array. You might also want to print both values independently, not the array as a whole, e.g. like this:
int[] pos = locateLargest(a);
System.out.println("The location of the largest element is at " + pos[0] + ":" + pos[1]);
To print Arrays use Arrays.toString(array) output will be like [x,y]
System.out.println("The location of the largest element is at "+ Arrays.toString(locateLargest(a)));
Your method locateLargest returns an int[] which will not be printed out nicely.
If you want to keep the signature of locateLargest as it is, you could change your code in main like this:
int[] positionOfLargest = locateLargest(a);
System.out.println("The location of the largest element is at " +
positionOfLargest[0] + "/" + positionOfLargest[1]);
This stores the result in positionOfLargest and then prints out x/y coordinates the way you want them.
Hey for finding largest you can have your method like this.
public static int[] locateLargest(double[][] a)
{
int maxValue = 0;
int maxRow = 0;
int maxColumn = 0;
for (int i = 0; i < a.length; i++)
{
for (int j = 0; j < a[i].length; j++)
{
If(a[i][j] > maxValue)
{
maxValue = a[i][j] ;
maxRow = i;
maxColumn = j;
}
}
}
int[] largest = new int[2];
largest[0] = maxRow;
largest[1] = maxColumn;
return largest;
}
u should edit your locateLargest as this:
public static int[] locateLargest(double[][] a)
{
//may be ur array is contain negative
//so u can not use zero as MAX it's better to use first array element
int MAX = a[0][0];
int maxRow = 0;
int maxColumn = 0;
for (int i = 0; i < a.length; i++)
{
for (int j = 0; j < a[i].length; j++)
{
if(MAx < a[i][j]){
maxRow = i;
maxColumn = j;
}
}
}
int[] largest = new int[2];
largest[0] = maxRow;
largest[1] = maxColumn;
String result="location of largest num =a["+maxRow+"]["+maxColumn+"]";
return largest;
}
Related
My code is almost done but the problem is the returning size it supposed to return the size after the duplicated elements has been removed. it wont output the right size.
import java.util.Scanner;
import java.util.Arrays;
public class Main
{
public static void main (String[] args)
{
int size;
int i;
int j;
Scanner scn = new Scanner(System.in);
System.out.print("Enter the number of elements: ");
size = scn.nextInt();
System.out.println("\n");
int myArray[] = new int [size];
for(i = 0; i < size; i++)
{
System.out.print("Enter value for num["+i+"]: ");
myArray[i] = scn.nextInt();
}
System.out.print("\nThe inputted values are ");
for(i = 0; i < size; i++)
{
System.out.print(" " + myArray[i] + ",");
}
System.out.print("\nDuplicate values ");
for (i = 0; i < myArray.length-1; i++)
{
for (j = i+1; j < myArray.length; j++)
{
if ((myArray[i] == myArray[j]) && (i != j))
{
System.out.print(" " +myArray[j]+ ",");
}
}
}
int length = myArray.length;
length = remove_dupli(myArray,length);
System.out.print("\nThe new values of the array are ");
for(i = 0; i < length; i++)
{
System.out.print(" " +myArray[i]+", ");
}
System.out.println("\nThe new length of the array is: "+array_sort(myArray));
}
is there a problem on this part?
public static int remove_dupli(int myArray[], int n){
if (n==0 || n==1){
return n;
}
int[] temp = new int[n];
int j = 0;
for (int i=0; i<n-1; i++){
if (myArray[i] != myArray[i+1]){
temp[j++] = myArray[i];
}
}
temp[j++] = myArray[n-1];
for (int i=0; i<j; i++){
myArray[i] = temp[i];
}
return j;
}
or this part?
public static int array_sort(int[] myArray) {
int index = 1;
for (int i = 1; i < myArray.length; i++) {
if (myArray[i] != myArray[index-1])
myArray[index++] = myArray[i];
}
return index;
}
}
The output should be:
Enter Number of Elements: 4
Enter value for num[0]: 2
Enter value for num[1]: 2
Enter value for num[2]: 3
Enter value for num[3]: 4
The inputted values are 2,2,3,4
Duplicated values 2,
The new values of the array are 2,3,4
The new length of the array is 3
The process you are using to find the duplicate elements is fine but you are not actually changing the elements in the array , you are just printing the non-duplicate ones, best approach is to change the value of the duplicate elements as a flag and then to find the length of the array after the duplicates have been removed,it will be easy :
for(int i=0;i<array.length;i++){
for(int j=i+1;j<array.length;j++)
{
if((array[i]==array[j]) && i!=j)
System.out.println("duplicate value:"array[j]);
array[j]=-1;
}
}
So, now for the array length after removing the duplicate elements is:
int count=0;
for(int i=0;i<array.length;i++){
if(array[i]!=-1)
count ++;
}
Can someone please explain the thought process behind this code? I am kind of confused on how it works. This is the question that the code is addressing:
Write code (using one or more loops) to fill an array "a" with 10 different random numbers between 1 and 10.
Thank you so much for any help!
public static void main(String[] args){
//R8.8
int a[] = new int[10];
Random randomGenerator = new Random();
for (int i = 0; i < a.length; i++){
a[i] = 1 + randomGenerator.nextInt(100);
}
for (int i = 0; i < a.length; i++) {
int number = 1 + randomGenerator.nextInt(100);
int count = 0;
for (int j = 0; j < i; j++) {
if (a[j] == number) {
count += 1;
}
}
if (count > 0) i -= 1;
else a[i] = number;
}
}
}
See my comments in the code itself:
public static void main(String[] args){
//make a new array of 10 integers
int a[] = new int[10];
//declare an object which we can use to generate random numbers
//this object probably uses the system time to generate numbers that appear random
//but at the end of the day, java does it for us so
//we don't really need to know or care how it generates random numbers
Random randomGenerator = new Random();
//loop over each element in our array
for (int i = 0; i < a.length; i++){
//for each element, set that element to a random between 1 and 100 inclusive
//nextInt(x) gets a number between 0 (inclusive) and x (not inclusive)
//so to translate that to 1 to x inclusive, we need to add 1 to the result
a[i] = 1 + randomGenerator.nextInt(100);
}
//everything below here does literally nothing to solve the problem
//everything you need to fill the array with random numbers is above
for (int i = 0; i < a.length; i++) {
int number = 1 + randomGenerator.nextInt(100);
int count = 0;
for (int j = 0; j < i; j++) {
if (a[j] == number) {
count += 1;
}
}
if (count > 0) i -= 1;
else a[i] = number;
}
}
}
Please note that you should use 1 + randomGenerator.nextInt(10); to fill the array with numbers between 1 and 10, not 1 + randomGenerator.nextInt(100);.
I was trying to write a method that finds the largest number in a column. However, it seems that I am having problem to find a way to return the highest number in a column rather than taking into consideration all numbers combined in the array. I would really appreciate any comments or feedback!
This is my code:
public static void max1(int[][] score) {
for (int i = 0; i < score.length; i++) {
int max = score[0][0];
for (int j = 0; j < score[i].length; j++)
if (score[i][j] > max)
max = score[i][j];
System.out.println(max + " ");
}
}
You are trying to find the max in row not in column. Do some changes in your code
public static void max1(int[][] score) {
for (int i = 0; i < score[0].length; i++) { // i should be your column
int max = score[0][i];// assign 1st value of the column as max
for (int j = 0; j < score.length; j++){ // j is your row
if (score[j][i] > max){ // check the column elements instead of row elements
max = score[j][i];// get the column values
}
}
System.out.println(max + " ");
}
}
Do int max = score[0][i]; instead of int max = score[0][0]; Because if you always intialize max with score[0][0] and this int is bigger then the biggest value in a column, you will get a wrong result.
And do:
if (score[innerloop][outerloop] > max)
max = score[innerloop][outerloop];
instead of:
if (score[outerloop][innerloop] > max)
max = score[outerloop][innerloop];
That was logical failure because the first index is the column and the secound is the row.
score[0][0] = 1;
score[0][1] = 2;
score[0][2] = 3;
score[1][0] = 4;
score[1][1] = 5;
score[1][2] = 6;
score[2][0] = 7;
score[2][1] = 8;
score[2][2] = 9;
The Array now look like this matrix:
1 2 3
4 5 6
7 8 9
You want compare for example 1,4,7 so you habe to compare score[0][0], score[0][1], score[0][2]. So the secound index must be the counter of the inner for-loop.
You need to specify the index of the column you want to find the max in and loop on rows:
public static int maxCol(int [][] score, int colIndex) {
int max = score[0][colIndex];
for(int i = 0 ; i < score.length ; ++i) {
max = Math.max(max, score[i][colIndex]);
}
return max;
}
public static void max1(int[][] score) {
for (int i = 0; i < score.length; i++) {
int max = -1;
for (int j = 0; j < score[i].length; j++)
if (score[i][j] > max)
max = score[i][j];
System.out.println("max: '" + max + "'");
}
}
And perhaps you switched your columns and rows, means you have to switch the code too, happened already a lot to me. Try to check if i is your rows and j is your columns.
The following code prints the Maximum Number in each column.
public static void max1(int[][] score) {
for (int i = 0; i < score.length; i++) {
int max = Integer.MIN_VALUE; // set max to minimum value before starting loop
for (int j = 0; j < score[i].length; j++)
{
if (score[i][j] > max)
max = score[i][j];
}
System.out.println(max + " ");
}
}
First you should change the int max = score[0][0]; into as int max = Integer.MIN_VALUE; as it might produce not valid result.
And the second is that you need to swap the index while compare
if (score[j][i] > max) {
max = score[j][i];
}
static int max1(int[][] score) {
int max = score[0][0]; // set initial value to the first index in array
for (int i = 0; i < score.length; i++) { // cycle through row
for (int j = 0; j < score[i].length; j++) { // cycle through colmn
if (score[i][j] > max) { // if the index value is greater than largest number
max = score[i][j]; // make it the new index value
}
}
} return max;
}
So here's my problem. I have to write a program that will fill array with random numbers(and it's ok), then it's necessary to print only even index numbers or only odd value numbers(j). Tried like this but when i put if statement and it shows every even number (index and value-the second in array) so it wrong. What should i do so?
import java.util.Random;
public class Array {
public static void main(String[] args)
{
int rows = 5;
int colu = 2;
Random r = new Random();
int [][] array = new int [rows][colu];
for(int row = 0; row < array.length; row++)
{
for(int col = 0; col < array[row].length; col++)
{
array[row][col] = r.nextInt(10);
}
}
for(int i = 0; i < array.length; i++)
{
for(int j = 0; j < array[i].length; j++)
{
if(array[i][j]%2 == 0){
System.out.print(array[i][j] + " ");
}
}
}
System.out.println();
}
}
Thanks
I'm going to take a stab at this but I'm not sure if I quite understand yet.
int array[][] = new int[row][col];
// ... populate the array with random numbers, works fine...
// Let's traverse the first column.
for (int i = 0; i < row; i++) {
int value = array[i][0]; // col 0 means first column
if (value % 2 == 0) {
// ...
}
}
// Let's traverse the second column.
for (int i = 0; i < row; i++) {
int value = array[i][1]; // col 1 means second column
// ...
}
Is this what you mean? If it is, do you see the pattern and how you could generalize this and make the code a bit smaller?
Just implement this formula in your "if" statement :
(Number × 2 )/4 ==0. You will always get even numbers. You can handle the rest :D
I need help with sorting Random numbers into a 2D array. I have to generate 50 random numbers into a column of the array, then sort the numbers in order (ascending or descending). This is what I have so far and am so lost. Please Help.
UPDATED VERSION
public static void main(String[] args)
{
int rows = 2;
int columns = 50;
int[][] anArray = new int[rows][columns];
Random rand = new Random();
for (int i = 0; i < anArray.length; i++)
{
for (int j = 0; j < anArray[0].length; j++)
{
int n = rand.nextInt(100);
anArray[i][j] = n;
}
}
int []temp;
for (int i=0;i<anArray.length;i++)
{
for (int j=0;j<anArray.length-i;j++ )
{
if (anArray[i][j]>anArray[i][j+1])
{
temp =anArray[j];
anArray[j+1]=anArray[j];
anArray[j+1]=temp;
}
}
}
for (int i = 0; i < anArray.length; i++)
{
for (int j=0;j<anArray.length-i;j++ )
{
System.out.println(anArray[i][j]);
}
}
}
}
You can sort 2D arrays on their initial element using a custom Comparator:
Arrays.sort(anArray, new Comparator<int[]>() {
public int compare(int[] lhs, int[] rhs) {
return lhs[0]-rhs[0];
}
});
First of all, you need nested for loops in order to properly insert the random numbers into the two dimensional array. I have also updated my response to show how the sorting should be done. Hope this helps!
EDITED TO SATISFY REQUIREMENTS MENTIONED IN COMMENT BELOW.
import java.util.Arrays;
import java.util.Random;
public class Test {
/**
* #param args
*/
public static void main(String[] args) {
int rows = 2;
int columns = 50;
int[][] anArray = new int[rows][columns];
Random rand = new Random();
//initialize the first row only
for (int j = 0; j < anArray[0].length; j++)
{
int n = rand.nextInt(100);
anArray[0][j] = n;
}
System.out.println("-----------Before the Sort----------------");
for (int i = 0; i < anArray.length; i++)
{
for (int j = 0; j < anArray[0].length; j++)
{
System.out.print(anArray[i][j] + ", "); //format any way you want
}
System.out.println(); //to make each row print on a new line.
}
anArray = mySort(anArray);
System.out.println("-----------After the Sort----------------");
for (int i = 0; i < anArray.length; i++)
{
for (int j = 0; j < anArray[0].length; j++)
{
System.out.print(anArray[i][j] + ", "); //format any way you want
}
System.out.println(); //to make each row print on a new line.
}
}
private static int[][] mySort(int[][] anArray) {
int [][] result = new int[anArray.length][anArray[0].length];
int thisRow[] = getRow(anArray, 0);
Arrays.sort(thisRow);
for(int j = 0; j < thisRow.length; j++){
result[0][j] = anArray[0][j];
result[1][j] = thisRow[j];
}
return result;
}
private static int[] getRow(int[][] anArray, int row) {
int thisRow[] = new int[anArray[row].length];
for(int j = 0; j < anArray[row].length; j++){
thisRow[j] = anArray[row][j];
}
return thisRow;
}
}
You can sort by considering the 2D array 1D. Let's consider a 3x4 array.
1st element's index is 0, 2nd is 1, 3rd is 2, 4th is 3, 5th is 4, etc.
General formula to convert from a 1D index to a 2D:
row_index = _1D_index % nRows;
col_index = _1D_index % nCols;
For example the 5th element has the 1D index of 4, to get the row: 4 % 3 = 1, to get the col, 4 % 4 = 0, so your element is at 1,0. What's the point of all this? Now you can just make a function
int GetAt(int index)
{
return array[index % nRows][index % nCols];
}
and something along the lines of:
void Swap(int index1, int index2)
{
int r1 = index1 % nRows;
int c1 = index1 % nCols;
int r2 = index2 % nRows;
int c2 = index2 % nCols;
int temp = array[r1][c1];
array[r1][c1] = array[r2][c2];
array[r2][c2] = temp;
}
And sort the array as if it was one dimensional :)