PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, October 17, 2022

[FIXED] How do I generate all combinations of integers in java when placement is restricted?

 October 17, 2022     combinations, integer, java, permutation     No comments   

Issue

I need to generate permutations over a set of integers.

However the placement of the numbers matter.

In position 0, the range is from 0-2. In position 1, the range is from 0-3. In position 2, the range is from 0-1.

So the answer would be:

000 001 010 011 020 021 030 031

100 101 110 111 120 121 130 131

200 201 210 211 220 221 230 231


Solution

Do something like:

public class Test {

    public static void main(String[] args) {
        Test x = new Test();
        x.generatePermutations(2, 3, 1);
    }

    private void generatePermutations(int intervalOne, int intervalTwo,
            int intervalThree) {
        for (int i = 0; i <= intervalOne; i++) {
            for (int j = 0; j <= intervalTwo; j++) {
                for (int k = 0; k <= intervalThree; k++) {
                    System.out.print(i + "" + j + "" + k + " ");
                }
            }
        }
    }
}

Edit: I think this will do an array of any number of intervals: (You have to check its correctness though:

public class Test {

    public static void main(String[] args) {
        Test x = new Test();
        int[] intervals = { 1, 1, 1, 1, 1 };
        x.generatePermutations(intervals);
    }

    private void generatePermutations(int[] intervals) {
        generatePermutations(intervals, 0, "");
    }

    private void generatePermutations(int[] intervals, int intpos,
            String lastPerm) {

        if (intpos == intervals.length)
            return;

        for (int i = 0; i <= intervals[intpos]; i++) {
            if (intpos == intervals.length - 1) {
                System.out.print(lastPerm + i + " ");
            }
            generatePermutations(intervals, intpos + 1, lastPerm + i);
        }
    }
}


Answered By - Bjørn Bråthen
Answer Checked By - Marilyn (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing