r/dailyprogrammer • u/Elite6809 1 1 • Mar 15 '15
[2015-03-16] Challenge #206 [Easy] Recurrence Relations, part 1
(Easy): Recurrence Relations, part 1
A recurrence relation is a mathematical construct for defining a series of numbers. It works by first giving an initial term, and then recursively defining the rest of the series as functions of the first one. For example, let's say we have a series of numbers called u, which is defined by this recurrence relation:
u[0] = 1
u[n+1] = 2 * u[n]The first relation tells us that u(0), the first term in the series, is 1. The second relation says that, given the n-th term u(n), the next term (u(n+1)) is the previous term multiplied by two. So, to get the second term in the series, you multiply the first term by two, to get 2. To get the third term in the series, you multiply the second term by two, to get 4.
Recurrence relations get their name in part due to their recursive nature, as successive terms are essentially defined as recursive application of a function, like this Python example:
def recurrence(n):
return n * 2
first_term = 1
second_term = recurrence(first_term)
third_term = recurrence(recurrence(first_term))
fourth_term = recurrence(third_term) # or recurrence(recurrence(recurrence(first_term)))Or, with the help of another function to apply the recurrence function for us:
def get_nth_term(recurrence_relation, first_term, n):
if n == 0:
return first_term
else:
return get_nth_term(recurrence_relation, recurrence_relation(first_term), n - 1)
sixteenth_term = get_nth_term(recurrence, first_term, 16) #65536You get the idea. Today you will be writing a program to compute the n-th term of a given series defined by a recurrence relation.
Formal Inputs and Outputs
Input Description
You will first accept a line of input like this one:
*3 +2 *2This string means that, to get the next term in the series, you multiply by three, add two, then multiply by two. The operation that takes place is the first character of every space-separated part of the line, and the possible characters are + for add, - for subtract, * for multiply, and / for divide; the number given can be any real number. Next, you will accept the starting value, like so:
0Finally, you will accept the term number to print to (where the first term in the series is term 0):
7(this input can be viewed on Wolfram|Alpha.)
Output Description
You are to print all terms in the series, up to the given term number, like so:
Term 0: 0
Term 1: 4
Term 2: 28
Term 3: 172
Term 4: 1036
Term 5: 6220
Term 6: 37324
Term 7: 223948Sample Inputs and Outputs
Series 1
This series starts with 1, and for each successive member of the series, will multiply the last one by two and add one.
Input
*2 +1
1
10Output
Term 0: 1
Term 1: 3
Term 2: 7
Term 3: 15
Term 4: 31
Term 5: 63
Term 6: 127
Term 7: 255
Term 8: 511
Term 9: 1023
Term 10: 2047Series 2
This one is a bit different. This just multiplies each successive term by -2. Notice how the series oscillates between positive and negative numbers?
Input
*-2
1
8Output
Term 0: 1
Term 1: -2
Term 2: 4
Term 3: -8
Term 4: 16
Term 5: -32
Term 6: 64
Term 7: -128
Term 8: 256Series 3
Input
+2 *3 -5
0
10Output
Term 0: 0
Term 1: 1
Term 2: 4
Term 3: 13
Term 4: 40
Term 5: 121
Term 6: 364
Term 7: 1093
Term 8: 3280
Term 9: 9841
Term 10: 29524Notes
More on recurrence relations on Wikipedia. Have a cool idea for a challenge? Submit it to /r/DailyProgrammer_Ideas!
35
u/skeeto -9 8 Mar 16 '15 edited Mar 17 '15
C, executing via x86_64 JIT compiler. This was a lot of fun to write! It compiles the recurrence relation into a function at run time, then calls that function over and over again to iterate it. In theory this should be incredibly fast, though there's no optimization step.
So how does it work? It uses
mmap()+mprotect()to grab a chunk of executable memory. Memory allocated the normal way (malloc()) is not executable on modern systems for security reasons. It then writes raw machine instructions into that memory (asmbuf_ins(),asmbuf_immediate()). Finally it assigns a function pointer to that memory and calls into it, executing the instructions while the ink is still wet.It uses x86_64 instructions and the System V AMD64 calling convention (e.g. everyone but Windows). To port to Windows, both
mmap()would have to be changed toVirtualAlloc()and the calling convention would need to be adjusted.Update edit: I wrote a patch that ports it to work on Windows instead.
While I know some x86 assembly, I don't actually know a good way to work out the encodings by hand, so I just disassembled the output of GCC/GAS with simple examples until I figured out the raw machine instructions I needed.
6
u/adrian17 1 4 Mar 16 '15 edited Mar 16 '15
J solution.
Explanation: the input expression
*3 +2 *2is converted to a string in the form(*&2)@(+&2)@(*&3), which is directly parsed as a J function with". 'f=:', function_string_here. The actual calculations is just thef^:(<n) startpart, the rest is input/output handling. The solution deviates from the challenge description in one place - negative numbers have to be written as _1and division as %(you can use "/" now), so the tokenizer can recognize them.edit: oneliner (sans the optional boilerplate):
Sample output:
5
u/marchelzo Mar 16 '15
Here's a Haskell one; I'm pretty happy with the way it turned out.
2
u/Quitechsol Mar 16 '15 edited Mar 17 '15
Java solution!
I really enjoy recursion for some odd reason, so this was fun, although it did feel like a glorified while loop. Well, here it is, my solution functions on the assumption that there is white space between a number the next operator (i.e. *2 -1), otherwise it will not work. Sorry, I cheeped out, all the given inputs had this format so... yeah, well here it is, critique is always welcome :)
2
u/wizao 1 0 Mar 16 '15
Should division truncate? I'm only asking because I noticed a number of solutions are using integer division. If there will be other parts to this challenge, it will be good if everybody uses the same.
2
u/ProdigalHacker Mar 19 '15
Python, a bit late to the party, this is my first time on this subreddit and actually the first coding I've done in about a year (and my previous experience wasn't exactly extensive). Trying to get back into things a bit and maintain the few skills I've picked up thus far.
I considered using a function to do most of the work, but given how relatively little there is to do overall, it didn't seem necessary.
This took me far longer than I'd like to admit, but I didn't have to look up too much reference material, so I'm mostly pleased with myself. Feedback is certainly appreciated.
9
u/krismaz 0 1 Mar 16 '15 edited Mar 16 '15
Nim. First ever Nim program even.
1
u/Elite6809 1 1 Mar 15 '15
This F# solution over-eggs the pudding somewhat, but it will make it easier for me to solve Part 2 on Friday. https://gist.github.com/Quackmatic/796387d5acef8bf5394c
4
u/fvandepitte 0 0 Mar 16 '15 edited Mar 17 '15
C++ with wrapper classes. If you have any feedback, please do so.
New Code after feedback from /u/h2g2_researcher
Old Code (bit lengthy):
Output:
EDIT: Did some cleanup after feedback
1
u/christopherLikesCake Mar 18 '15
here is my submission. I just created an account so I can submit yet which makes me sad in my white face but anyway I can not get the depth code to work. It will make sense when you see it. Any idea as to why? thank you
1
u/sbhansf Mar 20 '15
First attempt at one of these (Python 2):
1
u/amithgeorge Mar 29 '15
I only recently discovered this subreddit, so am going through the challenges and posting solutions if I happened to discover something interesting while solving it. Please bear with me :)
I initially solved the problem rather quickly. Didn't use recursion. Used reduce (Aggregate) twice. Once to create the recurrence forumla function from the input. Once to generate the relevant n terms.
The interesting thing was when I tried to make the code work with an initial value of any numeric type. A generic solution. That's when I realized the following:
Parsemethod, so as to convert the string operands to the appropriate type.I am also including the original integer specific code I had written - to contrast the complexity added by allowing for generic initial values.
Comments are welcome :)
C# <- Edited to add programming language used.
Original code meant to handle integers
Generic code
1
u/theforemancrew Apr 26 '15
J Solution. Sorry I'm late to the game.
You can use J's simple precedence rules and built-in tokenizer here. Repeat the expression the requisite # of times, reverse it, then tack the start value onto the end. The tokenizer keeps you from reversing the digits of numbers.
(The only other hitch is you have to replace non-commutative - and % with * and +, using rplc.)
Sample output:
1
u/marvin_the_martian May 03 '15
Python
3
u/Godspiral 3 3 Mar 16 '15 edited Mar 16 '15
In J, with these 2 utility adverbs
Y =: (&{::)(@:])
X =: (&{::)(@:[)
if you really want the formatting:
3
u/Stenwulf Mar 16 '15
Giving this a shot in Java
Sample Output:
4
u/ibeattetris Mar 16 '15 edited Mar 17 '15
C# Solution. I've been trying. To incorporate more "functional" techniques in my tool kit. This might suffer a bit in readability. Edit: I can't seem to get the formatting write to hide all the code. Edit2: Finally Fixed
2
u/joyeusenoelle Mar 15 '15
Python 3. Unoptimized, but it does the job.
2
u/G33kDude 1 1 Mar 16 '15
Solution in AutoHotkey
2
u/Jberczel Mar 16 '15
ruby (iterative) solution. avoided using eval and parsed the recurrence relation instead.
2
u/nil_zirilrash Mar 16 '15
Ada. It's a neat language, but string processing can be a bit of a pain at times, especially when the standard library does not have a string split function that I know of.
2
u/ocus Mar 16 '15
PHP solution (my modest contribution):
Wrap each part of the expression with parenthesis and eval the evil.
2
u/h2g2_researcher Mar 16 '15
Standards conforming C++.
It parses the stream, using one of the function objects included in the standard library to create a function by binding the value to the second argument.
The parser then calls itself recursively to get what the rest of the chain does. A lambda is used to chain the two function objects together.
All told that is <30 lines of code, 12 of which goes to a switch statement to choose whether to use an add, divide, etc ... (This could be made smaller by using a sparse array, but whatever. I don't feel like golfing it.)
The main function is then trivial: it just extracts the data, feeds it into the transform function and then runs a loop to output the results.
2
u/hutsboR 3 0 Mar 16 '15 edited Mar 16 '15
Elixir:
Usage:
Outputs a list of tuples in the form {nth term, n}Follows output spec.2
u/vesche Mar 16 '15
Python
2
u/kirsybuu 0 1 Mar 16 '15
D Language
2
u/NoobOfProgramming Mar 16 '15
The code is C++, but i solved it using math, not programming:
2
u/ChiefSnoopy Mar 16 '15
Haven't submitted a solution in a while, so just swung over to do the first challenge I saw. Here's my solution:
Python 3
2
u/armakuni Mar 17 '15
My solution in Lua 5.3. I create the recursive function from a string.
2
u/wizao 1 0 Mar 18 '15 edited Mar 22 '15
Haskell. Using arithmetic:
2
u/znl50 Mar 18 '15
Hope I'm not to late. Here's in java, I'm a first timer so any feedback is welcome!
2
u/patrickwonders Mar 19 '15
I discovered this reddit after reading this blog post: http://nullprogram.com/blog/2015/03/19/
After that blog post, I thought about how easy JIT is to do in Lisp. The solution here is in Common Lisp. I haven't made an effort to restrict it to integers that fit in a machine register, so the compiled functions created here are not as streamlined as the ones in the blog post (but they could be with only a tiny bit more effort). Leaving it as it is though, this allows it to use arbitrary precision integers, rationals, floating point numbers, or complex numbers.
Sample input using complex numbers:
Output of the above:
2
u/Espumma Mar 16 '15
Python 3.
1
u/6086555 Mar 16 '15
I tried Haskell but I'm not good enough yet so Python 2 it will be.
1
u/eslag90 Mar 16 '15 edited Mar 16 '15
Python 2.7. I can never wrap my head around recursion, so can't say it's the best way to do it.
1
u/franza73 Mar 16 '15
Perl solution:
1
u/streakycobra Mar 16 '15 edited Mar 16 '15
OCaml
It shows:
OCaml offers also strong static typing with type inference.
The usage of pattern matching works nicely here: the compiler warns me about the not exhaustive pattern matching, and even give me an example of a missed case (It appears without the «_ -> failwith "Malformed input"» line):
edit: improved formulation
1
u/og_king_jah Mar 16 '15
Here's a solution in F#.
1
u/Regimardyl Mar 16 '15 edited Mar 16 '15
My Haskell solution. Wanted to do proper errors, so it quickly became pretty messy.
1
u/lewisj489 0 1 Mar 16 '15
C#
https://gist.github.com/lewisj489/18fd1d978845d626e807
1
u/eLoox Mar 16 '15
Java. First timer. Be gentle. Hopefully I'm not late to the party.
1
u/TASagent Mar 16 '15 edited Mar 16 '15
An uninspired C++
A bit verbose, but I'm bracing for whatever Part II might be.
Feedback welcome - I never really have to use the standard lib for parsing/handling input, so there could be less stupid ways of doing what I did.
First Trial:
Second Trial:
Third Trial:
1
u/wizao 1 0 Mar 16 '15 edited Mar 22 '15
Haskell using function composition:
1
u/[deleted] Mar 16 '15
Well, I'm still very much not a fan of writing programs that require the user to enter input multiple times. It seems to me that, for the most part, real world applications don't require this. So... I dunno. I just didn't.
I used a command line argument parsing library called "clap" to get command line args. It has a major shortcoming I had to work around, but I got something that kind of does the job anyway.
Code here.
I had originally written a trait called
ApplyInstructionsand implemented that trait onVec<Instruction>to actually increment the value, but I decided that I was actually just repeating code already written infold(), so I went with that instead. I think that's a much better option anyway. The final version hasapply()as a method onInstruction.All the useful work in my solution is done in the following code block:
Everything else is just there to make that work. o.O
1
u/Scroph 0 0 Mar 16 '15 edited Mar 16 '15
Good ol' C (C language for the CTRL+F-ers). As an aspiring embedded software engineer, I need to start thinking of C as a high level language.
I actually cheated here by using atoi(), it automatically parses a "-9" string into a -9 integer.
1
u/chunes 1 2 Mar 16 '15 edited Mar 16 '15
Java:
In case you're wondering what the ternary operation is about, it's code to print the term like an integer if it's equivalent to one, or else print it like a floating point number. So 10.0 simply prints as 10 but 10.321 prints as 10.321.
1
u/bullzei Mar 16 '15
Java solution: This may look like a overkill but, just for the sake of variability in solutions, I implemented this with Chain-Of-Responsibility design pattern. Comments appreciated.
1
u/Lyrrad0 Mar 16 '15
Java. Pretty straightforward implementation.
1
u/RedditAg Mar 16 '15
Java no recursion
1
u/jnazario 2 0 Mar 16 '15 edited Mar 17 '15
scala. i should really get more comfortable with fold and friends. updated to use foldLeft once ... now to replace that for loop with something functional
1
u/ct075 Mar 17 '15
https://gist.github.com/CT075/350681fed076bc83230c
My "golfed" solution, I'm sure it could be trimmed down a lot more but I'm not actually good at this.
Sample runs: http://puu.sh/gDEoA/c41a4df457.png
1
u/theaffable Mar 17 '15
Python, with a little bit of OOP.
If you have any feedback I will greatly appreciate it, feel free to comment.
1
u/Isitar Mar 17 '15
C# as always comment like you want.
I know the goto is ugly and shitty and stupid but it's the only way how to fallthrough in a case... C# removed this feature if you have code in your case statement...
What my code differs from others is that I first parse the whole action and the function later doesn't parse my input anymore. so any error checkin can be done in an early stage (wich i didnt :P)
1
u/KevinTheGray Mar 17 '15
Here's mine in Swift:
import Foundation
1
u/[deleted] Mar 17 '15 edited Mar 17 '15
All right, here's my C# solution. It's way shorter than the Rust edition. It's also bound to explode any time you use invalid input and offers nothing in the way of help or guidance as to how to use it, but... Well, the way I figure it, that's the point of free software: you can read the source code if you need documentation! :)
You may notice that the core of the program is still identical: I define a set of operations to be carried out to generate the terms and fold over them (in linq, that's called
.Aggregate()) in a for loop to get the output for each term. The one big difference is that here I'm defining lambda expressions to do that work where before I was simply doing that work in a match expression. C# is much friendlier to functions like that at the moment.1
u/T-Fowl Mar 17 '15 edited Mar 17 '15
Scala, which I am still fairly new with.
1
u/[deleted] Mar 17 '15
Did a single java class using another class as a tester. If interested, I can post the test class as well. Any feedback is fine.
1
u/Pink401k Mar 18 '15
This is my first submission to /r/dailyprogrammer :) It's also my first attempt at using Rust for something harder than FizzBuzz.
My program will mostly work. There's some discrepancies between what the problem was looking for, and what I was able to come up with. First, the input numbers have to be single-digit, positive numbers. so 0..9; This is due to how I'm parsing the operator and number out in get_operators. I think I know how to improve this, potentially.
Also, error handling isn't all the way there. A lot of it will fail gracefully, but some of it won't. I need to learn how to name functions and stuff better... Also, my handling of inputs, parsing inputs, and types is pretty poor.
But! All in all I'm pretty happy with how this came out. Rust is a lot of fun, and I think I'm going to keep playing with this for a while.
feedback is definitely appreciated
1
u/Scara95 Mar 18 '15 edited Mar 18 '15
Just some experiments with Nial:
Edit: Just realized you have to insert a space between - and the number. Well, it was just to get a bit more comfortable with the language.
1
u/scarytall Mar 18 '15
Here's a Perl version that builds the recurrence function using function references. I use function references to define the operations because it's more secure than eval() and allows for customization.
Edit: Code formatting fix.
1
u/erxyi Mar 18 '15
next C submission, recurrence using...recurrence! I'm proud that it works properly with *---2 or --1. Neither valgrind nor cppcheck aren't yelling, so I guess that isn't really bad, however - comments are really appreciated. https://gist.github.com/anonymous/e6b33a31a0b76b7a759a
1
u/[deleted] Mar 19 '15
Late to the game, but... [Java]: This seems to be longer than some of the other java solutions. It outputs doubles instead of ints, but I figured that's fine. I'm a beginner, so any feedback is more than welcome. Cheers!
}
1
u/Steve132 0 1 Mar 19 '15
1
u/_Bia Mar 19 '15
1
u/mafnn Mar 19 '15
Here's my solution in C++. I'm new to it and come from a C background so it's probably full of awful things. Any feedback is very much appreciated!
1
u/[deleted] Mar 20 '15
Here's my Python3 solution. Pretty simple challenge IMO, except for the thing about calling the functions.
1
u/shadystone Mar 20 '15 edited Mar 20 '15
My first attempt at clojure (or anything remotely lispy). This probably doesn't follow convention that well, and there are some unnecessary string/split calls, but it gets the job done.
1
u/[deleted] Mar 20 '15
Written in Python 2.7
1
u/Roondak Mar 21 '15
Just recently found out about dailyprogramer, this is my first post on the sub. Here's my Java code, I made it output doubles since it said they could be any real number, not just ints. Unfortunately my output then doesn't really look like the one in the OP.
1
u/ralusek Mar 21 '15
Javascript (obviously needs trusted input to use eval):
1
u/fbWright Mar 21 '15
Python 3
It doesn't handle malformed input well, but it works with the provided sample inputs. It compiles the RPN to a lambda and uses it.
1
u/[deleted] Mar 22 '15
Powershell! Been on a "everything Microsoft" kick recently. Might try a VBA solution.
1
u/pabs Mar 22 '15
Ruby:
Output (Series 3):
1
u/mcdonalds_king Mar 26 '15 edited Apr 03 '15
Sorry y'all late to the party. Here is my solution in python 2.7:
1
u/[deleted] Mar 27 '15 edited Mar 28 '15
A solution in Rust.
1
u/[deleted] Apr 14 '15
Python
1
u/JMey94 0 0 Apr 16 '15
C#
1
u/[deleted] Mar 16 '15
C, though not nearly as amazing as /u/skeeto's.
0
u/[deleted] Mar 16 '15
[deleted] — view deleted comment
1
u/[deleted] Mar 16 '15 edited Mar 16 '15
[removed] — view removed comment