Ad
Code
Diff
  • const RGB_MAX: f64 = 255.;
    
    fn rgb_to_hsv(rgb: (u8, u8, u8)) -> (u16, u8, u8) {
        let (r, g, b) = rgb;
        let v = r.max(g).max(b) as f64 / RGB_MAX;
        if v == 0. {
            return (0, 0, 0);
        }
        let r = r as f64 / v;
        let g = g as f64 / v;
        let b = b as f64 / v;
        let s = 1. - r.min(g).min(b) as f64 / RGB_MAX;
        if s == 0. {
            return (0, 0, (v * 100.) as u8);
        }
        let hue_offset = |color| 60. * (1. - (1. - color / RGB_MAX) / s);
        let r = hue_offset(r);
        let g = hue_offset(g);
        let b = hue_offset(b);
        let peak = r.max(g).max(b);
        let h = if r == peak { // mostly red
            if g < b { 360. - b } else { 000. + g }
        } else if g == peak { // mostly green
            if b < r { 120. - r } else { 120. + b }
        } else { // mostly blue
            if r < g { 240. - g } else { 240. + r }
        };
        let h = h.round() as u16;
        let s = (s * 100.).round() as u8;
        let v = (v * 100.).round() as u8;
        let hsv = (h, s, v);
        hsv
    }
    • function rgbToHsv(rgb) {
    • let r = rgb[0], g = rgb[1], b = rgb[2];
    • const v = Math.max(r, g, b) / 255;
    • if (v == 0) return Array.of(0, 0, 0);
    • r /= v;
    • g /= v;
    • b /= v;
    • const s = 1 - Math.min(r, g, b) / 255;
    • if (s == 0) return Array.of(0, 0, v * 100);
    • r = 255 - (255 - r) / s;
    • g = 255 - (255 - g) / s;
    • b = 255 - (255 - b) / s;
    • const peak = Math.max(r, g, b);
    • let h = 0;
    • if (r == peak) h = g < b ? 360 - b * 60 / 255 : g * 60 / 255;
    • else if (g == peak) h = r > b ? 120 - r * 60 / 255 : 120 + b * 60 / 255;
    • else h = r > g ? 240 + r * 60 / 255 : 240 - g * 60 / 255;
    • return Array.of(Math.round(h), Math.round(s * 100), Math.round(v * 100));
    • const RGB_MAX: f64 = 255.;
    • fn rgb_to_hsv(rgb: (u8, u8, u8)) -> (u16, u8, u8) {
    • let (r, g, b) = rgb;
    • let v = r.max(g).max(b) as f64 / RGB_MAX;
    • if v == 0. {
    • return (0, 0, 0);
    • }
    • let r = r as f64 / v;
    • let g = g as f64 / v;
    • let b = b as f64 / v;
    • let s = 1. - r.min(g).min(b) as f64 / RGB_MAX;
    • if s == 0. {
    • return (0, 0, (v * 100.) as u8);
    • }
    • let hue_offset = |color| 60. * (1. - (1. - color / RGB_MAX) / s);
    • let r = hue_offset(r);
    • let g = hue_offset(g);
    • let b = hue_offset(b);
    • let peak = r.max(g).max(b);
    • let h = if r == peak { // mostly red
    • if g < b { 360. - b } else { 000. + g }
    • } else if g == peak { // mostly green
    • if b < r { 120. - r } else { 120. + b }
    • } else { // mostly blue
    • if r < g { 240. - g } else { 240. + r }
    • };
    • let h = h.round() as u16;
    • let s = (s * 100.).round() as u8;
    • let v = (v * 100.).round() as u8;
    • let hsv = (h, s, v);
    • hsv
    • }

Mixing procedural while loops and functional iterator chaining? Why not! Theoretically just as fast, assuming the compiler is smart enough.

Code
Diff
  • use std::iter::repeat;
    
    pub fn sort_desc(mut n: u64) -> u64 {
        let mut digit_counts = [0; 10];
        while n > 0 {
            digit_counts[n as usize % 10] += 1;
            n /= 10;
        }
        digit_counts
            .into_iter()
            .enumerate()
            .rev()
            .flat_map(|(digit, count)| repeat(digit as u64).take(count))
            .fold(0, |result, digit| result * 10 + digit)
    }
    • use std::iter::repeat;
    • pub fn sort_desc(mut n: u64) -> u64 {
    • let mut digit_counts = [0; 10];
    • while n > 0 {
    • let digit = (n % 10) as usize;
    • digit_counts[digit] += 1;
    • digit_counts[n as usize % 10] += 1;
    • n /= 10;
    • }
    • let mut result = 0;
    • for digit in (0..10).rev() {
    • for _ in 0..digit_counts[digit] {
    • result *= 10;
    • result += digit as u64;
    • }
    • }
    • result
    • digit_counts
    • .into_iter()
    • .enumerate()
    • .rev()
    • .flat_map(|(digit, count)| repeat(digit as u64).take(count))
    • .fold(0, |result, digit| result * 10 + digit)
    • }

I used a different accumulation strategy. It's probably the same speed.

Code
Diff
  • pub fn sort_desc(mut n: u64) -> u64 {
        let mut digit_counts = [0; 10];
        while n > 0 {
            let digit = (n % 10) as usize;
            digit_counts[digit] += 1;
            n /= 10;
        }
        let mut result = 0;
        for digit in (0..10).rev() {
            for _ in 0..digit_counts[digit] {
                result *= 10;
                result += digit as u64;
            }
        }
        result
    }
    • pub fn sort_desc(mut n: u64) -> u64 {
    • let mut digit_counts = [0; 10];
    • while n > 0 {
    • let digit = (n % 10) as usize;
    • digit_counts[digit] += 1;
    • n /= 10;
    • }
    • let mut result = 0;
    • let mut fac = 1;
    • for digit in 0..10 {
    • for digit in (0..10).rev() {
    • for _ in 0..digit_counts[digit] {
    • result += (digit as u64) * fac;
    • fac *= 10;
    • result *= 10;
    • result += digit as u64;
    • }
    • }
    • result
    • }
Code
Diff
  • use itertools::Itertools;
    use std::ops::Neg;
    
    fn shannon_entropy(s: &str) -> f64 {
        let symbols: Vec<char> = s.chars().collect();
        let len = symbols.len() as f64;
        
        symbols
            .iter()
            .unique()
            .map(|x| {
                let p = symbols.iter().filter(|&n| n == x).count() as f64 / len;
                p * p.log2()
            })
            .sum::<f64>()
            .neg()
    }
    • import math
    • use itertools::Itertools;
    • use std::ops::Neg;
    • def shannon_entropy(s):
    • symbols = list(s)
    • unique_symbols = set(s)
    • M = float(len(s))
    • entropy_list = []
    • for x in unique_symbols:
    • n_i = symbols.count(x)
    • P_i = n_i / M
    • entropy_i = P_i * (math.log(P_i, 2))
    • entropy_list.append(entropy_i)
    • sh_entropy = -(sum(entropy_list))
    • return sh_entropy
    • fn shannon_entropy(s: &str) -> f64 {
    • let symbols: Vec<char> = s.chars().collect();
    • let len = symbols.len() as f64;
    • symbols
    • .iter()
    • .unique()
    • .map(|x| {
    • let p = symbols.iter().filter(|&n| n == x).count() as f64 / len;
    • p * p.log2()
    • })
    • .sum::<f64>()
    • .neg()
    • }
Algorithms
Strings
Code
Diff
  • fn remove_string(input: &str, n: usize) -> Option<&str> {
        if n == 0 { return None }
        input.split('\0').nth(n - 1)
    }
    • #include <stdlib.h>
    • #include <string.h>
    • /*
    • Heap allocate the string and return it.
    • */
    • char* remove_string(const char *input, const int n)
    • {
    • if (n <= 0 || input == NULL) return NULL;
    • size_t len = 0;
    • for (size_t i = 0; i < (size_t)n; ++i)
    • {
    • input += len;
    • len = strlen(input) + 1;
    • if (len == 1) return NULL;
    • }
    • size_t index = 0;
    • char *res = (char*)malloc(sizeof(char) * (len + 1));
    • for (; *input != '\0'; input++) res[index++] = *input; res[index] = '\0';
    • return res;
    • fn remove_string(input: &str, n: usize) -> Option<&str> {
    • if n == 0 { return None }
    • input.split('\0').nth(n - 1)
    • }
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()
    • }
Loading more items...