C语言中如何避免数组重复值?5×5棋盘rand()去重及排除0方案
Hey there! No worries at all—every programmer starts with these kinds of questions, so let's break this down step by step to fix your 5×5 board issue.
问题根源
Your current code has two key issues:
rand() % 25produces numbers from 0 to 24, which is why you're seeing 0 values.- Since
rand()generates pseudo-random numbers, there's a high chance of duplicates when calling it 25 times in a row.
最优解决方案:Fisher-Yates 洗牌算法
The best way to get a set of unique numbers from 1 to 25 is to first create a sorted list of these numbers, then shuffle them randomly. This guarantees no duplicates and no zeros. Here's how to implement it:
Step 1: Initialize a sorted array of 1-25
First, create a 1D array that holds all numbers from 1 to 25—this gives us our full set of non-repeating, non-zero values.
Step 2: Shuffle the array with Fisher-Yates
This algorithm shuffles the array in-place, ensuring every permutation is equally likely, with no duplicates.
Step 3: Fill your 5×5 board from the shuffled array
Once shuffled, we can iterate through the 1D array and map it to your 2D board.
Modified Code
#include <stdio.h> #include <stdlib.h> #include <time.h> void createboard(int board[5][5]) { int numbers[25]; int i, temp, index; // Step 1: Fill numbers array with 1-25 for (i = 0; i < 25; i++) { numbers[i] = i + 1; } // Step 2: Fisher-Yates shuffle for (i = 24; i > 0; i--) { // Generate a random index between 0 and i (inclusive) index = rand() % (i + 1); // Swap current element with the random index element temp = numbers[i]; numbers[i] = numbers[index]; numbers[index] = temp; } // Step 3: Fill the 5x5 board from the shuffled array int count = 0; for (int rows = 0; rows < 5; rows++) { for (int columns = 0; columns < 5; columns++) { board[rows][columns] = numbers[count]; count++; } } } int main() { // Important: Call srand() ONCE at the start of your program srand(time(NULL)); int board[5][5]; createboard(board); // Test: Print the board to verify for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { printf("%3d", board[i][j]); } printf("\n"); } return 0; }
Key Notes
- Call
srand(time(NULL))only once: Placing it inmain()instead ofcreateboard()prevents resetting the random seed multiple times (which can cause repeated sequences if the function is called quickly). - Fisher-Yates is efficient: It runs in O(n) time, which is perfect for your 25-element array.
- No zeros, no duplicates: Since we start with 1-25 and just shuffle, you're guaranteed every number appears exactly once.
内容的提问来源于stack exchange,提问作者Quicky App

