use itertools::Itertools; fn sort_desc(number: u64) -> u64 { number.to_string().chars().sorted().rev().collect::<String>().parse().unwrap() }
- use itertools::Itertools;
fn print(number: u64) -> u64 {- fn sort_desc(number: u64) -> u64 {
- number.to_string().chars().sorted().rev().collect::<String>().parse().unwrap()
- }
#[cfg(test)] mod tests { use super::sort_desc; fn do_test(number: u64, expected: u64) { let actual = sort_desc(number); assert_eq!(actual, expected, "For {} expected {} but got {}", number, expected, actual); } #[test] fn test_sort_desc() { do_test(0, 0); do_test(1, 1); do_test(12, 21); do_test(123, 321); do_test(12345, 54321); do_test(123456789, 987654321); do_test(1234567890, 9876543210); } #[test] fn random_test() { fn solution(number: u64) -> u64 { let mut number = number.to_string().chars().map(|c| c.to_digit(10).unwrap() as u64).collect::<Vec<u64>>(); number.sort(); number.iter().rev().map(|c| c.to_string()).collect::<Vec<String>>().join("").parse::<u64>().unwrap() } for _ in 0..100 { let number = rand::random::<u32>(); do_test(number as u64, solution(number as u64)); } } }
#[test]fn test() {assert_eq!(print(4), 4);assert_eq!(print(12), 21);assert_eq!(print(101), 110);assert_eq!(print(400000005000007000), 754000000000000000);assert_eq!(print(307778062924466824), 988777666444322200);}- #[cfg(test)]
- mod tests {
- use super::sort_desc;
- fn do_test(number: u64, expected: u64) {
- let actual = sort_desc(number);
- assert_eq!(actual, expected, "For {} expected {} but got {}", number, expected, actual);
- }
- #[test]
- fn test_sort_desc() {
- do_test(0, 0);
- do_test(1, 1);
- do_test(12, 21);
- do_test(123, 321);
- do_test(12345, 54321);
- do_test(123456789, 987654321);
- do_test(1234567890, 9876543210);
- }
- #[test]
- fn random_test() {
- fn solution(number: u64) -> u64 {
- let mut number = number.to_string().chars().map(|c| c.to_digit(10).unwrap() as u64).collect::<Vec<u64>>();
- number.sort();
- number.iter().rev().map(|c| c.to_string()).collect::<Vec<String>>().join("").parse::<u64>().unwrap()
- }
- for _ in 0..100 {
- let number = rand::random::<u32>();
- do_test(number as u64, solution(number as u64));
- }
- }
- }
#[cfg(test)] mod tests { use super::disemvowel; use rand::Rng; fn do_test(string: &str, expected: &str) { assert_eq!(disemvowel(string), expected); } #[test] fn test() { do_test("HI GUYS", "H GYS"); do_test("AEIOU", ""); do_test("Shrek is an orge", "Shrk s n rg"); } #[test] fn random_tests() { for _ in 0..100 { let string = (0..rand::thread_rng().gen_range(0..20)) .map(|_| rand::Rng::sample(&mut rand::thread_rng(), rand::distributions::Alphanumeric) as char) .collect::<String>(); let expected = string.chars().filter(|&c| !"AEIOUaeiou".contains(c)).collect::<String>(); do_test(&string, &expected); } } }
- #[cfg(test)]
- mod tests {
- use super::disemvowel;
- use rand::Rng;
- fn do_test(string: &str, expected: &str) {
- assert_eq!(disemvowel(string), expected);
- }
- #[test]
- fn test() {
assert_eq!(disemvowel("HI GUYS"), "H GYS");assert_eq!(disemvowel("AEIOU"), "");assert_eq!(disemvowel("Shrek is an orge"), "Shrk s n rg");- do_test("HI GUYS", "H GYS");
- do_test("AEIOU", "");
- do_test("Shrek is an orge", "Shrk s n rg");
- }
- #[test]
- fn random_tests() {
- for _ in 0..100 {
- let string = (0..rand::thread_rng().gen_range(0..20))
- .map(|_| rand::Rng::sample(&mut rand::thread_rng(), rand::distributions::Alphanumeric) as char)
- .collect::<String>();
- let expected = string.chars().filter(|&c| !"AEIOUaeiou".contains(c)).collect::<String>();
- do_test(&string, &expected);
- }
- }
- }
Algorithms
Arrays
Mathematics
Geometry
#[cfg(test)] mod test { use super::make_move; fn do_test(init: (i32, i32), sequence: &str, expected: (i32, i32)) { assert_eq!(make_move(init, sequence), expected); } #[test] fn simple_test() { do_test((0, 0), "ttrbrrbllrt", (2, 1)); do_test((4, 1), "bllbrt", (3, 0)); do_test((-2, 4), "trlbb", (-2, 3)); do_test((5, 5), "trlbrb", (6, 4)); } #[test] fn random_test() { use rand::Rng; use std::iter; fn generate(len: usize) -> String { const CHARSET: &[u8] = b"lrbt"; let mut rng = rand::thread_rng(); let one_char = || CHARSET[rng.gen_range(0..CHARSET.len())] as char; iter::repeat_with(one_char).take(len).collect() } fn solution(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, }, ) }) } for _ in 0..100 { let init = ( rand::thread_rng().gen_range(-100..100), rand::thread_rng().gen_range(-100..100), ); let sequence = generate(rand::thread_rng().gen_range(0..100)); let expected = solution(init, &sequence); do_test(init, &sequence, expected); } } }
#[test]fn test() {assert_eq!(make_move((0, 0), "ttrbrrbllrt"), (2, 1));assert_eq!(make_move((4, 1), "bllbrt"), (3, 0));assert_eq!(make_move((-2, 4), "trlbb"), (-2, 3));assert_eq!(make_move((5, 5), "trlbrb"), (6, 4));- #[cfg(test)]
- mod test {
- use super::make_move;
- fn do_test(init: (i32, i32), sequence: &str, expected: (i32, i32)) {
- assert_eq!(make_move(init, sequence), expected);
- }
- #[test]
- fn simple_test() {
- do_test((0, 0), "ttrbrrbllrt", (2, 1));
- do_test((4, 1), "bllbrt", (3, 0));
- do_test((-2, 4), "trlbb", (-2, 3));
- do_test((5, 5), "trlbrb", (6, 4));
- }
- #[test]
- fn random_test() {
- use rand::Rng;
- use std::iter;
- fn generate(len: usize) -> String {
- const CHARSET: &[u8] = b"lrbt";
- let mut rng = rand::thread_rng();
- let one_char = || CHARSET[rng.gen_range(0..CHARSET.len())] as char;
- iter::repeat_with(one_char).take(len).collect()
- }
- fn solution(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,
- },
- )
- })
- }
- for _ in 0..100 {
- let init = (
- rand::thread_rng().gen_range(-100..100),
- rand::thread_rng().gen_range(-100..100),
- );
- let sequence = generate(rand::thread_rng().gen_range(0..100));
- let expected = solution(init, &sequence);
- do_test(init, &sequence, expected);
- }
- }
- }
Strings
#[cfg(test)] mod tests { use rand::distributions::{Alphanumeric, Distribution}; use rand::Rng; use std::collections::BTreeSet; use super::is_unique; fn do_test(input: &str, expected: bool) { let actual = is_unique(input); assert_eq!(actual, expected, "failed for input: \"{}\"", input); } #[test] fn test_unique() { do_test("abcdef", true); do_test("Aabcdef", true); do_test("gino", true); do_test("glhf", true); } #[test] fn test_repeated() { do_test("aabcdef", false); do_test("gg", false); do_test("phillip", false); } #[test] fn test_empty() { do_test("", true); } #[test] fn random_test() { for _ in 0..100 { let length: usize = rand::thread_rng().gen_range(0..10); let input: String = Alphanumeric .sample_iter(&mut rand::thread_rng()) .take(length) .map(char::from) .collect(); let expected = input.chars().collect::<BTreeSet<_>>().len() == input.len(); do_test(&input, expected); } } }
- #[cfg(test)]
- mod tests {
- use rand::distributions::{Alphanumeric, Distribution};
- use rand::Rng;
- use std::collections::BTreeSet;
- use super::is_unique;
- fn do_test(input: &str, expected: bool) {
- let actual = is_unique(input);
- assert_eq!(actual, expected, "failed for input: \"{}\"", input);
- }
- #[test]
- fn test_unique() {
assert!(is_unique("abcdef"));assert!(is_unique("Aabcdef"));assert!(is_unique("gino"));assert!(is_unique("glhf"));- do_test("abcdef", true);
- do_test("Aabcdef", true);
- do_test("gino", true);
- do_test("glhf", true);
- }
- #[test]
- fn test_repeated() {
assert!(!is_unique("aabcdef"));assert!(!is_unique("gg"));assert!(!is_unique("phillip"));- do_test("aabcdef", false);
- do_test("gg", false);
- do_test("phillip", false);
- }
- #[test]
- fn test_empty() {
assert!(is_unique(""));- do_test("", true);
- }
- #[test]
- fn random_test() {
- for _ in 0..100 {
- let length: usize = rand::thread_rng().gen_range(0..10);
- let input: String = Alphanumeric
- .sample_iter(&mut rand::thread_rng())
- .take(length)
- .map(char::from)
- .collect();
- let expected = input.chars().collect::<BTreeSet<_>>().len() == input.len();
- do_test(&input, expected);
- }
- }
Algorithms
Data Structures
Simulation
Logic
Games
Date Time
use std::collections::HashMap; fn time_parse(time: &str) -> f64 { let (h, m) = time.split_once(':').unwrap(); h.parse::<f64>().unwrap() * 60. + m.parse::<f64>().unwrap() } fn from_min_to_string(min: f64) -> String { let h = (min / 60.).floor() % 24.; let m = (min % 60.).floor(); format!("{:02}:{:02}", h, m) } const BUS_SCHEDULES: &str = r#"Skyport Crystalium 15 min 2 hours Crystalium Skyport 10 min 2 hours Skyport Oasis 20 min 3 hours Oasis Skyport 15 min 3 hours Oasis Crystalium 15 min 1.5 hours Crystalium Oasis 10 min 1.5 hours Skyport Nexus 15 min 4 hours Nexus Skyport 10 min 4 hours "#; fn arrival_time(route: Vec<&str>, departure_time: &str) -> String { let origin: Vec<&str> = vec!("Skyport"); if route.is_empty() { return "The Train Driver has the day off".to_string(); } else { let from = 0; let to = 1; let standby_time = 2; let travel_time = 4; let mut bus: HashMap<(String, String), (String, String)> = HashMap::new(); for line in BUS_SCHEDULES.lines() { let data = line.split_whitespace().collect::<Vec<_>>(); let bus_stop = (data[from].to_string(), data[to].to_string()); let data_stop = ( data[standby_time].to_string(), data[travel_time].to_string(), ); bus.insert(bus_stop, data_stop); } let mut total_travel_time = 0.0; let full_route: Vec<&&str> = origin.iter().chain(route.iter()).collect::<Vec<_>>(); for item in full_route.windows(2) { if item[0] == item[1] { total_travel_time += 1. * 60.; } else { let bus_stop = (item[0].to_string(), item[1].to_string()); match bus.get(&bus_stop) { Some((waiting_time, travel_time)) => { total_travel_time += travel_time.parse::<f64>().unwrap() * 60. + waiting_time.parse::<f64>().unwrap(); } None => { let back_to_origin = (item[0].to_string(), origin[0].to_string()); let from_origin_to_route = (origin[0].to_string(), item[1].to_string()); match bus.get(&back_to_origin) { Some((waiting_time, travel_time)) => { total_travel_time += travel_time.parse::<f64>().unwrap() * 60. + waiting_time.parse::<f64>().unwrap(); } None => { panic!("Could not find route between {} and Skyport", item[0]); } } match bus.get(&from_origin_to_route) { Some((waiting_time, travel_time)) => { total_travel_time += travel_time.parse::<f64>().unwrap() * 60. + waiting_time.parse::<f64>().unwrap(); } None => { panic!("Could not find route between Skyport and {}", item[1]); } } } } } } from_min_to_string(total_travel_time + time_parse(departure_time)) } }
import java.time.LocalTime;import java.time.format.DateTimeFormatter;import java.util.HashMap;import java.util.Map;public class Kata {public static String arrivalTime(final String[] route, final String departureTime) {if (route.length == 0) return "The Train Driver has the day off";LocalTime timeResult = LocalTime.parse(departureTime, DateTimeFormatter.ofPattern("HH:mm"));String origin = "Skyport";int index = 0;while (index < route.length) {String destination = route[index];Map<String, double[]> destinationMap = tableTime.get(origin);if (destinationMap != null && destinationMap.containsKey(destination)) {double[] times = destinationMap.get(destination);timeResult = calculateTime(timeResult, times);origin = destination;index++;} else if (origin.equals(destination)) {timeResult = timeResult.plusHours(1);index++;} else {String transfer = "Skyport";double[] times = tableTime.get(origin).get(transfer);timeResult = calculateTime(timeResult, times);origin = transfer;}}return timeResult.format(DateTimeFormatter.ofPattern("HH:mm"));}private static Map<String, Map<String, double[]>> tableTime = new HashMap<String, Map<String, double[]>>() {{addRecord("Skyport", "Crystalium", 15, 2);addRecord("Skyport", "Oasis", 20, 3);addRecord("Oasis", "Crystalium", 15, 1.5);addRecord("Skyport", "Nexus", 15, 4);}private void addRecord(final String origin, final String destiny, final double minutesWait,final double hoursTravel) {putIfAbsent(origin, new HashMap<>());get(origin).put(destiny, new double[] { minutesWait, hoursTravel });putIfAbsent(destiny, new HashMap<>());get(destiny).put(origin, new double[] { minutesWait - 5, hoursTravel });}};private static LocalTime calculateTime(final LocalTime currentTime, final double[] times) {int minutes = (int) times[0];int remainingMinutes = (int) (times[1] * 60);return currentTime.plusMinutes(minutes).plusMinutes(remainingMinutes);}}- use std::collections::HashMap;
- fn time_parse(time: &str) -> f64 {
- let (h, m) = time.split_once(':').unwrap();
- h.parse::<f64>().unwrap() * 60. + m.parse::<f64>().unwrap()
- }
- fn from_min_to_string(min: f64) -> String {
- let h = (min / 60.).floor() % 24.;
- let m = (min % 60.).floor();
- format!("{:02}:{:02}", h, m)
- }
- const BUS_SCHEDULES: &str = r#"Skyport Crystalium 15 min 2 hours
- Crystalium Skyport 10 min 2 hours
- Skyport Oasis 20 min 3 hours
- Oasis Skyport 15 min 3 hours
- Oasis Crystalium 15 min 1.5 hours
- Crystalium Oasis 10 min 1.5 hours
- Skyport Nexus 15 min 4 hours
- Nexus Skyport 10 min 4 hours
- "#;
- fn arrival_time(route: Vec<&str>, departure_time: &str) -> String {
- let origin: Vec<&str> = vec!("Skyport");
- if route.is_empty() {
- return "The Train Driver has the day off".to_string();
- } else {
- let from = 0;
- let to = 1;
- let standby_time = 2;
- let travel_time = 4;
- let mut bus: HashMap<(String, String), (String, String)> = HashMap::new();
- for line in BUS_SCHEDULES.lines() {
- let data = line.split_whitespace().collect::<Vec<_>>();
- let bus_stop = (data[from].to_string(), data[to].to_string());
- let data_stop = (
- data[standby_time].to_string(),
- data[travel_time].to_string(),
- );
- bus.insert(bus_stop, data_stop);
- }
- let mut total_travel_time = 0.0;
- let full_route: Vec<&&str> = origin.iter().chain(route.iter()).collect::<Vec<_>>();
- for item in full_route.windows(2) {
- if item[0] == item[1] {
- total_travel_time += 1. * 60.;
- } else {
- let bus_stop = (item[0].to_string(), item[1].to_string());
- match bus.get(&bus_stop) {
- Some((waiting_time, travel_time)) => {
- total_travel_time += travel_time.parse::<f64>().unwrap() * 60.
- + waiting_time.parse::<f64>().unwrap();
- }
- None => {
- let back_to_origin = (item[0].to_string(), origin[0].to_string());
- let from_origin_to_route = (origin[0].to_string(), item[1].to_string());
- match bus.get(&back_to_origin) {
- Some((waiting_time, travel_time)) => {
- total_travel_time += travel_time.parse::<f64>().unwrap() * 60.
- + waiting_time.parse::<f64>().unwrap();
- }
- None => {
- panic!("Could not find route between {} and Skyport", item[0]);
- }
- }
- match bus.get(&from_origin_to_route) {
- Some((waiting_time, travel_time)) => {
- total_travel_time += travel_time.parse::<f64>().unwrap() * 60.
- + waiting_time.parse::<f64>().unwrap();
- }
- None => {
- panic!("Could not find route between Skyport and {}", item[1]);
- }
- }
- }
- }
- }
- }
- from_min_to_string(total_travel_time + time_parse(departure_time))
- }
- }
#[cfg(test)] mod test { use super::*; fn dotest(route: Vec<&str>, departure_time: &str, expected: &str) { let actual = arrival_time(route.clone(), departure_time); println!( "route: {:?}, departure_time: {:?}, expected: {:?}, actual: {:?}", route, departure_time, expected, actual ); assert!( actual == expected, "route: {:?}, departure_time: {:?}, expected: {:?}, actual: {:?}", route, departure_time, expected, actual ); } #[test] fn single_destination_test() { dotest(vec!["Crystalium"], "10:00", "12:15"); dotest(vec!["Skyport"], "22:00", "23:00"); } #[test] fn multiple_destination_test() { dotest(vec!["Nexus", "Nexus"], "20:15", "01:30"); dotest(vec!["Crystalium", "Skyport", "Oasis"], "10:00", "17:45"); dotest(vec!["Nexus", "Skyport", "Oasis"], "21:30", "09:15"); } #[test] fn empty_route_test() { dotest(vec![], "10:00", "The Train Driver has the day off"); } #[test] fn overtime_test() { dotest(vec!["Crystalium", "Nexus"], "23:50", "08:30"); } }
import org.junit.jupiter.api.RepeatedTest;import org.junit.jupiter.api.Test;import static org.junit.jupiter.api.Assertions.assertEquals;import java.time.LocalTime;import java.time.format.DateTimeFormatter;import java.util.Arrays;import java.util.HashMap;import java.util.Map;import java.util.Random;class SolutionTest {/*-----------------------------SAMPLE TEST CASES----------------------------*/@Testvoid testSingleDestination() {String[] route = { "Crystalium" };String departureTime = "10:00";String expected = "12:15";String result = Kata.arrivalTime(route, departureTime);String msg = "Input: " + Arrays.toString(route) + ", " + departureTime;assertEquals(expected, result, msg);}@Testvoid testMultipleDestinations() {String[] route = { "Crystalium", "Skyport", "Oasis" };String departureTime = "10:00";String expected = "17:45";String result = Kata.arrivalTime(route, departureTime);String msg = "Input: " + Arrays.toString(route) + ", " + departureTime;assertEquals(expected, result, msg);}@Testvoid testDepartingFromMidnight() {String[] route = { "Nexus", "Skyport", "Oasis" };String departureTime = "21:30";String expected = "09:15";String result = Kata.arrivalTime(route, departureTime);String msg = "Input: " + Arrays.toString(route) + ", " + departureTime;assertEquals(expected, result, msg);}@Testvoid testNoDestinations() {String[] route = {};String departureTime = "12:00";String expected = "The Train Driver has the day off";String result = Kata.arrivalTime(route, departureTime);String msg = "Input: " + Arrays.toString(route) + ", " + departureTime;assertEquals(expected, result, msg);}/*-------------------------------TEST CASES---------------------------------*/@Testvoid testStaySkyport() {String[] route = { "Skyport" };String departureTime = "21:30";String expected = "22:30";String result = Kata.arrivalTime(route, departureTime);String msg = "Input: " + Arrays.toString(route) + ", " + departureTime;assertEquals(expected, result, msg);}@Testvoid testOasisNexus() {String[] route = { "Oasis", "Nexus" };String departureTime = "06:30";String expected = "17:20";String result = Kata.arrivalTime(route, departureTime);String msg = "Input: " + Arrays.toString(route) + ", " + departureTime;assertEquals(expected, result, msg);}@Testvoid testCrystaliumNexus() {String[] route = { "Crystalium", "Nexus" };String departureTime = "23:50";String expected = "08:30";String result = Kata.arrivalTime(route, departureTime);String msg = "Input: " + Arrays.toString(route) + ", " + departureTime;assertEquals(expected, result, msg);}@Testvoid testDuplicateCities() {String[] route = { "Crystalium", "Crystalium", "Oasis", "Oasis" };String departureTime = "00:30";String expected = "06:25";String result = Kata.arrivalTime(route, departureTime);String msg = "Input: " + Arrays.toString(route) + ", " + departureTime;assertEquals(expected, result, msg);}@Testvoid testDuplicateNexus() {String[] route = { "Nexus", "Nexus" };String departureTime = "20:15";String expected = "01:30";String result = Kata.arrivalTime(route, departureTime);String msg = "Input: " + Arrays.toString(route) + ", " + departureTime;assertEquals(expected, result, msg);}@RepeatedTest(50)void testRandom() {Random random = new Random();String[] possiblesRoutes = { "Skyport", "Crystalium", "Oasis", "Nexus" };int size = random.nextInt(30, 51);String[] randomRoute = new String[size];for (int i = 0; i < size; i++) {randomRoute[i] = possiblesRoutes[random.nextInt(possiblesRoutes.length)];}int hour = random.nextInt(0, 24);int minute = random.nextInt(0, 60);String randomDepartureTime = String.format("%02d:%02d", hour, minute);String result = Kata.arrivalTime(randomRoute, randomDepartureTime);String msg = "Random input: " + Arrays.toString(randomRoute) + ", " + randomDepartureTime;assertEquals(arrivalTime(randomRoute, randomDepartureTime), result, msg);}private static String arrivalTime(final String[] route, final String departureTime) {if (route.length == 0) return "The Train Driver has the day off";LocalTime timeResult = LocalTime.parse(departureTime, DateTimeFormatter.ofPattern("HH:mm"));String origin = "Skyport";int index = 0;while (index < route.length) {String destination = route[index];Map<String, double[]> destinationMap = tableTime.get(origin);if (destinationMap != null && destinationMap.containsKey(destination)) {double[] times = destinationMap.get(destination);timeResult = calculateTime(timeResult, times);origin = destination;index++;} else if (origin.equals(destination)) {timeResult = timeResult.plusHours(1);index++;} else {String transfer = "Skyport";double[] times = tableTime.get(origin).get(transfer);timeResult = calculateTime(timeResult, times);origin = transfer;}}return timeResult.format(DateTimeFormatter.ofPattern("HH:mm"));}private static Map<String, Map<String, double[]>> tableTime = new HashMap<String, Map<String, double[]>>() {{addRecord("Skyport", "Crystalium", 15, 2);addRecord("Skyport", "Oasis", 20, 3);addRecord("Oasis", "Crystalium", 15, 1.5);addRecord("Skyport", "Nexus", 15, 4);}private void addRecord(final String origin, final String destiny, final double minutesWait,final double hoursTravel) {putIfAbsent(origin, new HashMap<>());get(origin).put(destiny, new double[] { minutesWait, hoursTravel });putIfAbsent(destiny, new HashMap<>());get(destiny).put(origin, new double[] { minutesWait - 5, hoursTravel });}};private static LocalTime calculateTime(final LocalTime currentTime, final double[] times) {int minutes = (int) times[0];int remainingMinutes = (int) (times[1] * 60);return currentTime.plusMinutes(minutes).plusMinutes(remainingMinutes);}- #[cfg(test)]
- mod test {
- use super::*;
- fn dotest(route: Vec<&str>, departure_time: &str, expected: &str) {
- let actual = arrival_time(route.clone(), departure_time);
- println!(
- "route: {:?}, departure_time: {:?}, expected: {:?}, actual: {:?}",
- route, departure_time, expected, actual
- );
- assert!(
- actual == expected,
- "route: {:?}, departure_time: {:?}, expected: {:?}, actual: {:?}",
- route,
- departure_time,
- expected,
- actual
- );
- }
- #[test]
- fn single_destination_test() {
- dotest(vec!["Crystalium"], "10:00", "12:15");
- dotest(vec!["Skyport"], "22:00", "23:00");
- }
- #[test]
- fn multiple_destination_test() {
- dotest(vec!["Nexus", "Nexus"], "20:15", "01:30");
- dotest(vec!["Crystalium", "Skyport", "Oasis"], "10:00", "17:45");
- dotest(vec!["Nexus", "Skyport", "Oasis"], "21:30", "09:15");
- }
- #[test]
- fn empty_route_test() {
- dotest(vec![], "10:00", "The Train Driver has the day off");
- }
- #[test]
- fn overtime_test() {
- dotest(vec!["Crystalium", "Nexus"], "23:50", "08:30");
- }
- }
fn print(n: u64) -> u64 { let mut digits = n .to_string() .chars() .map(|c| c.to_digit(10).unwrap() as u64) .collect::<Vec<u64>>(); digits.sort(); digits .into_iter() .rev() .fold(0, |acc, digit| acc * 10 + digit) }
fn print(mut n: u64) -> u64 {let mut digits = Vec::new();while n > 0 {digits.push(n % 10);n /= 10;}- fn print(n: u64) -> u64 {
- let mut digits = n
- .to_string()
- .chars()
- .map(|c| c.to_digit(10).unwrap() as u64)
- .collect::<Vec<u64>>();
- digits.sort();
digits.into_iter().rev().fold(0, |acc, digit| acc * 10 + digit)}- digits
- .into_iter()
- .rev()
- .fold(0, |acc, digit| acc * 10 + digit)
- }
#[cfg(test)] mod tests { use super::*; use rand::Rng; fn dotest(n: u64, exp: u64) -> () { assert_eq!(print(n), exp, "{}", format!("{} should return {} ", n, exp)); } #[test] fn simple_test() { dotest(4, 4); dotest(12, 21); dotest(101, 110); dotest(400000005000007000, 754000000000000000); dotest(307778062924466824, 988777666444322200); } #[test] fn random_test() { let mut rng = rand::thread_rng(); for _ in 0..10 { let n = rng.gen_range(1..100000); let exp = print(n); dotest(n, exp); } } }
#[test]fn test() {assert_eq!(print(4), 4);assert_eq!(print(12), 21);assert_eq!(print(101), 110);assert_eq!(print(400000005000007000), 754000000000000000);assert_eq!(print(307778062924466824), 988777666444322200);- #[cfg(test)]
- mod tests {
- use super::*;
- use rand::Rng;
- fn dotest(n: u64, exp: u64) -> () {
- assert_eq!(print(n), exp, "{}", format!("{} should return {} ", n, exp));
- }
- #[test]
- fn simple_test() {
- dotest(4, 4);
- dotest(12, 21);
- dotest(101, 110);
- dotest(400000005000007000, 754000000000000000);
- dotest(307778062924466824, 988777666444322200);
- }
- #[test]
- fn random_test() {
- let mut rng = rand::thread_rng();
- for _ in 0..10 {
- let n = rng.gen_range(1..100000);
- let exp = print(n);
- dotest(n, exp);
- }
- }
- }
fn sum(arr: &[i32]) -> i32 { match arr.is_empty() { true => 0, false => arr[..].iter().sum::<i32>(), } }
def sum(arr):result = 0for i in arr:result += ireturn result- fn sum(arr: &[i32]) -> i32 {
- match arr.is_empty() {
- true => 0,
- false => arr[..].iter().sum::<i32>(),
- }
- }
#[cfg(test)] mod test { use super::*; #[test] fn test_sum() { assert_eq!(sum(&[1, 2, 3]), 6); } #[test] fn test_empty_sum() { assert_eq!(sum(&[]), 0); } }
import codewars_test as test# TODO Write testsfrom solution import sum- #[cfg(test)]
- mod test {
- use super::*;
- #[test]
- fn test_sum() {
- assert_eq!(sum(&[1, 2, 3]), 6);
- }
- #[test]
- fn test_empty_sum() {
- assert_eq!(sum(&[]), 0);
- }
# test.assert_equals(actual, expected, [optional] message)@test.describe("Example tests")def test_group():@test.it("Basic tests")def test_case():test.assert_equals(sum([1]), 1)test.assert_equals(sum([1,2,3]), 6)- }
#[cfg(test)] mod tests { use super::*; #[test] fn test_even_numbers_in_array() { let v = &[-567, 2, 100, -34, 1000, 99, 101, -1000, 200, 7, -100]; let r = v.iter().fold(0, |count, &num| count + (num & 1 == 0) as usize); assert_eq!(calculate_even_numbers(v), r); } #[test] fn test_empty_array() { assert_eq!(calculate_even_numbers(&[]), 0); } #[test] fn test_no_even_numbers() { let v = &[5, 7, 9, 1, 21, 33, 77, 57, 33, 91, 111, 23451]; assert_eq!(calculate_even_numbers(v), 0); } #[test] fn test_multiple_even_numbers() { let v = &[60, 180, 99, 100, 101, 103]; assert_eq!(calculate_even_numbers(v), 3); } #[test] fn test_large_numbers() { let v = &[10_000_000, 90_000, 700_000_000, 2, 70, 44]; assert_eq!(calculate_even_numbers(v), 6); } }
#[test]fn test() {assert_eq!(calculate_even_numbers(&[]), 0);assert_eq!(calculate_even_numbers(&[5, 7, 2, 4, 9]), 2);assert_eq!(calculate_even_numbers(&[60, 180, 99, 100, 101, 103]), 3);assert_eq!(calculate_even_numbers(&[99, 9, 1, 21, 33, 77, 57, 33, 91, 111, 23451]), 0);assert_eq!(calculate_even_numbers(&[10_000_000, 90_000, 700_000_000, 2, 70, 44]), 6);- #[cfg(test)]
- mod tests {
- use super::*;
- #[test]
- fn test_even_numbers_in_array() {
- let v = &[-567, 2, 100, -34, 1000, 99, 101, -1000, 200, 7, -100];
- let r = v.iter().fold(0, |count, &num| count + (num & 1 == 0) as usize);
- assert_eq!(calculate_even_numbers(v), r);
- }
- #[test]
- fn test_empty_array() {
- assert_eq!(calculate_even_numbers(&[]), 0);
- }
- #[test]
- fn test_no_even_numbers() {
- let v = &[5, 7, 9, 1, 21, 33, 77, 57, 33, 91, 111, 23451];
- assert_eq!(calculate_even_numbers(v), 0);
- }
- #[test]
- fn test_multiple_even_numbers() {
- let v = &[60, 180, 99, 100, 101, 103];
- assert_eq!(calculate_even_numbers(v), 3);
- }
- #[test]
- fn test_large_numbers() {
- let v = &[10_000_000, 90_000, 700_000_000, 2, 70, 44];
- assert_eq!(calculate_even_numbers(v), 6);
- }
- }
fn hello_world(world: bool) -> String { if world { return "Hello, World".to_string(); } return "Goodbye, World".to_string(); }
def hello_world(world):if world == True:return "Hello, World"return "Goodbye, World"- fn hello_world(world: bool) -> String {
- if world {
- return "Hello, World".to_string();
- }
- return "Goodbye, World".to_string();
- }
#[cfg(test)] mod tests { use super::*; #[test] fn test_add() { assert_eq!(hello_world(true), "Hello, World"); assert_eq!(hello_world(false), "Goodbye, World"); } }
import codewars_test as test# TODO Write testsimport solution # or from solution import example- #[cfg(test)]
- mod tests {
- use super::*;
# test.assert_equals(actual, expected, [optional] message)@test.describe("Example")def test_group():@test.it("test case")def test_case():test.assert_equals(1 + 1, 2)- #[test]
- fn test_add() {
- assert_eq!(hello_world(true), "Hello, World");
- assert_eq!(hello_world(false), "Goodbye, World");
- }
- }