ref: reformat code

main
lensfrex 7 months ago
parent 389867336d
commit ddc939fe45
Signed by: lensfrex
GPG Key ID: 0F69A0A2FBEE98A0
  1. 22
      cap3/common.go
  2. 68
      cap3/ex20.go
  3. 94
      cap3/ex21.go
  4. 76
      cap3/ex22.go
  5. 18
      cap3/ex23.go
  6. 2
      cap3/ex24.go
  7. 28
      cap3/ex25.go
  8. 32
      cap3/ex26.go
  9. 62
      cap3/ex27.go
  10. 30
      cap3/ex28.go
  11. 16
      cap3/ex29.go
  12. 52
      cap3/ex30.go
  13. 50
      cap3/ex31.go
  14. 38
      cap3/ex32.go
  15. 110
      cap3/ex34.go
  16. 34
      cap3/ex35.go
  17. 24
      cap3/ex36.go
  18. 32
      cap3/ex37.go
  19. 52
      cap3/ex38.go
  20. 10
      cap3/ex39.go
  21. 22
      cap3/ex40.go
  22. 18
      cap3/ex41.go
  23. 324
      cap3/example_test.go
  24. 48
      cap3/work10.go
  25. 14
      cap3/work11.go
  26. 36
      cap3/work12.go
  27. 28
      cap3/work14.go
  28. 46
      cap3/work15.go
  29. 22
      cap3/work16.go
  30. 10
      cap3/work17.go
  31. 72
      cap3/work18.go
  32. 38
      cap3/work19.go
  33. 104
      cap3/work20.go
  34. 62
      cap3/work21.go
  35. 16
      cap3/work22.go
  36. 10
      cap3/work23.go
  37. 44
      cap3/work24.go
  38. 52
      cap3/work25.go
  39. 8
      cap3/work27.go
  40. 158
      cap3/work6.go
  41. 22
      cap3/work7.go
  42. 14
      cap3/work8.go
  43. 38
      cap3/work9.go
  44. 114
      cap3/work_test.go

@ -3,19 +3,19 @@ package cap3
import "fmt" import "fmt"
func _printMatrix(matrix [][]int) { func _printMatrix(matrix [][]int) {
for _, row := range matrix { for _, row := range matrix {
for _, val := range row { for _, val := range row {
fmt.Printf("%d\t", val) fmt.Printf("%d\t", val)
} }
fmt.Println() fmt.Println()
} }
} }
func _makeMatrix(size int) [][]int { func _makeMatrix(size int) [][]int {
matrix := make([][]int, size) matrix := make([][]int, size)
for i := range matrix { for i := range matrix {
matrix[i] = make([]int, size) matrix[i] = make([]int, size)
} }
return matrix return matrix
} }

@ -2,42 +2,42 @@ package cap3
// Ex20 趣味矩阵 // Ex20 趣味矩阵
func Ex20(n int) [][]int { func Ex20(n int) [][]int {
matrix := make([][]int, n) matrix := make([][]int, n)
for i := 0; i < len(matrix); i++ { for i := 0; i < len(matrix); i++ {
matrix[i] = make([]int, n) matrix[i] = make([]int, n)
} }
for i := range n { for i := range n {
for j := range n { for j := range n {
// 对角线 // 对角线
if i == j || i+j == n-1 { if i == j || i+j == n-1 {
matrix[i][j] = 0 matrix[i][j] = 0
continue continue
} }
// 左上部分 // 左上部分
if i+j < n-1 { if i+j < n-1 {
if i < j { if i < j {
// 上 // 上
matrix[i][j] = 1 matrix[i][j] = 1
} else { } else {
// 左 // 左
matrix[i][j] = 2 matrix[i][j] = 2
} }
} }
// 右下边部分 // 右下边部分
if i+j > n-1 { if i+j > n-1 {
if i > j { if i > j {
// 下 // 下
matrix[i][j] = 3 matrix[i][j] = 3
} else { } else {
// 右 // 右
matrix[i][j] = 4 matrix[i][j] = 4
} }
} }
} }
} }
return matrix return matrix
} }

@ -2,65 +2,65 @@ package cap3
// Ex21 螺旋阵 // Ex21 螺旋阵
func Ex21(n int) [][]int { func Ex21(n int) [][]int {
matrix := _makeMatrix(n) matrix := _makeMatrix(n)
// 逐层往里填充 // 逐层往里填充
num := 1 num := 1
for layer := 0; layer < n/2; layer++ { for layer := 0; layer < n/2; layer++ {
// 方阵左边 // 方阵左边
for i := layer; i < n-layer; i++ { for i := layer; i < n-layer; i++ {
matrix[i][layer] = num matrix[i][layer] = num
num++ num++
} }
// 方阵下边 // 方阵下边
for i := layer + 1; i < n-layer; i++ { for i := layer + 1; i < n-layer; i++ {
matrix[n-layer-1][i] = num matrix[n-layer-1][i] = num
num++ num++
} }
// 方阵右边 // 方阵右边
for i := n - layer - 2; i >= layer; i-- { for i := n - layer - 2; i >= layer; i-- {
matrix[i][n-layer-1] = num matrix[i][n-layer-1] = num
num++ num++
} }
// 方阵上边 // 方阵上边
for i := n - layer - 2; i > layer; i-- { for i := n - layer - 2; i > layer; i-- {
matrix[layer][i] = num matrix[layer][i] = num
num++ num++
} }
} }
// 奇数阶中间位置需要手动设置 // 奇数阶中间位置需要手动设置
if n%2 != 0 { if n%2 != 0 {
matrix[n/2][n/2] = n * n matrix[n/2][n/2] = n * n
} }
return matrix return matrix
} }
func Ex21type2(n int) [][]int { func Ex21type2(n int) [][]int {
matrix := _makeMatrix(n + 10) matrix := _makeMatrix(n + 10)
row, col, t := 0, 0, 1 row, col, t := 0, 0, 1
for i := 0; i < n*n; { for i := 0; i < n*n; {
for j := 0; j < 2*n; j++ { for j := 0; j < 2*n; j++ {
i++ i++
matrix[row][col] = i matrix[row][col] = i
switch (j + 1) / (n + 1) { switch (j + 1) / (n + 1) {
case 0: case 0:
row += t row += t
case 1: case 1:
col += t col += t
} }
} }
n-- n--
t = -t t = -t
} }
return matrix return matrix
} }

@ -2,42 +2,42 @@ package cap3
// Ex22 魔方阵,罗伯法 // Ex22 魔方阵,罗伯法
func Ex22(n int) [][]int { func Ex22(n int) [][]int {
matrix := _makeMatrix(n) matrix := _makeMatrix(n)
if n%2 == 0 { if n%2 == 0 {
return matrix return matrix
} }
// 起始位置在第一行的中间 // 起始位置在第一行的中间
i, j := 0, n/2 i, j := 0, n/2
for num := 1; num <= n*n; num++ { for num := 1; num <= n*n; num++ {
matrix[i][j] = num // 填充数字 matrix[i][j] = num // 填充数字
num++ // 下一个数字 num++ // 下一个数字
i-- // 向上移动 i-- // 向上移动
j++ // 向右移动 j++ // 向右移动
// 如果移动后超出了上边界和右边界 // 如果移动后超出了上边界和右边界
if i < 0 && j > n-1 { if i < 0 && j > n-1 {
i += 2 // 向下移动两格 i += 2 // 向下移动两格
j-- // 向左移动一格 j-- // 向左移动一格
} }
// 如果超出了上边界 // 如果超出了上边界
if i < 0 { if i < 0 {
i = n - 1 // 移动到最下面一行 i = n - 1 // 移动到最下面一行
} }
// 如果超出了右边界 // 如果超出了右边界
if j > n-1 { if j > n-1 {
j = 0 // 移动到最左边一列 j = 0 // 移动到最左边一列
} }
// 如果当前位置已经填充了数字 // 如果当前位置已经填充了数字
if matrix[i][j] != 0 { if matrix[i][j] != 0 {
i += 2 // 向下移动两格 i += 2 // 向下移动两格
j-- // 向左移动一格 j-- // 向左移动一格
} }
} }
return matrix return matrix
} }

