Using nested loop on jlabel - java

I'm trying to find the cartesian product and print the result in jlabel but it only shows the last element of my array.
int list1 [] = { 1, 2, 3 };
int list2[] = { 1, 2, 3 };
int n1=list1.length;
int n2=list2.length;
findCart(list1, list2, n1, n2);
void findCart(int arr1[],int arr2[],
int n, int n1)
{
for (int i = 0; i < n; i++)
for (int j = 0; j < n1; j++)
jLabel1.setText("{"+ arr1[i]+", "
+ arr2[j]+"}, ");
}

You should concatenate the values before setting the text:
void findCart(int arr1[],int arr2[], int n, int n1)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n1; j++)
sb.append("{" + arr1[i] + ", " + arr2[j]+"}, ");
}
jLabel1.setText(sb.toString());
}

Related

How do I shorten my main method to where it still functions?

I have a java code to read the length of an integer array, output the range, length of the gap, and any distinct elements inside. Additionally, it will output the numbers again with none repeated.
I would like to shorten the length of my main method.
My code produces the correct output, it is just very lengthy. Additionally, is there a way I can edit this main method to where it won't require a drastic change to my other methods? Thank you so much!
package ArrayPrograms;
import java.util.Scanner;
public class WIP{
static int LargestGap(int [] a, int n)
{
int diff = Math.abs(a[1] - a[0]);
for(int i = 1; i < a.length-1; i++)
if(Math.abs(a[i+1]-a[i]) > diff)
diff = Math.abs(a[i+1] - a[i]);
return diff;
}
int range(int a[], int n)
{
int max1 = Integer.MIN_VALUE;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (Math.abs(a[i] - a[j]) > max1)
{
max1 = Math.abs(a[i] - a[j]);
}
}
}
return max1;
}
int numberOfDistinctElement(int a[], int n)
{
int num = 1;
for (int i = 1; i < n; i++)
{
int j = 0;
for (j = 0; j < i; j++)
if (a[i] == a[j])
break;
if (i == j)
num++;
}
return num;
}
int[] distinctElements(int a[], int n,int numberofDistinct)
{
int index = 0;
int[] distinct= new int[numberofDistinct];
for (int i = 0; i < n; i++)
{
int flag = 0;
for (int j = 0; j < i; j++){
if (a[i] == a[j]){
flag = 1;
break;
}
}
if (flag == 0){
distinct[index] = a[i];
index++;
}
}
return distinct;
}
***public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int num;
WIP obj=new WIP();
System.out.print("Enter the length of the array:");
num = in.nextInt();
int array[] = new int[num];
System.out.print("Enter the elements of the array: ");
for(int i = 0; i < num; i++)
{
array[i] = in.nextInt();
}
System.out.println("The largest gap in the array is "+WIP.LargestGap(array,num)+".");
System.out.println("The range of the array is "+obj.range(array,num)+".");
int numberofDistinct=obj.numberOfDistinctElement(array,num);
System.out.println("The number of distinct elements is "+numberofDistinct+".");
int[] distinctArray=obj.distinctElements(array,num,numberofDistinct);
System.out.print("The array of distinct elements is [");
for (int i = 0; i < distinctArray.length; i++)
if(i== distinctArray.length-1)
{
System.out.print(distinctArray[i]+"]");
}
else {
System.out.print( distinctArray[i]+ ",");
}
in.close();
}
}***
Sure thing. Here you go:
package arrayprograms;
import java.util.Scanner;
public class WIP{
static int LargestGap(int [] a, int n)
{
int diff = Math.abs(a[1] - a[0]);
for(int i = 1; i < a.length-1; i++)
if(Math.abs(a[i+1]-a[i]) > diff)
diff = Math.abs(a[i+1] - a[i]);
return diff;
}
int range(int a[], int n)
{
int max1 = Integer.MIN_VALUE;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (Math.abs(a[i] - a[j]) > max1)
{
max1 = Math.abs(a[i] - a[j]);
}
}
}
return max1;
}
int numberOfDistinctElement(int a[], int n)
{
int num = 1;
for (int i = 1; i < n; i++)
{
int j = 0;
for (j = 0; j < i; j++)
if (a[i] == a[j])
break;
if (i == j)
num++;
}
return num;
}
int[] distinctElements(int a[], int n,int numberofDistinct)
{
int index = 0;
int[] distinct= new int[numberofDistinct];
for (int i = 0; i < n; i++)
{
int flag = 0;
for (int j = 0; j < i; j++){
if (a[i] == a[j]){
flag = 1;
break;
}
}
if (flag == 0){
distinct[index] = a[i];
index++;
}
}
return distinct;
}
static void showResults(int[] array, int num, WIP obj){
System.out.println("The largest gap in the array is "+WIP.LargestGap(array,num)+".");
System.out.println("The range of the array is "+obj.range(array,num)+".");
int numberofDistinct=obj.numberOfDistinctElement(array,num);
System.out.println("The number of distinct elements is "+numberofDistinct+".");
int[] distinctArray=obj.distinctElements(array,num,numberofDistinct);
System.out.print("The array of distinct elements is [");
for (int i = 0; i < distinctArray.length; i++)
if(i== distinctArray.length-1)
{
System.out.print(distinctArray[i]+"]");
}
else {
System.out.print( distinctArray[i]+ ",");
}
}
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int num;
WIP obj=new WIP();
System.out.print("Enter the length of the array:");
num = in.nextInt();
int array[] = new int[num];
System.out.print("Enter the elements of the array: ");
for(int i = 0; i < num; i++)
{
array[i] = in.nextInt();
}
in.close();
showResults(array, num, obj );
}
}
There's not a whole lot you can do, like most of the comments say, but you can remove and edit some of the braces around that aren't necessary for the bodies. Here is a rough draft of it. The only things you could change besides that is to store all of the WIP.tests in variables in one code block and then print them all out in another code block; which would improve readability.
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
WIP obj = new WIP();
System.out.print("Enter the length of the array:");
int num = in.nextInt();
int array[] = new int[num] ;
System.out.print("Enter the elements of the array: ");
for(int i = 0; i < num; i++)
array[i] = in.nextInt();
System.out.println("The largest gap in the array is " + WIP.LargestGap(array,num) + ".");
System.out.println("The range of the array is " + obj.range(array,num) + ".");
int numberofDistinct = obj.numberOfDistinctElement( array, num );
System.out.println("The number of distinct elements is "+numberofDistinct+".");
int[] distinctArray = obj.distinctElements(array,num,numberofDistinct);
System.out.print("The array of distinct elements is [");
for (int i = 0; i < distinctArray.length; i++)
if(i== distinctArray.length-1)
System.out.print(distinctArray[i]+"]");
else
System.out.print( distinctArray[i]+ ",");
in.close();
}

