diff --git a/concepts/arithmetic/about.md b/concepts/arithmetic/about.md index a6b9918f..9ab815a1 100644 --- a/concepts/arithmetic/about.md +++ b/concepts/arithmetic/about.md @@ -83,7 +83,7 @@ There are a few other places that are arithmetic contexts: * The offset and length parts of the `${var:offset:length}` expansion. * The [`let` builtin command][let]. - * Note that `(( expression ))` is preferred over `let "expresson"`. + * Note that `(( expression ))` is preferred over `let "expression"`. Unlike the [arithmetic conditional][arithmetic-conditional] construct, the `let` expression is subject to filename-expansion and word-splitting, and it requires quoting. * Variable assignment, when the variable has the "integer attribute". @@ -100,7 +100,7 @@ There are a few other places that are arithmetic contexts: ~~~~exercism/note It is the author's opinion that `declare -i` has limited usage. - It's main benefit is to allow "bare" arithmetic (without the arithmetic expression syntax). + Its main benefit is to allow "bare" arithmetic (without the arithmetic expression syntax). This can cause confusion for readers of your code, where arithmetic expressions are evaluated in unexpected places. ~~~~ diff --git a/concepts/arithmetic/introduction.md b/concepts/arithmetic/introduction.md index 29161906..719519dc 100644 --- a/concepts/arithmetic/introduction.md +++ b/concepts/arithmetic/introduction.md @@ -83,7 +83,7 @@ There are a few other places that are arithmetic contexts: * The offset and length parts of the `${var:offset:length}` expansion. * The [`let` builtin command][let]. - * Note that `(( expression ))` is preferred over `let "expresson"`. + * Note that `(( expression ))` is preferred over `let "expression"`. Unlike the [arithmetic conditional][arithmetic-conditional] construct, the `let` expression is subject to filename-expansion and word-splitting, and it requires quoting. * Variable assignment, when the variable has the "integer attribute". @@ -100,7 +100,7 @@ There are a few other places that are arithmetic contexts: ~~~~exercism/note It is the author's opinion that `declare -i` has limited usage. - It's main benefit is to allow "bare" arithmetic (without the arithmetic expression syntax). + Its main benefit is to allow "bare" arithmetic (without the arithmetic expression syntax). This can cause confusion for readers of your code, where arithmetic expressions are evaluated in unexpected places. ~~~~ diff --git a/config.json b/config.json index 4ae3ef12..a2f49699 100644 --- a/config.json +++ b/config.json @@ -103,6 +103,18 @@ "looping" ], "status": "wip" + }, + { + "slug": "cars-assemble", + "name": "Cars Assemble", + "uuid": "54e48825-f563-4870-a456-d32a63720157", + "concepts": [ + "arithmetic" + ], + "prerequisites": [ + "conditionals" + ], + "status": "wip" } ], "practice": [ diff --git a/exercises/concept/cars-assemble/.docs/hints.md b/exercises/concept/cars-assemble/.docs/hints.md new file mode 100644 index 00000000..d1133800 --- /dev/null +++ b/exercises/concept/cars-assemble/.docs/hints.md @@ -0,0 +1,43 @@ +# Hints + +## General + +- Read about [shell arithmetic][arithmetic] in the bash manual, or the track's arithmetic concept page. +- Use [arithmetic expansion][expansion], `$(( ... ))`, to get the value of a calculation. +- Inside an arithmetic context, variables you have named do not need a `$`, but positional parameters such as `$1` do. +- Division discards the fractional part of the result. + +## 1. Find the success rate + +- Use an `if` command with `elif` branches. +- Compare numbers inside the [arithmetic command][conditional], `(( ... ))`. +- If you check the speeds in order, each condition needs only one comparison. + +## 2. Calculate the production per hour + +- Multiply the speed by the number of cars produced for one step of speed. + +## 3. Calculate the working cars per hour + +- A percentage of a number is the number times the percentage, divided by 100. +- The order of the operations matters: dividing a number smaller than 100 by 100 gives zero. + +## 4. Calculate the working cars per minute + +- Start with the calculation from the previous task. +- Convert from cars per hour to cars per minute. + +## 5. Load the cars for shipping + +- Division tells you how many times one number fits completely into another, which is the number of full trains. +- The remainder operator tells you what is left over after that division. + Look for both operators in the table of operators in the introduction. + +## 6. Expand the factory + +- Doubling again and again is a power of 2. +- Bash has an exponentiation operator: look for it in the table of operators in the introduction. + +[arithmetic]: https://www.gnu.org/software/bash/manual/bash.html#Shell-Arithmetic +[expansion]: https://www.gnu.org/software/bash/manual/bash.html#Arithmetic-Expansion +[conditional]: https://www.gnu.org/software/bash/manual/bash.html#Conditional-Constructs diff --git a/exercises/concept/cars-assemble/.docs/instructions.md b/exercises/concept/cars-assemble/.docs/instructions.md new file mode 100644 index 00000000..ed80fedf --- /dev/null +++ b/exercises/concept/cars-assemble/.docs/instructions.md @@ -0,0 +1,97 @@ +# Instructions + +You work at a car factory, and you want a script to help you analyze the production of its assembly line. + +The speed of the line can be set from `0` (off) to `10` (maximum). +For each step of speed, the line produces 221 cars per hour, so at speed `4` it produces `4 * 221 = 884` cars per hour. + +A faster line also spoils more cars. +The _success rate_ is the percentage of cars that have no faults: + +| Speed | Success rate | +| ------ | ------------ | +| 0 to 4 | 100% | +| 5 to 8 | 90% | +| 9 | 80% | +| 10 | 77% | + +You have six tasks, and they all belong to the same script. +The first argument names the task to perform, and the remaining arguments are the data for that task. +The script you are given already runs the right part of the code for each task, so you only need to fill in each part. + +All the numbers are whole numbers. +When a result has a fractional part, round it down. +Do not print anything other than the requested output. + +## 1. Find the success rate + +The argument is the speed of the line. +Print the success rate as a percentage, without the `%` sign. + +```text +$ bash cars_assemble.sh success-rate 7 +90 +``` + +## 2. Calculate the production per hour + +The argument is the speed of the line. +Print the number of cars produced in one hour, including the faulty ones. + +```text +$ bash cars_assemble.sh production 4 +884 +``` + +## 3. Calculate the working cars per hour + +The first argument is the speed of the line, and the second is the success rate as a percentage. +Use the rate you are given; you don't need to work it out from the speed. +Print the number of cars without faults produced in one hour. + +At speed 5 the line produces 1105 cars per hour. +With a success rate of 90, that is 994.5 working cars, which rounds down to 994. + +```text +$ bash cars_assemble.sh working 5 90 +994 +``` + +## 4. Calculate the working cars per minute + +The arguments are the same as in the previous task. +Print the number of cars without faults produced in one minute. + +```text +$ bash cars_assemble.sh per-minute 5 90 +16 +``` + +## 5. Load the cars for shipping + +The finished cars are shipped by train. +The first argument is the number of cars, and the second is the number of cars that fit on one train. + +Print the number of full trains, and the number of cars left over, separated by a space. + +```text +$ bash cars_assemble.sh shipping 994 150 +6 94 +``` + +## 6. Expand the factory + +The factory is growing. +Each expansion doubles the number of assembly lines: there is 1 line before any expansion, 2 lines after one expansion, 4 lines after two, and so on. +All the lines run at the same speed. + +The first argument is the speed of the lines, and the second is the number of expansions. +Print the number of cars produced in one hour by the whole factory, including the faulty ones. + +At speed 4 each line produces 884 cars per hour. +After 3 expansions there are 8 assembly lines, so the factory produces 7072 cars. + +```text +$ bash cars_assemble.sh expanded 4 3 +7072 +``` diff --git a/exercises/concept/cars-assemble/.docs/introduction.md b/exercises/concept/cars-assemble/.docs/introduction.md new file mode 100644 index 00000000..74029ca1 --- /dev/null +++ b/exercises/concept/cars-assemble/.docs/introduction.md @@ -0,0 +1,157 @@ +# Introduction + +## Arithmetic + +Bash can do arithmetic but _only with integers_. +If you need to do floating-point math, you'll need to call out to some external program (like [awk][awk] or [bc][bc]). + +The arithmetic operators are listed (in order of precedence) in the manual: [Shell Arithmetic][arithmetic]. + +These are the common ones, from highest to lowest precedence: + +| Operators | Meaning | +| --- | --- | +| `**` | exponentiation | +| `*` `/` `%` | multiplication, division, remainder | +| `+` `-` | addition, subtraction | +| `<=` `>=` `<` `>` | comparison | +| `==` `!=` | equality, inequality | +| `&&` | logical AND | +| `\|\|` | logical OR | +| `=` `+=` `-=` `*=` `/=` `%=` | assignment | + +Additionally, bash only performs arithmetic in certain places (known as arithmetic "contexts"). + +### Arithmetic Expansion + +As we saw in the [Variables][variables] lesson, math can be performed in an arithmetic expansion. + +```bash +x=$(( 3 + 4 )) +``` + +### Arithmetic Command + +The `(( expression ))` syntax is also used as a conditional, as described in the [Arithmetic Conditional][arithmetic-conditional] section of the Conditionals concept. + +It can also be used as a standalone command to modify a variable's value. + +```bash +(( x = x + 1 )) +echo "new value for x is $x" +``` + +~~~~exercism/caution +Be careful using arithmetic this way combined with `set -e`. +If the expression evaluates to zero, the exit status will be non-zero and bash will terminate. + +```bash +x=0 +(( x++ )) +echo "you will see this" + +set -e +x=0 +(( x++ )) +echo "shell exits on the previous line; you won't see this" +``` + +For a more thorough discussion about the `++` operator, see this article on [Postincrement vs Preincrement][incr] + +[incr]: https://thisvsthat.io/postincrement-vs-preincrement +~~~~ + + +### Other Places With Arithmetic Context + +There are a few other places that are arithmetic contexts: + +* The [arithmetic for-loop][looping-for]. + + ```bash + for (( i = 0; i < 10; i++ )); do + echo "$i" + done + ``` + +* The index part of a numerically-indexed array. + + ```bash + echo "The next element is ${array[x + 1]}" + # ................................^^^^^ + ``` + + For more about arrays, read the [Arrays][arrays] concept document. + +* The offset and length parts of the `${var:offset:length}` expansion. +* The [`let` builtin command][let]. + * Note that `(( expression ))` is preferred over `let "expression"`. + Unlike the [arithmetic conditional][arithmetic-conditional] construct, the `let` expression is subject to filename-expansion and word-splitting, and it requires quoting. +* Variable assignment, when the variable has the "integer attribute". + + ```bash + # variable x does not have the integer attribute + x="3 + 4" + declare -p x # => declare -- x="3 + 4" + + # variable y has the integer attribute + declare -i y + y="4 + 5" + declare -p y # => declare -i y="9" + ``` + + ~~~~exercism/note + It is the author's opinion that `declare -i` has limited usage. + Its main benefit is to allow "bare" arithmetic (without the arithmetic expression syntax). + This can cause confusion for readers of your code, where arithmetic expressions are evaluated in unexpected places. + ~~~~ + +### Using Variables in an Arithmetic Expressions + +Here is one aspect of arithmetic contexts that improves readability. + +```bash +height=10 +width=20 +area=$(( height * width )) +``` + +Did you notice that the `$` dollar signs are missing from the variables in the arithmetic expression? +Bash lets you do that. +It makes expressions much easier to read. + +The manual says, + +> Within an expression, shell variables may also be referenced by name without using the parameter expansion syntax. + +It even works for array elements: + +```bash +point1=(10 15) # these are (x, y) coordinates +point2=(20 7) +distance_squared=$(( (point1[0] - point2[0])**2 + (point1[1] - point2[1])**2 )) +``` + +But other parameter expressions need to use their special syntax. +For example, doubling the length of a string: + +```bash +s="hello world" +len=$(( ${#s} * 2 )) +``` + +Positional parameters also need the `$`. +If the first two positional parameters represent width and height: + +```bash +area=$(( $1 * $2 )) +``` + +[arithmetic]: https://www.gnu.org/software/bash/manual/bash.html#Shell-Arithmetic +[arithmetic-conditional]: https://exercism.org/tracks/bash/concepts/conditionals#h-arithmetic-conditional +[looping-for]: https://exercism.org/tracks/bash/concepts/looping#h-arithmetic-for-loop +[arrays]: https://exercism.org/tracks/bash/concepts/arrays +[let]: https://www.gnu.org/software/bash/manual/bash.html#index-let +[awk]: https://www.gnu.org/software/gawk/manual/html_node/index.html +[bc]: https://www.gnu.org/software/bc/manual/html_mono/bc.html +[variables]: https://exercism.org/tracks/bash/concepts/variables#h-arithmetic-expansion diff --git a/exercises/concept/cars-assemble/.docs/introduction.md.tpl b/exercises/concept/cars-assemble/.docs/introduction.md.tpl new file mode 100644 index 00000000..b5e569d6 --- /dev/null +++ b/exercises/concept/cars-assemble/.docs/introduction.md.tpl @@ -0,0 +1,3 @@ +# Introduction + +%{concept:arithmetic} diff --git a/exercises/concept/cars-assemble/.meta/config.json b/exercises/concept/cars-assemble/.meta/config.json new file mode 100644 index 00000000..45080845 --- /dev/null +++ b/exercises/concept/cars-assemble/.meta/config.json @@ -0,0 +1,23 @@ +{ + "authors": [ + "glennj" + ], + "files": { + "solution": [ + "cars_assemble.sh" + ], + "test": [ + "cars_assemble.bats" + ], + "exemplar": [ + ".meta/exemplar.sh" + ], + "invalidator": [ + "bats-extra.bash" + ] + }, + "forked_from": [ + "csharp/cars-assemble" + ], + "blurb": "Learn about arithmetic while analyzing the production of a car assembly line." +} diff --git a/exercises/concept/cars-assemble/.meta/design.md b/exercises/concept/cars-assemble/.meta/design.md new file mode 100644 index 00000000..f2e871b7 --- /dev/null +++ b/exercises/concept/cars-assemble/.meta/design.md @@ -0,0 +1,33 @@ +# Design + +## Goal + +The goal of this exercise is to introduce arithmetic in bash scripts. + +## Learning objectives + +- Use arithmetic expansion, `$(( ... ))`, to calculate a value. +- Compare numbers with the arithmetic command, `(( ... ))`. +- Know that bash arithmetic uses only integers, and that division discards the fractional part. +- Order the operations of a calculation to avoid losing precision. +- Use the remainder operator, `%`. +- Use the exponentiation operator, `**`. + +## Out of scope + +- Floating-point arithmetic, and external programs such as `bc` and `awk`. +- Assignment operators such as `+=`, and the increment and decrement operators. +- The `let` builtin and the integer attribute. +- Functions. +- The `case` and `shift` commands: the stub provides them to select the task. +- Validating the input. + +## Concepts + +The Concepts this exercise unlocks are: + +- `arithmetic` + +## Prerequisites + +- `conditionals` diff --git a/exercises/concept/cars-assemble/.meta/exemplar.sh b/exercises/concept/cars-assemble/.meta/exemplar.sh new file mode 100644 index 00000000..d726f238 --- /dev/null +++ b/exercises/concept/cars-assemble/.meta/exemplar.sh @@ -0,0 +1,50 @@ +#!/usr/bin/env bash + +readonly CARS_PER_SPEED_STEP=221 + +task=$1 +shift + +case $task in + success-rate) + speed=$1 + if (( speed <= 4 )); then + echo 100 + elif (( speed <= 8 )); then + echo 90 + elif (( speed == 9 )); then + echo 80 + else + echo 77 + fi + ;; + + production) + speed=$1 + echo $(( speed * CARS_PER_SPEED_STEP )) + ;; + + working) + speed=$1 + rate=$2 + echo $(( speed * CARS_PER_SPEED_STEP * rate / 100 )) + ;; + + per-minute) + speed=$1 + rate=$2 + echo $(( speed * CARS_PER_SPEED_STEP * rate / 100 / 60 )) + ;; + + shipping) + cars=$1 + capacity=$2 + echo "$(( cars / capacity )) $(( cars % capacity ))" + ;; + + expanded) + speed=$1 + expansions=$2 + echo $(( speed * CARS_PER_SPEED_STEP * 2 ** expansions )) + ;; +esac diff --git a/exercises/concept/cars-assemble/bats-extra.bash b/exercises/concept/cars-assemble/bats-extra.bash new file mode 100644 index 00000000..7cef63ea --- /dev/null +++ b/exercises/concept/cars-assemble/bats-extra.bash @@ -0,0 +1,642 @@ +# This is the source code for bats-support and bats-assert, concatenated +# * https://github.com/bats-core/bats-support +# * https://github.com/bats-core/bats-assert +# +# Comments have been removed to save space. See the git repos for full source code. + +############################################################ +# +# bats-support - Supporting library for Bats test helpers +# +# Written in 2016 by Zoltan Tombol +# +# To the extent possible under law, the author(s) have dedicated all +# copyright and related and neighboring rights to this software to the +# public domain worldwide. This software is distributed without any +# warranty. +# +# You should have received a copy of the CC0 Public Domain Dedication +# along with this software. If not, see +# . +# + +# shellcheck disable=SC2120 # (warning): fail references arguments, but none are ever passed. +fail() { + # shellcheck disable=2015 # (info): Note that A && B || C is not if-then-else. C may run when A is true. + (( $# == 0 )) && batslib_err || batslib_err "$@" + return 1 +} + +batslib_is_caller() { + local -i is_mode_direct=1 + + # Handle options. + while (( $# > 0 )); do + case "$1" in + -i|--indirect) is_mode_direct=0; shift ;; + --) shift; break ;; + *) break ;; + esac + done + + # Arguments. + local -r func="$1" + + # Check call stack. + if (( is_mode_direct )); then + [[ $func == "${FUNCNAME[2]}" ]] && return 0 + else + local -i depth + for (( depth=2; depth<${#FUNCNAME[@]}; ++depth )); do + [[ $func == "${FUNCNAME[$depth]}" ]] && return 0 + done + fi + + return 1 +} + +batslib_err() { + { if (( $# > 0 )); then + echo "$@" + else + cat - + fi + } >&2 +} + +batslib_count_lines() { + local -i n_lines=0 + local line + while IFS='' read -r line || [[ -n $line ]]; do + (( ++n_lines )) + done < <(printf '%s' "$1") + echo "$n_lines" +} + +batslib_is_single_line() { + for string in "$@"; do + (( $(batslib_count_lines "$string") > 1 )) && return 1 + done + return 0 +} + +batslib_get_max_single_line_key_width() { + local -i max_len=-1 + while (( $# != 0 )); do + local -i key_len="${#1}" + batslib_is_single_line "$2" && (( key_len > max_len )) && max_len="$key_len" + shift 2 + done + echo "$max_len" +} + +batslib_print_kv_single() { + local -ir col_width="$1"; shift + while (( $# != 0 )); do + printf '%-*s : %s\n' "$col_width" "$1" "$2" + shift 2 + done +} + +batslib_print_kv_multi() { + while (( $# != 0 )); do + printf '%s (%d lines):\n' "$1" "$( batslib_count_lines "$2" )" + printf '%s\n' "$2" + shift 2 + done +} + +batslib_print_kv_single_or_multi() { + local -ir width="$1"; shift + local -a pairs=( "$@" ) + + local -a values=() + local -i i + for (( i=1; i < ${#pairs[@]}; i+=2 )); do + values+=( "${pairs[$i]}" ) + done + + if batslib_is_single_line "${values[@]}"; then + batslib_print_kv_single "$width" "${pairs[@]}" + else + local -i i + for (( i=1; i < ${#pairs[@]}; i+=2 )); do + pairs[i]="$( batslib_prefix < <(printf '%s' "${pairs[$i]}") )" + done + batslib_print_kv_multi "${pairs[@]}" + fi +} + +batslib_prefix() { + local -r prefix="${1:- }" + local line + while IFS='' read -r line || [[ -n $line ]]; do + printf '%s%s\n' "$prefix" "$line" + done +} + +batslib_mark() { + local -r symbol="$1"; shift + # Sort line numbers. + # shellcheck disable=SC2046 # (warning): Quote this to prevent word splitting. + set -- $( sort -nu <<< "$( printf '%d\n' "$@" )" ) + + local line + local -i idx=0 + while IFS='' read -r line || [[ -n $line ]]; do + if (( ${1:--1} == idx )); then + printf '%s\n' "${symbol}${line:${#symbol}}" + shift + else + printf '%s\n' "$line" + fi + (( ++idx )) + done +} + +batslib_decorate() { + echo + echo "-- $1 --" + cat - + echo '--' + echo +} + +############################################################ + +assert() { + if ! "$@"; then + batslib_print_kv_single 10 'expression' "$*" \ + | batslib_decorate 'assertion failed' \ + | fail + fi +} + +assert_equal() { + if [[ $1 != "$2" ]]; then + batslib_print_kv_single_or_multi 8 \ + 'expected' "$2" \ + 'actual' "$1" \ + | batslib_decorate 'values do not equal' \ + | fail + fi +} + +assert_failure() { + : "${output?}" + : "${status?}" + + (( $# > 0 )) && local -r expected="$1" + if (( status == 0 )); then + batslib_print_kv_single_or_multi 6 'output' "$output" \ + | batslib_decorate 'command succeeded, but it was expected to fail' \ + | fail + elif (( $# > 0 )) && (( status != expected )); then + { local -ir width=8 + batslib_print_kv_single "$width" \ + 'expected' "$expected" \ + 'actual' "$status" + batslib_print_kv_single_or_multi "$width" \ + 'output' "$output" + } \ + | batslib_decorate 'command failed as expected, but status differs' \ + | fail + fi +} + +assert_line() { + local -i is_match_line=0 + local -i is_mode_partial=0 + local -i is_mode_regexp=0 + : "${lines?}" + + # Handle options. + while (( $# > 0 )); do + case "$1" in + -n|--index) + if (( $# < 2 )) || ! [[ $2 =~ ^([0-9]|[1-9][0-9]+)$ ]]; then + echo "\`--index' requires an integer argument: \`$2'" \ + | batslib_decorate 'ERROR: assert_line' \ + | fail + return $? + fi + is_match_line=1 + local -ri idx="$2" + shift 2 + ;; + -p|--partial) is_mode_partial=1; shift ;; + -e|--regexp) is_mode_regexp=1; shift ;; + --) shift; break ;; + *) break ;; + esac + done + + if (( is_mode_partial )) && (( is_mode_regexp )); then + echo "\`--partial' and \`--regexp' are mutually exclusive" \ + | batslib_decorate 'ERROR: assert_line' \ + | fail + return $? + fi + + # Arguments. + local -r expected="$1" + + if (( is_mode_regexp == 1 )) && [[ '' =~ $expected ]] || (( $? == 2 )); then + echo "Invalid extended regular expression: \`$expected'" \ + | batslib_decorate 'ERROR: assert_line' \ + | fail + return $? + fi + + # Matching. + if (( is_match_line )); then + # Specific line. + if (( is_mode_regexp )); then + if ! [[ ${lines[$idx]} =~ $expected ]]; then + batslib_print_kv_single 6 \ + 'index' "$idx" \ + 'regexp' "$expected" \ + 'line' "${lines[$idx]}" \ + | batslib_decorate 'regular expression does not match line' \ + | fail + fi + elif (( is_mode_partial )); then + if [[ ${lines[$idx]} != *"$expected"* ]]; then + batslib_print_kv_single 9 \ + 'index' "$idx" \ + 'substring' "$expected" \ + 'line' "${lines[$idx]}" \ + | batslib_decorate 'line does not contain substring' \ + | fail + fi + else + if [[ ${lines[$idx]} != "$expected" ]]; then + batslib_print_kv_single 8 \ + 'index' "$idx" \ + 'expected' "$expected" \ + 'actual' "${lines[$idx]}" \ + | batslib_decorate 'line differs' \ + | fail + fi + fi + else + # Contained in output. + if (( is_mode_regexp )); then + local -i idx + for (( idx = 0; idx < ${#lines[@]}; ++idx )); do + [[ ${lines[$idx]} =~ $expected ]] && return 0 + done + { local -ar single=( 'regexp' "$expected" ) + local -ar may_be_multi=( 'output' "$output" ) + local -ir width="$( batslib_get_max_single_line_key_width "${single[@]}" "${may_be_multi[@]}" )" + batslib_print_kv_single "$width" "${single[@]}" + batslib_print_kv_single_or_multi "$width" "${may_be_multi[@]}" + } \ + | batslib_decorate 'no output line matches regular expression' \ + | fail + elif (( is_mode_partial )); then + local -i idx + for (( idx = 0; idx < ${#lines[@]}; ++idx )); do + [[ ${lines[$idx]} == *"$expected"* ]] && return 0 + done + { local -ar single=( 'substring' "$expected" ) + local -ar may_be_multi=( 'output' "$output" ) + local -ir width="$( batslib_get_max_single_line_key_width "${single[@]}" "${may_be_multi[@]}" )" + batslib_print_kv_single "$width" "${single[@]}" + batslib_print_kv_single_or_multi "$width" "${may_be_multi[@]}" + } \ + | batslib_decorate 'no output line contains substring' \ + | fail + else + local -i idx + for (( idx = 0; idx < ${#lines[@]}; ++idx )); do + [[ ${lines[$idx]} == "$expected" ]] && return 0 + done + { local -ar single=( 'line' "$expected" ) + local -ar may_be_multi=( 'output' "$output" ) + local -ir width="$( batslib_get_max_single_line_key_width "${single[@]}" "${may_be_multi[@]}" )" + batslib_print_kv_single "$width" "${single[@]}" + batslib_print_kv_single_or_multi "$width" "${may_be_multi[@]}" + } \ + | batslib_decorate 'output does not contain line' \ + | fail + fi + fi +} + +assert_output() { + local -i is_mode_partial=0 + local -i is_mode_regexp=0 + local -i is_mode_nonempty=0 + local -i use_stdin=0 + : "${output?}" + + # Handle options. + if (( $# == 0 )); then + is_mode_nonempty=1 + fi + + while (( $# > 0 )); do + case "$1" in + -p|--partial) is_mode_partial=1; shift ;; + -e|--regexp) is_mode_regexp=1; shift ;; + -|--stdin) use_stdin=1; shift ;; + --) shift; break ;; + *) break ;; + esac + done + + if (( is_mode_partial )) && (( is_mode_regexp )); then + echo "\`--partial' and \`--regexp' are mutually exclusive" \ + | batslib_decorate 'ERROR: assert_output' \ + | fail + return $? + fi + + # Arguments. + local expected + if (( use_stdin )); then + expected="$(cat -)" + else + expected="${1-}" + fi + + # Matching. + if (( is_mode_nonempty )); then + if [ -z "$output" ]; then + echo 'expected non-empty output, but output was empty' \ + | batslib_decorate 'no output' \ + | fail + fi + elif (( is_mode_regexp )); then + # shellcheck disable=SC2319 # (warning) `$?` in a conditional expression: https://github.com/koalaman/shellcheck/wiki/SC2319 + if [[ '' =~ $expected ]] || (( $? == 2 )); then + # the regex matches an empty string or it is syntactically incorrect. + echo "Invalid extended regular expression: \`$expected'" \ + | batslib_decorate 'ERROR: assert_output' \ + | fail + elif ! [[ $output =~ $expected ]]; then + batslib_print_kv_single_or_multi 6 \ + 'regexp' "$expected" \ + 'output' "$output" \ + | batslib_decorate 'regular expression does not match output' \ + | fail + fi + elif (( is_mode_partial )); then + if [[ $output != *"$expected"* ]]; then + batslib_print_kv_single_or_multi 9 \ + 'substring' "$expected" \ + 'output' "$output" \ + | batslib_decorate 'output does not contain substring' \ + | fail + fi + else + if [[ $output != "$expected" ]]; then + batslib_print_kv_single_or_multi 8 \ + 'expected' "$expected" \ + 'actual' "$output" \ + | batslib_decorate 'output differs' \ + | fail + fi + fi +} + +assert_success() { + : "${output?}" + : "${status?}" + + if (( status != 0 )); then + { local -ir width=6 + batslib_print_kv_single "$width" 'status' "$status" + batslib_print_kv_single_or_multi "$width" 'output' "$output" + } \ + | batslib_decorate 'command failed' \ + | fail + fi +} + +refute() { + if "$@"; then + batslib_print_kv_single 10 'expression' "$*" \ + | batslib_decorate 'assertion succeeded, but it was expected to fail' \ + | fail + fi +} + +refute_line() { + local -i is_match_line=0 + local -i is_mode_partial=0 + local -i is_mode_regexp=0 + : "${lines?}" + + # Handle options. + while (( $# > 0 )); do + case "$1" in + -n|--index) + if (( $# < 2 )) || ! [[ $2 =~ ^([0-9]|[1-9][0-9]+)$ ]]; then + echo "\`--index' requires an integer argument: \`$2'" \ + | batslib_decorate 'ERROR: refute_line' \ + | fail + return $? + fi + is_match_line=1 + local -ri idx="$2" + shift 2 + ;; + -p|--partial) is_mode_partial=1; shift ;; + -e|--regexp) is_mode_regexp=1; shift ;; + --) shift; break ;; + *) break ;; + esac + done + + if (( is_mode_partial )) && (( is_mode_regexp )); then + echo "\`--partial' and \`--regexp' are mutually exclusive" \ + | batslib_decorate 'ERROR: refute_line' \ + | fail + return $? + fi + + # Arguments. + local -r unexpected="$1" + + if (( is_mode_regexp == 1 )) && [[ '' =~ $unexpected ]] || (( $? == 2 )); then + echo "Invalid extended regular expression: \`$unexpected'" \ + | batslib_decorate 'ERROR: refute_line' \ + | fail + return $? + fi + + # Matching. + if (( is_match_line )); then + # Specific line. + if (( is_mode_regexp )); then + if [[ ${lines[$idx]} =~ $unexpected ]]; then + batslib_print_kv_single 6 \ + 'index' "$idx" \ + 'regexp' "$unexpected" \ + 'line' "${lines[$idx]}" \ + | batslib_decorate 'regular expression should not match line' \ + | fail + fi + elif (( is_mode_partial )); then + if [[ ${lines[$idx]} == *"$unexpected"* ]]; then + batslib_print_kv_single 9 \ + 'index' "$idx" \ + 'substring' "$unexpected" \ + 'line' "${lines[$idx]}" \ + | batslib_decorate 'line should not contain substring' \ + | fail + fi + else + if [[ ${lines[$idx]} == "$unexpected" ]]; then + batslib_print_kv_single 5 \ + 'index' "$idx" \ + 'line' "${lines[$idx]}" \ + | batslib_decorate 'line should differ' \ + | fail + fi + fi + else + # Line contained in output. + if (( is_mode_regexp )); then + local -i idx + for (( idx = 0; idx < ${#lines[@]}; ++idx )); do + if [[ ${lines[$idx]} =~ $unexpected ]]; then + { local -ar single=( 'regexp' "$unexpected" 'index' "$idx" ) + local -a may_be_multi=( 'output' "$output" ) + local -ir width="$( batslib_get_max_single_line_key_width "${single[@]}" "${may_be_multi[@]}" )" + batslib_print_kv_single "$width" "${single[@]}" + if batslib_is_single_line "${may_be_multi[1]}"; then + batslib_print_kv_single "$width" "${may_be_multi[@]}" + else + may_be_multi[1]="$( printf '%s' "${may_be_multi[1]}" | batslib_prefix | batslib_mark '>' "$idx" )" + batslib_print_kv_multi "${may_be_multi[@]}" + fi + } \ + | batslib_decorate 'no line should match the regular expression' \ + | fail + return $? + fi + done + elif (( is_mode_partial )); then + local -i idx + for (( idx = 0; idx < ${#lines[@]}; ++idx )); do + if [[ ${lines[$idx]} == *"$unexpected"* ]]; then + { local -ar single=( 'substring' "$unexpected" 'index' "$idx" ) + local -a may_be_multi=( 'output' "$output" ) + local -ir width="$( batslib_get_max_single_line_key_width "${single[@]}" "${may_be_multi[@]}" )" + batslib_print_kv_single "$width" "${single[@]}" + if batslib_is_single_line "${may_be_multi[1]}"; then + batslib_print_kv_single "$width" "${may_be_multi[@]}" + else + may_be_multi[1]="$( printf '%s' "${may_be_multi[1]}" | batslib_prefix | batslib_mark '>' "$idx" )" + batslib_print_kv_multi "${may_be_multi[@]}" + fi + } \ + | batslib_decorate 'no line should contain substring' \ + | fail + return $? + fi + done + else + local -i idx + for (( idx = 0; idx < ${#lines[@]}; ++idx )); do + if [[ ${lines[$idx]} == "$unexpected" ]]; then + { local -ar single=( 'line' "$unexpected" 'index' "$idx" ) + local -a may_be_multi=( 'output' "$output" ) + local -ir width="$( batslib_get_max_single_line_key_width "${single[@]}" "${may_be_multi[@]}" )" + batslib_print_kv_single "$width" "${single[@]}" + if batslib_is_single_line "${may_be_multi[1]}"; then + batslib_print_kv_single "$width" "${may_be_multi[@]}" + else + may_be_multi[1]="$( printf '%s' "${may_be_multi[1]}" | batslib_prefix | batslib_mark '>' "$idx" )" + batslib_print_kv_multi "${may_be_multi[@]}" + fi + } \ + | batslib_decorate 'line should not be in output' \ + | fail + return $? + fi + done + fi + fi +} + +refute_output() { + local -i is_mode_partial=0 + local -i is_mode_regexp=0 + local -i is_mode_empty=0 + local -i use_stdin=0 + : "${output?}" + + # Handle options. + if (( $# == 0 )); then + is_mode_empty=1 + fi + + while (( $# > 0 )); do + case "$1" in + -p|--partial) is_mode_partial=1; shift ;; + -e|--regexp) is_mode_regexp=1; shift ;; + -|--stdin) use_stdin=1; shift ;; + --) shift; break ;; + *) break ;; + esac + done + + if (( is_mode_partial )) && (( is_mode_regexp )); then + echo "\`--partial' and \`--regexp' are mutually exclusive" \ + | batslib_decorate 'ERROR: refute_output' \ + | fail + return $? + fi + + # Arguments. + local unexpected + if (( use_stdin )); then + unexpected="$(cat -)" + else + unexpected="${1-}" + fi + + if (( is_mode_regexp == 1 )) && [[ '' =~ $unexpected ]] || (( $? == 2 )); then + echo "Invalid extended regular expression: \`$unexpected'" \ + | batslib_decorate 'ERROR: refute_output' \ + | fail + return $? + fi + + # Matching. + if (( is_mode_empty )); then + if [ -n "$output" ]; then + batslib_print_kv_single_or_multi 6 \ + 'output' "$output" \ + | batslib_decorate 'output non-empty, but expected no output' \ + | fail + fi + elif (( is_mode_regexp )); then + if [[ $output =~ $unexpected ]]; then + batslib_print_kv_single_or_multi 6 \ + 'regexp' "$unexpected" \ + 'output' "$output" \ + | batslib_decorate 'regular expression should not match output' \ + | fail + fi + elif (( is_mode_partial )); then + if [[ $output == *"$unexpected"* ]]; then + batslib_print_kv_single_or_multi 9 \ + 'substring' "$unexpected" \ + 'output' "$output" \ + | batslib_decorate 'output should not contain substring' \ + | fail + fi + else + if [[ $output == "$unexpected" ]]; then + batslib_print_kv_single_or_multi 6 \ + 'output' "$output" \ + | batslib_decorate 'output equals, but it was expected to differ' \ + | fail + fi + fi +} diff --git a/exercises/concept/cars-assemble/cars_assemble.bats b/exercises/concept/cars-assemble/cars_assemble.bats new file mode 100644 index 00000000..07d2f793 --- /dev/null +++ b/exercises/concept/cars-assemble/cars_assemble.bats @@ -0,0 +1,194 @@ +#!/usr/bin/env bats +load bats-extra + +# bats test_tags=task:1 +test_success_rate_when_the_line_is_off() { # @test + run bash cars_assemble.sh success-rate 0 + + assert_success + assert_output '100' +} + +# bats test_tags=task:1 +test_success_rate_at_speed_4() { # @test + run bash cars_assemble.sh success-rate 4 + + assert_success + assert_output '100' +} + +# bats test_tags=task:1 +test_success_rate_at_speed_5() { # @test + run bash cars_assemble.sh success-rate 5 + + assert_success + assert_output '90' +} + +# bats test_tags=task:1 +test_success_rate_at_speed_8() { # @test + run bash cars_assemble.sh success-rate 8 + + assert_success + assert_output '90' +} + +# bats test_tags=task:1 +test_success_rate_at_speed_9() { # @test + run bash cars_assemble.sh success-rate 9 + + assert_success + assert_output '80' +} + +# bats test_tags=task:1 +test_success_rate_at_speed_10() { # @test + run bash cars_assemble.sh success-rate 10 + + assert_success + assert_output '77' +} + +# bats test_tags=task:2 +test_production_when_the_line_is_off() { # @test + run bash cars_assemble.sh production 0 + + assert_success + assert_output '0' +} + +# bats test_tags=task:2 +test_production_at_speed_4() { # @test + run bash cars_assemble.sh production 4 + + assert_success + assert_output '884' +} + +# bats test_tags=task:2 +test_production_at_top_speed() { # @test + run bash cars_assemble.sh production 10 + + assert_success + assert_output '2210' +} + +# bats test_tags=task:3 +test_working_cars_when_none_are_faulty() { # @test + run bash cars_assemble.sh working 4 100 + + assert_success + assert_output '884' +} + +# bats test_tags=task:3 +test_working_cars_are_rounded_down() { # @test + run bash cars_assemble.sh working 5 90 + + assert_success + assert_output '994' +} + +# bats test_tags=task:3 +test_working_cars_at_top_speed() { # @test + run bash cars_assemble.sh working 10 77 + + assert_success + assert_output '1701' +} + +# bats test_tags=task:3 +test_working_cars_when_the_line_is_off() { # @test + run bash cars_assemble.sh working 0 100 + + assert_success + assert_output '0' +} + +# bats test_tags=task:4 +test_working_cars_per_minute_at_speed_1() { # @test + run bash cars_assemble.sh per-minute 1 100 + + assert_success + assert_output '3' +} + +# bats test_tags=task:4 +test_working_cars_per_minute_at_speed_5() { # @test + run bash cars_assemble.sh per-minute 5 90 + + assert_success + assert_output '16' +} + +# bats test_tags=task:4 +test_working_cars_per_minute_at_top_speed() { # @test + run bash cars_assemble.sh per-minute 10 77 + + assert_success + assert_output '28' +} + +# bats test_tags=task:4 +test_working_cars_per_minute_when_the_line_is_off() { # @test + run bash cars_assemble.sh per-minute 0 100 + + assert_success + assert_output '0' +} + +# bats test_tags=task:5 +test_shipping_with_cars_left_over() { # @test + run bash cars_assemble.sh shipping 994 150 + + assert_success + assert_output '6 94' +} + +# bats test_tags=task:5 +test_shipping_with_no_cars_left_over() { # @test + run bash cars_assemble.sh shipping 600 150 + + assert_success + assert_output '4 0' +} + +# bats test_tags=task:5 +test_shipping_less_than_one_full_train() { # @test + run bash cars_assemble.sh shipping 94 150 + + assert_success + assert_output '0 94' +} + +# bats test_tags=task:6 +test_factory_before_any_expansion() { # @test + run bash cars_assemble.sh expanded 4 0 + + assert_success + assert_output '884' +} + +# bats test_tags=task:6 +test_factory_after_one_expansion() { # @test + run bash cars_assemble.sh expanded 4 1 + + assert_success + assert_output '1768' +} + +# bats test_tags=task:6 +test_factory_after_three_expansions() { # @test + run bash cars_assemble.sh expanded 4 3 + + assert_success + assert_output '7072' +} + +# bats test_tags=task:6 +test_factory_at_top_speed_after_five_expansions() { # @test + run bash cars_assemble.sh expanded 10 5 + + assert_success + assert_output '70720' +} diff --git a/exercises/concept/cars-assemble/cars_assemble.sh b/exercises/concept/cars-assemble/cars_assemble.sh new file mode 100644 index 00000000..4412a20a --- /dev/null +++ b/exercises/concept/cars-assemble/cars_assemble.sh @@ -0,0 +1,54 @@ +#!/usr/bin/env bash + +# This script helps you analyze the production of a car assembly line. +# +# The first argument names the task to perform. +# The remaining arguments are the data for that task. +# +# The `case` command below runs the code for the requested task. +# The `shift` command removes the first argument, so that "$1" is the first +# of the arguments that are left. +# +# Add your code below each task comment. +# Keep the other lines as they are. + +task=$1 +shift + +case $task in + success-rate) + # Task 1: print the success rate, as a percentage. + # "$1" is the speed of the line. + + ;; + + production) + # Task 2: print the number of cars produced per hour. + # "$1" is the speed of the line. + + ;; + + working) + # Task 3: print the number of cars without faults produced per hour. + # "$1" is the speed of the line, and "$2" is the success rate. + + ;; + + per-minute) + # Task 4: print the number of cars without faults produced per minute. + # "$1" is the speed of the line, and "$2" is the success rate. + + ;; + + shipping) + # Task 5: print the number of full trains and of cars left over. + # "$1" is the number of cars, and "$2" is the capacity of one train. + + ;; + + expanded) + # Task 6: print the number of cars produced per hour by the whole factory. + # "$1" is the speed of the lines, and "$2" is the number of expansions. + + ;; +esac diff --git a/exercises/concept/road-map.md b/exercises/concept/road-map.md index e44ceb93..31f1e8d2 100644 --- a/exercises/concept/road-map.md +++ b/exercises/concept/road-map.md @@ -8,7 +8,7 @@ Ref: [Syllabus][syllabus] | [variables][variables] | [lasagna][lasagna] | [985][985] | cmds-args | | [quoting][quoting] | messy-downloads (OC) | [987][987] | variables | | [conditionals][conditionals] | [vehicle-purchase][vehicle-purchase] | | quoting | -| [arithmetic][arithmetic] | | | conditionals | +| [arithmetic][arithmetic] | cars-assemble | | conditionals | | [looping][looping] | | | conditionals | | [arrays][arrays] | elyses-enchantments | | looping | | [more-arrays][more-arrays] | card-games | | arrays |