public static int someFunc(int a, int b){
while(a <=b){
a+= 1;
return a;
}
return b;
}
so i was expecting it to return the new value over and over but it didnt, once i executed the code and saw for myself that, i realised it had something to do with pass by value or by reference which is something i dont really understand! can someone explain?
The immediate problem is that return returns! Nothing after it can be executed. You can't have a meaningful loop with an unconditional return in it.
As far as the other, no. That's not the issue as you return the new value of a. The a you passed in remains unchanged which is the pass by reference/value you speak of. Java is pass by value.
public class JHelp {
public static void main(String...args) {
JHelp j = new JHelp();
int a = 1;
System.out.print(j.f(a));
System.out.print(a);
}
int f(int a ) {
a += 1;
return a;
}
}
Will give you an output of:
21
because the return instruction exits the code hence the methods done its job it doenst need to iterate again once it reaches the return instruction, i however would have done it if the return instruction wasnt reached.
This is my first question ever at StackOverFlow:
I am studying to interviews with the help of "Cracking the code interview" (5th Edition) book,
and I was solving the next problem:
Implement a function to check if a binary tree is a binary search tree (Q 4.5 pg 86).
Before we move on, I would like just to remind you the difference between a Binary search tree to a simple Binary tree:
A Binary search tree imposes the condition that for all nodes, the left children are less than or equal to the current node, which is less than all the right nodes.
So one of the solution the book offers is to scan the tree with In-Order traversal and on the fly to check if every node we visit is greater then the last one, and it assumes the tree can't have a duplicate values:
public static int last_printed = Integer.MIN_VALUE;
public static boolean checkBST(TreeNode n) {
if(n == null) return true;
// Check / recurse left
if (!checkBST(n.left)) return false;
// Check current
if (n.data <= last_printed) return false;
last_printed = n.data;
// Check / recurse right
if (!checkBST(n.right)) return false;
return true; // All good!
}
Now, up here everything is good, but then the book quotes :
If you don't like the use of static variables, then you can tweak this code to use a wrapper class for the integer, as shown below:
Class WrapInt {
public int value;
}
After reading on wrapper class all over here and in other websites I just couldn't come to the conclusion, why and how should I use the wrapper class here instead of the static variable?
This is a mechanism whereby you can create an instance of WrapInt, and pass it around. You then expose the value only to code that should know about it, instead of a public static non-final variable that can be accessed and changed from anywhere.
The reason you have the wrapper class is because Java primitives are pass-by-value; passing around an int and then updating it wouldn't propagate the change through the rest of your system.
This would look like this:
public static boolean checkBST(TreeNode n) {
WrapInt counter = new WrapInt();
return checkBST(n, counter);
}
public static boolean checkBST(TreeNode n, WrapInt counter) {
if(n == null) return true;
// Check / recurse left
if (!checkBST(n.left, counter)) return false;
// Check current
if (n.data <= counter.value) return false;
counter.value = n.data;
// Check / recurse right
if (!checkBST(n.right, counter)) return false;
return true; // All good!
}
Here you go:
public static boolean checkBST(TreeNode n) {
WrapInt i = new WrapInt();
i.value = INTEGER.MIN_VALUE;
doCheckBST(n, i);
}
private static boolean doCheckBST(TreeNode n, WrapInt last_printed) {
if(n == null) return true;
// Check / recurse left
if (!checkBST(n.left, last_printed)) return false;
// Check current
if (n.data <= last_printed.value) return false;
last_printed.value = n.data;
// Check / recurse right
if (!checkBST(n.right, last_printed)) return false;
return true; // All good!
}
If there is the possibility that there will run 2+ sorts at the same time. The static will be used for both sortings. Both sortings have access to the same static value.
//thread 1
Sorting A = new Sorting(5,9,8);
A.sort();
//thread 2
Sorting B = new Sorting(999,100,7);
B.sort();
We cant predict which/how the thread is processed.
So this could end up in
A.checkBST(5) // last_printed = 5
B.checkBST(999) // last_printed = ??
B.checkBST(100) // last_printed = ??
A.checkBST(9) // last_printed = ??
...
...
If every sort instance has his own last_printed, you won't have synchronisation issues.
I think this is more formal way how to avoid of public static context property (e.g for thread safety), which is not optimal approach in object programming. But there are standard Primitive wrapper classes as: https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html
which can be used instead of new classes. Generally Wrapper pattern can be more general than your example: What is a wrapper class?
The problem with static variable is that another class/method or something can modify it and it will break your code.
Can you make it like that:
Class WrapInt {
public int value=Integer.MIN_VALUE;
}
public static boolean checkBST(TreeNode n,WrapInt lastPrinted) {
if(n == null) return true;
// Check / recurse left
if (!checkBST(n.left,lastPrinted)) return false;
// Check current
if (n.data <= lastPrinted.value) return false;
lastPrinted.value = n.data;
// Check / recurse right
if (!checkBST(n.right,lastPrinted)) return false;
return true; // All good!
}
Doing a course on concurrent programming.
As an example we have
final class Counter {
private AtomicInteger value;
public long getValue() {
return value.get();
}
public long increment() {
int v;
do {
v = value.get();
}
while(!value.compareAndSet(v, v+1));
return v+1;
}
}
Why would you use compareAndSet in this case and not incrementAndGet ?
Thanks
Here the the implementation of AtomicInteger.incrementAndGet() method from the JDK version I have on my machine:
/**
* Atomically increments by one the current value.
*
* #return the updated value
*/
public final int incrementAndGet() {
for (;;) {
int current = get();
int next = current + 1;
if (compareAndSet(current, next))
return next;
}
}
As you can see, the implementation is very similar to yours.
PS: Why do you compute v+1 twice?
From the Java docs,
compareAndSet :
Atomically sets the value to the given
updated value if the current value ==
the expected value.
public final boolean compareAndSet(V expect,
V update)
incrementAndGet :
Atomically increments by one the
current value.
public final int incrementAndGet()
Since compareAndSet basically does the same, I can't think about a single reason to use this handwritten implementation of increment.
In your case, the Class Counter implements the value increment in it's own way, and JDK AtomicInteger.incrementAndGet() also implements it in it's own way. But they also use the CAS method compareAndSet(V expect ,V newValue).
So these two kinds of implementation have no difference. The minor difference between the two ways is the circulation form. BTW, answer for compute v+1 twice.
while(!value.compareAndSet(v, v+1));----v+1 is the parameter for function , and realize value to add 1;
return v+1; v+1 is the return value;
I'm trying to use a priority queue in my code, and for some reason when I remove the objects, they aren't in order. Do you know what i"m doing wrong?
Here's my code:
the contructor:
recordedsong = new PriorityQueue<recordedNote>(50, new Comparator<recordedNote>()
{
public int compare(recordedNote n1, recordedNote n2)
{
long l = n1.rt()-n2.rt();
int i = (int)l;
return i;
}
});
where each recordedNotehas a long value that is returned my the method rt().
But when I call
while (!Song.isEmpty())
{
recordedNote temp = (recordedNote)Song.remove();
and then print temp.rt() for each one, all the numbers are out of order. And not just like reverse order, but all over the place, like 1103, 0, 500, 0, 220 orders like that.
Can you see if there's anything wrong with my contructor?
Thanks!
remove should work, and in fact it does work fine in a small example program that I created to help answer this question:
import java.util.Comparator;
import java.util.PriorityQueue;
public class TestPriorityQueue {
public static void main(String[] args) {
long[] noteTimes = {1103L, 0L, 500L, 0L, 220L, 1021212812012L};
PriorityQueue<RecordedNote> noteQueue = new PriorityQueue<RecordedNote>(10,
new Comparator<RecordedNote>() {
#Override
public int compare(RecordedNote o1, RecordedNote o2) {
Long time1 = o1.getTime();
Long time2 = o2.getTime();
// uses Long's built in compareTo method, so we
//don't have to worry as much about edge cases.
return time1.compareTo(time2);
}
});
for (int i = 0; i < noteTimes.length; i++) {
RecordedNote note = new RecordedNote(noteTimes[i]);
System.out.println(note);
noteQueue.add(note);
}
System.out.println();
while (noteQueue.size() > 0) {
System.out.println(noteQueue.remove());
}
}
}
class RecordedNote {
private long time;
public RecordedNote(long time) {
this.time = time;
}
public long getTime() {
return time;
}
#Override
public String toString() {
return "[Time: " + time + "]";
}
}
So this begs the question, why isn't it working for you? Myself, I don't see enough coherent code in your question to be able to answer this. We're not sure what is Song as I don't see this declared as a class or a variable, and I also don't see where you're using your PriorityQueue variable, recordedsong, anywhere. So I suggest you do the same thing as I: create a small compilable runnable program that we can run and modify and that demonstrates your problem, an http://sscce.org
I guess there is a possibility for i getting 0. So modify compare method so that it returns a positive value rather than the result.
Reading the API docs for PriorityQueue, it states the following:
The Iterator provided in method iterator() is not guaranteed to traverse the elements of the priority queue in any particular order. If you need ordered traversal, consider using Arrays.sort(pq.toArray()).
My guess is that remove() is not obligated to follow the natural ordering, either.
I'm pretty new to the idea of recursion and this is actually my first attempt at writing a recursive method.
I tried to implement a recursive function Max that passes an array, along with a variable that holds the array's size in order to print the largest element.
It works, but it just doesn't feel right!
I have also noticed that I seem to use the static modifier much more than my classmates in general...
Can anybody please provide any general tips as well as feedback as to how I can improve my code?
public class RecursiveTry{
static int[] n = new int[] {1,2,4,3,3,32,100};
static int current = 0;
static int maxValue = 0;
static int SIZE = n.length;
public static void main(String[] args){
System.out.println(Max(n, SIZE));
}
public static int Max(int[] n, int SIZE) {
if(current <= SIZE - 1){
if (maxValue <= n[current]) {
maxValue = n[current];
current++;
Max(n, SIZE);
}
else {
current++;
Max(n, SIZE);
}
}
return maxValue;
}
}
Your use of static variables for holding state outside the function will be a source of difficulty.
An example of a recursive implementation of a max() function in pseudocode might be:
function Max(data, size) {
assert(size > 0)
if (size == 1) {
return data[0]
}
maxtail = Max(data[1..size], size-1)
if (data[0] > maxtail) {
return data[0]
} else {
return maxtail
}
}
The key here is the recursive call to Max(), where you pass everything except the first element, and one less than the size. The general idea is this function says "the maximum value in this data is either the first element, or the maximum of the values in the rest of the array, whichever is larger".
This implementation requires no static data outside the function definition.
One of the hallmarks of recursive implementations is a so-called "termination condition" which prevents the recursion from going on forever (or, until you get a stack overflow). In the above case, the test for size == 1 is the termination condition.
Making your function dependent on static variables is not a good idea. Here is possible implementation of recursive Max function:
int Max(int[] array, int currentPos, int maxValue) {
// Ouch!
if (currentPos < 0) {
raise some error
}
// We reached the end of the array, return latest maxValue
if (currentPos >= array.length) {
return maxValue;
}
// Is current value greater then latest maxValue ?
int currentValue = array[currentPos];
if (currentValue > maxValue) {
// currentValue is a new maxValue
return Max(array, currentPos + 1, currentValue);
} else {
// maxValue is still a max value
return Max(array, currentPos + 1, maxValue);
}
}
...
int[] array = new int[] {...};
int currentPos = 0;
int maxValue = array[currentPos] or minimum int value;
maxValue = Max(array, currentPos, maxValue);
A "max" function is the wrong type of thing to write a recursive function for -- and the fact you're using static values for "current" and "maxValue" makes your function not really a recursive function.
Why not do something a little more amenable to a recursive algorithm, like factorial?
"not-homework"?
Anyway. First things first. The
static int[] n = new int[] {1,2,4,3,3,32,100};
static int SIZE = n.length;
have nothing to do with the parameters of Max() with which they share their names. Move these over to main and lose the "static" specifiers. They are used only once, when calling the first instance of Max() from inside main(). Their scope shouldn't extend beyond main().
There is no reason for all invocations of Max() to share a single "current" index. "current" should be local to Max(). But then how would successive recurrences of Max() know what value of "current" to use? (Hint: Max() is already passing other Max()'s lower down the line some data. Add "current" to this data.)
The same thing goes for maxValue, though the situation here is a bit more complex. Not only do you need to pass a current "maxValue" down the line, but when the recursion finishes, you have to pass it back up all the way to the first Max() function, which will return it to main(). You may need to look at some other examples of recursion and spend some time with this one.
Finally, Max() itself is static. Once you've eliminated the need to refer to external data (the static variables) however; it doesn't really matter. It just means that you can call Max() without having to instantiate an object.
As others have observed, there is no need for recursion to implement a Max function, but it can be instructive to use a familiar algorithm to experiment with a new concept. So, here is the simplified code, with an explanation below:
public class RecursiveTry
{
public static void main(String[] args)
{
System.out.println(Max(new int[] {1,2,4,3,3,32,100}, 0, 0));
}
public static int Max(int[] n, int current, int maxValue)
{
if(current < n.Length)
{
if (maxValue <= n[current] || current == 0))
{
return Max(n, current+1, n[current]);
}
return Max(n, current+1, maxValue);
}
return maxValue;
}
}
all of the static state is gone as unnecessary; instead everything is passed on the stack. the internal logic of the Max function is streamlined, and we recurse in two different ways just for fun
Here's a Java version for you.
public class Recursion {
public static void main(String[] args) {
int[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
System.out.println("Max: " + max(0, data));
}
public static int max(int i, int[] arr) {
if(i == arr.length-1) {
return arr[i];
}
int memo = max(i+1, arr);
if(arr[i] > memo) {
return arr[i];
}
return memo;
}
}
The recurrence relation is that the maximum element of an array is either the first element, or the maximum of the rest of the array. The stop condition is reached when you reach the end of the array. Note the use of memoization to reduce the recursive calls (roughly) in half.
You are essentially writing an iterative version but using tail recursion for the looping. Also, by making so many variables static, you are essentially using global variables instead of objects. Here is an attempt at something closer to a typical recursive implementation. Of course, in real life if you were using a language like Java that doesn't optimize tail calls, you would implement a "Max" function using a loop.
public class RecursiveTry{
static int[] n;
public static void main(String[] args){
RecursiveTry t = new RecursiveTry(new int[] {1,2,4,3,3,32,100});
System.out.println(t.Max());
}
RecursiveTry(int[] arg) {
n = arg;
}
public int Max() {
return MaxHelper(0);
}
private int MaxHelper(int index) {
if(index == n.length-1) {
return n[index];
} else {
int maxrest = MaxHelper(index+1);
int current = n[index];
if(current > maxrest)
return current;
else
return maxrest;
}
}
}
In Scheme this can be written very concisely:
(define (max l)
(if (= (length l) 1)
(first l)
(local ([define maxRest (max (rest l))])
(if (> (first l) maxRest)
(first l)
maxRest))))
Granted, this uses linked lists and not arrays, which is why I didn't pass it a size element, but I feel this distills the problem to its essence. This is the pseudocode definition:
define max of a list as:
if the list has one element, return that element
otherwise, the max of the list will be the max between the first element and the max of the rest of the list
A nicer way of getting the max value of an array recursively would be to implement quicksort (which is a nice, recursive sorting algorithm), and then just return the first value.
Here is some Java code for quicksort.
Smallest codesize I could get:
public class RecursiveTry {
public static void main(String[] args) {
int[] x = new int[] {1,2,4,3,3,32,100};
System.out.println(Max(x, 0));
}
public static int Max(int[] arr, int currPos) {
if (arr.length == 0) return -1;
if (currPos == arr.length) return arr[0];
int len = Max (arr, currPos + 1);
if (len < arr[currPos]) return arr[currPos];
return len;
}
}
A few things:
1/ If the array is zero-size, it returns a max of -1 (you could have another marker value, say, -MAX_INT, or throw an exception). I've made the assumption for code clarity here to assume all values are zero or more. Otherwise I would have peppered the code with all sorts of unnecessary stuff (in regards to answering the question).
2/ Most recursions are 'cleaner' in my opinion if the terminating case is no-data rather than last-data, hence I return a value guaranteed to be less than or equal to the max when we've finished the array. Others may differ in their opinion but it wouldn't be the first or last time that they've been wrong :-).
3/ The recursive call just gets the max of the rest of the list and compares it to the current element, returning the maximum of the two.
4/ The 'ideal' solution would have been to pass a modified array on each recursive call so that you're only comparing the first element with the rest of the list, removing the need for currPos. But that would have been inefficient and would have bought down the wrath of SO.
5/ This may not necessarily be the best solution. It may be that by gray matter has been compromised from too much use of LISP with its CAR, CDR and those interminable parentheses.
First, let's take care of the static scope issue ... Your class is defining an object, but never actually instantiating one. Since main is statically scoped, the first thing to do is get an object, then execute it's methods like this:
public class RecursiveTry{
private int[] n = {1,2,4,3,3,32,100};
public static void main(String[] args){
RecursiveTry maxObject = new RecursiveTry();
System.out.println(maxObject.Max(maxObject.n, 0));
}
public int Max(int[] n, int start) {
if(start == n.length - 1) {
return n[start];
} else {
int maxRest = Max(n, start + 1);
if(n[start] > maxRest) {
return n[start];
}
return maxRest;
}
}
}
So now we have a RecursiveTry object named maxObject that does not require the static scope. I'm not sure that finding a maximum is effective using recursion as the number of iterations in the traditional looping method is roughly equivalent, but the amount of stack used is larger using recursion. But for this example, I'd pare it down a lot.
One of the advantages of recursion is that your state doesn't generally need to be persisted during the repeated tests like it does in iteration. Here, I've conceded to the use of a variable to hold the starting point, because it's less CPU intensive that passing a new int[] that contains all the items except for the first one.