-
-
Save RandyMcMillan/31e72a7efba015fd1fdfe39f83b97b76 to your computer and use it in GitHub Desktop.
logic_gates.rs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /// A collection of digital logic gate algorithms. | |
| struct LogicGates; | |
| impl LogicGates { | |
| /// NOT gate: The output is the opposite of the input. | |
| fn not(a: u8) -> u8 { | |
| match a { | |
| 0 => 1, | |
| _ => 0, | |
| } | |
| } | |
| /// AND gate: Output is 1 only if both inputs are 1. | |
| fn and(a: u8, b: u8) -> u8 { | |
| if a == 1 && b == 1 { 1 } else { 0 } | |
| } | |
| /// OR gate: Output is 0 only if both inputs are 0. | |
| fn or(a: u8, b: u8) -> u8 { | |
| if a == 1 || b == 1 { 1 } else { 0 } | |
| } | |
| /// NAND gate: An AND gate followed by a NOT gate. | |
| fn nand(a: u8, b: u8) -> u8 { | |
| Self::not(Self::and(a, b)) | |
| } | |
| /// NOR gate: An OR gate followed by a NOT gate. | |
| fn nor(a: u8, b: u8) -> u8 { | |
| Self::not(Self::or(a, b)) | |
| } | |
| } | |
| fn main() { | |
| let inputs = [(0, 0), (0, 1), (1, 0), (1, 1)]; | |
| println!("--- Logic Gate Truth Tables ---"); | |
| // NOT Gate | |
| println!("\nNOT Gate:"); | |
| println!("INPUT | OUTPUT"); | |
| for i in [0, 1] { | |
| println!(" {} | {}", i, LogicGates::not(i)); | |
| } | |
| // AND Gate | |
| println!("\nAND Gate:"); | |
| println!("A | B | OUTPUT"); | |
| for (a, b) in inputs { | |
| println!("{} | {} | {}", a, b, LogicGates::and(a, b)); | |
| } | |
| // OR Gate | |
| println!("\nOR Gate:"); | |
| println!("A | B | OUTPUT"); | |
| for (a, b) in inputs { | |
| println!("{} | {} | {}", a, b, LogicGates::or(a, b)); | |
| } | |
| // NAND Gate | |
| println!("\nNAND Gate:"); | |
| println!("A | B | OUTPUT"); | |
| for (a, b) in inputs { | |
| println!("{} | {} | {}", a, b, LogicGates::nand(a, b)); | |
| } | |
| // NOR Gate | |
| println!("\nNOR Gate:"); | |
| println!("A | B | OUTPUT"); | |
| for (a, b) in inputs { | |
| println!("{} | {} | {}", a, b, LogicGates::nor(a, b)); | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://play.rust-lang.org/?version=stable&mode=debug&edition=2024&gist=fa75b119c9a1069e7691e20d30e25ba8