How to Output the Index of an Element in array

This was the task:
Design, implement and test programs to do each of the following:
a) Find the sum and number of positive integers in a list of 10 integers.
b) Find the smallest number in a list of 10 integers.
c) Determine and output the biggest and smallest numbers in a list of 10 integers.
The output should be of the form :
“The biggest number 304 was at position 3 in the list”
“The smallest number 4 was at position 8 in the list”
So I tried it and the Problem is that everything works except to give me the position of the biggest and smallest number.
import java.util.Arrays;
public class a5_2 {
#SuppressWarnings("unlikely-arg-type")
public static void main (String [] args) {
int m [] = {-3,23,7,12,4,-44,2,21,3,43} ;
System.out.println("Array: " + Arrays.toString(m));
int[] pos = findNumber(m);
System.out.println("Array without negatives: ");
for (int i = 0; i < pos.length; i++)
{
System.out.println(pos[i]);
}
System.out.println("Number of pos num: " + pos.length);
int sum = 0;
for (int i : pos)
sum += i;
System.out.println("Sum of pos num: " + sum);
int [] small = findSmallest(pos);
System.out.println("Smallest Number: ");
System.out.println(small[0] + " at pos: " + Arrays.asList(pos).indexOf(small[0]));
int [] big = findBiggest(pos);
System.out.println("Biggest Number: ");
System.out.println(big[0] + " at pos: " + Arrays.asList(pos).indexOf(big[0]));
}
public static int [] findNumber(int[] sum) {
int num = 0;
int n [] = new int [sum.length];
for(int i = 0; i < sum.length; i++)
{
if (sum[i] > 0)
{
n[num] = sum[i];
num++;
}
}
int [] pos = new int [num];
for (int k = 0 ; k < num ; k++)
{
pos[k] = n[k];
}
return pos;
}
public static int [] findSmallest(int[] pos) {
int temp;
for (int i = 0; i < pos.length; i++)
{
for (int j = i + 1; j < pos.length; j++)
{
if (pos[i] > pos[j])
{
temp = pos[i];
pos[i] =pos[j];
pos[j] = temp;
}
}
}
return pos;
}
public static int [] findBiggest(int[] pos) {
int temp;
for (int i = 0; i < pos.length; i++)
{
for (int j = i + 1; j < pos.length; j++)
{
if (pos[i] < pos[j])
{
temp = pos[i];
pos[i] =pos[j];
pos[j] = temp;
}
}
}
return pos;
}
}
Output of the position is -1 instead of the output it should give.
Thank you guys in advance :)
Arrays.asList(pos) is converting into List<int[]> convert it into List<Integer> and then get the index
List<Integer> comArray = Arrays.stream(m).boxed().collect(Collectors.toList());
System.out.println(small[0] + " at pos: " + comArray.indexOf(small[0]));
In java-7, i believe you know already how to convert int[] to List<integer>
List<Integer> comArray = new ArrayList<>();
List<Integer> intList = new ArrayList<Integer>();
for (int i : m)
{
intList.add(i);
}
Verified Code
#SuppressWarnings("unlikely-arg-type")
public static void main (String [] args) {
int m [] = {-3,23,7,12,4,-44,2,21,3,43} ;
List<Integer> comArray = Arrays.stream(m).boxed().collect(Collectors.toList());
System.out.println("Array: " + Arrays.toString(m));
int[] pos = findNumber(m);
System.out.println("Array without negatives: ");
for (int i = 0; i < pos.length; i++)
{
System.out.println(pos[i]);
}
System.out.println("Number of pos num: " + pos.length);
int sum = 0;
for (int i : pos)
sum += i;
System.out.println("Sum of pos num: " + sum);
int [] small = findSmallest(pos);
System.out.println("Smallest Number: ");
System.out.println(small[0] + " at pos: " + comArray.indexOf(small[0]));
int [] big = findBiggest(pos);
System.out.println("Biggest Number: ");
System.out.println(big[0] + " at pos: " + comArray.indexOf(big[0]));
}
public static int [] findNumber(int[] sum) {
int num = 0;
int n [] = new int [sum.length];
for(int i = 0; i < sum.length; i++)
{
if (sum[i] > 0)
{
n[num] = sum[i];
num++;
}
}
int [] pos = new int [num];
for (int k = 0 ; k < num ; k++)
{
pos[k] = n[k];
}
return pos;
}
public static int [] findSmallest(int[] pos) {
int temp;
for (int i = 0; i < pos.length; i++)
{
for (int j = i + 1; j < pos.length; j++)
{
if (pos[i] > pos[j])
{
temp = pos[i];
pos[i] =pos[j];
pos[j] = temp;
}
}
}
return pos;
}
public static int [] findBiggest(int[] pos) {
int temp;
for (int i = 0; i < pos.length; i++)
{
for (int j = i + 1; j < pos.length; j++)
{
if (pos[i] < pos[j])
{
temp = pos[i];
pos[i] =pos[j];
pos[j] = temp;
}
}
}
return pos;
}
}
Output
Array: [-3, 23, 7, 12, 4, -44, 2, 21, 3, 43]
Array without negatives:
23
7
12
4
2
21
3
43
Number of pos num: 8
Sum of pos num: 115
Smallest Number:
2 at pos: 6
Biggest Number:
43 at pos: 9
because Arrays.asList(pos) return List<int[]> not List<Integer>.

