| Bytes | Lang | Time | Link |
|---|---|---|---|
| 012 | Uiua | 240818T003208Z | janMakos |
| 015 | Japt | 190701T161351Z | Shaggy |
| 030 | EXAPUNKS 594 bytes 2 EXAs | 190701T183650Z | ymbirtt |
| 1785 | Nibbles | 221108T163629Z | Dominic |
| 038 | Wolfram Language Mathematica | 190702T161624Z | att |
| 011 | Vyxal | 221109T222711Z | emanresu |
| 011 | Husk | 221108T152943Z | Dominic |
| 069 | Python 3 | 190705T010559Z | Dat |
| 099 | Retina 0.8.2 | 190701T230358Z | Neil |
| 063 | C# Visual C# Interactive Compiler | 190701T122530Z | Expired |
| 012 | Stax | 190702T022548Z | Khuldrae |
| 097 | PowerShell | 190701T134830Z | Veskah |
| 059 | Python 3.8 prerelease | 190702T153456Z | ovs |
| 271 | MS SQL Server 2017 | 190702T153002Z | Andrei O |
| 059 | Python 2 | 190702T135459Z | Jitse |
| 013 | MathGolf | 190702T150836Z | maxb |
| 012 | MATL | 190701T093815Z | Luis Men |
| 064 | APLNARS | 190702T080149Z | user5898 |
| 086 | PowerShell | 190702T082721Z | mazzy |
| 021 | APL Dyalog Unicode | 190701T081243Z | Adá |
| 064 | JavaScript | 190702T030506Z | tsh |
| 046 | Haskell | 190701T195104Z | cole |
| 053 | R | 190701T211513Z | MickyT |
| 043 | Ruby | 190701T204433Z | Value In |
| 012 | Gaia | 190701T172034Z | Giuseppe |
| 012 | Jelly | 190701T103602Z | Nick Ken |
| 027 | APL+WIN | 190701T153203Z | Graham |
| 075 | Clojure | 190701T115840Z | NikoNyrh |
| 012 | 05AB1E | 190701T114300Z | Emigna |
| 015 | Pyth | 190701T122026Z | Sok |
| 066 | JavaScript ES6 | 190701T092548Z | Arnauld |
| 063 | Red | 190701T110120Z | Galen Iv |
| 018 | J | 190701T103045Z | Galen Iv |
| 060 | Python 2 | 190701T081417Z | TFeld |
| 017 | Charcoal | 190701T084711Z | Neil |
Uiua, 12 bytes
▽≤⊸⊓/+\+⊃↙↘¯
Uses the arrays in ascending order for easy.
Explanation
⊃↙↘¯ # split the array into 2 chunks
⊸⊓/+\+ # sum the rich and prefix sum of poor
▽≤ # filter by if the prefix sum is not greater
EXAPUNKS 594 bytes (2 EXAs, 30 Instructions)
I've wanted to try a code golf challenge in EXAPUNKS for a while, and you looked like the best fit I could find, so, congrats!
Input via files 200 and 201, for L and n respectively. Output via a new file. L and the output are in ascending order.
Basically, XA sums the last n values in L, then sends it to XB. It then seeks to the beginning of L and sends each value one-by-one to XB. XB first receives the total from XA and stores it in register X. It then receives values one-by-one from XA, deducting the new value from X, and writing those values to the output file until X < 0.
XA
GRAB 201
SUBI T F T
DROP
GRAB 200
SEEK 9999
SEEK T
MARK FIRST_SUM
ADDI F X X
ADDI T 1 T
SEEK -1
VOID F
TJMP FIRST_SUM
COPY X M
SEEK -9999
MARK SECOND_SUM
COPY F M
TEST EOF
FJMP SECOND_SUM
KILL
XB
MAKE
COPY M X
MARK LOOP
COPY M T
COPY T F
SUBI X T X
TEST X > 0
TJMP LOOP
SEEK -1
VOID F
KILL
JavaScript for the level here
Nibbles, 20 17 nibbles (8.5 bytes)
Edit: -3 nibbles using scan-append `\$: as a more efficient way to generate prefixes
/|\`\>@$:++<_@-~+
Previous version:
. # map over
`, # range from zero up to
,$ # length of arg1 minus 1
>$ # drop that many elements from
@ # arg1
>_ # with arg2 elements already dropped
| # now filter only those lists whose
+ # sum
-~ # subtracted from one
+ # added to
+ # the sum of
<_ # the first arg2 elements
@ # of arg1
# is truthy = greater than zero
/ # fold over this list of lists from right
# returning the left arg each time
# (so, output the first filtered list)
Wolfram Language (Mathematica), 40 38 bytes
Drop@##//.a_/;Tr@a>Tr@Take@##:>Rest@a&
Drop@## exclude first n values
//.a_ :>Rest@a drop from suffix
//. /;Tr@a>Tr@Take@## until suffix sum <= head sum
Vyxal, 11 bytes
Ẏ∑£ȯÞK≬∑¥≤∵
Try it Online! Fixed thanks to one of the Sʨɠɠans.
∑ # Sum
Ẏ # Of first n
£ # Stored to register
ȯÞK # Suffixes of rest
∵ # Maxmimum by...
≬--- # Next 3 as lambda...
∑ # Sum
≤ # Is less than (or equal to)
¥ # Register?
Husk, 11 bytes
ḟ(≤Σ↑¹³Σ)ṫ↓
ḟ(≤Σ↑⁰²Σ)ṫ↓⁰² # program with implicit arguments added
↓ # drop arg1 elements from arg2
ṫ # and get all suffixes;
ḟ( ) # now return the first that satisfies:
Σ # it's sum
≤ # is less than or equal to
Σ # sum of
↑⁰ # first arg1 elements of
² # arg2
Python 3, 71 69 bytes
lambda L,n:[L[i]for i in range(len(L)-n)if sum(L[:i+1])<=sum(L[-n:])]
Retina 0.8.2, 99 bytes
\d+
$*
^
;,
+`;,(1+)(,.*)1$
$1;$2
,
;$'¶$`,
;.*(;.*)
$1$1
T`,`_`.*;
1G`(1+);\1;
.*;
(1*),
$.1,
,$
Try it online! Link only includes some test cases; I could get it to work in some cases with negative numbers at a cost of 12 bytes (in particular the first n entries in L still need to be positive; theoretically I could probably only require the sum of the first n entries to be positive). Explanation:
\d+
$*
Convert to unary.
^
;,
Insert a marker at the start of L.
+`;,(1+)(,.*)1$
$1;$2
Move it down the list n times, summing as we go. This deletes n but its comma remains.
,
;$'¶$`,
Create an entry for each suffix of L.
;.*(;.*)
$1$1
Replace the middle with a copy of the suffix.
T`,`_`.*;
Sum the copy of the suffix.
1G`(1+);\1;
Take the first entry where the suffix sum does not exceed the prefix sum.
.*;
Delete the sums.
(1*),
$.1,
Convert to decimal.
.,$
Delete the trailing comma that came before n.
C# (Visual C# Interactive Compiler), 88 81 69 68 63 bytes
-4 bytes thanks to LiefdeWen
a=>b=>a.Skip(b).Where((x,i)=>a.Skip(i+b).Sum()<a.Take(b).Sum())
Stax, 12 bytes
îo╧╫Σ↑>'qµΣº
Run and debug it at staxlang.xyz!
Unpacked (14 bytes) and explanation:
:/|]{|+n|+>!}j
:/ Split array at index.
|] Suffixes. The bit after the split (the poor) is on top for this.
{ }j First item in array that yields truthy under the block:
|+ Sum array (collective wealth of the many).
n Copy second item to top of stack.
|+ Sum again. Wasted computation, but this location saves a byte.
>! Second item on stack less than or equal to first?
By consensus, I can leave this result on the stack. Stax will attempt an implicit print, which might fail, but appending an m to the unpacked program lets you see the output nicely.
Looks like { ... }j is the same as { ... fh. Huh. Edit: That's not quite the case; the only the former will stop when it gets a truthy result, possibly avoiding side effects or a fatal error later on.
PowerShell, 99 97 bytes
param($n,$l)do{$a+=$l[$i++]}until($a-gt($l[-1..-$n]-join'+'|iex)-or$i-gt$l.count-$n)$l[($i-2)..0]
Takes list in ascending order, output is descending (because it was easier to compare to the test cases :^))
Goes through the list backwards forwards, comparing the accumulator to the last n entries added together (via gluing them together with +s and passing the resulting string to invoke-expression). The Until loop needed additional logic to handle going into the Rich Neighborhood because it wouldn't stop if we're still not richer than the Rich Guys until we churn through the entire list.
Unrolled:
param($n,$list)
do{
$acc+=$list[$i++]
}until($acc -gt ($list[-1..-$n] -join '+'|invoke-expression) -or ($i -eq $list.count-$n))
$list[($i-2)..0]
Python 3.8 (pre-release), 59 bytes
Output is in ascending Order
def f(l,n):
s=sum(l[:n])
while(w:=l.pop())<s:yield w;s-=w
MS SQL Server 2017, 271 bytes
create function f(@L nvarchar(max),@ int)returns table return
select v
from(select*,sum(iif(n<=@,v,0))over()r,sum(v)over(order by v)p
from(select row_number()over(order by-v)n,v
from STRING_SPLIT(@L,',')cross apply(select
try_parse(value as int)v)t)t)t
where p<=r and @<n
I know that using a more relation-like table to store the input data can make the code more concise, but using the character data type to store the numeric list and the STRING_SPLIT function, I get shorter the Build Schema part :)
More readable version:
CREATE FUNCTION f(@L NVARCHAR(MAX), @n INT)
RETURNS TABLE AS RETURN (
SELECT
v
FROM (
SELECT
*,
SUM(IIF(n<=@n, v, 0)) OVER() AS r,
SUM(v) OVER(ORDER BY v) AS p
FROM(
SELECT ROW_NUMBER() OVER(ORDER BY -v) AS n, v
FROM STRING_SPLIT(@L, ',')
CROSS APPLY(
SELECT TRY_PARSE(value AS INT) AS v
) AS t
) AS t
) AS t
WHERE p <= r AND @n < n
);
Try it on SQL Fiddle!
Python 2, 59 bytes
Also compatible with Python 3
f=lambda l,n:l[n:]*(sum(l)/2>=l.pop(n)+sum(l[n:]))or f(l,n)
Explanation
The sum of the suffix is compared to half of the sum of the whole list. If the sum of the suffix is smaller or equal, the suffix is returned. If not, the function is called recursively with the first item of the suffix popped out.
MathGolf, 13 bytes
(‼≥≤Σ\æ╞`Σ≥▼Þ
Explanation
Takes input as n L
( pops n and decrements (TOS is n-1)
‼ apply next two operators to stack simultaneously
≥ slice L[n-1:] (gets all elements with index >= n-1)
≤ slice L[:n] (gets all elements with index <= n-1)
Σ get sum of topmost list (this is the sum of n largest elements)
\ swap top elements
æ ▼ do while false with pop using block of length 4
╞ discard from left of string/array
` duplicate the top two items on the stack
Σ sum the list which is on top
≥ is the sum of the partial list >= the desired sum?
Þ discard everything but TOS
The reason why this works is that in the first step, we actually divide the list into two overlapping parts. As an example, L = [4, 3, 2, 1], n = 2 will split up the list as [3, 2, 1] and [4, 3]. The reason for having an extra element in the first list is that in the loop, the first thing that happens is a discard. If an extra element was not prepended, the cases where the output should be the entire rest of the list would fail.
MATL, 13 12 bytes
1 byte saved thanks to @Giuseppe, based on the answer by @MickyT.
:&)PtYsbs>~)
Output is in ascending order.
Try it online! Or verify all test cases.
Explanation
Consider inputs 2 and [500,200,150,150,125,100,75,75,55,50,40,30,30,20,10,10,8,5,5,5,3,2,2,1,0,-2,-3].
: % Implicit input: n. Push [1 2 ... n]
% STACK: [1 2]
&) % Implicit input: array. Two-output indexing: pushes the subarray
% indexed by [1 2 ... n] and the remaining subarray
% STACK: [500 200], [150 150 125 ... -2 -3]
P % Flip
% STACK: [500 200], [-3 -2 ... 125 150 150]
t % Duplicate top of the stack
% STACK: [500 200], [-3 -2 ... 125 150 150], [-3 -2 ... 125 150 150]
Ys % Cumulative sum
% STACK: [500 200], [-3 -2 ... 125 150 150], [-3 -5 ...646 796 946]
b % Bubble up in the stack
% STACK: [-3 -2 ... 125 150 150], [-3 -5 ...646 796 946], [500 200]
s % Sum
% STACK: [-3 -2 ... 125 150 150], [-3 -5 ...646 796 946], 7
>~ % Greater than, negate; element-wise
% STACK: [-3 -2 ... 125 150 150], [1 1 ... 1 0 0]
) % Index. Implicit display
% STACK: [-3 -2 ... 125]
APL(NARS), 32 chars, 64 bytes
{v/⍨(+/⍺↑⍵)≥+/¨{⍵↓v}¨¯1+⍳≢v←⍺↓⍵}
test and comments:
q←{v/⍨(+/⍺↑⍵)≥+/¨{⍵↓v}¨¯1+⍳≢v←⍺↓⍵}
2 q 500,200,150,150,125,100,75,75,55,50,40,30,30,20,10,10,8,5,5,5,3,2,2,1,0,¯2,¯3
125 100 75 75 55 50 40 30 30 20 10 10 8 5 5 5 3 2 2 1 0 ¯2 ¯3
2 q 10,5,5,3
5 3
⎕fmt 7 q 7,2,1,¯2,¯4,¯5,¯10,¯12
┌1───┐
│ ¯12│
└~───┘
2 q 0,¯5,¯10,¯15
¯10 ¯15
⎕fmt 1 q 100,35,25,15,5,5,5,5,5,5,5,5,5,5,5,5,5
┌14───────────────────────────┐
│ 15 5 5 5 5 5 5 5 5 5 5 5 5 5│
└~────────────────────────────┘
2 q 1000,999,998,900,800,766,525,525,400,340,120,110,80,77,33,12,0,¯15,¯45,¯250
525 525 400 340 120 110 80 77 33 12 0 ¯15 ¯45 ¯250
1 q 10,5,5
5 5
⎕fmt 2 q ¯5,¯10,¯13
┌0─┐
│ 0│
└~─┘
⎕fmt 1 q 30,20,10,0,¯10,¯20,¯30
┌6───────────────────┐
│ 20 10 0 ¯10 ¯20 ¯30│
└~───────────────────┘
{v/⍨(+/⍺↑⍵)≥+/¨{⍵↓v}¨¯1+⍳≢v←⍺↓⍵}
v←⍺↓⍵ v is ⍵[(⍺+1)..≢⍵]
{⍵↓v}¨¯1+⍳≢v build the array of array cut v of 0..((≢v)-1) elements
+/¨ sum each of these element of array above
(+/⍺↑⍵)≥ compare ≥ with the sum of ⍵[1..⍺] obtain one bolean array
has the same lenght of v
v/⍨ return the element of v that are 1 of the boolean array above
I reported wrongly the byte length...
PowerShell, 86 bytes
param($n,$l)$l|?{$k++-ge$n}|?{(&{$l|%{$s+=($_,0,-$_)[($n-le$i)+(++$i-ge$k)]};$s})-ge0}
Unrolled:
param($n,$list)
$list|?{$k++-ge$n}|?{ # tail elements after $n only
$sumLeftSegmentMinusSumRightSgement = &{ # calc in a new scope to reinit variables $s, $i
$l|%{$s+=($_,0,-$_)[($n-le$i)+(++$i-ge$k)]} # sum(list[0..n-1]) - sum(list[k-1..list.Count-1])
$s # output sum to the outer scope
}
$sumLeftSegmentMinusSumRightSgement -ge 0 # output elements where sum >= 0
}
APL (Dyalog Unicode), 23 21 bytesSBCS
Anonymous prefix lambda, taking \$n\$ as left argument and \$L\$ as right argument.
{⍵↓⍨⍺⌈⊥⍨(+/⍺↑⍵)<+\⌽⍵}
{…} "dfn"; \$n\$ is ⍺ (leftmost Greek letter) and \$L\$ is ⍵ (rightmost Greek letter):
⌽⍵ reverse \$L\$
+\ prefix sums of that
(…)< Boolean mask where less than:
⍺↑⍵ take the first \$n\$ elements of \$L\$
+/ sum those
⍺⌈ the maximum of \$n\$ and that
⍵↓⍨ drop that many elements from the front of \$L\$
JavaScript, 64 bytes
f=(a,n,s=0,[h,...t]=a)=>n<1?f(a)>s?f(t,0,s):a:1/h?f(t,n-1,s+h):s
f=(
a, // remaining array
n, // if n >= 0: we try to find suffix <= s + a[0..n]
// if n is NaN (or undefined): we calculate sum(a) + s
s = 0, // previous sum
[h, ...t] = a // split array (a) into head (h) and tail (t)
) => (n < 1 ? // if n == 0
f(a) > s ? // if sum(a) > s
f(t,0,s) : // drop head and test tail again
a : // otherwise, a is the answer
1 / h ? // if a is not empty
f(t,n-1,s+h) : // add head to sum and recurse
s // we only reach here if n is NaN, return the sum
)
Haskell, 46 bytes
Displeased with how this looks; hope I’m just missing some obvious golfs.
n#l=until(((sum$take n l)>=).sum)tail$drop n l
I tried getting the prefix and suffix using splitAt and pattern matching in a guard, but that turned out to be 3 bytes more.
Planning on trying to convert to a recursive function with guards later to see if that lowers the byte count.
Explanation
n # l = until (((sum $ take n l) >= ) . sum) tail $ drop n l
n # l = -- define infix operator
n -- the number of elements
l -- the list
until -- until
sum -- the sum of the suffix
((sum $ take n l) >=) -- is <= the sum of the prefix
tail -- remove the first element
drop n l -- the suffix
What I refer to as "the prefix" is the first n elements and "the suffix" is the rest of the list.
R, 53 55 bytes
@Giuseppe saved me 2 bytes changing the way remove was done
function(n,L,Y=rev(L[0:-n]))Y[cumsum(Y)<=sum(L[1:n])]
Try it online! Takes the input as descending and outputs in ascending as allowed by rule 4.
Yis the rev ofLwith 1:n removed using0:-n- returns from
Ywhere cumulative sum is less then equal to the sum ofL[X]
Ruby, 47 43 bytes
Takes an ascending list as input. Removes \$n\$ items from the end of the array to get the initial sum, then continue removing items until the remaining elements' sum is less than the initial sum.
-4 bytes by reading the spec more closely.
->a,n{s=a.pop(n).sum;a.pop while a.sum>s;a}
Gaia, 12 bytes
eSe¤Σ¤┅⟪Σ⊃⟫∇
I think there's a byte I can golf if I get the stack just right.
e | eval first input as Gaia code
S | Split into a list of ["first n elements" "rest of elements"]
e | dump onto stack
¤Σ | swap and take the sum (sum of first n elements)
¤┅ | swap and take suffixes
⟪ ⟫∇ | return the first element of suffixes where:
Σ⊃ | the sum(first n elements) ≥ sum(suffix)
Jelly, 13 12 bytes
ṫḊÐƤS>¥ÞḣS¥Ḣ
Thanks to @JonathanAllan for saving a byte!
A dyadic link taking the list of values \$L\$ as left argument and the number \$n\$ as right.
Explanation
ṫ | Tail: take all values of L from the nth onwards (which is actually one too many; dealt with below)
ḊÐƤ | Take all suffixes, removing the first value from each. This will yield a list of all possible suffixes of L that exclude the first n values
Þ | Sort by:
S>¥ ḣS¥ | - The sum is greater than the sum of the first n values of L
Ḣ | Take the first resulting list and return from link (implicitly output when called as a full program)
APL+WIN, 27 bytes
Prompts for input of L then n.
⌽((+/n↑v)≥+\m)/m←⌽(n←⎕)↓v←⎕
Clojure, 66 75 bytes
#(loop[v(drop %2 %)](if(>(apply + v)(apply +(take %2 %)))(recur(rest v))v))
Sadly there doesn't seem to be a shorter idiom for the total sum of a sequence.
Edit: Oh when adding examples to the Try it online! link I noticed that the original answer gave wrong results when many negative numbers were present.
The doseq uses "keys" destructuring so it should be somewhat clear which data ends up in which symbol. #(...) is an anonymous function, here I'm binding it to the symbol f:
(def f #(loop[v(drop %2 %)](if(>(apply + v)(apply +(take %2 %)))(recur(rest v))v)))
(doseq [{:keys [L n]} [{:L [10,5,5,3] :n 2}
{:L [7,2,1,-2,-4,-5,-10,-12] :n 7}
{:L [30,20,10,0,-10,-20,-30] :n 1}]]
(println (f L n)))
Output:
(5 3)
(-12)
(20 10 0 -10 -20 -30)
05AB1E, 14 12 bytes
Saved 2 bytes thanks to Grimy
.$ΔDOI¹£O›.$
Explanation
.$ # drop the first n entries of the list
Δ # repeat the following code until the result doesn't change
DO # duplicate and sum the copy
I¹£O # calculate the sum of the first n items of the input
›.$ # if the current sum is greater than the sum of the first n items
# remove the first item of the current list
Pyth, 16 15 bytes
efgs>vzQsT._<vz
The input list is expected to be sorted in ascending order, rather than descending as is used in the examples.
It's at times like this when I really wish Pyth had a single token operator to access the second input more than once (E evaluates the next line of input, but repeated calls discard the previous value read).
efgs>vzQsT._<vzQ Implicit: Q=eval(input()), z=input() - that is, Q is list, z is string n
Trailing Q inferred
vz Evaluate z as integer
< Q Remove the above number of elements from the end of Q
._ Generate a list of all prefixes of the above
f Filter keep elements of the above, as T, where:
>vzQ Take the last z elements of Q
s Sum
g Is the above greater than or equal to...
sT ... the sum of T?
e Take the last remaining element, implicit print
Edit: saved 1 byte thanks to MrXcoder
JavaScript (ES6), 66 bytes
Takes input as (a)(n) with the list in ascending order.
a=>n=>(g=s=>n?g(s+a.pop(n--)):eval(a.join`+`)>s?g(s,a.pop()):a)(0)
Commented
a => n => // a[] = list, n = number of richest guys
( g = s => // g is a recursive function taking a sum s
n ? // if n is not equal to 0:
g(s + a.pop(n--)) // recursive call: add the last entry to s and decrement n
: // else:
eval(a.join`+`) // if the sum of the remaining entries
> s ? // is greater than s:
g(s, a.pop()) // recursive call with the last entry removed
: // else:
a // stop recursion and return a[]
)(0) // initial call to g with s = 0
J, 18 bytes
}.#~+/@{.>:+/\.@}.
Explanation:
A dyadic verb, taking n as its left argument and L - as its right argument.
}. drop the first n items from L
@ and
\. for each suffix (starting from the longest)
+/ find its sum
>. is this sum smaller or equal than (results in a boolean vector)
+/ the sum
@ of
{. the first n items of L
#~ use the 1s in the boolean vector to copy the respective
}. elements of L (without the first n)
Python 2, 60 bytes
l,n=input()
s=sum(l[:n])
while sum(l[n:])>s:n+=1
print l[n:]
Explanation:
First takes the sum of the first n items.
Then the sum of each sublist is compared to this sum. As soon as one is not larger, we stop.
Then the resulting (longest) sublist is printed.
Charcoal, 17 bytes
IΦθ¬∨‹κη‹Σ…θηΣ✂θκ
Try it online! Link is to verbose version of code. Explanation:
θ Input `L`
Φ ¬ Filter out elements where
κ Current index
‹ Is less than
η Input `n`
∨ Logical Or
θ Input `L`
… η First `n` terms
Σ Summed
‹ Is less than
✂θκ Remainder of `L`
Σ Summed
I Cast to string
Implicitly print on separate lines