Skip to content

Instantly share code, notes, and snippets.

View rlcheng's full-sized avatar

Richard rlcheng

  • Los Angeles, CA
View GitHub Profile
require "test/unit"
require "code_kata_reverse"
class ReverseTest < Test::Unit::TestCase
def setup
@test_string = "programming"
end
def test_reverse_against_original
assert_equal reverse_it(@test_string), @test_string.reverse, "reverse_it works"
#return the reverse the input string
#
#also works #(0..input_string.length - 1).each { |i| reversed[i] = input_string[(i + 1) * -1]}
def reverse_it (input_string)
reversed = String.new
input_string.split("").each { |x| reversed.insert(0, x)}
reversed
end
#
#write a method called "transpose" that takes this array of arrays:
#
#[
#['first', 'second'],
#['third', 'fourth']
#]
#
# and transposes it into this array of arrays
#
#
#write a method called "transpose" that takes this array of arrays:
#
#[
#['first', 'second'],
#['third', 'fourth']
#]
#
# and transposes it into this array of arrays
#
param_array = [
['working', 'husky'],
['sporting', 'labrador'],
['non-working', 'poodle'],
['sporting', 'pointer'],
['working', 'bernese mountain dog']
]
hashed = param_array.inject(Hash.new(Array.new)) { |h, a| h[a[0].gsub('-','_').to_sym] += [a[1]]; h }
class Array
def my_map(&block)
for i in 0..self.length-1
self[i] = block.call(self[i])
end
self
end
end
array = [1, 2, 3]
#add a logger to this class, such that there is only one logger, that writes to a file called ./logfile.txt
#one logger instance per charlie instance
#ok well onto part two -- one logger instance for all charlie instances
class Logger
def self.log(number)
File.open("logfile.txt", "a") { |f| f.puts number }
end
#Do whatever you need to do to Ruby, such that I can say: 9 - 8, and the answer will be 17
#And if I say 9 + 8, the answer will be 1
#so - i load whatever code you want to give me via a console, and I should be able to do the above
#turn plus into minus, minus into plus
#a short sentence explaining what you did and why it works would be nice
def add_sub_swap (math)
math = math.split(/\s+/) #makes sure that either 1 or more white space is removed
i = 0
while i < math.length do
#today's code kata: Write a function called word_count, that takes a sentence
#as a string as input, and #returns the frequency of each word in that
#sentence, as a hash whose key is the word, and whose count is the #number of
#times that word appears in that sentence.
#
#1) ignore case,
#2) ignore any non word characters
#Here is the paragraph:
#The quick brown fox jumped over the moon. This mammal did not jump over the sun; it jumped over the moon. And #it was quick about it.
#let's use the whole paragraph
#Given a 3 or 4 digit number with distinct digits, return a sorted array of all
#the unique numbers that can be formed with those digits.
#ie, given 123, return [123, 132, 213, 231, 312, 321]
def permutation(number)
number.to_s.split("").permutation.to_a.map { |element| element.join.to_i }
end
p permutation(123)