Skip to content

Instantly share code, notes, and snippets.

@philopaterwaheed
Last active February 6, 2024 07:32
Show Gist options
  • Save philopaterwaheed/b407bea8c3677314244af8b87d15c5c8 to your computer and use it in GitHub Desktop.
Save philopaterwaheed/b407bea8c3677314244af8b87d15c5c8 to your computer and use it in GitHub Desktop.
rust problem solving basics only
use either::Either;
fn sum_mix(arr: &[Either<i32, String>]) -> i32 {
let mut x : i32 = 0 ;
for my_either in arr {
match my_either{
Either::Left(left_value) => {
println!("Left value: {}", left_value);
x = x+ left_value;
}
Either::Right(right_value) => {
println!("Right value: {}", right_value);
x = x + right_value.parse::<i32>().unwrap();
}
}
}
x
}
fn sum_mix(arr: &[Either<i32, String>]) -> i32 {
let mut result = 0;
for element in arr {
match element {
Either::Left(x) => result += x,
Either::Right(x) => result += x.parse::<i32>().unwrap(),
}
}
result
}
fn powers_of_two(n: u8) -> Vec<u128> {
let mut vec :Vec<u128> = Vec ::new();
for i in (0_u32 .. (n+1) as u32) {
vec.push(u128::pow(2_u128,i)) ;
}
vec
}
fn string_to_array(s: &str) -> Vec<String> {
let mut vec : Vec<String> = Vec::new();
let mut ss = String :: new() ;
for ch in s.chars(){
if ch != ' '
{
ss.push(ch.clone());
}
else {
vec.push(ss.clone());
ss.clear();
}
}
vec.push(ss);
vec
}
fn to_alternating_case(s: &str) -> String {
let mut out = String::new();
for x in s.chars(){
match x.is_uppercase(){
false => out.push( x.to_uppercase().next().unwrap()),
true => out.push(x.to_lowercase().next().unwrap()),
}
}
out
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment