Liste todos os horários do dia a uma taxa de meia hora

31

A resposta mais curta vence.

Ele deve ser classificado e em 24 horas. A linha final não possui vírgula.

A saída deve ser a seguinte:

'00:00',
'00:30',
'01:00',
'01:30',
'02:00',
'02:30',
'03:00',
'03:30',
'04:00',
'04:30',
'05:00',
'05:30',
'06:00',
'06:30',
'07:00',
'07:30',
'08:00',
'08:30',
'09:00',
'09:30',
'10:00',
'10:30',
'11:00',
'11:30',
'12:00',
'12:30',
'13:00',
'13:30',
'14:00',
'14:30',
'15:00',
'15:30',
'16:00',
'16:30',
'17:00',
'17:30',
'18:00',
'18:30',
'19:00',
'19:30',
'20:00',
'20:30',
'21:00',
'21:30',
'22:00',
'22:30',
'23:00',
'23:30'
Espen Schulstad
fonte
6
São 24 horas? Você poderia fornecer toda a saída?
xnor
1
A saída deve ser classificada?
orlp
44
E se o programa demorar 23,5 horas para ser executado?
Tfitzger
9
Não vejo por que isso seria negativo.
Espen Schulstad
6
Apenas uma pequena sugestão sobre votos positivos. Tento aprovar todas as respostas válidas para um desafio que criei como uma pequena recompensa por fazer o esforço. Tenho bastante reputação e realmente não preciso de um voto positivo aqui, mas considere outros respondentes que podem desistir de responder se suas respostas forem ignoradas após muita reflexão e depuração.
Logic Knight

Respostas:

17

Pitão, 26 bytes

Pjbm%"'%02d:%s0',"d*U24"03

Demonstração.

Começamos com o produto cartesiano de range(24)( U24) com a string "03".

Em seguida, mapeamos esses valores para a substituição de formatação de string apropriada ( m%"'%02d:%s0',"d).

Em seguida, as cadeias resultantes são unidas no caractere de nova linha ( jb).

Finalmente, removemos a vírgula à direita ( P) e imprimimos.

isaacg
fonte
1
Parece que temos um novo candidato ao prêmio. Autor de pyth, que é quase enganando;)
Espen Schulstad
15

Befunge-93, 63 bytes

0>"'",:2/:55+/.55+%.":",:2%3*v
 ^,+55,","<_@#-*86:+1,"'".0. <

 

animation (animação feita com BefunExec )

Mikescher
fonte
14

Bash: 58 47 46 caracteres

h=`echo \'{00..23}:{0,3}0\'`
echo "${h// /,
}"
homem a trabalhar
fonte
Eu gosto desta solução :)
Espen Schulstad
1
Usuário anônimo sugerido echo \'{00..23}:{0,3}0\'|sed 's/ /,\n/g'de 40 caracteres. Agradável. Obrigado. Mas eu prefiro fazer uso da bashprópria força.
manatwork
1
printf "'%s',\n" {00..23}:{0,3}0
Izabera 9/05
@manatwork oh Eu não li a pergunta bem, desculpe ...
izabera
printf "'%s'\n" {00..23}:{0,3}0|sed $\!s/$/,/ é 45 bytes
izabera
10

CJam, 31 30 29 bytes

24,[U3]m*"'%02d:%d0',
"fe%~7<

Isso é bem simples, usando a formatação printf:

24,                              e# get the array 0..23
   [U3]                          e# put array [0 3] on stack
       m*                        e# do a cartesian product between 0..23 and [0 3] array
                                 e# now we have tuples like [[0 0], [0 3] ... ] etc
         "'%02d:%d0',
"fe%                             e# this is standard printf formatting. What we do here is
                                 e# is that we format each tuple on this string
    ~7<                          e# unwrap and remove comma and new line from last line
                                 e# by taking only first 7 characters

Experimente online aqui

Optimizer
fonte
Parece que isso vai levar o ouro. Vamos dar até amanhã;)
Espen Schulstad
@EspenSchulstad Eu gostaria que realmente me desse um pouco de ouro. sigh
Optimizer
3
Remember, it's not only viritual gold, but also honor. What we do in life echoes in eternity.
Espen Schulstad
10

