Tag Info

2

05AB1E, 8 bytes Ò3.ŒP€{ê Ò # prime factors of the input 3.Œ # all 3-element partitions P # take the product of each inner list €{ # sort each inner list ê # sort and uniquify the outer list Try it online!

1

Icon, 87 bytes procedure f(n) k:=[] a:=1to n&b:=1to a&c:=1to b&a*b*c=n&k|||:=[[a,b,c]]&\z return k end Try it online! Close to Python :)

0

Pyth, 12 bytes f*F.e-bkT.PU Try it online! UQ # [implicit Q=input] range(0,Q) .P Q# [implicit Q=input] all permutations of length Q f # filter that on lambda T: .e T # enumerated map over T: lambda b (=element), k (=index): -bk # b-k *F # multiply all together The filter works like this:...

2

Pyth, 11 bytes fqQ*FT.CSQ3 Try it online! SQ # range(1, Q+1) # Q = input .C 3 # combinations( , 3) f # filter(lambda T: vvv, ^^^) qQ # Q == *FT # fold(__operator_mul, T) ( = product of all elements)

4

Python 3.8 (pre-release),  83  80 bytes lambda n:[[i,j,k]for i in(r:=range(n+1))for j in r[i:]for k in r[j:]if i*j*k==n] Try it online! ...beating a two-loop version by three bytes: lambda n:[[i,j,n//i//j]for i in(r:=range(1,n+1))for j in r if(i<=j<=n/i/j)>n%(i*j)]

4

Jelly, 7 bytes œċ3P⁼¥Ƈ A monadic Link accepting a positive integer which yields a list of 3-lists of positive integers. Try it online! How? œċ3P⁼¥Ƈ - Link: positive integer, N 3 - literal three œċ - all combinations (of [1..N]) of length (3) with replacement i.e. [[1,1,1],[1,1,2],...,[1,1,N],[1,2,2],[1,2,3],...,[1,2,N],...,[N,N,N]] ...

5

Haskell, 52 bytes f n=[[a,b,c]|a<-[1..n],b<-[1..a],c<-[1..b],a*b*c==n] Try it online! Tuples are in descending order. "3" seems to be a small-enough number that writing out the 3 loops was shorter than anything general I could come up with.

2

C (clang), 89 bytes a,b,x;f(n){for(a=n;a;a--)for(b=a;b&&(x=n/a/b)<=b;b--)x*b*a-n||printf("%d,%d,%d ",x,b,a);} Try it online! Port of @Arnauld 👍 Saved 1 thanks to @Jonathan Frech better output format

4

Jelly, 11 bytes ÆDṗ3Ṣ€QP=¥Ƈ Try it online! A monadic link taking an integer as its argument and returning a list of lists of integers. Explanation ÆD | Divisors ṗ3 | Cartesian power of 3 Ṣ€ | Sort each list Q | Unique ¥Ƈ | Keep only where the following is true (as a dyad, using the original argument as ...

2

Retina, 59 bytes .+ * 2+%L$(?<=(_+))(?=(\1)*$) $ _$#2* A_(_+) \1\b _+ $.& Try it online! Link includes test suite. Explanation: .+ * Convert to unary. 2+%L$(?<=(_+))(?=(\1)*$)$ _$#2* Repeating twice, divide the last number on each line into all of its possible pairs of factors. The lookbehind is greedy and atomic, so once it's matched ... 5 JavaScript (V8), 61 60 bytes Prints the cuboids to STDOUT. n=>{for(z=n;y=z;z--)for(;(x=n/y/z)<=y;y--)x%1||print(x,y,z)} Try it online! Commented n => { // n = input for( // outer loop: z = n; // start with z = n y = z; // set y to z; stop if we've reached 0 z-- ... 2 Haskell, 67 60 59 bytes For a given $n$, this produces all 3-tuples of with entries in $\{1,2,\ldots,n\}$ and filters out the valid ones. To guarantee uniqueness we require that the tuples are sorted. f n=[x|x@[a,b,c]<-mapM id$[1..n]<$":-)",a*b*c==n,a<=b,b<=c] Try it online! 0 C (gcc), 187 180 bytes Saved seven bytes thanks to ceilingcat. *D,E;r(a,n,g,e){e=g=0;if(!a--){for(;e|=D[g]==g,g<E;g++)for(n=g;n--;)e|=D[n]==D[g];for(g*=e;g<E;)printf("%d ",D[g++]);e||puts("");}for(;g<E;r(a))D[a]=g++;}y(_){int M[E=_];D=M;r(_);} Try it online! 0 Wolfram Language (Mathematica), 14 bytes #@*#&@Ordering Try it online! Based on xnor's insight. 12 Python 2, 60 bytes def f(l):z=zip(l,range(len(l)));print map(sorted(z).index,z) Try it online! Uses zero-indexing. A fast algorithm with a simple idea. If we instead need to permute the input list to make it as close to $(1,2,...,n)$ as possible, we should just sort it, as proven below. Since we're instead permuting $(1,2,...,n)$, we choose the ... 0 J, 25 8 bytes #\/:@/:] Try it online! Much shorter answer based xnor's brilliant idea. original answer J, 25 bytes (0{]/:1#.|@-"1)i.@!@#A.#\ Try it online! 2 Ruby, 63 60 bytes ->v{[*1..v.size].permutation.max_by{|p|eval [p,0]*'*%p+'%v}} Try it online! There's a math trick here that could be helpful in other answers too--instead of minimizing the sum of the absolute values of the differences, we maximize the sum of the products. Why does that work? Minimizing the sum of (x-y) squared isn't equivalent to ... 2 Jelly, 5 bytes Œ¿œ?J A monadic Link accepting a list of numbers which yields a list of integers. Try it online! Or see the test-suite. How? Œ¿œ?J - Link: list of numbers, X Œ¿ - Index of X in a lexicographically sorted list of all permutations of X's items J - range of length of X œ? - Permutation at the index given on the left of the ... 1 Gaia, 13 bytes e:l┅f⟪D†Σ⟫∫ₔ( Try it online! e: | eval and dup input l┅f | push permutations of [1..length(input)] ⟪ ⟫∫ₔ | iterate over the permutations, sorting with minimum first D†Σ | the sum of the absolute difference of the paired elements ( | and select the first (minimum) 0 Wolfram Language (Mathematica), 57 bytes f@n_:=MinimalBy[Permutations@Range@Length@n,Tr@Abs[n-#]&] Try it online! 2 Jelly, 8 bytes LŒ!ạS¥ÐṂ Try it online! 1 Python 2, 149 126 112 bytes -23 bytes thanks to Mr. Xcoder -14 bytes thanks to xnor from itertools import* f=lambda a:min(permutations(range(len(a))),key=lambda x:sum(abs(a-b)for a,b in zip(x,a))) Try it online! Uses permutations of (0 ... n-1). 1 JavaScript (ES6), 61 bytes Based on xnor's insight. a=>[...a].map(g=n=>g[n]=a.sort((a,b)=>a-b).indexOf(n,g[n])+1) Try it online! Commented a => // a[] = input array [...a] // create a copy of a[] (unsorted) .map(g = n => // let g be in a object; for each value n in the copy of a[]: g[n] = ... 0 w/o any permutation package Python 3, 238 bytes def p(a,r,l): if r==[]:l+=[a];return for i in range(len(r)): p(a+[r[i]],r[:i]+r[i+1:],l) def m(l): s=(float("inf"),0);q=[];p([],list(range(len(l))),q) for t in q:D=sum(abs(e-f)for e,f in zip(l,t));s=(D,t)if D<s[0]else s return s[1] Try it online! 3 Perl 6, 44 bytes {permutations(+$_).min((*[]Z-$_)>>.abs.sum)} Try it online! Anonymous codeblock that returns the first minimum permutation with 0 indexing. Explanation: { } # Anonymous code block permutations(+$_) # From the permutations with the same length ...

0

Japt -g, 12 bytes Êõ á ñÈíaU x Try it For 0-indexed, replace the first 2 bytes with m, to map the array to its indices instead. Êõ á ñÈíaU x :Implicit input of array U Ê :Length õ :Range [0,Ê] á :Permutations ñÈ :Sort by í U : Interleave with U a : Reduce each ...

5

05AB1E, 7 bytes āœΣαO}н Try it online! Explanation ā # get the numbers 1 to len(input) + 1 œ # Permutations of this Σ } # Sort by ... α # Absolute difference O # Sum these н # And get the first one # implicitly print

1

Julia 1.2, 88 (82) bytes f(t)=get(t,(),[f.([t[1:i-1];t[i+1](t[i],t[i+2]);t[i+3:end]] for i=1:2:length(t)-2)...;]) julia> f([2, +, 3, *, 4]) 2-element Array{Int64,1}: 20 14 julia> f([18, /, 3, *, 2, -, 1]) 6-element Array{Float64,1}: 11.0 6.0 2.0 3.6 6.0 6.0 Takes a tape in the form of a vector of numbers and infix functions, evaluates ...

0

Perl 5 (-alp), 89 bytes my$x;map{$x.=$.(eval$&.$1).$2.$"while/\d+[-+*\/](?=(\d+)(.*))/g}@F;$_=$x;/[-+*\/]/&&redo TIO or unique values, 99 bytes my%H;map{$H{$.(eval$&.$1).$2}++while/\d+[-+*\/](?=(\d+)(.*))/g}@F;$_=join$",keys%H;/[-+*\/]/&&redo

2

Python 3, 108 bytes f=lambda e,s={*"+-*/"}:[str(eval(p.join(g)))for p in s for g in zip(*map(f,e.split(p),[s-{p}]*len(e)))]or[e] Try it online! The function takes a single string as input and returns a list of possible results. Ungolfed def get_all_eval_results(expr, operators={*"+-*/"}): results = [] for operator in operators: ...

1

Python 2, 182 172 bytes import re def f(s,P=set('+-/*')): S=[eval(s)] for p in P: t=s while p+' 'in t:t=re.sub(r'[-\d.]+ \%s [-\d.]+'%p,lambda m:eval(m.group()),t,1) S+=f(t,P-{p}) return S Try it online! Takes input with ints formatted as floats, as per "Integers can be replaced by floats for languages that implicitly parse type".

1

Jelly, 30 bytes œṡ⁹¹jṪḢƭ€jŒVɗßʋFL’$? Ḋm2QŒ!çƒ€ Try it online! A pair of links. The second one is the main link, and takes as its argument a Jelly list of floats/integers interspersed with the operators as characters. This is a flattened version of the way Jelly takes its input when run as a full program with command line arguments. The return value of the ... 4 JavaScript (V8), 118 112 bytes Prints the results. f=(s,x='',y=x,o='+-*/')=>[...o].map(v=>f(s.split(v).join(x+v+y),x+')',y+'(',o.replace(v,'')))|print(eval(y+s+x)) Try it online! Or see the deduplicated results. 2 Perl 6, 92 90 88 bytes {map {[o](@_)($_)},<* / + ->>>.&{$^a;&{S:g{[\-?<[\d.]>+]+%"$a "}=$/.EVAL}}.permutations} Try it online! Takes a string with a space after any operators and returns a set of numbers. This mostly works by substituting all instances of n op n with the eval'ed result for all permutations of the operators. ... 3 JavaScript (Node.js), 132 bytes a=>(w=[],F=(b,a)=>b?[...b].map(q=>F(b.replace(q,""),a.replace(eval(/[\\d.-]+( \${q} [\\d.-]+)+/g`),eval))):w.push(a))("+-*/",a)&&w Try it online! This allows duplicated outputs. JavaScript (Node.js), 165 161 155 153 152 137 bytes a=>Object.keys((F=(b,a)=>b?[...b].map(q=>F(b.replace(q,""),a.... 3 C# (Visual C# Interactive Compiler), 285 bytes x=>{int c=0,j,t=1,i;for(;c++<25;t=c){var r="*+-/".ToList();for(i=j=1;j++<4;t=t/j+1)(r[j-1],r[t%j])=(r[t%j],r[j-1]);float k(float z,int p=4){char d;int l;float m;return i<x.Count&&(l=r.IndexOf(d=x[i][0]))<p?k((m=k(x[(i+=2)-1],l))*0+d<43?z*m:d<44?z+m:d<46?z-m:z/m,p):z;}Print(k(x[0])... 0 Pyth, 24 15 bytes eSm.U/*bZibZd./ Try it online! ./Q # List of partitions of the input m # map that over lambda d: .U d # reduce d (with starting value first element of the list) on lambda b,Z: /*bZgbZ # (b * Z) / GCD(b, Z) S # this gives the list of lcms of all partitions. Sort this e ... 4 Python, 87 bytes f=lambda n,d=1:max([f(m,min(range(d,d<<n,d),key=(n-m).__rmod__))for m in range(n)]+[d]) Try it online! A recursive function that tracks the remaining n to partition and the running LCM d. Note that this means we don't need to track the actual numbers in the partition or how many of them we've used. We try each possible next part, n-... 4 Haskell, 44 bytes (%1) n%t=maximumt:[(n-d)%lcm t d|d<-[1..n]] Try it online! 2 Haskell, 70 67 bytes f n=maximum[foldl1 lcm a|k<-[1..n],a<-mapM id[1..n]<[1..k],sum a==n] Try it online! Edit: -3 bytes thanks to @xnor. 3 Perl 6, 50 bytes {max .map:{+(.[_],{.[@^a]}..._,)}}o&permutations Try it online! Checks all permutations directly, like @histocrat's Ruby solution. Explanation &permutations # Permutations of [0;n) { }o # Feed into block .map:{ } # Map ... 10 Wolfram Language (Mathematica), 44 bytes Max[PermutationOrder/@Permutations@Range@#]& Try it online! Wolfram Language (Mathematica), 31 bytes @DanielSchepler has a better solution: Max[LCM@@@IntegerPartitions@#]& Try it online! 3 JavaScript (ES6), 92 bytes Computes the maximum value of$\operatorname{lcm}(a_1,\ldots,a_k)$where$a_1+\ldots+a_k$is a partition of$n\$. f=(n,i=1,l=m=0)=>n?i>n?m:f(n-i,i,l*i/(G=(a,b)=>b?G(b,a%b):a)(l,i)||i)&f(n,i+1,l)|m:m=l>m?l:m Try it online! JavaScript (ES6), 95 bytes f=(n,i=1,m)=>i>>n?m:f(n,i+1,i<m|(g=(n,k=2,p=0)=...

3

Jelly, 7 bytes Œṗæl/€Ṁ Try it online! A monadic link taking an integer as its argument and returning an integer. Explanation Œṗ | Integer partitions æl/€ | Reduce each using LCM Ṁ | Maximum

2

Ruby, 77 bytes f=->n{a=*0...n;a.permutation.map{|p|(1..).find{a.map!{|i|p[i]}==a.sort}}.max} Try it online! (1..) infinite range syntax is too new for TIO, so the link sets an arbitrary upper bound. This uses the direct definition--enumerate all possible permutations, then test each one by mutating a until it gets back to its original position (which ...

2

Gaia, 25 23 22 bytes ,:Π¤d¦&⊢⌉/ 1w&ḍΣ¦¦⇈⊢¦⌉ Try it online! Not having LCM or integer partitions makes this approach rather long. ,:Π¤d¦&⊢⌉/ ;* helper function: LCM of 2 inputs 1w&ḍΣ¦¦ ;* push integer partitions ¦ ;* for each ⇈⊢ ;* Reduce by helper function ⌉ ;* and take the max

1

Python 3 + numpy, 115 102 99 bytes -13 bytes thanks to @Daniel Shepler -3 more bytes from @Daniel Shepler import numpy c=lambda n:[n]+[numpy.lcm(i,j)for i in range(1,n)for j in c(n-i)] l=lambda n:max(c(n)) Try it online! Brute force method: find all possible sequences a,b,c,... where a+b+c+...=n, then pick the one with the highest lcm.

9

05AB1E, 6 bytes Åœ€.¿Z Try it online! Åœ # integer partitions of the input €.¿ # lcm of each Z # maximum

Top 50 recent answers are included