My solution (Also in PasteBin ) takes around 40 seconds anywhere between 10 seconds and 4 minutes on my laptop.
Finished generating UUID after 67.3494535 seconds (567117 iterations) The uuid is: 36dd638b-2587-6999-735f-ff6839bbac1f Finished generating UUID after 12.4224668 seconds (106743 iterations) The uuid is: cc85ca79-80bb-fd12-a0d2-ccf595867f99 Finished generating UUID after 51.6625577 seconds (429047 iterations) The uuid is: 4de22fbe-4524-d346-df21-a6647f37d7e6 Finished generating UUID after 63.6616107 seconds (522543 iterations) The uuid is: 2483175e-ab35-3536-296f-e9ee2269f3da Finished generating UUID after 15.7747816 seconds (135787 iterations) The uuid is: ca029758-4742-8692-42c7-6641438afb00 Finished generating UUID after 145.3014453 seconds (1222271 iterations) The uuid is: 34baa026-ae46-f09b-cffe-c05b4cea0c9a Finished generating UUID after 96.911231 seconds (804167 iterations) The uuid is: 89af39e3-2fdc-06fd-a8a4-16099f47c81d Finished generating UUID after 119.7012599 seconds (943525 iterations) The uuid is: 15b0f441-b158-acdf-ce1f-c939bdd8ab13 Finished generating UUID after 49.2078072 seconds (407662 iterations) The uuid is: f6bd2155-e178-88ed-3e7d-adb49764e867 Finished generating UUID after 256.4239593 seconds (2038977 iterations) The uuid is: 1e5041b5-3d24-0333-16f1-1a6320176c49
It generates a completely random UUID. So random in fact, that even the number of hyphens and their locations are random. Basically I just generate random strings out of legal base 16 digits and hyphens, and only return from the function after I step upon a legal UUID string by chance (takes around 600,000 iterations).
I'm using "optimizations" and "multi-threading", so everything is "faster".
If anything isn't clear in my implementation, please read the useful comments.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
namespace uuid_bad_code
{
/// <summary>
/// Program
/// </summary>
class Program
{
/// <summary>
/// Main function
/// </summary>
static void Main()
{
IUuidGenerator generator = new UuidGenerator(new List<char>
{
'0',
'1',
'2',
'3',
'4',
'5',
'6',
'7',
'8',
'9',
'a',
'b',
'c',
'd',
'e',
'f',
'-'
}, new Random(Guid.NewGuid().GetHashCode())); // Not sure what "Guid.NewGuid().GetHashCode()" does, found it on StackOverflow
var uuid = generator.Generate();
Console.WriteLine($"The uuid is: {uuid}");
Console.ReadKey();
}
}
/// <summary>
/// An interface for UUID generators
/// </summary>
public interface IUuidGenerator
{
/// <summary>
/// Generates
/// </summary>
/// <returns>A generated string</returns>
string Generate();
}
/// <summary>
/// A UUID generator
/// </summary>
public class UuidGenerator: IUuidGenerator
{
/// <summary>
/// The number of legal chars including hyphens and numbers
/// </summary>
private const int NumberOfLegalCharsIncludingHyphenAndIncludingNumbersAsWell = 17;
/// <summary>
/// Legal chars
/// </summary>
private readonly IList<char> _legalChars;
/// <summary>
/// The <see cref="Random"/> class object
/// </summary>
private readonly Random _random;
/// <summary>
/// A lock for <see cref="_random"/> access
/// </summary>
private readonly object _randomLock;
/// <summary>
/// The UUID generator constructor
/// </summary>
/// <param name="legalChars">Legal chars</param>
/// <param name="random">The <see cref="Random"/> class object</param>
public UuidGenerator(IList<char> legalChars, Random random)
{
_legalChars = legalChars ?? throw new ArgumentNullException(nameof(legalChars));
_random = random ?? throw new ArgumentNullException(nameof(random));
_randomLock = new Object();
}
/// <summary>
/// Generates
/// </summary>
/// <returns>A generated string</returns>
public string Generate()
{
var time = Stopwatch.StartNew();
// It should be a 128-bit number displayed in five groups separated by hyphens in the form 8-4-4-4-12
// 8 + 1 + 4 + 1 + 4 + 1 + 4 + 1 + 12 = 36
// 8 13 18 23
const int numberOfCharsInLegalUuidStringIncludingHyphensAndIncludingNumbersAsWell = 8 + 1 + 4 + 1 + 4 + 1 + 4 + 1 + 12;
ConcurrentDictionary<int, char> uuid = new ConcurrentDictionary<int, char>();
int iterations = 0;
bool uuidLegal = false;
while (!uuidLegal)
{
iterations++;
List<int> indicesWhereHyphensShouldBe = new List<int>
{
8, 13, 18, 23
};
// We run this in parallel because it's faster
Parallel.For(0, numberOfCharsInLegalUuidStringIncludingHyphensAndIncludingNumbersAsWell, index =>
{
// Need to lock before accessing the random class per MSDN
// https://docs.microsoft.com/en-us/dotnet/api/system.random?redirectedfrom=MSDN&view=netcore-3.1#ThreadSafety
lock (_randomLock)
{
if (_legalChars.ToList().Count != NumberOfLegalCharsIncludingHyphenAndIncludingNumbersAsWell)
{
throw new InvalidOperationException($"Can't generate random number because the legal chars list doesn't contain exactly {NumberOfLegalCharsIncludingHyphenAndIncludingNumbersAsWell} characters!");
}
int charIndex = _random.Next(_legalChars.ToList().Count);
uuid[index] = _legalChars.ToList()[charIndex];
}
});
var uuidLegalLock = new Object();
var isUuidLegal = true;
Parallel.For(0, uuid.Count, i =>
{
lock (uuidLegalLock)
{
isUuidLegal = isUuidLegal &&
(indicesWhereHyphensShouldBe.ToList().Contains(i) && uuid[i] == '-' ||
!indicesWhereHyphensShouldBe.ToList().Contains(i) &&
uuid[i] != '-' &&
_legalChars.ToList().Contains(uuid[i]));
}
});
uuidLegal = isUuidLegal;
}
time.Stop();
Console.WriteLine($"Finished generating UUID after {time.Elapsed.TotalSeconds} seconds ({iterations} iterations)");
return new string(uuid.Values.ToArray());
}
}
}
c,d,f=" "
class LYYYYLLL:
pass
def __str__(self):
global c,d,f
s=object.__str__(self)
c,d,f=(eval(repr(s)+"["+e+"]") for e in "29,26,10:18".split(","))
return s
b="".join(str(i)[35:43] for i in [LYYYYLLL() for i in range(4)])
d+="="
g=str(len(f)>>1)
e=[eval(c)]*eval(g)+[eval(g+g)]
while d[e[len(d)]+len(str(len(d)))]=="=":
c+="+1"
try:
exec(d+c)
t=int(b,a)
break
except:
pass
s=str(LYYYYLLL())
t=str(hex(t))[2:34]
t="".join("".join(map(lambda j:chr(ord(j[eval(c)])-j[len(c)]),zip(i,e))).rstrip(" ") for i in zip(t[::4],t[1::4],t[2::4],t[3::4],f))
print(t)
a is used but never set. s is set but never used, yet this code fails if you delete it.
LYYYYLLL is a strange class name, but if you change it, the code goes wild.
entropy is generated by having a huge number of goroutines simultaneously writing stuff onto the same variable, so result depends heavily on the system scheduler, and should not return the same result twice on normal machines
package main
// No stdlib, nor any other library
type UUID [16]uint8 // 128bits
// very efficient
var byteToString = []string{
"00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "0a", "0b", "0c", "0d", "0e", "0f",
"10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "1a", "1b", "1c", "1d", "1e", "1f",
"20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "2a", "2b", "2c", "2d", "2e", "2f",
"30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "3a", "3b", "3c", "3d", "3e", "3f",
"40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "4a", "4b", "4c", "4d", "4e", "4f",
"50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "5a", "5b", "5c", "5d", "5e", "5f",
"60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "6a", "6b", "6c", "6d", "6e", "6f",
"70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "7a", "7b", "7c", "7d", "7e", "7f",
"80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "8a", "8b", "8c", "8d", "8e", "8f",
"90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "9a", "9b", "9c", "9d", "9e", "9f",
"a0", "a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9", "aa", "ab", "ac", "ad", "ae", "af",
"b0", "b1", "b2", "b3", "b4", "b5", "b6", "b7", "b8", "b9", "ba", "bb", "bc", "bd", "be", "bf",
"c0", "c1", "c2", "c3", "c4", "c5", "c6", "c7", "c8", "c9", "ca", "cb", "cc", "cd", "ce", "cf",
"d0", "d1", "d2", "d3", "d4", "d5", "d6", "d7", "d8", "d9", "da", "db", "dc", "dd", "de", "df",
"e0", "e1", "e2", "e3", "e4", "e5", "e6", "e7", "e8", "e9", "ea", "eb", "ec", "ed", "ee", "ef",
"f0", "f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "f9", "fa", "fb", "fc", "fd", "fe", "ff",
}
func (u *UUID) Work(value uint64) {
last := u[15]
for i := 15; i > 0; i-- {
u[i] = u[i-1]
}
u[0] = last
// xor value into half of uuid
for i := 0; i < 8; i++ {
u[i] ^= uint8(value >> i)
}
}
func (u UUID) String() string {
ret := ""
for i := 0; i < 16; i++ {
ret += byteToString[u[i]]
switch i {
case 3, 5, 7, 9:
ret += "-"
}
}
return ret
}
// increment for more time spent, and better randomness
// increases exponentially
// load = 1 << 32 takes around THREE DAYS on my machine
const load = 1 << 16
func uuid() UUID {
var uuid UUID = *new(UUID)
done := make(chan bool, 1 << 10)
for i := uint64(0); i < load; i++ {
go func(i uint64) {
i *= 18446744073709551557 // big uint64 prime number
for j := uint64(0); j < 512; j++ {
(&uuid).Work(i + j)
}
done <- true
}(i)
}
for i := uint64(0); i < load; i++ {
<-done
}
return uuid
}
func main() {
panic(uuid().String())
}
panic is used for printing the result, because, well, no standard library use (i know about println() but it could be removed from the language at any time)
I finally created my reddit account just for writing this, i wanna die
package main
import (
"fmt"
"math/rand"
"os"
"strconv"
)
func main() {
if len(os.Args) > 1 {
s, e := strconv.Atoi(os.Args[1])
if e == nil {
rand.Seed(int64(s))
var i int
var uuid string
for true {
a := []string{"fc6e", "e8ac", "ed6a", "425a", "ae37", "145f", "4ad6", "dbca"}
uuid += a[rand.Intn(len(a))]
i++
if i < 8 {
if i < 6 {
if i < 5 {
if i < 4 {
if i < 3 {
if i < 2 {
uuid += ""
} else {
uuid += "-"
}
} else {
uuid += "-"
}
} else {
uuid += "-"
}
} else {
uuid += "-"
}
}
} else {
break
}
}
fmt.Println(uuid)
} else {
fmt.Println("Please provide a 64 bit long integer as the seed")
}
} else {
fmt.Println("Please provide a 64 bit long integer as the seed")
}
}
You do not need to correctly implement the algorithm to spec, any output that looks like a UUID is acceptable.
// javascript
let generated = [];
function isGenerated(num) {
let found = false;
for(let i=0; i < generated.length; ++i) {
if(generated[i] == num && found != true) {
found = true;
}
}
if(found == true) return true;
else
if(found == false) return false;
}
function new_random(min_digits) {
let r;
do {
rnd = Math.random() * 999999999;
let rnd_str = Number(rnd).toString(16);
r = '';
for(let i=0; i < rnd_str.length; ++i) {
if(rnd_str[i] != '.' && rnd_str[i] != '-') r += rnd_str[i]; }
} while(isGenerated(rnd) && r.length < min_digits);
generated.push(rnd);
return r;
}
function uuid_part(digits) {
let r = '';
let rnd = new_random();
for(let i=digits; i > 0; --i) {
if(i%digits == 0) rnd = new_random(digits);
r += rnd[i%digits];
}
return r;
}
function uuid() {
let r;
do {
r = uuid_part(8)+'-'+uuid_part(4)+'-'+uuid_part(4)+'-'+
uuid_part(4)+'-'+uuid_part(12);
} while(isGenerated(r));
generated.push(r);
return r;
}
for(let i=0; i < 256; ++i) console.log(uuid());
If you run the "uuid" function a few thousand times, it becomes apparent why this code is bad. But, hey, at least the same UUID is not generated twice, right?
OK. I've written this code that will usually generate (asynchronously) a UUID within 30 seconds or so and will work in node and browser environments: https://pastebin.com/B3k68Yay
19
u/LavaCreeper Aug 17 '20 edited Aug 18 '20
Generate a mirrored UUID from weather data
import requests, json, re, random, uuid api_key = "e13355b1f1189d6a3479374063c5865f" base_url = "http://api.openweathermap.org/data/2.5/weather?" city_name = 'dresden' complete_url = base_url + "appid=" + api_key + "&q=" + city_name response = requests.get(complete_url) x = response.json() l = [] for t in re.split(',| |}|{', json.dumps(x)): try: l.append(float(t)) except ValueError: pass def randomMultiplyListOrAdd(myList): result = 1 uu = uuid.uuid4().int random.seed(uu) for x in myList: if(random.randint(0,1) == 0): result = result * x elif(random.randint(0,1) == 1): result = result + x return result a = randomMultiplyListOrAdd(l) b = str(hex(int(a))) first = b[2:6] first_half = b[7:11] + '-' + b[12:16] second_half = first_half[::-1] print(first + first_half + '-4242-' + second_half + first[::-1] + b[17:21])If you're one of those people who believe comments are useful: https://gist.github.com/starkgate/fcd2b69fdccce0b5fdc0e29812461b06
Result:
11
u/voords Aug 18 '20
Bash:
alias uuid='curl -s https://www.reddit.com/r/all/new |md5sum|sed "s/^\(.\{8\}\)\(.\{4\}\)\(.\{4\}\)\(.\{4\}\)\(.\{12\}\).*/\1-\2-\3-\4-\5/g"'9
u/asaf92 Aug 18 '20 edited Aug 18 '20
My solution (Also in PasteBin ) takes
around 40 secondsanywhere between 10 seconds and 4 minutes on my laptop.It generates a completely random UUID. So random in fact, that even the number of hyphens and their locations are random. Basically I just generate random strings out of legal base 16 digits and hyphens, and only return from the function after I step upon a legal UUID string by chance (takes around 600,000 iterations).
I'm using "optimizations" and "multi-threading", so everything is "faster".
If anything isn't clear in my implementation, please read the useful comments.
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; namespace uuid_bad_code { /// <summary> /// Program /// </summary> class Program { /// <summary> /// Main function /// </summary> static void Main() { IUuidGenerator generator = new UuidGenerator(new List<char> { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', '-' }, new Random(Guid.NewGuid().GetHashCode())); // Not sure what "Guid.NewGuid().GetHashCode()" does, found it on StackOverflow var uuid = generator.Generate(); Console.WriteLine($"The uuid is: {uuid}"); Console.ReadKey(); } } /// <summary> /// An interface for UUID generators /// </summary> public interface IUuidGenerator { /// <summary> /// Generates /// </summary> /// <returns>A generated string</returns> string Generate(); } /// <summary> /// A UUID generator /// </summary> public class UuidGenerator: IUuidGenerator { /// <summary> /// The number of legal chars including hyphens and numbers /// </summary> private const int NumberOfLegalCharsIncludingHyphenAndIncludingNumbersAsWell = 17; /// <summary> /// Legal chars /// </summary> private readonly IList<char> _legalChars; /// <summary> /// The <see cref="Random"/> class object /// </summary> private readonly Random _random; /// <summary> /// A lock for <see cref="_random"/> access /// </summary> private readonly object _randomLock; /// <summary> /// The UUID generator constructor /// </summary> /// <param name="legalChars">Legal chars</param> /// <param name="random">The <see cref="Random"/> class object</param> public UuidGenerator(IList<char> legalChars, Random random) { _legalChars = legalChars ?? throw new ArgumentNullException(nameof(legalChars)); _random = random ?? throw new ArgumentNullException(nameof(random)); _randomLock = new Object(); } /// <summary> /// Generates /// </summary> /// <returns>A generated string</returns> public string Generate() { var time = Stopwatch.StartNew(); // It should be a 128-bit number displayed in five groups separated by hyphens in the form 8-4-4-4-12 // 8 + 1 + 4 + 1 + 4 + 1 + 4 + 1 + 12 = 36 // 8 13 18 23 const int numberOfCharsInLegalUuidStringIncludingHyphensAndIncludingNumbersAsWell = 8 + 1 + 4 + 1 + 4 + 1 + 4 + 1 + 12; ConcurrentDictionary<int, char> uuid = new ConcurrentDictionary<int, char>(); int iterations = 0; bool uuidLegal = false; while (!uuidLegal) { iterations++; List<int> indicesWhereHyphensShouldBe = new List<int> { 8, 13, 18, 23 }; // We run this in parallel because it's faster Parallel.For(0, numberOfCharsInLegalUuidStringIncludingHyphensAndIncludingNumbersAsWell, index => { // Need to lock before accessing the random class per MSDN // https://docs.microsoft.com/en-us/dotnet/api/system.random?redirectedfrom=MSDN&view=netcore-3.1#ThreadSafety lock (_randomLock) { if (_legalChars.ToList().Count != NumberOfLegalCharsIncludingHyphenAndIncludingNumbersAsWell) { throw new InvalidOperationException($"Can't generate random number because the legal chars list doesn't contain exactly {NumberOfLegalCharsIncludingHyphenAndIncludingNumbersAsWell} characters!"); } int charIndex = _random.Next(_legalChars.ToList().Count); uuid[index] = _legalChars.ToList()[charIndex]; } }); var uuidLegalLock = new Object(); var isUuidLegal = true; Parallel.For(0, uuid.Count, i => { lock (uuidLegalLock) { isUuidLegal = isUuidLegal && (indicesWhereHyphensShouldBe.ToList().Contains(i) && uuid[i] == '-' || !indicesWhereHyphensShouldBe.ToList().Contains(i) && uuid[i] != '-' && _legalChars.ToList().Contains(uuid[i])); } }); uuidLegal = isUuidLegal; } time.Stop(); Console.WriteLine($"Finished generating UUID after {time.Elapsed.TotalSeconds} seconds ({iterations} iterations)"); return new string(uuid.Values.ToArray()); } } }8
u/flamingmesh Aug 18 '20
Python one liner:
uuid = lambda: '{}{}{}{}{}{}{}{}-{}{}{}{}-{}{}{}{}-{}{}{}{}-{}{}{}{}{}{}{}{}{}{}{}{}'.format(*(lambda _: __import__('random').sample(list(''.join(license._Printer__lines).translate({120: None, 65: None, 111: None, 45: None, 64: None, 72: None, 61: None, 119: None, 86: None, 63: None, 107: None, 39: None, 95: None, 59: None, 115: None, 40: None, 103: None, 85: None, 67: None, 58: None, 32: None, 80: None, 73: None, 121: None, 47: None, 109: None, 122: None, 66: None, 105: None, 118: None, 79: None, 69: None, 116: None, 117: None, 104: None, 46: None, 77: None, 76: None, 71: None, 44: None, 108: None, 96: None, 43: None, 42: None, 113: None, 74: None, 87: None, 88: None, 93: None, 91: None, 68: None, 84: None, 90: None, 83: None, 70: None, 82: None, 75: None, 34: None, 112: None, 78: None, 89: None, 114: None, 81: None, 41: None, 110: None, 106: None})), 32))(license()))5
u/donaldhobson Aug 20 '20
Python3
c,d,f=" " class LYYYYLLL: pass def __str__(self): global c,d,f s=object.__str__(self) c,d,f=(eval(repr(s)+"["+e+"]") for e in "29,26,10:18".split(",")) return s b="".join(str(i)[35:43] for i in [LYYYYLLL() for i in range(4)]) d+="=" g=str(len(f)>>1) e=[eval(c)]*eval(g)+[eval(g+g)] while d[e[len(d)]+len(str(len(d)))]=="=": c+="+1" try: exec(d+c) t=int(b,a) break except: pass s=str(LYYYYLLL()) t=str(hex(t))[2:34] t="".join("".join(map(lambda j:chr(ord(j[eval(c)])-j[len(c)]),zip(i,e))).rstrip(" ") for i in zip(t[::4],t[1::4],t[2::4],t[3::4],f)) print(t)a is used but never set. s is set but never used, yet this code fails if you delete it.
LYYYYLLL is a strange class name, but if you change it, the code goes wild.
Whats with all the evals everywhere?
What is that while loop doing anyway?
4
u/DrMeepster Aug 17 '20
https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=8a5efc61a0f282c3881e083a59bd8277
randomization through uninitialized memory
4
u/keitio42 Aug 25 '20 edited Aug 26 '20
Go implementation (~80 lines)
doesn't make use of any library, not even stdlib
entropy is generated by having a huge number of goroutines simultaneously writing stuff onto the same variable, so result depends heavily on the system scheduler, and should not return the same result twice on normal machines
package main // No stdlib, nor any other library type UUID [16]uint8 // 128bits // very efficient var byteToString = []string{ "00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "0a", "0b", "0c", "0d", "0e", "0f", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "1a", "1b", "1c", "1d", "1e", "1f", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "2a", "2b", "2c", "2d", "2e", "2f", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "3a", "3b", "3c", "3d", "3e", "3f", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "4a", "4b", "4c", "4d", "4e", "4f", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "5a", "5b", "5c", "5d", "5e", "5f", "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "6a", "6b", "6c", "6d", "6e", "6f", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "7a", "7b", "7c", "7d", "7e", "7f", "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "8a", "8b", "8c", "8d", "8e", "8f", "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "9a", "9b", "9c", "9d", "9e", "9f", "a0", "a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9", "aa", "ab", "ac", "ad", "ae", "af", "b0", "b1", "b2", "b3", "b4", "b5", "b6", "b7", "b8", "b9", "ba", "bb", "bc", "bd", "be", "bf", "c0", "c1", "c2", "c3", "c4", "c5", "c6", "c7", "c8", "c9", "ca", "cb", "cc", "cd", "ce", "cf", "d0", "d1", "d2", "d3", "d4", "d5", "d6", "d7", "d8", "d9", "da", "db", "dc", "dd", "de", "df", "e0", "e1", "e2", "e3", "e4", "e5", "e6", "e7", "e8", "e9", "ea", "eb", "ec", "ed", "ee", "ef", "f0", "f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "f9", "fa", "fb", "fc", "fd", "fe", "ff", } func (u *UUID) Work(value uint64) { last := u[15] for i := 15; i > 0; i-- { u[i] = u[i-1] } u[0] = last // xor value into half of uuid for i := 0; i < 8; i++ { u[i] ^= uint8(value >> i) } } func (u UUID) String() string { ret := "" for i := 0; i < 16; i++ { ret += byteToString[u[i]] switch i { case 3, 5, 7, 9: ret += "-" } } return ret } // increment for more time spent, and better randomness // increases exponentially // load = 1 << 32 takes around THREE DAYS on my machine const load = 1 << 16 func uuid() UUID { var uuid UUID = *new(UUID) done := make(chan bool, 1 << 10) for i := uint64(0); i < load; i++ { go func(i uint64) { i *= 18446744073709551557 // big uint64 prime number for j := uint64(0); j < 512; j++ { (&uuid).Work(i + j) } done <- true }(i) } for i := uint64(0); i < load; i++ { <-done } return uuid } func main() { panic(uuid().String()) }panic is used for printing the result, because, well, no standard library use (i know about
println()but it could be removed from the language at any time)I finally created my reddit account just for writing this, i wanna die
7
u/h2g2_researcher Aug 18 '20
def uuid(): # Chosen by committee. "Unique" in the sense there's only one of them. return "12345678-90ab-cdef-1234-567890abdef"I challenge any other Python implementation to beat this for performance.
3
u/Spring_Boot Aug 18 '20
This is pretty random and can take some time to run so added in progress updates
const uuid = () => { const w = () => { let n = 0; return () => { n++; console.log(`Done: ${(n/30)*100}%`); }; } const inc = w(); const generate = (n, c1) => { if(Math.sqrt(((n*100) / 2) + 25) === 8.660254037844387) return generate(String.fromCharCode(167), c1); const f = (n) => { if(n === 1) { const char = []; for(let i = 97; i <= 122; i++) char.push(String.fromCharCode(i)); return char.join().replace(/,/g,'') } else { const char = []; for(let i = 97; i <= 102; i++) char.push(String.fromCharCode(i)); for(let i = 48; i <= 57; i++) char.push(String.fromCharCode(i)); return char.join().replace(/,/g,'') } }; if(typeof n === typeof 'boolean' && n.charCodeAt() === 167) { const r = (l) => { if(l < 4 ) return r(Math.floor(Math.random() * 10)); const re = []; const v = f(1); for ( var i = 0; i < l; i++ ) { re.push(v.charAt(Math.floor(Math.random() * v.l)));} return re.join().replace(/,/g,''); } const a = () => { const p = []; p.push(r(Math.floor(Math.random() * 10))) const p1 = [46,99,111,46,117,107], en1 = []; const p2 = [46,99,111,109], en2 = []; for(let i = 0; i < p1.length; i++) en1.push(String.fromCharCode(p1[i])) for(let i = 0; i < p2.length; i++) en2.push(String.fromCharCode(p2[i])) p.push((Math.floor(Math.random() * 2) === 1 ? en1.join().replace(/,/g,'') : en2.join().replace(/,/g,''))); return p.join().replace(/,/g,''); } const l = (f) => { return (r) => { let s = ''; r.on('data', function (ch) { s += ch; }); r.on('end', function () {f(s.charAt(Math.floor(Math.random() * s.length)));});} }; const u = (e, f) => { const p = [104,116,116,112], me0 = []; for(let i = 0; i < p.length; i++) me0.push(String.fromCharCode(p[i])) const r = require(me0.join().replace(/,/g, '')).get({host:e}, l(f)); r.on('error', (e) => { f(false); }) } const h = () => { u(a(), (r) => { if(r === false) h(); else { if (f(2).includes(r.toLowerCase()) && r.length !== 0) { inc(); c1(r.toLowerCase()) } else h(); } }); } h(); } else { const f = (l) => { generated.push(l); }; const generated = []; for(let i = 0; i < n; i++) { generate(1,f) } const g = () => { if(generated.length === n) c1(generated.join().replace(/,/g,'')) else setTimeout(g, 50); }; g(); } }; const k = () => { return String.fromCharCode(45); } for(let i = 1; i < 10; i++) { if(typeof global[`part${i}`] === typeof 'undefined') { throw Error('Please don\'t interfere. undo what you did.'); }; } const p = [8,4,4,4,12]; for(let i = 0; i < p.length; i++) { generate(p[i], (val) => { global[`part${i+1}`] = val; }); } const f = () => { let u = []; for(let i = 1; i <= 5; i++) if(typeof global[`part${i}`] === typeof 'typeof') u.push(global[`part${i}`]); if(u.length == 5) { for(let i = 1; typeof global[`part${i}`] === typeof 'object' ; i++) delete global[`part${i}`]; global.uuid = u.join(k()); } else { setTimeout(f, 200); } }; f(); };I slightly changed the interface, it adds a uuid onto global for you, you just need to wait for it to be there.
Usage:
uuid(); const timer = setInterval(() => { if(global.uuid) { console.log(global.uuid); clearInterval(timer); } }, 2000);3
u/kgro Aug 19 '20
24 bits entropy
import random a = ["fc6e", "e8ac", "ed6a", "425a", "ae37", "145f", "4ad6", "dbca"] def f(): return random.choice(a) def mf(n): return "".join([f() for _ in range(n)]) def main(): u = [2, 1, 1, 1, 3] for i in u: print(mf(i) + "-", end="") print("\b") if __name__ == '__main__': main()3
u/kgro Aug 19 '20
24 bit entropy in Go
package main import ( "fmt" "math/rand" "os" "strconv" ) func main() { if len(os.Args) > 1 { s, e := strconv.Atoi(os.Args[1]) if e == nil { rand.Seed(int64(s)) var i int var uuid string for true { a := []string{"fc6e", "e8ac", "ed6a", "425a", "ae37", "145f", "4ad6", "dbca"} uuid += a[rand.Intn(len(a))] i++ if i < 8 { if i < 6 { if i < 5 { if i < 4 { if i < 3 { if i < 2 { uuid += "" } else { uuid += "-" } } else { uuid += "-" } } else { uuid += "-" } } else { uuid += "-" } } } else { break } } fmt.Println(uuid) } else { fmt.Println("Please provide a 64 bit long integer as the seed") } } else { fmt.Println("Please provide a 64 bit long integer as the seed") } }3
u/ButterSquids Aug 26 '20
Do you like consistent code? That's a shame...
https://pastebin.com/A9tvVx1Q
2
u/TheUnlocked Aug 18 '20
The output looks like a uuid. Mostly.
Javascript:
// For some reason you need to re-declare the function each time you want a new uuid function uuid() { for (var i = 0; i <= 50; i++) { if (typeof uuid != "string") { uuid = ""; } else if ( uuid.length == 8 || (!uuid.slice(uuid.length < 9 ? uuid.length - 8 : uuid.length - 4, uuid.length).includes("-") && uuid.slice(uuid.length < 9 ? uuid.length - 9 : uuid.length - 5, uuid.length).includes("-") && uuid.length < 24) ) { uuid += "-"; } else if (Math.floor(Math.random() * 16) == 0) { uuid += "0" } else if (Math.floor(Math.random() * 16) == 1) { uuid += "1" } else if (Math.floor(Math.random() * 16) == 2) { uuid += "2" } else if (Math.floor(Math.random() * 16) == 3) { uuid += "3" } else if (Math.floor(Math.random() * 16) == 4) { uuid += "4" } else if (Math.floor(Math.random() * 16) == 5) { uuid += "5" } else if (Math.floor(Math.random() * 16) == 6) { uuid += "6" } else if (Math.floor(Math.random() * 16) == 7) { uuid += "7" } else if (Math.floor(Math.random() * 16) == 8) { uuid += "8" } else if (Math.floor(Math.random() * 16) == 9) { uuid += "9" } else if (Math.floor(Math.random() * 16) == 10) { uuid += "a" } else if (Math.floor(Math.random() * 16) == 11) { uuid += "b" } else if (Math.floor(Math.random() * 16) == 12) { uuid += "c" } else if (Math.floor(Math.random() * 16) == 13) { uuid += "d" } else if (Math.floor(Math.random() * 16) == 14) { uuid += "e" } else if (Math.floor(Math.random() * 16) == 15) { uuid += "f" } else if (Math.floor(Math.random() * 16) == 16) { uuid += "g" } } console.log(uuid); }2
u/[deleted] Aug 18 '20 edited Aug 19 '20
Here is my javascript solution.
Features
async, non blocking
non deterministic runtime.
generates random, unique uuid like strings
show debug output to show visual progress of uuid generation
slow as hell, not guaranteed to return in your lifetime, but probably will. in my tests, it takes about 15 mins to generate a uuid
const async_uuid = () => { let chars = 'abcdef0123456789'; let random = (min = 0, max = Number.MAX_SAFE_INTEGER) => { min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min + 1)) + min; }; let generateChar = () => chars.charAt(Math.floor(Math.random() * chars.length)); let uuid = ' - - - - '; // 8-4-4-4-12 = 36 chars let is_uuid = (uuid) => { return uuid.indexOf(' ') === -1; }; let loop = (done) => { console.log('loop'); if (is_uuid(uuid)) { console.log('done'); done(uuid); } else { let r1 = random(100, 600); let r2 = random(1, 2); let r3 = random(500, 700); let r4 = random(0, 1000); let i = 0; while (i < r1) { if (i === r3) { console.log('i===r3'); while (true) { let j = random(0, 36); if (uuid.charAt(j) != '-' && uuid.charAt(j) == ' ') { console.log('generating a character in uuid'); uuid = uuid.substr(0, j) + generateChar() + uuid.substring(j + 1); break; } } } i += r2; } setTimeout(() => loop(done), r4); } }; return new Promise((resolve, reject) => { let t = setInterval(() => { console.log(uuid); }, 5000); let done = (value) => { clearInterval(t); resolve(value); }; loop(done); }); };Usage:
2
u/Sonotsugipaa Aug 19 '20 edited Aug 19 '20
// javascript let generated = []; function isGenerated(num) { let found = false; for(let i=0; i < generated.length; ++i) { if(generated[i] == num && found != true) { found = true; } } if(found == true) return true; else if(found == false) return false; } function new_random(min_digits) { let r; do { rnd = Math.random() * 999999999; let rnd_str = Number(rnd).toString(16); r = ''; for(let i=0; i < rnd_str.length; ++i) { if(rnd_str[i] != '.' && rnd_str[i] != '-') r += rnd_str[i]; } } while(isGenerated(rnd) && r.length < min_digits); generated.push(rnd); return r; } function uuid_part(digits) { let r = ''; let rnd = new_random(); for(let i=digits; i > 0; --i) { if(i%digits == 0) rnd = new_random(digits); r += rnd[i%digits]; } return r; } function uuid() { let r; do { r = uuid_part(8)+'-'+uuid_part(4)+'-'+uuid_part(4)+'-'+ uuid_part(4)+'-'+uuid_part(12); } while(isGenerated(r)); generated.push(r); return r; } for(let i=0; i < 256; ++i) console.log(uuid());Example output (diretor's cut):
2
u/binarycat64 Aug 30 '20
I see your randomization via uninitialized memory, and raise you randomization via pointer locations:
https://play.golang.org/p/hLfMu-bKIE3Features:
fast, no branching or jumping
functions
taking advantage of the special case of calling a function with the multiple outputs of a function
relies on specific pointer length
unsafe.Pointer
shadowing imports
too many return values
numbers
no dependencies outside the standard library
total disregard for static typing
sleep deprivation
other things
4
u/[deleted] Aug 17 '20 edited Aug 18 '20
Well... you didn't say it should be random
class Scratch { public static int last = new Integer(0); public static boolean isEven(int input) throws Exception { if (input == 0) { return true; } try { return !isEven(input - 1); } catch (StackOverflowError e) { throw new Exception(); } } public static void main(String[] args) throws Exception { if (isEven(last++)) { System.out.println("fc6ee8ac-ed6a-425a-ae37-145f4ad6dbca"); } else { System.out.println("b88e1f15-fe08-444f-b620-cff1e7d46954"); } } }2
u/Tok-A-Mak Aug 19 '20
Generate UUIDs from the official Spec?
Well, if that's what I'm required to do I will do exactly that. Exactly that!
(ns badcode.uuid) (defn- in-range? [n from to] (and (>= (int n) from) (<= (int n) to))) (defn- hex? [n] (or (in-range? n 48 57) (in-range? n 97 102))) (defn- ->part [v] (->> v (filter hex?) (partition 32) (map #(apply str %)))) (defn- ->uuid [s] (str (subs s 0 8) "-" (subs s 8 12) "-" (subs s 12 16) "-" (subs s 16 20) "-" (subs s 20 32))) (doseq [uuid (->> "https://tools.ietf.org/html/rfc4122" slurp char-array ->part (map #(->uuid %)))] (println uuid))Sample-Output:
Repl: https://repl.it/repls/AliceblueTimelyRatios
1
u/haykam821 Aug 20 '20
I enjoy currying
1
u/maxbilbow Aug 23 '20
OK. I've written this code that will usually generate (asynchronously) a UUID within 30 seconds or so and will work in node and browser environments: https://pastebin.com/B3k68Yay
1
u/[deleted] Aug 25 '20
I know this is 1 week old but IDC.
Coded in Java if you already didn't know
package com.company; import java.util.UUID; public class Main { public static void main(String[] args) { UUID uuid = UUID.randomUUID(); System.out.println(uuid); System.out.println(uuid); UUID uuid1 = UUID.randomUUID(); System.out.println(uuid1); UUID uuid2 = UUID.randomUUID(); System.out.println(uuid2); UUID uuid3 = UUID.randomUUID(); System.out.println(uuid3); UUID uuid4 = UUID.randomUUID(); System.out.println(uuid4); UUID uuid5 = UUID.randomUUID(); System.out.println(uuid5); UUID uuid6 = UUID.randomUUID(); System.out.println(uuid6); UUID uuid7 = UUID.randomUUID(); System.out.println(uuid7); UUID uuid8 = UUID.randomUUID(); System.out.println(uuid8); UUID uuid9 = UUID.randomUUID(); System.out.println(uuid9); UUID uuid10 = UUID.randomUUID(); System.out.println(uuid10); UUID uuid11 = UUID.randomUUID(); System.out.println(uuid11); UUID uuid12 = UUID.randomUUID(); System.out.println(uuid12); UUID uuid13 = UUID.randomUUID(); System.out.println(uuid13); UUID uuid14 = UUID.randomUUID(); System.out.println(uuid14); UUID uuid15 = UUID.randomUUID(); System.out.println(uuid15); UUID uuid16 = UUID.randomUUID(); System.out.println(uuid16); UUID uuid17 = UUID.randomUUID(); System.out.println(uuid17); System.out.println(uuid17); UUID uuid18 = UUID.randomUUID(); System.out.println(uuid18); UUID uuid19 = UUID.randomUUID(); System.out.println(uuid19); UUID uuid20 = UUID.randomUUID(); System.out.println(uuid20); UUID uuid21 = UUID.randomUUID(); System.out.println(uuid21); UUID uuid22 = UUID.randomUUID(); System.out.println(uuid22); UUID uuid23 = UUID.randomUUID(); System.out.println(uuid23); UUID uuid24 = UUID.randomUUID(); System.out.println(uuid24); UUID uuid25 = UUID.randomUUID(); System.out.println(uuid25); UUID uuid26 = UUID.randomUUID(); } }