This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fn count_squares(arr: &[usize]) -> usize { | |
use std::collections::HashMap; | |
let mut occurs = HashMap::<usize, usize>::new(); //создаём мапу, в которой будем хранить вхождения чисел | |
//перебираем все стороны из массива | |
for &i in arr.iter() { | |
//если такой стороны в мапе ещё нет, вставляем с нулевым количеством вхождений... | |
let count = occurs.entry(i).or_insert(0); | |
//...и инкрементируем | |
*count += 1; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fn count_places(street: &str) -> usize { | |
let mut free = vec![true; street.len()]; //заводим вектор, в котором будем писать, свободно ли место | |
//и инициализируем его истинными значениями | |
for (i, a) in street.bytes().enumerate() { //перебираем символы вместе с индексами | |
match a { //смотрим, что за символ | |
b'E' => free[i] = false, //если выезд - помечаем соответсвующее место как занятое | |
b'S' => { //если остановка - помечаем как занятое | |
free[i] = false; //текущее место... | |
free[i.saturating_sub(1)] = false; //...предыдущее... | |
free[i.saturating_sub(2)] = false; //...и предпредыдущее |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fn count_profit1(time: usize, orders: &[u32]) -> u32 { | |
if time == 0 || orders.len() == 0 { //микрооптимизация: если длина массива или время | |
return 0 //нулевое, то сразу возвращаем нуль | |
} | |
let mut sorted = orders.to_vec(); //инициализируем временный буфер | |
sorted.sort_unstable_by(|a, b| b.cmp(a)); //сортируем буфер по убыванию | |
sorted.into_iter().take(time).sum() //берём time первых элементов и суммируем | |
} | |
fn count_profit2(time: usize, orders: &[u32]) -> u32 { |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- Вспомогательная функция, разделяющая число | |
-- на младший разряд и все остальные | |
base10 x = (x `quot` 10, x `rem` 10) | |
-- Конструирует список из числа | |
mkListNum x = case base10 x of | |
(0, digit) -> [digit] | |
(rest, digit) -> (digit : mkListNum rest) | |
-- Переводит список обратно в число |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const SPEED_REGULAR_KMPH: i64 = 50; | |
const SPEED_CLEANUP_KMPH: i64 = 20; | |
type Point = (i64, i64); | |
struct Segment { | |
start: Point, | |
end: Point, | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Data.List (foldl') | |
solution = flip (-) 1 . foldl' lcm 1 . enumFromTo 1 | |
main = putStrLn . show $ solution 4 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
--gcd=greatest common divisor | |
gcd' x y | |
| x < y = gcd' y x | |
| x == y = x | |
| otherwise = let x' = x - y in x' `seq` gcd' x' y | |
--lcm=least common divisor | |
lcm' x y = | |
let prod = x*y | |
in prod `seq` prod `div` gcd' x y |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import qualified Data.Vector.Unboxed as V | |
--gcd=greatest common divisor | |
gcd' x y | |
| x < y = gcd' y x | |
| x == y = x | |
| otherwise = let x' = x - y in x' `seq` gcd' x' y | |
--lcm=least common multiple | |
lcm' x y = |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const COORD_BOUND: usize = 100; //Максимально воможное по модулю значение координат | |
type CoordBase = i16; //Тип координат. Выбирается так, чтобы включал в | |
type Coord = (CoordBase, CoordBase); //диапазон [-COORD_BOUND, COORD_BOUND] | |
struct View2d { //Вспомогательная структура для более удобной | |
side: usize, //индексации | |
inner: Vec<usize>, | |
} | |
impl View2d { |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Control.Arrow ((***), (&&&)) | |
shift = go | |
where | |
go [] = [] | |
go (x:xs) = xs ++ [x] | |
shiftedZipWith f = uncurry (zipWith f) . (&&&) id shift | |
shiftedSum = shiftedZipWith (+) | |
shiftedFSub = shiftedZipWith (flip (-)) |
OlderNewer