Bladeren bron

some changes

ayush99336 1 week geleden
bovenliggende
commit
020e63c936

+ 8 - 0
10.ToDoCLI/Cargo.toml

@@ -0,0 +1,8 @@
+[package]
+name = "todocli"
+version = "0.1.0"
+edition = "2024"
+
+[dependencies]
+serde = { version = "1.0.226", features = ["derive"] }
+serde_json = "1.0.145"

+ 120 - 0
10.ToDoCLI/src/main.rs

@@ -0,0 +1,120 @@
+use serde::{Deserialize, Serialize};
+use serde_json;
+use std::fs::{self, File};
+use std::io::{self, Write};
+#[derive(Serialize, Deserialize, Debug)]
+struct Task {
+    id: usize,
+    description: String,
+    completed: bool,
+}
+fn main() {
+    let mut tasks: Vec<Task> = load_tasks();
+    loop {
+        println!("\n To-Do List Menu");
+        println!("1. Add Task");
+        println!("2. View Tasks");
+        println!("3. Mark Task as Completed");
+        println!("4. Delete Task");
+        println!("5. Exit");
+        let choice = get_input("Enter your choice: ");
+        match choice.as_str() {
+            "1" => add_task(&mut tasks),
+            "2" => view_tasks(&tasks),
+            "3" => mark_task_completed(&mut tasks),
+            "4" => delete_task(&mut tasks),
+            "5" => {
+                save_tasks(&tasks);
+                println!("Tasks saved. Exiting...");
+                break;
+            }
+            _ => println!("Invalid choice, please try again."),
+        }
+    }
+}
+
+fn get_input(prompt: &str) -> String {
+    print!("{}", prompt);
+    io::stdout().flush().unwrap();
+    let mut input = String::new();
+    io::stdin()
+        .read_line(&mut input)
+        .expect("Failed to read line");
+    input.trim().to_string()
+}
+fn add_task(tasks: &mut Vec<Task>) {
+    let description = get_input("Enter task description: ");
+    let id = tasks.len() + 1;
+    let new_task = Task {
+        id,
+        description,
+        completed: false,
+    };
+    tasks.push(new_task);
+    println!("Task added successfully.");
+}
+fn view_tasks(tasks: &Vec<Task>) {
+    if tasks.is_empty() {
+        println!("No tasks available.");
+    } else {
+        for task in tasks {
+            let status = if task.completed {
+                "Completed"
+            } else {
+                "Pending"
+            };
+            println!(
+                "ID: {}, Description: {}, Status: {}",
+                task.id, task.description, status
+            );
+        }
+    }
+}
+//load tasks from file
+fn load_tasks() -> Vec<Task> {
+    match fs::read_to_string("tasks.json") {
+        Ok(content) => serde_json::from_str(&content).unwrap_or_else(|_| Vec::<Task>::new()),
+        Err(_) => Vec::new(),
+    }
+}
+//save tasks to file
+fn save_tasks(tasks: &Vec<Task>) {
+    let serialized = serde_json::to_string_pretty(tasks).expect("Failed to serialize tasks");
+    let mut file = File::create("tasks.json").expect("Failed to create file");
+    file.write_all(serialized.as_bytes())
+        .expect("Failed to write tasks to file");
+}
+
+//Mark task as completed
+fn mark_task_completed(tasks: &mut Vec<Task>) {
+    let id_input = get_input("Enter task ID to mark as completed: ");
+    if let Ok(id) = id_input.parse::<usize>() {
+        if let Some(task) = tasks.iter_mut().find(|t| t.id == id) {
+            task.completed = true;
+            println!("Task marked as completed.");
+        } else {
+            println!("Task with ID {} not found.", id);
+        }
+    } else {
+        println!("Invalid ID input.");
+    }
+}
+//Delete task
+fn delete_task(tasks: &mut Vec<Task>) {
+    let id_input = get_input("Enter task ID to delete: ");
+    if let Ok(id) = id_input.parse::<usize>() {
+        if let Some(pos) = tasks.iter().position(|t| t.id == id) {
+            let removed_task = tasks.remove(pos);
+            println!("Task '{}' deleted successfully.", removed_task.description);
+            
+            // Re-index remaining tasks to maintain sequential IDs
+            for (index, task) in tasks.iter_mut().enumerate() {
+                task.id = index + 1;
+            }
+        } else {
+            println!("Task with ID {} not found.", id);
+        }
+    } else {
+        println!("Invalid ID input.");
+    }
+}

+ 7 - 0
10.ToDoCLI/tasks.json

@@ -0,0 +1,7 @@
+[
+  {
+    "id": 1,
+    "description": "Sona Hai",
+    "completed": false
+  }
+]

