Trying to remember crazy java array trickery - java

I'm trying to remember some crazy java array trickery I came over in a certification exam. This was a couple of years ago and I'm a bit fuzzy on the details.
It goes something like this:
int[] a = {4,2,1}
int i = a[ a[0] = 0 ]
This is of course total bollocks but the question tried to show that an array saves it's state when it's accessed. So if I actually got it right I expected 'i' to equal 4 still, but as shown when run 'i' gets the new value 0.
The certification was for java 6 and I checked thats still what I'm running here (1.6.0_51 to be precise). Is it changed in some way or is my memory just completely off?
Thank you for indulging me in this, in reality, rather meaningless question :)
edit: I would never ever suggest to use or use this sort of weird thing in real code.

what about official documentaion?
http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.13.1
15.13.1 read it =)

int i = a[ a[0] = 0 ]
is equal to -
a[0] = 0 // this assignment change the index 0 value to 0 - {0,2,1}
int i = a[ 0 ] // this 0 comes from assignment operation which is assigned value.
so the result is 0.

Related

Is this faster than 2 for loops for iterating through a 2D array, or is it the same speed?

for (int x = 0; x < height; x++) {
map[x][y] = new Plot(x, y, "map");
if (x == 199 && y < 199) {
x = 0;
y++;
}
}
I have this code here that I set up to create a 2D array of 200x200 objects for a map, and I would like to know if it is the same speed or if it indeed runs faster. I'm trying to optimize the array creation.
Thanks!
EDIT : assuming Y starts at 0, and height is 200 always
EDIT 2 : Thank you to everybody who answered :D Yes I could've created something to test it, but eh
The generated code will not be faster - the instructions generated will be almost identical; in fact, when compiler optimisations are turned on, the compiler might struggle to optimise either loop effectively because it can't recognise them as simple loops.
The vast majority of the execution time will be spent allocating the new memory, and writing pointers to the map arrays. In fact, one potential improvement does leap out: at the moment, you're accessing the map arrays like this:
map[0][0]
map[1][0]
map[2][0]
...
map[0][1]
map[1][1]
map[2][1]
...
map[0][2]
and so on.
This is undesirable, because the addresses are far apart in memory. It is always better to access memory in such a way that addresses that are close to each other are accessed near to each other in time, because this is much friendlier to the cache.
So if you were to swap the order of iteration round (e.g. [0][0], [0][1], [0][2], ... [1][0], [1][1], [1][2]...) then you might find your code runs quicker - or you might not; it all depends on the architecture of the machine.
Just think about it, if you have i.e. 200*200 array and you want to put some new instance into each of it, you have to do it in every single "cell" = 40000 cells. You cant be better than that no matter the optimization.
Even if you dont have for-cycle and do it with
x[0][0] = ...
x[0][1] = ...
You still have to write 40000 commands

I need help in trying to fully understand the concept of recursion [duplicate]

