public class Temp{
static int add(int m,int n){
if(m==0)
return n+1;
else if(n==0)
return add(m-1,1);
else
return add(m-1,add(m,n-1));
}
public static void main(String[] a){
System.out.println(add(3,3));
}
}
I am not able to understand what this function is achieving. The output for (2,2) is 7 and for (3,3) is 61. I understand that the value of n decreases then value of m and then the base case is reached but how can I get the output without running the code for a given input?
This is the Ackermann function (https://en.wikipedia.org/wiki/Ackermann_function), an example of non-primitive recursive function.
What do you mean by getting the output without running the code for a given input?
If you wish to compute a given value, I suggest you use a HashMap as a cache so that you can reuse already computed values. Also, I think you'd better use BigInteger values if you use m values greater than 3.
Related
Is there a way to input a parameter (besides the seed) into a user-defined RNG in R? I understand the basics of RNGkind("user") and creating a RNG with RCPP, but I am unsure if I can defined a parameter can be used in this process. For instance, say I would want to create a function, say RNG_parameter(seed=123, multiplier=3) that simply multiplies my initialization table by a number (I wish to do more, but this example will hopefully make it easier). Essentially, this will create my user_unif_init but it will allow multiple parameters to be called. Is this possible to do? Whenever I try to create an exported function in my RCPP, it then says that: 'user_unif_rand' not in load table.
Edited: Example added (standard RNG example from Random.user)
I am looking for a way to add a parameter into a function which initializes the table, I am not sure if it can be done with user_unif_init or if I need to find another way to do it. I tried looking at Seeding a user supplied random number generator in R as similar example but RNGkind("user") wouldn't work for me when I added an exported function into the file.
#include <R_ext/Random.h>
static Int32 seed;
static double res;
static int nseed = 2;
double * user_unif_rand()
{
seed = 69069 * seed + 1;
res = seed * 2.32830643653869e-10;
return &res;
}
void user_unif_init(Int32 seed_in, int multiplier) {
seed[1]= seed_in;
seed[2]= seed_in* multiplier;
}
int * user_unif_nseed() { return &nseed; }
int * user_unif_seedloc() { return (int *) &seed; }
public class Main {
public static void main(String[] args) {
printDollars(7);
}
public static void printDollars(int n) {
if (n > 1) {
printDollars(n - 1);
}
for (int i = 0; i < n; i++) {
System.out.print("$");
}
}
}
How does the value of n get incremented after printDollars() function gets executed.
The value of n is actually decreased by one on every iteration.
When 7 enters the function for the first time, the logic checks whether the value is more than 1. Since 7 > 1, the value (7-1)=6 enters the next level of the recursive function. It happens several times (6 to 5, 5 to 4, etc), until the function reaches one.
One important thing to note, if you're just starting with recursion is that the dollar signs start to be printed when the code got to the point where n =1, since to reach that part of code, the machine has to get over all of the recursive calls. So the first '$' printed is actually one that comes from the call with n=1, then n=2, etc.
I suggest you try printing out n instead of '$', so that you get a clearer understanding of the way it works.
I tried memoizing the value of 'x', but it gives wrong answer.
Uncommenting the commented part will give wrong answer.
//vi dp(1000001,-1);
int f(int x,int cnt,const vi &v){
if(x<0)return INT_MAX;
if(x==0)return cnt;
//if(dp[x]!=-1)return dp[x];
int ans=INT_MAX;
for(const int &i:v){
ans=min(ans,f(x-i,cnt+1,v));
}
//dp[x]=ans;
return ans;
}
Without memoization, this is working fine.
Your function has 2 states and you are storing value for just one state. Suppose you want the value of f(2,2,v). Your dp[2] array can contain any values among f(2,x,v) where x can be any value of "cnt".
I am doing a leetcode problem.
A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).
How many possible unique paths are there?
So I tried this implementation first and got a "exceeds runtime" (I forgot the exact term but it means the implementation is slow). So I changed it version 2, which use a array to save the results. I honestly don't know how the recursion works internally and why these two implementations have different efficiency.
version 1(slow):
class Solution {
// int res[101][101]={{0}};
public:
int uniquePaths(int m, int n) {
if (m==1 || n==1) return 1;
else{
return uniquePaths(m-1,n) + uniquePaths(m,n-1);
}
}
};
version2 (faster):
class Solution {
int res[101][101]={{0}};
public:
int uniquePaths(int m, int n) {
if (m==1 || n==1) return 1;
else{
if (res[m-1][n]==0) res[m-1][n] = uniquePaths(m-1,n);
if (res[m][n-1]==0) res[m][n-1] = uniquePaths(m,n-1);
return res[m-1][n] + res[m][n-1];
}
}
};
Version 1 is slower beacuse you are calculating the same data again and again. I'll try to explain this on different problem but I guess that you know Fibonacci numbers. You can calculate any Fibonacci number by following recursive algorithm:
fib(n):
if n == 0 then return 0
if n == 1 then return 1
return fib(n-1) + fib(n-1)
But what actually are you calculating? If you want to find fib(5) you need to calculate fib(4) and fib(3), then to calculate fib(4) you need to calculate fib(3) again! Take a look at the image to fully understand:
The same situation is in your code. You compute uniquePaths(m,n) even if you have it calculated before. To avoid that, in your second version you use array to store computed data and you don't have to compute it again when res[m][n]!=0
I wanted to have a linked list of nodes with below structure.
struct node
{
string word;
string color;
node *next;
}
for some reasons I decided to use vector instead of list.my question is that is it possible to implement a vector which it's j direction is bounded and in i direction is unlimited and to add more two strings at the end of my vertex.
in other words is it possible to implement below structure in vector ?
j
i color1 color2 …
word1 word2 …
I am not good with C/C++, so this answer will only be very general. Unless you are extremely concerned about speed or memory optimization (most of the time you shouldn't be), use encapsulation.
Make a class. Make an interface which says what you want to do. Make the simples possible implementation of how to do it. Most of the time, the simplest implementation is good enough, unless it contains some bugs.
Let's start with the interface. You could have made it part of the question. To me it seems that you want a two-dimensional something-like-an-array of strings, where one dimension allows only values 0 and 1, and the other dimension allows any non-genative integers.
Just to make sure there is no misunderstanding: The bounded dimension is always size 2 (not at most 2), right? So we are basicly speaking about 2×N "rectangles" of strings.
What methods will you need? My guesses: A constructor for a new 2×0 size rectangle. A method to append a new pair of values, which increases the size of the rectangle from 2×N to 2×(N+1) and sets the two new values. A method which returns the current length of the rectangle (only the unbounded dimension, because the other one is constant). And a pair of random-access methods for reading or writing a single value by its coordinates. Is that all?
Let's write the interface (sorry, I am not good at C/C++, so this will be some C/Java/pseudocode hybrid).
class StringPairs {
constructor StringPairs(); // creates an empty rectangle
int size(); // returns the length of the unbounded dimension
void append(string s0, string s1); // adds two strings to the new J index
string get(int i, int j); // return the string at given coordinates
void set(int i, int j, string s); // sets the string at given coordinates
}
We should specify what will the functions "set" and "get" do, if the index is out of bounds. For simplicity, let's say that "set" will do nothing, and "get" will return null.
Now we have the question ready. Let's get to the answer.
I think the fastest way to write this class would be to simply use the existing C++ class for one-dimensional vector (I don't know what it is and how it is used, so I just assume that it exists, and will use some pseudocode; I will call it "StringVector") and do something like this:
class StringPairs {
private StringVector _vector0;
private StringVector _vector1;
private int _size;
constructor StringPairs() {
_vector0 = new StringVector();
_vector1 = new StringVector();
_size = 0;
}
int size() {
return _size;
}
void append(string s0, string s1) {
_vector0.appens(s0);
_vector1.appens(s1);
_size++;
}
string get(int i, int j) {
if (0 == i) return _vector0.get(j);
if (1 == i) return _vector1.get(j);
return null;
}
void set(int i, int j, string s) {
if (0 == i) _vector0.set(j, s);
if (1 == i) _vector1.set(j, s);
}
}
Now, translate this pseudocode to C++, and add any new methods you need (it should be obvious how).
Using the existing classes to build your new classes can help you program faster. And if you later change your mind, you can change the implementation while keeping the interface.