Initial upload

This commit is contained in:
2022-08-24 14:28:45 +02:00
parent c67653ddee
commit 57bc7b0289
370 changed files with 18479 additions and 0 deletions

View File

@@ -0,0 +1 @@
{"track":"julia","exercise":"binary-search","id":"ce0cd3b336094a49af31b3ed09f02bee","url":"https://exercism.io/my/solutions/ce0cd3b336094a49af31b3ed09f02bee","handle":"halfdan","is_requester":true,"auto_approve":false}

View File

@@ -0,0 +1,51 @@
# Binary Search
Implement a binary search algorithm.
Searching a sorted collection is a common task. A dictionary is a sorted
list of word definitions. Given a word, one can find its definition. A
telephone book is a sorted list of people's names, addresses, and
telephone numbers. Knowing someone's name allows one to quickly find
their telephone number and address.
If the list to be searched contains more than a few items (a dozen, say)
a binary search will require far fewer comparisons than a linear search,
but it imposes the requirement that the list be sorted.
In computer science, a binary search or half-interval search algorithm
finds the position of a specified input value (the search "key") within
an array sorted by key value.
In each step, the algorithm compares the search key value with the key
value of the middle element of the array.
If the keys match, then a matching element has been found and the range of indices that equal the search key value are returned.
Otherwise, if the search key is less than the middle element's key, then
the algorithm repeats its action on the sub-array to the left of the
middle element or, if the search key is greater, on the sub-array to the
right.
If the remaining array to be searched is empty, then the key cannot be
found in the array and a special "not found" indication is returned. Search methods in Julia typically return an empty range located at the insertion point in this case.
A binary search halves the number of items to check with each iteration,
so locating an item (or determining its absence) takes logarithmic time.
A binary search is a dichotomic divide and conquer search algorithm.
**For simplification, you can assume that all elements of the list to be searched are unique.** Feel free to implement a solution that works on lists with non-unique elements as a bonus task.
## Bonus task
Implement keyword arguments `by`, `lt` and `rev` so that `by` specifies a transformation applied to all elements of the list, `lt` specifies a comparison and `rev` specifies if the list is ordered in reverse.
## Source
Wikipedia [http://en.wikipedia.org/wiki/Binary_search_algorithm](http://en.wikipedia.org/wiki/Binary_search_algorithm)
Some phrases above and the bonus tasks are taken from the [Julia base documentation (MIT license)](https://docs.julialang.org/en/v1/base/sort/#Base.Sort.searchsorted) of `searchsorted`.
## Version compatibility
This exercise has been tested on Julia versions >=1.0.
## Submitting Incomplete Solutions
It's possible to submit an incomplete solution so you can see how others have completed the exercise.

View File

@@ -0,0 +1,68 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": ["# Binary Search\n", "\n", "Implement a binary search algorithm.\n", "\n", "Searching a sorted collection is a common task. A dictionary is a sorted\n", "list of word definitions. Given a word, one can find its definition. A\n", "telephone book is a sorted list of people's names, addresses, and\n", "telephone numbers. Knowing someone's name allows one to quickly find\n", "their telephone number and address.\n", "\n", "If the list to be searched contains more than a few items (a dozen, say)\n", "a binary search will require far fewer comparisons than a linear search,\n", "but it imposes the requirement that the list be sorted.\n", "\n", "In computer science, a binary search or half-interval search algorithm\n", "finds the position of a specified input value (the search \"key\") within\n", "an array sorted by key value.\n", "\n", "In each step, the algorithm compares the search key value with the key\n", "value of the middle element of the array.\n", "\n", "If the keys match, then a matching element has been found and the range of indices that equal the search key value are returned.\n", "\n", "Otherwise, if the search key is less than the middle element's key, then\n", "the algorithm repeats its action on the sub-array to the left of the\n", "middle element or, if the search key is greater, on the sub-array to the\n", "right.\n", "\n", "If the remaining array to be searched is empty, then the key cannot be\n", "found in the array and a special \"not found\" indication is returned. Search methods in Julia typically return an empty range located at the insertion point in this case.\n", "\n", "A binary search halves the number of items to check with each iteration,\n", "so locating an item (or determining its absence) takes logarithmic time.\n", "A binary search is a dichotomic divide and conquer search algorithm.\n", "\n", "**For simplification, you can assume that all elements of the list to be searched are unique.** Feel free to implement a solution that works on lists with non-unique elements as a bonus task.\n", "\n", "## Bonus task\n", "Implement keyword arguments `by`, `lt` and `rev` so that `by` specifies a transformation applied to all elements of the list, `lt` specifies a comparison and `rev` specifies if the list is ordered in reverse.\n", "\n", "## Source\n", "\n", "Wikipedia [http://en.wikipedia.org/wiki/Binary_search_algorithm](http://en.wikipedia.org/wiki/Binary_search_algorithm)\n", "\n", "Some phrases above and the bonus tasks are taken from the [Julia base documentation (MIT license)](https://docs.julialang.org/en/v1/base/sort/#Base.Sort.searchsorted) of `searchsorted`.\n", "\n", "## Version compatibility\n", "This exercise has been tested on Julia versions >=1.0.\n", "\n", "## Submitting Incomplete Solutions\n", "It's possible to submit an incomplete solution so you can see how others have completed the exercise."]
},
{
"cell_type": "markdown",
"metadata": {},
"source": ["## Your solution"]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": ["# submit"]
},
{
"cell_type": "markdown",
"metadata": {},
"source": ["## Test suite"]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": ["using Test\n", "\n", "# include(\"binary-search.jl\")\n", "\n", "@testset \"default binary search\" begin\n", " @testset \"value in array\" begin\n", " @test binarysearch([6], 6) == 1:1\n", " @test binarysearch([1, 3, 4, 6, 8, 9, 11], 6) == 4:4\n", " @test binarysearch([1, 3, 4, 6, 8, 9, 11], 1) == 1:1\n", " @test binarysearch([1, 3, 4, 6, 8, 9, 11], 11) == 7:7\n", " @test binarysearch([1, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 634], 144) == 10:10\n", " @test binarysearch([1, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377], 21) == 6:6\n", " end\n", " @testset \"value not in array\" begin\n", " @test binarysearch([1, 3, 4, 6, 8, 9, 11], 7) == 5:4\n", " @test binarysearch([1, 3, 4, 6, 8, 9, 11], 0) == 1:0\n", " @test binarysearch([1, 3, 4, 6, 8, 9, 11], 13) == 8:7\n", " @test binarysearch([], 1) == 1:0\n", " @test binarysearch([1, 2], 0) == 1:0\n", " end\n", "end\n", "\n", "@testset \"bonus tasks\" begin\n", " @testset \"reverse search\" begin\n", " @testset \"value in array\" begin\n", " @test_skip binarysearch([6], 6, rev = true) == 1:1\n", " @test_skip binarysearch([11, 9, 8, 6, 4, 3, 1], 6, rev = true) == 4:4\n", " @test_skip binarysearch([11, 9, 8, 6, 4, 3, 1], 1, rev = true) == 7:7\n", " @test_skip binarysearch([11, 9, 8, 6, 4, 3, 1], 11, rev = true) == 1:1\n", " @test_skip binarysearch([634, 377, 233, 144, 89, 55, 34, 21, 13, 8, 5, 3, 1], 144, rev = true) == 4:4\n", " @test_skip binarysearch([377, 233, 144, 89, 55, 34, 21, 13, 8, 5, 3, 1], 21, rev = true) == 7:7\n", " end\n", " @testset \"value not in array\" begin\n", " @test_skip binarysearch([11, 9, 8, 6, 4, 3, 1], 7, rev = true) == 4:3\n", " @test_skip binarysearch([11, 9, 8, 6, 4, 3, 1], 0, rev = true) == 8:7\n", " @test_skip binarysearch([11, 9, 8, 6, 4, 3, 1], 13, rev = true) == 1:0\n", " @test_skip binarysearch([], 1, rev = true) == 1:0\n", " end\n", " end\n", "\n", " @testset \"apply transformation\" begin\n", " @testset \"value in array\" begin\n", " @test_skip binarysearch([5.5], 6, by = round) == 1:1\n", " @test_skip binarysearch([1.1, 2.9, 4.4, 5.5, 8.1, 9.0, 10.8], 6, by = round) == 4:4\n", " @test_skip binarysearch([1.1, 2.9, 4.4, 5.5, 8.1, 9.0, 10.8], 1, by = round) == 1:1\n", " @test_skip binarysearch([1.1, 2.9, 4.4, 5.5, 8.1, 9.0, 10.8], 11, by = round) == 7:7\n", " @test_skip binarysearch([1.1, 2.9, 4.4, 5.5, 8.1, 9.0, 10.8], 11, by = abs2∘round) == 7:7\n", " @test_skip binarysearch([1, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 634], 144.4, by = round) == 10:10\n", " @test_skip binarysearch([1, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377], 20.6, by = round) == 6:6\n", " end\n", " @testset \"value not in array\" begin\n", " @test_skip binarysearch([1.1, 2.9, 4.4, 5.5, 8.1, 9.0, 10.8], 7, by = round) == 5:4\n", " @test_skip binarysearch([1.1, 2.9, 4.4, 5.5, 8.1, 9.0, 10.8], 0, by = round) == 1:0\n", " @test_skip binarysearch([1.1, 2.9, 4.4, 5.5, 8.1, 9.0, 10.8], 13, by = round) == 8:7\n", " @test_skip binarysearch([], 1, by = round) == 1:0\n", " end\n", " end\n", "\n", " @testset \"compare with > instead of <\" begin\n", " # this is equivalent to searching in reverse order\n", " @testset \"value in array\" begin\n", " @test_skip binarysearch([6], 6, lt = >) == 1:1\n", " @test_skip binarysearch([11, 9, 8, 6, 4, 3, 1], 6, lt = >) == 4:4\n", " @test_skip binarysearch([11, 9, 8, 6, 4, 3, 1], 1, lt = >) == 7:7\n", " @test_skip binarysearch([11, 9, 8, 6, 4, 3, 1], 11, lt = >) == 1:1\n", " @test_skip binarysearch([634, 377, 233, 144, 89, 55, 34, 21, 13, 8, 5, 3, 1], 144, lt = >) == 4:4\n", " @test_skip binarysearch([377, 233, 144, 89, 55, 34, 21, 13, 8, 5, 3, 1], 21, lt = >) == 7:7\n", " end\n", " @testset \"value not in array\" begin\n", " @test_skip binarysearch([11, 9, 8, 6, 4, 3, 1], 7, lt = >) == 4:3\n", " @test_skip binarysearch([11, 9, 8, 6, 4, 3, 1], 0, lt = >) == 8:7\n", " @test_skip binarysearch([11, 9, 8, 6, 4, 3, 1], 13, lt = >) == 1:0\n", " @test_skip binarysearch([], 1, lt = >) == 1:0\n", " end\n", " end\n", "end"]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Prepare submission\n",
"To submit your exercise, you need to save your solution in a file called `binary-search.jl` before using the CLI.\n",
"You can either create it manually or use the following functions, which will automatically write every notebook cell that starts with `# submit` to the file `binary-search.jl`.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# using Pkg; Pkg.add(\"Exercism\")\n",
"# using Exercism\n",
"# Exercism.create_submission(\"binary-search\")"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Julia 1.3.0",
"language": "julia",
"name": "julia-1.3"
},
"language_info": {
"file_extension": ".jl",
"mimetype": "application/julia",
"name": "julia",
"version": "1.3.0"
}
},
"nbformat": 4,
"nbformat_minor": 2
}

