Java add matrix antidiagonal elements - java

I want to add a NxN matrix antidiagonal elements using a for loop in a java program.
This code (2 conditions) does not work because it always says when the loop is executed sum2=0.
for (int i=0,j=t-1; i<t && j==0; i++, j--) {
sum2 = sum2 + aNumber[i][j];
}
Instead this one (one condition) works well.
for (int i=0, j=t-1; i<t ; i++, j--) {
sum2 = sum2 + aNumber[i][j];
}
Why does not work the first code?

In your first example the loop ends as soon as j != 0, if t > 1 this means that it will end immediately, making no iterations at all.

Try something like this:
int maxIndex = matrix.length - 1;
int sum = 0;
for (int i = 0; i <= maxIndex; i++) {
sum += matrix[i][maxIndex - i];
}
This relies on the fact that the sum of the indexes of each antidiagonal element is exactly equal to N.

Related

Divisible Sum Pairs

Though it will be weird to see this question I really need to understand some core concepts while I continue my journey of coding. I have a problem which is on Hackerrank it goes like DIVISIBLE SUM PAIRS
I will anyhow give the problem statement here:
Problem Statement
Given an array, where we have to find the number of pairs divisible by the given number k, and there is one more condition to it, which is :
the arr[i] < arr[j] from those pairs.
Example
For example, ar=[1,2,3,4,5,6] and k=5. Our three pairs meeting the criteria are [1,4] [2,3] and [4,6].
Code
Before I publish my code, I would like to tell you that my code has passed all the test cases, and it is accepted to move ahead to the next challenge, but there is a glitch that I'm trying to figure out, which is there in the code.
static int divisibleSumPairs(int n, int k, int[] ar) {
int count = 0;
for(int i=0; i<ar.length; i++){
for(int j=i+1; j<ar.length; j++){
if(((ar[i]+ar[j])%k)==0){
if(i < j)
count++;
}
}
}
return count;
}
Here when I do this if(i < j) count++, it gives me the correct result, but as soon as I do this if(ar[i] < a[j]) count++, it supposedly gives me a wrong answer.
Can anybody help me clear this out, like what is left? Since I know the check arr[i] < arr[j] should give the correct result. I don't want to proceed with the wrong knowledge.
EDITS
Since I have understood what I was doing wrong. And I have one edit in my code that is not starting the inner loop with 1, since it will start off with 1 every time the inner loop finishes, and again runs. I thank everyone who helped me clear this and made my concepts strong enough to deal with the questions like this.
I personally thank Mike 'Pomax' Kamermans, Ricola, and xerx593 for clearing out my doubts and giving me the core concepts of looping through the elements. It will help me in the future, and I won't repeat that thing again. :)
I just checked your link and the condition given in the question statement is
Find and print the number of (i,j) pairs where i < j and ar[i] + ar[j] is divisible by k.
Which is simply the number of unordered pairs of elements for which the sum is divisible by k.
However you wrote
there is one more condition to it, which is : the arr[i] < arr[j] from
those pairs.
I seems like you have misread the question. And it explains why the i<j condition works whereas arr[i] < arr[j] doesn't.
Now that you know that you only need the unordered pairs, no need to iterate j from 1 to ar.length. Since you need j > i, every j between 1 and i (inclusive) is useless. You can simplify your code to:
static int divisibleSumPairs(int n, int k, int[] ar) {
int count = 0;
for(int i=0; i<ar.length-1; i++){
for(int j=i+1; j<ar.length; j++){
if(((ar[i]+ar[j])%k)==0){
count++;
}
}
}
return count;
}
Wen you do i = {0 ... 10} and j = {1 ... 10}, then there are (about) 100 cmobinations (of i and j), (about) 50, where i < j and the rest vice versa. So your assumption is wrong, that:
it is supposedly giving me a wrong answer
...it gives you correctly the wrong answer! ...since when a[i] + a[j] % k == 0, then a[j] + a[i] % k == 0 also!
If you don't include the if(i < j), you count (the occurrence of pairs ..exactly) doubly.
An (implementation) alternative would be:
for (int i = 0; i < ar.length; i++) {
// ensure i < j via initialization ;)
for (int j = i + 1; j < ar.length; j++) {
if (((ar[i]+ar[j]) % k) == 0) {
counter++;
}
}
}
...to initialize the inner loop with i + 1 instead of 1.
EDIT:(after getting the question better)
Your assumption, that a[i] > a[j] is equivalent with i > j OR j < i(but not both), is almost correct: except when a[i] == a[j].
That's my solution in javaScript (Passed all test-cases):
function divisibleSumPairs(n, k, ar) {
let count=0;
for(let i=0; i<n; i++){
for(let j=0; j<n; j++){
if(i<j){
if((ar[i]+ar[j])%k===0) count++;
}
}
}
return count;
}
This solution is using javaScript :
divisibleSumPairs (n, k, ar) => {
let count = 0;
ar = ar.map((value, index, arr) => {
for (let i = index + 1; i <= arr.length; i++) {
if ((value + arr[i]) % k === 0) {
count++;
}
}
});
return count
}
Dart Solution
n = arr.length;
int numberOfDivisiblePairs = 0;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if ((arr[i] + arr[j]) % k == 0) {
numberOfDivisiblePairs++;
}
}
}
return numberOfDivisiblePairs;
A solution in Python 3 (Passed all test-cases):
The itertools.combinations(arr,r) returns the r length subsequences of elements from the input iterable. Combinations are emitted in lexicographic sort order. So, if the input iterable is sorted, the combination tuples will be produced in sorted order.
from itertools import combinations
def divisibleSumPairs(n,ar,k):
pairs = []
for com in combinations(ar,2):
if sum(com) % k == 0:
pairs.append(com)
return len(pairs)
nk = input().split()
n = int(nk[0])
k = int(nk[1])
ar = list(map(int, input().rstrip().split()))
print(divisibleSumPairs(n,ar,k))
If anyone is interested in an O(n) solution, here is my C# solution.
public static int divisibleSumPairs(int n, int k, List<int> ar)
{
Dictionary<int, int> map = new Dictionary<int, int>();
int cnt = 0;
foreach (int elem in ar)
{
int modulo = elem % k;
int complement = modulo == 0 ? 0 : k - modulo;
if (map.ContainsKey(complement))
{
cnt += map[complement];
}
if (map.ContainsKey(modulo))
{
++map[modulo];
}
else
{
map.Add(modulo, 1);
}
}
return cnt;
}
def divisibleSumPairs(n, k, ar):
result = 0
d = {}
for i in range(n):
mod = ar[i] % k
result += d.get(( k - mod ) % k, 0)
d[mod] = d.get(mod, 0) + 1
return result
solution in O(n)

