-
Notifications
You must be signed in to change notification settings - Fork 17
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
base: master
Are you sure you want to change the base?
Changes from 2 commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
module Bukanin | ||
module Arrays | ||
class << self | ||
def replace(array) | ||
max = array.max | ||
array.map { |item| item > 0 ? max : item } | ||
end | ||
|
||
def search(array, query) | ||
right = array.size | ||
left = 0 | ||
|
||
loop do | ||
break if left >= right | ||
mid = left + (right - left) / 2 | ||
if query <= array[mid] | ||
right = mid | ||
else | ||
left = mid + 1 | ||
end | ||
end | ||
|
||
(array[right] == query) ? right : -1 | ||
end | ||
end | ||
end | ||
end |
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 |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
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) | ||
sumstat = 0.0 | ||
counted = 0 | ||
|
||
for idx in 0..(array.size - 1) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. постарайся не использовать for, в реальной жизни он крайне редко используется. тут задачи скорее на map/reduce, можно смело использовать любые стандартные функции из арсенала массива |
||
item = array[idx] | ||
|
||
next if item['country'].nil? || item['country'].split(',').count < 2 | ||
|
||
if (rate = item['rating_kinopoisk'].to_f) > 0 | ||
counted += 1 | ||
sumstat += rate | ||
end | ||
end | ||
|
||
sumstat / counted | ||
end | ||
|
||
def chars_count(films, threshold) | ||
counted = 0 | ||
|
||
for idx in 0..(films.size - 1) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. тут тоже for нужно заменить |
||
next if films[idx]['rating_kinopoisk'].to_f < threshold | ||
counted += films[idx]['name'].scan(/и/i).length | ||
end | ||
|
||
counted | ||
end | ||
end | ||
end | ||
end |
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 |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
module Bukanin | ||
module Fp2 | ||
class MyArray < Array | ||
# Использовать стандартные функции массива для решения задач нельзя. | ||
# Использовать свои написанные функции для реализации следующих - можно. | ||
|
||
# Написать свою функцию my_each | ||
def my_each | ||
for elem in self | ||
yield(elem) | ||
end | ||
self | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. что вернется в конце функции если не написать тут self? |
||
end | ||
|
||
# Написать свою функцию my_map | ||
def my_map | ||
result = MyArray.new | ||
my_each do |elem| | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. |
||
result.append(yield(elem)) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. не припомню метод append у массива |
||
end | ||
result | ||
end | ||
|
||
# Написать свою функцию my_compact | ||
def my_compact | ||
result = MyArray.new | ||
my_each do |elem| | ||
result.append(elem) if elem | ||
end | ||
result | ||
end | ||
|
||
# Написать свою функцию my_reduce | ||
def my_reduce | ||
|
||
end | ||
end | ||
end | ||
end |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
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 } | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 There was a problem hiding this comment. Choose a reason for hiding this commentThe 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) | ||
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 |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
переписываем на рекурсию