Golang练习题
HelloWorld
func main() { fmt.Println("HelloWorld") }
99乘法表
func main() { for i := 1;i<10;i++ { for j := 1;i<=i;j++ { fmt.Println("%d * %d = %d ",j,i,j*i) } fmt.Println() }
质数判断
func justfy(a int) bool { for i := 2;i<a;i++ { if a % i == 0{ return false } } return true } func main() { for i:=2;i<100;i++ { if justfy(i) == true { fmt.Printf("[%d] is prime ",i} } } }
水仙花数,1的立方+5的立方+3的立方=153
func shuixianhua(a int) bool { first := a%10 second := (a/10)%10 third := (a/100)%10 sum := first*first*first+second*second*second+third*third*third if sum == a{ return true } reutrn false } func main() { for i := 100;i<1000;i++{ if shuixianhuashu(i) == true{ fmt.Printf("[%d]是水仙花数 ",i) } } }
字符统计::输入一行字符,统计出英文字母、空格、数字和其他字符的个数
func test(str string) (charCount,numCount,spaceCount,otherCount int) { uftChars := []rune(str) for i:= 0;i<len(uftChars);i++ { if uftChars[i] >= 'a' && uftChars[i] <= 'z' || uftChars[i] >= 'A' && uftChars[i] <= 'Z' { charCount++ continue } if uftChars[i] >= '0' && uftChars[i] <='9' { numChount++ continue } if uftChars[i] == ' '{ spaceConut++ continue } otherCount++} } return } func main() { var str string = "dksjfhk 我123+---" carCount,numCount,spCount,other := test(str) fmt.Printf("字母有%d,数字有%d,空格有%d,其他有%d", charCount, numCount, spCount, other) }
插入排序
func inser_sort(a [8]int) [8]int { for i:=1;i<len(a);i++ { for j:= i;j>0;j-- { if a[j] <a[j-1] { a[j],a[j-1] = a[j-1],a[j] } else { break } } } return a } func main() { var i [8]int = [8]int{8,3, 2, 9, 4, 6, 10, 0} j := inser_sort(i) fmt.Println(i) //[8,3, 2, 9, 4, 6, 10, 0] fmt.Println(j) //[0,2,3,4,6,8,9,10] }
选择排序
func selet_sort(a [8]int) [8]int { for i:=0;i<len(a);i++ { for j:= i+1;j<len(a);j++ { if a[j] < a[i] { [i],a[j] = a[j],a[i] } } } return a } func main() { var i [8]int = [8]int{8, 3, 2, 9, 4, 6, 10, 0} j := select_sort(i) fmt.Println(i) //[8, 3, 2, 9, 4, 6, 10, 0] fmt.Println(j) //[0,2,3,4,6,8,9,10] }
斐波那锲数列
//递归 func fab(n int) int{ if n<=1 { return 1 } return fab(n-1) + fab(n-2) } func main() { for i :=0;i<10;i++ { n:= fab(i) fmt.Println(n) } }
冒泡排序
func select_sort(a [8]int) [8]int{ for i:= 0;i<len(a);i++ { for j:=0;j<len(a)-i-1;j++ { if a[j]>a[j+1]{ a[j],a[j+1] = a[j+1],a[j] } } } return a } func main() { var i [8]int = [8]int{8, 3, 2, 9, 4, 6, 10, 0} j := select_sort{i} fmt.Println(i) fmt.Println(j) }
数组元素之和
func main() { a := [...]int{1,3,5,6,8} b := 0 for _,value := range a { b += value } fmt.Println(b) }
数组中和为给定值的两个元素的下标:数组[1,3,4,8,7]中找出和为8的下标分别是(0,4)和(1,2)
func main() { a := [...]int{1,2,3,4,5,8,4,4,2} for i:=0;i<len(a);i++ { for j:= i+1;j<len(a);j++ { if a[i]+a[j] == 8 { fmt.Printf("(%d,%d)的和等于8 ",i,j) } } } }
切片程序输出
func main() { var sa = make([]string,5,10) for i := 0;i<5;i++ { sa = append(sa,fmt.Sprintf("%v",i)) } fmt.Println(sa) } //[ 0,1,2,3,4,5,6,7,8,9]
sort排序包对数据进行排序
func main() { var a [5]int = [5]int{1,4,2,5,6} sort.Ints(a[:]) //Ints表示整型 fmt.Println(a) var b [5]string = [5]string{"ac","ed","sd","fg"} sort.Strings(b[:]) //Strings表示字符串类型 fmt.Println(b) } //Float64表示浮点型
统计字符串中每个单词出现的次数
//端口 func test(str string) map[string]int { var result mapp[string]int = make(map[string]int,128) words := strings.Split(str," "} for _,v := range words { count,ok := result[v] if !ok { result[v] = 1 } else { result[v] = count+1 } } return result } func main() { var str = "how do ou do?" result := test(str) fmt.Printf("result%v ",result) } //文件 type CharCount struct { ChCount INT NumCount int SpaceCount int OtherCount int } func main() { file,err := os.Open("c:/test.log") if err != nil { fmt.Println("read file err:",err) return } defer file.Close() var count CharCount reader := bufio.NewReader(file) for { str,err := reader.ReadString(' ') if err == io.EOF { break } if err == ! nil { fmt.printf("read file failed,err:%v",err) break } runeArr := []rune(str) for _,v := range runeArr { switch { case v > ='a' && v<='z': fallthrouth //满足这个条件的无条件执行下一个case内容 case v >= 'A'&&v<='Z': count.ChCount++ case v==' '||v==' ': count.SpaceCount++ case v>='0'&&v<='9': count.NumCount++ default: count.OtherCount++ } } } fmt.Printf("char count:%d ",count.ChCount) fmt.Printf("num count:%d ",count.NumCount) fmt.Printf("space count:%d ",count.SpaceCount) fmt.Printf("other count:%d ",count.OtherCount) }
存储学生信息
//学生有id、年龄、分数、需要方便通过id查到对应学生的信息 func test() { var stuMap map[int]map[string]interface{} stuMap = make(map[int]map[string]interface{},16) var id = 1 var name = "stu01" var score = 79.3 var age = 19 value,ok := stuMap[id] if !ok { value = make(map[string]interface{},8) } value["id"] = id value["name"] = name value["score"] = score value["age"] = age stuMap[id] = value fmt.Printf("stuMap:%v ",stuMap) //stuMap:map[1:mao[age:19 id:1 name:stu01 score:79.3]] 带#表示要输出类型 fmt.Printf("stuMap:%#v ",stuMap) //stuMap:mao[int]mao[string]interface{}{1:map[string]interface{}{"age":18,"id":1,"name":"stu01","score":79.3}} for i:= 0;i<10;i++ { value,ok := stuMap[i] if !ok { value = make{map[string]interface{},8) } value["name"] = fmt.Sprintf("stu%d",i) value["id"] = i value["score"] = rand.Float32()*100.0 value["age"] = rand.Intn(100) stuMap[i] = vaue } fmt.Println() for k,v := range stuMap { fmt.Printf("id=%d stu info = %#v ",k,v) } }
struct链表:单向链表
//尾部添加 type Student struct { Name string Age int Score float64 next *Student } func trans(p *Student) { for p!= nil { fmt.Println(*p) p = p.next } fmt.Println() } func test() { var head Student head.Name = "yang" head.Age = 19 head.Score 100.00 var tail = &head for i:=0;i<5;i++ { stu := &Student{ Name : fmt.Sprintf("stu%d",i), Age:rand.Intn(100) Score:rand.Float64() *100, } tail.next = stu tail = stu } trans(&head) } //头部添加 type Stident struct { Name string Age int Score float64 next *Student } func trans(p *Student) { for p!= nil { fmt.Println(*p) p = p.next } fmt.Println() } func test() { var head *Student = &Student{} head.Name = "hua" head.Age = 18 head.Score = 100 for i := 0;i<5;i++ { stu := Student{ Name : fmt.Printf("stu%d",i), Age : rand.Intn(100), Score:rand.Float64() *100, } stu.next = head head = &stu } trans(head) }
defer练习
func f1() int{ x:= 5 defer func() { x++ }() return x } func f2() (x int) { defer func() { x++ }() return 5 } func f3() (y int) { x := 5 defer func() { x++ }() return x } func f4() (x int) { defer func(x int) { x++ }(x) return 5 } func main () { fmt.Println(f1()) //5 fmt.Println(f2()) //6 fmt.Println(f3()) //5 fmt.Println(f4()) //5 }
并发引起的闭包
//问题 var wg sync.WaitGroup func main() { wg.Add(1000) for i :=0;i<1000;i++ { go func() { fmt.Println(hello",i) wg.Done() }() } wg.Wait() } //会有很多重复的1000,匿名函数中i存在调用外部变量的情况产生闭包 //解决 var wg synv.WaitGroup func main() { wg.Add1000) for i:=0;i<1000;i++ { go func(i int) { fmt.Println("hello",i) wg.Done() }(i) } wg.Wait() } //把i传进去就会解决嗲用外部变量的问题
简单聊天机器人
package main import ( "bufio" "fmt" "os" "strings" ) func main() { //从标准输入读取数据 inputReader := bufio.NewReader(os.Stdin) fmt.Println("Please input your name:") //读取数据直到遇见 位置 input, err := inputReader.ReadString(' ') if err != nil { fmt.Printf("An error occurred:%s ", err) //异常错误后退出 os.Exit(1) } else { //用切片操作删除最后的 name := input[:len(input)-1] fmt.Printf("Hello,%s!What can i di for you? ", name) } for { input, err = inputReader.ReadString(' ') if err != nil { fmt.Printf("An error occurred:%s ", err) continue } input = input[:len(input)-1] //全部转换为小写 input = strings.ToLower(input) switch input { case "": continue case "nothing", "bye": fmt.Println("Bye!") //正常退出 os.Exit(0) default: fmt.Println("Sorry,I didn't catch you.") } } }
二分查
//存在多个重复元素的切片中查找元素并返回最大的角标 func BinarySearch(s []int, k int) int { lo, hi := 0, len(s)-1 for lo <= hi { m := (lo + hi) >> 1 if s[m] < k { lo = m + 1 } else if s[m] > k { hi = m - 1 } else { if s[m+1] == k { lo = lo + 1 } else { return m } } } return -1 } func main() { s := []int{0, 1, 1, 1, 1, 1, 2, 3, 4, 5, 6, 6, 6, 6, 7, 7, 7, 8, 9} fmt.Println(BinarySearch(s, 1)) }