mirror of
https://github.com/mfocko/blog.git
synced 2024-11-21 12:33:57 +01:00
chore: transfer all KBs to single one
Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
parent
d207e870d4
commit
7427475022
159 changed files with 28847 additions and 0 deletions
20
.gitignore
vendored
Normal file
20
.gitignore
vendored
Normal file
|
@ -0,0 +1,20 @@
|
|||
# Dependencies
|
||||
/node_modules
|
||||
|
||||
# Production
|
||||
/build
|
||||
|
||||
# Generated files
|
||||
.docusaurus
|
||||
.cache-loader
|
||||
|
||||
# Misc
|
||||
.DS_Store
|
||||
.env.local
|
||||
.env.development.local
|
||||
.env.test.local
|
||||
.env.production.local
|
||||
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
14
.pre-commit-config.yaml
Normal file
14
.pre-commit-config.yaml
Normal file
|
@ -0,0 +1,14 @@
|
|||
# See https://pre-commit.com for more information
|
||||
# See https://pre-commit.com/hooks.html for more hooks
|
||||
repos:
|
||||
- repo: https://github.com/pre-commit/pre-commit-hooks
|
||||
rev: v3.2.0
|
||||
hooks:
|
||||
- id: trailing-whitespace
|
||||
- id: end-of-file-fixer
|
||||
- id: check-yaml
|
||||
- id: check-added-large-files
|
||||
- repo: https://github.com/pre-commit/mirrors-prettier
|
||||
rev: v2.2.1
|
||||
hooks:
|
||||
- id: prettier
|
41
README.md
Normal file
41
README.md
Normal file
|
@ -0,0 +1,41 @@
|
|||
# Website
|
||||
|
||||
This website is built using [Docusaurus 2](https://docusaurus.io/), a modern static website generator.
|
||||
|
||||
### Installation
|
||||
|
||||
```
|
||||
$ yarn
|
||||
```
|
||||
|
||||
### Local Development
|
||||
|
||||
```
|
||||
$ yarn start
|
||||
```
|
||||
|
||||
This command starts a local development server and opens up a browser window. Most changes are reflected live without having to restart the server.
|
||||
|
||||
### Build
|
||||
|
||||
```
|
||||
$ yarn build
|
||||
```
|
||||
|
||||
This command generates static content into the `build` directory and can be served using any static contents hosting service.
|
||||
|
||||
### Deployment
|
||||
|
||||
Using SSH:
|
||||
|
||||
```
|
||||
$ USE_SSH=true yarn deploy
|
||||
```
|
||||
|
||||
Not using SSH:
|
||||
|
||||
```
|
||||
$ GIT_USER=<Your GitHub username> yarn deploy
|
||||
```
|
||||
|
||||
If you are using GitHub pages for hosting, this command is a convenient way to build the website and push to the `gh-pages` branch.
|
3
babel.config.js
Normal file
3
babel.config.js
Normal file
|
@ -0,0 +1,3 @@
|
|||
module.exports = {
|
||||
presets: [require.resolve("@docusaurus/core/lib/babel/preset")],
|
||||
};
|
175
docusaurus.config.js
Normal file
175
docusaurus.config.js
Normal file
|
@ -0,0 +1,175 @@
|
|||
// @ts-check
|
||||
// Note: type annotations allow type checking and IDEs autocompletion
|
||||
|
||||
const lightCodeTheme = require("prism-react-renderer/themes/vsLight");
|
||||
const darkCodeTheme = require("prism-react-renderer/themes/dracula");
|
||||
|
||||
const math = require("remark-math");
|
||||
const katex = require("rehype-katex");
|
||||
|
||||
require("dotenv").config();
|
||||
|
||||
/** @type {import('@docusaurus/types').Config} */
|
||||
const config = {
|
||||
title: "Additional materials by mf",
|
||||
tagline: "Additional materials",
|
||||
url: process.env.URL,
|
||||
baseUrl: process.env.BASE_URL,
|
||||
onBrokenLinks: "warn",
|
||||
onBrokenMarkdownLinks: "warn",
|
||||
favicon: "img/favicon.ico",
|
||||
|
||||
i18n: {
|
||||
defaultLocale: "en",
|
||||
locales: ["en", "cs"],
|
||||
},
|
||||
|
||||
presets: [
|
||||
[
|
||||
"classic",
|
||||
/** @type {import('@docusaurus/preset-classic').Options} */
|
||||
({
|
||||
docs: {
|
||||
path: "ib002",
|
||||
routeBasePath: "ib002",
|
||||
sidebarPath: require.resolve("./sidebars.js"),
|
||||
editUrl: "https://gitlab.fi.muni.cz/xfocko/kb/tree/main",
|
||||
remarkPlugins: [math],
|
||||
rehypePlugins: [katex],
|
||||
},
|
||||
blog: false,
|
||||
theme: {
|
||||
customCss: require.resolve("./src/css/custom.css"),
|
||||
},
|
||||
}),
|
||||
],
|
||||
],
|
||||
|
||||
plugins: [
|
||||
[
|
||||
"@docusaurus/plugin-content-docs",
|
||||
{
|
||||
id: "ib015",
|
||||
path: "ib015",
|
||||
routeBasePath: "ib015",
|
||||
sidebarPath: require.resolve("./sidebars.js"),
|
||||
editUrl: "https://gitlab.fi.muni.cz/xfocko/kb/tree/main",
|
||||
remarkPlugins: [math],
|
||||
rehypePlugins: [katex],
|
||||
},
|
||||
],
|
||||
[
|
||||
"@docusaurus/plugin-content-docs",
|
||||
{
|
||||
id: "ib110",
|
||||
path: "ib110",
|
||||
routeBasePath: "ib110",
|
||||
sidebarPath: require.resolve("./sidebars.js"),
|
||||
editUrl: "https://gitlab.fi.muni.cz/xfocko/kb/tree/main",
|
||||
remarkPlugins: [math],
|
||||
rehypePlugins: [katex],
|
||||
},
|
||||
],
|
||||
[
|
||||
"@docusaurus/plugin-content-docs",
|
||||
{
|
||||
id: "pb071",
|
||||
path: "pb071",
|
||||
routeBasePath: "pb071",
|
||||
sidebarPath: require.resolve("./sidebars.js"),
|
||||
editUrl: "https://gitlab.fi.muni.cz/xfocko/kb/tree/main",
|
||||
remarkPlugins: [math],
|
||||
rehypePlugins: [katex],
|
||||
},
|
||||
],
|
||||
[
|
||||
"@docusaurus/plugin-content-docs",
|
||||
{
|
||||
id: "pb161",
|
||||
path: "pb161",
|
||||
routeBasePath: "pb161",
|
||||
sidebarPath: require.resolve("./sidebars.js"),
|
||||
editUrl: "https://gitlab.fi.muni.cz/xfocko/kb/tree/main",
|
||||
remarkPlugins: [math],
|
||||
rehypePlugins: [katex],
|
||||
},
|
||||
],
|
||||
],
|
||||
|
||||
stylesheets: [
|
||||
{
|
||||
href: "https://cdn.jsdelivr.net/npm/katex@0.13.24/dist/katex.min.css",
|
||||
type: "text/css",
|
||||
integrity:
|
||||
"sha384-odtC+0UGzzFL/6PNoE8rX/SPcQDXBJ+uRepguP4QkPCm2LBxH3FA3y+fKSiJ+AmM",
|
||||
crossorigin: "anonymous",
|
||||
},
|
||||
],
|
||||
|
||||
themeConfig:
|
||||
/** @type {import('@docusaurus/preset-classic').ThemeConfig} */
|
||||
({
|
||||
navbar: {
|
||||
title: "Additional materials by mf",
|
||||
items: [
|
||||
{
|
||||
type: "doc",
|
||||
docId: "ib002-intro",
|
||||
position: "left",
|
||||
label: "IB002",
|
||||
},
|
||||
// {
|
||||
// type: "doc",
|
||||
// docId: "ib015-intro",
|
||||
// docsPluginId: "ib015",
|
||||
// position: "left",
|
||||
// label: "IB015",
|
||||
// },
|
||||
// {
|
||||
// type: "doc",
|
||||
// docId: "ib110-intro",
|
||||
// docsPluginId: "ib110",
|
||||
// position: "left",
|
||||
// label: "IB110",
|
||||
// },
|
||||
{
|
||||
type: "doc",
|
||||
docId: "pb071-intro",
|
||||
docsPluginId: "pb071",
|
||||
position: "left",
|
||||
label: "PB071",
|
||||
},
|
||||
{
|
||||
type: "doc",
|
||||
docId: "pb161-intro",
|
||||
docsPluginId: "pb161",
|
||||
position: "left",
|
||||
label: "PB161",
|
||||
},
|
||||
{
|
||||
href: "https://gitlab.fi.muni.cz/xfocko/fi",
|
||||
label: "GitLab",
|
||||
position: "right",
|
||||
},
|
||||
],
|
||||
},
|
||||
footer: {
|
||||
style: "dark",
|
||||
copyright: `Copyright © ${new Date().getFullYear()} Matej Focko.`,
|
||||
},
|
||||
prism: {
|
||||
theme: lightCodeTheme,
|
||||
darkTheme: darkCodeTheme,
|
||||
additionalLanguages: [
|
||||
"csharp",
|
||||
"java",
|
||||
"dot",
|
||||
"nix",
|
||||
"haskell",
|
||||
"rust",
|
||||
],
|
||||
},
|
||||
}),
|
||||
};
|
||||
|
||||
module.exports = config;
|
14
ib002/00-intro-ib002.md
Normal file
14
ib002/00-intro-ib002.md
Normal file
|
@ -0,0 +1,14 @@
|
|||
---
|
||||
id: ib002-intro
|
||||
title: Introduction
|
||||
slug: /intro
|
||||
---
|
||||
|
||||
In this part you can find „random“ additional materials I have written over the
|
||||
course of teaching _Algorithms and data structures I_.
|
||||
|
||||
It is a various mix of stuff that may have been produced as a follow-up on some
|
||||
question asked at the seminar or spontanously.
|
||||
|
||||
If you have some ideas for posts, please do not hesitate to submit them as issues
|
||||
in the linked [GitLab](https://gitlab.fi.muni.cz/xfocko/kb/issues).
|
7
ib002/01-introduction/_category_.yaml
Normal file
7
ib002/01-introduction/_category_.yaml
Normal file
|
@ -0,0 +1,7 @@
|
|||
label: Introduction, linked list, queue and stack
|
||||
position: 1
|
||||
link:
|
||||
type: generated-index
|
||||
description: |
|
||||
Materials related to basic data structures such as linked list, queue or
|
||||
stack.
|
7
ib002/02-algorithms-correctness/_category_.yaml
Normal file
7
ib002/02-algorithms-correctness/_category_.yaml
Normal file
|
@ -0,0 +1,7 @@
|
|||
label: Algorithms and correctness
|
||||
position: 2
|
||||
link:
|
||||
type: generated-index
|
||||
description: |
|
||||
Materials related to basic ideas behind algorithms and proofs of their
|
||||
correctness.
|
333
ib002/02-algorithms-correctness/postcondition-ambiguity.md
Normal file
333
ib002/02-algorithms-correctness/postcondition-ambiguity.md
Normal file
|
@ -0,0 +1,333 @@
|
|||
---
|
||||
title: Vague postconditions and proving correctness of algorithms
|
||||
description: |
|
||||
Practical example that shows how precise postconditions can help with both
|
||||
debugging and testing of the code.
|
||||
---
|
||||
|
||||
## Introduction
|
||||
|
||||
[Source code](pathname:///files/ib002/postcondition-ambiguity/test_sort.py) used later on.
|
||||
|
||||
## Implementation of select sort from the exercises
|
||||
|
||||
To implement select sort from the exercises and make it as easy to read as possible, I have implemented maximum function that returns index of the biggest element from the first $n$ elements.
|
||||
|
||||
For the sake of time and memory complexity, I am also using `itertools.islice`, which makes a slice, but does not copy the elements into the memory like normal slice does.
|
||||
|
||||
There is also a `check_loop_invariant` function that will be described later.
|
||||
|
||||
```py showLineNumbers
|
||||
def compare_by_value(pair):
|
||||
index, value = pair
|
||||
return value
|
||||
|
||||
|
||||
def maximum(arr, n):
|
||||
first_n_elements = itertools.islice(enumerate(arr), n)
|
||||
index, value = max(first_n_elements, key=compare_by_value)
|
||||
return index
|
||||
|
||||
|
||||
def select_sort(arr, n):
|
||||
assert n == len(arr)
|
||||
|
||||
check_loop_invariant(arr, n, n)
|
||||
for i in reversed(range(1, n)):
|
||||
j = maximum(arr, i + 1)
|
||||
arr[i], arr[j] = arr[j], arr[i]
|
||||
|
||||
check_loop_invariant(arr, n, i)
|
||||
|
||||
return arr
|
||||
```
|
||||
|
||||
## Discussed preconditions, loop invariants and postconditions
|
||||
|
||||
You can safely replace `A` with `arr` or array for list.
|
||||
|
||||
### Precondition
|
||||
|
||||
As a precondition we have established that `A` represents an array of values and $n$ is length of the `A`.
|
||||
|
||||
### Loop invariant
|
||||
|
||||
As for loop invariant we have established that we require two properties:
|
||||
|
||||
1. `A[i + 1 : n]` is sorted
|
||||
2. all elements of `A[i + 1 : n]` are bigger or equal to the other elements
|
||||
|
||||
This invariant is later defined as `check_loop_invariant` function. It is checked before the first iteration and after each iteration.
|
||||
|
||||
### Postcondition
|
||||
|
||||
For the postcondition the first suggestion was that `A` must be sorted. And later we have added that `A'` must be a permutation of `A`.
|
||||
|
||||
> However at the end of the session question arose if it is really required to state in the postcondition that `A'` is a permutation.
|
||||
|
||||
## So is the permutation really required?
|
||||
|
||||
As I have said it is better to have postconditions explicit and do not expect anything that is not stated explicitly, e.g. _name suggests it_. In reality we could consider it as a smaller mistake (but it has consequences).
|
||||
|
||||
On the other hand explicit postconditions can be used to our advantage **and also** help our proof of correctness.
|
||||
|
||||
Consequences:
|
||||
|
||||
1. Property-based testing
|
||||
|
||||
If we have explicit postconditions we can use them to define properties of the output from our algorithms. That way we can use property-based testing, which does not depend on specific inputs and expected outputs, but rather on randomly generated input and checking if the output conforms to our expectations (the postconditions are fulfilled).
|
||||
|
||||
2. Proof of correctness
|
||||
|
||||
If we can prove that algorithm is correct even for algorithm that **is not** correct, we have a problem. That proof has no value and is useless.
|
||||
|
||||
For the sake of showcasing the power of postconditions I will introduce "select sort" that is not correct, but will comply with both the loop invariant and our vague postcondition and thus pass the tests.
|
||||
|
||||
## Implementation of the broken select sort
|
||||
|
||||
To make sure this thing passes everything, but our explicit postcondition with permutation will _blow it up_, I have designed this "select sort" as follows:
|
||||
|
||||
1. If I get empty list, there is nothing to do.
|
||||
2. I find maximum in the array.
|
||||
3. For each index from the end, I will assign `maximum + index`.
|
||||
This will ensure that even if the maximum in the original array was the first element, I will always satisfy that 2nd part of the loop invariant.
|
||||
|
||||
```py showLineNumbers
|
||||
def broken_select_sort(arr, n):
|
||||
assert n == len(arr)
|
||||
|
||||
if not arr:
|
||||
return
|
||||
|
||||
max_value = max(arr)
|
||||
|
||||
check_loop_invariant(arr, n, n)
|
||||
for i in reversed(range(n)):
|
||||
arr[i] = max_value + i
|
||||
|
||||
check_loop_invariant(arr, n, i)
|
||||
|
||||
return arr
|
||||
```
|
||||
|
||||
:::tip
|
||||
|
||||
There is also an easier way to break this, I leave that as an exercise ;)
|
||||
|
||||
:::
|
||||
|
||||
## Property-based tests for our sorts
|
||||
|
||||
Since we have talked a lot about proofs at the seminar, I would like to demonstrate it on the testing of the sorts. In the following text I will cover implementation of the loop invariant and both postconditions we have talked about and then test our sorts using them.
|
||||
|
||||
### Loop invariant
|
||||
|
||||
To check loop invariant I have implemented this function:
|
||||
|
||||
```py showLineNumbers
|
||||
def check_loop_invariant(arr, n, i):
|
||||
# A[i + 1 : n] is sorted
|
||||
for x, y in zip(itertools.islice(arr, i + 1, n), itertools.islice(arr, i + 2, n)):
|
||||
assert x <= y
|
||||
|
||||
# all elements of A[i + 1 : n] are bigger or equal to the other elements
|
||||
if i + 1 >= n:
|
||||
# in case there are no elements
|
||||
return
|
||||
|
||||
# otherwise, since the "tail" is sorted, we can assume that it is enough to
|
||||
# check the other elements to the smallest value of the tail
|
||||
smallest = arr[i + 1]
|
||||
for element in itertools.islice(arr, i + 1):
|
||||
assert smallest >= element
|
||||
```
|
||||
|
||||
First part checks if the "ending" of the array is sorted.
|
||||
|
||||
In second part I have used a _dirty trick_ of taking just the first element that is the smallest and compared the rest of the elements to it. Why is it enough? I leave it as an exercise ;)
|
||||
|
||||
### Postcondition(s)
|
||||
|
||||
I have defined both the vague and explicit postconditions:
|
||||
|
||||
```py showLineNumbers
|
||||
def check_vague_postcondition(original_arr, arr):
|
||||
if not arr:
|
||||
return
|
||||
|
||||
# check ordering
|
||||
for x, y in zip(arr, itertools.islice(arr, 1, len(arr))):
|
||||
assert x <= y
|
||||
|
||||
|
||||
def check_postcondition(original_arr, arr):
|
||||
if not arr:
|
||||
return
|
||||
|
||||
# check ordering
|
||||
for x, y in zip(arr, itertools.islice(arr, 1, len(arr))):
|
||||
assert x <= y
|
||||
|
||||
# get counts from original list
|
||||
original_counts = {}
|
||||
for value in original_arr:
|
||||
original_counts[value] = 1 + original_counts.get(value, 0)
|
||||
|
||||
# get counts from resulting list
|
||||
counts = {}
|
||||
for value in arr:
|
||||
counts[value] = 1 + counts.get(value, 0)
|
||||
|
||||
# if arr is permutation of original_arr then all counts must be the same
|
||||
assert counts == original_counts
|
||||
```
|
||||
|
||||
### Putting it together
|
||||
|
||||
Now that we have everything implement, we can move on to the implementation of the tests:
|
||||
|
||||
```py showLineNumbers
|
||||
from hypothesis import given, settings
|
||||
from hypothesis.strategies import integers, lists
|
||||
import pytest
|
||||
|
||||
@given(lists(integers()))
|
||||
@settings(max_examples=1000)
|
||||
@pytest.mark.parametrize(
|
||||
"postcondition", [check_vague_postcondition, check_postcondition]
|
||||
)
|
||||
@pytest.mark.parametrize("sorting_function", [select_sort, broken_select_sort])
|
||||
def test_select_sort(sorting_function, postcondition, numbers):
|
||||
result = sorting_function(numbers[:], len(numbers))
|
||||
postcondition(numbers, result)
|
||||
```
|
||||
|
||||
Since it might seem a bit scary, I will disect it by parts.
|
||||
|
||||
1. Parameters of test function
|
||||
|
||||
```py showLineNumbers
|
||||
def test_select_sort(sorting_function, postcondition, numbers):
|
||||
```
|
||||
|
||||
We are given 3 parameters:
|
||||
|
||||
- `sorting_function` - as the name suggests is the sorting function we test
|
||||
- `postcondition` - as the name suggests is the postcondition that we check
|
||||
- `numbers` - is random list of numbers that we will be sorting
|
||||
|
||||
2. Body of the test
|
||||
|
||||
```py showLineNumbers
|
||||
result = sorting_function(numbers[:], len(numbers))
|
||||
postcondition(numbers, result)
|
||||
```
|
||||
|
||||
We pass to the sorting function **copy** of the numbers we got, this ensures that once we are checking the more strict postcondition, we can gather the necessary information even after sorting the list in-situ, i.e. we can check if the `result` is really a `permutation` of the `numbers` even though the sorting functions has modified the passed in list.
|
||||
|
||||
:::caution
|
||||
|
||||
Now we get to the more complicated part and it is the _decorators_.
|
||||
|
||||
:::
|
||||
|
||||
3. 1st `parametrize` from the bottom
|
||||
|
||||
```py showLineNumbers
|
||||
@pytest.mark.parametrize("sorting_function", [select_sort, broken_select_sort])
|
||||
```
|
||||
|
||||
This tells pytest, that we want to pass the values from the list to the parameter `sorting_function`. In other words, this lets us use the same test function for both the correct and incorrect select sort.
|
||||
|
||||
4. 2nd `parametrize` from the bottom is similar, but works with the postcondition.
|
||||
The reason why they are separated is pretty simple, this way they act like cartesian product: for each sorting function we also use each postcondition.
|
||||
|
||||
5. `@settings` raises the count of tests that hypothesis runs (from default of 100(?)).
|
||||
|
||||
6. `@given(lists(integers()))`
|
||||
This means hypothesis is randomly creating lists of integers and passing them to the function, which has only one parameter left and that is `numbers`.
|
||||
|
||||
### Let's run the tests!
|
||||
|
||||
In case you want to experiment locally, you should install `pytest` and `hypothesis` from the PyPI.
|
||||
|
||||
```
|
||||
% pytest -v test_sort.py
|
||||
=================================== test session starts ====================================
|
||||
platform linux -- Python 3.6.8, pytest-3.8.2, py-1.7.0, pluggy-0.13.1 -- /usr/bin/python3
|
||||
cachedir: .pytest_cache
|
||||
rootdir: /home/xfocko/git/xfocko/ib002/postcondition-ambiguity, inifile:
|
||||
plugins: hypothesis-5.16.1
|
||||
collected 4 items
|
||||
|
||||
test_sort.py::test_select_sort[select_sort-check_vague_postcondition] PASSED [ 25%]
|
||||
test_sort.py::test_select_sort[select_sort-check_postcondition] PASSED [ 50%]
|
||||
test_sort.py::test_select_sort[broken_select_sort-check_vague_postcondition] PASSED [ 75%]
|
||||
test_sort.py::test_select_sort[broken_select_sort-check_postcondition] FAILED [100%]
|
||||
|
||||
========================================= FAILURES =========================================
|
||||
_________________ test_select_sort[broken_select_sort-check_postcondition] _________________
|
||||
|
||||
sorting_function = <function broken_select_sort at 0x7fac179308c8>
|
||||
postcondition = <function check_postcondition at 0x7fac1786d1e0>
|
||||
|
||||
@given(lists(integers()))
|
||||
> @settings(max_examples=1000)
|
||||
@pytest.mark.parametrize(
|
||||
"postcondition", [check_vague_postcondition, check_postcondition]
|
||||
)
|
||||
@pytest.mark.parametrize("sorting_function", [select_sort, broken_select_sort])
|
||||
def test_select_sort(sorting_function, postcondition, numbers):
|
||||
|
||||
test_sort.py:132:
|
||||
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
|
||||
test_sort.py:139: in test_select_sort
|
||||
postcondition(numbers, result)
|
||||
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
|
||||
|
||||
original_arr = [0, 0], arr = [0, 1]
|
||||
|
||||
def check_postcondition(original_arr, arr):
|
||||
if not arr:
|
||||
return
|
||||
|
||||
# check ordering
|
||||
for x, y in zip(arr, itertools.islice(arr, 1, len(arr))):
|
||||
assert x <= y
|
||||
|
||||
# get counts from original list
|
||||
original_counts = {}
|
||||
for value in original_arr:
|
||||
original_counts[value] = 1 + original_counts.get(value, 0)
|
||||
|
||||
# get counts from resulting list
|
||||
counts = {}
|
||||
for value in arr:
|
||||
counts[value] = 1 + counts.get(value, 0)
|
||||
|
||||
# if arr is permutation of original_arr then all counts must be the same
|
||||
> assert counts == original_counts
|
||||
E assert {0: 1, 1: 1} == {0: 2}
|
||||
E Differing items:
|
||||
E {0: 1} != {0: 2}
|
||||
E Left contains more items:
|
||||
E {1: 1}
|
||||
E Full diff:
|
||||
E - {0: 1, 1: 1}
|
||||
E + {0: 2}
|
||||
|
||||
test_sort.py:128: AssertionError
|
||||
----------------------------------- Captured stdout call -----------------------------------
|
||||
Falsifying example: test_select_sort(
|
||||
sorting_function=<function test_sort.broken_select_sort>,
|
||||
postcondition=<function test_sort.check_postcondition>,
|
||||
numbers=[0, 0],
|
||||
)
|
||||
============================ 1 failed, 3 passed in 6.84 seconds ============================
|
||||
```
|
||||
|
||||
We can clearly see that our broken select sort has passed the _vague postcondition_, but the explicit one was not satisfied.
|
||||
|
||||
## Summary
|
||||
|
||||
For proving the correctness of the algorithm it is better to be explicit than prove that algorithm is correct even though it is not. Being explicit also allows you to test smaller _chunks_ of code better.
|
6
ib002/03-time-complexity/_category_.yaml
Normal file
6
ib002/03-time-complexity/_category_.yaml
Normal file
|
@ -0,0 +1,6 @@
|
|||
label: Asymptotic notation and time complexity
|
||||
position: 3
|
||||
link:
|
||||
type: generated-index
|
||||
description: |
|
||||
Materials related to asymptotic notation and time complexity.
|
159
ib002/03-time-complexity/extend.md
Normal file
159
ib002/03-time-complexity/extend.md
Normal file
|
@ -0,0 +1,159 @@
|
|||
---
|
||||
title: Time complexity of ‹extend›
|
||||
description: |
|
||||
Hidden time complexity behind commonly used functions on lists and how can
|
||||
repeating of a relatively cheap operation increase its time complexity.
|
||||
---
|
||||
|
||||
## Introduction
|
||||
|
||||
Each year there is a lot of confusion regarding time complexity of the `extend` operation on the lists in Python. I will introduce two specific examples from previous year and also will try to explain it on one of the possible implementations of `extend` operation.
|
||||
|
||||
## Technicalities
|
||||
|
||||
At the beginning we should clear some of the „myths“ regarding extending of the lists. There is a common misunderstanding regarding differences between `a += b`, `a.extend(b)` and `a + b`.
|
||||
|
||||
- `a.extend(b)` - adds all elements from `b` to `a`.
|
||||
|
||||
Time complexity: $\mathcal{O}(n)$, where $n$ denotes the length of `b`.
|
||||
|
||||
- `a += b` - equivalent to `a.extend(b)`
|
||||
|
||||
- `a + b` - constructs a new list that contains elements from `a` followed by
|
||||
elements from `b`.
|
||||
|
||||
Time complexity: $\mathcal{O}(m + n)$, where $m, n$ denote the length of
|
||||
`a` and `b` respectively.
|
||||
|
||||
Space complexity: $\mathcal{O}(m + n)$, where $m, n$ denote the length of
|
||||
`a` and `b` respectively, since we construct new list.
|
||||
|
||||
## Example #1
|
||||
|
||||
Let us assume function that uses divide & conquer strategy to return indices at which we can find specific element in any list.
|
||||
|
||||
```py showLineNumbers
|
||||
def recursive_find_in_list(
|
||||
values: List[Any], key: Any, lower: int, upper: int
|
||||
) -> List[int]:
|
||||
if lower == upper:
|
||||
return [lower] if values[lower] == key else []
|
||||
|
||||
indices = []
|
||||
mid = (lower + upper) // 2
|
||||
|
||||
indices.extend(recursive_find_in_list(values, key, lower, mid))
|
||||
indices.extend(recursive_find_in_list(values, key, mid + 1, upper))
|
||||
|
||||
return indices
|
||||
|
||||
|
||||
def find_in_list(values: List[Any], key: Any) -> List[int]:
|
||||
return recursive_find_in_list(values, key, 0, len(values) - 1)
|
||||
```
|
||||
|
||||
This implementation works nicely, `extend` is linear (with the respect to the length of the list that is being appended).
|
||||
|
||||
Let us try to dissect the way this function works on some specific input (that will be pushed to the extreme, _just in case_ ;)
|
||||
|
||||
`find_in_list([1] * 5000, 1)`. What shall be the result of this? Since we have `key = 1` and the list contains only `1`s, we should get list of **all** indices.
|
||||
|
||||
If we were to draw a tree of call hierarchy of `recursive_find_in_list`, we would notice that in sum it is still linear to the length. **However we use `extend`!**
|
||||
|
||||
In the leaves of the tree we return lists of length 1. In this case it means calling `extend` 5000-times at the second-to-last level of the tree on the 1-element long lists, next level 2500 calls on 2-elements long lists, next one 1250 on 4-elements long lists, etc. At the top-level we get 2 calls on 5000/2-element long lists.
|
||||
|
||||
A lot of `extend` calls, right? And the lengths of the lists are growing (in this example, second call happens on 2500-elements long lists).
|
||||
|
||||
Because of the `extend` in each level of the tree (call hierarchy) we traverse all of the elements. That means:
|
||||
|
||||
$$
|
||||
\mathcal{O}(n \cdot \log n)
|
||||
$$
|
||||
|
||||
because we have $\log n$ levels in the tree and $n$ elements at each level.
|
||||
|
||||
## Example #2
|
||||
|
||||
As we could observe in the example above, `extend` iterates over all of the elements that it adds. In case of recursive calls, it results in iterating over the same elements multiple times.
|
||||
|
||||
Consider constructing of this list:
|
||||
|
||||
![Rendered construction of the list](/files/ib002/extend/rendered.svg)
|
||||
|
||||
<details>
|
||||
<summary>Source for the rendered construction of the list</summary>
|
||||
|
||||
```dot
|
||||
digraph G {
|
||||
node [shape=record];
|
||||
|
||||
a_node [label="1|2|3|4|5|6|7|8|9"]
|
||||
|
||||
b_node [label="1|2|3"]
|
||||
c_node [label="4|5|6"]
|
||||
d_node [label="7|8|9"]
|
||||
|
||||
a_node -> b_node [label="B"]
|
||||
a_node -> c_node [label="C"]
|
||||
a_node -> d_node [label="D"]
|
||||
|
||||
b_node -> "1"
|
||||
b_node -> "2"
|
||||
b_node -> "3"
|
||||
|
||||
c_node -> "4"
|
||||
c_node -> "5"
|
||||
c_node -> "6"
|
||||
|
||||
d_node -> "7"
|
||||
d_node -> "8"
|
||||
d_node -> "9"
|
||||
}
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
Let us assume that you extend the result with the list that you get from the recursive call.
|
||||
|
||||
- B iterates through 1, 2 and 3; returns `[1, 2, 3]`
|
||||
- C iterates through 4, 5 and 6; returns `[4, 5, 6]`
|
||||
- D iterates through 7, 8 and 9; returns `[7, 8, 9]`
|
||||
- now we return those lists to the calls from A), so each of the `extend` calls iterates through:
|
||||
|
||||
- 1, 2, 3 that was returned from B
|
||||
- 4, 5, 6 that was returned from C
|
||||
- 7, 8, 9 that was returned from D
|
||||
|
||||
and returns `[1, 2, 3, 4, 5, 6, 7, 8, 9]`
|
||||
|
||||
If the recursion had bigger depth and/or more elements, it would iterate through them more than twice, therefore it does not take constant time to do nor some constant multiple of the input, since it traverses all of the elements in each of the levels.
|
||||
|
||||
## Implementation of `extend`
|
||||
|
||||
There is an example of dynamic array:
|
||||
|
||||
- [interface (`dynlist.h`)](pathname:///files/ib002/extend/dynlist.h)
|
||||
- [implementation (`dynlist.c`)](pathname:///files/ib002/extend/dynlist.c)
|
||||
|
||||
For the sake of _Algorithms and Data Structures I_ we consider `APPEND` operation, i.e. adding the element to the end of the list, to have time complexity $\mathcal{O}(1)$ (**amortized**; which is out of the scope of IB002).
|
||||
|
||||
If we have a look at the `extend` implementation in this dynamic array example:
|
||||
|
||||
```c showLineNumbers
|
||||
void dynamic_array_extend(struct dynamic_array_t *arr, struct dynamic_array_t *src)
|
||||
{
|
||||
if (arr == NULL || src == NULL)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
for (size_t i = 0; i < src->count; i++)
|
||||
{
|
||||
dynamic_array_push_back(arr, dynamic_array_at(src, i));
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Apart from checking edge cases, we can notice that we run `for`-loop over the elements from the other array and add them one-by-one to the `arr`. Time complexity of this operation is time dependant on the `src` array.
|
||||
|
||||
In this specific implementation, you could also resize the memory allocated for the array in one go and copy _whole_ `src` array in one go. However even if you did so, it would be still dependant on the size of the `src` array. Cause you still need to copy $\texttt{count}(src) \cdot \texttt{elementSize}(src)$ bytes. From that we can assume that for specific instance of array the $\texttt{elementSize}(src)$ is fixed, therefore we consider it a constant. That way we are getting $\mathcal{O}(\texttt{count}(src))$ as a time complexity of our `extend` operation.
|
6
ib002/04-recursion/_category_.yaml
Normal file
6
ib002/04-recursion/_category_.yaml
Normal file
|
@ -0,0 +1,6 @@
|
|||
label: Recursion
|
||||
position: 4
|
||||
link:
|
||||
type: generated-index
|
||||
description: |
|
||||
Materials related to recursive algorithms and their time complexity.
|
6
ib002/05-sorting/_category_.yaml
Normal file
6
ib002/05-sorting/_category_.yaml
Normal file
|
@ -0,0 +1,6 @@
|
|||
label: Sorting algorithms
|
||||
position: 5
|
||||
link:
|
||||
type: generated-index
|
||||
description: |
|
||||
Materials related to sorting algorithms and their modifications.
|
7
ib002/06-heap-priority-queue/_category_.yaml
Normal file
7
ib002/06-heap-priority-queue/_category_.yaml
Normal file
|
@ -0,0 +1,7 @@
|
|||
label: Heap and priority queue
|
||||
position: 6
|
||||
link:
|
||||
type: generated-index
|
||||
description: |
|
||||
Materials related to the heap data structure and its usage for a priority
|
||||
queue.
|
6
ib002/07-bst/_category_.yaml
Normal file
6
ib002/07-bst/_category_.yaml
Normal file
|
@ -0,0 +1,6 @@
|
|||
label: Binary search trees
|
||||
position: 7
|
||||
link:
|
||||
type: generated-index
|
||||
description: |
|
||||
Materials related to binary search trees and algorithms on them.
|
6
ib002/08-rb-trees/_category_.yaml
Normal file
6
ib002/08-rb-trees/_category_.yaml
Normal file
|
@ -0,0 +1,6 @@
|
|||
label: Red-black trees
|
||||
position: 8
|
||||
link:
|
||||
type: generated-index
|
||||
description: |
|
||||
Materials related to red-black trees.
|
328
ib002/08-rb-trees/applications.md
Normal file
328
ib002/08-rb-trees/applications.md
Normal file
|
@ -0,0 +1,328 @@
|
|||
---
|
||||
title: Použití červeno-černých stromů
|
||||
description: |
|
||||
Ukázka použití červeno-černých stromů pro implementaci množiny nebo mapy
|
||||
a ukázky jednotlivých implementací ve standardních knižnicích známých jazyků.
|
||||
---
|
||||
|
||||
## Použití
|
||||
|
||||
Červeno-černé stromy jsou celkem oblíbené pro implementaci ADT množiny nebo slovníku za předpokladu, že nad vkládanými klíči existuje uspořádání. Jazyky níže implementují dané datové struktury v 2 variantách a to:
|
||||
|
||||
- seřazené: používají na pozadí právě červeno-černý strom
|
||||
- neseřazené: používají na pozadí hašovací tabulku
|
||||
|
||||
Pro srovnání, jak jsme si říkali na cvičení, červeno-černý strom má operace hledání, vkládání a mazání v časové složitosti $\mathcal{O}(\log n)$. Na druhou stranu hašovací tabulka má ideálně konstantní časovou složitost, ale v nejhorším případě (detaily na posledním cvičení v semestru) je to bohužel $\mathcal{O}(n)$.
|
||||
|
||||
Výše jsme si ukázali nějaké předpoklady nutné pro hašovací tabulku i červeno-černý strom. Co je tedy lepší?
|
||||
|
||||
- červeno-černý strom nám poskytuje _stabilní časovou složitost_, ale za cenu požadavku _uspořádání_ nad prvky
|
||||
- hašovací tabulka nám poskytuje _pomyslnou perfektní časovou složitost_
|
||||
|
||||
## Různé implementace
|
||||
|
||||
Pro ukázku použití červeno-černých stromů v implementacích standardních knihoven
|
||||
jsme vybrali několik jazyků.
|
||||
|
||||
Pokud Vás zajímají různé implementace, tak bychom doporučili „prohrabávat“ se přes ně v následujícím pořadí: `C# → Java → C++`. Důvod pro zvolené pořadí vychází z toho, že C# implementace je poměrně čitelná a obsahuje množství vysvětlujících komentářů. Implementace v Javě je stejně čitelná, ačkoli již s minimem komentářů, které se maximálně odkazují na CLRS. C++ implementace je „značně poznačená“ podtržítky ;)
|
||||
|
||||
### C++
|
||||
|
||||
V C++ si můžeme vybrat mezi 2 různými implementacemi (`clang` nebo `gcc`).
|
||||
|
||||
#### clang
|
||||
|
||||
Hlavičkové soubory, které používáme při práci s množinou nebo slovníkem (zajímavé sekce jsou vytaženy):
|
||||
|
||||
- [`map`](https://github.com/llvm/llvm-project/blob/main/libcxx/include/map)
|
||||
|
||||
```cpp
|
||||
template <class _Key, class _Tp, class _Compare = less<_Key>,
|
||||
class _Allocator = allocator<pair<const _Key, _Tp> > >
|
||||
class _LIBCPP_TEMPLATE_VIS map
|
||||
{
|
||||
public:
|
||||
// types:
|
||||
typedef _Key key_type;
|
||||
typedef _Tp mapped_type;
|
||||
typedef pair<const key_type, mapped_type> value_type;
|
||||
|
||||
// …
|
||||
|
||||
private:
|
||||
typedef __tree<__value_type, __vc, __allocator_type> __base;
|
||||
```
|
||||
|
||||
- [`set`](https://github.com/llvm/llvm-project/blob/main/libcxx/include/set)
|
||||
|
||||
```cpp
|
||||
template <class _Key, class _Compare = less<_Key>,
|
||||
class _Allocator = allocator<_Key> >
|
||||
class _LIBCPP_TEMPLATE_VIS set
|
||||
{
|
||||
public:
|
||||
// types:
|
||||
typedef _Key key_type;
|
||||
typedef key_type value_type;
|
||||
|
||||
// …
|
||||
|
||||
private:
|
||||
typedef __tree<value_type, value_compare, allocator_type> __base;
|
||||
```
|
||||
|
||||
U obou hlaviček si můžeme všimnout, že deklarují nějaký soukromý typ `__base`, který je aliasem pro `__tree`. Ten nás pak vede k hlavičce [`__tree`](https://github.com/llvm/llvm-project/blob/main/libcxx/include/__tree).
|
||||
|
||||
Výňatek:
|
||||
|
||||
```cpp
|
||||
/*
|
||||
|
||||
_NodePtr algorithms
|
||||
|
||||
The algorithms taking _NodePtr are red black tree algorithms. Those
|
||||
algorithms taking a parameter named __root should assume that __root
|
||||
points to a proper red black tree (unless otherwise specified).
|
||||
|
||||
…
|
||||
|
||||
*/
|
||||
```
|
||||
|
||||
#### gcc
|
||||
|
||||
Pro `gcc` je postup téměř stejný. Pro změnu v hlavičkách `map` a `set` nenajdeme nic, deklarace jsou až v hlavičkových souborech:
|
||||
|
||||
- [`bits/stl_map.h`](https://gcc.gnu.org/git/?p=gcc.git;a=blob;f=libstdc%2B%2B-v3/include/bits/stl_map.h;h=9c2b0745673431b4b396ba27982170478838137e;hb=HEAD)
|
||||
- [`bits/stl_set.h`](https://gcc.gnu.org/git/?p=gcc.git;a=blob;f=libstdc%2B%2B-v3/include/bits/stl_set.h;h=9c2b0745673431b4b396ba27982170478838137e;hb=HEAD)
|
||||
|
||||
V obou se zase odkazuje na nějakou hlavičku [`bits/stl_tree.h`](https://gcc.gnu.org/git/?p=gcc.git;a=blob;f=libstdc%2B%2B-v3/include/bits/stl_tree.h;h=a4de61417652a288e361a55fcc8bb7a9838c58a5;hb=HEAD), zase výňatek:
|
||||
|
||||
```cpp
|
||||
// Red-black tree class, designed for use in implementing STL
|
||||
// associative containers (set, multiset, map, and multimap). The
|
||||
// insertion and deletion algorithms are based on those in Cormen,
|
||||
// Leiserson, and Rivest, Introduction to Algorithms (MIT Press,
|
||||
// 1990), except that
|
||||
//
|
||||
// (1) the header cell is maintained with links not only to the root
|
||||
// but also to the leftmost node of the tree, to enable constant
|
||||
// time begin(), and to the rightmost node of the tree, to enable
|
||||
// linear time performance when used with the generic set algorithms
|
||||
// (set_union, etc.)
|
||||
//
|
||||
// (2) when a node being deleted has two children its successor node
|
||||
// is relinked into its place, rather than copied, so that the only
|
||||
// iterators invalidated are those referring to the deleted node.
|
||||
|
||||
enum _Rb_tree_color { _S_red = false, _S_black = true };
|
||||
|
||||
struct _Rb_tree_node_base
|
||||
{
|
||||
typedef _Rb_tree_node_base* _Base_ptr;
|
||||
typedef const _Rb_tree_node_base* _Const_Base_ptr;
|
||||
|
||||
_Rb_tree_color _M_color;
|
||||
_Base_ptr _M_parent;
|
||||
_Base_ptr _M_left;
|
||||
_Base_ptr _M_right;
|
||||
|
||||
static _Base_ptr
|
||||
_S_minimum(_Base_ptr __x) _GLIBCXX_NOEXCEPT
|
||||
{
|
||||
while (__x->_M_left != 0) __x = __x->_M_left;
|
||||
return __x;
|
||||
}
|
||||
|
||||
static _Const_Base_ptr
|
||||
_S_minimum(_Const_Base_ptr __x) _GLIBCXX_NOEXCEPT
|
||||
{
|
||||
while (__x->_M_left != 0) __x = __x->_M_left;
|
||||
return __x;
|
||||
}
|
||||
|
||||
static _Base_ptr
|
||||
_S_maximum(_Base_ptr __x) _GLIBCXX_NOEXCEPT
|
||||
{
|
||||
while (__x->_M_right != 0) __x = __x->_M_right;
|
||||
return __x;
|
||||
}
|
||||
|
||||
static _Const_Base_ptr
|
||||
_S_maximum(_Const_Base_ptr __x) _GLIBCXX_NOEXCEPT
|
||||
{
|
||||
while (__x->_M_right != 0) __x = __x->_M_right;
|
||||
return __x;
|
||||
}
|
||||
```
|
||||
|
||||
Tady už taky vidíme nějaký kód pro nalezení minima/maxima ve stromě. Mimo jiné
|
||||
ještě existuje [`tree.cc`](https://gcc.gnu.org/git/?p=gcc.git;a=blob;f=libstdc%2B%2B-v3/src/c%2B%2B98/tree.cc;h=fd14991589a57c6aa847f57105a938cd2bf4df6f;hb=HEAD), kde je lze nalézt třeba funkci s následující hlavičkou:
|
||||
|
||||
```cpp
|
||||
void
|
||||
_Rb_tree_insert_and_rebalance(const bool __insert_left,
|
||||
_Rb_tree_node_base* __x,
|
||||
_Rb_tree_node_base* __p,
|
||||
_Rb_tree_node_base& __header) throw ();
|
||||
```
|
||||
|
||||
### Java
|
||||
|
||||
V Javě jsou pro nás klíčové implementace [`TreeSet`](https://github.com/openjdk/jdk/blob/master/src/java.base/share/classes/java/util/TreeSet.java) a [`TreeMap`](https://github.com/openjdk/jdk/blob/master/src/java.base/share/classes/java/util/TreeMap.java).
|
||||
|
||||
V implementaci `TreeSet` si můžete povšimnout:
|
||||
|
||||
```java
|
||||
public class TreeSet<E> extends AbstractSet<E>
|
||||
implements NavigableSet<E>, Cloneable, java.io.Serializable
|
||||
{
|
||||
/**
|
||||
* The backing map.
|
||||
*/
|
||||
private transient NavigableMap<E,Object> m;
|
||||
|
||||
// Dummy value to associate with an Object in the backing Map
|
||||
private static final Object PRESENT = new Object();
|
||||
```
|
||||
|
||||
`TreeSet` v Javě tedy používá na pozadí `TreeMap` (což je vidět ve výchozím konstruktoru, kde se volá konstruktor přebírající `NavigableMap<E, Object>`, a je mu předáno `new TreeMap<>()`).
|
||||
|
||||
Co se týče `TreeMap`, tak hned ze začátku definice `TreeMap` je vidět:
|
||||
|
||||
```java
|
||||
public class TreeMap<K,V>
|
||||
extends AbstractMap<K,V>
|
||||
implements NavigableMap<K,V>, Cloneable, java.io.Serializable
|
||||
{
|
||||
/**
|
||||
* The comparator used to maintain order in this tree map, or
|
||||
* null if it uses the natural ordering of its keys.
|
||||
*
|
||||
* @serial
|
||||
*/
|
||||
@SuppressWarnings("serial") // Conditionally serializable
|
||||
private final Comparator<? super K> comparator;
|
||||
|
||||
private transient Entry<K,V> root;
|
||||
```
|
||||
|
||||
Takže máme „nějaký kořen“ typu `Entry<K,V>`. Zkusíme si najít definici daného typu…
|
||||
|
||||
```java
|
||||
// Red-black mechanics
|
||||
|
||||
private static final boolean RED = false;
|
||||
private static final boolean BLACK = true;
|
||||
|
||||
/**
|
||||
* Node in the Tree. Doubles as a means to pass key-value pairs back to
|
||||
* user (see Map.Entry).
|
||||
*/
|
||||
|
||||
static final class Entry<K,V> implements Map.Entry<K,V> {
|
||||
K key;
|
||||
V value;
|
||||
Entry<K,V> left;
|
||||
Entry<K,V> right;
|
||||
Entry<K,V> parent;
|
||||
boolean color = BLACK;
|
||||
```
|
||||
|
||||
A máme RB-tree.
|
||||
|
||||
(Implementace vychází z projektu OpenJDK.)
|
||||
|
||||
### C#
|
||||
|
||||
V C# se zaměříme na nejnovější vydání (.NET), které je open-source a podporováno i na operačních systémech založených na Linuxu.
|
||||
|
||||
Nejdříve se podíváme na implementaci slovníku ([`SortedDictionary`](https://github.com/dotnet/runtime/blob/main/src/libraries/System.Collections/src/System/Collections/Generic/SortedDictionary.cs)).
|
||||
|
||||
```csharp
|
||||
public class SortedDictionary<TKey, TValue> : IDictionary<TKey, TValue>, IDictionary, IReadOnlyDictionary<TKey, TValue> where TKey : notnull
|
||||
{
|
||||
[NonSerialized]
|
||||
private KeyCollection? _keys;
|
||||
[NonSerialized]
|
||||
private ValueCollection? _values;
|
||||
|
||||
private readonly TreeSet<KeyValuePair<TKey, TValue>> _set; // Do not rename (binary serialization)
|
||||
```
|
||||
|
||||
Na první pohled máme problém, protože `TreeSet` není `SortedSet`, který by jsme čekali. Když se přesuneme na konec souboru, tak zjistíme, že `TreeSet` je jenom _backward-compatible wrapper_ pro `SortedSet`.
|
||||
|
||||
Přesuneme se k [`SortedSet`](https://github.com/dotnet/runtime/blob/main/src/libraries/System.Collections/src/System/Collections/Generic/SortedSet.cs). A hned ze začátku vidíme:
|
||||
|
||||
```cs
|
||||
// A binary search tree is a red-black tree if it satisfies the following red-black properties:
|
||||
// 1. Every node is either red or black
|
||||
// 2. Every leaf (nil node) is black
|
||||
// 3. If a node is red, the both its children are black
|
||||
// 4. Every simple path from a node to a descendant leaf contains the same number of black nodes
|
||||
//
|
||||
// The basic idea of a red-black tree is to represent 2-3-4 trees as standard BSTs but to add one extra bit of information
|
||||
// per node to encode 3-nodes and 4-nodes.
|
||||
// 4-nodes will be represented as: B
|
||||
// R R
|
||||
//
|
||||
// 3 -node will be represented as: B or B
|
||||
// R B B R
|
||||
//
|
||||
// For a detailed description of the algorithm, take a look at "Algorithms" by Robert Sedgewick.
|
||||
|
||||
internal enum NodeColor : byte
|
||||
{
|
||||
Black,
|
||||
Red
|
||||
}
|
||||
|
||||
internal delegate bool TreeWalkPredicate<T>(SortedSet<T>.Node node);
|
||||
|
||||
internal enum TreeRotation : byte
|
||||
{
|
||||
Left,
|
||||
LeftRight,
|
||||
Right,
|
||||
RightLeft
|
||||
}
|
||||
```
|
||||
|
||||
Vysvětlení v komentáři trochu předbíhá náplň cvičení zaměřeného na B-stromy ;)
|
||||
|
||||
## Vztah mezi množinou a mapou
|
||||
|
||||
Při každé implementaci ve standardní knihovně jsme si mohli všimnout, že strom implementuje vždy jenom jeden typ:
|
||||
|
||||
| Jazyk | Způsob implementace |
|
||||
| ----- | ----------------------------------------------- |
|
||||
| C++ | mapa ukládá dvojice do množiny |
|
||||
| Java | množina ukládá prvky s „dummy“ hodnotou do mapy |
|
||||
| C# | mapa ukládá dvojice do množiny |
|
||||
|
||||
Mapa vyžaduje, aby každý klíč měl přiřazenou právě jednu hodnotu, tedy klíče jsou navzájem mezi sebou unikátní. To nám umožňuje organizovat klíče do množiny, zde ale narazíme na nepříjemný problém spočívající v tom, že musíme do množiny vkladat dvojice prvků: `(key, value)`. Tenhle přístup má ale zásadní problém:
|
||||
|
||||
```py showLineNumbers
|
||||
# let's represent dictionary/map as a set
|
||||
set_of_values = set()
|
||||
|
||||
# let's insert few pairs
|
||||
set_of_values.add((1, 2))
|
||||
set_of_values.add((0, 42))
|
||||
|
||||
# let's set key 1 to value 6
|
||||
set_of_values.add((1, 6))
|
||||
|
||||
set_of_values
|
||||
```
|
||||
|
||||
A dostaneme:
|
||||
|
||||
```
|
||||
{(1, 6), (1, 2), (0, 42)}
|
||||
```
|
||||
|
||||
V jednotlivých implementacích, které jste mohli vidět výše, se využívá nasledující, když:
|
||||
|
||||
- _mapa ukládá dvojice do množiny_: Dvojice je obalená v samostatním typu, který porovnává jenom klíče
|
||||
- _množina ukládá klíče do mapy_: V mapě se ignorují hodnoty přiřazené klíčům
|
6
ib002/09-b-trees/_category_.yaml
Normal file
6
ib002/09-b-trees/_category_.yaml
Normal file
|
@ -0,0 +1,6 @@
|
|||
label: B-trees
|
||||
position: 9
|
||||
link:
|
||||
type: generated-index
|
||||
description: |
|
||||
Materials related to B-trees.
|
6
ib002/10-graphs/_category_.yaml
Normal file
6
ib002/10-graphs/_category_.yaml
Normal file
|
@ -0,0 +1,6 @@
|
|||
label: Graphs
|
||||
position: 10
|
||||
link:
|
||||
type: generated-index
|
||||
description: |
|
||||
Materials related to basic graph algorithms and graph problems.
|
149
ib002/10-graphs/bfs-tree.md
Normal file
149
ib002/10-graphs/bfs-tree.md
Normal file
|
@ -0,0 +1,149 @@
|
|||
---
|
||||
title: Distance boundaries from BFS tree on undirected graphs
|
||||
description: |
|
||||
Short explanation of distance boundaries deduced from a BFS tree.
|
||||
---
|
||||
|
||||
## Introduction
|
||||
|
||||
As we have talked on the seminar, if we construct from some vertex $u$ BFS tree on an undirected graph, we can obtain:
|
||||
|
||||
- lower bound of length of the shortest path between 2 vertices from the _height difference_
|
||||
- upper bound of length of the shortest path between 2 vertices from the _path through the root_
|
||||
|
||||
## Lower bound
|
||||
|
||||
Consider the following graph:
|
||||
|
||||
![BFS graph](/files/ib002/bfs-tree/bfs_graph.svg)
|
||||
|
||||
<details>
|
||||
<summary>Source for the rendered graph</summary>
|
||||
|
||||
```dot showLineNumbers
|
||||
graph {
|
||||
a -- c
|
||||
a -- e
|
||||
|
||||
c -- i
|
||||
c -- b
|
||||
|
||||
e -- j
|
||||
|
||||
i -- d
|
||||
|
||||
b -- h
|
||||
|
||||
d -- h
|
||||
|
||||
h -- j
|
||||
}
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
We run BFS from the vertex $a$ and obtain the following BFS tree:
|
||||
|
||||
![BFS tree](/files/ib002/bfs-tree/bfs_tree.svg)
|
||||
|
||||
<details>
|
||||
<summary>Source for the BFS tree</summary>
|
||||
|
||||
```dot showLineNumbers
|
||||
digraph {
|
||||
a -> c
|
||||
a -> e
|
||||
|
||||
c -> b
|
||||
c -> i
|
||||
|
||||
e -> j
|
||||
|
||||
b -> h
|
||||
|
||||
i -> d
|
||||
}
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
Let's consider pair of vertices $e$ and $h$. For them we can safely lay, from the BFS tree, following properties:
|
||||
|
||||
- lower bound: $2$
|
||||
- upper bound: $4$
|
||||
|
||||
By having a look at the graph we started from, we can see that we have a path ‹$e, j, h$› that has a length 2. Apart from that we can also notice there is another path from $e$ to $h$ and that is ‹$e, a, c, i, d, h$›. And that path has a length of $5$. Doesn't this break our statements at the beginning? (_I'm leaving that as an exercise ;)_)
|
||||
|
||||
## Proof by contradiction
|
||||
|
||||
Let's keep the same graph, but break the lower bound, i.e. I have gotten a lower bound $2$, but „there must be a shorter path“! ;)
|
||||
|
||||
Now the more important question, is there a shorter path in that graph? The answer is no, there's no shorter path than the one with length $2$. So what can we do about it? We'll add an edge to have a shorter path. Now we have gotten a lower bound of $2$, which means the only shorter path we can construct has $1$ edge and that is ‹$e, h$› (no intermediary vertices). Let's do this!
|
||||
|
||||
![BFS tree](/files/ib002/bfs-tree/bfs_graph_with_additional_edge.svg)
|
||||
|
||||
<details>
|
||||
<summary>Source for the BFS graph with an additional edge</summary>
|
||||
|
||||
```dot showLineNumbers
|
||||
graph {
|
||||
a -- c
|
||||
a -- e
|
||||
|
||||
c -- i
|
||||
c -- b
|
||||
|
||||
e -- j
|
||||
e -- h
|
||||
|
||||
i -- d
|
||||
|
||||
b -- h
|
||||
|
||||
d -- h
|
||||
|
||||
h -- j
|
||||
}
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
Okay, so we have a graph that breaks the rule we have laid. However, we need to run BFS to obtain the new BFS tree, since we have changed the graph.
|
||||
|
||||
:::tip
|
||||
|
||||
Do we need to run BFS after **every** change?
|
||||
|
||||
I am leaving that as an exercise ;)
|
||||
|
||||
:::
|
||||
|
||||
![BFS tree](/files/ib002/bfs-tree/bfs_tree_with_additional_edge.svg)
|
||||
|
||||
<details>
|
||||
<summary>Source for the BFS tree</summary>
|
||||
|
||||
```dot showLineNumbers
|
||||
digraph {
|
||||
a -> c
|
||||
a -> e
|
||||
|
||||
c -> b
|
||||
c -> i
|
||||
|
||||
e -> h
|
||||
e -> j
|
||||
|
||||
i -> d
|
||||
}
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
Oops, we have gotten a new BFS tree, that has a height difference of 1.
|
||||
|
||||
:::tip
|
||||
|
||||
Try to think about a way this can be generalized for shortening of minimal length 3 to minimal length 2 ;)
|
||||
|
||||
:::
|
133
ib002/10-graphs/iterative-and-iterators.md
Normal file
133
ib002/10-graphs/iterative-and-iterators.md
Normal file
|
@ -0,0 +1,133 @@
|
|||
---
|
||||
title: Iterative algorithms via iterators
|
||||
description: |
|
||||
Examples of iterative implementations of DFS using iterators.
|
||||
---
|
||||
|
||||
## Introduction
|
||||
|
||||
- [Source code used later on.](pathname:///files/ib002/iterative-and-iterators/)
|
||||
|
||||
As we have talked on the seminar, iterative approach to implementing DFS is not very intuitive and is a very easy way how to create an incorrect implementation.
|
||||
|
||||
On the other hand, we have seen iterative implementation in the exercises and I have also prepared two from which one was similar to recursive implementation without colors from exercises and the other one used features of high-level languages.
|
||||
|
||||
## Different implementations
|
||||
|
||||
### Recursive DFS implementation from exercises without colors
|
||||
|
||||
```
|
||||
FUNCTION VisitedDFS(u, Visited) IS
|
||||
Visited <- Union(Visited, { u })
|
||||
FOR v IN u.successors DO
|
||||
IF v NOT IN Visited THEN
|
||||
Visited <- VisitedDFS(v, Visited)
|
||||
FI
|
||||
OD
|
||||
|
||||
RETURN Visited
|
||||
END
|
||||
```
|
||||
|
||||
This implementation is correct, does the DFS traversal as it should, however it has one „smallish“ downside and that is the time complexity. The usage of set raises the time complexity, of course it is implementation dependant. However in case of either RB-tree or hash-table implementation, we get look-up in time $\mathcal{O}(n)$ for hash-table in worst-case or $\mathcal{O}(\log n)$ for the other in the worst-case. Both are not ideal compared to checking color on vertex.
|
||||
|
||||
### Iterative DFS from the exercises
|
||||
|
||||
```
|
||||
PROCEDURE IterDFS(u)
|
||||
stack <- empty stack
|
||||
Push(stack, (u, 0))
|
||||
u.color <- gray
|
||||
time <- 1
|
||||
u.d <- time
|
||||
|
||||
WHILE NOT Empty(stack) DO
|
||||
(u, k) <- Pop(stack)
|
||||
|
||||
IF k < Length(u.successors) THEN
|
||||
// search is not finished, is pushed back to stack
|
||||
Push(stack, (u, k + 1))
|
||||
|
||||
v <- u.successors[k + 1]
|
||||
IF v.color = white THEN
|
||||
Push(stack, (v, 0))
|
||||
v.color <- gray
|
||||
time <- time + 1
|
||||
v.d <- time
|
||||
FI
|
||||
ELSE
|
||||
// u has no other successors, we can finish the search
|
||||
time <- time + 1
|
||||
u.f <- time
|
||||
u.color <- black
|
||||
FI
|
||||
OD
|
||||
END
|
||||
```
|
||||
|
||||
As we can see, there is some ordering in which we search through the successors. Time complexity is OK, stack holds at most all vertices (they must be on the current path).
|
||||
|
||||
### My iterative with path in stack
|
||||
|
||||
```
|
||||
PROCEDURE DFS(G, start) IS
|
||||
path <- [ start ]
|
||||
time <- 1
|
||||
start.d, start.color <- time, gray
|
||||
|
||||
WHILE NOT Empty(path) DO
|
||||
hasSuccessor <- false
|
||||
FOR successor IN path[-1].successors DO
|
||||
IF successor.color = white THEN
|
||||
hasSuccessor <- true
|
||||
successor.d, successor.color <- ++time, gray
|
||||
path <- Append(path, successor)
|
||||
BREAK
|
||||
FI
|
||||
OD
|
||||
IF NOT hasSuccessor THEN
|
||||
lastVertex <- Pop(path)
|
||||
lastVertex.f, lastVertex.color <- ++time, black
|
||||
FI
|
||||
OD
|
||||
END
|
||||
```
|
||||
|
||||
This approach is similar to the iterative solution from the exercises, but it does not keep the index of the next successor, therefore it always iterates through all of them, which raises the time complexity.
|
||||
|
||||
### My iterative solution with iterators
|
||||
|
||||
On the other hand, we do not actually have to depend on the representation of the graph. In this case, we just _somehow_ obtain the iterator (which yields all of the succesors) and keep it in the stack.
|
||||
|
||||
```
|
||||
PROCEDURE DFS(G, start) IS
|
||||
path <- [ (start, Iterator(start.successors)) ]
|
||||
time <- 1
|
||||
start.d, start.color <- time, gray
|
||||
|
||||
WHILE NOT Empty(path) DO
|
||||
lastVertex, successors <- path[-1]
|
||||
|
||||
IF NOT MoveNext(successors) THEN
|
||||
Pop(path)
|
||||
lastVertex.f, lastVertex.color <- ++time, black
|
||||
ELSE IF successors.Current.color = white THEN
|
||||
nextVertex <- successors.Current
|
||||
nextVertex.d, nextVertex.color <- ++time, gray
|
||||
path <- Append(path, (nextVertex, Iterator(nextVertex.successors)))
|
||||
FI
|
||||
OD
|
||||
END
|
||||
```
|
||||
|
||||
( The way we manipulate with the iterators is closest to the C# implementation. Apart from the `Iterator` thing :) In case you tried to implement it in C++, you would more than likely need to change the check, since you would get first successor right at the beginning )
|
||||
|
||||
So here we don't keep indices, but the iterators. We can also check existence of other successors easily: by the iterator moving after the last successor.
|
||||
|
||||
Closer explanation of the _iterator shenanigans_ follows. In the beginning, either `start` or when pushing new vertex, we are pushing an iterator that points _just before_ the first successor. When populating `lastVertex` and `successors` in the `while`-loop, we take the element from the top of the stack. `MoveNext` returns `true` if there is an element, i.e. successor in this case. If it returns `false` we have nothing to do and we pop the vertex from the stack (also set finishing time and color). If we have successor we check if it has been already visited or not. If has not, we set discovery time and color accordingly, also we add it to stack.
|
||||
|
||||
## Implementation
|
||||
|
||||
In case you want to play around with the code. At the beginning there is a link to the C# implementation that can be used. It has a basic representation of graph and includes BFS/DFS implementation in classes.
|
||||
|
||||
In `Program.cs` you can also find a method that returns graph we used on the seminar.
|
6
ib002/11-paths/_category_.yaml
Normal file
6
ib002/11-paths/_category_.yaml
Normal file
|
@ -0,0 +1,6 @@
|
|||
label: Paths in graphs
|
||||
position: 11
|
||||
link:
|
||||
type: generated-index
|
||||
description: |
|
||||
Materials related to finding paths in graphs.
|
6
ib002/12-hash-tables/_category_.yaml
Normal file
6
ib002/12-hash-tables/_category_.yaml
Normal file
|
@ -0,0 +1,6 @@
|
|||
label: Hash tables
|
||||
position: 12
|
||||
link:
|
||||
type: generated-index
|
||||
description: |
|
||||
Materials related to hash tables.
|
5
ib015/00-intro-ib015.md
Normal file
5
ib015/00-intro-ib015.md
Normal file
|
@ -0,0 +1,5 @@
|
|||
---
|
||||
id: ib015-intro
|
||||
title: Introduction
|
||||
slug: /intro
|
||||
---
|
5
ib110/00-intro-ib110.md
Normal file
5
ib110/00-intro-ib110.md
Normal file
|
@ -0,0 +1,5 @@
|
|||
---
|
||||
id: ib110-intro
|
||||
title: Introduction
|
||||
slug: /intro
|
||||
---
|
12
makefile
Normal file
12
makefile
Normal file
|
@ -0,0 +1,12 @@
|
|||
dev:
|
||||
URL=http://localhost BASE_URL=/ npm run start
|
||||
|
||||
deploy-aisa:
|
||||
URL=https://fi.muni.cz BASE_URL=~xfocko/ib002/ npm run build
|
||||
rsync -avzrlpptv --delete build/ aisa:~/public_html/ib002/
|
||||
|
||||
deploy-poincare:
|
||||
URL=https://fi.mfocko.xyz BASE_URL=/ npm run build
|
||||
rsync -avzrlpptv --delete build/ poincare:~/public_html/fi/
|
||||
|
||||
.PHONY: deploy-aisa deploy-poincare
|
21476
package-lock.json
generated
Normal file
21476
package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load diff
47
package.json
Normal file
47
package.json
Normal file
|
@ -0,0 +1,47 @@
|
|||
{
|
||||
"name": "fi",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"docusaurus": "docusaurus",
|
||||
"start": "docusaurus start",
|
||||
"build": "docusaurus build",
|
||||
"swizzle": "docusaurus swizzle",
|
||||
"deploy": "docusaurus deploy",
|
||||
"clear": "docusaurus clear",
|
||||
"serve": "docusaurus serve",
|
||||
"write-translations": "docusaurus write-translations",
|
||||
"write-heading-ids": "docusaurus write-heading-ids"
|
||||
},
|
||||
"dependencies": {
|
||||
"@docusaurus/core": "2.2.0",
|
||||
"@docusaurus/preset-classic": "2.2.0",
|
||||
"@mdx-js/react": "^1.6.22",
|
||||
"clsx": "^1.2.1",
|
||||
"dotenv": "^16.0.3",
|
||||
"hast-util-is-element": "^1.1.0",
|
||||
"prism-react-renderer": "^1.3.5",
|
||||
"react": "^17.0.2",
|
||||
"react-dom": "^17.0.2",
|
||||
"rehype-katex": "^5.0.0",
|
||||
"remark-math": "^3.0.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@docusaurus/module-type-aliases": "2.2.0"
|
||||
},
|
||||
"browserslist": {
|
||||
"production": [
|
||||
">0.5%",
|
||||
"not dead",
|
||||
"not op_mini all"
|
||||
],
|
||||
"development": [
|
||||
"last 1 chrome version",
|
||||
"last 1 firefox version",
|
||||
"last 1 safari version"
|
||||
]
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=16.14"
|
||||
}
|
||||
}
|
5
pb071/00-intro-pb071.md
Normal file
5
pb071/00-intro-pb071.md
Normal file
|
@ -0,0 +1,5 @@
|
|||
---
|
||||
id: pb071-intro
|
||||
title: Introduction
|
||||
slug: /intro
|
||||
---
|
49
pb071/bonuses/03.md
Normal file
49
pb071/bonuses/03.md
Normal file
|
@ -0,0 +1,49 @@
|
|||
---
|
||||
id: seminar-03
|
||||
title: 3rd seminar
|
||||
description: |
|
||||
Select sort implementation on arrays.
|
||||
---
|
||||
|
||||
This assignment has two versions. For the light version you can get 0.5 K₡. For
|
||||
the _full fat_ one 1 K₡. **You can choose only one of them**.
|
||||
|
||||
To both of them you are given some basic tests. You can also have a look at the
|
||||
code used by the tests and use it to your advantage.
|
||||
|
||||
Details can be found in the doxygen comments included in the source files.
|
||||
|
||||
## Light version (`main_light.c`)
|
||||
|
||||
[Source](pathname:///files/pb071/bonuses/03/main_light.c)
|
||||
|
||||
For the light version you have 3 functions to finish:
|
||||
|
||||
1. `swap` - that swaps two ints passed by pointers.
|
||||
2. `maximum` - that returns index of the biggest `int` in the array.
|
||||
3. `select_sort` - that sorts passed array using Select Sort.
|
||||
|
||||
## Full fat version (`main.c`)
|
||||
|
||||
[Source](pathname:///files/pb071/bonuses/03/main.c)
|
||||
|
||||
For the full fat version you have 4 functions to implement:
|
||||
|
||||
1. `swap` - that swaps two variables passed by pointers.
|
||||
2. `maximum` - that returns index of the biggest element in the array using the
|
||||
comparator.
|
||||
3. `select_sort` - that sorts passed array using Select Sort.
|
||||
4. `int_comparator` - that is used for generic sort and maximum
|
||||
|
||||
To 2nd and 3rd function you are given a pseudocode that you can use to implement
|
||||
it.
|
||||
|
||||
## Submitting
|
||||
|
||||
Ideally submit the assignment through the merge request. Step-by-step tutorial is
|
||||
present [here](../mr). For setting assignee my xlogin is `xfocko`.
|
||||
|
||||
In case you do not want to experiment on GitLab, send me the source code via email,
|
||||
but please prefix subject with: `[PB071/14][seminar-03]`
|
||||
|
||||
Deadline for the submission of the bonus is **March 27th 24:00**.
|
165
pb071/bonuses/04.md
Normal file
165
pb071/bonuses/04.md
Normal file
|
@ -0,0 +1,165 @@
|
|||
---
|
||||
id: seminar-04
|
||||
title: 4th seminar
|
||||
description: |
|
||||
Robot in a maze.
|
||||
---
|
||||
|
||||
For this bonus you can get 1.5 K₡ and another 0.5 K₡ for the bonus part of it.
|
||||
|
||||
[Source](pathname://files/pb071/bonuses/04/)
|
||||
|
||||
## Introduction
|
||||
|
||||
In this task you are given a 2D map for a robot. The map contains multiple markers:
|
||||
|
||||
- `^v<>` - which denote the directions the robot will be facing when he steps into
|
||||
the cell or starts on it.
|
||||
- `K` - denotes the key.
|
||||
- `T` - denotes the treasure.
|
||||
|
||||
In case robot lands at the beginning on unknown field, e.g. `.` in the tests, he
|
||||
faces the direction that is given through the parameter.
|
||||
|
||||
Your task is to write the `walk` function that returns end result of the walk.
|
||||
Walk can end in multiple ways:
|
||||
|
||||
- `FOUND_TREASURE` - when you find the treasure
|
||||
- `FOUND_KEY` - when you find the key
|
||||
- `OUT_OF_BOUNDS` - when the robot falls off the map
|
||||
- `INFINITE_LOOP` - in case you will implement the bonus
|
||||
- `NONE` - which is used right now as a default return in the skeleton, has no meaning
|
||||
later on
|
||||
|
||||
## Hard requirement
|
||||
|
||||
There is only one hard requirement that tests cannot check.
|
||||
|
||||
**You are not allowed to use any indexing related to map or your current position**
|
||||
**in your implementation.**
|
||||
|
||||
Reason for this requirement is for you to get used to working with pointers. And
|
||||
for the implementation of this task it is much easier to use just the pointers.
|
||||
|
||||
## Example of run
|
||||
|
||||
For a better understanding of your task, I will describe a simple walk with corresponding
|
||||
function call.
|
||||
|
||||
```c
|
||||
const char *map = (
|
||||
">.v"
|
||||
".K<"
|
||||
"..."
|
||||
);
|
||||
|
||||
walk(map, &map[6], '^', 3, 3);
|
||||
```
|
||||
|
||||
For this call, you should return `FOUND_KEY`. Let us walk through the walk ;)
|
||||
|
||||
1. Robot is placed at the bottom left corner, there is no direction specified, so
|
||||
he follows the direction given by parameter (upwards, denoted as `N`(orth),
|
||||
so that we can differentiate markers on the map with the robot when using printing
|
||||
function).
|
||||
|
||||
```
|
||||
>.v
|
||||
.K<
|
||||
N..
|
||||
```
|
||||
|
||||
2. Moves up:
|
||||
|
||||
```
|
||||
>.v
|
||||
NK<
|
||||
...
|
||||
```
|
||||
|
||||
3. Moves up (now covers `>`), changes direction to right:
|
||||
|
||||
```
|
||||
E.v
|
||||
.K<
|
||||
...
|
||||
```
|
||||
|
||||
4. Moves to right:
|
||||
|
||||
```
|
||||
>Ev
|
||||
.K<
|
||||
...
|
||||
```
|
||||
|
||||
5. Moves to right, faces south:
|
||||
|
||||
```
|
||||
>.S
|
||||
.K<
|
||||
...
|
||||
```
|
||||
|
||||
6. Moves down, faces west:
|
||||
|
||||
```
|
||||
>.v
|
||||
.KW
|
||||
...
|
||||
```
|
||||
|
||||
7. Moves left, founds key, returns `FOUND_KEY`:
|
||||
|
||||
```
|
||||
>.v
|
||||
.W<
|
||||
...
|
||||
```
|
||||
|
||||
## Bonus part
|
||||
|
||||
For the bonus part you are supposed to return `INFINITE_LOOP` in case the robot
|
||||
is stuck in the infinite loop. There are three tests for it. If you pass only the
|
||||
easy and medium one, you can get 0.25 K₡ for doing your best and trying it out. :)
|
||||
|
||||
## Easter eggs
|
||||
|
||||
- Statistics
|
||||
|
||||
| Language | Files | Lines | Blanks | Comments | Code | Complexity |
|
||||
| ---------------- | ----: | ----: | -----: | -------: | ---: | ---------: |
|
||||
| _C_ | 4 | 458 | 34 | 58 | 366 | 33 |
|
||||
| `test_maze.c` | | 225 | 9 | 0 | 216 | 4 |
|
||||
| `sol.maze.c` | | 141 | 15 | 28 | 98 | 24 |
|
||||
| `maze.c` | | 84 | 8 | 30 | 46 | 5 |
|
||||
| `main.c` | | 8 | 2 | 0 | 6 | 0 |
|
||||
| _C Header_ | 1 | 33 | 3 | 19 | 11 | 0 |
|
||||
| `maze.h` | | 33 | 3 | 19 | 11 | 0 |
|
||||
| _CMake_ | 1 | 25 | 4 | 6 | 15 | 2 |
|
||||
| `CMakeLists.txt` | | 25 | 4 | 6 | 15 | 2 |
|
||||
| **Total** | 6 | 516 | 41 | 83 | 392 | 35 |
|
||||
|
||||
- Majority of the line count in solution is caused by the formatting :)
|
||||
- Included headers can be interpreted as hints, same goes for the unimplemented
|
||||
`static` functions which you can use, but **are not required**.
|
||||
- Given `CMakeLists.txt` will generate 2 binaries, `test_maze` and `maze`.
|
||||
- `test_maze` runs the tests you are given.
|
||||
- `maze` runs the `main.c`, where you can debug, print mazes and whatever else
|
||||
you want.
|
||||
- I keep only one copy of `cut.h` in my repository, so you need to download it from
|
||||
[here](https://gitlab.fi.muni.cz/pb071/cut/-/jobs/159010/artifacts/file/1header/cut.h) and place it into the directory where you have your source code.
|
||||
- I would recommend cloning this repository and copying the `maze` directory to
|
||||
your own repository, since there are multiple files and it may be easier for you.
|
||||
|
||||
In case you have any questions, feel free to reach out to me.
|
||||
|
||||
## Submitting
|
||||
|
||||
Ideally submit the assignment through the merge request. Step-by-step tutorial is
|
||||
present [here](../mr). For setting assignee my xlogin is `xfocko`.
|
||||
|
||||
In case you do not want to experiment on GitLab, send me the source code via email,
|
||||
but please prefix subject with: `[PB071/14][seminar-04]`
|
||||
|
||||
Deadline for the submission of the bonus is **April 5th 24:00**.
|
169
pb071/bonuses/05-06.md
Normal file
169
pb071/bonuses/05-06.md
Normal file
|
@ -0,0 +1,169 @@
|
|||
---
|
||||
id: seminar-05-06
|
||||
title: 5th and 6th seminar
|
||||
description: |
|
||||
200IQ encryption.
|
||||
---
|
||||
|
||||
For this bonus you can get at maximum 2.5 K₡.
|
||||
|
||||
[Source](pathname:///files/pb071/bonuses/05-06/)
|
||||
|
||||
## Introduction
|
||||
|
||||
In this bonus you will implement few functions that will be used together for
|
||||
implementing a very special cipher.
|
||||
|
||||
### Task no. 1: Reverse (0.5 K₡)
|
||||
|
||||
Write a function `char* reverse(const char* text)` that returns copy of the input
|
||||
string in reversed order (also uppercase).
|
||||
|
||||
In case you are given `NULL`, return `NULL`.
|
||||
|
||||
Example (more in tests):
|
||||
|
||||
```c
|
||||
char* reversed = reverse("Hello world!");
|
||||
|
||||
printf("%s\n", reversed);
|
||||
// "!DLROW OLLEH"
|
||||
|
||||
if (reversed != NULL) {
|
||||
free(reversed);
|
||||
}
|
||||
```
|
||||
|
||||
### Task no. 2: Vigenère (0.5 K₡)
|
||||
|
||||
Vigenère cipher is similar to the Caesar cipher, but you also have a key that is
|
||||
used for encrypting (or decrypting).
|
||||
|
||||
Your task is to write two functions:
|
||||
|
||||
- `char* vigenere_encrypt(const char* key, const char* text)` for encrypting
|
||||
- `char* vigenere_decrypt(const char* key, const char* text)` for decrypting
|
||||
|
||||
In both of those you should return uppercase characters.
|
||||
|
||||
Meaning of the parameters you are given:
|
||||
|
||||
- `key` - String that represents key that is used for \*crypting. It consists of
|
||||
one word and can have only characters of the alphabet. Does not matter if they
|
||||
are uppercase or lowercase.
|
||||
- `text` - String that is to be \*crypted.
|
||||
|
||||
Function returns address of the encrypted (or decrypted) string. Or `NULL` in case
|
||||
error occurs.
|
||||
|
||||
Example:
|
||||
|
||||
```c
|
||||
char *encrypted = vigenere_encrypt("CoMPuTeR", "Hello world!");
|
||||
|
||||
printf("%s\n", encrypted);
|
||||
// "JSXAI PSINR!"
|
||||
|
||||
if (encrypted != NULL) {
|
||||
free(encrypted)
|
||||
}
|
||||
```
|
||||
|
||||
#### Bonus part (0.5 K₡)
|
||||
|
||||
If you can utilize helper function that would do both encrypting and decrypting,
|
||||
you can gain 0.5 K₡.
|
||||
|
||||
Usage of `true`/`false` to decide path in code is prohibited. It leads to merging
|
||||
of both functions into one. Point of this part is to discover a way to do this
|
||||
generically in such way that there are no separate paths for one or the other. One
|
||||
function with no branching for both of them, parametrization is your friend :)
|
||||
|
||||
### Task no. 3: Bit madness (0.5 K₡)
|
||||
|
||||
This is a state of the art crypto. Please do not share :)
|
||||
|
||||
For encrypting:
|
||||
|
||||
1. Split the character that is to be encrypted in halves (4 and 4 bits each).
|
||||
2. Bits in 1st half are to be split into pairs. Swap bits in those pairs.
|
||||
3. Then use the 4 bits that you created in the 2nd step for `XOR` with the other
|
||||
4 bits.
|
||||
|
||||
This simple and ingenious principle will be illustrated on the following example.
|
||||
String we want to encrypt is `Hello world!`. We need to encrypt each letter separately,
|
||||
so we will demonstrate on letter `H`:
|
||||
|
||||
1. Letter `H` is represented in ASCII as `72`.
|
||||
|
||||
`72` represented in binary is: `01001000`. So first 4 bits are: `0100` and last
|
||||
4 bits are `1000`.
|
||||
|
||||
2. First half of bits (`0100`) consists of 2 pairs (`01` and `00`) which we swap
|
||||
(`01 ~> 10` and `00 ~> 00`). That way we get `1000`.
|
||||
|
||||
3. That half is used for xor with the other 4 bits:
|
||||
|
||||
```
|
||||
1000 // second half
|
||||
XOR 1000 // first half after 2nd step
|
||||
--------
|
||||
0000
|
||||
```
|
||||
|
||||
4. Now we combine both halves (first one is `1000`, which we got from the 2nd step
|
||||
and second one is `0000`, which we got from the 3rd step) and get `10000000`,
|
||||
which is encrypted character `H` using this method.
|
||||
|
||||
In case of decryption, reverse those steps.
|
||||
|
||||
Your task is to implement functions:
|
||||
|
||||
- `unsigned char* bit_encrypt(const char* text)`
|
||||
- `char* bit_decrypt(const unsigned char* text)`
|
||||
|
||||
Example:
|
||||
|
||||
```c
|
||||
unsigned char* encrypted = bit_encrypt("Hello world!");
|
||||
|
||||
for (int i = 0; i < 12;i++) {
|
||||
printf("%x ", encrypted[i]);
|
||||
//80 9c 95 95 96 11 bc 96 b9 95 9d 10
|
||||
}
|
||||
|
||||
if (encrypted != NULL) {
|
||||
free(encrypted);
|
||||
}
|
||||
```
|
||||
|
||||
### Task no. 4: All combined to BMP (0.5 K₡)
|
||||
|
||||
Authors of the BMP cipher are non-disclosed :)
|
||||
|
||||
Create pair of functions:
|
||||
|
||||
- `unsigned char* bmp_encrypt(const char* key, const char* text)`
|
||||
- `char* bmp_decrypt(const char* key, const unsigned char* text)`
|
||||
|
||||
BMP cipher consists of following steps for encrypting:
|
||||
|
||||
1. Reverse the input string
|
||||
2. Use Vigenere on the string you got from step #1
|
||||
3. Use bit madness on the string you got from step #2
|
||||
|
||||
For decrypting, reverse the steps.
|
||||
|
||||
## Submitting
|
||||
|
||||
In case you have any questions, feel free to reach out to me.
|
||||
|
||||
---
|
||||
|
||||
Ideally submit the assignment through the merge request. Step-by-step tutorial is
|
||||
present [here](../mr). For setting assignee my xlogin is `xfocko`.
|
||||
|
||||
In case you do not want to experiment on GitLab, send me the source code via email,
|
||||
but please prefix subject with: `[PB071/14][seminar-05-06]`
|
||||
|
||||
Deadline for the submission of the bonus is **April 21th 24:00**.
|
160
pb071/bonuses/08.md
Normal file
160
pb071/bonuses/08.md
Normal file
|
@ -0,0 +1,160 @@
|
|||
---
|
||||
id: seminar-08
|
||||
title: 8th seminar
|
||||
description: |
|
||||
Manipulating with files only char-by-char and a magic tree.
|
||||
---
|
||||
|
||||
# 8th seminar bonus assignment
|
||||
|
||||
[Source](pathname:///files/pb071/bonuses/08/)
|
||||
|
||||
## Introduction
|
||||
|
||||
In this bonus you can implement two tasks, one of them has a bonus part with generic
|
||||
solution.
|
||||
|
||||
One is focused on counting ananas or in case of generic version any substring in
|
||||
the file, but with a restriction on the function you use.
|
||||
|
||||
Other one has a more algorithmic spirit.
|
||||
|
||||
For this bonus you can get at maximum 2.5 K₡.
|
||||
|
||||
## Warning
|
||||
|
||||
**DO NOT COMMIT test data** to your own git repository, since the tests include
|
||||
files that exceed 10MB by themselves. Even if they are on separate branch, they
|
||||
take up the space.
|
||||
|
||||
## Testing
|
||||
|
||||
For testing you are provided with python script (requires `click` to be installed:
|
||||
`pip3 install --user click`) and `Makefile` that provides following targets:
|
||||
|
||||
- `check-counting` - runs the `counting` tests
|
||||
- `check-counting-bonus` - runs the `counting` tests with bonus implemented
|
||||
- `check` - runs both `counting` and `counting-bonus` tests
|
||||
- `clean` - removes output files from the test runs
|
||||
|
||||
## Task no. 1: Counting (0.75 K₡)
|
||||
|
||||
Your first task is to make smallish program that counts occurences of specific
|
||||
(or given) word from file and writes the number to other file.
|
||||
|
||||
Usage of the program is:
|
||||
|
||||
```
|
||||
Usage: ./counting <input-file> <output-file> [string-to-be-counted]
|
||||
```
|
||||
|
||||
Arguments that are passed to the program represent:
|
||||
|
||||
- `<input-file>` - path to the file where we count the words
|
||||
- `<output-file>` - path to the file where we output the count
|
||||
- (optional argument) `[string-to-be-counted]` - in case you implement bonus,
|
||||
otherwise we default to word `ananas` ;)
|
||||
|
||||
In skeleton you are given 3 empty, but documented, functions to implement.
|
||||
|
||||
1. `count_anything` - function accepts input file and substring to be counted in
|
||||
the file, returns the count.
|
||||
2. `count_ananas` - same as `count_anything`, but specialized for ananases, the
|
||||
default implementation from the skeleton expects you to implement `count_anything`
|
||||
and therefore it just calls the other function.
|
||||
3. `write_number` - function that writes the number to the file, why would you
|
||||
need the function is explained later :)
|
||||
|
||||
### Requirements
|
||||
|
||||
For manipulation with the files you are only allowed to use `fopen`, `fclose`,
|
||||
`fgetc` and `fputc`. Functions like `fprintf` (except for `stderr` or logging) and
|
||||
`fscanf` are **forbidden**.
|
||||
|
||||
In case you struggle and want to use one of those functions, the solution will be
|
||||
penalized by 50% of points.
|
||||
|
||||
### Bonus part (0.75 K₡)
|
||||
|
||||
Bonus part of this assignment is to implement `count_anything` rather than `count_ananas`.
|
||||
|
||||
> Smaller hint: This task does not need dynamic allocation :) You just need one
|
||||
> good helper function and the right idea ;)
|
||||
|
||||
## Task no. 2: Weird trees (1 K₡)
|
||||
|
||||
In this task we are crossing our paths with _algorithms and data structures_.
|
||||
Your task is to write a program that constructs tree from the file that is given
|
||||
as an argument and pretty-prints it.
|
||||
|
||||
Input file consists of lines, that include `key` and `rank` in form `key;rank`
|
||||
or `nil`. Why would we have `nil` in a file? The file represents pre-order iteration
|
||||
through the tree. Leaves never have rank different than 0, so you can safely assume
|
||||
2 non-existing `nil`s in the input after you read such node ;)
|
||||
|
||||
<table><tr>
|
||||
<td>
|
||||
Example input file
|
||||
|
||||
```
|
||||
8;4
|
||||
5;3
|
||||
3;2
|
||||
2;1
|
||||
1;0
|
||||
nil
|
||||
4;0
|
||||
7;1
|
||||
6;0
|
||||
nil
|
||||
11;2
|
||||
10;1
|
||||
9;0
|
||||
nil
|
||||
12;0
|
||||
```
|
||||
|
||||
</td>
|
||||
<td>
|
||||
Tree it represents
|
||||
|
||||
![tree](/files/pb071/bonuses/08/tree.png)
|
||||
|
||||
</td>
|
||||
</tr></table>
|
||||
|
||||
In this task you are only provided with different trees in the `test-trees` directory.
|
||||
Implementation and format of the pretty-print is totally up to you. :)
|
||||
|
||||
Example of mine for the tree above:
|
||||
|
||||
```
|
||||
8 (rank = 4)
|
||||
+-- 5 (rank = 3)
|
||||
| +-- 3 (rank = 2)
|
||||
| | +-- 2 (rank = 1)
|
||||
| | | +-- 1 (rank = 0)
|
||||
| | +-- 4 (rank = 0)
|
||||
| +-- 7 (rank = 1)
|
||||
| +-- 6 (rank = 0)
|
||||
+-- 11 (rank = 2)
|
||||
+-- 10 (rank = 1)
|
||||
| +-- 9 (rank = 0)
|
||||
+-- 12 (rank = 0)
|
||||
```
|
||||
|
||||
> Can you find out what are those trees? :)
|
||||
|
||||
## Submitting
|
||||
|
||||
In case you have any questions, feel free to reach out to me.
|
||||
|
||||
---
|
||||
|
||||
Ideally submit the assignment through the merge request. Step-by-step tutorial is
|
||||
present [here](../mr). For setting assignee my xlogin is `xfocko`.
|
||||
|
||||
In case you do not want to experiment on GitLab, send me the source code via email,
|
||||
but please prefix subject with: `[PB071/14][seminar-08]`
|
||||
|
||||
Deadline for the submission of the bonus is **May 4th 24:00**.
|
162
pb071/bonuses/10.md
Normal file
162
pb071/bonuses/10.md
Normal file
|
@ -0,0 +1,162 @@
|
|||
---
|
||||
id: seminar-10
|
||||
title: 10th seminar
|
||||
description: |
|
||||
Finding bugs in a hangman.
|
||||
---
|
||||
|
||||
[Source](pathname:///files/pb071/bonuses/10/)
|
||||
|
||||
## Introduction
|
||||
|
||||
For this bonus you are given almost finished project - The Hangman Game. Your
|
||||
task is to try the game, in case you find any bugs point them out and cover as
|
||||
much of the game as possible with tests.
|
||||
|
||||
For this bonus you can get at maximum 2 K₡.
|
||||
|
||||
| Item | Bonus |
|
||||
| ---------------------------------------------- | ----- |
|
||||
| Fixing bugs from failing tests | 0.25 |
|
||||
| `word_guessed` | 0.50 |
|
||||
| Hidden bug | 0.50 |
|
||||
| Extending tests, undetectable bugs or evil bug | 0.37 |
|
||||
| Refactor | 0.38 |
|
||||
|
||||
## Project
|
||||
|
||||
Project consists of 2 source files - `hangman.c` and `main.c`.
|
||||
|
||||
`main.c` is quite short and concise, there is nothing for you to do.
|
||||
|
||||
`hangman.c` contains implementation of the game. In case you feel lost, consult
|
||||
the documentation in `hangman.h` that represents an interface that can be used
|
||||
for implementing the game.
|
||||
|
||||
Apart from those sources this project is a bit more complicated. _Game loop_ is
|
||||
realised via single encapsulated function that complicates the testing. Because
|
||||
of that, there are 2 kinds of tests:
|
||||
|
||||
- _Unit tests_ - that are present in `test_hangman.c` and can be run via:
|
||||
|
||||
```
|
||||
$ make check-unit
|
||||
```
|
||||
|
||||
They cover majorly functions that can be tested easily via testing framework.
|
||||
|
||||
- _Functional tests_ - same as in `seminar-08` and are focused on testing the
|
||||
program as whole. Basic smoke test is already included in `usage` test case.
|
||||
|
||||
They can be run via:
|
||||
|
||||
```
|
||||
$ make check-functional
|
||||
```
|
||||
|
||||
When testing `hangman` function (the game loop), it is suggested to create
|
||||
functional tests.
|
||||
|
||||
When submitting the files for review, please leave out functional tests that
|
||||
were given as a part of the assignment, so that it is easier to navigate, I
|
||||
will drag the common files myself. :)
|
||||
|
||||
> Whole test suite can be run via:
|
||||
>
|
||||
> ```
|
||||
> $ make check
|
||||
> ```
|
||||
|
||||
### Summary of the gameplay
|
||||
|
||||
1. Secret word gets chosen from the file that's path is given as an argument.
|
||||
2. You get 8 guesses.
|
||||
3. Invalid characters don't count.
|
||||
4. Already guessed characters don't count, even if not included in the secret.
|
||||
5. You can guess the whole word at once
|
||||
- If you get it right, you won, game ends.
|
||||
- If you don't get it right, you get to see the secret, game ends.
|
||||
6. In case of end of input, game finishes via force.
|
||||
7. In case of invalid input, no guesses are subtracted, game carries on.
|
||||
8. Letters and words are not case sensitive.
|
||||
|
||||
## Suggested workflow
|
||||
|
||||
As we have talked about on the seminar, I suggest you to follow
|
||||
_Test-Driven Development_
|
||||
in this case.
|
||||
|
||||
![TDD workflow](/files/pb071/bonuses/10/tdd_lifecycle.png)
|
||||
|
||||
In our current scenario we are already in the stage of refactoring and fixing the
|
||||
bugs. Therefore try to follow this succession of steps:
|
||||
|
||||
1. Try to reproduce the bug.
|
||||
2. Create a test that proves the presence of the bug.
|
||||
3. Fix the bug.
|
||||
|
||||
In case you are submitting the bonus via GitLab, it is helpful to commit tests
|
||||
before commiting the fixes, so that it is apparent that the bug is manifested.
|
||||
Example of `git log` (notice that the first line represents latest commit):
|
||||
|
||||
```
|
||||
feat: Implement fizz_buzzer
|
||||
test: Add tests for fizz_buzzer
|
||||
fix: Fix NULL-check in print_name
|
||||
test: Add test for NULL in print_name
|
||||
```
|
||||
|
||||
## Tasks
|
||||
|
||||
As to your tasks, there are multiple things wrong in this project.
|
||||
|
||||
1. There are 2 "bugs" that cannot be detected via tests, i.e. they are not bugs
|
||||
that affect functionality of the game.
|
||||
|
||||
2. There is one evil bug in `get_word`. It is not required to be fixed ;) Assign
|
||||
it the lowest priority.
|
||||
|
||||
3. There are some tests failing. Please try to figure it out, so you have green
|
||||
tests for the rest :)
|
||||
|
||||
4. We have gotten a bug report for `word_guessed`, all we got is
|
||||
|
||||
> doesn't work when there are too many `a`s
|
||||
|
||||
Please try to replicate the bug and create a tests, so we don't get any
|
||||
regression later on.
|
||||
|
||||
5. One hidden bug :) Closely non-specified, we cannot reproduce it and we were
|
||||
drunk while playing the game, so we don't remember a thing. :/
|
||||
|
||||
6. Try to cover as much code via the tests as possible. We are not going to look
|
||||
at the metrics, but DRY is violated a lot, so as a last task try to remove as
|
||||
much of the duplicit code as possible.
|
||||
|
||||
Tests should help you a lot in case there are some regressions.
|
||||
|
||||
---
|
||||
|
||||
In case you wonder why there are always 3 same words in the file with words, it
|
||||
is because of the `get_word` bug. It is not a bug that can be easily fixed, so
|
||||
it is a not requirement at all and you can still get all points for the bonus ;)
|
||||
|
||||
## Dictionary
|
||||
|
||||
- [Functional tests](https://en.wikipedia.org/wiki/Functional_testing)
|
||||
- [Smoke test](https://en.wikipedia.org/wiki/Smoke_testing_%28software%29)
|
||||
- [DRY](https://en.wikipedia.org/wiki/Don%27t_repeat_yourself)
|
||||
|
||||
## Submitting
|
||||
|
||||
In case you have any questions, feel free to reach out to me.
|
||||
|
||||
---
|
||||
|
||||
Ideally submit the assignment through the merge request. Step-by-step tutorial
|
||||
is present [here](../mr). For setting assignee my xlogin is `xfocko`.
|
||||
|
||||
In case you do not want to experiment on GitLab, send me the source code via
|
||||
email, but please prefix subject with: `[PB071/14][seminar-10]`
|
||||
|
||||
Deadline for the submission of the bonus is **May 17 24:00**.
|
6
pb071/bonuses/_category_.yaml
Normal file
6
pb071/bonuses/_category_.yaml
Normal file
|
@ -0,0 +1,6 @@
|
|||
label: Bonuses
|
||||
position: 1
|
||||
link:
|
||||
type: generated-index
|
||||
description: |
|
||||
Bonus assignments for Kontr Coins.
|
136
pb071/mr.md
Normal file
136
pb071/mr.md
Normal file
|
@ -0,0 +1,136 @@
|
|||
---
|
||||
title: Submitting merge requests
|
||||
---
|
||||
|
||||
# Submitting merge requests for review
|
||||
|
||||
This tutorial aims to show you how to follow basic git workflow and submit changes
|
||||
through _Merge Requests_ for review.
|
||||
|
||||
The rudimentary idea behind aims for changes to be present on a separate branch
|
||||
that is supposedly _merged_ into the default branch. Till then changes can be reviewed
|
||||
on _Merge Request_ and additional changes may be made based on the reviews. Once
|
||||
the changes satisfy requirements, the merge request is merged.
|
||||
|
||||
## Tutorial
|
||||
|
||||
> Use this tutorial only for bonus assignments **made by your tutors** or in case
|
||||
> you need to make up for the absence.
|
||||
|
||||
### Step #1 - Starting from the clean repository
|
||||
|
||||
In your repository (either locally or on aisa) type `git status` and check if your
|
||||
repository is clean and you are present on the main branch (`master`, `main` or
|
||||
`trunk`). If you do not know what your default branch is, it is probably `master`
|
||||
and you should not be on any other branch.
|
||||
|
||||
Output of the command should look like this:
|
||||
|
||||
```
|
||||
aisa$ git status
|
||||
On branch master # Or main or trunk.
|
||||
Your branch is up to date with 'origin/master'.
|
||||
|
||||
nothing to commit, working tree clean
|
||||
```
|
||||
|
||||
> In case you are on different branch or there are uncommitted changes,
|
||||
> **do not continue!!!** Clean your repository (commit the changes or discard
|
||||
> them), before you continue.
|
||||
|
||||
### Step #2 - Create new branch
|
||||
|
||||
In your repository write command:
|
||||
|
||||
```
|
||||
aisa$ git checkout -b BRANCH
|
||||
Switched to a new branch 'BRANCH'
|
||||
```
|
||||
|
||||
Instead of `BRANCH` use some reasonable name for the branch. For example if you
|
||||
are working on the seminar from 3rd week, name the branch `seminar-03`.
|
||||
|
||||
### Step #3 - Do the assignment
|
||||
|
||||
Download the skeleton for the seminar assignment, extract and program. For example
|
||||
if you are working on 3rd seminar, you can do so by:
|
||||
|
||||
```
|
||||
aisa$ wget https://www.fi.muni.cz/pb071/seminars/seminar-03/pb071-seminar-03.zip
|
||||
aisa$ unzip pb071-seminar-03.zip
|
||||
# Now you should have directory 'seminar-03'.
|
||||
aisa$ rm pb071-seminar-03.zip
|
||||
aisa$ cd seminar-03
|
||||
# You can work on the assignment.
|
||||
```
|
||||
|
||||
### Step #4 - Commit and upload the changes to GitLab
|
||||
|
||||
The same way you _add_ and _commit_ files for the homework assignments, you do for
|
||||
the seminar.
|
||||
|
||||
Now you can upload the changes to GitLab. `git push` is not enough, since repository
|
||||
on GitLab does not know your new branch. You can solve this by adding arguments:
|
||||
|
||||
```
|
||||
aisa$ git push origin BRANCH
|
||||
...
|
||||
remote: To create a merge request for BRANCH, visit:
|
||||
remote: https://gitlab.fi.muni.cz/login/pb071/merge_requests/new?merge_request%5Bsource_branch%5D=BRANCH
|
||||
...
|
||||
```
|
||||
|
||||
In the output you should have a link for creating a merge request. If you see this
|
||||
link, open it and skip next step.
|
||||
|
||||
### Step #5 - Creating a merge request manually
|
||||
|
||||
1. Open your repository on GitLab.
|
||||
2. On the left panel click on _Merge Requests_.
|
||||
3. Click on _New Merge Request_.
|
||||
4. In _Source branch_ select `login/pb071` and `BRANCH`, which you created.
|
||||
5. In _Target branch_ select `login/pb071` and your default branch you have seen
|
||||
in the output of the first command. (most likely `master`)
|
||||
6. Click on _Compare branches and continue_.
|
||||
|
||||
### Step #6 - Set assignees
|
||||
|
||||
On the page that is opened, please check at the top that you are creating merge
|
||||
request **from** your new branch **to** your default branch (one of `master`, `main`
|
||||
or `trunk`).
|
||||
|
||||
Then in the field _Assignees_ set your tutors based on the seminar group. You can
|
||||
use login for a quick look up.
|
||||
|
||||
In the end click on _Submit merge request_.
|
||||
|
||||
### Step #7 - Return to default branch
|
||||
|
||||
Homework assignments can be submitted only from branches specified in the rules
|
||||
for the course. Because of that, before you do anything else, you should switch
|
||||
back to your default branch.
|
||||
|
||||
First of all, same as in step #1, check that your repository is clean with `git status`.
|
||||
For the sake of safety, do not continue without clean repository. Then with command
|
||||
`git checkout BRANCH` switch to your default branch `BRANCH`.
|
||||
|
||||
If you do not know which branch is your default, try `git branch` that outputs all branches in your repository. Default branch is typically `master`, but can
|
||||
be `main` or `trunk`.
|
||||
|
||||
```
|
||||
aisa$ git status
|
||||
# Check if repository is clean
|
||||
|
||||
# If you know, what is your default branch, you can skip next command.
|
||||
aisa$ git branch
|
||||
# Find the default branch in the list; should be one of the `master`, `main` or
|
||||
# `trunk` and you should not have more than one of those.
|
||||
# In case the list clears the terminal and you cannot see shell prompt, you can
|
||||
# press `q` to quit the pager.
|
||||
|
||||
aisa$ git checkout master
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
Adapted from: https://www.fi.muni.cz/~xlacko1/pb071/mr.html
|
5
pb161/00-intro-pb161.md
Normal file
5
pb161/00-intro-pb161.md
Normal file
|
@ -0,0 +1,5 @@
|
|||
---
|
||||
id: pb161-intro
|
||||
title: Introduction
|
||||
slug: /intro
|
||||
---
|
163
pb161/environment.md
Normal file
163
pb161/environment.md
Normal file
|
@ -0,0 +1,163 @@
|
|||
---
|
||||
title: Environment
|
||||
description: |
|
||||
Suggestions for setting up a local environment for C++ course.
|
||||
---
|
||||
|
||||
## Required tools per OS
|
||||
|
||||
### Windows
|
||||
|
||||
Most likely WSL, VM or VPS. If you consider setting up either of those PITA, then
|
||||
VSCode + SSH to _aisa_ might be the best option for you.
|
||||
|
||||
Either of those will be linux distros, so jump to [next section](#linux).
|
||||
|
||||
### Linux
|
||||
|
||||
Majority (if not all) of the provided materials include makefile (contains absolute
|
||||
path, so in case of linting and compiling, you need to adjust to your needs). You
|
||||
basically need following list of tools:
|
||||
|
||||
- `gcc` - for compiling
|
||||
- `clang-tidy` - for linting (depends on distribution, might be provided with
|
||||
clang itself or in separate package, e.g. `clang-tools-extra`)
|
||||
- `clang-format` - for your own sanity of keeping consistent formatting
|
||||
- `make` - since you are provided makefiles and it might be quickest to set up
|
||||
- `valgrind` - in case you manage to create memory errors in your code
|
||||
|
||||
In case of Fedora it is following set of packages:
|
||||
|
||||
```sh
|
||||
sudo dnf install -y clang clang-tools-extra valgrind gcc make
|
||||
# If you decide to use google test: add `gtest` or `llvm-googletest` for clang
|
||||
```
|
||||
|
||||
### macOS
|
||||
|
||||
In case of macOS you should be able to find all of the packages in brew.sh, except
|
||||
`valgrind`, not sure if you can solve with podman/docker.
|
||||
|
||||
There is also an alterantive to homebrew, that is nixpkgs.
|
||||
|
||||
### nix(OS)
|
||||
|
||||
In case you run nixOS or linux distribution with nixpkgs or you use nixpkgs as a
|
||||
replacement for homebrew on macOS. You should be fine with the following config:
|
||||
|
||||
```nix
|
||||
with import <nixpkgs> {};
|
||||
stdenv.mkDerivation {
|
||||
name = "cppenv";
|
||||
buildInputs = [
|
||||
clang-tools
|
||||
|
||||
gnumake
|
||||
|
||||
gmock # used for google test
|
||||
valgrind # not sure about macOS though
|
||||
];
|
||||
}
|
||||
```
|
||||
|
||||
## IDEs
|
||||
|
||||
Choice of the IDE is mostly up to you, you do not need to use IDE at all ;)
|
||||
|
||||
I would probably recommend VSCode + appropriate extension or CLion if you are used
|
||||
to the JetBrains IDEs.
|
||||
|
||||
## git
|
||||
|
||||
I recommend you using some basic versioning for your code, even though you submit
|
||||
only the sources on _aisa_. There are specific reasons why I suggest it:
|
||||
|
||||
- once you submit the sources for evaluation, there is no way of getting previous
|
||||
submissions
|
||||
|
||||
i.e. if you introduce new bugs between submissions, you cannot compare two of
|
||||
them to pinpoint the bug, this can be easily resolved by _git tags_
|
||||
|
||||
- if you build a _commit, tag and submit_ habit, you might be able to address
|
||||
some of the smaller problems in your sources even before submission; more info
|
||||
in the [pre-commit section](#pre-commit)
|
||||
|
||||
In case you are planning to use git branches for separating different
|
||||
assignments and/or merge requests I suggest you to keep specifications and
|
||||
skeletons on your default branch, since _frag_ on _aisa_ automatically downloads
|
||||
everything that is not present and by that can create conflicts when switching
|
||||
branches.
|
||||
|
||||
Since frag creates a lot of support files (majority of them are dotfiles, i.e.
|
||||
hidden files), I recommend you to use following
|
||||
[gitignore](/files/pb161/environment/gitignore) configuration that should cover most of
|
||||
the scenarios.
|
||||
|
||||
### Reviews on merge requests
|
||||
|
||||
It might be harder to resolve, explain and/or address notes from the review if you
|
||||
get back your source code with notes all over the place, to help with this I offer
|
||||
you reviews on merge requests in GitLab.
|
||||
|
||||
It allows me to comment on your source code with an option for you to reply, so
|
||||
that we can clear any misunderstandings and vague comments if they arise.
|
||||
|
||||
Since I expect most of you to not require this, it might take some time for me
|
||||
to implement tool that would allow it, since the reviews shall be still submitted
|
||||
through _aisa_.
|
||||
|
||||
### pre-commit ([link](https://pre-commit.com/))
|
||||
|
||||
Pre-commit basically allows you to "check" your code before committing. It functions
|
||||
as a git hook, i.e. you want to make a commit, pre-commit checks it before-hand.
|
||||
|
||||
In case of C++ there are few use-cases:
|
||||
|
||||
- formatting
|
||||
- linting
|
||||
- building and/or running tests, in case you feel like masochist
|
||||
|
||||
However this might be a challenging task to implement, since most of the tasks
|
||||
are published from the beginning.
|
||||
|
||||
In case of formatting and linting, there are already existing hooks (there is a
|
||||
list of supported ones on the page), but there is also an option for you setting
|
||||
it up yourself (it is just a matter of specifying command and files it should run
|
||||
on).
|
||||
|
||||
## Testing
|
||||
|
||||
I have tried 2 frameworks for testing, one of them will be probably showcased in
|
||||
lectures. If you have not picked one yet, you can take an inspiration from the
|
||||
following.
|
||||
|
||||
### catch2
|
||||
|
||||
It is quite popular, only one header-file, also might be easier to set up.
|
||||
|
||||
Might feel slow to compile, this can be addressed by having one object file with
|
||||
precompiled `main` for tests, e.g.
|
||||
|
||||
```cpp
|
||||
/* File: catch_main.cpp
|
||||
* Compile it with: g++ $(CXXFLAGS) -c catch_main.cpp
|
||||
*
|
||||
* Once you have source file with tests, e.g. test_something.cpp, compile it in
|
||||
* a similar fashion: g++ $(CXXFLAGS) -c test_something.cpp $(LDLIBS)
|
||||
*
|
||||
* And link them together:
|
||||
* g++ catch_main.o test_something.o -o test_something
|
||||
*
|
||||
* Now you can run ./test_something and if you change it, you do not need to compile
|
||||
* the main again.
|
||||
*/
|
||||
#define CATCH_CONFIG_MAIN
|
||||
#include "catch.hpp"
|
||||
```
|
||||
|
||||
### Google Test
|
||||
|
||||
It is faster compared to catch2, even if you do not precompile the `main`. Might
|
||||
be more complicated to set up, since there are multiple files (it is not one header
|
||||
file). Not very user friendly on _aisa_. However can be installed through package
|
||||
manager.
|
8
sidebars.js
Normal file
8
sidebars.js
Normal file
|
@ -0,0 +1,8 @@
|
|||
// @ts-check
|
||||
|
||||
/** @type {import('@docusaurus/plugin-content-docs').SidebarsConfig} */
|
||||
const sidebars = {
|
||||
autogeneratedBar: [{ type: "autogenerated", dirName: "." }],
|
||||
};
|
||||
|
||||
module.exports = sidebars;
|
60
src/components/HomepageFeatures/index.js
Normal file
60
src/components/HomepageFeatures/index.js
Normal file
|
@ -0,0 +1,60 @@
|
|||
import React from "react";
|
||||
import clsx from "clsx";
|
||||
import styles from "./styles.module.css";
|
||||
|
||||
const FeatureList = [
|
||||
{
|
||||
title: "Content",
|
||||
description: (
|
||||
<>
|
||||
On this page you can find unofficial materials I have written over the
|
||||
course of teaching multiple courses at the FI.
|
||||
</>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: "Source",
|
||||
description: (
|
||||
<>
|
||||
This content can be found as a source at{" "}
|
||||
<a href="https://gitlab.com/mfocko/kb">GitLab</a> or{" "}
|
||||
<a href="https://gitlab.fi.muni.cz/xfocko/kb">FI GitLab</a>.
|
||||
</>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: "Deployment",
|
||||
description: (
|
||||
<>
|
||||
This content is also deployed on{" "}
|
||||
<a href="https://fi.muni.cz/~xfocko/kb">aisa</a> or{" "}
|
||||
<a href="https://fi.mfocko.xyz">poincare</a>.
|
||||
</>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
function Feature({ title, description }) {
|
||||
return (
|
||||
<div className={clsx("col col--4")}>
|
||||
<div className="text--center padding-horiz--md">
|
||||
<h3>{title}</h3>
|
||||
<p>{description}</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function HomepageFeatures() {
|
||||
return (
|
||||
<section className={styles.features}>
|
||||
<div className="container">
|
||||
<div className="row">
|
||||
{FeatureList.map((props, idx) => (
|
||||
<Feature key={idx} {...props} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
11
src/components/HomepageFeatures/styles.module.css
Normal file
11
src/components/HomepageFeatures/styles.module.css
Normal file
|
@ -0,0 +1,11 @@
|
|||
.features {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
padding: 2rem 0;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.featureSvg {
|
||||
height: 200px;
|
||||
width: 200px;
|
||||
}
|
30
src/css/custom.css
Normal file
30
src/css/custom.css
Normal file
|
@ -0,0 +1,30 @@
|
|||
/**
|
||||
* Any CSS included here will be global. The classic template
|
||||
* bundles Infima by default. Infima is a CSS framework designed to
|
||||
* work well for content-centric websites.
|
||||
*/
|
||||
|
||||
/* You can override the default Infima variables here. */
|
||||
:root {
|
||||
--ifm-color-primary: #2e8555;
|
||||
--ifm-color-primary-dark: #29784c;
|
||||
--ifm-color-primary-darker: #277148;
|
||||
--ifm-color-primary-darkest: #205d3b;
|
||||
--ifm-color-primary-light: #33925d;
|
||||
--ifm-color-primary-lighter: #359962;
|
||||
--ifm-color-primary-lightest: #3cad6e;
|
||||
--ifm-code-font-size: 95%;
|
||||
--docusaurus-highlighted-code-line-bg: rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
/* For readability concerns, you should choose a lighter palette in dark mode. */
|
||||
[data-theme="dark"] {
|
||||
--ifm-color-primary: #25c2a0;
|
||||
--ifm-color-primary-dark: #21af90;
|
||||
--ifm-color-primary-darker: #1fa588;
|
||||
--ifm-color-primary-darkest: #1a8870;
|
||||
--ifm-color-primary-light: #29d5b0;
|
||||
--ifm-color-primary-lighter: #32d8b4;
|
||||
--ifm-color-primary-lightest: #4fddbf;
|
||||
--docusaurus-highlighted-code-line-bg: rgba(0, 0, 0, 0.3);
|
||||
}
|
35
src/pages/index.js
Normal file
35
src/pages/index.js
Normal file
|
@ -0,0 +1,35 @@
|
|||
import React from "react";
|
||||
import clsx from "clsx";
|
||||
import useDocusaurusContext from "@docusaurus/useDocusaurusContext";
|
||||
import Layout from "@theme/Layout";
|
||||
import HomepageFeatures from "@site/src/components/HomepageFeatures";
|
||||
|
||||
import styles from "./index.module.css";
|
||||
|
||||
function HomepageHeader() {
|
||||
const { siteConfig } = useDocusaurusContext();
|
||||
return (
|
||||
<header className={clsx("hero hero--primary", styles.heroBanner)}>
|
||||
<div className="container">
|
||||
<h1 className="hero__title">{siteConfig.title}</h1>
|
||||
<p className="hero__subtitle">{siteConfig.tagline}</p>
|
||||
</div>
|
||||
</header>
|
||||
);
|
||||
}
|
||||
|
||||
export default function Home() {
|
||||
const { siteConfig } = useDocusaurusContext();
|
||||
return (
|
||||
<Layout
|
||||
title={`${siteConfig.title}`}
|
||||
description="Additional materials for the course of Algorithms and Data structures I"
|
||||
>
|
||||
<HomepageHeader />
|
||||
|
||||
<main>
|
||||
<HomepageFeatures />
|
||||
</main>
|
||||
</Layout>
|
||||
);
|
||||
}
|
23
src/pages/index.module.css
Normal file
23
src/pages/index.module.css
Normal file
|
@ -0,0 +1,23 @@
|
|||
/**
|
||||
* CSS files with the .module.css suffix will be treated as CSS modules
|
||||
* and scoped locally.
|
||||
*/
|
||||
|
||||
.heroBanner {
|
||||
padding: 4rem 0;
|
||||
text-align: center;
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
@media screen and (max-width: 996px) {
|
||||
.heroBanner {
|
||||
padding: 2rem;
|
||||
}
|
||||
}
|
||||
|
||||
.buttons {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
0
static/.nojekyll
Normal file
0
static/.nojekyll
Normal file
104
static/files/ib002/bfs-tree/bfs_graph.svg
Normal file
104
static/files/ib002/bfs-tree/bfs_graph.svg
Normal file
|
@ -0,0 +1,104 @@
|
|||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
|
||||
<!-- Generated by graphviz version 2.40.1 (20161225.0304)
|
||||
-->
|
||||
<!-- Title: %0 Pages: 1 -->
|
||||
<svg width="189pt" height="404pt" viewBox="0.00 0.00 189.00 404.00" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<g id="graph0" class="graph" transform="scale(1 1) rotate(0) translate(4 400)">
|
||||
<title>%0</title>
|
||||
<polygon fill="#ffffff" stroke="transparent" points="-4,4 -4,-400 185,-400 185,4 -4,4"/>
|
||||
<!-- a -->
|
||||
<g id="node1" class="node">
|
||||
<title>a</title>
|
||||
<ellipse fill="none" stroke="#000000" cx="126" cy="-378" rx="27" ry="18"/>
|
||||
<text text-anchor="middle" x="126" y="-373.8" font-family="Times,serif" font-size="14.00" fill="#000000">a</text>
|
||||
</g>
|
||||
<!-- c -->
|
||||
<g id="node2" class="node">
|
||||
<title>c</title>
|
||||
<ellipse fill="none" stroke="#000000" cx="99" cy="-306" rx="27" ry="18"/>
|
||||
<text text-anchor="middle" x="99" y="-301.8" font-family="Times,serif" font-size="14.00" fill="#000000">c</text>
|
||||
</g>
|
||||
<!-- a--c -->
|
||||
<g id="edge1" class="edge">
|
||||
<title>a--c</title>
|
||||
<path fill="none" stroke="#000000" d="M119.3258,-360.2022C115.1407,-349.0419 109.7679,-334.7143 105.5974,-323.593"/>
|
||||
</g>
|
||||
<!-- e -->
|
||||
<g id="node3" class="node">
|
||||
<title>e</title>
|
||||
<ellipse fill="none" stroke="#000000" cx="154" cy="-162" rx="27" ry="18"/>
|
||||
<text text-anchor="middle" x="154" y="-157.8" font-family="Times,serif" font-size="14.00" fill="#000000">e</text>
|
||||
</g>
|
||||
<!-- a--e -->
|
||||
<g id="edge2" class="edge">
|
||||
<title>a--e</title>
|
||||
<path fill="none" stroke="#000000" d="M129.2182,-360.0337C131.0409,-349.5449 133.2909,-336.0449 135,-324 142.3994,-271.8513 149.0765,-209.9625 152.1748,-180.0161"/>
|
||||
</g>
|
||||
<!-- i -->
|
||||
<g id="node4" class="node">
|
||||
<title>i</title>
|
||||
<ellipse fill="none" stroke="#000000" cx="27" cy="-234" rx="27" ry="18"/>
|
||||
<text text-anchor="middle" x="27" y="-229.8" font-family="Times,serif" font-size="14.00" fill="#000000">i</text>
|
||||
</g>
|
||||
<!-- c--i -->
|
||||
<g id="edge3" class="edge">
|
||||
<title>c--i</title>
|
||||
<path fill="none" stroke="#000000" d="M83.7307,-290.7307C71.512,-278.512 54.4602,-261.4602 42.2473,-249.2473"/>
|
||||
</g>
|
||||
<!-- b -->
|
||||
<g id="node5" class="node">
|
||||
<title>b</title>
|
||||
<ellipse fill="none" stroke="#000000" cx="99" cy="-234" rx="27" ry="18"/>
|
||||
<text text-anchor="middle" x="99" y="-229.8" font-family="Times,serif" font-size="14.00" fill="#000000">b</text>
|
||||
</g>
|
||||
<!-- c--b -->
|
||||
<g id="edge4" class="edge">
|
||||
<title>c--b</title>
|
||||
<path fill="none" stroke="#000000" d="M99,-287.8314C99,-277 99,-263.2876 99,-252.4133"/>
|
||||
</g>
|
||||
<!-- j -->
|
||||
<g id="node6" class="node">
|
||||
<title>j</title>
|
||||
<ellipse fill="none" stroke="#000000" cx="126" cy="-18" rx="27" ry="18"/>
|
||||
<text text-anchor="middle" x="126" y="-13.8" font-family="Times,serif" font-size="14.00" fill="#000000">j</text>
|
||||
</g>
|
||||
<!-- e--j -->
|
||||
<g id="edge5" class="edge">
|
||||
<title>e--j</title>
|
||||
<path fill="none" stroke="#000000" d="M150.5104,-144.0535C145.1449,-116.4592 134.9255,-63.9026 129.5336,-36.1727"/>
|
||||
</g>
|
||||
<!-- d -->
|
||||
<g id="node7" class="node">
|
||||
<title>d</title>
|
||||
<ellipse fill="none" stroke="#000000" cx="36" cy="-162" rx="27" ry="18"/>
|
||||
<text text-anchor="middle" x="36" y="-157.8" font-family="Times,serif" font-size="14.00" fill="#000000">d</text>
|
||||
</g>
|
||||
<!-- i--d -->
|
||||
<g id="edge6" class="edge">
|
||||
<title>i--d</title>
|
||||
<path fill="none" stroke="#000000" d="M29.2711,-215.8314C30.625,-205 32.3391,-191.2876 33.6983,-180.4133"/>
|
||||
</g>
|
||||
<!-- h -->
|
||||
<g id="node8" class="node">
|
||||
<title>h</title>
|
||||
<ellipse fill="none" stroke="#000000" cx="99" cy="-90" rx="27" ry="18"/>
|
||||
<text text-anchor="middle" x="99" y="-85.8" font-family="Times,serif" font-size="14.00" fill="#000000">h</text>
|
||||
</g>
|
||||
<!-- b--h -->
|
||||
<g id="edge7" class="edge">
|
||||
<title>b--h</title>
|
||||
<path fill="none" stroke="#000000" d="M99,-215.7623C99,-188.0633 99,-135.7005 99,-108.0896"/>
|
||||
</g>
|
||||
<!-- d--h -->
|
||||
<g id="edge8" class="edge">
|
||||
<title>d--h</title>
|
||||
<path fill="none" stroke="#000000" d="M49.6701,-146.3771C60.2373,-134.3003 74.7961,-117.6616 85.3566,-105.5924"/>
|
||||
</g>
|
||||
<!-- h--j -->
|
||||
<g id="edge9" class="edge">
|
||||
<title>h--j</title>
|
||||
<path fill="none" stroke="#000000" d="M105.6742,-72.2022C109.8593,-61.0419 115.2321,-46.7143 119.4026,-35.593"/>
|
||||
</g>
|
||||
</g>
|
||||
</svg>
|
After Width: | Height: | Size: 4.2 KiB |
109
static/files/ib002/bfs-tree/bfs_graph_with_additional_edge.svg
Normal file
109
static/files/ib002/bfs-tree/bfs_graph_with_additional_edge.svg
Normal file
|
@ -0,0 +1,109 @@
|
|||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
|
||||
<!-- Generated by graphviz version 2.40.1 (20161225.0304)
|
||||
-->
|
||||
<!-- Title: %0 Pages: 1 -->
|
||||
<svg width="189pt" height="404pt" viewBox="0.00 0.00 189.00 404.00" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<g id="graph0" class="graph" transform="scale(1 1) rotate(0) translate(4 400)">
|
||||
<title>%0</title>
|
||||
<polygon fill="#ffffff" stroke="transparent" points="-4,4 -4,-400 185,-400 185,4 -4,4"/>
|
||||
<!-- a -->
|
||||
<g id="node1" class="node">
|
||||
<title>a</title>
|
||||
<ellipse fill="none" stroke="#000000" cx="126" cy="-378" rx="27" ry="18"/>
|
||||
<text text-anchor="middle" x="126" y="-373.8" font-family="Times,serif" font-size="14.00" fill="#000000">a</text>
|
||||
</g>
|
||||
<!-- c -->
|
||||
<g id="node2" class="node">
|
||||
<title>c</title>
|
||||
<ellipse fill="none" stroke="#000000" cx="99" cy="-306" rx="27" ry="18"/>
|
||||
<text text-anchor="middle" x="99" y="-301.8" font-family="Times,serif" font-size="14.00" fill="#000000">c</text>
|
||||
</g>
|
||||
<!-- a--c -->
|
||||
<g id="edge1" class="edge">
|
||||
<title>a--c</title>
|
||||
<path fill="none" stroke="#000000" d="M119.3258,-360.2022C115.1407,-349.0419 109.7679,-334.7143 105.5974,-323.593"/>
|
||||
</g>
|
||||
<!-- e -->
|
||||
<g id="node3" class="node">
|
||||
<title>e</title>
|
||||
<ellipse fill="none" stroke="#000000" cx="154" cy="-162" rx="27" ry="18"/>
|
||||
<text text-anchor="middle" x="154" y="-157.8" font-family="Times,serif" font-size="14.00" fill="#000000">e</text>
|
||||
</g>
|
||||
<!-- a--e -->
|
||||
<g id="edge2" class="edge">
|
||||
<title>a--e</title>
|
||||
<path fill="none" stroke="#000000" d="M129.2182,-360.0337C131.0409,-349.5449 133.2909,-336.0449 135,-324 142.3994,-271.8513 149.0765,-209.9625 152.1748,-180.0161"/>
|
||||
</g>
|
||||
<!-- i -->
|
||||
<g id="node4" class="node">
|
||||
<title>i</title>
|
||||
<ellipse fill="none" stroke="#000000" cx="27" cy="-234" rx="27" ry="18"/>
|
||||
<text text-anchor="middle" x="27" y="-229.8" font-family="Times,serif" font-size="14.00" fill="#000000">i</text>
|
||||
</g>
|
||||
<!-- c--i -->
|
||||
<g id="edge3" class="edge">
|
||||
<title>c--i</title>
|
||||
<path fill="none" stroke="#000000" d="M83.7307,-290.7307C71.512,-278.512 54.4602,-261.4602 42.2473,-249.2473"/>
|
||||
</g>
|
||||
<!-- b -->
|
||||
<g id="node5" class="node">
|
||||
<title>b</title>
|
||||
<ellipse fill="none" stroke="#000000" cx="99" cy="-234" rx="27" ry="18"/>
|
||||
<text text-anchor="middle" x="99" y="-229.8" font-family="Times,serif" font-size="14.00" fill="#000000">b</text>
|
||||
</g>
|
||||
<!-- c--b -->
|
||||
<g id="edge4" class="edge">
|
||||
<title>c--b</title>
|
||||
<path fill="none" stroke="#000000" d="M99,-287.8314C99,-277 99,-263.2876 99,-252.4133"/>
|
||||
</g>
|
||||
<!-- j -->
|
||||
<g id="node6" class="node">
|
||||
<title>j</title>
|
||||
<ellipse fill="none" stroke="#000000" cx="126" cy="-18" rx="27" ry="18"/>
|
||||
<text text-anchor="middle" x="126" y="-13.8" font-family="Times,serif" font-size="14.00" fill="#000000">j</text>
|
||||
</g>
|
||||
<!-- e--j -->
|
||||
<g id="edge5" class="edge">
|
||||
<title>e--j</title>
|
||||
<path fill="none" stroke="#000000" d="M150.5104,-144.0535C145.1449,-116.4592 134.9255,-63.9026 129.5336,-36.1727"/>
|
||||
</g>
|
||||
<!-- h -->
|
||||
<g id="node7" class="node">
|
||||
<title>h</title>
|
||||
<ellipse fill="none" stroke="#000000" cx="99" cy="-90" rx="27" ry="18"/>
|
||||
<text text-anchor="middle" x="99" y="-85.8" font-family="Times,serif" font-size="14.00" fill="#000000">h</text>
|
||||
</g>
|
||||
<!-- e--h -->
|
||||
<g id="edge6" class="edge">
|
||||
<title>e--h</title>
|
||||
<path fill="none" stroke="#000000" d="M141.5196,-145.6621C132.5186,-133.8788 120.4207,-118.0416 111.431,-106.2733"/>
|
||||
</g>
|
||||
<!-- d -->
|
||||
<g id="node8" class="node">
|
||||
<title>d</title>
|
||||
<ellipse fill="none" stroke="#000000" cx="35" cy="-162" rx="27" ry="18"/>
|
||||
<text text-anchor="middle" x="35" y="-157.8" font-family="Times,serif" font-size="14.00" fill="#000000">d</text>
|
||||
</g>
|
||||
<!-- i--d -->
|
||||
<g id="edge7" class="edge">
|
||||
<title>i--d</title>
|
||||
<path fill="none" stroke="#000000" d="M29.0187,-215.8314C30.2222,-205 31.7458,-191.2876 32.9541,-180.4133"/>
|
||||
</g>
|
||||
<!-- b--h -->
|
||||
<g id="edge8" class="edge">
|
||||
<title>b--h</title>
|
||||
<path fill="none" stroke="#000000" d="M99,-215.7623C99,-188.0633 99,-135.7005 99,-108.0896"/>
|
||||
</g>
|
||||
<!-- h--j -->
|
||||
<g id="edge10" class="edge">
|
||||
<title>h--j</title>
|
||||
<path fill="none" stroke="#000000" d="M105.6742,-72.2022C109.8593,-61.0419 115.2321,-46.7143 119.4026,-35.593"/>
|
||||
</g>
|
||||
<!-- d--h -->
|
||||
<g id="edge9" class="edge">
|
||||
<title>d--h</title>
|
||||
<path fill="none" stroke="#000000" d="M48.887,-146.3771C59.622,-134.3003 74.4119,-117.6616 85.1401,-105.5924"/>
|
||||
</g>
|
||||
</g>
|
||||
</svg>
|
After Width: | Height: | Size: 4.4 KiB |
101
static/files/ib002/bfs-tree/bfs_tree.svg
Normal file
101
static/files/ib002/bfs-tree/bfs_tree.svg
Normal file
|
@ -0,0 +1,101 @@
|
|||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
|
||||
<!-- Generated by graphviz version 2.40.1 (20161225.0304)
|
||||
-->
|
||||
<!-- Title: %0 Pages: 1 -->
|
||||
<svg width="206pt" height="260pt" viewBox="0.00 0.00 206.00 260.00" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<g id="graph0" class="graph" transform="scale(1 1) rotate(0) translate(4 256)">
|
||||
<title>%0</title>
|
||||
<polygon fill="#ffffff" stroke="transparent" points="-4,4 -4,-256 202,-256 202,4 -4,4"/>
|
||||
<!-- a -->
|
||||
<g id="node1" class="node">
|
||||
<title>a</title>
|
||||
<ellipse fill="none" stroke="#000000" cx="135" cy="-234" rx="27" ry="18"/>
|
||||
<text text-anchor="middle" x="135" y="-229.8" font-family="Times,serif" font-size="14.00" fill="#000000">a</text>
|
||||
</g>
|
||||
<!-- c -->
|
||||
<g id="node2" class="node">
|
||||
<title>c</title>
|
||||
<ellipse fill="none" stroke="#000000" cx="99" cy="-162" rx="27" ry="18"/>
|
||||
<text text-anchor="middle" x="99" y="-157.8" font-family="Times,serif" font-size="14.00" fill="#000000">c</text>
|
||||
</g>
|
||||
<!-- a->c -->
|
||||
<g id="edge1" class="edge">
|
||||
<title>a->c</title>
|
||||
<path fill="none" stroke="#000000" d="M126.2854,-216.5708C122.0403,-208.0807 116.8464,-197.6929 112.1337,-188.2674"/>
|
||||
<polygon fill="#000000" stroke="#000000" points="115.237,-186.6477 107.6343,-179.2687 108.976,-189.7782 115.237,-186.6477"/>
|
||||
</g>
|
||||
<!-- e -->
|
||||
<g id="node3" class="node">
|
||||
<title>e</title>
|
||||
<ellipse fill="none" stroke="#000000" cx="171" cy="-162" rx="27" ry="18"/>
|
||||
<text text-anchor="middle" x="171" y="-157.8" font-family="Times,serif" font-size="14.00" fill="#000000">e</text>
|
||||
</g>
|
||||
<!-- a->e -->
|
||||
<g id="edge2" class="edge">
|
||||
<title>a->e</title>
|
||||
<path fill="none" stroke="#000000" d="M143.7146,-216.5708C147.9597,-208.0807 153.1536,-197.6929 157.8663,-188.2674"/>
|
||||
<polygon fill="#000000" stroke="#000000" points="161.024,-189.7782 162.3657,-179.2687 154.763,-186.6477 161.024,-189.7782"/>
|
||||
</g>
|
||||
<!-- b -->
|
||||
<g id="node4" class="node">
|
||||
<title>b</title>
|
||||
<ellipse fill="none" stroke="#000000" cx="27" cy="-90" rx="27" ry="18"/>
|
||||
<text text-anchor="middle" x="27" y="-85.8" font-family="Times,serif" font-size="14.00" fill="#000000">b</text>
|
||||
</g>
|
||||
<!-- c->b -->
|
||||
<g id="edge3" class="edge">
|
||||
<title>c->b</title>
|
||||
<path fill="none" stroke="#000000" d="M83.7307,-146.7307C73.803,-136.803 60.6847,-123.6847 49.5637,-112.5637"/>
|
||||
<polygon fill="#000000" stroke="#000000" points="51.7933,-109.8436 42.2473,-105.2473 46.8436,-114.7933 51.7933,-109.8436"/>
|
||||
</g>
|
||||
<!-- i -->
|
||||
<g id="node5" class="node">
|
||||
<title>i</title>
|
||||
<ellipse fill="none" stroke="#000000" cx="99" cy="-90" rx="27" ry="18"/>
|
||||
<text text-anchor="middle" x="99" y="-85.8" font-family="Times,serif" font-size="14.00" fill="#000000">i</text>
|
||||
</g>
|
||||
<!-- c->i -->
|
||||
<g id="edge4" class="edge">
|
||||
<title>c->i</title>
|
||||
<path fill="none" stroke="#000000" d="M99,-143.8314C99,-136.131 99,-126.9743 99,-118.4166"/>
|
||||
<polygon fill="#000000" stroke="#000000" points="102.5001,-118.4132 99,-108.4133 95.5001,-118.4133 102.5001,-118.4132"/>
|
||||
</g>
|
||||
<!-- j -->
|
||||
<g id="node6" class="node">
|
||||
<title>j</title>
|
||||
<ellipse fill="none" stroke="#000000" cx="171" cy="-90" rx="27" ry="18"/>
|
||||
<text text-anchor="middle" x="171" y="-85.8" font-family="Times,serif" font-size="14.00" fill="#000000">j</text>
|
||||
</g>
|
||||
<!-- e->j -->
|
||||
<g id="edge5" class="edge">
|
||||
<title>e->j</title>
|
||||
<path fill="none" stroke="#000000" d="M171,-143.8314C171,-136.131 171,-126.9743 171,-118.4166"/>
|
||||
<polygon fill="#000000" stroke="#000000" points="174.5001,-118.4132 171,-108.4133 167.5001,-118.4133 174.5001,-118.4132"/>
|
||||
</g>
|
||||
<!-- h -->
|
||||
<g id="node7" class="node">
|
||||
<title>h</title>
|
||||
<ellipse fill="none" stroke="#000000" cx="27" cy="-18" rx="27" ry="18"/>
|
||||
<text text-anchor="middle" x="27" y="-13.8" font-family="Times,serif" font-size="14.00" fill="#000000">h</text>
|
||||
</g>
|
||||
<!-- b->h -->
|
||||
<g id="edge6" class="edge">
|
||||
<title>b->h</title>
|
||||
<path fill="none" stroke="#000000" d="M27,-71.8314C27,-64.131 27,-54.9743 27,-46.4166"/>
|
||||
<polygon fill="#000000" stroke="#000000" points="30.5001,-46.4132 27,-36.4133 23.5001,-46.4133 30.5001,-46.4132"/>
|
||||
</g>
|
||||
<!-- d -->
|
||||
<g id="node8" class="node">
|
||||
<title>d</title>
|
||||
<ellipse fill="none" stroke="#000000" cx="99" cy="-18" rx="27" ry="18"/>
|
||||
<text text-anchor="middle" x="99" y="-13.8" font-family="Times,serif" font-size="14.00" fill="#000000">d</text>
|
||||
</g>
|
||||
<!-- i->d -->
|
||||
<g id="edge7" class="edge">
|
||||
<title>i->d</title>
|
||||
<path fill="none" stroke="#000000" d="M99,-71.8314C99,-64.131 99,-54.9743 99,-46.4166"/>
|
||||
<polygon fill="#000000" stroke="#000000" points="102.5001,-46.4132 99,-36.4133 95.5001,-46.4133 102.5001,-46.4132"/>
|
||||
</g>
|
||||
</g>
|
||||
</svg>
|
After Width: | Height: | Size: 4.6 KiB |
101
static/files/ib002/bfs-tree/bfs_tree_with_additional_edge.svg
Normal file
101
static/files/ib002/bfs-tree/bfs_tree_with_additional_edge.svg
Normal file
|
@ -0,0 +1,101 @@
|
|||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
|
||||
<!-- Generated by graphviz version 2.40.1 (20161225.0304)
|
||||
-->
|
||||
<!-- Title: %0 Pages: 1 -->
|
||||
<svg width="278pt" height="260pt" viewBox="0.00 0.00 278.00 260.00" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<g id="graph0" class="graph" transform="scale(1 1) rotate(0) translate(4 256)">
|
||||
<title>%0</title>
|
||||
<polygon fill="#ffffff" stroke="transparent" points="-4,4 -4,-256 274,-256 274,4 -4,4"/>
|
||||
<!-- a -->
|
||||
<g id="node1" class="node">
|
||||
<title>a</title>
|
||||
<ellipse fill="none" stroke="#000000" cx="135" cy="-234" rx="27" ry="18"/>
|
||||
<text text-anchor="middle" x="135" y="-229.8" font-family="Times,serif" font-size="14.00" fill="#000000">a</text>
|
||||
</g>
|
||||
<!-- c -->
|
||||
<g id="node2" class="node">
|
||||
<title>c</title>
|
||||
<ellipse fill="none" stroke="#000000" cx="99" cy="-162" rx="27" ry="18"/>
|
||||
<text text-anchor="middle" x="99" y="-157.8" font-family="Times,serif" font-size="14.00" fill="#000000">c</text>
|
||||
</g>
|
||||
<!-- a->c -->
|
||||
<g id="edge1" class="edge">
|
||||
<title>a->c</title>
|
||||
<path fill="none" stroke="#000000" d="M126.2854,-216.5708C122.0403,-208.0807 116.8464,-197.6929 112.1337,-188.2674"/>
|
||||
<polygon fill="#000000" stroke="#000000" points="115.237,-186.6477 107.6343,-179.2687 108.976,-189.7782 115.237,-186.6477"/>
|
||||
</g>
|
||||
<!-- e -->
|
||||
<g id="node3" class="node">
|
||||
<title>e</title>
|
||||
<ellipse fill="none" stroke="#000000" cx="171" cy="-162" rx="27" ry="18"/>
|
||||
<text text-anchor="middle" x="171" y="-157.8" font-family="Times,serif" font-size="14.00" fill="#000000">e</text>
|
||||
</g>
|
||||
<!-- a->e -->
|
||||
<g id="edge2" class="edge">
|
||||
<title>a->e</title>
|
||||
<path fill="none" stroke="#000000" d="M143.7146,-216.5708C147.9597,-208.0807 153.1536,-197.6929 157.8663,-188.2674"/>
|
||||
<polygon fill="#000000" stroke="#000000" points="161.024,-189.7782 162.3657,-179.2687 154.763,-186.6477 161.024,-189.7782"/>
|
||||
</g>
|
||||
<!-- b -->
|
||||
<g id="node4" class="node">
|
||||
<title>b</title>
|
||||
<ellipse fill="none" stroke="#000000" cx="27" cy="-90" rx="27" ry="18"/>
|
||||
<text text-anchor="middle" x="27" y="-85.8" font-family="Times,serif" font-size="14.00" fill="#000000">b</text>
|
||||
</g>
|
||||
<!-- c->b -->
|
||||
<g id="edge3" class="edge">
|
||||
<title>c->b</title>
|
||||
<path fill="none" stroke="#000000" d="M83.7307,-146.7307C73.803,-136.803 60.6847,-123.6847 49.5637,-112.5637"/>
|
||||
<polygon fill="#000000" stroke="#000000" points="51.7933,-109.8436 42.2473,-105.2473 46.8436,-114.7933 51.7933,-109.8436"/>
|
||||
</g>
|
||||
<!-- i -->
|
||||
<g id="node5" class="node">
|
||||
<title>i</title>
|
||||
<ellipse fill="none" stroke="#000000" cx="99" cy="-90" rx="27" ry="18"/>
|
||||
<text text-anchor="middle" x="99" y="-85.8" font-family="Times,serif" font-size="14.00" fill="#000000">i</text>
|
||||
</g>
|
||||
<!-- c->i -->
|
||||
<g id="edge4" class="edge">
|
||||
<title>c->i</title>
|
||||
<path fill="none" stroke="#000000" d="M99,-143.8314C99,-136.131 99,-126.9743 99,-118.4166"/>
|
||||
<polygon fill="#000000" stroke="#000000" points="102.5001,-118.4132 99,-108.4133 95.5001,-118.4133 102.5001,-118.4132"/>
|
||||
</g>
|
||||
<!-- h -->
|
||||
<g id="node6" class="node">
|
||||
<title>h</title>
|
||||
<ellipse fill="none" stroke="#000000" cx="171" cy="-90" rx="27" ry="18"/>
|
||||
<text text-anchor="middle" x="171" y="-85.8" font-family="Times,serif" font-size="14.00" fill="#000000">h</text>
|
||||
</g>
|
||||
<!-- e->h -->
|
||||
<g id="edge5" class="edge">
|
||||
<title>e->h</title>
|
||||
<path fill="none" stroke="#000000" d="M171,-143.8314C171,-136.131 171,-126.9743 171,-118.4166"/>
|
||||
<polygon fill="#000000" stroke="#000000" points="174.5001,-118.4132 171,-108.4133 167.5001,-118.4133 174.5001,-118.4132"/>
|
||||
</g>
|
||||
<!-- j -->
|
||||
<g id="node7" class="node">
|
||||
<title>j</title>
|
||||
<ellipse fill="none" stroke="#000000" cx="243" cy="-90" rx="27" ry="18"/>
|
||||
<text text-anchor="middle" x="243" y="-85.8" font-family="Times,serif" font-size="14.00" fill="#000000">j</text>
|
||||
</g>
|
||||
<!-- e->j -->
|
||||
<g id="edge6" class="edge">
|
||||
<title>e->j</title>
|
||||
<path fill="none" stroke="#000000" d="M186.2693,-146.7307C196.197,-136.803 209.3153,-123.6847 220.4363,-112.5637"/>
|
||||
<polygon fill="#000000" stroke="#000000" points="223.1564,-114.7933 227.7527,-105.2473 218.2067,-109.8436 223.1564,-114.7933"/>
|
||||
</g>
|
||||
<!-- d -->
|
||||
<g id="node8" class="node">
|
||||
<title>d</title>
|
||||
<ellipse fill="none" stroke="#000000" cx="99" cy="-18" rx="27" ry="18"/>
|
||||
<text text-anchor="middle" x="99" y="-13.8" font-family="Times,serif" font-size="14.00" fill="#000000">d</text>
|
||||
</g>
|
||||
<!-- i->d -->
|
||||
<g id="edge7" class="edge">
|
||||
<title>i->d</title>
|
||||
<path fill="none" stroke="#000000" d="M99,-71.8314C99,-64.131 99,-54.9743 99,-46.4166"/>
|
||||
<polygon fill="#000000" stroke="#000000" points="102.5001,-46.4132 99,-36.4133 95.5001,-46.4133 102.5001,-46.4132"/>
|
||||
</g>
|
||||
</g>
|
||||
</svg>
|
After Width: | Height: | Size: 4.6 KiB |
142
static/files/ib002/extend/dynlist.c
Normal file
142
static/files/ib002/extend/dynlist.c
Normal file
|
@ -0,0 +1,142 @@
|
|||
#include "dynlist.h"
|
||||
|
||||
#include <stdbool.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
void dynamic_array_init(struct dynamic_array_t *arr, size_t size)
|
||||
{
|
||||
if (arr == NULL)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
arr->data = NULL;
|
||||
arr->count = 0;
|
||||
arr->capacity = 0;
|
||||
arr->size = size;
|
||||
}
|
||||
|
||||
void dynamic_array_destroy(struct dynamic_array_t *arr)
|
||||
{
|
||||
if (arr == NULL)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (arr->data != NULL)
|
||||
{
|
||||
free(arr->data);
|
||||
arr->data = NULL;
|
||||
}
|
||||
arr->count = 0;
|
||||
arr->capacity = 0;
|
||||
}
|
||||
|
||||
void *dynamic_array_at(struct dynamic_array_t *arr, size_t index)
|
||||
{
|
||||
if (arr == NULL || index >= arr->count)
|
||||
{
|
||||
return NULL;
|
||||
}
|
||||
|
||||
return arr->data + index * arr->size;
|
||||
}
|
||||
|
||||
void *dynamic_array_front(struct dynamic_array_t *arr)
|
||||
{
|
||||
if (arr == NULL || arr->count < 1)
|
||||
{
|
||||
return NULL;
|
||||
}
|
||||
|
||||
return arr->data;
|
||||
}
|
||||
|
||||
void *dynamic_array_back(struct dynamic_array_t *arr)
|
||||
{
|
||||
if (arr == NULL || arr->count < 1)
|
||||
{
|
||||
return NULL;
|
||||
}
|
||||
|
||||
return arr->data + (arr->count - 1) * arr->size;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Resize the dynamic array when needed.
|
||||
* @param arr Array to be resized.
|
||||
* @returns <code>true</code> if resizing was successful or array was not resized,
|
||||
* <code>false</code> otherwise.
|
||||
*/
|
||||
static bool dynamic_array_resize(struct dynamic_array_t *arr)
|
||||
{
|
||||
if (arr == NULL || arr->count < arr->capacity)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
size_t new_capacity = arr->capacity ? (arr->capacity * 2) : 16;
|
||||
void *new_data = realloc(arr->data, new_capacity * arr->size);
|
||||
if (new_data == NULL)
|
||||
{
|
||||
// failed to reallocate memory
|
||||
return false;
|
||||
}
|
||||
|
||||
arr->data = new_data;
|
||||
arr->capacity = new_capacity;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool dynamic_array_push_back(struct dynamic_array_t *arr, void *data)
|
||||
{
|
||||
if (arr == NULL || data == NULL)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!dynamic_array_resize(arr))
|
||||
{
|
||||
// failed to reallocate memory
|
||||
return false;
|
||||
}
|
||||
|
||||
memcpy(dynamic_array_at(arr, arr->count), data, arr->size);
|
||||
arr->count++;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
void dynamic_array_pop_back(struct dynamic_array_t *arr)
|
||||
{
|
||||
if (arr == NULL || arr->count < 1)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
arr->count--;
|
||||
}
|
||||
|
||||
void dynamic_array_extend(struct dynamic_array_t *arr, struct dynamic_array_t *src)
|
||||
{
|
||||
if (arr == NULL || src == NULL)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
for (size_t i = 0; i < src->count; i++)
|
||||
{
|
||||
dynamic_array_push_back(arr, dynamic_array_at(src, i));
|
||||
}
|
||||
}
|
||||
|
||||
void dynamic_array_clear(struct dynamic_array_t *arr)
|
||||
{
|
||||
if (arr == NULL)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
arr->count = 0;
|
||||
}
|
76
static/files/ib002/extend/dynlist.h
Normal file
76
static/files/ib002/extend/dynlist.h
Normal file
|
@ -0,0 +1,76 @@
|
|||
#include <stdbool.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
struct dynamic_array_t
|
||||
{
|
||||
char *data;
|
||||
size_t count;
|
||||
size_t capacity;
|
||||
size_t size;
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief Initializes dynamic array. Sets size of single element and zeroes
|
||||
* everything else.
|
||||
* @param arr Array to be initialized.
|
||||
* @param size Size of one element in the array.
|
||||
*/
|
||||
void dynamic_array_init(struct dynamic_array_t *arr, size_t size);
|
||||
|
||||
/**
|
||||
* @brief Destroys dynamic array. Deallocates all the memory and resets fields.
|
||||
* @param arr Array to be destroyed.
|
||||
*/
|
||||
void dynamic_array_destroy(struct dynamic_array_t *arr);
|
||||
|
||||
/**
|
||||
* @brief Returns pointer to the element on the given index.
|
||||
* @param arr Array containing the element.
|
||||
* @param index Index of the element.
|
||||
* @returns Pointer to the element, <code>NULL</code> if index is out of bounds.
|
||||
*/
|
||||
void *dynamic_array_at(struct dynamic_array_t *arr, size_t index);
|
||||
|
||||
/**
|
||||
* @brief Returns pointer to the first element of the array.
|
||||
* @param arr Array containing the element.
|
||||
* @returns Pointer to the first element, <code>NULL</code> if no elements are
|
||||
* present.
|
||||
*/
|
||||
void *dynamic_array_front(struct dynamic_array_t *arr);
|
||||
|
||||
/**
|
||||
* @brief Returns pointer to the last element of the array.
|
||||
* @param arr Array containing the element.
|
||||
* @returns Pointer to the last element, <code>NULL</code> if no elements are
|
||||
* present.
|
||||
*/
|
||||
void *dynamic_array_back(struct dynamic_array_t *arr);
|
||||
|
||||
/**
|
||||
* @brief Adds element to the end of the array.
|
||||
* @param arr Array where the element is to be added.
|
||||
* @param data Pointer to the data, that are to be copied into the array.
|
||||
* @returns <code>true</code> if element added successfully, <code>false</code>
|
||||
* otherwise.
|
||||
*/
|
||||
bool dynamic_array_push_back(struct dynamic_array_t *arr, void *data);
|
||||
|
||||
/**
|
||||
* @brief Removes last element from the array.
|
||||
* @param arr Array from which the last element is to be removed.
|
||||
*/
|
||||
void dynamic_array_pop_back(struct dynamic_array_t *arr);
|
||||
|
||||
/**
|
||||
* @brief Extends array with the elements from another array.
|
||||
* @param arr Array to be extended.
|
||||
* @param src Array from which the elements are copied.
|
||||
*/
|
||||
void dynamic_array_extend(struct dynamic_array_t *arr, struct dynamic_array_t *src);
|
||||
|
||||
/**
|
||||
* @brief Clears out the array.
|
||||
* @param arr Array to be cleared.
|
||||
*/
|
||||
void dynamic_array_clear(struct dynamic_array_t *arr);
|
192
static/files/ib002/extend/rendered.svg
Normal file
192
static/files/ib002/extend/rendered.svg
Normal file
|
@ -0,0 +1,192 @@
|
|||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
|
||||
<!-- Generated by graphviz version 2.40.1 (20161225.0304)
|
||||
-->
|
||||
<!-- Title: G Pages: 1 -->
|
||||
<svg width="638pt" height="209pt" viewBox="0.00 0.00 638.00 208.80" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<g id="graph0" class="graph" transform="scale(1 1) rotate(0) translate(4 204.8)">
|
||||
<title>G</title>
|
||||
<polygon fill="#ffffff" stroke="transparent" points="-4,4 -4,-204.8 634,-204.8 634,4 -4,4"/>
|
||||
<!-- a_node -->
|
||||
<g id="node1" class="node">
|
||||
<title>a_node</title>
|
||||
<polygon fill="none" stroke="#000000" points="211.5,-164.3 211.5,-200.3 418.5,-200.3 418.5,-164.3 211.5,-164.3"/>
|
||||
<text text-anchor="middle" x="223" y="-178.1" font-family="Times,serif" font-size="14.00" fill="#000000">1</text>
|
||||
<polyline fill="none" stroke="#000000" points="234.5,-164.3 234.5,-200.3 "/>
|
||||
<text text-anchor="middle" x="246" y="-178.1" font-family="Times,serif" font-size="14.00" fill="#000000">2</text>
|
||||
<polyline fill="none" stroke="#000000" points="257.5,-164.3 257.5,-200.3 "/>
|
||||
<text text-anchor="middle" x="269" y="-178.1" font-family="Times,serif" font-size="14.00" fill="#000000">3</text>
|
||||
<polyline fill="none" stroke="#000000" points="280.5,-164.3 280.5,-200.3 "/>
|
||||
<text text-anchor="middle" x="292" y="-178.1" font-family="Times,serif" font-size="14.00" fill="#000000">4</text>
|
||||
<polyline fill="none" stroke="#000000" points="303.5,-164.3 303.5,-200.3 "/>
|
||||
<text text-anchor="middle" x="315" y="-178.1" font-family="Times,serif" font-size="14.00" fill="#000000">5</text>
|
||||
<polyline fill="none" stroke="#000000" points="326.5,-164.3 326.5,-200.3 "/>
|
||||
<text text-anchor="middle" x="338" y="-178.1" font-family="Times,serif" font-size="14.00" fill="#000000">6</text>
|
||||
<polyline fill="none" stroke="#000000" points="349.5,-164.3 349.5,-200.3 "/>
|
||||
<text text-anchor="middle" x="361" y="-178.1" font-family="Times,serif" font-size="14.00" fill="#000000">7</text>
|
||||
<polyline fill="none" stroke="#000000" points="372.5,-164.3 372.5,-200.3 "/>
|
||||
<text text-anchor="middle" x="384" y="-178.1" font-family="Times,serif" font-size="14.00" fill="#000000">8</text>
|
||||
<polyline fill="none" stroke="#000000" points="395.5,-164.3 395.5,-200.3 "/>
|
||||
<text text-anchor="middle" x="407" y="-178.1" font-family="Times,serif" font-size="14.00" fill="#000000">9</text>
|
||||
</g>
|
||||
<!-- b_node -->
|
||||
<g id="node2" class="node">
|
||||
<title>b_node</title>
|
||||
<polygon fill="none" stroke="#000000" points="100.5,-74.5 100.5,-110.5 169.5,-110.5 169.5,-74.5 100.5,-74.5"/>
|
||||
<text text-anchor="middle" x="112" y="-88.3" font-family="Times,serif" font-size="14.00" fill="#000000">1</text>
|
||||
<polyline fill="none" stroke="#000000" points="123.5,-74.5 123.5,-110.5 "/>
|
||||
<text text-anchor="middle" x="135" y="-88.3" font-family="Times,serif" font-size="14.00" fill="#000000">2</text>
|
||||
<polyline fill="none" stroke="#000000" points="146.5,-74.5 146.5,-110.5 "/>
|
||||
<text text-anchor="middle" x="158" y="-88.3" font-family="Times,serif" font-size="14.00" fill="#000000">3</text>
|
||||
</g>
|
||||
<!-- a_node->b_node -->
|
||||
<g id="edge1" class="edge">
|
||||
<title>a_node->b_node</title>
|
||||
<path fill="none" stroke="#000000" d="M278.5743,-164.1276C249.7143,-149.7297 209.2985,-129.5667 178.6975,-114.3002"/>
|
||||
<polygon fill="#000000" stroke="#000000" points="180.0501,-111.0637 169.5394,-109.7313 176.9252,-117.3274 180.0501,-111.0637"/>
|
||||
<text text-anchor="middle" x="246.6683" y="-133.2" font-family="Times,serif" font-size="14.00" fill="#000000">B</text>
|
||||
</g>
|
||||
<!-- c_node -->
|
||||
<g id="node3" class="node">
|
||||
<title>c_node</title>
|
||||
<polygon fill="none" stroke="#000000" points="280.5,-74.5 280.5,-110.5 349.5,-110.5 349.5,-74.5 280.5,-74.5"/>
|
||||
<text text-anchor="middle" x="292" y="-88.3" font-family="Times,serif" font-size="14.00" fill="#000000">4</text>
|
||||
<polyline fill="none" stroke="#000000" points="303.5,-74.5 303.5,-110.5 "/>
|
||||
<text text-anchor="middle" x="315" y="-88.3" font-family="Times,serif" font-size="14.00" fill="#000000">5</text>
|
||||
<polyline fill="none" stroke="#000000" points="326.5,-74.5 326.5,-110.5 "/>
|
||||
<text text-anchor="middle" x="338" y="-88.3" font-family="Times,serif" font-size="14.00" fill="#000000">6</text>
|
||||
</g>
|
||||
<!-- a_node->c_node -->
|
||||
<g id="edge2" class="edge">
|
||||
<title>a_node->c_node</title>
|
||||
<path fill="none" stroke="#000000" d="M315,-164.1276C315,-151.7124 315,-135.0106 315,-120.8579"/>
|
||||
<polygon fill="#000000" stroke="#000000" points="318.5001,-120.6453 315,-110.6453 311.5001,-120.6454 318.5001,-120.6453"/>
|
||||
<text text-anchor="middle" x="319.6683" y="-133.2" font-family="Times,serif" font-size="14.00" fill="#000000">C</text>
|
||||
</g>
|
||||
<!-- d_node -->
|
||||
<g id="node4" class="node">
|
||||
<title>d_node</title>
|
||||
<polygon fill="none" stroke="#000000" points="460.5,-74.5 460.5,-110.5 529.5,-110.5 529.5,-74.5 460.5,-74.5"/>
|
||||
<text text-anchor="middle" x="472" y="-88.3" font-family="Times,serif" font-size="14.00" fill="#000000">7</text>
|
||||
<polyline fill="none" stroke="#000000" points="483.5,-74.5 483.5,-110.5 "/>
|
||||
<text text-anchor="middle" x="495" y="-88.3" font-family="Times,serif" font-size="14.00" fill="#000000">8</text>
|
||||
<polyline fill="none" stroke="#000000" points="506.5,-74.5 506.5,-110.5 "/>
|
||||
<text text-anchor="middle" x="518" y="-88.3" font-family="Times,serif" font-size="14.00" fill="#000000">9</text>
|
||||
</g>
|
||||
<!-- a_node->d_node -->
|
||||
<g id="edge3" class="edge">
|
||||
<title>a_node->d_node</title>
|
||||
<path fill="none" stroke="#000000" d="M351.4257,-164.1276C380.2857,-149.7297 420.7015,-129.5667 451.3025,-114.3002"/>
|
||||
<polygon fill="#000000" stroke="#000000" points="453.0748,-117.3274 460.4606,-109.7313 449.9499,-111.0637 453.0748,-117.3274"/>
|
||||
<text text-anchor="middle" x="426.0533" y="-133.2" font-family="Times,serif" font-size="14.00" fill="#000000">D</text>
|
||||
</g>
|
||||
<!-- 1 -->
|
||||
<g id="node5" class="node">
|
||||
<title>1</title>
|
||||
<polygon fill="none" stroke="#000000" points="0,-.5 0,-36.5 54,-36.5 54,-.5 0,-.5"/>
|
||||
<text text-anchor="middle" x="27" y="-14.3" font-family="Times,serif" font-size="14.00" fill="#000000">1</text>
|
||||
</g>
|
||||
<!-- b_node->1 -->
|
||||
<g id="edge4" class="edge">
|
||||
<title>b_node->1</title>
|
||||
<path fill="none" stroke="#000000" d="M108.5802,-74.3976C94.59,-64.8117 77.2236,-52.9125 62.1142,-42.5597"/>
|
||||
<polygon fill="#000000" stroke="#000000" points="63.749,-39.4371 53.5213,-36.672 59.7923,-45.2116 63.749,-39.4371"/>
|
||||
</g>
|
||||
<!-- 2 -->
|
||||
<g id="node6" class="node">
|
||||
<title>2</title>
|
||||
<polygon fill="none" stroke="#000000" points="72,-.5 72,-36.5 126,-36.5 126,-.5 72,-.5"/>
|
||||
<text text-anchor="middle" x="99" y="-14.3" font-family="Times,serif" font-size="14.00" fill="#000000">2</text>
|
||||
</g>
|
||||
<!-- b_node->2 -->
|
||||
<g id="edge5" class="edge">
|
||||
<title>b_node->2</title>
|
||||
<path fill="none" stroke="#000000" d="M126.1011,-74.2079C121.916,-65.6051 116.8401,-55.1713 112.2178,-45.6699"/>
|
||||
<polygon fill="#000000" stroke="#000000" points="115.3186,-44.0429 107.7965,-36.5817 109.0239,-47.1052 115.3186,-44.0429"/>
|
||||
</g>
|
||||
<!-- 3 -->
|
||||
<g id="node7" class="node">
|
||||
<title>3</title>
|
||||
<polygon fill="none" stroke="#000000" points="144,-.5 144,-36.5 198,-36.5 198,-.5 144,-.5"/>
|
||||
<text text-anchor="middle" x="171" y="-14.3" font-family="Times,serif" font-size="14.00" fill="#000000">3</text>
|
||||
</g>
|
||||
<!-- b_node->3 -->
|
||||
<g id="edge6" class="edge">
|
||||
<title>b_node->3</title>
|
||||
<path fill="none" stroke="#000000" d="M143.8989,-74.2079C148.084,-65.6051 153.1599,-55.1713 157.7822,-45.6699"/>
|
||||
<polygon fill="#000000" stroke="#000000" points="160.9761,-47.1052 162.2035,-36.5817 154.6814,-44.0429 160.9761,-47.1052"/>
|
||||
</g>
|
||||
<!-- 4 -->
|
||||
<g id="node8" class="node">
|
||||
<title>4</title>
|
||||
<polygon fill="none" stroke="#000000" points="216,-.5 216,-36.5 270,-36.5 270,-.5 216,-.5"/>
|
||||
<text text-anchor="middle" x="243" y="-14.3" font-family="Times,serif" font-size="14.00" fill="#000000">4</text>
|
||||
</g>
|
||||
<!-- c_node->4 -->
|
||||
<g id="edge7" class="edge">
|
||||
<title>c_node->4</title>
|
||||
<path fill="none" stroke="#000000" d="M297.2022,-74.2079C288.3088,-65.0674 277.4042,-53.8599 267.7135,-43.9"/>
|
||||
<polygon fill="#000000" stroke="#000000" points="270.0752,-41.3083 260.593,-36.5817 265.0581,-46.1898 270.0752,-41.3083"/>
|
||||
</g>
|
||||
<!-- 5 -->
|
||||
<g id="node9" class="node">
|
||||
<title>5</title>
|
||||
<polygon fill="none" stroke="#000000" points="288,-.5 288,-36.5 342,-36.5 342,-.5 288,-.5"/>
|
||||
<text text-anchor="middle" x="315" y="-14.3" font-family="Times,serif" font-size="14.00" fill="#000000">5</text>
|
||||
</g>
|
||||
<!-- c_node->5 -->
|
||||
<g id="edge8" class="edge">
|
||||
<title>c_node->5</title>
|
||||
<path fill="none" stroke="#000000" d="M315,-74.2079C315,-65.9635 315,-56.0376 315,-46.8622"/>
|
||||
<polygon fill="#000000" stroke="#000000" points="318.5001,-46.5817 315,-36.5817 311.5001,-46.5818 318.5001,-46.5817"/>
|
||||
</g>
|
||||
<!-- 6 -->
|
||||
<g id="node10" class="node">
|
||||
<title>6</title>
|
||||
<polygon fill="none" stroke="#000000" points="360,-.5 360,-36.5 414,-36.5 414,-.5 360,-.5"/>
|
||||
<text text-anchor="middle" x="387" y="-14.3" font-family="Times,serif" font-size="14.00" fill="#000000">6</text>
|
||||
</g>
|
||||
<!-- c_node->6 -->
|
||||
<g id="edge9" class="edge">
|
||||
<title>c_node->6</title>
|
||||
<path fill="none" stroke="#000000" d="M332.7978,-74.2079C341.6912,-65.0674 352.5958,-53.8599 362.2865,-43.9"/>
|
||||
<polygon fill="#000000" stroke="#000000" points="364.9419,-46.1898 369.407,-36.5817 359.9248,-41.3083 364.9419,-46.1898"/>
|
||||
</g>
|
||||
<!-- 7 -->
|
||||
<g id="node11" class="node">
|
||||
<title>7</title>
|
||||
<polygon fill="none" stroke="#000000" points="432,-.5 432,-36.5 486,-36.5 486,-.5 432,-.5"/>
|
||||
<text text-anchor="middle" x="459" y="-14.3" font-family="Times,serif" font-size="14.00" fill="#000000">7</text>
|
||||
</g>
|
||||
<!-- d_node->7 -->
|
||||
<g id="edge10" class="edge">
|
||||
<title>d_node->7</title>
|
||||
<path fill="none" stroke="#000000" d="M486.1011,-74.2079C481.916,-65.6051 476.8401,-55.1713 472.2178,-45.6699"/>
|
||||
<polygon fill="#000000" stroke="#000000" points="475.3186,-44.0429 467.7965,-36.5817 469.0239,-47.1052 475.3186,-44.0429"/>
|
||||
</g>
|
||||
<!-- 8 -->
|
||||
<g id="node12" class="node">
|
||||
<title>8</title>
|
||||
<polygon fill="none" stroke="#000000" points="504,-.5 504,-36.5 558,-36.5 558,-.5 504,-.5"/>
|
||||
<text text-anchor="middle" x="531" y="-14.3" font-family="Times,serif" font-size="14.00" fill="#000000">8</text>
|
||||
</g>
|
||||
<!-- d_node->8 -->
|
||||
<g id="edge11" class="edge">
|
||||
<title>d_node->8</title>
|
||||
<path fill="none" stroke="#000000" d="M503.8989,-74.2079C508.084,-65.6051 513.1599,-55.1713 517.7822,-45.6699"/>
|
||||
<polygon fill="#000000" stroke="#000000" points="520.9761,-47.1052 522.2035,-36.5817 514.6814,-44.0429 520.9761,-47.1052"/>
|
||||
</g>
|
||||
<!-- 9 -->
|
||||
<g id="node13" class="node">
|
||||
<title>9</title>
|
||||
<polygon fill="none" stroke="#000000" points="576,-.5 576,-36.5 630,-36.5 630,-.5 576,-.5"/>
|
||||
<text text-anchor="middle" x="603" y="-14.3" font-family="Times,serif" font-size="14.00" fill="#000000">9</text>
|
||||
</g>
|
||||
<!-- d_node->9 -->
|
||||
<g id="edge12" class="edge">
|
||||
<title>d_node->9</title>
|
||||
<path fill="none" stroke="#000000" d="M521.4198,-74.3976C535.41,-64.8117 552.7764,-52.9125 567.8858,-42.5597"/>
|
||||
<polygon fill="#000000" stroke="#000000" points="570.2077,-45.2116 576.4787,-36.672 566.251,-39.4371 570.2077,-45.2116"/>
|
||||
</g>
|
||||
</g>
|
||||
</svg>
|
After Width: | Height: | Size: 11 KiB |
206
static/files/ib002/iterative-and-iterators/.editorconfig
Normal file
206
static/files/ib002/iterative-and-iterators/.editorconfig
Normal file
|
@ -0,0 +1,206 @@
|
|||
# Remove the line below if you want to inherit .editorconfig settings from higher directories
|
||||
root = true
|
||||
|
||||
# C# files
|
||||
[*.cs]
|
||||
|
||||
#### Core EditorConfig Options ####
|
||||
|
||||
# Indentation and spacing
|
||||
indent_size = 4
|
||||
indent_style = space
|
||||
tab_width = 4
|
||||
|
||||
# New line preferences
|
||||
end_of_line = lf
|
||||
insert_final_newline = true
|
||||
|
||||
#### .NET Coding Conventions ####
|
||||
|
||||
# Organize usings
|
||||
dotnet_separate_import_directive_groups = false
|
||||
dotnet_sort_system_directives_first = false
|
||||
file_header_template = unset
|
||||
|
||||
# this. and Me. preferences
|
||||
dotnet_style_qualification_for_event = false:silent
|
||||
dotnet_style_qualification_for_field = false:silent
|
||||
dotnet_style_qualification_for_method = false:silent
|
||||
dotnet_style_qualification_for_property = false:silent
|
||||
|
||||
# Language keywords vs BCL types preferences
|
||||
dotnet_style_predefined_type_for_locals_parameters_members = true:silent
|
||||
dotnet_style_predefined_type_for_member_access = true:silent
|
||||
|
||||
# Parentheses preferences
|
||||
dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity:silent
|
||||
dotnet_style_parentheses_in_other_binary_operators = always_for_clarity:silent
|
||||
dotnet_style_parentheses_in_other_operators = never_if_unnecessary:silent
|
||||
dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity:silent
|
||||
|
||||
# Modifier preferences
|
||||
dotnet_style_require_accessibility_modifiers = for_non_interface_members:silent
|
||||
|
||||
# Expression-level preferences
|
||||
dotnet_style_coalesce_expression = true:suggestion
|
||||
dotnet_style_collection_initializer = true:suggestion
|
||||
dotnet_style_explicit_tuple_names = true:suggestion
|
||||
dotnet_style_null_propagation = true:suggestion
|
||||
dotnet_style_object_initializer = true:suggestion
|
||||
dotnet_style_operator_placement_when_wrapping = beginning_of_line
|
||||
dotnet_style_prefer_auto_properties = true:silent
|
||||
dotnet_style_prefer_compound_assignment = true:suggestion
|
||||
dotnet_style_prefer_conditional_expression_over_assignment = true:silent
|
||||
dotnet_style_prefer_conditional_expression_over_return = true:silent
|
||||
dotnet_style_prefer_inferred_anonymous_type_member_names = true:suggestion
|
||||
dotnet_style_prefer_inferred_tuple_names = true:suggestion
|
||||
dotnet_style_prefer_is_null_check_over_reference_equality_method = true:suggestion
|
||||
dotnet_style_prefer_simplified_boolean_expressions = true:suggestion
|
||||
dotnet_style_prefer_simplified_interpolation = true:suggestion
|
||||
|
||||
# Field preferences
|
||||
dotnet_style_readonly_field = true:suggestion
|
||||
|
||||
# Parameter preferences
|
||||
dotnet_code_quality_unused_parameters = all:suggestion
|
||||
|
||||
# Suppression preferences
|
||||
dotnet_remove_unnecessary_suppression_exclusions = none
|
||||
|
||||
#### C# Coding Conventions ####
|
||||
|
||||
# var preferences
|
||||
csharp_style_var_elsewhere = false:silent
|
||||
csharp_style_var_for_built_in_types = false:silent
|
||||
csharp_style_var_when_type_is_apparent = false:silent
|
||||
|
||||
# Expression-bodied members
|
||||
csharp_style_expression_bodied_accessors = true:silent
|
||||
csharp_style_expression_bodied_constructors = false:silent
|
||||
csharp_style_expression_bodied_indexers = true:silent
|
||||
csharp_style_expression_bodied_lambdas = true:silent
|
||||
csharp_style_expression_bodied_local_functions = false:silent
|
||||
csharp_style_expression_bodied_methods = false:silent
|
||||
csharp_style_expression_bodied_operators = false:silent
|
||||
csharp_style_expression_bodied_properties = true:silent
|
||||
|
||||
# Pattern matching preferences
|
||||
csharp_style_pattern_matching_over_as_with_null_check = true:suggestion
|
||||
csharp_style_pattern_matching_over_is_with_cast_check = true:suggestion
|
||||
csharp_style_prefer_not_pattern = true:suggestion
|
||||
csharp_style_prefer_pattern_matching = true:silent
|
||||
csharp_style_prefer_switch_expression = true:suggestion
|
||||
|
||||
# Null-checking preferences
|
||||
csharp_style_conditional_delegate_call = true:suggestion
|
||||
|
||||
# Modifier preferences
|
||||
csharp_prefer_static_local_function = true:suggestion
|
||||
csharp_preferred_modifier_order = public,private,protected,internal,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,volatile,async:silent
|
||||
|
||||
# Code-block preferences
|
||||
csharp_prefer_braces = true:silent
|
||||
csharp_prefer_simple_using_statement = true:suggestion
|
||||
|
||||
# Expression-level preferences
|
||||
csharp_prefer_simple_default_expression = true:suggestion
|
||||
csharp_style_deconstructed_variable_declaration = true:suggestion
|
||||
csharp_style_inlined_variable_declaration = true:suggestion
|
||||
csharp_style_pattern_local_over_anonymous_function = true:suggestion
|
||||
csharp_style_prefer_index_operator = true:suggestion
|
||||
csharp_style_prefer_range_operator = true:suggestion
|
||||
csharp_style_throw_expression = true:suggestion
|
||||
csharp_style_unused_value_assignment_preference = discard_variable:suggestion
|
||||
csharp_style_unused_value_expression_statement_preference = discard_variable:silent
|
||||
|
||||
# 'using' directive preferences
|
||||
csharp_using_directive_placement = inside_namespace:silent
|
||||
|
||||
#### C# Formatting Rules ####
|
||||
|
||||
# New line preferences
|
||||
csharp_new_line_before_catch = false
|
||||
csharp_new_line_before_else = false
|
||||
csharp_new_line_before_finally = false
|
||||
csharp_new_line_before_members_in_anonymous_types = false
|
||||
csharp_new_line_before_members_in_object_initializers = false
|
||||
csharp_new_line_before_open_brace = none
|
||||
csharp_new_line_between_query_expression_clauses = true
|
||||
|
||||
# Indentation preferences
|
||||
csharp_indent_block_contents = true
|
||||
csharp_indent_braces = false
|
||||
csharp_indent_case_contents = true
|
||||
csharp_indent_case_contents_when_block = true
|
||||
csharp_indent_labels = one_less_than_current
|
||||
csharp_indent_switch_labels = true
|
||||
|
||||
# Space preferences
|
||||
csharp_space_after_cast = false
|
||||
csharp_space_after_colon_in_inheritance_clause = true
|
||||
csharp_space_after_comma = true
|
||||
csharp_space_after_dot = false
|
||||
csharp_space_after_keywords_in_control_flow_statements = true
|
||||
csharp_space_after_semicolon_in_for_statement = true
|
||||
csharp_space_around_binary_operators = before_and_after
|
||||
csharp_space_around_declaration_statements = false
|
||||
csharp_space_before_colon_in_inheritance_clause = true
|
||||
csharp_space_before_comma = false
|
||||
csharp_space_before_dot = false
|
||||
csharp_space_before_open_square_brackets = false
|
||||
csharp_space_before_semicolon_in_for_statement = false
|
||||
csharp_space_between_empty_square_brackets = false
|
||||
csharp_space_between_method_call_empty_parameter_list_parentheses = false
|
||||
csharp_space_between_method_call_name_and_opening_parenthesis = false
|
||||
csharp_space_between_method_call_parameter_list_parentheses = false
|
||||
csharp_space_between_method_declaration_empty_parameter_list_parentheses = false
|
||||
csharp_space_between_method_declaration_name_and_open_parenthesis = false
|
||||
csharp_space_between_method_declaration_parameter_list_parentheses = false
|
||||
csharp_space_between_parentheses = false
|
||||
csharp_space_between_square_brackets = false
|
||||
|
||||
# Wrapping preferences
|
||||
csharp_preserve_single_line_blocks = true
|
||||
csharp_preserve_single_line_statements = true
|
||||
|
||||
#### Naming styles ####
|
||||
|
||||
# Naming rules
|
||||
|
||||
dotnet_naming_rule.interface_should_be_begins_with_i.severity = suggestion
|
||||
dotnet_naming_rule.interface_should_be_begins_with_i.symbols = interface
|
||||
dotnet_naming_rule.interface_should_be_begins_with_i.style = begins_with_i
|
||||
|
||||
dotnet_naming_rule.types_should_be_pascal_case.severity = suggestion
|
||||
dotnet_naming_rule.types_should_be_pascal_case.symbols = types
|
||||
dotnet_naming_rule.types_should_be_pascal_case.style = pascal_case
|
||||
|
||||
dotnet_naming_rule.non_field_members_should_be_pascal_case.severity = suggestion
|
||||
dotnet_naming_rule.non_field_members_should_be_pascal_case.symbols = non_field_members
|
||||
dotnet_naming_rule.non_field_members_should_be_pascal_case.style = pascal_case
|
||||
|
||||
# Symbol specifications
|
||||
|
||||
dotnet_naming_symbols.interface.applicable_kinds = interface
|
||||
dotnet_naming_symbols.interface.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
|
||||
dotnet_naming_symbols.interface.required_modifiers =
|
||||
|
||||
dotnet_naming_symbols.types.applicable_kinds = class, struct, interface, enum
|
||||
dotnet_naming_symbols.types.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
|
||||
dotnet_naming_symbols.types.required_modifiers =
|
||||
|
||||
dotnet_naming_symbols.non_field_members.applicable_kinds = property, event, method
|
||||
dotnet_naming_symbols.non_field_members.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
|
||||
dotnet_naming_symbols.non_field_members.required_modifiers =
|
||||
|
||||
# Naming styles
|
||||
|
||||
dotnet_naming_style.pascal_case.required_prefix =
|
||||
dotnet_naming_style.pascal_case.required_suffix =
|
||||
dotnet_naming_style.pascal_case.word_separator =
|
||||
dotnet_naming_style.pascal_case.capitalization = pascal_case
|
||||
|
||||
dotnet_naming_style.begins_with_i.required_prefix = I
|
||||
dotnet_naming_style.begins_with_i.required_suffix =
|
||||
dotnet_naming_style.begins_with_i.word_separator =
|
||||
dotnet_naming_style.begins_with_i.capitalization = pascal_case
|
448
static/files/ib002/iterative-and-iterators/.gitignore
vendored
Normal file
448
static/files/ib002/iterative-and-iterators/.gitignore
vendored
Normal file
|
@ -0,0 +1,448 @@
|
|||
## Ignore Visual Studio temporary files, build results, and
|
||||
## files generated by popular Visual Studio add-ons.
|
||||
##
|
||||
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
|
||||
|
||||
# User-specific files
|
||||
*.rsuser
|
||||
*.suo
|
||||
*.user
|
||||
*.userosscache
|
||||
*.sln.docstates
|
||||
|
||||
# User-specific files (MonoDevelop/Xamarin Studio)
|
||||
*.userprefs
|
||||
|
||||
# Mono auto generated files
|
||||
mono_crash.*
|
||||
|
||||
# Build results
|
||||
[Dd]ebug/
|
||||
[Dd]ebugPublic/
|
||||
[Rr]elease/
|
||||
[Rr]eleases/
|
||||
x64/
|
||||
x86/
|
||||
[Aa][Rr][Mm]/
|
||||
[Aa][Rr][Mm]64/
|
||||
bld/
|
||||
[Bb]in/
|
||||
[Oo]bj/
|
||||
[Ll]og/
|
||||
[Ll]ogs/
|
||||
|
||||
# Visual Studio 2015/2017 cache/options directory
|
||||
.vs/
|
||||
# Uncomment if you have tasks that create the project's static files in wwwroot
|
||||
#wwwroot/
|
||||
|
||||
# Visual Studio 2017 auto generated files
|
||||
Generated\ Files/
|
||||
|
||||
# MSTest test Results
|
||||
[Tt]est[Rr]esult*/
|
||||
[Bb]uild[Ll]og.*
|
||||
|
||||
# NUnit
|
||||
*.VisualState.xml
|
||||
TestResult.xml
|
||||
nunit-*.xml
|
||||
|
||||
# Build Results of an ATL Project
|
||||
[Dd]ebugPS/
|
||||
[Rr]eleasePS/
|
||||
dlldata.c
|
||||
|
||||
# Benchmark Results
|
||||
BenchmarkDotNet.Artifacts/
|
||||
|
||||
# .NET Core
|
||||
project.lock.json
|
||||
project.fragment.lock.json
|
||||
artifacts/
|
||||
|
||||
# Tye
|
||||
.tye/
|
||||
|
||||
# StyleCop
|
||||
StyleCopReport.xml
|
||||
|
||||
# Files built by Visual Studio
|
||||
*_i.c
|
||||
*_p.c
|
||||
*_h.h
|
||||
*.ilk
|
||||
*.meta
|
||||
*.obj
|
||||
*.iobj
|
||||
*.pch
|
||||
*.pdb
|
||||
*.ipdb
|
||||
*.pgc
|
||||
*.pgd
|
||||
*.rsp
|
||||
*.sbr
|
||||
*.tlb
|
||||
*.tli
|
||||
*.tlh
|
||||
*.tmp
|
||||
*.tmp_proj
|
||||
*_wpftmp.csproj
|
||||
*.log
|
||||
*.vspscc
|
||||
*.vssscc
|
||||
.builds
|
||||
*.pidb
|
||||
*.svclog
|
||||
*.scc
|
||||
|
||||
# Chutzpah Test files
|
||||
_Chutzpah*
|
||||
|
||||
# Visual C++ cache files
|
||||
ipch/
|
||||
*.aps
|
||||
*.ncb
|
||||
*.opendb
|
||||
*.opensdf
|
||||
*.sdf
|
||||
*.cachefile
|
||||
*.VC.db
|
||||
*.VC.VC.opendb
|
||||
|
||||
# Visual Studio profiler
|
||||
*.psess
|
||||
*.vsp
|
||||
*.vspx
|
||||
*.sap
|
||||
|
||||
# Visual Studio Trace Files
|
||||
*.e2e
|
||||
|
||||
# TFS 2012 Local Workspace
|
||||
$tf/
|
||||
|
||||
# Guidance Automation Toolkit
|
||||
*.gpState
|
||||
|
||||
# ReSharper is a .NET coding add-in
|
||||
_ReSharper*/
|
||||
*.[Rr]e[Ss]harper
|
||||
*.DotSettings.user
|
||||
|
||||
# TeamCity is a build add-in
|
||||
_TeamCity*
|
||||
|
||||
# DotCover is a Code Coverage Tool
|
||||
*.dotCover
|
||||
|
||||
# AxoCover is a Code Coverage Tool
|
||||
.axoCover/*
|
||||
!.axoCover/settings.json
|
||||
|
||||
# Coverlet is a free, cross platform Code Coverage Tool
|
||||
coverage*[.json, .xml, .info]
|
||||
|
||||
# Visual Studio code coverage results
|
||||
*.coverage
|
||||
*.coveragexml
|
||||
|
||||
# NCrunch
|
||||
_NCrunch_*
|
||||
.*crunch*.local.xml
|
||||
nCrunchTemp_*
|
||||
|
||||
# MightyMoose
|
||||
*.mm.*
|
||||
AutoTest.Net/
|
||||
|
||||
# Web workbench (sass)
|
||||
.sass-cache/
|
||||
|
||||
# Installshield output folder
|
||||
[Ee]xpress/
|
||||
|
||||
# DocProject is a documentation generator add-in
|
||||
DocProject/buildhelp/
|
||||
DocProject/Help/*.HxT
|
||||
DocProject/Help/*.HxC
|
||||
DocProject/Help/*.hhc
|
||||
DocProject/Help/*.hhk
|
||||
DocProject/Help/*.hhp
|
||||
DocProject/Help/Html2
|
||||
DocProject/Help/html
|
||||
|
||||
# Click-Once directory
|
||||
publish/
|
||||
|
||||
# Publish Web Output
|
||||
*.[Pp]ublish.xml
|
||||
*.azurePubxml
|
||||
# Note: Comment the next line if you want to checkin your web deploy settings,
|
||||
# but database connection strings (with potential passwords) will be unencrypted
|
||||
*.pubxml
|
||||
*.publishproj
|
||||
|
||||
# Microsoft Azure Web App publish settings. Comment the next line if you want to
|
||||
# checkin your Azure Web App publish settings, but sensitive information contained
|
||||
# in these scripts will be unencrypted
|
||||
PublishScripts/
|
||||
|
||||
# NuGet Packages
|
||||
*.nupkg
|
||||
# NuGet Symbol Packages
|
||||
*.snupkg
|
||||
# The packages folder can be ignored because of Package Restore
|
||||
**/[Pp]ackages/*
|
||||
# except build/, which is used as an MSBuild target.
|
||||
!**/[Pp]ackages/build/
|
||||
# Uncomment if necessary however generally it will be regenerated when needed
|
||||
#!**/[Pp]ackages/repositories.config
|
||||
# NuGet v3's project.json files produces more ignorable files
|
||||
*.nuget.props
|
||||
*.nuget.targets
|
||||
|
||||
# Microsoft Azure Build Output
|
||||
csx/
|
||||
*.build.csdef
|
||||
|
||||
# Microsoft Azure Emulator
|
||||
ecf/
|
||||
rcf/
|
||||
|
||||
# Windows Store app package directories and files
|
||||
AppPackages/
|
||||
BundleArtifacts/
|
||||
Package.StoreAssociation.xml
|
||||
_pkginfo.txt
|
||||
*.appx
|
||||
*.appxbundle
|
||||
*.appxupload
|
||||
|
||||
# Visual Studio cache files
|
||||
# files ending in .cache can be ignored
|
||||
*.[Cc]ache
|
||||
# but keep track of directories ending in .cache
|
||||
!?*.[Cc]ache/
|
||||
|
||||
# Others
|
||||
ClientBin/
|
||||
~$*
|
||||
*~
|
||||
*.dbmdl
|
||||
*.dbproj.schemaview
|
||||
*.jfm
|
||||
*.pfx
|
||||
*.publishsettings
|
||||
orleans.codegen.cs
|
||||
|
||||
# Including strong name files can present a security risk
|
||||
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
|
||||
#*.snk
|
||||
|
||||
# Since there are multiple workflows, uncomment next line to ignore bower_components
|
||||
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
|
||||
#bower_components/
|
||||
|
||||
# RIA/Silverlight projects
|
||||
Generated_Code/
|
||||
|
||||
# Backup & report files from converting an old project file
|
||||
# to a newer Visual Studio version. Backup files are not needed,
|
||||
# because we have git ;-)
|
||||
_UpgradeReport_Files/
|
||||
Backup*/
|
||||
UpgradeLog*.XML
|
||||
UpgradeLog*.htm
|
||||
ServiceFabricBackup/
|
||||
*.rptproj.bak
|
||||
|
||||
# SQL Server files
|
||||
*.mdf
|
||||
*.ldf
|
||||
*.ndf
|
||||
|
||||
# Business Intelligence projects
|
||||
*.rdl.data
|
||||
*.bim.layout
|
||||
*.bim_*.settings
|
||||
*.rptproj.rsuser
|
||||
*- [Bb]ackup.rdl
|
||||
*- [Bb]ackup ([0-9]).rdl
|
||||
*- [Bb]ackup ([0-9][0-9]).rdl
|
||||
|
||||
# Microsoft Fakes
|
||||
FakesAssemblies/
|
||||
|
||||
# GhostDoc plugin setting file
|
||||
*.GhostDoc.xml
|
||||
|
||||
# Node.js Tools for Visual Studio
|
||||
.ntvs_analysis.dat
|
||||
node_modules/
|
||||
|
||||
# Visual Studio 6 build log
|
||||
*.plg
|
||||
|
||||
# Visual Studio 6 workspace options file
|
||||
*.opt
|
||||
|
||||
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
|
||||
*.vbw
|
||||
|
||||
# Visual Studio LightSwitch build output
|
||||
**/*.HTMLClient/GeneratedArtifacts
|
||||
**/*.DesktopClient/GeneratedArtifacts
|
||||
**/*.DesktopClient/ModelManifest.xml
|
||||
**/*.Server/GeneratedArtifacts
|
||||
**/*.Server/ModelManifest.xml
|
||||
_Pvt_Extensions
|
||||
|
||||
# Paket dependency manager
|
||||
.paket/paket.exe
|
||||
paket-files/
|
||||
|
||||
# FAKE - F# Make
|
||||
.fake/
|
||||
|
||||
# Ionide - VsCode extension for F# Support
|
||||
.ionide/
|
||||
|
||||
# CodeRush personal settings
|
||||
.cr/personal
|
||||
|
||||
# Python Tools for Visual Studio (PTVS)
|
||||
__pycache__/
|
||||
*.pyc
|
||||
|
||||
# Cake - Uncomment if you are using it
|
||||
# tools/**
|
||||
# !tools/packages.config
|
||||
|
||||
# Tabs Studio
|
||||
*.tss
|
||||
|
||||
# Telerik's JustMock configuration file
|
||||
*.jmconfig
|
||||
|
||||
# BizTalk build output
|
||||
*.btp.cs
|
||||
*.btm.cs
|
||||
*.odx.cs
|
||||
*.xsd.cs
|
||||
|
||||
# OpenCover UI analysis results
|
||||
OpenCover/
|
||||
|
||||
# Azure Stream Analytics local run output
|
||||
ASALocalRun/
|
||||
|
||||
# MSBuild Binary and Structured Log
|
||||
*.binlog
|
||||
|
||||
# NVidia Nsight GPU debugger configuration file
|
||||
*.nvuser
|
||||
|
||||
# MFractors (Xamarin productivity tool) working folder
|
||||
.mfractor/
|
||||
|
||||
# Local History for Visual Studio
|
||||
.localhistory/
|
||||
|
||||
# BeatPulse healthcheck temp database
|
||||
healthchecksdb
|
||||
|
||||
# Backup folder for Package Reference Convert tool in Visual Studio 2017
|
||||
MigrationBackup/
|
||||
|
||||
# Ionide (cross platform F# VS Code tools) working folder
|
||||
.ionide/
|
||||
|
||||
##
|
||||
## Visual studio for Mac
|
||||
##
|
||||
|
||||
|
||||
# globs
|
||||
Makefile.in
|
||||
*.userprefs
|
||||
*.usertasks
|
||||
config.make
|
||||
config.status
|
||||
aclocal.m4
|
||||
install-sh
|
||||
autom4te.cache/
|
||||
*.tar.gz
|
||||
tarballs/
|
||||
test-results/
|
||||
|
||||
# Mac bundle stuff
|
||||
*.dmg
|
||||
*.app
|
||||
|
||||
# content below from: https://github.com/github/gitignore/blob/master/Global/macOS.gitignore
|
||||
# General
|
||||
.DS_Store
|
||||
.AppleDouble
|
||||
.LSOverride
|
||||
|
||||
# Icon must end with two \r
|
||||
Icon
|
||||
|
||||
|
||||
# Thumbnails
|
||||
._*
|
||||
|
||||
# Files that might appear in the root of a volume
|
||||
.DocumentRevisions-V100
|
||||
.fseventsd
|
||||
.Spotlight-V100
|
||||
.TemporaryItems
|
||||
.Trashes
|
||||
.VolumeIcon.icns
|
||||
.com.apple.timemachine.donotpresent
|
||||
|
||||
# Directories potentially created on remote AFP share
|
||||
.AppleDB
|
||||
.AppleDesktop
|
||||
Network Trash Folder
|
||||
Temporary Items
|
||||
.apdisk
|
||||
|
||||
# content below from: https://github.com/github/gitignore/blob/master/Global/Windows.gitignore
|
||||
# Windows thumbnail cache files
|
||||
Thumbs.db
|
||||
ehthumbs.db
|
||||
ehthumbs_vista.db
|
||||
|
||||
# Dump file
|
||||
*.stackdump
|
||||
|
||||
# Folder config file
|
||||
[Dd]esktop.ini
|
||||
|
||||
# Recycle Bin used on file shares
|
||||
$RECYCLE.BIN/
|
||||
|
||||
# Windows Installer files
|
||||
*.cab
|
||||
*.msi
|
||||
*.msix
|
||||
*.msm
|
||||
*.msp
|
||||
|
||||
# Windows shortcuts
|
||||
*.lnk
|
||||
|
||||
# JetBrains Rider
|
||||
.idea/
|
||||
*.sln.iml
|
||||
|
||||
##
|
||||
## Visual Studio Code
|
||||
##
|
||||
.vscode/*
|
||||
!.vscode/settings.json
|
||||
!.vscode/tasks.json
|
||||
!.vscode/launch.json
|
||||
!.vscode/extensions.json
|
10
static/files/ib002/iterative-and-iterators/graphs.csproj
Normal file
10
static/files/ib002/iterative-and-iterators/graphs.csproj
Normal file
|
@ -0,0 +1,10 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net5.0</TargetFramework>
|
||||
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
</Project>
|
66
static/files/ib002/iterative-and-iterators/src/BFS.cs
Normal file
66
static/files/ib002/iterative-and-iterators/src/BFS.cs
Normal file
|
@ -0,0 +1,66 @@
|
|||
using System.Collections.Generic;
|
||||
|
||||
namespace graphs {
|
||||
class BFS<T> where T : notnull {
|
||||
private Graph<T> graph;
|
||||
|
||||
private Dictionary<T, int> Distance = new Dictionary<T, int>();
|
||||
private Dictionary<T, T?> Parent = new Dictionary<T, T?>();
|
||||
private Dictionary<T, Color> State = new Dictionary<T, Color>();
|
||||
|
||||
public BFS(Graph<T> graph) {
|
||||
this.graph = graph;
|
||||
}
|
||||
|
||||
public BFS<T> Run() {
|
||||
foreach (var vertex in graph.Vertices) {
|
||||
if (ColorOf(vertex) == Color.White) {
|
||||
RunFrom(vertex);
|
||||
}
|
||||
}
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
public BFS<T> RunFrom(T start) {
|
||||
State[start] = Color.Gray;
|
||||
Distance[start] = 0;
|
||||
Parent[start] = default(T);
|
||||
|
||||
var queue = new Queue<T>();
|
||||
queue.Enqueue(start);
|
||||
|
||||
while (queue.Count > 0) {
|
||||
var u = queue.Dequeue();
|
||||
|
||||
for (var iterator = graph.GetEdgesFrom(u); iterator.MoveNext();) {
|
||||
var v = iterator.Current;
|
||||
|
||||
if (GetOrDefault(State, v, Color.White) == Color.White) {
|
||||
State[v] = Color.Gray;
|
||||
Distance[v] = Distance[u] + 1;
|
||||
Parent[v] = u;
|
||||
|
||||
queue.Enqueue(v);
|
||||
}
|
||||
}
|
||||
|
||||
State[u] = Color.Black;
|
||||
}
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
private static V GetOrDefault<U, V>(Dictionary<U, V> flags, U u, V defaultValue)
|
||||
where U : notnull {
|
||||
if (flags.TryGetValue(u, out var flag)) {
|
||||
return flag;
|
||||
}
|
||||
return defaultValue;
|
||||
}
|
||||
|
||||
public int DistanceTo(T u) => GetOrDefault(Distance, u, 0);
|
||||
public T? ParentOf(T u) => GetOrDefault(Parent, u, default(T));
|
||||
public Color ColorOf(T u) => GetOrDefault(State, u, Color.White);
|
||||
}
|
||||
}
|
68
static/files/ib002/iterative-and-iterators/src/DFS.cs
Normal file
68
static/files/ib002/iterative-and-iterators/src/DFS.cs
Normal file
|
@ -0,0 +1,68 @@
|
|||
using System.Collections.Generic;
|
||||
|
||||
namespace graphs {
|
||||
class DFS<T> where T : notnull {
|
||||
private Graph<T> graph;
|
||||
|
||||
private int time;
|
||||
private Dictionary<T, int> Discovered = new Dictionary<T, int>();
|
||||
private Dictionary<T, int> Finished = new Dictionary<T, int>();
|
||||
private Dictionary<T, Color> State = new Dictionary<T, Color>();
|
||||
|
||||
public DFS(Graph<T> graph) {
|
||||
this.graph = graph;
|
||||
}
|
||||
|
||||
public DFS<T> Run() {
|
||||
time = 0;
|
||||
|
||||
foreach (var vertex in graph.Vertices) {
|
||||
if (ColorOf(vertex) == Color.White) {
|
||||
RunFrom(vertex, false);
|
||||
}
|
||||
}
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
public DFS<T> RunFrom(T start, bool reset = true) {
|
||||
var path = new Stack<(T, IEnumerator<T>)>();
|
||||
|
||||
if (reset) {
|
||||
time = 0;
|
||||
}
|
||||
|
||||
(Discovered[start], State[start]) = (++time, Color.Gray);
|
||||
path.Push((start, graph.GetEdgesFrom(start)));
|
||||
|
||||
while (path.Count > 0) {
|
||||
var (lastVertex, successors) = path.Peek();
|
||||
|
||||
if (!successors.MoveNext()) {
|
||||
path.Pop();
|
||||
(Finished[lastVertex], State[lastVertex]) = (++time, Color.Black);
|
||||
} else if (ColorOf(successors.Current) == Color.White) {
|
||||
var nextVertex = successors.Current;
|
||||
|
||||
(Discovered[nextVertex], State[nextVertex]) = (++time, Color.Gray);
|
||||
path.Push((nextVertex, graph.GetEdgesFrom(nextVertex)));
|
||||
}
|
||||
}
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
private static V GetOrDefault<U, V>(Dictionary<U, V> flags, U u, V defaultValue)
|
||||
where U : notnull
|
||||
where V : notnull {
|
||||
if (flags.TryGetValue(u, out var flag)) {
|
||||
return flag;
|
||||
}
|
||||
return defaultValue;
|
||||
}
|
||||
|
||||
public int DiscoveredAt(T u) => GetOrDefault(Discovered, u, 0);
|
||||
public int FinishedAt(T u) => GetOrDefault(Finished, u, 0);
|
||||
public Color ColorOf(T u) => GetOrDefault(State, u, Color.White);
|
||||
}
|
||||
}
|
44
static/files/ib002/iterative-and-iterators/src/Graph.cs
Normal file
44
static/files/ib002/iterative-and-iterators/src/Graph.cs
Normal file
|
@ -0,0 +1,44 @@
|
|||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
|
||||
namespace graphs {
|
||||
enum Color {
|
||||
White, Gray, Black
|
||||
}
|
||||
|
||||
class Graph<T> where T : notnull {
|
||||
private SortedSet<T> vertices = new SortedSet<T>();
|
||||
private SortedDictionary<T, SortedSet<T>> edges = new SortedDictionary<T, SortedSet<T>>();
|
||||
|
||||
public SortedSet<T> Vertices {
|
||||
get => vertices;
|
||||
}
|
||||
|
||||
public void AddVertex(T u) {
|
||||
vertices.Add(u);
|
||||
edges.Add(u, new SortedSet<T>());
|
||||
}
|
||||
|
||||
public void AddEdge(T u, T v) {
|
||||
if (edges.TryGetValue(u, out var edgesFromU)) {
|
||||
edgesFromU.Add(v);
|
||||
}
|
||||
}
|
||||
|
||||
public bool HasEdge(T u, T v) {
|
||||
if (edges.TryGetValue(u, out var edgesFromU)) {
|
||||
return edgesFromU.Contains(v);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public IEnumerator<T> GetEdgesFrom(T u) {
|
||||
if (edges.TryGetValue(u, out var edgesFromU)) {
|
||||
return edgesFromU.GetEnumerator();
|
||||
}
|
||||
|
||||
return Enumerable.Empty<T>().GetEnumerator();
|
||||
}
|
||||
}
|
||||
}
|
45
static/files/ib002/iterative-and-iterators/src/Program.cs
Normal file
45
static/files/ib002/iterative-and-iterators/src/Program.cs
Normal file
|
@ -0,0 +1,45 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace graphs {
|
||||
class Program {
|
||||
static Graph<string> CreateExampleGraph() {
|
||||
var vertices = new List<string>() {
|
||||
"s", "q", "t", "y", "r", "v", "w", "x", "z", "u"
|
||||
};
|
||||
|
||||
var graph = new Graph<string>();
|
||||
|
||||
foreach (var vertex in vertices) {
|
||||
graph.AddVertex(vertex);
|
||||
}
|
||||
|
||||
graph.AddEdge("s", "v");
|
||||
graph.AddEdge("q", "s");
|
||||
graph.AddEdge("q", "w");
|
||||
graph.AddEdge("q", "t");
|
||||
graph.AddEdge("t", "y");
|
||||
graph.AddEdge("t", "x");
|
||||
graph.AddEdge("y", "q");
|
||||
graph.AddEdge("r", "y");
|
||||
graph.AddEdge("r", "u");
|
||||
graph.AddEdge("v", "w");
|
||||
graph.AddEdge("w", "s");
|
||||
graph.AddEdge("x", "w");
|
||||
graph.AddEdge("x", "z");
|
||||
graph.AddEdge("z", "x");
|
||||
graph.AddEdge("u", "y");
|
||||
|
||||
return graph;
|
||||
}
|
||||
|
||||
static void Main(string[] args) {
|
||||
var graph = CreateExampleGraph();
|
||||
|
||||
var dfsTraversal = new DFS<string>(graph).Run();
|
||||
foreach (var vertex in graph.Vertices) {
|
||||
Console.WriteLine($"{vertex}(d: {dfsTraversal.DiscoveredAt(vertex)}, f: {dfsTraversal.FinishedAt(vertex)})");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
139
static/files/ib002/postcondition-ambiguity/test_sort.py
Normal file
139
static/files/ib002/postcondition-ambiguity/test_sort.py
Normal file
|
@ -0,0 +1,139 @@
|
|||
from hypothesis import given, settings
|
||||
from hypothesis.strategies import integers, lists
|
||||
import pytest
|
||||
|
||||
import itertools
|
||||
|
||||
|
||||
def compare_by_value(pair):
|
||||
"""
|
||||
Takes a pair from enumerate in form: `index, value` and returns the value
|
||||
|
||||
Args:
|
||||
pair (Tuple[int, T]): Index and element from the iterator at the index.
|
||||
|
||||
Returns:
|
||||
Element from the pair.
|
||||
"""
|
||||
index, value = pair
|
||||
return value
|
||||
|
||||
|
||||
def maximum(arr, n):
|
||||
"""
|
||||
Finds index of maximum element of first n elements in list.
|
||||
|
||||
Args:
|
||||
arr (List): List of values.
|
||||
n (int): Upper bound of index where to search for maximum (inclusive).
|
||||
|
||||
Returns:
|
||||
Index of a maximum element in `arr[:n]`.
|
||||
"""
|
||||
first_n_elements = itertools.islice(enumerate(arr), n)
|
||||
index, value = max(first_n_elements, key=compare_by_value)
|
||||
return index
|
||||
|
||||
|
||||
# Precondition: n = |A|
|
||||
# Loop invariant:
|
||||
# A[i + 1 : n] is sorted AND
|
||||
# all elements of A[i + 1 : n] are bigger or equal to the other elements
|
||||
# Postcondition: A is sorted
|
||||
def select_sort(arr, n):
|
||||
"""
|
||||
Sorts list `arr` using select sort algorithm.
|
||||
|
||||
Args:
|
||||
arr (List): List of values.
|
||||
n (int): Size of the list.
|
||||
|
||||
Returns:
|
||||
Sorted list `arr`.
|
||||
"""
|
||||
assert n == len(arr)
|
||||
|
||||
check_loop_invariant(arr, n, n)
|
||||
for i in reversed(range(1, n)):
|
||||
j = maximum(arr, i + 1)
|
||||
arr[i], arr[j] = arr[j], arr[i]
|
||||
|
||||
check_loop_invariant(arr, n, i)
|
||||
|
||||
return arr
|
||||
|
||||
|
||||
def broken_select_sort(arr, n):
|
||||
assert n == len(arr)
|
||||
|
||||
if not arr:
|
||||
return
|
||||
|
||||
max_value = max(arr)
|
||||
|
||||
check_loop_invariant(arr, n, n)
|
||||
for i in reversed(range(n)):
|
||||
arr[i] = max_value + i
|
||||
|
||||
check_loop_invariant(arr, n, i)
|
||||
|
||||
return arr
|
||||
|
||||
|
||||
def check_loop_invariant(arr, n, i):
|
||||
# A[i + 1 : n] is sorted
|
||||
for x, y in zip(itertools.islice(arr, i + 1, n), itertools.islice(arr, i + 2, n)):
|
||||
assert x <= y
|
||||
|
||||
# all elements of A[i + 1 : n] are bigger or equal to the other elements
|
||||
if i + 1 >= n:
|
||||
# in case there are no elements
|
||||
return
|
||||
|
||||
# otherwise, since the "tail" is sorted, we can assume that it is enough to
|
||||
# check the other elements to the smallest value of the tail
|
||||
smallest = arr[i + 1]
|
||||
for element in itertools.islice(arr, i + 1):
|
||||
assert smallest >= element
|
||||
|
||||
|
||||
def check_vague_postcondition(original_arr, arr):
|
||||
if not arr:
|
||||
return
|
||||
|
||||
# check ordering
|
||||
for x, y in zip(arr, itertools.islice(arr, 1, len(arr))):
|
||||
assert x <= y
|
||||
|
||||
|
||||
def check_postcondition(original_arr, arr):
|
||||
if not arr:
|
||||
return
|
||||
|
||||
# check ordering
|
||||
for x, y in zip(arr, itertools.islice(arr, 1, len(arr))):
|
||||
assert x <= y
|
||||
|
||||
# get counts from original list
|
||||
original_counts = {}
|
||||
for value in original_arr:
|
||||
original_counts[value] = 1 + original_counts.get(value, 0)
|
||||
|
||||
# get counts from resulting list
|
||||
counts = {}
|
||||
for value in arr:
|
||||
counts[value] = 1 + counts.get(value, 0)
|
||||
|
||||
# if arr is permutation of original_arr then all counts must be the same
|
||||
assert counts == original_counts
|
||||
|
||||
|
||||
@given(lists(integers()))
|
||||
@settings(max_examples=1000)
|
||||
@pytest.mark.parametrize(
|
||||
"postcondition", [check_vague_postcondition, check_postcondition]
|
||||
)
|
||||
@pytest.mark.parametrize("sorting_function", [select_sort, broken_select_sort])
|
||||
def test_select_sort(sorting_function, postcondition, numbers):
|
||||
result = sorting_function(numbers[:], len(numbers))
|
||||
postcondition(numbers, result)
|
0
static/files/ib015/.gitkeep
Normal file
0
static/files/ib015/.gitkeep
Normal file
0
static/files/ib110/.gitkeep
Normal file
0
static/files/ib110/.gitkeep
Normal file
264
static/files/pb071/bonuses/03/main.c
Normal file
264
static/files/pb071/bonuses/03/main.c
Normal file
|
@ -0,0 +1,264 @@
|
|||
#include <assert.h>
|
||||
#include <stdbool.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
/* If you want to see arrays before and after sorting, uncomment next line */
|
||||
// #define DEBUG_OUTPUT
|
||||
|
||||
/**
|
||||
* @brief Swaps two elements at given addresses of given size.
|
||||
* @param left Pointer to the first element.
|
||||
* @param right Pointer to the second element.
|
||||
* @param size Size of the memory one element takes.
|
||||
*/
|
||||
void swap(void *left, void *right, size_t size)
|
||||
{
|
||||
/* TODO */
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Get index of biggest element in the array.
|
||||
* @param ptr Pointer to the first element of the array.
|
||||
* @param count Count of the elements in the array.
|
||||
* @param size Size of one element in the array.
|
||||
* @param comp Comparator that is used to decide ordering of the elements.
|
||||
* @returns Index of the biggest element given the ordering.
|
||||
*/
|
||||
size_t maximum(void *ptr, size_t count, size_t size, int (*comp)(const void *, const void *))
|
||||
{
|
||||
/* Pseudocode:
|
||||
* ===========
|
||||
* max_index <- 0
|
||||
* FOR i <- 1 TO n - 1 DO
|
||||
* IF A[i] > A[max_index] THEN
|
||||
* max_index <- i
|
||||
* FI
|
||||
* OD
|
||||
* RETURN max_index
|
||||
*/
|
||||
/* TODO */
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Sort array in-situ using select-sort.
|
||||
* @param ptr Pointer to the first element of the array.
|
||||
* @param count Count of the elements in the array.
|
||||
* @param size Size of one element in the array.
|
||||
* @param comp Comparator that is used to decide ordering of the elements.
|
||||
*/
|
||||
void select_sort(void *ptr, size_t count, size_t size, int (*comp)(const void *, const void *))
|
||||
{
|
||||
/* Pseudocode:
|
||||
* ===========
|
||||
* FOR i <- n - 1 DOWNTO 1 DO
|
||||
* j <- MAXIMUM(A, i + 1)
|
||||
* SWAP(A, i, j)
|
||||
* OD
|
||||
*/
|
||||
/* TODO */
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Compares two integers that are given through generic pointers.
|
||||
* @param x Pointer to the integer x.
|
||||
* @param y Pointer to the integer y.
|
||||
* @returns 0 if x == y, <0 if x < y, >0 otherwise.
|
||||
*/
|
||||
static int int_comparator(const void *x, const void *y)
|
||||
{
|
||||
/* TODO */
|
||||
return 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Compares two characters by ASCII value.
|
||||
* @param x Pointer to the character x.
|
||||
* @param y Pointer to the character y.
|
||||
* @returns 0 if x == y, <0 if x < y, >0 otherwise.
|
||||
*/
|
||||
static int char_comparator(const void *x, const void *y)
|
||||
{
|
||||
char x_value = *(const char *) x;
|
||||
char y_value = *(const char *) y;
|
||||
return x_value - y_value;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Compares two characters by ASCII value in a reversed order.
|
||||
* @param x Pointer to the character x.
|
||||
* @param y Pointer to the character y.
|
||||
* @returns 0 if x == y, >0 if x < y, <0 otherwise.
|
||||
*/
|
||||
static int char_reversed_comparator(const void *x, const void *y)
|
||||
{
|
||||
char x_value = *(const char *) x;
|
||||
char y_value = *(const char *) y;
|
||||
return y_value - x_value;
|
||||
}
|
||||
|
||||
// #pragma region TESTS
|
||||
/**
|
||||
* @brief Check if array is sorted.
|
||||
* @param ptr Pointer to the first element of the array.
|
||||
* @param count Count of the elements in the array.
|
||||
* @param size Size of one element in the array.
|
||||
* @param comp Comparator that is used to decide ordering of the elements.
|
||||
*/
|
||||
static void check_if_sorted(void *ptr, size_t count, size_t size, int (*comp)(const void *, const void *))
|
||||
{
|
||||
char *left = ptr;
|
||||
char *right = (char *) ptr + size;
|
||||
|
||||
for (size_t i = 0; i < count - 1; i++) {
|
||||
assert(comp(left, right) <= 0);
|
||||
|
||||
left += size;
|
||||
right += size;
|
||||
}
|
||||
}
|
||||
|
||||
#ifdef DEBUG_OUTPUT
|
||||
/**
|
||||
* @brief Print numbers from an array.
|
||||
* @param array Pointer to the first element of the array.
|
||||
* @param count Count of the elements in the array.
|
||||
*/
|
||||
static void print_numbers(int *array, size_t count)
|
||||
{
|
||||
for (size_t i = 0; i < count; i++) {
|
||||
printf(" %d", array[i]);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
/**
|
||||
* @brief Run some basic tests on integer arrays.
|
||||
*/
|
||||
static void check_int_arrays()
|
||||
{
|
||||
/* You are free to add any other examples you like, in case you want to add
|
||||
* array with more than 10 elements, please adjust the size.
|
||||
*/
|
||||
|
||||
size_t examples_count = 5;
|
||||
int examples[][10] = {
|
||||
{ -1, 50, -10, 20, 30, 0, -100 },
|
||||
{ -100, 0, 30, 20, -10, 50, -1 },
|
||||
{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 },
|
||||
{ -1, -2, -3, -4, -5, -6, -7, -8, -9, -10 },
|
||||
{ 0, 0, 0, 0, 0, 0, 0, 0 }
|
||||
};
|
||||
|
||||
printf("[TEST] Integer arrays\n");
|
||||
for (size_t i = 0; i < examples_count; i++) {
|
||||
size_t count = sizeof(examples[i]) / sizeof(int);
|
||||
|
||||
#ifdef DEBUG_OUTPUT
|
||||
printf("Before sorting:");
|
||||
print_numbers(examples[i], count);
|
||||
putchar('\n');
|
||||
#endif
|
||||
|
||||
select_sort(examples[i], count, sizeof(int), int_comparator);
|
||||
|
||||
#ifdef DEBUG_OUTPUT
|
||||
printf("After sorting:");
|
||||
print_numbers(examples[i], count);
|
||||
printf("\n\n");
|
||||
#endif
|
||||
|
||||
check_if_sorted(examples[i], count, sizeof(int), int_comparator);
|
||||
}
|
||||
printf("[PASS] Tests passed.\n\n");
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Run some basic tests on strings. Also with reversed ordering.
|
||||
*/
|
||||
static void check_char_arrays()
|
||||
{
|
||||
#define MAX_SIZE 20
|
||||
/* You are free to add any other examples you like, in case you want to add
|
||||
* strings with more than 10 characters, please adjust the size.
|
||||
* mind the terminator ;)
|
||||
*/
|
||||
|
||||
const size_t examples_count = 5;
|
||||
char examples[][MAX_SIZE] = {
|
||||
"Hello World!",
|
||||
"hi",
|
||||
"aloha",
|
||||
"LET US SORT",
|
||||
"LeT uS sOrT"
|
||||
};
|
||||
|
||||
printf("[TEST] Char arrays\n");
|
||||
for (size_t i = 0; i < examples_count; i++) {
|
||||
size_t count = strlen(examples[i]);
|
||||
|
||||
char temp_array[MAX_SIZE];
|
||||
strncpy(temp_array, examples[i], MAX_SIZE);
|
||||
select_sort(temp_array, count, 1, char_comparator);
|
||||
|
||||
#ifdef DEBUG_OUTPUT
|
||||
printf("Before sorting: \"%s\"\n", examples[i]);
|
||||
printf("After sorting: \"%s\"\n\n", temp_array);
|
||||
#endif
|
||||
|
||||
check_if_sorted(temp_array, count, 1, char_comparator);
|
||||
}
|
||||
printf("[PASS] Tests passed.\n\n");
|
||||
|
||||
printf("[TEST] Char arrays reversed\n");
|
||||
for (size_t i = 0; i < examples_count; i++) {
|
||||
size_t count = strlen(examples[i]);
|
||||
|
||||
char temp_array[MAX_SIZE];
|
||||
strncpy(temp_array, examples[i], MAX_SIZE);
|
||||
select_sort(temp_array, count, 1, char_reversed_comparator);
|
||||
|
||||
#ifdef DEBUG_OUTPUT
|
||||
printf("Before sorting: \"%s\"\n", examples[i]);
|
||||
printf("After sorting: \"%s\"\n\n", temp_array);
|
||||
#endif
|
||||
|
||||
check_if_sorted(temp_array, count, 1, char_reversed_comparator);
|
||||
}
|
||||
printf("[PASS] Tests passed.\n\n");
|
||||
#undef MAX_SIZE
|
||||
}
|
||||
|
||||
static void annotate(const char *description, bool result)
|
||||
{
|
||||
printf("[TEST] %s\n", description);
|
||||
assert(result);
|
||||
printf("[PASS] Test passed.\n\n");
|
||||
}
|
||||
|
||||
static void check_int_comparator()
|
||||
{
|
||||
int a = 5, b = -10, c = -10;
|
||||
|
||||
annotate("Test comparator for: a > b", int_comparator(&a, &b) > 0);
|
||||
annotate("Test comparator for: b < a", int_comparator(&b, &a) < 0);
|
||||
annotate("Test comparator for: b = c", int_comparator(&b, &c) == 0);
|
||||
annotate("Test comparator for: a = a", int_comparator(&a, &a) == 0);
|
||||
annotate("Test comparator for: b = b", int_comparator(&b, &b) == 0);
|
||||
annotate("Test comparator for: c = c", int_comparator(&c, &c) == 0);
|
||||
}
|
||||
// #pragma endregion TESTS
|
||||
|
||||
int main(void)
|
||||
{
|
||||
/* Neither of those tests check for bad behaviour, like overwriting array
|
||||
* with elements satisfying ordering. **I** check those :scheming:
|
||||
*/
|
||||
check_int_comparator();
|
||||
check_int_arrays();
|
||||
check_char_arrays();
|
||||
|
||||
return 0;
|
||||
}
|
141
static/files/pb071/bonuses/03/main_light.c
Normal file
141
static/files/pb071/bonuses/03/main_light.c
Normal file
|
@ -0,0 +1,141 @@
|
|||
#include <assert.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
/* If you want to see arrays before and after sorting, uncomment next line */
|
||||
// #define DEBUG_OUTPUT
|
||||
|
||||
/**
|
||||
* @brief Swaps two elements at given addresses.
|
||||
* @param left Pointer to the first element.
|
||||
* @param right Pointer to the second element.
|
||||
*/
|
||||
void swap(int *left, int *right)
|
||||
{
|
||||
/* TODO */
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Get index of biggest element in the array.
|
||||
* @param ptr Pointer to the first element of the array.
|
||||
* @param count Count of the elements in the array.
|
||||
* @returns Index of the biggest element given the ordering.
|
||||
*/
|
||||
size_t maximum(int *ptr, size_t count)
|
||||
{
|
||||
/* Pseudocode:
|
||||
* ===========
|
||||
* max_index <- 0
|
||||
* FOR i <- 1 TO n - 1 DO
|
||||
* IF A[i] > A[max_index] THEN
|
||||
* max_index <- i
|
||||
* FI
|
||||
* OD
|
||||
* RETURN max_index
|
||||
*/
|
||||
/* TODO */
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Sort array in-situ using select-sort.
|
||||
* @param ptr Pointer to the first element of the array.
|
||||
* @param count Count of the elements in the array.
|
||||
*/
|
||||
void select_sort(int *ptr, size_t count)
|
||||
{
|
||||
/* Pseudocode:
|
||||
* ===========
|
||||
* FOR i <- n - 1 DOWNTO 1 DO
|
||||
* j <- MAXIMUM(A, i + 1)
|
||||
* SWAP(A, i, j)
|
||||
* OD
|
||||
*/
|
||||
/* TODO */
|
||||
}
|
||||
|
||||
// #pragma region TESTS
|
||||
/**
|
||||
* @brief Check if array is sorted.
|
||||
* @param ptr Pointer to the first element of the array.
|
||||
* @param count Count of the elements in the array.
|
||||
*/
|
||||
static void check_if_sorted(int *ptr, size_t count)
|
||||
{
|
||||
int *left = ptr;
|
||||
int *right = ptr + 1;
|
||||
|
||||
for (size_t i = 0; i < count - 1; i++) {
|
||||
assert(*left <= *right);
|
||||
|
||||
left++;
|
||||
right++;
|
||||
}
|
||||
}
|
||||
|
||||
#ifdef DEBUG_OUTPUT
|
||||
/**
|
||||
* @brief Print numbers from an array.
|
||||
* @param array Pointer to the first element of the array.
|
||||
* @param count Count of the elements in the array.
|
||||
*/
|
||||
static void print_numbers(int *array, size_t count)
|
||||
{
|
||||
for (size_t i = 0; i < count; i++) {
|
||||
printf(" %d", array[i]);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
/**
|
||||
* @brief Run some basic tests on integer arrays.
|
||||
*/
|
||||
static void check_int_arrays()
|
||||
{
|
||||
/* You are free to add any other examples you like, in case you want to add
|
||||
* array with more than 10 elements, please adjust the size.
|
||||
*/
|
||||
|
||||
size_t examples_count = 5;
|
||||
int examples[][10] = {
|
||||
{ -1, 50, -10, 20, 30, 0, -100 },
|
||||
{ -100, 0, 30, 20, -10, 50, -1 },
|
||||
{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 },
|
||||
{ -1, -2, -3, -4, -5, -6, -7, -8, -9, -10 },
|
||||
{ 0, 0, 0, 0, 0, 0, 0, 0 }
|
||||
};
|
||||
|
||||
printf("[TEST] Integer arrays\n");
|
||||
for (size_t i = 0; i < examples_count; i++) {
|
||||
size_t count = sizeof(examples[i]) / sizeof(int);
|
||||
|
||||
#ifdef DEBUG_OUTPUT
|
||||
printf("Before sorting:");
|
||||
print_numbers(examples[i], count);
|
||||
putchar('\n');
|
||||
#endif
|
||||
|
||||
select_sort(examples[i], count);
|
||||
|
||||
#ifdef DEBUG_OUTPUT
|
||||
printf("After sorting:");
|
||||
print_numbers(examples[i], count);
|
||||
printf("\n\n");
|
||||
#endif
|
||||
|
||||
check_if_sorted(examples[i], count);
|
||||
}
|
||||
printf("[PASS] Tests passed.\n\n");
|
||||
}
|
||||
// #pragma endregion TESTS
|
||||
|
||||
int main(void)
|
||||
{
|
||||
/* Neither of those tests check for bad behaviour, like overwriting array
|
||||
* with elements satisfying ordering. **I** check those :scheming:
|
||||
*/
|
||||
check_int_arrays();
|
||||
|
||||
return 0;
|
||||
}
|
12
static/files/pb071/bonuses/03/makefile
Normal file
12
static/files/pb071/bonuses/03/makefile
Normal file
|
@ -0,0 +1,12 @@
|
|||
CC=gcc
|
||||
CFLAGS=-std=c99 -Wall -Wextra -Werror -Wpedantic
|
||||
|
||||
main:
|
||||
$(CC) $(CFLAGS) main.c -o main
|
||||
|
||||
main_light:
|
||||
$(CC) $(CFLAGS) main_light.c -o main_light
|
||||
|
||||
check: main main_light
|
||||
valgrind ./main
|
||||
valgrind ./main_light
|
25
static/files/pb071/bonuses/04/CMakeLists.txt
Normal file
25
static/files/pb071/bonuses/04/CMakeLists.txt
Normal file
|
@ -0,0 +1,25 @@
|
|||
cmake_minimum_required(VERSION 3.0)
|
||||
|
||||
# Project configuration
|
||||
project(seminar04-bonus-maze)
|
||||
set(SOURCES maze.h maze.c)
|
||||
set(EXECUTABLE maze)
|
||||
|
||||
# Executable
|
||||
add_executable(maze ${SOURCES} main.c)
|
||||
add_executable(test_maze ${SOURCES} cut.h test_maze.c)
|
||||
|
||||
# Configure compiler warnings
|
||||
if (CMAKE_C_COMPILER_ID MATCHES Clang OR ${CMAKE_C_COMPILER_ID} STREQUAL GNU)
|
||||
# using regular Clang, AppleClang or GCC
|
||||
# Strongly suggested: neable -Werror
|
||||
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=gnu11 -Wall -Wextra -pedantic")
|
||||
elseif (${CMAKE_C_COMPILER_ID} STREQUAL MSVC)
|
||||
# using Visual Studio C++
|
||||
target_compile_definitions(${EXECUTABLE} PRIVATE _CRT_SECURE_NO_DEPRECATE)
|
||||
set(CMAKE_CXX_FLAGS "/permissive- /W4 /EHsc")
|
||||
endif()
|
||||
|
||||
if(MINGW)
|
||||
target_compile_definitions(${EXECUTABLE} PRIVATE __USE_MINGW_ANSI_STDIO=1)
|
||||
endif()
|
8
static/files/pb071/bonuses/04/main.c
Normal file
8
static/files/pb071/bonuses/04/main.c
Normal file
|
@ -0,0 +1,8 @@
|
|||
#include "maze.h"
|
||||
|
||||
#include <stdio.h>
|
||||
|
||||
int main(void)
|
||||
{
|
||||
return 0;
|
||||
}
|
84
static/files/pb071/bonuses/04/maze.c
Normal file
84
static/files/pb071/bonuses/04/maze.c
Normal file
|
@ -0,0 +1,84 @@
|
|||
#include "maze.h"
|
||||
|
||||
#include <stdbool.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
/**
|
||||
* @brief Checks if pointer points inside the memory specified by upper and lower
|
||||
* bound.
|
||||
* @param first Start of the allocated memory.
|
||||
* @param last First address that is not included in the allocated memory.
|
||||
* @param pos Pointer to memory.
|
||||
* @returns <code>true</code> if pos points to the memory [first, last), <code>
|
||||
* false</code> otherwise.
|
||||
*/
|
||||
static bool within_bounds(const char *first, const char *last, const char *pos)
|
||||
{
|
||||
/* TODO */
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Sets 2D coordinates of the pointer.
|
||||
* @param map Start of the 2D memory.
|
||||
* @param position Pointer to the map.
|
||||
* @param width Width of one row of the map.
|
||||
* @param row Output variable where the row is set.
|
||||
* @param col Output variable where the column is set.
|
||||
*/
|
||||
static void set_coordinates(const char *map, char *position, size_t width, size_t *row, size_t *col)
|
||||
{
|
||||
/* TODO */
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Checks if indices are within bounds of the 2D map.
|
||||
* @param width Width of the map.
|
||||
* @param height Height of the map.
|
||||
* @param row Row to be checked.
|
||||
* @param col Column to be checked.
|
||||
* @returns <code>true</code> if row,col are within bounds of the map,.<code>false
|
||||
* </code> otherwise.
|
||||
*/
|
||||
static bool within_bounds_by_index(size_t width, size_t height, size_t row, size_t col)
|
||||
{
|
||||
/* TODO */
|
||||
}
|
||||
|
||||
void print_maze(const char *map, char *position, char direction, size_t width, size_t height)
|
||||
{
|
||||
printf("Maze:\n");
|
||||
for (size_t row = 0; row < height; row++) {
|
||||
for (size_t col = 0; col < width; col++) {
|
||||
const char *current = &map[row * width + col];
|
||||
|
||||
if (current == position) {
|
||||
switch (direction) {
|
||||
case '^':
|
||||
putchar('N');
|
||||
break;
|
||||
case 'v':
|
||||
putchar('S');
|
||||
break;
|
||||
case '>':
|
||||
putchar('E');
|
||||
break;
|
||||
case '<':
|
||||
putchar('W');
|
||||
break;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
putchar(*current);
|
||||
}
|
||||
putchar('\n');
|
||||
}
|
||||
putchar('\n');
|
||||
}
|
||||
|
||||
enum end_state_t walk(const char *map, char *position, char direction, size_t width, size_t height)
|
||||
{
|
||||
/* TODO */
|
||||
return NONE;
|
||||
}
|
33
static/files/pb071/bonuses/04/maze.h
Normal file
33
static/files/pb071/bonuses/04/maze.h
Normal file
|
@ -0,0 +1,33 @@
|
|||
#include <stdlib.h>
|
||||
|
||||
enum end_state_t
|
||||
{
|
||||
NONE,
|
||||
FOUND_KEY,
|
||||
FOUND_TREASURE,
|
||||
OUT_OF_BOUNDS,
|
||||
INFINITE_LOOP,
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief Prints maze and the robot within it.
|
||||
* @param map Map of the maze.
|
||||
* @param position Current position of the robot.
|
||||
* @param direction Direction the robot is facing, one of "^v<>".
|
||||
* @param width Width of the map.
|
||||
* @param height Height of the map.
|
||||
*/
|
||||
void print_maze(const char *map, char *position, char direction, size_t width, size_t height);
|
||||
|
||||
/**
|
||||
* @brief Get end state of the robot after his walk.
|
||||
* @param map Map of the maze.
|
||||
* @param position Initial position of the robot in the maze.
|
||||
* @param direction Direction the robot is facing at the beginning. You can assume
|
||||
* correctness of this value.
|
||||
* @param width Width of the maze. You can assume correctness of this value.
|
||||
* @param height Height of the maze. You can assume correctness of this value.
|
||||
* @returns End state of the robot after his walk is finished or has been terminated
|
||||
* manually.
|
||||
*/
|
||||
enum end_state_t walk(const char *map, char *position, char direction, size_t width, size_t height);
|
246
static/files/pb071/bonuses/04/test_maze.c
Normal file
246
static/files/pb071/bonuses/04/test_maze.c
Normal file
|
@ -0,0 +1,246 @@
|
|||
#include "maze.h"
|
||||
|
||||
#define CUT_MAIN
|
||||
#include "cut.h"
|
||||
|
||||
static void check_result(char *map, size_t position, char direction, size_t width, size_t height, enum end_state_t expected)
|
||||
{
|
||||
enum end_state_t state = walk(map, &map[position], direction, width, height);
|
||||
ASSERT(state == expected);
|
||||
}
|
||||
|
||||
TEST(basic)
|
||||
{
|
||||
SUBTEST(spawns_on_treasure)
|
||||
{
|
||||
check_result(("T."
|
||||
".."),
|
||||
0,
|
||||
'>',
|
||||
2,
|
||||
2,
|
||||
FOUND_TREASURE);
|
||||
}
|
||||
SUBTEST(spawns_on_key)
|
||||
{
|
||||
check_result(("K."
|
||||
".."),
|
||||
0,
|
||||
'^',
|
||||
2,
|
||||
2,
|
||||
FOUND_KEY);
|
||||
}
|
||||
SUBTEST(spawns_on_treasure_in_middle)
|
||||
{
|
||||
check_result(("..."
|
||||
".T."
|
||||
"..."),
|
||||
4,
|
||||
'v',
|
||||
3,
|
||||
3,
|
||||
FOUND_TREASURE);
|
||||
}
|
||||
}
|
||||
|
||||
TEST(some_walking)
|
||||
{
|
||||
SUBTEST(straight_up)
|
||||
{
|
||||
check_result((".T."
|
||||
"..."
|
||||
"..."),
|
||||
7,
|
||||
'^',
|
||||
3,
|
||||
3,
|
||||
FOUND_TREASURE);
|
||||
}
|
||||
SUBTEST(down)
|
||||
{
|
||||
check_result(("..........................T"), 7, 'v', 1, 27, FOUND_TREASURE);
|
||||
}
|
||||
SUBTEST(to_right)
|
||||
{
|
||||
check_result(("..........................K"), 2, '>', 27, 1, FOUND_KEY);
|
||||
}
|
||||
SUBTEST(to_left)
|
||||
{
|
||||
check_result(("K.........................."), 15, '<', 27, 1, FOUND_KEY);
|
||||
}
|
||||
}
|
||||
|
||||
TEST(follows_directions)
|
||||
{
|
||||
SUBTEST(basic)
|
||||
{
|
||||
check_result((">..v"
|
||||
"...."
|
||||
"...K"
|
||||
"^..<"),
|
||||
12,
|
||||
'>',
|
||||
4,
|
||||
4,
|
||||
FOUND_KEY);
|
||||
}
|
||||
SUBTEST(no_way_to_avoid)
|
||||
{
|
||||
const char *directions = "<>^v";
|
||||
|
||||
for (size_t row = 0; row < 5; row++) {
|
||||
for (size_t col = 0; col < 5; col++) {
|
||||
for (size_t dir = 0; dir < 4; dir++) {
|
||||
check_result((">>>>v"
|
||||
"^>>vv"
|
||||
"^^T<v"
|
||||
"^^<<<"
|
||||
"^<<<<"),
|
||||
row * 5 + col,
|
||||
directions[dir],
|
||||
5,
|
||||
5,
|
||||
FOUND_TREASURE);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
TEST(follows_directions_even_to_doom)
|
||||
{
|
||||
SUBTEST(to_right)
|
||||
{
|
||||
check_result((".>.."
|
||||
"^KTK"
|
||||
".TvT"
|
||||
"...<"),
|
||||
1,
|
||||
'>',
|
||||
4,
|
||||
4,
|
||||
OUT_OF_BOUNDS);
|
||||
}
|
||||
SUBTEST(to_up)
|
||||
{
|
||||
check_result((".>.."
|
||||
"^KTK"
|
||||
".TvT"
|
||||
"...<"),
|
||||
4,
|
||||
'>',
|
||||
4,
|
||||
4,
|
||||
OUT_OF_BOUNDS);
|
||||
}
|
||||
SUBTEST(to_down)
|
||||
{
|
||||
check_result((".>.."
|
||||
"^KTK"
|
||||
".TvT"
|
||||
"...<"),
|
||||
10,
|
||||
'>',
|
||||
4,
|
||||
4,
|
||||
OUT_OF_BOUNDS);
|
||||
}
|
||||
SUBTEST(to_left)
|
||||
{
|
||||
check_result((".>.."
|
||||
"^KTK"
|
||||
".TvT"
|
||||
"...<"),
|
||||
15,
|
||||
'>',
|
||||
4,
|
||||
4,
|
||||
OUT_OF_BOUNDS);
|
||||
}
|
||||
}
|
||||
|
||||
TEST(mean)
|
||||
{
|
||||
SUBTEST(out_of_bounds_at_the_beginning)
|
||||
{
|
||||
check_result((".."
|
||||
".."),
|
||||
4,
|
||||
'v',
|
||||
2,
|
||||
2,
|
||||
OUT_OF_BOUNDS);
|
||||
check_result((".."
|
||||
".."),
|
||||
5,
|
||||
'v',
|
||||
2,
|
||||
2,
|
||||
OUT_OF_BOUNDS);
|
||||
check_result((".."
|
||||
".."),
|
||||
(size_t) -1,
|
||||
'v',
|
||||
2,
|
||||
2,
|
||||
OUT_OF_BOUNDS);
|
||||
check_result((">T<"
|
||||
"..."
|
||||
"^.^"),
|
||||
10,
|
||||
'^',
|
||||
3,
|
||||
3,
|
||||
OUT_OF_BOUNDS);
|
||||
}
|
||||
}
|
||||
|
||||
TEST(infinite_bonus)
|
||||
{
|
||||
SUBTEST(easy)
|
||||
{
|
||||
check_result((">.v"
|
||||
"..."
|
||||
"^.<"),
|
||||
0,
|
||||
'v',
|
||||
3,
|
||||
3,
|
||||
INFINITE_LOOP);
|
||||
}
|
||||
SUBTEST(medium)
|
||||
{
|
||||
check_result((">v"
|
||||
"^<"),
|
||||
2,
|
||||
'v',
|
||||
2,
|
||||
2,
|
||||
INFINITE_LOOP);
|
||||
}
|
||||
SUBTEST(hard)
|
||||
{
|
||||
check_result(("v.v"
|
||||
"..."
|
||||
"^.^"),
|
||||
0,
|
||||
'>',
|
||||
3,
|
||||
3,
|
||||
INFINITE_LOOP);
|
||||
}
|
||||
SUBTEST(harder)
|
||||
{
|
||||
check_result((">.v.."
|
||||
"....."
|
||||
"^...<"
|
||||
"....."
|
||||
"..>.^"),
|
||||
4,
|
||||
'v',
|
||||
5,
|
||||
5,
|
||||
INFINITE_LOOP);
|
||||
}
|
||||
}
|
25
static/files/pb071/bonuses/05-06/CMakeLists.txt
Normal file
25
static/files/pb071/bonuses/05-06/CMakeLists.txt
Normal file
|
@ -0,0 +1,25 @@
|
|||
cmake_minimum_required(VERSION 3.0)
|
||||
|
||||
# Project configuration
|
||||
project(seminar05-06-bonus-bmp)
|
||||
set(SOURCES bmp.h bmp.c)
|
||||
set(EXECUTABLE bmp)
|
||||
|
||||
# Executable
|
||||
add_executable(bmp ${SOURCES} main.c)
|
||||
add_executable(test_bmp ${SOURCES} cut.h test_bmp.c)
|
||||
|
||||
# Configure compiler warnings
|
||||
if (CMAKE_C_COMPILER_ID MATCHES Clang OR ${CMAKE_C_COMPILER_ID} STREQUAL GNU)
|
||||
# using regular Clang, AppleClang or GCC
|
||||
# Strongly suggested: neable -Werror
|
||||
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=gnu11 -Wall -Wextra -pedantic")
|
||||
elseif (${CMAKE_C_COMPILER_ID} STREQUAL MSVC)
|
||||
# using Visual Studio C++
|
||||
target_compile_definitions(${EXECUTABLE} PRIVATE _CRT_SECURE_NO_DEPRECATE)
|
||||
set(CMAKE_CXX_FLAGS "/permissive- /W4 /EHsc")
|
||||
endif()
|
||||
|
||||
if(MINGW)
|
||||
target_compile_definitions(${EXECUTABLE} PRIVATE __USE_MINGW_ANSI_STDIO=1)
|
||||
endif()
|
153
static/files/pb071/bonuses/05-06/bmp.c
Normal file
153
static/files/pb071/bonuses/05-06/bmp.c
Normal file
|
@ -0,0 +1,153 @@
|
|||
#include "bmp.h"
|
||||
|
||||
#include <ctype.h>
|
||||
#include <stdbool.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#define UNUSED(var) ((void) (var))
|
||||
|
||||
/**
|
||||
* Return reversed string.
|
||||
*
|
||||
* Function returns a pointer to the reversed string, which has been created
|
||||
* from the input parameter. If the input string is NULL or memory could not be
|
||||
* allocated, function returns NULL.
|
||||
*
|
||||
* @param text input string
|
||||
* @return reversed representation of input string, or NULL, if the string could
|
||||
* not be created.
|
||||
*/
|
||||
char *reverse(const char *text)
|
||||
{
|
||||
/* TODO */
|
||||
UNUSED(text);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Checks if key is valid.
|
||||
* @param key String that is used as a key
|
||||
* @returns true, if key is valid; false otherwise
|
||||
*/
|
||||
static bool check_key(const char *key)
|
||||
{
|
||||
/* TODO */
|
||||
UNUSED(key);
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Function for encrypting the given plaintext by applying the Vigenère cipher.
|
||||
*
|
||||
* @param key Pointer to a string representing the key which will be used
|
||||
* for encrypting the plaintext. The key is represented by a single
|
||||
* case-insensitive word consisting of only alphabetical characters.
|
||||
* @param text Pointer to a string representing the plaintext to be
|
||||
* encrypted.
|
||||
* @return the address of a copy of the ciphertext encrypted by the Vigenère
|
||||
* cipher, or NULL if the encryption was not successful.
|
||||
*/
|
||||
char *vigenere_encrypt(const char *key, const char *text)
|
||||
{
|
||||
/* TODO */
|
||||
UNUSED(key);
|
||||
UNUSED(text);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/**
|
||||
* Function for decrypting the given ciphertext by applying the Vigenère cipher.
|
||||
*
|
||||
* @param key Pointer to a string representing the key which has been used
|
||||
* for encrypting the ciphertext. The key is represented by a single
|
||||
* case-insensitive word consisting of only alphabetical characters.
|
||||
* @param text Pointer to a string representing the ciphertext to be
|
||||
* decrypted.
|
||||
* @return the address of a copy of the plaintext decrypted by the Vigenère
|
||||
* cipher, or NULL if the decryption was not successful.
|
||||
*/
|
||||
char *vigenere_decrypt(const char *key, const char *text)
|
||||
{
|
||||
/* TODO */
|
||||
UNUSED(key);
|
||||
UNUSED(text);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/**
|
||||
* Function for bitwise encryption according to the following process:
|
||||
* The character about to be encrypted is divided in half (4 bits + 4 bits).
|
||||
* Subsequently, the bits in the left half are divided into two pairs and the
|
||||
* values inside each pair are swapped. The four bits created by this way are
|
||||
* then used in a bitwise XOR operation with the remaining 4 bits.
|
||||
*
|
||||
* @param text String representing the plaintext to be encrypted.
|
||||
* @return a pointer to a newly created string containing the ciphertext
|
||||
* produced by encrypting the plaintext, or NULL if the encryption was not
|
||||
* successful.
|
||||
*/
|
||||
unsigned char *bit_encrypt(const char *text)
|
||||
{
|
||||
/* TODO */
|
||||
UNUSED(text);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/**
|
||||
* Function for bitwise decryption - it is the inverse of the bitwise encryption
|
||||
* function.
|
||||
*
|
||||
* @param text String representing the ciphertext to be decrypted.
|
||||
* @return a pointer to a newly created string containing the plaintext produced
|
||||
* by decrypting the ciphertext, or NULL if the decryption was not successful.
|
||||
*/
|
||||
char *bit_decrypt(const unsigned char *text)
|
||||
{
|
||||
/* TODO */
|
||||
UNUSED(text);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/**
|
||||
* Function for encrypting the given plaintext by applying the BMP cipher.
|
||||
* The process of encrypting by BMP:
|
||||
* <ol>
|
||||
* <li> the provided input string is encrypted by function reverse()
|
||||
* <li> the acquired string is encrypted by function vigenere_encrypt()
|
||||
* <li> function bit_encrypt() is applied on the resulting string
|
||||
* </ol>
|
||||
*
|
||||
* @param key Pointer to a string representing the key which will be used
|
||||
* for encrypting the plaintext. The key is represented by a single
|
||||
* case-insensitive word consisting of only alphabetical characters.
|
||||
* @param text String representing the plaintext to be encrypted.
|
||||
* @return the address of a copy of the ciphertext encrypted by the BMP cipher,
|
||||
* or NULL if the encryption was not successful.
|
||||
*/
|
||||
unsigned char *bmp_encrypt(const char *key, const char *text)
|
||||
{
|
||||
/* TODO */
|
||||
UNUSED(key);
|
||||
UNUSED(text);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/**
|
||||
* Function for decrypting the given ciphertext by applying the BMP cipher.
|
||||
* The process of decrypting by BMP is the opposite of BMP encryption.
|
||||
*
|
||||
* @param key Pointer to a string representing the key which has been used
|
||||
* for encrypting the ciphertext. The key is represented by a single
|
||||
* case-insensitive word consisting of only alphabetical characters.
|
||||
* @param text String representing the ciphertext to be decrypted.
|
||||
* @return the address of a copy of the plaintext decrypted by the BMP cipher,
|
||||
* or NULL if the decryption was not successful.
|
||||
*/
|
||||
char *bmp_decrypt(const char *key, const unsigned char *text)
|
||||
{
|
||||
/* TODO */
|
||||
UNUSED(key);
|
||||
UNUSED(text);
|
||||
return NULL;
|
||||
}
|
98
static/files/pb071/bonuses/05-06/bmp.h
Normal file
98
static/files/pb071/bonuses/05-06/bmp.h
Normal file
|
@ -0,0 +1,98 @@
|
|||
#ifndef _BMP_H
|
||||
#define _BMP_H
|
||||
|
||||
/**
|
||||
* Return reversed string.
|
||||
*
|
||||
* Function returns a pointer to the reversed string, which has been created
|
||||
* from the input parameter. If the input string is NULL or memory could not be
|
||||
* allocated, function returns NULL.
|
||||
*
|
||||
* @param text input string
|
||||
* @return reversed representation of input string, or NULL, if the string could
|
||||
* not be created.
|
||||
*/
|
||||
char *reverse(const char *text);
|
||||
|
||||
/**
|
||||
* Function for encrypting the given plaintext by applying the Vigenère cipher.
|
||||
*
|
||||
* @param key Pointer to a string representing the key which will be used
|
||||
* for encrypting the plaintext. The key is represented by a single
|
||||
* case-insensitive word consisting of only alphabetical characters.
|
||||
* @param text Pointer to a string representing the plaintext to be
|
||||
* encrypted.
|
||||
* @return the address of a copy of the ciphertext encrypted by the Vigenère
|
||||
* cipher, or NULL if the encryption was not successful.
|
||||
*/
|
||||
char *vigenere_encrypt(const char *key, const char *text);
|
||||
|
||||
/**
|
||||
* Function for decrypting the given ciphertext by applying the Vigenère cipher.
|
||||
*
|
||||
* @param key Pointer to a string representing the key which has been used
|
||||
* for encrypting the ciphertext. The key is represented by a single
|
||||
* case-insensitive word consisting of only alphabetical characters.
|
||||
* @param text Pointer to a string representing the ciphertext to be
|
||||
* decrypted.
|
||||
* @return the address of a copy of the plaintext decrypted by the Vigenère
|
||||
* cipher, or NULL if the decryption was not successful.
|
||||
*/
|
||||
char *vigenere_decrypt(const char *key, const char *text);
|
||||
|
||||
/**
|
||||
* Function for bitwise encryption according to the following process:
|
||||
* The character about to be encrypted is divided in half (4 bits + 4 bits).
|
||||
* Subsequently, the bits in the left half are divided into two pairs and the
|
||||
* values inside each pair are swapped. The four bits created by this way are
|
||||
* then used in a bitwise XOR operation with the remaining 4 bits.
|
||||
*
|
||||
* @param text String representing the plaintext to be encrypted.
|
||||
* @return a pointer to a newly created string containing the ciphertext
|
||||
* produced by encrypting the plaintext, or NULL if the encryption was not
|
||||
* successful.
|
||||
*/
|
||||
unsigned char *bit_encrypt(const char *text);
|
||||
|
||||
/**
|
||||
* Function for bitwise decryption - it is the inverse of the bitwise encryption
|
||||
* function.
|
||||
*
|
||||
* @param text String representing the ciphertext to be decrypted.
|
||||
* @return a pointer to a newly created string containing the plaintext produced
|
||||
* by decrypting the ciphertext, or NULL if the decryption was not successful.
|
||||
*/
|
||||
char *bit_decrypt(const unsigned char *text);
|
||||
|
||||
/**
|
||||
* Function for encrypting the given plaintext by applying the BMP cipher.
|
||||
* The process of encrypting by BMP:
|
||||
* <ol>
|
||||
* <li> the provided input string is encrypted by function reverse()
|
||||
* <li> the acquired string is encrypted by function vigenere_encrypt()
|
||||
* <li> function bit_encrypt() is applied on the resulting string
|
||||
* </ol>
|
||||
*
|
||||
* @param key Pointer to a string representing the key which will be used
|
||||
* for encrypting the plaintext. The key is represented by a single
|
||||
* case-insensitive word consisting of only alphabetical characters.
|
||||
* @param text String representing the plaintext to be encrypted.
|
||||
* @return the address of a copy of the ciphertext encrypted by the BMP cipher,
|
||||
* or NULL if the encryption was not successful.
|
||||
*/
|
||||
unsigned char *bmp_encrypt(const char *key, const char *text);
|
||||
|
||||
/**
|
||||
* Function for decrypting the given ciphertext by applying the BMP cipher.
|
||||
* The process of decrypting by BMP is the opposite of BMP encryption.
|
||||
*
|
||||
* @param key Pointer to a string representing the key which has been used
|
||||
* for encrypting the ciphertext. The key is represented by a single
|
||||
* case-insensitive word consisting of only alphabetical characters.
|
||||
* @param text String representing the ciphertext to be decrypted.
|
||||
* @return the address of a copy of the plaintext decrypted by the BMP cipher,
|
||||
* or NULL if the decryption was not successful.
|
||||
*/
|
||||
char *bmp_decrypt(const char *key, const unsigned char *text);
|
||||
|
||||
#endif
|
8
static/files/pb071/bonuses/05-06/main.c
Normal file
8
static/files/pb071/bonuses/05-06/main.c
Normal file
|
@ -0,0 +1,8 @@
|
|||
#include "playfair.h"
|
||||
|
||||
#include <stdio.h>
|
||||
|
||||
int main(void)
|
||||
{
|
||||
return 0;
|
||||
}
|
251
static/files/pb071/bonuses/05-06/test_bmp.c
Normal file
251
static/files/pb071/bonuses/05-06/test_bmp.c
Normal file
|
@ -0,0 +1,251 @@
|
|||
#include "bmp.h"
|
||||
|
||||
#include <ctype.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#define CUT_MAIN
|
||||
#include "cut.h"
|
||||
|
||||
void test_reverse(const char *input, const char *output)
|
||||
{
|
||||
char *reversed = reverse(input);
|
||||
|
||||
// check if not NULL
|
||||
ASSERT(reversed != NULL);
|
||||
|
||||
int result = strcmp(reversed, output);
|
||||
if (result != 0) {
|
||||
DEBUG_MSG("Expected: %s, but got: %s\n", output, reversed);
|
||||
}
|
||||
|
||||
ASSERT(strcmp(reversed, output) == 0);
|
||||
free(reversed);
|
||||
}
|
||||
|
||||
TEST(REVERSE)
|
||||
{
|
||||
SUBTEST(ABCD)
|
||||
{
|
||||
test_reverse("ABCD", "DCBA");
|
||||
}
|
||||
SUBTEST(BADACAD)
|
||||
{
|
||||
test_reverse("BADACAD", "DACADAB");
|
||||
}
|
||||
SUBTEST(qqsfyCCDAADQWQLLLlccaasq)
|
||||
{
|
||||
test_reverse("qqsfyCCDAADQWQLLLlccaasq", "QSAACCLLLLQWQDAADCCYFSQQ");
|
||||
}
|
||||
SUBTEST(NULL)
|
||||
{
|
||||
ASSERT(reverse(NULL) == NULL);
|
||||
}
|
||||
SUBTEST(EMPTY)
|
||||
{
|
||||
char *result = reverse("");
|
||||
ASSERT(result[0] == '\0');
|
||||
free(result);
|
||||
}
|
||||
SUBTEST(RANDOM)
|
||||
{
|
||||
test_reverse("hello", "OLLEH");
|
||||
test_reverse("malloc", "COLLAM");
|
||||
test_reverse("calloc", "COLLAC");
|
||||
test_reverse("realloc", "COLLAER");
|
||||
test_reverse("everything", "GNIHTYREVE");
|
||||
test_reverse("failing", "GNILIAF");
|
||||
test_reverse("LOL", "LOL");
|
||||
test_reverse("1273912739&^%$$*((", "((*$$%^&9372193721");
|
||||
}
|
||||
}
|
||||
|
||||
void test_bit(const char *input, const unsigned char *output, size_t length)
|
||||
{
|
||||
unsigned char *encrypted = bit_encrypt(input);
|
||||
char *decrypted = bit_decrypt(encrypted);
|
||||
|
||||
for (size_t i = 0; i < length; i++) {
|
||||
ASSERT(encrypted[i] == output[i]);
|
||||
ASSERT(decrypted[i] == input[i]);
|
||||
}
|
||||
|
||||
free(decrypted);
|
||||
free(encrypted);
|
||||
}
|
||||
|
||||
TEST(BIT)
|
||||
{
|
||||
SUBTEST(HELLO_WORLD)
|
||||
{
|
||||
const unsigned char output[] = { 0x80, 0x9c, 0x95, 0x95, 0x96, 0x11, 0xbc, 0x96, 0xb9, 0x95, 0x9d, 0x10 };
|
||||
test_bit("Hello world!", output, 12);
|
||||
}
|
||||
SUBTEST(MALLOC)
|
||||
{
|
||||
const unsigned char output[] = { 0x94, 0x98, 0x95, 0x95, 0x96, 0x9a };
|
||||
test_bit("malloc", output, 6);
|
||||
}
|
||||
SUBTEST(CALLOC)
|
||||
{
|
||||
const unsigned char output[] = { 0x9a, 0x98, 0x95, 0x95, 0x96, 0x9a };
|
||||
test_bit("calloc", output, 6);
|
||||
}
|
||||
SUBTEST(REALLOC)
|
||||
{
|
||||
const unsigned char output[] = { 0xb9, 0x9c, 0x98, 0x95, 0x95, 0x96, 0x9a };
|
||||
test_bit("realloc", output, 7);
|
||||
}
|
||||
SUBTEST(EVERYTHING)
|
||||
{
|
||||
const unsigned char output[] = { 0x9c, 0xbd, 0x9c, 0xb9, 0xb2, 0xbf, 0x91, 0x90, 0x97, 0x9e };
|
||||
test_bit("everything", output, 10);
|
||||
}
|
||||
SUBTEST(FAILING)
|
||||
{
|
||||
const unsigned char output[] = { 0x9f, 0x98, 0x90, 0x95, 0x90, 0x97, 0x9e };
|
||||
test_bit("failing", output, 7);
|
||||
}
|
||||
SUBTEST(LOL)
|
||||
{
|
||||
const unsigned char output[] = { 0x84, 0x87, 0x84 };
|
||||
test_bit("LOL", output, 3);
|
||||
}
|
||||
SUBTEST(GARBAGE)
|
||||
{
|
||||
const unsigned char output[] = { 0x32, 0x31, 0x34, 0x30, 0x3a, 0x32, 0x31, 0x34, 0x30, 0x3a, 0x17, 0xa4, 0x14, 0x15, 0x15, 0x1b, 0x19, 0x19 };
|
||||
test_bit("1273912739&^%$$*((", output, 18);
|
||||
}
|
||||
SUBTEST(HELLO_FI)
|
||||
{
|
||||
const unsigned char output[] = { 0x91, 0x9c, 0x95, 0x95, 0x96 };
|
||||
test_bit("hello", output, 5);
|
||||
}
|
||||
SUBTEST(BYE_FI)
|
||||
{
|
||||
const unsigned char output[] = { 0x9b, 0xb2, 0x9c };
|
||||
test_bit("bye", output, 3);
|
||||
}
|
||||
}
|
||||
|
||||
void test_vigenere(const char *key, const char *input, const char *output, size_t length)
|
||||
{
|
||||
char *encrypted = vigenere_encrypt(key, input);
|
||||
char *decrypted = vigenere_decrypt(key, encrypted);
|
||||
|
||||
ASSERT(encrypted != NULL);
|
||||
ASSERT(decrypted != NULL);
|
||||
|
||||
for (size_t i = 0; i < length; i++) {
|
||||
ASSERT(encrypted[i] == output[i]);
|
||||
ASSERT(decrypted[i] == toupper(input[i]));
|
||||
}
|
||||
|
||||
free(encrypted);
|
||||
free(decrypted);
|
||||
}
|
||||
|
||||
TEST(VIGENERE)
|
||||
{
|
||||
SUBTEST(HELLO_WORLD)
|
||||
{
|
||||
test_vigenere("CoMPuTeR", "Hello world!", "JSXAI PSINR!", 12);
|
||||
}
|
||||
SUBTEST(MALLOC)
|
||||
{
|
||||
test_vigenere("fails", "malloc", "RATWGH", 6);
|
||||
}
|
||||
SUBTEST(CALLOC)
|
||||
{
|
||||
test_vigenere("fails", "calloc", "HATWGH", 6);
|
||||
}
|
||||
SUBTEST(REALLOC)
|
||||
{
|
||||
test_vigenere("fails", "realloc", "WEIWDTC", 7);
|
||||
}
|
||||
SUBTEST(EVERYTHING)
|
||||
{
|
||||
test_vigenere("FAILS", "everything", "JVMCQYHQYY", 10);
|
||||
}
|
||||
SUBTEST(FAILING)
|
||||
{
|
||||
test_vigenere("fails", "failing", "KAQWASG", 7);
|
||||
}
|
||||
SUBTEST(LOL)
|
||||
{
|
||||
test_vigenere("oopsie", "LOL", "ZCA", 3);
|
||||
}
|
||||
SUBTEST(GARBAGE)
|
||||
{
|
||||
test_vigenere("fi", "1273912739&^%$$*((", "1273912739&^%$$*((", 18);
|
||||
}
|
||||
SUBTEST(HELLO_FI)
|
||||
{
|
||||
test_vigenere("fi", "hello", "MMQTT", 5);
|
||||
}
|
||||
SUBTEST(BYE_FI)
|
||||
{
|
||||
test_vigenere("fi", "bye", "GGJ", 3);
|
||||
}
|
||||
}
|
||||
|
||||
void test_bmp(const char *key, const char *input, const unsigned char *encrypted_expected, const char *decrypted_expected, size_t length)
|
||||
{
|
||||
unsigned char *encrypted = bmp_encrypt(key, input);
|
||||
char *decrypted = bmp_decrypt(key, encrypted);
|
||||
|
||||
ASSERT(encrypted != NULL);
|
||||
ASSERT(decrypted != NULL);
|
||||
|
||||
for (size_t i = 0; i < length; i++) {
|
||||
ASSERT(encrypted[i] == encrypted_expected[i]);
|
||||
ASSERT(decrypted[i] == decrypted_expected[i]);
|
||||
}
|
||||
|
||||
free(encrypted);
|
||||
free(decrypted);
|
||||
}
|
||||
|
||||
TEST(BMP)
|
||||
{
|
||||
SUBTEST(HELLO)
|
||||
{
|
||||
const unsigned char encrypted_expected[] = { 0xae, 0xae, 0xab, 0x85, 0x85 };
|
||||
test_bmp("fi", "hello", encrypted_expected, "HELLO", 5);
|
||||
}
|
||||
SUBTEST(FI)
|
||||
{
|
||||
const unsigned char encrypted_expected[] = { 0xaa, 0x82 };
|
||||
test_bmp("hello", "fi", encrypted_expected, "FI", 2);
|
||||
}
|
||||
SUBTEST(RANDOM)
|
||||
{
|
||||
const unsigned char encrypted_expected[] = { 0xa9, 0x87, 0xaf, 0x87, 0x89, 0xa2 };
|
||||
test_bmp("garbage", "random", encrypted_expected, "RANDOM", 6);
|
||||
}
|
||||
SUBTEST(LETS)
|
||||
{
|
||||
const unsigned char encrypted_expected[] = { 0x83, 0xa2, 0x81, 0x8c };
|
||||
test_bmp("see", "lets", encrypted_expected, "LETS", 4);
|
||||
}
|
||||
SUBTEST(how)
|
||||
{
|
||||
const unsigned char encrypted_expected[] = { 0x8d, 0x80, 0xaa };
|
||||
test_bmp("it", "how", encrypted_expected, "HOW", 3);
|
||||
}
|
||||
SUBTEST(works)
|
||||
{
|
||||
const unsigned char encrypted_expected[] = { 0xa9, 0x8b, 0x89, 0xa8, 0x80 };
|
||||
test_bmp("asjdljasdja", "works", encrypted_expected, "WORKS", 5);
|
||||
}
|
||||
SUBTEST(NOSPACES)
|
||||
{
|
||||
const unsigned char encrypted_expected[] = { 0x8d, 0x81, 0x82, 0x85, 0xae, 0xa0, 0x89, 0xa8, 0xa0, 0x85, 0x84, 0x89, 0x85, 0x84, 0x89, 0x8e, 0x8a, 0x84, 0x8e, 0xac, 0x84, 0xa9, 0xa8, 0xac, 0xa2 };
|
||||
test_bmp("meh", "longerTextThatHasNoSpaces", encrypted_expected, "LONGERTEXTTHATHASNOSPACES", 25);
|
||||
}
|
||||
SUBTEST(ayaya)
|
||||
{
|
||||
const unsigned char encrypted_expected[] = { 0x80, 0xa9, 0x80, 0x8e, 0xaf, 0x8e, 0x80, 0xa9, 0x80, 0x8e, 0xaf, 0x8e, 0x80, 0xa9, 0x80, 0x8e, 0xaf, 0x8e, 0x80, 0xa9, 0x80, 0x8e, 0xaf, 0x8e, 0x80, 0xa9, 0x80, 0x8e, 0xaf, 0x8e, 0x80, 0xa9, 0x80 };
|
||||
test_bmp("HUH", "ayayayayayayayayayayayayayayayaya", encrypted_expected, "AYAYAYAYAYAYAYAYAYAYAYAYAYAYAYAYA", 33);
|
||||
}
|
||||
}
|
24
static/files/pb071/bonuses/08/CMakeLists.txt
Normal file
24
static/files/pb071/bonuses/08/CMakeLists.txt
Normal file
|
@ -0,0 +1,24 @@
|
|||
cmake_minimum_required(VERSION 3.0)
|
||||
|
||||
# Project configuration
|
||||
project(seminar08-bonus)
|
||||
set(SOURCES counting.c trees.c)
|
||||
|
||||
# Executable
|
||||
add_executable(counting counting.c)
|
||||
add_executable(trees trees.c)
|
||||
|
||||
# Configure compiler warnings
|
||||
if (CMAKE_C_COMPILER_ID MATCHES Clang OR ${CMAKE_C_COMPILER_ID} STREQUAL GNU)
|
||||
# using regular Clang, AppleClang or GCC
|
||||
# Strongly suggested: neable -Werror
|
||||
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=gnu11 -Wall -Wextra -pedantic")
|
||||
elseif (${CMAKE_C_COMPILER_ID} STREQUAL MSVC)
|
||||
# using Visual Studio C++
|
||||
target_compile_definitions(${EXECUTABLE} PRIVATE _CRT_SECURE_NO_DEPRECATE)
|
||||
set(CMAKE_CXX_FLAGS "/permissive- /W4 /EHsc")
|
||||
endif()
|
||||
|
||||
if(MINGW)
|
||||
target_compile_definitions(${EXECUTABLE} PRIVATE __USE_MINGW_ANSI_STDIO=1)
|
||||
endif()
|
10
static/files/pb071/bonuses/08/Makefile
Normal file
10
static/files/pb071/bonuses/08/Makefile
Normal file
|
@ -0,0 +1,10 @@
|
|||
check-counting:
|
||||
python3 test-bonus.py test counting
|
||||
|
||||
check-counting-bonus:
|
||||
python3 test-bonus.py test counting --no-global-config
|
||||
|
||||
check: check-counting check-counting-bonus
|
||||
|
||||
clean:
|
||||
rm -rf test-*/*.out_produced
|
60
static/files/pb071/bonuses/08/counting.c
Normal file
60
static/files/pb071/bonuses/08/counting.c
Normal file
|
@ -0,0 +1,60 @@
|
|||
#include <ctype.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
#define UNUSED(x) ((void) (x))
|
||||
|
||||
/**
|
||||
* @brief Counts occurences of any substring in the file.
|
||||
* @param file File where the substring is to be counted in.
|
||||
* @param substring Substring to be counted.
|
||||
* @returns Count of occurences of the substring the given file.
|
||||
*/
|
||||
long count_anything(FILE *file, const char *substring)
|
||||
{
|
||||
/* TODO */
|
||||
UNUSED(file);
|
||||
UNUSED(substring);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Counts ananas. Nothing more to it.
|
||||
* @param file File where the ananas is to be counted in.
|
||||
* @returns Count of occurences of ananas.
|
||||
*/
|
||||
long count_ananas(FILE *file)
|
||||
{
|
||||
return count_anything(file, "ananas");
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Writes given number to the file, character by character.
|
||||
* @param file File where the number is supposed to be written.
|
||||
* @param number Number to be written.
|
||||
*/
|
||||
void write_number(FILE *file, long number)
|
||||
{
|
||||
/* TODO */
|
||||
UNUSED(file);
|
||||
UNUSED(number);
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Main function of a program.
|
||||
* @returns Exit code that denotes following:
|
||||
* 0 in case of success
|
||||
* 1 in case of invalid usage
|
||||
* 2 in case of failure on input file
|
||||
* 3 in case of failure on output file
|
||||
*/
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
if (argc < 3 || argc > 4) {
|
||||
printf("Usage: %s <input-file> <output-file> [string-to-be-counted]\n", argv[0]);
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* TODO */
|
||||
return 0;
|
||||
}
|
4
static/files/pb071/bonuses/08/counting.json
Normal file
4
static/files/pb071/bonuses/08/counting.json
Normal file
|
@ -0,0 +1,4 @@
|
|||
{
|
||||
"args": ["{test_case}.in", "{test_case}.out_produced"],
|
||||
"specialized_test": ["diff", "{test_case}.out", "{test_case}.out_produced"]
|
||||
}
|
1
static/files/pb071/bonuses/08/test-bonus.py
Symbolic link
1
static/files/pb071/bonuses/08/test-bonus.py
Symbolic link
|
@ -0,0 +1 @@
|
|||
../../test-bonus.py
|
1
static/files/pb071/bonuses/08/test-counting/basic.in
Normal file
1
static/files/pb071/bonuses/08/test-counting/basic.in
Normal file
|
@ -0,0 +1 @@
|
|||
ananas
|
1
static/files/pb071/bonuses/08/test-counting/basic.out
Normal file
1
static/files/pb071/bonuses/08/test-counting/basic.out
Normal file
|
@ -0,0 +1 @@
|
|||
1
|
File diff suppressed because one or more lines are too long
|
@ -0,0 +1 @@
|
|||
1747627
|
File diff suppressed because one or more lines are too long
|
@ -0,0 +1 @@
|
|||
0
|
0
static/files/pb071/bonuses/08/test-counting/empty.in
Normal file
0
static/files/pb071/bonuses/08/test-counting/empty.in
Normal file
1
static/files/pb071/bonuses/08/test-counting/empty.out
Normal file
1
static/files/pb071/bonuses/08/test-counting/empty.out
Normal file
|
@ -0,0 +1 @@
|
|||
0
|
65
static/files/pb071/bonuses/08/test-counting/fgetc.in
Normal file
65
static/files/pb071/bonuses/08/test-counting/fgetc.in
Normal file
|
@ -0,0 +1,65 @@
|
|||
FGETC(3) Linux Programmer's Manual FGETC(3)
|
||||
|
||||
NAME
|
||||
fgetc, fgets, getc, getchar, ungetc - input of characters and strings
|
||||
|
||||
SYNOPSIS
|
||||
#include <stdio.h>
|
||||
|
||||
int fgetc(FILE *stream);
|
||||
|
||||
char *fgets(char *s, int size, FILE *stream);
|
||||
|
||||
int getc(FILE *stream);
|
||||
|
||||
int getchar(void);
|
||||
|
||||
int ungetc(int c, FILE *stream);
|
||||
|
||||
DESCRIPTION
|
||||
fgetc() reads the next character from stream and returns it as an unsigned char cast to an int, or EOF on end of file or error.
|
||||
|
||||
getc() is equivalent to fgetc() except that it may be implemented as a macro which evaluates stream more than once.
|
||||
|
||||
getchar() is equivalent to getc(stdin).
|
||||
|
||||
fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into the buf‐
|
||||
fer. A terminating null byte ('\0') is stored after the last character in the buffer.
|
||||
|
||||
ungetc() pushes c back to stream, cast to unsigned char, where it is available for subsequent read operations. Pushed-back characters will be returned in reverse order; only one pushback is guaranteed.
|
||||
|
||||
Calls to the functions described here can be mixed with each other and with calls to other input functions from the stdio library for the same input stream.
|
||||
|
||||
For nonlocking counterparts, see unlocked_stdio(3).
|
||||
|
||||
RETURN VALUE
|
||||
fgetc(), getc() and getchar() return the character read as an unsigned char cast to an int or EOF on end of file or error.
|
||||
|
||||
fgets() returns s on success, and NULL on error or when end of file occurs while no characters have been read.
|
||||
|
||||
ungetc() returns c on success, or EOF on error.
|
||||
|
||||
ATTRIBUTES
|
||||
For an explanation of the terms used in this section, see attributes(7).
|
||||
|
||||
┌──────────────────────────┬───────────────┬─────────┐
|
||||
│Interface │ Attribute │ Value │
|
||||
├──────────────────────────┼───────────────┼─────────┤
|
||||
│fgetc(), fgets(), getc(), │ Thread safety │ MT-Safe │
|
||||
│getchar(), ungetc() │ │ │
|
||||
└──────────────────────────┴───────────────┴─────────┘
|
||||
|
||||
CONFORMING TO
|
||||
POSIX.1-2001, POSIX.1-2008, C89, C99.
|
||||
|
||||
It is not advisable to mix calls to input functions from the stdio library with low-level calls to read(2) for the file descriptor associated with the input stream; the results will be undefined and very prob‐
|
||||
ably not what you want.
|
||||
|
||||
SEE ALSO
|
||||
read(2), write(2), ferror(3), fgetwc(3), fgetws(3), fopen(3), fread(3), fseek(3), getline(3), gets(3), getwchar(3), puts(3), scanf(3), ungetwc(3), unlocked_stdio(3), feature_test_macros(7)
|
||||
|
||||
COLOPHON
|
||||
This page is part of release 5.07 of the Linux man-pages project. A description of the project, information about reporting bugs, and the latest version of this page, can be found at
|
||||
https://www.kernel.org/doc/man-pages/.
|
||||
|
||||
GNU 2017-09-15 FGETC(3)
|
4
static/files/pb071/bonuses/08/test-counting/fgetc.json
Normal file
4
static/files/pb071/bonuses/08/test-counting/fgetc.json
Normal file
|
@ -0,0 +1,4 @@
|
|||
{
|
||||
"args": ["{test_case}.in", "{test_case}.out_produced", "getc"],
|
||||
"specialized_test": ["diff", "{test_case}.out", "{test_case}.out_produced"]
|
||||
}
|
1
static/files/pb071/bonuses/08/test-counting/fgetc.out
Normal file
1
static/files/pb071/bonuses/08/test-counting/fgetc.out
Normal file
|
@ -0,0 +1 @@
|
|||
25
|
|
@ -0,0 +1 @@
|
|||
ananas bananas banana nanas nana
|
|
@ -0,0 +1,4 @@
|
|||
{
|
||||
"args": ["{test_case}.in", "{test_case}.out_produced", "banana"],
|
||||
"specialized_test": ["diff", "{test_case}.out", "{test_case}.out_produced"]
|
||||
}
|
|
@ -0,0 +1 @@
|
|||
2
|
31
static/files/pb071/bonuses/08/test-counting/lorem_empty.in
Normal file
31
static/files/pb071/bonuses/08/test-counting/lorem_empty.in
Normal file
|
@ -0,0 +1,31 @@
|
|||
|
||||
|
||||
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi auctor euismod enim a sodales. Praesent efficitur pharetra mi, et finibus nulla pellentesque euismod. Sed fringilla sed mi in aliquet. Quisque eu nibh id arcu suscipit tempus. Mauris quam urna, volutpat id iaculis non, lobortis a orci. Quisque commodo lectus sit amet nisl mattis accumsan. Proin iaculis erat in elementum dapibus.
|
||||
|
||||
Aliquam commodo congue neque id porta. Aliquam dictum justo est, a vulputate diam ullamcorper ac. Etiam cursus augue eu porttitor sagittis. Fusce egestas tellus quis semper egestas. Nunc metus neque, accumsan non nulla in, fringilla tincidunt tellus. Aliquam in tempus eros. Donec ornare leo in neque pretium mattis. Morbi consequat lacus vitae justo auctor, eget interdum lorem tincidunt. Morbi at nisl lobortis, ultricies augue a, viverra libero. Phasellus sit amet magna aliquam, scelerisque lectus sit amet, euismod eros.
|
||||
|
||||
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris in ipsum dui. Maecenas euismod est a dui euismod tristique. Maecenas tincidunt diam ut velit rutrum, a bibendum ligula pellentesque. Maecenas sit amet turpis a mi tristique vulputate non vitae metus. Aenean ut lectus ut eros maximus hendrerit at sed arcu. Nulla condimentum velit non mauris consectetur tempor. Duis fringilla ligula aliquam massa malesuada dignissim. Suspendisse dignissim arcu et augue tristique vestibulum. Nam auctor vulputate dignissim. Integer eget ultrices elit. Vivamus placerat sit amet mauris et lacinia. Maecenas lacinia ipsum blandit justo efficitur congue. Aliquam erat volutpat. Vivamus risus enim, mattis ac lacus molestie, blandit volutpat elit.
|
||||
|
||||
Mauris id arcu vitae urna finibus scelerisque. Nullam dictum interdum lacinia. Nunc congue turpis malesuada velit maximus suscipit. Pellentesque quis interdum risus. Quisque leo massa, viverra in condimentum quis, pharetra ut est. Nullam vehicula tempus elit sit amet placerat. Integer elementum, mauris eget rhoncus sagittis, est massa laoreet felis, sed ultricies risus urna et mi. Proin commodo ut libero in commodo. Nullam consequat tellus non tellus cursus, eget luctus tellus tempor. Proin ante risus, convallis et ex ac, cursus auctor turpis. Integer et mauris ut enim suscipit laoreet. Nulla tortor augue, eleifend id faucibus sed, faucibus eu turpis. Sed vel nibh non tortor venenatis dignissim. Nunc vel maximus mauris.
|
||||
|
||||
Mauris porta nunc eros, vel mattis augue dignissim in. Nunc tempus ac purus dignissim dapibus. Nulla sit amet ipsum dapibus, viverra dolor eu, pharetra lectus. Sed maximus felis justo. Cras nec condimentum nisl. Donec vitae metus suscipit, auctor augue in, blandit purus. Pellentesque viverra non est id mollis. Aenean fermentum nisi sit amet urna tincidunt, eget accumsan mauris bibendum. In vestibulum consectetur erat, ac gravida odio ultrices eu. Nullam quam mi, sagittis a nisl quis, vestibulum ultrices est.
|
||||
|
||||
In ut tempus nibh. Morbi consectetur gravida feugiat. Morbi non eros ut dui faucibus sagittis. Duis euismod metus quis enim aliquet iaculis. Pellentesque pellentesque sed lorem vitae euismod. Aliquam luctus fringilla urna, eget hendrerit augue. Aliquam malesuada nisl id eros viverra aliquam id ut sem. Mauris vel arcu eget nisi finibus varius in vitae arcu. Maecenas aliquet gravida quam feugiat vestibulum. Maecenas id nunc sit amet nulla imperdiet pharetra quis eu lectus. In pellentesque mattis bibendum. Proin ultrices eget turpis eu accumsan. In porttitor ante eget odio mattis egestas.
|
||||
|
||||
Mauris lacinia lacus vel eleifend mattis. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Donec eu quam orci. Vestibulum fermentum, odio iaculis porta semper, enim lorem faucibus nisl, eu vulputate enim turpis quis massa. Cras hendrerit pulvinar ante id mattis. Phasellus vitae neque lobortis, aliquam purus in, commodo ex. Aenean suscipit metus non sollicitudin porttitor. Maecenas a justo cursus, mattis ligula ut, vestibulum felis. Curabitur dapibus finibus lectus nec porttitor. Integer fringilla, dolor in varius sodales, purus risus bibendum tortor, in eleifend risus neque a elit. Phasellus placerat enim at nulla aliquam luctus. Nunc consequat placerat ornare. Suspendisse faucibus gravida arcu id ullamcorper.
|
||||
|
||||
Praesent dapibus mauris eu purus maximus vehicula. Nulla ultrices luctus eleifend. Etiam efficitur aliquam diam eu varius. Sed quis lacus volutpat, aliquet eros convallis, interdum erat. In auctor ipsum vitae massa rhoncus, nec sagittis purus gravida. Nullam condimentum fringilla euismod. Proin congue nisi ut est lacinia elementum.
|
||||
|
||||
Maecenas leo ex, mattis non neque ut, rutrum pulvinar enim. Morbi malesuada mollis risus, sed faucibus eros ultrices at. Aenean aliquet in odio sit amet rhoncus. Nulla nisi neque, vestibulum a sem sed, consectetur convallis neque. Nullam ac lectus vel eros luctus tincidunt rhoncus eu dui. Pellentesque vitae lorem congue, pretium felis vel, mattis velit. Nullam nulla elit, convallis eu congue sed, ultricies nec diam. Mauris et ligula dui. Praesent sit amet laoreet dolor. Aliquam erat volutpat. Nam feugiat iaculis vestibulum. Ut eget turpis at diam interdum finibus. Aliquam dictum fermentum dui, eget lobortis nibh interdum sagittis.
|
||||
|
||||
Nullam elit sapien, mollis sed convallis a, consectetur at ipsum. Integer viverra consequat turpis vel elementum. Aliquam tincidunt et est sit amet condimentum. Aenean nec sem semper, semper urna quis, aliquet ante. Duis malesuada, massa sit amet congue feugiat, sem diam accumsan lectus, at vestibulum dui libero non lectus. Maecenas nunc tortor, varius sed libero in, placerat consequat neque. Maecenas rutrum sem enim, vel hendrerit dolor luctus nec. Aliquam fringilla purus sagittis consequat pretium. Suspendisse iaculis pharetra est, eleifend elementum mauris viverra eu. Ut pellentesque tempus ipsum, ac maximus risus imperdiet ac. Nulla felis mauris, molestie eu aliquet non, pretium sit amet ante. Integer id cursus mauris. Nunc a mattis magna, nec luctus magna. Mauris sed vehicula nisi, id tincidunt mauris. Curabitur aliquam, eros vitae ultricies interdum, nunc felis placerat enim, eget maximus dui massa vel eros. Mauris turpis est, pretium ut fringilla at, lacinia non eros.
|
||||
|
||||
Mauris nulla massa, facilisis ut dui at, consequat dignissim felis. Pellentesque vitae nibh sed dui convallis faucibus a et risus. In id mauris ligula. Nunc nec ante sem. Curabitur purus eros, molestie ut nunc ut, cursus hendrerit est. Mauris bibendum viverra rhoncus. Nulla varius fringilla nulla, ac hendrerit neque tincidunt sed. Morbi malesuada bibendum elementum. In hac habitasse platea dictumst. Mauris at massa sed massa auctor pellentesque quis quis est. Fusce pharetra, sem nec malesuada consectetur, sapien nisl fermentum nisi, ac volutpat sapien sapien id ligula.
|
||||
|
||||
Mauris finibus ligula ac dolor feugiat, ac pellentesque felis venenatis. Cras scelerisque tempus libero, quis sollicitudin nunc pellentesque nec. Praesent pulvinar leo turpis, vel sagittis ligula dignissim ac. Nam ut bibendum diam. Etiam fermentum nunc tellus, sed ultrices neque porttitor a. Quisque placerat dignissim eros. Phasellus consectetur nisl erat, id luctus lacus scelerisque quis. Aenean mattis molestie mi, ac rhoncus felis congue id. Aliquam erat volutpat. Vestibulum ac accumsan dui. Phasellus a orci nec lacus rhoncus semper eu ac sapien.
|
||||
|
||||
Sed finibus, lectus eget interdum vehicula, lorem tortor ornare urna, id lacinia eros sem eu urna. Pellentesque consectetur vulputate arcu vitae aliquam. Aenean eleifend tempor dui. Mauris lectus diam, euismod vitae posuere et, pulvinar quis nulla. Donec sagittis vestibulum mi quis molestie. Sed eu lectus quis nunc vulputate tristique. Proin imperdiet nibh lectus. Nunc sagittis risus libero, sit amet dignissim ligula mollis a. Proin auctor, eros non condimentum fringilla, dolor neque consequat augue, quis ullamcorper velit nibh id nibh. Quisque mollis sit amet justo nec ultrices. Mauris vel commodo felis, porttitor rutrum turpis.
|
||||
|
||||
In et lacus quis ante commodo suscipit ac et leo. Nam in dui diam. Nulla molestie lacus ac nunc laoreet, vel lobortis nulla suscipit. Ut iaculis feugiat tincidunt. Vestibulum ut pharetra enim, vel pellentesque leo. Pellentesque sit amet rutrum mauris. Nullam ultricies augue id est interdum, sit amet consectetur eros eleifend.
|
||||
|
||||
Aliquam ac pretium arcu, quis viverra mi. Mauris tincidunt tincidunt libero, id aliquam ipsum scelerisque quis. Donec vitae purus et eros dapibus pulvinar. Interdum et malesuada fames ac ante ipsum primis in faucibus. Duis efficitur tempus tortor, et sodales augue ultricies sed. Phasellus nec finibus lacus, in aliquet turpis. Maecenas id turpis augue. Nunc finibus turpis purus, aliquam tempor magna ullamcorper ut. Morbi sit amet erat gravida, egestas metus vel, porttitor diam.
|
|
@ -0,0 +1 @@
|
|||
0
|
31
static/files/pb071/bonuses/08/test-counting/lorem_some.in
Normal file
31
static/files/pb071/bonuses/08/test-counting/lorem_some.in
Normal file
|
@ -0,0 +1,31 @@
|
|||
|
||||
|
||||
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi auctor euismod enim a sodales. Praesent efficitur pharetra mi, et finibus nulla pellentesque euismod. Sed fringilla sed mi in aliquet. Quisque eu nibh id arcu suscipit tempus. Mauris quam urna, volutpat id iaculis non, lobortis a orci. Quisque commodo lectus sit amet nisl mattis accumsan. Proin iaculis erat in elementum dapibus.
|
||||
|
||||
Aliquam commodo congue neque id porta. Aliquam dictum justo est, a vulputate diam ullamcorper ac. Etiam cursus augue eu porttitor sagittis. Fusce egestas tellus quis semper egestas. Nunc metus neque, accumsan non nulla in, fringilla tincidunt tellus. Aliquam in tempus eros. Donec ornare leo in neque pretium mattis. Morbi consequat lacus vitae justo auctor, eget interdum lorem tincidunt. Morbi at nisl lobortis, ultricies augue a, viverra libero. Phasellus sit amet magna aliquam, scelerisque lectus sit amet, euismod eros.
|
||||
|
||||
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris in nananananananas dui. Maecenas euismod est a dui euismod tristique. Maecenas tincidunt diam ut velit rutrum, a bibendum ligula ananas. Maecenas sit amet turpis a mi tristique vulputate non vitae metus. Aenean ut lectus ut eros maximus hendrerit at sed arcu. Nulla condimentum velit non mauris consectetur tempor. Duis fringilla ligula aliquam massa malesuada dignissim. Suspendisse dignissim arcu et augue tristique vestibulum. Nam auctor vulputate dignissim. Integer eget ultrices elit. Vivamus placerat sit amet mauris et lacinia. Maecenas lacinia ipsum blandit justo efficitur congue. Aliquam erat volutpat. Vivamus risus enim, mattis ac lacus molestie, blandit volutpat elit.
|
||||
|
||||
Mauris id arcu vitae urna finibus scelerisque. Nullam dictum interdum lacinia. Nunc congue turpis malesuada velit maximus suscipit. Pellentesque quis interdum risus. Quisque leo massa, viverra in condimentum quis, pharetra ut est. Nullam vehicula tempus elit sit amet placerat. Integer elementum, mauris eget rhoncus sagittis, est massa laoreet felis, sed ultricies risus urna et mi. Proin commodo ut libero in commodo. Nullam consequat tellus non tellus cursus, eget luctus tellus tempor. Proin ante risus, convallis et ex ac, cursus auctor turpis. Integer et mauris ut enim suscipit laoreet. Nulla tortor augue, eleifend id faucibus sed, faucibus eu turpis. Sed vel nibh non tortor venenatis dignissim. Nunc vel maximus mauris.
|
||||
|
||||
Mauris porta nunc eros, vel mattis augue dignissim in. Nunc tempus ac purus dignissim dapibus. Nulla sit amet ipsum dapibus, viverra dolor eu, pharetra lectus. Sed maximus felis justo. Cras nec condimentum nisl. Donec vitae metus suscipit, auctor augue in, blandit purus. Pellentesque viverra non est id mollis. Aenean fermentum nisi sit amet urna tincidunt, eget accumsan mauris bibendum. In vestibulum consectetur erat, ac gravida odio ultrices eu. Nullam quam mi, sagittis a nisl quis, vestibulum ultrices est.
|
||||
|
||||
In ut tempus nibh. Morbi consectetur gravida feugiat. Morbi non eros ut dui ananas sagittis. Duis euismod metus quis enim aliquet iaculis. Pellentesque pellentesque sed lorem vitae euismod. Aliquam luctus fringilla urna, eget hendrerit augue. Aliquam malesuada nisl id eros viverra aliquam id ut sem. Mauris vel arcu eget nisi finibus varius in vitae arcu. Maecenas aliquet gravida quam feugiat vestibulum. Maecenas id nunc sit amet nulla imperdiet pharetra quis eu lectus. In pellentesque mattis bibendum. Proin ultrices eget turpis eu accumsan. In porttitor ante eget odio mattis egestas.
|
||||
anans
|
||||
Mauris lacinia lacus vel eleifend mattis. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Donec eu aaaaaaaaaaaaaaaaaaaaaaaaaaaaananas orci. Vestibulum fermentum, odio iaculis porta semper, enim lorem faucibus nisl, eu vulputate enim turpis quis massa. Cras hendrerit pulvinar ante id mattis. Phasellus vitae neque lobortis, aliquam purus in, commodo ex. Aenean suscipit metus non sollicitudin porttitor. Maecenas a justo cursus, mattis ligula ut, vestibulum felis. Curabitur dapibus finibus lectus nec porttitor. Integer fringilla, dolor in varius sodales, purus risus bibendum tortor, in eleifend risus neque a elit. Phasellus placerat enim at nulla aliquam luctus. Nunc consequat placerat ornare. Suspendisse faucibus gravida arcu id ullamcorper.
|
||||
ananas
|
||||
Praesent dapibus mauris eu purus maximus vehicula. Nulla ultrices luctus eleifend. Etiam efficitur aliquam diam eu varius. Sed quis lacus volutpat, aliquet eros convallis, interdum erat. In auctor ipsum vitae massa rhoncus, nec sagittis purus gravida. Nullam condimentum fringilla euismod. Proin congue nisi ut est lacinia elementum.
|
||||
|
||||
Maecenas leo ex, mattis non neque ut, rutrum pulvinar enim. Morbi malesuada mollis risus, sed faucibus eros ultrices at. Aenean aliquet in aaaaaaaaaaaaaaaaaaaaaaaaaaaaananas sit amet rhoncus. Nulla nisi neque, vestibulum a sem sed, consectetur convallis neque. Nullam ac lectus vel eros luctus tincidunt rhoncus eu dui. Pellentesque vitae lorem congue, pretium felis vel, mattis velit. Nullam nulla elit, convallis eu congue sed, ultricies nec diam. Mauris et ligula dui. Praesent sit amet laoreet dolor. Aliquam erat volutpat. Nam feugiat iaculis vestibulum. Ut eget turpis at diam interdum finibus. Aliquam dictum fermentum dui, eget lobortis nibh interdum sagittis.
|
||||
|
||||
Nullam elit sapien, mollis sed convallis a, consectetur at ipsum. Integer viverra consequat turpis vel elementum. Aliquam tincidunt et est sit amet condimentum. Aenean nec sem semper, semper urna quis, aliquet ante. Duis malesuada, massa sit amet congue feugiat, sem diam accumsan lectus, at vestibulum dui libero non lectus. Maecenas nunc tortor, varius sed libero in, placerat consequat neque. Maecenas rutrum sem enim, vel hendrerit dolor luctus nec. Aliquam fringilla purus sagittis consequat pretium. Suspendisse iaculis pharetra est, eleifend elementum mauris viverra eu. Ut pellentesque tempus ipsum, ac maximus risus imperdiet ac. Nulla felis mauris, molestie eu aliquet non, pretium sit amet ante. Integer id cursus mauris. Nunc a mattis magna, nec luctus magna. Mauris sed vehicula nisi, id tincidunt mauris. Curabitur aliquam, eros vitae ultricies interdum, nunc felis placerat enim, eget maximus dui massa vel eros. Mauris turpis est, pretium ut fringilla at, lacinia non eros.
|
||||
|
||||
Mauris nulla massa, facilisis ut dui at, consequat dignissim felis. Pellentesque vitae nibh sed dui convallis faucibus a et risus. In id mauris ligula. Nunc nec ante sem. Curabitur purus eros, molestie ut nunc ut, cursus hendrerit est. Mauris bibendum viverra rhoncus. Nulla varius fringilla nulla, ac hendrerit neque tincidunt sed. Morbi malesuada bibendum elementum. In hac habitasse platea dictumst. Mauris at massa sed massa auctor pellentesque quis quis est. Fusce pharetra, sem nec malesuada consectetur, sapien nisl fermentum nisi, ac volutpat sapien sapien id ligula.
|
||||
|
||||
Mauris finibus ligula ac dolor feugiat, ac pellentesque felis venenatis. Cras anaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaanas tempus libero, quis sollicitudin nunc pellentesque nec. Praesent pulvinar leo turpis, vel sagittis ligula dignissim ac. Nam ut bibendum diam. Etiam fermentum nunc tellus, sed ultrices neque porttitor a. Quisque placerat dignissim eros. Phasellus consectetur nisl erat, id luctus lacus scelerisque quis. Aenean mattis molestie mi, ac rhoncus felis congue id. Aliquam erat volutpat. Vestibulum ac accumsan dui. Phasellus a orci nec lacus rhoncus semper eu ac sapien.
|
||||
|
||||
Sed finibus, lectus eget interdum vehicula, lorem tortor ornare urna, id lacinia eros sem eu urna. Pellentesque consectetur vulputate arcu vitae aliquam. Aenean eleifend tempor dui. Mauris lectus diam, euismod vitae posuere et, pulvinar quis nulla. Donec sagittis vestibulum mi quis molestie. Sed eu lectus quis nunc vulputate tristique. Proin imperdiet nibh lectus. Nunc sagittis risus libero, sit amet dignissim ligula mollis a. Proin auctor, eros non condimentum fringilla, dolor neque consequat augue, quis ullamcorper velit nibh id nibh. Quisque mollis sit amet justo nec ultrices. Mauris vel commodo felis, porttitor rutrum turpis.
|
||||
ananas
|
||||
In et lacus quis ante commodo suscipit ac et leo. Nam in dui diam. Nulla molestie lacus ac nunc laoreet, vel lobortis nulla suscipit. Ut iaculis feugiat tincidunt. Vestibulum ut pharetra enim, vel pellentesque leo. Pellentesque sit amet rutrum mauris. Nullam ultricies augue id est interdum, sit amet consectetur eros eleifend.
|
||||
|
||||
Aliquam ac pretium arcu, quis viverra mi. Mauris tincidunt tincidunt libero, id aliquam ipsum scelerisque quis. Donec vitae purus et eros dapibus pulvinar. Interdum et malesuada fames ac ante ipsum primis in faucibus. Duis efficitur tempus tortor, et sodales augue ultricies sed. Phasellus nec finibus lacus, in aliquet turpis. Maecenas id turpis augue. Nunc finibus turpis purus, aliquam tempor magna ullamcorper ut. Morbi sit amet erat gravida, egestas metus vel, porttitor diam.
|
|
@ -0,0 +1 @@
|
|||
7
|
264
static/files/pb071/bonuses/08/test-counting/mmap.in
Normal file
264
static/files/pb071/bonuses/08/test-counting/mmap.in
Normal file
|
@ -0,0 +1,264 @@
|
|||
MMAP(3P) POSIX Programmer's Manual MMAP(3P)
|
||||
|
||||
PROLOG
|
||||
This manual page is part of the POSIX Programmer's Manual. The Linux implementation of this interface may differ (consult the corresponding Linux manual page for details of Linux behavior), or the interface may not be imple‐
|
||||
mented on Linux.
|
||||
|
||||
NAME
|
||||
mmap — map pages of memory
|
||||
|
||||
SYNOPSIS
|
||||
#include <sys/mman.h>
|
||||
|
||||
void *mmap(void *addr, size_t len, int prot, int flags,
|
||||
int fildes, off_t off);
|
||||
|
||||
DESCRIPTION
|
||||
The mmap() function shall establish a mapping between an address space of a process and a memory object.
|
||||
|
||||
The mmap() function shall be supported for the following memory objects:
|
||||
|
||||
* Regular files
|
||||
|
||||
* Shared memory objects
|
||||
|
||||
* Typed memory objects
|
||||
|
||||
Support for any other type of file is unspecified.
|
||||
|
||||
The format of the call is as follows:
|
||||
|
||||
pa=mmap(addr, len, prot, flags, fildes, off);
|
||||
|
||||
The mmap() function shall establish a mapping between the address space of the process at an address pa for len bytes to the memory object represented by the file descriptor fildes at offset off for len bytes. The value of pa
|
||||
is an implementation-defined function of the parameter addr and the values of flags, further described below. A successful mmap() call shall return pa as its result. The address range starting at pa and continuing for len
|
||||
bytes shall be legitimate for the possible (not necessarily current) address space of the process. The range of bytes starting at off and continuing for len bytes shall be legitimate for the possible (not necessarily current)
|
||||
offsets in the memory object represented by fildes.
|
||||
|
||||
If fildes represents a typed memory object opened with either the POSIX_TYPED_MEM_ALLOCATE flag or the POSIX_TYPED_MEM_ALLOCATE_CONTIG flag, the memory object to be mapped shall be that portion of the typed memory object al‐
|
||||
located by the implementation as specified below. In this case, if off is non-zero, the behavior of mmap() is undefined. If fildes refers to a valid typed memory object that is not accessible from the calling process, mmap()
|
||||
shall fail.
|
||||
|
||||
The mapping established by mmap() shall replace any previous mappings for those whole pages containing any part of the address space of the process starting at pa and continuing for len bytes.
|
||||
|
||||
If the size of the mapped file changes after the call to mmap() as a result of some other operation on the mapped file, the effect of references to portions of the mapped region that correspond to added or removed portions of
|
||||
the file is unspecified.
|
||||
|
||||
If len is zero, mmap() shall fail and no mapping shall be established.
|
||||
|
||||
The parameter prot determines whether read, write, execute, or some combination of accesses are permitted to the data being mapped. The prot shall be either PROT_NONE or the bitwise-inclusive OR of one or more of the other
|
||||
flags in the following table, defined in the <sys/mman.h> header.
|
||||
|
||||
┌──────────────────┬──────────────────────────┐
|
||||
│Symbolic Constant │ Description │
|
||||
├──────────────────┼──────────────────────────┤
|
||||
│PROT_READ │ Data can be read. │
|
||||
│PROT_WRITE │ Data can be written. │
|
||||
│PROT_EXEC │ Data can be executed. │
|
||||
│PROT_NONE │ Data cannot be accessed. │
|
||||
└──────────────────┴──────────────────────────┘
|
||||
If an implementation cannot support the combination of access types specified by prot, the call to mmap() shall fail.
|
||||
|
||||
An implementation may permit accesses other than those specified by prot; however, the implementation shall not permit a write to succeed where PROT_WRITE has not been set and shall not permit any access where PROT_NONE alone
|
||||
has been set. The implementation shall support at least the following values of prot: PROT_NONE, PROT_READ, PROT_WRITE, and the bitwise-inclusive OR of PROT_READ and PROT_WRITE. The file descriptor fildes shall have been
|
||||
opened with read permission, regardless of the protection options specified. If PROT_WRITE is specified, the application shall ensure that it has opened the file descriptor fildes with write permission unless MAP_PRIVATE is
|
||||
specified in the flags parameter as described below.
|
||||
|
||||
The parameter flags provides other information about the handling of the mapped data. The value of flags is the bitwise-inclusive OR of these options, defined in <sys/mman.h>:
|
||||
|
||||
┌──────────────────┬─────────────────────────┐
|
||||
│Symbolic Constant │ Description │
|
||||
├──────────────────┼─────────────────────────┤
|
||||
│MAP_SHARED │ Changes are shared. │
|
||||
│MAP_PRIVATE │ Changes are private. │
|
||||
│MAP_FIXED │ Interpret addr exactly. │
|
||||
└──────────────────┴─────────────────────────┘
|
||||
It is implementation-defined whether MAP_FIXED shall be supported. MAP_FIXED shall be supported on XSI-conformant systems.
|
||||
|
||||
MAP_SHARED and MAP_PRIVATE describe the disposition of write references to the memory object. If MAP_SHARED is specified, write references shall change the underlying object. If MAP_PRIVATE is specified, modifications to the
|
||||
mapped data by the calling process shall be visible only to the calling process and shall not change the underlying object. It is unspecified whether modifications to the underlying object done after the MAP_PRIVATE mapping
|
||||
is established are visible through the MAP_PRIVATE mapping. Either MAP_SHARED or MAP_PRIVATE can be specified, but not both. The mapping type is retained across fork().
|
||||
|
||||
The state of synchronization objects such as mutexes, semaphores, barriers, and conditional variables placed in shared memory mapped with MAP_SHARED becomes undefined when the last region in any process containing the syn‐
|
||||
chronization object is unmapped.
|
||||
|
||||
When fildes represents a typed memory object opened with either the POSIX_TYPED_MEM_ALLOCATE flag or the POSIX_TYPED_MEM_ALLOCATE_CONTIG flag, mmap() shall, if there are enough resources available, map len bytes allocated
|
||||
from the corresponding typed memory object which were not previously allocated to any process in any processor that may access that typed memory object. If there are not enough resources available, the function shall fail. If
|
||||
fildes represents a typed memory object opened with the POSIX_TYPED_MEM_ALLOCATE_CONTIG flag, these allocated bytes shall be contiguous within the typed memory object. If fildes represents a typed memory object opened with
|
||||
the POSIX_TYPED_MEM_ALLOCATE flag, these allocated bytes may be composed of non-contiguous fragments within the typed memory object. If fildes represents a typed memory object opened with neither the POSIX_TYPED_MEM_ALLO‐
|
||||
CATE_CONTIG flag nor the POSIX_TYPED_MEM_ALLOCATE flag, len bytes starting at offset off within the typed memory object are mapped, exactly as when mapping a file or shared memory object. In this case, if two processes map an
|
||||
area of typed memory using the same off and len values and using file descriptors that refer to the same memory pool (either from the same port or from a different port), both processes shall map the same region of storage.
|
||||
|
||||
When MAP_FIXED is set in the flags argument, the implementation is informed that the value of pa shall be addr, exactly. If MAP_FIXED is set, mmap() may return MAP_FAILED and set errno to [EINVAL]. If a MAP_FIXED request is
|
||||
successful, then any previous mappings or memory locks for those whole pages containing any part of the address range [pa,pa+len) shall be removed, as if by an appropriate call to munmap(), before the new mapping is estab‐
|
||||
lished.
|
||||
|
||||
When MAP_FIXED is not set, the implementation uses addr in an implementation-defined manner to arrive at pa. The pa so chosen shall be an area of the address space that the implementation deems suitable for a mapping of len
|
||||
bytes to the file. All implementations interpret an addr value of 0 as granting the implementation complete freedom in selecting pa, subject to constraints described below. A non-zero value of addr is taken to be a suggestion
|
||||
of a process address near which the mapping should be placed. When the implementation selects a value for pa, it never places a mapping at address 0, nor does it replace any extant mapping.
|
||||
|
||||
If MAP_FIXED is specified and addr is non-zero, it shall have the same remainder as the off parameter, modulo the page size as returned by sysconf() when passed _SC_PAGESIZE or _SC_PAGE_SIZE. The implementation may require
|
||||
that off is a multiple of the page size. If MAP_FIXED is specified, the implementation may require that addr is a multiple of the page size. The system performs mapping operations over whole pages. Thus, while the parameter
|
||||
len need not meet a size or alignment constraint, the system shall include, in any mapping operation, any partial page specified by the address range starting at pa and continuing for len bytes.
|
||||
|
||||
The system shall always zero-fill any partial page at the end of an object. Further, the system shall never write out any modified portions of the last page of an object which are beyond its end. References within the ad‐
|
||||
dress range starting at pa and continuing for len bytes to whole pages following the end of an object shall result in delivery of a SIGBUS signal.
|
||||
|
||||
An implementation may generate SIGBUS signals when a reference would cause an error in the mapped object, such as out-of-space condition.
|
||||
|
||||
The mmap() function shall add an extra reference to the file associated with the file descriptor fildes which is not removed by a subsequent close() on that file descriptor. This reference shall be removed when there are no
|
||||
more mappings to the file.
|
||||
|
||||
The last data access timestamp of the mapped file may be marked for update at any time between the mmap() call and the corresponding munmap() call. The initial read or write reference to a mapped region shall cause the file's
|
||||
last data access timestamp to be marked for update if it has not already been marked for update.
|
||||
|
||||
The last data modification and last file status change timestamps of a file that is mapped with MAP_SHARED and PROT_WRITE shall be marked for update at some point in the interval between a write reference to the mapped region
|
||||
and the next call to msync() with MS_ASYNC or MS_SYNC for that portion of the file by any process. If there is no such call and if the underlying file is modified as a result of a write reference, then these timestamps shall
|
||||
be marked for update at some time after the write reference.
|
||||
|
||||
There may be implementation-defined limits on the number of memory regions that can be mapped (per process or per system).
|
||||
|
||||
If such a limit is imposed, whether the number of memory regions that can be mapped by a process is decreased by the use of shmat() is implementation-defined.
|
||||
|
||||
If mmap() fails for reasons other than [EBADF], [EINVAL], or [ENOTSUP], some of the mappings in the address range starting at addr and continuing for len bytes may have been unmapped.
|
||||
|
||||
RETURN VALUE
|
||||
Upon successful completion, the mmap() function shall return the address at which the mapping was placed (pa); otherwise, it shall return a value of MAP_FAILED and set errno to indicate the error. The symbol MAP_FAILED is de‐
|
||||
fined in the <sys/mman.h> header. No successful return from mmap() shall return the value MAP_FAILED.
|
||||
|
||||
ERRORS
|
||||
The mmap() function shall fail if:
|
||||
|
||||
EACCES The fildes argument is not open for read, regardless of the protection specified, or fildes is not open for write and PROT_WRITE was specified for a MAP_SHARED type mapping.
|
||||
|
||||
EAGAIN The mapping could not be locked in memory, if required by mlockall(), due to a lack of resources.
|
||||
|
||||
EBADF The fildes argument is not a valid open file descriptor.
|
||||
|
||||
EINVAL The value of len is zero.
|
||||
|
||||
EINVAL The value of flags is invalid (neither MAP_PRIVATE nor MAP_SHARED is set).
|
||||
|
||||
EMFILE The number of mapped regions would exceed an implementation-defined limit (per process or per system).
|
||||
|
||||
ENODEV The fildes argument refers to a file whose type is not supported by mmap().
|
||||
|
||||
ENOMEM MAP_FIXED was specified, and the range [addr,addr+len) exceeds that allowed for the address space of a process; or, if MAP_FIXED was not specified and there is insufficient room in the address space to effect the map‐
|
||||
ping.
|
||||
|
||||
ENOMEM The mapping could not be locked in memory, if required by mlockall(), because it would require more space than the system is able to supply.
|
||||
|
||||
ENOMEM Not enough unallocated memory resources remain in the typed memory object designated by fildes to allocate len bytes.
|
||||
|
||||
ENOTSUP
|
||||
MAP_FIXED or MAP_PRIVATE was specified in the flags argument and the implementation does not support this functionality.
|
||||
|
||||
The implementation does not support the combination of accesses requested in the prot argument.
|
||||
|
||||
ENXIO Addresses in the range [off,off+len) are invalid for the object specified by fildes.
|
||||
|
||||
ENXIO MAP_FIXED was specified in flags and the combination of addr, len, and off is invalid for the object specified by fildes.
|
||||
|
||||
ENXIO The fildes argument refers to a typed memory object that is not accessible from the calling process.
|
||||
|
||||
EOVERFLOW
|
||||
The file is a regular file and the value of off plus len exceeds the offset maximum established in the open file description associated with fildes.
|
||||
|
||||
The mmap() function may fail if:
|
||||
|
||||
EINVAL The addr argument (if MAP_FIXED was specified) or off is not a multiple of the page size as returned by sysconf(), or is considered invalid by the implementation.
|
||||
|
||||
The following sections are informative.
|
||||
|
||||
EXAMPLES
|
||||
None.
|
||||
|
||||
APPLICATION USAGE
|
||||
Use of mmap() may reduce the amount of memory available to other memory allocation functions.
|
||||
|
||||
Use of MAP_FIXED may result in unspecified behavior in further use of malloc() and shmat(). The use of MAP_FIXED is discouraged, as it may prevent an implementation from making the most effective use of resources. Most im‐
|
||||
plementations require that off and addr are multiples of the page size as returned by sysconf().
|
||||
|
||||
The application must ensure correct synchronization when using mmap() in conjunction with any other file access method, such as read() and write(), standard input/output, and shmat().
|
||||
|
||||
The mmap() function allows access to resources via address space manipulations, instead of read()/write(). Once a file is mapped, all a process has to do to access it is use the data at the address to which the file was
|
||||
mapped. So, using pseudo-code to illustrate the way in which an existing program might be changed to use mmap(), the following:
|
||||
|
||||
fildes = open(...)
|
||||
lseek(fildes, some_offset)
|
||||
read(fildes, buf, len)
|
||||
/* Use data in buf. */
|
||||
|
||||
becomes:
|
||||
|
||||
fildes = open(...)
|
||||
address = mmap(0, len, PROT_READ, MAP_PRIVATE, fildes, some_offset)
|
||||
/* Use data at address. */
|
||||
|
||||
RATIONALE
|
||||
After considering several other alternatives, it was decided to adopt the mmap() definition found in SVR4 for mapping memory objects into process address spaces. The SVR4 definition is minimal, in that it describes only what
|
||||
has been built, and what appears to be necessary for a general and portable mapping facility.
|
||||
|
||||
Note that while mmap() was first designed for mapping files, it is actually a general-purpose mapping facility. It can be used to map any appropriate object, such as memory, files, devices, and so on, into the address space
|
||||
of a process.
|
||||
|
||||
When a mapping is established, it is possible that the implementation may need to map more than is requested into the address space of the process because of hardware requirements. An application, however, cannot count on
|
||||
this behavior. Implementations that do not use a paged architecture may simply allocate a common memory region and return the address of it; such implementations probably do not allocate any more than is necessary. References
|
||||
past the end of the requested area are unspecified.
|
||||
|
||||
If an application requests a mapping that overlaps existing mappings in the process, it might be desirable that an implementation detect this and inform the application. However, if the program specifies a fixed address map‐
|
||||
ping (which requires some implementation knowledge to determine a suitable address, if the function is supported at all), then the program is presumed to be successfully managing its own address space and should be trusted
|
||||
when it asks to map over existing data structures. Furthermore, it is also desirable to make as few system calls as possible, and it might be considered onerous to require an munmap() before an mmap() to the same address
|
||||
range. This volume of POSIX.1‐2017 specifies that the new mapping replaces any existing mappings (implying an automatic munmap() on the address range), following existing practice in this regard. The standard developers also
|
||||
considered whether there should be a way for new mappings to overlay existing mappings, but found no existing practice for this.
|
||||
|
||||
It is not expected that all hardware implementations are able to support all combinations of permissions at all addresses. Implementations are required to disallow write access to mappings without write permission and to
|
||||
disallow access to mappings without any access permission. Other than these restrictions, implementations may allow access types other than those requested by the application. For example, if the application requests only
|
||||
PROT_WRITE, the implementation may also allow read access. A call to mmap() fails if the implementation cannot support allowing all the access requested by the application. For example, some implementations cannot support a
|
||||
request for both write access and execute access simultaneously. All implementations must support requests for no access, read access, write access, and both read and write access. Strictly conforming code must only rely on
|
||||
the required checks. These restrictions allow for portability across a wide range of hardware.
|
||||
|
||||
The MAP_FIXED address treatment is likely to fail for non-page-aligned values and for certain architecture-dependent address ranges. Conforming implementations cannot count on being able to choose address values for
|
||||
MAP_FIXED without utilizing non-portable, implementation-defined knowledge. Nonetheless, MAP_FIXED is provided as a standard interface conforming to existing practice for utilizing such knowledge when it is available.
|
||||
|
||||
Similarly, in order to allow implementations that do not support virtual addresses, support for directly specifying any mapping addresses via MAP_FIXED is not required and thus a conforming application may not count on it.
|
||||
|
||||
The MAP_PRIVATE function can be implemented efficiently when memory protection hardware is available. When such hardware is not available, implementations can implement such ``mappings'' by simply making a real copy of the
|
||||
relevant data into process private memory, though this tends to behave similarly to read().
|
||||
|
||||
The function has been defined to allow for many different models of using shared memory. However, all uses are not equally portable across all machine architectures. In particular, the mmap() function allows the system as
|
||||
well as the application to specify the address at which to map a specific region of a memory object. The most portable way to use the function is always to let the system choose the address, specifying NULL as the value for
|
||||
the argument addr and not to specify MAP_FIXED.
|
||||
|
||||
If it is intended that a particular region of a memory object be mapped at the same address in a group of processes (on machines where this is even possible), then MAP_FIXED can be used to pass in the desired mapping address.
|
||||
The system can still be used to choose the desired address if the first such mapping is made without specifying MAP_FIXED, and then the resulting mapping address can be passed to subsequent processes for them to pass in via
|
||||
MAP_FIXED. The availability of a specific address range cannot be guaranteed, in general.
|
||||
|
||||
The mmap() function can be used to map a region of memory that is larger than the current size of the object. Memory access within the mapping but beyond the current end of the underlying objects may result in SIGBUS signals
|
||||
being sent to the process. The reason for this is that the size of the object can be manipulated by other processes and can change at any moment. The implementation should tell the application that a memory reference is out‐
|
||||
side the object where this can be detected; otherwise, written data may be lost and read data may not reflect actual data in the object.
|
||||
|
||||
Note that references beyond the end of the object do not extend the object as the new end cannot be determined precisely by most virtual memory hardware. Instead, the size can be directly manipulated by ftruncate().
|
||||
|
||||
Process memory locking does apply to shared memory regions, and the MCL_FUTURE argument to mlockall() can be relied upon to cause new shared memory regions to be automatically locked.
|
||||
|
||||
Existing implementations of mmap() return the value -1 when unsuccessful. Since the casting of this value to type void * cannot be guaranteed by the ISO C standard to be distinct from a successful value, this volume of
|
||||
POSIX.1‐2017 defines the symbol MAP_FAILED, which a conforming implementation does not return as the result of a successful call.
|
||||
|
||||
FUTURE DIRECTIONS
|
||||
None.
|
||||
|
||||
SEE ALSO
|
||||
exec, fcntl(), fork(), lockf(), msync(), munmap(), mprotect(), posix_typed_mem_open(), shmat(), sysconf()
|
||||
|
||||
The Base Definitions volume of POSIX.1‐2017, <sys_mman.h>
|
||||
|
||||
COPYRIGHT
|
||||
Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1-2017, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 7,
|
||||
2018 Edition, Copyright (C) 2018 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the
|
||||
original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .
|
||||
|
||||
Any typographical or formatting errors that appear in this page are most likely to have been introduced during the conversion of the source files to man page format. To report such errors, see https://www.kernel.org/doc/man-
|
||||
pages/reporting_bugs.html .
|
||||
|
||||
IEEE/The Open Group 2017 MMAP(3P)
|
4
static/files/pb071/bonuses/08/test-counting/mmap.json
Normal file
4
static/files/pb071/bonuses/08/test-counting/mmap.json
Normal file
|
@ -0,0 +1,4 @@
|
|||
{
|
||||
"args": ["{test_case}.in", "{test_case}.out_produced", "mmap"],
|
||||
"specialized_test": ["diff", "{test_case}.out", "{test_case}.out_produced"]
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue