Added rng param to algo

This commit is contained in:
Andrew Golovashevich 2026-01-22 04:45:04 +03:00
parent d8b8ece8a7
commit 87cb8c3cf1
2 changed files with 10 additions and 11 deletions

View File

@ -8,14 +8,14 @@ pub(super) fn initializeBoard(b: &mut Board) {
}
}
fn random_range_with_hole(range: Range<usize>, hole: usize) -> usize {
fn random_range_with_hole(rng: &mut impl rand::Rng, range: Range<usize>, hole: usize) -> usize {
assert!(
range.contains(&hole),
"Hole not in range: {hole} !in {}..{}",
range.start,
range.end
);
let shrunk = random_range(range.start..(range.end - 1));
let shrunk = rng.random_range(range.start..(range.end - 1));
if shrunk >= hole {
return shrunk + 1;
} else {
@ -23,9 +23,9 @@ fn random_range_with_hole(range: Range<usize>, hole: usize) -> usize {
}
}
pub(super) fn swapRandomQueensOnce(b: &mut Board) {
let i1 = random_range(0..b.len());
let i2 = random_range_with_hole(0..b.len(), i1);
pub(super) fn swapRandomQueensOnce(b: &mut Board, rng: &mut impl rand::Rng) {
let i1 = rng.random_range(0..b.len());
let i2 = random_range_with_hole(rng, 0..b.len(), i1);
let tmp = b[i1];
b[i1] = b[i2];

View File

@ -1,7 +1,6 @@
use eframe::emath::Numeric;
use rand::{random, random_range};
use crate::algo::Board;
use crate::algo::misc::{initializeBoard, isOnDiagonal, swapRandomQueensOnce};
use crate::algo::Board;
use eframe::emath::Numeric;
pub(super) fn calculateEnergy(b: &Board) -> f64 {
let mut conflictsCount = 0usize;
@ -29,7 +28,7 @@ pub struct AnnealingConfig {
pub iterationsPerAge: usize
}
pub(crate) fn simulateAnnealing(len: usize, config: &AnnealingConfig) -> Board {
pub(crate) fn simulateAnnealing(len: usize, config: &AnnealingConfig, rng: &mut impl rand::Rng) -> Board {
assert!(config.targetTemperature < config.initialTemperature);
assert!((0f64..1f64).contains(&config.cooldownCoefficient));
@ -48,13 +47,13 @@ pub(crate) fn simulateAnnealing(len: usize, config: &AnnealingConfig) -> Board {
for _ in 0..config.iterationsPerAge {
let mut newState = currentState.clone();
swapRandomQueensOnce(&mut newState.board);
swapRandomQueensOnce(&mut newState.board, rng);
newState.energy = calculateEnergy(&newState.board);
if newState.energy <= currentState.energy {
currentState = newState
} else {
let test = random::<f64>();
let test = rng.random::<f64>();
let delta = newState.energy - currentState.energy;
let calc = (-delta/test).exp();