# Questions tagged [recursion]

14689 questions

-1

votes

1

answer

12

Views

### Treating an array of single digit numbers like a single number and adding 1 to it - Without Join(),concat() or making it a string

I have an array like so [1,9,9,9,9,9]. I want to increment this array by one and return [2,0,0,0,0,0]. Here's the catch - you can't join() or concat(). You cannot change the array in any way other than adding to it. However, you can reverse it but I'm not sure how much that would help
Also, here a...

0

votes

1

answer

29

Views

### Why if block doesn't pass? [duplicate]

This question already has an answer here:
Why do inaccuracies occur in floating point math operations?
29 answers
I was doing a coding challenge and run into this problem that I have never encounter before. The question ask to return change in the most efficient way. User put in the price, and the...

0

votes

0

answer

5

Views

### Recursive product mips

I made some changes to the code, but it is still printing a 9digit number. Not sure what's going on here. When I type in 2 * 3, it outputs 268501017. Im having a hard time find out how to get the result from the register and print it.
main:
#prompt 1
li $v0, 4 # Print the String at Label “I...

1

votes

3

answer

80

Views

### Generate lexicographic series efficiently in Python

I want to generate a lexicographic series of numbers such that for each number the sum of digits is a given constant. It is somewhat similar to 'subset sum problem'. For example if I wish to generate 4-digit numbers with sum = 3 then I have a series like:
[3 0 0 0]
[2 1 0 0]
[2 0 1 0]
[2 0 0 1]
[1 2...

1

votes

2

answer

57

Views

### Definition and Initialization of a tuple whose components are of the same templated class, but with different specialisations

I am new to c++ metaprogramming. I tried to look at other answers, but I was not able to find one that could suit my problem.
Or simply I was not able to apply it to my case.
Here I will post a simplified version of the code, to highlight the main features which I would like to obtain.
What I would...

1

votes

1

answer

65

Views

### Using an accumulator to sum up numbers in F#

I'm trying to solve a problem that requires me to sum up 2 numbers but I have to use an accumulator in my function.
This is the math formula:
sum(m, n) = m + (m + 1) + (m + 2) + · · · + (m + (n − 1)) + (m + n)
Here is what I have so far:
let rec g (m, n) =
let rec gAcc m n a =
match n with
|...

-1

votes

1

answer

14

Views

### recursively search through json and node with parent node javascript

I have json collection, which is contains nested elements as an array or key value pair and can be nested upto any length. I need to pass through an array, and find the items within it and convert them with their respective values.
For example, in the given below array, I have an Array
['TRC030-A',...

1

votes

1

answer

17

Views

### Recursion to separate one word into three or more words java

I am trying to write a program that will take input from dictionary.txt document and will store the words in a dictionary list, and then determine if the word can be broken up into three or more words and if yes, then printing out the original word followed by the new words for example disconsolaten...

744

votes

21

answer

462.8k

Views

### How can I access and process nested objects and arrays?

I have a nested data structure containing objects and arrays. How can I extract the information, i.e. access a specific or multiple values (or keys)?
For example:
var data = {
code: 42,
items: [{
id: 1,
name: 'foo'
}, {
id: 2,
name: 'bar'
}]
};
How could I access the name of the second item in items...

1

votes

0

answer

13

Views

### Maximum path sum In a triangle for nonprime numbers

what is the final Result guys !! mine 8219 and I have been told it's wrong !!
You will have an orthogonal triangle input from a file and you need to find the maximum sum of the numbers according to given rules below;
You will start from the top and move downwards to an adjacent number as in below....

1

votes

2

answer

5.7k

Views

### parse recursively unknown json input structure in java

I'm trying to parse recursively unknown json input structure in java like the format below and trying to rewrite the same structure in another json.
Meanwhile I need to validate each & every json key/values while parsing.
{'Verbs':[{
'aaaa':'30d', 'type':'ed', 'rel':1.0, 'id':'80', 'spoken':'en', 'c...

0

votes

2

answer

22

Views

### Getting segmentation fault when trying to print linked list data reversely using recursion

I have created linked list of nodes. And wanted to print the data of each node reversely using recursion technique. I got the working as well as segfaulted code. I am trying to understand whats actually problem in segfaulted code.
Actually I tried debugging using GDB but I dont know exactly how to t...

0

votes

1

answer

32

Views

### How do I recursively and reflectively get a list of all possible field name paths?

I am trying to get a collection of string that give me the names of the fields of all my class members, separated by .s. For example:
public class Apple
{
public Banana MyBanana = new Banana();
public Cranberry MyCranberry = new Cranberry();
}
public class Banana
{
public int MyNumber = 5;
public C...

0

votes

2

answer

11

Views

### Recursive Logic to Handle Document Count Based on Page Number Passed in Request

In my Node/MongoDB backend I am returning a count to my Angular front-end, which is then used by the logic in our front-end to serve up pagination UI for the end user.
Because one section of our data is quite large (so the count takes quite a while to come back), I am instead passing counts increme...

1

votes

1

answer

1.4k

Views

### Java Calculate Max Steps of Stairs and skip stair

I recently got an interview for an intern position and one of the questions was similar to this:
Input: n for number of actions, k for a stair that you could not step
on
Question: Jack has n amount of actions where he wants to reach the
maximum number of steps but cannot step on the kth stair. For...

6

votes

7

answer

218

Views

### Which programming languages support functions that take themselves as arguments?

I'm doing an academic exercise (for personal growth). I want to find programming languages that allow you to define functions that are capable of accepting themselves (i.e., pointers to themselves) as arguments.
For example, in JavaScript:
function foo(x, y) {
if (y === 0) return;
x(x, y - 1);
}
foo...

1

votes

1

answer

58

Views

### Generator Recursion in Sieve of Eratosthenes Skips Steps

I ran into an issue with the sieve algorithm I have written here. I have tried to fix it for a total of about 10 hours now. I've looked around here for similar questions but I can't seem to find anyone who has had this issue. I'm relatively new to python, and after reading through a lot of generator...

1

votes

3

answer

57

Views

### How to get Ancient Father of each son Recursive SQL

I've got this Original table:
And i need to Get this Table, By Recursive SQL Query (probably with 'With' clause) but not sure how to get it:
Would be glad if you can help,
thanks in advance

1

votes

2

answer

56

Views

### Retrieving recursively all elements in a list

I have a class 'Job' defined like this :
public class Job extends AbstractJob
{
private String name;
private String jobCount;
private String status;
private List children;
public Job(String name, String jobCount, String status, List children) {
this.name = name;
this.jobCount = jobCount;
this.status...

1

votes

4

answer

68

Views

### filtering tuple inside a tuple recursively

i'm trying to figure out how to filter a tuple inside a tuple
like so:
input>>>filter_tree((1,2,3,4,(1,2,3)),lambda x:x%2==0)
output>>> ((2,4,(2))
this is how far I got :
def filter_tree(tree,f):
if type(tree)!=tuple:
return tree
return tuple(filter(f,tuple(filter_tree(node,f) for node in tree)))...

1

votes

3

answer

83

Views

### Add an element(Int,Double…) at the end of an “Any” type list

I'm trying to add an element at the end of 'Any' type list ( List[Any] ).
I want to use a recursive function to build it the idea is 'if I need of this element I'll append it, when the iteration is over my list will be complete'.
In the following code the idea is 'I have a List 'l' if the element 'e...

1

votes

2

answer

41

Views

### Convert recursive function to iterative function

Although this may seem like a duplicate (maybe it is but I haven't found a solution to this version of the problem yet), I don't think it is.
Below is my recursive function which blows python's recursion limit and I'd need to make it iterative instead but I'm having issues seeing how it could be pos...

1

votes

1

answer

24

Views

### Pandas Knowing the Employee of a Boss

Is it possible to extract the hierarchy of employee by a given table using pandas?
for example we have this table
+-------+--------+
| empID | bossID |
+-------+--------+
| a1 | b2 |
| a2 | a1 |
| c1 | a2 |
| d2 | a2 |
| a4 | aa |
+-------+--------+
employee b2 on...

1

votes

1

answer

74

Views

### C - Depth first search in adjacency matrix using recursion

I have a recursion problem I would like to solve using recursion.
For example, given this adjacency matrix AdjMat:
0 1 2 3
0 0 1 0 0
1 1 0 1 0
2 0 1 0 1
3 0 0 1 0
Say I would like to look at column 0 and all of its neighbors, and its neighbors' neighbors (distance of 2), and store all of the row in...

1

votes

3

answer

39

Views

### Count Vowels in String Using Recursion With JavaScript

Hello I'm trying to understand recursion in JavaScript.
So far I have:
function countVowels(string) {
let vowelCount = 0;
// if we're not at the end of the string,
// and if the character in the string is a vowel
if (string.length - 1 >= 0 && charAt(string.length -1) === 'aeiouAEIOU') {
//increase...

1

votes

5

answer

52

Views

### Remove all numbers except the first using recursion

Basically what I have to do is to remove all digits and leave the first one. If it's a number under 10 keep that number.
I already made some code but instead of removing all digits following the first, I removed the first digit.
My code:
public static int keepFirstDigit(int num) {
// Can't change an...

0

votes

0

answer

3

Views

### Creating a list of interleaved elements: Prolog

I am defining a function alternate_func(Ps, P) where Ps is a list of lists and P is a list of all elements in Ps that behaves in the following way: .
?- alternate_func([[p,q],[r,s]],P).
P=[p,r,q,s]. (case 1)
?- alternate_func([P,Q,R],[p,q,r,s,t,u]).
P=[p,s], Q=[q,t], R=[r,u]. (case 2)
?- alternate...

1

votes

2

answer

6.5k

Views

### Looping through tree hierarchy in python?

I'm new here and pretty new to python!
We got a homework, and I already was able to do rest of it, but one problem remains:
If I have a tree hierarchy like this:
root = [
parent1 = [
child1,
child2 = [
sub_child
]
child3
],
parent2 = [
child1,
child2
]
]
And they are all instances of one class named...

1

votes

0

answer

87

Views

### Fibonacci in linear time by using an extra pointer

I have a function to find the nth number in a fibonacci sequence, in which I am recursively calling the function. The sum is stored in a class variable and I have an extra pointer I increment every time the function gets called. This extra pointer is the gate keeper which dictates the base case of w...

1

votes

1

answer

73

Views

### Cannot recursively remove certain files with Remove-Item -Recurse -Force

On powershell 5.1
Using this within a foreach loop, ex:
foreach ($i in $folder.subfolders) {
if( $i.path -like '*node_modules' ){
Remove-Item $i.path -Force -Recurse
}
}
I keep running into this particular error:
+ CategoryInfo : WriteError: (_node_modules_r...dationpath.html:FileInfo) [Rem...

1

votes

1

answer

25

Views

### Difficulty with python recursion

Can someone explain why:
def sum_digits(n):
if n // 10 == 0: return n
else: return sum_digits(n // 10) + n % 10
print(sum_digits(137))
returns 11 and when i replace + with * it returns 1 instead of 21.

1

votes

1

answer

77

Views

### MYSQL: recursive procedure that builds a string for each row

I would like to create a procedure that recursively went through a table and built a string for every row. Each row is related to another row except for a few that are at the top of the hierarchy.
Here is what I have:
CREATE TABLE item (
id INT NOT NULL AUTO_INCREMENT,
name...

1

votes

1

answer

653

Views

### Render React component recursively

I got an array of objects and need to recursively render every single object like unmarked list :
All data comes from server like simple JSON:
{
'Id': 1,
'Description': 'asd',
'Src': ' ',
'Lft': 0,
'Rgt': 9
},
{
'Id': 2,
'Description': 'asd2',
'Src': ' ',
'Lft': 1,
'Rgt': 2
},
{
'Id': 3,
'Descriptio...

1

votes

0

answer

756

Views

### Hibernate Infinite recursion in One-To-One relationship

I have a mid-size project that is using One-To-One and One-To-Many relationships. Days ago, I got an Infinite recursion in One-To-Many relationships, but I managed to fixed it with those two annotations: @JsonManagedReference and @JsonBackReference.
Now I am facing the same error, but in One-To-One...

1

votes

1

answer

146

Views

### Python function returns None in elif or else

I have the variable r of type dict. Variable item holds a list of items, and total_results is an int. As long as the condition is met that the number of items is less than the total amount of items, the function is called recursively. However, if I test whether the items are equal to the total resul...

1

votes

1

answer

202

Views

### Prolog - Towers Of Hanoi, outputting the “towers” as they are after each step

I have seen multiple questions showing the way how one could solve the Towers Of Hanoi question in Prolog with and without lists, however what I haven't seen yet is a way for one to use the recursive algorithm, while also being able to output each step.
Here is my code of the Hanoi algorithm:
move(1...

1

votes

1

answer

56

Views

### How to print the name of a recursive lambda template?

For debug purpose, would it be possible to use any macro to print the name of a recursively defined lambda inside a class template function? For example
template
class X{
public:
X();
//rest of declaration
private:
//rest of declaration
};
template X::X(){
functionsomeLambda = [] (){
//recursive d...

1

votes

2

answer

1k

Views

### Check if string is balanced with brackets

I have to write Python supplementary function:
def find(searched, open)
for function which recursively checks if the input string has balanced brackets:
def balanced (text):
#....
return find(text, None)[1]
I can't use stack. I have to include option, when input string is empty, when the bracket...

1

votes

0

answer

81

Views

1

votes

1

answer

229

Views

### Error of infinite recursion in R(Shiny)

I am working on R(Shiny) that is working on a loan prediction model. I am trying to calculate loan amount for a particular method but it is showing me an error for infinite recursion and just like mentioned in most of the posts even I have tried options(expressions = 1000) value, but am still experi...