#! /usr/bin/julia

# Rosetta Code, Twelve statements

function showflaggedbits{T<:BitArray{1}}(a::T, f::T)
    tf = map(x->x ? "T" : "F", a)
    flg = map(x->x ? "*" : " ", f)
    join(tf .* flg, " ")
end

const props = [s -> length(s) == 12,
               s -> sum(s[7:12]) == 3,
               s -> sum(s[2:2:end]) == 2,
               s -> !s[5] || (s[6] & s[7]),
               s -> !any(s[2:4]),
               s -> sum(s[1:2:end]) == 4,
               s -> s[2] $ s[3],
               s -> !s[7] || (s[5] & s[6]),
               s -> sum(s[1:6]) == 3,
               s -> s[11] & s[12],
               s -> sum(s[7:9]) == 1,
               s -> sum(s[1:end-1]) == 4]

const NDIG = length(props)
NDIG < WORD_SIZE || println("WARNING, too many propositions!")

mhist = zeros(Int, NDIG+1)

println("Checking the ", NDIG, " statements against all possibilities.\n")
print(" "^15)
for i in 1:NDIG
    print(@sprintf "%3d" i)
end
println()

for i in 0:(2^NDIG-1)
    s = bitpack(digits(i, 2, NDIG))
    t = bitpack([p(s) for p in props])
    misses = s$t
    mcnt = sum(misses)
    mhist[NDIG-mcnt+1] += 1
    mcnt < 2 || mcnt == NDIG || continue
    if mcnt == 0
        print("    Exact Match: ")
    elseif mcnt == NDIG
        print("     Total Miss: ")
    else
        print("      Near Miss: ")
    end
    println(showflaggedbits(t, misses))
end

println()
println("Distribution of matches")
println(" Matches  Cases")
for i in (NDIG+1):-1:1
    println(@sprintf "    %2d => %4d" i-1 mhist[i])
end
