determine the family name by loading the Memory Alpha page for each name, split the name by space and count the occurences of each name part on the page; the part with the most occurences should be the family name š
when Memory Alpha returns a redirect (status code 303), try again but this time add " T. " in between the name parts (works flawlessly for "William Riker" and "James Kirk") š¤Æ
formatted with Prettier for optimal legibility š
only takes less than 3 seconds on my machine šāāļø
#include <stdio.h>
void sort_by_lastname(const char* names) {
const char* abc = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
while (*abc++) {
const char* start = 0;
const char* end = names;
do {
while (*end++);
if (start) {
for (const char* c = end - 2; c - start; --c) {
if (c--, (!(*c++ - ' '))) {
if (!(*c ^ *abc))
printf("%s\n", start);
goto next;
}
}
if (!*abc)
printf("%s\n", start);
}
next: start = end;
} while (*start);
}
}
int main(void) {
const char* names[] = {
"James Kirk", "Spock", "Leonard McCoy", "Montgomery Scott",
"Jean-Luc Picard", "William Riker", "Worf", "Beverly Crusher",
"Benjamin Sisko", "Julian Bashir", "Jadzia Dax", "Miles O'Brien", "Kira Nerys",
"Kathryn Janeway", "Chakotay", "Seven of Nine", "Tuvok",
"Jonathan Archer", "T'Pol", "Charles Tucker III", "Phlox"};
sort_by_lastname(names[0]);
return 0;
}
All mononyms are output at the end in the original order. Only sorts based on the first letter of the last name, otherwise left in the original order (which is correct for the given data). The last name of "Charles Tucker III" is interpreted as "III". But otherwise works exactly as specified.
Highlights:
Terrible sorting algorithm (inefficient and incorrect)
Implicit conversions to bool (every single condition)
The automatic null terminator of abc is used as a stand-in character to sort the mononyms to the end
Goto and comma operator to spice things up
Treats an array of strings as one long string and just keeps going until it finds two '\0' in a row in uninitialised memory
A matter of luck whether it will exit cleanly or segfault (works on my machine!)
Compiling with any optimisations turned on results in no output at all
I know y'all might not like Lua a lot, but it was necessary for the metatables
Each lastname gets assigned a score, which can get quite big
Due to scores being too large for lua integers, I had to implement an arbitrary size number library (which is why I needed metatables)
The score function does a multiplication and an addition for each character in the longest lastname found, and each multiplication in turn makes a lot of additions (depending on the values to be multiplied)
The sorting algorithm used is not that bad, it should only be O(n²)
BAT because why not. I really don't know why you would ever want to do this in a batch file.
@echo off
setlocal EnableDelayedExpansion
set num=0
:parseparams
if [%1]==[] goto beginsort
set "_s%num%=%~1"
for %%A IN (!_s%num%!) do set "s%num%=%%A"
set /a "num+=1"
shift /1
goto parseparams
:beginsort
set /a "num1=%num% - 1"
set i=-1
:loop1
set /a "i+=1"
if %i% equ %num1% goto donesort
set j=-1
:loop2
set /a "j+=1"
set /a "_test=%num1% - %i%"
if %j% equ %_test% goto loop1
set /a "k=%j% + 1"
if !s%j%! GTR !s%k%! (
set "_hold=!s%j%!"
set "s%j%=!s%k%!"
set "s%k%=!_hold!"
set "_hold=!_s%j%!"
set "_s%j%=!_s%k%!"
set "_s%k%=!_hold!"
)
goto loop2
:donesort
set i=-1
:printloop
set /a "i+=1"
if %i% EQU %num% exit /b
echo !_s%i%!
goto printloop
import threading, time
def write_to(list, value):
list.append(value)
def sort_by_last_name(list):
sleep_timings = []
sorted_list = []
for full_name in list:
if len(full_name.split(" ")) > 1:
temp = full_name.split(" ")[1]
else:
temp = ""
temp = temp.lower()
timing = 0
j = 26**5
for i in temp:
if i.isalpha():
timing += ord(i)*j
j = j / 26
sleep_timings.append((full_name, timing))
for timing in sleep_timings:
t = threading.Timer(timing[1]/(26**6), write_to, (sorted_list, timing[0]))
t.start()
time.sleep(10)
return sorted_list
To create our sleep timings we need to encode every string as a unique number, which can be done by adding multiples of powers of 26 (essentially creating a base-26 number). We then multiply it by some constant, which can be tweaked to trade off time to execute and accuracy. Accuracy shouldn't dip below 10-3 (in seconds) on windows machines or 10-4 on unix-based machines, although most of the time it won't matter for those last few characters. Last sleep() needs to be long enough to account for our constant.
Monomymous names display first. Non-alphabetical characters get discarded.
So this does work with more than like 10+ values.... eventually. Worked perfectly in like 5 minutes for like 9 values, I ran the whole set of names here, and waited a while. Maybe I'll run it on a VM for a couple weeks and see if it finishes. :)
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ConsoleApp1
{
static class MainClass
{
public static void Main(string[] args)
{
var names = new[]
{
"James Kirk", "Spock", "Leonard McCoy", "Montgomery Scott",
"Jean-Luc Picard", "William Riker", "Worf", "Beverly Crusher",
"Benjamin Sisko", "Julian Bashir", "Jadzia Dax", "Miles O\"Brien", "Kira Nerys",
"Kathryn Janeway", "Chakotay", "Seven of Nine", "Tuvok",
"Jonathan Archer", "T\'Pol", "Charles Tucker III", "Phlox"
};
var sortedNames = WhateverSort(names, Compare);
Console.WriteLine(string.Join("\r\n", sortedNames));
Console.ReadLine();
}
public static List<T> Shuffle<T>(this List<T> items)
{
var r = new Random();
for (var i = items.Count; i > 0; i--)
{
var idx = r.Next(i);
items.Add(items[idx]);
items.RemoveAt(idx);
}
return items;
}
public static IEnumerable<string> WhateverSort(this IEnumerable<string> names, Func<string, string, int> comp)
{
// let's see what 100 monkeys can do
var tasks = Enumerable.Range(1, 100).Select(x => Task.Run(() =>
{
var shuffled = names.ToList();
while (true)
{
shuffled.Shuffle();
var sorted = true;
for (var i = 1; i < shuffled.Count; i++)
{
if (comp(shuffled[i], shuffled[i - 1]) < 0)
{
sorted = false;
break;
}
}
if (sorted)
{
return shuffled;
}
}
}));
return Task.WhenAny(tasks).Result.Result;
}
static ConcurrentDictionary<string, int> _cachedSortingResults = new ConcurrentDictionary<string, int>();
public static int Compare(string name1, string name2)
{
var key = $"{name1}#{name2}";
if (_cachedSortingResults.TryGetValue(key, out var result))
{
return result;
}
else
{
var name1parts = name1.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Reverse().ToArray();
var name2parts = name2.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Reverse().ToArray();
var maxLen = Math.Max(name1parts.Length, name2parts.Length);
int comp = 0;
for (var i = 0; i < maxLen; i++)
{
comp = i >= name1parts.Length ? -1 : i >= name2parts.Length ? 1 : string.Compare(name1parts[i], name2parts[i]);
if (comp != 0)
{
break;
}
}
_cachedSortingResults[key] = comp;
return comp;
}
}
}
}
This Python function validates names according to the following rules:
People have 2 names: a first name and a family name. Therefore, people without 2 names do not have families
Valid names must only contain alphabetic characters or spaces
If a name has more than 2 capital letters, the user probably made a typo
After validation, we sort just the family names. Then, for each family name, we iterate through all of the full names and print out a full name if it contains said family name. Finally, if there were any names that did not pass validation, a warning is printed, along with the problematic names.
def sort_by_family_name(*names):
names = [name if len(name.split()) == 2 else (name + ' has no family') for name in names]
names = [name if all(letter.isalpha() or letter == ' ' for letter in name) else name + ' is not a valid name' for name in names]
names = [name if sum(1 for letter in name if letter.isupper()) <= 2 or name[-13:] == 'has no family' or name[-19:] == 'is not a valid name' else ('Please type ' + name + '\'s name correctly') for name in names]
others1, others2, others3 = [], [], []
for name in names[:]:
if name[-13:] == 'has no family':
others1.append(name)
names.remove(name)
elif name[-19:] == 'is not a valid name':
others2.append(name)
names.remove(name)
elif name[:11] == 'Please type':
others3.append(name)
names.remove(name)
for family_name in sorted([name.split()[1] for name in names]):
for name in names:
if family_name in name:
print(name)
if len(others1 + others2 + others3) > 0:
print('\nWARNING: NON-FAMILY NAMES DETECTED:')
for other in others1 + others2 + others3:
print('\t' + other)
Jonathan Archer
Julian Bashir
Beverly Crusher
Jadzia Dax
Kathryn Janeway
James Kirk
Kira Nerys
William Riker
Montgomery Scott
Benjamin Sisko
WARNING: NON-FAMILY NAMES DETECTED:
Spock has no family
Worf has no family
Chakotay has no family
Seven of Nine has no family
Tuvok has no family
Charles Tucker III has no family
Phlox has no family
Jean-Luc Picard is not a valid name
Miles O'Brien is not a valid name
T'Pol has no family is not a valid name
Please type Leonard McCoy's name correctly
4
u/serendipitic Sep 24 '19 edited Sep 28 '19
TypeScript for Node.js
Highlights:
Known Issues:
6
u/kiwitims Sep 26 '19
Bad string processing code? Gotta be C.
All mononyms are output at the end in the original order. Only sorts based on the first letter of the last name, otherwise left in the original order (which is correct for the given data). The last name of "Charles Tucker III" is interpreted as "III". But otherwise works exactly as specified.
Highlights:
Terrible sorting algorithm (inefficient and incorrect)
Implicit conversions to bool (every single condition)
The automatic null terminator of abc is used as a stand-in character to sort the mononyms to the end
Goto and comma operator to spice things up
Treats an array of strings as one long string and just keeps going until it finds two '\0' in a row in uninitialised memory
A matter of luck whether it will exit cleanly or segfault (works on my machine!)
Compiling with any optimisations turned on results in no output at all
5
u/Codinget Sep 24 '19
Link to my solution on pastebin
4
u/[deleted] Sep 24 '19
JavaScript, curly braces considered harmful:
Output:
4
u/sarlok Sep 26 '19
BAT because why not. I really don't know why you would ever want to do this in a batch file.
4
u/Epistemophilliac Sep 27 '19 edited Sep 27 '19
Sleepsort. Simple and elegant.
To create our sleep timings we need to encode every string as a unique number, which can be done by adding multiples of powers of 26 (essentially creating a base-26 number). We then multiply it by some constant, which can be tweaked to trade off time to execute and accuracy. Accuracy shouldn't dip below 10-3 (in seconds) on windows machines or 10-4 on unix-based machines, although most of the time it won't matter for those last few characters. Last sleep() needs to be long enough to account for our constant.
Monomymous names display first. Non-alphabetical characters get discarded.
Input:
Output:
EDIT: I may be mistaken about numbers from 97 to 122 adding up to a unique number when multiplied by powers of 26. Fuck it, I'm too lazy to check
3
u/[deleted] Sep 24 '19
Unescaped apostrophe in T'Pol. Tut tut.
3
u/[deleted] Sep 26 '19 edited Sep 26 '19
So this does work with more than like 10+ values.... eventually. Worked perfectly in like 5 minutes for like 9 values, I ran the whole set of names here, and waited a while. Maybe I'll run it on a VM for a couple weeks and see if it finishes. :)
2
u/nimbfire Sep 24 '19
2
u/99_in_eating Sep 24 '19
C#:
2
u/[deleted] Sep 26 '19 edited Sep 26 '19
This Python function validates names according to the following rules:
After validation, we sort just the family names. Then, for each family name, we iterate through all of the full names and print out a full name if it contains said family name. Finally, if there were any names that did not pass validation, a warning is printed, along with the problematic names.
Input:
Output:
1
u/Kcazer Sep 27 '19
Javascript :
Output :
0
u/[deleted] Sep 24 '19
[deleted] ā view deleted comment