バイナリクロック
Posted feedbacks - C#
結構素直な方法と思います。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | class Program
{
static void Main(string[] args)
{
DateTime now = DateTime.Now;
byte hours = (byte)now.Hour;
byte minutes = (byte)now.Minute;
StringBuilder uh = new StringBuilder();
StringBuilder lh = new StringBuilder();
StringBuilder um = new StringBuilder();
StringBuilder lm = new StringBuilder();
for (byte i = 0; i < 8; i++)
{
byte mask = (byte)(1 << (7 - i));
if ((hours & mask) != 0)
{
uh.Append("■");
lh.Append("□");
}
else
{
uh.Append("□");
lh.Append("■");
}
if ((minutes & mask) != 0)
{
um.Append("■");
lm.Append("□");
}
else
{
um.Append("□");
lm.Append("■");
}
}
Console.Write(uh);
Console.WriteLine(um);
Console.Write(lh);
Console.WriteLine(lm);
Console.WriteLine(now);
}
|
LINQを使ってワンライナー的な処理を書いてみました。「Select( binary =>」の部分まで一行にしてしまうと、かえって読みにくくなると判断したのでこの程度で。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
Console.WriteLine(new DateTime(2009, 7, 8, 20, 18, 0));
Console.WriteLine(BinaryClock.Convert(new DateTime(2009, 7, 8, 20, 18, 0)));
Console.ReadLine();
}
}
public class BinaryClock
{
public static string Convert(DateTime dateTime)
{
return string.Join(Environment.NewLine, new int[] { dateTime.Hour, dateTime.Minute }
.Select(num => System.Convert.ToString(num, 2)).Select(binary =>
{
return new string(binary.ToCharArray().Select(c => c == '0' ? '□' : '■').ToArray()).PadLeft(6, ' ');
}).ToArray());
}
}
//2009/07/08 20:18:00
// ■□■□□
// ■□□■□
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | using System;
using System.Linq;
namespace ConsoleApplication {
class Program {
static void Main(string[] args) {
// 現在の時刻を表示する
BinaryClock bc = new BinaryClock();
Console.WriteLine(bc.ToString());
// 指定した時刻を表示する
DateTime dt = new DateTime(2009, 1, 1, 20, 18, 0);
Console.WriteLine(bc.ToString(dt));
Console.ReadLine();
}
}
public class BinaryClock {
private static string ToBinString(int num, int width) {
string format = string.Format("{{0,{0}}}", width);
string s = String.Format(format,
System.Convert.ToString(num, 2));
return s.Aggregate("", (t, c) => t + (c == '1' ? '■' : '□'));
}
public string ToString(DateTime dateTime) {
return " " + ToBinString(dateTime.Hour, 5) + "\n" +
ToBinString(dateTime.Minute, 6);
}
public override string ToString() {
return ToString(DateTime.Now);
}
}
}
|



lunlumo #9282() [ Ruby ] Rating6/8=0.75
20:18の場合,例えば以下の様な出力をするイメージです。
出力例:
■□■□□
□■□□■□
see: Binary Clock Widget
Rating6/8=0.75-0+
[ reply ]