Printing all permutations of integer array in Java [duplicate] - java

This question already has answers here:
Getting permutations of an int[] removing duplicates sets
(5 answers)
Closed 7 years ago.
I've just written a code for printing all the possible permutations from 1 to n in an int array in Java, but I think it is more complex than it needs to be. I am using Hashset to avoid repetitions. If someone finds something than can be simplified, please write.
import java.util.*;
public class ProblemFour {
private static int n;
private static void printResult(int[] result) {
Set<Integer> set = new HashSet<>();
Integer[] nums = new Integer[result.length];
for (int i = 1; i <= n; i++) {
nums[i - 1] = result[i - 1];
}
for (Integer num : nums) {
set.add(num);
}
if(set.size() == n) {
String s = "[ ";
for (Integer num : nums) {
s += num + " ";
}
System.out.println(s + "] ");
}
}
private static void permute(int[] result, int index) {
if (index == result.length) {
printResult(result);
return;
}
for (int i = 1; i <= n; i++) {
result[index] = i;
permute(result, index+1);
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("From 1 to: ");
n = input.nextInt();
int[] result = new int[n];
permute(result, 0);
}
}

I made this permutations code way back it uses lists as a data structure in it.
public List<List<Integer>> permute(int[] numbers) {
// we use a list of lists rather than a list of arrays
// because lists support adding in the middle
// and track current length
List<List<Integer>> permutations = new ArrayList<List<Integer>>();
// Add an empty list so that the middle for loop runs
permutations.add(new ArrayList<Integer>());
for ( int i = 0; i < numbers.length; i++ ) {
// create a temporary container to hold the new permutations
// while we iterate over the old ones
List<List<Integer>> current = new ArrayList<List<Integer>>();
for ( List<Integer> permutation : permutations ) {
for ( int j = 0, n = permutation.size() + 1; j < n; j++ ) {
List<Integer> temp = new ArrayList<Integer>(permutation);
temp.add(j, numbers[i]);
current.add(temp);
}
}
permutations = new ArrayList<List<Integer>>(current);
}
return permutations;
}

Related

Turning multi-line string into array in java

I am making a function that can turn a number into a simplified radical square root. I have so far made a function that can return the factors of a number. I want to turn the string into an array so I can index through the numbers in a for loop and test if they have a perfect square root. How can I do this?
This is what I have so far:
public static void factor(int num) {
for (int i = 1; i <= num; ++i) {
if (num % i == 0) {
System.out.println(i);
}
}
}
inputing the number 20 outputs
1
2
4
5
10
20
I want to turn this into {1, 2, 4, 5, 10, 20}
You can store them in a List when you print.
public static void factor(int num) {
List<Integer> list = new ArrayList<Integer>();
for (int i = 1; i <= num; ++i) {
if (num % i == 0) {
list.add(i);
System.out.println(i);
}
}
//iterate over the list
for(int val: list){
//do something with val
}
}
However if you only want to convert a multi-line string to an array, do
yourMultiLineString.split("\n");
Read using a Scanner, store in a List, then use the .toArray() method.
List<Integer> l = new ArrayList<>();
Scanner sc = new Scanner(System.in);
for(int i = 0; i < 7; i++){
l.add(Integer.parseInt(sc.nextLine()));
}
int[] arr = (int[]) l.toArray();
You need to create a list of integers and push your data into it just like the list in below code:
public static void factor(int num) {
List<Integer> list = new ArrayList<>();
for (int i = 1; i <= num; ++i) {
if (num % i == 0) {
list.add(i);
}
}
for(Integer i: list) {
System.out.println(i);
}
// OR via indexing
for(int i=0; i<list.size(); i++) {
System.out.println(list.get(i));
}
}
}

saving odd numbers between two number in an array [duplicate]

This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 3 years ago.
Trying to save odd numbers between 2 numbers in an array
public class OddNumber {
static int[] oddNumbers(int l, int r) {
if (r <= l)
return null;
int size = ((r - l) / 2) + 1;
int arr[] = new int[size];
int p = 0;
for (int i = l; i <= r; i++) {
if (i % 2 != 0) {
arr[p] = i;
p++;
}
}
return arr;
}
public static void main(String[] args) {
System.out.println("Odd numbers between 2 & 9 are: " + oddNumbers(2, 9));
}
}
It is always giving same junk value "Odd numbers between 2 & 9 are: [I#15db9742". I dont know what is the problem
public class Solution {
static int[] oddNumbers(int l, int r) {
List<Integer> list = new ArrayList<>();
for (int i = l; i <= r; i++) {
if (i % 2 == 0) {
list.add(i);
}
}
int arr[] = new int[list.size()];
for(int i = 0 ; i < list.size(); i++) {
arr[i]=list.get(i);
}
return arr;
}
public static void main(String[] args) {
int arr[] = oddNumbers(2, 9);
for(int i : arr) {
System.out.print(i + " ");
}
}
}

Counting Sort implementation

Hello I am having difficulty implementing a counting sort method in java. I believe the problem comes from the last two loops I have in the method. I am getting an ArrayIndexOutOfBounds exception : 8. I believe this comes from my second to last for loop when at index 5 the value is 8 but I am not sure how to resolve this. Any help is appreciated. Thank you!
In my code k is the highest value in the input array.
Code:
public static void main(String[] args) {
int [] arrayOne = {0,1,1,3,4,5,3,0};
int [] output = Arrays.copyOf(arrayOne, arrayOne.length);
System.out.println(Arrays.toString(arrayOne));
countingSort(arrayOne, output, 5);
System.out.println(Arrays.toString(output));
}
public static void countingSort(int[] input, int[] output , int k){
int [] temp = Arrays.copyOf(input, k+1);
for (int i = 0; i <= k; i++){
temp[i] = 0;
}
for (int j = 0; j <= input.length - 1; j++){
temp[input[j]] = temp[input[j]] + 1;
}
for (int i = 1; i <= k; i++){
temp[i] = temp[i] + temp[i-1];
}
for (int j = input.length; j >= 1; j--){
output[temp[input[j]]] = input[j];
temp[input[j]] = temp[input[j]] - 1;
}
}
The problem is in the first loop because the array temp lenght is 6 and you are doing 7 interations in there.
So at the end of the for it is trying to do temp[6]=0 and the last position of your array is temp[5].
To fix this change your first loop to:
for (int i = 0; i < k; i++){
In the last loop you will get the same exception cause input[8] doesn't exist.
import java.util.Arrays;
public class CountingSort {
public static void main(String[] args) {
int[] input = {0,1,1,3,4,5,3,0};
int[] output = new int[input.length];
int k = 5; // k is the largest number in the input array
System.out.println("before sorting:");
System.out.println(Arrays.toString(input));
output = countingSort(input, output, k);
System.out.println("after sorting:");
System.out.println(Arrays.toString(output));
}
public static int[] countingSort(int[] input, int[] output, int k) {
int counter[] = new int[k + 1];
for (int i : input) { counter[i]++; }
int ndx = 0;
for (int i = 0; i < counter.length; i++) {
while (0 < counter[i]) {
output[ndx++] = i;
counter[i]--;
}
}
return output;
}
}
Above code is adapted from: http://www.java67.com/2017/06/counting-sort-in-java-example.html
this may help but try using the Arraya.sort() method.
e.g:
//A Java program to sort an array of integers in ascending order.
// A sample Java program to sort an array of integers
// using Arrays.sort(). It by default sorts in
// ascending order
import java.util.Arrays;
public class SortExample
{
public static void main(String[] args)
{
// Our arr contains 8 elements
int[] arr = {13, 7, 6, 45, 21, 9, 101, 102};
Arrays.sort(arr);
System.out.printf("Modified arr[] : %s",
Arrays.toString(arr));
}
}
example is a snippet from https://www.geeksforgeeks.org/arrays-sort-in-java-with-examples/
As per algorithm following implementation, I have prepared for the count sort technique
public static int[] countSort(int elements[]) {
int[] sorted = new int[elements.length+1];
int[] range = new int[getMax(elements)+1];
for(int i=0;i<range.length;i++) {
range[i] = getCount(i, elements);
try {
range[i] = range[i]+range[i-1];
}catch(ArrayIndexOutOfBoundsException ae) {
continue;
}
}
for(int i=0;i<elements.length;i++) {
sorted[range[elements[i]]] = elements[i];
range[elements[i]] = range[elements[i]]-1;
}
return sorted;
}
public static int getCount(int value,int[] elements) {
int count = 0;
for(int element:elements) {
if(element==value) count++;
}
return count;
}
public static int getMax(int elements[]) {
int max = elements[0];
for(int i=0;i<elements.length;i++) {
if(max<elements[i]) {
max = elements[i];
}
}
return max;
}
Please review and let me know if any feedback and it is more helpful.
Note :
Non-negative no won't support in the above implementation.
don't use 0th index of the sorted array.

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.

having issues with a quicksort method

So i am doing a challenge located at https://www.hackerrank.com/challenges/quicksort2 and im having trouble wrapping my head around doing this the way they want. They are asking for the program to do a quicksort using subArrays and then put those sub arrays together at the end to come up with the result. Here is the challenge and i will have my code below. needless to say i don't have it working. All the code was provided and the challenge is to write the partition method
Print Sub-Arrays
In this challenge, print your array every time your partitioning method finished, i.e. print every sorted sub-array The first element in a sub-array should be used as a pivot. Partition the left side before partitioning the right side. The pivot should not be added to either side. Instead, put it back in the middle when combining the sub-arrays together.
Input Format
There will be two lines of input:
n - the size of the array
ar - the n numbers of the array
Output Format
Print every partitioned sub-array on a new line.
Constraints
1<=n<=1000
-1000<=x<= 1000 , x ∈ ar
There are no duplicate numbers.
Sample Input
7
5 8 1 3 7 9 2
Sample Output
2 3
1 2 3
7 8 9
1 2 3 5 7 8 9
Code
import java.util.*;
public class Solution {
static int[] result;
static void partition(int[] ar) {
int p = 0;
int s = 0;
int l = 0;
int small[] = new int[ar.length];
int pivot[] = new int[ar.length];
int large[] = new int[ar.length];
for(int i = 0; i < ar.length; i++){
if(i == 0 || ar[i]==pivot[0]){
pivot[p] = ar[i];
p++;
}
else if(ar[i]>pivot[0]){
large[l] = ar[i];
l++;
}
else if(ar[i]<pivot[0]){
small[s] = ar[i];
s++;
}
}
if(s>2){
int[] smallA = new int[s];
for(int i = 0; i < s; i ++){
smallA[i] = small[i];
}
partition(smallA);
}
if(l>2){
int[] largeA = new int[l];
for(int i = 0; i < l; i ++){
largeA[i] = large[i];
}
partition(largeA);
}
}
static void printArray(int[] ar) {
for(int n: ar){
System.out.print(n+" ");
}
System.out.println("");
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] ar = new int[n];
result = new int[n];
for(int i=0;i<n;i++){
ar[i]=in.nextInt();
}
partition(ar);
}
}
i have to use this format, i can edit the partition method but the rest stays per rules of the challenge
I haven't checked your code, but this seems to work. It's easier to make it with List
import java.util.*;
public class quickSorter
{
public quickSorter()
{
}
public List<Integer> partition(List<Integer> list){
int pivot = list.get(0);
List<Integer> result;
List<Integer> leftSide = new ArrayList<>();
List<Integer> rightSide = new ArrayList<>();
for (int i=0;i<list.size();i++){
if (list.get(i)<pivot){
leftSide.add(list.get(i));
}
else if (list.get(i)>pivot){
rightSide.add(list.get(i));
}
}
if (leftSide.size()>1){
result = this.partition(leftSide);
leftSide=result;
}
if (rightSide.size()>1){
result = this.partition(rightSide);
rightSide=result;
}
List<Integer> combined = new ArrayList<>();
combined.addAll(leftSide);
combined.add(pivot);
combined.addAll(rightSide);
//print out
for (int j:combined){
System.out.print(j+" ");
}
System.out.println();
return combined;
}
public static void main(String[] a){
quickSorter qs = new quickSorter();
List<Integer> list = new ArrayList<>();
System.out.println();
Scanner in = new Scanner(System.in);
int n = in.nextInt();
for(int i=0;i<n;i++){
list.add(in.nextInt());
}
System.out.println();
List<Integer> sorted = qs.partition(list);
}
}

Categories