A good bank of recursion solutions in C/C++/Java/C# [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 6 years ago.
Improve this question
I saw this question, but the answers there are not very relevant.
A friend needs a bank of solved recursion problems to help him study for a test tomorrow.
He learned the issue theoretically, but is having problems grasping how to actually solve recursion problems. Do you know a good source of solved recursion problems (preferably in C, but can be in a C-style language as well) available on the net?
Note - examples in functional languages will not help much here. My friend is in a study race to pass his test tomorrow, and I'm sure switching languages will just confuse him at this point (it might be educational on other, less stressed times).

One of the best ways to learn recursion is to get some experience in a functional programming language such as Haskell or Lisp or Scheme.
So finding recursive problems can be reduced to finding some problems and answers related to functional programming languages. Here's an example 99 lisp problems.
It really only takes 5 minutes to learn Scheme or Lisp so you can get started with examples right away for the test tomorrow you mentioned.
Another great way to learn recursion is to get some practice in mathematical proofs involving induction.
Key concepts relating to recursion:
With recursion you don't need to know how to solve the problem. You just need to know 2 things. 1) how to solve the smallest instance of the problem, and 2) how to break it up into smaller parts.
Equivalently, you just have to keep in mind that you need: 1) a base case and 2) a recursive case.
The base case handles 1 single instance of what you want to do with smallest input.
The recursive case breaks the problem into a subproblem. Eventually this subproblem will reduce to the base case.
Example:
//1+...+n = n*n(+1)/2 = sumAll(n):
int sumAll(int x)
{
if(x == 0) //base case
return 0;
else
return sumAll(x-1) + x; //recursive case
}
It is important to understand that the base case is not hard to figure out. It just has to exist. Here is an equivalent solution for x> 0:
//1+...+n = n*n(+1)/2 = sumAll(n):
int sumAll(int x)
{
if(x == 1) //base case
return 1;
else
return sumAll(x-1) + x; //recursive case
}

This article explains recursion and has some simple C examples for traversing linked list and binary tree

This is going to sound like a very lame answer, but recursion is a paradigm that's often very hard to grasp at the first for beginners. It will take more than a day's meditation on the subject for your friend to firmly grasp the concept.
You may want to have him peruse Project Euler for a potential direction to study.

I think Haskell's syntax is great for thinking recursively, because the pattern matching construct makes the base case and the recursive case so obvious. Translating this into another language is then fairly straightforward.
sumAll [] = 0
sumAll (x:xs) = x + sumAll xs
To understand this, you really only need to know that
[] represents an empty list,
(x:xs) splits a list into a head (x) and a tail (xs)
You don't need to learn all of Haskell (which is, let's face it, hard) - but doing some of the basics certainly helps you think in recursion.

In c /c++ language a function can call itself and this case is called Recursion. Mainly recursion have two cases:
Base case.
recursive case.
and we have some recursive categories like as...
Liner recursion
Binary recursion
Nested recursion
Mutual recursion
Tail recursion
Here take a example to discuss recursion ...
// a recursive program to calculate NcR //
#include <stdio.h>
int ncr(int x,int y)
{
if(y>x)
{
printf("!sorry,the operation can't processed.");
getch();
exit(1);
}
else if(y==0 ||y==x) //base case
{
return(1);
}
else
{
return(ncr(x-1,y-1)+ncr(x-1,y)); //recursive case
}
}

Read SICP(Structure and Interpretation of Computer Programs)

#include<iostream>
using namesspace std;
int E(int x);
int main()
{
int x;
cout << E(x) << endl;
return 0;
}
int E(int x)
{
return x ? (x % 10 + E(x/10)) : 0;
}

Related

Does bitwise inclusive OR with assignment operator have advantages over typical assignment in java?

When looking at some code on one or another git, sometimes I can see that devs use bitwise inclusive OR compound assignment operator (|=) where simple assignment would be enough. Unfortunately, I don't have any code with this solution at hand, so I'll try to describe it as best I can.
Let's say, we have the following code in java:
boolean found = false;
for (String s : stringSet) {
if (s == null || s.equals("")) {
found |= true; // <== this line
}
}
if (!found) {
System.out.println("No interesting string found");
}
I ask only about the pointed line. Why people do it this way? I understand that we can have a really great amount of data, billions or trillions to iterate over. But does the pointed line changes the efficiency so dramatically? Would it be noticeably slower for a lot of data, if I change it to simple assignment: found = true;?
I don't exclude the possibility that not a speed is the main argument, but it seemed most meaningful to me.
And yes, I know this code can be converted to method or streams, but it's only a simplification of a code where it would be far more complicated etc. We can assume that before the pointed line (or even before if), there are tons of code that do something meaningful. Please, don't suggest something like "use streams instead", because I know how to java advanced already. I'd like to understand the phenomenon of this somehow enigmatic solution using bitwise inclusive OR.

