Home
Preface
Chapter Solutions
Programming Examples
Homework Problems
Homework Solutions MEA's
Search Useful Links

Programming Examples

Chapter 5 Programming Examples

Finding Maximum output using Arrays
1  #! /usr/bin/ruby
2  arr = Array.new
3  arr[0] = 73
4  arr[1] = 98
5  arr[2] = 86
6  arr[3] = 61
7  arr[4] = 96
8  i = 0
9  max = 0
10 while  (i < arr.size)
11  	 if (arr[i] > max)
12		max = arr[i]
13	end
14    i = i + 1
15 end
16 puts "Max == > "+max.to_s


 
 
Selection Sorting
1  #! /usr/bin/ruby
2  arr = Array.new
3  arr[0] = 73
4  arr[1] = 98
5  arr[2] = 86
6  arr[3] = 61
7  arr[4] = 96
8
9  # lets find the largest value and sink it to the bottom
10  i = 1
11  j = 0
12  bottom = arr.size - 1
13  while (bottom > 0)
14  # start off the max being the first element in the array
15	   max = arr[0]
16	   maxPos = 0
17         i = 1
18	   # lets see if there is a larger element  
19         while  (i <= bottom)
20		if (arr[i] > max)
21			max = arr[i]
22			maxPos = i
23		end
24         i = i + 1
25	   end
26
27 # now swap the next highest value down to the bottom 
28 # Note some ties will be swapped 
29	   if (maxPos < bottom)
30		temp = arr[bottom]
31		arr[bottom] = arr[maxPos]
32		arr[maxPos] = temp
33	   end
34	bottom = bottom - 1
35 end
36
37 puts "Sorted Array"
38 i = 0
39 while (i < arr.size)
40	   puts ("arr["+i.to_s+"] ==> "+arr[i].to_s)
41	   i = i + 1 
42 end
43


 
 
Printing a Tic-Tac-Toe Board
1  #! /usr/bin/ruby
2  arr = Array.new (3,Array.new(3))
3  arr[0] = ["x","x","x"]
4  arr[1] = ["x","o","x"]
5  arr[2] = ["x","x","x"]
6  # now lets print the board largest value and sink it puts  "Tic Tac Toe Board"
7  for i in 0..2
8	currentRow = A[i]
9	for j in 0..2
10		print currentRow[j]+' '
11	end
12	print "\n"
13 end



 
 
Breaking the Sequence: Arrays are consecutively numbered lists with the use of nil
1  #! /usr/bin/ruby
2  arr = Array.new
3  arr[1] = "Value 1"
4  arr[4] = "Value 2"
5  i = 0
6  puts "Array size is: " + arr.size.to_s
7  while  (i < arr.size)
8	puts "Element #" + i.to_s +" is: " + arr[i].to_s
9       i = i + 1
10 end




 
 
Using Hashes
1  #! /usr/bin/ruby
2  arr = Hash.new
3  arr['Hank']  = [ 98, 95, 93, 96 ]
4  arr['Susan'] = [ 74, 90, 84, 92 ]
5  arr['Jane']  = [ 72, 87, 68, 54 ]