How to resolve the algorithm ABC problem step by step in the Rust programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm ABC problem step by step in the Rust programming language

Table of Contents

Problem Statement

You are given a collection of ABC blocks   (maybe like the ones you had when you were a kid).
There are twenty blocks with two letters on each block. A complete alphabet is guaranteed amongst all sides of the blocks. The sample collection of blocks:

Write a function that takes a string (word) and determines whether the word can be spelled with the given collection of blocks.

The rules are simple:

Let's start with the solution:

Step by Step solution about How to resolve the algorithm ABC problem step by step in the Rust programming language

Source code in the rust programming language

use std::iter::repeat;

fn rec_can_make_word(index: usize, word: &str, blocks: &[&str], used: &mut[bool]) -> bool {
    let c = word.chars().nth(index).unwrap().to_uppercase().next().unwrap();
    for i in 0..blocks.len() {
        if !used[i] && blocks[i].chars().any(|s| s == c) {
            used[i] = true;
            if index == 0 || rec_can_make_word(index - 1, word, blocks, used) {
                return true;
            }
            used[i] = false;
        }
    }
    false
}

fn can_make_word(word: &str, blocks: &[&str]) -> bool {
    return rec_can_make_word(word.chars().count() - 1, word, blocks, 
                             &mut repeat(false).take(blocks.len()).collect::<Vec<_>>());
}

fn main() {
    let blocks = [("BO"), ("XK"), ("DQ"), ("CP"), ("NA"), ("GT"), ("RE"), ("TG"), ("QD"), ("FS"), 
                  ("JW"), ("HU"), ("VI"), ("AN"), ("OB"), ("ER"), ("FS"), ("LY"), ("PC"), ("ZM")];
    let words = ["A", "BARK", "BOOK", "TREAT", "COMMON", "SQUAD", "CONFUSE"];
    for word in &words {
        println!("{} -> {}", word, can_make_word(word, &blocks))
    }
}

  

You may also check:How to resolve the algorithm Optional parameters step by step in the Julia programming language
You may also check:How to resolve the algorithm Maze solving step by step in the Ruby programming language
You may also check:How to resolve the algorithm Ranking methods step by step in the C# programming language
You may also check:How to resolve the algorithm Conditional structures step by step in the Arturo programming language
You may also check:How to resolve the algorithm Averages/Simple moving average step by step in the Quackery programming language