How to resolve the algorithm Order disjoint list items step by step in the Nim programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Order disjoint list items step by step in the Nim programming language

Table of Contents

Problem Statement

Given   M   as a list of items and another list   N   of items chosen from   M,   create   M'   as a list with the first occurrences of items from   N   sorted to be in one of the set of indices of their original occurrence in   M   but in the order given by their order in   N. That is, items in   N   are taken from   M   without replacement, then the corresponding positions in   M'   are filled by successive items from   N.

The words not in   N   are left in their original positions.

If there are duplications then only the first instances in   M   up to as many as are mentioned in   N   are potentially re-ordered.

Is ordered as:

Show the output, here, for at least the following inputs:

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Order disjoint list items step by step in the Nim programming language

Source code in the nim programming language

import algorithm, strutils


proc orderDisjoint(m, n: string): string =

  # Build the list of items.
  var m = m.splitWhitespace()
  let n = n.splitWhitespace()

  # Find the indexes of items to replace.
  var indexes: seq[int]
  for item in n:
    let idx = m.find(item)
    if idx >= 0:
      indexes.add idx
      m[idx] = ""   # Set to empty string for next searches.
  indexes.sort()

  # Do the replacements.
  for i, idx in indexes:
    m[idx] = n[i]

  result = m.join(" ")


when isMainModule:

  template process(a, b: string) =
    echo a, " | ", b, " → ", orderDisjoint(a, b)

  process("the cat sat on the mat", "mat cat")
  process("the cat sat on the mat", "cat mat")
  process("A B C A B C A B C", "C A C A")
  process("A B C A B D A B E", "E A D A")
  process("A B", "B")
  process("A B", "B A")
  process("A B B A", "B A")


  

You may also check:How to resolve the algorithm Write language name in 3D ASCII step by step in the Ada programming language
You may also check:How to resolve the algorithm Mutual recursion step by step in the BaCon programming language
You may also check:How to resolve the algorithm Find if a point is within a triangle step by step in the AutoHotkey programming language
You may also check:How to resolve the algorithm Exponentiation order step by step in the Smalltalk programming language
You may also check:How to resolve the algorithm Sort an array of composite structures step by step in the UNIX Shell programming language