How to loop this statement with 3 changing values to setText for 40 textfields?

Here is the code when I haven't stored in a list. This gets what I want to display in different textfields but I want it to be shorter so I want to loop it.
//"answerStoration.retrieveDataChoices(i,TB)" is a function from other class that returns an arraylist;
quizAnswer1store.setText(answerStoration.retrieveDataChoices(1,TB).get(0));
quizAnswer2store.setText(answerStoration.retrieveDataChoices(1,TB).get(1));
quizAnswer3store.setText(answerStoration.retrieveDataChoices(1,TB).get(2));
quizAnswer4store.setText(answerStoration.retrieveDataChoices(1,TB).get(3));
quizAnswer1store2.setText(answerStoration.retrieveDataChoices(2,TB).get(0));
quizAnswer2store2.setText(answerStoration.retrieveDataChoices(2,TB).get(1));
quizAnswer3store2.setText(answerStoration.retrieveDataChoices(2,TB).get(2));
quizAnswer4store2.setText(answerStoration.retrieveDataChoices(2,TB).get(3));
quizAnswer1store3.setText(answerStoration.retrieveDataChoices(3,TB).get(0));
quizAnswer2store3.setText(answerStoration.retrieveDataChoices(3,TB).get(1));
quizAnswer3store3.setText(answerStoration.retrieveDataChoices(3,TB).get(2));
quizAnswer4store3.setText(answerStoration.retrieveDataChoices(3,TB).get(3));
I stored it in a List "quizAnswerSTORE" and I tried to loop but doesnt work.
int k = 0;
for(int i = 0; i<quizAnswerSTORE.size(); i++){
for(int j = 1; j < 11; j++){
while(k<4){
quizAnswerSTORE.get(i).setText(answerStoration.retrieveDataChoices(j,TB).get(k));
}
}
}
The expected result is to diplay different values from a database in different 40 txtfields. Because each time the loop values increments, it rolls through my database with different values. J variable represents the id in my database. And the K is an index in the values taken in the arrayList returned by retrieveDataAnswers function from a four columned database.
There you go. I hope you can solve this.
You can use mod to control maximun int values, for example i % 10 can't take values more than 10.
Example:
public class Main {
public static void main(String[] args) {
int j = 1;
int k = 0;
for(int i = 0; i < 40; i++) {
System.out.println("quizAnswerSTORE"+i+".setText(answerStoration.retrieveDataChoices("+j+",TB).get("+k+"));");
k = (k + 1)%4;
if( k == 0) {
j = (j+1) % 11;
}
}
}
}
output:
quizAnswerSTORE0.setText(answerStoration.retrieveDataChoices(1,TB).get(0));
quizAnswerSTORE1.setText(answerStoration.retrieveDataChoices(1,TB).get(1));
quizAnswerSTORE2.setText(answerStoration.retrieveDataChoices(1,TB).get(2));
quizAnswerSTORE3.setText(answerStoration.retrieveDataChoices(1,TB).get(3));
quizAnswerSTORE4.setText(answerStoration.retrieveDataChoices(2,TB).get(0));
quizAnswerSTORE5.setText(answerStoration.retrieveDataChoices(2,TB).get(1));
quizAnswerSTORE6.setText(answerStoration.retrieveDataChoices(2,TB).get(2));
quizAnswerSTORE7.setText(answerStoration.retrieveDataChoices(2,TB).get(3));
quizAnswerSTORE8.setText(answerStoration.retrieveDataChoices(3,TB).get(0));
quizAnswerSTORE9.setText(answerStoration.retrieveDataChoices(3,TB).get(1));
quizAnswerSTORE10.setText(answerStoration.retrieveDataChoices(3,TB).get(2));
quizAnswerSTORE11.setText(answerStoration.retrieveDataChoices(3,TB).get(3));
...
quizAnswerSTORE38.setText(answerStoration.retrieveDataChoices(10,TB).get(2));
quizAnswerSTORE39.setText(answerStoration.retrieveDataChoices(10,TB).get(3));
Try to be consistent with your indentation and line up closing brackets '}' with their corresponding statement.
The first problem I see with this code is that k is never incremented inside the while loop so it will always have the same value and loop forever. The second problem I see is that k is not reset after the while loop so when it goes through the loop the first time (and is correctly incremented) it will stay at a value of 4 and the loop will be skipped every time after that.
I'm not sure what you're trying to achieve (I could use some more information or a sample output) but to begin with you can correct the loop error by changing the while loop to a for loop like so.
for (int i = 0; i < quizAnswerSTORE.size(); i++) {
for (int j = 1; j < 11; j++) {
for (int k = 0; k < 4; k++) {
quizAnswerSTORE.get(i).setText(answerStoration.retrieveDataChoices(j,TB).get(k));
}
}
}
Alternatively, if you wanted to keep the while loop, you could so it like so.
for (int i = 0; i < quizAnswerSTORE.size(); i++) {
for (int j = 1; j < 11; j++) {
int k = 0; // Set k inside the 2nd loop and it will reset to 0 after the while loop
while(k < 4) {
quizAnswerSTORE.get(i).setText(answerStoration.retrieveDataChoices(j,TB).get(k));
k++; // Shorthand for k += 1 which is shorthand for k = k + 1
}
}
}

