Ad
Code
Diff
  • fn find_the_longest_word(sentence: &str) -> Option<&str> {
        let max_len = sentence.split_whitespace().map(str::len).max()?;
        let mut max_words = sentence.split_whitespace().filter(|word| word.len() == max_len);
        let first_max = max_words.next();
        let second_max = max_words.next();
        if second_max.is_some() {
            return None;
        }
        first_max
    }
    
    
    • use std::cmp::Ordering;
    • fn find_the_longest_word(sentence: &str) -> Option<&str> {
    • let mut longest_word = None;
    • let mut max_length = 0;
    • for word in sentence.split_whitespace() {
    • match word.len().cmp(&max_length) {
    • Ordering::Less => {},
    • Ordering::Equal => {
    • if longest_word.is_none() {
    • longest_word = Some(word);
    • } else {
    • max_length += 1;
    • longest_word = None;
    • }
    • },
    • Ordering::Greater => {
    • max_length = word.len();
    • longest_word = Some(word);
    • }
    • }
    • let max_len = sentence.split_whitespace().map(str::len).max()?;
    • let mut max_words = sentence.split_whitespace().filter(|word| word.len() == max_len);
    • let first_max = max_words.next();
    • let second_max = max_words.next();
    • if second_max.is_some() {
    • return None;
    • }
    • longest_word
    • first_max
    • }
Code
Diff
  • fn find_squares_in_array(arr: &[i32]) -> i32 {
        arr.iter().map(|n| n.pow(2)).sum()
    }
    
    
    • using System;
    • public class Program
    • {
    • public static int FindSquaresInArray(int[] arr)
    • {
    • int sum = 0;
    • for (int i = 0; i < arr.Length; i++)
    • {
    • for (int j = 0; j < arr[i]; j++)
    • {
    • sum += arr[i];
    • }
    • }
    • return sum;
    • }
    • fn find_squares_in_array(arr: &[i32]) -> i32 {
    • arr.iter().map(|n| n.pow(2)).sum()
    • }

1 character shorter.

Code
Diff
  • fn return_int(i:u8)->u8{i}
    • fn return_int<T>(i:T)->T{i}
    • fn return_int(i:u8)->u8{i}

"optimization"

Code
Diff
  • fn return_int<T>(i:T)->T{i}
    • fn return_int(i: i32) -> i32 { i }
    • fn return_int<T>(i:T)->T{i}

More pedantic approach. nand function in different module to represent it being the primitive.

Code
Diff
  • mod preloaded;
    use preloaded::nand;
    
    fn not(a: bool) -> bool {
        nand(a, a)
    }
    
    fn and(a: bool, b: bool) -> bool {
        nand(nand(a, b), nand(a, b))
    }
    
    fn or(a: bool, b: bool) -> bool {
        nand(nand(a, a), nand(b, b))
    }
    
    fn xor(a: bool, b: bool) -> bool {
        nand(nand(nand(a, b), nand(nand(a, a), nand(b, b))), nand(nand(a, b), nand(nand(a, a), nand(b, b))))
    }
    
    fn nor(a: bool, b: bool) -> bool {
        nand(nand(nand(a, a), nand(b, b)), nand(nand(a, a), nand(b, b)))
    }
    
    fn xnor(a: bool, b: bool) -> bool {
        nand(nand(a, b), nand(nand(a, a), nand(b, b)))
    }
    
    • fn nand(a: bool, b: bool) -> bool {
    • !(a && b)
    • }
    • mod preloaded;
    • use preloaded::nand;
    • fn not(a: bool) -> bool {
    • nand(a, a)
    • }
    • fn and(a: bool, b: bool) -> bool {
    • not(nand(a, b))
    • nand(nand(a, b), nand(a, b))
    • }
    • fn or(a: bool, b: bool) -> bool {
    • nand(not(a), not(b))
    • nand(nand(a, a), nand(b, b))
    • }
    • fn xor(a: bool, b: bool) -> bool {
    • and(nand(a, b), or(a, b))
    • nand(nand(nand(a, b), nand(nand(a, a), nand(b, b))), nand(nand(a, b), nand(nand(a, a), nand(b, b))))
    • }
    • fn nor(a: bool, b: bool) -> bool {
    • and(not(a), not(b))
    • nand(nand(nand(a, a), nand(b, b)), nand(nand(a, a), nand(b, b)))
    • }
    • fn xnor(a: bool, b: bool) -> bool {
    • nand(nand(a, b), nand(nand(a, a), nand(b, b)))
    • }
Code
Diff
  • fn multiply<T: std::ops::Mul>(a: T, b: T) -> T::Output {
        a * b
    }
    • fn multiply<T: std::ops::Mul<Output = T>>(a: T, b: T) -> T {
    • fn multiply<T: std::ops::Mul>(a: T, b: T) -> T::Output {
    • a * b
    • }
Code
Diff
  • fn twin_sum_solutions(array: &[i32]) -> Vec<i32> {
        array
            .windows(2)
            .filter(|w| w[0] == w[1])
            .map(|w| w[0] + w[1])
            .collect()
    }
    • // Code goes here
    • fn twin_sum_solutions(array: &[i32]) -> Vec<i32> {
    • array
    • .windows(2)
    • .filter(|w| w[0] == w[1])
    • .map(|w| w[0] + w[1])
    • .collect()
    • }
Code
Diff
  • fn disemvowel(string: &str) -> String {
        string.chars().filter(|&c| !"AEIOUaeiou".contains(c)).collect()
    }
    • def disemvowel(string_):
    • list_of_oo = ["a", "e", "i", "o", "u", "O" ,"A" ,"E" ,"I"]
    • newset = ""
    • n = 0
    • while n < len(list_of_oo):
    • for i in string_:
    • if list_of_oo[n] == i:
    • string_ = string_.replace(i , "-")
    • print(list_of_oo[n])
    • n += 1
    • return string_
    • fn disemvowel(string: &str) -> String {
    • string.chars().filter(|&c| !"AEIOUaeiou".contains(c)).collect()
    • }
Fundamentals
Games
Code
Diff
  • fn riddle(word: &str) -> usize {
        word.trim_matches(|c: char| !c.is_ascii_alphabetic()).len()
    }
    • def riddle(word):
    • return len(word) - 1
    • fn riddle(word: &str) -> usize {
    • word.trim_matches(|c: char| !c.is_ascii_alphabetic()).len()
    • }
Code
Diff
  • fn hello<T: Locale>(whoever: &str) -> String {
        T::say_hello_to(whoever)
    }
    
    trait Locale {
        fn say_hello_to(whoever: &str) -> String;
    }
    
    struct English;
    
    impl Locale for English {
        fn say_hello_to(whoever: &str) -> String {
            format!("hello {whoever}")
        }
    }
    
    struct Pirate;
    
    impl Locale for Pirate {
        fn say_hello_to(whoever: &str) -> String {
            format!("yar {whoever}")
        }
    }
    
    struct Binary<T>(std::marker::PhantomData::<T>);
    
    impl<T: Locale> Locale for Binary<T> {
        fn say_hello_to(whoever: &str) -> String {
            T::say_hello_to(whoever)
                .chars()
                .map(|ch| format!("{:08b}", ch as u8))
                .collect()
        }
    }
    • class Locale {
    • sayHelloTo(whoever){
    • throw new Error("Not implemented");
    • }
    • fn hello<T: Locale>(whoever: &str) -> String {
    • T::say_hello_to(whoever)
    • }
    • class EnglishLocale extends Locale {
    • sayHelloTo(whoever){
    • return `hello ${whoever}`;
    • }
    • trait Locale {
    • fn say_hello_to(whoever: &str) -> String;
    • }
    • class PirateLocale extends Locale {
    • sayHelloTo(whoever){
    • return `yar ${whoever}`;
    • }
    • }
    • struct English;
    • class BinaryLocale extends EnglishLocale {
    • sayHelloTo(whoever) {
    • let msg = super.sayHelloTo(whoever);
    • return this.txtToBin(msg);
    • }
    • txtToBin(text) {
    • let result = [];
    • for(let character of text){
    • let binaryArr = this.numberToBinaryArray(character.charCodeAt());
    • result = result.concat(binaryArr);
    • impl Locale for English {
    • fn say_hello_to(whoever: &str) -> String {
    • format!("hello {whoever}")
    • }
    • }
    • return result.join("");
    • }
    • numberToBinaryArray(number) {
    • let result = [];
    • while(number > 0){
    • let bit = Math.floor(number % 2) != 0 ? 1 : 0;
    • result.unshift(bit)
    • number = Math.floor(number / 2);
    • }
    • struct Pirate;
    • while(result.length != 8) {
    • result.unshift(0);
    • impl Locale for Pirate {
    • fn say_hello_to(whoever: &str) -> String {
    • format!("yar {whoever}")
    • }
    • return result;
    • }
    • }
    • const GREET_LANG = {
    • ENGLISH: new EnglishLocale(),
    • PIRATE: new PirateLocale(),
    • BINARY: new BinaryLocale(),
    • }
    • struct Binary<T>(std::marker::PhantomData::<T>);
    • const hello = (whoever, lang=GREET_LANG.ENGLISH) => lang.sayHelloTo(whoever);
    • impl<T: Locale> Locale for Binary<T> {
    • fn say_hello_to(whoever: &str) -> String {
    • T::say_hello_to(whoever)
    • .chars()
    • .map(|ch| format!("{:08b}", ch as u8))
    • .collect()
    • }
    • }
Code
Diff
  • fn contains_common_item(a: &[char], b: &[char]) -> bool {
        a.iter().any(|n| b.contains(n))
    }
    • //Given 2 Arrays, Return True if arrays contain common item, else false.
    • //e.g a= ['a','b','g','c'] and b =['z','e','c'] returns true
    • // naive approach, loop through first array, with each item in a, loop through b and compare item to
    • //each item in b returning true if a match is found or false.
    • //input : 2 arrays
    • //output: bool
    • using System.Collections.Generic;
    • public class Kata{
    • public static bool ContainsCommonItem(char[] a, char[] b){ //naive O(a*b)
    • for(int i=0;i<a.Length;i++)
    • for(int j=0; j< b.Length; j++)
    • if(a[i]==b[j])
    • return true;
    • return false;
    • }
    • public static bool ContainsCommonItemBetter(char[] a,char[]b){
    • HashSet<char> items = new HashSet<char>();
    • foreach(char item in a)
    • items.Add(item);
    • for (int i =0; i< b.Length; i++)
    • if (items.Contains(b[i]))
    • return true;
    • return false;
    • }
    • }
    • fn contains_common_item(a: &[char], b: &[char]) -> bool {
    • a.iter().any(|n| b.contains(n))
    • }
Code
Diff
  • use std::cmp::Ordering;
    
    fn find_the_longest_word(sentence: &str) -> Option<&str> {
        let mut longest_word = None;
        let mut max_length = 0;
        for word in sentence.split_whitespace() {
            match word.len().cmp(&max_length) {
                Ordering::Less => {},
                Ordering::Equal => {
                    if longest_word.is_none() {
                        longest_word = Some(word);
                    } else {             
                        max_length += 1;
                        longest_word = None;
                    }
                },
                Ordering::Greater => {
                    max_length = word.len();
                    longest_word = Some(word);
                }
            }
        }
        longest_word
    }
    
    
    • export function findTheLongestWord (sentence?: string): string{
    • // You Can Code Below Here
    • return ``
    • }
    • use std::cmp::Ordering;
    • fn find_the_longest_word(sentence: &str) -> Option<&str> {
    • let mut longest_word = None;
    • let mut max_length = 0;
    • for word in sentence.split_whitespace() {
    • match word.len().cmp(&max_length) {
    • Ordering::Less => {},
    • Ordering::Equal => {
    • if longest_word.is_none() {
    • longest_word = Some(word);
    • } else {
    • max_length += 1;
    • longest_word = None;
    • }
    • },
    • Ordering::Greater => {
    • max_length = word.len();
    • longest_word = Some(word);
    • }
    • }
    • }
    • longest_word
    • }
Code
Diff
  • #[derive(Default)]
    struct Node {
        code: &'static str,
        bomb: bool,
        children: Vec<Node>,
    }
    
    // precondition: there is only one bomb in the recursive structure
    fn find_the_bomb(nodes: &[Node]) -> Option<String> {
        nodes
            .iter()
            .find_map(|node| {
                if node.bomb {
                    return Some(node.code.to_string());
                }
                if let Some(bomb) = find_the_bomb(&node.children) {
                    return Some(format!("{} > {}", node.code, bomb))
                }
                None
            })
    }
    
    • interface ListOfBoxes {
    • code: string,
    • bomb?: boolean,
    • boxes?: ListOfBoxes[]
    • #[derive(Default)]
    • struct Node {
    • code: &'static str,
    • bomb: bool,
    • children: Vec<Node>,
    • }
    • export function findTheBomb (listOfBoxes: ListOfBoxes[]): string{
    • // You Can Code Below Here
    • return ``
    • }
    • // precondition: there is only one bomb in the recursive structure
    • fn find_the_bomb(nodes: &[Node]) -> Option<String> {
    • nodes
    • .iter()
    • .find_map(|node| {
    • if node.bomb {
    • return Some(node.code.to_string());
    • }
    • if let Some(bomb) = find_the_bomb(&node.children) {
    • return Some(format!("{} > {}", node.code, bomb))
    • }
    • None
    • })
    • }
Code
Diff
  • fn filtering_data_more_than_equal(mut data: Vec<i32>, comparator: i32) -> Vec<i32> {
        data.retain(|&num| num >= comparator);
        data
    }
    • export function filteringDataMoreThanEqual (data: number[], comparator: number): string{
    • return String(data);
    • fn filtering_data_more_than_equal(mut data: Vec<i32>, comparator: i32) -> Vec<i32> {
    • data.retain(|&num| num >= comparator);
    • data
    • }
Code
Diff
  • fn factorial(n: u8) -> u64 {
        if n == 0 {
            1
        } else {
            n as u64 * factorial(n - 1)
        }
    }
    • def factorial(n):
    • # your code goes here
    • return
    • fn factorial(n: u8) -> u64 {
    • if n == 0 {
    • 1
    • } else {
    • n as u64 * factorial(n - 1)
    • }
    • }
Loading more items...