This question already has answers here:
Understanding recursion [closed]
(20 answers)
Closed 5 years ago.
Before you get started, I have used google countless times in hopes of searching for a very brief and simple explanation of how recursion works when it has a return type. But I guess I'm not as bright as I thought since i still cant understand it quite well.
Take the following code snippet (in java) as an example
public static int recursion(int num)
{
int result;
if (num == 1)
result = 1;
else
result = recursion(num - 1) + num;
return result;
}
I grabbed this code from my professors lecture slide and he said this will return 1 + 2 + 3 + ... + num.
I just need someone to explain how the process works in the method that i provided. Maybe a step by step approach might help me understand how recursion works.
recursion(5) = recursion(4) + 5, let's figure out recursion(4) and come back to this later
recursion(4) = recursion(3) + 4, let's figure out recursion(3) and come back to this later
recursion(3) = recursion(2) + 3, ...
recursion(2) = recursion(1) + 2, ...
recursion(1) = 1, we know this!
recursion(2) = 1 + 2, now we can evaluate this
recursion(3) = (1+2) + 3, and now we can evaluate this
recursion(4) = (1+2+3) + 4, ...
recursion(5) = (1+2+3+4) + 5, the answer to our original question
Note: Without knowing recursion(1), we'd have gone to 0, -1, -2, and so on until forever. This known quantity is called the base case and it is a requirement for recursion.
Basically when there is a stack buildup for each item that is created beyond the last iteration. (Where num=1)
When n>1 the if statement kicks the iteration to the else which 'saves' the result in a stack and calls the same funtion again with n-1
what this effectively does is keep calling the same function until you hit your designated 'base case' which is n=1
Recursion is all about solving a problem by breaking it into a smaller problem. In your case, the question is "how do you sum the numbers from 1 to n", and the answer is "sum up all the numbers from 1 to n-1, and then add n to it". You've phrased the problem in terms of a smaller or simpler version of itself. This often involves separating out a "base case"—an irreducibly simple problem with a straightforward answer.
public static int recursion(int num)
{
int result;
if (num == 1)
result = 1; // Base case: the sum of the numbers from 1 to 1 is 1.
else
result =
// This is the sum of numers from 1 to n-1. The function calls itself.
recursion(num - 1)
// Now add the final number in the list, and return your result.
+ num;
return result;
}
You're defining the unsolved problem in terms of itself, which works because the solution always involves either the base case or a simpler version of the problem (which itself further involves either the base case or an even simpler version of the problem).
I'll close with one of my favorite jokes:
How do you explain recursion to a five-year-old?
You explain recursion to a four-year-old, and wait a year.
Going by the classic code example you posted. if you call your method like so with number passed in as 5:
recursion(5);
In layman terms just to understand, your function will create & call another copy of your function in the else block as below:
recursion(4);
and then
recursion(3);
recursion(2);
recursion(1);
as the number keeps decrementing.
Finally it will call the if part in the final copy of the method as num will satisfy num == 1. So from there it starts unwinding & returning each value to the previous call.
As each method call has its own stack to load method local variables on, there will be n number of stacks created for n calls. When the deepest call in recursion is made, then the stacks start unwinding. Hence recursion achieved
The most important thing however to note is that there is a base-most call in your code, which is done at 1 just because you have the check if (num == 1). Else it would be infinite recursion & of course a fatal & wrong program to write. The base-most call is from where its called as stack unwinding in recursion terms.
Example: Finding the factorial of a number is the most classic examples of recursion.
Performance: Do look into recursion vs iteration and recursion vs looping to see what are the performance impacts of recursion

Clarification on Mystery

