All possible permutations of a NxN matrix in Java - java

I want to generate all possible permutations of a matrix using recursion.
For example 2x2 matrix will have 24 possibilities.
1 2 1 2 1 3 1 4
3 4, 4 3, 2 4, 2 3....24 possibilities.
Here is my code. The logic looks fine but I could get only four different possibilities. I hope someone can help me out with this.
public class NewClass
{
public static int LENGTH=2,count=0;
public static int check_if_array_is_fully_filled(int[][] a)
{
for(int i=0;i<a.length;i++)
{
for(int j=0;j<a.length;j++)
{
if(a[i][j]==0)
{
return 0;
}
}
}
return 1;
}
public static int[][] initialize_all_zeros(int[][] a)
{
for(int i=0;i<a.length;i++)
{
for(int j=0;j<a.length;j++)
{
a[i][j]=0;
}
}
return a;
}
public static void display(int[][] a)
{
for(int i=0;i<a.length;i++)
{
for(int j=0;j<a.length;j++)
{
System.out.print(a[i][j] + " ");
}
System.out.println();
}
System.out.println("********");
count++;
}
public static void generate(int[][] a, int value_to_enter, int done)
{
if(done == 0)
{
for(int i=0;i<a.length;i++)
{
for(int j=0;j<a.length;j++)
{
if(a[i][j] == 0)
{
a[i][j]=value_to_enter;
value_to_enter++;
int v = check_if_array_is_fully_filled(a);
if(v == 1)
{
done = 1;
}
else
{
generate(a,value_to_enter,0);
}
}
}
}
}
if(done == 1)
{
display(a);
}
}
public static void main(String[] agrs)
{
int[][] a;
for(int i=0;i<LENGTH;i++)
{
for(int j=0;j<LENGTH;j++)
{
a = new int[LENGTH][LENGTH];
a = initialize_all_zeros(a);
a[i][j]=1;
generate(a,2,0);
}
}
System.out.println(count);
}
}

Here is the recursive function for a 1d array using the same logic as you did. The 2d is more or less the same thing.
private static void generate(int[] values, int currentValue) {
if (currentValue == values.length + 1) {
System.out.println(Arrays.toString(values));
return;
}
for (int i = 0; i < values.length; i++) {
if (values[i] == 0) {
values[i] = currentValue;
generate(values, currentValue + 1);
values[i] = 0;
}
}
}
Call like so:
generate(new int[3], 1);
Outputs
[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[3, 1, 2]
[2, 3, 1]
[3, 2, 1]
Which should be encapsulated in a
public static void generate(int size) {
generate(new int[size], 1);
}

My pseudo approach would be:
convert matrix to list
permute list
for each permutation of the list, convert list back to matrix.
You have not mentioned if all the elements in your matrix are unique. If they are not, then you need to remove duplicate lists from your permutation as well (need to filter after 2, before 3.
permute list:
The easiest way to understand this is by recursion.
The base step is when you have two numbers, the permutations are easy. it is (a,b) and (b,a)
To add a third element, you will add the element to all positions
e.g. permute(c,{(a,b), (b,a)}) = { (c,a,b), (a,c,b),(a,b,c),
(c,b,a), (b,c,a), (b,a,c) }
so, you recursion will be permute(a,permutedlist)
for each b in permutedlist, add a to all possible positions in the list.

Related

Given an integer array (of length n), find and return all the subsets of input array using recursion in Java

Suppose my input array is [15,20,12]
The required answer is a 2D array
The Required is output is as followed
[12
20
20 12
15
15 12
15 20
15 20 12
]
Not clear if it's homework or practical case. This is how would I solve it using Guava PowerSet:
public static void main(String[] args) {
Integer input[] = {15,20,12};
List<Integer> rev = Lists.reverse(Arrays.asList(input));
Set<Integer> indices = IntStream.range(0, input.length).boxed().collect(ImmutableSet.toImmutableSet());
Object output[] = Sets.powerSet(indices).stream()
.filter(indexset -> !indexset.isEmpty())
.map(indexset -> indexset.stream().map(i -> rev.get(i)).collect(Collectors.collectingAndThen(toList(), Lists::reverse)))
.map(List::toArray)
.toArray();
System.out.println(Arrays.deepToString(output));
}
Disclaimer:
This is my original work. No part of the solution has been copied from anywhere.
My solution works perfectly for 3 elements. However, this needs to be improved to work for arrays of other sizes. Despite this, I am publishing it so that OP or anyone else can extend this solution to work for an array of any size.
This question is close to the power set except for the fact that a power set can not have duplicate elements. If this exception is removed from this question, there are many solutions available e.g. at 1, 2, 3 etc.
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] arr = { 15, 20, 12 };
System.out.println(Arrays.deepToString(subsets(arr)));
}
public static int[][] subsets(int input[]) {
int[][] subarrs = new int[(int) Math.pow(2, input.length) - 1][input.length];
int[] indices = { 0 };
subsetsHelper(input, subarrs, 0, 0, 0, indices);
return subarrs;
}
private static void subsetsHelper(int input[], int[][] subarrs, int index, int i, int j, int[] indices) {
if (i == input.length) {
subarrs[index] = input;
return;
}
int[] subarr = new int[indices.length];
for (int x = 0; x < subarr.length; x++) {
subarr[x] = input[indices[x]];
}
subarrs[index] = subarr;
if (j == input.length - 1) {
subsetsHelper(input, subarrs, index + 1, i + 1, i + 1, new int[] { i + 1 });
} else {
subsetsHelper(input, subarrs, index + 1, i, j + 1, new int[] { i, j + 1 });
}
}
}
Output:
[[15], [15, 20], [15, 12], [20], [20, 12], [12], [15, 20, 12]]
Here you go.
public static void main(String[] args) {
int[] nums= {15, 20, 12};
int[][] subsets = subsets(nums);
for (int i = 1; i < subsets.length; i++) {
System.out.println(Arrays.toString(subsets[i]));
}
}
public static int[][] subsets(int input[]) {
List<List<Integer>> list = new ArrayList<>();
subsetsHelper(list, new ArrayList<>(), input, 0);
return convertListToArray(list);
}
private static void subsetsHelper(List<List<Integer>> list , List<Integer> resultList, int [] nums, int start){
list.add(new ArrayList<>(resultList));
for(int i = start; i < nums.length; i++){
// add element
resultList.add(nums[i]);
// Explore
subsetsHelper(list, resultList, nums, i + 1);
// remove
resultList.remove(resultList.size() - 1);
}
}
private static int[][] convertListToArray(List<List<Integer>> list) {
int[][] array = new int[list.size()][];
for (int i = 0; i < array.length; i++) {
array[i] = new int[list.get(i).size()];
}
for(int i=0; i<list.size(); i++){
for (int j = 0; j < list.get(i).size(); j++) {
array[i][j] = list.get(i).get(j);
}
}
return array;
}
1.As each recursion call will represent subset here, add resultList(see recursion code above) to the list of subsets in each call.
2.Iterate over elements of a set.
3.In each iteration
Add elements to the list
explore(recursion) and make start = i+1 to go through remaining elements of the array.
Remove element from the list
Output:
[15]
[15, 20]
[15, 20, 12]
[15, 12]
[20]
[20, 12]
[12]
public static int[][]returnallsub(int arr[], int si){
if(si==arr.length)
{int[][]ret=new int [1][0];
return ret;
}
int [][]rss =returnallsub(arr,si+1);
int [][]tss=new int[rss.length*2][];
int i=0;
for(;i<rss.length;i++) {
tss[i]=new int [rss[i].length];
}
int k=0;
for(;k<rss.length;k++) {
tss[i]=new int [rss[k].length+1];
i++;
}
int j=0;
for(i=0;i<rss.length;i++) {
for(j=0;j<rss[i].length;j++){
tss[i][j]=rss[i][j];
}
}
for(k=i;k<tss.length;k++) {
tss[k][0]=arr[si];
}
int r=i;
for(i=0;i<rss.length;i++) {
for(j=0;j<rss[i].length;j++){
tss[r][j+1]=rss[i][j];
}
r++;
}
return tss;
}
public static int[][] subsets(int arr[]) {
int start=0;
return returnallsub( arr,0);
}
}

How to count and list odd numbers in an array

public class OddsAndEvens {
// counts all the odd numbers in the array
private static int countOdds(int[] array) {
int count = 0;
for(int i = 0; i < array.length; i++) {
if(array[i] % 2 == 1 && array[i] % 2 != 0) {
count++;
}
}
return count;
}
// returns an array with all the odd numbers
public static int[] getAllOdds(int[] array) {
int[] yaArray = new int[countOdds(array)];
int j = 0;
for(int i = 0; i < array.length; i++) {
if(array[i] % 2 == 1 && array[i] % 2 != 0) {
yaArray[j] = array[i];
}
j++;
}
return yaArray;
}
}
///////////////////////////////////////////////////////////
runner code
public class OddsAndEvensRunner {
public static void main(String args[]) {
System.out.println("Odds - " + Arrays.toString(OddsAndEvens.getAllOdds(new int[]{2,4,6,8,10,12,14})));
System.out.println("Evens - " + Arrays.toString(OddsAndEvens.getAllEvens(new int[]{2,4,6,8,10,12,14})));
System.out.println("\nOdds - " + Arrays.toString(OddsAndEvens.getAllOdds(new int[]{1,2,3,4,5,6,7,8,9})));
System.out.println("Evens - " + Arrays.toString(OddsAndEvens.getAllEvens(new int[]{1,2,3,4,5,6,7,8,9})));
System.out.println("\nOdds - " + Arrays.toString(OddsAndEvens.getAllOdds(new int[]{2,10,20,21,23,24,40,55,60,61})));
System.out.println("Evens - " + Arrays.toString(OddsAndEvens.getAllEvens(new int[]{2,10,20,21,23,24,40,55,60,61})));
}
}
Ignore code relating to evens. When run the odd array only lists out one odd number instead of the others inside of the first array along with a couple of zeros. I tried a lot of things but simply won't count all of the odd numbers.
Take a look at this part:
public static int[] getAllOdds(int[] array) // when
{
int[] yaArray = new int[countOdds(array)];
int j = 0;
for(int i = 0; i<array.length;i++)
if(array[i]%2==1 && array[i]%2!=0)
yaArray[j]=array[i];
j++;
return yaArray;
}
The variable j is incremented only once, which is after the loop ends.
If you have multiple statements to be executed in looping or conditional branch, use brackets.
Also array[i]%2==1 means the same thing as array[i]%2!=0, so can eliminate one of them.
public static int[] getAllOdds(int[] array) // when
{
int[] yaArray = new int[countOdds(array)];
int j = 0;
for(int i = 0; i<array.length;i++)
{
if(array[i]%2==1)
{
yaArray[j]=array[i];
j++;
}
}
return yaArray;
}
Use List instead of Arrays. List is better to use.
Try like this,
public static void main(String[] args) {
System.out.println("Odds - " + Arrays.toString(getAllEvens(new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 })));
System.out.println("Evens - " + Arrays.toString(getAllOdds(new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 })));
}
public static Object[] getAllOdds(int[] array) {
List<Integer> list = new ArrayList<>();
for (int no : array) {
if (no % 2 != 0)
list.add(no);
}
return list.toArray();
}
public static Object[] getAllEvens(int[] array) {
List<Integer> list = new ArrayList<>();
for (int no : array) {
if (no % 2 == 0)
list.add(no);
}
return list.toArray();
}
You can also return list instead of list.toArray() for better list.

sorting numbers in a vector and print them in accening order

I want to make a sorting algorithm .. My vector should be printed in accending order .. I made this code but it does not work ...
public class User {
public static int[] sort(int[] a) {
if (a == null) {
return null;
} else {
for(int i=0; i<a.length; i++) {
if(a[i++] < a[i]) {
int x= a[i];
int y=a[i++];
a[i++] =x;
a[i] = y;
} else {
return a;
}
}
}
return a;
}
public static void main(String[] args) {
int a[] = { 4, 6, 8, 2, 4, 1 };
System.out.println(Arrays.toString(sort(a)));
}
}
I am getting error output .. I got [4, 6, 6, 6, 4, 1]
How to correct the code?
thanks
Your sorting algorithm is not implemented well.
Try this one:
for(int i=0; i<a.length; i++) {
for(int j=i+1; j<a.length; j++) {
if(a[j] < a[i]) {
int x= a[i];
a[i] = a[j];
a[j] = x;
}
}
}
Change
public static int sort(int[] a) {
if (a == null) {
return 0;
}
...
return a;
to
public static int[] sort(int[] a) {
if (a == null) {
return null;
}
...
return a;
So that your method would return the whole array, not just a single value.
&
System.out.println(sort(a));
to
System.out.println(Arrays.toString(sort(a)));
So as to print the array correctly.
EDIT:
You can get your array sorted simply by using Arrays.sort():
int a[] = { 4, 6, 8, 2, 4, 1 };
Arrays.sort(a);
System.out.println(Arrays.toString(a));

Using Java check n value is appears n time and the number is in consecutive location in an given array

Question: Define an array to be packed if all its values are positive, each value n appears n times and all equal values are in consecutive locations. So for example, {2, 2, 3, 3, 3} is packed because 2 appears twice and 3 appears three times. But {2, 3, 2, 3, 3} is not packed because the 2s are not in consecutive locations. And {2, 2, 2, 3, 3, 3} is not packed because 2 appears three times.
Write a method named isPacked that returns 1 if its array argument is packed, otherwise it returns 0. You may assume that the array is not null
If you are programming in Java or C#, the function signature is
int isPacked(int[ ] a)
public class isPackd{
public static void main(String[] args){
int result=isPacked(new int[ ] {2, 2, 1});
System.out.println("Return: " + result);
result=isPacked(new int[ ] {7, 7, 7, 7, 1, 7, 7, 7});
System.out.println("Return: " + result);
}//main()
public static int isPacked(int[ ] a){
for (int i=0; i<a.length; i++) {
int chkHowManyTimes=howManyTimes(a, a.length, a[i]);
if (chkHowManyTimes !=a[i]) {
return 0;
} // end of if
} // end of for
if (isConsecutive(a)==0) {
return 0;
} // end of if
return 1;
}//isPacked()
public static int howManyTimes(int[] array, int length, int findNumber){
int count=0;
for (int i=0; i<length; i++) {
if (array[i]==findNumber) {
count +=1;
} // end of if
} // end of for
//System.out.println(count);
return count;
}//howMany..()
public static int isConsecutive(int[] a){
//
//need help here to write code for this section
//
return 1;
}//isCon..()
}//class
I need help to check whether the number is in consecutive location or not.
And then,here is the full code below.
So, is there anything just feel free to ask here.
public class Consecutive
{
/***************************************************************************/
Author :- ShihabSoft
/***************************************************************************/
public static void main(String[] someArgs)
{
int[] args=new int[someArgs.length];
for(int i=0;i<someArgs.length;i++)
args[i]=Integer.parseInt(someArgs[i]);
int swit=checkArrConsecutive(args);
if(swit==0 || swit==1)
System.out.println("All "+args.length+" values appeared accordingly in the array");
switch(swit)
{
case 0:
System.out.println("Array is not well packed.");
break;
case 1:
System.out.println("Array is well packed");
}
}
//As per your needs we need two functions
static int checkArrConsecutive(int[] args)
{
int curr=0,temp=0;
if(args!=null)
{
int numIndex=0;
for(int i=0;i<args.length;i++)
{
curr=args[i];
temp=0;
if(checkNoccursNtime(args,curr)==0)
{
System.out.println("Sorry the number :- "+curr+" at index '"+i+"' repeats more or less than '"+curr+"' times");
return 2;
}
for(int j=numIndex;j<args.length;j++)
{
if(temp==curr)
break;
if(args[j]!=curr)
{
return 0;
}
else
temp++;
}
if(curr!=(args.length!=(i+1) ? args[i+1] : args[i]))
numIndex=i+1;
}
return 1;
}
return 0;
}
static int checkNoccursNtime(int[] args,int n)
{
if(args!=null)
{
int curr=0,temp=0;
temp=0;
curr=n;
for(int j=0;j<args.length;j++)
{
if(args[j]==curr && temp != curr)
temp++ ;
else if(args[j]==curr)
return 0;
}
return temp==curr ? 1 : 0;
}
return 0;
}
}
Just compile the above code and run passing values like this.
java Consecutive 5 5 5 5 5 1 2 2 3 3 3
public class Packed {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] a = { 7, 7, 7, 7, 7,7, 7 };
int tt = isPacked(a);
System.out.println(tt);
}
private static int isPacked(int[] a) {
int n;
int count = 0;
int k = 0;
int initialindex;
int finalindex = 0;
for (int i = 0; i < a.length; i++) {
if (a[i] < 0) {
return 0;
}
n = a[i];
k = 0;
initialindex = i;
for (int j = 0; j < a.length; j++) {
k++;
if (n == a[j]) {
i++;
finalindex = k;
count++;
}
}
if (n != count || (finalindex - initialindex) != count) {
return 0;
}
i--;
count = 0;
}
return 1;
}
}

