Location of the largest and smallest number in an array - java

I can't figure out how I can get the index location of the largest and smallest numbers in an array. Someone who can help me out here?
My code:
int[] array = {4, 2, 7, 6, -3, -1, -2, 42, 0, -42, 9, -4, 5, -5, -6, -7, -8, -99, 42, 11, 20, 1, 2, 3};
int smallest = array[0];
int largest = array[0];
for (int i = 1; i < array.length; i++){
if (array[i] > largest) {
largest = array[i];
} else if (array[i] < smallest)
smallest = array[i];
}
System.out.println("Largest: " + largest);
System.out.println("Smallest: " + smallest);
I have already the largest and smallest numbers, but how can I find the index locations.

Create two more variables to store Largest index and smallest index, now whenever you assign a new value to smallest and largest in if-else statements also assign the value of i.
int smallestInd = 0;
int largestInd = 0;
for (int i = 1; i < array.length; i++){
if (array[i] > largest) {
largest = array[i];
largestInd = i;
} else if (array[i] < smallest)
smallest = array[i];
smallestInd = i;
}

This should work
int[] array = {4, 2, 7, 6, -3, -1, -2, 42, 0, -42, 9, -4, 5, -5, -6, -7, -8, -99, 42, 11, 20, 1, 2, 3};
int si, smallest = array[si = 0];
int li, largest = array[li = 0];
for (int i = 1; i < array.length; i++) {
if (array[i] > largest) {
largest = array[li = i];
} else if (array[i] < smallest) {
smallest = array[si = i];
}
}
System.out.println("Largest: " + li);
System.out.println("Smallest: " + si);
or easier readable:
int[] array = {4, 2, 7, 6, -3, -1, -2, 42, 0, -42, 9, -4, 5, -5, -6, -7, -8, -99, 42, 11, 20, 1, 2, 3};
int si = 0, smallest = array[0];
int li = 0, largest = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] > largest) {
largest = array[i];
li = i;
} else if (array[i] < smallest) {
smallest = array[i];
si = i;
}
}
System.out.println("Largest: " + li);
System.out.println("Smallest: " + si);

