I need some help in JAVA:
I have a function signature which I can't change, and my function needs to be recursive and to return String array without any option to add it to the signature.
This is the signature I've got:
public String[] findSimilar(String w, int index, int k)
The function looks for similar words in a TRIE structure, with a difference of K letters changes between them.
For example- in a TRIE withe the words hello, nice, nine, cry, for the word "bike" and k=2, the function will return a String[] with nice and nine.
I'm not looking for a solution, just for a method to return string array.
** I wrote a function with the signature I've received as a wrapper, but I just found out that I can't use wrapper.
Thank you!
The trivial example:
public String[] findSimilar(String w, int index, int k) {
return new String[] {"string1","string2"}
}
Maybe more useful:
public String[] findSimilar(String w, int index, int k) {
List<String> similar = new ArrayList<>();
// insert some implementation here
return similar.toArray(new String[similar.size()]);
}
I'm not looking for a solution, just for a method to return string array.
To return a string array with literals string1 and string2 you could just use an array initializer such as return new String[] { "string1", "string2"};
Else, you could just create the String array and assign values to its positions if you know beforehand how many elements you will be returning:
String[] arr = new String[2];
arr[0] = "string1";
arr[1] = "string2";
return arr;
If it's the return type of a recursive function, you'll probably need to use the result from the recursive call to build your own result in the current call. Taking into account arrays cannot be extended, you'll need to create a new one with the expected size, and copy the values of the result into it for instance with System.arraycopy.
Use something like this.
I would not like to provide full code just an idea
public String[] findSimilar(String w, int index, int k) {
String[] res1=findSimilar(conditions one);
String[] res2=findSimilar(conditions two);
String[] res=new String[res1.length+res2.length];
//use public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
System.arraycopy(copyFrom, ..., copyTo, ..., ...);
}
Related
New to Java coding, please bear with me.
I'm trying to pass my ArrayList chosenWords held in my method getChosenWords(int length) to my method getRandom(int length). I need the ArrayList so I can chose a random index and return a random string.
Note, it's not declared in the Class fields and I am not able to change the parameters of my methods. I have to find another way to pass the ArrayList in but I'm unsure how to. The unit test uses these set parameters and I can't change parameters or the fields as other classes rely on them staying the same.
I'm pretty sure this is the line that needs changing ArrayList<String> chosenWords;
and currently I have an error variable not initialised on this line. random.nextInt(chosenWords.size());
Any suggestions?
Method1
// Takes strings in ArrayList words and stores strings with char int length to ArrayList chosenWords
public ArrayList<String> getChosenWords(int length) {
ArrayList<String> chosenWords = new ArrayList<>();
for(String word1 : words) {
if(word1.length() == length) {
chosenWords.add(word1);
}
}
return chosenWords;
}
Method2
//Returns a randomly selected string from ArrayList chosenWords
public String getRandom(int length) {
ArrayList<String> chosenWords;
Random random = new Random();
int randomIndex = random.nextInt(chosenWords.size());
return chosenWords.get(randomIndex);
}
The obvious solution, if the OP hasn't used it yet?
public String getRandom(int length) {
ArrayList<String> chosenWords = getChosenWords(length);
Random random = new Random();
int randomIndex = random.nextInt(chosenWords.size());
return chosenWords.get(randomIndex);
}
That way chosenWords will be initialized.
Instead of receiving length as a parameter in the getRandom() function, take an ArrayList. Pass the arraylist chosenWords to the getRandom() function and return the value received from the getRandom() function.
Hope that helps.
I've got a generic array class and I want to return an array in the main so I can use the sort method that I have ready in the main. I understand that the constructor has an array in it so I'm wondering if I can use that. Or do I need to set up a new method to return this.array ? Also it returns a generic array, how do I choose the type in main?
public class dynamicArray <T>{
private int index;
private T[] array;
public dynamicArray() {
array = (T[])new Object[10];
this.index = 0;
}
public T [] populate() {
return this.array;
}
Here I chose the integer type for the class. I'm not sure how can I extract the
array from the constructor.
public static void main(String[] args) {
dynamicArray<Integer>array = new<Integer>dynamicArray();
array.add(10);
array.add(5);
array.add(6);
array.add(11);
array.add(13);
array.add(20);
int [] arr = array.populate();
mergeSort(arr);
System.out.println(array.toString());
}
Unfortunately, arrays and generics don't work well together. Take a look at the source code of java's ArrayList - it is implemented with an Object[] and not a T[] - then every method will cast to T (which costs literally zero, it's just ugly and causes compiler warnings). I advise you do the same here: Arrays actually KNOW their component type (unlike a list of Ts, which does not, there is no method on a java.util.List that you can invoke to get the component type), and therefore casting Object[] to T[] is just wrong; java allows this solely for backwards compatibility reasons.
Basically, you can't work with T[] without things being subtly wrong and a lot of compiler errors.
In this specific case? I would strenuously advise you to use a private List<T> array; field instead of a T[] field.
Your call to array.populate() (that seems like a bizarre name for this method!) IS retrieving the array you created in the constructor. You are doing what you're asking for: "Extracting the array from the constructor" - invoking populate() on the object returned by the new dynamicArray<Integer>() is doing exactly that.
NB: You have a typo in your source code. it's new dynamicArray<Integer>();, not new<Integer>dynamicArray();. Perhaps that's causing some issues?
NB2: Java conventions dictate it's DynamicArray, and something like getBackingArray (instead of populate).
I think you ask two question :
How to set Integer type of that array object.
How to get Integer[] to int[]
Here is the code :
private int index;
private T[] array;
public dynamicArray() {
array = (T[])new Object[10];
this.index = 0;
}
public T [] populate() {
return this.array;
}
public void add(T x) {
array[++index] = x;
}
public static void main(String[] args) {
dynamicArray<Integer>array = new<Integer>dynamicArray();
array.add(10);
array.add(5);
array.add(6);
array.add(11);
array.add(13);
array.add(20);
int[] arr = Arrays.stream(array.populate())
.mapToInt(i -> i)
.toArray();
System.out.println(array.toString());
}
Answer for 1st question is you can not set Integer type because there wasn't any add method in your class. Answer for 2nd question is you try to convert Integer[] to int[] but there is no direct way to cast this. you just need to change Integer -> Object then Object -> int. This can be done easily using streams which is in Java 8 and i have used lambda here for showing power of lambda function.
Here is a possible alternative. Pass the type of array to the constructor. But essentially you are creating a limited form of ArrayList so you may just as well use that. Note that this still has the limitation that you can't use primitive arrays as the array type.
dynamicArray<Integer> array = new dynamicArray<>(new Integer[0]);
array.add(10);
array.add(5);
array.add(6);
array.add(11);
array.add(13);
array.add(20);
Integer[] a = array.getArray();
System.out.println(Arrays.toString(a));
}
class dynamicArray<T> {
private int size = 0;
private T[] array;
public dynamicArray(T[] a) {
array = a;
}
public void add(T value) {
if (array.length == size) {
array = Arrays.copyOf(array, size == 0 ? 10 : size*2);
}
array[size++] = value;
}
#SuppressWarnings("unchecked")
public T[] getArray() {
// need to copy the array since the length and size could be different.
T[] arrayCopy = (T[]) Array.newInstance(array.getClass().getComponentType(), size);
System.arraycopy(array, 0, arrayCopy, 0, size);
return arrayCopy;
}
}
I'm quite new to Java, and I'm not sure about is it possible to do something like below and how to do it with code.
String[] a = {"a", "b", "c", ...}; //unknown amount of elements
String[] b = new String[]{ //I want to put a's element in here assume I don't know what's the length of a };
Any idea of what I can put inside the braces after the constructor to initialize the string array b.
p.s. I'm not allowed to use string array a directly and must use constructor to declare string array b. I'm not allowed to use ArrayList.
Thanks!
The most concise way would be:
String[] b = Arrays.copyOf(a, a.length);
Use array copy to do the task.
Its prototype is:-
public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
String[] a = {"a", "b", "c", ...}; //unknown amount of elements
String []b=new String[a.length];
System.arraycopy(a,0,b,0,a.length);
So I know how to sort a Java array of ints or floats (or other data types). But what if it was a string array String[] arr = {} where the array contained elements like 2x^2, 4x^4. As you can see, there are several indices that have integers, which could be sorted.
The way I would think to sort this is to splice out the number at an index. Sort those numbers, then map each old index to the new index.
I feel like there is a better way.
The essential question: Does a sorting method exist that can sort a string array based on an integer at a certain index of each index?
If you are wondering, here would be some sample inputs and outputs of an algorithm as such.
Array: {"2x^3","2x^0","1x^1"}
Output:{"2x^3","1x^1","2x^0"} // Sorted based on last index
static final Comparator<String> myComparator =
new Comparator<String>() {
public int compare(String s1, String s2)
{
// split s1 and s2, compare what you need
// and return the result.
// e.g.
// char digit1 = s1[s1.length() - 1];
// char digit2 = s2[s2.length() - 1];
// return (int)(digit1 - digit2);
}
};
Collections.sort(list, myComparator);
// or
Arrays.sort(array, myComparator);
So you are letting someone else's sort method do the sorting for you, you just need to provide a method to say how to compare the items. There are some rules and regulations you need to stick to (e.g. if A < B, B < C then A must be < C).
You can also do it inline/anonymously:
Collections.sort(list, new Comparator<String>() {
public int compare(String s1, String s2) {
...
}
});
I am trying to add, remove and reference items from an array I create in my main java file, but I am having trouble figuring out the correct syntax. In actionscript they have push() and pop() for adding and removing items in an array, is there an equivalent in android?
In Java an array has a fixed size (after initialisation), meaning that you can't add or remove items from an array.
int[] i = new int[10];
The above snippet mean that the array of integers has a length of 10. It's not possible add an eleventh integer, without re-assign the reference to a new array, like the following:
int[] i = new int[11];
In Java the package java.util contains all kinds of data structures that can handle adding and removing items from array-like collections. The classic data structure Stack has methods for push and pop.
For those who don't have time to refactor the code to replace arrays with Collections (for example ArrayList), there is an alternative. Unlike Collections, the length of an array cannot be changed, but the array can be replaced, like this:
array = push(array, item);
The drawbacks are that
the whole array has to be copied each time you push, and
the original array Object is not changed, so you have to update the variable(s) as appropriate.
Here is the push method for String:
(You can create multiple push methods, one for String, one for int, etc)
private static String[] push(String[] array, String push) {
String[] longer = new String[array.length + 1];
for (int i = 0; i < array.length; i++)
longer[i] = array[i];
longer[array.length] = push;
return longer;
}
This alternative is more efficient, shorter & harder to read:
private static String[] push(String[] array, String push) {
String[] longer = new String[array.length + 1];
System.arraycopy(array, 0, longer, 0, array.length);
longer[array.length] = push;
return longer;
}
Use Array list
http://developer.android.com/reference/java/util/ArrayList.html
You can use Arrays.copyOf() with a little reflection to make a nice helper function.
public class ArrayHelper {
public static <T> T[] push(T[] arr, T item) {
T[] tmp = Arrays.copyOf(arr, arr.length + 1);
tmp[tmp.length - 1] = item;
return tmp;
}
public static <T> T[] pop(T[] arr) {
T[] tmp = Arrays.copyOf(arr, arr.length - 1);
return tmp;
}
}
Usage:
String[] items = new String[]{"a", "b", "c"};
items = ArrayHelper.push(items, "d");
items = ArrayHelper.push(items, "e");
items = ArrayHelper.pop(items);
Results
Original: a,b,c
Array after push calls: a,b,c,d,e
Array after pop call: a,b,c,d
You can use LinkedList. It has methods peek, poll and offer.