DEV Community

vinay
vinay

Posted on

1

Golang TwoSum

package main

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

func BruteForce(nums []int, target int) []int {
    IntSlice := new([]int)
    // using linear search chek
    for index1, Num1 := range nums {
        for index2, Num2 := range nums {
            //if both the number add == target and index not same then append to IntSlice
            if Num1+Num2 == target && index1 != index2 {
                *IntSlice = append(*IntSlice, index1)
            }
        }
    }
    return *IntSlice
}
func HashMap(nums []int, target int) []int {
    //Hashmap store the complement and index
    //3,2,3 -->6
    see := make(map[int]int)
    //map[]

    //result
    IntSlice := new([]int)
    //chek the complement if true append both index to IntSlice if not update to Hashmap
    for Cindex := 0; Cindex < len(nums); Cindex++ {
        // 3:=6-3
        r := target - nums[Cindex]
        //val,bool:=map[key]
        index, ok := see[r]
        if ok {
            *IntSlice = append(*IntSlice, index, Cindex)
            //0,2
        }
        //update to Hashmap
        //complement=index
        //
        //map[3:0,2:1,]
        see[nums[Cindex]] = Cindex
    }
    return *IntSlice

}

func main() {
    reader := bufio.NewReader(os.Stdin)
    //using reader read the input by using readline
    fmt.Print("Please enter your Slice Numbers: ")
    //example:
    //Please enter your Slice Numbers:2 7 11 6
    val, _, _ := reader.ReadLine()
    //ReadLine return byte,bool,error

    //convert byte to string
    Readline := strings.TrimSpace(string(val))

    //split convert string to slice_string
    input1 := strings.Split(Readline, " ")
    var a []int
    for i := 0; i < len(input1); i++ {
        intnum, err := strconv.Atoi(input1[i])
        if err != nil {
            log.Fatal(err)
        }
        a = append(a, intnum)
    }

    //convert byte to string
    fmt.Print("Please enter your target Number : ")
    var w int
    fmt.Scanln(&w)
    output := HashMap(a, w)
    fmt.Println("Hash map Two Sum is :", output)
    output2 := BruteForce(a, w)
    fmt.Println("Bruit_Force Two Sum is :", output2)

}

Enter fullscreen mode Exit fullscreen mode

unit test of about code

package main

import (
    "reflect"
    "testing"
)

func TestHashMap(t *testing.T) {
    type args struct {
        nums   []int
        target int
    }
    tests := []struct {
        name string
        args args
        want []int
    }{
        {
            name: "CHEk",
            args: args{
                nums:   []int{2, 7, 11, 15},
                target: 9,
            },
            want: []int{0, 1},
        }, {
            name: "CHEk",
            args: args{
                nums:   []int{3, 2, 4},
                target: 6,
            },
            want: []int{1, 2},
        }, {
            name: "CHEk",
            args: args{
                nums:   []int{3, 3},
                target: 6,
            },
            want: []int{0, 1},
        },
    }
    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            if got := HashMap(tt.args.nums, tt.args.target); !reflect.DeepEqual(got, tt.want) {
                t.Errorf("HashMap() = %v, want %v", got, tt.want)
            }
        })
    }
}

Enter fullscreen mode Exit fullscreen mode

Heroku

Amplify your impact where it matters most — building exceptional apps.

Leave the infrastructure headaches to us, while you focus on pushing boundaries, realizing your vision, and making a lasting impression on your users.

Get Started

Top comments (0)

Image of DataStax

AI Agents Made Easy with Langflow

Connect models, vector stores, memory and other AI building blocks with the click of a button to build and deploy AI-powered agents.

Get started for free

👋 Kindness is contagious

If this article connected with you, consider tapping ❤️ or leaving a brief comment to share your thoughts!

Okay