Page 1 of 1

How would i do this?

Posted: Sat May 14, 2011 6:30 pm
by Cheatmasterbw
Does anyone know how i can do something like this

Convert this:
Code: Select all
aaaaaaaaaafffffffggggggggggggaaaaaaaaaaaaaaa
to this:
Code: Select all
[10]a[7]f[12]g[15]a
and back?

thanks in advance!

Re: How would i do this?

Posted: Sat May 14, 2011 8:59 pm
by mandai
This one took some thinking.
Code: Select all
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        Dim compacted As String = compact_string("abbbcccc")
        MsgBox(compacted)

        Dim expanded As String = expand_string(compacted)
        MsgBox(expanded)
    End Sub

    Function compact_string(ByVal input As String) As String
        Dim output As String = ""

        If input.Length > 0 Then

            Dim chars As List(Of Char) = New List(Of Char)
            Dim amounts As List(Of Integer) = New List(Of Integer)

            chars.Add(input(0))
            amounts.Add(1)
            For i As Integer = 1 To input.Length - 1
                If input(i) = chars(chars.Count - 1) Then
                    amounts(amounts.Count - 1) += 1
                Else
                    chars.Add(input(i))
                    amounts.Add(1)
                End If
            Next

            For i As Integer = 0 To amounts.Count - 1
                output += "[" & amounts(i) & "]" & chars(i)
            Next

        End If

        Return output
    End Function

    Function expand_string(ByVal input As String) As String

        Dim output As String = ""

        Dim lines As String() = input.Split(New Char() {"["c, "]"c})
        For i As Integer = 1 To lines.Length - 1 Step 2
            Dim times As Integer = Integer.Parse(lines(i))
            For i2 As Integer = 0 To times - 1
                output += lines(i + 1)
            Next
        Next

        Return output
    End Function