search
HomeBackend DevelopmentGolangDetailed explanation of using Go language to find similarities and differences between two arrays

The following tutorial column of golang will introduce to you the similarities and differences of using go language to find two arrays. I hope it will be helpful to friends in need!

I recently encountered a small requirement on the project. The input is two arrays, an old array and a new array. The requirement Get all the new and deleted elements of the new array relative to the old array. For example:

输入:
arr_old: {"1", "2", "4", "5", "7", "9"}
arr_new: {"2", "3", "4", "6", "7"}
返回:
arr_added: {"3", "6"}
arr_deleted: {"1", "5", "9"}

There is no similar direct comparison method in the standard library of go. You need to implement it yourself. The simplest method is of course the old array. Go to the new array for each element. If it is not found, it is deleted. Then the elements of the new array are searched for in the old array one by one. If it is not found, it is added. However, this method is too inefficient.

Here I use an idea based on set operations, that is, to find the intersection and union of two arrays respectively. The union minus the intersection is all the changed elements (or new ones) , or deleted), traverse the elements in this set and search in the old array. If it is found in the old array, then it is the deleted element; otherwise, if it is not found, it must be found in the new array (use Without actually traversing it again), then it is the newly added element.

Above the code, there is a trick here, which is to take advantage of the uniqueness of the map key in go, use the elements of the array as the key of the map, and use map to achieve fast search.

package main

import (
	"fmt"
)

func main() {
	//fmt.Println("Hello World!")
	src := []string{"1", "2", "4", "5", "7", "9"}
	dest := []string{"2", "3", "4", "6", "7"}

	added, removed := Arrcmp(src, dest)
	fmt.Printf("add: %v\nrem: %v\n", added, removed)
}

func Arrcmp(src []string, dest []string) ([]string, []string) {
	msrc := make(map[string]byte) //按源数组建索引
	mall := make(map[string]byte) //源+目所有元素建索引

	var set []string //交集

	//1.源数组建立map
	for _, v := range src {
		msrc[v] = 0
		mall[v] = 0
	}
	//2.目数组中,存不进去,即重复元素,所有存不进去的集合就是并集
	for _, v := range dest {
		l := len(mall)
		mall[v] = 1
		if l != len(mall) { //长度变化,即可以存
			l = len(mall)
		} else { //存不了,进并集
			set = append(set, v)
		}
	}
	//3.遍历交集,在并集中找,找到就从并集中删,删完后就是补集(即并-交=所有变化的元素)
	for _, v := range set {
		delete(mall, v)
	}
	//4.此时,mall是补集,所有元素去源中找,找到就是删除的,找不到的必定能在目数组中找到,即新加的
	var added, deleted []string
	for v, _ := range mall {
		_, exist := msrc[v]
		if exist {
			deleted = append(deleted, v)
		} else {
			added = append(added, v)
		}
	}

	return added, deleted
}

Run results:

add: [6 3]
rem: [1 5 9]

We welcome everyone to exchange ideas for more efficient methods.

The above is the detailed content of Detailed explanation of using Go language to find similarities and differences between two arrays. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:csdn. If there is any infringement, please contact admin@php.cn delete
Security Considerations When Developing with GoSecurity Considerations When Developing with GoApr 27, 2025 am 12:18 AM

Gooffersrobustfeaturesforsecurecoding,butdevelopersmustimplementsecuritybestpracticeseffectively.1)UseGo'scryptopackageforsecuredatahandling.2)Manageconcurrencywithsynchronizationprimitivestopreventraceconditions.3)SanitizeexternalinputstoavoidSQLinj

Understanding Go's error InterfaceUnderstanding Go's error InterfaceApr 27, 2025 am 12:16 AM

Go's error interface is defined as typeerrorinterface{Error()string}, allowing any type that implements the Error() method to be considered an error. The steps for use are as follows: 1. Basically check and log errors, such as iferr!=nil{log.Printf("Anerroroccurred:%v",err)return}. 2. Create a custom error type to provide more information, such as typeMyErrorstruct{MsgstringDetailstring}. 3. Use error wrappers (since Go1.13) to add context without losing the original error message,

Error Handling in Concurrent Go ProgramsError Handling in Concurrent Go ProgramsApr 27, 2025 am 12:13 AM

ToeffectivelyhandleerrorsinconcurrentGoprograms,usechannelstocommunicateerrors,implementerrorwatchers,considertimeouts,usebufferedchannels,andprovideclearerrormessages.1)Usechannelstopasserrorsfromgoroutinestothemainfunction.2)Implementanerrorwatcher

How do you implement interfaces in Go?How do you implement interfaces in Go?Apr 27, 2025 am 12:09 AM

In Go language, the implementation of the interface is performed implicitly. 1) Implicit implementation: As long as the type contains all methods defined by the interface, the interface will be automatically satisfied. 2) Empty interface: All types of interface{} types are implemented, and moderate use can avoid type safety problems. 3) Interface isolation: Design a small but focused interface to improve the maintainability and reusability of the code. 4) Test: The interface helps to unit test by mocking dependencies. 5) Error handling: The error can be handled uniformly through the interface.

Comparing Go Interfaces to Interfaces in Other Languages (e.g., Java, C#)Comparing Go Interfaces to Interfaces in Other Languages (e.g., Java, C#)Apr 27, 2025 am 12:06 AM

Go'sinterfacesareimplicitlyimplemented,unlikeJavaandC#whichrequireexplicitimplementation.1)InGo,anytypewiththerequiredmethodsautomaticallyimplementsaninterface,promotingsimplicityandflexibility.2)JavaandC#demandexplicitinterfacedeclarations,offeringc

init Functions and Side Effects: Balancing Initialization with Maintainabilityinit Functions and Side Effects: Balancing Initialization with MaintainabilityApr 26, 2025 am 12:23 AM

Toensureinitfunctionsareeffectiveandmaintainable:1)Minimizesideeffectsbyreturningvaluesinsteadofmodifyingglobalstate,2)Ensureidempotencytohandlemultiplecallssafely,and3)Breakdowncomplexinitializationintosmaller,focusedfunctionstoenhancemodularityandm

Getting Started with Go: A Beginner's GuideGetting Started with Go: A Beginner's GuideApr 26, 2025 am 12:21 AM

Goisidealforbeginnersandsuitableforcloudandnetworkservicesduetoitssimplicity,efficiency,andconcurrencyfeatures.1)InstallGofromtheofficialwebsiteandverifywith'goversion'.2)Createandrunyourfirstprogramwith'gorunhello.go'.3)Exploreconcurrencyusinggorout

Go Concurrency Patterns: Best Practices for DevelopersGo Concurrency Patterns: Best Practices for DevelopersApr 26, 2025 am 12:20 AM

Developers should follow the following best practices: 1. Carefully manage goroutines to prevent resource leakage; 2. Use channels for synchronization, but avoid overuse; 3. Explicitly handle errors in concurrent programs; 4. Understand GOMAXPROCS to optimize performance. These practices are crucial for efficient and robust software development because they ensure effective management of resources, proper synchronization implementation, proper error handling, and performance optimization, thereby improving software efficiency and maintainability.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.