Solved Problems

Output a string to the console

Write the string "Hello World!" to STDOUT
groovy
println "Hello World!"

Retrieve a string containing ampersands from the variables in a url

My PHP script first does a query to obtain customer info for a form. The form has first name and last name fields among others. The customer has put entries such as "Ron & Jean" in the first name field in the database. Then the edit form script is called with variables such as

"http://myserver.com/custinfo/edit.php?mode=view&fname=Ron & Jean&lname=Smith".

The script variable for first name $_REQUEST['firstname'] never gets beyond the "Ron" value because of the ampersand in the data.

I have tried various functions like urldecode but all to no avail. I even tried encoding the url before the view screen is painted so that the url looks like "http://myserver/custinfo/edit.php?mode=view&fname="Ronxxnbsp;xxamp;xxnbsp;Jean"&lname=SMITH". (sorry I had to add the xx to replace the ampersand or it didn't display meaningful url contents the browser sees.)

Of course this fails for the same reasons. What is a better approach?
groovy
// Given the nature of the question text, I am assuming the question
// is how to produce a application/x-www-form-urlencoded compliant string

def basename = 'http://somedomain.com/somebase/'
def parameter = 'Bart & Lisa'
// equivalent to php
println basename + URLEncoder.encode(parameter)
// recommended approach is to specify encoding
println basename + URLEncoder.encode(parameter, "UTF-8")

string-wrap

Wrap the string "The quick brown fox jumps over the lazy dog. " repeated ten times to a max width of 78 chars, starting each line with "> "

Expected output:
> The quick brown fox jumps over the lazy dog. The quick brown fox jumps over t
> he lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox
> jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The qui
> ck brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy
> dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps o
> ver the lazy dog. The quick brown fox jumps over the lazy dog.
groovy
'The quick brown fox jumps over the lazy dog. '.multiply(10).split('(?<=\\G.{76})').each{println '> ' + it}
st = "The quick brown fox jumps over the lazy dog. " * 10
width = 76
while(st){
(first, st) = st.length() > width? [st[0..width], st[(width+1)..-1].trim()] : [st, null]
println "> $first"
}

write a recursive c function to compute gcd(x,y).

groovy
def gcd(x,y) {
y ? gcd(y, x%y) : y
}

Random Function trhows the same number in SoapUI

Hi,
I'm a Tester but a little bit involved in technical tests, currently I need to send different information each time that a request is sent in SoapUI, I inserted a Groovy Scrpt task on my test in order to genereate new values.

Based on your Random code from the link http://langref.org/groovy/numbers
have created the following lines:

random = new Random(12345)
ixRandom =(1..5).collect {random.nextInt(20-1)+1}
log.info(ixRandom[0])
log.info(ixRandom[1])
log.info(ixRandom[2])
log.info(ixRandom[3])
log.info(ixRandom[4])

And got this same result each time I run it:
Thu Nov 08 07:57:41 PST 2012:INFO:12
Thu Nov 08 07:57:41 PST 2012:INFO:2
Thu Nov 08 07:57:41 PST 2012:INFO:14
Thu Nov 08 07:57:41 PST 2012:INFO:15
Thu Nov 08 07:57:41 PST 2012:INFO:5


QUESTION: what need to release the memory in order to receive new numbers generated by the random function?
- have used ixRandom.clear() without any success.

Please help me out!


Although I switch the seed back and forward from
ixRandom =(1..5).collect {random.nextInt(20-1)+1}
to
ixRandom =(1..5).collect {random.nextInt(21-1)+1}

got the same results over and over!


Really appreciate your time

Alfonso
groovy
def ixRandom =(1..5).collect {new Random().nextInt(20-1)+1}
println(ixRandom[0])
println(ixRandom[1])
println(ixRandom[2])
println(ixRandom[3])
println(ixRandom[4])

Define a string containing special characters

Define the literal string "\#{'}${"}/"
groovy
special = "\\#{'}\${\"}/"
special = '\\#{\'}${"}/'
special = /\#{'}${'$'}{"}\//
assert '42'.isNumber()

Define a multiline string

Define the string:
"This
Is
A
Multiline
String"
groovy
def text =
"""This
Is
A
Multiline
String"""
def text = "This\nIs\nA\nMultiline\nString"

Define a string containing variables and expressions

Given variables a=3 and b=4 output "3+4=7"
groovy
println "$a+$b=${a+b}"
printf "%d+%d=%d\n", a, b, a + b

Reverse the characters in a string

Given the string "reverse me", produce the string "em esrever"
groovy
reversed = "reverse me".reverse()

Reverse the words in a string

Given the string "This is a end, my only friend!", produce the string "friend! only my end, the is This"
groovy
reversed = "This is the end, my only friend!".split().reverse().join(' ')
reversed = "This is the end, my only friend!".tokenize(' ').reverse().join(' ')
def revdelim(c, s) { StringUtils.reverseDelimited(s, c) }
revwords = this.&revdelim.curry(" " as char)
reversed = revwords("This is the end, my only friend!")
reversed = StringUtils.reverseDelimited("This is the end, my only friend!", " " as char)

Text wrapping

Wrap the string "The quick brown fox jumps over the lazy dog. " repeated ten times to a max width of 78 chars, starting each line with "> ", yielding this result:

