js和go生成6位不重复发字符串

作者:admin 发布日期:2024年1月12日 15:22 浏览量:69

js代码:

function generateUniqueString() {
  const letters = 'abcdefghijklmnopqrstuvwxyz';
  const letterNumberCombination = 'abcdefghijklmnopqrstuvwxyz0123456789';
  
  let uniqueString = letters.charAt(Math.floor(Math.random() * letters.length));
  
  for (let i = 1; i < 6; i++) {
    uniqueString += letterNumberCombination.charAt(Math.floor(Math.random() * letterNumberCombination.length));
  }
  
  return uniqueString;
}

// 示例使用
const uniqueString = generateUniqueString();
console.log("Generated Unique String:", uniqueString);

go代码:

package main

import (
	"fmt"
	"math/rand"
	"time"
)

const letterBytes = "abcdefghijklmnopqrstuvwxyz"

func generateUniqueString() string {
	rand.Seed(time.Now().UnixNano())

	// 生成以字母开头的字符串
	firstChar := string(letterBytes[rand.Intn(len(letterBytes))])

	// 生成字母+数字组合的5位字符串
	letterNumberPart := generateRandomString(5)

	// 拼接生成的字符串
	uniqueString := firstChar + letterNumberPart

	return uniqueString
}

func generateRandomString(length int) string {
	const letterNumberBytes = "abcdefghijklmnopqrstuvwxyz0123456789"
	b := make([]byte, length)
	for i := range b {
		b[i] = letterNumberBytes[rand.Intn(len(letterNumberBytes))]
	}
	return string(b)
}

func main() {
	uniqueString := generateUniqueString()
	fmt.Println("Generated Unique String:", uniqueString)
}