Meglio tardi che mai!


12

Il tuo programma / funzione, ecc. Avrà 2 ingressi. Il primo sarà un elenco di chi è venuto alla mia festa e quando. Esempio:

Kevin 13:02  
Ruby 5  
Sam 3  
Lisa 6  
Bob 12  

Cosa significa? Vuol dire che Kevin è arrivato prima alla mia festa (alle 13:02, 24 ore su 24), poi Ruby 5 minuti dopo, poi Sam 3 minuti dopo, poi Lisa 6 minuti dopo e infine Bob 12 minuti dopo.

Il secondo input sarà quando la mia festa è iniziata. Esempio:

13:15

(24 ore). L'output deve essere l'elenco delle persone in ritardo. (Chiunque sia puntuale, va bene.) Calcoli di esempio (solo per esempio, non emetterli)

Kevin 13:02
Ruby 13:07
Sam 13:10
Lisa 13:16
Bob 13:28

Lisa e Bob sono arrivati ​​dopo 13:15, quindi questo programma dovrebbe stampare "Lisa, Bob".

Presupposti di input

  • L'ingresso 1 sarà sempre un nome (regex [A-Z][a-z]*), quindi uno spazio, quindi un tempo di 24 ore nel modulo hours:minutessulla prima riga, quindi un nome, uno spazio e un numero intero positivo (numero di minuti dopo) nelle righe successive . Ci sarà sempre almeno 1 riga.
  • Se lo desideri, puoi prendere l'ingresso 1 con qualsiasi altro carattere anziché un'interruzione di riga.
  • L'ingresso 2 sarà nel formato hours:minutes.
  • Se lo desideri, puoi prendere i tuoi input come una stringa separata da qualsiasi carattere. Questo è facoltativo
  • Non preoccuparti del crossover diurno. Le mie feste non lo seguiranno mai 23:59.

Regole di uscita

  • L'output può essere un valore di ritorno della funzione o una stringa ripetuta su STDIN, un file, ecc. È necessario restituire una stringa o un array / elenco.
    • Se restituisci una stringa, deve essere ogni persona in ritardo (l'ordine non ha importanza), separato da qualsiasi delimitatore non alfanumerico.
    • Se si restituisce un array / elenco, deve essere un elenco di tutti coloro che erano in ritardo.

2
È necessario il formato di input rigoroso? Ad esempio, il primo input potrebbe essere un elenco di elenchi, ognuno dei quali è una "riga" contenente i due elementi di dati?
Jonathan Allan,

"L'ingresso 1 sarà sempre un nome (regex [A-Z][a-z]*)" Questo suggerisce che i nomi possono essere vuoti?
HyperNeutrino,

2
Suppongo che intendevi "sì, è necessario il formato di input rigoroso".
Jonathan Allan,

2
Il formato di input rigoroso rende questa sfida meno interessante
Luis Mendo,

3
"Le mie feste non finiranno mai dopo le 11:59." intendi 23:59?
TSH

Risposte:


3

MATL , 31 byte

jYb1L&)1&)XUYs1440/0whwYO+jYO>)

Il primo input utilizza lo spazio anziché l'interruzione di riga (consentita dalla sfida).

L'output utilizza l'interruzione di linea come separatore.

Provalo online!

Spiegazione

j       % Input first string
Yb      % Split at spaces. Gives cell array of strings
1L&)    % Separate into subarrays with odd and even indices. Odd are names, even
        % are time and increments in minutes
1&)     % Separate the subarray of even indices into first entry and remaining
        % entries. The first is a string representing the time of first arrival,
        % the rest are strings representing increments in minutes
XU      % Convert strings representing increments into the actual numbers
Ys      % Cumulative sum
1440/   % Divide by 1440 (number of minutes in a day)
0wh     % Prepend a 0
w       % Swap. Bring the string with time of first arrival to the top
YO      % Convert to serial date number. Fractional part indicates time
+       % Add. This gives all arrivals as serial date numbers
j       % Input second string
YO      % Convert to serial date number
>       % Less than?, element-wise
)       % Index: select the names for which the comparison gave true
        % Implicitly display

6

JavaScript (ES6), 98 97 byte

Salvato 1 byte grazie a Neil

Visualizza l'elenco degli ospiti le l'orario della festa hnella sintassi del curry (l)(h). Si aspetta un'interruzione di riga finale nell'elenco. Restituisce un elenco separato da spazi di nomi come Lisa Bob.

