I'm running into a problem with a program that I'm writing for a class.
I was given a text file that contains three matrices and I need to create a loop that prints out all three of them in the output through various filters.
Here is what the file contains:
15 15
91 114 75 145 149 250 31 103 88 123 27 120 187 140 52
108 23 43 126 51 9 107 29 20 221 18 41 178 245 159
187 53 7 107 96 82 70 2 171 2 36 84 135 187 92
176 30 199 230 178 61 48 211 208 143 178 207 79 196 217
26 6 117 170 4 245 63 93 108 44 163 19 6 220 131
7 210 228 154 213 96 102 254 63 34 25 215 168 23 207
131 254 198 215 164 6 141 150 147 26 242 199 237 131 240
102 22 248 74 26 3 138 145 132 120 97 126 8 86 166
178 68 73 127 56 180 182 152 3 149 184 42 204 9 172
104 203 99 132 204 137 33 69 140 19 131 38 239 56 180
163 249 88 222 98 150 58 155 115 188 70 189 162 33 1
113 141 52 196 139 241 68 37 89 215 166 7 200 179 26
21 68 167 53 226 167 193 232 133 79 212 163 101 157 233
122 17 114 224 129 247 35 84 120 51 91 149 127 150 19
217 253 145 45 205 179 107 76 214 48 230 218 8 135 25
6 6
201 159 87 63 240 244
231 32 222 76 5 255
10 5 248 139 47 64
167 76 138 177 107 159
188 122 154 165 205 22
222 149 148 85 129 57
5 5
201 159 87 63 240
231 32 222 76 5
10 5 248 139 47
167 76 138 177 107
188 122 154 165 205
I was able to get a loop that read the file and prints out the first 15x15 array, but I need a loop that will print out the other three after it including the filters applied to the data.
That is:
Base image data:
(15x15 array)
(6x6 array)
(5x5 array)
Filtered data:
(15x15 filtered)
(6x6 filtered)
(5x5 filtered)
I'm able to print out the first array just fine, but I am racking my brain trying to find a way to loop the code to print out the other two arrays. Additionally, I have a second problem that when the filtered data is printed, it's all 0s like so:
Base Image Data
91 114 75 145 149 250 31 103 88 123 27 120 187 140 52
108 23 43 126 51 9 107 29 20 221 18 41 178 245 159
187 53 7 107 96 82 70 2 171 2 36 84 135 187 92
176 30 199 230 178 61 48 211 208 143 178 207 79 196 217
26 6 117 170 4 245 63 93 108 44 163 19 6 220 131
7 210 228 154 213 96 102 254 63 34 25 215 168 23 207
131 254 198 215 164 6 141 150 147 26 242 199 237 131 240
102 22 248 74 26 3 138 145 132 120 97 126 8 86 166
178 68 73 127 56 180 182 152 3 149 184 42 204 9 172
104 203 99 132 204 137 33 69 140 19 131 38 239 56 180
163 249 88 222 98 150 58 155 115 188 70 189 162 33 1
113 141 52 196 139 241 68 37 89 215 166 7 200 179 26
21 68 167 53 226 167 193 232 133 79 212 163 101 157 233
122 17 114 224 129 247 35 84 120 51 91 149 127 150 19
217 253 145 45 205 179 107 76 214 48 230 218 8 135 25
Image Filter1:
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
The code I have it pretty extensive, so I'm having trouble pinpointing why it's returning 0s.
Here is my code:
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(new File("imagedata.txt"));
int r = scanner.nextInt();
int c = scanner.nextInt();
int [][] imageData = new int[r][c];
//for loop to create 2d array from image data
for(int row=0; row<imageData.length; row++) {
for(int col=0; col<imageData[row].length; col++) {
imageData[row][col] = scanner.nextInt();
}
}
System.out.println("Base Image Data");
for(int[] row : imageData) {
for(int num : row) {
System.out.print(num+" ");
}
System.out.println();
}
System.out.println("Image Filter1:");
int[][] filter1 = applyFilter1(imageData);//call return from applyFilter1
for(int[] row : filter1){
for(int num : row){
System.out.print(num+" ");
}
System.out.println();
}
}
public static int[][] applyFilter1(int[][] imageData){
int[][] filtered = new int[imageData.length][imageData[0].length];
for (int row=0; row<filtered.length;row++){
for (int col=0;col<filtered[row].length;col++){
int[] nebs = getNeighbors(row, col, imageData);
int sum = 0;
for(int i=0; i<nebs.length; i++){
sum = sum + nebs[i];
int average = sum / nebs.length;
filtered[row][col] = average;
}
}
}
return filtered;
}
public static int[] getNeighbors(int row, int col, int[][] imageData){
//find neighbors of current index
int [][] copyImage = new int[imageData.length][imageData[0].length];
try{
for(int r=0; r<imageData.length; r++){
for(int c=0; c<imageData[r].length; c++){
imageData[r][c] = copyImage[r][c];
}
}
} catch(Exception e){
System.out.println("Array copy not successful");
}
//handles the top row of the array
if(row==0){//if copyImage[0].length
if(col==0){//handles upper left corner of array
int[] nebs = {copyImage[row][col], copyImage[row+1][col],
copyImage[row][col+1]};
return nebs;
}
else if(col==copyImage[row].length-1){//handles upper right corner of array
int[] nebs = {copyImage[row][col], copyImage[row][col-1],
copyImage[row+1][col]};
return nebs;
}
else{//handles top row of array between corners
int[] nebs = {copyImage[row][col], copyImage[row][col-1],
copyImage[row+1][col], copyImage[row][col+1]};
return nebs;
}
}
//handles the bottom row of the array
else if(row==copyImage.length-1){//if the row is at max value
if(col==0){//handles botton left corner of array
int[] nebs = {copyImage[row][col], copyImage[row-1][col],
copyImage[row][col+1]};
return nebs;
}
else if(col==copyImage[row].length-1){//handles bottom right corner of array
int[] nebs = {copyImage[row][col], copyImage[row-1][col],
copyImage[row][col-1]};
return nebs;
}
else{//handles bottom row of array
int[] nebs = {copyImage[row][col], copyImage[row-1][col],
copyImage[row][col-1], copyImage[row][col+1]};
return nebs;
}
}
//handles leftmost column of array
else if(col==0){//if col=0 and row increases
int[] nebs = {copyImage[row][col], copyImage[row-1][col],
copyImage[row+1][col], copyImage[row][col+1]};
return nebs;
}
//handles rightmost column of array
else if(col==copyImage[row].length-1){//if col=max value and row increases
int[] nebs = {copyImage[row][col], copyImage[row-1][col],
copyImage[row+1][col], copyImage[row][col-1]};
return nebs;
}
//handles values in the body of the array
else{
int[] nebs = {copyImage[row][col], copyImage[row-1][col],
copyImage[row+1][col], copyImage[row][col-1],
copyImage[row][col+1]};
return nebs;
}
}
I'm still new to java, despite the amount of code in this program. So any guidance and feedback is welcome.
You can simply read this file line-by-line, split each string into an array of numbers, then format them as a three-character string, concatenate them back and output. No matter how many matrices are in this file.
List<String> list = List.of(
"91 114 75 145 149 250 31 103 88 123 27 120 187 140 52",
"108 23 43 126 51 9 107 29 20 221 18 41 178 245 159",
"187 53 7 107 96 82 70 2 171 2 36 84 135 187 92");
list.stream()
.map(str -> Arrays
// split string into an array of numbers
.stream(str.split("\s+"))
// format as a three-character string
.map(s -> String.format("%3s", s))
// concatenate into a single string
.collect(Collectors.joining(" ")))
// output line by line
.forEach(System.out::println);
Output:
91 114 75 145 149 250 31 103 88 123 27 120 187 140 52
108 23 43 126 51 9 107 29 20 221 18 41 178 245 159
187 53 7 107 96 82 70 2 171 2 36 84 135 187 92
Given a sorted array of positive integers. Your task is to rearrange the array elements alternatively i.e first element should be max value, second should be min value, third should be second max, fourth should be second min and so on.
class RearrangeAlternate{
public void swapMax(int arr[], int i, int n){
int x = arr[i];
int j;
for(j = n-1; j>i; j--){
if(arr[j] > x){
break;
}
}
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
public void swapMin(int arr[], int i, int n){
int x = arr[i];
int j;
int res = n-1;
for(j = n-1; j>i; j--){
if(arr[j] < x){
if(arr[j] < arr[res]){
res = j;
}
}
}
int temp = arr[i];
arr[i] = arr[res];
arr[res] = temp;
}
public void rearrange(int arr[], int n){
for(int i = 0; i<n; i++){
if(i%2 == 0){
swapMax(arr, i, n);
}
else swapMin(arr, i, n);
}
}
}
Please help me find the error
It is showing wrong output for somecases.
eg.
82
12 23 28 43 44 59 60 68 70 85 88 92 124 125 136 168 171 173 179 199 212 230 277 282 306 314 316 325 328 336 337 363 365 368 369 371 374 387 394 414 422 427 430 435 457 493 506 527 531 538 541 546 568 583 650 691 730 737 751 764 778 783 785 789 794 803 809 815 847 858 863 874 887 896 916 920 926 927 930 957 981 997
My codes output: 997 12 981 23 957 28 930 43 927 44 926 59 920 60 916 68 896 70 887 85 874 88 863 92 858 124 847 125 815 136 809 168 803 171 794 173 789 179 785 199 783 212 778 230 764 277 751 282 737 306 730 314 691 316 650 325 568 328 527 336 506 337 430 363 374 369 541 365 583 368 531 371 493 387 538 394 457 414 435 422 546 427
Answer: 997 12 981 23 957 28 930 43 927 44 926 59 920 60 916 68 896 70 887 85 874 88 863 92 858 124 847 125 815 136 809 168 803 171 794 173 789 179 785 199 783 212 778 230 764 277 751 282 737 306 730 314 691 316 650 325 583 328 568 336 546 337 541 363 538 365 531 368 527 369 506 371 493 374 457 387 435 394 430 414 427 422
Since your array is sorted, you can simply do it as follows:
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int temp;
for (int i = 0; i < arr.length; i++) {
if (i % 2 == 0) {
// Store the last element to 'temp'
temp = arr[arr.length - 1];
// Shift all elements, starting from index, 'i', to one place right
for (int j = arr.length - 2; j >= i; j--) {
arr[j + 1] = arr[j];
}
// Put the value stored in 'temp' to index, 'i'
arr[i] = temp;
}
}
System.out.println(Arrays.toString(arr));
}
}
Output:
[10, 1, 9, 2, 8, 3, 7, 4, 6, 5]
Since the array is sorted and we need to rearrange alternatively,we can use the technique to store two numbers at a single position in such a manner that we are also able to retrieve back the original element when required.
Let's say we need to store n1 and n2 at same position then we can formulate it like :
====================== n1 = n1 + (n2%z)*z ======================
To extract n1 we can modulo n1 by z and to extract n2 we can divide n1 by z.
For more detailed explanation,you can refer this video : https://youtu.be/KOglcclYgXI
using lambda — doing the rearranging outside the original arr
O(n) time complexity
int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
int[] tmp = IntStream.range( 0, (arr.length + 1) / 2 )
.flatMap( n -> IntStream.of( arr[arr.length - n - 1], arr[n] ) ).toArray();
System.arraycopy( tmp, 0, arr, 0, arr.length );
gets for arr: [11, 1, 10, 2, 9, 3, 8, 4, 7, 5, 6]
The solution mentioned below solves the problem in O(N) Time complexity and O(1) Space Complexity WITHOUT using the "storing 2 values at one location concept". Moreover this algorithm can also handle duplicate values & float values given the input list is non-decreasingly sorted and consists of positive real numbers only.
PS: If you wish you can modify my algorithm slightly to make it work for negative values as well.
Please don't get intimidated by looking at the code. Implementation is very simple. Algorithm might be a bit tricky to understand.
def reArrange(arr, print_arr_state=True):
# arr: non-decreasingly sorted list of positive floats/ints
length = len(arr)
for i in range(length):
if arr[i] > 0:
cycler(arr, i, length, print_arr_state)
arr[i] = abs(arr[i]) # This is the tricky part
# printing the array after every iteration
if print_arr_state:
print('after', i, 'th iteration:', arr)
def cycler(arr, start_index, length, print_cycler_array=True):
if print_cycler_array:
print('cycler function:', arr, end=' ---> ')
half_length_index = length // 2
swap_index = start_index
current_value = arr[start_index]
while True:
if swap_index < half_length_index:
swap_index = 2 * swap_index + 1
else:
swap_index = 2 * (length - 1 - swap_index)
# Placing the current value at swap_index and making the making current_value variable refer to the value which was at swap_index
swap_value = arr[swap_index]
arr[swap_index] = -1 * current_value # -1 * ?? This is the tricky part of the algo
current_value = swap_value
# cycler function will not stop until the simple cycle is complete
# simple cycle is complete when swap_index == start_index
if swap_index == start_index:
if print_cycler_array:
print(arr)
return
Giving Input (input_array) and Calling reArrange function:
input_array = [0.1, 2, 3.2, 3.3, 3.3, 4, 5.7, 5.7, 6.8, 7, 8, 9]
reArrange(input_array)
Output:
answer_array = [9, 0.1, 8, 2, 7, 3.2, 6.8, 3.3, 5.7, 3.3, 5.7, 4]
Understanding the algorithm
Tricky part of the algorithm:
Every value belongs to exactly 1 cycle and this cycle is a simple cycle (simple cycle vs complex cycle in graphs). One execution of cycler function corresponds to one cycle which is also a simple cycle.
Whenever I cover a value during a cycle, I multiply it with -1 (to indicate that it is covered) and store it in the input array itself.
During the i-th iteration of the loop of reArrange function, if I find the i-th value to be negative I get an indication that this value is a part of a cycle executed for some j-th iteration (where j < i), thus I don't call the cycler function on this value. But if this value is positive (indicating that none of cycles executed so far has covered this value), it implies that it is not covered yet and hence should be covered in the i-th iteration using the cycler function.
But wait!, if I have multiplied all values with -1 my final answer will be -1 * correct_answer_array. To solve this problem, one solution is to reiterate my answer_array (which was input_array initially and now has transformed to my answer_array) and take the absolute of each value OR I can do the same thing during my first and only iteration (of reArrange function's loop) by taking the absolute of the value before moving to the i+1-th iteration.
Some valid questions
There are few aspects of this algorithm that I haven't covered in this post. Let me leave you with some of these aspects in the form of questions:
Is the while loop of cycler function guaranteed to terminate?
Why should we not cover a value more than once?
How can we handle the negative input values (if any)?
Isn't a single cycle sufficient to cover all the values of the input_array. (Isn't a single call of the cycler function sufficient to cover all the values)?
Hint: eg: 1 2 3 4 5 6 7, this example will lead to 3 cycles. (cycler function will be called thrice)
What happens during a single call of cycler function?
Hint: Every value which is the part of this cycle shifts to the place where it is supposed to be in the correct_answer_array. Once a value is at its correct place, it should not be disturbed again.
Please visit the comments section at the bottom of this page (GeeksforGeeks) to see the dry run of the algorithm. Please make sure you read all of the comments by me because I have created a bit of mess there.
Given a sorted array of positive integers. Your task is to rearrange the array elements alternatively i.e first element should be max value, second should be min value, third should be second max, fourth should be second min and so on.
//c#
using System;
using System.Collections.Generic;
using System.Text;
namespace vijay
{
class oddEven
{
public static void Main()
{
int n = Convert.ToInt32(Console.ReadLine());
int[] arr = new int[n];
for(int i=0;i<n;i++)
arr[i]=Convert.ToInt32(Console.ReadLine());
// example input int[] arr = {8,7,6,5,4,3,2,1 };
Array.Sort(arr); //sorting array
Array.Sort(arr);
int f = 1,f1=0;
int[] dummy = new int[n];
int a = arr.Length / 2;
for(int i=0;i<n;i++)
{
if(i<a) //first half add in even position
{
dummy[f]=arr[i];
f += 2;
}
else //second half add in odd positions
{
dummy[f1] = arr[i];
f1 += 2;
}
}
Console.WriteLine("\n\n\n\n"); //print the result
foreach(int q in dummy)
{
Console.WriteLine(q);
}
}
}
}
//python
list=[2,5,8,9,4,6,7,1]
a=sorted(list)
b=reversed(sorted(list))
c=a[0:len(a)//2]
d=a[len(a)//2:][::-1]
for i in range(len(c)):
print(d[i],end=' ')
print(c[i],end=' ')
I want my code to print out 10 numbers per line and count how many numbers there are. I also want to be able to find the max number. I am having trouble figuring out how to find the max. Here is my code.
int valCount = 0;
int numCount =0;
while (startingNum > 1) {
int count = 0;
System.out.print(startingNum + " ");
valCount++;
if(valCount%10 ==0)
System.out.println();
if (startingNum % 2==0) {
startingNum = startingNum/2;
numCount++;
} else {
startingNum = (startingNum*3) +1;
numCount++;
}
}
This is the correct code:
public static void main(String[] args) {
int startingNum = 27;
int counter = 0;
while (startingNum > 1) {
counter++;
System.out.print(startingNum + " ");
if (counter % 10 == 0)
System.out.println();
if (startingNum % 2 == 0) {
startingNum = startingNum / 2;
} else {
startingNum = (startingNum * 3) + 1;
}
}
System.out.println(1);
}
You can use a counter, increment it at each print, when you reach a multiple of 10 print a new line, also to align the different elements, I would suggest to use printf, here I set to %5d because max number has 4 digit, if it goes up to like 6 digit use %7d
int valCount = 0;
while (startingNum > 1) {
System.out.printf("%5d", startingNum);
valCount++;
if(valCount%10 ==0)
System.out.println();
if (startingNum % 2==0) {
startingNum = startingNum/2;
} else {
startingNum = (startingNum*3) +1;
}
}
System.out.printf(" 1");
The Demo code will give you :
27 82 41 124 62 31 94 47 142 71
214 107 322 161 484 242 121 364 182 91
274 137 412 206 103 310 155 466 233 700
350 175 526 263 790 395 1186 593 1780 890
445 1336 668 334 167 502 251 754 377 1132
566 283 850 425 1276 638 319 958 479 1438
719 2158 1079 3238 1619 4858 2429 7288 3644 1822
911 2734 1367 4102 2051 6154 3077 9232 4616 2308
1154 577 1732 866 433 1300 650 325 976 488
244 122 61 184 92 46 23 70 35 106
53 160 80 40 20 10 5 16 8 4
2 1
hi guys the problem that im having with this code is that the number of mersenne primes is supposed to be 4 but it outputs 8. i know this because the number of Mersenne primes between 1 and 1000 are 3, 7, 31, and 127 but it also outputs 15, 63, 255, and 511. which i dont know why. is there also a way to output the counts of Primes per 100 numbers? thanks
public static void main(String[] args) {
System.out.println("Prime numbers between 1 and 1000 are\n");
String message = "";
String message2 = "";
// loop numbers from 1 to 1,000, printing only the primes
int counter2 = 0;
int counter = 0;
for( int number s= 2; number <= 1000; number ++){
if(isPrime(number)) {
counter++;
if(counter % 10 == 0) {
System.out.println(number);
}
else
System.out.print(number + " ");
}
}
for(int number2 = 2; number2 <= 1000; number2 ++){
if(isMersenne(number2)){
counter2++;
System.out.print(number2 + "*");
}
}
System.out.print( "\n\n The number of primes between 1 and 1000 are " + counter);
System.out.print( "\n The number of Mersennes is " + counter2);
}
public static boolean isPrime( int number ){
// initialize the boolean variable prime to true
boolean isPrime = true;
for(int divisor = 2; divisor <= number /2; divisor++) {
if(number % divisor == 0) {
isPrime = false;
}
}
return isPrime;
}
public static boolean isMersenne(int number){
// declare and initialize variable powTwo to 2
int powTwo = 2;
boolean mersenne = false;
while(powTwo <= number){
powTwo *= 2;
if(powTwo - number == 1)
// if the prime is one less than a power of 2, return true
mersenne = true;
}
return mersenne;
} // end method isMersenne
}
this is the output of my program
Prime numbers between 1 and 1000 are
2 3 5 7 11 13 17 19 23 29
31 37 41 43 47 53 59 61 67 71
73 79 83 89 97 101 103 107 109 113
127 131 137 139 149 151 157 163 167 173
179 181 191 193 197 199 211 223 227 229
233 239 241 251 257 263 269 271 277 281
283 293 307 311 313 317 331 337 347 349
353 359 367 373 379 383 389 397 401 409
419 421 431 433 439 443 449 457 461 463
467 479 487 491 499 503 509 521 523 541
547 557 563 569 571 577 587 593 599 601
607 613 617 619 631 641 643 647 653 659
661 673 677 683 691 701 709 719 727 733
739 743 751 757 761 769 773 787 797 809
811 821 823 827 829 839 853 857 859 863
877 881 883 887 907 911 919 929 937 941
947 953 967 971 977 983 991 997 3*7*15*31*63*127*255*511*
The number of primes between 1 and 1000 are 168
The number of Mersennes is 8
Your problem is that isMersenne is just checking whether the number is one less than a power of two. It's not also checking that it's a prime.
You need to change your isMersenne method so that it calls isPrime after checking whether the number is one less than a power of two. If isPrime returns false, then isMersenne should also return false.
I am trying to print all possible sequences of n and I don't know where I went wrong.
Example: If I let n = 3, then I have to get 33 possible combinations.
import java.util.Scanner;
public class MyPermutations {
public static void show(int[] a) {
for (int i = 0; i < a.length; i++)
System.out.printf("%d", a[i]);
System.out.printf("\n");
}
public static void swap(int[] a, int i, int j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
public static boolean hasNext(int[] a) {
int N = a.length;
// find rightmost element a[k] that is smaller than element to its right
int k;
for (k = N-2; k >= 0; k--)
if (a[k] < a[k+1]) break;
if (k == -1) return false;
// find rightmost element a[j] that is larger than a[k]
int j = N-1;
while (a[k] > a[j])
j--;
swap(a, j, k);
for (int r = N-1, s = k+1; r > s; r--, s++)
swap(a, r, s);
return true;
}
public static void perm(int N) {
// initialize permutation
int[] a = new int[N];
for (int i = 1; i < N; i++) {
a[0]=1;
a[i] = i+1;
}
// print permutations
show(a);
while (hasNext(a))
show(a);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = Integer.parseInt(sc.next());
perm(N);
}
}
Input:
3
My Output:
123 132 213 231 312 321
Expected Output:
111 112 113 121 122 123 131 132 133
211 212 213 221 222 223 231 232 233
311 312 313 321 322 323 331 332 333
Forget about swap, and start over.
Think of it like incrementing a number, except you can only use digits 1-N.
E.g. for N=4, start with 1111. Print it.
Increment to 1112, then 1113, then 1114.
Next increment carries over, so 1121, 1122, ..., 1144.
Handle multiple carry overs, 1211.
And so on until you reach 4444, and you're done.
Of course, you could just loop through the N^N combinations, and use division and remainder to build to "digits" for each combination:
private static void perm(int n) {
char[] digits = new char[n];
final int combinations = (int)Math.pow(n, n);
for (int i = 0; i < combinations; i++) {
for (int num = i, j = n - 1; j >= 0; num /= n, j--)
digits[j] = (char)('1' + num % n);
System.out.print(digits);
System.out.print((i + 1) % (n * n) == 0 ? System.lineSeparator() : " ");
}
}
Output
// perm(1)
1
// perm(2)
11 12 21 22
// perm(3)
111 112 113 121 122 123 131 132 133
211 212 213 221 222 223 231 232 233
311 312 313 321 322 323 331 332 333
// perm(4)
1111 1112 1113 1114 1121 1122 1123 1124 1131 1132 1133 1134 1141 1142 1143 1144
1211 1212 1213 1214 1221 1222 1223 1224 1231 1232 1233 1234 1241 1242 1243 1244
1311 1312 1313 1314 1321 1322 1323 1324 1331 1332 1333 1334 1341 1342 1343 1344
1411 1412 1413 1414 1421 1422 1423 1424 1431 1432 1433 1434 1441 1442 1443 1444
2111 2112 2113 2114 2121 2122 2123 2124 2131 2132 2133 2134 2141 2142 2143 2144
2211 2212 2213 2214 2221 2222 2223 2224 2231 2232 2233 2234 2241 2242 2243 2244
2311 2312 2313 2314 2321 2322 2323 2324 2331 2332 2333 2334 2341 2342 2343 2344
2411 2412 2413 2414 2421 2422 2423 2424 2431 2432 2433 2434 2441 2442 2443 2444
3111 3112 3113 3114 3121 3122 3123 3124 3131 3132 3133 3134 3141 3142 3143 3144
3211 3212 3213 3214 3221 3222 3223 3224 3231 3232 3233 3234 3241 3242 3243 3244
3311 3312 3313 3314 3321 3322 3323 3324 3331 3332 3333 3334 3341 3342 3343 3344
3411 3412 3413 3414 3421 3422 3423 3424 3431 3432 3433 3434 3441 3442 3443 3444
4111 4112 4113 4114 4121 4122 4123 4124 4131 4132 4133 4134 4141 4142 4143 4144
4211 4212 4213 4214 4221 4222 4223 4224 4231 4232 4233 4234 4241 4242 4243 4244
4311 4312 4313 4314 4321 4322 4323 4324 4331 4332 4333 4334 4341 4342 4343 4344
4411 4412 4413 4414 4421 4422 4423 4424 4431 4432 4433 4434 4441 4442 4443 4444
If you look at your output, the problem is obvious. You are not accounting for multiple instances of the same number (i.e. 2 2's or 3 3's).
If you want all possible permutations your code is just fine, as permutations are made from swapping elements only and not reusing them.
If you want to build all possible combinations (including aaa, aab, etc.) instead it won't be enough to just swap the elements.
public List<String> combinations(List<Character> elements) {
List<String> combinations = new ArrayList<>();
if (elements.isEmpty()) {
return combinations;
}
if (elements.size() == 1) {
combinations.add(String.valueOf(elements.get(0)));
return combinations;
}
for (int i = 0; i < elements.size(); i++) {
int current = elements.get(i);
List<String> subCombinations = combinations(elements);
StringBuilder builder;
for (String s : subCombinations) {
builder = new StringBuilder();
builder.append(current).append(s);
combinations.add(builder.toString());
}
}
return combinations;
}