This commit is contained in:
1
optimizer/canvas/.gitignore
vendored
Normal file
1
optimizer/canvas/.gitignore
vendored
Normal file
@@ -0,0 +1 @@
|
||||
/target
|
||||
7
optimizer/canvas/Cargo.lock
generated
Normal file
7
optimizer/canvas/Cargo.lock
generated
Normal file
@@ -0,0 +1,7 @@
|
||||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "canvas"
|
||||
version = "0.1.0"
|
||||
16
optimizer/canvas/Cargo.toml
Normal file
16
optimizer/canvas/Cargo.toml
Normal file
@@ -0,0 +1,16 @@
|
||||
[package]
|
||||
name = "canvas"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
arbitrary = "1.4.1"
|
||||
itertools = "0.14.0"
|
||||
|
||||
[dev-dependencies]
|
||||
criterion = { version = "0.7", features = ["html_reports"] }
|
||||
rand = "0.9.2"
|
||||
|
||||
[[bench]]
|
||||
name = "painting"
|
||||
harness = false
|
||||
73
optimizer/canvas/benches/painting.rs
Normal file
73
optimizer/canvas/benches/painting.rs
Normal file
@@ -0,0 +1,73 @@
|
||||
use arbitrary::{Arbitrary, Unstructured};
|
||||
use canvas::{Card, draw_painting};
|
||||
use criterion::{BenchmarkId, Criterion, criterion_group, criterion_main};
|
||||
use rand::{Rng, rngs::StdRng};
|
||||
use std::{hint::black_box, time::Duration};
|
||||
|
||||
use crate::random_card::RandomCard;
|
||||
|
||||
mod random_card;
|
||||
|
||||
fn criterion_benchmark(c: &mut Criterion) {
|
||||
let cards = vec![
|
||||
Card::from_dbg_string(".ttt."),
|
||||
Card::from_dbg_string("t.l.."),
|
||||
Card::from_dbg_string("ll..pt"),
|
||||
];
|
||||
assert_eq!(draw_painting(&cards, &[]), Some([0, 1, 2]));
|
||||
c.bench_function("painting optimizer", |b| {
|
||||
b.iter(|| {
|
||||
draw_painting(&black_box(cards.clone()), &[]);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
fn random_card_pool<const N: usize>(rng: &mut StdRng) -> Vec<Card> {
|
||||
<[RandomCard; N] as Arbitrary>::arbitrary(&mut Unstructured::new(&rng.random::<[u8; 32]>()))
|
||||
.unwrap()
|
||||
.map(|x| x.0)
|
||||
.to_vec()
|
||||
}
|
||||
|
||||
fn from_elem(c: &mut Criterion) {
|
||||
use rand::SeedableRng;
|
||||
// Define a seed. This can be any value that implements the `SeedableRng` trait.
|
||||
let seed: [u8; 32] = [
|
||||
8u64.to_be_bytes(),
|
||||
8u64.to_be_bytes(),
|
||||
8u64.to_be_bytes(),
|
||||
8u64.to_be_bytes(),
|
||||
]
|
||||
.concat()
|
||||
.try_into()
|
||||
.unwrap();
|
||||
|
||||
// Create a new RNG with the specified seed.
|
||||
let mut rng: StdRng = SeedableRng::from_seed(seed);
|
||||
// Generate a random number using the seeded RNG.
|
||||
let card_pool = [
|
||||
random_card_pool::<4>(&mut rng),
|
||||
random_card_pool::<8>(&mut rng),
|
||||
random_card_pool::<16>(&mut rng),
|
||||
random_card_pool::<32>(&mut rng),
|
||||
random_card_pool::<64>(&mut rng),
|
||||
random_card_pool::<128>(&mut rng),
|
||||
];
|
||||
|
||||
let mut group = c.benchmark_group("from_elem");
|
||||
for size in card_pool.iter() {
|
||||
group.bench_with_input(BenchmarkId::from_parameter(size.len()), size, |b, size| {
|
||||
b.iter(|| {
|
||||
draw_painting(&black_box(size.clone()), &[])
|
||||
});
|
||||
});
|
||||
}
|
||||
group.finish();
|
||||
}
|
||||
|
||||
criterion_group!(name = benches;
|
||||
config = Criterion::default()
|
||||
.warm_up_time(Duration::from_millis(100))
|
||||
.measurement_time(Duration::from_millis(500));
|
||||
targets = criterion_benchmark, from_elem);
|
||||
criterion_main!(benches);
|
||||
30
optimizer/canvas/benches/random_card.rs
Normal file
30
optimizer/canvas/benches/random_card.rs
Normal file
@@ -0,0 +1,30 @@
|
||||
use arbitrary::{Arbitrary, Unstructured};
|
||||
use canvas::{Card, CardField};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct RandomCard(pub(crate) Card);
|
||||
#[derive(Debug)]
|
||||
struct RandomCardField(CardField);
|
||||
|
||||
impl<'a> Arbitrary<'a> for RandomCardField {
|
||||
fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
|
||||
let i = u.int_in_range(0..=15)?;
|
||||
if let Ok(w) = CardField::try_from_bits(i) {
|
||||
Ok(RandomCardField(w))
|
||||
} else {
|
||||
Ok(RandomCardField(CardField::Empty))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Arbitrary<'a> for RandomCard {
|
||||
fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
|
||||
let mut r = vec![];
|
||||
for _ in 0..5 {
|
||||
r.push(u.arbitrary::<RandomCardField>()?)
|
||||
}
|
||||
let w: [RandomCardField; 5] = r.try_into().unwrap();
|
||||
let r = Card::from(w.map(|x: RandomCardField| x.0));
|
||||
Ok(RandomCard(r))
|
||||
}
|
||||
}
|
||||
121
optimizer/canvas/src/card.rs
Normal file
121
optimizer/canvas/src/card.rs
Normal file
@@ -0,0 +1,121 @@
|
||||
use crate::{CardField, Icon};
|
||||
|
||||
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
|
||||
// There are 60 cards in the base set
|
||||
pub struct Card {
|
||||
field: u32,
|
||||
}
|
||||
|
||||
pub struct CardFieldIter {
|
||||
index: u8,
|
||||
field: u32,
|
||||
}
|
||||
|
||||
impl Iterator for CardFieldIter {
|
||||
type Item = CardField;
|
||||
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
if self.index < 5 {
|
||||
let old_index = self.index;
|
||||
self.index += 1;
|
||||
let bitmask = (1 << (CardField::BITPACKED_SIZE as u8)) - 1;
|
||||
let result = (self.field >> (CardField::BITPACKED_SIZE as u8 * old_index)) & bitmask;
|
||||
Some(CardField::try_from_bits(result as u8).unwrap())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<[CardField; 5]> for Card {
|
||||
fn from(value: [CardField; 5]) -> Self {
|
||||
let field = value
|
||||
.iter()
|
||||
.map(|x| x.to_bits())
|
||||
.zip((0u8..).step_by(CardField::BITPACKED_SIZE))
|
||||
.map(|(a, shift_count)| (a as u32) << (shift_count))
|
||||
.fold(0u32, |a, b| a | b);
|
||||
Self { field }
|
||||
}
|
||||
}
|
||||
|
||||
impl Card {
|
||||
pub fn field_iter(&self) -> CardFieldIter {
|
||||
CardFieldIter {
|
||||
index: 0,
|
||||
field: self.field,
|
||||
}
|
||||
}
|
||||
pub const fn empty() -> Self {
|
||||
Self { field: u32::MAX }
|
||||
}
|
||||
pub fn from_dbg_string(text: &str) -> Self {
|
||||
let mut result = [CardField::Empty; 5];
|
||||
let mut current_field = 0;
|
||||
let mut char_iter = text.chars();
|
||||
let match_icon = |x: char| {
|
||||
let field = match x {
|
||||
's' => Icon::Square,
|
||||
'c' => Icon::Circle,
|
||||
't' => Icon::Triangle,
|
||||
'l' => Icon::Color,
|
||||
_ => return None,
|
||||
};
|
||||
Some(field)
|
||||
};
|
||||
while let Some(c) = char_iter.next() {
|
||||
if let Some(f) = match_icon(c) {
|
||||
result[current_field] = CardField::Icon(f);
|
||||
current_field += 1;
|
||||
continue;
|
||||
}
|
||||
let field = match c {
|
||||
'p' => {
|
||||
let f = match_icon(char_iter.next().expect("No icon after point symbol"))
|
||||
.expect("Incorrect icon after point symbol");
|
||||
CardField::PointsPer(f)
|
||||
}
|
||||
'd' => {
|
||||
let f1 =
|
||||
match_icon(char_iter.next().expect("No first icon after double symbol"))
|
||||
.expect("Incorrect first icon after double symbol");
|
||||
let f2 = match_icon(
|
||||
char_iter
|
||||
.next()
|
||||
.expect("No second icon after double symbol"),
|
||||
)
|
||||
.expect("Incorrect second icon after double symbol");
|
||||
CardField::DoubleIcon(f1, f2)
|
||||
}
|
||||
'.' => CardField::Empty,
|
||||
'-' => continue,
|
||||
_ => panic!("Unknown character {c}"),
|
||||
};
|
||||
|
||||
result[current_field] = field;
|
||||
current_field += 1;
|
||||
}
|
||||
result.into()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::{CardField, Icon, card::Card};
|
||||
|
||||
#[test]
|
||||
fn test_correctness() {
|
||||
let card = Card::from_dbg_string("l..t.");
|
||||
println!("{:0x}", card.field);
|
||||
assert_eq!(
|
||||
card.field_iter().collect::<Vec<_>>(),
|
||||
vec![
|
||||
CardField::Icon(Icon::Color),
|
||||
CardField::Empty,
|
||||
CardField::Empty,
|
||||
CardField::Icon(Icon::Triangle),
|
||||
CardField::Empty,
|
||||
]
|
||||
)
|
||||
}
|
||||
}
|
||||
123
optimizer/canvas/src/icon_bitfield.rs
Normal file
123
optimizer/canvas/src/icon_bitfield.rs
Normal file
@@ -0,0 +1,123 @@
|
||||
use crate::Card;
|
||||
use crate::CardField;
|
||||
use crate::Icon;
|
||||
use crate::Painting;
|
||||
|
||||
#[derive(Debug, Default, Clone, PartialEq, Eq)]
|
||||
pub(crate) struct IconBitfield {
|
||||
circle: u8,
|
||||
square: u8,
|
||||
triangle: u8,
|
||||
color: u8,
|
||||
points: u8,
|
||||
}
|
||||
|
||||
impl IconBitfield {
|
||||
pub fn get_icon_bits(&self, icon: Icon) -> u8 {
|
||||
match icon {
|
||||
Icon::Circle => self.circle,
|
||||
Icon::Square => self.square,
|
||||
Icon::Triangle => self.triangle,
|
||||
Icon::Color => self.color,
|
||||
}
|
||||
}
|
||||
pub fn get_point_bits(&self) -> u8 {
|
||||
self.points
|
||||
}
|
||||
|
||||
fn add_icon(&mut self, icon: Icon, index: u8) {
|
||||
let field = match icon {
|
||||
Icon::Circle => &mut self.circle,
|
||||
Icon::Square => &mut self.square,
|
||||
Icon::Triangle => &mut self.triangle,
|
||||
Icon::Color => &mut self.color,
|
||||
};
|
||||
*field |= 1 << index;
|
||||
}
|
||||
pub fn add_field(&mut self, field: CardField, index: u8) {
|
||||
debug_assert!(index < 5);
|
||||
match field {
|
||||
CardField::Icon(icon) => self.add_icon(icon, index),
|
||||
CardField::DoubleIcon(icon1, icon2) => {
|
||||
self.add_icon(icon1, index);
|
||||
self.add_icon(icon2, index);
|
||||
}
|
||||
CardField::PointsPer(_) => self.points |= 1 << index,
|
||||
CardField::Empty => (),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn new(card: &Card) -> Self {
|
||||
let mut result = Self::default();
|
||||
(0u8..)
|
||||
.zip(card.field_iter())
|
||||
.for_each(|(index, field)| result.add_field(field, index));
|
||||
result
|
||||
}
|
||||
|
||||
pub fn from_painting(painting: &Painting) -> Self {
|
||||
let mut bits = Self::new(&painting[0]);
|
||||
bits.layer_below(&Self::new(&painting[1]))
|
||||
.layer_below(&Self::new(&painting[2]));
|
||||
bits
|
||||
}
|
||||
|
||||
pub fn all_fields(&self) -> u8 {
|
||||
self.circle | self.square | self.triangle | self.color | self.points
|
||||
}
|
||||
|
||||
/// Result of putting the other card below this one
|
||||
pub fn layer_below(&mut self, other: &Self) -> &mut Self {
|
||||
// 1 x 0 = 0
|
||||
// 0 x 0 = 0
|
||||
// 0 x 1 = 1
|
||||
// 1 x 1 = 0
|
||||
// Should be !a & b
|
||||
|
||||
let bitmask = !self.all_fields() & other.all_fields();
|
||||
self.circle |= other.circle & bitmask;
|
||||
self.square |= other.square & bitmask;
|
||||
self.triangle |= other.triangle & bitmask;
|
||||
self.color |= other.color & bitmask;
|
||||
self.points |= other.points & bitmask;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::{Icon, icon_bitfield::IconBitfield};
|
||||
|
||||
#[test]
|
||||
fn test_add_field() {
|
||||
let mut x: IconBitfield = Default::default();
|
||||
x.add_icon(Icon::Circle, 2);
|
||||
let expected = IconBitfield {
|
||||
circle: 0b00100,
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(x, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_layer_below() {
|
||||
let mut a: IconBitfield = IconBitfield {
|
||||
color: 0b00010,
|
||||
points: 0b01000,
|
||||
..Default::default()
|
||||
};
|
||||
let b = IconBitfield {
|
||||
triangle: a.get_point_bits(),
|
||||
square: 0b10000,
|
||||
..Default::default()
|
||||
};
|
||||
let expected = IconBitfield {
|
||||
color: a.get_icon_bits(Icon::Color),
|
||||
points: a.get_point_bits(),
|
||||
square: b.get_icon_bits(Icon::Square),
|
||||
..Default::default()
|
||||
};
|
||||
a.layer_below(&b);
|
||||
assert_eq!(a, expected);
|
||||
}
|
||||
}
|
||||
152
optimizer/canvas/src/lib.rs
Normal file
152
optimizer/canvas/src/lib.rs
Normal file
@@ -0,0 +1,152 @@
|
||||
#![allow(dead_code)]
|
||||
#![warn(clippy::unwrap_used, clippy::expect_used)]
|
||||
use crate::objective::Objective;
|
||||
|
||||
mod card;
|
||||
mod icon_bitfield;
|
||||
mod objective;
|
||||
mod optimizer;
|
||||
|
||||
pub use card::Card;
|
||||
|
||||
pub use optimizer::draw_painting;
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Shop {
|
||||
cards: [Card; 5],
|
||||
coins: [u8; 5],
|
||||
}
|
||||
|
||||
#[repr(u8)]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub enum Icon {
|
||||
Circle = 0b00,
|
||||
Square = 0b01,
|
||||
Triangle = 0b10,
|
||||
Color = 0b11,
|
||||
}
|
||||
|
||||
impl TryFrom<u8> for Icon {
|
||||
type Error = ();
|
||||
|
||||
fn try_from(value: u8) -> Result<Self, Self::Error> {
|
||||
ICON_ORDER
|
||||
.get(value as usize)
|
||||
.map(|x| Ok(*x))
|
||||
.unwrap_or(Err(()))
|
||||
}
|
||||
}
|
||||
const ICON_ORDER: [Icon; 4] = [Icon::Circle, Icon::Square, Icon::Triangle, Icon::Color];
|
||||
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub enum CardField {
|
||||
Icon(Icon),
|
||||
PointsPer(Icon),
|
||||
DoubleIcon(Icon, Icon),
|
||||
#[default]
|
||||
Empty,
|
||||
}
|
||||
|
||||
impl CardField {
|
||||
pub const BITPACKED_SIZE: usize = 4;
|
||||
pub fn try_from_bits(bits: u8) -> Result<Self, ()> {
|
||||
{
|
||||
let bits = bits & ((1 << Self::BITPACKED_SIZE) - 1);
|
||||
if (bits) == 0b1111 {
|
||||
Ok(Self::Empty)
|
||||
} else if (bits & (1 << 3)) != 0 {
|
||||
let bits = bits & ((1 << 3) - 1);
|
||||
if bits == 5 {
|
||||
Ok(Self::DoubleIcon(Icon::Triangle, Icon::Color))
|
||||
} else if bits >= 3 {
|
||||
Ok(Self::DoubleIcon(
|
||||
Icon::Square,
|
||||
Icon::try_from(bits + 2 - 3)?,
|
||||
))
|
||||
} else {
|
||||
Ok(Self::DoubleIcon(Icon::Circle, Icon::try_from(bits + 1)?))
|
||||
}
|
||||
} else if bits & (1 << 2) != 0 {
|
||||
let bits = bits & ((1 << 2) - 1);
|
||||
Ok(Self::PointsPer(Icon::try_from(bits)?))
|
||||
} else {
|
||||
Ok(Self::Icon(Icon::try_from(bits)?))
|
||||
}
|
||||
}
|
||||
}
|
||||
/// There are only 4 + 4 + 6 + 1 possibilities when double icons are sorted
|
||||
fn to_bits(self) -> u8 {
|
||||
match self {
|
||||
CardField::Icon(icon) => icon as u8,
|
||||
CardField::PointsPer(icon) => icon as u8 | (1 << 2),
|
||||
CardField::DoubleIcon(mut a, mut b) => {
|
||||
debug_assert_ne!(a, b);
|
||||
if a > b {
|
||||
(a, b) = (b, a);
|
||||
}
|
||||
let tag = match a {
|
||||
// 0..=2
|
||||
Icon::Circle => ICON_ORDER.iter().position(|x| b == *x).unwrap() as u8 - 1,
|
||||
// 3..=4
|
||||
Icon::Square => ICON_ORDER.iter().position(|x| b == *x).unwrap() as u8 - 2 + 3,
|
||||
// 5
|
||||
Icon::Triangle => {
|
||||
debug_assert_eq!(b, Icon::Color);
|
||||
5
|
||||
}
|
||||
Icon::Color => panic!("Color as first double is not possible"),
|
||||
};
|
||||
tag | (1 << 3)
|
||||
}
|
||||
CardField::Empty => (1 << 4) - 1,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Player {
|
||||
cards: Vec<Card>,
|
||||
coins: u8,
|
||||
paintings: Vec<[Card; 3]>,
|
||||
}
|
||||
|
||||
type Painting = [Card; 3];
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Board {
|
||||
players: Vec<Player>,
|
||||
shop: Shop,
|
||||
objectives: [CriteriaCard; 4],
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Default)]
|
||||
struct PointThresholds(u32);
|
||||
|
||||
impl PointThresholds {
|
||||
const BITFIELD_SIZE: usize = 4;
|
||||
pub fn len(&self) -> usize {
|
||||
(self.0.ilog2() as usize).div_ceil(Self::BITFIELD_SIZE)
|
||||
}
|
||||
pub fn new(points: &[u8]) -> Self {
|
||||
let mut result = Self(0);
|
||||
for (index, p) in points.iter().enumerate() {
|
||||
result.set(index, *p);
|
||||
}
|
||||
result
|
||||
}
|
||||
fn set(&mut self, index: usize, value: u8) {
|
||||
debug_assert!(value < (1 << Self::BITFIELD_SIZE));
|
||||
self.0 |= u32::from(value) << (index * Self::BITFIELD_SIZE);
|
||||
}
|
||||
pub fn get(&self, index: usize) -> u8 {
|
||||
let bitmask = (1u8 << Self::BITFIELD_SIZE) - 1;
|
||||
(self.0 >> (index * Self::BITFIELD_SIZE)) as u8 & bitmask
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct CriteriaCard {
|
||||
objective: Objective,
|
||||
// Points depending on how often the criteria was met
|
||||
points: PointThresholds,
|
||||
}
|
||||
184
optimizer/canvas/src/objective.rs
Normal file
184
optimizer/canvas/src/objective.rs
Normal file
@@ -0,0 +1,184 @@
|
||||
use crate::{icon_bitfield::IconBitfield, Icon, Painting, ICON_ORDER};
|
||||
|
||||
// There are 12 objectives/criteria in the base set
|
||||
#[derive(Debug)]
|
||||
pub enum Objective {
|
||||
AllFields,
|
||||
/// Must use every icon in the vector at least once
|
||||
IconsUsed(IconSet),
|
||||
/// The count of all icons in the vec `.0` combined is exactly `.1`
|
||||
ExactlyNIcons((IconSet, u8)),
|
||||
/// These icons are in fields exactly next to each other
|
||||
/// One icon can only be the neighbor of one other icon
|
||||
Neighbors(Vec<(Icon, Icon)>),
|
||||
/// Both icons are on one card, but not adjacent
|
||||
DistantNeighbors(Vec<(Icon, Icon)>),
|
||||
NInARow(Icon, u8),
|
||||
}
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct IconSet(u8);
|
||||
|
||||
pub struct IconSetIterator {
|
||||
icon_set: IconSet,
|
||||
index: u8,
|
||||
}
|
||||
|
||||
impl From<&[Icon]> for IconSet {
|
||||
fn from(value: &[Icon]) -> Self {
|
||||
let v = value
|
||||
.iter()
|
||||
.map(|x| 1 << ICON_ORDER.iter().position(|v| x == v).unwrap())
|
||||
.fold(0, |a, b| a | b);
|
||||
Self(v)
|
||||
}
|
||||
}
|
||||
|
||||
impl IconSet {
|
||||
pub fn len(&self) -> usize {
|
||||
self.0.count_ones() as usize
|
||||
}
|
||||
}
|
||||
|
||||
impl Iterator for IconSetIterator {
|
||||
type Item = Icon;
|
||||
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
while self.index < 4 {
|
||||
let old_index = self.index;
|
||||
self.index += 1;
|
||||
|
||||
if self.icon_set.0 & (1 << old_index) != 0 {
|
||||
return Some(*ICON_ORDER.get(old_index as usize).unwrap());
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoIterator for IconSet {
|
||||
type Item = Icon;
|
||||
type IntoIter = IconSetIterator;
|
||||
|
||||
fn into_iter(self) -> Self::IntoIter {
|
||||
IconSetIterator {
|
||||
icon_set: self,
|
||||
index: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Objective {
|
||||
pub fn count_matches_bitfield(&self, bitfield: &IconBitfield) -> u8 {
|
||||
match self {
|
||||
Objective::AllFields => {
|
||||
if bitfield.all_fields() == 0b11111 {
|
||||
1
|
||||
} else {
|
||||
0
|
||||
}
|
||||
}
|
||||
Objective::IconsUsed(icons) => {
|
||||
let bits = bitfield;
|
||||
if icons.into_iter().all(|i| bits.get_icon_bits(i) > 0) {
|
||||
1
|
||||
} else {
|
||||
0
|
||||
}
|
||||
}
|
||||
Objective::ExactlyNIcons((icons, count)) => {
|
||||
let bits = bitfield;
|
||||
|
||||
if icons
|
||||
.into_iter()
|
||||
.map(|i| bits.get_icon_bits(i).count_ones())
|
||||
.sum::<u32>() as u8
|
||||
== *count
|
||||
{
|
||||
1
|
||||
} else {
|
||||
0
|
||||
}
|
||||
}
|
||||
Objective::NInARow(icon, count) => {
|
||||
let mut bits = bitfield.get_icon_bits(*icon);
|
||||
let bitmask = (1 << count) - 1;
|
||||
let mut res_count = 0;
|
||||
while bits > 0 {
|
||||
if (bits) & bitmask == bitmask {
|
||||
res_count += 1;
|
||||
bits >>= count;
|
||||
} else {
|
||||
bits >>= 1;
|
||||
}
|
||||
}
|
||||
res_count
|
||||
// Objective::Neighbors(items) => todo!(),
|
||||
// Objective::DistantNeighbors(items) => todo!(),
|
||||
}
|
||||
_ => todo!(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn count_matches(&self, painting: &Painting) -> u8 {
|
||||
self.count_matches_bitfield(&IconBitfield::from_painting(painting))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::{
|
||||
Card, Icon, Painting,
|
||||
objective::{IconSet, Objective},
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn test_all_fields() {
|
||||
let v: Painting = [
|
||||
Card::from_dbg_string("...ct"),
|
||||
Card::from_dbg_string("s.s.."),
|
||||
Card::from_dbg_string(".l.t."),
|
||||
];
|
||||
assert_eq!(Objective::AllFields.count_matches(&v), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_n_in_a_row() {
|
||||
let v: Painting = [
|
||||
Card::from_dbg_string("...ll"),
|
||||
Card::from_dbg_string("ll..."),
|
||||
Card::from_dbg_string("..t.."),
|
||||
];
|
||||
assert_eq!(Objective::NInARow(Icon::Color, 2).count_matches(&v), 2);
|
||||
let tricky_two: Painting = [
|
||||
Card::from_dbg_string("...ll"),
|
||||
Card::from_dbg_string("tl..."),
|
||||
Card::from_dbg_string("..lc."),
|
||||
];
|
||||
assert_eq!(
|
||||
Objective::NInARow(Icon::Color, 2).count_matches(&tricky_two),
|
||||
2
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_icons_used() {
|
||||
let v: Painting = [
|
||||
Card::from_dbg_string("...ll"),
|
||||
Card::from_dbg_string("ll..."),
|
||||
Card::from_dbg_string("..t.."),
|
||||
];
|
||||
|
||||
assert_eq!(
|
||||
Objective::IconsUsed(IconSet::from([Icon::Color].as_slice())).count_matches(&v),
|
||||
1
|
||||
);
|
||||
assert_eq!(
|
||||
Objective::IconsUsed(IconSet::from([Icon::Triangle].as_slice())).count_matches(&v),
|
||||
1
|
||||
);
|
||||
assert_eq!(
|
||||
Objective::IconsUsed(IconSet::from([Icon::Circle].as_slice())).count_matches(&v),
|
||||
0
|
||||
);
|
||||
}
|
||||
}
|
||||
90
optimizer/canvas/src/optimizer.rs
Normal file
90
optimizer/canvas/src/optimizer.rs
Normal file
@@ -0,0 +1,90 @@
|
||||
use itertools::Itertools;
|
||||
|
||||
use crate::{CardField, CriteriaCard, card::Card, icon_bitfield::IconBitfield};
|
||||
|
||||
struct OneIndexIterator {
|
||||
n: u64,
|
||||
offset: u8,
|
||||
}
|
||||
|
||||
impl From<u64> for OneIndexIterator {
|
||||
fn from(value: u64) -> Self {
|
||||
Self {
|
||||
n: value,
|
||||
offset: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Iterator for OneIndexIterator {
|
||||
type Item = u8;
|
||||
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
if self.n == 0 {
|
||||
return None;
|
||||
}
|
||||
let new_offset = self.n.trailing_zeros() as u8;
|
||||
self.n >>= new_offset + 1;
|
||||
let result = self.offset + new_offset;
|
||||
self.offset += new_offset + 1;
|
||||
Some(result)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn draw_painting(cards: &[Card], obj: &[(&CriteriaCard, u8)]) -> Option<[usize; 3]> {
|
||||
let bitfields = cards.iter().map(IconBitfield::new).collect::<Vec<_>>();
|
||||
let mut best: Option<([usize; 3], u8)> = None;
|
||||
for stack in (0..cards.len()).permutations(3) {
|
||||
let stack_indices: [_; 3] = stack.try_into().unwrap();
|
||||
let stack = stack_indices.map(|x| cards[x]);
|
||||
let maps = stack_indices.map(|x| &bitfields[x]);
|
||||
let mut painting = maps[0].clone();
|
||||
painting.layer_below(maps[1]).layer_below(maps[2]);
|
||||
let criteria_points = obj
|
||||
.iter()
|
||||
.map(|(criteria, reached)| {
|
||||
criteria.points.get(usize::from(
|
||||
criteria.objective.count_matches_bitfield(&painting) + *reached,
|
||||
))
|
||||
})
|
||||
.sum::<u8>();
|
||||
let bonus_points = OneIndexIterator::from(u64::from(painting.get_point_bits()))
|
||||
.map(|bit_index| {
|
||||
let matched_icon = stack
|
||||
.iter()
|
||||
.map(|x| x.field_iter().nth(usize::from(bit_index)).unwrap())
|
||||
.find_map(|x| match x {
|
||||
CardField::PointsPer(icon) => Some(icon),
|
||||
_ => None,
|
||||
})
|
||||
.expect("Point bits lied");
|
||||
painting.get_icon_bits(matched_icon).count_ones() as u8 * 2
|
||||
})
|
||||
.sum::<u8>();
|
||||
let total_points = bonus_points + criteria_points;
|
||||
let stack_result = (stack_indices, total_points);
|
||||
if let Some(bp) = &mut best {
|
||||
if bp.1 < total_points {
|
||||
*bp = stack_result;
|
||||
}
|
||||
} else {
|
||||
best = Some(stack_result)
|
||||
}
|
||||
}
|
||||
best.map(|x| x.0)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::{card::Card, optimizer::draw_painting};
|
||||
|
||||
#[test]
|
||||
fn test_basic() {
|
||||
let cards = vec![
|
||||
Card::from_dbg_string(".ttt."),
|
||||
Card::from_dbg_string("t.l.."),
|
||||
Card::from_dbg_string("ll..pt"),
|
||||
];
|
||||
assert_eq!(draw_painting(&cards, &[]), Some([0, 1, 2]));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user