Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions concepts/arithmetic/about.md
Original file line number Diff line number Diff line change
Expand Up @@ -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".

Expand All @@ -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.
~~~~

Expand Down
4 changes: 2 additions & 2 deletions concepts/arithmetic/introduction.md
Original file line number Diff line number Diff line change
Expand Up @@ -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".

Expand All @@ -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.
~~~~

Expand Down
12 changes: 12 additions & 0 deletions config.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Comment thread
glennj marked this conversation as resolved.
Resolved
}
],
"practice": [
Expand Down
43 changes: 43 additions & 0 deletions exercises/concept/cars-assemble/.docs/hints.md
Original file line number Diff line number Diff line change
@@ -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
97 changes: 97 additions & 0 deletions exercises/concept/cars-assemble/.docs/instructions.md
Original file line number Diff line number Diff line change
@@ -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
```
157 changes: 157 additions & 0 deletions exercises/concept/cars-assemble/.docs/introduction.md
Original file line number Diff line number Diff line change
@@ -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
3 changes: 3 additions & 0 deletions exercises/concept/cars-assemble/.docs/introduction.md.tpl
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Introduction

%{concept:arithmetic}
23 changes: 23 additions & 0 deletions exercises/concept/cars-assemble/.meta/config.json
Original file line number Diff line number Diff line change
@@ -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."
}
Loading
Loading