RosettaCodeData/Task/Fractran/Julia/fractran.julia

42 lines
921 B
Text
Raw Permalink Normal View History

2023-07-01 11:58:00 -04:00
# FRACTRAN interpreter implemented as an iterable struct
using .Iterators: filter, map, take
struct Fractran
rs::Vector{Rational{BigInt}}
i₀::BigInt
2023-07-18 13:51:12 -07:00
limit::Int
2023-07-01 11:58:00 -04:00
end
2023-07-18 13:51:12 -07:00
Base.iterate(f::Fractran, i = f.i₀) =
2023-07-01 11:58:00 -04:00
for r in f.rs
2023-07-18 13:51:12 -07:00
if iszero(i % r.den)
2023-07-01 11:58:00 -04:00
i = i ÷ r.den * r.num
2023-07-18 13:51:12 -07:00
return i, i
2023-07-01 11:58:00 -04:00
end
end
2023-07-18 13:51:12 -07:00
interpret(f::Fractran) =
take(
map(trailing_zeros,
filter(ispow2, f))
f.limit)
2023-07-01 11:58:00 -04:00
2023-07-18 13:51:12 -07:00
Base.show(io::IO, f::Fractran) =
join(io, interpret(f), ' ')
2023-07-01 11:58:00 -04:00
macro code_str(s)
2023-07-18 13:51:12 -07:00
[eval(Meta.parse(replace(t, "/" => "//"))) for t ∈ split(s)]
2023-07-01 11:58:00 -04:00
end
2023-07-18 13:51:12 -07:00
primes = Fractran(code"17/91 78/85 19/51 23/38 29/33 77/29 95/23
77/19 1/17 11/13 13/11 15/14 15/2 55/1", 2, 30)
2023-07-01 11:58:00 -04:00
# Output
println("First 25 iterations of FRACTRAN program 'primes':\n2 ",
join(take(primes, 25), ' '))
println("\nWatch the first 30 primes dropping out within seconds:")
primes