algorithm,recursion,permutation

A common approach is as follows. If you have, say, K bins, then add K-1 special values to your initial array. I will use the -1 value assuming that it never occurs in the initial array; you can choose a different value. So for your example the initial array becomes...

You can always raise an exception: fun last [] = raise Empty | last (x::xs) = last' x xs fun last' x [] = x | last' _ (x::xs) = last' x xs Another option (if you would pardon the pun): fun last [] = NONE | last (x::xs) =...

This looks like a special case of a (jargon here but it can help with googling) paramorphism, a generalisation of primitive recursion to all initial algebras. Reimplementing ListCase Let's have a look at how to reimplement your function using such a combinator. First we define the notion of paramorphism: a...

python,algorithm,function,recursion

Just sort on the last column: sorted(f,key=lambda x: int(x.split(",")[-1])) You can use bisect to find where to put the new data to keep the data ordered after it is sorted once: from bisect import bisect import csv with open("foo.txt") as f: r = list(csv.reader(f)) keys = [int(row[-1]) for row in...

You need to make sure you actually construct and return a new list in your recursive function: sequencize <- function(list, loopn="1") { if (!is.list(list)){ loopn } else { l <- lapply(1:length(list), function(i) sequencize(list[[i]], paste(loopn,i,sep="."))) names(l) <- names(list) l } } str(sequencize(l)) # List of 3 # $ a: chr "1.1"...

java,recursion,binary-tree,nodes

public Node { int data: Node left; Node right; } int countChildren(Node head) { if(head==null) return 0; return ((head.left == null) ? 0 : countChildren(head.left) + 1) + ((head.right == null) ? 0 : countChildren(head.right) + 1); } This is my suggestion....

c++,recursion,methods,private,public

"My intuition is that perhaps this is done to ensure that people using the public class methods don't go full dingus mode and end up calling a recursive function with parameters that won't ever lead to a stopping/base case." Your intuition is right up to some point. head is...

javascript,recursion,promise,bluebird

Catch the failure, wait five seconds, then try again. function doAsyncRecursive() { return doAsyncThing().catch(function() { return Promise.delay(5000).then(doAsyncRecursive); }); } Here doAsyncThing is a function corresponding to the //do async thing comment in the OP's code, defined as returning a promise. In the original code, the success or failure of the...

This will return a set of all detonated cells including the one that started the chain reaction. module Location = type T = {Row: int; Column: int } let subtract l1 l2 = {Row=l1.Row - l2.Row;Column=l1.Column-l2.Colum let detonate (field:Field.T) (start:Cell.T) = let rec inner cells m acc = match cells...

Basically, you are finding all permutations of the array using a recursive permutation algorithm. There are 4 things you need to change: First, start your loop from pos, not 0 Second, swap elements back after recursing (backtracking) Third, only test once you have generated each complete permutation (when pos =...

windows,powershell,batch-file,recursion,cmd

If you retrieve all images using the Get-ChildItem cmdlet you can group it by directory and get all information you need: $root = 'c:' $7zipPath = "C:\Program Files\PeaZip\res\7z\7z.exe" Get-ChildItem $root -recurse -Filter '*.jpg' | group Directory | select -expand name | foreach { $directoryName = get-item $_ | select -expand...

r,if-statement,recursion,vector,integer

Your sapply call is applying fun across all values of x, when you really want it to be applying across all values of i. To get the sapply to do what I assume you want to do, you can do the following: sapply(X = 1:length(x), FUN = fun, x =...

javascript,animation,dom,recursion,requestanimationframe

When you execute this line: requestAnimationFrame(animate);, the function animate will be called inside requestAnimationFrame and will get the time variable passed as an argument. Something like this (narrowed and rough): function requestAnimationFrame(callback) { var time = getTime(); callback(time); //Where callback is your `animate` function }; Of course that requestAnimationFrame does...

java,parsing,recursion,nlp,pseudocode

I wrote this for python. I believe you can read it as a pseudocode. I will edit the post for Java later . I added the Java implementation later. import re # grammar repository grammar_repo = [] s = "( S ( NP-SBJ ( PRP I ) ) ( [email protected]

list,pointers,haskell,recursion,functional-programming

That's pretty much what the recursive solution does. It's the copying of a which takes O(n) (where n is the length of a. The length of b doesn't affect the complexity). There is really no "trick" to copy a list of n elements in O(1) time....

sql-server,recursion,common-table-expression,reportbuilder3.0

This is an iteration based approach to the issue, maybe this helps or someone else can figure out how to do the updates without a loop. The first part of the CTE is to figure out what subjects exist in the hierarchy. It might not be the optimal one but...

You should compile with warnings switched on. rekursiv does not always return a value. Change rekursiv( v, i + 1, n, min ); to return rekursiv( v, i + 1, n, min ); ...

Integer examples are for 32 bit int arithmetics, DWORD is 32bit unsigned int floating pow(x,y)=x^y is usually evaluated like this: How Math.Pow (and so on) actualy works so the fractional exponent can be evaluated: pow(x,y) = exp2(y*log2(x)) this can be done also on fixed point fixed point bignum pow integer...

This is recursive void reverse(int number, int& result) { if (number == 0) return; else { result *= 10; result += number % 10; reverse(number / 10, result ); } } This is how you call it with (545146548) example void main() { int result = 0; reverse(545146548, result); cout...

You'll need a type parameter for the Collection element type, potentially a type parameter for the actual Collection type if you need it, and a type parameter for the values. class SubClass<E, K extends Collection<E>, V> implements Map<K, V> { ... } If you don't need the specific Collection type,...

Here's how I implemented the same program. I think there is something fishy with the second line in your code string letters[8];. Also you may want to check your genNumbers and convert functions. #include <stdlib.h> #include <time.h> #include <stdio.h> int nums[8]; char letters[9]; void genNumbers() { for (int i=0; i<8;...

json,scala,recursion,playframework,play-json

As you've discovered, you can't use the JSON inception macro here, but you can write your own Format (note that I've replaced BSONObjectID with Long for the sake of a complete working example): import play.api.libs.functional.syntax._ import play.api.libs.json._ case class SettingsRepository( id: Option[Long], name: Option[String], children: Option[List[SettingsRepository]] ) implicit val repositoryFormat:...

javascript,jquery,recursion,jquery-ui-autocomplete

Usually when you get a stack overflow error, it is because you have a recursion for which no exit condition exist or is triggered. Looking at your code, here's the function that causes the problem. $('.js-main-search').data("uiAutocomplete").close = function (event) { if (!selected) { $('.js-main-search').data("uiAutocomplete").close.apply(this, arguments); } selected = false; };...

It seems that you mean the following #include <stdio.h> #include <string.h> char * combine_strings( char *result, const char *s1, const char *s2 ) { if ( *s1 == '\0' && *s2 == '\0' ) { *result = '\0'; return result; } else if ( *s1 == '\0' ) { *result++...

Wihtout knowing the exact error message, I am not 100% sure what is the problem, but I guess it is the following: Your function looks like this (simplified): int calc(int x) { if(someCondition){ if(otherCondition){} calc(x+1); } else { return mul; } } The problem is that if someCondition is true,...

recursion,types,julia-lang,type-alias

Dose this work for what you are doing? typealias NestedTuple0{N,T} Tuple{Union(T,N),Union(T,N)} typealias NestedTuple{T} NestedTuple0{NestedTuple0{T},T} Note: I am only able to try this in 036, not 04 An exmple of use: function rnt(p) np = 0.95*p a=rand() <p ? rnt(np) : 1 b=rand() <p ? rnt(np) : 2 (a,b) end x=rnt(1.0)...

The problem is that you are doing an O(n) operation each time in triadicIteraction here: for n in range(signsQty): signs[n] = 1-combCopy%3 # [0,1,2] -> [1,0,-1], correct range for signs combCopy = combCopy//3 To see this, you can use the profile module from the standard library and implementing the function...

java,recursion,stack-overflow,maze

I think there is no bug as such (not that I can see) but you are recursing way too much which caused this issue. I am not sure what values are you feeding into the program, but I was able to notice the issue with initializing the above program with...

java,recursion,binary-search-tree

Your problem is that when you return from one level in the recursive stack indicating that you found the target, you forget to use this information at the higher levels to stop the search. Try this (remove the print statements in your final product of course): private static boolean modifiedInorderTraversal(Node...

You could use sapply to loop through the list returned by strsplit, handling each of the list elements: sapply(strsplit((df$a), split=", "), function(x) mean(as.numeric(x))) # [1] 2.5 5.0 7.5 ...

javascript,arrays,function,recursion

You're missing a return when calling steamroller recursively. Fixed code: 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;} return steamroller(arr); } steamroller([1, [2], [3, [[4]]]]); ...

I would deal with this by making a small change to my design (assuming the snippet in your question is pseudocode for a class): TreeNode { string name; TreeNode Parent; ObservableCollection<TreeNode> Children; public void Delete() { Parent.Children.Remove(this); } } This makes a little bit more work for you maintaining an...

python,recursion,depth-first-search

Try something like this: def all_paths_dfs(graph, start, end, path=None): if path is None: path = [] path.append(start) all_paths = set() if start == end: all_paths.add(tuple(path)) else: for neighbor in graph[start]: if neighbor not in path: all_paths |= all_paths_dfs(graph, neighbor, end, path) path.pop() return all_paths if __name__ == "__main__": graph =...

java,recursion,binary-tree,nodes

I suppose the problem comes from if (node == null){ root = newNode; } You are traversing the tree and in the last step you are asking the left/right child of a leaf node. This hasn't one, so it's child is null. This is the value returned by the recursive...

In your first code, Case 1: return reverse(i++); will cause stack overflow as the value of unchanged i will be used as the function argument (as the effect of post increment will be sequenced after the function call), and then i will be increased. So, it is basically calling the...

algorithm,recursion,big-o,complexity-theory,recurrence

It looks like the lower bound is pretty good, so I tried to proof that the upper bound is O(log n / log log n). But let me first explain the other bounds (just for a better understanding). TL;DR T(n) is in Θ(log n / log log n). T(n) is...

javascript,arrays,algorithm,recursion,matrix

Your code is very close but it is doing more than it needs to do. Here I simplify and bug fix: var input = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]; var spiralTraversal = function(matriks){ var result = []; var goAround...

The line does executes, how can you say it does not executes. I have added the syso statement, it does print, actually you are calling substring in a recursion, once the length becomes 1, it will execute. public static String reverseString(String str) { String reverse = ""; if (str.length() ==...

If you just want a flat list then this is simple recursion. In pseudo-code, it would look like this: IList<Employee> GetEmployees(Employee manager) { var result = new List<Employee>(); var employees = _employeeDb.Employees .Where(e => e.ManagerEmployeeNumber == manager.EmployeeNumber) .ToList(); foreach (var employee in employees) { result.Add(employee); result.AddRange(GetEmployees(employee)); } return result; }...

java,debugging,recursion,immutability

It is the new node, that should take its content from node in general. It must be the equals/compare. More solid code would be: int comparison = key.compareTo(node.getKey()); if (comparison < 0) { return new Node<K, E>( insert(node.getLeft(), key, elem), node.getKey(), node.getElem(), node.getRight()); } else if (comparison == 0) {...

Recursion is your friend: require 'set' def t_h(inp, prefix = []) if (inp.is_a?(Hash)) result = [] inp.each do |k,v| pprefix = prefix.dup result << t_h(v, pprefix << k) end return result.flatten(1) elsif (inp.is_a?(Set)) result = [] inp.each do |el| result << t_h(el, prefix) end return result.flatten(1) else pprefix = prefix.dup...

The runtime error that you are experiencing here is a stack overflow. The fact that you do not experience it when modifying the definition to use a stuck does not mean it will not occur. Increase the iteration depth just slightly you will also be able to achieve the same...

I could provide you with exact code that works, but I feel like you're trying to discover things yourself, There are plenty of examples on the Internet already. So here's a more general hint - you can rework your algorithm to work like this: def solve(problem): if problem is trivial...

Whenever the constructor is called, its return address is pushed onto the stack. As the stack is finite and smaller than the heap memory, you are getting error like StackOverflowError rather than OutOfMemoryError. The constructor is a method and since the heap memory is much larger than the stack memory,...

java,function,recursion,sum,digit

You aren't actually recursing. You've setup your base case, but when solving a problem recursively you should have code within the function that calls the function itself. So you're missing a line that calls sumDigits, with a smaller argument. Consider two important parts of a recursive soutlion: The base case....

Ah I found your problem. You must only return the empty string if n == 0. Returning str will return that extra last letter a second time as the call repeatFront(Ch, 1) and repeatFront(C, 0) both return C. Fix by changing the return on n==0 to return ""; : if(n==0)...

php,function,recursion,return,return-value

You are not assigning the return value of the recursive call back to $filter_video, change to: if ($total_count > $page_size * $page_number) { $filter_video = get_video_list($page_number, $filter_video); } Or, even better: pass by reference. This eliminates the need for return values altogether, especially useful for recursive functions (notice &$filter_video in...

javascript,recursion,stack,intern

The easy way to perform recursion in a Command chain (or any Promise chain, actually!) is to hold your stack in closure, then call the method that does the work recursively as a Promise callback until your stack is exhausted. Once the stack is resolved undefined will be returned by...

As you can see in the documentation: https://developer.apple.com/library/ios/documentation/CloudKit/Reference/CloudKit_constants/#//apple_ref/c/tdef/CKErrorCode ZoneBusy The server is too busy to handle this zone operation. Try the operation again in a few seconds. If you encounter this error again, increase the delay time exponentially for each subsequent retry to minimize server contention for the zone. So...

Recursion is a way of thinking that's gained by practice. So congratulations on your attempt. It's not correct, but don't be discouraged. Here are two ways to go about the problem. Your goal is to subdivide it into a smaller version of itself plus a (hopefully easy and fast to...

Basically, recursion can simulate every loop, so you could create a recursive method for just about every method containing a loop – however it is not guaranteed that the recursive version will finish (because your looped version may use state to cache results, while your recursive version doesn't) or even...

c++,pointers,recursion,struct,allocation

I don't understand your algorithm, but I can tell where you are failing. switch (coord) { case 'N':{ room_ptr->south->north = NULL; room_ptr->south = NULL; } case 'S':{ room_ptr->north->south = NULL; // <-- Program Fails Here room_ptr->north = NULL; } room_ptr->north at this moment is a null pointer and you are...

recursion,isabelle,theorem-proving

The theoretical explanation First of all, the notion of a datatype of commands that allow non-deterministic choice from an arbitrary set of commands is deeply problematic. I will explain why. Suppose you had a datatype datatype Cmd = Skip | NonDeterministicChoice "Cmd set" like you wanted. Let A := (UNIV...

ruby,algorithm,search,recursion

The first time you enter the adjacencies[to_append].each, you immediately return from the method, therefore the loop will never be executed more than once. You need to return a list of phone numbers instead of just a single phone number build that list somehow in your recursive call ...

c++,arrays,algorithm,recursion

Do a regular binary search but with the (array[i] == i) condition instead of searching for a particular value. If (array[i] > i) move left else move right Of course this requires the values to be sorted, but your example indicates that is the case....

javascript,algorithm,recursion

I'm going to extend @georg's answer and provide a full implementation var additivePersistance = (function () { function sumOfDigits (n) { var ret = 0; n.toString().split('').forEach(function (i) { ret += parseInt(i, 10); }); return ret; } return function additivePersistance (n) { if (n < 10) { return 0; } return...

python,list,dictionary,recursion

It's a bug. Fixed in 0.15.0 You're passing in empty arrays, and the function handles it incorrectly. Either update your Scipy, or skip if the arrays are empty (though check that your data isn't wrong and that it makes sense to have an empty array there). Some suggestions for your...

c#,.net,multithreading,asynchronous,recursion

If GetDataAsync is the only blocking operation that you have, then you can use asynchronous programming throughout, avoiding the need for Parallel.ForEach calls or blocking Wait calls. public async Task Process() { WebJob[] jobs = CreateWebJobs(); // dummy jobs await Task.WhenAll(jobs.Select(ExecuteJob)); } private async Task ExecuteJob(WebJob job, [CallerMemberName] string memberName...

This implementation of nth should be what you are looking for: function nth(list, number){ if (list.rest != null && number !=0 ) { number--; return nth(list.rest, number); } return list.value; } When the recursion "termination condition" is reached i.e. that the list rest element is null and that number ===...

Why will the method stop (and give the correct answer) if I do not remove Character.isDigit(s.charAt(0)) in the return? It stops because the && operator short-circuits the expression: return (Character.isDigit(s.charAt(0)) && isRoundNumber(s.substring(1))); With &&, if the first operand (the bit before the &&) is false, the second operand is...

I fixed the code. Essentially I'd been going about the problem all wrong: I was missing a case check. What I mean is that there are four possible outcomes for each subsequent recursion of the method: The end of the array has been reached and the returned value should be...

string,function,haskell,if-statement,recursion

Your code doesn't handle the case where a line is shorter than the maximum length. This is somewhat obscured by another bug: n is decremented until a whitespace is found, and then f is called recursively passing this decremented value of n, effectively limiting all subsequent lines to the length...

scala,recursion,case,frequency

Cons operator (::) is an infix operator so if you want to get a type of List[T] and not List[List[T]] then you should write freq(c, y.filter(_ == c),(count(c,y),c)) :: list) ...

string,function,haskell,recursion,parameters

Yes, once you call again f with a new value of n, it has no way to reference the old value of n unless you pass it explicitly. One way to do it is to have an internal recursive function with its width parameter, as you have, but that can...

We learned in class it's kinda like dominos (each method call is like setting up one domino). When you have void myMethod( int counter) { if(counter == 0) return; else { myMethod(counter-1); System.out.println(""+counter); return; } } The counter is going in at 3, then 2 then 1, once counter hit's...

java,recursion,parameter-passing,bucket

There are a few problems with your code, I don't think you need recursion at all for this. A loop would do. the tempBoolean variable is always set to false; Your num variable falls back to original value after every recursive call, hence the recursion will process more pixels than...

If you only need a Test whether a car is available you could use this: public Person CheckPerson(Person person) { return person.Cars.Any() || person.Children.Any(x => CheckPerson(x) != null) ? person : null; } But I think you should return an IEnumerable<Person> that contains all persons that have a car (or...

javascript,recursion,getter-setter

It's quite simple. In your second example, the get, calls itself. Since you reference the property me.name, JavaScript needs to get that property. When this happens, the getter is triggered. Using your second example, JavaScript calls the getter, but the getter is then told to do the exact same thing:...

You can approach a solution to this by using a while loop rather than recursion: function getJsonStuff($page_id) { $url = "https://www.example.com/id=" . $page_id . "&pageToken="; $results = array(); $token = ""; while(true) { $json = json_decode(file_get_contents($url . $token), true); if (!isset($json["token"]) || empty($json["token"])) { break; } $token = $json["token"]; $results[]...

python-3.x,recursion,tree,member

Be very, very cautious of this: def __init__(self, value, parent=None, children=[]): and this: def insertChildren(self, children=[]): The initial value -- the list object created by [] -- is a single object which is shared. Widely. You are using this single, shared, default list object widely. You may want to use...

It doesn't work, because in the first pass of the helper method ListNode prev = reverseList(head.next); returns [3, 2], and then you assign your old head (1) to be the next node after the new head of the reversed list (3). Therefore, the end result is [3, 1]....

Edit In hindsight, this problem is a running partitioned maximum over Column1 * 2. It can be done as simply as SELECT Id, Column1, Model, Product, MAX(Column1 * 2) OVER (Partition BY Model, Product Order BY ID ASC) AS Column2 FROM Table1; Fiddle Original Answer Here's a way to do...

Iteration is your friend here. Iteration: "repeat something until it's done." Recursion: "Solve a large problem by breaking it up into smaller and smaller pieces until you can solve it; combine the results." Recursion is also much slower usually, and when iteration is applicable it's almost always prefered. Related question:...

Afraid I don't know much about python, but I can probably help you with the algorithm. The encoding process repeats the following: multiply the current total by 17 add a value (a = 1, b = 2, ..., z = 26) for the next letter to the total So at...

You can pass in a parameter marking visited rows: get_acc_x<-function(rownum, seen){ if (seen[rownum]) { # Whatever you want to do, cycle detected } seen[rownum] <- T if(testdf[rownum, 'x'] == testdf[rownum, 'y']){ return(rownum) }else{ get_acc_x(testdf[rownum, 'y'], seen) } } When calling, use get_acc_x(rownum, rep(F, nrow(df)) to pass in an all False...

java,c++,algorithm,recursion,dfs

In the line res.add(temp); temp is a reference. You are adding a reference to the same list (itemList) every time you add it. Try changing it to something list res.add(new ArrayList(temp)); so that it copies the list instead....

java,recursion,nullpointerexception,linked-list

It looks like you were getting a bit tied up in the recursion. I modified your method to accept a Node along with the product from the previous iteration. At each step of the iteration I update the value in the already-existing List, so there is no need for using...

When you're recursing arguments.callee(data.sub, array); you're not returning the result, instead you're ignoring the result and returning data from the initial call. Try adding a return to that line so that the result of the recursive call is the result of the overall function. Also be aware that arguments.callee won't...

ruby,linux,bash,recursion,ulimit

I believe the ulimit needs to be bigger due to Ruby's boilerplate around function calls. In /vm_eval.c we see this: rb_call0 - this is used to execute Ruby's functions. It accepts 6 arguments. this in turn calls vm_call0, which accepts 7 arguments. this in turn calls vm_call0_body which accepts 3...

sql,tsql,recursion,order,hierarchy

The easiest way would be to pad the keys to a fixed length. e.g. 038,007 will be ordered before 038,012 But the padding length would have to be safe for the largest taskid. Although you could keep your path trimmed for readability and create an extra padded field for sorting....

java,arrays,recursion,bubble-sort

You mention in the comments that you've already solved bubblesort. So I'm going to assume you have a method with the signature void bubbleSort(int[] arr). Your code shows you understand how to acquire an array from the user, so we don't need to handle that. Now what you're describing is...

In the recursive case, you'll want to return as well. This will enable the base case to return the value that was generated through all the recursive calls that came before. Try this: var id = [1,2,3,4,5,6]; function generatePlayerId(){ var check = false; var tempId = Math.floor(Math.random()*7)+1; for(var i=0;i<id.length;i++){ if(tempId...

Using the modified code from @Frank nx <- 5L xx <- mget(paste0('x', 1:nx)) cux <- Reduce(union, xx, accumulate=TRUE) lengths(Map(intersect, xx[-1], cux[-nx] )) ...

I just want to know how order of execution of statements occur in recursion i.e given recursive call is before the second if condition , so will the second if condition be checked ? Yes, the second if condition will be checked, after the recursive call returns. And it...

javascript,python,arrays,recursion,go

If you give me some feedback on this I can edit it because it doesn't do exactly what you asked but it is the jist. I'll edit with a technical explanation of what has to be changed to meet your exact example. package main import "fmt" func main() { words...

ios,objective-c,arrays,recursion,comparator

The comparator is called for every comparison. That means it is invoked multiple times for every element. Every subarray is then sorted multiple times. Before first sorting, you should backtrack the structure and sort the inner structures first instead of having a recursive comparator. In other words, don't mix comparator...

This doesn't finish the recursion, since you don't exit the method when the condition is met, and you still make the next recursive call (m(limit - 1);) : if (limit == 0) { System.out.println("finished2"); } m(limit - 1); This will end the recursion : if (limit == 0) { System.out.println("finished2");...

When a equals 0 it causes f'(x) = 2a to go to 0 in which case you get division by 0 in this step: a = (a * a + x) / (2 * a); When f'(x) goes to 0, it indicates you are at a minimum or maximum: http://en.wikipedia.org/wiki/Newton%27s_method...

You have three return statements in play if (n < 10 && n==7) return 1; if (n < 10 && n!=7) return 0; else return count7(n/10) + count; Only the third one (the recursive case) uses the count variable at all. When you do count7(7), that triggers the base case...

python,recursion,turtle-graphics

The example invocation you posted (spiral( 100, 90, 0.9 )) seems to treat the second parameter as the degree of each turn whereas you treat it as the number of turns to make a complete 360 degree turn in your code. Either change the call to spiral(20, 4, 0.9) or...