feat: add initial implementation of 24 game solution with main function

This commit is contained in:
SquidSpirit 2025-08-18 10:55:06 +08:00
parent 51bfae35cd
commit 3030d16bad
3 changed files with 78 additions and 0 deletions

7
679_24_game/Cargo.lock generated Normal file
View File

@ -0,0 +1,7 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "twenty_four_game"
version = "0.1.0"

6
679_24_game/Cargo.toml Normal file
View File

@ -0,0 +1,6 @@
[package]
name = "twenty_four_game"
version = "0.1.0"
edition = "2024"
[dependencies]

65
679_24_game/src/main.rs Normal file
View File

@ -0,0 +1,65 @@
fn main() {
println!("{}", Solution::judge_point24(vec![1, 5, 9, 1]));
}
struct Solution;
impl Solution {
pub fn judge_point24(cards: Vec<i32>) -> bool {
let mut stack: Vec<Vec<f64>> = vec![cards.iter().map(|&v| v as f64).collect()];
while let Some(cards) = stack.pop() {
println!("{:?}", cards);
if cards.len() == 1 {
if (cards.first().unwrap() - 24f64).abs() < 1e-6 {
return true;
} else {
continue;
}
}
for i in 0..(cards.len() - 1) {
for j in (i + 1)..cards.len() {
let a = cards[i];
let b = cards[j];
let mut left_cards = cards.clone();
left_cards.remove(j);
left_cards.remove(i);
println!("{i} {j} {:?}", left_cards);
let mut new_cards = left_cards.clone();
new_cards.push(a + b);
stack.push(new_cards);
let mut new_cards = left_cards.clone();
new_cards.push(a * b);
stack.push(new_cards);
let mut new_cards = left_cards.clone();
new_cards.push(a - b);
stack.push(new_cards);
let mut new_cards = left_cards.clone();
new_cards.push(b - a);
stack.push(new_cards);
if b.abs() > 1e-6 {
let mut new_cards = left_cards.clone();
new_cards.push(a / b);
stack.push(new_cards);
}
if a.abs() > 1e-6 {
let mut new_cards = left_cards.clone();
new_cards.push(b / a);
stack.push(new_cards);
}
}
}
}
false
}
}