Golang-テキストを指定し、奇数行の正の数の二乗和を求めます

HENNGEの採用情報をスタックで見たので、オンラインの筆記試験を受けました。メソッドに3つの質問が与えられました。これが最初の質問です。Golangを使用してテキストを処理します。

要件は次のとおりです。

慎重に考えた後、私はルールを見つけました:

  1. 行1は、行の総数を指定します。
  2. 偶数行nは、次の行の奇数行n +1の数を指定します。
  3. 結果は、すべてのデータが入力された後に出力されます。つまり、データは最後に配列にスローされ、最後にトラバースされます。

促す:

  1. リクエストは使用できません。
  2. 基本的なライブラリのみを使用できます。

Golangのループステートメントはforから出てくるので、gotoと再帰だけが残ります。gotoを使うと地獄に行くので、再帰を使います。ゴランを学んだことがないので、序文を数時間しか読んでいません。もっと料理を書くかもしれませんが、許してください。

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
}

 

 

 

 

 

 

おすすめ

転載: blog.csdn.net/u013362192/article/details/107128724