Issue in swapping specific array elements - java

The following is no homework. I'm just trying to write my own permutation code. I have an idea but I have problems in writing this idea as code.
As example the input is myArray={1,2,3};
Then the output is supposed to be:
1 2 3
2 1 3
2 3 1
3 2 1
3 1 2
1 3 2
I figured out it's possible by switching the first element with second, then switch second with third (however not entirely possible, but I know I need this).
That's why my question is how can I do this in Java?
I have 1 2 3 and I want switch first element with second, so I get 2 1 3. Print this. Now I want switch second element with third, I get 2 3 1, print it. Repeat n! times where n is myArray length.
I tried to do this with the following code but it seems like I'm far away from it :(
public class Test{
public static void main(String[] args){
int[] myArray = {1,2,3};
for(int x=0; x<6; x++){
for(int i=0; i<myArray.length-1; i++){
int temp=myArray[i];
myArray[i]=myArray[i+1];
myArray[i+1]=temp;
}
for(int i=0; i<myArray.length; i++){
System.out.print(myArray[i]+" ");
}
System.out.println("");
}
}
}
Output:
2 3 1
3 1 2
1 2 3
2 3 1
3 1 2
1 2 3

I'm not sure if I understood correctly though.
public static void main(String[] args) {
int[] myArray = {1, 2, 3};
for (int i = 0; i < 6; i++) {
print(myArray);
int temp = myArray[i % myArray.length];
myArray[i % myArray.length] = myArray[(i + 1) % myArray.length];
myArray[(i + 1) % myArray.length] = temp;
}
}
private static void print(int[] array) {
for (int anArray : array) {
System.out.print(anArray + " ");
}
System.out.println("");
}
EDIT:
I noticed, there is a wrong order, so it should be better:
public static void main(String[] args) {
int[] myArray = {1, 2, 3};
for (int i = 0; i < 6; i++) {
int idx = i % (myArray.length - 1);
print(myArray);
int temp = myArray[idx];
myArray[idx] = myArray[idx + 1];
myArray[idx + 1] = temp;
}
}

Related

Attempting to create a matrix array from a file, but program returns two of the same matrix?

Okay, the goal of the program is to add together two matrices that are filled by a file. My program creates and prints the first array just fine, but when I attempt to fill and print the second one, it just fills and reprints the first one. I can justify why, but I am not sure how to go about fixing it.
Here is the file
3 4
2 1 7 -10
0 5 -3 12
1 7 -2 -5
0 1 2 3
4 5 6 7
8 9 0 1
The 3 and 4 are just to determine the rows and columns, as you'll see in the code below. So the first array/matrix is:
2 1 7 -10
0 5 -3 12
1 7 -2 -5
And the second
0 1 2 3
4 5 6 7
8 9 0 1
Here is my code:
public class Matrices {
public static int[][] readMatrix(int rows, int columns, String file) throws FileNotFoundException {
Scanner fileReader = new Scanner(new FileInputStream(file));
rows = fileReader.nextInt();
columns = fileReader.nextInt();
int[][] result = new int[rows][columns];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
result[i][j] = fileReader.nextInt();
}
}
return result;
}
public static void printMatrix(int[][] matrix) {
int rows = matrix.length;
int columns = matrix[0].length;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
}
And my driver:
public class MatricesDriver {
public static void main(String[] args)throws FileNotFoundException {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter name of file: ");
String filename = keyboard.next();
File file = new File(filename);
int rows = 0;
int columns = 0;
int[][] a = Matrices.readMatrix(rows, columns, filename);
int[][] b = Matrices.readMatrix(rows, columns, filename);
Matrices.printMatrix(a);
System.out.println();
Matrices.printMatrix(b);
}
}
The code works fine for filling and printing the first matrix, but fails to do the same on the second matrix. Here is the output:
Enter name of file:
data/MAtrices.txt
2 1 7 -10
0 5 -3 12
1 7 -2 -5
2 1 7 -10
0 5 -3 12
1 7 -2 -5
It just prints the first matrix again. How do I create the two separate matrices using the same file?
You need to make sure that each matrices is being read from the right row number. Therefore, if you keep the record of row/column number then you'll be set:
class Matrices {
private Scanner fileReader;
private int rows;
private int columns;
public Matrices(String file) throws FileNotFoundException {
this.fileReader = new Scanner(new FileInputStream(file));
rows = fileReader.nextInt();
columns = fileReader.nextInt();
}
public int[][] readMatrix() throws FileNotFoundException {
int[][] result = new int[rows][columns];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
result[i][j] = fileReader.nextInt();
}
}
return result;
}
public static void printMatrix(int[][] matrix) {
for ( int[] anArray : matrix ) {
for ( int anInt : anArray ) {
System.out.print(anInt+ " ");
}
System.out.println();
}
}
}
and main method would become:
public static void main(String[] args) throws FileNotFoundException {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter name of file: ");
String filename = keyboard.next();
Matrices matrixReader = new Matrices(filename);
int[][] a = matrixReader.readMatrix();
int[][] b = matrixReader.readMatrix();
Matrices.printMatrix(a);
System.out.println();
Matrices.printMatrix(b);
}
and the OUTPUT would be:
2 1 7 -10
0 5 -3 12
1 7 -2 -5
0 1 2 3
4 5 6 7
8 9 0 1
You have to change your read method to read and return two matrices!
Right now it keeps opening the file, reading the first entry only to return that. It shows only the first matrix because your current code simply stops instead of reading the data of the second matrix.
You could enhance your file format to include the number of matrices, too. And then you have to return an array of matrices instead of just one, simply by reading all information given in your input file.
But honestly, your code is pretty good as it is now, I would rather go with using multiple files and keeping exactly one matrix in each file.

