Generating permutations of an int array using java -- error - java

I am writing a JAVA code to generate all permutations of a integer array.
Though I am getting the number of permutations right, the permutations themselves are not correct.
On running I obtain:
Input array Length
3
1
2
3
0Permutation is
1, 2, 3,
##########################
1Permutation is
1, 3, 2,
##########################
2Permutation is
3, 1, 2,
##########################
3Permutation is
3, 2, 1,
##########################
4Permutation is
1, 2, 3,
##########################
5Permutation is
1, 3, 2,
##########################
6 number of permutations obtained
BUILD SUCCESSFUL (total time: 3 seconds)
public class PermulteArray {
public static int counter = 0;
public static void Permute(int[] input, int startindex) {
int size = input.length;
if (size == startindex + 1) {
System.out.println(counter + "Permutation is");
for (int i = 0; i < size; i++) {
System.out.print(input[i] + ", ");
}
System.out.println();
System.out.println("##########################");
counter++;
} else {
for (int i = startindex; i < size; i++) {
int temp = input[i];
input[i] = input[startindex];
input[startindex] = temp;
Permute(input, startindex + 1);
}
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Input array Length");
int arraylength = in.nextInt();
int[] input = new int[arraylength];
for (int i = 0; i < arraylength; i++) {
input[i] = in.nextInt();
}
counter = 0;
Permute(input, 0);
System.out.println(counter + " number of permutations obtained");
}
}

int temp=input[i];
input[i]=input[startindex];
input[startindex]=temp;
Permute(input, startindex+1);
You've swapped an element before calling Permute but you need to swap it back again afterwards to keep consistent positions of elements across iterations of the for-loop.

This is the best solution I have seen so far :
public static void main(String[] args) {
int[] a = { 1, 2, 3, 4, 5, 6 };
permute(0, a);
}
public static void permute(int start, int[] input) {
if (start == input.length) {
//System.out.println(input);
for (int x : input) {
System.out.print(x);
}
System.out.println("");
return;
}
for (int i = start; i < input.length; i++) {
// swapping
int temp = input[i];
input[i] = input[start];
input[start] = temp;
// swap(input[i], input[start]);
permute(start + 1, input);
// swap(input[i],input[start]);
int temp2 = input[i];
input[i] = input[start];
input[start] = temp2;
}
}

check this out
for (int i = startindex; i < input2.length; i++) {
char[] input = input2.clone();
char temp = input[i];
input[i] = input[startindex];
input[startindex] = temp;
permute(input, startindex + 1);
}

//This will give correct output
import java.util.Scanner;
public class PermulteArray {
public static int counter = 0;
public static void Permute(int[] input, int startindex) {
int size = input.length;
if (size == startindex + 1) {
System.out.println(counter + "Permutation is");
for (int i = 0; i < size; i++) {
System.out.print(input[i] + ", ");
}
System.out.println();
System.out.println("##########################");
counter++;
} else {
for (int i = startindex; i < size; i++) {
int temp = input[i];
input[i] = input[startindex];
input[startindex] = temp;
Permute(input, startindex + 1);
temp = input[i];
input[i] = input[startindex];
input[startindex] = temp;
}
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Input array Length");
int arraylength = in.nextInt();
int[] input = new int[arraylength];
for (int i = 0; i < arraylength; i++) {
input[i] = in.nextInt();
}
counter = 0;
Permute(input, 0);
System.out.println(counter + " number of permutations obtained");
}
}

You can solve this using recursive calls.
https://github.com/Pratiyush/Master/blob/master/Algorithm%20Tutorial/src/arrays/Permutations.java
public void swap(int[] arr, int i, int j)
{
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
public void permute(int[] arr, int i)
{
if (i == arr.length)
{
System.out.println(Arrays.toString(arr));
return;
}
for (int j = i; j < arr.length; j++)
{
swap(arr, i, j);
permute(arr, i + 1); // recurse call
swap(arr, i, j); // backtracking
}
}
public static void main(String[] args) {
Permutations permutations = new Permutations();
int[] arr = {1, 2, 3,4};
permutations.permute(arr, 0);
}
Also, other approaches are available in
http://www.programcreek.com/2013/02/leetcode-permutations-java/
http://www.programcreek.com/2013/02/leetcode-permutations-ii-java/

public class PermuteArray {
public static void permute(char[] input2, int startindex) {
if (input2.length == startindex) {
displayArray(input2);
} else {
for (int i = startindex; i < input2.length; i++) {
char[] input = input2.clone();
char temp = input[i];
input[i] = input[startindex];
input[startindex] = temp;
permute(input, startindex + 1);
}
}
}
private static void displayArray(char[] input) {
for (int i = 0; i < input.length; i++) {
System.out.print(input[i] + "; ");
}
System.out.println();
}
public static void main(String[] args) {
char[] input = { 'a', 'b', 'c', 'd'};
permute(input, 0);
}
}

import java.util.ArrayList;
public class RecursivePermGen {
void permGen(int n, int m, ArrayList<Integer> cur) {
if(m == 0) {
System.out.println(cur);
return;
}
for(int i = 1; i <= n; i++) {
cur.add(0, i);
permGen(n, m-1, cur);
cur.remove(0);
}
}
public static void main(String[] args) {
RecursivePermGen pg = new RecursivePermGen();
ArrayList<Integer> cur = new ArrayList<Integer>();
pg.permGen(2, 2, cur);
}
}

I have simple answer for this question, you can try with this.
public class PermutationOfString {
public static void main(String[] args) {
permutation("123");
}
private static void permutation(String string) {
printPermutation(string, "");
}
private static void printPermutation(String string, String permutation) {
if (string.length() == 0) {
System.out.println(permutation);
return;
}
for (int i = 0; i < string.length(); i++) {
char toAppendToPermutation = string.charAt(i);
String remaining = string.substring(0, i) + string.substring(i + 1);
printPermutation(remaining, permutation + toAppendToPermutation);
}
}
}

A solution i have used several times (mostly for testing purposes) is in the following gist. It is based on the well-known algorithm to generate permutations in lexicographic order (no recursion):
/**
* Compute next (in lexicographic order) permutation and advance to it.
*
* Find greater index i for which a j exists, such that:
* j > i and a[i] < a[j] (i.e. the 1st non-inversion).
* For those j satisfying the above, we pick the greatest.
* The next permutation is provided by swapping
* items at i,j and reversing the range a[i+1..n]
*/
void advanceToNext() {
// The array `current` is the permutation we start from
// Find i when 1st non-inversion happens
int i = n - 2;
while (i >= 0 && current[i] >= current[i + 1])
--i;
if (i < 0) {
// No next permutation exists (current is fully reversed)
current = null;
return;
}
// Find greater j for given i for 1st non-inversion
int j = n - 1;
while (current[j] <= current[i])
--j;
// Note: The range a[i+1..n] (after swap) is reverse sorted
swap(current, i, j); // swap current[i] <-> current[j]
reverse(current, i + 1, n); // reverse range [i+1..n]
}
A complete solution (in the form of a class) lies here:
https://gist.github.com/drmalex07/345339117fef6ca47ca97add4175011f

Related

Method to find second highest number in an array in java

Getting output of 0 each time when im ment to get 3 looked over my code my not sure where i have gone wrong i can do it without using a method i know but just trying to practice java
public class App {
public static int second(int a[],int n) {
int[] arr = new int [n];
int temp;
for(int i=0;i<n;i++) {
for(int j=i+1;j<n;j++) {
if(arr[i] > arr[j]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
return arr[n-2];
}
public static void main(String[] args) {
int[] arr = {1,3,2,5,3};
int n = 5;
int result = second(arr,n);
System.out.println(result);
}
}
You could change the array parameter name arr and remove the declaration or copy the values from a to arr.
public static int second(int arr[],int n) {
int temp;
for(int i=0;i<n;i++) {
for(int j=i+1;j<n;j++) {
if(arr[i] > arr[j]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
return arr[n-2];
}
The reason you get zero is because the primitive int cannot be null. So, when you create the array of length 5, it starts out filled with zeroes.
Doing it by using streams:
public static int second(int a[]) {
return Arrays.stream(a)
.sorted()
.skip(a.length - 2)
.findFirst()
.getAsInt();
}
I removed the second argument. It sorts your array and skips all the elements prior to the one you want, before picking the now first element.
public static int second(int[] arr) {
int highest = arr[0];
int second = 0;
for (int i = 1; i < arr.length; i++) {
int j = arr[i];
if (j >= highest) {
highest = j;
} else if (j > second) {
second = j;
}
}
return second;
}
public static void main(String[] args) {
int[] arr = {1, 3, 2, 5, 3};
int result = second(arr);
System.out.println(result);
}
Here is one way that doesn't require sorting.
int[] arr = { 10, 2, 3, 19, 2, 3, 5 };
System.out.println(second(arr));
prints
10
set largest to the first value in the array
set secondLargest to the smallest possible
now iterate thru the array.
if the current value is greater than largest:
replace secondLargest with Largest
replace largest with current value
else check to see if current value is greater than secondLargest and assign if true.
public static int second(int arr[]) {
int largest = arr[0];
int secondLargest = Integer.MIN_VALUE;
for (int i = 1; i < arr.length; i++) {
if (arr[i] > largest) {
secondLargest = largest;
largest = arr[i];
} else if (arr[i] > secondLargest) {
secondLargest = arr[i];
}
}
return secondLargest;
}
public static int second(int arr[],int n) {
int temp;
if(arr.length < 2) {
return -1;
}
else {
for(int i=0;i<n;i++) {
for(int j=i+1;j<n;j++) {
if(arr[i] > arr[j]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
return arr[n-2];
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int a[] = {23,14,56,77,66,67};
int high = 0;
int sec = 0;
for(int i = 0 ; i <a.length; i++){
if(high < a[i]){
sec = high;
high = a[i];
}
else if(sec < a[i]){
sec = a[i];
}
}
System.out.println("the first highest number is " + high);
System.out.println("the second highest number is " + sec);
}
}
public static int sec(){
int arr[] = {12,3,67,4,5,65};
int high = 0;
int low = 0;
for(int i = 0 ; i < arr.length ; i ++){
if(high < arr[i]){
low = high;
high = arr[i];
}
else if(low < arr[i]){
low = arr[i];
}
}
return low;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
sch obj = new sch();
int a = obj.sec();
System.out.println(a);
}
}
package com;
public class FindSecondHighestNumberInArray {
public static void main(String[] args) {
int []arrayOfIngeger = {-23,-989,-878,-2,-5,-3,-4,-123,-345,-98,-675,-98};
int highestNumber = arrayOfIngeger[0];
int secHighestNumber = 0;
for(int i = 1; i < arrayOfIngeger.length; i++ ) {
if(highestNumber < arrayOfIngeger[i]) {
secHighestNumber = highestNumber;
highestNumber = arrayOfIngeger[i];
}else if(secHighestNumber < arrayOfIngeger[i] && arrayOfIngeger[i] != highestNumber) {
secHighestNumber = arrayOfIngeger[i];
}
}
System.out.println("second Highest Number in Array : "+secHighestNumber);
}
}

Finding contiguous array

I am trying to get an output of [4,6,6,7] with length 4 where arr[i] <= arr[i+1] where it is non-decreasing and it is contiguous. I know what i have to do but i dont know how to do it. my code prints out [3,4,6,6,7]. I am just having trouble on the contiguous part, any help? im not allowed to use extra arrays.
public static void ascentLength(int arr[], int size) {
int length = 0;
int index = 0;
int count = 1;
for (int i = 0; i < size-1; i++) {
index = i;
if (arr[0] <= arr[i+1] && count >0) {
System.out.println(arr[i]+ " index:" + index);
length++;
count++;
}
if (arr[0] >= arr[i+1]) {
}
}
System.out.println("length: " + length);
}
/* Driver program to test above function */
public static void main(String[] args) {
int arr[] = {5, 3, 6, 4, 6, 6, 7, 5};
int n = arr.length;
ascentLength(arr, n);
}
Here is my solution, it would be easier, if you could work with List, but this works for arrays:
public static void ascentLength(int arr[], int size) {
if(size == 1) System.out.println("length: 1");
// variables keeping longest values
int longestStartingIndex = 0;
int longestLength = 1;
// variables keeping current values
int currentStartingIndex = 0;
int currentCount = 1;
for (int i = 1; i < size; i++) {
if (arr[i-1] <= arr[i]) {
currentCount++;
} else {
// check if current count is the longest
if(currentCount > longestLength) {
longestLength = currentCount;
longestStartingIndex = currentStartingIndex;
}
currentStartingIndex = i;
currentCount = 1;
}
}
if(currentCount > longestLength) {
longestLength = currentCount;
longestStartingIndex = currentStartingIndex;
}
}

Finding most frequency number in array

By using following I am able to find most frequently occurring integer in an array. But following code it will not work for few scenarios. How can I fix the code inside for loop? I want to enhance this approach only.
class FindingMostFrequencyOccur {
public static void main(String args[]) {
int A[] = { 1, 2, 3, 3, 1, 3, 1};
int M = 3; // Maximum Number in Array
int result = findFrequency(M, A);
System.out.println("Result "+result);
}
static int findFrequency(int M, int[] A) {
int N = A.length;
int[] count = new int[M + 1];
for (int i = 0; i <= M; i++)
count[i] = 0;
int maxOccurence = 1;
int index = -1;
for (int i = 0; i < N; i++) {
if (count[A[i]] > 0) {
int tmp = count[A[i]];
if (tmp > maxOccurence) {
maxOccurence = tmp;
index = i;
}
count[A[i]] = tmp + 1;
} else {
count[A[i]] = 1;
}
}
return A[index];
}
}
Can you we improve in this line
if (count[A[i]] > 0) {
int tmp = count[A[i]];
if (tmp > maxOccurence) {
maxOccurence = tmp;
index = i;
}
count[A[i]] = tmp + 1;
} else {
count[A[i]] = 1;
}
To get the frequency of m in a use:
static int findFrequency(int m, int[] a) {
return (int)IntStream.of(a).filter(i-> i==m).count();
}
To get a map of all frequencies in a use:
static Map<Integer, Integer> findFrequency(int[] a) {
Map<Integer, Integer> m = new HashMap<>();
IntStream.of(a).distinct().forEach(i->{
m.put(i, findFrequency(i,a));
});
return m;
}
In this logic, you take each element of the array, and find the number of times it is repeated to the right of it, in the array. This is given by local_frequency. If this happens to be more than max_frequency, then this number at arr[i] is stored in number, and then max_frequency stores local_frequency
public static void main(String[] args)
{
int[] arr = {1, 2, 3, 4, 3, 2, 1, 5, 5, 5, 4, 4, 3, 4};
int result = findMostFrequent(arr);
System.out.println(result + " is the most frequent number");
}
public static int findMostFrequent(int[] arr)
{
int number = arr[0];
int maxFrequency = 0;
for(int i =0 ; i < arr.length; i++)
{
int local_frequency = 0;
for(int j = i; j < arr.length; j++)
{
if(arr[i] == arr[j])
local_frequency++;
}
if(local_frequency > maxFrequency)
{
number = arr[i];
maxFrequency = local_frequency;
}
}
return number;
}

search palindrome number in a list of array. if there exist palindrome number in the list, return its size

Check if there exists a Palindrome Number in the list.
If found return its size, else return -1.
public class Program{
public static boolean palindrome(String list){
String reversedString = "";
for (int i = list.length() -1; i >=0; i--){
reveresedString += list.charAt(i)
}
return list.equals(revereseString);
}
}
sample input: [3,5,2,6,3,6,2,1]
palindrome number found: [2,6,3,6,2]
sample output: 5
Here is a pseudo code.
output = -1;
for (i = 0; i < list.length; i++){
num = list[i];
indices[] = \\ get all the indices which the "num" value appears, only include those indices that are greater than "i"
for (j = 0; j < indices.length; j++){
flag = true;
k = i;
for (l = indices[j]; l >= k; l--, k++){
if (list[k] != list[l]) {
flag = false;
break;
}
}
if (flag){
length = (indices[j] - i) + 1;
if (length != 1 && length > output) { // checking of length != 1 will exclude those palindromes of length 2
output = length;
}
}
}
}
return output;
Here is the full code.
public class Main {
/**
* #param args
*/
public static void main(String[] args) {
int[] list = { 3, 5, 2, 2, 6, 3, 6, 3, 6, 3, 6, 2, 2, 1 };
System.out.print(palindrome(list));
}
public static int palindrome(int[] list) {
int output = -1;
for (int i = 0; i < list.length; i++) {
int num = list[i];
ArrayList<Integer> indices = getIndices(list, i, num);
for (int j = 0; j < indices.size(); j++) {
boolean flag = true;
int k = i;
for (int l = indices.get(j); l >= k; l--, k++) {
if (list[k] != list[l]) {
flag = false;
break;
}
}
if (flag) {
int length = (indices.get(j) - i) + 1;
if (length != 1 && length > output) {
output = length;
}
}
}
}
return output;
}
public static ArrayList<Integer> getIndices(int[] list, int start, int num) {
ArrayList<Integer> result = new ArrayList<Integer>();
for (int i = start + 1; i < list.length; i++) {
if (list[i] == num) {
result.add(i);
}
}
return result;
}
}

Quicksort by length of String in Array

I have strings scanned from the user. Next step is to sort array by the length of text, I don't know what I'm doing wrong, sometimes it's working.
public static void quickSort(String[] subtitles, int start, int end) {
int i = start;
int j = end;
if (j - i >= 1) {
String pivot = subtitles[i];
while (j > 1) {
while (subtitles[i].compareTo(pivot) <= 0 && i < end && j > i)
i++;
while (subtitles[j].compareTo(pivot) >= 0 && j > start && j >= i)
j--;
if (j > i)
swap(subtitles, i, j);
}
swap(subtitles, start, j);
quickSort(subtitles, start, j - 1);
quickSort(subtitles, j + 1, end);
} else
return;
}
public static void swap(String[] a, int i, int j) {
String tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int amountStrings = 3;
String[] subtitles = new String[amountStrings];
System.out.println("insert ");
for (int i = 0; i < amountStrings; i++) {
subtitles[i] = scan.next();
}
System.out.println("--------");
quickSort(subtitles, 0, subtitles.length - 1);
for (int i = 0; i < subtitles.length; i++) {
System.out.print(subtitles[i] + " ");
}
Incorrect:
In:
asdzxc asd zxc
Out:
asd asdzxc zxc
Correct:
In:
sdf sdfsfwer s
Out:
s sdf sdfsfwer
Ok, I reviewed your code and made two new methods. One sorts the array alphabetically and one sorts by counting the number of letters in each word of the array. It is up to you what methods fits you well.
Tested and working.
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;
public class Subtitles {
public static void sortAlfabetical(String x[]) {
int j;
boolean found = true; // will determine when the sort is finished
String temp;
while (found) {
found = false;
for (j = 0; j < x.length - 1; j++) {
if (x[j].compareToIgnoreCase(x[j + 1]) > 0) { // ascending sort
temp = x[j];
x[j] = x[j + 1]; // swap
x[j + 1] = temp;
found = true;
}
}
}
for (int i = 0; i < x.length; i++) {
System.out.print(x[i] + " ");
}
}
public static void compare(String[] arrayOne) {
Arrays.sort(arrayOne, new Comparator<String>() {
#Override
public int compare(String o1, String o2) {
return o1.length() - o2.length();
}
});
for (String s : arrayOne) {
System.out.print(s + " ");
}
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int amountStrings = 3;
String[] subtitles = new String[amountStrings];
System.out.println("insert ");
for (int i = 0; i < amountStrings; i++) {
subtitles[i] = scan.next();
}
System.out.println("--------");
System.out.print("Sorting alphabetical: ");
sortAlfabetical(subtitles);
System.out.println();
System.out.println("===========================");
System.out.print("Sorting by word length: ");
compare(subtitles);
}
}

Categories