Using split method from the standard library is boring :)
also improved edge cases so it behaves like standard library
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;
- }
#[test] fn test() { assert_eq!(split("Hello World", ' '), ["Hello", "World"]); assert_eq!(split("John-brings-his-cat", '-'), ["John", "brings", "his", "cat"]); assert_eq!(split(",joe,mama,", ','), ["", "joe", "mama", ""]); }
- #[test]
- fn test() {
- assert_eq!(split("Hello World", ' '), ["Hello", "World"]);
- assert_eq!(split("John-brings-his-cat", '-'), ["John", "brings", "his", "cat"]);
- assert_eq!(split(",joe,mama,", ','), ["", "joe", "mama", ""]);
- }
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();
- }
#[cfg(test)] mod tests { use super::*; #[test] fn test() { assert_eq!(remove_symbols("y&%ou sho!!!uld! no@t e@at yell==ow sn**ow"), "you should not eat yellow snow"); assert_eq!(remove_symbols("whe%%re ar*@e th£e birds"), "where are the birds"); assert_eq!(remove_symbols("b@an@anas are fu£@ll of potassi&%&um"), "bananas are full of potassium"); // assert.strictEqual(1 + 1, 2); } }
// Since Node 10, we're using Mocha.// You can use `chai` for assertions.const chai = require("chai");const assert = chai.assert;// Uncomment the following line to disable truncating failure messages for deep equals, do:// chai.config.truncateThreshold = 0;// Since Node 12, we no longer include assertions from our deprecated custom test framework by default.// Uncomment the following to use the old assertions:const Test = require("@codewars/test-compat");describe("Solution", function() {it("should test for something", function() {Test.assertEquals(removeSymbols("y&%ou sho!!!uld! no@t e@at yell==ow sn**ow"), "you should not eat yellow snow");Test.assertEquals(removeSymbols("whe%%re ar*@e th£e birds"), "where are the birds");Test.assertEquals(removeSymbols("b@an@anas are fu£@ll of potassi&%&um"), "bananas are full of potassium");- #[cfg(test)]
- mod tests {
- use super::*;
- #[test]
- fn test() {
- assert_eq!(remove_symbols("y&%ou sho!!!uld! no@t e@at yell==ow sn**ow"), "you should not eat yellow snow");
- assert_eq!(remove_symbols("whe%%re ar*@e th£e birds"), "where are the birds");
- assert_eq!(remove_symbols("b@an@anas are fu£@ll of potassi&%&um"), "bananas are full of potassium");
- // assert.strictEqual(1 + 1, 2);
});});- }
- }
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)
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;
- }
#[cfg(test)] mod tests { use super::*; use std::collections::*; #[test] fn test_sum() { let (a, b, c) = ([1], Vec::from([3, 1]), LinkedList::from([1, 2, 3])); assert_eq!(sum(&a), 1); assert_eq!(sum(&b), 4); assert_eq!(sum(&c), 6); } }
- #[cfg(test)]
- mod tests {
- use super::*;
- use std::collections::*;
- #[test]
- fn test_sum() {
assert_eq!(sum([1]), 1);assert_eq!(sum(Vec::from([3, 1])), 4);assert_eq!(sum(LinkedList::from([1, 2, 3])), 6);- let (a, b, c) = ([1], Vec::from([3, 1]), LinkedList::from([1, 2, 3]));
- assert_eq!(sum(&a), 1);
- assert_eq!(sum(&b), 4);
- assert_eq!(sum(&c), 6);
- }
- }
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();
- }
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 = 0for i in arr:result += ireturn 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;
- }
#[cfg(test)] mod tests { use super::*; use std::collections::*; #[test] fn test_sum() { assert_eq!(sum([1]), 1); assert_eq!(sum(Vec::from([3, 1])), 4); assert_eq!(sum(LinkedList::from([1, 2, 3])), 6); } }
import codewars_test as test# TODO Write testsfrom solution import sum- #[cfg(test)]
- mod tests {
- use super::*;
- use std::collections::*;
# test.assert_equals(actual, expected, [optional] message)@test.describe("Example tests")def test_group():@test.it("Basic tests")def test_case():test.assert_equals(sum([1]), 1)test.assert_equals(sum([1,2,3]), 6)- #[test]
- fn test_sum() {
- assert_eq!(sum([1]), 1);
- assert_eq!(sum(Vec::from([3, 1])), 4);
- assert_eq!(sum(LinkedList::from([1, 2, 3])), 6);
- }
- }
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);
- }
// Add your tests here. // See https://doc.rust-lang.org/stable/rust-by-example/testing/unit_testing.html #[cfg(test)] mod tests { use super::*; #[test] fn test_kashikashi() { assert!(kashikashi().is_ok()); assert_eq!(2 + 2, 4); } }
import codewars_test as test# TODO Write testsimport solution # or from solution import example- // Add your tests here.
- // See https://doc.rust-lang.org/stable/rust-by-example/testing/unit_testing.html
# test.assert_equals(actual, expected, [optional] message)@test.describe("Example")def test_group():@test.it("test case")def test_case():test.assert_equals(1 + 1, 2)- #[cfg(test)]
- mod tests {
- use super::*;
- #[test]
- fn test_kashikashi() {
- assert!(kashikashi().is_ok());
- assert_eq!(2 + 2, 4);
- }
- }
200
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]);
- }
Changes
- slight optimization by removing the use of Vec
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,
- }
Changes:
- Streamlined error handling
- Changed the Error enum to handle more error cases
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,
- }
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.
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 = tempdef fahrenheit_to_celsius(self):passdef 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!()
- }
- }
#[cfg(test)] mod tests { use super::TemperatureConverter; fn test(input: i32, output: f32) { let converter = TemperatureConverter::new(input); assert_eq!(converter.fahrenheit_to_celcius(), output, "\nExpected:\n(right)\n but got:\n(left)"); } #[test] fn test_fahrenheit_to_celcius() { println!("Testing: fahrenheit_to_celsius"); test(0, -17.78); test(32, 0.0); test(76, 24.44); test(112, 44.44); test(-55, -48.33); } #[test] fn test_celcius_to_fahrenheit() { println!("Testing: celsius_to_fahrenheit"); test(0, 32.0); test(32, 89.6); test(-17, 1.4); test(48, 118.4); } }
import codewars_test as testfrom solution import TemperatureConverter- #[cfg(test)]
- mod tests {
- use super::TemperatureConverter;
- fn test(input: i32, output: f32) {
- let converter = TemperatureConverter::new(input);
- assert_eq!(converter.fahrenheit_to_celcius(), output, "\nExpected:\n(right)\n but got:\n(left)");
- }
@test.describe("Example")def test_group():@test.it("test case 1: fahrenheit_to_celsius")def test_case():test.assert_equals(TemperatureConverter(0).fahrenheit_to_celsius(), -17.78)test.assert_equals(TemperatureConverter(32).fahrenheit_to_celsius(), 0)test.assert_equals(TemperatureConverter(76).fahrenheit_to_celsius(), 24.44)test.assert_equals(TemperatureConverter(112).fahrenheit_to_celsius(), 44.44)test.assert_equals(TemperatureConverter(-55).fahrenheit_to_celsius(), -48.33)def test_group():@test.it("test case 2: celsius_to_fahrenheit")def test_case():test.assert_equals(TemperatureConverter(0).celsius_to_fahrenheit(), 32)test.assert_equals(TemperatureConverter(32).celsius_to_fahrenheit(), 89.6)test.assert_equals(TemperatureConverter(-17).celsius_to_fahrenheit(), 1.4)test.assert_equals(TemperatureConverter(48).celsius_to_fahrenheit(), 118.4)- #[test]
- fn test_fahrenheit_to_celcius() {
- println!("Testing: fahrenheit_to_celsius");
- test(0, -17.78);
- test(32, 0.0);
- test(76, 24.44);
- test(112, 44.44);
- test(-55, -48.33);
- }
- #[test]
- fn test_celcius_to_fahrenheit() {
- println!("Testing: celsius_to_fahrenheit");
- test(0, 32.0);
- test(32, 89.6);
- test(-17, 1.4);
- test(48, 118.4);
- }
- }
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();
- }
// Add your tests here. // See https://doc.rust-lang.org/stable/rust-by-example/testing/unit_testing.html #[cfg(test)] mod tests { use super::*; #[test] fn lowercase_words() { assert_eq!(&capitalise("joe biden"), "Joe Biden"); } #[test] fn words_with_one_letter() { assert_eq!(&capitalise("a b c deez"), "A B C Deez"); } #[test] fn ignore_non_ascii() { assert_eq!(&capitalise("red green & blue *) purple"), "Red Green & Blue *) Purple"); } }
// Since Node 10, we're using Mocha.// You can use `chai` for assertions.const chai = require("chai");const assert = chai.assert;// Uncomment the following line to disable truncating failure messages for deep equals, do:// chai.config.truncateThreshold = 0;// Since Node 12, we no longer include assertions from our deprecated custom test framework by default.// Uncomment the following to use the old assertions:// const Test = require("@codewars/test-compat");- // Add your tests here.
- // See https://doc.rust-lang.org/stable/rust-by-example/testing/unit_testing.html
describe("Solution", function() {it("should test for something", function() {// Test.assertEquals(1 + 1, 2);// assert.strictEqual(1 + 1, 2);});});- #[cfg(test)]
- mod tests {
- use super::*;
- #[test]
- fn lowercase_words() {
- assert_eq!(&capitalise("joe biden"), "Joe Biden");
- }
- #[test]
- fn words_with_one_letter() {
- assert_eq!(&capitalise("a b c deez"), "A B C Deez");
- }
- #[test]
- fn ignore_non_ascii() {
- assert_eq!(&capitalise("red green & blue *) purple"), "Red Green & Blue *) Purple");
- }
- }
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,
- }
- }
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,
- }
- }