# Trending December 2023 # Golang Program To Compare Elements In Two Slices # Suggested January 2024 # Top 16 Popular

You are reading the article Golang Program To Compare Elements In Two Slices updated in December 2023 on the website Daihoichemgio.com. We hope that the information we have shared is helpful to you. If you find the content interesting and meaningful, please share it with your friends and continue to follow and support us for the latest updates. Suggested January 2024 Golang Program To Compare Elements In Two Slices

In this tutorial, we will learn how to compare elements in two slices. In slices a simple equality comparison is not possible so the slices are compared with their lengths and the elements present in the loop. The output will be printed in the form of Boolean value on the console with the help of fmt.Println() function. Let’s see how to execute this with the help of an example.

Method 1: Using a user-defined function

In this method, we will compare elements in two slices using an external function and, in that function, we will set some conditions, if the slices satisfy those conditions, they will be considered equal else they won’t be considered equal. Let’s have a look to get a better understanding.

Syntax func append(slice, element_1, element_2…, element_N) []T

The append function is used to add values to an array slice. It takes number of arguments. The first argument is the array to which we wish to add the values followed by the values to add. The function then returns the final slice of array containing all the values.

Algorithm

Step 1 − Create a package main and import fmt package in the program.

Step 2 − Create a main function, in it create two slices of type string and call a function named slice_equality with two slices as arguments.

Step 3 − Create a function slice_equality and in that function check if the length of the first slice is not equal to the second slice return false.

Step 4 − In the next case run a for loop till the range of str1 and check if the elements of str2 are equal to str1, if they are not equal return false.

Step 5 − After checking all the conditions set in the algorithm, if not even once false is returned, return true to the function.

Step 6 − Print the Boolean value using fmt.Println() function where ln refers to the next line here.

Example

Golang program to compare elements in two slices using custom function

package main import "fmt" func slice_equality(str1, str2 []string) bool { if len(str1) != len(str2) { return false } for i, str := range str1 { if str != str2[i] { return false } } return true } func main() { str1 := []string{"Goa", "Gujarat"} str2 := []string{"Goa", "Gujarat"} fmt.Println("The slices are equal or not before adding any element:") fmt.Println(slice_equality(str1, str2)) str2 = append(str2, "Mumbai") fmt.Println("The slices are equal or not after adding another element:") fmt.Println(slice_equality(str1, str2)) } Output The slices are equal or not before adding any element: true The slices are equal or not after adding another element: false Method 2: Using built-in function

In this method, we will use reflect.DeepEqual() function to compare two slices recursively. Built-in functions ease our work and shorten the code. The output here will be printed using fmt.Println() function. Let’s have a look and inculcate how to solve this problem.

Syntax reflect.DeepEqual()

This function compares two values recursively. It traverses and check the equality of the corresponding data values at each level. However, the solution is less safe as compared to comparison in loops. Reflect should be used with care and should be used in those cases where it’s of utmost importance.

func append(slice, element_1, element_2…, element_N) []T

The append function is used to add values to an array slice. It takes number of arguments. The first argument is the array to which we wish to add the values followed by the values to add. The function then returns the final slice of array containing all the values.

Algorithm

Step 1 − Create a package main and import fmt and reflect package in the program.

Step 2 − Create a function main and in that function create two slices of type string which are to be compared with each other.

Step 3 − In the first case before adding any new element in the slice, compare the slices using reflect.DeepEqual() function with the slices as parameters.

Step 4 − In the second case add new string in the slice and compare the slices using reflect.DeepEqual() function with the slices as parameters.

Step 5 − The output will be printed using fmt.Prinln() function on the console as a Boolean value.

Example

Golang program to compare elements in two slices using built-in function

package main import ( "fmt" "reflect" ) func main() { str1 := []string{"Goa", "Gujarat"} str2 := []string{"Goa", "Gujarat"} fmt.Println("The strings are equal or not before adding any element:") fmt.Println(reflect.DeepEqual(str1, str2)) str2 = append(str2, "Mumbai") fmt.Println("The strings are equal or not after adding any element:") fmt.Println(reflect.DeepEqual(str1, str2)) } Output The strings are equal or not before adding any element: true The strings are equal or not after adding any element: false Conclusion

