Multi-dimensional array, fill the matrix by numbers - java

So I am completely stumped. I need to create a multi-dimensional array n×n and have it be filled in a particular way. I have been able to create the 2d array per n×n but have no idea how to fill it. Below I have included the task worded exactly as given to me:
Given the number n, not greater than 100. Create the matrix of size n×n and fill it by the following rule. Numbers 0 should be stored on the primary diagonal. The two diagonals, adjacent to the primary one, should contain numbers 1. The next two diagonals - numbers 2, etc.
Sample Input 1:
5
Sample Output 1:
0 1 2 3 4
1 0 1 2 3
2 1 0 1 2
3 2 1 0 1
4 3 2 1 0
Here is my code so far. Any direction would be GREAT!!
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int[][] array = new int[n][n];
for (int i = 0; i < array.length; i++) {
System.out.println(Arrays.toString(array[i]));
}
}
}

import java.util.Arrays;
import java.util.Scanner;
public class FillTheMatrixByTheNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
scanner.close();
int[][] matrix = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
matrix[i][j] = Math.abs(j - i);
}
}
for (int i = 0; i < n; i++) {
String str = Arrays.toString(matrix[i]);
str = str.replace("[", "")
.replace(",", "")
.replace("]", "");
System.out.println(str);
}
}
}

Here's how I would approach your problem:
I would use nested for loops, one to iterate over the rows, and one to iterate over the columns. In my example, i is iterating over rows, and j is iterating over columns. Now that I know I'm hitting each cell of the matrix once and only once, I just have to figure out a way to calculate the cell's value from i and j. In this case, the cell's value is the column number minus the row number, or j - i, except there's no negatives, which can easily be solved with an absolute value (Math.abs(int)). Below is how I would do it:
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int[][] array = new int[n][n];
for (int i = 0; i < n; i++) { //iterate over rows
for (int j = 0; j < n; j++) { //iterate over columns
array[i][j] = Math.abs(j - i); //calculate cell's value
}
}
for (int i = 0; i < n; i++) {
System.out.println(Arrays.toString(array[i]));
}
}
}

import java.util.Scanner;
class Main {
public static void main(String[] args) {
// put your code here
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int[][] array = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
array[i][j] = Math.abs(j - i);
System.out.print(array[i][j] + " ");
}
System.out.println("");
}
}
}

You can subtract a column index from a row index or vice versa and take abs value from a result. This way you get a cell value:
int n = 5;
int[][] arr = IntStream.range(0, n)
.mapToObj(i -> IntStream.range(0, n)
.map(j -> Math.abs(i - j))
.toArray())
.toArray(int[][]::new);
// output
Arrays.stream(arr).map(Arrays::toString).forEach(System.out::println);
[0, 1, 2, 3, 4]
[1, 0, 1, 2, 3]
[2, 1, 0, 1, 2]
[3, 2, 1, 0, 1]
[4, 3, 2, 1, 0]

Related

Product of array in a new array except the current index value

Given an array of integers, create a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i.
For example, if our input was [1, 2, 3, 4, 5], the expected output would be [120, 60, 40, 30, 24]. If our input was [3, 2, 1], the expected output would be [2, 3, 6].
Note: Do not use division.
import java.util.Scanner;
public class Productofarray {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int prod = 1, i, j = 0;
System.out.println("How many values do you want to enter");
int n = sc.nextInt();
int a[] = new int[n];
int a2[] = new int[n];
System.out.println("Input " + n + " values:");
for (i = 0; i < n; i++) {
a[i] = sc.nextInt();
}
for (i = 0; i < n; i++) {
inner:
while (j < n) {
if (a[j] == a[i]) {
j++;
continue inner;
}
prod *= a[j];
}
a2[i] = prod;
System.out.println(a2[i]);
}
}
}
I have written this code but the problem is that it is keep on running and it never ends can someone help me what I am doing wrong here.
This should get you closer; as pointed out by Maneesh's answer, you're not checking that you're at the current index i.e i == j instead of a[i]==a[j]. you also do not need the label and it is suggested that you avoid them completely.
for(int i=0; i<n; i++)
{
// this loop can be replaced with a stream.reduce - however that seems to require copying a1 in place to remove the element at index i first as reduce doesn't seem to pass the current index.
for(int j = 0; j < n; j++) {
if(j i) continue;
a2[i] *= a1[j];
}
System.out.println(a2[i]);
}
it took me a second to figure it out but here's a example using the Java 8 Stream APIs:
for(int i=0; i<n; i++) // for i -> n
{
final int currentIndex = i;
a2[i] = IntStream.range(0, a1.length)
.filter(index -> index != currentIndex) // ingore the curent index
.map(index -> a1[index]) // map the remaining indecies to the values
.reduce((subTotal, current) -> subTotal * current); // reduce to a single int through multiplication.
}
System.out.println(a2[i]);
I haven't tested it but it should work (maybe with a tweak or two). The. gist of it is making a new array (IntStream.range) that contains every element of the given array but the one at currentIndex (.filter().map()) and then multiply the elements (reduce(... subTotal * current)). Note that this solution creates a new array for every iteration through the for loop which, with extremely large arrays, is memory-inefficient.
because you are not incrementing j when i!=j. also, you should check for i==j not a[i]==a[j].

Fill 2D array square and print in specific patterns

Ive been working on this assignment question for about 4 days now and I'm about to go crazy. We have specific directions to follow for this code;
"Your program should proceed as follows:
Display a welcome message.
Prompt the user for an integer which is 3. If the number entered is < 3. keep prompting the user until they enter a number 3 (use a do/while). This number will determine the size of the square array.
Fill the array as per pattern 1 and display it using printf to format the array.
Fill the same array as per pattern 2 and display it using printf t0 format the array.
Display a closing message."
Pattern:
I'm still stuck on pattern one. I tried to do first do a for loop which in it there's an if statement that checks if the column number is even or not, if it is, to print out the code backwards. The question also recommends using a while loop and a do/while loop...?
Also any tips on to how to go about the second patterns.
Here is my code.
import java.util.Scanner;
public class a3q33
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
int n;
do
{
System.out.println("How many rows/columns do you want your array to have? (Must be at least 3)");
n=keyboard.nextInt();
} while(n < 3);
int [][] arr = new int [n][n];
int i, j, k=1;
for(i=0;i<n;i++)
{
if(i % 2 != 0)
{
for(j=n;j>0;j--)
{
k = k+n;
arr[i][j]=k;
k--;
}
}
else
{
for(j=0;j<n;j++)
{
arr[i][j]=k;
k++;
}
}
}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
System.out.printf(arr[i][j]+" ");
}
System.out.printf("");
System.out.println();
}
}
}
Any help would be greatly appreciated!
I assume that you meant "row" instead of "column" for the condition check given that the convention is arr[row][column]?
Also, the for loop in your code:
for(j=n;j>0;j--)
This will decrement the row/column index down to 1 and not 0. So you will miss one element at arr[0][...] or arr[...][0].
Also, j=n will be out of bound.
Instead, try using:
for(j=n-1;j>-1;j--)
It would be a good first steps to look into.
import java.util.Scanner;
public class a3q33{
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
int n;
do{
System.out.println("How many rows/columns do you want your array to have? (Must be at least 3)");
n=keyboard.nextInt();
} while(n < 3);
int count = 1;
int [][] arr = new int [n][n];
for(int i = 0;i<n; i++){
if(i%2==0){
for(int j = 0;j<n; j++){
arr [i][j] = count;
count++;
}
}
else{
for(int j = n-1;j>=0; j--){
arr [i][j] = count;
count++;
}
}
}
System.out.println("\nPattern 1 \n");
// print the array
for (int i = 0; i < n; i++){
for (int j = 0; j < n; j++){
System.out.printf("%d\t",arr[i][j]);
}
System.out.println();
}
// reset count back to 1 and fill the array in the same way only without the if/else
// for n = 5 for example this will produce [1, 2, 3, 4, 5 ]
// [6, 7, 8, 9, 10]
// [11,12, 13, 14, 15]
// [16,17, 18, 19, 20]
// [21,22, 23, 24, 25]
count = 1;
for(int i = 0;i<n; i++){
for(int j = 0;j<n; j++){
arr [i][j] = count;
count++;
}
}
// rotate arrays using arraycopy; for array at index 1 rotate by one, at index 2 by 2 and so on see
//http://stackoverflow.com/questions/31174840/how-to-rotate-an-array
//
for (int i = 1; i<n; i++){
int [] temp = new int [n];
for (int j = 0; j < n; j++) {
temp[(j + i) % n] = arr[i][j];
}
System.arraycopy(temp, 0, arr[i], 0, n);
arr[i]=temp;
}
System.out.println("\nPattern 2 \n");
// print the array
for (int i = 0; i < n; i++){
for (int j = 0; j < n; j++){
System.out.printf("%d\t",arr[i][j]);
}
System.out.println();
}
}
}
You can achieve this by checking the modulo:
for (int i = 0; i < n; i++) {
int start = i * n;
for (int j = 0; j < n; j++) {
arr[i][j] = i * n + ((i % 2 === 0) ? (j + 1) : (n - j));
}
}

Java - how to stop nested loops from checking same indices twice?

Given an array and a number N call a pair of numbers from the array a Perfect Pair if their sum is equal to N.
Find all of the perfect pairs and return the sum of their indices. Note that any element of the array can only be counted in one Perfect Pair.
Examples
pairwise([1, 4, 2, 3, 0, 5], 7) = 11
Since the Perfect Pairs are (4, 3) and (2, 5) with indices 1 + 3 + 2 + 5 = 11.
pairwise([1, 3, 2, 4], 4) = 1
Since the element at index 0 (i.e. 1) and the element at index 1 (i.e. 3) form the only Perfect Pair.
Input 1 (arr) → array.integer :
array of non-negative integers
Input 2 (N) → integer :
positive integer
Output → integer :
sum of indices and 0 if no Perfect Pair exists
My Code:
public static void main(String[] args) {
int x[] = {1,4,2,3,0,5};
System.out.println(pairwise(x, 7));
}
public static int pairwise(int[] arr, int N) {
int t=0;
for(int i=0;i<arr.length;i++){
for(int k=0;k<arr.length;k++){
if(arr[i]+arr[k] == N){
t+=i+k;
}
}
}
return t;
}
The problem is my code checks indices twice, like (0,1) and (1,0) are treated like different indices.
The simplest options is to not check these in the first place. I assume i == k is not valid so you don't want to check k < i either.
public static void main(String[] args) {
int x[] = {1, 4, 2, 3, 0, 5};
System.out.println(pairwise(x, 7));
}
public static int pairwise(int[] arr, int N) {
int t = 0;
for (int i = 0; i < arr.length - 1; i++) {
for (int k = i + 1; k < arr.length; k++) {
if (arr[i] + arr[k] == N) {
t += i + k;
arr[i] = arr[k] = Integer.MIN_VALUE; // don't use these again
continue;
}
}
}
return t;
}
prints
11
This ensures you won't go over the same numbers twice.
Note: this is an O(n^2) approach, if you have more numbers you will want an O(n) approach which means using a set or map of numbers.
// O(n)
Map<Integer, Integer> intToIndex = new HashMap<>();
for(int i = 0; i < arr.length; i++)
intToIndex.put(arr[i], i);
// O(n)
for(int i = 0; i < arr.length; i++) {
int numberToLookFor = N - arr[i];
Integer k = intToIndex.get(numberToLookFor);
if (k != null) {
assert arr[i] + arr[k] == N;
// do something with i and k
}
}
Start the second loop from i, not 0.
for(int i = 0; i < 10; i++)
{
for(int j = i; j < 10; j ++)
{
System.out.println("(" + i + "," + j + ")");
}
}
Output:
I reduced `10` to `4`.
(0,0)
(0,1)
(0,2)
(0,3)
(0,4)
(1,1)
(1,2)
(1,3)
(1,4)
(2,2)
(2,3)
(2,4)
(3,3)
(3,4)
(4,4)

Adding the columns of a jagged 2D array

