title: Visible Dice Faces

text:
# Question
Title: Visible Dice Faces
A traditional Western die is a cube, on which the integers 1 to 6 are marked on the faces. Pairs that add to 7 are placed on opposite faces.

As it is cube, we can only see between 1 and 3 faces (inclusive)1 at any given time. Opposite faces can never be seen at the same time.

Your task is to write a program or function which, given a list of integers representing sides on a die, determines if it is possible to see these faces at the same time.

1Okay, maybe you can see 4 or 5 faces with a pair of eyes, but for the purpose of this challenge we observing the die from a single point.

---

# Rules:

* Your submission may assume the input list:
    + Is non-empty.
    + Only contains values which satisfy `1 ≤ n ≤ 6`.
    + Contains no duplicate elements.
* You may *not* assume that the input is sorted.
* Your submission should output a truthy / falsy value: truthy is the faces can be seen at the same time, falsy otherwise.
* This is , so the shortest answer (in bytes) wins!
* Standard loopholes are forbidden by default.

---

## Test Cases

**Truthy:**

```
[6]                 (One face)
[6, 2]              (Share a side)
[1, 3]              (Share a side)
[2, 1, 3]           (Share a vertex)
[3, 2, 6]           (Share a vertex)

```

**Falsy:**

```
[1, 6]              (1 and 6 are opposite)
[5, 4, 2]           (2 and 5 are opposite)
[3, 1, 4]           (3 and 4 are opposite)
[5, 4, 6, 2]        (Cannot see 4 faces)
[1, 2, 3, 4, 5, 6]  (Cannot see 6 faces)

```

# Answer
> 21 votes
# JavaScript (ES6),  ~~38 34 30 29~~  28 bytes

Takes input as any number of separate parameters. Returns `0` or `1`.

```
(a,b,c,d)=>!(d|(a^b^c)%7)^!c

```

### Test cases

```
let f =

(a,b,c,d)=>!(d|(a^b^c)%7)^!c

console.log('[Truthy]')
console.log(f(6      ))
console.log(f(6, 2   ))
console.log(f(1, 3   ))
console.log(f(2, 1, 3))
console.log(f(3, 2, 6))

console.log('[Falsy]')
console.log(f(1, 6            ))
console.log(f(5, 4, 2         ))
console.log(f(3, 1, 4         ))
console.log(f(5, 4, 6, 2      ))
console.log(f(1, 2, 3, 4, 5, 6))
```

### How?

Below are simplified versions of the main expression according to the number of parameters provided, undefined variables being coerced to either **0** or **false**:

```
# of param. | simplified expression        | comment
------------+------------------------------+---------------------------------------------
     1      | !(a % 7) ^ 1                 | always true
     2      | !((a ^ b) % 7) ^ 1           | false for (1,6), (2,5) and (3,4)
     3      | !((a ^ b ^ c) % 7)           | see the table below
     4+     | !(d | (a ^ b ^ c) % 7)       | always false

```

*NB*: The order of **(a,b,c)** doesn't matter because they're always XOR'd together.

The trickiest case is the 3rd one. Here is a table showing all possible combinations:

```
a | b | c | a^b^c | %7 | =0? | faces that sum to 7
--+---+---+-------+----+-----+--------------------
1 | 2 | 3 |   0   |  0 | Yes | none
1 | 2 | 4 |   7   |  0 | Yes | none
1 | 2 | 5 |   6   |  6 | No  | 2 + 5
1 | 2 | 6 |   5   |  5 | No  | 1 + 6
1 | 3 | 4 |   6   |  6 | No  | 3 + 4
1 | 3 | 5 |   7   |  0 | Yes | none
1 | 3 | 6 |   4   |  4 | No  | 1 + 6
1 | 4 | 5 |   0   |  0 | Yes | none
1 | 4 | 6 |   3   |  3 | No  | 1 + 6
1 | 5 | 6 |   2   |  2 | No  | 1 + 6
2 | 3 | 4 |   5   |  5 | No  | 3 + 4
2 | 3 | 5 |   4   |  4 | No  | 2 + 5
2 | 3 | 6 |   7   |  0 | Yes | none
2 | 4 | 5 |   3   |  3 | No  | 2 + 5
2 | 4 | 6 |   0   |  0 | Yes | none
2 | 5 | 6 |   1   |  1 | No  | 2 + 5
3 | 4 | 5 |   2   |  2 | No  | 3 + 4
3 | 4 | 6 |   1   |  1 | No  | 3 + 4
3 | 5 | 6 |   0   |  0 | Yes | none
4 | 5 | 6 |   7   |  0 | Yes | none

```

---

# Alt. version #1, 32 bytes

Takes input as an array. Returns a boolean.

```
a=>a.every(x=>a.every(y=>x+y-7))

```

### Test cases

```
let f =

a=>a.every(x=>a.every(y=>x+y-7))

console.log('[Truthy]')
console.log(f([6]      ))
console.log(f([6, 2]   ))
console.log(f([1, 3]   ))
console.log(f([2, 1, 3]))
console.log(f([3, 2, 6]))

console.log('[Falsy]')
console.log(f([1, 6]            ))
console.log(f([5, 4, 2]         ))
console.log(f([3, 1, 4]         ))
console.log(f([5, 4, 6, 2]      ))
console.log(f([1, 2, 3, 4, 5, 6]))
```

---

# Alt. version #2, Chrome/Firefox, 34 bytes

This one abuses the sort methods of Chrome and Firefox. It doesn't work with Edge.

Takes input as an array. Returns `0` or `1`.

```
a=>a.sort((a,b)=>k&=a+b!=7,k=1)&&k

```

### Test cases

```
let f =

a=>a.sort((a,b)=>k&=a+b!=7,k=1)&&k

console.log('[Truthy]')
console.log(f([6]      ))
console.log(f([6, 2]   ))
console.log(f([1, 3]   ))
console.log(f([2, 1, 3]))
console.log(f([3, 2, 6]))

console.log('[Falsy]')
console.log(f([1, 6]            ))
console.log(f([5, 4, 2]         ))
console.log(f([3, 1, 4]         ))
console.log(f([5, 4, 6, 2]      ))
console.log(f([1, 2, 3, 4, 5, 6]))
```

# Answer
> 16 votes
# Python 2, 35 bytes

```
lambda a:any(7-i in a for i in a)<1

```

Try it online!

# Answer
> 9 votes
# Haskell, 24 bytes

*-3 bytes thanks to H.PWiz.*

```
f l=all(/=7)$(+)<$>l<*>l

```

Try it online!

## Explanation

```
f l=all(/=7)$(+)<$>l<*>l

f l=                      -- make a function f that takes a single argument l
             (+)<$>l<*>l  -- take the sum of each pair in the cartesian product...
    all(/=7)$             -- ...and check if they're all inequal to 7

```

# Answer
> 7 votes
# Regex (Perl / Java / PCRE2 v10.34+), ~~30~~ ~~29~~ 27 bytes

```
^(?!.*:(x(\2?+:.*\b)?){7}:)

```

Takes its input in unary, as a concatenation of strings of `x` characters whose lengths represent the numbers, separated and enclosed on both sides by `:` characters. Example: `:x:xxxxxx:` represents `[1, 6]`.

Try it online! \- Perl
Try it online! \- Java
Attempt This Online! \- PCRE2 v10.40+

This is an adaptation of the ~~31~~ ~~30~~ 28 byte version below, but it prevents more than one split from occurring in a somewhat more complex manner. Upon matching a split, `\2` captures the intervening elements, including commas – or just a single comma if there are no intervening elements.

How this prevents more than one split would be simple to explain if `(?(2)\2)` were used instead of `\2?+`. Then the mechanism would be that on subsequent attempts to match a splitting after one has already occurred, that would be forced to coincide with matching a duplicate element, or two commas in a row.

But `\2?+` will successfully make an empty match if `\2` is not an exact match at that position. However, note that if this did happen, it could only result in false negatives (returning "False" incorrectly) – never false positives – because it could make the pattern inside the negative lookahead match when it shouldn't, but it can't prevent a match that should have happened.

All lists of 4 or more numbers will return "False", so the addition of false negatives won't matter. And lists of 2 or fewer elements can only match one split anyway (where `\2` captures a single comma alone), so no false negatives could result there.

So we only need to consider lists of 3 elements:

* Only two splits can occur at most, and if that is the case, `\2` will contain exactly one comma. The first split prevents a second split from being matched because `\2?+,` would only match two commas in a row.
* Or if a split matches one intervening element, only one split can occur anyway, so there's no place for a second split to match.

And here is a test harness with all 156 lists of 3 or fewer elements, demonstrating this regex to work correctly:

Try it online! \- Perl

# Regex (Perl / Java / Python`regex` / Ruby / PCRE), ~~31~~ ~~30~~ 28 bytes

```
^(?!.*:(x\2?+(:).*\b|x){7}:)

```

Try it online! \- Perl
Try it online! \- Java
Try it online! / Attempt This Online! \- **Python (with `regex`)**
Try it online! \- Ruby
Try it online! \- **PCRE**

This is an adaptation of the ~~33~~ ~~32~~ ~~31~~ 29 byte version below, but it prevents more than one split from occurring with `\2?+(,)`, which forces a split to coincide with matching two commas in a row (which can never happen in the input specification) if a split has already occurred.

# Regex (Perl / Boost / Python / Python`regex` / Ruby / PCRE / .NET), ~~33~~ ~~32~~ ~~31~~ 29 bytes

```
^(?!.*:(?(1)x|x(:.*\b)?){7}:)

```

Try it online! \- Perl
Try it online! \- **Boost**
Try it online! / Attempt This Online! \- **Python**
Try it online! / Attempt This Online! \- Python (with `regex`)
Try it online! \- Ruby
Try it online! \- PCRE
Try it online! \- **.NET**

This works by asserting that no two numbers add up to exactly 7. It does this by consuming exactly 7 `x` characters – a split is allowed to occur at any point within this, but not more than once.

```
^             # Anchor to start
(?!           # Negative lookahead - assert that the following can't match:
    .*:           # Skip to after any occurrence of a bounding character,
                  # which denotes the beginning of a number's unary
                  # representation.
    (?(1)         # Conditional upon whether \1 is set:
        # If \1 is set:
        x             # tail -= 1
    |
        # If \1 is unset:
        # (This is only allowed to match once within this loop. There is no
        # need to verify afterward that it matched exactly once, because the
        # input specification allows us to assume there will be no numbers
        # greater than 6 – so, 7 will never appear.)
        x             # tail -= 1
        (
            :.*\b         # Complete the match for the current number, and
                          # skip to the beginning of any subsequent number's
                          # unary representation.
        )?            # Match the above optionally
    ){7}          # Iterate the above exactly 7 times; this can never result in
                  # the 7th iteration ending in a split, as that would require
                  # matching 7 x's in a row, but the input is guaranteed not to
                  # contain a 7.
    :             # Assert that tail == 0 (i.e, that this is the end of a
                  # number's unary representation)
)

```

Strangely, this actually works with Python's `re` library, even though `(?(2)`...`)` is a forward-declared conditional, and `re` doesn't support forward-declared or nested backreferences; `\2` in that position would throw an error.

Equally strangely, it works in Boost, even though that regex engine doesn't support nested or forward-declared backreferences either, and a `\2` in that position would cause Boost to throw an error as well.

The previous 33 byte version did not work properly with Python's `re`; it used a nested conditional, and Python silently treated that as a no-op, making the regex return some false negatives. But strangely, that version works in Python`regex`, even though that engine doesn't support nested backreferences either.

# Regex (Perl / Java / Python`regex` / Ruby / PCRE / .NET), ~~34~~ ~~33~~ ~~32~~ 30 bytes

```
^(?!.*:(x(?!\2):.*\b()|x){7}:)

```

Try it online! \- Perl
Try it online! \- Java
Try it online! / Attempt This Online! \- Python (with `regex`)
Try it online! \- Ruby
Try it online! \- PCRE
Try it online! \- .NET

This adds Java support to the above ~~33~~ ~~32~~ ~~31~~ 29 byte version, by removing the use of the conditional `(?(2)`...`)`. Support for Python and Boost is dropped, due to the use of the nested backreference `\2`.

# Regex (ECMAScript 2018 / Python`regex` / .NET), ~~41~~ ~~36~~ 34 bytes

```
^(?!(.*:)(\b(?<=^\1x+).*:x|x){7}:)

```

Try it online! \- **ECMAScript 2018**
Try it online! / Attempt This Online! \- Python (with `regex`)
Try it online! \- .NET

```
^             # Anchor to start
(?!           # Negative lookahead - assert that the following can't match:
    (.*:)         # Skip to after any occurrence of a bounding character,
                  # which denotes the beginning of a number's unary
                  # representation;
                  # \1 = the entire portion of the string that has been
                  # skipped, going all the way back to its beginning.
    (
        \b            # Assert that we're on a word boundary
        # The below is only allowed to match once within this loop. There is
        # no need to verify afterward that it matched exactly once, because
        # the input specification allows us to assume there will be no numbers
        # greater than 6 (so, 7 will never appear).
        (?<=          # Lookbehind - evaluated from right to left (so in this
                      # listing, read it from bottom to top)
            ^         # Assert this is the start of the string
            \1        # Match \1
            x+        # Skip back to the beginning of the unary representation
                      # of the current number
        )
        .*:           # Complete the match for the current number, and skip
                      # to the beginning of any subsequent number's unary
                      # representation.
        x             # tail -= 1
    |              # or...
        x             # tail -= 1 (and do nothing else)
    ){7}          # Iterate the above exactly 7 times; this can never result in
                  # the 7th iteration ending in a split, as that would require
                  # matching 7 x's in a row, but the input is guaranteed not to
                  # contain a 7.
    :             # Assert that tail == 0 (i.e, that this is the end of a
                  # number's unary representation)
)

```

A previous 41 byte version using lookbehind appears to expose a bug in Python`regex`:

```
^(?!(.*\b)x+(,.*\b)x+\b(?<=^\1(\2?x){7}))

```

Try it online! \- ECMAScript 2018 - works
Attempt This Online! \- Python (with `regex`) - does not work
Try it online! \- .NET - works

Upon investigation, the bug actually has nothing to do with lookbehind. I reported it here and it is now fixed.

# Regex (ECMAScript or better), ~~73~~ ~~69~~ ~~46~~ ~~41~~ ~~40~~ ~~39~~ 37 bytes

```
^(?!.*:(?=x*(.*))(x(?=\1).+\b|x){7}:)

```

Try it online! \- **ECMAScript** (SpiderMonkey)
Try it online! \- ECMAScript 2018 (Node.js)
Try it online! \- Perl
Try it online! \- Java
Try it online! \- Boost
Try it online! \- Python
Try it online! / Attempt This Online! \- Python (with `regex`)
Try it online! \- Ruby
Try it online! \- PCRE
Try it online! \- .NET

This now ports the ~~33~~ ~~32~~ 31 byte version's algorithm to support ECMAScript:

```
^             # Anchor to start
(?!           # Negative lookahead - assert that the following can't match:
    .*:           # Skip to after any occurrence of a bounding character,
                  # which denotes the beginning of a number's unary
                  # representation.
    (?=x*(.*))    # \1 = the entire string following the current number's
                  #      unary representation
    (
        x             # tail -= 1
        # The below is only allowed to match once within this loop. There is
        # no need to verify afterward that it matched exactly once, because
        # the input specification allows us to assume there will be no numbers
        # greater than 6 (so, 7 will never appear).
        (?=\1)        # Assert that the entire string following the current
                      # position matches what was captured in \1, which
                      # accomplishes two things – it asserts that we
                      # haven't skipped to another number yet, and that
                      # we've finished consuming the entire current number,
                      # i.e. that tail == 0.
        .+\b          # Skip to the beginning of any subsequent number's
                      # unary representation (the first character skipped
                      # will be a comma).
    |              # or...
        x             # tail -= 1 (and do nothing else)
    ){7}          # Iterate the above exactly 7 times; this can never result in
                  # the 7th iteration ending in a split, as that would require
                  # matching 7 x's in a row, but the input is guaranteed not to
                  # contain a 7.
    \b            # Assert that tail == 0 (i.e, that this is the end of a
                  # number's unary representation)
)

```

The previous ~~73~~ 69 byte version worked by treating every possible pair of numbers that add to 7 as a separate case, like the decimal version below:

```
^(?!(?=.*\bx\b).*x{6}|(?=.*\bxx\b).*\bx{5}\b|(?=.*\bxxx\b).*\bx{4}\b)

```

# ~~Regex (.NET), 46 bytes~~

```
^(?!.*\b(){7}(?<-1>x)+,.*\b(?<-1>x)+(?(1)^)\b)

```

Obsoleted by the ~~33~~ 32 byte version above.

# ~~Regex (Perl / Boost / Python / Ruby / PCRE / .NET), 58 bytes~~

```
^(?!.*\b(x)?(xx)?(xxxx,.*\b|,.*\bxxxx)(?(2)|xx)(?(1)|x)\b)

```

Obsoleted by the versions above. Worked by capturing two numbers in binary, and asserting that the second number has all 3 of its lowermost bits flipped when compared to the first number (and asserting that this doesn't occur anywhere in the input).

# Regex (ECMAScript or better), ~~38~~ 37 bytes

```
^(?!(?=.*1).*6|(?=.*2).*5|(?=.*3).*4)

```

Takes its input in decimal. There is no need for delimiters, because the full range fits into a single digit.

Try it online! - ECMAScript / Perl / Java / Python / .NET

Pure regex is very limited in what math can be done on decimal input, so this version just asserts that no two numbers occur anywhere in the list that add up to 7, by exhaustively listing all the pairs that could do so.

# Answer
> 6 votes
# Cubically, ~~41~~ 34 bytes

```
$(7:*-!F-!S-!B'-!B'-!S-!F$):0+>2=%

```

Try it online!

Takes input as a space-separated list of integers, printing `1` for true and `0` for false.

Explanation:

```
$(7 ... $)

```

For every integer in the input...

```
:*

```

Place it in the notepad, and multiply it by itself.

Cubically can only use values in one of its nine memory locations, and the notepad is the only one that can be freely read or written, so I perform the next calculation "scaled up" by the current input value itself, memory location 7--since it's nonzero and doesn't change until we read a new integer (or character) with `$` (or `~`). This is shorter than using a face we don't modify as the scale factor, because the notepad is the implicit argument for `*` and the input is the implicit argument for `-`.

```
-!F

```

Subtract the input from the notepad. If this makes it 0 (the original input was 1), rotate the front face of the memory Rubik's Cube once clockwise.

Doing this once replaces a row of `0`s on face 0 with `1`; doing this again replaces those `1`s with `5`s.

```
-!S-!B'-!B'-!S-!F

```

Repeat for the other five possible values: rotate the front if it's 6, the middle if it's 2 or 5, and the back if it's 3 or 4. (The back rotations have to be clockwise with respect to the front, so they're actually counterclockwise `B'` with respect to the back.)

```
:0+>2

```

After the loop, set the notepad to the sum of face 0, add it to itself, and check if it's strictly greater than the sum of face 2.

Face 0 contains a mix of `0`, `1`, and `5`, and we want to discriminate between cases where it contains any `5`s and cases where it doesn't. The greatest sum it can have without `5`s is 9, and the least sum it can have with `5`s is 15 (since only whole rows at a time are moved without being mixed, it has to be a multiple of 3), so doubling it turns 9 into 18, which is the sum of face 2 (since none of the rotations performed in the loop affected face 2).

```
=%

```

Output whether or not the notepad equals the input buffer.

The input buffer is set to 0 after exhausting the input, and the notepad contains 1 if the faces can't all be seen or 0 if they can, so comparing them for equality inverts that to satisfy the challenge's truthiness requirement.

# Answer
> 5 votes
# Mathematica, 20 bytes

```
xFreeQ[#+x&/@x,7]

```

The  is `\[Function]`

-12 bytes from Martin Ender
-7 bytes from Misha Lavrov

Try it online!

# Answer
> 5 votes
# APL (Dyalog), 7 bytes

```
~7∊∘.+⍨

```

Try it online!

`∘.+⍨` \- addition table (every element with every element)

`7∊` \- 7 exists?

`~` \- negate

---

# APL (Dyalog), 7 bytes

```
⍬≡⊢∩7-⊢

```

Try it online!

`7-⊢` \- subtract each element from 7

`⊢∩` \- intersect with the original array

`⍬≡` \- empty?

# Answer
> 5 votes
# , 27 bytes

*thanks to Gregor for fixing a bug*

```
function(d)!any((7-d)%in%d)

```

Try it online!

Port of Chas Brown's answer. Having vectorized operations helps make this much shorter in R.

# Answer
> 4 votes
# Retina, ~~21~~ 20 bytes

```
O`.
M`1.*6|2.*5|34
0

```

Try it online! Link includes test cases. Edit: Saved 1 byte thanks to @MartinEnder. Explanation:

```
O`.

```

Sort the input.

```
M`1.*6|2.*5|34

```

Check for a pair of opposite sides (3 and 4 sort next to each other). This returns 1 for an invalid die or 0 for a valid one.

```
0

```

Logically negate the result.

# Answer
> 4 votes
# Thunno `D`, ~~7~~ \\$5\log\_{256}(96)\approx\\$ 4.12 bytes

```
7_Gze

```

Attempt This Online!

```
7_     # subtract each from 7
  G    # map each to the input with it removed
   ze  # all equal?

```

Now ~~beating~~ tied with the language's creator!

# Answer
> 4 votes
# Nibbles, 5.5 bytes (11 nibbles)

```
-~+.$?@- 7

```

For each element `x` of input, checks tbat `7-x` is not present in the input. Outputs `1` (truthy) if faces can be seen at the same time, and negative value (falsy) if they cannot.

```
-~+.$?@- 7
   .        # map over
    $       # input:
     ?      #   index of (or 0 if absent)
      @     #   in input
            #   of
       - 7  #   7 minus
            #   (implicit) each element
  +         # sum the list
-~          # and subtract from 1.
            # (0 and negative values are falsy,
            # 1 is truthy)

```

# Answer
> 4 votes
# Nekomata \+ `-e`, 4 bytes

```
ᵒ+7f

```

Attempt This Online!

```
ᵒ+     Generate a 2d table with addition
  7f   Check if the result is free of 7.

```

`-e` prints `True` if the computation has any result, and `False` otherwise.

Let's take `[3,1,4]` as an example. `ᵒ+` returns the 2d array `[[6,4,7],[4,2,5],[7,5,8]]`, which contains `7`. So the result is `False`.

# Answer
> 3 votes
# Jelly, 5 bytes

```
7_f⁸Ṇ

```

Try it online!

Port of Chas Brown's answer.

### Explanation

```
7_f⁸Ṇ
7_    Subtract each element from 7
  f⁸  Filter with the original list
    Ṇ Check if empty

```

# Answer
> 3 votes
# Haskell, 26 bytes

```
f x=null[1|7<-(+)<$>x<*>x]

```

Try it online!

# Answer
> 3 votes
# Pyth, 5 bytes

```
!@-L7

```

Try it here.

# Answer
> 3 votes
# Actually, 8 bytes

```
;∙♂Σ7@cY

```

Try it online! (runs all the test cases)

Explanation:

```
;∙♂Σ7@cY
;∙        Cartesian product with self
  ♂Σ      sum all pairs
    7@c   count 7s
       Y  logical negate

```

# Answer
> 3 votes
## Husk, 5 bytes

```
Ëo≠7+

```

Try it online!

### Explanation

```
Ëo     Check that the following function gives a truthy value for all pairs
       from the input.
    +    Their sum...
  ≠7     ...is not equal to 7.

```

# Answer
> 3 votes
# Perl 6, 18 bytes

```
!(1&6|2&5|3&4∈*)

```

Try it online!

`1 & 6 | 2 & 5 | 3 & 4` is a junction consisting of the numbers 1 and 6, OR the numbers 2 and 5, OR the numbers 3 and 4. This junction is an element of () the input list `*` if it contains 1 and 6, or 2 and 5, or 3 and 4. That result is then negated (`!`) to get the required boolean value.

# Answer
> 3 votes
# Vyxal, 4 bytes

```
7ε↔¬

```

Try it Online!

Very simple answer, ports the approach of the 5 byte Jelly.

## Explained

```
7ε↔¬
7ε    # Abs difference of 7 with each item in the input
  ↔   # Remove items in that list that are also in the input
   ¬  # Logical negation - empty list turns into 1, non-empty turns into 0

```

# Answer
> 3 votes
# Thunno `D`, \\$ 5 \log\_{256}(96) \approx \\$ 4.12 bytes

```
7_cS!

```

Attempt This Online! or verify all test cases

#### Explanation

```
7_cS!  # Implicit input
7_     # Subtract each from 7
  c    # Is each in the input?
   S!  # All are false?
       # Implicit output

```

# Answer
> 3 votes
# Jelly, 4 bytes

```
7_ḟƑ

```

Try it online!

Relatively trivial golf of Erik's solution.

```
7_      For each face, subtract it from 7.
   Ƒ    Is the list of results unchanged by
  ḟ     filtering out elements of the original input?

```

Needless to say, a simple `7_f` would win if inverted output were permitted.

# Answer
> 3 votes
# Nibbles, 6 bytes

```
-~,`&.$- 7$

```

Attempt This Online!

Disgusting. Surely there is a better way to do this.

# Answer
> 2 votes
# Pyth, 5 bytes

```
-7sM*

```

**Test suite.**

isaacg saved a byte!

# Answer
> 2 votes
# Ruby, ~~36 31 24~~ 23 bytes

```
->l{l-l.map{|x|7-x}==l}

```

Try it online!

It was so simple, I was looking for the solution to the wrong problem all the time.

# Answer
> 2 votes
## Alice, 18 bytes

```
/..y1nr@
\iReA6o/

```

Try it online!

Prints `Jabberwocky` for valid inputs and nothing otherwise.

### Explanation

Unfolding the zigzag control flow, the program is really just:

```
i.e16r.RyAno

i.  Read all input and duplicate it.
e16 Push "16".
r   Range expansion to get "123456".
.R  Duplicate and reverse.
y   Transliterate, replaces each face with its opposite.
A   Intersection with input.
n   Logical NOT, turns empty strings into "Jabberwocky"
    and everything else into an empty string.

```

# Answer
> 2 votes
## Retina, 20 bytes

```
T`_654`d
M`(.).*\1
0

```

Try it online!

An alternative to Neil's approach.

### Explanation

```
T`_654`d

```

Turn `6`,`5`, `4` into `1`, `2`, `3`, respectively.

```
M`(.).*\1

```

Try to find repeated characters and count the number of matches.

```
0

```

Make sure the result was zero (effectively a logical negation).

# Answer
> 2 votes
# Factor \+ `sets.extras`, 24 bytes

```
[ 7 over n-v disjoint? ]

```

Try it online!

```
          ! { 2 1 3 }
7         ! { 2 1 3 } 7
over      ! { 2 1 3 } 7 { 2 1 3 }
n-v       ! { 2 1 3 } { 5 6 4 }
disjoint? ! t    (i.e. is the intersection empty?)

```

# Answer
> 2 votes
# Japt `-x!`, 5 bytes

```
fUma7

```

Try it or verify test cases

-1 byte thanks to Shaggy

This is basically a port of Lyxal's Vyxal answer.

```
fUma7  x!
f          # elements in both the input and
 Um        #   the input, with each num mapped to
   a7      #     its absolute difference with 7
       x!  # flags: x = sum, ! = logical not

```

# Answer
> 2 votes
# Japt `-!`, 5 bytes

```
ï+ ø7

```

Try it

# Answer
> 2 votes
# C (GCC), 77 bytes

```
i,j;r;f(v,l)int*v;{for(i=r=-1;++i<l;)for(j=0;j<l;)r*=v[i]+v[j++]-7;return r;}

```

Try It Online!

Explanation:

```
i,j;r;
f(v,l)int*v;
{
    // i and r are both initialized to -1. i is incremented by 1 before the
    // loop, making its value equal 0, and for each iteration of the loop,
    // until it's out of bounds of v.
    for(i=r=-1;++i<l;)
        // j also loops through the vector
        for(j=0;j<l;)
            // If v[i]+v[j] == 7, set r to 0, otherwise multiply it by
            // something. If i == j, the sum will never equal 7 since a whole
            // number multiplied by 2 is never odd. Otherwise, the numbers
            // will equal 7 if they're on opposite sides of the die.
            r*=v[i]+v[j++]-7;
    return r;
}

```

# Answer
> 2 votes
# Desmos, ~~45~~ 39 bytes

```
f(x)=0^{[(7-i-x)^2.minfori=x.sort].min}

