diff --git a/config.json b/config.json index 220215d2885d5..46b570f3e8f89 100644 --- a/config.json +++ b/config.json @@ -5,6 +5,13 @@ "active": false, "test_pattern": "TODO", "exercises": [ + { + "slug": "difference-of-squares", + "difficulty": 1, + "topics": [ + "generators" + ] + }, { "slug": "word-count", "difficulty": 1, diff --git a/exercises/difference-of-squares/difference-of-squares.jl b/exercises/difference-of-squares/difference-of-squares.jl new file mode 100644 index 0000000000000..79f86a647cef9 --- /dev/null +++ b/exercises/difference-of-squares/difference-of-squares.jl @@ -0,0 +1,14 @@ +"Square the sum of the numbers up to the given number" +function sum_of_squares(n::Int) + +end + +"Sum the squares of the numbers up to the given number" +function square_of_sum(n::Int) + +end + +"Subtract sum of squares from square of sums" +function difference(n::Int) + +end diff --git a/exercises/difference-of-squares/example.jl b/exercises/difference-of-squares/example.jl new file mode 100644 index 0000000000000..47a477b219dc6 --- /dev/null +++ b/exercises/difference-of-squares/example.jl @@ -0,0 +1,9 @@ +# This uses reduce instead of sum because sum can't handle empty collections properly. +# There is no universal zero-element, so it has to be specified manually and cannot +# be determined automatically. Otherwise, n=0 will cause an error. +sum_of_squares(n::Int) = reduce(+, 0, i^2 for i in 1:n) + +# However, sum{T<:Real}(r::Range{T}) can handle "empty" ranges. +square_of_sum(n::Int) = sum(1:n)^2 + +difference(n::Int) = square_of_sum(n) - sum_of_squares(n) diff --git a/exercises/difference-of-squares/runtests.jl b/exercises/difference-of-squares/runtests.jl new file mode 100644 index 0000000000000..89a39e45c4b2c --- /dev/null +++ b/exercises/difference-of-squares/runtests.jl @@ -0,0 +1,22 @@ +using Base.Test + +include("difference-of-squares.jl") + +@testset "Square the sum of the numbers up to the given number" begin + @test square_of_sum(5) == 225 + @test square_of_sum(10) == 3025 + @test square_of_sum(100) == 25502500 +end + +@testset "Sum the squares of the numbers up to the given number" begin + @test sum_of_squares(5) == 55 + @test sum_of_squares(10) == 385 + @test sum_of_squares(100) == 338350 +end + +@testset "Subtract sum of squares from square of sums" begin + @test difference(0) == 0 + @test difference(5) == 170 + @test difference(10) == 2640 + @test difference(100) == 25164150 +end