Why is my code not passing the HighScores tests?

Here’s my code:

class HighScores {
  List<int> scores;
  HighScores(this.scores);

  int latest() {
    return scores.last;
  }

  int personalBest() {
    List<int> sortedScores = scores;
    sortedScores.sort();
    return sortedScores.last;
  }

  List<int> personalTopThree() {
    List<int> topThree = [];
    List<int> sortedScores = scores;
    sortedScores.sort();
    int l = sortedScores.length;
    if (l>0) topThree.add(sortedScores[l-1]);
    if (l>1) topThree.add(sortedScores[l-2]);
    if (l>2) topThree.add(sortedScores[l-3]);
    return topThree;
  }

  
}

Beside this, I’ve tried a bunch of other solutions & they all fail. I’m not sure what I’m doing wrong! I’m also not sure I understand the tests. Some of them seem to be testing things other than what’s discussed in the exercise’s directions, e.g.,

  test('Latest score after personal best', () {
    final scores = HighScores(<int>[20, 70, 15, 25, 30]);
    scores.personalBest();
    expect(scores.latest(), equals(30));
  }, skip: true);

sounds to me like the expectation is the program will run scores.personalBest() (which would expect a return value of 70) and then run scores.latest()? Is that what’s being tested?

Other people have passed this exercise, and it’s categorized as “easy.” What am I missing?

Thanks, in advance, for your help!
Al C.

Yes. This test is checking that the personalBest() function doesn’t change the return value of latest()

A quick look at sort method - List class - dart:core library - Dart API suggests that sort mutates an array. I would presume that List<int> sortedScores = scores does not copy the array, but simply means that sortedScores and scores represent the same array in memory. So my suspicion would be that you’re unintentially reordering the original array in PersonalBest().

That’s probably a common mistake, which is why the test exists.


(Note, I’ve never written a line of Dart in my life, so I might be totally wrong :slight_smile:))

Hey Jeremy,
Thank you for the speedy reply! I really appreciate it, esp. since you’ve never even written Dart code before :grinning:

I searched and experimented a little, and you’re absolutely right!
List bList = aList; just makes a shallow copy (is that the right term?) bList is still pointing to aList. If I add an item to aList it’ll show up as a member of bList, and sorting one list sorts the other. (If anyone’s interested, I figured out you can copy such that the new list isn’t pointing to the old one via List bList = [...aList]; or List bList = List.from(aList); or List bList = aList.toList(); … so exercism is helping me learn!)

That said, I still kinda’ wish the exercise was worded a little differently, or somehow made clearer what you need to be able to do to pass the tests. But maybe that’s just me.

Anyway, thanks again for your help!
Al

Glad to help!

Suggestions on improvements welcome! :slight_smile: