偽のローダーにしてください


29

このように偽のローダーを作成します。

パラメーター :

  • loadingこれらのいずれかを周期的に表示する(スペース)-\|/(スペース)(0から100のパーセンテージカウンター)%
  • パーセンテージカウンターは、表示が変わるたびに1ずつ増加することになっています。
  • カウンターが次の反復にジャンプするのにかかる時間はランダムです。関数/メソッドが、1<= ms <=750ここmsでミリ秒単位の時間の範囲で確率が0を超えるすべてのランダムな整数を生成できる限り、任意の種類のランダムが実行されます。
  • 開始時にloading - 0 %
  • 終了時にloading - 100 %
  • 入力は不要です。
  • 完全なプログラムまたは機能、または同様のものを提出してください。

私が使用したコード:

C ++

#include<stdio.h>
#include<time.h>
#include<windows.h>

int main()
{
    srand(time(NULL));
    char a[15],b[]="-\\|/";
    int i=0,j=0,ms;
    while(j<101)
    {
        (i<3)?i++:i=0;
        wsprintf(a,"loading %c %d ",b[i],j++);
        printf(a);puts("%");
            //This part is to make the output look cool
        switch(rand()%9)
        {
            case 0:ms=1;break;
            case 1:ms=2;break;
            case 2:ms=5;break;
            case 3:ms=10;break;
            case 4:ms=15;break;
            case 5:ms=20;break;
            case 6:ms=25;break;
            case 7:ms=50;break;
            case 8:ms=500;
        }
        Sleep(ms);  //Otherwise this is supposed to be random
        if(j<101)   //like this Sleep(rand()%750+1);
        system("cls");
    }
}

勝者

  • 最小バイトのコードが優先されます。


1
これは複製だとは思いませんでした。この質問は> <>では実装できませんが、たとえば*> <>で実装できます。とても気に入りました。
redstarcoder 16

1
@Mego質問は重複ではありません。出力は少し異なり、ランタイムは完全に異なり、出力に 250msの固定遅延ではなくランダム時間が必要です。ある質問に対する回答は、大幅な修正なしでは他の質問には使用できません。質問を読んでください。
イスマエルミゲル

8
もう一つの挑戦の著者として、私はduの議論に参加します。循環文字(\|/-)は同じですが、答えは無限ではなく、静的な出力ではなく乱数の生成を伴うという点で異なるようです。したがって、最初はコピーされたと感じましたが、これは私にはだまされたようには見えません。
FlipTack 16

@ flp.tkcこのアイデアは、-\|/私がいくつかのゲームで見たように、多くの場所を組み合わせたものであり、コンソールインストールプログラムからインスピレーションを受けました。
ムクルクマール

回答:


6

MATL、45バイト

101:"'loading'O'-\|/'@)O@qVO37&hD750Yr100/&Xx

オフラインコンパイラでの実行例:

enter image description here

または、MATL Online試しください

説明

101:          % Push array [1 2 ... 101]
"             % For each
  'loading'   %   Push this string
  O           %   Push 0. When converted to char it will be displayed as a space
  '-\|/'      %   Push this sring
  @)          %   Modular index into this string with iteration index
  O           %   Push 0
  @q          %   Iteration index minus 1
  V           %   Convert to string
  O           %   Push 0
  37          %   Push 37, which is ASCII for '%'
  &h          %   Concatenate horizontally into a string, Numbers are converted to char
  D           %   Display
  750Yr       %   Random integer with uniform distribution on [1 2 ... 750]
  100/        %   Divide by 100
  &Xx         %   Pause that many tenths of a second and clear screen
              % End (implicit)

16

Powershell、71 68 65バイト

https://codegolf.stackexchange.com/a/101357/59735に類似

バカではないことで3バイトを節約しました(ロード時に...を残します)

-3 VisualMelonのおかげ

750が含まれていることを確認するために750-> 751を変更しました。

0..100|%{cls;"loading $("|/-\"[$_%4]) $_ %";sleep -m(random 751)}

説明:

0..100|%{                                  #For range 0-100...
    cls                                    #Clear Display
    "loading $("|/-\"[$_%4]) $_ %"    #Display the current string
    sleep -m(random 750)                  #Sleep random ms up to 750
}