View File

@@ -0,0 +1,14 @@
function binarysearch(haystack, needle)
lo, hi = 1, length(haystack)
while lo <= hi
idx = Int(floor((hi + lo ) / 2))
if needle > haystack[idx]
lo = idx + 1
elseif needle < haystack[idx]
hi = idx - 1
else
return idx:idx
end
end
lo:hi
end

View File

@@ -0,0 +1,76 @@
using Test
include("binary-search.jl")
@testset "default binary search" begin
@testset "value in array" begin
@test binarysearch([6], 6) == 1:1
@test binarysearch([1, 3, 4, 6, 8, 9, 11], 6) == 4:4
@test binarysearch([1, 3, 4, 6, 8, 9, 11], 1) == 1:1
@test binarysearch([1, 3, 4, 6, 8, 9, 11], 11) == 7:7
@test binarysearch([1, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 634], 144) == 10:10
@test binarysearch([1, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377], 21) == 6:6
end
@testset "value not in array" begin
@test binarysearch([1, 3, 4, 6, 8, 9, 11], 7) == 5:4
@test binarysearch([1, 3, 4, 6, 8, 9, 11], 0) == 1:0
@test binarysearch([1, 3, 4, 6, 8, 9, 11], 13) == 8:7
@test binarysearch([], 1) == 1:0
@test binarysearch([1, 2], 0) == 1:0
end
end
@testset "bonus tasks" begin
@testset "reverse search" begin
@testset "value in array" begin
@test_skip binarysearch([6], 6, rev = true) == 1:1
@test_skip binarysearch([11, 9, 8, 6, 4, 3, 1], 6, rev = true) == 4:4
@test_skip binarysearch([11, 9, 8, 6, 4, 3, 1], 1, rev = true) == 7:7
@test_skip binarysearch([11, 9, 8, 6, 4, 3, 1], 11, rev = true) == 1:1
@test_skip binarysearch([634, 377, 233, 144, 89, 55, 34, 21, 13, 8, 5, 3, 1], 144, rev = true) == 4:4
@test_skip binarysearch([377, 233, 144, 89, 55, 34, 21, 13, 8, 5, 3, 1], 21, rev = true) == 7:7
end
@testset "value not in array" begin
@test_skip binarysearch([11, 9, 8, 6, 4, 3, 1], 7, rev = true) == 4:3
@test_skip binarysearch([11, 9, 8, 6, 4, 3, 1], 0, rev = true) == 8:7
@test_skip binarysearch([11, 9, 8, 6, 4, 3, 1], 13, rev = true) == 1:0
@test_skip binarysearch([], 1, rev = true) == 1:0
end
end
@testset "apply transformation" begin
@testset "value in array" begin
@test_skip binarysearch([5.5], 6, by = round) == 1:1
@test_skip binarysearch([1.1, 2.9, 4.4, 5.5, 8.1, 9.0, 10.8], 6, by = round) == 4:4
@test_skip binarysearch([1.1, 2.9, 4.4, 5.5, 8.1, 9.0, 10.8], 1, by = round) == 1:1
@test_skip binarysearch([1.1, 2.9, 4.4, 5.5, 8.1, 9.0, 10.8], 11, by = round) == 7:7
@test_skip binarysearch([1.1, 2.9, 4.4, 5.5, 8.1, 9.0, 10.8], 11, by = abs2∘round) == 7:7
@test_skip binarysearch([1, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 634], 144.4, by = round) == 10:10
@test_skip binarysearch([1, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377], 20.6, by = round) == 6:6
end
@testset "value not in array" begin
@test_skip binarysearch([1.1, 2.9, 4.4, 5.5, 8.1, 9.0, 10.8], 7, by = round) == 5:4
@test_skip binarysearch([1.1, 2.9, 4.4, 5.5, 8.1, 9.0, 10.8], 0, by = round) == 1:0
@test_skip binarysearch([1.1, 2.9, 4.4, 5.5, 8.1, 9.0, 10.8], 13, by = round) == 8:7
@test_skip binarysearch([], 1, by = round) == 1:0
end
end
@testset "compare with > instead of <" begin
# this is equivalent to searching in reverse order
@testset "value in array" begin
@test_skip binarysearch([6], 6, lt = >) == 1:1
@test_skip binarysearch([11, 9, 8, 6, 4, 3, 1], 6, lt = >) == 4:4
@test_skip binarysearch([11, 9, 8, 6, 4, 3, 1], 1, lt = >) == 7:7
@test_skip binarysearch([11, 9, 8, 6, 4, 3, 1], 11, lt = >) == 1:1
@test_skip binarysearch([634, 377, 233, 144, 89, 55, 34, 21, 13, 8, 5, 3, 1], 144, lt = >) == 4:4
@test_skip binarysearch([377, 233, 144, 89, 55, 34, 21, 13, 8, 5, 3, 1], 21, lt = >) == 7:7
end
@testset "value not in array" begin
@test_skip binarysearch([11, 9, 8, 6, 4, 3, 1], 7, lt = >) == 4:3
@test_skip binarysearch([11, 9, 8, 6, 4, 3, 1], 0, lt = >) == 8:7
@test_skip binarysearch([11, 9, 8, 6, 4, 3, 1], 13, lt = >) == 1:0
@test_skip binarysearch([], 1, lt = >) == 1:0
end
end
end

View File

@@ -0,0 +1 @@
{"track":"julia","exercise":"minesweeper","id":"a839588890684ea89e338552c20ab03a","url":"https://exercism.io/my/solutions/a839588890684ea89e338552c20ab03a","handle":"halfdan","is_requester":true,"auto_approve":false}

View File

@@ -0,0 +1,43 @@
# Minesweeper
Add the mine counts to a completed Minesweeper board.
Minesweeper is a popular game where the user has to find the mines using
numeric hints that indicate how many mines are directly adjacent
(horizontally, vertically, diagonally) to a square.
In this exercise you have to create some code that counts the number of
mines adjacent to a given empty square and replaces that square with the
count.
The board is a rectangle composed of blank space (' ') characters. A mine
is represented by an asterisk ('\*') character.
If a given space has no adjacent mines at all, leave that square blank.
## Examples
For example you may receive a 5 x 4 board like this (empty spaces are
represented here with the '·' character for display on screen):
```
·*·*·
··*··
··*··
·····
```
And your code will transform it into this:
```
1*3*1
13*31
·2*2·
·111·
```
## Version compatibility
This exercise has been tested on Julia versions >=1.0.
## Submitting Incomplete Solutions
It's possible to submit an incomplete solution so you can see how others have completed the exercise.

View File