@ -1,18 +1,18 @@
package cap3 package cap3
type Pair struct { type Pair struct {
first, second int first, second int
} }
func Ex23(nums []int) [][]int { func Ex23(nums []int) [][]int {
countMap := _makeMatrix(10) countMap := _makeMatrix(10)
for _, num1 := range nums { for _, num1 := range nums {
for _, num2 := range nums { for _, num2 := range nums {
countMap[num1][num2]++ countMap[num1][num2]++
countMap[num2][num1]++ countMap[num2][num1]++
} }
} }
return countMap return countMap
} }

@ -1,5 +1,5 @@
package cap3 package cap3
func Ex24(n int) int { func Ex24(n int) int {
return 0 return 0
} }

@ -1,20 +1,20 @@
package cap3 package cap3
func Ex25(studentScore [][]int) int { func Ex25(studentScore [][]int) int {
studentCount := 0 studentCount := 0
for _, scores := range studentScore { for _, scores := range studentScore {
scoreCount := 0 scoreCount := 0
for _, score := range scores { for _, score := range scores {
if score >= 90 { if score >= 90 {
scoreCount++ scoreCount++
} }
if scoreCount > 3 { if scoreCount > 3 {
studentCount++ studentCount++
break break
} }
} }
} }
return studentCount return studentCount
} }

@ -1,22 +1,22 @@
package cap3 package cap3
func Ex26(n int) []int { func Ex26(n int) []int {
lights := make([]bool, n) lights := make([]bool, n)
// 默认值false,实际上意味着第一个人已经把所有灯关了,没必要再操作一遍 // 默认值false,实际上意味着第一个人已经把所有灯关了,没必要再操作一遍
// 第i个人,从第二个人开始 // 第i个人,从第二个人开始
for i := 2; i <= n; i++ { for i := 2; i <= n; i++ {
// 编号为i的倍数的灯状态取反 // 编号为i的倍数的灯状态取反
for j := 1; i*j <= n; j++ { for j := 1; i*j <= n; j++ {
lights[i*j-1] = !lights[i*j-1] lights[i*j-1] = !lights[i*j-1]
} }
} }
result := make([]int, 0, n) result := make([]int, 0, n)
for light, on := range lights { for light, on := range lights {
if on { if on {
result = append(result, light+1) result = append(result, light+1)
} }
} }
return result return result
} }

@ -3,38 +3,38 @@ package cap3
type Ex27Condition int type Ex27Condition int
const ( const (
Ex27ConditionMin Ex27Condition = iota Ex27ConditionMin Ex27Condition = iota
Ex27ConditionMax Ex27ConditionMax
) )
func Ex27(nums []int) (max1, max2, min1, min2 int) { func Ex27(nums []int) (max1, max2, min1, min2 int) {
size := len(nums) size := len(nums)
if size < 3 { if size < 3 {
return return
} }
// 最大的乘积 // 最大的乘积
maxProd := nums[size-1] * nums[1] maxProd := nums[size-1] * nums[1]
max1, max2 = nums[size-1], nums[1] max1, max2 = nums[size-1], nums[1]
// 最小的乘积 // 最小的乘积
minProd := nums[size-1] * nums[1] minProd := nums[size-1] * nums[1]
min1, min2 = nums[size-1], nums[1] min1, min2 = nums[size-1], nums[1]
for i := 1; i < size; i++ { for i := 1; i < size; i++ {
first, second := (size+i-1)%size, (i+1)%size first, second := (size+i-1)%size, (i+1)%size
// 当前的乘积 // 当前的乘积
currentProd := nums[first] * nums[second] currentProd := nums[first] * nums[second]
// 找出最大最小的乘积 // 找出最大最小的乘积
if currentProd > maxProd { if currentProd > maxProd {
maxProd = currentProd maxProd = currentProd
max1, max2 = nums[first], nums[second] max1, max2 = nums[first], nums[second]
} else if currentProd < minProd { } else if currentProd < minProd {
minProd = currentProd minProd = currentProd
min1, min2 = nums[first], nums[second] min1, min2 = nums[first], nums[second]
} }
} }
return max1, max2, min1, min2 return max1, max2, min1, min2
} }

@ -1,20 +1,20 @@
package cap3 package cap3
func Ex28(nums []int) { func Ex28(nums []int) {
n := len(nums) n := len(nums)
for i := 0; i < n-1; i++ { for i := 0; i < n-1; i++ {
swapped := false swapped := false
for j := 0; j < n-1-i; j++ { for j := 0; j < n-1-i; j++ {
if nums[j] < nums[j+1] { if nums[j] < nums[j+1] {
tmp := nums[j] tmp := nums[j]
nums[j] = nums[j+1] nums[j] = nums[j+1]
nums[j+1] = tmp nums[j+1] = tmp
swapped = true swapped = true
} }
} }
if !swapped { if !swapped {
break break
} }
} }
} }

@ -1,13 +1,13 @@
package cap3 package cap3
func Ex29(nums []int) bool { func Ex29(nums []int) bool {
for _, num1 := range nums { for _, num1 := range nums {
for _, num2 := range nums { for _, num2 := range nums {
if num1 == num2 { if num1 == num2 {
return false return false
} }
} }
} }
return true return true
} }

@ -5,33 +5,33 @@ import "math"
type Ex30TriangleType int type Ex30TriangleType int
const ( const (
Ex30TriangleTypeNone Ex30TriangleType = iota // 不是三角形 Ex30TriangleTypeNone Ex30TriangleType = iota // 不是三角形
Ex30TriangleTypeNormal Ex30TriangleType = iota // 普通三角形 Ex30TriangleTypeNormal Ex30TriangleType = iota // 普通三角形
Ex30TriangleTypeIsosceles Ex30TriangleType = iota // 等腰三角形 Ex30TriangleTypeIsosceles Ex30TriangleType = iota // 等腰三角形
Ex30TriangleTypeEquilateral Ex30TriangleType = iota // 等边三角形 Ex30TriangleTypeEquilateral Ex30TriangleType = iota // 等边三角形
Ex30TriangleTypeRight Ex30TriangleType = iota // 直角三角形 Ex30TriangleTypeRight Ex30TriangleType = iota // 直角三角形
) )
func Ex30(nums []float64) Ex30TriangleType { func Ex30(nums []float64) Ex30TriangleType {
a, b, c := nums[0], nums[1], nums[2] a, b, c := nums[0], nums[1], nums[2]
if a <= 0 || b <= 0 || c <= 0 || a+b <= c || a+c <= b || b+c <= a { if a <= 0 || b <= 0 || c <= 0 || a+b <= c || a+c <= b || b+c <= a {
return Ex30TriangleTypeNone return Ex30TriangleTypeNone
} }
if a == b && b == c { if a == b && b == c {
return Ex30TriangleTypeEquilateral return Ex30TriangleTypeEquilateral
} }
if a == b || a == c || b == c { if a == b || a == c || b == c {
return Ex30TriangleTypeIsosceles return Ex30TriangleTypeIsosceles
} }
if math.Pow(a, 2)+math.Pow(b, 2) == math.Pow(c, 2) || if math.Pow(a, 2)+math.Pow(b, 2) == math.Pow(c, 2) ||
math.Pow(a, 2)+math.Pow(c, 2) == math.Pow(b, 2) || math.Pow(a, 2)+math.Pow(c, 2) == math.Pow(b, 2) ||
math.Pow(b, 2)+math.Pow(c, 2) == math.Pow(a, 2) { math.Pow(b, 2)+math.Pow(c, 2) == math.Pow(a, 2) {
return Ex30TriangleTypeRight return Ex30TriangleTypeRight
} else { } else {
return Ex30TriangleTypeNormal return Ex30TriangleTypeNormal
} }
} }

