I use the JAMA.matrix package..how do i print the columns of a matrix
The easiest way would probably be to transpose the matrix, then print each row. Taking part of the example from the API:
double[][] vals = {{1.,2.,3},{4.,5.,6.},{7.,8.,10.}};
Matrix a = new Matrix(vals);
Matrix aTransposed = a.transpose();
double[][] valsTransposed = aTransposed.getArray();
// now loop through the rows of valsTransposed to print
for(int i = 0; i < valsTransposed.length; i++) {
for(int j = 0; j < valsTransposed[i].length; j++) {
System.out.print( " " + valsTransposed[i][j] );
}
}
As duffymo pointed out in a comment, it would be more efficient to bypass the transposition and just write the nested for loops to print down the columns instead of across the rows. If you need to print both ways that would result in twice as much code. That's a common enough tradeoff (speed for code size) that I leave it to you to decide.
You can invoke the getArray() method on the matrix to get a double[][] representing the elements.
Then you can loop through that array to display whatever columns/rows/elements you want.
See the API for more methods.
public static String strung(Matrix m) {
StringBuffer sb = new StringBuffer();
for (int r = 0; r < m.getRowDimension(); ++ r) {
for (int c = 0; c < m.getColumnDimension(); ++c)
sb.append(m.get(r, c)).append("\t");
sb.append("\n");
}
return sb.toString();
}
Related
I am working on a java program. where I have taken an input string and I am putting each char from a string in a 4*4 matrix. If the input string length is small than 16 i.e 4*4 matrix, then I am adding padding '#' char.
But Now, suppose the input string length is more than 16 then I want to create a new array and put remaining chars into it. I can't use a vector, set, map. So How can I code now?
here is some code. key=4.
char[][] giveMeNewArray() {
char[][] matrix = new char[key][key];
return matrix;
}
void putCharIntoMatrix() {
int counter = 0;
char[][] myArray = giveMeNewArray();
System.out.println("myArray: " + myArray);
for (int i = 0; i < key; i++) {
for (int j = 0; j < key; j++) {
if (counter >= inputString.length()) {
myArray[i][j] = '#';
} else {
myArray[i][j] = inputString.charAt(key * i + j);
}
counter++;
}
}
for (int i = 0; i < key; i++) {
for (int j = 0; j < key; j++) {
System.out.print(myArray[i][j] + " ");
}
System.out.println();
}
}
So if I'm understanding this question correctly, you want to create a matrix to hold the characters of an input string, with a minimum size of 4*4?
You're probably better off creating a proper matrix rather than expanding it:
Do you want your matrix to always be square?
Get the next-highest (self-inclusive) perfect square using Math.sqrt
int lowRoot = (int)Math.sqrt(inString.length());
int root;
if(lowRoot * lowRoot < inString.length())
root = lowRoot+1;
else
root = lowRoot;
Create your matrix scaled for your input, minimum four
int size = (root < 4) ? 4 : root;
char[][] matrix = new char[size][size];
But if you really want to expand it, you can just create a new matrix of a greater size:
char[][] newMatrix = new char[oldMatrix.length+1][oldMatrix[0].length+1];
And copy the old matrix into the new matrix
for(int i = 0; i < oldMatrix.length; ++i){
for(int j = 0; j < oldMatrix[i].length; ++j){
newMatrix[i][j] = oldMatrix[i][j];
}
}
If you expand by one each time you'll do tons of expands, if you expand by more you might expand too far.
This is really inefficient versus just doing some math at the beginning. Making a properly sized matrix from the start will save you a bunch of loops over your data and regularly having two matrices in memory.
If understand you request correctly, if the string length is bigger than 16 you just create a new array, well how about making a list of array initilized at one array and if there are more than 16 chars just add an array to the list using your method that returns an array.
so I am supposed to initialize a 10x10 matrix and fill it with different patterns such as:
........................
........................
... ... ... ... ... ...
... ... ... ... ... ...
.. .. .. .. .. ..
.. .. .. .. .. ..
. . . . . .
. . . . . .
how would I would go about controlling the number of times the . character appears in each cell. I know I can loop through the matrix and after the next even numbered row I could decrease the number of times the . character appears but how do I go about doing this.
Thanks for the update on the question. here is some code that I believe does what you are looking for.
public static String printDots(int numDots)
{
String dots = "";
for(int i = 0; i < numDots; i++)
{
dots += ".";
}
return dots;
}
public static void main(String[] args)
{
String[][] matrix = new String[10][10];
int numDots = 4;
for (int i = 0; i < matrix.length; i++)
{
for(int j = 0; j < matrix[i].length; j++)
{
matrix[i][j] = printDots(numDots);
}
if(i%2 != 0)
numDots--;
}
for(int i = 0; i < matrix.length; i++)
{
for(int j= 0; j < matrix[i].length; j++)
System.out.println(matrix[i][j]);
}
}
}
By the nature of arrays/matrices, you will probably want to use loops. In your problem, you could use one loop to traverse down rows of the matrix. To fill the columns you might use another loop. Some pseudocode might look like
for (int i = 0; i < matrix.Rows; i++) //standard indexing loop
var pattern = determinePrintingPattern(row)
print(pattern)
In your problem in particular, it looks like the printing of dots happens in 6 groups of 4, with decreasing dots every even row. So
function returnPattern determinePrintingPattern(int row) //might look like pseudocoded
for 6 iterations
print 4 - row/2 dots //integer division is desirable and will truncate (drop the decimal)
Break the problem down.
Write a method that creates a string of length length with dots dots positioned correctly within it, ie with a signature like:
String dotty(int length, int dots) {
// your code here
}
Get that working, then write a method to create an array of these Strings:
String[] dottyArray(int length, int dots, int size) {
String[] result = new String[size];
Arrays.fill(result, dotty(length, dots);
return result;
}
Then create a loop to call that method to fill a 2D array:
String[][] dottyGrid(int length, int columns, int rows) {
String[][] result = new String[rows][];
for (int row = 0; row < rows; row++)
result[row] = dottyArray(length, (rows - row / 2) / 2, columns);
return result;
}
The one small "trick" is that integer division truncated the fractional part, which neatly makes the dots amount step by 2.
I'm trying to make an encryption program where the user enters a message and then converts the "letters into numbers".
For example the user enters a ABCD as his message. The converted number would be 1 2 3 4 and the numbers are stored into a one dimensional integer array. What I want to do is be able to put it into a 2x2 matrix with the use of two dimensional arrays.
Here's a snippet of my code:
int data[] = new int[] {10,20,30,40};
*for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
for (int ctr=0; ictr<data.length(); ictr++){
a[i][j] = data[ctr];}
}
}
I know there's something wrong with the code but I am really lost.
How do I output it as the following?
10 20
30 40
(instead of just 10,20,30,40)
Here's one way of doing it. It's not the only way. Basically, for each cell in the output, you calculate the corresponding index of the initial array, then do the assignment.
int data[] = new int[] {10, 20, 30, 40, 50, 60};
int width = 3;
int height = 2;
int[][] result = new int[height][width];
for(int i = 0; i < height; i++) {
for(int j = 0; j < width; j++) {
result[i][j] = data[i * width + j];
}
}
Seems like you want to output a 2xn matrix while still having the values stored in a one-dimensional array. If that's the case then you can to this:
Assume the cardinality m of your set of values is known. Then, since you want it to be 2 rows, you calculate n=ceil(m/2), which will be the column count for your 2xn matrix. Note that if m is odd then you will only have n-1 values in your second row.
Then, for your array data (one-dimension array) which stores the values, just do
for(i=0;i<2;i++) // For each row
{
for(j=0;j<n;j++) // For each column,
// where index is baseline+j in the original one-dim array
{
System.out.print(data[i*n+j]);
}
}
But make sure you check the very last value for an odd cardinality set. Also you may want to do Integer.toString() to print the values.
Your code is close but not quite right. Specifically, your innermost loop (the one with ctr) doesn't accomplish much: it really just repeatedly sets the current a[i][j] to every value in the 1-D array, ultimately ending up with the last value in the array in every cell. Your main problem is confusion around how to work ctr into those loops.
There are two general approaches for what you are trying to do here. The general assumption I am making is that you want to pack an array of length L into an M x N 2-D array, where M x N = L exactly.
The first approach is to iterate through the 2D array, pulling the appropriate value from the 1-D array. For example (I'm using M and N for sizes below):
for (int i = 0, ctr = 0; i < M; ++ i) {
for (int j = 0; j < N; ++ j, ++ ctr) {
a[i][j] = data[ctr];
}
} // The final value of ctr would be L, since L = M * N.
Here, we use i and j as the 2-D indices, and start ctr at 0 and just increment it as we go to step through the 1-D array. This approach has another variation, which is to calculate the source index explicitly rather than using an increment, for example:
for (int i = 0; i < M; ++ i) {
for (int j = 0; j < N; ++ j) {
int ctr = i * N + j;
a[i][j] = data[ctr];
}
}
The second approach is to instead iterate through the 1-D array, and calculate the destination position in the 2-D array. Modulo and integer division can help with that:
for (int ctr = 0; ctr < L; ++ ctr) {
int i = ctr / N;
int j = ctr % N;
a[i][j] = data[ctr];
}
All of these approaches work. Some may be more convenient than others depending on your situation. Note that the two explicitly calculated approaches can be more convenient if you have to do other transformations at the same time, e.g. the last approach above would make it very easy to, say, flip your 2-D matrix horizontally.
check this solution, it works for any length of data
public class ArrayTest
{
public static void main(String[] args)
{
int data[] = new int[] {10,20,30,40,50};
int length,limit1,limit2;
length=data.length;
if(length%2==0)
{
limit1=data.length/2;
limit2=2;
}
else
{
limit1=data.length/2+1;
limit2=2;
}
int data2[][] = new int[limit1][limit2];
int ctr=0;
//stores data in 2d array
for(int i=0;i<limit1;i++)
{
for(int j=0;j<limit2;j++)
{
if(ctr<length)
{
data2[i][j] = data[ctr];
ctr++;
}
else
{
break;
}
}
}
ctr=0;
//prints data from 2d array
for(int i=0;i<limit1;i++)
{
for(int j=0;j<limit2;j++)
{
if(ctr<length)
{
System.out.println(data2[i][j]);
ctr++;
}
else
{
break;
}
}
}
}
}
I've initialized a 1d and 2d array and now I basically just want to be able to perform matrix multiplication on them. However, I'm not quite getting the proper answer. I think I've mixed up the for loop where I try to ensure I only multiply the correct values, but can't quite get the hang of it.
edit: I've fixed it, I was misunderstanding what the length method of a 2D array returned (thought it returned columns and not rows). The below code is my corrected code. Thanks everyone.
public static double[] getOutputArray(double[] array1D, double[][] array2D) {
int oneDLength = array1D.length;
int twoDLength = array2D[0].length;
double[] newArray = new double[array2D[0].length]; // create the array that will contain the result of the array multiplication
for (int i = 0; i < twoDLength; i++) { // use nested loops to multiply the two arrays together
double c = 0;
for (int j = 0; j < oneDLength; j++) {
double l = array1D[j];
double m = array2D[j][i];
c += l * m; // sum the products of each set of elements
}
newArray[i] = c;
}
return newArray; // pass newArray to the main method
} // end of getOutputArray method
There are some problems, first of all, you should decide how the vectors represented, are you multiplying from left or right.
For the maths: vector 1xn times matrix nxm will result in 1xm, while matrix mxn times nx1 result in mx1.
I think the following would work for you:
public static double[] getOutputArray(double[] array1D, double[][] array2D) {
int oneDLength = array1D.length;
int twoDLength = array2D.length;
double[] newArray = new double[twoDLength]; // create the array that will contain the result of the array multiplication
assert twoDLength >0 && array2D[0].length == oneDLength;
for (int i = 0; i < twoDLength; i++) { // use nested loops to multiply the two arrays together
double c = 0;
for (int j = 0; j < oneDLength; j++) {
double l = array1D[j];
double m = array2D[i][j];
c += l * m; // sum the products of each set of elements
}
newArray[i] = c;
}
return newArray; // pass newArray to the main method
} // end of getOutputArray method
I hope I did not make a mistake, while trying to fix.
This seems simple enough but I get the error "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at reverse.main(reverse.java:28)"
I initially take inputs from the user to write an array, and then I want to print the array backwards. I understand there are other ways of doing this, but I mainly want to know why this is not working. Going through it line by line makes sense?
PS. If it's not a problem, is there any better way of doing this?
import java.util.Scanner;
public class reverse {
/**
* #param args
*/
public static void main(String[] args) {
System.out.printf("Enter the number of values in array: ");
Scanner scanner = new Scanner(System.in);
int n;
n = scanner.nextInt();
double[] a1 = new double[n];
int i;
System.out.printf("Enter the value in the array: ");
for (i = 0; i < n; i++){
Scanner scanner2 = new Scanner(System.in);
a1[i] = scanner2.nextInt();
}
double j;
double k;
for (i = 0; i < n/2; i++){
j = a1[i];
k = a1[n-i]; //error line;
a1[i]=k;
a1[n-i]=j;
}
for(i = 0; i < n; i++){
System.out.println(" "+a1[i]);
}}
}
When i = 0, n-i will result in n, which is one larger than the available indexes( 0 -> n-1 ).
for (i = 0; i < n/2; i++){
j = a1[i];
k = a1[n-i]; //error line;
a1[i]=k;
a1[n-i]=j;
}
Collections.reverse(Arrays.asList(array))
Will reverse an array for you, then just print its values out. It's great to do these kinds of problems as exercises but if you're ever woring in the industry it's usually better to rely on the Java API for trivial things like this. Probably going to be faster and a lot more simpler than anything you can come up with.
As said by Samhain, when i = 0, then n-i == n, which is greater than the last index of the array (since arrays start with index 0).
The simplest solution is to just subtract an additional 1 from n-i.
j = a1[i];
k = a1[n-i-1];
a1[i]=k;
a1[n-i-1]=j;
Also, creating a new Scanner is totally unnecessary. Just continue to use the first one you created.
for (i = 0; i < n; i++){
a1[i] = scanner.nextInt();
}
Finally, for what it's worth, if you're using nextInt you don't need to declare your array as a double[] (nor do j and k need to be doubles). You can just use ints.
Here's it running on ideone.