Did more of the collatz thing but i got tired of it and i'm not gonna do it anymore
This commit is contained in:
parent
7fb534c57a
commit
a3d191944a
|
@ -1,3 +1,71 @@
|
|||
use std::iter::Peekable;
|
||||
fn main() {
|
||||
println!("Hello, world!");
|
||||
let mut cache: [Option<usize>; 1_000_000] = [None; 1_000_000];
|
||||
cache[1] = Some(1);
|
||||
|
||||
println!("{}", collatz_counter(5, &mut cache));
|
||||
}
|
||||
|
||||
/// this function counts and caches the length of the collatz sequence generated by to_count
|
||||
fn collatz_counter(to_count: usize, cache: &mut [Option<usize>; 1_000_000]) -> usize {
|
||||
// TODO: integrate function into iterator ? or pass iterator with function ? ( solve recursion
|
||||
// creationg multple iterators possibly adding things to the cache as i go ? all would be known if they're
|
||||
// iterated by subtracting from the current position so for that a temporary cache would be needed
|
||||
// to record all the current ones
|
||||
// integrate the iterator
|
||||
// change the array to use u16 instead of usize for memory ?
|
||||
|
||||
// what i need passed : i know my current place in the sequence, and the original sequenced number,
|
||||
// and i know the cache, and i know the sequence iterator
|
||||
//
|
||||
// what i need to solve for : where the current index meets with the cache
|
||||
//
|
||||
// what i need to do : continue iterating
|
||||
|
||||
let sequence_itr = CollatzItr::sequence(to_count).peekable();
|
||||
fn recurse(
|
||||
count: usize,
|
||||
to_count: usize,
|
||||
cache: &mut [Option<usize>; 1_000_000],
|
||||
mut sequence_itr: Peekable<CollatzItr>
|
||||
) -> usize {
|
||||
if let Some(in_cache) = cache[*sequence_itr.peek().expect("unexpected item in bagging area: iterator ended before match was found")] {
|
||||
let total_count: usize = count + in_cache;
|
||||
cache[to_count] = Some(total_count);
|
||||
println!("match found: {}", sequence_itr.peek().expect("nyeh"));
|
||||
dbg!(total_count)
|
||||
}
|
||||
else {
|
||||
sequence_itr.next();
|
||||
recurse(count+1, to_count, cache, sequence_itr)
|
||||
}
|
||||
}
|
||||
recurse(1, to_count, cache, sequence_itr)
|
||||
}
|
||||
|
||||
struct CollatzItr {
|
||||
index: usize,
|
||||
}
|
||||
|
||||
//TODO: make recursive
|
||||
impl Iterator for CollatzItr {
|
||||
type Item = usize;
|
||||
fn next(&mut self) -> Option<usize> {
|
||||
let x = self.index;
|
||||
if x % 2 == 0 {
|
||||
self.index = x / 2;
|
||||
Some(self.index)
|
||||
} else if x == 1 {
|
||||
None
|
||||
} else {
|
||||
self.index = 3 * x + 1;
|
||||
Some(self.index)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl CollatzItr {
|
||||
fn sequence(x: usize) -> Self {
|
||||
CollatzItr { index: x }
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue