How to resolve the algorithm Sort a list of object identifiers step by step in the Nim programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Sort a list of object identifiers step by step in the Nim programming language
Table of Contents
Problem Statement
Object identifiers (OID) are strings used to identify objects in network data.
Show how to sort a list of OIDs, in their natural sort order.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Sort a list of object identifiers step by step in the Nim programming language
Source code in the nim programming language
import algorithm, sequtils, strutils
type OID = distinct string
# Borrow the `$` procedure from the base string type.
proc `$`(oid: OID): string {.borrow.}
template toSeqInt(oid: OID): seq[int] =
## Convert an OID into a sequence of integers.
oid.string.split('.').map(parseInt)
proc oidCmp(a, b: OID): int =
## Compare two OIDs. Return 0 if OIDs are equal, -1 if the first is
## less than the second, +1 is the first is greater than the second.
let aseq = a.toSeqInt
let bseq = b.toSeqInt
for i in 0..<min(aseq.len, bseq.len):
result = cmp(aseq[i], bseq[i])
if result != 0: return
result = cmp(aseq.len, bseq.len)
when isMainModule:
const OIDS = [OID"1.3.6.1.4.1.11.2.17.19.3.4.0.10",
OID"1.3.6.1.4.1.11.2.17.5.2.0.79",
OID"1.3.6.1.4.1.11.2.17.19.3.4.0.4",
OID"1.3.6.1.4.1.11150.3.4.0.1",
OID"1.3.6.1.4.1.11.2.17.19.3.4.0.1",
OID"1.3.6.1.4.1.11150.3.4.0"]
for oid in OIDS.sorted(oidCmp):
echo oid
import algorithm, sequtils, strutils
type OID = object
value: string
list: seq[int]
proc initOID(s: string): OID =
OID(value: s, list: s.split('.').map(parseInt))
proc `$`(oid: OID): string =
oid.value
proc oidCmp(a, b: OID): int =
## Compare two OIDs. Return 0 if OIDs are equal, -1 if the first is
## less than the second, +1 is the first is greater than the second.
for i in 0..<min(a.list.len, b.list.len):
result = cmp(a.list[i], b.list[i])
if result != 0: return
result = cmp(a.list.len, b.list.len)
when isMainModule:
const OIDS = [initOID("1.3.6.1.4.1.11.2.17.19.3.4.0.10"),
initOID("1.3.6.1.4.1.11.2.17.5.2.0.79"),
initOID("1.3.6.1.4.1.11.2.17.19.3.4.0.4"),
initOID("1.3.6.1.4.1.11150.3.4.0.1"),
initOID("1.3.6.1.4.1.11.2.17.19.3.4.0.1"),
initOID("1.3.6.1.4.1.11150.3.4.0")]
for oid in OIDS.sorted(oidCmp):
echo oid
You may also check:How to resolve the algorithm Random number generator (device) step by step in the Sidef programming language
You may also check:How to resolve the algorithm Execute Computer/Zero step by step in the Delphi programming language
You may also check:How to resolve the algorithm Trabb Pardo–Knuth algorithm step by step in the J programming language
You may also check:How to resolve the algorithm Write float arrays to a text file step by step in the J programming language
You may also check:How to resolve the algorithm Empty string step by step in the Harbour programming language