Scalar Multiplication - java

EDIT
The question is this: Scalar multiplication is defined as B = A * s, where B and A are equally sized matrices (2D array of numbers, in this example let's use integers) and s is a scalar value. Each element of A is multiplied to s, which is then stored in the corresponding element in matrix B.
Write a program that accepts a 4x4 matrix and a scalar value, and perform scalar multiplication, storing the result in a separate 4x4 matrix.
import java.util.*;
public class arrayExercises {
public static void main (String [] args){
//Scalar Value
Scanner sc = new Scanner (System.in);
int scalar = 0;
//Array for A
int matrix [][];
matrix = new int [4][4];
System.out.println("Enter the numbers in the 4x4 matrix");
for (int i=0; i < matrix.length; i++)
{
for (int j =0; j<matrix[i].length; j++)
matrix[i][j] = sc.nextInt();
}
System.out.println("Enter scaler value:");
scalar = sc.nextInt();
sc.close();
}
}

not giving a direct solution. giving you a hint instead.
so far from your code, you have created a matrix and withing 2 for loop you have set the values of the matrix from user input.
now to get a scalar multiplication you need to do a similar operation. create another matrix of the same size as the previous matrix. and in a similar way within 2 loop multiply each and every element of the old matrix with the scalar value and set it to the coresponding index of the new matrix.

System.out.println("Enter scaler value:");
scalar = sc.nextInt();
int scalarMatrix [][];
scalarMatrix = new int [4][4];
for (int i=0; i < scalarMatrix.length; i++)
{
for (int j =0; j<scalarMatrix[i].length; j++)
scalarMatrix[i][j] = (int)(matrix[i][j]*scalar);
}
Something along these lines should work. What you are doing is getting each result from the initial matrix and essentially copying them into the new matrix but multiplying it by the variable "scalar" as you do so.

Related

How to reduce memory:

I need to create the input graph(graph with backward edges). Ex: 1-st graph has edges from 1 to 2, from 2 to 3; input graph has edges from 3 to 2, from 2 to 1.
The problem is that I'm creating matrix (N^N memory usage). How to use less memory for this task?
import java.util.Scanner;
public class ReverseGraph{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int n = Integer.parseInt(scan.nextLine()); // number of vertices
//matrix of vertices
int[][] matrix = new int[n][n];
Scanner sc;
//create graph by input method(if A vertex associates with B vert than put "1" on B row, A column)
for(int i = 0; i < n;i++){
String line = scan.nextLine();
sc = new Scanner(line);
while(sc.hasNextInt()){
matrix[sc.nextInt() - 1][i] = 1;
}
}
scan.close();
//Begin write the input graph
System.out.println(n); //write num of vertices
//write
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
if(matrix[i][j] == 1)
System.out.print((j+1) + " ");
}
System.out.println();
}
}
}
Options for reducing the memory footprint.
An adjacency list implemented as an ArrayList<int[]> where the int[] are 2-element arrays each of which represents a link.
As above, except using a custom class with two int fields to represent a link.
As a HashMap<Integer, HashSet<Integer>> or HashMap<Integer, HashSet<Integer>> or HashMap<Integer, TreeSet<Integer>>, where each set or list represents the destinations of the links.
The equivalent to the above using Trove collection types.
All of these1 are O(L) on the number of links rather O(N^2) on the number if nodes.
1 - Apart from the variations that use TreeSet ...

Union of multiple arrays

I am using this code in order to create a certain number of arrays and fill them with certain numbers:
public void CreateVars() {
System.out.println("Enter the numbers of variables: ");
int i = s.nextInt();
int[][] var = new int[i][];
for (int j = 0; j < i; j++) {
System.out.println("Enter the number of values: ");
int p = s.nextInt();
System.out.println("Enter the numbers: ");
var[j] = new int[p];
for (int q = 0; q < p; q++) {
int n = s.nextInt();
var[j][q] = n;
}
}
}
How can I use the created arrays and do a union, for ex. A union B union C, since there is always a different number of arrays.
Thanks in advance
change your method to return the created array.
create a second method that takes the 2-dimansional array as parameter and returns a 1-dimensional array. This will to the union as I will show later
use Arrays.toString() to display the arrays content via System.out.println()
in the new method create a variable for the 1-dimensionl target array.
then loop over the first dimension of the parameter:
for(int[] subArray : parameterArray)
in that loop create a new temporary 1-dimensional array variable with the size of the current size of the target variable plus the size of the current subArray.
int[] tempArray = Arrays.copyOf(targetArray,targetArray.length+subArray.length]);
iterate over the subArray and copy the current value at the appropriate position in the temp array.
when finished the inner loop store the tempArray as targetArray
targetArray = tempArray;

How to make a matrix from scratch in java

