All Problems
Output a string to the console
Write the string
"Hello World!" to STDOUT
go
fmt.Printf("Hello, world\n")
fmt.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
The script variable for first name $_REQUEST
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
Of course this fails for the same reasons. What is a better approach?
"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?
string-wrap
Wrap the string
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.
"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.
go
package main
import (
"fmt"
"strings"
)
func main() {
str := "The quick brown fox jumps over the lazy dog. "
chs := strings.Split(str, "")
j := 1
for i := 0; i < 10; i++ {
for n, l := 0, len(chs); n < l; n++ {
if j == 1 {
fmt.Print("> ")
}
fmt.Print(chs[n])
if j == 77 {
fmt.Println()
j = 1;
}else {
j++;
}
}
}
}
import (
"fmt"
"strings"
)
func main() {
str := "The quick brown fox jumps over the lazy dog. "
chs := strings.Split(str, "")
j := 1
for i := 0; i < 10; i++ {
for n, l := 0, len(chs); n < l; n++ {
if j == 1 {
fmt.Print("> ")
}
fmt.Print(chs[n])
if j == 77 {
fmt.Println()
j = 1;
}else {
j++;
}
}
}
}
package main
func main() {
chs := []rune("The quick brown fox jumps over the lazy dog. ")
j := 1
for i := 0; i < 10; i++ {
for _, v := range chs {
if j == 1 {
print("> ")
}
print(string(v))
if j == 77 {
println()
j = 1;
}else {
j++;
}
}
}
}
func main() {
chs := []rune("The quick brown fox jumps over the lazy dog. ")
j := 1
for i := 0; i < 10; i++ {
for _, v := range chs {
if j == 1 {
print("> ")
}
print(string(v))
if j == 77 {
println()
j = 1;
}else {
j++;
}
}
}
}
Define a string containing special characters
Define the literal string
"\#{'}${"}/"
go
s := "\\#{'}${\"}/"
s := `"\#{'}${"}/"`
Define a multiline string
Define the string:
"This
Is
A
Multiline
String"
go
text := "This\nIs\nA\nMultiline\nString\n"
text := "This\n" + "Is\n" + "A\n" + "Multiline\n" + "String\n"
var s = `This
Is
A
Multiline
String`
Is
A
Multiline
String`
Define a string containing variables and expressions
Given variables a=3 and b=4 output
"3+4=7"
go
a, b := 3, 4
fmt.Printf("%d+%d=%d\n", a, b, a + b)
fmt.Printf("%d+%d=%d\n", a, b, a + b)
a, b := 3, 4
fmt.Println(a, "+", b, "=", a+b)
fmt.Println(a, "+", b, "=", a+b)
Reverse the characters in a string
Given the string
"reverse me", produce the string "em esrever"
go
package main;
import "utf8";
import "fmt";
func reverse(s string) string {
o := make([]int, utf8.RuneCountInString(s))
i := len(o)
for _, c := range s {
i--
o[i] = c
}
return string(o)
}
func main() {
fmt.Print(reverse("reverse me"));
}
import "utf8";
import "fmt";
func reverse(s string) string {
o := make([]int, utf8.RuneCountInString(s))
i := len(o)
for _, c := range s {
i--
o[i] = c
}
return string(o)
}
func main() {
fmt.Print(reverse("reverse me"));
}
func Reverse(s string) string {
runes := []rune(s)
for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
runes[i], runes[j] = runes[j], runes[i]
}
return string(runes)
}
runes := []rune(s)
for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
runes[i], runes[j] = runes[j], runes[i]
}
return string(runes)
}
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"
go
words := strings.Split("This is the end, my only friend!", " ")
nr := len(words)
reversed := make([]string, nr)
for i, word := range words {
reversed[nr - i - 1] = word
}
s := strings.Join(reversed, " ")
fmt.Println(s)
nr := len(words)
reversed := make([]string, nr)
for i, word := range words {
reversed[nr - i - 1] = word
}
s := strings.Join(reversed, " ")
fmt.Println(s)
func reverse(list []string) ([]string) {
if len(list) == 1 {
return list
}
return append(reverse(list[1:]), list[0])
}
func main() {
words := strings.Split("This is the end, my only friend!", " ")
s := strings.Join(reverse(words), " ")
fmt.Println(s)
}
if len(list) == 1 {
return list
}
return append(reverse(list[1:]), list[0])
}
func main() {
words := strings.Split("This is the end, my only friend!", " ")
s := strings.Join(reverse(words), " ")
fmt.Println(s)
}
Text wrapping
Wrap the string
> 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.
"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.
go
import "fmt"
import "strings"
const WIDTH = 72
func main() {
s := "The quick brown fox jumps over the lazy dog."
words := strings.Split(s, " ")
tmp := words
for i, pos := 0, 0; i < 10; i++ {
for len(words) > 0 {
if pos == 0 {
fmt.Printf("> ")
}
if pos + len(words[0]) > WIDTH {
fmt.Printf("\n")
pos = 0
} else {
fmt.Printf("%s ", words[0])
pos += len(words[0]) + 1
words = words[1:]
}
}
words = tmp
}
fmt.Printf("\n")
}
import "strings"
const WIDTH = 72
func main() {
s := "The quick brown fox jumps over the lazy dog."
words := strings.Split(s, " ")
tmp := words
for i, pos := 0, 0; i < 10; i++ {
for len(words) > 0 {
if pos == 0 {
fmt.Printf("> ")
}
if pos + len(words[0]) > WIDTH {
fmt.Printf("\n")
pos = 0
} else {
fmt.Printf("%s ", words[0])
pos += len(words[0]) + 1
words = words[1:]
}
}
words = tmp
}
fmt.Printf("\n")
}
Remove leading and trailing whitespace from a string
Given the string
" hello " return the string "hello".
go
s := strings.TrimSpace(" hello ")
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
For example:
String is: Hello World #123
ROT13 returns: Uryyb Jbeyq #123
ROT47 returns: w6==@ (@C=5 R`ab
Make a string uppercase
Transform
"Space Monkey" into "SPACE MONKEY"
go
strings.ToUpper("Space Monkey")
Make a string lowercase
Transform
"Caps ARE overRated" into "caps are overrated"
go
strings.ToLower("Caps ARE overRated")
Capitalise the first letter of each word
Transform
"man OF stEEL" into "Man Of Steel"
go
strings.Title(strings.ToLower("man OF stEEL"))
Find the distance between two points
go
import "fmt"
import "math"
type Point struct {
x, y float64
}
func (p Point) distance(other Point) (float64) {
dx := p.x - other.x
dy := p.y - other.y
return math.Sqrt(dx * dx + dy * dy)
}
func main() {
origin := Point{ 0, 0 }
point := Point{ 1, 1 }
fmt.Println(point.distance(origin))
}
import "math"
type Point struct {
x, y float64
}
func (p Point) distance(other Point) (float64) {
dx := p.x - other.x
dy := p.y - other.y
return math.Sqrt(dx * dx + dy * dy)
}
func main() {
origin := Point{ 0, 0 }
point := Point{ 1, 1 }
fmt.Println(point.distance(origin))
}
Zero pad a number
Given the number 42, pad it to 8 characters like 00000042
go
fmt.Printf("%08d", 42)
Right Space pad a number
Given the number 1024 right pad it to 6 characters
"1024 "
go
fmt.Printf("%-6d", 1024)
Format a decimal number
Format the number 7/8 as a decimal with 2 places: 0.88
go
fmt.Printf("%.2f", 7.0 / 8.0)
Left Space pad a number
Given the number 73 left pad it to 10 characters
" 73"
go
fmt.Printf("%10d", 73)
Generate a random integer in a given range
Produce a random integer between 100 and 200 inclusive
go
rand.Intn(100) + 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.
go
rand.Seed(0xdeadbeef)
for i := 0; i < 5; i++ {
fmt.Printf("%v ", rand.Int())
}
fmt.Println()
rand.Seed(0xdeadbeef)
for i := 0; i < 5; i++ {
fmt.Printf("%v ", rand.Int())
}
fmt.Println()
for i := 0; i < 5; i++ {
fmt.Printf("%v ", rand.Int())
}
fmt.Println()
rand.Seed(0xdeadbeef)
for i := 0; i < 5; i++ {
fmt.Printf("%v ", rand.Int())
}
fmt.Println()
Check if a string matches a regular expression
Display
"ok" if "Hello" matches /[A-Z][a-z]+/
go
result, _ := regexp.MatchString("[A-Z][a-z]+", "Hello")
if result {
fmt.Println("ok")
}
if result {
fmt.Println("ok")
}
Check if a string matches with groups
Display
"two" if "one two three" matches /one (.*) three/
go
re, _ := regexp.Compile("one (.*) three")
groups := re.FindStringSubmatch("one two three")
if len(groups) > 0 {
fmt.Println(groups[1])
}
groups := re.FindStringSubmatch("one two three")
if len(groups) > 0 {
fmt.Println(groups[1])
}
Check if a string contains a match to a regular expression
Display
"ok" if "abc 123 @#$" matches /\d+/
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+)/
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 "*"
go
i := 0
f := func (in string) (out string) {
i++
if i == 1 {
return "*"
}
return in
}
re, _ := regexp.Compile("e")
s := re.ReplaceAllStringFunc("Red Green Blue", f)
fmt.Println(s)
f := func (in string) (out string) {
i++
if i == 1 {
return "*"
}
return in
}
re, _ := regexp.Compile("e")
s := re.ReplaceAllStringFunc("Red Green Blue", f)
fmt.Println(s)
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"
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+)\}/.
Define an empty list
Assign the variable
"list" to a list with no elements
go
var l []string;
Define a static list
Define the list
[One, Two, Three, Four, Five]
go
var l = []string{"One", "Two", "Three", "Four", "Five"}
Join the elements of a list, separated by commas
Given the list
[Apple, Banana, Carrot] produce "Apple, Banana, Carrot"
go
s := strings.Join([]string {"Apple", "Banana", "Carrot"}, ", ")
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(
join(
join(
join(
join(
[Apple, Banana, Carrot]) = "Apple, Banana, and Carrot"
join(
[One, Two]) = "One and Two"
join(
[Lonely]) = "Lonely"
join(
[]) = ""
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]]
From a List Produce a List of Duplicate Entries
Taking a list:
Write the code to produce a list of duplicates in the list:
["andrew", "bob", "chris", "bob"]
Write the code to produce a list of duplicates in the list:
["bob"]
Fetch an element of a list by index
Given the list
[One, Two, Three, Four, Five], fetch the third element ('Three')
go
fmt.Println(list[2])
Fetch the last element of a list
Given the list
[Red, Green, Blue], access the last element ('Blue')
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?
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.
Remove an element from a list by index
Given the list
[Apple, Banana, Carrot], remove the first element to produce the list [Banana, Carrot]
go
offset := 0
list = append(list[:offset], list[offset+1:]...)
list = append(list[:offset], list[offset+1:]...)
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"]
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.
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'.
Perform an operation on every item of a list
Perform an operation on every item of a list, e.g.
for the list
the list of sizes of the strings, e.g.
for the list
["ox", "cat", "deer", "whale"] calculate
the list of sizes of the strings, e.g.
[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.
split the list into numbers and non-numbers.
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.
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.
Define an empty map
go
m := make(map[int]string)
Define an initial map
Define the map
{circle:1, triangle:3, square:4}
go
m := map[string]int{ "circle": 1, "square": 4, "triangle": 2 }
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"
go
m := map[string]string{ "joe": "cat", "mary": "turtle", "bill": "canary" }
if _, ok := m["mary"]; ok {
fmt.Println("ok")
}
if _, ok := m["mary"]; ok {
fmt.Println("ok")
}
Retrieve a value from a map
Given a map pets
{joe:cat,mary:turtle,bill:canary} print the pet for "joe" ("cat")
go
fmt.Println(pets["joe"])
Add an entry to a map
Given an empty pets map, add the mapping from
"rob" to "dog"
go
pets["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"
go
fmt.Println(pets["bill"])
delete(pets, "bill")
delete(pets, "bill")
fmt.Println(pets["bill"])
pets["bill"] = "", false
pets["bill"] = "", false
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
go
var maplist = make(map[string]int)
var list = [6]string{"a","b","a","c","b","b"}
for _, v := range list {
maplist[v] += 1
}
fmt.Println(maplist)
var list = [6]string{"a","b","a","c","b","b"}
for _, v := range list {
maplist[v] += 1
}
fmt.Println(maplist)
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
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.
go
if name == "Bob" {
fmt.Println("Hello", name)
}
fmt.Println("Hello", name)
}
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"
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
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.
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"
Perform an action a fixed number of times (FOR)
Display the string
"Hello" five times like "HelloHelloHelloHelloHello"
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!"
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
1> First line of file
2> Second line of file
3> Third line of file
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.
go
t, err := time.Parse("2006-01-02 15:04", "2008-05-06 13:29")
if err == nil {
fmt.Println(t)
}
if err == nil {
fmt.Println(t)
}
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.
go
t := time.Now().Add(8 * 24 * time.Hour)
fmt.Println(t.Day())
// no day of year
fmt.Println(t.Month())
fmt.Println(t.Weekday())
fmt.Println(t.Day())
// no day of year
fmt.Println(t.Month())
fmt.Println(t.Weekday())
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.)
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.)
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.
If you can also do this without creating a Date object you can show that too.
go
fmt.Println(time.Now())
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.
go
type Greeter struct {
whom string
}
func (g Greeter) greet() {
fmt.Printf("Hello %s\n", g.whom)
}
func main() {
Greeter{"world"}.greet()
}
whom string
}
func (g Greeter) greet() {
fmt.Printf("Hello %s\n", g.whom)
}
func main() {
Greeter{"world"}.greet()
}
Instantiate object with mutable state
Reimplement the Greeter class so that the
For example, if the greetee is changed to
Hello, Tommy!
The getter would then be used to display the line:
I have just greeted Tommy.
'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.
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
* A
* A
* 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.
Implement and use an Interface
Create a Serializable interface consisting of
* 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
Next, create a Person class which has
'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.
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.
go
resp, err := http.Get(url)
if err != nil {
fmt.Println("Error", err)
}
defer resp.Body.Close()
bodyBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println("Read Error", err)
}
matched, _ := regexp.Match(lang,bodyBytes)
if matched {
fmt.Println("Go is in the page")
} else {
fmt.Println("Go isn't in the page")
}
if err != nil {
fmt.Println("Error", err)
}
defer resp.Body.Close()
bodyBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println("Read Error", err)
}
matched, _ := regexp.Match(lang,bodyBytes)
if matched {
fmt.Println("Go is in the page")
} else {
fmt.Println("Go isn't in the page")
}
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.
Process an XML document
Given the XML Document:
<shopping>
<item name=
<item name=
</shopping>
Print out the total cost of the items, e.g. $14.50
<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
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=
<item name=
</shopping>
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>
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:
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]
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.
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.
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)
In other words, a list of random strings.
-Output-
(In python syntax)
In other words, all possible permutations of each input string are computed.
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.
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
Notice that in this problem, at each step or
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.
Create a multithreaded "Hello World"
Create a program which outputs the string
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.
"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.
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.
(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.
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)
Please input another string to permute: (input thread)
EXIT
Quitting, I
--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.
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.
Put a internationalizate of HelloWorld program
Set locale to
In pseudocode:
Void main ()
"es" (spanish) and provide a program that changes outputs ("Helloworld") depending of locale.
In pseudocode:
Void main ()
{
Locale.set("es")
print.translate("Helloworld, Locale.get)
}
180
"http://www.ecigarettefresh.com/cartomizer-ecigarette-c-7.html ">Cartomizer E-Cigarette<
/a>strong>"http://www.ecigarettefresh.com/cartomizer-ecigarette-c-7.html ">Electronic Cigarette<
/a>strong>"http://www.ecigarettefresh.com/cartomizer-ecigarette-c-7.html ">Smokeless Cigarettes<
/a>strong>"http://www.ecigarettefresh.com/cartomizer-ecigarette-c-7.html ">discount Electronic Cigarette<
/a>strong>"http://www.ecigarettefresh.com/disposable-ecigarette-c-8.html ">Disposable E-Cigarette<
/a>strong>"http://www.ecigarettefresh.com/accessories-c-6.html ">Accessories<
/a>strong>"http://www.ecigarettefresh.com/mini-ecigarette-c-13.html ">Mini E-cigarette<
/a>strong>"http://www.ecigarettefresh.com/esmoking-c-11.html ">electric cigarette outlet<
/a>strong>"http://www.ecigarettefresh.com/smokeless-cigarettes-c-12.html ">Smokeless Cigarettes online<
/a>strong>"http://www.ecigarettefresh.com/ecigarette-c-9.html ">Electronic Cigarette online<
/a>strong>. "http://blog.allluxurywatches.com"> outlet blog <
/a>
outlet a>"http://blog.linksoflondonshopping.com"> About ecigarettefresh.com blog
180
"http://www.lovembtshoes.com/ ">mbt boots<
/a>strong>"http://www.lovembtshoes.com/ ">mbt shoes<
/a>strong>"http://www.lovembtshoes.com/ ">buy mbt boots<
/a>strong>"http://www.lovembtshoes.com/ ">discount mbt shoes<
/a>strong>"http://www.lovembtshoes.com/ ">mbt shoes online<
/a>strong>"http://www.lovembtshoes.com/mbt-tariki-c-50.html ">MBT Tariki shoes outlet<
/a>strong>"http://www.lovembtshoes.com/mbt-karibu-c-18.html ">wholesale MBT Karibu shoes<
/a>strong>"http://www.lovembtshoes.com/mbt-kafala-black-leather-women-shoes-p-68.html ">buy MBT Kafala shoes<
/a>strong>"http://www.lovembtshoes.com/mbt-meli-c-33.html ">MBT Meli<
/a>strong>"http://www.lovembtshoes.com/mbt-kifundo-c-25.html ">discount MBT Kifundo<
/a>strong>. "http://blog.bootsonlinecompany.com"> Bia blog <
/a>
Bia a>"http://blog.linkuggbootsoutlet.com"> About lovembtshoes.com blog
180
[Mall3411] - $175.01 : </title>
html; charset=utf-8" />
keywords" content="Low Cost Custom-Made bretelles sexy mariage mariée robe de mariée Robes [Mall3411] Robes de Mariée Robes de mariée 2012 Robe de mariée sexy Robes de mariée robes Quinceanera Robes de bal Robes de soirée Robes de bal Robes de soirée Robes de cocktail " />
description" content=" Low Cost Custom-Made bretelles sexy mariage mariée robe de mariée Robes [Mall3411] - Nom de l'article: " />
- TOP_MENU_HOME
- Robes de cocktail
- Robes de soirée
- Robes de mariée
- Robes de bal
- Contactez-nous
- http:
//fr.weddingdressescompany.com/»,«http:/fr.weddingdressescompany.com/' ) " > Marque page