Make me a fake loader

29

7

Make a fake loader just like this :

Parameters :

  • Display loading (space) one of these cyclically-\|/ (space) (percentage counter from 0-100) then a %.
  • The percentage counter is supposed to increment by 1 every time the display changes.
  • The time taken by counter to jump to next iteration is random. Any kind of random will do as long as the function/method is capable of generating all random integers having probability > 0 in range 1<= ms <=750 here ms being time in milliseconds.
  • Start at loading - 0 %.
  • End at loading - 100 %.
  • NO INPUT is required.
  • submit a full program or function or whatever similar.

The code that I used :

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");
    }
}

Winner

  • the code with least bytes wins.

Mukul Kumar

Posted 2016-12-08T17:28:58.323

Reputation: 2 585

11Related – James – 2016-12-08T17:32:51.540

1I didn't think this was a duplicate. This question cannot be implemented in ><>, but can be in *><> for example. I quite liked it. – redstarcoder – 2016-12-08T21:25:10.543

1@Mego The question isn't a duplicate. The output is a little different, the runtime is completelly different and the output requires a random time instead of a fixed 250ms delay. Answers on one question can't be used on the other without heavy modification. Please, read the questions. – Ismael Miguel – 2016-12-08T21:32:05.910

8As the author of the other challenge I'll step in with the dupe debate. Although the cycling chars (\|/-) are the same, the answer seems to be different in that it is not infinite and involves generation of random numbers, rather than a static output. Therefore I'll say, although I initially felt copied, this doesn't look like a dupe to me. – FlipTack – 2016-12-08T22:12:48.670

@flp.tkc this idea came from many places combined like I saw -\|/ in some games.And I was inspired from console installation programs. – Mukul Kumar – 2016-12-09T02:50:20.627

Are 1..750ms an exact, a maximal or a minimal range of numbers that we should generate for the delay? – Titus – 2016-12-09T17:49:21.403

@Titus If you know c-related languages then this should clarify your doubt rand ()%750+1. – Mukul Kumar – 2016-12-09T17:59:08.347

My issue is that in PHP rand() returns an integer; and you cannot delay by milliseconds: it´s either seconds or microseconds. So: would [1..750k] microseconds be ok? or [1..1mill] microseconds? – Titus – 2016-12-09T18:14:23.933

@Titus Sure that's ok [1,750K] is acceptable. And a v.important point has been clarified i.e. the time-delay is in milliseconds. – Mukul Kumar – 2016-12-09T18:23:02.983

Answers

6

MATL, 45 bytes

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

Example run in the offline compiler:

enter image description here

Or try it at MATL Online!

Explanation

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)

Luis Mendo

Posted 2016-12-08T17:28:58.323

Reputation: 87 464

16

Powershell, 71 68 65 Bytes

Similar to https://codegolf.stackexchange.com/a/101357/59735

Saved 3 bytes by not being an idiot (left the ... on loading)

-3 thanks to VisualMelon

changed 750 -> 751 to make sure 750 is included.

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

Explanation:

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
}

Updated gif

enter image description here

colsw

Posted 2016-12-08T17:28:58.323

Reputation: 3 195

your output is not exactly same please see my gif and correct yours – Mukul Kumar – 2016-12-08T19:22:36.487

I think you can drop the space after -m, and lose the parentheses around $_%4 (seems to work on my box at least). – VisualMelon – 2016-12-08T20:44:27.723

@VisualMelon thanks, the () were leftover from the other challenge I straight copied my code from. – colsw – 2016-12-09T08:45:40.230

8

Python 2, 119 113 112 Bytes

I had originally gone with the random amount being random()/.75, however the endpoint wouldn't be included. There isn't much difference from this to the other question for the infinite load time except for the randomness and the fact that it actually ends.

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

thanks to Jonathan Allan for saving 6 bytes, and DJMcMayhem for saving a byte!

Kade

Posted 2016-12-08T17:28:58.323

Reputation: 7 463

1Save 6 bytes with import time,random as r and r.randint. – Jonathan Allan – 2016-12-08T18:14:24.577

@JonathanAllan Didn't realize you could import like that, thanks! – Kade – 2016-12-08T18:22:19.437

A for loop is slightly shorter: for i in range(101):print'\rLoading','-\|/'[i%4],i,'%',;time.sleep(r.randint(1,750)/1e3) – James – 2016-12-08T18:31:29.663

@DJMcMayhem Whoops, I had been testing it with range(1,101) for some reason.. – Kade – 2016-12-08T18:33:12.520

Acttually, I found something another 3 bytes shorter: i=0;for c in'-\|/'*25:print'\rLoading',c,i,'%',;time.sleep(r.randint(1,750)/1e3);i+=1 – James – 2016-12-08T18:35:54.737

@DJMcMayhem Ooh, fancy ;) Thanks! – Kade – 2016-12-08T18:37:13.333

@DJMcMayhem although that will end at 99% :( – Jonathan Allan – 2016-12-08T18:52:22.097

@JonathanAllan Didn't think of that, I reverted my answer. – Kade – 2016-12-08T18:59:24.213

@Kade Looking at the rules you don't have to include 750 as a possible sleeping value as the comments under the question (and the sample code) say that it doesn't have to be uniform. So random()/.7 should be valid and shorter. – matsjoyce – 2016-12-08T19:38:00.817

@matsjoyce The example code has the 'cool bonus' in it, in the comments it does clearly state the normally used code which implies a value 1 <= x <= 750 to be generated. Also, dividing by a decimal will produce a sleep value over rather than under it. Even then, it isn't as simple because if random() decides to be 0.00005 I am now attempting to call sleep for under a millisecond, which isn't valid. – Kade – 2016-12-08T19:43:40.220

Incidentally, at this point in golfing, import time,random as r and r.randint don't save you any bytes from just using import time,random and random.randint. – Sherlock9 – 2016-12-09T06:23:53.563

The last comma in print'\rLoading','-\|/'[i%4],i,'%', is unnecessary. – Rainbolt – 2016-12-09T18:09:52.583

@Rainbolt that doesn't seem to be the case.

– Kade – 2016-12-13T14:01:33.567

6

*><> (Starfish), 86 82 bytes

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

Try it here!

This may be able to be golfed more, but I don't see anything super obvious. It sleeps 100ms, 400ms, or 700ms, if this isn't random enough, let me know!

Thanks to @TealPelican for saving me 4 bytes and making it much more random!

The biggest challenges I found (while still trying to keep it small) were randomness, and actually outputting "loading - 100 %" at the end, instead of just exiting at my nearest convenience :p.

redstarcoder

Posted 2016-12-08T17:28:58.323

Reputation: 1 771

1

Hey, I love this take on the ><> language, it opens up a lot more challenges :D - I've had a bit of a tweak on your code and I've not reduced it by much but changed the random numbers. Link to ><> code The only change to make this viable in *><> would be changing the ~ from the code link to S to use the time. This does generate random numbers all the way up to 749 and cuts out some excess stack operations. P.S I'd love it if you could make *><> online interpreter :D

– Teal pelican – 2016-12-12T11:29:09.037

1@Tealpelican, thanks! I love your changes, especially the random number generator! I'd also love an online *><> interpreter :p. I don't play around with JS too often, but I'll both look into playing with JS, or maybe running the Go interpreter through GopherJS first for a head-start. :) – redstarcoder – 2016-12-12T15:03:43.007

1Thanks, it took a while to actually come up with a working version but this seems the mosted golfed I could generate. I'll keep my eye out for it and if not may dabble into making a python one. I still think the first line could be golfed a bit more but I haven't been able to do it myself. – Teal pelican – 2016-12-12T15:26:30.130

1

@Tealpelican hopefully this fills the online interpreter itch, or at least gets the ball rolling. I'm going to look into a way to share code later. https://starfish.000webhostapp.com/

– redstarcoder – 2016-12-12T18:54:48.093

1That was quick, just running the program in it now and seems to work fine :D I'm going to try have a look at using this for some challenges this week. – Teal pelican – 2016-12-12T20:37:36.790

1@Tealpelican awesome I look forward to that! I just added a share feature, which I hope is okay (just does text compression). – redstarcoder – 2016-12-12T21:06:03.753

6

Batch, 185 bytes

@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%

The timing is fairly poor unfortunately, but Batch doesn't have anything better to use than ping.

Neil

Posted 2016-12-08T17:28:58.323

Reputation: 95 035

This only works on Windows. FreeCom DOS batch gives Loading % Invalid switch. - /aw (I would love to try it in MS DOS if I can still find my copy). – Brian Minton – 2016-12-09T21:56:38.880

@BrianMinton: Good luck running it on MS DOS (no ping command) – Joshua – 2016-12-09T22:53:05.850

@BrianMinton It requires CMD.EXE because of the advanced variable substitutions. – Neil – 2016-12-09T23:50:45.280

@Joshua Well, not built in at least; that didn't happen until Windows 2000. – Neil – 2016-12-09T23:52:19.677

5

Perl 6, 67 bytes

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

Expanded:

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

}

Brad Gilbert b2gills

Posted 2016-12-08T17:28:58.323

Reputation: 12 713

4

Javascript (ES6), 128 118 116 115 112 110 109 bytes

This seems to work perfectly fine, even with this sketchy source of "random" numbers.

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

Alternative 1, Javascript + HTML, 16 + 84 bytes

This one uses an already-existing element to display the remaining content:

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

Alternative 2, 95 bytes

