function playfair(key, txt, isencode=true, from = "J", to = "")
    to = (to == "" && from == "J") ? "I" : to

    function canonical(s, dup_toX=true)
        s = replace(replace(uppercase(s), from => to), r"[^A-Z]" => "")
        a, dupcount = [c for c in s], 0
        for i in 1:2:length(a)-1
            if s[i] == s[i + 1]
                dup_toX && splice!(a, i+1+dupcount:i+dupcount, 'X')
                dupcount += 1
            end
        end
        s = String(a)
        return isodd(length(s)) ? s * "X" : s
    end

    # Translate key into an encoding 5x5 translation matrix.
    keyletters = unique([c for c in canonical(key * "ABCDEFGHIJKLMNOPQRSTUVWXYZ", false)])
    m = Char.((reshape(UInt8.(keyletters[1:25]), 5, 5)'))

    # encod is a dictionary of letter pairs for encoding.
    encod = Dict()

    # Map pairs in same row or same column of matrix m.
    for i in 1:5, j in 1:5, k in 1:5
        if j != k
            encod[m[i, j] * m[i, k]] = m[i, mod1(j + 1, 5)] * m[i, mod1(k + 1, 5)]
        end
        if i != k
            encod[m[i, j] * m[k, j]] = m[mod1(i + 1, 5), j] * m[mod1(k + 1, 5), j]
        end
        # Map pairs not on same row or same column.
        for l in 1:5
            if i != k && j != l
                encod[m[i, j] * m[k, l]] = m[i, l] * m[k, j]
            end
        end
    end

    # Get array of pairs of letters from text.
    canontxt = canonical(txt)
    letterpairs = [canontxt[i:i+1] for i in 1:2:length(canontxt)-1]

    if isencode
        # Encode text
        return join([encod[pair] for pair in letterpairs], " ")
    else
        # Decode text
        decod = Dict((v, k) for (k, v) in encod)
        return join([decod[pair] for pair in letterpairs], " ")
    end
end

orig = "Hide the gold in...the TREESTUMP!!!"
println("Original: ", orig)

encoded = playfair("Playfair example", orig)
println("Encoded: ", encoded)

println("Decoded: ", playfair("Playfair example", encoded, false))

Implement the Playfair cipher for both encryption and decryption. It allows the user to choose whether 'J' equals 'I' or there's no 'Q' in the alphabet. The resulting encrypted and decrypted messages are presented in capitalized digraphs, separated by spaces.


Works with: Julia version 1.8
using Printf

struct Digraph{T <: Real,U}
    edges::Dict{Tuple{U,U},T}
    verts::Set{U}
end

function Digraph(edges::Vector{Tuple{U,U,T}}) where {T <: Real,U}
    vnames = Set{U}(v for edge in edges for v in edge[1:2])
    adjmat = Dict((edge[1], edge[2]) => edge[3] for edge in edges)
    return Digraph(adjmat, vnames)
end

vertices(g::Digraph) = g.verts
edges(g::Digraph)    = g.edges

neighbours(g::Digraph, v) = Set((b, c) for ((a, b), c) in edges(g) if a == v)

function dijkstrapath(g::Digraph{T,U}, source::U, dest::U) where {T, U}
    @assert source ∈ vertices(g) "$source is not a vertex in the graph"

    # Easy case
    if source == dest return [source], 0 end
    # Initialize variables
    inf  = typemax(T)
    dist = Dict(v => inf for v in vertices(g))
    prev = Dict(v => v   for v in vertices(g))
    dist[source] = 0
    Q = copy(vertices(g))
    neigh = Dict(v => neighbours(g, v) for v in vertices(g))

    # Main loop
    while !isempty(Q)
        u = reduce((x, y) -> dist[x] < dist[y] ? x : y, Q)
        pop!(Q, u)
        if dist[u] == inf || u == dest break end
        for (v, cost) in neigh[u]
            alt = dist[u] + cost
            if alt < dist[v]
                dist[v] = alt
                prev[v] = u
            end
        end
    end

    # Return path
    rst, cost = U[], dist[dest]
    if prev[dest] == dest
        return rst, cost
    else
        while dest != source
            pushfirst!(rst, dest)
            dest = prev[dest]
        end
        pushfirst!(rst, dest)
        return rst, cost
    end
end

# testgraph = [("a", "b", 1), ("b", "e", 2), ("a", "e", 4)]
const testgraph = [("a", "b", 7),  ("a", "c", 9),  ("a", "f", 14), ("b", "c", 10),
             ("b", "d", 15), ("c", "d", 11), ("c", "f", 2),  ("d", "e", 6),
             ("e", "f", 9)]

function testpaths()
    g = Digraph(testgraph)
    src, dst = "a", "e"
    path, cost = dijkstrapath(g, src, dst)
    println("Shortest path from $src to $dst: ", isempty(path) ?
       "no possible path" : join(path, " → "), " (cost $cost)")
    # Print all possible paths
    @printf("\n%4s | %3s | %s\n", "src", "dst", "path")
    @printf("----------------\n")
    for src in vertices(g), dst in vertices(g)
        path, cost = dijkstrapath(g, src, dst)
        @printf("%4s | %3s | %s\n", src, dst, isempty(path) ? "no possible path" : join(path, " → ") * " ($cost)")
    end
end

testpaths()

Implement Dijkstra's algorithm to find the shortest path from a source node to all other nodes in a graph. The graph is represented by an adjacency matrix or list, and a start node. The algorithm outputs a set of edges representing the shortest path to each reachable node. The program also interprets the output to display the shortest path from the source node to specific nodes.


Translation of: Sidef
module AVLTrees

import Base.print
export AVLNode, AVLTree, insert, deletekey, deletevalue, findnodebykey, findnodebyvalue, allnodes

@enum Direction LEFT RIGHT
avlhash(x) = Int32(hash(x) & 0xfffffff)
const MIDHASH = Int32(div(0xfffffff, 2))

mutable struct AVLNode{T}
    value::T
    key::Int32
    balance::Int32
    left::Union{AVLNode, Nothing}
    right::Union{AVLNode, Nothing}
    parent::Union{AVLNode, Nothing}
end
AVLNode(v::T, b, l, r, p) where T <: Real = AVLNode(v, avlhash(v), Int32(b), l, r, p)
AVLNode(v::T, h, b::Int64, l, r, p) where T <: Real = AVLNode(v, h, Int32(b), l, r, p)
AVLNode(v::T) where T <: Real = AVLNode(v, avlhash(v), Int32(0), nothing, nothing, nothing)

AVLTree(typ::Type) = AVLNode(typ(0), MIDHASH, Int32(0), nothing, nothing, nothing)
const MaybeAVL = Union{AVLNode, Nothing}

height(node::MaybeAVL) = (node == nothing) ? 0 : 1 + max(height(node.right), height(node.left))

function insert(node, value)
    if node == nothing
        node = AVLNode(value)
        return true
    end
    key, n, parent::MaybeAVL = avlhash(value), node, nothing
    while true
        if n.key == key
            return false
        end
        parent = n
        ngreater = n.key > key
        n = ngreater ? n.left : n.right
        if n == nothing
            if ngreater
                parent.left = AVLNode(value, key, 0, nothing, nothing, parent)
            else
                parent.right = AVLNode(value, key, 0, nothing, nothing, parent)
            end
            rebalance(parent)
            break
        end
    end
    return true
end

function deletekey(node, delkey)
    node == nothing && return nothing
    n, parent = MaybeAVL(node), MaybeAVL(node)
    delnode, child = MaybeAVL(nothing), MaybeAVL(node)
    while child != nothing
        parent, n = n, child
        child = delkey >= n.key ? n.right : n.left
        if delkey == n.key
            delnode = n
        end
    end
    if delnode != nothing
        delnode.key = n.key
        delnode.value = n.value
        child = (n.left != nothing) ? n.left : n.right
        if node.key == delkey
            root = child
        else
            if parent.left == n
                parent.left = child
            else
                parent.right = child
            end
            rebalance(parent)
        end
    end
end

deletevalue(node, val) = deletekey(node, avlhash(val))

function rebalance(node::MaybeAVL)
    node == nothing && return nothing
    setbalance(node)
    if node.balance < -1
        if height(node.left.left) >= height(node.left.right)
            node = rotate(node, RIGHT)
        else
            node = rotatetwice(node, LEFT, RIGHT)
        end
    elseif node.balance > 1
        if node.right != nothing && height(node.right.right) >= height(node.right.left)
            node = rotate(node, LEFT)
        else
            node = rotatetwice(node, RIGHT, LEFT)
        end
    end
    if node != nothing && node.parent != nothing
        rebalance(node.parent)
    end
end

function rotate(a, direction)
    (a == nothing || a.parent == nothing) && return nothing
    b = direction == LEFT ? a.right : a.left
    b == nothing && return
    b.parent = a.parent
    if direction == LEFT
        a.right = b.left
    else
        a.left  = b.right
    end
    if a.right != nothing
        a.right.parent = a
    end
    if direction == LEFT
        b.left = a
    else
        b.right = a
    end
    a.parent = b
    if b.parent != nothing
        if b.parent.right == a
            b.parent.right = b
        else
            b.parent.left = b
        end
    end
    setbalance([a, b])
    return b
end

function rotatetwice(n, dir1, dir2)
    n.left = rotate(n.left, dir1)
    rotate(n, dir2)
end

setbalance(n::AVLNode) = begin n.balance = height(n.right) - height(n.left) end
setbalance(n::Nothing) = 0
setbalance(nodes::Vector) = for n in nodes setbalance(n) end

function findnodebykey(node, key)
    result::MaybeAVL = node == nothing ? nothing : node.key == key ? node :
        node.left != nothing && (n = findbykey(n, key) != nothing) ? n :
        node.right != nothing ? findbykey(node.right, key) : nothing
    return result
end
findnodebyvalue(node, val) = findnodebykey(node, avlhash(v))

function allnodes(node)
    result = AVLNode[]
    if node != nothing
        append!(result, allnodes(node.left))
        if node.key != MIDHASH
            push!(result, node)
        end
        append!(result, node.right)
    end
    return result
end

function Base.print(io::IO, n::MaybeAVL)
    if n != nothing
        n.left != nothing && print(io, n.left)
        print(io, n.key == MIDHASH ? "<ROOT> " : "<$(n.key):$(n.value):$(n.balance)> ")
        n.right != nothing && print(io, n.right)
    end
end

end # module

using .AVLTrees

const tree = AVLTree(Int)

println("Inserting 10 values.")
foreach(x -> insert(tree, x), rand(collect(1:80), 10))
println("Printing tree after insertion: ")
println(tree)

implement an AVL tree, a self-balancing binary search tree where the heights of the two child subtrees of any node differ by at most one. The code ensures this by rebalancing the tree after each insertion or deletion. The operations of lookup, insertion, and deletion all take O(log n) time. The code does not allow duplicate node keys. The AVL tree implemented can be compared with red-black trees for its efficiency in lookup-intensive applications.


immutable Point{T<:FloatingPoint}
    x::T
    y::T
end

immutable Circle{T<:FloatingPoint}
    c::Point{T}
    r::T
end
Circle{T<:FloatingPoint}(a::Point{T}) = Circle(a, zero(T))

using AffineTransforms

function circlepoints{T<:FloatingPoint}(a::Point{T}, b::Point{T}, r::T)
    cp = Circle{T}[]
    r >= 0 || return (cp, "No Solution, Negative Radius")
    if a == b
        if abs(r) < 2eps(zero(T))
            return (push!(cp, Circle(a)), "Point Solution, Zero Radius")
        else
            return (cp, "Infinite Solutions, Indefinite Center")
        end
    end
    ca = Complex(a.x, a.y)
    cb = Complex(b.x, b.y)
    d = (ca + cb)/2
    tfd = tformtranslate([real(d), imag(d)])
    tfr = tformrotate(angle(cb-ca))
    tfm = tfd*tfr
    u = abs(cb-ca)/2
    r-u > -5eps(r) || return(cp, "No Solution, Radius Too Small")
    if r-u < 5eps(r)
        push!(cp, Circle(apply(Point, tfm*[0.0, 0.0]), r))
        return return (cp, "Single Solution, Degenerate Centers")
    end
    v = sqrt(r^2 - u^2)
    for w in [v, -v]
        push!(cp, Circle(apply(Point, tfm*[0.0, w]), r))
    end
    return (cp, "Two Solutions")
end

tp = [Point(0.1234, 0.9876),
      Point(0.0000, 2.0000),
      Point(0.1234, 0.9876),
      Point(0.1234, 0.9876),
      Point(0.1234, 0.9876)]

tq = [Point(0.8765, 0.2345),
      Point(0.0000, 0.0000),
      Point(0.1234, 0.9876),
      Point(0.8765, 0.2345),
      Point(0.1234, 0.9876)]

tr = [2.0, 1.0, 2.0, 0.5, 0.0]

println("Testing circlepoints:")
for i in 1:length(tp)
    p = tp[i]
    q = tq[i]
    r = tr[i]
    (cp, rstatus) = circlepoints(p, q, r)
    println(@sprintf("(%.4f, %.4f), (%.4f, %.4f), %.4f => %s",
                     p.x, p.y, q.x, q.y, r, rstatus))
    for c in cp
        println(@sprintf("    (%.4f, %.4f), %.4f",
                         c.c.x, c.c.y, c.r))
    end
end

The code defines a function that takes two 2D points and a radius as inputs and returns two circles that pass through these points. The function also handles special cases such as when the radius is zero, the points are coincident, the points form a diameter, or the points are too far apart. The function uses the AffineTransforms.jl package to create a coordinate system centered on the midpoint between the two points. The points are treated as complex numbers to help determine the midpoint and rotation angle. The code also includes a task to calculate the total area of the circles.


Implement the main step of the GOST 28147-89 symmetric encryption algorithm, which involves taking a 64-bit block of text and one of the eight 32-bit encryption key elements, using a replacement table, and returning an encrypted block.


while true
    n = rand(0:19)
    @printf "%4d" n
    if n == 10
        println()
        break
    end
    n = rand(0:19)
    @printf "%4d\n" n
end

generate and print random numbers from 0 to 19. If the generated number is 10, the loop stops. If the number is not 10, a second random number is generated and printed before the loop restarts. If 10 is never generated, the loop runs indefinitely.


# v0.6

using Primes

function mersennefactor(p::Int)::Int
    q = 2p + 1
    while true
        if log2(q) > p / 2
            return -1
        elseif q % 8 in (1, 7) && Primes.isprime(q) && powermod(2, p, q) == 1
            return q
        end
    q += 2p
    end
end

for i in filter(Primes.isprime, push!(collect(1:20), 929))
    mf = mersennefactor(i)
    if mf != -1 println("M$i = ", mf, " × ", (big(2) ^ i - 1) ÷ mf)
    else println("M$i is prime") end
end

implement a method to find a factor of a Mersenne number (in this case, M929). The method uses efficient algorithms to determine if a number divides 2P-1, including a self-implemented modPow operation. It also incorporates properties of Mersenne numbers to refine the process, such as the form of any factor q of 2P-1 and the conditions that q must meet. The method stops when 2kP+1 > sqrt(N). It only works on Mersenne numbers where P is prime.


using LibExpat

xdoc = raw"""<inventory title="OmniCorp Store #45x10^3">

    <item upc="123456789" stock="12">
      <name>Invisibility Cream</name>
      <price>14.50</price>
      <description>Makes you invisible</description>
    </item>
    <item upc="445322344" stock="18">
      <name>Levitation Salve</name>
      <price>23.99</price>
      <description>Levitate yourself for up to 3 hours per application</description>
    </item>

    <item upc="485672034" stock="653">
      <name>Blork and Freen Instameal</name>
      <price>4.95</price>
      <description>A tasty meal in a tablet; just add water</description>
    </item>
    <item upc="132957764" stock="44">
      <name>Grob winglets</name>
      <price>3.56</price>
      <description>Tender winglets of Grob. Just add water</description>
    </item>

</inventory>
"""

debracket(s) = replace(s, r".+\>(.+)\<.+" => s"\1")

etree = xp_parse(xdoc)
firstshow = LibExpat.find(etree, "//item")[1]
println("The first item's node XML entry is:\n", firstshow, "\n\n")

prices = LibExpat.find(etree, "//price")
println("Prices:")
for p in prices
    println("\t", debracket(string(p)))
end
println("\n")

namearray = LibExpat.find(etree, "//name")
println("Array of names of items:\n\t", map(s -> debracket(string(s)), namearray))

The code performs three XPath queries on a given XML document. It retrieves the first "item" element, prints out each "price" element, and gets an array of all the "name" elements. The XML document represents an inventory of a store. The LibExpat module is used for XML pathing.


julia> S1 = Set(1:4) ; S2 = Set(3:6) ; println(S1,"\n",S2)
Set{Int64}({4,2,3,1})
Set{Int64}({5,4,6,3})

julia> 5 in S1 , 5 in S2
(false,true)

julia> intersect(S1,S2)
Set{Int64}({4,3})

julia> union(S1,S2)
Set{Int64}({5,4,6,2,3,1})

julia> setdiff(S1,S2)
Set{Int64}({2,1})

julia> issubset(S1,S2)
false

julia> isequal(S1,S2)
false

julia> symdiff(S1,S2)
Set{Int64}({5,6,2,1})

demonstrate various set operations such as creation, checking if an element is present in a set, union, intersection, difference, subset and equality of sets. The code also optionally shows other set operations and methods to modify a mutable set. It may implement a set using an associative array, binary search tree, hash table, or an ordered array of binary bits. The code also discusses the time complexity of the basic test operation in different scenarios.


using Dates

lo, hi = 2008, 2121
xmas = collect(Date(lo, 12, 25):Year(1):Date(hi, 12, 25))
filter!(xmas) do dt
    dayofweek(dt) == Dates.Sunday
end

println("Years from $lo to $hi having Christmas on Sunday: ")
foreach(println, year.(xmas))

The code determines the years between 2008 and 2121 where Christmas (25th December) falls on a Sunday, using standard date handling libraries. It also compares the results with other languages to identify any anomalies in date/time representation, such as overflow issues similar to y2k problems.


The code performs QR decomposition on a given matrix using the Householder reflections method. It demonstrates this process on an example matrix and uses the decomposition for solving linear least squares problems. The code also handles cases where the matrix is not square by removing zero padded bottom rows. It finally solves the upper triangular system by back substitution.


Works with: Julia version 0.6
a = [1, 2, 3, 4, 1, 2, 3, 4]
@show unique(a) Set(a)

implement three methods to remove duplicate elements from an array: 1) Using a hash table, 2) Sorting the array and removing consecutive duplicates, and 3) Iterating through the list and discarding any repeated elements.


