Exercism: Go version of the 'Difference of Squares' exercise.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

54 lines
1.2 KiB

9 years ago
  1. package diffsquares
  2. import "testing"
  3. var tests = []struct{ n, sqOfSums, sumOfSq int }{
  4. {5, 225, 55},
  5. {10, 3025, 385},
  6. {100, 25502500, 338350},
  7. }
  8. func TestSquareOfSums(t *testing.T) {
  9. for _, test := range tests {
  10. if s := SquareOfSums(test.n); s != test.sqOfSums {
  11. t.Fatalf("SquareOfSums(%d) = %d, want %d", test.n, s, test.sqOfSums)
  12. }
  13. }
  14. }
  15. func TestSumOfSquares(t *testing.T) {
  16. for _, test := range tests {
  17. if s := SumOfSquares(test.n); s != test.sumOfSq {
  18. t.Fatalf("SumOfSquares(%d) = %d, want %d", test.n, s, test.sumOfSq)
  19. }
  20. }
  21. }
  22. func TestDifference(t *testing.T) {
  23. for _, test := range tests {
  24. want := test.sqOfSums - test.sumOfSq
  25. if s := Difference(test.n); s != want {
  26. t.Fatalf("Difference(%d) = %d, want %d", test.n, s, want)
  27. }
  28. }
  29. }
  30. // Benchmark functions on just a single number (100, from the original PE problem)
  31. // to avoid overhead of iterating over tests.
  32. func BenchmarkSquareOfSums(b *testing.B) {
  33. for i := 0; i < b.N; i++ {
  34. SquareOfSums(100)
  35. }
  36. }
  37. func BenchmarkSumOfSquares(b *testing.B) {
  38. for i := 0; i < b.N; i++ {
  39. SumOfSquares(100)
  40. }
  41. }
  42. func BenchmarkDifference(b *testing.B) {
  43. for i := 0; i < b.N; i++ {
  44. Difference(100)
  45. }
  46. }