I want to print the following pattern in java:
a+1357+1
b+246+2
a+13+3
b+2+4
following is my code, but with this i can only print odd no. or only even no.s
public static void main(String[] args) {
int rows = 7;
for(int i = rows; i >= 1; i=i-2) {
for(int j = 1; j <= i; j=j+2) {
System.out.print(j + " ");
}
System.out.println();
}
}
DEMO
var rows = 4;
for (var i = 4; i > 0; i--) {
for (var j = 1; j <= i; j++) {
document.write((i % 2) + (2 * j) - 1 + " ");
}
document.write('<br>');
}
public static void main(String[] args) {
int rows = 4;
for(int i = rows; i > 0; i--) {
for(int j = 1; j <= i; j++) {
System.out.print((i%2)+(2*j)-1 + " ");
}
System.out.println();
}
}
You need to make a pattern for it. here you can use (i%2)+(2*j)-1
With only a few updates of your code (but not very readable):
int rows = 7;
for (int i = rows; i >= 1; i = i - 2) {
System.out.print((((i + 1) % 4) == 0 ? "a" : "b") + " + ");
for (int j = 1; j <= i; j = j + 2) {
System.out.print((j + ((i + 2) % 4) / 2));
}
System.out.println(" + " + (10 - i) / 2);
}
But instead of using my code, I suggest you write down exactly how the "pattern" is defined and write new code based on your specification. These loops are not optimal.
I am working on a problem where I've to print the largest sum among all the hourglasses in the array. You can find the details about the problem here-
What I tried:
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int arr[][] = new int[6][6];
for (int arr_i = 0; arr_i < 6; arr_i++) {
for (int arr_j = 0; arr_j < 6; arr_j++) {
arr[arr_i][arr_j] = in.nextInt();
}
}
int sum = 0;
int tmp_sum = 0;
for (int arr_i = 0; arr_i < 4; arr_i++) {
for (int arr_j = 0; arr_j < 4; arr_j++) {
if (arr[arr_i][arr_j] > 0) {
sum = sum + (arr[arr_i][arr_j]) + (arr[arr_i][arr_j + 1]) + (arr[arr_i][arr_j + 2]);
sum = sum + (arr[arr_i + 1][arr_j + 1]);
sum = sum + (arr[arr_i + 2][arr_j]) + (arr[arr_i + 2][arr_j + 1]) + (arr[arr_i + 2][arr_j + 2]);
if (tmp_sum < sum) {
tmp_sum = sum;
}
sum = 0;
}
}
}
System.out.println(tmp_sum);
}
}
Input:
1 1 1 0 0 0
0 1 0 0 0 0
1 1 1 0 0 0
0 9 2 -4 -4 0
0 0 0 -2 0 0
0 0 -1 -2 -4 0
Output:
12
Expected Output:
13
Screenshot:
I don't know where I'm doing wrong. I cannot understand why the expected output is 13. According to the description given in the problem it should be 10. Is this a wrong question or my understanding about this is wrong?
Remove the if (arr[arr_i][arr_j] > 0) statement. It prevents finding the answer at row 1, column 0, because that cell is 0.
Comments for other improvements to your code:
What if the best hourglass sum is -4? You should initialize tmp_sum to Integer.MIN_VALUE. And name it maxSum, to better describe it's purpose.
You shouldn't define sum outside the loop. Declare it when it is first assigned, then you don't have to reset it to 0 afterwards.
Your iterators should be just i and j. Those are standard names for integer iterators, and keeps code ... cleaner.
If you prefer longer names, use row and col, since that is what they represent.
You don't need parenthesis around the array lookups.
For clarity, I formatted the code below to show the hourglass shape in the array lookups.
Scanner in = new Scanner(System.in);
int arr[][] = new int[6][6];
for (int i = 0; i < 6; i++){
for (int j = 0; j < 6; j++){
arr[i][j] = in.nextInt();
}
}
int maxSum = Integer.MIN_VALUE;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
int sum = arr[i ][j] + arr[i ][j + 1] + arr[i ][j + 2]
+ arr[i + 1][j + 1]
+ arr[i + 2][j] + arr[i + 2][j + 1] + arr[i + 2][j + 2];
if (maxSum < sum) {
maxSum = sum;
}
}
}
System.out.println(maxSum);
This was my solution. I wrapped an if statement around the code that calculates the sum, that makes sure we don't go out of bounds.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int arr[][] = new int[6][6];
int max = Integer.MIN_VALUE;
int tempMax = 0;
for(int i=0; i < 6; i++){
for(int j=0; j < 6; j++){
arr[i][j] = in.nextInt();
}
}
for(int i=0; i < 6; i++){
for(int j=0; j < 6; j++){
if (i + 2 < 6 && j + 2 < 6) {
tempMax += arr[i][j] + arr[i][j + 1] + arr[i][j + 2];
tempMax += arr[i + 1][j + 1];
tempMax += arr[i + 2][j] + arr[i + 2][j + 1] + arr[i + 2][j + 2];
if (max < tempMax) {
max = tempMax;
}
tempMax = 0;
}
}
}
System.out.println(max);
}
Here's the simple and easy to understand C# equivalent code for your hourglass problem.
class Class1
{
static int[][] CreateHourGlassForIndex(int p, int q, int[][] arr)
{
int[][] hourGlass = new int[3][];
int x = 0, y = 0;
for (int i = p; i <= p + 2; i++)
{
hourGlass[x] = new int[3];
int[] temp = new int[3];
int k = 0;
for (int j = q; j <= q + 2; j++)
{
temp[k] = arr[i][j];
k++;
}
hourGlass[x] = temp;
x++;
}
return hourGlass;
}
static int findSumOfEachHourGlass(int[][] arr)
{
int sum = 0;
for (int i = 0; i < arr.Length; i++)
{
for (int j = 0; j < arr.Length; j++)
{
if (!((i == 1 && j == 0) || (i == 1 && j == 2)))
sum += arr[i][j];
}
}
return sum;
}
static void Main(string[] args)
{
int[][] arr = new int[6][];
for (int arr_i = 0; arr_i < 6; arr_i++)
{
string[] arr_temp = Console.ReadLine().Split(' ');
arr[arr_i] = Array.ConvertAll(arr_temp, Int32.Parse);
}
int[] sum = new int[16];
int k = 0;
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
int[][] hourGlass = CreateHourGlassForIndex(i, j, arr);
sum[k] = findSumOfEachHourGlass(hourGlass);
k++;
}
}
//max in sum array
Console.WriteLine(sum.Max());
}
}
Happy Coding.
Thanks,
Ankit Bajpai
You can try this code:
I think this will be easy to understand for beginners.
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int arr[][] = new int[6][6];
for(int arr_i=0; arr_i < 6; arr_i++){
for(int arr_j=0; arr_j < 6; arr_j++){
arr[arr_i][arr_j] = in.nextInt();
}
}
int sum = 0;
int sum2 = 0;
int sum3 = 0;
int x = 0;
int max = Integer.MIN_VALUE;
for(int i = 0; i < 4; i++){
for(int j = 0; j < 4; j++){
for(int k = 0; k < 3; k++){
sum += arr[i][j+k]; //top elements of hour glass
sum2 += arr[i+2][j+k]; //bottom elements of hour glass
sum3 = arr[i+1][j+1]; //middle elements of hour glass
x = sum + sum2 + sum3; //add all elements of hour glass
}
if(max < x){
max = x;
}
sum = 0;
sum2 = 0;
sum3 = 0;
x = 0;
}
}
System.out.println(max);
}
}
Here is another easy option, hope it helps:
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int a[][] = new int[6][6];
for(int i=0; i < 6; i++){
for(int j=0; j < 6; j++){
a[i][j] = in.nextInt();
}
}
int hg = Integer.MIN_VALUE, sum;
for(int i=0; i<4; i++){
for(int j=0; j<4; j++){
sum = 0;
sum = sum + a[i][j] + a[i][j+1] + a[i][j+2];
sum = sum + a[i+1][j+1];
sum = sum + a[i+2][j] + a[i+2][j+1] + a[i+2][j+2];
if(sum>hg)
hg = sum;
}
}
System.out.println(hg);
in.close();
}
}
there is another opetion in case of -(minus) and zero output we can use shorted ser Treeset for the same . below is the sameple code
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int arr[][] = new int[6][6];
for(int i=0; i < 6; i++){
for(int j=0; j < 6; j++){
arr[i][j] = in.nextInt();
}
}
int sum=0;int output=0;
Set<Integer> set=new TreeSet<Integer>();
for(int k=0;k<4;k++ )
{
for(int y=0;y<4;y++)
{
sum=arr[k][y]+arr[k][y+1]+arr[k][y+2]+arr[k+1][y+1]+arr[k+2][y]+arr[k+2][y+1]+arr[k+2][y+2]; set.add(sum);
}
}
int p=0;
for(int u:set)
{
p++;
if(p==set.size())
output=u;
}
System.out.println(output);
}
}
Solved in PHP, may be helpful.
<?php
$handle = fopen ("php://stdin","r");
$input = [];
while(!feof($handle))
{
$temp = fgets($handle);
$input[] = explode(" ",$temp);
}
$maxSum = PHP_INT_MIN;
for($i=0; $i<4; $i++)
{
for($j=0; $j<4; $j++)
{
$sum = $input[$i][$j] + $input[$i][$j + 1] + $input[$i][$j + 2]
+ $input[$i + 1][$j + 1] +
$input[$i + 2][$j] + $input[$i + 2][$j + 1] + $input[$i + 2][$j + 2];
if($sum > $maxSum)
{
$maxSum = $sum;
}
}
}
echo $maxSum;
?>
Passes all test cases
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
int rowSize = 6;
int colSize = 6;
int[][] array = new int[rowSize][colSize];
for(int row = 0; row < rowSize; row++) {
for(int col = 0; col < colSize; col++) {
array[row][col] = read.nextInt();
}
}
read.close();
int max = Integer.MIN_VALUE;
for(int row = 0; row < 4; row++) {
for(int col = 0; col < 4; col++) {
int sum = calculateHourglassSum(array, row, col);
if(sum > max) {
max = sum;
}
}
}
System.out.println(max);
}
private static int calculateHourglassSum(int[][] array, int rowIndex, int colIndex) {
int sum = 0;
for(int row = rowIndex; row < rowIndex + 3; row++) {
for(int col = colIndex; col < colIndex + 3; col++) {
if(row == rowIndex + 1 && col != colIndex + 1) {
continue;
}
sum += array[row][col];
}
}
return sum;
}
}
function galssSum(array) {
let maxGlass = 0;
if (array[0].length == 3) {
maxGlass = 1;
} else if (array[0].length > 3) {
maxGlass = array.length - 2;
}
let maxValue = -100000;
for (let i = 0; i < maxGlass; i++) {
for (let j = 0; j < maxGlass; j++) {
let a = array[i][j] + array[i][j + 1] + array[i][j + 2];
let b = array[i + 1][j + 1];
let c = array[i + 2][j] + array[i + 2][j + 1] + array[i + 2][j + 2];
let sum = a + b + c;
if (maxValue<sum) {
maxValue = sum;
}
}
}
return maxValue;
}
console.log(galssSum([[1, 1, 1, 0, 0, 0], [0, 1, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0], [0, 0, 2, 4, 4, 0], [0, 0, 0, 2, 0, 0], [0, 0, 1, 2, 4, 0]]));
int hourglassSum(vector<vector<int>> vec) {
int res = 0;
int size = ((vec[0].size())-2) * ((vec.size())-2);
//cout<<size<<endl;
vector<int> res_vec(size);
int j = 0;
int itr =0 ;
int cnt = 0;
int mid = 0;
int l =0;
while((l+2) < vec.size())
{
while((j+2) < vec.size())
{
for(int i =j ;i<j+3; i+=2)
{
//cout<<i<<" :";
for(int k=l;k<l+3;k++)
{
//cout<<k<<" ";
res_vec[itr] += vec[i][k];
}
//cout<<endl;
}
res_vec[itr] += vec[j+1][l+1];
//cout<<endl;
itr++;
j++;
}
l++;
j=0;
}
int max=res_vec[0];
for(int i =1;i<res_vec.size();i++)
{
if(max < res_vec[i])
{
max = res_vec[i];
}
//cout<<res_vec[i]<< " ";
}
res = max;
//cout<<endl;
return res;
}
// Complete the hourglassSum function below.
static int hourglassSum(int[][] arr) {
int max = Integer.MIN_VALUE;
for (int i = 0; i < arr.length - 2; i++) {
for (int j = 0; j < arr.length - 2; j++) {
int hourGlassSum = (arr[i][j] + arr[i][j + 1] + arr[i][j + 2])
+ (arr[i + 1][j + 1])
+ (arr[i + 2][j] + arr[i + 2][j + 1] + arr[i + 2][j + 2]);
max = Math.max(hourGlassSum,max);
}
}
return max;
}
public static int hourglassSum(List<List<Integer>> arr) {
// Write your code here
int maxSum = Integer.MIN_VALUE;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
int sum = arr.get(i).get(j) +arr.get(i).get(j+1) +
arr.get(i).get(j+2)+arr.get(i+1).get(j+1)+
arr.get(i+2).get(j)+arr.get(i+2).get(j+1)+arr.get(i+2).get(j+2);
if (maxSum < sum) {
maxSum = sum;
}
}
}
return maxSum;
}
}
Iterative way,Passing all test cases in hackerank web
public static int hourglassSum(List<List<Integer>> arr) {
// Write your code here
int rowsCount=arr.size();
int colCount=arr.get(0).size();
Integer max=Integer.MIN_VALUE;
Integer subSum=0;
for(int r=0; (r+3)<=rowsCount; r++)
{
for(int c=0; (c+3)<=colCount; c++)
{
subSum= hourglassSubSum(arr,r,c);
System.out.println("r,c,subSum "+r+" "+c+" "+" "+subSum);
if(subSum>max)
{
max=subSum;
}
}
}
return max;
}
public static int hourglassSubSum(List<List<Integer>> hourglassArray,
int rowIndex,int colIndex) {
// Write your code here
Integer subSum=0;
for(int i=rowIndex;i<(rowIndex+3);i++)
{
for(int j=colIndex;j<(colIndex+3);j++)
{
if(i==(rowIndex+1) && (j==colIndex || j==colIndex+2))
{
continue;
}
subSum=subSum+hourglassArray.get(i).get(j);
}
}
return subSum;
}
Solution for actual "2D Array - DS" challenge from HackerRank https://www.hackerrank.com/challenges/2d-array
public static int hourglassSum(List<List<Integer>> arr) {
int maxSum = Integer.MIN_VALUE;
for (int col=0; col <= 3; col++) {
for (int row=0; row <= 3; row++) {
int sum = calcHourglass(arr, col, row);
maxSum = Math.max(sum, maxSum);
}
}
return maxSum;
}
private static int calcHourglass(List<List<Integer>> arr, int col, int row) {
int sum = 0;
for (int i=0; i < 3; i++) {
sum += arr.get(row).get(col+i); // the top of the hourglass
sum += arr.get(row+2).get(col+i); // the bottom of the hourglass
}
sum += arr.get(row+1).get(col+1); // the center
return sum;
}
import java.io.*;
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int low = -9,high = 5;
int lh = low * high;
int sum = 0, i, j;
int max = 0;
int a[][] = new int[6][6];
for (i = 0; i < 6; i++) {
for (j = 0; j < 6; j++) {
a[i][j] = in.nextInt();
}
}
for (i = 0; i < 4; i++) {
for (j = 0; j < 4; j++) {
sum = (a[i][j] + a[i][j+1] + a[i][j+2]);
sum = sum + a[i+1][j+1];
sum = sum + (a[i+2][j] + a[i+2][j+1] + a[i+2][j+2]);
if (sum > lh) lh = sum;
}
}
System.out.print(lh);
}
}
Here you go..
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int a[][] = new int[6][6];
int max = 0;
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 6; j++) {
a[i][j] = in.nextInt();
}
}
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
int sum = a[i][j] + a[i][j + 1] + a[i][j + 2] + a[i + 1][j + 1]
+ a[i + 2][j] + a[i + 2][j + 1] + a[i + 2][j + 2];
if (sum > max || (i == 0 && j == 0)) {
max = sum;
}
}
}
System.out.println(max);
}
so im done with the whole thing and i compile it when i ran it it had a error for said: arrayindexexception and i try looking for my mistake and i could not find it so i need someone to see if they can help me
public class Merging
{
public static int[] merge(int[] arrA, int[] arrB)
{
int[] sum = new int[arrA.length + arrB.length];
int i = 0, j = 0, k = 0;
while ( i < arrA.length && j < arrB.length)
{
if(arrA[i] < arrB[j])
{
sum[k] = arrA[i];
i++;
k++;
}else
sum[k] = arrB[i];
j++;
k++;
}
return sum;
}
public static void main(String[] args)
{
int a = (int)(Math.random() * (50-20+1)+20);
int b = (int)(Math.random() * (50-20+1)+20);
int[] a1 = new int[a];
int[] a2 = new int[b];
int i = 0;
while(i < a1.length && 1 < a2.length)
{
a1[i] = (int) (Math.random() * (150-20+1)+20);
a2[i] = (int) (Math.random() * (150-20+1)+20);
i++;
}
for(int j = 0; j < a1.length; j++)
{
System.out.print(a1[j]);
}
System.out.println();
for(int k = 0; k < a2.length; k++)
{
System.out.print(a1[k]);
}
System.out.println();
System.out.print(merge(a1,a2));
}
}
Two errors.
1.) Change from 1 < a2.length to i < a2.length
while (i < a1.length && i < a2.length) {
a1[i] = (int) (Math.random() * (150 - 20 + 1) + 20);
a2[i] = (int) (Math.random() * (150 - 20 + 1) + 20);
i++;
}
2.) Change from System.out.print(a1[k]); to System.out.print(a2[k]);
for (int k = 0 ; k < a2.length ; k++) {
System.out.print(a2[k]);
}
In your while loop
while(i < a1.length && 1 < a2.length)
the "1" should be an "i"
One of your problems is here
for(int k = 0; k < a2.length; k++)
{
System.out.print(a1[k]);
}
You're iterating through a1, but your index goes to the length of a2.
Need little help with my programming.
I'd like to create a grid with n columns and n rows. A also would like to show or print adjacency matrix.For start I did create some code, but the results are not correct, and I don't know hot to fix it. I need this grid to calculate shortest path, mutation of this grid, ...
The first for loop create a nice grid size n*n, but I don't know how to create links between naighbour nodes. The second code (which is in comment, create a adjacency matrix, but is not correnct -> node 3-4,7-8, 11-12 shouldn't be connected (if we have 4x4 grid), and in this code is missing last 4 nodes (if n=4).
Can someone tell me where did I fail in my coding :)?
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Network_1 {
public static void main(String[] args) throws Exception {
BufferedReader input1 = new BufferedReader(new InputStreamReader(
System.in));
System.out.println("Enter the number of columns/rows");
int cols = Integer.parseInt(input1.readLine());
input1.close();
int N = cols * cols;
int[][] A = new int[N][N];
for (int i = 0; i < N; i++) {
if (i > 1
&& ((cols == 0 && N % i == 0) || (cols > 0 && i % cols == 0))) {
if (cols == 0) {
cols = i;
}
System.out.print("\n");
}
System.out.format("%3d", i);
}
System.out.println("\nAdjacency matrix:");
for(int i = 0; i < N; i++) {
for(int j = 0; j < N; j++) {
System.out.print(A[i][j] + " ");
}
System.out.println();
}
/*
// If I try to create my "grid" with this code, I do not get true results
// The Matrix is incorrect
for(int i=0; i<N-cols; i++){
for(int j=0; j<N-cols; j++){
if((cols > 0) && (i % cols == 0)){
A[i][i+1] = 0;
A[i + 1][i] = 0;
}else{
A[i][i+1] = 1;
A[i + 1][i] = 1;
A[i][i+cols] = 1;
A[i + cols][i] = 1;
}
}
}
System.out.println("Adjacency matrix2:");
for(int i = 0; i < N; i++) {
for(int j = 0; j < N; j++) {
System.out.print(A[i][j] + " ");
}
System.out.println("");
}
*/
}
}
Helo. I did some other approach and this work quite well for me right now. I know tis isn't the best solution, but it wokrs for now. Now I will etst if realy works...
public static int[][] make_grid(int cols) {
int N = cols * cols;
int[][] A = new int[N][N];
for (int i = 0; i < N; i++) {
A[i][i] = 0;
int left= i - 1;
int right= i + 1;
int upper= i - cols;
int bottom= i + cols;
if (left> 0)
A[i][left] = 1;
if (rigft% cols != 0) {
if (right< N)
A[i][right] = 1;
}
if (upper> 0)
A[i][upper] = 1;
if (bottom< N)
A[i][bottom] = 1;
}
return A;
}
I have to ask for an input and display a diamond with that many lines. I have a code but it displays less lines than I input. I'm confused with where I'm going wrong?
This is the code I have currently:
Code:
import java.util.Scanner;
public class PROBLEM3 {
public static void main(String [] args){
Scanner scan = new Scanner (System.in);
System.out.println("Please input number of lines:");
int i = 0, j, k, n;
n = scan.nextInt();
for(k = 0; k <= n / 2; k++){
for (i = 0; i < n - k; i++){
System.out.print(" ");
}
for (j = 1; j < k; j++){
System.out.print("*");
}
for (j = 1; j < k - 1 ; j++){
System.out.print("*");
}
System.out.println("");
}
for (k = (n / 2); k <= n ; k++){
for (i = 0; i < k; i++){
System.out.print(" ");
}
for ( i = 1; i < n - k ; i++){
System.out.print("*");
}
for (j = 0; j < n - k - 2; j++){
System.out.print("*");
}
System.out.print("\n");
}
scan.close();
}
}
Output:
Please input number of lines:
5
*
***
*
please try the below code,
import java.util.Scanner;
public class PROBLEM3 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Please input number of lines:");
int i = 0, j, k, n;
n = scan.nextInt();
for (k = 1; k <= (n + 1) / 2; k++) {
for (i = 0; i < n - k; i++) {
System.out.print(" ");
}
for (j = 0; j < k; j++) {
System.out.print("* ");
}
System.out.println("");
}
for (k = ((n + 1) / 2); k < n; k++) {
for (i = 1; i < k; i++) {
System.out.print(" ");
}
for (j = 0; j < n - k; j++) {
System.out.print(" *");
}
System.out.println("");
}
scan.close();
}
}