Skip to content

Commit

Permalink
feat: add climbing the leaderboard solution
Browse files Browse the repository at this point in the history
  • Loading branch information
leometzger committed Aug 14, 2023
1 parent bdc2c4e commit e82ade7
Show file tree
Hide file tree
Showing 2 changed files with 96 additions and 0 deletions.
62 changes: 62 additions & 0 deletions implementation/climbing_the_leaderboard.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
package implementation

func searchIndex(ranked []int32, player int32, current int) int32 {
// is the first one
if ranked[0] < player {
return -1
}

// is the last one
if ranked[len(ranked)-1] > player {
return int32(len(ranked) - 1)
}

// binary search
mid := len(ranked) / 2
for {
if ranked[mid] == player {
return int32(mid)
}

if ranked[mid] > player && ranked[mid+1] <= player { // found the middle guy
return int32(mid)
}

if ranked[mid] < player {
mid = mid / 2
} else {
mid = mid + mid/2
}
}
}

func climbingLeaderboard(ranked []int32, players []int32) []int32 {
var result []int32
positions := make([]int32, len(ranked))

counter := int32(1)
positions[0] = counter

for i := 1; i < len(ranked); i++ {
if ranked[i] == ranked[i-1] {
positions[i] = counter
} else {
counter++
positions[i] = counter
}
}

for i := 0; i < len(players); i++ {
previous := searchIndex(ranked, players[i], len(ranked)/2)

if previous == -1 {
result = append(result, 1)
} else if ranked[previous] == players[i] {
result = append(result, positions[previous])
} else {
result = append(result, positions[previous]+1)
}
}

return result
}
34 changes: 34 additions & 0 deletions implementation/climbing_the_leaderboard_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package implementation

import (
"testing"

"github.com/stretchr/testify/assert"
)

type ClimbingTheLeaderboard struct {
ranked []int32
player []int32
result []int32
}

func TestClimbingTheLeaderboard(t *testing.T) {
tests := []ClimbingTheLeaderboard{
{
ranked: []int32{100, 100, 50, 40, 40, 20, 10},
player: []int32{5, 25, 50, 120},
result: []int32{6, 4, 2, 1},
},
{
ranked: []int32{100, 90, 90, 80, 75, 60},
player: []int32{50, 65, 77, 90, 102},
result: []int32{6, 5, 4, 2, 1},
},
}

for _, test := range tests {
assert.Equal(t, test.result, climbingLeaderboard(test.ranked, test.player))
}
}

func TestClimbingTheLeaderboardFiles(t *testing.T) {}

0 comments on commit e82ade7

Please sign in to comment.