import java.util.Scanner;
class Main
{
public static void main(String args[])
{
int i, j;
Scanner reader = new Scanner (System.in);
int array[][] = new int[4][4];
System.out.println("Enter Numbers: ");
for (i = 0; i < 4; i++)
for (j = 0; j < 4; j++)
array[i][j] = reader.nextInt();
System.out.println("Square: ");
for (i = 0; i < 4; i++)
{
for (j = 0; j < 4; j++)
System.out.print(array[i][j] + " ");
System.out.println();
}
}
}
I have this code written in java that asks a user for 16 numbers and then prints the numbers in a 4x4 array. I have to find the sum of each individual column and each individual row and of each individual diagonal. I am not sure how to do that.
I do not know what you are even trying to do in your code, you just input and print 4x4 array. In java arrays are fixed you can use ArrayList and other built in classes to do this in easier way. This algorithm would be a good way for variable size of inputs since 4 can be replaced by any value:
int matrixWidthHeight = 4;
int rowSum[matrixWidthHeight];
int columnSum[matrixWidthHeight];
for (int i = 0; i < matrixWidthHeight; ++i) {
for (int j = 0; j < matrixWidthHeight; ++j)
rowSum[i] += arr[i][j];
for (int j = 0; j < matrixWidthHeight; ++j)
rowSum[i] += arr[j][i];
sumDiagonal1 += arr[i][matrixWidthHeight - i]; // / diagonal sum
sumDiagonal2 += arr[matrixWidthHeight - i][i]; // \ diagonal sum
}
I do not know how Java works behind the seen, but for array size of 4 you can do:
int rowSum[4];
int columnSum[4];
for (int i = 0; i < 4; ++i) {
rowSum[i] += arr[i][0];
rowSum[i] += arr[i][1];
rowSum[i] += arr[i][2];
rowSum[i] += arr[i][3];
columnSum[i] += arr[0][i];
columnSum[i] += arr[1][i];
columnSum[i] += arr[2][i];
columnSum[i] += arr[3][i];
sumDiagonal1 += arr[i][4 - i]; // / diagonal sum
sumDiagonal2 += arr[4 - i][i]; // \ diagonal sum
}
The first one is easy to adjust for all kind of sizes, but is N^2, the second one is N, but today this does not matter for matrix of 4x4, since it is 4 * 2 * 4 (32) loop ops, vs 4 loop ops isn't a big deal for today CPUs.
You can't change the length of an array after it's initialization in java. What you can do and should do here is to copy the content of the old array into a new array with more rows/columns. The same holds true for the diagonals.
In, Java, arrays are immutable in length, which means that you can't add or remove a column or row in your case. You might want to take a look at a Collection, such as ArrayLists. Those have an implementation which allows for scaling.
You can always read a bit more about Collections here.
Related
This code is radix sort in Java.
Now I can sort. But I want to reduce its functionality if there is no change in the
array, let it stop the loop and show the value.
Where do I have to fix it? Please guide me, thanks in advance.
public class RadixSort {
void countingSort(int inputArray[], int size, int place) {
//find largest element in input array at 'place'(unit,ten's etc)
int k = ((inputArray[0] / place) % 10);
for (int i = 1; i < size; i++) {
if (k < ((inputArray[i] / place) % 10)) {
k = ((inputArray[i] / place) % 10);
}
}
//initialize the count array of size (k+1) with all elements as 0.
int count[] = new int[k + 1];
for (int i = 0; i <= k; i++) {
count[i] = 0;
}
//Count the occurrence of each element of input array based on place value
//store the count at place value in count array.
for (int i = 0; i < size; i++) {
count[((inputArray[i] / place) % 10)]++;
}
//find cumulative(increased) sum in count array
for (int i = 1; i < (k + 1); i++) {
count[i] += count[i - 1];
}
//Store the elements from input array to output array using count array.
int outputArray[] = new int[size];
for (int j = (size - 1); j >= 0; j--) {
outputArray[count[((inputArray[j] / place) % 10)] - 1] = inputArray[j];
count[(inputArray[j] / place) % 10]--;//decrease count by one.
}
for (int i = 0; i < size; i++) {
inputArray[i] = outputArray[i];//copying output array to input array.
}
System.out.println(Arrays.toString(inputArray));
}
void radixSort(int inputArray[], int size) {
//find max element of inputArray
int max = inputArray[0];
for (int i = 1; i < size; i++) {
if (max < inputArray[i]) {
max = inputArray[i];
}
}
//find number of digits in max element
int d = 0;
while (max > 0) {
d++;
max /= 10;
}
//Use counting cort d no of times
int place = 1;//unit place
for (int i = 0; i < d; i++) {
System.out.print("iteration no = "+(i+1)+" ");
countingSort(inputArray, size, place);
place *= 10;//ten's , hundred's place etc
}
}
1
I'm going to resist typing out some code for you and instead go over the concepts since this looks like homework.
If I'm understanding you correctly, your problem boils down to: "I want to check if two arrays are equivalent and if they are, break out of a loop". Lets tackle the latter part first.
In Java, you can use the keyword"
break;
to break out of a loop.
A guide for checking if two arrays are equivalent in java can be found here:
https://www.geeksforgeeks.org/compare-two-arrays-java/
Sorry if this doesnt answer your question. Im just gonna suggest a faster way to find the digits of each element. Take the log base 10 of the element and add 1.
Like this : int digits = (int) Math.log10(i)+1;
A brief explanation: With the code below it will make a randomly generated Square and some code below would make sure that it was a Magic Square, in which the sum of the elements in each row, column, and the two diagonals are the same value.
My teacher said at maximum it should take three minutes to generate a magic square. So all I ask is there anything that can be done to improve or fix this code, please?
import java.util.ArrayList;
import java.util.Random;
class Main {
public static void main(String[] args) {
int size = 9;
int N = 3;
boolean result = true;
ArrayList<Integer> list = new ArrayList<Integer>(size);
int[][] mat = new int[N][N];
while (result) {
for (int i = 1; i <= size; i++) {
list.add(i);
}
Random rand = new Random();
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
int index = rand.nextInt(list.size());
System.out.print(list.remove(index)+" ");
}
System.out.println();
}
System.out.println();
// Checking process
// sumd1 and sumd2 are the sum of the two diagonals
int sumd1 = 0, sumd2 = 0;
for (int i = 0; i < N; i++) {
// (i, i) is the diagonal from top-left -> bottom-right
// (i, N - i - 1) is the diagonal from top-right -> bottom-left
sumd1 += mat[i][i];
sumd2 += mat[i][N - 1 - i];
}
// if the two diagonal sums are unequal then it is not a magic square
if (sumd1 != sumd2)
result = false;
// calculating sums of Rows and columns and checking if they are equal to each other,as well as equal to diagonal sum or not
for (int i = 0; i < N; i++) {
int rowSum = 0, colSum = 0;
for (int j = 0; j < N; j++) {
rowSum += mat[i][j];
colSum += mat[j][i];
}
if (rowSum != colSum || colSum != sumd1)
result=false;
}
result = true;
}
}
}
Trying with random numbers to coincidentally find a solution is deadly slow.
If you have the numbers 1 to 9, its entire sum 1+2+3+...+8+9 is 9*(1+9)/2 = 45.
As you have 3 rows and 3 colums, a row and column must sum upto 45/3 = 15.
Now that should restrict the number of possibilities.
So you must build in some intelligence in the code. Avoid random numbers as they do not even guarantee you'll find a solution in hundred years.
If you already treated recursion, that would be the easiest way to try all possibly valid combinations.
If you already treated Set, a BitSet maybe might be useful for a row, column or diagonal.
If you find it hard to code walking through all possibilities, you might hold the 2 dimensional matrix in a 1 dimensional array int[N*N], and have N (rows) + N (columns) + 2 (diagonals) arrays of N indices.
And of course I will not spoil your fun and satisfaction finding a smart solution.
Work it out on paper first.
I'm trying to add all the elements together in an array that was decided through user input, Every time I run the code that I've constructed below I get a number that is obviously not the sum of the elements. What am I doing wrong?
import java.util.Scanner;
public class SumProduct
{
public static void main (String []args)
{
Scanner input = new Scanner (System.in);
int[] array1 = new int [input.nextInt()];
input = scan.nextInt();
for (int i = 0; i < array1.length; i++)
{
array1[i] = input.nextInt();
}
for (int i = 0; i < array1.length; i++)
{
int j = array1[i];
int k = array1[i]+1;
int sum = j + k;
System.out.print(sum);
}
}
}
You probably want to prompt the user to enter the size of the array if you're going to do this.This line of code is allowing whatever the user enters to be the size of your array.
int[] array1 = new int [input.nextInt()]; //this sets the size of the array through user input
scan doesn't exist in the currrent context:
input = scan.nextInt(); // this is invalid syntax as scan is not the Scanner you created
for (int i = 0; i < array1.length; i++)
{
array1[i] = input.nextInt();
}
I would do this to keep adding elements to the array:
// no need for this: input = scan.nextInt();
for (int i = 0; i < array1.length; i++)
{
System.out.println("Enter integer to add:");
array1[i] = input.nextInt();
}
This code will give you the sum of the elements if you just add one element at a time instead of two to the sum variable:
int sum = 0;
for (int i = 0; i < array1.length; i++)
{
sum += array1[i];
System.out.print(sum); // this will print out sum after each addition
}
System.out.print(sum); // this will print out sum after the entire array is summed
Adding some logic to only allow the user to enter so many numbers to the array would be helpful as well. You will need to move on from them entering data into the array at some point. Then also remember to close the scanner when you're finished getting data from the user:
input.close();
Your problem is in the following lines of code:
for (int i = 0; i < array1.length; i++)
{
int j = array1[i];
int k = array1[i]+1;
int sum = j + k;
System.out.print(sum);
}
it should look something like
int sum = 0;
for (int i = 0; i < array1.length; i++)
{
sum = sum + array1[i];
}
System.out.print(sum);
The first change is to declare the variable "sum" outside of the loop. The way it's written, it will get declared, then disappear, then declared, then disappear for every loop iteration. You also probably want to initialize it to 0
The second change is to your summation logic. Lets assume your array contains the three numbers [1, 2, 3] and walk through your logic.
j = array1[0] //(j == 1)
k = array1[0] + 1 //(k == 1 + 1 == 2)
sum = j + k //(sum == 1 + 2 == 3)
You then throw out the variable "sum" like I mentioned earlier, and start over with the same logic on the second array element, then again on the third.
i.e. j = 2, k = 2+1, sum = 2 + 2 + 1. followed by j = 3, k = 3 + 1, sum = 3 + 3 + 1.
You can probably see how this isn't the sum, and results in you logging the three digits 3, 5, and 7 for this example case.
In my updated logic, we simply loop through each element and add it to the current running total.
hope this helps
I was trying to do a 2D array program to demonstrate a TRANSPOSE but I am getting error .. here is my code.
import java.util.Scanner;
/* To demonstrate TRANSPOSE USING 2-D array */
public class Array_2ddd {
public static void main(String args[]) {
Scanner s1 = new Scanner(System.in);
int i, j;
int myArray1[][] = new int[9][9];
int myArray2[][] = new int[9][9];
for (i = 0; i < 9; i++) {
for (j = 0; j < 9; j++) {
System.out.println("Enter array from 1 to 9");
myArray1[i][j] = s1.nextInt();
System.out.print("your array is" + myArray2[i][j]);
}
}
// Transposing now...
for (i = 0; i < 9; i++) {
for (j = 0; j < 9; j++) {
myArray2[i][j] = myArray1[j][i];
}
}
// After transposing
for (i = 0; i < 9; i++) {
for (j = 0; j < 9; j++) {
System.out.print("Your array is as follow" + myArray2[i][j]);
}
}
}
}
EDIT: My error during runtime (Solved)
EDIT 2: Solved
EDIT 3: The loop is in infinity ..it keeps on asking for values fromt the user even when i wrote i<9 and j<9..it still keeps on asking for values till infinity..
There are several errors in your code, also it is recommend that the dimensions of the array is to be declared as a final int, so your code works for all matrix sizes and that debugging is easier. In your original code, the errors are:
At the input step, you are printing one element of myArray[2] before you perform the transpose. That means, you are getting your array is0.
In the section commented "After transposing", you are outputting your array wrong. Namely, for each entry, you call System.out.print("Your array is as follow" + myArray2[i][j]);, and that you forgot to add a new line after each row (when inner loop is finished).
"..it keeps on asking for values fromt the user even when i wrote i<9 and j<9..it still keeps on asking for values till infinity.." There are 81 entries for the 9-by-9 case and you did not output which i,j index to be applied. You probably mistaken an infinite loop with a long but terminating loop.
Your transpose step is good.
Here is a refined version of your code which allows you to input array (in reading order, or more technically, row-major order), create a transposed array. You can copy and compare your current code with this code directly to test it.
public static void main(String args[]) {
final int m = 9; // Rows
final int n = 9; // Columns
Scanner s1 = new Scanner(System.in);
int i, j;
int myArray1[][] = new int[m][n]; // Original array, m rows n cols
int myArray2[][] = new int[n][m]; // Transposed array, n rows m cols
// Input
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
// Should be only prompt.
// Improved to show which entry will be affected.
System.out.printf("[%d][%d]" + "Enter array from 1 to 9\n", i, j);
myArray1[i][j] = s1.nextInt();
}
}
// Transposing now (watch for the ordering of m, n in loops)...
for (i = 0; i < n; i++)
{
for (j = 0; j < m; j++)
{
myArray2[i][j] = myArray1[j][i];
}
}
// After transposing, output
System.out.print("Your array is:\n");
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
System.out.print(myArray1[i][j] + " ");
}
System.out.println(); // New line after row is finished
}
System.out.print("Your transposed array is:\n");
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {
System.out.print(myArray2[i][j] + " ");
}
System.out.println();
}
s1.close();
}
For an array with three rows (m = 3) and four columns (n = 4), I inputted the numbers from 0 to 9, and then 0, 1, 2. As expected, the output should be:
Your array is:
0 1 2 3
4 5 6 7
8 9 0 1
Your transposed array is:
0 4 8
1 5 9
2 6 0
3 7 1
You define your matrix as 9x9
int myArray1[][] = new int[9][9];
But actually you want to insert 10x10 items:
for (i = 0; i <= 9; i++)
{
for (j = 0; j <= 9; j++)
So either:
Redefine your arrays to store 10x10 items
int myArray1[][] = new int[10][10];
Only read and store 9x9 items in your defined array
for (i = 0; i < 9; i++) {
for (j = 0; j < 9; j++)
You haven't close your first outer for loop i.e in line 17 and change your array size to 10,as you wanted take 10 input (for 0 to 9 = 10 values).
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?