calculate sum recursive from a stack - recursion

Why is the below code printing "6" ? I would have expected "13" as a result.
void testSum(){
Stack<Integer> myStack = new Stack();
myStack.add(3);
myStack.add(4);
myStack.add(6);
System.out.println(calculateSum(myStack, 0));
}
Integer calculateSum(Stack<Integer> myStack, int sum) {
if (!myStack.empty()) {
sum = sum + myStack.pop();
calculateSum(myStack, sum);
}
return sum;
}

What mangusta said is correct.
You could do something like this too:
static void testSum(){
Stack<Integer> myStack = new Stack();
myStack.add(3);
myStack.add(4);
myStack.add(6);
System.out.println(calculateSum(myStack));
}
static Integer calculateSum(Stack<Integer> myStack) {
if (!myStack.empty())
return myStack.pop() + calculateSum(myStack);
return 0;
}

sum is passed by value. If you want to imitate passing by reference, you may create a wrapper class for integer, like below:
class IntWrapper
{
int n;
}
and modify your code accordingly:
static void testSum(){
Stack<Integer> myStack = new Stack();
myStack.add(3);
myStack.add(4);
myStack.add(6);
System.out.println(calculateSum(myStack, new IntWrapper()));
}
static Integer calculateSum(Stack<Integer> myStack, IntWrapper sum) {
if (!myStack.empty()) {
sum.n = sum.n + myStack.pop();
calculateSum(myStack, sum);
}
return sum.n;
}

Related

How to return an array using .C interface to R

I have this simple bit of code:
void test(int *testvec, int *testlen, int *testres) {
for (int i = 0; i < *testlen; i++){
testres[i]=0;
if (testvec[i] < 0){
testres[i] = -1;}
else if (testvec[i] == 0){
testres[i] = 0;}
else {testres[i] = 1;}
}
}
}
When I pass
testresult = function (testvec, len){
signC = .C("signC", as.integer(testvec), as.integer(length(testvec)), as.integer(testvector("integer"), length(testvec)))
return (signC)
}
testvec = c(1,2,-3,0,2)
It seems that nothing has been processed.
I am pretty new to C and I can't understand how to assign a value to an array dynamically within the contest of .C interface within R.
Thank you for your help.
.C interface functions can’t return values. If you want to modify values in C, you need to pass a vector of sufficient size into the function, and write into that vector:
sign = function (testvec) {
sign_c = integer(length(testvec))
.C("signC", as.integer(testvec), length(testvec), sign_c)
sign_c
}

Hashing, can't insert to hash table

struct googlePlayApp{
string name;
string category;
double rating;
int reviews;
googlePlayApp *next;
};
void appInsert(googlePlayApp &newApp, int &cmps) {
int slot = hash1(newApp.name, HASH_SIZE);
int cmps1 = 1;
googlePlayApp *tmp = appHash[slot];
if (tmp == 0)
appHash[slot] = &newApp;
else
{
while(tmp->next != 0)
{
tmp = tmp->next;
cmps1++;
}
tmp->next = &newApp;
}
cmps += cmps1;
}
while (getline(inFile, inputLine)) {
googlePlayApp newApp;
readSingleApp(inputLine, newApp);
appInsert(newApp, cmps);
linesRead++;
}
My program stops on the 65th iteration of the while loop....
64th for the appInsert call...
Why can't I get this to work?
This is a program where it reads a data file and stores it in a hash table and collision dealt with open addressing....
updated question
bool appFind(const string &name, googlePlayApp &foundApp, int &cmps) {
// Implement this function
int slot = hash1(name);
int cmps1 = 1;
googlePlayApp *tmp = appHash[slot];
while(tmp && tmp->name != name)
{
cmps1++;
tmp = tmp->next;
}
cmps += cmps1;
if(tmp)
{
foundApp.name = appHash[slot]->name;
foundApp.category = appHash[slot]->category;
foundApp.rating = appHash[slot]->rating;
foundApp.reviews = appHash[slot]->reviews;
}
else return false;
}
this is my serach function and I'm trying to search if an app exists based on the data I stored from my code above. I'm trying to search it by the hash addresses, but it's not working...

volatile test did not meet its happen-before feature in JLS

