+ 1
Java code (Find duplicated value in the array)
i need explanation of this code,i got mine inside code but doesn't correct https://code.sololearn.com/c54wNT94oXlX/?ref=app
12 RĂ©ponses
+ 2
Rael one moment, Iâm just writing it up for you and will add it here :)
Edit: Okay, the code I posted here explains how the code you wrote works and how my edited version works.
https://code.sololearn.com/c0B9eI40DEzd/#java
I hope it is clear enough for you.
+ 3
If you take out the second for loop, and change these lines it works:
for(int i = 0;i < arr.length-1;i++){
if(arr[i] == arr[i+1])
I think your code didn't work the way you wanted it to because of the nested for loop;for each instance of i it would run all of q. So what it was actually doing was this:
int[] arr = {33, 23, 67, 44, 44, 33, 345, 78};
i= 0, q= i+1 = 1
(33) (23)
arr[0] == arr[1] - Wrong
i=0, q++ = 2
(33) (67)
arr[0] == arr[2] - Wrong
i=0, q++ =3
(33) (44)
arr[0] == arr[3] - Wrong
i=0, q++ =3
(33) (44)
arr[0] == arr[4] - Wrong
i=0, q++ =4
(33) (33)
arr[0] == arr[5] - Correct
i=0, q++ =5
(33) (345)
arr[0] == arr[6] - Wrong
i=0, q++ =6
(33) (78)
arr[0] == arr[7] - Wrong
End loop, back to start:
i= 1, q = i+1 =2
(23) (67)
arr[1] == arr[2] - Wrong
i=1, q++ =3
(33) (44)
arr[1] == arr[3] - Wrong
and so on. I hope this makes sense?
+ 2
The code runs like that:
The first loop stands on a value and inside of it the second loop passes all the rest values and compares them and every time is moving on to the next value in the first loop(after the second one finishes with all the rest).
+ 2
Rael the code you wrote originally will find all duplicates in the array (q) as long as they are ahead of the index of i - that is, all duplicates that exist in the array (result: 33, 44).
The altered lines i suggested will compare items in the array that are next to each other to see if they match, which was the logic you typed out in your code comments (result: 44).
+ 2
Rael please see my last answer
+ 1
Eliya Ben Baruch like my comments inside the code?
+ 1
Rael no, it doesn't just compare with the next one.
For example from you code:
33 == 23
33 == 67
And so on until 33 will be compared with all the values in the array and then 23 will and then 67 and so on.
+ 1
Eliya Ben Baruch q = i+1
q = 0+1 which is 23 and i dont understand is how q = 1+1 since the i = 0
+ 1
Rincewind But it got the duplicated value that i wanted
+ 1
Rincewind Thank you so much! it helped me a lot! im so careless,i didnt mention the q++ ,AHHHHH,btw im really appreciate your explain,thank you again!
0
Rael Because the second loop keeps moving the whole values in the array for i = 0
0
Rincewind i hope u can explain the code like before because my english is bad actually...