aiweek-reconstruction/tools/algorithm.go

94 lines
1.8 KiB
Go
Raw Normal View History

2024-05-18 01:46:35 +08:00
package tools
import (
"log"
"os"
"sort"
)
//去除两个切片中的重复值
func ExcludeSlice(slice1, slice2 []string) []string {
// 创建一个map用于存储slice1中的所有元素
elementsInSlice1 := make(map[string]bool)
for _, v := range slice1 {
elementsInSlice1[v] = true
}
// 创建一个新的切片,用于存放结果
var result []string
for _, v := range slice2 {
// 如果元素不在slice1中则添加到结果切片中
if _, exists := elementsInSlice1[v]; !exists {
result = append(result, v)
}
}
return result
}
//反转切片
func ReverseSlice(s []string) []string {
length := len(s)
reversed := make([]string, length)
for i, v := range s {
reversed[length-i-1] = v
}
return reversed
}
//去掉切片中的空字符串
func RemoveEmptyStrings(s []string) []string {
var nonEmptyStrings []string
for _, str := range s {
if str != "" {
nonEmptyStrings = append(nonEmptyStrings, str)
}
}
return nonEmptyStrings
}
//slice每个元素中的换行符去掉
func RemoveNewlineElements(slice []string) []string {
var cleanSlice []string
for _, s := range slice {
if s != "\n" && s != "" {
cleanSlice = append(cleanSlice, s)
}
}
return cleanSlice
}
//slice每个元素中添加一个换行符
func AddNewlineToEachElement(slice []string) []string {
var newSlice []string
for _, s := range slice {
newSlice = append(newSlice, s+"\n")
}
return newSlice
}
//文件名排序
func ReadFilename(directory string) string {
entries, err := os.ReadDir(directory)
if err != nil {
log.Printf("读取目录失败,错误是:%v", err)
return ""
}
var s []string
// 遍历目录条目并打印文件名
for _, entry := range entries {
// 使用entry.Name()获取文件名
s = append(s, entry.Name())
}
sort.Strings(s)
readyToDelete := s[0]
return readyToDelete
}