Golang-指定文本,求奇數行正數平方和

在stack看到HENNGE公司的招聘信息,於是去參加了一次線上筆試。對方法發了三道題,此爲第一道題——使用Golang處理文本。

下爲要求:

仔細思考後,發現一個規律:

  1. 第1行指定總行數;
  2. 偶數行n指定下一行奇數行n+1行的個數;
  3. 全部數據喂完後出結果,意味着最後是扔進數組,放到最後遍歷。

提示:

  1. 要求不能使用for;
  2. 只能使用基本庫。

因爲Golang的循環語句出來了for,只剩下goto和遞歸。因爲用goto會下地獄,因此我用遞歸。因爲沒學過Golang,只看了幾個小時的語句介紹,可能寫的比較菜,見諒。

package main

import (
	"fmt"
	"io/ioutil"
	"regexp"
	"strconv"
	"strings"
)

var output []int

func main() {
	var err1 error
	var testfile0 []string

	// That's the test file name
	// this demo get data from the test.txt
	file, err1 := ioutil.ReadFile("./test.txt")
	if err1 != nil {
		fmt.Println(err1)
	}

	testfile0 = strings.Split(string(file), "\r\n")

	total, _ := strconv.Atoi(testfile0[0])
	count := 0
	m := 0
	list(m, testfile0, count, total)
	// fmt.Println(output)
	outPrint(0, output)
}

func squareSum(n int, arr []string) int {
	// fmt.Println("傳進來的參數,代表個數:", n)
	// fmt.Println("此時指定奇數行的值:", arr[n-1])
	num, _ := strconv.Atoi(arr[n-1])

	if n == 1 {
		num1, _ := strconv.Atoi(arr[0])
		// fmt.Println("最後一個的平方:", num1*num1)
		return num1 * num1
	}
	if num >= 0 {
		// fmt.Println("平方:", num*num)
		return num*num + squareSum(n-1, arr)
	}

	return squareSum(n-1, arr)

}

func outPrint(i int, output []int) {

	if i+1 > len(output) {
		return
	}
	// fmt.Println("i", i)
	// fmt.Println("output[i]", output[i])
	fmt.Println(output[i])
	i++
	outPrint(i, output)
	return
}

func list(m int, testfile0 []string, count int, total int) {
	if m+1 >= len(testfile0) {
		// fmt.Println(count)
		if count == total {
			fmt.Println("success, the first line number equal the test line ")
			return
		}
		fmt.Println("error, the first line number not equal the test line")
		return

	}

	if (m+1)%2 == 0 {
		var sum int = 0
		// fmt.Println("m:", m)
		// fmt.Println("testfile0[m+1]:", testfile0[m+1])
		pretext := regexp.MustCompile(`\s`)

		text := pretext.ReplaceAllString(testfile0[m+1], `,`)
		// fmt.Println("得到的數組:", text)
		// fmt.Println("上一行,指定的數字個數:", testfile0[m])

		var arr []string = strings.Split(text, ",")
		num, _ := strconv.Atoi(testfile0[m])
		sum = squareSum(num, arr)

		count++
		// fmt.Println("total:", sum)
		output = append(output, sum)
		// fmt.Println(output)
		// outPrint(0, output)
		// return output
	}

	m++
	list(m, testfile0, count, total)
	// fmt.Println(output)
	return
}

 

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章