Can't understand why loop is not updating variable value - java

When I create this method to find the index of the smallest number in an array starting from a specific index, it keeps returning 0 no matter which numbers are in the array. It seems that index = i in the for loop is not updating the value of the index variable, even if the array contains other numbers lower than the 0 spot. Why?
public static int indexOfSmallestFrom(int[] array, int startIndex) {
int smallest = array[startIndex];
int index = 0;
for (int i = startIndex; i < array.length; i++) {
int each = array[i];
if (each < smallest) {
smallest = each;
index = i;
}
}
return index;
}
edit: Here's the main method:
public static void main(String[] args) {
// write your test code here
int[] array = {99, 3, 1, 7, 4, 5, 2, 4};
System.out.println("Smallest: " + indexOfSmallestFrom(array, 1));
}
It works correctly every time EXCEPT when the startIndex variable passed to the method call is 2! When a 1 is passed as above, it correctly returns 2, when 3 is passed, it correctly returns 6, etc. ???

Because when you pass startIndex = 2 into the function, we have smallest = array[startIndex] = 1 in this case, and your code initializes int index = 0;. However, in your for loop, you have:
for (int i = startIndex; i < array.length; i++) {
int each = array[i];
if (each < smallest) {
smallest = each;
index = i;
}
}
Since your smallest was initialized to the number at position startIndex but not your index, and the fact that startIndex happened to be the index of the smallest number, your if (each < smallest) will never be entered, meaning that index will stay at 0.
To fix this, either change int index = 0; to int index = startIndex; OR you can change the condition in the if statement to if (each <= smallest) and your code should work fine (note that if you do this, it will return the last index if multiple minimums are present in the array).

Your code works for me, may be the smallest value is in 0 place in your case. But you should change index = startingIndex. Because that is where you are comparing items from.
public static int indexOfSmallestFrom(int[] array, int startIndex) {
int smallest = array[startIndex];
int index = startIndex;
for (int i = startIndex; i < array.length; i++) {
int each = array[i];
if (each < smallest) {
smallest = each;
index = i;
}
}
return index;
}
Or change < to <=
public static int indexOfSmallestFrom(int[] array, int startIndex) {
int smallest = array[startIndex];
int index = 0;
for (int i = startIndex; i < array.length; i++) {
int each = array[i];
if (each <= smallest) {
smallest = each;
index = i;
}
}
return index;
}

Because the value in position 2 is the SMALLEST value (it's 1), hence the if condition is never entered :).

Related

What is the issue with my maximum product algorithm

Here is the code:
public static int MaxProduct(int... a){ // the max possible product from an array
int i = 0;
int j = 0;
int m = 0;
int n = a.length;
while (i<n){
j++;
while(j<n ){
if (a[i]*a[j] > m){
m = a[i]*a[j];
j++;
}
}
i++;
}
return m;
}
System.out.println(MaxProduct(1,2,3,4,5));
The algorithm seems to work as expected (after check and making a table of the debugger). For the first index of an array it checks all possible products and edits m accordingly from 1 through to 5. And then once j is equal to 5 a[j]understandably is out of bounds since there are only 5 elements in the array
I then see the arrayoutofbounds error in the debugger beside (again which is what id expect) but instead of i increasing, and the second while loop starting the cycle again, a[i] stays as 1, the algorithm concludes, and i get the output 5
How do i get this to output 20 (4x5)
You need to make two changes. Check below 2 TODOs.
public static int MaxProduct(int... a) { // the max possible product from an array
int i = 0;
int j = 0;
int m = 0;
int n = a.length;
while (i < n) {
j = i + 1; // TODO: 1
while (j < n) {
if (a[i] * a[j] > m) {
m = a[i] * a[j];
}
j++; // TODO:2
}
i++;
}
return m;
}

How to select the largest index of the smallest element in a single array Java

Basically, I need to find the largest index of the smallest element in an array. The first input is the number of elements. However, if the same number is repeated later in the array, it needs to return that index.
Right now my code finds the smallest number and returns the index of that number. How do I update the index?
import java.util.Scanner;
public class smallestelement {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int length = input.nextInt();
int [] a = new int[length];
for (int i = 0; i < length; i++){
a[i] = input.nextInt();
}
// minimum
int min = a[0];
// counter
int index = 0;
// loop continues as long as i is less than the length of the array
for (int i = 0; i < a.length; i++){
min = a[i];
index = i;
}
System.out.println(index);
}
}
You need to use an if statement to check if you are really looking at a smaller element. Use <= to do the comparison, so that when you see an equally-smallest value, the later index is used.
for (int i = 1; i < a.length; i++) {
if (a[i] <= min) {
min = a[i];
index = i;
}
}
By the way, it's fine for the loop to start at 1 instead of 0, since you initialise min and index before the loop using the value at index 0.

