Compare commits
2 Commits
d03225edce
...
cat-town
Author | SHA1 | Date | |
---|---|---|---|
09ee33a751
|
|||
ee9fb1955c
|
3
cat-town/.gitignore
vendored
Normal file
3
cat-town/.gitignore
vendored
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
/node_modules/
|
||||||
|
/src/*.js
|
||||||
|
/dist/
|
4838
cat-town/package-lock.json
generated
Normal file
4838
cat-town/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
30
cat-town/package.json
Normal file
30
cat-town/package.json
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
{
|
||||||
|
"name": "cat-town",
|
||||||
|
"version": "0.1.0",
|
||||||
|
"private": true,
|
||||||
|
"main": "index.js",
|
||||||
|
"scripts": {
|
||||||
|
"webpack": "webpack",
|
||||||
|
"dev": "webpack serve --config webpack.development.js",
|
||||||
|
"start": "npm run dev",
|
||||||
|
"build:dev": "webpack --config webpack.development.js",
|
||||||
|
"build:prod": "webpack --config webpack.production.js"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@excaliburjs/testing": "^0.25.1",
|
||||||
|
"clean-webpack-plugin": "^3.0.0",
|
||||||
|
"compression-webpack-plugin": "^7.1.2",
|
||||||
|
"html-webpack-plugin": "^5.5.0",
|
||||||
|
"source-map-loader": "^2.0.2",
|
||||||
|
"terser-webpack-plugin": "^5.3.6",
|
||||||
|
"ts-loader": "^9.4.2",
|
||||||
|
"typescript": "^4.9.4",
|
||||||
|
"webpack": "^5.75.0",
|
||||||
|
"webpack-cli": "^4.10.0",
|
||||||
|
"webpack-dev-server": "^4.11.1",
|
||||||
|
"webpack-merge": "^5.8.0"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"excalibur": "^0.27.0"
|
||||||
|
}
|
||||||
|
}
|
17
cat-town/src/actors/player.ts
Normal file
17
cat-town/src/actors/player.ts
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
import { Actor, Color, vec } from 'excalibur'
|
||||||
|
import { Resources } from '../resources'
|
||||||
|
|
||||||
|
export class Player extends Actor {
|
||||||
|
constructor() {
|
||||||
|
super({
|
||||||
|
pos: vec(150, 150),
|
||||||
|
width: 25,
|
||||||
|
height: 25,
|
||||||
|
color: new Color(255, 100, 100)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
onInitialize() {
|
||||||
|
this.graphics.use(Resources.Cat.toSprite())
|
||||||
|
}
|
||||||
|
}
|
16
cat-town/src/cat.ts
Normal file
16
cat-town/src/cat.ts
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
// type Cat = {
|
||||||
|
// name string;
|
||||||
|
// years int;
|
||||||
|
// centimeters int;
|
||||||
|
// kilograms int;
|
||||||
|
// coloring Coloring;
|
||||||
|
// pattern Pattern;
|
||||||
|
// mood Mood;
|
||||||
|
// };
|
||||||
|
//
|
||||||
|
// type Coloring = 'orange' | 'black' | 'brown' | 'blue';
|
||||||
|
//
|
||||||
|
// type Pattern = 'plain' | 'striped' | 'spotted';
|
||||||
|
//
|
||||||
|
// type Mood = 'happy' | 'sad' | 'purring' |
|
||||||
|
// 'screaming' | 'mad' | 'scratchy' | 'curious' | 'concerned';
|
BIN
cat-town/src/images/cat.png
Normal file
BIN
cat-town/src/images/cat.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 8.8 KiB |
BIN
cat-town/src/images/cat.png-autosave.kra
Normal file
BIN
cat-town/src/images/cat.png-autosave.kra
Normal file
Binary file not shown.
30
cat-town/src/index.ts
Normal file
30
cat-town/src/index.ts
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
import { Engine, Loader, DisplayMode } from 'excalibur'
|
||||||
|
import { Beginning } from './scenes/beginning'
|
||||||
|
import { Player } from './actors/player'
|
||||||
|
import { Resources } from './resources'
|
||||||
|
|
||||||
|
class Game extends Engine {
|
||||||
|
private player: Player
|
||||||
|
private beginning: Beginning
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
super({ displayMode: DisplayMode.FitScreen })
|
||||||
|
}
|
||||||
|
|
||||||
|
public start() {
|
||||||
|
this.beginning = new Beginning()
|
||||||
|
this.player = new Player()
|
||||||
|
this.beginning.add(this.player)
|
||||||
|
|
||||||
|
game.add('beginning', this.beginning)
|
||||||
|
|
||||||
|
const loader = new Loader(Object.values(Resources))
|
||||||
|
|
||||||
|
return super.start(loader)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const game = new Game()
|
||||||
|
game.start().then(() => {
|
||||||
|
game.goToScene('beginning')
|
||||||
|
})
|
8
cat-town/src/resources.ts
Normal file
8
cat-town/src/resources.ts
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
import { ImageSource } from 'excalibur'
|
||||||
|
import catImage from './images/cat.png'
|
||||||
|
|
||||||
|
const Resources = {
|
||||||
|
Cat: new ImageSource(catImage)
|
||||||
|
}
|
||||||
|
|
||||||
|
export { Resources }
|
7
cat-town/src/scenes/beginning.ts
Normal file
7
cat-town/src/scenes/beginning.ts
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
import { Engine, Scene } from 'excalibur'
|
||||||
|
|
||||||
|
export class Beginning extends Scene {
|
||||||
|
public onInitialize(engine: Engine) {}
|
||||||
|
public onActivate() {}
|
||||||
|
public onDeactivate() {}
|
||||||
|
}
|
22
cat-town/src/town.ts
Normal file
22
cat-town/src/town.ts
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
// type Town = {
|
||||||
|
// grid Grid;
|
||||||
|
// };
|
||||||
|
//
|
||||||
|
// type Grid = {
|
||||||
|
// squares Map<Coords, Square>;
|
||||||
|
// };
|
||||||
|
//
|
||||||
|
// type Coords = {
|
||||||
|
// x int;
|
||||||
|
// y int;
|
||||||
|
// };
|
||||||
|
//
|
||||||
|
// type Square = {
|
||||||
|
// description string;
|
||||||
|
// things Map<string, Thing>;
|
||||||
|
// };
|
||||||
|
//
|
||||||
|
// type Thing = {
|
||||||
|
// name string;
|
||||||
|
// description string;
|
||||||
|
// };
|
14
cat-town/tsconfig.json
Normal file
14
cat-town/tsconfig.json
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"allowSyntheticDefaultImports": true,
|
||||||
|
"moduleResolution": "node",
|
||||||
|
"sourceMap": true,
|
||||||
|
"target": "es2017",
|
||||||
|
"module": "es6",
|
||||||
|
"types": ["excalibur"],
|
||||||
|
"outDir": "./dist/",
|
||||||
|
"esModuleInterop": true,
|
||||||
|
"forceConsistentCasingInFileNames": true,
|
||||||
|
"skipLibCheck": true
|
||||||
|
}
|
||||||
|
}
|
47
cat-town/webpack.common.js
Normal file
47
cat-town/webpack.common.js
Normal file
@@ -0,0 +1,47 @@
|
|||||||
|
const path = require("path");
|
||||||
|
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
|
||||||
|
const HtmlWebPackPlugin = require("html-webpack-plugin");
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
entry: "./src/index.ts",
|
||||||
|
target: "web",
|
||||||
|
output: {
|
||||||
|
filename: '[name].js',
|
||||||
|
sourceMapFilename: "[file].map",
|
||||||
|
path: path.resolve(__dirname, "dist"),
|
||||||
|
},
|
||||||
|
devtool: "source-map",
|
||||||
|
module: {
|
||||||
|
rules: [
|
||||||
|
{
|
||||||
|
test: /\.(png|svg|jpg|jpeg|gif)$/i,
|
||||||
|
type: "asset/resource"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
test: /\.js$/,
|
||||||
|
use: ["source-map-loader"],
|
||||||
|
exclude: [path.resolve(__dirname, "node_modules/excalibur")],
|
||||||
|
enforce: "pre",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
test: /\.tsx?$/,
|
||||||
|
use: "ts-loader",
|
||||||
|
exclude: /node_modules/,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
resolve: {
|
||||||
|
extensions: [".tsx", ".ts", ".js"],
|
||||||
|
},
|
||||||
|
optimization: {
|
||||||
|
splitChunks: {
|
||||||
|
chunks: "all",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
plugins: [
|
||||||
|
new CleanWebpackPlugin(),
|
||||||
|
new HtmlWebPackPlugin({
|
||||||
|
title: "Cat Town",
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
};
|
12
cat-town/webpack.development.js
Normal file
12
cat-town/webpack.development.js
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
const { merge } = require("webpack-merge");
|
||||||
|
const common = require("./webpack.common");
|
||||||
|
|
||||||
|
module.exports = merge(common, {
|
||||||
|
mode: "development",
|
||||||
|
devtool: "inline-source-map",
|
||||||
|
devServer: {
|
||||||
|
static: {
|
||||||
|
directory: "./dist",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
13
cat-town/webpack.production.js
Normal file
13
cat-town/webpack.production.js
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
const { merge } = require("webpack-merge");
|
||||||
|
const CompressionWebpackPlugin = require("compression-webpack-plugin");
|
||||||
|
const TerserPlugin = require("terser-webpack-plugin");
|
||||||
|
const common = require("./webpack.common");
|
||||||
|
|
||||||
|
module.exports = merge(common, {
|
||||||
|
mode: "production",
|
||||||
|
optimization: {
|
||||||
|
minimize: true,
|
||||||
|
minimizer: [new TerserPlugin()],
|
||||||
|
},
|
||||||
|
plugins: [new CompressionWebpackPlugin()],
|
||||||
|
});
|
@@ -1 +0,0 @@
|
|||||||
3.12.0
|
|
@@ -1,156 +0,0 @@
|
|||||||
[build-system]
|
|
||||||
requires = ["hatchling"]
|
|
||||||
build-backend = "hatchling.build"
|
|
||||||
|
|
||||||
[project]
|
|
||||||
name = "leetcode"
|
|
||||||
description = 'What A Mess'
|
|
||||||
readme = "README.md"
|
|
||||||
version = "0.1.0"
|
|
||||||
requires-python = ">=3.7"
|
|
||||||
license = "MIT"
|
|
||||||
keywords = []
|
|
||||||
authors = [
|
|
||||||
{ name = "Dan Buch", email = "dan@meatballhat.com" },
|
|
||||||
]
|
|
||||||
classifiers = [
|
|
||||||
"Development Status :: 4 - Beta",
|
|
||||||
"Programming Language :: Python",
|
|
||||||
"Programming Language :: Python :: 3.7",
|
|
||||||
"Programming Language :: Python :: 3.8",
|
|
||||||
"Programming Language :: Python :: 3.9",
|
|
||||||
"Programming Language :: Python :: 3.10",
|
|
||||||
"Programming Language :: Python :: 3.11",
|
|
||||||
"Programming Language :: Python :: Implementation :: CPython",
|
|
||||||
"Programming Language :: Python :: Implementation :: PyPy",
|
|
||||||
]
|
|
||||||
dependencies = [
|
|
||||||
"ipython"
|
|
||||||
]
|
|
||||||
|
|
||||||
[project.urls]
|
|
||||||
Documentation = "https://github.com/unknown/leetcode#readme"
|
|
||||||
Issues = "https://github.com/unknown/leetcode/issues"
|
|
||||||
Source = "https://github.com/unknown/leetcode"
|
|
||||||
|
|
||||||
[tool.hatch.envs.default]
|
|
||||||
dependencies = [
|
|
||||||
"coverage[toml]>=6.5",
|
|
||||||
"pytest",
|
|
||||||
]
|
|
||||||
[tool.hatch.envs.default.scripts]
|
|
||||||
test = "pytest {args:tests}"
|
|
||||||
test-cov = "coverage run -m pytest {args:tests}"
|
|
||||||
cov-report = [
|
|
||||||
"- coverage combine",
|
|
||||||
"coverage report",
|
|
||||||
]
|
|
||||||
cov = [
|
|
||||||
"test-cov",
|
|
||||||
"cov-report",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[tool.hatch.envs.all.matrix]]
|
|
||||||
python = ["3.7", "3.8", "3.9", "3.10", "3.11"]
|
|
||||||
|
|
||||||
[tool.hatch.envs.lint]
|
|
||||||
detached = true
|
|
||||||
dependencies = [
|
|
||||||
"black>=23.1.0",
|
|
||||||
"mypy>=1.0.0",
|
|
||||||
"ruff>=0.0.243",
|
|
||||||
]
|
|
||||||
[tool.hatch.envs.lint.scripts]
|
|
||||||
typing = "mypy --install-types --non-interactive {args:src/leetcode tests}"
|
|
||||||
style = [
|
|
||||||
"ruff {args:.}",
|
|
||||||
"black --check --diff {args:.}",
|
|
||||||
]
|
|
||||||
fmt = [
|
|
||||||
"black {args:.}",
|
|
||||||
"ruff --fix {args:.}",
|
|
||||||
"style",
|
|
||||||
]
|
|
||||||
all = [
|
|
||||||
"style",
|
|
||||||
"typing",
|
|
||||||
]
|
|
||||||
|
|
||||||
[tool.black]
|
|
||||||
target-version = ["py37"]
|
|
||||||
line-length = 120
|
|
||||||
skip-string-normalization = true
|
|
||||||
|
|
||||||
[tool.ruff]
|
|
||||||
target-version = "py37"
|
|
||||||
line-length = 120
|
|
||||||
select = [
|
|
||||||
"A",
|
|
||||||
"ARG",
|
|
||||||
"B",
|
|
||||||
"C",
|
|
||||||
"DTZ",
|
|
||||||
"E",
|
|
||||||
"EM",
|
|
||||||
"F",
|
|
||||||
"FBT",
|
|
||||||
"I",
|
|
||||||
"ICN",
|
|
||||||
"ISC",
|
|
||||||
"N",
|
|
||||||
"PLC",
|
|
||||||
"PLE",
|
|
||||||
"PLR",
|
|
||||||
"PLW",
|
|
||||||
"Q",
|
|
||||||
"RUF",
|
|
||||||
"S",
|
|
||||||
"T",
|
|
||||||
"TID",
|
|
||||||
"UP",
|
|
||||||
"W",
|
|
||||||
"YTT",
|
|
||||||
]
|
|
||||||
ignore = [
|
|
||||||
# Allow non-abstract empty methods in abstract base classes
|
|
||||||
"B027",
|
|
||||||
# Allow boolean positional values in function calls, like `dict.get(... True)`
|
|
||||||
"FBT003",
|
|
||||||
# Ignore checks for possible passwords
|
|
||||||
"S105", "S106", "S107",
|
|
||||||
# Ignore complexity
|
|
||||||
"C901", "PLR0911", "PLR0912", "PLR0913", "PLR0915",
|
|
||||||
]
|
|
||||||
unfixable = [
|
|
||||||
# Don't touch unused imports
|
|
||||||
"F401",
|
|
||||||
]
|
|
||||||
|
|
||||||
[tool.ruff.isort]
|
|
||||||
known-first-party = ["leetcode"]
|
|
||||||
|
|
||||||
[tool.ruff.flake8-tidy-imports]
|
|
||||||
ban-relative-imports = "all"
|
|
||||||
|
|
||||||
[tool.ruff.per-file-ignores]
|
|
||||||
# Tests can use magic values, assertions, and relative imports
|
|
||||||
"tests/**/*" = ["PLR2004", "S101", "TID252"]
|
|
||||||
|
|
||||||
[tool.coverage.run]
|
|
||||||
source_pkgs = ["leetcode", "tests"]
|
|
||||||
branch = true
|
|
||||||
parallel = true
|
|
||||||
omit = [
|
|
||||||
"src/leetcode/__about__.py",
|
|
||||||
]
|
|
||||||
|
|
||||||
[tool.coverage.paths]
|
|
||||||
leetcode = ["src/leetcode", "*/leetcode/src/leetcode"]
|
|
||||||
tests = ["tests", "*/leetcode/tests"]
|
|
||||||
|
|
||||||
[tool.coverage.report]
|
|
||||||
exclude_lines = [
|
|
||||||
"no cov",
|
|
||||||
"if __name__ == .__main__.:",
|
|
||||||
"if TYPE_CHECKING:",
|
|
||||||
]
|
|
@@ -1,131 +0,0 @@
|
|||||||
import enum
|
|
||||||
import itertools
|
|
||||||
import pprint
|
|
||||||
import typing
|
|
||||||
|
|
||||||
|
|
||||||
def yep(s: str) -> bool:
|
|
||||||
return s.strip().lower().startswith("y")
|
|
||||||
|
|
||||||
|
|
||||||
def guess_bisect_repl(lower: int, upper: int) -> int:
|
|
||||||
mid = lower + ((upper - lower) // 2)
|
|
||||||
|
|
||||||
if yep(input(f"is it {mid}? ")):
|
|
||||||
return mid
|
|
||||||
|
|
||||||
if yep(input(f"higher than {mid}? ")):
|
|
||||||
return guess_bisect_repl(mid, upper)
|
|
||||||
|
|
||||||
return guess_bisect_repl(lower, mid)
|
|
||||||
|
|
||||||
|
|
||||||
def find_sqrt_ish(n: int) -> int:
|
|
||||||
return int(find_bisect(0, n, gen_sqrt_check(n)))
|
|
||||||
|
|
||||||
|
|
||||||
def gen_sqrt_check(n: int) -> typing.Callable[[float], int]:
|
|
||||||
def check(mid: float) -> int:
|
|
||||||
mid_sq: float = mid * mid
|
|
||||||
|
|
||||||
if mid_sq == n:
|
|
||||||
return 0
|
|
||||||
|
|
||||||
if mid_sq < n:
|
|
||||||
return 1
|
|
||||||
|
|
||||||
return -1
|
|
||||||
|
|
||||||
return check
|
|
||||||
|
|
||||||
|
|
||||||
def find_bisect(lower: float, upper: float, check: typing.Callable[[float], int]) -> float:
|
|
||||||
mid: float = lower + ((upper - lower) / 2)
|
|
||||||
|
|
||||||
print(f"lower={lower} mid={mid} upper={upper}")
|
|
||||||
|
|
||||||
if mid == lower or mid == upper or check(mid) == 0:
|
|
||||||
return mid
|
|
||||||
|
|
||||||
if check(mid) == 1:
|
|
||||||
return find_bisect(mid, upper, check)
|
|
||||||
|
|
||||||
return find_bisect(lower, mid, check)
|
|
||||||
|
|
||||||
|
|
||||||
def cartesian_path(p0: tuple[int, int], p1: tuple[int, int]) -> list[tuple[int, int]]:
|
|
||||||
path: list[tuple[int, int]] = []
|
|
||||||
|
|
||||||
if p0 < p1:
|
|
||||||
for i in range(p0[1], p1[1]):
|
|
||||||
path.append((i, p0[0]))
|
|
||||||
|
|
||||||
for i in range(p0[0], p1[0]):
|
|
||||||
path.append((p1[1], i))
|
|
||||||
|
|
||||||
else:
|
|
||||||
for i in range(p0[1], p1[1] - 1, -1):
|
|
||||||
path.append((i, p0[0]))
|
|
||||||
|
|
||||||
for i in range(p0[0] - 1, p1[0], -1):
|
|
||||||
path.append((p1[1], i))
|
|
||||||
|
|
||||||
return path
|
|
||||||
|
|
||||||
|
|
||||||
def gen_matrix(width: int, height: int) -> list[list[int]]:
|
|
||||||
return [list(range(width)) for _ in range(height)]
|
|
||||||
|
|
||||||
|
|
||||||
def matrix_spiral(matrix: list[list[typing.Any]]) -> list[typing.Any]:
|
|
||||||
return [matrix[y][x] for x, y in matrix_spiral_path(matrix)]
|
|
||||||
|
|
||||||
|
|
||||||
def matrix_spiral_path(matrix: list[list[int]]) -> list[tuple[int, int]]:
|
|
||||||
snek = SpinSnek(matrix)
|
|
||||||
|
|
||||||
while snek.step():
|
|
||||||
...
|
|
||||||
|
|
||||||
return snek.path
|
|
||||||
|
|
||||||
|
|
||||||
class SpinSnek:
|
|
||||||
def __init__(self, board: list[list[int]], loc: tuple[int, int] = (0, 0)):
|
|
||||||
self.max_loc: tuple[int, int] = (len(board[0]) - 1, len(board) - 1)
|
|
||||||
self.spinner: itertools.cycle[tuple[int, int]] = itertools.cycle(
|
|
||||||
[
|
|
||||||
(1, 0), # east
|
|
||||||
(0, 1), # south
|
|
||||||
(-1, 0), # west
|
|
||||||
(0, -1), # north
|
|
||||||
]
|
|
||||||
)
|
|
||||||
self.direction = next(self.spinner)
|
|
||||||
self.path: list[tuple[int, int]] = [loc]
|
|
||||||
self.missteps: int = 0
|
|
||||||
|
|
||||||
def step(self) -> bool:
|
|
||||||
loc = self.path[-1]
|
|
||||||
next_loc: tuple[int, int] = (
|
|
||||||
loc[0] + self.direction[0],
|
|
||||||
loc[1] + self.direction[1],
|
|
||||||
)
|
|
||||||
|
|
||||||
if (
|
|
||||||
next_loc[0] > self.max_loc[0]
|
|
||||||
or next_loc[1] > self.max_loc[1]
|
|
||||||
or next_loc[0] < 0
|
|
||||||
or next_loc[1] < 0
|
|
||||||
or next_loc in self.path
|
|
||||||
):
|
|
||||||
self.direction = next(self.spinner)
|
|
||||||
if self.missteps > 3:
|
|
||||||
return False
|
|
||||||
|
|
||||||
self.missteps += 1
|
|
||||||
return self.step()
|
|
||||||
|
|
||||||
self.missteps: int = 0
|
|
||||||
self.path.append(next_loc)
|
|
||||||
return True
|
|
@@ -1,61 +0,0 @@
|
|||||||
import pytest
|
|
||||||
|
|
||||||
import stuff
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize(
|
|
||||||
("n", "expected"),
|
|
||||||
[
|
|
||||||
(0, 0),
|
|
||||||
(1, 1),
|
|
||||||
(5, 2),
|
|
||||||
(4, 2),
|
|
||||||
(8, 2),
|
|
||||||
(9, 3),
|
|
||||||
],
|
|
||||||
)
|
|
||||||
def test_find_sqrt_ish(n: int, expected: int):
|
|
||||||
assert stuff.find_sqrt_ish(n) == expected
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize(
|
|
||||||
("matrix", "expected"),
|
|
||||||
[
|
|
||||||
(
|
|
||||||
[
|
|
||||||
["a", "b", "c"],
|
|
||||||
["d", "e", "f"],
|
|
||||||
["g", "h", "i"],
|
|
||||||
],
|
|
||||||
["a", "b", "c", "f", "i", "h", "g", "d", "e"],
|
|
||||||
),
|
|
||||||
(
|
|
||||||
[
|
|
||||||
[1, 2, 3, 4],
|
|
||||||
[5, 6, 7, 8],
|
|
||||||
[9, 10, 11, 12],
|
|
||||||
],
|
|
||||||
[1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7],
|
|
||||||
),
|
|
||||||
(
|
|
||||||
[
|
|
||||||
[1, 2, 3, 4, 5, 6, 7, 8, 9],
|
|
||||||
[1, 2, 3, 4, 5, 6, 7, 8, 9],
|
|
||||||
[1, 2, 3, 4, 5, 6, 7, 8, 9],
|
|
||||||
[1, 2, 3, 4, 5, 6, 7, 8, 9],
|
|
||||||
[1, 2, 3, 4, 5, 6, 7, 8, 9],
|
|
||||||
],
|
|
||||||
[]
|
|
||||||
+ [1, 2, 3, 4, 5, 6, 7, 8, 9] # right
|
|
||||||
+ [9, 9, 9] # down
|
|
||||||
+ [9, 8, 7, 6, 5, 4, 3, 2, 1] # left
|
|
||||||
+ [1, 1] # up
|
|
||||||
+ [1, 2, 3, 4, 5, 6, 7, 8] # right
|
|
||||||
+ [8] # down
|
|
||||||
+ [8, 7, 6, 5, 4, 3, 2] # left
|
|
||||||
+ [2, 3, 4, 5, 6, 7], # right
|
|
||||||
),
|
|
||||||
],
|
|
||||||
)
|
|
||||||
def test_matrix_spiral(matrix, expected):
|
|
||||||
assert stuff.matrix_spiral(matrix) == expected
|
|
14
rustbyexample/.gitignore
vendored
14
rustbyexample/.gitignore
vendored
@@ -1,3 +1,11 @@
|
|||||||
/out/
|
/custom_types/*
|
||||||
/*.d/out
|
/hello/*
|
||||||
/*.d/**/out
|
/primitives/*
|
||||||
|
/variable_bindings/*
|
||||||
|
/types/*
|
||||||
|
|
||||||
|
!/custom_types/*.rs
|
||||||
|
!/hello/*.rs
|
||||||
|
!/primitives/*.rs
|
||||||
|
!/variable_bindings/*.rs
|
||||||
|
!/types/*.rs
|
||||||
|
@@ -1,18 +0,0 @@
|
|||||||
use std::convert::From;
|
|
||||||
|
|
||||||
#[allow(dead_code)]
|
|
||||||
#[derive(Debug)]
|
|
||||||
struct Number {
|
|
||||||
value: i32,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl From<i32> for Number {
|
|
||||||
fn from(item: i32) -> Self {
|
|
||||||
Number { value: item }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn main() {
|
|
||||||
let num = Number::from(30);
|
|
||||||
println!("My number is {:?}", num);
|
|
||||||
}
|
|
@@ -1,19 +0,0 @@
|
|||||||
use std::convert::Into;
|
|
||||||
|
|
||||||
#[allow(dead_code)]
|
|
||||||
#[derive(Debug)]
|
|
||||||
struct Number {
|
|
||||||
value: i32,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Into<Number> for i32 {
|
|
||||||
fn into(self) -> Number {
|
|
||||||
Number { value: self }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn main() {
|
|
||||||
let int = 5;
|
|
||||||
let num: Number = int.into();
|
|
||||||
println!("My number is {:?}", num);
|
|
||||||
}
|
|
@@ -1,16 +0,0 @@
|
|||||||
use std::fmt;
|
|
||||||
|
|
||||||
struct Circle {
|
|
||||||
radius: i32,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl fmt::Display for Circle {
|
|
||||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
|
||||||
write!(f, "Circle of radius {}", self.radius)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn main() {
|
|
||||||
let circle = Circle { radius: 6 };
|
|
||||||
println!("{}", circle.to_string());
|
|
||||||
}
|
|
@@ -1,7 +0,0 @@
|
|||||||
fn main() {
|
|
||||||
let parsed: i32 = "5".parse().unwrap();
|
|
||||||
let turbo_parsed = "10".parse::<i32>().unwrap();
|
|
||||||
|
|
||||||
let sum = parsed + turbo_parsed;
|
|
||||||
println!("Sum: {:?}", sum);
|
|
||||||
}
|
|
@@ -1,28 +0,0 @@
|
|||||||
use std::convert::TryFrom;
|
|
||||||
use std::convert::TryInto;
|
|
||||||
|
|
||||||
#[derive(Debug, PartialEq)]
|
|
||||||
struct EvenNumber(i32);
|
|
||||||
|
|
||||||
impl TryFrom<i32> for EvenNumber {
|
|
||||||
type Error = ();
|
|
||||||
|
|
||||||
fn try_from(value: i32) -> Result<Self, Self::Error> {
|
|
||||||
if value % 2 == 0 {
|
|
||||||
Ok(EvenNumber(value))
|
|
||||||
} else {
|
|
||||||
Err(())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn main() {
|
|
||||||
assert_eq!(EvenNumber::try_from(8), Ok(EvenNumber(8)));
|
|
||||||
assert_eq!(EvenNumber::try_from(5), Err(()));
|
|
||||||
|
|
||||||
let result: Result<EvenNumber, ()> = 8i32.try_into();
|
|
||||||
assert_eq!(result, Ok(EvenNumber(8)));
|
|
||||||
|
|
||||||
let result: Result<EvenNumber, ()> = 5i32.try_into();
|
|
||||||
assert_eq!(result, Err(()));
|
|
||||||
}
|
|
@@ -1,4 +1,3 @@
|
|||||||
#[allow(dead_code)]
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
struct Person {
|
struct Person {
|
||||||
name: String,
|
name: String,
|
@@ -1,25 +0,0 @@
|
|||||||
#[allow(path_statements)]
|
|
||||||
#[allow(unused_must_use)]
|
|
||||||
fn main() {
|
|
||||||
let x = 5;
|
|
||||||
x;
|
|
||||||
x + 1;
|
|
||||||
15;
|
|
||||||
|
|
||||||
let x = 5u32;
|
|
||||||
|
|
||||||
let y = {
|
|
||||||
let x_squared = x * x;
|
|
||||||
let x_cube = x_squared * x;
|
|
||||||
|
|
||||||
x_cube + x_squared + x
|
|
||||||
};
|
|
||||||
|
|
||||||
let z = {
|
|
||||||
2 * x;
|
|
||||||
};
|
|
||||||
|
|
||||||
println!("x is {:?}", x);
|
|
||||||
println!("y is {:?}", y);
|
|
||||||
println!("z is {:?}", z);
|
|
||||||
}
|
|
@@ -1,13 +0,0 @@
|
|||||||
fn main() {
|
|
||||||
for n in 1..101 {
|
|
||||||
if n % 15 == 0 {
|
|
||||||
println!("fizzbuzz");
|
|
||||||
} else if n % 3 == 0 {
|
|
||||||
println!("fizz");
|
|
||||||
} else if n % 5 == 0 {
|
|
||||||
println!("buzz");
|
|
||||||
} else {
|
|
||||||
println!("{}", n);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
@@ -1,13 +0,0 @@
|
|||||||
fn main() {
|
|
||||||
for n in 1..=100 {
|
|
||||||
if n % 15 == 0 {
|
|
||||||
println!("fizzbuzz");
|
|
||||||
} else if n % 3 == 0 {
|
|
||||||
println!("fizz");
|
|
||||||
} else if n % 5 == 0 {
|
|
||||||
println!("buzz");
|
|
||||||
} else {
|
|
||||||
println!("{}", n);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
@@ -1,12 +0,0 @@
|
|||||||
fn main() {
|
|
||||||
let names = vec!["Bob", "Frank", "Ferris"];
|
|
||||||
|
|
||||||
for name in names.iter() {
|
|
||||||
match name {
|
|
||||||
&"Ferris" => println!("There is a rustacean among us!"),
|
|
||||||
_ => println!("Hello {}", name),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
println!("names: {:?}", names);
|
|
||||||
}
|
|
@@ -1,12 +0,0 @@
|
|||||||
fn main() {
|
|
||||||
let names = vec!["Bob", "Frank", "Ferris"];
|
|
||||||
|
|
||||||
for name in names.into_iter() {
|
|
||||||
match name {
|
|
||||||
"Ferris" => println!("There is a rustacean among us!"),
|
|
||||||
_ => println!("Hello {}", name),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
//println!("names: {:?}", names);
|
|
||||||
}
|
|
@@ -1,12 +0,0 @@
|
|||||||
fn main() {
|
|
||||||
let mut names = vec!["Bob", "Frank", "Ferris"];
|
|
||||||
|
|
||||||
for name in names.iter_mut() {
|
|
||||||
*name = match name {
|
|
||||||
&mut "Ferris" => "There is a rustacean among us!",
|
|
||||||
_ => "Hello",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
println!("names: {:?}", names);
|
|
||||||
}
|
|
@@ -1,23 +0,0 @@
|
|||||||
fn main() {
|
|
||||||
let n = 5;
|
|
||||||
|
|
||||||
if n < 0 {
|
|
||||||
print!("{} is negative", n);
|
|
||||||
} else if n > 0 {
|
|
||||||
print!("{} is positive", n);
|
|
||||||
} else {
|
|
||||||
print!("{} is zero", n);
|
|
||||||
}
|
|
||||||
|
|
||||||
let big_n = if n < 10 && n > -10 {
|
|
||||||
println!(", and is a small number, increase net-fold");
|
|
||||||
|
|
||||||
10 * n
|
|
||||||
} else {
|
|
||||||
println!(", and is a big number, halve the number");
|
|
||||||
|
|
||||||
n / 2
|
|
||||||
};
|
|
||||||
|
|
||||||
println!("{} -> {}", n, big_n);
|
|
||||||
}
|
|
@@ -1,25 +0,0 @@
|
|||||||
fn main() {
|
|
||||||
let number = Some(7);
|
|
||||||
let letter: Option<i32> = None;
|
|
||||||
let emoticon: Option<i32> = None;
|
|
||||||
|
|
||||||
if let Some(i) = number {
|
|
||||||
println!("Matched {:?}!", i);
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Some(i) = letter {
|
|
||||||
println!("Matched {:?}!", i);
|
|
||||||
} else {
|
|
||||||
println!("Didn't match a number. Let's go with a letter!");
|
|
||||||
}
|
|
||||||
|
|
||||||
let i_like_letters = false;
|
|
||||||
|
|
||||||
if let Some(i) = emoticon {
|
|
||||||
println!("Matched {:?}!", i);
|
|
||||||
} else if i_like_letters {
|
|
||||||
println!("Didn't match a number. Let's go with a letter!");
|
|
||||||
} else {
|
|
||||||
println!("I don't like letters. Let's go with an emoticon :)!");
|
|
||||||
}
|
|
||||||
}
|
|
@@ -1,27 +0,0 @@
|
|||||||
enum Foo {
|
|
||||||
Bar,
|
|
||||||
Baz,
|
|
||||||
Qux(u32),
|
|
||||||
}
|
|
||||||
|
|
||||||
fn main() {
|
|
||||||
let a = Foo::Bar;
|
|
||||||
let b = Foo::Baz;
|
|
||||||
let c = Foo::Qux(100);
|
|
||||||
|
|
||||||
if let Foo::Bar = a {
|
|
||||||
println!("a is a foobar");
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Foo::Bar = b {
|
|
||||||
println!("b is foobar");
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Foo::Qux(value) = c {
|
|
||||||
println!("c is {}", value);
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Foo::Qux(value @ 100) = c {
|
|
||||||
println!("c is one hundred (value: {:?})", value);
|
|
||||||
}
|
|
||||||
}
|
|
@@ -1,11 +0,0 @@
|
|||||||
enum Foo {
|
|
||||||
Bar,
|
|
||||||
}
|
|
||||||
|
|
||||||
fn main() {
|
|
||||||
let a = Foo::Bar;
|
|
||||||
|
|
||||||
if let Foo::Bar = a {
|
|
||||||
println!("a is foobar");
|
|
||||||
}
|
|
||||||
}
|
|
@@ -1,16 +0,0 @@
|
|||||||
use std::str::FromStr;
|
|
||||||
|
|
||||||
fn get_count_item(s: &str) -> (u64, &str) {
|
|
||||||
let mut it = s.split(' ');
|
|
||||||
let (Some(count_str), Some(item)) = (it.next(), it.next()) else {
|
|
||||||
panic!("Can't segment count item pair: '{s}'");
|
|
||||||
};
|
|
||||||
let Ok(count) = u64::from_str(count_str) else {
|
|
||||||
panic!("Can't parse integer: '{count_str}'");
|
|
||||||
};
|
|
||||||
(count, item)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn main() {
|
|
||||||
assert_eq!(get_count_item("3 chairs"), (3, "chairs"));
|
|
||||||
}
|
|
@@ -1,18 +0,0 @@
|
|||||||
#![allow(unreachable_code)]
|
|
||||||
#![allow(unused_labels)]
|
|
||||||
|
|
||||||
fn main() {
|
|
||||||
'outer: loop {
|
|
||||||
println!("Entered the outer loop");
|
|
||||||
|
|
||||||
'inner: loop {
|
|
||||||
println!("Entered the inner loop");
|
|
||||||
|
|
||||||
break 'outer;
|
|
||||||
}
|
|
||||||
|
|
||||||
println!("This point will never be reached");
|
|
||||||
}
|
|
||||||
|
|
||||||
println!("Exited the outer loop");
|
|
||||||
}
|
|
@@ -1,13 +0,0 @@
|
|||||||
fn main() {
|
|
||||||
let mut counter = 0;
|
|
||||||
|
|
||||||
let result = loop {
|
|
||||||
counter += 1;
|
|
||||||
|
|
||||||
if counter == 10 {
|
|
||||||
break counter * 2;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
assert_eq!(result, 20);
|
|
||||||
}
|
|
@@ -1,23 +0,0 @@
|
|||||||
fn main() {
|
|
||||||
let mut count = 0u32;
|
|
||||||
|
|
||||||
println!("Let's count until infinity!");
|
|
||||||
|
|
||||||
loop {
|
|
||||||
count += 1;
|
|
||||||
|
|
||||||
if count == 3 {
|
|
||||||
println!("three");
|
|
||||||
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
println!("{}", count);
|
|
||||||
|
|
||||||
if count == 5 {
|
|
||||||
println!("OK, that's enough");
|
|
||||||
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
@@ -1,14 +0,0 @@
|
|||||||
fn age() -> u32 {
|
|
||||||
15
|
|
||||||
}
|
|
||||||
|
|
||||||
fn main() {
|
|
||||||
println!("Tell me what type of person you are");
|
|
||||||
|
|
||||||
match age() {
|
|
||||||
0 => println!("I haven't celebrated my first birthday yet"),
|
|
||||||
n @ 1..=12 => println!("I'm a child of age {:?}", n),
|
|
||||||
n @ 13..=19 => println!("I'm a teen of age {:?}", n),
|
|
||||||
n => println!("I'm an old person of age {:?}", n),
|
|
||||||
}
|
|
||||||
}
|
|
@@ -1,11 +0,0 @@
|
|||||||
fn some_number() -> Option<u32> {
|
|
||||||
Some(42)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn main() {
|
|
||||||
match some_number() {
|
|
||||||
Some(n @ 42) => println!("The Answer: {}!", n),
|
|
||||||
Some(n) => println!("Not interesting... {}", n),
|
|
||||||
_ => (),
|
|
||||||
}
|
|
||||||
}
|
|
@@ -1,30 +0,0 @@
|
|||||||
#[allow(dead_code)]
|
|
||||||
enum Color {
|
|
||||||
Red,
|
|
||||||
Blue,
|
|
||||||
Green,
|
|
||||||
RGB(u32, u32, u32),
|
|
||||||
HSV(u32, u32, u32),
|
|
||||||
HSL(u32, u32, u32),
|
|
||||||
CMY(u32, u32, u32),
|
|
||||||
CMYK(u32, u32, u32, u32),
|
|
||||||
}
|
|
||||||
|
|
||||||
fn main() {
|
|
||||||
let color = Color::RGB(122, 17, 40);
|
|
||||||
|
|
||||||
println!("What color is it?");
|
|
||||||
match color {
|
|
||||||
Color::Red => println!("The color is Red!"),
|
|
||||||
Color::Blue => println!("The color is Blue!"),
|
|
||||||
Color::Green => println!("The color is Green!"),
|
|
||||||
Color::RGB(r, g, b) => println!("Red: {}, green: {}, and blue: {}!", r, g, b),
|
|
||||||
Color::HSV(h, s, v) => println!("Hue: {}, saturation: {}, value: {}!", h, s, v),
|
|
||||||
Color::HSL(h, s, l) => println!("Hue: {}, saturation: {}, lightness: {}!", h, s, l),
|
|
||||||
Color::CMY(c, m, y) => println!("Cyan: {}, magenta: {}, yellow: {}!", c, m, y),
|
|
||||||
Color::CMYK(c, m, y, k) => println!(
|
|
||||||
"Cyan: {}, magenta: {}, yellow: {}, key (black): {}!",
|
|
||||||
c, m, y, k
|
|
||||||
),
|
|
||||||
}
|
|
||||||
}
|
|
@@ -1,29 +0,0 @@
|
|||||||
fn main() {
|
|
||||||
let reference = &4;
|
|
||||||
|
|
||||||
match reference {
|
|
||||||
&val => println!("Got a value via destructuring: {:?}", val),
|
|
||||||
}
|
|
||||||
|
|
||||||
match *reference {
|
|
||||||
val => println!("Got a value via dereferencing: {:?}", val),
|
|
||||||
}
|
|
||||||
|
|
||||||
let _not_a_reference = 3;
|
|
||||||
|
|
||||||
let ref _is_a_reference = 3;
|
|
||||||
|
|
||||||
let value = 5;
|
|
||||||
let mut mut_value = 6;
|
|
||||||
|
|
||||||
match value {
|
|
||||||
ref r => println!("Got a reference to a value: {:?}", r),
|
|
||||||
}
|
|
||||||
|
|
||||||
match mut_value {
|
|
||||||
ref mut m => {
|
|
||||||
*m += 10;
|
|
||||||
println!("We added 10. `mut_value`: {:?}", m);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
@@ -1,27 +0,0 @@
|
|||||||
fn main() {
|
|
||||||
let array = [1, -2, 6];
|
|
||||||
|
|
||||||
match array {
|
|
||||||
[0, second, third] => println!("array[0] = 0, array[1] = {}, array[2] = {}", second, third),
|
|
||||||
|
|
||||||
[1, _, third] => println!(
|
|
||||||
"array[0] = 1, array[2] = {} and array[1] was ignored",
|
|
||||||
third
|
|
||||||
),
|
|
||||||
|
|
||||||
[-1, second, ..] => println!(
|
|
||||||
"array[0] = -1, array[1] = {} and all the other ones were ignored",
|
|
||||||
second
|
|
||||||
),
|
|
||||||
|
|
||||||
[3, second, tail @ ..] => println!(
|
|
||||||
"array[0] = 3, array[1] = {} and the other elements were {:?}",
|
|
||||||
second, tail
|
|
||||||
),
|
|
||||||
|
|
||||||
[first, middle @ .., last] => println!(
|
|
||||||
"array[0] = {}, middle = {:?}, array[2] = {}",
|
|
||||||
first, middle, last
|
|
||||||
),
|
|
||||||
}
|
|
||||||
}
|
|
@@ -1,19 +0,0 @@
|
|||||||
fn main() {
|
|
||||||
struct Foo {
|
|
||||||
x: (u32, u32),
|
|
||||||
y: u32,
|
|
||||||
}
|
|
||||||
|
|
||||||
let foo = Foo { x: (1, 2), y: 3 };
|
|
||||||
|
|
||||||
match foo {
|
|
||||||
Foo { x: (1, b), y } => println!("First of x is 1, b = {}, y = {}", b, y),
|
|
||||||
Foo { y: 2, x: i } => println!("y is 2, i = {:?}", i),
|
|
||||||
Foo { y, .. } => println!("y = {}, we don't care about x", y),
|
|
||||||
}
|
|
||||||
|
|
||||||
let faa = Foo { x: (1, 2), y: 3 };
|
|
||||||
|
|
||||||
let Foo { x: x0, y: y0 } = faa;
|
|
||||||
println!("Outside: x0 = {x0:?}, y0 = {y0}");
|
|
||||||
}
|
|
@@ -1,12 +0,0 @@
|
|||||||
fn main() {
|
|
||||||
let triple = (0, -2, 3);
|
|
||||||
|
|
||||||
println!("Tell me about {:?}", triple);
|
|
||||||
match triple {
|
|
||||||
(0, y, z) => println!("First is `0`, `y` is {:?}, and `z` is {:?}", y, z),
|
|
||||||
(1, ..) => println!("First is `1` and the rest doesn't matter"),
|
|
||||||
(.., 2) => println!("last is `2` and the rest doesn't matter"),
|
|
||||||
(3, .., 4) => println!("First is `3`, last is `4`, and the rest doesn't matter"),
|
|
||||||
_ => println!("It doesn't matter what they are"),
|
|
||||||
}
|
|
||||||
}
|
|
@@ -1,16 +0,0 @@
|
|||||||
#[allow(dead_code)]
|
|
||||||
enum Temperature {
|
|
||||||
Celsius(i32),
|
|
||||||
Fahrenheit(i32),
|
|
||||||
}
|
|
||||||
|
|
||||||
fn main() {
|
|
||||||
let temperature = Temperature::Celsius(35);
|
|
||||||
|
|
||||||
match temperature {
|
|
||||||
Temperature::Celsius(t) if t > 30 => println!("{}C is above 30 Celsius", t),
|
|
||||||
Temperature::Celsius(t) => println!("{}C is below 30 Celsius", t),
|
|
||||||
Temperature::Fahrenheit(t) if t > 86 => println!("{}F is above 86 Fahrenheit", t),
|
|
||||||
Temperature::Fahrenheit(t) => println!("{}F is below 86 Fahrenheit", t),
|
|
||||||
}
|
|
||||||
}
|
|
@@ -1,9 +0,0 @@
|
|||||||
fn main() {
|
|
||||||
let number: u8 = 4;
|
|
||||||
|
|
||||||
match number {
|
|
||||||
i if i == 0 => println!("Zero"),
|
|
||||||
i if i > 0 => println!("Greater than zero"),
|
|
||||||
_ => unreachable!("Should never happen."),
|
|
||||||
}
|
|
||||||
}
|
|
@@ -1,19 +0,0 @@
|
|||||||
fn main() {
|
|
||||||
let number = 13;
|
|
||||||
|
|
||||||
println!("Tell me about {}", number);
|
|
||||||
match number {
|
|
||||||
1 => println!("One!"),
|
|
||||||
2 | 3 | 5 | 7 | 11 => println!("This is a prime"),
|
|
||||||
13..=19 => println!("A teen"),
|
|
||||||
_ => println!("Ain't special"),
|
|
||||||
}
|
|
||||||
|
|
||||||
let boolean = true;
|
|
||||||
let binary = match boolean {
|
|
||||||
false => 0,
|
|
||||||
true => 1,
|
|
||||||
};
|
|
||||||
|
|
||||||
println!("{} -> {}", boolean, binary);
|
|
||||||
}
|
|
@@ -1,17 +0,0 @@
|
|||||||
fn main() {
|
|
||||||
let mut n = 1;
|
|
||||||
|
|
||||||
while n < 101 {
|
|
||||||
if n % 15 == 0 {
|
|
||||||
println!("fizzbuzz");
|
|
||||||
} else if n % 3 == 0 {
|
|
||||||
println!("fizz");
|
|
||||||
} else if n % 5 == 0 {
|
|
||||||
println!("buzz");
|
|
||||||
} else {
|
|
||||||
println!("{}", n);
|
|
||||||
}
|
|
||||||
|
|
||||||
n += 1;
|
|
||||||
}
|
|
||||||
}
|
|
@@ -1,13 +0,0 @@
|
|||||||
fn main() {
|
|
||||||
let mut optional = Some(0);
|
|
||||||
|
|
||||||
while let Some(i) = optional {
|
|
||||||
if i > 9 {
|
|
||||||
println!("Greater than 9, quit!");
|
|
||||||
optional = None;
|
|
||||||
} else {
|
|
||||||
println!("`i` is `{:?}`. Try again.", i);
|
|
||||||
optional = Some(i + 1);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
@@ -1,14 +0,0 @@
|
|||||||
fn apply<F>(f: F)
|
|
||||||
where
|
|
||||||
F: Fn(),
|
|
||||||
{
|
|
||||||
f();
|
|
||||||
}
|
|
||||||
|
|
||||||
fn main() {
|
|
||||||
let x = 7;
|
|
||||||
|
|
||||||
let print = || println!("{}", x);
|
|
||||||
|
|
||||||
apply(print);
|
|
||||||
}
|
|
@@ -1,36 +0,0 @@
|
|||||||
fn main() {
|
|
||||||
use std::mem;
|
|
||||||
|
|
||||||
let color = String::from("green");
|
|
||||||
|
|
||||||
let print = || println!("`color`: {}", color);
|
|
||||||
|
|
||||||
print();
|
|
||||||
|
|
||||||
let _reborrow = &color;
|
|
||||||
print();
|
|
||||||
|
|
||||||
let _color_moved = color;
|
|
||||||
|
|
||||||
let mut count = 0;
|
|
||||||
|
|
||||||
let mut inc = || {
|
|
||||||
count += 1;
|
|
||||||
println!("`count`: {}", count);
|
|
||||||
};
|
|
||||||
|
|
||||||
inc();
|
|
||||||
|
|
||||||
inc();
|
|
||||||
|
|
||||||
let _count_reborrowed = &mut count;
|
|
||||||
|
|
||||||
let movable = Box::new(3);
|
|
||||||
|
|
||||||
let consume = || {
|
|
||||||
println!("`movable`: {:?}", movable);
|
|
||||||
mem::drop(movable);
|
|
||||||
};
|
|
||||||
|
|
||||||
consume();
|
|
||||||
}
|
|
@@ -1,8 +0,0 @@
|
|||||||
fn main() {
|
|
||||||
let haystack = vec![1, 2, 3];
|
|
||||||
|
|
||||||
let contains = move |needle| haystack.contains(needle);
|
|
||||||
|
|
||||||
println!("{}", contains(&1));
|
|
||||||
println!("{}", contains(&4));
|
|
||||||
}
|
|
@@ -1,36 +0,0 @@
|
|||||||
fn apply<F>(f: F)
|
|
||||||
where
|
|
||||||
F: FnOnce(),
|
|
||||||
{
|
|
||||||
f();
|
|
||||||
}
|
|
||||||
|
|
||||||
fn apply_to_3<F>(f: F) -> i32
|
|
||||||
where
|
|
||||||
F: Fn(i32) -> i32,
|
|
||||||
{
|
|
||||||
f(3)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn main() {
|
|
||||||
use std::mem;
|
|
||||||
|
|
||||||
let greeting = "hello";
|
|
||||||
let mut farewell = "goodbye".to_owned();
|
|
||||||
|
|
||||||
let diary = || {
|
|
||||||
println!("I said {}.", greeting);
|
|
||||||
|
|
||||||
farewell.push_str("!!!");
|
|
||||||
println!("Then I screamed {}.", farewell);
|
|
||||||
println!("Now I can sleep. zzzzz");
|
|
||||||
|
|
||||||
mem::drop(farewell);
|
|
||||||
};
|
|
||||||
|
|
||||||
apply(diary);
|
|
||||||
|
|
||||||
let double = |x| 2 * x;
|
|
||||||
|
|
||||||
println!("3 doubled: {}", apply_to_3(double));
|
|
||||||
}
|
|
@@ -1,12 +0,0 @@
|
|||||||
fn main() {
|
|
||||||
let outer_var = 42;
|
|
||||||
|
|
||||||
let closure_annotated = |i: i32| -> i32 { i + outer_var };
|
|
||||||
let closure_inferred = |i| i + outer_var;
|
|
||||||
|
|
||||||
println!("closure_annotated: {}", closure_annotated(1));
|
|
||||||
println!("closure_inferred: {}", closure_inferred(1));
|
|
||||||
|
|
||||||
let one = || 1;
|
|
||||||
println!("closure returning one: {}", one());
|
|
||||||
}
|
|
@@ -1,74 +0,0 @@
|
|||||||
struct Point {
|
|
||||||
x: f64,
|
|
||||||
y: f64,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Point {
|
|
||||||
fn origin() -> Point {
|
|
||||||
Point { x: 0.0, y: 0.0 }
|
|
||||||
}
|
|
||||||
|
|
||||||
fn new(x: f64, y: f64) -> Point {
|
|
||||||
Point { x: x, y: y }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
struct Rectangle {
|
|
||||||
p1: Point,
|
|
||||||
p2: Point,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Rectangle {
|
|
||||||
fn area(&self) -> f64 {
|
|
||||||
let Point { x: x1, y: y1 } = self.p1;
|
|
||||||
let Point { x: x2, y: y2 } = self.p2;
|
|
||||||
|
|
||||||
((x1 - x2) * (y1 - y2)).abs()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn perimeter(&self) -> f64 {
|
|
||||||
let Point { x: x1, y: y1 } = self.p1;
|
|
||||||
let Point { x: x2, y: y2 } = self.p2;
|
|
||||||
|
|
||||||
2.0 * ((x1 - x2).abs() + (y1 - y2).abs())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn translate(&mut self, x: f64, y: f64) {
|
|
||||||
self.p1.x += x;
|
|
||||||
self.p2.x += x;
|
|
||||||
|
|
||||||
self.p1.y += y;
|
|
||||||
self.p2.y += y;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
struct Pair(Box<i32>, Box<i32>);
|
|
||||||
|
|
||||||
impl Pair {
|
|
||||||
fn destroy(self) {
|
|
||||||
let Pair(first, second) = self;
|
|
||||||
|
|
||||||
println!("Destroying Pair({}, {})", first, second);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn main() {
|
|
||||||
let rectangle = Rectangle {
|
|
||||||
p1: Point::origin(),
|
|
||||||
p2: Point::new(3.0, 4.0),
|
|
||||||
};
|
|
||||||
|
|
||||||
println!("Rectangle perimeter: {}", rectangle.perimeter());
|
|
||||||
println!("Rectangle area: {}", rectangle.area());
|
|
||||||
|
|
||||||
let mut square = Rectangle {
|
|
||||||
p1: Point::origin(),
|
|
||||||
p2: Point::new(1.0, 1.0),
|
|
||||||
};
|
|
||||||
|
|
||||||
square.translate(1.0, 1.0);
|
|
||||||
|
|
||||||
let pair = Pair(Box::new(1), Box::new(2));
|
|
||||||
|
|
||||||
pair.destroy();
|
|
||||||
}
|
|
@@ -1,29 +0,0 @@
|
|||||||
fn main() {
|
|
||||||
fizzbuzz_to(100);
|
|
||||||
}
|
|
||||||
|
|
||||||
fn is_divisible_by(lhs: u32, rhs: u32) -> bool {
|
|
||||||
if rhs == 0 {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
lhs % rhs == 0
|
|
||||||
}
|
|
||||||
|
|
||||||
fn fizzbuzz(n: u32) -> () {
|
|
||||||
if is_divisible_by(n, 15) {
|
|
||||||
println!("fizzbuzz");
|
|
||||||
} else if is_divisible_by(n, 3) {
|
|
||||||
println!("fizz");
|
|
||||||
} else if is_divisible_by(n, 5) {
|
|
||||||
println!("buzz");
|
|
||||||
} else {
|
|
||||||
println!("{}", n);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn fizzbuzz_to(n: u32) {
|
|
||||||
for n in 1..=n {
|
|
||||||
fizzbuzz(n);
|
|
||||||
}
|
|
||||||
}
|
|
@@ -1,4 +1,3 @@
|
|||||||
#[allow(dead_code)]
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
struct Person<'a> {
|
struct Person<'a> {
|
||||||
name: &'a str,
|
name: &'a str,
|
@@ -20,6 +20,6 @@ impl fmt::Display for List {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
let v = List(vec![6, 0, 6, 8, 0, 8, 9, 1, 1, 1, 3, 1, 2]);
|
let v = List(vec![1, 2, 3]);
|
||||||
println!("{}", v);
|
println!("{}", v);
|
||||||
}
|
}
|
@@ -1,5 +1,3 @@
|
|||||||
#[allow(unused_variables)]
|
|
||||||
#[allow(unused_assignments)]
|
|
||||||
fn main() {
|
fn main() {
|
||||||
let logical: bool = true;
|
let logical: bool = true;
|
||||||
|
|
@@ -22,14 +22,5 @@ fn main() {
|
|||||||
println!("borrow a section of the array as a slice");
|
println!("borrow a section of the array as a slice");
|
||||||
analyze_slice(&ys[1..4]);
|
analyze_slice(&ys[1..4]);
|
||||||
|
|
||||||
let empty_array: [u32; 0] = [];
|
// println!("{}", xs[5]);
|
||||||
assert_eq!(&empty_array, &[]);
|
|
||||||
assert_eq!(&empty_array, &[][..]);
|
|
||||||
|
|
||||||
for i in 0..xs.len() + 1 {
|
|
||||||
match xs.get(i) {
|
|
||||||
Some(xval) => println!("{}: {}", i, xval),
|
|
||||||
None => println!("Slow down! {} is too far!", i),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
@@ -3,8 +3,6 @@ fn main() {
|
|||||||
|
|
||||||
println!("1 - 2 = {}", 1i32 - 2);
|
println!("1 - 2 = {}", 1i32 - 2);
|
||||||
|
|
||||||
println!("1e4 is {}, -2.5e-3 is {}", 1e4, -2.5e-3);
|
|
||||||
|
|
||||||
println!("true AND false is {}", true && false);
|
println!("true AND false is {}", true && false);
|
||||||
println!("true OR false is {}", true || false);
|
println!("true OR false is {}", true || false);
|
||||||
println!("NOT true is {}", !true);
|
println!("NOT true is {}", !true);
|
@@ -1,15 +0,0 @@
|
|||||||
type NanoSecond = u64;
|
|
||||||
type Inch = u64;
|
|
||||||
type U64 = u64;
|
|
||||||
|
|
||||||
fn main() {
|
|
||||||
let nanoseconds: NanoSecond = 5 as U64;
|
|
||||||
let inches: Inch = 2 as U64;
|
|
||||||
|
|
||||||
println!(
|
|
||||||
"{} nanoseconds + {} inches = {} unit?",
|
|
||||||
nanoseconds,
|
|
||||||
inches,
|
|
||||||
nanoseconds + inches
|
|
||||||
);
|
|
||||||
}
|
|
15
rustbyexample/types/alias.rs
Normal file
15
rustbyexample/types/alias.rs
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
type NanoSecond = u64;
|
||||||
|
type Inch = u64;
|
||||||
|
|
||||||
|
#[allow(non_camel_case_types)]
|
||||||
|
type u64_t = u64;
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
let nanoseconds: NanoSecond = 5 as u64_t;
|
||||||
|
let inches: Inch = 2 as u64_t;
|
||||||
|
|
||||||
|
println!("{} nanoseconds + {} inches = {} unit?",
|
||||||
|
nanoseconds,
|
||||||
|
inches,
|
||||||
|
nanoseconds + inches);
|
||||||
|
}
|
@@ -13,3 +13,4 @@ fn main() {
|
|||||||
let shadowed_binding = 2;
|
let shadowed_binding = 2;
|
||||||
println!("shadowed in outer block: {}", shadowed_binding);
|
println!("shadowed in outer block: {}", shadowed_binding);
|
||||||
}
|
}
|
||||||
|
|
@@ -11,5 +11,5 @@ fn main() {
|
|||||||
|
|
||||||
let _unused_variable = 3u32;
|
let _unused_variable = 3u32;
|
||||||
|
|
||||||
let _noisy_unused_variable = 2u32;
|
let noisy_unused_variable = 2u32;
|
||||||
}
|
}
|
Reference in New Issue
Block a user