## context free – Eliminating left recursion using a loop construct

I’m trying to merge a little bit of theory with a little bit of practice. I’m writing a parser-generator that generates a top-down parser based on a given grammar.

I’d like to handle left- and right recursion properly, so they would each yield the “left-recursive” and “right-recursive” tree respectively (I’m not sure if left- and rightmost derivative would be a correct term here, that would mean the whole tree). This is very important for PEG, where the associativity and order of operations is encoded in the tree. The problem is that top-down parsers can’t deal with left-recursion directly.

I know the elimination rule for left-recursion, which is given a rule in the form

$$A rightarrow A alpha_1 | dots | A alpha_n | beta_1 | dots | beta_m$$

We can rewrite it into right-recursion using the following 2 rules:

$$A rightarrow beta_1 A’ | dots | beta_m A’ \ A’ rightarrow alpha_1 A’ | dots | alpha_n A’ | varepsilon$$

This is fine for the “formal” part, but the grammar became right-recursive. To me this rule seems like it’s just using right-recursion to essentially loop parts of the grammar.

So my idea was to introduce a looping construct that would account for folding the tree left. If I introduce a new postfix operator `*` that would mean repeating the construct 0 or more times, would the following also be a valid equivalent left-recursion elimination for A?

$$A rightarrow (beta_1 | dots | beta_m) (alpha_1 | dots | alpha_n)^*$$

Note that since the repetition can occur 0 times, this should account for the “epsilon-case” too.

I have a strong suspicion that this is equivalent, as I did something very similar when manually parsing left-associative operators in math expressions. I’d like confirmation before introducing it in a general tool.

## recursion – Perform sum of squared numbers without using for loop

There is a base case… it’s the line `if x > 0 {`

compare to the for loop version

`for x=input: x>0: x=x-1 {`

`findSquareSum(input,a,x)` sets x=input

`if x > 0 {` is the condition check

`findSquareSum(x-1, a, iteration)` decrements x

also consider the modified fucntion

``````func findSquareSum(x int, a ()int, iteration int) {
var num int
if x <= 0 { return }

fmt.Scanf("%d", &num)
if num > 0 {
a(iteration-1) += num * num
}
findSquareSum(x-1, a, iteration)
}
``````

now it should look more like the base cases we are to seeing. It should also be clear that this is equivalent to the askers version (unless my go syntax is wrong!)

similarly

``````func readTest(x int, a ()int){
var input int
if x <= 0 { return }
fmt.Scanf("%d", &input)
findSquareSum(input,a,x)
}
``````

## recursion – How to perform AND on binary “recursive repeating sequences”?

Suppose, we have a two binary sequences, encoded as “recursive repeating sequences” (I don’t know exactly how to name them). Each sequence can contain other sequences and has number related to how many times this sequence is repeated, or can contain a bit either 0 or 1. Following image describes it visually:

On this image repetition is denoted by lower index number nearby ending bracket. The bits need to be expanded are denoted by regular size font.

Each sequence can produce binary sequence (sequence of bits), when we expand it.

The questions are:

1. Can we create a algorithm, that performs AND on two recursive repeating sequences, without expanding both of them? (The algorithm should produce third recursive repeating sequence, such when we expand it, it is AND on both expanded input sequences).
2. If the answer for first question is true, how such algorithm will look (for example in pseudo code) ?

Note: In practice, the numbers responsible for repetition may be very large, so expansion of whole sequence is not practical in terms of computation – but if algorithm will need to do it partially, it may be accepted.

## recursion – Recursive Palindrome in JavaScript

Would someone review this code, and confirm that it is indeed recursive? I’m learning computer science and going through different types of algorithms. Right now, I’m focusing on recursion want to ensure that this recursive palindrome method is truly recursive. I’ve passed six different strings, three that were palindromes and three that were not. The method worked as expected, but again; I’m really looking for a cross-check to ensure this is recursive.