@@ -0,0 +1,68 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": ["# Minesweeper\n", "\n", "Add the mine counts to a completed Minesweeper board.\n", "\n", "Minesweeper is a popular game where the user has to find the mines using\n", "numeric hints that indicate how many mines are directly adjacent\n", "(horizontally, vertically, diagonally) to a square.\n", "\n", "In this exercise you have to create some code that counts the number of\n", "mines adjacent to a given empty square and replaces that square with the\n", "count.\n", "\n", "The board is a rectangle composed of blank space (' ') characters. A mine\n", "is represented by an asterisk ('\\*') character.\n", "\n", "If a given space has no adjacent mines at all, leave that square blank.\n", "\n", "## Examples\n", "\n", "For example you may receive a 5 x 4 board like this (empty spaces are\n", "represented here with the '·' character for display on screen):\n", "\n", "```\n", "·*·*·\n", "··*··\n", "··*··\n", "·····\n", "```\n", "\n", "And your code will transform it into this:\n", "\n", "```\n", "1*3*1\n", "13*31\n", "·2*2·\n", "·111·\n", "```\n", "\n", "## Version compatibility\n", "This exercise has been tested on Julia versions >=1.0.\n", "\n", "## Submitting Incomplete Solutions\n", "It's possible to submit an incomplete solution so you can see how others have completed the exercise."]
},
{
"cell_type": "markdown",
"metadata": {},
"source": ["## Your solution"]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": ["# submit"]
},
{
"cell_type": "markdown",
"metadata": {},
"source": ["## Test suite"]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": ["using Test\n", "\n", "# include(\"minesweeper.jl\")\n", "\n", "@testset \"no rows\" begin\n", " @test annotate([]) == []\n", "end\n", "\n", "@testset \"no columns\" begin\n", " @test annotate([\"\"]) == [\"\"]\n", "end\n", "\n", "@testset \"no mines\" begin\n", " minefield = [\" \",\n", " \" \",\n", " \" \"]\n", " out = [\" \",\n", " \" \",\n", " \" \"]\n", " @test annotate(minefield) == out\n", "end\n", "\n", "@testset \"minefield only mines\" begin\n", " minefield = [\"***\",\n", " \"***\",\n", " \"***\"]\n", " out = [\"***\",\n", " \"***\",\n", " \"***\"]\n", " @test annotate(minefield) == out\n", "end\n", "\n", "@testset \"mine surrounded by spaces\" begin\n", " minefield = [\" \",\n", " \" * \",\n", " \" \"]\n", " out = [\"111\",\n", " \"1*1\",\n", " \"111\"]\n", " @test annotate(minefield) == out\n", "end\n", "\n", "@testset \"space surrounded by mines\" begin\n", " minefield = [\"***\",\n", " \"* *\",\n", " \"***\"]\n", " out = [\"***\",\n", " \"*8*\",\n", " \"***\"]\n", " @test annotate(minefield) == out\n", "end\n", "\n", "@testset \"horizontal line\" begin\n", " minefield = [\" * * \"]\n", " out = [\"1*2*1\"]\n", " @test annotate(minefield) == out\n", "end\n", "\n", "@testset \"horizontal line mines at edges\" begin\n", " minefield = [\"* *\"]\n", " out = [\"*1 1*\"]\n", " @test annotate(minefield) == out\n", "end\n", "\n", "@testset \"vertical line\" begin\n", " minefield = [\" \",\n", " \"*\",\n", " \" \",\n", " \"*\",\n", " \" \"]\n", " out = [\"1\",\n", " \"*\",\n", " \"2\",\n", " \"*\",\n", " \"1\"]\n", " @test annotate(minefield) == out\n", "end\n", "\n", "@testset \"vertical line mines at edges\" begin\n", " minefield = [\"*\",\n", " \" \",\n", " \" \",\n", " \" \",\n", " \"*\"]\n", " out = [\"*\",\n", " \"1\",\n", " \" \",\n", " \"1\",\n", " \"*\"]\n", " @test annotate(minefield) == out\n", "end\n", "\n", "@testset \"cross\" begin\n", " minefield = [\" * \",\n", " \" * \",\n", " \"*****\",\n", " \" * \",\n", " \" * \"]\n", " out = [\" 2*2 \",\n", " \"25*52\",\n", " \"*****\",\n", " \"25*52\",\n", " \" 2*2 \"]\n", " @test annotate(minefield) == out\n", "end\n", "\n", "@testset \"large minefield\" begin\n", " minefield = [\" * * \",\n", " \" * \",\n", " \" * \",\n", " \" * *\",\n", " \" * * \",\n", " \" \"]\n", " out = [\"1*22*1\",\n", " \"12*322\",\n", " \" 123*2\",\n", " \"112*4*\",\n", " \"1*22*2\",\n", " \"111111\"]\n", " @test annotate(minefield) == out\n", "end"]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Prepare submission\n",
"To submit your exercise, you need to save your solution in a file called `minesweeper.jl` before using the CLI.\n",
"You can either create it manually or use the following functions, which will automatically write every notebook cell that starts with `# submit` to the file `minesweeper.jl`.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# using Pkg; Pkg.add(\"Exercism\")\n",
"# using Exercism\n",
"# Exercism.create_submission(\"minesweeper\")"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Julia 1.3.0",
"language": "julia",
"name": "julia-1.3"
},
"language_info": {
"file_extension": ".jl",
"mimetype": "application/julia",
"name": "julia",
"version": "1.3.0"
}
},
"nbformat": 4,
"nbformat_minor": 2
}

View File

@@ -0,0 +1,25 @@
function annotate(field)
afield = []
for x 1:length(field)
line = ""
for y 1:length(field[x])
el = field[x][y]
if el == '*'
line = "$line$el"
continue
end
stars = 0
if x > 1
stars += count(c -> c == '*', field[x - 1][max(y - 1, 1):min(y + 1, length(field[x]))])
end
stars += count(c -> c == '*', field[x][max(y - 1, 1):min(y + 1, length(field[x]))])
if x < length(field)
stars += count(c -> c == '*', field[x + 1][max(y - 1, 1):min(y + 1, length(field[x]))])
end
ch = stars == 0 ? " " : "$stars"
line = "$line$ch"
end
append!(afield, [line])
end
afield
end

View File

@@ -0,0 +1,121 @@
using Test
include("minesweeper.jl")
@testset "no rows" begin
@test annotate([]) == []
end
# @testset "no columns" begin
# @test annotate([""]) == [""]
# end
@testset "no mines" begin
minefield = [" ",
" ",
" "]
out = [" ",
" ",
" "]
@test annotate(minefield) == out
end
@testset "minefield only mines" begin
minefield = ["***",
"***",
"***"]
out = ["***",
"***",
"***"]
@test annotate(minefield) == out
end
@testset "mine surrounded by spaces" begin
minefield = [" ",
" * ",
" "]
out = ["111",
"1*1",
"111"]
@test annotate(minefield) == out
end
@testset "space surrounded by mines" begin
minefield = ["***",
"* *",
"***"]
out = ["***",
"*8*",
"***"]
@test annotate(minefield) == out
end
@testset "horizontal line" begin
minefield = [" * * "]
out = ["1*2*1"]
@test annotate(minefield) == out
end
@testset "horizontal line mines at edges" begin
minefield = ["* *"]
out = ["*1 1*"]
@test annotate(minefield) == out
end
@testset "vertical line" begin
minefield = [" ",
"*",
" ",
"*",
" "]
out = ["1",
"*",
"2",
"*",
"1"]
@test annotate(minefield) == out
end
@testset "vertical line mines at edges" begin
minefield = ["*",
" ",
" ",
" ",
"*"]
out = ["*",
"1",
" ",
"1",
"*"]
@test annotate(minefield) == out
end
@testset "cross" begin
minefield = [" * ",
" * ",
"*****",
" * ",
" * "]
out = [" 2*2 ",
"25*52",
"*****",
"25*52",
" 2*2 "]
@test annotate(minefield) == out
end
@testset "large minefield" begin
minefield = [" * * ",
" * ",
" * ",
" * *",
" * * ",
" "]
out = ["1*22*1",
"12*322",
" 123*2",
"112*4*",
"1*22*2",
"111111"]
@test annotate(minefield) == out
end

View File

@@ -0,0 +1 @@
{"track":"julia","exercise":"pascals-triangle","id":"802dc59e8eb8489f9fa601b08be5a1ac","url":"https://exercism.io/my/solutions/802dc59e8eb8489f9fa601b08be5a1ac","handle":"halfdan","is_requester":true,"auto_approve":false}

View File

@@ -0,0 +1,25 @@
# Pascal's Triangle
Compute Pascal's triangle up to a given number of rows.
In Pascal's Triangle each number is computed by adding the numbers to
the right and left of the current position in the previous row.
```text
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
# ... etc
```
## Source
Pascal's Triangle at Wolfram Math World [http://mathworld.wolfram.com/PascalsTriangle.html](http://mathworld.wolfram.com/PascalsTriangle.html)
## Version compatibility
This exercise has been tested on Julia versions >=1.0.
## Submitting Incomplete Solutions
It's possible to submit an incomplete solution so you can see how others have completed the exercise.

View File