I was able to came up with two answers :
ary.sort();
console.log(
`This is max ${ary[0]} of the numbers and here is ${
ary[-1]
} the min of the numbers list!`
);
_________________________________________________________________
` let ary = [8, 13, 2, 5, 44, 1, 5, 55];
let max = ary[0];
let min = ary[0];
let locationMax, locationMin;
for (i = 0; i <= ary.length; i++) {
if (ary[i] > max) {
max = ary[i];
locationMax = i;
} else if (ary[i] < min) {
min = ary[i];
locationMin = i;
}
}
console.log(
`This is the location of the max ${locationMax} so The second location number ${locationMin} is for min!`
);

Related

Java: Checking for duplicate values in one array and assigning a simpler ID into another array of the same size

I have two arrays:
array 1:
{101,101,101,102,102,103,103,104,104,105}
and array 2:
{0,0,0,0,0,0,0,0,0,0};
For every duplicate element in array 1, I want an new ID in each element of array 2. This the result I am trying to achieve:
array1 = {101,101,101,102,102,103,103,104,104,105};
array2 = {1,1,1,2,2,3,3,4,4,5};
You might get a better idea of what I am trying to do when you see my code.
The code I have provided is the closest I have gotten to getting the result I want. I have tried switching up the logic in many different ways and haven't gotten a result better than what the code I have provided gives.
public class Challenge {
public static void main(String[] args) throws Exception {
int[] arr1 = {11,11,11,12,12,13,13,14,14,15};
int[] arr2 = new int[10];
System.out.println("Initial arrays");
System.out.println();
System.out.println(Arrays.toString(arr1));
System.out.println(Arrays.toString(arr2));
int id = 1;
int count = 0;
int trueCount = 0;
boolean isMatching = true;
boolean beginWrite = true;
for (int i = 0; i < arr1.length; i++) {
for (int j = i + 1; j < arr1.length; j++) {
count++;
if (arr1[i] != arr1[j]) {
isMatching = false;
trueCount = count;
count = 0;
for (int k = 0; k < arr1.length; k++) {
if (k == trueCount) {
beginWrite = false;
}
if (beginWrite == true) {
arr2[i] = id;
i++;
}
}
}
}
}
System.out.println();
System.out.println("Result");
System.out.println();
System.out.println(Arrays.toString(arr1));
System.out.println(Arrays.toString(arr2));
}
}
Output:
Initial arrays
[11, 11, 11, 12, 12, 13, 13, 14, 14, 15]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
Result
[11, 11, 11, 12, 12, 13, 13, 14, 14, 15]
[1, 1, 1, 0, 0, 0, 0, 0, 0, 0]
Expected output:
Initial arrays
[11, 11, 11, 12, 12, 13, 13, 14, 14, 15]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
Result
[11, 11, 11, 12, 12, 13, 13, 14, 14, 15]
[1, 1, 1, 2, 2, 3, 3, 4, 4, 5]
I think I understand your question and one thing that could make your life a lot easier is a data structure called a HashMap.
If you're unfamiliar it is basically a set of (key, value) pairs where each key is unique making it so we could put your unaltered ids as keys and new ids as values. Then as we're iterating, we can check to see if we've created an id for that unaltered id yet and if we have use that id.
The code with this added to it would look something like this:
public class Challenge {
public static void main(String[] args) throws Exception {
int[] arr1 = {11,11,11,12,12,13,13,14,14,15};
int[] arr2 = new int[10];
HashMap<Integer, Integer> ids = new HashMap<Integer, Integer>();
System.out.println("Initial arrays");
System.out.println();
System.out.println(Arrays.toString(arr1));
System.out.println(Arrays.toString(arr2));
int id = 1;
int count = 0;
int trueCount = 0;
boolean isMatching = true;
boolean beginWrite = true;
for (int i = 0; i < arr1.length; i++) {
if (ids.containsKey(arr1[i])) {
arr2[i] = ids.get(arr1[i]);
} else {
ids.put(arr1[i], id);
arr2[i] = id;
id++;
}
}
System.out.println();
System.out.println("Result");
System.out.println();
System.out.println(Arrays.toString(arr1));
System.out.println(Arrays.toString(arr2));
}
}
The old fashion way with a single for loop:
int[] array1 = {104,105,101,103,102,103,102,101,104,101};
int[] array2 = new int[array1.length];
System.out.println("Original Array: " + Arrays.toString(array1).replaceAll("[\\[\\]]", ""));
Arrays.sort(array1); // Make sure the Array is sorted (in the case it isn't).
System.out.println("Array: Sorted: " + Arrays.toString(array1).replaceAll("[\\[\\]]", ""));
int prevValue = array1[0];
array2[0] = 1;
int counter = 1;
for (int i = 1; i < array1.length; i++) {
if (array1[i] == prevValue) {
array2[i] = counter;
prevValue = array1[i];
}
else {
counter++;
array2[i] = counter;
prevValue = array1[i];
}
}
System.out.println("The Result: " + Arrays.toString(array2).replaceAll("[\\[\\]]", ""));
Initialize the first value of arr2 to the id = 1
If the next value of arr1 is the same as the previous, keep setting same id
If the next value of arr1 is not the same as the previous, increment id by 1
int[] arr1 = {11,11,11,12,12,13,14,14,14,15};
int[] arr2 = new int[10];
...
int id = 1;
for (int i = 0; i < arr1.length; i++) {
if (i == 0) {
arr2[i] = id;
} else {
if ((arr1[i])==(arr1[i-1])) {
arr2[i] = id;
} else {
id++;
arr2[i] = id;
}
}
}
Initial arrays
[11, 11, 11, 12, 12, 13, 14, 14, 14, 15]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
Result
[11, 11, 11, 12, 12, 13, 14, 14, 14, 15]
[1, 1, 1, 2, 2, 3, 4, 4, 4, 5]
Try this.
int[] arr1 = {11,11,11,12,12,13,13,14,14,15};
int[] arr2 = new int[arr1.length];
System.out.println("Initial arrays");
System.out.println();
System.out.println(Arrays.toString(arr1));
System.out.println(Arrays.toString(arr2));
int[] id = {1};
Map<Integer, Integer> ids = new HashMap<>();
for (int i = 0; i < arr1.length; i++)
arr2[i] = ids.compute(arr1[i], (k, v) -> v == null ? id[0]++ : v);
System.out.println();
System.out.println("Result");
System.out.println();
System.out.println(Arrays.toString(arr1));
System.out.println(Arrays.toString(arr2));

finding min & max in an array with 3 increments

I need to find the max and min for every 3 elements of a data using java array.
For double data[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14} , what is the max and min in every 3 elements? In other words, what is the max and min for {1,2,3}, {4, 5, 6}, {7, 8, 9}, etc.
I have the following method, but it is not getting the right results.
for (int i = 0; i < data.length; i+=3) {
for (int r = i; r < i + 3 && r < data.length; r++) {
if (data[r] < lowest) { lowest = data[r]; }
if (data[r] > highest) { highest = data[r]; }
}
lowest = highest;
highest = 0;
How about this?
int[] data = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14};
int processed = 0;
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
for (int i = 0; i < data.length; i++) {
if (data[i] < min) {
min = data[i];
}
if (data[i] > max) {
max = data[i];
}
processed++;
if (processed == 3) {
System.out.println("Min is: " + min);
System.out.println("Max is: " + max);
System.out.println("--------");
processed = 0;
min = Integer.MAX_VALUE;
max = Integer.MIN_VALUE;
}
}
Output:
Min is: 1
Max is: 3
--------
Min is: 4
Max is: 6
--------
Min is: 7
Max is: 9
--------
Min is: 10
Max is: 12
--------
It's unclear what to do with the numbers 13 and 14, as they don't form a block of 3, but I guess you get the idea of the algorithm.

I'm trying to sort an array at least at greatest. Now I've got something just like this:

//Creating the array
int[] n = {2, 9, 56, 73, 32, 8, 23, 21, 12, 53, 9, 0, 1};
//Creating the sorting algoritm
for(int i = 1; i <= n.length; i++) {
for(int j = 1; j <= n.length; j++) {
if(n[j]<n[i]) {
int c = n[j];
n[j] = n[i];
n[i] = c;
}
}
}
//Printing the values of the array
for(int i = 0; i < n.length; i ++)
System.out.println(n[i]);
}
If you're doing this just to sort it, perhaps try just using Arrays.sort(n).
Documentation for Arrays class
If you're doing it just because you wan't to write your own sort function then there's a lot more that you need to do. Will the Arrays.sort(n) work for your purposes?
The following array shall be sorted.
int[] n = {2, 9, 56, 73, 32, 8, 23, 21, 12, 53, 9, 0, 1};
public int [] sort(int[] array) {
for (int i = 0; i < array.length; i++) {
for (int j = i+1; j < array.length; j++) {
if ( (array[i] > array[j]) && (i != j) ) {
int temp = array[j];
array[j] = array[i];
array[i] = temp;
}
}
}
return array;
}
The array can be sorted by calling sort method with array as parameter e.g.
int[] array = {2, 9, 56, 73, 32, 8, 23, 21, 12, 53, 9, 0, 1};
int[] sortedArray = sort(array);

Roulette wheel selection in GA: ArrayIndexOutOfBoundsException error

Based on this answer I've tried to do my roulette wheel selection in genetic algorithm.
private static final int NUMBER_OF_TOURISTS = 20;
private static int[] roulette(int population[]) {
int sumProb = 0;
for (int i = 0; i < population.length; i++) {
sumProb += population[i];
}
int[] rouletteIndex = new int[NUMBER_OF_TOURISTS];
Random r = new Random();
for (int i = 0; i < NUMBER_OF_TOURISTS; i++) {
int numberRand = r.nextInt(sumProb);
//-------------------------------------------------------
int j = 0;
while (numberRand > 0) {
numberRand = numberRand - population[j];
j++;
}
rouletteIndex[i] = j-1;
//-------------------------------------------------------
}
return rouletteIndex;
}
after this I get:
[6, 2, -1, 19, 13, 2, 14, 2, 6, 19, 7, 14, 18, 0, 1, 9, 13, 10, 7, 2]
"-1"? But how, when j should be always greater than 0.
Is this happen when numberRand = 0 and than while loop doesn't start even once? But how to fix this?
Random.nextInt(int bound) returns 0 (inclusive) to specified bound (exclusive).
So your loop:
while (numberRand > 0) {
numberRand = numberRand - population[j];
j++;
}
Will not run if nextInt(int bound) returns 0, resulting in j being 0 at: rouletteIndex[i] = j-1;

how to add up element in multidimensional array?

I feel like the answer so simple but I just can't figure out what it is. I have an multidimensional array such as this:
int [][] number =
{{ 10, 15, 11, 13, 72, 87, 266},
{ 50, 65, 80, 94, 12, 134, 248},
{ 1, 2, 1, 9, 1, 39, 26},
{ 13, 20, 76, 4, 8, 72, 28},
{ 2, 1, 29, 2, 12, 907, 92},
{ 16, 4, 308, 7, 127, 1, 52}
};
I'm trying to add up all the integers in the each array index and display it at the end so what I thought up of is this
int total=0;
for (int k=0;k<6;k++){
for (int i=0;i<7;i++){
total=number[k][i]+total;}}
System.out.println(total);
What I noticed is that it will add up all the numbers in the entire array. But how do I stop it at the end of each index?
Your question is not clear . But from what I understood you must do
for (int k=0;k<6;k++){
int total=0;
for (int i=0;i<7;i++){
total=number[k][i]+total;}
System.out.println(total);}
It will print sum of all rows
Couldn't the loop be like this:
for (int k = 0; k < 6; k++) {
int total = 0;
for (int i = 0; i < 7; i++) {
total += number[k][i];
}
System.out.println(total);
}
Assuming I get what you mean by stop it at the end of each index.
And better should it be if you parametrize your loops to fit in each dimension length:
for (int k = 0; k < number.length; k++) {
int total = 0;
for (int i = 0; i < number[k].length; i++) {
total += number[k][i];
}
System.out.println(total);
}

Categories

Resources