printing a 2d array java

The program I need to write is a square 2d array made of numbers, like this
0 1 2
3 4 5
6 7 8
or this
0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
15 16 17 18 19
20 21 22 23 24
The program reads the number "d" (side of the square 2d array- above are examples of d=3 and d=5), number "n" (how many inputs there will be next) and these n inputs (eg. if n=3, the program should let me insert three numbers, like from the first example, let's say I'd choose 1 and 4 and 3. So the input looks like:
3
3
1 4 2
Then, it needs to calculate the distance between the first and second, second and third input and sum them up. That sum is then the output. Here is the program
if(b==2) {
int d=sc.nextInt();
int n=sc.nextInt();
int[][] array=new int[d][d]; //length and heigth of array
int c=0;
int manhattanDistanceSum=0;
for (int i = 0; i < n; i ++){ //for inserting values
for (int j = 0; j < n; j ++){
if (i < n){
i++;
array[i][j] = sc.nextInt();
}
else {
break;
}
for( i=0; i<array.length;i++) {
for( j=0;j<array[0].length;j++) {
array[i][j]=c; //actual locations of numbers
//numbers in array
c++;
if(manhattanDistanceSum != 0) {
int dx= c / d;
int dy= c % d;
c=Math.abs(dx) + Math.abs(dy);
manhattanDistanceSum+=c;
}
}
}
System.out.print(array[i][j]);
System.out.println();
}
}
System.out.println(manhattanDistanceSum);
}
}
}
*the b doesn't matter, it just means this is going to be a square array, so ignore it. It has nothing to do with this.
This is all I got, and need help with anything that is wrong in my code.
Thankyou
I've just cobbled together this example and tested that it works with positive and negative numbers. It might not do exactly what you want (for example, is the data in your array organised row-by-column or column-by-row) and it might not exactly format the output the way you want, but it should show you how to iterate through the array and analyse and then extract the data to produce a String which can be printed out.
Be sure to conduct your own testing (create unit tests for all cases which your application will need) as I have thrown this together in a few minutes in the hope that it would get you started. It should not be considered a finished product by any means.
public static void main(String[] args) {
int[][] data = {{0, -10734, 2}, {3, 437, 5}, {6, 733838, 8}};
System.out.println("Table:\n" + formatAsTable(data));
}
public static String formatAsTable(int[][] squareNumericArray) {
int cellSpacing = 2;
StringBuilder sb = new StringBuilder();
int squareSide = squareNumericArray.length;
int cellSize = findLargestNumericString(squareNumericArray)
+ cellSpacing;
for (int firstIndex = 0; firstIndex < squareSide; ++firstIndex) {
if (squareNumericArray[firstIndex].length != squareSide) {
throw new IllegalArgumentException(
"Array must have same size in both dimensions.");
}
for (int secondIndex = 0; secondIndex < squareSide; ++secondIndex) {
sb.append(String.format("%-" + cellSize + "d",
squareNumericArray[firstIndex][secondIndex]));
}
sb.append("\n");
}
return sb.toString();
}
private static int findLargestNumericString(int[][] squareNumericArray) {
int maxLength = 0;
for (int firstIndex = 0; firstIndex < squareNumericArray.length;
++firstIndex) {
for (int secondIndex = 0; secondIndex
< squareNumericArray[firstIndex].length; ++secondIndex) {
String numberAsString = Integer.toString(
squareNumericArray[firstIndex][secondIndex]);
if (numberAsString.length() > maxLength) {
maxLength = numberAsString.length();
}
}
}
return maxLength;
}
This code will output the following to the console:
Table:
0 -10734 6
3 437 5
6 733838 19

Write a NESTED LOOP code segment that produces this output

I know there is another thread with the same name, but the answer isn't really the one I'm looking for.
I can only use for loops. The other answer uses complex syntax like:
reverse = !reverse ? i == max : reverse;
i = reverse ? i-1 : i+1;
Can it be simpler than that?
Thanks a lot.
So, this is the output.
I can only get until 4 I don't know how to keep from there...
1
1 2
1 2 3
1 2 3 4
1 2 3
1 2
1
This is what I have so far:
public static void main(String[] args) {
// TODO Auto-generated method stub
for(int i=1;i<=4;i++) {
for(int j = 1; j <= i; j++) System.out.print(j+" ");
System.out.println("");
}
for(int i=4;i>=1;i--){
for(int j = 1; j <= i; j++) System.out.print(j+" ");
System.out.println("");
}
}
}
but my output is the following:
1
1 2
1 2 3
1 2 3 4
1 2 3 4
1 2 3
1 2
1
Hii have done using the below code
public class Test
{
public static void main(String args[]) {
int j,i;
int max=4;
int n=0;
for(i=0;i<((max*2)-1);i++)
{
if(i<max)
n++;
else
n--;
for(j=1;j<=n;j++)
{
System.out.print(j+" ");
}
System.out.println("");
}
}
}
The below is the outputYou can generalize it for any number i hope this is fine
Your two outer loops are:
for(int i=1;i<=4;i++) {
for(int i=4;i>=1;i--) {
This will generate the sequence 1, 2, 3, 4, 4, 3, 2, 1. If you want to only have one 4-length row in the output, change the second loop to:
for(int i=3;i>=1;i--) {
so that it starts from 3, instead of 4. The problem is that currently, both your outer loops generate the value 4 right after one another.

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]);
}

Reversing elements of an array

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]);
}
}
}

Categories

Resources