-1
\$\begingroup\$

You need to make a program, that when giving a list and a string, searches on the list for items that contains the string.

Examples:

Input: th [thing, awesome, potato, example]
Output: thing (Because it starts with "th")

Input: ing [thing, potato]
Output: thing (Because it ends with "ing")

Input: tat [thing, potato]
Output: potato (Because it contains "tat")

Input: tat [tato, potato]
Output: tato, potato (If there are 2 or more results matching, print all of them)

Remember, this is code golf, so the shortest code wins.

Leaderboard

Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.

/* Configuration */

var QUESTION_ID = 72079; // 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 = 48934; // 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,]*[^\s,]),.*?(\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,
      });
    
  });
  
  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;
    if (/<a/.test(lang)) lang = jQuery(lang).text();
    
    languages[lang] = languages[lang] || {lang: a.language, 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 > b.lang) return 1;
    if (a.lang < b.lang) 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}

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

#language-list {
  padding: 10px;
  width: 290px;
  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="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">
<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>
<div id="language-list">
  <h2>Winners 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>
<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\$
  • 4
    \$\begingroup\$ The spec shouldn't be explained in the answers \$\endgroup\$ – Blue Feb 14 '16 at 18:59
  • \$\begingroup\$ Did you mean "contains" the other substring? \$\endgroup\$ – Downgoat Feb 14 '16 at 19:07
  • \$\begingroup\$ Yup, that's right. \$\endgroup\$ – AlexINF Feb 14 '16 at 19:08

13 Answers 13

3
\$\begingroup\$

TeaScript, 4 bytes

F@Iσ

Output is cast to string.

Try it online

Explanation

F@  // Filter input 1
 Iσ // Includes input 2
| improve this answer | |
\$\endgroup\$
  • 1
    \$\begingroup\$ Downvote and no comments? \$\endgroup\$ – Winny May 1 '16 at 5:09
  • 1
    \$\begingroup\$ Downgoats and no comments. \$\endgroup\$ – user85052 Jan 23 at 1:37
2
\$\begingroup\$

Python 2, 42 36 bytes

lambda i,a:filter(lambda v:i in v,a)

Thanks to muddyfish for saving 6 bytes

Test:

a=lambda i,a:filter(lambda v:i in v,a)
a('th', ['thing', 'awesome', 'potato', 'example']) # ['thing']
a('ing', ['thing', 'potato'])                      # ['thing']
a('tat', ['thing', 'potato'])                      # ['potato']
a('tat', ['tato', 'potato'])                       # ['tato', 'potato']
| improve this answer | |
\$\endgroup\$
  • 2
    \$\begingroup\$ Sometimes the right answer is boring. lambda i,a:[v for v in a if i in v] (35) \$\endgroup\$ – seequ Feb 14 '16 at 20:08
  • \$\begingroup\$ Regex please... \$\endgroup\$ – Anthony Pham Feb 14 '16 at 23:49
2
\$\begingroup\$

JavaScript ES6, 32 bytes

(s,a)=>a.filter(e=>~e.search(s))

33 bytes if the string might contain regexp metacharacters:

(s,a)=>a.filter(e=>~e.indexOf(s))
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ The spec is blurry enough, so I 'm not concerned about this ... but if the string can be any string and not just letters, you sholud use indexoOf instead of search \$\endgroup\$ – edc65 Feb 15 '16 at 8:10
  • \$\begingroup\$ @edc65 Yes, I wasn't sure whether to mention that. \$\endgroup\$ – Neil Feb 15 '16 at 8:54
1
\$\begingroup\$

Pyth - 5 bytes

f}zTQ

Try it online here.

Filters the input list by if the input string is in it.

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Could you explain it? \$\endgroup\$ – AlexINF Feb 14 '16 at 19:03
  • \$\begingroup\$ @Alex82 sure, adding! \$\endgroup\$ – Maltysen Feb 14 '16 at 19:04
1
\$\begingroup\$

vim, 13

dd:v/\V<C-r>"<BS>/d<cr>

Expects input as

th
thing
awesome
potato
example

Outputs on separate lines.

dd      delete first line into " (default) register
:v/     apply to every line that doesn't match the following regexp...
\V        "very nomagic" - strips chars of their special regex meaning
<C-r>"    paste contents of " register into the command
<BS>      remove the trailing newline from the first line
/d      ... delete the lines
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Doesn't this remove all matches (can't test right now) \$\endgroup\$ – seequ Feb 14 '16 at 20:15
  • \$\begingroup\$ @Seeq Sorry, my explanation is wrong. :v operates on all lines that do not match. \$\endgroup\$ – Doorknob Feb 14 '16 at 20:30
  • \$\begingroup\$ That would make more sense. Anyways, another feature of vim that I did not know about (+1) \$\endgroup\$ – seequ Feb 14 '16 at 20:32
1
\$\begingroup\$

Racket, 49 bytes

(λ(l s)(filter-map(curryr string-contains? s)l))
| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Python 2, 47 bytes

a=input()
print[x for x in input()if x in a]
| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Bash, 27 bytes

tr \  \\n<<<${@:2}|fgrep $1

Sample run:

llama@llama:...code/shell/ppcg72079search$ ./search.sh th thing awesome potato example
thing

With multiple outputs, they will be on separate lines.

tr \  \\n   replace spaces with newlines (equivalent to tr ' ' '\n')
<<<${@:2}   ... with STDIN as all but first argument
|fgrep $1   fgrep for first argument (fgrep is grep w/ "fixed" string, not regex)
| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

sh, 5 bytes

Accepts a list of words on stdin, one per line, and a search string as command line argument.

fgrep

This submisson should be valid by the rules on scoring builtin functions.

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

𝔼𝕊𝕄𝕚𝕟, 4 chars / 5 bytes

í⒡ăî

Try it here (Firefox only).

Simple.

Explanation

Filter input array by string input.

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

R, 38 28 bytes

function(x,y)grep(y,x,,,T,T)

simply a wrapper for grep, with value = TRUE to return the value [not a logical flag], and fixed (to allow regex-like strings to be searched and not processed as regex.

edit - 10 bytes by passing empty arguments to allow positional matching

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Mathematica, 29 bytes

Select[#2,StringContainsQ@#]&

Very simple.

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

W, 5 bytes

b@t!W

Explanation

ba      % Implicit inputs
  b     % Access the second operand
   @    % Show two operands (yields [b,b,a])
      W % Select everything in a that fullfills this condition:
    t   % Trim everything in the current item
        % that appears in the input
        % Yields ([b,b.trim(a)])
     !  % Negate this result, determining whether
        % the input is a subset of the current item

        % Keeping all of the items that fullfill
        % this condition yields a list by default
```
| improve this answer | |
\$\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.