Les 26 milliardaires les plus riches possèdent-ils autant de richesses que les 3,8 milliards de personnes les plus pauvres?

37

Introduction:

Il y a quelques jours, j'ai lu ce billet avec le même titre quand je l'ai trouvé dans la HNQ. Dans cette question, on discute de la revendication du président-candidat Bernie Sanders, qui a affirmé ce qui suit:

Aujourd'hui, les 26 milliardaires les plus riches du monde, 26, possèdent autant de richesses que les 3,8 milliards les plus pauvres de la planète, soit la moitié de la population mondiale.
Lien vers la vidéo

est vrai ou pas. Veuillez vous rendre à la question elle-même pour y trouver des réponses et des discussions.

En ce qui concerne le défi réel basé sur cette revendication:

Défi:

Deux entrées: une liste numérique triée par ordre décroissant L et un nombre n (où n est 1n<length of L ).
Sortie: le plus long sous-liste de suffixe possible de L dont la somme totale est à la somme des premiers n valeurs dans la liste L .

Exemple:

Entrées: L = [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]et n=2 .
Sortie:[125,100,75,75,55,50,40,30,30,20,10,10,8,5,5,5,3,2,2,1,0,-2,-3]

Pourquoi?

Les n=2 valeurs de la liste L ( [500,200]) totalisent 700. Si nous prenons tous les suffixes des nombres restants, ainsi que leurs sommes:

Suffix:                                                                  Sum:

[-3]                                                                     -3
[-2,-3]                                                                  -5
[0,-2,-3]                                                                -5
[1,0,-2,-3]                                                              -4
[2,1,0,-2,-3]                                                            -2
[2,2,1,0,-2,-3]                                                          0
[3,2,2,1,0,-2,-3]                                                        3
[5,3,2,2,1,0,-2,-3]                                                      8
[5,5,3,2,2,1,0,-2,-3]                                                    13
[5,5,5,3,2,2,1,0,-2,-3]                                                  18
[5,5,5,5,3,2,2,1,0,-2,-3]                                                23
[10,5,5,5,5,3,2,2,1,0,-2,-3]                                             33
[10,10,5,5,5,5,3,2,2,1,0,-2,-3]                                          43
[20,10,10,5,5,5,5,3,2,2,1,0,-2,-3]                                       63
[30,20,10,10,5,5,5,5,3,2,2,1,0,-2,-3]                                    93
[30,30,20,10,10,5,5,5,5,3,2,2,1,0,-2,-3]                                 123
[40,30,30,20,10,10,5,5,5,5,3,2,2,1,0,-2,-3]                              163
[50,40,30,30,20,10,10,5,5,5,5,3,2,2,1,0,-2,-3]                           213
[55,50,40,30,30,20,10,10,5,5,5,5,3,2,2,1,0,-2,-3]                        268
[75,55,50,40,30,30,20,10,10,5,5,5,5,3,2,2,1,0,-2,-3]                     343
[75,75,55,50,40,30,30,20,10,10,5,5,5,5,3,2,2,1,0,-2,-3]                  418
[100,75,75,55,50,40,30,30,20,10,10,5,5,5,5,3,2,2,1,0,-2,-3]              518
[125,100,75,75,55,50,40,30,30,20,10,10,5,5,5,5,3,2,2,1,0,-2,-3]          643
[150,125,100,75,75,55,50,40,30,30,20,10,10,5,5,5,5,3,2,2,1,0,-2,-3]      793
[150,150,125,100,75,75,55,50,40,30,30,20,10,10,5,5,5,5,3,2,2,1,0,-2,-3]  943

Le suffixe le plus long qui a une somme inférieure ou égale à 700est [125,100,75,75,55,50,40,30,30,20,10,10,8,5,5,5,3,2,2,1,0,-2,-3]avec une somme de 643, voilà notre résultat.