@ -1,34 +1,34 @@
package cap3 package cap3
func Ex31(a, b, c int) int { func Ex31(a, b, c int) int {
lcm, maxNum := 0, 0 lcm, maxNum := 0, 0
maxNum = max(a, b, c) maxNum = max(a, b, c)
for i := 2; i <= maxNum; i++ { for i := 2; i <= maxNum; i++ {
hasDivisible := true hasDivisible := true
for hasDivisible { for hasDivisible {
hasDivisible = false hasDivisible = false
if a%i == 0 { if a%i == 0 {
a = a / i a = a / i
hasDivisible = true hasDivisible = true
} }
if b%i == 0 { if b%i == 0 {
b = b / i b = b / i
hasDivisible = true hasDivisible = true
} }
if c%i == 0 { if c%i == 0 {
c = c / i c = c / i
hasDivisible = true hasDivisible = true
} }
if hasDivisible { if hasDivisible {
lcm = lcm * i lcm = lcm * i
} }
} }
maxNum = max(a, b, c) maxNum = max(a, b, c)
} }
return lcm return lcm
} }

@ -1,28 +1,28 @@
package cap3 package cap3
func Ex32() int { func Ex32() int {
for x := 1; x <= 4; x++ { for x := 1; x <= 4; x++ {
count := 0 count := 0
if x != 1 { if x != 1 {
count++ count++
} }
if x == 3 { if x == 3 {
count++ count++
} }
if x == 4 { if x == 4 {
count++ count++
} }
if x != 4 { if x != 4 {
count++ count++
} }
if count == 3 { if count == 3 {
return x return x
} }
} }
return 0 return 0
} }

@ -3,69 +3,69 @@ package cap3
import "fmt" import "fmt"
const ( const (
_opAdd = '+' // 加 _opAdd = '+' // 加
_opMinus = '-' // 减 _opMinus = '-' // 减
_opMulti = '*' // 乘 _opMulti = '*' // 乘
_opDiv = '/' // 除 _opDiv = '/' // 除
) )
var allOperations = [4]byte{_opAdd, _opMinus, _opMulti, _opDiv} var allOperations = [4]byte{_opAdd, _opMinus, _opMulti, _opDiv}
func Ex34(x1, x2, x3, x4, x5, y int) []string { func Ex34(x1, x2, x3, x4, x5, y int) []string {
result := make([]string, 0) result := make([]string, 0)
operations := make([]byte, 4) operations := make([]byte, 4)
nums := [5]int{x1, x2, x3, x4, x5} nums := [5]int{x1, x2, x3, x4, x5}
// 一层一层尝试运算符 // 一层一层尝试运算符
for _, operations[0] = range allOperations { for _, operations[0] = range allOperations {
// 当前为除法,判断下一个数是否为0,如果是则直接跳过,下同 // 当前为除法,判断下一个数是否为0,如果是则直接跳过,下同
if operations[0] == _opDiv && nums[1] == 0 { if operations[0] == _opDiv && nums[1] == 0 {
continue continue
} }
for _, operations[1] = range allOperations { for _, operations[1] = range allOperations {
if operations[1] == _opDiv && nums[2] == 0 { if operations[1] == _opDiv && nums[2] == 0 {
continue continue
} }
for _, operations[2] = range allOperations { for _, operations[2] = range allOperations {
if operations[2] == _opDiv && nums[3] == 0 { if operations[2] == _opDiv && nums[3] == 0 {
continue continue
} }
for _, operations[4] = range allOperations { for _, operations[4] = range allOperations {
if operations[4] == _opDiv && nums[4] == 0 { if operations[4] == _opDiv && nums[4] == 0 {
continue continue
} }
// 计算表达式 // 计算表达式
p, f, q := 0, 1, nums[1] p, f, q := 0, 1, nums[1]
for i, op := range operations { for i, op := range operations {
switch op { switch op {
case _opAdd: case _opAdd:
p += f * q p += f * q
f, q = 1, nums[i+1] f, q = 1, nums[i+1]
case _opMinus: case _opMinus:
p += f * q p += f * q
f, q = -1, nums[i+1] f, q = -1, nums[i+1]
case _opMulti: case _opMulti:
q *= nums[i+1] q *= nums[i+1]
case _opDiv: case _opDiv:
q /= nums[i+1] q /= nums[i+1]
} }
} }
// 结果等于给定的数字y,添加到结果集中 // 结果等于给定的数字y,添加到结果集中
if p+f*q == y { if p+f*q == y {
text := "" text := ""
for _, num := range nums { for _, num := range nums {
text += fmt.Sprintf("%d %c ", num, operations) text += fmt.Sprintf("%d %c ", num, operations)
} }
text += fmt.Sprintf("%d = %d\n", nums[4], y) text += fmt.Sprintf("%d = %d\n", nums[4], y)
result = append(result, text) result = append(result, text)
} }
} }
} }
} }
} }
return result return result
} }

@ -1,24 +1,24 @@
package cap3 package cap3
func Ex35(boxNum int, expectWeigh, actualWeigh int) []int { func Ex35(boxNum int, expectWeigh, actualWeigh int) []int {
result := make([]int, 0) result := make([]int, 0)
// 实际值重量正常重量差 / 10 // 实际值重量正常重量差 / 10
w := (expectWeigh - actualWeigh) / 10 w := (expectWeigh - actualWeigh) / 10
// w转化为2的幂的和 // w转化为2的幂的和
for w != 0 { for w != 0 {
// k是箱子编号,从0开始, t是2的幂 // k是箱子编号,从0开始, t是2的幂
k, t := 0, 1 k, t := 0, 1
// 找到最接近w的2的k次方t,当t大于w时结束小循环 // 找到最接近w的2的k次方t,当t大于w时结束小循环
for w-t >= 0 { for w-t >= 0 {
t *= 2 t *= 2
// t是2的k次方 // t是2的k次方
k++ k++
} }
result = append(result, k-1) result = append(result, k-1)
w -= t / 2 w -= t / 2
} }
return result return result
} }

@ -1,20 +1,20 @@
package cap3 package cap3
func Ex36(num int) []int { func Ex36(num int) []int {
// 用另外一种写法,直接存能整除的数 // 用另外一种写法,直接存能整除的数
divNums := make([]int, 0) divNums := make([]int, 0)
if num%3 == 0 { if num%3 == 0 {
divNums = append(divNums, 3) divNums = append(divNums, 3)
} }
if num%5 == 0 { if num%5 == 0 {
divNums = append(divNums, 5) divNums = append(divNums, 5)
} }
if num%7 == 0 { if num%7 == 0 {
divNums = append(divNums, 7) divNums = append(divNums, 7)
} }
return divNums return divNums
} }

@ -1,24 +1,24 @@
package cap3 package cap3
func Ex37(n int) []int { func Ex37(n int) []int {
var coeff func(nums []int, n int) var coeff func(nums []int, n int)
coeff = func(nums []int, n int) { coeff = func(nums []int, n int) {
if n <= 0 { if n <= 0 {
return return
} }
// 第一个和最后一个数字肯定是1 // 第一个和最后一个数字肯定是1
nums[0] = 1 nums[0] = 1
coeff(nums, n-1) coeff(nums, n-1)
nums[n] = 1 nums[n] = 1
for i := n - 1; i > 0; i-- { for i := n - 1; i > 0; i-- {
nums[i] += nums[i-1] nums[i] += nums[i-1]
} }
} }
nums := make([]int, n+1) nums := make([]int, n+1)
coeff(nums, n) coeff(nums, n)
return nums return nums
} }

@ -1,33 +1,33 @@
package cap3 package cap3
func Ex38(k int, nums []int) { func Ex38(k int, nums []int) {
gcd := func(m, n int) int { gcd := func(m, n int) int {
a, b := m, n a, b := m, n
if m < n { if m < n {
a, b = n, m a, b = n, m
} }
r := a % b r := a % b
for r != 0 { for r != 0 {
a = b a = b
b = r b = r
r = a % b r = a % b
} }
return b return b
} }
numsLen := len(nums) numsLen := len(nums)
first, gcdNumb := 0, gcd(numsLen, k) first, gcdNumb := 0, gcd(numsLen, k)
for i := 0; i < gcdNumb; i++ { for i := 0; i < gcdNumb; i++ {
first = nums[i] first = nums[i]
startIdx := i startIdx := i
for j := 0; j < numsLen/gcdNumb; j++ { for j := 0; j < numsLen/gcdNumb; j++ {
startIdx = (startIdx + k) % numsLen startIdx = (startIdx + k) % numsLen
// 交换 // 交换
tmp := nums[startIdx] tmp := nums[startIdx]
nums[startIdx] = first nums[startIdx] = first
first = tmp first = tmp
} }
} }
} }

@ -1,10 +1,10 @@
package cap3 package cap3
func Ex39(a, b, c int) int { func Ex39(a, b, c int) int {
result := 70*a + 21*b + 15*c result := 70*a + 21*b + 15*c
for result > 105 { for result > 105 {
result -= 105 result -= 105
} }
return result return result
} }

@ -1,18 +1,18 @@
package cap3 package cap3
func Ex40(n int) int { func Ex40(n int) int {
var fab func(n int) int var fab func(n int) int
fab = func(n int) int { fab = func(n int) int {
if n == 1 { if n == 1 {
return 1 return 1
} }
if n == 2 { if n == 2 {
return 2 return 2
} }
return fab(n-1) + fab(n-2) return fab(n-1) + fab(n-2)
} }
return fab(n) return fab(n)
} }

@ -3,14 +3,14 @@ package cap3
import "math" import "math"
func Ex41(t int) (float64, float64) { func Ex41(t int) (float64, float64) {
a, b := math.Pow(3, float64(t))/4, math.Pow(3, float64(t+1))/4 a, b := math.Pow(3, float64(t))/4, math.Pow(3, float64(t+1))/4
if t%2 == 0 { if t%2 == 0 {
a -= 0.75 a -= 0.75
b += 0.75 b += 0.75
} else { } else {
a += 0.75 a += 0.75
b -= 0.75 b -= 0.75
} }
return a, b return a, b
} }

@ -1,247 +1,247 @@
package cap3 package cap3
import ( import (
"fmt" "fmt"
"strconv" "strconv"
"testing" "testing"
) )
func TestEx1(t *testing.T) { func TestEx1(t *testing.T) {
fmt.Println(Ex1(1)) fmt.Println(Ex1(1))
fmt.Println(Ex1(2)) fmt.Println(Ex1(2))
fmt.Println(Ex1(3)) fmt.Println(Ex1(3))
fmt.Println(Ex1(4)) fmt.Println(Ex1(4))
fmt.Println(Ex1(5)) fmt.Println(Ex1(5))
fmt.Println(Ex1(6)) fmt.Println(Ex1(6))
fmt.Println(Ex1(7)) fmt.Println(Ex1(7))
fmt.Println(Ex1(8)) fmt.Println(Ex1(8))
fmt.Println(Ex1(9)) fmt.Println(Ex1(9))
} }
func TestEx2(t *testing.T) { func TestEx2(t *testing.T) {
result := Ex2() result := Ex2()
for num, factors := range result { for num, factors := range result {
fmt.Printf("%d's factors are %+v\n", num, factors) fmt.Printf("%d's factors are %+v\n", num, factors)
} }
} }
func TestEx3(t *testing.T) { func TestEx3(t *testing.T) {
matrix := [][]int{ matrix := [][]int{
{1, 4, 5, 1}, {1, 4, 5, 1},
{8, 9, 6, 7}, {8, 9, 6, 7},
{1, 1, 4, 2}, {1, 1, 4, 2},
{0, 8, 2, 9}, {0, 8, 2, 9},
} }
row, col, val := Ex3(matrix) row, col, val := Ex3(matrix)
if row != -1 && col != -1 { if row != -1 && col != -1 {
fmt.Printf("(%d,%d): %d\n", row, col, val) fmt.Printf("(%d,%d): %d\n", row, col, val)
} }
} }
func TestEx5(t *testing.T) { func TestEx5(t *testing.T) {
beadsNum := 5 beadsNum := 5
step := 0 step := 0
fmt.Println("NoneRecursive: ") fmt.Println("NoneRecursive: ")
Ex5(beadsNum, AlgoTypeNoneRecursion, func(from string, to string) { Ex5(beadsNum, AlgoTypeNoneRecursion, func(from string, to string) {
step++ step++
fmt.Printf("step %d: %s -> %s\n", step, from, to) fmt.Printf("step %d: %s -> %s\n", step, from, to)
}) })
fmt.Println("----------------") fmt.Println("----------------")
step = 0 step = 0
fmt.Println("Recursive: ") fmt.Println("Recursive: ")
Ex5(beadsNum, AlgoTypeRecursion, func(from string, to string) { Ex5(beadsNum, AlgoTypeRecursion, func(from string, to string) {
step++ step++
fmt.Printf("step %d: %s -> %s\n", step, from, to) fmt.Printf("step %d: %s -> %s\n", step, from, to)
}) })
} }
func TestEx6(t *testing.T) { func TestEx6(t *testing.T) {
prev := 0 prev := 0
Ex6RecursionOutput(6, func(dividedNums []int) { Ex6RecursionOutput(6, func(dividedNums []int) {
for i, num := range dividedNums { for i, num := range dividedNums {
if i == 0 { if i == 0 {
if prev != num { if prev != num {
prev = num prev = num
fmt.Println() fmt.Println()
} }
fmt.Printf("%d", num) fmt.Printf("%d", num)
} else { } else {
fmt.Printf("+%d", num) fmt.Printf("+%d", num)
} }
} }
fmt.Print("\t\t\t") fmt.Print("\t\t\t")
}) })
fmt.Println() fmt.Println()
fmt.Println("------------") fmt.Println("------------")
result := Ex6Recursion(6) result := Ex6Recursion(6)
fmt.Println(result) fmt.Println(result)
result = Ex6NoneRecursion(6) result = Ex6NoneRecursion(6)
fmt.Println(result) fmt.Println(result)
} }
func TestEx7(t *testing.T) { func TestEx7(t *testing.T) {
num := uint64(123456) num := uint64(123456)
Ex7(num, AlgoTypeNoneRecursion, func(digit uint8) { Ex7(num, AlgoTypeNoneRecursion, func(digit uint8) {
fmt.Printf("%d ", digit) fmt.Printf("%d ", digit)
}) })
fmt.Println() fmt.Println()
Ex7(num, AlgoTypeRecursion, func(digit uint8) { Ex7(num, AlgoTypeRecursion, func(digit uint8) {
fmt.Printf("%d ", digit) fmt.Printf("%d ", digit)
}) })
fmt.Println() fmt.Println()
} }
func TestEx8(t *testing.T) { func TestEx8(t *testing.T) {
num := uint64(123456) num := uint64(123456)
Ex8(num, AlgoTypeNoneRecursion, func(digit uint8) { Ex8(num, AlgoTypeNoneRecursion, func(digit uint8) {
fmt.Printf("%d ", digit) fmt.Printf("%d ", digit)
}) })
fmt.Println() fmt.Println()
Ex8(num, AlgoTypeRecursion, func(digit uint8) { Ex8(num, AlgoTypeRecursion, func(digit uint8) {
fmt.Printf("%d ", digit) fmt.Printf("%d ", digit)
}) })
fmt.Println() fmt.Println()
} }
func TestEx9(t *testing.T) { func TestEx9(t *testing.T) {
bits := Ex9t1(137) bits := Ex9t1(137)
fmt.Printf("%d=", 137) fmt.Printf("%d=", 137)
for i, bit := range bits { for i, bit := range bits {
if bit { if bit {
fmt.Printf("2^%d + ", i) fmt.Printf("2^%d + ", i)
} }
} }
println() println()
pows := Ex9t2(137) pows := Ex9t2(137)
fmt.Printf("%d=", 137) fmt.Printf("%d=", 137)
for _, pow := range pows { for _, pow := range pows {
fmt.Printf("2^%d + ", pow) fmt.Printf("2^%d + ", pow)
} }
println() println()
} }
func TestEx10(t *testing.T) { func TestEx10(t *testing.T) {
Ex10(5, 3, func(nums []int) { Ex10(5, 3, func(nums []int) {
fmt.Printf("%+v\n", nums) fmt.Printf("%+v\n", nums)
}) })
} }
func TestEx14(t *testing.T) { func TestEx14(t *testing.T) {
num := uint64(8734112) num := uint64(8734112)
Ex14StrInput(strconv.FormatUint(num, 10), func(str string) { Ex14StrInput(strconv.FormatUint(num, 10), func(str string) {
fmt.Printf("%s-", str) fmt.Printf("%s-", str)
}) })
fmt.Println() fmt.Println()
Ex14NumInput(num, func(str string) { Ex14NumInput(num, func(str string) {
fmt.Printf("%s-", str) fmt.Printf("%s-", str)
}) })
fmt.Println() fmt.Println()
} }
func TestEx15(t *testing.T) { func TestEx15(t *testing.T) {
result := Ex15(60, 70) result := Ex15(60, 70)
for cash, cashNum := range result { for cash, cashNum := range result {
fmt.Printf("%d->%d, ", cashes[cash], cashNum) fmt.Printf("%d->%d, ", cashes[cash], cashNum)
} }
fmt.Println() fmt.Println()
result = Ex15(60, 100) result = Ex15(60, 100)
for cash, cashNum := range result { for cash, cashNum := range result {
fmt.Printf("%d->%d, ", cashes[cash], cashNum) fmt.Printf("%d->%d, ", cashes[cash], cashNum)
} }
fmt.Println() fmt.Println()
result = Ex15(60, 74) result = Ex15(60, 74)
for cash, cashNum := range result { for cash, cashNum := range result {
fmt.Printf("%d->%d, ", cashes[cash], cashNum) fmt.Printf("%d->%d, ", cashes[cash], cashNum)
} }
fmt.Println() fmt.Println()
result = Ex15(60, 130) result = Ex15(60, 130)
for cash, cashNum := range result { for cash, cashNum := range result {
fmt.Printf("%d->%d, ", cashes[cash], cashNum) fmt.Printf("%d->%d, ", cashes[cash], cashNum)
} }
fmt.Println() fmt.Println()
} }
func TestEx16(t *testing.T) { func TestEx16(t *testing.T) {
count := 0 count := 0
Ex16(func(x, x2 int) { Ex16(func(x, x2 int) {
count++ count++
fmt.Printf("%d: %d, x^2=%d\n", count, x, x2) fmt.Printf("%d: %d, x^2=%d\n", count, x, x2)
}) })
} }
func TestEx17(t *testing.T) { func TestEx17(t *testing.T) {
n, k := 10, 2 n, k := 10, 2
result := Ex17Normal(n, k) result := Ex17Normal(n, k)
fmt.Println(result) fmt.Println(result)
result = Ex17Math(n, k) result = Ex17Math(n, k)
fmt.Println(result) fmt.Println(result)
} }
func TestEx18(t *testing.T) { func TestEx18(t *testing.T) {
fmt.Println(Ex18("6451", "6637") == "42815287") fmt.Println(Ex18("6451", "6637") == "42815287")
fmt.Println(Ex18("1111", "2") == "2222") fmt.Println(Ex18("1111", "2") == "2222")
// 来个夸张点的 // 来个夸张点的
ans := "59431035264803873745814101793588195732295068254603339623610036212240642359886400430165726959529476600423448130231213495885200101414878403047792277609642" ans := "59431035264803873745814101793588195732295068254603339623610036212240642359886400430165726959529476600423448130231213495885200101414878403047792277609642"
fmt.Println(Ex18( fmt.Println(Ex18(
"953249582974085793083245237450927435989430572386540298743509843545728475284751234", "953249582974085793083245237450927435989430572386540298743509843545728475284751234",
"62345723854798175908734905872984724974984398572942345324535728479275413") == ans, "62345723854798175908734905872984724974984398572942345324535728479275413") == ans,
) )
result := Ex18type3([]uint8{6, 4, 5, 1}, 6637) result := Ex18type3([]uint8{6, 4, 5, 1}, 6637)
fmt.Println(DigitSlice2String(result) == "42815287") fmt.Println(DigitSlice2String(result) == "42815287")
} }
func TestEx19(t *testing.T) { func TestEx19(t *testing.T) {
fmt.Println(Ex19(10)) fmt.Println(Ex19(10))
fmt.Println(Ex19(100)) fmt.Println(Ex19(100))
} }
func TestEx20(t *testing.T) { func TestEx20(t *testing.T) {
matrix := Ex20(5) matrix := Ex20(5)
_printMatrix(matrix) _printMatrix(matrix)
} }
func TestEx21(t *testing.T) { func TestEx21(t *testing.T) {
matrix := Ex21(3) matrix := Ex21(3)
_printMatrix(matrix) _printMatrix(matrix)
fmt.Println("----------------") fmt.Println("----------------")
matrix = Ex21(4) matrix = Ex21(4)
_printMatrix(matrix) _printMatrix(matrix)
fmt.Println("================") fmt.Println("================")
matrix = Ex21type2(3) matrix = Ex21type2(3)
_printMatrix(matrix) _printMatrix(matrix)
fmt.Println("----------------") fmt.Println("----------------")
matrix = Ex21type2(4) matrix = Ex21type2(4)
_printMatrix(matrix) _printMatrix(matrix)
} }
func TestEx22(t *testing.T) { func TestEx22(t *testing.T) {
m := Ex22(3) m := Ex22(3)
_printMatrix(m) _printMatrix(m)
} }