If I can assume a tab is opened and that you're pasting this into the console:

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

Instead of showing the HTML, the title of the document will change.


Thank you to @user2428118 for saving 2 bytes!

Ismael Miguel

Posted 2016-12-08T17:28:58.323

Reputation: 6 797

You can drop the () after Date to save two bytes. – user2428118 – 2016-12-09T09:39:52.737

@user2428118 I didn't knew that that works! Thank you for the tip. – Ismael Miguel – 2016-12-09T11:24:44.930

4

F#, 118 bytes

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))}

In order to run this snippet, pass it into Async.Start or Async.RunSynchronously.

pmbanka

Posted 2016-12-08T17:28:58.323

Reputation: 171

Instant upvote because of F# – Snowfire – 2016-12-09T14:12:05.570

4

PHP, 90 83 80 78 77 Bytes

77:

The closing ; is not needed.

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

78:

While looking for another workaround to get a 0 initially without initializing the variable I came up with this:

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

Changed back to echo to win a few bytes as I only used printf to force-format as int. By incrementing the incremented $i with 0 I get a valid integer. By using single quotes as string delimiter the backslash does not need to be escaped, resulting in another byte freed

80:

Moving the increment of $i from the last for-section to the prinf gave me another 3 off. (See comments below)

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

83:

Removed init of a variable with the loaderstates.

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

90:

I tried removing the init of $i to gain some bytes, as I had to add quite a few to enable the loader animation. printf adds 2 as opposed to echo, but formatting NULL as an integer results in 0.

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

thisisboris

Posted 2016-12-08T17:28:58.323

Reputation: 141

There's one mistake: The question requires the delay to be between 1 and 750, inclusive. You have between 0 and 750. Also, you could move the increment to the printf, saving you a single byte: for(;$i<101;usleep(rand(1,750)*1e3))printf("\rloading %s %d%%",'-\|/'[$i%4],$i++); (82 bytes) – Ismael Miguel – 2016-12-09T16:26:33.570

1

@IsmaelMiguel rand() is inclusive, or is this because of the multiplication by *1e3? I'm going to sneak in that free byte.

– thisisboris – 2016-12-09T16:31:31.657

The question requires a random interval between 1ms and 750ms (inclusive). rand(0,750)*1e3 returns a value between 0 (invalid) and 750, which is multiplied by 1000. rand(1,75e4) returns a value between 1 (invalid) and 750000. The delay must be rand(1,750)*1e3, since you use usleep(). It works with microseconds, which is 1000x smaller than a millisecond. – Ismael Miguel – 2016-12-09T17:13:17.910

This may take you inconveniently close to user59178´s answer, but echo is 3 bytes shorter than printf. You may want to put the most recent version to the top and use #title instead of **title**. And there is a space missing between the number and the %. – Titus – 2016-12-09T20:01:01.930

@Titus I can't use echo here because I didn't initialize my $i, null to string evaluates to '', via printf I force integer (%d) resulting in null = 0. #justphpthings – thisisboris – 2016-12-13T15:04:12.697

So you would start with 0 % ... or not? But nm; this adds a little diversity to the answers. – Titus – 2016-12-13T17:23:21.433

With a regular error it would start with %, not even a number in front of it. I thought I would be able to make it shorter than the current shortest PHP answer because I didn't have to init ($i=-1 is 5 chars, whilst printf is only 2 longer than echo) but I guess the needed placeholders made it longer again. This does give me an idea to possibly golf it even further – thisisboris – 2016-12-14T12:18:32.550

If you run with -r, you have to use double quotes and you need the final ; (+1 byte). If not, you have to surround the code with PHP tags (+4 bytes). Nice one none the less. – Titus – 2017-01-12T00:58:11.327

3

Groovy, 113 87 bytes

-36 bytes thanks to lealand

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

Magic Octopus Urn

Posted 2016-12-08T17:28:58.323

Reputation: 19 422

284 bytes, and should run from Groovy console: p=-1;101.times{println"Loading ${"-\\|/"[p++%4]} $p%";sleep Math.random()*750as int} – lealand – 2016-12-08T23:57:53.953

1Although the question owner not explicitly requested, he probably wants the consecutive loading messages to overwrite each other. There is no size difference, so better change println"Loading…print"\rLoading…. And remove that variable p, use the implicit it instead. – manatwork – 2016-12-09T11:48:28.967

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 :)

Snowfire

Posted 2016-12-08T17:28:58.323

Reputation: 181

1You can use \r (carriage return) instead of Console.Clear(). You can also inline s variable to save some bytes. – pmbanka – 2016-12-09T14:11:06.167

1You can also save an extra byte by replacing the i<=100 for i<101 – auhmaan – 2016-12-09T16:33:42.107

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 – 2017-01-19T18:32:12.243

