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.
3
votes
1answer
50 views
Recursively convert a list of lists into a dict of dicts
As a challenge to myself, I wrote a solution to this Stack Overflow question. For completeness, the bulk of the question is as follows:
Problem
Input:
[
['key1', 'value1'],
['key2',
[
...
3
votes
2answers
138 views
Hanoi towers time exeeded
I am having problem with a simple Hanoi tower program. I need to do something to reduce its time.
#include <stdio.h>
#include <fstream>
using namespace std;
int hanojus(int n, char a, ...
7
votes
1answer
104 views
Sudoku Week-End Challenge - Brute-Force Recursive solver
This is part of my attempt at the Week-End Challenge #3. The overall problem is larger than will fit in one question. This is a well-contained subset of my larger program.
The goal of this part is to ...
3
votes
3answers
131 views
String Extension improvement
I am creating a string extension to validate some input.
My scenario is when we have a string it will format it according to following guideline.
If the sample string is “One Two Three Four Five” and ...
2
votes
1answer
42 views
lexical scope v let in scheme functions
I've been chewing through a bit of The Little Schemer and the Peano examples got me thinking about operation size and time.
I got some help on making Peano Multiplication linear -- however (time ...
1
vote
1answer
37 views
Linear Peano multiplication in Scheme?
I've been running through The Little Schemer, and have hit the example of Peano multiplication. The solution is given in TLS (reproduced below) -- however what interests me is the order of the ...
4
votes
2answers
63 views
Count possible paths through a maze
You have to find a path through which the rat move from the starting
position (0,0) to the final position where cheese is (n,n). List the
total no of possible paths which the rat can take to ...
1
vote
1answer
52 views
Checking user permission, where permission is granted for specific EmployeeGroup that has self reference
The users get permissions to do specific things for a specific group of employees. These employee groups have a self reference. So an employee group (C) can be a child of group (B), and group (B) is ...
3
votes
1answer
77 views
Better way to create samples
I've done this piece of code for creating all possible samples without repetitions, but I think that it is a so heavy algorithm because every time I call this recursive function I create a new vector ...
-2
votes
0answers
35 views
Better way to create samples recursively [closed]
I've done this piece of code for creating Bernoulli samples, but I think that it is a so heavy algorithm becouse every time I call this recursive function I create a new vector that is passed to it. ...
2
votes
1answer
50 views
Given set of cubes can we get a given word?
Given some cubes, can cubes be arranged such that an input word can be formed from the top view of the cubes?
For example: assume an imaginary cube with only 3 surfaces where cube1: {a, b, c} and ...
6
votes
1answer
116 views
Find all subsets of an int array whose sums equal a given target
I am trying to implement a function below:
Given a target sum, populate all subsets, whose sum is equal to the target sum, from an int array.
For example:
Target sum is 15.
An int array is { ...
3
votes
5answers
151 views
count all array[index] == index occurrences
The method foo gets a sorted list with different numbers as a parameter and returns the count of all the occurrences such that: i == list[i] (where i is the index 0 <= i <= len(list)).
def ...
3
votes
1answer
53 views
I've written remainder(x,y) in OCaml. Is there more efficient than O(n)?
Here's my code:
let rem x y =
let rec aux acc i n =
if i=n then acc else
if acc+1=y then aux 0 (i+1) n else
aux (acc+1) (i+1) n in
aux 0 0 x;;
I'm just learning OCaml and I wonder:
...
1
vote
0answers
89 views
How to optimize this maze solver?
I've written C# code for solving a maze problem. It works, but I want to optimize it so that it could give me all paths. To solve the maze, I walk on the zeros and assumed that the final is reaching ...
2
votes
0answers
40 views
Optimize RecursionArray interface
I created a class a while ago that I named a "Recursion Array". It is a way to create dynamically memoized sequences such as the Fibonacci sequence or the factorial numbers sequences. The concept is ...
3
votes
1answer
53 views
Is a Recursive-Iterative Method Better than a Purely Iterative Method to find out if a number is prime?
I made this program in C that tests if a number is prime. I'm as yet unfamiliar with Algorithm complexity and all that Big O stuff, so I'm unsure if my approach, which is a combination of iteration ...
2
votes
2answers
47 views
Move Line across Plane
I want move a Vertical line segment across a plane or another way sweep the plane, from Left to right.
The figure illustrates how the segment is moving at the X-axis. When x1 >= X beginning and i ...
1
vote
1answer
50 views
Recursive GCD using a lambda
This works just fine, however, the assignment was to write a recursive "function". I'm curious to see if this should count.
Any comments / suggestions/ stuff I should watch out for are appreciated. ...
2
votes
2answers
162 views
Maze - code review
Maze puzzle, a 1 in input matrix means "allowed" 0 means "blocked". Given such a matrix find route from 1st quadrant to the last (n-1, n-1). I would like to get some feedback to optimize and make this ...
2
votes
2answers
58 views
Optimizing odds calculator
I am trying to setup an odds calculator for a best of 7 series, given independent odds for each event.
The following code works, but I would like to add recursion to simplify the end.
public class ...
2
votes
2answers
438 views
Boggle solver in Java
This is a boggle solver in Java. I would like code reviewers to optimize the code, suggest better coding practices, and help make it cleaner.
I am also unsure of the complexity and would appreciate ...
0
votes
1answer
55 views
Javascript recursive object is defined test
I wrote the method below, and was wondering whether a better way exists/best practice tips
_objectIsDefined = function (obj, path) {
if (typeof path !== 'undefined') {
// if we have been given ...
2
votes
2answers
120 views
How can I store the fibonacci sequence in a vector during each recursive call? [closed]
#include <iostream>
#include <vector>
void getUserNum(int &);
int rFib(int n);
void dispSeq(std::vector<int> &vRef);
int main()
{
int userNum;
getUserNum(userNum);
...
1
vote
0answers
146 views
Recursive JSON walk in Python
I wrote this JSON walker to help with moving objects around while updating Legacy JSONs to match a new schema. Please let me know how I could further optimize it, or more importantly, make it easier ...
2
votes
2answers
67 views
Recursive function refactoring help: occurrences of char in string starting at ith char
Just getting into functional programming and F# with the most appropriately titled Functional Programming Using F#. I wrote the following function definition for problem 2.4 but I'm thinking there's ...
3
votes
2answers
112 views
Is this recursion a bad idea and does it make for clean code?
This is a program I made to bounce the letter a across the screen. I made a few others, but this one I made with a recursive bounce() method. I know main() is a bit empty, but I intend to make an ...
6
votes
1answer
327 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
158 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
383 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
103 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
99 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;
...
4
votes
2answers
463 views
How can I improve this recursive Sudoku solver?
I've been asked to attach a C++ code sample to my application for an entry-level C++ programmer position in a videogame company. I've created a simple, yet complete console application to solve ...
3
votes
1answer
451 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
77 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, ...
2
votes
2answers
333 views
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
240 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
121 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 ...
2
votes
1answer
199 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
52 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
1k 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>> ...
2
votes
1answer
146 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
1answer
360 views
Recursive find function in JavaScript / jQuery
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
569 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
61 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
106 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 ...
2
votes
2answers
582 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
59 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 ...
4
votes
1answer
258 views
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 ...
1
vote
2answers
53 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 = ...