In this tutorial, of comparing slices, we used two methods to execute the program. In the first method we used custom function with some conditions and in the second method we used a built-in function named reflect.DeepEqual() function.

You're reading Golang Program To Compare Elements In Two Slices

## Golang Program To Remove Repeated Elements From An Array

In this tutorial, we will write a go language program to remove duplicate elements from an array. By removing the duplicate entries, we mean that we wish to remove a value repeating multiple times. In this tutorial, we are using examples of an array of integers as well as an array of strings.

Method 1: Remove Duplicate Values from an Array using an External Function

The following code illustrates how we can remove duplicate values from an array of integers using a user-defined function.

Algorithm

Step 1 − First, we need to import the fmt package.

Step 2 − Now, make a function named removeDuplicate() that accepts an array as an argument and returns an array after removing all the duplicate entries.

Step 3 − This function uses a for loop to iterate over the array.

Step 4 − Here we have created a map that has keys as integers and values as Boolean by default the values stored by the map_var are false.

Step 5 − During each iteration from the array, we are checking the value of map_var if it is false then we have to take that value and append it into the new array created above.

Step 6 − Repeat this process until all the array values are checked and then return the new array just formed.

Step 7 − Now, we need to start the main function.

Step 8 − Initialize an array arr of integers, store values to it, and print the array on the screen.

Step 9 − Now call the removeDuplicate function by passing the array created above as an argument to it.

Step 10 − Store the result obtained in an array called result and print the array on the screen.

Example

Golang program to remove duplicate values from an array using an external function.

package main import "fmt" func removeDuplicate(arr [8]int) []int { map_var := map[int]bool{} result := []int{} for e := range arr { if map_var[arr[e]] != true { map_var[arr[e]] = true result = append(result, arr[e]) } } return result } func main() { arr := [8]int{1, 2, 2, 4, 4, 5, 7, 5} fmt.Println("The unsorted array entered is:", arr) result := removeDuplicate(arr) fmt.Println("The array obtained after removing the duplicate values is:", result) } Output The unsorted array entered is: [1 2 2 4 4 5 7 5] The array obtained after removing the duplicate values is: [1 2 4 5 7] Method 2: Remove Duplicate Elements from an Array without using the Maps

Let us now look at another example of how we can remove duplicate entries from an array without using the maps.

Algorithm

Step 1 − Import the fmt package that allows us to print anything on the screen.

Step 2 − Call the main() function.

Step 3 − Initialize and store the elements in an array of integers and print it on the screen.

Step 4 − Iterate over the array using for loops to check if the current element is equal to the next element or not.

Step 5 − If both the elements are equal then remove the duplicate element using the for loop and decrement the size of the array by 1 by doing size–

Step 6 − Once iterated over the whole array print the elements of the new array obtained on the screen using fmt.Println() function.

Example

GoLang Program to Remove Duplicate Elements from an Array.

package main import "fmt" func main() { arr := []int{1, 2, 2, 4, 4, 5, 7, 5} fmt.Println("The unsorted array entered is:", arr) size := len(arr) for i := 0; i < size; i++ { for j := i + 1; j < size; j++ { if arr[i] == arr[j] { for k := j; k < size-1; k++ { arr[k] = arr[k+1] } size-- j-- } } } fmt.Println("The elements of array obtained after removing the duplicate values is:") for i := 0; i < size; i++ { fmt.Println(arr[i]) } } Output The unsorted array entered is: [1 2 2 4 4 5 7 5] The elements of array obtained after removing the duplicate values is: 1 2 4 5 7 Conclusion

We have successfully compiled and executed a golang program to remove duplicate elements from an array along with examples.

## Golang Program To Calculate The Sum Of Columns Of Matrix Elements

A matrix is a collection of numbers arranged in rows and columns, a two-dimensional array, each of the values of this matrix is known as an element. Here we will use three methods to find the sum of column elements and compare each method for the same using go programming.

Here is an example of a matrix and the sum value of it’s columns −

The given matrix is −

0 1 2 4 5 6 8 9 7

Sum of elements in column 1 is 12

Sum of elements in column 2 is 15

Sum of elements in column 3 is 15

Algorithm

Step 1 − Import the fmt package.

Step 2 − Now we need to start the main() function.

Step 3 − Then we are creating a matrix naming matrix and assign elements to it.

Step 4 − Print the matrix on the screen using fmt.Println() function.

Step 5 − Initialize a new variable called sum of type int to hold the resultant sum.

Step 6 − To find sum of the column elements use the for loop to iterate over the matrix.

Step 7 − Using the first for loop is used to get the column of the matrix while the second for loop gives us the column of the matrix.

Step 8 − Once the loop gets over the matrix elements update the sum variable by adding values to it.

Step 9 − Print the sum of the matrix on the screen.

Example 1

In the following example, we will use a for loop to iterate over the matrix and find the sum of its elements and print it on the screen.

package main import "fmt" func main() { matrix := [][]int{ {0, 1, 2}, {4, 5, 6}, {8, 9, 7}, } fmt.Println("The given matrix is:") for i := 0; i < 3; i++ { for j := 0; j < 3; j++ { fmt.Print(matrix[i][j], "t") } fmt.Println() } fmt.Println() for i := 0; i < len(matrix[0]); i++ { sum := 0 for j := 0; j < len(matrix); j++ { sum += matrix[j][i] } fmt.Printf("Sum of elements in column %d is %dn", i+1, sum) } } Output The given matrix is: 0 1 2 4 5 6 8 9 7 Sum of elements in column 1 is 12 Sum of elements in column 2 is 15 Sum of elements in column 3 is 15 Example 2

In this example we will find the sum of the columns of matrix elements using range function.

package main import "fmt" func main() { matrix := [][]int{ {10, 1, 2}, {4, 50, 6}, {8, 9, 7}, } fmt.Println("The given matrix is:") for i := 0; i < 3; i++ { for j := 0; j < 3; j++ { fmt.Print(matrix[i][j], "t") } fmt.Println() } fmt.Println() for i := 0; i < len(matrix[0]); i++ { sum := 0 for _, row := range matrix { sum += row[i] } fmt.Printf("Sum of elements in column %d is %dn", i+1, sum) } } Output The given matrix is: 10 1 2 4 50 6 8 9 7 Sum of elements in column 1 is 22 Sum of elements in column 2 is 60 Sum of elements in column 3 is 15 Example 3

In this example we will use the recursion approach to find the sum of columns of matrix elements.

package main import "fmt" func colSum(matrix [][]int, col int) int { if col == len(matrix[0]) { return 0 } sum := 0 for i := range matrix { sum += matrix[i][col] } return sum } func main() { matrix := [][]int{ {20, 1, 22}, {43, 5, 16}, {86, 91, 10}, } fmt.Println("The given matrix is:") for i := 0; i < 3; i++ { for j := 0; j < 3; j++ { fmt.Print(matrix[i][j], "t") } fmt.Println() } fmt.Println() for i := 0; i < len(matrix[0]); i++ { fmt.Printf("Sum of elements in column %d is %dn", i+1, colSum(matrix, i)) } } Output The given matrix is: 20 1 22 43 5 16 86 91 10 Sum of elements in column 1 is 149 Sum of elements in column 2 is 97 Sum of elements in column 3 is 48 Conclusion

We have successfully compiled and executed a go language program to calculate the sum of columns of matrix elements along with examples. In the first and second example we have used for loop and range functions respectively in the main() section of the program while in the last example we have used a separate function to implement the logic.

## How To Swap Two Numbers In Golang?

In this tutorial, we will discuss swapping two numbers in Golang. We will cover two approaches: first swapping two numbers within the function and second creating a different function.

Swapping two numbers within the function Algorithm

Example

import

“fmt”

func

main

(

)

{

var

number1

,

number2

,

number3

int

number1

=

45

number2

=

63

fmt

.

Println

(

“Numbers before swapping: n Number 1 =”

,

number1

,

“n Number 2 =”

,

number2

)

number3

=

number1 number1

=

number2 number2

=

number3

fmt

.

Println

(

“Numbers after swapping:n Number 1 =”

,

number1

,

“n Number 2 =”

,

number2

,

“n(Swap within the function)”

)

}

