16
\$\begingroup\$

Introduction

Every string has an "alphabet", composed of the characters that make it up. For example, the alphabet of \$abcaabbcc\$ is \${a, b,c}\$. There are two operations you can do with alphabets: getting the alphabet of a string, and seeing if another string has a given alphabet.

Challenge

Given two strings, you must write a function that finds the alphabet of the first string, and returns a truthy or falsy value based on whether that alphabet makes up the second string, ie. if the alphabet of the first string is the same as that of the second. However, the function should also return a truthy value if the alphabet of the first string is a superset of, or contains, the alphabet of the second.

  • The two strings will be of variable length. They might be empty. If they are, their alphabets are considered and empty list/set. Any valid unicode string could be an input.
  • The function must return a truthy or falsy value. Any type of output is OK, as long as, when converted to a boolean in your language (or the equivalent), it is true.

Examples

  • String 1: "abcdef", String 2: "defbca"
    Output: truthy
  • String 1: "abc", String 2: "abc123"
    Output: falsy
  • String 1: "", String 2: ""
    Output: truthy
  • String 1: "def", String 2: "abcdef"
    Output falsy
  • String 1: "abcdef", String 2: "abc"
    Output truthy
  • String 1: "😀😁😆", String 2: "😁😆😀"
  • Output: truthy

Rules

This is , so shortest answer in bytes wins!

\$\endgroup\$
  • 7
    \$\begingroup\$ Did you mean String 1: "abcdef", String 2: "def" for the last test case? \$\endgroup\$ – Arnauld Oct 25 at 21:28
  • \$\begingroup\$ Test cases with repeating letters would also be good. \$\endgroup\$ – xnor Oct 25 at 21:46
  • 8
    \$\begingroup\$ Then, it's basically the same test case as the 2nd one. You should add one where the 1st alphabet is a superset of the 2nd. \$\endgroup\$ – Arnauld Oct 25 at 22:10
  • 3
    \$\begingroup\$ "Any valid unicode string could be an input." <-- if unicode support is mandatory, you should include some unicode test cases. (I have a feeling some existing answers will fail them.) \$\endgroup\$ – Nathaniel Oct 26 at 19:58
  • 3
    \$\begingroup\$ Recommended test case: {"😀😁😆", "😀😁😆🀀", falsey} (Explanation: 😀 is F0 98 9F 80 in UTF-8, 🀀 is F0 9F 80 80 in UTF-8; If an answer is checking the UTF-8 bytes instead of characters, it will return truthy) \$\endgroup\$ – pizzapants184 Oct 27 at 20:18

37 Answers 37

19
\$\begingroup\$

Python 3, 21 bytes

lambda a,b:{*a}>={*b}

Try it online!

\$\endgroup\$
9
\$\begingroup\$

Haskell, 13 bytes

all.flip elem

Try it online!

Haskell doesn't have built-in set or subset functions, so we need to do it ourselves. This is a pointfree version of

17 bytes

a%b=all(`elem`a)b

Try it online!

which it itself shortened from

22 bytes

a%b=and[elem c a|c<-b]

Try it online!

\$\endgroup\$
6
\$\begingroup\$

Python 3, 28 23 bytes

lambda x,y:not{*y}-{*x}

Try it online!

-5 bytes thanks to Wizzwizz4

28 bytes

lambda x,y:not set(y)-set(x)

Try it online!

Simply turns the two inputs into sets and subtracts the sets from each other

\$\endgroup\$
  • \$\begingroup\$ If you used {*y} syntax, you could remove that space for -5 bytes. \$\endgroup\$ – wizzwizz4 Oct 26 at 14:50
4
\$\begingroup\$

Brachylog, 3 bytes

dp⊆

Try it online!

Takes string 1 as the output variable and string 2 as the input variable.

\$\endgroup\$
4
\$\begingroup\$

JavaScript (ES6), 31 bytes

Takes arrays of characters as input.

a=>b=>b.every(c=>a.includes(c))

Try it online!


25 bytes

For the record, below is my original answer, which was designed for alphanumeric characters.

a=>b=>!b.match(`[^${a}]`)

Try it online!

\$\endgroup\$
  • \$\begingroup\$ Won't this fail if a contains a hyphen? e.g f("a-c")("abc") \$\endgroup\$ – Shaggy Oct 25 at 22:35
  • \$\begingroup\$ @Shaggy Yes, I overlooked the any valid unicode string part. Updated. \$\endgroup\$ – Arnauld Oct 25 at 23:14
2
\$\begingroup\$

Pyth, 7 bytes

g.{w.{w

Try it online!

First string on first line of input, second string on second line.

\$\endgroup\$
  • \$\begingroup\$ I'm pretty sure !-E works. \$\endgroup\$ – FryAmTheEggman Oct 25 at 21:54
  • 1
    \$\begingroup\$ Submit it separately then, you'll deserve any upvotes you get for it. \$\endgroup\$ – randomdude999 Oct 25 at 22:02
2
\$\begingroup\$

J, 5 bytes

*/@e.

Try it online!

Is each char of the 2nd string an element of e. the 1st string? This returns a boolean mask, whose elements we multiply together with */. J is smart about 0 values so that if you apply */ to the empty list '' you get 1.

J, 6 bytes

''-:-.

Try it online!

Does the empty string '' match -: 1st string "set minused" -. from the 2nd?

\$\endgroup\$
2
\$\begingroup\$

Japt -!, 15 10 5 bytes

k@VøX

Try it online!

Thanks to @Shaggy for -5.

\$\endgroup\$
  • \$\begingroup\$ Welcome to Japt! \$\endgroup\$ – Shaggy Oct 25 at 22:26
  • 1
    \$\begingroup\$ 6 bytes, using the -! flag. \$\endgroup\$ – Shaggy Oct 25 at 22:31
  • \$\begingroup\$ Or maybe 5 bytes \$\endgroup\$ – Shaggy Oct 25 at 22:33
  • 1
    \$\begingroup\$ Flags are free ;) \$\endgroup\$ – Shaggy Oct 25 at 23:46
  • \$\begingroup\$ 4 bytes? \$\endgroup\$ – Shaggy Oct 25 at 23:48
2
\$\begingroup\$

APL (Dyalog Unicode), 3 bytes

×/∊

Try it online!

Use it as string2 f string1.

How it works

×/∊
  ∊  Does each char of string2 appear in string1?
×/   All of them?
\$\endgroup\$
  • \$\begingroup\$ Switch to dzaima/APL and save a byte: ∧∊ Try it online! \$\endgroup\$ – Adám Nov 3 at 13:46
2
\$\begingroup\$

Ruby, 21 bytes

->x,y{!y.tr(x,"")[0]}

The tr method replaces all instances of the first string it's passed with the corresponding character in the second string it's passed. So all characters from x are removed from y. If there are any characters left, then it returns the first value (all values are truthy in ruby except false and nil) and inverses it. And if there are no characters left, then nil is inversed.

Golfy Tricks Implemented:

  • Using y.tr(x,"") instead of y.chars-x.chars
  • Using !array[0] instead of array.empty?

Try it online!

\$\endgroup\$
2
\$\begingroup\$

W, 4 bytes

W is a new esolang inspired by Wren dedicated to cancelling out Wren's verbosity. (Well, I guess this beats ties with Keg...)

t''=

Explanation

This transpiles to the following Wren code:

Fn.new {|A, B| "" == B.trim(A)}

Try the full program online!

t    Trim the implicitly-given inputs
 ''  Return a null string
   = Check equality

Wren, 86 60 30 26 bytes

I didn't expect this. Wren is very hard to golf.

Fn.new{|a,b|b.trim(a)==""}

Try it online!

Explanation

Fn.new{                    // New anonymous function
       |a,b|               // With parameters a and b
            b.trim(a)      // After removing all characters in a that are in b
                           // (If b can be assembled using a the result should
                           // be a null string; otherwise it should be a
                           // non-empty string.
                     ==""} // Is this result an empty string?
\$\endgroup\$
  • \$\begingroup\$ Fn.new{ ... } is a bit verbose (comparing to (vars)=>expression) but it looks so pretty. And the "meat" is quite small (just 18 bytes)! \$\endgroup\$ – Ismael Miguel Oct 28 at 16:56
  • 2
    \$\begingroup\$ Never think of eating a wren. It is tiny and you can't get a lot of meat out of it despite of its attracting appearance. \$\endgroup\$ – A _ Oct 29 at 14:25
2
\$\begingroup\$

MATL, 3 bytes

wmA

Try it online! Or verify all test cases.

Explanation

The code implicitly takes two strings as inputs, swaps them, and verifies if All the characters in the first string (originally the second input) are members of the other string.

(A non-empty array containing exclusively ones is truthy in MATL. This would allow omitting A if it wasn't for the case with empty inputs).

\$\endgroup\$
1
\$\begingroup\$

Zsh, 35 bytes

a=(${(s::)1})
((!${#${(s::)2}:|a}))

Try it online!

      ${(s::)2}        # split second parameter into characters
   ${          :|a}    # remove all elements of $a
   ${#            }    # count
((!                ))  # return truthy if 0, falsy if non-zero
\$\endgroup\$
1
\$\begingroup\$

Jelly, 3 bytes

fƑ@

Try it online!

A dyadic link taking two strings and returning a Boolean. If the order of the input s can be reversed, I could save one byte.

Works by checking whether the second string is unchanged when filtering to just the characters in the first.

\$\endgroup\$
  • \$\begingroup\$ The OP has now said that the input order cannot be reversed :-/ \$\endgroup\$ – Luis Mendo Oct 26 at 10:01
1
\$\begingroup\$

Haskell, 24 bytes

f a b=all(\c->elem c a)b

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Japt -!, 3 bytes

VkU

Try it

VkU   U = first string, V = second
Vk    Remove all characters in V
  U   that are present in U
-!    If the string is empty, return true, else false
\$\endgroup\$
1
\$\begingroup\$

R, 40 bytes

function(x,y,`+`=utf8ToInt)all(+y%in%+x)

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Bracmat, 51 bytes

(f=a b.!arg:(?a,?b)&vap$((=.@(!a:? !arg ?)&|F).!b))

The function f returns a list of Fs, one F for each character in b that is not in a's alphabet. An empty list means that b's alphabet is contained in a's alphabet. The function vap splits the second argument, which must be a string, in UTF-8 encoded characters if the second argument (!b in this case) is valid UTF-8, and otherwise in bytes.

Try it online!

\$\endgroup\$
1
\$\begingroup\$

C (gcc), 94 85 bytes

f(a,b,c)int*a,*b,*c;{for(;*b;++b){for(c=a;*c&&*c!=*b;++c);if(!*c)return 0;}return 1;}

Try it online!

-9 bytes from JL2210

Returns int: 1 for truthy and 0 for falsey.

Note: takes two parameters that are each pointers to null-terminated wide strings (wchar_t are the same size as int on the platform used on TIO, so we can take the strings as int* instead of including wchar.h and taking them as wchar_t*)

Explanation/Ungolfed:

#include <wchar.h>
int f(const wchar_t *a, const wchar_t *b) {
    for ( ; *b != L'\0'; ++b) { // For each character in the second string
        const wchar_t *temp;
        for (temp = a; *temp != L'\0'; ++temp) {
            if (*temp == *b) break;
            // If the character is in the first string,
            // then continue and check the next character
        }
        if (*temp == L'\0') return 0;
        // If the character was not found, return 0 (falsey)
    }
    return 1; // If every character was found, return 1 (truthy)
}
\$\endgroup\$
1
\$\begingroup\$

Lua, 75 bytes

load'b,a=...return a:gsub(".",load"return not b:find(...,1,1)and [[]]")==a'

Try it online!

Now this is a bit messy. load is used to create function here, so everything inside is its body. Here, after taking input, following transformation is done: every symbol in second string is checked in first one. If it is found, internal function return false and no replacement is done. Otherwise, symbol is removed (replaced with empty string). Resulting string is compared with one passed as input, efficiently checking that no deletions were performed.

TIO link also include test cases.

\$\endgroup\$
  • \$\begingroup\$ awesome golfing \$\endgroup\$ – LMD Oct 28 at 18:17
1
\$\begingroup\$

PHP (7.4), 26 25 bytes

fn($a,$b)=>!strtok($b,$a)

Try it online!

PHP's strtok, basically removes characters of its second parameter, form its first parameter and returns the result or false if the result is empty. By removing $a characters from $b, if the result is empty (false), we output a truthy, else a falsy.

\$\endgroup\$
  • 1
    \$\begingroup\$ Alternativelly, for PHP 4.1.2 and older, you can use <?=!strtok($b,$a); (18 bytes) directly, where the short_open_tag and register_globals default to 1 (enabled). For this, a POST/GET/COOKIE/SESSION would need to have the keys a and b set. \$\endgroup\$ – Ismael Miguel Oct 28 at 16:51
  • 1
    \$\begingroup\$ @IsmaelMiguel I prefer to forget register globals and old PHP versions. You can post it as a separate answer though. \$\endgroup\$ – Night2 Oct 28 at 17:02
  • 1
    \$\begingroup\$ No, thanks. Was just posting it as a reminder that PHP used to be a lot worse. \$\endgroup\$ – Ismael Miguel Oct 28 at 17:43
1
\$\begingroup\$

Lua, 114 bytes

d=function(a,c,v)for _,k in ipairs(a) do c[k]=v end end
function l(a,b)c={};d(b,c,1);d(a,c);return not next(c) end

Try it online!

Couldn't get it shorter with plain Lua because lightweight Lua knows few builtins. If it needs to work with strings:

Lua, 116 bytes

function d(a,c,v)for _,k in a:gmatch"." do c[k]=v end end
function l(a,b)c={};d(b,c,1);d(a,c);return not next(c) end

Try it online!

\$\endgroup\$
  • \$\begingroup\$ I think you can't use ipairs on strings? \$\endgroup\$ – val Oct 28 at 12:01
  • \$\begingroup\$ @val I can't. I expect the input to be a list/table with the characters. Else it would be around ~20 bytes longer I assume. \$\endgroup\$ – LMD Oct 28 at 17:56
  • \$\begingroup\$ I think it doesn't fulfill challenge requirements then: "given two strings". I like the idea tho! \$\endgroup\$ – val Oct 28 at 18:02
  • \$\begingroup\$ @val A string essentially is a list of characters. But I could add a solution for strings too. \$\endgroup\$ – LMD Oct 28 at 18:03
  • \$\begingroup\$ @val added, at the cost of two additional bytes \$\endgroup\$ – LMD Oct 28 at 18:07
1
\$\begingroup\$

Gaia, 1 byte

Try it online!

Just a built-in. For strings, it checks for character-wise superset.

Test Suite

\$\endgroup\$
1
\$\begingroup\$

CJam, 5 bytes

ll\-!

Try it online!

Test Suite

Explanation

ll     Read 2 lines of input
  \    Swap their order
   -   Remove from the second input all characters in the first
    !  Negate
\$\endgroup\$
1
\$\begingroup\$

Keg, 13 7 5 4 bytes

-``=

Try it online!

-1 byte with trailing newline

And y'all thought W could beat Keg!

This one's a bit of a stretch, as it uses a footer and header to define a function. I'll explain later.

Answer History

7 bytes (SBCS)

᠀᠀^-``=

Try it online!

-6 bytes due to the fact I realised I could just compare the result to an empty string.

Explained

᠀᠀^-``=
᠀᠀      #Take the two input strings
  ^     #Reverse stack to place strings in correct input order
   -    #Subtract the first string from the second
    ``= #Compare the result to an empty string, pushing either 1 or 0

13 bytes (SBCS)

᠀᠀^-÷!&ø&[0|1

Try it online!

Uses features from Keg, Reg and Keg+!

Explained

᠀᠀^-÷!&ø&[0|1
᠀᠀              #Take the two strings as input
  ^             #Reverse the stack so that string subtraction works
   -÷           #Subtract first input from second and item split the result
     !          #Push the length of this splitted string
      &ø&       #Safely store this length in the register while clearing the stack
         [0|1   #Push 0 if there are still items otherwise 1 if empty string
\$\endgroup\$
  • \$\begingroup\$ You're using a code snippet if you don't include the code defining the function. \$\endgroup\$ – A _ Oct 28 at 12:33
0
\$\begingroup\$

Charcoal, 5 bytes

⬤η№θι

Try it online! Link is to verbose version of code. Outputs a Charcoal boolean, i.e. - for true, nothing for false. Explanation:

⬤       All of
 η      Second string
  №     Count (is non-zero) in
   θ    First string of
    ι   Character of second string
        Implicitly print
\$\endgroup\$
0
\$\begingroup\$

Perl 5, 53 bytes

sub{local$_=pop;eval"y/@{[quotemeta pop]}//d";!y///c}

Try it online!

\$\endgroup\$
0
\$\begingroup\$

Rust, 106 104 bytes

|a:&str,b:&str|{let c=|x:&str|x.chars().collect::<std::collections::HashSet<_>>();c(b).is_subset(&c(a))}

Try it online!

\$\endgroup\$
0
\$\begingroup\$

Scala, 46 bytes

(a:String,b:String)=>(b.toSet&~a.toSet)==Set()

Try it online!

\$\endgroup\$
0
\$\begingroup\$

Perl 6, 17 bytes

!(*R∖*)o**.comb

Try it online!

Also known as Raku. Anonymous code object taking two arguments and returning a boolean.

Explanation:

       **.comb   # Map each string to a list of characters
      o          # Then return if
  *R∖*           # The second argument set minus the first
!(    )          # Is empty?

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.