일반적인 1부터 12까지 아라비아 숫자가 적혀있는 시계가 있습니다.
이 시계는 오전 12:00 정각에 작동하기 시작하여 하루동안 움직이게 되어있습니다.
이 때 시침과 분침이 직각이 될 때의 시간을 hh:mm 형태로 나타내고 하루동안 직각이 된 총 횟수를 구해보세요!
- 09:00
- 15:00
...
Total: n번!
시간표현은 오전, 오후가 아닌 24시 방식으로 써주세요!
48개의 풀이가 있습니다.
#!/usr/bin/env python
#-*- coding: utf-8 -*-
'''
시침은 하루에 2회전, 분침은 하루에 24회전 한다.
같은 방향으로 회전하므로 시침에 대한 분침의 "상대적인" 회전수는
하루에 24-2 = 22회전이다.
시침과 분침이 직각을 이루는 경우는 분침이 시침에 대해 다음과 같은 회전수를
했을 경우이다.
1/4, 3/4, 1+1/4, 1+3/4, ... , 21+1/4 , 21+3/4
따라서 하루에 총 44번 직각을 이룬다는 것을 알 수 있다.
위의 수열을 일반항으로 표현하면
(2n-1)/4 (1<=n<=44)이다.
상대적인 1회전에 걸리는 시간은 24/22 = 12/11 시간이고,
위의 일반항에 12/11을 곱하면 24시간중 직각을 이루는 시간의 일반항이 나온다.
즉,
3(2n-1)/11 (1<=n<=44)
위의 결과값은 시간이므로 프로그램에서는 이를 시간과 분으로 적절히 변환해서
표현하면 되겠다.
예) 3.25시 -> 3:15
'''
for n in range(1, 45):
h=(6*n-3)/11.0
m = (h-int(h))*60
print "%02d:%02d"%(h,m)
print "Total:44번!"
Python 3.4.2 각속도 개념이해가 필요합니다. 위키피디아-각속도를 참조하세요.
각속도란 변화시간내에 몇도나 돌아갔나를 나타내는 개념입니다. 속도의 거리가 각도로 바뀌어 있다고 생각하면 쉽습니다.
즉, 속도 = 거리/시간 이듯이 각속도 = 각도/시간 입니다.
아시다시피 분침은 시침보다 빨리 돕니다. 즉 분침이 시침보다 각속도가 빠릅니다. (흡사 거북이와 토끼)
그리고 분침과 시침의 속도는 모두 등속도입니다. (가속도가 아닙니다. 매우 중요)
얼마나 빠를까요? 하루를 기준으로 생각해봅시다. 그럼 0시 시침과 분침이 같은 출발선에 서 있다가 뛰기 시작한다면
하루에 분침은 24바퀴를 돕니다. 시침은 두바퀴를 돌죠. 즉, 분침각속도 = 24바퀴/하루, 시침각속도 = 2바퀴/하루 입니다.
즉, 0시에서 다음날 0시가 되는, 하루라는 동일한 기준시점에 분침은 시침보다 22바퀴를 더 앞서 달리고 있는 겁니다. 이해가시죠?
그럼 차근차근 0시부터 생각해보면,
출발선에서 "땅"하고 시작하면 분침은 휭~하고 앞서 달리기 시작합니다.
(1) 그러다 어느 시각에 분침이 시침을 1/4바퀴 앞섭니다. 즉, 1/4 * 바퀴(360도) = 90도 를 앞섭니다.
자 계속 달립니다. 분침은 계속 시침과 간격을 벌립니다.
(2) 그러다 어느 시각에 분침이 시침을 3/4바퀴 앞섭니다. 즉, 3/4 * 바퀴(360도) = 270도 를 앞섭니다.
자 이제는 분침은 이미 한바퀴를 돌았습니다. 그리고 시침을 재쳐버립니다. 그리고서
(3) 그러다 어느 시각에 분침이 시침을 한바퀴와 1/4바퀴 앞섭니다. 즉, 5/4(1 과 1/4) * 바퀴(360도) = 450도 를 앞섭니다.
(4) 그리고 더 달려가서 분침은 시침을 1 과 3/4 바퀴 즉, 7/4 * 바퀴(360도) = 630도 앞서죠
.
.
이렇게 계속 달리면 결국 분침은 계속 앞서 나가게 되고 다음날 0시가 되는 시점에 22바퀴를 앞서게 된다고 했으니 그전에는
(44) 마지막으로 어느 시각에 분침이 시침을 21바퀴와 3/4바퀴 앞섭니다.
즉, 분침이 한바퀴를 앞서갈때마다 2번 직각을 이루고 총 44번 직각을 이룹니다.
이해가시나요? 그럼, 이제 단위를 바꿔 봅시다.
어느 시각이라고 했으니 시간단위로 바꿉니다.
분침각속도 = 24바퀴/하루 = 24*360도/24시간 = 360 도/시간
시침각속도 = 2바퀴/하루 = 2*360도/24시간 = 30 도/시간
T1 에 1/4 * 360도 앞서고
T2 에 3/4 * 360도 앞서고
T3 에 5/4 * 360도 앞서고
T4 에 7/4 * 360도 앞서고
.
.
Tn 에 (2n-1)/4 * 360 도 를 앞서게 됩니다. 맞죠? 이로서 앞서는 직각도 수열의 일반공식입니다.
각속도 = 각도/시간 이라고 했으니 각도 = 각속도*시간 입니다. 그리고 시간 = 각도/각속도 입니다.
그런데 어느 시각에 라고 했으니 시간은 동일합니다.
그렇다면 분침각도 - 시침각도 = 직각도의 일반공식 이란 얘기고,
이건 (분침각속도 - 시침각속도)*직각을 이루는 시간 = 직각도의 일반공식 이며
따라서 직각을 이루는 시간 = 직각도의 일반공식/(분침각속도 - 시침각속도) 입니다. (여기까지 이해하셨나요?)
대입해봅니다.
(360 도/시간 - 30 도/시간)Tn = (2n-1)/4 * 360도
Tn = (2n-1)/4 * 360/330
= (2n-1)/4 * 12/11
= 3*(2n-1) / 11
라는 직각을 이루는 시간의 일반공식이 나옵니다 여기다가 1<= n <=44 를 integer 를 대입하면 됩니다.
m_turn = 24 # 분침 하루에 도는 바퀴
h_turn = 2 # 시침 하루에 도는 바퀴
times_right = (m_turn - h_turn) * 2 # 한시간에 2번 직각을 이룰때 하루에 모두 몇번?
print("{} times".format(times_right))
for i in range(1, times_right+1):
hour = (3*(2*i-1))/11.0 # 만나는 시간을 floating 으로
min = (hour - int(hour)) * 60 # 소숫점부분만 분단위로
print("%2d:%02d"%(hour,min)) # **:** 단위로 출력
hr_angle= 0
count=0
for h in range(24):
min_angle=0
if hr_angle>=360-1.0/12.0: hr_angle = 0
for m in range(360):
angle=abs(min_angle-hr_angle)
if angle>=90.0-0.42 and angle<=90.42 or angle>=270.0-0.42 and angle<=270.42:
print "%0.2d:%0.2d"%(h,m/6); count+=1
min_angle += 1
hr_angle += 1.0/12.0
print "Total: %d times!"%count
``````출력결과입니다.
00:16
00:49
01:21
01:54
02:27
03:00
03:32
04:05
04:38
05:10
05:43
06:16
06:49
07:21
07:54
08:27
09:00
09:32
10:05
10:38
11:10
11:43
12:16
12:49
13:21
13:54
14:27
15:00
15:32
16:05
16:38
17:10
17:43
18:16
18:49
19:21
19:54
20:27
21:00
21:32
22:05
22:38
23:10
23:43
Total: 44 times!
시침과 분침이 겹쳐있는 상태에서 다음 겹친 상태로 가는데는 720/11 분이 걸리고, 그 사이에 두 번의 직각이 되는 시점이 있습니다. (180/11, 540/11) 하루는 1440분이니 시침과 분침이 겹치는 시점은 총 22회 있고, 따라서 44회의 직각이 있을 수 있습니다.
따라서 초항이 180/11, 공차가 360/11 인 등차수열로 해당 시점의 분을 구할 수 있고, 분단위의 시간을 00시00분 포맷으로 표시해주면 됩니다.
from fractions import Fraction
def format_time(p):
return "{:02d}:{:02d}".format(*divmod(int(p), 60))
a1 = Fraction(180, 11)
k = Fraction(360, 11)
for i in range(44):
print(format_time(a1 + k * i))
결과는 다음과 같습니다.
00:16
00:49
01:21
01:54
02:27
03:00
03:32
04:05
04:38
05:10
05:43
06:16
06:49
07:21
07:54
08:27
09:00
09:32
10:05
10:38
11:10
11:43
12:16
12:49
13:21
13:54
14:27
15:00
15:32
16:05
16:38
17:10
17:43
18:16
18:49
19:21
19:54
20:27
21:00
21:32
22:05
22:38
23:10
23:43
python입니다.
from fractions import Fraction
from math import floor
total = 0
for i in range(90, 7920, 180):
total += 1
minute = Fraction(i*2, 11)
hour = floor(Fraction(i, 330))
print(hour, '시', minute-60*hour, '분')
print('총', total, '번')
0시를 기준으로 시침과 분침이 회전한 각도의 차이를 A라 합시다. 그러면 시침과 분침이 직각일 때 A의 값으로 가능한 것은
가 됩니다. A를 5.5로 나누면 0시를 기준으로 몇 분인지 구할 수 있습니다.
여기선 분수 표현을 위해 fractions 모듈을 사용했습니다.
def Clock ( i, j ):
print ("" if i>9 else "0") + str(i) + ":" + ("" if j>9 else "0") + str(j)
su = 0
bfr = 0
for i in range(24) :
for j in range (60) :
a = abs ( (i if (i<12) else (i-12)) * 5 * 6 + 30 * j / 60 - j * 6 )
if a > 180 : a = 360 - a
if ( a >= 90 and bfr < 90 ) or ( a <= 90 and bfr > 90 ) :
Clock( i, j )
su += 1
bfr = a
print "Total: %d times!"%su
void exce92()
{
int hh = 0, mm = 0;
int dgr = 0;
int count = 0;
for (int i = 0; i < 720; i++)
{
mm += 2;
if (mm == 60)
{
mm = 0;
hh++;
}
dgr = (dgr + 11) % 360;
if (dgr == 90 || dgr == 270)
{
count++;
printf("%d. %02d:%02d\n", count,hh, mm);
}
}
printf("총 %d번 90도가 됩니다.\n", count);
}
매 분마다 체크를 하니까 생각보다 90도가 되는 횟수가 적네요..
res = filter(lambda x : abs((30*(x[0]%12) + 1/2*x[1]) - 6*x[1]) == 90,[ (x,y) for x in range(0,24) for y in range(0,60) ])
for x, y in res :
print '%02d:%02d' % (x,y)
print "total : %d" % len(res)
한줄코드 도전!
제 시계는 분단위로 움직입니다 또각 또각
oneDayMunite = 24*60; # 하루 총 분의 양
h = 0
ma = 0
ha = 0
m = 0
result =[];
for i in range(0,oneDayMunite+1):
#시간 증가
if(m > 0 and m%60 == 0):
ma = 0 #시간이 지나면 분침각도는 0
m = 0 #시간이 지나면 0분부터~
h = h+1 #시간증가
if(h == 12): #12시가 되면은 각도가 0
ha = 0
#결과 넣기
if(abs(ma-ha) == 90 or abs(ma-ha) == 270):
result.append(str(h).zfill(2) +":"+ str(m).zfill(2))
#결과확인용 debug
print( str(abs(ma-ha)) + " " + str(h) +":"+ str(m) + " ha:"+str(ha) +" ma:"+ str(ma) )
ma = ma+6 #분침은 6도 씩 증가
ha = ha+0.5 #시침은 0.5도 씩 증가
m = m+1 #1분증가
for x in result:
print(x)
print("총 " + str(len(result)) + "번 !")
1분 이동시 분침 이동각도 = 6 1분 이동시 시침 이동각도 = 0.5 1시간 이동시 시침 이동각도 = 30
90 또는 270도가 될때마다 카운트 증가
result = 0
for hour in range(0, 24) :
for min in range(0, 60) :
h_degree = ((hour * 30) + (min * 0.5)) % 360
m_degree = min * 6
gap = abs(h_degree - m_degree)
if gap == 90 or gap == 270 :
print(hour , min, sep=" : ")
result += 1
print("total " , result)
C#
int count = 0;
for(int i = 0; i <= 23; i++)
{
for(int j = 0; j <= 59; j++) {
double angleHour = ((360d / (12d * 60d)) * (i * 60d + j)) % 360d;
double angleMinute = (360d / 60d * (i * 60d + j)) % 360d;
double abs = Math.Abs(angleHour - angleMinute);
if (abs == 90d || abs == 270d)
{
count++;
Console.WriteLine("{0:d4} {1:d2}:{2:d2}", count, i, j);
}
}
}
Console.WriteLine("Total: {0}번!", count);
결과값 : 0001 03:00 0002 09:00 0003 15:00 0004 21:00 Total: 4번!
이게 분단위라 정확히 90도는 4번 밖에 안 나오네요.
static void Main(string[] args)
{
int count = 0;
for (int h = 1; h < 24; h++)
{
for(int s = 0; s < 60;s++)
{
double hangle = ((h>12?h-12:h)*30)+s*0.5;
int mangle = s==0?360:s*6;
Console.WriteLine("{0} : {1} 시침각도 {2} 분침각도 {3}", h<=9?"0"+h.ToString():h.ToString(), s<=9?"0"+s.ToString():s.ToString(),hangle,mangle);
if(Math.Abs(hangle-mangle) == 90||Math.Abs(hangle -mangle)== 270)
{
count++;
}
}
}
Console.WriteLine("직각인된 횟수 {0}", count);
}
from fractions import Fraction
import math
si = 0.0
bun = 0.0
transition = 2 * math.pi / 360
counter = 0
for i in range(25):
for j in range(60):
for k in range(60):
si = si + 0.5/60
bun = bun + 0.1
if round(si,1) - round(bun,1) == 90 or round(bun,1) - round(si,1) == 90 or round(si,1) - round(bun,1) == 270 or round(bun,1) - round(si,1) == 270:
zero =''
zero2 =''
if i<10 : zero = '0'
if j<10 : zero2 = '0'
print("%s%d:%s%d" % (zero,i ,zero2, j))
counter = counter + 1
bun = 0
print('Total: %d번!'% counter)
파이썬 2.7
def append_result():
result.append('{}:{}'.format(hour, min))
result.append('{}:{}'.format(hour, (min+30)%60))
result = []
for hour in range(24):
for min in range(60):
if hour < 12 :
if hour >=9:
rec = hour*5 + 15 - min - 60 # 시:분, 9:00, 10:5, 11:10
if rec == 0:
append_result()
else:
rec = hour*5 + 15 - min # 시:분, 0:15, 1:20, 2:25, 3:30
if rec == 0:
append_result()
else:
if hour >= 21 :
rec = (hour-12)*5 + 15 - min - 60 # 시:분, 0:15, 1:20, 2:25, 3:30
if rec == 0:
append_result()
else:
rec = (hour-12)*5 + 15 - min # 시:분, 0:15, 1:20, 2:25, 3:30
if rec == 0:
append_result()
print result; print
print '총 개수: ', len(result)
결과:
['0:15', '0:45', '1:20', '1:50', '2:25', '2:55', '3:30', '3:0', '4:35', '4:5', '5:40', '5:10', '6:45', '6:15', '7:50', '7:20', '8:55', '8:25', '9:0', '9:30', '10:5', '10:35', '11:10', '11:40', '12:15', '12:45', '13:20', '13:50', '14:25', '14:55', '15:30', '15:0', '16:35', '16:5', '17:40', '17:10', '18:45', '18:15', '19:50', '19:20', '20:55', '20:25', '21:0', '21:30', '22:5', '22:35', '23:10', '23:40']
총 개수: 48
** 코드가 거지같네요.. **
#include <stdio.h>
#include <math.h>
int main(void){
int h,m,i=1;
double ha=-0.5,ma;
for(h=0;h<12;h++){
for(m=0;m<60;m++){
ma=m*6.0;
ha+=0.5;
if((fabs(ha-ma)==90)||(fabs(ha-ma)==270)){
printf("%d. %02d:%02d\n",i,h,m);
i++;
printf("%d. %02d:%02d\n",i,h+12,m);
i++;
}
}
}
printf("Total=%d\n",i-1);
}
출력결과: 1. 03:00 2. 15:00 3. 09:00 4. 21:00 Total=4 원래 4번 나오는게 맞는건가요???
lst = []
result = []
for i in range(86401):
if round((11.0/120.0)*float(i), 0)%180 == 90:
lst.append("%d:%d" % (i//3600, (i//60)%60))
lst = list(set(lst))
print lst
print len(lst)
1초 단위로 움직입니다. 분 단위로 움직이면 4번밖에 안나와서....
import math
m = h = math.pi/2;
previous = [0,0,1]; now = [0,0,1]; result = []
for x in range(24):
for y in range(60):
h = math.pi*(1/2-(x/6+y/360)); m = math.pi*(1/2-y/30)
now = [x,y,math.cos(h-m)]
if previous[2] * now[2] <= 0:result.append(now[:2] if x in list(3*k for k in range(8)) else previous[:2])
previous = now
for x, y in result:print(str(x)+':'+str(y))
44개네요. 삼각함수로 이전값*현재값<=0 이면 추가. 파이썬 3.5.1
#파이썬3.5.1
'''
시침과 분침이 직각이 되는 경우는 시침이 분침 앞에 있을때 경우와 분침이 시침 앞에 있을때 경우가 있다.
(여기서 몇도을 움직인다는 것은 12시를 기준, 시계방향으로이다. 앞에 있다는 것도 시계방향으로이다.)
또, 오전 오후 두가지 경우가 있으므로 1시부터 12시까지만 생각한다.
그리고,
1시간동안 시침은 30도, 분침은 360도
1분동안 시침은 0.5도, 분침은 6도
움직인다.
h시 m분이고(1<=h<=12,0<=m<=59) 시침이 분침 앞에 있을때
시침이 움직인 각도는 30*h+0.5*m도
분침이 움직인 각도는 6*m도
30*h+0.5m - 6*m = 90
30*h - 90 = 5.5*m
m = 300/55 * h - 900/55
=60/11 * h - 180/11
분침이 시침 앞에 있을때
6*m - (30*h+0.5*m) = 90
5.5*m = 90+30*h
m = 60/11 * h + 180/11
(h의 단위는 '시', m의 단위는 '분'이다;'도'가 아니다)
m과 h와의 관계를 알아냈으니, 이를 토대로 코드를 짠다.
'''
from fractions import *
#그냥 실수로 나누어 실행해보았더니 중복될것이 중복이 안되어 분수형태로 해보았다
#이에따라 출력형식도 조금 변형하였다
times = []
for h in range(0,12):
mm = Fraction(60*h,11)-Fraction(180,11)
if mm < 0:
hh = h - 1
if h > 0:
t1 = (hh, mm+60)
else:
t1 = (hh+12, mm+60)
else:
t1 = (h, mm)
mp = Fraction(60*h,11)+Fraction(180,11)
if mp >= 60:
hh = h + 1
if hh < 12:
t3 = (hh, mp-60)
else:
t3 = (hh-12, mp-60)
else:
t3 = (h, mp)
t2 = (t1[0]+12, t1[1])
t4 = (t3[0]+12, t3[1])
times.extend([t1,t2,t3,t4])
times = sorted(list(set(times)))
for t in times:
print(str(t[0])+'시 '+str(t[1])+'분')
print('Total :', len(times), 'times!')
출력:
0시 180/11분
0시 540/11분
1시 240/11분
1시 600/11분
2시 300/11분
3시 0분
3시 360/11분
4시 60/11분
4시 420/11분
5시 120/11분
5시 480/11분
6시 180/11분
6시 540/11분
7시 240/11분
7시 600/11분
8시 300/11분
9시 0분
9시 360/11분
10시 60/11분
10시 420/11분
11시 120/11분
11시 480/11분
12시 180/11분
12시 540/11분
13시 240/11분
13시 600/11분
14시 300/11분
15시 0분
15시 360/11분
16시 60/11분
16시 420/11분
17시 120/11분
17시 480/11분
18시 180/11분
18시 540/11분
19시 240/11분
19시 600/11분
20시 300/11분
21시 0분
21시 360/11분
22시 60/11분
22시 420/11분
23시 120/11분
23시 480/11분
Total : 44 times!
C#으로 작성했습니다. 1분에 시침은 0.5도, 분침은 6도 움직이는 것으로 4번 나옵니다. 1초로 계산하게 되면, 3으로 나눠떨어지지 않기 때문에 round를 써야 하는데 정확한 90도가 아니기 때문에 넘겼습니다.
public int CountRightAngles()
{
var count = 0;
var hour = 0m;
var minute = 0m;
for (int i = 0; i < 12; i++)
{
for (int j = 0; j < 60; j++)
{
minute += 6.0m;
hour += 0.5m;
if (Math.Abs(hour - minute) == 90)
count++;
}
minute = 0m;
if (Math.Abs(hour - minute) == 90)
count++;
}
return count*2;
}
Ruby
rtime = ->n { h=(6*n-3)/11.0; m=(h-h.to_i)*60; "%2d. %02d:%02d" %[n,h,m] }
out_rt = proc { puts (1..44).map(&rtime), "Total: 44번!"}
or
rtime = ->n { h=(6*n-3)/11.0; m=(h-h.to_i)*60; "%2d. %02d:%02d" %[n,h,m] }
times = ->n=0,r=[] { r << rtime[n+=1] until rtime[n+1][4,2]> '23'; r }
out_rt = ->r=times[] { puts r, "Total: #{r.size}번!"}
Test
expect(rtime[1] ).to eq " 1. 00:16"
expect(rtime[44]).to eq "44. 23:43"
#=> stdout test
rt_outs = " 1. 00:16\n 2. 00:49\n 3. 01:21\n 4. 01:54\n 5. 02:27\n 6. 03:00\n"+
" 7. 03:32\n 8. 04:05\n 9. 04:38\n10. 05:10\n11. 05:43\n12. 06:16\n"+
"13. 06:49\n14. 07:21\n15. 07:54\n16. 08:27\n17. 09:00\n18. 09:32\n"+
"19. 10:05\n20. 10:38\n21. 11:10\n22. 11:43\n23. 12:16\n24. 12:49\n"+
"25. 13:21\n26. 13:54\n27. 14:27\n28. 15:00\n29. 15:32\n30. 16:05\n"+
"31. 16:38\n32. 17:10\n33. 17:43\n34. 18:16\n35. 18:49\n36. 19:21\n"+
"37. 19:54\n38. 20:27\n39. 21:00\n40. 21:32\n41. 22:05\n42. 22:38\n"+
"43. 23:10\n44. 23:43\nTotal: 44번!\n"
expect { out_rt[] }.to output(rt_outs).to_stdout
Java로 구현하였습니다.
public class Clock90Deg {
public static void main(String[] args) {
int count = 0;
for (int i = 0; i < 24; i++) {
int hour = i % 12;
int min = (int)((30 * hour - 90) / 5.5);
if ((min >= 0) && (min <= 60))
{
System.out.print(String.format("%02d", i) + ":" + String.format("%02d", min));
System.out.println();
count++;
}
min = (int)((30 * hour + 90) / 5.5);
if ((min >= 0) && (min <= 60)) {
System.out.print(String.format("%02d", i) + ":" + String.format("%02d", min));
System.out.println();
count++;
}
}
System.out.println("Total: " + String.valueOf(count) + "번!");
}
}
hour시 min분에 직각이 될 때는 |30 * hour + 0.5 * hour - 6 * min| = 90이 성립한다는 점에서 착안하여 풀었습니다.
C언어 입니다. 저는 그냥 반복문돌렸습니다.. 접근법은 시침이 1번이동할때 분침은 12번 이동한다 이구요 ㅎㅎ.. 그래서 횟수는 48회나오고 8시 59분이 직각으로나오고, 9시 00도 직각으로나오네요 ㅡㅜ
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<malloc.h>
int main()
{
int j = 0;
int i = 0;
int count = 0;
for (int k = 0; k < 2; k++)
{
for (i = 0; i < 60; i++)
{
for (int c = 0; c < 12; c++)
{
if ((60 + j + c - i) % 60 == 15)
{
printf("%d : %d \n", (i / 5) + k * 12, j + c);
count++;
}
if ((60 + i - j - c) % 60 == 15)
{
printf("%d : %d \n", (i / 5) + k * 12, j + c);
count++;
}
}
j += 12;
j = j % 60;
}
}
printf("횟수 : %d ", count);
}
자바 로 코딩
1분에 시침 과 분침이 직각이 되는 수는 2번
12시 부터 24시 까지 1440 번이 나오네요
이거 맞나요?ㅎㅎ
1. calendar 생성
2. Calendar.SECOND 증가
public static void main(String[] args){
// 변수 초기화
int checkSecondTime_1 = 0;
int checkSecondTime_2 = 0;
String endTimeCheck = "";
int minute = 0;
int second = 0;
int secondCnt = 0;
int totalCnt = 0;
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY , 0);
cal.set(Calendar.MINUTE , 0);
cal.set(Calendar.SECOND , 0);
try{
do{
minute = cal.get(Calendar.MINUTE);
second = cal.get(Calendar.SECOND);
if( second == 0 ){
checkSecondTime_1 = minute + 15;
checkSecondTime_2 = minute + 45;
}
if( checkSecondTime_1 == second || checkSecondTime_2 == second){
System.out.println( new SimpleDateFormat("hh:mm:ss").format(cal.getTime()) );
totalCnt++;
}
// SECOND 카운트
cal.add(Calendar.SECOND, ++secondCnt);
secondCnt = 0;
endTimeCheck = new SimpleDateFormat("HHmmss").format(cal.getTime());
}while( !"000000".equals(endTimeCheck) );
System.out.println("총 횟수 :: ==> " + totalCnt);
}catch(Exception e){
e.printStackTrace();
}
}
c언어 활용
#include<stdio.h>
int main(void)
{
int i, time;
int index=0;
int time_array[50];
for(i=1; ; i+=2)
{
time=90*i/5.5;
if(time>1440)
{
break;
}
else
{
time_array[index]=time;
index++;
}
}
for(i=0; i<index; i++)
{
printf("%02d:%02d \n", time_array[i]/60, time_array[i]%60);
}
printf("total %d times \n", index);
return 0;
}
%02d는 정수형을 출력할 때 되도록 2자릿수로 맞추고, 빈 공간은 0으로 채워넣으라는 의미입니다(ex: 5->05) 출력결과는 다음과 같습니다(숫자 색깔 다르게 나오는건 무시하세요)
00:16
00:49
01:21
01:54
02:27
03:00
03:32
04:05
04:38
05:10
05:43
06:16
06:49
07:21
07:54
08:27
09:00
09:32
10:05
10:38
11:10
11:43
12:16
12:49
13:21
13:54
14:27
15:00
15:32
16:05
16:38
17:10
17:43
18:16
18:49
19:21
19:54
20:27
21:00
21:32
22:05
22:38
23:10
23:43
total 44 times
package test003;
public class RightAngle {
private Integer count = 0;
private boolean seeLeft = true;
protected void printTime(Integer hour, Integer minute) {
System.out.println(String.format("%02d", hour) + ":" + String.format("%02d", minute));
}
protected Integer getCount() {
return count;
}
protected void loop() {
int maxHour = 24;
int maxMinute = 60;
for (int hour = 0; hour < maxHour; hour++) {
for (int minute = 0; minute < maxMinute; minute++) {
isItRightAngle(hour, minute);
}
}
System.out.println("Total:" + getCount() + "번");
}
protected void isItRightAngle(Integer hour, Integer minute) {
double hourPosition = (double) (((hour % 12) * 60 + minute)) / 720;
double minutePostion = (double) minute / 60;
double distance = minutePostion - hourPosition;
if (distance <= 0) {
distance = minutePostion + 1 - hourPosition;
}
if (seeLeft == true & distance >= 0.25 & distance < 0.5) {
if (distance == 0.25) {
printTime(hour, minute);
} else {
printTime(hour, minute - 1);
}
count++;
seeLeft = false;
} else if (seeLeft == false & distance >= 0.75) {
if (distance == 0.75) {
printTime(hour, minute);
} else {
printTime(hour, minute - 1);
}
count++;
seeLeft = true;
}
}
public static void main(String[] args) {
new RightAngle().loop();
}
}
00:16 00:49 01:21 01:54 02:27 03:00 03:32 04:05 04:38 05:10 05:43 06:16 06:49 07:21 07:54 08:27 09:00 09:32 10:05 10:38 11:10 11:43 12:16 12:49 13:21 13:54 14:27 15:00 15:32 16:05 16:38 17:10 17:43 18:16 18:49 19:21 19:54 20:27 21:00 21:32 22:05 22:38 23:10 23:43 Total:44번
d_h = 360.0 / 12.0 / 60.0 # 시침이 1분에 움직이는 각도 0.5
d_m = 360.0 / 1.0 / 60.0 # 분침이 1분에 움직이는 각도 6
m_h = 0
m_m = 0
total = 0
for m in range(0, (24 * 60)):
if m != 0:
m_h = (m_h + d_h) % 360
m_m = (m_m + d_m) % 360
#시침은 6도씩 움직인다고 가정함(분침이 1분에 움직이는 각도, 시계의 한 눈금)
mm_h = m_h - (m_h % 6)
if abs(mm_h - m_m) == 90 or abs(mm_h - m_m) == 270:
total+=1
print('{:>2}. {:0>2}:{:0>2}'.format(total, m // 60, m % 60))
print('Total:{}번!'.format(total))
Python 3.5.2에서 작성하였습니다.
시침이 시계 한눈금(6도)씩 움직인다고 가정해서 48번이 나왔습니다.
hour, count = 11, 0
for x in range(24):
hour += 1
if hour == 25:
hour = 1
_h = (12 % hour * 30) % 180
for y in range(60):
_m = (y * 6) % 180
if abs(_h - _m) == 90:
count += 1
print('%d. %02d:%02d' % (count, hour, y))
print('Total: %d번!' % count)
#### 2017.01.23 D-395 ####
시침 고정되어있을때
_h, count = -0.5, 1
for x in range(12,37):
for y in range(60):
_h = (_h + 0.5) % 180
_m = y * 6 % 180
if abs(_h - _m) == 90:
print('%d. %02d:%02d' % (count, x%24, y))
count += 1
#### 2017.01.24 D-394 ####
시침이동할때.
def clock():
k=1
for i in range(24):
for j in range(60):
n=i*30+j*0.5
m=j*6
#print(abs(n-m)%180)
if abs(abs(n-m)%180-90)<2.75:
print("%d. %0.2d:%0.2d" %(k,i,j))
k+=1
print("총 %d번" %k )
clock()
public class HourMinute {
public static void main(String[] args) {
int c = 0;
for (Double i = 0D; i <= 60 * 24; i++) {
Double h = (i * 0.5);
Double m = (i * 6) % 360;
Double hm = Math.abs(h - m) % 360;
if (hm == 90 || hm == 270) {
System.out.printf("%02d:%02d \n", h.intValue() / 30, m.intValue());
c++;
}
}
System.out.println(c);
}
}
애매하네요...
hr=-1
a=0
for i in range(24):
for k in range(1,60):
if k in [1,12,24,36,48]:
hr=hr+1
if hr==60:
hr=0
if k==60:
k=0
result=abs(k-hr)
if result==15 or result==45:
a=a+1
print("{0}:{1}--{2}".format(i,k,a))
답이 정확하게 맞는지는 모르겠습니다. 시침을 분침과 같이 놓고 뺏을때 절대값이 15와 45가 나오는 것에서 답을 추론하였습니다. 그리고 시침을 5로 나눠서 출력하였습니다.
public class Rightangle{
public static void main(String[] args){
int mcount=0;
int hcount=0;
int right=0;
int rcount=0;
String memo="";
for(int i=1;i<=120;i++){
for(int j=0;j<12;j++){
mcount+=1;
if((Math.abs(mcount-hcount)==15) || (Math.abs(mcount-hcount)==45)){
right++;
int hour = hcount/5;
if(hour/10==0){
String temp = "0"+hour;
memo=memo+temp+":"+mcount+"\n";
rcount++;
}
else{
memo=memo+hour+":"+mcount+"\n";
rcount++;
}
}
}
hcount+=1;
if(mcount==60)
mcount=0;
}
System.out.print(memo);
System.out.println("갯수는"+rcount);
}
}
Python 3으로 작성해 보았습니다. Python에서 클래스 연습하려고 클래스로 만들었습니다. 전 총 4번만 나오네요. 다른 경우는 float방식에서 1도 이하의 오차가 발생하여 정확하게 90도가 되는 시간이 없는 것 같아요 ㅠㅠ 맞는지 한번만 봐주세요~
답: 3:0 (90.0) 9:0 (270.0) 15:0 (90.0) 21:0 (270.0)
코드:
class hourAndMinDegree:
currentHour = 0
currentMin = 0
hourDegree = float(360/12)
hourMinDegree = float(hourDegree/60)
minDegree = float(360/60)
def increaseTime(self):
self.currentMin += 1
if self.currentMin == 60:
self.currentHour += 1
self.currentMin = 0
if self.currentHour == 24:
self.currentHour = 0
def calculateDegree(self, degree):
while True:
self.increaseTime()
currentHourDegree = self.hourDegree * self.currentHour + self.hourMinDegree * self.currentMin if self.currentHour < 12 else self.hourDegree * (self.currentHour - 12) + self.hourMinDegree * self.currentMin
currentMinDegree = self.minDegree * self.currentMin
degreeDiff = currentMinDegree - currentHourDegree if currentMinDegree > currentHourDegree else currentHourDegree - currentMinDegree
if degreeDiff == degree or degreeDiff == (360-degree):
print(str(self.currentHour) + ':' + str(self.currentMin) + " (" + str(degreeDiff) + ") ")
if self.currentHour == 0 and self.currentMin == 0:
break
if __name__ == "__main__":
timerCal = hourAndMinDegree()
timerCal.calculateDegree(90)
초단위로 계산해보았습니다.
초단위로 하면 90도/270도가 딱 맞는 시간은 3시, 9시, 15시, 21시밖에 없지요.
그래서 이전 각도와 지금 각도의 차를 가지고
89->90, 90->89, 269->270, 270->269 넘어갈 때만 출력하도록 하였습니다.
지저분해졌지만, 그래도 44번이 나오긴 하는군요 ^^
javascript
var minAngle = function(sec) {
return (sec / 10) % 360;
};
var hourAngle = function(sec) {
return (sec / 120) % 360;
}
var getTime = function(sec) {
return `${("0" + parseInt(sec / 3600)).slice(-2)}:${("0" + parseInt((sec % 3600) / 60)).slice(-2)}`;
}
var count = 0;
var now = 0;
var prev = 0;
for (let i = 0; i < 86400; i++) {
now = Math.abs(hourAngle(i) - minAngle(i));
// 이전각을 기억하여 89-90/269-270 변할 때를 체크
if ((parseInt(prev) === 89 && parseInt(now) === 90)
|| (parseInt(prev) === 90 && parseInt(now) === 89)
|| (parseInt(prev) === 269 && parseInt(now) === 270)
|| (parseInt(prev) === 270 && parseInt(now) === 269)) {
console.log(getTime(i));
count++;
}
prev = now;
}
console.log(`${count}번`);
int main() { int j = 0; int i = 0; int count = 0; for (int k = 0; k < 2; k++) { for (i = 0; i < 60; i++) { for (int c = 0; c < 12; c++) { if ((60 + j + c - i) % 60 == 15) { printf("%d : %d \n", (i / 5) + k * 12, j + c); count++; } if ((60 + i - j - c) % 60 == 15) { printf("%d : %d \n", (i / 5) + k * 12, j + c); count++; } } j += 12; j = j % 60; }
}
printf("횟수 : %d ", count);
}
참고 많이 하고 한건데 완벽하지는 않을거에요 디버깅 해보시고 오류난거 수정하면 괜찮을거 같아요
public class ClockAngle {
public static void main(String[] args) {
int hour;
float minute;
for(int n=1; n<=44; n++) {
hour = (3*(2*n-1))/11;
minute = (((3*(2*(float)n-1))/11)%1)*60;
System.out.println(hour + " : " + (int)minute);
}
System.out.println("total: 44번!");
}
}
def angle(h, m):
h = h if h < 12 else h - 12 ## 24h -> 12h
am = 360 * m / 60 ## angle of hour
ah = 360 * h / 12 + am / 12 ## angle of minuite
ang = abs(am-ah) ## angle btw hour and minute
ang = ang if ang <= 180 else 360-ang ## normalize angle under 180
return ang
tmp = (0, 0, 0)
cnt = 0
for h in range(24):
for m in range(60):
if (90 - tmp[2]) * (90 - angle(h, m)) < 0: ## if cross over 90
cnt += 1 ## increase cnt
print('%2d. %02d:%02d' %(cnt, tmp[0], tmp[1])) ## print time
tmp = (h, m, angle(h, m))
print('Total: %d번!' %cnt)
파이썬 3.6
아이디어>
time,hour,h_angle,m_angle,watch_angle,count,t = '',0,0,0,0,0,0
timelist =[]
for i in range(3):
for h in range(10):
if i == 2 and h > 3:
break
for m in range(6):
for n in range(10):
time = str(i)+str(h)+':'+str(m)+str(n)
hour = int(str(i)+str(h))
m_angle = int(str(m)+str(n))
if 0 < m_angle <=10:
h_angle = hour * 5
elif 10 < m_angle <= 20:
h_angle = hour * 5 + m
elif 20 < m_angle <= 30:
h_angle = hour * 5 + m
elif 30 < m_angle <= 40:
h_angle = hour * 5 + m
elif 40 < m_angle <= 50:
h_angle = hour * 5 + m
else:
h_angle = hour * 5 + m
if h_angle > 60:
h_angle = h_angle - 60
watch_angle = h_angle - m_angle
timelist.append([time,h_angle,m_angle,watch_angle])
if abs(watch_angle) == 15 or abs(watch_angle) == 45:
if int(timelist[t][1])-int(timelist[t-1][1]) >= int(timelist[t][2])-int(timelist[t-1][2]) and timelist[t-1][3] == timelist[t][3]:
pass
else:
count += 1
print("%d 번째:"%count,time)
t += 1
print("\n""Total : %d번! "%count)
1 번째: 00:16
2 번째: 00:49
3 번째: 01:22
4 번째: 01:55
5 번째: 02:27
6 번째: 03:00
7 번째: 03:33
8 번째: 04:05
9 번째: 04:38
10 번째: 05:10
11 번째: 05:44
12 번째: 06:16
13 번째: 06:49
14 번째: 07:22
15 번째: 07:55
16 번째: 08:27
17 번째: 09:00
18 번째: 09:33
19 번째: 10:05
20 번째: 10:38
21 번째: 11:10
22 번째: 11:44
23 번째: 12:16
24 번째: 12:49
25 번째: 13:22
26 번째: 13:55
27 번째: 14:27
28 번째: 15:00
29 번째: 15:33
30 번째: 16:05
31 번째: 16:38
32 번째: 17:10
33 번째: 17:44
34 번째: 18:16
35 번째: 18:49
36 번째: 19:22
37 번째: 19:55
38 번째: 20:27
39 번째: 21:00
40 번째: 21:33
41 번째: 22:05
42 번째: 22:38
43 번째: 23:10
44 번째: 23:44
Total : 44번!
분침과 시침의 속도 차이는 1시간에 330도 입니다.
90도, 270도, 450도, .... (180*n-90)도 에서 직각이 됩니다.
따라서 (180n-90)/33060분에 직각입니다.
1시간은 60분으로 나누어 몫은 시간 hh, 나머지는 분mm 입니다.
# 파이썬
for m in range(1, 45):
minute = (180*m-90)/330*60
hh = int(minute // 60)
mm = int(minute % 60)
print(str(m) + ". " + str(hh)+":"+str(mm))
def clock():
a = list()
for i in range(24*60):
if (abs(55*i-900)%3600 < abs(55*(i+1)-900)%3600 and abs(55*i-900)%3600< abs(55*(i-1)-900)%3600) or (abs(55*i-2700)%3600 < abs(55*(i+1)-2700)%3600 and abs(55*i-2700)%3600 < abs(55*(i-1)-2700)%3600):
a.append("{0:02d}:{1:02d}".format(i//60, i%60))
return a, len(a)
print(clock())
ans_list=['03:00','09:00','15:00','21:00']
for hour in range(0,24):
temp_hour_angle=(hour%12)*30
if 270>=temp_hour_angle>90:
for min in range(0,60):
if 84.5<temp_hour_angle-5.5*min<90 or -95.5<temp_hour_angle-5.5*min<-90:
if min<10 and hour<10:
ans_list.append('0'+str(hour)+":"+"0"+str(min-1))
elif min<10 and hour>=10:
ans_list.append(str(hour)+":"+"0"+str(min-1))
elif min>=10 and hour<10:
ans_list.append('0'+str(hour)+":"+str(min-1))
else:
ans_list.append(str(hour)+':'+str(min-1))
elif temp_hour_angle<=90:
for min in range(0,60):
if -90<temp_hour_angle-5.5*min<-84.5 or -270<temp_hour_angle-5.5*min<-264.5:
if min<10 and hour<10:
ans_list.append('0'+str(hour)+":"+"0"+str(min))
elif min<10 and hour>=10:
ans_list.append(str(hour)+":"+"0"+str(min))
elif min>=10 and hour<10:
ans_list.append('0'+str(hour)+":"+str(min))
else:
ans_list.append(str(hour)+':'+str(min))
elif temp_hour_angle>270:
for min in range(0,60):
if 84.5<temp_hour_angle-5.5*min<90 or 265.5<temp_hour_angle-5.5*min<270:
if min<10 and hour<10:
ans_list.append('0'+str(hour)+":"+"0"+str(min-1))
elif min<10 and hour>=10:
ans_list.append(str(hour)+":"+"0"+str(min-1))
elif min>=10 and hour<10:
ans_list.append('0'+str(hour)+":"+str(min-1))
else:
ans_list.append(str(hour)+':'+str(min-1))
ans_list.sort()
for ans in ans_list:
print(ans)
print(len(ans_list))
import java.text.*;
public class Main {
public static void main(String[] args) {
double time=0;
int n=1;
while(true) {
time=(3*(2*n-1))/11;
if(time>24.0) {
break;
}
n++;
int hours=(int)time;
int minutes=(int)((time-((int)time))*60);
System.out.println(hours+":"+minutes);
}
System.out.println(n-1);//1부터 시작하므로.
}
}
public class Main {
public static void main(String[] args) {
int count = 0, h = 0, m = 0;
while (h != 24) {
if (++m == 60) {
m = 0;
h++;
}
double angle = Math.abs(m * 6 - ((h >= 12 ? h - 12 : h) * 30 + m * 0.5));
if ((angle <= 90 && angle > 84.5) || (angle <= 270 && angle > 264.5)) {
count++;
System.out.println(String.format("%02d:%02d", h, m));
}
}
System.out.println(count);
}
}
mv,hv = 6,0.5
r = []
for i in range(1441):
t = (mv*i - hv*i)%360
for j in (90,270):
if t > j and oldt <= j: r.append(i-1)
oldt = t
print('total:',len(r))
for i in r:
print('{:02}:{:02}'.format(i//60,i%60))
시침:30도/시간, 분침:360도/시간
자정에서 h시간 (0.0 <= h < 24.0)이 지났을 때,
시침과 분침의 각도차는
(360 - 30)h = 330h
이다. 따라서
330h % 360=90 또는 330h % 360=270
=> 330h=360n+90 또는 330h=360n+270, n = 0,1,2,...
=> h=(360n+90)/330 또는 (360n+270)/330, n=0,1,2...
를 만족하는 h의 집합 H를 구하면 된다. h의 범위에 위 식을 대입하면
0.0<=h<24.0
=> 0.0<=(360n+90)/330<24.0 또는 0.0<=(360n+270)/330<24.0
=> -0.25<=n<21.75 또는 -0.75<=n<21.25
=> 0<=n<=21
그러므로
H = {h | h=(360n+90)/330 또는 h=(360n+270)/330, n = 0,1,...,21}
중1 수준 수학인데 왜케 어렵지... T.T
H = {(360*n+90)/330 for n in range(22)} | {(360*n+270)/330 for n in range(22)}
for h in sorted(H):
hh, mm = int(h), int((h-int(h))*60)
print('{:02d}:{:02d}'.format(hh, mm))
print('총', len(H), '번')
#하루동안 시침과 분침의 각이 직각이 된 횟수
hour=0;minute=0;second=0;count=0;counts=0
k=[90,270,450,630]
for hour in range(0,24):
for minute in range(0,60):
for second in range(0,60):
angle_m=minute*6+0.1*second
angle_h=minute*0.5+hour*30+second/120
angle=angle_h-angle_m
if abs(round(angle)) in k:#각도오차:+-0.5
count+=1
print(hour,':',minute)
break#각 시각(hh:mm)당 1회만 출력
print('total:{}회'.format(count))
Python 3
ang_diff가 다음의 조건을 만족하는 경우를 출력함 90˚ - delta < ang_diff < 90˚ + delta or 270˚ - delta < ang_diff < 270˚ + deltadelta = 6˚ / 2def main():
count = 0
for hh in range(24):
for mm in range(60):
if is_right_angle(hh, mm):
print(f"{hh:0>2}:{mm:0>2}")
count += 1
print(count)
def is_right_angle(hh, mm):
hh_ang = ((60 * hh + mm) * 0.5) % 360
mm_ang = 6 * mm
ang_diff = hh_ang - mm_ang
if ang_diff < 0:
ang_diff += 360
delta = 3
chk1 = 90 - delta < ang_diff < 90 + delta
chk2 = 270 - delta < ang_diff < 270 + delta
return chk1 or chk2
if __name__ == "__main__":
main()