Java Printing Array based off Another Array - java

I am trying to print an Array, however, I am needing to print the right array, off of an integer from another array.
(i.e.) arrayInt contains 2,4,6,5,1. I want to use a for loop to print the numbers. Then, I want to print the double that is corresponding to the int. arrayInt, that has been sorted, is 1,2,3,4,5 and arrayDouble, that hasn't been sorted, is 2.6,6.9,1.3,2.4,9.8. After I print arrayInt[0], which is 1, I want to print the corresponding (in this case the 1st) value in arrayDouble.
The following code is what I came up with:
for (int k = 0; k < 7; k++)
System.out.printf("%d %.2f\n", sortedNum[k], arrayWeight[(sortedNum[k])]);

I think you kinda answered your own question here, have you tried the code that you specified?
If I understood correctly you want to print something from an array based on the index that is stored in another array, if so, the following code should work (notice I removed the parenthesees from your code):
for (int k = 0; k < 7; k++) {
System.out.printf("%d %.2f\n", sortedNum[k], arrayWeight[sortedNum[k]]);
}
This is assuming sortedNum is an array of ints and arrayWeight is an array of floats.

You have to check size of second array before trying to fetch value from it
for (int k = 0; k < 7; k++) {
if (sortedNum[k] < arrayWeight.length)
System.out.printf("%d %.2f\n", sortedNum[k], arrayWeight[sortedNum[k]]);
}

Related

Delete the highest number of an array

First I created a random array then I decided to create another array to save the number except the highest. I got the prob when printing the array removed the highest number. I assume the issue when assigning item in b but I can't figure out. Please help :<
public static int[] deleteHighestNum(int a[]) {
int b[] = new int[a.length - 1];
for (int i = 0, j = 0; i < a.length; i++) {
if (a[i] > a[j]) {
b[j++] = a[j];
}
}
return b;
you first create a copy of the array with the .clone() method. This will be the second array you created. then you create an int x or something of this sort and set it equal to 0.
start now by iterating the array. if the number is greater then your int, replace the int.
once it is done, make another loop, that checks each value of your second array and if a number is equal to your int, delete it. done.

How to get index of array based on elements value Java

I have an array filled with double values. I want to get the index of the 2nd and the 3rd and 4th lowest values in the array. This is what I have tried but I haven't been getting what I want.
double[] wantedVals = new double [3];
for(double n :allValues){
if(n < wantedVals[2] && n > wantedVals[1]) {
wantedVals[2] = n;
}
}
System.out.println("All Values: "+ Arrays.toString(allValues));
System.out.println("2nd, 3rd, 4th lowest values index: " + Arrays.toString(wantedVals));
}
Here is the output.
All Values: [314.8490027477457, 558.1219589782775, 0.0, 538.3207360335937, 519.5707513178547, 271.85862019623363, 452.44377672120766, 448.3506884613316, 365.0024775172766, 380.61611237571117, 225.73376879634114, 310.28009020077326, 121.53621181051349, 95.45317487517113, 280.453364828718, 57.11775118122211, 343.1257001358977, 365.58868943629807, 530.7625668260243, 227.4473840254049, 319.9578951791938, 291.8377585984206, 494.999842171692, 464.97103404405743]
2nd, 3rd, 4th lowest values: [0.0, 0.0, 0.0]
What I want to do is get the indexes of the 2nd, 3rd and 4th lowest values in All Values array.
Do an index sort, and then output the indexes. Like this:
final int MAX_ARRAY_SIZE = (the biggest that your all values array will be)
int index[] = new int[MAX_ARRAY_SIZE];
for(int i = 0; i < allValues.length(); i++)
{
index[ i ] = i;
}
//Simple Bubble Sort
for(int i = 0; i < allValues.length() - 1; i++)
{
for(int j = i + 1; j < allValues.length(); j++)
{
if(allValues[ index[ i ] ] > allValues[ index[ j ] ])
{
int temp = index[ i ];
index[ i ] = index[ j ];
index[ j ] = temp;
}
}
}
System.out.println("Indexes of 2nd to 4th lowest numbers are the following: ");
for(int i = 1; i < 4; i++)
{
System.out.println(index[ i ]);
}
Mark this as the answer if it answers your question.
Hope this helps!
I can think of two ways to accomplish this: sort the array, and search it repetitively. Neither of these is likely to be the most efficient, but they should be good enough for most use cases (with the latter being slightly more efficient).
If you want to sort the array, simple use Arrays.paralellSort() and get whatever values you need from the resulting array.
If you want to search it repetitively, then simply go through the array and find the lowest value. Make note of this value in a variable, and repeat the original code -- unless the current value is the lowest. It would be best to use a HashSet to contain the list of already selected values, since a HashSet can efficiently be checked for a value and have a value added to it.

