Skip to content

Commit

Permalink
Merge 79f8506 into e1fbcf3
Browse files Browse the repository at this point in the history
  • Loading branch information
vaskoz committed Apr 27, 2019
2 parents e1fbcf3 + 79f8506 commit a255612
Show file tree
Hide file tree
Showing 3 changed files with 92 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -259,3 +259,4 @@ problems from
* [Day 245](https://github.com/vaskoz/dailycodingproblem-go/issues/506)
* [Day 246](https://github.com/vaskoz/dailycodingproblem-go/issues/508)
* [Day 247](https://github.com/vaskoz/dailycodingproblem-go/issues/510)
* [Day 248](https://github.com/vaskoz/dailycodingproblem-go/issues/512)
27 changes: 27 additions & 0 deletions day248/problem.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package day248

// MaxIf is a typical max function using an if branch.
func MaxIf(a, b int64) int64 {
if a > b {
return a
}
return b
}

// MaxSubtractAndShift finds the max using subtraction
// and right shifting.
func MaxSubtractAndShift(a, b int64) int64 {
return a - ((a - b) & ((a - b) >> 63))
}

// MaxXor uses xor and branching to calculate the max.
// Go requires if branching to convert a bool to an int64.
// NOTE: No benefit here due to branching if, might as well use MaxIf.
// Benchmark perf shows actually worse than MaxIf as expected.
func MaxXor(a, b int64) int64 {
bit := int64(0)
if a < b {
bit = int64(-1)
}
return a ^ ((a ^ b) & bit)
}
64 changes: 64 additions & 0 deletions day248/problem_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
package day248

import "testing"

// nolint
var testcases = []struct {
a, b, max int64
}{
{10, 20, 20},
{20, 1, 20},
{30, 2, 30},
{1, -2, 1},
}

func TestMaxIf(t *testing.T) {
t.Parallel()
for _, tc := range testcases {
if max := MaxIf(tc.a, tc.b); max != tc.max {
t.Errorf("Expected %v, got %v", tc.max, max)
}
}
}

func BenchmarkMaxIf(b *testing.B) {
for i := 0; i < b.N; i++ {
for _, tc := range testcases {
MaxIf(tc.a, tc.b)
}
}
}

func TestMaxSubtractAndShift(t *testing.T) {
t.Parallel()
for _, tc := range testcases {
if max := MaxSubtractAndShift(tc.a, tc.b); max != tc.max {
t.Errorf("Expected %v, got %v", tc.max, max)
}
}
}

func BenchmarkMaxSubtractAndShift(b *testing.B) {
for i := 0; i < b.N; i++ {
for _, tc := range testcases {
MaxSubtractAndShift(tc.a, tc.b)
}
}
}

func TestMaxXor(t *testing.T) {
t.Parallel()
for _, tc := range testcases {
if max := MaxXor(tc.a, tc.b); max != tc.max {
t.Errorf("Expected %v, got %v", tc.max, max)
}
}
}

func BenchmarkMaxXor(b *testing.B) {
for i := 0; i < b.N; i++ {
for _, tc := range testcases {
MaxXor(tc.a, tc.b)
}
}
}

0 comments on commit a255612

Please sign in to comment.