I'm trying to make a program that will make square matrices based on user input. I know that arrays exist, but I wanted to make a matrix from scratch so that I could better understand the basic concept of it and further extend my understanding of loops. So far I have been able to make a square matrix that will accept one number as an input into that matrix, for example I input a square 2x2 matrix and while I want it to look like this 1 2 3 4 with 1 and 2 being above 3 and 4. I have only gotten it to accept one user input that it places in all four slots. For example, if my user input is 1 then the matrix looks like this 1 1
1 1
My code looks like this thus far:
int number;
System.out.println("What are the dimensions of the matrix?");
number = in.nextInt();
for (int k = 0; k < number; k = k +1)
{
System.out.println("What are the numbers in your matrix?");
int matrix_number = in.nextInt();
for (int i = 0; i < number; i = i + 1)
{
for (int j = 0; j < number; j = j + 1)
{
System.out.print(matrix_number);
}
System.out.println();
}
}
I believe that my problem lies in my first for loop where I have the user input the matrix number. Any helpful suggestions on how I can better write this so that the user can input a different number for each slot in the matrix?
It looks like you are trying to create a matrix and then populate it with values read from the user.
To create an N x N matrix of integers
int[][] matrix = new int[n][n]();
To assign a value to a matrix cell [i, j]:
matrix[i][j] = someValue;
Obviously, if you want to read a different value for each cell, you need to call nextInt() multiple times; i.e. once for each value you want to read.
(Note to other readers: I'm not coding this for the OP, because he will learn more by coding it himself.)
You can create a matrix using 2 dimensional arrays:
int[][] matrix = new int[row][column]; //row is the number of matrix rows
//column is the number of matrix columns
To access the elements of the matrix and define it after the declaration, you can use a nested for loop:
for (i = 0; i < row; i++ )
for (j = 0; j < column; j++)
{
scores[i][j] = value; // value is your chosen integer for that index
}
}
As you mention in your question, user has to input only onces and that it places in all four slots.
For example, if user input is 1 then the matrix looks like this 1 1 1 1.
Then no need for first for loop, just remove it.
int number;
System.out.println("What are the dimensions of the matrix?");
number = in.nextInt();
System.out.println("What are the numbers in your matrix?");
int matrix_number = in.nextInt();
for (int i = 0; i < number; i = i + 1)
{
for (int j = 0; j < number; j = j + 1)
{
System.out.print(matrix_number);
}
System.out.println();
}
You want the user to say the size of the square matrix, then you want the user to tell you every number in the matrix. You only need two loops here:
int number;
System.out.println("What are the dimensions of the matrix?");
number = in.nextInt();
for (int i = 0; i < number; i = i + 1)
{
for (int j = 0; j < number; j = j + 1)
{
System.out.println("What are the numbers in your matrix?");
int matrix_number = in.nextInt();
System.out.print(matrix_number);
}
System.out.println();
}
If you don't want your matrix polluted by "What are the numbers in your matrix?" questions, then you're going to need to learn how to store user input into some sort of data structure. As you said in your question, arrays are a great way to do this (as are 2d arrays).
If you were willing to learn file input or file output, then you could do what you seek without "storing" the numbers in an array. Either read the numbers in from a file and output them to the screen, or have the user type them as user input and output the matrix to a file.
Edit: You could try to erase the "What are the numbers in your matrix?" system out by printing backspace characters on linux systems. More here:
How to delete stuff printed to console by System.out.println()?

Transferring the contents of a one-dimensional array to a two-dimensional array

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

java two dimensional array sorting

Write a program that prompts the user to enter a nxn matrix of double values and displays a new matrix which has the columns of the initial matrix sorted. You may use any sorting algorithm to solve the problem; please specify the name of the used sorting algorithm into your code header. Your program must implement a sorting algorithm; you cannot use the sorting methods provided in the Array class. The sorting should be implemented into a method, in which a new array is returned and the original array is intact:
public static double[][] sortCol(double[][] a)
The program should also implement a method that prints the initial and the result matrices to user. The print out should be nicely formatted. Here is a sample run:
What is the dimension of matrix? 3
Enter a 3x3 matrix row by row:
0.15 0.875 0.375
0.55 0.005 0.225
0.30 0.12 0.4
The column sorted array is:
0.15 0.005 0.225
0.3 0.12 0.375
0.55 0.875 0.4
This is what I have. I believe it is almost perfect. The sorting method I used I think will sort the column but it may also be sorting the rows. However when I run the program I get this...
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:909)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextDouble(Scanner.java:2456)
at Hmwk3_jrgluck.main(Hmwk3_jrgluck.java:16)
Any ideas/ help..
import java.util.Scanner;
public class sdfjasdf {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("What is the dimension of your matrix?");
int matrixdim = input.nextInt();
double[][] matrix = new double[matrixdim][matrixdim];
System.out.println("Enter " + matrixdim + " rows, and " + matrixdim
+ " columns.");
Scanner input1 = new Scanner(System.in);
for (int row = 0; row < matrix.length; row++) {
for (int column = 0; column < matrix.length; column++)
matrix[row][column] = input1.nextDouble();
}
System.out.println(sortCol(matrix));
}
public static double sortCol(double[][] matrix) {
for (int i = 0; i < matrix.length; i++) {
double currentMin = matrix[i][0];
int currentMinIndex = i;
for (int j = i; j < matrix.length; j++) {
if (currentMin > matrix[j][0]
|| (currentMin == matrix[j][0] && matrix[currentMinIndex][1] > matrix[j][1])) {
currentMin = matrix[j][0];
currentMinIndex = j;
}
}
if (currentMinIndex != i) {
double temp0 = matrix[currentMinIndex][0];
double temp1 = matrix[currentMinIndex][1];
matrix[currentMinIndex][0] = matrix[i][0];
matrix[currentMinIndex][1] = matrix[i][1];
matrix[i][0] = temp0;
matrix[i][1] = temp1;
}
}
return sortCol(matrix);
}
}
I suspect that your locale can require commas instead dots in float number format. Try changing your data to
0,15 0,875 0,375
0,55 0,005 0,225
0,30 0,12 0,4
If that is true but you prefer to (or must) use dots instead of comma you can change locale used in Scanner by invoking
input.useLocale(new Locale("en", "US"));
or change global Locale before creating Scanner object with
Locale.setDefault(new Locale("en", "US"));
Also return type of sortCol should be aether
double[][] in case you want to return sorted copy of array (without changing original one). In that case you will need to first create copy of original array
void in case you want to sort original array (you don't have to return reference to object that you already have since you used it as methods argument)
Right now you are trying to return double by invoking again sortCol(matrix), so it again will try to return sortCol(matrix) (and so on) which will lead to stack overflow.

Categories

Resources