Skip to content

Commit

Permalink
Implement short term palindrome optimization (#17)
Browse files Browse the repository at this point in the history
* short term palindrome optimization

* refactor
  • Loading branch information
haozhiliu authored and nothing0012 committed Oct 23, 2023
1 parent a91c68e commit 745f702
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 6 deletions.
9 changes: 9 additions & 0 deletions src/block_rarity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,9 @@ impl<'de> Deserialize<'de> for BlockRarity {

pub(crate) fn is_palindrome(n: &u64) -> bool {
let s = n.to_string();
if s.chars().nth(0) != s.chars().last() {
return false;
}
let reversed = s.chars().rev().collect::<String>();
s == reversed
}
Expand Down Expand Up @@ -127,6 +130,12 @@ fn is_pizza_sat(sat: &Sat) -> bool {
mod tests {
use super::*;

#[test]
fn test_is_palindrome() {
assert!(is_palindrome(&164114646411461u64));
assert!(!is_palindrome(&164114646411462u64));
}

#[test]
fn block_rarities() {
assert_eq!(
Expand Down
45 changes: 39 additions & 6 deletions src/subcommand/server/rpc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -220,18 +220,40 @@ fn get_block_rarity_chunks(block_rarity: &BlockRarity, start: u64, end: u64) ->
}
}
BlockRarity::Palindrome => {
if end - start <= 10_000 {
for i in start..end {
if is_palindrome(&i) {
chunks.push((i, i + 1));
}
}
for palindrome in get_palindromes_from_sat_range(start, end) {
chunks.push((palindrome, palindrome + 1))
}
}
}
chunks
}

fn get_palindromes_from_sat_range(start: u64, end: u64) -> Vec<u64> {
let mut res = vec![];
let s = start.to_string();
let e = end.to_string();

if end - start > 1_000_000 {
return res;
}

// Below magic numbers are only applicable for <= 1 million sats ranges.
// Will change to the long term solution in the future.
if s.len() == e.len()
&& s.len() >= 14
&& s.chars().nth(6) != s.chars().nth(s.len() - 7)
&& e.chars().nth(6) != e.chars().nth(e.len() - 7)
{
return res;
}
for i in start..end {
if is_palindrome(&i) {
res.push(i);
}
}
res
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down Expand Up @@ -350,4 +372,15 @@ mod tests {
},]
);
}

#[test]
fn test_get_palindromes_from_sat_range() {
env_logger::init();
let mut palindromes = get_palindromes_from_sat_range(3153515_5000000, 3153515_6000000);
assert_eq!(palindromes, vec![31535155153513]);
palindromes = get_palindromes_from_sat_range(1999999_9999999, 2000000_0999999);
assert_eq!(palindromes, vec![20000000000002]);
palindromes = get_palindromes_from_sat_range(3153515_6000000, 3153515_7000000);
assert_eq!(palindromes.len(), 0);
}
}

0 comments on commit 745f702

Please sign in to comment.