小数の説明


12

の形式で小数を指定する<float>, <precision>と、フロートの小数部分(つまり小数部)のグラフィック表現を描画します。例:

  1. 入力:6.75, 4、出力:

    6||| 7
     ---- 
    

    6.75(入力からの最初の数)は説明する数、4(入力からの2番目の数)はパイプの下のダッシュの数です。 6床は6.75、7天井は6.75。パイプの数はdecimal part of first input number * second input numberです。

  2. 入力:10.5, 6、出力:

    10|||   11
      ------
    
  3. 入力:20.16, 12、出力

    20||          21
      ------------
    

    .16 実際には1.92本のパイプを使いますが、1.92本のパイプを描くことができないので、2本にします。

  4. 入力:1.1, 12、出力:

    1|           2
     ------------
    

    .1 この場合は1.2パイプなので、1パイプにフロアリングされます。

  5. また、エッジケース。入力:(5, 4つまり、数値は整数です)、出力:

    5    6
     ----
    

  • 説明する数値は正の浮動小数点数であり、言語能力によってのみ制限されます。
  • 精度の数値は2より大きい偶数の整数です(つまり、必要な最小精度は4です)。任意の大きさにすることもできます。
  • > = n.5パイプはn + 1に切り上げられます(つまり、1.5は2に丸められ、2.5は3に丸められます)。<n.5パイプはnに丸められます(つまり、1.4は1に丸められ、2.4は2に丸められます)。
  • あなたの言語にとってより便利な場合は、入力を配列として取ることができます[6.75, 4]。入力を逆の順序で取得する場合、つまり[4, 6.75]、回答で指定してください。

希望する出力形式を正確に特定できますか?
-isaacg

@isaacg 4つの出力例を示しました。不明な点は何ですか?
ニカエル

いくつかのコーナーケースが明らかになっているようです。例えば、入力5.0 45to 6またはfrom 4toを描画し5ますか?入力1.25 2:0または1 |があり、その理由(つまり、丸め規則は何ですか?)入力の最初の数値は正でなければなりませんか?最大の精度と大きさは何ですか?入力の2番目の数値は正でなければなりませんか?負の場合、後方に描画しますか?
ピーターテイラー

@ピーターは明確にした。
ニカエル

丸め規則をカバーしていないと思います。
ピーターテイラー

回答:


6

CJam、32バイト

l~1md@:X*mo'|*XSe]1$)NW$s,S*'-X*

スペースで区切られた最初の精度と10進数の秒を取ります。

すべてのテストケースを実行します。

説明

l~   e# Read input and evaluate, pushing precision and decimal on the stack.
1md  e# Divmod 1, separating the decimal into integer and fractional part.
@:X  e# Pull up precision, store in X.
*mo  e# Multiply precision by fractional part and round.
'|*  e# Push that many vertical bars.
XSe] e# Pad with length X with spaces.
1$)  e# Copy integer part and increment.
N    e# Push linefeed.
W$   e# Copy integer part.
s,   e# Get number of digits as length of string representation.
S*   e# Push that many spaces, to indent the hyphens correctly.
'-X* e# Push X hyphens.

うん、うまくいくようだ。
ニカエル

4

Mathematica、119バイト