+ 6 - 0
2temperature_converter/Cargo.toml

@@ -0,0 +1,6 @@
+[package]
+name = "temp_converter"
+version = "0.1.0"
+edition = "2024"
+
+[dependencies]

+ 62 - 0
2temperature_converter/src/main.rs

@@ -0,0 +1,62 @@
+use std::io;
+
+fn main() {
+    println!("Welcome to temperature controller");
+    println!("1: Celcius to Fahrenheit");
+    println!("2: Celcius to Fahrenheit");
+    println!("Please select an option (1 or 2):");
+
+    let mut choice = String::new();
+    io::stdin()
+        .read_line(&mut choice)
+        .expect("Failed to read input");
+
+    let choice: u32 = match choice.trim().parse() {
+        Ok(num) => num,
+        Err(_) => {
+            println!("Invalid choice. Please enter 1 or 2.");
+            return;
+        }
+    };
+    if choice == 1 {
+        celcius_to_fahrenheit();
+    } else if choice == 2 {
+        fahrenheit_to_celcius();
+    } else {
+        println!("Invalid choice. Please enter 1 or 2.");
+    }
+}
+
+fn celcius_to_fahrenheit() {
+    println!("Enter temperature in celcius");
+    let mut temp = String::new();
+    io::stdin()
+        .read_line(&mut temp)
+        .expect("Failed to read Input");
+    let temp: f64 = match temp.trim().parse() {
+        Ok(num) => num,
+        Err(_) => {
+            println!("Enter a valid number for the temperature!");
+            return;
+        }
+    };
+    let fahrenheit = (temp * 9.0 / 5.0) + 32.0;
+    println!("The temperature in Fahrenheit is {:.2}F ", fahrenheit);
+}
+
+fn fahrenheit_to_celcius() {
+    println!("Enter temperature in celcius");
+    let mut temp = String::new();
+    io::stdin()
+        .read_line(&mut temp)
+        .expect("Failed to read Input");
+    let temp: f64 = match temp.trim().parse() {
+        Ok(num) => num,
+        Err(_) => {
+            println!("Enter a valid number for the temperature!");
+            return;
+        }
+    };
+    let celcius = (temp - 32.0) * 5.0 / 9.0;
+    println!("The temperature in Celcius is {:.2}C", celcius);
+}

+ 6 - 0
3SimpleCalculator/Cargo.toml

@@ -0,0 +1,6 @@
+[package]
+name = "simplecalculator"
+version = "0.1.0"
+edition = "2024"
+
+[dependencies]

+ 59 - 0
3SimpleCalculator/src/main.rs

@@ -0,0 +1,59 @@
+use std::io;
+
+fn main() {
+    println!("Simple Calculator");
+    println!("Available operations: +, -, *, /");
+    println!("enter your operation with spaces eg., (5 + 3):");
+    let mut input = String::new();
+    io::stdin()
+        .read_line(&mut input)
+        .expect("Enter a valid operation.");
+    let tokens: Vec<&str> = input.trim().split_whitespace().collect();
+    if tokens.len() != 3 {
+        println!(
+            "Invalid input, Please follow the format: number <space> operator <space> number "
+        );
+        return;
+    }
+    println!("Vecor is {:?}", tokens);
+
+    let num1: f64 = match tokens[0].parse() {
+        Ok(n) => n,
+        Err(_) => {
+            println!("Enter first number");
+            return;
+        }
+    };
+    let num2: f64 = match tokens[2].parse() {
+        Ok(n) => n,
+        Err(_) => {
+            println!("Enter Second number");
+            return;
+        }
+    };
+    let operator = tokens[1];
+    match operator {
+        "+" => {
+            println!("Result: {}", num1 + num2);
+        }
+        "-" => {
+            println!("Result: {}", num1 - num2);
+        }
+        "*" => {
+            println!("Result: {}", num1 * num2);
+        }
+        "/" => {
+            if num2 == 0.0 {
+                println!("Cannot divide by zero");
+                return;
+            }
+            println!("Result: {}", num1 / num2);
+        }
+        _ => {
+            println!(
+                "Invalid operator {}, Please use one of +, -, *, /",
+                operator
+            );
+        }
+    };
+}

+ 7 - 0
4.GuessingGame/Cargo.toml

@@ -0,0 +1,7 @@
+[package]
+name = "guessinggame"
+version = "0.1.0"
+edition = "2024"
+
+[dependencies]
+rand = "0.9.2"

+ 29 - 0
4.GuessingGame/src/main.rs