Finding all Indices of a number from an Array (Java)

Say I have an array of:
int [] I = { 1, 3, 6, 3, 7,3, 9, 3};
int value = 3;
I have a for loop that tracks the amount of occurences of the value:
int counter = 0;
for(int x = 0; x < I.length; x++)
{
if(I[x] == value)
{
counter++;
}
}
I make a new array with length equal to the number of occurrences, that can store all the indices of the occurences from the original array:
int [] index = new int [counter];
for(int x = 0; x < index.length; x++)
{
for(int i = 0; i<I.length; i++)
{
if(I[i] == value){
index[x] = i;
}
}
}
However, when I print my array of indices, i just get the last index printed the amount of times counter is equal to, when I want all the indices.
for(int i = 0; i<index.length; i++)
{
System.out.println(index[i]);
}
It just prints "7" (the last index) 3 times. How do I go about fixing this so I have an array of all indices?
Thank you.
Your second for loop should not be nested; you should only increment x when you find a match. Something like,
for (int i = 0, x = 0; i < I.length; i++) {
if (I[i] == value) {
index[x] = i;
x++;
}
}
Assuming you're using Java 8+, you could have written a filter() on the range of indices in the array. Like,
int[] index = IntStream.range(0, I.length).filter(i -> I[i] == value).toArray();
System.out.println(Arrays.toString(index));
Just remove the outer for loop and store into the index array as you iterate through the original array I. The problem with your code is that, since you repeat the iterations once for each index in the index array, you end up with the last found index (7 in your case).
for(int i = 0, x = 0; i < I.length; i++) {
if(I[i] == value) {
index[x++] = i;
}
}

Find smallest integer value in array list in Java without Arrays.sort

How can I find the smallest value in a int array without changing the array order?
code snippet:
int[] tenIntArray = new int [10];
int i, userIn;
Scanner KyBdIn = new Scanner(System.in);
System.out.println("Please enter 10 integer numbers ");
for(i = 0; i < tenIntArray.length; i++){
System.out.println("Please enter integer " + i);
userIn = KyBdIn.nextInt();
tenIntArray[i] = userIn;
}
I am not sure how I can find the smallest array value in the tenIntArray and display the position
For example the array holds - [50, 8, 2, 3, 1, 9, 8, 7 ,54, 10]
The output should say "The smallest value is 1 at position 5 in array"
This figure should be helpful :
Then to answer your question, what would you do on paper ?
Create and initialize the min value at tenIntArray[0]
Create a variable to hold the index of the min value in the array and initialize it to 0 (because we said in 1. to initialize the min at tenIntArray[0])
Loop through the elements of your array
If you find an element inferior than the current min, update the minimum value with this element and update the index with the corresponding index of this element
You're done
Writing the algorithm should be straightforward now.
Try this:
//Let arr be your array of integers
if (arr.length == 0)
return;
int small = arr[0];
int index = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] < small) {
small = arr[i];
index = i;
}
}
Using Java 8 Streams you can create a Binary operator which compares two integers and returns smallest among them.
Let arr is your array
int[] arr = new int[]{54,234,1,45,14,54};
int small = Arrays.stream(arr).reduce((x, y) -> x < y ? x : y).getAsInt();
The method I am proposing will find both min and max.
public static void main(String[] args) {
findMinMax(new int[] {10,40,50,20,69,37});
}
public static void findMinMax(int[] array) {
if (array == null || array.length < 1)
return;
int min = array[0];
int max = array[0];
for (int i = 1; i <= array.length - 1; i++) {
if (max < array[i]) {
max = array[i];
}
if (min > array[i]) {
min = array[i];
}
}
System.out.println("min: " + min + "\nmax: " + max);
}
Obviously this is not going to one of the most optimized solution but it will work for you. It uses simple comparison to track min and max values. Output is:
min: 10
max: 69
int[] input = {12,9,33,14,5,4};
int max = 0;
int index = 0;
int indexOne = 0;
int min = input[0];
for(int i = 0;i<input.length;i++)
{
if(max<input[i])
{
max = input[i];
indexOne = i;
}
if(min>input[i])
{
min = input[i];
index = i;
}
}
System.out.println(max);
System.out.println(indexOne);
System.out.println(min);
System.out.println(index);
Here is the function
public int getIndexOfMin(ArrayList<Integer> arr){
int minVal = arr.get(0); // take first as minVal
int indexOfMin = -1; //returns -1 if all elements are equal
for (int i = 0; i < arr.size(); i++) {
//if current is less then minVal
if(arr.get(i) < minVal ){
minVal = arr.get(i); // put it in minVal
indexOfMin = i; // put index of current min
}
}
return indexOfMin;
}
the first index of a array is zero. not one.
for(i = 0; i < tenIntArray.length; i++)
so correct this.
the code that you asked is :
int small = Integer.MAX_VALUE;
int i = 0;
int index = 0;
for(int j : tenIntArray){
if(j < small){
small = j;
i++;
index = i;
}
}
System.out.print("The smallest value is"+small+"at position"+ index +"in array");

