-1

I created a map to contain sum of numbers in each file with filename as key. But after running the program, it only displays some of the files even though the total sum is correct. I am unable to find root cause. Adding the code below.

Attaching the input files below:

package main

import (
    "bufio"
    "fmt"
    "io"
    "os"
    "strconv"
    "sync"
)

type SumMap struct {
    sum map[string]int
    sync.Mutex
}

func main() {
    files := []string{"num1.txt", "num2.txt", "num3.txt", "num4.txt", "num5.txt"}

    sumMap := SumMap{}
    sumMap.sum = map[string]int{}

    var wg sync.WaitGroup

    total := 0
    for _, fileName := range files {
        file, err := os.Open(fileName)
        if err != nil {
            fmt.Printf("Unable to open %v : %v", file, err)
            return
        }
        rd := bufio.NewReader(file)
        wg.Add(1)

        calculateSum := func() {
            for {
                line, err := rd.ReadString('\n')
                if err == io.EOF {
                    wg.Done()
                    file.Close()
                    break
                }
                number, lineErr := strconv.Atoi(line[:len(line)-1])
                if lineErr == nil {
                    sumMap.Lock()
                    sumMap.sum[fileName] += number
                    sumMap.Unlock()
                }
            }
        }

        go calculateSum()
    }
    wg.Wait()
    for fileName, value := range sumMap.sum {
        fmt.Printf("Sum of all number in %v = %v\n", fileName, value)
        total += value
    }
    fmt.Println("\nTotal Sum =", total)
}

Input files can be found in this github repo: Input files

Expected Response:

Sum of all number in num1.txt = <<the sum of numbers in num1.txt>>
Sum of all number in num2.txt = <<the sum of numbers in num2.txt>>
Sum of all number in num3.txt = <<the sum of numbers in num3.txt>>
Sum of all number in num4.txt = <<the sum of numbers in num4.txt>>
Sum of all number in num5.txt = <<the sum of numbers in num5.txt>>

Total Sum = 4103109

Actual Response

Sum of all number in num2.txt = 807398
Sum of all number in num3.txt = 824497
Sum of all number in num4.txt = 771367
Sum of all number in num5.txt = 1699847

Total Sum = 4103109

The sum of numbers for num1.txt is missing, yet the total sum is correct!

Badrri
  • 11
  • 5
  • "it only displays some of the files even though the total sum is correct". What does this mean? Can you show, exactly, what the programming is outputting vs what you are expecting to see? – Hymns For Disco May 31 '22 at 06:01
  • 1
    In your case is var fileName https://stackoverflow.com/questions/69984933/goroutine-inside-for-loop-takes-only-the-last-value-of-slice – Rahmat Fathoni May 31 '22 at 06:23
  • 1
    @RahmatFathoni, the solution you pointed is working for me. I added fileName2 := fileName just after the for loop and replaced all the fileName occurrences. Thanks – Badrri May 31 '22 at 07:53

0 Answers0