go 课后作业题 by Mars Zhang
刚刚接触 Glong 练习题供大家参考!
go 课后作业题 by Mars Zhang
- 基础题
- go 实现 while 循环实现输出 "2-3+4-5+6...+100" 的和
- for 循环实现 9 乘 9 乘法表
- golang 实现冒泡排序
- golang 实现快排
- 判断101-200之间有多少个素数,并输出所有素数
- 实现map的有序遍历 (待改进)
- 字符串反转
- 合并两个有序列表
- 进阶题
- 找最长公共前缀 (待改进)
- 字符串压缩 (待改进)
1. 基础题
01. go 实现 while 循环实现输出 "2-3+4-5+6...+100" 的和
package main
import "fmt"
func main() {
// while loop for sum "2-3+4-5+6 ... + 100"
// there is no while loop in go, we write for loop instead
// odd number - and even number +
total := 0
count := 2
for {
if total < 101 {
if count%2 == 0 {
total += count
count++
fmt.Printf("%v ", total)
} else {
total -= count76
count++
fmt.Printf("%v ", total)
}
} else {
break // jump out for loop
}
}
}
############# OUTPUT #############
2 -1 3 -2 4 -3 5 -4 6 -5 7 -6 8 -7 9 -8 10 -9 11 -10 12 -11 13 -12 14 -13 15 -14 16 -15 17 -16 18 -17 19 -18 20 -19 21 -20 22 -21 23 -22 24 -23 25 -24 26 -25 27 -26 28 -27 29 -28 30 -29 31 -30 32 -31 33 -32 34 -33 35 -34 36 -35 37 -36 38 -37 39 -38 40 -39 41 -40 42 -41 43 -42 44 -43 45 -44 46 -45 47 -46 48 -47 49 -48 50 -49 51 -50 52 -51 53 -52 54 -53 55 -54 56 -55 57 -56 58 -57 59 -58 60 -59 61 -60 62 -61 63 -62 64 -63 65 -64 66 -65 67 -66 68 -67 69 -68 70 -69 71 -70 72 -71 73 -72 74 -73 75 -74 76 -75 77 -76 78 -77 79 -78 80 -79 81 -80 82 -81 83 -82 84 -83 85 -84 86 -85 87 -86 88 -87 89 -88 90 -89 91 -90 92 -91 93 -92 94 -93 95 -94 96 -95 97 -96 98 -97 99 -98 100 -99 101
############# OUTPUT #############
02. for 循环实现 9 乘 9 乘法表
package main
import "fmt"
func main() {
for i := 1; i < 10; i++ {
for j := 1; j <= i; j++ {
fmt.Printf("%d*%d=%d ", j, i, i*j)
}
fmt.Println()
}
}
############# OUTPUT #############
1*1=1
1*2=2 2*2=4
1*3=3 2*3=6 3*3=9
1*4=4 2*4=8 3*4=12 4*4=16
1*5=5 2*5=10 3*5=15 4*5=20 5*5=25
1*6=6 2*6=12 3*6=18 4*6=24 5*6=30 6*6=36
1*7=7 2*7=14 3*7=21 4*7=28 5*7=35 6*7=42 7*7=49
1*8=8 2*8=16 3*8=24 4*8=32 5*8=40 6*8=48 7*8=56 8*8=64
############# OUTPUT #############
03. golang 实现冒泡排序
package main
import "fmt"
func main() {
fmt.Println("Please input 10 integer numbers!")
x, err := intScanln(10)
if err != nil {
fmt.Println(err)
return
}
res := bubbleSort(x)
fmt.Println(res)
}
func intScanln(n int) ([]int, error) {
x := make([]int, n)
y := make([]interface{}, len(x))
for i := range x {
y[i] = &x[i]
}
n, err := fmt.Scanln(y...)
x = x[:n]
return x, err
}
func bubbleSort(array []int) []int {
length := len(array)
//isChange :=false
for i := 0; i < length; i++ {
for j := 0; j < length-i-1; j++ {
// j <= length-i-1 这个是关键,每次 i ,少比较最后一位数组
if array[j] > array[j+1] {
array[j+1], array[j] = array[j], array[j+1]
//isChange = true
}
}
// 直接跳下次循环
// if !isChange {
// break;
// }
}
return array
}
############# OUTPUT #############
Please input 10 integer numbers!
12 34 56 78 89 12 34 67 47 28
[12 12 28 34 34 47 56 67 78 89]
############# OUTPUT #############
04. golang 实现快排
// https://mojotv.cn/algorithm/golang-quick-sort
package main
import (
"fmt"
"testing"
)
func main() {
fmt.Println("Please input 10 integer numbers!")
x, err := intScanln(10)
if err != nil {
fmt.Println(err)
return
}
QuickSort(x, 0, len(x)-1)
fmt.Println(x)
}
func intScanln(n int) ([]int, error) {
x := make([]int, n)
y := make([]interface{}, len(x))
for i := range x {
y[i] = &x[i]
}
n, err := fmt.Scanln(y...)
x = x[:n]
return x, err
}
func partition(list []int, low, high int) int {
pivot := list[low] //导致 low 位置值为空
for low < high {
//high指针值 >= pivot high指针👈移
for low < high && pivot <= list[high] {
high--
}
//填补low位置空值
//high指针值 < pivot high值 移到low位置
//high 位置值空
list[low] = list[high]
//low指针值 <= pivot low指针👉移
for low < high && pivot >= list[low] {
low++
}
//填补high位置空值
//low指针值 > pivot low值 移到high位置
//low位置值空
list[high] = list[low]
}
list[low] = pivot
return low
}
func QuickSort(list []int, low, high int) {
if high > low {
pivot := partition(list, low, high)
QuickSort(list, low, pivot-1)
QuickSort(list, pivot+1, high)
}
}
############# OUTPUT #############
Please input 10 integer numbers!
1 23 32 12 24 43 12 24 35 46
[1 12 12 23 24 24 32 35 43 46]
############# OUTPUT #############
05. 判断101-200之间有多少个素数,并输出所有素数
package main
import (
"fmt"
"math"
)
func main() {
h := 0
fmt.Println("We are going to determine how many primes are there between 101-200 and output all primes!!")
for m := 101; m <= 201; m++ {
leap := 1
k := math.Sqrt(float64(m)) //返回数字的平方根
//fmt.Println(k)
for i := 2; i <= int(k+1); i++ { //K+1,表示从2循环到K(包含k)
if m%i == 0 {
leap = 0
break
}
}
if leap == 1 {
fmt.Printf("%-4d", m)
h += 1
if h%10 == 0 {
fmt.Printf("%v", "")
}
}
}
fmt.Printf("The total is %d", h)
}
############# OUTPUT #############
We are going to determine how many primes are there between 101-200 and output all primes!!
101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181 191 193 197 199 The total is 21
############# OUTPUT #############
06. 实现map的有序遍历 (待改进)
package main
import "sort"
func main() {
m := make(map[string]string)
m["name"] = "a1"
m["age"] = "c2"
m["gender"] = "b3"
keys := make([]string, 0)
for k := range m {
keys = append(keys, k)
}
//排序 key
sort.Strings(keys)
for _, key := range keys {
println(m[key])
}
}
07. 字符串反转
package main
import "fmt"
//reference https://zhuanlan.zhihu.com/p/78550943
func main() {
var str = ""
fmt.Println("please input a string for reverse!")
fmt.Scanln(&str)
fmt.Println(Reverse(str))
}
func Reverse(s string) string {
a := []rune(s)
for i, j := 0, len(a)-1; i < j; i, j = i+1, j-1 {
a[i], a[j] = a[j], a[i]
}
return string(a)
}
############# OUTPUT #############
please input a string for reverse!
adfkajdfadfadfa
afdafdafdjakfda
############# OUTPUT #############
08. 合并两个有序列表
package main
// https://www.zhujianqiang.com/detail/78
// https://blog.csdn.net/weixin_40165163/article/details/90613244
import (
"fmt"
)
func main() {
l1 := &ListNode{
Val: 1, Next: &ListNode{
Val: 2,
Next: &ListNode{
Val: 4,
Next: nil,
},
},
}
l2 := &ListNode{
Val: 1, Next: &ListNode{
Val: 3,
Next: &ListNode{
Val: 4,
Next: nil,
},
},
}
x := mergeTwoLists(l1, l2)
fmt.Println("We are going to going to merge tow lists!")
LinkPrint(x)
}
type ListNode struct {
Val int
Next *ListNode
}
func LinkPrint(cur *ListNode) {
for cur != nil {
fmt.Printf("%v ", cur.Val)
cur = cur.Next
}
}
func mergeTwoLists(l1 *ListNode, l2 *ListNode) *ListNode {
var a *ListNode
pos := &ListNode{Val: -1, Next: nil}
a = pos
for {
if l1 != nil && l2 != nil {
if l1.Val <= l2.Val {
pos.Next = l1
l1 = l1.Next
} else {
pos.Next = l2
l2 = l2.Next
}
pos = pos.Next
} else {
break
}
}
if l1 != nil {
pos.Next = l1
}
if l2 != nil {
pos.Next = l2
}
return a.Next
}
2. 进阶题
01. 找最长公共前缀 (待改进)
package main
import (
"fmt"
"strings"
)
// https://studygolang.com/articles/26567
// https://www.codeleading.com/article/95264982568/
// https://yourbasic.org/golang/split-string-into-slice/
func main() {
str := ""
fmt.Println("please input a string split with comma ',' !")
fmt.Scanln(&str)
text := longestCommonPrefix(strings.Split(str, ","))
fmt.Println(text)
}
func longestCommonPrefix(strs []string) string {
// 定义返回值
var s string
// 首先找到最短的字符串作为基准
tag := shortest(strs)
// 为空直接返回
if tag == "" {
return ""
}
// 对基准由长到短依次判断
for i := 0; i < len(tag); i++ {
// 定义基准的指定长度为返回值
s = tag[0 : len(tag)-i]
// 遍历数组中每个字符串,判断其指定长度下是否和基准一致
for _, str := range strs {
// 找到不一致的则清空返回值,退出循环,进行下一个长度的判断
if s != str[0:len(s)] {
s = ""
break
}
}
// 如果上面循环全部通过,说明某一长度下所有字符串都满足,则直接返回
if s != "" {
return s
}
}
return s
}
// 找到最短的字符串
func shortest(strs []string) string {
s := ""
for _, str := range strs {
if str == "" {
return ""
}
if s == "" || len(str) < len(s) {
s = str
}
}
return s
}
############# OUTPUT #############
please input a string split with comma ',' !
bug,bud,bus
bu
############# OUTPUT #############
02. 字符串压缩 (待改进)
package main
import (
"fmt"
"strconv"
)
//reference https://zhuanlan.zhihu.com/p/78550943
func main() {
var inputStr = ""
fmt.Println("Please input a string to see if need to compress!")
fmt.Scanln(&inputStr)
fmt.Println(Compress(inputStr))
}
func Compress(s string) string {
str := s
str1 := ""
str2 := ""
isQuit := false
x := 1
//z := len(str) - 1
fmt.Println(str)
fmt.Println(len(str))
//fmt.Println(str1)
for i := 0; i < len(str); i++ {
str1 = string(str[i])
if i >= (len(str) - 1) { // 最后一个字符,没必须再比较
str1 = str1 + strconv.Itoa(x)
str2 = str2 + str1
//fmt.Println(str2)
break
}
if str1 == string(str[i+1]) { // 第一字符,如当前字符与一下字符相等
for { //直到找到不等,退出 for
if string(str[i]) == string(str[i+x]) {
x = x + 1
if (i + x) >= len(str) {
str1 = str1 + strconv.Itoa(x)
x = 1
isQuit = true
break
}
} else {
str1 = str1 + strconv.Itoa(x)
//fmt.Println(str1)
i = i + (x - 1)
x = 1
break //找到不等,退出 for
}
}
} else { // 如果不等
str1 = string(str[i]) + strconv.Itoa(1)
}
str2 = str2 + str1
str1 = ""
//fmt.Println(str1)
// fmt.Println(str2)
if isQuit == true {
break
}
}
if len(str2) >= len(str) {
fmt.Println("do not need to compress string, print original string!!!")
str2 = str
} else {
fmt.Println("all string are compressed, print compressed string !!!")
}
return str2
}
############# OUTPUT #############
Please input a string to see if need to compress!
aaaaaabbbbbcccccddddd
21
all string are compressed, print compressed string !!!
a6b5c5d5
############# OUTPUT #############
Please input a string to see if need to compress!
absdfedddee
11
do not need to compress string, print original string!!!
absdfedddee
############# OUTPUT #############
// 在声明时初始化数据
L1 := map[int]int{
0: 1,
1: 2,
2: 4,
}
// 在声明时初始化数据
L2 := map[int]int{
0: 1,
1: 3,
2: 4,
}
mergeTwoLists(L1, L2)
mergeTwoLists(L1*ListNode, L2*ListNode)