更新されたgif

enter image description here


あなたの出力ではありません正確に私のGIFと正しいあなたを参照してください同じ
Mukulクマールを

-mにスペースを削除し、括弧をなくすことができると思います$_%4(少なくとも私のボックスでは動作するようです)。
VisualMelon 16

@VisualMelonに感謝()します。これは、コードを直接コピーした他の課題からの残り物でした。
colsw 16

8

Python 2、119 113 112バイト

もともとランダムな量で行っていましたrandom()/.75が、エンドポイントは含まれません。ランダムなロード時間と、実際に終了するという事実を除き、無限のロード時間については、これと他の質問との間に大きな違いはありません。

import time,random as r
for i in range(101):print'\rLoading','-\|/'[i%4],i,'%',;time.sleep(r.randint(1,750)/1e3)

6バイトを保存してくれたJonathan Allanと、バイトを保存してくれたDJMcMayhemに感謝します!


1
で6つのバイトを保存import time,random as rしてr.randint
ジョナサンアラン

@ジョナサンアランあなたはそのようにインポートできることに気づかなかった、ありがとう!
カーデ

forループAは少し短いです:for i in range(101):print'\rLoading','-\|/'[i%4],i,'%',;time.sleep(r.randint(1,750)/1e3)
DJMcMayhem

@DJMcMayhemおっと、私はそれをテストしていたrange(1,101)。..何らかの理由で
カーデ

:Acttually、私は何か他の3が短くバイト見つかったi=0;for c in'-\|/'*25:print'\rLoading',c,i,'%',;time.sleep(r.randint(1,750)/1e3);i+=1
DJMcMayhem

6

バッチ、185バイト

@set s=-\!/
@for /l %%i in (0,1,100)do @call:l %%i
@exit/b
:l
@cls
@set c=%s:~0,1%
@set s=%s:~1%%c%
@echo Loading %c:!=^|% %1 %%
@set/aw=%random%%%751
@ping>nul 1.1 -n 1 -w %w%

残念ながらタイミングはかなり悪いですが、Batchにはを使用するよりも良いものはありませんping


これはWindowsでのみ機能します。FreeCom DOSバッチが提供しますLoading % Invalid switch. - /aw (コピーがまだ見つかったら、MS DOSで試してみたいです)。
ブライアンミントン

@ブライアンミントン:MS DOS上でそれを実行する幸運(pingコマンドなし)
ジョシュア

@BrianMinton高度な変数置換のため、CMD.EXEが必要です。
ニール

@Joshuaまあ、少なくとも組み込まれていません。それは、Windows 2000まで実現しなかった
ニール・

6

*> <>(ヒトデ)、86 82バイト

| v1*aoooooooo"loading K"&0"-\|/"
!0x1! +
%$<.0+af{od;?)*aa&:&Soono$&+1:&"  %"{o:}

ここで試してみてください!

これはもっとゴルフができるかもしれないが、私は何も非常に明白ではありません。スリープ時間が100ミリ秒、400ミリ秒、または700ミリ秒です。これが十分にランダムでない場合は、お知らせください。

@TealPelicanに感謝します。4バイトを節約して、もっとランダムにしました!

私が見つけた最大の課題は(それを小さくしようとしても)ランダム性であり、実際に「loading-100%」を最後に出力することでした。


1
ちょっと、私は> <>言語のこのテイクが大好きです、それはより多くの挑戦を開きます:D-私はあなたのコードを少し調整しましたが、それをあまり減らしませんでしたが、乱数を変更しました。> <>コードへのリンク *> <>でこれを実行可能にするための唯一の変更は、時間を使用するために〜をコードリンクからSに変更することです。これにより、749までの乱数が生成され、余分なスタック操作がカットされます。PSあなたが*> <>オンライン通訳者を作ることができればそれが大好きです:D
ティールペリカン

1
@Tealpelican、ありがとう!あなたの変更、特に乱数ジェネレータが大好きです!また、オンラインの*> <>インタープリターも必要です。私はJSを頻繁にいじりませんが、両方ともJSで遊ぶことを検討するか、Goインタープリターを最初にGopherJSを介して実行してヘッドスタートを行います。:)
redstarcoder 16

