Generating Power Set of a String Recursively in Java - java

I'm trying to do recursive implementation of a Power Set generator working off of some pseudocode I was given, but when given a string like "abc", rather than having sets
{}, {a}, {b}, {c}, {a,b}, {a,c}, {b,c}, and {a,b,c},
I get {}, {0}, {1}, {2}, {0,1}, etc.
public static ArrayList GenerateSubsets(String setString) {
ArrayList A = new ArrayList<String>();
ArrayList temp = new ArrayList<String>();
if(setString.length() > 0) {
temp = GenerateSubsets(setString.substring(0,setString.length() - 1));
for(int i = 0; i < temp.size(); i++) {
System.out.println("Temp i: "+temp.get(i));
A.add(temp.get(i));
A.add(temp.get(i) + " " + (setString.length() - 1));
}
return A;
}
else
A.add("");
return A;
}
This is based directly on the pseudocode, why isn't it working correctly?
Edit: This is the test
public static void main(String[] args) {
ArrayList one = GenerateSubsets("abcd");
for(int i = 0; i < one.size(); i++) {
System.out.print(one.get(i)+ ", ");
if(i%5 == 0) {
System.out.println("");
}
}
}
And I get output of (without the line breaks)
,
3, 2, 2 3, 1, 1 3,
1 2, 1 2 3, 0, 0 3, 0 2,
0 2 3, 0 1, 0 1 3, 0 1 2, 0 1 2 3,

Statement (setString.length() - 1) gives you the index of char. And by concatenating it you receive a Power set of indexes. You need use setString.charAt(setString.length()-1) to receive char at given position.

Related

How to get output and get sum of columns in array / matrix?

hello to all you code geniuses on here
ill try to explain my problem as simply as i can
image1
To produce image1, lets say an array like below is required, keeping in mind that the numbers are placed left to right in the first row, then go backwards in the second row, and if you added more numbers, it would create a third row.
int[] something = {1, 2, 3, 2, 1, 2, 1, 3, 3, 1, 1, 2}
so i want to make to make a "map" of the layout, like this desired output below.
2 1 1 3 3 1
1 2 3 2 1 2
and then from there i would want to find the total for each column, so like this.
2 1 1 3 3 1
1 2 3 2 1 2
..................
3 3 4 5 4 3
(and i then want to make store this layout and sum within another array)
hopefully that all made sense, if so,
how could i go about doing this?
thanks heaps : )
Seems like you can use a two-dimensional array data structure to solve this:
int[][] something = new int[][]{
{2, 1, 1, 3, 3, 1},
{1, 2, 3, 2, 1, 2}
};
int totalForColomn1 = something[0][0] + something [1][0];
int totalForColomn2 = something[0][1] + something [1][1];
// ...
int totoalForColomn6 = something[0][5] + something [1][5];
If you could only use one-dimensional array:
int[] something = new int[] {2, 1, 1, 3, 3, 1, 4, 2, 3, 2, 1, 2};
int row_size = 6;
int totalForColomn1 = something[0] + something[0 + row_size];
int totalForColomn2 = something[1] + something[1 + row_size];
// ...
int totalForColomn6 = something[5] + something[5 + row_size];
Remember to keep a consistant row_size by putting those undecided element to 0.
In this case, you should init your array like:
int[] something = new int[] {0, 0, 0, 0, 1, 4, 1, 2, 3, 2, 1, 1};
So If I am reading this correctly if L is the length of your array you want to add the nth and L-1-nth element of the array and store the result in an array. I through this together quickly so I did not handle what happens if the input array is of odd length (your question did not specify).
import java.util.Arrays;
public class App {
public static void main(String[] args) {
int[] something = {1, 2, 3, 2, 1, 2, 1, 3, 3, 1, 1, 2};
System.out.println(Arrays.toString(addValues(something)));
}
public static int [] addValues(int [] input){
int[] output = new int[input.length / 2];
for(int i = 0; i<input.length/2; i++){
output[i] = input[i] + input[input.length -1 - i ];
}
return output;
}
}
EDIT:
I think this will work for the case where the are an arbitrary number of rows.
The main insite into how this work is in the grid below.
0 1 2 3 4 5 :row 0
11 10 9 8 7 6 :row 1
12 13 14 15 16 17:row 2
23 22 21 20 19 18:row 3
So whether the output index is going up or down is determined by the row number and every time we hit an input index that is the same size as our output array we need to stay at the same output index.
import java.util.Arrays;
public class App {
public static void main(String[] args) {
int[] something = { 1, 2, 3, 2, 1, 2, 1, 3, 3, 1, 1, 2 };
System.out.println(Arrays.toString(addValues(something, 6)));
}
public static int[] addValues(int[] input, int row_lenth) {
int[] output = new int[row_lenth];
int output_index = 0;
for (int i = 0; i < input.length; i++) {
if (i % row_lenth != 0) {
if ((i / row_lenth) % 2 == 0) {
output_index++;
} else {
output_index--;
}
}
output[output_index] += input[i];
}
return output;
}
}
import java.util.Scanner;
public class Stckoverq {
public static void main(String args[]) {
Scanner sn = new Scanner(System.in);
System.out.print("What is the size of array? ");
int size = sn.nextInt();
System.out.print("What is length of the row?");
int len = sn.nextInt();
int ind = 0, i = 0, j = 0;
//variable 'ind' is for getting the element from arr[] array at index ind
int rac[][] = new int[size/len][len];
//variable 'i' and 'j' is for storing rows and column elements respectively in array rac[]
int arr[] = new int[size];
System.out.println("Enter array elements: ");
for(int k=0;k<size;k++)
arr[k] = sn.nextInt();
while(ind!=arr.length)
{
if(j==len) {
j=0; //Reset column index
i++; //Increase row index
}
rac[i][j] = arr[ind];
ind++;
j++; //Increase column index
}
//Now print the rows and columns................
for(int r =0;r<size/len;r++) {
for(int c=0;c<len;c++)
System.out.print(rac[r][c]+"\t");
System.out.println();
}
int sum[] = new int[len];
//this array sum[] is used to store sum of all row elements.
int s = 0;
for(int c=0;c<len;c++) {
for(int r =0;r<size/len;r++)
s += rac[r][c];
sum[c] = s;
s = 0;
}
for(int x: sum)
System.out.print(x+"\t");
}
}

Insertionsort for Array with permutation (Java)

So I have this array which I have to sort with Insertionssort:
( 4 1 2 3 )= arr[0] ,
( 1 2 3 4 )=arr[1] ,
( 4 3 2 1 ) = arr[2],
( 3 1 2 4 )= arr[3] ,
( 4 3 1 2 ) = arr[4] ,
( 2 1 3 4 ) = arr[5] ,
( 4 1 3 2 ) = arr[6] ,
( 1 4 2 3 )= arr[7]
One array will be swapped with another if the difference between value 1 - 4 of array 1 and the difference between value 1-4 of array 2 is higher. For example: arr[0] < arr[1], because 1(4-3) < 3(4-1). If the difference is the same the values will be compared: for example: arr[5] & arr[6] have the same difference(2) but arr[6].value(1) > arr[5].value(1) --> swap.
so the sorted array will look like this:
(3,1,2,4) < (4,1,2,3) < (1,4,2,3) < (2,1,3,4) < (4,1,3,2) < (4,3,1,2) < (1,2,3,4) < (4,3,2,1)
I have this methode atm, where is just checked the first criteria:
public int insertionsort(permutation[] arr, int gap) {
int count = 0;
for (int i = gap; i<arr.length-1; i++) {
count++;
permutation new = arr[i];
int k = i;
System.out.println("K: " + k);
System.out.println("gap: "+ gap);
while(Math.abs(arr[i].value(1)-arr[i].value(4)) > Math.abs(arr[i-gap].value(1) -
arr[i-gap].value(4))) {
arr[k] = arr[k-gap];
k = k-gap;
System.out.println("k-gap: " + (k-gap));
}
arr[k] = new;
}
return count;
}
Now I thought my array would be sorted in the order of the small differences first but it doesnt seem right. I hope you can help me!
I'm not clear what the purpose of the gap argument is, hopefully you can incorporate it if needed, but here's a direct translation into Java of the standard Insertion Sort method.
static void sort(permutation[] perms)
{
for(int i=1; i<perms.length; i++)
{
permutation fixed = perms[i];
int j = i - 1;
while(j >= 0 && perms[j].compareTo(fixed) > 0)
{
perms[j+1] = perms[j];
j -= 1;
}
perms[j+1] = fixed;
}
}
With a guess at what the permutation class might look like:
static class permutation
{
int len;
int[] arr;
public permutation(int... vals)
{
len = vals.length;
arr = vals.clone();
}
int value(int pos)
{
return arr[pos-1];
}
public int compareTo(permutation p)
{
int cmp = Math.abs(value(1)-value(len)) - Math.abs(p.value(1)-p.value(len));
if(cmp == 0)
for(int i=1; cmp==0 && i<=len; i++)
cmp = value(i)-p.value(i);
return cmp;
}
}
Test:
permutation[] perms = {
new permutation(4,1,2,3),
new permutation(1,2,3,4),
new permutation(4,3,2,1),
new permutation(3,1,2,4),
new permutation(4,3,1,2),
new permutation(2,1,3,4),
new permutation(4,1,3,2),
new permutation(1,4,3,2)
};
sort(perms);
for(permutation p : perms)
System.out.println(Arrays.toString(p.arr));
Output:
[1, 4, 3, 2]
[3, 1, 2, 4]
[4, 1, 2, 3]
[2, 1, 3, 4]
[4, 1, 3, 2]
[4, 3, 1, 2]
[1, 2, 3, 4]
[4, 3, 2, 1]