@@ -0,0 +1,68 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": ["# Pascal's Triangle\n", "\n", "Compute Pascal's triangle up to a given number of rows.\n", "\n", "In Pascal's Triangle each number is computed by adding the numbers to\n", "the right and left of the current position in the previous row.\n", "\n", "```text\n", " 1\n", " 1 1\n", " 1 2 1\n", " 1 3 3 1\n", "1 4 6 4 1\n", "# ... etc\n", "```\n", "\n", "## Source\n", "\n", "Pascal's Triangle at Wolfram Math World [http://mathworld.wolfram.com/PascalsTriangle.html](http://mathworld.wolfram.com/PascalsTriangle.html)\n", "\n", "## Version compatibility\n", "This exercise has been tested on Julia versions >=1.0.\n", "\n", "## Submitting Incomplete Solutions\n", "It's possible to submit an incomplete solution so you can see how others have completed the exercise."]
},
{
"cell_type": "markdown",
"metadata": {},
"source": ["## Your solution"]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": ["# submit\n", "function triangle(n)\n", "\n", "end"]
},
{
"cell_type": "markdown",
"metadata": {},
"source": ["## Test suite"]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": ["using Test\n", "\n", "# include(\"pascals-triangle.jl\")\n", "\n", "const rows = [[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1], [1, 5, 10, 10, 5, 1], [1, 6, 15, 20, 15, 6, 1], [1, 7, 21, 35, 35, 21, 7, 1], [1, 8, 28, 56, 70, 56, 28, 8, 1], [1, 9, 36, 84, 126, 126, 84, 36, 9, 1]]\n", "\n", "@testset \"$i row(s)\" for i in eachindex(rows)\n", " @test triangle(i) == @view rows[1:i]\n", "end\n", "\n", "@testset \"special cases\" begin\n", " @test_throws DomainError triangle(-1)\n", " @test isempty(triangle(0))\n", "end"]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Prepare submission\n",
"To submit your exercise, you need to save your solution in a file called `pascals-triangle.jl` before using the CLI.\n",
"You can either create it manually or use the following functions, which will automatically write every notebook cell that starts with `# submit` to the file `pascals-triangle.jl`.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# using Pkg; Pkg.add(\"Exercism\")\n",
"# using Exercism\n",
"# Exercism.create_submission(\"pascals-triangle\")"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Julia 1.3.0",
"language": "julia",
"name": "julia-1.3"
},
"language_info": {
"file_extension": ".jl",
"mimetype": "application/julia",
"name": "julia",
"version": "1.3.0"
}
},
"nbformat": 4,
"nbformat_minor": 2
}

View File

@@ -0,0 +1,9 @@
function triangle(n)
n == 0 && return []
n < 0 && throw(DomainError("Invalid n given"))
rows = [[1]]
for _ 2:n
push!(rows, [a+b for (a,b) zip([0;rows[end]], [rows[end]; 0])])
end
rows
end

View File

@@ -0,0 +1,14 @@
using Test
include("pascals-triangle.jl")
const rows = [[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1], [1, 5, 10, 10, 5, 1], [1, 6, 15, 20, 15, 6, 1], [1, 7, 21, 35, 35, 21, 7, 1], [1, 8, 28, 56, 70, 56, 28, 8, 1], [1, 9, 36, 84, 126, 126, 84, 36, 9, 1]]
@testset "$i row(s)" for i in eachindex(rows)
@test triangle(i) == @view rows[1:i]
end
@testset "special cases" begin
@test_throws DomainError triangle(-1)
@test isempty(triangle(0))
end

View File

@@ -0,0 +1 @@
{"track":"julia","exercise":"perfect-numbers","id":"6aa6745ac14f4533b0a7b20f97053979","url":"https://exercism.io/my/solutions/6aa6745ac14f4533b0a7b20f97053979","handle":"halfdan","is_requester":true,"auto_approve":false}

View File

@@ -0,0 +1,28 @@
# Perfect Numbers
Determine if a number is perfect, abundant, or deficient based on
Nicomachus' (60 - 120 CE) classification scheme for natural numbers.
The Greek mathematician [Nicomachus](https://en.wikipedia.org/wiki/Nicomachus) devised a classification scheme for natural numbers, identifying each as belonging uniquely to the categories of **perfect**, **abundant**, or **deficient** based on their [aliquot sum](https://en.wikipedia.org/wiki/Aliquot_sum). The aliquot sum is defined as the sum of the factors of a number not including the number itself. For example, the aliquot sum of 15 is (1 + 3 + 5) = 9
- **Perfect**: aliquot sum = number
- 6 is a perfect number because (1 + 2 + 3) = 6
- 28 is a perfect number because (1 + 2 + 4 + 7 + 14) = 28
- **Abundant**: aliquot sum > number
- 12 is an abundant number because (1 + 2 + 3 + 4 + 6) = 16
- 24 is an abundant number because (1 + 2 + 3 + 4 + 6 + 8 + 12) = 36
- **Deficient**: aliquot sum < number
- 8 is a deficient number because (1 + 2 + 4) = 7
- Prime numbers are deficient
Implement a way to determine whether a given number is **perfect**, **abundant** or **deficient**.
## Source
Taken from Chapter 2 of Functional Thinking by Neal Ford. [http://shop.oreilly.com/product/0636920029687.do](http://shop.oreilly.com/product/0636920029687.do)
## Version compatibility
This exercise has been tested on Julia versions >=1.0.
## Submitting Incomplete Solutions
It's possible to submit an incomplete solution so you can see how others have completed the exercise.

View File

@@ -0,0 +1,68 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": ["# Perfect Numbers\n", "\n", "Determine if a number is perfect, abundant, or deficient based on\n", "Nicomachus' (60 - 120 CE) classification scheme for natural numbers.\n", "\n", "The Greek mathematician [Nicomachus](https://en.wikipedia.org/wiki/Nicomachus) devised a classification scheme for natural numbers, identifying each as belonging uniquely to the categories of **perfect**, **abundant**, or **deficient** based on their [aliquot sum](https://en.wikipedia.org/wiki/Aliquot_sum). The aliquot sum is defined as the sum of the factors of a number not including the number itself. For example, the aliquot sum of 15 is (1 + 3 + 5) = 9\n", "\n", "- **Perfect**: aliquot sum = number\n", " - 6 is a perfect number because (1 + 2 + 3) = 6\n", " - 28 is a perfect number because (1 + 2 + 4 + 7 + 14) = 28\n", "- **Abundant**: aliquot sum > number\n", " - 12 is an abundant number because (1 + 2 + 3 + 4 + 6) = 16\n", " - 24 is an abundant number because (1 + 2 + 3 + 4 + 6 + 8 + 12) = 36\n", "- **Deficient**: aliquot sum < number\n", " - 8 is a deficient number because (1 + 2 + 4) = 7\n", " - Prime numbers are deficient\n", "\n", "Implement a way to determine whether a given number is **perfect**, **abundant** or **deficient**.\n", "\n", "## Source\n", "\n", "Taken from Chapter 2 of Functional Thinking by Neal Ford. [http://shop.oreilly.com/product/0636920029687.do](http://shop.oreilly.com/product/0636920029687.do)\n", "\n", "## Version compatibility\n", "This exercise has been tested on Julia versions >=1.0.\n", "\n", "## Submitting Incomplete Solutions\n", "It's possible to submit an incomplete solution so you can see how others have completed the exercise."]
},
{
"cell_type": "markdown",
"metadata": {},
"source": ["## Your solution"]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": ["# submit\n", ""]
},
{
"cell_type": "markdown",
"metadata": {},
"source": ["## Test suite"]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": ["using Test\n", "\n", "# include(\"perfect-numbers.jl\")\n", "\n", "@testset \"Perfect numbers\" begin\n", "\n", " @testset \"Smallest perfect number is classified correctly\" begin\n", " @test isperfect(6)\n", " end\n", "\n", " @testset \"Medium perfect number is classified correctly\" begin\n", " @test isperfect(28)\n", " end\n", "\n", " @testset \"Large perfect number is classified correctly\" begin\n", " @test isperfect(33550336)\n", " end\n", "end\n", "\n", "@testset \"Abundant numbers\" begin\n", "\n", " @testset \"Smallest abundant number is classified correctly\" begin\n", " @test isabundant(12)\n", " end\n", "\n", " @testset \"Medium abundant number is classified correctly\" begin\n", " @test isabundant(30)\n", " end\n", "\n", " @testset \"Large abundant number is classified correctly\" begin\n", " @test isabundant(33550335)\n", " end\n", "end\n", "\n", "@testset \"Deficient numbers\" begin\n", "\n", " @testset \"Smallest prime deficient number is classified correctly\" begin\n", " @test isdeficient(2)\n", " end\n", "\n", " @testset \"Smallest non-prime deficient number is classified correctly\" begin\n", " @test isdeficient(4)\n", " end\n", "\n", " @testset \"Medium deficient number is classified correctly\" begin\n", " @test isdeficient(32)\n", " end\n", "\n", " @testset \"Large deficient number is classified correctly\" begin\n", " @test isdeficient(33550337)\n", " end\n", "\n", " @testset \"Edge case (no factors other than itself) is classified correctly\" begin\n", " @test isdeficient(1)\n", " end\n", "end\n", "\n", "@testset \"Invalid inputs\" begin\n", "\n", " @testset \"Zero is rejected (not a natural number)\" begin\n", " @test_throws DomainError isdeficient(0)\n", " @test_throws DomainError isperfect(0)\n", " @test_throws DomainError isabundant(0)\n", " end\n", "\n", " @testset \"Negative integer is rejected (not a natural number)\" begin\n", " @test_throws DomainError isdeficient(-1)\n", " @test_throws DomainError isperfect(-1)\n", " @test_throws DomainError isabundant(-1)\n", " end\n", "end"]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Prepare submission\n",
"To submit your exercise, you need to save your solution in a file called `perfect-numbers.jl` before using the CLI.\n",
"You can either create it manually or use the following functions, which will automatically write every notebook cell that starts with `# submit` to the file `perfect-numbers.jl`.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# using Pkg; Pkg.add(\"Exercism\")\n",
"# using Exercism\n",
"# Exercism.create_submission(\"perfect-numbers\")"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Julia 1.3.0",
"language": "julia",
"name": "julia-1.3"
},
"language_info": {
"file_extension": ".jl",
"mimetype": "application/julia",
"name": "julia",
"version": "1.3.0"
}
},
"nbformat": 4,
"nbformat_minor": 2
}

View File

