text:
Balanced and Centre-Free Sets of Points
Taking in Input
Define a function f as follows:
IF x < 0:
    f(x) = -√|x|
ELSE:
    f(x) = √x

In your programs/functions, each point (x, y) given as input will correspond to the point (f(x), f(y)). For example, if the points (4, -2) and (-1, 5) are given as input, your program will be dealing with the points (2, -√2) and (-1, √5). From now on, we will be referring to points in this format, rather than points in the format given in the input.
You will take in a set/list of points as input which will then be converted to Cartesian points with the function f.
Balanced Sets of Points
Denote by PQ the Euclidean distance from point P to point Q.
A set of points S is balanced if, and only if, for all pairs of distinct points A and B in S, there exists a point C in S such that AC = BC. For example, the set of points {(0, 2), (-√3, -1), (√3, -1)} is balanced because the points in this set are the vertices of an equilateral triangle. Note that this set of points would be taken as input by the program/function as {(0, 4), (-3, -1), (3, -1)}.
Centre-Free Sets of Points
Again, denote by PQ the Euclidean distance from point P to point Q.
A set of points S is centre-free if, and only if, for all triples of distinct points A, B and C in S, there does not exist a point P in S such that AP = BP = CP. For example, the set of points {(0, 2), (-√3, -1), (√3, -1)} is centre-free, but if you add the point (0, 0) to this set, it is no longer centre-free.
Formatting the Output
The output will be in the form of a two-digit binary number. Suppose we are given the set of points S. After having applied the function f to each point (see section "Taking in Input"), the first digit of this binary number will indicate whether this set of points is balanced and the second digit of this binary number will indicate whether this set of points is centre-free. For example, 10 will indicate that the given set of points is balanced, but not centre-free.
Also note that the digits 1 and 0 may be replaced with any truthy and falsy values. As opposed to strings, arrays and ordered pairs are also acceptable.
Test Cases
> {(0, 4), (-3, -1), (3, -1)}
11

> {(0, 4), (3, 1), (3, -1), (0, -4), (-3, -1), (-3, 1)}
01

> {(0, 4), (-3, -1), (3, -1), (0, 0)}
00

> {(0, 4), (-3, -1), (3, -1), (0, -4), (0, 0)}
00

> {(0, 16), (-3, 1),(-12, -4), (0, -4), (12, -4), (3, 1)}
10

Winning Criterion
Make your code as short as possible.
Credits
This was inspired by Problem 1 from IMO 2015. (Great problem, by the way!)

Would an output like [True, False] instead of 10 be acceptable?

@Stephen Yes. 10, [1, 0], [True, False] and TrueFalse are all examples of acceptable output.

If I am correct, the points given by the last test-case are (0,2),(-√3,-1),(√3,-1),(0,-2),(0,0). Furthermore the distance between (0,2) and  each of (-√3,-1),(√3,-1),(0,2) are √12,√12,4 while the distance between (0,0) and each of (-√3,-1),(√3,-1),(0,2) are 2,2,2, but none of the pairs (√12,2),(√12,2),(4,2) contain equal elements. Does this not imply it is not a balanced set?

@JonathanAllan Yargh! I made that one up on the spot by taking a rhombus made of two equilateral triangles and putting a dot in the middle. Fixed!

I guess you want a 10 test-case - would {(0,4),(-¾,¼),(-3,-1),(0,-1),(3,-1),(¾,¼)} work (making, I think, an equilateral triangle along with the midpoints of each of its edges)?

Also for the second test-case I see no C for the pair A=(0,2) and B=(1,√3) so I don't think it is balanced. (I think only 30 of the 66 A,B pairs have a C in that case)

@JonathanAllan Sorry about all the wrong test cases; I got muddled up. Thanks for the 10 test case!

No downvotes so far! :-) :-) :-) I guess this was a bit more well-received than my last challenge...

Jelly, 36 bytes
ạþE€Ṁ
®Œcç€®Ạ
A½×Ṡ×1,ıSµ€©œc3ñ€®Ṁ¬¢,

A full program printing the representation of a list of two ones/zeros.
This relies on theoretical infinite-precision floating point arithmetic, which is, of course, not the case. So here is a (43 byte) version which uses a 1e-10 leeway for the pair-wise distance comparisons it makes:
ạþI€×ȷ10ỊẠ€Ṁ
®Œcç€®Ạ
A½×Ṡ×1,ıSµ€©œc3ñ€®Ṁ¬¢,

Try It Online!
How?
(I'll include the replacement code used in place of E - equals to allow the leeway here)
ạþI€×ȷ10ỊẠ€Ṁ - Link 1: any all-equal distance complex numbers?: list of lists; list
ạþ           - outer-product with absolute difference
  I€         - incremental differences for €ach
    ×ȷ10     - multiply by 10^10
        Ị    - insignificant (abs(z)<=1) (vectorises)
         Ạ€  - all? for €ach
           Ṁ - maximum

®Œcç€®Ạ - Link 2: isBalanced? no-arguments (requires register to be populated - see Main)
®       - recall from register (the points as a list of complex numbers)
 Œc     - pairs
     ®  - recall from register (the points as a list of complex numbers)
   ç€   - call the last link (1) as a dyad for €ach pair
      Ạ - all truthy?

A½×Ṡ×1,ıSµ€©œc3ñ€®Ṁ¬¢, - Main link: list of (x, y) inputs
         µ€            - for €ach (x,y) pair, p:
A                      -   absolute value of p (vectorises)
 ½                     -   square root (vectorises)
   Ṡ                   -   sign of p (vectorises)
  ×                    -   multiply (vectorises)
     1,ı               -   literal [1, 0+1i]
    ×                  -   multiply (vectorises)
        S              -   sum
           ©           - (copy the result to the register)
            œc3        - combinations of length 3
                 ®     - recall from register
               ñ€      - call the next link (1) as a dyad for €ach triple
                  Ṁ    - maximum (1 if any triple has a centre)
                   ¬   - not (0 if any triple has a centre - hence isCentreFree?)
                    ¢  - call the last link as a nilad
                     , - pair with the calculated isCentreFree?
                       - implicit print

The whole reason I added the function f is so that people could store the coordinates as pairs of surds without issues arising with floating point arithmetic. Good job, though!

Python 2, 303 302 bytes
Edit: -1 byte thanks to @Mr.Xcoder
lambda x,y:f((x[0]-y[0])**2+(x[1]-y[1])**2)
f=lambda x:x<0and-f(-x)or x**.5
v=lambda a,b,p:abs(d(a,p)-d(b,p))<1e-9
def e(k):k=[(f(a),f(b))for a,b in k];print+all(any(v(a,b,c)for c in k)for a in k for b in k if a!=b),1-any(any(v(a,b,p)*v(b,c,p)for p in k)*len({a,b,c})>2for a in k for b in k for c in k)

Try it online!

-1e-9<d(a,p)-d(b,p)<1e-9 means abs(d(a,p)-d(b,p))<1e-9 (302 bytes)

I do Python golf a lot, but I've never come across the all and any functions. What do they do?

@J843136028 all returns true if all the values in the argument (which must be iterable) are true, while any returns true if at least on of the values in the argument are true.

@HalvardHummel Thank you!


text:
Is this a valid Takuzu board?
Takuzu is a logic game in which you have to complete a grid with cells containing 0s and 1s. The grid must follow 3 rules:

No three horizontal or vertical consecutive cells can be the same.
There must be an equal number of 0s and 1s in each row and column.
No two rows can be the same, and no two columns can be the same.

Let's look at a finished grid:
0011
1100
0101
1010

As you can see, this board follows rule 1, 2 and 3. There are no three horizontal or vertical cells that are the same, all the rows and columns contain an equal number of 0s and 1s, and no two rows and no two columns are the same.
Let's look at a grid that isn't valid:
110100
010011
011010
101100
100011
001101

There's a bunch of problems with this grid. For example, row 5 has three 0s in a row, and column 2 has three 1s in a row, followed by three 0s. Therefore, this is not a valid grid.
Task:
Your task is to make a program which, given a 2D array of n * n 0s and 1s, verifies the board to see if it's a valid, finished Takuzu board.
Examples:
0011
1100
0101
1010

This board follows all the rules, and is therefore a valid Takuzu board. You must return a truthy value for this.
11
00

This is not a valid board - row 1 doesn't follow rule 2. You must return a falsey value for this.
100110
101001
010101
100110
011010
011001

This is not a valid board, it fails (only) due to rule 3 - the first and fourth rows are the same.
110100
001011
010011
101100
100110
011001

This is not a valid board, it fails (only) due to rule 3 - the first and fourth columns are the same.
011010
010101
101100
010011
100110
101001

This is a valid board.
Rules and Specs:

You can assume that all boards are square of dimensions n * n, where n is a positive even integer.
You can assume that all boards are finished.
You may take input as a 2D array containing values signifying 0 and 1, or as a string.
You must output consistent truthy and falsey values for truthy and falsey boards, and the values representing "truthy" and "falsey" cannot be the same.

This is code-golf, so shortest code in bytes wins!

Related

I know this as 0h h1...

@EriktheOutgolfer Yeah, I started off only knowing this as 0h h1 as well, but Takuzu is the original name of the puzzle.

@EriktheOutgolfer I always knew it as "Binary Puzzle" or "Subiku", but "Takuzu" is as Qwerp-Derp mentioned the original name.

Some more test cases would be nice (I’m missing large, valid boards.)

May we print a falsy for truthy and vice versa? May we take an array of strings?

When taking a single string, can we omit the linebreaks?

@Titus Yes, you may.

Brachylog, 20 18 bytes
≠\≠,?¬{∋s₃=|∋ọtᵐ≠}

Try it online!
Explanation
≠                           All rows are different
 \                          Transpose
  ≠                         All columns are different
   ,?                       Append the list of rows to the list of columns
     ¬{          }          It is impossible that:
       ∋                      A row/column of the matrix…
        s₃=                   …contains a substring of 3 equal elements
           |                Or that:
            ∋ọ                The occurences of 1s and 0s in a row/column…
              tᵐ≠             …are not equal

"Append the list of rows to the list of columns" smart way to golf it! And here I thought your 20-byte answer was to the point and golfed as much as could be. I see Brachylog is as good in validating the matrices as it is in solving them. :)

Shouldn't it output false for this?

@H.PWiz Good find, thanks. Reverted to the 18 bytes version that worked.

@LuisMendo I'm just putting all rows and all columns in the same list basically.

Newest version fails for this input.

@Zgarb Correct, thanks. That's the third time I've had to rollback an edit, the opening post is in desperate need of better test cases...

Husk, 19 18 bytes
S=‼(Tf§=LṁDum(ṁ↑2g

Try it online!
1 byte saved thanks to H.PWiz!
The main idea is applying a series of transformations to the input that are identities for a valid board and checking if the final result is the same as the original input.
Explanation
S=‼(Tf§=LṁDum(ṁ↑2g
            m(ṁ↑2g    in each line, take at most two items for each sequence of equal items
           u          remove duplicate lines
     f§=LṁD          keep only those lines where the sum of each element doubled is equal to the length of the line
    T                 transpose the matrix (swap rows with columns)
  ‼                   do all the previous operations again
S=                    check if the final result is equal to the original input

Some reshuffling to remove a )

@H.PWiz that was almost obvious, dumb me!

Jelly, 17 bytes
-*S;E3Ƥ€F$TȯQZµ⁺⁼

Try it online!
-6 bytes thanks to miles and Jonathan Allan.

I believe you can shorten this to 21 bytes. TIO

@miles ...maybe even 19 bytes?

@JonathanAllan that's 18 bytes...yeah you did the µZ$⁺ thing again :p...and 17 bytes by swapping a bit :D now I beat brachylog hehe

@EriktheOutgolfer Not anymore, it's a tie!

@JonathanAllan Nice. Also I believe this is the first time the prefix/infix quick I added has been useful.

Mathematica, 143 bytes
And@@Flatten@(((s=#;Equal@@(Count[s,#]&/@{0,1})&&FreeQ[Subsequences@s,#]&/@{{1,1,1},{0,0,0}})&/@#)&&(DeleteDuplicates@#==#)&/@{#,Transpose@#})&

input

[{{0, 0, 1, 1}, {1, 1, 0, 0}, {0, 1, 0, 1}, {1, 0, 1, 0}}]

Python 2, 127 bytes
a=input()
n=len(a)
b=zip(*a)
print[n/2]*n*2==map(sum,a+b)>len(set(a))==len(set(b))==n<'0, 0, 0'not in`a+b`>'1, 1, 1'not in`a+b`

Try it online!
Reads a list of n n-tuples as input.
I could output by exit code by writing 1/(…) instead of print… but it feels scummy. Should I?
Explanation
n is the size of the board; b is a list of columns (transpose of a). The rest is one long chained comparison:

[n/2]*n*2==map(sum,a+b) checks rule 2. Each row and column should sum to n/2.
map(sum,a+b)>len(set(a)) is always true (list > int).
len(set(a))==len(set(b))==n checks rule 3.
n<'0, 0, 0' is always true (int < str).
'0, 0, 0'not in`a+b`>'1, 1, 1'not in`a+b` checks rule 1. `a+b` is the string representation of all the rows and columns; for the example input on TIO it is
"[(0, 0, 1, 1), (1, 1, 0, 0), (0, 1, 0, 1), (1, 0, 1, 0), (0, 1, 0, 1), (0, 1, 1, 0), (1, 0, 0, 1), (1, 0, 1, 0)]"

The `a+b`>'1, 1, 1' in the center is always true since this string is guaranteed to start with "[", which is greater than "1".

If you want to output by exit code, you could do [n/2]*n*2==map(sum,a+b)>len(set(a))==len(set(b))==n<'0, 0, 0'not in`a+b`>'1, 1, 1'not in`a+b`>x, which is 2 bytes shorter than division and results in a NameError for truthy inputs.

MATL, 27 bytes
,G@?!]tEqts~w7BZ+|3<bXBSdvA

Input is a matrix containing 0 and 1. Output is 0 for falsy, 1 for truthy.
Try it online! Or see test cases: 1, 2, 3, 4, 5.
Explanation
,       % Do twice. First iteration will use the input, second its transpose
  G     %   Push input
  @     %   Push iteration index: first 0, then 1
  ?     %   If nonzero
    !   %     Transpose
  ]     %   End
  t     %   The top of the stack contains the input or its transpose. Duplicate
  Eq    %   Convert to bipolar form, i.e. replace 0 by -1
  t     %   Duplicate
  s     %   Sum of each column
  ~     %   Negate. If all results are true, condition 2 is fulfilled
  w     %   Swap. Moves copy of bipolar input/transposed input to top
  7B    %   Push [1 1 1], obtained as 7 converted to binary
  Z+    %   2D convolution. Gives a matrix of the same size as the input
  |3<   %   Is each entry less than 3 in absolute value? If all results are true,
        %   condition 1 is fulfilled
  b     %   Bubble up. Moves copy of input/transposed input to top
  XB    %   Convert each row from binary to a number
  Sd    %   Sort, consecutive differences. If all results are nonzero, condition 3
        %   is fulfilled
  v     %   Concatenate all results so far into a column vector
  A     %   True if all entries are nonzero
        % End (implicit). Display (implicit)

Husk, 27 25 bytes
Λ§&Λȯ¬VEX3§&Λ§=#0#1S=uSeT

Input is a list of lists and output is 1 for True and 0 for False
Try it online!
Explaination
                      SeT    Create a list with the input and itself transposed
Λ                            Is the following function true for all in the list
 §&                          And the results of the following functions
   Λȯ¬VEX3                     Test for rule 1
          §&                   The and of:
            Λ§=#0#1                Test for rule 2
                   S=u             Test for rule 3

Test 1
Λȯ¬VEX3
Λ         Is it True for all ...
   V      Are any of the ...
     X3   Substrings of length 3 ...
    E     All equal
 ȯ¬       Logical not

Test 2
Λ§=#0#1
Λ         Is it true for all that ...
 §=       The results of the two functions are equal
   #0         Number of 0s
     #1       Number of 1s

Test 3
S=u
S=    Is the result of the following function equal two its argument
  u   Remove duplicates

Pyth, 31 bytes
Thanks a lot to @Leaky Nun.
.Asm++mqy/k\0lQdm<hk3srL8d{Id,C

Verify all the test cases or Try it here!

Pyth,  48 46 44  42 bytes
This is the initial solution.
&{IQ&{I.TQ.Am&q/d\0/d\1!+/d*3\0/d*3\1sC,.T

Verify all the test cases or Try it here!

&{IQ&{I.TQ.Am&q/d\0/d\1!+/d*3\0/d*3\1sC,.T     Full program with implicit input.

 {IQ                                           Is the input invariant under deduplicating?
&    {I.TQ                                     And is its transpose invariant too?
                                        .TQ    Transpose.
                                           Q   The input.
                                     sC,       Zip the above, [^, ^^] (and flatten).
    &                                          And is the following condition met?
          .Am                                  All elements are truthy when mapping over ^^.
              q/d\0/d\1                        There are as many 0s as 1s.
             &         !+/d*3\0/d*3\1          And there are no runs of 3 equal elements.

Retina, 129 89 85 bytes
.+
$&,$&
O#$`.(?=.*,)
$.%`
.+
$&;$&
+`(01|10)(?=.*;)

1ms`(.)\1\1|\d,?;|(\D\d+\b).*\2

Try it online! Outputs 0 for valid, 1 for invalid. Edit: Saved 4 bytes thanks to @MartinEnder. Explanation:
.+
$&,$&

Duplicate each row with , separators.
O#$`.(?=.*,)
$.%`

Transpose the first duplicate.
.+
$&;$&

Duplicate again, this time with ; separators.
+`(01|10)(?=.*;)

Delete all matching pairs of digits that precede a semicolon.
1ms`(.)\1\1|\d,?;|(\D\d+\b).*\2

Check to see whether any column or row fails any of the rules; (.)\1\1 checks for three identical digits in a row, \d,?; checks for an unpaired digit and (\D\d+\b).*\2 checks for a duplicate.

If the purpose of the (...).* in the last stage is just to do max(matches,1) then you can save three bytes by using a 1 in the configuration instead.

And .\b\d+\b can be \D\d+\b.

@MartinEnder Originally I replaced invalid output with no output and tested it at the end... I eventually honed it down to a single test at the end and realised I could omit the leading .* I had previously been using but didn't think to use a configuration to limit the result, thanks!

Java 8, 350 326 325 312 303 299 298 259 255 bytes
int r,z,c,p,i,j,k,d,u,v=1;int c(int[][]b){v(b);k=v-=u=1;v(b);return r;}void v(int[][]b){String m="",x;for(d=b.length;j<d|k<d;k+=u,j+=v,r=m.contains(x)|z!=0?1:r,m+=x)for(x="#",c=0,k*=u,j*=v;j<d&k<d;z+=i|i-1,c*=i^p^1,x+=p=i,r=++c>2?1:r,k+=v,j+=u)i=b[k][j];}

Returns 0 when it's a valid board; 1 if it's invalid for one or more of the three rules.
-95 bytes thanks to @Nevay.
Explanation:
Try it here.
int r,z,c,p,i,j,k,d,u,v=1;
                     // Temp integers on class-level

int c(int[][]b){     // Method (1) with int-matrix parameter and int return-type
  v(b);              //  Validate the rows
  k=v-=u=1;          //  Switch rows with columns, and reset `u` to 1
  v(b);              //  Validate the columns
  return r;          //  Return the result
}                    // End of method (1)

void v(int[][]b){    // Separated method (2) with int-matrix parameter and no return-type
  String m="",s;     //  Two temp Strings to validate uniqueness of rows
  for(d=b.length;    //  Set the dimension of the matrix to `d`
      j<d|k<d        //  Loop (1) as long as either `j` or `k` is smaller than `d`
    ;                //   After every iteration:
     k+=u,j+=v       //    Increase the loop-indexes
     r=m.contains(s) //    If we've found a duplicated row,
     |z!=0?          //    or if the amount of zeroes and ones on this row aren't equal
      1:r,           //     Set `r` to 1 (invalid due to either rule 2 or 3)
     m+=s)           //    Append the current row to the String `m`
    for(s=",",       //   Set String `x` to a separator-character
        c=0,         //   Reset the counter to 0
        k*=u,j*=v,   //   Increase the loop-indexes
        j<d&k<d      //   Inner loop (2) as long as both `j` and `k` are smaller than `d`
     ;               //    After every iteration:
      z+=i|i-1,      //     Increase or decrease `z` depending on whether it's a 0 or 1
      c*=i^p^1,      //     Reset `c` if current digit `i` does not equal previous `p`
      s+=p=i,        //     Set previous `p` to current digit, and append it to String `s`
      r=++c>2?       //     If three of the same adjacent digits are found:
         1:r;        //      Set `r` to 1 (invalid due to rule 1)
        k+=v,j+=u)   //      Increase the loop-indexes
      i=b[k][j];     //    Set `i` to the current item in the matrix
                     //   End of inner loop (2) (implicit / single-line body)
                     //  End of loop (2) (implicit / single-line body)
}                    // End of separated method (2)

R, 114 107 bytes
-7 thanks to Giuseppe, calling functions out of order and really compressing the conditions down
function(x)any(f(x),f(t(x)))
f=function(x)c(apply(x,1,function(y)max(rle(y)$l)>2+mean(y)-.5),duplicated(x))

Try it online!
This just applies the rules to the columns of the matrix, then the columns of the transpose of the matrix.
Takes input in the form:

matrix(c(0,0,1,1,1,1,0,0,0,1,0,1,1,0,1,0), ncol=4)

Which is just how R takes 2D arrays.
Outputs TRUE for failures, FALSE for passes.

107 bytes

General updates: used mean(y)-.5 inside the internal f function to get the means rather than colMeans, and made g anonymous. It will add warnings for converting double to logical in the call to any but that's OK.

@Giuseppe Thanks! I really like that combined apply, very clever change! I had it as 2 seperate applys in an early stage and didn't realise how cleanly you could combine them.

here's a way of getting input in a little more nicely

Perl 6, 100 93 bytes
Junctions FTW! They save 7 bytes.
For the time being, this seems to be beating all the other submissions written in non-golfy languages. Yippie!
{!max (@(.map(*.join)).&{.repeated| |.map:{$_~~/000|111/|.comb(0)-.comb(1)}}for @^a,[Z] @^a)}

Try it online!
Explanation: It's a block that takes the board as list of lists. We make a transpose with [Z] @^a (reduce the list of lists with zip operator). So @^a,[Z] @^a is a list of the board and its transpose. We loop over it with for which works exactly like map, just being 1 char cheaper in this case.
Inside, we first join the lists constituting rows into strings, so we have list of strings instead of list of lists (@(.map(*.join))). Then we use an anonymous block on it (.&{...}), where we actually evaluate the rules. We'll evaluate them only row-wise. (Since we do it for the original array and the transpose as well.)
To save quite some !'s, we use a bit of logic and instead of testing (NO repeated rows) AND (NO 3 consecutive same symbols) AND (NOT different counts of 0 and 1), we test NOT[ (repeated rows) OR (3 consecutive same symbols) OR (different counts) ]. That's what we do in the anonymous block: .repeated gives all rows that occur more than once, then we map over the rows, try to match 3 consecutive symbols using a regex, and subtract the counts of 0's and 1's. These are OR'red with the |. (Actually it creates a very powerful thing called a junction, but we don't use any of its powers :)) After all of this, we get a list of 2 "bools" (uncollapsed junctions). We finally or them (using max) and negate (!), which gives the desired result.

J, 40 38 55 bytes
0=[:([:+/^:_(3(0=3|+/)\"1 ]),:-.@~:,:#=[:+/"1+:@])|:,:]

Try it online!
Defines a function taking a square matrix as input.
At least it's beating Pyth (for now...) (erroneously). I should go back to counting the emoji hidden in my code since J also lends itself well to that:
[: /^: :1 |: :] :-.@ :# :@] :~@
Explanation (slightly outdated)
This looks different from my answer, and I may get to updating it. Parts of it are still the same -- I just was not checking for rule 3 for and improperly checking for rule 2 before.
Split into a few functions and ungolfed:
join_trans  =. |: ,: ]
part_3      =. 3 (0 = 3 | +/)\"1 ]
f           =. 1 - 2 * ]
main        =. 0 = [: ([: +/^:_ part_3 , f) join_trans

join_trans
|: ,: ]
|:       Transpose
   ,:    Laminated to
      ]  Input

This joins the transpose of the matrix to itself, creating an array of matrices.
part_3
3 (0 = 3 | +/)\"1 ]
                  ]  Input (matrix and transpose)

This checks the sum of partitions of 3 row-wise to see if it is 3 or 0 (since either of these means an invalid board), returning 1 if it is and 0 otherwise. It operates on both the matrix and its transpose since it's given both.
f
1 - 2 * ]

For lack of a better name, I call this f. It replaces the 0s with _1 and leaves the 1s unchanged. This is to allow me to eventually check if the number of 0s and 1s are equal in each row and column (the sum of each of the rows should be 0).
main
0 = [: ([: +/^:_ part_3 , f) join_trans
                             join_trans  Join transpose to input
                 part_3 , f              Apply the validity checks and join them
           +/^:_                         Sum until it converges
0 =                                      Equate to 0

Basically, I leverage the fact that I've set it up so that f join_trans and part_3 join_trans both should sum to 0 iff the board is valid. part_3 should be all zeroes for a valid board and the entirety of f should sum to zero for a valid board, meaning that the sum of their sums is 0 only for a valid board.

At least it's beating Pyth (for now...). - I really need to golf my answer

@Mr.Xcoder haha yeah, you always seem to pull through which is why I added the "for now" bit. Not that my answer doesn't have room for golfing -- I just don't know how to do it too well.

You can remove that part now

This code for 33 bytes should be equivalent to yours */@,@,&(~:,(0~:3|3+/\]),#=2*+/)|:

Haskell, 137 136 127 bytes
9 bytes saved thanks to Lynn!
import Data.List
j=isSubsequenceOf
l x=x==nub x&&and[sum y*2==length x&&not(j[0,0,0]y||j[1,1,1]y)|y<-x]
g x=l x&&l(transpose x)

Try it online!

Roll both alls into one and:  l x=x==nub x&&and[sum y*2==length x&&not(j[0,0,0]y||j[1,1,1]y)|y<-x]

@Lynn Thanks! I was trying to roll those two together for a while.  Don't know why I couldn't figure that out.

Could you change j=isSubSequenceOf to j x=isSubSequenceOf[x,x,x]?

@Cyoce Seems to lose me a byte. If you have a way of doing it that saves me a byte I'd be happy to implement it.  The idea seems like a good one.

On mobile, hmmm... Maybe instead of j a b invoke (and define) it as a#b?

@Cyoce Same byte count unfortunately.

Dyalog APL, 64 52 51 49 48 bytes
Requires ⎕IO←0
{⍲/{(∨/∊⍷∘⍵¨3/¨⍳2)∧((⊢≡∪)↓⍵)∧∧/(≢=2×+/)⍵}¨⍵(⍉⍵)}

Try it online!

Python 3, 187 bytes
lambda m,c=lambda m:all([len({*m})==len(m),sum(~-("000"in x)*~-("111"in x)and x.count("1")==x.count("0")for x in m)==len(m)]):c(["".join(x[i]for x in m)for i in range(len(m[0]))])and c(m)

Try it online!
Takes input as a list of lines.

187 bytes

171 bytes

147 bytes, based on @Mr.Xcoder's suggestion.

05AB1E, 29 bytes
ø‚D€ÙQIDøì©O·IgQP®εŒ3ù€Ë_P}PP

Try it online!
Explanation
Rule: 3
ø‚        # pair the input with the zipped input
  D       # duplicate
   €Ù     # deduplicate each
     Q    # check for equality with the unmodified copy

Rule: 2
IDøì          # prepend zipped input to input
    ©         # store a copy in register for rule 1
     O        # sum each row/column
      ·       # double
       IgQ    # check each for equality to length of input
          P   # product

Rule: 1
®ε            # apply to each row/column in register
  Œ3ù         # get sublists of length 3
     €Ë       # check each if all elements are equal
       _      # logical not
        P     # product
         }    # end apply
          P   # product

Then we take the product of the result of all 3 rules with P

PHP, 245+1 bytes
ew this is bulky. linebreaks are for reading convenience only:
$t=_;foreach($a=($i=str_split)($s=$argn)as$i=>$c)$t[$i/($e=strlen($s)**.5)+$i%$e*$e]=$c;
for(;$k++<2;$s=$t)$x|=preg_match("#000|111|(\d{"."$e}).*\\1#s",chunk_split($s,$e))
|($m=array_map)(array_sum,$m($i,$i($s,$e)))!=array_fill(0,$e,$e/2);echo!$x;

Takes a single string without newlines, prints 1 for truthy, nothing for falsy.
Run as pipe with -nR or try it online.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Perfect, Germain, Vampire, Mersenne! (Don't forget narcissistic)

Six is a number perfect in itself, and not because God created all things in six days; rather, the converse is true. God created all things in six days because the number six is perfect.

I am fascinated by numbers. As were Sophie Germain and Marin Mersenne. To be more specific, these two were fascinated by primes: a number with only two integer divisors: itself and 1. In fact, they were so fascinated by primes that classes of primes were named after them:
A Mersenne prime is a prime number which can be generated by the formula 2p - 1 where p is a prime. For example, 7 = 2^3 - 1 therefore 7 is a Mersenne prime.
A Germain prime is similar. It is a prime number that when plugged into the formula 2p + 1 it also produces a prime. E.g. 11 is Germain as 2*11 + 1 = 23 which is prime.
But now let's move on to the next three numbers: perfect, vampire and narcissistic numbers.
A perfect number is very easy to understand. It can be easily defined as

A number where all its divisors except itself sum to itself. For example, 6 is a perfect number as the divisors of 6 (not including 6) are 1,2,3 which sum to make 6.

A vampire number may be the most difficult to code. A vampire number is a number whose digits can be split into two numbers, of equal length, made from all those digits, that when multiplied, produce the original number. Leading 0s aren't allowed in either of the numbers E.g. 136,948 = 146 x 938
Finally a narcissistic number, probably the hardest to understand. A narcissistic number is a number in which the individual digits, raised to the power of the total number of digits sum to make the original number. A single digit number has to be narcissistic.
For example, 8,208 is narcissistic:
84 + 24 + 04 + 84 = 4,096 + 16 + 0 + 4,096 = 8,208
Your task is to create a program that will take an integer and return what category it fits into. The categories are Mersenne, Germain, Perfect, Vampire, Narcissistic and False. Every number that doesn't fit into the first five categories is False. False doesn't have to necessarily be a falsy value.
If a value fits in more than one category, e.g. 3, you may output any correct result.
Output can be in any form, for example, 6 different numbers, as long as you say what it is in your answer.
Even if it is shorter, you aren't allowed to hard code each number as that ruins maths.
This is a code-golf so shortest code wins!
Examples
Input -> Output

10 -> False
7 -> Mersenne
8208 -> Narcissistic
28 -> Perfect
153 -> Narcissistic
2 -> Germain
17 -> False
16,758,243,290,880 -> Vampire
31 -> Mersenne
33,550,336 -> Perfect
173 -> Germain
136,948 -> Vampire

We seem to have a challenge for almost all of these tasks individually. Grouping a bunch of them together doesn't make this not a duplicate in my eyes, but I won't hammer yet in case the community disagrees.

FWIW I, too, think this is a duplicate

Is an incorrect answer due to a precision error okay?

Out of curiosity, are there any numbers which fit in more than 1 category?

@SocraticPhoenix 3, stated in the challenge.

@Okx yes, precision errors do not need to be handled

@mathmandan yes, I meant narcissistic. My bad.

05AB1E, 43 40 39 bytes
Lo<¹å¹p&¹·>p¹p&¹Ñ¨OQ¹œε2ä}P¹å¹S¹gmOQ)Xk

-1 for False, 0 for Mersenne, 1 for Germain, 3 for Perfect, 4 for Vampire, and 5 for Narcissistic.
Try it online!

.²p isn't enough I think, floats are prime in 05AB1E, and .² may return a float.

@EriktheOutgolfer Fixed.

Pyth, 71 bytes
x[.EmqQ*shdsed.cs.pM.cK`Q/lK2 2qsP{*MyPQQ&P_hyQP_Q<.&QhQP_QqQsm^sdlKK)1

Try it here! or Verify the test cases.
Alternative solution, 71  bytes:
x[.EmqQ*shdsed.cs.pM.cK`Q/lK2 2qsP{*MyPQQ&P_hyQP_Q&.AjQ2P_QqQsm^sdlKK)1

Try it here! or Verify the test cases.
This returns -1 for False, 0 for Vampire, 1 for Perfect, 2 for Sophie Germain, 3 for Mersenne and 4 for Narcissistic. In case more are truthy, this picks the one with the lowest index. Unfortunately, this memory errors for the following test cases: 33550336, 16758243290880.

Explanation
Vampire (29 bytes)
.EmqQ*shdsed.cs.pM.cK`Q/lK2 2

                  .c `Q/lK2      Get all combinations of the input's digits of half its length.
                .pM              Get all possible permutations of each.
             .cs            2    Get all possible two-number combinations, flattened.
.EmqQ*shdsed                     Check if any has the product equal to the input.

Let's go through an example. Let's assume our input is 1260.

First of all, we get the all the possible combinations of 2 digits (number_of_digits / 2). We get ['12', '16', '10', '26', '20', '60'].
Then, we get the possible permutations of each, [['12', '21'], ['16', '61'], ['10', '01'], ['26', '62'], ['20', '02'], ['60', '06']].
We flatten that (['12', '21', '16', '61', '10', '01', '26', '62', '20', '02', '60', '06']) and get all the possible 2-element combinations. This list is quite long:
[['12', '21'], ['12', '16'], ['12', '61'], ['12', '10'], ['12', '01'], ['12', '26'], ['12', '62'], ['12', '20'], ['12', '02'], ['12', '60'], ['12', '06'], ['21', '16'], ['21', '61'], ['21', '10'], ['21', '01'], ['21', '26'], ['21', '62'], ['21', '20'], ['21', '02'], ['21', '60'], ['21', '06'], ['16', '61'], ['16', '10'], ['16', '01'], ['16', '26'], ['16', '62'], ['16', '20'], ['16', '02'], ['16', '60'], ['16', '06'], ['61', '10'], ['61', '01'], ['61', '26'], ['61', '62'], ['61', '20'], ['61', '02'], ['61', '60'], ['61', '06'], ['10', '01'], ['10', '26'], ['10', '62'], ['10', '20'], ['10', '02'], ['10', '60'], ['10', '06'], ['01', '26'], ['01', '62'], ['01', '20'], ['01', '02'], ['01', '60'], ['01', '06'], ['26', '62'], ['26', '20'], ['26', '02'], ['26', '60'], ['26', '06'], ['62', '20'], ['62', '02'], ['62', '60'], ['62', '06'], ['20', '02'], ['20', '60'], ['20', '06'], ['02', '60'], ['02', '06'], ['60', '06']]

The next step is getting the product of each pair:
[252, 192, 732, 120, 12, 312, 744, 240, 24, 720, 72, 336, 1281, 210, 21, 546, 1302, 420, 42, 1260, 126, 976, 160, 16, 416, 992, 320, 32, 960, 96, 610, 61, 1586, 3782, 1220, 122, 3660, 366, 10, 260, 620, 200, 20, 600, 60, 26, 62, 20, 2, 60, 6, 1612, 520, 52, 1560, 156, 1240, 124, 3720, 372, 40, 1200, 120, 120, 12, 360]

And then compare to the input:
[False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, True, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False]

Finally, the last step is checking if any value is truthy. And there is one (at index 19 into the list). Hence, this returns a truthy value for 1260, thanks to the pair [21, 60].

Perfect (10 bytes)
qsP{*MyPQQ

q        Q   Is equal to the input?
 s           Sum.
   {*MyPQ    Its divisors.
  P          Popped (since we want the proper divisors).

Sophie Germain (9 bytes)
&P_hyQP_Q

      P_Q    Is the input prime?
 P_hy        Is the input doubled + 1 prime?
&            Logical AND.

Mersenne (9 bytes)
<.&QhQP_Q

<             Is smaller?
 .&             Bitwise AND between:
   Q              The input
    hQ             And the input + 1
              than:
      P_Q       Is the input prime?

This tests if the input + 1 is a power of two (i.e. if it is a Mersenne number), and then performs the primality test. In Python, bool is a subclass of int, so truthy is treated as 1 and falsy is treated as 0. To avoid checking explicitly that one is 0 and the other is 1, we compare their values using < (since we only have 1 such case).
In the alternative approach, this part is changed to &.AjQ2P_Q. This works as follows:
&.AjQ2P_Q

   jQ2      The input in binary as a list of digits.
 .A         Are all truthy (i.e equal to 1)?
&     P_Q   ... And is prime?

This uses the fact that any number of the form 2n - 1 only consists of 1 when written in binary, and also checks if it is prime.
Narcissistic (10 bytes)
qQsm^sdlKK

q            Is equal?
 Q           The Input
   m     K   Map over the string representation of the input.
    ^sdlK    Raise each digit to the power of the number of digits the input has.
  s          Summed.

When it comes to the rest of the code, [...) builds a list of bool values and x[...)1 gets the index of the first truthy element.

Jelly, 53 bytes
“+1l2Ḟ⁼¡Ḟ$ÆPȧÆP“_1HÆPȧÆP“ÆḌS⁼“DŒ!œs€2ḌP€ċ“D*L$S⁼”v€TX

Try it online!
Returns 1 for Mersenne, 2 for Germain, 3 for Perfect, 4 for Vampire, 5 for Narcissistic and 0 for False. Returns random in case many are true.

05AB1E, 51 bytes
"p¹p* "D">2.nDîpsïÿ<;ÿÑ¨OQ œε2ä}P¹å s¹gmOQ"#ε.V}ā*à

Try it online!
Returns 1 for Mersenne, 2 for Germain, 3 for Perfect, 4 for Vampire, 5 for Narcissistic and 0 for False. Returns max in case many are true.

Lo<så to check if it is a power of 2 - 1.

Python 2, 292 286 274 bytes
-2 bytes thanks to @Okx
-4 bytes thanks to @Mr.Xcoder
lambda n:[n&-~n<a(n),a(n)&a(2*n+1),sum(k*(n%k<1)for k in range(1,n))==n,any(len(c)%2<1<n==int(j(c[::2]))*int(j(c[1::2]))for c in permutations(`n`)),sum(int(d)**len(`n`)for d in`n`)==n,1].index(1)
a=lambda n:all(n%k for k in range(2,n))*~-n>0
j=''.join
from itertools import*

Try it online!
Output is 0 for mersenne, 1 for germaine, 2 for perfect, 3 for vampire, 4 for narcissistic and 5 for false.

Ungolfed
from itertools import*
f=lambda n:
  [
    n&-~n == 0 and a(n),                               # Is n a Mersenne prime?
    a(n) and a(2*n+1),                                 # Is n a Germain prime?
    sum(k for k in range(1,n) if n%k<1)==n,            # Is n a perfect number?
    any(len(c)%2<1<                                    # Is n a vampire number?
      n==int(''.join(c[:len(c)/2]))*int(''.join(c[len(c)/2:]))
      for c in permutations(`n`)),
    sum(int(d)**len(str(n)) for d in str(n))==n,       # Is n a narcissistic number?
    1
  ].index(1)                                           # Get the first position
                                                       # of a 1 (or True) in the list
a=lambda n:False if n<2 else all(n%k for k in range(2,n)) # primality check

286 bytes. You had an unneeded space.

272 bytes. >0 is redundant in the lambda, as bool is a subclass of int.

@Mr.Xcoder An output of 1 is required for the Germain test. Without >0 the code fails to recognise Germain primes.

@ovs Ok, sorry. I missed that

Mathematica, 275 bytes
If[!FreeQ[(S=Select)[2^Range@#-1,PrimeQ],#],1,If[!FreeQ[S[Prime@Range@#,PrimeQ[2#+1]&],#],2,If[PerfectNumberQ@#,3,If[!FreeQ[Times@@FromDigits/@#&/@S[Subsets[Tuples[v=(j=IntegerDigits)@#,{(k=IntegerLength)@#/2}],{2}],ContainsAll[Flatten@#,v]&],#],4,If[Tr[j@#^k@#]==#,5,6]]]]]&

thanx to @Mr. Xcoder for letting me know that I don't have to use the string-names!

Wait how did you post this? It was closed 15 minutes ago.

@cairdcoinheringaahing Client-side checks.

275 bytes: If[!FreeQ[(S=Select)[2^Range@#-1,PrimeQ],#],1,If[!FreeQ[S[Prime@Range@#,PrimeQ[2#+1]&],#],2,If[PerfectNumberQ@#,3,If[!FreeQ[Times@@FromDigits/@#&/@S[Subsets[Tuples[v=(j=IntegerDigits)@#,{(k=IntegerLength)@#/2}],{2}],ContainsAll[Flatten@#,v]&],#],4,If[Tr[j@#^k@#]==#,5,0]]]]]&. You do not have to use the exact strings, you may use any 6 consistent values.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Draw some ASCII stars
Write a program or function that draws an ASCII star, given the size of the arms as input.
Here's a star of size 1
_/\_
\  /
|/\|

Here's a star of size 2
   /\
__/  \__
\      /
 \    /
 | /\ |
 |/  \|

Here's a star of size 3
     /\
    /  \
___/    \___
\          /
 \        /
  \      /
  |  /\  |
  | /  \ |
  |/    \|

And so on.
Input
A single positive integer in any convenient format, n > 0.
Output
An ASCII-art representation of a star, following the above rules. Leading/trailing newlines or other whitespace are optional, provided that the points line up appropriately.
Rules

Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
Standard loopholes are forbidden.
This is code-golf so all usual golfing rules apply, and the shortest code (in bytes) wins.

Is it just my screen, or do the stars look abnormally tall and thin?

Stupid ASCII and its lack of shallow slants...

@cairdcoinheringaahing The font used by SE isn't square - there's significant whitespace between lines, which increases the distortion.

Charcoal, 20 17 bytes
-3 bytes thanks to Neil.
Ｎν↙ν↑↑ν↖ν ×_ν↗ν‖Ｍ

Try it online! Link is to verbose version.
I'm pretty happy with this golf so...
Explanation
Ｎν                 take a number as input and store in ν
  ↙ν               print / ν times downwards to the left
    ↑              move up once
     ↑ν            print | ν times upwards
       ↖ν          print \ ν times upwards to the left
                   print a space
          ×_ν      print _ ν times
             ↗ν    print / ν times upwards to the right
               ‖Ｍ  reflect horizontally

     /\
    /  \    "No, this is Patrick!"
___/    \___
\   ☉ ☉    /
 \       /
  \      /
  |  /\  |
  | /  \ |
  |/    \|

Drawing it bottom to top saves 2 bytes.

For some reason, I have to increment the argument to Polygon... Am I doing something wrong?

That's because Polygon leaves the cursor on the last character, but I wasn't using Polygon... in fact I wasn't using the best code either, I'm down to 17 now.

I dunno if if I got 17 the same way you did but... Thanks!

Near enough. I actually had Move(:Right); for (n) Print("_");.

SOGL V0.12, 27 24 bytes
╔*¹.╚№┼№.╝+ø┐.∙.1ž.╚┼+╬³

Try it Here!
Explanation:
╔*                        push a string with input amount of underscores
  ¹                       wrap that in an array
   .╚                     push a "/" diagonal of the size of the input (the top lines)
     №                    reverse vertically
      ┼                   add horizontally the underscores behind the array
       №                  reverse vertically back
        .╝+               below that add a "\" diagonal (middle lines)
           ø              push an empty string as the base of the vertical bars
            ┐.∙           get an array of "|" with the length of the input
               .1ž        at [input; 1] in the empty string insert that
                  .╚┼     horizontally append a "/" diagonal
                     +    add that below everything else
                      ╬³  palindromize horizontally

Python 2,  166 160 157 155  152 bytes
The exec approach is exactly the same byte count.
i=input();t,z=" \\";y=t*2
for k in range(i*3):s=k%i;o=i+~s;p=i+o;g="_ "[i>k+1]*p;print[g+"/"+y*k+z+g,t*s+z+y*p+"/",~-i*t+"|"+o*t+"/"+y*s+z+o*t+"|"][k/i]

Try it online!
Saved 3 bytes thanks to Jonathan Frech.

You could save some bytes by replacing t=" ";y,z=t*2,"\\" with t,z=" \\";y=t+t.

@JonathanFrech Thank you.

Java 8, 385 376 344 304 285 280 268 264 252 250 + 19 bytes
n->{int s=2*n,w=2*s,e=n-1,i=0,o,l[][]=new int[n*3][w];for(;i<n;l[i][s+~i]=l[n+i][w+~i]=l[o][s+~i]=47,l[i][o]=l[o][o]=l[n+i][i]=92,l[e][i]=l[e][w-++i]=95,l[o][e]=l[o][s+n]=124)o=s+i;for(int[]b:l)System.out.println(new String(b,0,w).replace(""," "));}
Try it online!

You can shorten it by 10 bytes using bitwise tricks and moving all your integer declarations outside your loops (270 bytes)

And you can save yet another 2 bytes by moving the int o= outside the loop too (268 bytes)

You can save 4 more bytes by getting rid of the for-loop brackets and using ++ directly on the last occurrence of i, like this: 264 bytes.

252 bytes

@Nevay Very clever, thank you

RIP my solution. You can lose two more bytes by using an int[][] for the character data: TIO.

@Jakob I'm not too sure how mine works anymore... What does that String constructor do?

Don't be afraid to check the docs. The constructor takes Unicode code points instead of bytes (which happen to have identical data here because only ASCII is used). The int parameters indicate that the string should be built from the entire array.

Java 7, 295 bytes
Solution is method f.
String s(String s,int n){while(n-->0)s=" "+s;return s;}String f(int x){String n="\n",s="/",b="\\",o="",u="_";int i=0;for(x--;i<x;u+="_")o+=s(s,2*x-i+1)+s(b,2*i++)+n;o+=u+s+s(b,2*i)+u+n;while(i>=0)o+=s(b,x-i)+s(s,4*x-2*(x+~i--))+n;while(i++<x)o+=s("|",x)+s(s,x-i)+s(b,2*i)+s("|",x-i)+n;return o;}

Try It Online (JDK 8)
Ungolfed
String s(String s, int n) {
    while (n-- > 0)
        s = " " + s;
    return s;
}

String f(int x) {
    String
        n = "\n",
        s = "/",
        b = "\\",
        o = "",
        u = "_"
    ;
    int i = 0;
    for (x--; i < x; u += "_")
        o += s(s, 2*x - i + 1) + s(b, 2 * i++) + n;
    o += u + s + s(b, 2 * i) + u + n;
    while (i >= 0)
        o += s(b, x - i) + s(s, 4*x - 2*(x + ~i--)) + n;
    while (i++ < x)
        o += s("|", x) + s(s, x - i) + s(b, 2 * i) + s("|", x - i) + n;
    return o;
}

Acknowledgments

-1 byte thanks to Kevin Cruijssen

You can save a byte by lowering x by 1 right from the start: <T>String s(T s,int n){return"".format("%"+-~n+"s",s);}String f(int x){String n="\n",s="/",b="\\",o="",u="_";int i=0;for(x--;i<x;u+="_")o+=s(s,2*x-i+1)+s(b,2*i++)+n;o+=u+s+s(b,2*i++)+u+n;for(;i-->0;)o+=s(b,x-i)+s(s,4*x-2*(x+~i))+n;for(;++i<=x;)o+=s("|",x)+s(s,x-i)+s(b,2*i)+s("|",x-i)+n;return o;}

Mathematica, 189 bytes
n(
  s_±x_±y_:=s->Array[If[x==y,s," "]&,{n,n}];
  StringRiffle[Characters@{"_/\\_","\\  /","|/\\:"}/.
    {"_"±#±n,"|"±#2±n,":"±#2±1,"\\"±#±#2,"/"±(n-#+1)±#2," "±0±1}
    /.":"->"|"//ArrayFlatten,"
",""])

Line 2 defines the helper operator ±, which is used to make line 4 evaluate to:
{"_"  -> Array[If[#1 == n,          "_", " "] &, {n, n}],
 "|"  -> Array[If[#2 == n,          "|", " "] &, {n, n}],
 ":"  -> Array[If[#2 == 1,          ":", " "] &, {n, n}],
 "\\" -> Array[If[#1 == #2,         "\\"," "] &, {n, n}],
 "/"  -> Array[If[1 + n - #1 == #2, "/", " "] &, {n, n}],
 " "  -> Array[If[0 == 1,           " ", " "] &, {n, n}]}

In line 3, the ReplaceAll (/.) takes a matrix representing the star of size 1 as well as the list of rules above. For the final steps, we use ArrayFlatten, which is shorter than SubstitutionSystem, and StringRiffle.

Python 2, 137 bytes
n=input()
b,f,s,v='\/ |'
for i in range(3*n):u=i/~-n*n*'_';d=f+i%n*2*s+b;print[u+d+u,b+s*2*(3*n+~i)+f,v+d.center(2*n)+v][i/n].center(4*n)

Try it online!


text:
What an Odd Function
Your task here will be to implement a function1 that forms a permutation on the positive integers (A bijection from the positive integers onto themselves).  This means that each positive integer should appear exactly once in the permutation.  The catch is your function should have a larger probability of outputting an odd number than an even number.
Now this may seem strange or impossible.  Surely there are just as many odd numbers as even numbers?  And while this intuition is correct for finite sets it actually does not hold for infinite sets.  For example take the following permutation:
1 3 2 5 7 4 9 11 6 13 15 8 17 19 10 21 23 12 25 27 14 29 31 16 33 35 18 37 39 20 41 43 22 45 47 24 49 51 26 53 55 ...

If you take any subsection of the sequence with size greater than \$1\$ you will have at least as many odd numbers as even numbers, thus it seems that the probability of any random term being odd is greater than that of being even.  You will also note every number odd or even number will eventually appear in the sequence and can only appear once.  Thus the sequence is a true permutation.
Definition of Probability
To avoid confusion or ambiguity I am going to clearly lay out what is meant by probability in this question.
Let us say we have a function \$f\$.  The probability of a number being odd will be defined as the limit of ratio odd members of the set to the size of the set \$f\{1\dots n\}\$ as \$n\$ tends towards infinity.
$$\lim_{n\rightarrow \infty}\dfrac{\left|\{x : x \in \{1\dots n\}, \mathrm{odd}(f(x))\}\right|}{n}$$
For example the aforementioned function would have a probability of being odd of \$2/3\$.

This is code-golf so answers will be scored in bytes with less bytes being better.

Extra Challenges
Here are some fun ideas to play around with and perhaps try to implement.  These are just for fun and do not affect scoring in any way. Some of these are not even valid solutions to this challenge, and an answer which only includes solutions to challenges 2 or 3 is not a valid answer, and is liable to be deleted.

Write a permutation with an odd probability of \$1\$. (this is possible)

Write a permutation that has more odd numbers than even numbers in \$f\{1\dots n\}\$ for any \$n\$ but has a odd probability of \$1/2\$.

Write a permutation that has no defined probability (that is there is no limit). (Now a standalone challenge here)

1: Here function will mean program or function.  It is just a piece of code that takes input and produces output.

Jelly, 7 bytes
Æf^<¥4P

Swaps 2s and 3s in the input's prime factorization. The probability of odds is 2/3.
Try it online!
How it works
Æf^<¥4P  Main link. Argument: n

Æf       Compute all prime factors of n, with duplicates.
    ¥4   Combine the two links to the left into a dyadic chain and call it with
         right argument 4.
   <       Compare each prime factor with 4. Yields 1 for 2 and 3, 0 otherwise.
  ^        Bitwise XOR the results with the corresponding prime factors.
         This maps 2 to 3, 3 to 2, and all other primes to themselves.
      P  Take the product of the resulting primes.

This answer is quite clever.  I believe I understand why it works but you might want to include a proof that it works because I found it unintuitive at first.

Proof that this is a permutation: the function is its own inverse. Proof of ratio: chance that an output is odd is the chance that the original had no factors 3, which is exactly when it's not divisible by three. That chance is 2/3.

Husk, 11 10 bytes
-1 byte thanks to Leo, and a slightly different function
This has an odd probability of 1
!uΣz:NCNİ1

Try it online!
It indexes the sequence:
[1,2,3,5,7,9,11,4,13,15,17,19,21,23,25,27,29,6,31,33]
1 odd, 1 even, 5 odd, 1 even, 9 odd, 1 even, 13 odd...

Explanation
!               Index the following sequence (1-indexed)
 u              remove duplicates                     [1,2,3,5,7,9,11,4,13,15...]
  Σ              Concatenate                          [1,1,2,3,5,3,7,9,11,4,13..]
   z:            Zipwith append                       [[1,1],[2,3,5],[3,7,9,11]..
     N          Natural numbers
      CNİ1      Odd numbers cut into lists of lengths [[1],[3,5],[7,9,11]...]
                corresponding to the Natural numbers

Could you explain the function?

1 byte less by using nub: https://tio.run/##yygtzv6vkFuce3jboeX6PsqqRrmPmhof7lhcdGjbf8XSc4urrPyc/Y5sMPz//78hlxGXMZehAZeRAZepAZABxhDCAAA

Haskell, 35 34 32 bytes
f n=n:2*n+1:2*n+3:f(n+2)
(f 0!!)

Implements the example sequence [1,3,2,5,7,4,9,11,6,13,15,8,17,19,10,21,...].
Try it online!
For reference: old version, 34 bytes (-1 byte thanks to @xnor):
(!!)$do e<-[0,2..];[e,2*e+1,2*e+3]

Try it online!

Save a paren: (!!)$do ...

Everybody does Challenge 1, so let's do the other two.
Perl 6, 26 bytes — Challenge 2
{($_==1)+$_-(-1)**($_%%2)}

Try it online!
It's just 1 3 2 5 4 7 6... In an even number of terms, there are always 2 more odd numbers than even. In an odd number, 1 more. However this has clearly limit of (n+2)/(2n+2) -> ½.

Perl 6, 70 bytes — Challenge 3
{((1,),(2,4),->@a,@ {@(map(@a[*-1]+2*(*+1),^(4*@a)))}...*).flat[$_-1]}

Try it online!
Admittedly, this is horribly golfed. It indexes a sequence that contains 2⁰ odd numbers, then 2¹ even, then 2² odd, then 2³ even, and so on.
The probability after n such "blocks", if n is odd, is (2⁰+2²+2⁴+...+2ⁿ⁻¹)/(2ⁿ-1). The sum in the numerator is equal to ⅓(4½(n+1) - 1) = ⅓(2n+1 - 1). So the probability after odd number of blocks is ⅔ (in the limit).
If we add one more block (and strike an even count of them n+1), however, we didn't add any odd numbers (numerator stays the same) but there is now (2n+1 - 1) numbers in total. The parentheses cancel and we get the probability of ⅓ (in the limit).
This is apparently supposed to have 2 different cluster points, ⅓ and ⅔, to make sure that the limit doesn't exist, but this doesn't really prove it. My attempt to do a solid, rigorous proof can be found in this Math.SE answer: https://math.stackexchange.com/a/2416990/174637. Bashing mistakes is welcome.

Perl 6, 39 bytes — The core challenge.
{my$l=$_ div 3;$_%3??2*($_-$l)-1!!2*$l}

Try it online!
Though I posted this answer because of the challenges 2 and 3 which offered a pleasant little mathy puzzle, there is a strict requirement for all answers to contain a solution to the core challenge. Here it is then.
This is the  example sequence.

These are extra challenges. For this to be a valid answer you must supply a solution to the core challenge. A solution to challenge 1 is also a solution to the core challenge, but a solution to challenges 2 or 3 is not.

Well, the extra challenges are what's interesting on this question for me. The core challenge is not. But I added some solution anyway.

I asked for a proof that your response to Challenge 3 has no limit in this Math.SE question: https://math.stackexchange.com/questions/2416053/what-is-the-limit-of-the-ratio-of-odd-numbers-to-even-numbers-in-this-sequence

@Kevin, thanks for asking. I think I may have confused you. I was quite sure it was OK. The only thing is that I often prove things quite rigorously for myself, just for the peace of mind (because your feet may slip quite easily, esp. when handling infinite objects like this)  — and I haven't done it here. That's all what I wanted to say.

@Ramillies To be honest, I asked mostly because I'm interested in it for myself. I suspect your reasoning is correct, but selfishly, I want to see a formal proof just out of curiosity. :P If you're insulted by my question on Math.SE, let me know and I'll delete it. I apologize for not asking you first.

@Kevin, I'm not insulted at all :—). It would be great to have somebody sit down and write out the proof. I even tried, but when I wrote down the proposition I want to prove, I just thought a little bit about that and said "Nah, I'm too lazy" :—D. (It looks like I would need to do extensive discussion for quite a few separate cases, and I really hate proofs like that!)

@Ramillies Sounds good, thanks :D

@Kevin — so after all, I overcame my laziness (a heroic deed!) and made the proof. I posted it as an answer to your Math.SE question. Hopefully it's OK (doing this kind of work at the night isn't really a good idea :—)). It turned out that it isn't nearly as horrible as I initially thought.

Your first program.can be golfed to 20 bytes

Husk, 8 bytes
!uΣzeİ1N

Try it online!
This implements the example sequence (1,3,2,5,7,4...).
Explanation
!uΣzeİ1N
   ze       zip together
     İ1       the odd numbers
       N      with the natural (positive) numbers
  Σ         flatten the resulting list
 u          remove duplicates
!           index into the obtained sequence with the input

Brain-Flak, 120 bytes
(({})<{{({}[()]<({}(()[{}]))>)}{}({}[({})]<({}<>{}<({}())>)><>)}>)<>({}[()]){{}((<>{}<>[{}]){}[()])<>}{}{(({}){})<>{}}<>

Try it online!
Performs the following function:

This function generates the sequence
2 4 1 6 3 5 7 8 9 11 13 15 17 19 21 10 23 25 27 29...

The function has an odd probability of 1

R, 82 bytes (Extra challenge 1)
f<-function(n){if(sqrt(n)==floor(sqrt(n))){2*sqrt(n)}else{2*(n-floor(sqrt(n)))-1}}

Try it Online!
If the input is a perfect square, gives an even number. Otherwise, gives an odd number. The perfect squares have natural density 0, which means that this sequence gives odd numbers with probability 1.

Could you add a TIO link please?

58 bytes

56 bytes

53 bytes

C (gcc), 29 bytes
f(n){return n&3?n+n/2|1:n/2;}

Try it online!
Every fourth number is even:
1 3 5   7 9 11   13 15 17   19 21 23   25 27 29
      2        4          6          8          10

Extra challenge 1, 52 bytes
f(n,i){for(i=0;n>>i/2;i+=2);return n&n-1?2*n-i-1:i;}

Try it online!
Returns 2*(x+1) if n equals 2x and consecutive odd numbers otherwise:
    1   3 5 7   9 11 13 15 17 19 21    23 25
2 4   6       8                     10

return n&n-1?2*n-i-1:i; can be return~-n&n?2*n+~i:i for -2. In addition, but return  can be n= to save some more bytes.

Brain-Flak, 140 138 136 bytes
({}<(((()())()()))((<>[()])[()()])>){({}[()]<(({}(({}({}))[({}[{}])]))[({}[{}])]<>(({}(({}({}))[({}[{}])]))[({}[{}])])<>)>)}{}({}<{}{}>)

Try it online!
Explanation
This performs a similar function to the one suggested in the question.
2 3 1 4 7 5 6 11 9 8 15 13 10 17 15 ...

It works mostly based on a snippet I made to roll the stack for size 3 stacks.
(({}(({}({}))[({}[{}])]))[({}[{}])])

We set up two stacks one with accumulator values (two odd one even) and one with the numbers 4 4 2.  Each iteration we roll both stacks and add the top of the left stack to the top of the right stack.
(({}(({}({}))[({}[{}])]))[({}[{}])]<>(({}(({}({}))[({}[{}])]))[({}[{}])])<>)

This will increment each odd number by 4 and the one even number by 2.  As we loop through we get a pattern of 2 odd 1 even, with every positive integer being hit.  Thus we just loop n times with n being the input.  This has an asymptotic probability of 2/3.

Re:direction, 20 19 bytes
+++>>
 v>
 +>>
v>
<

Try it online!
-1 by rearranging to remove a space.
Here's what happens, based on the input number:

3n: It runs along the first line n times, picking up 2n >s, before going down from the first +. It then adds a v, and hits the bottom <, which points to itself to halt, outputting 2n.
3n+1: It again runs along the first line n times, picking up 2n >s, and then it passes the first + and goes down on the second one. It then adds a v. The loop on the third line doubles the number of >s in the queue to 4n before ending by consuming the v. On the fourth line, another > is added, for 4n+1, before ending in the same way as the previous case, outputting 4n+1.
3n+2: Mostly the same as the above case, except going down from the third + and then adding an extra > before joining the same path, making 2n+1, which becomes 4n+2, then 4n+3, and outputting 4n+3.

Jelly, 10 bytes
ÆE;0ṭ2/FÆẸ

The probability of odds is 2/3.
Try it online!
How it works
ÆE;0ṭ2/FÆẸ  Main link. Argument: n

ÆE          Compute the exponents of n's prime factorization.
  ;0        Append a 0.
     2/     Reduce all pairs by...
    ṭ         tack, appending the left argument to the right one.
            This inverts all non-overlapping pairs of exponents.
       F    Flatten the result.
        ÆẸ  Consider the result a prime factorization and compute the corresponding
            integer.

JavaScript, 23 bytes
n=>n/2+n/2%2+(n%4&&n-1)

Output: 1, 3, 5, 2, 7, 9, 11, 4, 13, 15, 17, 6, 19, 21, 23, 8...

For all n = 4k:

f(n) = n/2 = 2k

For all n = 4k + b

f(n) = n/2 + b/2 + n - 1 = 3/2 * (4k + b) + 1/2 * b - 1 = 6k + 2b - 1

Challenge 2:
n=>n^(n>1)

Output: 1, 3, 2, 5, 4, 7, 6, 9, 8, 11, 10, 13, 12, 15, 14

n=>n%4?1.5*n|1:n/2 is 5 bytes shorter.

C, 80 bytes
#define R if(k++==n)return
i,j,k;f(n){for(i=k=1,j=2;;i+=4,j+=2){R i;R i+2;R j;}}

Implementation of the example permutation from the question.
Try it online!

Batch, 36 bytes
@cmd/cset/an=%1*2,(-~n*!!(n%%3)+n)/3

Implements the sequence given in the question.

CJam (21 bytes)
{2b_(&!\_,2*\1$~+2b?}

Online demo showing the first 32 outputs. This is an anonymous block (function).
This is also a solution to challenge 1: the numbers mapped to even numbers are the powers of 2, so the density of even numbers in the first n outputs is lg(n)/n which tends to zero.
Dissection
{         e# Declare a block; let's call the input x
  2b      e#   Convert to base 2
  _(&     e#   Copy, pull out first digit (1) and set intersection with rest
  !       e#   Boolean not, so empty set (i.e. power of 2) maps to 1 and non-empty
          e#   to 0
  \_,2*   e#   Take another copy, find its length, and double it
  \1$~+   e#   Take the original base 2 array and append ~(2L) = -2L-1
  2b      e#   Convert from base 2, to get 2x-2L-1
  ?       e#   Take the 2L if it was a power of 2, and the 2x-2L-1 otherwise
}

Perl 40 bytes
$,=$";$i=4;{say$i-3,$i/2,($i+=4)-5;redo}

Brain-Flueue, 88 bytes
({}<(((<>)[()])[()()])>)<>(((()())()()))<>{({})({})({})({}[()]<({}<>({})<>)>)}{}{}({}){}

Try it online!
Explanation
This implements the same function as my last answer but uses Brain-Flueue's FIFO model to cut some corners.  Here are the first couple terms it generates.
2 3 1 4 7 5 6 11 9 8 15 13 10 17 15 ...

The first part of the code is just a bit of setup, we put 0,-1,-3 on the first stack and 2,4,4 on the second stack.  The 2,4,4 will be used to cycle through even and odd numbers just as I did in my Brain-Flak answer.
We then loop n times, each time adding the top of the left stack to the right stack.  Since Brain-Flueue uses queues as opposed to stacks the values naturally roll as we touch them preventing the need for extra code.

What is the difference between Flueue and Flak?

@tfbninja Flueue uses a Queue instead of a stack.

but...you're using the bflk interpreter... how do you make it different

@tfbninja The -lflueue argument.

Lean, 85 bytes
import data.nat.prime
λx,list.prod$list.map(λp,if p<4then 5-p else p)$nat.factors x

Try it online!
Swaps 2s with 3s in the prime factorization.

Vyxal, 6 bytes
ǐ:4<꘍Π

Try it Online! or run it from 1 to 100.
Port of Dennis's Jelly answer. 1J is needed due to a bug in Vyxal where the product of [] returns 0 instead of 1. Bug fixed.
How?
ǐ:4<꘍Π
ǐ      # Get the prime factors with duplicates
 :     # Duplicate
  4<   # For each item, is it less than 4? (Vectorizes, produces a list of 1s and 0s)
    ꘍  # Bitwise XOR the two arrays (vectorizes)
     Π # Product of resulting array

Vyxal, 8 bytes
Þ∞y$:ẇYf

Try it Online!
Challenge number 1 - a list with an odd probability 1. Creates an infinite list.
The sequence generated looks like \$2, \color{red}{1}, \color{black}{4}, \color{red}{3, 5, 7}, \color{black}6, \color{red}{9, 11, 13, 15, 17},  \color{black}{8}\cdots\$, interleaving the even numbers with the odd numbers in ever-growing chunks.
If we take the first \$k^2+k\$ terms for integer \$k\$, \$\sum_{n=0}^{k}2n+1 = k^2\$ of them will be odd and \$k\$ will be even, so the proportion of odd numbers is \$\frac{k}{k+1}\$. As \$k \to ∞ \$, \$ \frac{k}{k+1} \to 1\$.
Þ∞       # Infinite list of positive integers
  y$     # Uninterleave, pushing odds and evens, and swap the odds on top
    :ẇ   # Cut odds into sequences of lengths [1, 3, 5, 7...]
      Yf # Interleave and flatten.

Pyth, 9 bytes
*Fmxd<d4P

Try it here! or Test more in one go!
You can use this code to verify the ratio of odd numbers up to a certain point. Substitute 10000 with your desired limit (don't set it much higher, because it memory errors).
Km*Fmxk<k4PdS10000clf%T2KlK

Try it here.
The above gives roughly 0.667. The true probability of odd occurrences is 2/3. This approach is an equivalent implementation of Dennis' answer.

Explanation
*Fmxd<d4P   Full program.

        P   Prime factors.
  m         Map over ^.
   x        Bitwise XOR between:
    d          The current prime factor.
     <d4       The integer corresponding to the boolean value of current factor < 4.
*F          Product of the list.

Python 2, 46 104 55 bytes
lambda n:2*((n-int(n**.5))+.5,n**.5-1)[n!=1>0==n**.5%1]

Try it online!
Misread the question, now properly implemented a function that can be used to generate a sequence instead of one that generates a sequence. Also excluded 0 from the set of possible outputs.
Probability of finding an odd positive integer now converges to 1.

This should return an number, not a set / list as far as I understood

Also, this is not a correct permutation, since it contains 0.

@Mr.Xcoder Thanks for noticing.

Lua, 67 53 bytes
Explanation coming when I'm done golfing this :)
This program takes an integer via command-line arguments as input and prints out the nth element of the exemple sequence to STDOUT
n=...print(n%3<1 and n/3*2or n+math.floor(n/3)+n%3-1)

Explanations
n=...                              -- shorthand for the argument
print(                             -- prints out the result of the following ternary
     n%3<1                         -- if n is divisible by 3
       and n/3*2                   -- prints out the corresponding even number
       or n+math.floor(n/3)+n%3-1) -- else prints out the odd number

The even numbers of this sequence are both the nth even number and the n multiple of 3, hence the formula n%3*2 is sufficient to generate them.
For odd numbers, it's a little bit more tough. Based on the fact that we can find them depending on the current n, we have the following table :
n       |  1   2   4   5   7   8   10   11
target  |  1   3   5   7   9   11  13   15
target-n|  +0  +1  +1  +2  +2  +3  +3   +4

Let's call the value target-n i, we can see that each time n%3==2, i is incremented. There goes our formula :
n+math.floor(n/3)+n%3-1

The odd numbers are based on n on which we add i.
The value of i increments at the same rate as the euclidian division by 3, with an offset. math.floor(n/3) gives us the rate of increment and n%3-1 gives us the offset, making it happens on n%3==2 instead of n%3==0.

One byte could easily be saved by removing an unnecessary space (...and (n/...).

@JonathanFrech was able to save 2 at this spot by totally removing the parenthesis as and n/3*2or works just as fine

Jelly, 9 bytes
Ḥ€’ĖUẎQ⁸ị

Try it online!
Implements 1, 3, 2, 5, 7, 4, 9, 11, 6, ... (probability 2/3).

05AB1E, 11 bytes
·ÅÉā‚ø˜Ù¹<è

Try it online!

Java 8, 20 bytes
n->n%4>0?n+n/2|1:n/2

Port of @nwellnhof's C answer.
Some things I tried myself ended up being a few bytes longer or slightly incorrect..
Implements: 1,3,5,2,7,9,11,4,13,15,17,6,19,21,23,8,25,27,29,10,31,33,35,12,37,...
with a probability of 3/4.
Try it here.

05AB1E, 6 bytes
ÒD4‹^P

Port of @Dennis' Jelly answer, so make sure to upvote him!
The probability of odds is therefore also \$\frac{2}{3}\$.
Try it online (outputs an infinite list after timing out) or only output the first \$n\$ values instead.
Explanation:
Ò       # Get the prime factors of the (implicit) input-integer, counting multiplicities
 D      # Duplicate this list
  4‹    # Check for each value whether it's smaller than 4 (1 for 2 and 3; 0 otherwise)
    ^   # Bitwise-XOR the two lists at the same indices
        # (2 becomes 3; 3 becomes 2; everything else remains unchanged)
     P  # And take the product of this
        # (after which the result is output implicitly)

x86 32-bit machine code, 12 bytes
a8 03 74 05 8d 04 40 0c 02 d1 e8 c3

A port of nwellnhof's C answer. Uses the regparm(1) calling convention – argument in EAX, result in EAX.
Try it online! (contains all five functions)
Assembly:
f:
    test al, 3                  # Take the low two bits of the value.
    jz point0                   # Jump if they are both 0.
    lea eax, [eax + eax * 2]    # Triple the value in EAX.
    or al, 2                    # Set the twos bit in EAX.
point0:
    shr eax, 1                  # Shift EAX right by 1 bit.
    ret                         # Return.

The opposite
I also found an 11-byte function with a 1/4 odd probability:
0f bc c8 d3 e8 83 f1 01 d3 e0 c3

Assembly:
fe:
    bsf ecx, eax    # Set ECX to the position of the lowest 1 bit in EAX.
    shr eax, cl     # Shift EAX right by that quantity, removing all ending 0 bits.
    xor ecx, 1      # Invert the lowest bit of ECX.
    shl eax, cl     # Shift EAX left, introducing a modified number of ending 0 bits.
    ret             # Return.

1st extra challenge: 18 bytes
f3 0f b8 c8 d1 e0 0f bd d0 d1 e2 48 29 d0 e2 01 92 c3

Implements a function several other answers have used, mapping powers of 2 to even numbers in ascending order and other numbers to odd numbers in ascending order: \$
f_1(2^m) = 2m+2 \$, and for \$ n \in [2^m, 2^{m+1})\$, \$ f_1(n) = 2n - 2m - 3\$.
Assembly:
f1:
    popcnt ecx, eax # Set ECX to the number of 1 bits in EAX.
    shl eax, 1      # Shift EAX left by 1, doubling it to 2n.
    bsr edx, eax    # Set EDX to the position of the highest 1 bit in EAX -- m+1.
    shl edx, 1      # Shift EDX left by 1, doubling it to 2m+2.
    dec eax         # Decrement EAX to 2n-1.
    sub eax, edx    # Subtract EDX from EAX, making it 2m-2n-3.
    loop point1     # Decrement ECX and jump if it's nonzero -- if the value was not a power of 2.
    xchg eax, edx   # Exchange EAX and EDX, making EAX 2m+2.
point1:
    ret             # Return.

2nd extra challenge: 6 bytes
83 f0 01 74 fb c3

Produces \$ 1, 3, 2, 5, 4, 7, 6, ... \$
Assembly:
f2:
    xor eax, 1  # Invert the lowest bit of the value.
    jz f2       # Jump back if that makes it 0 (and it will be flipped back to 1).
    ret         # Return.

3rd extra challenge: 12 bytes
0f bd c8 d3 d8 19 d2 d3 c0 29 d0 c3

Rearranges the bits of the value by moving the second-highest bit to the bottom. This produces 1 odd, 1 even, 1 odd, 2 even, 2 odd, 4 even, 4 odd, ...
Assembly:
f3:
    bsr ecx, eax    # Set ECX to the position of the highest 1 bit in EAX.
    rcr eax, cl     # Rotate EAX and the carry flag CF together left by that quantity.
# Note that the value of CF after BSR is officially undefined,
#  but it is consistently 0 on at least some systems, which is what this function needs.
# This puts the second-highest bit of the value into CF,
#  while the highest bit goes to the bottom position and the lower bits go to the top.
    sbb edx, edx    # Subtract EDX+CF from EDX, making its value -CF.
    rol eax, cl     # Rotate EAX right by the same value, not including CF in the rotation.
# EAX now contains all the bits of the original value except the second-highest,
#  followed by a single 0 bit; if the original value was 1, EAX is now 1.
    sub eax, edx    # Subtract EDX from EAX, replacing the removed bit at the bottom.
    ret             # Return.

Python 2, 39 bytes
lambda n:[n/3*4+1,n/3*4+3,n/3*2+2][n%3]

Try it online!
outputs :
1, 3, 2, 5, 7, 4, 9, 11, 6, 13, 15, 8, 17, 19, 10, 21, 23, 12, 25, 27, 14, 29, 31, 16 ...

Odd probability = 2/3
If generating the sequence without taking an inputs is accepted, I also have:
Python 2, 34 bytes
i=3
while 1:print-~i/2,i-2,i,;i+=4

Try it online!
Outputs:
2 1 3 4 5 7 6 9 11 8 13 15 10 17 19 12 21 23 14 25 27 16 29 31 18 33 35 20 37 39 22 41 ...

Odd probability = 2/3

Mathematical function, 48 bytes
You said "function", so I'm making a function. Takes an input x and returns the x+1th term. It does mess up when given a non-integer.
       x>=1>(x-1) mod 2:x+2
f(x)={ x>=1>x mod 2:x       }
       x=0:1

Excluding non-meaningful whitespace.
Here's a graph:

There are always one or two more odd numbers than even ones.

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
These Days Work for Me
Background
You're an attractive code golfer and quite a few people are asking you out.
You don't have time to think about which days exactly you're available, so you decide to create a function the accepts a date and returns the days of that week.
You then take those days of the week, insert it into your calendar program to see if anyone else has asked you out already.
Rules

Accepts a date in YYYY-MM-DD format
Returns an array/list of dates of that week. (Sunday is the first day)

The dates can be displayed as the milliseconds between January 1, 1970 and that date, in a "common" date format1, or date objects.

The order of the dates must be ascending.

(Although you're smart enough to include support for a descending list, the program is able to work quickest with an ascending list and who has a few milliseconds to spare?)

Must work with on any day since 1993. (Yes, you're 24 years old at the time of writing!)
Every Javascript answer gets a high five!

Specs
Sample Input: whichDates(2017-08-29)
Output: (the equivalent of)

console.log([
  Date.parse('2017-08-27'),
  Date.parse('2017-08-28'),
  Date.parse('2017-08-29'),
  Date.parse('2017-08-30'),
  Date.parse('2017-08-31'),
  Date.parse('2017-09-01'),
  Date.parse('2017-09-02'),
]);

1 A format that is fairly well known. Such as YYYY-MM-DD.
2 This is code-golf! Shortest code per language wins, but the shortest code overall gets the emerald checkmark!

Related

Also, I suggest you to allow other formats, other than YYYY-MM-DD (I don't see a good reason why it should be strict).

The first sentence is the weirdest and less plausible introduction I've seen in a challenge. Well done :-)

@LuisMendo Thanks! But you never know who exactly is secretly admiring your sick programming skills....

Why Every Javascript answer gets a high five! ?

@sergiol I wanted to encourage JS, as I enjoy learning JS tricks.

Date.parse(2017-08-27) ?? should this be Date.parse('2017-08-27')?

Japt, 15 bytes
ÐU
7Æf1X+Uf -Ue

Test it

Explanation
Implicit input of string U.
ÐU

Convert U to a date object and reassign to U.
7Æ

Create an array of integers from 0 to 6, passing each through a function where X is the current element.
f1

Set the date of U.
X+Uf

Add the current date of U to X.
-Ue

Subtract the current day of the week of U.
Implicitly output the resulting array.

Perl 6, 47 bytes
{my$d=Date.new($_);map($d+*-$d.day-of-week,^7)}

Try it online!
The code is almost self-explanatory. First we make up a Date object $d from the string, which happens to be in the nice ISOwhatever format. We can perform arithmetic with the dates (adding an integer = adding that many days, the same with subtracting). So $d-$d.day-of-week is the last this (oh my god, week has always started with Monday for me :D) week's Sunday. (.day-of-week is 1 for Monday to 7 for Sunday.) We then map over 0 to 6 (^7) and add that to the Sunday, getting all the days in the week. The number we're mapping over appears in the place of the star *. This list is then returned.

JavaScript (ES6), 73 63 62 Bytes
I thought I'd also have a go at it in JavaScript.
Edit: Using the milliseconds approach, as allowed by the prompt, I reduced it down to 62 bytes.
s=>[..."0123456"].map(i=>(x=new Date(s))-(x.getDay()-i)*864e5)

You could perform a .map(x=>new Date(x)) on the returned array if you wanted to convert it.

Maintaining the date approach  (72 Bytes)
s=>[..."0123456"].map(i=>new Date((x=new Date(s))-(x.getDay()-i)*864e5))

There was a bug in my initial submission, it is fixed. Thanks to an observation by milk, I was able to remove the bug and still lower the byte count.

High Five!!

Welcome to the site!

It's shorter to just write out the numbers in the array. 60 bytes: s=>[..."0123456"].map(i=>(x=new Date(s))-(x.getDay()-i)*8e7)

Welcome to PPCG, and nicely tied :) Tip 1: Ditch the keys and use the index instead of the element when mapping over the array. Tip 2: For an array this small, it's shorter to generate it the way I did.

JavaScript (ES6), 76 bytes
I think I've finally found the environment least conducive to efficient golfing: from behind my bar, while serving pints with my other hand!
s=>[...""+8e6].map((_,x)=>d.setDate(d.getDate()-d.getDay()+x),d=new Date(s))

Try it online (Snippet to follow)

Explanation
s=>

Anonymous function taking the string (of format yyyy-(m)m-(d)d) as an argument via parameter s.
[...""+8e6]

Create an array of 7 elements by converting 8000000 in scientific notation to a string and destructuring it, which is shorter than [...Array(7)].
.map((_,x)=>          )

Map over the array, passing each element through a function where _ is the current element, which won't be used, and x is the current index, 0-based.
,d=new Date(s)

Convert s to a Date object and assign it to variable d
d.setDate(     )

Set the date of d.
d.getDate()

Get the current date of d.
-d.getDay()

Subtract the current weekday number, 0-indexed, to get Sunday.
+x

Add x.

while serving pints with my other hand! - Nice multitasking skills :-)

Almost forgot... High Five!

@ChrisHappy if you're learning JS, don't look to code golf for tips :P

@cairdcoinheringaahing Got it. I don't think I worded it well. I'm not really interested in learning how JS works, more advanced tricks with it :)

@Shaggy Could you add an explaination when you have time?

@ChrisHappy: It could well be Sunday until I have time enough to write one up; stuck behind the bar 'til then.

@ChrisHappy: Found a minute, explanation added. You should have a look at the JS tips under the [tag:tips] tag if you're looking for more trickd for golfing in JS.

MATL, 22 21 bytes
7:j8XOs21Y2=f-GYO+1XO

Output is in dd-mm-yyyy format.
Try it at MATL Online!
Explanation
7:     % Push [1 2 3 4 5 6 7]
j      % Input as a string
8XO    % Convert date to string with format 8, which is 'Mon', 'Tue' etc
s      % Sum
21Y2   % Push predefined literal [298 302 288 305 289 296 310]. The first number
       % is the sum of ASCII codes of 'Mon', the second is that of 'Tue', etc.
=      % Is equal?, element-wise
f      % Index of nonzero value. For example, if input is a Friday this gives 5
-      % Subtract, element-wise. For a Friday this gives [-4 -3 -2 -1 0 1 2]
G      % Push input again
YO     % Convert to date number: number of days from January 0, 0000
+      % Add, element-wise
1XO    % Convert to date format 1, which is 'dd-mm-yyyy'. Implicitly display

Python 3, 133 124 126 112 bytes
-9 bytes thanks to Mr. Xcoder
+2 bytes because the week starts with Sunday
-14 bytes thanks to notjagan
from datetime import*
a=date(*map(int,input().split('-')))
for i in range(7):print(a-timedelta(a.weekday()-i+1))

That didn't go as well as I had hoped.

127 bytes

124 bytes

110 bytes.

This works in Python2 also if we do raw_input() instead of input() above. (+4 bytes).  range still works in Python2 for this small thing as well.  Without raw_input you get errors.

Bash + common utilities, 53
jot -w@ 7 `date -f- +%s-%w*86400|bc` - 86400|date -f-

Try it online.
This assumes that the output of GNU date is a "common" date format, e.g. Fri Sep  1 00:00:00 UTC 2017.
Explanation
           date -f- +%s-%w*86400                       # read date from STDIN, output expression "seconds-since-epoch - (index of day in week * 60 * 60 * 24)
                                |bc                    # arithmetically evaluate generated expression - result is date of required sunday in seconds-since-epoch
jot -w@ 7 `                        ` - 86400           # output seconds-since-epoch for all 7 required days of the week, prefixed with "@"
                                            |date -f-  # convert all seconds-since-epoch dates back to regular dates

Mathematica 20 bytes?
Mathematica expresses the list of days as a single date object.  If such date object is acceptable output, the following 20-byte pure function will work:
#~DateObject~"Week"&

Example
#~DateObject~"Week"&["2017-08-29"]

I don't see a problem with it! :)

Python 2, 115 Bytes or 111 Bytes, depending on input format.
Basically, this is almost the same code in the answer for Python3 written by Sobsz, but made to work in Python 2.

If input is in the form YYYY-MM-DD:
(This assumes the input is not wrapped in single-quotes to denote a string as input)
Key difference is that we need raw_input instead of input, unless we explicitly specify the date in 'YYYY-MM-DD' within the apostrophes to identify it as a string literal. Without the string literal input, we get a Syntax Error, hence the use of raw_input to accept dates in YYYY-MM-DD directly without putting it in string literals.
This of course assumes that the input is put in like so: 2017-08-29.
from datetime import*
a=date(*map(int,raw_input().split('-')))
for i in range(7):print a-timedelta(a.weekday()-i+1)

+4 from Sobsz's answer, then -1 because we don't need parentheses for the print statement and save a byte from the closing parenthesis not being there; total of +3 bytes difference.
Try it Online!

If input is in the form 'YYYY-MM-DD':
(Note that we must have the date provided inside quotes in order for this answer to work)
We get to save 4 bytes because we don't need the raw_ and this is effectively the same answer as Sobsz provides, minus a byte because we don't need the parentheses around the print command.
Thanks to Mr. Xcoder for pointing this one out, though this is technically an exact duplicate then, minus one byte, of Sobsz's answer.
from datetime import*
a=date(*map(int,input().split('-')))
for i in range(7):print a-timedelta(a.weekday()-i+1)

Welcome to PPCG! You can replace raw_input() with input and surround the input with quotes to save 4 bytes. Of course, that turns your solution into a duplicate though :P

@Mr.Xcoder True, which is why I skipped that.  Though, if we put the input in quotes first, we actually save a byte from Sobsz, and I did make a note of that.

Java 8 (161 154 123 122 102 + 19 36 bytes)
Try it online!
import static java.time.LocalDate.*;

e->{for(int i=0;i<7;System.out.println(parse(e).plusDays(i++-parse(e).getDayOfWeek().getValue()%7)));}

Don't forget to include imports in your solution and byte count.

Also you can save bytes by removing l and replacing references with LocalDate.parse(e).

@Jakob Good shout, thank you

And now you can increment i in the loop body to save 1 byte. Oh, and the java.util.function.* import isn't used by the lambda, so you don't have to count it as part of the solution.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Collatz's First Conjecture
Background
The Collatz Conjecture is quite well-known. Take any natural number. Triple and increment if odd; cut in half if even. Repeat, and it will reach 1 eventually. This famous conjecture, however, is only that, for it is yet unproven.
Little-known to the world, that was not Lothar Collatz's first attempt at fame. His first Conjecture (now proven) was a touch simpler:

Take any natural number n.
While n ≠ 4, find the length of its written-out form (English). Store this value to n.

The conjecture is that all natural numbers will eventually become 4. This did not catch on as well as Collatz had hoped, so he returned to the drawing board.
Your task
Read a positive integer n < 2147483648 (2^31) from input and return/print the number of iterations required to reach 4.
Things to note
Do not use and. 228 is "two hundred twenty-eight," not "two hundred and twenty-eight."
Do not use articles. 145 is "one hundred forty-five," not "a hundred forty-five.)
Commas set apart each three orders or magnitude: "one million, four hundred eighty-two thousand, one hundred seventy-five."
Punctuation is counted. Spaces are not. Hyphenate 21-99 except multiples of ten.
Test cases

4 (four): 0
  3 (three→five→four): 2
  6278 (six thousand, two hundred seventy-eight→thirty-five→eleven→six→three→five→four): 6
  1915580 (one million, nine hundred fifteen thousand, five hundred eighty→fifty-five→ten→three→five→four): 5
  2147483647 (two billion, one hundred forty-seven million, four hundred eighty-three thousand, six hundred forty-seven→ninety-three→twelve→six→three→five→four): 6

This is code-golf, so the shortest code (in bytes) in each language WINS! Good luck!

one million, nine hundred fifteen thousand, five hundred eighty is of length 63, not 55. The correct result for 1915580 is 6, not 5.

@Mr.Xcoder Punctuation is counted. Spaces are not

@H.PWiz Thanks for letting me know, I fixed my answer.

Do numbers above 10^66 need to be handled?

No, will edit soon to address this.

Four has Four Letters

Python 3 + inflect,  122  114 bytes
Saved 8 bytes thanks to Scrooble.
from inflect import*
f=lambda k,i=0:k!=4and f(len(engine().number_to_words(k,andword="").replace(" ","")),i+1)or i

This cannot be tested online because of the package it uses. Running the test suite gives:

4 -> 0
3 -> 2
6278 -> 6
1915580 -> 5

I'm unfamiliar with inflect, but from reading the linked page, I believe that this could be shortened by using number_to_words(k,andword="") instead of number_to_words(k).replace(" and","") (saves 8 bytes).