Generate Truth Combination "Java implementation"

Source: Internet
Author: User

/** * Problem Description: Prints all truth combinations for a given n boolean variable. * For example, n = 2 o'clock, all truth combinations are (true, false), (true, True), (false, True), (false, False). * * Basic idea of the algorithm: * Use an array of length n to store n boolean variables; bit 1 means true, bit 0 means false, * generates each truth tuple, actually generates an array of 0 and 1. * * Generate a method for each truth tuple: Start with zero and add one at a successive.  * For example, 001, 010, 011, 101, 111 * * Specific algorithm: * Each time starting from the lowest bit, the lowest bit as "one" Processing: *① If the lowest bit is 0, then 1 can be "not carry"; *② if the lowest bit is 1, then 0; Because of the carry, further lower the lower as "one" processing. * Until a certain person from 0 to 1 "Do not carry". * * For example: 011: *① The lowest bit is 1, set 0, keep the position, *② the lower is 1, set 0, keep the position, the *③ secondary low is 0, set 1. The result is 100 * * * Tip: *① Since this only involves placing 1 or 0, it is actually set to TRUE or FALSE, * Therefore, you can store the Boolean value directly in the array, it is not necessary to convert between 1,0 and true, false. * *② set an end identifier variable Endflag, when 1..1-0..0 is set to TRUE * */package algorithm; Import Java.io.bufferedreader;import Java.io.ioexception;import Java.io.InputStreamReader;       public class Combination {private boolean[] combination;       Private Long Count;             Private Boolean Endflag; Public combination (inT n) {if (n <= 0) throw new illegalargumentexception ("parameter must be a positive integer");                     if (combination = = null) {combination = new boolean[n];                     Count = 0;              Endflag = false;        }}/** * Solve the problem and print all the truth combination results. * */public void solution () {System.out.println ("n =" + combination.length + "* * * * All true              Value combination: ");                     do {System.out.println (Getonetuple ());                     count++;                         Increone ();              } while (!terminate ());       System.out.println ("Truth combination Number:" + count); }/** * Successive plus one to generate each truth tuple * */private void Increone () {int              I                     for (i=0; i < combination.length; i++) {//If 0, then 1, end.                        if (combination[i] = = False) {    Combination[i] = true;                     Break                            } else {//if 1, then 0, and the same processing via i++ to sub-low                     Combination[i] = false;              }}//By 1..1-0..0, set endflag = true;       if (i = = combination.length) {Endflag = true;}        }/** * Converted to a Boolean array representing the generated truth tuple based on an integer array representing the generated truth tuple.           * */Private String getonetuple () {StringBuilder tuple = new StringBuilder (");                  for (int i=0; i < combination.length; i++) {tuple.append (combination[i]);             Tuple.append (",");           }//delete the extra comma Tuple.deletecharat (Tuple.length ()-1);           Tuple.append (")");    return tuple.tostring ();    }/** * Termination condition: End identifier Endflag = true;    * */Private Boolean terminate () {return endflag = = true; } PUBlic static void Main (string[] args) {BufferedReader stdin = new BufferedReader (New InputStreamReader (System              . in));                     try {String s = null;                               while ((s = stdin.readline ()). Matches ("[1-9][0-9]*")) {int n = integer.parseint (s);                            System.out.println ("n =" + N);                            Combination C = new combination (n);                     C.solution ();              }} catch (IOException e) {e.printstacktrace ();                     } catch (Exception e) {System.out.println (E.getmessage ());              E.printstacktrace ();       }//combination C = new combination (3);//C.solution (); }      }

  

Algorithm Analysis:

The total run time consists of two parts: a processing time and a judgment end time.

T (n) = Setbit (n) + judgeend (n)

Where: Judgeend (n) = 2^n, because every transformation from 0..0, 1..1, 0..0 makes a simple comparison operation, Endflag = True, total spend 2^n

The following calculation setbit (n):

n = 1 O'Clock 0, 1 setbit (1) = 1;

n = 2 o'clock 00-> setbit (2) = 121 "Position count: 1+2+1"

n = 3 o'clock 000–> 001, 010, 011, 101----111 setbit (3) = 1213121

n = 4 o'clock 0000, 0001, 0010, 0011, 0100, 0101--0110, 0111-- 1111 Setbit (4) = 121312141213121

Induction can be:

Setbit (n) = n + 2setBit (n-1) setbit (1) = 1; Solution: Setbit (n) = O (n^2)

So T (n) = 2^n

Generate Truth Combination "Java implementation"

Related Article

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.