1
おかげで、実際に動作するバージョンを思い付くのに時間がかかりましたが、これは私が生成できる最もゴルフのようです。私はこれに目を光らせ、そうでない場合はPythonを作成することに手を出すかもしれません。私はまだ最初のラインがもう少しゴルフされるかもしれないと思うが、私は自分でそれをすることができなかった。
ティールペリカン

1
@Tealpelicanがオンライン通訳のかゆみを埋めるか、少なくともボールが転がることを願っています。後でコードを共有する方法を検討します。starfish.000webhostapp.com
redstarcoder 16

1
それは簡単で、プログラムを実行するだけで問題なく動作するようです:D今週、いくつかの課題でこれを使用することを試みます
ティールペリカン

5

Perl 6、67バイト

for |<- \ | />xx* Z 0..100 {print "\rloading $_ %";sleep .750.rand}

拡張:

for

  # produce a list of all the pairs of values

  |<- \ | /> xx *   # a flat infinite list of "clock faces"
  Z                 # zipped with
  0 .. 100          # all the numbers from 0 to 100 inclusive

  # &zip / &infix:<Z> stop on the shortest list

{

  # 「$_」 will look something like 「("/", 39)」
  # when it is coerced to a Str, all of its elements
  # will be coerced to Str, and joined with spaces

  print "\rloading $_ %";

  sleep .750.rand

}

4

ジャバスクリプト(ES6)、128 118 116 115 112 110 109バイト

これは、この「乱数」の大ざっぱなソースであっても、完璧に機能するようです。

(X=_=>setTimeout(i>99||X,1+new Date%750,document.body.innerHTML=`<pre>Loading ${'-\\|/'[i%4]} ${i++}%`))(i=0)


代替案1、Javascript + HTML、16 + 84バイト

これは、既存の要素を使用して残りのコンテンツを表示します。

(X=_=>setTimeout(i>99||X,1+new Date%750,a.innerHTML=`${'-\\|/'[i%4]} ${i++}%`))(i=0)
Loading <a id=a>

代替案2 2、95バイト

タブが開かれ、コンソールにこれを貼り付けていると想定できる場合:

(X=_=>setTimeout(i>99||X,1+new Date%750,document.title=`Loading ${'-\\|/'[i%4]} ${i++}%`))(i=0)

HTMLを表示する代わりに、ドキュメントのタイトルが変更されます。


@ user2428118に2バイトの節約をありがとう!


()after Dateをドロップして、2バイトを保存できます。
user2428118 16

@ user2428118それが機能することを知りませんでした!ヒントをありがとう。
イスマエルミゲル

4

F#、118バイト

async{let r=System.Random()
for i in 0..100 do printf"\rLoading %O %d %%""|/-\\".[i%4]i;do!Async.Sleep(r.Next(1,750))}

このスニペットを実行するには、Async.Startまたはに渡しAsync.RunSynchronouslyます。


F#による
即時の賛成票

4

PHP、90 83 80 78 77バイト

77:

閉鎖;は必要ありません。

for(;$i<101;usleep(rand(1,75e4)))echo"\rloading ",'-\|/'[$i%4],' ',$i+++0,'%'

78:

変数を初期化せずに最初に0を取得する別の回避策を探しているときに、私はこれを思いつきました:

for(;$i<101;usleep(rand(1,75e4)))echo"\rloading ",'-\|/'[$i%4],' ',$i+++0,'%';

printfを使用してintとして強制フォーマットするだけなので、エコーに戻って数バイトを獲得しました。インクリメントされた$ iを0でインクリメントすることにより、有効な整数を取得します。文字列の区切り文字として一重引用符を使用することにより、バックスラッシュをエスケープする必要がなくなり、別のバイトが解放されます

80:

$ iの増分を最後のforセクションからprinfに移動すると、さらに3オフになりました。(以下のコメントを参照)

for(;$i<101;usleep(rand(1,75e4)))printf("\rloading %s %d%%","-\\|/"[$i%4],$i++);

83:

loaderstatesを持つ変数の初期化を削除しました。

for(;$i<101;usleep(rand(1,75e4)),$i++)printf("\rloading %s %d%%","-\\|/"[$i%4],$i);

90:

ローダーアニメーションを有効にするにはかなりの数を追加する必要があるため、$ iのinitを削除していくつかのバイトを獲得しようとしました。printfはエコーではなく2を追加しますが、NULLを整数としてフォーマットすると0になります。

for($l='-\|/';$i<101;usleep(rand(0,750)*1e3),$i++)printf("\rloading %s %d%%",$l[$i%4],$i);

間違いが1つあります。この質問では、遅延が1〜750である必要があります。0から750の間です。また、増分をに移動してprintf、1バイトを節約できます。for(;$i<101;usleep(rand(1,750)*1e3))printf("\rloading %s %d%%",'-\|/'[$i%4],$i++);(82バイト)
イスマエルミゲル

1
@IsmaelMiguel rand()は包括的ですか、または* 1e3による乗算のためですか?その空きバイトに忍び込むつもりです。
thisisboris

質問に、1ミリ秒から750ミリ秒までのランダムな間隔が必要です。rand(0,750)*1e3は0(無効)から750までrand(1,75e4)の値を返し、これに1000を掛けます。1(無効)から750000の間の値を返しrand(1,750)*1e3ますusleep()。ミリ秒よりも1000倍小さいマイクロ秒で動作します。
イスマエルミゲル

これにより、user59178の答えに不便に近くなる可能性がありますが、echoは3バイトより短くなりprintfます。最新バージョンを一番上に置き、の#title代わりに使用することもでき**title**ます。そして、数字との間にスペースがありません%
タイタス

@Titus $ iを初期化していないため、ここでエコーを使用できません。文字列のnullが ''に評価されるため、printfを介して整数(%d)を強制的にnull = 0にします。#justphpthings
thisisboris

3

Groovy、113 87バイト

lealandのおかげで-36バイト

{p=-1;101.times{print"\rLoading ${"-\\|/"[p++%4]} $p%";sleep Math.random()*750as int}}​

2
84バイト、およびGroovyのコンソールから実行する必要があります:p=-1;101.times{println"Loading ${"-\\|/"[p++%4]} $p%";sleep Math.random()*750as int}
lealand

1
質問の所有者は明示的に要求していませんが、おそらく連続した読み込みメッセージが互いに上書きすることを望んでいます。サイズに違いはありませんので、より良い変更println"Loading…print"\rLoading…。そして、その変数pを削除し、代わりに暗黙のそれを使用します。
マナトワーク16

3

Bash、162 104バイト

関連する質問に関するZacharyの回答を修正し、manatworkによって大幅に改善しました。

s='-\|/'
for x in {0..100};{
printf "\rloading ${s:x%4:1} $x %%"
sleep `printf .%03d $[RANDOM%750+1]`
}

I had to look up how to do random numbers in bash.

Ungolfed / Explained

s='-\|/'
for x in {0..100}
{
    # \r returns the carriage to the beginning of the current line.
    # ${s:x%4:1} grabs a substring from s, at index x%4, with a length of 1.
    printf "\rloading ${s:x%4:1} $x %%"

    # "$RANDOM is an internal bash function that returns
    #   a pseudorandom integer in the range 0 - 32767."
    # .%03d is a dot followed by a base-ten number formatted to 3 places,
    #   padded with zeros if needed.
    # sleep accepts a floating point number to represent milliseconds.
    sleep `printf .%03d $[RANDOM%750+1]`
}

1
Nice first try. See Tips for golfing in Bash for improvement tips. Personally would go with s='-\|/';for x in {0..100};{ printf "\rloading ${s:x%4:1} $x %%";sleep `printf .%03d $[RANDOM%750+1]`; } BTW, our fellow site Unix & Linux also has a question about How to do integer & float calculations, in bash or other languages/frameworks?.
manatwork

@manatwork Good links! I didn't know about $[math], using { } instead of do done, or using back ticks instead of $(). Yeah, reusing $x for accessing the loader graphic array makes sense. Also, slapping a . in front of the number to get the decimal for sleep is pretty sweet!
Hydraxan14

3

C#, 170 149 135 Bytes

