How to resolve the algorithm Run-length encoding step by step in the BASIC programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Run-length encoding step by step in the BASIC programming language

Table of Contents

Problem Statement

Given a string containing uppercase characters (A-Z), compress repeated 'runs' of the same character by storing the length of that run, and provide a function to reverse the compression. The output can be anything, as long as you can recreate the input with it.

Note: the encoding step in the above example is the same as a step of the Look-and-say sequence.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Run-length encoding step by step in the BASIC programming language

Source code in the basic programming language

DECLARE FUNCTION RLDecode$ (i AS STRING)
DECLARE FUNCTION RLEncode$ (i AS STRING)

DIM initial AS STRING, encoded AS STRING, decoded AS STRING

INPUT "Type something: ", initial
encoded = RLEncode(initial)
decoded = RLDecode(encoded)
PRINT initial
PRINT encoded
PRINT decoded

FUNCTION RLDecode$ (i AS STRING)
    DIM Loop0 AS LONG, rCount AS STRING, outP AS STRING, m AS STRING

    FOR Loop0 = 1 TO LEN(i)
        m = MID$(i, Loop0, 1)
        SELECT CASE m
            CASE "0" TO "9"
                rCount = rCount + m
            CASE ELSE
                IF LEN(rCount) THEN
                    outP = outP + STRING$(VAL(rCount), m)
                    rCount = ""
                ELSE
                    outP = outP + m
                END IF
        END SELECT
    NEXT
    RLDecode$ = outP
END FUNCTION

FUNCTION RLEncode$ (i AS STRING)
    DIM tmp1 AS STRING, tmp2 AS STRING, outP AS STRING
    DIM Loop0 AS LONG, rCount AS LONG

    tmp1 = MID$(i, 1, 1)
    tmp2 = tmp1
    rCount = 1

    FOR Loop0 = 2 TO LEN(i)
        tmp1 = MID$(i, Loop0, 1)
        IF tmp1 <> tmp2 THEN
            outP = outP + LTRIM$(RTRIM$(STR$(rCount))) + tmp2
            tmp2 = tmp1
            rCount = 1
        ELSE
            rCount = rCount + 1
        END IF
    NEXT

    outP = outP + LTRIM$(RTRIM$(STR$(rCount)))
    outP = outP + tmp2
    RLEncode$ = outP
END FUNCTION


  

You may also check:How to resolve the algorithm Compile-time calculation step by step in the Ursala programming language
You may also check:How to resolve the algorithm Truth table step by step in the Factor programming language
You may also check:How to resolve the algorithm Legendre prime counting function step by step in the Pascal programming language
You may also check:How to resolve the algorithm Digital root/Multiplicative digital root step by step in the 11l programming language
You may also check:How to resolve the algorithm Multiplication tables step by step in the Frink programming language