@ -2,33 +2,33 @@ package cap3
// Work10 狼找兔子,返回兔子是否有幸免的机会,有则返回可能的洞穴 // Work10 狼找兔子,返回兔子是否有幸免的机会,有则返回可能的洞穴
func Work10(m, n int) (bool, []int) { func Work10(m, n int) (bool, []int) {
gcd := func(m, n int) int { gcd := func(m, n int) int {
a, b := m, n a, b := m, n
if m < n { if m < n {
a, b = n, m a, b = n, m
} }
r := a % b r := a % b
for r != 0 { for r != 0 {
a = b a = b
b = r b = r
r = a % b r = a % b
} }
return b return b
} }
r := gcd(m, n) r := gcd(m, n)
if r == 1 { if r == 1 {
return false, nil return false, nil
} }
safeHoles := make([]int, 0) safeHoles := make([]int, 0)
for i := 0; i < n; i++ { for i := 0; i < n; i++ {
if i%r != 0 { if i%r != 0 {
safeHoles = append(safeHoles, i) safeHoles = append(safeHoles, i)
} }
} }
return true, safeHoles return true, safeHoles
} }

@ -2,12 +2,12 @@ package cap3
// Work11 求n!结果中0的数量 // Work11 求n!结果中0的数量
func Work11(n int) int { func Work11(n int) int {
count := 0 count := 0
for i := 1; i <= n; i++ { for i := 1; i <= n; i++ {
for num := i; num%5 == 0; num /= 5 { for num := i; num%5 == 0; num /= 5 {
count++ count++
} }
} }
return count return count
} }

@ -1,24 +1,24 @@
package cap3 package cap3
func Work12() []int { func Work12() []int {
size := 52 size := 52
cardStatus := make([]bool, 52) cardStatus := make([]bool, 52)
start, count := 2, 0 start, count := 2, 0
for count <= 104 { for count <= 104 {
for j := start; j < size; j++ { for j := start; j < size; j++ {
if j%start == 0 { if j%start == 0 {
cardStatus[j] = !cardStatus[j] cardStatus[j] = !cardStatus[j]
count++ count++
} }
} }
} }
result := make([]int, 0) result := make([]int, 0)
for i, faceDown := range cardStatus { for i, faceDown := range cardStatus {
if !faceDown { if !faceDown {
result = append(result, i) result = append(result, i)
} }
} }
return result return result
} }

