When to add -1 to array recursion? - java

I can't understand one thing, when do I need to add -1 to arr.length and when I don't need to add -1?
For example, this code will only work if I add -1:
public boolean array220(int[] nums, int index) {
if(index >= nums.length - 1)
return false;
if(nums[index] * 10 == nums[index + 1])
return true;
return array220(nums, index + 1);
}
And this code will only work if I won't add -1:
public int array11(int[] nums, int index) {
if(index >= nums.length)
return 0;
if(nums[index] == 11)
return 1 + array11(nums, index + 1);
return array11(nums, index + 1);
}

In the first example you access elements of the array using both nums[index] and nums[index+1].
Since the array lookup value must be < nums.length, the constraint is:
index+1 < nums.length
aka:
index < nums.length - 1
which means you exclusion logic is the reverse test:
if (index >= nums.length - 1)
In the second example, you only access nums[index], so:
index < nums.length
giving exclusion logic as:
if (index >= nums.length)

Since arrays are zero-based, arr.length is the size of the array, in the number of elements. This means that the last index is at arr.length-1, since 0 is the first element.
There's no clear cut rules, as for example if you use >= instead of > (or more usually <= vs. <, like in a simple for loop) you need to adjust your values.

If your array is empty, it contains 0 elements and the length is 0.
If your array has 1 element in 0 index, then the length is 1.
If your array has 2 elements in 0 and 1 indexes, then the length is 2.
and so on..
we can notice , that the first index of every array is 0 so the last index is always array.length-1.
therefore we can use two methods
first method
:if you want to use <
so the code will be something like (note that in the end , i will be equal to array.length-1)
for(int i=0;i<arr.length;i++)
second method:if you want to use <=
so the code will be something like (note that in the end , i will also be equal to array.length-1)
for(int i=0;i<=arr.length-1;i++)

Related

Trying to display the last index of a item in array Java

I am trying to display the last index of an item in array, an example:
{6,4,7,3,11,4} Last index of 4 = 5
I have written this method so far:
public int lastIndexOf(int[] nums, int num) {
int found = 0;
for (int i = nums.length; i < 0 ; i--) {
if (nums[i] == num) {
return i;
}
}
return -1;
}
Why does this not work? I am under the impression that you need to start the for loop at the start of the arrays length and then work backwards. I want to be able to use a for loop to do this, I set up a condition if there are no occurrences of the number to return -1 but when I am running this code I always return -1 no matter what numbers I am putting in.
How would I solve this using a for loop?
Your for loop conditions are not correct. Should be
for (int i = nums.length-1; i >= 0 ; i--) {
The "i<0" from before prevented it from entering the loop.
But the "i = nums.length" would have given you an Index out of bounds error. Need to subtract by 1 because Arrays are 0 indexed
You can also turn the array into list and use List's lastIndexOf method so you don't have to implement yourself.
Arrays.asList(nums).lastIndexOf(num)
note that lastIndexOf return -1 if num is not found in nums

Reversing elements in array

I've been looking at a for-loop that reverses the elements in an array, but I do not quite understand what's going on inside it. This is the code:
int middleIndex = (array.length) / 2;
for (int i = 0; i < middleIndex; i++) {
int temporaryVariable = array[i];
array[i] = array[array.length - 1 - i];
array[array.length - 1 - i] = temporaryVariable;
}
What exactly does the two lines below int temporaryVariable = array[i] do? How exactly does it reverse the elements?
It effectively reverses the elements of the array by swapping first with last element, second with second_last etc. In this way the number of operations are ayrray_length / 2.
The 2 lines after int temporaryVariable = array[i]; simply swap the i'th element with the i'th from last element, and we run this loop half time the number of elements in array.
First of all remember that array indexes start from 0.
So the index of the last element is the array.length - 1.
Those 3 lines are swapping the first item with the last item, then the 2nd item with the 2nd-from-last item, etc. The temporaryVariable is used as a temporary place to store one of the values during swapping, so that it doesn't get lost when it is overwritten by the other value.
Take a copy of the value at i:
int temporaryVariable = array[i];
Put item i from the end of the array (array.length - 1 - i) instead of it.
array[i] = array[array.length - 1 - i];
Put the temporarily stored item which was item i at i from the end (array.length - 1 - i).
array[array.length - 1 - i] = temporaryVariable;
The loop stops when i reaches the middle of the array. (If the array has an odd number of elements the middle one stays where it is.)
This algorithm is taking N/2 iterations of swapping values stored in an array. It starts from the beggining of the array (Index 0) and goes until its half(index N/2). It swaps the first element(indexed 0) with the last one (indexed N - 1 - 0), then swaps the second element(indexed 0 + 1) with the one before the last one(indexed N - 1 - (0 + 1)), and so on.
another part was to return the second biggest number, but for some reason it returns the third biggest number, which is really weird.
This is the code:
public static int returnSecondBiggest(int[] array) {
int largestElement = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] > largestElement) {
largestElement = array[i];
}
}
int secondBiggest = Integer.MIN_VALUE;
for (int i = 0; i < array.length; i++) {
if (array[i] > secondBiggest && array[i] != largestElement) {
secondBiggest = array[i];
}
}
return secondBiggest;
}
How does it return the third when the code should return the second? I'm so lost.

Returning the number of times a number appears in an Array?

