Input ∩ Source Code

71

4

Intro

The challenge is to create a program/function that prints the intersection of its own source code and a given string input. This is code golf and to be more precise:

  • Let I be the input set
    • {"a","b","c"}
  • Let S be the source code set
    • {"b","f"}
  • Then the intersection is what they share
    • I ∩ S = {"b"}

Input

Input is flexible. It should be able to handle the character encoding used for the source code.

Output

Output is flexible. It should be the set of characters that the input and source code share. Also, sets are unordered collections of distinct objects. In summary:

  • Output is flexible:
    • Could be any data structure (string or otherwise)
    • Could unordered
    • Could have a trailing \n
    • Should be distinct

Restriction

Similar to challenges, the program/function may not read its own source code and 0-byte solutions are not allowed.

Examples

  • #1
functor x(I){ return I ∩ self; }

Inputs                                Outputs
------                                -------
enter preformatted text here      ->  {"e","n","t","r","f","o","x"}

["Albrt"," Einstin"]              ->  {"l","r","t","n","s"}
  • #2
(_)->_&"(_)->&\"\\"

Inputs                                Outputs
------                                -------
"Security at the expense of       ->  "
usability comes at the expense 
of security."

(0____0)                          ->  (_)
  • #3
ಠa益длф


Inputs                                Outputs
------                                -------
Far out in the uncharted backwaters ->"a"    
of the unfashionable end of the 
Western Spiral arm of the Galaxy lies 
a small unregarded yellow sun. 
Orbiting this at a distance of roughly 
ninety-eight million miles is an 
utterly insignificant little blue-green 
planet whose ape-descended life forms 
are so amazingly primitive that they 
still think digital watches are a pretty 
neat idea.

(ノಠ益ಠ)ノ彡┻━┻                      ->"ಠ益"

Test Cases

Albert Einstein

\__( O__O)_/

!@#$%^&*()_+{}|:"<>?

1234567890-=[]\;',./

(ノಠ益ಠ)ノ彡┻━┻

“¤>%,oỊȤʠ“ØụĊ5D³ṃṠɼQ»j;Ç;“;}¶”

┬──┬ ノ( ゜-゜ノ)

Far out in the uncharted backwaters of the unfashionable end of the Western Spiral arm of the Galaxy lies a small unregarded yellow sun. Orbiting this at a distance of roughly ninety-eight million miles is an utterly insignificant little blue-green planet whose ape-descended life forms are so amazingly primitive that they still think digital watches are a pretty neat idea.

Update

  • [16-08-10]: sets are unordered collections of distinct objects
  • [16-08-10]: trailing newline is acceptable

NonlinearFruit

Posted 2016-08-10T18:30:58.493

Reputation: 5 334

2May the output contain duplicate characters? – Digital Trauma – 2016-08-10T18:44:09.617

1@DigitalTrauma From examples #1, #2 and #3 it appears not – Luis Mendo – 2016-08-10T18:50:24.020

@DigitalTrauma Sorry for the ambiguity, sets (in the mathematical sense) ignore order and have no repetition. – NonlinearFruit – 2016-08-10T19:05:37.400

Is a trailing newline acceptable when printing the output? – Dennis – 2016-08-10T19:07:53.237

@Dennis Yes, a trailing newline is acceptable. – NonlinearFruit – 2016-08-10T19:18:19.100

23

Congratulations for coming up with a generalised quine where the best solutions are not based on the language's standard quine. :)

– Martin Ender – 2016-08-10T20:27:45.900

1If a set should not have repetition, shouldn't the input sets also not contain repetition? Or is the input actually not a set? – user81655 – 2016-08-11T15:37:08.207

@user81655 When I said "Let I be the input set" I meant that I is the set of the input not that the input is a set – NonlinearFruit – 2016-08-11T19:49:57.590

Are sets typically ordered or not? that is, does the order of the output matter? – cat – 2016-08-13T02:20:55.147

@cat Sets are unordered so the order of the output does not matter. – NonlinearFruit – 2016-08-13T02:26:16.377

TBH, the definition of "set" is not ambiguous in any way. – Andrea Lazzarotto – 2016-08-15T00:47:14.557

@Andrea I'm sorry, did you mean the English definition is unambiguous or the mathematical definition? :P – NonlinearFruit – 2016-08-15T02:39:34.820

Are they different? A set is an unordered collection of non repeating elements. The problem defined in the Q was clear before adding the clarification. :) Especially for people who write code which are expected to know the definition of a "set" in any programming language. – Andrea Lazzarotto – 2016-08-15T10:54:35.960

@AndreaLazzarotto The duplicate knives in my 40-piece silverware set beg to differ... – NonlinearFruit – 2016-09-02T21:00:14.703

@NonlinearFruit eheh... That is another kind of set that has nothing to do with math or programming. I guess a Hollywood movie set could beg to differ as well. :) – Andrea Lazzarotto – 2016-09-02T21:14:00.757

Answers

24

Jelly, 10 6 bytes

“Ṿf”Ṿf

Try it online!

How it works

“Ṿf”Ṿf  Main link. Argument: s (string)

“Ṿf”    Set the return value to 'Ṿf'.
    Ṿ   Uneval; yield '“Ṿf”'.
     f  Filter; remove the characters from '“Ṿf”' that do not appear in s.

Dennis

Posted 2016-08-10T18:30:58.493

Reputation: 196 637

15

Python 3, 44 bytes

Thanks Karl for saving me one byte :-) Thanks Dada for saving me two bytes!

I think this works, but it's my first quine challenge so I'm not 100% sure. :\

print(set("printseu()&'"+'+"')&set(input()))

Lambda version with 43 bytes: lambda a:set(" lambdaset()&'"+':+"')&set(a)

Jeremy

Posted 2016-08-10T18:30:58.493

Reputation: 521

8'eroticpuns\()&\'' is shorter than adding the strings. (escaped the ' but then you need a additional \\) Why is the dot there? – KarlKastor – 2016-08-10T19:26:11.580

woops, the . was a relic from less golfed code. Using backslash doesn't work because then the output from \\ is \\\, and duplicating the input character isn't allowed, I think. – Jeremy – 2016-08-10T19:32:18.703

1Your lambda is missing the :. – Dennis – 2016-08-10T19:45:44.067

Thanks @Dennis. My eyes start clouding over after trying to find all the characters in the program ;) – Jeremy – 2016-08-10T19:48:47.927

@KarlKastor is that letters configuration really random?
@Jeremy Am I missing something or c and o aren't needed in the first set?
– Dada – 2016-08-10T19:59:23.413

thjx @Dada! The reason I've had these random chars still in there is because my first crack used set.intersection instead of the ampersand. – Jeremy – 2016-08-10T20:02:34.273

@KarlKastor ahah, you're pretty good at that. Not sure if it's really appropriate on SE/PPCG tho – Dada – 2016-08-10T20:25:39.687

1@Dada: If you'd prefer, it could be inspectour, nicestupor, poeticurns, nopictures, recountspi, or inputscore. Or for the new one you might use prunesit (an accurate description of what code golfers do!), ipunster, or nursepit among others. – Deusovi – 2016-08-11T06:53:20.577

You can get down to 40 with set unpacking print({*'''printu()&'{}*'''}&{*input()}). – Morgan Thrapp – 2016-08-11T16:02:25.580

Or 36 with a lambda lambda a:{*''' lambda&':{}*'''}&{*a}. – Morgan Thrapp – 2016-08-11T16:07:37.017

@MorganThrapp thanks! That's quite a significant improvement, I don't feel it's right for me to take credit for it. – Jeremy – 2016-08-11T17:16:21.870

@Jeremy Up to you. It's the same algorithm, which is usually what I use to determine if I feel okay with taking a suggestion or not. – Morgan Thrapp – 2016-08-11T17:20:50.553

12

Dyalog APL, 8 bytes

'∩''⊢'∩⊢

is returns those characters from the left argument that are present in the right argument (if the left argument has no duplicates – as in this case – then the result also has no duplicates

is the argument

Then the string just has those two plus the quote character (doubled, as it is in a string).

TryAPL online!

Adám

Posted 2016-08-10T18:30:58.493

Reputation: 37 779

11

GolfScript, 6 bytes

"`&"`&

Try it online!

How it works

        # (implicit) Push the input on the stack.
"`&"    # Push the string '`&' on the stack.
   `    # Inspect; turn the string into '"`&"'.
     &  # Perform set intersection.

Dennis

Posted 2016-08-10T18:30:58.493

Reputation: 196 637

So that's how you can get quotes into the string without having to add backslash. – Pseudo Nym – 2019-12-18T13:00:12.690

9

Perl 6, 56, 55 bytes

"French" / Unicode version (55 bytes)

say perl q.say perlq∩$*IN\\\.comb:..comb∩$*IN.comb:

"Texas" / ASCII versions (56 bytes)

say (q.sayq(&) $*IN\\\.combperl..comb (&)$*IN.comb).perl
say perl q.sayq(&) $*IN\\\.comb:perl..comb (&)$*IN.comb:

Non-golfed:

my \Source = 'my \\Source = \'say ( $*IN.comb.Set ∩ Source.comb.Set ).perl\'';
say ( $*IN.comb.Set ∩ Source.comb.Set ).perl

Examples:

$ echo -n 'say perl q.say perlq∩$*IN\\\.comb:..comb∩$*IN.comb:' > test-unicode.p6

$ echo -n 'say (q.sayq(&) $*IN\\\.combperl..comb (&)$*IN.comb).perl' > test-ascii.p6

$ perl6 test-ascii.p6 <<< 'abcdefghijklmnopqrstuvwxyz'
set("p","a","l","r","c","q","b","s","e","m","y","o")

$ perl6 test-unicode.p6 < test-unicode.p6
set("\\","I","p"," ","a","c","l","r","q","b","∩","*","s","m","e",".","y",":","o","N","\$")

$ perl6 test-ascii.p6 < test-ascii.p6
set("p","\\","I"," ","a","l","r","c","q","b",")","*","s","e","m","\&",".","(","y","o","N","\$")

$ perl6 test-ascii.p6 < test-unicode.p6
set("p","\\","I"," ","a","l","r","c","q","b","*","s","e","m",".","y","o","N","\$")

$ perl6 test-unicode.p6 <<< 'Albert Einstein'
set(" ","l","r","b","s","e")

$ perl6 test-unicode.p6 <<< '\__( O__O)_/'
set("\\"," ")

$ perl6 test-ascii.p6 <<< '!@#$%^&*()_+{}|:"<>?'
set(")","*","\&","(","\$")

$ perl6 test-unicode.p6 <<< "1234567890-=[]\\;',./"
set("\\",".")

$ perl6 test-unicode.p6 <<< '(ノಠ益ಠ)ノ彡┻━┻'
set()

“¤>%,oỊȤʠ“ØụĊ5D³ṃṠɼQ»j;Ç;“;}¶”
set("o")

