Ad

Using split method from the standard library is boring :)
also improved edge cases so it behaves like standard library

Code
Diff
  • fn split(string: &str, separator: char) -> Vec<&str> {
        let mut split = Vec::new();
        let mut i = 0;
        
        for (j, c) in string.char_indices() {
            if c == separator {
                let slice = &string[i..j];
                split.push(slice);
                i = j + 1;
            }
        }
        
        
        split.push(&string[i..]);
        return split;
    }
    
    • fn split(string: &str, separator: char) -> Vec<&str> {
    • string.split(separator).collect()
    • let mut split = Vec::new();
    • let mut i = 0;
    • for (j, c) in string.char_indices() {
    • if c == separator {
    • let slice = &string[i..j];
    • split.push(slice);
    • i = j + 1;
    • }
    • }
    • split.push(&string[i..]);
    • return split;
    • }
Code
Diff
  • fn remove_symbols(s: &str) -> String {
        return s
            .chars()
            .filter(|&c| c.is_alphanumeric() || c == ' ')
            .collect();
    }
    • function removeSymbols(str) {
    • const regEx = /[&%!@=\*£]/g;
    • const newStr = str.replaceAll(regEx, "");
    • return (newStr);
    • fn remove_symbols(s: &str) -> String {
    • return s
    • .chars()
    • .filter(|&c| c.is_alphanumeric() || c == ' ')
    • .collect();
    • }
Functional Programming
Code
Diff
  • fn prime_factors(n: u32) -> Vec<u32> {
        let factors: Vec<u32> = (2..=n).filter(|i| n % i == 0).collect();
        return factors
            .into_iter()
            .take_while(|i| i * i <= n)
            .find(|x| n % x == 0)
            .map(|i| {
                let mut sub_factors = vec![i];
                sub_factors.extend(prime_factors(n / i));
                sub_factors
            })
            .unwrap_or(vec![n])
    }
    • fn prime_factors(number: u32) -> Vec<u32> {
    • match (2..number).find(|divisor| number % divisor == 0) {
    • Some(factor) => [vec![factor], prime_factors(number / factor)].concat(),
    • None => vec![number],
    • }
    • }
    • fn prime_factors(n: u32) -> Vec<u32> {
    • let factors: Vec<u32> = (2..=n).filter(|i| n % i == 0).collect();
    • return factors
    • .into_iter()
    • .take_while(|i| i * i <= n)
    • .find(|x| n % x == 0)
    • .map(|i| {
    • let mut sub_factors = vec![i];
    • sub_factors.extend(prime_factors(n / i));
    • sub_factors
    • })
    • .unwrap_or(vec![n])
    • }

Changes

  • the function now only accepts references to the input cuz duh
  • the types has to implement copy so basically all integers from the standard library (RIP bigint)
Code
Diff
  • use num::Num;
    
    fn sum<'a, S>(arr: impl IntoIterator<Item = &'a S>) -> S where S: 'a + Num + Copy {
        let mut sum = S::zero();
        for i in arr {
            sum = sum + *i;
        }
        return sum;
    }
    • use std::iter::Sum;
    • use num::Num;
    • fn sum<T, S>(arr: T) -> S where T: IntoIterator<Item = S>, S: Sum {
    • return arr.into_iter().sum();
    • fn sum<'a, S>(arr: impl IntoIterator<Item = &'a S>) -> S where S: 'a + Num + Copy {
    • let mut sum = S::zero();
    • for i in arr {
    • sum = sum + *i;
    • }
    • return sum;
    • }
Code
Diff
  • use std::iter::Sum;
    
    fn sum<T, S>(arr: T) -> S where T: IntoIterator<Item = S>, S: Sum {
        return arr.into_iter().sum();
    }
    • use std::ops::Add;
    • use num::Zero;
    • use std::iter::Sum;
    • fn sum<T, S>(arr: T) -> S where T: IntoIterator<Item = S>, S: Add<Output = S> + Zero {
    • let mut sum: S = Zero::zero();
    • for i in arr {
    • sum = sum + i;
    • }
    • return sum;
    • fn sum<T, S>(arr: T) -> S where T: IntoIterator<Item = S>, S: Sum {
    • return arr.into_iter().sum();
    • }
Code
Diff
  • use std::ops::Add;
    use num::Zero;
    
    fn sum<T, S>(arr: T) -> S where T: IntoIterator<Item = S>, S: Add<Output = S> + Zero {
        let mut sum: S = Zero::zero();
        for i in arr {
            sum = sum + i;
        }
        return sum;
    }
    • def sum(arr):
    • result = 0
    • for i in arr:
    • result += i
    • return result
    • use std::ops::Add;
    • use num::Zero;
    • fn sum<T, S>(arr: T) -> S where T: IntoIterator<Item = S>, S: Add<Output = S> + Zero {
    • let mut sum: S = Zero::zero();
    • for i in arr {
    • sum = sum + i;
    • }
    • return sum;
    • }
Code
Diff
  • use std::io::*;
    
    fn kashikashi() -> Result<()> {
        const BUFF: [u8; 7] = [104, 101, 108, 108, 111, 10, 55];
        return stdout().write_all(&BUFF);
    }
    • print("hello")
    • print(2+5)
    • use std::io::*;
    • fn kashikashi() -> Result<()> {
    • const BUFF: [u8; 7] = [104, 101, 108, 108, 111, 10, 55];
    • return stdout().write_all(&BUFF);
    • }

200

Code
Diff
  • pub fn bool_check(bools: [bool; 3]) -> bool {
        return (bools[0] && bools[1]) || (bools[0] && bools[2]) || (bools[1] && bools[2]);
    }
    • pub fn bool_check(bools: [bool; 3]) -> bool {
    • bools.into_iter().filter(|&b| b).count() >= 2
    • return (bools[0] && bools[1]) || (bools[0] && bools[2]) || (bools[1] && bools[2]);
    • }
Strings
Mathematics
Parsing

Changes

  • slight optimization by removing the use of Vec
Code
Diff
  • fn math(expression: &str) -> Result<i32, MathError> {
        // remove whitespace
        let expression: String = expression.chars().filter(|ch| !ch.is_whitespace()).collect();
        let operator: char = expression.chars().find(|ch| ['+', '-', '*', '/', '='].contains(&ch)).ok_or(MathError::MissingOperator)?;
        
        // converting each string slice to an integer
        let mut operands = expression.split(operator).filter_map(|n| n.parse::<i32>().ok());
        let num1 = operands.next().ok_or(MathError::InvalidOperand)?;
        let num2 = operands.next().ok_or(MathError::InvalidOperand)?;
        
        // divide by zero check
        if operator == '/' && num2 == 0 {
            return Err(MathError::DivideByZero);
        }
        
        let res: Option<i32> = match operator {
            '+' => num1.checked_add(num2),
            '-' => num1.checked_sub(num2),
            '*' => num1.checked_mul(num2),
            '/' => num1.checked_div(num2),
            '=' => Some((num1 == num2).into()),
            _   => unreachable!()
        };
        
        return res.ok_or(MathError::Overflow);
    }
    
    use MathError::*;
    #[derive(Debug, PartialEq, Eq)]
    enum MathError {
        MissingOperator,
        InvalidOperand,
        DivideByZero,
        Overflow,
    }
    
    
    
    • fn math(expression: &str) -> Result<i32, MathError> {
    • // remove whitespace
    • let expression: String = expression.chars().filter(|ch| !ch.is_whitespace()).collect();
    • let operator: char = expression.chars().find(|ch| ['+', '-', '*', '/', '='].contains(&ch)).ok_or(MathError::MissingOperator)?;
    • let operands: Vec<i32> = expression.split(operator).filter_map(|n| n.parse().ok()).collect();
    • let num1 = *operands.get(0).ok_or(MathError::InvalidOperand)?;
    • let num2 = *operands.get(1).ok_or(MathError::InvalidOperand)?;
    • // converting each string slice to an integer
    • let mut operands = expression.split(operator).filter_map(|n| n.parse::<i32>().ok());
    • let num1 = operands.next().ok_or(MathError::InvalidOperand)?;
    • let num2 = operands.next().ok_or(MathError::InvalidOperand)?;
    • // check if they divide by zero
    • // divide by zero check
    • if operator == '/' && num2 == 0 {
    • return Err(MathError::DivideByZero);
    • }
    • let res = match operator {
    • let res: Option<i32> = match operator {
    • '+' => num1.checked_add(num2),
    • '-' => num1.checked_sub(num2),
    • '*' => num1.checked_mul(num2),
    • '/' => num1.checked_div(num2),
    • '=' => Some((num1 == num2).into()),
    • _ => unreachable!()
    • };
    • return res.ok_or(MathError::Overflow);
    • }
    • use MathError::*;
    • #[derive(Debug, PartialEq, Eq)]
    • enum MathError {
    • MissingOperator,
    • InvalidOperand,
    • DivideByZero,
    • Overflow,
    • }
Strings
Mathematics
Parsing

Changes:

  • Streamlined error handling
  • Changed the Error enum to handle more error cases
Code
Diff
  • fn math(expression: &str) -> Result<i32, MathError> {
        // remove whitespace
        let expression: String = expression.chars().filter(|ch| !ch.is_whitespace()).collect();
        let operator: char = expression.chars().find(|ch| ['+', '-', '*', '/', '='].contains(&ch)).ok_or(MathError::MissingOperator)?;
        
        let operands: Vec<i32> = expression.split(operator).filter_map(|n| n.parse().ok()).collect();
        let num1 = *operands.get(0).ok_or(MathError::InvalidOperand)?;
        let num2 = *operands.get(1).ok_or(MathError::InvalidOperand)?;
        
        // check if they divide by zero
        if operator == '/' && num2 == 0 {
            return Err(MathError::DivideByZero);
        }
        
        let res = match operator {
            '+' => num1.checked_add(num2),
            '-' => num1.checked_sub(num2),
            '*' => num1.checked_mul(num2),
            '/' => num1.checked_div(num2),
            '=' => Some((num1 == num2).into()),
            _   => unreachable!()
        };
        
        return res.ok_or(MathError::Overflow);
    }
    
    use MathError::*;
    #[derive(Debug, PartialEq, Eq)]
    enum MathError {
        MissingOperator,
        InvalidOperand,
        DivideByZero,
        Overflow,
    }
    
    
    
    • fn math(expression: &str) -> Result<i32, MathError> {
    • // remove whitespace
    • let expression: String = expression.chars().filter(|ch| !ch.is_whitespace()).collect();
    • let operator: char = expression.chars().find(|ch| ['+', '-', '*', '/', '='].contains(&ch)).ok_or(MathError::MissingOperator)?;
    • let operands: Vec<i32> = expression.split(operator).filter_map(|n| n.parse().ok()).collect();
    • let num1 = *operands.get(0).ok_or(MathError::InvalidOperand)?;
    • let num2 = *operands.get(1).ok_or(MathError::InvalidOperand)?;
    • // check if they divide by zero
    • if operator == '/' && num2 == 0 {
    • return Err(MathError::DivideByZero);
    • }
    • match operator {
    • '+' => num1.checked_add(num2).ok_or(MathError::Overflow),
    • '-' => num1.checked_sub(num2).ok_or(MathError::Overflow),
    • '*' => num1.checked_mul(num2).ok_or(MathError::Overflow),
    • '/' => num1.checked_div(num2).ok_or(MathError::Overflow),
    • '=' => Ok((num1 == num2).into()),
    • let res = match operator {
    • '+' => num1.checked_add(num2),
    • '-' => num1.checked_sub(num2),
    • '*' => num1.checked_mul(num2),
    • '/' => num1.checked_div(num2),
    • '=' => Some((num1 == num2).into()),
    • _ => unreachable!()
    • }
    • };
    • return res.ok_or(MathError::Overflow);
    • }
    • use MathError::*;
    • #[derive(Debug, PartialEq, Eq)]
    • enum MathError {
    • MissingOperator,
    • InvalidOperand,
    • DivideByZero,
    • Overflow,
    • }
Strings
Mathematics
Code
Diff
  • fn math(expression: &str) -> Result<i32, MathError> {
        // remove whitespace
        let expression: String = expression.chars().filter(|ch| !ch.is_whitespace()).collect();
        let operator: char = expression.chars().find(|ch| ['+', '-', '*', '/', '='].contains(&ch)).ok_or(MathError::MissingOperator)?;
        
        let operands: Vec<i32> = expression.split(operator).filter_map(|n| n.parse().ok()).collect();
        let num1 = *operands.get(0).ok_or(MathError::InvalidOperand)?;
        let num2 = *operands.get(1).ok_or(MathError::InvalidOperand)?;
        
        // check if they divide by zero
        if operator == '/' && num2 == 0 {
            return Err(MathError::DivideByZero);
        }
        
        match operator {
            '+' => num1.checked_add(num2).ok_or(MathError::Overflow),
            '-' => num1.checked_sub(num2).ok_or(MathError::Overflow),
            '*' => num1.checked_mul(num2).ok_or(MathError::Overflow),
            '/' => num1.checked_div(num2).ok_or(MathError::Overflow),
            '=' => Ok((num1 == num2).into()),
            _   => unreachable!()
        }
    }
    
    use MathError::*;
    #[derive(Debug, PartialEq, Eq)]
    enum MathError {
        MissingOperator,
        InvalidOperand,
        DivideByZero,
        Overflow,
    }
    
    
    
    • fn math(s: &str) -> Result<i32, MathError> {
    • let s: String = s.chars().filter(|ch| !ch.is_whitespace()).collect();
    • let Some((num1, num2)) =
    • s.split_once(|c| ['+', '-', '*', '/', '='].contains(&c))
    • else {
    • return Err(MissingOperator);
    • };
    • fn math(expression: &str) -> Result<i32, MathError> {
    • // remove whitespace
    • let expression: String = expression.chars().filter(|ch| !ch.is_whitespace()).collect();
    • let operator: char = expression.chars().find(|ch| ['+', '-', '*', '/', '='].contains(&ch)).ok_or(MathError::MissingOperator)?;
    • let operands: Vec<i32> = expression.split(operator).filter_map(|n| n.parse().ok()).collect();
    • let num1 = *operands.get(0).ok_or(MathError::InvalidOperand)?;
    • let num2 = *operands.get(1).ok_or(MathError::InvalidOperand)?;
    • // check if they divide by zero
    • if operator == '/' && num2 == 0 {
    • return Err(MathError::DivideByZero);
    • }
    • let operator = &s[num1.len()..=num1.len()];
    • let (Ok(num1), Ok(num2)) = (num1.parse::<i32>(), num2.parse::<i32>()) else {
    • return Err(InvalidOperand);
    • };
    • match operator {
    • "+" => Ok(num1 + num2),
    • "-" => Ok(num1 - num2),
    • "*" => Ok(num1 * num2),
    • "/" => {
    • if num2 != 0 {
    • Ok(num1 / num2)
    • } else {
    • Err(DivideByZero)
    • }
    • },
    • "=" => Ok(i32::from(num1 == num2)),
    • _ => unreachable!(),
    • '+' => num1.checked_add(num2).ok_or(MathError::Overflow),
    • '-' => num1.checked_sub(num2).ok_or(MathError::Overflow),
    • '*' => num1.checked_mul(num2).ok_or(MathError::Overflow),
    • '/' => num1.checked_div(num2).ok_or(MathError::Overflow),
    • '=' => Ok((num1 == num2).into()),
    • _ => unreachable!()
    • }
    • }
    • use MathError::*;
    • #[derive(Debug, PartialEq, Eq)]
    • enum MathError {
    • MissingOperator,
    • InvalidOperand,
    • DivideByZero
    • DivideByZero,
    • Overflow,
    • }

Modify the fahrenheit_to_celsius() and celsius_to_fahrenheit() functions of the TemperatureConverter struct so that it converts self.temp to either fahrenheit or celsius respectively.

Code
Diff
  • struct TemperatureConverter {
        // add what you need
    }
    
    // implement these three
    impl TemperatureConverter {
        fn new(temp: i32) -> Self {
            todo!()
        }
        fn fahrenheit_to_celcius(self) -> f32 {
            todo!()
        }
        fn celsius_to_fahrenheit(self) -> f32 {
            todo!()
        }
    }
    
    
    • class TemperatureConverter:
    • def __init__(self, temp):
    • self.temp = temp
    • def fahrenheit_to_celsius(self):
    • pass
    • def celsius_to_fahrenheit(self):
    • pass
    • struct TemperatureConverter {
    • // add what you need
    • }
    • // implement these three
    • impl TemperatureConverter {
    • fn new(temp: i32) -> Self {
    • todo!()
    • }
    • fn fahrenheit_to_celcius(self) -> f32 {
    • todo!()
    • }
    • fn celsius_to_fahrenheit(self) -> f32 {
    • todo!()
    • }
    • }
Code
Diff
  • fn capitalise(s: &str) -> String {
        return s
            .split(' ')
            .map(capitalise_word)
            .collect::<Vec<String>>()
            .join(" ");
    }
    
    fn capitalise_word(s: &str) -> String {
        if s.len() == 0 {
            return s.to_uppercase();
        }
        return s.get(0..=0).unwrap().to_uppercase() + s.get(1..).unwrap();
    }
    • function capitalize(sentence) {
    • let words = sentence.split(' ');
    • const length = words.length;
    • for (let i = 0; i < length; ++i) {
    • words[i] = words[i][0].toUpperCase() + words[i].substr(1)
    • }
    • return words.join(' ');
    • fn capitalise(s: &str) -> String {
    • return s
    • .split(' ')
    • .map(capitalise_word)
    • .collect::<Vec<String>>()
    • .join(" ");
    • }
    • console.log(capitalize("i am a javascript programmer"));
    • fn capitalise_word(s: &str) -> String {
    • if s.len() == 0 {
    • return s.to_uppercase();
    • }
    • return s.get(0..=0).unwrap().to_uppercase() + s.get(1..).unwrap();
    • }
Strings
Mathematics
Code
Diff
  • fn math(s: &str) -> i32 {
        // first remove whitespace characters so all we have left are digits and the operator
        let num_str: String = s.chars().filter(|ch| *ch != ' ').collect();
        
        // extract the operator character
        let pos: usize = num_str    
            .chars()
            .position(|ch| ch == '+' || ch == '-' || ch == '*' || ch == '/' || ch == '=')
            .expect("invalid operator, expected '+, -, *, / or =");
        let operator: char = num_str
            .chars()
            .nth(pos)
            .unwrap();
        
        // extract the two numbers from the string
        let num1: i32 = num_str.get(0..pos).unwrap().parse().unwrap();
        let num2: i32 = num_str.get(pos + 1..).unwrap().parse().unwrap();
        
        match operator {
            '+' => num1 + num2,
            '-' => num1 - num2,
            '*' => num1 * num2,
            '/' => num1 / num2,
            _ => (num1 == num2) as i32,
        }
    }
    • fn math(s: &str) -> i32 {
    • // first remove whitespace characters so all we have left are digits and the operator
    • let num_string: String = s.chars().filter(|ch| *ch != ' ').collect();
    • let num_str: String = s.chars().filter(|ch| *ch != ' ').collect();
    • // extract the operator character
    • let operator: char = num_string
    • let pos: usize = num_str
    • .chars()
    • .find(|ch| ['+', '-', '*', '/', '='].contains(&ch))
    • .position(|ch| ch == '+' || ch == '-' || ch == '*' || ch == '/' || ch == '=')
    • .expect("invalid operator, expected '+, -, *, / or =");
    • let operator: char = num_str
    • .chars()
    • .nth(pos)
    • .unwrap();
    • // extract the two numbers from the string
    • let num: Vec<i32> = num_string.split(operator).map(|n| n.parse().expect("string contains an invalid number")).collect();
    • let num1: i32 = num_str.get(0..pos).unwrap().parse().unwrap();
    • let num2: i32 = num_str.get(pos + 1..).unwrap().parse().unwrap();
    • match operator {
    • '+' => num[0] + num[1],
    • '-' => num[0] - num[1],
    • '*' => num[0] * num[1],
    • '/' => num[0] / num[1],
    • _ => (num[0] == num[1]) as i32,
    • '+' => num1 + num2,
    • '-' => num1 - num2,
    • '*' => num1 * num2,
    • '/' => num1 / num2,
    • _ => (num1 == num2) as i32,
    • }
    • }
Strings
Mathematics
Code
Diff
  • fn math(s: &str) -> i32 {
        // first remove whitespace characters so all we have left are digits and the operator
        let num_string: String = s.chars().filter(|ch| *ch != ' ').collect();
        
        // extract the operator character
        let operator: char = num_string
            .chars()
            .find(|ch| ['+', '-', '*', '/', '='].contains(&ch))
            .expect("invalid operator, expected '+, -, *, / or =");
        
        // extract the two numbers from the string
        let num: Vec<i32> = num_string.split(operator).map(|n| n.parse().expect("string contains an invalid number")).collect();
        
        match operator {
            '+' => num[0] + num[1],
            '-' => num[0] - num[1],
            '*' => num[0] * num[1],
            '/' => num[0] / num[1],
            _ => (num[0] == num[1]) as i32,
        }
    }
    • fn math(e: &str) -> i32 {
    • let mut ope = '\0';
    • let mut first = 0;
    • let mut secon = 0;
    • for c in e.chars() {
    • match c {
    • '+' => { ope = '+'; },
    • '-' => { ope = '-'; },
    • '*' => { ope = '*'; },
    • '/' => { ope = '/'; },
    • '=' => { ope = '='; },
    • '0'..='9' => {
    • if ope == '\0' {
    • first *= 10;
    • first += c as i32 - '0' as i32;
    • } else {
    • secon *= 10;
    • secon += c as i32 - '0' as i32;
    • }
    • }
    • ' ' => {},
    • _ => {panic!("wrong value");}
    • }
    • }
    • return match ope {
    • '+' => first + secon,
    • '-' => first - secon,
    • '*' => first * secon,
    • '/' => first / secon,
    • '=' => (first == secon) as i32,
    • _ => panic!("no operator")
    • fn math(s: &str) -> i32 {
    • // first remove whitespace characters so all we have left are digits and the operator
    • let num_string: String = s.chars().filter(|ch| *ch != ' ').collect();
    • // extract the operator character
    • let operator: char = num_string
    • .chars()
    • .find(|ch| ['+', '-', '*', '/', '='].contains(&ch))
    • .expect("invalid operator, expected '+, -, *, / or =");
    • // extract the two numbers from the string
    • let num: Vec<i32> = num_string.split(operator).map(|n| n.parse().expect("string contains an invalid number")).collect();
    • match operator {
    • '+' => num[0] + num[1],
    • '-' => num[0] - num[1],
    • '*' => num[0] * num[1],
    • '/' => num[0] / num[1],
    • _ => (num[0] == num[1]) as i32,
    • }
    • }