Number of symbols in base with an underscore
count(x -> occursin("_", x), string.(names(Base)))
Check if parentheses in a string are balanced
check(s) = mapreduce(x->(x=='(')-(x==')'), (x,y)-> x<0 ? -1 : x+y, s)==0
Apply f to the elements of v and concatenate the result.
mapconcat(f, v) = [z for x in v for z in f(x)]
List of sublists of l
powerset(l) = foldl((y,x) -> append!(y,vcat.(y,x)), l, init=[[]])
Some binary tree
gentree(n) = n == 0 ? 0 : [[gentree(n-1)],[gentree(n-1)]]
Flatten a nested list
flatit(A) = mapreduce(x -> isa(x,Array) ? flatit(x) : x, vcat, A)
Moving julia. Not sure where it comes from.
for i=1:100 println(" "^floor(Int,30*(1+sin(.2*i)))*"julia"); sleep(.1);end
Search for the element in it with max f value, with the associated value
argmax(f, it) = maximum(zip(f.(it), it))
UTF-8 trigonometry
sin(π/60) ≈ √2*(√5-1)*(3*√3+3)/48 - (3*√3-3)*√(5+√5)/24
The exponential function
my_exp(x,n=10) = foldr((k,r) -> 1+x/k*r, 1:n, init = 1)
Math formula
println.(join(n^2:n^2+n, "+") *"=" * join(n^2+n+1:n^2+2n, "+") for n =1:5);
Pythagorean triples
[(a,b,c) for a = 1:100 for b = a:100 for c = b:100 if a^2+b^2 == c^2]
The Blancmange curve
using Winston
fplot(x -> sum(1/2^k*abs(2^k*x-round(2^k*x)) for k = 0:20), [0, 1])
The Pascal triangle
using LinearAlgebra
pascal(n) = round.(Int, exp(diagm(-1 => 1:n)))
The Fibonacci sequence
fib(n) = n>1 ? fib(n-1)+fib(n-2) : 1
Absolute frequencies in the game of Yahtzee
using DataStructures, Base.Iterators
counter(sort(collect(values(counter(x)))) for x in product(fill(1:6,5)...))
Solution to first Euler problem
sum(filter(x -> x%3 == 0 || x%5 == 0, 1:999))
Three years of Sundays
using Primes
@time factor(big(2)^67-1)
Edit: added some links. And the mandatory tests:
using Test
test_set() =
@testset "oneliner" begin
@test check("(1*(2+3))") == true
@test check("(1)*(2+3))") == false
@test mapconcat(sum, [[1,3],[0,1]]) == [4,1]
@test powerset([1,2]) == [[], [1], [2], [1, 2]]
@test gentree(2) == [[[[0], [0]]], [[[0], [0]]]]
@test length(flatit(gentree(4))) == 16
@test argmax(x -> x^2, -9:10) == (100, 10)
@test pascal(5)[3+1,2+1] == 3
@test fib(4) == 5
@test sum(filter(x -> x%3 == 0 || x%5 == 0, 1:999)) == 233168
@test my_exp(1) ≈ exp(1)
@test prod(first, factor(big(2)^67-1).pe) == big(2)^67-1
end