Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Completed: arrays, fp #40

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions test/bukanin/arrays/solution.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
module Bukanin
module Arrays
class << self
def replace(array)
max = array.max
array.map { |item| item > 0 ? max : item }
end

def search(array, query)
r = search_bin(array, 0, array.size, query)
array[r] == query ? r : -1
end

def search_bin(array, left, right, query)
return right if left >= right

mid = left + (right - left) / 2
query <= array[mid] ? right = mid : left = mid + 1

search_bin(array, left, right, query)
end
end
end
end
26 changes: 26 additions & 0 deletions test/bukanin/arrays/test.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
require './test/test_helper.rb'
require_relative './solution.rb'

class Bukanin::ArraysTest < Minitest::Test
# Заменить все положительные элементы целочисленного массива на максимальное значение элементов массива.
def test_replace
array = [3, 2, -8, 4, 100, -6, 7, 8, -99]
new_array = Bukanin::Arrays.replace(array)

assert new_array == [100, 100, -8, 100, 100, -6, 100, 100, -99]
end

# Реализовать бинарный поиск
# Функция должна возвращать индекс элемента
def test_bin_search
assert Bukanin::Arrays.search([1], 900) == -1
assert Bukanin::Arrays.search([1], 1) == 0
assert Bukanin::Arrays.search([], 900) == -1
assert Bukanin::Arrays.search([1, 4, 5, 7, 8, 9], 9) == 5
assert Bukanin::Arrays.search([1, 4, 5, 7, 8, 9], 1) == 0
assert Bukanin::Arrays.search([1, 4, 5, 7, 8, 9], 6) == -1

array = (1..10000).to_a
assert Bukanin::Arrays.search(array, array[1000]) == 1000
end
end
17 changes: 17 additions & 0 deletions test/bukanin/fp/solution.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
module Bukanin
module Fp
class << self
# Обратиться к параметрам фильма можно так:
# film["name"], film["rating_kinopoisk"], film["rating_imdb"],
# film["genres"], film["year"], film["access_level"], film["country"]
def rating(array)
items = array.select { |elem| !elem['country'].nil? && elem['rating_kinopoisk'].to_f > 0 && elem['country'].count(',') > 0 }
items.map { |elem| elem['rating_kinopoisk'].to_f }.reduce(:+) / items.size
end

def chars_count(films, threshold)
films.map { |elem| elem['rating_kinopoisk'].to_f >= threshold ? elem['name'].scan(/и/i).length : 0 }.reduce(:+)
end
end
end
end
25 changes: 25 additions & 0 deletions test/bukanin/fp/test.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
require 'csv'
require './test/test_helper.rb'
require_relative './solution.rb'

class Bukanin::FpTest < Minitest::Test
# Посчитать средний рейтинг фильмов по версии кинопоиска у которых две или больше стран
# Фильмы у которых рейтиг не задан или равен 0 не учитывать в расчете среднего.
def test_rating
array = CSV.readlines('./test/fixtures/films.csv', headers: true)

result = Bukanin::Fp.rating(array)
assert result == 6.809410385259628
end

# Посчитать количесвто букв 'и' в названиях всех фильмов с рейтингом кинопоиска больше или равным заданному значению
def test_chars_count
array = CSV.readlines('./test/fixtures/films.csv', headers: true)

result = Bukanin::Fp.chars_count(array, 5)
assert result == 3966

result = Bukanin::Fp.chars_count(array, 8.5)
assert result == 42
end
end
45 changes: 45 additions & 0 deletions test/bukanin/fp2/solution.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
module Bukanin
module Fp2
class MyArray < Array
# Использовать стандартные функции массива для решения задач нельзя.
# Использовать свои написанные функции для реализации следующих - можно.

# Написать свою функцию my_each
def my_each
for elem in self
block_given? ? yield(elem) : elem
end
self
end

# Написать свою функцию my_map
def my_map
result = MyArray.new
my_each do |elem|
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

result << yield(elem)
end
result
end

# Написать свою функцию my_compact
def my_compact
result = MyArray.new
my_each.each { |elem| result << elem unless elem.nil? }
result
end

# Написать свою функцию my_reduce
def my_reduce(memo = nil)
if memo.nil?
shift = 1
memo = self[0]
else
shift = 0
end

drop(shift).my_each { |e| memo = yield(memo, e) }
memo
end
end
end
end
50 changes: 50 additions & 0 deletions test/bukanin/fp2/test.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
require 'csv'
require './test/test_helper.rb'
require_relative './solution.rb'

class Bukanin::Fp2Test < Minitest::Test
def setup
@array = generate :array
@my_array = Bukanin::Fp2::MyArray.new(@array)
@int = generate :int
end

def test_my_each
result = []
my_result = []

func = -> (element) { result << element if element.odd? }
my_func = -> (element) { my_result << element if element.odd? }

assert @array.each(&func) == @my_array.my_each(&my_func)
assert result == my_result
end

def test_my_map
func = -> (element) { element * @int }
assert @array.map(&func) == @my_array.my_map(&func)
assert @array.map(&func).map(&func) == @my_array.my_map(&func).my_map(&func)
end

def test_my_compact
func = -> (element) { element if element.even? }
func_another = -> (element) { element * @int }
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

добавь ещё вот такой assert

func_yet_another = -> (element) { element.even? }
assert @array.map(&func_yet_another).compact == @my_array.my_map(&func_yet_another).my_compact

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Тест не проходит потому что из my_each возвращаются Enumerator'ы с одинаковыми элементами, но разными адресами в памяти

assert @array.map(&func).compact == @my_array.my_map(&func).my_compact
assert @array.map(&func).compact.map(&func_another) == @my_array.my_map(&func).my_compact.my_map(&func_another)

func_yet_another = -> (element) { element.even? }

puts @array.map(&func_yet_another).compact.inspect
puts @my_array.my_map(&func_yet_another).my_compact.inspect

assert @array.map(&func_yet_another).compact == @my_array.my_map(&func_yet_another).my_compact
end

def test_my_reduce
func = -> (acc, element) { acc * element }

assert @array.reduce(&func) == @my_array.my_reduce(&func)
assert @array.reduce(2, &func) == @my_array.my_reduce(2, &func)
assert @array.reduce(&:+) == @my_array.my_reduce(&:+)
end
end