Sie sind auf Seite 1von 5

//Quianzon, Janelle V. //SEM2 /Wednesday 6:00 9:00 PM/4ITE //December 10, 2012 7.8 1.

. Prepare and test a method entitled square that returns the square of its single parameter. def square(int sq) { sq * sq } n1 = 9 n2 = 5 println 'The square root of ' +n1+ ' is: ' +square(n1) println 'The square root of ' +n2+ ' is: ' +square(n2) RESULT:

3. Write and test a method to determine whether a given time of day is before another. Each time is represented by a triple of the form 11, 59, AM, or 1, 15, PM. def compareDate(h1,m1,d1,h2,m2,d2) { if (d1=="AM" && d2=="PM") return true else if(d1 == 'AM' && d2 == 'AM' || d1 == 'PM' && d2 == 'PM') { if(h1==h2) { if(m1<m2) return true else return false

} else if(h1<h2) return true else return false } else return false } def h1 = 10 def m1 = 23 def d1 = "AM" def h2 = 11 def m2 = 23 def d2 = "AM"

if(compareDate(h1,m1,d1,h2,m2,d2)) println h1+ ':' +m1 + d1+ ' is before ' +h2+ ':' +m2 + d2 else println h1+ ':' +m1 + d1+ ' is not before ' +h2+ ':' + m2 + d2 RESULT:

def h1 = 10 def m1 = 23 def d1 = "PM" def h2 = 11 def m2 = 23 def d2 = "AM"

4. The values 1, 2, 4, 8, 16, ... are powers of the value 2. First, develop a method isEven that determines whether its single integer parameter is an even value. Then, using isEven, develop a recursive method isPowerOfTwo that determines if its single parameter is a power of 2. def isEven(num) { if (num%2==0) return true else return false } def isPowerOfTwo(num) { if (num == 0) return true else if (num==1 && isEven(num)) isPowerOfTwo(num/2) else return false } def num = 20 if (isEven(num)) println num+ " is even" else

println num+ " is not even" if (isPowerOfTwo(num)) println num+ " is a power of two" else println num+ " is not a power of two" RESULT:

Def num = 8

13. Develop a method entitled explode that transforms a string into a List of Strings of size one. The method signature is: def explode(str) { ... }

Now, develop the complementary method implode, which accepts a list of Strings and concatenates them into a single String: def implode(strList) { ... } Using these two methods, develop the method reverseString for reversing the characters of a String parameter: def reverseString(str) { ... } Finally, develop the method isPalindrome to return the boolean true if the single String parameter is palindromic, that is, reads the same forward and backward: def isPalindrome(str) { .. }

15. The greatest common divisor of two integers can be determined from Euclids algorithm. It is defined recursively as: gcd(n, m) = n if n == m gcd(n, m) = gcd(n, m n) if n < m gcd(n, m) = gcd(n m, m) otherwise Implement a method to realize this and show that gcd(18, 27) is 9. def gcd(n,m) { if (m<n && n%m==0) return m else if (n<m) return gcd(m,n) else return gcd(m,n%m) }

def n = 18 def m = 27

println 'GCD of ' +n+ ' and ' +m+ ' is ' +gcd(n,m) RESULT:

Das könnte Ihnen auch gefallen