Reversing elements of an array - java

Given an array a and two other int variables, k and temp, write a loop that reverses the elements of the array.
for (k = 0; k < a.length-1; k++) {
temp = a[k];
a[k] = a[a.length-1-k];
a[a.length-1-k] = temp;
}
This is not working. Any idea why?

E.g., for a = [0, 1, 2, 3, 4, 5] you'll switch 0 and 5 twice: when i == 0 and when i == 5. This double-switching will put both elements into their original positions: (0, 5) -> (5, 0) -> (0, 5).
Try to make your loop to go through half of array only: so each pair is switched once.

You need to stop your loop at a.length/2 (in the middle).
for(k=0;k<a.length/2;k++)
This should work for odd and even length arrays if this is integer division.

check this at my blog hope this going to help http://codeheaven.wordpress.com/
Here is the code from above link:
public class ArrayReversing {
public static void main(String a[]){
int arr[]={ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 };
int temp;
int as = arr.length;
int k = as – 1;
System.out.println(“Array Before Reversing”);
printArray(arr);//method used to print array on screen
ArrayReverse://using loops with title
for(int i = 0; i < arr.length/2 ; i++){
temp = arr[k];// swaping
arr[k] = arr[i];
arr[i] = temp;
k–;
}
System.out.println(“Array After Reversing”);
printArray(arr); // calling the method printArray to print the elements of array
}
static void printArray(int ar[]){
PrintArray:
for(int l:ar)
System.out.println(l);
}
}
Output:
Array Before Reversing
1
2
3
4
5
6
7
8
Array After Reversing
8
7
6
5
4
3
2
1

Use a Stack. A stack reverses the elements that are added to it. A stack can be described as First In, Last Out (FILO). "Push" adds the elements to the stack and "Pop" removes them.
public static int[] num1 = {1,2,3,4,5,6};
public static Stack<Integer> stack = new Stack<Integer>();
public static void main(String[] args) {
for(int i = 0; i < num1.length; i++){
stack.push(num1[i]);
}
for(int i = 0; i < num1.length; i++){
System.out.print(stack.pop());
}
}
Output:
654321

You are swapping elements from each end of the array... and iterating to the items you've already swapped... is that enough of a hint?

You might also want to look at the ArrayUtils.reverse method.
Here is an example using that method.
I know you cannot use it in this assignment. But you should be aware of this and use it whenever possible, say in your assignments, projects.

This will work
int a[] = {1,2,3,4,5};
for (int k = 0; k < a.length/2; k++) {
int temp = a[k];
a[k] = a[a.length-(1+k)];
a[a.length-(1+k)] = temp;
}

Try this will simply work:
public class ReverseArray{
public static void main(String[] args){
int[] a ={1,2,3,4,5};
for(int i=a.length-1;i>=0;i--){
System.out.print(a[i]);
}
}
}

Related

Understanding what java code prints

