27
\$\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!

The Catalogue

The Stack Snippet at the bottom of this post generates the catalogue from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

## Language Name, N bytes

where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:

## Ruby, <s>104</s> <s>101</s> 96 bytes

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:

## Perl, 43 + 2 (-p flag) = 45 bytes

You can also make the language name a link which will then show up in the snippet:

## [><>](https://esolangs.org/wiki/Fish), 121 bytes

/* Configuration */

var QUESTION_ID = 194869; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 8478; // This should be the user ID of the challenge author.

/* App */

var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;

function answersUrl(index) {
  return "https://api.stackexchange.com/2.2/questions/" +  QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}

function commentUrl(index, answers) {
  return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}

function getAnswers() {
  jQuery.ajax({
    url: answersUrl(answer_page++),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      answers.push.apply(answers, data.items);
      answers_hash = [];
      answer_ids = [];
      data.items.forEach(function(a) {
        a.comments = [];
        var id = +a.share_link.match(/\d+/);
        answer_ids.push(id);
        answers_hash[id] = a;
      });
      if (!data.has_more) more_answers = false;
      comment_page = 1;
      getComments();
    }
  });
}

function getComments() {
  jQuery.ajax({
    url: commentUrl(comment_page++, answer_ids),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      data.items.forEach(function(c) {
        if (c.owner.user_id === OVERRIDE_USER)
          answers_hash[c.post_id].comments.push(c);
      });
      if (data.has_more) getComments();
      else if (more_answers) getAnswers();
      else process();
    }
  });  
}

getAnswers();

var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;

var OVERRIDE_REG = /^Override\s*header:\s*/i;

function getAuthorName(a) {
  return a.owner.display_name;
}

function process() {
  var valid = [];
  
  answers.forEach(function(a) {
    var body = a.body;
    a.comments.forEach(function(c) {
      if(OVERRIDE_REG.test(c.body))
        body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>';
    });
    
    var match = body.match(SCORE_REG);
    if (match)
      valid.push({
        user: getAuthorName(a),
        size: +match[2],
        language: match[1],
        link: a.share_link,
      });
    else console.log(body);
  });
  
  valid.sort(function (a, b) {
    var aB = a.size,
        bB = b.size;
    return aB - bB
  });

  var languages = {};
  var place = 1;
  var lastSize = null;
  var lastPlace = 1;
  valid.forEach(function (a) {
    if (a.size != lastSize)
      lastPlace = place;
    lastSize = a.size;
    ++place;
    
    var answer = jQuery("#answer-template").html();
    answer = answer.replace("{{PLACE}}", lastPlace + ".")
                   .replace("{{NAME}}", a.user)
                   .replace("{{LANGUAGE}}", a.language)
                   .replace("{{SIZE}}", a.size)
                   .replace("{{LINK}}", a.link);
    answer = jQuery(answer);
    jQuery("#answers").append(answer);

    var lang = a.language;
    lang = jQuery('<a>'+lang+'</a>').text();
    
    languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang, user: a.user, size: a.size, link: a.link};
  });

  var langs = [];
  for (var lang in languages)
    if (languages.hasOwnProperty(lang))
      langs.push(languages[lang]);

  langs.sort(function (a, b) {
    if (a.lang_raw.toLowerCase() > b.lang_raw.toLowerCase()) return 1;
    if (a.lang_raw.toLowerCase() < b.lang_raw.toLowerCase()) return -1;
    return 0;
  });

  for (var i = 0; i < langs.length; ++i)
  {
    var language = jQuery("#language-template").html();
    var lang = langs[i];
    language = language.replace("{{LANGUAGE}}", lang.lang)
                       .replace("{{NAME}}", lang.user)
                       .replace("{{SIZE}}", lang.size)
                       .replace("{{LINK}}", lang.link);
    language = jQuery(language);
    jQuery("#languages").append(language);
  }

}
body {
  text-align: left !important;
  display: block !important;
}

#answer-list {
  padding: 10px;
  width: 290px;
  float: left;
}

#language-list {
  padding: 10px;
  width: 500px;
  float: left;
}

table thead {
  font-weight: bold;
}

