Public speaking course notes Read "Dynamo, Amazon’s Highly Available Key-value Store" Read "Bigtable, A Distributed Storage System for Structured Data" Read "Streaming Systems" 3, Watermarks Read "Streaming Systems" 1&2, Streaming 101 Read "F1, a distributed SQL database that scales" Read "Zanzibar, Google’s Consistent, Global Authorization System" Read "Spanner, Google's Globally-Distributed Database" Read "Designing Data-intensive applications" 12, The Future of Data Systems IOS development with Swift Read "Designing Data-intensive applications" 10&11, Batch and Stream Processing Read "Designing Data-intensive applications" 9, Consistency and Consensus Read "Designing Data-intensive applications" 8, Distributed System Troubles Read "Designing Data-intensive applications" 7, Transactions Read "Designing Data-intensive applications" 6, Partitioning Read "Designing Data-intensive applications" 5, Replication Read "Designing Data-intensive applications" 3&4, Storage, Retrieval, Encoding Read "Designing Data-intensive applications" 1&2, Foundation of Data Systems Three cases of binary search TAMU Operating System 2 Memory Management TAMU Operating System 1 Introduction Overview in cloud computing 2 TAMU Operating System 7 Virtualization TAMU Operating System 6 File System TAMU Operating System 5 I/O and Disk Management TAMU Operating System 4 Synchronization TAMU Operating System 3 Concurrency and Threading TAMU Computer Networks 5 Data Link Layer TAMU Computer Networks 4 Network Layer TAMU Computer Networks 3 Transport Layer TAMU Computer Networks 2 Application Layer TAMU Computer Networks 1 Introduction Overview in distributed systems and cloud computing 1 A well-optimized Union-Find implementation, in Java A heap implementation supporting deletion TAMU Advanced Algorithms 3, Maximum Bandwidth Path (Dijkstra, MST, Linear) TAMU Advanced Algorithms 2, B+ tree and Segment Intersection TAMU Advanced Algorithms 1, BST, 2-3 Tree and Heap TAMU AI, Searching problems Factorization Machine and Field-aware Factorization Machine for CTR prediction TAMU Neural Network 10 Information-Theoretic Models TAMU Neural Network 9 Principal Component Analysis TAMU Neural Network 8 Neurodynamics TAMU Neural Network 7 Self-Organizing Maps TAMU Neural Network 6 Deep Learning Overview TAMU Neural Network 5 Radial-Basis Function Networks TAMU Neural Network 4 Multi-Layer Perceptrons TAMU Neural Network 3 Single-Layer Perceptrons Princeton Algorithms P1W6 Hash Tables & Symbol Table Applications Stanford ML 11 Application Example Photo OCR Stanford ML 10 Large Scale Machine Learning Stanford ML 9 Anomaly Detection and Recommender Systems Stanford ML 8 Clustering & Principal Component Analysis Princeton Algorithms P1W5 Balanced Search Trees TAMU Neural Network 2 Learning Processes TAMU Neural Network 1 Introduction Stanford ML 7 Support Vector Machine Stanford ML 6 Evaluate Algorithms Princeton Algorithms P1W4 Priority Queues and Symbol Tables Stanford ML 5 Neural Networks Learning Princeton Algorithms P1W3 Mergesort and Quicksort Stanford ML 4 Neural Networks Basics Princeton Algorithms P1W2 Stack and Queue, Basic Sorts Stanford ML 3 Classification Problems Stanford ML 2 Multivariate Regression and Normal Equation Princeton Algorithms P1W1 Union and Find Stanford ML 1 Introduction and Parameter Learning

Ruby practice 1

2016-04-26

Why Homework?

These problems are excellent for ruby learning and is homework for some course, like CSCE606 at Texas A&M University.

And one good way to get quick start with a language is:

  • Read documents quickly to get familiar with basic grammar
  • Then code, code and code

If you can find a good problem series, then life will become easier. Here I post some ruby homework which I think is pretty beneficial for you study on ruby and rails.
So let’s go and write some code.
It maybe hard at first. But don’t give up, just go to Google and Stack Overflow

Q1: Palindrome?

Write a method that determines whether a given word or phrase is a palindrome, that is, it reads the same backwards as forwards, ignoring case, punctuation, and nonword characters. (characters that Ruby regexps would treat as nonword characters, that is, as boundaries between words). Your solution should not use any iteration. The rubular.com may be helpful in developing appropriate Ruby regular expressions. Methods you might find useful include: String#downcase, String#gsub and String#reverse. Suggestion: Use method chaining to make your code look more beautiful. Examples:

