challenge LL Golf Hole 7 - バイト数を読みやすくする

与えられたバイト数を読みやすくしてください。読みやすくとは、いわゆる human readable な表記とします(詳しくはサンプルのコードを参考にしてください)。

与えるバイト数についてはリテラルで与える、標準入力で与える、引数で与えるなどは自由とします。

余力のあるものはこのプログラムを短くしてください。

※ LL Future実行委員の高野光弘です。この出題は LL Future公式の出題であり、優れたものについてはLL Golfのセッションでご紹介させていただくかもしれません。ご理解の上、ご投稿ください。また、LL Futureのチケットは現在も発売中です。よろしければ、メインイベントの方にもぜひご参加ください。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
b = gets.to_i
if b < 10**3
    puts b
elsif b < 10**6
    puts "%.1fk" % (b.to_f/10**3)
elsif b < 10**9
    puts "%.1fM" % (b.to_f/10**6)
elsif b < 10**12
    puts "%.1fG" % (b.to_f/10**9)
else
    puts "%.1fT" % (b.to_f/10**12)
end

Posted feedbacks - OCaml

移植しました。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
#load "nums.cma";;
open Num
let conv =
  let base = (Int 1024) in
  let rec sub byte k bound = function
    | [] -> raise (Invalid_argument "over")
    | hd::tl -> 
        if byte </ bound then
          Printf.sprintf "%.1f%s" (float_of_num (byte // k)) hd
        else
          sub byte (k */ base) (bound */ base) tl
  in
    fun byte -> sub byte (Int 1) base ["b"; "k"; "M"; "G";"T"]
  ;;
(*
  conv (Int 1024);;
  conv (Big_int (Big_int.big_int_of_string "10000000000"));; 
*)

OCamlで。

値は引数文字列, 1k = 1000, 小数点は 1 桁まで, 切捨てです。

短くして 247 bytes でした

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
let foo n =
  let u = " kMGT" in
  let l = String.length n in
  let idx = if (l mod 3) == 0 then (l / 3) - 1 else (l / 3) in
    Printf.printf "%s%s %cbytes\n"
      (String.sub n 0 (l - (idx * 3)))
      (if l > 3 then "." ^ (String.sub n (l-(idx*3)) 1) else "")
      u.[idx]
;;

(*
短く
let f n = let u = " kMGT" in let l = String.length n in let x = if (l mod 3) == 0 then (l / 3) - 1 else (l / 3) in Printf.printf "%s%s %cbytes\n" (String.sub n 0 (l - (x * 3))) (if l > 3 then "."^(String.sub n (l-(x*3)) 1) else "") u.[x];;
*)

foo "76543210";;

Index

Feed

Other

Link

Pathtraq

loading...