table td {
  padding: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Sites/codegolf/all.css?v=ffb5d0584c5f">
<div id="language-list">
  <h2>Shortest Solution by Language</h2>
  <table class="language-list">
    <thead>
      <tr><td>Language</td><td>User</td><td>Score</td></tr>
    </thead>
    <tbody id="languages">

    </tbody>
  </table>
</div>
<div id="answer-list">
  <h2>Leaderboard</h2>
  <table class="answer-list">
    <thead>
      <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr>
    </thead>
    <tbody id="answers">

    </tbody>
  </table>
</div>
<table style="display: none">
  <tbody id="answer-template">
    <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
  </tbody>
</table>
<table style="display: none">
  <tbody id="language-template">
    <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
  </tbody>
</table>

\$\endgroup\$
11
  • 7
    \$\begingroup\$ Did you mean String 1: "abcdef", String 2: "def" for the last test case? \$\endgroup\$
    – Arnauld
    Oct 25, 2019 at 21:28
  • \$\begingroup\$ Test cases with repeating letters would also be good. \$\endgroup\$
    – xnor
    Oct 25, 2019 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, 2019 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\$
    – N. Virgo
    Oct 26, 2019 at 19:58
  • 9
    \$\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\$ Oct 27, 2019 at 20:18

51 Answers 51

25
\$\begingroup\$

Python 3, 21 bytes

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

Try it online!

Explanation

\$\endgroup\$
2
  • \$\begingroup\$ Hi, can you explain your answer ? \$\endgroup\$ Dec 20, 2019 at 12:17
  • 1
    \$\begingroup\$ @DorianTurba Thanks for adding an explanation! \$\endgroup\$
    – xnor
    Dec 22, 2019 at 4:09
11
\$\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\$
8
\$\begingroup\$

Regex (ECMAScript 2018 / Pythonregex / .NET), 20 bytes

Takes the two strings in joined format, delimited by a single newline. That is why there are two newlines in the regex itself (saving 2 bytes compared to if \n were used):


((.)(?<=\2.*
.*))*$

Try it online! - ECMAScript 2018
Try it online! - Python import regex
Try it online! - .NET

It just so happens that the order of String 1 and String 2 dictated by this question is the one that makes it a bit nontrivial in regex, impossible to do without variable-length lookbehind or non-atomic lookahead. If it were the other way around, it would be possible in vanilla ECMAScript.

\n         # 1. Find the newline, so we can match against String 2
(          # 2. Start loop at the beginning of String 2
  (.)      # 3. At every iteration, capture another character from String 2 into \2
  (?<=     # 4. positive lookbehind - look backwards
    \2.*   # 6. Assert that the captured character \2 can be found in String 1
    \n.*   # 5. Find the newline, so we can match against String 1
  )
)*         # 7. Continue the loop as long as possible
$          # 8. Assert that when the loop has finished, we've reached String 2's end

Regex (Java), 29 or 27 bytes

Java has a limited sort of variable-length lookbehind. It's unlimited in length, but there are strict limits as to what is allowed in a lookbehind (most notably, all backreferences must be inside a lookahead inside the lookbehind), and stricter limits on what will actually work in a lookbehind. So in principle it has the same power as full-fledged variable-length lookbehind in its ability to solve computation problems, but will do so less efficiently.

In this case, two limits come into play: \2 need to be backreferenced in a lookahead, and apparently, if an expression like .*x.* is in a lookbehind (where x is any character), it will silently fail to work properly. Here we work around this problem by collapsing the .*\n.* into [\s\S]*:


((.)(?<=^(?=.*\2)[\s\S]*))*$

29 bytes - Try it online!

This problem could also be solved by using comma as a delimiter instead of newline:

,((.)(?<=^(?=[^,]*\2).*))*$

27 bytes - Try it online!

Or by using the s (dotall) flag with newline as the delimiter:


((.)(?<=^(?=[^
]*\2).*))*$

27 bytes - Try it online!

Regex (PCRE1), 48 bytes + s flag

It is possible to emulate variable-length lookbehind using recursive constant-width lookbehind:


((.)((?<=(?=
((?<=(?=$.|\2|(?4)).))|(?3)).)))*$

Try it online! (C++)
Try it on regex101

The recursive lookbehind goes through two stages in this regex: first (?3) to find the newline, and then (?4) to find the captured character. The regex could be 1 byte shorter if some character that is guaranteed not to be present in the input were used as the dummy impossible match instead of $..

/s single line mode (dotall) is used so that newline can be the delimiter, with the . in the lookbehinds being allowed to match it. With any other choice of delimiter (even a control character), this flag would not be needed. Therefore, I have not included it in the byte count. FWIW though, keeping newline as the delimiter and not using /s mode would require upping the length to 52 bytes (with a regex that runs much more slowly, due to putting the newline after the lookbehind), costing the same in bytes as adding (?s) would, thus not worthwhile.

Regex (PCRE2 / Perl 5), 45 bytes + s flag

Same approach as PCRE1, but the dummy impossible match $. is no longer needed to avoid a "recursive call could loop indefinitely" error:


((.)((?<=(?=
((?<=(?=\2|(?4)).))|(?3)).)))*$

Try it online! - PCRE2 (C++)
Try it online! - PCRE2 (PHP – doesn't work, and I don't know why)
Try it online! - Perl 5

Regex (PCRE2) length-limited, 39 38\$+\lfloor log_{10}L_{max}\rfloor\$ bytes

It is possible to emulate molecular lookbehind (and some of the power of variable-length lookbehind) using jaytea's lookahead quantification trick, but this limits the maximum possible length of String 2 to 1023 characters. In the linked blog post I commented (as Davidebyzero) on a way to extend this limit by a couple of orders of magnitude, but it nevertheless remains.

This trick does not work in Perl 5, because apparently it has the same "no empty optional" behavior as ECMAScript. [Edit: This isn't true in most circumstances. Needs to be looked into.]

1 byte can be saved by omitting the anchor. Any non-match will remain a non-match even if it is attempted from later positions in the first string, because if the second string isn't made up of a subset of the first string's characters, it certainly won't be made up of a smaller subset. This does result in a slowdown for non-matches.

((?=(?=.*
(\2?(.?))).*\3)){1,1023}?.*
\2$

Try it online! (C++)
Try it online! (PHP)

Regex (PCRE2) length-limited const, 36 35\$+\lfloor log_{10}L_{max}\rfloor\$ bytes

The regex still works with a constant quantifier (for a total length of 39 bytes), but will take more steps (but not necessarily much more time, depending on the optimization done by the regex engine).

((?=(?=.*
(\2?(.?))).*\3)){1149}.*
\2$

Try it online! (C++)
Try it online! (PHP)

Regex (Perl 5 / .NET / Java) length-limited const, 34 33\$+\lfloor log_{10}L_{max}\rfloor\$ bytes

This version works in Perl, in which the quantifier can go up to {32766} (which would make a regex length of 40 bytes, and still execute fast), and in Java, in which the quantifier apparently can go up to {400000000165150719} (but must be much smaller for execution time to be practical).

PCRE1 (and PCRE2 earlier than v10.35), as well as Ruby, treat any quantifer greater than 1 on a lookaround as being 1, so the lookaround must be wrapped in a dummy group, costing 2 bytes. But in Perl 5, .NET, Java, and Python 3, lookarounds can be directly quantified:

(?=(?=.*
(\1?(.?))).*\2){9999}.*
\1$

Try it online! - Perl 5
Try it online! - .NET (C#)
Try it online! - Java - 1 byte longer – needs the anchor for some reason – this needs investigation

Regex (PCRE1) length-limited, {45 or 42 44 or 41}\$+\lfloor log_{10}L_{max}\rfloor\$ bytes

Due to a fundamental flaw in PCRE1's design, a workaround is needed to prevent the regex from returning truthy when the last character of String 2 is not present in String 1:

((?=(?=.*
(\2?(.?))).*\3.*(
\2))){1,481}?.*\4$

Try it online! (C++)
Try it on regex101

The regex still works with a constant quantifier, but will take more steps (but not necessarily much more time, depending on the optimization done by the regex engine):

((?=(?=.*
(\2?(.?))).*\3.*(
\2))){500}.*\4$

Try it online! (C++)
Try it on regex101

Regex (Ruby) length-limited, 50 49\$+\lfloor log_{10}L_{max}\rfloor\$ bytes

The lookahead quantification trick fully works in Ruby, and can go as high as {100000}. There is no support for nested backreferences, so \2 must be copied to \4 in a lookahead:

((?=(?=.*
(\4?(.?))).*\3(?=.*
(\2)))){1,100000}?.*
\2$

Try it online!

While Ruby's regex engine does have subroutine calls, and thus at first glance it might appear to be possible to adapt the solutions that emulate variable-length lookbehind to it, it does not appear to be possible to do so. Any attempt at recursion with subroutine calls generates the error "never ending recursion", even when there are clear-cut terminating conditions.

Regex (Pythonregex) length-limited const, 44\$+\lfloor log_{10}L_{max}\rfloor\$ bytes

The lookahead quantification trick works in Python 3 (using the regex module rather than re), but only with a constant quantifier. This is a shame, because Python can go as high as {4294967294}, but increasing its value in this regex causes super-exponential slowdown. There is no support for nested backreferences, so just like the Ruby version, \2 must be copied to \4 in a lookahead.

(?=(?=.*
(\3?(.?))).*\2(?=.*
(\1))){300}.*
\1$

Try it online!

Regex (RegexMathEngine -xml), 27 bytes

In RegexMathEngine, molecular (non-atomic) lookahead can be used in the form of (?*...) when enabled using the -xml command line parameter ("enable extension: molecular lookahead").

This needs to be anchored because the delimiter is inside a negative lookahead, so without the anchor, a non-match could become a match by leapfrogging the delimiter and starting its match within the second string.

^(?!(?*.*,(.)+)(?!.*\1.*,))

Comma is the delimiter because it is not yet possible to work with strings containing newlines when using command-line invocation of this regex engine (which works as a one-line-at-a-time grep).

Regex (PCRE2 v10.35+), 27 24 bytes

PCRE does not have variable-length lookbehinds, but PCRE2 v10.34 has introduced non-atomic lookarounds in the form of (*napla:...) and (*naplb:...) (with the added synonyms of (?*...) and (?<*...) in v10.35), making it also able to solve this problem in the general case. This is shorter than in RegexMathEngine thanks to the use of newline as a delimiter:

^(?!(?*.*
(.)+)(?!.*\1))

Try it on regex101
Attempt This Online! (PHP)

You can change the delimiter (for example to comma: ^(?!(?*.*,(.)+)(?!.*\1.*,))), to test on the command line using pcre2grep.

If the strings were in the other order: Regex (ECMAScript / Python), 19 bytes

If String 2 comes before String 1, there is no need for lookbehind or non-atomic lookahead, and the solution is universal to all regex engines that have lookahead. It does now need to be anchored though, because otherwise, any non-match could become a match by discarding the beginning of the first string.

^((.)(?=.*
.*\2))*

Try it online! - ECMAScript
Try it online! - Python

^(          # start loop at the beginning of String 2
  (.)       # at every iteration, capture another character from String 2 into \2
  (?=.*\n   # look ahead to String 1 (by finding the newline)
    .*\2    # assert that the captured character \2 can be found in String 1
  )
)*          # continue the loop as long as possible
\n          # assert that when the loop has finished, we've reached String 2's end
\$\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\$
1
  • \$\begingroup\$ If you used {*y} syntax, you could remove that space for -5 bytes. \$\endgroup\$
    – wizzwizz4
    Oct 26, 2019 at 14:50
5
\$\begingroup\$

Brachylog, 3 bytes

dp⊆

Try it online!

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

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

Gaia, 1 byte

Try it online!

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

Test Suite

\$\endgroup\$
0
5
\$\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\$
1
  • 1
    \$\begingroup\$ Similar 20 byte answer. These both technically fail though because tr and count will do the wrong thing if ^ or - show up in the wrong place. \$\endgroup\$
    – histocrat
    Dec 30, 2019 at 22:05
5
\$\begingroup\$

W, 2 bytes

Back then I definitely had the negation instruction. If you think it's boring then continue.

t!

Explanation

t  % Remove all characters of 1st input that appears in 2nd input.
   % e.g. ['abcdef','abc'] -> 'def'
 ! % Negate the result. So if the resulting string had something,
   % it will return falsy. Otherwise it will yield truthy.

W, 4 bytes

W is back, reimplemented!

t""=

If you want to specify your input and code, you look for imps.py and then re-set those variables like this:

read = ["abcabc","abc"]

prog = 't""='

Note that your inputs must be in a single array with the joined values.

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\$
2
  • \$\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\$ Oct 28, 2019 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\$
    – user85052
    Oct 29, 2019 at 14:25
4
\$\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\$
1
  • \$\begingroup\$ Switch to dzaima/APL and save a byte: ∧∊ Try it online! \$\endgroup\$
    – Adám
    Nov 3, 2019 at 13:46
3
\$\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\$
0
3
\$\begingroup\$

Japt -!, 15 10 5 bytes

k@VøX

Try it online!

Thanks to @Shaggy for -5.

\$\endgroup\$
6
  • \$\begingroup\$ Welcome to Japt! \$\endgroup\$
    – Shaggy
    Oct 25, 2019 at 22:26
  • 1
    \$\begingroup\$ 6 bytes, using the -! flag. \$\endgroup\$
    – Shaggy
    Oct 25, 2019 at 22:31
  • \$\begingroup\$ Or maybe 5 bytes \$\endgroup\$
    – Shaggy
    Oct 25, 2019 at 22:33
  • 1
    \$\begingroup\$ Flags are free ;) \$\endgroup\$
    – Shaggy
    Oct 25, 2019 at 23:46
  • \$\begingroup\$ 4 bytes? \$\endgroup\$
    – Shaggy
    Oct 25, 2019 at 23:48
3
\$\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\$
3
\$\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\$
4
  • 1
    \$\begingroup\$ 85 bytes \$\endgroup\$
    – S.S. Anne
    Oct 27, 2019 at 23:25
  • 1
    \$\begingroup\$ 78 bytes \$\endgroup\$
    – ceilingcat
    Oct 28, 2019 at 5:58
  • \$\begingroup\$ @ceilingcat 74 bytes by replacing last return with a= \$\endgroup\$
    – girobuz
    Jan 21, 2020 at 22:12
  • \$\begingroup\$ building on @ceilingcat 76 bytes \$\endgroup\$
    – c--
    Jul 3, 2022 at 4:12
3
\$\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\$
1
  • \$\begingroup\$ awesome golfing \$\endgroup\$
    – Luatic
    Oct 28, 2019 at 18:17
3
\$\begingroup\$

PHP (7.4), 26 25 28 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.

Christoph mentioned an issue with output of '0' from strtok (which equals to false), and to solve it, ''>= is used instead of a simple NOT (!) at a cost of +3 bytes. ''== would work the same way as well.

\$\endgroup\$
5
  • 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\$ Oct 28, 2019 at 16:51
  • 2
    \$\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, 2019 at 17:02
  • 1
    \$\begingroup\$ No, thanks. Was just posting it as a reminder that PHP used to be a lot worse. \$\endgroup\$ Oct 28, 2019 at 17:43
  • \$\begingroup\$ Sadly this doesn't work correctly e.g. 'abc', 'abc0a123'. strtok returns '0' which will then be transformed to true. \$\endgroup\$
    – Christoph
    Jan 23, 2020 at 13:56
  • 1
    \$\begingroup\$ @Christoph Thanks, fixed. \$\endgroup\$
    – Night2
    Jan 24, 2020 at 17:17
2
\$\begingroup\$

Pyth, 7 bytes

g.{w.{w

Try it online!

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

\$\endgroup\$
3
  • 2
    \$\begingroup\$ I'm pretty sure !-E works. \$\endgroup\$ Oct 25, 2019 at 21:54
  • 1
    \$\begingroup\$ Submit it separately then, you'll deserve any upvotes you get for it. \$\endgroup\$ Oct 25, 2019 at 22:02
  • \$\begingroup\$ Also 7 bytes \$\endgroup\$
    – hakr14
    Feb 13, 2021 at 0:39
2
\$\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\$
0
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\$
0
2
\$\begingroup\$

Kotlin, 35 bytes

{a,b->(b.toSet()-a.toSet()).none()}

Try it online!

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

PowerShell, 34 bytes

param($a,$b)0-notin($b|%{$_-in$a})

Try it online!

Takes two arrays of chars as input.

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

K (ngn/k), 5 bytes

~^&/?

Try it online!

A tacit function taking two arguments.

  • ? find the indices of the first matches of the right-hand argument in the left-hand argument; returns 0N (null) if it's not present
  • &/ take the minimum
  • ~^ is the minimum not null?
\$\endgroup\$
2
\$\begingroup\$

C (gcc), 51 bytes

f(a,b)int*a,*b;{return wcschr(a,*b)&&f(a,b+1)|!*b;}

Try it online!

In this 51 bytes version I tweaked a little bit the 53 bytes version (see below, former answer) thanks to && :

  • At each letter *b I check we can find it in string a.
  • If not, it means wcschr(a,*b) equal 0, so the program will not bother to execute the second part &&f(a,b+1) (that allows us to go deeper in the recursive) and so it return 0...
  • ...along with !*b | NOT of pointer b: if we had arrived at the end of b, the pointer is NULL so we return 0|!NULL <=> 0|1 <=> 1. If the pointer is not NULL (which means wcschr(a,*b) previously returned NULL before string a's \0) then we return 0|!PTR <=> 0|0 <=> 0

C (gcc), 53 bytes

f(a,b)int*a,*b;{return*b&&wcschr(a,*b)?f(a,b+1):!*b;}

Try it online!

This is a recursive function

  • wcschr(a,*b) looks for unicode character *b in string a, return NULL character is not found, else pointer to the character (!=NULL).
  • We keep looking if 1/ we are not at the end of string b (*b!=NULL) and 2/ while we keep finding our char *b in string a.
  • If both conditions are true we inspect our next character in string b f(a,b+1)
  • if not we return NOT of the pointer to *b : if we had arrived at the end of b then *b is NULL and our function return true, if not it means that wcschr failed before reaching end of string b.

NB: wcschr is the builtin function equivalent of strchr (man strchr)

#include <wchar.h>
#ifndef WCSCHR
# define WCSCHR __wcschr
#endif
/* Find the first occurrence of WC in WCS.  */
wchar_t *
WCSCHR (const wchar_t *wcs, const wchar_t wc)
{
  do
    if (*wcs == wc)
      return (wchar_t *) wcs;
  while (*wcs++ != L'\0');
  return NULL;
}
libc_hidden_def (__wcschr)
weak_alias (__wcschr, wcschr)
libc_hidden_weak (wcschr)
\$\endgroup\$
1
  • \$\begingroup\$ it looks like you're reading past the end of string b in the 51 byte verion this should fix it \$\endgroup\$
    – c--
    Jul 3, 2022 at 4:03
2
\$\begingroup\$

Whispers v1, 50 43 bytes

> Input
> Input
>> {2}
>> 3⊆1
>> Output 4

Try it online!

Squeezed pseudo code:

>> Output ( Set(Input2) ⊆ Input 1)

Explanation:

As always in Whispers, we execute the last line first:

>> Output 4

Outputs the result of line 4:

>> 3⊆1

Returns a Boolean representing the result of line 3 being a subset of the result of line 1. Let's evaluate line 1 first:

>> Input

Takes the first line of the input.

Now line 3:

>> {2}

This line forms the set of the result of line 2, which takes the next line of input.

So we get the squashed pseudocode:

>> Output ( Set(Input2) ⊆ Input 1)
\$\endgroup\$
2
\$\begingroup\$

x86-16 machine code, 14 bytes

00000000: 85c9 ac57 518b caf2 ae59 5fe1 f5c3       ...WQ....Y_...

Listing:

85 C9       TEST CX, CX         ; check for empty string
        S_LOOP: 
AC          LODSB               ; next char in string 2 
57          PUSH DI             ; save first string pointer 
51          PUSH CX             ; save first string length 
8B CA       MOV  CX, DX         ; put first string length into scan counter 
F2 AE       REPNZ SCASB         ; compare string 2 char to each in string 1 until match 
59          POP  CX             ; restore first string length 
5F          POP  DI             ; restore first string pointer 
E1 F5       LOOPZ S_LOOP        ; loop until end of second string OR no matches 
C3          RET                 ; return to caller

Callable function - input string 1 at [DI] length in DX, string 2 at [SI] length in CX. Output ZF if Truthy, NZ if Falsy.

Programming note: if input string 2 is empty, it will (harmlessly) loop 65,535 times in order to correctly return ZF. This is because LOOPcc decrements before testing for 0 so it must wrap around the 16-bit counter register before reaching 0 again. Otherwise a JZ or JCXZ after the TEST would eliminate this at a cost of +2 bytes, but hey, this is Code Golf not Efficiency Golf.

Tests:

enter image description here

Try it online!

\$\endgroup\$
1
\$\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\$
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\$

Perl 5, 53 bytes

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

Try it online!

\$\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\$
1
  • \$\begingroup\$ The OP has now said that the input order cannot be reversed :-/ \$\endgroup\$
    – Luis Mendo
    Oct 26, 2019 at 10:01
1
\$\begingroup\$

Haskell, 24 bytes

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

Try it online!

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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