How to calculate the number of childern in a tree using recursion

I have designed a recursive algorithm to find the number of children in a string. The string is actually an array such as [1,0,1,0,1]. There three possible children of this string which are [0,0,1,0,1], [1,0,0,0,1] and [1,0,1,0,0]. Thus the criteria for creating the children is to decrement only one non-zero entry in the string. Since there are three non-zero entries in [1,0,1,0,1] so three possible children. Continuing in this fashion each children can now have two possible children and so on. The recursion stop when there is only one non-zero entry in the string.
This is my code:
public class Recursion {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
int[] c={1,0,1,0,1};
System.out.println(num(c));
}
private static int num(int[] v){
if(numChildren(v)==1){
return 1;
}
else{
int[][] ge=children(v);
for(int[] e:ge){
return 1+num(e);
}
System.out.print("this return should never execute");
return 0;
}
}
private static int numChildren(int[] val){
int sum=0;
for(int i=0;i<val.length;i++){
if(val[i]!=0){
sum+=1;
}
}
return sum;
}
private static int[][] children(int[] p){
int pChildern=numChildren(p);
int[] d=new int[pChildern];
int[][] r=new int[pChildern][];
int c=0;
for(int j=0;j<p.length;j++){
if(p[j]!=0){
d[c]=j;
c++;
}
}
for(int i=0;i<pChildern;i++){
p[d[i]]--;
r[i]=p.clone();
p[d[i]]++;
}
return r;
}
}
My code does execute but doesn't produce correct result. It should print 6 but it prints 3.
Can any one suggest me what is wrong with this code?
// Returns size of subtree including the root
int getNumChilds(Node node) {
int count = 1;
for (Node child : node.getChildren()) {
count += getNumChilds(child);
}
return count;
}
I didn't really go into details, but this block looks weird:
int[][] ge=children(v);
for(int[] e:ge){
return 1+num(e);
}
System.out.print("this return should never execute");
return 0;
You want to sum up all its children here, but you return too early. It should be something like this:
int[][] ge=children(v);
int totChild = 0;
for(int[] e:ge){
totChild = totChild + num(e);
}
return totChild;
I think following code might be well suited to your needs.
{1, 0, 1, 0, 1} --> gives 7 (2 x 2 x 2 - 1)
{1, 1, 1, 1, 1} --> gives 31 (2 x 2 x 2 x 2 x 2 - 1)
{4, 4, 1, 1, 1} --> gives 199 (5 x 5 x 2 x 2 x 2 - 1)
-1 is to remove {0, 0, 0, 0, 0} from children.
public class Recursion {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
int[] c={4,4,1,1,1};
System.out.println(num(c, 0));
}
private static void print(int[] v) {
System.out.print("[");
for ( int i = 0; i < v.length; ++i ) {
System.out.print(v[i] + ",");
}
System.out.println("] ");
}
private static int num(int[] v, int k){
if(numChildren(v)==1){
return 1;
}
else{
int r = 1;
for ( int i = k; i < v.length; ++i ) {
if ( v[i] > 0) {
int o = v[i];
v[i] = o - 1;
print(v);
r += num(v, i);
v[i] = o;
}
}
return r;
}
}
private static int numChildren(int[] val){
int sum=0;
for(int i=0;i<val.length;i++){
if(val[i]!=0){
sum+=1;
}
}
return sum;
}
}

Categories