@@ -0,0 +1,8 @@
function aliquot_sum(n)
n <= 0 && throw(DomainError("Aliquot sum only exists for natural numbers"))
sum([x for x in 1:div(n, 2) if mod(n, x) == 0])
end
isperfect(n) = aliquot_sum(n) == n
isabundant(n) = aliquot_sum(n) > n
isdeficient(n) = aliquot_sum(n) < n

View File

@@ -0,0 +1,71 @@
using Test
include("perfect-numbers.jl")
@testset "Perfect numbers" begin
@testset "Smallest perfect number is classified correctly" begin
@test isperfect(6)
end
@testset "Medium perfect number is classified correctly" begin
@test isperfect(28)
end
@testset "Large perfect number is classified correctly" begin
@test isperfect(33550336)
end
end
@testset "Abundant numbers" begin
@testset "Smallest abundant number is classified correctly" begin
@test isabundant(12)
end
@testset "Medium abundant number is classified correctly" begin
@test isabundant(30)
end
@testset "Large abundant number is classified correctly" begin
@test isabundant(33550335)
end
end
@testset "Deficient numbers" begin
@testset "Smallest prime deficient number is classified correctly" begin
@test isdeficient(2)
end
@testset "Smallest non-prime deficient number is classified correctly" begin
@test isdeficient(4)
end
@testset "Medium deficient number is classified correctly" begin
@test isdeficient(32)
end
@testset "Large deficient number is classified correctly" begin
@test isdeficient(33550337)
end
@testset "Edge case (no factors other than itself) is classified correctly" begin
@test isdeficient(1)
end
end
@testset "Invalid inputs" begin
@testset "Zero is rejected (not a natural number)" begin
@test_throws DomainError isdeficient(0)
@test_throws DomainError isperfect(0)
@test_throws DomainError isabundant(0)
end
@testset "Negative integer is rejected (not a natural number)" begin
@test_throws DomainError isdeficient(-1)
@test_throws DomainError isperfect(-1)
@test_throws DomainError isabundant(-1)
end
end

View File

@@ -0,0 +1 @@
{"track":"julia","exercise":"prime-factors","id":"5198169256b2415da05999facf51ba03","url":"https://exercism.io/my/solutions/5198169256b2415da05999facf51ba03","handle":"halfdan","is_requester":true,"auto_approve":false}

View File

@@ -0,0 +1,40 @@
# Prime Factors
Compute the prime factors of a given natural number.
A prime number is only evenly divisible by itself and 1.
Note that 1 is not a prime number.
## Example
What are the prime factors of 60?
- Our first divisor is 2. 2 goes into 60, leaving 30.
- 2 goes into 30, leaving 15.
- 2 doesn't go cleanly into 15. So let's move on to our next divisor, 3.
- 3 goes cleanly into 15, leaving 5.
- 3 does not go cleanly into 5. The next possible factor is 4.
- 4 does not go cleanly into 5. The next possible factor is 5.
- 5 does go cleanly into 5.
- We're left only with 1, so now, we're done.
Our successful divisors in that computation represent the list of prime
factors of 60: 2, 2, 3, and 5.
You can check this yourself:
- 2 * 2 * 3 * 5
- = 4 * 15
- = 60
- Success!
## Source
The Prime Factors Kata by Uncle Bob [http://butunclebob.com/ArticleS.UncleBob.ThePrimeFactorsKata](http://butunclebob.com/ArticleS.UncleBob.ThePrimeFactorsKata)
## Version compatibility
This exercise has been tested on Julia versions >=1.0.
## Submitting Incomplete Solutions
It's possible to submit an incomplete solution so you can see how others have completed the exercise.

View File

@@ -0,0 +1,68 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": ["# Prime Factors\n", "\n", "Compute the prime factors of a given natural number.\n", "\n", "A prime number is only evenly divisible by itself and 1.\n", "\n", "Note that 1 is not a prime number.\n", "\n", "## Example\n", "\n", "What are the prime factors of 60?\n", "\n", "- Our first divisor is 2. 2 goes into 60, leaving 30.\n", "- 2 goes into 30, leaving 15.\n", " - 2 doesn't go cleanly into 15. So let's move on to our next divisor, 3.\n", "- 3 goes cleanly into 15, leaving 5.\n", " - 3 does not go cleanly into 5. The next possible factor is 4.\n", " - 4 does not go cleanly into 5. The next possible factor is 5.\n", "- 5 does go cleanly into 5.\n", "- We're left only with 1, so now, we're done.\n", "\n", "Our successful divisors in that computation represent the list of prime\n", "factors of 60: 2, 2, 3, and 5.\n", "\n", "You can check this yourself:\n", "\n", "- 2 * 2 * 3 * 5\n", "- = 4 * 15\n", "- = 60\n", "- Success!\n", "\n", "## Source\n", "\n", "The Prime Factors Kata by Uncle Bob [http://butunclebob.com/ArticleS.UncleBob.ThePrimeFactorsKata](http://butunclebob.com/ArticleS.UncleBob.ThePrimeFactorsKata)\n", "\n", "## Version compatibility\n", "This exercise has been tested on Julia versions >=1.0.\n", "\n", "## Submitting Incomplete Solutions\n", "It's possible to submit an incomplete solution so you can see how others have completed the exercise."]
},
{
"cell_type": "markdown",
"metadata": {},
"source": ["## Your solution"]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": ["# submit\n", ""]
},
{
"cell_type": "markdown",
"metadata": {},
"source": ["## Test suite"]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": ["# include(\"prime-factors.jl\")\n", "using Test\n", "\n", "@testset \"no factors\" begin\n", " @test prime_factors(1) == []\n", "end\n", "\n", "@testset \"prime number\" begin\n", " @test prime_factors(2) == [2]\n", "end\n", "\n", "@testset \"square of a prime\" begin\n", " @test prime_factors(9) == [3, 3]\n", "end\n", "\n", "@testset \"cube of a prime\" begin\n", " @test prime_factors(8) == [2, 2, 2]\n", "end\n", "\n", "@testset \"product of primes and non-primes\" begin\n", " @test prime_factors(12) == [2, 2, 3]\n", "end\n", "\n", "@testset \"product of primes\" begin\n", " @test prime_factors(901255) == [5, 17, 23, 461]\n", "end\n", "\n", "@testset \"factors include a large prime\" begin\n", " @test prime_factors(93819012551) == [11, 9539, 894119]\n", "end"]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Prepare submission\n",
"To submit your exercise, you need to save your solution in a file called `prime-factors.jl` before using the CLI.\n",
"You can either create it manually or use the following functions, which will automatically write every notebook cell that starts with `# submit` to the file `prime-factors.jl`.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# using Pkg; Pkg.add(\"Exercism\")\n",
"# using Exercism\n",
"# Exercism.create_submission(\"prime-factors\")"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Julia 1.3.0",
"language": "julia",
"name": "julia-1.3"
},
"language_info": {
"file_extension": ".jl",
"mimetype": "application/julia",
"name": "julia",
"version": "1.3.0"
}
},
"nbformat": 4,
"nbformat_minor": 2
}

View File

@@ -0,0 +1,13 @@
function prime_factors(n::Int)
primes = []
while n != 1 && n > 1
for i in 2:n
if n % i == 0
push!(primes, i)
n = div(n, i)
break
end
end
end
primes
end

View File

@@ -0,0 +1,30 @@
include("prime-factors.jl")
using Test
@testset "no factors" begin
@test prime_factors(1) == []
end
@testset "prime number" begin
@test prime_factors(2) == [2]
end
@testset "square of a prime" begin
@test prime_factors(9) == [3, 3]
end
@testset "cube of a prime" begin
@test prime_factors(8) == [2, 2, 2]
end
@testset "product of primes and non-primes" begin
@test prime_factors(12) == [2, 2, 3]
end
@testset "product of primes" begin
@test prime_factors(901255) == [5, 17, 23, 461]
end
@testset "factors include a large prime" begin
@test prime_factors(93819012551) == [11, 9539, 894119]
end

View File

@@ -0,0 +1 @@
{"track":"julia","exercise":"run-length-encoding","id":"bd55331dd6c8411595b7f396026666c9","url":"https://exercism.io/my/solutions/bd55331dd6c8411595b7f396026666c9","handle":"halfdan","is_requester":true,"auto_approve":false}

View File