> The quick brown fox jumps over the lazy dog. The quick brown fox jumps
> over the lazy dog. The quick brown fox jumps over the lazy dog. The
> quick brown fox jumps over the lazy dog. The quick brown fox jumps
> over the lazy dog. The quick brown fox jumps over the lazy dog. The
> quick brown fox jumps over the lazy dog. The quick brown fox jumps
> over the lazy dog. The quick brown fox jumps over the lazy dog. The
> quick brown fox jumps over the lazy dog.
groovy
// no built-in fill, define one using brute force approach
def fill(text, width=80, prefix='') {
width = width - prefix.size()
def out = []
List words = text.replaceAll("\n", " ").split(" ")
while (words) {
def line = ''
while (words) {
if (line.size() + words[0].size() + 1 > width) break
if (line) line += ' '
line += words[0]
words = words.tail()
}
out += prefix + line
}
out.join("\n")
}
println fill('The quick brown fox jumps over the lazy dog. ' * 10, 72, '> ')
// no built-in fill, define one using lastIndexOf
def fill(text, width=80, prefix='') {
def out = ''
def remaining = text.replaceAll("\n", " ")
while (remaining) {
def next = prefix + remaining
def found = next.lastIndexOf(' ', width)
if (found == -1) remaining = ''
else {
remaining = next.substring(found + 1)
next = next[0..found]
}
out += next + '\n'
}
out
}
println fill('The quick brown fox jumps over the lazy dog. ' * 10, 72, '> ')
prefix = '> '
input = 'The quick brown fox jumps over the lazy dog. '
wrap(input * 10, 72 - prefix.size()).eachLine{ println prefix + it }

Remove leading and trailing whitespace from a string

Given the string "  hello    " return the string "hello".
groovy
assert "hello" == " hello ".trim()

Simple substitution cipher

Take a string and return the ROT13 and ROT47 (Check Wikipedia) version of the string.
For example:
String is: Hello World #123
ROT13 returns: Uryyb Jbeyq #123
ROT47 returns: w6==@ (@C=5 R`ab
groovy
char rot13(s) {
char c = s
switch(c) {
case 'A'..'M': case 'a'..'m': return c+13
case 'N'..'Z': case 'n'..'z': return c-13
default : return c
}
}
String.metaClass.rot13 = {
delegate.collect(this.&rot13).join()
}

from = '!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~'
to = 'PQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNO'
String.metaClass.rot47 = {
delegate.collect{ int found = from.indexOf(it); found < 0 ? it : to[found] }.join()
}

assert 'Hello World #123'.rot13() == 'Uryyb Jbeyq #123'
assert 'Hello World #123'.rot47() == 'w6==@ (@C=5 R`ab'

Make a string uppercase

Transform "Space Monkey" into "SPACE MONKEY"
groovy
println "Space Monkey".toUpperCase()
def lower = 'Space Monkey'
assert lower.toUpperCase() == 'SPACE MONKEY'

Make a string lowercase

Transform "Caps ARE overRated" into "caps are overrated"
groovy
println "Caps ARE overRated".toLowerCase()

Capitalise the first letter of each word

Transform "man OF stEEL" into "Man Of Steel"
groovy
def capitalize(s) { s[0].toUpperCase() + s[1..-1].toLowerCase() }
caps = "man OF stEEL".replaceAll(/\w+/) { w -> capitalize(w) }
caps = "man OF stEEL".replaceAll(/\w+/) { w -> StringUtils.capitalize(w.toLowerCase()) }
caps = WordUtils.capitalizeFully("man OF stEEL")
"man OF stEEL".toLowerCase().tokenize().collect { it.capitalize() }.join(' ')
"man OF stEEL".toLowerCase().capitalize().replaceAll(/( +)([^ ]+)/, { "${it[0]}${it[1].toLowerCase().capitalize()}" })

Find the distance between two points

groovy
distance = distance(x1, y1, x2, y2)
distance = sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1))

Zero pad a number

Given the number 42, pad it to 8 characters like 00000042
groovy
formatted = new DecimalFormat('00000000').format(42)
formatted = 42.toString().padLeft(8, '0')
// to stdout
printf "%08d\n", 42
// to a string
formatted = sprintf("%08d", 42)
formatted = String.format("%08d", 42)

Right Space pad a number

Given the number 1024 right pad it to 6 characters "1024  "
groovy
println 1024.toString().padRight(6)
formatted = sprintf("%-6d", 1024)

Format a decimal number

Format the number 7/8 as a decimal with 2 places: 0.88
groovy
def result = 7/8
println result.round(new MathContext(2))
def result = 7/8
printf "%.2g", result
new Double(7/8).round(2)

Left Space pad a number

Given the number 73 left pad it to 10 characters "        73"
groovy
println 73.toString().padLeft(10)
printf "%10d\n", 73

Generate a random integer in a given range

Produce a random integer between 100 and 200 inclusive
groovy
random = new Random()
randomInt = random.nextInt(200-100+1)+100

Generate a repeatable random number sequence

Initialise a random number generator with a seed and generate five decimal values. Reset the seed and produce the same values.
groovy
random = new Random(12345)
orig = (1..5).collect { random.nextInt(200-100+1)+100 }
random = new Random(12345)
repeat = (1..5).collect { random.nextInt(200-100+1)+100 }
assert orig == repeat

Check if a string matches a regular expression

Display "ok" if "Hello" matches /[A-Z][a-z]+/
groovy
if ("Hello" =~ /[A-Z][a-z]+/) println 'ok'
if ("Hello".find(/[A-Z][a-z]+/)) println 'ok'
// with precompiled regex
def regex = ~/[A-Z][a-z]+/
if ("Hello".find(regex)) println 'ok'
// with precompiled regex
def regex = ~/[A-Z][a-z]+/
if ("Hello".matches(regex)) println 'ok'
if ("Hello".matches("[A-Z][a-z]+")) println 'ok'

Check if a string matches with groups

Display "two" if "one two three" matches /one (.*) three/
groovy
matcher = ("one two three" =~ /one (.*) three/)
if (matcher) println matcher[0][1]
match = "one two three".find("one (.*) three") { it[1] }
if (match) println match

Check if a string contains a match to a regular expression

Display "ok" if "abc 123 @#$" matches /\d+/
groovy
if ('abc 123 @#$' =~ /\d+/) println 'ok'
if ('abc 123 @#$'.find(/\d+/)) println 'ok'

