How to get Maximum value in multiple array? - java

I want to take the maximum value obtained from result.length, but I have trouble in the way to call it, can you help me?
double[][] result = matrixMultiplexing(neighboursAdjSquare(matrixEgoNetwork), matrixDecrement(ones, matrixEgoNetwork));
double max = result[0][0];
ArrayList<Double> val= new ArrayList<>();
for (int i = 0; i < result.length; i++) {
for (int j = i+1; j < result.length; j++) {
Arrays.sort(result);
if(result[i][j]== "I wanna called here" ){
val.add(result[i][j]);
}
}
}
The error is cannot applied 'double',double[]'
can you help me fix that?

public class FindMaxOf2dArray {
public static void main(String[] argv) {
double[][] arr2d = new double[][]{
{1.0, 2.0, 3.0, 4.0},
{5.0, 6.0, 7.0, 8.0},
{99.0, 0.0, 0.0, -1.0}
};
double maxOfarr2d = findMaxOf2dArray(arr2d);
System.out.println("The maximum value contained in arr2d is " + maxOfarr2d);
}
static double findMaxOf2dArray(double[][] arr2d){
double maxValue = Double.MIN_VALUE;
for(int i = 0; i < arr2d.length; i++){ //iterate through the number of arrays
for(int j = 0; j < arr2d[i].length; j++){//iterate through each value in the given array
if(arr2d[i][j] > maxValue){
maxValue = arr2d[i][j];
}
}
}
return maxValue;
}
}
This would be the most straight-forward way to find the maximum value within a 2d-array. Not necessarily the best way, but it should be easy to follow the logic. In the method findMaxOf2dArray(double[][]) we set the maximum value to the smallest possible value that can be stored in a double. Then we enter a for-loop that loops through each array that contains doubles. For every iteration of this loop we enter a second for-loop that iterates through each value stored in the current array. Each value is then compared against the value stored in maxValue. If the value stored in the array is greater than the value stored in maxValue, then we change the value of maxValue to the value stored in the array. Finally after checking each value in each array of the 2d-array, we return the value stored in maxValue.
I believe the problem with your code is that you never iterate through the values stored in each array. You only iterate through the arrays themselves–twice. Each value stored in result[i] is itself an array which holds the double values that you want to compare. Additionally by starting j at i + 1 you skip i + 1 values to be iterated through. Lastly, a double cannot be compared to a String.

Related

Java returning numbers below the avg

ne of my projects assigned was to create an array for 10 variables which the user inputs and to have the program output the average of the input number as well as listing the numbers below the average. I am able to obtain the average without an issue but my code to return the numbers below the average seems to not be doing the job. For example if I input into the array the values [1,2,3,4,5,6,7,8,9,10] the average outputs as 5.5 (which is good) but the output I want from BelowAverage is 1,2,3,4,5 can anyone help me?
public static double BelowAverage(ArrayList<Double> Averages) {
int i, aveless = 0; double avg = 0;
for(i = 0; i < Averages.size(); i++)
avg = Averages.get(i);
avg /= Averages.size();
for(i = 0; i < Averages.size(); i++)
if(Averages.size() < avg)
aveless++;
return aveless;
}
No need to use wrappers, you could use double instead of Double.
Your variable naming is weird, why do you have an ArrayList of averages instead of numbers?
Follow Java naming conventions:
firstWordLowerCaseVariable
firstWordLowerCaseMethod()
FirstWordUpperCaseClass
ALL_WORDS_UPPER_CASE_CONSTANT
and use them consistently
You already have a method that calculates the average, why not use it?
So, for example, your code might look like this (with slight modifications):
public static int belowAverage(List<Double> numbers) {
double avg = calculateAverages(numbers); //Go, get the average using the method you already have
int aveless = 0;
for (int i = 0; i < numbers.size(); i++) {
if (numbers.get(i) < avg) { //Instead of comparing the numbers array size, compare the number against the average.
aveless++;
}
}
return aveless;
}
I added opening and closing curly braces for the for loop as I think it's easier to read that way.
I also changed the return type to int instead of double on this method as you only want to count, so, decimal point is not needed and moved the System.out.println() call inside the calculateAverage() method to the main method.
I also changed the parameter type to the interface one (from ArrayList to List)
Your problem seems to bee on this line:
if(Averages.size() < avg) aveless++;
You should be checking Averages.get(i) < avg instead, otherwise what is the point of looping?
If I understand correctly, and you want a list with all the numbers below the average, you should change the return value and the code, like this:
public static ArrayList<Double> BelowAverage(ArrayList<Double> Averages) {
// You already have a method for calculating the average, so use it
double avg = CalculateAverages(Averages);
ArrayList<Double> aveless = new ArrayList<Double>();
int i;
for(i = 0; i < Averages.size(); i++){
double number = Averages.get(i);
if(number < avg){
aveless.add(number);
}
}
return aveless;
}
There are several problems with your code. Let's go through them one at a time.
First problem:
for(i = 0; i < Averages.size(); i++)
avg = Averages.get(i); //this line
avg /= Averages.size();
You are simply reassigning the value of avg in the loop. What you want to do is to keep adding values to it. Replace = with += to get avg += Averages.get(i);.
Second problem:
for(i = 0; i < Averages.size(); i++)
if(Averages.size() < avg)
aveless++;
Here you are checking whether avg is larger than the size of the list which is not what you want to be doing. What you wonder is whether avg is larger than the values in the list. You need to replace Averages.size() with Averages.get(i). This is a relatively easy mistake to spot because the loop is not really achieving anything right now, so look out for things like this.
Edit: There are a few other problems as well. avg should be a double and not an int, because ints cannot store decimal places and there is no guarantee that your average is a whole number, so you will get a rounding error. Furthermore, your method should return an int instead of a double because "the number of values below average" is always an integer.
To count the number of 'numbers' which have less value than the average, you should compare each element inside that array with the average, not with the size of the array. Try it as follows:
public static double BelowAverage(ArrayList<Double> Averages) {
int i, aveless = 0; double avg = 0;
for(i = 0; i < Averages.size(); i++)
avg = Averages.get(i);
avg /= Averages.size();
for(Double a : Averages)
if(a < avg) aveless++;
return aveless;
}

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 make the max/min element of an array to 0? or remove them from the array

