I am trying to write up a block of code that takes an array of integers as an argument and returns the index of the smallest element in the array. Also, the function should return -1 if the list is an empty list.
So far I have got,
public static int indexOfSmallest(int[] array){
int index = 0;
int min = array[index];
for (int i = 1; i < array.length; i++){
if (array[i] <= min){
min = array[i];
index = i;
}
}
return index;
}
But, I'm getting this error and unsure what I need to fix.
Any help would be much appreciated. Thank you.
The error is self explanatory. You fail to handle the case of empty input array.
public static int indexOfSmallest(int[] array){
// add this
if (array.length == 0)
return -1;
int index = 0;
int min = array[index];
for (int i = 1; i < array.length; i++){
if (array[i] <= min){
min = array[i];
index = i;
}
}
return index;
}
If the smallest element appears multiple times, and you want to return the index of its first occurrence, change your condition to:
if (array[i] < min)
If your numbers array is empty, and index is declared as 0, then min = array[index] will cause an error as you're trying to access the nonexistent first element of an empty list.
You should insert an if(before the for loop) that checks if the numbers array is empty.
You are getting IndexOutOfBoundsException because you are trying to retrieve a value from an empty array in the line:
int min = array[index];
Just check if array is empty before this line using:
if(array.length < 1) return -1;
public static int indexOfSmallest(int[] arr) {
int imin = 0;
for (int i = 1; i < arr.length; i++) {
if (arr[i] < arr[imin]) {
imin = i;
}
}
return imin;
}
or
int min = Arrays.stream(arr).min().orElseThrow();
int imin = Arrays.stream(arr).boxed().collect(Collectors.toList()).indexOf(min);
Related
Here is the question:
Given an integer array nums and an integer val, remove all
occurrences of val in nums in place. The relative order of the
elements may be changed.
Since it is impossible to change the length of the array in some
languages, you must instead have the result be placed in the first
part of the array nums.
More formally, if there are k elements after removing the duplicates,
then the first k elements of nums should hold the final result. It
does not matter what you leave beyond the first k elements.
Return k after placing the final result in the first k slots of
nums.
Do not allocate extra space for another array. You must do this by
modifying the input array in-place with O(1) extra memory.
I've tried to remove the given target val by shifting the value to the end of the array index by iteration of nums.length-1 every time the val is found in the given array. I just want to know what's wrong with my approach.
Below is the code I've tried:
class Solution {
public int removeElement(int[] nums, int val) {
for (int i = 0; i < nums.length; i++) {
if (val == nums[i]) {
for (int j = i; j < nums.length - 1; j++) {
nums[j + 1] = nums[j];
}
break;
}
}
return nums;
}
}
Your algorithm correctly would be the following. The error was returning the array, but that was changed in-situ. You should have returned the new reduced length.
public int removeElement(int[] nums, int val) {
int k = nums.length;
for (int i = 0; i < k; i++) {
if (val == nums[i]) {
--k;
//for (int j = i; i < k; j++) {
// nums[j] = nums[j + 1];
//}
System.arraycopy(nums, i+1, nums, i, k-i);
--i; // Check the new nums[i] too
}
}
return k;
}
The for-j loop can be replaced with System.arraycopy (which handles overlapping of the same array too).
Or:
public int removeElement(int[] nums, int val) {
int k = 0;
for (int i = 0; i < n; i++) {
if (val != nums[i]) {
nums[k] = nums[i];
++k;
}
}
return k;
}
This is my code in leetcode. Hope will help you
class Solution {
public int removeElement(int[] nums, int val) {
ArrayList<Integer> list = new ArrayList<>();
for(int i=0;i<nums.length;i++){
if(nums[i]!=val){
list.add(nums[i]);
}
}
for(int i=0;i<list.size();i++){
nums[i]= list.get(i);
}
return list.size();
}
}
I am trying to get the indices of large numbers within an array and I am having trouble doing so..
My code works if there is only one large number in the array. However, if there is one or more of the same large number, it does not works.
For example,
if I have an array {2,1,1,2,1}, it should return me the index 0 and 3 (this does not)
if I have an array {2,1,3,2,1}, it will then return me index 2. (this works)
Currently, I am trying to store the index by making use of an array, however in my code, as given in my example above, it only returns me the index of the first large number it found.
My code:
class Main {
public static void getIndexOfMax(int array[]) {
int max = array[0];
int pos = 0;
int max_index[] = new int[array.length];
int counter = 0;
for(int i=1; i<array.length; i++) {
if (max < array[i])
{
pos = i;
max = array[i];
max_index[counter] = pos;
counter += 1;
}
}
public static void main(String[] args) {
int[] num = {2,1,1,2,1};
getIndexOfMax(num);
}
}
Thanks in advance for any replies!
You need to check another case when you find the maximum value again and store the index. And when the new maximum value starts the counter from 0 again.
public static void printIndexOfMax(int array[]) {
int max = 0;
int max_index[] = new int[array.length];
int counter = 0;
for (int i = 0; i < array.length; i++) {
if (max <= array[i]) { // Allowing same maximum number
if (max < array[i]) // Start counter from 0 when new maximum value found
counter = 0;
max = array[i];
max_index[counter] = i;
counter++;
}
}
for (int i = 0; i < counter; i++) {
System.out.println(max_index[i]);
}
}
You can have another conditional stating, if max is equal to an array element, then store that element index also. Then you would have to declare another array for the max index positions.
`if (max < array[i]) {
pos = i;
indexStorage.add(pos)
max = array[I];
max_index[counter] = pos;
counter += 1;
}`
How can I optimize my algorithm to find the minimum absolute value difference in a given array. Here is my approach which checks each and every element and returning the value.
static int minAbsVal(int[] myArray){
ArrayList<Integer> diffs= new ArrayList(); // all absolute value differences
for (int i = 0; i < myArray.length; i++) {
for (int j = 0; j < myArray.length; j++) {
if (myArray[j]!=myArray[i]){
int absVal =Math.abs( myArray[i]- myArray[j]);
diffs.add(absVal);
}
}
}
int min = diffs.get(0);
for (int i = 1; i < diffs.size(); i++) {
if (min>diffs.get(i)){
min = diffs.get(i);
}
}
return min;
}
Check this solution. If array contains duplicates than it returns 0 if you wanna avoid than you can add conditions also.
static int minAbsVal(int[] myArray){
Arrays.sort(myArray);
ArrayList<Integer> diffs= new ArrayList<Integer>(); // all absolute value differences
for (int i = 0; i < myArray.length-1; i++) {
diffs.add(Math.abs( myArray[i+1] - myArray[i]));
}
Collections.sort(diffs);
return diffs.get(0);
}
Or you can also use :-
static int minAbsVal(int[] myArray){
Arrays.sort(myArray);
int minimum=Math.abs( myArray[1] - myArray[0]);
for (int i = 1; i < myArray.length-1; i++) {
int diff = Math.abs( myArray[i+1] - myArray[i]);
if (diff == 0)
return 0;
else if (minimum > diff)
minimum = diff;
}
return minimum;
}
Check the following solution,
static int minimumAbsoluteDifference(int n, int[] arr) {
int a = Math.abs(arr[1]-arr[0]);
Arrays.sort(arr);
for(int x=0;x<n-1;x++){
if(Math.abs(arr[x]-arr[x+1])<a){
a = Math.abs(arr[x]-arr[x+1]);
if(a==0){
return a;
}
}
}
return a;
}
Dependson the size of your array a good approach would be to divide it in different smaller arrays and look for the minimum of each in pararell and then compare those results .
Anyways you dont need so many iterations, you can just set the baseValue to the first element of the array and when iterating the array compare the baseValue vs the current, if the current is smaller then asign baseValue to current (I would rename baseValue to minValue in that case)
Wrote some code to try to find the maximum element in an un-ordered array and then delete it from the array. My first loop has the logic to find the maximum element while the second loop should take in the variable from the first loop, look ahead one space and then insert into the max element.
My below code seems to work for my second idea .. but does not find the right max array element.
My array has the following values {6, 3, 5, 2, 7, 9, 4}. It is finding the max array element to be 7 .. it should be 9.
public void deleteMax() {
// set value for comparison starting from the beginning of the array
int arrayMax = arr[0];
for (int i = 0; i < nElems; i++) {
if (arr[i] > arrayMax) {
arrayMax = arr[i];
for (int k = i; k < nElems; k++) {
arr[k] = arr[k + 1];
nElems--;
break;
}
}
}
}
why not use jQuery $.grep & Math.max like:
var arr = [6, 3, 5, 2, 7, 9, 4];
var maxNum = Math.max.apply(null, arr);
var newArr = $.grep( arr, function( n ) {
return n != maxNum;
});
console.log(newArr);
Fiddle
EDIT:
Well didn't realize you're using Java as the question showed in JavaScript section...
in Java, You can find max number in array like
int maxNum = arr.get(0); // get the first number in array
for (int i = 1; i < arr.length; i++) {
if ( arr.get(i) > maxNum) {
maxNum = array.get(i);
}
}
arr.remove(maxNum);
Well,, you don't need any second loop.
Only one loop and two variables called, f.ex. MaxElementPosition and MaxElementValue, which are updated every time inside the loop if the number on this position is greater than the last MaxElementValue, update both value and position.
While the loop you do need the value for comparing. In the end you only need the position.
Your inner loop is irrelevant, you only have a 1D array, so it makes no sense to do any inner iteration.
If you insist on performing no sorting on the array, then you could do something like this:
public void deleteMax() {
// set value for comparison starting from the beginning of the array
int arrayMax = arr[0];
int maxIndex = 0;
for (int i = 0; i < nElems; i++) {
if (arr[i] > arrayMax) {
arrayMax = arr[i];
maxIndex = i;
}
}
arr.remove(maxIndex);
}
Once the for loop finishes, we remove the item at maxIndex
#Alex is on the right track, but there is no remove function that can be called on an array in java. All that you need is the variable maxIndex that he gets, which of course will be the first occurence of this maximum, so if you need to remove every occurence of the maximum, that would be a different issue. So once you use #Alex code:
int arrayMax = arr[0];
int maxIndex = 0;
for (int i = 0; i < nElems; i++) {
if (arr[i] > arrayMax) {
arrayMax = arr[i];
maxIndex = i;
}
}
This would be much easier if instead of an array, you were to use an ArrayList, in which case the code would look like:
int arrayMax = arr.get(0);
int maxIndex = 0;
for (int i = 0; i < nElems; i++) {
if (arr[i] > arrayMax) {
arrayMax = arr[i];
maxIndex = i;
}
}
arr.remove(maxIndex);
Otherwise you would have to create a temp array to remove the value:
int[] temp = new int[arr.length-1];
for(int i = 0, index = 0; index < nElems; i++, index++)
{
if(index == maxIndex) index++;
temp[i] = arr[index];
}
arr = temp;
In my JAVA code, I am given a data and I have to find the mode. Everything successfully compiled, and every method works. However, when I try to access the mode, I get an java.lang.ArrayIndexOutOfBoundsException: 987 in my terminal window. The highlighted portion is in the following method, which is one of my max methods. The data array, by the way, is just int [] data.
public int maxOfData(int [] oa)
{
int max = oa[0];
for (int i = 1; i < size; i++)
{
if (oa[i] > max)
max = oa[i];
}
return max;
}
The exception is on the line if(oa[i] > max)
And the mode code is this:
public int[] modeOfData()
{
int[] tally = new int[maxOfData() + 1];
for( int i = 0; i < size; i++)
{
tally[data[i]]++;
}
//max contains frequency of modes
int max = maxOfData (tally);
int count = 0;
for( int i = 0; i < tally.length; i++)
{
if( tally[i] == max )
count++;
}
//count occurence of maxValue in tally (for)
//that determines how many modes there are
//declare another int called modes
int[] modes = new int[count];
//size of array should be count
//loop through tally and extract modes: it's the index value.
int pos = 0;
for( int i = 0; i < tally.length; i++)
{
if(tally[i] == count)
modes[pos++] = i;
}
return modes;
//modes are where the values are == max
}
My other max for data is the same but data instead of oa. I need both max methods, just like that, according to my teacher. So what do I do? How do I fix this?
I think the line
for (int i = 1; i < size; i++)
should be
for (int i = 1; i < oa.length; i++)
ArrayIndexOutOfBound Exception is thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array. Whenever you iterate an Array object. you need to iterate while checking the index is always lesser than its length
for example,
for(int i=1;i<array.length;i++){
//access array content in ith position
System.out.println(array[i]);
}
Your size variable has the value of an illegal array index. that's the problem
Look at the number stored into size and then check to see what size you declared oa[] to be. If size is bigger than the size of oa[] then you have a problem.
Problem is in this part of code
int max = oa[0];
for (int i = 1; i < size; i++)
{
if (oa[i] > max)
max = oa[i];
}
rewrite the method maxOfData(int [] oa) with proper checks like this
public int maxOfData(int[] oa) {
if (oa == null) {
throw new IllegalArgumentException("Input array is null");
}
int max=oa[0];
for (int i = 1; i < oa.length; i++) {
if (oa[i] > max)
max = oa[i];
}
return max;
}
if input array is null it should not be processed.