$ perl6 test-unicode.p6 <<< '┬──┬ ノ( ゜-゜ノ)'
set(" ")


$ perl6 test-ascii.p6 <<< 'Far out in the uncharted backwaters of the unfashionable end of the Western Spiral arm of the Galaxy lies a small unregarded yellow sun. Orbiting this at a distance of roughly ninety-eight million miles is an utterly insignificant little blue-green planet whose ape-descended life forms are so amazingly primitive that they still think digital watches are a pretty neat idea.'
set("p"," ","a","l","r","c","b","s","e","m",".","y","o")

Brad Gilbert b2gills

Posted 2016-08-10T18:30:58.493

Reputation: 12 713

2Doesn't $*PROGRAM access the source code of the program, and thus violate the rules? – celtschk – 2016-08-12T08:34:13.997

@celtschk I should have re-read the question before posting, fixed. ( Technically the compiler could see that $*PROGRAM is read from and store the entire source as a string in the compiled program, which would have put it into a grey area ) – Brad Gilbert b2gills – 2016-08-15T00:29:34.223

9

Python 2, 56 46 39 Bytes

-1 Byte thanks to @Jeremy

lambda a:set(':&()smelt\ bad\'')&set(a)

anonymous lambda function, takes a string, returns a set

old version:

lambda x,w=set('newmatrixbuspdl_:-)(=,\ \''):w-(w-set(x))

KarlKastor

Posted 2016-08-10T18:30:58.493

Reputation: 2 352

I like this, but it returns two backslashes on \\\ instead of just one. – Jeremy – 2016-08-10T19:35:59.847

Also, i think you can save a byte by changing the name of the lambda to a – Jeremy – 2016-08-10T19:37:19.450

1@Jeremy Thanks for tip, '\\' is just Python's way of representing a backslash in string form, because a single one would escape the end quote, so you have to escape the backslash with a backslash to make it work. Type print '\\' and you'll see that it is just the representation for one backslash. – KarlKastor – 2016-08-10T20:12:18.020

You can get to 36 with lambda a:{*''' lambda&':{}*'''}&{*a}. – Morgan Thrapp – 2016-08-11T16:08:12.313

1@MorganThrapp 35 lambda a:{*' lambda&\\\':{}*'}&{*a} – seequ – 2016-08-11T20:44:01.063

@MorganThrapp: Which Python version are you using? Even in Python3 i get a SyntaxError: invalid syntax – KarlKastor – 2016-08-12T09:17:44.740

It only works in 3.5 and on. – Morgan Thrapp – 2016-08-12T15:07:34.933

8

MATL, 8 bytes

'X&'''X&

Try it online!

Input is a string enclosed in single quotes. If the string contains a single-quote symbol, it should be duplicated to escape it.

Explanation

'X&'''   % Push string with the three characters used by the program. The single-quote 
         % symbol needs to be escaped by duplicating it
X&       % Take input implicitly. Set intersection. Display implicitly

Luis Mendo

Posted 2016-08-10T18:30:58.493

Reputation: 87 464

6

Actually, 6 bytes

`∩è`è∩

Try it online!

Explanation:

`∩è`è∩
`∩è`    push the function `∩è` (which contains every character in the source code except '`')
    è   repr (same as Python repr - leaves "`∩è`", which contains every character in the source code)
      ∩ set intersection with input

Mego

Posted 2016-08-10T18:30:58.493

Reputation: 32 998

5

05AB1E, 11 bytes

Code:

"'ÃJÙ"'"JÃÙ

Uses the CP-1252 encoding. Try it online!.

Adnan

Posted 2016-08-10T18:30:58.493

Reputation: 41 965

5