()=>{for(int i=0;i++<=100;System.Threading.Thread.Sleep(new Random().Next(1,750)))Console.Write($"\rloading {@"-\|/"[i % 4]} {i} %");};

Ungolfed:

static void l()
{
    for (int i = 0; i <= 100; System.Threading.Thread.Sleep(new Random().Next(1, 750)))
        Console.Write($"\rloading {@"-\|/"[i % 4]} {i} %");   
}

I won't guarantee that every character in this is right, please correct me if there are compilation errors. I had to type the whole thing on my phone so I might have accidentally included some errors... ¯_(ツ)_/¯ I hope you guys forgive me that

Tested it on my PC, works like a charm and I even saved a whole 20 bytes thanks to pmbanka :)


1
You can use \r (carriage return) instead of Console.Clear(). You can also inline s variable to save some bytes.
pmbanka

1
You can also save an extra byte by replacing the i<=100 for i<101
auhmaan

for (int i = 0; i <= 100; i++) can be rewritten as for (int i = 0; i++ <= 100;) Then you can put the Thread.Sleep within the place where i++ was and save both curly brackets. Cutting 3 bytes in total
CSharpie

Also OP didnt ask for a Programm so you can replace static void l() with ()=>
CSharpie

2

C 112 103 bytes

Saved 9 bytes thanks to @G. Sliepen. Not very exciting, just a golf of your C++ answer basically. Also not a very exciting random function. I thought about Sleep(c[i%4]), or Sleep(i) but they're not random at all!

#import<windows.h>
i;f(){for(;i<101;printf("\rloading %c %d %%","-\\|/"[i%4],i++),Sleep(rand()%750+1));}

Ungolfed:

#include <windows.h>
int i;
void f() {
  for(;i<101;) {
    printf("\rloading %c %d %%", "-\\|/"[i%4], i++);
    Sleep(rand()%750+1);
  }
}

3
I am afraid but rand ()%750 generates numbers from 0-749 you will need to add 1.
Mukul Kumar

Changing rand()%750 to rand()%751 won't give the result you want. It will generate a random value between 0 and 750. In the question, the delay must be between 1 and 750 (inclusive). According to tutorialspoint.com/c_standard_library/c_function_rand.htm, the rand() function generates numbers between 0 and (at least) 32767. If you do 0 % 750, you get 0 since 0 / <anything> == 0.
Ismael Miguel

Shave off 9 bytes by removing char*c="-\\|/"; and using the literal string directly instead of the variable c: printf(...,"-\\|/"[i%4],...)
G. Sliepen

2

Mathematica, 133 Bytes

Dynamic[If[x<100,x++,,x=0];Row@{"Loading ",StringPart["-\|/",1+x~Mod~4]," ",x,"%"},
    UpdateInterval:>RandomReal@.75,TrackedSymbols:>{}]

This will run once, assuming x is undefined. Clear@x will restart it.

55 characters tied up in verbosity :/


Is that a fixed interval or will it be repeatedly randomized?
Titus

It's randomized. UpdateInterval:>.75 would have been fixed
Kelly Lowder

1
@Titus: I believe UpdateInterval:>RandomReal@.75 repeatedly calls RandomReal, but UpdateInterval->RandomReal@.75 would call it only once.
Omar

2

R - 94 bytes

for(i in 0:100){cat('\rLoading',c('-','\\','|','/')[i%%4+1],i,'%');Sys.sleep(sample(750,1)/1e3)}

Really nice that sample(750,1) == sample(1:750,1).


2

HTML + JS (ES6), 16 + 87 = 103 bytes

(f=_=>a.innerHTML='\\|/-'[i++%4]+` ${i<100&&setTimeout(f,Math.random()*750),i} %`)(i=0)
loading <a id=a>


2

PHP, 66 79 bytes

for($i=-1;++$i<101;usleep(rand(1,75e4)))echo"\rloading ","-\\|/"[$i%4]," $i %";

Unfortunately I had to assign $i in order to get it to print '0'.
Use like:

php -r 'for($i=-1;++$i<101;usleep(rand(1,75e4)))echo"\rloading ","-\\|/"[$i%4]," $i %";'

Edits: thanks to Titus confirming exactly what's allowed with Mukul Kumar we can save 3 bytes with a less restricted range, but not all 9 bytes with an unrestricted range. Thanks also for pointing out that I forgot the cycling character and providing a simple solution to do it.