Big O for 3 nested for loops?

public int Loop(int[] array1) {
int result = 0;
for (int i = 0; i < array1.length; i++) {
for (int j = 0; j < array1.length; j++) {
for (int k = 1; k < array1.length; k = k * 2) {
result += j * j * array1[k] + array1[i] + array1[j];
}
}
}
return result;
}
I'm trying to find the complexity function that counts the number of arithmetic operations here. I know the complexity class would be O(n^3), but I'm having a bit of trouble counting the steps.
My reasoning so far is that I count the number of arithmetic operations which is 8, so would the complexity function just be 8n^3?
Any guidance in the right direction would be very much appreciated, thank you!
The first loop will run n times, the second loop will run n times however the third loop will run log(n) times (base 2). Since you are multiplying k by two each time the inverse operation would be to take the log. Multiplying we have O(n^2 log(n))
If we can agree that the following is one big step:
result += j * j * array1[k] + array1[i] + array1[j]
then let's call that incrementResult.
How many times is incrementResult called here? (log n)
for (int k = 1; k < array1.length; k = k * 2) {
// incrementResult
}
Lets call that loop3. Then how many times is loop3 called here? (n)
for (int j = 0; j < array1.length; j++) {
// loop 3
}
Let's call that loop2. Then, how many times is loop2 called here? (n)
for (int i = 0; i < array1.length; i++) {
// loop 2
}
Multiply all of those and you'll get your answer :)
That depends on the loops. For instance:
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
for (int k = 0; k < 10; k++) {
sum += i * j * k;
}
}
}
has complexity O(1), because the number of iterations does not depend on the input at all.
Or this:
for (int i = 0; i < n*n*n*n*n*n; i++) {
sum += i;
}
is O(n^6), even though there is a single loop.
What really matters is how many iterations each loop makes.
In your case, it is easy to see that each iteration of the innermost loop is O(1). How many iterations are there? How many times do you need to double a number until you reach n? If x is the number of iterations, we'd exit the loop at the first x such that k = 2^x > n. Can you solve this for x?
Each iteration of the second loop will do this, so the cost of the second loop is the number of iterations (which are easier to count this time) times the cost of the inner loop.
And each iteration of the first loop will do this, so the cost of the first loop is the number of iterations (which is also easy to count) times the cost of the second loop.
Overall, the runtime is the product of 3 numbers. Can you find them?

