Skip to content

Commit

Permalink
Median example
Browse files Browse the repository at this point in the history
  • Loading branch information
matthiasgoergens committed Dec 13, 2024
1 parent 475e0c6 commit 7f38f61
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 1 deletion.
22 changes: 21 additions & 1 deletion ceno_host/tests/test_elf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ fn test_sorting() -> Result<()> {
let mut hints = CenoStdin::default();
let mut rng = rand::thread_rng();

// Provide some random numbers to sort:
// Provide some random numbers to sort.
hints.write(&(0..1000).map(|_| rng.gen::<u32>()).collect::<Vec<_>>())?;

let all_messages = ceno_host::run(CENO_PLATFORM, ceno_examples::sorting, &hints);
Expand All @@ -109,6 +109,26 @@ fn test_sorting() -> Result<()> {
Ok(())
}

#[test]
fn test_median() -> Result<()> {
use rand::Rng;
let mut hints = CenoStdin::default();
let mut rng = rand::thread_rng();

// Provide some random numbers to find the median of.
let mut nums = (0..1000).map(|_| rng.gen::<u32>()).collect::<Vec<_>>();
hints.write(&nums)?;
nums.sort();
hints.write(&nums[nums.len() / 2])?;

let all_messages = ceno_host::run(CENO_PLATFORM, ceno_examples::median, &hints);
assert!(!all_messages.is_empty());
for (i, msg) in enumerate(&all_messages) {
println!("{i}: {msg}");
}
Ok(())
}

fn run(state: &mut VMState) -> Result<Vec<StepRecord>> {
let steps = state.iter_until_halt().collect::<Result<Vec<_>>>()?;
eprintln!("Emulator ran for {} steps.", steps.len());
Expand Down
1 change: 1 addition & 0 deletions examples-builder/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ const EXAMPLES: &[&str] = &[
"ceno_rt_panic",
"hints",
"sorting",
"median",
];
const CARGO_MANIFEST_DIR: &str = env!("CARGO_MANIFEST_DIR");

Expand Down
20 changes: 20 additions & 0 deletions guest/examples/examples/median.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
//! Find the median of a collection of numbers.
//!
//! Of course, we are asking our good friend, the host, for help, but we still need to verify the answer.
#![no_main]
#![no_std]

extern crate ceno_rt;
use ceno_rt::println;
use core::fmt::Write;
use rkyv::{Archived, vec::ArchivedVec};

ceno_rt::entry!(main);
fn main() {
let numbers: &ArchivedVec<u32> = ceno_rt::read();
let median_candidate: &Archived<u32> = ceno_rt::read();
let median_candidate = &&median_candidate.to_native();
let smaller = numbers.into_iter().filter(move |x| x < median_candidate).count();
assert_eq!(smaller, numbers.len() / 2);
println!("{}", median_candidate);
}

0 comments on commit 7f38f61

Please sign in to comment.