1
The random requirements are that you generate all 1ms to 750ms with a possibility>0. I can´t see that other values are prohibited. rand(1,75e4) saves 3 bytes; 1e6 can save another one; and no parameters at all save 9 bytes altogether; and I don´t see that violate any rule. But you forgot to cycle the character: +16 for ","-\\|/"[$i%4]," instead of -.
Titus

@Titus Won't usleep(rand(1,75e4)) generate a random interval between 1 microsecond and 750 milliseconds? Also, according to the question, the interval must be between 1 and 750, inclusive.
Ismael Miguel

See the latest comments on the question: 1 to 75e4 is acceptable.
Titus

@Titus I'd considered changes like those but decided to go with what seemed implied by the question (integer millisecond delays). Thanks for asking exactly what was allowed!
user59178

2

Noodel, noncompeting 40 bytes

Just going back through old challenges (as in challenges that were made before Noodel) and competing with Noodel to find where it is weak.

Loading¤”ḋḟƇḣ⁺s¤ṡ⁺Ḷ101ạ¤%ɱṠĖ²⁺Çṛ749⁺1ḍ€Ḃ

If final output does not matter, then can save 2 bytes.

Loading¤”ḋḟƇḣ⁺s¤ṡ⁺Ḷ101ạ¤%ɱṠĖ²⁺Çṛ749⁺1ḍ

Noodel pushes the top of the stack to the screen at the end of the program so by adding the €Ḃ it prevents that from happening.

Try it:)

How It Works

Loading¤”ḋḟƇḣ⁺s¤ṡ⁺Ḷ101ạ¤%ɱṠĖ²⁺Çṛ749⁺1ḍ€Ḃ # Main Noodel script.

Loading¤”ḋḟƇḣ⁺s¤ṡ⁺                       # Creates the array ["Loading¤-¤", "Loading¤\¤", "Loading¤|¤", "Loading¤/¤"]
Loading¤                                 # Pushes the string "Loading¤"
        ”Ƈḟḋḣ                            # Pushes the array ["-", "\", "|", "/"]
             ⁺s                          # Concats "Loading¤" to each element in the array by prepending.
               ¤                         # Pushes a "¤" onto the stack.
                ṡ                        # Pushes
                 ⁺

                  Ḷ101ạ¤%ɱṠĖ²⁺Çṛ749⁺1ḍ   # Main loop that creates the animation.
                  Ḷ101                   # Loop the following code 101 times.
                      ạ                  # Pushes on a copy of the next animation element from the array.
                       ¤%                # Pushes the string "¤%"
                         ɱ               # Pushes on the current count of the number of times that have looped (zero based).
                          Ṡ              # Swaps the two items at the bottom of the stack.
                           Ė             # Pushes the item at the bottom of the stack to the top (which will be the string selected from the array).
                            ²⁺           # Concat twice appending the loop count then the string "¤%" to the string selected from the array.
                              Ç          # Pops the string off of the stack, clears the screen, then prints the string.
                               ṛ749      # Randomly generate an integer from 0 to 749.
                                   ⁺1    # Increment the random number producing a random number from 1 - 750.
                                     ḍ   # Pop off the stack and delay for that number of milliseconds.

                                      €Ḃ # Ends the loop and prevents anything else being displayed.
                                      €  # Ends the loop (new line could be used as well)
                                       Ḃ # Destroys the current stack therein, nothing gets pushed to the screen at the end of the program.

<div id="noodel" code="Loading¤”ḋḟƇḣ⁺s¤ṡ⁺Ḷ101ạ¤%ɱṠĖ²⁺Çṛ749⁺1ḍ€Ḃ" input="" cols="14" rows="2"></div>

<script src="https://tkellehe.github.io/noodel/noodel-latest.js"></script>
<script src="https://tkellehe.github.io/noodel/ppcg.min.js"></script>


Why are there so many ¤s?
Kritixi Lithos

@KritixiLithos Noodel uses spaces as a NOP so for printing a space the ¤ is used:)
tkellehe

1
Btw, it's nice that there is a stack snippet for this :)
Kritixi Lithos