Hi guys I am fairly new to this and have a question about this code. I am unsure about how the output is what it is so if someone could explain it to a beginner I'd be grateful! This is the code:
public class NewClass{
public static int[] first(int[] a) { // Array {1,2,3} is passed as an argument
int[] b = new int[a.length];
for (int i = 0; i < a.length; i++)
b[i] = a[a.length - 1 - i];
return b;
}
public static void second(int[] a) { // Use more descriptive names for you methods. If its aim is to reverse the array than call it reverseArray or something alike.
for (int i = 0; i < a.length/2; i++) { // a.length = 3, a.length/2 = 1; So this loop will run only once
int temp = a[i]; // temp = 4
a[i] = a[a.length - 1 - i]; // a[0] = a[3 - 1 - 0] (a[2]) equals a[0] = 6
a[a.length - 1 - i] = temp; // a[2] = temp equals a[2] = 4
} // Array has become {6,5,4} (So it's been reversed.)
}
public static void main(String[] args) {
int[][] matrix = {{1,2,3},{4,5,6}}; // Array of two elements, both elements refering to an other array with three elements
System.out.println(matrix.length); // This will print 2. It is a two dimensional array.
first(matrix[0]); // Calling the first method and passing the {1,2,3} array as argument. It does stuff to a copy of the array (int[] b), but the returned value is never used. Array {1,2,3} is untouched.
second(matrix[1]); // Same as with the first method
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) // You should use { }. It will make the code easier to read. Only line 25 is executed inside this nested loop
System.out.print(matrix[i][j]); // This will run 6 times (2 (outer loop) x 3 (nested loop)). It will print matrix[0][0], matrix[0][1], matrix[0][2], matrix[1][0], matrix[1][1], matrix[1][2]. Respectively 123 (next line) 456
System.out.println();
}
}
}
It outputs 2, then 1,2,3 and finally 6,5,4.
In your first function you are creating a new array. This array is returned however the value is never copied into the original. Therefore when printing the matrix the first loop will stay as 1, 2, 3. If you want this to change switch the line:
first(matrix[0]);
To:
matrix[0] = first(matrix[0]);
The second function takes the original array and loops once (since a.length is 3 and 3 / 2 = 1). During this loop it converts a[0] to a[a.length - 1 - i] or a[3 - 1 - 0]. It then switches a[a.length - 1 - i] or a[2] to temp which is a[0]. This will switch the first and last element in the array which are 6 and 4.
At first, your code is quite messy. Try to use the proper indentation (four spaces for each block). It makes the code easier to read (and you might have figured out the answer yourself).
public class NewClass{
public static int[] first(int[] a) { // Array {1,2,3} is passed as an argument
int[] b = new int[a.length];
for (int i = 0; i < a.length; i++)
b[i] = a[a.length - 1 - i];
return b;
}
public static void second(int[] a) { // Use more descriptive names for you methods. If its aim is to reverse the array than call it reverseArray or something alike.
for (int i = 0; i < a.length/2; i++) { // a.length = 3, a.length/2 = 1; So this loop will run only once
int temp = a[i]; // temp = 4
a[i] = a[a.length - 1 - i]; // a[0] = a[3 - 1 - 0] (a[2]) equals a[0] = 6
a[a.length - 1 - i] = temp; // a[2] = temp equals a[2] = 4
} // Array has become {6,5,4} (So it's been reversed.)
}
public static void main(String[] args) {
int[][] matrix = {{1,2,3},{4,5,6}}; // Array of two elements, both elements refering to an other array with three elements
System.out.println(matrix.length); // This will print 2. It is a two dimensional array.
first(matrix[0]); // Calling the first method and passing the {1,2,3} array as argument. It does stuff to a copy of the array (int[] b), but the returned value is never used. Array {1,2,3} is untouched.
second(matrix[1]); // Same as with the first method
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) // You should use { }. It will make the code easier to read. Only line 25 is executed inside this nested loop
System.out.print(matrix[i][j]); // This will run 6 times (2 (outer loop) x 3 (nested loop)). It will print matrix[0][0], matrix[0][1], matrix[0][2], matrix[1][0], matrix[1][1], matrix[1][2]. Respectively 123 (next line) 456
System.out.println();
}
}
}
It outputs 2, then 1,2,3 and finally 6,5,4.

Permutation of int[] array-adding to list

I have an algorithm to count each permutation of an int array. In this case - when I want to print these permutations - everything worked fine. But if I want to save the arrays to the arraylist, it saved the correct number of them, but it saved only the one same option. I know that the problem will be trivial, but I can't solve it. Thanks for your help.
I add to the method printArray, that it saved the printed Array to Arraylist afterwards.
Output of printArray is correct, but output of printList is like this:
1 2 3 4 5 6
(and this input is printed n!, which is correct but its only one permutation)
Here is my code:
public class Permute {
ArrayList<int[]> list;
public Permute() {
list=new ArrayList<>();
}
void printArray(int[] a) {
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
System.out.println("");
list.add(a);
}
void printList(){
for(int[] arr:list){
for(int item:arr){
System.out.print(item+" ");
}
System.out.println("");
}
}
void permute(int[] a, int k) {
if (k == a.length)
printArray(a);
else {
for (int i = k; i < a.length; i++) {
int temp = a[k];
a[k] = a[i];
a[i] = temp;
permute(a, k + 1);
temp = a[k];
a[k] = a[i];
a[i] = temp;
}
}
}
public static void main(String[] args) {
Permute p = new Permute();
int a[] = {1, 2, 3, 4, 5, 6};
p.permute(a, 0);
p.printList();
}
}
You are using the same array over and over again. You rearrange the items inside it.
It's fine when you print it. But when you come to save it in a list, what gets saved is the array reference, not the array contents.
So you enter a reference to the same object n! times into the the list. At the end of the operation, all those references still refer to the same object - and printing the list will print that same array again and again, with the most recent contents it has.
If you want to save the different contents each time, you'll need to make a copy of the array, and save that copy.
So, for example, you can use
list.add( Arrays.copyOf(a, a.length) );