So I'm doing a bunch of exercises, one of them asks me to write a method that is passed an array with each slot type int. This method should return the number of times 99 occurs in the array. Here's what I came up with on the fly:
public static int countNum(int[]x)
{
int count = 0;
for (int i = 0; i <= x.length;i++);
{
if (x[i] == 99)
count++;
}
return count;
}
All in all, I just need to write the method. Am I on the right track?
Well, there are two mistakes.
First: i < x.length; it should be like that or i <= x.length - 1; like that or you will get out of your array.
Second:
for (int i = 0; i <= x.length;i++)**;**
{
if (x[i] == 99)
count++;
}
You don't need ; or the next code will be out of for.
array.length returns length of an array and you don't want to iterate from 0 to length, but from 0 to length - 1.
Why? For example if an array is [1, 5] then:
array.length == 2, array[0] == 1, array[1] == 5 but array[2] throws java.lang.ArrayIndexOutOfBoundsException (because it tries to reach an element which is not in the array)
Remove the semicolon after the for statement:
for (int i = 0; i <= x.length;i++);
(a for loop executes statements which comes directly after it, and ";" ends a statement. The for(...) followed by ";" means that you have a loop which does nothing x.length times)

Understanding the logic of an add to an array method

This method is used to insert the element toAdd as the new first element of the array arr, shifting all of the current elements over to make space. The original last element of the array will just be lost. The method has no return value and if the array has no elements it should have no effect.
public static void insert(int[] arr, int toAdd){
if(arr.length > 0) {
for(int i = arr.length - 1; i > 0; --i) {
arr[i] = arr[i - 1];
}
arr[0] = toAdd;
}
}
I understand the part about if(arr.length > 0) this guarantees that we are working with an array with at least 1 element. The rest of the logic confuses me. Why set i = arr.length, why a - 1 afterward? why i > 0? and --i?
Thank you
You are browsing your array from its last element to the first, while shifting each element over by one. For example, when i = 3 we moving element 2 to position 3.
But this method doesn't work. A correct version would be:
public static void insert(int[] arr, int toAdd){
if(arr.length > 0) {
for(int i = arr.length - 1; i > 0; i--) {
arr[i] = arr[i - 1];
}
arr[0] = toAdd;
}
}
--i reduce the value of i before its use so it should be i-- or i should begin at arr.length or else you won't move the last element.
arr.length will return the number of elements in the array. If you had an array with elements at index 0, 1, and 2, it would return "3". The problem is that the array index is inclusive at 0, so you need to subtract 1 from the length to get the valid index of the last element in the array. (ie 3 - 1 = 2 and 2 is the true index of the last element)
The loop uses i > 0 because the index i is being decremented (ie i = i -1) by the '--i'. So the loop is starting at the highest element in the array (length -1), and counting down to the lowest (index 0).
Lastly, the line assigning toAdd to 0 should be outside of the for loop.
Why set i = arr.length and --i?
It is i = arr.length-1 and this the last index of the array. You have to start shifting elements looping backwards (--i, i-- would be ok, too), otherwise you'll be overriding elements before you can shift them.
why i > 0?
arr[0] = toAdd; should be outside of the loop and would fail for arr.length == 0.
You can simplify to:
public static void insert(int[] arr, int toAdd){
if(arr.length > 0) {
for(int i = arr.length - 1; i > 0; --i)
arr[i] = arr[i - 1];
arr[0] = toAdd;
}
}

Add 0 and 1 is alternate array cells in java

I have any array with value 0,0,0,0,0,0,0,0,1,1,1
Now my required output should be like each zero will be in odd index and 1 will be in even and if 0 left after that it should be copied after 1 and viceversa.
Means the output will be 0,1,0,1,0,1,0,0,0,0,0....
But the above operation must be done in a single pass of array
So I created an array with same size ,
then I started traversing the main array and one's 0 is encoutered I put a counter to set the value in odd index and viceversa
In the end when the index crossed the length of new array created , I started adding the 0 into the new cell in even mode from backward.
What can be the other better solution.
You don't need an extra array for this. You can do it in-place. Just keep two pointers, one which stops after every odd step and one which finds the 1s. When the second pointer encounters a 1 just swap it with the first pointer, increment the first pointer. Do this for the length of the array.
Lets try inplace in one pass
Keep one pointer at the beginning of the array and one at the end of the array.
I am assuming that number of zeroes is greater than number of ones
int begin = 0, end = length - 1;
while (begin < end){
if (A[begin] == 0 && A[end] == 1){
if (begin % 2 != 0){
int tmp = A[end];
A[end] = A[begin];
A[begin] = temp;
end--;
}
begin++;
}
else
break;
}
Remember, above solution won't work for cases when number of ones is greater than number of zeroes
#include<stdio.h>
main()
{
int arr[]={1,0,0,1,0,1,1,1,0,1};
int n=10;
int odd,one,tmp;
odd=one=0;
while(true)
{
while(odd<n && arr[odd])
odd+=2;
while(one<n && (((one<=odd)&&(one%2==0)) || !arr[one]))
one++;
if(odd<n && one<n)
{
arr[one]=arr[one]^arr[odd];
arr[odd]=arr[one]^arr[odd];
arr[one]=arr[one]^arr[odd];
}
else
break;
}
for(int i=0;i<n;i++)
printf("%d ",arr[i]);
}

Categories