Règles du challenge:

  • Les valeurs dans le n premier préfixe ne sont pas comptées dans le suffixe de sortie. Par exemple, les entrées L = [10,5,5,3]et n=2 auraient pour résultat [5,3], et non [5,5,3].
  • I / O est flexible. Vous pouvez entrer L sous forme de liste / flux / tableau d'entiers / décimales / chaînes, une seule chaîne délimitée, un par un via STDIN, etc. Vous pouvez également générer une liste / flux / tableau d'entiers / décimales / chaînes, imprimer / retourner une chaîne délimitée, imprimer un numéro sur chaque nouvelle ligne, etc. Votre appel.
  • La sortie est garantie d'être non vide. Ainsi, vous n’avez pas à traiter de cas de tests tels que L = [-5,-10,-13]et n=2 ce qui donne [].
  • Si vous le souhaitez, l’entrée et / ou la sortie peuvent aussi bien être dans l’ordre croissant que dans l’ordre décroissant.

Règles générales:

  • C'est du , donc la réponse la plus courte en octets est gagnante.
    Ne laissez pas les langues de code-golf vous décourager de poster des réponses avec des langues autres que le code de golf. Essayez de trouver une réponse aussi courte que possible à n'importe quel langage de programmation.
  • Les règles standard s'appliquent à votre réponse avec les règles d'E / S par défaut . Vous êtes donc autorisé à utiliser STDIN / STDOUT, fonctions / méthode avec les paramètres appropriés et des programmes complets de type de retour, de type renvoyé. Ton appel.
  • Les failles par défaut sont interdites.
  • Si possible, veuillez ajouter un lien avec un test pour votre code (c.-à-d. TIO ).
  • En outre, l'ajout d'une explication de votre réponse est fortement recommandé.

Cas de test:

Inputs: L=[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], n=2
Output: [125,100,75,75,55,50,40,30,30,20,10,10,8,5,5,5,3,2,2,1,0,-2,-3]

Inputs: L=[10,5,5,3], n=2
Output: [5,3]

Inputs: L=[7,2,1,-2,-4,-5,-10,-12], n=7
Output: [-12]

Inputs: L=[30,20,10,0,-10,-20,-30], n=1
Output: [20,10,0,-10,-20,-30]

Inputs: L=[100,35,25,15,5,5,5,5,5,5,5,5,5,5,5,5,5], n=1
Output: [15,5,5,5,5,5,5,5,5,5,5,5,5,5]

Inputs: L=[0,-5,-10,-15], n=2
Output: [-10,-15]

Inputs: L=[1000,999,998,900,800,766,525,525,400,340,120,110,80,77,33,12,0,-15,-45,-250], n=2
Output: [525,525,400,340,120,110,80,77,33,12,0,-15,-45,-250]

Inputs: L=[10,5,5], n=1
Output: [5,5]
Kevin Cruijssen
la source
Puis-je écrire une réponse qui ne fonctionne qu'avec des entiers positifs (ou peut-être non négatifs; je ne l'ai pas encore écrite) en raison de l'absence d'un type entier dans la langue?
Neil
3
@ Neil Je suppose que vous parlez de Retina ici? Mais bien sûr, vous pouvez supposer que toutes les valeurs sont non négatives dans ce cas. Cependant, est-il préférable d’avoir une deuxième version qui fonctionne pour les valeurs négatives, car j’ai le sentiment que c’est réalisable (avec une augmentation considérable du nombre d’octets et de quelques solutions de rechange); ce qui est plus un sentiment général qu'un fait réel, ne sachant pas s'il est effectivement possible de contourner la partie des valeurs négatives).
Kevin Cruijssen le
6
Le cas de test réel ressemblerait à ceci [131000000000, 96500000000, 82500000000, 76000000000, (7.7 billion more entries)]:: p
Arnauld
2
Qu'en est-il du scénario où aucune des valeurs ne répond aux critères: [1,2,3] n = 1? Que voulez-vous pour la sortie?
ouflak
@ouflak Voir la troisième règle de challenge: " Le résultat est garanti pour être non vide. Vous n'aurez ainsi pas à traiter de cas de test tels que L = [-5,-10,-13]et n=2ayant abouti []. " croissant si vous le souhaitez), il n’ya donc [1,2,3]pas de liste d’entrée valide pour commencer (à moins que vous ne choisissiez une entrée croissante, auquel cas ce [1,2]serait le résultat).
Kevin Cruijssen le

Réponses:

17

C # (compilateur interactif Visual C #) , 88 81 69 68 63 octets

-4 octets grâce à LiefdeWen

a=>b=>a.Skip(b).Where((x,i)=>a.Skip(i+b).Sum()<a.Take(b).Sum())

Essayez-le en ligne!

Données expirées
la source
I'm thinking you could shave off two more by eliminating +b in the Skip call; it's redundant to check the first n list, but I think it's still correct.
TheRubberDuck
3
@TheRubberDuck nope, had to add it in for the case where the prefix and suffix overlap. I.e [10,5,5,3], n = 2
Expired Data
64 bytes
LiefdeWen
@LiefdeWen nice! it's actually less too if we use a curried function
Expired Data
@ExpiredData Oh yeah, forgot I removed it.
LiefdeWen
12

EXAPUNKS (2 EXAs, 30 Instructions, 594-byte solution file)

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

ymbirtt
la source
IIRC doesn't exapunks have a way to save solutions? If so you should use byte count rather than in game instructions.
Wheat Wizard
1
@SriotchilismO'Zaic, yep, I didn't think the files were supposed to be easily-accessible, but I've just found them. I'll add the size-on-disk. A bunch of metadata that I didn't write gets stored alongside it, but I guess this is the best way to actually get a single "byte count" out of this game.
ymbirtt
I'd love to take the time to look at these files and see if there is a way to sort of golf the metadata down. I also wonder if some instructions take more memory than others.
Wheat Wizard
@SriotchilismO'Zaic, they actually do. All the instructions get stored as plaintext, so for a start we can turn all the marks to single-letter identifiers. The name of your solution is in there, so we can remove a few bytes by calling the solution 'a'. Some parts of it also seem related to the virtual network you created for the EXA, though. Honestly, I think the "fairest" way to score EXAPUNKS solutions is to either use the byte count of the actual code, or the number of instructions. This might be worth a meta post...
ymbirtt
2
@ymbirtt I suppose the question then comes down to could you write an interpreter which will look at the instructions and convert into the saved data? Well trivially yes, just write a program which inputs for you from the source.. it would count as a different language though.
Expired Data
11

Python 2, 60 bytes

l,n=input()
s=sum(l[:n])
while sum(l[n:])>s:n+=1
print l[n:]

Try it online!


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.

TFeld
la source
2
actually the most readable one +1
Kryštof Řeháček
10

05AB1E, 14 12 bytes

Saved 2 bytes thanks to Grimy

.$ΔDOI¹£O›.$

Try it online!

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
Emigna
la source
2
'Exactly' the same as what I had prepared as solution. And by 'exactly' I mean mine was .$.sʒO²¹£O>‹}θ. :)
Kevin Cruijssen
2
@KevinCruijssen here's 12
Grimmy
1
ASCII-only 12 (using a different input method).
Grimmy
1
@Grimy: Huh. I never knew | overwrote the last-input, interesting.
Emigna
2
@Grimy: See this vs this. Normally when all inputs are consumed, the last input is implicitly used for all instances of next input. Using | here makes the result of | become the last input instead of what was actually the last input.
Emigna
7

J, 18 bytes

}.#~+/@{.>:+/\.@}.

Try it online!

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)
Galen Ivanov
la source
7

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}

Try it online!

Value Ink
la source
7

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.

  • Y is the rev of L with 1:n removed using 0:-n
  • returns from Y where cumulative sum is less then equal to the sum of L[X]
MickyT
la source
@Giuseppe as always thanks. Tried removing the X using -(1:n) but of course that was the same size, so left it
MickyT
6

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)

