Ad
Code
Diff
  • fn missing_number(nums: &[u32]) -> u32 {
        (0..=nums.len() as u32).find(|n| !nums.contains(&n)).unwrap()
    }
    • class Solution {
    • public:
    • int missingNumber(vector<int>& nums) {
    • }
    • };
    • fn missing_number(nums: &[u32]) -> u32 {
    • (0..=nums.len() as u32).find(|n| !nums.contains(&n)).unwrap()
    • }
Code
Diff
  • fn split(string: &str, separator: char) -> Vec<&str> {
        string.split(separator).collect()
    }
    
    • #include <string>
    • #include <sstream>
    • #include <vector>
    • auto split(const std::string& str, char sep) {
    • auto result = std::vector<std::string>{};
    • auto stream = std::stringstream(str);
    • auto buffer = std::string{};
    • while (std::getline(stream, buffer, sep)) result.emplace_back(buffer);
    • return result;
    • fn split(string: &str, separator: char) -> Vec<&str> {
    • string.split(separator).collect()
    • }
Code
Diff
  • fn mean(x: &[u64]) -> u64 {
        x.iter().sum::<u64>() / x.len() as u64
    }
    
    • #include <iostream>
    • double Mean(double x[], int n){
    • double sum = 0;
    • for(int i = 0; i < n; i++){
    • sum += x[i];
    • }
    • return sum / n;
    • }
    • fn mean(x: &[u64]) -> u64 {
    • x.iter().sum::<u64>() / x.len() as u64
    • }
Code
Diff
  • fn total_fine(speed: i32, signals: &[i32]) -> u32 {
        signals.iter().map(|&signal| fine(speed, signal)).sum()
    }
    
    fn fine(speed: i32, signal: i32) -> u32 {
        match speed - signal {
            ..=9 => 0,
            10..=19 => 100,
            20..=29 => 250,
            30.. => 500
        }
    }
    • public class Kata {
    • public static int speedLimit(int speed, int[] signals) {
    • int penalty = 0;
    • for (int i = 0; i < signals.length; i++){
    • if (speed > signals[i]){
    • if (speed - signals[i] >= 30){
    • penalty += 500;
    • } else if (speed - signals[i] >= 20 && speed - signals[i] < 30){
    • penalty += 250;
    • } else if (speed - signals[i] >= 10 && speed - signals[i] < 20){
    • penalty += 100;
    • }
    • }
    • }
    • return penalty;
    • fn total_fine(speed: i32, signals: &[i32]) -> u32 {
    • signals.iter().map(|&signal| fine(speed, signal)).sum()
    • }
    • fn fine(speed: i32, signal: i32) -> u32 {
    • match speed - signal {
    • ..=9 => 0,
    • 10..=19 => 100,
    • 20..=29 => 250,
    • 30.. => 500
    • }
    • }

Optimized for conciseness

Code
Diff
  • use itertools::Itertools;
    
    fn print(number: u64) -> u64 {
        number.to_string().chars().sorted().rev().collect::<String>().parse().unwrap()
    }
    • fn print(mut number: u64) -> u64 {
    • let mut digits = Vec::new();
    • while number > 0 {
    • digits.push(number % 10);
    • number /= 10;
    • }
    • digits.sort();
    • digits.into_iter().rev().fold(0, |result, digit| result * 10 + digit)
    • use itertools::Itertools;
    • fn print(number: u64) -> u64 {
    • number.to_string().chars().sorted().rev().collect::<String>().parse().unwrap()
    • }

Optimized for speed

Code
Diff
  • fn print(mut number: u64) -> u64 {
        let mut digits = Vec::new();
        while number > 0 {
            digits.push(number % 10);
            number /= 10;
        }
        digits.sort();
        digits.into_iter().rev().fold(0, |result, digit| result * 10 + digit)
    }
    • import java.util.Arrays;
    • public class MaxNumber {
    • public static long print(long number) {
    • return number
    • fn print(mut number: u64) -> u64 {
    • let mut digits = Vec::new();
    • while number > 0 {
    • digits.push(number % 10);
    • number /= 10;
    • }
    • digits.sort();
    • digits.into_iter().rev().fold(0, |result, digit| result * 10 + digit)
    • }
Code
Diff
  • struct Test {
        a: Option<String>,
        b: Option<String>,
    }
    
    impl Test {
        fn new() -> Self {
            Self {
                a: Default::default(),
                b: None,
            }
        }
    }
    • namespace Test {
    • public class Test {
    • public string a;
    • public string b = null;
    • }
    • struct Test {
    • a: Option<String>,
    • b: Option<String>,
    • }
    • impl Test {
    • fn new() -> Self {
    • Self {
    • a: Default::default(),
    • b: None,
    • }
    • }
    • }
Code
Diff
  • fn find_max(array: &[i32]) -> i32 {
        *array.iter().max().unwrap()
    }
    
    • public class Kata {
    • public static int findMax(int[] my_array) {
    • // Write a method that returns the largest integer in the list.
    • // You can assume that the list has at least one element.
    • return 7;
    • }
    • }
    • fn find_max(array: &[i32]) -> i32 {
    • *array.iter().max().unwrap()
    • }
Algorithms
Logic
Code
Diff
  • fn get_nth_words(string: &str, n: usize) -> String {
        if n == 0 { return String::new() }
        string.split(" ").skip(n - 1).step_by(n).collect::<Vec<_>>().join(" ")
    }
    • def get_nth_words(string, n):
    • if n < 1: return ""
    • return ' '.join(['',*string.split()][::n][1:])
    • fn get_nth_words(string: &str, n: usize) -> String {
    • if n == 0 { return String::new() }
    • string.split(" ").skip(n - 1).step_by(n).collect::<Vec<_>>().join(" ")
    • }
Code
Diff
  • fn find_multiples(base: usize, limit: usize) -> Vec<usize> {
        (base..=limit).step_by(base).collect()
    }
    • def find_multiples(b, l):
    • a=[]
    • for i in range(b,l+1,b):
    • a.append(i)
    • return a
    • fn find_multiples(base: usize, limit: usize) -> Vec<usize> {
    • (base..=limit).step_by(base).collect()
    • }

Manually checked lock. Contains unsafe and is most likely to be unsound since I'm still learning concurrency.

Code
Diff
  • use std::{thread, sync::atomic::{AtomicBool, Ordering::*}};
    
    fn count() -> u32 {
        let lock = AtomicBool::new(false);
        let count = 0;
        thread::scope(|s| {
            for _ in 0..10 {
                s.spawn(|| {
                    for _ in 0..100 {
                        while lock.compare_exchange(false, true, Acquire, Relaxed).is_err() {}
                        let count_ptr = &count as *const u32 as *mut u32;
                        unsafe { *count_ptr += 1; }
                        lock.store(false, Release);
                    }
                });
            }
        });
        count
    }
    • use std::{thread, sync::atomic::{AtomicU32, Ordering::Relaxed}};
    • use std::{thread, sync::atomic::{AtomicBool, Ordering::*}};
    • fn count() -> u32 {
    • let count = AtomicU32::new(0);
    • let lock = AtomicBool::new(false);
    • let count = 0;
    • thread::scope(|s| {
    • for _ in 0..10 {
    • s.spawn(|| {
    • for _ in 0..100 {
    • let current = count.load(Relaxed);
    • count.store(current + 1, Relaxed);
    • while lock.compare_exchange(false, true, Acquire, Relaxed).is_err() {}
    • let count_ptr = &count as *const u32 as *mut u32;
    • unsafe { *count_ptr += 1; }
    • lock.store(false, Release);
    • }
    • });
    • }
    • });
    • count.into_inner()
    • count
    • }

Seems like it should be worse than an atomic since there's additional overhead, but isn't notably slower.

Code
Diff
  • use std::{thread, sync::Mutex};
    
    fn count() -> u32 {
        let count = Mutex::new(0);
        thread::scope(|s| {
            for _ in 0..10 {
                s.spawn(|| {
                    for _ in 0..100 {
                        *count.lock().unwrap() += 1;
                    }
                });
            }
        });
        count.into_inner().unwrap()
    }
    • use std::{thread, sync::atomic::{AtomicU32, Ordering::Relaxed}};
    • use std::{thread, sync::Mutex};
    • fn count() -> u32 {
    • let count = AtomicU32::new(0);
    • let count = Mutex::new(0);
    • thread::scope(|s| {
    • for _ in 0..10 {
    • s.spawn(|| {
    • for _ in 0..100 {
    • let current = count.load(Relaxed);
    • count.store(current + 1, Relaxed);
    • *count.lock().unwrap() += 1;
    • }
    • });
    • }
    • });
    • count.into_inner()
    • count.into_inner().unwrap()
    • }

Feels kinda like cheating. Surprisingly not faster. Maybe the thread spawning dominates the runtime anyways?

Code
Diff
  • use std::{thread, sync::atomic::{AtomicU32, Ordering::Relaxed}};
    
    fn count() -> u32 {
        let global_count = AtomicU32::new(0);
        thread::scope(|s| {
            for _ in 0..10 {
                s.spawn(|| {
                    let mut local_count = 0;
                    for _ in 0..100 {
                        local_count += 1;
                    }
                    global_count.fetch_add(local_count, Relaxed);
                });
            }
        });
        global_count.into_inner()
    }
    • use std::{thread, sync::atomic::{AtomicU32, Ordering::Relaxed}};
    • fn count() -> u32 {
    • let count = AtomicU32::new(0);
    • let global_count = AtomicU32::new(0);
    • thread::scope(|s| {
    • for _ in 0..10 {
    • s.spawn(|| {
    • let mut local_count = 0;
    • for _ in 0..100 {
    • let current = count.load(Relaxed);
    • count.store(current + 1, Relaxed);
    • local_count += 1;
    • }
    • global_count.fetch_add(local_count, Relaxed);
    • });
    • }
    • });
    • count.into_inner()
    • global_count.into_inner()
    • }
Code
Diff
  • fn encode(string: &str) -> String {
        string.chars().map(|ch| {
            match ch {
                'a' => '1',
                'e' => '2',
                'i' => '3',
                'o' => '4',
                'u' => '5',
                _ => ch
            }
        }).collect()
    }
    
    fn decode(string: &str) -> String {
        string.chars().map(|ch| {
            match ch {
                '1' => 'a',
                '2' => 'e',
                '3' => 'i',
                '4' => 'o',
                '5' => 'u',
                _ => ch
            }
        }).collect()
    }
    • function encode(string){
    • return [...string].map(el => {return ( "aeiou".includes(el))? "aeiou".indexOf(el) + 1 : el}).join('')}
    • fn encode(string: &str) -> String {
    • string.chars().map(|ch| {
    • match ch {
    • 'a' => '1',
    • 'e' => '2',
    • 'i' => '3',
    • 'o' => '4',
    • 'u' => '5',
    • _ => ch
    • }
    • }).collect()
    • }
    • function decode(string){
    • return [...string].map(el => {return ("12345".includes(el)) ? {'1':"a","2":"e","3":"i","4":"o","5":"u"}[el] : el}).join('')
    • }
    • fn decode(string: &str) -> String {
    • string.chars().map(|ch| {
    • match ch {
    • '1' => 'a',
    • '2' => 'e',
    • '3' => 'i',
    • '4' => 'o',
    • '5' => 'u',
    • _ => ch
    • }
    • }).collect()
    • }

The simple fix. Runtime around 3 seconds for 10000 calls.

Code
Diff
  • use std::{thread, sync::atomic::{AtomicU32, Ordering::Relaxed}};
    
    fn count() -> u32 {
        let count = AtomicU32::new(0);
        thread::scope(|s| {
            for _ in 0..10 {
                s.spawn(|| {
                    for _ in 0..100 {
                        count.fetch_add(1, Relaxed);
                    }
                });
            }
        });
        count.into_inner()
    }
    • use std::{thread, sync::atomic::{AtomicU32, Ordering::Relaxed}};
    • fn count() -> u32 {
    • let count = AtomicU32::new(0);
    • thread::scope(|s| {
    • for _ in 0..10 {
    • s.spawn(|| {
    • for _ in 0..100 {
    • let current = count.load(Relaxed);
    • count.store(current + 1, Relaxed);
    • count.fetch_add(1, Relaxed);
    • }
    • });
    • }
    • });
    • count.into_inner()
    • }
Loading more items...