Android Question How many values appear (in sequence) code snippet help?

Mashiane

Expert
Licensed User
Longtime User
Hi there

I need some list conversion code snippet. Assume my list contains these values...

2,2,2,5,6,2,1,3,5,7,9,10,10,6,6,4,4,4,4,2,2,2,2

I need a snippet that will return a map maintaining the sequencing of the values and how many times they appear. From above, the output should be

2-3,5-1,6-1,2-1,1-1,3-1,5-1,7-1,9-1,10-2,6-2,4-4,2-4

What the code snippet should do...

1. Pass the list of values in the list (whether sorted / unsorted)
2. The code snippet should detect per value, how many they are e.g 2,2,2 = 2-3, meaning the value 2 appears 3 times
3. The sequence of values should be maintained i.e. there can be another sequence for the same value somewhere in the list, e.g. we start with value 2 and end with value 2.

Thanks a lot!
 

JordiCP

Expert
Licensed User
Longtime User
As a map can not hold different entries for a same key, the snippet could return for instance another list of a custom type

Something like this (assumes the list is non-empty and populated with ints)
B4X:
Sub Process_Globals
  Type sequencePair(value as int, numTimes as int)
End Sub
Sub Activity_Create(FirstTime as Boolean)
   '...
   Dim l As List
   l.Initialize
   l.AddAll(Array As Int(2,2,2,3,4,4,1,1,1,1,1,3,3,7,7,7,7,2,2,8,2))
   Dim l2 As List=FindSequences(l)
   For k=0 To l2.Size-1
     Dim pSeq As sequencePair = l2.Get(k)
     Log(pSeq.value&"-"&pSeq.numTimes)
   Next

Ens Sub

Sub FindSequences(srcList as List) as List
   Dim dstList as List
   dstList.initialize 
   Dim currentSequencePair as sequencePair
   currentSequencePair.initialize
   currentSequencePair.value=srcList.Get(0)
   currentSequencePair.numTimes=1
   For k=1 to srcList.size-1  '<-- edited!! (originally was 0)
      Dim newVal as int=srcList.Get(k)
      If newVal=currentSequencePair.value Then
         currentSequencePair.numTimes=currentSequencePair.numTimes+1
      Else
         dstList.Add(currentSequencePair)
         Dim currentSequencePair as sequencePair
         currentSequencePair.initialize
         currentSequencePair.value = newVal
         currentSequencePair.numTimes=1
     End If
   Next
   If currentSequencePair.numTimes>0 Then dstList.add(currentSequencePair)
   Return dstList
End Sub
 
Upvote 0

JordiCP

Expert
Licensed User
Longtime User
uhmmmm...yes but
3. The sequence of values should be maintained i.e. there can be another sequence for the same value somewhere in the list, e.g. we start with value 2 and end with value 2.
the request was not to count the totals but repeated sequences: 2-3,5-1,6-1,2-1,1-1,3-1,5-1,7-1,9-1,10-2,6-2,4-4,2-4 ;)
 
Upvote 0
Top