Taking string and putting it into an array Java - java

I am making a java program that will Use “brute force” by generating all possible permutations and checking if any are matching. Example: If G1 = “0-1 0-2 1-2 1-3 2-3” and G2 = “1-3 2-0 0-3 1-2 1-0” then the permutation 0123 → 2310 does not match, but 0123 → 2013 does match.
I need to make a graph class the represents the graph as a 2-D boolean array and has member functions to check if 2 vertices are an edge and to print a graph. The constructor should use the above string representing a list of edges.
I need to know how I would take the string in that format and put it in an array.
Overall, I want to find out if the two graphs are isomorphic.
The code below is the permutation generator.
// Generator of all permutations of: 0,1,2,...,n-1
public class PermutationGenerator
{
// private data
private int[] perm;
private boolean first;
// constructor
public PermutationGenerator (int n)
{
perm = new int [n];
first = true;
}
public int[] next ()
{
int n = perm.length;
// starting permutation: 0 1 2 3 ... n-1
if (first)
{
first = false;
for (int i = 0 ; i < n ; i++)
perm [i] = i;
return perm;
}
// construct the next permutation
// find largest k so that perm[k] < perm[k+1]; if none, finish
int i, j, k, l;
for (k = n - 2 ; k >= 0 && perm [k] >= perm [k + 1] ; k--)
;
if (k < 0)
return null; // no more
// find largest l so that perm[k] < perm[l]
for (l = n - 1 ; l >= 0 && perm [k] >= perm [l] ; l--)
;
// swap perm[k] and perm[l]
swap (perm, k, l);
// reverse perm[k+1]...perm[n-1]
for (i = k + 1, j = n - 1 ; i < j ; i++, j--)
swap (perm, i, j);
return perm;
}
// swap a[i] and a[j]
private static void swap (int a[], int i, int j)
{
int temp = a [i];
a [i] = a [j];
a [j] = temp;
}
}

I think there is an easier way to determine if the two graphs (represented by strings g1 and g2) are the same - how about:
new HashSet<String>(Arrays.asList(g1.split(" "))).equals(
new HashSet<String>(Arrays.asList(g2.split(" ")))
(Let me know if I'm missing something)
If you still wanted to parse the string and use it to fill a boolean adjacency matrix you could do this:
Split adjacency-list string on spaces to form an array, call it arr.
Loop over arr, split each element on "-" to form a new array, call it x (one such array will be produced for each element of arr, since you're looping over it).
Set matrix[i][j] to true, where i and j are the first and second elements of x (respectively) parsed as integers.

Split the string on the space using String.split() to get an array of strings {0-1,0-2,1-2,1-3,2-3}.
Loop through these and split on the - to pull each number which you can then put into an array. Not very efficient but simple way to parse your example string.

Related

Permutations of a set of data in Java

I have 10,000 items in a set whereby each must be made into triads.
I need an algorithm to efficiently find each triad.
For example:
{A,B,C,D,...}
1.AAA
2.AAB
3.AAC
4.AAD
...
all the way to ZZY, ZZZ.
The method I'm using is very inefficient, I created a nested forloop of 3 which iterates through an array, which has a run-time of O(N^3) and terrible on performance obvious. Which kind of algo and data structure would be better for this? Thank you
Function to print all permutations of K length from a set of n characters with
repetition of characters:
static void printKLengthPerm(char[] set, String prefix, int n, int k)
{
if (k == 0)
{
System.out.println(prefix);
return;
}
for (int i = 0; i < n; i++)
{
String newPrefix = prefix + set[i];
printKLengthPerm(set, newPrefix, n, k - 1);
}
}
Calling the function to print all permutations of 3 length from a set all capital english alphabets:
char[] set = new char[26];
for(int i = 0; i < 26; i++)
set[i] = (char)(i+65);
int n = set.length;
printKLengthPerm(set, "", n, 3);

I need help sorting an array in java based on frequency in this one particular way

need help taking an an array, counting frequency, putting in another array with array index acting at the number and individual value acting as the frequency in Java
You can sort a large array of m integers that are in the range 1 to n by using an array count of n
entries to count the number of occurrences of each integer in the array. For example, consider
the following array A of 14 integers that are in the range from 1 to 9 (note that in this case m =
14 and n = 9):
9 2 4 8 9 4 3 2 8 1 2 7 2 5
Form an array count of 9 elements such that count[i-1] contains the number of times that i
occurs in the array to be sorted. Thus, count is
1 4 1 2 1 0 1 2 2
In particular,
count[0] = 1 since 1 occurs once in A.
count[1] = 4 since 2 occurs 4 times in A.
count[2]=1 since 3 occurs once in A.
count[3] =2 since 4 occurs 2 times in A.
Use the count array to sort the original array A. Implement this sorting algorithm in the function
public static void countingSort(int[] a, int n )
and analyze its worst case running time in terms of m (the length of array a) and n.
After calling countingSort(), a must be a sorted array (do not store sorting result in a
temporary array).
edit:
this is what i've tried
public static void countingSort1(int[] a, int n) {
int [] temp = new int[n];
int [] temp2 = new int[n];
int visited = -1;
for (int index = 0; index < n; index++) {
int count = 1;
for (int j = index +1; j < n; j++) {
if(a[index] == a[j]) {
count++;
temp[j] = visited;
}
}
if (temp[index]!= visited) {
temp[index] = count;
}
}
for(int i = 1; i < temp.length; i++) {
if (temp[i] != visited) {
System.out.println(" " +a[i] + " | " +temp[i]);
}
}
Just to count the frequency but i think im doing it wrong
Something like below should do the work:
Since you already know what the highest value is, in yor example 9,
create a frequency array with space for nine elements.
iterate over your input array and for each value you find increase
the value at the index of the value in your frequency arra by one
create a counter for the index and initialize it with 0
iterate over your frequency array in a nested loop and replace the
values in your input array with the indexes of your frequency array.
I leave the analysis of the complexity to you
public static void countingSort(int[] a, int n ){
//counting
int[] freq = new int[n];
for(int i = 0; i<a.length; i++){
freq[a[i]-1]++;
}
//sorting
int index = 0;
for(int i = 0; i< freq.length; i++){
for(int j = 0;j < freq[i];j++){
a[index++]= i+1;
}
}
System.out.println(Arrays.toString(a));
}

Changing 2D ArrayList code to 2D array code

I found this code online and it works well to permute through the given array and return all possible combinations of the numbers given. Does anyone know how to change this code to incorporate a 2D array instead?
public static ArrayList<ArrayList<Integer>> permute(int[] numbers) {
ArrayList<ArrayList<Integer>> permutations = new ArrayList<ArrayList<Integer>>();
permutations.add(new ArrayList<Integer>());
for ( int i = 0; i < numbers.length; i++ ) {
ArrayList<ArrayList<Integer>> current = new ArrayList<ArrayList<Integer>>();
for ( ArrayList<Integer> p : permutations ) {
for ( int j = 0, n = p.size() + 1; j < n; j++ ) {
ArrayList<Integer> temp = new ArrayList<Integer>(p);
temp.add(j, numbers[i]);
current.add(temp);
}
}
permutations = new ArrayList<ArrayList<Integer>>(current);
}
return permutations;
}
This is what I have attempted:
public static int[][] permute(int[] numbers){
int[][] permutations = new int[24][4];
permutations[0] = new int[4];
for ( int i = 0; i < numbers.length; i++ ) {
int[][] current = new int[24][4];
for ( int[] permutation : permutations ) {
for ( int j = 0; j < permutation.length; j++ ) {
permutation[j] = numbers[i];
int[] temp = new int[4];
current[i] = temp;
}
}
permutations = current;
}
return permutations;
}
However this returns all zeroes. I chose 24 and 4 because that is the size of the 2D array that I need.
Thanks
It’s not really that easy. The original code exploits the more dynamic behaviour of ArrayList, so a bit of hand coding will be necessary. There are many correct thoughts in your code. I tried to write an explanation of the issues I saw, but it became too long, so I decided to modify your code instead.
The original temp.add(j, numbers[i]); is the hardest part to do with arrays since it invloves pushing the elements to the right of position j one position to the right. In my version I create a temp array just once in the middle loop and shuffle one element at a time in the innermost loop.
public static int[][] permute(int[] numbers) {
// Follow the original here and create an array of just 1 array of length 0
int[][] permutations = new int[1][0];
for (int i = 0; i < numbers.length; i++) {
// insert numbers[i] into each possible position in each array already in permutations.
// create array with enough room: when before we had permutations.length arrays, we will now need:
int[][] current = new int[(permutations[0].length + 1) * permutations.length][];
int count = 0; // number of new permutations in current
for (int[] permutation : permutations) {
// insert numbers[i] into each of the permutation.length + 1 possible positions of permutation.
// to avoid too much shuffling, create a temp array
// and use it for all new permutations made from permutation.
int[] temp = Arrays.copyOf(permutation, permutation.length + 1);
for (int j = permutation.length; j > 0; j--) {
temp[j] = numbers[i];
// remember to make a copy of the temp array
current[count] = temp.clone();
count++;
// move element to make room for numbers[i] at next position to the left
temp[j] = temp[j - 1];
}
temp[0] = numbers[i];
current[count] = temp.clone();
count++;
}
assert count == current.length : "" + count + " != " + current.length;
permutations = current;
}
return permutations;
}
My trick with the temp array means I don’t get the permutations in the same order as in the origianl code. If this is a requirement, you may copy permutation into temp starting at index 1 and shuffle the opposite way in the loop. System.arraycopy() may do the initial copying.
The problem here is that you really need to implement properly the array version of the ArrayList.add(int,value) command. Which is to say you do an System.arraycopy() and push all the values after j, down one and then insert the value at j. You currently set the value. But, that overwrites the value of permutation[j], which should actually have been moved to permutations[j+1] already.
So where you do:
permutation[j] = numbers[i];
It should be:
System.arraycopy(permutation,j, permutations, j+1, permutations.length -j);
permutation[j] = numbers[i];
As the ArrayList.add(int,value) does that. You basically wrongly implemented it as .set().
Though personally I would scrap the code and go with something to dynamically make those values on the fly. A few more values and you're talking something prohibitive with regard to memory. It isn't hard to find the nth index of a permutation. Even without allocating any memory at all. (though you need a copy of the array if you're going to fiddle with such things without incurring oddities).
public static int[] permute(int[] values, long index) {
int[] returnvalues = Arrays.copyOf(values,values.length);
if (permutation(returnvalues, index)) return returnvalues;
else return null;
}
public static boolean permutation(int[] values, long index) {
return permutation(values, values.length, index);
}
private static boolean permutation(int[] values, int n, long index) {
if ((index == 0) || (n == 0)) return (index == 0);
int v = n-(int)(index % n);
int temp = values[n];
values[n] = values[v];
values[v] = temp;
return permutation(values,n-1,index/n);
}

Split an array into 4 portions

I have to create a method that divides the array of integers taken as input into an array that is made in this way:
The first portion is composed of the elements which, divided by 4, generate rest 0
The second portion is composed of the elements which, divided by 4, give rest 1
The third portion is composed of the elements which, divided by 4, give remainder 2
The fourth portion is composed of the elements, divided by 4, give rest 3
For example, the following array:
[0,2,4,5,6,8,7,9,10,12,14,15,17,20,1]
must become this here:
[0,4,8,12,20,5,9,17,1,2,6,10,14,7,15]
The result I get is:
[0,4,5,8,6,2,7,9,10,12,14,15,17,20,1]
Within subsequences no matter the order of items, just be in the subsequence correct.
I wrote this method but doen't work properly, some items are out of place.
public static void separate4Colors(int[] a) {
int i = 0;
int j = 0;
int k = 0;
int h = a.length - 1;
while(k <= h) {
if(a[k] % 4 == 0) {
swap(a, k, i);
k++;
i++;
j++;
}
else if(a[k] % 4 == 1) {
swap(a, k, i);
k++;
i++;
}
else if(a[k] % 4 == 2) {
k++;
}
else {
while(h > k && a[k] % 4 == 3)
h--;
swap(a, k, h);
h--;
}
}
}
private static void swap(int[] a, int x, int y) {
int temp = a[x];
a[x] = a[y];
a[y] = temp;
}
Can someone help me fix it?
A similar exercise that I've done and that work is to divide the array into 3 portions instead that 4:
public static void separate3Colors(int[] a) {
int j = 0;
int k = a.length - 1;
int i = 0;
while(j <= k) {
if(a[j] % 3 == 0) {
swap(a, j, i);
j++;
i++;
}
else if(a[j] % 3 == 1) {
j++;
}
else {
swap(a, j, k);
k--;
}
}
}
You can do it in a single line by sorting the array using a comparator that compares numbers modulo 4. Unfortunately, it requires an array of Integer objects.
Another approach would be writing the results into a different array. You can walk the array once to determine indexes at which the values with each remainder will start, and then walk the array again to make an ordered copy:
int[] index = new int[4];
for(int n : a) {
int r = n % 4;
if (r != 3) {
index[r+1]++;
}
}
index[2] += index[1];
index[3] += index[2];
// At this point each index[k] has the position where elements
// with remainder of k will start
int[] res = new int[a.length];
for(int n : a) {
res[index[n%4]++] = n;
}
This places the re-ordered array into the res variable.
Demo.
This exercice is obviously a variant of the famous Dutch National Flag Problem by the late E. Dijkstra https://en.wikipedia.org/wiki/Dutch_national_flag_problem
and the same resolution technique can be applied (with success, of course).
Consider that, at some point while running your algorithm, the arrays has five parts. One part contains numbers you know have with remainder 0, one part for remainders 1, etc. And one part for unclassified numbers. Each step of the algorithm consists of
looking at the first unclassified number
swapping some numbers at the borders so the number falls in the right part.
So the "unsorted" zone shrinks by one unit.
Sometimes a picture helps (go figure). I chose the have the unclassified elements between the 1's and the 2's.
000000000111111uuuuuuu22222333333333
?
If remainder of the number under test is 1, just leave it there. If it is zero, swap it with the first "1". etc.
At the beginning, of course, the situation is depicted as
uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
?

Transferring the contents of a one-dimensional array to a two-dimensional array

I'm trying to make an encryption program where the user enters a message and then converts the "letters into numbers".
For example the user enters a ABCD as his message. The converted number would be 1 2 3 4 and the numbers are stored into a one dimensional integer array. What I want to do is be able to put it into a 2x2 matrix with the use of two dimensional arrays.
Here's a snippet of my code:
int data[] = new int[] {10,20,30,40};
*for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
for (int ctr=0; ictr<data.length(); ictr++){
a[i][j] = data[ctr];}
}
}
I know there's something wrong with the code but I am really lost.
How do I output it as the following?
10 20
30 40
(instead of just 10,20,30,40)
Here's one way of doing it. It's not the only way. Basically, for each cell in the output, you calculate the corresponding index of the initial array, then do the assignment.
int data[] = new int[] {10, 20, 30, 40, 50, 60};
int width = 3;
int height = 2;
int[][] result = new int[height][width];
for(int i = 0; i < height; i++) {
for(int j = 0; j < width; j++) {
result[i][j] = data[i * width + j];
}
}
Seems like you want to output a 2xn matrix while still having the values stored in a one-dimensional array. If that's the case then you can to this:
Assume the cardinality m of your set of values is known. Then, since you want it to be 2 rows, you calculate n=ceil(m/2), which will be the column count for your 2xn matrix. Note that if m is odd then you will only have n-1 values in your second row.
Then, for your array data (one-dimension array) which stores the values, just do
for(i=0;i<2;i++) // For each row
{
for(j=0;j<n;j++) // For each column,
// where index is baseline+j in the original one-dim array
{
System.out.print(data[i*n+j]);
}
}
But make sure you check the very last value for an odd cardinality set. Also you may want to do Integer.toString() to print the values.
Your code is close but not quite right. Specifically, your innermost loop (the one with ctr) doesn't accomplish much: it really just repeatedly sets the current a[i][j] to every value in the 1-D array, ultimately ending up with the last value in the array in every cell. Your main problem is confusion around how to work ctr into those loops.
There are two general approaches for what you are trying to do here. The general assumption I am making is that you want to pack an array of length L into an M x N 2-D array, where M x N = L exactly.
The first approach is to iterate through the 2D array, pulling the appropriate value from the 1-D array. For example (I'm using M and N for sizes below):
for (int i = 0, ctr = 0; i < M; ++ i) {
for (int j = 0; j < N; ++ j, ++ ctr) {
a[i][j] = data[ctr];
}
} // The final value of ctr would be L, since L = M * N.
Here, we use i and j as the 2-D indices, and start ctr at 0 and just increment it as we go to step through the 1-D array. This approach has another variation, which is to calculate the source index explicitly rather than using an increment, for example:
for (int i = 0; i < M; ++ i) {
for (int j = 0; j < N; ++ j) {
int ctr = i * N + j;
a[i][j] = data[ctr];
}
}
The second approach is to instead iterate through the 1-D array, and calculate the destination position in the 2-D array. Modulo and integer division can help with that:
for (int ctr = 0; ctr < L; ++ ctr) {
int i = ctr / N;
int j = ctr % N;
a[i][j] = data[ctr];
}
All of these approaches work. Some may be more convenient than others depending on your situation. Note that the two explicitly calculated approaches can be more convenient if you have to do other transformations at the same time, e.g. the last approach above would make it very easy to, say, flip your 2-D matrix horizontally.
check this solution, it works for any length of data
public class ArrayTest
{
public static void main(String[] args)
{
int data[] = new int[] {10,20,30,40,50};
int length,limit1,limit2;
length=data.length;
if(length%2==0)
{
limit1=data.length/2;
limit2=2;
}
else
{
limit1=data.length/2+1;
limit2=2;
}
int data2[][] = new int[limit1][limit2];
int ctr=0;
//stores data in 2d array
for(int i=0;i<limit1;i++)
{
for(int j=0;j<limit2;j++)
{
if(ctr<length)
{
data2[i][j] = data[ctr];
ctr++;
}
else
{
break;
}
}
}
ctr=0;
//prints data from 2d array
for(int i=0;i<limit1;i++)
{
for(int j=0;j<limit2;j++)
{
if(ctr<length)
{
System.out.println(data2[i][j]);
ctr++;
}
else
{
break;
}
}
}
}
}

Categories

Resources