Java : Simple array with custom range of values (int)? - java

i have the following code;
int minValForRange = myDataObj.getMinValue();
int maxValForRange = myDataObj.getMaxValue();
String[] arrOfRangesForSelection = new String[maxValForRange];
Logger.d(String.valueOf(minValForRange));
Logger.d(String.valueOf(maxValForRange));
for (int i = minValForRange; i <= maxValForRange; i++) {
arrOfRangesForSelection[i] = String.valueOf(i);
}
minValForRange & maxValForRange are dynamic variables (in this case are 1 and 300) so it this case code above is throwing exception:
length=300; index=300
How to have an array which is indexed from minValueRange please?
Many thanks for any advice.

How to have an array which is indexed from minValueRange please?
You can't, in Java. Your best bet is just to do the math as necessary (but I mention a couple of alternatives below, which really just encapsulate it), e.g.:
int minValForRange = myDataObj.getMinValue();
int maxValForRange = myDataObj.getMaxValue();
String[] arrOfRangesForSelection = new String[maxValForRange - minValForRange + 1];
// Enough room for the range (inclusive) -----^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Logger.d(String.valueOf(minValForRange));
Logger.d(String.valueOf(maxValForRange));
for (int i = minValForRange; i <= maxValForRange; i++) {
arrOfRangesForSelection[i - minValForRange] = String.valueOf(i);
// The math ------------^^^^^^^^^^^^^^^^^^
}
(Note that in the above I'm assuming maxValForRange should be included, because that's how you wrote your loop, which is why we have + 1 in the line allocating the array.)
If you didn't want maxValForRange to be included (in programming, we usually include the lower bound but not the upper bound), you wouldn't have the + 1 on the array allocation and would use < rather than <= in the loop:
int minValForRange = myDataObj.getMinValue();
int maxValForRange = myDataObj.getMaxValue();
String[] arrOfRangesForSelection = new String[maxValForRange - minValForRange];
// No + 1 here --------------------------------------------------------------^
Logger.d(String.valueOf(minValForRange));
Logger.d(String.valueOf(maxValForRange));
for (int i = minValForRange; i < maxValForRange; i++) {
// Just < here ----------------^
arrOfRangesForSelection[i - minValForRange] = String.valueOf(i);
}
If you want, you can trivially write a class that will provide get and set methods which do the necessary math so you don't have to repeat it all over the code, and wrap your array in that class.
You can also do an ArrayList subclass that does the necessary math.

Access to array element is zero-based, so when you try to access maxValForRange, you have to have maxValForRange+1 size;

just use i < maxVal instead of i <= maxVal.
for (int i = minValForRange; i < maxValForRange; i++)
arrOfRangesForSelection[i] = String.valueOf(i);

Related

randomly select and delete 2 different items form array

