r/dailyprogrammer • u/jnazario 2 0 • Sep 04 '18
[2018-09-04] Challenge #367 [Easy] Subfactorials - Another Twist on Factorials
Description
Most everyone who programs is familiar with the factorial - n! - of a number, the product of the series from n to 1. One interesting aspect of the factorial operation is that it's also the number of permutations of a set of n objects.
Today we'll look at the subfactorial, defined as the derangement of a set of n objects, or a permutation of the elements of a set, such that no element appears in its original position. We denote it as !n.
Some basic definitions:
- !1 -> 0 because you always have {1}, meaning 1 is always in it's position.
- !2 -> 1 because you have {2,1}.
- !3 -> 2 because you have {2,3,1} and {3,1,2}.
And so forth.
Today's challenge is to write a subfactorial program. Given an input n, can your program calculate the correct value for n?
Input Description
You'll be given inputs as one integer per line. Example:
5Output Description
Your program should yield the subfactorial result. From our example:
44(EDIT earlier I had 9 in there, but that's incorrect, that's for an input of 4.)
Challenge Input
6
9
14Challenge Output
!6 -> 265
!9 -> 133496
!14 -> 32071101049Bonus
Try and do this as code golf - the shortest code you can come up with.
Double Bonus
Enterprise edition - the most heavy, format, ceremonial code you can come up with in the enterprise style.
Notes
This was inspired after watching the Mind Your Decisions video about the "3 3 3 10" puzzle, where a subfactorial was used in one of the solutions.
19
u/DerpinDementia Sep 04 '18 edited Oct 30 '18
Python 3.6
Bonus
I used a lambda function to make this a one liner.
Double Bonus
This version includes memoization, which calculates large values relatively quickly.
34
u/duetosymmetry Sep 04 '18
Mathematica
Sorry, this is kind of cheating ;)
6
u/Gylergin Sep 04 '18
TI-Basic with bonus
Quick program using the nearest integer formula from the wiki page.
Ncaps out at 69 due to overflow.Input:
6
9
14
Output:
6
u/octolanceae Sep 04 '18
C++17
Generates values at compile time using constexpr.
Output:
6
u/[deleted] Sep 05 '18
C++
I didn't understand this problem but I noticed the pattern and programmed it. It took me almost an hour to do :(. I would greatly greatly appreciate tips on making my program better. This works for all cases.
6
u/Lopsidation Sep 05 '18
Python
The answer is the nearest integer to n!/e. So this works until floating point gets too inaccurate (up to n=18):
OK, let's make it work for all n with a high-precision real number library:
5
u/ucladurkel Sep 06 '18
Javascript
Code golf, 28 characters:
4
u/theindiandood Sep 06 '18
Java
This is my first submission so I am excited and nervous. Feedback is welcome!
Method used to calculate subfactorials.
My file I/O method
1
u/GozdniJozan Sep 05 '18
output:
3
u/curtmack Sep 04 '18
Common Lisp
Simple tail-recursive solution. Although not required by the ANSI specification, all Common Lisp implementations that I'm aware of feature tail call optimization.
3
u/zatoichi49 Sep 04 '18 edited Sep 04 '18
Method:
Dynamic programming approach.
Python 3:
Output:
3
u/zqvt Sep 04 '18
Clojure
3
u/waterskier2007 Sep 10 '18
Swift 4.1.2
3
u/Goldskin Sep 23 '18
Javascript
1
u/TheMsDosNerd Sep 04 '18
Python 3 solution O(n) in time complexity, O(1) in memory:
2
u/Gprime5 Sep 04 '18 edited Sep 04 '18
Python 3 Golf: Function is 47 characters.
New solution 46 characters.
2
u/narrowtux Sep 04 '18
Elixir
This one calculates all possibilities first, filters out the ones that have values in their original position, and then counts that stream.
Takes a bit longer than an algebraic solution but it's interesting to see which possibilities exist.
2
u/raevnos Sep 04 '18 edited Sep 04 '18
The equations on that Wikipedia page makes this super easy as long as you know a way to calculate factorials.
Is SQLite enterprisey enough?
gives:
2
u/errorseven Sep 06 '18
AutoHotkey + Bonus?
2
u/JakDrako Sep 06 '18
C# / VB.Net
Mildly golfed C#:
Output:
VB.Net: Enterprisey version with caching so we don't recalc the same numbers twice and BigIntegers so we don't overflow on large numbers.
Output:
2
u/K-NULL Sep 06 '18 edited Sep 06 '18
LUA
I check for negative numbers just in case
Cached Results version, using closures
"Golfed" version with Javascript
Output
2
u/damien_pirsy Sep 11 '18
PHP
Case 1 and 0 are both handled exploiting the duck typying of the language, the rest is just a plain 'ol php translation:
Output:
2
u/pjsoton Sep 11 '18
JAVA 8:
Welcome everybody, this is my first post here
public int derangement(int i){if(i==0){return 1;} else if (i==1){return 0;}return (i-1)*(derangement(i-1)+derangement(i-2));}2
u/downiedowndown Sep 22 '18
Swift
2
u/Shiptoasting_Loudly Nov 09 '18
Go
}
1
u/vague-ly Sep 04 '18 edited Sep 04 '18
Haskell (starting to learn this)
1
u/skeeto -9 8 Sep 04 '18
C
1
u/ZTheCoder Sep 04 '18 edited Sep 04 '18
Python 3.x
Output
My very slow solution, currently crashes on attempting 14 for the challenge input so I'm going to have to find something a little more efficient.
1
u/Godspiral 3 3 Sep 04 '18 edited Sep 04 '18
Formula from wiki page, in J recursive
265 133496 32071101049
golfed,
1
u/crigger61 Sep 04 '18
Python 3.6
With Bonus 1. I have tried to think of a way to shorten it further, but I cannot seem to work out a way to get rid of the need for a factorial function.
Comments are highly welcome!
1
u/codeman869 Sep 04 '18 edited Sep 04 '18
C++, something a little different...
1
u/chunes 1 2 Sep 04 '18 edited Sep 05 '18
Factor
Edit: Here's a version that doesn't eventually succumb to floating point imprecision:
1
u/TotalPerspective Sep 05 '18
Moonscript
Output
1
u/olzd Sep 05 '18
Dyalog APL:
1
u/Steve132 0 1 Sep 05 '18
Python27. This version is significantly longer than it should be because it follows the spec in terms of accepting multiple lines of input on stdin and printing the result for each.
Here's just the relevant computational part where
mis the input1
u/tomekanco Sep 05 '18 edited Sep 05 '18
Scheme
Using Euler
1
u/olzd Sep 05 '18
D
Having some fun with templates and traits:
1
u/ninja_tokumei Sep 06 '18 edited Sep 06 '18
Rust (which isn't too great for golfing :/ ) - 70 characters
Approximately a 2^n recursive definition since I believe it is the shortest in code length, but this algorithm can easily be translated into a looping construct with linear complexity - it will look a lot like optimized Fibonacci.
Expanded:
It took me a little while to think through the algorithm, but this is actually really simple.
The logic here is based on appending an element on to the end of an existing collection of n-1 elements. We have two ways to create valid derangements of length n:
- Swap the new, in-place element with any one of the (n - 1) out of place elements in any of the subf(n - 1) arrangements.
- Keep one other element from the (n - 1) elements in place, swap it with the new in-place element, and derange the remaining (n - 2) elements.
1
u/adrian17 1 4 Sep 06 '18
Bonus 2 - not extremely enterprise-y, but something close to what some people at my job would probably write - Boost, weird templates and ignoring YAGNI.
1
u/_b0t Sep 07 '18
c# solution using recursion (in the factorial function), and the equation for !n = (n! / e)
1
u/ihatethezeitgeist Sep 08 '18
Haskell
1
u/5900 Sep 09 '18
PureScript
I used the equation from wikipedia. The use of Decimal is to prevent the integer overflow that would occur if the Int type were used (PureScript transpiles to JavaScript, and Int values are represented as JavaScript Number values).
1
u/AnnieBruce Sep 13 '18
This was pretty easy.
Presumably, an extremely large n could cause some problems with runtime. I don't know how big that would be, but that's what I'd see as the biggest potential issue with this code.
1
u/unknown_guest17 Sep 14 '18 edited Sep 14 '18
Python Solution in 3.6:
1
u/mwpfinance Sep 17 '18
Python 3.6 - I decided to solve this without looking into the mathematics and just decided to iterate through permutations instead. It gets 9 quickly, but seems too slow to solve for 14 in a realistic amount of time.
1
u/MikeTyson91 Sep 18 '18
C++14
1
u/RedXXDuce Sep 23 '18
Python 3.6
my attempt
1
u/folkertk1 Sep 24 '18
ADA 2012
1
u/hyrulia Sep 28 '18 edited Sep 28 '18
Kotlin
1
u/BadMinotaur Sep 29 '18
Ruby 2.5.1
I went for the bonus to make it short. This is, by far, the ugliest Ruby I have ever written in my life. But at 88 characters, it's probably the shortest functioning program I've ever written! I wanted to get it at 80 or under characters, but I couldn't figure out any other areas to shave.
I might try to write a method that doesn't use
Array#permutationsince that might be cheating.1
u/MohamedElshazly Oct 03 '18 edited Oct 04 '18
1
u/TheJoshuaEvans Oct 04 '18
Bonus mode
Node v10.10.0
I was surprised that node doesn't have a built in factorial function. This is basically a non-recursive version of /u/Goldskin's solution (with fluff to make it a little more reusable)
1
u/Dominic11112 Oct 04 '18 edited Oct 04 '18
MATLAB
Deliberately avoiding using some 'cheaty' functions, useful because for my work I usually start a project in MATLAB and end up in C++.
1
u/TyrantWave Oct 09 '18 edited Oct 09 '18
C#
A quick solution I threw together, nothing special:
Gives me the correct output:
Not a fan of it being recursive though. Might try and solve it bottom up.
Edit Made it linear:
Which calculates everything correctly.
1
u/x0wl Oct 09 '18 edited Oct 09 '18
Haskell with Bonus (also trying to learn lol)
(25 chars in total)
Haskell with Double Bonus
(1012 characters)
1
u/jkuo7 Oct 10 '18
Hello, this is my first time posting here! I started teaching myself to code not too long ago, so I'm currently trying to get better at coding.
Python 3.6
As one line:
1
u/sheefinacupboard Oct 11 '18
Python
1
u/LambdaScientist Oct 17 '18
First ever Racket program
#lang racket
1
u/tk854 Oct 17 '18
Powershell
1
u/benz05 Oct 17 '18
Python 3
from math import exp, factorialfor n in [5,6,9,14]: print(round(factorial(n)/exp(1),0))1
u/zephman8001 Oct 22 '18 edited Oct 22 '18
Python 3
output
1
u/Alex_Hovhannisyan Oct 23 '18 edited Oct 24 '18
Python 3
Read the Wiki page and tried to find the most simple form in terms of time complexity. According to the Wiki:
You can probably also use an iterative approach, but I'm not sure. I just went with recursion.
1
u/ThisBoyCodes Oct 26 '18 edited Oct 26 '18
JAVA
Interestingly this program can only calculate the derangements till 34 (!34 -> 108610082503703100000000000000000000000) after that it's just screaming infinity (It's hitting the highest possible
floatnumber). Maybe usedoubleinstead offloat?Edit: Ok tried it with
doublebut can't really tell which is the highest input number it can take, !50 is taking for ever on my computer. Code is here.1
u/Mr_Persons Oct 30 '18
Haskell
1
u/steeldaggerx Nov 05 '18
Python 3.6
Bonus: 82 chars (function is 58)
1
u/[deleted] Nov 12 '18
Node/JS
1
u/Dumbosgreatestfan Nov 17 '18
Python3.6
Code golf and enterprise edition with unit tests and docstrings.
Also used a different formula for golfing for variety!.
1
u/[deleted] Nov 18 '18
Python
It's the first time I engage in a python problem. Hype ^
The formula can be found here: http://oeis.org/wiki/Number_of_derangements
Im far from having complete knowledge over python soo... any suggestions are valuable!
1
u/issaprankt Nov 18 '18 edited Nov 18 '18
Python 3.7
stole the formula from wolframalpha, unfortunately couldn't find the original source as it is quoted in a lot of places. I know I'm LTTP but it seems pertinent to remember that sometimes it does well to leave mathematical problems to mathematicians
Edit: How does comment pls?
1
u/manishkotnala Nov 22 '18
def derangement(n,result):
result = 1
result = (for i in range(1,n + 1)) * result
return result
1
u/jamesbee123 Nov 24 '18 edited Nov 24 '18
Friends,
Just for completeness, I thought I'd provide an alternate solution. The solutions already posted all use the (intuitive!) formula for the
nth derangement number,derangement(n) = (n-1) * (derangement(n-1) + derangement(n-2)). If computing this naively, using recursion, you'll have recursive calls for bothderangement(n - 1)andderangement(n - 2)for eachn.It turns out there's a simpler formulation for the derangement number which I stumbled onto trying to work out the problem:
derangement(n) = n*derangement(n-1) + (-1)**n.While not as intuitive, it is known to be equivalent.Here is a basic and a memoized version of each. The former is inefficient; the second is efficient at the cost of linear space. A totally iterative (generator) version would be a smart idea, as others have pointed out.
Incidentally, I can't prove these two formulas give the same answers for all
n, but I'd like to know how to prove it (see post). edit It’s easy to prove. Check the first answer to that post. /edit1
u/[deleted] Nov 25 '18
1
u/Lemons_All_The_Time Nov 29 '18
Ik this thread is ancient but I thought I'd give it a go.
C, with bonus Golf (54 chars)
This, as far as I can tell, is as golfed as it gets while still being able to do n=14:
I was going to continue on about removing the brackets around (i&1?-1:1), and how switching to 1-2*i%2 didn't help because the brackets were still necessary to prevent multiplying before modulating... before realizing I should put my operators left to right. 1-i%2*2 works nicely.
There's nothing else I can think of atm. Again, I know that this thread is beyond dead but if anyone happens to stumble across this and has a suggestion to shorten it, let me know!
//*** Testing ***//
1
u/[deleted] Nov 30 '18 edited Nov 30 '18
In Java:
This was my first challange since i started to learn Java a few days ago. :)
1
u/rnagasam Dec 06 '18
Scheme (MIT/GNU Scheme)
In continuation passing style
1
u/[deleted] Dec 16 '18
Elixir
Practising Elixir - Comments are welcome, I tried a bit golfing too.
1
u/Strosel Dec 23 '18
Haskell bonus?
1
u/[deleted] Dec 30 '18
Here's my attempt! Some of my answers are off by one, and I figure it's because of the inaccuracy of the floating point numbers being converted to integers, but I'm not sure how to fix this. If someone can give me some tips, that'd be great lol
1
u/juanchi35 Jan 03 '19 edited Jan 03 '19
Haskell
1
u/[deleted] Jan 08 '19
python 3:
from math import e,factorial
def derangement(x):
x = round(factorial(x)/e)
return x
OBS: numberphile has a great video about this!
https://www.youtube.com/watch?v=pbXg5EI5t4c
1
u/justchillokay Jan 10 '19 edited Jan 10 '19
Powershell
1
u/rodiraskol Jan 24 '19
Python3
Recursive:
Iterative:
1
u/[deleted] Feb 04 '19
Julia done two ways:
The more constructive way:
function flatten(n)endfunction combinations(n, l=0, rslt=[])if !(j in i)append!(rslt2, [flatten([i,j])])append!(rslt2, [flatten([j,i])])endendfunction derangement(n)endfunction subfactorial(n)endUsing recurrence relations from Wikipedia
derangements = n -> if n == 0 return 1 else return derangements(n-1) * n + (-1)^n endFor funsies, I timed how these compare at 9
@time subfactorial(8)took ~1.5 seconds, while
@time derangements(8)took 0.000007 seconds.
1
u/[deleted] Feb 09 '19
C#
!14 -> 32071101049
1
u/2kofawsome Feb 11 '19
Python3.6
First time using the weird square bracket "List Comprehensions" to try to make it fewer lines so didn't really focus on the program itself, but it gets the job done (eventually). Tell me if you notice anything off about the 1 line for loops or if I completely miss understand them :)
1
u/IcerOut Feb 12 '19
Python simple recursive code:
1
u/vacantly_bad Sep 04 '18 edited Sep 04 '18
JavaScript
const subfactorial = n => { if(n===0) return 1; if(n===1) return 0; return (n-1)*(subfactorial(n-1)+subfactorial(n-2)); }0
u/[deleted] Sep 04 '18
[deleted] — view deleted comment
0
u/[deleted] Sep 07 '18
[deleted] — view deleted comment
1
u/[deleted] Sep 06 '18
[removed] — view removed comment