text:
Make a transparent 448*448 image
This is a simple challenge.
The task is to write code that outputs a 448*448 square image with 100% transparency.  The output should follow the standard image rules.

What's to stop people from submitting a 0-byte answer which "outputs" a transparent (invisible) image to the screen?

@12Me21 Would that be 448*448?

Is this a parody of (or at least inspired by) a closed question on stackoverflow?

What's special about 448 px?

@dan04  CDXLVIII is the number of integer partitions of 33 into distinct parts.  It also  cannot be written as a sum of 3 squares.

@Foon  Definitely not a parody but certainly I was interested enough to ask on SO before realising it would be much more fun here.

Imagemagick in some shell, 35
convert -size 448x448 xc:none a.png

Is this allowed?

Oh! I had no idea this would work. It's surprising and clever, so yes!

Please specify the shell

Bash, I guess? That's what I used when I tested it. Any POSIX shell should work?

Works also in Windows (if ImageMagick is in the PATH before \windows\system32).

On Windows ImageMagick is not being shipped with convert tool, because the name clashes with system utility. You run magick convert ...  instead.

I believe since convert is the language you wish to use, you only need to calculate the parameters as part of the byte count, so only the -size 448x448 xc:none a.png part. This is from the rule that non-standard parameters count in the byte count - but the filename itself shouldn't

@SztupY the convert is part of ImageMagick, so calling it its own language would not work.

it's an own command. You can just say the language you are using is ImageMagick Convert. Might be worth opening a meta about it though

APL (Dyalog Unicode), 11 bytesSBCS
Full program. Prints 448-by-448-by-4 array representing a 448-by-448 rgba image.
448 448 4⍴0

Try it online!
⍴ is reshape

I don't know APL at all, but I guess it doesn't have a duplicate to golf the 448 448?

448*448=200704, so cant you replace the space separated 448 448 with 200704, saving 1 byte?

@NaCl In that case why not just multiply that by 4 and have 802832p0 as the answer?

@NaCl Because that's not one of the valid image formats per default rules.

@JohnHamilton For the same reason as my answer to NaCl.

ironically that is how images are stored in most graphics image systems, as a one dimensional array

Go, 70
import i"image";func a()i.Image{return i.NewRGBA(i.Rect(0,0,448,448))}

Never seen a golf in Go before. Defines a function called a that outputs the image

Call it a Go-lf.

Java 8

Saving the image to a file with path s, 101 bytes
s->javax.imageio.ImageIO.write(new java.awt.image.BufferedImage(448,448,2),"png",new java.io.File(s))

Try it online... somehow
Returning the BufferedImage, 46 bytes
v->new java.awt.image.BufferedImage(448,448,2)

Saving the image to the file f, 83 bytes
f->javax.imageio.ImageIO.write(new java.awt.image.BufferedImage(448,448,2),"png",f)

Dumping PNG to STDOUT, 92 bytes (thanks ASCII-only!)
v->javax.imageio.ImageIO.write(new java.awt.image.BufferedImage(448,448,2),"png",System.out)

Try it online!Thanks to Kevin for saving a byte for the second and fourth solutions!

Do you mean empty or transparent?

I'm pretty sure empty pngs are transparent, are they not? I typed this up on my phone so I can't check

Just write to stdout

@ASCII-only So, write an empty (filled with zeros) 4484484 array to stdout? Anyways I like the idea of creating an actual PNG file.

@BenjaminUrquhart no i mean write the bytestream to stdout, you can just redirect in the stream anyway

like this. also you could use bash on TIO to verify your existing solution works

@ASCII-only I didn't know ImageIO.write accepted streams. Guess it makes sense

You can golf the ()-> in two of your answers to v->, since it's allowed to have an empty unused input (for which I personally use Void). Your last TIO would then be this instead.

what about 24 bytes output as 3d array rows, cols, rgba. like Python answer

@NahuelFouilleul because I want to output an actual image and not a pixel by pixel representation of one

Thank you for outputting an actual image!

@Anush you're welcome

Jelly, 8 bytes
448ṁ4¬¥þ

A niladic Link which yields a 448 by 448 RGBA array of transparent black pixels.
Try it online!
How?
448ṁ4¬¥þ - Link: no arguments
448      - 448
       þ - outer-product with: -- i.e. [[f(x,y) for y in [1..448]] for x in [1..448]]
      ¥  -   last two links as a dyad:
   ṁ4    -     mould like [1,2,3,4]  -- e.g. x=7 -> [7,7,7,7]
     ¬   -     logical NOT                       -> [0,0,0,0]

JavaScript (ES6), 74 69 bytes

f=
(_=document.createElement`canvas`)=>_.toDataURL(_.height=_.width=448)
;document.write(f());

Returns a PNG image encoded as a data: URL suitable e.g. for setting as the src of an HTMLImageElement. Edit: Saved 3 bytes thanks to @Shaggy and a further 2 bytes thanks to @Arnauld.

71 bytes?

document.createElement\canvas` ` should work, saving 2 more bytes.

If createelement is valid would seeing document.body and using the fact an id becomes a variable be valid? Also stack snippet pls

Could you add something like d=document at the top and replace document with d? Should save ~5 characters.

@Luke The document.write is just part of the stack snippet, not part of the function, so it doesn't count anyway.

Java 8, 23 (or 20) bytes
v->new int[448][448][4]

Returns a 3D array of 448x448x4 0s.
Try it online.
Explanation:
v->  // Method with empty unused parameter and 3D integer-array as return-type
  new int[448][448][4]
     // Create a 3D array of dimensions 448 by 448 by 4 (filled with 0s by default)

v->new int[448][448]

Returns a 448x448 matrix of 0s.
In Java, RGBA values can be represented by an integer. The hexadecimal 0x00000000 would represent 00 for red, green, blue, and alpha respectively. And 0x00000000 is equal to the integer 0.
Try it online.

Ah ah ah, love it :-) Doesn't it work with simply v->new int[448][448]? Because a color can be represented with an integer (RGBA) in Java.

@OlivierGrégoire No, I need the four 0s per 448x448 pixel for the RBGA values. EDIT: Hmm.. is an integer 0-255 a valid RBGA value? I know it's a valid RGB value, but also RGBA? I almost never use images in Java, so not too familiar with them. I simply based my 4 inner 0s on other answers.

Yes, four 0s as (in hexadecimal) 0x00000000 that fit on an int. The first 2 hex digits are the Alpha, the next 2 are the red, the next 2 are the green, the final 2 are the blue.So you only need an integer. See BufferedImage.TYPE_INT_ARGB. You have 4 values, summarized as one integer. And 0x00000000 is equal to 0.

I think this is the first time in ~2 years here I've seen Java actually be competitive!

@Shaggy With these golfing languages around it's still not that competitive.. Besides, I had a few other semi-competitive Java answers in the past, like this one, or this one that was winning until the Bash showed up (and R golfed its answer).

05AB1E, 12 10 9 bytes
448LDδ4Å0

Try it online.
or alternatively:
¾4Ž1ÂDиии

Try it online.
-2 bytes thanks to @Emigna.
-1 byte thanks to @Adnan.
Outputs a 448x448x4 3D list of 0s.
Explanation:
448LD      # Push a list in the range [1,448], and duplicate it
     δ     # Outer product; apply the following double-vectorized:
      4Å0  #  Push a list of 4 0s: [0,0,0,0]
           # (and output the result implicitly)

  Ž1ÂD     # Push compressed integer 448, and duplicate it
      и    # Create a list of 448 times 448
 4     и   # Transform it into a list of 448 times 448 times 4
¾       и  # Transform it into a list of 448 times 448 times 4 times 0
           # (and output the result implicitly)

See this 05AB1E answer of mine (section How to compress large integers?) to understand why Ž1Â is 448.

Processing, 66 bytes
PGraphics g=createGraphics(448,448);g.beginDraw();g.save("a.png");

dzaima/APL + APLP5, 18 16 bytes
{P5.img⍴∘0,⍨448}

Function that outputs an image object that can be drawn to the screen (for no effect) or converted back to pixel values.
-2 thanks to ngn!

would this work? {P5.img⍴∘0,⍨448}

@ngn it indeed would, thanks!

Python 2.7, 17 Bytes (22 With Print)
[[[0]*4]*488]*488

With Print:
print[[[0]*4]*488]*488

As variable:
x=[[[0]*4]*488]*488

As an array of RGBA is allowed, that is what I have created above, defaulting to all 0's - meaning black, but totally transparent.
Try it online!

Again, with this one, just multiply manually and you get [0]*802816 that should also work.

@JohnHamilton Correct me if I'm wrong, but I do believe that it would have to be a 3D array (An array of rows of pixels) i.e. array[pixel x coord][pixel y coord][r/g/b/a]

Not quite as concise but here is an alternative that gets the zeros into a numpy array... np.zeros([4]+[448]*2)

HTML, 25 bytes
Is this valid?
<svg height=448 width=448

Test it (background applied with CSS so you can "see" it)

I don't believe that this is valid, as writting <svg height=448 width=448 into an html file and opening it produces an empty <body>. However, with the penality of 1 byte, if you write <svg height=448 width=448>, it produces a <body> with an empty SVG image.

@IsmaelMiguel, we define languages by their interpreter rather than their (intended) implementation. That an interpreter exists (in this case CodePen) that allows us to omit the closing > means that this is, indeed, valid, as far as the markup goes.

Codepen adds additional HTML code to make it work. It adds a <!DOCTYPE html>, <html>, <head>, <style>, <script> and everything goes to the <body>. Some of the additional code is required to produce the desired output. You can see that the resulting code is parsed as <svg height="448" width="448" < body></svg>, because it writes <svg height=448 width=448 </body> in the iframe. As such, I still believe it isn't valid.

Rust - 206 201 168 bytes
use std::{io::Write,fs::File};fn main(){let mut v=vec![0,0,2,0,0,0,0,0,0,0,0,0,192,1,192,1,32,0];v.extend(vec![0u8;802816]);File::create("o.tga").unwrap().write(&v);}

This writes an actual, readable o.tga file, without any libraries or builtin functions, using the TGA binary format per http://paulbourke.net/dataformats/tga/ , by hard coding the width and height into the binary file header.

-5 bytes shorten filename, fix img size, @ASCII-only

does it need to be printed to a file though :P

does it even need to be 2 dimensional? I could just say [0;4444444]; and say i created a 444x444 transparent image. im making it interesting.

well also a would work as file name would it not. btw it's 448448 not 444444 so this is invalid

oops, ha ha thanks

to make it even more interesting, run length encode it :P (image data should be [255,0,0,0,0] 6272 times ([0,0,0,0] 128 times, repeated 6272 times). image type would then be 10 not 2. even better, colormap for shorter run length encoding (0,0,0,0 -> 0)

i think that would take more space than my version.

of course, but you said you wanted to make it interesting :P (rle colormapped should be something like [0,1,9,0,0,1,0,32,0,0,0,0,192,1,192,1,32,0,0,0,0,0] and [255,0] 6272 times btw). also, i wonder if you could make the first one a string? (escaping things like 0 -> \0 and/or 2 -> \x02 if you need to)

i couldnt figure out how the string version would be shorter.

You could make every value 1 byte, with no delimiter ad well, of course this assumes 0x00 is valid in a rust file and that strings have iter

i am not aware of how to do it at the current moment. rust strings are like, literally, utf8. ill try some things though

the problem with string encoding is that its not easily convertible to bytes, any way i can figure to do it will take up more space than just having the vector of bytes separated by commas.

You could save quite a lot if you sent it to the standard output: https://doc.rust-lang.org/std/io/fn.stdout.html and it is acceptable (most upvoted as well, in the meta): https://codegolf.meta.stackexchange.com/a/9095

"When operating in a console, the Windows implementation of this stream does not support non-UTF-8 byte sequences. Attempting to write bytes that are not valid UTF-8 will return an error." - i wanted it to be portable

C# (Visual C# Interactive Compiler), 21 bytes
_=>new int[448,448,4]

Try it online!

C# (Visual C# Interactive Compiler), 48 bytes
_=>(Enumerable.Repeat((0,0,0,0),200704),448,448)

Apparently outputting [1D array of pixels, width, height] is ok, so this outputs a tuple of `(IEnumerable of pixels, width, height).
Try it online!
C# (Visual C# Interactive Compiler), 58 bytes
_=>Enumerable.Repeat(Enumerable.Repeat((0,0,0,0),448),448)

The original matrix returning answer.
Since the image IO rules allow output as a matrix of RGB values, this submission outputs a matrix of RGBA values, represented by tuples with four values, all being 0.
Try it online!

PHP, 192 bytes
Sadly, PHP kinda sucks in that aspect because it requires a whole lot of code. But then again, where doesn't PHP suck.
$i=imagecreatetruecolor(448,448);imagesavealpha($i,true);$b=imagecolorallocatealpha($i,0,0,0,127);imagefill($i,0,0,$b);imagepng($i,'i.png');header('Content-type: image/png');readfile('i.png');

Ungolfed:
$i=imagecreatetruecolor(448,448);         // Create a new image with a set width
imagesavealpha($i,true);                  // Tell PHP to save alphachannels on that image
$b=imagecolorallocatealpha($i,0,0,0,127); // set the actual transparency values
imagefill($i,0,0,$b);                     // Fill the image with the color saved above
imagepng($i,'i.png');                     // Save the file as PNG
header('Content-type: image/png');        // Set the content type for the browser
readfile('i.png');                        // Read the file and output it

Obviously, if you just want to create it without outputting it, you can omit the header() and readfile() commands. Still, it's idiotically long.

on the positive side, this is one of the most 'readable' answers that indicates exactly what its doing

@donbright Not really the point of codegolfing tho. ;P However, there is no other way to do this in PHP I guess, unless I just echo some HTML.

@YUNOWORK According to the rules, you can export an array. You can use '<?php return '.var_export(array_fill(0,952576,0),1).';'; to export the array in an executable way. you can do php -f image.php > array.php, and somewhere else you can do $array = include('array.php'); to have an usable array again. But I don't know if it is valid, so, I'm giving it to you to add as an alternative. Or even a <?=json_encode(array_fill(0,952576,0));.

By the way, true can be replaced with 1, to save 3 bytes. Reading the documentation of imagepng(), you can just do header('Content-type: image/png');imagepng($i);. I believe you can also replace $b=imagecolorallocatealpha($i,0,0,0,127);imagefill($i,0,0,$b); with imagefill($i,0,0,imagecolorallocatealpha($i,0,0,0,127)); but dont quote me on that.

I just tested and <? imagecolorallocatealpha($i=imagecreate(448,448),0,0,0,127);header('Content-type: image/png');imagepng($i); produces a transparent image (109 bytes). Automatically sends the image to the browser/standard output and everything.

Python 3.7 - PIL Imported, 30 bytes
Image.new("LA",[448]*2).show()

This requires an import but has the benefit of creating and displaying an actual image file rather than an abstract empty array.
Explanation:
from PIL import Image
Image.new(    // create a new image
mode="LA"     // select LA colour mode, this is grey-scale plus an alpha channel
size=[448]*2  // size argument needs to be a 2D tuple, [448*2] is a better golf shot than (448,448)
color=0       // populates the image with the specified colour, helpfully preset to transparent
).show()      // display the image object

Image.show() will open the image in your default image program. In my case this opens a temporary bitmap file in Windows Photo Viewer but results may vary. Arguably this is cheating since the bitmap representation contains no transparency
Variations...
Image.new("LA",[448]*2)                 // 24 bytes but doesn't open image
Image.new("LA",[448]*2).show()          // 30 bytes, shows you a bitmap
Image.new("LA",[448]*2).save("x.png")   // 37 bytes, saves image to disk

If you do not count your import, you should state your language as Python 3.7 -- PIL imported or something similar. Furthermore, in your explanation you capitalize Import.

Thanks, corrected. Should I give my answer as 24 bytes, 30 or 37?

The byte count depends on the language you use. As of now, your submission takes 30 bytes in the language Python 3 with PIL imported. If you wrote in Python 3, it would most likely be longer. Of course, if you use the language Python 3 with the entire PIL namespace imported, your answer would be new("LA",[448]*2).show(), 26 bytes.

Thanks so much for submitting code I can actually run and which produces output I can test!

MATLAB, 31 bytes
imwrite(nan(448),'.png','tr',1)

Creates a 448 x 448 matrix of NaN values, and then uses imwrite to save them to a PNG file named '.png' and sets the transparency to 1, making it transparent. The 'Transparency' parameter name is able to be abbreviated to 'tr' as MATLAB allows for partial string  matching of parameter names as long as the shortened version is unique among available parameters.

wait, why 443??

@ASCII-only Fat fingers :)

O_o that was an insanely quick reply

Jelly, 10 9 bytes
x4Wẋ448Ɗ⁺

Try it online!
Outputs a 448x448x4 array
Thanks to @JonathanAllan for saving a byte.

2¡ can be ⁺

JavaScript (Node.js), 39 bytes
_=>[w=448,w,Array(w*w).fill([0,0,0,0])]

Apparently outputting [height, width, 1d array of RGBA values] is ok.
Try it online!
-3 bytes thanks to @Arnauld

invalid... it's a list of strings

Also you can output [1D array of pixels, width, height]

@ASCII-only Fixed now

41 bytes or 39 bytes if we can output [width, height, array].

SmileBASIC, 27 bytes
DIM A[448,448]SAVE"DAT:I",A

Saves a 2-dimensional 448x448 array filled with 0s to a file named DAT:I (Which is shorter than defining a function that returns the array, somehow)
The standard formats (used by all graphics functions) for colors in SmileBASIC are 32 bit ARGB and 16 bit 5551 RGBA, and 0 is transparent in both of them.

What makes this transparent instead of black?

The colors are in 4 byte ARGB format (commonly used in Smilebasic), so 0x00000000 is Alpha = 0, Red = 0, Green = 0, Blue = 0. Black would be 0xFF000000.

kudos to SmileBasic for using a RAW image format lol

I would complain on technicality that this isn't an image format since it isn't GRP but I'll let it go since the actual data being stored is the same.

@snail_ It's just outputting a matrix of pixels, not using a specific image format.

@12Me21 It's valid according to PPCG

raw pixel data is sometimes referred to as a raw image format, and a lot of cameras provide a raw pixel buffer data file. Photoshop can even read certain types of raw image formats. Unity3d can also use it for heightmaps

Red, 33 bytes
a: make image![448x448 0.0.0.255]

Opacity defaults to fully opaque(0)
This is how to use it /a full program/ :
Red [ ]
a: make image! [ 448x448 0.0.0.255 ]
view [ image a ]

MathGolf, 10 bytes
º4♦7*_ß{.a

Try it online!
Explanation
º            push [0]
 4           push 4
  ♦7*        push 64*7=448
     _       duplicate TOS
      ß      wrap last three elements in array (stack is now [[0], [4, 448, 448]])
       {     foreach in [4, 448, 448]
        .    repeat TOS x times
         a   wrap TOS in array

This method saves 1 byte compared to the "standard" ♦7*_4º*a*a*

ScPL for iOS Shortcuts, 98 bytes
Text"R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"
Base64Encode Decode
ResizeImage 448

Shortcut iCloud Link
Takes a 1x1 transparent gif encoded as base64 and resizes it

that was ... weird... what is the icloud link i just went to? ?

@donbright when you share a shortcut from the shortcuts app, it makes that link

Japt, 9 bytes
448ÆZç4Æ0

Try it online!

Jstx, 24 bytes
♪☺ü@/øP♦£Q)%)£Q◄úæD)%)£Q

Explanation
♪☺ü@ # Push literal 448
/    # Store the first stack value in the a register.
ø    # Push literal 0
P    # Push four copies of the first stack value.
♦    # Push literal 4
£Q   # Push stack values into a list of the size of the first stack value starting with the second stack value.
)    # Push the value contained in the a register.
%    # Push the second stack value the absolute value of the first stack value times.
)    # Push the value contained in the a register.
£Q   # Push stack values into a list of the size of the first stack value starting with the second stack value.
◄úæ  # Push literal \n
D    # Push the sum of the second and first stack values.
)    # Push the value contained in the a register.
%    # Push the second stack value the absolute value of the first stack value times.
)    # Push the value contained in the a register.
£Q   # Push stack values into a list of the size of the first stack value starting with the second stack value.

Try it online!

R, 21 bytes
array(0,c(448,448,4))

Try it online!
Returns a 3D-array of zeroes.

C++, SFML, 131 bytes
#include <SFML/Graphics.hpp>
void f(){sf::Image i;i.create(448,448);i.createMaskFromColor(sf::Color::Black);i.saveToFile("a.png");}

JavaScript + HTML, 56 bytes

location=C.toDataURL()
<canvas id=C width=448 height=448>

Clicking "Run code snippet" will generate a 448x448 transparent PNG in an IFRAME. You may then right-click "Save image as..." to download it to your computer.

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


text:
Black Hole challenge from codewars
I came across this challenge from codewars. I wish to know how to solve this problem. The problem description is given below.
Its elements are in range[1..n^2]. The matrix is filled by rings, from the outwards the innermost. Each ring is filled with numbers in the following way:

The first number is written in the top left corner;
The second number is written in the top right corner;
The third number is written in the bottom right corner;
The fourth number is written in the bottom left corner;
Each next number is written next to the number written 4 steps before it,
until the ring is filled.

The matrix is constructed when all numbers are written.```
Given the size of the hole, return the number written at (a, b) - you may use any consistent indexing, but please specify if (a, b) is anything other than 0-indexed and row-major.
Example
For n = 4, a = 1, b = 1, the output should be 13.
The hole looks like this:
[ [  1,  5,  9,  2 ]
  [ 12, 13, 14,  6 ]
  [  8, 16, 15, 10 ]
  [  4, 11,  7,  3 ]
]

The element at (1, 1) is 13

Test cases
(a, b) is 0-indexed and row-major here.
n   a   b   result
1   0   0    1
2   0   0    1
3   0   0    1
4   0   0    1
2   0   1    2
3   0   1    5
3   1   1    9
4   1   1   13
4   2   1   16
5   2   3   22

Welcome to the site.  As it stands your question is lacking a crucial component that we require of all questions, an "objective winning criterion".  That is, an objective way to score answers.  The most common one is [tag:code-golf].

@SriotchilismO'Zaic, Hi When I heard about Programming Puzzles and Code gulf, I thought it's about asking a programming challenge and getting a solution to it. Am sorry, am new to this site. I don't know 'Objective winning criterion'

If you want an easy winning criterion, the majority of the questions on this site are tagged as [tag:code-golf], meaning that the winning criterion is the least bytes.

@senox, Yes. Thanks for helping me. I would go with least bytes as winning criterion

May we instead take 1-indexed indices [a,b] (i.e. top-left is 1st row, 1st column, so [1,1] ...and your example 13 would be at [2,2])?

Please ping me when you've addressed @JonathanAllan's question and I'll cast my vote to reopen. Welcome to PPCG, by the way :) Nice first challenge. For future reference, we have a Sandbox where you can post challenges for community feedback and iron out any issues before posting them to Main.

Does codewars allow their challenges to be posted on other sites?

@JoKing. Am sorry, I dont know.

@JonathanAllan Sounds good.

Thanks, I made an update - it's best to edit the post accordingly rather than leaving specifications in the comment section - please check you agree with it.

@JonathanAllan. Now I agree with 1-indexed array. So do I need to edit the (a,b) values ?. Since it is 1-indexed array, [a,b] starts from [1,1].

I edited to allow other indexing, but kept zero-indexing and row-major (top-bottom; left-right) as the default (hence why I added the sentence above the test cases too) if you click "edited ... mins ago" you can see the diff.

If you're going to accept an answer at all, then at least accept the one that is actually winning by the winning criterion

Python 2, 120 119 90 bytes
def f(n,a,b):n-=1;A,B,C=min((a,b,1),(n-b,a,2),(n-a,n-b,3),(b,n-a,4));return(n-A)*4*A+4*B+C

Try it online!

Python 3, 87 bytes
def f(n,a,b):A,B=min((a,b+1/4),(n+~b,a+.5),(n+~a,n-b-1/4),(b,n-a));return(n+~A)*4*A+B*4

Try it online!
Returns a float
-3 bytes, thanks to Arnauld

Explanation:
This takes advantage of the fact that there is some symmetry to the matrix.
The matrix can be split into four quarters, which are equal when rotated (+ an offset of 1-3).

The first part A,B,C=... finds out which quarter the current coordinates are in, by finding the smallest coordinates, relative to each quarter:

(green: (a,b), yellow: (n-b,a), red: (n-a,n-b), blue: (b,n-a))
The coordinate pair is then converted to a value:
(0,0) = 1, (0,1) = 5, and so on; each coordinate is 4 larger than the previous.
sum((n-(i*2))*4for i in range(A)) skips the rows above, +(B-A)*4 moves along the row, and +C adds the offset.
sum((n-(i*2))*4for i in range(A))+(B-A)*4+C is shortened to (n-A)*4*A+4*B+C

it's interesting, the question seems to imply the input is always an even number, but your algorithm works for odd as well?

@donbright The testcases have both even and odd numbers?

lol oops!  my bad

05AB1E (legacy), 36 31 28 25 bytes
<αìRDÀsā)ø{н`Š4*ŠD¹<α4**O

Port of @TFeld's Python answer, so make sure to upvote him!
-3 bytes thanks to @Emigna.
Inputs are \$n\$ and \$[a,b]\$.
Uses the legacy version instead of the new 05AB1E version, because there seems to be a bug with the sorting ({) of multidimensional lists.
Try it online or verify all test cases.
Explanation:
<          # Decrease the (implicit) input `n` by 1
 α         # Take the absolute difference with the (implicit) input-list
           #  (we now have `[n-1-a, n-1-b]`)
  ì        # Prepend the input (we now have `[n-1-a, n-1-b, a, b]`)
   R       # Reverse the list (we now have `[b, a, n-1-b, n-1-a]`)
DÀ         # Duplicate this list, and rotate it once towards the left
    s      # Swap these two lists
ā          # Push a list in the range [1, length_list] without popping the list: [1,2,3,4]
     )     # Wrap all three lists into a list (we now have
           #  `[[a, n-1-b, n-1-a, b], [b, a, n-1-b, n-1-a], [1, 2, 3, 4]]`)
      ø    # Zip/transpose; swapping rows/columns (we now have
           #  `[[a, b, 1], [n-1-b, a, 2], [n-1-a, n-1-b, 3], [b, n-1-a, 4]]`)
       {н  # Get the minimum by sorting the lists and getting the first inner list
           # (since the minimum builtins in 05AB1E flatten multidimensional lists
           #  and give a single integer)
`          # Push all three values to the stack: `A`, `B`, and `C`
Š          # Triple-swap once, so the order is now `C`, `A`, `B`
 4*        # Multiply `B` by 4
Š          # Triple-swap again to `B*4`, `C`, `A`
 D         # Duplicate `A`
  ¹<α      # Take the absolute difference with `n-1` (so basically `n-1-A`)
     4*    # Multiply that by 4
       *   # Multiply it with the duplicated `A`
O          # Sum all values on the stack (`B*4 + C + (n-1-A)*4*A`)
           # (and output the result implicitly)

<αRIRì can be <αìR and 4L can be ā.

@Emigna I'm an idiot.. I tried some things with append, prepend, and rotates, and eventually ended up with what I had. Two reverses and a prepend.. Why not just prepend first and then reverse.. dohh.. Thanks! Oh, also thanks for ā. I always forget about that builtin for some reason..

Jelly, 28 bytes
³_1ị’;1×4
’0;_ⱮpƝẎAµżJṂFµæ.Ç

Try it online!
Based on @TFeld’s python answer so be sure to upvote that one too.

JavaScript (ES6), 86 bytes
(w,y,x)=>[x+(Y=w+~y)*y,y+(w+=~x)*x,w+Y*y,Y+w*x][k=x<y?x>Y?2:3:x<Y?0:x>y?1:Y-y&&2]*4-~k

Try it online!

Jelly, 20 bytes
ZUẎTḢṬ_Ʋṁ
+þ`ṠÇƬSœị@

A dyadic Link accepting n on the left and [a,b] (1-indexed) on the right.
Try it online!
How?
ZUẎTḢṬ_Ʋṁ - Link 1, next matrix (rotated): current matrix
Z         - transpose          }
 U        - reverse each row   } -> rotate clockwise 1/4
  Ẏ       - tighten into a flat list of values
       Ʋ  - last four links as a monad:
   T      -   truthy indices -- e.g. [0,0,1,0,1,1,0] -> [3,5,6]
    Ḣ     -   head (empty list yields 0)             ->  3
     Ṭ    -   un-truth (0 yields an empty list)      -> [0,0,1]
      _   - subtract (vectorises)                    -> [0,0,0,0,1,1,0]
        ṁ - mould to shape of the current matrix again

+þ`ṠÇƬSœị@ - Main Link: integer, n; list of integers [a,b]
  `         - using left (n) as both arguments:
 þ          -   table of (implicit range of integer arguments)
+           -     addition
   Ṡ        - sign -- now we have an n by n matrix of ones
     Ƭ      - collect up (a list of matrices) while results are different with:
    Ç       -   last Link (1) as a monad
      ¬     - logical NOT (replace the 1s with 0s and vice-versa)
       S    - sum (vectorises)
          @ - with swapped arguments:
        œị  -   multidimensional index into

Rust - 340 bytes
fn f(n:usize,x:usize,y:usize)->usize{let (mut r,d)=(0,(n-1)&1);for l in ((1+d)..=n).step_by(2) {let (mut i,m,mx,mut z)=(0,l/2,n/2,0);loop {z=4*i+n*n-l*l;let u=[mx+m-i-d,mx-m,mx+m-d,mx-m+i];if (x,y)==(u[0],u[1]){r=z+4}if (x,y)==(u[2],u[0]){r=z+3}if (x,y)==(u[3],u[2]){r=z+2}if (x,y)==(u[1],u[3]){r=z+1}i+=1;if i>=l-1{break};}}r}

still got some work to do, but it basically draws the whole spiral, centered on a point in the middle, and saves the value at requested point x,y.
ungolf spiral draw at play.rust-lang.org

source: Stack Exchange

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

sort: votes


text:
Shift the weekday!
Employers love to see their employees working hard, while the employees would love to work less, especially those with a monthly rather than hourly payment.
The laziest of employees are thinking about the world where every month starts with the same weekday and it makes them wonder if they would work more or less.
The greediest of employers are thinking about the world where every month starts with the same weekday and it makes them wonder if their employees would work more or less.
Your task (as a lazy employee or greedy employer, you choose) is to write the shortest program or function that given weekday every month must start outputs the number of working and weekend days.
Input

Weekday identificator. This can be a 0- or 1-based index, case-insensitive shortname (Mo/Mon, Tu/Tue etc) or case-insensitive full name (Monday, tuesday etc) as long as you specify the format.

Output

One of the following output formats allowed:

A string of single space/comma/semicolon separated values.
A list of values.
A multi-line string of values with a trailing line break allowed.

The output format must be consistent.
2 values must present in the output: number of working days in base 10 and number of weekends in base 10.

Rules

Assume the year is 365 days.
Workdays are Monday, Tuesday, Wednesday, Thursday and Friday.
Week starts with Monday.
No national weekends are accounted.
This is code-golf so all usual golfing rules apply, and the shortest code (in bytes) wins.

Examples
 Input  | Output
--------+--------
 Monday | 269 96
    Tue | 269,96
      3 | 269 96   // 1-based index
      3 | 262, 103 // 0-based index
     fr | 251;114
      5 | 247 118  // 0-based index
 sunday | 258;107 // 0-based index

If anyone can come up with a more pun title, feel free to change it.

So this can be hardcoded?

@Quintec and I was hoping I thought of everything... I generalized the challenge.

Must we assume that the months work like in the Gregorian calendar? Like, are there 7 months with 31 days, 4 months with 30 days and 1 month with 28 days?

@EriktheOutgolfer I thought about adding an arbitrary length of months to make it more challenging and now that one of the ways is to precalculate most of the values I see I should have done that... But yea, your assumption is correct.

Isn't Week starts with Monday just an arbitrary restriction?

@Adám it is for those not hardcoding precalculated values (doubt anyone will do this way) and might that yield a different results.

JavaScript (ES6),  34  33 bytes
Takes input as a 0-based index. Returns [weekend_days, working_days].
i=>[w=96|'5621'[i-3]*11%24,365-w]

Try it online!
How?
The minimum number of weekend days \$w_i\$ being \$96\$, we can just store the difference \$d_i=w_i-96\$ for each possible input and output \$[96+d_i, 365-(96+d_i)]\$.
This gives:
$$[0,0,0,7,18,22,11]$$
It's worth noting that \$96=2^5+2^6\$ and each value above is less than \$2^5\$, which means that we can compute \$96\text{ OR }d_i\$ instead of \$96+d_i\$ and still get the correct result.
We use the following formula to convert \$i\$ to \$d_i\$:
$$d_i=(x_i\times11)\bmod 24$$
where \$x_i\$ consists of a single decimal digit:
$$[0,0,0,5,6,2,1]$$
Hence the JS code:
96 | '5621'[d - 3] * 11 % 24

For \$i<3\$, '5621'[d-3] is undefined and '5621'[d-3]*11%24 results in NaN. But because we use a bitwise OR, this is coerced to \$0\$ and returns \$96\$ as expected.

Python 3.8 (pre-release), 37 bytes
lambda d:(k:=ord('```grvk'[d]),365-k)

Monday is 0, returns a tuple (weekend days, weekdays).
Try it online!

Jelly,  16  15 bytes
-1 thanks to Erik the Outgolfer (use of printing in a full-program mode)
ị“```grvk‘Ṅ365_

Monday is 1, prints weekend days then weekdays to STDOUT.
Try it online!

I am not sure how to build data for Jelly's hash function, ḥ, but maybe that would be better...

I don't think the hash function will be better, as you'd still need to include the “```grvk‘ list in the left argument. However, you can save a byte by converting this to a full program (;365ạ\ → Ṅ365_).

I thought one could use the inputs as the keys with some salt that produces the right numbers by search (the option to take the day name would work best I guess); the salt could be bigger though... Anyway I don't know how any of the code works or how to use the C++ code on the branch - if you have some time maybe you can work that out. Nice golf using printing, thanks!

05AB1E, 17 bytes
.•OζΛ¦•IèÇ<D365αì

0-indexed (0 = Monday; 6 = Sunday), returns [working_days, weekend_days].
Try it online or verify all test cases.
Explanation:
.•OζΛ¦•            # Push compressed string "aaahswl"
       Iè          # Index the input-integer into it
         Ç         # Convert the character to its unicode value
          <        # Decrease that by 1
           D365α   # Create a copy, and get its absolute difference with 365
                ì  # Prepend this (and output the result implicitly)

See this 05AB1E tip of mine (section How to compress strings not part of the dictionary?) to understand why .•OζΛ¦• is "aaahswl".


text:
Source permutation
A permutation of a set \$S = \{s_1, s_2, \dotsc, s_n\}\$ is a bijective function \$\pi: S \to S\$. For example, if \$S = \{1,2,3,4\}\$ then the function \$\pi: x \mapsto 1 + (x + 1 \mod 4)\$ is a permutation:
$$
\pi(1) = 3,\quad
\pi(2) = 4,\quad
\pi(3) = 1,\quad
\pi(4) = 2
$$
We can also have permutations on infinite sets, let's take \$\mathbb{N}\$ as an example: The function \$\pi: x \mapsto x-1 + 2\cdot(x \mod 2)\$ is a permutation, swapping the odd and even integers in blocks of two. The first elements are as follows:
$$
2,1,4,3,6,5,8,7,10,9,12,11,14,13,16,15,\dotsc
$$
Challenge
Your task for this challenge is to write a function/program implementing any1 permutation on the positive natural numbers. The score of your solution is the sum of codepoints after mapping them with the implemented permutation.
Example
Suppose we take the above permutation implemented with Python:
def pi(x):
    return x - 1 + 2*(x % 2)

Try it online!
The character d has codepoint \$100\$, \$\texttt{pi}(100) = 99\$. If we do this for every character, we get:
$$
99,102,101,31,111,106,39,119,42,57,9,31,31,31,31,113,102,115,118,113,109,31,119,31,46,31,50,31,44,31,49,41,39,119,31,38,31,49,42
$$
The sum of all these mapped characters is \$2463\$, this would be the score for that function.
Rules
You will implement a permutation \$\pi\$ either as a function or program

given an natural number \$x\$, return/output \$\pi(x)\$
for the purpose of this challenge \$\mathbb{N}\$ does not contain \$0\$
the permutation must non-trivially permute an infinite subset of \$\mathbb{N}\$
your function/program is not allowed to read its own source

Scoring
The score is given by the sum of all codepoints (zero bytes may not be part of the source code) under that permutation (the codepoints depend on your language2, you're free to use SBCS, UTF-8 etc. as long as your language supports it).
The submission with the lowest score wins, ties are broken by earliest submission.

Except for permutations which only permute a finite subset of \$\mathbb{N}\$, meaning that the set \$\{ x | \pi(x) \neq x \}\$ must be infinite.
If it improves your score, you can for example use a UTF-8 encoded Jelly submission instead of the usual SBCS.

@JoKing "zero bytes may not be part of the source code" re: the second question

Related.

Jelly, score  288 250 212  199
-38 thanks to Erik the Outgolfer!
C-*+

Swaps even with odd.
The score is \$67+45+44+43=199\$ - see self-scoring here.
Try it online!

Apparently, Leaky Nun's -*ạ has a score of 300... however, -*_@ has a score of 250. Maybe I should post that as my own, although it's the same permutation.

Ah nice observation by Leaky Nun, so -*N+ scores 212

It wasn't an observation, it was a self-answer to his (now pretty old) challenge. ;-)

C-*+ sound like some future variation of C++.

JavaScript (ES6), Score =  276  268
$=>(--$^40)+!0

Try it online!

but 54^54 is 0

@JonathanAllan Thanks for notifying. I somehow missed that part. Should be correct now.

Perl 6, Score: 201
*-!0+^40+!0

Try it online!
Port of Arnauld's answer. This benefits from xor (+^) having the same precedence as - and +, and the use of a Whatever lambda to reduce overall characters. Other than that, I couldn't find a way of representing it differently that got a better score.
Perl 6, Score 804 702
{{(++$∉ords(q[!$%()+-2?[]_doqrsx{}∉])??++$+22-$++%2-$++%2!!++$)xx$_}()[-!$+$_]}

Try it online!
The first quine-y type answer here, and I think it scores pretty well.
This produces the sequence \$23,22,25,24...\$ from the question body with the range \$1,2,3,4...21\$ inserted at the indexes of the unique sorted codepoints of the code. For example, the 30th through 35th elements of the sequence are \$50, 53, 52, 1, 55, 54\$ since the 33rd codepoint is ! and that's the lowest codepoint in my code.

O_o that's a massive improvement

Python 2 score: 742 698 694 points
lambda a:a^96or~~96

Try it online!
-44 points thanks to Ørjan Johansen; -4 points thx to xnor.

Ørjan Johansen: Fixed (and it saved me 44 bytes!)

Good save (although that's not bytes)

That's some generous crediting!

Wouldn't have edited if you hadn't pointed out the flaw :)

It's cheaper to replace the space before 96 with ~~.

Retina 0.8.2, 6 bytes, score 260
T`O`RO

Try it online! Link includes self-scoring footer. Simply swaps digits 1 and 9 and 3 and 7 in the decimal representations, so that numbers that contain no digits coprime to 10 are unaffected.

C# (Visual C# Interactive Compiler), 22 bytes, Score 247 245
A=>A>65?A-1+A%2*2:66-A

Try it online!
Simple, if less than 66, return 66 minus input, else use the formula in the question that swaps even and odd numbers.

What's wrong with the previous version A=>A<66?66-A:A?

@JoKing Except for permutations which only permute a finite subset of $\mathbb{N}$, meaning that the set ${ x | \pi(x) \neq x }$ must be infinite. The set isn't infinite, since the only values in the set are 1-65, since above 65, all values of A map to A

Oh darn, I didn't notice that. That means my own answer is invalid too :(

TI-BASIC, 9 bytes, score 1088 1051 1000
Ans-cos(π2fPart(2⁻¹Ans

Swaps even with odd.  Even maps to Ans-1 and odd maps to Ans+1.
TI-BASIC is tokenized, so this program will have the following hex-values:
Ans   -    cos(  π    2    fPart(  2   ⁻¹  Ans
72    71   C4    AC   32   BA      32  0C  72

Thus the score is: \$113+114+195+171+49+185+49+11+113=1000\$
Output test program:
For(I,1,10
I
Ans-cos(π2fPart(2⁻¹Ans
Disp Ans
Pause
End

Which outputs:
2
1
4
3
6
5
8
7
10
9

Notes:

TI-BASIC's token values can be found here.
Pause is used in the output program to better see the permutation, as the calculator only has 8 lines.  Press [ENTER] to view the next permutation.

Charcoal, 13 bytes, score 681
⁻⁺²³²ι⊗﹪⊖ι²³³

Try it online! Link is to self-scoring version with header to map over an array of byte codes. (Charcoal has a custom code page so I've manually inserted the correct byte codes in the input.) Works by reversing ranges of 233 numbers, so that 117, 350, 583 ... are unchanged. Explanation:
     ι          Value
 ⁺              Plus
  ²³²           Literal 232
⁻               Minus
         ι      Value
        ⊖       Decremented
       ﹪        Modulo
          ²³³   Literal 233
      ⊗         Doubled

Haskell, score 985
(\((.),(-))->(.)*200+mod(-39+(-))200+1).(\(*)->divMod((*)-1)200)

Try it online!

I don't think this is a permutation, since adding a*200 has no effect modulo 200 so a  doesn't matter.

@xnor Good catch. That's supposed to be outside of the mod. At some point while golfing, I must have messed up order of operations. Fixed now, thanks!

I think there's another issue that 40 maps to 0 but the challenge requires positive integers, which makes approaches like this tricky.

@xnor Fixed. (Sigh, there goes my score.)

Using sum[1|...] over if..then..else should help.

@ბიმო That helped a lot, thanks!

looks a bit better :P

Btw. what happened to 161?

@ASCII-only I'm not convinced that adding a \\ and causing a warning makes it look better :P

@ბიმო I originally either subtracted 39 or added 161 to the remainder. Now, instead, I always subtract 39 and add 1 to the quotient in the cases when I would have added 161 before.

better? :P

@ASCII-only Sure, edited.

I meant that your function doesn't map to 161, so it's not a permutation.

@ბიმო Ah, I thought you were asking where the constant in my code went. Okay, fixing...

@ბიმო Fixed. (Interestingly, fixing that improved my score.)

1208?

@ASCII-only Yep, nice savings!

1018?

btw, you don't need bytecount since that doesn't matter

Let us continue this discussion in chat.

05AB1E, score: 488 in 05AB1E's code page
È·<-

Swaps odd and even like the example function.
Will try to improve the score from here.
Try it online with input in the range [1, 100] or Try it online with the codepoints.
Explanation:
È     # Check if the (implicit) input is even (1 if truthy; 0 if falsey)
 ·    # Double (2 if truthy; 0 if falsey)
  <   # Decrease by 1 (1 if truthy; -1 if falsey)
   -  # Subtract it from the (implicit) input (and output implicitly)

Brainfuck, 47 bytes, score 2988
,[-<+<+>>]<[->[>+<[-]]+>[<->-]<<]>[-<<++>>]<<-.

Try it online!
I used the permutation given in the introduction. Since this is bijection you can use it as a simple symmetric cipher similar to ROT13 or Atbash. My solution works on unbounded cells. However, by restricting yourself to 8-bit cells, you could save 2 points by replacing [-] with [+].


text:
New Order #1: How does this feel?
Introduction
Putting all positive numbers in its regular order (1, 2, 3, ...) is a bit boring, isn't it? So here is a series of challenges around permutations (reshuffelings) of all positive numbers.
The first challenge in this series is to output a(n) for a given n as input, where a(n) is A064413, also known as the EKG sequence because the graph of its values resembles an electrocardiogram (hence the "How does this feel" reference). Interesting properties of this sequence are that all positive integers appear exactly once. Another notable feature is that all primes occur in increasing order.

Task
Given an integer input n, output a(n).
\$a(n)\$ is defined as:

\$a(1) = 1; a(2) = 2;\$
for \$n > 2\$, \$a(n)\$ is the smallest number not already used which shares a factor with \$a(n-1)\$

Note: 1-based indexing is assumed here; you may use 0-based indexing, so \$a(0) = 1; a(1) = 2\$, etc. Please mention this in your answer if you choose to use this.
Test cases
Input | Output
--------------
1     | 1
5     | 3
20    | 11
50    | 49
123   | 132
1234  | 1296
3000  | 3122
9999  | 10374

Rules

Input and output are integers (your program should at least support input and output in the range of 1 up to 32767)
Invalid input (floats, strings, negative values, etc.) may lead to unpredicted output, errors or (un)defined behaviour.
Default I/O rules apply.
Default loopholes are forbidden.
This is code-golf, so the shortest answers in bytes wins

Final note
See this related PP&CG question.

@Giuseppe: this is not a duplicate. The other question isn't about the sequence itself, but a slice of the sequence ("the n first terms of the sequence are greater than n" to be exact). This is a more "pure sequence" version of the same sequence (and thus another challenge). By the way: sandboxed here.

Seems like for most, if not all, languages it would be a trivial change from counting greater than n to indexing into at n or tailing. For example Husk in the linked challenge is #>¹↑¡§ḟȯ←⌋→`-Nḣ2 and here !¡§ḟȯ←⌋→`-Nḣ2 would do (Try it). The definition of "duplicate" is not "is exactly the same as". I'll leave it to others to decide since I don't want to hammer this closed as I may have missed something.

Maybe you should specify that a(n) shares a factor other than 1 with a(n-1), since every number shares 1 as a factor. Also, may my answer be '2-indexed', where a(2) is 1, a(3) is 2, and so on?

This would be good for one fast code completion...

05AB1E, 25 bytes
1ˆ2ˆF∞.Δ¯yå≠¯θy¿2@*}ˆ}¯¨θ

0-indexed
Try it online or Output the first \$n\$ items.
Explanation:
1ˆ2ˆ            # Add both 1 and 2 to the global_array
F               # Loop the (implicit) input amount of times:
 ∞.Δ            #  Get the first 1-indexed value resulting in truthy for the following:
    ¯yå≠        #   Where this value is not in the global_array yet
              * #   AND:
        ¯θ ¿    #   Where the greatest common divisor of the last item of the global_array
          y @2  #   and the current value, is larger than or equal to 2
   }ˆ           #  After a new value has been found: add it to the global_array
}¯              # After the loop: push the global_array
  ¨θ            # Then remove the last element, and then take the new last element
                # (which is output implicitly as result)

Haskell, 66 65 64 bytes
f n|n<3=n|m<-n-1=[k|k<-[1..],k`gcd`f m>1,all(/=k)$f<$>[1..m]]!!0

Try it online!

Haskell, 60 bytes
((1:2#[3..])!!)
n#l|x:_<-[y|y<-l,gcd y n>1]=n:x#filter(/=x)l

Try it online!
Zero-indexed; could save four bytes if series started with 2 (kinda (-1)-indexed, but without value for -1 being defined). Builds the infinite list by lazily maintaining the list of unused numbers.

Might be worth mentioning that you could make this considerably less inefficient if you import Data.List and use delete x instead of filter(/=x). If this needs to work for large arguments, such an optimization will quickly become necessary.

Indeed, using delete is the reasonable thing to do here, but in code-golf we don't care. I sometimes mention more efficient variants, when the difference is spectacular, or otherwise interesting. Here, it is not too bad: TIO can compute all test cases in less than 10 seconds.

Python 2, 104 bytes
This uses 0-based indexing.
from fractions import*
l=[1,2]
exec'i=3\nwhile gcd(i,l[-1])<2or i in l:i+=1\nl+=i,;'*input()
print l[-2]

Try it online!

Ruby, 86 bytes
a=->(n){n<3?n:1.step{|i|return i if a[n-1].gcd(i)!=1&&(0...n).map(&a).all?{|j|j!=i}}}

This runs forever for inputs as low as 10, though.

Here's a version with memoization with 102 bytes that runs in acceptable time:
m={};a=->(n){n<3?n:m[n]||1.step{|i|return m[n]=i if a[n-1].gcd(i)!=1&&(0...n).map(&a).all?{|j|j!=i}}}

can you save a byte with gcd >1 instead of !=1?

MACHINE LANGUAGE(X86, 32 bit)+C language library malloc()/free()functions, bytes 325
00000750  51                push ecx
00000751  52                push edx
00000752  8B44240C          mov eax,[esp+0xc]
00000756  8B4C2410          mov ecx,[esp+0x10]
0000075A  3D00000000        cmp eax,0x0
0000075F  7414              jz 0x775
00000761  81F900000000      cmp ecx,0x0
00000767  740C              jz 0x775
00000769  39C8              cmp eax,ecx
0000076B  7710              ja 0x77d
0000076D  89C2              mov edx,eax
0000076F  89C8              mov eax,ecx
00000771  89D1              mov ecx,edx
00000773  EB08              jmp short 0x77d
00000775  B8FFFFFFFF        mov eax,0xffffffff
0000077A  F9                stc
0000077B  EB11              jmp short 0x78e
0000077D  31D2              xor edx,edx
0000077F  F7F1              div ecx
00000781  89C8              mov eax,ecx
00000783  89D1              mov ecx,edx
00000785  81FA00000000      cmp edx,0x0
0000078B  77F0              ja 0x77d
0000078D  F8                clc
0000078E  5A                pop edx
0000078F  59                pop ecx
00000790  C20800            ret 0x8

00000793  53                push ebx
00000794  56                push esi
00000795  57                push edi
00000796  55                push ebp
00000797  55                push ebp
00000798  8B442418          mov eax,[esp+0x18]
0000079C  3D02000000        cmp eax,0x2
000007A1  7641              jna 0x7e4
000007A3  3DA0860100        cmp eax,0x186a0
000007A8  7757              ja 0x801
000007AA  40                inc eax
000007AB  89C7              mov edi,eax
000007AD  C1E003            shl eax,0x3
000007B0  50                push eax
000007B1  E80E050000        call 0xcc4
000007B6  81C404000000      add esp,0x4
000007BC  3D00000000        cmp eax,0x0
000007C1  743E              jz 0x801
000007C3  89C5              mov ebp,eax
000007C5  89F8              mov eax,edi
000007C7  C1E002            shl eax,0x2
000007CA  890424            mov [esp],eax
000007CD  50                push eax
000007CE  E8F1040000        call 0xcc4
000007D3  81C404000000      add esp,0x4
000007D9  3D00000000        cmp eax,0x0
000007DE  7415              jz 0x7f5
000007E0  89C3              mov ebx,eax
000007E2  EB28              jmp short 0x80c
000007E4  E9A3000000        jmp 0x88c
000007E9  53                push ebx
000007EA  E8E5040000        call 0xcd4
000007EF  81C404000000      add esp,0x4
000007F5  55                push ebp
000007F6  E8D9040000        call 0xcd4
000007FB  81C404000000      add esp,0x4
00000801  B8FFFFFFFF        mov eax,0xffffffff
00000806  F9                stc
00000807  E981000000        jmp 0x88d
0000080C C60301            mov byte [ebx],0x1
0000080F  C6430101          mov byte [ebx+0x1],0x1
00000813  C7450001000000    mov dword [ebp+0x0],0x1
0000081A  C7450402000000    mov dword [ebp+0x4],0x2
00000821  B902000000        mov ecx,0x2
00000826  BE01000000        mov esi,0x1
0000082B  B802000000        mov eax,0x2
00000830  8B542418          mov edx,[esp+0x18]
00000834  4A                dec edx
00000835  C6040300          mov byte [ebx+eax],0x0
00000839  40                inc eax
0000083A  3B0424            cmp eax,[esp]
0000083D  72F6              jc 0x835
0000083F  BF02000000        mov edi,0x2
00000844  81C701000000      add edi,0x1
0000084A  3B3C24            cmp edi,[esp]
0000084D  779A              ja 0x7e9
0000084F  803C3B01          cmp byte [ebx+edi],0x1
00000853  74EF              jz 0x844
00000855  57                push edi
00000856  51                push ecx
00000857  E8F4FEFFFF        call 0x750
0000085C  3D01000000        cmp eax,0x1
00000861  76E1              jna 0x844
00000863  46                inc esi
00000864  897CB500          mov [ebp+esi*4+0x0],edi
00000868  89F9              mov ecx,edi
0000086A  C6043B01          mov byte [ebx+edi],0x1
0000086E  39D6              cmp esi,edx
00000870  72CD              jc 0x83f
00000872  53                push ebx
00000873  E85C040000        call 0xcd4
00000878  81C404000000      add esp,0x4
0000087E  55                push ebp
0000087F  E850040000        call 0xcd4
00000884  81C404000000      add esp,0x4
0000088A  89F8              mov eax,edi
0000088C  F8                clc
0000088D  5D                pop ebp
0000088E  5D                pop ebp
0000088F  5F                pop edi
00000890  5E                pop esi
00000891  5B                pop ebx
00000892  C20400            ret 0x4
00000895

Above gcd and the function...
This below assembly code generate the functions and the test program:
; nasmw -fobj  this.asm
; bcc32 -v  this.obj
section _DATA use32 public class=DATA

global _main
extern _printf
extern _malloc
extern _free

dspace dd 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0

fmt db "%u " , 13, 10, 0, 0
fmt1 db "%u %u" , 13, 10, 0, 0

IgcdIIuIIIuIIIuIn db "gcd(%u, %u)=%u" , 13, 10, 0, 0
IfunIIuIIIuIn db "fun(%u)=%u" , 13, 10, 0, 0

section _TEXT use32 public class=CODE

gcd:
      push    ecx
      push    edx
      mov     eax,  dword[esp+  12]
      mov     ecx,  dword[esp+  16]
      cmp     eax,  0
      je      .e
      cmp     ecx,  0
      je      .e
      cmp     eax,  ecx
      ja      .1
      mov     edx,  eax
      mov     eax,  ecx
      mov     ecx,  edx
      jmp     short  .1
.e:   mov     eax,  -1
      stc
      jmp     short  .z
.1:   xor     edx,  edx
      div     ecx
      mov     eax,  ecx
      mov     ecx,  edx
      cmp     edx,  0
      ja      .1            ; r<c
.2:   clc
.z:
      pop     edx
      pop     ecx
      ret     8

fun:
      push    ebx
      push    esi
      push    edi

   push    ebp
      push    ebp
      mov     eax,  dword[esp+  24]
      cmp     eax,  2
      jbe     .a
      cmp     eax,  100000
      ja      .e
      inc     eax
      mov     edi,  eax
      shl     eax,  3
      push    eax
      call    _malloc
      add     esp,  4
      cmp     eax,  0
      je      .e
      mov     ebp,  eax
      mov     eax,  edi
      shl     eax,  2
      mov     dword[esp+  0],  eax
      push    eax
      call    _malloc
      add     esp,  4
      cmp     eax,  0
      je      .0
      mov     ebx,  eax
      jmp     short  .1
.a:   jmp     .y
.b:   push    ebx
      call    _free
      add     esp,  4
.0:   push    ebp
      call    _free
      add     esp,  4
.e:   mov     eax,  -1
      stc
      jmp     .z
.1:   mov     byte[ebx],  1
      mov     byte[ebx+1],  1
      mov     dword[ebp],  1
      mov     dword[ebp+4],  2
      mov     ecx,  2
      mov     esi,  1
      mov     eax,  2
      mov     edx,  dword[esp+  24]
      dec     edx
.2:   mov     byte[ebx+eax],  0
      inc     eax
      cmp     eax,  dword[esp+  0]
      jb      .2
.3:   mov     edi,  2
.4:   add     edi,  1
      cmp     edi,  dword[esp+  0]
      ja      .b
      cmp     byte[ebx+edi],  1
      je      .4
      push    edi
      push    ecx
      call    gcd
      cmp     eax,  1
      jbe     .4
      inc     esi
      mov     [ebp+esi*4],  edi
      mov     ecx,  edi
      mov     byte[ebx+edi],  1
      cmp     esi,  edx
      jb      .3
      push    ebx
      call    _free
      add     esp,  4
      push    ebp
      call    _free
      add     esp,  4
      mov     eax,  edi
.y:   clc
.z:
      pop     ebp
      pop     ebp
      pop     edi
      pop     esi
      pop     ebx
      ret     4

_main:
      pushad

      push    6
      push    3
      call    gcd
      pushad
      push    eax
      push    6
      push    3
      push    IgcdIIuIIIuIIIuIn
      call    _printf
      add     esp,  16
      popad
      push    2
      push    2
      call    gcd
      pushad
      push    eax
      push    2
      push    2
      push    IgcdIIuIIIuIIIuIn
      call    _printf
      add     esp,  16
      popad

      push    1
      push    1
      call    gcd
      pushad
      push    eax
      push    1
      push    1
      push    IgcdIIuIIIuIIIuIn
      call    _printf
      add     esp,  16
      popad
      push    0
      push    1
      call    gcd
      pushad
      push    eax
      push    0
      push    1
      push    IgcdIIuIIIuIIIuIn
      call    _printf
      add     esp,  16
      popad
      push    0
      call    fun
      pushad
      push    eax
      push    0
      push    IfunIIuIIIuIn
      call    _printf
      add     esp,  12
      popad
      push    1
      call    fun
      pushadpush    eax
      push    1
      push    IfunIIuIIIuIn
      call    _printf
      add     esp,  12
      popad
      push    2
      call    fun
      pushad
      push    eax
      push    2
      push    IfunIIuIIIuIn
      call    _printf
      add     esp,  12
      popad
      push    3
      call    fun
      pushad
      push    eax
      push    3
      push    IfunIIuIIIuIn
      call    _printf
      add     esp,  12
      popad
      push    4
      call    fun
      pushad
      push    eax
      push    4
      push    IfunIIuIIIuIn
      call    _printf
      add     esp,  12
      popad
      push    5
      call    fun
      pushad
      push    eax
      push    5
      push    IfunIIuIIIuIn
      call    _printf
      add     esp,  12
      popad
      push    123
      call    fun
      pushad
      push    eax
      push    123
      push    IfunIIuIIIuIn
      call    _printf
      add     esp,  12
      popad
      push    1234
      call    fun
      pushad
      push    eax
      push    1234
      push    IfunIIuIIIuIn
      call    _printf
      add     esp,  12
      popad
      push    3000
      call    fun
      pushad
      push    eax
      push    3000
      push    IfunIIuIIIuIn
      call    _printf
      add     esp,  12
      popad
      push    9999
      call    fun
      pushad
      push    eax
      push    9999
      push    IfunIIuIIIuIn
      call    _printf
      add     esp,  12
      popad
      push    99999
      call    fun
      pushad
      push    eax
      push    99999
      push    IfunIIuIIIuIn
      call    _printf
      add     esp,  12
      popad
      popad
      mov     eax,  0
      ret

the results:
gcd(3, 6)=3
gcd(2, 2)=2
gcd(1, 1)=1
gcd(1, 0)=4294967295
fun(0)=0
fun(1)=1
fun(2)=2
fun(3)=4
fun(4)=6
fun(5)=3
fun(123)=132
fun(1234)=1296
fun(3000)=3122
fun(9999)=10374
fun(99999)=102709

It is possible bugs and wrong copy past...

Perl 6, 84 80 73 69 50 49 bytes
(0-indexed)
{(1,2,{+(1...all @_[*-1]gcd*>1,*∉@_)}...*)[$_]}

Thanks to this answer for some tricks.
Thanks to ASCII-only for shaving a byte.

Have you tried using the sequence operator ...? It makes sequence stuff like this a lot easier. For example, your my@a=1,2;push @a,operation while condition can be 1,2,{operation}...condition. With a few other golfs, this can be as low as 49 bytes

Not sure if that'd work here because the next term depends on all of the previous terms.

67 (0-indexing is allowed though, so this could be 65)

Derp, didn't come to my mind that there was .first.

O_o well that was a big jump. it'd be nice if you could link to TIO though

check the comments on the other answer, 49. also please don't put "(0-indexed)" in title, it messes up leaderboard scripts

APL(NARS), chars 119, bytes 238
∇r←a w;i;j;v
r←w⋄→0×⍳w≤2⋄i←2⋄r←⍳2⋄v←1,1,(2×w)⍴0
j←¯1+v⍳0
j+←1⋄→3×⍳1=j⊃v⋄→3×⍳∼1<j∨i⊃r⋄r←r,j⋄i+←1⋄v[j]←1⋄→2×⍳w>i
r←i⊃r
∇

this test it takes 1m:49s here:
  a¨1 5 20 50 123 1234 3000
1 3 11 49 132 1296 3122

Java (JDK), 161 155 152 151 bytes
Saved a byte by switching int[] tracking to leverage the existing BigInteger!
n->{int j,k=n;for(var b=java.math.BigInteger.ONE;0<--n;b=b.setBit(k=j))for(j=1;b.testBit(++j)|b.valueOf(j).gcd(b.valueOf(k)).intValue()<2;);;return k;}

Try it online!

Gaia, 27 bytes
2┅@⟨:1⟪Ė₌0⟪;)d;d&1D⟫?⟫#+⟩ₓE

Try it online!
1-based indexing.
Runs rather slowly, as it tries each integer until it finds a(n).
2┅				| push [1 2]
  @				| push n
   ⟨			 ⟩ₓ	| do n times:
    :				| dup
     1⟪		      ⟫#	| and find the first 1 integer i where the following results in a truthy value:
       Ė₌	     ?		| is i an Ėlement of the list? Also push an extra copy of the arguments
	 0			| if so, give falsy result, so try the next integer
	  ⟪	    ⟫		| else do the following:
	   ;)d			| get divisors of a(n-1)
	      ;d		| get divisors of i
		&1D		| set intersect and remove the first element (which is always 1)
				| this yields an empty set if no divisors are shared (falsy, so try next integer)
				| or a non-empty set (truthy, so returns i = a(n))
			+	| and concatenate to list (end loop).
			   E	| finally, Extract the nth element (n taken implicitly)


text:
Could you please stop shuffling the deck and play already?
Challenge:
Input: A list of distinct positive integers within the range \$[1, \text{list-size}]\$.
Output: An integer: the amount of times the list is riffle-shuffled. For a list, this means the list is split in two halves, and these halves are interleaved (i.e. riffle-shuffling the list [1,2,3,4,5,6,7,8,9,10] once would result in [1,6,2,7,3,8,4,9,5,10], so for this challenge the input [1,6,2,7,3,8,4,9,5,10] would result in 1).
Challenge rules:

You can assume the list will only contain positive integers in the range \$[1, \text{list-size}]\$ (or \$[0, \text{list-size}-1]\$ if you choose to have 0-indexed input-lists).
You can assume all input-lists will either be a valid riffle-shuffled list, or a sorted list which isn't shuffled (in which case the output is 0).
You can assume the input-list will contain at least three values.

Step-by-step example:
Input: [1,3,5,7,9,2,4,6,8]
Unshuffling it once becomes: [1,5,9,4,8,3,7,2,6], because every even 0-indexed item comes first [1, ,5, ,9, ,4, ,8], and then all odd 0-indexed items after that [ ,3, ,7, ,2, ,6, ].
The list isn't ordered yet, so we continue:
Unshuffling the list again becomes: [1,9,8,7,6,5,4,3,2]
Again becomes: [1,8,6,4,2,9,7,5,3]
Then: [1,6,2,7,3,8,4,9,5]
And finally: [1,2,3,4,5,6,7,8,9], which is an ordered list, so we're done unshuffling.
We unshuffled the original [1,3,5,7,9,2,4,6,8] five times to get to [1,2,3,4,5,6,7,8,9], so the output is 5 in this case.
General rules:

This is code-golf, so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
Standard rules apply for your answer with default I/O rules, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
Default Loopholes are forbidden.
If possible, please add a link with a test for your code (i.e. TIO).
Also, adding an explanation for your answer is highly recommended.

Test cases:
Input                                                   Output

[1,2,3]                                                 0
[1,2,3,4,5]                                             0
[1,3,2]                                                 1
[1,6,2,7,3,8,4,9,5,10]                                  1
[1,3,5,7,2,4,6]                                         2
[1,8,6,4,2,9,7,5,3,10]                                  2
[1,9,8,7,6,5,4,3,2,10]                                  3
[1,5,9,4,8,3,7,2,6,10]                                  4
[1,3,5,7,9,2,4,6,8]                                     5
[1,6,11,5,10,4,9,3,8,2,7]                               6
[1,10,19,9,18,8,17,7,16,6,15,5,14,4,13,3,12,2,11,20]    10
[1,3,5,7,9,11,13,15,17,19,2,4,6,8,10,12,14,16,18,20]    17
[1,141,32,172,63,203,94,234,125,16,156,47,187,78,218,109,249,140,31,171,62,202,93,233,124,15,155,46,186,77,217,108,248,139,30,170,61,201,92,232,123,14,154,45,185,76,216,107,247,138,29,169,60,200,91,231,122,13,153,44,184,75,215,106,246,137,28,168,59,199,90,230,121,12,152,43,183,74,214,105,245,136,27,167,58,198,89,229,120,11,151,42,182,73,213,104,244,135,26,166,57,197,88,228,119,10,150,41,181,72,212,103,243,134,25,165,56,196,87,227,118,9,149,40,180,71,211,102,242,133,24,164,55,195,86,226,117,8,148,39,179,70,210,101,241,132,23,163,54,194,85,225,116,7,147,38,178,69,209,100,240,131,22,162,53,193,84,224,115,6,146,37,177,68,208,99,239,130,21,161,52,192,83,223,114,5,145,36,176,67,207,98,238,129,20,160,51,191,82,222,113,4,144,35,175,66,206,97,237,128,19,159,50,190,81,221,112,3,143,34,174,65,205,96,236,127,18,158,49,189,80,220,111,2,142,33,173,64,204,95,235,126,17,157,48,188,79,219,110,250]
                                                        45

One or two test cases with an odd length and an output greater than 0 would be nice. It's easy to mess the riffle in such cases if you have to write the riffle code by yourself instead of relying on builtins.

@OlivierGrégoire The [1,3,5,7,9,2,4,6,8] is of length 9, but I will add a few more for lengths 7 and 11 perhaps. EDIT: Added the test cases [1,3,5,7,2,4,6] = 2 (length 7) and [1,6,11,5,10,4,9,3,8,2,7] = 6 (length 11). Hope that helps.

My bad: I was sure the test case you mentioned was of size 8. But thanks for the extra test cases.

Is it ok to return false or other castable values instead of 0?

@Alex Yeah sure. I believe the Python answer already does so as well.

Question as currently formulated seems "wrong"... a single riffle shuffle should result in the first and last cards changing, unless you're pulling some kind of con trick! i.e. [6,1,7,2,8,3,9,4,10,5] after a single shuffle of 10 cards.

@Steve I guess you're kinda right. Riffle-shuffling in general simply interleaves two halves, so both [1,6,2,7,3,8,4,9,5,10] or [6,1,7,2,8,3,9,4,10,5] are possible. In my challenge it does mean that the top card will always remain the top card, so it's indeed a bit of a con-trick.. I've never seen someone irl use only riffle-shuffles to shuffle a deck of cards however. Usually they also use other type of shuffles in between. Anyway, it's too late to change the challenge now, so for the sake of this challenge the top card will always remain the top card after a riffle-shuffle.

@IMSoP It was indeed supposed to be alternated, but I've edited it to interleaved now.

There are two forms of riffle (faro) shuffle depending on whether the first card comes from the first half of the deck or from the second half.  The first of these, which is the version described here is an out-shuffle.  The second is an in-shuffle.  It's fairly easy to see that an out-shuffle on n cards is equivalent to an in-shuffle on the n-2 inside cards, followed by replacing the first and last cards.

Jelly, 8 bytes
ŒœẎ$ƬiṢ’

Try it online!
How?
ŒœẎ$ƬiṢ’ - Link: list of integers A
    Ƭ    - collect up until results are no longer unique...
   $     -   last two links as a monad:
Œœ       -     odds & evens i.e. [a,b,c,d,...] -> [[a,c,...],[b,d,...]]
  Ẏ      -     tighten                         -> [a,c,...,b,d,...]
     Ṣ   - sort A
    i    - first (1-indexed) index of sorted A in collected shuffles
      ’  - decrement

JavaScript (ES6), 44 bytes
Shorter version suggested by @nwellnhof
Expects a deck with 1-indexed cards as input.
f=(a,x=1)=>a[x]-2&&1+f(a,x*2%(a.length-1|1))

Try it online!
Given a deck \$[c_0,\ldots,c_{L-1}]\$ of length \$L\$, we define:
$$x_n=\begin{cases}
2^n\bmod L&\text{if }L\text{ is odd}\\
2^n\bmod (L-1)&\text{if }L\text{ is even}\\
\end{cases}$$
And we look for \$n\$ such that \$c_{x_n}=2\$.

JavaScript (ES6),  57 52  50 bytes
Expects a deck with 0-indexed cards as input.
f=(a,x=1,k=a.length-1|1)=>a[1]-x%k&&1+f(a,x*-~k/2)

Try it online!
How?
Since JS is lacking native support for extracting array slices with a custom stepping, simulating the entire riffle-shuffle would probably be rather costly (but to be honest, I didn't even try). However, the solution can also be found by just looking at the 2nd card and the total number of cards in the deck.
Given a deck of length \$L\$, this code looks for \$n\$ such that:
$$c_2\equiv\left(\frac{k+1}{2}\right)^n\pmod k$$
where \$c_2\$ is the second card and \$k\$ is defined as:
$$k=\begin{cases}
L&\text{if }L\text{ is odd}\\
L-1&\text{if }L\text{ is even}\\
\end{cases}$$

Python 2, 39 bytes
f=lambda x:x[1]-2and-~f(x[::2]+x[1::2])

Try it online!
-4 thanks to Jonathan Allan.

Save four bytes with f=lambda x:2!=x[1]and-~f(x[::2]+x[1::2])

@JonathanAllan Oh, of course! Well... != can be -. ;-)

Ah, yeah caveat emptor :D (or just x[1]>2 I guess)

APL (Dyalog Unicode), 35 26 23 22 bytesSBCS
{⍵≡⍳≢⍵:0⋄1+∇⍵[⍒2|⍳⍴⍵]}

Try it online!
Thanks to Adám for the help, Erik the Outgolfer for -3 and ngn for -1.
The TIO link contains two test cases.
Explanation:
{⍵≡⍳≢⍵:0⋄1+∇⍵[⍒2|⍳⍴⍵]}
{⍵≡⍳≢⍵:0⋄1+∇⍵[⍒2|⍳⍴⍵]} ⍝ function takes one argument: ⍵, the array
 ⍵≡⍳≢⍵                 ⍝ if the array is sorted:
 ⍵≡⍳≢⍵                 ⍝ array = 1..length(array)
      :0               ⍝ then return 0
        ⋄              ⍝ otherwise
         1+            ⍝ increment
           ∇           ⍝ the value of the recursive call with this argument:
            ⍵[      ]  ⍝ index into the argument with these indexes:
                 ⍳⍴⍵   ⍝ - generate a range from 1 up to the size of ⍵
               2|      ⍝ - %2: generate a binary mask like [1 0 1 0 1 0]
              ⍒        ⍝ - grade (sorts but returns indexes instead of values), so we have the indexes of all the 1s first, then the 0s.

¹

Count the recursion depth for -3.

@EriktheOutgolfer Much better, thanks!

∧/2≤/⍵ -> ⍵≡⍳≢⍵

@ngn didn't realize the array had no holes. Thanks!

R, 58 55 45 bytes
a=scan();while(a[2]>2)a=matrix(a,,2,F<-F+1);F

Try it online!
Simulates the sorting process. Input is 1-indexed, returns FALSE for 0.

Very nice! I was working on a similar approach but using a recursive function, which didn't work out as golfy.

Perl 6, 34 32 bytes
-2 bytes thanks to Jo King
{(.[(2 X**^$_)X%$_-1+|1]...2)-1}

Try it online!
Similar to Arnauld's approach. The index of the second card after n shuffles is 2**n % k with k defined as in Arnauld's answer.

Perl 6, 36 34 32 bytes
-2 bytes thanks to nwellnhof
$!={.[1]-2&&$!(.sort:{$++%2})+1}

Try it online!
Reverse riffle shuffles by sorting by the index modulo 2 until the list is sorted, then returns the length of the sequence.
It's funny, I don't usually try the recursive approach for Perl 6, but this time it ended up shorter than the original.
Explanation:
$!={.[1]-2&&$!(.sort:{$++%2})+1}
$!={                           }   # Assign the anonymous code block to $!
    .[1]-2&&                       # While the list is not sorted
            $!(             )      # Recursively call the function on
               .sort:{$++%2}       # It sorted by the parity of each index
                             +1    # And return the number of shuffles

Java (JDK), 59 bytes
a->{int c=0;for(;a[(1<<c)%(a.length-1|1)]>2;)c++;return c;}

Try it online!
Works reliably only for arrays with a size less than 31 or solutions with less than 31 iterations. For a more general solution, see the following solution with 63 bytes:
a->{int i=1,c=0;for(;a[i]>2;c++)i=i*2%(a.length-1|1);return c;}

Try it online!
Explanation
In a riffle, the next position is the previous one times two modulo either length if it's odd or length - 1 if it's even.
So I'm iterating over all indices using this formula until I find the value 2 in the array.
Credits

-8 bytes thanks to Kevin Cruijssen. (Previous algorithm, using array)
-5 bytes thanks to Arnauld.

163 bytes by using two times x.clone() instead of A.copyOf(x,l).

64 bytes

@Arnauld Thanks! I had a hard time figuring how to simplify that "length if odd else length - 1"

@Arnauld Oh! My new algorithm is actually the same as yours... And I spent half an hour figuring it out by myself...

More precisely, it's equivalent to an improvement over my original algorithm found by @nwellnhof.

I went away and thought about the algorithm over lunch and came up with the same idea... only to find you'd already discovered it. +1

I've since found https://math.stackexchange.com/a/886088/30622 which explains why the value 2 is always in the largest cycle.

@Neil My original idea was to "follow" a value. For the sake of simplicity I chose the value next to 1, which is 2 in the sorted array. That's how I noticed the pattern and made the formula.

I was just making sure that the formula works for all inputs. Obviously 2 is the simplest value to check, but it is also never one of the cases where the algorithm fails. (A example failure case would be checking for 4 in a shuffle of size 10; since 4 and 7 just swap places, it would always return 0 or 1.)

@Neil Nice to know: I hadn't noticed the swap. Thanks :)

J, 28 26 bytes
-2 bytes thanks to Jonah!
 1#@}.(\:2|#\)^:(2<1{])^:a:

Try it online!
Inspired be Ven's APL solution.
Explanation:
               ^:       ^:a:   while
                 (2<1{])       the 1-st (zero-indexed) element is greater than 2
     (        )                do the following and keep the intermediate results
          i.@#                 make a list form 0 to len-1
        2|                     find modulo 2 of each element
      /:                       sort the argument according the list of 0's and 1's
1  }.                          drop the first row of the result
 #@                            and take the length (how many rows -> steps)

K (ngn/k), 25 bytes
Thanks to ngn for the advice and for his K interpreter!
{#1_{~2=x@1}{x@<2!!#x}\x}

Try it online!

converge-iterate, then drop one, and count - this leads to shorter code

@ngn. So, similar to my J solution - I'll try it later, thanks!

1#@}.(\:2|#\)^:(2<1{])^:a: for 26 bytes

05AB1E (legacy), 9 bytes
[DāQ#ι˜]N

Try it online!
Explanation
[   #  ]     # loop until
  ā          # the 1-indexed enumeration of the current list
 D Q         # equals a copy of the current list
     ι˜      # while false, uninterleave the current list and flatten
        N    # push the iteration index N as output

I didn't even knew it was possible to output the index outside the loop in the legacy. I thought it would be 0 again at that point, just like in the new 05AB1E version. Nice answer! Shorter than my 10-byter using the unshuffle-builtin Å≠ that inspired this challenge. :)

@KevinCruijssen: Interesting. I didn't know there was an unshuffle. In this instance it's the same as my version, but unshuffle maintains dimensions on 2D arrays.

Alternative 9-byter that works in both versions: [DāQD–#ι˜

Husk, 11 bytes
L↑S≠ŀ¡ȯΣTC2

Try it online!

PowerShell, 116 114 108 84 78 bytes
-24 bytes thanks to Erik the Outgolfer's solution.
-6 bytes thanks to mazzy.
param($a)for(;$a[1]-2){$n++;$t=@{};$a|%{$t[$j++%2]+=,$_};$a=$t.0+$t.1;$j=0}+$n

Try it online!

you can save a bit more: Try it online!

@muzzy, you're right again :) thanks

C (GCC) 64 63 bytes
-1 byte from nwellnhof
i,r;f(c,v)int*v;{for(i=r=1;v[i]>2;++r)i=i*2%(c-1|1);return~-r;}

This is a drastically shorter answer based on Arnauld's and Olivier Grégoire's answers. I'll leave my old solution below since it solves the slightly more general problem of decks with cards that are not contiguous.
Try it online

C (GCC) 162 bytes
a[999],b[999],i,r,o;f(c,v)int*v;{for(r=0;o=1;++r){for(i=c;i--;(i&1?b:a)[i/2]=v[i])o=(v[i]>v[i-1]|!i)&o;if(o)return r;for(i+=o=c+1;i--;)v[i]=i<o/2?a[i]:b[i-o/2];}}

Try it online
a[999],b[999],i,r,o; //pre-declare variables
f(c,v)int*v;{ //argument list
    for(r=0;o=1;++r){ //major loop, reset o (ordered) to true at beginning, increment number of shuffles at end
        for(i=c;i--;(i&1?b:a)[i/2]=v[i]) //loop through v, split into halves a/b as we go
            o=(v[i]>v[i-1]|!i)&o; //if out of order set o (ordered) to false
        if(o) //if ordered
            return r; //return number of shuffles
        //note that i==-1 at this point
        for(i+=o=c+1;i--;)//set i=c and o=c+1, loop through v
            v[i]=i<o/2?a[i]:b[i-o/2];//set first half of v to a, second half to b
    }
}

Perl 5 -pa, 77 68 bytes
map{push@{$_%2},$_}0..$#F;++$\,@F=@F[@0,@1]while"@F"ne"@{[1..@F]}"}{

Try it online!

R, 70 72 bytes
x=scan();i=0;while(any(x>sort(x))){x=c(x[y<-seq(x)%%2>0],x[!y]);i=i+1};i

Try it online!
Now handles the zero shuffle case.

@user2390246 fair point. Adjusted accordingly

Ruby, 42 bytes
f=->d,r=1{d[r]<3?0:1+f[d,r*2%(1|~-d.max)]}

Try it online!
How:
Search for number 2 inside the array: if it's in second position, the deck hasn't been shuffled, otherwise check the positions where successive shuffles would put it.

APL(NARS), chars 49, bytes 98
{0{∧/¯1↓⍵≤1⌽⍵:⍺⋄(⍺+1)∇⍵[d],⍵[i∼d←↑¨i⊂⍨2∣i←⍳≢⍵]}⍵}

why use in the deepest loop, one algo that should be nlog(n), when we can use one linear n? just for few bytes more?
[⍵≡⍵[⍋⍵] O(nlog n) and the confront each element for see are in order using ∧/¯1↓⍵≤1⌽⍵ O(n)]test:
  f←{0{∧/¯1↓⍵≤1⌽⍵:⍺⋄(⍺+1)∇⍵[d],⍵[i∼d←↑¨i⊂⍨2∣i←⍳≢⍵]}⍵}
  f ,1
0
  f 1 2 3
0
  f 1,9,8,7,6,5,4,3,2,10
3
  f 1,3,5,7,9,11,13,15,17,19,2,4,6,8,10,12,14,16,18,20
17

That’s the first time I’ve seen someone differentiate between characters and bytes . It always bugs me when I see Unicode characters and they claim that it’s one byte per character. This  is not one byte!

@Kerndog73 All is number, but in APL think characters are not numbers... (they seems element in AV array)

R, 85 bytes
s=scan();u=sort(s);k=0;while(any(u[seq(s)]!=s)){k=k+1;u=as.vector(t(matrix(u,,2)))};k

Try it online.
Explanation
Stupid (brute force) method, much less elegant than following the card #2.
Instead of unshuffling the input s we start with a sorted vector u that we progressively shuffle until it is identical with s.  This gives warnings (but shuffle counts are still correct) for odd lengths of input due to folding an odd-length vector into a 2-column matrix; in that case, in R, missing data point is filled by recycling of the first element of input.
The loop will never terminate if we provide a vector that cannot be unshuffled.
Addendum: you save one byte if unshuffling instead. Unlike the answer above, there is no need to transpose with t(), however, ordering is byrow=TRUE which is why T appears in matrix().
R, 84 bytes
s=scan();u=sort(s);k=0;while(any(s[seq(u)]!=u)){k=k+1;s=as.vector(matrix(s,,2,T))};k

Try it online!

I took the liberty of fixing your title and adding a TIO-link for the test cases (based on the other R answer), and also verified your answer works as intended, so +1 from me and welcome to PPCG! :)

Lua (LuaJIT), 119 96 79 bytes
n=t;while 2~=n[2]do n={}for a=1,#t*2,2 do x=a-#t n[#n+1]=t[a]or t[x+x%2]end;t=n

Try it online!

MATLAB, 70 bytes
function s(l),x=max(l);find(find(l==2)==1+mod(2.^(1:x),x-1))*(l(2)~=2)

explanation:
every nth shuffle, 2 will be pushed n^2 indices down from its previous position, wrapping around when it reaches the last position. That means that the function for index(n) is
1+mod(2^n,list-size-1)
for a list-size of 10, then, the indices are:

index(1) = 3       -> [1 6 2 7 3 8 4 9 5 10]
index(2) = 5       -> [1 8 6 4 2 9 7 5 3 10]
index(3) = 9       -> [1 9 8 7 6 5 4 3 2 10]
index(4) = 17 => 8 -> [1 5 9 4 8 3 7 2 6 10]

etc.
Using this, I find the index where 2 is, and find which power of 2 that is along the array. That power corresponds the the number of shuffles. To account for 0 shuffles, the whole thing is multiplied by the boolean value of l(2)~=2 to make sure that it returns 0 when 2 is in the right place, which only happens for an unshuffled array.

Welcome to CGCC! Pretty smart approach, so +1 from me. :) MATLAB doesn't have an online compiler, right? Since I don't see it in the tio.run list. Could you in that case perhaps add a screenshot as verification for the test cases? :)

PowerShell, 62 71 70 66 bytes
+9 bytes when Test cases with an even number of elements added.
-1 byte with splatting.
-4 bytes: wrap the expression with $i,$j to a new scope.
for($a=$args;$a[1]-2;$a=&{($a|?{++$j%2})+($a|?{$i++%2})}){$n++}+$n

Try it online!

Japt, 13 11 10 bytes
Taking my shiny, new, very-work-in-progress interpreter for a test drive.
ÅÎÍ©ÒßUñÏu

Try it or run all test cases
ÅÎÍ©ÒßUñÏu     :Implicit input of integer array U
Å              :Slice the first element off U
 Î             :Get the first element
  Í            :Subtract from 2
   ©           :Logical AND with
    Ò          :  Negation of bitwise NOT of
     ß         :  A recursive call to the programme with input
      Uñ       :    U sorted
        Ï      :    By 0-based indices
         u     :    Modulo 2

This interpreter looks super cool.

Red, 87 79 78 bytes
func[b][c: 0 while[b/2 > 2][c: c + 1 b: append extract b 2 extract next b 2]c]

Try it online!

Pyth, 18 bytes
L?SIb0hys%L2>Bb1
y

Try it online!
-2 thanks to @Erik the Outgolfer.
The script has two line: the first one defines a function y, the second line calls y with the implicit Q (evaluated stdin) argument.
L?SIb0hys%L2>Bb1
L                function y(b)
 ?               if...
  SIb            the Invariant b == sort(b) holds
     0           return 0
      h          otherwise increment...
       y         ...the return of a recursive call with:
             B   the current argument "bifurcated", an array of:
              b   - the original argument
            >  1  - same with the head popped off
          L      map...
         % 2     ...take only every 2nd value in each array
        s         and concat them back together

¹

14 bytes

Wolfram Language (Mathematica), 62 bytes
c=0;While[Sort[a]!=a,a=a[[1;;-1;;2]]~Join~a[[2;;-1;;2]];c++];c

Try it online!
Explanation
The input list is a . It is unriffled and compared with the sorted list until they match.

Stax, 14 bytes
ü≈:☻‼Xí┌ùß♦▲▬á

Run and debug it

Vyxal 3, 7 bytes
ϩUJiᶤᵞS

Try it Online!
ϩUJiᶤᵞS
ϩ  i     # Apply and collect until value is no longer unique, including initial value
 UJ      # Uninterleave and append
    ᶤᵞS  # first index where the list is sorted (invariant after sort)

Created with the help of Luminespire.

Python 3, 40 bytes
f=lambda x:x[1]-2and 1+f(x[::2]+x[1::2])  # 1-based
f=lambda x:x[1]-1and 1+f(x[::2]+x[1::2])  # 0-based

Try it online!
I need to refresh the page more frequently: missed Erik the Outgolfer's edit doing a similar trick =)

-2 by removing the f=. No need to assign the lambda to a variable, it is allowed without it; and it's still possible to call it. The "invisible" variable _ is set to the last evaluated value, so lambda x:x[1]-2and 1+f(x[::2]+x[1::2]) would set _ to that exact lambda.

Oh, this is brilliant! I will certainly have fun (and debugging profit) playing with it

No way to demonstrate it though: it only works in REPL mode

Never mind, I only just realized that you use recursion and need it assigned to f. However, for answers that don't use recursion you still don't need it.