I'm trying to return all possible permutations of values in a String array. I've come up with the following code making all possible permutations; it works fine.
private void combineArray(String sPrefix, String[] sInput, int iLength) {
if (iLength == sPrefix.length()) {
//This value should be returned and concatenated:
System.out.println(sPrefix);
} else {
for (int i=0; i<sInput.length; i++) {
combineArray(sPrefix.concat(sInput[i]), ArrayUtils.removeElement(sInput, sInput[i]), iLength);
}
}
}
If I put in {x, y ,z} it prints to the console:
xyz
xzy
yxz
yzx
zxy
zyx
My problem is that I can't find a way to return these values to the original calling function. So I'd like this function not to return 'void' but a 'String' containing the concatened values of sPrefix.
I've been struggling with this for a while now and I can't seem to see clearly anymore. :) Any help would be appreciated.
Rather than returning a list, I think it might work better to pass in a list as an argument, and populate it inside the method:
private void combineArray(List<String> lOut, String sPrefix, String[] sInput, int iLength) {
if (iLength == sPrefix.length()) {
//This value should be returned and concatenated:
System.out.println(sPrefix);
lOut.add(sPrefix);
} else {
for (int i=0; i<sInput.length; i++) {
combineArray(lOut, sPrefix.concat(sInput[i]), ArrayUtils.removeElement(sInput, sInput[i]), iLength);
}
}
}
You can then have a wrapper method that creates the new ArrayList<String>, passes it into the above method, and returns it.
You can have an ArrayList<String> and add all the strings to it.. And then you can return this ArrayList..
List<String> listString = new ArrayList<>();
private void combineArray(String sPrefix, String[] sInput, int iLength) {
if (iLength == sPrefix.length()) {
listString.add(sPrefix);
//This value should be returned and concatenated:
System.out.println(sPrefix);
} else {
for (int i=0; i<sInput.length; i++) {
combineArray(sPrefix.concat(sInput[i]), ArrayUtils.removeElement(sInput, sInput[i]), iLength);
}
}
return listString;
}
Keep appending to the same output.. Like this:
private String combineArray(String sPrefix, String[] sInput, int iLength, String output) {
if (iLength == sPrefix.length()) {
//This value should be returned and concatenated:
System.out.println(sPrefix);
output = output+"|+sPrefix;
return output;
} else {
for (int i=0; i<sInput.length; i++) {
output = combineArray(sPrefix.concat(sInput[i]), ArrayUtils.removeElement(sInput, sInput[i]), iLength, output);
}
}
}
You can also use a ListArray instead of a String, once the basic concept works..
Related
//this is the method to get the first string in the arraylist
public static Integer findFirstString(ArrayList<String> arrayOfStrings, String stringToFind) {
if (arrayOfStrings.isEmpty()) {
return -1;
}
if (arrayOfStrings.get(0).equals(stringToFind)) {
return 0;
}
//int index = 0;
//Error is line below this
Integer resultArray = findFirstString(arrayOfStrings.get(index), stringToFind);
if (resultArray == -1) {
return resultArray;
}
else {
return resultArray + 1;
}
}
I need help fixing the get(index) part, I'm not sure if initializing it helps or if it is completely incorrect.
In you code your method
findFirstString(ArrayList<String> arrayOfStrings, ....
is expecting an ArrayList, but when you can it as
findFirstString(arrayOfStrings.get(index)...
the method
arrayOfStrings.get(index)
only returns one Object.
Consider change your method so that it passing in an index which should be used like (not tested)
public static Integer findFirstString(ArrayList<String> arrayOfStrings, String stringToFind,
int index) {
if (arrayOfStrings.isEmpty()) {
return -1;
}
if (arrayOfStrings.get(index).equals(stringToFind)) {
return 0;
}
return findFirstString(arrayOfStrings, stringToFind, index++);
}
This may be a very simple question, but I can't seem to find a suitable answer on Google. I have a class called Player, which has a String array called playerInv with a size of 10.
In my Main Activity Class, I want to run a for loop to determine the first index in the array that is empty (""). I then want to populate that with a new string, and then terminate the loop. How do I do this?
Sorry for the nooby question. Like I said, I've tried Google to no avail!
For Loop:
String playerInvTemp[] = thePlayer.getPlayerInv; ERROR -- cannot resolve getPlayerInv
for (int i=0; i < playerInvTemp.length; i++)
{
if ((!playerInvTemp[i].isEmpty()) || playerInvTemp[i] == null)
{
setPlayerInv("Blood Essence", i); ERROR cannot resolve setPlayerInv
//invText.setText();
Blood = true;
break;
}
}
Player Class:
public class Player {
private int playerPos;
private int playerHP;
private String playerInv[];
Player(int startPos, int startHP, String[] newInventory)
{
playerPos = startPos;
playerHP = startHP;
playerInv = newInventory;
}
public int getPlayerPos() {
return playerPos;
}
public void setPlayerPos(int playerPos) {
this.playerPos = playerPos;
}
public int getPlayerHP(){
return playerHP;
}
public void setPlayerHP(int playerHP){
this.playerHP = playerHP;
}
public String getPlayerInv(int pos)
{
return playerInv[pos];
}
public void setPlayerInv(String playerInv[]) {
for (int i=0; i<10; i++)
{
this.playerInv[i] = playerInv[i];
}
}
public void setPlayerInv(String val, int index)
{
this.playerInv[index] = val;
}
public String getPlayerInv()
{
return this.playerInv; *//this gives error "Incompatible types. Required java.lang.string, found java.lang.string[]"*
}
}
Do this
Add these two method in Player class
public void setPlayerInv(String val, int index)
{
this.playerInv[index] = val;
}
public String[] getPlayerInv()
{
return this.playerInv;
}
then change your for loop like this
String playerInvTemp[] = thePlayer.getPlayerInv();
for (int i=0; i < playerInvTemp.length; i++)
{
if (!playerInvTemp[i].isEmpty()) || playerInvTemp[i] == null)
{
setPlayerInv("Blood Essence", i);
//invText.setText();
Blood = true;
break;
}
}
Bunch of problems here, .length() is not valid for an array, it should be .length.
`for (int i=0; i<thePlayer.getPlayerInv(i).length(); i++)`
You most likely mean null or at least need to check for it, here and you need [] not ():
if (thePlayer.getPlayerInv[i] == "" or theplayer.getPlayerInv[i] == null)
This is all wrong, and as a matter of fact you need to post your code and errors, you have many problems and should start with learning some basics about Java.
Try some beginners tutorials (https://www.google.com/search?q=java+tutorials&ie=utf-8&oe=utf-8). You have a lot of both syntax and logic errors.
Do you run an instance of constructor player()??
I did
Player a=new Player();
a.getPlayerInv(0)
and works fine.
I am attempting to print out a hashset taking in records from a database which are currently stored in two seperate ArrayLists. When I attempt to print out the HashSet the following error shows.
This is your HashSet[nyu.Sorting#378bf509, nyu.Sorting#7b23ec81, nyu.Sorting#15aeb7ab, nyu.Sorting#27d6c5e0, nyu.Sorting#7ef20235, nyu.Sorting#4f3f5b24, nyu.Sorting#6acbcfc0, nyu.Sorting#2d98a335, nyu.Sorting#5fd0d5ae, nyu.Sorting#16b98e56]
And this is my code:
public static HashSet<Sorting> t() {
Sorting s = new Sorting();
int TimeNeededOne = 75;
int TimeNeededTwo = 75;
int assignedTimeOne = 0;
int assignedTimeTwo = 0;
HashSet<Sorting> c = new HashSet<Sorting>();
for(int i=0; i<=i1.size()-1; i++)
{
if((assignedTimeOne < TimeNeededOne) && !(assignedTimeOne+ i1.get(i).getLengthMins() > offensiveTimeInMins) )
{
c.add(i1.get(i));
assignedTimeOne += i1.get(i).getLengthMins();
}
}
for(int i=0; i<=i2.size()-1; i++)
{
if((assignedTimeTwo < TimeNeededTwo) && !(assignedTimeTwo + i2.get(i).getLengthMins() > TimeNeededTwo) )
{
c.add(i2.get(i));
assignedTimeTwo += i2.get(i).getLengthMins();
}
}
System.out.println("Training programme :" + c.size());
System.out.println("This is your training programme" + c.toString());
return c;
}
The c.size is there to confirm that ten entries are made which is correct however the formatting of the records from the hashset obviously contains a problem. Any help with this issue would be greatly appreciated.
Thanks.
One way of doing this would be to override the toString() method of your Sorting class to print its contents:
public class Sorting {
...
#Override
public String toString() {
// Return a String that represents this object
return "...";
}
}
You need override toString() method in the Sorting class, for example:
class Sorting {
...
#Override
public String toString() {
// a string representation of Sorting object
}
}
java.util.Iterator runs through the whole collection and for each element invokes a toString() method. The data recorded in the java.lang.StringBuilder, which returns of its string representation at the end.
Hello I have implemented this basic program which should sort out the strings that are inserted however it somehow is failing to insert the strings .
For example if I implement :
TestSort t = new TestSort();
t.i("abc");
t.i("aab");
Can anybody see the error and help me fix this error please ?
Thank you
Here is the code :
public class TestSort {
private int length;
String[] data;
public TestSort() {
length = 0;
}
public void i(String value) {
data[length] = value;
setSorted(data);
length++;
}
public void setSorted(String data[]) {
for(int i = data.length-1; i >= 0; i--) {
for(int j = 0; j < i; j++) {
if(data[j].compareTo(data[j + 1]) > -1) {
String temp = data[j];
data[j] = data[j + 1];
data[j + 1] = temp;
}
}
}
for(int i = 0; i < data.length; i++) {
System.out.print(data[i] +" ");
}
}
}
You don't initialize the array data. So it is set null, and accesses with data[i] will get you an NullPointerException. Even if you initialize this field, it will not work, as Arrays in Java have a fixed size, you have to reallocate the Array, if you insert a new value. You should try a List-implementation instead.
So the code should initialize in the constructor:
data = new ArrayList<String>();
and insertion would change to
data.add(value);
you can change your constructor code as (String array max length can be taken as input parameter):
public testsort()
{
data = new String[10];
length = 0;
}
But if you are not sure with the size of array you can use ArrayList.
You are getting exception because you are comparing with data[j+1] that is still null.
first time when you call
t.i("abc");
there is only one reference in data array that is pointing to String literal "abc" and that is at index 0. index 1 is still referring to null.
first String is already sorted so no need to sort that. if you are having more than one string then you should call setSorted() method.
to solve this you can put your condition in loop as:
if((data[j] != null && data[j+1] != null) &&(data[j].compareTo(data[j + 1]) > -1))
A working example but still: use a List and life is much easier :-)
public class Test {
private int length;
private String[] data;
public Test(int arrayLength) {
// INITIALIZE YOU ARRAY --> No NULLPOINTEREXCEPTION!
data = new String[arrayLength];
length = 0;
}
public void i(String value) {
data[length] = value;
length++;
}
public void setSorted() {
for (int j = 0; j < data.length - 1; j++) {
if (data[j].compareTo(data[j + 1]) > -1) {
String temp = data[j];
data[j] = data[j + 1];
data[j + 1] = temp;
}
}
for (String s : data) {
System.out.println(s);
}
}
public static void main(String[] args) {
Test t = new Test(5);
t.i("bbb");
t.i("aaa");
t.i("ccc");
t.i("zzz");
t.i("ddd");
// USE SETSORTED HERE --> else you fill your array with the same elements
t.setSorted();
}
}
The variable 'data' is null since it is nowhere initialized hence giving null pointer exception. Since 'data' is an array and as per the rule whenever an array is defined, it has to be of defined length. for e.g if we consider your case. 'data' can be initialized as :-
String[] data = new String[any numerical value]
the numerical value will be its length i.e. the maximum number of elements it can hold.
Secondly, as per your program statement :-
data[length] = value;
is trying to assign value at data's [length] index which is completely wrong since you haven't defined the length therefore how could you guess the index's value. Therefore your this approaoch is logically wrong.
For such situation i.e. whenever we're unaware about the length of the array, use of ArrayList is suggested. Therefore your program can be re-written by two ways:-
1) Either define the length of the array
String[] data = new String[n];
where n ranges from at least 1 to any positive integer.
2) By using ArrayList
public class Main {
List<String> data;
public Main(){
data = new ArrayList<String>();
}
public static void main(String... q){
Main m = new Main();
m.insertData("abc");
m.insertData("zxy");
m.insertData("aab");
m.insertData("aaa");
m.showData();
}
public void insertData(String str){
data.add(str);
Collections.sort(data);
}
public void showData(){
if(data!=null && !data.isEmpty()){
for(String s : data){
System.out.println(s);
}
}
}
}
output:-
aaa
aab
abc
zxy
Hope this helps.
as Mnementh suggested, the reason for NPE is that you have created the field data of type String[] but you never initialized it.
Other answers have provided every reason on why your code throwing ugly errors; I have just improved your code by replacing your String[] with List<String> so you don't have to worry about the size of your array anymore.
Sorting is also simplified now using Collections.sort().
have a look,
class test1 {
public static void main(String[] args) {
Test sorting = new Test();
sorting.input("abc");
sorting.input("cba");
sorting.input("aab");
sorting.setSorted();
}
}
class Test {
private List<String> data = new ArrayList<String>();
public void input(String value) {data.add(value);}
public void setSorted() {
Collections.sort(data);
for (String current : data) {
System.out.println(current);
}
}
}
if you are using Java 8, then you can use Arrays.parallerSort(), it performs sorting the same way as Collection.sort but with a parallel implementation.
Current sorting implementations provided by the Java Collections Framework > (Collections.sort and Arrays.sort) all perform the
sorting operation sequentially in the calling thread. This enhancement
will offer the same set of sorting operations currently provided by
the Arrays class, but with a parallel implementation that utilizes the
Fork/Join framework. These new API's are still synchronous with regard
to the calling thread as it will not proceed past the sorting
operation until the parallel sort is complete.
to implement it, replace Collections.sort with Arrays.parallelSort in the above code,
Replace,
Collections.sort(data);
with,
Arrays.parallelSort(data.toArray(new String[data.size()]));
I wanted to know if there's a native method in array for Java to get the index of the table for a given value ?
Let's say my table contains these strings :
public static final String[] TYPES = {
"Sedan",
"Compact",
"Roadster",
"Minivan",
"SUV",
"Convertible",
"Cargo",
"Others"
};
Let's say the user has to enter the type of car and that then in the background the program takes that string and get's it's position in the array.
So if the person enters : Sedan
It should take the position 0 and store's it in the object of Cars created by my program ...
Type in:
Arrays.asList(TYPES).indexOf("Sedan");
String carName = // insert code here
int index = -1;
for (int i=0;i<TYPES.length;i++) {
if (TYPES[i].equals(carName)) {
index = i;
break;
}
}
After this index is the array index of your car, or -1 if it doesn't exist.
for (int i = 0; i < Types.length; i++) {
if(TYPES[i].equals(userString)){
return i;
}
}
return -1;//not found
You can do this too:
return Arrays.asList(Types).indexOf(userSTring);
I had an array of all English words. My array has unique items. But using…
Arrays.asList(TYPES).indexOf(myString);
…always gave me indexOutOfBoundException.
So, I tried:
Arrays.asList(TYPES).lastIndexOf(myString);
And, it worked. If your arrays don't have same item twice, you can use:
Arrays.asList(TYPES).lastIndexOf(myString);
try this instead
org.apache.commons.lang.ArrayUtils.indexOf(array, value);
Use Arrays class to do this
Arrays.sort(TYPES);
int index = Arrays.binarySearch(TYPES, "Sedan");
No built-in method. But you can implement one easily:
public static int getIndexOf(String[] strings, String item) {
for (int i = 0; i < strings.length; i++) {
if (item.equals(strings[i])) return i;
}
return -1;
}
There is no native indexof method in java arrays.You will need to write your own method for this.
An easy way would be to iterate over the items in the array in a loop.
for (var i = 0; i < arrayLength; i++) {
// (string) Compare the given string with myArray[i]
// if it matches store/save i and exit the loop.
}
There would definitely be better ways but for small number of items this should be blazing fast. Btw this is javascript but same method should work in almost every programming language.
Try this Function :
public int indexOfArray(String input){
for(int i=0;i<TYPES,length();i++)
{
if(TYPES[i].equals(input))
{
return i ;
}
}
return -1 // if the text not found the function return -1
}
Testable mockable interafce
public interface IArrayUtility<T> {
int find(T[] list, T item);
}
implementation
public class ArrayUtility<T> implements IArrayUtility<T> {
#Override
public int find(T[] array, T search) {
if(array == null || array.length == 0 || search == null) {
return -1;
}
int position = 0;
for(T item : array) {
if(item.equals(search)) {
return position;
} else {
++position;
}
}
return -1;
}
}
Test
#Test
public void testArrayUtilityFindForExistentItemReturnsPosition() {
// Arrange
String search = "bus";
String[] array = {"car", search, "motorbike"};
// Act
int position = arrayUtility.find(array, search);
// Assert
Assert.assertEquals(position, 1);
}
Use this as a method with x being any number initially.
The string y being passed in by console and v is the array to search!
public static int getIndex(int x, String y, String[]v){
for(int m = 0; m < v.length; m++){
if (v[m].equalsIgnoreCase(y)){
x = m;
}
}
return x;
}
Refactoring the above methods and showing with the use:
private String[] languages = {"pt", "en", "es"};
private Integer indexOf(String[] arr, String str){
for (int i = 0; i < arr.length; i++)
if(arr[i].equals(str)) return i;
return -1;
}
indexOf(languages, "en")