@@ -0,0 +1,29 @@
+use rand::{self, Rng};
+use std::cmp::Ordering;
+use std::io;
+fn main() {
+    println!("Welccome to guessing game");
+    let secret = rand::rng().random_range(1..=100);
+
+    loop {
+        let mut guess = String::new();
+        println!("Please input your guess:");
+        io::stdin()
+            .read_line(&mut guess)
+            .expect("Failed to take input");
+        let guess: u32 = guess.trim().parse().expect("Please type a number");
+        println!("You Guessed : {}", guess);
+
+        match guess.cmp(&secret) {
+            Ordering::Less => {
+                println!("Too Small")
+            }
+            Ordering::Greater => println!("Too Big"),
+            Ordering::Equal => {
+                println!("You Win");
+                println!("The secret number was : {}", secret);
+                break;
+            }
+        }
+    }
+}

+ 6 - 0
5.WordCounter/Cargo.toml

@@ -0,0 +1,6 @@
+[package]
+name = "word_counter"
+version = "0.1.0"
+edition = "2024"
+
+[dependencies]

+ 1 - 0
5.WordCounter/sample.txt

@@ -0,0 +1 @@
+asdasf srasf asdas asdasd asdasd asfcxvx sadasd

+ 32 - 0
5.WordCounter/src/main.rs

@@ -0,0 +1,32 @@
+use std::env;
+use std::fs::File;
+#[allow(unused)]
+use std::io::{self, Read};
+
+fn main() {
+    //collect cl arguments
+    let args: Vec<String> = env::args().collect();
+    if args.len() != 2 {
+        println!("Use Cargo run <filepath>");
+    }
+    // println!("Hello, world!");
+    let file_path = &args[1];
+    println!("Reading file: {}!", file_path);
+    let mut file = match File::open(file_path) {
+        Ok(file) => file,
+        Err(err) => {
+            println!("Error opening the file {}", err);
+            return;
+        }
+    };
+    let mut contents = String::new();
+    if let Err(err) = file.read_to_string(&mut contents) {
+        println!("Error reading the file {} ", err);
+        return;
+    }
+    let word_count = count_words(&contents);
+    println!("Word COunt is {}", word_count);
+}
+fn count_words(text: &str) -> usize {
+    text.split_whitespace().count()
+}

+ 6 - 0
6.BMI/Cargo.toml

@@ -0,0 +1,6 @@
+[package]
+name = "bmi_calculator"
+version = "0.1.0"
+edition = "2024"
+
+[dependencies]

+ 47 - 0
6.BMI/src/main.rs

@@ -0,0 +1,47 @@
+use std::{f64, io};
+
+fn main() {
+    println!("Welcome to BMI Calculator");
+    println!("Please Enter Weight in KG");
+    let weight: f64 = match get_input_as_f64() {
+        Some(value) => value,
+        None => {
+            println!("Failed to take input for weight please enter a valid number");
+            return;
+        }
+    };
+    println!("Please Enter Height in meters");
+    let height: f64 = match get_input_as_f64() {
+        Some(value) => value,
+        None => {
+            println!("Failed to take input for weight please enter a valid number");
+            return;
+        }
+    };
+
+    let bmi = calculate_bmi(&weight, &height);
+    println!("Your BMI is {bmi}");
+    let result = classify_bmi(bmi);
+    println!("Your BMI is in {result} category");
+}
+
+fn get_input_as_f64() -> Option<f64> {
+    let mut wt = String::new();
+    io::stdin().read_line(&mut wt).expect("msg");
+    let wt = wt.trim().parse::<f64>().expect("Please enter a number");
+    return Some(wt);
+}
+fn calculate_bmi(&weight: &f64, &height: &f64) -> f64 {
+    return weight / (height * height);
+}
+fn classify_bmi(bmi: f64) -> &'static str {
+    if bmi < 18.5 {
+        "UnderWeight"
+    } else if bmi >= 18.5 && bmi <= 24.9 {
+        "Normal Weight"
+    } else if bmi >= 25.0 && bmi <= 29.9 {
+        "OverWeight"
+    } else {
+        "Obesity"
+    }
+}

+ 6 - 0
7.PalindromeCheck/Cargo.toml

@@ -0,0 +1,6 @@
+[package]
+name = "palindrome"
+version = "0.1.0"
+edition = "2024"
+
+[dependencies]

+ 29 - 0
7.PalindromeCheck/src/main.rs

