This question already has an answer here: Return value of recursive function is 'undefined' 1 answer I've created the following function to flatten a nested array: function steamroller(arr) { arr = arr.reduce(function(a, b, i){ return a.concat(b); },[]); if (!Array.isArray(arr[arr.length-1])) {console.log(arr); return arr;} steamroller(arr); } steamroller([1, [2], [3, [[4]]]]); The...

While toying with Swift, I've encountered a situation which crashes and I still not have figured out why. Let define: class TestClass { var iteration: Int = 0 func tick() -> Void{ if iteration > 100000 { print("Done!") return } iteration++ tick() } } The tick() function calls itself and...

For People With A Similar Question (written after finding a solution): This problem, as you might notice according to the answers below, has a lot of different solutions. I only chose Evan's because it was the easiest one for me implement into my own code. However, from what I tried,...

I would like to create a nested tuple type, that can hold itself, or the particular type it contains. So I thought: typealias NestedTuple{T} Tuple{Union(T,NestedTuple{T}),Union(T,NestedTuple{T})} However this comes up with an error LoadError: UndefVarError: NestedTuple not defined How is this kind of typealias normally done? (I am in julia 0.4)...

I was following the Eloquent Javascript book and making the linked list exercise. I am stuck with recursion. I use the following code: function arrayToList(array){ var list = {}; length = array.length; while(array.length > 0){ element = array.pop(); if (length == array.length + 1 ) list = { value: element,...

I have a promise chain with a recursive promise doAsyncRecursive() in the middle like so: doAsync().then(function() { return doAsyncRecursive(); }).then(function() { return doSomethingElseAsync(); }).then(function(result) { console.log(result); }).catch(errorHandler); doAsyncRecursive() has to do something and if it at first does not succeed, i then after want to try every 5 seconds until...

I have the following function: function getJsonStuff($page_id, $token = "") { $json = json_decode(file_get_contents("https://www.example.com/id=" . $page_id . "&pageToken=" . $token), true); if (isset($json["token"]) && !empty($json["token"])) { getJsonStuff($playlist_id, $json["token"]); } else { return $json; } } The JSON given on the page I'm retrieving it from only returns 20 results, but...

The purpose of my function is to generate 8 random letters n times (specified when it is compiled). I approached this by writing two functions called genNumbers - which generates 8 random numbers (between 0 and 25) and places them into an array called numbers, and convert - which converts...

I need to calculate averages for a hierarchical organization. Each student can have grades in different subjects (not all students have grades in all subjects), and each student has a Parent (which is a unit). Each unit has a parent which is another unit, and so on. The number of...

I am trying to a list of all of the employees that are under a manager in a table. So a manager can go to a webpage and view every single person that is under him/her including all hierarchies. An Employee consists of this: public class Employee { int id...

I have the following code in Java: public static boolean isRoundNumber(String s) { System.out.println("the string is: "+s); if (s.length() == 0) { System.out.println("check 1"); return false; } if (s.length() == 1) { System.out.println("check 2"); return Character.isDigit(s.charAt(0)); } else { System.out.print("checking: " + s.charAt(0)+ " | "); return (Character.isDigit(s.charAt(0)) && isRoundNumber(s.substring(1)));...

I have a large collection of CSV formatted reports related to faxes received over a period of time. I am attempting to parse through these reports using logparser to obtain a total number of pages received. I see that the -i:csv option does not support recursion of directories. As an...

I am not sure if power by squaring takes care of negative exponent. I implemented the following code which works for only positive numbers. #include <stdio.h> int powe(int x, int exp) { if (x == 0) return 1; if (x == 1) return x; if (x&1) return powe(x*x, exp/2); else...

We have recently been working on implementing recursive methods for several classes (trees, heaps, queues, linked lists, etc) in C++ for my computer science class. I have not been having any trouble writing the implementations for the methods, but something my professor mentioned briefly in passing confused me and she...

public int count7(int n) { int count = 0; if (n%10 == 7) count= 1; if(n%10 != 7) count= 0; if (n < 10 && n==7) return 1; if (n < 10 && n!=7) return 0; else return count7(n/10) + count; } I have the above function that recursively adds...

I have a recursive function that reads a list of scout records from a file, and adds then in order of their ID's to a list box. The function is called with addScouts(1) The function is below: def addScouts(self,I): i = I with open(fileName,"r") as f: lines = f.readlines() for...

I want to write a recursive function that combines 2 string into one string that is in alphabetic order , the 2 strings are only small letters and in ascending alphabetical order . Example : s1: "aegiz" s2: "abhxy" s3: "aabeghixyz" I am still new to recursive functions and to...

I am trying to call this recursive method,but I don't understand why it's not reaching the else statement to return mul. I am passing value 0,in the main function,which is less than n,and on x becoming greater than n,it should move to else function. #include <cmath> #include <cstdio> #include <vector>...

I'm trying to get the last element of a list of integers in SML but I want to indicate (somehow) when the user passes in an unacceptable list (such as an empty one). My code is here: fun lastInList [] = ~1 | lastInList [x] = x | lastInList (x::xs)...

I'm trying to recreate a function spiral() using recursion that takes the parameters initLen (pixel length of first side), N (angle connecting segments), and mult (a float amount indicating how much bigger/smaller each segment should be after each turn - ex: mult = 0.5 means each segment would be half...

Could anyone please explain why "return str" line never executes? public static String reverseString(String str){ String reverse=""; if(str.length() == 1){ return str; //at one point this condition will be true, but value never returns } else { reverse += str.charAt(str.length()-1) + reverseString(str.substring(0,str.length()-1)); return reverse; } } public static void main(String...

I have this recursive function to reverse a positive integer. Anybody having an efficient algorithm to do the task using fewer recursive calls (but still using recursion), please post here! int countDigit (const int & _X) { if (_X < 10) return 1; return (countDigit(_X / 10) + 1); }...

I'm having trouble trying to delete a item inside a tree structured object. My object is as below TreeNode { string name; ObservableCollection<TreeNode> Children; } I thought if I recursively process through the tree and find my node and delete it but I ran into trouble. I did something along...

I want to create a Tree data structure that consists of TreeNode objects. The root is a TreeNode. Each TreeNode has one parent TreeNode and a list of children TreeNodes. The Tree is built up recursively. I simplified the code to make the example not too difficult. The function get_list_of_values_from_somewhere...

The question comes from Introduction to Algorithms 3rd Edition, P63, Problem 3-6, where it's introduced as Iterated functions. I rewrite it as follows: int T(int n){ for(int count = 0; n > 2 ; ++count) { n = n/log₂(n); } return count; } Then give as tight a bound as...

I have a test df: testdf<-data.frame(x = seq(1,10), y= c(1, 1, 4, 3, 2, 6, 7, 4, 9, 10)) testdf x y 1 1 1 2 2 1 3 3 4 4 4 3 5 5 2 6 6 6 7 7 7 8 8 4 9 9 9 10...

I have a large data frame with columns that are a character string of numbers such as "1, 2, 3, 4". I wish to add a new column that is the average of these numbers. I have set up the following example: set.seed(2015) library(dplyr) a<-c("1, 2, 3, 4", "2, 4,...

I have a BSTD implementation which is inserting values incorrectly and I can't find for the life of me what is going on. EXPECTED ACTUAL -------- ---------- Alex Janice Carlos Janice Elton Janice Janice Zidane Zidane Zidane Implementation private Node<K,E> insert(Node<K,E> node, K key, E elem) { if (node ==...

My Problem statement: Main Folder -SubFolder1 --1.jpg --2.jpg -SUbFolder2 --Subsubfolder ---1.jpg ---2.jpg I have this main folder which has subdirectories and at the last subdirectory, there are images. Now, what I wish to achieve is recursively check if image file(s) exists in a subdirectory If it does, zip all the...

I'm trying to solve a puzzle, which is to reverse engineer this code, to get a list of possible passwords, and from those there should be one that 'stands out', and should work function checkPass(password) { var total = 0; var charlist = "abcdefghijklmnopqrstuvwxyz"; for (var i = 0; i...

When given an array of integers, I'm trying to change each element with the product of the integers before it. For example, int[] array = {2,2,3,4}; is now: {2, 4, 12, 48}; I added each element to a LinkedList, and I'm trying to do this recursively. This is what I...

I'm trying to come up with basic web crawler. The stack keeps track of all the URLs to visit in future. Until the stack gets empty, want to get list of all hrefs used within a web page. Tried to use arguments.calee but it returns: RangeError: Maximum call stack size...

Let's say we have a basic binary tree, capable of being searched recursively: class BinaryTree{ private int Element; private BinaryTree LeftNode; private BinaryTree RightNode; //Class Constructors //Class Methods } I initially learned this design of binary tree and a general tree mainly because it was simple and easy to use....

this is very basic java program for understanding step by step recursive function return value ,but unfortunately i can't realize this output , plz help me to fully understanding this subject , thank you This is my code public class rectest { void myMethod( int counter) { if(counter == 0)...

I'm trying to understand everything that is happening in this little code example in Eloquent Javascript: The Document Object Model (Chapter 13), but I'm not clear on where exactly the value for "time" is being passed into the animate() function before the function itself gets passed into requestAnimationFrame(). What exactly...

The code below contains a recursive method which should always return 7 however it return undefined whenever it has to re-generate a number because the number generated was already contained within the array that is defined at the top of the code. My question is... why is this happening and...

Can someone please explain the following function ? void printNthFromLast(struct node* head, int n) { static int i = 0; if(head == NULL) return; printNthFromLast(head->next, n); if(++i == n) printf("%d", head->data); } I just want to know how order of execution of statements occur in recursion i.e given recursive call...

I am trying to write a procedure that inserts calculated table data into another table. The problem I have is that I need each row's calculated column to be influenced by the result of the previous row's calculated column. I tried to lag the calculation itself but this does not...

I am working on an API to get data, just like the other standard API, it limit on the return numbers of item , e.g. each page return only 1 item in my case. So , I have to get the total_count, page_size (it is 1 at my case), and...

I'm trying to create an implementation of Map that takes collections as keys. What do you even call this conundrum? What is the right way to do the class signature? class SubClass <K extends Collection<E>, V> implements Map<K, V> ^^ Is improper syntax, but indicates what I want to do....

I'm learning F# and I'm building a minesweeper app. As part of that, I'm trying to have a method that detonates all adjacent mines if a mine is detonated, recursively. So if I have a grid like: | 0 | 1 | 2 | ------------------------ 0 | E-1 | M...

I have the task of writing a program called any? that requires an input of a list and one-argument procedure and then tells you if any element in that list satisfies the procedure. ex: (any? odd? (list 2 4 6 8)) -> false I need to use foldr in the...

When client get a CKErrorRequestRateLimited client should perform operation again after RequestRateLimited sec. But what do you do when get some different error type i.e. CKErrorZoneBusy. How do you manage that case? I try to resend message recursively in every 10 sec, but it seems it does not help, because...

I was just curious I have this piece of Java code. My question is what is the reason to return 1.0 * the recursive call? in the else portion of the code My 2nd question is when I declare the E variable as 0.0000001 AND A , X variables as...

To solve my problem, I need to put together all possible arrays of length N, containing -1, 0 and 1, and run them through some function to see whether they meet a certain criterion. I have implemented 2 methods, a triadic numbers method and a recursion. They both return correct...

I am doing some computations, but am having a hard time wrining a program in r that accomplishes what I need. x1<-c('a','b','c','d','a') x2<-c('b','e','g') x3<-c('c','a','h','j') x4<-c('d','l','m','o','p','x','y','z') x5<-c('f','q','a') I am looking of a way to compute y1<-length(intersect(x1,x2)) y2<-length(intersect(x3, union(x1,x2))) y3<-length(intersect(x4, union(x3,union(x1,x2)))) y4<-length(intersect(x5, union(x4, union(x3,union(x1,x2))))) ...

I'm trying to sort an array that can contain different types of structures within itself. Right now I can't seem to get it to recursively sort itself when it has subarrays in the root array. In the following code below, I have a test array that contains two sub arrays,...

I am looking at processing a hierarchical structure in a recursive fashion using C# asynchronous features (TPL/ async/await). Here is an overview of what I am trying to do I have a jobs collection to process as shown below. Each Job has something to do and optionally can have one...

I made a program that generates tiles/pixels. Within this program is a function that is used to fill in gaps and holes, and here is how I intended it to work: A method is given an integer limit. This method then goes through paint bucket-like recursion where it repaints its...

i am trying to reduce a number to a desired range of values, say x until it is less than 100. What I am doing is dividing the number with 10 until it is less than 100. what would be a better approach a recursive one or iterative one.

In Haskell, I recently found the following function useful: listCase :: (a -> [a] -> b) -> [a] -> [b] listCase f [] = [] listCase f (x:xs) = f x xs : listCase f xs I used it to generate sliding windows of size 3 from a list, like...

Please help to understand why does the following code public class HeapQn1 { /** * @param args */ public HeapQn1() { new HeapQn1(); } static HeapQn1 n = new HeapQn1(); public static void main(String[] args) { } } results in java.lang.StackOverflowError at com.rg.test.interview.HeapQn1.<init>(HeapQn1.java:8) at com.rg.test.interview.HeapQn1.<init>(HeapQn1.java:9) ... As per my understanding...

So, I have this function which aims to align the text on the left without cutting words(only white spaces). However my problem is that I cannot find a stopping condition of the function and it goes infinitely. f n "" = "" --weak condition f n s = if n...

So my coding exercise is given the reference to the node count its children. I've decided to use recursion and I was wondering is this a elegant way to do this: Let's assume there is class Node which represent every node in the tree: public Node { int data: Node...

I'm attempting to use recursive methods to solve a maze represented by an int array of 1s and 0s in Java. wasHere[] checks if the method has already parsed that particular set of coordinates, correctPath[] records the answer path to the maze; both of them are initialized with every index...

I don't understand why the code below is not returning the rate variable. The weird thing is that right above the return statement there is a puts statement that actually does print out the right value for rate. def irr(lower_guess, higher_guess, increment, *amounts) rate = lower_guess precision_level = 0.1 while...

I'm writing a code that ask at the user to insert the numbers of the array and then write each numbers, do the same thing in another array, and at the end compare the first array with the second array and print out the bubble sort of all numbers, so...

Assuming I have a list of elements [1,2,3,4,] and a number of bins (let's assume 2 bins), I want to come up with a list of all combinations of splitting up items 1-4 into the 2 bins. Solution should look something like this [{{1}, {2,3,4}}, {{2}, {1,3,4}}, {{3}, {1,2,4}}, {{4},...

This function may work on infinity association lists, and it is easy to find out why: findKey :: (Eq k) => k -> [(k,v)] -> Maybe v findKey key [] = Nothing findKey key ((k,v):xs) = if key == k then Just v else findKey key xs When it find...

I am understanding recursion and so I tried writing reverse a linked list program. I have written the below function but it says segmentation error (core dumped). void reverse(){ if (head -> next == NULL){ return; } reverse (head -> next); struct node *q = (struct node*) malloc (sizeof(struct node));...

As I understood, a List in Haskell is a similar to a Linked-List in C language. So for expressions below: a = [1,2,3] b = [4,5,6] a ++ b Haskell implement this in a recursive way like this: (++) (x:xs) ys = x:xs ++ ys The time complexity for that...

This question already has an answer here: Building a promise chain recursively in javascript - memory considerations 2 answers I'm trying to achieve a pattern in which I invoke an endless recursive loop of thenables (Promise-based chaining) that are likely to run for several hours (I'm playing around with...

I don't understand this, as far as I can tell these two snippets of code should do the same thing. But they aren't. Can someone shine some light as to why this is happening? I am simply trying to find the total files inside a folder. This count should include...

So, I have this function that aligns the text to the left for a given column width. I have already fixed some of its problems, but I am unable to make it not use the decremented parameter once it is called, but to return to the starting value of n....

So I'm trying to make an algorithm that starts at the first "room" and then recursively goes outward and starts deleting all rooms from the outside in. A room is a struct with 4 "doors" (pointers to rooms): North, South, East, and West. The function takes two arguments: pointer to...

I am trying to make a recursive function which should return the sum of digits. The function should have only one argument. So far I have this; public int sumDigits(int n) { if(n%10 == n) // last digit remains return n; else{ int rightdigit; rightdigit = n%10; // taking out...

While working through some Coderbyte challenges, I was able to solve the following problem recursively, but was hoping to get some feedback on how I can improve it. Have the function AdditivePersistence(num) take the num parameter being passed which will always be a positive integer and return its additive persistence...

Given a sorted vector x: x <- c(1,2,4,6,7,10,11,12,15) I am trying to write a small function that will yield a similar sized vector y giving the last consecutive integer in order to group consecutive numbers. In my case it is (defining groups 2, 4, 7, 12 and 15): > y...

I have just started to learn Scala after some experience with functional programming in other languages. def freq(c:Char, y:String, list:List[(Char,Int)]): List[(Char,Int)] = list match{ case _ => freq(c, y.filter(_ == c), list :: List((count(c,y),c))) case nil => list } In the above code I am getting an error when trying...

Suppose I have a list, l<-list(a="",b="",c=list(d="",e=list(f=""),g="")) and it looks like: List of 3 $ a: chr "" $ b: chr "" $ c:List of 3 ..$ d: chr "" ..$ e:List of 1 .. ..$ f: chr "" ..$ g: chr "" Now I want to assign values based on...

Whatever the input, the result is always 0. Why is that ? #include <stdio.h> #include <conio.h> int rekursiv( int v[], int i, int n, int *min ); int main( void ) { int v[ 100 ]; int n, i, min; printf( "Shkruanni n: " ); scanf( "%d", &n ); printf(...

I'm trying to find all possible solutions to the 3X3 magic square. There should be exactly 8 solutions. My code gets them all but there are a lot of repeats. I'm having a hard time tracking the recursive steps to see why I'm getting all the repeats. // This program...

I have written an iterative DFS by implementing a stack. Now I am trying to write the same DFS recursively and I am running into the problems. My question is, when I write it iteratively, I can keep certain global variables, such as paths=[] and I will add into it...

I wrote an implementation of an algorithm for a course with Ruby 2.1 running in Ubuntu. The algorithm was easiest to express utilising recursion. Initially Ruby was raising the "stack level too deep SystemStack" exception due to the large memory requirements of the problem and implementation. To allow the algorithm...

I've search around SOF for a while and read similar post. I didn't find any of those answers satisfactory. The issue i'm having is that I want to traverse a tree until 'the root node' and a target node are the same. If the 'root' == target, I want to...

I'm trying to write a recursive algorithm that returns true if at least one array[i] == i. And false if there is no array[i] = i. Also, the parameters needed are (int * arr, int start, int end). So i'll be traversing the array with a pointer. For example: int...

Can someone please help me understand the significance of the '_' character in the setters and getters of javascript. For example I have the following code which works fine. var user = { get name() { return this._name; }, set name(value) { this._name = value; } }; var me =...

I have a complex data structure that I'm trying to process. Explanation of the data structure: I have a dictionary of classes. The key is a name. The value is a class reference. The class contains two lists of dictionaries. Here's a simple example of my data structure: import scipy.stats...

I am trying to insert node in a binary tree using recursive method. But once its out of the method the root becomes the new node and left child and right child are null. With this I'm trying to learn how recursion works. Also, does recursive method always has to...

Problem: Reverse a singly linked list recursively. I know how to solve this problem, but one of my recursive methods is wrong, I can not figure out what's wrong with this code. Could anyone figure out that? Thanks a lot! Test case: Input: [1,2,3] Output: [3,1] Expected: [3,2,1] public class...

For example, given a set like below - S=[1,3] we want to get the list of list with following values: [[],[1],[3],[1,3]] I used C++ with the following code and it worked perfect for me. However, after I changed it to Java, the code didn't give me right results. Any help?...

I'm working through a toy problem in Ruby: how to produce all possible 10-digit phone numbers where each successive number is adjacent to the last on the keypad. I've represented the adjacent relationships between numbers, and have a recursive function, but my method isn't iterating through the whole solution space....

I'm teaching myself about recursive calling of methods in java. I'm constantly getting StackOverFlowErroron my implementation: public class LimitedRecursion { public void m(int limit) { if (limit == 0) { System.out.println("finished2"); } m(limit - 1); } } i have set the limit to 42 in the main. Can someone point...

This question already has an answer here: What does the comma operator `,` do in C? 8 answers In the below block of code, I am trying to understand how the line return reverse((i++, i)) is working. #include <stdio.h> void reverse(int i); int main() { reverse(1); } void reverse(int...

I have a recursive class defined : case class SettingsRepository(id: Option[BSONObjectID], name: Option[String], children: Option[List[SettingsRepository]]) with a JSON implicit format as below : implicit val repositoryFormat = Json.format[SettingsRepository] How can I do to resolve this compilation error? : No implicit format for Option[List[models.practice.SettingsRepository]] available. In /path/to/the/file.scala:95 95 implicit val repositoryFormat...

So I have a tree of people with children and I only want to get the people with cars. if a child has a car but the parent does not, I want to keep the parent in the tree. I thought the best way would be to use a recursive...

I'm having trouble with my C++ code in xCode. I've tried debugging and I can't fix it. I know it's roughly when my mergeSort() method calls my mergeNumbers() method. I know it's not the method itself because I've run the method without threading and it works just fine. It's when...

I am trying to use the Haskell Diagrams library for drawing binary trees. This is my tree type: data Tree a = Empty | Node { label :: a, left,right :: Tree a } leaf :: a -> Tree a leaf a = Node a Empty Empty This is a...

I am creating a recursive algorithm to brute force a Sudoku puzzle. I have gotten everything to work properly, however, I am trying to figure out how to stop the process once it correctly finishes a puzzle. Here is what I have so far. def solve(board, cell): #calculate row and...

When I git add a folder, the whole content and all subfolders are staged automatically. In case the folder contains subfolders which I do not want to commit, I have to unstage them manually and add them to .gitignore afterwards. The explicit unstaging feels like I'm doing something wrong here....

I've been searching around to practice my recursion, however I've run out of practice problems on codingBat, and a few others. If you've got more suggestions, feel free to comment them! My question is how do YOU identify when a method can simply be turned into a recursive method, even...

I am trying (and failing) to correctly order my recursive CTE. My table consists of a parent-child structure where one task can relate to another on a variety of different levels. For example I could create a task (this is the parent), then create a sub-task from this and then...

The problem I am wondering if is there a natural way of encoding in Isabelle a grammar like this: type_synonym Var = string datatype Value = VInt int | ... datatype Cmd = Skip | NonDeterministicChoice "Cmd set" | ... The motivation would be to give definition a few specification...

I'm trying to write a recursive function which returns the correct nested object within my model, based on an array of indexes. My console log labelled 'inside function' actually shows the correct obj! Which is baffling me as all I do after that is return that obj, but the function...

I have a lot of parse trees like this: ( S ( NP-SBJ ( PRP I ) ) ( [email protected] ( VP ( VBP have ) ( NP ( DT a ) ( [email protected] ( NN savings ) ( NN account ) ) ) ) ( . . ) )...

I'm studying basic Java and I there's a question on a programming assignment that I'm having a lot of trouble with concerning recursive overloading of sort of a search method. Here's what I'm being asked to do: Write a method that accepts a two-dimensional int[][] array as the parameter and...

I'm trying to come up with a solution that takes in a matrix like this: [[1,2,3,4], [5,6,7,8], [9,10,11,12], [13,14,15,16]] and returns an array traversing the array as a spiral, so in this example: [1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10] I'm having trouble getting this recursive solution to work, in which the result array takes the...

So here is my autocomplete functionality: var selected; var itemAdded = false; $('.js-main-search').autocomplete({ minLength: 3, source: function(request, response) { $.getJSON('/dashboard/searchDocumentsAndCompanies.do', { q: request.term}, function(data) { if(data.length == 0){ data = [ {name: 'No matches found', resultType: 'COMPANY', noResults: true}, {name: 'No matches found', resultType: 'BRANCHES', noResults: true}, ]; } data.unshift({name:...

I am trying the coding bat problem repeatFront: Given a string and an int n, return a string made of the first n characters of the string, followed by the first n-1 characters of the string, and so on. You may assume that n is between 0 and the length...

I would like to convert an embedding structure into a flat one. An embedding structure is a set of 0 or more objects, such as: a string or a hash having some string as key and some other embedding structure as value. A flat structure is a set of arrays...