Best way to think about implementing recursive methods? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 2 years ago.
Improve this question
so I was wondering if any of you can give me tips regarding this. I've been doing some challenges like (the classical) making a method to calculate the nth number of a Fibonacci sequence using a single recursive call (aka. avoid return fibo(n-1) + fibo(n-2);).
I really scratched my head on that one and ended up looking at the solution that made use of a helper method -
public static int fibonacci(int n) {
if (n < 2) {
return n;
}
return fibonacci_helper(n, 1, 0);
}
public static int fibonacci_helper(int n, int previous, int current) {
if (n < 1) {
return current;
}
return fibonacci_helper(n - 1, current, previous + current);
}
I'm not really sure what approach one takes to solve questions like that quickly (without first solving it iteratively and translating that to a tail recursion, which takes a lot of time).
Would really appreciate some tips, thanks in advance.
You need to first decide if the question needs a recursive solution.Typically a recursion is needed when a present solution is dependent on some previous (already calculated) solution.
To start with , first check on small inputs(call them corner/base cases) . Then build on it (manually by dry running) on small inputs.Once you have done this, you can , in most cases , figure out the recurrence relation(like here in fibonacci).Test its validity , and then using base cases and current recurrence relation , write a recursion.
For example , the given code searches for a node with particular value in a binary tree(check out if you don't know what binary tree is: https://en.wikipedia.org/wiki/Binary_tree)
bool search(Node root,int val){
if(root==null)//base case 1
return false;
if(root.value==val)//base case 2
return true;
return(search(root.left,val)||search(root.right,val));//recursing left and right subtrees for looking out for the value
}
Play with it on paper, and try discover hidden computations that are redone needlessly. Then try to avoid them.
Here you have f(n) = f(n-1) + f(n-2); obviously f(n-1) = f(n-2) + f(n-3) redoes f(n-2) needlessly, etc. etc. etc.. What if you could do the two at once?
Have f2(n) return two values, for n and for (n-1); then you do (in pseudocode)
f(n) = let { (a,b) := f2(n-1) } in (a+b)
Now you have two functions, none is yet defined, what good does it do? Turn this f into f2 as well, so it returns two values, not one, just as we expect it to do:
f2(n) = let { (a,b) := f2(n-1) } in (a+b,a)
And voila, a recursive definition where a is reused.
All that's left is to add some corner/edge/base case(s), and check for the off-by-1 errors.
Or even better, reverse the time arrow, start from the base case, and get your iterative version for free.
Recursion is a tool which is there to help us, to make problem solving easier.
The area you're thinking of is called Dynamic Programming. The way it works is that the solution to the larger problem you're trying to solve is composed of solutions to smaller problems, and the time complexity can be reduced dramatically if you keep those solutions and reuse them, instead of calculating them multiple times. The general approach to take is to consider how the problem can be broken down, and which solutions to the smaller problems you'll need to remember in order to solve it. In this case, you could do it in linear time and linear space by keeping all the results in an array, which should be pretty easy to think of if you're looking for a DP solution. Of course that can be simplified because you don't need to keep all those numbers, but that's a separate problem.
Typically, DP solutions will be iterative rather than recursive, because you need to keep a large number of solutions available to calculate the next larger one. To change it to use recursion, you just need to figure out which solutions you need to pass on, and include those as the parameters.

fizzbuzz - can it be shorter?

WARNING:I'm not asking for a better code, I'm asking for a shorter code for HackerRank just to learn what can be done to shorten it.
I'm newbie to Java and was trying out this FizzBuzz problem:
Write a program that prints the numbers from 1 to 100. But for multiples of three print >“Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which >are multiples of both three and five print “FizzBuzz”.
I wrote my solution as short as possible.
class Solution{
public static void main(String[]b){
for(int i=1;i<101;i++){
String a=(i%3==0)?(i%5==0)?"FizzBuzz":"Fizz":(i%5==0)?"Buzz":i+"";
System.out.println(a);}}}
and I got a 3.6 score. But obviously there's room to improve because some people wrote it with 27 characters less. How is that possible ? Any suggestions? I don't really care about the ranks, I just wanna know what I'm missing.
EDIT: So with your help, I made it like this:
class Solution{public static void main(String[]b){for(int i=1;i<101;i++){System.out.println((i%3==0)?(i%5==0)?"FizzBuzz":"Fizz":(i%5==0)?"Buzz":i);}}}
and it seems I got rid of 14 characters. God knows what the other people did to lose 13 more characters. Anyway, thanks.
What about something like:
for(int i=0;i++<100;System.out.println((i%3>0?"":"Fizz")+(i%5>0?i%3>0?i:"":"Buzz")))
Warning: this code is just an exercise of trying to make the code shorter. It is neither good or readable as normal code should try to be!
Yes, it is possible to make it even shorter. Proof: According to the leaderboard, the highest score for java is 7.00.
How? Spoiler: identifier(s), parentheses, line breaks, pre/post increment. The conditions may be written as i%3>0 or the opposite like i%3<1.
class S{public static void main(String[]a){for(int i=0;++i<101;)System.out.println(i%3>0?i%5>0?i:"Buzz":"Fizz"+(i%5>0?"":"Buzz"));}}
It may not be getting significantly shorter yet, most likely due to the boilerplate code for main and print method. Based on everything suggested on this QA so far, it is possible to achieve at least 6.90 in Java if not the current max which is 7.00.
For example,
class S{public static void main(String[]a){for(int i=0;++i<101;)System.out.println(i%3>0?i%5>0?i:"Buzz":i%5>0?"Fizz":"FizzBuzz");}}
If we are open to try out other languages, we may wish to try JS with caution/advisory.
Many more approaches have been discussed here and here.
Java, C, C++, C#, Python, Ruby, R, none of the submissions in these languages reached the top score yet which is 16.0. It leads us to the question, which submission led to the top score? The answer is bash scripting. Proof: leaderboard for bash
How? The hint has been kindly provided by the author of the top submission, Byron Formwalt at here.
If we are new to bash scripting, we may wish to get started with few resources mentioned here, here, and here.
Disclaimer: Even though this may be suitable for the purpose of the getting higher score in hackerrank or just for exercise, it may not be a good practice for Best_coding_practices. There are many scopes for improvement in this post. Suggestions are welcome. Acknowledgements/Thanks.
It just becomes an argument to migrate to Kotlin!
fun fizzBuzz(number: Int) = when {
number.divisibleBy(3) and number.divisibleBy(5) -> "Fizz-Buzz"
number.divisibleBy(3) -> "Fizz"
number.divisibleBy(5) -> "Buzz"
else -> number.toString()
}
fun Int.divisibleBy(number: Int) = this % number == 0
fun main() {
(1..100).forEach {
println(fizzBuzz(it))
}
}
function fizzBuzz(n) {
for (i = 1; i <= n; i++) {
let result = "";
if (i % 3 === 0) result += "Fizz";
if (i % 5 === 0) result += "Buzz";
if (i % 7 === 0) result += "Foo";
console.log(result || i);
}
}
fizzBuzz(105);
It will check every condition, if all are true then all will be added together as well as it works with the single true condition as well as two true conditions.

Replacing recursion with while-loops and accumulators

I'd like to calculate the height and set the resizeWeight of a JSplitPane that may contain other JSplitPanes and other Components as well. The concept right now looks the following (warning: snippet, not a fully functional code fragment; I only need guidelines for rewriting the recursive invocations with a while-loop using accumulators, not a fully functional solution code).
splitPane.setResizeWeight(calculateComponentHeight(splitPane.getTopComponent()) / calculateNewSplitPaneHeight(splitPane));
...
private double calculateNewSplitPaneHeight(JSplitPane sp) {
return calculateComponentHeight(sp.getTopComponent()) + calculateComponentHeight(sp.getBottomComponent());
}
private double calculateComponentHeight(Component c) {
if (c instanceof JSplitPane) {
return calculateNewSplitPaneHeight((JSplitPane) c);
}
return (double) c.getHeight();
}
As I may not know the level of embeddedness of the split panes, what can be a practical approach towards resolving such recursions?
And yes, I know, splitPane.getPreferredSize().height and splitPane.getTopComponent().getPreferredSize().height give me the answers I need without any recursive invocations. This is question is merely here to work one's brain on recursions and loops.
You can emulate recursion with a stack: How can you emulate recursion with a stack?
I once made a try on emulating a simple Fibonacci-like recursion:
f(n) = f(n-1) + f(n-2) + array[n]
The result is placed on a GitHub and is written according to the explanations in the linked answer. I should admit that it was a more complex task than I first imagined.

Is it good practice to use the xor operator for boolean checks? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I personally like the exclusive or, ^, operator when it makes sense in the context of boolean checks because of its conciseness. I much prefer to write
if (boolean1 ^ boolean2)
{
//do it
}
than
if((boolean1 && !boolean2) || (boolean2 && !boolean1))
{
//do it
}
but I often get confused looks from other experienced Java developers (not just the newbies), and sometimes comments about how it should only be used for bitwise operations.
I'm curious as to the best practices regarding the usage of the ^ operator.
You can simply use != instead.
I think you've answered your own question - if you get strange looks from people, it's probably safer to go with the more explicit option.
If you need to comment it, then you're probably better off replacing it with the more verbose version and not making people ask the question in the first place.
I find that I have similar conversations a lot. On the one hand, you have a compact, efficient method of achieving your goal. On the other hand, you have something that the rest of your team might not understand, making it hard to maintain in the future.
My general rule is to ask if the technique being used is something that it is reasonable to expect programmers in general to know. In this case, I think that it is reasonable to expect programmers to know how to use boolean operators, so using xor in an if statement is okay.
As an example of something that wouldn't be okay, take the trick of using xor to swap two variables without using a temporary variable. That is a trick that I wouldn't expect everybody to be familiar with, so it wouldn't pass code review.
I think it'd be okay if you commented it, e.g. // ^ == XOR.
You could always just wrap it in a function to give it a verbose name:
public static boolean XOR(boolean A, boolean B) {
return A ^ B;
}
But, it seems to me that it wouldn't be hard for anyone who didn't know what the ^ operator is for to Google it really quick. It's not going to be hard to remember after the first time. Since you asked for other uses, its common to use the XOR for bit masking.
You can also use XOR to swap the values in two variables without using a third temporary variable.
// Swap the values in A and B
A ^= B;
B ^= A;
A ^= B;
Here's a Stackoverflow question related to XOR swapping.
if((boolean1 && !boolean2) || (boolean2 && !boolean1))
{
//do it
}
IMHO this code could be simplified:
if(boolean1 != boolean2)
{
//do it
}
With code clarity in mind, my opinion is that using XOR in boolean checks is not typical usage for the XOR bitwise operator. From my experience, bitwise XOR in Java is typically used to implement a mask flag toggle behavior:
flags = flags ^ MASK;
This article by Vipan Singla explains the usage case more in detail.
If you need to use bitwise XOR as in your example, comment why you use it, since it's likely to require even a bitwise literate audience to stop in their tracks to understand why you are using it.
I personally prefer the "boolean1 ^ boolean2" expression due to its succinctness.
If I was in your situation (working in a team), I would strike a compromise by encapsulating the "boolean1 ^ boolean2" logic in a function with a descriptive name such as "isDifferent(boolean1, boolean2)".
For example, instead of using "boolean1 ^ boolean2", you would call "isDifferent(boolean1, boolean2)" like so:
if (isDifferent(boolean1, boolean2))
{
//do it
}
Your "isDifferent(boolean1, boolean2)" function would look like:
private boolean isDifferent(boolean1, boolean2)
{
return boolean1 ^ boolean2;
}
Of course, this solution entails the use of an ostensibly extraneous function call, which in itself is subject to Best Practices scrutiny, but it avoids the verbose (and ugly) expression "(boolean1 && !boolean2) || (boolean2 && !boolean1)"!
If the usage pattern justifies it, why not? While your team doesn't recognize the operator right away, with time they could. Humans learn new words all the time. Why not in programming?
The only caution I might state is that "^" doesn't have the short circuit semantics of your second boolean check. If you really need the short circuit semantics, then a static util method works too.
public static boolean xor(boolean a, boolean b) {
return (a && !b) || (b && !a);
}
As a bitwise operator, xor is much faster than any other means to replace it. So for performance critical and scalable calculations, xor is imperative.
My subjective personal opinion: It is absolutely forbidden, for any purpose, to use equality (== or !=) for booleans. Using it shows lack of basic programming ethics and fundamentals. Anyone who gives you confused looks over ^ should be sent back to the basics of boolean algebra (I was tempted to write "to the rivers of belief" here :) ).
!= is OK to compare two variables. It doesn't work, though, with multiple comparisons.
str.contains("!=") ^ str.startsWith("not(")
looks better for me than
str.contains("!=") != str.startsWith("not(")

Categories