Recursion in computer science is a method of problem solving where the solution to a problem depends on solutions to smaller instances of the same problem.
0
votes
0answers
30 views
Recursion confusion in Haskell [closed]
I hope someone can help figure out where my error lies. Calling g 3 4 0 2 (M.empty,0) [], I would expect [[2,1,0,1]] as a result. Instead, I'm seeing [[2,1,0,1],[2,1,0,1]].
The program is supposed ...
2
votes
0answers
58 views
Permutation of given string
I am reading a book on DSA, and the author explains how to generate the permutation of strings using recursion. I want to know if there are better ways of doing the same, unless this is the best ...
2
votes
2answers
101 views
Python code snippet could probably be more elegant
I'm looking to let people define arbitrarily nested lists of lists and return a random json document for them. Right now the assumption is that if you have a structure like this:
[item1, item2, ...
7
votes
3answers
164 views
Attempt at method to draw diamond (recursive or not ?)
I'm not so good with recursion, so I've decided to tackle an exercise consisting of drawing this pattern using characters:
*
***
*****
*******
*********
***********
*************
...
3
votes
2answers
90 views
Recursive a+b function
I am practising recursion and have written the small code for summing a+b as below:
#include <stdio.h>
int b=6;
static int cnt;
void main(void)
{
int a=9,sum;
sum=succ(a);
...
0
votes
2answers
81 views
Code optimization for euler's problem 28
I have found the solution for euler's problem using recursion.Is it okay or is there any other way to optimize the code?
static long GetSumofDiagonals(int cubeSize)
{
long sum = 0;
...
3
votes
1answer
71 views
Recursive branch and bound for knapsack problem
I've got the imperative styled solution working perfectly.
What I'm wondering is how to make a recursive branch and bound.
This is my code below, Evaluate function returns the optimistic estimate, ...
1
vote
1answer
64 views
Ruby string splicer
So I came across an interesting problem awhile back, and I finally got around to solving it. Basically, it needs to allow the user to provide two words, and have them progressively splice together, ...
1
vote
2answers
147 views
c++ Fibonacci sequence implementation
This was too slow for my computer :
int f(unsigned int x)
{
if(x <= 1) return 1;
else return f(x-1)+f(x-2);
}
/* main */
int main() {
for(int i = 0; i < 50; i++) cout << f(i) << ...
4
votes
3answers
164 views
Implementing an algorithm that walks the DOM without recursion
Here's a simple algorithm that walks the DOM given a node:
function walkDOM(n) {
do {
console.log(n);
if (n.hasChildNodes()) {
walkDOM(n.firstChild)
}
} ...
1
vote
1answer
92 views
Pure PHP array_diff_assoc_recursive function
For my application, I was using array_diff_assoc, when I noticed it was returning the wrong value. I was using multidimensional arrays, therefore I needed a array_diff_assoc_recursive method.
I ...
1
vote
2answers
76 views
Optimize Recursive Function to traverse nested DOM nodes
I wrote a recursive function that traverses nested DOM nodes of the following form:
<a href="#" title="test">
<div id="nested-image">
<img src="image.jpg" />
...
2
votes
2answers
48 views
I'm practicing turning for loops into recursive functions. what do you think?
I am trying to turn this function:
collection = ['hey', 5, 'd']
for x in collection:
print(x)
Into this one:
def printElement(inputlist):
newlist=inputlist
if len(newlist)==0:
...
0
votes
2answers
157 views
Recursive method to return a set of all combinations
Can someone explain me how this code works or if it is possible to be written in another way? I tried it with just ArrayList but cannot figure it out.
public static Set<Set<Integer>> ...
1
vote
1answer
122 views
What is this structure called?
So I've been writing this data structure for a few days, and now I'm really curious about what it actually is, and to get some critique on my logic.
A branch, based on this usage, exists when a HEAD ...
2
votes
0answers
144 views
Javascript / Jquery Recursive find function
I wrote the following code as a way of plucking data from a n-depth javascript object.
It works a charm and even appends the parents of the the found item.
I was just wondering if you guys had any ...
3
votes
1answer
146 views
java recursive method to print a descending then ascending integer sequence
From a programming assignment:
Write a method writeSequence that accepts an integer n as a parameter and prints a symmetric sequence of n numbers with descending integers ending in 1 followed by ...
1
vote
1answer
50 views
Assign value of nested array as array key
I have a multi dimensional array like this:
[0] =>
['batch_id'] => '1'
['some_stuff'] => 'values'
[0] =>
['unit_id'] => '12'
['some_stuff'] => 'values'
...
1
vote
1answer
72 views
Recursive Determinant
The following code I devised to compute a determinant:
module MatrixOps where
determinant :: (Num a, Fractional a) => [[a]] -> a
determinant [[x]] = x
determinant mat =
sum [s*x*(determinant ...
1
vote
1answer
228 views
Pascal's Triangle in Javascript
Here's the problem statement:
Given an integer value, print out Pascal's Triangle to the corresponding depth in row-major format:
Input Sample:
6
Output Sample:
1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 ...
1
vote
1answer
48 views
Improve file-path finding method
I am using a recursive algorithm to find all of the file-paths in a given directory: it returns a dictionary like this: {'Tkinter.py': 'C:\Python27\Lib\lib-tk\Tkinter.py', ...}.
I am using this in a ...
2
votes
0answers
83 views
functional javascript - recursively walking a tree to build up a new one; could this be better factored as a reduce?
/**
* recursively build a nested Backbone.Model or Backbone.Collection
* from a deep JSON structure.
*
* undefined for regex values
*/
exports.modelify = function modelify (data) {
if ...
1
vote
2answers
51 views
Recursively print in scala
I have just picked up Scala like 2 hours ago, and I am thinking of printing a series like 1 to 10 but in a recursive fashion. I do not understand what is wrong with this:
def printSeries(x:Int):Int = ...
2
votes
2answers
108 views
How can I optimize this recursive function?
I have a function that I need to optimize:
def search(graph, node, maxdepth = 10, depth = 0):
nodes = []
for neighbor in graph.neighbors_iter(node):
if ...
-2
votes
1answer
61 views
whats wrong with my recursion? [closed]
I am working on trying to create a tree in a recursive fashion. I have gotten constructive feedback on my previous questions so I try once more. I dont want to use malloc, and please dont post ...
2
votes
1answer
83 views
Iterative Collatz with memoization
I'm trying to write efficient code for calculating the chain-length of each number.
For example, 13 -> 40 -> 20 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1.
It took 13 iterations ...
2
votes
2answers
88 views
Finding first match in recursive search
I am searching a recursive solution space and would like to return the first match I find. (I am using this to solve sudoku, but I guess this would apply to any recursively defined problem or ...
1
vote
1answer
79 views
Recursive java.util.Properties references
Background
A subclass of java.util.Properties attempts to recursively resolve configured properties:
prop_a=Prop A is ${prop_b}
prop_b=Prop B is ${prop_c}
prop_c=Prop C.
After reading the file, ...
1
vote
3answers
102 views
List-flattening function in erlang feels too wordy
I wrote a tail-recursive list-flattening function, but I'm not too happy with it.
a) Is tail-recursion necessary here, or will the function be optimized without it?
b) It's ugly how many clauses ...
0
votes
1answer
92 views
Creating an Array of Linked Lists from a BST
Question
Given a binary search tree, design an algorithm which creates a linked list of all the nodes at each depth (eg, if you have a tree with depth D, you’ll have D linked lists)
Here is my ...
4
votes
2answers
96 views
Recursive XML2JSON parser
I made a Python function that takes an XML file as a parameter and returns a JSON.
My goal is to convert some XML get from an old API to convert into Restful API.
This function works, but it is ...
2
votes
1answer
87 views
Efficiency of Recursive Checkers Legal Move Generator
I'm implementing a checkers engine for a scientific experiment. I found out through profiling that this is one of the functions that takes up a lot of time. I'm not looking for an in-depth analysis, ...
6
votes
1answer
187 views
Is there a better way to walk a directory tree?
I just started to learn Haskell, and i wrote a function that walks the directory tree recursively and pass the content of each directory to a callback function:
The content of the directory is a ...
2
votes
2answers
97 views
multi-recursive replacement function
I wrote a function for creating all possible translations of a source string, based on a multiple translation map. It works, but generates a lot of intermediate maps (see line marked with *). Is there ...
1
vote
0answers
208 views
PostgreSQL: Get all recursive dependencies of a single database object
I've written a SELECT statement that creates a List of all objects that depend on a single object, so that if I wanted to DROP that object I could DROP all referenced objects first without using ...
2
votes
1answer
54 views
Avoiding use of an initialized variable that will either be changed or ignored
Follow on from this question
This is a follow on question from one I asked a few days ago. I am making (or rather have made) a recursive method that takes a list of ArrayList objects as its ...
3
votes
3answers
274 views
Trying to make recursive code designed to find objects with even references tidier
As the title says, I'm trying to make my code less horrible looking! For a university practical, I've to use recursive methods to return the even references in a collection of Integer objects stored ...
2
votes
1answer
208 views
Javascript “recursion” via setTimeout
I understand that because of Javascript's single-threaded execution, long loops or recursive calls could make the browser unresponsive while they execute.
I thought about simulating recursion using ...
1
vote
3answers
92 views
How to improve this functional python fast exponentiation routine?
I have the following python functions for exponentiation by squaring :
def rep_square(b,exp):
return reduce(lambda sq,i: sq + [sq[-1]*sq[-1]],xrange(len(radix(exp,2))),[b])
def ...
2
votes
1answer
263 views
Recursion and iteration how can i optimize this code
I have written some code which will fetch contents from a resource which is actually stored in a tree format. Since it is in a tree format, there will be a parent-child relation and hence recursion.
...
1
vote
1answer
174 views
Code review for recursion to map phone number to strings
I am trying to solve the following via recursion: In a phone we have each digit mapped to a number.
Example:
1 2(ABC) 3(DEF)
4(GHI) 5(JKL) 6(MNO)
7(PRS) 8(TUV) 9(XYZ)
* 0 ...
3
votes
2answers
119 views
JQuery typed wrapper in C#; possible recursion
I am writing an object in C# to mimic jQuery's various functions. That is, calling the constructor is akin to calling the $() function of jQuery. For example,
var a = new JQuery("div").eq(0);
...
2
votes
1answer
83 views
How to rewrite recursion in a more ruby way
def get_all_friends(uid, client)
friends = client.friendships.friends(uid: uid)
total = friends.total_number
get_friends(total, 0, uid, client)
end
def get_friends(total, cursor, uid, client)
...
2
votes
1answer
79 views
Which of these two paren-matching functions is better?
I am currently trying to learn Haskell (after taking a Scala course on Coursera); but while I can write functions that do what I want, I worry that I am not learning to write idomatic/clean/performant ...
4
votes
4answers
316 views
What do you think of my Recursive FizzBuzz?
I wanted to see if I fully understood recursion so I attempted the FizzBuzz challenge and applied recursion to it.
Did I do it correctly? Is this good code? Is there a more efficient way of doing ...
3
votes
1answer
99 views
Haskell tips/why doesnt this scale linearly?
My friend wrote a program which compares random arrangements of die faces to find the one with the most evenly distributed faces - especially when the faces are not a mere sequence.
I translated his ...
-1
votes
1answer
77 views
recursive function [closed]
I want to generate a random number then to check if it is in the database. If not then redo it.
My pseudo code:
PIN = GenerateRandomNumber().ToString();
...
1
vote
0answers
172 views
Print all interleavings of given two strings
Given two strings str1 and str2, write a function that prints all
interleavings of the given two strings. You may assume that all
characters in both strings are different
Example:
Input: ...
7
votes
1answer
662 views
Print all permutations with repetition of characters
Given a string of length n, print all permutation of the given string.
Repetition of characters is allowed. Print these permutations in
lexicographically sorted order
Examples:
Input: AB
...
2
votes
1answer
235 views
Scala: tail-recursive factorial
Is there anything what could be improved on this code?
def factorial(n: Int, offset: Int = 1): Int = {
if(n == 0) offset else factorial(n - 1, (offset * n))
}
The idea is to have tail-recursive ...