@ -3,20 +3,20 @@ package cap3
import "math" import "math"
func Work14() []int { func Work14() []int {
resultSet := make([]int, 0) resultSet := make([]int, 0)
for num := 100; num <= 999; num++ { for num := 100; num <= 999; num++ {
// 开方取整,再平方判,断是否能获得原来的数,来识别是否为完全平方数 // 开方取整,再平方判,断是否能获得原来的数,来识别是否为完全平方数
intSqrt := int(math.Sqrt(float64(num)) + 0.5) intSqrt := int(math.Sqrt(float64(num)) + 0.5)
if intSqrt*intSqrt != num { if intSqrt*intSqrt != num {
continue continue
} }
// num的百位,十位,个位数,其中有相等即可 // num的百位,十位,个位数,其中有相等即可
a, b, c := num/100, num%100/10, num%10 a, b, c := num/100, num%100/10, num%10
if a == b || a == c || b == c { if a == b || a == c || b == c {
resultSet = append(resultSet, num) resultSet = append(resultSet, num)
} }
} }
return resultSet return resultSet
} }

@ -1,33 +1,33 @@
package cap3 package cap3
func Work15() map[string]string { func Work15() map[string]string {
// 甲队成员 // 甲队成员
teamA := []string{"A", "B", "C"} teamA := []string{"A", "B", "C"}
// 乙队成员 // 乙队成员
teamB := []string{"X", "Y", "Z"} teamB := []string{"X", "Y", "Z"}
match := map[string]string{} match := map[string]string{}
// 遍历所有可能的匹配方式 // 遍历所有可能的匹配方式
for _, b := range teamB { for _, b := range teamB {
for _, a := range teamA { for _, a := range teamA {
// A不和X比赛 // A不和X比赛
if a == "A" && b == "X" { if a == "A" && b == "X" {
continue continue
} }
// C不和X或Z比赛 // C不和X或Z比赛
if a == "C" && (b == "X" || b == "Z") { if a == "C" && (b == "X" || b == "Z") {
continue continue
} }
// 如果没人匹配,当前就作为对手匹配 // 如果没人匹配,当前就作为对手匹配
if _, exists := match[b]; !exists { if _, exists := match[b]; !exists {
match[a] = b match[a] = b
} }
} }
} }
return match return match
} }

@ -1,18 +1,18 @@
package cap3 package cap3
func Work16(n int) []int { func Work16(n int) []int {
result := make([]int, 0) result := make([]int, 0)
if n%4 == 0 { if n%4 == 0 {
result = append(result, 7) result = append(result, 7)
} }
if n%7 == 0 { if n%7 == 0 {
result = append(result, 7) result = append(result, 7)
} }
if n%9 == 0 { if n%9 == 0 {
result = append(result, 9) result = append(result, 9)
} }
return result return result
} }

@ -1,10 +1,10 @@
package cap3 package cap3
func Work17(a, b, c int) int { func Work17(a, b, c int) int {
result := 70*a + 21*b + 15*c result := 70*a + 21*b + 15*c
for result > 105 { for result > 105 {
result -= 105 result -= 105
} }
return result return result
} }

@ -1,45 +1,45 @@
package cap3 package cap3
func Work18(callback func(four, five int)) { func Work18(callback func(four, five int)) {
// 检查两个数是否由9个不同的数字组成 // 检查两个数是否由9个不同的数字组成
checkDigitUnique := func(a, b int) bool { checkDigitUnique := func(a, b int) bool {
// 创建一个map来跟踪每个数字是否已经出现过 // 创建一个map来跟踪每个数字是否已经出现过
mark := map[int]bool{} mark := map[int]bool{}
// 检查第一个数的每一位数字 // 检查第一个数的每一位数字
for ; a > 0; a /= 10 { for ; a > 0; a /= 10 {
// 如果数字已经在map中,直接返回false // 如果数字已经在map中,直接返回false
if _, exists := mark[a%10]; exists { if _, exists := mark[a%10]; exists {
return false return false
} else { } else {
// map标记 // map标记
mark[a%10] = true mark[a%10] = true
} }
} }
for ; b > 0; b /= 10 { for ; b > 0; b /= 10 {
if _, exists := mark[b%10]; exists { if _, exists := mark[b%10]; exists {
return false return false
} else { } else {
mark[b%10] = true mark[b%10] = true
} }
} }
// map中的数字总数为9,返回true // map中的数字总数为9,返回true
return len(mark) == 9 return len(mark) == 9
} }
// 遍历所有的四位数 // 遍历所有的四位数
for four := 1000; four <= 9999; four++ { for four := 1000; four <= 9999; four++ {
// 计算当前四位数的两倍 // 计算当前四位数的两倍
five := 2 * four five := 2 * four
// 检查结果是否为五位数 // 检查结果是否为五位数
if 10000 <= five && five <= 99999 { if 10000 <= five && five <= 99999 {
// 调用checkUnique函数检查数字是否互不相同,条件满足则回调 // 调用checkUnique函数检查数字是否互不相同,条件满足则回调
if checkDigitUnique(four, five) { if checkDigitUnique(four, five) {
callback(four, five) callback(four, five)
} }
} }
} }
} }

@ -1,31 +1,31 @@
package cap3 package cap3
import ( import (
"math" "math"
"strings" "strings"
) )
var ( var (
_hexMap = map[byte]int{ _hexMap = map[byte]int{
'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '0': 0, '1': 1, '2': 2, '3': 3, '4': 4,
'5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9,
'A': 10, 'B': 11, 'C': 12, 'D': 13, 'E': 14, 'F': 15, 'A': 10, 'B': 11, 'C': 12, 'D': 13, 'E': 14, 'F': 15,
} }
) )
func Work19(hexStr string) int { func Work19(hexStr string) int {
// 将输入字符串转换为大写,以便匹配映射表 // 将输入字符串转换为大写,以便匹配映射表
hexStr = strings.ToUpper(hexStr) hexStr = strings.ToUpper(hexStr)
decValue := 0 decValue := 0
// 从字符串最右端开始转换每个字符 // 从字符串最右端开始转换每个字符
for i := 0; i < len(hexStr); i++ { for i := 0; i < len(hexStr); i++ {
char := hexStr[len(hexStr)-1-i] char := hexStr[len(hexStr)-1-i]
// 获取字符对应的十进制值,计算十进制 // 获取字符对应的十进制值,计算十进制
if value, exists := _hexMap[char]; exists { if value, exists := _hexMap[char]; exists {
decValue += value * int(math.Pow(16, float64(i))) decValue += value * int(math.Pow(16, float64(i)))
} }
} }
return decValue return decValue
} }

@ -1,56 +1,56 @@
package cap3 package cap3
func Work20(callback func(x, y, z int)) { func Work20(callback func(x, y, z int)) {
// 检查x, y, z是否包含1到9的所有数字各一次,且不包含0 // 检查x, y, z是否包含1到9的所有数字各一次,且不包含0
checkDigit := func(x, y, z int) bool { checkDigit := func(x, y, z int) bool {
appearCnt := make([]int, 10) // 创建一个数组来存储数字0-9的出现次数 appearCnt := make([]int, 10) // 创建一个数组来存储数字0-9的出现次数
// x的各位数字 // x的各位数字
appearCnt[x/10]++ appearCnt[x/10]++
appearCnt[x%10]++ appearCnt[x%10]++
// y的各位数字 // y的各位数字
appearCnt[y%10]++ appearCnt[y%10]++
appearCnt[y/10%10]++ appearCnt[y/10%10]++
appearCnt[y/100]++ appearCnt[y/100]++
// z的各位数字 // z的各位数字
appearCnt[z%10]++ appearCnt[z%10]++
appearCnt[z/10%10]++ appearCnt[z/10%10]++
appearCnt[z/100%10]++ appearCnt[z/100%10]++
appearCnt[z/1000]++ appearCnt[z/1000]++
// 有0,不符合条件 // 有0,不符合条件
if appearCnt[0] != 0 { if appearCnt[0] != 0 {
return false return false
} }
// 检查1-9出现次数 // 检查1-9出现次数
for _, cnt := range appearCnt { for _, cnt := range appearCnt {
if cnt != 1 { if cnt != 1 {
return false return false
} }
} }
return true return true
} }
// 双重循环遍历所有可能的x和y组合 // 双重循环遍历所有可能的x和y组合
// x从12开始到98 // x从12开始到98
for x := 12; x < 99; x++ { for x := 12; x < 99; x++ {
// y从123开始到986 // y从123开始到986
for y := 123; y < 987; y++ { for y := 123; y < 987; y++ {
// 如果乘积超过9999,停止内层循环(太大了,已经不符合条件了) // 如果乘积超过9999,停止内层循环(太大了,已经不符合条件了)
z := x * y z := x * y
if z > 9999 { if z > 9999 {
break break
} }
// 检查x, y, z各位数字情况 // 检查x, y, z各位数字情况
if checkDigit(x, y, z) { if checkDigit(x, y, z) {
// 回调结果 // 回调结果
callback(x, y, z) callback(x, y, z)
} }
} }
} }
} }

