By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,805 Members | 1,280 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,805 IT Pros & Developers. It's quick & easy.

Find all vectors with sum equal of vector elements and elements not bigger of k witho

P: 5
I want to find all vectors with sum equal of vector elements and elements not bigger of k but without using recursion. For example in number of vector elements n is 5, sum=10 and k=3 than, the output will be:

3 1 2 2 2
3 1 2 1 3
3 1 1 3 2
3 1 1 2 3
3 1 0 3 3
3 0 3 3 1
3 0 3 2 2
3 0 3 1 3
3 0 2 3 2
3 0 2 2 3
3 0 1 3 3
2 3 3 2 0
2 3 3 1 1
2 3 3 0 2
2 3 2 3 0

The source code with using recursion in Java is:
Expand|Select|Wrap|Line Numbers
  1. private static void printVectors(int p[], int n) {
  2.  
  3.         for (int i = 0; i < n; i++) {
  4.             System.out.print(p[i] + " ");
  5.         }
  6.         System.out.println();
  7.     }
  8.  
  9.     private static void computeVectors(int[] n, int sum, int k, int k1, int i) {
  10.  
  11.  
  12.         if (sum == 0) {
  13.  
  14.             printVectors(n, n.length);
  15.         } else if (i < n.length) {
  16.  
  17.             for (int j = k; j >= 0; j--) {
  18.  
  19.                 if (j <= k1) {
  20.                     n[i] = j;
  21.                     computeVectors(n, sum - j, sum - j, k1, i + 1);
  22.                 }
  23.             }
  24.         }
  25.     }
My question is how to redesign computeVectors() function without using recursion?
Apr 9 '13 #1
Share this Question
Share on Google+
1 Reply


10K+
P: 13,264
Generally, you replace recursion with iteration by

i) identify the base case
ii) write a loop that runs until the base case is reached
iii) get closer to the base case at each step in the loop and send the remaining results to the start of the loop

Try it and post what you have tried if you are stuck.
Apr 9 '13 #2

Post your reply

Sign in to post your reply or Sign up for a free account.