primeiro commit com exercicios de Exercism realizados até esta data

This commit is contained in:
2026-10-17 22:10:27 +01:00
commit 58fccbe27a
708 changed files with 35038 additions and 0 deletions
@@ -0,0 +1,26 @@
{
"authors": [
"oanaOM"
],
"files": {
"solution": [
"annalyns_infiltration.go"
],
"test": [
"annalyns_infiltration_test.go"
],
"exemplar": [
".meta/exemplar.go"
],
"invalidator": [
"go.mod"
]
},
"forked_from": [
"csharp/annalyns-infiltration"
],
"blurb": "Learn about booleans by helping Annalyn free her best friend.",
"custom": {
"taskIdsEnabled": true
}
}
@@ -0,0 +1 @@
{"track":"go","exercise":"annalyns-infiltration","id":"7a1da8b9a1844d21a3cc71aca4ee5f0b","url":"https://exercism.org/tracks/go/exercises/annalyns-infiltration","handle":"sanctushck","is_requester":true,"auto_approve":false}
+41
View File
@@ -0,0 +1,41 @@
# Help
## Running the tests
To run the tests run the command `go test` from within the exercise directory.
If the test suite contains benchmarks, you can run these with the `--bench` and `--benchmem`
flags:
go test -v --bench . --benchmem
Keep in mind that each reviewer will run benchmarks on a different machine, with
different specs, so the results from these benchmark tests may vary.
## Submitting your solution
You can submit your solution using the `exercism submit annalyns_infiltration.go` command.
This command will upload your solution to the Exercism website and print the solution page's URL.
It's possible to submit an incomplete solution which allows you to:
- See how others have completed the exercise
- Request help from a mentor
## Need to get help?
If you'd like help solving the exercise, check the following pages:
- The [Go track's documentation](https://exercism.org/docs/tracks/go)
- The [Go track's programming category on the forum](https://forum.exercism.org/c/programming/go)
- [Exercism's programming category on the forum](https://forum.exercism.org/c/programming/5)
- The [Frequently Asked Questions](https://exercism.org/docs/using/faqs)
Should those resources not suffice, you could submit your (incomplete) solution to request mentoring.
To get help if you're having trouble, you can use one of the following resources:
- [How to Write Go Code](https://golang.org/doc/code.html)
- [Effective Go](https://golang.org/doc/effective_go.html)
- [Go Resources](http://golang.org/help)
- [StackOverflow](http://stackoverflow.com/questions/tagged/go)
+23
View File
@@ -0,0 +1,23 @@
# Hints
## General
- There are three [boolean operators][logical operators] to work with boolean values.
- Multiple operators can be combined in a single expression.
## 1. Check if a fast attack can be made
- The logical NOT operator (`!`) can be placed before an expression to negate its value.
## 2. Check if the group can be spied upon
- Logical operators are typically used to evaluate whether two or more expressions are true or not true.
## 3. Check if the prisoner can be signaled
- Logical operators execute in the order of their precedence (from highest to lowest): `!`, `&&`, `||`.
- For more details check out the Operator Precedence section on the [official golang documentation][operators] and the [truth table][truth table].
[logical operators]: https://golang.org/ref/spec#Logical_operators
[operators]: https://golang.org/ref/spec#Operators
[truth table]: https://www.digitalocean.com/community/tutorials/understanding-boolean-logic-in-go
+111
View File
@@ -0,0 +1,111 @@
# Annalyn's Infiltration
Welcome to Annalyn's Infiltration on Exercism's Go Track.
If you need help running the tests or submitting your code, check out `HELP.md`.
If you get stuck on the exercise, check out `HINTS.md`, but try and solve it without using those first :)
## Introduction
Booleans in Go are represented by the predeclared boolean type `bool`, which values can be either `true` or `false`.
It's a defined type.
```go
var closed bool // boolean variable 'closed' implicitly initialized with 'false'
speeding := true // boolean variable 'speeding' initialized with 'true'
hasError := false // boolean variable 'hasError' initialized with 'false'
```
Go supports three logical operators that can evaluate expressions down to Boolean values, returning either `true` or `false`.
| Operator | What it means |
| ----------- | --------------------------------------------- |
| `&&` (and) | It is true if both statements are true. |
| `\|\|` (or) | It is true if at least one statement is true. |
| `!` (not) | It is true only if the statement is false. |
## Instructions
In this exercise, you'll be implementing the quest logic for a new RPG game a friend is developing.
The game's main character is Annalyn, a brave girl with a fierce and loyal pet dog.
Unfortunately, disaster strikes, as her best friend was kidnapped while searching for berries in the forest.
Annalyn will try to find and free her best friend, optionally taking her dog with her on this quest.
After some time spent following her best friend's trail, she finds the camp in which her best friend is imprisoned.
It turns out there are two kidnappers: a mighty knight and a cunning archer.
Having found the kidnappers, Annalyn considers which of the following actions she can engage in:
- _Fast attack_: a fast attack can be made if the knight is sleeping, as it takes time for him to get his armor on, so he will be vulnerable.
- _Spy_: the group can be spied upon if at least one of them is awake.
Otherwise, spying is a waste of time.
- _Signal prisoner_: the prisoner can be signaled using bird sounds if the prisoner is awake and the archer is sleeping, as archers are trained in bird signaling so they could intercept the message.
- _Free prisoner_: Annalyn can try sneaking into the camp to free the prisoner.
This is a risky thing to do and can only succeed in one of two ways:
- If Annalyn has her pet dog with her she can rescue the prisoner if the archer is asleep.
The knight is scared of the dog and the archer will not have time to get ready before Annalyn and the prisoner can escape.
- If Annalyn does not have her dog then she and the prisoner must be very sneaky!
Annalyn can free the prisoner if the prisoner is awake and the knight and archer are both sleeping, but if the prisoner is sleeping they can't be rescued: the prisoner would be startled by Annalyn's sudden appearance and wake up the knight and archer.
You have four tasks: to implement the logic for determining if the above actions are available based on the state of the three characters found in the forest and whether Annalyn's pet dog is present or not.
## 1. Check if a fast attack can be made
Define the `CanFastAttack()` function that takes a boolean value that indicates if the knight is awake.
This function returns `true` if a fast attack can be made based on the state of the knight.
Otherwise, returns `false`:
```go
var knightIsAwake = true
fmt.Println(CanFastAttack(knightIsAwake))
// Output: false
```
## 2. Check if the group can be spied upon
Define the `CanSpy()` function that takes three boolean values, indicating if the knight, archer and the prisoner, respectively, are awake.
The function returns `true` if the group can be spied upon, based on the state of the three characters.
Otherwise, returns `false`:
```go
var knightIsAwake = false
var archerIsAwake = true
var prisonerIsAwake = false
fmt.Println(CanSpy(knightIsAwake, archerIsAwake, prisonerIsAwake))
// Output: true
```
## 3. Check if the prisoner can be signaled
Define the `CanSignalPrisoner()` function that takes two boolean values, indicating if the archer and the prisoner, respectively, are awake.
The function returns `true` if the prisoner can be signaled, based on the state of the two characters.
Otherwise, returns `false`:
```go
var archerIsAwake = false
var prisonerIsAwake = true
fmt.Println(CanSignalPrisoner(archerIsAwake, prisonerIsAwake))
// Output: true
```
## 4. Check if the prisoner can be freed
Define the `CanFreePrisoner()` function that takes four boolean values.
The first three parameters indicate if the knight, archer and the prisoner, respectively, are awake.
The last parameter indicates if Annalyn's pet dog is present.
The function returns `true` if the prisoner can be freed based on the state of the three characters and Annalyn's pet dog presence.
Otherwise, it returns `false`:
```go
var knightIsAwake = false
var archerIsAwake = true
var prisonerIsAwake = false
var petDogIsPresent = false
fmt.Println(CanFreePrisoner(knightIsAwake, archerIsAwake, prisonerIsAwake, petDogIsPresent))
// Output: false
```
## Source
### Created by
- @oanaOM
@@ -0,0 +1,22 @@
package annalyn
// CanFastAttack can be executed only when the knight is sleeping.
func CanFastAttack(knightIsAwake bool) bool {
return !knightIsAwake
}
// CanSpy can be executed if at least one of the characters is awake.
func CanSpy(knightIsAwake, archerIsAwake, prisonerIsAwake bool) bool {
return knightIsAwake || archerIsAwake || prisonerIsAwake
}
// CanSignalPrisoner can be executed if the prisoner is awake and the archer is sleeping.
func CanSignalPrisoner(archerIsAwake, prisonerIsAwake bool) bool {
return !archerIsAwake && prisonerIsAwake
}
// CanFreePrisoner can be executed if the prisoner is awake and the other 2 characters are asleep
// or if Annalyn's pet dog is with her and the archer is sleeping.
func CanFreePrisoner(knightIsAwake, archerIsAwake, prisonerIsAwake, petDogIsPresent bool) bool {
return (prisonerIsAwake && (!knightIsAwake && !archerIsAwake)) || (!archerIsAwake && petDogIsPresent)
}
@@ -0,0 +1,286 @@
package annalyn
import "testing"
type charactersState struct {
desc string
knightIsAwake bool
archerIsAwake bool
prisonerIsAwake bool
dogIsPresent bool
expected bool
}
func TestCanFastAttack(t *testing.T) {
tests := []charactersState{
{
desc: "Knight is awake",
knightIsAwake: true,
expected: false,
},
{
desc: "Knight is sleeping",
knightIsAwake: false,
expected: true,
},
}
for _, tc := range tests {
t.Run(tc.desc, func(t *testing.T) {
if got := CanFastAttack(tc.knightIsAwake); got != tc.expected {
t.Errorf("CanFastAttack(%v) = %v; want %v", tc.knightIsAwake, got, tc.expected)
}
})
}
}
func TestCanSpy(t *testing.T) {
tests := []charactersState{
{
desc: "All characters are sleeping",
knightIsAwake: false,
archerIsAwake: false,
prisonerIsAwake: false,
expected: false,
},
{
desc: "Knight is awake, archer and prisoner are sleeping",
knightIsAwake: true,
archerIsAwake: false,
prisonerIsAwake: false,
expected: true,
},
{
desc: "Knight and archer are awake, prisoner is sleeping",
knightIsAwake: true,
archerIsAwake: true,
prisonerIsAwake: false,
expected: true,
},
{
desc: "Knight and prisoner are awake, archer is sleeping",
knightIsAwake: true,
archerIsAwake: false,
prisonerIsAwake: true,
expected: true,
},
{
desc: "Archer is awake, knight and prisoner are sleeping",
knightIsAwake: false,
archerIsAwake: true,
prisonerIsAwake: false,
expected: true,
},
{
desc: "Archer and prisoner are awake, knight is sleeping",
knightIsAwake: false,
archerIsAwake: true,
prisonerIsAwake: true,
expected: true,
},
{
desc: "Prisoner is awake, knight and archer are sleeping",
knightIsAwake: false,
archerIsAwake: false,
prisonerIsAwake: true,
expected: true,
},
{
desc: "All characters are awake",
knightIsAwake: true,
archerIsAwake: true,
prisonerIsAwake: true,
expected: true,
},
}
for _, tc := range tests {
t.Run(tc.desc, func(t *testing.T) {
if got := CanSpy(tc.knightIsAwake, tc.archerIsAwake, tc.prisonerIsAwake); got != tc.expected {
t.Errorf("CanSpy(%v, %v, %v) = %v; want %v", tc.knightIsAwake, tc.archerIsAwake, tc.prisonerIsAwake, got, tc.expected)
}
})
}
}
func TestCanSignalPrisoner(t *testing.T) {
tests := []charactersState{
{
desc: "All characters are sleeping",
archerIsAwake: false,
prisonerIsAwake: false,
expected: false,
},
{
desc: "Archer is sleeping, prisoner is awake",
archerIsAwake: false,
prisonerIsAwake: true,
expected: true,
},
{
desc: "Archer is awake, prisoner is sleeping",
archerIsAwake: true,
prisonerIsAwake: false,
expected: false,
},
{
desc: "All characters are awake",
archerIsAwake: true,
prisonerIsAwake: true,
expected: false,
},
}
for _, tc := range tests {
t.Run(tc.desc, func(t *testing.T) {
if got := CanSignalPrisoner(tc.archerIsAwake, tc.prisonerIsAwake); got != tc.expected {
t.Errorf("CanSignalPrisoner(%v, %v) = %v; want %v", tc.archerIsAwake, tc.prisonerIsAwake, got, tc.expected)
}
})
}
}
func TestCanFreePrisoner(t *testing.T) {
tests := []charactersState{
{
desc: "All characters are sleeping. Dog is not present.",
knightIsAwake: false,
archerIsAwake: false,
prisonerIsAwake: false,
dogIsPresent: false,
expected: false,
},
{
desc: "All characters are sleeping. Dog is present.",
knightIsAwake: false,
archerIsAwake: false,
prisonerIsAwake: false,
dogIsPresent: true,
expected: true,
},
{
desc: "Knight and archer are sleeping. Prisoner is awake. Dog is not present.",
knightIsAwake: false,
archerIsAwake: false,
prisonerIsAwake: true,
dogIsPresent: false,
expected: true,
},
{
desc: "Knight and archer are sleeping. Prisoner is awake. Dog is present.",
knightIsAwake: false,
archerIsAwake: false,
prisonerIsAwake: true,
dogIsPresent: true,
expected: true,
},
{
desc: "Knight is sleeping. Archer is awake. Prisoner is sleeping. Dog is not present.",
knightIsAwake: false,
archerIsAwake: true,
prisonerIsAwake: false,
dogIsPresent: false,
expected: false,
},
{
desc: "Knight is sleeping. Archer is awake. Prisoner is sleeping. Dog is present.",
knightIsAwake: false,
archerIsAwake: true,
prisonerIsAwake: false,
dogIsPresent: true,
expected: false,
},
{
desc: "Knight is sleeping. Archer is awake. Prisoner is awake. Dog is not present.",
knightIsAwake: false,
archerIsAwake: true,
prisonerIsAwake: true,
dogIsPresent: false,
expected: false,
},
{
desc: "Knight is sleeping. Archer is awake. Prisoner is awake. Dog is present.",
knightIsAwake: false,
archerIsAwake: true,
prisonerIsAwake: true,
dogIsPresent: true,
expected: false,
},
{
desc: "Knight is awake. Archer is sleeping. Prisoner is sleeping. Dog is not present.",
knightIsAwake: true,
archerIsAwake: false,
prisonerIsAwake: false,
dogIsPresent: false,
expected: false,
},
{
desc: "Knight is awake. Archer is sleeping. Prisoner is sleeping. Dog is present.",
knightIsAwake: true,
archerIsAwake: false,
prisonerIsAwake: false,
dogIsPresent: true,
expected: true,
},
{
desc: "Knight is awake. Archer is sleeping. Prisoner is awake. Dog is not present",
knightIsAwake: true,
archerIsAwake: false,
prisonerIsAwake: true,
dogIsPresent: false,
expected: false,
},
{
desc: "Knight is awake. Archer is sleeping. Prisoner is awake. Dog is present",
knightIsAwake: true,
archerIsAwake: false,
prisonerIsAwake: true,
dogIsPresent: true,
expected: true,
},
{
desc: "Knight and archer are awake. Prisoner is sleeping. Dog is not present",
knightIsAwake: true,
archerIsAwake: true,
prisonerIsAwake: false,
dogIsPresent: false,
expected: false,
},
{
desc: "Knight and archer are awake. Prisoner is sleeping. Dog is present",
knightIsAwake: true,
archerIsAwake: true,
prisonerIsAwake: false,
dogIsPresent: true,
expected: false,
},
{
desc: "Knight and archer are awake. Prisoner is awake. Dog is not present",
knightIsAwake: true,
archerIsAwake: true,
prisonerIsAwake: true,
dogIsPresent: false,
expected: false,
},
{
desc: "Knight and archer are awake. Prisoner is awake. Dog is present",
knightIsAwake: true,
archerIsAwake: true,
prisonerIsAwake: true,
dogIsPresent: true,
expected: false,
},
{
desc: "Everyone is sleeping. Dog is not present",
knightIsAwake: false,
archerIsAwake: false,
prisonerIsAwake: false,
dogIsPresent: false,
expected: false,
},
}
for _, tc := range tests {
t.Run(tc.desc, func(t *testing.T) {
if got := CanFreePrisoner(tc.knightIsAwake, tc.archerIsAwake, tc.prisonerIsAwake, tc.dogIsPresent); got != tc.expected {
t.Errorf("CanFreePrisoner(%v,%v,%v,%v) = %v; want %v", tc.knightIsAwake, tc.archerIsAwake, tc.prisonerIsAwake, tc.dogIsPresent, got, tc.expected)
}
})
}
}
+3
View File
@@ -0,0 +1,3 @@
module annalyn
go 1.26
+28
View File
@@ -0,0 +1,28 @@
{
"authors": [
"DavyJ0nes",
"kahgoh"
],
"contributors": [
"tehsphinx",
"andrerfcsantos"
],
"files": {
"solution": [
"cars_assemble.go"
],
"test": [
"cars_assemble_test.go"
],
"exemplar": [
".meta/exemplar.go"
],
"invalidator": [
"go.mod"
]
},
"blurb": "Learn about numbers and type conversion by analyzing an assembly line in a car factory.",
"custom": {
"taskIdsEnabled": true
}
}
+1
View File
@@ -0,0 +1 @@
{"track":"go","exercise":"cars-assemble","id":"4fa36f30c78743439e2f50df93aeb7bb","url":"https://exercism.org/tracks/go/exercises/cars-assemble","handle":"sanctushck","is_requester":true,"auto_approve":false}
+41
View File
@@ -0,0 +1,41 @@
# Help
## Running the tests
To run the tests run the command `go test` from within the exercise directory.
If the test suite contains benchmarks, you can run these with the `--bench` and `--benchmem`
flags:
go test -v --bench . --benchmem
Keep in mind that each reviewer will run benchmarks on a different machine, with
different specs, so the results from these benchmark tests may vary.
## Submitting your solution
You can submit your solution using the `exercism submit cars_assemble.go` command.
This command will upload your solution to the Exercism website and print the solution page's URL.
It's possible to submit an incomplete solution which allows you to:
- See how others have completed the exercise
- Request help from a mentor
## Need to get help?
If you'd like help solving the exercise, check the following pages:
- The [Go track's documentation](https://exercism.org/docs/tracks/go)
- The [Go track's programming category on the forum](https://forum.exercism.org/c/programming/go)
- [Exercism's programming category on the forum](https://forum.exercism.org/c/programming/5)
- The [Frequently Asked Questions](https://exercism.org/docs/using/faqs)
Should those resources not suffice, you could submit your (incomplete) solution to request mentoring.
To get help if you're having trouble, you can use one of the following resources:
- [How to Write Go Code](https://golang.org/doc/code.html)
- [Effective Go](https://golang.org/doc/effective_go.html)
- [Go Resources](http://golang.org/help)
- [StackOverflow](http://stackoverflow.com/questions/tagged/go)
+32
View File
@@ -0,0 +1,32 @@
# Hints
## General
- To learn more about types in Go, check [Tour of Go: Basic Types][basic types].
- To learn more about type conversions in Go, check [Tour of Go: Type 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.
- When multiplying two numbers together, they both need to be of the same type.
Use [type conversions][type conversions] if needed.
## 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 `CalculateProductionRatePerHour` function you made 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.
[basic types]: https://tour.golang.org/basics/11
[type conversions]: https://tour.golang.org/basics/13
[modulo operator]: https://golangbyexamples.com/remainder-modulus-go-golang/
+138
View File
@@ -0,0 +1,138 @@
# Cars Assemble
Welcome to Cars Assemble on Exercism's Go Track.
If you need help running the tests or submitting your code, check out `HELP.md`.
If you get stuck on the exercise, check out `HINTS.md`, but try and solve it without using those first :)
## Introduction
## Numbers
Go contains basic numeric types that can represent sets of either integer or floating-point values.
There are different types depending on the size of value you require and the architecture of the computer where the application is running (e.g. 32-bit and 64-bit).
For the sake of this exercise you will only be dealing with:
- `int`: e.g. `0`, `255`, `2147483647`.
A signed integer that is at least 32 bits in size (value range of: -2147483648 through 2147483647).
But this will depend on the systems architecture.
Most modern computers are 64 bit, therefore `int` will be 64 bits in size (value rate of: -9223372036854775808 through 9223372036854775807).
- `float64`: e.g. `0.0`, `3.14`.
Contains the set of all 64-bit floating-point numbers.
- `uint`: e.g. `0`, `255`.
An unsigned integer that is the same size as `int` (value range of: 0 through 4294967295 for 32 bits and 0 through 18446744073709551615 for 64 bits)
Numbers can be converted to other numeric types through Type Conversion.
## Arithmetic Operators
Go supports many standard arithmetic operators:
| Operator | Example |
| -------- | -------------- |
| `+` | `4 + 6 == 10` |
| `-` | `15 - 10 == 5` |
| `*` | `2 * 3 == 6` |
| `/` | `13 / 3 == 4` |
| `%` | `13 % 3 == 1` |
For integer division, the remainder is dropped (e.g. `5 / 2 == 2`).
Go has shorthand assignment for the operators above (e.g. `a += 5` is short for `a = a + 5`).
Go also supports the increment and decrement statements `++` and `--` (e.g. `a++`).
## Converting between types
Converting between types is done via a function with the name of the type to convert to.
For example:
```go
var x int = 42 // x has type int
f := float64(x) // f has type float64 (ie. 42.0)
var y float64 = 11.9 // y has type float64
i := int(y) // i has type int (ie. 11)
```
## Arithmetic operations on different types
In many languages you can perform arithmetic operations on different types of variables, but in Go this gives an error.
For example:
```go
var x int = 42
// this line produces an error
value := float32(2.0) * x // invalid operation: mismatched types float32 and int
// you must convert int type to float32 before performing arithmetic operation
value := float32(2.0) * float32(x)
```
## 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`:
```go
CalculateWorkingCarsPerHour(1547, 90)
// => 1392.3
```
**Note:** the return value should be a `float64`.
## 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:
```go
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:
```go
CalculateCost(37)
// => 355000
CalculateCost(21)
// => 200000
```
**Note:** the return value should be an `uint`.
## Source
### Created by
- @DavyJ0nes
- @kahgoh
### Contributed to by
- @tehsphinx
- @andrerfcsantos
+19
View File
@@ -0,0 +1,19 @@
package cars
// CalculateWorkingCarsPerHour calculates how many working cars are
// produced by the assembly line every hour.
func CalculateWorkingCarsPerHour(productionRate int, successRate float64) float64 {
return float64(productionRate) * successRate/100.0
}
// CalculateWorkingCarsPerMinute calculates how many working cars are
// produced by the assembly line every minute.
func CalculateWorkingCarsPerMinute(productionRate int, successRate float64) int {
return int(float64(productionRate)/60 * successRate/100)
}
// CalculateCost works out the cost of producing the given number of cars.
func CalculateCost(carsCount int) uint {
var numberOfBundles uint = uint(carsCount/10)
return (numberOfBundles*95000) + (uint(carsCount)-(numberOfBundles*10))*10000
}
+197
View File
@@ -0,0 +1,197 @@
package cars
import (
"math"
"testing"
)
const floatEqualityThreshold = 1e-9
func floatingPointEquals(got, want float64) bool {
absoluteDifferenceBelowThreshold := math.Abs(got-want) <= floatEqualityThreshold
relativeDifferenceBelowThreshold := math.Abs(got-want)/(math.Abs(got)+math.Abs(want)) <= floatEqualityThreshold
return absoluteDifferenceBelowThreshold || relativeDifferenceBelowThreshold
}
func TestCalculateWorkingCarsPerHour(t *testing.T) {
tests := []struct {
name string
productionRate int
successRate float64
want float64
}{
{
name: "calculate working cars per hour for production rate 0",
productionRate: 0,
successRate: 100,
want: 0.0,
},
{
name: "calculate working cars per hour for 100% success rate",
productionRate: 221,
successRate: 100,
want: 221.0,
},
{
name: "calculate working cars per hour for 80% success rate",
productionRate: 426,
successRate: 80,
want: 340.8,
},
{
name: "calculate working cars per hour for 20.5% success rate",
productionRate: 6824,
successRate: 20.5,
want: 1398.92,
},
{
name: "calculate working cars per hour for 0% success rate",
productionRate: 8000,
successRate: 0,
want: 0,
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
got := CalculateWorkingCarsPerHour(tc.productionRate, tc.successRate)
if !floatingPointEquals(got, tc.want) {
t.Errorf(
"CalculateWorkingCarsPerHour(%d, %f) = %f, want %f",
tc.productionRate,
tc.successRate,
got,
tc.want,
)
}
})
}
}
func TestCalculateWorkingCarsPerMinute(t *testing.T) {
tests := []struct {
name string
productionRate int
successRate float64
want int
}{
{
name: "calculate working cars per minute for production rate 0",
productionRate: 0,
successRate: 100,
want: 0,
},
{
name: "calculate working cars per minute for 100% success rate",
productionRate: 221,
successRate: 100,
want: 3,
},
{
name: "calculate working cars per minute for 80% success rate",
productionRate: 426,
successRate: 80,
want: 5,
},
{
name: "calculate working cars per minute for 20.5% success rate",
productionRate: 6824,
successRate: 20.5,
want: 23,
},
{
name: "calculate working cars per minute for 0% success rate",
productionRate: 8000,
successRate: 0,
want: 0,
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
got := CalculateWorkingCarsPerMinute(tc.productionRate, tc.successRate)
if got != tc.want {
t.Errorf(
"CalculateWorkingCarsPerMinute(%d, %f) = %d, want %d",
tc.productionRate,
tc.successRate,
got,
tc.want,
)
}
})
}
}
func TestCalculateCost(t *testing.T) {
tests := []struct {
name string
carsCount int
want uint
}{
{
name: "calculate cost to produce 0 cars",
carsCount: 0,
want: 0,
},
{
name: "calculate the cost of materials to produce 1 car",
carsCount: 1,
want: 10000,
},
{
name: "calculate cost to produce 2 cars",
carsCount: 2,
want: 20000,
},
{
name: "calculate cost to produce 9 cars",
carsCount: 9,
want: 90000,
},
{
name: "calculate cost to produce 10 cars",
carsCount: 10,
want: 95000,
},
{
name: "calculate cost to produce 100 cars",
carsCount: 100,
want: 950000,
},
{
name: "calculate cost to produce 21 cars",
carsCount: 21,
want: 200000,
},
{
name: "calculate cost to produce 37 cars",
carsCount: 37,
want: 355000,
},
{
name: "calculate cost to produce 56 cars",
carsCount: 56,
want: 535000,
},
{
name: "calculate cost to produce 148 cars",
carsCount: 148,
want: 1410000,
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
got := CalculateCost(tc.carsCount)
if got != tc.want {
t.Errorf(
"CalculateCost(%d) = %d, want %d",
tc.carsCount,
got,
tc.want,
)
}
})
}
}
+3
View File
@@ -0,0 +1,3 @@
module cars
go 1.26
+1
View File
@@ -0,0 +1 @@
https://exercism.org/tracks/go
+35
View File
@@ -0,0 +1,35 @@
{
"authors": [
"k4rtik"
],
"contributors": [
"bitfield",
"ekingery",
"ferhatelmas",
"hilary",
"kytrinyx",
"leenipper",
"petertseng",
"robphoenix",
"SebastianKristof",
"sebito91",
"tleen"
],
"files": {
"solution": [
"hello_world.go"
],
"test": [
"hello_world_test.go"
],
"example": [
".meta/example.go"
],
"invalidator": [
"go.mod"
]
},
"blurb": "The classical introductory exercise. Just say \"Hello, World!\".",
"source": "This is an exercise to introduce users to using Exercism",
"source_url": "https://en.wikipedia.org/wiki/%22Hello,_world!%22_program"
}
+1
View File
@@ -0,0 +1 @@
{"track":"go","exercise":"hello-world","id":"a2527b7e2191407ea00beb5991895983","url":"https://exercism.org/tracks/go/exercises/hello-world","handle":"sanctushck","is_requester":true,"auto_approve":false}
+41
View File
@@ -0,0 +1,41 @@
# Help
## Running the tests
To run the tests run the command `go test` from within the exercise directory.
If the test suite contains benchmarks, you can run these with the `--bench` and `--benchmem`
flags:
go test -v --bench . --benchmem
Keep in mind that each reviewer will run benchmarks on a different machine, with
different specs, so the results from these benchmark tests may vary.
## Submitting your solution
You can submit your solution using the `exercism submit hello_world.go` command.
This command will upload your solution to the Exercism website and print the solution page's URL.
It's possible to submit an incomplete solution which allows you to:
- See how others have completed the exercise
- Request help from a mentor
## Need to get help?
If you'd like help solving the exercise, check the following pages:
- The [Go track's documentation](https://exercism.org/docs/tracks/go)
- The [Go track's programming category on the forum](https://forum.exercism.org/c/programming/go)
- [Exercism's programming category on the forum](https://forum.exercism.org/c/programming/5)
- The [Frequently Asked Questions](https://exercism.org/docs/using/faqs)
Should those resources not suffice, you could submit your (incomplete) solution to request mentoring.
To get help if you're having trouble, you can use one of the following resources:
- [How to Write Go Code](https://golang.org/doc/code.html)
- [Effective Go](https://golang.org/doc/effective_go.html)
- [Go Resources](http://golang.org/help)
- [StackOverflow](http://stackoverflow.com/questions/tagged/go)
+45
View File
@@ -0,0 +1,45 @@
# Hello World
Welcome to Hello World on Exercism's Go Track.
If you need help running the tests or submitting your code, check out `HELP.md`.
## Instructions
The classical introductory exercise.
Just say "Hello, World!".
["Hello, World!"][hello-world] is the traditional first program for beginning programming in a new language or environment.
The objectives are simple:
- Modify the provided code so that it produces the string "Hello, World!".
- Run the test suite and make sure that it succeeds.
- Submit your solution and check it at the website.
If everything goes well, you will be ready to fetch your first real exercise.
[hello-world]: https://en.wikipedia.org/wiki/%22Hello,_world!%22_program
## Source
### Created by
- @k4rtik
### Contributed to by
- @bitfield
- @ekingery
- @ferhatelmas
- @hilary
- @kytrinyx
- @leenipper
- @petertseng
- @robphoenix
- @SebastianKristof
- @sebito91
- @tleen
### Based on
This is an exercise to introduce users to using Exercism - https://en.wikipedia.org/wiki/%22Hello,_world!%22_program
+3
View File
@@ -0,0 +1,3 @@
module greeting
go 1.18
+6
View File
@@ -0,0 +1,6 @@
package greeting
// HelloWorld greets the world.
func HelloWorld() string {
return "Hello, World!"
}
+40
View File
@@ -0,0 +1,40 @@
package greeting
import "testing"
// Define a function named HelloWorld that takes no arguments,
// and returns a string.
// In other words, define a function with the following signature:
// HelloWorld() string
func TestHelloWorld(t *testing.T) {
expected := "Hello, World!"
if observed := HelloWorld(); observed != expected {
t.Fatalf("HelloWorld() = %v, want %v", observed, expected)
}
}
// BenchmarkHelloWorld() is a benchmarking function. These functions follow the
// form `func BenchmarkXxx(*testing.B)` and can be used to test the performance
// of your implementation. They may not be present in every exercise, but when
// they are you can run them by including the `-bench` flag with the `go test`
// command, like so: `go test -v --bench . --benchmem`
//
// You will see output similar to the following:
//
// BenchmarkHelloWorld 2000000000 0.46 ns/op
//
// This means that the loop ran 2000000000 times at a speed of 0.46 ns per loop.
//
// While benchmarking can be useful to compare different iterations of the same
// exercise, keep in mind that others will run the same benchmarks on different
// machines, with different specs, so the results from these benchmark tests may
// vary.
func BenchmarkHelloWorld(b *testing.B) {
if testing.Short() {
b.Skip("skipping benchmark in short mode.")
}
for i := 0; i < b.N; i++ {
HelloWorld()
}
}
+31
View File
@@ -0,0 +1,31 @@
{
"authors": [
"tehsphinx"
],
"contributors": [
"ekingery",
"andrerfcsantos",
"bobtfish"
],
"files": {
"solution": [
"lasagna.go"
],
"test": [
"lasagna_test.go"
],
"exemplar": [
".meta/exemplar.go"
],
"invalidator": [
"go.mod"
]
},
"forked_from": [
"csharp/lucians-luscious-lasagna"
],
"blurb": "Learn about packages, functions, and variables by helping Gopher cook lasagna.",
"custom": {
"taskIdsEnabled": true
}
}
+1
View File
@@ -0,0 +1 @@
{"track":"go","exercise":"lasagna","id":"ff1a7a2429c741b1b4c4202a1d422002","url":"https://exercism.org/tracks/go/exercises/lasagna","handle":"sanctushck","is_requester":true,"auto_approve":false}
+41
View File
@@ -0,0 +1,41 @@
# Help
## Running the tests
To run the tests run the command `go test` from within the exercise directory.
If the test suite contains benchmarks, you can run these with the `--bench` and `--benchmem`
flags:
go test -v --bench . --benchmem
Keep in mind that each reviewer will run benchmarks on a different machine, with
different specs, so the results from these benchmark tests may vary.
## Submitting your solution
You can submit your solution using the `exercism submit lasagna.go` command.
This command will upload your solution to the Exercism website and print the solution page's URL.
It's possible to submit an incomplete solution which allows you to:
- See how others have completed the exercise
- Request help from a mentor
## Need to get help?
If you'd like help solving the exercise, check the following pages:
- The [Go track's documentation](https://exercism.org/docs/tracks/go)
- The [Go track's programming category on the forum](https://forum.exercism.org/c/programming/go)
- [Exercism's programming category on the forum](https://forum.exercism.org/c/programming/5)
- The [Frequently Asked Questions](https://exercism.org/docs/using/faqs)
Should those resources not suffice, you could submit your (incomplete) solution to request mentoring.
To get help if you're having trouble, you can use one of the following resources:
- [How to Write Go Code](https://golang.org/doc/code.html)
- [Effective Go](https://golang.org/doc/effective_go.html)
- [Go Resources](http://golang.org/help)
- [StackOverflow](http://stackoverflow.com/questions/tagged/go)
+44
View File
@@ -0,0 +1,44 @@
# Hints
## General
- An [integer value][integers] can be defined as one or more consecutive digits.
- If you see a `panic:` error when running the tests, this is because you have not implemented one of the functions (it should say which one) or you have left the boilerplate in place. You need to remove the `panic(...)` line from the supplied code and replace it with a real implementation.
## 1. Define the expected oven time in minutes
- You need to define a [constant][constants] and assign it the expected oven time in minutes.
- If you see an `undefined: OvenTime` error then double check that you have the constant defined.
- If you see an `invalid operation: got != tt.expected (mismatched types float64 and int)` error then you have likely put a decimal point into the `OvenTime` causing Go to infer the type as a floating point number. Remove the decimal and the type will be inferred as an `int`.
- If you see a `syntax error: non-declaration statement outside function body` error then it is likely that you forgot the `const` keyword.
- If you see a `syntax error: unexpected :=, expecting =` error then you are likely trying to assign the constant using `:=` like a variable; constants are assigned using `=` not `:=`.
## 2. Calculate the remaining oven time in minutes
- You need to define a [function][functions] with a single parameter.
- You have to [explicitly return an integer][return] from a function.
- The function's parameter is an [integer][integers].
- You can [call][calls] one of the other functions you've defined previously.
- You can use the [mathematical operator for subtraction][operators] to subtract values.
## 3. Calculate the preparation time in minutes
- You need to define a [function][functions] with a single parameter.
- You have to [explicitly return an integer][return] from a function.
- The function's parameter is an [integer][integers].
- You can use the [mathematical operator for multiplication][operators] to multiply values.
## 4. Calculate the elapsed working time in minutes
- You need to define a [function][functions] with two parameters.
- You have to [explicitly return an integer][return] from a function.
- The function's parameter is an [integer][integers].
- You can [call][calls] one of the other functions you've defined previously.
- You can use the [mathematical operator for addition][operators] to add values.
[functions]: https://tour.golang.org/basics/4
[return]: https://golang.org/ref/spec#Return_statements
[operators]: https://golang.org/ref/spec#Operators
[integers]: https://golang.org/ref/spec#Integer_literals
[calls]: https://golang.org/ref/spec#Calls
[constants]: https://tour.golang.org/basics/15
+151
View File
@@ -0,0 +1,151 @@
# Gopher's Gorgeous Lasagna
Welcome to Gopher's Gorgeous Lasagna on Exercism's Go Track.
If you need help running the tests or submitting your code, check out `HELP.md`.
If you get stuck on the exercise, check out `HINTS.md`, but try and solve it without using those first :)
## Introduction
[Go](https://golang.org) is a statically typed, compiled programming language.
This exercise introduces three major language features: Packages, Functions, and Variables.
## Packages
Go applications are organized in packages.
A package is a collection of source files located in the same directory.
All source files in a directory must share the same package name.
When a package is imported, only entities (functions, types, variables, constants) whose names start with a capital letter can be used / accessed.
The recommended style of naming in Go is that identifiers will be named using `camelCase`, except for those meant to be accessible across packages which should be `PascalCase`.
```go
package lasagna
```
## Variables
Go is statically-typed, which means all variables [must have a defined type](https://en.wikipedia.org/wiki/Type_system) at compile-time.
Variables can be defined by explicitly specifying a type:
```go
var explicit int // Explicitly typed
```
You can also use an initializer, and the compiler will assign the variable type to match the type of the initializer.
```go
implicit := 10 // Implicitly typed as an int
```
Once declared, variables can be assigned values using the `=` operator.
Once declared, a variable's type can never change.
```go
count := 1 // Assign initial value
count = 2 // Update to new value
count = false // This throws a compiler error due to assigning a non `int` type
```
## Constants
Constants hold a piece of data just like variables, but their value cannot change during the execution of the program.
Constants are defined using the `const` keyword and can be numbers, characters, strings or booleans:
```go
const Age = 21 // Defines a numeric constant 'Age' with the value of 21
```
## Functions
Go functions accept zero or more parameters.
Parameters must be explicitly typed, there is no type inference.
Values are returned from functions using the `return` keyword.
A function is invoked by specifying the function name and passing arguments for each of the function's parameters.
Note that Go supports two types of comments.
Single line comments are preceded by `//` and multiline comments are inserted between `/*` and `*/`.
```go
package greeting
// Hello is a public function.
func Hello (name string) string {
return hi(name)
}
// hi is a private function.
func hi (name string) string {
return "hi " + name
}
```
## Instructions
In this exercise you're going to write some code to help you cook a brilliant lasagna from your favorite cooking book.
You have four tasks, all related to the time spent cooking the lasagna.
## 1. Define the expected oven time in minutes
Define the `OvenTime` constant with how many minutes the lasagna should be in the oven. According to the cooking book, the expected oven time in minutes is 40:
```go
OvenTime
// => 40
```
## 2. Calculate the remaining oven time in minutes
Define the `RemainingOvenTime()` function that takes the actual minutes the lasagna has been in the oven as a parameter and returns how many minutes the lasagna still has to remain in the oven, based on the expected oven time in minutes from the previous task.
```go
func RemainingOvenTime(actual int) int {
// TODO
}
RemainingOvenTime(30)
// => 10
```
## 3. Calculate the preparation time in minutes
Define the `PreparationTime` function that takes the number of layers you added to the lasagna as a parameter and returns how many minutes you spent preparing the lasagna, assuming each layer takes you 2 minutes to prepare.
```go
func PreparationTime(numberOfLayers int) int {
// TODO
}
PreparationTime(2)
// => 4
```
## 4. Calculate the elapsed working time in minutes
Define the `ElapsedTime` function that takes two parameters: the first parameter is the number of layers you added to the lasagna, and the second parameter is the number of minutes the lasagna has been in the oven.
The function should return how many minutes in total you've worked on cooking the lasagna, which is the sum of the preparation time in minutes, and the time in minutes the lasagna has spent in the oven at the moment.
```go
func ElapsedTime(numberOfLayers, actualMinutesInOven int) int {
// TODO
}
ElapsedTime(3, 20)
// => 26
```
## Source
### Created by
- @tehsphinx
### Contributed to by
- @ekingery
- @andrerfcsantos
- @bobtfish
+3
View File
@@ -0,0 +1,3 @@
module lasagna
go 1.18
+19
View File
@@ -0,0 +1,19 @@
package lasagna
// TODO: define the 'OvenTime' constant
const OvenTime int = 40
// RemainingOvenTime returns the remaining minutes based on the `actual` minutes already in the oven.
func RemainingOvenTime(actualMinutesInOven int) int {
return OvenTime - actualMinutesInOven
}
// PreparationTime calculates the time needed to prepare the lasagna based on the amount of layers.
func PreparationTime(numberOfLayers int) int {
return numberOfLayers * 2
}
// ElapsedTime calculates the time elapsed cooking the lasagna. This time includes the preparation time and the time the lasagna is baking in the oven.
func ElapsedTime(numberOfLayers, actualMinutesInOven int) int {
return PreparationTime(numberOfLayers) + actualMinutesInOven
}
+94
View File
@@ -0,0 +1,94 @@
package lasagna
import "testing"
type lasagnaTests struct {
name string
layers, time, expected int
}
func TestOvenTime(t *testing.T) {
tests := []lasagnaTests{
{
name: "Calculates how many minutes the lasagna should be in the oven",
layers: 0,
time: 40,
expected: 40,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := OvenTime; got != tt.expected {
t.Errorf("OvenTime(%d) = %d; want %d", tt.expected, got, tt.expected)
}
})
}
}
func TestRemainingOvenTime(t *testing.T) {
tests := []lasagnaTests{
{
name: "Remaining minutes in oven",
layers: 0,
time: 15,
expected: 25,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := RemainingOvenTime(tt.time); got != tt.expected {
t.Errorf("RemainingOvenTime(%d) = %d; want %d", tt.time, got, tt.expected)
}
})
}
}
func TestPreparationTime(t *testing.T) {
tests := []lasagnaTests{
{
name: "Preparation time in minutes for one layer",
layers: 1,
time: 0,
expected: 2,
},
{
name: "Preparation time in minutes for multiple layers",
layers: 4,
time: 0,
expected: 8,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := PreparationTime(tt.layers); got != tt.expected {
t.Errorf("PreparationTime(%d) = %d; want %d", tt.layers, got, tt.expected)
}
})
}
}
func TestElapsedTime(t *testing.T) {
tests := []lasagnaTests{
{
name: "Total time in minutes for one layer",
layers: 1,
time: 30,
expected: 32,
},
{
name: "Total time in minutes for multiple layers",
layers: 4,
time: 8,
expected: 16,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := ElapsedTime(tt.layers, tt.time); got != tt.expected {
t.Errorf("ElapsedTime(%d, %d) = %d; want %d", tt.layers, tt.time, got, tt.expected)
}
})
}
}
+35
View File
@@ -0,0 +1,35 @@
{
"authors": [
"nathany"
],
"contributors": [
"alebaffa",
"bitfield",
"ekingery",
"ferhatelmas",
"hilary",
"kytrinyx",
"leenipper",
"petertseng",
"robphoenix",
"sebito91",
"soniakeys",
"tleen",
"eklatzer"
],
"files": {
"solution": [
"raindrops.go"
],
"test": [
"raindrops_test.go",
"cases_test.go"
],
"example": [
".meta/example.go"
]
},
"blurb": "Convert a number into its corresponding raindrop sounds - Pling, Plang and Plong.",
"source": "A variation on FizzBuzz, a famous technical interview question that is intended to weed out potential candidates. That question is itself derived from Fizz Buzz, a popular children's game for teaching division.",
"source_url": "https://en.wikipedia.org/wiki/Fizz_buzz"
}
+1
View File
@@ -0,0 +1 @@
{"track":"go","exercise":"raindrops","id":"4fc80ccd49df464995e301a419919798","url":"https://exercism.org/tracks/go/exercises/raindrops","handle":"sanctushck","is_requester":true,"auto_approve":false}
+41
View File
@@ -0,0 +1,41 @@
# Help
## Running the tests
To run the tests run the command `go test` from within the exercise directory.
If the test suite contains benchmarks, you can run these with the `--bench` and `--benchmem`
flags:
go test -v --bench . --benchmem
Keep in mind that each reviewer will run benchmarks on a different machine, with
different specs, so the results from these benchmark tests may vary.
## Submitting your solution
You can submit your solution using the `exercism submit raindrops.go` command.
This command will upload your solution to the Exercism website and print the solution page's URL.
It's possible to submit an incomplete solution which allows you to:
- See how others have completed the exercise
- Request help from a mentor
## Need to get help?
If you'd like help solving the exercise, check the following pages:
- The [Go track's documentation](https://exercism.org/docs/tracks/go)
- The [Go track's programming category on the forum](https://forum.exercism.org/c/programming/go)
- [Exercism's programming category on the forum](https://forum.exercism.org/c/programming/5)
- The [Frequently Asked Questions](https://exercism.org/docs/using/faqs)
Should those resources not suffice, you could submit your (incomplete) solution to request mentoring.
To get help if you're having trouble, you can use one of the following resources:
- [How to Write Go Code](https://golang.org/doc/code.html)
- [Effective Go](https://golang.org/doc/effective_go.html)
- [Go Resources](http://golang.org/help)
- [StackOverflow](http://stackoverflow.com/questions/tagged/go)
+59
View File
@@ -0,0 +1,59 @@
# Raindrops
Welcome to Raindrops on Exercism's Go Track.
If you need help running the tests or submitting your code, check out `HELP.md`.
## Introduction
Raindrops is a slightly more complex version of the FizzBuzz challenge, a classic interview question.
## Instructions
Your task is to convert a number into its corresponding raindrop sounds.
If a given number:
- is divisible by 3, add "Pling" to the result.
- is divisible by 5, add "Plang" to the result.
- is divisible by 7, add "Plong" to the result.
- **is not** divisible by 3, 5, or 7, the result should be the number as a string.
## Examples
- 28 is divisible by 7, but not 3 or 5, so the result would be `"Plong"`.
- 30 is divisible by 3 and 5, but not 7, so the result would be `"PlingPlang"`.
- 34 is not divisible by 3, 5, or 7, so the result would be `"34"`.
~~~~exercism/note
A common way to test if one number is evenly divisible by another is to compare the [remainder][remainder] or [modulus][modulo] to zero.
Most languages provide operators or functions for one (or both) of these.
[remainder]: https://exercism.org/docs/programming/operators/remainder
[modulo]: https://en.wikipedia.org/wiki/Modulo_operation
~~~~
## Source
### Created by
- @nathany
### Contributed to by
- @alebaffa
- @bitfield
- @ekingery
- @ferhatelmas
- @hilary
- @kytrinyx
- @leenipper
- @petertseng
- @robphoenix
- @sebito91
- @soniakeys
- @tleen
- @eklatzer
### Based on
A variation on FizzBuzz, a famous technical interview question that is intended to weed out potential candidates. That question is itself derived from Fizz Buzz, a popular children's game for teaching division. - https://en.wikipedia.org/wiki/Fizz_buzz
+105
View File
@@ -0,0 +1,105 @@
package raindrops
// This is an auto-generated file. Do not change it manually. Run the generator to update the file.
// See https://github.com/exercism/go#synchronizing-tests-and-instructions
// Source: exercism/problem-specifications
// Commit: 25c2ae5 build(deps): bump fast-uri from 3.1.0 to 3.1.2 (#2653)
type testCase struct {
description string
input int
expected string
}
var testCases = []testCase{
{
description: "the sound for 1 is 1",
input: 1,
expected: "1",
},
{
description: "the sound for 3 is Pling",
input: 3,
expected: "Pling",
},
{
description: "the sound for 5 is Plang",
input: 5,
expected: "Plang",
},
{
description: "the sound for 7 is Plong",
input: 7,
expected: "Plong",
},
{
description: "the sound for 6 is Pling as it has a factor 3",
input: 6,
expected: "Pling",
},
{
description: "2 to the power 3 does not make a raindrop sound as 3 is the exponent not the base",
input: 8,
expected: "8",
},
{
description: "the sound for 9 is Pling as it has a factor 3",
input: 9,
expected: "Pling",
},
{
description: "the sound for 10 is Plang as it has a factor 5",
input: 10,
expected: "Plang",
},
{
description: "the sound for 14 is Plong as it has a factor of 7",
input: 14,
expected: "Plong",
},
{
description: "the sound for 15 is PlingPlang as it has factors 3 and 5",
input: 15,
expected: "PlingPlang",
},
{
description: "the sound for 21 is PlingPlong as it has factors 3 and 7",
input: 21,
expected: "PlingPlong",
},
{
description: "the sound for 25 is Plang as it has a factor 5",
input: 25,
expected: "Plang",
},
{
description: "the sound for 27 is Pling as it has a factor 3",
input: 27,
expected: "Pling",
},
{
description: "the sound for 35 is PlangPlong as it has factors 5 and 7",
input: 35,
expected: "PlangPlong",
},
{
description: "the sound for 49 is Plong as it has a factor 7",
input: 49,
expected: "Plong",
},
{
description: "the sound for 52 is 52",
input: 52,
expected: "52",
},
{
description: "the sound for 105 is PlingPlangPlong as it has factors 3, 5 and 7",
input: 105,
expected: "PlingPlangPlong",
},
{
description: "the sound for 3125 is Plang as it has a factor 5",
input: 3125,
expected: "Plang",
},
}
+3
View File
@@ -0,0 +1,3 @@
module raindrops
go 1.26
+8
View File
@@ -0,0 +1,8 @@
package raindrops
func Convert(number int) string {
var NumberAsString = ""
var OutputString = ""
if ()
panic("Please implement the Convert function")
}
+21
View File
@@ -0,0 +1,21 @@
package raindrops
import "testing"
func TestConvert(t *testing.T) {
for _, tc := range testCases {
t.Run(tc.description, func(t *testing.T) {
if actual := Convert(tc.input); actual != tc.expected {
t.Fatalf("Convert(%d) = %q, want: %q", tc.input, actual, tc.expected)
}
})
}
}
func BenchmarkConvert(b *testing.B) {
for b.Loop() {
for _, test := range testCases {
Convert(test.input)
}
}
}
+24
View File
@@ -0,0 +1,24 @@
{
"authors": [
"nikimanoledaki",
"micuffaro"
],
"files": {
"solution": [
"weather_forecast.go"
],
"test": [
"weather_forecast_test.go"
],
"exemplar": [
".meta/exemplar.go"
],
"invalidator": [
"go.mod"
]
},
"blurb": "Learn about comments by helping a weather station manage their weather forecasting program.",
"custom": {
"taskIdsEnabled": false
}
}
@@ -0,0 +1 @@
{"track":"go","exercise":"weather-forecast","id":"a9e0603772514be1b32ccb5505fce949","url":"https://exercism.org/tracks/go/exercises/weather-forecast","handle":"sanctushck","is_requester":true,"auto_approve":false}
+41
View File
@@ -0,0 +1,41 @@
# Help
## Running the tests
To run the tests run the command `go test` from within the exercise directory.
If the test suite contains benchmarks, you can run these with the `--bench` and `--benchmem`
flags:
go test -v --bench . --benchmem
Keep in mind that each reviewer will run benchmarks on a different machine, with
different specs, so the results from these benchmark tests may vary.
## Submitting your solution
You can submit your solution using the `exercism submit weather_forecast.go` command.
This command will upload your solution to the Exercism website and print the solution page's URL.
It's possible to submit an incomplete solution which allows you to:
- See how others have completed the exercise
- Request help from a mentor
## Need to get help?
If you'd like help solving the exercise, check the following pages:
- The [Go track's documentation](https://exercism.org/docs/tracks/go)
- The [Go track's programming category on the forum](https://forum.exercism.org/c/programming/go)
- [Exercism's programming category on the forum](https://forum.exercism.org/c/programming/5)
- The [Frequently Asked Questions](https://exercism.org/docs/using/faqs)
Should those resources not suffice, you could submit your (incomplete) solution to request mentoring.
To get help if you're having trouble, you can use one of the following resources:
- [How to Write Go Code](https://golang.org/doc/code.html)
- [Effective Go](https://golang.org/doc/effective_go.html)
- [Go Resources](http://golang.org/help)
- [StackOverflow](http://stackoverflow.com/questions/tagged/go)
+20
View File
@@ -0,0 +1,20 @@
# Hints
## General
- A [documentation comment][comment] should be written directly before the entity that it is describing, start with the name of what it is describing, take the form of a sentence, and end with a period.
## 1. Document package weather
- The [package comment][comment] should be written directly before the package, start with `Package x`, and end with a period.
## 2. Document the CurrentCondition and CurrentLocation variables
- The [variable comment][variable comment] should be written right before the variable that it is describing, start with its name, and end with a period.
## 3. Document the Forecast() function
- The [function comment][comment] should come directly before the function, start with the name of the function and end with a period.
[comment]: https://golang.org/doc/effective_go.html#commentary
[variable comment]: https://dave.cheney.net/practical-go/presentations/qcon-china.html#_comments
+66
View File
@@ -0,0 +1,66 @@
# Weather Forecast
Welcome to Weather Forecast on Exercism's Go Track.
If you need help running the tests or submitting your code, check out `HELP.md`.
If you get stuck on the exercise, check out `HINTS.md`, but try and solve it without using those first :)
## Introduction
In the previous exercise, we saw that there are two ways to write comments in Go: single-line comments that are preceded by `//`, and multiline comment blocks that are wrapped with `/*` and `*/`.
## Documentation comments
In Go, comments play an important role in documenting code. They are used by the `godoc` command, which extracts these comments to create documentation about Go packages. A documentation comment should be a complete sentence that starts with the name of the thing being described and ends with a period.
Comments should precede packages as well as exported identifiers, for example exported functions, methods, package variables, constants, and structs, which you will learn more about in the next exercises.
A package-level variable can look like this:
```go
// TemperatureCelsius represents a certain temperature in degrees Celsius.
var TemperatureCelsius float64
```
## Package comments
Package comments should be written directly before a package clause (`package x`) and begin with `Package x ...` like this:
```go
// Package kelvin provides tools to convert
// temperatures to and from Kelvin.
package kelvin
```
## Function comments
A function comment should be written directly before the function declaration. It should be a full sentence that starts with the function name. For example, an exported comment for the function `Calculate` should take the form `Calculate ...`. It should also explain what arguments the function takes, what it does with them, and what its return values mean, ending in a period):
```go
// CelsiusFreezingTemp returns an integer value equal to the temperature at which water freezes in degrees Celsius.
func CelsiusFreezingTemp() int {
return 0
}
```
## Instructions
Goblinocus is a country that takes its weather forecast very seriously. Since you are a renowned, responsible and proficient developer, they asked you to write a program that can forecast the current weather condition of various cities in Goblinocus. You were busy at the time and asked one of your friends to do the job instead. After a while, the president of Goblinocus contacted you and said they do not understand your friend's code. When you check the code, you discover that your friend did not act as a responsible programmer and there are no comments in the code. You feel obligated to clarify the program so goblins can understand them as well.
## 1. Document package weather
Since goblins are not as smart as you are, they forgot what the package should do for them. Please write a comment for `package weather` that describes its contents. The package comment should introduce the package and provide information relevant to the package as a whole.
## 2. Document the CurrentCondition and CurrentLocation variables
The president of Goblinocus is a bit paranoid and fears uncommented variables are used to destroy their country. Please clarify the usage of the package variables `CurrentCondition` and `CurrentLocation` and put the president's mind at ease. This should tell any user of the package what information the variables store, and what they can do with it.
## 3. Document the Forecast() function
Goblinocus forecast operators want to know what the `Forecast()` function does (but do not tell them how it works, since unfortunately, they will get more confused). Please write a comment for this function that describes what the function does, but not how it does it.
## Source
### Created by
- @nikimanoledaki
- @micuffaro
+3
View File
@@ -0,0 +1,3 @@
module weather
go 1.18
+13
View File
@@ -0,0 +1,13 @@
// Package weather provides tools to help in weather forecast.
package weather
// CurrentCondition represents the current weather condition.
var CurrentCondition string
// CurrentLocation represents the current location to get weather information.
var CurrentLocation string
// Forecast returns information about the weather in the given location.
func Forecast(city, condition string) string {
CurrentLocation, CurrentCondition = city, condition
return CurrentLocation + " - current weather condition: " + CurrentCondition
}
@@ -0,0 +1,140 @@
package weather
import (
"fmt"
"go/ast"
"go/parser"
"go/token"
"strings"
"testing"
)
func TestComments(t *testing.T) {
filename := "weather_forecast.go"
fs := token.NewFileSet()
f, err := parser.ParseFile(fs, filename, nil, parser.ParseComments)
if err != nil {
t.Fatal(err)
}
wantedComments := 4
got := len(f.Comments)
if got != wantedComments {
t.Errorf("Incorrect number of comments: got %d, want %d", got, wantedComments)
}
testPackageComment(t, f)
ast.Inspect(f, func(node ast.Node) bool {
switch n := node.(type) {
case *ast.GenDecl:
if n.Lparen.IsValid() {
for _, v := range n.Specs {
testBlockIdentifierComment(t, v.(*ast.ValueSpec))
}
} else {
testIdentifierComment(t, n)
}
case *ast.FuncDecl:
testFunctionComment(t, n)
}
return true
})
}
func testPackageComment(t *testing.T, node *ast.File) {
t.Helper()
if node.Doc == nil {
t.Errorf("Package weather should have a comment")
}
packageName := node.Name.Name
want := "Package " + packageName
packageComment := node.Doc.Text()
if ok, errStr := testComment("Package", packageName, packageComment, want); !ok {
t.Error(errStr)
}
}
func testIdentifierComment(t *testing.T, node *ast.GenDecl) {
t.Helper()
identifierName := node.Specs[0].(*ast.ValueSpec).Names[0].Name
if node.Doc == nil {
t.Errorf("Exported identifier %s should have a comment", identifierName)
}
identifierComment := node.Doc.Text()
want := identifierName
if ok, errStr := testComment("Variable", identifierName, identifierComment, want); !ok {
t.Error(errStr)
}
}
func testBlockIdentifierComment(t *testing.T, node *ast.ValueSpec) {
t.Helper()
identifierName := node.Names[0].Name
if node.Doc == nil {
t.Errorf("Exported identifier %s should have a comment", identifierName)
}
identifierComment := node.Doc.Text()
want := identifierName
if ok, errStr := testComment("Variable", identifierName, identifierComment, want); !ok {
t.Error(errStr)
}
}
func testFunctionComment(t *testing.T, node *ast.FuncDecl) {
t.Helper()
funcName := node.Name.Name
if node.Doc == nil {
t.Errorf("Exported function %s() should have a comment", funcName)
}
funcComment := node.Doc.Text()
want := funcName
if ok, errStr := testComment("Function", funcName, funcComment, want); !ok {
t.Error(errStr)
}
}
func testComment(entityKind, entityName, comment, wantedPrefix string) (ok bool, errString string) {
trimmedComment := strings.TrimSpace(comment)
lowerEntity := strings.ToLower(entityKind)
// Check if comment has wanted prefix
if !strings.HasPrefix(trimmedComment, wantedPrefix) {
errorString := fmt.Sprintf("%s comment for %s '%s' should start with '// %s ...': got '// %s'",
entityKind, lowerEntity, entityName, wantedPrefix, trimmedComment)
return false, errorString
}
// Check if comment content is empty
commentContent := strings.TrimPrefix(trimmedComment, wantedPrefix)
commentContent = strings.TrimSpace(commentContent)
commentContent = strings.TrimSuffix(commentContent, ".")
if commentContent == "" {
lowerEntity := strings.ToLower(entityKind)
errorString := fmt.Sprintf("%s comment of '%s' should provide a description of the %s, e.g '// %s <%s_description>'",
entityKind, entityName, lowerEntity, wantedPrefix, lowerEntity)
return false, errorString
}
// Check if comment ends in a period
if !strings.HasSuffix(trimmedComment, ".") {
return false, fmt.Sprintf("%s comment for %s '%s' should end with a period (.)",
entityKind, lowerEntity, entityName)
}
return true, ""
}