How does the snippet work? Does the imported script find the element with the id of noodle, then translate the code to Javascript?
Carcigenicate

@Carcigenicate, Yes. The "parser" is the JavaScript function noodel which handles the code properly. It translates the code into tokens that are JavaScript objects that get chained together then executed. The ppcg.min.js creates the proper HTML objects and translates the output of what is parsed into the HTML objects to create the display. Every token is executed by stepping through them triggering a step event which is registered to update the screen:) Does that help?
tkellehe

2

C 126 121 bytes

f(){i=0;char c[]="/-\\|";for(;i<101;i++){printf("\rloading %c %d %% ",c[i%4],i);fflush(stdout);usleep(1000*(rand()%75));}

Ungolfed version:

 void f()
 {
  int i=0;
  char c[]="/-\\|";
  for(;i<101;i++)
  {
    printf("\rloading %c %d %% ",c[i%4], i);
    fflush(stdout);
    usleep(1000*(rand()%75));  
  }
 } 

@Carcigenicate @ Mukul Kumar Did not read between the lines there, Thanks! :)


1
c[] is not random... But is cycling....
Mukul Kumar

Or, in other words, you're not supposed to pick a random character from "\|/-", you're supposed to display /, then -, then \, then |, in a cycle.
Carcigenicate

@MukulKumar @ Carcigenicate Updated the code so that it does what the spec says regarding cycling characters!
Abel Tom

1

MATLAB, 108 bytes

function k;for i=0:100;a='-\|/';pause(rand*.749+.001);clc;['loading ' a(mod(i,3)+1) ' ' num2str(i) ' %']
end

1

Octave, 122 120 119 108 bytes

I misread the challenge and created an infinite loader that restarted at 0 once it passed 100. Making it into a one time only loader:

a='\|/-';for i=0:100;clc;disp(['Loading ',a(1),' ',num2str(i),' %']);a=a([2:4,1]);pause(0.749*rand+.001);end

Circulating a, a=a([2:4,1]) was flawr's idea here. Also, saved 2 bytes by skipping the parentheses after rand thanks to MattWH.


Should it be .749*rand()+.001? This can wait for 751ms. Also you can leave the () off rand and save 2 bytes.
MattWH

1

ForceLang, 250 bytes

Noncompeting, requires language features which postdate the question

def D def
D w io.write
D l e+"loading"+s
D z string.char 8
D s string.char 32
D d datetime.wait 750.mult random.rand()
D e z.repeat 24
D n set i 1+i
D k s+n+s+"%"
set i -1
label 1
w l+"-"+k
if i=100
exit()
d
w l+"\"+k
d
w l+"|"+k
d
w l+"/"+k
d
goto 1

I should probably fix some bugs related to string literal parsing soon.


1

Racket 110 bytes

