Ad
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()
    • }

Try fixing the race condition while keeping the program multithreaded.

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.into_inner()
}
Strings
Code
Diff
  • use std::collections::BTreeSet;
    
    fn is_unique(string: &str) -> bool {
        string.chars().collect::<BTreeSet<_>>().len() == string.len()
    }
    
    • use std::collections::BTreeSet;
    • fn is_unique(string: &str) -> bool {
    • let mut known = BTreeSet::new();
    • for character in string.chars() {
    • if known.contains(&character) {
    • return false;
    • }
    • known.insert(character);
    • }
    • true
    • string.chars().collect::<BTreeSet<_>>().len() == string.len()
    • }
Code
Diff
  • fn main() {
        let h = "Hello";
        let w = "World";
        println!("{h} {w}");
    }
    
    • ## Created by RHB
    • # Your code here
    • [print(chr(i),end="") for i in [100, 108, 114, 111, 87, 32, 111, 108, 108, 101, 72][::-1]]
    • fn main() {
    • let h = "Hello";
    • let w = "World";
    • println!("{h} {w}");
    • }
Algorithms
Arrays
Mathematics
Geometry
Code
Diff
  • fn make_move(init: (i32, i32), sequence: &str) -> (i32, i32) {
        sequence.chars().fold(init, |(x, y), c| (
            x + match c { 'r' => 1, 'l' => -1, _ => 0 },
            y + match c { 't' => 1, 'b' => -1, _ => 0 },
        ))
    }
    • fn make_move(init: [i32; 2], sequence: &str) -> [i32; 2] {
    • sequence.chars().fold(init, |[x, y], c| [
    • x + (c == 'r') as i32 - (c == 'l') as i32,
    • y + (c == 't') as i32 - (c == 'b') as i32,
    • ])
    • fn make_move(init: (i32, i32), sequence: &str) -> (i32, i32) {
    • sequence.chars().fold(init, |(x, y), c| (
    • x + match c { 'r' => 1, 'l' => -1, _ => 0 },
    • y + match c { 't' => 1, 'b' => -1, _ => 0 },
    • ))
    • }
Algorithms
Arrays
Mathematics
Geometry
Code
Diff
  • fn make_move(init: [i32; 2], sequence: &str) -> [i32; 2] {
        sequence.chars().fold(init, |[x, y], c| [
            x + (c == 'r') as i32 - (c == 'l') as i32,
            y + (c == 't') as i32 - (c == 'b') as i32,
        ])
    }
    • fn make_move(mut init: [i32; 2], sequence: &str) -> [i32; 2] {
    • for c in sequence.chars() {
    • match c {
    • 't' => init[1] += 1,
    • 'b' => init[1] -= 1,
    • 'r' => init[0] += 1,
    • 'l' => init[0] -= 1,
    • _ => {}
    • }
    • }
    • init
    • fn make_move(init: [i32; 2], sequence: &str) -> [i32; 2] {
    • sequence.chars().fold(init, |[x, y], c| [
    • x + (c == 'r') as i32 - (c == 'l') as i32,
    • y + (c == 't') as i32 - (c == 'b') as i32,
    • ])
    • }
Algorithms
Arrays
Mathematics
Geometry
Code
Diff
  • fn make_move(mut init: [i32; 2], sequence: &str) -> [i32; 2] {
        for c in sequence.chars() {
            match c {
                't' => init[1] += 1,
                'b' => init[1] -= 1,
                'r' => init[0] += 1,
                'l' => init[0] -= 1,
                _ => {}
            }
        }
        init
    }
    • function makeMove(init, sequence) {
    • [...sequence].forEach(move => {
    • switch (move) {
    • case 't':
    • init[1]++;
    • break;
    • case 'b':
    • init[1]--;
    • break;
    • case 'r':
    • init[0]++;
    • break;
    • case 'l':
    • init[0]--;
    • break;
    • default:
    • break;
    • fn make_move(mut init: [i32; 2], sequence: &str) -> [i32; 2] {
    • for c in sequence.chars() {
    • match c {
    • 't' => init[1] += 1,
    • 'b' => init[1] -= 1,
    • 'r' => init[0] += 1,
    • 'l' => init[0] -= 1,
    • _ => {}
    • }
    • }
    • });
    • return init;
    • init
    • }
Loading more items...