I read such a solution to rotate an array
the question:
public class Solution {
public void rotate(int[] nums, int k) {
int temp, previous;
for (int i = 0; i < k; i++) {
previous = nums[nums.length - 1];
for (int j = 0; j < nums.length; j++) {
temp = nums[j];
nums[j] = previous;
previous = temp;
}
}
}
}
I am confused about previous = nums[num.lengh -1],
is it a range as nums[0:10] or a single element as nums[0]?
It's a single element, he is taking the element in the num.length -1 position, and the value inside is being swapped with nums[j]:
for j=0 you have:
temp = num[0];
num[0] = num[num.length-1]
num[num.length-1] = temp;
And so on.
It is a single element, because num.lengh - 1 is an int and just gives you the last accessible index of the array.
If you check wether the length of the array is > 0, then you can safely use the length of the array to determine the last accessible index.
The length of an array is very often used in loops like yours:
Here the length is used to make sure you don't access unavailable indexes:
for (int j = 0; j < nums.length; j++)
You can write slightly a different condition without changing the functionality
for (int j = 0; j <= nums.length - 1; j++)
But if you do the following, you will get an IndexOutOfBoundsException:
for (int j = 0; j <= nums.length; j++)
The last iteration would try to access nums[nums.length], which isn't there...
nums[nums.length - 1]; gives you the last position of the array. It is -1 cause the positions of an array starts with 0 not with 1.
If you don't write -1 you would get an Out of bounds exception.
single, this is due to you're performing a mathematical expression and then getting a valeu from that. meaning you're taking the length of the array list then subtracting 1 and then getting that value or in other words you're getting the last value.
to get all values you must loop like a for loop etc.
for (i = 0; i < array.length; i++) {
System.out.print(array[i]);
}
Related
I need to perform a cyclic shift of the array elements to the left by n characters.
Here is my code:
public static void moveLeft(int[] arr, int num) {
int[] temp = new int[num];
for (int i = 0; i < num; i++) {
temp[i] = arr[i];
}
for(int i = arr.length - num; i > 0; i++) {
arr[i-num] = arr[i];
}
for (int i = 0; i < num; i++) {
arr[i] = temp[i];
}
}
When I run this code, I get this error: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 10
for( ...; i > 0; i++) is very suspicious, that is, while i > 0 do increment i (if not starting with negative values, i will be incremented till it (silently) overflows or an Exception is thrown somewhere else).
{incrementing ++ requires an upper limit < value (or <=); decrementing -- a lower one > value (or >=) }
The code is accessing arr[i] (and arr[i-num]), so arr.length should be the limit (assuming non-negative num): i < arr.length
it is also the logical choice since it should copy all numbers from index num up to the end of the array.
I looked up this array sorting method and there's one thing that confuses me about it when changing the initial for-loop initialization.
The original for-loop was initialized by 1
(1) for (int i = 1; i < list.length; i++)
I then decided to initialize it by 0 so I adjusted list.length in the if-statement accordingly by deducting 1.
(2) for (int i = 0; i < list.length-1; i++)
Here's the full sorting method:-
public static void sortList(int[] list) {
int temp;
for (int i = 1; i < list.length; i++) {
for (int j = i; j > 0; j--) {
if (list[j] < list[j - 1]) {
temp = list[j];
list[j] = list[j - 1];
list[j - 1] = temp;
}
}
}
}
The original four loop mentioned in the code above correctly sorts the following array [5, 3, 10, 8] to [3, 5, 8, 10]
But my adjustment results in the following: [3, 5, 10, 8].
Why does the original four-loop work, but mine doesn't? Shouldn't both four-loops run 3 times?
I later fixed my issue by adding an equal to the lesser-than operator
(3) for (int i = 0; i <= list.length-1; i++)
But I don't get why it works now. This new four-loop now runs 4 times contrary to how it runs 3 times in the original one and both managed to sort the array.
My question is simple, and its answer is almost certainly a simple one too but I'm too much of a novice to figure it out myself.
Why do these two work:-
(1) for (int i = 0; i <= list.length-1; i++)
(2) for (int i = 1; i < list.length; i++)
But not this one:-
(3) for (int i = 0; i < list.length-1; i++)
Even though four-loop (1) and (3) are identical.
Because (2) for (int i = 0; i < list.length-1; i++) simply ignores the list.length-1 element of the input array. It is never processed, so it will always stay on the last position in the initial array.
Loops (1) and (3) are not identical since (1) for (int i = 0; i <= list.length-1; i++) will process the last element.
I need to make this insertion sort function essentially copy elements to the right until the value that needs to be moved would be in the correct position, however, with the code I'm using I typically end up getting garbage out, and have tried multiple iterations with the same result. I am at wits end as I see no reason why this shouldn't work.
public static void Sort(Comparable[] a) {
int n = a.length;
Comparable temp = 0;
int x;
// Starting with the element at index 1...
for (int i = 1; i < n; i++) {
// ...move to the left until we find one less
// than the current element.
for (int j = i; j > 0; j--) {
if (less(a[j], a[j - 1]))
{
temp = a[j];
for(x = j; x > 0 && less(temp, a[x]); x--)
{
a[x] = a[x - 1];
}
a[x] = temp;
//exch(a, j, j - 1);
}
else
break;
}
}
}
less(a, b) checks to see if a < b, by the way.
On the first iteration of the innermost loop, in this condition: x > 0 && less(temp, a[x]) you are checking whether the value you just stored in temp... is less than the value you just stored in temp, referred to by another name. This will always return false, causing the loop to never start. The end result is that the entire method is an expensive no-op. If you're testing it by sending in a randomly jumbled array, you'll end up with the array still randomly jumbled when it's done.
To fix this, simply subtract 1 from the index in that condition, making it x > 0 && less(temp, a[x - 1]).
The rest of your code looks correct, I think, though the loop with j is redundant and can be removed.
This should do the trick
public static void Sort(Comparable[] a) {
int n = a.length;
Comparable temp = 0;
int x;
// Starting with the element at index 1...
for (int i = 1; i < n; i++) {
// ...move to the left until we find one less
// than the current element.
for (int j = i; j > 0; j--) {
if (less(a[j], a[j - 1]))
{
temp = a[j];
for(x = j; x > 0 && less(temp, a[x-1]); x--)
{
a[x] = a[x - 1];
}
a[x] = temp;
//exch(a, j, j - 1);
}
else
break;
}
}
}
So my task is to read a file line by line and store the integers into an array. Then to add the integers in spots 1-5, 2-6, 3-7 etc. and store those into a new array.
In array 1 there is 4 more values than array 2. I need to compare these Arrays and see if array1 is 0.999 bigger than array2.
If it is indeed larger, I need to print out the LOCATION of the number in the array 1.
Right now my problem is my code is outputting that every number is larger than the corresponding number in array 2.
Code:
import java.io.*;
import java.util.Arrays;
import java.util.Scanner;
public class Asgn7
{
public static void main(String[] args) throws FileNotFoundException
{
Scanner file = new Scanner(new File("asgn7data.txt"));
double[] array = new double[file.nextInt()];
double[] newArray = new double[array.length - 4];
double tempVal = 0;
int j = 0;
int count = 0;
while(file.hasNext())
{
for(int i = 0; i < array.length ; i++)
{
array[i] = file.nextInt();
}
for(j = 0; j < array.length - 4; j++)
{
for(int k = 0; k < 5; k++)
{
newArray[j] += array[j+k] / 5;
}
}
for(int i = 2; i < array.length; i++)
{
if(array[i] > (newArray[i-2] + 0.999));
{
count++;
tempVal = count;
}
System.out.println(tempVal);
}
}
}
}
The values which should be compared are from 3-13.
Judging by the picture, you are not placing the values in the correct index in the second array, or you are not matching the correct ones.
If you want it to look exactly like in the picture, the second array should be declared:
double[] newArray = new double[array.length - 2];
And the loop to fill it should be changed to:
for(j = 2; j < array.length - 2; j++)
{
for(int k = -2; k <= 2; k++)
{
newArray[j] += array[j+k] / 5;
}
}
This will put the averages in the third, fourth, fifth... elements in newArray. And now you can compare them directly:
for(int i = 2; i < array.length - 2; i++)
{
if(array[i] > (newArray[i] + 0.999))
{
count++;
tempVal = count;
}
System.out.println(tempVal);
}
If you want to save the two unused spaces, as you originally did, rather than responding exactly to the picture, then you should calculate the values as you originally did. But remember to compare each element to the one two places before it and stop 2 places before the end.
Instead of
for(int i = 2; i < array.length; i++)
use
for(int i = 2; i < array.length - 2; i++)
To print the location, your construct with the count and tempVal is unnecessary. You just need to print i+1. Also note that you have a ; after your if. This means it's an empty if, and the block after it is always performed. Never have a ; after an if, for, while etc.
Not clear with what you are asking for in your question but without questioning what's the logic, by just looking at your code:
for(int i = 2; i < array.length; i++)
{
if(array[i] > (newArray[i-2] + 0.999));
{
count++;
tempVal = count;
}
System.out.println(tempVal);
}
}
if you relocate the system.out line as follows, I think you will get what you expect as follows:
for(int i = 2; i < array.length - 2; i++)
{
if(array[i] > (newArray[i-2] + 0.999));
{
System.out.println(tempVal);
// count++;
// tempVal = count;
}
}
}
PS: Please note that I have also changed the boundary for the loop to stop iteration on 13th member of the array, instead of 15.
Are you sure you're parsing the numbers correctly?
See Java: Reading integers from a file into an array
Why don't you print them out after parsing for verification?
btw, this will overflow the index of the 2nd array (since it is created using new double[array.length - 4]):
for(int i = 2; i < array.length; i++)
so does your code run?
I am using a for loop to check whether the array i enter in as a parameter has more ups or downs in terms of integers. I am not sure why but my compiler is throwing an index out of bounds exception. Would be nice if someone can just point it out.
public boolean moreUpsThanDowns(int[] a)
{
int counterup = 0;
int counterdown = 0;
for(int i=0 ; i <= a.length ; i++){
if (a[(i+1)] - a[i] > 0 ){
counterup++;
} else if(a[(i+1)] - a[i] < 0 ){
counterdown++;
} else if(a[(i+1)] - a[i] == 0 ){
counterup = counterup;
counterdown = counterdown;
}
}
if (counterup > counterdown){
return true;
} else {
return false;
}
}
A small semantic correction - the compiler isn't throwing any exception - your code compiles just fine. The runtime execution of this code causes an exception.
And more to the point, an array a has elements from 0 to a.length - 1. Your code attempts to access element number a.length and a.length + 1, which would both cause this exception. Since you reference a[i + 1] in the code, your loop should end at a.length - 2, or, in cleaner terms, the condition should be: i < a.length - 1. So, so summarize:
for (int i = 0 ; i < a.length ; i++) {
You are getting an out of bounds exception because of this line:
for(int i=0 ; i <= a.length ; i++){
It should be:
for(int i=0 ; i < a.length ; i++){
This is because arrays in c# are 0 indexed.
For example if an array has 10 elements and you access it like a[10], you get an out of bounds exception because the last element is a[9].
array begin from index 0 so if arrays contain 3 element . the last element will be a[2]
so
for(int i=0 ; i <= a.length ; i++) must be for(int i=0 ; i < a.length ; i++)
and must check if i+1 < a.length or not
if(i+1 < a.length)
For zero based indexing the range is [0,a.length). Not only is the loop out of bounds, the +1 goes even further out. Try,
for (int i = 1; i < a.length; i++)
if (a[i] - a[i-1] > 0)
counterup++;
Nitpicking, you only need one counter. Increment on up, decrement on down. Return true if the final count is greater than zero. You can omit the final condition (==) as well.