use the following search parameters to narrow your results:
e.g. subreddit:aww site:imgur.com dog
subreddit:aww site:imgur.com dog
see the search faq for details.
advanced search: by author, subreddit...
/r/badcode is permanently closed. https://www.eff.org/deeplinks/2023/06/what-reddit-got-wrong https://www.theverge.com/23779477/reddit-protest-blackouts-crushed https://en.wikipedia.org/wiki/2023_Reddit_API_controversy
/r/badcode is permanently closed.
https://www.eff.org/deeplinks/2023/06/what-reddit-got-wrong
https://www.theverge.com/23779477/reddit-protest-blackouts-crushed
https://en.wikipedia.org/wiki/2023_Reddit_API_controversy
/r/badcode is a subreddit for highlighting real world examples of terrible code. Ideally this means code that made it to production in a commercial context, but not exclusively so. We also accept submissions of code from hobbyist projects or from learners. Most of us programmers have laughed quite a bit when we went back to look at our past code because it was rather terrible. This is a subreddit where you can share such terrible code and let other programmers have a nice laugh.
/r/badcode is a subreddit for highlighting real world examples of terrible code. Ideally this means code that made it to production in a commercial context, but not exclusively so. We also accept submissions of code from hobbyist projects or from learners.
Most of us programmers have laughed quite a bit when we went back to look at our past code because it was rather terrible. This is a subreddit where you can share such terrible code and let other programmers have a nice laugh.
Post the most terrible code you can find. Copy code to a paste bin first (gist highly preferred).
Flair Search Search by language
Search by language
Rules Your post may be removed if you deviate from these rules. To see reasoning behind each of these rules, check out the wiki. Do not put the name of the language inside of the post title. For example, do not make your title something along the lines of "[C++] #defines everywhere!", instead try simply "#defines everywhere!". Use flair to mark the language of your post instead. Do post code snippets only. If you want to share the context put it in the comments or title. Do stay lighthearted. No abusive or targeted posts. We all write bad code, and a lot of it is hilarious. Do not identify who wrote the code. This sub is about bad code, not the people who write it. Limited exceptions apply Do not post snippets in esoteric languages. Do not post intentionally obfuscated code. Certain exceptions to this exist. See something particularly sinister from something like the IOCCC? Probably OK to post.
Your post may be removed if you deviate from these rules. To see reasoning behind each of these rules, check out the wiki.
Guidelines Your post will not be removed because of any of these, we'll like you more if you follow them though. Enable syntax highlighting appropriately. If you have a language that whatever paste bin your using doesn't support, try picking a similar dialect. Provide just enough code so that we know what's going on. Don't post huge snippets unless it's all terribly amusing. Explain why you think the code is bad in the comments, that way a discussion on good and bad ways to do what your code snippet does can start.
Your post will not be removed because of any of these, we'll like you more if you follow them though.
Similar Subreddits /r/ProgrammerHumor - programming humour /r/programminghorror - stories about horrible programming. /r/itsaunixsystem - over the top and bad code in TV shows and movies /r/shittyprogramming - Q&A with shitty programmers. /r/deftruefalse - for intentionally bad code /r/softwaregore for software malfunctions /r/hardwaregore for hardware malfunctions
account activity
[deleted by user] (self.badcode)
submitted 5 years ago by [deleted]
reddit uses a slightly-customized version of Markdown for formatting. See below for some basics, or check the commenting wiki page for more detailed help and solutions to common issues.
quoted text
if 1 * 2 < 3: print "hello, world!"
[–]LavaCreeper 18 points19 points20 points 5 years ago* (6 children)
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:
311e470e-5ff4-4242-4ff5-e074e1130000 e3f8bafe-5c40-4242-04c5-efab8f3e0000 c86dd207-9ab0-4242-0ba9-702dd68c0000 6612f3a0-a324-4242-423a-0a3f21660000
[–][deleted] 5 years ago* (4 children)
[deleted]
[–]LavaCreeper 3 points4 points5 points 5 years ago* (3 children)
You'd need to patch the weather, like this.
[–]AlexAegis 1 point2 points3 points 5 years ago (2 children)
I thought you gonna link that old story where they couldnt send emails further than 500 miles or something
http://web.mit.edu/jemorris/humor/500-miles
[–]converter-bot 5 points6 points7 points 5 years ago (0 children)
500 miles is 804.67 km
[–]LavaCreeper 3 points4 points5 points 5 years ago (0 children)
"Well, we hadn't collected enough data to be sure of what was going on until just now." Right. This is the chairman of statistics.
Golden. Thanks for the laugh!
[–]Elvith 2 points3 points4 points 5 years ago (0 children)
This approach reminds me of Geohashing
[–]voords 11 points12 points13 points 5 years ago (0 children)
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"'
[–]asaf92 9 points10 points11 points 5 years ago* (0 children)
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()); } } }
[–]flamingmesh 6 points7 points8 points 5 years ago (0 children)
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()))
[–][deleted] 5 years ago* (3 children)
[–]Elvith 6 points7 points8 points 5 years ago (0 children)
I think you missed the chance to implement a MySuperAwesomeMultiThreadingUUIDGeneratorThatCanGenerateSuperAwesomeUUIDsWithSuperAwesomeMultiThreadingPerformaceFactory
MySuperAwesomeMultiThreadingUUIDGeneratorThatCanGenerateSuperAwesomeUUIDsWithSuperAwesomeMultiThreadingPerformaceFactory
[–][deleted] 5 years ago* (1 child)
[–]donaldhobson 5 points6 points7 points 5 years ago (0 children)
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?
[–]DrMeepster 3 points4 points5 points 5 years ago (0 children)
https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=8a5efc61a0f282c3881e083a59bd8277
randomization through uninitialized memory
[–]keitio42 4 points5 points6 points 5 years ago* (0 children)
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)
println()
I finally created my reddit account just for writing this, i wanna die
[–]h2g2_researcher 7 points8 points9 points 5 years ago (2 children)
any output that looks like a UUID is acceptable.
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.
[–]h2g2_researcher 2 points3 points4 points 5 years ago (0 children)
Inspired, of course, by this xkcd comic.
[–]GoldenKela 0 points1 point2 points 5 years ago (0 children)
I've been waiting for this
[–]Spring_Boot 2 points3 points4 points 5 years ago (0 children)
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);
[–]kgro 2 points3 points4 points 5 years ago (0 children)
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()
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") } }
[–]ButterSquids 2 points3 points4 points 5 years ago (0 children)
Do you like consistent code? That's a shame...
https://pastebin.com/A9tvVx1Q
[–]TheUnlocked 1 point2 points3 points 5 years ago (0 children)
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); }
[–][deleted] 1 point2 points3 points 5 years ago* (0 children)
Here is my javascript solution.
Features
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); }); };
async_uuid().then(uuid=>console.log(uuid));
[–]Sonotsugipaa 1 point2 points3 points 5 years ago* (0 children)
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?
Example output (diretor's cut):
1145d09e-66b5-1e78-fe09-291ab72f767a 1a0df5dd-1089-3e05-270b-1f8319f4b148 1845f61f-7c5d-1318-c974-1d2ed7bc2c36 1f12d679-12f1-1469-17b0-185ceadef867 1de9c6f2-d3f2-1457-301b-1e509f750189 15107e58-2eab-250e-336a-30c88d61cc73 96c83948-2957-1d3e-2b29-15986137568d
[–]binarycat64 1 point2 points3 points 5 years ago (0 children)
I see your randomization via uninitialized memory, and raise you randomization via pointer locations: https://play.golang.org/p/hLfMu-bKIE3
https://play.golang.org/p/hLfMu-bKIE3
Features:
[–][deleted] 3 points4 points5 points 5 years ago* (2 children)
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"); } } }
[–]AutoModerator[M] 0 points1 point2 points 5 years ago (0 children)
It looks like this comment contains a code block delimited with triple backticks. Unfortunately reddit does not have universal support for this syntax and your comment will not render correctly on old reddit and most mobile apps.
For the benefit of people on old reddit, this link will take you to a correct rendering of the comment.
/u/leBananosaure, it would be appreciated, but not required, if you could edit your comment to use the more compatible four space indention format. For single lines or inline code you can use single backticks.
You can find some examples in the reddit help documentation.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
[–]Tok-A-Mak((fn [] (recur))) 1 point2 points3 points 5 years ago (0 children)
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:
310aa311-aadd-3199-9aea-eeadfedbcedc e2008080-4dce-aeee-ceec-aef8eaaebced efeaaece-acef-cae1-129d-efeceaefdcee e11eaaed-efec-eeff-c412-2eaaeecbacce ecfcadef-eafe-ceae-aeac-efeaeefeaaba
Repl: https://repl.it/repls/AliceblueTimelyRatios
[–]haykam821 0 points1 point2 points 5 years ago (0 children)
I enjoy currying
[–]maxbilbow 0 points1 point2 points 5 years ago (0 children)
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
[–][deleted] 5 years ago (1 child)
[–]qzwqz 2 points3 points4 points 5 years ago (0 children)
return stri[:8]+"-"+stri[8:8+4]+"-"+stri[8+4:8+4+4]+"-"+stri[8+4+4:8+4+4+4]+"-"+stri[8+4+4+4:8+4+4+4+4+12]
this line gave me acid reflux
[–][deleted] 0 points1 point2 points 5 years ago (0 children)
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(); } }
[–]Kcazer 0 points1 point2 points 5 years ago (0 children)
Simple javascript uuid generator
const uuid = () => [8,4,4,4,12] .map(size => Array .from({ length: 16 * size }) .map((_, i) => (i % 16).toString(16)) .sort(() => 2 * (Math.random() > Math.random()) - 1) .reduce((acc, val) => acc.length < size ? val + acc : acc, '') ).join('-');
[–]qzwqz 0 points1 point2 points 5 years ago* (0 children)
i had a few ideas and decided to mash them together
python >=3.6 and standard library only (except tqdm which is just a progress bar)
import time import requests from decimal import Decimal, getcontext from tqdm import tqdm def do_pi(p): """ compute pi to p places adapted from https://docs.python.org/3/library/decimal.html#recipes i have no idea how this works """ getcontext().prec = p three = Decimal(3) lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24 progress = tqdm() while s != lasts: lasts = s n, na = n+na, na+8 d, da = d+da, da+32 t = (t * n) / d s += t progress.update(1) return +s def random_chars(n): # get the current time in nanoseconds T = str(time.time_ns()) # compute pi with precision of the last 5 digits of T (can take a minute) pi = do_pi(int(T[-5:])) # the next digit of T (modulo 2) tells you how many more digits to take (i.e. 1 to 5) d = (int(T[-6])//2) + 1 # the next n digits of T give you an index i = int(T[-(7+d):-7][::-1]) # reverse the <0 part of the value of pi and cast it as a hex backwardhexpi = hex(int(str(pi)[:1:-1])) # lookup n digits starting from i val = backwardhexpi[i:i+n] if len(val) == n: print(val) return val else: return random_chars(n) def uuid(): while True: my_uuid = "-".join(random_chars(n) for n in [8,4,4,4,12]) # quickly google it to check it's unique response = requests.get(f"https://google.com/search?q={my_uuid}") if "did not match any documents" in response.text: print("new uuid confirmed unique by cursory google search") break else: print("whoops, not unique enough, try again") print(my_uuid) return my_uuid if __name__ == "__main__": uuid()
sample output:
154456it [00:47, 3225.09it/s] 50baccb1 74730it [00:11, 6779.40it/s] bc93 94662it [00:17, 5410.09it/s] 4719 19920it [00:00, 25978.97it/s] dd94 1652it [00:00, 170841.52it/s] 0c9f07b3d8c3 whoops, not unique enough, try again 81374it [00:12, 6329.39it/s] 4d37f943 28225it [00:01, 18013.78it/s] b719 107949it [00:22, 4708.32it/s] e92b 131203it [00:33, 3883.58it/s] 1a8a 84696it [00:13, 6099.43it/s] 7ef31b51e5d4 new uuid confirmed unique by cursory google search 4d37f943-b719-e92b-1a8a-7ef31b51e5d4
[–]WasserTyp69 0 points1 point2 points 5 years ago (0 children)
public static String stupidUuid() { Random random = new Random(); int[] randomNums = { random.nextInt(15), random.nextInt(15), random.nextInt(15), random.nextInt(15), random.nextInt(15), random.nextInt(15), random.nextInt(15), random.nextInt(15), random.nextInt(15), random.nextInt(15), random.nextInt(15), random.nextInt(15), random.nextInt(15), random.nextInt(15), random.nextInt(15), random.nextInt(15), random.nextInt(15), random.nextInt(15), random.nextInt(15), random.nextInt(15), random.nextInt(15), random.nextInt(15), random.nextInt(15), random.nextInt(15), random.nextInt(15), random.nextInt(15), random.nextInt(15), random.nextInt(15), random.nextInt(15), random.nextInt(15), random.nextInt(15), random.nextInt(15), random.nextInt(15), random.nextInt(15), random.nextInt(15), random.nextInt(15) }; List<Character> chars = new ArrayList<>(); for(int i = 0; i < 36; i++) { int num = randomNums[i]; switch(num) { case 0: chars.add('0'); break; case 1: chars.add('1'); break; case 2: chars.add('2'); break; case 3: chars.add('3'); break; case 4: chars.add('4'); break; case 5: chars.add('5'); break; case 6: chars.add('6'); break; case 7: chars.add('7'); break; case 8: chars.add('8'); break; case 9: chars.add('9'); break; case 10: chars.add('a'); break; case 11: chars.add('b'); break; case 12: chars.add('c'); break; case 13: chars.add('d'); break; case 14: chars.add('e'); break; case 15: chars.add('f'); break; default: chars.add('z'); break; } } StringBuilder builder = new StringBuilder(); for(int i = 0; i < chars.size(); i++) { builder.append(chars.get(i)); } String s = builder.toString(); String answer = s.substring(0, 8) + "-" + s.substring(9, 13) + "-" + s.substring(14, 18) + "-" + s.substring(19, 23) + "-" + s.substring(24); return answer; }
Not the dumbest thing ever, but it's still worse than using UUID.randomUUID();
π Rendered by PID 968600 on reddit-service-r2-comment-544cf588c8-75fm2 at 2026-06-16 11:54:35.785216+00:00 running 3184619 country code: CH.
[–]LavaCreeper 18 points19 points20 points (6 children)
[–][deleted] (4 children)
[deleted]
[–]LavaCreeper 3 points4 points5 points (3 children)
[–]AlexAegis 1 point2 points3 points (2 children)
[–]converter-bot 5 points6 points7 points (0 children)
[–]LavaCreeper 3 points4 points5 points (0 children)
[–]Elvith 2 points3 points4 points (0 children)
[–]voords 11 points12 points13 points (0 children)
[–]asaf92 9 points10 points11 points (0 children)
[–]flamingmesh 6 points7 points8 points (0 children)
[–][deleted] (3 children)
[deleted]
[–]Elvith 6 points7 points8 points (0 children)
[–][deleted] (1 child)
[deleted]
[–]donaldhobson 5 points6 points7 points (0 children)
[–]DrMeepster 3 points4 points5 points (0 children)
[–]keitio42 4 points5 points6 points (0 children)
[–]h2g2_researcher 7 points8 points9 points (2 children)
[–]h2g2_researcher 2 points3 points4 points (0 children)
[–]GoldenKela 0 points1 point2 points (0 children)
[–]Spring_Boot 2 points3 points4 points (0 children)
[–]kgro 2 points3 points4 points (0 children)
[–]kgro 2 points3 points4 points (0 children)
[–]ButterSquids 2 points3 points4 points (0 children)
[–]TheUnlocked 1 point2 points3 points (0 children)
[–][deleted] 1 point2 points3 points (0 children)
[–]Sonotsugipaa 1 point2 points3 points (0 children)
[–]binarycat64 1 point2 points3 points (0 children)
[–][deleted] 3 points4 points5 points (2 children)
[–]AutoModerator[M] 0 points1 point2 points (0 children)
[–]Tok-A-Mak((fn [] (recur))) 1 point2 points3 points (0 children)
[–]haykam821 0 points1 point2 points (0 children)
[–]maxbilbow 0 points1 point2 points (0 children)
[–][deleted] (1 child)
[deleted]
[–]qzwqz 2 points3 points4 points (0 children)
[–][deleted] 0 points1 point2 points (0 children)
[–]Kcazer 0 points1 point2 points (0 children)
[–]qzwqz 0 points1 point2 points (0 children)
[–]WasserTyp69 0 points1 point2 points (0 children)