Loop through a string matching a regex and performing an action for each match

Create a list [fish1,cow3,boat4] when matching "(fish):1 sausage (cow):3 tree (boat):4" with regex /\((\w+)\):(\d+)/
groovy
list = (text =~ /\((\w+)\):(\d+)/).collect{ it[1] + it[2] }
list = []
text.eachMatch(/\((\w+)\):(\d+)/){
list << it[1] + it[2]
}
list = []
text.eachMatch(/\((\w+)\):(\d+)/){ m, name, number ->
list << "$name$number"
}
list = (text =~ /\((\w+)\):(\d+)/).collect{ all, name, num -> "$name$num" }
list = text.findAll(regex){ _, name, num -> "$name$num" }
list = text.findAll(regex){ it[1] + it[2] }

Replace the first regex match in a string with a static string

Transform "Red Green Blue" into "R*d Green Blue" by replacing /e/ with "*"
groovy
replaced = "Red Green Blue".replaceFirst("e", "*")

Replace all regex matches in a string with a static string

Transform "She sells sea shells" into "She X X shells" by replacing /se\w+/ with "X"
groovy
replaced = text.replaceAll(/se\w+/,"X")

Replace all regex matches in a string with a dynamic string

Transform "The {Quick} Brown {Fox}" into "The kciuQ Brown xoF" by reversing words in braces using the regex /\{(\w+)\}/.
groovy
replaced = "The {Quick} Brown {Fox}".replaceAll(/\{(\w+)\}/, { full, word -> word.reverse() } )

Define an empty list

Assign the variable "list" to a list with no elements
groovy
list = []
// if a special kind of list is required
list = new LinkedList() // java style
LinkedList list = [] // statically typed
// using 'as' operator
list = [] as java.util.concurrent.CopyOnWriteArrayList

Define a static list

Define the list [One, Two, Three, Four, Five]
groovy
list = ['One', 'Two', 'Three', 'Four', 'Five']
// other variations
List<String> numbers1 = ['One', 'Two', 'Three', 'Four', 'Five']
String[] numbers2 = ['One', 'Two', 'Three', 'Four', 'Five']
numbers3 = new LinkedList(['One', 'Two', 'Three', 'Four', 'Five'])
numbers4 = ['One', 'Two', 'Three', 'Four', 'Five'] as Stack // Groovy 1.6+

Join the elements of a list, separated by commas

Given the list [Apple, Banana, Carrot] produce "Apple, Banana, Carrot"
groovy
string = fruit.join(', ')
string = fruit.toString()[1..-2]

Join the elements of a list, in correct english

Create a function join that takes a List and produces a string containing an english language concatenation of the list. It should work with the following examples:
join([Apple, Banana, Carrot]) = "Apple, Banana, and Carrot"
join([One, Two]) = "One and Two"
join([Lonely]) = "Lonely"
join([]) = ""
groovy
def join(list) {
if (!list) return ''
switch(list.size()) {
case 1:
return list[0]
case 2:
return list.join(' and ')
default:
return list[0..-2].join(', ') + ', and ' + list[-1]
}
}
ArrayList.metaClass.joinEng = { ->
def closureMap = [0: { -> delegate.join(' and ')}, 1 : {-> delegate.join(' and ')}].withDefault { k -> { -> delegate[0..-2].join(', ') + ', and ' + delegate[-1] } }
if (delegate.size()) closureMap[delegate.size()-1].call()
else ""
}

assert ["a"].joinEng() == "a"
assert ["a", "b"].joinEng() == "a and b"
assert ["a", "b", "c"].joinEng() == "a, b, and c"
assert [].joinEng() == ""
def join(list) {
list.join(', ').reverse().replaceFirst(/,/, "dna ").reverse()
}

Produce the combinations from two lists

Given two lists, produce the list of tuples formed by taking the combinations from the individual lists. E.g. given the letters ["a", "b", "c"] and the numbers [4, 5], produce the list: [["a", 4], ["b", 4], ["c", 4], ["a", 5], ["b", 5], ["c", 5]]
groovy
letters = ['a', 'b', 'c']
numbers = [4, 5]
combos = [letters, numbers].combinations()

From a List Produce a List of Duplicate Entries

Taking a list:
["andrew", "bob", "chris", "bob"]

Write the code to produce a list of duplicates in the list:
["bob"]
groovy
def input = ["andrew", "bob", "chris", "bob"]

def output = input.findAll{input.count(it)>1}.unique()

assert output == ["bob"]

Fetch an element of a list by index

Given the list [One, Two, Three, Four, Five], fetch the third element ('Three')
groovy
list = ['One', 'Two', 'Three', 'Four', 'Five']
result = list[2] // index starts at 0

Fetch the last element of a list

Given the list [Red, Green, Blue], access the last element ('Blue')
groovy
list = ['Red', 'Green', 'Blue']
result = list[-1]
list = ['Red', 'Green', 'Blue']
result = list.last()

Find the common items in two lists

Given two lists, find the common items. E.g. given beans = ['broad', 'mung', 'black', 'red', 'white'] and colors = ['black', 'red', 'blue', 'green'], what are the bean varieties that are also color names?
groovy
beans = ['broad', 'mung', 'black', 'red', 'white']
colors = ['black', 'red', 'blue', 'green']
common = beans.intersect(colors)
assert common == ['black', 'red']

Display the unique items in a list

Display the unique items in a list, e.g. given ages = [18, 16, 17, 18, 16, 19, 14, 17, 19, 18], display the unique elements, i.e. with duplicates removed.
groovy
ages = [18, 16, 17, 18, 16, 19, 14, 17, 19, 18]
println ages.unique()
ages = [18, 16, 17, 18, 16, 19, 14, 17, 19, 18]
unique = ages as Set
println unique

Remove an element from a list by index

