fn mean(x: &[f64]) -> f64 { let x_len_float = x.len() as f64; return x.iter().sum::<f64>() / x_len_float; }
fn mean(x: &[u64]) -> u64 {x.iter().sum::<u64>() / x.len() as u64- fn mean(x: &[f64]) -> f64 {
- let x_len_float = x.len() as f64;
- return x.iter().sum::<f64>() / x_len_float;
- }
#[test] fn test_positive_integers() { assert_eq!(mean(&[4_f64, 8_f64, 4_f64, 8_f64]), 6_f64); } #[test] fn test_floats() { let actual = mean(&[0.48, 3.28, -5.77, 3.49]); let expected = 0.3700000; const EPSILON: f64 = 1e-7; let diff = (actual-expected).abs(); assert!(diff < EPSILON, "Difference between the computed mean: {} and expected: {} is greater than {}", actual, expected, EPSILON); }
- #[test]
fn test() {assert_eq!(mean(&[4, 8, 4, 8]), 6);- fn test_positive_integers() {
- assert_eq!(mean(&[4_f64, 8_f64, 4_f64, 8_f64]), 6_f64);
- }
- #[test]
- fn test_floats() {
- let actual = mean(&[0.48, 3.28, -5.77, 3.49]);
- let expected = 0.3700000;
- const EPSILON: f64 = 1e-7;
- let diff = (actual-expected).abs();
- assert!(diff < EPSILON, "Difference between the computed mean: {} and expected: {} is greater than {}", actual, expected, EPSILON);
- }
Skipped the string-building part and did a sum instead.
For an array of chars [48+5, 48+6, 48+7]
you have an array of numeric values [5, 6, 7]
which leads to 5 * 10^0 + 6 * 10^1 + 7 * 10^2 = 765
(which is the maximum and the equivalent of reversing the string)
Added a test for execution time performance (if that is a concern)
and a test for random values
import java.util.Arrays; public class MaxNumber { public static long print(long number) { long sum = 0; String numStr = String.valueOf(number); char[] digits = numStr.toCharArray(); Arrays.sort(digits); // here the digits are sorted in ascending order for (int i = 0; i < digits.length; i++) { sum += Math.round( Character.getNumericValue(digits[i]) * Math.pow(10, i) ); } return sum; } }
- import java.util.Arrays;
- public class MaxNumber {
- public static long print(long number) {
- long sum = 0;
- String numStr = String.valueOf(number);
- char[] digits = numStr.toCharArray();
- Arrays.sort(digits);
StringBuilder sortedStr = new StringBuilder(new String(digits));return Long.parseLong(sortedStr.reverse().toString());- // here the digits are sorted in ascending order
- for (int i = 0; i < digits.length; i++) {
- sum += Math.round( Character.getNumericValue(digits[i]) * Math.pow(10, i) );
- }
- return sum;
- }
- }
import org.junit.Test; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.ThreadLocalRandom; import java.util.logging.Logger; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; public class MaxNumberTest { private static final Logger logger = Logger.getLogger(MaxNumberTest.class.getName()); // Adjust as needed public static final double MAX_EXECUTION_TIME_MS = 5; public static final int MAX_WAIT_TIME_LOOP_IN_SEC = 10; public static String concatenateCharacters(List<Character> charList) { StringBuilder sb = new StringBuilder(); for (Character ch : charList) { sb.append(ch); } return sb.toString(); } @Test public void testFour() { assertEquals(4, MaxNumber.print(4)); } @Test public void testTwelve() { assertEquals(21, MaxNumber.print(12)); } @Test public void testOneHundred() { assertEquals(110, MaxNumber.print(101)); } @Test public void testHuge1() { assertEquals(754000000000000000L, MaxNumber.print(400000005000007000L)); } @Test public void testHuge2() { assertEquals(988777666444322200L, MaxNumber.print(307778062924466824L)); } @Test public void testFunctionTimePerformance() { ThreadLocalRandom random = ThreadLocalRandom.current(); long beforeWarmup = System.currentTimeMillis(); // warmup of CPU cache for (int i = 0; i < 200; i++) { MaxNumber.print(random.nextLong(0, Long.MAX_VALUE / 10)); } long afterWarmup = System.currentTimeMillis(); double warmupTimeSec = (afterWarmup - beforeWarmup) / 1_000D; assertTrue(warmupTimeSec < MAX_WAIT_TIME_LOOP_IN_SEC, "Rough execution time is too high: " + String.format("%.1f", warmupTimeSec * 5) + "ms"); // factor of 5 is due to 1000 (ms/s) / 200 iterations long startTime = System.nanoTime(); int iterations = 10_000; // ------ for (int i = 0; i < iterations; i++) { MaxNumber.print(random.nextLong(0, Long.MAX_VALUE / 10)); } // ------ long endTime = System.nanoTime(); // Calculate the execution time in milliseconds long totalExecutionTimeMs = (endTime - startTime) / 1_000_000; double avgExecTimeMs = totalExecutionTimeMs / (double) iterations; logger.info("Average execution time was: " + String.format("%.3f", avgExecTimeMs) + "ms"); assertTrue(avgExecTimeMs <= MAX_EXECUTION_TIME_MS, "Execution time exceeded the " + MAX_EXECUTION_TIME_MS + "ms limit"); } @Test public void testRandomValues() { char[] almostAllDigits = new char[]{'0','0','1','2','2','3','3','3','4','5','6','7','7','8','8','9','9'}; for (int i = 0; i < 100; i++) { List<Character> allDigitList = new ArrayList<>(); for (char digit : almostAllDigits) { allDigitList.add(digit); } Collections.shuffle(allDigitList); allDigitList.add(0, '1'); // to prevent starting with 0 String shuffledDigits = concatenateCharacters(allDigitList); long randomNumber = Long.parseLong(shuffledDigits); long actualMaxNumber = MaxNumber.print(randomNumber); long expectedMaxNumber = 998877654333221100L; // allMostAllDigits joined with {'1'}, in descending order assertEquals(expectedMaxNumber, actualMaxNumber, "Expected: " + expectedMaxNumber + " from " + randomNumber +", but got: " + actualMaxNumber); } } }
import static org.junit.Assert.assertEquals;- import org.junit.Test;
import java.util.Random;- import java.util.ArrayList;
- import java.util.Collections;
- import java.util.List;
- import java.util.concurrent.ThreadLocalRandom;
- import java.util.logging.Logger;
- import static org.junit.jupiter.api.Assertions.assertEquals;
- import static org.junit.jupiter.api.Assertions.assertTrue;
- public class MaxNumberTest {
- private static final Logger logger = Logger.getLogger(MaxNumberTest.class.getName());
- // Adjust as needed
- public static final double MAX_EXECUTION_TIME_MS = 5;
- public static final int MAX_WAIT_TIME_LOOP_IN_SEC = 10;
- public static String concatenateCharacters(List<Character> charList) {
- StringBuilder sb = new StringBuilder();
- for (Character ch : charList) {
- sb.append(ch);
- }
- return sb.toString();
- }
- @Test
- public void testFour() {
- assertEquals(4, MaxNumber.print(4));
- }
- @Test
- public void testTwelve() {
- assertEquals(21, MaxNumber.print(12));
- }
- @Test
- public void testOneHundred() {
- assertEquals(110, MaxNumber.print(101));
- }
- @Test
- public void testHuge1() {
- assertEquals(754000000000000000L, MaxNumber.print(400000005000007000L));
- }
- @Test
- public void testHuge2() {
- assertEquals(988777666444322200L, MaxNumber.print(307778062924466824L));
- }
- @Test
- public void testFunctionTimePerformance() {
- ThreadLocalRandom random = ThreadLocalRandom.current();
- long beforeWarmup = System.currentTimeMillis();
- // warmup of CPU cache
- for (int i = 0; i < 200; i++) {
- MaxNumber.print(random.nextLong(0, Long.MAX_VALUE / 10));
- }
- long afterWarmup = System.currentTimeMillis();
- double warmupTimeSec = (afterWarmup - beforeWarmup) / 1_000D;
- assertTrue(warmupTimeSec < MAX_WAIT_TIME_LOOP_IN_SEC, "Rough execution time is too high: "
- + String.format("%.1f", warmupTimeSec * 5) + "ms"); // factor of 5 is due to 1000 (ms/s) / 200 iterations
- long startTime = System.nanoTime();
- int iterations = 10_000;
- // ------
- for (int i = 0; i < iterations; i++) {
- MaxNumber.print(random.nextLong(0, Long.MAX_VALUE / 10));
- }
- // ------
- long endTime = System.nanoTime();
- // Calculate the execution time in milliseconds
- long totalExecutionTimeMs = (endTime - startTime) / 1_000_000;
- double avgExecTimeMs = totalExecutionTimeMs / (double) iterations;
- logger.info("Average execution time was: " + String.format("%.3f", avgExecTimeMs) + "ms");
- assertTrue(avgExecTimeMs <= MAX_EXECUTION_TIME_MS,
- "Execution time exceeded the " + MAX_EXECUTION_TIME_MS + "ms limit");
- }
- @Test
- public void testRandomValues() {
- char[] almostAllDigits = new char[]{'0','0','1','2','2','3','3','3','4','5','6','7','7','8','8','9','9'};
- for (int i = 0; i < 100; i++) {
- List<Character> allDigitList = new ArrayList<>();
- for (char digit : almostAllDigits) {
- allDigitList.add(digit);
- }
- Collections.shuffle(allDigitList);
- allDigitList.add(0, '1'); // to prevent starting with 0
- String shuffledDigits = concatenateCharacters(allDigitList);
- long randomNumber = Long.parseLong(shuffledDigits);
- long actualMaxNumber = MaxNumber.print(randomNumber);
- long expectedMaxNumber = 998877654333221100L; // allMostAllDigits joined with {'1'}, in descending order
- assertEquals(expectedMaxNumber, actualMaxNumber, "Expected: " + expectedMaxNumber + " from " + randomNumber +", but got: " + actualMaxNumber);
- }
- }
- }