Java - Sorting a 2D Array by Row Sum

Trying to write a method that swaps the rows of a 2D array in order of increasing row sum.
For example, if I have the following 2d array:
int [][] array = {4,5,6},{3,4,5},{2,3,4};
I would want it to output an array as so:
{2 3 4}, {3 4 5}, {4 5 6}
Methodology:
a.) take the sums of each row and make a 1D array of the sums
b.) do a bubble sort on rowSum array
c.) swap the rows of the original array based on the bubble sort swaps made
d.) then print the newly row sorted array.
Here's my code so far:
public void sortedArrayByRowTot() {
int [][] tempArray2 = new int [salaryArray.length [salaryArray[0].length];
for (int i = 0; i < tempArray2.length; i++) {
for (int j = 0; j < tempArray2[i].length; j++) {
tempArray2[i][j] = salaryArray[i][j];
}
}
int [] rowSums = new int [tempArray2.length];
int sum = 0;
for (int i = 0; i < tempArray2.length; i++) {
for (int j = 0; j < tempArray2[i].length; j++) {
sum += tempArray2[i][j];
}
rowSums[i] = sum;
sum = 0;
}
int temp;
int i = -1;
for(int j = rowSums.length; j > 0; j--){
boolean isSwap = false;
for (i = 1; i < j; i++) {
if(rowSums[i-1] > rowSums[i]) {
temp = rowSums[i-1];
rowSums[i-1] = rowSums[i];
rowSums[i] = temp;
isSwap = true;
}
}
if(!isSwap){
break;
}
}
for (int k = 0; k < tempArray2.length; k++) {
temp = tempArray2[i-1][k];
tempArray2[i-1][k] = tempArray2[i][k];
tempArray2[i][k] = temp;
}
for (int b = 0; b < tempArray2.length; b++) {
for (int c = 0; c < tempArray2[b].length; c++) {
System.out.print(tempArray2[b][c] + " ");
}
}
}
}
Not sure if I am doing part c of my methodology correctly?
It keeps saying "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2"
As #shmosel said, you can do it like this:
public static void sortedArrayByRowTot() {
int [][] array = {{4,5,6},{3,4,5},{2,3,4}};
Arrays.sort(array, Comparator.comparingInt(a -> IntStream.of(a).sum()));
}
I was able to solve my question. Thanks.
public void sortedArrayByRowTot() {
//Creates tempArray2 to copy salaryArray into
int [][] tempArray2 = new int [salaryArray.length][salaryArray[0].length];
//Copies salaryArray into tempArray2
for (int i = 0; i < salaryArray.length; i++) {
for (int j = 0; j < salaryArray[i].length; j++) {
tempArray2[i][j] = salaryArray[i][j];
}
}
//Creates rowSum array to store sum of each row
int [] rowSums = new int [tempArray2.length];
for (int i = 0; i < tempArray2.length; i++) {
for (int j = 0; j < tempArray2[0].length; j++) {
rowSums[i] += tempArray2[i][j];
}
}
//Modified Bubble Sort of rowSum array (highest to lowest values)
int temp;
int i = 0;
for(int j = rowSums.length; j > 0; j--){
boolean isSwap = false;
for (i = 1; i < j; i++) {
if(rowSums[i-1] < rowSums[i]) {
temp = rowSums[i-1];
rowSums[i-1] = rowSums[i];
rowSums[i] = temp;
isSwap = true;
//swaps rows in corresponding tempArray2
int [] temp2 = tempArray2[i-1];
tempArray2[i-1] = tempArray2[i];
tempArray2[i] = temp2;
}
}
if(!isSwap){
break;
}
}
//Prints sorted array
System.out.println("Sorted array: ");
for (i = 0; i < tempArray2.length; i++) {
for (int j = 0; j < tempArray2[i].length; j++) {
System.out.print("$"+ tempArray2[i][j] + " ");
}
System.out.println();
}
}
You may try this way. That I have solved.
public class Solution{
public static void sortedArrayByRowTot() {
int [][] salaryArray = { {4,5,6},{3,4,5},{2,3,4} };
int [][] tempArray2 = new int [salaryArray.length][salaryArray[0].length];
for (int i = 0; i < salaryArray.length; i++) {
for (int j = 0; j < salaryArray[i].length; j++) {
tempArray2[i][j] = salaryArray[i][j];
}
}
// Buble Sort to store rowSums
int [] rowSums = new int [tempArray2.length];
for (int i = 0; i < tempArray2.length; i++) {
for (int j = 0; j < tempArray2[0].length; j++) {
rowSums[i] += tempArray2[i][j];
}
}
//Buble Sort by Rows Sum (Lowest Value to Highest)
int temp;
int i = 0;
for(int j = rowSums.length; j > 0; j--){
boolean isSwap = false;
for (i = 1; i < j; i++) {
if(rowSums[i-1] > rowSums[i]) {
temp = rowSums[i-1];
rowSums[i-1] = rowSums[i];
rowSums[i] = temp;
isSwap = true;
//swaps rows in corresponding tempArray2
int [] temp2 = tempArray2[i-1];
tempArray2[i-1] = tempArray2[i];
tempArray2[i] = temp2;
}
}
if(!isSwap){
break;
}
}
/** No Need.
for (int k = 0; k < tempArray2.length; k++) {
temp = tempArray2[i-1][k];
tempArray2[i-1][k] = tempArray2[i][k];
tempArray2[i][k] = temp;
}
*/
for (int b = 0; b < tempArray2.length; b++) {
for (int c = 0; c < tempArray2[b].length; c++) {
System.out.print(tempArray2[b][c] + " ");
}
}
}
public static void main(String[] args) {
sortedArrayByRowTot();
}
}