``````function obtainFirstCharacterOfString(str) {
const firstChar = str.slice(0, 1);
return firstChar;
}

function obtainLastCharacterOfString(str) {
const lastChar = str.slice(-1);
return lastChar;
}

function recursivePalindrome(str) {
// Base case
if (str.length === 0 || str.length === 1) {
return 'String is not a palindrome';
}

const firstChar = obtainFirstCharacterOfString(str);
const lastChar = obtainLastCharacterOfString(str);

if (firstChar === lastChar) {
if (str.slice(1, -1).length === 1) {
return 'String is a palindrome';
} else {
return recursivePalindrome(str.slice(1, -1));
}
} else {
return 'String is not a palindrome';
}
}
``````

## reinforcement learning – Resources on Dynamic Programming with Indefinite Recursion

I am trying to explain the value iteration method that is used in reinforcement learning. The method is used to estimate a solution to a recursive equation like:

$$Return(state_t,action_t) = Reward(state_t,state_{t+1}) + gamma * max begin{bmatrix} Return(state_{t+1}, action_{t+1}==’n’)\ Return(state_{t+1}, action_{t+1}==’e’)\ Return(state_{t+1}, action_{t+1}==’w’)\ Return(state_{t+1}, action_{t+1}==’s’) end{bmatrix}$$

Normally, if the sub-problems(RHS) are overlapping, a problem like this can be solved using recursive or iterative dynamic programming. However, in the case of reinforcement learning the recursion is often mutual, and thus the dynamic programming solution has no natural point of termination.

The value iteration method works by filling up the memorization table with arbitrary values and then repeatedly applying the recursive equation to every cell in the table until the values in the cell converge.

A similar approach is used in the HITS algorithm where the hub and authority values have mutual recursion.

Are there any good resources, preferably online, that deal with the application of dynamic programming to problems with mutual, indefinite recursion?

## recursion – How to create a recursive method for java classes with catalog structure?

I need to make a catalog structure with classes.
It must look like the following:

``````Group
1] Subgroup1
1.1 subgroup1
1.1.1 product1
1.1.2 product2
1.2 subgroup2
2]  Subgroup2
2.1 subgroup1
2.1.1 product1
2.1.2 product2
2.2 subgroup2
``````

I have created three classes Group, SubGroup, and LeafGroup with such relation:

``````class Group {
int id;
String name;
}

class SubGroup extends Group {

List<Group> subgroups;
}

class LeafGroup extends Group {

List<Product> products;
}
``````

So, only Leaf Group has products.
I need to create a method for the group where each group will recursively get all available products.
For example. for Subgroup2 available 2.1.1 product and 2.1.2 product.
As I understand it must check if the subgroup has products and if no, calls itself and check it in the next level.
Have can correctly looks this recursive method ?

## recursion – Add list of vectors to list of vectors recursively

This question relates to `https://mathematica.stackexchange.com/questions/95033/add-a-vector-to-a-list-of-vectors` whereas here I want to add list of vectors to list of vectors recursively.
Given:

``````m = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}}
k = m
``````

Adding each vector of m to each vector of k is done by

``````k = Transpose(# + Transpose(m)) & /@ k
``````

resulting in

``````     {{{2, 0}, {1, 1}, {0, 0}, {1, -1}}, {{1, 1}, {0, 2}, {-1, 1}, {0,0}}, {{0, 0}, {-1, 1}, {-2, 0}, {-1, -1}}, {{1, -1}, {0,0}, {-1, -1}, {0, -2}}}
``````

This is my new k and should go back into my code, so I can add the vectors `m` to each element of this new k. The new result starts with {{{{3,0},{2,1},{1,0),{2,-1}}… I tried

``````Table(k = (Transpose(# + Transpose(m)) & /@ k), {i, 2})
``````

But it does not work and then I get too confused. Any idea for this tree-like structure?

## recursion – Symbolic Solution of recurrence equation in two variables

I have a recursive equation of the form `R(p,q)=frac{c}{2a-1}(R(p,q-1)+cfrac{2a-b}{2a-1} sum_{j=1}^{p-1} left((1-b)frac{c}{2a-1}right)^{p-j-1} R(j,k-1) )` with `a, b, c` as certain parameters independent of `p` and `q` and the initial condition is `R(i,0)=afrac{c^{p-1}}{(2a-1)^p}`. I have solved it and got the solution of the form `R(p,q)=frac{ab^{q-1}c^{p-1}}{(2a-1)^{p+q}}left(frac{(2a)^q}{b^{q-1}}-sum_{i=1}^{q}(2a-b)^i(1-b)^{p-i}binom{p-1}{i-1}sum_{r=1}^{q-i+1}binom{r+i-2}{i-1}(frac{2a}{b})^{q-r-i+1}right)`. My questions are can we write the solution in a more compact and easy form? Can anybody assisst me in solving it by some other technique?

## recursion – A recursive_transform Template Function with Unwrap Level for Various Type Arbitrary Nested Iterable Implementation in C++

This is a follow-up question for A recursive_transform Template Function Implementation with std::invocable concept in C++ and A recursive_transform Template Function Implementation with recursive_invoke_result_t and std::ranges::transform in C++. Besides the version using `std::invocable`, I am attempting to implement another type `recursive_transform` function with the unwrap level parameter so that the usage like `recursive_transform<1>(Ranges, Lambda)` is available.

The experimental implementation

The experimental implementation of `recursive_transform` function with the unwrap level parameter is as follows.

``````//  recursive_invoke_result_t implementation
template<typename, typename>
struct recursive_invoke_result { };

template<typename T, std::invocable<T> F>
struct recursive_invoke_result<F, T> { using type = std::invoke_result_t<F, T>; };

template<typename F, template<typename...> typename Container, typename... Ts>
requires (
!std::invocable<F, Container<Ts...>>&&
std::ranges::input_range<Container<Ts...>>&&
requires { typename recursive_invoke_result<F, std::ranges::range_value_t<Container<Ts...>>>::type; })
struct recursive_invoke_result<F, Container<Ts...>>
{
using type = Container<typename recursive_invoke_result<F, std::ranges::range_value_t<Container<Ts...>>>::type>;
};

template<typename F, typename T>
using recursive_invoke_result_t = typename recursive_invoke_result<F, T>::type;

//  recursive_transform implementation (the version with unwrap_level)
template<std::size_t unwrap_level = 1, class T, class F>
constexpr auto recursive_transform(const T& input, const F& f)
{
if constexpr (unwrap_level > 0)
{
recursive_invoke_result_t<F, T> output{};
std::ranges::transform(
std::ranges::cbegin(input),
std::ranges::cend(input),
std::inserter(output, std::ranges::end(output)),
(&f)(auto&& element) { return recursive_transform<unwrap_level - 1>(element, f); }
);
return output;
}
else
{
return f(input);
}
}
``````

Test cases

``````//  non-nested input test, lambda function applied on input directly
int test_number = 3;
std::cout << recursive_transform<0>(test_number, ()(auto&& element) { return element + 1; }) << std::endl;

//  nested input test, lambda function applied on input directly
std::vector<int> test_vector = {
1, 2, 3
};
std::cout << recursive_transform<0>(test_vector, ()(auto element)
{
element.push_back(4);
element.push_back(5);
return element;
}).size() << std::endl;

//  std::vector<int> -> std::vector<std::string>
auto recursive_transform_result = recursive_transform<1>(
test_vector,
()(int x)->std::string { return std::to_string(x); }
);                                                                                  //  For testing

std::cout << "std::vector<int> -> std::vector<std::string>: " +
recursive_transform_result.at(0) << std::endl;                                  //  recursive_transform_result.at(0) is a std::string

//  std::vector<string> -> std::vector<int>
std::cout << "std::vector<string> -> std::vector<int>: "
<< recursive_transform<1>(
recursive_transform_result,
()(std::string x) { return std::atoi(x.c_str()); }).at(0) + 1 << std::endl; //  std::string element to int

//  std::vector<std::vector<int>> -> std::vector<std::vector<std::string>>
std::vector<decltype(test_vector)> test_vector2 = {
test_vector, test_vector, test_vector
};

auto recursive_transform_result2 = recursive_transform<2>(
test_vector2,
()(int x)->std::string { return std::to_string(x); }
);                                                                                  //  For testing

std::cout << "string: " + recursive_transform_result2.at(0).at(0) << std::endl;     // recursive_transform_result.at(0).at(0) is also a std::string

//  std::deque<int> -> std::deque<std::string>
std::deque<int> test_deque;
test_deque.push_back(1);
test_deque.push_back(1);
test_deque.push_back(1);

auto recursive_transform_result3 = recursive_transform<1>(
test_deque,
()(int x)->std::string { return std::to_string(x); });                          //  For testing

std::cout << "string: " + recursive_transform_result3.at(0) << std::endl;

//  std::deque<std::deque<int>> -> std::deque<std::deque<std::string>>
std::deque<decltype(test_deque)> test_deque2;
test_deque2.push_back(test_deque);
test_deque2.push_back(test_deque);
test_deque2.push_back(test_deque);

auto recursive_transform_result4 = recursive_transform<2>(
test_deque2,
()(int x)->std::string { return std::to_string(x); });                          //  For testing

std::cout << "string: " + recursive_transform_result4.at(0).at(0) << std::endl;

//  std::list<int> -> std::list<std::string>
std::list<int> test_list = { 1, 2, 3, 4 };
auto recursive_transform_result5 = recursive_transform<1>(
test_list,
()(int x)->std::string { return std::to_string(x); });                          //  For testing
std::cout << "string: " + recursive_transform_result5.front() << std::endl;

//  std::list<std::list<int>> -> std::list<std::list<std::string>>
std::list<std::list<int>> test_list2 = { test_list, test_list, test_list, test_list };
auto recursive_transform_result6 = recursive_transform<2>(
test_list2,
()(int x)->std::string { return std::to_string(x); });                          //  For testing
std::cout << "string: " + recursive_transform_result6.front().front() << std::endl;
``````

Full Testing Code

The full testing code:

``````#include <algorithm>
#include <array>
#include <cassert>
#include <chrono>
#include <complex>
#include <concepts>
#include <deque>
#include <execution>
#include <exception>
#include <functional>
#include <iostream>
#include <iterator>
#include <list>
#include <map>
#include <mutex>
#include <numeric>
#include <optional>
#include <ranges>
#include <stdexcept>
#include <string>
#include <tuple>
#include <type_traits>
#include <utility>
#include <variant>
#include <vector>

//  recursive_invoke_result_t implementation
template<typename, typename>
struct recursive_invoke_result { };

template<typename T, std::invocable<T> F>
struct recursive_invoke_result<F, T> { using type = std::invoke_result_t<F, T>; };

template<typename F, template<typename...> typename Container, typename... Ts>
requires (
!std::invocable<F, Container<Ts...>>&&
std::ranges::input_range<Container<Ts...>>&&
requires { typename recursive_invoke_result<F, std::ranges::range_value_t<Container<Ts...>>>::type; })
struct recursive_invoke_result<F, Container<Ts...>>
{
using type = Container<typename recursive_invoke_result<F, std::ranges::range_value_t<Container<Ts...>>>::type>;
};

template<typename F, typename T>
using recursive_invoke_result_t = typename recursive_invoke_result<F, T>::type;

//  recursive_transform implementation (the version with unwrap_level)
template<std::size_t unwrap_level = 1, class T, class F>
constexpr auto recursive_transform(const T& input, const F& f)
{
if constexpr (unwrap_level > 0)
{
recursive_invoke_result_t<F, T> output{};
std::ranges::transform(
std::ranges::cbegin(input),
std::ranges::cend(input),
std::inserter(output, std::ranges::end(output)),
(&f)(auto&& element) { return recursive_transform<unwrap_level - 1>(element, f); }
);
return output;
}
else
{
return f(input);
}
}

int main()
{
//  non-nested input test, lambda function applied on input directly
int test_number = 3;
std::cout << recursive_transform<0>(test_number, ()(auto&& element) { return element + 1; }) << std::endl;

//  nested input test, lambda function applied on input directly
std::vector<int> test_vector = {
1, 2, 3
};
std::cout << recursive_transform<0>(test_vector, ()(auto element)
{
element.push_back(4);
element.push_back(5);
return element;
}).size() << std::endl;

//  std::vector<int> -> std::vector<std::string>
auto recursive_transform_result = recursive_transform<1>(
test_vector,
()(int x)->std::string { return std::to_string(x); }
);                                                                                  //  For testing

std::cout << "std::vector<int> -> std::vector<std::string>: " +
recursive_transform_result.at(0) << std::endl;                                  //  recursive_transform_result.at(0) is a std::string

//  std::vector<string> -> std::vector<int>
std::cout << "std::vector<string> -> std::vector<int>: "
<< recursive_transform<1>(
recursive_transform_result,
()(std::string x) { return std::atoi(x.c_str()); }).at(0) + 1 << std::endl; //  std::string element to int

//  std::vector<std::vector<int>> -> std::vector<std::vector<std::string>>
std::vector<decltype(test_vector)> test_vector2 = {
test_vector, test_vector, test_vector
};

auto recursive_transform_result2 = recursive_transform<2>(
test_vector2,
()(int x)->std::string { return std::to_string(x); }
);                                                                                  //  For testing

std::cout << "string: " + recursive_transform_result2.at(0).at(0) << std::endl;     // recursive_transform_result.at(0).at(0) is also a std::string

//  std::deque<int> -> std::deque<std::string>
std::deque<int> test_deque;
test_deque.push_back(1);
test_deque.push_back(1);
test_deque.push_back(1);

auto recursive_transform_result3 = recursive_transform<1>(
test_deque,
()(int x)->std::string { return std::to_string(x); });                          //  For testing

std::cout << "string: " + recursive_transform_result3.at(0) << std::endl;

//  std::deque<std::deque<int>> -> std::deque<std::deque<std::string>>
std::deque<decltype(test_deque)> test_deque2;
test_deque2.push_back(test_deque);
test_deque2.push_back(test_deque);
test_deque2.push_back(test_deque);

auto recursive_transform_result4 = recursive_transform<2>(
test_deque2,
()(int x)->std::string { return std::to_string(x); });                          //  For testing

std::cout << "string: " + recursive_transform_result4.at(0).at(0) << std::endl;

//  std::list<int> -> std::list<std::string>
std::list<int> test_list = { 1, 2, 3, 4 };
auto recursive_transform_result5 = recursive_transform<1>(
test_list,
()(int x)->std::string { return std::to_string(x); });                          //  For testing
std::cout << "string: " + recursive_transform_result5.front() << std::endl;

//  std::list<std::list<int>> -> std::list<std::list<std::string>>
std::list<std::list<int>> test_list2 = { test_list, test_list, test_list, test_list };
auto recursive_transform_result6 = recursive_transform<2>(
test_list2,
()(int x)->std::string { return std::to_string(x); });                          //  For testing
std::cout << "string: " + recursive_transform_result6.front().front() << std::endl;
return 0;
}
``````

All suggestions are welcome.

The summary information:

## java – Reverse linked list(using Recursion) – Time and space Complexity

How to calculate time and space complexity for the below recursive code.

Idea : Initially traverse till previous of last node and make the last node to point it’s previous node and the previous node to point null. (Do the same until head point’s to null)

``````private void reverseList(Node node,Node prev) {

if (node.next == null) {
node.next = prev;
prev.next = null;
}
else {
reverseList(node.next,node);