Haskell (30 bytes)

This is such a boring solution... But I couldn't do better. :(

filter(`elem`"f(term)\"i`l\\")

MarLinn

Posted 2016-08-10T18:30:58.493

Reputation: 231

5

Brachylog, 23 bytes

:{e.~e":{}e~\"fd\."}fd.

Try it online!

Explanation

:{                 }f      Find all chars that verify the predicate below
                     d.    Remove duplicates and output

  e.                       Take a char from the input ; this is our output…
    ~e":{}e~\"fd\."        … if that char is in the string :{}e~"fd. (the first \ is here
                               to escape the ")

Fatalize

Posted 2016-08-10T18:30:58.493

Reputation: 32 976

1Can you have a look at our chatroom? – Leaky Nun – 2016-08-11T09:56:07.973

1+1 for moustache man :{ and surprised moustache man :{} – Destructible Lemon – 2016-08-17T04:29:58.870

4

Pyth, 9 8 bytes

1 byte thanks to Sp3000

@Q"\Q@\"

Try it online!

@Q"\Q@\"
@Q"\Q@\""   implicit string ending

@Q           intersect the input with
  "\Q@\""   the string containing '\', 'Q', '@', '"'.

Leaky Nun

Posted 2016-08-10T18:30:58.493

Reputation: 45 011

@z"z\"@ is 1 byte shorter. – drobilc – 2016-08-13T11:23:46.783

@drobilc That would miss out the \. – Leaky Nun – 2016-08-13T12:26:02.253

oh, yeah, totally forgot about that. – drobilc – 2016-08-13T12:32:23.567

4

C, 142 bytes

main(i){char*p,a[]="remain([*]){fought?>:01;,\\\"=capsv+-l}";for(;(i=getchar())>=0;p?putchar(i),memmove(p,p+1,a+strlen(a)-p):0)p=strchr(a,i);}

Try it on ideone.

owacoder

Posted 2016-08-10T18:30:58.493

Reputation: 1 556

2An ungolfed version and/or explanation would be great! – YSC – 2016-08-11T11:58:37.113

You could have used sizeof a instead of strlen(a) for one byte saved, but even better is to give the array a known size: a[99]="...", and replace strlen(a) by 99 to shave off 5 bytes. – G. Sliepen – 2016-09-08T11:58:54.587

Another 3 or 4 bytes can be saved by replacing (i=getchar())>=0 with read(0,&i,1). This works on little-endian machines. i is initialized to 1 if you don't run the program with any arguments. If you want it to work on big-endian machines as well, remove i from the argument list of main() and declare it inside the body as a char (but then you save only 3 bytes). read() conveniently returns 0 on EOF. – G. Sliepen – 2016-09-08T12:03:50.520

4

Bash, 45 50 41 39 37 34 29 bytes

-9 bytes thanks to Geoff Reedy
-4 bytes thanks to Dennis
-5 bytes thanks to Nahuel Fouilleul

grep -o '[] [|\'\'grepouniq-]

Try it online!

Riley

Posted 2016-08-10T18:30:58.493

Reputation: 11 345

Don't you only need one grep command? – Geoff Reedy – 2016-08-11T23:21:35.033

@GeoffReedy The first grep command splits the input into one character per line. – Dennis – 2016-08-12T03:43:24.910

Right but couldn't the -o be put on to the second grep – Geoff Reedy – 2016-08-12T12:52:42.793

You're right, and that saves having to check for the '.'. Thanks! – Riley – 2016-08-12T14:11:19.990

grep -o '[] [|\'\'greposrtu-]|sort -u should work. – Dennis – 2016-08-12T21:08:55.407

Is there something wrong with my suggestion? It seems to save 2 bytes over your current approach. – Dennis – 2016-08-18T06:05:47.150

@Titus I'm not sure what you mean. – Riley – 2016-12-21T17:01:19.877

Your expression contains backslashes. Are backslashes matched in the filtering process? – Titus – 2016-12-21T17:06:03.953

1@Titus After BASH does it's thing, grep gets -o and [] [|\'grepouniq-]. So it is looking for anything of these: [ ] {space} [ | {slash} ' g r e p o u n i q - ]. – Riley – 2016-12-21T17:09:41.293

@Titus does that help? – Riley – 2016-12-21T17:17:47.073

why uniq is used? uniq filters only adjacent matching lines (if sorted for example) – Nahuel Fouilleul – 2017-09-22T13:03:43.053

I'm not sure why I had uniq. Input will only have 1 of each character (because it's a set), so I don't need remove duplicates. Thanks! – Riley – 2017-09-22T13:15:34.617

4

CJam, 8 bytes

"`q&"`q&

Try it here.

Explanation:

"`q&"    e# Push that string to the stack
     `   e# Stringify, pops the string and pushes "\"`r&\"" to the stack
      q  e# Pushes the input to the stack
       & e# Union, pops two elements and pushes a list of every element that is contained in both.

