Skip to content

Commit

Permalink
Add exercise: difference of squares (JuliaLang#11)
Browse files Browse the repository at this point in the history
  • Loading branch information
SaschaMann committed Jan 28, 2017
1 parent d403fe9 commit 87bfac6
Show file tree
Hide file tree
Showing 4 changed files with 52 additions and 0 deletions.
7 changes: 7 additions & 0 deletions config.json
Expand Up @@ -5,6 +5,13 @@
"active": false,
"test_pattern": "TODO",
"exercises": [
{
"slug": "difference-of-squares",
"difficulty": 1,
"topics": [
"generators"
]
},
{
"slug": "word-count",
"difficulty": 1,
Expand Down
14 changes: 14 additions & 0 deletions 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
9 changes: 9 additions & 0 deletions 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)
22 changes: 22 additions & 0 deletions 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

0 comments on commit 87bfac6

Please sign in to comment.