diff --git a/concepts/numbers/.meta/config.json b/concepts/numbers/.meta/config.json new file mode 100644 index 00000000..a6712f1a --- /dev/null +++ b/concepts/numbers/.meta/config.json @@ -0,0 +1,7 @@ +{ + "authors": [ + "colinleach" + ], + "contributors": [], + "blurb": "Kotlin has a variety of integer and floating point types, and a math library to manipulate them." +} diff --git a/concepts/numbers/about.md b/concepts/numbers/about.md new file mode 100644 index 00000000..937e9b1c --- /dev/null +++ b/concepts/numbers/about.md @@ -0,0 +1,154 @@ +# About Numbers + +## Numerical types + +[Numbers][numbers] can be integer, unsigned integer, or floating point types. +Each comes in various "sizes", meaning how many bits it needs in memory. + +Unlike some scripting languages (Ruby, recent versions of Python), each type in Kotlin has a maximum ([`MAX_VALUE`][max_value]) and minimum ([`MIN_VALUE`][min_value]) value it can store. +Assigning larger values will cause ["overflow"][wiki-overflow], causing either an exception (_bad_) or corrupted data (_worse_). + +- Integers can be `Byte`, `Short`, `Int` or `Long`, respectively 8, 16, 32 and 64 bits (1, 2 4, 8 bytes). +- Unsigned integers have a `U` prefix: `UByte`, `UShort`, `UInt` or `ULong`. +- Floating point types are `Float` (32-bit) or `Double` (64-bit). + +Integer variables relying on type inference default to `Int`, even on 64-bit machines, but floating point variables default to `Double`. + +Other types can, of course, be specified, but there are a few syntactic shortcuts, and big integer literals become `Long` if they would overflow `Int`. + +```Kotlin +val one = 1 // defaults to Int +val threeBillion = 3_000_000_000 // Long, with optional underscores for clarity +val oneLong = 1L // Long +val oneByte: Byte = 1 +val oneDouble = 1.0 // defaults to Double +val oneFloat = 1.0f // Float +val lightSpeed = 3.0e8 // scientific notation (units of m/s) +``` + +Hexadecimal and binary literals are conventional: `0x7F` and `0b100101` respectively. +Octal literals are not supported in Kotlin. + +## Arithmetic + +The basic arithmetic operators are the same as in many languages: + +```Kotlin +4 + 3 // => 7 +4 - 3 // => 1 +4 * 3 // => 12 +4 / 3 // => 1 Int / Int always gives an Int +-8 / 3 // => -2 Truncated towards zero +-8.0 / 3 // => -2.6666666666666665 +``` + +To get a floating point result from division, at least one of the numerator / denominator must be floating point. + +Division by zero is more interesting. + +```Kotlin +1 / 0 // => java.lang.ArithmeticException: / by zero +3.0 / 0.0 // => Infinity +0.0 / 0.0 // => NaN (Not a Number) +``` + +Integer division by zero is an error, but [IEEE floating point standards][wiki-IEEE] can apply in other cases. + +The modulo operator `%` gives the remainder from integer division: + +```Kotlin +8 % 3 // => 2 +``` + +Kotlin, like other JVM languages, has no exponentiation operator (_this annoys scientists and engineers_). +We need to use the [`pow()`][pow] function from the [`math`][math] library, and the number being raised to some power must be `Float` or `Double`. + +```kotlin +2.0.pow(3) // => 8.0 +2.pow(3) // Unresolved reference (2 is Int, so not allowed) +``` + +## Rounding + +The [`math`][math] library contains several functions to round floating point numbers to a nearby integer. + +_Did the last line sound slightly odd?_ +When we say "a nearby integer", there are two questions: + +- Is the return value still Float/Double, or is it converted to Int/Long? +- How are ties rounded? Does `4.5` round to `4` or `5`? + +It is not Kotlin's fault if this seems complicated. +Mathematicians have been arguing about this for centuries. + +### `round()`, `floor()`, `ceil()`, `truncate()` + +These four functions all return the same floating-point type as the input, but differ in how they round. + +- [`round()`][round] gives the _nearest_ integer if this is unambiguous, or the _nearest even_ integer when tied. +- [`floor()`][floor] rounds towards negative infinity. +- [`ceil()`][ceil] rounds towards positive infinity +- [`truncate()`][truncate] rounds towards zero + +```kotlin +round(4.7) // => 5.0 (nearest integer) +round(4.5) // => 4.0 (nearest even integer) + +floor(4.7) // => 4.0 (towards -Inf) +floor(-4.7) // => 5.0 + +ceil(4.7) // => 5.0 (towards +Inf) +ceil(-4.7) // => -4.0 + +truncate(4.7) // => 4.0 (towards zero) +truncate(-4.7) // => -4.0 +``` + +### `roundToInt()`, `roundToLong()` + +These two functions do a type conversion after rounding, so the return type is `Int` or `Long` respectively. + +Ties are always rounded towards positive infinity. + +```kotlin +4.3.roundToInt() // => 4 (nearest integer) +4.5.roundToInt() // => 5 (nearest integer towards +Inf) +(-4.5).roundToInt() // => -4 +``` + +Note also the different syntax: `x.roundToInt()` versus `round(x)`. + +## Type conversions + +Kotlin will quietly do implicit conversions in a few cases, for example `Int` to `Double` in a mixed arithmetic expression: + +```Kotlin +3 + 4.0 // => 7.0 +``` + +Internally, the `+` operator is overloaded to handle this. + +More generally, explicit conversions are required: + +```Kotlin +val x = 7.3 +x.toInt() // => 7 + +val n = 42 +n.toDouble() // => 42.0 +``` + +See the [manual][conversions] for the full list of `toX()` methods. + +[numbers]: https://kotlinlang.org/docs/numbers.html +[wiki-IEEE]: https://en.wikipedia.org/wiki/IEEE_754 +[conversions]: https://kotlinlang.org/docs/numbers.html#explicit-number-conversions +[pow]: https://kotlinlang.org/api/core/kotlin-stdlib/kotlin.math/pow.html +[math]: https://kotlinlang.org/api/core/kotlin-stdlib/kotlin.math/ +[round]: https://kotlinlang.org/api/core/kotlin-stdlib/kotlin.math/round.html +[floor]: https://kotlinlang.org/api/core/kotlin-stdlib/kotlin.math/floor.html +[ceil]: https://kotlinlang.org/api/core/kotlin-stdlib/kotlin.math/ceil.html +[truncate]: https://kotlinlang.org/api/core/kotlin-stdlib/kotlin.math/truncate.html +[wiki-overflow]: https://en.wikipedia.org/wiki/Integer_overflow +[max_value]: https://kotlinlang.org/api/core/kotlin-stdlib/kotlin/-int/-companion/#-244053257%2FProperties%2F-956074838 +[min_value]: https://kotlinlang.org/api/core/kotlin-stdlib/kotlin/-int/-companion/#-1907397559%2FProperties%2F-956074838 diff --git a/concepts/numbers/introduction.md b/concepts/numbers/introduction.md new file mode 100644 index 00000000..09c4c108 --- /dev/null +++ b/concepts/numbers/introduction.md @@ -0,0 +1,140 @@ +# Introduction + +## Numerical types + +[Numbers][numbers] can be integer, unsigned integer, or floating point types. +Each comes in various "sizes", meaning how many bits it needs in memory. + +- Integers can be `Byte`, `Short`, `Int` or `Long`, respectively 8, 16, 32 and 64 bits. +- Unsigned integers have a `U` prefix: `UByte`, `UShort`, `UInt` or `ULong`. +- Floating point types are `Float` (32-bit) or `Double` (64-bit). + +Integer variables relying on type inference default to `Int`, even on 64-bit machines, but floating point variables default to `Double`. + +Other types can, of course, be specified, but there are a few syntactic shortcuts, and big integer literals become `Long` if they would overflow `Int`. + +```Kotlin +val one = 1 // defaults to Int +val threeBillion = 3_000_000_000 // Long, with optional underscores for clarity +val oneLong = 1L // Long +val oneByte: Byte = 1 +val oneDouble = 1.0 // defaults to Double +val oneFloat = 1.0f //Float +val lightSpeed = 3.0e8 // scientific notation (units of m/s) +``` + +Hexadecimal and binary literals are conventional: `0x7F` and `0b100101` respectively. +Octal literals are not supported in Kotlin. + +## Arithmetic + +The basic arithmetic operators are the same as in many languages: + +```Kotlin +4 + 3 // => 7 +4 - 3 // => 1 +4 * 3 // => 12 +4 / 3 // => 1 Int / Int always gives an Int +-8 / 3 // => -2 Truncated towards zero +-8.0 / 3 // => -2.6666666666666665 +``` + +To get a floating point result from division, at least one of the numerator / denominator must be floating point. + +Division by zero is more interesting. + +```Kotlin +1 / 0 // => java.lang.ArithmeticException: / by zero +3.0 / 0.0 // => Infinity +0.0 / 0.0 // => NaN (Not a Number) +``` + +Integer division by zero is an error, but IEEE floating point standards can apply in other cases. + +The modulo operator `%` gives the remainder from integer division: + +```Kotlin +8 % 3 // => 2 +``` + +Kotlin, like other JVM languages, has no exponentiation operator. +We need to use the `pow()` function from the [`math`][math] library, and the number being raised to some power must be `Float` or `Double`. + +```kotlin +2.0.pow(3) // => 8.0 +2.pow(3) // Unresolved reference (2 is Int, so not allowed) +``` + +## Rounding + +The [`math`][math] library contains several functions to round floating point numbers to a nearby integer. + +_Did the last line sound slightly odd?_ +When we say "a nearby integer", there are two questions: + +- Is the return value still Float/Double, or is it converted to Int/Long? +- How are ties rounded? Does `4.5` round to `4` or `5`? + +It is not Kotlin's fault if this seems complicated. +Mathematicians have been arguing about this for centuries. + +### `round()`, `floor()`, `ceil()`, `truncate()` + +These four functions all return the same floating-point type as the input, but differ in how they round. + +- `round()` gives the _nearest_ integer if this is unambiguous, or the _nearest even_ integer when tied. +- `floor()` rounds towards negative infinity. +- `ceil()` rounds towards positive infinity +- `truncate()` rounds towards zero + +```kotlin +round(4.7) // => 5.0 (nearest integer) +round(4.5) // => 4.0 (nearest even integer) + +floor(4.7) // => 4.0 (towards -Inf) +floor(-4.7) // => 5.0 + +ceil(4.7) // => 5.0 (towards +Inf) +ceil(-4.7) // => -4.0 + +truncate(4.7) // => 4.0 (towards zero) +truncate(-4.7) // => -4.0 +``` + +### `roundToInt()`, `roundToLong()` + +These two functions do a type conversion after rounding, so the return type is `Int` or `Long` respectively. + +Ties are always rounded towards positive infinity. + +```kotlin +4.3.roundToInt() // => 4 (nearest integer) +4.5.roundToInt() // => 5 (nearest integer towards +Inf) +(-4.5).roundToInt() // => -4 +``` + +Note also the different syntax: `x.roundToInt()` versus `round(x)`. + +## Type conversions + +Kotlin will quietly do implicit conversions in a few cases, for example `Int` to `Double` in a mixed arithmetic expression: + +```Kotlin +3 + 4.0 // => 7.0 +``` + +More generally, explicit conversions are required: + +```Kotlin +val x = 7.3 +x.toInt() // => 7 + +val n = 42 +n.toDouble() // => 42.0 +``` + +See the [manual][conversions] for the full list of `toX()` methods. + +[numbers]: https://kotlinlang.org/docs/numbers.html +[conversions]: https://kotlinlang.org/docs/numbers.html#explicit-number-conversions +[math]: https://kotlinlang.org/api/core/kotlin-stdlib/kotlin.math/ diff --git a/concepts/numbers/links.json b/concepts/numbers/links.json new file mode 100644 index 00000000..3a725bc6 --- /dev/null +++ b/concepts/numbers/links.json @@ -0,0 +1,14 @@ +[ + { + "url": "https://kotlinlang.org/docs/numbers.html", + "description": "Kotlin introduction to numbers" + }, + { + "url": "https://kotlinlang.org/docs/numbers.html#explicit-number-conversions", + "description": "Numeric type conversions" + }, + { + "url": "https://kotlinlang.org/api/core/kotlin-stdlib/kotlin.math/", + "description": "Kotlin math library" + } +] diff --git a/config.json b/config.json index ba7a0c1d..0902b37a 100644 --- a/config.json +++ b/config.json @@ -55,6 +55,18 @@ "basics" ], "status": "wip" + }, + { + "slug": "cars-assemble", + "name": "cars-assemble", + "uuid": "9a67e10e-c331-4474-af3a-9cea17aa3f87", + "concepts": [ + "numbers" + ], + "prerequisites": [ + "basics" + ], + "status": "wip" } ], "practice": [ @@ -1196,6 +1208,7 @@ "practices": [], "prerequisites": [], "difficulty": 6, + "status": "deprecated", "topics": [ "conditionals", "games", @@ -1203,8 +1216,7 @@ "lists", "matrices", "strings" - ], - "status": "deprecated" + ] }, { "slug": "rail-fence-cipher", @@ -1387,6 +1399,11 @@ "uuid": "168827c0-4867-449a-ad22-611c87314c48", "slug": "conditionals", "name": "Conditionals" + }, + { + "uuid": "0501f1e3-8443-4386-9107-4c28cb10469f", + "slug": "numbers", + "name": "Numbers" } ], "key_features": [ diff --git a/exercises/concept/cars-assemble/.docs/hints.md b/exercises/concept/cars-assemble/.docs/hints.md new file mode 100644 index 00000000..172b0154 --- /dev/null +++ b/exercises/concept/cars-assemble/.docs/hints.md @@ -0,0 +1,25 @@ +# Hints + +## General + +- To learn more about type conversions in Kotlin, check [Explicit number conversions][type conversions]. + +## 1. Calculate the number of working cars produced per hour + +- The percentage (passed as an argument) is a number between 0-100. To make this percentage a bit easier to work with, start by dividing it by 100. +- To compute the number of cars produced successfully, multiply the percentage (divided by 100) by the number of cars produced. + +## 2. Calculate the number of working cars produced per minute + +- Start by calculating the production of successful cars per hour. For this, you can use the function you implemented from the previous step. +- Knowing the production per hour of cars, you can get the production per minute by dividing the production per hour by 60 (the number of minutes in an hour). +- Remember to cast the result to an `Int` + +## 3. Calculate the cost of production + +- Start by working out how many groups of 10 cars there are. You can do this by dividing the number of cars by 10. +- Then work out how many cars are remaining (the [modulo operator][modulo operator] is useful for this). +- To arrive at the cost, multiply the number of groups by the cost to produce 10 cars and then multiply the number of cars remaining by the cost to produce each individual car. Then sum the results of the multiplication together. + +[type conversions]: https://kotlinlang.org/docs/numbers.html#explicit-number-conversions +[modulo operator]: https://www.baeldung.com/kotlin/integer-division-modulus \ No newline at end of file diff --git a/exercises/concept/cars-assemble/.docs/instructions.md b/exercises/concept/cars-assemble/.docs/instructions.md new file mode 100644 index 00000000..58a5c97b --- /dev/null +++ b/exercises/concept/cars-assemble/.docs/instructions.md @@ -0,0 +1,53 @@ +# Instructions + +In this exercise you'll be writing code to analyze the production in a car factory. + +## 1. Calculate the number of working cars produced per hour + +The cars are produced on an assembly line. +The assembly line has a certain speed, that can be changed. +The faster the assembly line speed is, the more cars are produced. +However, changing the speed of the assembly line also changes the number of cars that are produced successfully, that is cars without any errors in their production. + +Implement a function that takes in the number of cars produced per hour and the success rate and calculates the number of successful cars made per hour. The success rate is given as a percentage, from `0` to `100`: + +```kotlin +CarsAssemble.calculateWorkingCarsPerHour(1547, 90) +// => 1392.3 +``` + +**Note:** the return value should be a `Double`. + +## 2. Calculate the number of working cars produced per minute + +Implement a function that takes in the number of cars produced per hour and the success rate and calculates how many cars are successfully produced each minute: + +```kotlin +CarsAssemble.calculateWorkingCarsPerMinute(1105, 90) +// => 16 +``` + +**Note:** the return value should be an `Int`. + +## 3. Calculate the cost of production + +Each car normally costs $10,000 to produce individually, regardless of whether it is successful or not. +But with a bit of planning, 10 cars can be produced together for $95,000. + +For example, 37 cars can be produced in the following way: +37 = 3 x groups of ten + 7 individual cars + +So the cost for 37 cars is: +3\*95,000+7\*10,000=355,000 + +Implement the function `CalculateCost` that calculates the cost of producing a number of cars, regardless of whether they are successful: + +```kotlin +CarsAssemble.calculateProductionCost(37) +// => 355000 + +CarsAssemble.calculateProductionCost(21) +// => 200000 +``` + +**Note:** the return value should be an `ULong`. \ No newline at end of file diff --git a/exercises/concept/cars-assemble/.docs/introduction.md b/exercises/concept/cars-assemble/.docs/introduction.md new file mode 100644 index 00000000..e69de29b diff --git a/exercises/concept/cars-assemble/.meta/config.json b/exercises/concept/cars-assemble/.meta/config.json new file mode 100644 index 00000000..1f65a49f --- /dev/null +++ b/exercises/concept/cars-assemble/.meta/config.json @@ -0,0 +1,17 @@ +{ + "authors": [ + "kahgoh" + ], + "files": { + "solution": [ + "src/main/kotlin/CarsAssemble.kt" + ], + "test": [ + "src/test/kotlin/CarsAssembleTest.kt" + ], + "exemplar": [ + ".meta/src/reference/kotlin/CarsAssemble.kt" + ] + }, + "blurb": "Learn about numbers and type conversion by analyzing an assembly line in a car factory." +} diff --git a/exercises/concept/cars-assemble/.meta/src/reference/kotlin/CarsAssemble.kt b/exercises/concept/cars-assemble/.meta/src/reference/kotlin/CarsAssemble.kt new file mode 100644 index 00000000..199c0501 --- /dev/null +++ b/exercises/concept/cars-assemble/.meta/src/reference/kotlin/CarsAssemble.kt @@ -0,0 +1,16 @@ +object CarsAssemble { + + fun calculateWorkingCarsPerHour(productionRate : Int, successRate : Double) : Double { + return productionRate * successRate / 100 + } + + fun calculateWorkingCarsPerMinute(productionRate : Int, successRate : Double) : Int { + val result = calculateWorkingCarsPerHour(productionRate, successRate) / 60 + return result.toInt() + } + + fun calculateProductionCost(carsCount : Int) : ULong { + val result = (carsCount / 10) * 95_000 + (carsCount % 10) * 10_000 + return result.toULong() + } +} diff --git a/exercises/concept/cars-assemble/build.gradle.kts b/exercises/concept/cars-assemble/build.gradle.kts new file mode 100644 index 00000000..3db5dc4f --- /dev/null +++ b/exercises/concept/cars-assemble/build.gradle.kts @@ -0,0 +1,23 @@ +import org.gradle.api.tasks.testing.logging.TestExceptionFormat + +plugins { + kotlin("jvm") +} + +repositories { + mavenCentral() +} + +dependencies { + implementation(kotlin("stdlib-jdk8")) + + testImplementation("junit:junit:4.13.2") + testImplementation(kotlin("test-junit")) +} + +tasks.withType { + testLogging { + exceptionFormat = TestExceptionFormat.FULL + events("passed", "failed", "skipped") + } +} diff --git a/exercises/concept/cars-assemble/gradle/wrapper/gradle-wrapper.jar b/exercises/concept/cars-assemble/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000..7f93135c Binary files /dev/null and b/exercises/concept/cars-assemble/gradle/wrapper/gradle-wrapper.jar differ diff --git a/exercises/concept/cars-assemble/gradle/wrapper/gradle-wrapper.properties b/exercises/concept/cars-assemble/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000..3fa8f862 --- /dev/null +++ b/exercises/concept/cars-assemble/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.4-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/exercises/concept/cars-assemble/gradlew b/exercises/concept/cars-assemble/gradlew new file mode 100755 index 00000000..1aa94a42 --- /dev/null +++ b/exercises/concept/cars-assemble/gradlew @@ -0,0 +1,249 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/exercises/concept/cars-assemble/gradlew.bat b/exercises/concept/cars-assemble/gradlew.bat new file mode 100755 index 00000000..93e3f59f --- /dev/null +++ b/exercises/concept/cars-assemble/gradlew.bat @@ -0,0 +1,92 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/exercises/concept/cars-assemble/settings.gradle.kts b/exercises/concept/cars-assemble/settings.gradle.kts new file mode 100644 index 00000000..054e2f7e --- /dev/null +++ b/exercises/concept/cars-assemble/settings.gradle.kts @@ -0,0 +1,13 @@ +pluginManagement { + repositories { + mavenCentral() + gradlePluginPortal() + } + resolutionStrategy { + eachPlugin { + when (requested.id.id) { + "org.jetbrains.kotlin.jvm" -> useModule("org.jetbrains.kotlin:kotlin-gradle-plugin:1.6.0") + } + } + } +} diff --git a/exercises/concept/cars-assemble/src/main/kotlin/CarsAssemble.kt b/exercises/concept/cars-assemble/src/main/kotlin/CarsAssemble.kt new file mode 100644 index 00000000..b2197a7a --- /dev/null +++ b/exercises/concept/cars-assemble/src/main/kotlin/CarsAssemble.kt @@ -0,0 +1,14 @@ +object CarsAssemble { + + fun calculateWorkingCarsPerHour(productionRate : Int, successRate : Double) : Double { + TODO("Please implement the calculateWorkingCarsPerHour method") + } + + fun calculateWorkingCarsPerMinute(productionRate : Int, successRate : Double) : Int { + TODO("Please implement the calculateWorkingCarsPerMinute method") + } + + fun calculateProductionCost(carsCount : Int) : ULong { + TODO("Please implement the calculateProductionCost method") + } +} diff --git a/exercises/concept/cars-assemble/src/test/kotlin/CarsAssembleTest.kt b/exercises/concept/cars-assemble/src/test/kotlin/CarsAssembleTest.kt new file mode 100644 index 00000000..4ec6d481 --- /dev/null +++ b/exercises/concept/cars-assemble/src/test/kotlin/CarsAssembleTest.kt @@ -0,0 +1,107 @@ +import kotlin.test.Test +import kotlin.test.assertEquals + +class CarsAssembleTest { + + val tolerance = 1e-9 + + @Test + fun `calculate working cars per hour with 0 production rate`() { + assertEquals(0.0, CarsAssemble.calculateWorkingCarsPerHour(0, 100.0), tolerance) + } + + @Test + fun `calculate working cars per hour with 100 percent success rate`() { + assertEquals(221.0, CarsAssemble.calculateWorkingCarsPerHour(221, 100.0), tolerance) + } + + @Test + fun `calculate working cars per hour with 80 percent success rate`() { + assertEquals(340.8, CarsAssemble.calculateWorkingCarsPerHour(426, 80.0), tolerance) + } + + @Test + fun `calculate working cars per hour with 20 point 5 percent success rate`() { + assertEquals(1398.92, CarsAssemble.calculateWorkingCarsPerHour(6824, 20.5), tolerance) + } + + @Test + fun `calculate working cars per hour with 0 percent success rate`() { + assertEquals(0.0, CarsAssemble.calculateWorkingCarsPerHour(8000, 0.0), tolerance) + } + + @Test + fun `calculate working cars per minute with 0 production rate`() { + assertEquals(0, CarsAssemble.calculateWorkingCarsPerMinute(0, 100.0)) + } + + @Test + fun `calculate working cars per minute with 100 percent success rate`() { + assertEquals(3, CarsAssemble.calculateWorkingCarsPerMinute(221, 100.0)) + } + + @Test + fun `calculate working cars per minute with 80 percent success rate`() { + assertEquals(5, CarsAssemble.calculateWorkingCarsPerMinute(426, 80.0)) + } + + @Test + fun `calculate working cars per minute with 20 point 5 percent success rate`() { + assertEquals(23, CarsAssemble.calculateWorkingCarsPerMinute(6824, 20.5)) + } + + @Test + fun `calculate working cars per minute with 0 percent success rate`() { + assertEquals(0, CarsAssemble.calculateWorkingCarsPerMinute(8000, 0.0)) + } + + @Test + fun `calculate production cost for 0 cars`() { + assertEquals(0uL, CarsAssemble.calculateProductionCost(0)) + } + + @Test + fun `calculate production cost for 1 car`() { + assertEquals(10_000uL, CarsAssemble.calculateProductionCost(1)) + } + + @Test + fun `calculate production cost for 2 cars`() { + assertEquals(20_000uL, CarsAssemble.calculateProductionCost(2)) + } + + @Test + fun `calculate production cost for 9 cars`() { + assertEquals(90_000uL, CarsAssemble.calculateProductionCost(9)) + } + + @Test + fun `calculate production cost for 10 cars`() { + assertEquals(95_000uL, CarsAssemble.calculateProductionCost(10)) + } + + @Test + fun `calculate production cost for 100 cars`() { + assertEquals(95_0000uL, CarsAssemble.calculateProductionCost(100)) + } + + @Test + fun `calculate production cost for 21 cars`() { + assertEquals(200_000uL, CarsAssemble.calculateProductionCost(21)) + } + + @Test + fun `calculate production cost for 37 cars`() { + assertEquals(355_000uL, CarsAssemble.calculateProductionCost(37)) + } + + @Test + fun `calculate production cost for 56 cars`() { + assertEquals(535_000uL, CarsAssemble.calculateProductionCost(56)) + } + + @Test + fun `calculate production cost for 148 cars`() { + assertEquals(1_410_000uL, CarsAssemble.calculateProductionCost(148)) + } +}