print how many rows contains consecutive elements matching a+b=c - java

I'm trying to print how many rows contain subarrays (a, b, c) which satisfy a + b = c
int [][] matrix = {
{0,**5,2,7**,0,0},
{6,0,2, 1,-5,5},
{8,5,**1,1,2**,-2},
{3,-1,-5,-3,-4,-2}
};
this is the matrix in question it has only two sums so my program should print 2 , but somehow i miss something , the program should only print the rows that contain a sum of numbers not matter how many they are on a row
int [][] matrix = {
{0,5,2,7,9,0},
{6,0,2, 1,-5,5},
{8,5,1,1,2,-2},
{3,-1,-5,-3,-4,-2}
};
for example here we have 3 sums, but my program should print 2 anyway
public static int rowSumsOfThree(int [][] matrix) {
int count = 0 ;
if (matrix.length != 0 ) {
for (int i = 0 ; i < matrix.length ; i++) {
for (int j = 0 ; j < matrix[0].length-2 ; j++)
if (matrix[i][j] + matrix[i][j+1] == matrix[i][j+2]) {
count++;
break;
}
}}
return count;
}
this is my code so far , i know it's maybe some stupid mistake i make , if you can provide some explanation it is greatly appreciated , thank you all
Maybe my english is bad , I need to create a method that sums the elements within an array as
int [] matrix = {{2,3,4,7,8,3,2},
{1,23,4,2,2,}};
given this matrix , i need to sum them like this , first two elements = the third , second and third element = the fourth and so on , if the algorithm checks than it should return on how many rows it checks , first matrix should be 2 , second matrix should be 1 ; i hope i explained better
EDIT : Use of break solved my problem ! It will count only one sum per row , even if there are more per row , therefor count will be equal also to the numbers of rows. thank you for the help

As ari said, your return statement should be:
return count;
not
return rowIndex;
It's a very simple bug, consider deleting your question.

Related

Algorithm to calculate maximum points by deleting a number

I am going through this leetcode algorithm, I am trying to understand it by reading the explanation many times since 2 days, but I am not able to get the concept how the program is solved.
This is the problem statement:
Given an array nums of integers, you can perform operations on the
array.
In each operation, you pick any nums[i] and delete it to earn nums[i]
points. After, you must delete every element equal to nums[i] - 1 or
nums[i] + 1.
You start with 0 points. Return the maximum number of points you can
earn by applying such operations.
Example 1: Input: nums = [3, 4, 2] Output: 6 Explanation: Delete 4 to
earn 4 points, consequently 3 is also deleted. Then, delete 2 to earn
2 points. 6 total points are earned.
Here is the explanation for on how it is solved:
Algorithm
For each unique value k of nums in increasing order, let's maintain
the correct values of avoid and using, which represent the answer if
we don't take or take k respectively.
If the new value k is adjacent to the previously largest value prev,
then the answer if we must take k is (the point value of k) + avoid,
while the answer if we must not take k is max(avoid, using).
Similarly, if k is not adjacent to prev, the answer if we must take k
is (the point value of k) + max(avoid, using), and the answer if we
must not take k is max(avoid, using).
At the end, the best answer may or may not use the largest value in
nums, so we return max(avoid, using).
and the corresponding Java program:
public int deleteAndEarn(int[] nums) {
int[] count = new int[10001];
for (int x: nums) count[x]++;
int avoid = 0, using = 0, prev = -1;
for (int k = 0; k <= 10000; ++k) if (count[k] > 0) {
int m = Math.max(avoid, using);
if (k - 1 != prev) {
using = k * count[k] + m;
avoid = m;
} else {
using = k * count[k] + avoid;
avoid = m;
}
prev = k;
}
return Math.max(avoid, using);
}
I am not able to understand how avoid and using variables are used here and how it is solving the problem statement.
Can you please help me in understanding this.
I went through the problem on that page.
The algorithm is based on a very nice trick. It is very easy to solve this problem when you process the input first before applying the algorithm.
The input is reorganized into buckets.
Lets say you have the input : 1 1 2 3 3 2 2 4 4 4
You can reorganize it into
(Two 1s), (Three 2s), ( Two 3s), (Three 4s)
Now according to the problem, if you pick any bucket you should give up the bucket containing ( bucket-element-value - 1 ) and ( bucket-element-value + 1 ), which are actually adjacent ones to this bucket.
The problem now boils down to how would you pick buckets to get maximum sum given that constraint that you cannot get the adjacent bucket values ?
It is simple - As you go through the buckets, you have two things that you can do with a bucket. Either avoid it or use it.
If you avoid it, what is the maximum amount you can achieve - it depends on what you did with the previous one.
amountWhenAvoided[i] = Math.max( amountWhenAvoided[i-1], amountWhenTaken[i-1] );
If you use it, what is the maximum amount you can achieve? You get that bucket's value + whatever you got when you left/avoided the previous bucket.
amountWhenTaken[i] = amountWhenAvoided[i-1] + valueOfBucket[i]
Once you reach end of buckets the answer will be :
Math.max( amountWhenTaken[n], amountWhenAvoided[n] )
You could code this like:
public int deleteAndEarn( int[] nums ) {
//reorganize.
int[] valueOfBucket= new int[10001] //This is the maximum size of the buckets.
for ( int num : nums ) {
valueOfBucket[num] += num; //Populate each bucket.
}
//Now go through each bucket - remember - a bucket could be empty that's fine.
int[] amountWhenTaken = new int[n];
int[] amountWhenAvoided = new int[n];
amountWhenTaken[0] = 0; //Because there are no buckets to start with - buckets start from 1
amountWhenAvoided[0] = 0;
for ( int i = 1; i <= n; i++ ) {
amountWhenAvoided[i] = Math.max( amountWhenAvoided[i-1], amountWhenTaken[i-1] );
amountWhenTaken[i] = amountWhenAvoided[i-1] + valueOfBucket[i];
}
return Math.max( amountWhenTaken[n], amountWhenAvoided[n] );
}
If you observe the code above, it is really not needed to do it with arrays. Because the current element in the array depends on its previous element, so we can do it with just two variables lets call them avoiding, using
Then the second for loop can be written as:
public int deleteAndEarn( int[] nums ) {
//reorganize.
int[] valueOfBucket= new int[10001] //This is the maximum size of the buckets.
for ( int num : nums ) {
valueOfBucket[num] += num; //Populate each bucket.
}
//Now go through each bucket - remember - a bucket could be empty that's fine.
int using_prev = 0;
int avoiding_prev = 0;
int avoiding_curr = 0;
int using_curr = 0;
for ( int i = 1; i <= n; i++ ) {
avoiding_curr = Math.max( avoiding_prev, using_prev);
using_curr = avoiding_prev + valueOfBucket[i];
avoiding_prev = avoiding_curr;
using_prev = using_curr;
}
return Math.max( avoiding_curr, using_curr );
}

Print characters as a Matrix

