generating different distinct permutation of fixed length(L) - java

I am writing a program to generate different permutation of an array with fixed length of 3.
The main problem I am facing is that it always generate dublicate permutation, How can i fix it without using Java set<>.
public class generatingCombination {
public static void main(String[] args) {
String s="ABCDEF";
printArray(s,0,new char[3], new boolean[s.length()]);
}
static void printArray(String s,int x,char []arr, boolean [] used){
if(x==3){
System.out.println(Arrays.toString(arr));
return;
}
else
{
for( int i=0;i<s.length();i++){
if(used[i]) continue;
arr[x]=s.charAt(i);
used[i]=true;
printArray(s, x+1, arr,used);
used[i]=false;
printArray(s, x+1, arr,used);
}
}
}
}

If you're only interested in permutations of length 3, then why not just:
public static void main(String[] args) {
String s = "ABCDEF";
for (int i = 0; i < s.length(); i++) {
for (int j = 0; j < s.length(); j++) {
if (j == i) {
continue;
}
for (int k = 0; k < s.length(); k++) {
if (k == i || k == j) {
continue;
}
System.out.println(Arrays.toString(new char[] { s.charAt(i), s.charAt(j), s.charAt(k)}));
}
}
}
}

Related

How to create simple triagle pattern in Java

I am trying to output a triangle like this one:
19283765
2837465
37465
465
5
However, my actual output looks like this instead:
98765
8765
765
65
5
public class JavaNumber2 {
public static void main(String[] args) {
int r = 9;
for (int g = 9; g <= r; g--) {
for (int j = g; j >= 5; j--) {
System.out.print(j);
}
System.out.println();
}
}
}
How can I modify this so that I get the first output instead?
The condition in the first for loop is wrong g<=r should be g>=0, and one if condition to print in reverse order.
public static void main(String[] args) {
int r = 9;
for (int g = 9; g >=0; g--) {
for (int j = g; j >= 5; j--) {
if(g==9) {
if(j>6) {
System.out.print(r+1-j);
}
}else {
if(j>5) {
System.out.print(r+1-j);
}
}
System.out.print(j);
}
System.out.println();
}
}
I have this answer:
public class T2Tree {
public static void main(String[] args) {
for (int i = 5; i >0; i--) {
for (int j = 0; j < i; j++) {
System.out.print(j+1+5-i);
if (j<i-1) {
System.out.print(9-j+i-5);
}
}
System.out.println();
}
}
}
Or you can use a recursion (works with any start and end as well):
class Ideone
{
public static void main (String[] args)
{
int left = 1;
int right = 9;
while(right >= left){
r(left, right);
System.out.println();
left++;
right--;
}
}
private static void r(int left, int right){
System.out.print(left);
if(left != right){
System.out.print(right);
}
if(right > left){
r(left + 1, right - 1);
}
}
}

Java: Another way of generating permutations? [duplicate]

This question already has answers here:
Generating all permutations of a given string
(57 answers)
Closed 6 years ago.
I have the following code that will generate the permutations of an entered string, but is it possible for it to be changed so that there is no use of the for loop, just recursion?
public static void findPermutations (String beginningString, String endingString) {
if (endingString.length() <= 1)
System.out.println(beginningString + endingString);
else
for (int i = 0; i < endingString.length(); i++) {
try {
String newString = endingString.substring(0, i) + endingString.substring(i + 1);
permuteString(beginningString + endingString.charAt(i), newString);
} catch (StringIndexOutOfBoundsException exception) {
exception.printStackTrace();
}
}
}
Here is an answer that i found somewhere else so no credit to me. Can't find question again though
public class Permutations {
// print N! permutation of the characters of the string s (in order)
public static void perm1(String s) { perm1("", s); }
private static void perm1(String prefix, String s)
{
int N = s.length();
if (N == 0)
{
System.out.println(prefix);
}
else {
for (int i = 0; i < N; i++)
perm1(prefix + s.charAt(i), s.substring(0, i) + s.substring(i+1, N));
}
}
// print N! permutation of the elements of array a (not in order)
public static void perm2(String s) {
int N = s.length();
char[] a = new char[N];
for (int i = 0; i < N; i++)
a[i] = s.charAt(i);
perm2(a, N);
}
private static void perm2(char[] a, int n) {
if (n == 1) {
if(new String(a).contains("ncl-"))
System.out.println(a);
return;
}
for (int i = 0; i < n; i++) {
swap(a, i, n-1);
perm2(a, n-1);
swap(a, i, n-1);
}
}
// swap the characters at indices i and j
private static void swap(char[] a, int i, int j) {
char c = a[i];
a[i] = a[j];
a[j] = c;
}
public static void main(String[] args) throws IOException {
//String word = "nst n-eitoira cp2vmamoocnla1e k nfto-k7re id6";
String word = "doggy";
perm1(word);
System.out.println();
perm2(word);
}
}

How do I simplify these For-loops to save lines of code? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
The output of the code displays the following:
The code below seems pretty funky to me, even as a newbie. I imagine the code can be done more efficiently or at least lines of code can be saved without having to whip out so many loops.
If anyone can provide a cleaner solution, thanks in advance.
public class diamond {
public static void main(String[] args) {
for (int c=1; c<=10; c++) {
for (int d=1; d<=11-c; d++) {
System.out.print("*");
}
for (int e=2; e<c*2; e++) {
System.out.print(" ");
}
for (int i=1; i<=11-c; i++) {
System.out.print("*");
}
System.out.println();
}
for (int f=2; f<=10; f++) {
for (int g=1; g<=f; g++) {
System.out.print("*");
}
for (int h=2; h<22-f*2; h++) {
System.out.print(" ");
}
for (int j=1; j<=f; j++) {
System.out.print("*");
}
System.out.println();
}
}
}
The key is to notice repetitive patterns in your code and factor it out.
You could use a helper method to print a series of N characters:
public static void printNTimes(char value, int n) {
for (int i = 0; i < n; i++) {
System.out.print(value);
}
}
You can generalize the approach by using constants for the characters involved and the size of the diamond.
private static final char OuterChar = '*';
private static final char InnerChar = ' ';
private static final int Size = 10;
And add another helper method to print a row with N instances of one character on the outside, and 2 * (Size - N) characters on the inside:
private static void printRow(int n) {
printNTimes(OuterChar, n);
printNTimes(InnerChar, (Size - n) * 2);
printNTimes(OuterChar, n);
System.out.println();
}
Your code then becomes:
public class diamond
{
private static final char OuterChar = '*';
private static final char InnerChar = ' ';
private static final int Size = 10;
public static void printNTimes(char value, int n) {
for (int i = 0; i < n; i++) {
System.out.print(value);
}
}
private static void printRow(int n) {
printNTimes(OuterChar, n);
printNTimes(InnerChar, (Size - n) * 2);
printNTimes(OuterChar, n);
System.out.println();
}
public static void main(String[] args) {
for (int c = Size; c >= 1; c--) {
printRow(c);
}
for (int c = 2; c <= Size; c++) {
printRow(c);
}
}
}
int max=9,min=10;
for(int i=0;i<19;i++){
for(int j=0;j<20;j++){
if(j<min || j>max){
System.out.print("*");
}
else{
System.out.print(" ");
}
}
if(i<9){
min--;
max++;
}
else {
min++;
max--;
}
System.out.println();
}
I find this rather clear but YMMV.
for( int i = 10; i >= 1; i-- ){
String s = "**********".substring(0, i);
System.out.printf( "%-10s%10s\n", s, s );
}
for( int i = 1; i <= 10; i++ ){
String s = "**********".substring(0, i);
System.out.printf( "%-10s%10s\n", s, s );
}
Since this is repeated within the loop:
for (int d=1; d<=11-c; d++)
{
System.out.print("*");
}
you could write it to a variable and print it out twice. That would eliminate two loops. (one subloop in each outer loop)
I like to wrap logic in code that is easy to read and maintain so instead of doing loads of nested for-loops I wrote a class with descriptive methods.
package se.wederbrand.stackoverflow.diamond;
import java.util.ArrayList;
import java.util.List;
public class Diamond {
final List<String> rows;
public static void main(String[] args) {
System.out.println(new Diamond(10));
}
public Diamond(int width) {
this.rows = new ArrayList<>();
for (int stars = 1; stars <= width; stars++) {
// add all rows, start from the middle and build around it
addRows(stars, width);
}
}
private void addRows(int stars, int width) {
String row = generateRow(stars, width);
// add on top
this.rows.add(0, row);
if (stars > 1) {
// add to bottom
this.rows.add(row);
}
}
private String generateRow(int stars, int width) {
String row = "";
int spaces = width - stars;
for (int j = 0; j < stars; j++) {
row += "*";
}
for (int j = 0; j < spaces; j++) {
row += " ";
}
for (int j = 0; j < stars; j++) {
row += "*";
}
return row;
}
#Override
public String toString() {
String diamond = "";
for (String row : rows) {
diamond += row + System.lineSeparator();
}
return diamond;
}
}
This is an fun question as you get to see how everybody takes a different approach to solving it. This way just gives you a string that is "padded" with another character on the other side.
public static void main(String[] args) {
for (int c = 1; c <= 10; c++) {
System.out.println(printPadded(11 - c, '*', (c - 1) * 2, ' '));
}
for (int f = 10; f >= 2; f--) {
System.out.println(printPadded(11 - f, '*', (f - 1) * 2, ' '));
}
}
public static String printPadded(int padCount, char padCharacter,
int middleCount, char middleCharacter) {
StringBuilder s = new StringBuilder(padCount * 2 + middleCount);
for (int i = 0; i < padCount; i++) {
s.append(padCharacter);
}
for (int i = 0; i < middleCount; i++) {
s.append(middleCharacter);
}
for (int i = 0; i < padCount; i++) {
s.append(padCharacter);
}
return s.toString();
}

How to find the Odd and Even numbers in an Array?

Right now, I'm trying to find the odd and even numbers of an array. Here's the code of what I have so far. I know my findEvens() and findOdds() methods are messed up because they keep giving me off values whenever I try to print the final result. For example, if I try to find the odds of {1,5,8,3,10}, it gives me {5,3,0}. And if I try to find the evens of {2,5,8,7,19}, it gives me {2,8,0}. Anyone know why?
public class Scores {
private int[] numbers;
public Scores(int[] numbersIn) {
numbers = numbersIn;
}
public int[] findEvens() {
int numberEvens = 0;
for (int i = 0; i < numbers.length; i++) {
if (i % 2 == 0) {
numberEvens++;
}
}
int[] evens = new int[numberEvens];
int count = 0;
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] % 2 == 0) {
evens[count] = numbers[i];
count++;
}
}
return evens;
}
public int[] findOdds() {
int numberOdds = 0;
for (int i = 0; i < numbers.length; i++) {
if (i % 2 == 0) {
numberOdds++;
}
}
int[] odds = new int[numberOdds];
int count = 0;
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] % 2 == 1) {
odds[count] = numbers[i];
count++;
}
}
return odds;
}
public double calculateAverage() {
int sum = 0;
for (int i = 0; i < numbers.length; i++) {
sum += numbers[i];
}
return (double) sum / numbers.length;
}
public String toString() {
String result = "";
for (int i = 0; i < numbers.length; i++) {
result += numbers[i] + "\t";
}
return result;
}
public String toStringInReverse() {
String result = "";
for (int i = numbers.length - 1; i >= 0; i--) {
result += numbers[i] + "\t";
}
return result;
}
}
You're problem is in counting how many even numbers you have
public int[] findEvens() {
int numberEvens = 0;
for (int i = 0; i < numbers.length; i++) {
if (i % 2 == 0) {
numberEvens++;
}
}
this will always return a number that is half the size of the length of numbers because you're doing mod division on the number of elements in the array, not on the elements themselves. Add numbers[i] to the if statement
public int[] findEvens() {
int numberEvens = 0;
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] % 2 == 0) {
numberEvens++;
}
}
looks like you've got the same problem with odd count
'i' is used as conditional variable for looping. You should not divide this by 2. You have to divide the array element. like
if (numbers[i] % 2 == 0) {
numberEvens++;
}
then it should work. Thanks
Try This Code
import java.util.Scanner;
public class OddEven {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("enter number Elements in Array");
int n = s.nextInt();
int arr[] = new int[n];
System.out.println("enter Elements ");
for(int i=0; i<n; i++) {
arr[i]=s.nextInt();
}
int [] odd = filterOdd(arr);
try {
for(int i=0; i<n; i++) {
System.out.println("Odd" + odd[i]);
}
} catch(ArrayIndexOutOfBoundsException e) {}
int [] even = filterEven(arr);
try {
for(int i=0; i<n; i++) {
System.out.println("Even" + even[i]);
}
} catch(ArrayIndexOutOfBoundsException e) {}
}
public static int[] filterOdd(int[] a) {
int l = 0;
int j = 0;
for(int i=0; i<a.length; i++) {
if(a[i]%2==1) {
l++;
}
}
int k[]=new int[l];
for(int i=0; i<a.length; i++) {
if(a[i]%2==1) {
k[j] = a[i];
j++;
}
}
return k;
}
public static int[] filterEven(int[] a) {
int l = 0;
int j = 0;
for(int i=0; i<a.length; i++) {
if(a[i]%2==0) {
l++;
}
}
int k[] = new int[l];
for(int i=0; i<a.length; i++) {
if(a[i]%2==0) {
k[j] = a[i];
j++;
}
}
return k;
}
}
public class Array {
public static void main(String[] args) {
// TODO code application logic here
//Array declaration and value asign
int number[]=new int[]{1,2,3,4,5,6,7,8,9};
// for loop to move number
for(int p=0;p<number.length;p++)
{
// check number is even or odd??
if(number[p]%2==0)
System.out.println(number[p]+ " is Even number");
else
System.out.println( number[p]+" is odd umber");
}
}
}
Odd array one columns and another columns even array
public class OddEven {
public static void main(String[] args) {
int arr[]={1,2,3,4,5,6,7,8};
int ss[]=new int[10];
int odd[]=new int[10];
int i;
int k;
for( i=0;i<arr.length;i++)
{
if(arr[i]%2==0)
{
ss[i]=arr[i];
System.out.print(""+ss[i]);
System.out.print(" ");
}
if((arr[i]%2)!=0)
{
odd[i]=arr[i];
System.out.print(""+odd[i]);
System.out.print(" ");
}else
{
System.out.println(" ");
}
}
}
}
========================================output==============================
1 2
3 4
5 6
7 8

Printing special characters in a for loop instead of numbers

This is what the program is printing:
(0,0)(0,1)(0,2)
(1,0)(1,1)(1,2)
(2,0)(2,1)(2,2)
What I want it to do is to print ( * ) in replace of (1,1). I know an if statement is involved, but I'm having a hard time trying to figure out the condition I should put.
public class loops {
public static void main(String[] args)
{
int i=1;
for (int k = i-1; i< 4; i++)
{
int j =1;
for (int l = j-1; j < 4; j++)
{
if (k ==i+1 && l == j+1) System.out.print("( * )");
else System.out.print("("+k+","+l+")");
l++;
}
System.out.println();
k++;
}
}
}
The if condition is part of it, but you are also complicating your for loops, try this:
public class loops {
public static void main(String[] args)
{
for (int k = 0; k<3; k++)
{
for (int j = 0; j<3; j++)
{
if (k ==1 && j == 1)
{
System.out.print("( * )");
} else {
System.out.print("("+k+","+j+")");
}
}
System.out.println("");
}
}
}
you should just validate if both values are equal to 1 then print (*) , otherwise the result

Categories