I've looked all over for a good answer, but I was surprised I couldn't find one that accomplished quite what I'm trying to do. I want to create a method that finds a columns sum in a jagged 2D array, regardless of the size, whether it's jagged, etc. Here is my code:
public static int addColumn(int[][] arr, int x) {
int columnSum = 0;
int i = 0;
int j = 0;
int numRows = arr.length;
//add column values to find sum
while (i < numRows) {
while (j < arr.length) {
columnSum = columnSum + arr[i][x];
j++;
i++;
}
}//end while loop
return columSum;
}
So, for example, consider I have the following array:
int[][] arr = {{10, 12, 3}, {4, 5, 6, 8}, {7, 8}};
I want to be able to pass x as 2, and find the sum for Column 3 which would be 9. Or pass x as 3 to find Column 4, which would simply be 8. My code is flawed as I have it now, and I've tried about a hundred things to make it work. This is a homework assignment, so I'm looking for help to understand the logic. I of course keep getting an Out of Bounds Exception when I run the method. I think I'm overthinking it at this point since I don't think this should be too complicated. Can anyone help me out?
I think that your second while loop is making your sum too big. You should only have to iterate over the rows.
while (i < numRows) {
if (x < arr[i].length) {
columnSum += arr[i][x];
}
++i;
}
In Java 8, you can use IntStream for this purpose:
public static int addColumn(int[][] arr, int x) {
// negative column index is passed
if (x < 0) return 0;
// iteration over the rows of a 2d array
return Arrays.stream(arr)
// value in the column, if exists, otherwise 0
.mapToInt(row -> x < row.length ? row[x] : 0)
// sum of the values in the column
.sum();
}
public static void main(String[] args) {
int[][] arr = {{10, 12, 3}, {4, 5, 6, 8}, {7, 8}};
System.out.println(addColumn(arr, 2)); // 9
System.out.println(addColumn(arr, 3)); // 8
System.out.println(addColumn(arr, 4)); // 0
System.out.println(addColumn(arr, -1));// 0
}
I saw the codes above. None of it is the adequate answer since posting here the code which meets the requirement. Code might not look arranged or optimized just because of the lack of time. Thanks.... :)
package LearningJava;
import java.util.Scanner;
public class JaggedSum {
public static void main(String[] args) {
int ik = 0;
int ij = 0;
Scanner scan = new Scanner(System.in);
int p = 0;
int q = 0;
int[][] arr = new int[2][];
System.out.println("Enter the value of column in Row 0 ");
p = scan.nextInt();
System.out.println("Enter the value of column in Row 1 ");
q = scan.nextInt();
arr[0] = new int[p];
arr[1] = new int[q];
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
arr[i][j] = scan.nextInt();
}
}
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
if (arr[1].length > arr[0].length) {
int[] columnSum = new int[arr[1].length];
int x;
for (x = 0; x < arr[0].length; x++) {
columnSum[x] = arr[0][x] + arr[1][x];
System.out.println(columnSum[x]);
}
ik = arr[0].length;
for (int j = ik; j < arr[1].length; j++) {
columnSum[j] = arr[1][j];
System.out.println(columnSum[j]);
}
} else {
int[] columnSum = new int[arr[0].length];
int x;
for (x = 0; x < arr[1].length; x++) {
columnSum[x] = arr[0][x] + arr[1][x];
System.out.println(columnSum[x]);
}
ij = arr[1].length;
for (int j = ij; j < arr[0].length; j++) {
columnSum[j] = arr[0][j];
System.out.println(columnSum[j]);
}
}
}
}

Displaying the contents of an arrayList<int[]>

The program below generates 10 pairs of random numbers of a certain size and stores them in an ArrayList named test -
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Random;
public class randomGenerate
{
static ArrayList<String> tcase=new ArrayList<String>();
static ArrayList<int[]> test=new ArrayList<int[]>();
public static void main(String args[])
{
tcase.add("1");
tcase.add("2");
tcase.add("3");
tcase.add("4");
tcase.add("5");
tcase.add("6");
randomSelection(10,2);
for(int i=0;i<test.size();i++)
{
System.out.println(Arrays.toString(test.get(i)));
}
}
static int randomNo(int max,int min)
{
Random obj = new Random();
int n = max - min + 1;
int i = obj.nextInt(n);
int randomNum = min + i;
return randomNum;
}
static void randomSelection(int limit, int pairSize)
{
int max = Integer.parseInt(Collections.max(tcase));
int min = Integer.parseInt(Collections.min(tcase));
System.out.println(max+" "+min);
int ar[]=new int[pairSize];
for(int i = 0;i < limit;i++)
{
for(int j = 0;j < pairSize;j++)
{
ar[j]=randomNo(max,min);
System.out.print(ar[j]);
}
test.add(ar);
System.out.println();
}
}
}
My problem is that while printing the contents of the arrayList "test" only the last value is displayed. Why is it not displaying all the values.
output - (for example)
23
65
45
63
12
23
52
52
16
12
[1, 2]
[1, 2]
[1, 2]
[1, 2]
[1, 2]
[1, 2]
[1, 2]
[1, 2]
[1, 2]
[1, 2]
You're always modifying and adding the same array to the list at each iteration.
Think of a situation like this :
You need to create a new array at each iteration :
for(int i = 0;i < limit;i++){
int ar[]=new int[pairSize]; //create a new one at each iteration
for(int j = 0;j < pairSize;j++){
ar[j]=randomNo(max,min);
System.out.print(ar[j]);
}
test.add(ar);
System.out.println();
}
The problem is that you are adding the array ar to the ArrayList test each iteration in randomSelection(), so when you modify ar in the next iteration, you are modifying it inside the ArrayList, to solve this try:
Way 1:
Create a new array each iteration
int ar[];
for (int i = 0; i < limit; i++) {
ar = new int[pairSize]; // Initialize inside 'for'
for (int j = 0; j < pairSize; j++) {
ar[j] = randomNo(max, min);
System.out.print(ar[j]);
}
test.add(ar);
}
Way 2:
Create a copy of the array ar and add it to test:
int ar[] = new int[pairSize];
for (int i = 0; i < limit; i++) {
for (int j = 0; j < pairSize; j++) {
ar[j] = randomNo(max, min);
System.out.print(ar[j]);
}
test.add(ar.clone()); // Create a copy
}

Categories

Resources