Loovjo

Posted 2016-08-10T18:30:58.493

Reputation: 7 357

4

Retina, 21 20 bytes

Removes characters not in the source code, then removes duplicate characters.

[^Ds.n\n[-a_-]

Ds`.

Try it online

mbomb007

Posted 2016-08-10T18:30:58.493

Reputation: 21 944

Your source code contains a linefeed (your output doesn't). – Martin Ender – 2016-08-11T17:58:50.050

I had basically the same solution earlier but forgot to post it. You can save a few bytes with the range [-a (and then include an underscore and a hyphen and drop the backtick on the second line). But for future reference, ] wouldn't need escaping if you put it as the first character. Oh and for niceness, you can swap the two stages to avoid the trailing linefeed. – Martin Ender – 2016-08-11T19:41:19.993

@MartinEnder This still doesn't deduplicate line feeds, is that a problem? – mbomb007 – 2016-08-12T13:39:37.897

Oh you're right, I didn't notice that. You'll have to add s to the options of D and the character class then. – Martin Ender – 2016-08-12T13:41:02.230

4

C#, 36 bytes

s=>s.Intersect("s=>.Interc(\"\\);");

Intended cast is Func<string, IEnumerable<char>> (string input, IEnumerable<char> output).

milk

Posted 2016-08-10T18:30:58.493

Reputation: 3 043

@Kobi Intersect<TSource> enumerates first, collecting all distinct elements of that sequence. It then enumerates second, marking those elements that occur in both sequences.. second is already distinct therefore Intersect will return only distinct elements.

– milk – 2016-08-13T09:02:52.317

4

Mathematica, 35 bytes

Characters@"\"#&@C\acehrst⋂"⋂#&

Anonymous function. Ignore any generated messages. Takes a list of characters as input and returns a list of characters as output. The Unicode character is U+22C2 for \[Intersection].

LegionMammal978

Posted 2016-08-10T18:30:58.493

Reputation: 15 731

4

Vim, 78 68 78 79 61 keystrokes

Completely changed my approach:

oo/\$kjxd<esc>/o<cr>xj$/\/<cr>xj$/\\<cr>xj$/$<cr>xj$/k<cr>xj$/x<cr>xj$/j<cr>xj$/d<cr>xkdd

How it works:

First, it makes a line with all the program characters, then, it finds the first instance of each of the program characters, which is either in the input, if the input and output intersect, or the output if they don't, deletes it, moves to the last character of the file (so it wraps around) and does that for each unique character in source, except d, where instead of moving to the end of the file, it finishes up by deleting the input

Destructible Lemon

Posted 2016-08-10T18:30:58.493

Reputation: 5 908

Backslash is in your code but doesn´t seem to be in your string. – Titus – 2016-12-21T16:54:03.870

Isn't it the third? – Destructible Lemon – 2016-12-21T20:11:45.627

3

JavaScript (Chrome 58 on OS X 10), 12654 12426 11992 Bytes

https://paste.ubuntu.com/25593218/

https://paste.ubuntu.com/25595798/

https://paste.ubuntu.com/25595831/

The original code:

var t=prompt();"!+()[]".split("").forEach(function(f){if(t.includes(f))alert(f)})

This was then converted into a programming style called jsfk which only uses these six characters:

(+)[!] 

using an online compiler.

Tornado547

Posted 2016-08-10T18:30:58.493

Reputation: 389

If jsfk is the language, you should use that in the header instead of Javascript.

– NonlinearFruit – 2017-09-23T14:00:46.583

1@NonlinearFruit jsfk is a programming style. It is valid javascript – Tornado547 – 2017-11-28T16:01:43.960

3

PowerShell v4+, 122 104 bytes

([char[]]($args[0]+'acegfhmnoprstu012|][()"?+_,.$-{0}{1}{2}'-f("'","}","{"))|group|?{$_.count-gt1}).name

Ugh. Quines or quine-like code in PowerShell sucks, because the string replacement formatting is so clunky.

The string ace...{2} in the middle is every character that's present in the rest of the code. The {0}{1}{2} is used in conjunction with the -format operator to pull the '{} characters into the string.

That's combined as a char-array with the input $args, then fed into the pipeline. The first stop is Group-Object which (essentially) creates a hashtable of the input objects and how many times they occur in the input. That's piped to |?{...} the Where-Object to only select those items that have a .count greater than 1. We encapsulate that in parens, and pluck out the .Name portion of the hashtable (which is where the v4+ requirement comes into play, otherwise we'd need an additional |Select Name stage to the pipeline).

Those elements are left on the pipeline (as an array), and printing is implicit.

AdmBorkBork

Posted 2016-08-10T18:30:58.493

Reputation: 41 581

3

JavaScript (ES6), 59 57 bytes

f=
t=>[..."\"().=>O[\\]defilnrtx~"].filter(e=>~t.indexOf(e))
;
<input placeholder=Input oninput=o.value=f(this.value).join``><input placeholder=Output id=o>

Returns an array of characters present in both the original string/character array and the source code. Edit: Saved 2 bytes thanks to @user81655.

Neil

Posted 2016-08-10T18:30:58.493

Reputation: 95 035

f=s=>[...new Set(f+'')]... could save bytes. – user81655 – 2016-08-11T15:17:53.887

Or even shorter: f=s=>[...s].filter(c=>(new Set(f+'')).has(c)) – user81655 – 2016-08-11T15:27:12.637

@user81655 At least in Firefox, f+'' works by reading f's source code. (In certain cases you could get Firefox to crash by changing the source file and then attempting to stringify a function loaded from it.) – Neil – 2016-08-11T15:27:58.433

@user81655 Your second example fails when s has repeated elements, and indexOf is shorter than new Set anyway. – Neil – 2016-08-11T15:30:51.947

In that case, you could try saving chars (like changing the c parameter to a character that is already in the list). – user81655 – 2016-08-11T15:30:58.703

As far as I'm aware, the input set follows the same set rules (no duplicates). – user81655 – 2016-08-11T15:31:26.080

@user81655 Thanks for that c tip, but check the test cases for duplicates, I think you might find some. – Neil – 2016-08-11T15:33:29.600

Ah, that's interesting. The comments clarifying that a set does not contain duplicates seem to contradict the test cases. If the input is in fact a set, you could even take it as a Set then do s.has(c) inside the filter. You can change the s to another character as well by the way. – user81655 – 2016-08-11T15:39:03.847

3

Python 2, 44 bytes

x='c=set;print c(`x`)&c(raw_input())';exec x

Just for fun, here's a quine-like full program submission. Outputs the string representation of a Python 2 set.

Sp3000

Posted 2016-08-10T18:30:58.493

Reputation: 58 729

3

Matlab, 37 bytes

Quite simple:

Uses the builtin intersect to find the intersection. The source code is hard coded. Input must be given inside quotation marks ''

intersect(input(''),'''intersc(pu),')

Stewie Griffin

Posted 2016-08-10T18:30:58.493

Reputation: 43 471

You should've used an anonymous function...beat you by 5 bytes

– Sanchises – 2016-12-21T15:46:29.707

Hehe, I guess that wasn't my best golf... – Stewie Griffin – 2016-12-21T17:07:33.193

2

MATLAB, 32 bytes

@(t)intersect(t,'@(t)inersc,''')

Essentially the same as Stewie Griffin's approach (the intersect built-in is hard to avoid), but this edition saves an entire 5 bytes over his by taking the input as an anonymous function, with the variable name t chosen to occur within intersect (any other character in that string would have done as well). Call as ans('yourInput').

Sanchises

Posted 2016-08-10T18:30:58.493

Reputation: 8 530

2

Java 8, 131 129 131 bytes

a->{java.util.Set r=new java.util.HashSet();for(String s:a)if("a->{jv.utilSe r=nwHsh();fog:\"\\cd}".contains(s))r.add(s);return r;}

+2 bytes again due to a bug-fix

Explanation:

Try it here.

a->{                    // Method with String-array parameter and Set return-type
  java.util.Set r=new java.util.HashSet();
                        //  The result Set
  for(String s:a)       //  Loop over the input String-array
    if("a->{jv.utilSe r=nwHsh();fog:\"\\cd}".contains(s))
                        //   If the current character is part of the source-code:
      r.add(s);         //    Add it to the Set
                        //  End of loop (implicit / single-line body)
  return r;             //  Return the result-Set
}                       // End of method

Kevin Cruijssen

Posted 2016-08-10T18:30:58.493

Reputation: 67 575

2

Brachylog (newer), 18 bytes

{∈"{∈\\\"&}ˢd"&}ˢd

Try it online!

It's this plus the de-duplication predicate. Doesn't necessarily beat Fatalize's solution since his is in an older and very different version of the language.

Unrelated String

Posted 2016-08-10T18:30:58.493

Reputation: 5 300

2

W, 12 bytes

34C+t"34C+tt

Explanation

34C+t"       % Everyone in the execution sequence excluding a quote
      34C+   % Add a (") quote
          t  % Trim out everything in this string in input
           t % Trim the string so that the intersection is kept

user85052

Posted 2016-08-10T18:30:58.493

Reputation:

2

q (38 bytes)

Reads from stdin

"readint0\\\" "inter read0 0

edit: was missing backslash

skeevey

Posted 2016-08-10T18:30:58.493

Reputation: 4 139

I'm not familiar with q, could you add a link? – NonlinearFruit – 2016-09-12T16:13:26.553

sure, http://code.kx.com

– skeevey – 2016-09-13T17:41:54.917

2

R, 129 bytes

f=function(s){b=strsplit("f=unctio(s){arpl;,[1]b\\\"qemh0T}",c())[[1]];cat(b[unique(pmatch(strsplit(s,c())[[1]],b,0,T))],sep="")}

If I ungolf it, it needs to have weird things changed like a newline in the string for b. Anyhow, its super simple -- builds a vector with all characters in the function in it. Then it pulls the input into a vector, and checks membership.

user5957401

Posted 2016-08-10T18:30:58.493

Reputation: 699

1you haven't visited the site in almost a year, but f=function(s)cat(instersect(strsplit(s,"")[[1]],strsplit("f=unctio(s)aerpl,\\\"[1]","")[[1]]),sep="") is 101 bytes, and I think the I/O format can be simpler, without cat... – Giuseppe – 2017-08-08T19:26:41.737

2

Ruby, 34 + n flag = 35 bytes

Doesn't exactly work with multi-lined input, since -n causes the program to process STDIN line-by-line. There aren't newlines in this code, but trying to input something like that will output multiple arrays instead of one. If that is not good according to spec, please inform me and I will fix.

p $_.chars&"\\\"p $_.chars&".chars

Value Ink

Posted 2016-08-10T18:30:58.493

Reputation: 10 608

2

Java 8 lambda, 152 142 140 characters

Quite short:

s->s.chars().mapToObj(i->(char)i).filter(c->"COSTab\"\\cefh(i)j+l-mn.oprstuv>".contains(""+c)).collect(java.util.stream.Collectors.toSet())

Or ungolfed over here:

public class Q89400 {

    static Set<Character> inAndQuine(String in) {
        return in.chars()
                .mapToObj(i->(char)i)
                .filter(c->"COSTab\"\\cefh(i)j+l-mn.oprstuv>".contains(""+c))
                .collect(java.util.stream.Collectors.toSet());

    }
}

Of course the ungolfed solution is wrong, as it doesn't match the curly brackets and some more characters, it's just their for the sake of completeness.

The function takes input as a String and returns a java.util.Set<Character> containing the characters which are present in both input and source.

Updates

It turned out that the solution wasn't working. I thought String#contains tests for a regex match but it is just a literal matching. I added some escaping to quote the characters like . but this wasn't necessary but ruined everything instead. Now without this escaping we save some characters and now it actually works :)

Thanks to @NonlinearFruit for reminding me of using one-character variables.

Frozn

Posted 2016-08-10T18:30:58.493

Reputation: 381

Rename in to be a single letter like a – NonlinearFruit – 2016-08-12T12:16:49.087

3@NonlinearFruit you're right :O how could I forget about that?! – Frozn – 2016-08-12T13:13:56.220

2

ListSharp, 222 bytes

STRG S=READ[<here>+"\\S.txt"]
ROWS T=ROWSPLIT S BY [""]
ROWS R=ROWSPLIT "STRG =EAD[<her>+\".tx]OWPLIBYCFMHVNc#isn()oay\r\n" BY [""]
ROWS R=SELECT FROM T WHERE[EVERY STRG IS ANY STRG IN R]
SHOW=<c#R.Distinct().ToArray()c#>

ridiculous but im entertained

downrep_nation

Posted 2016-08-10T18:30:58.493

Reputation: 1 152

2

sed, 47 characters

:s;st[^])(*\1.s2t:[;^]tt;st\(.\)\(.*\1\)t\2t;ts

I'm a little disappointed at how long this came out to be, especially the bit to remove repeated characters.

Geoff Reedy

Posted 2016-08-10T18:30:58.493

Reputation: 2 828

Which version of sed is this? GNU sed says sed: -e expression #1, char 47: unterminated `s' command. – Dennis – 2016-08-12T03:03:01.707

43 bytes including 1 for -r: sed -r ':;ss[^][str().*\12;:^]ss;ss(.)(.*\1)s\2s;t' i wrote it before noticing yours and it turned out to be very similar – izabera – 2016-08-12T07:23:07.043

@Dennis fixed; turned out having a : after the [ caused it to try and parse a character class – Geoff Reedy – 2016-08-12T13:04:50.773

@izabera nice, I'm quite surprised that the : command doesn't actually need a label and that it changes the meaning of t without a label – Geoff Reedy – 2016-08-12T13:07:54.820

yeah it's a gnuism – izabera – 2016-08-12T13:25:44.337

Hm, that works well for a single line, but it breaks if there's more than one. – Dennis – 2016-08-12T15:48:05.083

2

SQF, 71 69 64 bytes

Using the file-as-a-function format:

i="-_h ;""=()sSplitrng"splitString"";i-(i-(_this splitString""))

Call as "STRING" call NAME_OF_COMPILED_FUNCTION

Οurous

Posted 2016-08-10T18:30:58.493

Reputation: 7 916

2

Pyth, 6 8 Bytes

{@"{@\"\

Expects input as a string.

Try it online!

Explanation:

 @     Q    Intersect implied input with:
  "{@\"\     The string containing {@"\
{          and then remove duplicates.

Steven H.

Posted 2016-08-10T18:30:58.493

Reputation: 2 841

Unfortunately, that doesn't remove duplicates. – Dennis – 2016-08-15T22:14:32.297

Fixed! Unfortunately, that costs two additional bytes, tying it with the other Pyth answer. – Steven H. – 2016-08-15T22:17:02.903

1

PHP, 61 bytes

<?=preg_filter("_<\?=[aefiglprtv$(\_[\],)\\;1\"]_",$argv[1]);

takes input from first command line argument.

no regex, 74 bytes

for(;""<$c=$argv[1][$i++];)if(strstr("aceghiosrtv()$<=[1]\;\"",$c))echo$c;

takes input from first command line argument. Run with -nr.

Note: ; needs no escaping; so PHP takes the backslash before the semicolon literally.

Titus

Posted 2016-08-10T18:30:58.493

Reputation: 13 814

1

Java (OpenJDK 8), 58 bytes

s->s.filter("s->.filter(\"\\:cona)d"::contains).distinct()

Try it online!

Accepts the input as Stream<String>, whereas each character of the input is a stream element, and returns a filtered, distinct stream.

Nevay

Posted 2016-08-10T18:30:58.493

Reputation: 421

1

Japt, 14 15 bytes

My very first "proper" quine. At long fecking last!

oQ+"oQ+ ‰"Q ‰

Try it

Shaggy

Posted 2016-08-10T18:30:58.493

Reputation: 24 623

1

Lua, 91 bytes

Old challenge, but still lacking a Lua solution, so...

s=...(" s=.(\\\"):gub,fnctiod1awre"):gsub(".",function(c)c=s:find(c,1,1)and io.write(c)end)

Try it online!

Jonathan S.

Posted 2016-08-10T18:30:58.493

Reputation: 423

1

J, 18 bytes

'''&()[-.'&([-.-.)

How it works

 ''&()[-.           the character set, '' stands for '
          &         is the left operand
           ([    )  the set> itself, ignore <the input
           (   -.)  the set> except any characters in <the input
                      (the wrong ones remain)
           ( -.  )  the set itself> except <the wrong characters

Try it online!

FrownyFrog

Posted 2016-08-10T18:30:58.493

Reputation: 3 112

It's easier to see where your code ends and the explanation begins if you put the explanation in a separate programming puzzle. Also, consider adding a try it online link to your answer so that users can test your submission. Besides that, great first post and welcome to PPCG!

– LyricLy – 2017-09-23T10:44:24.670

1

Perl 6, 38 bytes

<say .comb∩$*IN.comb#<>~EVAL>~~.EVAL

Try it online!

The generalised quine still manages to beat out the trivial program by a few bytes

Perl 6, 41 bytes

say <$*. <>INabcmosy∩>.comb∩$*IN.comb

Try it online!

Jo King

Posted 2016-08-10T18:30:58.493

Reputation: 38 234

1

Husk, 7 bytes

n"n\\\"

Try it online!

n          The intersection of
 "n\\\"    the string n, \, "
           with the input.

I tried to work around having to escape the quote with a backslash, but that just made it longer:

Husk, 8 bytes

n:'""n:'

Try it online!

n         The intersection of
  '"      the character "
 :        prepended to
  "n:'    the string n, :, '
          with the input.

Another attempt to eliminate backslashes, which would be two bytes shorter if it didn't need to remove duplicates:

Husk, 7 bytes

uns"nsu

Try it online!

u          Without duplicate elements,
 n         the intersection of
  s        the string representation of
   "nsu    the string n, s, u
           with the input.

Unrelated String

Posted 2016-08-10T18:30:58.493

Reputation: 5 300

1

Python, 48 bytes

First thing I though of. It can probably be golfed more.

Input comes from sdtin. Output goes to stdout as a set object

print set(raw_input())&set("raw_pint se(u)\&\"")

Iguanodon

Posted 2016-08-10T18:30:58.493

Reputation: 31

Is this 40 bytes? – Jeremy – 2016-08-10T19:34:28.590

1doesn't work for input \\ – KarlKastor – 2016-08-10T19:43:23.330

@Jeremy You're right, I forgot to update that. It's 47. – Iguanodon – 2016-08-10T20:00:16.597

@KarlKastor Fixed – Iguanodon – 2016-08-10T20:02:19.143

0

Burlesque, 10 bytes

#QupIN#Qvv

Try it online!

Turns out the lazy way worse than doing it generally because I can't get a quote within a quote nicely. "IN_+"'"_+IN

#Q  #Push the code onto the stack
up  #Convert to string
IN  #Intersection
#Q  #Make sure a #Q is captured
vv  #Drop the resulting push

DeathIncarnate

Posted 2016-08-10T18:30:58.493

Reputation: 916

@a'_' Do you mean because it produces an extra ""? If so, then adding a "Q" cures it. Try it online!

– DeathIncarnate – 2020-01-19T23:40:50.000