How do I add a number(73) into the middle of an array and then move all the numbers from the middle up one so no number is overwriting. Here is my code so far the 73 should go into the middle and the numbers after it should all move over. Can't use an ARRAYLIST.
int midpoint = length/2;
array[midpoint] = 73;
for (int i = midpoint; i<length; i++){
aNums[i+1] = array[i];
System.out.print(array[i] + " ");
}
displayArray1(array,length);
You can't add to an array. You first have to create a bigger array.
int[] newArray = new int[array.length + 1];
Then you have to copy the first half of the array
for(int i = 0; i < midpoint; i++) {
newArray[i] = array[i];
}
Then put the new midpoint in
newArray[midpoint] = 73;
Then copy the other half
for(int i = midpoint + 1; i < array.length; i++) {
newArray[i+1] = array[i];
}
And then newArray has the new midpoint.
Technically the last three steps could be done in any order, but it is much more readable to do them in that order. Now you can call your display method or really do whatever you want with it.
There is a utility method called arrayCopy that can assist with moving the array elements. You may or may not be permitted to use it. It's a bit wordy with its parameters, but is a bit faster than a typical for-loop at runtime because it leverages native code.
int[] newArray = new int[array.length + 1];
System.arrayCopy(array,0,newArray,0,midpoint);
newArray[midpoint] = 73;
System.arrayCopy(array,midpoint,newArray,midpoint+1,array.length - midpoint);
To explain those calls, the arraycopy uses:
System.arrayCopy(arrayFrom,
startPosInArrayFrom,
arrayTo,
startPosInArrayTo,
numElementsToCopy);
Use a List, or more specifically an ArrayList:
ArrayList<Integer> list = new ArrayList<>();
// ... put stuff in list
int midpoint = list.size()/2;
list.add(midpoint, 73);
you are causing yourself a lot more trouble using an array.
use an ArrayList, which is backed by an array
ArrayList l = new ArrayList();
//...fill contents
int index = l.size()/2;
l.add(index, 72);
Related
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.
So I am trying to make an Array with random numbers, but whenever I try Math.random or create a new Random object and use it, I always get the same number multiple times. My code is this one:
int[] Array = new int[size];
for (int Y : Array) {
Array[Y] = (int) (Math.random() * 10) + 3;
}
or this one:
int[] Array = new int[size];
for (int Y: Array) {
Array[Y] = rand.nextInt(30);
}
The output im getting is: [0][3][3][3][3][3][3][3][3][3][3][3][3][3][3][3][3][3][3][3][3][3][3][3][3][3][3][3][3][3]
I haven't set a seed and I tried it outside the loop and inside but still only get the same number.
You are not referring to the index of the array, but to the specific element which remains the same. You have to use indexed loop.
Try with that (it is a good practice to use camelCase for variables, so 'Array' starting with small 'a')
int[] array = new int[size];
for(int i = 0; i < array.length; i++) {
array[i] = rand.nextInt(30);
}
I want to remove a single element from an array. This is what I have tried so far:
for (int i = pos + 1; i < currentSize; i++)
values[???] = values[i];
currentSize--;
I'm so confused on what goes inside the [???]
If anyone can help I would really really appreciate it.
Arrays are not very kind in nature, as they can't be resized. As soon as you have learned about objects and generics you will pretty much stop using arrays and transition to Collections. But for now, you'll have to create a new (smaller) array and copy all - but one - value. I will keep it very basic, so you learn the most:
int indexToRemove = 3;
Object[] newArray = new Object[values.length - 1];
for (int i = 0; i < newArray.length; i++) {
if (i < indexToRemove) {
newArray[i] = values[i];
} else {
newArray[i] = values[i + 1];
}
}
I didn't know of which type your values are, so I just took Object. You may want to replace that.
The ??? In this case indicates the index of the array where you wish to get the value from. If you have an array A with elements 5, 10, 15, and 20 then each of the elements can be retrieved with their index. I.e. the index for 5 is 0, for 10 its 1.
An array of size n will have n-1 elements in it due to zero indexing (A[0] is the first element).
I have an array of terms (terms meaning an object with a coefficient and a degree, represented as for example 1.0x^6). The array that I have right now contains 3 terms:
[1.0x^6, 4.0x^5, 10.0x^0].
My goal is to create a bigger array with these terms, but ALSO with terms with a 0 coefficient that are not represented in my array. That probably was not too clear, so here is basically what I want my new array to look like:
[1.0x^6, 4.0x^5, 0.0x^4, 0.0x^3, 0.0x^2, 0.0x^1, 10.0x^0].
Currently, I am iterating through my original array, and if the degree equals the new array.length - 1, I am setting newArray[i] = array[i], if that makes sense. For example, for the first term and i = 0, the degree is 6, and so if 6 = newArray.length - 1 (which is 6), then newArray[i] = array[i].
The problem, however is that array is smaller than newArray, so I am getting an out of bounds error. Any ideas on how to fix this? Sorry for the long post, thanks!
EDIT: Here is my actual code. Sorry if the explanation was unclear.
int max = 0;
Term temp;
for(int i=0; i<array.length; i++) {
max = i;
for(int j=i; j< array.length; j++) {
if(array[j].getDegree() > array[max].getDegree()) {
max = j;
}
}
temp = array[i];
array[i] = array[max];
array[max] = temp;
}
Above, the array is sorted in terms of descending degree. I want to now have the new array contain the old terms, but also 0x^i for all the i that are not used in my set of terms.
Term[] newArray = new Term[this.degree()+1];
for (int c = 0; c < newArray.length; c++) {
if (array[c].getDegree()==newArray.length-1-c) {
newArray[c] = array[c];
}
else {
newArray[c] = new Term(0, newArray.length-1-c);
}
}
There are issues in my code above, and I can see that now because in that for loop, array[c] is not defined for any c > 2. Eclipse is telling my that I have an out of bounds error.
Arrays have a fixed size. If you want to create a bigger array, you need to know the size beforehand and define it accordingly. Also, it seems that you are going through both the arrays using the same iteration variable.
I assume you are doing something like this:
for(i=0;i<newArray.length;i++){
newArray[i] = array[i]; //size of newArray is bigger than array
}
Then you will always get an array index out of bounds exception because "array" is smaller than "newArray" and you go out of bounds when i>=array.length.
You need to fix your code logic.
So I've got this method:
public static int[] select(int maxWidth, int maxHeight) {
int rHeight = StdRandom.uniform(0, maxHeight);
int rWidth = StdRandom.uniform(0, maxWidth);
return new int[] {rHeight, rWidth};
}
And I'm not advanced enough to work with it on the right way.
I've got a second method where I want to execute 'select' several times. My idea was to do it with a for-loop like that (in which 'n' is a int):
for(int i = 0; i < n; i++){
select(h, w);
}
But now I don't know how to save the result from this for-loop in an 1d-array, since I will always get an error when trying to save like that:
int[] a = new int[select(h, w)];
I'm very aware that this looks very strange and wrong but I just don't know how to do it in the right way and I don't know for what I have to search on google.
Here is a way you could do it:
int[][] a = new int[n][];
for(int i = 0; i < n; i++){
a[i] = select(h, w);
}
Basically this code creates a 2d array, then in the for loop, adds the result of select to each element of the array.
I don't think you can do this in a 1D array, if you want to run select multiple times, and each time it returns an array, you'll have to have an array of arrays. If you are adamant about having a 1D array to store the answers, you'll have to implement a tuple class, although I think you're better off just doing a 2D array the way Sub 6 Resources showed.
int[] combined = new int[n*2];
for(int i = 0; i < n; i++){
int a[] = select(h, w);
System.arraycopy(a, 0, combined, i*2, 2);
}