Skip to content

Instantly share code, notes, and snippets.

View takuma-saito's full-sized avatar

takuma.saito takuma-saito

  • 05:46 (UTC +09:00)
View GitHub Profile
@takuma-saito
takuma-saito / connection_pool.rb
Last active May 3, 2020 10:32
connection_pool.rb
class ConnectionPool
attr_reader :conns
def initialize(max, &block)
@mutex = Mutex.new # マルチスレッドからの排他的ロック
@cv = ConditionVariable.new
@max = max
@que = []
@conns = []
@create_block = block
@created = 0
@takuma-saito
takuma-saito / main.rb
Created May 3, 2020 07:13
覆面算(汎用版)
# 問題:
# http://hidesugar.web.fc2.com/ym2/ym2musikuizan2.txt
# ABCDEF * G = FABCDE
# 解答: 230769 * 4 = 923076
def solve(sx, sy, sz, mapping)
x = sx.inject(0) {|sum, x| sum * 10 + mapping[x]}
y = sy.inject(0) {|sum, y| sum * 10 + mapping[y]}
z = Enumerator.new do |e|
t = (x * y)
@takuma-saito
takuma-saito / fukumen.rb
Last active May 3, 2020 06:36
fukumen.rb
# 問題: https://twitter.com/nada_mathclub/status/1256418924737880069
# : vivid * vive = brillante の覆面算を解く
# 解答: 62621 * 6267 = 392445807
def solve(v, i, d, e)
return nil if v == 0
vivid = [v, i, v, i, d].inject(0) {|sum, x| sum * 10 + x}
vive = [v, i, v, e].inject(0) {|sum, x| sum * 10 + x}
brillante = Enumerator.new do |e|
t = (vivid * vive)
class Future
def initialize(&block)
@que = Queue.new
@t = Thread.new {
@que << block.call
}
end
def value
return @que.pop
ensure
@takuma-saito
takuma-saito / pubsub.rb
Last active May 3, 2020 04:14
pubsub.rb
class Topic
attr_reader :name
def initialize(name)
@name = name
@clients = {}
end
def publish(message)
@clients.values.each {|client| client.receive(@name, message)}
end
@takuma-saito
takuma-saito / Gemfile
Last active May 2, 2020 13:31
worker_get_url.rb
source 'https://rubygems.org'
gem 'open_uri_redirections'
require 'thread'
class Workers
def initialize(count)
@q = Queue.new
@count = count
@jobs = (0...@count).map.with_index {|id|
Thread.new do
while (job = @q.pop)
total = job.(id, total)
@takuma-saito
takuma-saito / timeout.rb
Last active May 2, 2020 12:10
timeout.rb
class TimeoutError < StandardError; end
def timeout(sec)
x = Thread.current
t = Thread.new do
begin
sleep sec
x.raise TimeoutError.new "Exceed maximum timeout value #{sec}s"
rescue e
x.raise e
end
require 'strscan'
BEGIN_TAGS = %w(<%= <%# <%)
END_TAGS = %w(%>)
class MiniErb
def scan(content)
scanner = ::StringScanner.new(content)
state = :text
until scanner.eos?
case state
module Forwardable
def delegate_methods(obj, *methods)
methods.each {|method| delegate_method(obj, method)}
end
def delegate_method1(obj, method)
self.module_eval %Q{
def #{method}(*args, &block)
_#{obj}.#{method}(*args, &block)
end
}