Why does this array rotation program give 0 as output?

The program is supposed to shift all values in the array to the right. Please help with what I have done wrong...
int[] array = new int[] {1, 2, 3, 4, 5};
int[] rotated = new int [array.length];
int rotationTimes = scan.nextInt();
if (rotationTimes > 4){
rotationTimes %= 5;
}
for (int i = 0; i <= rotationTimes; i++){
if (i == 4) {
rotated[0] = array[4];
break;
}
array[i] = rotated[i + 1];
}
System.out.println(Arrays.toString(rotated));
The expected output should be {5, 1, 2, 3, 4}. It outputs an array of 0s...
Thank you a lot.
You weren't populating the rotated array. You were modifying the array reference!
You were checking if index == 4 when you could do array.length - 1.
You need to determine the target index as being (index + rotationTimes) then if it exceeds array.length - 1 (the last index) you use the modulus operator to make sure it doesnt overflow. For example, if the current index is 4 (the last one) and the iterations is 1, (4 + 1) is greater than 4 so the target index is (4 + 1) % 5 = 0.
public static void main(String[] args) {
int[] array = new int[] {1, 2, 3, 4, 5};
int[] rotated = new int [array.length];
System.out.println("Enter amount of times to rotate: ");
Scanner scan = new Scanner(System.in);
int rotationTimes = scan.nextInt();
if (rotationTimes > 4){
rotationTimes %= 5;
}
for (int index = 0; index < array.length; index++) {
int targetIndex = index + rotationTimes;
if (targetIndex > array.length - 1) {
targetIndex %= array.length;
}
rotated[targetIndex] = array[index];
}
System.out.println("Input: " + Arrays.toString(array));
System.out.println("Rotations: " + rotationTimes);
System.out.println("Output: " + Arrays.toString(rotated));
}
Input: [1, 2, 3, 4, 5]
Rotations: 1
Output: [5, 1, 2, 3, 4]
Input: [1, 2, 3, 4, 5]
Rotations: 2
Output: [4, 5, 1, 2, 3]

Java moving last array element into first

I need to move the java array last element into first .
int[] ar = { 1, 2, 3, 4, 5 };
input is like 1 2 3 4 5
output should be like 5 1 2 3 4
please provide the code
i have tried the below code
int temp ;
for(int i = 0; i<ar.length -1; i++){
temp = ar[i];
ar[i] = ar[i+1];
ar[i+1] = temp;
}
But it is giving output as 23451
You can use below code
public static void main(String[] args) {
int[] ar = { 1, 2, 3, 4, 5 };
int[] result = new int[ar.length];
System.arraycopy(ar, 0, result, 1, ar.length - 1);
result[0] = ar[ar.length - 1];
System.out.println(Arrays.toString(result));
}

Adding blank rows to a 2d array in Java

Say I have the following 2d array in Java set to a variable named myMap:
1 3 1
3 2 3
1 3 1
The next step in my program is to add rows and columns of zeros as follows:
1 0 3 0 1
0 0 0 0 0
3 0 2 0 3
0 0 0 0 0
1 0 3 0 1
Basically, I'm adding arrays of zero into the spaces between the previous rows/columns. I then fill them in with appropriate numbers (irrelevant to my question) and repeat the process (adding more rows/columns of zeros) a finite number of times.
My question is as follows- what is the easiest and most efficient way to do this in Java? I know I could create a new 2d array and copy everything over, but I feel like there may be a more efficient way to do this. My intuition says that a 2d ArrayList may be the better way to go.
Also, and this my be important, when my program begins, I DO know what the maximum size this 2d array. Also, I cannot expect the symmetry of the numbers that I put in for this example (these were just put in for a good visual reference).
Here's a solution with ArrayLists: (test included)
int[][] ar = new int[][]
{
{ 0, 1, 2 },
{ 3, 4, 5 },
{ 6, 7, 8 } };
ArrayList<ArrayList<Integer>> a = new ArrayList<>(ar.length);
ArrayList<Integer> blankLine = new ArrayList<>(ar.length * 2 - 1);
for (int i = 0; i < ar.length * 2 - 1; i++)
{
blankLine.add(0);
}
for (int i = 0; i < ar.length; i++)
{
ArrayList<Integer> line = new ArrayList<>();
for (int j = 0; j < ar[i].length; j++)
{
line.add(ar[i][j]);
if (j != ar[i].length - 1)
line.add(0);
}
a.add(line);
if (i != ar.length - 1)
a.add(blankLine);
}
for (ArrayList<Integer> b : a)
{
System.out.println(b);
}
Output:
[0, 0, 1, 0, 2]
[0, 0, 0, 0, 0]
[3, 0, 4, 0, 5]
[0, 0, 0, 0, 0]
[6, 0, 7, 0, 8]
Algorithm
int[][] appendRows(int[][] bag, int[]... rows) {
int[][] extendedBag = new int[bag.length + rows.length][];
int i = 0;
for (int[] row : bag) { fillRow(extendedBag, row, i++); }
for (int[] row : rows) { fillRow(extendedBag, row, i++); }
return extendedBag;
}
// WHERE #fillRow(int[][], int[], int) =
void fillRow(int[][] bag, int[] row, int i) {
bag[i] = new int[row.length];
System.arraycopy(row, 0, bag[i++], 0, row.length);
}
Demo
import java.util.Arrays;
/** Utilities for 2D arrays. */
public class Array2dUtils {
public static void main(String[] args) {
int[][] bag = new int[][] {
{ 0 },
{ 1, 1 },
{ 2, 2, 2 }
};
int[] row1 = new int[] { 3, 3};
int[] row2 = new int[] { 4 };
int[][] biggerBag = appendRows(bag, row1, row2);
System.out.println("Bag:\n" + toString(bag));
System.out.println("Bigger Bag:\n" + toString(biggerBag));
}
/** Append one or more rows to a 2D array of integers. */
public static int[][] appendRows(int[][] bag, int[]... rows) {
int[][] extendedBag = new int[bag.length + rows.length][];
int i = 0;
for (int[] row : bag) { fillRow(extendedBag, row, i++); }
for (int[] row : rows) { fillRow(extendedBag, row, i++); }
return extendedBag;
}
/* fill i-th item of the bag */
private static void fillRow(int[][] bag, int[] row, int i) {
bag[i] = new int[row.length];
System.arraycopy(row, 0, bag[i++], 0, row.length);
}
/** Pretty-prints a 2D array of integers. */
public static String toString(int[][] bag) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < bag.length; ++i) {
sb.append(Arrays.toString(bag[i])).append("\n");
}
return sb.toString();
}
}
$ javac Array2dUtils.java
$ java -cp "." Array2dUtils
Bag:
[0]
[1, 1]
[2, 2, 2]
Bigger Bag:
[0]
[1, 1]
[2, 2, 2]
[3, 3]
[4]

Categories