@ -3,39 +3,39 @@ package cap3
import "math" import "math"
func Work21(callback func(num, sqrt int)) { func Work21(callback func(num, sqrt int)) {
// 检查两个数是否由9个不同的数字组成 // 检查两个数是否由9个不同的数字组成
checkDigitUnique := func(a, b int) bool { checkDigitUnique := func(a, b int) bool {
// 创建一个map来跟踪每个数字是否已经出现过 // 创建一个map来跟踪每个数字是否已经出现过
mark := map[int]bool{} mark := map[int]bool{}
// 检查第一个数的每一位数字 // 检查第一个数的每一位数字
for ; a > 0; a /= 10 { for ; a > 0; a /= 10 {
// 如果数字已经在map中,直接返回false // 如果数字已经在map中,直接返回false
if _, exists := mark[a%10]; exists { if _, exists := mark[a%10]; exists {
return false return false
} else { } else {
// map标记 // map标记
mark[a%10] = true mark[a%10] = true
} }
} }
for ; b > 0; b /= 10 { for ; b > 0; b /= 10 {
if _, exists := mark[b%10]; exists { if _, exists := mark[b%10]; exists {
return false return false
} else { } else {
mark[b%10] = true mark[b%10] = true
} }
} }
// map中的数字总数为9,返回true // map中的数字总数为9,返回true
return len(mark) == 9 return len(mark) == 9
} }
for num1 := 100000; num1 < 1000000; num1++ { for num1 := 100000; num1 < 1000000; num1++ {
for num2 := 100; num2 < 1000; num2++ { for num2 := 100; num2 < 1000; num2++ {
if math.Sqrt(float64(num1)) == float64(num2) && checkDigitUnique(num1, num2) { if math.Sqrt(float64(num1)) == float64(num2) && checkDigitUnique(num1, num2) {
callback(num1, num2) callback(num1, num2)
} }
} }
} }
} }

@ -1,13 +1,13 @@
package cap3 package cap3
func Work22(nums []int) int { func Work22(nums []int) int {
size := len(nums) size := len(nums)
maxSum := 0 maxSum := 0
for i := size; i < size*2; i++ { for i := size; i < size*2; i++ {
i1, i2, i3, i4 := (i-1)%size, i%size, (i+2)%size, (i+2)%size i1, i2, i3, i4 := (i-1)%size, i%size, (i+2)%size, (i+2)%size
sum := nums[i1] + nums[i2] + nums[i3] + nums[i4] sum := nums[i1] + nums[i2] + nums[i3] + nums[i4]
maxSum = max(maxSum, sum) maxSum = max(maxSum, sum)
} }
return maxSum return maxSum
} }

@ -1,10 +1,10 @@
package cap3 package cap3
func Work23(n int) []int { func Work23(n int) []int {
digits := make([]int, 0, 16) digits := make([]int, 0, 16)
for ; n > 0; n /= 10 { for ; n > 0; n /= 10 {
digits = append(digits, n%10) digits = append(digits, n%10)
} }
return digits return digits
} }

@ -1,29 +1,29 @@
package cap3 package cap3
func Work24(callback func(num1, num2, result int)) { func Work24(callback func(num1, num2, result int)) {
check := func(x int) bool { check := func(x int) bool {
for ; x != 0; x /= 10 { for ; x != 0; x /= 10 {
n := x % 10 n := x % 10
// 如果有一个数字不是素数,直接false // 如果有一个数字不是素数,直接false
if n != 2 && n != 3 && n != 5 && n != 7 { if n != 2 && n != 3 && n != 5 && n != 7 {
return false return false
} }
} }
return true return true
} }
// num1三位数,num2一位数,遍历查找 // num1三位数,num2一位数,遍历查找
for num1 := 100; num1 <= 9999; num1++ { for num1 := 100; num1 <= 9999; num1++ {
for num2 := 1; num2 <= 0; num2++ { for num2 := 1; num2 <= 0; num2++ {
// 乘出来的结果应该是四位数 // 乘出来的结果应该是四位数
result := num1 * num2 result := num1 * num2
if 1000 <= result && result <= 9999 { if 1000 <= result && result <= 9999 {
if check(num1) && check(num2) && check(result) { if check(num1) && check(num2) && check(result) {
callback(num1, num2, result) callback(num1, num2, result)
} }
} }
} }
} }
} }

@ -1,33 +1,33 @@
package cap3 package cap3
func Work25(callback func(num1, num2, num3, num4, result int)) { func Work25(callback func(num1, num2, num3, num4, result int)) {
// 类似work24 // 类似work24
check := func(x int) bool { check := func(x int) bool {
for ; x != 0; x /= 10 { for ; x != 0; x /= 10 {
n := x % 10 n := x % 10
// 如果有一个数字不是素数,直接false // 如果有一个数字不是素数,直接false
if n != 2 && n != 3 && n != 5 && n != 7 { if n != 2 && n != 3 && n != 5 && n != 7 {
return false return false
} }
} }
return true return true
} }
// num1三位数,num2一位数,遍历查找 // num1三位数,num2一位数,遍历查找
for num1 := 100; num1 <= 9999; num1++ { for num1 := 100; num1 <= 9999; num1++ {
for num2 := 1; num2 <= 0; num2++ { for num2 := 1; num2 <= 0; num2++ {
// 乘出来的结果应该是四位数 // 乘出来的结果应该是四位数
result := num1 * num2 result := num1 * num2
if 1000 <= result && result <= 9999 { if 1000 <= result && result <= 9999 {
// 第二个乘数的两个数字位和中间的两个相乘结果 // 第二个乘数的两个数字位和中间的两个相乘结果
num2Digit1, num2Digit2 := num2%10, num2/10 num2Digit1, num2Digit2 := num2%10, num2/10
num3, num4 := num2Digit1*num1, num2Digit2*num1 num3, num4 := num2Digit1*num1, num2Digit2*num1
if check(num1) && check(num2) && check(num3) && check(num4) && check(result) { if check(num1) && check(num2) && check(num3) && check(num4) && check(result) {
callback(num1, num2, num3, num4, result) callback(num1, num2, num3, num4, result)
} }
} }
} }
} }
} }

@ -1,11 +1,11 @@
package cap3 package cap3
var _monthNames = []string{ var _monthNames = []string{
"January", "February", "March", "April", "January", "February", "March", "April",
"May", "June", "July", "August", "September", "May", "June", "July", "August", "September",
"October", "November", "December", "October", "November", "December",
} }
func Work27(n int) string { func Work27(n int) string {
return _monthNames[n-1] return _monthNames[n-1]
} }

