HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Swap even/odd characters

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
charactersevenswapodd

Problem

I wrote some code to solve this problem https://www.hackerrank.com/challenges/string-o-permute which basically states: take an even length string and swap all the even indexed characters. For example the string "abcd" should become "badc". I'm looking for a general code review as I'm very new to F# and specifically I'd really like to get rid of the ignoredTupleValue variable, it seems like a kludge to me. I'd also like to collapse the whole thing into one function but I was running into scoping issues with the StringBuilder.

open System
open System.Text

[]
let main argv =
    let numCases = Console.ReadLine() |> int
    for i = numCases downto 1 do
        let strIn = Console.ReadLine()
        let pairs = Seq.pairwise strIn
        let ignoredTupleValue = ('1', '1')
        let swappedTuples = pairs |> Seq.mapi (fun idx pair ->
                                if idx % 2 = 0 then
                                    let (a, b) = pair
                                    (b, a)
                                else
                                    ignoredTupleValue)
        let answer = Seq.fold (fun (sb : StringBuilder) pair ->
                                if pair <> ignoredTupleValue then
                                    let (a, b) = pair
                                    sb.Append(a) |> ignore
                                    sb.Append(b) |> ignore
                                sb)
                                (new StringBuilder())
                                swappedTuples
        printfn "%s" (answer.ToString())
    0

Solution

The solution should look like (pseudocode, I know little F# too ;) ):

String
  |> ChunksOf 2
  |> Map Reverse
  |> Flatten


An example explains clearly

"abcd" -> ["ab", "cd"] -> ["ba", "dc"] -> "badc"


The key of effective Functional Programming is making good use of the built-in functions and carefully combining them.

Code Snippets

String
  |> ChunksOf 2
  |> Map Reverse
  |> Flatten
"abcd" -> ["ab", "cd"] -> ["ba", "dc"] -> "badc"

Context

StackExchange Code Review Q#129496, answer score: 7

Revisions (0)

No revisions yet.