a=ToString;b=Array;a[c=Floor@#]<>{b["|"&,d=Round[#2#~Mod~1]],b[" "&,#2-d],a[c+1],"
"," "&~b~IntegerLength@c,"-"&~b~#2}&

試しました...テスト:

In[1]:= a=ToString;b=Array;f=a[c=Floor@#]<>{b["|"&,d=Round[#2#~Mod~1]],b[" "&,#2-d],a[c+1],"\n"," "&~b~IntegerLength@c,"-"&~b~#2}&;

In[2]:= f[6.75, 4]

Out[2]= 6||| 7
         ----

In[3]:= f[10.5, 6]

Out[3]= 10|||   11
          ------

In[4]:= f[20.16, 12]

Out[4]= 20||          21
          ------------

In[5]:= f[1.1, 12]

Out[5]= 1|           2
         ------------

In[6]:= f[5, 4]

Out[6]= 5    6
         ----

実用的なデモを提供してもらえますか、それとも不可能ですか?
ニカエル


3

Java、253 206 181バイト

@Kenneyのおかげで、一度使用した条件と変数をインライン化し、冗長な変数を整理することで47バイトを節約しました。

@Kenneyのおかげで、3項演算子で2つのループをインライン化することで、25バイトを節約しました。

純粋なストリング操作:

インラインループバージョン(181バイト):

String m(float f,int p){int g=(int)f,i=0;String h="",q=""+g;int c=q.length();for(;i<c+p;)h+=i++<c?" ":"-";for(i=c;i<p+c;)q+=i++<c+Math.round((f-g)*p)?"|":" ";return q+(g+1)+"\n"+h;}

4ループバージョン(206バイト):

String m(float f,int p){int g=(int)f,i=0;String h="",q=""+g;int c=q.length();for(;i++<c;)h+=" ";for(;i<=c+p;i++)h+="-";for(i=c;i<c+Math.round((f-g)*p);i++)q+="|";for(;i++<p+c;)q+=" ";return q+(g+1)+"\n"+h;}

ゴルフされていないバージョン:

String m(float f,int p){
//initialize some useful values, d is the number of pipes needed
int g=(int)f,d=Math.round((f-g)*p),i=0;
String h="",q=""+g;//append the floored value to the pipe string first
int c=q.length();
for(;i<c;i++)h+=" ";//pad hyphen string with spaces for alignment
for(++i;i<=c+p;i++)h+="-";//append hyphens
for(i=c;i<c+d;i++)q+="|";//append pipes
for(;i<p+c;i++)q+=" ";//append spaces for padding
return q+(g+1)+"\n"+h;}//concatenate the strings in order, separating the strings with a UNIX newline, and return it.

ideone.comの作業例。完全なプログラムは、STDIN入力をとして受け入れます <float>,<precision>

注:JavaのMath.round(float)ラウンドRoundingMode.HALF_UPでは、OPが必要な動作であるデフォルトを使用します。

提供されたテストケースの出力は、OPが提供したものとdiff-matchedでした。


気にしないでください!あなたは、削除するのを忘れたaあなたは210バイトで取得するために別の23を救うことができる233であなたを設定し、(使用されることはありません):交換q.length()では、b13を保存しますint g=(int)f, b=(""+g).length(), c=b, i=0;forセーブ6の条件でイテレーターをインクリメントし、インライン化d(1回使用)すると4がセーブされますint c = b; for(;i++<b;)h+=" "; for(;i++<=b+p;)h+="-"; for(i=c;i<c+Math.round((f-g)*p);i++)q+="|"; for(;i++<p+b;)q+=" ";
ケニー

また、誰かが代わりにエスケープシーケンスの実際の改行を使用して提案したが、私は、Windows上だから、CRLFだということ、2はとにかく与えられたバイト\n
Tamoghna Chowdhuryの

ニース-はい、b旧式になりました;-)次の場合でも、2番目に1バイトを保存できますfor(;i++<=c+p;)。あなたは可能性が Windows上でUNIXの改行コードでファイルを保存するが、残念ながらJavaは複数行の文字列を許可していません ...
ケニー

@ケニー、いや。やってみた ハイフンの位置がずれます。とにかく、Javaは仕事にふさわしい人ではありません。
タモグナチョードリー

forループを2つだけ使用して181バイトfor(;i<c+p;)h+=i++<c?" ":"-";for(i=c;i<p+c;)q+=i++<c+Math.round((f-g)*p)?"|":" ";
ケニー

3

ジャバスクリプトES6、105の 104バイト

(f,p)=>(i=f|0)+("|".repeat(j=(f-i)*p+.5|0)+" ".repeat(p-j))+(i+1)+(`
`+i).replace(/\d/g," ")+"-".repeat(p)

おかげで、1バイト保存されました。


申し訳ありませんが、ダッシュが出力の一部であることに気付いていませんでした。スペースを視覚化するためにダッシュがそこにあると思いました。
ニール

(f,p)=>(i=f|0)+("|"[r="repeat"](j=(f-i)*p+.5|0)+" "[r](p-j))+(i+1)+("\n"+i).replace(/\d/g," ")+"-"[r](p)
ママファンロール

そうそう、\n実際の改行に置き換えてください。そして、必ずテンプレート文字列でラップしてください。
ママファンロール

2

Haskell、113バイト

(%)=replicate.round
s=show
x!y|(n,m)<-properFraction x=[s n,(y*m)%'|',(y-y*m)%' ',s$n+1,"\n",s n>>" ",y%'-']>>=id

使用例:

*Main> putStrLn $ 20.16 ! 12
20||          21
  ------------

properFraction小数を整数部分と小数部分に分割します。出力は、単一の文字列に連結されたパーツのリスト(初期番号、バー、スペース、...)です(経由で>>=id)。


これのオンラインデモを見ることができますか?
ニカエル

@nicael:デモmain完全なプログラムのラッパー付き)。
-nimi