l=>h=>l.replace(/(.* )(.*)\n/g,(_,a,b)=>(t-=T(b))<0?a:'',t=(T=h=>eval(h.replace(/:/,'*60+')))(h))

Formattato e commentato

l => h =>                         // given a list of guests l and a party time h
  l.replace(                      // for each guest in l:
    /(.* )(.*)\n/g,               //   extract the name a and arrival time b
    (_, a, b) =>                  //   subtract the arrival time from the time counter
      (t -= T(b)) < 0 ?           //   if the result is negative:
        a                         //     the guest is late: keep the name
      :                           //   else:
        '',                       //     the guest is on time: remove this entry
    t = (                         //   initialize the time counter t
      T = h =>                    //   define T():
        eval(                     //     a function that takes either a time
          h.replace(/:/, '*60+')  //     in hh:mm format or an amount of minutes
        )                         //     and returns an amount of minutes   
    )(h)                          //   call it with the party time
  )                               // end of replace()

dimostrazione

let f =

l=>h=>l.replace(/(.* )(.*)\n/g,(_,a,b)=>(t-=T(b))<0?a:'',t=(T=h=>eval(h.replace(/:/,'*60+')))(h))

console.log(f(`Kevin 13:02
Ruby 5
Sam 3
Lisa 6
Bob 12
`)('13:15'))


Soluzione intelligente! +1. Il mio è molto lontano ....... :(
Arjun,

Non (.*) (.*)\nfunziona?
Neil,

@Neil Essendo avido di default, il primo (.*)corrisponderebbe all'intera linea.
Arnauld,

Quindi quale spazio corrisponderebbe?
Neil,

@Neil Oh, scusa, hai ragione.
Arnauld,

6

PHP, 118 98 95 91 byte

while($n=$argv[++$i])$i&1?$p=$n:($t=($f=strtotime)($n)?:$t+60*$n)<=$f(end($argv))?:print$p;

accetta input dagli argomenti della riga di comando (se lo desideri, puoi interpretarlo come linee separate da spazi); stampa i nomi senza delimitatore. Esegui -ro testalo online .

modifica 1: salvati 20 byte con la stampa diretta
modifica 2: salvati 3 byte rimuovendo il delimitatore
modifica 3: salvati 4 byte sfruttando che numeri interi non sono date valide perstrtotime

abbattersi

while($n=$argv[++$i])       # loop through arguments, skip [0]
    $i&1                        # if index is odd   
    ?   $p=$n                   # then assign name to $p
    :   ($t=                    # else $t =
        ($f=strtotime)($n)          # if $n is a valid time, parse it
        ?:$t+60*$n                  # else add $n minutes to current $t
        )<=$f(end($argv))           # if $t <= parsed party start
        ?                           # then do nothing
        :print$p;                   # else print name

6

c, 178 byte

main(c,o,d,e,g,O,l,f,x,y)char**o,d[80],*O,*l,*f;{for(sscanf(o[2],"%d:%d",&e,&g),x=e*60+g,l=";",f=o[1];O=strtok(f,l);f=0)(y=sscanf(O,"%s%d:%d",d,&e,&g)^2?e*60+g:y+e)>x?puts(d):0;}

Provalo online


5

JavaScript ES6, 185 byte

l=>t=>l.split`
`.map(p=>p.split` `).map((p,i,a)=>[p[0],i?d(a[0][1])+a.slice(1,i+1).reduce((a,p)=>a+=+p[1],0)*6e4:(d=x=>Date.parse(`2017T${x}`))(p[1])]).filter(p=>p[1]>d(t)).map(p=>p[0])

Provalo online!

const f = l=>t=>l.split`
`.map(p=>p.split` `).map((p,i,a)=>[p[0],i?d(a[0][1])+a.slice(1,i+1).reduce((a,p)=>a+=+p[1],0)*6e4:(d=x=>Date.parse(`2017T${x}`))(p[1])]).filter(p=>p[1]>d(t)).map(p=>p[0])


console.log(f('Kevin 13:02\nRuby 5\nSam 3\nLisa 6\nBob 12')('13:15'))


Per quanto ne so dalle specifiche, il modulo di input potrebbe essere più rigoroso.
Jonathan Allan,

Penso che sia corretto ora.
Powelles,

Sì - ho anche chiesto informazioni sulla rigidità degli input.
Jonathan Allan,

... in realtà hai i tempi nei tuoi input, non gli offset che dovrebbero esseref('Kevin 13:02\nRuby 5\nSam 3...
Jonathan Allan,

1
@JonathanAllan Grazie. Ho capito adesso.
Powelles,

4

PowerShell , 215 196 180 byte

param($a,$b)$x,[array]$a=$a-split',';$z=@{};$i,$j=-split$x;$z[$i]=($y=date $j);0..($a.count-1)|%{$i,$j=-split$a[$_];$z[$i]=($y=$y|% *es $j)};($z|% *or|?{$_.value-gt(date $b)}).Name

Provalo online!

All'incirca 1/3 di questo è l'analisi dell'input, quindi non sono sicuro di quanto ancora posso golf.

Accetta l'input $acome una stringa delimitata da virgole di nomi e tempi / minuti e $bcome hh:mmstringa. In primo luogo, -split $asulla ,, memorizzare il primo risultato in $xe il restante in $a, con una ri-cast esplicito di $acome array(in modo che il ciclo in seguito corretto funzionamento). Abbiamo il nostro Inizializziamo tabella hash $z, set $ie $jdi essere $x -splitin spazi, e impostare $z[$i]di essere il datedi $j(memorizzati in $yper un uso successivo).

Quindi passiamo attraverso il resto $a. Ogni iterazione, facciamo in modo simile - -splitla stringa su uno spazio bianco, imposta l' $zindice appropriato in modo che sia molti più minuti oltre dove siamo attualmente. Questo utilizza un trucco abbreviato per il nome della proprietà per salvare alcuni byte, usando |% *es $jinvece di .AddMinutes($j).

Alla fine, noi .GetEnumerator()(di nuovo usando il trucco) della nostra tabella hash, e Where-Objectselezioniamo quelle voci con un han di valuetale -greater (cioè, sono in ritardo alla festa). Selezioniamo quindi solo i relativi. L'output è un array implicito, tra cui il default inserisce le nuove righe.t$b.NameWrite-Output

Ho salvato un sacco grazie a Briantist per avermi ricordato che [array] è una cosa. E un sacco di più per la punta abbreviata del nome della proprietà.


Ammetto di aver letto e testato minimamente questo, ma non potevi farlo$x,[array]$a=$a-split',' ?
briantist

1
@briantist Sì, grazie. Continuavo a cercare un modo per utilizzare l'operatore virgola nell'assegnazione multipla e semplicemente non funzionava. Avevo completamente dimenticato che [array]è un cast valido. Haha. Troppo golf, immagino.
AdmBorkBork,

Sono su cellulare quindi sarebbe difficile testarlo, ma penso GetEnumeratore AddMinutessono buoni candidati per la %sintassi del metodo
briantista

@briantist Yep. Ne salva un altro 16. Grazie!
AdmBorkBork,

4

Python 2 , 140.148, 144 byte

t,h,n=map(str.split,input().replace(':','').split(';')),100,0
for a,v in t[:-1]:
 n+=int(v)
 if n%h/60:n=n/h*h+n%h%60+h
 if`n`>t[-1][0]:print a,

Provalo online!

Formato di input:

'Kevin 13:02;Ruby 5;Sam 3;Lisa 6;Bob 12;13:15'

Non gestisce correttamente il trabocco dei minuti: 'Kevin 13:47;Ruby 5;Sam 3;Lisa 6;Bob 12;14:00'non stampa nulla, anche se Lisa e Bob sono ancora in ritardo.
L3viathan,

1
o si. C'è stato un problema tecnico! Aggiustato. Grazie!
Keerthana Prabhakaran,

3

Bash, 135 124 115 byte

a=($1)
for i in `seq 3 2 ${#a[@]}`
do((v+=a[i]))
((`date -d${a[1]} +%s`+v*60>`date -d$2 +%s`))&&echo ${a[i-1]}
done

Provalo online!


3

CJam, 66 54 58 54 51 49 46 byte

{{':/60b}:K~)rSrKs++q+S/2/z~:i[{1$+}*]2$+$@#>}

L'ingresso 1 è dato tramite STDIN, l'ingresso 2 è dato come una stringa nello stack. L'output è un array nello stack. Il separatore per l'ingresso 1 è uno spazio, ad es Kevin 13:02 Ruby 5 Sam 3 Lisa 6 Bob 12.

Traccia dello stack:

         e# Stack:               | "13:15"
{        e# Define K and run it:
  ':/    e#   Split on colon:    | ["13" "15"]
  60b    e#   From base 60:      | 795
}:K~     e# End def
)        e# Increment:           | 796
r        e# Read token:          | 796 "Kevin"
S        e# Push space:          | 796 "Kevin" " "
r        e# Read another token:  | 796 "Kevin" " " "13:02"
K        e# K()                  | 796 "Kevin" " " 782
s        e# Convert to string:   | 796 "Kevin" " " "782"
++       e# Add together:        | 796 "Kevin 782"
q        e# Read rest of input:  | 796 "Kevin 782" " Ruby 5 Sam 3 Lisa 6 Bob 12"
+        e# Add together:        | 796 "Kevin 782 Ruby 5 Sam 3 Lisa 6 Bob 12"
S/       e# Split on spaces:     | 796 ["Kevin" "782" "Ruby" "5" "Sam" "3" "Lisa" "6" "Bob" "12"]
2/       e# Group by 2:          | 796 [["Kevin" "782"] ["Ruby" "5"] ["Sam" "3"] ["Lisa" "6"] ["Bob" "12"]]
z        e# Transpose:           | 796 [["Kevin" "Ruby" "Sam" "Lisa" "Bob"] ["782" "5" "3" "6" "12"]]
~        e# Unpack:              | 796 ["Kevin" "Ruby" "Sam" "Lisa" "Bob"] ["782" "5" "3" "6" "12"]
:i       e# Convert all to int:  | 796 ["Kevin" "Ruby" "Sam" "Lisa" "Bob"] [782 5 3 6 12]
[{1$+}*] e# Accumulate:          | 796 ["Kevin" "Ruby" "Sam" "Lisa" "Bob"] [782 787 790 796 808]
2$       e# Copy back element:   | 796 ["Kevin" "Ruby" "Sam" "Lisa" "Bob"] [782 787 790 796 808] 796
+        e# Add into array:      | 796 ["Kevin" "Ruby" "Sam" "Lisa" "Bob"] [782 787 790 796 808 796]
$        e# Sort:                | 796 ["Kevin" "Ruby" "Sam" "Lisa" "Bob"] [782 787 790 796 796 808]
#        e# Find index:          | ["Kevin" "Ruby" "Sam" "Lisa" "Bob"] 3
>        e# Slice:               | ["Lisa" "Bob"]

Spiegazione:

  • La procedura Kconverte tra un tempo hh:mme un numero che rappresenta il numero di minuti trascorsi dalla mezzanotte.
  • Leggiamo la prima persona e sostituiamo il loro tempo con K (il loro tempo). Aggiungiamo quindi questo alla parte anteriore dell'input.
  • Quindi eseguiamo alcune operazioni sulle stringhe per ottenere un elenco di nomi e un elenco di volte, ad esempio [782 5 3 6 12].
  • Accumulando questo elenco, otteniamo [782 787 790 796 808], il che dà i tempi in cui sono venuti tutti.
  • Il modo più breve per scoprire chi è in ritardo è inserire l'ora di inizio nell'array e quindi riordinarlo per posizionarlo dove dovrebbe essere. Troviamo quindi l'indice per capire dove si trova, quindi suddividiamo l'elenco di nomi da quell'indice.

2

JavaScript, 285 283 byte

Visualizza l'elenco degli ospiti ie l'orario della festa pnella sintassi del curry (i)(p). Restituisce un elenco separato da virgole di nomi come Lisa,Bob.

i=>p=>{n=i.split`
`,a=new Date(0,0,0,...n[0].split` `[1].split`:`),y=new Date(0,0,0,...p.split`:`),t=[a];w=a;n.slice(1).map((j,k,l)=>{h=l[k].split` `[1]*6e4;t.push(new Date(w.getTime()+h));w=new Date(w.getTime()+h)});return n.filter((j,k,l)=>t[k]>y).map(j=>j.split` `[0]).join()}

So che è piuttosto lungo e attualmente all'ultimo posto con un discreto margine, ma è quello che ho potuto inventare.

f=i=>p=>{n=i.split`
`,a=new Date(0,0,0,...n[0].split` `[1].split`:`),y=new Date(0,0,0,...p.split`:`),t=[a];w=a;n.slice(1).map((j,k,l)=>{h=l[k].split` `[1]*6e4;t.push(new Date(w.getTime()+h));w=new Date(w.getTime()+h)});return n.filter((j,k,l)=>t[k]>y).map(j=>j.split` `[0]).join()}

console.log(f(`Kevin 13:02
Ruby 5
Sam 3
Lisa 6
Bob 12
`)('13:15'))


2

C # , 269 267 byte


golfed

(l,t)=>{var h=System.DateTime.MinValue;var s=System.DateTime.ParseExact(t,"HH:mm",null);var o="";foreach(var p in l.Split('\n')){var i=p.Split(' ');h=h.Ticks<1?System.DateTime.ParseExact(i[1],"HH:mm",null):h.AddMinutes(int.Parse(i[1]));if(h>s)o+=i[0]+" ";}return o;};

Ungolfed

( l, t ) => {
   var h = System.DateTime.MinValue;
   var s = System.DateTime.ParseExact( t, "HH:mm", null );
   var o = "";

   foreach( var p in l.Split( '\n' ) ) {
      var i = p.Split( ' ' );

      h = h.Ticks < 1
         ? System.DateTime.ParseExact( i[ 1 ], "HH:mm", null )
         : h.AddMinutes( int.Parse( i[ 1 ] ) );

      if( h > s )
         o += i[ 0 ] + " ";
   }

   return o;
};

Leggibile non golfato

( l, t ) => {
   // var to check the time of arrival
   var h = System.DateTime.MinValue;

   // var to store the start time of the party
   var s = System.DateTime.ParseExact( t, "HH:mm", null );

   // var with the names of those who arrived late
   var o = "";

   // Cycle through which line
   foreach( var p in l.Split( '\n' ) ) {
      // Split the name and time
      var i = p.Split( ' ' );

      // Check if the time of arrival still has the initial value
      h = h.Ticks < 1

         // If so, grab the time of the first person
         //   Expects to have a time format of 'hh:mm'
         ? System.DateTime.ParseExact( i[ 1 ], "HH:mm", null )

         // Otherwise, add the difference to the var
         : h.AddMinutes( int.Parse( i[ 1 ] ) );

      // Check if the current time is later than the party start time
      if( h > s )

         // If so, add the name to the list
         o += i[ 0 ] + " ";
   }

   // Return the names of the persons who arrived late
   return o;
};

Codice completo

using System;
using System.Collections.Generic;

namespace Namespace {
   class Program {
      static void Main( String[] args ) {
         Func<String, String, String> f = ( l, t ) => {
            var h = System.DateTime.MinValue;
            var s = System.DateTime.ParseExact( t, "HH:mm", null );
            var o = "";

            foreach( var p in l.Split( '\n' ) ) {
               var i = p.Split( ' ' );

               h = h.Ticks < 1
                  ? System.DateTime.ParseExact( i[ 1 ], "HH:mm", null )
                  : h.AddMinutes( int.Parse( i[ 1 ] ) );

               if( h > s )
                  o += i[ 0 ] + " ";
            }

            return o;
         };

         List<KeyValuePair<String, String>>
            testCases = new List<KeyValuePair<String, String>> {
               new KeyValuePair<String, String>(
                  "Kevin 13:02\nRuby 5\nSam 3\nLisa 6\nBob 12",
                  "13:15"
               ),
               new KeyValuePair<String, String>(
                  "Kevin 13:15\nRuby 5\nSam 3\nLisa 6\nBob 12",
                  "13:15"
               ),
            };

         foreach( KeyValuePair<String, String> testCase in testCases ) {
            Console.WriteLine( $" Input:\n{testCase.Key}\n\n{testCase.Value}\n\nOutput:\n{f( testCase.Key, testCase.Value )}\n" );
         }

         Console.ReadLine();
      }
   }
}

Uscite

  • v1.1 - - 2 bytes- Grazie a VisualMelon
  • v1.0 - 269 bytes- Soluzione iniziale.

Appunti

  • Formato di output: genera i nomi separati da spazi

È possibile salvare alcuni byte aggiungendo una using D=System.DateTime;direttiva (non dimenticare di sostituire la vars!). Dovresti davvero fornire tipi per i parametri lambda per rendere questo codice completamente inequivocabile (es (string l,string f).). Penso anche che ci sia un piccolo bug, è necessario h>spiuttosto che h>=s(1 byte di risparmio!) Come da "(Chiunque sia puntuale, va bene.)". Si può fare h.Ticks<1? Potresti trovare un nullable DateTimepiù economico dell'uso DateTime.Min, ma non ho verificato tutte le implicazioni qui. Con la clausola using, ==D.Mindovrebbe funzionare anche.
VisualMelon,

A proposito dell'uso dubito che potrei ancora tirare fuori un'espressione lambda con esso. Sono abbastanza sicuro di non poterlo aggiungere a metà codice . I tipi lambda espliciti sono un'altra cosa che non ho visto le persone farlo, e ci sono andato - se è illegale , dillo, ma anche le mod non hanno detto nulla, forse va bene ?. h>sLo farò. h.Ticks<1e anche questo.
auhmaan,

Sono fiducioso che lo permettiamo usingse con tali lambda, non riesco a trovare nulla che lo dica esplicitamente su meta, ma questa domanda suggerisce fortemente che è permesso. Vi è un ragionevole consenso sul fatto che dovrebbero essere richiesti tipi di parametri espliciti (aggiungerei che sono fermamente a favore). A proposito, le mod sono lì per mantenere le cose civili dalla prospettiva di SE, non per far rispettare le regole di PPCG.
VisualMelon,

Sono un po 'contrario a usings, soprattutto perché riterrei che richiederebbe un codice completo, quindi sto dicendo che dubito di poter eseguire una funzione come soluzione - forse aggiungendo due blocchi, uno per se l' usingaltro per funzione lambda? Per quanto riguarda il consenso, penso che l'aggiunta dei dispersi Func<...> f = ...;lo risolverebbe, anche se dovrebbe essere specificato il nome completoSystem.Func<...> f = ...;
auhmaan,

Potrebbe essere meglio avere solo una funzione ben definita (si aggiunge solo string scon la sintassi C # 7 (6? Non ricordo) se preferisci non mescolare lambda e usi.
VisualMelon,

2

CJam , 43 41 byte

q~':/60b:Y;Sf/()':/60b+a\+{)iT+:TY>{;}|}%

Provalo online!

Spiegazione

q~        e# Read and eval all input.

':/       e# Split the start time on colons.
60b       e# Convert the result from base 60, to get the start time in minutes.
:Y;       e# Store this time in variable Y, and discard it from the stack.

Sf/       e# Split each string in the guest list on spaces.
(         e# Pull out the first guest from the list.
)         e# Pull out the time from the guest.
':/60b+   e# Convert the time to a number of minutes (same way as before), then add it back
          e#   to the guest.
a\+       e# Add the guest back to the start of the guest list.

          e# At this point, the first guest has his/her arrival time in minutes, and everyone
          e#  else still has their original number.

{         e# Apply this block to each guest:
 )i       e#  Pull out the number and cast it to an integer.
 T+       e#  Add the value of variable T to it (T is initially 0).
 :T       e#  Store the result back into T.
 Y>{;}|   e#  If the resulting number of minutes is not after the start time, delete the 
          e#    guest's name.
}%        e# (end of block)

          e# Implicit output.

2

Lua, 211 206 byte

Il primo codegolf dell'anno per me dovrebbe essere ancora golfabile.

Modifica: 5 byte salvati usando una scorciatoia per string.match

function f(l,T)m=T.match
r=function(X)return
m(X,"^%d+")*3600+60*m(X,"%d+$")end
T=r(T)z={}y=0
for i=1,#l do
h=m(l[i],"%d.*")h=i>1 and y+h*60or r(h)y=h
z[#z+1]=h>T and m(l[i],"%u%l*")or nil
end return z end

spiegazioni

function f(l,T)                         -- declare the function f(list,partyTime)
  r=function(X)                         -- declare a function r that convert hh:mm in seconds
    return X:match("^%d+")*3600         -- return the sum of seconds the hours
          +60*X:match("%d+$")           -- and in the seconds
  end                                   
  T=r(T)                                -- convert the partyTime in seconds
  z={}                                  -- create the shameList for late partygoers
  y=0                                   -- y will keep us updated on the second count
  for i=1,#l                            -- iterate over l
  do                                    
    h=l[i]:match("%d.*")                -- h is a shorthand for the time of arrival
    h=i>1                               -- if we're on the second line at least
        and y+h*60                      -- update h with the time of arrival in second
      or r(h)                           -- else use r()(for the first partygoer only)
    y=h                                 -- update our reference for adding time
    z[#z+1]=h>T                         -- if the last partygoer was late
                and l[i]:match("%u%l*") -- add its name to the shameList
              or nil                    -- else, don't do anything
  end                                   
  return z                              -- return the shameList
end                                 

se vuoi provare questo codice, puoi usare il seguente frammento

function f(l,T)r=function(X)return
X:match("^%d+")*3600+60*X:match("%d+$")end
T=r(T)z={}y=0
for i=1,#l do
h=l[i]:match("%d.*")h=i>1 and y+h*60or r(h)y=h
z[#z+1]=h>T and l[i]:match("%u%l*")or nil
end return z end

retour = f({"Kevin 13:02","Ruby 5","Sam 3","Lisa 6","Bob 12"},"13:15")
for i=1,#retour
do
  print(retour[i])
end

2

Java, 346 304 284 275 byte

  • -9 byte, grazie a @KevinCruijssen
void g(int m,String[]n,String[]a,int M){for(int i=0;i<n.length;i++)if((M+=i>0?p(a[i]):0)>m)System.out.print(n[i]);}
int p(String n){return new Short(n);}
int h(String t){return p(t.split(":")[0])*60+p(t.split(":")[1]);}
void f(String[]n,String[]a,String b){g(h(b),n,a,h(a[0]));}

Live dettagliato

public static void g(int m, String[] n, String[] a, int M)
{
    for(int i = 0; i < n.length; i++)
    {
        if((M += i>0 ? p(a[i]) : 0) > m)
        {
            System.out.println(n[i]);
        }
    } 
}

public static int p(String n)
{
    return Integer.parseInt(n);
}

public static int h(String t)
{
    return p(t.split(":")[0])*60+p(t.split(":")[1]);
}

public static void f(String[] n, String[] a, String b)
{
    g(h(b),n,a,h(a[0]));
}

1
Nice golf (per Java.) Hai bisogno di spazio tra String[] n,e String[] a?
programmatore

@ programmer5000 no, ho anche rimosso le variabili delle ore e le ho accumulate in minuti.
Khaled.K,

1
È possibile sostituire Integer.parseInt(n)con new Short(n). E sulla base delle osservazioni della sfida, LisaBobè anche un'uscita valida, in modo da poter cambiare l' printlna print.
Kevin Cruijssen,

1

Lotto, 163 byte

@set/pp=
@set/ap=%p::=*60+%
:l
@set g=
@set/pg=
@if "%g%"=="" exit/b
@set t=%g:* =%
@set/ap-=%t::=*60+%
@for %%g in (%g%)do @(if %p% lss 0 echo %%g)&goto l

Accetta input su STDIN. La prima riga è l'ora di inizio della festa, quindi l'elenco degli ospiti. Usa il trucco di @Arnauld per convertire l'hh: mm in minuti.

L'input preferito di Batch per questo sarebbe come una serie di parametri della riga di comando (a partire dall'ora del party, quindi da ogni guest e time come argomenti separati). Ciò richiederebbe solo 129 byte:

@set p=%1
@set/ap=%p::=*60+%
:l
@set t=%3
@set/ap-=%t::=*60+%
@if %p% lss 0 echo %2
@shift
@shift
@if not "%2"=="" goto l

1

Groovy, 121 byte

{g,t->y={Date.parse('hh:mm',it)};u=y(t);d=y(g.remove(0)[1]);g.find{z=it[1];use(groovy.time.TimeCategory){d+z.minutes}>u}}

1

PowerShell, 170 160 byte

select-string '(?m)^((\w*) )?((\d\d):)?(\d?\d)$'-a|% matches|%{,$_.groups[2,4,5].value}|%{}{$b+=($c=60*$_[1]+$_[2]);$a+=,@{n=$_[0];t=$b}}{$a|? n|? t -gt $c|% n}

Provalo online!


Meglio tardi che mai!
programmatore

Sono a riposo oggi, quindi ho un po 'di tempo per divertirmi un po'
Andrei Odegov,
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.