In the above code first, we are declaring two integer variables then we are initializing the variables. In the next step, we are swapping both the integer variables within the function using the third variable. In the end, we are printing the integer variable after swapping.

Output Numbers before swapping: Number 1 = 45 Number 2 = 63 Numbers after swapping: Number 1 = 63 Number 2 = 45 (within the function) Swapping two numbers using a different function Algorithm

Example

import

“fmt”

func

swapNumbers

(

number1

,

number2

*

int

)

{

var

number3

int

number3

=

*

number1

*

number1

=

*

number2

*

number2

=

number3

}

func

main

(

)

{

var

number1

,

number2

int

number1

=

45

number2

=

63

fmt

.

Println

(

“Numbers before swapping: n Number 1 =”

,

number1

,

“n Number 2 =”

,

number2

)

swapNumbers

(

&

number1

,

&

number2

)

fmt

.

Println

(

“Numbers after swapping:n Number 1 =”

,

number1

,

“n Number 2 =”

,

number2

,

“n(Swap using different function)”

)

}

In the above code first, we are declaring two integer variables then we are initializing the variables. In the next step, we are swapping both the integer variables using the swapNumber() function. In the end, we are printing the integer variable after swapping.

Syntax number3 = *number1 *number1 = *number2 *number2 = number3

We are passing parameters as call by address so that value will get swapped globally due to which we are putting * in front of number 1 and number2. And in the above code, we are using a third variable to do the swapping. Storing number1 in number3 then number2 in number1 and then number3 in number1.

Output Numbers before swapping: Number 1 = 45 Number 2 = 63 Numbers after swapping: Number 1 = 63 Number 2 = 45 (within the function) Swapping two numbers with one line of code

Golang supports a syntax using which we can swap two variables in one line.

Syntax Variable1, variable2 = variable2, variable1 Example

import

“fmt”

func

main

(

)

{

var

number1

,

number2

int

number1

=

45

number2

=

63

fmt

.

Println

(

“Numbers before swapping: n Number 1 =”

,

number1

,

“n Number 2 =”

,

number2

)

number1

,

number2

=

number2

,

number1

fmt

.

Println

(

“Numbers after swapping:n Number 1 =”

,

number1

,

“n Number 2 =”

,

number2

,

“n(Swap using a one-liner syntax)”

)

}

In the above code first, we are declaring two integer variables then we are initializing the variables. In the next step, we are swapping both the integer variables using the one-line syntax supported by Golang. In the end, we are printing the integer variable after swapping

Syntax number1, number2 = number2, number1 –

As Golang supports initializing multiple variables at the same time so here in this line we are initializing number1 with number2 and number2 with number1.

Output Numbers before swapping: Number 1 = 45 Number 2 = 63 Numbers after swapping: Number 1 = 63 Number 2 = 45 (Swap using a one-liner syntax)

In these ways, we can swap two numbers in Golang. The separate function or one-liner lies under good programming standards. To learn more about Golang you can follow this tutorials.

## How To Add Two Binary Strings In Golang?

This tutorial will show how we can add two binary strings in Golang. Also, we will cover and understand all the cases while adding two strings using examples.

Example

Algorithm

Example

import

“fmt”

func

(

string1

,

string2 string

)

string

{

return

(

string2

,

string1

)

}

difference

:

=

len

(

string2

)

len

(

string1

)

for

i

:

=

0

;

i

<

difference

;

i

++

{

string1

=

“0”

+

string1

}

carry

:

=

“0”

:

=

“”

