title: Rotate every row and column in a matrix

text:
# Question
Title: Rotate every row and column in a matrix
# The Challenge

Given a `n x n` matrix of integers with `n >= 2`

```
1 2
3 4

```

and a list of integers with exactly `2n`elements

```
[1,2,-3,-1]

```

output the rotated matrix. This matrix is contructed in the following way:

* Take the first integer in the list and rotate the first row to the right by this value.
* Take the next integer and rotate the first column down by this value.
* Take the next integer and rotate the second row to the right by this value, etc. until you rotated every row and column of the matrix once.

The list can contain negative integers which means that you shift the row/column left/up instead of right/down. If the integer is zero, don't rotate the row/column.

**Example using the input above**

```
List element      Matrix         Explanation
------------------------------------------------------------
1                  2 1           Rotate 1st row right by 1
                   3 4

2                  2 1           Rotate 1st column down by 2
                   3 4

-3                 2 1           Rotate 2nd row left by 3
                   4 3

-1                 2 3           Rotate 2nd column up by 1
                   4 1

```

# Rules

* You may choose the most conventient input format. Just make it clear which one you use.
* Function or full program allowed.
* Default rules for input/output.
* Standard loopholes apply.
* This is , so lowest byte-count wins. Tiebreaker is earlier submission.

# Test cases

Input format here is a list of lists for the matrix and a normal list for the integers.

```
[[1,2],[3,4]],[1,2,-3,-1] -> [[2,3],[4,1]]
[[1,2],[3,4]],[1,1,1,1] -> [[3,2],[4,1]]
[[1,2],[3,4]],[0,0,0,0] -> [[1,2],[3,4]]
[[1,2,-3],[-4,5,6],[7,-8,0]],[1,-2,0,-1,3,4] -> [[7,5,0],[-3,-8,2],[-4,1,6]]
[[1,2,-3],[-4,5,6],[7,-8,0]],[3,12,-3,0,-6,-3] -> [[1,2,-3],[-4,5,6],[7,-8,0]]

```

**Happy Coding!**

# Answer
## CJam, 13 bytes

```
{{a.m>1m<z}/}

```

An unnamed block (function) that takes the matrix and the list on top of the stack (in that order) and leaves the new matrix in their place.

Run all test cases.

Same idea, same byte count, different implementations:

```
{{\(@m>a+z}/}
{{(Im>a+z}fI}
{{:\Im>]z}fI}

```

### Explanation

Ideally we want to treat each instruction in the list the same, and just use it to rotate the first row of the matrix. This can be done quite easily by transforming the matrix after each instruction a bit and making sure that all those extra transformations cancel out in the end. So after processing each instruction, we rotate *all* rows one up (such that the next instruction along the same dimension processes the next row) and then transpose the matrix, such that we're actually processing columns next. These additional transformations are orthogonal to the instructions in the list and have a period of exactly `2n`, just what we need.

As for the code:

```
{      e# For each instruction...
  a    e#   Wrap it in a singleton array.
  .m>  e#   Combine it element-wise with the matrix to rotate right. This is
       e#   a fairly common idiom to apply a binary operation only to the first
       e#   element of an array, since element-wise operations just retain all the
       e#   unpaired elements of the longer array.
  1m<  e#   Rotate the rows one up.
  z    e#   Transpose.
}/

```
> 5 votes

# Answer
# APL (Dyalog Extended), ~~17~~ ~~15~~ ~~14~~ 13 bytes

*-3 bytes by Adám*

```
(⍉1⊖⌽`@1⍢⌽)/⌽

```

Try it online!

Takes input as a list where the first element is the matrix, and the remaining elements are the rotation amounts. If ⌽ rotated to the right instead of left, this would beat CJam.

```
(⍉1⊖⌽@1 1⍢⌽)/⌽    Monadic train:
(⍉1⊖⌽@1 1⍢⌽)      Helper function to rotate and transpose once.
                        Takes args ⍺ (amount to rotate) and ⍵ (current array)
     ⌽                 Function to rotate left
        1 1             2-element vector containing 1.
                        The second 1 is redundant, but saves 1 byte over (,1).
     ⌽@1 1             Function to rotate the 1st row left by ⍺.
     ⌽@1 1⍢⌽          Reverse ⍵, rotate 1st row left by ⍺, then reverse again.
                        This rotates the first row of ⍵ to the *right*.
  1⊖                   Rotate all the rows upward,
 ⍉                                                 then transpose.
(⍉1⊖⌽@1 1⍢⌽)/⌽   Fold (/) this function over the reversed input.
                     If our input is ⍵, ⍺_1, ⍺_2, ..., ⍺_2n,
                     the reversed input will be ⍺_2n, ..., ⍺_1, ⍵.
                     The / operator applies the function right to left,
                     so the ⌽ is necessary.

```
> 4 votes

# Answer
## Python 2, 96 bytes

```
def f(m,v):
    for i,x in enumerate(v):x%=len(m);r=m[i/2];m[i/2]=r[-x:]+r[:-x];m=zip(*m)
    return m

```

*Tests*

`f` returns a list of tuples. Each line in the function body is indented with 1 tab character.
> 2 votes

# Answer
# Stax, 12 bytes

```
ÄBí•`»O╒┬g½ë

```

Run and debug it
> 0 votes

---
Tags: code-golf, array, matrix
---


# Question
Title: Print "beep boop bop" using complicated methods
This challenge is pretty simple: you need to alert / print / show to the user the text "beep boop bop" (or "beep\nboop\nbop", with newlines), but it needs to be obfuscated. (where you couldn't see anything saying "beep", "boop", or "bop"). Points are calculated where your point value is in **characters** (**not** bytes)

# Answer
> 1 votes
Bash, 16 bytes

```
echo b{ee,oo,o}p

```

# Answer
> 0 votes
# Perl 6, 21 bytes

```
put <bee boo bo>X~'p'

```

Try it online!

Prints all the words on one line by joining all the prefixes with the last letter `p`

---
Tags: code-golf, kolmogorov-complexity
---


title: Check if point lies inside triangle

text:
# Question
Title: Check if point lies inside triangle
Your goal is to determine whether a given 2D point X lies within the area of the triangle with given vertices A,B,C.

Write a function that takes in the coordinates of the test point X and the three triangle vertices (so that's 8 coordinates total) and returns True if the point lies inside that triangle, and False if it lies outside.

Don't worry about edge cases. If the point lies on the boundary of the triangle (edge or vertex) or the triangle is actually a line segment, your code can do whatever, including crashing. Also don't worry about numerical stability or floating-point precision.

Your code must be a named function. Code snippets will not be accepted.

Fewest characters wins.

**Input:**

Eight real numbers representing coordinates. The numbers will lie in the range `(-1,1)`.

The exact input format is flexible. You could, for example, take in eight numbers, a list of eight numbers, a list of four points each given by a tuple, a 2\*4 matrix, four complex numbers, two lists of the x-coordinates and y-coordinates, and so on.

The input needs to just be the numbers in some container, with no additional data. You can't use the input to do any preprocessing, nor may you require any constraints on the input, such as requiring the points be given in ascending y coordinate. Your input must allow any eight coordinates (though your code can behave arbitrarily in the edge cases mentioned earlier).

Please state your input format.

**Output:**

Either the corresponding Boolean `True`/`False`, the corresponding number `1`/`0`, or the analogues in your language.

**Test cases**

The inputs are given a list `[X,A,B,C]` of four tuples, the test point first, then the three triangle vertices. I've grouped them into those whose outputs should be `True` and those that should be `False`.

`True` instances:

```
[(-0.31961, -0.12646), (0.38478, 0.37419), (-0.30613, -0.59754), (-0.85548, 0.6633)]
[(-0.87427, -0.00831), (0.78829, 0.60409), (-0.90904, -0.13856), (-0.80685, 0.48468)]
[(0.28997, -0.03668), (-0.28362, 0.42831), (0.39332, -0.07474), (-0.48694, -0.10497)]
[(-0.07783, 0.04415), (-0.34355, -0.07161), (0.59105, -0.93145), (0.29402, 0.90334)]
[(0.36107, 0.05389), (0.27103, 0.47754), (-0.00341, -0.79472), (0.82549, -0.29028)]
[(-0.01655, -0.20437), (-0.36194, -0.90281), (-0.26515, -0.4172), (0.36181, 0.51683)]
[(-0.12198, -0.45897), (-0.35128, -0.85405), (0.84566, 0.99364), (0.13767, 0.78618)]
[(-0.03847, -0.81531), (-0.18704, -0.33282), (-0.95717, -0.6337), (0.10976, -0.88374)]
[(0.07904, -0.06245), (0.95181, -0.84223), (-0.75583, -0.34406), (0.16785, 0.87519)]
[(-0.33485, 0.53875), (-0.25173, 0.51317), (-0.62441, -0.90698), (-0.47925, 0.74832)]

```

`False` instances:

```
[(-0.99103, 0.43842), (0.78128, -0.10985), (-0.84714, -0.20558), (-0.08925, -0.78608)]
[(0.15087, -0.56212), (-0.87374, -0.3787), (0.86403, 0.60374), (0.01392, 0.84362)]
[(0.1114, 0.66496), (-0.92633, 0.27408), (0.92439, 0.43692), (0.8298, -0.29647)]
[(0.87786, -0.8594), (-0.42283, -0.97999), (0.58659, -0.327), (-0.22656, 0.80896)]
[(0.43525, -0.8923), (0.86119, 0.78278), (-0.01348, 0.98093), (-0.56244, -0.75129)]
[(-0.73365, 0.28332), (0.63263, 0.17177), (-0.38398, -0.43497), (-0.31123, 0.73168)]
[(-0.57694, -0.87713), (-0.93622, 0.89397), (0.93117, 0.40775), (0.2323, -0.30718)]
[(0.91059, 0.75966), (0.60118, 0.73186), (0.32178, 0.88296), (-0.90087, -0.26367)]
[(0.3463, -0.89397), (0.99108, 0.13557), (0.50122, -0.8724), (0.43385, 0.00167)]
[(0.88121, 0.36469), (-0.29829, 0.21429), (0.31395, 0.2734), (0.43267, -0.78192)]

```

# Answer
# Javascript / ECMAScript 6, 161 159 158 / 152

Javascript:

```
function $(t,r,i,a,n,g,l,e){b=(-g*l+a*(-n+l)+i*(g-e)+n*e)/2;c=b<0?-1:1;d=(a*l-i*e+(e-a)*t+(i-l)*r)*c;f=(i*g-a*n+(a-g)*t+(n-i)*r)*c;return d>0&&f>0&&d+f<2*b*c}

```

ECMAScript 6 version (thanks m.buettner, saves 6 characters)

```
$=(t,r,i,a,n,g,l,e)=>{b=(-g*l+a*(-n+l)+i*(g-e)+n*e)/2;c=b<0?-1:1;d=(a*l-i*e+(e-a)*t+(i-l)*r)*c;f=(i*g-a*n+(a-g)*t+(n-i)*r)*c;return d>0&&f>0&&d+f<2*b*c}

```

Call it as such (returns `true` or `false`):

```
$(pointX, pointY, v1X, v1Y, v2X, v2Y, v3X, v3Y);

```

Uses some fancy barycentric coordinate math based on code from this answer. An ungolfed version for your reading enjoyment follows:

```
function $ (pointX, pointY, v1X, v1Y, v2X, v2Y, v3X, v3Y) {
  var A =  (-v2Y * v3X + v1Y * (-v2X + v3X) + v1X * (v2Y - v3Y) + v2X * v3Y) / 2;
  var sign = A < 0 ? -1 : 1;
  var s = (v1Y * v3X - v1X * v3Y + (v3Y - v1Y) * pointX + (v1X - v3X) * pointY) * sign;
  var t = (v1X * v2Y - v1Y * v2X + (v1Y - v2Y) * pointX + (v2X - v1X) * pointY) * sign;
  return s > 0 && t > 0 && s + t < 2 * A * sign;
}

```
> 20 votes

# Answer
## Python 2.7 ~~128~~ ~~127~~ ~~117~~ ~~110~~ ~~109~~ ~~103~~ ~~99~~ ~~95~~ ~~94~~ ~~91~~ 90

My first code-golf attempt!

## Code

```
f=lambda x,y,t:sum(a*y+c*b+d*x<d*a+c*y+b*x for i in(0,1,2)for a,b,c,d in[t[i-1]+t[i]])%3<1

```

Takes as input (x,y,t) where (x,y) is the point we're checking and t is a triangle t = ((x1,y1),(x2,y2),(x3,y3)).

## Explanation

I'm calculating the determinants of the matrices

```
| 1 x1 y1 |      | 1 x2 y2 |      | 1 x3 y3 |
| 1 x2 y2 | ,    | 1 x3 y3 | ,    | 1 x1 y1 | .
| 1 x  y  |      | 1 x  y  |      | 1 x  y  |

```

These determinants represent the signed distances from the sides of the triangle to the point (x,y). If they all have the same sign, then the point is on the same side of every line and is thus contained in the triangle.

In the code above, `a*y+c*b+d*x-d*a-c*y-b*x` is a determinant of one of these matrices.

I'm using the fact that `True+True+True==3` and `False+False+False==0` to determine if these determinants all have the same sign.

I make use of Python's negative list indices by using `t[-1]` instead of `t[(i+1)%3]`.

Thanks Peter for the idea to use `s%3<1` instead of `s in(0,3)` to check if s is either 0 or 3!

## Sagemath Version

Not really a different solution so I'm including it in this answer, a sagemath solution using **80** characters:

```
f=lambda p,t,o=[1]:sum([det(Matrix([o+t[i-1],o+t[i],o+p]))<0for i in 0,1,2])%3<1

```

where `p=[x,y]`, and `t=[[x1,y1],[x2,y2],[x3,y3]]`
> 19 votes

# Answer
## Mathematica, 67 bytes

```
f=Equal@@({#2,-#}&@@(#-#2).(x-#)>0&@@@Partition[x=#;#2,2,1,{1,1}])&

```

The function takes two arguments, the point `X` and a list of points `{A,B,C}`, which are referred to as `#` and `#2` respectively. That is if you call

```
f[X,{A,B,C}]

```

then you'll get `#` as `X` and `#2` as `{A,B,C}`. (Note that there are two other anonymous functions nested inside the code - `#` and `#2` have a different meaning within those.)

Here is an explanation of the function itself:

```
                                              x=#;#2            & (* Save X into a variable x, but evaluate to {A,B,C}. *)
                                    Partition[x=#;#2,2,1,{1,1}] & (* Get a cyclic list of pairs {{A,B},{B,C},{C,B}}. *)
       (                        &@@@Partition[x=#;#2,2,1,{1,1}])& (* Define an anonymous function and apply it to each
                                                                     of the above pairs. The two elements are referred
                                                                     to as # and #2. *)
       (          (#-#2)        &@@@Partition[x=#;#2,2,1,{1,1}])& (* Subtract the two points. For a pair of vertices
                                                                     this yields a vector corresponding to the edge
                                                                     between them. *)
        {#2,-#}&                                                  (* An anonymous function that takes two values,
                                                                     reverses them, inverts the sign of one of them
                                                                     and puts them into a list. *)
       ({#2,-#}&@@(#-#2)        &@@@Partition[x=#;#2,2,1,{1,1}])& (* Applied to the edge, this yields its normal. *)
       ({#2,-#}&@@(#-#2).(x-#)  &@@@Partition[x=#;#2,2,1,{1,1}])& (* Take the scalar product of that normal with a
                                                                     vector from a vertex to x. This is projection of
                                                                     this vector onto that normal and hence the SIGNED
                                                                     distance of x from the edge. *)
       ({#2,-#}&@@(#-#2).(x-#)>0&@@@Partition[x=#;#2,2,1,{1,1}])& (* Check the sign of that distance, the exact mapping
                                                                     between (left, right) and (True, False) is
                                                                     irrelevant, as long as it's consistent. *)
Equal@@({#2,-#}&@@(#-#2).(x-#)>0&@@@Partition[x=#;#2,2,1,{1,1}])& (* Check if all signs are equal - that is, if point X
                                                                     lies on the same side of all edges. This is
                                                                     equivalent to check that the point is inside the
                                                                     triangle. *)

```

Note that this function will actually work for *any* convex n-gon as long as its vertices are given in either clockwise or counter-clockwise order.
> 16 votes

# Answer
# CJam, ~~66~~ ~~63~~ ~~59~~ ~~52~~ ~~46~~ ~~34~~ ~~32~~ ~~31~~ ~~30~~ 28 characters

```
"Ă䒟损崙㩴ァ椟饃꿾藭鑭蘁"2G#b131b:c~

```

After transforming the Unicode string, the following code (**33 bytes**) gets evaluated:

```
{2*2/\f{f{+~@-@@-}~@@*@@*>})-!}:T

```

Expects `X [A B C]` as input, where each point is of the form `[double double]`. Output is 1 or 0.

Try it online.

A big thank you goes to user23013 for saving 6 characters (13 bytes of uncompressed code)!

### Test cases

```
$ cat triangle.cjam
"Ă䒟损崙㩴ァ椟饃꿾藭鑭蘁"2G#b131b:c~

[
  [-0.31961 -0.12646] [ [0.38478 0.37419]   [-0.30613 -0.59754] [-0.85548 0.6633]   ] T
  [-0.87427 -0.00831] [ [0.78829 0.60409]   [-0.90904 -0.13856] [-0.80685 0.48468]  ] T
  [0.28997 -0.03668]  [ [-0.28362 0.42831]  [0.39332 -0.07474]  [-0.48694 -0.10497] ] T
  [-0.07783 0.04415]  [ [-0.34355 -0.07161] [0.59105 -0.93145]  [0.29402 0.90334]   ] T
  [0.36107 0.05389]   [ [0.27103 0.47754]   [-0.00341 -0.79472] [0.82549 -0.29028]  ] T
  [-0.01655 -0.20437] [ [-0.36194 -0.90281] [-0.26515 -0.4172]  [0.36181 0.51683]   ] T
  [-0.12198 -0.45897] [ [-0.35128 -0.85405] [0.84566 0.99364]   [0.13767 0.78618]   ] T
  [-0.03847 -0.81531] [ [-0.18704 -0.33282] [-0.95717 -0.6337]  [0.10976 -0.88374]  ] T
  [0.07904 -0.06245]  [ [0.95181 -0.84223]  [-0.75583 -0.34406] [0.16785 0.87519]   ] T
  [-0.33485 0.53875]  [ [-0.25173 0.51317]  [-0.62441 -0.90698] [-0.47925 0.74832]  ] T
  [-0.99103 0.43842]  [ [0.78128 -0.10985]  [-0.84714 -0.20558] [-0.08925 -0.78608] ] T
  [0.15087 -0.56212]  [ [-0.87374 -0.3787]  [0.86403 0.60374]   [0.01392 0.84362]   ] T
  [0.1114 0.66496]    [ [-0.92633 0.27408]  [0.92439 0.43692]   [0.8298 -0.29647]   ] T
  [0.87786 -0.8594]   [ [-0.42283 -0.97999] [0.58659 -0.327]    [-0.22656 0.80896]  ] T
  [0.43525 -0.8923]   [ [0.86119 0.78278]   [-0.01348 0.98093]  [-0.56244 -0.75129] ] T
  [-0.73365 0.28332]  [ [0.63263 0.17177]   [-0.38398 -0.43497] [-0.31123 0.73168]  ] T
  [-0.57694 -0.87713] [ [-0.93622 0.89397]  [0.93117 0.40775]   [0.2323 -0.30718]   ] T
  [0.91059 0.75966]   [ [0.60118 0.73186]   [0.32178 0.88296]   [-0.90087 -0.26367] ] T
  [0.3463 -0.89397]   [ [0.99108 0.13557]   [0.50122 -0.8724]   [0.43385 0.00167]   ] T
  [0.88121 0.36469]   [ [-0.29829 0.21429]  [0.31395 0.2734]    [0.43267 -0.78192]  ] T
]p;

$ cjam triangle.cjam
[1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0]

```
> 7 votes

# Answer
# C – 156 bytes

Input are array of 3 floats in X, 3 floats in Y and separate x and y for the test point. Bonus: handles all edge cases!

```
int f(float*X,float*Y,float x,float y){int i,j,c=0;for(i=0,j=2;i<3;j=i++)if(((Y[i]>y)!=(Y[j]>y))&&(x<(X[j]-X[i])*(y-Y[i])/(Y[j]-Y[i])+X[i]))c=!c;return c;}

```

Adapted from PNPOLY.
> 5 votes

# Answer
# Pyth 1.0.5, 57 54 51

```
DgYb=Z0J'bWbK;bDiHNR*-'H'K-@N1@K1~Z>iYJiJY=JK)R!%Z3

```

Defines the function g, which takes two inputs: the test point, and then the list of the vertices of the triangle. Outputs `True` and `False`. Note: Destroys the input, specifically b, the list of the vertices of the triangle.

Try it here. The last few characters, `gvwvw` call the function with a test case on the next two lines.

Based on this algorithm

Explanation:

```
DgYb                  Define g(Y,b):
=Z0                     Z=0
J'b                     J=b[0]              (No = is needed because j is special).
Wb                      While len(b)>0:     (While b:)
K;b                       K=b.pop()
DiHN                      Define i(H,N):
R*-'H'K-@N1@K1              Return half of the linked equation.
~ZiYJiJY                  Z+=i(Y,J)>i(J,Y)
=JK                       J=K
)                       Wend
R!%Z3                   return not Z%3==0   (True iff Z == 0 or 3)

```

The CJam - Pyth war rages on!
> 4 votes

# Answer
# J 64 45 (42 without assignment)

```
c=:*./@(>:&0)@({.(,(1-+/))@%.|:@}.)@(}:-"1{:)

```

The assignment is not necessary for the thing to be a function, so unsure whether to count it or not. Taking advantage of the flexible input: I'd like to have an array of (1 + number of vertices) x (dimensionality of the space).

Hoping to score some extra points here ... : This thing works for any dimension of simplex, not just triangles in a plane, but also a 3 sided pyramid in 3d space and so on. It also works when the number of vertices of the simplex is smaller than (n+1), then it computes whether the projection of the point onto the simplex is inside or not.

It converts to barycentric coordinates, then checks for negative ones, indicating the point is outside. Do mind J uses _ for negative

```
NB. example in triangle
D =: 4 2 $ 1 1 0 0 3 0 0 2 NB. 4 rows , x first, then the vertices of the triangle

NB. subtract last vertex coordinates from the rest and drop reference node
n=: (}:-"1{:)

NB. preprocessed to barycentric coordinates
bar=: {. (, 1 - +/)@%. |:@}.

NB. all positive
ap =: *./@(>:&0)

insided =: ap@bar@n

inside D
1

```

A run on the given examples:

```
   true =: 0 : 0
[(-0.31961, -0.12646), (0.38478, 0.37419), (-0.30613, -0.59754), (-0.85548, 0.6633)]
[(-0.87427, -0.00831), (0.78829, 0.60409), (-0.90904, -0.13856), (-0.80685, 0.48468)]
[(0.28997, -0.03668), (-0.28362, 0.42831), (0.39332, -0.07474), (-0.48694, -0.10497)]
[(-0.07783, 0.04415), (-0.34355, -0.07161), (0.59105, -0.93145), (0.29402, 0.90334)]
[(0.36107, 0.05389), (0.27103, 0.47754), (-0.00341, -0.79472), (0.82549, -0.29028)]
[(-0.01655, -0.20437), (-0.36194, -0.90281), (-0.26515, -0.4172), (0.36181, 0.51683)]
[(-0.12198, -0.45897), (-0.35128, -0.85405), (0.84566, 0.99364), (0.13767, 0.78618)]
[(-0.03847, -0.81531), (-0.18704, -0.33282), (-0.95717, -0.6337), (0.10976, -0.88374)]
[(0.07904, -0.06245), (0.95181, -0.84223), (-0.75583, -0.34406), (0.16785, 0.87519)]
[(-0.33485, 0.53875), (-0.25173, 0.51317), (-0.62441, -0.90698), (-0.47925, 0.74832)]
)

   false =: 0 : 0
[(-0.99103, 0.43842), (0.78128, -0.10985), (-0.84714, -0.20558), (-0.08925, -0.78608)]
[(0.15087, -0.56212), (-0.87374, -0.3787), (0.86403, 0.60374), (0.01392, 0.84362)]
[(0.1114, 0.66496), (-0.92633, 0.27408), (0.92439, 0.43692), (0.8298, -0.29647)]
[(0.87786, -0.8594), (-0.42283, -0.97999), (0.58659, -0.327), (-0.22656, 0.80896)]
[(0.43525, -0.8923), (0.86119, 0.78278), (-0.01348, 0.98093), (-0.56244, -0.75129)]
[(-0.73365, 0.28332), (0.63263, 0.17177), (-0.38398, -0.43497), (-0.31123, 0.73168)]
[(-0.57694, -0.87713), (-0.93622, 0.89397), (0.93117, 0.40775), (0.2323, -0.30718)]
[(0.91059, 0.75966), (0.60118, 0.73186), (0.32178, 0.88296), (-0.90087, -0.26367)]
[(0.3463, -0.89397), (0.99108, 0.13557), (0.50122, -0.8724), (0.43385, 0.00167)]
[(0.88121, 0.36469), (-0.29829, 0.21429), (0.31395, 0.2734), (0.43267, -0.78192)]
)
   NB. replace - by _ to avoid problems
   NB. cut up per row, drop the [ ] and convert to numbers
   $dat_t =: ((4 2 $ ".)@}:@}.;._2) (true='-')} true ,: '_'
10 4 2
   $dat_f =: ((4 2 $ ".)@}:@}.;._2) (false='-')}false,: '_'
10 4 2
   NB. this results in arrays with shape 10 4 2

   NB. for each 4 x 2 array (rank 2), do c for all true instances
   c=:*./@(>:&0)@({.(,(1-+/))@%.|:@}.)@(}:-"1{:)
   c"2 dat_t
1 1 1 1 1 1 1 1 1 1
   NB. the same for the false ones, demonstrating anonymous usage
   NB. still a function though (or verb in J parlance)
   *./@(>:&0)@({.(,(1-+/))@%.|:@}.)@(}:-"1{:)"2 dat_f
0 0 0 0 0 0 0 0 0 0

```
> 4 votes

# Answer
## HTML5 + JS, 13b + 146b / 141b / 114 chars

HTML:

```
<canvas id=C>

```

JS (146b):

```
// @params: t1x, t1y, t2x, t2y, t3x, t3y, pointx, pointy
function T(a,b,c,d,e,f,g,h){with(C.getContext("2d"))return beginPath(),moveTo(a,b),lineTo(c,d),lineTo(e,f),fill(),!!getImageData(g,h,1,1).data[3]}

```

or ES6 (141b):

```
T=(a,b,c,d,e,f,g,h)=>{with(C.getContext("2d"))return beginPath(),moveTo(a,b),lineTo(c,d),lineTo(e,f),fill(),!!getImageData(g,h,1,1).data[3]}

```

or ES6 unicode-obfuscated (114 chars):

```
eval(unescape(escape('').replace(/uD./g,'')))

```

demo: http://jsfiddle.net/xH8mV/

Unicode obfuscation made with: http://xem.github.io/obfuscatweet/
> 4 votes

# Answer
# Python (65)

People seem to be done submitting, so I'll post my own solution to my question.

```
f=lambda X,L:sum(((L[i-1]-X)/(L[i]-X)).imag>0for i in(0,1,2))%3<1

```

`X` is the complex number representing the test points, and `L` is a list of three points, each a complex number.

First, I'll explain a less golfed version of the code;

```
def f(X,A,B,C):A-=X;B-=X;C-=X;return((A/B).imag>0)==((B/C).imag>0)==((C/A).imag>0)

```

We shift the points `A,B,C,X` so that `X` is at the origin, taking advantage of Python's built-in complex arithmetic. We need to check if the origin is contained in the convex hull of `A,B,C`. This is equivalent to the origin always lying on the same side (left or right) of the line segments AB, BC, and AC.

A segment `AB` has the origin on the left if one travel counterclockwise less than 180 degrees to get from A to B, and on the right otherwise. If we consider the angles `a`, `b`, and `c` corresponding to these points, this means `b-a < 180 degrees` (taken angles in the range 0 to 360 degrees). As complex numbers, `angle(B/A)=angle(B)/angle(A)`. Also, `angle(x) < 180 degrees` exactly for point in he upper half-plane, which we check via `imag(x)>0`.

So whether the origin lies to the left of AB is expressed as `(A/B).imag>0`. Checking whether these are all equal for each cyclic pair in `A,B,C` tells us whether triangle `ABC` contains the origin.

Now, let's return to the fully golfed code

```
f=lambda X,L:sum(((L[i-1]-X)/(L[i]-X)).imag>0for i in(0,1,2))%3<1

```

We generate each cyclic pair in `(A-X,B-X,C-X)=(L[0]-X,L[1]-X,L[2]-X)`, taking advantage of negative Python list indices wrapping around (`L[-1]` = `L[2]`). To check that the Bools are all `True` (`1`) or all `False` (`0`), we add them and check divisibility by 3, as many solutions did.
> 3 votes

# Answer
# Fortran - ~~232~~ ~~218~~ ~~195~~ 174

Bloody awful. The function is horrendous because of the requirement that the data is passed to it and we cannot preprocess it.

```
logical function L(x);real::x(8);p=x(1)-x(3);q=x(2)-x(4);r=x(5)-x(3);s=x(6)-x(4);t=x(7)-x(3);u=x(8)-x(4);L=ALL([p*(s-u)+q*(t-r)+r*u-t*s,p*u-q*t,q*r-p*s]>=r*u-t*s);endfunction

```

The decrease of 14 characters is because I forgot to golf the function name from my test runs. The further decrease is due to implicit typing and forgetting to change the function name. The next 20 characters came off due to reading in the points as a single array. The full program is

```
program inTriagle
   real, dimension(2) :: a,b,c,x
   do
      print*,"Enter coordinates as x,a,b,c"
      read*,x,a,b,c
      if(all(x==0.0).and.all(a==0.0).and.all(b==0.0).and.all(c==0.0)) exit
      print*,"Is point in triangle: ",T(x,a,b,c)
   enddo
 contains!
   logical function L(x)
     real::x(8)
     p=x(1)-x(3);q=x(2)-x(4);r=x(5)-x(3)
     s=x(6)-x(4);t=x(7)-x(3);u=x(8)-x(4)
     L=ALL([p*(s-u)+q*(t-r)+r*u-t*s,p*u-q*t,q*r-p*s]>=r*u-t*s)
   endfunction
end program inTriagle

```
> 2 votes

# Answer
# C# 218 (149?)

```
using P=System.Drawing.PointF;
bool F(P[]p){for(int i=0;i<4;i++){p[i].X*=1e7f;p[i].Y*=1e7f;}P[]a=new P[3];Array.Copy(p,1,a,0,3);var g=new System.Drawing.Drawing2D.GraphicsPath();g.AddLines(a);return g.IsVisible(p[0]);}

```

Probably not as character-efficient as a mathematical method, but it's a fun use of libraries. Incidentally, also rather slow.

Also taking advantage of "Also don't worry about numerical stability or floating-point precision." - unfortunately, `GraphicsPath` uses `int`s internally, so a value in the range -1 \< f \< 1 can only have three possible values. Since floats only have 7 digits of precision, I just multiply by 1e7 to turn them into whole numbers. Hm, I guess it's not really *losing* any precision. It's also exploitable in another way: I probably could have taken advantage of ignoring precision and just given the "wrong" answer.

*If* I'm allowed to ignore the character cost of importing libraries, **149** (at the very least, `System.Linq` and `System.Drawing` are pretty standard on most WinForms projects, but `System.Drawing.Drawing2D` might be a bit of a stretch):

```
bool G(PointF[]p){for(int i=0;i<4;i++){p[i].X*=1e7f;p[i].Y*=1e7f;}var g=new GraphicsPath();g.AddLines(p.Skip(1).ToArray());return g.IsVisible(p[0]);}

```

Test program (yea, it's ugly):

```
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using P=System.Drawing.PointF;
using System.Linq;

class Program
{
    static void Main(string[] args)
    {
        Program prog = new Program();
        foreach (string test in
@"[(-0.31961, -0.12646), (0.38478, 0.37419), (-0.30613, -0.59754), (-0.85548, 0.6633)]
[(-0.87427, -0.00831), (0.78829, 0.60409), (-0.90904, -0.13856), (-0.80685, 0.48468)]
[(0.28997, -0.03668), (-0.28362, 0.42831), (0.39332, -0.07474), (-0.48694, -0.10497)]
[(-0.07783, 0.04415), (-0.34355, -0.07161), (0.59105, -0.93145), (0.29402, 0.90334)]
[(0.36107, 0.05389), (0.27103, 0.47754), (-0.00341, -0.79472), (0.82549, -0.29028)]
[(-0.01655, -0.20437), (-0.36194, -0.90281), (-0.26515, -0.4172), (0.36181, 0.51683)]
[(-0.12198, -0.45897), (-0.35128, -0.85405), (0.84566, 0.99364), (0.13767, 0.78618)]
[(-0.03847, -0.81531), (-0.18704, -0.33282), (-0.95717, -0.6337), (0.10976, -0.88374)]
[(0.07904, -0.06245), (0.95181, -0.84223), (-0.75583, -0.34406), (0.16785, 0.87519)]
[(-0.33485, 0.53875), (-0.25173, 0.51317), (-0.62441, -0.90698), (-0.47925, 0.74832)]
[(-0.99103, 0.43842), (0.78128, -0.10985), (-0.84714, -0.20558), (-0.08925, -0.78608)]
[(0.15087, -0.56212), (-0.87374, -0.3787), (0.86403, 0.60374), (0.01392, 0.84362)]
[(0.1114, 0.66496), (-0.92633, 0.27408), (0.92439, 0.43692), (0.8298, -0.29647)]
[(0.87786, -0.8594), (-0.42283, -0.97999), (0.58659, -0.327), (-0.22656, 0.80896)]
[(0.43525, -0.8923), (0.86119, 0.78278), (-0.01348, 0.98093), (-0.56244, -0.75129)]
[(-0.73365, 0.28332), (0.63263, 0.17177), (-0.38398, -0.43497), (-0.31123, 0.73168)]
[(-0.57694, -0.87713), (-0.93622, 0.89397), (0.93117, 0.40775), (0.2323, -0.30718)]
[(0.91059, 0.75966), (0.60118, 0.73186), (0.32178, 0.88296), (-0.90087, -0.26367)]
[(0.3463, -0.89397), (0.99108, 0.13557), (0.50122, -0.8724), (0.43385, 0.00167)]
[(0.88121, 0.36469), (-0.29829, 0.21429), (0.31395, 0.2734), (0.43267, -0.78192)]".Split('\n'))
        {
            string t = test.Replace("[(", "").Replace(")]", "");
            string[] points = t.Split(new string[] { "), (" }, StringSplitOptions.None);

            string[] p = points[0].Split(',');
            P[] xabc = new P[4];

            for (int i = 0; i < 4; i++)
            {
                p = points[i].Split(',');
                xabc[i] = new F(float.Parse(p[0]), float.Parse(p[1]));
            }

            Console.WriteLine(test + "=>" + prog.F(xabc));
        }

        Console.ReadKey();
    }

    bool G(PointF[]p)
    {
        for(int i=0;i<4;i++){p[i].X*=1e7f;p[i].Y*=1e7f;}
        var g=new GraphicsPath();
        g.AddLines(p.Skip(1).ToArray());
        return g.IsVisible(p[0]);
    }

    bool F(P[]p)
    {
        for(int i=0;i<4;i++){p[i].X*=1e7f;p[i].Y*=1e7f;}
        var g=new System.Drawing.Drawing2D.GraphicsPath();
        g.AddLines(p.Skip(1).ToArray());
        return g.IsVisible(p[0]);
    }
}

```
> 2 votes

# Answer
# MATLAB: 9!

Not a whole lot of me to write here

```
inpolygon

```

Can be called like so:

```
inpolygon(2/3, 2/3, [0 1 1], [0 0 1])

```

Output is assigned to a variable named `ans`

---

If I actually had to write a function, it may be something like so, could probably be optimized:

```
function y=f(a,b,c,d)
inpolygon(a,b,c,d)

```
> 2 votes

# Answer
### Haskell — ~~233~~ 127

Using cross products as described here:

```
h(a,b)(p,q)(r,s)(t,u)=z a b p q r s==z a b r s t u&&z a b r s t u==z a b t u p q where z j k l m n o =(o-m)*(j-l)+(l-n)*(k-m)>0

```

Previous solution implemented using barycentric coordinates and the formulae described in this Stack Exchange answer:

```
g(p,q)(r,s)(t,u)(v,w)=
 let (j,k)=(p+(-r),q+(-s))
     (l,m)=(t+(-r),u+(-s))
     (n,o)=(v+(-r),w+(-s))
     d=l*o-n*m
     a=(j*(m-o)+k*(n-l)+l*o-n*m)/d
     b=(j*o-k*n)/d
     c=(k*l-j*m)/d
 in (0<=a&&a<1)&&(0<=b&&b<1)&&(0<=c&&c<1)

```

Both functions `g` and `h` take four pairs, the first of which is the point to be tested for inclusion and the rest being the coordinates of the vertices of the triangle.

To test with the sample input:

```
let trueTestCases =
  [((-0.31961, -0.12646), (0.38478, 0.37419), (-0.30613, -0.59754), (-0.85548, 0.6633)),
   ((-0.87427, -0.00831), (0.78829, 0.60409), (-0.90904, -0.13856), (-0.80685, 0.48468)),
   ((0.28997, -0.03668), (-0.28362, 0.42831), (0.39332, -0.07474), (-0.48694, -0.10497)),
   ((-0.07783, 0.04415), (-0.34355, -0.07161), (0.59105, -0.93145), (0.29402, 0.90334)),
   ((0.36107, 0.05389), (0.27103, 0.47754), (-0.00341, -0.79472), (0.82549, -0.29028)),
   ((-0.01655, -0.20437), (-0.36194, -0.90281), (-0.26515, -0.4172), (0.36181, 0.51683)),
   ((-0.12198, -0.45897), (-0.35128, -0.85405), (0.84566, 0.99364), (0.13767, 0.78618)),
   ((-0.03847, -0.81531), (-0.18704, -0.33282), (-0.95717, -0.6337), (0.10976, -0.88374)),
   ((0.07904, -0.06245), (0.95181, -0.84223), (-0.75583, -0.34406), (0.16785, 0.87519)),
   ((-0.33485, 0.53875), (-0.25173, 0.51317), (-0.62441, -0.90698), (-0.47925, 0.74832))]

let falseTestCases =
  [((-0.99103, 0.43842), (0.78128, -0.10985), (-0.84714, -0.20558), (-0.08925, -0.78608)),
   ((0.15087, -0.56212), (-0.87374, -0.3787), (0.86403, 0.60374), (0.01392, 0.84362)),
   ((0.1114, 0.66496), (-0.92633, 0.27408), (0.92439, 0.43692), (0.8298, -0.29647)),
   ((0.87786, -0.8594), (-0.42283, -0.97999), (0.58659, -0.327), (-0.22656, 0.80896)),
   ((0.43525, -0.8923), (0.86119, 0.78278), (-0.01348, 0.98093), (-0.56244, -0.75129)),
   ((-0.73365, 0.28332), (0.63263, 0.17177), (-0.38398, -0.43497), (-0.31123, 0.73168)),
   ((-0.57694, -0.87713), (-0.93622, 0.89397), (0.93117, 0.40775), (0.2323, -0.30718)),
   ((0.91059, 0.75966), (0.60118, 0.73186), (0.32178, 0.88296), (-0.90087, -0.26367)),
   ((0.3463, -0.89397), (0.99108, 0.13557), (0.50122, -0.8724), (0.43385, 0.00167)),
   ((0.88121, 0.36469), (-0.29829, 0.21429), (0.31395, 0.2734), (0.43267, -0.78192))]

type Point = (Double, Double)

test :: [(Point, Point, Point, Point)] -> [Bool]
test testCases =
  map (\((px,py),(ax,ay),(bx,by),(cx,cy)) -> h (px,py) (ax,ay) (bx,by) (cx,cy)) testCases

test trueTestCases --> [True,True,True,True,True,True,True,True,True,True]
test falseTestCases --> [False,False,False,False,False,False,False,False,False,False]

```

Ungolfed solutions:

```
type Point = (Double, Double)

-- using cross products

triangulate' (a, b) (p, q) (r, s) (t, u) =
  (side a b p q r s == side a b r s t u) && (side a b r s t u == side a b t u p q)
  where side j k l m n o = (o - m) * (j - l) + (-n + l) * (k - m) >= 0

-- using barycentric coordinates

triangulate :: (Point, Point, Point, Point) -> Bool
triangulate ((px, py), (ax, ay), (bx, by), (cx, cy)) =
  let (p'x, p'y) = (px + (-ax), py + (-ay))
      (b'x, b'y) = (bx + (-ax), by + (-ay))
      (c'x, c'y) = (cx + (-ax), cy + (-ay))
      d = b'x * c'y - c'x * b'y
      a = (p'x * (b'y - c'y) + p'y * (c'x - b'x) + b'x * c'y - c'x * b'y) / d
      b = (p'x * c'y - p'y * c'x) / d
      c = (p'y * b'x - p'x * b'y) / d
  in
      (0 <= a && a < 1) && (0 <= b && b < 1) && (0 <= c && c < 1)

```
> 2 votes

# Answer
# JavaScript (ES6) 120

```
C=(p,q,i,j,k,l,m,n,
 z=j*(m-k)+i*(l-n)+k*n-l*m,
 s=(j*m-i*n+(n-j)*p+(i-m)*q)/z,
 t=(i*l-j*k+(j-l)*p+(k-i)*q)/z
)=>s>0&t>0&s+t<1

```

Directly copied from my answer to This other question

**Test** In FireFox/FireBug console

*Output* all 1s

```
;[
C(-0.31961, -0.12646, 0.38478, 0.37419, -0.30613, -0.59754, -0.85548, 0.6633),
C(-0.87427, -0.00831, 0.78829, 0.60409, -0.90904, -0.13856, -0.80685, 0.48468),
C(0.28997, -0.03668, -0.28362, 0.42831, 0.39332, -0.07474, -0.48694, -0.10497),
C(-0.07783, 0.04415, -0.34355, -0.07161, 0.59105, -0.93145, 0.29402, 0.90334),
C(0.36107, 0.05389, 0.27103, 0.47754, -0.00341, -0.79472, 0.82549, -0.29028),
C(-0.01655, -0.20437, -0.36194, -0.90281, -0.26515, -0.4172, 0.36181, 0.51683),
C(-0.12198, -0.45897, -0.35128, -0.85405, 0.84566, 0.99364, 0.13767, 0.78618),
C(-0.03847, -0.81531, -0.18704, -0.33282, -0.95717, -0.6337, 0.10976, -0.88374),
C(0.07904, -0.06245, 0.95181, -0.84223, -0.75583, -0.34406, 0.16785, 0.87519),
C(-0.33485, 0.53875, -0.25173, 0.51317, -0.62441, -0.90698, -0.47925, 0.74832)
]

```

*Output* all 0s

```
;[
C(-0.99103, 0.43842,0.78128, -0.10985,-0.84714, -0.20558,-0.08925, -0.78608),
C(0.15087, -0.56212,-0.87374, -0.3787,0.86403, 0.60374,0.01392, 0.84362),
C(0.1114, 0.66496,-0.92633, 0.27408,0.92439, 0.43692,0.8298, -0.29647),
C(0.87786, -0.8594,-0.42283, -0.97999,0.58659, -0.327,-0.22656, 0.80896),
C(0.43525, -0.8923,0.86119, 0.78278,-0.01348, 0.98093,-0.56244, -0.75129),
C(-0.73365, 0.28332,0.63263, 0.17177,-0.38398, -0.43497,-0.31123, 0.73168),
C(-0.57694, -0.87713,-0.93622, 0.89397,0.93117, 0.40775,0.2323, -0.30718),
C(0.91059, 0.75966,0.60118, 0.73186,0.32178, 0.88296,-0.90087, -0.26367),
C(0.3463, -0.89397,0.99108, 0.13557,0.50122, -0.8724,0.43385, 0.00167),
C(0.88121, 0.36469,-0.29829, 0.21429,0.31395, 0.2734,0.43267, -0.78192)
]

```
> 2 votes

# Answer
# SmileBASIC, ~~111~~ 100 characters

```
DEF T X,Y,A,B,C,D,E,F
Q=9e5GCLS
GTRI(A-X)*Q,Q*(B-Y),Q*(C-X),Q*(D-Y),Q*(E-X),Q*(F-Y)?!!GSPOIT(0,0)END

```

Draws a triangle and checks the color of the pixel at the point. The triangle is scaled up 99999x and shifted so that the point to check will be at (0,0) before being drawn, to minimize loss in precision.
> 2 votes

# Answer
# Intel 8087 FPU assembly, ~~222~~ 220 bytes

Uses only the 8087 FPU hardware to calculate. Here is the unassembled (ungolfed in this case too) version as a MACRO (will spare you the 220 hex byte codes):

```
; calculate the area of of a triangle ABC using determinate
; input: coordinates (float), Ax,Ay,Bx,By,Cx,Cy
; output: area in ST
TAREA   MACRO   A1,A2,B1,B2,C1,C2
    FLD  A1
    FLD  B2
    FLD  C2
    FSUB        ; ST = By - Cy
    FMUL        ; ST = Ax * ( By - Cy )
    FLD  B1
    FLD  C2
    FLD  A2
    FSUB        ; ST = Cy - Ay
    FMUL        ; ST = Bx * ( Cy - Ay )
    FLD  C1
    FLD  A2
    FLD  B2
    FSUB        ; Ay - By
    FMUL        ; Cx * ( Ay - By )
    FADD        ; Cx * ( Ay - By ) + Bx * ( Cy - Ay )
    FADD        ; Cx * ( Ay - By ) + Bx * ( Cy - Ay ) + Ax * ( By - Cy )
    FLD1        ; make a value of 2
    FADD ST,ST  ; ST = 2
    FDIV        ; divide by 2
    FABS        ; take abs value
        ENDM

; determine if point X is in triangle ABC
; input: points X, A, B, C
; output: ZF=1 if X in triangle, ZF=0 if X not in triangle
TXINABC     MACRO X1,X2,A1,A2,B1,B2,C1,C2

    TAREA  A1,A2,B1,B2,C1,C2    ; ST(3) = area of triangle ABC
    TAREA  X1,X2,B1,B2,C1,C2    ; ST(2) = area of triangle XBC
    TAREA  A1,A2,X1,X2,C1,C2    ; ST(1) = area of triangle AXC
    TAREA  A1,A2,B1,B2,X1,X2    ; ST(0) = area of triangle ABX

    FADD        ; add areas of triangles with point
    FADD        ; ST = ST + ST(1) + ST(2)
    FCOMPP      ; compare ST to ST(1) and pop results
    FWAIT       ; sync CPU/FPU
    FSTSW R     ; store result flags to R
    MOV  AX, R  ; move result to AX
    SAHF        ; store result into CPU flags for conditional check
        ENDM

```

## Explanation

Uses the determinate to calculate the area of the ABC triangle, and then the triangle formed with the X point and two other points of the ABC triangle. If the area of triangle ABC equals the sum of areas of triangles XBC + AXC + ABX, then the point is within the triangle. The result is returned as ZF.

### What's neat about this

All of the math and floating point operations are done in hardware with 80-bit extended precision. The final floating point comparison is also done in hardware so will be very accurate.

This also uses all eight of the 8087's stack registers at once.

### What's not quite as neat about this

As the points of the triangle must be plugged back into the formulas several times during the calculation, it requires each variable in memory to be loaded into the FPU's stack registers one at a time in the correct order. While this can be fairly easily modeled like a function as a MACRO, it means that the code is expanded each time at assembly, creating redundant code. 41 bytes were saved by moving some of the same repeated code segments into PROCs. However it makes the code less readable, so the above listing is without it (which is why it's labeled as "ungolfed").

## Tests

Here is a test program using IBM DOS showing output:

```
TTEST   MACRO T
        LOCAL IS_IN_TRI

    TXINABC T,T+4*1,T+4*2,T+4*3,T+4*4,T+4*5,T+4*6,T+4*7
    MOV  DX, OFFSET TEQ     ; load true string by default
    JZ   IS_IN_TRI          ; if ZF=1, it is in triangle, skip to display
    MOV  DX, OFFSET FEQ     ; otherwise ZF=0 means not in triangle, so load false string
IS_IN_TRI:
    MOV  AH, 9              ; DOS write string function
    INT  21H
        ENDM

START:
    FINIT                   ; reset 8087

    TTEST   T0              ; true tests
    TTEST   T1
    TTEST   T2
    TTEST   T3
    TTEST   T4
    TTEST   T5
    TTEST   T6
    TTEST   T7
    TTEST   T8
    TTEST   T9

    TTEST   F0              ; false tests
    TTEST   F1
    TTEST   F2
    TTEST   F3
    TTEST   F4
    TTEST   F5
    TTEST   F6
    TTEST   F7
    TTEST   F8
    TTEST   F9

    RET         ; return to DOS

T0  DD  -0.31961, -0.12646, 0.38478, 0.37419, -0.30613, -0.59754, -0.85548, 0.6633
T1  DD  -0.87427, -0.00831, 0.78829, 0.60409, -0.90904, -0.13856, -0.80685, 0.48468
T2  DD  0.28997, -0.03668, -0.28362, 0.42831, 0.39332, -0.07474, -0.48694, -0.10497
T3  DD  -0.07783, 0.04415, -0.34355, -0.07161, 0.59105, -0.93145, 0.29402, 0.90334
T4  DD  0.36107, 0.05389, 0.27103, 0.47754, -0.00341, -0.79472, 0.82549, -0.29028
T5  DD  -0.01655, -0.20437, -0.36194, -0.90281, -0.26515, -0.4172, 0.36181, 0.51683
T6  DD  -0.12198, -0.45897, -0.35128, -0.85405, 0.84566, 0.99364, 0.13767, 0.78618
T7  DD  -0.03847, -0.81531, -0.18704, -0.33282, -0.95717, -0.6337, 0.10976, -0.88374
T8  DD  0.07904, -0.06245, 0.95181, -0.84223, -0.75583, -0.34406, 0.16785, 0.87519
T9  DD  -0.33485, 0.53875, -0.25173, 0.51317, -0.62441, -0.90698, -0.47925, 0.74832

F0  DD  -0.99103, 0.43842, 0.78128, -0.10985, -0.84714, -0.20558, -0.08925, -0.78608
F1  DD  0.15087, -0.56212, -0.87374, -0.3787, 0.86403, 0.60374, 0.01392, 0.84362
F2  DD  0.1114, 0.66496, -0.92633, 0.27408, 0.92439, 0.43692, 0.8298, -0.29647
F3  DD  0.87786, -0.8594, -0.42283, -0.97999, 0.58659, -0.327, -0.22656, 0.80896
F4  DD  0.43525, -0.8923, 0.86119, 0.78278, -0.01348, 0.98093, -0.56244, -0.75129
F5  DD  -0.73365, 0.28332, 0.63263, 0.17177, -0.38398, -0.43497, -0.31123, 0.73168
F6  DD  -0.57694, -0.87713, -0.93622, 0.89397, 0.93117, 0.40775, 0.2323, -0.30718
F7  DD  0.91059, 0.75966, 0.60118, 0.73186, 0.32178, 0.88296, -0.90087, -0.26367
F8  DD  0.3463, -0.89397, 0.99108, 0.13557, 0.50122, -0.8724, 0.43385, 0.00167
F9  DD  0.88121, 0.36469, -0.29829, 0.21429, 0.31395, 0.2734, 0.43267, -0.78192

TEQ DB 'In Triangle',0DH,0AH,'$'
FEQ DB 'Not In Triangle',0DH,0AH,'$'

```

### Output

```
In Triangle
In Triangle
In Triangle
In Triangle
In Triangle
In Triangle
In Triangle
In Triangle
In Triangle
In Triangle
Not In Triangle
Not In Triangle
Not In Triangle
Not In Triangle
Not In Triangle
Not In Triangle
Not In Triangle
Not In Triangle
Not In Triangle
Not In Triangle

```
> 2 votes

# Answer
## C 414 (was 465)

Golfed

```
#define D double
int F(D ax,D ay,D bx,D by,D cx,D cy,D px,D py){int y=0;double J,K;D m=(ax-bx<0.001)?(by-ay)/(ax-bx):1000;D b=m*ax+ay;J=m*cx-cy+b;K=m*px-py+b;if(J*K>=0)y=1;return y;}D T[8],k;int i,n;void G(){while(i<8){scanf("%lf",&k);T[i++]=k;}n+=F(T[2],T[3],T[4],T[5],T[6],T[7],T[0],T[1]);n+=F(T[4],T[5],T[6],T[7],T[2],T[3],T[0],T[1]);n+=F(T[2],T[3],T[6],T[7],T[4],T[5],T[0],T[1]);printf(n==3?"True":"False");}

```

Original function declaration added for explanation

```
/**
* determine if points C & P are on same side of line AB
* return 1 if true, 0 otherwise
*/
int PointsSameSide(D ax,D ay,D bx,D by,D cx, D cy, D px, D py);

```

Rewritten as a named function: input via stdin one each line or all in one line space-separated.

```
#define D double
int F(D ax,D ay,D bx,D by,D cx, D cy, D px, D py)
{
int y=0;
double J,K;
D m = (ax-bx<0.001)?(by-ay)/(ax-bx):1000;
D b = m*ax+ay;
J=m*cx-cy+b;
K=m*px-py+b;
if(J*K>=0)y=1;
return y;
}
double T[8],k;
int i,n;
void G()
{
while(i<8){scanf("%lf",&k);T[i++]=k;}
n+=F(T[2],T[3],T[4],T[5],T[6],T[7],T[0],T[1]);
n+=F(T[4],T[5],T[6],T[7],T[2],T[3],T[0],T[1]);
n+=F(T[2],T[3],T[6],T[7],T[4],T[5],T[0],T[1]);
printf(n==3?"True":"False");
}

```
> 1 votes

# Answer
# JavaScript 125/198

If points are provided in 8 arguments:

```
function d(x,y,a,b,c,d,e,f){function z(a,b,c,d){return(y-b)*(c-a)-(x-a)*(d-b)>0}return(z(a,b,c,d)+z(c,d,e,f)+z(e,f,a,b))%3<1}

```

If points are provided in a 2-dimensional array:

```
function c(s){return (z(s[1][0],s[1][1],s[2][0],s[2][1])+z(s[2][0],s[2][1],s[3][0],s[3][1])+z(s[3][0],s[3][1],s[1][0],s[1][1]))%3<1;function z(a,b,c,d){return (s[0][1]-b)*(c-a)-(s[0][0]-a)*(d-b)>0}}

```

This code doesn't use any of those fancy vector math. Instead, it only uses a simple algebra trick to determine if the point is inside the triangle or not. The formula:

```
(y-b)(c-a) - (x-a)(d-b)

```

which tells the point is on which side of a line, is derived from rearranging the definition of slope:

```
            m = (y2-y1)/(x2-x1)
      (y2-y1) = m(x2-x1)
       (y-y1) = m(x-x1)     ,substituting point we are testing (x,y) to be the 2nd point
       (y-y1) = (x-x1)(y2-y1)/(x2-x1)  ,substitute back the original definition of m
(y-y1)(x2-x1) = (x-x1)(y2-y1)    <-- left side will be greater than the right side, if
                                     the point is on the left; otherwise, it's on the right
            0 = (y-b)(c-a)-(x-a)(d-b) ,where (a,b)=(x1,y1), (c,d)=(x2,y2)

```

If we test all 3 sides, all 3 should yield some numbers with the same sign only when the point is inside the triangle since we are testing it around the triangle. If the point is on a side then one of the test should return 0.

jsFiddle test code: http://jsfiddle.net/DerekL/zEzZU/

```
var l = [[-0.31961, -0.12646, 0.38478, 0.37419, -0.30613, -0.59754, -0.85548, 0.6633],[-0.87427, -0.00831, 0.78829, 0.60409, -0.90904, -0.13856, -0.80685, 0.48468],[0.28997, -0.03668, -0.28362, 0.42831, 0.39332, -0.07474, -0.48694, -0.10497],[-0.07783, 0.04415, -0.34355, -0.07161, 0.59105, -0.93145, 0.29402, 0.90334],[0.36107, 0.05389, 0.27103, 0.47754, -0.00341, -0.79472, 0.82549, -0.29028],[-0.01655, -0.20437, -0.36194, -0.90281, -0.26515, -0.4172, 0.36181, 0.51683],[-0.12198, -0.45897, -0.35128, -0.85405, 0.84566, 0.99364, 0.13767, 0.78618],[-0.03847, -0.81531, -0.18704, -0.33282, -0.95717, -0.6337, 0.10976, -0.88374],[0.07904, -0.06245, 0.95181, -0.84223, -0.75583, -0.34406, 0.16785, 0.87519],[-0.33485, 0.53875, -0.25173, 0.51317, -0.62441, -0.90698, -0.47925, 0.74832],
         [-0.99103, 0.43842, 0.78128, -0.10985, -0.84714, -0.20558, -0.08925, -0.78608],[0.15087, -0.56212, -0.87374, -0.3787, 0.86403, 0.60374, 0.01392, 0.84362],[0.1114, 0.66496, -0.92633, 0.27408, 0.92439, 0.43692, 0.8298, -0.29647],[0.87786, -0.8594, -0.42283, -0.97999, 0.58659, -0.327, -0.22656, 0.80896],[0.43525, -0.8923, 0.86119, 0.78278, -0.01348, 0.98093, -0.56244, -0.75129],[-0.73365, 0.28332, 0.63263, 0.17177, -0.38398, -0.43497, -0.31123, 0.73168],[-0.57694, -0.87713, -0.93622, 0.89397, 0.93117, 0.40775, 0.2323, -0.30718],[0.91059, 0.75966, 0.60118, 0.73186, 0.32178, 0.88296, -0.90087, -0.26367],[0.3463, -0.89397, 0.99108, 0.13557, 0.50122, -0.8724, 0.43385, 0.00167],[0.88121, 0.36469, -0.29829, 0.21429, 0.31395, 0.2734, 0.43267, -0.78192]];

function d(x,y,a,b,c,d,e,f){function z(a,b,c,d){return(y-b)*(c-a)-(x-a)*(d-b)>0}return(z(a,b,c,d)+z(c,d,e,f)+z(e,f,a,b))%3<1}

for(var i = 0; i < l.length; i++){
    console.log(d.apply(undefined,l[i]));    //10 true, 10 false
}

```

---

**97 characters** (not counting spaces or tabs) count if converted into CoffeeScript:

```
d=(x,y,a,b,c,d,e,f)->
    z=(a,b,c,d)->
        (y-b)*(c-a)-(x-a)*(d-b)>0
    (z(a,b,c,d)+z(c,d,e,f)+z(e,f,a,b))%3<1

```

**115 characters** if converted into ES6:

```
d=(x,y,a,b,c,d,e,f)=>{z=(a,b,c,d)=>{return (y-b)*(c-a)-(x-a)*(d-b)>0};return(z(a,b,c,d)+z(c,d,e,f)+z(e,f,a,b))%3<1}

```
> 1 votes

# Answer
**Java, 149 characters**

```
g=Math.atan2(100*(d-y),(a-x));h=Math.atan2(100*(e-y),(b-x));i=Math.atan2(100*(f-y),(c-x));k=Math.round(Math.abs(g-h)+Math.abs(h-i)+Math.abs(i-g))==6;

```

Horrible considering I have to write "Math." every time. This is the actual program:

```
package mathPackage;
public class InTriangle {
public static void main(String[] args) {
    boolean k;
    double a=-1,b=0,c=1,d=0,e=1,f=0,x=0,y=0.4;
    double g,h,i;
    g=Math.atan2(100*(d-y),(a-x));
    h=Math.atan2(100*(e-y),(b-x));
    i=Math.atan2(100*(f-y),(c-x));
    k=Math.round(Math.abs(g-h)+Math.abs(h-i)+Math.abs(i-g))==6;
    System.out.println(k);
    System.out.println(g);
    System.out.println(h);
    System.out.println(i);
    System.out.print(Math.abs(g-h)+Math.abs(h-i)+Math.abs(i-g));
}
}

```

where a is the x of point a,b is the x of point b, c for x of c, d is y of a, e is y of b, f is the y of c, and x and y are the x and y of the point. The boolean k determines whether it is true or not.
> 1 votes

# Answer
## R, 23

Inspired by MATLAB,

```
SDMTools::pnt.in.poly()

```

called like `SDMTools::pnt.in.poly(point,triangle)` where `point` is a length-2 vector and `triangle` is a 3x2 matrix of vertices. SDMTools is available on CRAN.
> 1 votes

# Answer
# Mathematica, 38 characters

```
RegionMember[Polygon[#[[1]]],#[[2]]] &

```

Example:

```
d = {{{0, 0}, {1, 0}, {.5, .7}}, {.5, .6}};

RegionMember[Polygon[#[[1]]], #[[2]]] & @ d

```

(\* True \*)
> 1 votes

# Answer
# C (gcc), 108 bytes

```
i;f(a,b,c,d,e,f,g,h)float a,b,c,d,e,f,g,h;{i=(e-=a)*(h-=b)>(f-=b)*(g-=a);i=(c-=a)*f>(d-=b)*e==i&i==g*d>h*c;}

```

Try it online!

Takes three cross products and returns `1` if the sign of the  component doesn't change.
> 0 votes

---
Tags: code-golf, geometry
---


title: Decrypt xor-encryption

text:
# Question
Title: Decrypt xor-encryption
Your task is to take an encrypted string as input, and output the string decrypted, to reveal its hidden message.

The strings, both the input and output, will contain characters from this list of 64 ASCII-characters (note the leading space):

```
 !"#$%&'()*+,-./0123456789:;=?@[\]^_abcdefghijklmnopqrstuvwxyz|~

```

These characters are assigned numbers, in the order they are listed above:

```
  ! " # $ % &   ...
0 1 2 3 4 5 6   ...

```

So, space is number 0, `!` is number 1 and `~` is number 63. These numbers can be represented in 6-bit binary code:

```
 :  0:  000000
!:  1:  000001
":  2:  000010
#:  3:  000011
.. ...  ......
z: 61:  111101
|: 62:  111110
~: 63:  111111

```

---

The encryption is very simple:

I'll use `eC` for encrypted characters, and `C` for characters of the original string. `C(n)` is the n'th character of the original string, while `eC(n)` is the n'th character of the encrypted string.

**You'll use the 6-bit binary representation of the characters. The first character will be `eC(0) = not(C(0))`. From there, all characters will be `eC(n) = xor(C(n),C(n-1))`.**

**Example:**

Let's assume the input string is `code`.

* `c` is the 38th character (zero indexed), or `100110` in binary. The encrypted version has all bits flipped, so `011001 -> 25 -> '9'` (again, zero indexed).
* `o` is the 50th character, or `110010` in binary. `xor(100110, 110010) = 010100 = 20 = '4'`.
* `d` is the 39th character, or `100111` in binary. `xor(100111, 110010) = 010101 = 21 = '5'`.
* `e` is the 40th character, or `101000` in binary. `xor(101000, 100111) = 001111 = 15 = '/'`.

So, if the original string is `code`, the encrypted string will become `945/`.

---

## Test cases:

```
945/
code

,&'8[14 =?;gp+% 2'@s&&c45/eg8?&
programming puzzles & code golf

;a$5$%0r?2@12dw6# lb-eg&519nt%ot=9$@es@96+?;ga" 4*)&ta56dp[?o#t%oh/"(&?#ee![,+,/+fe4"
a $150 reward will be given to those sending account and pin# to hackers@steal_id.com

~!#!'!#!/!#!'!#![!#!'!#!/!#!'!#!~!#!'!#!/!#!'!#![!#!'!#!/!#!'!#!
 !"#$%&'()*+,-./0123456789:;=?@[\]^_abcdefghijklmnopqrstuvwxyz|~

```

# Answer
> 9 votes
# Jelly, ~~27~~ 26 bytes

```
ØJḟ“<>`{}”ḟØAɓi@€_33^\96_ị

```

Try it online!

### Alternate version, 22 bytes (non-competing)

Jelly finally caught up with other golfing langs and got a *printable ASCII* atom, so this works now.

```
ØṖḟ“<>`{}”ḟØAɓi@€’^\Nị

```

Try it online!

## How it works

```
ØJḟ“<>`{}”ḟØAɓi@€_33^\96_ị  Main link. Argument: s (string)

ØJ                          Yield Jelly's code page, i.e., 32 non-ASCII characters,
                            followed by all printable ASCII characters, followed by
                            129 non-ASCII characters.
  ḟ“<>`{}”                  Filterfalse; remove the characters "<>`{}".
          ḟØA               Filterfalse; remove all uppercase ASCII letters.
                            Let's call the resulting alphabet a.
             ɓ              Begin a new, dyadic chain.
                            Left argument: s. Right argument: a
              i@€           Find the (1-based) index of all characters of s in a.
                 _33        Subtract 33, so ' ' maps to 0, '~' maps to 63.
                    ^\      Compute the cumulative bitwise XOR.
                            We didn't take the bitwise NOT of the first index,
                            which can be rectified by subtracting all results from
                            63. However, we must also add 33 to account for the
                            fact that the index of ' ' in a is 33.
                      96_   Subtract the results from 96.
                         ị  Index into a.

```

# Answer
> 6 votes
## JavaScript (ES6), 115 bytes

```
s=>s.replace(/./g,s=>d[x^=d.indexOf(s)],x=63,d=` !"#$%&'()*+,-./0123456789:;=?@[\\]^_abcdefghijklmnopqrstuvwxyz|~`)

```

### Test cases

```
let f =

s=>s.replace(/./g,s=>d[x^=d.indexOf(s)],x=63,d=` !"#$%&'()*+,-./0123456789:;=?@[\\]^_abcdefghijklmnopqrstuvwxyz|~`)

console.log(f("945/"))
console.log(f(",&'8[14 =?;gp+% 2'@s&&c45/eg8?&"))
console.log(f(';a$5$%0r?2@12dw6# lb-eg&519nt%ot=9$@es@96+?;ga" 4*)&ta56dp[?o#t%oh/"(&?#ee![,+,/+fe4"'))
console.log(f("~!#!'!#!/!#!'!#![!#!'!#!/!#!'!#!~!#!'!#!/!#!'!#![!#!'!#!/!#!'!#!"))
```

# Answer
> 5 votes
# Jelly,  ~~34~~  31 bytes

-3 bytes thanks to Dennis (use  twice rather than `œ-`, `;` and `¤`; use `”~` rather than **63** )

```
32r126Ọḟ“<>`{}”ḟØAṙ1ɓ”~;i@€^\Ḋị

```

A monadic link taking and returning lists of characters.
\*Note: the input arguments to a Jelly program utilise Python string formatting, so quoting with `"`, `'`, `'''` (or if unambiguous no quoting) are all options.

**Try it online!**

### How?

Bitwise-xor is invertible (given "leading zeros").

Bitwise-Not is an xor with "all ones" - in this case only **6** ones are ever required, so **27-1 = 63**.

Once we have created the array or characters and looked up the indexes of the input characters, the decode itself is then simply a cumulative reduction by bitwise-xor, after which we may index back into the same array.

```
32r126Ọḟ“<>`{}”ḟØAṙ1ɓ”~;i@€^\Ḋị - Main link: string, s
32r126                          - inclusive range -> [32,33,...,125,126]
      Ọ                         - cast to ordinals -> " !...}~"
        “<>`{}”                 - literal ['<','>','`','{','}']
       ḟ                        - filter discard
                ØA              - yield "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
               ḟ                - filter discard
                  ṙ1            - rotate left by one (Jelly indexing is one based)
                    ɓ           - dyadic chain separation, swapping arguments (call that p)
                     ”~         - literal '~'
                       ;        - concatenate with s (`~` has value 63 for the bitwise-not)
                        i@€     - first index* of €ach character of s in p
                            \   - cumulative reduce by:
                           ^    -   bitwise-xor
                             Ḋ  - dequeue (remove the 63 from '~')
                              ị - index into p

```

* *Note:* looking up a space in p will yield a 64, but that's OK since indexing back into p is modular so adding a leading `1` is like adding 64, taking the index right back around to where it needs to be).

# Answer
> 3 votes
# Java, 225 bytes

```
String D(String E){String A="",C=" !\"#$%&'()*+,-./0123456789:;=?@[\\]^_abcdefghijklmnopqrstuvwxyz|~";for(int i=-1,J=0;++i<E.length();J=C.indexOf(E.charAt(i)),A+=C.charAt(i<1?(1<<6)-1-J:C.indexOf(A.charAt(i-1))^J));return A;}

```

I have not golfed in Java in a very long time, so any golfing tips are appreciated.

Try It Online!

# Answer
> 2 votes
# 05AB1E, 40 bytes

```
'~«vžQAu"<>{}`"«SK©yk64+b¦S}r.gG^DJC®sè?

```

Try it online!

**Explanation**

```
'~«                                       # append input to "~"
   v                                      # for each char y in the resulting string
    žQ                                    # push printable ascii chars
      Au                                  # push upper case alphabet
        "<>{}`"«                          # append "<>{}`"
                SK                        # remove those chars from printable ascii
                  ©                       # store a copy in register
                   yk                     # get the index of y in that string
                     64+                  # add 64
                        b                 # convert to binary
                         ¦S               # remove leading 1 and convert to list of bits
                           }              # end loop
                            r             # reverse stack
                             .gG          # len(stack)-1 times do
                                ^         # xor top 2 lists of bits on the stack
                                 DJC      # convert a copy to decimal
                                    ®sè   # index into the char string with this
                                       ?  # print

```

# Answer
> 2 votes
# CPU x86 instruction set, 235 bytes

```
00000750  50                push eax
00000751  8A10              mov dl,[eax]
00000753  80FA00            cmp dl,0x0
00000756  7418              jz 0x770
00000758  31DB              xor ebx,ebx
0000075A  EB03              jmp short 0x75f
0000075C  F9                stc
0000075D  EB13              jmp short 0x772
0000075F  8A83C1A14000      mov al,[ebx+0x40a1c1]
00000765  3C00              cmp al,0x0
00000767  74F3              jz 0x75c
00000769  38C2              cmp dl,al
0000076B  7404              jz 0x771
0000076D  43                inc ebx
0000076E  EBEF              jmp short 0x75f
00000770  42                inc edx
00000771  F8                clc
00000772  58                pop eax
00000773  C3                ret
00000774  53                push ebx
00000775  8B442408          mov eax,[esp+0x8]
00000779  31C9              xor ecx,ecx
0000077B  09C0              or eax,eax
0000077D  7505              jnz 0x784
0000077F  31C0              xor eax,eax
00000781  48                dec eax
00000782  EB2F              jmp short 0x7b3
00000784  E8C7FFFFFF        call 0x750
00000789  72F4              jc 0x77f
0000078B  7510              jnz 0x79d
0000078D  F6D3              not bl
0000078F  80E33F            and bl,0x3f
00000792  88D9              mov cl,bl
00000794  8AB3C1A14000      mov dh,[ebx+0x40a1c1]
0000079A  8830              mov [eax],dh
0000079C  40                inc eax
0000079D  E8AEFFFFFF        call 0x750
000007A2  72DB              jc 0x77f
000007A4  750D              jnz 0x7b3
000007A6  30D9              xor cl,bl
000007A8  8AB1C1A14000      mov dh,[ecx+0x40a1c1]
000007AE  8830              mov [eax],dh
000007B0  40                inc eax
000007B1  EBEA              jmp short 0x79d
000007B3  5B                pop ebx
000007B4  C20400            ret 0x4
000007B7  53                push ebx
000007B8  8B442408          mov eax,[esp+0x8]
000007BC  31C9              xor ecx,ecx
000007BE  09C0              or eax,eax
000007C0  7505              jnz 0x7c7
000007C2  31C0              xor eax,eax
000007C4  48                dec eax
000007C5  EB32              jmp short 0x7f9
000007C7  E884FFFFFF        call 0x750
000007CC  72F4              jc 0x7c2
000007CE  750F              jnz 0x7df
000007D0  30D9              xor cl,bl
000007D2  8AB1C1A14000      mov dh,[ecx+0x40a1c1]
000007D8  8830              mov [eax],dh
000007DA  88D9              mov cl,bl
000007DC  40                inc eax
000007DD  EBE8              jmp short 0x7c7
000007DF  8B442408          mov eax,[esp+0x8]
000007E3  E868FFFFFF        call 0x750
000007E8  72D8              jc 0x7c2
000007EA  750D              jnz 0x7f9
000007EC  F6D3              not bl
000007EE  80E33F            and bl,0x3f
000007F1  8AB3C1A14000      mov dh,[ebx+0x40a1c1]
000007F7  8830              mov [eax],dh
000007F9  5B                pop ebx
000007FA  C20400            ret 0x4

```

The function find() and deCript() + the string abc: 171 bytes + 64 bytes=235 assembly with nasmw and compiler/library with Borland C compiler:

```
; nasmw -fobj  this.asm
; bcc32 -v  this.obj
section _DATA use32 public class=DATA
global _main
extern _printf

fmt1 db "result=%s" , 13, 10, 0, 0
fmt2 db "abc[63]=%c" , 13, 10, 0, 0
code1 db "code" , 0, 0
code2 db ",&'8[14 =?;gp+% 2'@s&&c45/eg8?&" , 0, 0
code3 db ';a$5$%0r?2@12dw6# lb-eg&519nt%ot=9$@es@96+?;ga" 4*)&ta56dp[?o#t%oh/"(&?#ee![,+,/+fe4"' , 0, 0
abc db ' !"#$%' , "&'()*+,-./0123456789:;=?@[\]^_abcdefghijklmnopqrstuvwxyz|~" , 0, 0

section _TEXT use32 public class=CODE

find:
      push    eax
      mov     dl,  [eax]
      cmp     dl,  0
      je      .2
      xor     ebx,  ebx
      jmp     short  .1
.e:   stc
      jmp     short  .z
.1:   mov     al,  [abc+ebx]
      cmp     al,  0
      je      .e
      cmp     dl,  al
      je      .3
      inc     ebx
      jmp     short  .1
.2:   inc     edx           ; set zf=0
.3:   clc
.z:   pop     eax
      ret

deCript:
      push    ebx
      mov     eax,  dword[esp+8]
      xor     ecx,  ecx
      or      eax,  eax
      jnz     .1
.e:   xor     eax,  eax
      dec     eax
      jmp     short  .z
.1:   call    find
      jc      .e
      jnz     .2
      not     bl
      and     bl,  03Fh
      mov     cl,  bl
      mov     dh,  [abc+ebx]
      mov     [eax],  dh
      inc     eax
.2:   call    find
      jc      .e
      jnz     .z
      xor     cl,  bl
      mov     dh,  [abc+ecx]
      mov     [eax],  dh
      inc     eax
      jmp     short  .2
.z:
      pop     ebx
      ret     4

cript:
      push    ebx
      mov     eax,  dword[esp+8]
      xor     ecx,  ecx
      or      eax,  eax
      jnz     .1
.e:   xor     eax,  eax
      dec     eax
      jmp     short  .z
.1:   call    find
      jc      .e
      jnz     .2
      xor     cl,  bl
      mov     dh,  [abc+ecx]
      mov     [eax],  dh
      mov     cl,  bl
      inc     eax
      jmp     short  .1
.2:   mov     eax,  dword[esp+8]
      call    find
      jc      .e
      jnz     .z
      not     bl
      and     bl,  03Fh
      mov     dh,  [abc+ebx]
      mov     [eax],  dh
.z:
      pop     ebx
      ret     4

_main:
      pushad

      push    code1
      call    cript
      push    code1
      push    fmt1
      call    _printf
      add     esp,  8

      xor     eax,  eax
      mov     al,  [abc+63]
      push    eax
      push    fmt2
      call    _printf
      add     esp,  8

      push    code1
      call    deCript
      push    code1
      push    fmt1
      call    _printf
      add     esp,  8
      push    code2
      call    deCript
      push    code2
      push    fmt1
      call    _printf
      add     esp,  8
      push    code3
      call    deCript
      push    code3
      push    fmt1
      call    _printf
      add     esp,  8

      popad
      mov     eax,  0
      ret

```

results:

```
result=945/
abc[63]=~
result=code
result=programming puzzles & code golf
result=a $150 reward will be given to those sending account and pin# to hackers@steal_id.com

```

Assembly is better (for say the true I use a macro system, yes I know it is too long but as the C one +- with macro system , for say the true because the instructions are simpler it is easy write code in assembly even without make corrections as one write in English (not I) )

# Answer
> 2 votes
# C (gcc), 153 bytes

```
char*i=" !\"#$%&'()*+,-./0123456789:;=?@[\\]^_abcdefghijklmnopqrstuvwxyz|~";a(b){b=index(i,b)-i;}f(char*x){for(*x=i[a(*x)^63];x[1];)*x=i[a(*x)^a(*++x)];}

```

Try it online!

Slightly golfed less

```
char*i=" !\"#$%&'()*+,-./0123456789:;=?@[\\]^_abcdefghijklmnopqrstuvwxyz|~";
a(b){
  b=index(i,b)-i;
}
f(char*x){
  for(*x=i[a(*x)^63];x[1];)
    *x=i[a(*x)^a(*++x)];
}

```

# Answer
> 2 votes
# APL (Dyalog Unicode), 52 bytesSBCS

Requires `⎕IO←0`

```
{C[2∘⊥¨≠\~@0⊢(6/2)∘⊤¨⍵⍳⍨C←(32↓⎕UCS⍳127)~⎕A,'<>{}`']}

```

Try it online!

# Answer
> 1 votes
# Röda, ~~120~~ 100 bytes

```
f a{A=[]seq 32,126|chr _|{|v|A+=v if[v=~"[^<>`{}A-Z]"]}_;l=63;a|{|c|l=indexOf(c,A) b_xor l;[A[l]]}_}

```

Try it online!

I used the `l=63` trick from the JavaScript answer. ~~Right now I am working on shortening `A` so golfing in progress...~~

# Answer
> 1 votes
# Python 2, 155 bytes

```
lambda s,m=' !"#$%&\'()*+,-./0123456789:;=?@[\\]^_abcdefghijklmnopqrstuvwxyz|~':''.join(m[i]for i in reduce(lambda a,b:a+[a[-1]^b],map(m.find,s),[63])[1:])

```

Try it online!

# Answer
> 1 votes
# PHP, 103 Bytes

```
for($x=63;~$c=$argn[$i++];)echo($a=join(preg_grep("#[^A-Z<>`{}]#",range(" ","~"))))[$x^=strpos($a,$c)];

```

Try it online!

## PHP, 107 Bytes

```
for($x=63;~$c=$argn[$i++];)echo($a=preg_filter("#[A-Z<>`{}]#","",join(range(" ","~"))))[$x^=strpos($a,$c)];

```

Try it online!

## PHP, 118 Bytes

```
for($x=63;~$c=$argn[$i++];)echo($a=join(array_diff(range(" ","~"),range(A,Z),str_split("<>`{}"))))[$x^=strpos($a,$c)];

```

Try it online!

# Answer
> 1 votes
## Python + Numpy, 214 bytes

Can't compete with other Python solution, though uses different, pure numeric approach:

```
from numpy import *
def f(s):
    r=range
    A=array
    S=A(r(32,60)+[61,63,64]+r(91,96)+r(97,123)+[124,126])
    T=A(r(128))
    T[S]=A(r(64))
    W=T[fromstring(s,"b")]
    W[0]=~W[0]
    W=S[bitwise_xor.accumulate(W)&63]
    print W.tobytes()[::4]

```

A bit of explanation:

* `S=A(r(32,60)+...)` \- define alphabet as code ranges
* `T=A(r(128))` \- init hash table of size 128 (largest codepoint)
* `T[S]=A(r(64))` \- fill the hash table, i.e. write indices 0-63 to the elements with ASCII indices
* `W=T[fromstring(s,"b")]` \- convert the input to array & translate it into new codes
* `W[0]=~W[0]` \- invert 1st value
* `W=S[bitwise_xor.accumulate(W)&63]` \- use Numpy's accumulate method with xor to avoid looping, reset 2 left bits and translate back to ascii

# Answer
> 1 votes
# Alice, 46 bytes

```
/" >"{""ZNr\'?wi.h%)qXq&[.&]?oe(K
\"<~`r}A*"!/

```

Try it online!

### Explanation

The first half of the program runs in ordinal mode and sets up the mapping from numbers to characters. The second half runs in cardinal mode and uses this mapping to decode the input.

```
" ~"                    Push this string
    r                   Convert to entire range (all printable ASCII)
     "AZ"               Push this string
         r              Convert to entire range
          "<>`{}"       Push this string
                 *      Append last two strings
                  N     Remove characters from full string
                   !    Copy entire string to tape

'?                      Push 63 (code point of ?) onto the stack
  w                     Store return address (start main loop)
   i                    Take byte of input
    .h%                 Calculate n mod (n+1): this crashes on EOF (-1)
       )                Find byte on tape
        q               Get position on tape
         X              Bitwise XOR with current value
          q&[           Return to tape position 0
             .&]        Move to tape position corresponding to result of earlier XOR
                ?o      Get and output byte at current tape position
                  e(    Search for -1 to left of current tape position (which will put us at position -1)
                    K   Jump to previously pushed return address.

```

# Answer
> 1 votes
# Japt `-P`, 33 bytes

```
;
EkB+"<>}\{`"1
¬i63 åÈ^VaYÃÅm!gV

```

Try it online!

For some reason, the test cases object to running as a suite, so here's the second, third, and fourth individually.

Explanation:

```
;                    #Set E to a string of all printable ASCII characters

Ek          1        #Set V to E with these characters removed:
  B                  # All uppercase letters
   +"<>}\{`"         # and the characters "<>}{`"

¬                    #Turn the input into an array
 i63                 #Add the number 63 to the front of that array
     å     Ã         #Replace each character with:
      È              # The index of the previous decoded character in V
       ^             # Xor with...
        VaY          # The index of the current character in V
            Å        #Remove the extra character
             m!gV    #Map the indexes to the character in V
                     #Join to a string due to the flag

```

# Answer
> 1 votes
# APL(NARS), 72 chars, 144 bytes

```
{r←6⍴2⋄y←{r⊤⍵}¨¯1+⍵⍳⍨s←⎕AV[33..127]∼⎕A,'{<>}`'⋄y[1]←⊂∼↑y⋄s[1+{r⊥⍵}¨≠\y]}

```

This suppose the input is always in the array 's'... For understand how to do decipher i had to write the assembly version first... test:

```
  h←{r←6⍴2⋄y←{r⊤⍵}¨¯1+⍵⍳⍨s←⎕AV[33..127]∼⎕A,'{<>}`'⋄y[1]←⊂∼↑y⋄s[1+{r⊥⍵}¨≠\y]}
  h ,'6'
f
  h '945/'
code
  h ",&'8[14 =?;gp+% 2'@s&&c45/eg8?&"
programming puzzles & code golf
  h ';a$5$%0r?2@12dw6# lb-eg&519nt%ot=9$@es@96+?;ga" 4*)&ta56dp[?o#t%oh/"(&?#ee![,+,/+fe4"'
a $150 reward will be given to those sending account and pin# to hackers@steal_id.com
  h "~!#!'!#!/!#!'!#![!#!'!#!/!#!'!#!~!#!'!#!/!#!'!#![!#!'!#!/!#!'!#!"
 !"#$%&'()*+,-./0123456789:;=?@[\]^_abcdefghijklmnopqrstuvwxyz|~

```

# Answer
> 1 votes
# 105 103 bytes, machine code (16-bit x86), 57 instructions

```
00000000: ff 01 b9 01 00 89 fa b4 3f cd 21 85 c0 75 02 cd
00000010: 20 8a 05 2c 20 3c 1d 72 1b 48 3c 1e 72 16 48 3c
00000020: 39 72 11 2c 1a 3c 25 72 0b 48 3c 3f 72 06 48 3c
00000030: 40 72 01 48 32 04 24 3f 88 04 3c 3f 72 01 40 3c
00000040: 3e 72 01 40 3c 24 72 01 40 3c 1f 72 02 04 1a 3c
00000050: 1d 72 01 40 3c 1c 72 01 40 04 20 43 89 d9 88 05
00000060: b4 40 cd 21 4b eb 9b

```

Running: save to codegolf.com, dosbox:

`codegolf.com < input.bin`

Almost forgot fun part:

Howdy, this is my second entry. Previous one was RC4. Done using HT hexeditor, **without compiler**, but this time I was using Ctrl-a `assemble instruction`, I still dunno if this counts as an entry or not.

## Why & how

In as similar manner I've started by creating file with `NOP`s, then I reused reading in /writing out from RC4. I first written in python 'translation ladder' from ascii to index. and used that in assembly, created similar ladder in reverse direction, finally I added small trick to handle first byte

In a similar fashion to RC4 last step was getting rid of additional `nops`, which required fixing jumps.

## Dissection

Again program relies on initial register values.

```
00000000 ff01                    inc         word ptr [bx+di]

```

Dummy, will be needed later

```
00000002 b90100                  mov         cx, 0x1
00000005 89fa                    mov         dx, di
00000007 b43f                    mov         ah, 0x3f
00000009 cd21                    int         0x21

```

read byte

```
0000000b 85c0                    test        ax, ax
0000000d 7502                    jnz         0x11
0000000f cd20                    int         0x20

```

quit if stdin finished

```
00000011 8a05                    mov         al, [di]
00000013 2c20                    sub         al, 0x20
00000015 3c1d                    cmp         al, 0x1d
00000017 721b                    jc          0x34
00000019 48                      dec         ax
0000001a 3c1e                    cmp         al, 0x1e
0000001c 7216                    jc          0x34
0000001e 48                      dec         ax
0000001f 3c39                    cmp         al, 0x39
00000021 7211                    jc          0x34
00000023 2c1a                    sub         al, 0x1a
00000025 3c25                    cmp         al, 0x25
00000027 720b                    jc          0x34
00000029 48                      dec         ax
0000002a 3c3f                    cmp         al, 0x3f
0000002c 7206                    jc          0x34
0000002e 48                      dec         ax
0000002f 3c40                    cmp         al, 0x40
00000031 7201                    jc          0x34
00000033 48                      dec         ax

```

ladder that translates ascii to index (mind that all jumps go to 0x134)

```
00000034 3204                    xor         al, [si]

```

xor byte by previous byte, `SI` points at address `0x100`, which initially contains 0xFF from the opcode of a dummy instruction at the top, which results in negate behavior (reminder: COMs are loaded at 0x100)

```
00000036 243f                    and         al, 0x3f
00000038 8804                    mov         [si], al

```

limit result to index, and store byte at 0x100,

```
0000003a 3c3f                    cmp         al, 0x3f
0000003c 7201                    jc          0x3f
0000003e 40                      inc         ax
0000003f 3c3e                    cmp         al, 0x3e
00000041 7201                    jc          0x44
00000043 40                      inc         ax
00000044 3c24                    cmp         al, 0x24
00000046 7201                    jc          0x49
00000048 40                      inc         ax
00000049 3c1f                    cmp         al, 0x1f
0000004b 7202                    jc          0x4f
0000004d 041a                    add         al, 0x1a
0000004f 3c1d                    cmp         al, 0x1d
00000051 7201                    jc          0x54
00000053 40                      inc         ax
00000054 3c1c                    cmp         al, 0x1c
00000056 7201                    jc          0x59
00000058 40                      inc         ax
00000059 0420                    add         al, 0x20

```

ladder in reverse direction

```
0000005b 43                      inc         bx
0000005c 89d9                    mov         cx, bx
0000005e 8805                    mov         [di], al
00000060 b440                    mov         ah, 0x40
00000062 cd21                    int         0x21
00000064 4b                      dec         bx

```

put byte under \[di\], write byte to stdout (mind that AH=40h uses DX as an address, but it was set at the top, when reading byte)

mind that stdin -\> stdout and stdout to stdin is done using inc bx / dec bx

```
00000067 eb99                    jmp         0x2

```

loop ^^

## Tools and resources

---
Tags: code-golf, binary, encryption
---


# Question
Title: Is this a consecutive-prime/constant-exponent number?
A while ago, I had a look at the prime factorization of 27000:

> 27000 = 23 × 33 × 53

There are two special things about that:

* **consecutive-prime**: The primes are consecutive: 2 is the 1st prime, 3 is the 2nd prime, 5 is the 3rd prime.
* **constant-exponent**: The exponent is the same for every prime (always 3)

Mathematically expressed:

> An integer *x* is a consecutive-prime/constant-exponent number if there exist strictly positive integers *n*, *k*, *m* such that *x* = *p**n**m* × *p**n*+1*m* × ... × *p**n*+*k**m*, where *p**j* is the *j*-th prime

Your task is to test if a positive integer fulfills these conditions.

## Input:

A positive integer \> 1, in any reasonable form.

## Output:

One of two values, at least one of which has to be constant, indicating whether the input is a consecutive-prime/constant-exponent number.

## Edge cases:

* primes are truthy, as the factorization for prime *p* is *p*1
* other numbers that can be written as *p**m* where *p* is a prime are also truthy.

## Rules:

* Standard loopholes apply.
* No worries about integer overflow, but numbers up to 255 must work.
* Shortest code in bytes wins.

## Test cases:

Truthy:

```
2
3
4
5
6
7
8
9
11
13
15
27000
456533

```

Falsy:

```
10
12
14
72
10000000

```

Here is a python script generating some test cases.

### The fact that I accepted an answer does not mean that the challenge is over; the winner can still change!

# Answer
# 05AB1E, 4 bytes

```
Ó0ÛË

```

Try it online!

**Explanation**

```
Ó     # get a list of prime exponents
 0Û   # remove leading zeroes
   Ë  # all remaining elements are equal

```
> 14 votes

# Answer
# Regex (ECMAScript), ~~276~~ ~~205~~ ~~201~~ ~~193~~ ~~189~~ ~~177~~ 174 bytes

Comparing the multiplicities (exponents) of different prime factors is an interesting problem for solving with ECMAScript regex – the lack of backreferences that persist through iterations of a loop makes it a challenge to count anything. Even if counting the numerical trait in question is possible, often a more indirect approach makes for better golf.

As with my other ECMA regex posts, I'll give a **spoiler warning:** I highly recommend learning how to solve unary mathematical problems in ECMAScript regex. It's been a fascinating journey for me, and I don't want to spoil it for anybody who might potentially want to try it themselves, especially those with an interest in number theory. See this earlier post for a list of consecutively spoiler-tagged recommended problems to solve one by one.

So **do not read any further if you don't want some advanced unary regex magic spoiled for you**. If you do want to take a shot at figuring out this magic yourself, I highly recommend starting by solving some problems in ECMAScript regex as outlined in that post linked above.

The main payload from a regex I previously developed turned out to be very applicable to this challenge. That is the regex that finds the prime(s) of highest multiplicity. My first solution for that was very long, and I later golfed it way down in stages, first rewriting it to use molecular lookahead, and then porting it back to plain ECMAScript using an advanced technique to work around the lack of molecular lookahead, and subsequently golfing it down to be much smaller than the original plain ECMAScript solution.

The part from that regex that applies to this problem is the first step, which finds Q, the smallest factor of N that shares all of its prime factors. Once we have this number, all we have to do to show that N is a "constant-exponent number" is divide N by Q until we can't any longer; if the result is 1, all primes are of equal multiplicity.

After submitting an answer using my previously developed algorithm for finding Q, I realized that it could be calculated in an entirely different way: Find the largest square-free factor of N (using the same algorithm as my Carmichael number regex). As it turns out, this poses no difficulty at all in terms of stepping around the lack of molecular lookahead and variable-length lookbehind (no need to pull in the advanced technique previously used), and is 64 bytes shorter! \[Note, at the time, molecular lookahead still offered a slight benefit, but thanks to later golfs, it no longer does at all.\] Additionally it eliminates the complexity of treating square-free N and prime N as different special cases, dropping another 7 bytes from this solution.

(There still remain other problems that require the advanced technique formerly used here to golf down the calculation of Q, but currently none of them are represented by my PPCG posts.)

I put the multiplicity test before the consecutive-primes test because the latter is much slower; putting tests that can fail more quickly first makes the regex faster for uniformly distributed input. It's also better golf to put it first, because it uses more backreferences (which would cost more if they were double-digit). \[The multiplicity test is now split in two for golf, with the consecutive-primes test sandwiched inside.\]

I was able to drop 4 bytes from this regex (193 → 189) using a trick found by Grimmy that can futher shorten the form of division in which the assertion that \\$dividend-quotient\\$ is divisible by \\$divisor-1\\$ can be skipped. (Skipping this assertion was already saving 4 bytes, so now it's saving 8 bytes.) This algorithm (in both its 4 byte longer form and the currently used one) is guaranteed to match the correct quotient when at least one of these constraints is met (along with satisfying the assertion that \\$dividend\\$ is divisible by \\$divisor\\$):

* \\$divisor^2+2(divisor)+1 \< 4(dividend)\\$
* \\$quotient=1\\$ or equivalently \\$divisor=dividend\\$
* \\$divisor\\$ is a prime power
    + One of the cases in which this must be true is when \\$dividend\\$ is semi-prime and neither of the two other conditions are met. It also must be true if \\$dividend\\$ is a prime power.

We're actually not guaranteed in this context that any of those constraints will be met. Most notably, we're not even asserting that \\$quotient\\$ (which will become the next \\$dividend\\$) is still divisible by \\$divisor\\$ after each iteration of the loop. But an additional fact comes to the rescue: if the division algorithm matches an incorrect quotient (which it doesn't always do even when none of the above constraints are met), the incorrect answer is guaranteed to be less than \\$divisor\\$ but greater than \\$1\\$.

So if this happens when repeatedly dividing N by Q, the loop will terminate, and the final result will not be 1, thus guaranteeing no false positives. If N is actually a constant-exponent number, the correct quotient will always be greater than or equal to Q, so this doesn't cause any false negatives either.

Further golfs:

* -3 bytes by dividing by N just like any other largest square-free factor, instead of treating N being square-free as a special case (inspired by H.PWiz but goes farther then what he did, saving 1 extra byte – he made it so the regex attempted to divide by 0 in the case that Q=N, and then asserted that the end result of the repeated division was Q rather than 1)
* -6 bytes by changing `(?=A)(?!B)` to `(?!B)A` (some of this is from multiple uses of backrefs changing from double to single digit, with less of the opposite occurring) – thanks to H.PWiz
* -2 bytes by capturing the smallest prime as \\$\ge 2\\$ instead of augmenting the non-composite test to be a full prime test – thanks to H.PWiz
* -2 bytes by removing an extraneous pair of parentheses – thanks to H.PWiz
* -2 bytes by changing an outermost `(|(x+)\2*(?=\2$))` to `(|x*)\1*(?=\1\b)`, similarly to what I did in the alternate answer here; one of these bytes is from a backref changing from double to single digit

And the regex:

`^(?=(|x*)\1*(?=\1\b)(((?=(xx+?)\4*$)(?=(x+)(\5+$))\6(?!\4*$))*x$))(?!(((xx+)(?=\9+$)(x+))(?!\8+$)(x+))\7*(?=\7$)(?!(\11\10?)?(xx+)\13+$))((?=((x*)(?=\2\16*$)x)(\15*$))\17)*x$`

Try it online!

```
^                           # tail = N = input number

# Assert that all of N's prime factors are of equal multiplicity. There are two stages
# to this, which we will call Step 1 and Step 2. For golf reasons, a negative assertion
# is inserted between them.

# Step 1: Find Q, the largest square-free factor of N (which will also be the smallest
# factor of N that has all the same prime factors as N).
(?=
    (|x*)\1*(?=\1\b)        # cycle tail through all of the divisors of N, including N,
                            # from largest to smallest;
                            # \1 = the divisor, or zero if the divisor is N itself
    # Assert that tail is square-free (its prime factors all have single multiplicity)
    (                       # \2 = tail = the divisor
        (
            (?=(xx+?)\4*$)  # \4 = smallest prime factor of tail
            (?=(x+)(\5+$))  # \5 = tail / \4 (implicitly); \6 = tool to make tail = \5
            \6              # tail = \5
            (?!\4*$)        # Assert that tail is no longer divisible by \4, i.e. that
                            # that prime factor was of exactly single multiplicity.
        )*x$
    )
)

# Assert that there exists no trio of prime numbers such that N is divisible by the
# smallest and largest prime but not the middle prime.
(?!
    (                       # \7 = a factor of N
        (                   # \8 = a non-factor of N between \7 and \9
            (xx+)(?=\9+$)   # \9 = a factor of N smaller than \7 and greater than 1
            (x+)            # \10 = tool (with \11) to make tail = \9
        )
        (?!\8+$)
        (x+)                # \11 = tool to make tail = \8
    )
    \7*(?=\7$)              # tail = \7

    # Assert that \7, \8, and \9 are all prime
    (?!
        (\11\10?)?          # tail = either \7, \8, or \9
        (xx+)\13+$          # Assert tail is not composite; no need to test against
                            # 0 and 1, because we captured \9 > 1
    )
)

# Step 2: Require that the result of repeatedly dividing N by \2 is 1.
(
    # In this division calculation \15 = N / \2, we can skip the test for N-\15 being
    # divisible by \2-1. (Actually doing that test would make the regex 8 bytes larger.)
    # The quotient matched by this abbreviated algorithm is guaranteed to be correct if
    # the real quotient is 1 or is not less than the divisor, or if the divisor is a
    # prime power. Our input here is not guaranteed to satisfy any of those constraints.
    # But if none of those constraints are met, and the quotient matched by the algorithm
    # is incorrect, the incorrect quotient is guaranteed to be less than the divisor and
    # greater than 1. And once that happens, this loop will terminate, as the current
    # value will no longer be divisible by our divisor \2.
    (?=
        (                   # \15 = tail / \2
            (x*)            # \16 = \15-1
            (?=\2\16*$)
            x
        )
        (\15*$)             # \17 = tool to make tail = \15
    )
    \17                     # tail = \15
)*
x$                          # Require that the end result is 1

```

## Regex (ECMAScript+`(?*)`, ~~195~~ ~~187~~ ~~183~~ bytes

Obsoleted by no longer treating N being square-free as a special case (i.e. is now identical to the above).

## Regex (ECMAScript 2018), ~~198~~ ~~195~~ ~~194~~ ~~186~~ ~~182~~ bytes

Obsoleted by no longer treating N being square-free as a special case and changing `(?=A)(?!B)` to `(?!B)A` (i.e. is now identical to the above).
> 9 votes

# Answer
# Jelly, ~~13~~ ~~6~~ 5 bytes

```
ÆEt0E

```

Try it online!

Still outgolfed... (thanks Erik for -1 byte)

---

**Explanation**

```
ÆE     # get a list of prime exponents (noooo long builtin name)
  t0   # remove zeroes on both sides (leading or trailing)
    E  # all remaining elements are equal

```
> 6 votes

# Answer
# JavaScript (ES6), 87 bytes

Returns **0** for truthy or a non-zero integer for falsy.

```
f=(n,k=2,j,i)=>n%k?j*(P=d=>k%--d?P(d):d==!i)(k)|j-i|(n>1&&f(n,k+1,j||i)):f(n/k,k,j,-~i)

```

Try it online!

### Commented

```
f = (                     // f() = recursive function taking:
  n,                      //   n = input
  k = 2,                  //   k = current factor
  j,                      //   j = reference exponent, initially undefined
  i                       //   i = current exponent, undefined each time we start testing
) =>                      //       the next factor
  n % k ?                 // if k is not a divisor of n:
    j * (                 //   ignore the primality of k if j is still undefined
      P = d =>            //     P() = function testing if k is prime:
        k % --d ?         //       decrement d; if d is not a divisor of k:
          P(d)            //         do a recursive call until it is
        :                 //       else:
          d == !i         //         unless i is already defined: d must not be equal to 1
                          //         (if it is: k is the next prime but does not divide n)
    )(k) |                //   initial call to P() with d = k
    j - i | (             //   if both i and j are defined, they must be equal
      n > 1 &&            //   if n is not yet equal to 1,
      f(n, k + 1, j || i) //   go on with k + 1; if j is undefined, set it to i
    )                     //   (otherwise, stop recursion and return what we have)
  :                       // else:
    f(n / k, k, j, -~i)   //   increment the current exponent and go on with n / k

```
> 6 votes

# Answer
# CJam, ~~30~~ 29 bytes

```
{mFz~)-!\__W=,\0=>\-:mp1#W=&}

```

Try it online!

My first answer after a nearly 2(!)-year break, so it can probably be golfed more. This is a block that takes input as an integer (can also be mapped over for arrays of integers).

## Explanation

```
{        e# Begin block
 mF      e# Factor input, giving an array of primes and their powers
 z~      e# Transpose and dump, giving an array of primes and an array of powers
 )-      e# Check that the powers are the same: subtract each power from the last element
 !       e# Negate to make sure they're all 0
 \__W=,  e# Get the range from 0 to the largest prime minus one
 \0=>    e# Slice that array so it only includes everything larger than the smallest prime
 \-      e# Remove the original primes from the range array
 :mp     e# Check each element for primality. If the input's primes are consecutive,
         e# this will contain no primes
 1#W=    e# Make sure a "1" is not found
 &       e# If the powers are the same AND primes are consecutive, return 1. Otherwise, 0.
}

```
> 5 votes

# Answer
# Stax, ~~5~~ 6 bytes

```
╣♥qJ╬c

```

Run and debug it

Unpacked, ungolfed, and commented, it looks like this.

```
|n    get the exponents of the prime factorization
0:D   trim leading zeroes
:u    array has exactly a single distinct element

```

**Edit:** ~~This doesn't work on `512`. I'll give it some thought and hopefully a fix later.~~ It works now.
> 5 votes

# Answer
# Stax, 9 bytes

1 is truthy, 0 is falsy

```
αAG<└\{┬⌠

```

Run and debug it

**Explanation**

```
|nX0-u%x:^=      # Full Program, unpacked, implicit input
|n               # Exponents of sequential primes in factorization. (eg. 20 -> [2 0 1])
  X              # Save to X register
   0-            # Remove all '0' from array
     u%          # Get unique numbers and get length of array
       x         # Copy back the array saved to X
        :^       # Is it ascending
         =       # Are the two comparisons equal? implicit output

```

Can probably be golfed more, but it covers the cases I was missing in the last solution.
> 3 votes

# Answer
# Java 10, ~~223~~ ~~191~~ ~~178~~ ~~176~~ 168 bytes

```
n->{var s=new java.util.HashSet();for(int f=1,i=1,x,j;n>1;){for(x=++i,j=2;j<x;)x=x%j++<1?1:x;if(x>1){for(j=0;n%i<1&&n>(f=0);n/=i)j++;if(f<1)s.add(j);}}return s.size();}

```

Returns `1` as truthy, and `>=2` as falsey.

Try it online.

**Explanation:**

```
n->{                   // Method with integer parameter and boolean return-type
  var s=new java.util.HashSet();
                       //  Set to keep track of the prime exponents
  for(int f=1,         //  Prime-flag, starting at 1
          i=1,x,j;     //  Index and temp integers
          n>1;){       //  Loop as long as `n` is still larger than 1
    for(x=++i,         //   Set `x` to `i`, after we've increased `i` by 1 first with `++i`
        j=2;           //   Set `j` to 2 (first prime)
        j<x;)          //   Inner loop as long as `j` is still smaller than `x`
      x=x%j++<1?       //    If `x` is divisible by `j`:
         1             //     Set `x` to 1
        :              //    Else:
         x;            //     Leave `x` unchanged
    if(x>1){           //    If `x` is larger than 1 (if `i` is a prime):
      for(j=0;         //     Use `j` as counter, and set it to 0
          n%i<1        //     If `n` is divisible by `i`:
                       //      And loop as long as `n` is still divisible by `i`,
          &&n>         //      and `n` is larger than 0
              (f=0);   //      (and set `f` to 0 at the same time)
          n/=i)        //       Divide `n` by `i`
        j++;           //       And increase `j` by 1
      if(f<1)          //     If the flag `f` is now/still 0:
        s.add(j);}}    //      Add counter `j` to the Set
  return s.size();}    //  Return the amount of items in the Set
                       //  (1 being true, >=2 being false)

```

**Some example inputs:**

`n=15`:

* Flag remains `1` for the first prime 2 (because 15 is not divisible by 2).
* Flag goes from `1` to `0` as soon as we're at the prime 3. Since 15 is divisible by 3, `n` becomes 5 (15/31), and the Set becomes `[] → [1]`.
* Then we check the next prime 5. Since 5 is divisible by 5, `n` becomes 1 (5/51), and the Set remains the same (`[1] → [1]`).
* Now `n=1`, so we stop the outer loop. The Set (`[1]`) only contains one item, the `1` from both adjacent primes 3 and 5, so we return true.

`n=14`:

* Flag goes from `1` to `0` for the first prime 2 (because 14 is divisible by 2). `n` becomes 7 (14/21), and the Set becomes `[] → [1]`.
* Then we check the next prime 3. Since 7 is not divisible by 3, `n` remains the same, and the Set becomes `[1] → [1,0]`.
* Then we check the next prime 5. Since 7 is also not divisible by 5, `n` remains the same, and the Set remains the same as well (`[1,0] → [1,0]`).
* Then we check the next prime 7. Since 7 is divisible by 7, `n` becomes 1 (7/71), and the Set remains the same (`[1,0] → [1,0]`).
* Now `n=1`, so we stop the outer loop. The Set (`[1,0]`) contains two items, the `1` from the non-adjacent primes 2 and 7, and the `0` from the primes 3 and 5, so we return false.

`n=72`:

* Flag goes from `1` to `0` for the first prime 2, because 72 is divisible by 2 (multiple times). So `n` becomes 9 (72/23), and the Set becomes `[] → [3]`.
* Then we check the next prime 3. Since 9 is divisible by 3 (multiple times), `n` becomes 1 (9/32), and the Set becomes `[3] → [3,2]`.
* Now `n=1`, so we stop the outer loop. The Set (`[3,2]`) contains two items, the `3` from prime 2, and the `2` from prime 3, so we return false.
> 3 votes

# Answer
# Husk, 11 bytes

```
Λ§*≈¤≈oṗ←gp

```

Try it online!

Outputs 0 if not a consecutive-prime/constant-exponent number.
> 3 votes

# Answer
# MATL, ~~12 11~~ 10 bytes

```
YFtgYsg)Zs

```

Try it at MATL Online!

Thanks to Luis Mendo for the remove-leading-zeroes part. He also pointed out that swapping truth values is allowed, so this returns **0** for numbers that satisfy the challenge requirements and any positive value otherwise.

Grosso Modo, this generates the exponents of the sequential prime factorization, removes leading zeroes and calculates the standard deviation.
> 3 votes

# Answer
# Octave, 67 bytes

```
@(x)~any(diff(find(h=histc(factor(x),primes(x))))-1)&h(h>0)==max(h)

```

Try it online!

I believe this is the only solution that uses a histogram.

### Explanation:

This makes a histogram, where the variable to be counted are the factors of the input, and placed in the bins `primes(x)`, which is all primes less than the input. We then find the location of the prime factors, takes the difference between each of the indices and subtract one. If there are any elements that aren't zero (i.e. the difference of the indices of prime numbers is not 1), then this will result in a falsy value, otherwise it will return a truthy value.

We then chech that all non-zero elements in the histogram are equal to the maximum element. If there are values that aren't equal then this will result in a falsy value, otherwise it will return a truthy value.

If both those blocks are truthy then our input is a consecutive prime constant exponent number!
> 2 votes

# Answer
# , 16 bytes

Big thanks to FrownyFrog for -8 bytes!

```
(=&#+/\=@#])_&q:

```

Try it online!

## My old solution:

# , 24 bytes

```
[:(1=[:#@~.{.@I.}.])_&q:

```

Try it online!

## Explanation:

`_&q:` prime exponents

`{.@I.}.]` removes the leading zeros by finding the first non-zero element:

```
     }.   drop
       ]  from the list of exponents
{.@       as much items as the first of the
   I.     indices of non-zero elements

```

`1=[:#@~.` tests if all remaining numbers are equal:

```
  [:#@~.  finds the length of the list after removing the duplicates
1=        is it 1?

```
> 2 votes

# Answer
# MATL, 7 bytes

```
0iYFhdz

```

The result is `1` iff input satisfies the requirement.

Try it online! Or verify all test cases

### Explanation

```
0    % Push 0
i    % Push input number
YF   % Exponents of consecutive prime factors
h    % Concatenate horizontally
d    % Consecutive differences
z    % Number of nonzeros. Implicitly display

```
> 2 votes

# Answer
# APL (Dyalog Extended), 28 bytes

```
{f p←`↓⍭⍵⋄(1=≢∪p)∧∨/f⍷⍸1⍭⍳⍵}

```

Try it online!

### How:

```
{f p←`↓⍭⍵⋄(1=≢∪p)∧∨/f⍷⍸1⍭⍳⍵} ⍝ Monadic function, takes an argument ⍵
       ⍭⍵                     ⍝ Prime factors and exponents of ⍵
     `↓                        ⍝ split the resulting matrix in 2 vectors
 f p←                          ⍝ assign the factors to f and the powers to p
         ⋄                     ⍝ then
                          ⍳⍵   ⍝ range [1..⍵]
                        1⍭     ⍝ primality check for each element in the vector
                       ⍸        ⍝ where; returns the indices of truthy values
                     f⍷         ⍝ find the factors; returns a boolean vector
                   ∨/           ⍝ logical OR reduction
                  ∧             ⍝ logical AND
           (   ∪p)              ⍝ unique members of the powers
              ≢                 ⍝ tally; returns the number of elements in the vector
            1=                  ⍝ check if there's only one element

```
> 1 votes

# Answer
# Wolfram Language (Mathematica), 65 bytes

```
Differences[{PrimePi@#,#2}&@@@FactorInteger@#]~MatchQ~{{1,0}...}&

```

Try it online!
> 0 votes

# Answer
# Pari/GP, 63 bytes

```
n->#Set(vector(#(a=factor(n)~),i,[primepi(a[1,i])-i,a[2,i]]))<2

```

Try it online!
> 0 votes

# Answer
# , 14 bytes

```
1#.2~:/\0,_&q:

```

1 in the output indicates consecutive constant exponent.

Try it online!

```
        0,_&q:   zero followed by the prime exponents of input
   2~:/\         for every two consecutive values, 1 if they are different
1#.              convert from base-1, just add them up

```
> 0 votes

# Answer
# Clean, 127 bytes

```
import StdEnv
@n=[]== $n
?n#j= $n
= @n||j==filter@[hd j..last j]&&any(\p=(prod j)^p==n)[1..n]
$n=[i\\i<-[2..n-1]|n/i*i==n&& @i]

```

Try it online!

Defines the function `? :: Int -> Bool` using `$ :: Int -> [Int]` to factorize and `@ :: Int -> Bool` to check primality.
> 0 votes

# Answer
# APL(NARS) 41 chars, 82 bytes

```
{(1=≢∪+/¨{v=⍵⊃v}¨⍳≢v)∧(1↓w)≡¯1↓1πw←∪v←π⍵}

```

{π⍵} is the function factorization of argument ⍵ in the list of prime factors (repeat if one prime appear more time);
{1π⍵} is the function next prime (note that in this case its argument is not a scalar but one array of integers). test:

```
  h←{(1=≢∪+/¨{v=⍵⊃v}¨⍳≢v)∧(1↓w)≡¯1↓1πw←∪v←π⍵}
  (2..30)/⍨h¨2..30
2 3 4 5 6 7 8 9 11 13 15 16 17 19 23 25 27 29 30
  h¨27000 456533 72 10000000
1 1 0 0

```
> 0 votes

---
Tags: code-golf, decision-problem, number-theory, primes
---