Skip to content

Instantly share code, notes, and snippets.

View takuma-saito's full-sized avatar

takuma.saito takuma-saito

  • 08:30 (UTC +09:00)
View GitHub Profile
@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
}
@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)
@takuma-saito
takuma-saito / calc-main.rb
Last active February 28, 2020 11:38
calc-main.rb
# 4,6,6,5,6 を1つずつと四則演算、累乗のみを使って 777を作る
def solve(nums)
if nums.length === 1
yield({val: nums[0]})
return
end
len = nums.length
len.times do |i|
solve(nums[0...i]) do |l|
@takuma-saito
takuma-saito / rec_math.rb
Created February 23, 2020 15:28
rec_math.rb
def rec(num, values)
if num == 0
values.reverse!
puts "#{values.join("+")}=#{values.inject(&:+)}"
values.reverse!
return
end
k = 1
begin
d = 10 ** k
@takuma-saito
takuma-saito / pqueue.rb
Last active February 12, 2020 15:11
pqueue.rb
M = 1 << 63
class PQueue
def initialize(n)
size = 1
size += 1 while (n = n/2) != 0
size = 1 << size
@arr = Array.new(size, M)
@i = 0
end
@takuma-saito
takuma-saito / convert_filename.sh
Created February 11, 2020 07:13
convert_filename.sh
#!/bin/bash -e
# 日本語重複問題対応スクリプト
find . -type f |
while read src;
do
dist="$(echo $src | nkf -w --ic=utf8-mac -)"
if [[ "$dist" != "$src" ]]; then
echo mv "$src" "$dist"
fi
done | sh
@takuma-saito
takuma-saito / square_root.rb
Last active February 9, 2020 18:28
square_root.rb
# [l, r)
def init
@sorted_bucket_items = @items.each_slice(BUCKET_SIZE).to_a.map {|x| x.sort {|a, b| b <=> a}}
end
# [l, r)
def query(l, r, k)
lb, ub = [0, 1 << 63]
while ub - lb > 1
mid = (ub+lb)/2
@takuma-saito
takuma-saito / segment_tree_bin.rb
Created February 9, 2020 16:25
segment_tree_bin.rb
# 配列 items が与えられたとする、[L, R) に対して最大値を与えよ
class SegmentTree
attr_reader :items
def initialize(n)
while (v = (n & (n - 1))) != 0
n = v
end
@size = n << 2
@items = Array.new(@size, [])
end