@@ -0,0 +1,34 @@
# Run Length Encoding
Implement run-length encoding and decoding.
Run-length encoding (RLE) is a simple form of data compression, where runs
(consecutive data elements) are replaced by just one data value and count.
For example we can represent the original 53 characters with only 13.
```text
"WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWB" -> "12WB12W3B24WB"
```
RLE allows the original data to be perfectly reconstructed from
the compressed data, which makes it a lossless data compression.
```text
"AABCCCDEEEE" -> "2AB3CD4E" -> "AABCCCDEEEE"
```
For simplicity, you can assume that the unencoded string will only contain
the letters A through Z (either lower or upper case) and whitespace. This way
data to be encoded will never contain any numbers and numbers inside data to
be decoded always represent the count for the following character.
## Source
Wikipedia [https://en.wikipedia.org/wiki/Run-length_encoding](https://en.wikipedia.org/wiki/Run-length_encoding)
## Version compatibility
This exercise has been tested on Julia versions >=1.0.
## Submitting Incomplete Solutions
It's possible to submit an incomplete solution so you can see how others have completed the exercise.

View File

@@ -0,0 +1,68 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": ["# Run Length Encoding\n", "\n", "Implement run-length encoding and decoding.\n", "\n", "Run-length encoding (RLE) is a simple form of data compression, where runs\n", "(consecutive data elements) are replaced by just one data value and count.\n", "\n", "For example we can represent the original 53 characters with only 13.\n", "\n", "```text\n", "\"WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWB\" -> \"12WB12W3B24WB\"\n", "```\n", "\n", "RLE allows the original data to be perfectly reconstructed from\n", "the compressed data, which makes it a lossless data compression.\n", "\n", "```text\n", "\"AABCCCDEEEE\" -> \"2AB3CD4E\" -> \"AABCCCDEEEE\"\n", "```\n", "\n", "For simplicity, you can assume that the unencoded string will only contain\n", "the letters A through Z (either lower or upper case) and whitespace. This way\n", "data to be encoded will never contain any numbers and numbers inside data to\n", "be decoded always represent the count for the following character.\n", "\n", "## Source\n", "\n", "Wikipedia [https://en.wikipedia.org/wiki/Run-length_encoding](https://en.wikipedia.org/wiki/Run-length_encoding)\n", "\n", "## Version compatibility\n", "This exercise has been tested on Julia versions >=1.0.\n", "\n", "## Submitting Incomplete Solutions\n", "It's possible to submit an incomplete solution so you can see how others have completed the exercise."]
},
{
"cell_type": "markdown",
"metadata": {},
"source": ["## Your solution"]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": ["# submit\n", "function encode(s)\n", "end\n", "\n", "\n", "\n", "function decode(s)\n", "end"]
},
{
"cell_type": "markdown",
"metadata": {},
"source": ["## Test suite"]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": ["using Test\n", "\n", "# include(\"run-length-encoding.jl\")\n", "\n", "\n", "# Tests adapted from `problem-specifications//canonical-data.json` @ v1.0.0\n", "# Encode and decode the strings under the given specifications.\n", "\n", "@testset \"encode strings\" begin\n", " @test encode(\"\") == \"\"\n", " @test encode(\"XYZ\") == \"XYZ\"\n", " @test encode(\"AABBBCCCC\") == \"2A3B4C\"\n", " @test encode(\"WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWB\") == \"12WB12W3B24WB\"\n", " @test encode(\"aabbbcccc\") == \"2a3b4c\"\n", " @test encode(\" hsqq qww \") == \"2 hs2q q2w2 \"\n", "end\n", "\n", "@testset \"decode strings\" begin\n", " @test decode(\"\") == \"\"\n", " @test decode(\"XYZ\") == \"XYZ\"\n", " @test decode(\"2A3B4C\") == \"AABBBCCCC\"\n", " @test decode(\"12WB12W3B24WB\") == \"WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWB\"\n", " @test decode(\"2a3b4c\") == \"aabbbcccc\"\n", " @test decode(\"2 hs2q q2w2 \") == \" hsqq qww \"\n", "end\n", "\n", "@testset \"encode then decode\" begin\n", " @test decode(encode(\"zzz ZZ zZ\")) == \"zzz ZZ zZ\"\n", "end"]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Prepare submission\n",
"To submit your exercise, you need to save your solution in a file called `run-length-encoding.jl` before using the CLI.\n",
"You can either create it manually or use the following functions, which will automatically write every notebook cell that starts with `# submit` to the file `run-length-encoding.jl`.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# using Pkg; Pkg.add(\"Exercism\")\n",
"# using Exercism\n",
"# Exercism.create_submission(\"run-length-encoding\")"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Julia 1.3.0",
"language": "julia",
"name": "julia-1.3"
},
"language_info": {
"file_extension": ".jl",
"mimetype": "application/julia",
"name": "julia",
"version": "1.3.0"
}
},
"nbformat": 4,
"nbformat_minor": 2
}

View File

@@ -0,0 +1,34 @@
function encode(s)
ch = nothing
cnt = 1
result = ""
for c s
if ch nothing
ch = c
continue
end
if ch == c
cnt += 1
else
result *= cnt > 1 ? "$cnt$ch" : "$ch"
ch = c
cnt = 1
end
end
if ch nothing
result *= cnt > 1 ? "$cnt$ch" : "$ch"
end
result
end
function decode(s)
items = collect(eachmatch(r"(\d+)?(.)", s))
result = ""
for item items
cnt = parse(Int, (item[1] nothing) ? "1" : item[1])
result *= item[2]^cnt
end
result
end

View File

@@ -0,0 +1,29 @@
using Test
include("run-length-encoding.jl")
# Tests adapted from `problem-specifications//canonical-data.json` @ v1.0.0
# Encode and decode the strings under the given specifications.
@testset "encode strings" begin
@test encode("") == ""
@test encode("XYZ") == "XYZ"
@test encode("AABBBCCCC") == "2A3B4C"
@test encode("WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWB") == "12WB12W3B24WB"
@test encode("aabbbcccc") == "2a3b4c"
@test encode(" hsqq qww ") == "2 hs2q q2w2 "
end
@testset "decode strings" begin
@test decode("") == ""
@test decode("XYZ") == "XYZ"
@test decode("2A3B4C") == "AABBBCCCC"
@test decode("12WB12W3B24WB") == "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWB"
@test decode("2a3b4c") == "aabbbcccc"
@test decode("2 hs2q q2w2 ") == " hsqq qww "
end
@testset "encode then decode" begin
@test decode(encode("zzz ZZ zZ")) == "zzz ZZ zZ"
end

View File

@@ -0,0 +1 @@
{"track":"julia","exercise":"scrabble-score","id":"eb4d940ab0c344d19a57272dc9fe3da9","url":"https://exercism.io/my/solutions/eb4d940ab0c344d19a57272dc9fe3da9","handle":"halfdan","is_requester":true,"auto_approve":false}

View File

@@ -0,0 +1,50 @@
# Scrabble Score
Given a word, compute the Scrabble score for that word.
## Letter Values
You'll need these:
```text
Letter Value
A, E, I, O, U, L, N, R, S, T 1
D, G 2
B, C, M, P 3
F, H, V, W, Y 4
K 5
J, X 8
Q, Z 10
```
## Examples
"cabbage" should be scored as worth 14 points:
- 3 points for C
- 1 point for A, twice
- 3 points for B, twice
- 2 points for G
- 1 point for E
And to total:
- `3 + 2*1 + 2*3 + 2 + 1`
- = `3 + 2 + 6 + 3`
- = `5 + 9`
- = 14
## Extensions
- You can play a double or a triple letter.
- You can play a double or a triple word.
## Source
Inspired by the Extreme Startup game [https://github.com/rchatley/extreme_startup](https://github.com/rchatley/extreme_startup)
## Version compatibility
This exercise has been tested on Julia versions >=1.0.
## Submitting Incomplete Solutions
It's possible to submit an incomplete solution so you can see how others have completed the exercise.

View File

@@ -0,0 +1,51 @@
using Test
include("scrabble-score.jl")
@testset "lowercase letter" begin
@test score("a") == 1
end
@testset "uppercase letter" begin
@test score("A") == 1
end
@testset "valuable letter" begin
@test score("f") == 4
end
@testset "short word" begin
@test score("at") == 2
end
@testset "short, valuable word" begin
@test score("zoo") == 12
end
@testset "medium word" begin
@test score("street") == 6
end
@testset "medium, valuable word" begin
@test score("quirky") == 22
end
@testset "long, mixed-case word" begin
@test score("OxyphenButazone") == 41
end
@testset "english-like word" begin
@test score("pinata") == 8
end
@testset "non-english letter is not scored" begin
@test score("piñata") == 7
end
@testset "empty input" begin
@test score("") == 0
end
@testset "entire alphabet available" begin
@test score("abcdefghijklmnopqrstuvwxyz") == 87
end

View File

@@ -0,0 +1,68 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": ["# Scrabble Score\n", "\n", "Given a word, compute the Scrabble score for that word.\n", "\n", "## Letter Values\n", "\n", "You'll need these:\n", "\n", "```text\n", "Letter Value\n", "A, E, I, O, U, L, N, R, S, T 1\n", "D, G 2\n", "B, C, M, P 3\n", "F, H, V, W, Y 4\n", "K 5\n", "J, X 8\n", "Q, Z 10\n", "```\n", "\n", "## Examples\n", "\n", "\"cabbage\" should be scored as worth 14 points:\n", "\n", "- 3 points for C\n", "- 1 point for A, twice\n", "- 3 points for B, twice\n", "- 2 points for G\n", "- 1 point for E\n", "\n", "And to total:\n", "\n", "- `3 + 2*1 + 2*3 + 2 + 1`\n", "- = `3 + 2 + 6 + 3`\n", "- = `5 + 9`\n", "- = 14\n", "\n", "## Extensions\n", "\n", "- You can play a double or a triple letter.\n", "- You can play a double or a triple word.\n", "\n", "## Source\n", "\n", "Inspired by the Extreme Startup game [https://github.com/rchatley/extreme_startup](https://github.com/rchatley/extreme_startup)\n", "\n", "## Version compatibility\n", "This exercise has been tested on Julia versions >=1.0.\n", "\n", "## Submitting Incomplete Solutions\n", "It's possible to submit an incomplete solution so you can see how others have completed the exercise."]
},
{
"cell_type": "markdown",
"metadata": {},
"source": ["## Your solution"]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": ["# submit\n", "function score(str)\n", "\n", "end"]
},
{
"cell_type": "markdown",
"metadata": {},
"source": ["## Test suite"]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": ["using Test\n", "\n", "# include(\"scrabble-score.jl\")\n", "\n", "@testset \"lowercase letter\" begin\n", " @test score(\"a\") == 1\n", "end\n", "\n", "@testset \"uppercase letter\" begin\n", " @test score(\"A\") == 1\n", "end\n", "\n", "@testset \"valuable letter\" begin\n", " @test score(\"f\") == 4\n", "end\n", "\n", "@testset \"short word\" begin\n", " @test score(\"at\") == 2\n", "end\n", "\n", "@testset \"short, valuable word\" begin\n", " @test score(\"zoo\") == 12\n", "end\n", "\n", "@testset \"medium word\" begin\n", " @test score(\"street\") == 6\n", "end\n", "\n", "@testset \"medium, valuable word\" begin\n", " @test score(\"quirky\") == 22\n", "end\n", "\n", "@testset \"long, mixed-case word\" begin\n", " @test score(\"OxyphenButazone\") == 41\n", "end\n", "\n", "@testset \"english-like word\" begin\n", " @test score(\"pinata\") == 8\n", "end\n", "\n", "@testset \"non-english letter is not scored\" begin\n", " @test score(\"piñata\") == 7\n", "end\n", "\n", "@testset \"empty input\" begin\n", " @test score(\"\") == 0\n", "end\n", "\n", "@testset \"entire alphabet available\" begin\n", " @test score(\"abcdefghijklmnopqrstuvwxyz\") == 87\n", "end"]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Prepare submission\n",
"To submit your exercise, you need to save your solution in a file called `scrabble-score.jl` before using the CLI.\n",
"You can either create it manually or use the following functions, which will automatically write every notebook cell that starts with `# submit` to the file `scrabble-score.jl`.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# using Pkg; Pkg.add(\"Exercism\")\n",
"# using Exercism\n",
"# Exercism.create_submission(\"scrabble-score\")"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Julia 1.3.0",
"language": "julia",
"name": "julia-1.3"
},
"language_info": {
"file_extension": ".jl",
"mimetype": "application/julia",
"name": "julia",
"version": "1.3.0"
}
},
"nbformat": 4,
"nbformat_minor": 2
}

