How to get index of first and last position of repeating elements in an array in scala

admin

7/2/2023
All Articles

#How get index of first last position of repeating elements in an array in scala

How to get  index  of first  and last position of repeating elements in an array in scala

How to get  index  of first  and last position of repeating elements in an array in scala ?

I assume that you hae input array is (3,3,4,0,4,7,7,7) and input search element is & .
We are   searching for a solution independent by the last and first position of give input item that is 7, which is  present in the array.
In this case you need a loop where you perform your work on the current item found :-
 
 
var arr = Array(3,3,4,0,4,7,7,7)
var input =7
var count =0
var index=0
var pointer =0
for (ar <- arr )
{
   
  if (ar == input ){
    
    if(count== 0)
    {
      index = pointer + count
      println ("first index of input tht is "+input+"- "+index)
    }
    count =count+1
    
  }
  pointer =pointer +1
 
  
}
println("last value of index of element" +input+" -" + (index+count))
 
 

Output of above program is :

 
 
first index of input tht is 7 is - 5
last value of index of element 7 is  -8

Conclusion :

I am trying to find the starting  index  of repeated numbers in my array  .
and print value of first index that is 5 .
 
Similarly 
 
I am trying to find the last  index  of repeated numbers in my array  .
and print value of first index that is 8 .
 
I Hope you can easily undersand my approch of finding Solution .
for any query kindly drop mail.