Given the list [Apple, Banana, Carrot], remove the first element to produce the list [Banana, Carrot]
groovy
// to produce a new list
newlist = list.tail() // for 'Apple' at start
newlist = list - 'Apple' // for 'Apple' anywhere
// mutate original list
list.remove(0)

Remove the last element of a list

groovy
list = ['Apple', 'Banana', 'Carrot']
// to produce a new list
newlist = list[0,1]
// to modify original list
list.remove(2)
list = ['Apple', 'Banana', 'Carrot']

result = list[0,-2]

//or using ranges
result = list[0..-2]

Rotate a list

Given a list ["apple", "orange", "grapes", "bananas"], rotate it by removing the first item and placing it on the end to yield ["orange", "grapes", "bananas", "apple"]
groovy
first = items.head()
items = items.tail() + first
items = items[1..-1] + items[0]
items = items + items.remove(0)

Gather together corresponding elements from multiple lists

Given several lists, gather together the first element from every list, the second element from every list, and so on for all corresponding index values in the lists. E.g. for these three lists, first = ['Bruce', 'Tommy Lee', 'Bruce'], last = ['Willis', 'Jones', 'Lee'], years = [1955, 1946, 1940] the result should produce 3 actors. The middle actor should be Tommy Lee Jones.
groovy
first = ['Bruce', 'Tommy Lee', 'Bruce']
last = ['Willis', 'Jones', 'Lee']
years = [1955, 1946, 1940]
actors = [first, last, years].transpose()
assert actors.size() == 3
assert actors[1] == ['Tommy Lee', 'Jones', 1946]

List Combinations

Given two source lists (or sets), generate a list (or set) of all the pairs derived by combining elements from the individual lists (sets). E.g. given suites = ['H', 'D', 'C', 'S'] and faces = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'], generate the deck of 52 cards, confirm the deck size and check it contains an expected card, say 'Ace of Hearts'.
groovy
faces = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']
suites = ['H', 'D', 'C', 'S']
deck = [faces, suites].combinations()
assert deck.size() == 52
assert ['A', 'H'] in deck

Perform an operation on every item of a list

Perform an operation on every item of a list, e.g.
for the list ["ox", "cat", "deer", "whale"] calculate
the list of sizes of the strings, e.g. [2, 3, 4, 5]
groovy
animals = ["ox", "cat", "deer", "whale"]
assert animals*.size() == [2, 3, 4, 5]
// or somewhat more verbosely, using collect
animals = ["ox", "cat", "deer", "whale"]
assert animals.collect { it.size() } == [2, 3, 4, 5]

Split a list of things into numbers and non-numbers

Given a list that might contain e.g. a string, an integer, a float and a date,
split the list into numbers and non-numbers.
groovy
now = new Date()
things = ["hello", 25, 3.14, now]
(numbers, others) = things.split{ it instanceof Number }
assert numbers == [25, 3.14]
assert others == ["hello", now]

Test if a condition holds for all items of a list

Given a list, test if a certain logical condition (i.e. predicate) holds for all items of the list.
groovy
[2,3,4].every{it > 1}

Test if a condition holds for any items of a list

Given a list, test if a certain logical condition (i.e. predicate) holds for any items of the list.
groovy
[2,3,4].any{it > 3}

Define an empty map

groovy
def map = [:]
Map map = new HashMap();

Define an unmodifiable empty map

groovy
empty = Collections.EMPTY_MAP
map = [:].asImmutable()
def empty = MapUtils.EMPTY_SORTED_MAP
def empty = ImmutableMap.of()

Define an initial map

Define the map {circle:1, triangle:3, square:4}
groovy
shapes = [circle:1, triangle:3, square:4]
// if you require a specific type of map ...
LinkedHashMap shapes1 = [circle:1, triangle:3, square:4]
Properties shapes2 = [circle:1, triangle:3, square:4]
TreeMap shapes3 = [circle:1, triangle:3, square:4]
shapes4 = [circle:1, triangle:3, square:4] as ConcurrentHashMap // as variation

Check if a key exists in a map

Given a map pets {joe:cat,mary:turtle,bill:canary} print "ok" if an pet exists for "mary"
groovy
pets = [joe:'cat', mary:'turtle', bill:'canary']
if(pets.containsKey('mary')) println 'ok'
pets = [joe:'cat', mary:'turtle', bill:'canary']
if(pets.mary) println 'ok'

Retrieve a value from a map

Given a map pets {joe:cat,mary:turtle,bill:canary} print the pet for "joe" ("cat")
groovy
pets = [joe:'cat', mary:'turtle', bill:'canary']
assert pets['joe'] == 'cat'
assert pets.joe == 'cat'

Add an entry to a map

Given an empty pets map, add the mapping from "rob" to "dog"
groovy
pets['rob'] = 'dog'
pets.rob = 'dog'
pets.put('rob', 'dog')

Remove an entry from a map

Given a map pets {joe:cat,mary:turtle,bill:canary} remove the mapping for "bill" and print "canary"
groovy
pets = [joe:'cat', mary:'turtle', bill:'canary']
println pets.remove('bill')

Check if all given keys exists in a map

Given a map pets {joe:cat,mary:turtle,bill:canary} print "ok" if an pet exists for "joe" and "mary"
groovy
def pets = [joe: 'cat', mary: 'turtle', bill: 'canary']
if (pets.keySet().containsAll(['joe', 'mary'])) println "ok"

Create a histogram map from a list

Given the list [a,b,a,c,b,b], produce a map {a:2, b:3, c:1} which contains the count of each unique item in the list
groovy
histogram = [:]
list.each { item ->
if (!histogram.containsKey(item)) histogram[item] = 0
histogram[item]++
}
histogram = [:]
list.each { histogram[it] = (histogram[it] ?: 0) + 1 }
def histogram = [:].withDefault{ 0 }
list.each { histogram[it] += 1 }
histogram
list.inject([:].withDefault{ 0 }) { map, nr -> map[nr] += 1; map}