View File

@@ -0,0 +1,36 @@
const CHARACTER_SCORES = Dict(
'A' => 1,
'E' => 1,
'I' => 1,
'O' => 1,
'U' => 1,
'L' => 1,
'N' => 1,
'R' => 1,
'S' => 1,
'T' => 1,
'D' => 2,
'G' => 2,
'B' => 3,
'C' => 3,
'M' => 3,
'P' => 3,
'F' => 4,
'H' => 4,
'V' => 4,
'W' => 4,
'Y' => 4,
'K' => 5,
'J' => 8,
'X' => 8,
'Q' => 10,
'Z' => 10
)
function score(str::AbstractString)
sum([score(uppercase(c)) for c in str])
end
function score(c::Char)
get(CHARACTER_SCORES, c, 0)
end

View File

@@ -0,0 +1 @@
{"track":"julia","exercise":"triangle","id":"0d677e9f53324414bd3d0bcf8c468849","url":"https://exercism.io/my/solutions/0d677e9f53324414bd3d0bcf8c468849","handle":"halfdan","is_requester":true,"auto_approve":false}

33
julia/triangle/README.md Normal file
View File

@@ -0,0 +1,33 @@
# Triangle
Determine if a triangle is equilateral, isosceles, or scalene.
An _equilateral_ triangle has all three sides the same length.
An _isosceles_ triangle has at least two sides the same length. (It is sometimes
specified as having exactly two sides the same length, but for the purposes of
this exercise we'll say at least two.)
A _scalene_ triangle has all sides of different lengths.
## Note
For a shape to be a triangle at all, all sides have to be of length > 0, and
the sum of the lengths of any two sides must be greater than or equal to the
length of the third side. See [Triangle Inequality](https://en.wikipedia.org/wiki/Triangle_inequality).
## Dig Deeper
The case where the sum of the lengths of two sides _equals_ that of the
third is known as a _degenerate_ triangle - it has zero area and looks like
a single line. Feel free to add your own code/tests to check for degenerate triangles.
## Source
The Ruby Koans triangle project, parts 1 & 2 [http://rubykoans.com](http://rubykoans.com)
## Version compatibility
This exercise has been tested on Julia versions >=1.0.
## Submitting Incomplete Solutions
It's possible to submit an incomplete solution so you can see how others have completed the exercise.

View File

@@ -0,0 +1,64 @@
using Test
include("triangle.jl")
@testset "check equilateral triangles" begin
@testset "true if all sides are equal" begin
@test is_equilateral([2, 2, 2]) == true
@test is_equilateral([0.5, 0.5, 0.5]) == true
end
@testset "false if any side is unequal" begin
@test is_equilateral([2, 3, 2]) == false
end
@testset "false if no sides are equal" begin
@test is_equilateral([5, 4, 6]) == false
end
@testset "false if invalid triangle" begin
@test is_equilateral([0, 0, 0]) == false
end
end
@testset "check isosceles triangles" begin
@testset "true if at least 2 sides are equal" begin
@test is_isosceles([3, 4, 4]) == true
@test is_isosceles([4, 3, 4]) == true
@test is_isosceles([4, 4, 3]) == true
@test is_isosceles([4, 4, 4]) == true
@test is_isosceles([0.4, 0.5, 0.5]) == true
@test is_isosceles([0.5, 0.4, 0.5]) == true
@test is_isosceles([0.5, 0.5, 0.4]) == true
end
@testset "false if no sides are equal" begin
@test is_isosceles([2, 3, 4]) == false
end
@testset "false if invalid triangle" begin
@test is_isosceles([1, 1, 3]) == false
end
end
@testset "check scalene triangles" begin
@testset "true if no sides are equal" begin
@test is_scalene([5, 4, 6]) == true
@test is_scalene([0.5, 0.4, 0.6]) == true
end
@testset "false if at least 2 sides are equal" begin
@test is_scalene([3, 4, 4]) == false
@test is_scalene([4, 3, 4]) == false
@test is_scalene([4, 4, 3]) == false
@test is_scalene([4, 4, 4]) == false
@test is_scalene([0.4, 0.5, 0.5]) == false
@test is_scalene([0.5, 0.4, 0.5]) == false
@test is_scalene([0.5, 0.5, 0.4]) == false
end
@testset "false if invalid triangle" begin
@test is_scalene([7, 3, 2]) == false
end
end

View File

@@ -0,0 +1,68 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": ["# Triangle\n", "\n", "Determine if a triangle is equilateral, isosceles, or scalene.\n", "\n", "An _equilateral_ triangle has all three sides the same length.\n", "\n", "An _isosceles_ triangle has at least two sides the same length. (It is sometimes\n", "specified as having exactly two sides the same length, but for the purposes of\n", "this exercise we'll say at least two.)\n", "\n", "A _scalene_ triangle has all sides of different lengths.\n", "\n", "## Note\n", "\n", "For a shape to be a triangle at all, all sides have to be of length > 0, and\n", "the sum of the lengths of any two sides must be greater than or equal to the\n", "length of the third side. See [Triangle Inequality](https://en.wikipedia.org/wiki/Triangle_inequality).\n", "\n", "## Dig Deeper\n", "\n", "The case where the sum of the lengths of two sides _equals_ that of the\n", "third is known as a _degenerate_ triangle - it has zero area and looks like\n", "a single line. Feel free to add your own code/tests to check for degenerate triangles.\n", "\n", "## Source\n", "\n", "The Ruby Koans triangle project, parts 1 & 2 [http://rubykoans.com](http://rubykoans.com)\n", "\n", "## Version compatibility\n", "This exercise has been tested on Julia versions >=1.0.\n", "\n", "## Submitting Incomplete Solutions\n", "It's possible to submit an incomplete solution so you can see how others have completed the exercise."]
},
{
"cell_type": "markdown",
"metadata": {},
"source": ["## Your solution"]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": ["# submit\n", "function is_equilateral(sides)\n", "end\n", "\n", "function is_isosceles(sides)\n", "end\n", "\n", "function is_scalene(sides)\n", "end"]
},
{
"cell_type": "markdown",
"metadata": {},
"source": ["## Test suite"]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": ["using Test\n", "\n", "# include(\"triangle.jl\")\n", "\n", "@testset \"check equilateral triangles\" begin\n", " @testset \"true if all sides are equal\" begin\n", " @test is_equilateral([2, 2, 2]) == true\n", " @test is_equilateral([0.5, 0.5, 0.5]) == true\n", " end\n", "\n", " @testset \"false if any side is unequal\" begin\n", " @test is_equilateral([2, 3, 2]) == false\n", " end\n", "\n", " @testset \"false if no sides are equal\" begin\n", " @test is_equilateral([5, 4, 6]) == false\n", " end\n", "\n", " @testset \"false if invalid triangle\" begin\n", " @test is_equilateral([0, 0, 0]) == false\n", " end\n", "end\n", "\n", "@testset \"check isosceles triangles\" begin\n", " @testset \"true if at least 2 sides are equal\" begin\n", " @test is_isosceles([3, 4, 4]) == true\n", " @test is_isosceles([4, 3, 4]) == true\n", " @test is_isosceles([4, 4, 3]) == true\n", " @test is_isosceles([4, 4, 4]) == true\n", " @test is_isosceles([0.4, 0.5, 0.5]) == true\n", " @test is_isosceles([0.5, 0.4, 0.5]) == true\n", " @test is_isosceles([0.5, 0.5, 0.4]) == true\n", " end\n", "\n", " @testset \"false if no sides are equal\" begin\n", " @test is_isosceles([2, 3, 4]) == false\n", " end\n", "\n", " @testset \"false if invalid triangle\" begin\n", " @test is_isosceles([1, 1, 3]) == false\n", " end\n", "end\n", "\n", "\n", "@testset \"check scalene triangles\" begin\n", " @testset \"true if no sides are equal\" begin\n", " @test is_scalene([5, 4, 6]) == true\n", " @test is_scalene([0.5, 0.4, 0.6]) == true\n", " end\n", "\n", " @testset \"false if at least 2 sides are equal\" begin\n", " @test is_scalene([3, 4, 4]) == false\n", " @test is_scalene([4, 3, 4]) == false\n", " @test is_scalene([4, 4, 3]) == false\n", " @test is_scalene([4, 4, 4]) == false\n", " @test is_scalene([0.4, 0.5, 0.5]) == false\n", " @test is_scalene([0.5, 0.4, 0.5]) == false\n", " @test is_scalene([0.5, 0.5, 0.4]) == false\n", " end\n", "\n", " @testset \"false if invalid triangle\" begin\n", " @test is_scalene([7, 3, 2]) == false\n", " end\n", "end"]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Prepare submission\n",
"To submit your exercise, you need to save your solution in a file called `triangle.jl` before using the CLI.\n",
"You can either create it manually or use the following functions, which will automatically write every notebook cell that starts with `# submit` to the file `triangle.jl`.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# using Pkg; Pkg.add(\"Exercism\")\n",
"# using Exercism\n",
"# Exercism.create_submission(\"triangle\")"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Julia 1.3.0",
"language": "julia",
"name": "julia-1.3"
},
"language_info": {
"file_extension": ".jl",
"mimetype": "application/julia",
"name": "julia",
"version": "1.3.0"
}
},
"nbformat": 4,
"nbformat_minor": 2
}