How to print an array that was inputted from Scanner? [duplicate]

This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 6 years ago.
So I have an array and trying to print what was input to the scanner. I'm trying to print the matrix that was input. Heres the code, what am I doing wrong here? I tried to print just graph, doesn't work.
/** Accept number of vertices **/
System.out.println("Enter number of vertices\n");
int V = input.nextInt();
/** get graph **/
System.out.println("\nEnter matrix\n");
int[][] graph = new int[V][V];
for (int i = 0; i < V; i++)
for (int j = 0; j < V; j++)
graph[i][j] = input.nextInt();
System.out.print(graph);
Printing arrays by simply passing it into System.out.print will print the array's hashcode. See this.
What you want to do is: System.out.println(Arrays.deepToString(graph));
Arrays.toString(...) will work for single dimensional arrays.
Arrays.deepToString(...) will work for more complex arrays.
Because when you try to print graph, you are actually printing a reference to an array object (If I am correct).
Also, for variables (like "V") you should use small caps
Instead of printing a graph, do this:
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
System.out.print(graph[i][j]);
}
System.out.println();
}
You can print the contents of an array using the Arrays.toString() method but it doesn't work for multidimensional arrays, so for a 2 dimensional array, you'll need to loop through the elements in the first dimension. Like this:
for (int[] g : graph) {
System.out.println(Arrays.toString(g));
}

Random number generator continues to include 0

I'm trying to populuate an array with random numbers to be sorted and used in a binary search. All of my code seems to work fine except the generating part. The numbers need be between 1-32767 and I continue to get 0.
for(int i = 0; i < SIZE-1; i++){
array[i] = (gen.nextInt(32767 - 1) + 1);
}
// Print out five entries
for(int i = 0; i < 5; i++){
System.out.println(array[i]);
}
// Sort array
Arrays.sort(array);
// Print out first five sorted entries
for(int i = 0; i < 5; i++){
System.out.println(array[i]);
}
After they're sorted and printed, the first entry is always 0. Perhaps this has to do with the array sorting, and I'm not realizing it. Any suggestions?
You're never setting the last element of the array -- use i < SIZE, not i < SIZE-1.

Searching specific rows in a multi-dimensional array

I'm new to java programming and I can't wrap my head around one final question in one of my assignments.
We were told to create a static method that would search a 2-D array and compare the numbers of the 2-D array to an input number...so like this:
private static int[] searchArray(int[][] num, int N){
Now, the part what we're returning is a new one-dimensional array telling the index of the first number in each row that is bigger than the parameter variable N. If no number is bigger than N, then a -1 is returned for that position of the array.
So for example a multi-dimensional array named "A":
4 5 6
8 3 1
7 8 9
2 0 4
If we used this method and did searchArray(A, 5) the answer would be "{2,0,0,-1)"
Here is a very good explanation about Java 2D arrays
int num[][] = {{4,5,6},{8,3,1},{7,8,9}};
int N = 5;
int result[] = new int[num.length];
for(int i=0; i<num.length; i++){
result[i] = -1;
for(int j=0; j<num[0].length; j++){
if( N < num[i][j] ){
result[i] = j;
break;
}
}
}
for(int i=0; i<result.length; i++){
System.out.println(result[i]);
}
The first for loop(The one with a for inside it) traverses the 2D array from top to bottom
in a left to right direction. This is, first it goes with the 4 then 5,6,8,3,1,7,8,9.
First the result array is created. The length depends of the number of rows of num.
result[i] is set to -1 in case there are no numbers bigger than N.
if a number bigger than N is found the column index is saved result[i] = j and a break is used to exit the for loop since we just want to find the index of the first number greater than N.
The last for loop just prints the result.
Generally when using multi-dimensional arrays you are going to use a nested for loop:
for(int i = 0; i < outerArray.length; i++){
//this loop searches through each row
for(int j = 0; j < innerArrays.length; j++) {
//this loop searches through each column in a given row
//do your logic code here
}
}
I won't give you more than the basic structure, as you need to understand the question; you'll be encountering such structures a lot in the future, but this should get you started.

Categories

Resources