How to resolve the algorithm Selectively replace multiple instances of a character within a string step by step in the Nim programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Selectively replace multiple instances of a character within a string step by step in the Nim programming language

Table of Contents

Problem Statement

This is admittedly a trivial task but I thought it would be interesting to see how succinctly (or otherwise) different languages can handle it. Given the string: "abracadabra", replace programatically:

Note that there is no replacement for the third 'a', second 'b' or first 'r'. The answer should, of course, be : "AErBcadCbFD".

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Selectively replace multiple instances of a character within a string step by step in the Nim programming language

Source code in the nim programming language

import std/tables

type
  # Table of replacements for a character.
  Replacements = Table[int, char]
  # Table mapping characters to their replacement table.
  ReplacementTable = Table[char, Replacements]

const ReplTable = {'a': {1: 'A', 2: 'B', 4: 'C', 5: 'D'}.toTable,
                   'b': {1: 'E'}.toTable,
                   'r': {2: 'F'}.toTable
                  }.toTable

proc replace(text: string; replTable: ReplacementTable): string =
  var counts: Table[char, int]  # Follow count of characters.
  for c in text:
    if c in replTable:
      counts.mgetOrPut(c, 0).inc  # Update count for this char.
      let pos = counts[c]
      result.add replTable[c].getOrDefault(pos, c)
    else:
      result.add c

echo replace("abracadabra", ReplTable)


  

You may also check:How to resolve the algorithm Substring step by step in the Kotlin programming language
You may also check:How to resolve the algorithm Loops/Do-while step by step in the Befunge programming language
You may also check:How to resolve the algorithm Catamorphism step by step in the Standard ML programming language
You may also check:How to resolve the algorithm Ethiopian multiplication step by step in the Craft Basic programming language
You may also check:How to resolve the algorithm Bitwise operations step by step in the Racket programming language