recursion,mapping,lisp , Mapping function in LISP


Mapping function in LISP

Question:

Tag: recursion,mapping,lisp

I need your help on something. I have a list in input:

(1 ((2 3) (4 ((5) (6)))) ((7 8) (9 10)) 11)

I want to receive in output the following:

((1 2 3 7 8 11)

 (1 2 3 9 10 11)

 (1 4 5 7 8 11)

 (1 4 5 9 10 11)

 (1 4 6 7 8 11)

 (1 4 6 9 10 11))

The functions such as mapcar, mapcan, maplist... do not help. I think that it is necessary to use recursive function, but do not have any idea how.


Answer:

The function you described seems to be DNF calculation. Here is my solution:

(defun dnf (f)
  (when f
    (if (consp f)
        (let ((f-car-dnf (dnf (car f)))
              (f-cdr-dnf (dnf (cdr f))))
          (if (or (null f-cdr-dnf) (every #'consp f))
              (append f-car-dnf f-cdr-dnf)
              (mapcan
                (lambda (f-cdr-cj)
                        (mapcar (lambda (f-car-cj) (append f-car-cj f-cdr-cj))
                                f-car-dnf))
                f-cdr-dnf)))
        `((,f)))))

Is it an intern task?


Related:


Recursive function with local variable not executing if statement


java,recursion
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...

Recursive average for hierarchical organization


sql-server,recursion,common-table-expression,reportbuilder3.0
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...

Decremented value called in the recursion in Haskell


string,function,haskell,recursion,parameters
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....

Recursive function returns undefined when there is only one numerical possibility


javascript,recursion
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...

Recursive algorithm that returns a bool when checking if array[i] == i (must be O(log n))


c++,arrays,algorithm,recursion
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...

3 X 3 magic square recursively


c++,algorithm,math,recursion
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...

EXC_BAD_ACCESS error occurring when running recursive merge sort method in a thread


c++,multithreading,sorting,recursion
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...

Recurions: simple spiral with python turtle


python,recursion,turtle-graphics
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...

sum of Digits through Recursion


java,function,recursion,sum,digit
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...

Recusively count children nodes in binary tree


java,recursion,binary-tree,nodes
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...

In order Traversal Breaking Out Of Recursive Loop


java,recursion,binary-search-tree
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...

Python recursive function not recursing


python,recursion
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...

algorithm to get all combinations of splitting up N items into K bins


algorithm,recursion,permutation
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},...

R Creating a Character Column from a Numeric Column w/o using For Loop


r,for-loop,mapping,character,lookup
I am trying to create a column of characters based on an existing column of numbers, preferably without using a for loop. I have come up with a variety of ways to do this, but I keep feeling like I'm making this far more complicated than it needs to be....

Scala first program issue


scala,recursion,case,frequency
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...

js recursive function not returning correct child object


javascript,recursion
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...

JavaScript objects: 'addEventListener is not a function'


javascript,html,object,canvas,mapping
I create an array of JavaScript objects called elements and loop through it in order to draw every one on a canvas as well as hooking up a few event handlers to it. However, I get an error stating that 'Uncaught TypeError: elements[i].addEventListener is not a function' Here is the...

Stopping condition on a recursive function - Haskell


string,function,haskell,if-statement,recursion
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...

Recursion with termination condition Java


java,recursion
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...

Java : recursive constructor call and stackoverflow error


java,recursion,constructor
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...

R: split string into numeric and return the mean as a new column in a data frame


r,recursion,dplyr,strsplit
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,...

How does ((a++,b)) work? [duplicate]


c,function,recursion,comma
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...

How can I declare a counter inside of my recursive function? (Additive Persistence: Coderbyte)


javascript,algorithm,recursion
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...

Getting all Employees under a Manager C#


c#,sql,.net,recursion
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...

Finding minimum with a recursive function


c,recursion,minimum
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(...

BSTD inorder traversal produces erroneous behaviour


java,debugging,recursion,immutability
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 ==...

chaining recursive promise with bluebird


javascript,recursion,promise,bluebird
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...

Recursive Lag Column Calculation in SQL


sql,sql-server,recursion
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...

Reversing an integer using recursive method in C++


c++,recursion
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); }...

Reverse Linked List recursively, why it is wrong


recursion
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...

How do I clear an array at the end of a do-while loop in C++?


c++,arrays,recursion,do-while
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...

Recursion with the least sideeffect


c#,recursion,side-effects
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...

Too much recursion - jquery - autocomplete


javascript,jquery,recursion,jquery-ui-autocomplete
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:...

Eloquent Javascript: DOM Animation snippet


javascript,animation,dom,recursion,requestanimationframe
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...

Recursion of Linked List


java,recursion,nullpointerexception,linked-list
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...

BAD_ACCESS during recursive calls in Swift


swift,recursion
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...

Selenium Web Driver : How to map html elements to Java Object.


selenium,webdriver,mapping
As part of Selenium Web-driver learning I came across a scenario. Please let me know the professional approach to proceed. I am testing a eCommerce application where while I click on Mobile link all mobile phones are getting displayed.I want to check whether they are sorted based on name and...

Mapping from One Sheet to Another Fill Unfilled chracter


excel,excel-vba,printing,header,mapping
So I have one excel document that has partially filled character array ("|" shows excel column line): Current Result ("_" is a space): 1111GGH80100022190 1112QQH80100023201 1113GGH80100045201 1114AAH80100025190 So my current code outputs this above result. The problem is that characters 1-5 and 21-24 get skipped over. In general if there...

Recursive solution doesn't iterate correctly


ruby,algorithm,search,recursion
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....

T-SQL Ordering a Recursive Query - Parent/Child Structure


sql,tsql,recursion,order,hierarchy
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...

R: recursive function to give groups of consecutive numbers


r,if-statement,recursion,vector,integer
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...

My function will log a value to the console, but it won't return the same value - why? [duplicate]


javascript,arrays,function,recursion
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...

Insert node recursively


java,recursion,binary-tree,nodes
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...

Python RuntimeError: maximum recursion depth exceeded in cmp


python,list,dictionary,recursion
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...

Use Recursion to get Subsets of an array. C++ and Java give me different results


java,c++,algorithm,recursion,dfs
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?...

Recursion scheme in Haskell for repeatedly breaking datatypes into “head” and “tail” and yielding a structure of results


haskell,recursion
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...

How to flatten a structure of embedded Set and Hash


ruby,recursion
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...

Spiral traversal of a matrix - recursive solution in JavaScript


javascript,arrays,algorithm,recursion,matrix
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...

Isabelle: Unsupported recursive occurrence of a datatype via type constructor “Set.set”


recursion,isabelle,theorem-proving
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...

Identifying methods that can be converted into a recursive method


java,recursion
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...