Showing posts with label algorithms. Show all posts
Showing posts with label algorithms. Show all posts

How to calculate number of paper folds to get thickness equal to distance to the moon?

I wanted to try how a programming exercise would translate to a blog post.

I opened Brilliant.com and the first exercise was a puzzle of folding paper. I decided to solve it using Julia language.


How thick is a sheet of printer paper?

For this exercise, let's assume 0.097mm to 0.1mm depending on the "weight" of the paper.



# define known variables
building = 828             # units: m -- Burj Khalifa building
moon = 391000000     # units: m; distance to the moon
sheet = 0.1 / 1000        # unit: m -- thickness of 100 sheets is 1 cm




function fold(initial, desired)
folds = 0                                              # initial number of folds
achieved = initial                                # initial thickness
results = []
while true
achieved = achieved * 2               # fold paper
if achieved >= desired break end # check if time to exit the loop
push!(results, achieved)               # add to results
folds = folds + 1                           # increment
end

return results 
end 

results = fold(sheet, moon)                         # replace moon with building
folds = size(results)[1]                               # size is a tuple, get first element
thickness = results[folds] /1_000_000
print("We used $folds to get $thickness thousand km.")
println()
data = results ./ 1000.0                               # data need to be Array{Float64, 1}, in km
increments = size(results)[1]



using Plots
using PlutoUI

How to create a slider in Julia?


I use that slider to show me the progression of thickness from 1 fold to as many as it takes.
@bind slider_ui Slider(1:increments) # one widget per cell


How to create a drop-down menu in Julia?


@bind plot_type Select(["scatter","line","bar"])



How to draw a simple diagram to visualize the data?

 
plot(
data[1:slider_ui], 
seriestype=Symbol(plot_type), 
title="x=$slider_ui folds, y=km, $plot_type plot"
)



 

So, what is the number of folds to get to the moon?


Only 42 folds will take us to the moon and a bit further!




As an Amazon Associate I earn from qualifying purchases.

apt quotation..