Run main
public class ThreadTest {
volatile int p = 0, q = 0;
public void test() throws InterruptedException {
Thread writeThread = new Thread(){
public void run(){
while (!isInterrupted()) {
p++;
q++;
}
}
};
Thread readThread = new Thread(){
public void run(){
while (!isInterrupted()) {
//p should not be less than q
if(p<q){
System.out.println("happen before violation p = " + p + ";q = " + q);
}
}
}
};
writeThread.start();
readThread.start();
Thread.currentThread().sleep(2);
writeThread.interrupt();
readThread.interrupt();
}
public static void main(String[] args) throws InterruptedException {
new ThreadTest().test();
}
}
output
happen before violation p = 736;q = 827
happen before violation p = 4635;q = 4657
happen before violation p = 6421;q = 6440
happen before violation p = 8719;q = 8803
You should read p AFTER q for being sure that their values are in "not less than" order:
int q_value = q; // Read 'q' once
int p_value = p; // Read 'p' AFTER q
if(p_value < q_value) // ... happens-before violation
In that case volatile modifier is required only for q, and it can be omitted for p without constraints' violation.
In you original code nothing prevents the compiler from reading p BEFORE q. So readThread can see p value from 736-th iteration of the writeThread, but see q value from 827-th iteration.
Or readThread can see p value from the beginning of the 100-th iteration(that is, p=100), but see q value from the end of that iteration(that is, q=101).

Calculating Standard Deviation in Assignment

I have an assignment for my class that reads like this: Write a class called Stats. The constructor will take no input. There will be a method addData(double a) which will be used to add a value from the test program. Methods getCount(), getAverage() and getStandardDeviation() will return the appropriate values as doubles.
Here's what I have so far:
public class Stats
{
public Stats (double a)
{
a=0.0
}
public void addData(double a)
{
while (
sum=sum+a;
sumsq=sumsq+Math.pow(a,2)
count=count+1
}
public double getCount()
{
return count;
}
public double getAverage()
{
average=sum/count
return average;
}
public double getStandardDeviation()
{
private double sum=o;
private double count=0;
private double sumsq=0;
My problem is figuring out how to calculate the standard deviation using the variables I've defined.
Thanks guys!
You can't do this with the variables you defined. You need to keep the original data to be able to compute the formula
sigma = Math.sqrt( sum(Math.pow(x-mean, 2)) / count )
So,
(1) create private array or list into which you'll add your values in addData. That's all you need to do in addData.
(2) getCount = length of the list
(3) getAverage = sum of values in list / getCount()
(4) getStandardDeviation is something like
double avg = getAverage();
double cnt = getCount();
double sumsq = 0;
for (int i = 0; i < values.Count(); i++) {
sumsq += Math.pow(values[i] - avg, 2);
}
stdev = Math.sqrt(sumsq / cnt);

Recursively searching a tree to get the binary coding for a character

Hi im trying to figure out how to recursively search a tree to find a character and the binary code to get to that character. basically the goal is to go find the code for the character and then write it to a file. the file writer part i can do no problem but the real problem is putting the binary code into a string. while im searching for the character. please help!
this is the code for the recursive method:
public String biNum(Frequency root, String temp, String letter)
{
//String temp = "";
boolean wentLeft = false;
if(root.getString() == null && !wentLeft)
{
if(root.left.getString() == null)
{
temp = temp + "0";
return biNum(root.left, temp, letter);
}
if(root.left.getString().equals(letter))
{
return temp = temp + "0";
}
else
{
wentLeft = true;
temp = temp.substring(0, temp.length() - 1);
return temp;
}
}
if(root.getString() == null && wentLeft)
{
if(root.right.getString() == null)
{
temp = temp + "1";
return (biNum(root.right, temp, letter));
}
if(root.right.getString().equals(letter))
{
return temp = temp + "1";
}
else
{
wentLeft = false;
temp = temp.substring(0, temp.length() - 1);
return temp;
}
}
return temp;
}
and this is the Frequency class:
package huffman;
public class Frequency implements Comparable {
private String s;
private int n;
public Frequency left;
public Frequency right;
private String biNum;
private String leaf;
Frequency(String s, int n, String biNum)
{
this.s = s;
this.n = n;
this.biNum = biNum;
}
public String getString()
{
return s;
}
public int getFreq()
{
return n;
}
public void setFreq(int n)
{
this.n = n;
}
public String getLeaf()
{
return leaf;
}
public void setLeaf()
{
this.leaf = "leaf";
}
#Override
public int compareTo(Object arg0) {
Frequency other = (Frequency)arg0;
return n < other.n ? -1 : (n == other.n ? 0 : 1);
}
}
In your updated version, I think you should re-examine return biNum(root.left, temp, letter);. Specifically, what happens if the root node of the entire tree has a left child which is not a leaf (and thus root.left.getString() == null) but the value you seek descends from the right child of the root node of the entire tree.
Consider this tree, for example:
26
/ \
/ \
/ \
11 15
/ \ / \
/ B A \
6 5 6 9
/ \ / \
D \ C sp
3 3 4 5
/ \
E F
2 1
and trace the steps your function will follow looking for the letter C.
Perhaps you should consider traversing the entire tree (and building up the pattern of 1s and 0s as you go) without looking for any specific letter but taking a particular action when you find a leaf node?

Resources