palindrome?("A man, a plan, a canal -- Panama")  #=> true
palindrome?("Madam, I'm Adam!")  # => true
palindrome?("Abracadabra")  # => false (nil is also ok)
def palindrome?(string)
 # your code here
end

Example Code

#!/usr/bin/env ruby
# encoding: utf-8
#Run this program and enter the word or phrase you 
#wanna test, you will see the result!

def palindrome?
	print "Enter here: "
	text = gets.chomp.downcase.gsub(/[\W|_]/,"")
	
	if text == text.reverse
		puts "Palindrome? #{true}" 
	else
		puts "Palindrome? #{false}"
	end
end

Q2: Count Words

Given a string of input, return a hash whose keys are words in the string and whose values are the number of times each word appears. Do not use for-loops. Iterators such as each are permitted. Nonwords should be ignored. Case should not matter. A word is defined as a string of characters between word boundaries. (“\b” in a Ruby regexp means matches word boundaries). Example:

count_words("A man, a plan, a canal -- Panama")
# => {'a' => 3, 'man' => 1, 'canal' => 1, 'panama' => 1, 'plan' => 1}
count_words "Doo bee doo bee doo"  # => {'doo' => 3, 'bee' => 2}
def count_words(string)
 # your code here
end

Example Code

#!/usr/bin/env ruby
# encoding: utf-8

# Used to count the times each word appear in a string
def count_words
	print "Enter your string: "
	words = gets.chomp.scan(/\b[a-z]+/)
	# or use this 
	# string = gets.chomp.downcase.gsub(/\W*$/,"")
	# words = string.split(/\b\W+\b/) # put each word in an Array
	dict = Hash.new 
	words.each do |word|
		if dict.has_key?(word)
			dict[word] += 1
		else
			dict[word] = 1
		end		
	end
	return dict
end

Q3: Rock Paper Scissors

In a game of rock-paper-scissors, each player chooses to play Rock (R), Paper (P), or Scissors (S). The rules are: Rock beats Scissors (R>S), Scissors beats Paper (S>P), but Paper beats Rock (P>R). A rock-paper-scissors game is encoded as a list, where each list element is a two-element list that encodes a player’s name and a player’s strategy.

[ [ "Kristen", "P" ], [ "Pam", "S" ] ]
# returns the list ["Pam", "S"] wins since S>P

Write a method rps_game_winner that takes a two-element list and behaves as follows:

  • If the number of players is not equal to 2, raise WrongNumberOfPlayersError.
  • If either player’s strategy is something other than “R”, “P” or “S” (case-insensitive), raise NoSuchStrategyError.
  • Otherwise, return the name and strategy of the winning player. If both players use the same strategy, the first player is the winner.

Here is some code scaffolding:

class WrongNumberOfPlayersError < StandardError 
end
class NoSuchStrategyError < StandardError
end
def rps_game_winner(game)
    raise WrongNumberOfPlayersError unless game.length == 2
    # your code here
end

Example Code

#!/usr/bin/env ruby
# encoding: utf-8

class WrongNumberOfPlayersError < StandardError ;end
class NoSuchStrategyError < StandardError ;end

def rps_game_winner(list)
	# check num of players
	raise WrongNumberOfPlayersError unless list.length == 2
	# check strategy
	list.each do |temp|
		raise NoSuchStrategyError unless ['r','p','s'].include?(temp[1].downcase)
	end

	strategy_1 = list[0][1].downcase
	strategy_2 = list[1][1].downcase

	case [strategy_1,strategy_2]
	when ['r','p'],['p','s'],['s','r'] #the latter one wins
		flag = 1
	else
		flag = 0 # include tie, the former one wins
	end
	return list[flag]
end

if __FILE__ == $0
	#list = [["Kristen","R"],["Pam","S"]] # enter strategies here
	#list = [["Kristen","R"],["Pam","S"],["Kaihatu",'P']]
	list = [["Kristen","R"], ["Pam","S"]]
	print rps_game_winner(list)
end

Creative Commons License
Melon blog is created by melonskin. This work is licensed under a Creative Commons Attribution-NonCommercial 4.0 International License.
© 2016-2024. All rights reserved by melonskin. Powered by Jekyll.