Try it online!

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
Arnauld
la source
1
@KevinCruijssen Seems like I misread the requirement. Should be fixed now.
Arnauld
And unlike some other answers that had fixed the same issue, without an increase in byte-count. :) (And partially my bad, should have included a test case for to begin with..)
Kevin Cruijssen
5

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)

Try it online!


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.

Jitse
la source
4

Pyth, 16 15 bytes

efgs>vzQsT._<vz

Try it online!

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

Sok
la source
@Mr.Xcoder Good grief, what an obvious save! Thanks 👍
Sok
4

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

Try it online!

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
)
tsh
la source
4

Stax, 12 bytes

îo╧╫Σ↑>'qµΣº

Run and debug it at staxlang.xyz!

Nicer version

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.

Khuldraeseth na'Barya
la source
3

Japt, 16 bytes

£sV+YÃæ_x §U¯V x

Try it

£sV+YÃæ_x §U¯V x     :Implicit input of U=L and V=n
£                    :Map U, with Y being the 0-based indices
 sV+Y                :  Slice U from index V+Y
     Ã               :End map
      æ              :First element that returns true
       _             :When passed through the following function
        x            :  Reduce by addition
          §          :  Less than or equal to
           U¯V       :    Slice U to index V
               x     :    Reduce by addition
Shaggy
la source
3

Jelly, 13 12 bytes

ṫḊÐƤS>¥ÞḣS¥Ḣ

Try it online!

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)
Nick Kennedy
la source
You can save a byte by sorting instead of filtering: ṫḊÐƤS>¥ÞḣS¥Ḣ
Jonathan Allan
3

Gaia, 12 bytes

eSe¤Σ¤┅⟪Σ⊃⟫∇

Try it online!

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)
Giuseppe
la source
3

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

Try it online!

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.

cole
la source
3

APL (Dyalog Unicode), 23 21 bytesSBCS

Anonymous prefix lambda, taking n as left argument and L as right argument.

{⍵↓⍨⍺⌈⊥⍨(+/⍺↑⍵)<+\⌽⍵}

Try it online!

{} "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

⊥⍨count trailing truths

⍺⌈ the maximum of n and that

⍵↓⍨ drop that many elements from the front of L

Adám
la source
1
@KevinCruijssen Nicely spotted. Fixed.
Adám
3

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]
Luis Mendo
la source
3

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]

Try it online!

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]
Veskah
la source
3

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.

Neil
la source
Nice answer. :) Could you perhaps add a TIO link to the version that's 12 bytes longer containing negative numbers. And np that it doesn't work when the first n numbers sum to a negative value. As long as it works with positive integers it's still fine. Well done.
Kevin Cruijssen
1
@KevinCruijssen My negative number version turned out to be prohibitively slow, but I managed to fix that by using the r option, so I've now linked it in with some test cases.
Neil
2

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
Neil
la source
2

PowerShell, 86 bytes

param($n,$l)$l|?{$k++-ge$n}|?{(&{$l|%{$s+=($_,0,-$_)[($n-le$i)+(++$i-ge$k)]};$s})-ge0}

Try it online!

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
}
mazzy
la source
2

MathGolf, 13 bytes

(‼≥≤Σ\æ╞`Σ≥▼Þ

Try it online!

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.

maxb
la source
2

Wolfram Language (Mathematica), 40 bytes

Drop@##//.{a_,b__}/;a+b>Tr@Take@##:>{b}&

Try it online!

Drop@##                     (*don't include the first n values*)
 //.{a_,b__}/;a+b>Tr@Take@##(*while the remaining values sum to greater than the sum of the first n*)
     :>{b}&                 (*drop the first element*)
attinat
la source
1

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)
NikoNyrh
la source
1
Would you mind adding a TIO with test code (I see Clojure in the list)? If it isn't possible somehow (version mismatch, or using builtins that aren't available on TIO), could you include a screenshot with some of the test cases as verification that it works?
Kevin Cruijssen
1

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

RosLuP
la source
1

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!

Andrei Odegov
la source