How can I remove the item in an array that is selected by the random?.
Instead of giving me two different items in an array it's just printing the same item selected by the random.
String[] names = {"jey","abby","alyssa","cole","yzabel","miho"};
Random rand = new Random();
String names_rand = names[rand.nextInt(names.length)];
for(int i = 0; i < 2; i++){
System.out.println(names_rand);
}
It's simply because any code outside the for loop won't run again, try this to run the random code every loop to get a new (possible same since it's random) string from the array
String[] names = {"jey","abby","alyssa","cole","yzabel","miho"};
Random rand = new Random();
for(int i = 0; i < 2; i++){
String names_rand = names[rand.nextInt(names.length)];
System.out.println(names_rand);
}
as for deleting the item that would be somehow complicated using a string array as once it's allocated you can't add or delete from it (you can't modify it's size )unless you are willing to make a new temporary array, copy all of its items without the chosen string like this maybe :
String[] names = {"jey", "abby", "alyssa", "cole", "yzabel", "miho"};
Random rand = new Random();
for (int i = 0; i < Math.min(2, names.length); i++) {
int randInt = rand.nextInt(names.length), cpyIdx = 0;
String[] namesTemp = new String[names.length - 1];
for (int j = 0; j < names.length; j++) {
if (j != randInt) {
namesTemp[cpyIdx] = names[j];
cpyIdx++;
}
}
names = namesTemp;
a better version of this complicated code would be using an ArrayList, which allows to add and remove its items (change its size at runtime) easily with just one method call like this :
ArrayList<String> names = new ArrayList<>(Arrays.asList("jey", "abby", "alyssa", "cole", "yzabel", "miho"));
Random rand = new Random();
for (int i = 0; i < Math.min(2, names.size()); i++) {
int randInt = rand.nextInt(names.size());
names.remove(randInt);
}
you can read more about ArrayLists how to add/remove items through this link as well as many tutorials out there just write ArrayList java in google search engine
N.B : I've added Math.min(2, names.length) to the for loop condition as I was afraid you would get to the case that the array length would be less than the number of items you want to delete, using Math.min I'm ensuring that the for loop won't try access an item that isn't there in the array
If you are required to use Arrays then this way is probably among the best
with the limitations involved.
generate a random number and get the name
create a new temporary array to hold the all names less the one removed.
copy all names up to but excluding the one removed to the temp array
copy all names just after the one excluded to the temp array.
assign the temp array to the original array
normal exceptions will be thrown if a null or empty array is used.
Random r = new Random();
String[] names =
{ "jey", "abby", "alyssa", "cole", "yzabel", "miho" };
ArrayList<Integer> a;
int idx = r.nextInt(names.length);
String name = names[idx];
String[] temp = new String[names.length - 1];
for (int i = 0; i < idx; i++) {
temp[i] = names[i];
}
for (int i = idx; i < temp.length; i++) {
temp[i] = names[i + 1];
}
names = temp;
System.out.printf("'%s' was removed.%n",name);
System.out.println(Arrays.toString(names));
Prints something like
'jey' has been removed.
[abby, alyssa, cole, yzabel, miho]
It's interesting to note that the best way would be to use an ArrayList as already given in a previous answer. But the primary reason is that an ArrayList does not need to make a temporary array but simply copies in place. Then it adjusts the size value, effectively hiding the garbage still in the internal array.

How to remove object from array

Please bear within as it might be difficult to understand
I have an array of jbuttons 50 size big, for this example ill use 7 I have jbutton object within 1 2 3 4 6 7 but not 5. These are printed on the screen. I want to remove these jbuttons however all buttons up to 5 are removed while the last two are not.
for(int i = 1; i < 51; i++){
if(seat.buttonArray[i] == null){
remove(seat.buttonArray[i]);
seat.buttonArray[i] = null;}
}
There is no way to remove element from array, assuming you want latter indexes changed after remove. For this purpose, you should use List:
Iterator buttonIterator = seat.buttonList.iterator();
while (buttonIterator.hasNext()) {
Object button = buttonIterator.next(); //or more specific type, if your list was generified
if (button == null) { //or some other criteria, wrote this just as an example
buttonIterator.remove();
}
}
If using array is mandatory, you have two options:
Set seat.buttonArray[i] to null value, indicating it has been removed;
Recreate array each time you deleted something. See System.arraycopy javadoc for details, although I do not recommend this approach because of performance considerations.
You could store the values in a temp array and then copy what you want back into your original array. Somewhat similar to this:
int myArray[50];
int temp[50];
int good;
for (int i = 0; i < 50; i++) {
myArray[i] = i;
}
for (int i = 0; i < 50; i++) {
temp[i] = myArray[i];
}
good = 0;
for (int i = 0; i < 50; i++) {
if (i < 10) {
} else {
myArray[good] = temp[i];
good += 1;
}
}
Looks messier than I first thought... But it essentially does what you're wanting.

Count characters in a multidimensional array, Java

Below is my code:
public int maxTurns = 0;
public String[][] bombBoard = new String[9][9];
...
public void loadBombs()
{
//loadArray();
Random randomGen = new Random();
for (int u=1; u<=9; u++)
{
int randomRow = randomGen.nextInt(9);
int randomCol= randomGen.nextInt(9);
bombBoard[randomRow][randomCol] = "#";
}
//counting #'s -- setting variable
for (int d = 0; d < bombBoard[bombRow].length; d++)
{
for (int e = 0; e < bombBoard[bombCol].length; e++)
{
if (bombBoard[d].equals("#") || bombBoard[e].equals("#"))
{
maxTurns++;
}
}
}
All I want to do is count the amount of (#)'s in the multidimensional array and assign it to a variable called maxTurns.
Probably very simple, just having a super hard time with it tonight. Too much time away from Java >.<
This line is equating the character # with the entire dth row or eth row. Does not make sense really because an array row cannot equal to a single character.
if (bombBoard[d].equals("#") || bombBoard[e].equals("#"))
Instead, access a single cell like this
if (bombBoard[d][e].equals("#"))
And initialize maxTurns before counting i.e. before your for loop:
maxTurns = 0;
You need to change the if codition
if (bombBoard[d].equals("#") || bombBoard[e].equals("#"))
to
if (bombBoard[d][e].equals("#"))
You are using 2D Array, and do array[i][j] can populate its value for a gavin position.
do you want to count from the whole array or certain parts of the array only?
From the code snippet you gave above, I can't really tell how you iterate the array since I'm not sure what is
bombBoard[bombRow].length and bombBoard[bombCol].length
But if you want to iterate the whole array, think you should just use:
for (int d = 0; d < 9; d++) // as you declared earlier, the size of array is 9
{
for (int e = 0; e < 9; e++) // as you declared earlier, the size of array is 9
{
if (bombBoard[d][e].equals("#"))
{
maxTurns++;
}
}
}

Storing computations in arrays - second try

im new to Java and currently trying to learn how to best store numbers in arrays.
the specific problem im working on is trying to find a way to better implement the below methods by storing the computations in an array.
the code looks like this:
public static long myF(int N) {
long[] computedValues;
computedValues = new long[N+1];
computedValues[0] = 0;
computedValues[1] = 1;
for (int i = 2; i < computedValues.length ;i++){
computedValues[i] = computedValues[(i-1)]+computedValues[(i-2)];
System.out.println("array["+(i)+"] = "+computedValues[i]);
}
return computedValues[N-1];
}
public static void runMyF() {
for (int N = 0; N < 100; N++)
StdOut.println(N + " " + myF(N));
}
public static void main(String[] args) {
runMyF ();
}
Main in this code is supposed to call runMyF(), and then runMyF() is supposed to call myF().
My problem is that I cant get computedValues[0] = 0; computedValues[1] = 1; included in the output and the second problem is that ie get this error message when runMyF() calls myF():
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at algs11.MyFib.myF(MyFib.java:21)
at algs11.MyFib.runMyF(MyFib.java:30)
at algs11.MyFib.main(MyFib.java:37)
Any help please?
#Dukeling, your solution was a bit over my pay grade (sorry) - I think there are some bugs in my code and I need help to find them. Thank you.
You're incrementing the wrong variable.
for (int i = 2; i < computedValues.length; N++){
should be
for (int i = 2; i < computedValues.length; i++){
Note the N++ changed to i++.
Remember to initialize computedValues[0] and computedValues[1]. This should appear before the loop:
computedValues[0] = 0;
if (N > 0) // needed because when N = 0, the below will be out of bounds
computedValues[1] = 1;
It should probably be computedValues = new long[N+1];, otherwise the array is too small.
You need to return the correct value - change return computedValues[N]; to return 0;.
Additional efficiency:
I guess the point is to compare the efficiency of the two method. If not, you should declare computedValues outside of the function as an ArrayList and, in the function, add to it as required. This will cause you to only compute each value once for the entire run of the program.
static ArrayList<Long> computedValues = new ArrayList<Long>(Arrays.asList(0l,1l));
public static long myF(int N) {
for (int i = computedValues.size(); i <= N; i++){
computedValues.add(computedValues.get(i-1) + computedValues.get(i-2));
System.out.println("array[" + i + "] = " + computedValues.get(i));
}
return computedValues.get(N);
}
You forgot the initial numbers in the array:
long[] computedValues;
computedValues = new long[N];
computedValues[0] = 0;
computedValues[1] = 1;
You are initializing computedValues to a new long
computedValues = new long[N];
I think you wanted to do this :
computedValues[i] = F(N);
Also, in your loop you are not incementing i which makes it as infinite loop. Change it to
for (int i = 2; i < computedValues.length ;i++)
You can use a method that returns an arraylist:
ArrayList<Long>series=new ArrayList<Long>();
for(int i=0;i<100;i++)
{
if(i==0)series.add(new Long(0));
if(i==1)series.add(new Long(1));
if(i>1)series.add(new Long(series.get(i-1).longValue()+series.get(i-2).longValue()));
}
the list will have 0,1,1,2,3,5,8,....

Efficient methods for Incrementing and Decrementing in the same Loop

Suppose some situations exist where you would like to increment and decrement values in the same for loop. In this set of situations, there are some cases where you can "cheat" this by taking advantage of the nature of the situation -- for example, reversing a string.
Because of the nature of building strings, we don't really have to manipulate the iterate or add an additional counter:
public static void stringReversal(){
String str = "Banana";
String forwardStr = new String();
String backwardStr = new String();
for(int i = str.length()-1; i >= 0; i--){
forwardStr = str.charAt(i)+forwardStr;
backwardStr = backwardStr+str.charAt(i);
}
System.out.println("Forward String: "+forwardStr);
System.out.println("Backward String: "+backwardStr);
}
However, suppose a different case exists where we just want to print a decremented value, from the initial value to 0, and an incremented value, from 0 to the initial value.
public static void incrementAndDecrement(){
int counter = 0;
for(int i = 10; i >= 0; i--){
System.out.println(i);
System.out.println(counter);
counter++;
}
}
This works well enough, but having to create a second counter to increment seems messy. Are there any mathematical tricks or tricks involving the for loop that could be used that would make counter redundant?
Well it looks like you just want:
for(int i = 10; i >= 0; i--){
System.out.println(i);
System.out.println(10 - i);
}
Is that the case? Personally I'd normally write this as an increasing loop, as I find it easier to think about that:
for (int i = 0; i <= 10; i++) {
System.out.println(10 - i);
System.out.println(i);
}
Note that your string example is really inefficient, by the way - far more so than introducing an extra variable. Given that you know the lengths involved to start with, you can just start with two char[] of the right size, and populate the right index each time. Then create a string from each afterwards. Again, I'd do this with an increasing loop:
char[] forwardChars = new char[str.length()];
char[] reverseChars = new char[str.length()];
for (int i = 0; i < str.length(); i++) {
forwardChars[i] = str.charAt(i);
reverseChars[reverseChars.length - i - 1] = str.charAt(i);
}
String forwardString = new String(forwardChars);
String reverseString = new String(reverseChars);
(Of course forwardString will just be equal to str in this case anyway...)
You can have multiple variables and incrementers in a for loop.
for(int i = 10, j = 0; i >= 0; i--, j++) {
System.out.println(i);
System.out.println(j);
}

Categories