Random generation with Bugs does not repeat 1-9 of the code

Source: Internet
Author: User
#include "pch.h" #include "stdio.h" #include "stdlib.h" #include "time.h" int m[9] = {0};int main (void) {Srand (time (0)); for (int i = 1; i < ten; i++) {M[i-1] = rand ()%9+1;for (int j = 0; J < I-1, J + +) {while (m[j] = = M[i-1]) {m[i-1] = rand ()% 9 + 1;}} for (int i = 0; i < 9; i++) {printf ("%d", M[i]);}}

  

The general idea is no problem, produce a random number, we assume it at M[i-1] position, then need from m[0] to m[i-2] and m[i-1] in order to determine whether the random number has been generated before.

while (m[j] = = M[i-1]) {m[i-1] = rand ()% 9 + 1;}

However, this paragraph is problematic, when encountering a random number that has already been generated before, and then produce a new random number, and at this time M[j] J value may not start from 0, so m[j] from the current value of J to M[i-2], and less m[0]~m[j-1] judgment, which is the root cause of the bug.

Random generation with Bugs does not repeat 1-9 of the code

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.