TheAlgorithms/Go · error

contains same character

Error message

%q contains same character %q

What it means

NewPolybius requires unique characters in the (truncated, uppercased) alphabet; a repeated rune would map several key positions to the same coordinate, so the constructor reports the suffix containing the duplicate.

Solutions

  1. Deduplicate chars before passing them (e.g. preserve first occurrence order)
  2. Use a standard 25-letter alphabet with I/J merged
  3. Reject user-supplied alphabets containing duplicates
Defensive patterns

Strategy: validation

When it happens

Trigger: Thrown at cipher/polybius/polybius.go:41 when the library encounters an invalid state.

Common situations: See trigger scenarios.


AI-assisted analysis of TheAlgorithms/Go@5ba447ec5f (2026-09-02). Data as JSON: /api/errors/76dfd1052a86472d. Report an issue: GitHub.

Appendix: source

Thrown at cipher/polybius/polybius.go:41

// If the size of "chars" is longer than "size",
// "chars" are truncated to "size".
func NewPolybius(key string, size int, chars string) (*Polybius, error) {
	if size < 0 {
		return nil, fmt.Errorf("provided size %d cannot be negative", size)
	}
	key = strings.ToUpper(key)
	if size > len(chars) {
		return nil, fmt.Errorf("provided size %d is too small to use to slice string %q of len %d", size, chars, len(chars))
	}
	for _, r := range chars {
		if (r < 'a' || r > 'z') && (r < 'A' || r > 'Z') {
			return nil, fmt.Errorf("provided string %q should only contain latin characters", chars)
		}
	}
	chars = strings.ToUpper(chars)[:size]
	for i, r := range chars {
		if strings.ContainsRune(chars[i+1:], r) {
			return nil, fmt.Errorf("%q contains same character %q", chars[i+1:], r)
		}
	}

	if len(key) != size*size {
		return nil, fmt.Errorf("len(key): %d must be as long as size squared: %d", len(key), size*size)
	}
	return &Polybius{size, chars, key}, nil
}

// Encrypt encrypts with polybius encryption
func (p *Polybius) Encrypt(text string) (string, error) {
	encryptedText := ""
	for _, char := range strings.ToUpper(text) {
		encryptedChar, err := p.encipher(char)
		if err != nil {
			return "", fmt.Errorf("failed encipher: %w", err)
		}
		encryptedText += encryptedChar

View on GitHub (pinned to 5ba447ec5f)