How to resolve the algorithm Executable library step by step in the Wren programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Executable library step by step in the Wren programming language
Table of Contents
Problem Statement
The general idea behind an executable library is to create a library that when used as a library does one thing; but has the ability to be run directly via command line. Thus the API comes with a CLI in the very same source code file. Task detail Notes:
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Executable library step by step in the Wren programming language
Source code in the wren programming language
/* Executable_library.wren */
var Hailstone = Fn.new { |n|
if (n < 1) Fiber.abort("Parameter must be a positive integer.")
var h = [n]
while (n != 1) {
n = (n%2 == 0) ? (n/2).floor : 3*n + 1
h.add(n)
}
return h
}
var libMain_ = Fn.new {
var h = Hailstone.call(27)
System.print("For the Hailstone sequence starting with n = 27:")
System.print(" Number of elements = %(h.count)")
System.print(" First four elements = %(h[0..3])")
System.print(" Final four elements = %(h[-4..-1])")
System.print("\nThe Hailstone sequence for n < 100,000 with the longest length is:")
var longest = 0
var longlen = 0
for (n in 1..99999) {
var h = Hailstone.call(n)
var c = h.count
if (c > longlen) {
longest = n
longlen = c
}
}
System.print(" Longest = %(longest)")
System.print(" Length = %(longlen)")
}
// Check if it's being used as a library or not.
import "os" for Process
if (Process.allArguments[1] == "Executable_library.wren") { // if true, not a library
libMain_.call()
}
/* Executable_library_2.wren */
import "./Executable_library" for Hailstone
var freq = {}
for (i in 1...100000) {
var len = Hailstone.call(i).count
var f = freq[len]
freq[len] = f ? f + 1 : 1
}
var mk = 0
var mv = 0
for (k in freq.keys) {
var v = freq[k]
if (v > mv) {
mk = k
mv = v
}
}
System.print("The Hailstone length returned most is %(mk), which occurs %(mv) times.")
You may also check:How to resolve the algorithm Last Friday of each month step by step in the jq programming language
You may also check:How to resolve the algorithm Conditional structures step by step in the Jakt programming language
You may also check:How to resolve the algorithm Probabilistic choice step by step in the Common Lisp programming language
You may also check:How to resolve the algorithm Set step by step in the Common Lisp programming language
You may also check:How to resolve the algorithm Non-decimal radices/Output step by step in the Forth programming language