/*

For

example

,

100

” and ”

110

.

So

,

for

the last characters in the string i

.

e “

0

” and “

0

” the first

else

if

condition will

run

.

Then

for

the middle characters i

.

e “

0

” and “

1

” the last

else

if

condition will run and

for

the first characters i

.

e “

1

” and “

1

” the first

if

condition will run

.

*

/

if

string1

[

i

]

==

‘1’

&&

string2

[

i

]

==

‘1’

{

if

carry

==

“1”

{

=

“1”

+

}

else

{

=

“0”

+

=

“1”

}

}

else

if

string1

[

i

]

==

‘0’

&&

string2

[

i

]

==

‘0’

{

if

carry

==

“1”

{

=

“1”

+

=

“0”

}

else

{

=

“0”

+

}

}

else

if

string1

[

i

]

!=

string2

[

i

]

{

if

carry

==

“1”

{

=

“0”

+

}

else

{

=

“1”

+

}

}

}

if

carry

==

“1”

{

=

“1”

+

}

return

}

func

main

(

)

{

var

string1

,

string2 string

string1

=

“10101”

string2

=

“100111”

result

:

=

(

string1

,

string2

)

fmt

.

Println

(

“The Numeric representation of”

,

string1

,

“is”

,

“21.”

)

fmt

.

Println

(

“The Numeric representation of”

,

string2

,

“is”

,

“39.”

)

fmt

.

Println

(

,

string1

,

“and”

,

string2

,

“is”

,

result

,

“whose value in numeric is 60.”)

}

In the above code, the main logic resides in binaryAdditionOfStrings() function so we will discuss it line by line.

Output The numeric representation of 10101 is 21. The numeric representation of 100111 is 39. The binary addition of 10101 and 100111 is 111100 whose value in numeric is 60.

## Golang Program To Create Directories

Golang has internal packages like os and io packages for creating a new directory. Here, we will create a directory using two examples. In the first example we will use os.Mkdir function and in the second example we will use ioutil.WriteFile function to execute the program.

Method 1: Using os.Mkdir Function

In this method, a directory named dirName variable is created using the os.Mkdir function. The permission bits for the new directory are the second input to os.Mkdir, which we set to 0755. (read, write, and execute permissions for the owner and read and execute permissions for others). The program will print “Directory created successfully!” if the directory creation is successful otherwise it will produce an error message.

Syntax os.Mkdir()

The os.Mkdir function in Go helps in creating a new directory with the specified name and permission bits (mode).

Algorithm

Step 1 − Create a package main and declare fmt(format package),and os package in the program where main produces executable codes and fmt helps in formatting input and output.

Step 2 − Create a directoryname variable and assign it to the newdir one wants to create.

Step 3 − Use os.Mkdir function to create a new directory.

Step 4 − If an error persists while creating the directory, print the error on the console using fmt.Println() function where ln means new line and return.

Step 5 − If the directory is created successfully, Print the success message using the statement used in Step4.

Example

In this example we will use os.Mkdir function to create new directory.

package main import ( "fmt" "os" ) func main() { directoryname := "newdir" err := os.Mkdir(directoryname, 0755) if err != nil { fmt.Println(err) return } fmt.Println("Directory created successfully!") } Output Directory created successfully! Method 2: Using io/ioutil Package

In this method, an empty file with the name and permission bits is created using the ioutil.WriteFile function. If the function returns a nil error and the file is successfully created, we will print success. The WriteFile function will create the directory and if an error comes while creating a directory, we will print the error message.

Syntax Ioutil.WriteFile()

The ioutil.WriteFile function in Go is used to write a byte slice to a file.

Algorithm

Step 1 − Create a package main and declare fmt(format package), io/ioutil package in the program where main produces executable codes and fmt helps in formatting input and output.

Step 2 − Create the function main and in that function create a variable directoryname and assign it to newdir.

Step 3 − Use ioutil package function iouti.WriteFile function to create a directory.

Step 4 − If an error comes while creating the directory, print the error on the console and return.

Step 5 − If the directory is created successfully, print the success statement on the console.

Step 6 − The print statement is executed fmt.Println() function where ln means new line.

Example

In this example, we will use io/ioutil package function to create new directory.

package main import ( "fmt" "io/ioutil" ) func main() { directoryname := "newdir" err := ioutil.WriteFile(directoryname, []byte(""), 0755) if err != nil { fmt.Println(err) return } fmt.Println("Directory created successfully!") } Output Directory created successfully! Conclusion

We executed the program of creating a directory using two methods. In the first method we used os.Mkdir function and in the second method we used io/ioutil package to execute the program.

Update the detailed information about Golang Program To Compare Elements In Two Slices on the Daihoichemgio.com website. We hope the article's content will meet your needs, and we will regularly update the information to provide you with the fastest and most accurate information. Have a great day!