Also OP didnt ask for a Programm so you can replace static void l() with ()=> – CSharpie – 2017-01-19T18:36:04.207

3

Bash, 162 104 bytes

Modification of Zachary's answer on a related question, with massive improvements by 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]`
}

Hydraxan14

Posted 2016-12-08T17:28:58.323

Reputation: 131

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.se] also has a question about How to do integer & float calculations, in bash or other languages/frameworks?.

– manatwork – 2016-12-12T09:56:48.203

@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 – 2016-12-12T15:38:01.820

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);
  }
}

nmjcman101

Posted 2016-12-08T17:28:58.323

Reputation: 3 274

3I am afraid but rand ()%750 generates numbers from 0-749 you will need to add 1. – Mukul Kumar – 2016-12-08T20:35:45.147

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 https://www.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 – 2016-12-08T21:08:42.560

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

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.

user59178

Posted 2016-12-08T17:28:58.323

Reputation: 1 007

1The 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 – 2016-12-09T16:11:14.337

@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 – 2016-12-09T17:46:19.400

See the latest comments on the question: 1 to 75e4 is acceptable. – Titus – 2016-12-09T18:34:08.607

@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 – 2016-12-12T09:49:43.360

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 :/

Kelly Lowder

Posted 2016-12-08T17:28:58.323

Reputation: 3 225

Is that a fixed interval or will it be repeatedly randomized? – Titus – 2016-12-09T18:37:08.963

It's randomized. UpdateInterval:>.75 would have been fixed – Kelly Lowder – 2016-12-09T19:15:01.920

1@Titus: I believe UpdateInterval:>RandomReal@.75 repeatedly calls RandomReal, but UpdateInterval->RandomReal@.75 would call it only once. – Omar – 2016-12-14T02:12:54.683

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).

bouncyball

Posted 2016-12-08T17:28:58.323

Reputation: 401

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>

darrylyeo

Posted 2016-12-08T17:28:58.323

Reputation: 6 214

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>

tkellehe

Posted 2016-12-08T17:28:58.323

Reputation: 605

Why are there so many ¤s? – user41805 – 2017-01-11T18:54:42.540

@KritixiLithos Noodel uses spaces as a NOP so for printing a space the ¤ is used:) – tkellehe – 2017-01-11T18:56:05.337

1Btw, it's nice that there is a stack snippet for this :) – user41805 – 2017-01-11T18:57:10.313

How does the snippet work? Does the imported script find the element with the id of noodle, then translate the code to Javascript? – Carcigenicate – 2017-01-20T01:03:23.857

@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 – 2017-01-20T02:00:30.947

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! :)

Abel Tom

Posted 2016-12-08T17:28:58.323

Reputation: 1 150

1c[] is not random... But is cycling.... – Mukul Kumar – 2017-01-19T19:05:30.517

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 – 2017-01-20T00:58:58.873

@MukulKumar @ Carcigenicate Updated the code so that it does what the spec says regarding cycling characters! – Abel Tom – 2017-01-20T04:39:20.867

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.

Stewie Griffin

Posted 2016-12-08T17:28:58.323

Reputation: 43 471

Should it be .749*rand()+.001? This can wait for 751ms. Also you can leave the () off rand and save 2 bytes. – MattWH – 2016-12-09T16:05:53.723

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

MattWH

Posted 2016-12-08T17:28:58.323

Reputation: 331

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)

rnso

Posted 2016-12-08T17:28:58.323

Reputation: 1 635

What's with the stuff at the end in the gif? – Carcigenicate – 2017-01-20T01:03:55.890

This seem to be an artefact from screen capture program. – rnso – 2017-01-20T03:09:53.120

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.

SuperJedi224

Posted 2016-12-08T17:28:58.323

Reputation: 11 342

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}

Tom Lazar

Posted 2016-12-08T17:28:58.323

Reputation: 31

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 – 2016-12-13T16:36:11.793

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.

python-b5

Posted 2016-12-08T17:28:58.323

Reputation: 89

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

sergiol

Posted 2016-12-08T17:28:58.323

Reputation: 3 055

Your output seems little off... – Mukul Kumar – 2017-01-17T14:31:44.293

hmm,,, my code disappeared! ... – sergiol – 2017-01-17T17:02:08.307

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 – 2017-01-19T03:46:21.023

@MukulKumar: Fixed. – sergiol – 2017-01-19T15:03:18.707

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

Timtech

Posted 2016-12-08T17:28:58.323

Reputation: 12 038

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)))

Carcigenicate

Posted 2016-12-08T17:28:58.323

Reputation: 3 295

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

Kevin Cruijssen

Posted 2016-12-08T17:28:58.323

Reputation: 67 575

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

polyglotrealIknow

Posted 2016-12-08T17:28:58.323

Reputation: 21