// tag::play_recursive[]
/// Play Recursive Combat
///
/// Returns a tuple of a flag indicating the winning player (true for player 1, false for player
/// two) and the winning player's score
:play_recursive[]
Play Recursive Combat

Returns a tuple of a flag indicating the winning player (true for player 1, false for player
two) and the winning player's score
: play_recursive [] Play Recursive Combat Returns a tuple of a flag indicating the winning player ( true for player 1 false for player two ) and the winning player ' s score
pub fn play_recursive(mut decks: (VecDeque<usize>, VecDeque<usize>)) -> (bool, usize) {
    // holds games played before
    let mut seen = HashSet::new();
    while !decks.0.is_empty() && !decks.1.is_empty() {
        // make sure game does not repeat
        if seen.contains(&decks) {
            return (true, calc_score(&decks.0));
        }
        seen.insert(decks.clone());
        // deal first card
        let a = decks.0.pop_front().unwrap();
        let b = decks.1.pop_front().unwrap();
        let mut a_wins = a > b;
        if a <= decks.0.len() && b <= decks.1.len() {
            // recurse
            a_wins = play_recursive((decks.0.iter().take(a).cloned().collect(),
                                     decks.1.iter().take(b).cloned().collect())).0;
        }
        // winner takes cards
        if a_wins {
            decks.0.push_back(a);
            decks.0.push_back(b);
        } else {
            decks.1.push_back(b);
            decks.1.push_back(a);
        }
    }
    (!decks.0.is_empty(), calc_score(if decks.0.is_empty() { &decks.1 } else { &decks.0 }))
}
pub fn play_recursive ( mut decks : ( VecDeque < usize > , VecDeque < usize > ) ) -> ( bool , usize ) { // holds games played before let mut seen = HashSet :: new ( ) ; while ! decks . 0 . is_empty ( ) && ! decks . 1 . is_empty ( ) { // make sure game does not repeat if seen . contains ( & decks ) { return ( true , calc_score ( & decks . 0 ) ) ; } seen . insert ( decks . clone ( ) ) ; // deal first card let a = decks . 0 . pop_front ( ) . unwrap ( ) ; let b = decks . 1 . pop_front ( ) . unwrap ( ) ; let mut a_wins = a > b ; if a <= decks . 0 . len ( ) && b <= decks . 1 . len ( ) { // recurse a_wins = play_recursive ( ( decks . 0 . iter ( ) . take ( a ) . cloned ( ) . collect ( ) , decks . 1 . iter ( ) . take ( b ) . cloned ( ) . collect ( ) ) ) . 0 ; } // winner takes cards if a_wins { decks . 0 . push_back ( a ) ; decks . 0 . push_back ( b ) ; } else { decks . 1 . push_back ( b ) ; decks . 1 . push_back ( a ) ; } } ( ! decks . 0 . is_empty ( ) , calc_score ( if decks . 0 . is_empty ( ) { & decks . 1 } else { & decks . 0 } ) ) }
tag::play_recursive[]
Play Recursive Combat
tag :: play_recursive [] Play Recursive Combat
decks
(VecDeque<usize>, VecDeque<usize>)