すべての大丈夫(:テストところでように見えます、それはより便利コンパイラだと思います)。
ニカエル

2

MATL、49バイト

2#1\tYUbiXK*Yo'|'1bX"tnKw-Z"hb1+YUhht4Y2m13*_45+c

リリース6.0.0を使用言語/コンパイラの。MatlabまたはOctaveで実行します。

チャレンジと同じ順序で数字を受け取ります。

>> matl
 > 2#1\tYUbiXK*Yo'|'1bX"tnKw-Z"hb1+YUhht4Y2m13*_45+c
 >
> 20.16
> 12
20||          21
  ------------

>> matl
 > 2#1\tYUbiXK*Yo'|'1bX"tnKw-Z"hb1+YUhht4Y2m13*_45+c
 >
> 5
> 4
5    6
 ----

説明

2#1\       % implicit input 1st number. Separate decimal and integer part
tYU        % duplicate integer part and convert to string
biXK*Yo    % input 2nd number. Copy it. Multiply by decimal part of 1st number and round
'|'1bX"    % row vector of as many '|' as needed
tnKw-Z"    % row vector of as many spaces as needed
h          % concat horiontally
b1+YUhh    % integer part of 1st number plus 1. Convert to string. Concat twice
t4Y2m      % detect numbers in this string
13*_45+c   % transform numbers into spaces, and non-numbers into '|'
           % implicitly display both strings

オンライン通訳者はいますか?
ニカエル

