You are not logged in. Please login at www.codechef.com to post your questions!

×

how can i decrease complexity of this part of code??

this code prints a combination of elememts present in an array "pts" (4 elements at atime) in such a way that a particular combination of digits never occurs more than once.. eg. if 1 2 3 4 is printed already then none of its permutations should get printed.

for (int i = 0; i < pts.length; i++) {

        for (int j = i+1; j < pts.length; j++) {

            for (int k = j+1; k < pts.length; k++) {

                for (int l = k+1; l < pts.length; l++) {

                    System.out.println(""+i+" "+j+" "+k+" "+l);

                }//l

            }//k

        }//j

if anyone can suggest some other approach or can tell me how to reduce this code's complexity... I shall be thankful. :)

asked 12 Oct '14, 14:10

rishabh_gour's gravatar image

2★rishabh_gour
11
accept rate: 0%


The number of solutions of this problem is in worst case C(n,4) (Number of ways of selecting four elements from a set of n elements). This is O(n^4). Since the number of solutions is O(n^4), which you have to generate, you cannot improve the worst case complexity.

To avoid printing permutations of the same group of four numbers, first sort the array. Now, the numbers generated by the four nested "for loops" written above, will be in sorted order. So, if any repetitions occur, they will occur consecutively. You will need to store the last group of numbers printed. If the current group is same as the previous group, don't print it. If they are unequal, print the current group, and update the previous group.

link

answered 13 Oct '14, 00:36

aakashc31's gravatar image

4★aakashc31
22134
accept rate: 27%

toggle preview
Preview

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Markdown Basics

  • *italic* or _italic_
  • **bold** or __bold__
  • link:[text](http://url.com/ "title")
  • image?![alt text](/path/img.jpg "title")
  • numbered list: 1. Foo 2. Bar
  • to add a line break simply add two spaces to where you would like the new line to be.
  • basic HTML tags are also supported
  • mathemetical formulas in Latex between $ symbol

Question tags:

×1,664
×144

question asked: 12 Oct '14, 14:10

question was seen: 959 times

last updated: 13 Oct '14, 00:36