Building a new slice with append is the way to filter a list.
What to build
A program that removes repeated numbers and keeps the first appearance of each.
Requirements
- Read n, then n whole numbers.
- Print the numbers without repeats, in their original order, on one line separated by spaces.
- On the next line print
removed: K, where K is how many numbers were left out.
Input
Line 1: n. Then n whole numbers.
Output
Two lines.
Constraints
1 ≤ n ≤ 100; each number is between -100 and 100.
Example
Input:
6
1 2 2 3 1 4
Output:
1 2 3 4
removed: 2
Why it works
The result slice only receives numbers that it does not contain yet, so each value appears once, in the order it first showed up. The difference in length gives the number removed.
Examples
Example 1 · Input
6 1 2 2 3 1 4
Expected output
1 2 3 4 removed: 2
Example 2 · Input
3 5 5 5
Expected output
5 removed: 2
Hints
Hint 1
Keep a result slice; add a number only if it is not already in it.
Hint 2
Write a small function contains(list []int, x int) bool.
Solution
Show one correct solution (try it yourself first)
package main
import "fmt"
func contains(list []int, x int) bool {
for _, v := range list {
if v == x {
return true
}
}
return false
}
func main() {
var n int
fmt.Scan(&n)
result := []int{}
for i := 0; i < n; i++ {
var x int
fmt.Scan(&x)
if !contains(result, x) {
result = append(result, x)
}
}
for i, v := range result {
if i > 0 {
fmt.Print(" ")
}
fmt.Print(v)
}
fmt.Println()
fmt.Println("removed:", n-len(result))
}