Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

nanoid.ASCII doesn't have a flat distribution and isn't using the full charset #9

Closed
37sprinkles opened this issue May 7, 2024 · 1 comment

Comments

@37sprinkles
Copy link

Notice the lack of numbers and lowercase letters in the below sample. Using go 1.22.2 and github.com/jaevor/go-nanoid v1.4.0

	generator, err = nanoid.ASCII(32)
	if err != nil {
		panic(err)
	}

	for range 10 {
		fmt.Println(generator())
	}

Result:

IJ!YZQ#YI@}}~Q@},AJB~}AR+Q?RBIIB
?}!}R,~?YQ,I!R,IR,BA#A+~}A+AYQ@A
#~@!Y}IQ#JQ,QQBYBRQI}}#,QZZB}YB~
BI?J,Y+YI@~+Y#??Q@ZYY+Y?@#YJ}AR+
B+,A}Z@IQZZIA,!!#}!ZB?Y,I#Q}IA!!
}~RQBI@+AZ~@B}RB~?~,?}#R}AQ@B}AA
RQ}I+A#YAQB~Y?I}BI!~I!Q?,QI~??YY
@Q+}~!,R}~,RJ#+?+#@#IJJI~!J!Z@YA
?~!~!IQB~+YI~,I~#}!BZ+!?#JZ!YJ?,
#Y}!@~~R#YZ}Y,A!+}!JZ!RAQ?RQ+IJ+

It fails the below test that I added manually in my local environment.

func TestASCIIFlatDistribution(t *testing.T) {
	tries := 500_000

	length := 90
	hits := make(map[rune]int)

	f, err := nanoid.ASCII(length)
	if err != nil {
		panic(err)
	}

	for i := 0; i < tries; i++ {
		id := f()
		for _, r := range id {
			hits[r]++
		}
	}

	for _, count := range hits {
		require.InEpsilon(t, length*tries/90, count, 0.01, "should have flat-distribution")
	}
}
@jaevor
Copy link
Owner

jaevor commented Jun 3, 2024

Nice catch, thanks. I've made the function just forward to CustomASCII for now, and added this test, which for some reason barely satisfies the 0.01 requirement, reaching mostly 0.01-0.0125 for me. Idk, so it's sitting at 0.015 for now. 46eb13d.

@jaevor jaevor closed this as completed Jun 3, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants