Code snippets
Snippet 1
var maxC rune = -1
for _, r := range text {
if unicode.IsUpper(r) && r > maxC {
maxC = r
}
}Snippet 2
product := 1
for i := 0; i < DIM; i++ {
product *= numbers[i]
}Snippet 3
lastRainyDay := -1
for i, measure := range mmRain {
if measure > 0 {
lastRainyDay = i
}
}Snippet 4
sum := 0
for i := 0; i < DIM; i++ {
if numbers[i]%3 == 0 {
sum += numbers[i]
}
}Snippet 5
for i := 1; i < DIM; i++ {
fmt.Println(numbers[i] - numbers[i-1])
}Snippet 6
sum := 0
i := 0
for sum < TARGET {
sum += numbers[i]
i++
if sum >= TARGET {
break
}
}
fmt.Println(TARGET,"reached at",i)Snippet 7
var min byte = text[0]
for i := 1; i < DIM; i++ {
if text[i] < min {
min = text[i]
}
}Snippet 8
alternating := true
for i := 1; i < DIM; i++ {
if (numbers[i] > 0) == (numbers[i-1] > 0) {
alternating = false
break
}
}Snippet 9
var previous rune = text[0]
for _, current := range text {
if current < previous {
fmt.Println()
}
fmt.Print(string(current), " ")
previous = current
}Analyze the code snippets above and then write the answers to the following questions
- What is the purpose of each snippet? Match each one to one of the following descriptions:
- Identify the last rainy day.
- Sum the numbers that are multple of 3.
- Find the “greatest” capital letter (the one with the highest alphabet position).
- Divide a sequence of characters in its increasing subsequences (sequences of characters in increasing alphabetical positions).
- Find the smallest character (the one with the least ASCII code).
- Compute the differences between consecutive numbers in a a sequence.
- Compute the product of a sequence of numbers.
- Check if the numbers in a sequence alternate between positive and negative.
- Establish when the sum of a sequenze of numbers exceeds a given bound.
Cluster the code snippets based on similarities. Which similarities can you find? (otherwise said: which criterium -or criteria- did you use to cluster them?)
What do the following snippets have in common?
- snippets 1, 3, and 9?
- snippets 2, 4, and 5?
- snippets 6 and 8?
- snippets 1 and 9?
- snippets 4 and 8?
- What do the following snippets have in common?
- snippets 5, 8 and 9?
- snippets 1 and 7?
- snippets 2, 4 and 6?
- The following pairs of snippets have similar structures and carry out somewhat similar tasks, but not identical. What structural, and thus semantic differences do they exhibit?
- snippets 2 and 4?
- snippets 1 and 3?
