I'm trying to figure out what constitutes an instruction in java code. In class lecture that I attended professor mentioned 7 things that can be constituted as instruction but. I am having trouble making out what.
assignment, access of array, return statement, addition multiplication subtraction,..
Here is a example code she gave out:
int sum = 0;
int i = 0;
while ( i < 3 ) {
sum += A[ i ];
i++;
}
she says there are total of 18 instructions in this java code but I only count 15. Could you guys clarify why this is.
I believe something is missed in the explanation what count as instruction
Taking this schema there would be twenty.
1) int sum = 0; // 1 assignment
2) int i = 0; // 1 assignment
3) while ( i < 3 ) { // 1 comparison
4) sum += A[ i ]; // 1 array access, 1 addition, 1 assignment --> sum = sum + A[i]
5) i++; // 1 addition, 1 assignment --> i = i + 1;
6) }
The lines 3-5 are executed three times.
Related
Here is a question from previous HackerEarth Challenge -
Roy has a matrix of size NxN. Rows and Columns are numbered from 0 to N-1.
jth column of ith row contains absolute difference between i and j.
In other words, Matrix[i][j] = abs(i-j) where 0 ≤ i, j < N.
Your task is to find sum of this matrix i.e.
sum = 0
for i=0 to N-1
for j=0 to N-1
sum += Matrix[i][j]
and here is my solution to this problem -
public static long getSum(int num, long acc) {
if (num == 1)
return acc;
long sum = 0;
for (int i = 0; i < num; i++) {
sum += i;
}
sum = sum * 2;
return getSum(num - 1, acc + sum);
}
But this function fails for large number like say anything greater than 4500. I get Stack Over Flow Error.
Here I have tried two things basically to keep the code optimized -
use tail recursion, and
keep running time of this function of order 'n'
So please tell me if I have achieved the two things here correctly. If yes what else can I do to optimize this code. Thanks for your help.
The matrix has very simple structure (I draw only top right half, bottom left is the same, mirrored)
0 1 2 3 4 5 ...
. 0 1 2 3 4 ...
. . 0 1 2 3 ...
. . . 0 1 2 ...
. . . . 0 1 ...
. . . . . 0 ...
It is clear that Kth row contains arithmetic progression 0..(N - K - 1), so it's sum is
Sk = (N - K - 1) * (N - K) / 2
and overall sum is (O(N) solution)
S = 2 * Sum[k = 0..N-1] (Sk)
Moreover, while sum of every row is 'triangular' number, sum of triangular numbers is 'Tetrahedral number', and there is closed formula, that leads to O(1) solution
S = 2 * ((N-1)*N*(N+1)/6) = N*(N+1)*(N-1)/3
Example: for N=4 S = 3*4*5/3 = 20
Tail recursion
Tail recursion does not protect you from stack overflow in Java. Some other languages can recognise tail-calls and optimize them during compilation so they do not extend the stack.
...tail call optimization is hard to do in the JVM because of the security model and the need to always have a stack trace available.
(From Does the JVM prevent tail call optimizations?)
It is however easy to replace tail recursions with a loop:
public static long getSum(int num, long acc) {
while (num > 1) {
long sum = 0;
for (int i = 0; i < num; i++) {
sum += i;
}
sum = sum * 2;
//set up values for next loop
num--;
acc += sum;
}
return acc;
}
Big-O
keep running time of this function of order 'n'
You have not achieved this. It is clear to see there are 2 nested loops over num, and num is decreasing, I think this makes it O(n log n)
Hello i am having a tough time trying to write a function that can create an array that holds integers, that equal my simple math problem.
my problem is not adding integers into the array but finding the correct integers that could add up to a math problem.
for example i have a simple math problem like: 10 + 10 = ? we know it equals 20
so i want my array to hold up to ten integers, that when added all together equal 20.
this is what i have been trying in code but not getting the results i want.
while (totalCount != answer
&& count < setCount) {
randomNumber = rand.nextInt((int) answer / 2) + 1;
if(count < setCount) {
sumOfBalloons.add(randomNumber);
totalCount += randomNumber;
count++;
}
if(totalCount > answer) {
count = 0;
totalCount = 0;
sumOfBalloons.clear();
}
}
i am trying to find random numbers that add up to the math problems answer so i can draw them on balloons. problem is i can never get ten numbers to equal the answer in my while loop.
does anyone know some way of doing something like this?
need array to hold 3 - 10 integers that equals my math problems answer.
** update on code thanks to the advice i received i managed to fix my while loop now it looks like this
had to post like this cause my rep is very low. sorry.
while (totalCount != answer) {
randomNumber = rand.nextInt((int) answer / 2) + 1;
if(totalCount + randomNumber > answer) {
randomNumber = rand.nextInt((int) answer - totalCount) + 1;
}
if(count + 1 == setCount) {
randomNumber = answer - totalCount;
}
if(count < setCount) {
sumOfBalloons.add(randomNumber);
totalCount += randomNumber;
count++;
}
if(totalCount > answer
|| totalCount == answer
&& count < setCount
|| totalCount != answer
&& count == setCount) {
count = 0;
totalCount = 0;
sumOfBalloons.clear();
}
}
this is what i got in my console from this code
Total count = 10
Total totalCount = 20
sumOfBalloons 0 = 2
sumOfBalloons 1 = 3
sumOfBalloons 2 = 3
sumOfBalloons 3 = 2
sumOfBalloons 4 = 1
sumOfBalloons 5 = 4
sumOfBalloons 6 = 2
sumOfBalloons 7 = 1
sumOfBalloons 8 = 1
sumOfBalloons 9 = 1
I think there are a few options here re: generating random numbers that sum to 20.
Here's one possible solution:
Create an array of length 4, for example.
Generate random number between 1 and 6 for each of the first 3 indices of your array.
At this point you'll have an array of the form: { 4, 5, 2, _ } (where our 4th element hasn't been chosen yet).
Sum our first 3 elements: 4 + 5 + 2 = 11. Determine 4th element by calculating 20 - current_total (11) = 9.
Set myArray[3] = 9;
A few things to note:
You may need to modify the range of possible random numbers ( 1-6 ) I've given. Consider what happens if the array we generate turns out to be { 2, 1, 2, _ }...then there's no digit that will ensure the elements sum to 20.
Another option is to use an arrayList instead of an array. The benefit to this is that you can keep adding elements to your arrayList until you either hit 20 (then you're done) or go over (in which case you delete the most recent element and begin adding again). You also won't need (or be able) to know the length of your arrayList in advance.
So I need to output a sum of factorials like 1!+2!...+n!=sum I found a way to get a single factorial but I don't know how to sum them together. This is my attempt at doing so:
System.out.println("Ievadiet ciparu");
Scanner in = new Scanner(System.in);
n = in.nextInt();
if ( n < 0 )
System.out.println("Ciparam jabut pozitivam.");
else
{
while (x>2){
for ( c = 1 ; c <= n ; c++ )
fact = fact*c;
sum=sum+fact;
n=n-1;
if (n==0) break;
}
System.out.println("Faktorialu summa "+sum);
Rather than have a loop 1-n and calculate each factorial elsewhere, I would accumulate the sum as you calculate the factorials - ie have two local variables; one for factorial and one for the sum:
long factorial = 1, sum = 0;
for (int i = 1; i <= n; i++) {
factorial *= i;
sum += factorial;
}
When tested with n = 5, sum is 153, which is correct: 1 + 2 + 6 + 24 + 120
Your problem was that the sum was outside the loop - you just needed braces like here.
Also, your while loop condition x < 2 will never change, so either the loop will never execute (if x > 1) or the loop will never terminate, because x is not changed within the loop.
hmmm my search for finding a recursive(via recursive method calling) version of these code still getting nowhere
`public static long factorialSum(long n){
long x = n;
for(int i = 1; i < n; i++){
x = (n-i)*(1+x);
}
return x;
}`
if you just look at the problem more closely you'll see you can do it in linear time, the trick is in (n-1)! + n! = (n-1)!*(1 + n), to understand this more deeply i recommend add (n-2)! just to see how it grows.
Say that length=11 and that I want to subtract 2 from it on every cycle until it reaches 1. Is my code for the for method correct? And what would it be for a while loop?
for(int i =length ; i!=1; i-=2)
EDIT: This was the question. To solve it I made an if statement that if the length%2==1 I would use the for loop listed above. Then I am going to write an else stating modifying the code above to stop at 0. Does this make sense?
The sum of all digits at odd positions (right-to-left starting at 1 as the right-most digit) of a numeric input. (For example, if the input is 432677, the sum would be 7 + 6 + 3 = 16.)
For is not a method. It's a language construct. Just a nitpick.
Almost. If i starts out even you'll never end. Use:
for(int i =length ; i>1; i-=2)
If the 1 is inclusive, you could try:
for(int i = length; i >= 1; i -= 2){ ... }
Or
for(int i = length; i > 0; i -= 2){ ... }
If the 1 is exclusive, you could try:
for(int i = length; i > 1; i -= 2){ ... }
Is there a nicer way to do the count I'm doing below?
I'm sure this must be possible with modulus or something. I'm looking for someway to manipulate i instead of using the extra variable x. (to beautify this).
Here is the long way round:
int MAX = 4;
int x = 0;
for (int i = 0; i < 50; i++) {
System.out.print(x);
if(x++; == MAX)
x = 0;
}
Expected outcome:
// 0 1 2 3 0 1 2 3 0 1 2 3 0 1 2 3 .. etc
for (int i = 0; i < 50; i++) { System.out.print(i % MAX); }
Yes, you can just do x = i % MAX;
Your code is pretty clear as is. While modulus % might save you a few keystrokes, it's not necessary. Natural human expression is generally preferred, especially if your coding at 4am or coming back to your code 6 months later.