Drill

ProblemsGo › validation

Score a password

mediumvalidationStringsGo

The sign-up form shows a strength meter with five segments, one for each rule the password satisfies.

passwordScore(password: string) → int

Go needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.

Solve it in Python →

Where you start

func passwordScore(password string) int {
	
}

Worked examples

CallResult
passwordScore("abc")1
passwordScore("abcdefgh")2
passwordScore("Abcdefg1")4
passwordScore("Abcdefg1!")5

Hint

Five independent booleans, added up. No early returns.

Reference solution in Go
func passwordScore(password string) int {
	lower, upper, digit, other := false, false, false, false
	for i := 0; i < len(password); i++ {
		c := password[i]
		switch {
		case c >= 'a' && c <= 'z':
			lower = true
		case c >= 'A' && c <= 'Z':
			upper = true
		case c >= '0' && c <= '9':
			digit = true
		default:
			other = true
		}
	}
	n := 0
	if len(password) >= 8 {
		n++
	}
	for _, f := range []bool{lower, upper, digit, other} {
		if f {
			n++
		}
	}
	return n
}

The same problem in another language

More validation problems in Go