@ -1,8 +1,8 @@
package cap3 package cap3
import ( import (
"fmt" "fmt"
"strings" "strings"
) )
// //
@ -13,84 +13,84 @@ import (
var before bool = false var before bool = false
func printString(str string) { func printString(str string) {
temp := "" temp := ""
for i := 0; i < len(str); i++ { for i := 0; i < len(str); i++ {
if i == 0 { if i == 0 {
before = false before = false
} else { } else {
if str[i-1] == '*' || str[i-1] == '/' { if str[i-1] == '*' || str[i-1] == '/' {
before = true before = true
} else { } else {
before = false before = false
} }
} }
if str[i] == '(' { if str[i] == '(' {
temp = getString(str[i:]) temp = getString(str[i:])
if i == 0 { if i == 0 {
str = temp str = temp
} else { } else {
str = str[:i] + temp str = str[:i] + temp
} }
} }
} }
fmt.Println(str) fmt.Println(str)
} }
func getString(str string) string { func getString(str string) string {
result := str result := str
temp := "" temp := ""
i := 0 i := 0
length := 0 length := 0
add := false add := false
for i = 1; i < len(str); { for i = 1; i < len(str); {
if str[i] == '+' || str[i] == '-' { if str[i] == '+' || str[i] == '-' {
add = true add = true
} }
if str[i] == '(' { if str[i] == '(' {
temp = getString(str[i:]) temp = getString(str[i:])
length = len(temp) + len(str[:i]) length = len(temp) + len(str[:i])
str = str[:i] + temp str = str[:i] + temp
if length != len(result) { if length != len(result) {
if i > 1 { if i > 1 {
i-- i--
} }
} else { } else {
i = strings.Index(str, ")") + 1 i = strings.Index(str, ")") + 1
} }
result = str result = str
continue continue
} }
if str[i] == ')' { if str[i] == ')' {
break break
} }
i++ i++
} }
result = str result = str
if before { if before {
return result return result
} }
if !add { if !add {
if i+1 < len(str) { if i+1 < len(str) {
str = str[1:] str = str[1:]
temp = str temp = str
result = str[:i-1] + temp[i:] result = str[:i-1] + temp[i:]
} else if i+1 == len(str) { } else if i+1 == len(str) {
str = str[1:] str = str[1:]
temp = str temp = str
result = str[:i-1] + temp[i:] result = str[:i-1] + temp[i:]
} }
} else { } else {
if i+1 < len(str) { if i+1 < len(str) {
if str[i+1] != '*' && str[i+1] != '/' { if str[i+1] != '*' && str[i+1] != '/' {
str = str[1:] str = str[1:]
temp = str temp = str
result = str[:i-1] + temp[i:] result = str[:i-1] + temp[i:]
} }
} else if i+1 == len(str) { } else if i+1 == len(str) {
str = str[1:] str = str[1:]
temp = str temp = str
result = str[:i-1] + temp[i:] result = str[:i-1] + temp[i:]
} }
} }
return result return result
} }

@ -1,18 +1,18 @@
package cap3 package cap3
func Work7(m, n int) int { func Work7(m, n int) int {
var ack func(m, n int) int var ack func(m, n int) int
ack = func(m, n int) int { ack = func(m, n int) int {
if m == 0 { if m == 0 {
return n + 1 return n + 1
} }
if n == 0 { if n == 0 {
return ack(m-1, 1) return ack(m-1, 1)
} }
return ack(m-1, ack(m, n-1)) return ack(m-1, ack(m, n-1))
} }
return ack(m, n) return ack(m, n)
} }

@ -1,12 +1,12 @@
package cap3 package cap3
func Work8(input string) bool { func Work8(input string) bool {
length := len(input) length := len(input)
for i := 0; i < length/2; i++ { for i := 0; i < length/2; i++ {
if input[i] != input[length-1-i] { if input[i] != input[length-1-i] {
return false return false
} }
} }
return true return true
} }

@ -2,27 +2,27 @@ package cap3
// Work9 蚂蚁爬房,求a~b路线数,动规解法,时间O(n),空间O(1) // Work9 蚂蚁爬房,求a~b路线数,动规解法,时间O(n),空间O(1)
func Work9(a, b int) int { func Work9(a, b int) int {
if a > b { if a > b {
return 0 return 0
} }
length := b - a length := b - a
if length <= 2 { if length <= 2 {
return 1 return 1
} }
// 从a开始到后两个房间路线分别有一个和两种路线 // 从a开始到后两个房间路线分别有一个和两种路线
//a+1:(a->a+1),a+2:(a->a+1->a+2, a->a+2) //a+1:(a->a+1),a+2:(a->a+1->a+2, a->a+2)
prev, prev2 := 1, 2 prev, prev2 := 1, 2
step := 0 step := 0
// 前两步已经走过了,所以len-2 // 前两步已经走过了,所以len-2
for i := 0; i < length-2; i++ { for i := 0; i < length-2; i++ {
step = prev + prev2 step = prev + prev2
// 上两个变成上一个,上一个变成下一个 // 上两个变成上一个,上一个变成下一个
prev2 = prev prev2 = prev
prev = step prev = step
} }
return step return step
} }

@ -1,107 +1,107 @@
package cap3 package cap3
import ( import (
"fmt" "fmt"
"testing" "testing"
) )
func TestWork1(t *testing.T) { func TestWork1(t *testing.T) {
result := Work1(100) result := Work1(100)
for _, b := range result { for _, b := range result {
fmt.Print(b) fmt.Print(b)
} }
fmt.Println() fmt.Println()
} }
func TestWork2(t *testing.T) { func TestWork2(t *testing.T) {
matrix := Work2([]int{5, 7, 4, 8, 9, 1}) matrix := Work2([]int{5, 7, 4, 8, 9, 1})
_printMatrix(matrix) _printMatrix(matrix)
println("----------------") println("----------------")
matrix = Work2type2([]int{5, 7, 4, 8, 9, 1}) matrix = Work2type2([]int{5, 7, 4, 8, 9, 1})
_printMatrix(matrix) _printMatrix(matrix)
} }
func TestWork3(t *testing.T) { func TestWork3(t *testing.T) {
matrix := Work3(7) matrix := Work3(7)
_printMatrix(matrix) _printMatrix(matrix)
fmt.Println("----------------") fmt.Println("----------------")
matrix = Work3(6) matrix = Work3(6)
_printMatrix(matrix) _printMatrix(matrix)
} }
func TestWork4(t *testing.T) { func TestWork4(t *testing.T) {
matrix := Work4(5) matrix := Work4(5)
_printMatrix(matrix) _printMatrix(matrix)
} }
func TestWork5(t *testing.T) { func TestWork5(t *testing.T) {
matrix := Work5(6) matrix := Work5(6)
_printMatrix(matrix) _printMatrix(matrix)
fmt.Println("----------------") fmt.Println("----------------")
matrix = Work5(5) matrix = Work5(5)
_printMatrix(matrix) _printMatrix(matrix)
fmt.Println("----------------") fmt.Println("----------------")
matrix = Work5(10) matrix = Work5(10)
_printMatrix(matrix) _printMatrix(matrix)
} }
func TestWork9(t *testing.T) { func TestWork9(t *testing.T) {
result := Work9(1, 2) result := Work9(1, 2)
println(result) println(result)
result = Work9(3, 6) result = Work9(3, 6)
println(result) println(result)
} }
func TestWork11(t *testing.T) { func TestWork11(t *testing.T) {
result := Work11(4) result := Work11(4)
println(result) println(result)
result = Work11(60) result = Work11(60)
println(result) println(result)
result = Work11(1000) result = Work11(1000)
println(result) println(result)
} }
func TestWork15(t *testing.T) { func TestWork15(t *testing.T) {
match := Work15() match := Work15()
for a, b := range match { for a, b := range match {
fmt.Println(a, " vs ", b) fmt.Println(a, " vs ", b)
} }
} }
func TestWork16(t *testing.T) { func TestWork16(t *testing.T) {
result := Work16(123) result := Work16(123)
fmt.Print("can be devide by ") fmt.Print("can be devide by ")
for _, num := range result { for _, num := range result {
fmt.Printf("%d, ", num) fmt.Printf("%d, ", num)
} }
println() println()
} }
func TestWork23(t *testing.T) { func TestWork23(t *testing.T) {
digits := Work23(123456) digits := Work23(123456)
fmt.Printf("%d digits\n", len(digits)) fmt.Printf("%d digits\n", len(digits))
for i := len(digits) - 1; i >= 0; i-- { for i := len(digits) - 1; i >= 0; i-- {
print(digits[i]) print(digits[i])
} }
println() println()
for _, digit := range digits { for _, digit := range digits {
print(digit) print(digit)
} }
println() println()
} }

Loading…
Cancel
Save