Below problem has a list of characters and number of columns as the input. Number of columns is not a constant and can vary with every input.
Output should have all the rows fully occupied except for the last one.
list: a b c d e f g
colums: 3
Wrong:
a b c
d e f
g
Wrong:
a d g
b e
c f
Correct:
a d f
b e g
c
I have tried below:
public static void printPatern(List<Character> list, int cols) {
for (int i = 0; i < cols; i++) {
for (int j = i; j < list.size(); j += cols) {
System.out.print(list.get(j));
}
System.out.println();
}
}
It gives output as (which is wrong):
a d g
b e
c f
I am trying to come with an algorithm to print the correct output. I want to know what are the different ways to solve this problem. Time and Space complexity doesn't matter. Also above method which I tried is wrong because it takes columns as the parameter but that's actually acting as the number of rows.
FYI: This is not a HOMEWORK problem.
Finally able to design the algorithm for this problem
Please refer below java code same
public class puzzle{
public static void main(String[] args){
String list[] = { "a", "b", "c","d","e","f","g","h","i","j" };
int column = 3;
int rows = list.length/column; //Calculate total full rows
int lastRowElement = list.length%column;//identify number of elements in last row
if(lastRowElement >0){
rows++;//add inclomplete row to total number of full filled rows
}
//Iterate over rows
for (int i = 0; i < rows; i++) {
int j=i;
int columnIndex = 1;
while(j < list.length && columnIndex <=column ){
System.out.print("\t"+list[j]);
if(columnIndex<=lastRowElement){
if(i==rows-1 && columnIndex==lastRowElement){
j=list.length; //for last row display nothing after column index reaches to number of elements in last row
}else{
j += rows; //for other rows if columnIndex is less than or equal to number of elements in last row then add j value by number of rows
}
}else {
if(lastRowElement==0){
j += rows;
}else{
j += rows-1; //for column greater than number of element in last row add j = row-1 as last row will not having the column for this column index.
}
}
columnIndex++;//Increase column Index by 1;
}
System.out.println();
}
}
}
This is probably homework; so I am not going to do it for you, but give you some hints to get going. There are two points here:
computing the correct number of rows
computing the "pattern" that you need when looping your list so that you print the expected result
For the first part, you can look into the modulo operation; and for the second part: start iterating your list "on paper" and observe how you are printing the correct result manually.
Obviously, that second part is the more complicated one. It might help if you realize that printing "column by column" is straight forward. So when we take your correct example and print the indexes instead of values, you get:
0 3 6
1 4 7
2 5
Do that repeatedly for different input; and you will soon discover the pattern of indexes that you need to print "row by row".

Adding each column in a 2D array which become values of the last row

I'm trying to add all of the values for each column in a 2D array and these sums become values that overwrite the last row of the array
for example:
4 5 6 7 8
1 2 3 4 5
0 0 0 0 0 //this row will be replaced by the sum of each column
4 5 6 7 8
1 2 3 4 5
5 7 9 11 13
public static void fillTotals(int[][] scores)
{
int count = 0;
for (int r = 0; r < scores.length - 1; r++)
{
scores[r][0] += count;
scores[scores.length - 1][scores[0].length - 1] = count;
}
}
I thought I could keep the columns the same and add it down with the changing rows but it isn't rewriting the last row. Also I don't know how to change the values at the bottom
You need to iterate once over all rows and columns, actually iterate over all rows, for every column. If you assume that the number of columns is the same for every row, then you can use scores[0].length as a fixed value.
public static void fillTotals(int[][] scores) {
for (int c=0; c < scores[0].length; ++c) {
int sum = 0;
for (int r=0; r < scores.length - 1; ++r) {
sum += scores[r][c];
}
scores[scores.length - 1][c] = sum;
}
}
This assumes that the final row of the 2D array is not part of the sum and is available to be overwritten with the sum of all preceding values, for each column.
Well, the reason that nothing is being updated is that you never change count, so you just end up adding 0 to everything. I think what you want instead of:
scores[r][0] += count;
is:
count += scores[r][0];
That way count will contain the summation of every element in the first column.
To be clear, scores[r][0] += count; is the same as scores[r][0] = scores[r][0] + count;, whereas I think you probably want count = scores[r][0] + count;
That being said, Im still pretty sure this code isnt actually going to work (sorry), since you only ever actually sum values from the first column. However, for the sake of not just doing way may be a school assignment for you, Im just going to leave it there. If you're still stuck let me know, and I'll try to help!

Reprint a String array Java

I have a string array
"Ben", "Jim", "Ken"
how can I print the above array 3 times to look like this:
"Ben", "Jim", "Ken"
"Jim", "Ben", "Ken"
"Ken", "Jim", "Ben"
I just want each item in the initial array to appear as the first element. The order the other items appear does not matter.
more examples
Input
"a","b","c","d"
output
"a","b","c","d"
"b","a","c","d"
"c","b","a","d"
"d","a","c","d"
Method signature
public void printArray(String[] s){
}
Rather than give you straight-up code, I'm going to try and explain the theory/mathematics for this problem.
The two easiest ways I can come up with to solve this problem is to either
Cycle through all the elements
Pick an element and list the rest
The first method would require you to iterate through the indices and then iterate through all the elements in the array and loop back to the beginning when necessary, terminating when you return to the original element.
The second method would require you to iterate through the indices, print original element, then proceed to iterate through the array from the beginning, skipping the original element.
As you can see, both these methods require two loops (as you are iterating through the array twice)
In pseudo code, the first method could be written as:
for (i = array_start; i < array_end; i++) {
print array_element[i]
for (j = i + 1; j != i; j++) {
if (j is_larger_than array_end) {
set j equal to array_start
}
print array_element[j]
}
}
In pseudo code, the second method could be written as:
for (i = array_start; i < array_end; i++) {
print array_element[i]
for (j = array_start; j < array_end; j++) {
if (j is_not_equal_to i) {
print array_element[j]
}
}
}
public void printArray(String[] s){
for (int i = 0; i < s.length; i++) {
System.out.print("\"" + s[i] + "\",");
for (int j = 0; j < s.length; j++) {
if (j != i) {
System.out.print("\"" + s[j] + "\",");
}
}
System.out.println();
}
}
This sounds like a homework question so while I feel I shouldn't answer it, I'll give a simple hint. You are looking for an algorithm which will give all permutations (combinations) of the "for loop index" of the elements not the elements themselves. so if you have three elements a,b,c them the index is 0,1,2 and all we need is a way to generate permutations of 0,1,2 so this leads to a common math problem with a very simple math formula.
See here: https://cbpowell.wordpress.com/2009/11/14/permutations-vs-combinations-how-to-calculate-arrangements/
for(int i=0;i<s.length;i++){
for(int j=i;j<s.length+i;j++) {
System.out.print(s[j%(s.length)]);
}
System.out.println();
}
Using mod is approppiate for this question. The indexes of the printed values for your first example are like this;
0 1 2
1 2 0
2 0 1
so if you write them like the following and take mod of length of the array (3 in this case) you will reach solution.
0 1 2
1 2 3
2 3 4

Searching specific rows in a multi-dimensional array

I'm new to java programming and I can't wrap my head around one final question in one of my assignments.
We were told to create a static method that would search a 2-D array and compare the numbers of the 2-D array to an input number...so like this:
private static int[] searchArray(int[][] num, int N){
Now, the part what we're returning is a new one-dimensional array telling the index of the first number in each row that is bigger than the parameter variable N. If no number is bigger than N, then a -1 is returned for that position of the array.
So for example a multi-dimensional array named "A":
4 5 6
8 3 1
7 8 9
2 0 4
If we used this method and did searchArray(A, 5) the answer would be "{2,0,0,-1)"
Here is a very good explanation about Java 2D arrays
int num[][] = {{4,5,6},{8,3,1},{7,8,9}};
int N = 5;
int result[] = new int[num.length];
for(int i=0; i<num.length; i++){
result[i] = -1;
for(int j=0; j<num[0].length; j++){
if( N < num[i][j] ){
result[i] = j;
break;
}
}
}
for(int i=0; i<result.length; i++){
System.out.println(result[i]);
}
The first for loop(The one with a for inside it) traverses the 2D array from top to bottom
in a left to right direction. This is, first it goes with the 4 then 5,6,8,3,1,7,8,9.
First the result array is created. The length depends of the number of rows of num.
result[i] is set to -1 in case there are no numbers bigger than N.
if a number bigger than N is found the column index is saved result[i] = j and a break is used to exit the for loop since we just want to find the index of the first number greater than N.
The last for loop just prints the result.
Generally when using multi-dimensional arrays you are going to use a nested for loop:
for(int i = 0; i < outerArray.length; i++){
//this loop searches through each row
for(int j = 0; j < innerArrays.length; j++) {
//this loop searches through each column in a given row
//do your logic code here
}
}
I won't give you more than the basic structure, as you need to understand the question; you'll be encountering such structures a lot in the future, but this should get you started.

Categories

Resources