tbdsux / siffer

Simple Caesar Cipher utility tools
MIT License
0 stars 0 forks source link

The code seems to be too complex #1

Closed ghost closed 3 years ago

ghost commented 3 years ago

Rot13 is a straightforward algorithm - it basically shifts letters by 13 positions. Why not just use basic math over chars? An example from Rosetta Code https://rosettacode.org/wiki/Rot-13#Nim adapted to strings (and a bit optimized with preallocation):

import std/strutils

# func means proc with a {.noSideEffect.} pragma
func rot13(str: string): string =
  result = newString(str.len)
  # iterate over each char in the string, giving its index and the char itself
  for i, c in str:
    result[i] = 
      case toLowerAscii(c)
      of 'a'..'m': chr(ord(c) + 13)
      of 'n'..'z': chr(ord(c) - 13)
      else: c

echo rot13("hello world")
echo rot13("HELLO WOrld")

# rot13(rot13(x)) will return the original string x
# because that's how rot13 works
echo rot13(rot13("hello world"))
echo rot13(rot13("HELLO WOrld"))
SolitudeSF commented 3 years ago

pr's are welcome

tbdsux commented 3 years ago

didn't know anyone will take interest over this simple project, I am a very beginner with Nim :sweat_smile: and this project was just meant for practice :sweat_smile:

btw, for the code, .. it was on purpose to be re-usable for other rotation ciphers, not only rot13 :blush:

tbdsux commented 3 years ago

I have accepted this change. Thank you very much for mentioning a better approach @Yardanico ...

I learned something from the code itself. :blush: