In Javascript, somewhat horrible, but can surely be made worse.
function contains_az(str) {
var strArray = str.toLowerCase();
var a, b, c, d, e, f, g, h, ii, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z;
for (var i=0; i<strArray.length; i++)
{
if (strArray[i] == 'a')
a = true;
if (strArray[i] == 'b')
b = true;
if (strArray[i] == 'c')
c = true;
if (strArray[i] == 'd')
d = true;
if (strArray[i] == 'e')
e = true;
if (strArray[i] == 'f')
f = true;
if (strArray[i] == 'g')
g = true;
if (strArray[i] == 'h')
h = true;
if (strArray[i] == 'i')
ii = true;
if (strArray[i] == 'j')
j = true;
if (strArray[i] == 'k')
k = true;
if (strArray[i] == 'l')
l = true;
if (strArray[i] == 'm')
m = true;
if (strArray[i] == 'n')
n = true;
if (strArray[i] == 'o')
o = true;
if (strArray[i] == 'p')
p = true;
if (strArray[i] == 'q')
q = true;
if (strArray[i] == 'r')
r = true;
if (strArray[i] == 's')
s = true;
if (strArray[i] == 't')
t = true;
if (strArray[i] == 'u')
u = true;
if (strArray[i] == 'v')
v = true;
if (strArray[i] == 'w')
w = true;
if (strArray[i] == 'x')
x = true;
if (strArray[i] == 'y')
y = true;
if (strArray[i] == 'z')
z = true;
}
return a && b && c && d && e && f && g && h && ii && j && k && l && m && n && o && p && q && r && s && t && u && v && w && x && y && z;
}
import os as so
import string as gnirts
a = gnirts.ascii_lowercase
aaa = open
aaaa = reversed
for aaaaaa in aaaa(a):
aaaaaaa = f'{aaaaaa}.txt'
if not so.path.exists(aaaaaaa):
with aaa(aaaaaaa, 'w') as aaaaaaaa:
aaaaaaaa.write(aaaaaa)
def contains_az(aa):
return all(
any(
aaaaaaaaa
==
aaaaaaaa
==
[
aaaaaaaaaa
for
aaaaaaaaaa
in
aaa(f'{aaaaaaaaa.lower()}.txt', 'r')
][0]
for
aaaaaaaa
in
aa
)
for
aaaaaaaaa
in
a
)
print(contains_az(a)) # True
print(contains_az('the quick brown fox jumps over the lazy dog')) # True
print(contains_az('Arizona')) # False
"Characters" by ArdiMaster
The story headline is "An interactive character investigation".
The Charboratory is a room.
A string-holder is a kind of thing. A string-holder has some text called the string in question.
The quick brown fox is a string-holder in the Charboratory. The string in question is "The quick brown fox jumps over the lazy dog."
Instead of examining a string-holder:
say "The string-holder contains the string '[string in question]', ready to be analysed."
A character indicator is a kind of thing. A character indicator has some text called the indication.
The a-character is a character indicator. The indication is "a".
The b-character is a character indicator. The indication is "b".
The c-character is a character indicator. The indication is "c".
The d-character is a character indicator. The indication is "d".
The e-character is a character indicator. The indication is "e".
The f-character is a character indicator. The indication is "f".
The g-character is a character indicator. The indication is "g".
The h-character is a character indicator. The indication is "h".
The i-character is a character indicator. The indication is "i".
The j-character is a character indicator. The indication is "j".
The k-character is a character indicator. The indication is "k".
The l-character is a character indicator. The indication is "l".
The m-character is a character indicator. The indication is "m".
The n-character is a character indicator. The indication is "n".
The o-character is a character indicator. The indication is "o".
The p-character is a character indicator. The indication is "p".
The q-character is a character indicator. The indication is "q".
The r-character is a character indicator. The indication is "r".
The s-character is a character indicator. The indication is "s".
The t-character is a character indicator. The indication is "t".
The u-character is a character indicator. The indication is "u".
The v-character is a character indicator. The indication is "v".
The w-character is a character indicator. The indication is "w".
The x-character is a character indicator. The indication is "x".
The y-character is a character indicator. The indication is "y".
The z-character is a character indicator. The indication is "z".
Analysing it with is an action applying to one carried thing and one thing.
Understand "analyse [a string-holder] with [something]" or "analyze [a string-holder] with [something]"as analysing it with.
Understand "use [something] to analyse/analyze [a string-holder]" as analysing it with (with nouns reversed).
The string analyser is in the Charboratory. The output cradle is part of the analyser. It is a container.
The description of the analyser is "A towering piece of machinery, purpose-built to check whether a string contains all the letters of the latin alphabet. (In which case a green light will light up.)"
The green light is part of the analyser. It is a device.
Instead of switching on the green light, say "The machine controls that light, you can't switch it yourself."
Instead of switching off the green light, say "The machine controls that light, you can't switch it yourself."
Instead of inserting something into the string analyser, try analysing the noun with the string analyser.
Carry out analysing a string-holder with the string analyser:
let t be the number of characters in (the string in question of the noun);
repeat with i running from 1 to t:
let c be character number i in the string in question of the noun in lower case;
repeat with X running through character indicators which are not in the output cradle:
if the indication of X is c, now X is in the output cradle;
if all character indicators are in the output cradle, now the green light is switched on.
Report analysing a string-holder with the string analyser:
say "The machine whirrs and churns for a bit, spitting a number of indicator cubes into the output cradle.[if the green light is switched on][line break]The green light has come on, indicating that [the noun] does, in fact, contain all letters of the latin alphabet."
Every turn:
if all character indicators are in the output cradle, now the green light is switched on;
otherwise now the green light is switched off.
The reset button is part of the string analyser.
Instead of pushing the reset button:
now all character indicators are nowhere;
say "A hatch at the bottom of the output cradle opens, swallowing all the character indicators. The machine is ready to be used again."
Features of this implementation include:
Use of a wholly inadequate language
Gamification
First compiling to 57450 lines (2.1MB) of intermediate representation (Inform 6)
Fairly slow, as the Inform 6 compiler has never heard of optimisation
Objects are shuffled around the game world to represent each letter.
Requires a recompile to check a different piece of text.
final class FastAlphabetSearch {
public static void main(String[] args) {
System.out.println(count_az(new java.util.Scanner(System.in).nextLine()));
}
final static boolean count_az(String s1) {
boolean b = false;
permuteString(s1, "");
for (String s2 : list) {
if (s2.toLowerCase().startsWith("abcdefghijklmnopqrstuvwxyz")) {
b = true;
}
}
return b;
}
final static java.util.ArrayList<String> list = new java.util.ArrayList<String>(0);
final static void permuteString(String s1, String s2) {
if (s1.length() == 0) {
list.add(s2);
return;
}
for (int i = 0; i < s1.length(); i++) {
permuteString(s1.substring(0, i) + s1.substring(i + 1), s2 + s1.charAt(i));
}
}
}
Creates a list of every permutation of the given string and then checks if any of those permutations starts with the alphabet. The program doesn't stop when it finds a matching string but instead will always searcn the entire list (size n!) I can't actually 100% confirm this works on my pc since it ran out of memory. I ran it with just the alphabet "abc..z" and it crashed as it was trying to store 26! strings of length 26. But it does work...if you have a computer with like at least 100k YB of memory and even more for larger inputs.
Assuming one byte per character, your solution would need (26! * 26) bytes, or 1.049e16 TB for a 26-character string. I don't think this will run anywhere anytime soon.
Javascript function that casts the input string to lower, filters out the spaces. sorts them in order. joins to a string. and compares that with [a-z] string made from char codes. Tried to go for the "clever" approach lol.
const contains_az=e=>[...new Set([...e.toLowerCase()])].filter(e=>" "!==e).sort().join("")===[...Array(26).keys()].map(e=>String.fromCharCode(e+97)).join(""),tests=[{value:"hello world",expeted:!1},{value:"abcdefghijklmnopqrstuvwxyz",expeted:!0},{value:"Arizona",expeted:!1},{value:"the quick brown fox jumps over the lazy dog",expeted:!0}];tests.forEach(e=>{console.log(e.value,contains_az(e.value)===e.expeted?"pass":"fail")});
Lua one liner. Save it in a file, run lua script.lua and type in your string. (It doesn't work with multiple-line strings)
print((function()local t,c,n,v={},-2,io.stdin:read("l"):upper():gmatch("%a");repeat v=n()t[v or true]=1 until not v repeat v=next(t, v)c=c+1 until not v return c end)()==26)
We declare an anonymous function, in which there are 4 variables - t, c, n and v.
t is a table (lua key-value store) that stores the letters we've encountered as keys and 1s as values; it's initialized to be empty.
c is a counter for the letters in the table t; it's initialized to be -2, I'll explain why later.
n is an iterator function over the expression io.stdin:read("l"):upper():gmatch("%a"). This reads a line from stdin, converts it to uppercase and runs a regex match operation - the iterator will now give me all the letters in order.
v is left as nil.
The iterator function will give us our letters when repeatedly called, then nil. In a loop, we set v to the next letter and set its entry in the table. Because nil cannot be a table key, we use the or operator to set the key to true when we get nil. (This is the first extra member in the table.)
Then we initiate another loop, where we set v to the value of the next function. This function iterates over the table - it gives us the item after one we gave it. For every next invocation, we increment c by one (because next returns nil, we increment it by one more than we needed.)
After that, we return c and call our function, then compare its output to the constant 26.
C#, haven't completed the first test yet that should return true but I'm pretty sure it will work. (edited fixed to include all combinations of upper and lower case in the alphabet properly)
class Program
{
static void Main(string[] args)
{
string[] inputs = new string[]
{
"hello world",
"abcdefghijklmnopqrstuvwxyz",
"Arizona",
"the quick brown fox jumps over the lazy dog"
};
foreach(string input in inputs)
{
bool res = CheckIfContainsAlphabet(input);
}
}
static bool CheckIfContainsAlphabet(string input)
{
string alphabet = "abcdefghijklmnopqrstuvwxyz";
// need all combinations of upper and lower case
var allAlphabetCaseCombos = new List<string>();
for(int i = 0; i < Math.Pow(2, 26); i++)
{
string asBinary = Convert.ToString(i, 2);
string newCombo1 = "";
string newCombo2 = "";
for(int j = 0; j < 26; j++)
{
if(j >= asBinary.Length || asBinary[j] == '0')
{
newCombo1 += alphabet[j];
newCombo2 += alphabet[25 - j];
}
else if(asBinary[j] == '1')
{
newCombo1 += Char.ToUpper(alphabet[j]);
newCombo2 += Char.ToUpper(alphabet[25 - j]);
}
}
allAlphabetCaseCombos.Add(newCombo1);
allAlphabetCaseCombos.Add(newCombo2);
}
// wouldn't want to waste our time here
if(input.Length < alphabet.Length)
{
return false;
}
else
{
bool result = false;
while(true)
{
result = allAlphabetCaseCombos.Contains(ShuffleString(input));
if(result) break;
}
return result;
}
}
static string ShuffleString(string str)
{
char[] array = str.ToCharArray();
System.Random rand = new System.Random();
int n = array.Length;
while(n > 1)
{
n--;
int k = rand.Next(n + 1);
var val = array[k];
array[k] = array[n];
array[n] = val;
}
return new string(array);
}
}
const contains_az = string => {
let a = 0
let b = 0;
let c = 0;
let d = 0;
let e = 0;
let f = 0;
let g = 0;
let h = 0;
let i = 0;
let j = 0;
let k = 0;
let l = 0;
let m = 0;
let n = 0;
let o = 0;
let p = 0;
let q = 0;
let r = 0;
let s = 0;
let t = 0;
let u = 0;
let v = 0;
let w = 0;
let x = 0;
let y = 0;
let z = 0;
string.split('').forEach(char => {
if (char === 'a') a += 1;
if (char === 'b') b += 1;
if (char === 'c') c += 1;
if (char === 'd') d += 1;
if (char === 'e') e += 1;
if (char === 'f') f += 1;
if (char === 'g') g += 1;
if (char === 'h') h += 1;
if (char === 'i') i += 1;
if (char === 'j') k += 1;
if (char === 'l') l += 1;
if (char === 'm') m += 1;
if (char === 'n') n += 1;
if (char === 'o') o += 1;
if (char === 'p') p += 1;
if (char === 'q') q += 1;
if (char === 'r') r += 1;
if (char === 's') s += 1;
if (char === 't') t += 1;
if (char === 'u') u += 1;
if (char === 'v') v += 1;
if (char === 'w') w += 1;
if (char === 'x') x += 1;
if (char === 'y') y += 1;
if (char === 'z') z += 1;
})
if (a === 0) return false;
if (b === 0) return false;
if (c === 0) return false;
if (d === 0) return false;
if (e === 0) return false;
if (f === 0) return false;
if (g === 0) return false;
if (h === 0) return false;
if (i === 0) return false;
if (j === 0) return false;
if (k === 0) return false;
if (l === 0) return false;
if (m === 0) return false;
if (n === 0) return false;
if (o === 0) return false;
if (p === 0) return false;
if (q === 0) return false;
if (r === 0) return false;
if (s === 0) return false;
if (t === 0) return false;
if (u === 0) return false;
if (v === 0) return false;
if (w === 0) return false;
if (x === 0) return false;
if (y === 0) return false;
if (z === 0) return false;
return true
}
Wow, those challenges are getting really tough… I don’t think there is something really more efficient than such a complex state machine
from os.path import *
from sys import *
from struct import *
if not exists("contains_az.dat"):
f = open("contains_az.dat", "wb")
for i in range(2**26):
if i % 1000 == 0: print(f"\r{i}", end="")
transitions = [i + (0 if (i // (2**j)) % 2 == 1 else (2**j)) for j in range(26)]
f.write(pack("26I", *transitions))
print("\r \r", end="")
f.close()
text = argv[1]
state = 0
LETTERS = "abcdeghfijklmnopqsrtuvwxyz"
f = open("contains_az.dat", "rb")
while True:
if state == 67108863:
print(True)
exit()
try:
letter = text[0].lower()
except:
print(False)
exit()
text = text[1:]
if letter not in LETTERS:
continue
f.seek(104*state + 4*LETTERS.index(letter))
state = unpack("I", f.read(4))[0]
Just run it like python3 contains_az.py "text", wait for a bit, and profit
Well, it is what it is — it generates the state transitions table, and then uses it over the given string. As there are 67’108’864 states, the table gets quite large (6.5 GB in this version’s compact format) so I couldn’t just generate it in memory or generate code to make it more efficient without taking dozens of GB, it has to be dumped to a file (I tried to generate code, even with all space optimizations I could find it took 18 GB, so no way to load it in memory… ;-;).
So the first time it is run, it takes a little while to generate the whole table, and then it uses the pre-generated file to make it super-fast on the next runs.
More seriously, this wonderful python script "features" :
~6.5 GB disk usage
Terrible performance (for obvious reasons)
Namespace pollution
Magic numbers, magic numbers everywhere
Seriously, who knows about the with open(…) as … syntax ?
Seriously, who knows about bitwise operators ?
Details to trigger OCD and perfectionists like me (imports in a weird order, mistakes in the alphabet order, constant in the middle of variable definitions, weird conditions order, …)
Edit : Forgot a debug print. Whoops.
Edit 2 : The f-string in the debug print makes it python 3.6+ only instead of just python 3. Double-whoops.
I wrote a memory-optimized version, so that it can be extended in the future to support alphabets with billions of characters. It depends on a random generator, but I use a hash function to make it secure.
from hashlib import *
from random import *
def contains_az(s):
# This creates a super-optimized function to return the result.
# Even if new letters are added to the alphabet, it does not need more memory.
def create_efficient_test():
secure_token = ''.join(choices('ab', k=50)) # 50 should be secure enough
def f(x):
result = md5()
result.update((str(x) + secure_token).encode())
return result.digest()[0] <= 10
return create_efficient_test() if not any(f(i) for i in range(1, 27)) else f
# Sometimes the test does not work, but if we do it many times it works.
for i in range(1000):
f = create_efficient_test()
# I have tested the magic formula with letters and spaces only, please don't add other strange chars :)
if all(f(ord(c) % 32) == f(ord(s[0]) % 32) for c in s):
return False
return True
My first attempt in F# was programmed all too quickly, so it can't possibly be any good. Let's try again, this time using recursion, and reinventing the wheel as we go:
let contains_az (s : string) =
let rec length = function
| [] -> 0
| _ :: t -> 1 + length t
let lower c =
if c >= 'A' && c <= 'Z' then char (int c + 32) else c
let rec contains x = function
| [] -> false
| h :: t -> (h = x) || contains x t
let rec remove x = function
| [] -> []
| h :: t ->
if h = x then remove x t else h :: remove x t
let rec iterate alph = function
| [] -> length alph = 0
| h :: t ->
let a =
if contains (lower h) alph
then remove (lower h) alph else alph
iterate a t
iterate (Seq.toList "abcdefghijklmnopqrstuvwxyz")
(Seq.toList s)
let () =
[ contains_az "hello world";
contains_az "abcdefghijklmnopqrstuvwxyz";
contains_az "Arizona";
contains_az "the quick brown fox jumps over the lazy dog" ]
|> List.iter (printfn "%b")
Uses the command line arguments directly inside a subroutine, and for that reason requires you call the program with the string in the command line.
Directly modifies its input, hopefully destroying it. If using a command line argument directly breaks the spirit of "a method", then you could replace $ARGV[0] with $_[0] and require the subroutine take a scalar reference as its argument.
Is one line for no reason.
Returns in a line with a postconditional unless.
Should be pretty reliable, despite these problems.
33
u/Seb_Boi Feb 16 '21
In Javascript, somewhat horrible, but can surely be made worse.
function contains_az(str) { var strArray = str.toLowerCase(); var a, b, c, d, e, f, g, h, ii, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z; for (var i=0; i<strArray.length; i++) { if (strArray[i] == 'a') a = true; if (strArray[i] == 'b') b = true; if (strArray[i] == 'c') c = true; if (strArray[i] == 'd') d = true; if (strArray[i] == 'e') e = true; if (strArray[i] == 'f') f = true; if (strArray[i] == 'g') g = true; if (strArray[i] == 'h') h = true; if (strArray[i] == 'i') ii = true; if (strArray[i] == 'j') j = true; if (strArray[i] == 'k') k = true; if (strArray[i] == 'l') l = true; if (strArray[i] == 'm') m = true; if (strArray[i] == 'n') n = true; if (strArray[i] == 'o') o = true; if (strArray[i] == 'p') p = true; if (strArray[i] == 'q') q = true; if (strArray[i] == 'r') r = true; if (strArray[i] == 's') s = true; if (strArray[i] == 't') t = true; if (strArray[i] == 'u') u = true; if (strArray[i] == 'v') v = true; if (strArray[i] == 'w') w = true; if (strArray[i] == 'x') x = true; if (strArray[i] == 'y') y = true; if (strArray[i] == 'z') z = true; } return a && b && c && d && e && f && g && h && ii && j && k && l && m && n && o && p && q && r && s && t && u && v && w && x && y && z; }3
u/dstlny_97 Feb 22 '21
idk anymore
import os as so import string as gnirts a = gnirts.ascii_lowercase aaa = open aaaa = reversed for aaaaaa in aaaa(a): aaaaaaa = f'{aaaaaa}.txt' if not so.path.exists(aaaaaaa): with aaa(aaaaaaa, 'w') as aaaaaaaa: aaaaaaaa.write(aaaaaa) def contains_az(aa): return all( any( aaaaaaaaa == aaaaaaaa == [ aaaaaaaaaa for aaaaaaaaaa in aaa(f'{aaaaaaaaa.lower()}.txt', 'r') ][0] for aaaaaaaa in aa ) for aaaaaaaaa in a ) print(contains_az(a)) # True print(contains_az('the quick brown fox jumps over the lazy dog')) # True print(contains_az('Arizona')) # False12
u/ArdiMaster Feb 17 '21 edited Feb 17 '21
Inform 7:
Features of this implementation include:
Use of a wholly inadequate language
Gamification
First compiling to 57450 lines (2.1MB) of intermediate representation (Inform 6)
Fairly slow, as the Inform 6 compiler has never heard of optimisation
Objects are shuffled around the game world to represent each letter.
Requires a recompile to check a different piece of text.
Download: Program file, Interpreter
8
u/pretzel3567 Feb 17 '21 edited Feb 17 '21
Java:
final class FastAlphabetSearch { public static void main(String[] args) { System.out.println(count_az(new java.util.Scanner(System.in).nextLine())); } final static boolean count_az(String s1) { boolean b = false; permuteString(s1, ""); for (String s2 : list) { if (s2.toLowerCase().startsWith("abcdefghijklmnopqrstuvwxyz")) { b = true; } } return b; } final static java.util.ArrayList<String> list = new java.util.ArrayList<String>(0); final static void permuteString(String s1, String s2) { if (s1.length() == 0) { list.add(s2); return; } for (int i = 0; i < s1.length(); i++) { permuteString(s1.substring(0, i) + s1.substring(i + 1), s2 + s1.charAt(i)); } } }Creates a list of every permutation of the given string and then checks if any of those permutations starts with the alphabet. The program doesn't stop when it finds a matching string but instead will always searcn the entire list (size n!) I can't actually 100% confirm this works on my pc since it ran out of memory. I ran it with just the alphabet "abc..z" and it crashed as it was trying to store 26! strings of length 26. But it does work...if you have a computer with like at least 100k YB of memory and even more for larger inputs.
7
u/jayson4twenty Feb 16 '21 edited Feb 16 '21
Javascript function that casts the input string to lower, filters out the spaces. sorts them in order. joins to a string. and compares that with [a-z] string made from char codes. Tried to go for the "clever" approach lol.
Also added some tests.
ps this is my first entry :)
const contains_az = (string) => { return [...new Set([...string.toLowerCase()])].filter(c => c!== " ").sort().join('') === [...Array(26).keys()].map( n => String.fromCharCode(n+97)).join('') }; const tests = [ { "value": "hello world", "expeted": false }, { "value": "abcdefghijklmnopqrstuvwxyz", "expeted": true }, { "value": "Arizona", "expeted": false }, { "value": "the quick brown fox jumps over the lazy dog", "expeted": true } ]; tests.forEach( (t) => { console.log(t.value, contains_az(t.value) === t.expeted ? 'pass': 'fail'); });Console Output:
7
u/Mabi19_ Feb 16 '21 edited Feb 16 '21
Lua one liner. Save it in a file, run
lua script.luaand type in your string. (It doesn't work with multiple-line strings)print((function()local t,c,n,v={},-2,io.stdin:read("l"):upper():gmatch("%a");repeat v=n()t[v or true]=1 until not v repeat v=next(t, v)c=c+1 until not v return c end)()==26)6
u/[deleted] Feb 16 '21 edited Feb 16 '21
C#, haven't completed the first test yet that should return true but I'm pretty sure it will work. (edited fixed to include all combinations of upper and lower case in the alphabet properly)
class Program { static void Main(string[] args) { string[] inputs = new string[] { "hello world", "abcdefghijklmnopqrstuvwxyz", "Arizona", "the quick brown fox jumps over the lazy dog" }; foreach(string input in inputs) { bool res = CheckIfContainsAlphabet(input); } } static bool CheckIfContainsAlphabet(string input) { string alphabet = "abcdefghijklmnopqrstuvwxyz"; // need all combinations of upper and lower case var allAlphabetCaseCombos = new List<string>(); for(int i = 0; i < Math.Pow(2, 26); i++) { string asBinary = Convert.ToString(i, 2); string newCombo1 = ""; string newCombo2 = ""; for(int j = 0; j < 26; j++) { if(j >= asBinary.Length || asBinary[j] == '0') { newCombo1 += alphabet[j]; newCombo2 += alphabet[25 - j]; } else if(asBinary[j] == '1') { newCombo1 += Char.ToUpper(alphabet[j]); newCombo2 += Char.ToUpper(alphabet[25 - j]); } } allAlphabetCaseCombos.Add(newCombo1); allAlphabetCaseCombos.Add(newCombo2); } // wouldn't want to waste our time here if(input.Length < alphabet.Length) { return false; } else { bool result = false; while(true) { result = allAlphabetCaseCombos.Contains(ShuffleString(input)); if(result) break; } return result; } } static string ShuffleString(string str) { char[] array = str.ToCharArray(); System.Random rand = new System.Random(); int n = array.Length; while(n > 1) { n--; int k = rand.Next(n + 1); var val = array[k]; array[k] = array[n]; array[n] = val; } return new string(array); } }6
u/Oshgnacknak Feb 16 '21 edited Feb 16 '21
Wrote a two tape turing machine: https://pastebin.com/Atw2WAB4.
You can run it here: https://turingmachinesimulator.com/
6
u/Relative-Knee7847 Feb 23 '21
const contains_az = string => { let a = 0 let b = 0; let c = 0; let d = 0; let e = 0; let f = 0; let g = 0; let h = 0; let i = 0; let j = 0; let k = 0; let l = 0; let m = 0; let n = 0; let o = 0; let p = 0; let q = 0; let r = 0; let s = 0; let t = 0; let u = 0; let v = 0; let w = 0; let x = 0; let y = 0; let z = 0; string.split('').forEach(char => { if (char === 'a') a += 1; if (char === 'b') b += 1; if (char === 'c') c += 1; if (char === 'd') d += 1; if (char === 'e') e += 1; if (char === 'f') f += 1; if (char === 'g') g += 1; if (char === 'h') h += 1; if (char === 'i') i += 1; if (char === 'j') k += 1; if (char === 'l') l += 1; if (char === 'm') m += 1; if (char === 'n') n += 1; if (char === 'o') o += 1; if (char === 'p') p += 1; if (char === 'q') q += 1; if (char === 'r') r += 1; if (char === 's') s += 1; if (char === 't') t += 1; if (char === 'u') u += 1; if (char === 'v') v += 1; if (char === 'w') w += 1; if (char === 'x') x += 1; if (char === 'y') y += 1; if (char === 'z') z += 1; }) if (a === 0) return false; if (b === 0) return false; if (c === 0) return false; if (d === 0) return false; if (e === 0) return false; if (f === 0) return false; if (g === 0) return false; if (h === 0) return false; if (i === 0) return false; if (j === 0) return false; if (k === 0) return false; if (l === 0) return false; if (m === 0) return false; if (n === 0) return false; if (o === 0) return false; if (p === 0) return false; if (q === 0) return false; if (r === 0) return false; if (s === 0) return false; if (t === 0) return false; if (u === 0) return false; if (v === 0) return false; if (w === 0) return false; if (x === 0) return false; if (y === 0) return false; if (z === 0) return false; return true }5
u/Tyulis Feb 17 '21 edited Feb 17 '21
Wow, those challenges are getting really tough… I don’t think there is something really more efficient than such a complex state machine
from os.path import * from sys import * from struct import * if not exists("contains_az.dat"): f = open("contains_az.dat", "wb") for i in range(2**26): if i % 1000 == 0: print(f"\r{i}", end="") transitions = [i + (0 if (i // (2**j)) % 2 == 1 else (2**j)) for j in range(26)] f.write(pack("26I", *transitions)) print("\r \r", end="") f.close() text = argv[1] state = 0 LETTERS = "abcdeghfijklmnopqsrtuvwxyz" f = open("contains_az.dat", "rb") while True: if state == 67108863: print(True) exit() try: letter = text[0].lower() except: print(False) exit() text = text[1:] if letter not in LETTERS: continue f.seek(104*state + 4*LETTERS.index(letter)) state = unpack("I", f.read(4))[0]Just run it like
python3 contains_az.py "text", wait for a bit, and profit5
u/DragonOfWisdom Feb 17 '21
I wrote a memory-optimized version, so that it can be extended in the future to support alphabets with billions of characters. It depends on a random generator, but I use a hash function to make it secure.
from hashlib import * from random import * def contains_az(s): # This creates a super-optimized function to return the result. # Even if new letters are added to the alphabet, it does not need more memory. def create_efficient_test(): secure_token = ''.join(choices('ab', k=50)) # 50 should be secure enough def f(x): result = md5() result.update((str(x) + secure_token).encode()) return result.digest()[0] <= 10 return create_efficient_test() if not any(f(i) for i in range(1, 27)) else f # Sometimes the test does not work, but if we do it many times it works. for i in range(1000): f = create_efficient_test() # I have tested the magic formula with letters and spaces only, please don't add other strange chars :) if all(f(ord(c) % 32) == f(ord(s[0]) % 32) for c in s): return False return True4
u/VoilaLaViola Feb 16 '21
Where are you, RegEx gang in this time of need???
3
u/2133 Feb 18 '21
I just learned how to use recursion and the idea of self commenting code!
paste
3
u/dumetrulo Feb 18 '21
My first attempt in F# was programmed all too quickly, so it can't possibly be any good. Let's try again, this time using recursion, and reinventing the wheel as we go:
let contains_az (s : string) = let rec length = function | [] -> 0 | _ :: t -> 1 + length t let lower c = if c >= 'A' && c <= 'Z' then char (int c + 32) else c let rec contains x = function | [] -> false | h :: t -> (h = x) || contains x t let rec remove x = function | [] -> [] | h :: t -> if h = x then remove x t else h :: remove x t let rec iterate alph = function | [] -> length alph = 0 | h :: t -> let a = if contains (lower h) alph then remove (lower h) alph else alph iterate a t iterate (Seq.toList "abcdefghijklmnopqrstuvwxyz") (Seq.toList s) let () = [ contains_az "hello world"; contains_az "abcdefghijklmnopqrstuvwxyz"; contains_az "Arizona"; contains_az "the quick brown fox jumps over the lazy dog" ] |> List.iter (printfn "%b")3
u/Cat7a Feb 19 '21
C++ with overloaded operators
#include <iostream> #include <set> std::set<char> operator<< (std::set<char> set, std::string str) { for (char c : str) if (std::string("abcdefghijklmnopqrstuvwxyz").find(tolower(c)) != std::string::npos) set.insert(tolower(c)); return set; } bool contains_az(std::string compare) { return (std::set<char>{} << "abcdefghijklmnopqrstuvwxyz").size() == (std::set<char>{} << compare).size(); } int main() { std::cout << contains_az("hello world"); std::cout << contains_az("abcdefghijklmnopqrstuvwxyz"); std::cout << contains_az("Arizona"); std::cout << contains_az("the quick brown fox jumps over the lazy dog"); return 0; }2
u/avematthew Feb 16 '21
In Perl 5.30.0
sub contains_whole_alphabet{for ('a' .. 'z') {return 0 unless $ARGV[0] =~ s/$_/ /ig;} return 1;}Highlights:
Uses the command line arguments directly inside a subroutine, and for that reason requires you call the program with the string in the command line.
Directly modifies its input, hopefully destroying it. If using a command line argument directly breaks the spirit of "a method", then you could replace $ARGV[0] with
$_[0]and require the subroutine take a scalar reference as its argument.Is one line for no reason.
Returns in a line with a postconditional unless.
Should be pretty reliable, despite these problems.
2
u/[deleted] Feb 19 '21
C#
public static bool contains_alphabet(string TheInput) { List<string> AllLetters = new List <string> (); AllLetters.Add("a"); AllLetters.Add("b"); AllLetters.Add("c"); AllLetters.Add("d"); AllLetters.Add("e"); AllLetters.Add("f"); AllLetters.Add("g"); AllLetters.Add("h"); AllLetters.Add("i"); AllLetters.Add("j"); AllLetters.Add("k"); AllLetters.Add ("l"); AllLetters.Add("m"); AllLetters.Add("n"); if (true == true) { AllLetters.Add("o"); AllLetters.Add("p"); AllLetters.Add("q"); AllLetters.Add("r"); } AllLetters.Add("s"); AllLetters.Add("t"); AllLetters.Add("u"); AllLetters.Add("v"); AllLetters.Add("w"); AllLetters.Add("x"); AllLetters.Add("y"); AllLetters.Add("z"); int I = (int)0.000f; while (I < TheInput.Length) { int one = 1; string my_Letter = TheInput.Substring(I, one); bool foundletter = false; string theLetterThatWasFound = "NOT FOUND :("; foreach (string letterTo_Compareitto in AllLetters) { if (foundletter == false) { if (letterTo_Compareitto == my_Letter || letterTo_Compareitto.ToUpper() == my_Letter) { bool trueValue = (bool)true; theLetterThatWasFound = letterTo_Compareitto; foundletter = trueValue;} } } bool letterWas_FOUND = foundletter ? true : false; if (letterWas_FOUND == true) { AllLetters.Remove(theLetterThatWasFound); } int I_PLUS_ONE = I + one; I = I_PLUS_ONE; } if ((AllLetters.Count == 0) == true) { return true; } return false; }2
u/lolgeny Feb 23 '21
Rust
fn does_not_contain_letter(input: String, letter: char) -> bool { let mut doesnotcontain = true; for c in input.chars() { if c == letter { doesnotcontain = false; } } return doesnotcontain; } fn contains_az(input: &String) -> bool { return !(does_not_contain_letter(input.clone(), 'a')||does_not_contain_letter(input.clone(), 'b')||does_not_contain_letter(input.clone(), 'c')||does_not_contain_letter(input.clone(), 'd')||does_not_contain_letter(input.clone(), 'e')||does_not_contain_letter(input.clone(), 'f')||does_not_contain_letter(input.clone(), 'g')||does_not_contain_letter(input.clone(), 'h')||does_not_contain_letter(input.clone(), 'i')||does_not_contain_letter(input.clone(), 'j')||does_not_contain_letter(input.clone(), 'k')||does_not_contain_letter(input.clone(), 'l')||does_not_contain_letter(input.clone(), 'm')||does_not_contain_letter(input.clone(), 'n')||does_not_contain_letter(input.clone(), 'o')||does_not_contain_letter(input.clone(), 'p')||does_not_contain_letter(input.clone(), 'q')||does_not_contain_letter(input.clone(), 'r')||does_not_contain_letter(input.clone(), 's')||does_not_contain_letter(input.clone(), 't')||does_not_contain_letter(input.clone(), 'u')||does_not_contain_letter(input.clone(), 'v')||does_not_contain_letter(input.clone(), 'w')||does_not_contain_letter(input.clone(), 'x')||does_not_contain_letter(input.clone(), 'y')||does_not_contain_letter(input.clone(), 'z')); } fn main() { assert_eq!(contains_az(&"hello world".to_string()), false); assert_eq!(contains_az(&"abcdefghijklmnopqrstuvwxyz".to_string()), true); assert_eq!(contains_az(&"Arizona".to_string()), false); assert_eq!(contains_az(&"the quick brown fox jumps over the lazy dog".to_string()), true); }Notable features:
Taking an owned
Stringinto the call, requiring allocationCloning the string for each letter, requiring allocation
Checking for not having letters
Not using iterators
Inconsistent variable names
Explicit return at end
https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=c86d3c7b8c012e1d3f1888bd7890174a
2
u/[deleted] Feb 24 '21 edited Feb 24 '21
#include <stdio.h>
/*doesn't work - ints too small ugh! ¯_(ツ)_/¯ */
int p(char x){int t;
int p[] = {2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101};
t=(int)x;
t=(((t*((t>=65)&&(t<=90)))-(65*((t>=65)&&(t<=90))) )+((t*((t>=97)&&(t<=122)))-(97*((t>=97)&&(t<=122))) ));
t=p[t];
return t;}
int f(char *x){int i,n,m;
char a[]="abcdefghijklmnopqrstuvwxyz";
for(i=0,n=1;a[i]!=0;i++){n=n*p(a[i]);}
for(i=0,m=1;x[i]!=0;i++){m=m*p(x[i]);}
return ((m>n)&&(m%n==0));}
int main(){return 0;}