View File

@@ -0,0 +1,14 @@
is_equilateral(sides) = is_valid(sides) && (sides[1] == sides[2] == sides[3])
function is_isosceles(sides)
is_valid(sides) && (sides[1] == sides[2] || sides[1] == sides[3] || sides[2] == sides[3])
end
function is_scalene(sides)
is_valid(sides) && !is_isosceles(sides)
end
function is_valid(sides)
sides = sort(sides)
(sides[1] + sides[2] > sides[3]) && all(i -> i > 0, sides)
end

View File

@@ -0,0 +1 @@
{"track":"julia","exercise":"trinary","id":"a33190c993fa4f9c917b0c33141e98a3","url":"https://exercism.io/my/solutions/a33190c993fa4f9c917b0c33141e98a3","handle":"halfdan","is_requester":true,"auto_approve":false}

32
julia/trinary/README.md Normal file
View File

@@ -0,0 +1,32 @@
# Trinary
Convert a trinary number, represented as a string (e.g. '102012'), to its
decimal equivalent using first principles.
The program should consider strings specifying an invalid trinary as the
value 0.
Trinary numbers contain three symbols: 0, 1, and 2.
The last place in a trinary number is the 1's place. The second to last
is the 3's place, the third to last is the 9's place, etc.
```shell
# "102012"
1 0 2 0 1 2 # the number
1*3^5 + 0*3^4 + 2*3^3 + 0*3^2 + 1*3^1 + 2*3^0 # the value
243 + 0 + 54 + 0 + 3 + 2 = 302
```
If your language provides a method in the standard library to perform the
conversion, pretend it doesn't exist and implement it yourself.
## Source
All of Computer Science [http://www.wolframalpha.com/input/?i=binary&a=*C.binary-_*MathWorld-](http://www.wolframalpha.com/input/?i=binary&a=*C.binary-_*MathWorld-)
## Version compatibility
This exercise has been tested on Julia versions >=1.0.
## Submitting Incomplete Solutions
It's possible to submit an incomplete solution so you can see how others have completed the exercise.

47
julia/trinary/runtests.jl Normal file
View File

@@ -0,0 +1,47 @@
using Test
include("trinary.jl")
@testset "trinary 1 is decimal 1" begin
@test trinary_to_decimal("1") == 1
end
@testset "trinary 2 is decimal 2" begin
@test trinary_to_decimal("2") == 2
end
@testset "trinary 10 is decimal 3" begin
@test trinary_to_decimal("10") == 3
end
@testset "trinary 11 is decimal 4" begin
@test trinary_to_decimal("11") == 4
end
@testset "trinary 100 is decimal 9" begin
@test trinary_to_decimal("100") == 9
end
@testset "trinary 112 is decimal 14" begin
@test trinary_to_decimal("112") == 14
end
@testset "trinary 222 is decimal 26" begin
@test trinary_to_decimal("222") == 26
end
@testset "trinary 1122000120 is decimal 32091" begin
@test trinary_to_decimal("1122000120") == 32091
end
@testset "invalid trinary digits returns 0" begin
@test trinary_to_decimal("1234") == 0
end
@testset "invalid word as input returns 0" begin
@test trinary_to_decimal("carrot") == 0
end
@testset "invalid numbers with letters as input returns 0" begin
@test trinary_to_decimal("0a1b2c") == 0
end

View File

@@ -0,0 +1,68 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": ["# Trinary\n", "\n", "Convert a trinary number, represented as a string (e.g. '102012'), to its\n", "decimal equivalent using first principles.\n", "\n", "The program should consider strings specifying an invalid trinary as the\n", "value 0.\n", "\n", "Trinary numbers contain three symbols: 0, 1, and 2.\n", "\n", "The last place in a trinary number is the 1's place. The second to last\n", "is the 3's place, the third to last is the 9's place, etc.\n", "\n", "```shell\n", "# \"102012\"\n", " 1 0 2 0 1 2 # the number\n", "1*3^5 + 0*3^4 + 2*3^3 + 0*3^2 + 1*3^1 + 2*3^0 # the value\n", " 243 + 0 + 54 + 0 + 3 + 2 = 302\n", "```\n", "\n", "If your language provides a method in the standard library to perform the\n", "conversion, pretend it doesn't exist and implement it yourself.\n", "\n", "## Source\n", "\n", "All of Computer Science [http://www.wolframalpha.com/input/?i=binary&a=*C.binary-_*MathWorld-](http://www.wolframalpha.com/input/?i=binary&a=*C.binary-_*MathWorld-)\n", "\n", "## Version compatibility\n", "This exercise has been tested on Julia versions >=1.0.\n", "\n", "## Submitting Incomplete Solutions\n", "It's possible to submit an incomplete solution so you can see how others have completed the exercise."]
},
{
"cell_type": "markdown",
"metadata": {},
"source": ["## Your solution"]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": ["# submit\n", "function trinary_to_decimal(str)\n", "\n", "end"]
},
{
"cell_type": "markdown",
"metadata": {},
"source": ["## Test suite"]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": ["using Test\n", "\n", "# include(\"trinary.jl\")\n", "\n", "@testset \"trinary 1 is decimal 1\" begin\n", " @test trinary_to_decimal(\"1\") == 1\n", "end\n", "\n", "@testset \"trinary 2 is decimal 2\" begin\n", " @test trinary_to_decimal(\"2\") == 2\n", "end\n", "\n", "@testset \"trinary 10 is decimal 3\" begin\n", " @test trinary_to_decimal(\"10\") == 3\n", "end\n", "\n", "@testset \"trinary 11 is decimal 4\" begin\n", " @test trinary_to_decimal(\"11\") == 4\n", "end\n", "\n", "@testset \"trinary 100 is decimal 9\" begin\n", " @test trinary_to_decimal(\"100\") == 9\n", "end\n", "\n", "@testset \"trinary 112 is decimal 14\" begin\n", " @test trinary_to_decimal(\"112\") == 14\n", "end\n", "\n", "@testset \"trinary 222 is decimal 26\" begin\n", " @test trinary_to_decimal(\"222\") == 26\n", "end\n", "\n", "@testset \"trinary 1122000120 is decimal 32091\" begin\n", " @test trinary_to_decimal(\"1122000120\") == 32091\n", "end\n", "\n", "@testset \"invalid trinary digits returns 0\" begin\n", " @test trinary_to_decimal(\"1234\") == 0\n", "end\n", "\n", "@testset \"invalid word as input returns 0\" begin\n", " @test trinary_to_decimal(\"carrot\") == 0\n", "end\n", "\n", "@testset \"invalid numbers with letters as input returns 0\" begin\n", " @test trinary_to_decimal(\"0a1b2c\") == 0\n", "end"]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Prepare submission\n",
"To submit your exercise, you need to save your solution in a file called `trinary.jl` before using the CLI.\n",
"You can either create it manually or use the following functions, which will automatically write every notebook cell that starts with `# submit` to the file `trinary.jl`.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# using Pkg; Pkg.add(\"Exercism\")\n",
"# using Exercism\n",
"# Exercism.create_submission(\"trinary\")"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Julia 1.3.0",
"language": "julia",
"name": "julia-1.3"
},
"language_info": {
"file_extension": ".jl",
"mimetype": "application/julia",
"name": "julia",
"version": "1.3.0"
}
},
"nbformat": 4,
"nbformat_minor": 2
}

6
julia/trinary/trinary.jl Normal file
View File

@@ -0,0 +1,6 @@
function trinary_to_decimal(str)
all(x -> x ('0', '1', '2'), str) || return 0
number = parse(Int, str)
digs = digits(number)
sum([k*3^(i-1) for (i,k) in enumerate(digs)])
end