Skip to content

Instantly share code, notes, and snippets.

@craftyc0der
Last active April 14, 2021 13:30
Show Gist options
  • Save craftyc0der/21a2bab061224892188d1cdca1e8aea9 to your computer and use it in GitHub Desktop.
Save craftyc0der/21a2bab061224892188d1cdca1e8aea9 to your computer and use it in GitHub Desktop.
Powerset generator in Rust for Twitter Math
$ target/debug/powerset
powerset:
 Input: [1, 2, 3, 4, 5]
 Output: ["", "1", "2", "12", "3", "13", "23", "123", "4", "14", "24", "124", "34", "134", "234", "1234", "5", "15", "25", "125", "35", "135", "235", "1235", "45", "145", "245", "1245", "345", "1345", "2345", "12345"] 
 Has odd count of 16
[package]
name = "powerset"
version = "0.0.1"
edition = "2018"
[dependencies]
[features]
[[bin]]
name = "powerset"
path = "src/powerset.rs"
fn main() {
let powerset: Vec<String> = powerset::create_set(&default_set());
println!(
"powerset:\n Input: {:?}\n Output: {:?} \n Has odd count of {}",
default_set(),
powerset,
powerset::odd_count(&powerset)
);
}
fn default_set() -> [i8; 5] {
[1, 2, 3, 4, 5]
}
pub mod powerset {
//! Module that calculates powerset and counts odd length values
//! imports
use std::fmt::Write;
//* create set function
pub fn create_set(set: &[i8]) -> Vec<String> {
let base: u32 = 2;
let length: u32 = set.len() as u32;
let power: u32 = base.pow(set.len() as u32);
let mut arr: Vec<String> = vec![String::new(); power as usize];
for n in 0..power {
let mut buffer = String::new();
for r in 0..length {
if n & (1 << r) == 0 {
let _ = write!(&mut buffer, "{}", set[r as usize]);
}
}
let index = power - n - 1;
arr[index as usize] = buffer;
}
arr
}
//* count odd lengths
pub fn odd_count(powerset: &Vec<String>) -> u32 {
let mut count: u32 = 0;
for member in powerset.into_iter() {
match member.len() % 2 {
1 => count += 1,
_ => {}
}
}
count
}
//* count even lengths
pub fn even_count(powerset: &Vec<String>) -> u32 {
let mut count: u32 = 0;
for member in powerset.into_iter() {
match member.len() % 2 {
0 => count += 1,
_ => {}
}
}
count
}
}
#[test]
fn test_odd_count() {
assert!(powerset::odd_count(&powerset::create_set(&default_set())) == 16)
}
#[test]
fn test_odd_count_large() {
assert!(powerset::odd_count(&powerset::create_set(&[1, 2, 3, 4, 5, 6, 7, 8, 9])) == 256)
}
#[test]
fn test_odd_plus_even_count_large() {
let powerset = powerset::create_set(&[1, 2, 3, 4, 5, 6, 7, 8, 9]);
assert!(
powerset::odd_count(&powerset) + powerset::even_count(&powerset) == powerset.len() as u32
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment