I want to create a Java method, which accepts an inputArray = Object[n][], where n can be any integer, and outputs a list of possible n-size combinations between all values of the n subarrays. Below is an example:
Input Array: (where Object=String and n=3)
String[] subarrayA = {"A0","A1","A2"};
String[] subarrayB = {"B0","B1"};
String[] subarrayC = {"C0","C1","C2","C3"};
String[3][] inputArray = {subarrayA, subarrayB, subarrayC};
Desired Output:
{A0,B0,C0},{A0,B0,C1},{A0,B0,C2},{A0,B0,C3},
{A0,B1,C0},{A0,B1,C1},{A0,B1,C2},{A0,B1,C3},
{A1,B0,C0},{A1,B0,C1},{A0,B0,C2},{A1,B0,C3},
{A1,B1,C0},{A1,B1,C1},{A1,B1,C2},{A1,B1,C3},
{A2,B0,C0},{A2,B0,C1},{A2,B0,C2},{A2,B0,C3},
{A2,B1,C0},{A2,B1,C1},{A2,B1,C2},{A2,B1,C3}
Obviously, I cannot have a fixed nested-loop inside my method since I do not know n in advance. So, I am guessing the only way to solve it would be through a recursive method? Any recommendations?
P.S: I am aware of the simple combination-related posts on the website.
This should solve your problem.
public static void permute(String array[][], int index, ArrayList<String> output){
if(index == array.length){
System.out.println(output.toString());
}
else{
for(int i=0 ; i<array[index].length ; i++){
output.add(array[index][i]);
permute(array,index+1,output);
output.remove(output.size() - 1);
}
}
}
Related
Im trying to figure out a way to override a specific array in this scenario.
Im iterating through a LinkedList and when I encounter the Element null I am supposed to add the index of the Element to an already defined array of ints.
public int [] indexes()
{
int [] result = new int [0];
int counter = 0;
Element current = first;
int k = 0;
for(int i = 0 ; i< size() ; i++)
{
if(current.getContent()==null)
{
counter++;
}
}
int [] temp = new int [counter];
current = first;
for(int i = 0 ; i< size() ; i++)
{
if(current.getContent()==null)
{
temp[k++] = i ;
}
}
result = temp;
return result;
As you can already see, I have an array with no elements in it and a length of 0.
Afterwards Im iterating through the List to check if and how many Elements are null. When I find one I increment the counter.
I set up a new temporary array with the length of the counter and the fill the temporary Element with the indexes.
1st Question : Does the line result = temp; work as intended? Does the array called result now contain the array of temp?
2nd Question : How can I check if an Element is null in a LinkedList without getting a NullpointerException? I tried using the following in my if conditions:
current == null
current.getContent() == null
current.equals(null)
current.getContent().equals(null)
All of those returned a counter of 0 which means it didnt increment the counter when encountering a Null-Element. How can I rewrite the if conditions?
Question 1: Yes. result and temp refer to the same data.
Question 2: your for loop is problematic:
for(int i = 0 ; i< size() ; i++)
{
if(current.getContent()==null)
{
temp[k++] = i ;
}
}
You're not changing current, so it's always pointed to the first element.
I'm not sure if you're using Java's LinkedList<> or implementing your own.
I wrote this little program. I think it demonstrates what you're trying to do:
import java.util.*;
public class Foo {
public static void main(String[] args) {
LinkedList<String> list = new LinkedList<String>();;
list.add("Hello");
list.add("There");
list.add(null);
for (String str: list) {
System.out.println(str != null ? str : "<null>");
}
ArrayList<Integer> indexes = new ArrayList<Integer>();
int index = 0;
for (String str: list) {
if (str == null) {
indexes.add(index);
}
++index;
}
for (Integer thisIndex: indexes) {
System.out.println(thisIndex);
}
}
}
At the end, you would need to convert from ArrayList into an int[]. But the output from this little guy is:
$ javac Foo.java && java Foo
Hello
There
<null>
2
I was able to override the result array with this line.
result = temp;
Also the way to check if an Element is null in the List was:
current.getContent() == null;
And last I actually forgot setting the current pointer to the next Element which actually was my biggest problem:
current = current.getSucc();
Thanks for everyone's help and time. I really appreciate it!
I am working on the following coding prompt for my class:
Your task is to write a method with the following signature:
public static String[] removeFromArray(String[] arr, String toRemove)
The method should return a string array that has the same contents as arr, except without any
occurrences of the toRemove string. For example, if your method is called by the code below
String[] test = {“this”, “is”, “the”, “example”, “of”, “the”, “call”};
String[] result = removeFromArray(test, “the”);
System.out.println(Arrays.toString(result));
it should generate the following output:
[this, is, example, of, call]
Note: Your method will be passed values for arr and toRemove by the testing program – you should not
read these values in from the user inside your method. Also, you must write this method with the
signature requested above in order to receive credit. You do not need to write the code that calls the
method – only the method itself.
Hint: Because you must specify the length of an array when you create it, you will likely need to make
two loops through the input array: one to count the number of occurrences of the toRemove string so
that you can create the new array with the proper size and a second to copy all of the other strings to the new array.
I have everything working in my code but the last part where I have to print out the new array does not work, I know I have make it smaller so it will print out properly, but I can't get that part to work. I know I have to get rid of the null, but I don't know how. Also my code has to work for any array not just the test case I have. Some help or advice would really be nice. Thank you very much!!! :)
Here is my code:
public static void main(String[] args) {
String[] test = {"this", "is", "the", "example", "of", "the", "call"};
String[] remove = removeFromArray(test, "the");
System.out.println(Arrays.toString(remove));
}
public static String[] removeFromArray(String[] arr, String toRemove) {
int count = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i].equals(toRemove)) {
count++;
}
}
String[] result = new String[arr.length - count];
//for (int i = 0; i < arr.length; i++) {
// if(!arr[i].equals(toRemove)){
// result[].equals(arr[i]);
//}
//}
return result;
}
you approach looks ok, it looks like the commented code yor are trying to assign the new array with the wrong emthod
you should use result[i] = arr[i] ; instead of result[].equals(arr[i]);
do at the end:
String[] result = new String[arr.length - count];
int k = 0;
for (int i = 0; i < arr.length; i++) {
if(!toRemove.equals(arr[i])){
result[k] = arr[i];
k++;
}
}
return result;
Your last part should be assigning the value to the array one by one.
int j = 0;
for (int i = 0; i < arr.length; i++) {
if(!toRemove.equals(arr[i])){
result[j++] = arr[i];
}
}
It's asking you to return a new String array which excludes the given word. Loop through the array and add word which does not equal to the given word.
public static String[] removeFromArray(String[] arr, String toRemove){
ArrayList<String> words = new ArrayList<>();
for(String s : arr)
if(!s.equals(toRemove))
words.add(s);
return words.toArray(new String[0]);
}
Since array size cannot be changed after being created, use an ArrayList to store the words, then return as an array.
I know you're new to programming itself, so the solutions given are perfectly fine.
However, using Java, you'd usually use the libraries; in this case, the Collections library. If you're using Java 8, this is how you would do it:
public static String[] removeFromArray(String[] arr, String toRemove) {
// create a List and fill it with your items
ArrayList<String> list = new ArrayList();
Collections.addAll(list, arr);
// remove the items that are equal to the one to be removed
list.removeIf(s -> toRemove.equals(s));
// transfer back to array
return list.toArray(new String[list.size()]);
}
Then, there are Java 8 Streams, which would make this
public static String[] removeFromArray(String[] arr, String toRemove) {
return Arrays.stream(arr) // create stream from array
.filter(s -> !toRemove.equals(s)) // filter out items
.toArray(String[]::new); // create array from stream
}
So I basically have an array that looks like this:
BG6001;1193;M;63;B+
BG6001;1124;M;41;C
BG6001;1121;F;FA;FA
BG6001;1143;M;26;FA
BG6001;1157;F;74;A
And what I've been trying to do is to count how many times the letter "M" appears in it, and add it into a counter
Any ideas?
What I have tried so far:
for (int i=0; i<name.length(); i++) {
if (name.charAt(i)=='M' ) counter++;
}
System.out.println("the string contains " + count + " times the letter M")
You should probably use a foreach loop. Try implementing something like this:
int counter=0;
String[][] array = something;
for(String[] subArray : array)
for(String string : subArray)
if(string.toLowerCase().equals("m"))
counter++;
//Counter has the value of the amount of 'm's in the array
#mike fischer please check the below code whoich gives you the count of "M" in an Array.
public class Arraycount {
public static void main(String args[]){
String[] a=new String[5];
a[0]="BG6001;1193;M;63;B+";
a[1]="BG6001;1124;M;41;C";
a[2]="BG6001;1121;F;FA;FA";
a[3]="BG6001;1143;M;26;FA";
a[4]="BG6001;1157;F;74;A";
int count=0;
for(int i=0;i<=a.length-1;i++){
for(int j=0;j<=a[i].length()-1;j++){
char c=a[i].charAt(j);
if(c=='M'){
count++;
}
}
}
System.out.println("Number of M present in an array is "+count);
}
}
My answer is very similar to 7H3_H4CK3R's answer with some variation. Specifically, if a particular letter (in this case, "M") could appear anywhere in the string, you can do the following (and I apologize for using C# rather than Java syntax here, I'm not sitting in front of a Java compiler, but hopefully the differences won't be too difficult to follow):
private static int Count(string[][] data, char letterToFind)
{
int count = 0;
// Loop over each array
foreach (string[] array in data)
{
// Each array is a collection of strings
foreach (string str in array)
{
// Loop through the characters in each string
for (int i = 0; i < str.Length; i++)
{
if (str[i] == letterToFind)
{
count++;
}
}
}
}
return count;
}
Alternatively, if you're looking for something where the entire string is "M" 7H3_H4CK3R's answer should do the trick.
I have this code below to count the frequency of a string in an ArrayList
public static int count (ArrayList<String> c, String str){
int num = 0;
num = Collections.frequency(c, str);
return num;
}
What I have to do now is to improve this so that the function takes in ArrayList<ArrayList<String>> and can loop through the set of Arraylists and Count the occurrences of the String. Any ideas would be great.
You need to use two nested for loops, looping through each list with the first one and looping through each element of the current list with the second, i.e.:
int count = 0;
for (ArrayList<String> list : lists) {
for (String string : list) {
if (list.equals("something")) count++;
}
}
To compute the frequency you'll also need to count the total number of elements in all the lists, but I'll leave that to you as it should be straightforward now.
Dude, you described the algorithm, it won't get simpler than that. Just code the thing.
Keep in mind that Collections::frequency is misnamed (IMHO), it should be count.
In java 8 use the stream
public void findOccurenceInLists(ArrayList<ArrayList<String>> lists, String myStr) throws Exception {
int occurence = 0;
lists.stream().forEach((list) -> {
occurence += list.stream().filter((str) -> str.equals(myStr)).count();
});
System.out.println(occurence + " occurence found");
}
I'm trying to create a program that takes user input and sorts it alphabetically as it comes in using compareTo String operations (not array.sort) and prints the final sorted array at the end. I've got most of the body of this problem down but am lost once I get to the sort function. Does anyone have any ideas on how I might be able to finish out the SortInsert method?
import java.util.*;
public class SortAsInserted {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int array_size = GetArraySize();
String[] myArray = new String[array_size];
for (int i = 0; i < array_size; i++){
String nextString = GetNextString();
String[] sortedArray = SortInsert(nextString, myArray);
}
PrintArray(sortedArray);
}
input.close();
}
}
public static String[] SortInsert(String nextString, String[] myArray){
for(int i = 0; i < myArray.length;)
if (nextString.compareToIgnoreCase(myArray[i]) > 0) {
i++;
//if current text is less(alphabetically) than position in Array
}else if (nextString.compareToIgnoreCase(myArray[i]) < 0){
}
}
public static int GetArraySize(){
Scanner input = new Scanner(System.in);
System.out.print("How many items are you entering?: ");
int items_in_array = input.nextInt();
return items_in_array;
}
public static void PrintArray(String[] x) {
for (int i = 0; i < x.length; i++){
System.out.print(x[i]);
}
}
public static String GetNextString(){
Scanner input = new Scanner(System.in);
System.out.println("Enter the next string: ");
String next_string = input.nextLine();
return next_string;
}
}
There are a number of problems with this code. First I'll answer your immediate question, then enumerate some of the other problems.
The SortInsert method takes a String[] that will have been initialized with null values, so you will need to take that into account. The for loop would look something like this. (I'm using comments instead of writing the actual code since I'm not doing the project)
for (int i=0; i<myArray.length; ++i) {
if (myArray[i] == null) {
// we found a blank spot. use it to hold nextString.
break;
} else if (nexString.compareToIgnoreCase(myArray[i]) < 0) {
// nextString should be in spot i, so make room for it
// by shuffling along whatever is in the array at "i" and later
// by one place, then put nextString into position "i"
break;
}
// otherwise we'll just move to the next position to check
}
Now for the other issues.
You have a Scanner object in main that is never used. There's no point in having it and closing it at the end if your other methods make their own.
myArray will always be the sorted array so there's no point in making a local variable called sortedArray and return it from SortInsert. Note that your attempt to print sortedArray would fail anyway because that local variable is only in scope within the for loop.
When printing it should be myArray being passed to PrintArray.
If you're going to sort as you go, the TreeMap data structure is what you should be using, not an array. However, if you want to sort as you go with an array, you need to add some lines into your else if clause in SortInsert (should be sortInsert, BTW). (Another question: why is it else if rather than just else?)
The lines should create a new array of size one greater than the existing array, copy the first i-1 elements of the old array to the new array, put the new element in position i, then copy the remaining elements of the old array into positions one greater in the new array.
Once you find the position you wish to insert at, you have to shift all of the following elements down by one. Something like the following:
String temp = array[position];
for (int j = position+1; j < array_size-1; j++) {
String temp2 = array[j];
array[j] = temp;
temp = temp2;
}
array[array_size-1] = temp;