Tetris New Line algorithm: Eclectic programming second

Source: Internet
Author: User

"title":

An array int a[10] that requires a random value of 0 or 1 for each element, but these 10 elements cannot be 0 or all 1.

"description": Tetris in the need to insert a number of random squares at the bottom of the row, to increase the difficulty of the game. Of course not a row is full of squares, so you can't drop it. Also can not have no box, that is less difficult.

"Method 1" one by one random, unified judgment

Randomly generated 10 elements, if all are 0, or are 1, regenerate.

The key of the algorithm is not to generate random numbers, but how to determine the random number produced is 0? All 1? or 0 or 1 of them.

"Method 1.1" Sign method (partial method)

Add variable n1. If n1=1 indicates that 10 random numbers are all 0.

In addition to the variable N2. If n2=1 indicates that 10 random numbers are all 1.

int n1 =1, n2 = 1;
for (int i=0; i<10; i++)
{
a[i] = random(2);
if (a[i] == 0)    n2 = 0 ;
else n1 = 0;
}

if (n1 == 1 || n2 == 1) 重新来过。

"Method 1.2" holistic approach

Add all the values of the a[i] and the result is 0 for all 0, and the result is 10 for all 1.

int sum=0;
for (int i=0; i<10; i++)
{
a[i] = random(2);
sum += a[i];
}

if (sum==0 || sum == 10) 重新来过。

There are many ways to say it again:

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.