I've had a decent search and am unable to find working code that moves down an array. What I am hoping to do, is to store the value in the last position in the array, replace the last position and then move array[20] to array[19]. This is meant to count the last 20 moves the player makes, but I'm having trouble actually storing. This is what I have attempted to do
//an int moveArray[20] previously stated and instantiated
int temp1, temp2;
for (int i = moveArray.length - 1; i > 0; i--)
{
temp1 = moveArray[i - 1];
temp2 = moveArray[i - 2];
moveArray[i - 1] = moveArray[i];
temp1 = temp2;
}
moveArray[moveArray.length - 1] = intoWalk;
any advice or solutions would really help, thanks
From what I understand of your code . You should use the following loop, there seems to be no need for temporary variables.
for(int i=0;i<moveArray.length-1;i++){
moveArray[i] = moveArray[i+1];
}
moveArray[moveArray.length - 1] = intoWalk;
First, you don't need to use temporary variables :
int [] moveArray = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20};
int intoWalk = 21;
for (int i = 0; i < moveArray.length-1; i++) {
moveArray[i] = moveArray[i+1];
}
moveArray[moveArray.length - 1] = intoWalk;
for (int i=0; i<moveArray.length; i++)
System.out.println(moveArray[i]);
But there is a better way to do it : use a linked list to emulate a FIFO :
LinkedList<Integer> fifo = new LinkedList<Integer>();
int intoWalk = 21;
for (int i=1; i<=20; i++)
fifo.add(i);
fifo.removeFirst();
fifo.add(intoWalk);
for (Integer fifoItem : fifo)
System.out.println(fifoItem);
By doing this, you don't have to modify every element in your array each time you want to add a number, just to add and remove an item from the linked list.
//an int moveArray[20] previously stated and instantiated
int temp1, temp2;
temp1 = moveArray[moveArray.length - 1];
for (int i = moveArray.length - 2; i >= 0; i--)
{
temp2 = moveArray[i];
moveArray[i] = temp1;
temp1 = temp2;
}
moveArray[moveArray.length - 1] = intoWalk;
The above should do what you want.
However, I don't think this is the right way to go.
I would use the same array as a circular array - that way - you don't need to move down everytime.
Maintain a start index. It begins at
start = 0;
It remains at 0 till the time all 20 elements are filled up.
When the next element comes in,
moveArray[start] = intoWalk;
++start;
When you want to iterate through the array at any time, you begin at start instead of beginning at 0.
int i = start;
do
{
// do what you want
i = (i + 1)%20;
} while (i != start);
First make the last element free by moving all the elements one row down.
Sample :
String[] sarr=new String[10];
for(int i=0;i<sarr.length;i++){
sarr[i]=sarr[i+1];
}
Then assign the new variable to the end.
sarr[sarr.length-1]="new value";
This approach is simpler and more readable.
EDIT : Yes Bohemian is right it was throwing an ArrayIndexOutOfBounds exception. The reason was that i+1 will try to refer to an index out of the array's range at the last iteration.
The solution is either to set the last element to null or break when it's the last element.
I will go with setting the last element to null. The changed code is below.
int nextElementIndex = i + 1;
sarr[i] = nextElementIndex < sarr.length ? sarr[nextElementIndex] : null;
Related
I have an array that contains [45,8,50,15,65,109,2]. i would like to check to see if the zero element of my array is greater than my first element.
if ( 45 > 8)
then i would like to add 45 to brand new sub array.
i would like to continue checking my array for anything that is bigger than 45 and add it to the new sub array.
The new sub array has to keep the numbers added in the way they where added.The result should be [45,50,65,109]
I thought by creating this was going in the right direction but im doing something wrong so please help.
int[] x = [45,8,50,15,65,109,2];
int[] sub = null;
for(int i = 0; i > x.length; i++) {
for(int k = 0; k > x.length; k++) {
if(x[i] > x[k]){
sub = i;
First thing first. Your question contains some errors.
you should write int[] x = {45,8,50,15,65,109,2}; instead of int[] x = [45,8,50,15,65,109,2]; You can not use [] to initialize array!
What does it mean for(int i = 0; i > x.length; i++). Your program must not run! Because, the value of i is less than x.langth. First condition check is false, so loop will not works!
Same for for(int k = 0; k > x.length; k++)
How do you want to store value in an array without index? You have to write sub[i] = x[i]; here, i means what index value you want to store where!
Finally, do you want to do sorting? If yes, then you need another variable named temp means temporary!
Try to clear the basic and after then try this code.Sorting Link
Best of Luck!
It is possible to filter the input array using Java 8 Stream API:
int[] x = {45, 8, 50, 15, 65, 109, 2};
int[] sub = Arrays.stream(x)
.filter(n -> n >= x[0])
.toArray();
System.out.println(Arrays.toString(sub));
Output:
[45, 50, 65, 109]
If you're trying to fetch everything greater than 0th element.
Use the following:
Plain old java code:
int[] x = {45,8,50,15,65,109,2};
int[] sub = new int[x.length];
int first = x[0];
sub[0]=first;
int index=1;
for(int i = 1; i < x.length; i++) {
if(x[i] > first){
sub[index]=x[i];
index++;
}}
Streams API:
int[] x = {45, 8, 50, 15, 65, 109, 2};
int[] sub = Arrays.stream(x).filter(number -> number>=
x[0]).toArray();
where stream() is converting array to a stream, filter is applying the required condition and then ending it with conversion into an Array again.
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 am working on an assignment where we need to take a integer array and sort it using a Bucket Sort.
My issue comes when trying to increase to the next column, but only if there is an element already in the "bucket" already.
So, using my array below, 22 is the first element and will go in row 2 column 0, which is correct, but using i as the column is obviously not correct because it always increases the column and I eventually get an index out of bounds.
I can't wrap my head around how to correctly increase the index of the bucketArray column, only if there is an element in that position. I've tried using an additional for loop that handled the column but that didn't work either.
Any pointers in the right direction would be greatly appreciated! I'm sure also there are other ways to create a bucket sort but the assignment said to use a 2d array for each bucket so I was trying to get it to work that way.
public class BucketSort {
public static void main(String args[]) {
int intArray[] = {22, 45, 12, 8, 10, 6, 72, 81, 33, 18, 50, 14};
int eachBucket[][] = new int[10][11];
int j;
double max = 81;
int min = 6;
int divider = (int)Math.ceil((max + 1) / 10);
for(int i = 0; i < intArray.length; i++) {
j = (int)Math.floor(intArray[i] / divider);
eachBucket[j][i] = intArray[i];
}
}
}
Use the 11th element to track how many elements in the current bucket have been used, something like this
for(int i = 0; i < intArray.length; i++) {
j = (int)Math.floor(intArray[i] / divider);
eachBucket[j][eachBucket[j][10]] = intArray[i];
eachBucket[j][10]++;
}
The problem with a fixed-sized second dimension is if you have more that n elements to put into any one bucket. Probably not a problem here.
This is more of an self defined programming exercise than a real problem. I have an array of java.lang.Comparable items. I need to maintain two pointers (an index into the array i.e., int values) i,j . i starts at the beginning of array and moves right until it encounters an element which is less than or equal to the previous element. When it does it stops moving right and ends up pointing to the element which is out of order(element which is not greater than the previous). Similarly j starts at the end of the array and moves left until it finds an element which is not less than the previous.
Also, I need to make sure that the indices don't run out of the array i.e., i cannot go below 0 and j cannot go above arraylength-1
lets say we have an array of 5 elements.
i = 0;
j = 4;(which is the arraylength-1 )
if C,D,E,F,G is the array ,the final values of i and j will be
i = 4 and j = 0
if array is J,D,E,F,G ,the final values of i, j will be
i = 0 , j = 0
if array is B,C,A,D,G , final values of i,j will be
i = 2 , j = 1
I tried to code the logic for moving i to the right, using a while loop as below. I was able to get it working for the i pointer in two cases.
public class PointerMovement{
public static void ptrsPointToOutOfOrderElements(Comparable[] a){
int lo = 0;
int hi = a.length-1;
int i = lo;
int t=i+1;
int j = hi;
//only for moving i to the right .
while(less(a[i],a[t])){
if(t == hi){
i=t;
break;
}
i++;
t++;
}
i=t;
for(Comparable x:a){
System.out.print(x+",");
}
System.out.println();
System.out.println("bad element or end of array at i="+i+"==>"+a[i]);
}
private static boolean less(Comparable x,Comparable y){
return x.compareTo(y) < 0;
}
public static void main(String[] args) {
String[] a = new String[]{"C","D","E","F","G"};//works
//String[] a = new String[]{"B","C","A","D","G"};//works
//String[] a = new String[]{"J","D","E","F","G"};//fails!
ptrsPointToOutOfOrderElements(a);
}
}
My line of reasoning given below
I maintain i=0; and another variable t=i+1
when the while loop fails, less(a[i],a[t]) is false .We need to return a pointer to a[t] which is out of order. so i=t and return i.
if we reach right end of array, the test if(t == hi) passes and we assign i=t and now i points to end of array.
However, the code fails when the out of order element is in the 0th position in the array.
J,D,E,F,G
Instead of i (=0) we get i=1 because i=t is assgined.i ends up pointing to D instead of J.
Can someone point me in the right direction?
update:
this seems to work
public static void ptrsPointToOutOfOrderElements(Comparable[] a){
int lo = 0;
int hi = a.length-1;
int i = lo;
while(less(a[i],a[i+1])){
if(i+1 == hi){
break;
}
i++;
}
i++;
int j = hi;
while(less(a[j-1],a[j])){
if(j-1 == lo){
break;
}
j--;
}
j--;
for(Comparable x:a){
System.out.print(x+",");
}
System.out.println();
if(i>=j){
System.out.println("pointers crossed");
}
System.out.println("bad element or end of array at i="+i+"==>"+a[i]);
System.out.println("bad element or end of array at j="+j+"==>"+a[j]);
}
I do not think you have a problem:
String[] a = new String[]{"C","D","E","F","G"};//works, index should be 4 (but should it be so? It would indicate that G is out of order while it is not. I think you should return 5, indicating that none is out of order.
String[] a = new String[]{"B","C","A","D","G"};//works, index should be 2 as A is out of order
String[] a = new String[]{"J","D","E","F","G"};//works since the first out of order element is indeed D, with index 1
I have tried using simple for loop.
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
for (var i = 0, j = arr.length - 1; i <= j; i++, j--) {
console.log(arr[i] + ' , ' + arr[j]);
}
Output :
1 , 10
2 , 9
3 , 8
4 , 7
5 , 6
I have an unusual problem. I've been implementing Merge Sort and have encountered the following: The method works correctly except on the last pass. Given a random Integer array as input returns an Integer array where the first half and the second half are sorted separately. The merge works correctly except on the last pass. After fiddling with the debugger for a few hours I figured out that "mention point" is always evaluating to false on the last pass, even though it shouldn't based on the values.
All help is appreciated.
public static Integer[] mergeSort(Integer[] input)
{
if (input.length == 1) return input;
int splittle = input.length / 2;
Integer[] first = new Integer[splittle];
Integer[] second = new Integer[input.length - splittle];
for (int i = 0; i < splittle; i++)
first[i] = input[i];
for (int i = splittle; i < input.length; i++)
second[i - splittle] = input[i];
mergeSort(first);
mergeSort(second);
LinkedList<Integer> returner = new LinkedList<Integer>();
PriorityQueue<Integer> sFirst = new PriorityQueue<Integer>();
PriorityQueue<Integer> sSecond = new PriorityQueue<Integer>();
for (int i = 0; i < first.length; i++)
sFirst.offer(first[i]);
for (int i = 0; i < second.length; i++)
sSecond.offer(second[i]);
// while (!sFirst.isEmpty()&&!sSecond.isEmpty())
// returner.add((sFirst.peek()>=sSecond.peek() ?
// sFirst.poll():sSecond.poll()));
// expansion of line above for debugging purposes
while (!sFirst.isEmpty() && !sSecond.isEmpty())
{
int temp = 0;
if (sFirst.peek() >= sSecond.peek())
temp = sFirst.poll(); // Mention point
else
temp = sSecond.poll();
returner.add(temp);
}
while (!sFirst.isEmpty())
returner.add(sFirst.poll());
while (!sSecond.isEmpty())
returner.add(sSecond.poll());
return returner.toArray(new Integer[0]);
}
The problem is inside your while code, and more specific when you use the poll() method.
You had:
if (sFirst.peek() >= sSecond.peek())
temp = sFirst.poll(); // Mention point
else
temp = sSecond.poll();
when you should had:
if (sFirst.peek() >= sSecond.peek())
temp = sSecond.poll(); // Mention point
else
temp = sFirst.poll();
Before, in an input like this:
sFirst = [-9, 1, 2, 9, 89] and sSecond = [4, 15, 18, 23, 31, 123]
you would have if (-9 >= 4) which would be false, so you would do the else part, which would poll() from sSecond although you should poll() from sFirst. -9 should be the first element to be added in the returner list, not 4.
Also (based on ccoakley answer) change, you should use the returned array from mergeSort(), which can be done easily by:
first = mergeSort(first);
second = mergeSort(second);
You can have a look of the working code (after the changes) here.
I hope this helps: why do you have mergeSort return an Integer array, but then not use the return value in your call to mergeSort(first) and mergeSort(second)?
It appears as if part of your code was written to sort the passed in values and part was written to return a sorted array.