TryBugHunt
goOtherMedium

Player ranks follow their position in the list, not their score

BugFind the bug and fix the code

What it should do

rankOf(scores, player) returns the rank (1 is the best) of the player at index player in scores. rankOf([50, 90, 70], 0) returns 3, because 50 is the lowest score.

What happens instead

rankOf([50, 90, 70], 0) returns 1, and rankOf([50, 90, 70], 1) returns 2.

package main

import "sort"

func rankOf(scores []int, player int) int {
    sorted := scores
    sort.Sort(sort.Reverse(sort.IntSlice(sorted)))
    for i, s := range sorted {
        if s == scores[player] {
            return i + 1
        }
    }
    return -1
}

Test a custom input to verify an edge case (e.g. empty lists, negative numbers, duplicates).

⏱️0:00
Hints
🏆 0 hints = Flawless Solve
Think & Test Cooldown
2:00 remaining

Take a moment to read the bug symptom and trace the code with Run & Check before unlocking Hint 1.

Hint 2
Unlocks after Hint 1
Hint 3
Unlocks after Hint 2

This bug belongs to the mutation and copying bugs pattern

Slices that share one backing array, so changing a copy changes the original.

What you'll practise

A medium Go debugging exercise about mutation and copying bugs: slices that share one backing array, so changing a copy changes the original.

The checks your fix must pass

Signs of this kind of bug

Spoiler: why this bug happens(try it first; the hints get warmer one at a time)

sorted := scores copies only the slice header, so both names point at the same array. Sorting sorted also sorts scores, and scores[player] then reads whoever moved into that position, not the player you asked about. The result is that the rank simply matches the index. Assigning a slice never copies its elements; when you need to sort or modify a copy, make one with append([]int{}, scores...) or make plus copy.

The pattern behind it: mutation and copying bugs.

More mutation and copying bugs to practise

Embed this challenge on your site

Paste this into any web page or blog post. Visitors fix the bug right there, in their browser.

<iframe src="https://trybughunt.com/embed/336a1d1d-5a4d-413d-b434-55ecbce88cb5" title="Debugging challenge: Player ranks follow their position in the list, not their score" width="100%" height="580" loading="lazy" style="border:1px solid #d4d4d8;border-radius:12px;max-width:760px"></iframe>
<p style="font-size:14px">Debugging challenge from <a href="https://trybughunt.com/challenges/336a1d1d-5a4d-413d-b434-55ecbce88cb5">TryBugHunt</a></p>