Python 2, 58 56 bytes

for i in range(48):print"'%02d:%s0',"[:57-i]%(i/2,i%2*3)

Like sentiao's answer but using a for loop, with slicing to remove the comma. Thanks to @grc for knocking off two bytes.

Sp3000
fonte
Would this work: "'%02d:%s0',"[:57-i]
grc
@grc Ahaha of course, that's much better
Sp3000
Better than I could do!
Tim
6

Java - 119 bytes

I started with Java 8's StringJoiner, but that means including an import statement, so I decided to do it the old way:

void f(){String s="";for(int i=0;i<24;)s+=s.format(",\n'%02d:00',\n'%02d:30'",i,i++);System.out.print(s.substring(2));}

Perhaps this can be improved by getting rid of the multiple occuring String and System keywords.

Sander
fonte
a version in groovy perhaps :)
Espen Schulstad
You can shorten this to 159: Remove the space before a, move the i increment, lose the for braces, and move the comma/newline to the beginning (which lets you use the shorter substring and get rid of length()). Since functions are allowed by default, you can get make it even shorter by eliminating boilerplate: void f(){String s="";for(int i=0;i<24;)s+=String.format(",\n'%02d:00',\n'%02d:30'",i,i++);System.out.print(s.substring(2));} Even a bit more if you make it just return the string instead of printing it, but that seems to go against the spirit, if not the letter.
Geobits
Damn, that's brilliant! I got to keep those tricks in mind, thanks!
Sander
Oh, another few: change String.format to s.format. Your compiler/IDE may complain about it, but it works ;)
Geobits
1
Nice one! format's a static method, so it should be accessed by its class, but indeed, using it this way also works!
Sander
5

Ruby, 94 61 56 51

$><<(0..47).map{|i|"'%02d:%02d'"%[i/2,i%2*30]}*",
"

Thanks to @blutorange (again) for his help in golfing!

rorlork
fonte
You can reduce that to 61 bytes: puts (0..47).to_a.map{|h|"'%02d:%02d'"%[h/2,h%2*30]}.join"," (there's a newline after the last comma)
blutorange
Thank you again! I really didn't try it much...
rorlork
Ruby needs some love. 58 bytes ;) puts Array.new(48){|i|"'%02d:%02d'"%[i/2,i%2*30]}.join','
blutorange
@blutorange @rcrmn you can reduce 4 more bytes (and get to my solution below :)) ) by replacing .join with * :)
Tomáš Dundáček
5

Perl, 52 50 48 45B

$,=",
";say map<\\'$_:{0,3}0\\'>,"00".."23"

With help from ThisSuitIsBlackNot :)

alexander-brett
fonte
4

JAVA 95 94 bytes

I love the fact that printf exists in Java:

void p(){for(int i=0;i<24;)System.out.printf("'%02d:00',\n'%02d:30'%c\n", i,i++,(i<24)?44:0);}

Ungolfed

void p(){
    for(int i=0;i<24;)
        System.out.printf("'%02d:00',\n'%02d:30'%c\n", i,i++,(i<24)?44:0);
}

EDIT Replaced the ',' with 44

tfitzger
fonte
24.times{printf("'%02d:00',\n'%02d:30'%c\n",it,it,(it<24)?44:0)}​ in groovy :) same solution, just that it's down to 65 chr
Espen Schulstad
@EspenSchulstad Would that be considered a standalone function, or is there other boilerplate that would be needed to get it to run?
tfitzger
1
If you have groovy, you could either run that in groovysh or just as a groovy script in a .groovy-file. then you don't need no function.
Espen Schulstad
@EspenSchulstad Interesting. I've only done minimal work with Groovy.
tfitzger
4

Pyth, 32 31 bytes

I golfed something in python but it turned out to be exactly the same as Sp3000's answer. So I decided to give Pyth a try:

V48<%"'%02d:%d0',",/N2*3%N2-54N

It's a exact translation of Sp3000 answer:

for i in range(48):print"'%02d:%d0',"[:57-i]%(i/2,i%2*3)

It's my first go at Pyth, so please do enlighten me about that 1 byte saving.

Def
fonte
Nicely done, and welcome to Pyth.
isaacg
3

PHP, 109 bytes

foreach(new DatePeriod("R47/2015-05-07T00:00:00Z/PT30M")as$d)$a[]=$d->format("'H:i'");echo implode(",\n",$a);
nickb
fonte
3

Ruby, 54 51 bytes

puts (0..23).map{|h|"'#{h}:00',
'#{h}:30'"}.join",
"
golgappa
fonte
1
You can reduce 3 bytes by changing \n to actual newlines and removing the space between join and ". On the other hand, take note that the specified output has leading zeros for the hours.
rorlork
Also, some more bytes by changing puts to $><< (without space) and .join with *. You still have the leading zero problem for the hours, though.
rorlork
3

C, 116,115,101,100,95,74,73, 71

May be able to scrape a few more bytes off this...

main(a){for(;++a<50;)printf("'%02d:%d0'%s",a/2-1,a%2*3,a<49?",\n":"");}
Joshpbarron
fonte
You can save 3 bytes by creating a function rather than a complete program. Just replace "main" with "f", or whatever your favourite letter is.
Bijan
Oh thats a very nice suggestion.....one I always forget!
Joshpbarron
3

T-SQL, 319 307 305 bytes

WITH t AS(SELECT t.f FROM(VALUES(0),(1),(2),(3),(4))t(f)),i AS(SELECT i=row_number()OVER(ORDER BY u.f,v.f)-1FROM t u CROSS APPLY t v),h AS(SELECT i,h=right('0'+cast(i AS VARCHAR(2)),2)FROM i WHERE i<24)SELECT''''+h+':'+m+CASE WHEN i=23AND m='30'THEN''ELSE','END FROM(VALUES('00'),('30'))m(m) CROSS APPLY h

Un-golfed version:

WITH
t AS(
    SELECT
        t.f
    FROM(VALUES
         (0),(1),(2),(3),(4)
    )t(f)
),
i AS(
    SELECT
        i = row_number() OVER(ORDER BY u.f,v.f) - 1
    FROM t u 
    CROSS APPLY t v
),
h AS(
    SELECT
        i,
        h = right('0'+cast(i AS VARCHAR(2)),2)
    FROM i
    WHERE i<24
)
SELECT
    '''' + h + ':' + m + CASE WHEN i=23 AND m='30' 
                              THEN '' 
                              ELSE ',' 
                         END
FROM(
    VALUES('00'),('30')
)m(m)
CROSS APPLY h
Pieter Geerkens
fonte
2

Pyth, 34 bytes

j+\,bmjk[\'?kgd20Z/d2\:*3%d2Z\')48

This can definitely be improved.

Try it online: Pyth Compiler/Executor

Explanation:

     m                          48   map each d in [0, 1, ..., 47] to:
        [                      )       create a list with the elements:
         \'                              "'"
           ?kgd20Z                       "" if d >= 20 else 0
                  /d2                    d / 2
                     \:                  ":"
                       *3%d2             3 * (d%2)
                            Z            0
                             \'          "'"
      jk                               join by "", the list gets converted into a string
j+\,b                                join all times by "," + "\n"
Jakube
fonte
Always impressive with these golfing languages :) I do somehow appreciate it more when it's done in a non-golfing language. Does anyone know if there is a golf-jar-lib to java for instance?
Espen Schulstad
Obligatory port of sentiao's gives 31: j+\,bm%"'%02d:%s0'",/d2*3%d2 48 with string formatting
Sp3000
2

Python 2, 69 bytes

print',\n'.join(["'%02d:%s0'"%(h,m)for h in range(24)for m in'03'])

Quite obvious, but here's an explanation:

  • using double-for-loop
  • alternating between '0' and '3' in string format is shorter than a list
  • %02d does the padding for h
  • mdoesn't need padding as the alternating character is on a fixed position
  • '\n'.join() solves the final-line requirements

I have no idea if it can be done shorter (in Python 2).

by Sp3000, 61 bytes : print',\n'.join("'%02d:%s0'"%(h/2,h%2*3)for h in range(48))

sentiao
fonte
1
How about: print',\n'.join("'%02d:%s0'"%(h/2,h%2*3)for h in range(48))
Sp3000
Brilliant, Sp3000! (you should post it)
sentiao
1
Nah, not different enough to post in my book. All I did was drop the square brackets (which are unnecessary even in your one) and drop m. (Also it's 59 bytes, not 61)
Sp3000
2

Haskell, 85 bytes

putStr$init$init$unlines$take 48['\'':w:x:':':y:"0',"|w<-"012",x<-['0'..'9'],y<-"03"]

Unfortunately printf requires a 19 byte import, so I cannot use it.

nimi
fonte
2

Julia: 65 64 61 characters

[@printf("'%02d:%d0'%s
",i/2.01,i%2*3,i<47?",":"")for i=0:47]

Julia: 64 characters

(Kept here to show Julia's nice for syntax.)

print(join([@sprintf("'%02d:%d0'",h,m*3)for m=0:1,h=0:23],",
"))
manatwork
fonte
2

Fortran 96

do i=0,46;print'(a1,i2.2,a,i2.2,a2)',"'",i/2,":",mod(i,2)*30,"',";enddo;print'(a)',"'23:30'";end

Standard abuse of types & requirement only for the final end for compiling. Sadly, due to implicit formatting, the '(a)' in the final print statement is required. Still, better than the C and C++ answers ;)

Kyle Kanos
fonte
2

JavaScript (ES6), 77 86+1 bytes

Didn't realize there had to be quotes on each line (+1 is for -p flag with node):

"'"+Array.from(Array(48),(d,i)=>(i>19?"":"0")+~~(i/2)+":"+3*(i&1)+0).join("',\n'")+"'"

old solution:

Array.from(Array(48),(d,i)=>~~(i/2).toFixed(2)+":"+3*(i&1)+"0").join(",\n")

ungolfed version (using a for loop instead of Array.from):

var a = [];
// there are 48 different times (00:00 to 23:30)
for (var i = 0; i < 48; i++) {
    a[i] =
        (i > 19 ? "" : "0") +
            // just a ternary to decide whether to pad
            // with a zero (19/2 is 9.5, so it's the last padded number)
        ~~(i/2) +
            // we want 0 to 24, not 0 to 48
        ":" +  // they all then have a colon
        3*(i&1) +
            // if i is odd, it should print 30; otherwise, print 0
        "0" // followed by the last 0
}
console.log(a.join(",\n"));
royhowie
fonte
72: Array.from(Array(48),(d,i)=>`'${i>19?"":0}${0|i/2}:${i%2*3}0'`).join`,\n`. Replace \n with an actual newline.
Mama Fun Roll
2

golflua 52 51 chars

~@n=0,47w(S.q("'%02d:%d0'%c",n/2,n%2*3,n<47&44|0))$

Using ascii 44 = , and 0 a space saves a character.

An ungolfed Lua version would be

for h=0,47 do
   print(string.format("'%02d:%d0'%c",h/2,h%2*3, if h<47 and 44 or 0))
end

The if statement is much like the ternary operator a > b ? 44 : 0.

Kyle Kanos
fonte
2

C# - 120 bytes

class P{static void Main(){for(var i=0;i<24;i++)System.Console.Write("'{0:00}:00',\n'{0:00}:30'{1}\n",i,i==23?"":",");}}
Berend
fonte
2

Python, 60 58 64 bytes

for i in range(24):print("'%02d:00,\n%02d:30'"%(i,i)+', '[i>22])

Ungolfed:

for i in range(24):
    if i <23:
        print( ('0'+str(i))[-2:] + ':00,\n' + str(i) + ':30,')
    else:
        print( ('0'+str(i))[-2:] + ':00,\n' + str(i) + ':30')

Try it online here.

Tim
fonte
1
Why not put it on 1 line, and save another 2 bytes.
isaacg
I don't think this works - no leading zero on the hour.
isaacg
1
@isaacg fixed that!
Tim
The output is not the same as in the original question.
sentiao
@sentiao what is different?
Tim
2

𝔼𝕊𝕄𝕚𝕟, 39 chars / 67 bytes (non-competing)

↺;Ḁ⧺<Ḱ;)ᵖ`'⦃Ḁ<Ḕ?0:⬯}⦃0|Ḁ/2}:⦃Ḁ%2*3}0',”

Try it here (Firefox only).

Not a single alphabetical character in sight...

Mama Fun Roll
fonte
2

PHP, 69 70 62 bytes

for($x=-1;++$x<47;)printf("'%02d:%d0',
",$x/2,$x%2*3)?>'23:30'

Try it online

Outputting '23:30' at the end is a bit lame, and so is closing the php context using ?> without opening or re-opening it. An cleaner alternative (but 65 bytes) would be:

for($x=-1;++$x<48;)printf("%s'%02d:%d0'",$x?",
":'',$x/2,$x%2*3);

Try it online

Thank you @Dennis for the tips. Alternative inspired by the contribution of @ismael-miguel.

mk8374876
fonte
1
Welcome to Programming Puzzles & Code Golf! Your code prints a null byte at the end. I'm not sure if that is allowed.
Dennis
@Dennis Thank you, you're right... I assumed PHP would see it as end-of-string. Posted a new version.
mk8374876
<?...?>'23:30' saves three bytes. Also, you can replace \n with an actual newline.
Dennis
2

Swift, 74 bytes

Updated for Swift 2/3...and with new string interpolation...

for x in 0...47{print("'\(x<20 ?"0":"")\(x/2):\(x%2*3)0'\(x<47 ?",":"")")}
GoatInTheMachine
fonte
The final line is specified to not have a comma & your code prints it.
Kyle Kanos
1

Javascript, 89 bytes

for(i=a=[];i<24;)a.push((x="'"+("0"+i++).slice(-2))+":00'",x+":30'");alert(a.join(",\n"))
SuperJedi224
fonte
1
Quick question: how many arguments Array.push() supports? ;)
manatwork
You're right. That is a polyad. Thanks, I'll make that change after I finish testing my entry for another challenge.
SuperJedi224
A few more characters can be removed with some elementary reorganizations: for(i=a=[];i<24;)a.push((x=("0"+i++).slice(-2))+":00",x+":30");alert(a.join(",\n"))
manatwork
There, I fixed it.
SuperJedi224
That reuse of variable x is quite ugly coding habit. If you change the loop control variable to something else (as in my suggestion at 2015-05-07 15:28:25Z), then you can add the opening single quotes to x's value to reduce the two "'"+ pieces to one: for(i=a=[];i<24;)a.push((x="'"+("0"+i++).slice(-2))+":00'",x+":30'");alert(a.join(",\n"))
manatwork
1

Python 2: 64 bytes

print ',\n'.join(['%02d:00,\n%02d:30'%(h,h) for h in range(24)])
Alan Hoover
fonte
The output is not the same as in the original question.
sentiao
I don't know what happened to the edit I made. here is the correct version also 64 chars: print',\n'.join("'%02d:00',\n'%02d:30'"%(h,h)for h in range(24))
Alan Hoover
1

Ruby - 52 bytes

puts (0..47).map{|i|"'%02d:%02d'"%[i/2,i%2*30]}*",
"
Tomáš Dundáček
fonte
This seems like my solution with just the change of the .join for *... It's common courtesy to instead of just posting a new answer with a minor improvement, to suggest the improvement to the original poster. See meta.codegolf.stackexchange.com/questions/75/…
rorlork
@rcrmn I agree I made a mistake and I apologize for it - should've had looked for other ruby answers first. Great work though in your answer with $><<!
Tomáš Dundáček
Don't worry about it, you are new here: I was advising you so that you could avoid this in the future.
rorlork
1

Python 2, 74 65 bytes

We generate a 2 line string for each hour, using text formatting:

print',\n'.join("'%02u:00',\n'%02u:30'"%(h,h)for h in range(24))

This code is fairly clear, but the clever indexing and integer maths in the answer by Sp3000 gives a shorter solution.

Logic Knight
fonte
1
no reason to use formatting for 00 and 30, save 9 bytes with "'%02u:00',\n'%02u:30'"%(h,h)
DenDenDo
you could save some bytes by having too loops : print',\n'.join("'%02u:%02u'"%(h,i)for h in range(24)for i in[0,30])
dieter
Thanks DenDenDo. I used this to save some bytes. Dieter, I can see where your idea may help, but I could save more bytes with that idea from DenDenDo.
Logic Knight