Categorise a list

Given the list [one, two, three, four, five] produce a map {3:[one, two], 4:[four, five], 5:[three]} which sorts elements into map entries based on their length
groovy
map = ['one', 'two', 'three', 'four', 'five'].groupBy{ it.size() }

Perform an action if a condition is true (IF .. THEN)

Given a variable name, if the value is "Bob", display the string "Hello, Bob!". Perform no action if the name is not equal.
groovy
if (name=='Bob')
println "Hello, Bob!"

Perform different actions depending on a boolean condition (IF .. THEN .. ELSE)

Given a variable age, if the value is greater than 42 display "You are old", otherwise display "You are young"
groovy
if (age > 42)
println "You are old"
else
println "You are young"
println "You are " + (age > 42 ? "old" : "young")

Perform different actions depending on several boolean conditions (IF .. THEN .. ELSIF .. ELSE)

groovy
if (age > 84)
println "You are really ancient"
else if (age > 30)
println "You are middle-aged"
else
println "You are young"

Replacing a conditional with many branches with a switch/case statement

Many languages support more compact forms of branching than just if ... then ... else such as switch or case or match. Use such a form to add an appropriate placing suffix to the numbers 1..40, e.g. 1st, 2nd, 3rd, 4th, ..., 11th, 12th, ... 39th, 40th
groovy
def suffix(n) {
switch(n) {
case { n % 100 in 4..20 } : return 'th'
case { n % 10 == 1 } : return 'st'
case { n % 10 == 2 } : return 'nd'
case { n % 10 == 3 } : return 'rd'
default : return 'th'
}
}
(1..40).each { n ->
println "$n${suffix(n)}"
}

Perform an action multiple times based on a boolean condition, checked before the first action (WHILE .. DO)

Starting with a variable x=1, Print the sequence "1,2,4,8,16,32,64,128," by doubling x and checking that x is less than 150.
groovy
x = 1
while (x < 150) {
print x + ","
x *= 2
}
println()

Perform an action multiple times based on a boolean condition, checked after the first action (DO .. WHILE)

Simulate rolling a die until you get a six. Produce random numbers, printing them until a six is rolled. An example output might be "4,2,1,2,6"
groovy
// Groovy has no do..while; use a normal while
int dice = 0
while (dice != 6) {
dice = Math.random() * 6 + 1
print dice
if (dice != 6) print ','
}

Perform an action a fixed number of times (FOR)

Display the string "Hello" five times like "HelloHelloHelloHelloHello"
groovy
println "Hello" * 5
5.times { print "Hello" }; println()

Perform an action a fixed number of times with a counter

Display the string "10 .. 9 .. 8 .. 7 .. 6 .. 5 .. 4 .. 3 .. 2 .. 1 .. Liftoff!"
groovy
10.downto(1) { print it + " .. " }
println "Liftoff!"

Read the contents of a file into a string

groovy
contents = file.text

Process a file one line at a time

Open the source file to your solution and print each line in the file, prefixed by the line number, like:
1> First line of file
2> Second line of file
3> Third line of file
groovy
int count = 0
file.eachLine { line ->
println "${++count} > $line"
}
file.eachLine { line, count ->
println "${++count} > $line"
}

Write a string to a file

groovy
file.delete()
file << 'some text'
file.text = 'some text'

Append to a file

groovy
file << 'some text'

file writng and reading groovy delimitter

actually i need a file containing text as follows
srikanth,100,123,134

and this text to be written in targert file i,e an other text file as
follows
srikanth
100
123
134


all this is to be done in groovy
solution required urgentkly
groovy
new File("output.txt").withWriter{out->
new File("input.txt").text.split(",").each{
out.writeLine(it)
}
}
new File("output.txt") << new File("input.txt").text.split(",").join("\n")

Process each file in a directory

groovy
dir.eachFile{ f -> process(f) }

Process each file in a directory recursively

groovy
dir.eachFileRecurse{ f -> process(f) }

Parse a date and time from a string

Given the string "2008-05-06 13:29", parse it as a date representing 6th March, 2008 1:29:00pm in the local time zone.
groovy
def date = new SimpleDateFormat("yyy-MM-dd HH:mm").parse("2008-05-06 13:29")
def date = Date.parse("yyy-MM-dd HH:mm", "2008-05-06 13:29")

Display information about a date

Display the day of month, day of year, month name and day name of the day 8 days from now.
groovy
use (TimeCategory) {
eight_days_time = 1.week.from.now + 1.day
}
println eight_days_time[DAY_OF_MONTH]
println eight_days_time.format('d') // alternative to above
println eight_days_time[DAY_OF_YEAR]
println eight_days_time.format('MMMM')
println eight_days_time.format('EEEE')

Display a date in different locales

Display a language/locale friendly version of New Year's Day for 2009 for several languages/locales. E.g. for languages English, French, German, Italian, Dutch the output might be something like:

Thursday, January 1, 2009
jeudi 1 janvier 2009
giovedì 1 gennaio 2009
Donnerstag, 1. Januar 2009
donderdag 1 januari 2009

(Indicate in comments where possible if any language specific or operating system configuration needs to be in place.)
groovy
cal = Calendar.instance
cal.set(2009, JANUARY, 1)
[ENGLISH, FRENCH, ITALIAN, GERMAN, new Locale('nl')].each { lang ->
println getDateInstance(FULL, lang).format(cal.time)
}

// relies on Java I18N capabilities which supports many locales, see:
// http://java.sun.com/javase/technologies/core/basic/intl/
// available Locales may depend on your version of Java and/or
// operating system and/or installed fonts

Display the current date and time

Create a Date object representing the current date and time. Print it out.
If you can also do this without creating a Date object you can show that too.
groovy
println new Date()
OOP

Define a class