How to optimize this piece of code? [Processing inside nested for loops]

for (int i = 0,len=size-2; i < len; i++) {
for (int j = 1,leng = size-1; j < leng; j++) {
for (int k = 2; k < size; k++) {
if (i < j && j < k) {
sum = sum + Math.floor((a[i] + a[j] + a[k]) / (a[i] * a[j] * a[k]));
}
}
}
}
I need this piece of code to run in atleast half of the current running time.Here, the array 'a' is of the type double. I am taking inputs via the reader class. How to achieve a faster run time?
Your nested loops do nothing but iterate unless the condition i < j && j < k is satisfied. But the middle and inner loops start their iterations at the same initial value every time, regardless of the values of the outer loop indexes. For example, when i is 5, the middle loop still starts at 1 and the inner one still starts at 2, even though they can know that they will not perform any useful work for those values.
Start each loop iterating from a more useful point. You will save much useless index arithmetic and many vain index comparisons. In fact, if you do it properly then you shouldn't need to perform any index comparisons at all.
Details, such as they are, are left as an exercise. I've probably offered too much help already.
You can rewrite 1/(x*y*z)as 1*(1/x)*(1/y)*(1/z). Multiplying is faster than dividing. You can precalculate array of reciprocal values as ra[i] = 1/a[i]. There can be further optimizations, but it depends on what values there can be, You did not answer that question.
With this code there will not be any need of an if statement:
x is always inferior to y which is always inferior to z
for (int x = 0; x < size - 2; x++)
for(int y = x + 1; y < size - 1; y++)
for(int z = y + 1; z < size; z++)
sum += Math.floor((a[x] + a[y] + a[z]) / (a[x] * a[y] * a[z]));