How to divide a series of values in one array by a series of values in another array

I am a beginner in Java and would like to ask some help with a array problem I am having. I am trying to build a simple program that has two int type arrays with 5 integers in each array. I want to divide the length of integers in one array by the length of integers in the other array. My program seems to work to some extent, since it gives me the results of the divisions. However it also gives me the following error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at ArrayDivide.main(ArrayDivide.java:11)
Can someone tell me once going wrong? Here is my code:
public class ArrayDivide {
public static void main(String[] args) {
int arr1[]={8,4,6,8,4};
int arr2[]={2,4,2,1,2};
for (int x =0;x <arr1.length;x++){
for (int j =0;x <arr2.length;j++){
int result = arr1[x] / arr2[j];
System.out.println(result);
}
}
}
}
Divide each number of outer array (arr1) with respective number in other array(arr2)
The code is shown below. You should also put check to verify that both arrays have same length.
public static void main(String[] args) {
int arr1[]={8,4,6,8,4};
int arr2[]={2,4,2,1,2};
for (int x =0;x <arr1.length;x++){
int result = arr1[x] / arr2[x];
System.out.println(result);
}
}
Output is:
4
1
3
8
2
Divide each number of outer array(arr1) with each number in other array (arr2)
And if you want to divide each number of outer array with each number of inner array then use the below code. In your code condition is not right, it should be j <arr2.length and not x <arr2.length.
public static void main(String[] args) {
int arr1[]={8,4,6,8,4};
int arr2[]={2,4,2,1,2};
for (int i=0; i<arr1.length; i++){
for (int j =0;j<arr2.length;j++){
int result = arr1[i] / arr2[j];
System.out.println(result);
}
}
}
Change second loop to
for (int j =0;j <arr2.length;j++){
ie j <arr2.length from x <arr2.length
Loop
for (initialization; condition ;updation)
Since you dint compare j in condition part loop moves on giving you exception at the 5th index
public class ArrayDivide {
public static void main(String[] args) {
int arr1[]={8,4,6,8,4};
int arr2[]={2,4,2,1,2};
for (int x =0;x <arr1.length;x++){
int result = arr1[x] / arr2[x];
System.out.println(result);
}
}
}
ArrayIndexOutOfBoundException exceptions occurs when you try to access an item who's index is greater than the array's size.
Here in the above code :
for (int x =0 ; x < arr1.length ; x++){
for (int j =0 ; 0 < arr2.length ; j++){
int result = arr1[x] / arr2[j];
System.out.println(result);
}
}
You have x < arr2.lengh.
Suppose your arr1 length is 10 and arr2 length is 5, in this case when j ll be 6, it ll still be less than 10 and your code int result = arr1[x] / arr2[j]; ll try to access arr2[6] which ll produce an ArrayIndexOutOfBoundException.
To fix this, in the inner loop you need to check from 0 to arr2's length.
Answer :
for (int x =0;x <arr1.length;x++){
for (int j =0;x <arr2.length;j++){
int result = arr1[x] / arr2[j];
System.out.println(result);
}
}

How to Fix Spanish Numbers

What I have to do is to create a SpanishNumbers application that displays numbers 1 through 10 in Spanish. A method with an int parameter should display the Spanish word for the number passed. A loop structure in the main() method should be used to call the method ten times. The Spanish word equivalents for numbers 1 through 10 are...
1 uno 2 dos, 3 tres, 4 cuatro, 5 cinco, 6 seis, 7 siete, 8 ocho, 9 nueve, 10 diez.
I do not know why am I getting this error below
http://i.stack.imgur.com/HLIiI.png
Thanks in advanced!
import java.util.Scanner;
public class SpanishNumberss {
public static void spanishNumbers(int num) {
String[] numbers = {"uno", "dos", "tres", "cuatro", "cinco", "seis", "siete", "ocho", "nueve", "diez"};
for (int i = 1; i <= num; i++) {
System.out.println(numbers[num]);
}
}
public static void main(String args[]) {
for (int i = 1; i <= 10; i++)
spanishNumbers(i);
}
}
In Java, indexes of an array start with 0, not 1, and run through length - 1, not length.
Adjust your for loop condition in main as follows:
for (int i = 0; i < numbers.length; i++)
You'll need to adjust your other for loop similarly.
Arrays indexes are 0 based (starts from 0 not from 1) . Also you are declaring your array numbers inside the method each time is called just declare as a class variable. So take care that in your example index 0 refers to 1 (uno) and so on.
I made you an example and add 0,"cero"
public class SpanishNumberss {
private static final String[] numbers = {"cero","uno", "dos", "tres", "cuatro", "cinco", "seis", "siete", "ocho", "nueve", "diez"};
public static void spanishNumbers(int num) {
//loop here is unnecesary
System.out.println(numbers[num]);
}
public static void main(String args[]) {
//and here in main i call them from 1 to 10
for (int i = 1; i < 11; i++){
spanishNumbers(i);
}
}
}
ArrayIndexOutOfBounds means you have gone out of the boundaries of your array (in your case numbers). What you have to realize is array's are 0 index-based. So in your for loop, you really 0 - 9, not 1-10.
And an even better solution, as #rgettman has posted is to use the length property of the array. So you are not hard-coding in those magic numbers.
Arrays go from 0 to N-1
That's why you're getting that error, change your for cycle to:
for (int i = 1; i <= num; i++) {
System.out.println(numbers[num]);
}
Your problem is here:
for (int i = 1; i <= num; i++)
Arrays in Java are 0-based. So the valid indices run from 0 to array.length - 1. So an array of length 5 would have the valid indices 0, 1, 2, 3, and 4. Change your loop to the following:
for (int i = 0; i < num; i++)
This will ensure that in your loop i will only have the values from 0 to 9.
your loop should only have the values from 0 to 9:
for (int i = 0; i < num; i++)
first of all i don't think you need a loop in the spanishnumber method...
cos you already know the index of what you are looking...// that's if i understand you
so the only place you need the loop is in the main method...so your code should look like dis
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
spanishNumbers(6);
}
}
public static void spanishNumbers(int num) {
String[] numbers = {"uno", "dos", "tres", "cuatro", "cinco", "seis", "siete", "ocho", "nueve", "diez"};
System.out.println(numbers[num -1]);
}

