Learning Rust Through DSA: The First Steps

Learning Rust Through DSA: The First Steps

I have always had a fascination with Rust. Everyone is always praising Rust and saying how it will be the future and how big tech companies are integrating Rust in their systems. I always wanted to learn it but learning Python first and trying to learn C++ in my university Computer Science-1 course left me traumatized. I am kind of scared of going low level now. But understanding low level concepts is fundamental in building a career in computer science.

So.................. I made a genius plan. Since I have to learn Data Structures and Algorithms at some point. How about I learn those two at once. Yeah, it will be tough, and it might take me longer to learn them both together than to just learn and practice them individually. I am up for the challenge.
Here is what I am going to do.
-> I will learn a DSA concept first.
-> I will implement it in python.
-> I will try to implement it in Rust and learn all the necessary syntaxes along the way

First Concept.
Sum of Two Digits Problem:
Yeah..... I know it is way too basic, but we have to start at some place.
Here's the question:
Compute the sum of two single digit numbers.
Input: Two single digit numbers.
Output: The sum of these numbers.

It might look easy on paper or with Python but doing it in Rust was more complicated than I thought. Taking inputs in Rust isn't as simple as just writing input(). There are a lot of extra work that needs to be done.

For example, we can't directly take an int as input. We have to create an empty string. Then use the readline method to enter a value into the empty string. Then we have to remove the whitespaces create an error handling system then parse the string as int. Here's the final code.

use std::io;

fn main() {
    let mut input = String::new();
    io::stdin().read_line(&mut input).expect("Failed to read input.");

    // Split the input line into words and parse them as integers
    let mut inputs = input.trim().split_whitespace();
    let input1: i32 = inputs.next().unwrap().parse().expect("Please enter a valid integer");
    let input2: i32 = inputs.next().unwrap().parse().expect("Please enter a valid integer");
    let sum: i32 = input1 + input2;

    println!("{}", sum);
}

Now, we can move on to the next problem.

Maximum Pairwise Product Problem:
Find the maximum product of two distinct numbers in a sequence of non-negative integers.
Input: An integer n and a sequence of n non-negative integers.
Output: The maximum value that can be obtained by multiplying two different elements from the sequence.

Sample 1.
Input:
3 1 2 3
Output: 6

The easiest way to solve this is by using the Naive Algorithm.

  1. Initialize product to 0

  2. Loop i from 1 to n:

    1. Loop j from 1 to n:

      1. If i is not equal to j:

        1. If product is less than A[i] * A[j]:

          • Set product to A[i] * A[j]
  3. Return product

Firstly, we have to import the necessary modules. Here we are going to be using use std::io;

Then we take the necessary inputs.

    let mut n = String::new();
        io::stdin().read_line(&mut n).expect("Failed to read line");

    let mut input = String::new();
        io::stdin().read_line(&mut input).expect("Failed to read line");

Since we are taking multiple values at once, we will declare a vector.

let numbers: Vec<u64> = input
        .split_whitespace()
        .map(|num| num.parse().expect("Failed"))
        .collect();

I am not going in depth in the vector declaration syntax. Then we use a loop to find the two biggest number in the vector. We can easily find out the product by multiplying them. Here's how the code looks after I'm done.

use std::io;

fn main() {
    let mut n = String::new();
    io::stdin().read_line(&mut n).expect("Failed to read line");
    let mut input = String::new();
    io::stdin().read_line(&mut input).expect("Failed to read line");

    let numbers: Vec<u64> = input
        .split_whitespace()
        .map(|num| num.parse().expect("Failed"))
        .collect();

    let mut max1 = 0;
    let mut max2 = 0;

    for &number in &numbers {
        if number > max1 {
            max2 = max1;
            max1 = number;
        } 
        else if number > max2 {
            max2 = number;
        }
    }

    let result = max1 * max2;
    println!("{}", result);
}

This is where I will stop for today. I'll be learning new stuff, and I will keep updating my progress in this blog.