I'm trying to reverse an array line by line

To clarify, this IS a homework assignment. I'm merely looking for advice, I'm not looking for someone to do my homework for me.
I've already done the first half. It uses two arrays to print an Asterisk design (in this case, the letter 'S'. That works fine. Then, I skip two lines and print the design but flipped (so each line is reversed). It seems to be working fine, but when I run the program, it prints two S's and the second one isn't reversed. Any ideas of what I'm doing wrong?
public class Design {
public static void main (String [] args) {
char [] array = new char [150];
for (int index = 0; index < array.length; index ++)
{
array [index] = '#';
}
int [] indexNumbers = {
0,1,2,3,4,5,6,7,8,9,10,20,30,40,50,
60,70,71,72,73,74,75,76,77,78,79,89,99,109,119,129,139,140,
141,142,143,144,145,146,147,148,149
};
for (int i = 0; i < indexNumbers.length; i++)
{
array [indexNumbers[i]] = ' ';
}
for (int index = 0; index < array.length; index ++)
{
if (index % 10 == 0 && index > 0)
System.out.println();
System.out.print (array[index]);
}
//Now, to reverse the letter
System.out.println();
System.out.println();
int lines = 5;
for (int i = 0; i< array.length; i++){
if (i >= lines)
lines += 10;
char temp = array [i];
array [i] = array [lines - i - 1];
array [lines - i - 1] = temp;
}
for (int index = 0; index < array.length; index ++)
{
if (index % 10 == 0 && index > 0)
System.out.println();
System.out.print (array[index]);
}
}
}
EDIT: Yeah... the design is in spaces, everything else is asterisks.
your reversing is a bit confused.... makes it easier if you do it in two loops.
for (int row = 0; row < (array.Length / 10); row++)
{
for (int col = 0; col < 5; col++)
{
int rowStart = row * 10;
int rowEnd = rowStart + 9;
char temp = array[rowStart + col];
array[rowStart + col] = array[rowEnd - col];
array[rowEnd - col] = temp;
}
}
First, why don't you use String[] or char[][]? Instead you are using a simple array to put multiple lines within. This makes your code confuse and brittle.
To swap an array, the rule is generally simple: Get the first and the last line and swap them. Get the second and the second last, and swap them, get the third and the third last and swap them... Until you get to the middle. This will be much easier if you have an array where each element is a line (like in an String[] or in an char[][]).
If you need to keep the idea of a simple char[] where each 10-char block is a line, simply swap each 10-char block like I stated above.
If you don't want to change the general behaviour of your program, this is the problematic block:
int lines = 5;
for (int i = 0; i< array.length; i++){
if (i >= lines)
lines += 10;
char temp = array [i];
array [i] = array [lines - i - 1];
array [lines - i - 1] = temp;
}
You are not swapping lines here, instead you are swapping chars. This way, your if is not checking and skipping lines, but is instead checking and skipping chars.
This is better:
int lines = array.length / 10;
for (int i = 0; i<= lines / 2; i++){
for (int j = 0; j < 10; j++) {
char t = array[i * 10 + j];
array[i * 10 + j] = array[(lines - i - 1) * 10 + j];
array[(lines - i - 1) * 10 + j] = t;
}
}
So..
First of all, start by printing '#' instead of ' ', and '.' instead of '#'. You will see more clearly what's going on.
Second, you have a problem in the reverse, you are actually not reversing anything, the way you calculate the index lines - i - 1 is wrong. The good way is (i / 10) * 10 + (10 - (i % 10)) -1. Yep, is kinda horrible, but if you want that in one line, using a one-dimension array, there it is. Now it's up to you to understand it, and integrate it in your code ;)

Categories

Resources