Declare a class named Greeter that takes a string on creation and greets using this string if you call the "greet" method.
groovy
// version using named parameters
class Greeter {
def whom
def greet() { println "Hello, $whom" }
}
new Greeter(whom:'world').greet()
// version using traditional constructor
class Greeter {
private whom
Greeter(whom) { this.whom = whom }
def greet() { println "Hello, $whom" }
}
new Greeter('world').greet()

Instantiate object with mutable state

Reimplement the Greeter class so that the 'whom' property or data member remains private but is mutable, and is provided with getter and setter methods. Invoke the setter to change the greetee, invoke 'greet', then use the getter in displaying the line, "I have just greeted {whom}.".

For example, if the greetee is changed to 'Tommy' using the setter, the 'greet' method would display:

Hello, Tommy!

The getter would then be used to display the line:

I have just greeted Tommy.
groovy
class Greeter {
def whom
def greet() { println "Hello, $whom!" }
}

greeter = new Greeter(whom:"world"); greeter.greet()

greeter.whom = 'Tommy'; greeter.greet()
println "I have just greeted $greeter.whom"

Implement Inheritance Heirarchy

Implement a Shape abstract class which will form the base of an inheritance hierarchy that models 2D geometric shapes. It will have:

* A non-mutable 'name' property or data member set by derived or descendant classes at construction time
* A 'area' method intended to be overridden by derived or descendant classes ( double precision floating point return value)
* A 'print' method (also for overriding) will display the shape's name, area, and all shape-specific values

Two derived or descendant classes will be created:
* Circle    -> Constructor requires a '
radius' argument, and a 'circumference' method to be implemented  
* Rectangle -> Constructor requires '
length' and 'breadth' arguments, and a 'perimeter' method to be implemented 

Instantiate an object of each class, and invoke each objects '
print' method to show relevant details.
groovy
abstract class Shape {
final name
Shape(name) { this.name = name }
abstract area()
abstract print()
}

class Circle extends Shape {
final radius
Circle(radius) {
super('circle')
this.radius = radius
}
def area() { Math.PI * radius * radius }
def circumference() { 2 * Math.PI * radius }
def print() {
println "I am a $name with ->"
printf 'Radius: %.2f\n', radius
printf 'Area: %.2f\n', area()
printf 'Circumference: %.2f\n', circumference()
}
}

class Rectangle extends Shape {
final length, breadth
def Rectangle(length, breadth) {
super("rectangle")
this.length = length
this.breadth = breadth
}
def area() { length * breadth }
def perimeter() { 2 * length + 2 * breadth }
def print() {
println "I am a $name with ->"
printf 'Length, Width: %.2f, %.2f\n', length, breadth
printf 'Area: %.2f\n', area()
printf 'Perimeter: %.2f\n', perimeter()
}
}

shapes = [new Circle(4.2), new Rectangle(2.7, 3.1), new Rectangle(6.2, 2.6), new Circle(17.3)]
shapes.each { shape -> shape.print() }

Implement and use an Interface

Create a Serializable interface consisting of 'save' and 'restore' methods, each of which:

* Accept a stream or handle or descriptor argument for the source or destination
* Save to destination or restore from source the properties or data members of the implementing class (restrict yourself to the primitive types 'int' and 'string')

Next, create a Person class which has 'name' and 'age' properties or data members and implements this interface. Instantiate a Person object, save it to a serial stream, and instantiate a new Person object by restoring it from the serial stream.
groovy
// Built-in functionality but with slightly different names. Showing usage:
class Person implements Serializable { String name; int age }
p1 = new Person(name:'John', age:21)
p2 = null
output = new ByteArrayOutputStream() // or FileOutputStream, etc.
output.withObjectOutputStream { oos -> oos << p1 }
input = new ByteArrayInputStream(output.toByteArray())
input.withObjectInputStream(getClass().classLoader){ ois -> p2 = ois.readObject() }
assert p2.name == 'John'
assert p2.age == 21

Check your language appears on the langref.org site

Your language name should appear within the HTML found at the http://langreg.org main page.
groovy
assert new URL('http://langref.org').text.contains('groovy')

Send an email

Use library functions, classes or objects to create a short email addressed to your own email address. The subject should be, "Greetings from langref.org", and the user should be prompted for the message body, and whether to cancel or proceed with sending the email.
groovy
// numerous libraries exist, this uses ant
// needs these jars: mailapi.jar, smtp.jar, ant-javamail.jar, ant-nodeps.jar
new AntBuilder().with {
input(message:'Message to send:', addproperty:'body')
input(message:'Send email?', validargs:'y,n,Y,N', addproperty:'confirm')
condition(property:'abort') { matches(string:'${confirm}', pattern:'n|N') }
fail(if:'abort', 'Email send aborted by user')
mail(mailhost:'smtp.gmail.com', mailport:'465', ssl:'on', user:'you@gmail.com',
subject:'Greetings from langref.org', password:'your_password'){
from(address:'you@gmail.com')
to(address:'rob@langref.org')
message('${body}')
}
}
XML

Process an XML document

Given the XML Document:

<shopping>
  <item name="bread" quantity="3" price="2.50"/>
  <item name="milk" quantity="2" price="3.50"/>
</shopping>

Print out the total cost of the items, e.g. $14.50
groovy
printf '$%.2f\n', new XmlSlurper().parseText(xml).item.collect{
it.@quantity.toInteger() * it.@price.toFloat()
}.sum()

create some XML programmatically

Given the following CSV:

bread,3,2.50
milk,2,3.50

Produce the equivalent information in XML, e.g.:

<shopping>
  <item name="bread" quantity="3" price="2.50" />
  <item name="milk" quantity="2" price="3.50" />
