How to resolve the algorithm Rep-string step by step in the F# programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Rep-string step by step in the F# programming language

Table of Contents

Problem Statement

Given a series of ones and zeroes in a string, define a repeated string or rep-string as a string which is created by repeating a substring of the first N characters of the string truncated on the right to the length of the input string, and in which the substring appears repeated at least twice in the original. For example, the string 10011001100 is a rep-string as the leftmost four characters of 1001 are repeated three times and truncated on the right to give the original string. Note that the requirement for having the repeat occur two or more times means that the repeating unit is never longer than half the length of the input string.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Rep-string step by step in the F# programming language

Source code in the fsharp programming language

let isPrefix p (s : string) = s.StartsWith(p)
let getPrefix n (s : string) = s.Substring(0,n)

let repPrefixOf str =
    let rec isRepeatedPrefix p s = 
        if isPrefix p s then isRepeatedPrefix p (s.Substring (p.Length))
        else isPrefix s p

    let rec getLongestRepeatedPrefix n =
        if n = 0 then None
        elif isRepeatedPrefix (getPrefix n str) str then Some(getPrefix n str)
        else getLongestRepeatedPrefix (n-1)

    getLongestRepeatedPrefix (str.Length/2)

[<EntryPoint>]
let main argv =
    printfn "Testing for rep-string (and showing the longest repeated prefix in case):" 
    [
    "1001110011"
    "1110111011"
    "0010010010"
    "1010101010"
    "1111111111"
    "0100101101"
    "0100100"
    "101"
    "11"
    "00"
    "1"
    ] |>
    List.map (fun s ->
        match repPrefixOf s with | None -> s + ": NO" | Some(p) -> s + ": YES ("+ p + ")")
    |> List.iter (printfn "%s")
    0


  

You may also check:How to resolve the algorithm Roman numerals/Encode step by step in the Nim programming language
You may also check:How to resolve the algorithm Luhn test of credit card numbers step by step in the BCPL programming language
You may also check:How to resolve the algorithm Inverted syntax step by step in the Phix programming language
You may also check:How to resolve the algorithm Sorting algorithms/Permutation sort step by step in the Quackery programming language
You may also check:How to resolve the algorithm Vector step by step in the BQN programming language