まだ:-( MatlabまたはOctaveで実行
ルイスメンドー

2

Perl、90バイト

print$f,"|"x($d=.5+($b=pop)*(($a=pop)-($f=0|$a))),$"x(1+$b-$d),$f+1,$/,$"x length$f,"-"x$b

入力をコマンドライン引数として期待します。ファイルに保存して(たとえば90.pl)、実行するperl 90.pl 6.75 4

コメント付き

print $f,                        # floored input (initialized below due to expr nesting)
      "|" x ($d=.5+              # rounded pipe count (`x` operator casts to int)
             +($b=pop)           # second argument  (executed first)
             *( ($a=pop)         # first argument   (executed second)
               -($f=0|$a) )      # minus floored first argument = fractional part
            ),
      $"x(1+$b-$d),              # spaces
      $f+1,                      # floored + 1
      $/,                        # newline
      $"  x length $f,           # 2nd line alignment
      "-" x $b                   # the 'ruler'

1

Stackgoat31 27バイト

CFv1%C*D'|^w1P-Y^vHXNY^w'-^

他のほとんどの回答と同様です。もっとゴルフできるかどうかを確認します。入力は、コンマ区切り、スペース区切り、またはほとんどすべての区切りが可能です。

Stackgoatはこのチャレンジの後に作られたため、競合しません

説明

CF   // Input, floored, push to stack
v1%  // Decimal part
C*   // Times second part
D    // Duplicate that result
'|^  // Repeat | by previous number
w    // Second input
1P   // Move # of |'s to the top of stack
-    // Subtract
Y^   // Repeat " " by above number
vH   // Ceil first input
X    // Newline
Z+   // Add to 
N    // Get length of first #
Y^   // Repeat by spaces
w'-  // Repeat - second input times

1

Lua、157バイト

長いが、より短い解決策が見つからない

function f(d,n)r=""a=math.floor(d)d,s=d-a,a..r for i=1,#s do r=r.." "end for i=1,n do s,r=s..(i-.5>n*d and" "or"|"),r.."-"end s=s..a+1 return s.."\n"..r end

非ゴルフ

function g(d,n)
  r=""
  a=math.floor(d)
  d,s=d-a,a..r                         -- d now contains its decimal part
  for i=1,#s do r=r.." "end            -- padding the hyphens
  for i=1,n
  do
    s,r=s..(i-.5>n*d and" "or"|"),r.."-"
    -- s is concatenated with a "|" if i-.5>n*d, a space otherwise
  end
  s=s..a+1
  return s.."\n"..r
end

luaをオンラインでテストできます。次のテストケースが役立ちます。

function f(d,n)r=""a=math.floor(d)d,s=d-a,a..r for i=1,#s do r=r.." "end for i=1,n do s,r=s..(i-.5>n*d and" "or"|"),r.."-"end s=s..a+1 return s.."\n"..r end
print(f(16.75,4))
print(f(5,4))
print(f(20.16,12))

1

C、 233 231バイト

#include <stdlib.h>
#include <math.h>
i,n,l;main(c,v)char**v;{double m;l=atol(v[2]);n=(int)(modf(atof(v[1]),&m)*l+0.5);c=printf("%.f",m);for(;i++<l;)putchar(i>n?32:'|');printf("%.f\n",m+1);printf("%*s",c,"");for(;--i;)putchar(45);}

ゴルフをしていない:

#include <stdlib.h>
#include <math.h>
i,n,l;

main(c,v)
char**v;
{
    double m;
    l=atol(v[2]); /* Get length from command line */
    n=(int)(modf(atof(v[1]),&m)*l+0.5); /* Get number of pipes and lower limit */
    c=printf("%.f",m); /* print lower limit */

    /* print pipes and spaces */
    for(;i++<l;)
            putchar(i>n?32:'|');

    /* print upper limit */
    printf("%.f\n",m+1);

    /* print spaces before dashes */
    printf("%*s",c,"");

    /* print dashes */
    for(;--i;)
            putchar(45);
}

1

Python 3、116 108バイト

def f(F,P):l=int(F);h,p=str(l+1),int((F-l)*P+.5);l=str(l);print(l+"|"*p+" "*(P-p)+h);print(" "*len(l)+"-"*P)

trinket.ioリンク

Seeqにいくつかの文字を保存していただきありがとうございます。

最初のバージョン:

def f(F,P):
 l=int(F)
 h,s,p=str(l+1)," ",int((F-l)*P+.5)
 l=str(l)
 print(l+"|"*p+s*(P-p)+h)
 print(s*len(l)+"-"*P)

ゴルフされていないバージョン:

def frac(F,P):
        low = int(F)
        high = low+1
        pipes = int((F-low)*P+.5)
        print(str(low)+"|"*pipes+" "*(P-pipes)+str(high))
        print(" "*len(str(low))+"-"*P)

実用的なデモを提供していただけますか?
ニカエル

このtrinket.ioリンクは機能するはずです:trinket.io/python/409b1488f8
ジャックブラウンスタイン

実際には、スペースリテラルを保存するよりも使用する方が少ない文字数です。すべての行をで結合することもでき;ます。h一度しか使用しないので、インライン化する必要もあります。いくつかの文字を保存する必要はありません。
Seequ

@Seeqスペースリテラルの適切なキャッチ。早い段階で、2行目の終わりに空白スペースを印刷していました。それが不要であることに気付いた後、節約のためにコードを再確認しませんでした。hトリッキーです。len最後の2行の連結と機能を機能させるにlは、文字列であるh必要があるため、に置き換える必要がありstr(int(l)+1)ます。h変換前に設定するとl、数文字が節約されます。
ジャックブラウンスタイン
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.