</shopping>
groovy
b = new groovy.xml.MarkupBuilder()
b.shopping {
csv.eachLine { line ->
(n, q, p) = line.split(',')
item(name:n, quantity:q, price:p)
}
}
// Groovy equivalent of Java JAXB solution
@XmlAccessorType(NONE)
class Item {
@XmlAttribute String name
@XmlAttribute Integer quantity
@XmlAttribute Double price
}

@XmlAccessorType(NONE)
@XmlRootElement
class Shopping {
@XmlElement Set<Item> items = []
}

Shopping shopping = new Shopping()
csvtext.eachLine{ line ->
(n, q, p) = line.split(',')
shopping.items << new Item(name:n, quantity:q.toInteger(), price:p.toDouble())
}
JAXB.marshal shopping, System.out

Find all Pythagorean triangles with length or height less than or equal to 20

Pythagorean triangles are right angle triangles whose sides comply with the following equation:

a * a + b * b = c * c

where c represents the length of the hypotenuse, and a and b represent the lengths of the other two sides. Find all such triangles where a, b and c are non-zero integers with a and b less than or equal to 20. Sort your results by the size of the hypotenuse. The expected answer is:

[3, 4, 5]
[6, 8, 10]
[5, 12, 13]
[9, 12, 15]
[8, 15, 17]
[12, 16, 20]
[15, 20, 25]
groovy
Set results = []
for (x in 1..20)
for (y in x..20) {
def z = sqrt(x*x + y*y)
if (z.toInteger() == z) results << [x, y, z.toInteger()]
}
println results.sort{it[2]}.join('\n')
Set results = []
for (x in 1..20)
for (y in x..20) {
def z = sqrt(x*x + y*y)
if (z.toInteger() == z) results << [x, y, z.toInteger()]
}
println results.sort{it[2]}.join('\n')

Greatest Common Divisor

Find the largest positive integer that divides two given numbers without a remainder. For example, the GCD of 8 and 12 is 4.

groovy
static def gcd(int i, int j) {
if (Math.min(i,j)==0) return Math.max(i,j)
else return gcd(Math.min(i,j),Math.abs(i-j))
}
Fun

produces a copy of its own source code

In computing, a quine is a computer program which produces a copy of its own source code as its only output.
groovy
s="s=%s;printf s,s.inspect()";printf s,s.inspect()
evaluate s='char q=39;print"evaluate s=$q$s$q"'
s="s=%c%s%c;printf s,34,s,34";printf s,34,s,34
s='s=%c%s%1$c;printf s,39,s';printf s,39,s
printf _='printf _=%c%s%1$c,39,_',39,_

Subdivide A Problem To A Pool Of Workers (No Shared Data)