Say I enter values 1-10 in the array and when I try to run the code and print the values of my array, the max value of the element is still 10.0, how can I make that value to 0.0 or completely remove it from my array?
btw, I'm new to java and programming.
import java.util.Scanner;
public class Exer20 {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
double[] judges = new double[10];
for(int a=0; a < judges.length; a++){
judges[a] = input.nextDouble();
}
double max = judges[0];
double maxIndex = 0;
double min = judges[0];
for(int x = 0; x < judges.length; x++){
if(judges[x] > max)
max = judges[x];
maxIndex = x;
}
maxIndex = 0.0;
max = 0.0;
for(double b:judges)
System.out.println(b);
}
}
change this line:
max = 0.0;
to
judges[maxIndex] = 0.0
when you set primitive types they are copied by value. So when you change max it doesn't affect the judges array. You have to manipulate the array directly.
As your question already states that you are entering the values in your array of type double from 1-10 in sorted order,hence the minimum value in the array will be at 0th location and maximum value in array will be at last location, hence to make them 0 use the following code snippet:
judges[0]=0.0; //setting minimum to 0
judges[judges.length-1]=0.0; //setting maximum to 0
In case your array is not sorted,then make them in sorted order using any of sorting logic and apply the above given code snippet,as sorting of array will help to easily locate minimum and maximum value in array.

calculate the average value across indicies of a hash map

I tried writing this code to test out my idea on how to calculate the average value across like indices of a hash map.
i.e. for each array contained within the hashmap if the first value for the first array was 2, and the first value for the second array was 4 , and the first value for the third array was 3, I want to assign the value of (4+3+2/3)= 3 to the final double[] array for the first index, and so on for all the indices 2 through n.
int Size = 3;
double[] AVERAGED_WEIGHTS = new double[Size];
//store weights to be averaged.
Map<Integer,double[]> cached_weights = new HashMap<Integer,double[]>();
double[] weights = new double[Size];
int iteration = 0;
do
{
weights[iteration] = Math.floor(Math.random() * 10000) / 10000;
iteration++;
//store weights for averaging
cached_weights.put( iteration , weights );
}
while (iteration < Size);
//calc averages
for (Entry<Integer, double[]> entry : cached_weights.entrySet())
{
int key = entry.getKey();
double[] value = entry.getValue();
AVERAGED_WEIGHTS[ key - 1 ] += value[ key - 1 ];
if (key == iteration)
{
AVERAGED_WEIGHTS[ key - 1 ] /= key;
}
}
for(int i = 0; i < weights.length; i++)
{
weights[i] = AVERAGED_WEIGHTS[i];
}
This mimics the structure of the original program wherein the weights are populated through a do while loop. This code is broken though and does not sucessfully perform the operation described above. I've been searching online and trying different ways to fix it but I've not been able to solve it. Perhaps someone can spot my faulty logic.
Maybe I misunderstood you, but you are not computing the average because for each array in your map, you are not taking into account all its positions. You are using the key and that makes absolutely no sense. Anyways, your code is very confusing. What you need to do is simply one loop inside the other. One going through the arrays and another going through the elements of each array. A way to compute the average is the following (in a didactic way):
//compute averages
double[] sums = new double[size];
double[] averages = new double[size];
for (Entry<Integer, double[]> entry : cachedWeights.entrySet()) {
double[] value = entry.getValue();
for(int pos=0; pos < Math.min(size, value.length); pos++){
sums[pos] += value[pos];
}
}
for(int pos=0; pos < size; pos++){
averages[pos] = sums[pos] / cachedWeights.size();
}

