Golang. Sum of consecutive numbers


The problem is to find in an array of integers a sequence of consecutive numbers whose sum is equal to n.

Our program will read a list of integers (e.g., 5 2 3 4 6 1 4 10 1), followed by one integer n (e.g., 7). Example output:

5 2 3 4 6 1 4 10 1
7
5 + 2 = 7
3 + 4 = 7
6 + 1 = 7

If there is no sequence, we output “There is no solution”.

Code:

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

func getNum(r *bufio.Reader) []int {
	input, _ := r.ReadString('\n')

	input = strings.TrimSpace(input)

	nStr := strings.Split(input, " ")

	var nInt []int

	for _, v := range nStr {
		n, _ := strconv.Atoi(v)
		nInt = append(nInt, n)
	}

	return nInt
}

func main() {
	r := bufio.NewReader(os.Stdin)

	nums := getNum(r)
	numStr, _ := r.ReadString('\n')
	numStr = strings.TrimSpace(numStr)
	n, _ := strconv.Atoi(numStr)

	// check summ of 2 nums to find out n

	var sum int
	var nlist []int
	success := false

	for i := 0; i < len(nums); i++ {
		nlist = nil
		sum = 0
		for j := i; j < len(nums); j++ {
			nlist = append(nlist, nums[j])
			sum += nums[j]
			if sum == n {
				for v := 0; v < len(nlist); v++ {
					if v+1 < len(nlist) {
						fmt.Printf("%d + ", nlist[v]) // to put +
					} else {
						fmt.Printf("%d", nlist[v]) // last element
					}
				}
				fmt.Printf(" = %d\n", n)
				success = true
				break
			}

		}
	}
	if !success {
		fmt.Println("There is no solution")
	}
}

 


This entry was posted in Go (en). Bookmark the permalink.

Leave a Reply

🇬🇧 Attention! Comments with URLs/email are not allowed.
🇷🇺 Комментарии со ссылками/email удаляются автоматически.