Take a hard to compute problem and split it up between multiple worker threads. In your solution, try to fully utilize available cores or processors. (I'm looking at you, Python!)

Note: In this question, there should be no need for shared state between worker threads while the problem is being solved. Only after every thread completes computation are the answers recombined into a single output.

Example:

-Input-

(In python syntax)

["ab", "we", "tfe", "aoj"]

In other words, a list of random strings.

-Output-

(In python syntax)

[ ["ab", "ba", "aa", "bb", "a", "b"], ["we", "ew", "ww", "ee", "w", "e"], ...

In other words, all possible permutations of each input string are computed.
groovy
// as per Java answer, doesn't duplicate chars from input string, i.e. no 'aa'
def ans = [].asSynchronized()
def words = ["ab", "we", "tfe", "aoj"]
def threads = []

void permutations(String prefix, String w, Set<String> permSet) {
int n = w.size()
if (!n) permSet << prefix
else n.times { i ->
permutations(prefix + w[i], w[0..<i] + w[i+1..<n], permSet)
}
}

words.each { word ->
def t = Thread.start {
def wordAns = [] as Set
for (int i = 0; i < word.size(); i++)
for (int j = i + 1; j <= word.size(); j++)
permutations("", word[i..<j], wordAns)
ans << wordAns
}
threads << t
}

threads.each{ it.join() }
println ans
// as per Java answer, doesn't duplicate chars from input string, i.e. no 'aa'
def ans = [].asSynchronized()
def words = ["ab", "we", "tfe", "aoj"]

void permutations(String prefix, String w, Set<String> permSet) {
int n = w.size()
if (!n) permSet << prefix
else n.times { i ->
permutations(prefix + w[i], w[0..<i] + w[i+1..<n], permSet)
}
}

withParallelizer {
words.eachParallel { word ->
def wordAns = [] as Set
for (int i = 0; i < word.size(); i++)
for (int j = i + 1; j <= word.size(); j++)
permutations("", word[i..<j], wordAns)
ans << wordAns
}
}

println ans

Subdivide A Problem To A Pool Of Workers (Shared Data)

Take a hard to compute problem and split it up between multiple worker threads. In your solution, try to fully utilize available cores or processors. (I'm looking at you, Python!)

Note: In this question, there should be a need for shared state between worker threads while the problem is being solved.

Example:

-Conway Game of Life-

From Wikipedia:

The universe of the Game of Life is an infinite two-dimensional orthogonal grid of square cells, each of which is in one of two possible states, live or dead. Every cell interacts with its eight neighbors, which are the cells that are directly horizontally, vertically, or diagonally adjacent. At each step in time, the following transitions occur:

1. Any live cell with fewer than two live neighbours dies, as if caused by underpopulation.
2. Any live cell with more than three live neighbours dies, as if by overcrowding.
3. Any live cell with two or three live neighbours lives on to the next generation.
4. Any dead cell with exactly three live neighbours becomes a live cell.

The initial pattern constitutes the seed of the system. The first generation is created by applying the above rules simultaneously to every cell in the seed—births and deaths happen simultaneously, and the discrete moment at which this happens is sometimes called a tick (in other words, each generation is a pure function of the one before). The rules continue to be applied repeatedly to create further generations.


--However, for our purposes, we will assign a size to the game "board": 2^k * 2^k . That is, the board should be easy to subdivide.

Notice that in this problem, at each step or "tick", each thread/process will need to share data with its neighborhood.
groovy
// some crude assumptions made for size and amount of parallelism
enum State { ALIVE, DEAD }
import static State.*

seed = '''\
* *
** **
** *
*
**
***
**
* \
'''

def computeNextGen(inboard, outboard, n) {
// crudely split into 4 chunks but could be smarter if we wanted
int half = n/2
def t1 = Thread.start { computeNextGen(inboard, outboard, n, 0, half, 0, half) }
def t2 = Thread.start { computeNextGen(inboard, outboard, n, 0, half, half, n) }
def t3 = Thread.start { computeNextGen(inboard, outboard, n, half, n, 0, half) }
def t4 = Thread.start { computeNextGen(inboard, outboard, n, half, n, half, n) }
[t1, t2, t3, t4].each{ it.join() }
}

def computeNextGen(inboard, outboard, n, minx, maxx, miny, maxy) {
for (int i = minx; i < maxx; i++)
for (int j = 0; j < maxy; j++)
if (i == 0 || i == n-1 || j == 0 || j == n-1)
outboard[i][j] = DEAD
for (int i = minx; i < maxx; i++) {
for (int j = miny; j < maxy; j++) {
if (i == 0 || i == n-1 || j == 0 || j == n-1)
continue
int count = 0
[[-1, 0, 1], [-1, 0, 1]].combinations().each{ dx, dy ->
if ((dx || dy) && inboard[i+dx][j+dy] == ALIVE) count++
}
switch(count) {
case {count == 3}:
case {inboard[i][j] == ALIVE && count == 2}:
outboard[i][j] = ALIVE; break
default:
outboard[i][j] = DEAD
}
}
}
}

void printBoard(board) {
println '--------'
println board*.collect{ it == DEAD ? ' ' : '*' }*.join().join('\n')
}

void initBoard(seed, board) {
def row = 0
seed.readLines().each { line ->
def col = 0
line.each { ch ->
board[row][col++] = ch == '*' ? ALIVE : DEAD
}
row++
}
}

def N = 8
def NUM_CYCLES = 3
def board1 = new State[N][N]
def board2 = new State[N][N]
initBoard(seed, board1)
NUM_CYCLES.times {
computeNextGen board1, board2, N
printBoard board2
computeNextGen board2, board1, N
printBoard board1
}

Create a multithreaded "Hello World"

Create a program which outputs the string "Hello World" to the console, multiple times, using separate threads or processes.

Example:

-Output-

Thread one says Hello World!
Thread two says Hello World!
Thread four says Hello World!
Thread three says Hello World!

-Notice that the threads can print in any order.
groovy
["one","two","three","four"].each { tid ->
Thread.start {
println "Thread $tid says Hello World!"
}
}
import static groovyx.gpars.Parallelizer.*
withParallelizer {
["one","two","three","four"].eachParallel {
println "Thread $it says Hello World!"
}
}

Create read/write lock on a shared resource.

Create multiple threads or processes who are either readers or writers. There should be more readers then writers.

(From Wikipedia):

Multiple readers can read the data in parallel but an exclusive lock is needed while writing the data. When a writer is writing the data, readers will be blocked until the writer is finished writing.

Example:

-Output-

Thread one says that the value is 8.
Thread three says that the value is 8.
Thread two is taking the lock.
Thread four tried to read the value, but could not.
Thread five tried to write to the value, but could not.
Thread two is changing the value to 9.
Thread two is releasing the lock.
Thread four says that the value is 9.
...

--Notice that when a needed resource is locked, a thread can set a timer and try again in the future, or wait to be notified that the resource is no longer locked.
groovy
def lock = new ReentrantLock()
Integer value = 8

20.times { i ->
if (i % 3 == 0) {
Thread.start {
if (!lock.tryLock()) {
println "Thread " + i + " tried to write the value, but could not."
lock.lock()
}
value = (int) (Math.random() * 10)
println "Thread " + i + " is changing the value to " + value
lock.unlock()
println "Thread " + i + " is releasing the lock."
}
} else {
Thread.start {
if (!lock.tryLock()) {
println "Thread " + i + " tried to read the value, but could not."
lock.lock()
}
println "Thread " + i + " says that the value is " + value + "."
lock.unlock()
}
}
}

Separate user interaction and computation.

Allow your program to accept user interaction while conducting a long running computation.

Example:

Hello user! Please input a string to permute: (input thread)
abcdef
Passing on abcdef... (input thread)
Please input another string to permute: (input thread)
lol
Passing on lol... (input thread)
Done Work On abcdef! (worker thread)
["abcdef", "abcefd", ... ] (worker thread)
Please input another string to permute: (input thread)
EXIT
Quitting, I'll let my worker thread know... (input thread)
We'
re quitting! Alright! (worker thread)

--Notice, that this could be accomplished on the command line or within a GUI. The point is that computation and user interaction should take place on separate threads of control.
groovy
def threads = new ConcurrentLinkedQueue<Thread>()

void permutations(String prefix, String w, Set<String> permSet) {
int n = w.size()
if (!n) permSet << prefix
else n.times { i ->
permutations(prefix + w[i], w[0..<i] + w[i+1..<n], permSet)
}
}

println 'Welcome to the parallel permuter'
System.in.withReader { r ->
while (true) {
print 'Enter word:'
def word = r.readLine()
if (word == 'EXIT') {
while (!threads.isEmpty())
threads.poll().stop(new ThreadDeath())
break
} else
threads << Thread.start {
try {
def wordAns = [] as Set
for (int i = 0; i < word.size(); i++)
for (int j = i + 1; j <= word.size(); j++)
permutations("", word[i..<j], wordAns)
println '\nAnswer:' + wordAns
print 'Enter word:'
} catch (ThreadDeath td) {
println 'Thread aborted!'
}
}
}
}