sort!(A, alg=QuickSort)

function quicksort!(A,i=1,j=length(A))
    if j > i
        pivot = A[rand(i:j)] # random element of A
        left, right = i, j
        while left <= right
            while A[left] < pivot
                left += 1
            end
            while A[right] > pivot
                right -= 1
            end
            if left <= right
                A[left], A[right] = A[right], A[left]
                left += 1
                right -= 1
            end
        end
        quicksort!(A,i,right)
        quicksort!(A,left,j)
    end
    return A
end

qsort(L) = isempty(L) ? L : vcat(qsort(filter(x -> x < L[1], L[2:end])), L[1:1], qsort(filter(x -> x >= L[1], L[2:end])))

implement the Quicksort algorithm. It sorts an array or list of elements with a strict weak order. The algorithm works by selecting a pivot element and dividing the rest of the elements into two partitions - one with elements less than the pivot and the other with elements greater than the pivot. It then recursively sorts both partitions and joins them together with the pivot. The codes also include a version of the Quicksort algorithm that works in place by swapping elements within the array to avoid additional memory allocation. The pivot selection method is not specified.


Works with: Julia version 0.6
ts = Dates.today()

println("Today's date is:")
println("\t$ts")
println("\t", Dates.format(ts, "E, U dd, yyyy"))

display the current date in two formats: "2007-11-23" and "Friday, November 23, 2007".


function powerset(x::Vector{T})::Vector{Vector{T}} where T
    result = Vector{T}[[]]
    for elem in x, j in eachindex(result)
        push!(result, [result[j] ; elem])
    end
    result
end

implement a function that takes a set as input and returns its power set. The power set includes all subsets of the input set, including the empty set and the set itself. The function also demonstrates the handling of edge cases where the input set is empty or contains only the empty set.


using Printf

function romanencode(n::Integer)
    if n < 1 || n > 4999 throw(DomainError()) end

    DR = [["I", "X", "C", "M"] ["V", "L", "D", "MMM"]]
    rnum = ""
    for (omag, d) in enumerate(digits(n))
        if d == 0
            omr = ""
        elseif d <  4
            omr = DR[omag, 1] ^ d
        elseif d == 4
            omr = DR[omag, 1] * DR[omag, 2]
        elseif d == 5
            omr = DR[omag, 2]
        elseif d <  9
            omr = DR[omag, 2] * DR[omag, 1] ^ (d - 5)
        else
            omr = DR[omag, 1] * DR[omag + 1, 1]
        end
        rnum = omr * rnum
    end
    return rnum
end

testcases = [1990, 2008, 1668]
append!(testcases, rand(1:4999, 12))
testcases = unique(testcases)

println("Test romanencode, arabic => roman:")
for n in testcases
    @printf("%-4i => %s\n", n, romanencode(n))
end

create a function that converts a positive integer into its equivalent Roman numeral representation.


julia> A = Vector(undef, 3)   # create an heterogeneous 1-D array of length 3
3-element Vector{Any}:
 #undef
 #undef
 #undef

julia> A[1] = 4.5 ; A[3] =  "some string" ; show(A)
{4.5,#undef,"some string"}

julia> A[1]          # access a value. Arrays are 1-indexed
4.5

julia> push!(A, :symbol) ; show(A)    # append an element
{4.5,#undef,"some string",:symbol}

julia> A[10]         # error if the index is out of range
ERROR: BoundsError()

julia> B = Array(String, 3) ; B[1]="first" ; push!(B, "fourth") ; show(B)
["first",#undef,#undef,"fourth"]

julia> push!(B, 3)   # type error
ERROR: no method convert(Type{String}, Int64)
 in push! at array.jl:488

julia> ['a':'c'...]     # type inference
3-element Vector{Char}:
 'a': ASCII/Unicode U+0061 (category Ll: Letter, lowercase)
 'b': ASCII/Unicode U+0062 (category Ll: Letter, lowercase)
 'c': ASCII/Unicode U+0063 (category Ll: Letter, lowercase)

demonstrate the basic syntax of arrays in Julia, including creating both heterogeneous and typed arrays, assigning values to them, and retrieving elements. The code also shows how to handle both fixed-length and dynamic arrays.


mystring = read("file1", String)
open(io->write(io, mystring), "file2", "w")

cp("file1","file2")

infile = open("file1", "r")
outfile = open("file2", "w")
write(outfile, read(infile, String))
close(outfile)
close(infile)

open(IO ->write(IO, read("file1", String)), "file2", "w")

demonstrate how to create a file named "output.txt" and write into it the contents of "input.txt" file via an intermediate variable. It also showcases how to read from a file into a variable and how to write a variable's contents into a file. The code also includes a one-liner that ensures the file handle is closed even if an error occurs during the read/write process. It also mentions the use of Julia's `cp` function to copy file contents.


julia> uppercase("alphaBETA")
"ALPHABETA"

julia> lowercase("alphaBETA")
"alphabeta"

julia> a = 'ß'
'ß': Unicode U+00DF (category Ll: Letter, lowercase)

julia> uppercase(a)
'ẞ': Unicode U+1E9E (category Lu: Letter, uppercase)

demonstrate the conversion of the string "alphaBETA" to upper-case and lower-case using the default encoding. The codes also showcase additional case conversion functions such as swapping case, capitalizing the first letter, etc. that are available in the language's library. It also handles special cases like the transformation of "ß" to "ẞ" in Julia.


Works with: Julia version 0.6

function closestpair(P::Vector{Vector{T}}) where T <: Number
    N = length(P)
    if N < 2 return (Inf, ()) end
    mindst = norm(P[1] - P[2])
    minpts = (P[1], P[2])
    for i in 1:N-1, j in i+1:N
        tmpdst = norm(P[i] - P[j])
        if tmpdst < mindst
            mindst = tmpdst
            minpts = (P[i], P[j])
        end
    end
    return mindst, minpts
end

closestpair([[0, -0.3], [1., 1.], [1.5, 2], [2, 2], [3, 3]])

The code provides two algorithms to solve the Closest Pair of Points problem in a two-dimensional plane. The first algorithm is a brute-force approach with a time complexity of O(n^2), which iterates over all pairs of points to find the minimum distance. The second algorithm uses a recursive divide-and-conquer approach with a time complexity of O(n log n), which sorts the points by x and y coordinates, divides them into two halves, and recursively finds the closest pairs in each half and the strip between them.


julia> collection = []
0-element Array{Any,1}

julia> push!(collection, 1,2,4,7)
4-element Array{Any,1}:
 1
 2
 4
 7

create a collection in Julia, add a few values to it, and utilize various collection types including vectors, matrices, lists, associative arrays, and bitsets. The code also demonstrates slicing notation and list comprehensions similar to Python, but with a base index of 1.


Library: JuMPusing JuMP
using GLPKMathProgInterface

model = Model(solver=GLPKSolverMIP())

@variable(model, vials_of_panacea >= 0, Int)
@variable(model, ampules_of_ichor >= 0, Int)
@variable(model, bars_of_gold >= 0, Int)

@objective(model, Max, 3000*vials_of_panacea + 1800*ampules_of_ichor + 2500*bars_of_gold)

@constraint(model, 0.3*vials_of_panacea + 0.2*ampules_of_ichor + 2.0*bars_of_gold <= 25.0)
@constraint(model, 0.025*vials_of_panacea + 0.015*ampules_of_ichor + 0.002*bars_of_gold <= 0.25)

println("The optimization problem to be solved is:")
println(model)

status = solve(model)

println("Objective value: ", getobjectivevalue(model))
println("vials of panacea = ", getvalue(vials_of_panacea))
println("ampules of ichor = ", getvalue(ampules_of_ichor))
println("bars of gold = ", getvalue(bars_of_gold))

determine the maximum value of items that a traveler can carry in his knapsack, given the weight and volume constraints. The items include vials of panacea, ampules of ichor, and bars of gold. The code calculates the optimal quantity of each item to maximize the total value, considering that only whole units of any item can be taken.


demonstrate a loop in Julia that prints a comma-separated list from 1 to 10, using separate output statements for the number and the comma. The loop uses the short-circuiting && operator to ensure the comma is not printed on the last iteration.


Works with: Julia version 0.6
Translation of: Python
function toposort(data::Dict{T,Set{T}}) where T
    data = copy(data)
    for (k, v) in data
        delete!(v, k)
    end
    extraitems = setdiff(reduce(∪, values(data)), keys(data))
    for item in extraitems
        data[item] = Set{T}()
    end
    rst = Vector{T}()
    while true
        ordered = Set(item for (item, dep) in data if isempty(dep))
        if isempty(ordered) break end
        append!(rst, ordered)
        data = Dict{T,Set{T}}(item => setdiff(dep, ordered) for (item, dep) in data if item ∉ ordered)
    end
    @assert isempty(data) "a cyclic dependency exists amongst $(keys(data))"
    return rst
end

data = Dict{String,Set{String}}(
    "des_system_lib" => Set(split("std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee")),
    "dw01" =>           Set(split("ieee dw01 dware gtech")),
    "dw02" =>           Set(split("ieee dw02 dware")),
    "dw03" =>           Set(split("std synopsys dware dw03 dw02 dw01 ieee gtech")),
    "dw04" =>           Set(split("dw04 ieee dw01 dware gtech")),
    "dw05" =>           Set(split("dw05 ieee dware")),
    "dw06" =>           Set(split("dw06 ieee dware")),
    "dw07" =>           Set(split("ieee dware")),
    "dware" =>          Set(split("ieee dware")),
    "gtech" =>          Set(split("ieee gtech")),
    "ramlib" =>         Set(split("std ieee")),
    "std_cell_lib" =>   Set(split("ieee std_cell_lib")),
    "synopsys" =>       Set(),
    )

println("# Topologically sorted:\n - ", join(toposort(data), "\n - "))

The code implements a function that performs a topological sort on VHDL libraries based on their dependencies. It ensures that no library is compiled before the ones it depends on. The function also handles cases of self-dependencies and flags un-orderable dependencies. It uses either Kahn's 1962 topological sort or depth-first search algorithm for sorting.


startswith("abcd","ab")            #returns true
findfirst("ab", "abcd")            #returns 1:2, indices range where string was found
endswith("abcd","zn")              #returns false
match(r"ab","abcd") != Nothing     #returns true where 1st arg is regex string
for r in eachmatch(r"ab","abab")
	println(r.offset)
end                                #returns 1, then 3 matching the two starting indices where the substring was found

The code checks if a given string starts with, contains, or ends with a second string. It also prints the location of the match and handles multiple occurrences of the second string within the first string.


Translation of: Python
using Combinatorics

function foursquares(low, high, onlyunique=true, showsolutions=true)
    integers = collect(low:high)
    count = 0
    sumsallequal(c) = c[1] + c[2] == c[2] + c[3] + c[4] == c[4] + c[5] + c[6] == c[6] + c[7]
    combos = onlyunique ? combinations(integers) :
                          with_replacement_combinations(integers, 7)
    for combo in combos, plist in unique(collect(permutations(combo, 7)))
        if sumsallequal(plist)
            count += 1
            if showsolutions
                println("$plist is a solution for the list $integers")
            end
        end
    end
    println("""Total $(onlyunique?"unique ":"")solutions for HIGH $high, LOW $low: $count""")
end

foursquares(1, 7, true, true)
foursquares(3, 9, true, true)
foursquares(0, 9, false, false)

The code finds all possible solutions for a 4-squares puzzle where each square sums up to the same total. It operates under two conditions: each letter representing a unique value between 1-7 and 3-9, and each letter representing a non-unique value between 0-9. The code also counts the number of non-unique solutions.


using Gtk, Colors, Graphics, Dates

const radius = 300
const win = GtkWindow("Clock", radius, radius)
const can = GtkCanvas()
push!(win, can)

global drawcontext = []

function drawline(ctx, l, color)
    isempty(l) && return
    p = first(l)
    move_to(ctx, p.x, p.y)
    set_source(ctx, color)
    for i = 2:length(l)
        p = l[i]
        line_to(ctx, p.x, p.y)
    end
    stroke(ctx)
end

function clockbody(ctx)
    set_coordinates(ctx, BoundingBox(0, 100, 0, 100))
    rectangle(ctx, 0, 0, 100, 100)
    set_source(ctx, colorant"yellow")
    fill(ctx)
    set_source(ctx, colorant"blue")
    arc(ctx, 50, 50, 45, 45, 360)
    stroke(ctx)
    for hr in 1:12
        radians = hr * pi / 6.0
        drawline(ctx, [Point(50 + 0.95 * 45 * sin(radians),
            50 - 0.95 * 45 * cos(radians)),
            Point(50 + 1.0 * 45 * sin(radians),
            50 - 1.0 * 45 * cos(radians))], colorant"blue")
    end
end

Gtk.draw(can) do widget
    ctx = getgc(can)
    if length(drawcontext) < 1
        push!(drawcontext, ctx)
    else
        drawcontext[1] = ctx
    end
    clockbody(ctx)
end

function update(can)
    dtim = now()
    hr = hour(dtim)
    mi = minute(dtim)
    sec = second(dtim)
    if length(drawcontext) < 1
        return
    end
    ctx = drawcontext[1]
    clockbody(ctx)
    rad = (hr % 12) * pi / 6.0 + mi * pi / 360.0
    drawline(ctx, [Point(50, 50),
        Point(50 + 45 * 0.5 * sin(rad), 50 - 45 * 0.5 * cos(rad))], colorant"black")
    stroke(ctx)
    rad = mi * pi / 30.0  + sec * pi / 1800.0
    drawline(ctx, [Point(50, 50),
        Point(50 + 0.7 * 45 * sin(rad), 50 - 0.7 * 45 * cos(rad))], colorant"darkgreen")
    stroke(ctx)
    rad = sec * pi / 30.0
    drawline(ctx, [Point(50, 50),
        Point(50 + 0.9 * 45 * sin(rad), 50 - 0.9 * 45 * cos(rad))], colorant"red")
    stroke(ctx)
    reveal(can)
end

Gtk.showall(win)
sloc = Base.Threads.SpinLock()
lock(sloc)
signal_connect(win, :destroy) do widget
    unlock(sloc)
end
while !trylock(sloc)
    update(win)
    sleep(1.0)
end

illustrate a time-keeping device that updates every second and cycles periodically. It is designed to be simple, efficient, and not to overuse CPU resources by avoiding unnecessary system timer polling. The time displayed aligns with the system clock. Both text-based and graphical representations are supported.


# IF THIS SMALL FUNCTION IS PLACED IN THE STARTUP.JL
# FILE, IT WILL BE LOADED ON STARTUP. THE REST OF
# THIS EXAMPLE IS IN ALL UPPERCASE.
function RUNUPPERCASECODE(CO)
    COD = replace(lowercase(CO), "date" => "Date")
    for E in Meta.parse(COD, 1) eval(E) end
end

CODE = """BEGIN

USING DATES;
CENTEROBJECT(X, N) = BEGIN S = UPPERCASE(STRING(X)); RPAD(LPAD(S, DIV(N + LENGTH(S), 2)), N) END;
FUNCTION FORMATMONTH(YR, MO)
    DT = DATE(\"\$YR-\$MO-01\");
    DAYOFWEEKFIRST = DAYOFWEEK(DT);
    NUMWEEKLINES = 1;
    STR = UPPERCASE(CENTEROBJECT(MONTHNAME(DT), 20) * \"\\NMO TU WE TH FR SA SU\\N\");
    STR *= \" \" ^ (3 * (DAYOFWEEKFIRST - 1)) * LPAD(STRING(1), 2);
    FOR I = 2:DAYSINMONTH(DT)
        IF (I + DAYOFWEEKFIRST + 5) % 7 == 0
            STR *= \"\\N\" * LPAD(I, 2);
            NUMWEEKLINES += 1;
        ELSE
            STR *= LPAD(STRING(I), 3);
        END;
    END;
    STR *= NUMWEEKLINES < 6 ? \"\\N\\N\\N\" : \"\\N\\N\";
    ARR = [];
    FOR S IN SPLIT(STR, \"\\N\")
        PUSH!(ARR, RPAD(S, 20)[1:20])
    END;
    JOIN(ARR, \"\\N\");
END;

FUNCTION FORMATYEAR(DISPLAYYEAR)
    CALMONTHS = [FORMATMONTH(DISPLAYYEAR, MO) FOR MO IN 1:12];
    MONTHSPERLINE = 6;
    JOINSPACES = 2;
    STR = \"\\N\" * CENTEROBJECT(DISPLAYYEAR, 132) * \"\\N\";
    MONTHCAL = [SPLIT(FORMATMONTH(DISPLAYYEAR, I), \"\\N\") FOR I IN 1:12];
    FOR I IN 1:MONTHSPERLINE:LENGTH(CALMONTHS) - 1
        FOR J IN 1:LENGTH(MONTHCAL[1])
            MONTHLINES = MAP(X->MONTHCAL[X][J], I:I + MONTHSPERLINE - 1);
            STR *= RPAD(JOIN(MONTHLINES, \" \" ^ JOINSPACES), 132) * \"\\N\";
        END;
        STR *= \"\\N\";
    END;
    STR;
END;

PRINTLN(FORMATYEAR(1969));

END;
"""

RUNUPPERCASECODE(CODE)

provide an algorithm for a calendar task, formatted to fit a 132-character wide page, inspired by 1969 era line printers. The code must be entirely in uppercase, mimicking the constraints of 1960s programming. The code does not include Snoopy generation, but rather a placeholder. The code is written in Julia and can be executed from a string using Meta.parse() and eval functions.


function primitiven{T<:Integer}(m::T)
    1 < m || return T[]
    m != 2 || return T[1]
    !isprime(m) || return T[2:2:m-1]
    rp = trues(m-1)
    if isodd(m)
        rp[1:2:m-1] = false
    end
    for p in keys(factor(m))
        rp[p:p:m-1] = false
    end
    T[1:m-1][rp]
end

function pythagoreantripcount{T<:Integer}(plim::T)
    primcnt = 0
    fullcnt = 0
    11 < plim || return (primcnt, fullcnt)
    for m in 2:plim
        p = 2m^2
        p+2m <= plim || break
        for n in primitiven(m)
            q = p + 2m*n
            q <= plim || break
            primcnt += 1
            fullcnt += div(plim, q)
        end
    end
    return (primcnt, fullcnt)
end

println("Counting Pythagorian Triplets within perimeter limits:")
println("    Limit          All   Primitive")
for om in 1:10
    (pcnt, fcnt) = pythagoreantripcount(10^om)
    println(@sprintf "    10^%02d  %11d   %9d" om fcnt pcnt)
end

The code determines the number of Pythagorean triples with a perimeter not exceeding 100 and identifies how many of these are primitive. It also handles large values up to a maximum perimeter of 100,000,000. The solution utilizes the Euclidean concept of m and n as generators of Pythagorean triplets, ensuring that the generated triplets are primitive when m and n are coprime and have opposite parity.


# v0.6

using Tk

w = Toplevel("Example")

"Creates an empty GUI window that can respond to close requests."


using DataStructures

function letterfreq(file::AbstractString; fltr::Function=(_) -> true)
    sort(Dict(counter(filter(fltr, read(file, String)))))
end

display(letterfreq("src/Letter_frequency.jl"; fltr=isletter))

Open a text file, count the frequency of each letter, and differentiate between counting all characters or only letters A to Z.


Works with: Julia version 0.6
abstract type AbstractNode{T} end

struct EmptyNode{T} <: AbstractNode{T} end
mutable struct Node{T} <: AbstractNode{T}
    data::T
    next::AbstractNode{T}
end
Node{T}(x) where T = Node{T}(x::T, EmptyNode{T}())

mutable struct LinkedList{T}
    head::AbstractNode{T}
end
LinkedList{T}() where T = LinkedList{T}(EmptyNode{T}())
LinkedList() = LinkedList{Any}()

Base.isempty(ll::LinkedList) = ll.head isa EmptyNode
function lastnode(ll::LinkedList)
    if isempty(ll) throw(BoundsError()) end
    nd = ll.head
    while !(nd.next isa EmptyNode)
        nd = nd.next
    end
    return nd
end

function Base.push!(ll::LinkedList{T}, x::T) where T
    nd = Node{T}(x)
    if isempty(ll)
        ll.head = nd
    else
        tail = lastnode(ll)
        tail.next = nd
    end
    return ll
end
function Base.pop!(ll::LinkedList{T}) where T
    if isempty(ll)
        throw(ArgumentError("list must be non-empty"))
    elseif ll.head.next isa EmptyNode
        nd = ll.head
        ll.head = EmptyNode{T}()
    else
        nx = ll.head
        while !isa(nx.next.next, EmptyNode)
            nx = nx.next
        end
        nd = nx.next
        nx.next = EmptyNode{T}()
    end
    return nd.data
end

lst = LinkedList{Int}()
push!(lst, 1)
push!(lst, 2)
push!(lst, 3)
pop!(lst) # 3
pop!(lst) # 2
pop!(lst) # 1

define a data structure for a singly-linked list element. This element contains a data member for storing a numeric value and a mutable link to the next element in the list.


Translation of: F#
const width = height = 1000.0
const trunklength = 400.0
const scalefactor = 0.6
const startingangle = 1.5 * pi
const deltaangle = 0.2 * pi

function tree(fh, x, y, len, theta)
   if len >= 1.0
       x2 = x + len * cos(theta)
       y2 = y + len * sin(theta)
       write(fh, "<line x1='$x' y1='$y' x2='$x2' y2='$y2' style='stroke:rgb(0,0,0);stroke-width:1'/>\n")
       tree(fh, x2, y2, len * scalefactor, theta + deltaangle)
       tree(fh, x2, y2, len * scalefactor, theta - deltaangle)
    end
end

outsvg = open("tree.svg", "w")
write(outsvg,
    """<?xml version='1.0' encoding='utf-8' standalone='no'?>
    <!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 1.1//EN'
    'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'>
    <svg width='100%%' height='100%%' version='1.1'
    xmlns='http://www.w3.org/2000/svg'>\n""")

tree(outsvg, 0.5 * width, height, trunklength, startingangle)

write(outsvg, "</svg>\n") # view file tree.svg in browser

generate and draw a fractal tree by first drawing the trunk, then splitting the trunk at the end by a certain angle to form two branches, and repeating this process until a desired level of branching is reached.


using Primes

""" Return the factors of n, including 1, n """
function factors(n::T)::Vector{T} where T <: Integer
  sort(vec(map(prod, Iterators.product((p.^(0:m) for (p, m) in eachfactor(n))...))))
end

const examples = [28, 45, 53, 64, 6435789435768]

for n in examples
    @time println("The factors of $n are: $(factors(n))")
end

compute the factors of a given positive integer, excluding zero and negative numbers. The factors are the positive integers that can divide the input number to yield a positive integer. For prime numbers, the factors are 1 and the number itself.


Translation of: Python
txt = """Given\$a\$txt\$file\$of\$many\$lines,\$where\$fields\$within\$a\$line\$
are\$delineated\$by\$a\$single\$'dollar'\$character,\$write\$a\$program
that\$aligns\$each\$column\$of\$fields\$by\$ensuring\$that\$words\$in\$each\$
column\$are\$separated\$by\$at\$least\$one\$space.
Further,\$allow\$for\$each\$word\$in\$a\$column\$to\$be\$either\$left\$
justified,\$right\$justified,\$or\$center\$justified\$within\$its\$column."""

# left/right/center justification of strings:
ljust(s, width) = s * " "^max(0, width - length(s))
rjust(s, width) = " "^max(0, width - length(s)) * s
function center(s, width)
  pad = width - length(s)
  if pad <= 0
    return s
  else
    pad2 = div(pad, 2)
    return " "^pad2 * s * " "^(pad - pad2)
  end
end

parts = [split(rstrip(line, '$'), '$') for line in split(txt, '\n')]

max_widths = zeros(Int, maximum(length, parts))
for line in parts
  for (i, word) in enumerate(line)
    max_widths[i] = max(max_widths[i], length(word))
  end
end
max_widths += 1 # separate cols by at least one space

for (label, justify) in (("Left", ljust), ("Right",rjust), ("Center",center))
  println(label, " column-aligned output:")
  for line in parts
    for (j, word) in enumerate(line)
      print(justify(word, max_widths[j]))
    end
    println()
  end
  println("-"^sum(max_widths))
end

The code reads a text file with lines separated by a dollar character. It aligns each column of fields by ensuring at least one space between words in each column. It also allows each word in a column to be left, right, or center justified. The minimum space between columns is computed from the text, not hard-coded. Trailing dollar characters or consecutive spaces at the end of lines do not affect the alignment. The output is suitable for viewing in a mono-spaced font on a plain text editor or basic terminal.


ASCII Art[edit]
Translation of: Python
Works with: Julia version 0.6
_pr(t::Dict, x::Int, y::Int, z::Int) = join((rstrip(join(t[(n, m)] for n in range(0, 3+x+z))) for m in reverse(range(0, 3+y+z))), "\n")

function cuboid(x::Int, y::Int, z::Int)
    t = Dict((n, m) => " " for n in range(0, 3 + x + z), m in range(0, 3 + y + z))
    xrow = vcat("+", collect("$(i % 10)" for i in range(0, x)), "+")
    for (i, ch) in enumerate(xrow) t[(i, 0)] = t[(i, 1+y)] = t[(1+z+i, 2+y+z)] = ch end
    yrow = vcat("+", collect("$(j % 10)" for j in range(0, y)), "+")
    for (j, ch) in enumerate(yrow) t[(0, j)] = t[(x+1, j)] = t[(2+x+z, 1+z+j)] = ch end
    zdep = vcat("+", collect("$(k % 10)" for k in range(0, y)), "+")
    for (k, ch) in enumerate(xrow) t[(k, 1+y+k)] = t[(1+x+k, 1+y+k)] = t[(1+x+k, k)] = ch end

    return _pr(t, x, y, z)
end

for (x, y, z) in [(2, 3, 4), (3, 4, 2), (4, 2, 3), (5, 5, 6)]
    println("\nCUBOID($x, $y, $z)\n")
    println(cuboid(x, y, z))
end

generate a graphical or ASCII art representation of a cuboid with dimensions 2x3x4, ensuring three faces are visible, and allowing for either static or rotational projection.


using LDAPClient

conn = LDAPClient.LDAPConnection("ldap://localhost:10389")
LDAPClient.simple_bind(conn, "user", "password")
LDAPClient.unbind(conn)

establish a connection to an Active Directory or Lightweight Directory Access Protocol server.


# Julia 1.0
function rot13(c::Char)
    shft = islowercase(c) ? 'a' : 'A'
    isletter(c) ? c = shft + (c - shft + 13) % 26 : c
end

rot13(str::AbstractString) = map(rot13, str)

implement a rot-13 function that replaces every letter of the ASCII alphabet with the letter which is "rotated" 13 characters around the 26 letter alphabet. The function should work on both upper and lower case letters, preserve case, and pass all non-alphabetic characters without alteration. Optionally, the function can be wrapped in a utility program that performs rot-13 encoding line-by-line for every line of input in each file listed on its command line or acts as a filter on its standard input.


Works with: Julia version 0.6
lst = Pair[Pair("gold", "shiny"),
           Pair("neon", "inert"),
           Pair("sulphur", "yellow"),
           Pair("iron", "magnetic"),
           Pair("zebra", "striped"),
           Pair("star", "brilliant"),
           Pair("apple", "tasty"),
           Pair("ruby", "red"),
           Pair("dice", "random"),
           Pair("coffee", "stimulating"),
           Pair("book", "interesting")]

println("The original list: \n - ", join(lst, "\n - "))
sort!(lst; by=first)
println("\nThe list, sorted by name: \n - ", join(lst, "\n - "))
sort!(lst; by=last)
println("\nThe list, sorted by value: \n - ", join(lst, "\n - "))

sort an array of composite structures, specifically name-value pairs, by the key name using a custom comparator.


for i in 1:5
    for j in 1:i
        print("*")
    end
    println()
end

demonstrate how to use nested for loops to print a specific pattern. The number of iterations in the inner loop is controlled by the outer loop, resulting in a pattern of increasing asterisks.


Works with: Julia version 0.6

dict = Dict('a' => 97, 'b' => 98) # list keys/values
# Dict{Char,Int64} with 2 entries:
#   'b' => 98
#   'a' => 97

dict = Dict(c => Int(c) for c = 'a':'d') # dict comprehension
# Dict{Char,Int64} with 4 entries:
#   'b' => 98
#   'a' => 97
#   'd' => 100
#   'c' => 99

dict['é'] = 233; dict # add an element
# Dict{Char,Int64} with 3 entries:
#   'b' => 98
#   'a' => 97
#   'é' => 233

emptydict = Dict() # create an empty dict
# Dict{Any,Any} with 0 entries

dict["a"] = 1 # type mismatch
# ERROR: MethodError: Cannot `convert` an object of type String to an object of type Char

typeof(dict) # type is infered correctly
# Dict{Char,Int64}

"Creates an associative array, also known as a dictionary, map, or hash, associating characters with their code points. This is achieved through dictionary comprehension, creating an empty dictionary and filling it, and using the specific syntax for typed dictionaries."


using Printf

function getlgc(r::Integer, a::Integer, c::Integer, m::Integer, sh::Integer)
    state = r
    return function lgcrand()
        state = mod(a * state + c, m)
        return state >> sh
    end
end

seed, nrep = 0, 10
bsdrand = getlgc(seed, 1103515245, 12345, 2 ^ 31, 0)

println("The first $nrep results for a BSD rand seeded with $seed:")
for _ in 1:nrep
    @printf("%14d\n", bsdrand())
end

msrand = getlgc(seed, 214013, 2531011, 2 ^ 31, 16)

println("\nThe first $nrep results for a M\$ rand seeded with $seed:")
for _ in 1:nrep
    @printf("%14d\n", msrand())
end

The code replicates two historic random number generators: the rand() function from BSD libc and the rand() function from the Microsoft C Runtime (MSCVRT.DLL). It uses a linear congruential generator formula to generate a sequence of random numbers, given a seed. The generated sequence matches the original generator when starting from the same seed. The code also includes a function, getlgc, which creates a linear congruential generator as a closure.


Works with: Julia version 0.6

function Base.insert!(ll::LinkedList{T}, index::Integer, item::T) where T
    if index == 1
        if isempty(ll)
            return push!(ll, item)
        else
            ll.head = Node{T}(item, ll.head)
        end
    else
        nd = ll.head
        while index > 2
            if nd.next isa EmptyNode
                throw(BoundsError())
            else
                nd = nd.next
                index -= 1
            end
        end
        nd.next = Node{T}(item, nd.next)
    end
    return ll
end

define a method to insert an element 'C' into a singly-linked list after a specified element 'A'. This is implemented in the context of a list comprised of elements A->B. The functionality also references the LinkedList implementation found in Singly-linked_list/Element_definition#Julia.


Works with: Julia version 0.6

halve(x::Integer) = x >> one(x)
double(x::Integer) = Int8(2) * x
even(x::Integer) = x & 1 != 1

function ethmult(a::Integer, b::Integer)
    r = 0
    while a > 0
        r += b * !even(a)
        a = halve(a)
        b = double(b)
    end
    return r
end

@show ethmult(17, 34)

function ethmult2(a::Integer, b::Integer)
    A = [a]
    B = [b]
    while A[end] > 1
        push!(A, halve(A[end]))
        push!(B, double(B[end]))
    end
    return sum(B[map(!even, A)])
end

@show ethmult2(17, 34)

The code defines three helper functions to halve, double, and check if an integer is even. These functions are then used to implement the Ethiopian multiplication method. The Ethiopian multiplication function takes two integers as input and uses the helper functions to repeatedly halve the first number and double the second number. It discards rows where the halved number is even and sums the remaining doubled numbers to produce the multiplication result.


function solve24(nums)
    length(nums) != 4 && error("Input must be a 4-element Array")
    syms = [+,-,*,/]
    for x in syms, y in syms, z in syms
        for i = 1:24
            a,b,c,d = nthperm(nums,i)
            if round(x(y(a,b),z(c,d)),5) == 24
                return "($a$y$b)$x($c$z$d)"
            elseif round(x(a,y(b,z(c,d))),5) == 24
                return "$a$x($b$y($c$z$d))"
            elseif round(x(y(z(c,d),b),a),5) == 24
                return "(($c$z$d)$y$b)$x$a"
            elseif round(x(y(b,z(c,d)),a),5) == 24
                return "($b$y($c$z$d))$x$a"
            end
        end
    end
    return "0"
end

The code takes four digits as input, either from the user or randomly generated, and computes arithmetic expressions according to the rules of the 24 game. It also displays examples of the solutions it generates. For Julia version 0.5 and higher, it requires the Combinatorics package for combinatorial functions like `nthperm`.


Works with: Julia version 0.6

help?> factorial
search: factorial Factorization factorize

  factorial(n)

  Factorial of n. If n is an Integer, the factorial is computed as an integer (promoted to at
  least 64 bits). Note that this may overflow if n is not small, but you can use factorial(big(n))
  to compute the result exactly in arbitrary precision. If n is not an Integer, factorial(n) is
  equivalent to gamma(n+1).

  julia> factorial(6)
  720

  julia> factorial(21)
  ERROR: OverflowError()
  [...]

  julia> factorial(21.0)
  5.109094217170944e19

  julia> factorial(big(21))
  51090942171709440000

function fact(n::Integer)
    n < 0 && return zero(n)
    f = one(n)
    for i in 2:n
        f *= i
    end
    return f
end

for i in 10:20
	println("$i -> ", fact(i))
end

The code is a function that calculates the factorial of a given number. It can be implemented either iteratively or recursively. The function may optionally handle errors for negative input values.


function cowsbulls()
	print("Welcome to Cows & Bulls! I've picked a number with unique digits between 1 and 9, go ahead and type your guess.\n
		You get one bull for every right number in the right position.\n
		You get one cow for every right number, but in the wrong position.\n
		Enter 'n' to pick a new number and 'q' to quit.\n>")
	function new_number()
		s = [1:9]
		n = ""
		for i = 9:-1:6
			n *= string(delete!(s,rand(1:i)))
		end
		return n
	end
	answer = new_number()
	while true
		input = chomp(readline(STDIN))
		input == "q" && break
		if input == "n"
			answer = new_number()
			print("\nI've picked a new number, go ahead and guess\n>")
			continue
		end
		!ismatch(r"^[1-9]{4}$",input) && (print("Invalid guess: Please enter a 4-digit number\n>"); continue)
		if input == answer
			print("\nYou're right! Good guessing!\nEnter 'n' for a new number or 'q' to quit\n>")
		else
			bulls = sum(answer.data .== input.data)
			cows = sum([answer[x] != input[x] && contains(input.data,answer[x]) for x = 1:4])
			print("\nNot quite! Your guess is worth:\n$bulls Bulls\n$cows Cows\nPlease guess again\n\n>")
		end
	end
end

function bullsandcows ()
    bulls = cows = turns = 0
    result = (s = [] ; while length(unique(s))<4 push!(s,rand('1':'9')) end; unique(s))
    println("A game of bulls and cows!")
    while (bulls != 4)
      print("Your guess? ")
      guess = collect(chomp(readline(STDIN)))
      if ! (length(unique(guess)) == length(guess) == 4 && all(isdigit,guess))
         println("please, enter four distincts digits")
         continue
      end
      bulls = sum(map(==, guess, result))
      cows = length(intersect(guess,result)) - bulls
      println("$bulls bulls and $cows cows!") ; turns += 1
    end
    println("You win! You succeeded in $turns guesses.")
  end

generate a four-digit random number without duplication, take player's guesses, validate the guesses, calculate and print the score based on the matching digits and their positions. The game ends when the player's guess matches the generated number.


generates a collection of 1000 normally distributed pseudo-random numbers with a mean of 1.0 and a standard deviation of 0.5, using Julia's standard library function randn.


implement a function to calculate the dot product of two vectors. The vectors can be of arbitrary length, but must be the same length for the dot product operation. The function multiplies corresponding elements from each vector and sums the results. The functionality is similar to built-in linear algebra functions in Julia.


stream = IOBuffer("1\n2\n3\n4\n\n6")

while !eof(stream)
    line = readline(stream)
    println(line)
end

The code reads data from a text stream either word-by-word or line-by-line until there is no more data. It creates a text stream, reads and prints each line on the screen. The lines end with a newline except the last one. When the end of the stream is reached, an empty string is returned.


using LightXML

# Modified from the documentation for LightXML.jl. The underlying library requires an encoding string be printed.

# create an empty XML document
xdoc = XMLDocument()

# create & attach a root node
xroot = create_root(xdoc, "root")

# create the first child
xs1 = new_child(xroot, "element")

# add the inner content
add_text(xs1, "some text here")

println(xdoc)

Create a simple DOM and serialize it into the specified XML format.


ts = time()

println("The system time is (in ISO 8601 format):")
println(strftime("    %F %T %Z", ts))

the system time in a specified unit. This can be used for debugging, network information, random number seeds, or program performance. The time is retrieved either by a system command or a built-in language function. It is related to the task of date formatting and retrieving system time.


Works with: Julia version 0.6
using Base.Test

function appendchecksum(chars::AbstractString)
    if !all(isalnum, chars) throw(ArgumentError("invalid SEDOL number '$chars'")) end
    weights = [1, 3, 1, 7, 3, 9, 1]

    s = 0
    for (w, c) in zip(weights, chars)
        s += w * parse(Int, c, 36)
    end
    return string(chars, (10 - s % 10) % 10)
end

tests = ["710889", "B0YBKJ", "406566", "B0YBLH", "228276", "B0YBKL", "557910", "B0YBKR", "585284", "B0YBKT", "B00030"]
csums = ["7108899", "B0YBKJ7", "4065663", "B0YBLH2", "2282765", "B0YBKL9", "5579107", "B0YBKR5", "5852842", "B0YBKT7", "B000300"]

@testset "Checksums" begin
    for (t, c) in zip(tests, csums)
        @test appendchecksum(t) == c
    end
end

The code takes a list of 6-digit SEDOLs as input, calculates the checksum digit for each SEDOL, and appends it to the end of the respective SEDOL. It also validates the input to ensure it contains only valid characters for a SEDOL string.


ASCII Text[edit]
Translation of: C
function draw_sphere(r, k, ambient, light)
    shades = ('.', ':', '!', '*', 'o', 'e', '&', '#', '%', '@')
    for i in floor(Int, -r):ceil(Int, r)
        x = i + 0.5
        line = IOBuffer()
        for j in floor(Int, -2r):ceil(2r)
            y = j / 2 + 0.5
            if x ^ 2 + y ^ 2 ≤ r ^ 2
                v = normalize([x, y, sqrt(r ^ 2 - x ^ 2 - y ^ 2)])
                b = dot(light, v) ^ k + ambient
                intensity = ceil(Int, (1 - b) * (length(shades) - 1))
                if intensity < 1
                    intensity = 1 end
                if intensity > length(shades)
                    intensity = length(shades) end
                print(shades[intensity])
            else
                print(' ')
            end
        end
        println()
    end
end

light = normalize([30, 30, -50])
draw_sphere(20, 4, 0.1, light)
draw_sphere(10, 2, 0.4, light)

Graphical[edit]
# run from REPL

using Makie

φ = 0:π/100:2π

θ = 0:π/200:π

x = [cos(θ) * sin(φ) for θ in θ, φ in φ]
y = [sin(θ)*sin(φ) for θ in θ, φ in φ]
z = [cos(φ) for θ in θ, φ in φ]

surface(x, y, z, backgroundcolor = :black, show_axis = false)

"Generates a graphical or ASCII art representation of a sphere, with either static or rotational projection."


using Printf

function ordinal(n::Integer)
    n < 0 && throw(DomainError())
    suffixes = ("st", "nd", "rd")
    u = n % 10
    t = n ÷ 10 % 10
    if u > 3 || u == 0 || t == 1
        suf = "th"
    else
        suf = suffixes[u]
    end
    return string(n, suf)
end

println("Tests of ordinal formatting of integers.")
for (i, n) in enumerate(0:25)
    (i - 1) % 10 == 0 && println()
    @printf("%7s", ordinal(n))
end

println()
for (i, n) in enumerate(250:265)
    (i - 1) % 10 == 0 && println()
    @printf("%7s", ordinal(n))
end

println()
for (i, n) in enumerate(1000:1025)
    (i - 1) % 10 == 0 && println()
    @printf("%7s", ordinal(n))
end

Nth(x::Integer) = if x % 100 ∈ [11, 12, 13] "th" else ["th", "st", "nd", "rd", "th"][min(x % 10 + 1, 5)] end
NthA(x::Integer) = "$(x)'$(Nth(x)) "
[0:25..., 250:265..., 1000:1025...] .|> NthA .|> print;

Code summarization: The given code defines a function that accepts an integer greater than or equal to zero and returns a string representation of the number with an ordinal suffix. The function is used to display the output for specific ranges of integer inputs: 0-25, 250-265, and 1000-1025. The use of apostrophes in the ordinal suffix is optional.


Works with: Julia version 1.0
stripChar = (s, r) -> replace(s, Regex("[$r]") => "")

"Function to remove specific characters from a given string"


function fizzbuzz(triggers :: Vector{Tuple{Int, ASCIIString}}, upper :: Int)
    for i = 1 : upper
        triggered = false

        for trigger in triggers
            if i % trigger[1] == 0
                triggered = true
                print(trigger[2])
            end
        end

        !triggered && print(i)
        println()
    end
end

print("Enter upper limit:\n> ")
upper = parse(Int, readline())

triggers = Tuple{Int, ASCIIString}[]
print("Enter factor/string pairs (space delimited; ^D when done):\n> ")
while (r = readline()) != ""
    input = split(r)
    push!(triggers, (parse(Int, input[1]), input[2]))
    print("> ")
end

println("EOF\n")
fizzbuzz(triggers, upper)

The code takes a maximum number and a list of factor-word pairs as input from the user. It then prints numbers from 1 to the maximum number, replacing multiples of the factors with the corresponding words. If a number is a multiple of more than one factor, it prints all associated words in the order of the factors. For instance, for the number 15 and factors 3 ("Fizz") and 5 ("Buzz"), it prints "FizzBuzz". The user is assumed to provide valid input.


Creates a string variable with a specific text value, prepends another string literal to it, and displays the content of the variable. If possible, the operation is performed without referring to the variable twice in one expression.


Works with: Julia version 0.6

using Luxor
function dragon(turtle::Turtle, level=4, size=200, direction=45)
    if level != 0
        Turn(turtle, -direction)
        dragon(turtle, level-1, size/sqrt(2), 45)
        Turn(turtle, direction*2)
        dragon(turtle, level-1, size/sqrt(2), -45)
        Turn(turtle, -direction)
    else
        Forward(turtle, size)
    end
end

Drawing(900, 500, "./Dragon.png")
t = Turtle(300, 300, true, 0, (0., 0.0, 0.0));
dragon(t, 10,400)
finish()
preview()

The code generates a dragon curve fractal, either displaying it directly or writing it to an image file. It uses various algorithms including recursive, successive approximation, iterative, and Lindenmayer system of expansions. It also includes functionalities to determine the curl direction, calculate absolute direction, and X,Y coordinates of a point, and to test if a given point or segment is on the curve. The code uses the Luxor library for its operations.


Works with: Julia version 0.6
function guess()
    number = dec(rand(1:10))
    print("Guess my number! ")
    while readline() != number
        print("Nope, try again... ")
    end
    println("Well guessed!")
end

guess()

"Implement a number guessing game where the computer selects a number between 1 and 10. The player is repeatedly prompted to guess the number until the correct number is guessed, upon which a 'Well guessed!' message is displayed and the program terminates. A conditional loop is used to facilitate repeated guessing."


Works with: Julia version 0.6
@show collect('a':'z')
@show join('a':'z')

generate a sequence of all lower case ASCII characters from a to z. This is done in a reliable coding style suitable for large programs, using strong typing if available. The code avoids manual enumeration of characters to prevent bugs. It also demonstrates how to access a similar sequence from the standard library if it exists.


Works with: Julia version 1.0
using Printf

for n in (0, 5, 50, 9000)
    @printf("%6i → %s\n", n, string(n, base=2))
end

# with pad
println("\nwith pad")
for n in (0, 5, 50, 9000)
    @printf("%6i → %s\n", n, string(n, base=2, pad=20))
end

generate a sequence of binary digits for a given non-negative integer. The output displays only the binary digits of each number, followed by a newline, without any whitespace, radix, sign markers, or leading zeros. The conversion can be achieved using built-in radix functions or a user-defined function.


Translation of: Python
using CSV, DataFrames, Statistics

# load data from csv files
#df_patients = CSV.read("patients.csv", DataFrame)
#df_visits = CSV.read("visits.csv", DataFrame)

# create DataFrames from text that is hard coded, so use IOBuffer(String) as input
str_patients = IOBuffer("""PATIENT_ID,LASTNAME
1001,Hopper
4004,Wirth
3003,Kemeny
2002,Gosling
5005,Kurtz
""")
df_patients = CSV.read(str_patients, DataFrame)
str_visits = IOBuffer("""PATIENT_ID,VISIT_DATE,SCORE
2002,2020-09-10,6.8
1001,2020-09-17,5.5
4004,2020-09-24,8.4
2002,2020-10-08,
1001,,6.6
3003,2020-11-12,
4004,2020-11-05,7.0
1001,2020-11-19,5.3
""")
df_visits = CSV.read(str_visits, DataFrame)

# merge on PATIENT_ID, using an :outer join or we lose Kurtz, who has no data, sort by ID
df_merge = sort(join(df_patients, df_visits, on="PATIENT_ID", kind=:outer), (:PATIENT_ID,))

fnonmissing(a, f) = isempty(a) ? [] : isempty(skipmissing(a)) ? a[1] : f(skipmissing(a))

# group by patient id / last name and then aggregate to get latest visit and mean score
df_result = by(df_merge, [:PATIENT_ID, :LASTNAME]) do df
    DataFrame(LATEST_VISIT = fnonmissing(df[:VISIT_DATE], maximum),
              SUM_SCORE = fnonmissing(df[:SCORE], sum),
              MEAN_SCORE = fnonmissing(df[:SCORE], mean))
end
println(df_result)

"Merge and aggregate two provided .csv datasets into a new dataset, grouping by patient id and last name, calculating the maximum visit date, and the sum and average of the scores per patient. The resulting dataset can be displayed on screen, stored in memory, or written to a file."


using Gtk, Graphics

const can = @GtkCanvas()
const win = GtkWindow(can, "Draw a Pixel", 320, 240)

draw(can) do widget
    ctx = getgc(can)
    set_source_rgb(ctx, 255, 0, 0)
    move_to(ctx, 100, 100)
    line_to(ctx, 101,100)
    stroke(ctx)
end

show(can)
const cond = Condition()
endit(w) = notify(cond)
signal_connect(endit, win, :destroy)
wait(cond)

"Creates a 320x240 window and draws a single red pixel at position (100, 100)."


Works with: Julia version 0.6
function readconf(file)
    vars = Dict()
    for line in eachline(file)
        line = strip(line)
        if !isempty(line) && !startswith(line, '#') && !startswith(line, ';')
            fspace  = searchindex(line, " ")
            if fspace == 0
                vars[Symbol(lowercase(line))] = true
            else
                vname, line = Symbol(lowercase(line[1:fspace-1])), line[fspace+1:end]
                value = ',' ∈ line ? strip.(split(line, ',')) : line
                vars[vname] = value
            end
        end
    end
    for (vname, value) in vars
        eval(:($vname = $value))
    end
    return vars
end

readconf("test.conf")

@show fullname favouritefruit needspeeling otherfamily

read a configuration file and set variables based on the contents. It ignores lines starting with a hash or semicolon and blank lines. It sets variables 'fullname', 'favouritefruit', 'needspeeling', and 'seedsremoved' based on the file entries. It also stores multiple parameters from the 'otherfamily' entry into an array.


Works with: Julia version 0.6
haversine(lat1, lon1, lat2, lon2) =
    2 * 6372.8 * asin(sqrt(sind((lat2 - lat1) / 2) ^ 2 +
    cosd(lat1) * cosd(lat2) * sind((lon2 - lon1) / 2) ^ 2))

@show haversine(36.12, -86.67, 33.94, -118.4)

Implement a function to calculate the great-circle distance between two points on a sphere using the Haversine formula. The function takes the coordinates of Nashville International Airport (BNA) and Los Angeles International Airport (LAX) as input and returns the distance between them. The calculation uses the recommended earth radius of 6372.8 km or 6371 km, depending on the level of precision required.


readurl(url) = open(readlines, download(url))

readurl("http://rosettacode.org/index.html")

Print the content of a specified URL to the console using HTTP request.


luhntest(x::Integer) = (sum(digits(x)[1:2:end]) + sum(map(x -> sum(digits(x)), 2 * digits(x)[2:2:end]))) % 10 == 0

function luhntest(x::Integer)
    d = reverse(digits(x))
    s = sum(d[1:2:end])
    s += sum(sum.(digits.(2d[2:2:end])))
    return s % 10 == 0
end

for card in [49927398716, 49927398717, 1234567812345678, 1234567812345670]
    println(luhntest(card) ? "PASS " : "FAIL ", card)
end

"Implement a function to validate credit card numbers using the Luhn algorithm. The function takes a number as input, reverses the digits, calculates two partial sums s1 and s2 by summing odd digits and summing the digits of twice the even digits respectively, and checks if the total sum ends in zero. The function is used to validate a set of given numbers."


Works with: Julia version 0.6

using Memoize
@memoize josephus(n::Integer, k::Integer, m::Integer=1) = n == m ? collect(0:m .- 1) : mod.(josephus(n - 1, k, m) + k, n)

@show josephus(41, 3)
@show josephus(41, 3, 5)

The code determines the final survivor in the Josephus problem, given a number of prisoners and a step count for execution. It also provides a way to calculate which prisoner is at any given position on the killing sequence. The prisoners can be numbered either from 0 to n-1 or from 1 to n. The code uses both recursive and iterative methods. The complexity of the solution is O(kn) for the complete killing sequence and O(m) for the m-th prisoner to die.


Works with: Julia version 1.0
@show "ha" ^ 5

# The ^ operator is really just call to the `repeat` function
@show repeat("ha", 5)

The code takes a string or a character as input and repeats it a specified number of times. For example, if the input is "ha" and 5, the output will be "hahahahaha". Similarly, if the input is "*" and 5, the output will be "*****".


Translation of: Perl

s = "I am a string"
if ismatch(r"string$", s)
    println("'$s' ends with 'string'")
end

s = "I am a string"
s = replace(s, r" (a|an) ", " another ")

implement Perl-compatible regular expressions in Julia using the built-in PCRE library. They test for a match in a string and perform substitutions in part of a string using a regular expression.


function arithmetic (a = parse(Int, readline()), b = parse(Int, readline()))
  for op in  [+,-,*,div,rem]
    println("a $op b = $(op(a,b))")
  end
end

take two integers as input from the user and display their sum, difference, product, integer quotient, remainder, and exponentiation. The code also indicates the rounding direction for the quotient and the sign of the remainder. It does not include error handling. A bonus feature is the inclusion of the `divmod` operator example.


matchall(r::Regex, s::String[, overlap::Bool=false]) -> Vector{String}

   Return a vector of the matching substrings from eachmatch.

ts = ["the three truths", "ababababab"]
tsub = ["th", "abab"]

println("Test of non-overlapping substring counts.")
for i in 1:length(ts)
    print(ts[i], " (", tsub[i], ") => ")
    println(length(matchall(Regex(tsub[i]), ts[i])))
end
println()
println("Test of overlapping substring counts.")
for i in 1:length(ts)
    print(ts[i], " (", tsub[i], ") => ")
    println(length(matchall(Regex(tsub[i]), ts[i], true)))
end

The code defines a function that counts the number of non-overlapping occurrences of a specific substring within a given string. It takes two arguments: the main string and the substring to search for. The function returns an integer representing the count of non-overlapping occurrences. The matching process is done either from left-to-right or right-to-left to yield the maximum number of matches.


Translation of: R
function solve(n::Integer, from::Integer, to::Integer, via::Integer)
  if n == 1
    println("Move disk from $from to $to")
  else
    solve(n - 1, from, via, to)
    solve(1, from, to, via)
    solve(n - 1, via, to, from)
  end
end

solve(4, 1, 2, 3)

"Implement a recursive solution to solve the Towers of Hanoi problem."


Works with: Julia version 1.2

@show binomial(5, 3)

function binom(n::Integer, k::Integer)
    n ≥ k || return 0 # short circuit base cases
    (n == 1 || k == 0) && return 1

    n * binom(n - 1, k - 1) ÷ k
end

@show binom(5, 3)

The code calculates binomial coefficients, specifically it is able to output the binomial coefficient of 5 choose 3, which is 10. It uses the formula for binomial coefficients and can handle tasks related to combinations, permutations, combinations with repetitions, and permutations with repetitions. It also includes a built-in recursive version.


Translation of: Java
# v0.6

function shellsort!(a::Array{Int})::Array{Int}
    incr = div(length(a), 2)
    while incr > 0
        for i in incr+1:length(a)
            j = i
            tmp = a[i]
            while j > incr && a[j - incr] > tmp
                a[j] = a[j-incr]
                j -= incr
            end
            a[j] = tmp
        end
        if incr == 2
            incr = 1
        else
            incr = floor(Int, incr * 5.0 / 11)
        end
    end
    return a
end

x = rand(1:10, 10)
@show x shellsort!(x)
@assert issorted(x)

implement the Shell sort algorithm to sort an array of elements. This algorithm, invented by Donald Shell, uses a diminishing increment sort and interleaved insertion sorts based on an increment sequence. The increment size reduces after each pass until it reaches 1, turning the sort into a basic insertion sort. The data is almost sorted at this point, providing the best case for insertion sort. The increment sequence can vary but should always end in 1. Sequences with a geometric increment ratio of about 2.2 have been found to work well.


using Color, Images, FixedPointNumbers

const M_RGB_Y = reshape(Color.M_RGB_XYZ[2,:], 3)

function rgb2gray(img::Image)
    g = red(img)*M_RGB_Y[1] + green(img)*M_RGB_Y[2] + blue(img)*M_RGB_Y[3]
    g = clamp(g, 0.0, 1.0)
    return grayim(g)
end

function gray2rgb(img::Image)
    colorspace(img) == "Gray" || return img
    g = map((x)->RGB{Ufixed8}(x, x, x), img.data)
    return Image(g, spatialorder=spatialorder(img))
end

ima = imread("grayscale_image_color.png")
imb = rgb2gray(ima)
imc = gray2rgb(imb)
imwrite(imc, "grayscale_image_rc.png")

using Color, Images, FixedPointNumbers

ima = imread("grayscale_image_color.png")
imb = convert(Image{Gray{Ufixed8}}, ima)
imwrite(imb, "grayscale_image_julia.png")

The code extends the data storage type to support grayscale images. It defines two operations: one to convert a color image to a grayscale image and another for the reverse conversion. The conversion uses the CIE recommended formula for luminance calculation. The code also ensures that rounding errors from floating-point arithmetic do not cause run-time issues or distorted results. The code may also reverse compansion before applying the CIE transformation to extract luminance from RGB.


Library: Julia/Tk
using Tk

const frameinterval = 0.12 # partial seconds between change on screen display

function windowanim(stepinterval::Float64)
    wind = Window("Animation", 300, 100)
    frm = Frame(wind)
    hello = "Hello World!                                           "
    but = Button(frm, width=30, text=hello)
    rightward = true
    callback(s) = (rightward = !rightward)
    bind(but, "command", callback)
    pack(frm, expand=true, fill = "both")
    pack(but, expand=true, fill = "both")
    permut = [hello[i:end] * hello[1:i-1] for i in length(hello)+1:-1:2]
    ppos = 1
    pmod = length(permut)
    while true
        but[:text] = permut[ppos]
        sleep(stepinterval)
        if rightward
            ppos += 1
            if ppos > pmod
                ppos = 1
            end
        else
            ppos -= 1
            if ppos < 1
                ppos = pmod
            end
        end
    end
end

windowanim(frameinterval)

Library: Julia/Gtk
using Gtk.ShortNames

const frameinterval = 0.12 # partial seconds between change on screen display

function textanimation(stepinterval::Float64)
    hello = "Hello World!                        "
    win = Window("Animation", 210, 40) |> (Frame() |> (but = Button("Switch Directions")))
    rightward = true
    switchdirections(s) = (rightward = !rightward)
    signal_connect(switchdirections, but, "clicked")
    permut = [hello[i:end] * hello[1:i-1] for i in length(hello)+1:-1:2]
    ppos = 1
    pmod = length(permut)
    nobreak = true
    endit(w) = (nobreak = false)
    signal_connect(endit, win, :destroy)
    showall(win)
    while nobreak
        setproperty!(but, :label, permut[ppos])
        sleep(stepinterval)
        if rightward
            ppos += 1
            if(ppos > pmod)
                ppos = 1
            end
        else
            ppos -= 1
            if(ppos < 1)
                ppos = pmod
            end
        end
    end
end

textanimation(frameinterval)

Create a GUI animation where the string "Hello World! " appears to rotate right by periodically moving the last letter to the front. The direction of rotation reverses when the user clicks on the text.


julia> i = 0
0

julia> while true
           println(i)
           i += 1
           i % 6 == 0 && break
       end
0
1
2
3
4
5

julia> @eval macro $(:do)(block, when::Symbol, condition)
           when ≠ :when && error("@do expected `when` got `$s`")
           quote
               let
                   $block
                   while $condition
                       $block
                   end
               end
           end |> esc
       end
@do (macro with 1 method)

julia> i = 0
0

julia> @do begin
           @show i
           i += 1
       end when i % 6 ≠ 0
i = 0
i = 1
i = 2
i = 3
i = 4
i = 5

julia> macro do_while(condition, block)
           quote
               let
                   $block
                   while $condition
                       $block
                   end
               end
           end |> esc
       end
@do_while (macro with 1 method)

julia> i = 0
0

julia> @do_while i % 6 ≠ 0 begin
           @show i
           i += 1
       end
i = 0
i = 1
i = 2
i = 3
i = 4
i = 5

implement a do-while loop in Julia that starts with a value at 0 and continues to loop while the value mod 6 is not equal to 0. In each iteration, the value is incremented by 1 and then printed. The loop is executed at least once. The do-while behavior is mimicked using a macro that resembles the classic C style do-while, using 'when' instead of 'while' due to keyword restrictions in Julia.


Byte Length[edit]
sizeof("møøse") # 7
sizeof("𝔘𝔫𝔦𝔠𝔬𝔡𝔢") # 28
sizeof("J̲o̲s̲é̲") # 13
Character Length[edit]
length("møøse") # 5
length("𝔘𝔫𝔦𝔠𝔬𝔡𝔢") # 7
length("J̲o̲s̲é̲") # 8
Grapheme Length[edit]
import Unicode
length(Unicode.graphemes("møøse")) # 5
length(Unicode.graphemes("𝔘𝔫𝔦𝔠𝔬𝔡𝔢")) # 7
length(Unicode.graphemes("J̲o̲s̲é̲")) # 4

determine the character and byte length of a string, taking into account different encodings like UTF-8 and UTF-16. It handles non-BMP code points correctly, providing actual character counts in code points, not in code unit counts. The code also provides the string length in graphemes if possible. In Julia, the byte length is determined using sizeof and the string length is determined using length.


Works with: Linux
const rdev = "/dev/random"
rstream = try
    open(rdev, "r")
catch
    false
end

if isa(rstream, IOStream)
    b = readbytes(rstream, 4)
    close(rstream)
    i = reinterpret(Int32, b)[1]
    println("A hardware random number is:  ", i)
else
    println("The hardware random number stream, ", rdev, ", was unavailable.")
end

demonstrate how to generate a random 32-bit number using the system's built-in mechanism, not just a software algorithm.


julia> "My String"[2:end] # without first character
"y String"

julia> "My String"[1:end-1] # without last character
"My Strin"

julia> "My String"[2:end-1] # without first and last characters
"y Strin"

The code demonstrates how to remove the first, last, and both the first and last characters from a string. It works with any valid Unicode code point in UTF-8 or UTF-16, referencing logical characters, not code units. It doesn't necessarily support all Unicode characters for other encodings like 8-bit ASCII or EUC-JP.


Translation of: Javausing Sockets

const portnum = 12345

function canopen()
    try
        server = listen(portnum)
        println("This is the only instance.")
        sleep(20)
    catch y
        if findfirst("EADDRINUSE", string(y)) != nothing
            println("There is already an instance running.")
        end
    end
end

canopen()

"Check if an application instance is already running, display a message if so, and terminate the program."


win = GtkWindow("hello", 100, 100)
fullscreen(win)
sleep(10)
println(width(win), " ", height(win))
destroy(win)

"Determines the maximum height and width of a window that can fit within the physical display area of the screen, considering window decorations and menubars. It adjusts for multiple monitors and tiling window managers, using the Gtk library."


function check(i, j)
    id, im = div(i, 9), mod(i, 9)
    jd, jm = div(j, 9), mod(j, 9)

    jd == id && return true
    jm == im && return true

    div(id, 3) == div(jd, 3) &&
    div(jm, 3) == div(im, 3)
end

const lookup = zeros(Bool, 81, 81)

for i in 1:81
    for j in 1:81
        lookup[i,j] = check(i-1, j-1)
    end
end

function solve_sudoku(callback::Function, grid::Array{Int64})
    (function solve()
        for i in 1:81
            if grid[i] == 0
                t = Dict{Int64, Nothing}()

                for j in 1:81
                    if lookup[i,j]
                        t[grid[j]] = nothing
                    end
                end

                for k in 1:9
                    if !haskey(t, k)
                        grid[i] = k
                        solve()
                    end
                end

                grid[i] = 0
                return
            end
        end

        callback(grid)
    end)()
end

function display(grid)
    for i in 1:length(grid)
        print(grid[i], " ")
        i %  3 == 0 && print(" ")
        i %  9 == 0 && print("\n")
        i % 27 == 0 && print("\n")
    end
end

grid = Int64[5, 3, 0, 0, 2, 4, 7, 0, 0,
             0, 0, 2, 0, 0, 0, 8, 0, 0,
             1, 0, 0, 7, 0, 3, 9, 0, 2,
             0, 0, 8, 0, 7, 2, 0, 4, 9,
             0, 2, 0, 9, 8, 0, 0, 7, 0,
             7, 9, 0, 0, 0, 0, 0, 8, 0,
             0, 0, 0, 0, 3, 0, 5, 0, 6,
             9, 6, 0, 0, 1, 0, 3, 0, 0,
             0, 5, 0, 6, 9, 0, 0, 1, 0]

solve_sudoku(display, grid)

"Implement a Sudoku solver that takes a partially filled 9x9 grid as input and outputs the completed Sudoku grid in a human-readable format."


Works with: Julia version 0.6
function knuthshuffle!(r::AbstractRNG, v::AbstractVector)
    for i in length(v):-1:2
        j = rand(r, 1:i)
        v[i], v[j] = v[j], v[i]
    end
    return v
end
knuthshuffle!(v::AbstractVector) = knuthshuffle!(Base.Random.GLOBAL_RNG, v)

v = collect(1:20)
println("# v = $v\n   -> ", knuthshuffle!(v))

implement the Knuth shuffle (also known as the Fisher-Yates shuffle) algorithm. This algorithm randomly shuffles the elements of an array in-place. The shuffling process involves iterating from the last index of the array down to 1, and for each index, swapping the element at that index with an element at a random index within the range of 0 to the current index. If in-place modification of the array is not possible in the used programming language, the algorithm can be adjusted to return a new shuffled array. The algorithm can also be modified to iterate from left to right if needed.


using Dates

const wday = Dates.Fri
const lo = 1
const hi = 12

print("\nThis script will print the last ", Dates.dayname(wday))
println("s of each month of the year given.")
println("(Leave input empty to quit.)")

while true
    print("\nYear> ")
    y = chomp(readline())
    0 < length(y) || break
    y = try
        parseint(y)
    catch
        println("Sorry, but \"", y, "\" does not compute as a year.")
        continue
    end
    println()
    for m in Date(y, lo):Month(1):Date(y, hi)
        println("    ", tolast(m, wday))
    end
end

The code takes a year as input and outputs the dates of the last Friday of each month for that given year.


display the string "Goodbye, World!" without appending a newline at the end, using Julia's print function which doesn't automatically insert a newline.


using Gtk

function twoentrywindow()
    txt = "Enter Text Here"
    txtchanged = false

    win = GtkWindow("Keypress Test", 500, 100) |> (GtkFrame() |> (vbox = GtkBox(:v)))
    lab = GtkLabel("Enter some text in the first box and 7500 into the second box.")
    txtent = GtkEntry()
    set_gtk_property!(txtent,:text,"Enter Some Text Here")
    nument = GtkEntry()
    set_gtk_property!(nument,:text,"Enter the number seventy-five thousand here")
    push!(vbox, lab, txtent, nument)

    function keycall(w, event)
        strtxt = get_gtk_property(txtent, :text, String)
        numtxt = get_gtk_property(nument, :text, String)
        if strtxt != txt && occursin("75000", numtxt)
            set_gtk_property!(lab, :label, "You have accomplished the task.")
        end
    end
    signal_connect(keycall, win, "key-press-event")

    cond = Condition()
    endit(w) = notify(cond)
    signal_connect(endit, win, :destroy)
    showall(win)
    wait(cond)
end

twoentrywindow()

"Implement functionality to accept a string and the integer 75000 as inputs from a graphical user interface."


updated version for Julia 1.x | Rename isalpha to isletter #27077 | https://github.com/JuliaLang/julia/pull/27077[edit]
# Caeser cipher
# Julia 1.5.4
# author: manuelcaeiro | https://github.com/manuelcaeiro

function csrcipher(text, key)
    ciphtext = ""
    for l in text
        numl = Int(l)
        ciphnuml = numl + key
        if numl in 65:90
            if ciphnuml > 90
                rotciphnuml = ciphnuml - 26
                ciphtext = ciphtext * Char(rotciphnuml)
            else
                ciphtext = ciphtext * Char(ciphnuml)
            end
        elseif numl in 97:122
            if ciphnuml > 122
                rotciphnuml = ciphnuml - 26
                ciphtext = ciphtext * Char(rotciphnuml)
            else
                ciphtext = ciphtext * Char(ciphnuml)
            end
        else
            ciphtext = ciphtext * Char(numl)
        end
    end
    return ciphtext
end

text = "Magic Encryption"; key = 13
csrcipher(text, key)

implement both encoding and decoding functions of a Caesar cipher. The cipher rotates the alphabet letters based on a key ranging from 1 to 25, replacing each letter with the corresponding next letter in the alphabet. The codes also handle cases of wrapping from Z to A. The codes illustrate that Caesar cipher provides minimal security as it is vulnerable to frequency analysis and brute force attacks. The codes also demonstrate that Caesar cipher is identical to Vigenère cipher with a key length of 1 and to Rot-13 with a key of 13.


Computes the least common multiple (LCM) of two integers, m and n, which is the smallest positive integer that has both m and n as factors. If either m or n is zero, the LCM is zero. The LCM can be calculated by iterating all multiples of m until finding one that is also a multiple of n, or by using the formula lcm(m, n) = |m × n| / gcd(m, n), where gcd is the greatest common divisor. The LCM can also be found by merging the prime decompositions of both m and n.


Works with: Julia version 0.6
module CUSIP

function _lastdigitcusip(input::AbstractString)
    input = uppercase(input)
    s = 0

    for (i, c) in enumerate(input)
        if isdigit(c)
            v = Int(c) - 48
        elseif isalpha(c)
            v = Int(c) - 64 + 9
        elseif c == '*'
            v = 36
        elseif c == '@'
            v = 37
        elseif c == '#'
            v = 38
        end

        if iseven(i); v *= 2 end
        s += div(v, 10) + rem(v, 10)
    end

    return Char(rem(10 - rem(s, 10), 10) + 48)
end

checkdigit(input::AbstractString) = input[9] == _lastdigitcusip(input[1:8])

end  # module CUSIP

for code in ("037833100", "17275R102", "38259P508", "594918104", "68389X106", "68389X105")
    println("$code is ", CUSIP.checkdigit(code) ? "correct." : "not correct.")
end

The code validates the last digit (check digit) of a given CUSIP code, which is a nine-character alphanumeric code used to identify North American financial securities. The validation is performed according to a specific algorithm that considers the numeric value of digits, the ordinal position of letters in the alphabet, and specific values for special characters. The code also handles the doubling of values for even-positioned characters. The final check digit is calculated as (10 - (sum of calculated values mod 10)) mod 10.


print("This host's word size is ", WORD_SIZE, ".")
if ENDIAN_BOM == 0x04030201
    println("And it is a little-endian machine.")
elseif ENDIAN_BOM == 0x01020304
    println("And it is a big-endian machine.")
else
    println("ENDIAN_BOM = ", ENDIAN_BOM, ", which is confusing")
end

The code prints the word size and endianness of the host machine, using Julia's ENDIAN_BOM, a 32-bit unsigned integer created from an array of four 8-bit unsigned integers, as an endianness marker.


""" Rosetta code task rosettacode.org/wiki/Rosetta_Code/Rank_languages_by_popularity """

using Dates
using DataFrames
using HTTP
using JSON3

""" Get listing of all tasks and draft tasks with authors and dates created, with the counts as popularity """
function rosetta_code_language_example_counts(verbose = false)
    URL = "https://rosettacode.org/w/api.php?"
    LANGPARAMS = ["action" => "query", "format" => "json", "formatversion" => "2", "generator" => "categorymembers",
       "gcmtitle" => "Category:Programming_Languages", "gcmlimit" => "500", "rawcontinue" => "", "prop" => "title"]
    queryparams = copy(LANGPARAMS)
    df = empty!(DataFrame([[""], [0]], ["ProgrammingLanguage", "ExampleCount"]))

    while true  # get all the languages listed, with curid, eg rosettacode.org/w/index.php?curid=196 for C
        resp = HTTP.get(URL * join(map(p -> p[1] * (p[2] == "" ? "" : ("=" * p[2])), queryparams), "&"))
        json = JSON3.read(String(resp.body))
        pages = json.query.pages
        reg = r"The following \d+ pages are in this category, out of ([\d\,]+) total"
        for p in pages
            lang = replace(p.title, "Category:" => "")
            langpage = String(HTTP.get("https://rosettacode.org/w/index.php?curid=" * string(p.pageid)).body)
            if !((m = match(reg, langpage)) isa Nothing)
                push!(df, [lang, parse(Int, replace(m.captures[1], "," => ""))])
                verbose && println("Language: $lang, count: ", m.captures[1])
            end
        end
        !haskey(json, "query-continue") && break  # break if no more pages, else continue to next pages
        queryparams = vcat(LANGPARAMS, "gcmcontinue" => json["query-continue"]["categorymembers"]["gcmcontinue"])
    end

    return sort!(df, :ExampleCount, rev = true)
end

println("Top 20 Programming Languages on Rosetta Code by Number of Examples, As of: ", now())
println(rosetta_code_language_example_counts()[begin:begin+19, :])

The code sorts and ranks the most popular computer programming languages based on the number of members in Rosetta Code categories. It uses both web scraping and API methods to access data. The code also includes optional functionality to filter incorrect results. It generates a complete ranked list of all programming languages, which is updated periodically.


Translation of: Python
for i in collection
   println(i)
end

utilize Julia's "for each" loop or "range" syntax to iterate over and print each element in a collection, including arrays, tuples, strings, dictionaries, and numeric scalars.


s = "Hello,How,Are,You,Today"
a = split(s, ",")
t = join(a, ".")

println("The string \"", s, "\"")
println("Splits into ", a)
println("Reconstitutes to \"", t, "\"")

"Tokenizes a string by commas into an array, and displays the words to the user separated by a period, including a trailing period."


julia> gcd(4,12)
4
julia> gcd(6,12)
6
julia> gcd(7,12)
1

function gcd{T<:Integer}(a::T, b::T)
    neg = a < 0
    while b != 0
        t = b
        b = rem(a, b)
        a = t
    end
    g = abs(a)
    neg ? -g : g
end

find the greatest common divisor (GCD), also known as the greatest common factor (gcf) and greatest common measure, of two integers using Julia's built-in gcd function. This function is implemented in Julia 0.2's standard library and uses a different implementation from the GMP library for arbitrary-precision integers. The code is related to the task of finding the least common multiple.


using Sockets # for version 1.0
println("Echo server on port 12321")
try
    server = listen(12321)
    instance = 0
    while true
        sock = accept(server)
        instance += 1
        socklabel = "$(getsockname(sock)) number $instance"
        @async begin
            println("Server connected to socket $socklabel")
            write(sock, "Connected to echo server.\r\n")
            while isopen(sock)
                str = readline(sock)
                write(sock,"$str\r\n")
                println("Echoed $str to socket $socklabel")
            end
            println("Closed socket $socklabel")
        end
    end
catch y
    println("Caught exception: $y")
end

Implement an echo server that listens on TCP port 12321, accepts and handles multiple simultaneous connections from localhost, echoes complete lines back to clients, and logs connection information. The server remains responsive even if a client sends a partial line or stops reading responses.


The code defines a boolean function, isnumber, that checks if a given string can be parsed directly into a numeric value, including floating point and negative numbers. It does not consider symbols, expressions, or complex number literals that can evaluate to numbers.


# v0.6.0

using Requests

str = readstring(get("https://sourceforge.net/"))

Send a GET request to the URL "https://www.w3.org/", validate the host certificate, and print the obtained resource to the console without any authentication.


using Luxor

isinside(p, a, b) = (b.x - a.x) * (p.y - a.y) > (b.y - a.y) * (p.x - a.x)

function intersection(a, b, s, f)
    dc = [a.x - b.x, a.y - b.y]
    dp = [s.x - f.x, s.y - f.y]
    n1 = a.x * b.y - a.y * b.x
    n2 = s.x * f.y - s.y * f.x
    n3 = 1.0 / (dc[1] * dp[2] - dc[2] * dp[1])
    Point((n1 * dp[1] - n2 * dc[1]) * n3, (n1 * dp[2] - n2 * dc[2]) * n3)
end

function clipSH(spoly, cpoly)
    outarr = spoly
    q = cpoly[end]
    for p in cpoly
        inarr = outarr
        outarr = Point[]
        s = inarr[end]
        for vtx in inarr
            if isinside(vtx, q, p)
                if !isinside(s, q, p)
                    push!(outarr, intersection(q, p, s, vtx))
                end
                push!(outarr, vtx)
            elseif isinside(s, q, p)
                push!(outarr, intersection(q, p, s, vtx))
            end
            s = vtx
        end
        q = p
    end
    outarr
end

subjectp = [Point(50, 150), Point(200, 50), Point(350, 150), Point(350, 300),
    Point(250, 300), Point(200, 250), Point(150, 350), Point(100, 250), Point(100, 200)]

clipp = [Point(100, 100), Point(300, 100), Point(300, 300), Point(100, 300)]

Drawing(400, 400, "intersecting-polygons.png")
background("white")
sethue("red")
poly(subjectp, :stroke, close=true)
sethue("blue")
poly(clipp, :stroke, close=true)
clipped = clipSH(subjectp, clipp)
sethue("gold")
poly(clipped, :fill, close=true)
finish()
preview()
println(clipped)

implement the Sutherland-Hodgman polygon clipping algorithm. The code takes a closed polygon and a rectangle as inputs, clips the polygon by the rectangle, and outputs the sequence of points that define the resulting clipped polygon. For extra credit, the code also displays all three polygons on a graphical surface, using different colors for each polygon and filling the resulting polygon. The orientation of the display can be either north-west or south-west.


function ties{T<:Real}(a::Array{T,1})
    unique(a[2:end][a[2:end] .== a[1:end-1]])
end

function rankstandard{T<:Real}(a::Array{T,1})
    r = collect(1:length(a))
    1 < r[end] || return r
    for i in ties(a)
        r[a.==i] = r[a.==i][1]
    end
    return r
end

function rankmodified{T<:Real}(a::Array{T,1})
    indexin(a, a)
end

function rankdense{T<:Real}(a::Array{T,1})
    indexin(a, unique(a))
end

function rankordinal{T<:Real}(a::Array{T,1})
    collect(1:length(a))
end

function rankfractional{T<:Real}(a::Array{T,1})
    r = float64(collect(1:length(a)))
    1.0 < r[end] || return r
    for i in ties(a)
        r[a.==i] = mean(r[a.==i])
    end
    return r
end

scores = [44, 42, 42, 41, 41, 41, 39]
names = ["Solomon", "Jason", "Errol", "Garry",
         "Bernard", "Barry", "Stephen"]

srank = rankstandard(scores)
mrank = rankmodified(scores)
drank = rankdense(scores)
orank = rankordinal(scores)
frank = rankfractional(scores)

println("    Name    Score  Std  Mod  Den  Ord  Frac")
for i in 1:length(scores)
    print(@sprintf("   %-7s", names[i]))
    print(@sprintf("%5d ", scores[i]))
    print(@sprintf("%5d", srank[i]))
    print(@sprintf("%5d", mrank[i]))
    print(@sprintf("%5d", drank[i]))
    print(@sprintf("%5d", orank[i]))
    print(@sprintf("%7.2f", frank[i]))
    println()
end

The code includes functions to apply different ranking methods (Standard, Modified, Dense, Ordinal, Fractional) on a given list of competition scores. It also includes a helper function to identify duplicated scores. The ranking methods handle ties differently as per their definitions. The ordinal ranking function assumes that the list position already reflects any tie-breaking policy.


# v0.6.0

rad = π / 4
deg = 45.0

@show rad deg
@show sin(rad) sin(deg2rad(deg))
@show cos(rad) cos(deg2rad(deg))
@show tan(rad) tan(deg2rad(deg))
@show asin(sin(rad)) asin(sin(rad)) |> rad2deg
@show acos(cos(rad)) acos(cos(rad)) |> rad2deg
@show atan(tan(rad)) atan(tan(rad)) |> rad2deg

demonstrate the usage of trigonometric functions (sine, cosine, tangent, and their inverses) with the same angle in both radians and degrees. It also includes the conversion of the results of inverse functions to radians and degrees. If the language lacks these functions, the code calculates them using known approximations or identities.


Works with: Julia version 0.6

using MathProgBase, Cbc

struct KPDSupply{T<:Integer}
    item::String
    weight::T
    value::T
    quant::T
end
Base.show(io::IO, kdps::KPDSupply) = print(io, kdps.quant, " ", kdps.item, " ($(kdps.weight) kg, $(kdps.value) €)")

function solve(gear::Vector{KPDSupply{T}}, capacity::Integer) where T<:Integer
    w = getfield.(gear, :weight)
    v = getfield.(gear, :value)
    q = getfield.(gear, :quant)
    sol = mixintprog(-v, w', '<', capacity, :Int, 0, q, CbcSolver())
    sol.status == :Optimal || error("this problem could not be solved")

    if all(q .== 1) # simpler case
        return gear[sol.sol == 1.0]
    else
        pack = similar(gear, 0)
        s = round.(Int, sol.sol)
        for (i, g) in enumerate(gear)
            iszero(s[i]) && continue
            push!(pack, KPDSupply(g.item, g.weight, g.value, s[i]))
        end
        return pack
    end
end

gear = [KPDSupply("map", 9, 150, 1),
        KPDSupply("compass", 13, 35, 1),
        KPDSupply("water", 153, 200, 2),
        KPDSupply("sandwich", 50, 60, 2),
        KPDSupply("glucose", 15, 60, 2),
        KPDSupply("tin", 68, 45, 3),
        KPDSupply("banana", 27, 60, 3),
        KPDSupply("apple", 39, 40, 3),
        KPDSupply("cheese", 23, 30, 1),
        KPDSupply("beer", 52, 10, 3),
        KPDSupply("suntan cream", 11, 70, 1),
        KPDSupply("camera", 32, 30, 1),
        KPDSupply("T-shirt", 24, 15, 2),
        KPDSupply("trousers", 48, 10, 2),
        KPDSupply("umbrella", 73, 40, 1),
        KPDSupply("waterproof trousers", 42, 70, 1),
        KPDSupply("waterproof overclothes", 43, 75, 1),
        KPDSupply("note-case", 22, 80, 1),
        KPDSupply("sunglasses", 7, 20, 1),
        KPDSupply("towel", 18, 12, 2),
        KPDSupply("socks", 4, 50, 1),
        KPDSupply("book", 30, 10, 2)]

pack = solve(gear, 400)
println("The hiker should pack: \n - ", join(pack, "\n - "))
println("\nPacked weight: ", sum(getfield.(pack, :weight)), " kg")
println("Packed value: ", sum(getfield.(pack, :value)), " €")

The code determines the optimal combination of items a tourist can carry in his knapsack, given a maximum weight limit of 4 kg. It uses Julia's MathProgBase package and the mixintprog function to solve the bounded Knapsack problem. The aim is to maximize the total value of items without exceeding the weight limit. The items cannot be divided, only whole units can be taken.


ccall(:jl_exit_on_sigint, Cvoid, (Cint,), 0)

function timeit()
    ticks = 0
    try
        while true
            sleep(0.5)
            ticks += 1
            println(ticks)
        end
    catch
    end
end

@time timeit()
println("Done.")

The code outputs an integer every half second. It handles the SIGINT or SIGQUIT signal, typically generated by user's ctrl-C or ctrl-\ input respectively, to stop the output, display the program's runtime in seconds, and then terminate the program. The code uses 'ccall' to pass the SIGINT signal to Julia as an error when running in the main() function, which is not required in Julia's REPL.


import Base.+
Base.:+(s::AbstractString, n::Real) = string((x = tryparse(Int, s)) isa Int ? x + 1 : parse(Float64, s) + 1)
@show "125" + 1
@show "125.15" + 1
@show "1234567890987654321" + 1