Skip to content

Instantly share code, notes, and snippets.

@natemcintosh
Last active September 19, 2025 21:17
Show Gist options
  • Select an option

  • Save natemcintosh/569a2d1b285fce7794ed7e40ff5ce35a to your computer and use it in GitHub Desktop.

Select an option

Save natemcintosh/569a2d1b285fce7794ed7e40ff5ce35a to your computer and use it in GitHub Desktop.
Can Your Team Self-Organize?
use itertools::Itertools;
use rayon::prelude::*;
/// For a given list of numbers, try counting all the possible ways of pulling out all
/// possible numbers of elements, see if it is sorted, and if so, collect the one with
/// the maximum length.
fn calc_max_score(nums: &[usize]) -> usize {
// Use the power set to go through all possible combos of all possible elements,
// while retaining the order of the elements
nums.iter()
.powerset()
// Only want sorted combinations
.filter(|v| v.is_sorted())
.map(|v| v.len())
.max()
.expect("Slice had no items")
}
fn main() {
// For all possible permutations of the numbers
let nums: [usize; 10] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// Generate all permutations using itertools, then parallelize the score calculation
let scores: Vec<usize> = nums
.iter()
.permutations(nums.len())
// Convert to parallel iterator
.par_bridge()
.map(|perm| {
// Convert Vec<&usize> to Vec<usize> for calc_max_score
let owned_perm: Vec<usize> = perm.into_iter().copied().collect();
calc_max_score(&owned_perm)
})
.collect();
// Calculate the mean of the scores
let mean = scores.iter().sum::<usize>() as f64 / scores.len() as f64;
println!("Mean score: {}", mean);
println!("Total permutations processed: {}", scores.len());
// Show some statistics
if let (Some(min_score), Some(max_score)) = (scores.iter().min(), scores.iter().max()) {
println!("Score range: {} to {}", min_score, max_score);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment