Generate random UUID

15

2

I need a UUID. Your job is to generate one.

The canonical UUID (Universally Unique IDentifier) is a 32 digit hexadecimal number with hyphens inserted in certain points.The program should output 32 hex digits (128 bits), in the form of xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx (8-4-4-4-12 digits), where x is a random hexadecimal number. Assuming that your language's PRNG is perfect, all valid outputs must have the same probability of being generated.

TL;DR

Generate 32 random hexadecimal digits in the form 8-4-4-4-12 digits. Shortest code wins.

EDIT: Must be hexadecimal. Always generating decimal only is invalid. EDIT 2: No built-ins. These aren't GUIDs, just generic hex digits.


Example output:

ab13901d-5e93-1c7d-49c7-f1d67ef09198
7f7314ca-3504-3860-236b-cface7891277
dbf88932-70c7-9ae7-b9a4-f3df1740fc9c
c3f5e449-6d8c-afe3-acc9-47ef50e7e7ae
e9a77b51-6e20-79bd-3ee9-1566a95d9ef7
7b10e43c-3c57-48ed-a72a-f2b838d8374b

Input, and standard loopholes are disallowed.


This is , so shortest code wins. Also, feel free to ask for clarifications.

clap

Posted 2015-09-22T03:59:53.883

Reputation: 834

1To be clear, we should print one randomly generated UUID, yes? – Dennis – 2015-09-22T04:08:59.940

5

Seems like a less strict version of http://codegolf.stackexchange.com/q/32309/14215

– Geobits – 2015-09-22T04:09:45.220

@Dennis: correct. – clap – 2015-09-22T04:12:57.430

@Geobits: true, but not a duplicate :P – clap – 2015-09-22T04:13:18.717

9"These examples are not random. Try to attach some significance." What does that mean? – Alex A. – 2015-09-22T04:15:22.317

@Alex it means exactly that. They're not random, I took them from somewhere. – clap – 2015-09-22T04:16:14.923

I don't think this is a duplicate. Sure, the intended output is strikingly similar, but all answers from Generate four type-4 GUIDs for me only use 448 bits of entropy.

– Dennis – 2015-09-22T04:16:26.887

@AlexA. I took the idea from here

– clap – 2015-09-22T04:17:50.317

3Actually, one does not need hexadecimal numbers, 10-base can also be random. For example, 12345678-1234-1234-1234-123456789012 should be a valid UUID (or is any hex digit necessary?). Do you consider this a loophole? – Voitcus – 2015-09-22T07:26:25.760

3The title and first sentence suggest that you want a canonical UUID, and the examples given appear to follow the spec for UUIDs, but you actually seem to be asking for something else. – Peter Taylor – 2015-09-22T08:48:51.083

2The required format user version 1 to version 5 and invalid formats for a UUID. Please, read about version 4 and decide what you want. – Ismael Miguel – 2015-09-22T09:42:13.367

3I feel compelled to point out that the version 4 (random) UUID has a required format of xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx where y is one of [89AB]. At the time of this comment, none of the answers (except C# using a built in library) are guaranteed to produce a valid random UUID (and actually, are quite likely to not produce one). – None – 2015-09-22T13:59:36.990

This challenge isn't specifically for any version of UUIDs, but just generating a generic 8-4-4-4-12 string. The output strings look to be UUIDv4 but there's already a UUIDv4 challenge. – clap – 2015-09-22T14:11:29.120

@Voitcus It could be a loophole, but I specified in the question that it should be in hexadecimal. – clap – 2015-09-22T14:12:20.577

@ConfusedMr_C I can add a letter A at the end of the output string and there will be hexadecimal digit. In my opinion your question is not clear. – Voitcus – 2015-09-23T07:45:59.857

I'd suggest the following wording: Assuming that your language's PRNG is perfect, all valid outputs must have the same probability of being generated. – Dennis – 2015-09-24T19:59:09.623

Ooh, thanks! :D I'll use that. – clap – 2015-09-25T02:42:32.347

Answers

11

Pyth, 20 bytes

j\-msm.HO16*4hdj83 3

Demonstration.

Encodes [1, 0, 0, 0, 2] as 83 in base 3, then adds one and multiplies by four to get the length of each segment. Then makes hex digits and joins on hyphens.

isaacg

Posted 2015-09-22T03:59:53.883

Reputation: 39 268

8

CJam, 26 25 bytes

8 4__C]{{Gmr"%x"e%}*'-}/;

Try it online in the CJam interpreter.

How it works

8 4__C]{              }/   For each I in [8 4 4 4 12]:
        {         }*         Do I times:
         Gmr                   Pseudo-randomly select an integer between 0 and 15.
            "%x"e%             Apply hexadecimal string formatting.
                    '-       Push a hyphen-minus.
                        ;  Discard the last hyphen-minus.

Dennis

Posted 2015-09-22T03:59:53.883

Reputation: 196 637

8

Julia, 80 bytes

h=hex(rand(Uint128),32)
print(h[1:8]"-"h[9:12]"-"h[13:16]"-"h[17:20]"-"h[21:32])

Generate a random 128-bit integer, get its hexidecimal representation as a string padded to 32 digits, and divide that into segments joined with dashes.

Thanks to ConfusedMr_C and kvill for their help!

Alex A.

Posted 2015-09-22T03:59:53.883

Reputation: 23 761

5

Perl 5, 43 bytes

Saved 2 bytes thanks to @Xcali!

printf"%04x"."-"x/[2-5]/,rand 2**16for 1..8

Try it online!

Dom Hastings

Posted 2015-09-22T03:59:53.883

Reputation: 16 415

1

Shaved two bytes, still using your basic method: Try it online!

– Xcali – 2019-12-08T04:04:49.877

Thank you @Xcali! – Dom Hastings – 2019-12-11T14:00:23.673

5

PowerShell, 77 69 67 bytes

((8,4,4,4,12)|%{((1..$_)|%{'{0:X}'-f(random(16))})-Join""})-Join"-"

edit: extraneous parens:

((8,4,4,4,12)|%{((1..$_)|%{('{0:X}'-f(random(16)))})-Join""})-Join"-"

edit: was able to remove the trailing .Trim("-") from the original:

(((8,4,4,4,12)|%{((1..$_)|%{('{0:X}'-f(random(16)))})+"-"})-Join"").Trim("-")

It may be clearer with some whitespace given the nature of the flags (-f and -Join). I would still like to lose the final Trim("-"):

(((8,4,4,4,12)|%{((1..$_)|%{('{0:X}' -f (random(16)))}) + "-"}) -Join "").Trim("-")

Or, using the built-in functionality (ala the C# answer above)

'{0}'-f[System.Guid]::NewGuid()

However, it seems a wee bit shortcut-y even if it comes in at 31 bytes.

Forty3

Posted 2015-09-22T03:59:53.883

Reputation: 341

61 byte: (8,4,4,4,12|%{-join(1..$_|%{'{0:X}'-f(random(16))})})-join'-' – mazzy – 2018-08-08T12:48:13.613

5

Python 2, 86 84 bytes

from random import*;print'-'.join('%%0%ix'%i%randint(0,16**i-1)for i in[8,4,4,4,12])

This chains string formatters to make Python format the hex numbers uniquely for each segment.

Ungolfed:

import random

final = []
for i in [8, 4, 4, 4, 12]:               # Iterate through every segment
    max = (16 ** i) - 1                  # This is the largest number that can be
                                         # represented in i hex digits
    number = random.randint(0, max)      # Choose our random segment
    format_string = '%0' + str(i) + 'x'  # Build a format string to pad it with zeroes
    final.append(format_string % number) # Add it to the list

print '-'.join(final)                    # Join every segment with a hyphen and print

This could use some improvement, but I'm proud.

jqblz

Posted 2015-09-22T03:59:53.883

Reputation: 2 062

4

PHP, 69 72 75 bytes

foreach([8,4,4,4,12]as$c)$r[]=rand(".1e$c","1e$c");echo join('-',$r);

This does not output hex digits (a, ... f). They are allowed, but not required by the question body.

No digit group starts with 0 (also not required).

edit: saved 3 bytes thanks to @IsmaelMiguel

Voitcus

Posted 2015-09-22T03:59:53.883

Reputation: 755

That looks like a bi more than 32 bytes. – isaacg – 2015-09-22T09:30:31.263

@isaacg yes, sorry - my mistake – Voitcus – 2015-09-22T09:31:41.350

You should use join() instead.

– Ismael Miguel – 2015-09-22T13:25:03.493

3

R, 63 bytes

x=sample(c(0:9,letters[1:6]),36,1);x[0:3*5+9]='-';cat(x,sep='')

Try it online!

The code first builds a 36 character random string, and then places the four hyphens. It outputs a UUID to stdout.

NofP

Posted 2015-09-22T03:59:53.883

Reputation: 754

Replace the c call with sprintf("%x",0:15) for -1. – J.Doe – 2018-10-10T09:31:04.947

3

JavaScript, ES6, 106 bytes

"8-4-4-4-12".replace(/\d+/g, m => {t=0;for(i=0; i<m; i++) {t+=(Math.random()*16|0).toString(16)}return t})

Uses Regex replace. Treats the format string as a count for generating a hex char. Hoisting wherever I can; omitting semicolons where possible.

Reno McKenzie

Posted 2015-09-22T03:59:53.883

Reputation: 31

89 bytes, '8-4-4-4-12'.replace(/\d+/g,n=>Math.floor(16**n*Math.random()).toString(16).padStart(n,0)) – kamoroso94 – 2018-08-29T16:03:47.883

3

C#, 65 Bytes

using System;class C{void Main(){Console.Write(Guid.NewGuid());}}

edit: Yes ! C# is shorter than another Language (besides Java) :)

Stephan Schinkel

Posted 2015-09-22T03:59:53.883

Reputation: 596

1

I think this is considered a standard loophole... :( http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default

– Dom Hastings – 2015-09-22T09:18:27.323

1I think this is not considered a standard loophole: As you can see the request to abandon this stuff just got 2 upvotes in over 1 year. Contrarily the comment that says you should use built-in-functions got 58 upvotes. Or as one commenter said --> If we were all limited to the same set of built-in functions, every contest would be won by APL or Golfscript because their command names are the shortest. (Michael Stern) – Stephan Schinkel – 2015-09-22T09:40:13.923

1or to just put it another way around: Can we use printf? or should we use inline asm to trigger interupt 21? – Stephan Schinkel – 2015-09-22T09:41:02.103

A good point! I didn't intend to upset, I only meant to be helpful! I guess then, Mathematica could win with CreateUUID[]! – Dom Hastings – 2015-09-22T11:02:12.320

1@StephanSchinkel The "only 2 upvotes in a year" is misleading. It has 47 upvotes and 45 downvotes right now, so a net +2. That being said, the generally accepted threshold is higher than that, so you're right that it doesn't "really" count as a standard loophole right now. – Geobits – 2015-09-22T19:00:40.637

However, does that function give a formatted GUID with certain positions fixed? If so, I don't think it qualifies, since the spec says every x position (32 total) should be random. – Geobits – 2015-09-22T19:03:44.943

Is this valid? The OP edited in "No built-ins. These aren't GUIDs, just generic hex digits." – mbomb007 – 2017-10-20T21:42:48.803

Don't know who is downvoting me here. Please have a look at when I answered the question. I answered at Revision 3 of the question. Current Revision is 7. No built ins came with Revision 6. 4 days after I have answered the question. But thanks nonetheless :-) – Stephan Schinkel – 2017-10-26T11:51:14.420

3

gawk, 86

BEGIN{for(srand();j++<32;printf(j~"^9|13|17|21"?"-":E)"%c",x+(x>10?87:48))x=rand()*16}

You can use this once every second to generate a unique random "UUID". This is because srand() uses the system time in seconds since epoch as argument if there is no argument given.

for n in `seq 100` do awk 'BEGIN{for(srand();j++<32;printf(j~"^9|13|17|21"?"-":E)"%c",x+(x>10?87:48))x=rand()*16}'; sleep 1; done

I think the awk part is rather elegant.

BEGIN{
    srand()
    for(;j++<32;) {
        x=rand()*16
        x+=(x>10?87:48)
        printf "%c", x
        if(j~"^8|12|16|20")printf "-"
    }
}

If you want to use it more often than once every second you can call it in bash like this. Note that the awk part is changed too.

echo `awk 'BEGIN{for(srand('$RANDOM');j++<32;printf(j~"^9|13|17|21"?"-":E)"%c",x+(x>10?87:48))x=rand()*16}'`

The echo is added there to print a new line every time.

Cabbie407

Posted 2015-09-22T03:59:53.883

Reputation: 1 158

3

K5, 35 bytes

"-"/(0,8+4*!4)_32?`c$(48+!10),65+!6

To generate a hex alphabet I generate a character string (`c$) from a list of digits (48+!10) and the first 6 capital letters (65+!6). An alternate way of generating the digits which is the same length is ,/$!10.

With the string "0123456789ABCDEF" generated, the rest is simple. Select 32 random values from this set (32?), slice (_) the resulting string at 0 8 12 16 20 computed via (0,8+4*!4), and then join the resulting string fragments with dashes ("-"/).

In action:

  "-"/(0,8+4*!4)_32?`c$(48+!10),65+!6
"9550E114-A8DA-9533-1B67-5E1857F355E1"

JohnE

Posted 2015-09-22T03:59:53.883

Reputation: 4 632

2

Kotlin, 175 bytes

fun main(a:Array<String>){
fun f()="0123456789abcdef".get((Math.random()*16).toInt())
var s=""
for(i in listOf(8,4,4,4,12)){
for(j in 1..i)
s+=f()
if(i!=12)s+="-"}
println(s)}

Try it online!

My first ever Kotlin program & PPCG submission

Cheldon

Posted 2015-09-22T03:59:53.883

Reputation: 91

2

APL (Dyalog Unicode), 115 78 bytes

a←⊣,'-',⊢
H←⊃∘(⎕D,819⌶⎕A)¨16∘⊥⍣¯1
(H 8?16)a(H 4?16)a(H 4?16)a(H 4?16)a H 12?16

Try it online!

This is my first APL submission. Huge thanks to @Adám for bearing with me at the PPCG's APL chat and for the hexadecimal conversion function.

Thanks to @Zacharý for 1 byte

Edited to fix byte count.

J. Sallé

Posted 2015-09-22T03:59:53.883

Reputation: 3 233

You can assume ⎕IO←0 at no byte cost, Adám does that alot. Also, most bytes (IIRC, all the ones you have here) can be counted as one in APL. – Zacharý – 2017-10-19T20:44:05.680

@Zacharý I've used TIO to count the bytes for my submission, should I have used the number of characters instead? I'm still new to PPCG and using APL, so I don't have much actual knowledge of how to do the byte count for it. – J. Sallé – 2017-10-20T12:42:26.450

Also, you can change a(H 12?16) to a H 12?16 to save one byte. – Zacharý – 2017-10-20T22:41:52.297

2

Japt, 32 bytes

[8,4,4,4,12]m@MqG**X sG ù0X} q"-

Try it online!

Bejofo

Posted 2015-09-22T03:59:53.883

Reputation: 31

Welcome to PPCG and welcome to Japt :) I'll take a run through your solutions so far when I can make some time (just back from holidays, so much to catch up on) but the first tip I'll offer is to familiarise yourself with the Unicode shortcuts (m@ - £, for example) and, to help get you started here's a hastily golfed 24 byte version of your solution: https://ethproductions.github.io/japt/?v=1.4.6&code=I+4wMTbsRCCjTXFHcFgpc0cg+TBYw3Et&input= Drop into the Japt chatroom if you've any questions.

– Shaggy – 2018-08-17T09:14:25.980

2

Perl 6, 53 bytes

The obvious one:

say join '-',(0..9,'a'..'f').flat.roll(32).rotor(8,4,4,4,12)».join # 67

Translating the Perl 5 example using printf, results in code that is a bit shorter.

printf ($_='%04x')~"$_-"x 4~$_ x 3,(0..^4⁸).roll(8) # 53

Brad Gilbert b2gills

Posted 2015-09-22T03:59:53.883

Reputation: 12 713

(0..16⁴)?! You can do that in Perl? – clap – 2015-12-03T02:34:46.657

1

@VoteToSpam You can as of 9 days ago. ( Perl 6 will be released later this month )

– Brad Gilbert b2gills – 2015-12-04T15:29:04.157

Cooooool. Maybe I should learn it – clap – 2015-12-04T16:23:52.187

@VoteToSpam That's nothing compared to 1,2,4,8,16 ... * which generates a lazy infinite list of the powers of 2. ( {2**$++} ... * also works ) – Brad Gilbert b2gills – 2015-12-04T16:29:33.993

1

Perl, 51 bytes

say"xx-x-x-x-xxx"=~s/x/sprintf"%04x",rand 65536/reg

Requires perl5 >= 5.10 I think. For the /r modifier and for say().

Kjetil S.

Posted 2015-09-22T03:59:53.883

Reputation: 1 049

1

Nice! That's much better than mine! Having looked at your solution, you might even be able to save more based on this meta post with s//xx-x-x-x-xxx/;s/x/sprintf"%04x",rand 65536/eg using -p flag, would also mean it works on older versions without -E.

– Dom Hastings – 2017-07-17T07:27:37.887

Thanks. Your suggestion is:

echo|perl -pe's//xx-x-x-x-xxx/;s/x/sprintf"%04x",rand 65536/eg'

And thats just 48 chars between ' '. (Is this kind of cheating? Maybe not) – Kjetil S. – 2017-07-17T08:03:20.033

According to this meta post it's acceptable, I haven't had an opportunity to utilise that mechanism myself yet, but hopefully I will soon enough! Would be 49 bytes (+ -p) but still pretty good and I wouldn't have considered that approach without seeing your answer!

– Dom Hastings – 2017-07-17T08:24:41.903

1

C++, 194 193 221 210 201 bytes

+7 bytes thanks to Zacharý ( detected a - that should not be at the end )

#include<iostream>
#include<random>
#include<ctime>
#define L(a)for(int i=0;i<a;++i)std::cout<<"0123456789abcdef"[rand()%16];
#define P(a)printf("-");L(a)
void t(){srand(time(0));L(8)P(4)P(4)P(4)P(12)}

If someone has a way to get a different value every execution without changing srand and without including <ctime>, that would be great

HatsuPointerKun

Posted 2015-09-22T03:59:53.883

Reputation: 1 891

Can't #define L(a) for ... be #define L(a)for...? (Might have already asked that) – Zacharý – 2017-10-19T20:52:01.843

This is invalid, there's a "-" at the end (which there shouldn't be) – Zacharý – 2017-10-20T22:44:19.893

@Zacharý Correction applied now – HatsuPointerKun – 2017-10-21T08:55:39.183

210 bytes – Zacharý – 2017-10-21T15:50:42.213

1Could you do something like "0123456789abcdef"[rand()%16], and then remove f? – Zacharý – 2017-10-22T17:27:50.190

You could save one byte by changing L(a) to ;for(...)..., P(a) to printf("-")L(a), then remove the semicolon before L(8). – Zacharý – 2018-05-31T19:49:14.543

I'm not entirely sure if these apply to C++ as well as C, but... you can have the defines in compiler -D... instructions, saving you a whopping 12 bytes total. Also, instead of rand(), you can use clock() to avoid seeding and to get a reasonable degree of randomness, saving you 13 bytes. Furthermore, puts() is 2 bytes shorter than printf(), and using putchar() instead of cout would save you another 2. Total bytes saved: 29. – None – 2018-08-05T18:53:45.010

173 bytes – ceilingcat – 2020-01-28T01:40:36.297

1

J, 42 39 37 27 bytes

echo'-'(8+5*i.4)},hfd?36#16

Try it online!

FrownyFrog

Posted 2015-09-22T03:59:53.883

Reputation: 3 112

1

Befunge-93, 97 bytes

v>4448v,+<    <
0*    :  >59*0^
62v0-1_$:|>*6+^
>^>41v < @^99<
v<*2\_$:54+` |
?0>+\1-^ v*68<>
>1^

Try it online!

I'm sure this can be shrunk, but this is my first try :)

nornagon

Posted 2015-09-22T03:59:53.883

Reputation: 111

1

Bash, 67 bytes

for l in 4 2 2 2 6;{ o+=`xxd -p -l$l</dev/random`-;}
echo ${o::-1}

apilat

Posted 2015-09-22T03:59:53.883

Reputation: 111

Welcome to PPCG! – Dennis – 2018-08-05T15:39:47.810

1

C (gcc), 143 110 103 96 94 bytes

Golfed down to 94 bytes thanks to ceilingcat and Jonathan Frech.

(*P)()="\xf\x31À";*z=L"\10\4\4\4\14";main(n){for(;*z;*++z&amp;&amp;putchar(45))for(n=*z;n--;printf("%x",P()&amp;15));}

Try it online!

Explanation:

/*
  P is a pointer to a function.
  The string literal contains actual machine code of the function:

  0F 31     rdtsc
  C3        ret

  0xc3 is the first byte of the UTF-8 representation of the character À
*/
(*P)() = "\xf\61À";

// encode uuid chunk lengths as literal characters
// we use wide characters with 'L' prefix because
// sizeof(wchar_t)==sizeof(int) for 64-bit gcc C on TIO
// so z is actually a zero-terminated string of ints
*z = L"\8\4\4\4\14"

main (n)
{
    for (
        ; 

        // loop until we reach the trailing zero
        *z;

        // increase the pointer and dereference it
        *++z 
             // and output a hyphen, if the pointer does not point at zero
             && putchar(45) 
    )
        // output a random hex string with length pointed at by z
        for (n = *z; n--; printf ("%x", P()&15));
}

Max Yekhlakov

Posted 2015-09-22T03:59:53.883

Reputation: 601

1

Hello and welcome to PPCG! 110 bytes.

– Jonathan Frech – 2018-08-08T07:16:13.610

@JonathanFrech Thank you! Your version is very impressive! – Max Yekhlakov – 2018-08-08T08:27:58.097

Suggest *z=L"\27\23\17\vz" instead of *z=L"\10\4\4\4\14" and for(n=32;n--;z+=printf("-%x"+(n!=*z),P()&15)-1) instead of for(;*z;*++z&&putchar(45))for(n=*z;n--;printf("%x",P()&15)) – ceilingcat – 2018-10-09T17:52:31.570

1

C (gcc),  94   91  86 bytes

main(i){srand(&i);i=803912;for(;i--%16||(i/=16)&&printf("-");printf("%x",rand()%16));}

Try it online!

I would have liked to suggest this version in a comment to Max Yekhlakov (his answer), but unfortunately I do not have the 50 needed reputation points yet, so here is my answer.

803912 is C4448 in hexadecimal, it describes how the output should be formatted (12-4-4-4-8), it is reversed because least significant digits will be read first.
 

Edits:

  • saved 3 bytes thanks to Jonathan Frech
  • saved 5 more bytes by replacing srand(time(0)) with srand(&i)

Annyo

Posted 2015-09-22T03:59:53.883

Reputation: 231

1main(){...;int i= can be main(i){...;i=. – Jonathan Frech – 2018-08-08T12:44:37.040

I've been thinking something, apparently srand() accept an unsigned int as its seed parameter. On tio.run, an unsigned int is 4 bytes long but the UUID is 16 bytes long. This means only a tiny fraction of the valid outputs (1/2^12) will be generated, thus my solution (as well as the previous one with time(0)) is not valid. What do you think ? – Annyo – 2018-08-27T07:49:09.690

The OP states Assuming that your language's PRNG is perfect, all valid outputs must have the same probability of being generated.. The seed entropy does not necessarily determine the RNG entropy, though it likely does (did not check the srand() implementation). However, srand() is to my knowledge reasonably uniform, so if the RNG was perfect, it would still be uniform. I therefore think your answer is valid. – Jonathan Frech – 2018-08-27T12:21:23.377

Ok, I understand. I could also submit my answer as a function, assuming srand() has already been done, and in this case there will be no doubt. But I'm not sure if this is allowed, other C/C++ submissions all seem to include srand() int the answer (unless it does not use rand()) – Annyo – 2018-08-27T12:34:59.007

81 bytes – ceilingcat – 2019-02-08T07:23:40.493

1

JavaScript REPL, 79 bytes

'66-6-6-6-666'.replace(/6/g,_=>(Math.random().toString(16)+'00000').slice(2,6))

Try it online!

Math.random may return 0. Adding 5 zeros make the slicing get 4 0s

l4m2

Posted 2015-09-22T03:59:53.883

Reputation: 5 985

1

Forth (gforth), 91 89 bytes

include random.fs
hex
: f 0 4 4 4 8 20 0 do dup i = if + ." -" then 10 random 1 .r loop ;

Try it online!

Explanation

Changes the base to hexadecimal, then outputs numbers/segments of the appropriate length with dashes at specified intervals

Code Explanation

include random.fs          \ include the random module
hex                        \ set the base to hexadecimal
: f                        \ start a new word definition
  0 4 4 4 8                \ enter the intervals to place dashes
  20 0 do                  \ start a counted loop from 0 to 0x20 (32 in decimal)
    dup i =                \ check if we are on a character that needs a dash
    if                     \ if we are
      +                    \ calculate the next character that gets a dash
      ." -"                \ output a dash
    then                   \ end the if block
    f random               \ get a random number between 0x0 and 0xf
    1 .r                   \ output it right-aligned in 1-character space
  loop                     \ end the loop
;                          \ end the word definition

reffu

Posted 2015-09-22T03:59:53.883

Reputation: 1 361

1

Java with Ten Foot Laser Pole v. 1.06, 126 bytes

String u(){return sj224.tflp.util.StringUtil.replace("aa-a-a-a-aaa","a",s->String.format("%04x",(int)(Math.random()*65536)));}

Tested with version 1.06 of the library, but this should work with any version 1.04 or newer.

SuperJedi224

Posted 2015-09-22T03:59:53.883

Reputation: 11 342

1

MATLAB/Octave , 95 bytes

a='-';b=strcat(dec2hex(randi(16,32,1)-1)');[b(1:8) a b(9:12) a b(13:16) a b(17:20) a b(21:32)]

costrom

Posted 2015-09-22T03:59:53.883

Reputation: 478

0

Tcl, 95 bytes

time {append g [format %x[expr [incr i]%4|$i<7|$i>21?"":"-"] [expr int(rand()*16)]]} 32;puts $g

Try it online!


Tcl, 97 bytes

time {append g [format %x[expr [incr i]%4||$i<7||$i>21?"":"-"] [expr int(rand()*16)]]} 32;puts $g

Try it online!


Tcl, 98 bytes

time {incr i;append g [format %x[expr $i%4||$i<7||$i>21?"":"-"] [expr int(rand()*16)]]} 32;puts $g

Try it online!

Tcl, 101 bytes

time {incr i;append g [format %x[expr !($i%4)&&$i>7&&$i<21?"-":""] [expr int(rand()*16)]]} 32;puts $g

Try it online!

Tcl, 104 bytes

proc D {n\ 4} {time {append g [format %x [expr int(rand()*16)]]} $n;set g}
puts [D 8]-[D]-[D]-[D]-[D 12]

Try it online!

sergiol

Posted 2015-09-22T03:59:53.883

Reputation: 3 055

0

Jelly, 17 bytes

ØhWẋ36X€”-“µÇŒð‘¦

Try it online!

Erik the Outgolfer

Posted 2015-09-22T03:59:53.883

Reputation: 38 134

0

SmileBASIC, 65 62 bytes

DEF G H?"-";:END
DEF H?HEX$(RND(65536),4);
END H G G G G H H H

I created a function to print 4 random hex digits: DEF H?HEX$(RND(65536),4);:END as well as 4 digits with a - after them: DEF G:H?"-";:END. Then it just has to call these functions a bunch of times.

12Me21

Posted 2015-09-22T03:59:53.883

Reputation: 6 110

0

Chip, 109 + 6 = 115 bytes

Requires flags -wc36, causing +6 bytes

!ZZZZZZZZZZZZZZZZZZZZZZ
,-----.,+vv--^----^---z
?]]]--R\acd
?xx+-)\\b
?x+x-)\\c
?^xx\--\d
`-xx]v~\e
f*`)'`-\g

Try it online!

Generates 4 random bits (the four ?'s) and converts to hex digits:

  • 0x0 - 0x9 => 0 - 9
  • 0xa - 0xe => b - f
  • 0xf => a

...a bit unconventional, but it saved me some bytes at no expense to the distribution of outcomes.

Phlarx

Posted 2015-09-22T03:59:53.883

Reputation: 1 366

0

Ruby, 51 47 + 14 = 65 61 bytes

Run with ruby -rsecurerandom (+14 bytes)

[8,4,4,4,12].map{|n|SecureRandom.hex n}.join ?-

Returns output

Piccolo

Posted 2015-09-22T03:59:53.883

Reputation: 261

0

Java, 192 181 bytes

interface T{static int t(){return (int)(Math.random()*65536);}static void main(String[]a){System.out.printf("aa-a-a-a-aaa".replaceAll("a","%04x"),t(),t(),t(),t(),t(),t(),t(),t());}}

SuperJedi224

Posted 2015-09-22T03:59:53.883

Reputation: 11 342

0

Octave, 106 105 103 99 96 bytes

function[]=f,g=@(l)[48:57,'a':'f'](randi(16,[1 l]));strjoin({g(8),g(4),g(4),g(4),g(12)},'-'),end

Try it Online

DimChtz

Posted 2015-09-22T03:59:53.883

Reputation: 916

0

Pyth, 34 bytes

VS32 aYO16)s.e?}km*d4r2 6+\-bb.HMY

Try it online!

trying to generate the indexes of where the "-" should go, and doing the replacement in a smaller way than hardcoding was an interesting challenge, and probably the hardest part.

Explanation

VS32 aYO16)                          // for N in range(32), append a random number 0-15 to the list Y
                              .HMY   // convert each number in Y to its Hex equivalent
                 m*d4r2 6            // make an array (of indexes) containing [8 12 16 20]. *4 mapped over (range(2,6) -> [2,3,4,5])
            .e                       // enumerating map on the random hex list. For each digit, index is k and value is b.
              ?}k        +\-bb       // map onto each digit the ternary question "is index k in the array of idexes?"
                                     // if no, replace with b (the value that was already there), if yes replace it with "-b".
           s                         // "".join( ) to make the list into a string

Tryer

Posted 2015-09-22T03:59:53.883

Reputation: 71

0

MBASIC, 92 bytes

1 FOR I=1 TO 32:PRINT HEX$(INT(RND*16));:IF I=8 OR I=12 OR I=16 OR I=20 THEN PRINT"-";
2 NEXT

Generates 32 "random" hex digits, adding a hyphen in the appropriate places.

Output:

D36A49D6-85AC-51DC-6D84-3BB1EB1A0816

wooshinyobject

Posted 2015-09-22T03:59:53.883

Reputation: 171

0

Pushy, 34 bytes

12N4448s$:Z15U&T)?39+;48+'.;L?45'.

Try it online!

12                                 \ Push 12 to stack
  N                                \ Remove printing delimiter (normally a newline)
   4448s                           \ Push 4448, then split into digits
                                   \ The stack is now [12, 4, 4, 4, 8]
        $                          \ While items left on stack:
         :                         \ (top item) times do:
          Z15U                     \    Push random(0, 15)
              &T)?                 \    If bigger than 10 (a hex digit):
                  39+;             \      Add 39 (offset from ASCII numbers to lowercase)
                      48+          \   Add 48, converting it into the correct character
                         '.        \   Print and pop this character
                           ;L?45'. \ Print a dash ('-'), unless stack is now empty.

FlipTack

Posted 2015-09-22T03:59:53.883

Reputation: 13 242

0

05AB1E, 19 bytes

ŽΣÌvy4*F15ÝΩh}'-}J¨

Try it online.

Explanation:

ŽΣÌ                   # Compressed integer 21113
   v            }     # Loop over each of its digits `y`
    y4*               #  Multiply `y` by 4
       F     }        #  Loop that many times
        15Ý           #   Create a list in the range [0,15]
           Ω          #   Pick a random number from it
            h         #   Convert it to hexadecimal
              '-     '#  Push string "-"
                 J    # After the loops, join the entire stack together
                  ¨   # And remove the trailing "-" (and output the result implicitly)

See this 05AB1E tip of mine (section How to compress large integers?) to understand why ŽΣÌ is 21113.

Kevin Cruijssen

Posted 2015-09-22T03:59:53.883

Reputation: 67 575

0

Python 3.8 (pre-release), 31 bytes

import uuid;print(uuid.uuid4())

Try it online!

Python has an inbuilt package for this specific task. Enjoy :P

Divy

Posted 2015-09-22T03:59:53.883

Reputation: 51

3This doesn't follow the spec, since the first number of the third segment is always 4 (plus the questions says No built-ins) – Jo King – 2019-12-06T10:40:42.247

Ahh sorry, I didn't read the question properly. I am very impatient :P. Also, could you help me understand why the 3rd segment always starts with 4? isn't uuid4 supposed to generate a random UUID? – Divy – 2019-12-07T11:11:57.907

From the comments under the question: UUID has a required format of xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx where y is one of [89AB]. I personally don't know why this is – Jo King – 2019-12-07T22:09:52.393

0

JavaScript (ES6), 79 bytes

a=>[8,4,4,4,12].map(g=e=>e?(16*Math.random()|0).toString(16)+g(e-1):"").join`-`

Naruyoko

Posted 2015-09-22T03:59:53.883

Reputation: 459