I'm trying to implement a method that uses multiple String[] arrays to print a wordlist which contains every possible combination of the Strings in the arrays, in order and using max. 1 String of each array.
example: {"this" | "that"} {"is" | "was"} {"cool" | "lame"}
String[] array1 = {"this", "that"};
String[] array2 = {"is", "was"};
String[] array3 = {"cool", "lame"};
should be used for the following output:
thisiscool
thatiscool
thiswascool
thatwascool
thiswaslame
thatwaslame
thisislame
thatislame
I've been experimenting with nested for-loops:
String out1 = "";
for(int a = 0; a < array1.length; a++) {
out1 = array1[a];
System.out.println(out1);
for(int b = 0; b < array2.length; b++) {
out1 += array2[b];
System.out.println(out1);
for(int c = 0; c < array3.length; c++) {
out1 += array3[c];
System.out.println(out1);
This didn't work well though. Maybe there's a better approach to this?
String[] array1 = {"this", "that"};
String[] array2 = {"is", "was"};
String[] array3 = {"cool", "lame"};
String text="";
for(int a = 0; a < array1.length; a++) {
text=array1[a];
for(int b = 0; b < array2.length; b++) {
text+=array2[b];
for(int c = 0; c < array3.length; c++){
System.out.println(text+array3[c]);
}
text=array1[a];
}
}
Demonstration of same logic in JS
Run the following snippet
let array1 = ["this", "that"];
let array2 = ["is", "was"];
let array3 = ["cool", "lame"];
let text="";
for(let a = 0; a < array1.length; a++) {
text=array1[a];
for(let b = 0; b < array2.length; b++) {
text+=array2[b];
for(let c = 0; c < array3.length; c++){
console.log(text+array3[c]);
}
text=array1[a]
}
}
.as-console-wrapper { max-height: 100% !important; top: 0; }
#Supercool. has already left a perfect answer.
But as your opinion, I've been trying to figure out if there's a better way to visualize than nested for-loops, and I've come up with a way to "recursive call"
By using a 'double array' and 'recursive',
although you add a new array, you don't have to write an additional for-loop.
Like this
public class StackOver
{
static String[][] array = {{"this","that"},
{"is","was"},
{"cool","lame"},};
public static void recString(String[][] a, int index, String output) {
//make break-point
if(index == a.length) { //if 'index' reached to the end of array 'a'?
System.out.println(output); //print out string 'output' that collected so far
//output should be = (a[0][?] + a[1][?] +...+ a[length-1][?])
return; //And end the method.
}
// if 'index' didn't reach to the end of array ::
//If there's an array that hasn't been explored yet,
for(int i = 0; i < a[index].length; i++) {
recString(a, index+1, output + a[index][i]);
//Add 1 to 'index' and add String out put that added '[index][i]'
//as parameters and call this method again.
//This form is called recursive call!
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String t = "";
recString(array,0,t);
}
}
Even if the array changes, with recursive calls,
you can examine every array without changing the code and draw possible combinations.
Ex).
static String[][] array = {{"I","You","They"},
{"love","hate"},
{"me","you"},
{"too","either"},};
Well, the grammar is a little awkward, but it's an example of stretching the arrangement a little bit longer.
Related
I am coding a program to output common elements of an array. I've got it working, but not to the standard it should be. Currently I have a function getCommonElements that prints each string index of where the string arrays have a commonality, but I have to return an empty string. I want to only return that string (array3) as a list of all the common elements. Thank you.
--The commented out part is the part that I have working, but want to replace. Currently this runs and gives an out of bounds error and I understand why, just want to change that.--
public class GetCommonElement {
public static String[] getCommonElements(String[] array1, String[] array2){
String[] array3 = {""};
for(int i =0; i < array1.length; i++){
for(int j = 0; j < array2.length; j++){
if (array1[i] == array2[j]){
/*System.out.print(array1[i]);
System.out.printf("\n");*/
String temp = array1[i];
for(int k = 0; k < array2.length; k++){
array3[k] = temp;
}
}
}
}
return array3;
}
TLDR: How do I compare two arrays and output the common elements into the new array.
First of all, you should't be using the == operator to compare objects like String. String objects are cached for short ones, but in general there may be String objects that have the same content but doesn't have the same memory address, so == will give you a false. You should be using the String.equals(Object o) method, or the null safe java.util.Objects.equals(Object o1, Object o2).
In addition, you don't know how many items match in the two arrays, so you don't know the length of your array3 result before the execution of the method. I recomend you to use a Set, or if you want, a List object for the result.
The code of the method might be something like the following:
public static String[] getCommonElements(String[] array1, String[] array2) {
List<String> coincidences = new ArrayList<>(
Math.min(array1.length, array2.length)
);
for (int i = 0; i < array1.length; i++) {
for (int j = 0; j < array2.length; j++) {
if (Objects.equals(array1[i], array2[j])
&& !coincidences.contains(array1[i])) {
coincidences.add(array1[i]);
}
}
}
return coincidences.stream().toArray(String[]::new);
}
You can see here how to append an array. so you could start with an empty array String[] array3 = {}; and instead of array3[k] = temp; you would do something like
array3 = Arrays.copyOf(array3, array3.length + 1);
array3[array3.length - 1] =temp;
Alternatively you could count the matches then initialize an array of appropriate size. One problem I see with your code is that it will do strange things if multiples exist in each array. For example if the string "blah" existed twice in each array it would match 4 times. So for this reason I would probably do something like this which checks for redundancy:
public class matching{
public static String[] getCommonElements(String[] array1, String[] array2){
boolean[] matches = new boolean[array1.length];
boolean hasAMatch = false;
boolean isRedundant = false;
int nMatches = 0;
for(int i =0; i < array1.length; i++){
isRedundant = false;
for(int i2=0;i2<i;i2++){
if(array1[i]==array1[i2]){
isRedundant = true;
break;
}
}
if(!isRedundant){
hasAMatch = false;
for(int j=0; j < array2.length; j++){
if (array1[i] == array2[j]){
hasAMatch = true;
nMatches++;
break;
}
}
if(hasAMatch){
matches[i] = true;
}
}
}
String[] array3 = new String[nMatches];
nMatches = 0;
for(int i =0; i < array1.length; i++){
if(matches[i]){
array3[nMatches] = array1[i];
nMatches ++;
}
}
return(array3);
}
public static void main(String []args){
String[] a = {"blah","blah","didy","blah blah"};
String[] b = {"blah","ditty","blagh blah"};
String[] c = getCommonElements(a,b);
for(int i =0; i < c.length; i++){
System.out.println(c[i]);
}
}
}
I am attempting to solve a semi-difficult problem in which I am attempting to create an array and return a 3 dimensional array based on the parameter which happens to be a 2 dimensional int array. The array I'm attempting to return is a String array of 3 dimensions. So here is the code:
public class Displaydata {
static String[][][] makeArray(int[][] dimensions) {
String myArray[][][];
for (int i = 0; i < dimensions.length; i++) {
for (int j = 0; j < dimensions[i].length; j++) {
myArray[][][] = new String[i][j][]; //getting error here.
}
}
return myArray;
}
static void printArray(String[][][] a) {
for (int i = 0; i < a.length; i++) {
System.out.println("\nrow_" + i);
for (int j = 0; j < a[i].length; j++) {
System.out.print( "\t");
for (int k = 0; k < a[i][j].length; k++)
System.out.print(a[i][j][k] + " ");
System.out.println();
}
}
}
public static void main(String[] args) {
int [][] dim = new int[5][];
dim[0] = new int[2];
dim[1] = new int[4];
dim[2] = new int[1];
dim[3] = new int[7];
dim[4] = new int[13];
dim[0][0] = 4;
dim[0][1] = 8;
dim[1][0] = 5;
dim[1][1] = 6;
dim[1][2] = 2;
dim[1][3] = 7;
dim[2][0] = 11;
for (int i = 0; i < dim[3].length;i++)
dim[3][i] = 2*i+1;
for (int i = 0; i < dim[4].length;i++)
dim[4][i] = 26- 2*i;
String[][][] threeDee = makeArray(dim);
printArray(threeDee);
}
}
As you can see from the source code, I'm getting an error when I try to create an instance of my 3-dimensional array which I'm attempting to return. I'm supposed to create a three dimensional array with the number of top-level rows determined by the length of dimensions and, for each top-level row i, the number of second-level rows is determined by the length of dimensions[i]. The number of columns in second-level row j of top-level row i is determined by the value of dimensions[i][j]. The value of each array element is the concatenation of its top-level row index with its second-level row index with its column index, where indices are represented by letters : ‘A’ for 0, ‘B’ for 1 etc. (Of course, this will only be true if the indices don’t exceed 25.) I don't necessarily know where I'm going wrong. Thanks!
You should not be initializing the array on every iteration of the loop. Initialize it once outside the loop and then populate it inside the loop.
static String[][][] makeArray(int[][] dimensions) {
String[][][] myArray = new String[25][25][1];
for (int i = 0; i < dimensions.length; i++) {
for (int j = 0; j < dimensions[i].length; j++) {
myArray[i][j][0] = i + "," + j;
}
}
return myArray;
}
I just plugged in values for the size of the first two dimensions, you will need to calculate them based on what you put in there. The 'i' value will always be dimensions.length but the 'j' value will be the largest value returned from dimensions[0].length -> dimensions[n-1].length where 'n' is the number of elements in the second dimension.
Also you will need to set up a way to convert the numbers in 'i' and 'j' to letters, maybe use a Map.
I guess you should initialize the array as
myArray = new String[i][j][]; //getting error here.
I think
myArray[][][] = new String[i][j][]; //getting error here.
should be:
myArray[i][j] = new String[5]; // I have no idea how big you want to go.
And then you can fill in each element of you inner-most array like such:
myArray[i][j][0] = "first item";
myArray[i][j][1] = "second string";
...
I think you should just change that line to:
myArray = new String[i][j][]; //look ma! no compiler error
Also, you would need to initialize myArray to something sensible (perhaps null?)
I have this array.
char [] cornStrand = {'G','G','A','G','T','T','C','C','C','A'};
I also have this array, for which the values are inputted by the user running the program.
char [] bacteriaStrand = new char [5];
String strBases = scan.nextLine();
for (int s=0; s <bacteriaStrand.length; s++)
{
char c = strBases.charAt(s);
bacteriaStrand[s]= c ;
}
The second block of code essentially inputs the values that the user entered into the bacteria strand array.
Now comes the tricky part. I need to "splice" and combine both arrays. By this I mean:
If the first character of
char [] bacteriaStrand
is A, then I have to insert
char [] bacteriaStrand
After the first G in
char [] cornStrand
Now, after I splice this, I have to put what I spliced into a new array, called
char [] combinedStrand
This is where I am becoming confused. If anyone can help, please do so! I would gladly appreciate it!
Maybe do something like this:
public char[] combine(char[] bacteriaStrand, char[] cornStrand) {
char[] result = new char[bacteriaStrand.length + cornStrand.length];
if (bacteriaStrand[0] == 'A') {
for (int i = 0; i < cornStrand.length; i++) {
boolean insertedBacteria = false;
if (cornStrand[i] == 'G') {
insertedBacteria = true;
for (int j = 0; j < bacteriaStrand.length; j++) {
result[i + 1 + j] = bacteriaStrand[j];
}
if (insertedBacteria)
i += bacteriaStrand.length;
result[i] = cornStrand[i];
}
}
}
return result;
}
If that is the only rule, it seems pretty simple to do.
if (bacteriaStrand[0] == 'A') {
int totalLength = cornStrand.length + bacteriaStrand.length;
char [] combinedStrand = new char [totalLength];
for(int i=0; i<cornStrand.length; i++){
combinedStrand[i] = cornStrand[i]; //fill in corn until you find the first G
if (cornStrand[i] == 'G') {
int j = 0;
for(; j<bacteriaStrand.length; j++){
combinedStrand[i+j+1] = bacteriaStrand[j]; //fill in bacteria
}
i++;
for(;i<cornStrand.length;i++){
combinedStrand[i+j+1] = cornStrand[i] //fill in the rest of corn
}
}
}//now this loop will break, since you increased i, so you won't get duplicates
}
I am writing a really simple program which automatically extends the array when the user reaches the limit of the current array.
The problem is that I am getting a java.lang.ArrayIndexOutOfBoundsException when I run my PrintList method and I really don't know why. It's working perfectly if I use a random number, which is bigger than the array (e.g. 500), but if I use
for (int i = 0; i < stringArray.length; i++)
or
for (int i = 0; i <= stringArray.length; i++)
I get a nasty exception. How do I deal with this and why am I getting it in the first place?
Thanks a lot for your help!
Here's the source code of my program:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int index = 0;
String[] randomString = new String[1];
while (index <= randomString.length) {
out.println("Enter your string");
String input = keyboard.next();
randomString[index] = input;
PrintArray(randomString);
index++;
if (index >= randomString.length) {
ExtendArray(randomString);
continue;
}
}
}
public static void ExtendArray(String[] stringArray) {
String[] secondArray = new String[stringArray.length * 2];
// Copy first array into second array
for (int i = 0; i < stringArray.length; i++) {
stringArray[i] = secondArray[i];
stringArray = secondArray;
}
}
public static void PrintArray(String[] stringArray) {
for (int i = 0; i < stringArray.length; i++) {
out.println(" " + stringArray[i]);
}
}
Java does not work in the methods you are trying to employ. Everything in Java is passed by value, unless it is a data point in an object. What you are trying to employ is a pass by reference, which is not possible in Java.
What you are trying to do is an already existing data structure called a Vector: http://docs.oracle.com/javase/7/docs/api/java/util/Vector.html
I would suggest doing this: (not sure if it will work properly, as my current PC doesn't have dev tools):
public static String[] ExtendArray(String[] stringArray) {
String[] secondArray = new String[stringArray.length * 2];
// Copy first array into second array
for (int i = 0; i < stringArray.length; i++) {
secondArray[i] = stringArray[i];
}
return secondArray;
}
then calling it like so in main:
randomString = ExtendArray(randomString);
Relating to vectors, this is how it works in a Vector class:
public void incrementCount(int count){
int increment = (count * 2);
Object newElementData [] = new Object[increment];
for(int i = 0; i < count; i++)
{
newElementData[i] = elementData[i];
}
elementData = new Object[increment];
elementData = newElementData;
}
In this case, elementData is the original array, newElementData is a temp array that acts to up the bounds.
You cant get error on your PrintArray method, you get the error on the line before!
randomString[index] = input;
Because if you do this
index <= randomString.length
The last iteration is out of bounds, String of length 10 has values on 0-9. You have to change the while cycle to
index < randomString.length
Also your ExtendArray method is NOT functional!
You are supposed to swap out the randomString array for a new array with double length. You create a new array and copy the contents of the old one to the new one, but don't do anything with the new array.
I suppose you want the ExtendArray method to return the new array, and set the randomString variable to be the new array.
You need to return your second array from ExtendArray function:
public static String[] ExtendArray(String[] stringArray) {
String[] secondArray = new String[stringArray.length * 2];
// Copy first array into second array
for (int i = 0; i <= stringArray.length; i++) {
stringArray[i] = secondArray[i];
}
return secondArray;
}
and in your main:
randomString = ExtendArray(randomString);
also your while condition should be:
while (index < randomString.length)
I want to compare two arrays and store the difference in another array
For example the two arrays might be
String[] a1 = { "cat" , "dog" };
String[] a2 = { "cat" , "rabbit" };
The resultant array would be like this
{ "rabbit" }
I use this code, but it does not work
int n = 0;
for (int k = 0; k <= temp.length; k++)
{
for (int u = 0; u <= origenal.length; u++)
{
if (temp[k] != origenal[u] && origenal[u] != temp[k])
{
temp2[n] = temp[k];
System.out.println(temp[u]);
n++;
}
}
}
This should do the trick.
String[] result = new String[100];
Int k = 0;
Boolean test = true;
for(i=0; i < a1.length; i++){
for(j=0; j < a2.length; j++){
if(a2[i].equals(a1[i])) continue;
test = false
}
if(test == false) result[k++] = a1[i];
}
I think that this may be what you are looking for. Note that it will only add to the third 'array' if the value exist in second array but not in first. In your example only rabbit will be stored, not dog (even though dog does not exist in both). This example could possibly be shortened but I wanted to keep it like this so it is easier to see what is going on.
First import:
import java.util.ArrayList;
import java.util.List;
Then do the following to populate and analyze the arrays
String a1[] = new String[]{"cat" , "dog"}; // Initialize array1
String a2[] = new String[]{"cat" , "rabbit"}; // Initialize array2
List<String> tempList = new ArrayList<String>();
for(int i = 0; i < a2.length; i++)
{
boolean foundString = false; // To be able to track if the string was found in both arrays
for(int j = 0; j < a1.length; j++)
{
if(a1[j].equals(a2[i]))
{
foundString = true;
break; // If it exist in both arrays there is no need to look further
}
}
if(!foundString) // If the same is not found in both..
tempList.add(a2[i]); // .. add to temporary list
}
tempList will now contain 'rabbit' as according to the specification. If you necessary need it to be a third array you can convert it to that quite simply by doing the following:
String a3[] = tempList.toArray(new String[0]); // a3 will now contain rabbit
To print the content of either the List or Array do:
// Print the content of List tempList
for(int i = 0; i < tempList.size(); i++)
{
System.out.println(tempList.get(i));
}
// Print the content of Array a3
for(int i = 0; i < a3.length; i++)
{
System.out.println(a3[i]);
}