Ad
Code
Diff
  • fn price(servings: i32, price: i32) -> i32 {
        (servings > 0) as i32 * (servings * price + 1)
    }
    • fn price(servings: i32, price: i32) -> i32 {
    • match servings > 0 {
    • true => servings * price + 1,
    • false => 0
    • }
    • }
    • (servings > 0) as i32 * (servings * price + 1)
    • }

True coerces to 1, False coerces to 0

Code
Diff
  • def count(text: str) -> int:
        return sum(char in "AEIOUaeiou" for char in text)
    • def count(text: str) -> int:
    • return sum(1 for char in text if char in "AEIOUaeiou")
    • return sum(char in "AEIOUaeiou" for char in text)
Code
Diff
  • fn count(text: &str) -> usize {
        text.chars().filter(|&c| "AEIOUaeiou".contains(c)).count()
    }
    
    • def count():
    • #code
    • # Ispis rezultata
    • print("Broj samoglasnika u riječi je:", broj_samoglasnika)
    • fn count(text: &str) -> usize {
    • text.chars().filter(|&c| "AEIOUaeiou".contains(c)).count()
    • }
Code
Diff
  • fn get_ids(mut num: u32) -> u32 {
        let mut sum = 0;
        while num > 0 {
            sum += num % 10;
            num /= 10;
        }
        sum
    }
    • function getIDS($number) {
    • return array_sum(str_split($number));
    • fn get_ids(mut num: u32) -> u32 {
    • let mut sum = 0;
    • while num > 0 {
    • sum += num % 10;
    • num /= 10;
    • }
    • sum
    • }
Code
Diff
  • fn greet(name: &str) -> String {
        format!("hello my name is {name}")
    }
    • public class People {
    • private int age;
    • private String name;
    • private String lastName;
    • private String GREET="hello";
    • public String greet(){
    • return GREET +" my name is "+ name;
    • }
    • fn greet(name: &str) -> String {
    • format!("hello my name is {name}")
    • }
Code
Diff
  • fn morse_code(msg: &str) -> String {
        msg.chars().map(|c| MORSE[c as usize - 32]).collect::<Vec<&str>>().join(" ")
    }
    
    const MORSE: [&str; 91] = [
        "/", // 
        "-.-.--", // !
        ".-..-.", // "
        "�", // #
        "�", // $
        "�", // %
        ".-...", // &
        ".----.", // '
        "-.--.",  // (
        "-.--.-", // )
        "�", // *
        ".-.-.",  // +
        "--..--", // ,
        "-....-", // -
        ".-.-.-", // .
        "-..-.", // /
        
        "-----", // 0
        ".----", // 1
        "..---", // 2
        "...--", // 3
        "....-", // 4
        ".....", // 5
        "-....", // 6
        "--...", // 7
        "---..", // 8
        "----.", // 9
        
        "---...", // :
        "�", // ;
        "�", // <
        "-...-", // =
        "�", // >
        "..--..", // ?
        ".--.-.", // @
        
        ".-",   // A
        "-...", // B
        "-.-.", // C
        "-..",  // D
        ".",    // E
        "..-.", // F
        "--.",  // G
        "....", // H
        "..",   // I
        ".---", // J
        "-.-",  // K
        ".-..", // L
        "--",   // M
        "-.",   // N
        "---",  // O
        ".--.", // P
        "--.-", // Q
        ".-.",  // R
        "...",  // S
        "-",    // T
        "..-",  // U
        "...-", // V
        ".--",  // W
        "-..-", // X
        "-.--", // Y
        "-..",  // Z
        
        "-.--.", // [
        "�", // \
        "-.--.-", // ]
        "�", // ^
        "..--.-", // _
        "�", // `
        
        ".-",   // a
        "-...", // b
        "-.-.", // c
        "-..",  // d
        ".",    // e
        "..-.", // f
        "--.",  // g
        "....", // h
        "..",   // i
        ".---", // j
        "-.-",  // k
        ".-..", // l
        "--",   // m
        "-.",   // n
        "---",  // o
        ".--.", // p
        "--.-", // q
        ".-.",  // r
        "...",  // s
        "-",    // t
        "..-",  // u
        "...-", // v
        ".--",  // w
        "-..-", // x
        "-.--", // y
        "-..",  // z
    ];
    
    • dot='.'
    • dash='-'
    • morse = {'a':[dot,dash],'b':[dash,dot,dot,dot],'c':[dash,dot,dash,dot],'d':[dash,dot,dot],'e':[dot],'f':[dot,dot,dash,dot],'g':[dash,dash,dot],'h':[dot,dot,dot,dot],""
    • 'i':[dot,dot],'j':[dot,dash,dash,dash],'k':[dash,dot,dash],'l':[dot,dash,dot,dot],'m':[dash,dash],'n':[dash,dot],'o':[dash,dash,dash],'p':[dot,dash,dash],'q':[dash,dash,dot,dash],""
    • 'r':[dot,dash,dot],'s':[dot,dot,dot],'t':[dash],'u':[dot,dot,dash],'v':[dot,dot,dot,dash],'w':[dot,dash,dash],'x':[dash,dot,dot,dash],'y':[dash,dot,dash,dash],'z':[dash,dot,dot],""
    • '0':[dash,dash,dash,dash,dash],'1':[dot,dash,dash,dash,dash],'2':[dot,dot,dash,dash,dash],'3':[dot,dot,dot,dash,dash],'4':[dot,dot,dot,dot,dash],'5':[dot,dot,dot,dot,dot],""
    • '6':[dash,dot,dot,dot,dot],'7':[dash,dash,dot,dot,dot],'8':[dash,dash,dash,dot,dot],'9':[dash,dash,dash,dash,dot]}
    • fn morse_code(msg: &str) -> String {
    • msg.chars().map(|c| MORSE[c as usize - 32]).collect::<Vec<&str>>().join(" ")
    • }
    • def morse_code(msg):
    • code=''
    • for i in msg:
    • if i==' ':
    • code+=' '
    • else:
    • for j in morse[i.lower()]:
    • code+=j
    • return code
    • print(morse_code('1122'))
    • const MORSE: [&str; 91] = [
    • "/", //
    • "-.-.--", // !
    • ".-..-.", // "
    • "�", // #
    • "�", // $
    • "�", // %
    • ".-...", // &
    • ".----.", // '
    • "-.--.", // (
    • "-.--.-", // )
    • "�", // *
    • ".-.-.", // +
    • "--..--", // ,
    • "-....-", // -
    • ".-.-.-", // .
    • "-..-.", // /
    • "-----", // 0
    • ".----", // 1
    • "..---", // 2
    • "...--", // 3
    • "....-", // 4
    • ".....", // 5
    • "-....", // 6
    • "--...", // 7
    • "---..", // 8
    • "----.", // 9
    • "---...", // :
    • "�", // ;
    • "�", // <
    • "-...-", // =
    • "�", // >
    • "..--..", // ?
    • ".--.-.", // @
    • ".-", // A
    • "-...", // B
    • "-.-.", // C
    • "-..", // D
    • ".", // E
    • "..-.", // F
    • "--.", // G
    • "....", // H
    • "..", // I
    • ".---", // J
    • "-.-", // K
    • ".-..", // L
    • "--", // M
    • "-.", // N
    • "---", // O
    • ".--.", // P
    • "--.-", // Q
    • ".-.", // R
    • "...", // S
    • "-", // T
    • "..-", // U
    • "...-", // V
    • ".--", // W
    • "-..-", // X
    • "-.--", // Y
    • "-..", // Z
    • "-.--.", // [
    • "�", // \
    • "-.--.-", // ]
    • "�", // ^
    • "..--.-", // _
    • "�", // `
    • ".-", // a
    • "-...", // b
    • "-.-.", // c
    • "-..", // d
    • ".", // e
    • "..-.", // f
    • "--.", // g
    • "....", // h
    • "..", // i
    • ".---", // j
    • "-.-", // k
    • ".-..", // l
    • "--", // m
    • "-.", // n
    • "---", // o
    • ".--.", // p
    • "--.-", // q
    • ".-.", // r
    • "...", // s
    • "-", // t
    • "..-", // u
    • "...-", // v
    • ".--", // w
    • "-..-", // x
    • "-.--", // y
    • "-..", // z
    • ];
Code
Diff
  • fn price(servings: u32, price: u32) -> u32 {
        let mut cost = servings * price;
        if servings > 0 {
            cost += 1
        }
        cost
    }
    
    • def price(servings, price):
    • if servings >0:
    • cost = servings * price
    • fn price(servings: u32, price: u32) -> u32 {
    • let mut cost = servings * price;
    • if servings > 0 {
    • cost += 1
    • return cost
    • else:
    • return 0
    • }
    • cost
    • }
Code
Diff
  • fn reverse_string(word: &str) -> String {
        word.chars().rev().collect()
    }
    • public class ReverseString {
    • public static String reverseString(String word) {
    • String reversedWord = "";
    • for (int i = 0; i < word.length(); i++) {
    • reversedWord = word.charAt(i) + reversedWord;
    • }
    • return reversedWord;
    • }
    • fn reverse_string(word: &str) -> String {
    • word.chars().rev().collect()
    • }
Code
Diff
  • fn fizzbuzz(n: u32) -> String {
        if is_prime(n) {
            "Prime".to_owned()
        } else if n % 15 == 0 {
            "FizzBuzz".to_owned()
        } else if n % 3 == 0 {
            "Fizz".to_owned()
        } else if n % 5 == 0 {
            "Buzz".to_owned()
        } else {
            n.to_string()
        }
    }
    
    // inefficient but this is just a simple demonstration
    fn is_prime(n: u32) -> bool {
        n > 1 && (2..n).all(|d| n % d != 0)
    }
    • class IsPrimeNumber:
    • """Returns True if n is a prime number, False otherwise"""
    • def __init__(self, n):
    • self.n = n
    • def calculate(self):
    • pass
    • class Fizz:
    • """Returns True if n is divisible by 3, False otherwise"""
    • def __init__(self, n):
    • self.n = n
    • def calculate(self):
    • pass
    • class Buzz:
    • """Returns True if n is divisible by 5, False otherwise"""
    • def __init__(self, n):
    • self.n = n
    • def calculate(self):
    • pass
    • class FizzBuzz:
    • """Returns True if n is divisible by 3 and 5, False otherwise"""
    • def __init__(self, n):
    • self.n = n
    • def calculate(self):
    • pass
    • class CodeWarKata776:
    • """Executes the Fizz, Bizz, FizzBuzz Prime sequence."""
    • def __init__(self, n):
    • self.n = n
    • def calculate_prime(self):
    • pass
    • def calculate_fizz(self):
    • pass
    • def calculate_buzz(self):
    • pass
    • def calculate_fizzbuzz(self):
    • pass
    • def execute(self):
    • pass
    • fn fizzbuzz(n: u32) -> String {
    • if is_prime(n) {
    • "Prime".to_owned()
    • } else if n % 15 == 0 {
    • "FizzBuzz".to_owned()
    • } else if n % 3 == 0 {
    • "Fizz".to_owned()
    • } else if n % 5 == 0 {
    • "Buzz".to_owned()
    • } else {
    • n.to_string()
    • }
    • }
    • // inefficient but this is just a simple demonstration
    • fn is_prime(n: u32) -> bool {
    • n > 1 && (2..n).all(|d| n % d != 0)
    • }

Correction pour agir comme la question originale decrit.

Code
Diff
  • fn closest_to_zero(ints: &[i32]) -> i32 {
        *ints.iter().min_by_key(|x| (x.abs(), x.is_negative())).unwrap_or(&0)
    }
    
    • fn closest_to_zero(ints: &[i32]) -> i32 {
    • *ints.iter().min_by_key(|x| x.abs()).unwrap_or(&0)
    • *ints.iter().min_by_key(|x| (x.abs(), x.is_negative())).unwrap_or(&0)
    • }

Two can play at that game 🦀 (admittedly less straightforward since Rust is more explicit around operations and potential errors)

Code
Diff
  • fn reverse_int(n: u128) -> u128 {
        n.to_string().chars().rev().collect::<String>().parse().unwrap()
    }
    
    
    
    • def reverse_int(n):
    • return int(str(n)[::-1])
    • fn reverse_int(n: u128) -> u128 {
    • n.to_string().chars().rev().collect::<String>().parse().unwrap()
    • }
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()
    • }
Loading more items...