```

Try it on Desmos!

# Answer
> 2 votes
# TI-Basic, 26 bytes

```
max(seq(min(7-I≠Ans),I,1,dim(Ans

```

Takes input in `Ans`.

# Answer
> 2 votes
# Vyxal, 4 bytes

```
7εF⁼

```

Try it Online!

```
7ε   # 7 - each item
  F  # Remove values that are in ^
   ⁼ # Is it equal to the original?

```

# Answer
> 2 votes
# Scala, 50 bytes

Try it online!

```
def f(a:Seq[Int])=a.forall(i=> !(a.contains(7-i)))

```

# Answer
> 2 votes
# Thunno 2, 4 bytes

```
7_ṗ⁼

```

Attempt This Online!

#### Explanation

```
      # implicit input
7_    # subtract from 7
  ṗ   # set difference
   ⁼  # exactly equal
      # implicit output

```

# Answer
> 1 votes
# 05AB1E, 5 bytes

```
7αå_P

```

Try it online!

**Explanation**

```
7α      # absolute difference between 7 an each in input list
  å     # check each element if it exist in input
   _    # logical negate
    P   # product of list

```

One of several ways to do this in 5 bytes in 05AB1E

# Answer
> 1 votes
# Perl 5, 51 + 1 (`-a`) = 52 bytes

```
say$F[0]+($t=$F[1])-7&&$F[0]+$t-7&&$t+$F[2]-7&&@F<4

```

Try it online!

# Answer
> 1 votes
# Clean, 49 bytes

```
import StdEnv
f l=and[(a+b)<>7\\(a,b)<-diag2 l l]

```

Try it online!

# Answer
> 1 votes
# GNU sed, ~~37~~ 22 + 1 = 23 bytes

+1 byte for `-r` flag. Takes input as digits; prints the input for truthy and `0` for falsy.

-10 bytes thanks to @MartinEnder.

```
y/123/654/
/(.).*\1/c0

```

Try it online!

## Explanation

Similar to @MartinEnder’s Alice answer.

```
y/123/654/   # Transliterate 1-3 to 6-4
/(.).*\1/c0  # If a digit appears twice, replace the pattern space with 0

```

# Answer
> 1 votes
# , 12 bytes

```
7-.@e.[:,+/~

```

This is pretty much the same as the first APL solution by Uriel

Try it online!

# Answer
> 1 votes
# Java (OpenJDK 8), 43 bytes

```
l->l.stream().noneMatch(x->l.contains(7-x))

```

Try it online!

# Answer
> 1 votes
# Swift, 46 bytes

```
f(a:Int)->[Int]{!a.contains{a.contains(7-$0)}}

```

Takes input as `[Int]` (integer array) and returns a `Bool` (boolean).

## Short Explanation (ungolfed)

```
f(a:Int)->[Int]{
    !a.contains (where: {n in    // The input doesn't have an element where
        a.contains(7 - n)        //    the opposite side is in the input
    })
}

```

# Answer
> 1 votes
# Clojure, ~~89~~ ~~80~~ 72 bytes

-9 bytes because I realized use of `reduced` is unnecessary

-8 bytes by changing from using `reduce` to using `some`

```
#(if(< 0(count %)4)(not(some(fn[[a b]](=(+ a b)7))(for[a % b %][a b]))))

```

I tried writing this without looking at any of the tricks other answers use. I may be able to improve on this later.

Returns `true` for true cases, `false` if any sides sum to 7, and `nil` if the number of sides is illegal.

---

```
(defn can-see? [dice-sides]
  ; Ensure its a valid length
  (if (< 0 (count dice-sides) 4)

    ; Then check if any of the permutations sum to 7
    (not (some (fn [[a b]]
                 (= (+ a b) 7))

               ; Generate all permutations
               (for [a dice-sides, b dice-sides] [a b])))))

```

# Answer
> 1 votes
# jq, 25 bytes

```
[.[] as $s|$s+.[]==7]|any

```

Try it online!

Generates all comparisons `side + side == 7`, and outputs `true` if any are.

Saves quite a bit over the obvious answer:

```
[combinations(2)|add]|contains([7])

```

# Answer
> 1 votes
# Python, 55 Bytes

```
lambda x:all(all(int(a)+int(b)-7 for a in x)for b in x)

```

7ry 17 0n11n3

# Answer
> 0 votes
## Haskell, ~~46 41~~ 37 bytes

```
f z=all ((/=7).sum) [[x,y]|x<-z,y<-z]

```

Takes the Cartesian product of the list with itself, then checks if all of the resulting lists do not sum to 7. (If any of them summed to 7, opposite faces would be visible, and "all do not" is shorter than "not any do".)

# Answer
> 0 votes
# IBM/Lotus Notes Formula, 7 bytes

```
!7-i*=i

```

Takes input from a multi-value number field i.

Recursively subtracts each value of i from 7 and checks to see if it is in the original list. ! changes the 1 if it is to a 0 (faces cannot all be seen).

**Test Cases (no TIO available for Notes Formula)**

---
Tags: code-golf, decision-problem
---


# Question
Title: Output the first position in your program for each input character
# Challenge

Write a non-empty program/function `p` that, given a non-empty input string `s`, outputs the position of the **first occurrence** of each character of `s` in the source code of `p`.

For example, if your program is

```
main() { cout << magic << cin }
^0   ^5   ^10  ^15  ^20  ^25

```

and it receives an input `abcd{`, the output should be

```
[1, x, 9, x, 7] (0-based)        [2, x, 10, x, 8] (1-based)

```

Here, `x` represents any output that is not a valid output for a character position (e.g., a negative number, `0` if you use 1-based indexing, `NaN`, `Inf`, the string `potato`, a number greater than your program's length, etc).

## Restrictions

Reading the source code is not allowed (like in a proper quine). The use of comments is allowed, but does count towards your score.

Input and output can be done in a reasonable format, but must be **unambiguous** (only additional delimiters, no `rand` stream and claiming that the answer is somewhere in there), **consistent** (e.g., the `x` from above should always be the same value) and **human-readable**; for example, a string or a character array. You can assume that the input is a string (or array) of printable ASCII characters; no need to handle the entire Unicode set.

---

### Custom code-page or non-printable ascii in your code?

If your language uses a custom code-page (Jelly, APL, etc), you must take that into account (so a program `€æÆ` must output `[1, x, 2]` for an input `€%æ`). Using only non-ASCII characters to output `-1` always (since the input is ASCII-only) is not a valid solution. You may assume that your program natively accepts your custom codepage, i.e., if your program has a method of converting a character `A` to an integer `65` (ASCII encoding), you may assume that it now converts the 65th character in your codepage to `65`.

---

Inspired on the following challenge: Positional Awareness

# Answer
## Python2, 55 Bytes

```
a=" )dfi(+m,nprut.';";print map(('a="'+a).find,input())

```

Starts with a string that contains all the characters used in the code, and then search the indexes
> 25 votes

# Answer
# Lenguage, 56,623 bytes

Below is a hexdump of the first 256 bytes. The remaining bytes can be chosen arbitrarily.

```
0000000: 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f  ................
0000010: 10 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f  ................
0000020: 20 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f   !"#$%&'()*+,-./
0000030: 30 31 32 33 34 35 36 37 38 39 3a 3b 3c 3d 3e 3f  0123456789:;<=>?
0000040: 40 41 42 43 44 45 46 47 48 49 4a 4b 4c 4d 4e 4f  @ABCDEFGHIJKLMNO
0000050: 50 51 52 53 54 55 56 57 58 59 5a 5b 5c 5d 5e 5f  PQRSTUVWXYZ[\]^_
0000060: 60 61 62 63 64 65 66 67 68 69 6a 6b 6c 6d 6e 6f  `abcdefghijklmno
0000070: 70 71 72 73 74 75 76 77 78 79 7a 7b 7c 7d 7e 7f  pqrstuvwxyz{|}~.
0000080: 80 81 82 83 84 85 86 87 88 89 8a 8b 8c 8d 8e 8f  ................
0000090: 90 91 92 93 94 95 96 97 98 99 9a 9b 9c 9d 9e 9f  ................
00000a0: a0 a1 a2 a3 a4 a5 a6 a7 a8 a9 aa ab ac ad ae af  ................
00000b0: b0 b1 b2 b3 b4 b5 b6 b7 b8 b9 ba bb bc bd be bf  ................
00000c0: c0 c1 c2 c3 c4 c5 c6 c7 c8 c9 ca cb cc cd ce cf  ................
00000d0: d0 d1 d2 d3 d4 d5 d6 d7 d8 d9 da db dc dd de df  ................
00000e0: e0 e1 e2 e3 e4 e5 e6 e7 e8 e9 ea eb ec ed ee ef  ................
00000f0: f0 f1 f2 f3 f4 f5 f6 f7 f8 f9 fa fb fc fd fe ff  ................

```

Output is in bytes, as customary for brainfuck et al.

### How it works

This is a simple cat program, specifically `,[.,]`.

The source code contains all 256 byte values in order, so each byte's index in it matches its value.
> 12 votes

# Answer
# Lenguage, 1.22e7 bytes

Consists of `12263215` `NUL` bytes, *(Hex 0x00)*.

Outputs a `NUL` for every character that doesn't appear in the source.

> The ruse is that the input will never contain a `NUL`, so we always output the amount of `NUL`s that there are characters in the input.

This translates to the following Brainfuck program

```
,[[-].,]

```

And with a breakdown...

```
,[[-].,]
,[    ,]    #Basic Input loop.
  [-]       #Zero out the cell.
     .      #Print it (A NUL).

```

*This just shows the sheer power of Lenguage as a golfing language. Fear it.*
> 11 votes

# Answer
# Jelly, ~~10~~ 9 bytes

```
“ṾiÐ€Ɠv”v

```

Try it online!

### How it works

```
“ṾiÐ€Ɠv”v  Main link. No arguments.

“ṾiÐ€Ɠv”   Set the left argument and the return value to s := 'ṾiÐ€Ɠv'.
        v  Execute the string s as a monadic Jelly program with argument s.

 Ṿ         Uneval; yield a string representation of s, i.e., r := '“ṾiÐ€Ɠv”'.
     Ɠ     Read one line from STDIN and evaluate it like Python would.
  iÐ€      Find the index of each character in the input in r.
      v    Eval the list of indices as a monadic Jelly program with argument s.
           Why?
             This is the shortest way to add the character 'v' to the string s,
             meaning that we can use r without having to append anything.
           What?
             The v atom vectorizes at depth 1 for its left argument, meaning that
             it acts on arrays of numbers and/or characters. When fed an array of
             integers, it first converts them to strings, then concatenates the
             strings and evaluates them as a Jelly program. For example, the array
             [1, 2, 3] gets cast to the string '123', then evaluates, yielding 123.
             Something slightly different happens if the array starts with a 0. For
             example, the array [0, 1, 2] gets cast to '012' just as before, but
             Jelly views '0' and '12' as two separate tokens; numeric literals
             cannot start with a 0. Since the Jelly program is monadic, the first
             token – '0' – sets the return value to 0. Since the second token –
             '12' – is also a niladic link, the previous return value is printed
             before changing the return value to 12. Then, the program finishes
             and the last return value is printed implicitly.

```
> 8 votes

# Answer
# pbrain, ~~402~~ ~~356~~ ~~340~~ ~~338~~ 329 bytes

```
[(:<>)+,-.](>>>>>>)+([-]<<[->+>+<<]>>[-<<+>>]>>[-<+<+>>]<[->+<]<[-<->]<)+([-]+++++++[>+++++++++++++<-]>)+([-]+++++[>++++++++<-]>)+(-:<+++[->++++++<]>)+(-:++)+(-:++)+(----:+)+(-:++)+(-:+)+(-:+)+(-:+)+([-]++:++)+([>[->+>+<<]>>[-<<+>>]<:>>+:[[-]>+<]>-[<<<<[-.>]>>>>>>+>>>>>]<<[-]<<+<-]>>>)[-]>>>>>>>,[<<<<<<++<+++++++++++++:>>>>>>,]

```

Phew, @KritixiLithos and I have been working on this for 4 days now.

Prints `0x00` if input char isn't in program, index of the char (1-based) in hex otherwise. Try it online!

### Explanation:

```
[(:<>)+,-.]
All chars listed here; like other submissions
(>>>>>>)
@KritixiLithos added this part; I don't know what it does but saves the program
+([-]<<[->+>+<<]>>[-<<+>>]>>[-<+<+>>]<[->+<]<[-<->]<)
Comparison ;calculates z=x!=y and puts it in between x and y
Start; X _ _ _ Y
           ^
End;   X Z _ _ Y
         ^
+([-]+++++++[>+++++++++++++<-]>)
Function to add 91 to the tape
+([-]+++++[>++++++++<-]>)
Function to add 40 to the tape
+(-:<+++[->++++++<]>)
Function to add 58 to the tape
+(-:++)
Function to add 60 to the tape
+(-:++)
Function to add 62 to the tape
+(----:+)
Function to add 41 to the tape
+(-:++)
Function to add 43 to the tape
+(-:+)
Function to add 44 to the tape
+(-:+)
Function to add 45 to the tape
+(-:+)
Function to add 46 to the tape
+([-]++:++)
Function to add 93 to the tape
+([>[->+>+<<]>>[-<<+>>]<:>>+:[[-]>+<]>-[<<<<[-.>]>>>>>>+>>>>>]<<[-]<<+<-]>>>)

```

This last function is the loop. It loops through the selected characters `[(:<>)+,-.]` in order and compares the input with the character. Now I'm going to give a deeper explanation on how this loop works.

```
12-n n+2 _ n+2: _ _ _ i _ _ _ _ _ _;  n=loop counter
                  ^                ;  i=input

```

The stack looks like that while in a loop. The loop will run until `12-n` is `0`. Then we have the counter which is `n+2`. This counter is also the number of the function for each of the selected characters. So when `n=0`, `n+2` will be corresponding to the first character, ie `[`. `>[->+>+<<]>>[-<<+>>]<:` does just that, it converts the counter to the character.

Once the pointer is where the caret is, we will compare the character produced from the counter variable with the input while preserving them.

```
12-n n+2 _ n+2: Z _ _ i _ _ _ _ _ _;  n=loop counter
                ^                  ;  i=input

```

`Z` is `0` when the character is equal to the input, or some other non-zero integer otherwise.

Now we come up with an if-statement to check this equality.

```
[[-]>+<]

```

If `Z` is non-zero, ie the character and the input are *not* the same, we increment the next memory place.

After we come out of this if-statement, we decrement the next memory place. Now this memory place contains `!Z`. Finally using this, we output the index of the character if it matches with the input and then exit the loop forcibly. Else, we continue on with the loop until either it is over or a match is found.

```
[-]>>>>>>>
Clears first byte; goes to position to start program
,[<<<<<<++<+++++++++++++:>>>>>>,]
Loops inputs

```
> 8 votes

# Answer
## CJam, ~~14~~ 12 bytes

```
{sq\f#p_~}_~

```

Uses 0-based indexing and `-1` for characters that don't appear in the source.

Try it online!
> 7 votes

# Answer
# Javascript, 34 bytes

```
f=a=>a.map(v=>('f='+f).indexOf(v))

```

It takes input as array of strings, `x` is `-1` (0-based indexing).
> 6 votes

# Answer
## Ruby, ~~41 88 86 71 69 67 61~~ 56 bytes

```
a='p$<.chrs{| #index};"';$<.chars{|c|p"a='#{a}".index c}

```

Thx Lynn for killing 6 bytes
> 5 votes

# Answer
# C, ~~153~~ ~~152~~ 143 bytes

```
char s[99],p[]="odeflnrti%()*+-0;<={}\\";c;f(char*i){sprintf(s,"char s[99],p[]=\"%s",p);for(c=0;c<strlen(i);)printf("%d ",strchr(s,i[c++])-s);}

```

Try it online!
> 5 votes

# Answer
# \>\<\> (Fish) 70 bytes

```
 #.0+4*a5;!?l|!?f4*b+l1--naolc3*1+0.01?!|~ed+0.0+2e-{:;!?+1:i-1:r}+2:"

```

Probably the longest \>\<\> 1 liner I've ever made.

It will print the output for each character found on a separate line (0 indexed).

A non found character will always print the length of the code + 1 (I could change this if deemed not okay in it's current state) so in this case 71 will always be the "Not found" characters.

I'll run up an explanation once I get the time.

Some test cases;

##K = 1\n1\n71

#"# = 1\n69\n1

Try it online

\>\<\> language
> 4 votes

# Answer
# Perl 6, ~~50~~ 52 bytes

```
{(('R~.index$_) for}\\'R~'{((\'').index($_) for $_)}

```

Translation of G B's Ruby solution and Rod's Python solution.

A lambda that inputs a list of characters and outputs a list of zero-based indexes (`Nil` for nonexistent characters).

*EDIT: Fixed an oversight - required adding 2 bytes :(*
> 3 votes

# Answer
## Clojure, ~~43~~ ~~56~~ 48 bytes

Edit: Damn I forgot about `2`! Increased from 43 to 56.

Edit 2: Updated the sample code below this text, updated the number of bytes not to include `(def f ...`) but just the hash-map part.

```
{\{ 0\\   1\  3\0   4\1 10\3 14\4 20\2 34 \} 43}

```

The hash-map consists only of characters `01234{\\}`, and it encodes their locations. In Clojure hash-maps can be used functions, as shown in this complete example (`f` could be replaced by the hash-map definition):

```
; Keeping track of the zero-based index:
;      00000000001111111111222222222233333333334444444444
;      01234567890123456789012345678901234567890123456789
(def f {\{ 0\\   1\  3\0   4\1 10\3 14\4 20\2 34 \} 43})

(map f "0123456789{} \\abcdef") ; (4 10 34 14 20 nil nil nil nil nil 0 43 3 1 nil nil nil nil nil nil)
(apply str (keys f))            ; " 01234{\\}"

```

I guess this counts :)
> 3 votes

# Answer
# 05AB1E, 19 bytes

```
"'ìsvDyk,"'"ìsvDyk,

```

Try it online!

This outputs -1 in place of missing chars.

---

Luis Mendo posted this (slightly modified) on Golf you a quine for great good! , adding "s" and "k" to that quine results in this answer as well. However, I can't take credit for that trivial of a modification... Luis, you can message me if you'd like to repost this and I'll just delete it. If you want to see my progress before finding that question, view edits. Well... It ***was*** significantly like his at one point.
> 3 votes

# Answer
# Thunno 2, 10 bytes

```
"Ṙs€Ȯ"Ṙs€Ȯ

```

Attempt This Online!

#### Explanation

```
"Ṙs€Ȯ"Ṙs€Ȯ  # Implicit input
"Ṙs€Ȯ"      # Push the string "Ṙs€Ȯ"
      Ṙ     # Surround it by quotes
       s€Ȯ  # Get the index of each character
            # of the input in the string
            # Implicit output

```
> 3 votes

# Answer
# JavaScript, 39 bytes

```
p=s=>[...s].map(c=>`p=${p}`.indexOf(c))

console.log( p('mapP') )
```
> 2 votes

# Answer
# Pyth, 11 bytes

```
xL_+N"N+_Lx

```

A program that takes input of a `"quoted string"`, with any quotes in the string escaped with a preceding `\`, and prints a list of zero-indexed values with `-1` for characters not in the source.

Try it online!

**How it works**

```
xL_+N"N+_Lx    Program. Input: Q
xL_+N"N+_Lx"Q  Implicit quote closure and implicit input
     "N+_Lx"   Yield the string "N+_Lx"
   +N          Prepend a quote
  _            Reverse
 L          Q  Map over Q:
x               Yield the index of the character in the string
               Implicitly print

```
> 2 votes

# Answer
# Java 8, ~~172~~ ~~122~~ 119 bytes

```
a->/*.forEch(Systemupin"\dxO)+ ;:*/a.forEach(c->System.out.print("a->/*.forEch(Systemupin\"\\dxO)+ ;:".indexOf(c)+" "))

```

0-indexed, and gives `-1` for characters that aren't part of the source code.

Try it online.

**Explanation:**

```
a->                    // Method with character-array parameter and no return-type
  /*.forEch(Systemupin"\dxO)+ ;:*/
                       //  Comment containing the remaining characters of the code
  a.forEach(c->        //  Loop over the input-array:
    System.out.print(  //   Print
      "a->/*.forEch(Systemupin\"\\dxO)+ ;:"
                       //   from a String containing all the characters used in the code
      .indexOf(c)+" "))//   the index of the char, plus a space as delimiter

```
> 2 votes

# Answer
# SmileBASIC, ~~128~~ ~~96~~ ~~88~~ 86 bytes

```
?R<3+CD,4LINPUT(S$)WHILE""<S$?INSTR("?R<3+CD,4LINPUT(S$)WHILE"+CHR$(34),SHIFT(S$))WEND

```

An important thing to realize is that this is not *really* a quine challenge. You only need the source code up to the **last unique character**.

I put at least 1 of each character at the beginning of the code: `?R<3+CD,4LINPUT(S$)WHILE"` so I only have to store a copy of the program up to the first quotation mark.
> 2 votes

# Answer
# Japt `-m`, 2 bytes

Takes input as a character array. Output is 0-based, using `-1` for invalid characters. String input *could* also be used but there would be no separator between the output indices, which shouldn't be an issue as it would be unambiguous seeing as they can only be `0` & `-1`.

```
bb

```

Try it

```
bb     :Implicit map of each U in input array/string
b      :First 0-based index in U of
 b     :  Literal "b"

```

Alternatively:

```
aa

```

Try it

`a` being `lastIndexOf`.
> 2 votes

# Answer
# Python, ~~90~~ 88 bytes

```
a,b,d=" ()+.7:[]efilmnor","a,b,d=\"",lambda e:[[b.find(d),a.find(d)+7][d in a]for d in e]

```

Test case:

```
print(d("a,b(]q"))
#[0, 1, 2, 8, 15, -1]

```
> 1 votes

# Answer
# Stacked, noncompeting, 36 bytes

When I said this language was still in development, I meant it. Apparently, `prompt` used to consume the entire stack. This is why I can't have nice things. Try it here!

```
[tostr ':!' + prompt CS index out]:!

```

This is the standard quine framework. Basically, `:` duplicates the function `[...]` on the stack, which is then executed with `!`. Then, the inside of `[...]` executes with the function on the stack. It casts it to a string, appends `:!` (the program itself), then takes a string input with `prompt`. `CS` converts it to a character string. A character string is a bit different from a regular string in that it has operators vectorize over it. In this case, `index` vectorizes over the input, yielding each index of the input string in the program, finally being `out`putted.

For input `Hello, World!`, this gives:

```
(-1 27 -1 -1 2 -1 6 -1 2 5 -1 26 9)

```

I tried using the one without a quine (i.e. encoding the string of characters that appear in your source), but there is only one type of quotation mark in Stacked, namely, `'`, so it would be longer to do that type of solution.
> 1 votes

# Answer
# Husk, 12 bytes

```
m€`:'""m€`:'

```

Try it online!

### Explanation

The explanation is using `¨` to delimit strings and `'` to delimit characters:

```
m€`:'""m€`:'  -- implicit input, for example: ¨m"a1`¨
      "m€`:'  -- string literal: ¨m€`:'¨
  `:'"        -- append character '"': ¨m€`:'"¨
m             -- map function over each character (example with 'a'):
 €            -- | index of first occurrence (1-indexed): 0
              -- : [1,6,0,0,3]

```
> 1 votes

# Answer
# , ~~31~~ 22 bytes

```
11|1+i.~&'11|1+i.~&'''

```

Try it online!

1-indexed, 0 for characters that aren’t present in the code. `''` stands for a single quote. Find each character in the string `11|1+i.~&'`, add 1, modulo 11.
> 1 votes

# Answer
## Perl 5 with `-pl`, 43 bytes

Uses newline separated input and prints `-1` for characters not appearing in the program.

```
$s=q{$_=index"\$s=q{$s};eval\$s",$_};eval$s

```

Try it online!
> 1 votes

# Answer
# \>\<\>, 31 bytes

```
'rd3*i:0(?;}{:}-&b0&?.75*l-nao]

```

Try it online!

Output is 1-indexed, with `32` meaning the character is not in the code.
> 1 votes

# Answer
# Stax, 19 bytes

```
"'sym[]I+"'"s+ym[]I

```

Run and debug it

Outputs 0-based index, one character per line. Turns out it's shorter than modifying the `"34bL"34bL` quine I wrote earlier.
> 1 votes

# Answer
# JavaScript, ~~59~~ 57 bytes

-2 Bytes thanks to Shaggy

```
a=>(m='Opined.fx,"+)',a.map(x=>("a=>(m='"+m).indexOf(x)))

```

Without reading source.

Attempt This Online!
> 1 votes

# Answer
# SAS, 124 ~~60~~ bytes;

The new answer is shift from pure SAS 4GL to SAS macrolanguage.

The code:

```
%let S=%nrstr(%macro _(t);data;s=&t;do i=1to length(s);p=find(symget("S"),char(s,i));put p@;end;run;%mend;%_);%unquote(&S())

```

To run it, insert your `'string'` enclosed in single quotes between brackets after `&S`, for example:

```
...%unquote(&S('!#&%macro _sS@'))

```

and in the log you will see:

```
0 0 20 1 2 3 4 5 6 7 8 18 57 77

```

To escape single quote in the string write it doubled: `'AB''CD'`.

---

\[EDIT:\] 60 bytes answer was suggested for rejection as "a snippet, meaning it cannot just assume variables are defined". In context of SAS 4GL programming I agree to disagree with that opinion. ;-)

I keep it below for further comments.

---

Code assume that the string is given in a variable `s` and the source code is stored in macroVariable `s`.

The code:

```
do i=1to length(s);p=find(symget("S"),char(s,i));put p@;end;

```

Process goes as follows:

1. store source code in macrovariable `S` by runing:

```
data _null_;
  call symputX("S",'do i=1to length(s);p=find(symget("S"),char(s,i));put p@;end;',"G");
run;

```
2. assign string `"i S;abcd{"` to variable `s` and resolve ( by `&S.` ) the macrovariable `S`:

```
data;
s="i S;abcd{";
&S.
run;

```

The Log says:

```
1    data _null_;
2    call symputX("S",'do i=1to length(s);p=find(symget("S"),char(s,i));put p@
2  ! ;end;',"G");
3    run;

NOTE: DATA statement used (Total process time):
      real time           0.00 seconds
      cpu time            0.00 seconds

4
5    data;
6    s="i S;abcd{";
7    &S.
8    run;

4 3 35 19 41 0 39 1 0
NOTE: The data set WORK.DATA14 has 1 observations and 3 variables.
NOTE: DATA statement used (Total process time):
      real time           0.00 seconds
      cpu time            0.00 seconds

```

You can run:

```
%put %length(%superq(S));

```

to get source code length.
> 1 votes

# Answer
# Python 2, ~~49~~ 48 bytes

-1 byte thanks to Jo King

```
c='print map(("c=%r;ex"%c).find,input())';exec c

```

Try it online!

---

# Python 3, ~~53~~ ~~52~~ 51 bytes

-1 byte thanks to Jo King

```
c='print(*map(("c=%r;ex"%c).find,input()))';exec(c)

```

Try it online!
> 0 votes

# Answer
# Burlesque, 27 bytes

```
#Qup~-"#Q"j?+wd\[Ppm{pPjFi}

```

Try it online!

Returns list of indices with `-1` for each not present.

```
#Q      #Push remaining code to stack
up      #Turn to string
~-      #Remove brackets
"#Q"j?+ #Add the "#Q" to the beginning
wd\[    #Remove all spaces
Pp      #Push to virtual stack
m{      #Map (apply to each char in input)
  pP    #Pop from other stack
  jFi}  #Find character in string

```
> 0 votes

# Answer
# PowerShell Core, 33 bytes

```
$f={$args|%{"`$f={$f}"|% i*f $_}}

```

Try it online!

Takes the string argument using splatting.

Returns `-1` when a character can't be found

It works by storing a code block in the variable `$f`, then converts it to a string adding the missing bits `"`$f={$f}"` and does an `indexOf` each input character and returns the result.
> 0 votes

---
Tags: code-golf, string, quine
---


# Question
Title: Print the sum of the squares of some numbers
This is a little codegolf challenge from codingame.com. I was wondering how much Python3 code is necessary (but of course answers are not limited to Python3).

**Input**
The first line contains one positive integer n. The second line contains n positive integers. Each consecutive integers on the second line are separated by one space. There is no newline at the end of the second line.

**Output**
One line containing the sum of the squares of the numbers on the second input line, and no white space except an optional newline at the end.

Each entry must be a complete program with input and output, not only a function. Shortest code wins.

For example, input:

```
5
1 2 5 7 8

```

and output:

```
143

```

# Answer
# Jelly, 5 bytes

```
ṣ⁶V²S

```

Try it online.

Input format is rather annoying....

## Explanation

```
ṣ⁶V²S
ṣ⁶       split by space
  V      map eval over the resulting list -- the newline in the first element causes the first line to be treated as a separate link and ignored
   ²     map square over the list
    S    sum

```
> 2 votes

# Answer
# 05AB1E, 5 bytes

Code:

```
²ð¡nO

```

Explanation:

```
²      # Take the second input, the first input is ignored
 ð¡    # Split on spaces
   n   # Square each element
    O  # Take the sum and implicitly output it

```

Uses **CP-1252** encoding.

Try it online!
> 2 votes

# Answer
## Python 3, 52

```
i=input;print(sum(int(d)**2for d in i(i()).split()))

```
> 2 votes

# Answer
# MATL, 6 bytes

```
xjU2^s

```

**Try it online!**

```
x    % take first input and throw it away
j    % take second input as a string
U    % convert to array with those numbers
2^   % element-wise square
s    % sum of array

```
> 1 votes

# Answer
# Python 3, 54 bytes

*-\[\] thanks to shooqie*

```
print(sum(int(i)**2for i in input(input()).split()))

```

Takes input as specified in the first version of the question.

So to answer your question: Not a lot.
> 1 votes

# Answer
## Pyke, 10 bytes

```
;\ cFE2^)s

```

Takes input as requested

Try it here (Yay setup a try-it page!)

Or 5 bytes if allowed a list of ints:

```
2Rm^s

```

Or noncompeting (add squared node), 3 bytes

```
mXs

```
> 1 votes

# Answer
## Minkolang 0.15, 9 bytes

```
n[n2;+]N.

```

Try it here!

### Explanation

```
n            Take number from input
 [    ]      Pop top of stack and repeat that many times
  n          Take number from input
   2;        Square it
     +       Add to top of stack
       N.    Output as number and stop.

```
> 1 votes

# Answer
## CJam, 10 bytes

```
l;l~]2f#1b

```

Test it here.

### Explanation

```
l;   e# Read first line and discard.
l~   e# Read second line and evaluate, dumping all integers on the stack.
]    e# Wrap them in an array.
2f#  e# Square each.
1b   e# Sum.

```
> 1 votes

# Answer
# Octave, 45 bytes

Octave is not exactly designed for accepting random input formats. For instance, input over multiple lines is impossible. Also, numbers can't be entered as a list unless you have brackets. For that reason, the input must be taken as a string.

```
input('');disp((x=str2num(input('','s')))*x')

input('')                                     % Take the first input line and discard
                         input('','s')        % Take the second input as a string
               x=str2num(input('','s'))       % Convert the string to a list of numbers, x
               (x=str2num(input('','s')))*x'  % Multiply x by x transposed
                                              % This is equivalent to sum(x.^2) but shorter
          disp((x=str2num(input('','s')))*x') % Display the result

```

Call it like this:

```
input('');disp((x=str2num(input('','s')))*x')
5
1 2 5 7 8
143

```
> 1 votes

# Answer
# R, 22 bytes

Nothing very flash, handles the input as specified

```
cat(sum(scan()[-1]^2))

```

Test run

```
> cat(sum(scan()[-1]^2))
1: 5
2: 1 2 5 7 8
7:
Read 6 items
143
>

```
> 1 votes

# Answer
## Lua, ~~74~~ 62 Bytes

**Edit: saved 8 bytes due to @KennyLau**

It's quite straigthforward, skip the first line and iterate over the group of digits in the second.

```
i,x=io.read,0i()i():gsub("%d+",function(d)x=x+d*d end)print(x)

```

### Ungolfed

```
x=0
i=io.read
i()
i():gsub("%d+",function(d)
   x=x+d*d
end)
print(x)

```
> 1 votes

# Answer
# Pyth, 10 bytes

```
sm^sd2ce.z

```

Try it here!

Takes input in the exact same format as specified in the challenge.

### Explanation

```
sm^sd2ce.z  # .z = input lines

       e.z  # only take the last line
      c     # split on spaces
 m          # map each number d
   sd       # convert to integer
  ^  2      # square
s           # sum all squares

```

### Alterntive solutions with more generous input formats

**8 bytes** if I may omit the number count:

```
sm^sd2cz

```

Try it here!

**4 bytes** if I may take the input as list of integers:

```
s^R2

```

Try it here!
> 0 votes

# Answer
## Pyth, 9 bytes

```
s^R2re.z7

```

Try it here

Or 7 bytes if allowed to omit line 1

```
s^R2rz7

```
> 0 votes

# Answer
# C,65 bytes

```
j,k;main(i){for(;scanf("%d",&i)+1;j++&&(k+=i*i));printf("%d",k);}

```
> 0 votes

# Answer
## Haskell, 48 bytes

```
main=interact$show.sum.map((^2).read).tail.words

```

How it works:

```
interact                 read whole input, pass it to a function and
                         print it's return value. The function is:

               words     split at whitespace into words
           tail          drop first element (the number on line #1)
    map(       )         convert each word
           read             to integers
       (^2)                 and square
  sum                    sum all values
show                     convert back to string

```
> 0 votes

# Answer
# , 4 bytes + 100

```
+/*:

```

Try it.

```
   +/*:1 2 5 7 8
143

```

A +100 punishment in the byte-count to myself for not having standard input.
> 0 votes

# Answer
## Batch, 76 bytes

```
@set/px=
@set/px=
@set t=0
@for %%n in (%x%)do set/at+=%%n*%%n
@echo %t%

```
> 0 votes

# Answer
# GS2, 5 bytes

```
W",Φd

```

Try it online!

### How it works

```
W      Find all numbers in the input; push a list.
 "     Discard the first number.
  ,    Square.
   Φ   Map the last instruction over the list of numbers.
    d  Compute the sum of all squares.

```
> 0 votes

# Answer
# Japt, 8 bytes

```
Ns1 mp x

```

Try it in the Japt Interpreter.

### How it works

The code is parsed as

```
N.s(1).m(p).x()

```
* `N` is a variable; it contains the parsed input.
* `s(1)` discards the first array element.
* `m(p)` maps `p` (square) over the remaining array.
* `x()` computes the sum of the array of squares.
> 0 votes

# Answer
# Pylongolf2, 8 bytes

```
c| n²+~

```

```
c  - read the input
|  - split by space (note the 1 space after |)
n  - convert all of that in the list to numbers
²  - Square everything in the list
+  - Sum everything in the list
~  - Print it

```
> 0 votes

# Answer
# GolfScript, 13 bytes

Input is extremely easy for GolfScript.

```
~](;{.*}%{+}*

```

Try it online!

## Explanation

```
~             # Take & Evaluate the input
 ]            # Wrap the whole input into a list
  (;          # Remove the first item
    {.*}%     # Map with squaring
         {+}* # Reduce by summation

```
> 0 votes

# Answer
# JavaScript (V8), 38 bytes

```
x=>Math.hypot(...x.match(/\s\d+/g))**2

```

Try it online!
> 0 votes

# Answer
# Thunno 2 `S`, 4 bytes

```
sON²

```

Attempt This Online!

With normal I/O it would be **1 byte** (with `S` flag):

```
²

```

Attempt This Online!

#### Explanation

```
sON²  # Implicit input
s     # Discard the first input
 O    # Split the second input on spaces
  N   # Convert each string to a number
   ²  # Square each number
      # Implicit output of the sum

```
> 0 votes

---
Tags: code-golf, arithmetic
---