I have just started taking a Computer Science class online and I am quite new to Programming(a couple of week's worth of experience). I am working on an assignment, but I do not understand what a mystery method is. I have yet to find an answer that I can wrap my head around online, in my textbook, or from my professor. Any explanation using this code as an example would also be greatly appreciated!
This is the equation where I saw it in:
public static void mystery1(int n) {
System.out.print(n + " ");
if (n > 0) {
n = n - 5;
}
if (n < 0) {
n = n + 7;
} else {
n = n * 2;
}
System.out.println(n);
}
If anybody can help, that would be amazing! Thank you!
First of all, I voted your question up because I think it's a valid question for someone who is just beginning in computer programming, and I think that some people fail to understand the significance and purpose of Stack Overflow, which is to help programmers in times of need.
Secondly, I think that the couple of users that have commented on your post are on the right track. I have personally never heard of a mystery method, so I think the goal here is for you to simply figure out what the method does. In this case, the method takes a parameter for int 'n'. This means that if, at any point in the application, the 'mystery1()' method is called, an integer will have to be passed as the variable.
Let's say that a user enters the number '9'. The method would be called by the code mystery1(9). This would then run the first part of the 'if' statement, because n is greater than 0. So, n would be equal to n - 5, or 9 - 5, which is 4. (So, n=4.)
I hope my answer was somewhat helpful to you. Take care.
Your assignment is probably to figure out what this method does. More specifically, what does it print to the screen. I'll walk you through how to figure this out.
You have a function, also called a methood, called mystery1. A function is just a named block of code that you can use throughout other pieces of code. This function takes an integer argument called n. Let's assume n=12 for this example.
The first thing that happens in your function when it is called is that n is printed out via the System.out.print method. Notice that it prints a blank space after it. Notice also at the end it prints another value of n that gets assigned within the method. So the method is going to print "12 ?" without the double quotes. The question mark is what we have to figure out. The code says if n > 0 then n = n-5. Since 12 is greater than 0, n gets the new value of 7. The next if statement says if n is less than 0, n gets assigned n+7. But it is not less than zero, it is 7 at this point, so we move to the else statement. In this statement n gets multiplied by 2 which is 14. So the last statement prints 14.
So for an input value of 12 this method prints:
12 14
I hope this helps. If not, please give more detail about your assignment and what you don't understand about my explanation.
The point of this kind of exercise is that you are given a method, but they don't tell you what it does (hence the "mystery"). You are supposed to figure out what it does on your own (like "solving the mystery"). It doesn't mean that the method is special in any way.
Say I give you a "mystery" method like this:
public static void mystery(int n) {
System.out.println(n+1);
}
You would "solve the mystery" by telling me that this method prints out the number that comes after n. Nothing else is special here.
In the example you gave, your job would be to tell me why the method prints out 0 0 when n = 0, or 6 2 when n = 6.
I think the usage of the term "mystery method" is rather misleading, as it has clearly made you (and many, many, many others) believe that something about these methods is special and something that you need to learn about. There isn't anything special about them, and there's nothing to learn.
I think a lot of people would understand this better if instructors just said "tell me what this method does" instead of trying treat students like 5 year olds by saying "Here's a mystery method (ooh, fancy and entertaining). Can you play detective and solve the mystery for me?"

post increment behaviour [duplicate]

This question already has answers here:
What is x after "x = x++"?
(18 answers)
Closed 9 years ago.
i have small doubt.why the below code is printing value i=2.
int i=2;
i=i++;
System.out.println(i);
can someone please explain me what is happening in line no 2.
so there is no meaning here of doing ++ here?
Thanks
i=i++;
Because first the assignment happens, then the increment applies.
Something like:
first i gets 2, then ++ operation happens, but results won't be re-assigned to i, so i value will remain as 2.
i = i++; first evaluates the i++ expression, which increments i and evaluates to the value of i prior to the increment. Since you immediately assign to i this value, it resets the value of i so the increment appears to never have happened. i = ++i; would cause the other behavior.
When you are telling i=i++; you are telling the computer to assign i to i, and after that, increment i's value, but it will not affect i, because i's value is 2.
The correct way to do it should be i=++i; meaning, add 1 to i before assigning it to i, or you could simply use i++;
Thanks to all for helping me in understanding the things which was of great value.
I found somewhere nice post on this.
I got the answer from the suggestion given by stackoverflow forum only but there was some clear explanation missing what I feel.
Miljen Mikic suggested link is not working and saying page not found.
Some Clear explanation given for problem below is
int a=2, b=2;
int c = a++/b++;
System.out.println(c);
disassembles to the following.
0:iconst_2 ; [I]Push the constant 2 on the stack[/I]
1:istore_1 ; [I]Pop the stack into local variable 1 (a)[/I]
2:iconst_2 ; [I]Push the constant 2 on the stack, again[/I]
3:istore_2 ; [I]Pop the stack into local variable 2 (b)[/I]
4:iload_1 ; [I]Push the value of a on the stack[/I]
5:iinc1, 1 ; [I]Add 1 to local variable 1 (a)[/I]
8:iload_2 ; [I]Push the value of b on the stack[/I]
9:iinc2, 1 ; [I]Add 1 to local variable 2 (b)[/I]
12:idiv ; [I]Pop two ints off the stack, divide, push result[/I]
13:istore_3 ; [I]Pop the stack into local variable 3 (c)[/I]
14:return
which help me understand much better.
Please add to this If I am wrong in my point.
Thanks for all your answers.

How to reduce an algorithm into smaller parts so I can scale it?

I have updated this question(found last question not clear, if you want to refer to it check out the reversion history). The current answers so far do not work because I failed to explain my question clearly(sorry, second attempt).
Goal:
Trying to take a set of numbers(pos or neg, thus needs bounds to limit growth of specific variable) and find their linear combinations that can be used to get to a specific sum. For example, to get to a sum of 10 using [2,4,5] we get:
5*2 + 0*4 + 0*5 = 10
3*2 + 1*4 + 0*5 = 10
1*2 + 2*4 + 0*5 = 10
0*2 + 0*4 + 2*5 = 10
How can I create an algo that is scalable for large number of variables and target_sums? I can write the code on my own if an algo is given, but if there's a library avail, I'm fine with any library but prefer to use java.
One idea would be to break out of the loop once you set T[z][i] to true, since you are only basically modifying T[z][i] here, and if it does become true, it won't ever be modified again.
for i = 1 to k
for z = 0 to sum:
for j = z-x_i to 0:
if(T[j][i-1]):
T[z][i]=true;
break;
EDIT2: Additionally, if I am getting it right, T[z][i] depends on the array T[z-x_i..0][i-1]. T[z+1][i] depends on T[z+1-x_i..0][i-1]. So once you know if T[z][i] is true, you only need to check one additional element (T[z+1-x_i][i-1]) to know if T[z+1][i-1] will be true.
Let's say you represent the fact whether T[z][i] was updated by a variable changed. Then, you can simply say that T[z][i] = changed && T[z-1][i]. So you should be done in two loops instead of three. This should make it much faster.
Now, to scale it - Now that T[z,i] depends only on T[z-1,i] and T[z-1-x_i,i-1], so to populate T[z,i], you do not need to wait until the whole (i-1)th column is populated. You can start working on T[z,i] as soon as the required values are populated. I can't implement it without knowing the details, but you can try this approach.
I take it this is something like unbounded knapsack? You can dispense with the loop over c entirely.
for i = 1 to k
for z = 0 to sum
T[z][i] = z >= x_i cand (T[z - x_i][i - 1] or T[z - x_i][i])
Based on the original example data you gave (linear combination of terms) and your answer to my question in the comments section (there are bounds), would a brute force approach not work?
c0x0 + c1x1 + c2x2 +...+ cnxn = SUM
I'm guessing I'm missing something important but here it is anyway:
Brute Force Divide and Conquer:
main controller generates coefficients for say, half of the terms (or however many may make sense)
it then sends each partial set of fixed coefficients to a work queue
a worker picks up a partial set of fixed coefficients and proceeds to brute force its own way through the remaining combinations
it doesn't use much memory at all as it works sequentially on each valid set of coefficients
could be optimized to ignore equivalent combinations and probably many other ways
Pseudocode for Multiprocessing
class Controller
work_queue = Queue
solution_queue = Queue
solution_sets = []
create x number of workers with access to work_queue and solution_queue
#say for 2000 terms:
for partial_set in coefficient_generator(start_term=0, end_term=999):
if worker_available(): #generate just in time
push partial set onto work_queue
while solution_queue:
add any solutions to solution_sets
#there is an efficient way to do this type of polling but I forget
class Worker
while true: #actually stops when a stop work token is received
get partial_set from the work queue
for remaining_set in coefficient_generator(start_term=1000, end_term=1999):
combine the two sets (partial_set.extend(remaining_set))
if is_solution(full_set):
push full_set onto the solution queue

Categories

Resources