use crate::Solution;
use pmath::digits::digits;
problem!(Problem0040, 40, "Champernowne's Constant");
impl Solution for Problem0040 {
fn solve(&self) -> String {
POSITIONS
.into_iter()
.map(|pos| get_digit(pos) as i32)
.product::<i32>()
.to_string()
}
}
const POSITIONS: [u64; 7] = [1, 10, 100, 1_000, 10_000, 100_000, 1_000_000];
fn get_digit(pos: u64) -> u8 {
let mut n = 0;
let mut prev_count = 0;
let mut next_count = 0;
while next_count <= pos {
n += 1;
prev_count = next_count;
next_count += 9 * n * 10u64.pow(n as u32 - 1);
}
let mut number = 10u64.pow(n as u32 - 1) - 1;
let mut digits_to_move = pos - prev_count - 1;
number += digits_to_move / n;
digits_to_move %= n;
number += 1;
digits(number, 10)
.nth_back(digits_to_move as usize)
.unwrap()
}