Table of Contents
Efficient generation of character arrangement and combination: avoid duplication and exclude all the same
Home Backend Development PHP Tutorial How to generate non-repetitive permutation combinations based on character set and number of layers, and exclude all characters of the same combinations?

How to generate non-repetitive permutation combinations based on character set and number of layers, and exclude all characters of the same combinations?

Apr 01, 2025 am 06:57 AM
python arrangement

How to generate non-repetitive permutation combinations based on character set and number of layers, and exclude all characters of the same combinations?

Efficient generation of character arrangement and combination: avoid duplication and exclude all the same

This article describes how to generate non-repetitive permutation combinations based on a given character set and number of layers, and effectively exclude combinations where all characters are the same. For example, the character set is 'a' and 'b', which generates a combination of different layers: the first layer is 'a', 'b'; the second layer is 'ab', 'ba' (excluding 'aa', 'bb'); the third layer contains 'aab', 'aba', 'abb', 'baa', 'bab', 'bba', etc.

We will adopt two algorithm strategies: digital replacement method and backtracking method.

Method 1: Digital replacement method (more concise)

This method treats permutations as m-digit numbers. Taking the character set 'a', 'b' as an example, 'a' is 0 and 'b' is 1. Second-layer combination: 00('aa'), 01('ab'), 10('ba'), 11('bb'). Iterate through all m-digit numbers and convert them into character combinations. In order to exclude the same combination, it is determined whether the generated m-digit number can be divisible by (11...1) (the number of 1 is equal to the number of layers m).

Python code example:

 def generate_combinations(charset, layers, allow_all_same=False):
    results = []
    n = len(charset)
    all_ones = sum(n**i for i in range(layers))
    for i in range(n**layers):
        if allow_all_same or i % all_ones != 0: #Exclude combination = ""
            temp = i
            for _ in range(layers):
                combination = charset[temp % n] combination
                temp //= n
            results.append(combination)
    Return results

print(generate_combinations('ab', 2)) # ['ab', 'ba']
print(generate_combinations('ab', 2, True)) # ['aa', 'ab', 'ba', 'bb']
print(generate_combinations('ab', 3)) # ['aab', 'aba', 'abb', 'baa', 'bab', 'bba']
print(generate_combinations('abc', 2)) # ['ab', 'ac', 'ba', 'bc', 'ca', 'cb']
Copy after login

Method 2: Backtracking method (easier to understand)

Backtrace is a recursive algorithm that tries all combinations. Add a character to the current combination at each step, and recursively generates longer combinations. Use the flag to determine whether the current combination is the same character, and avoid duplication and the same combination.

Python code example:

 def generate_combinations_recursive(charset, layers, allow_all_same=False):
    results = []
    current_combination = [''] * layers

    def backtrack(index, all_same):
        if index == layers:
            if not all_same:
                results.append("".join(current_combination))
            Return
        for char in charset:
            current_combination[index] = char
            backtrack(index 1, all_same and char == current_combination[index - 1] if index > 0 else False)

    for char in charset:
        current_combination[0] = char
        backtrack(1, not allow_all_same)

    Return results


print(generate_combinations_recursive('AB', 2)) # ['AB', 'BA']
print(generate_combinations_recursive('AB', 2, True)) # ['AA', 'AB', 'BA', 'BB']
print(generate_combinations_recursive('AB', 3)) # ['AAB', 'ABA', 'ABB', 'BAA', 'BAB', 'BBA']
print(generate_combinations_recursive('ABC', 2)) # ['AB', 'AC', 'BA', 'BC', 'CA', 'CB']
Copy after login

Both methods can effectively solve the problem, and the choice depends on specific needs and preferences. The digital replacement method is simpler, and the backtracking method is easier to understand and expand.

The above is the detailed content of How to generate non-repetitive permutation combinations based on character set and number of layers, and exclude all characters of the same combinations?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1663
14
PHP Tutorial
1266
29
C# Tutorial
1239
24
PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

How to adjust the wordpress article list How to adjust the wordpress article list Apr 20, 2025 am 10:48 AM

There are four ways to adjust the WordPress article list: use theme options, use plugins (such as Post Types Order, WP Post List, Boxy Stuff), use code (add settings in the functions.php file), or modify the WordPress database directly.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

How to run sublime code python How to run sublime code python Apr 16, 2025 am 08:48 AM

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

Where to write code in vscode Where to write code in vscode Apr 15, 2025 pm 09:54 PM

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

Golang vs. Python: Performance and Scalability Golang vs. Python: Performance and Scalability Apr 19, 2025 am 12:18 AM

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

See all articles