Export prisoner data to JSON.

This commit is contained in:
2022-07-02 12:04:43 +02:00
parent 33cb815296
commit b9c2ae82d6
3 changed files with 68 additions and 4 deletions

View File

@ -25,6 +25,7 @@
extern crate rand;
use structopt::StructOpt;
use serde::{Serialize,Deserialize};
// define the commandline parameters
#[derive(StructOpt)]
@ -33,18 +34,24 @@ struct Opt
{
#[structopt(short, long, default_value="100", help = "The number of inmates in the problem")]
size:u32,
#[structopt(long, help = "Print to stdout the JSON for the results")]
json:bool,
}
// define the prisoner data
#[derive(Serialize, Deserialize)]
struct Prisoner
{
// prisoner id number
id:u32,
// if the prisoner found his number
found:bool,
// number of attempt he found it in
attempts:u32,
}
fn main() {
fn main()
{
// read the commandline parameters
let opts = Opt::from_args();
@ -77,6 +84,8 @@ fn main() {
{
// create the prisoner for index `i`
let mut prisoner_i = Prisoner {
// assign the id number
id: i,
// assume the prisoner does not find his box
found: false,
// set number of attempts to 0
@ -108,12 +117,20 @@ fn main() {
}
// if any prisoner has not found their number
if prisoners.iter().any(|i| !i.found)
if !opts.json
{
println!("failure");
if prisoners.iter().any(|i| !i.found)
{
println!("failure");
}
else
{
println!("success");
}
}
else
{
println!("success");
let out_json = serde_json::to_string(&prisoners).unwrap();
println!("{}", out_json);
}
}