How to show index not the element

Hi im trying to show the index of the array not the element this is part of my code so far:
int randomInt2 = randomGenerator.nextInt(15)+1;
double [] distances = new double [randomInt2];
Arrays.sort(distances);// sorts array from highest to lowest
for (double val : distances) {
System.out.println("["+val+"],");
}
System.out.println("The Nearest to point 1 is point: ");
Each index holds an value between 1-1000 but i do not want to show the value i want to show the index so that I can show what indexes are closest to point 1 (which is 0)
Sorry if im not being clear and if you need me to explain more then I am happy to
Thanks to dasblinkenlight's comment I finally understood what you need.
The easiest way to do what you need to do would be to create an object like
class Value implements Comparable<Value> {
int index;
dobule value;
public int compareTo(Value val) {
return Double.compare(this.value, val.value);
}
}
And use it to store the values. Note the Comparable implementation - allows you to use Collections.sort() and Arrays.sort().
You could also not use sorting. Sorting an array is a much more complex operation than finding the minimum value. Just iterate over the array once and find the smallest value and return its index.
double minVal = Double.MAX_VALUE;
int minIndex = -1;
for (int i=0, max=distances.length; i<max;i++) {
if (values[i] < minVal) {
minVal = values[i];
minIndex = i;
}
}
System.out.println("The Nearest to point 1 is point: "+minIndex+" with value "+minVal);
As for indexes: you can't use standard foreach loop if you want to access the index of a given element. One of the reasons is that some collections you may iterate over do not support element ordering (like a Set).
You have to use standard for loop or track the index yourself.
for (int i=0, max=distances.length; i<max;i++) {
System.out.println("["+i+"] "+distances[i]);
}
or
int i = 0;
for (double val : distances) {
System.out.println("["+i+"] "+val);
i++;
}
try like this
for (int i=0;i< distances.length;i++) {
System.out.println("distances["+i+"]");
}
I assume you want to find out the index of the item with lowest distance in the original array. When you sort the array, this information is lost, as it will simply indexed from 0..length-1. Therefore, your answer will always be 0.
You can do 2 things:
1) Find the minimum value:
double[] distances = new double [randomInt2];
// Need copy to for sorting
double[] c = Arrays.copyOf(distances, distances.length);
// Find minimum value
Arrays.sort(c);
double min = c[0];
// Search that value in the original array:
for (int i = 0; i < distances.length; ++i) {
if (distances[i] == min) {
System.out.println("Minimum distance at: " + i);
break;
}
}
2) Store the index information with the distance information:
For this you need to:
write your own class, like public class Distance, with a distance and index member.
Implement a Comperator<Distance>, so that instances are compared by distance
Make a function like Distance[] convertToDistance(double[] array) that creates a Distance array from your pure double values (if needed)
Sort the array using Arrays.sort(T[], Comparator<? extends T>) method
Get the result from sortedDistances[0].index
You can just used an old fashioned for loop instead of an enhanced for loop:
Arrays.sort(distances);// sorts array from highest to lowest
for (int i = 0; i < distances.lengh; ++i) {
System.out.println("index: " + i + ":[" + val + "],");
}
you might every distance let be an object of
class Distance {
public Distance(double dist) {
this.dist = dist;
this.id = idcount++;
}
static int idcount = 0;
public int id;
public double dist;
}
and than call the id in every

Categories

Resources