Not all Array Elements Display When Using A Sort Method Logic

I have this code;
They both use system.out.println statements to print out the array elements. Originally I used a return statement with Arrays.toString(array) to show the array in the main method that worked fine. Now I could like to use print statements just to keep the level of complexity down. As you can see the output form sort is missing the last element in the array, this is because I am using array.length -1. however if I don't use array.length -1 I will get an .ArrayIndexOutOfBoundsException so anyone have a practical solution for this?
import java.util.Arrays;
public class SortMethod
{
static int[] array = {2,1,5,3,5};
public void sort(int[] arrays)
{
for(int i = 0;i < arrays.length - 1;i++ )
{
int store = 0;
if (arrays[i + 1 ] < arrays[i])
{
store = arrays[i];
arrays[i] = arrays[i + 1];
arrays[i + 1] = store;
}
System.out.print(arrays[i]);
}
System.out.println();
}
public void reverse (int[] arrays)
{
for (int i=arrays.length-1; i >=0; i--)
{
System.out.print(arrays[i]);
}
}
/**
* #param args
*/
public static void main(String[] args)
{
// TODO Auto-generated method stub
SortMethod sort = new SortMethod();
sort.sort(array);
sort.reverse(array);
}
}
Output;
From Sort:1235
From Reverse:55321
First of all your sorting method doesn't actually sort properly. You check values with the value immediately to its left, but what happens if you have a 4 at the end of the list?
{2,1,5,3,5,4}
would return the result:
123545
which is hardly sorted... You'll want to take every value you switch, and check it backwards as well making sure its not also smaller than the previous value. Right now you sort values to the right but never back to the left.
Also you can just do the sorting algorithm, and then iterate through the array afterwards and print the values then, rather than trying to print them in the middle of the sorting method:
public class TestCode
{
static int[] array = {2,1,5,3,5,4,9,1,99,7};
public void sort(int[] arrays)
{
for(int i = 0; i < arrays.length - 1 ;i++ )
{
int store = 0;
// Move larger values to the right
if (arrays[i] > arrays[i + 1])
{
store = arrays[i];
arrays[i] = arrays[i + 1];
arrays[i + 1] = store;
// Sort swapped smaller values to the left
for(int j = i; j > 1; j--)
{
if (arrays[j] < arrays[j - 1])
{
store = arrays[j];
arrays[j] = arrays[j - 1];
arrays[j - 1] = store;
}
}
}
}
for(int i = 0; i < array.length; i ++)
{
System.out.print(arrays[i] + " ");
}
System.out.println();
}
public void reverse (int[] arrays)
{
for (int i=arrays.length-1; i >=0; i--)
{
System.out.print(arrays[i] + " ");
}
}
/**
* #param args
*/
public static void main(String[] args)
{
// TODO Auto-generated method stub
TestCode sort = new TestCode();
sort.sort(array);
sort.reverse(array);
}
}
Gives the output:
1 1 2 3 4 5 5 7 9 99
99 9 7 5 5 4 3 2 1 1
SUMMARY:
When sorting arrays you'll need to iterate though the array array.length - 1 times to compare the values (you don't need to compare the last value with the value to its right because there isn't one).
When printing an array you need to iterate through it array.length times and print out each and every value. Your main problem is coming from trying to print out the array in your sorting algorithm which is only iterating through the array array.length - 1 times when you should probably just print the array outside of the sorting algorithm.
The last line of the public void sort(int[] arrays) function:
System.out.println();
should be
System.out.println(arrays[arrays.length - 1]);
as you want to print the hole array.
And for the record, the public void sort(int[] arrays) function does not actually sort an array. It is not what the sort should do just by one pass of checking and swapping of the neighboring elements.
For example, if the array is initialized as:
static int[] array = {2,1,5,3,5};
The resulting array of sort is: 53215, and the reversed array is 51235. Both are not the intended result.
In sort() you're iterating from 0 to arrays.length-1 (exclusive), so for arrays.length==5 variable i will take values: 0, 1, 2, 3
In reverse() you iterate from arrays.length-1 (inclusive) to 0 - i will take values: 4, 3, 2, 1, 0.
When you remove -1 part from arrays.length-1 in sort() you're getting ArrayOutOfBoundsException because you reference arrays[i + 1] which will be out of arrays range for i==4.
Change your sort method as follows :
public void sort(int[] arrays) {
// int i = 0;
for (int i = 0; i < arrays.length - 1; i++) {
int store = 0;
if (arrays[i + 1] < arrays[i]) {
store = arrays[i];
arrays[i] = arrays[i + 1];
arrays[i + 1] = store;
}
System.out.print(arrays[i]);
if (i + 1 == arrays.length - 1) {
System.out.print(arrays[i + 1]);
}
}
System.out.println();
}
Just added a new print statement
if (i + 1 == arrays.length - 1) {
System.out.print(arrays[i + 1]);
}
to print the last array element.
First of all I would like to point out that the code is incomplete. This is just half the sorting code, I can see you are trying to use bubble sort, but unfortunately the inner loop is missing.
Apart from this there is no problem in this code.
Could you just replace your sort method with the one given below? This will fix all the issues.
public void sort(int[] a){
int temp = 0;
for(int i = 0 ; i < a.length ; i++){
for(int j = 0 ; j< a.length - 1 ; j++){
if(a[j] > a[j+1]){
temp = a[j];
a[j] = a[j+1];
a[j+1]=temp;
}
}
}
printArray(a);
System.out.println();
}
public void printArray(int[] a){
for(int i = 0 ; i < a.length ; i++){
System.out.print(a[i]);
}
}
Also, I would recommend you to read about sorting techniques. You can always visit Sorting articles

Categories

Resources