Skip to content

Commit

Permalink
Implement and test CliffScorer
Browse files Browse the repository at this point in the history
  • Loading branch information
NicMcPhee committed Oct 20, 2024
1 parent de62fe8 commit f43d738
Showing 1 changed file with 55 additions and 3 deletions.
58 changes: 55 additions & 3 deletions src/cliff_scorer.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,16 @@
use ec_core::{individual::scorer::Scorer, test_results::Score};
use ec_core::individual::scorer::Scorer;
use ec_linear::genome::bitstring::Bitstring;

use crate::knapsack::Knapsack;

#[derive(Debug, PartialEq, Eq)]
enum CliffScore {
Score(u64),
Overloaded,
}

// We'll need to impl `PartialOrd` and `Ord` on `CliffScore`.

struct CliffScorer {
knapsack: Knapsack,
}
Expand All @@ -14,9 +22,53 @@ impl CliffScorer {
}

impl Scorer<Bitstring> for CliffScorer {
type Score = anyhow::Result<Score<i64>>;
type Score = CliffScore;

fn score(&self, genome: &Bitstring) -> Self::Score {
todo!()
let value = self.knapsack.value(genome);
let weight = self.knapsack.weight(genome);
if weight > self.knapsack.capacity() {
CliffScore::Overloaded
} else {
CliffScore::Score(value)
}
}
}

#[cfg(test)]
mod tests {
use test_case::test_case;

use ec_core::individual::scorer::Scorer;
use ec_linear::genome::bitstring::Bitstring;

use crate::{cliff_scorer::CliffScore, item::Item, knapsack::Knapsack};

use super::CliffScorer;

#[test_case([false, false, false], 0; "choose no items")]
#[test_case([false, true, false], 9; "choose one item")]
#[test_case([true, false, true], 7; "choose two items")]
fn test_choices(choices: [bool; 3], expected_value: u64) {
let knapsack = Knapsack::new(
vec![Item::new(1, 5, 8), Item::new(2, 9, 6), Item::new(3, 2, 7)],
100,
);
let scorer = CliffScorer::new(knapsack);

let choices = Bitstring::from_iter(choices);
assert_eq!(scorer.score(&choices), CliffScore::Score(expected_value));
}

#[test]
fn test_overloading() {
let knapsack = Knapsack::new(
vec![Item::new(1, 5, 8), Item::new(2, 9, 6), Item::new(3, 2, 7)],
10,
);
let scorer = CliffScorer::new(knapsack);

let choices = Bitstring::from_iter([true, true, false]);
assert_eq!(scorer.score(&choices), CliffScore::Overloaded);
}
}

0 comments on commit f43d738

Please sign in to comment.