Do you make me up?

19

5

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
  • String 1: "abcdef", String 2: "acf"
  • 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>

sugarfi

Posted 2019-10-25T21:20:35.743

Reputation: 1 239

7Did you mean String 1: "abcdef", String 2: "def" for the last test case? – Arnauld – 2019-10-25T21:28:21.773

Test cases with repeating letters would also be good. – xnor – 2019-10-25T21:46:38.350

@Arnauld - sorry, about that, I meant the output to be falsy. I fixed it now. – sugarfi – 2019-10-25T22:06:36.333

8Then, 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. – Arnauld – 2019-10-25T22:10:23.573

Can we take the inputs in reverse order? – Embodiment of Ignorance – 2019-10-26T01:42:53.557

No, inputs will always be in the order mentioned. – sugarfi – 2019-10-26T02:05:56.677

3"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.) – Nathaniel – 2019-10-26T19:58:15.747

"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." you should include a test case for this. – Okx – 2019-10-27T18:59:30.517

7Recommended 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) – pizzapants184 – 2019-10-27T20:18:00.470

Suggested test case: "abcdef", "acf" (which I think should be truthy if I understand the challenge correctly)? Some of the answers are incorrect for this test case. – Kevin Cruijssen – 2020-01-21T11:05:44.930

@KevinCruijssen - ok, will do. – sugarfi – 2020-01-21T22:01:47.553

Answers

23

xnor

Posted 2019-10-25T21:20:35.743

Reputation: 115 687

Hi, can you explain your answer ? – Dorian Turba – 2019-12-20T12:17:39.817

1@DorianTurba Thanks for adding an explanation! – xnor – 2019-12-22T04:09:21.027

10

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!

xnor

Posted 2019-10-25T21:20:35.743

Reputation: 115 687

6

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

Lyxal

Posted 2019-10-25T21:20:35.743

Reputation: 5 253

If you used {*y} syntax, you could remove that space for -5 bytes. – wizzwizz4 – 2019-10-26T14:50:38.773

5

Brachylog, 3 bytes

dp⊆

Try it online!

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

Unrelated String

Posted 2019-10-25T21:20:35.743

Reputation: 5 300

4

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!

Arnauld

Posted 2019-10-25T21:20:35.743

Reputation: 111 334

Won't this fail if a contains a hyphen? e.g f("a-c")("abc") – Shaggy – 2019-10-25T22:35:46.877

@Shaggy Yes, I overlooked the any valid unicode string part. Updated. – Arnauld – 2019-10-25T23:14:33.913

4

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?

user85052

Posted 2019-10-25T21:20:35.743

Reputation:

Fn.new{ ... } is a bit verbose (comparing to (vars)=>expression) but it looks so pretty. And the "meat" is quite small (just 18 bytes)! – Ismael Miguel – 2019-10-28T16:56:07.993

2Never 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. – None – 2019-10-29T14:25:29.313

4

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!

IMP1

Posted 2019-10-25T21:20:35.743

Reputation: 510

1Similar 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. – histocrat – 2019-12-30T22:05:45.217

3

Japt -!, 15 10 5 bytes

k@VøX

Try it online!

Thanks to @Shaggy for -5.

randomdude999

Posted 2019-10-25T21:20:35.743

Reputation: 789

Welcome to Japt! – Shaggy – 2019-10-25T22:26:19.280

16 bytes, using the -! flag. – Shaggy – 2019-10-25T22:31:36.687

Or maybe 5 bytes

– Shaggy – 2019-10-25T22:33:49.883

1Flags are free ;) – Shaggy – 2019-10-25T23:46:49.017

4 bytes? – Shaggy – 2019-10-25T23:48:15.250

4-byte one seems broken to me and i can't figure out how to fix it @Shaggy. fixed the thing about flags though – randomdude999 – 2019-10-26T00:37:42.757

3

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?

Jonah

Posted 2019-10-25T21:20:35.743

Reputation: 8 729

3

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)
}

pizzapants184

Posted 2019-10-25T21:20:35.743

Reputation: 3 174

185 bytes – S.S. Anne – 2019-10-27T23:25:46.447

178 bytes – ceilingcat – 2019-10-28T05:58:31.217

@ceilingcat 74 bytes by replacing last return with a= – girobuz – 2020-01-21T22:12:46.700

3

Gaia, 1 byte

Try it online!

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

Test Suite

Business Cat

Posted 2019-10-25T21:20:35.743

Reputation: 8 927

3

Regex (ECMAScript 2018 / Python 3 / .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 / Node.js)
Try it online! (Python 3)
Try it online! (.NET / C#)

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 on regex101 (only takes one input at a time)

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\$+\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.

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

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

Regex (PCRE2) length-limited const, 36\$+\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\$+\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)

Regex (PCRE1) length-limited, {45 or 42}\$+\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 on regex101 (only takes one input at a time)

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 on regex101 (only takes one input at a time)

Regex (Ruby) length-limited, 50\$+\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 (Python 3) 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.

Since regex.match() (as opposed to regex.findall()) puts an implied ^ at the beginning of the pattern, 1 byte can be dropped from the regex:

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

Try it online!

Regex (PCRE2 v10.34), 32 29 bytes

PCRE does not have variable-length lookbehinds, but PCRE2 v10.34 has introduced non-atomic lookarounds in the form of (*napla:...) and (*naplb:...), making it also able to solve this problem in the general case:

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

Try it online! (C) (doesn't work yet because TIO still has only PCRE2 v10.33)
Try it online! (PHP) (doesn't work yet because TIO still has only PCRE2 v10.33)

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

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"):

^(?!(?*.*,(.)+)(?!.*\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).

If the strings were in the other order: Regex (ECMAScript), 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:

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

Try it online!

^(          # 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

Deadcode

Posted 2019-10-25T21:20:35.743

Reputation: 3 022

2

Pyth, 7 bytes

g.{w.{w

Try it online!

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

randomdude999

Posted 2019-10-25T21:20:35.743

Reputation: 789

1I'm pretty sure !-E works. – FryAmTheEggman – 2019-10-25T21:54:33.750

1Submit it separately then, you'll deserve any upvotes you get for it. – randomdude999 – 2019-10-25T22:02:00.457

2

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).

Luis Mendo

Posted 2019-10-25T21:20:35.743

Reputation: 87 464

2

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.

Night2

Posted 2019-10-25T21:20:35.743

Reputation: 5 484

1

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.

– Ismael Miguel – 2019-10-28T16:51:43.980

1@IsmaelMiguel I prefer to forget register globals and old PHP versions. You can post it as a separate answer though. – Night2 – 2019-10-28T17:02:20.673

1No, thanks. Was just posting it as a reminder that PHP used to be a lot worse. – Ismael Miguel – 2019-10-28T17:43:44.387

Sadly this doesn't work correctly e.g. 'abc', 'abc0a123'. strtok returns '0' which will then be transformed to true. – Christoph – 2020-01-23T13:56:03.317

1@Christoph Thanks, fixed. – Night2 – 2020-01-24T17:17:04.873

2

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?

Bubbler

Posted 2019-10-25T21:20:35.743

Reputation: 16 616

Switch to dzaima/APL and save a byte: ∧∊ Try it online!

– Adám – 2019-11-03T13:46:05.497

2

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.

val says Reinstate Monica

Posted 2019-10-25T21:20:35.743

Reputation: 409

awesome golfing – LMD – 2019-10-28T18:17:43.050

2

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

Business Cat

Posted 2019-10-25T21:20:35.743

Reputation: 8 927

2

Kotlin, 35 bytes

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

Try it online!

snail_

Posted 2019-10-25T21:20:35.743

Reputation: 1 982

2

PowerShell, 34 bytes

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

Try it online!

Takes two arrays of chars as input.

mazzy

Posted 2019-10-25T21:20:35.743

Reputation: 4 832

1

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.

Nick Kennedy

Posted 2019-10-25T21:20:35.743

Reputation: 11 829

The OP has now said that the input order cannot be reversed :-/ – Luis Mendo – 2019-10-26T10:01:04.137

1

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

Neil

Posted 2019-10-25T21:20:35.743

Reputation: 95 035

1

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

GammaFunction

Posted 2019-10-25T21:20:35.743

Reputation: 2 838

1

Perl 5, 53 bytes

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

Try it online!

Denis Ibaev

Posted 2019-10-25T21:20:35.743

Reputation: 876

1

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!

LMD

Posted 2019-10-25T21:20:35.743

Reputation: 377

I think you can't use ipairs on strings? – val says Reinstate Monica – 2019-10-28T12:01:48.597

@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. – LMD – 2019-10-28T17:56:33.320

I think it doesn't fulfill challenge requirements then: "given two strings". I like the idea tho! – val says Reinstate Monica – 2019-10-28T18:02:50.597

@val A string essentially is a list of characters. But I could add a solution for strings too. – LMD – 2019-10-28T18:03:51.127

@val added, at the cost of two additional bytes – LMD – 2019-10-28T18:07:45.603

Wow, good job! Didn't expected it to be only two bytes away :-). Btw, I also have Lua answer here (75 bytes), although it uses entirely different way. You probably can shorten your solution by using load+vararg for functions. – val says Reinstate Monica – 2019-10-28T18:12:16.200

1

Haskell, 24 bytes

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

Try it online!

juancho

Posted 2019-10-25T21:20:35.743

Reputation: 21

1

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

Embodiment of Ignorance

Posted 2019-10-25T21:20:35.743

Reputation: 7 014

1

R, 40 bytes

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

Try it online!

Robin Ryder

Posted 2019-10-25T21:20:35.743

Reputation: 6 625

1

Keg, 13 7 5 4 3 bytes

-⑫=

-1 byte due to the new operator that pushes an empty string

Answer History

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

Lyxal

Posted 2019-10-25T21:20:35.743

Reputation: 5 253

You're using a code snippet if you don't include the code defining the function. – None – 2019-10-28T12:33:39.483

1

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!

Bart Jongejan

Posted 2019-10-25T21:20:35.743

Reputation: 71

1

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?

Jo King

Posted 2019-10-25T21:20:35.743

Reputation: 38 234

1

C# (.NET Core), 52 bytes 46 bytes 53 bytes

static bool f(string a, string b)=>b.All(a.Contains);

Try it online!

Palle Due

Posted 2019-10-25T21:20:35.743

Reputation: 111

1Why not b.All(a.Contains)? Note that you have to write a function or a full program, not a snippet. Most of the time, C# answers use anonymous functions. In this case a valid answer would be a=>b=>b.All(a.Contains) (of type Func<string, Func<string, bool>>, a function that returns a function that returns the result) – my pronoun is monicareinstate – 2019-11-03T05:14:46.700

1

05AB1E, 4 bytes

€ê`å

Try it online! or verify all test cases

Explanation

ې    Remove duplicates and sort each input
  `   Dump alphabets to the stack
   å  Check if the 2nd alphabet is contained in the 1st one

Wisław

Posted 2019-10-25T21:20:35.743

Reputation: 554

Fails for ["abcdef", "acf"] (should be truthy, but is falsey in your program). – Kevin Cruijssen – 2020-01-22T08:03:45.220

1

Clojure, 39 Bytes

(fn[a b](every? #(contains?(set a)%)b))

Try it online!

Thoma

Posted 2019-10-25T21:20:35.743

Reputation: 71

1

GolfScript, 9 bytes

n/{$.&}/=

Try it online!

Takes input as two newline-separated strings.

Explanation:

n/         Split by newline
  {   }/   For each word
   $.&     Sorted setwise intersection between it and itself
        =  Compare

Pseudo Nym

Posted 2019-10-25T21:20:35.743

Reputation: 181

This is incorrect... it is checking that both strings contain the same set of characters, but should be checking that the set of characters contained in the first string is a superset of that of the second string. (Also doesn't work with UTF-8, but I'm not sure GolfScript can do so?)

– Deadcode – 2020-01-20T08:10:29.107

1

Perl 5, 46 bytes

sub{local$_=pop.'␀'.pop;/^((.)(?=.*␀.*\2))*␀/}

Try it online!

This uses the ECMAScript regex from my pure regex answer (explained there). The unprintable character NUL (ASCII 0) is used as the delimiter, shown here as .

If side effects and absence of use strict are allowed it becomes 45 bytes:

sub{$z=pop.'␀'.pop;$z=~/^((.)(?=.*␀.*\2))*␀/}

Try it online!

If the side effect of modifying $_ is allowed, it becomes 41 bytes:

sub{$_=pop.'␀'.pop;/^((.)(?=.*␀.*\2))*␀/}

Try it online!

Deadcode

Posted 2019-10-25T21:20:35.743

Reputation: 3 022

1

GolfScript, 4 bytes

Pretty basic solution, disregarding the existing longer solution. Also, I beat CJam!

~\-!

Try it online!

Explanation

~    # Dump items of list to the stack
 \-  # Swap and find the difference
   ! # Negate the result

user85052

Posted 2019-10-25T21:20:35.743

Reputation:

Works for ASCII, but fails with the test case suggested by @pizzapants184 - "" "" - is it possible to make this answer work for UTF-8?

– Deadcode – 2020-01-20T07:58:26.743

I'm not sure whether GolfScript could do so. – None – 2020-01-20T08:19:37.983

1

Kotlin, 50 bytes

{s1:String,s2:String->s2.filter{it !in s1}.none()}

Try it online!

adrian.nastase

Posted 2019-10-25T21:20:35.743

Reputation: 31

2Welcome to the site! How does this take input? – Post Rock Garf Hunter – 2020-01-23T14:07:30.423

@PostRockGarfHunter Thanks for letting me know. I've updated the answer by adding a Try it online! link so that the solution can be tested. I hope it's OK like this, as I've seen this approach used by others. – adrian.nastase – 2020-01-23T20:36:56.933

0

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!

wizzwizz4

Posted 2019-10-25T21:20:35.743

Reputation: 1 895

0

Scala, 46 bytes

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

Try it online!

Denis Ibaev

Posted 2019-10-25T21:20:35.743

Reputation: 876

0

Prolog (SWI), 92 bytes

e(_,[]).
e(L,[H|T]):-member(H,L),e(L,T).
f(X,Y):-string_chars(X,A),string_chars(Y,B),e(A,B).

Try it online!

Marix

Posted 2019-10-25T21:20:35.743

Reputation: 21

0

Julia 1.0, 19 bytes

x\y=all(c->c∈x,y)

Try it online!

Thought I beat python till I saw xnor's answer! Uses a generator to check if every character in y exists in () x. Explanation: pass an anonymous function that checks if c is in x as the predicate to all, check that it returns true for all values in y.

Previous 22 byte solution: x\y=all(c∈x for c=y)

Try it online!

gggg

Posted 2019-10-25T21:20:35.743

Reputation: 1 715

0

Python 2.7 .pyc file, 130 bytes

Sorry, bytecode formats are just too much fun to pass up for simpler tasks

Hexdump because there's plenty of nulls :)

00000000: 03f3 0d0a fb0b 8b59 6300 0000 0000 0000  .......Yc.......
00000010: 0004 0000 0040 0000 0073 1a00 0000 7400  .....@...s....t.
00000020: 0074 0100 6302 0083 0000 8301 0003 8300  .t..c...........
00000030: 0083 0100 6b05 0046 2800 0000 0028 0200  ....k..F(....(..
00000040: 0000 7303 0000 0073 6574 7309 0000 0072  ..s....sets....r
00000050: 6177 5f69 6e70 7574 2800 0000 0028 0000  aw_input(....(..
00000060: 0000 2800 0000 0073 0000 0000 7308 0000  ..(....s....s...
00000070: 003c 6d6f 6475 6c65 3e00 0000 0073 0000  .<module>....s..
00000080: 0000                                     ..

Optimizations over the in built compiler:

  • Stack juggling the functions
  • Zero byte filename because it's valid
  • Crashing at the end because why spend a byte exiting cleanly

python-xdis output for the file:

# pydisasm version 4.1.0
# Python bytecode 2.7 (62211)
# Disassembled from Python 2.7.15+ (default, Jul  9 2019, 16:51:35)
# [GCC 7.4.0]
# Timestamp in code: 1502284795 (2017-08-09 13:19:55)
  0:
            LOAD_GLOBAL          (set)
            LOAD_GLOBAL          (raw_input)
            DUP_TOPX             2
            CALL_FUNCTION        0 (0 positional, 0 named)
            CALL_FUNCTION        1 (1 positional, 0 named)
            ROT_THREE
            CALL_FUNCTION        0 (0 positional, 0 named)
            CALL_FUNCTION        1 (1 positional, 0 named)
            COMPARE_OP           (>=)
            PRINT_EXPR

With bytes to make it easier to see where byte saves could be

# pydisasm version 4.1.0
# Python bytecode 2.7 (62211)
# Disassembled from Python 2.7.15+ (default, Jul  9 2019, 16:51:35)
# [GCC 7.4.0]
# Timestamp in code: 1502284795 (2017-08-09 13:19:55)
  0:           0 |74 00 00| LOAD_GLOBAL          (set)
               3 |74 00 01| LOAD_GLOBAL          (raw_input)
               6 |63 00 02| DUP_TOPX                  2
               9 |83 00 00| CALL_FUNCTION        (0 positional, 0 named)
              12 |83 00 01| CALL_FUNCTION        (1 positional, 0 named)
              15 |03      | ROT_THREE
              16 |83 00 00| CALL_FUNCTION        (0 positional, 0 named)
              19 |83 00 01| CALL_FUNCTION        (1 positional, 0 named)
              22 |6b 00 05| COMPARE_OP           (>=)
              25 |46      | PRINT_EXPR

famous1622

Posted 2019-10-25T21:20:35.743

Reputation: 451

0

Java, 90 Bytes

(String[] a)->a[1].chars().filter(x->!a[0].contains((String.valueOf((char)x)))).count()<1;

Not great, but chars() helps some...

Disco Mike

Posted 2019-10-25T21:20:35.743

Reputation: 19