How can I convert these nested loops into recursive form? - java

I'm having trouble with trying to generate all possible combinations of a n*n grid. The code below shows how I would go about it using nested loops and a 2*2 grid. However, if I wanted to do the same thing for, say a 6*6 grid, it would be too annoying to make such an extensive list of loops.
Can anyone help me convert the bruteSolve() method into a recursive method so that I can choose how big the grid is?
Thanks in advance :) This has been a problem I've been stuck on for ages :(
static ArrayList<Integer> numbers;
static int n;
static int [] [] grid;
static int count;
public static void main (String [] args){
n = 2;
grid = new int [n] [n] ;
bruteSolve(n);
}
public static void bruteSolve(int n){
for (int i=1; i<n+1; i++){
grid [0][0] = i;
for (int j=1; j<n+1; j++){
grid [0][1] = j;
for (int k=1; k<n+1; k++){
grid [1][0] = k;
for (int l=1; l<n+1; l++){
grid [1][1] = l;
System.out.println(Arrays.deepToString(grid));
}
}
}
}
}

public static void main (String [] args){
int[][] arr = new int[2][2];
int from = 1, to = 2; // counter range
doit(0, arr, from, to);
// or
doit2(0, 0, arr, from, to);
}
// single iterator - process the data as unidimensional array, computing real indexes
public static void doit(int index, int[][] arr, int from, int to) {
if(arr == null || arr.length == 0 || arr[0] == null || arr[0].length == 0) {
System.err.println("Matrix inconsistent");
return;
}
if(index >= arr.length * arr[0].length) {
System.out.println(Arrays.deepToString(arr));
} else {
int x = index % arr[0].length;
int y = index / arr[0].length;
for(int n = from;n <= to;n++) {
arr[y][x] = n;
doit(index+1, arr, from, to);
}
}
}
// less complex but more comparisons
public static void doit2(int x, int y, int[][] arr, int from, int to) {
if(arr == null || arr.length == 0 || arr[0] == null || arr[0].length == 0) {
System.err.println("Matrix inconsistent");
return;
}
if(y >= arr.length) {
System.out.println(Arrays.deepToString(arr));
} else if(x >= arr[0].length) {
doit2(0, y+1, arr, from, to);
} else {
for(int n = from;n <= to;n++) {
arr[y][x] = n;
doit2(x + 1, y, arr, from, to);
}
}
}

Related

Error in the recursive method for quick sorting

The results of sorting before and after are identical.
Perhaps the error lies in the recursion.
is it possible to shorten the writing of a recursive case for quick sorting?
Where is the error?
(The recursive case takes up an insanely large amount of space, I understand that optimization and code purity are terrible)
love everyone)
import java.util.Random;
import java.util.Arrays;
public class Main {
//array creation
public static void main(String[] args) {
Random rand = new Random();
int[] numbers = new int[100];
//filling an array with random values
for (int i = 0; i < numbers.length;i++) {
numbers[i] = rand.nextInt(100);
}
//the array display method before sorting
System.out.println("Before:");
String num = Arrays.toString(numbers);
System.out.print(num);
//calling
quicksort(numbers, 0, numbers.length - 1);
//the sorting result
System.out.println("\nAfter:");
System.out.print(num);
}
//quicksort
private static void quicksort(int[] numbers, int lowIndex, int highIndex) {
if(lowIndex >= highIndex) {
return;
}
int pivot = numbers[highIndex];
int leftPointer = lowIndex;
int rightPointer = highIndex;
while(leftPointer < rightPointer) {
while ( numbers[leftPointer] <= pivot && leftPointer < rightPointer) {
leftPointer++;
}
while(numbers[rightPointer] >= pivot && leftPointer < rightPointer) {
rightPointer--;
}
swap(numbers, leftPointer, rightPointer);
}
swap(numbers, leftPointer, highIndex);
quicksort(numbers, lowIndex, leftPointer - 1);
quicksort(numbers,leftPointer + 1, highIndex);
}
//replacing the reference element
private static void swap(int[] numbers, int index1, int index2) {
int temp = numbers[index1];
numbers[index1] = numbers[index2];
numbers[index2] = temp;
}
}

Java: Implementing Merge Sort

I want to implement Merge Sort using one a mergeSort method that splits the sequences of an int array up until it's a single element and using a method merge to put them together.
With my code as it is I get a Stackoverflow Error.
Anyone has an idea why?
public static int[] mergeSort(int[] seq) {
return mergeSort(seq, 0, seq.length - 1);
}
private static int[] mergeSort(int[] seq, int l, int r) {
if (seq.length < 2) {
return seq;
}
int s = (l + r) / 2;
int[] a = new int[s];
int[] b = new int[seq.length - s];
for (int i : a) {
a[i] = seq[i];
}
for (int j : b) {
b[j] = seq[s + j];
}
mergeSort(a);
mergeSort(b);
return merge(a, b);
}
public static int[] merge(int[] ls, int[] rs) {
// Store the result in this array
int[] result = new int[ls.length + rs.length];
int i, l, r;
i = l = r = 0;
while (i < result.length) {
if (l < ls.length && r < rs.length) {
if (ls[l] < rs[r]) {
result[i] = ls[l];
++i;
++l;
} else {
result[i] = rs[r];
++i;
++r;
}
} else if (l >= ls.length) {
while (r < rs.length) {
result[i] = rs[r];
++i;
++r;
}
} else if (r >= rs.length) {
while (l < ls.length) {
result[i] = ls[l];
++i;
++l;
}
}
}
return result;
}
The stack overflow is caused by calling the method recursively too many times, possibly infinitely.
private static int[] mergeSort(int[] seq, int l, int r) this will always be called with l=0 and r=seq.length-1, so it's not really necessary to overload.
Here: int s = (l + r) / 2; if the array has 2 elements, this will return 0 (l=0, r=1), so the array will be split to a length 0, and a length 2 (and here is what causes the infinite recursive calls). Add one to the result, and the splitting of the array will work correctly.
To copy the parts of the original array, it's easier to use Arrays.copyOfRange() than writing your own for loop. And you're trying to use the existing elements of arrays a and b, which will all be 0, for indexing.
There are two small issues with your code.
First one is here:
public static int[] mergeSort(int[] seq) {
return mergeSort(seq, 0, seq.length - 1);
}
You need to call it as return mergeSort(seq, 0, seq.length);
The reason behind that is that for example when you have 2 elements and you call it like that with -1 you pass an array with 2 elements but s=1+0/2 =0 and you don't actually split it. Each subsequent recursion call is done with one empty array and one array with the same 2 elements causing an infinite loop and a stackoverflow exception
The second problem is this one:
for (int i : a) { and for (int i : b) {
You can't do the for loop like because you want to iterate on indexes not values of the array. You need to change it to:
for (int i=0;i<a.length;i++) {
a[i] = seq[i];
}
for (int i=0;i<b.length;i++) {
b[i] = seq[s + i];
}
And the last problem with your code is that you don't assign the values of the resulting sorted array and when you do the recursive calls it returns the sorted sub part but you don't get the result. It should become:
a=mergeSort(a);
b=mergeSort(b);
And here is the final code:
public static void main(String... args) {
int[] array={3,9,4,5,1} ;
array=mergeSort(array);
for(int i:array) {
System.out.print(i+",");
}
}
private static int[] mergeSort(int[] seq) {
if (seq.length < 2) {
return seq;
}
int s = seq.length / 2; //You always use that value. no need for 2 methods
int[] a = new int[s];
int[] b = new int[seq.length - s];
for (int i=0;i<a.length;i++) {
a[i] = seq[i];
}
for (int i=0;i<b.length;i++) {
b[i] = seq[s + i];
}
a=mergeSort(a);
b=mergeSort(b);
return merge(a, b);
}
public static int[] merge(int[] ls, int[] rs) {
// Store the result in this array
int[] result = new int[ls.length + rs.length];
int i, l, r;
i = l = r = 0;
while (i < result.length) {
if (l < ls.length && r < rs.length) {
if (ls[l] < rs[r]) {
result[i] = ls[l];
++i;
++l;
} else {
result[i] = rs[r];
++i;
++r;
}
} else if (l >= ls.length) {
while (r < rs.length) {
result[i] = rs[r];
++i;
++r;
}
} else if (r >= rs.length) {
while (l < ls.length) {
result[i] = ls[l];
++i;
++l;
}
}
}
return result;
}

move all even numbers on the first half and odd numbers to the second half in an integer array

I had an interview question which i could not solve.
Write method (not a program) in Java Programming Language that will move all even numbers on the first half and odd numbers to the second half in an integer array.
E.g. Input = {3,8,12,5,9,21,6,10}; Output = {12,8,6,10,3,5,9,21}.
The method should take integer array as parameter and move items in the same array (do not create another array). The numbers may be in different order than original array. This is algorithm test, so try to give as efficient algorithm as you can (possibly linear O(n) algorithm). Avoid using built in functions/API. *
Also some basic intro to what is data structure efficiency
Keep two indices: one to the first odd number and one to the last even number. Swap such numbers and update indices.
(With a lot of help from #manu-fatto's suggestion) I believe this would do it:
private static int[] OddSort(int[] items)
{
int oddPos, nextEvenPos;
for (nextEvenPos = 0;
nextEvenPos < items.Length && items[nextEvenPos] % 2 == 0;
nextEvenPos++) { }
// nextEvenPos is now positioned at the first odd number in the array,
// i.e. it is the next place an even number will be placed
// We already know that items[nextEvenPos] is odd (from the condition of the
// first loop), so we'll start looking for even numbers at nextEvenPos + 1
for (oddPos = nextEvenPos + 1; oddPos < items.Length; oddPos++)
{
// If we find an even number
if (items[oddPos] % 2 == 0)
{
// Swap the values
int temp = items[nextEvenPos];
items[nextEvenPos] = items[oddPos];
items[oddPos] = temp;
// And increment the location for the next even number
nextEvenPos++;
}
}
return items;
}
This algorithm traverses the list exactly 1 time (inspects each element exactly once), so the efficiency is O(n).
// to do this in one for loop
public static void evenodd(int[] integer) {
int i = 0, temp = 0;
int j = integer.length - 1;
while (j >= i) {
// swap if found odd even combo at i and j
if (integer[i] % 2 != 0 && integer[j] % 2 == 0) {
temp = integer[i];
integer[i] = integer[j];
integer[j] = temp;
i++;
j--;
} else {
if (integer[i] % 2 == 0) {
i++;
}
if (integer[j] % 2 == 1) {
j--;
}
}
}
}
#JLRishe,
Your algorithm doesn't maintain the order. For a simple example, say {1,5,2}, you will change the array to {2,5,1}. I could not comment below your post as I am a new user and lack reputations.
public static void sorted(int [] integer) {
int i, j , temp;
for (i = 0; i < integer.length; i++) {
if (integer[i] % 2 == 0) {
for (j = i; j < integer.length; j++) {
if (integer[j] % 2 == 1) {
temp = y[i];
y[i] = y[j];
y[j] = temp;
}
}
}
System.out.println(integer[i]);
}
public static void main(String args[]) {
sorted(new int[]{1, 2,7, 9, 4});
}
}
The answer is 1, 7, 9, 2, 4.
Could it be that you were asked to implement a very basic version of the BubbleSort where the sort value of element e, where e = arr[i], = e%2==1 ? 1 : -1 ?
Regards
Leon
class Demo
{
public void sortArray(int[] a)
{
int len=a.length;
int j=len-1;
for(int i=0;i<len/2+1;i++)
{
if(a[i]%2!=0)
{
while(a[j]%2!=0 && j>(len/2)-1)
j--;
if(j<=(len/2)-1)
break;
a[i]=a[i]+a[j];
a[j]=a[i]-a[j];
a[i]=a[i]-a[j];
}
}
for(int i=0;i<len;i++)
System.out.println(a[i]);
}
public static void main(String s[])
{
int a[]=new int[10];
System.out.println("Enter 10 numbers");
java.util.Scanner sc=new java.util.Scanner(System.in);
for(int i=0;i<10;i++)
{
a[i]=sc.nextInt();
}
new Demo().sortArray(a);
}
}
private static void rearrange(int[] a) {
int i,j,temp;
for(i = 0, j = a.length - 1; i < j ;i++,j--) {
while(a[i]%2 == 0 && i != a.length - 1) {
i++;
}
while(a[j]%2 == 1 && j != 0) {
j--;
}
if(i>j)
break;
else {
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
public void sortEvenOddIntegerArray(int[] intArray){
boolean loopRequired = false;
do{
loopRequired = false;
for(int i = 0;i<intArray.length-1;i++){
if(intArray[i] % 2 != 0 && intArray[i+1] % 2 == 0){
int temp = intArray[i];
intArray[i] = intArray[i+1];
intArray[i+1] = temp;
loopRequired = true;
}
}
}while(loopRequired);
}
You can do this with a single loop by moving odd items to the end of the array when you find them.
static void EvensToLeft(int[] items) {
int end = items.length;
for (int i = 0; i < end; i++) {
if (items[i] % 2) {
int t = items[i];
items[i--] = items[--end];
items[end] = t;
}
}
}
Given an input array of length n the inner loop executes exactly n times, and computes the parity of each array element exactly once.
Use two counters i=0 and j=a.length-1 and keep swapping even and odd elements that are in the wrong place.
public int[] evenOddSort(int[] a) {
int i = 0;
int j = a.length - 1;
int temp;
while (i < j) {
if (a[i] % 2 == 0) {
i++;
} else if (a[j] % 2 != 0) {
j--;
} else {
temp = a[i];
a[i] = a[j];
a[j] = temp;
i++;
j--;
}
}
return a;
}
public class SeperatOddAndEvenInList {
public static int[] seperatOddAndEvnNos(int[] listOfNumbers) {
int oddNumPointer = 0;
int evenNumPointer = listOfNumbers.length - 1;
while(oddNumPointer <= evenNumPointer) {
if(listOfNumbers[oddNumPointer] % 2 == 0) { //even number, swap to front of last known even number
int temp;
temp = listOfNumbers[oddNumPointer];
listOfNumbers[oddNumPointer] = listOfNumbers[evenNumPointer];
listOfNumbers[evenNumPointer] = temp;
evenNumPointer--;
}
else { //odd number, go ahead... capture next element
oddNumPointer++;
}
}
return listOfNumbers;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int []arr = {3, 8, 12, 5, 9, 21, 6, 10};
int[] seperatedArray = seperatOddAndEvnNos(arr);
for (int i : seperatedArray) {
System.out.println(i);
}
}
}
public class ArraysSortEvensFirst {
public static void main(String[] args) {
int[] arr = generateTestData();
System.out.println(Arrays.toString(arr));
ArraysSortEvensFirst test = new ArraysSortEvensFirst();
test.sortEvensFirst(arr);
}
private static int[] generateTestData() {
int[] arr = {1,3,5,6,9,2,4,5,7};
return arr;
}
public int[] sortEvensFirst(int[] arr) {
int end = arr.length;
int last = arr.length-1;
for(int i=0; i < arr.length; i++) {
// find odd elements, then move to even slots
if(arr[i]%2 > 0) {
int k = findEven(last, arr);
if(k > i) swap(arr, i, k);
last = k;
}
}
System.out.println(Arrays.toString(arr));
return arr;
}
public int findEven(int last, int[] arr) {
for(int k = last; k > 0; k--) {
if(arr[k]%2 == 0) {
return k;
}
}
return -1; // not found;
}
public void swap(int[] arr, int x, int y) {
int temp = arr[x];
arr[x] = arr[y];
arr[y] = temp;
}
}
Output:
[1, 3, 5, 6, 9, 2, 4, 5, 7]
[4, 2, 6, 5, 9, 3, 1, 5, 7]
efficiency is O(log n).
public class TestProg {
public static void main(String[] args) {
int[] input = { 32, 54, 35, 18, 23, 17, 2 };
int front = 0;
int mid = input.length - 1;
for (int start = 0; start < input.length; start++) {
//if current element is odd
if (start < mid && input[start] % 2 == 1) {
//swapping element is also odd?
if (input[mid] % 2 == 1) {
mid--;
start--;
}
//swapping element is not odd then swap
else {
int tmp = input[mid];
input[mid] = input[start];
input[start] = tmp;
mid--;
}
}
}
for (int x : input)
System.out.print(x + " ");
}
}

Combinations of integers

I'd appreciate any help on the following problem. I have n integers from 0 to n-1, and I'm trying to generate a list of all possible combinations of length k (i.e. k concatenated integers) such that every pair of consecutive integers are not equal. So, for example, (1)(2)(3)(2) would be valid with k = 4, but (1)(2)(3)(3) would not be valid. Any ideas on how to approach this most efficiently? (I don't care much about length/degree of complexity of the code, just efficiency)
It is the code:
void Generate(int[] source, List<int[]> result, int[] build, int k, int num) {
if (num == k) {
int[] a = (int[])build.clone();
result.add(a);
return;
}
for (int i = 0; i < source.length; i++)
if (num == 0 || source[i] != build[num - 1])
{
build[num] = source[i];
Generate(source, result, build, k, num + 1);
}
}
How to call:
int k = 2;
List<int[]> a = new ArrayList<int[]>();
Generate(new int[]{1,2,3}, a, new int[k], k, 0);
public class Generator {
final int k = 2;
final char[] n = new char[]{'0','1','2','3','4','5','6','7','8','9'};
final char[] text = new char[k];
public void gen(int i, int not_n) {
if(i == k) {
System.out.println(text);
return;
}
for(int j = 0; j < n.length; j++) {
if(j == not_n) continue;
text[i] = n[j];
gen(i+1, j);
}
}
public static void main(String[] args) {
new Generator().gen(0, -1);
}
}
public static void recursiveOutput(Integer n, int k, int limit, String prints){
k++;
if(k>limit)
return;
String statePrints = prints;
//cycle through all available numbers
for(Integer i = 1; i<=n; i++)
{
statePrints = prints;
//First cycle
if(k==1){
statePrints+= "(" + i.toString() + ")";
recursiveOutput(n, k, limit, statePrints);
}
//check if predecessor is not the same
if(i != Integer.parseInt(statePrints.substring(statePrints.length()-2,statePrints.length()-1))){
statePrints += "(" + i.toString() + ")";
recursiveOutput(n, k, limit, statePrints);
}
}
//Check if the length matches the combination length
if(statePrints.length() == 3 * limit)
System.out.println(statePrints);
}
call :recursiveOutput(3,0,4,"");

Implementing merge sort in java

Here's my implementation of Merge Sort in java
import java.io.*;
import java.util.Arrays;
public class MergeSort
{
private static int [] LeftSubArray(int [] Array)
{
int [] leftHalf = Arrays.copyOfRange(Array, 0, Array.length / 2);
return leftHalf;
}
private static int [] RightSubArray(int [] Array)
{
int [] rightHalf = Arrays.copyOfRange(Array, Array.length / 2 + 1, Array.length);
return rightHalf;
}
private static int [] Sort(int [] A)
{
if(A.length > 1)
{
return Merge( Sort( LeftSubArray(A) ) , Sort( RightSubArray(A) ) );
}
else
{
return A;
}
}
private static int [] Merge(int [] B, int [] C)
{
int [] D = new int[B.length + C.length];
int i,j,k;
i = j = k = 0;
while(k < D.length)
{
if(i == B.length)
{
//Copy the remainder of C into D
while(k < D.length){ D[k++] = C[j++]; }
}
if(j == C.length)
{
//Copy the remainder of B into D
while(k < D.length){ D[k++] = B[i++]; }
}
if(i<B.length && j<C.length)
{
if(B[i] > C[j]){ D[k++] = B[i++]; }
else { D[k++] = C[j++]; }
}
}
return D;
}
public static void main(String [] args)
{
int [] array = {1,3,5,2,4};
int [] sorted = MergeSort.Sort(array);
for(int i = 0;i < sorted.length; ++i)
{
System.out.print(sorted[i] + " ");
}
}
}
The output I get is
2 1
From what I can tell there seems a problem with my division of the right sub array.
What am I doing wrong?
Here is the javadoc of copyOfRange:
Parameters:
original - the array from which a range is to be copied
from - the initial index of the range to be copied, **inclusive**
to - the final index of the range to be copied, **exclusive**. (This index may lie outside the array.)
I highlighted two words you should pay special attention to ;-)
If your array has 10 elements, then LeftSubArray copies elements 0..5, and RightSubArray copies elements 6..10. But if the first element is at index 0, then there is no element w/ an index 10. And if copyOfRange(a,b) gives elements indexed a..b-1, then LeftSA is yielding 0..4 and RightSA is yielding 6..9. Either way, your assumption about division seems to be accurate.
With your code [1,3,5,2,4] is split into [1,3] and [2,4]. Good luck
This piece of code works: you had couple of errors:
see next diffs:
rightSubArray method
copy the remainder of B
copy the remainder of C
The code that works follows:
public class MergeSort
{
private static int [] LeftSubArray(int [] Array)
{
int [] leftHalf = Arrays.copyOfRange(Array, 0, Array.length / 2);
return leftHalf;
}
private static int [] RightSubArray(int [] Array)
{
int[] rightHalf = Arrays.copyOfRange(Array, Array.length / 2,
Array.length);
return rightHalf;
}
private static int [] Sort(int [] A)
{
if(A.length > 1)
{
return Merge( Sort( LeftSubArray(A) ) , Sort( RightSubArray(A) ) );
}
else
{
return A;
}
}
private static int [] Merge(int [] B, int [] C)
{
int [] D = new int[B.length + C.length];
int i,j,k;
i = j = k = 0;
while(k < D.length)
{
if(i == B.length)
{
//Copy the remainder of C into D
while (j < C.length) {
D[k++] = C[j++];
}
}
if(j == C.length)
{
//Copy the remainder of B into D
while (i < B.length) {
D[k++] = B[i++];
}
}
if (i < B.length && j < C.length)
{
if (B[i] > C[j]) {
D[k++] = B[i++];
} else {
D[k++] = C[j++];
}
}
}
return D;
}
public static void main(String [] args)
{
int [] array = {1,3,5,2,4};
int [] sorted = MergeSort.Sort(array);
for(int i = 0;i < sorted.length; ++i)
{
System.out.print(sorted[i] + " ");
}
}
}
I found a rigth solution in Robert Sedgewick book "Algorithms on java language"
Read here about merge

Categories