@@ -0,0 +1,29 @@
+use std::io;
+fn main() {
+    println!("Palindrome Checker");
+    let mut input = String::new();
+    io::stdin()
+        .read_line(&mut input)
+        .expect("Unable to read input");
+    let cleaned_input: String = clean_string(&input);
+    println!("Cleaned Input is {cleaned_input}");
+    if cleaned_input.is_empty() {
+        println!("Please enter a valid non emptyy string");
+        return;
+    }
+    if is_palindrome(&cleaned_input) {
+        println!("{} is palindrome", input.trim());
+    } else {
+        println!("{} is not palindrome", input.trim());
+    }
+}
+fn clean_string(input: &str) -> String {
+    input
+        .chars()
+        .filter(|c| c.is_alphanumeric())
+        .map(|c| c.to_ascii_lowercase().to_string())
+        .collect::<String>()
+}
+fn is_palindrome(s: &str) -> bool {
+    s == s.chars().rev().collect::<String>()
+}

+ 6 - 0
8.Fibonacci/Cargo.toml

@@ -0,0 +1,6 @@
+[package]
+name = "fibonacci"
+version = "0.1.0"
+edition = "2024"
+
+[dependencies]

+ 38 - 0
8.Fibonacci/src/main.rs

@@ -0,0 +1,38 @@
+use std::io;
+
+fn main() {
+    println!("Fibonacci Sequence Generator!");
+    println!("Enter the number of terms you want to generate");
+    let num_terms = match get_input_as_u32() {
+        Some(value) => value,
+        None => {
+            println!("Unable to get input");
+            return;
+        }
+    };
+    if num_terms == 0 {
+        println!("Number of terms should be greater than 0");
+        return;
+    }
+    let sequence = fib_generator(&num_terms);
+    println!("The sequence generated is {:?}", sequence);
+}
+fn get_input_as_u32() -> Option<u32> {
+    let mut input = String::new();
+    io::stdin()
+        .read_line(&mut input)
+        .expect("Failed to take input");
+    let input = input.trim().parse::<u32>().expect("msg");
+    Some(input)
+}
+fn fib_generator(num: &u32) -> Vec<u32> {
+    if *num == 1 {
+        return vec![0];
+    }
+    let mut seq: Vec<u32> = Vec::from([0, 1]);
+    for i in 2..*num {
+        let x = seq[i as usize - 1] + seq[i as usize - 2];
+        seq.push(x);
+    }
+    seq
+}

+ 1 - 0
9.prime_checker/.gitignore

@@ -0,0 +1 @@
+/target

+ 6 - 0
9.prime_checker/Cargo.toml

@@ -0,0 +1,6 @@
+[package]
+name = "prime_checker"
+version = "0.1.0"
+edition = "2021"
+
+[dependencies]

+ 59 - 0
9.prime_checker/src/main.rs

@@ -0,0 +1,59 @@
+use std::io;
+
+fn main() {
+    println!("🔢 Prime Number Checker");
+    println!("Enter a positive integer to check if it's prime:");
+
+    let number = match get_input_as_u32() {
+        Some(value) => value,
+        None => {
+            println!("❌ Invalid input. Please enter a positive integer.");
+            return;
+        }
+    };
+
+    if number <= 1 {
+        println!("❌ The number must be greater than 1.");
+        return;
+    }
+
+    if is_prime(number) {
+        println!("✅ {} is a prime number.", number);
+    } else {
+        println!("❌ {} is not a prime number.", number);
+    }
+}
+
+/// Reads user input and attempts to parse it as u32
+fn get_input_as_u32() -> Option<u32> {
+    let mut input = String::new();
+    io::stdin()
+        .read_line(&mut input)
+        .expect("❌ Failed to read input");
+
+    match input.trim().parse::<u32>() {
+        Ok(value) => Some(value),
+        Err(_) => None,
+    }
+}
+
+/// Checks if a number is prime
+fn is_prime(n: u32) -> bool {
+    if n <= 1 {
+        return false;
+    }
+    if n == 2 {
+        return true; // 2 is the only even prime number
+    }
+    if n % 2 == 0 {
+        return false; // Eliminate even numbers greater than 2
+    }
+
+    let limit = (n as f64).sqrt() as u32 + 1;
+    for i in 3..limit {
+        if n % i == 0 {
+            return false;
+        }
+    }
+    true
+}

+ 0 - 2
README.md

@@ -1,2 +0,0 @@
-# 100daysofrust
-

+ 6 - 0
hello_rust/Cargo.toml

@@ -0,0 +1,6 @@
+[package]
+name = "hello_rust"
+version = "0.1.0"
+edition = "2024"
+
+[dependencies]

+ 4 - 0
hello_rust/src/main.rs

@@ -0,0 +1,4 @@
+fn main() {
+    println!("Hello, Rust! Welcome to day 1");
+    println!("Welcome Back!!!");
+}