Algorithms Flashcards
Reverse and Integer
x = 12345
x = 12345 y = 0 while x > 0 do y = y*10 y = y + (x%10) x = x/10 end puts y
Make a nested array
[‘Dave’, 7, ‘Miranda’, 3, ‘Jason’, 11]
p [‘Dave’, 7, ‘Miranda’, 3, ‘Jason’, 11].each_slice(2).to_a
[[“Dave”, 7], [“Miranda”, 3], [“Jason”, 11]]
array = [“Jason”, “Jason”, “Teresa”, “Judah”, “Michelle”, “Judah”, “Judah”, “Allison”]
=> {“Jason”=>2, “Teresa”=>1, “Judah”=>3, “Michelle”=>1, “Allison”=>1}
count = Hash.new(0)
array.each {|v| count[v] += 1 }
or
array.inject(Hash.new(0)) { |total, e| total[e] += 1 ;total}
p count => {“Jason”=>2, “Teresa”=>1, “Judah”=>3, “Michelle”=>1, “Allison”=>1}
dividing an even number with biggest equal odd numbers as;
36 => [9,9,9,9]
54 => [27, 27]
56 => [7,7,7,7,7,7,7,7]
def fun(num) odd = num odd /= 2 while odd.even? [odd] * (num / odd) end
ruby prime number or not
- prime? => false
- prime? => true
class Fixnum def prime? ('1' * self) !~ /^1?$|^(11+?)\1+$/ end end
19283945 => (5,4,9,3,8,2,9,1)
n.to_s.chars.reverse!.map(&:to_i)
n.to_s.split(“”).reverse!.map(&:to_i)
19283945 => (5,4,9,3,8,2,9,1)
filter_list([1,’a’,’b’,0,15]) => [1,0,15]
l. reject {|i| i.is_a? String }
l. delete_if {|i| i.is_a? String }
l. select {|i| i.is_a? Integer }
l. delete_if { |x| x.class == String }
l. select{ |w| w.is_a? Numeric }
filter_list([1,’a’,’b’,0,15]) => [1,0,15]
add_binary(a,b)
(51,12) => 111111
(1,1) => 10
def add_binary(a,b) (a+b).to_s(2) end (51,12) => 111111 (1,1) => 10
arr(0,1) => 0+1 = 1
arr(-3,2) => -3 + -2 + -1 + 0 + 1 + 2 = -3
if b > a (a..b).to_a.inject(0, &:+) else (b..a).to_a.inject(0, &:+) end
or
b > a ? (a..b).reduce(:+) : (b..a).reduce(:+)
arr(0,1) => 0+1 = 1
arr(-3,2) => -3 + -2 + -1 + 0 + 1 + 2 = -3
find the smallest word in an array
s.split.map(&:size).min l = s.split(" ").min_by {|w| w.size } return l.length # l: length of the shortest word
Increment by set, then sum all numbers
sequence_sum(2, 6, 2), 12)
sequence_sum(1, 5, 1), 15)
sequence_sum(1, 5, 3), 5)
def sequence_sum(begin_number, end_number, step)
return 0 if begin_number > end_number
sum = 0
(begin_number..end_number).step(step) {|v| sum += v}
sum
end
or
(begin_number..end_number).step(step).reduce(0, :+)
sum of the numbers in a range (enumerable method)
(5. .10).reduce(:+)
(5. .10).inject(:+)
(5. .10).inject {|sum, n| sum + n }
Find the binaries 225 76 10011001 101001011
225 = 128 + 64 + 32 + 0 + 0 + 0 + 0 + 1 –> 11100001
76 = 64 + 0 + 0 + 8 + 4 + 0 + 0 –> 1001100
10011001 –> 128 + 0 + 0 + 16 + 8 + 0 + 0 + 1 = 143
101001011 –> 256 + 0 + 128 + 0 + 0 + 16 + 0 + 2 + 1 = 403
Binary to Hex conversion
1 0 1 0 0 1 1 0
----1 0 1 0 0 1 1 0 = 166 8 4 2 1 - 8 4 2 1 1 0 1 0 - 0 1 1 0 0xA 0x6 ----> 0xA6
Hex to Binary conversion
0xF2
---0xF2 0xF 0x2 8 4 2 1 - 8 4 2 1 1 1 1 1 - 0 0 1 0 ------> 11110010 = 242
Decimal to Hex conversion
137
137 / 16 –> 8 whole(128) + 0x9 (remainder)
8 / 16 –> 0 + 8 (remainder)
——> 0x89
Decimal to Hex conversion
243
243 / 16 –> 15 whole(240) + 0x3 (remainder)
15 –> F
——> 0xF3
Hex to Decimal conversion
0x9F
—-0x9F
9 x 16 = 144
F –> 15
—–> 144 + 15 = 159
Hex to Decimal conversion
0xA59C
----0xA59C 10 x (16x16x16) = 40960 5 x (16x16) = 1280 9 x 16 = 144 C --> 12 --------> 42.396
Regex expressions for “a b”
/s
/S
[^a]
“a b”
/s –> whitespace between a and b
/S –> match only a and b
[^a] –> match whitespace and b (not a)
Regex expressions \d \D \h \H \w \W
\d – Any decimal digit (0-9)
\D – Any character but a decimal digit (not decimal)
\w – matches “word characters”,
\W – matches “non-word characters”.
\h – Any hexadecimal digit (0-9, A-F, a-f) (ruby only)
\H – Any character but a hexadecimal digit (ruby only)
Write a regex that matches any sequence of 3 characters delimited by whitespace characters.
“reds and blues
the lazy cat sleeps”
“reds and blues
the lazy cat sleeps”
/\s…\s/ – matches \whitespace(and/the/cat)whitespace\
%w(1 2 3 4)
=> [“1”, “2”, “3”, “4”]
check if the number is integer?
def integer?(num)
num.to_i.to_s == num
end
How to load a file like .yml?
require ‘yaml’
MESSAGES = YAML.load_file(‘calculator_messages.yml’)
what does .yml file return?
welcome: ‘welcome to programming’
Hash
=> def messages(message)
MESSAGES[message]
end
print float m with only 2 digits
{format(‘%02.2f’, m)}
process => Another game! Y/N
answer = gets.chomp
unless answer.downcase.start_with?(‘y’)
if answer !~ /y/i
famous_words = ‘seven years ago..’
add ‘Four score and’ in front of the famous words string
“Four score and “ + famous_words
famous_words.prepend(“Four score and “)
“Four score and “ «_space;famous_words
flintstones = { “Fred” => 0, “Wilma” => 1, “Barney” => 2, “Betty” => 3}
get the array [“Barney”, 2] ?
flintstones.assoc(“Barney”)
# check that "Spot" is present ages = { "Herman" => 32, "Lily" => 30, "Grandpa" => 402 }
ages. has_key?(“Spot”)
ages. include?(“Spot”)
ages. member?(“Spot”)
ages. key?(“Lily”)
monsters = “The Monsters are creepy in a good way.”
=> “tHE mUNSTERS ARE CREEPY IN A GOOD WAY.”
monsters.swapcase
ages = { "Herman" => 32, "Lily" => 30 } additional_ages = { "Marilyn" => 22, "Spot" => 237 }
ages.merge!(additional_ages)
flintstones = %w(Fred Barney Wilma)
add “Dino” and “Hoppy” to array
flintstones.concat(%w(Dino Hoppy))
statement = “The Flintstones Rock!”
count number of “t” in string
=> statement.scan(‘t’).count
=> statement.chars.count{|char| char =~ /t/}
clear screen in command line?
def clear_screen
system(“clear”) || system(“cls”)
end
produce = { 'apple' => 'Fruit', 'carrot' => 'Vegetable', 'pear' => 'Fruit', 'broccoli' => 'Vegetable' }
select_fruit(produce) # => {“apple”=>”Fruit”, “pear”=>”Fruit”}
def select_fruit(str) h = str.delete_if {|key,value| str[key] != 'Fruit' } end
select_fruit(produce) # => {“apple”=>”Fruit”, “pear”=>”Fruit”}
{ a: “ant”, b: “bear”, c: “cat” }.each_with_index {|pair, index| puts “The index of #{pair} is #{index}.” }
[1, 2, 3].each_with_object([]) {|num, array|
array «_space;num if num.odd? }
{ a: “ant”, b: “bear”, c: “cat” }.first(2)
each_with_index => # The index of [:a, “ant”] is 0.
each_with_object => # [1, 3] # array is initialized in method!
firtst(2) => # [[:a, “ant”], [:b, “bear”]]
odd, even = [1, 2, 3].partition do |num|
num.odd?
end
long, short = { a: “ant”, b: “bear”, c: “cat” }.partition do |key, value|
value.size > 3
end
odd # => [1, 3]
even # => [2]
partition # => [[[:b, “bear”]], [[:a, “ant”], [:c, “cat”]]]
long. to_h # => { :b => “bear” }
short. to_h # => { :a => “ant”, :c => “cat” }
[1, 2, 3].reject do |num|
num > 3
end
reject => [1, 2, 3] (return values if false)
hash = { a: ‘ant’, b: ‘bear’ }
hash.shift
=> [:a, “ant”]
arr = [1, 2, 3, 4, 5]
arr. take(2)
arr. fetch(2)
arr. slice(2)
arr = [1, 2, 3, 4, 5]
arr. take(2) => # [1, 2]
arr. fetch(2) => # 3
arr. slice(2) => # 3
ages = { “Herman” => 32, “Lily” => 30, “Grandpa” => 5843}
sum all values
total_ages = 0
ages.each { |key, value| total_ages += value }
total_ages
ages.values.inject(:+)
ages = { “Herman” => 32, “Lily” => 30, “Grandpa” => 402 }
remove if the age is over 100
ages. keep_if { |_, age| age < 100 }
ages. select {|k,v| v < 100 }
ages. delete_if {|k,v| v > 100 }
flintstones = %w(Fred Barney Wilma Betty BamBam Pebbles)
get index of element starting with ‘Be’
flintstones. index {|v| v.start_with?(‘Be’) }
flintstones. index { |name| name[0, 2] == “Be” }
flintstones. each_with_index {|v, index| puts index if v.chars.first(2).join == ‘Be’}
flintstones = %w(Fred Barney Wilma Betty BamBam Pebbles)
=> [“Fre”, “Bar”, “Wil”, “Bet”, “Bam”, “Peb”]
flintstones. map {|v| v.split(‘’).take(3).join }
flintstones. map! { |name| name[0, 3] }
{ “F”=>1, “R”=>1, “T”=>1, “c”=>1, “e”=>2, … }
statement = “The Flintstones Rock”
{ “F”=>1, “R”=>1, “T”=>1, “c”=>1, “e”=>2, … }
statement.chars.each_with_object({}) {|letter, hash| hash[letter] = statement.scan(letter).count unless letter == ‘ ‘ }
munsters = {
“Lily” => { “age” => 30, “gender” => “female” },
“Grandpa” => { “age” => 402, “gender” => “male” },
“Eddie” => { “age” => 10, “gender” => “male” }, }
add an age_group acc. to the age
{ “Lily” => {“age” => 30, “gender” => “female”, “age_group” => “adult” },
“Grandpa” => { “age” => 402, “gender” => “male”, “age_group” => “senior” },
“Eddie” => { “age” => 10, “gender” => “male”, “age_group” => “kid” } }
munsters.values.each do |hash| case hash['age'] when (0..18) hash['age_group'] = 'kid' when (18...65) hash['age_group'] = 'adult' else hash['age_group'] = 'senior' end end
2 <=> 1 1 <=> 2 2 <=> 2 'b' <=> 'a' 'a' <=> 'b' 'b' <=> 'b' 1 <=> 'a'
2 <=> 1 # => 1 1 <=> 2 # => -1 2 <=> 2 # => 0 'b' <=> 'a' # => 1 'a' <=> 'b' # => -1 'b' <=> 'b' # => 0 1 <=> 'a' # => nil
’!’ <=> ‘A’
‘b’ <=> ‘}’
‘A’ <=> ‘a’
How do you determine a string’s ASCII position?
’!’ <=> ‘A’ # => -1
‘b’ <=> ‘}’ # => -1
‘A’ <=> ‘a’ # => -1
You can determine a string’s ASCII position by calling ord on the string.
‘b’.ord # => 98
‘}’.ord # => 125