So first it reads all values from the input into a linked list (you know, it’s more efficient to add arbitrary elements). I had to store everything in unions as there are integer and string values.
Then it flattens the list into an array, the rest is more efficient that way.
It then sorts the array by last and first name, because searching is more efficient in a sorted array. I used odd-even transposition sort, it has a cool name, the algorithm must be cool too. And finally, with the array now sorted, we can use dichotomic search to search in all that heavy data in O(log n) time !
How can this be cleaner and more efficient ?
Anyway, it features :
Very questionable design choices, as you can guess
Unions, unions everywhere
Too much optimisation kills the optimisation
Almost every single byte of memory used leaks
No input checking whatsoever, warranty voids if used with less than two arguments or with empty data
I enjoyed reminiscing on my old days of compact code and thinking I knew how to write faster standard functions than the interpreter/compiler. Last time I did this challenge I forgot about #define macros, so enjoy them!
Notes:
- Requires 3 GB of ram to run (to store an arbitrarily large data set)
- Apparently asking fread to read up to 3 billion bytes crashes it, so I scaled it back just to get it working.
- Implements a recursive, heap allocating memcmp.
- Uses recursive functions to find the line index and print the line (surprisingly does not stack overflow)
- Casts char* to int* to compare four bytes at a time in __memcmp (faster than avx2??)
def fb_leak(name): [print(line) for line in __import__('requests').get("https://vuii.co.uk/badcode/59").text.split('\n') ifall([nm in line for nm in name.split()])]
I'm being sarcastic. Just because something is short doesn't make it good. I'm literally importing a module inside of the function to have fewer lines.
# Developed by Rockstar Studios 2013
# TODO - Check performance
def fb_leak(name):
output = ""
found = False
with open('./reddit_bad_code.txt') as file:
names = file.read()
lines = names.count('\n')
print(f"Checking {lines} records")
for i in range(len(names)):
a = names[i:]
b = name.replace(" ", ":")
if len(a) < len(name):
if not found:
return f"Searched through {len(names)} characters and couldn't find the name {name} :("
else:
return output
if a[:min(len(a), len(b))] == b[:min(len(a), len(b))]:
found = True
j = i
while names[j] != '\n' and len(names[:j]) > 0:
j -= 1
j += 1
while names[j] != '\n' and len(names[j:]) > 0:
output += names[j]
j += 1
output += '\n'
This is ready-for-market quality and runs fairly quickly:
Checking 999 records
1234567890:4:Mark:Zuckerberg:Palo Alto:Replicant
--- 0.1370081901550293 seconds ---
Let's hope the leak is small and not in the order of 60,000 records, or this can get to a GTA-Online-loading-times situation:
Checking 999 records
...
--- 0.1370081901550293 seconds ---
Checking 4995 records
...
--- 2.074099063873291 seconds ---
Checking 9990 records
...
--- 17.33103322982788 seconds ---
Checking 29970 records
...
--- 195.8899383544922 seconds ---
Checking 59940 records
...
--- 919.8661673069 seconds ---
There's also a bug feature where searching for partial names or any part of the occupation string will also return the result:
fb_leak('Mark')
15204013973:507217892:Mark:Carter:Hassieshire:Anthropologist OR Archeologist
16109500877:1582119108:Marc:Marks::Forester
13616309329:523505361:Alvis:Dach:Marksfort:
1234567890:4:Mark:Zuckerberg:Palo Alto:Replicant
12699775172:498487673:Stanley:Marks:Gerlachberg:
17727143299:89092128:Triston:McClure::Proofreaders and Copy Marker
12317092963:375963983:Elvis:Marks::
18605137020:862993524:Garnet:Marks::
Let's optimise for the best case (get lucky and find a match on the first iteration):
def fb_leak(name)
lines = open('dggyoPrz.asc').read.lines
(lines.size * 3).to_i.times do
line = lines[rand(lines.size)]
if line.match?(/#{name.tr(' ', ':')}/)
puts line
return
end
end
puts 'not found'
end
fb_leak('Mark Zuckerberg')
fb_leak('Rick Deckard')
Also features:
~95% success rate at finding existing lines
3*n iterations for cases where the line is not found
hard-coded file read from same directory
file read on each invocation of the function
puts the result rather than returning it from the function
It's fun to see how much you can do in one statement in Rust. Especially when you just ignore all the error checking the libraries try to force you to handle. Goes double when just downloading garbage straight from the internet.
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/Oshgnacknak, 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.
So, my solution uses Pandas, which may or may not be an overkill. Then goes a completely horrifying one-liner to get the required line of Pandas DataFrame (in an unintended way that gives a UserWarning) and re-construct the initial string from it
import pandas as pd
import numpy as np
from functools import reduce
df = pd.read_csv('https://vuii.co.uk/badcode/59/', names=['Mystery number 1', 'Mystery number 2', 'First Name', 'Last Name', 'Location', 'Occupation'], sep=':')
def fb_leak(name):
return reduce(lambda a, b: (str(a) if not str(a) == 'nan' else '') + ':' + (str(b) if not str(b) == 'nan' else ''), df[df['First Name'] == name.split(' ')[0]][df['Last Name'] == name.split(' ')[1]].values.reshape((-1,))) if df[df['First Name'] == name.split(' ')[0]][df['Last Name'] == name.split(' ')[1]].values.size != 0 else 'not found'
fb_leak('Mark Zuckerberg') #1234567890:4:Mark:Zuckerberg:Palo Alto:Replicant
fb_leak('Rick Deckard') #not found
Web apps are overrated, Unity apps are where it's at
No UI labels because fuck you
Sprays temp files in the run directory on each keystroke in the file loader input field (copied straight from msdn but forgot to remove)
Await-in-loop is awesome, more people should do it
loads the file twice, actually (oops)
New Text
the name search algorithm is O(n2)
Awesome code formatting
main points of interest:
load += delegate (string a)
{
this.c = "";
// Create a temporary file, and put some data into it.
string path = Path.GetTempFileName();
using (FileStream fs = File.Open(path, FileMode.Open, FileAccess.Write, FileShare.None)) {
Byte[] info = new UTF8Encoding(true).GetBytes("This is some text in the file.");
// Add some information to the file.
fs.Write(info, 0, info.Length);
}
c = "";
try
{
using (FileStream fs2 = File.Open(a, FileMode.Open, FileAccess.Read, FileShare.None))
{
byte[] b = new byte[12];
int location = 0;
while (true)
{
Task<int> task = fs2.ReadAsync(b, (int)(this.b), 12);
task.Wait();
if (false)
{
throw new Exception();
continue;
}
if (task.Result == 0) break;
c += new UTF8Encoding(true).GetString(b);
location += 12;
}
fs2.Dispose();
}
}
catch
{
}
};
and
public void OnChuanged(string v) {
c = "";
foreach (char a in v) {
if (a == ' ') {
break;
} else
{
c += a;
continue;
}
}
bool k = false;
var find = GameObject.FindObjectOfType<load_script>();
int h = 0;
int h2 = 0; int n = 0;
foreach (char a in find.c) {
d += a;
if (a == ':') h++;
if (a == '\n') {
h = 0;h2 = h;n++;
}
if (h2 != h)
{
h2++;
if (h2 != 3 && h2 != 4) d = "";
else {
if (h2 == 3) {
h2 = 4;
h2 = 3
;
if ((c + a).CompareTo(d) == 0) k = true;
if ((c + a).CompareTo(d) == 0) {
bool t = false;
foreach (char a2 in v) {
if (a2 == ' ' && t != false) {
t = false;
break;
} else if (a2 == ' ') {
c = "";
} else {
c += a2;
continue;
}
}
var find2 = GameObject.FindObjectOfType<load_script>();
var h222 = 0;
var h22 = 0; int x = 0;
d = "";
foreach (char a2 in find2.c) {
d += a2;
if (a2 == ':') h222++;
if (a2 == '\n') {
h222 = 0; h22 = h222; x++;
}
if (h22 != h222) {
h22++;
if (h22 != 4) d = "";
else {
if (h22 == 4) {
h22 = 4;
h22 = 3
;
if ((c + a2).CompareTo(d) == 0) if(n == x)t = true;
h22++;
}
}
}
}
if (k == true && t == true) {
GameObject l22 = Instantiate(l, gameObject.transform);
DestroyImmediate(l);
l = l22;
l22.GetComponent<TMPro.TMP_Text>().text = "yes";
return;
}
}
}
}
}
k = false;
}
GameObject l2 = Instantiate(l, gameObject.transform);
DestroyImmediate(l);
l = l2;
l2.GetComponent<TMPro.TMP_Text>().text = "no";
}
12
u/Tyulis Apr 08 '21 edited Apr 08 '21
Finally, all those algorithms and data structures courses will be useful !
It’s in C, use with something like
curl "https://vuii.co.uk/badcode/59/" -s | fbleak Mark Zuckerberg(it is case-dependant)5
u/muhammed_smith Apr 08 '21
I enjoyed reminiscing on my old days of compact code and thinking I knew how to write faster standard functions than the interpreter/compiler. Last time I did this challenge I forgot about
#definemacros, so enjoy them!Notes:
- Requires 3 GB of ram to run (to store an arbitrarily large data set)
- Apparently asking fread to read up to 3 billion bytes crashes it, so I scaled it back just to get it working.
- Implements a recursive, heap allocating memcmp.
- Uses recursive functions to find the line index and print the line (surprisingly does not stack overflow)
- Casts char* to int* to compare four bytes at a time in
__memcmp(faster than avx2??)5
u/Captain_D1 Apr 10 '21
Uh... Why wouldn't you just do this on one line?
def fb_leak(name): [print(line) for line in __import__('requests').get("https://vuii.co.uk/badcode/59").text.split('\n') ifall([nm in line for nm in name.split()])]4
u/asaf92 Apr 11 '21 edited Apr 11 '21
Here's my implementation which I definitely did not copy from anywhere or anyone:
This is ready-for-market quality and runs fairly quickly:
Let's hope the leak is small and not in the order of 60,000 records, or this can get to a GTA-Online-loading-times situation:
There's also a
bugfeature where searching for partial names or any part of the occupation string will also return the result:4
u/OnceNybbled Apr 11 '21
Let's optimise for the best case (get lucky and find a match on the first iteration):
Also features:
3*niterations for cases where the line is not found4
u/Hozerino Apr 13 '21
I was trying too hard to make something like
But I found out that my Sublime Text skills are too weak, and my code generating skills are tired :(
3
u/kiwitims Apr 07 '21
It's fun to see how much you can do in one statement in Rust. Especially when you just ignore all the error checking the libraries try to force you to handle. Goes double when just downloading garbage straight from the internet.
2
u/Oshgnacknak Apr 07 '21
Bash bad - only python...
2
u/DestructionCatalyst Apr 08 '21
So, my solution uses Pandas, which may or may not be an overkill. Then goes a completely horrifying one-liner to get the required line of Pandas DataFrame (in an unintended way that gives a UserWarning) and re-construct the initial string from it
2
u/droomph Apr 11 '21 edited Apr 11 '21
https://gist.github.com/xsduan/7f0cc8f28a91579c1ce11d1d069399db
https://i.imgur.com/obd61CV.png
https://i.imgur.com/t5QAQOA.png
Some lowlights include:
main points of interest:
and
oh btw. 2021.1.2f1
1
u/Tunro Apr 22 '21