find second and third maximum element array java

I have to find 1st, 2nd, and 3rd largest array. I know I could simply sort it and return array[0], array[1], array[3]. But the problem is, i need the index, not the value.
For example if i have float[] listx={8.0, 3.0, 4.0, 5.0, 9.0} it should return 4, 0, and 3.
Here's the code I have but it doesn't work:
//declaration max1-3
public void maxar (float[] listx){
float maxel1=0;
float maxel2=0;
float maxel3=0;
for (int i=0; i<listx.length; i++){
if(maxel1<listx[i])
{maxel1=listx[i];
max1=i;
}
}
listx[max1]=0; //to exclude this one in nextsearch
for (int j=0; j<listx.length; j++){
if(listx[j]>maxel2)
{maxel2=listx[j];
max2=j;
}
}
listx[max2]=0;
for (int k=0; k<listx.length; k++){
if(listx[k]>maxel3)
{maxel3=listx[k];
max3=k;
}
}
}
I get max1 right but after that all the elements turns to 0. hence max2 and max3 become 0. Please suggest me what is wrong with this solution. Thank you.
You can find the three elements using a single loop, and you don't need to modify the array.
When you come across a new largest element, you need to shift the previous largest and the previous second-largest down by one position.
Similarly, when you find a new second-largest element, you need to shift maxel2 into maxel3.
Instead of using the three variables, you might want to employ an array. This will enable you to streamline the logic, and make it easy to generalize to k largest elements.
Make 3 passes over array: on first pass find value and 1st index of maximum element M1, on second pass find value and 1st index of maximum element M2 which is lesser than M1 and on third pass find value/1st index M3 < M2.
Try this code it will work :)
public class Array
{
public void getMax( double ar[] )
{
double max1 = ar[0]; // Assume the first
double max2 = ar[0]; // element in the array
double max3 = ar[0]; // is the maximum element.
int ZERO = 0;
// Variable to store inside it the index of the max value to set it to zero.
for( int i = 0; i < ar.length; i++ )
{
if( ar[i] >= max1)
{
max1 = ar[i];
ZERO = i;
}
}
ar[ZERO] = 0; // Set the index contains the 1st max to ZERO.
for( int j = 0; j < ar.length; j++ )
{
if( ar[j] >= max2 )
{
max2 = ar[j];
ZERO = j;
}
}
ar[ZERO] = 0; // Set the index contains the 2st max to ZERO.
for( int k = 0; k < ar.length; k++ )
{
if( ar[k] >= max3 )
{
max3 = ar[k];
ZERO = k;
}
}
System.out.println("1st max:" + max1 + ", 2nd: " +max2 + ",3rd: "+ max3);
}
public static void main(String[] args)
{
// Creating an object from the class Array to be able to use its methods.
Array array = new Array();
// Creating an array of type double.
double a[] = {2.2, 3.4, 5.5, 5.5, 6.6, 5.6};
array.getMax( a ); // Calling the method that'll find the 1st max, 2nd max, and and 3rd max.
}
}
I suggest making a single pass instead of three for optimization. The code below works for me. Note that the code does not assert that listx has at least 3 elements. It is up to you to decide what should happen in case it contains only 2 elements or less.
What I like about this code is that it only does one pass over the array, which in its best case would have faster running time compared to doing three passes, with a factor proportionate to the number of elements in listx.
Assume i1, i2 and i3 store the indices of the three greatest elements in listx, and i0 is one of i1, i2 and i3 that points to the smallest element. In the beginning, i1 = i2 = i3 because we haven't found the largest elements yet. So let i0 = i1. If we find a new index j such that that listx[j] > listx[i0], we set i0 = j, replacing that old index with an index that leads to a greater element. Then we find the index among i1, i2 and i3 that now leads to the smallest element of out the three, so that we can safely discard that one in case a new large element comes along.
Note: This code is in C, so translate it to Java if you want to use it. I made sure to use similar syntax to make that easier. (I wrote it in C because I lacked a Java testing environment.)
void maxar(float listx[], int count) {
int maxidx[3] = {0};
/* The index of the 3rd greatest element
* in listx.
*/
int max_3rd = 0;
for (int i = 0; i < count; i++) {
if (listx[maxidx[max_3rd]] < listx[i]) {
/* Exchange 3rd greatest element
* with new greater element.
*/
maxidx[max_3rd] = i;
/* Find index of smallest maximum. */
for (int j = (max_3rd + 1) % 3; j != max_3rd; j = (j + 1) % 3) {
if (listx[maxidx[j]] < listx[maxidx[max_3rd]]) {
max_3rd = j;
}
}
}
}
/* `maxidx' now contains the indices of
* the 3 greatest values in `listx'.
*/
printf("3 maximum elements (unordered):\n");
for (int i = 0; i < 3; i++) {
printf("index: %2d, element: %f\n", maxidx[i], listx[maxidx[i]]);
}
}
public class ArrayExample {
public static void main(String[] args) {
int secondlargest = 0;
int thirdLargest=0;
int largest = 0;
int arr[] = {5,4,3,8,12,95,14,376,37,2,73};
for (int i = 0; i < arr.length; i++) {
if (largest < arr[i]) {
secondlargest = largest;
largest = arr[i];
}
if (secondlargest < arr[i] && largest != arr[i])
secondlargest = arr[i];
if(thirdLargest<arr[i] && secondlargest!=arr[i] && largest!=arr[i] && thirdLargest<largest && thirdLargest<secondlargest)
thirdLargest =arr[i];
}
System.out.println("Largest number is: " + largest);
System.out.println("Second Largest number is: " + secondlargest);
System.out.println("third Largest number is: " + thirdLargest);
}
}
def third_mar_array(arr):
max1=0
max2=0
max3=0
for i in range(0,len(arr)-1):
if max1<arr[i]:
max1=arr[i]
max_in1=i
arr[max_in1]=0
for j in range(0,len(arr)-1):
if max2<arr[j]:
max2=arr[j]
max_in2=j
arr[max_in2]=0
for k in range(0,len(arr)-1):
if max3<arr[k]:
max3=arr[k]
max_in3=k
#arr[max_in3]=0
return max3
n=[5,6,7,3,2,1]
f=first_array(n)
print f
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int testcase = sc.nextInt();
while (testcase-- > 0) {
int sizeOfArray = sc.nextInt();
int[] arr = new int[sizeOfArray];
for (int i = 0; i < sizeOfArray; i++) {
arr[i] = sc.nextInt();
}
int max1, max2, max3;
max1 = 0;
max2 = 0;
max3 = 0;
for (int i = 0; i < sizeOfArray; i++) {
if (arr[i] > max1) {
max3 = max2;
max2 = max1;
max1 = arr[i];
}
else if (arr[i] > max2) {
max3 = max2;
max2 = arr[i];
}
else if (arr[i] > max3) {
max3 = arr[i];
}
}
System.out.println(max1 + " " + max2 + " " + max3);
}
}
}

Categories