DEV Community

Discussion on: Square a number: awful answers only

Collapse
 
mattother profile image
mattother • Edited

Simple enough. Just create some random square images and check randomly to see if the diagonal of one equals our number, with the added bonus of a potential for an awesome looking image.

And by the Infinite Monkey Theorem, given an infinite number of monkeys running an inifinite number of square functions, we'll eventually have the worlds greatest image. What a bonus.

module Square

using Images, Colors, FileIO

function square(num)
    v = tryGetSquare(num, 5000, 10000000)
    if v == -1
        error("Could not find square root")
    end
    return v
end

function tryGetSquare(num, maxNum, maxIter)
    if !isdir("images")
        mkdir("images")
    end
    for _ in 1:maxIter
        makeImg(maxNum)
        s = testImage(num)
        if s != -1
            return s
        end
    end
    return -1
end

function makeImg(maxNum)
    dims = rand(1:maxNum, 1)[1]
    imgc = rand(RGB{Float32}, dims, dims)
    path = string("images/", dims, ".png")
    save(path, imgc)
    return path
end

function testImage(num)
    images = readdir("images")
    pickedImg = rand(1:length(images))
    imgData = load(string("images/", images[pickedImg]))
    dia = dialogonalLength(imgData)
    if dia == num
        return length(imgData)
    end
    return -1
end

function dialogonalLength(imgData)
    count = 0
    for x in 1:size(imgData, 1)
        for y in 1:size(imgData, 2)
            if x == y
                count += 1
            end
        end
    end
    return count
end

end # module
Enter fullscreen mode Exit fullscreen mode