Advertisement
Justaus3r

Untitled

Aug 30th, 2021
2,237
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Nim 5.75 KB | None | 0 0
  1. #[
  2.   Remake of my python's ccube script that validates if a number follows collatz conjecture
  3. ]#
  4. import std/[os,strutils,strformat,random]
  5. import bigints
  6.  
  7. randomize()
  8.  
  9. let VER = "0.1.3"
  10. let banner = fmt"""
  11. ░█████╗░░█████╗░██╗░░░██╗██████╗░███████╗
  12. ██╔══██╗██╔══██╗██║░░░██║██╔══██╗██╔════╝
  13. ██║░░╚═╝██║░░╚═╝██║░░░██║██████╦╝█████╗░░
  14. ██║░░██╗██║░░██╗██║░░░██║██╔══██╗██╔══╝░░
  15. ╚█████╔╝╚█████╔╝╚██████╔╝██████╦╝███████╗
  16. ░╚════╝░░╚════╝░░╚═════╝░╚═════╝░╚══════╝Version{VER}"""
  17.  
  18. proc showUsage():void =  
  19.   echo(banner)
  20.   echo("""
  21.  
  22. Usage:ccube <ARGS>
  23. Note:These arguments are not positional,
  24. meaning you can use them in any order.
  25.  
  26. ARGUMENTS:
  27. --noloop:<true/false> | A boolean to check if next numbers
  28.                      | are to be validated for collatz conjecture.
  29.                      | by default this boolean is false
  30.                      |
  31. -n:<number>           | Number to be checked for.if no number
  32.                      | is given then a random number from
  33.                      | 1 to 1000 is used.
  34.                      |
  35. --file:<Path>         | Path for the file in which result will
  36.                      | be stored.if 'void' is specified then
  37.                      | results wont be stored in file.
  38.                      | default path is current directory.
  39.                      | default filename is iterationData.txt
  40. Examples:
  41.  1:ccube --noloop:false -n:69 --file:void
  42.  This command will calculate cc for numbers
  43.  onward from 68.no result will be stored.
  44.  
  45.  2:ccube -n:6969 --noloop:true
  46.  This command will check cc for only current number.
  47.  result is stored in samw directory with default
  48.  filename.
  49.  
  50.  3:ccube -n:69 --noloop:false --file:~/Desktop/pp.txt
  51.  This command will check cc for numbers
  52.  onward from 68.results are stored in Desktop on
  53.  file name pp.txt.
  54.  
  55.  cc* = collatz conj
  56. """)
  57.   quit()
  58.  
  59. proc parseParams():(string,string,string) =
  60.   if paramCount() > 0:
  61.     var
  62.       paramSequence:seq[string] = @[]
  63.       forbiddenCharArray = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","!","@","#","$","%","^","&","*","(",")","_","-","=","+","'","\"",":",";","<",">",".","/","?","[","]","{","}"]
  64.       validBools = ["true","false"]
  65.       noLoopSwitch = "--noloop:"
  66.       fileSwitch = "--file:"
  67.       numberParam = "-n:"
  68.       filePath:string
  69.       number:string
  70.       noLoopSwitchBool:string
  71.     for i in 1..paramCount():
  72.       paramSequence.add(paramStr(i))
  73.     for param in paramSequence:
  74.       if noLoopSwitch in param:
  75.         try:
  76.           noLoopSwitchBool = param.split(':')[1]
  77.           if noLoopSwitchBool in validBools:
  78.             discard
  79.           else:
  80.             stderr.write(&"Error:\"{noLoopSwitchBool}\",Invalid bool used")
  81.             quit()
  82.         except IndexDefect:
  83.           stderr.write("Error:Bad use of --noloop switch,valid bool expected")
  84.           quit()
  85.      
  86.       if numberParam in param:
  87.         try:
  88.           number = param.split(':')[1]
  89.           for forbiddenChar in forbiddenCharArray:
  90.             if forbiddenChar.toUpper in number or forbiddenChar.toLower in number:
  91.               stderr.write(fmt"Error:Expected a valid integer but got '{number}',[Value Error]")
  92.               quit()
  93.         except IndexDefect:
  94.           stderr.write("Error:Bad use of --noloop switch,valid integer expected")
  95.           quit()
  96.      
  97.       if fileSwitch in param:
  98.         try:
  99.           filePath = param.split(':')[1]      
  100.         except IndexDefect:
  101.           stderr.write("Error:Bad use of --file switch,valid file path expected")
  102.           quit()
  103.    
  104.     if len(filePath) > 0:
  105.       discard
  106.     else:
  107.       filePath = fmt"{getCurrentDir()}{DirSep}iterationData.txt"
  108.    
  109.     if len(number) > 0:
  110.       discard
  111.     else:
  112.       number = $rand(1..1000)
  113.    
  114.     if len(noLoopSwitchBool) > 0:
  115.       discard
  116.     else:
  117.       noLoopSwitchBool = "false"
  118.    
  119.     result = (noLoopSwitchBool,number,filePath)
  120.  
  121.   else:
  122.     showUsage()
  123.  
  124. proc isEven(number:BigInt):bool =
  125.   if number mod 2 == 0:
  126.     result = true
  127.   else:
  128.     result = false
  129.  
  130.  
  131.  
  132. proc main(cmdArgs:(string,string,string)):void =
  133.   var
  134.     noLoopSwitchBool = cmdArgs[0]
  135.     number = initBigInt(cmdArgs[1])
  136.     filePath = cmdArgs[2]
  137.     isLooping = true
  138.     incrementer:BigInt
  139.     noOfIterations:BigInt = initBigInt("0")
  140.   while isLooping or noLoopSwitchBool == "false":
  141.     incrementer = number
  142.     while number != 1:
  143.       if isEven(number):
  144.         number = number div 2
  145.         inc noOfIterations
  146.       else:
  147.         number = (number * 3) + 1
  148.         inc noOfIterations
  149.  
  150.     var echoData = &"""-----------------------------------
  151. Current Number:{incrementer}
  152. Number of iterations:{noOfiterations}
  153. -----------------------------------{'\n'}"""
  154.  
  155.     echo(echoData)
  156.     if filePath == "void":
  157.       discard
  158.     else:
  159.       try:
  160.         let writeData = open(filePath,fmAppend)
  161.         writeData.write(echoData)
  162.         writeData.close
  163.       except IOError as e:
  164.         stderr.write(fmt"Error:An Error occured while writing data,{'\n'}{'\n'}Details:{e.msg}")
  165.         quit()
  166.     inc incrementer
  167.     number = incrementer
  168.     noOfIterations = initBigInt("0")
  169.     if noLoopSwitchBool == "true":
  170.       isLooping = false
  171.  
  172.  
  173.  
  174.  
  175.  
  176. main(parseParams())
  177.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement