Liệt kê tất cả thời gian trong ngày với tốc độ nửa giờ


31

Câu trả lời ngắn nhất thắng.

Nó phải được sắp xếp, và trong 24 giờ. Dòng cuối cùng không có dấu phẩy.

Đầu ra phải như sau:

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

6
Đây có phải là 24 giờ không? Bạn có thể vui lòng cung cấp toàn bộ đầu ra?
xnor

1
Đầu ra phải được sắp xếp?
orlp

44
Điều gì xảy ra nếu chương trình của tôi mất 23,5 giờ để chạy?
tfitzger

9
Tôi không thể thấy tại sao đó là một tiêu cực.
Espen Schulstad

6
Chỉ là một gợi ý nhỏ về upvotes. Tôi cố gắng nâng cao mọi câu trả lời hợp lệ cho một thử thách mà tôi tạo ra như một phần thưởng nhỏ cho nỗ lực. Tôi có rất nhiều đại diện và không thực sự cần một upvote ở đây, nhưng vui lòng xem xét những người trả lời khác có thể từ bỏ trả lời nếu câu trả lời của họ bị bỏ qua sau nhiều suy nghĩ khó khăn và gỡ lỗi.
Logic Knight

Câu trả lời:


17

Bình thường, 26 byte

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

Trình diễn.

Chúng tôi bắt đầu với sản phẩm cartesian của range(24)( U24) với chuỗi "03".

Sau đó, chúng tôi ánh xạ các giá trị này đến sự thay thế hình thành chuỗi thích hợp ( m%"'%02d:%s0',"d).

Sau đó, các chuỗi kết quả được nối trên ký tự dòng mới ( jb).

Cuối cùng, chúng tôi xóa dấu phẩy ( P) và in.


1
Có vẻ như chúng tôi có một ứng cử viên mới cho giải thưởng. Tác giả của pyth, gần như gian lận;)
Espen Schulstad

15

Befunge-93, 63 byte

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

 

hoạt hình (hoạt hình được thực hiện với BefunExec )


14

Bash: 58 47 46 ký tự

h=`echo \'{00..23}:{0,3}0\'`
echo "${h// /,
}"

Tôi thích giải pháp này :)
Espen Schulstad

1
Người dùng ẩn danh đề xuất echo \'{00..23}:{0,3}0\'|sed 's/ /,\n/g'40 ký tự. Tốt đẹp. Cảm ơn. Nhưng tôi thích tận dụng bashsức mạnh của chính mình.
manatwork

1
printf "'%s',\n" {00..23}:{0,3}0
izabera

@manatwork oh tôi đã không đọc câu hỏi tốt, xin lỗi ...
izabera

printf "'%s'\n" {00..23}:{0,3}0|sed $\!s/$/,/ là 45 byte
izabera

10

CJam, 31 30 29 byte

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

Điều này khá dễ dàng khi sử dụng định dạng 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

Dùng thử trực tuyến tại đây


Có vẻ như điều này sẽ lấy vàng. Chúng tôi sẽ cung cấp cho đến ngày mai;)
Espen Schulstad

@EspenSchulstad Tôi ước nó thực sự sẽ cho tôi một ít vàng. thở dài
Tối ưu hóa

3
Hãy nhớ rằng, nó không chỉ là vàng, mà còn là danh dự. Những gì chúng ta làm trong cuộc sống, vang trong cõi đời đời.
Espen Schulstad

10

Python 2, 58 56 byte

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.


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.


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!


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 :)


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


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.


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);

3

Ruby, 54 51 bytes

puts (0..23).map{|h|"'#{h}:00',
'#{h}:30'"}.join",
"

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":"");}

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

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"

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


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.


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],",
"))

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 ;)


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"));

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.


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?"":",");}}

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.


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

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.


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 ?",":"")")}

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"))

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)])

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]}*",
"

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.


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
Khi sử dụng trang web của chúng tôi, bạn xác nhận rằng bạn đã đọc và hiểu Chính sách cookieChính sách bảo mật của chúng tôi.
Licensed under cc by-sa 3.0 with attribution required.