(for((i 101))(printf"Loading ~a ~a % ~n"(list-ref'("-" "\\" "|" "/")(modulo i 4))i)(sleep(/(random 750)1000)))

Ungolfed:

(define(f)
  (for ((i 101))
    (printf "Loading ~a ~a % ~n" (list-ref '("-" "\\" "|" "/") (modulo i 4)) i)
    (sleep (/(random 750)1000))))

Testing:

(f)

Output: enter image description here

(This gif file is showing slower display than actual)


What's with the stuff at the end in the gif?
Carcigenicate

This seem to be an artefact from screen capture program.
rnso

1

107 75 Ruby

-32 thanks to manatwork

Normal

i=0
(0..100).each{|c|
system'clear'
puts"loading #{'\|/-'[i=-~i%4]} #{c} %"
sleep rand*(0.750-0.01)+0.01
}

Golfed

101.times{|c|$><<"\rloading #{'-\|/'[c%4]} #{c} %";sleep rand*0.749+0.001}

Given you have a single line of output to overwrite, the system'clear' is overkill here. Also the use of the separate variable i. Oh, and precalculate where possible: 0.750-0.010.749 (also note that you lack one decimal place in 0.01 – should be 0.001). The resulting 101.times{|c|$><<"\rloading #{'-\|/'[c%4]} #{c} %";sleep rand*0.749+0.001} becomes very similar to Conor O'Brien's Ruby answer in Loading… Forever but so is the challenge.
manatwork

1

Python 3, 149 bytes

import time,random;f=0;n=0
while n<=100:
 print("Loading...","|/-\\"[f],n,"%",end="\r");f+=1
 if f>=3:f=0
 n+=1
 time.sleep(random.uniform(.25,.75))

Similar to Loading... Forever, but I did have to edit my answer from there a lot.


1

TI-Basic, 80 bytes

For(I,0,100
For(A,0,randE2
End
Text(0,0,"loading "+sub("-\|/",1+fPart(I/4),1)+" ",I," %
End

The randomness comes from the For( loop (E is scientific E token) and since TI-Basic is interpreted there is also automatically some overhead. Remember that in TI-Basic, lowercase letters and some less common ASCII symbols are two bytes each (so specifically for this program, l o a d i n g sub( \ | % are the two-byte tokens


1

Clojure, 109 bytes

(doseq[[c i](map vector(cycle"\\|/-")(range 101))](print"\rloading"c i\%)(flush)(Thread/sleep(rand-int 751)))

Loops over a list of the range of numbers from 0 to 100, zipped with an infinite list of "\|/-" repeating forever.

; (map vector...) is how you zip in Clojure
;  All arguments after the first to map are lists. The function is expected to
;  take as many arguments as there are lists. vector is var-arg.
(doseq [[c i] (map vector (cycle "\\|/-") (range 101))]
  ; \r to erase the old line
  (println "\rloading" c i \%)
  (Thread/sleep (rand-int 751)))

1

tcl, 116

set i 0;time {lmap c {- \\ | /} {puts -nonewline stderr "\rloading $c $i%";after [expr int(187*rand())]};incr i} 100

Playable in http://www.tutorialspoint.com/execute_tcl_online.php?PID=0Bw_CjBb95KQMOXoybnVSOVJEU00


Your output seems little off...
Mukul Kumar

hmm,,, my code disappeared! ...
sergiol

I mean that your output is in this format "loading... xx%" instead it should be like this "loading - xx%" where '-' varies as explained in the question.
Mukul Kumar

@MukulKumar: Fixed.
sergiol

1

Java 8, 130 bytes

()->{for(int n=0;n<101;Thread.sleep((long)(1+Math.random()*750)))System.out.print("\rloading "+"-\\|/".charAt(n%4)+" "+n+++" %");}

Explanation:

()->{                           // Method without parameter nor return-type
  for(int n=0;n<101;            //  Loop from 0 to 100
      Thread.sleep((long)(1+Math.random()*750)))
                                //   And sleep randomly 1-750 ms 
    System.out.print(           //   Print:
      "\r                       //    Reset to the start of the line
      loading "                 //    Literal "loading "
      +"-\\|/".charAt(n%4)+" "  //    + the spinner char & a space
      +n++                      //    + the number (and increase it by 1)
      +" %");                   //    + a space & '%'
                                //  End of loop (implicit / single-line body)
}                               // End of method

Output gif:

enter image description here


0

Visual Basic, 371 Bytes

module m
sub main()
Dim s as Object
for i as Integer=0 to 100
Select Case new System.Random().next(0,9)
Case 0
s=1
Case 1
s=2
Case 2
s=5
Case 3
s=10
Case 4
s=15
Case 5
s=20
Case 6
s=25
Case 7
s=50
Case 8
s=500
End Select
Console.SetCursorPosition(0,0)
console.write("loading "+"-\|/"(i mod 4)+" "+i.tostring+" %")
system.threading.thread.sleep(s)
next
end sub
end module

Expanded:

module m
    sub main()
        Dim s as Object
        for i as Integer=0 to 100
            Select Case new System.Random().next(0,9)
                Case 0
                s=1
                Case 1
                s=2
                Case 2
                s=5
                Case 3
                s=10
                Case 4
                s=15
                Case 5
                s=20
                Case 6
                s=25
                Case 7
                s=50
                Case 8
                s=500
            End Select
            Console.SetCursorPosition(0,0)
            console.write("loading " + "-\|/"(i mod 4) + " " + i.tostring + " %")
            system.threading.thread.sleep(s)
        next
    end sub
end module
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.