Java - How to Solve this 2D Array Hour Glass?

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

parameter for my average function, the error it writes is "cannot find symbol"

/*METODA MAIN*/
public static void main(String[] args) {
Scanner sc = new Scanner(System. in );
int m, n;
int sloupec;
float prumerSloupce;
System.out.println("zadej pocet radku pole: ");
m = sc.nextInt();
System.out.println("zadej pocet sloupcu pole: ");
n = sc.nextInt();
int[][] a;
/*NAPLNENI POLE NAHODNYMI CISLY*/
a = naplnPole(m, n);
/*TISKNUTI POLE*/
tiskPole(a);
System.out.println("Zadej cislo sloupce, jehoz prumer chces znat ");
sloupec = sc.nextInt();
prumerSloupce = aritmetickyPrumerSloupce(a, sloupec);
/*METODA NAPLNENI POLE*/
public static int[][] naplnPole(int m, int n) {
int[][] x = new int[m][n];
for (int i = 0; i < x.length; i++) {
for (int j = 0; j < x[i].length; j++) {
x[i][j] = (int) Math.round(Math.random() * 9);
}
}
return x;
} /*METODA TISKNUTI POLE*/
public static void tiskPole(int[][] x) {
for (int i = 0; i < x.length; i++) {
for (int j = 0; j < x[i].length; j++) {
System.out.print(x[i][j] + " ");
}
System.out.println();
}
}
/*METODA ZJISTENI ARITMETICKEHO PRUMERU SLOUPCE*/
public static float aritmetickyPrumerSloupce(int[][] a, int sloupec) {
int sum = 0;
for (int i = 0; i < a.length; i++)
sum += array[i][sloupec];`this is the error line`
return sum / (float) a.length;
}
Everything works except the method, i'm trying to get average of a column from a matrix that consist of random numbers. number of rows and columns is defined by typing from scanner.
You aren't defining your array a anywhere that I can see;
int[][] a = { { 1, 2 }, { 3, 4 } };
System.out.println(Arrays.deepToString(a));
// ...
prumerSloupce = aritmetickyPrumerSloupce(a, column);
and your function should be using a.length like
public static float aritmetickyPrumerSloupce(int[][] a, int column) {
int sum = 0;
for (int i = 0; i < a.length; i++)
sum += a[i][column];
return sum / (float) a.length;
}

Categories