Skip to content

Instantly share code, notes, and snippets.

@Arkoniak
Created December 1, 2020 16:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Arkoniak/5ad9d94974a4435bd47598e95327a089 to your computer and use it in GitHub Desktop.
Save Arkoniak/5ad9d94974a4435bd47598e95327a089 to your computer and use it in GitHub Desktop.
Advent of Code, day 01, data generation
using StableRNGs
function validate2(res, n)
cnt = 0
for i in res
for j in res
cnt += (i != j) & (i + j == n)
end
end
cnt == 2
end
function validate3(res, n)
cnt = 0
for i in res
for j in res
for k in res
cnt += (i != j) & (i != k) & (j != k) & (i + j + k == n)
end
end
end
cnt == 6
end
function validate4(res, n)
cnt = 0
for i in res
for j in res
for k in res
for h in res
cnt += (i != j) & (i != k) & (j != k) &
(i != h) & (j != h) & (k != h) &
(i + j + k + h == n)
end
end
end
end
cnt == 24
end
function gen(rng, n, k)
while true
n0 = n
res = Int[]
found = true
for i in 1:k - 1
k0 = rand(rng, 1:n0 - 1)
if k0 < 100
break
end
push!(res, k0)
n0 = n0 - k0
if n0 == 1 && i < k - 1
found = false
break
end
end
if found
push!(res, n - sum(res))
if length(unique(res)) == k && res[end] > 100
return res
end
end
end
end
function genset4(rng, n, l)
while true
x1 = gen(rng, n, 3)
x2 = gen(rng, n, 2)
x3 = gen(rng, n, 4)
x = union(x1, x2, x3)
!validate2(x, n) | !validate3(x, n) | !validate4(x, n) && continue
y = setdiff(1:2020, x)
for z in x
v = n - z
idx = searchsortedfirst(y, v)
if idx <= length(y) && y[idx] == v
deleteat!(y, idx)
end
end
for i1 in 1:length(x)
for i2 in i1+1:length(x)
v1 = x[i1]
v2 = x[i2]
v = n - (v1 + v2)
idx = searchsortedfirst(y, v)
if idx <= length(y) && y[idx] == v
deleteat!(y, idx)
end
end
end
for i1 in 1:length(x)
for i2 in i1+1:length(x)
for i3 in i2+1:length(x)
v1 = x[i1]
v2 = x[i2]
v3 = x[i3]
v = n - (v1 + v2 + v3)
idx = searchsortedfirst(y, v)
if idx <= length(y) && y[idx] == v
deleteat!(y, idx)
end
end
end
end
found = true
for _ in 1:l-length(x)
if isempty(y)
found = false
break
end
idx = rand(rng, 1:length(y))
x0 = y[idx]
deleteat!(y, idx)
v = n - x0
idx = searchsortedfirst(y, v)
if idx <= length(y) && y[idx] == v
deleteat!(y, idx)
end
for z in x
v = n - (z + x0)
idx = searchsortedfirst(y, v)
if idx <= length(y) && y[idx] == v
deleteat!(y, idx)
end
end
for i1 in 1:length(x)
for i2 in i1+1:length(x)
v1 = x[i1]
v2 = x[i2]
v = n - (v1 + v2 + x0)
idx = searchsortedfirst(y, v)
if idx <= length(y) && y[idx] == v
deleteat!(y, idx)
end
end
end
push!(x, x0)
end
found && return x
end
end
##################################
# Usage
rng = StableRNG(2021)
res = genset4(rng, 2020, 200);
# Validation
@assert length(unique(res)) == length(res)
@assert length(res) == 200
@assert validate2(res, 2020)
@assert validate3(res, 2020)
@assert validate4(res, 2020)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment