+ 1
Just a minor bug i think
i wanna print first index of array and getting just zero. i think my base condition is fine. Problem is occurring in the return recursive part ?? correct me if I'm wrong here is my attempt 👇 https://code.sololearn.com/c1Szk9Q17Nru/?ref=app
13 Antworten
+ 2
Jayakrishna🇮🇳
By his logic he is getting 0 on value 2 also which should be index 1
+ 2
A͢J function is predefined i could not pass extra variable so i have used this way 👇
class HelloWorld {
public static int firstIndex(int input[], int x) {
return firstOccurance(input,x,0);
}
public static int firstOccurance(int input[],int x,int start){
if(start==input.length){
return -1;
}
if(input[start]==x){
return start;
}
return firstOccurance(input,x,start+1);
}
public static void main(String[] args) {
int[] arr={9, 8, 10, 8};
int x = 10;
System.out.println(firstIndex(arr,x));
}
}
+ 2
A͢J Thanks you sir 😌
+ 1
Davinder Kumar
You are always comparing with 0 here
int start=0;
if(input.length == start){
return
start will be always 0
+ 1
Sir i want to minimise the length of array so it can iterate over array and find my desire output. I tried copyArray approach here but that doesn't work . what sort of code i can write here then 😐
+ 1
Davinder Kumar
Try with reference variable
class HelloWorld {
public static int firstIndex(int input[], int i, int x) {
if(input.length <= i)
return -1;
if(input[i] == x)
return i;
return firstIndex(input, ++i, x);
}
public static void main(String[] args) {
int arr[] = {1, 2, 8, 4, 5, 2};
int num = 8;
int i = 0;
System.out.println(firstIndex(arr, i, num));
}
}
+ 1
Davinder Kumar
That is also fine
+ 1
A͢J one more question is that can i use these ways to get desire results in real interviews if the function is predefined?
+ 1
Davinder Kumar
Yes doesn't matter but your all test cases should satisfy.
+ 1
Jayakrishna🇮🇳 i couldn't do it from main because it is predefined function and i had to solve it by using those two parameters only that's why i additionally defined new function in firstIndex function. I hope you got me.
0
Any array first index is 0 only..!
Am I missing anything to understand this question?
Your code,
if(input[start]==x){
return start;
Here start = 0, x is index you passed is 1
So input[0] = 1 so 1 == 1 true then returns start which value is 0.
What else output you expecting?
edit:
code changed??
0
Seems original code changed..! It makes confusion, better make copy for updates..
Is there any need to use 2 methods..?
If not, Can be done using firstOccurence directly in main..
0
Davinder Kumar Yes. Just got noticed, already mentioned to AJ reply..