text:
Reverse a string by chunks
Your task is to write a program which, given a number and a string, splits the string into chunks of that size and reverses them.
Rules
Your program will receive a positive integer n, as well as a string s with length at least one consisting of only printable ASCII (not including whitespace). The string should then be split into chunks of length n, if the length of the string isn't divisible by n any leftover at the end should be considered its own chunk. Then, reverse the order of the chunks and put them together again.
Test Cases
n   s           Output

2   abcdefgh    ghefcdab
3   foobarbaz   bazbarfoo
3   abcdefgh    ghdefabc
2   a           a
1   abcdefgh    hgfedcba
2   aaaaaa      aaaaaa
2   baaaab      abaaba
50  abcdefgh    abcdefgh
6   abcdefghi   ghiabcdef

This is code-golf, so you should aim for as few bytes as possible.

Related.

Jelly, 2 bytes
sṚ

A full program that prints the result.
Try it online!
How?
sṚ - Main link: string, number                                   e.g. 'abcdefg', 3
s  - split string into chunks of length number (keeping any overflow) ["abc","def","g"]
 Ṛ - reverse the resulting list                                       ["g","def","abc"]
   - implicit print                                                   gdefabc

I like how two bytes generated 4 lines of explanation.

Python 3, 35 bytes
f=lambda s,n:s and f(s[n:],n)+s[:n]

Try it online!

How does the and keyword work here ? @Dennis

@ShinMigami13 empty string is not truthy so this ends the recursion

05AB1E, 5 4 3 bytes
-1 thanks to Dennis
-1 thanks to carusocomputing
ôRJ

Try it online!
     # Implicit: push input
 ô   # Split in pieces of length b
  RJ # Reverse and join

¹ isn't needed.

JavaScript (ES6), 37 bytes
n=>F=s=>s&&F(s.slice(n))+s.slice(0,n)

Takes input by currying: number first, then string, like f(2)("abcdefgh").

let f =
n=>F=s=>s&&F(s.slice(n))+s.slice(0,n)

let g = (n, s) => console.log(`f(${n})("${s}"): ${f(n)(s)}`)

g(2, "abcdefgh")
g(3, "foobarbaz")
g(3, "abcdefgh")
g(2, "a")
g(1, "abcdefgh")
g(2, "aaaaaa")
g(2, "baaaab")
g(50, "abcdefgh")

Perl 6,  28  20 bytes
{$^b.comb($^a).reverse.join}

Try it
{[R~] $^b.comb($^a)}

Try it
Expanded:
{  # bare block lambda with placeholder parameters ｢$a｣ and ｢$b｣
  [R[~]] # reduce the following using the reverse meta operator `R`
         # combined with the string concatenation operator

    # `comb` with a number splits the invocant into chunks of that size
    $^b.comb($^a)
}

Bash + coreutils, 22
fold -$1|tac|tr -d \\n

Try it online.

I've learned 4 new linux commands this week on PPCG fold is one of them, thanks!

Haskell, 32 bytes
n#""=""
n#s=n#drop n s++take n s

Try it online!

Pretty. It's nice when precedence works in golf

PHP, 53 Bytes
<?=join(array_reverse(str_split($argv[2],$argv[1])));

Röda, 36 bytes
f n{[[_]..[try head n-1]]|reverse|_}

Try it online!
It's a function that takes one argument. The characters of the string must be in the stream.
try is used to discard errors in case that the head function can't read n-1 values.
Explanation:
f n{[[_]..[try head n-1]]|reverse|_}
f n{                               } /* Function declaration */
                                     /* In a loop: */
      _                              /*   Pull one value */
           try head n-1              /*   Pull n-1 values (or less) */
     [ ]..[            ]             /*   Make an array */
    [                   ]            /*   Push it to the stream */
                         |reverse    /* Reverse all values in the stream */
                                 |_  /* Flat all arrays in the stream */
                                     /* Characters in the stream are printed */

Not as obfuscated as usually. I think it's quite beautiful. :)

You managed to make a program less readable than the jelly solution.

Why doesn't [[try head n]] work instead of [[_]..[try head n-1]]?

@KritixiLithos Because _ loops the expression. [[try head n]] would take n values once, but [[_]..[try head n-1]] takes n values as long as there are values left.

CJam, 5 bytes
q~/W%

Input is a number and a string enclosed in double quotes, separated by whitespace.
Try it online! Or verify all test cases.
Explanation
q~   e# Read all input and evaluate: pushes a number and a string
/    e# Split string into chunks of that size. Last chunk may be
     e# smaller. Gives an array of strings
W%   e# Reverse the array. Implicitly display

Batch, 74 bytes
@if %2=="" (echo %~3)else set s=%~2&call %0 %1 "%%s:~%1%%" "%%s:~,%1%%%~3"

Rather annoyingly this ends up being recursive rather than tail recursive.

V, 13 10 bytes
òÀ|lDÏpòÍî

Try it online!
ò      ò    ' Recursively
 À|         ' Go to the "nth" column
   l        ' Move one character right (breaks loop when no more chunks)
    D       ' Delete from here to the end of the line
     Ï      ' Add a line above the current line (now contains one chunk)
      p     ' Paste the remainder of the line that was deleted
        Íî  ' Remove all newlines

In Action:
abcdefghijkl

turns into
efghijkl
abcd

which becomes
ijkl
efgh
abcd

before all newlines are removed

PowerShell, 56 49 bytes
-7 bytes thanks to mazzy
param($n,$s)$s-split"(.{$n})"-ne''|%{$r=$_+$r};$r

Try it online!

49 bytes 2) Please, post a full program, not a codesnippet. How to check? Extract your code in a separate file with the extension .ps1 and try calling this script instead of your code. If it works, then the test was successful.

brainfuck, 78 bytes
,<<<+[[>]>+>[[>],<[<]>+>-]<-[->>[>]>>+<<<[<]<]>>]<<<<[[<]>[-[+.[-]]+>]<[<]<<<]

The first byte of the input is the chunk size, given by byte value. The rest of the bytes are considered to be the string.
Try it online!
Expanded and commented
Read the chunk size byte
This cell will become a counter cell
,

Move left a few cells an increment;
this is to make the starting position
line up with the relative positioning
needed to fit in with the loop
<<<+

While the current cell is nonzero:
[

 Move right to the first zero cell
 [>]

 Move right once and increment and then move right to the counter cell
 The increment is required because of "move to zero cell" loops
 >+>

 This loop will store one chunk of the input in consecutive memory cells
 [
  [>]   Move right until a zero cell is hit
  ,     Store 1 byte of input there
  <[<]  Move back left until a zero cell (other than the current one) is hit
  >+>-  Increment the temporary cell by 1 and decrement the counter
 ] (end loop once the counter hits zero)

 Decrement the temp cell (because we needed to have 1 there initially to make the cell location work)
 <-

 Move the temp cell to three cells after the end of the chunk
 This is the new counter cell for the next chunk
 [->>[>]>>+<<<[<]<]

 Move two cells right from where the temp cell was
 This is the first cell of the chunk; if it's 0
 then the input is finished and the loop should end
 >>
]

Due to the way the counter is kept track of the tape head
will always be four cells to the right of the last input cell
when the loops breaks
<<<<

Now the chunks are printed one by one
At the start of an iteration the tape head is at the end of a chunk
[
 Locate the start of the last chunk
 [<]>

 Print the chunk:
 [
  Print the byte held in the current cell if it isn't 1
  This is necessary because we left a stray 1 in a cell at
  the start which shouldn't be printed
  -[+.[-]]+

  Move to the next cell
  >
 ]

 Move to just left of the chunk
 <[<]

 Move three cells over to the end of the next chunk
 <<<
]

Mathematica, 46 bytes
""<>Reverse@Partition[Characters@#2,#,#,1,{}]&

Anonymous function. Takes a number and a string as input and returns a string as output. Not much to see here.

Pyth, 5 bytes
s_c.*

Try it online.
Explanation
   .*  splat implicit input
  c    split into chunks length n
 _     reverse
s      join

Javascript - 54 47 46 bytes
Remade:
(s,n)=>s.match(eval(`/.{1,${n}}/g`)).reverse()

Used as
f=(s,n)=>s.match(eval(`/.{1,${n}}/g`)).reverse()
alert(f("abcdefgh",2));

Thank you to @ETHproductions for some RegEx quickenning
Thank you to @Shaggy for an extra byte in the eval!
Original:
(s,n)=>s.match(new RegExp('.{1,'+n+'}','g')).reverse()

Nice answer! I believe you can save a couple bytes by creating the regex with eval('/.{1,'+n+'}/g')

@ETHproductions Ah yes. That's what I've been attempting to do. I wasn't familiar enough with regex to do it though!

I think you can save a byte with currying, s=>n=> ...

Save a byte with eval("/.{1,${n}}/g"), using backticks instead of quotation marks.

Java, 147 138 Bytes
String r(String s,int n){String r="";int l=s.length();for(int i=l/n*n;i>=0;i-=n)if(!(i>=l))r+=(i+n)>=l?s.substring(i):s.substring(i,i+n);return r;}
Saved 9 Bytes thanks to Kevin Cruijssen!
String r(String s,int n){String r="";int l=s.length(),i=l/n*n;for(;i>=0;i-=n)if(i<l)r+=i+n>=l?s.substring(i):s.substring(i,i+n);return r;}

In expanded form:
String r(String s,int n){
    String r="";
    int l=s.length(),i=l/n*n;
    for(;i>=0;i-=n)
        if(i<l)
            r+=i+n>=l?s.substring(i):s.substring(i,i+n);
    return r;
}

This is actually my first try to codegolf ever, so any feedback is welcome!

Welcome to PPCG!

Hi, welcome to PPCG! This is already pretty good, but there are still a few things to golf some more: int l=s.length();for(int i=l/n*n; can be int l=s.length(),i=l/n*n;for(; so you only have int  once. And if(!(i>=l)) can be if(l<i). And r+=(i+n)>=l? can be without the parenthesis: r+=i+n>=l?. Also, if you haven't seen it yet, I can recommend looking through Tips for Golfing in Java for some pretty cool golfing tips to use. :) Once again, welcome.

Retina, 38 bytes
1 byte saved thanks to @LeakyNun
^

+`(.* (1)+¶)((?<-2>.)+)
$3$1
 1+¶

(Note the space on the second line, and the trailing space)
This program takes input as unary on the first line, and the string on the second.
Try it online!
Test Suite! (slightly modified)
Explanation
The first step is to prepend a space (will become important later on).
^

Now we reverse. This uses .NET's balancing groups. It is important to note that groups here act as stacks, so every match is essentially pushed onto the stack. Here we capture every digit in the unary number into group 2. Now each time a character in the string is found, a match is popped from group 2. This ensures the the number of characters does not exceed that of the unary number.
+`(.* (1)+¶)                       Capture the unary number in group 2
             ((?<-2>.)+)           Balancing group for substrings
$3$1                               Reverse

And finally remove the unary number and the newline.
 1+¶

I think it is acceptable to take the number in unary.

Anyhow, you can replace \d by . to save a byte.

The second ^ is also redundant.

@LeakyNun The program now takes input in unary, so I have no need for the \d anymore. And thanks for golfing away the caret :)

33 bytes by using lazy (non-greedy) match.

Never mind, switch back to the previous version.

Perl 5, 25 bytes
Uses the -lnM5.010 flags.
say reverse<>=~/.{1,$_}/g

Try it online!
Shoutout to Grinnz for telling me about =~ m/.{1,$n}/g
-M5.010 enables the use of the say function, which for our purposes is print with a shorter name.
-n puts the first line of input into $_, and -l chomps off the trailing newline.
We then get the second line of input using <>, and apply it to the regex .{1,$_}: any character, between 1 and $_ (the first input) times. Since this is greedy by default, it tries to always match $_ characters. The 1, is needed for the possible leftover chunk at the end.
The /g modifier gives us every match of that regex in the input string as a list, which is then reversed and printed. In Perl, passing a list to say joins it without any delimiter by default.

Dyalog APL Extended, 16 15 bytes
{∊⌽⍵⊂⍨(≢⍵)⍴=⍳⍺}

Try it online!

You don't need the f←

Why, ,/ → ∊

@Adám Oh hey that applies to my answer too, thanks

Pavel: yep, obviously.. @Adám thanks!

14: ∊∘⌽⊢⊂⍨≢⍤⊢⍴1↑⍨⊣

Convex, 2 bytes
/¥

Try it online!

Scala, 57 55 bytes
(n:Int,s:String)=>(""/:s.grouped(n).toSeq.reverse)(_+_)

Thanks Jacob! Try it here.
Note: By using the symbol form of foldLeft ("/:"), I was able to take off a couple more bytes.

make it anonymous function, and use mkString instead of reduceLeft, and shave off 7 bytes: (n:Int,s:String)=>s.grouped(n).toSeq.reverse.mkString("")

Python, 62 bytes
lambda n,s:''.join([s[i:i+n]for i in range(0,len(s),n)][::-1])

Try it online!

Python3 answer is shorter & also works for python 2.7: f=lambda n,s:s and f(n,s[n:])+s[:n]

Stacked, 9 bytes
#<rev''#`

Try it online!
#< chunks, rev reverses, and ''#` joins by empty string. Quite simple.

QBIC, 24 bytes
:;[1,_lA|,a|Z=_sA,b,a|+Z

This makes excellent use of the new substring-function I recently added to QBIC:
:;          Read in the cmd line params a (number) and A$ (text)
[1,_lA|,a|  Set up a FOR loop: FOR b = 1; b <= A$.length; b += a
Z=          Modify Z$; Z$ is autoprinted at the end of QBIC code
_sA,b,a|    SUBSTRING: _s is the function followed by the string
               to take from, the starting pos and the # of chars
+Z          Take chunks from further into A$, put them before Z$

Pyth, 4 bytes
s_cF

Takes input as "s",n: Try it for yourself!

C, 69 bytes
i;f(s,n)char*s;{i=strlen(s);for(i-=i%n;printf("%.*s",n,s+i),i;i-=n);}

Result is printed out to the standard output.

Ohm, 5 bytes
σ]QWJ

Try it online!
Explanation
σ]QWJ
σ         # Split input1 into input2 pieces
 ]        # Flatten array
  Q       # Reverses stack
   W      # Wraps stack to array
    J     # Joins stack
          # Implicit print

APL (Dyalog Unicode), 14 bytesSBCS
∊∘⌽⊢⊂⍨⊢∘≢⍴1↑⍨⊣

Try it online!
Explanation:
∊∘⌽⊢⊂⍨⊢∘≢⍴1↑⍨⊣ ⍝ This is a giant composed function, made of all these pieces:
               ⍝ Left argument: ⍺, the split size (refered as ⊣)
               ⍝ Right argument: ⍵, the string (refered as ⊢)
          1↑⍨⊣ ⍝ Swapped operator ↑:
               ⍝     Start with a 1, then pads with `0` until size ⍺
      ⊢∘≢      ⍝ Get the tally (≢) composed with ⊢, gives the of length ⊢
         ⍴     ⍝ Reshape the list of 1 0 0... into the size of the string:
               ⍝     As opposed to ↑, this will repeat the sequence instead of padding with 0. Gives (1 0 0 1 0 0) for a string of length 6.
   ⊢⊂⍨         ⍝ Swapped operator ⊂:
               ⍝ Split the string at all the 1s
  ⌽            ⍝ Reverse the list
∊              ⍝ Enlist, flattens
 ∘             ⍝ (composition necessary for parsing precedence)

Works similarly to @dzaima's, though it took me a lot of attempts to get there.
¹

R, 69 60 bytes
function(s,n)cat(substring(s,(x=nchar(s):0*n)+1,x+n),sep="")

Try it online!
Thanks to Kirill L. for the suggestion to remove seq.

Looks like this works too for 66.

@KirillL. we can go to 60 bytes if we reverse the order of arguments to : and some manipulation lets us get rid of the trailing -1.

Smart, very nice!

PHP, 78 bytes
function h($n,$s){return$n>strlen($s)?$s:h($n,substr($s,$n)).substr($s,0,$n);}

Try it online!
Shockingly, there's no other submission for this using recursion in PHP.  I mean, when you think PHP you think recursion, right?
Ungolfed
function g($n, $s) {
    if ( $n > strlen( $s ) ) {
        return $s;
    } else {
        return g( $n, substr( $s, $n ) ) . substr( $s, 0, $n );
    }
}

><>, 37 34 bytes
1[&\&
0=?\i:0(?v}l&:&%
28o ]!?l~<.

Try it online!

J-uby, 25 bytes
~:each_slice%A|A|:~|:join

Attempt This Online!

Arturo, 32 bytes
$=>[split.every:&&|reverse|join]

Try it!

PowerShell, 75 bytes
$n,$r=$args;if($r-match"(.{1,$n})(.*)"){$s=&$f $n $matches.2;$s+$matches.1}

*I'm guessing that it may be a repeating in a some sense but it's the Recursion
** It's a few bit of fat-free version
Try it online

C++, 111 bytes
#import<string>
using S=std::string;S f(S s,int n){S r;for(int i=0;i<s.size();i+=n)r=s.substr(i,n)+r;return r;}

Try it online!

Haskell, 40 37 bytes
n#""=""
n#s|(a,b)<-splitAt n s=n#b++a

Usage example: 2 # "abcdefgh" -> "ghefcdab". Try it online!
Split the input string s at position n and into a (first part) and b (second part). Return a recursive call with b appended by a. The  base case is the empty input string, where the result is also the empty string.
Note: splitAt returns the whole string as the first part and the empty string as the second part if the position is greater than the length of the string (splitAt 5 "a" -> ("a","")).
Edit: @Ørjan Johansen saved 3 bytes. Thanks!

It's shorter to make a pattern match with n#""="".

non-competing pointfree version, just for fun: import Data.Lists;((concat.reverse).).chunk

Octave, 44 bytes
@(n,s){[~,I]=sort(-ceil(find(s)/n));s(I)}{2}

Try it online!
or
Verify all test cases!
Explanation:
Example input: s = 'abcdefgh' and n = 3
-ceil(          %round and negate
    find(s)     %generate a range from 1 to len(s)
    /n          %divide by n
    )

a=-ceil([1 2 3 4 5 6 7 8]/3) =

    a = -1  -1  -1  -2  -2  -2  -3  -3

[~,I] = sort(a)  %return index of sorted elements

    I = 7   8   4   5   6   1   2   3
s(I)             %sort s by I
      = ghdefabc

k, 13 bytes
{,/|(x,0N)#y}

Takes in a number x, and a string y. Splits the string y into a list of strings of length x with (x,0N)#y, reverses the list with |, and turns it into one string by folding join through the list with ,/.

Ruby, 37 Bytes
->n,s{s.scan(/.{1,#{n}}/).reverse*''}

Sample run:
irb(main):001:0> ->n,s{s.scan(/.{1,#{n}}/).reverse*''}[3,'abcdefgh']
=> "ghdefabc"

Cheddar, 25 bytes
s->n->s.chunk(n).rev.fuse

Try it online!

Clojure, 50 bytes
#(apply str(flatten(reverse(partition-all % %2))))

Just following the spec, couldn't figure how to make it any shorter.

Implicit, 4 3 bytes
×®"

Try it online!
×®"    « input: string, integer               »;
×      « split string into chunks of integer  »;
 ®     « reverse entire stack                 »;
  "    « stringify entire stack               »;
       « implicit string output               »;

REXX, 69 bytes
parse arg s,n,c
do length(s)%n+1
  parse var s b+(n) s
  c=b||c
  end
say c

Explanation:

Get arguments s and n. Given that there are only two arguments, c will be initialized as empty.
Loop for the length of s MOD n adding 1 to account for leftovers.
For each iteration, chop off n characters from beginning of s and store them in b, then append b to beginning of c.

Husk, 3 bytes
Σ↔C

Try it online!
Takes input as two separate command-line arguments, which thanks to Husk's strong typing and overloaded builtins, don't actually need to be in any particular order since they both get fed directly into C, which cuts whichever one of its arguments is a list into sublists of the length given by whichever argument is a number.
Σ      Concatenate
 ↔     the reversed
  C    chunks of the given length of the string input.

Perl 5, 29 bytes
My solution is almost the same as @Pavel.
Uses the -lnM5.010 flags.
Just another 4-byte longer way to split line with unpack instead regexp match.
Needs one to calc penalty bytes for 3 flags?
Takes flag M5.010 only one byte penalty?
say reverse unpack"(A$_)*",<>

Try it online!

APL(NARS), 73 chars, 146 bytes
r←a f w;k;i;j
k←≢w⋄i←1⋄j←a⋄r←⍬
→3×⍳i>k⋄r←r,⊂w[i..k⌊j]⋄i+←a⋄j+←a⋄→2
r←∊⌽r

This is better because easier to write and to read... test:
  2 f '123'
312
 2 f 'abcdefgh'
ghefcdab
  3 f 'foobarbaz'
bazbarfoo
  2 f 'aaaaaa'
aaaaaa
  2 f 'baaaab'
abaaba
  50 f 'abcdefgh'
abcdefgh
  6  f  'abcdefghi'
ghiabcdef

@dzaima now it is ok that input output

APL (Dyalog Classic), 22 bytes
{0~⍨∊⊖(⌈⍺÷⍨≢⍵)⍺⍴⍵,⍺⍴0}

Try it online!

Forth (gforth), 101 bytes
: f >r dup i mod tuck - dup 3 pick + rot type i - -1 max r> -1 rot ?do over i + over type dup -loop ;

Try it online!
Definitely not the most golfed it could be, but this one requires more stack manipulation than usual, so it's a bit more complicated to golf.
Explanation

Get string-length % chunk-size
Print string-length % chunk-size characters starting from addr + (string-length - (string-length % chunk-size)) [effectively, we're printing the last chunk separate, since it's size might be smaller than the chunk-size]
Loop backwards from the start of the last chunk to the beginning of the string, printing the appropriate chunk for each iteration of the loop

Code Explanation
: f            \ start a new word definition
  >r           \ stick chunk-size on the return stack (accessible by i)
  dup i mod    \ duplicate string-length and length%chunk-size (size of last chunk)
  tuck -       \ make copy of last-chunk-size then get last-chunk start position
  dup 3 pick + \ add last-chunk position to string address to get address of last-chunk
  rot type     \ print last-chunk
  i -          \ subtract chunk-size from last-chunk position to get second-to-last chunk position
  -1 max       \ change to -1 in case string is smaller than chunk-size
  r> -1 rot    \ move chunk-size off return stack, end loop at -1, and arrange params for loop
  ?do          \ start loop from last-chunk-pos to -1
    over i +   \ get current chunk start address
    over type  \ print current chunk
    dup        \ duplicate chunk-size
  -loop        \ subtract chunk-size from loop-index and end loop body
;              \ end word definition

SNOBOL4 (CSNOBOL4), 74 bytes
	S =INPUT
	N =INPUT
S	S LEN(N) . X REM . S	:F(O)
	O =X O
O	OUTPUT =S O
END

Try it online!

Japt -P, 4 bytes
òV w

Try it
òV w     :Implicit input of string U and integer V
òV       :Split U into chunks of length V
   w     :Reverse
         :Implicitly join & output

Elixir, 35 bytes
&Enum.reverse Enum.chunk_every&2,&1

Try it online!

q, 20 bytes
An anonymous composition of built-ins:
'[raze reverse@;cut]

Example:
q)'[raze reverse@;cut][2;"abcdefghi"]
"ighefcdab"

(equivalent to lambda {raze reverse x cut y})

Where can I find an interpreter or compiler for this language?

See https://kx.com/connect-with-us/download/

Perl 6, 11 bytes
&[R~]o&comb

Try it online!
Anonymous combination of two functions, &comb, which splits a string into chunks of size n, and &[R~], which reverse concatenates a list.

Vyxal s, 2 bytes
/Ṙ

Try it online!

Factor, 24 bytes
[ group reverse concat ]

Try it online!

Thunno 2 J, 2 bytes
ẇr

Attempt This Online!
Explanation
ẇr  # Implicit input
ẇ   # Split (input 1) into chunks of length (input 2)
 r  # Reverse the resulting list
    # Implicit output, joined

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


text:
Make me a real-time reputation counter!
Recently, I have found my reputation changing time to time. I would like to know my reputation changing real-time.

The job
Given an id of a user on PPCG (ex.64499), Print the user's reputation every 10 seconds. You may ignore the daily quota.

Examples
64499
3808
40695

Possible output format
12345
12,345

You really hate using the sandbox, right?

@Mr.Xcoder I do dislike it but I don't hate it, I just use it very hardly.

Do we have to worry about stack overflows?

@Dennis stack overflows?

Yes. If we call our function/program recursively, it will eventually stop working. Also, should we print the reputation exactly every 10 seconds or can we wait 10 seconds after printing the rep, not taking the time the query took into account?

@Dennis Worrying about stack overflows? no. The second question: the latter.

Yeah. Make a programming language where the function call stack is limited to size 5! :P Continue discussion here if wanted

For reputation 123456, can we print 123,456?

@Dennis Sure, if we can see the actual reputation.

Can I print 123,456 reputation instead? If so, what additional information is allowed? I assume I couldn't simply display the entire web page...

If you edit your clarifications from the comments into the question and rule what exactly may be displayed in the output and if subsequent outputs are allowed to overwrite the previous one, I think this can be reopened.

Bash + coreutils + w3m, 90 71 69 67 bytes
watch -tn10 w3m codegolf.stackexchange.com/u/$1\|grep -Pom1 ^[,-9]+

Takes the user ID as a command line argument and displays the reputation of the corresponding user (e.g., 135,249) in the upper left corner of the terminal.
Alternate version, 57 bytes, invalid?
watch -tn10 w3m codegolf.stackexchange.com/u/$1\|sed 44!d

This displays 135,249 reputation instead of 135,249.

This reply seems to assure you that if you can see the reputation it's valid, so I think that you can as well print 135,119 reputation.

Also, this test run seems a little bit fake...

Hm, if I interpret it what way, I could just open the URL in any browser and let the user search for the reputation count.

Right, then you should ask OP if that's allowed. And I believe that the , is already interpreter that way, although it is in fact valid numeric representation.

source: Stack Exchange

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

sort: votes


text:
Lossy or Lossless?
Given an audio file, determine whether it is encoded in a lossy format or a lossless format. For the purposes of this challenge, only the following formats need to be classified:

Lossy

AC3
AMR
AAC
MP2
MP3
Ogg Vorbis
WMA

Lossless

AIFF
FLAC
TTA
WAV

Rules

If input is taken in the form of a filename, no assumptions should be made about the filename (e.g. the extension is not guaranteed to be correct for the format, or even present).
There will be no ID3 or APEv2 metadata present in input files.
Any two unique and distinguishable outputs may be used, such as 0 and 1, lossy and lossless, foo and bar, etc.

Test Cases
The test cases for this challenge consist of a zip file located here which contains two directories: lossy and lossless. Each directory contains several audio files that are all 0.5-second 440 Hz sine waves, encoded in various formats. All of the audio files have extensions matching the formats above, with the exception of A440.m4a (which is AAC audio in a MPEG Layer 4 container).

"AAC audio in a MPEG Layer 4 container" raises the question: what other container formats do answers need to handle?

@PeterTaylor Only AAC was given special mention because I couldn't find a way to provide AAC audio without embedding it in an MPEG Layer 4 container via FFMPEG. The Vorbis audio is embedded in an Ogg container (as is the norm for Vorbis audio). All others are standalone formats.

Are you sure about the TTA file? According to the spec, TTA files should start with the magic number TTA1 or TTA2. FFM2 (the magic number of your file) appears to correspond to FFmpeg stream. Linux file recognizes the TTA1 header, but not the FFM2 one.

Also, can we assume that AAC will always be in an MPEG Layer 4 header? If not, what can we assume?

Can we take the contents of the file as an input or does our code have to retrieve them?

@Shaggy The contents may be piped in, or taken as a filename/URL or any of the other default I/O methods, so long as no additional input is used.

Would my 20 byte solution, so? Sorry, I'm still learning all the rules & standards around here.

@Shaggy It appears valid to me.

Sweet, thanks, @Mego :)

Jelly, 7 5 bytes
ƈƈeØA

Lossy formats return 0, lossless formats return 1.
Try it online! (permalinks in Gist)
Background
The formats we have to support have the following magic numbers, i.e., they start with these bytes.
Format    Header (text)       Header (hex)
-----------------------------------------------------------------------------------
AC3       .w                  0B 77
AMR       #!AMR               23 21 41 4D 52
AAC       ÿñP@..ü             FF F1 50 40 00 1F FC
  M4A     ... ftypM4A         00 00 00 20 66 74 79 70 4D 34 41 20
MP2       ÿû                  FF FB
MP3       ÿû                  FF FB
OGG       OggS                4F 67 67 53
WMA       0&²u.fÏ.¦Ù.ª.bÎl    30 26 B2 75 8E 66 CF 11 A6 D9 00 AA 00 62 CE 6C

AIFF      FORM????AIFF        46 4F 52 4D ?? ?? ?? ?? 41 49 46 46
FLAC      fLaC                66 4C 61 43
TTA       TTA1                54 54 41 31
  FFM2    FFM2                46 46 4D 32
WAV       RIFF????WAVE        52 49 46 46 ?? ?? ?? ?? 57 41 56 45

Indented entries are containers for the preceding format that appear in the test cases. ? denotes a variable byte. . denotes an unprintable byte. All other bytes are displayed as their ISO 8859-1 character.
By looking only at the second byte, we can determine the format in an easy way:
Lossless formats have an uppercase letter as their second byte, while lossy formats do not.
How it works
ƈƈeØA  Main link. No arguments.

ƈ      Read a char from STDIN and set the left argument to this character.
 ƈ     Read another char from STDIN and set the return value to this character.
   ØA  Yield the uppercase alphabet, i.e., "ABCDEFGHIJKLMNOPQRSTUVWXYZ".
  e    Exists; return 1 if the return value (second char on STDIN) belongs to the
       uppercase alphabet, 0 if not.

This is a very clever solution.

C, 82 80 32 bytes
Inspired by @Dennis' answer, this can be reduced much further:
main(){return getchar()&200^64;}

Pipe the file data to stdin. Returns 0 for lossless, or nonzero for lossy.
Or the original longer check:
char v[5];main(){scanf("%4c",v);return*v&&strstr("fLaC FORM RIFF TTA1 FFM2",v);}

Pipe the file data to stdin. Returns nonzero (1) for lossless, or 0 for lossy.
From what I can tell, all the formats you listed have separate magic numbers (except AIFF/WAV, but those are both lossless anyway), so this just checks that magic number for a known lossless value. The *v&& is just to protect against matching files which start with a null byte (M4A).
I've included the values I found in spec sheets (fLaC = FLAC, RIFF = WAV/AIFF, TTA1 = TTA), and FORM = AIFF and FFM2 = TTA are from the sample files provided (I can only guess these are wrapper formats or later versions).

Or a shorter feels-like-cheating alternative:
Bash + file, 61 bytes
N="$(file "$1")";[[ $N = *": d"* || $N = *IF* || $N = *FL* ]]

Takes the filename as an argument. Returns 0 for lossless, or nonzero for lossy.
Does exactly what you'd expect; asks file what the filetype is, then checks for known patterns. TTA matches : d (: data), AIFF / WAV match IF, and FLAC matches FL. None of the lossless results match any of these, and I've tested that it still works if the filenames are removed.

Testing:
for f in "$@"; do
    echo "Checking $f:";
    ./identify2 "$f" && echo "shorter C says LOSSLESS" || echo "shorter C says LOSSY";
    ./identify < "$f" && echo "longer C says LOSSY" || echo "longer C says LOSSLESS";
    ./identify.sh "$f" && echo "file says LOSSLESS" || echo "file says LOSSY";
done;

# This can be invoked to test all files at once with:
./identify_all.sh */*

Does your Bash solution also work if the file extension is incorrect? "the extension is not guaranteed to be correct for the format", so you should be able to give a file a wrong extension and still have it work.

@mbomb007 I've just tested with the extensions mixed up and it still identifies them fine. I think file doesn't trust extensions anyway (lots of users thing renaming a png to a jpeg is the same as converting it!)

GS2, 3 bytes
◄5ì

Lossy formats return 0, lossless formats return 1.
Try it online! (permalinks in Gist)
Background
The formats we have to support have the following magic numbers, i.e., they start with these bytes.
Format    Header (text)       Header (hex)
-----------------------------------------------------------------------------------
AC3       .w                  0B 77
AMR       #!AMR               23 21 41 4D 52
AAC       ÿñP@..ü             FF F1 50 40 00 1F FC
  M4A     ... ftypM4A         00 00 00 20 66 74 79 70 4D 34 41 20
MP2       ÿû                  FF FB
MP3       ÿû                  FF FB
OGG       OggS                4F 67 67 53
WMA       0&²u.fÏ.¦Ù.ª.bÎl    30 26 B2 75 8E 66 CF 11 A6 D9 00 AA 00 62 CE 6C

AIFF      FORM????AIFF        46 4F 52 4D ?? ?? ?? ?? 41 49 46 46
FLAC      fLaC                66 4C 61 43
TTA       TTA1                54 54 41 31
  FFM2    FFM2                46 46 4D 32
WAV       RIFF????WAVE        52 49 46 46 ?? ?? ?? ?? 57 41 56 45

Indented entries are containers for the preceding format that appear in the test cases. ? denotes a variable byte. . denotes an unprintable byte. All other bytes are displayed as their ISO 8859-1 character.
By looking only at the second byte, we can determine the format in an easy way:
Lossless formats have an uppercase letter as their second byte, while lossy formats do not.
How it works
     (implcit) Push the entire input from STDIN as a string on the stack.
◄    Push 1.
 5   Get the strings character at index 1, i.e., its second character.
  ì  Test if the character is an uppercase letter.

Cubix, 16 bytes
$-!u'HIa'@/1@O<

Net form:
    $ -
    ! u
' H I a ' @ / 1
@ O < . . . . .
    . .
    . .

Try it yourself
You should input the file decimal byte values in a separated list. The separator doesn't matter, anything that is not a digit or a minus sign suffices. The code really only cares about the first byte, so you can leave out the rest of the file if you like. The program outputs 0 for lossless, and 1 for lossy. Try it here! The default input uses a FLAC header.
Explanation
The nice thing about files is that (nearly) all of them have a so-called magic. Those are the first few bytes of the file. Good software doesn't check the file extension, but rather the file magic to see if it can handle a certain file.
Dennis has found a way to use this magic to find the compression type, but the fact that he discarded the first byte made me want to try to come up with a method that used the first byte, rather than the second. After all, this community is all about saving bytes.
Here's a list of the first bytes of the different file types. I ordered them into two groups: lossy and lossless. Here are the values of their first byte in decimal, hexadecimal and binary. You might see a pattern already...
Lossy:                  Lossless:
255:0xFF:0b11111111     102:0x66:0b01100110
 79:0x4F:0b01001111      84:0x54:0b01010100
 35:0x23:0b00100011      82:0x52:0b01010010
 11:0x0B:0b00001011      70:0x46:0b01000110
  0:0x00:0b00000000

The pattern I saw, was that the second bit (counted from left to right) was always on on the "lossless" bytes and the fifth bit was always off. This combination does not appear in any of the lossy formats. To "extract" this, we would simply do a binary AND (by 0b01001000 (=72)) and then compare to 0b01000000 (=64). If both are equal, the input format is lossless, otherwise it's lossy.
Sadly, Cubix doesn't have such a comparison operator, so I used subtraction (if the result is 64, this yields 0, and it results in 8, -56 or -64 otherwise. I'll get back to this later.
First, let's start at the beginning of the program. The binary AND is done using the a command:
'HIa
'H   # Push 0b01001000 (72)
  I  # Push input
   a # Push input&72

Then, we compare to 64 using subtraction (note we hit a mirror that reflects the IP to the top face [first line, second character, pointing south] in the middle of this part).
'@-
'@  # Push 0b01000000 (64)
  - # Subtract from (input&72)
    # Yields 0 for lossy, non-zero otherwise

After the IP is turned around by the u, we use some control flow to push a 1 to the stack if (and only if) the top of the stack is non-zero:
!$1
!   # if top = 0:
 $1 #   do nothing
    # else:
  1 #   push 1

After we wrap around the cube, we hit the < instruction, which points the IP west on the fourth line. All that's left to do is output and terminate.
O@
O  # Output top of the stack as number
 @ # End program

So, the program outputs 0 for lossless, and 1 for lossy.

Chip, 11 bytes
~Z~S
t'G~aF

Shamelessly replicated Dennis' Jelly answer in Chip.
Lossless returns 0x0, lossy returns 0x1.
Try it online, links in gist (thanks Dennis for the TIO strategy here)
Explain!
~Z~S
t'

This portion is housekeeping: it Skips the first byte, and terminates after the second.
G~aF

This is the meat of the decision. Each input byte is accessed by the bits HGFEDCBA. If G is set, and F is not, that means the byte is within the range 0x40 to 0x5f (which is roughly equivalent to 'uppercase', and good enough for the task at hand).
However, for byte savings, I invert this decision from G and (not F) to (not G) or F, since or's can be implicit in Chip.
This resultant true/false value is then placed into a, which is the lowest bit of the output. (All other bits will be zero). In the TIO, I run the output through hexdump so that the values are visible.
Equivalently, in C-ish, one would say something like:
out_byte = !(in_byte & 0x40) && (in_byte & 0x20)

JavaScript (ES6), 20 bytes
c=>/^[fFRT]/.test(c)

Explanation
Takes the contents of the file as an input and returns true if the file is lossless or false if it is lossy by testing the first character of that input to see if it is an f, F, R or T.

Try It
Paste the contents of a file into the textarea.

f=
c=>/^[fFRT]/.test(c)
i.addEventListener("input",_=>console.log(f(i.value)))
<textarea id=i></textarea>

Second effort, 81 63 bytes
Fetches the contents of a file from a provided URL, which turned out to be overkill.
u=>fetch(u).then(r=>r.text()).then(t=>alert(/^[fFRT]/.test(t)))

First effort, 146 116 89 bytes
Invalid as mime types are tied to extensions and, apparently, response headers qualify as additional input.
u=>fetch(u).then(r=>alert(/aiff|flac|tta|wave|wav$/.test(r.headers.get("Content-Type"))))

web servers usually generate the MIME based on the file extension, which is against the rules here. Have you checked if it works on files served without an extension? (if it does then you should probably include the name of the server you're using as part of the "language")

@Dave Pretty sure they don't. MIME and extension are not dependent on each other at all. If you change a file's extension and upload it, the MIME type is the MIME of the actual content of the file, not the extension. As it is, though, taking input as a URL is probably not allowed. I'm not sure.

@mbomb007 I'm not sure why you say that; mime types are an internet thing, not a filesystem / file thing, and the servers I'm aware of will determine it based on extension using a configured lookup (for speed of serving headers; they don't want to inspect every file before serving it). Take for example Apache's AddType <mime> <extension>, or IIS's <MimeMap>. Of course a specific setup or file hosting tool could do a proper inspection, and that would merit making the server choice be part of the answer (since it's the server that's determining the filetype!)

I've done file validation with .NET, and the MIME type matched the content even when the extension was changed before upload.

@mbomb007 then whichever .NET component you used must have performed file inspection either during the upload or when serving the files (I'd guess during upload for performance, but you never know). So going back to my original comment, that would make this answer something like "JavaScript + .NET SeverLibraryXYZ". As for taking input from a URL, I can see why you're hesitant but personally I'd consider it valid as long as the server choice is mentioned. Maybe there's an existing meta on it, but ultimately of course it's up to Mego.

Using the Internet is off-limits by default as a loophole.

@mbomb007 The intent of that loophole is to prevent answers from fetching information from the internet that is not present in the challenge to gain an advantage. Use of the MIME type in content headers counts as loophole abuse here, because that's extra input. Fetching from a URL is fine, but using response data other than the actual file data isn't.

Yes, MIME types are tied to extensions (at least in IIS) but I had hoped using them would be sufficient to meet the requirement that we not use file extensions to determine file type. I've updated my answer to determine type from the contents of the file, instead. @Mego, do you have a link to a consensus that responses headers count as extra input?

@Shaggy There is no consensus needed because there is no confusion - the input is only the file data (and optionally a filename, should that I/O method be used). Anything else is extra input.

Yeah, I suppose I can see the point, @Mego; the fact that the method I'm using to retrieve the file contents includes the headers in the response is irrelevant.

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


text:
Expand the Binomial
Challenge
Given three numbers \$a\$, \$b\$, and \$n\$, you must expand \$(a + bx)^n\$ in ascending powers of \$x\$ up to \$x^3\$.
Binomial Expansion
Note that this method is an approximation
The binomial expansion works like so:
(a + bx)^n = a^n(1 + bx/a)^n
           = a^n(1 + n(bx/a) + n(n -1)(bx/a)^2/2! + n(n-1)(n-1)(bx/a)^3/3!)

Or, more readable:
$$\begin{align}
(a+bx)^n &= a^n\left(1+\frac{b}{a}x\right)^n\\
&\approx a^n\left(1 + n\left(\frac{b}{a}x\right)+ \frac{n(n-1)}{2!}\left(\frac{b}{a}x\right)^2 + \frac{n(n-1)(n-2)}{3!}\left(\frac{b}{a}x\right)^3\right)
\end{align}$$
Which simplifies down to an expression in the form
$$\alpha + \beta x + \gamma x^2 + \delta x^3$$
Where \$\alpha\$, \$\beta\$, \$\gamma\$ and \$\delta\$ are constants which you must calculate.
These constants should be given to at least 3 decimal places where appropriate (i.e. 1.2537 should be output instead of 1.25, but 1.2 can be output if the answer is exactly 1.2).
You must then output these four constants in a list (in order as they appear in the final equation). This list may be separated however you wish.
Input
The inputs \$a\$ and \$b\$ will be integers in the range -100 to 100 inclusive where \$a \neq 0\$.
\$n\$ will be given to one decimal place and will be in the range \$-2 \leq n \leq 2\$
Examples
a = 1, b = 6, n = -1.0
1, -6, 36, -216

a = 3, b = 2, n = 2.0
9, 12, 4, 0

a = 5, b = 4, n = 0.3
1.621, 0.389, -0.109, 0.049

Winning
The shortest code in bytes wins.

Related

There is no way your equations can hold, as the left side has degree n in x, where as the right side has degree 3.

@flawr This method is a way to approximate the value of the polynomial

is a guaranteed to be non-zero?

@tsh Yes, I suppose that's fair

Oh look! There goes Mathematica!

Title change suggestion: Expand the Binomial Approximation

Mathematica, 45 37 bytes
It turns out that Binomial threads over lists!
Binomial[#3,r={0,1,2,3}]#2^r#^(#3-r)&

Each of Binomial[#3,r={0,1,2,3}], #2^r and #^(#3-r) returns a length-4 list, which are implicitly multiplied together term-by-term, giving the binomial coefficients.

Old solution (45 bytes):
FoldList[#~D~x/#2&,(#+#2x)^#3,Range@3]/.x->0&

And a 43-byte solution that works except when n = 0:
Series[(#+#2x)^#3,{x,0,3}][[3]]~PadRight~4&

ooo, I love the Series...[[3]] hack!

Haskell, 80 74 64 63 62 bytes
I've tried many more sophisticated approaches, but they all were longer than the straightforward approach. (In meantime golfed down a bit.)
Thanks for -1 byte @Laikoni!
(a#b)n|c<-b/a=(*a**n)<$>1:c*n:map(n*(n-1)*c*c*)[1/2,c*(n-2)/6]

Try it online!

Haskell, 46 bytes
(a%b)n=scanl(*)(a**n)[(n-i+1)/i*b/a|i<-[1..3]]

Try it online!
Expresses the ratios of consecutive terms, and uses them to recover the terms by scanl(*) starting with the first term a*n. The ratios have form (n-i+1)/i*b/a.

Casio BASIC, 144 bytes
?→A
?→B
?→N
B÷A→B
A^N→A
A((N(N-1))÷2!×B²)→S
A((N(N-1)(N-2)÷3!×B³)→T
N×B×A→N
ClrText
Locate 1,1,A
Locate 1,2,N
Locate 1,3,S
Locate 1,4,T

Output is in a line like so:
34.5
20
11
56.85

JavaScript, 55 53 50 bytes
(a,b,n)=>[s=a**n,s*=n*(b/=a),s*=--n*b/2,s*--n*b/3]

(a,b,n)=>a?[s=a**n,s*=n*(b/=a),s*=--n*b/2,s*--n*b/3]:(t=[0,0,0,0])|n>3?t:(t[n]=b**n,t)

MATL, 30 bytes
^li1G/3:"t@^2G@:q-HM/p*w]x4$h*

Try it online!
Input in a, n, b order.

Pari/GP, 29 bytes
(a,b,n)->Vec((a+b*x)^n)[1..4]

Try it online!

Axiom, 80 bytes
h(a,b,n)==(v:=series((a+b*x)^(n::Fraction INT));[coefficient(v,i)for i in 0..3])

exercises
(91) -> h(1,6,-1.0)
...
   (91)  [1,- 6,36,- 216]
                                            Type: List Expression Integer
(92) -> h(3,2,2.0)
   (92)  [9,12,4,0]
                                            Type: List Expression Integer
(93) -> h(5,4,0.3)
                  10+-+3     10+-+3    10+-+3
          10+-+3 6 \|5     42 \|5   476 \|5
   (93)  [ \|5  ,-------,- --------,---------]
                    25        625     15625
                                            Type: List Expression Integer
(94) -> map(numeric, %)
   (94)
   [1.6206565966 927624351, 0.3889575832 0626298443, - 0.1089081232 9775363564,
    0.0493716825 6164831482 4]
                                                         Type: List Float

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


text:
Simplified Train Set
Many different types of train set exist, ranging from wooden tracks like Brio, to fully digital control perfect tiny metal replicas of real trains, but they all require a track to be designed, ideally using as many of your pieces as possible.
So, your task is to determine whether, given input of the available pieces, it is possible to build a complete closed circuit using all of the elements, and if not, how many pieces will be left from the maximum possible circuit.
Since this is a simplified train set, there are only 3 elements: big curve, little curve, and straight. These are all based on a square grid:

"Big Curve" is a 90 degree corner, covering 2 units in each dimension
"Little Curve" is a 90 degree corner, covering one unit in each direction
"Straight" is a straight element, 1 unit long

This means that the minimum circuit possible is formed of 4 little curves - it's a circle, of radius 1 unit. This can be extended by adding pairs of straight elements to form various ovals. There are other circuits possible by adding more curves, or by mixing the types of curve.
This train set doesn't include any junctions, or methods for tracks to cross, so it's not valid for two elements to connect to the same end of an other element (no Y formations) or to cross over one another (no X formations). Additionally, it's a train set, so any formation which doesn't allow a train to pass isn't valid: examples include straights meeting at 90 degree angles (there must always be a curve between perpendicular straights) and curves meeting at 90 degree angles (curves must flow).
You also want to use as many pieces as possible, ignoring what type they are, so you'll always opt for a circuit which has more bits in. Finally, you only have one train, so any solution which results in multiple circuits is unacceptable.
Input
Either an array of three integers, all greater than or equal to 0, corresponding to the number of big curves, little curves, and straights available, or parameters passed to your program, in the same order.
Output
A number corresponding to the number of pieces left over when the maximum possible circuit for the elements provided is constructed.
Test data
Minimal circuit using big curves
Input: [4,0,0]
Output: 0

Slightly more complicated circuit
Input: [3,1,2]
Output: 0

Incomplete circuit - can't join
Input: [3,0,0]
Output: 3

Incomplete circuit - can't join
Input: [3,1,1]
Output: 5

Circuit where big curves share a centre
Input: [2,2,0]
Output: 0

Bigger circuit
Input: [2,6,4]
Output: 0

Circuit where both concave and convex curves required
Input: [8,0,0] or [0,8,0]
Output: 0

Circuit with left over bit
Input: [5,0,0] or [0,5,0]
Output: 1

Notes

2 straights and a little curve are equivalent to a big curve, but use more pieces, so are preferred - should never be a situation where this combination is left, if there are any big curves in the circuit
4 little curves can usually be swapped for 4 straights, but not if this would cause the circuit to intersect itself
The train set is also idealised - the track elements take up the widths shown, so it is valid for curves to pass through a single grid square without intersecting, in some cases. The grid just defines the element dimensions. In particular, two big curves can be placed so that the grid square at the top left of the example diagram would also be the bottom right square of another big curve running from left to top (with the diagram showing one running from right to bottom)
A small curve can fit in the empty space under a big curve (bottom right grid square above). A second big curve could also use that space, shifted one across and one down from the first
A small curve cannot fit on the same grid space as the outside of a big curve - mostly because there is no way to connect to it which doesn't intersect illegally

So the output for [5,0,0] or [0,5,0] would be 1. Is that correct? Could you add such a test case?

@arnauld Yes, that's correct. Should always be the remaining number of elements after building the longest possible circuit.

Could you please confirm that this is a solution for [8,0,0], with two 2x2 elements overlapping in the center of the grid?

Yes, that's the expected solution for that test case.

I am not clear on how the self-intersection works.  Could you be more explicit in defining what is allowed and what is forbidden?

@WheatWizard I've added some explicit details - basically, big curves can go back to back, and little curves can fit "in" big curves.

[JavaScript (Node.js)], 1220 bytes
f=r=>{var a=[{n:0,d:[[0,-1,"0000000101011"],[1,-1,"0011111111111"],[0,0,"0111101111111"],[1,0,"1100010000000"]],e:[2,-1,1]},{n:0,d:[[-1,-1,"1001111111111"],[0,-1,"0000010010110"],[-1,0,"0110000100000"],[0,0,"1101111011111"]],e:[-2,-1,3]},{n:1,d:[[0,0,"0011101111111"]],e:[1,0,1]},{n:1,d:[[0,0,"1001111011111"]],e:[-1,0,3]},{n:2,d:[[0,0,"1111101011111"]],e:[0,-1,0]}],e=r=>{var a=r.d,e=r.e,n=[];return a.forEach(r=>{var a=r[2];n.push([-r[1],r[0],""+a[10]+a[5]+a[0]+a[8]+a[3]+a[11]+a[6]+a[1]+a[9]+a[4]+a[12]+a[7]+a[2]])}),{d:n,e:[-e[1],e[0],e[2]]}};i=((r,a)=>{for(var n=0;n<r.d;n++,a=e(a));var p=!1;return a.d.forEach(a=>{var e=r[`${r.p.x+a[0]},${r.p.y+a[1]}`];void 0===e&&(e="00000000000000");for(var n="",d=0;d<13;d++)"1"===e[d]&&"1"===a[2][d]&&(p=!0),n+=e[d]===a[2][d]?e[d]:"1";r[`${r.p.x+a[0]},${r.p.y+a[1]}`]=n}),r.p.x+=a.e[0],r.p.y+=a.e[1],r.d=(r.d+a.e[2])%4,!p});var n=[],p=(r,e)=>{a.forEach(a=>{var d=Object.assign({},r);if(d.p=Object.assign({},r.p),!(e[a.n]<=0)&&i(d,a)){if(d.ps+=a.n,0==d.p.x&&0==d.p.y&&0==d.d)return void n.push(d);var s=Object.assign([],e);s[a.n]-=1,p(d,s)}})};p({p:{x:0,y:0},d:0,ps:""},Object.assign([],r));var d=0;n.forEach(r=>{r.ps.length>d&&(d=r.ps.length)}),console.log(r[0]+r[1]+r[2]-d)};

Try it online!
Note: The input is actually the variable q at the start. [2,6,4] will also take quite a bit of time as this is a brute force solution without optimizations.
I actually did this because it hasn't been answered in over a year and I was just kinda curious if it was possible.

Original Code:
var q = [4, 2, 4];
var t = [
    {
        n: 0,
        d: [
            [0, -1, "0000000101011"],
            [1, -1, "0011111111111"],
            [0, 0, "0111101111111"],
            [1, 0, "1100010000000"]
        ],
        e: [2, -1, 1],

    },
    {
        n: 0,
        d: [
            [-1, -1, "1001111111111"],
            [0, -1, "0000010010110"],
            [-1, 0, "0110000100000"],
            [0, 0, "1101111011111"]
        ],
        e: [-2, -1, 3]
    },
    {
        n: 1,
        d: [
            [0, 0, "0011101111111"]
        ],
        e: [1, 0, 1]
    },
    {
        n: 1,
        d: [
            [0, 0, "1001111011111"]
        ],
        e: [-1, 0, 3]
    },
    {
        n: 2,
        d: [
            [0, 0, "1111101011111"]
        ],
        e: [0, -1, 0]
    },
];

r = (p) => {
    var d = p.d; var e = p.e; var o = [];
    d.forEach(i => {
        var d = i[2];
        o.push([-i[1], i[0], "" + d[10] + d[5] + d[0] + d[8] + d[3] + d[11] + d[6] + d[1] + d[9] + d[4] + d[12] + d[7] + d[2]])
    });
    return { d: o, e: [-e[1], e[0], e[2]] };
};

i = (g, p) => {
    //console.log(g.p, g.d);
    for (var i = 0; i < g.d; i++ , p = r(p));
    var c = false;
    p.d.forEach(d => {
        var v = g[`${g.p.x + d[0]},${g.p.y + d[1]}`];
        if (v === undefined) v = "00000000000000";
        var o = "";
        for (var i = 0; i < 13; i++) {
            if (v[i] === '1' && d[2][i] === '1')
                c = true;
            o += (v[i] === d[2][i]) ? v[i] : '1';
        }
        //console.log(o);
        g[`${g.p.x + d[0]},${g.p.y + d[1]}`] = o;
    });
    g.p.x += p.e[0];
    g.p.y += p.e[1];
    g.d = (g.d + p.e[2]) % 4;
    return !c;
};

var l = [];
var re = (g, p) => {
    t.forEach(piece => {
        var gr = Object.assign({}, g);
        gr.p = Object.assign({}, g.p);
        if (p[piece.n] <= 0)
            return;
        if (i(gr, piece)) {
            gr.ps += piece.n;
            if (gr.p.x == 0 && gr.p.y == 0 && gr.d == 0) {
                l.push(gr);
                return;
            }
            var ti = Object.assign([], p);
            ti[piece.n] -= 1;
            re(gr, ti);
        }
    });
};
var gr = { p: { x: 0, y: 0 }, d: 0, ps: "" };
re(gr, Object.assign([], q));

var c = 0;
var lo = 0;
l.forEach(g => {
    if (g.ps.length > lo) {
        require("./draw.js")(g, `outs/out${c++}.png`)
        lo = g.ps.length;
    }
});

console.log(q[0] + q[1] + q[2] - lo);

first I should include a graphic of the tiles I used.

The sections of this tile were given a number and
used for comparison and overlap handling later.

So there first thing is the array t at the start.
This is a collection of track pieces that contain
    n[ame]: the index of the input array.
    d[ata]: the offset from the current tile and the Tile bit values.
    e[nd]: the relative offset and rotation that the piece provides.

function r[otate] ( p[iece] )
    this outputs a piece that is rotated by 90 degrees
    by rearranging the tile bits and the end offset

function i[nsert] ( g[rid], p[iece] )
    this modifies the passed in grid trying to place down each tile of the piece.
    if it hits a point where 2 tiles intersect it sets a flag c[ollision]
    it then adjusts the current p[osition] and and d[irection] stored in the grid.
    then it returns !c[ollision]

function re[peat] ( g[rid], p[eices] )
    this iterates across all nodes which
        creates a copy of the g[rid] as gr[id].
        checks if the piece is available if not continue
        if the peice is added without a collision
            add piece name to gr[id].ps[piece string];
            it checks if its back at the start
                add gr[id] to l[ist]
                return as no more pieces can be added without a collision.
            clone peices remove the used peice ti[nput]
            call re[peate] (gr[id], ti[nput])

call re[peate] with empty grid

search l[ist] for longest piece string
and output input added together minus the length of the longest string.

Sorry if the write up is hard to read I'm not used to explaining how my code works.
P.S. I actually also made a few functions for drawing the maps to a png
but of course those were remove to save at least some space.

I'm impressed - I'd kind of given up hope on this one! Would be interested in a write up

@Matthew I'll see when I get time to write one up. It actually might take a little while. But yeah, normally these are my favorite kinds of puzzles to do. Even if it's not short it's fun to prove it's possible.

@Matthew added the write up.

Is there a reason why you chose to use p[a.n]-=1 instead of p[a.n]--?

Initializing q like that isn't an allowed input method. Most commonly, either make it a function argument or read it from stdin.

I did originally consider making the challenge drawing a map using the pieces, but noticed that graphical output challenges that also combined some other calculation didn't seem to get many answers. This was the "easy" version of the challenge!

@ØrjanJohansen Oh sorry about that I'll see what I can do to fix that really quick.

@JonathanFrech I was writing so much and moving so much around that I just over looked it. I know more compression things I could do like removing vars but it already took me quite a few hours to write on its own.

@ØrjanJohansen Is this updated version more compliant?

Yes. Actually you don't need to include the f= or the final ;, since it's an anonymous function that doesn't refer to itself.

@ØrjanJohansen Okay, thanks for the help! I'll do that next time I get a chance to really cut it down further.

Thanks for pushing that! Does this actually try to put all the pieces in place and then count what´s left? Would be a shame to waste all that data: Care to do a version with ascii art output?

@Titus I could possibly try the ascii version tomorrow, but yeah it places down all the pieces and it actually just gets the length of the final name which corresponds to the number of pieces used.

@Titus it's not the most pretty solution as I kinda hacked it together from my normal drawing code but here it is: https://pastebin.com/iL74aXEp


text:
Embedded Triangles!
Your task: given an integer n, output an embedded triangle to the nth depth.
Standard methods of input and output, input in any convenient format, output should be as a string. Examples are 0-indexed, you can use 1-indexed if you want. Standard loopholes apply
The left and right sides of each figure is 2^n, when 0 indexed. The top is twice that.
Examples:
n=0
--
\/

n=1
----
\/ /
 \/

n=2
--------
\/ /   /
 \/   /
  \  /
   \/

This is code-golf, so shortest code wins!
This is NOT a duplicate of the Embedded Hexagons! challenge. I don't think any answers from that question could be trivially copied over to this one.

@BetaDecay Aww, come on. same author, no big deal.

Sure, but where does it end? Embedded squares? Embedded Circles? Embedded dodecagons? One challenge IMO is enough

@BetaDecay How does one have an ASCII circle? More to the point, I don't think any answer to the hexagon challenge could be trivially copied over. And what is the problem with similar challenges that are substantially different? If there is one, please let me know.

I'm nominating to reopen this question because I don't see how the hexagon challenge's answers could be trivially copied to this challenge.

I'm voting to reopen, as I don't believe they're dupes. However, I've downvoted the challenge. It's kinda boring to have many sets of embedded , and you've got at least 1 more in teh sandbox.

Charcoal, 27 bytes
ＮαＷα«Ｘ²ι↙ＡＸ²⁻ι¹β↙β↑↖β→Ａ⁻α¹α

Try it online!
Just modified my submission from the hexagon challenge a bit to make a triangle.

16 bytes: ＦＥＮＸ²ι«ιι↙↙ι↑↖ι→ (1-indexed).

@Neil I think this solution is different enough to warrant its own answer

Retina, 44 bytes
^
\/
+`( *)/1
$1/$1 $1/
*`.
-
;+(*G`
\\..
 \

Try it online!
I only want to print successful replacements, but I don't really know how to do that.
As I'm no longer allowed to add another answer, here's a Batch answer for 192 bytes:
@echo off
set d=-
set l=\
set r=/
for /l %%i in (1,1,%1)do @call set r=%%r%%%%d:-= %%/&call set d=%%d%%-%%d%%
echo -%d%
:l
echo %l%%r%
set l= %l%
set r=%r:~2%
if not "%r%"=="" goto l

And here's a JavaScript (ES7) port of @lanlock4's excellent Mathematica answer for 124 bytes:

f=
n=>[...Array(2**n+1)].map((_,i)=>[...Array(2<<n)].map((_,j)=>i?i+~j?i>j?` `:i+j-(i+j&-i-j)?` `:`/`:`\\`:`-`).join``).join`
`
<input type=number min=0 oninput=o.textContent=f(this.value)><pre id=o>

And here's a Charcoal answer for 16 bytes:
ＦＥＮＸ²ι«ιι↙↙ι↑↖ι→

Try it online! Link is to verbose version of code. Explanation:
  Ｎ                 Input number
 Ｅ                  Map over implicit range
    ²               Literal 2
     ι              Current index
   Ｘ                Exponentiate
Ｆ     «             Loop over resulting powers of 2
       ι            Print right
        ι           Print right again
         ↙          Move down and left
          ↙ι        Print down and left
            ↑       Move up
             ↖ι     Print up and left
               →    Move right

Now you could add another answer, go ahead! (It's quite weird putting irrelevant answers all-in-one.)

@Memberfor3months I could, but I don't know what I'd do with my ES7 answer, seeing as Arnauld outgolfed it anyway.

Mathematica, 105 bytes
""<>Table[Which[i<1,"-",i==j,"\\",IntegerQ@Log2[i+j-1]&&j>i,"/",1>0," "],{i,0,2^#},{j,2*2^#}]~Riffle~"\n"&

where \n is replaced with a newline.
Explanation: Makes an array of characters (indexed from i = 0 to 2^n vertically, j = 1 to 2^(n+1) horizontally) according to these rules:

If i<1 (so i = 0), put a "-" (for the top row)
If i==j, put a "\" (escaped, for the left-hand side)
If Log2[i+j-1] is an integer (so i+j-1 is a power of 2) and j>i, put a "/" (for the other edges)
And put " " everywhere else.

Then ""<>...~Riffle~"\n"& turns this array into a string.

JavaScript (JavaScript Shell), 136 132 bytes
t=2**readline();p=print;p(v='-'.repeat(t*2));for(y=0;y<t;y++)p(' '.repeat(y)+'\\'+v.replace(/-/g,(_,i)=>i&-~i?' ':'/').slice(y*2+1))

Try it:

readline = () => prompt();
print = (...args) => output += (args.join(' ') + '\n');
output = '';

t=2**readline();p=print;p(v='-'.repeat(t*2));for(y=0;y<t;y++)p(' '.repeat(y)+'\\'+v.replace(/-/g,(_,i)=>i&-~i?' ':'/').slice(y*2+1))

document.write(`<pre>${output}</pre>`);

readline = prompt; probably suffices.

C, 200 bytes
#define P printf(
i,j,k,l;f(n){for(i=0,k=pow(2,n);i++<k;)P"--");for(i=0;i<k;++i){l=P"\n%*c",i+1,92);for(j=0;j<n;++j)if(2*(int)pow(2,j)+1-i>l)l+=P"%*c",2*(int)pow(2,j)+1-i-l,47);P"%*c",2*k-i-l+1,47);}}

Try it online!

JavaScript (ES6), 108 95 93 92 bytes

let f =

n=>(g=x=>y>1<<n?'':x<2<<n?' /\\-'[y?~x+y?+!(k=x+y,x<y|k&-k-k):2:3]+g(x+1):`
`+g(!++y))(y=0)

console.log(f(0))
console.log(f(1))
console.log(f(2))
console.log(f(3))

05AB1E, 45 bytes
I made it! (It's a fun challenge, I don't get why they VTC'd it)
<oLð×ε¨'\«}IL<oð×ε¨'/«}JDgU.sR2ô€нøJ»X>'-×s‚»

Try it online!

Canvas, 22 bytes
╵ｒＨ２；＾／Ｌ ×；＋ｎ｝ｌ＼ｎＬ-×；∔

Try it here!
Explanation
'rH2;^/L ×;+n}l\nL-×;∔
'                      increment input integer n
 r                     range 0..n
  H          }         push an empty string and start a loop
   2;^                 get 2^i
      /                antidiagonal of that length
       L               get width(don't pop)
         ×;_           add that many spaces to the left
            n          overlap with prev iteration
              l        get height(don't pop)
               \       create a diagonal of that length
                n      and overlap with the created sides
                 L     get width(don't pop)
                  -×;∔ add that many minuses to the top

PHP, 137 Bytes
for(;$i<1+2**$a=$argn;++$i)for($n=0;$n<$m=2**($a+1);$s[]=2**++$n)echo$n%$m?"":"\n",$i?$i-1!=$n?$i<=$n&in_array($i+$n,$s)?"/":" ":"\\":"-";

Online Version
Expanded
for(;$i<1+2**$a=$argn;++$i)
for($n=0;$n<$m=2**($a+1);$s[]=2**++$n) # fill array for sum compare after loop
echo$n%$m?"":"\n", # print line feed
$i  # false for first line
 ?$i-1!=$n # row number - 1 equal column print \
  ?$i<=$n&in_array($i+$n,$s) # if row number lte column and sum of both in array print /
   ?"/"
   :" " # else print space
  :"\\"
 :"-"; # fill first line

A recursive way for 199 Bytes
function f($a){global$r;for(;$i<1+2**$a;$i++)for($n=0;$n<$m=2**($a+1);$n++)$r[$i][$n]=$i?$i-1!=$n?$i<=$n&&$i+$n==2**($a+1)?"/":" ":"\\":"-";$a?f($a-1):0;}f($argn);echo join("\n",array_map("join",$r));


text:
Help Gödel with his β function
Gödel's β  function takes three natural numbers as arguments.
It is defined as β(x,y,z) = rem(x, 1 + (z + 1) · y) = rem(x, (z · y + y + 1) )
where rem(a, b) denotes the remainder after integer division of a by b.
The β Lemma now states that:

For any sequence of natural numbers (k_0, k_1, … , k_n), there are natural numbers b and c such that, for every i ≤ n, β(b, c, i) = k_i.

Gödel needs help to find b and c for any given input (k_0, k_1, … , k_n), k_i ∈ ℕ.

Write a function that takes in an array of length n, filled with natural numbers, and gives a possible b,c output that fulfilles the Lemma for the array.

Do not get solutions by brute force!
(In my totally unprofessionall opinion, it is brute force when you first get a number and then do the calculation. That is guessing the number and then looking if the guess was correct. What I want to be coded here is a solution which calculates the numbers and does not have to check whether they fulfill the lemma because they were calculated to do so. )
Construct them with the equations and information given.
Shortest code wins, bonus points if you do it in Javascript because I am just getting into it :)

Example:
[5, 19, 7, 8] -> (1344595, 19)
1344505 % (1 + (0 + 1) * 19) = 5
1344505 % (1 + (1 + 1) * 19) = 19
1344505 % (1 + (2 + 1) * 19) = 7
1344505 % (1 + (3 + 1) * 19) = 8

Welcome to PPCG! This is a nice first question, but I would recommend adding some test cases to make it more clear.

Hi. I didnt add any tests because there are sometimes different ways to solve for one array. If I gave an input-output pair it could seem like this input had to give this output.

@Tweakimp Even so, a single worked example could help clarify the rather formal definition.

You are saying "shortest", does it means a brute force solution is just ok? although there is some constructive solutions

@tsh You are right, I should clarify that brute force solutions are not allowed, because that would take away the nice construction problem :)

Related

It's not clear what qualifies as "brute force". Obviously an approach which iterates through all pairs (b, c) until it finds one which works would be brute force, and an approach which runs in time linear in the length of the input would not be, but there's a large gap between those. Where is the line drawn?

@PeterTaylor i think "solve it in P" is acceptable (not brute force), while we assume your math operations (add, mul, rem...) on two number are O(1).

@PeterTaylor This is significantly more complicated than the related challenge, as the moduli are not (co)prime here.

@MartinEnder I added an example I generated with my answer.

Did someone say Beta?

@orlp, https://codegolf.meta.stackexchange.com/q/12110/194 . PS Who says they're not coprime? That's one of the questions hidden behind my question about what qualifies as brute force...

@Peter Taylor: In my totally unprofessionall opinion, it is brute force when you first get a number and then do the calculation. That is guessing the number and then looking if the guess was correct. What I want to be coded here is a solution which calculates the numbers and does not have to check whether they fulfill the lemma because they were calculated to do so.

@PeterTaylor I just realized that for some (non-optimal) c it doesn't have to be not coprime. But for some k the optimal c leads to not pairwise coprime moduli.

I think %, the modulo operator, is more widely known than rem. It works the same way: a%b returns the same thing as rem(a,b). Your call, but I recommend using it.

JavaScript (ES6), 104 bytes
a=>[c=a.reduce(c=>c*++i,Math.max(...a),i=0),a.reduce(g=(x,k)=>x%m-k?g(x+n,k):(n*=m,m+=c,x),0,n=1,m=c+1)]

Returns [c, b] as an array. The solution it returns isn't minimal in c but I think it is minimal in b for the given c. For 120 bytes this returns solutions minimal in c and in b for the given c:
f=(a,c=1,b=a.reduce(g=(x,k)=>x%m-k?d--?g(x+n,k):0/0:n%m?g(x,k,n+=o):(o=n,d=m+=c,x),0,o=n=1,d=m=c+1))=>1/b?[b,c]:f(a,c+1)

Ungolfed minimal solution solver:
function godel(a) {
    for (c = 0;; c++) {
        var b = 0, n = 1, i = 0;
        for (;;) {
            var m = c * i + c + 1;
            // Increase b until β(b,c,i) = a[i]
            // Adding n won't change output for smaller i
            for (j = 0; j < m; j++) if (b % m != a[i]) b += n;
            if (j == m) break; // couldn't find a remainder, c too low
            i++;
            if (i == a.length) return [b, c]; // Result!
            // Next time we want adding n to b not to change β(b,c,i)
            for (j = 1; n * j % m != 0; j++);
            n *= j;
        }
    }
}

Great! Would you be so kind and comment the code? :)


text:
Build a Digital Plotter
Problem adapted from the book Fortran 77 by Donald M. Monro
Introduction
Digital plotting machines are widely used to produce various forms of drawings, graphs and other pictorial results. Most such machines can move their pens only in certain directions, usually as single steps in the X and Y direction or both. A typical machine would move in one of the eight directions shown in Fig. 1:

Fig. 1
Challenge
Write a program without trigonometric functions which takes a number from 0 to 7 (inclusive) as input and outputs the corresponding coordinates of the endpoints in Fig. 1.
Output should as an array or list with two elements (i.e. (1, 0) or [0,-1])
Table of I/O
0 (1, 0)
1 (1, 1)
2 (0, 1)
3 (-1, 1)
4 (-1, 0)
5 (-1, -1)
6 (0, -1)
7 (1, -1)

Winning
Shortest code in bytes wins

Does a rotate(x) function count as a trigonometric function? (it just rotates the "canvas" by x radians)

@Kritixi No, the restriction is solely on cos, sin, tan, sec etc.

I'm pretty sure there's a related question that involves following the perimeter of a square of specified size but I can't find it.

Can May we 1 index instead of 0 index?

@Jonathan No, it must start at 0

Are you going to select the winner?

@2501 Sure, just let me get round to it

Jelly, 8 bytes
Hı*µḞ,ĊṠ

Using complex arithmetic appears to be allowed.
Try it online!
How it works
Hı*µḞ,ĊṠ  Main link. Argument: n

H         Halve; yield n/2.
 ı*       Yield i^(n/2), where i is the imaginary unit. Since i = e^(iπ/2), this
          computes e^(inπ/4) = cos(nπ/4) + i×sin(nπ/4) = x + iy, where (x, y) is
          the coordinate pair of (nπ/4)/(2π) = n/8 turns along the unit circle.
   µ      Begin a new chain with argument z = x + iy.
    Ḟ     Real part of z; yield x.
      Ċ   Imaginary part of z; yield y.
     ,    Pair, yielding (x, y).
       Ṡ  Apply the sign function to x and y.

Python 2, 29 bytes
lambda n:1j**(n/2)*(1+n%2*1j)

Returns the coordinates as a complex number.

Oh nice. I didn't even think of using complex numbers!

Of course this does use trigonometric functions in a sense.

@ceasedtoturncounterclockwis Sure, but it simplifies the equation until they're no longer present.

Mathematica, 24 bytes
Sign@{12-8#+#^2,4#-#^2}&

Pure function, using Sign and knowing where certain parabolas go.

C, 103 86 74 73 70 bytes
Thanks to @orlp for saving 12 15 bytes!
f(n){n="biM1*#?["[n]/7;printf("%c%d %d",n&8?32:45,n/4&1,n%2*~-(n&2));}

Try it online!

"\16\17\13\7\6\5\9\15"[n] == "pw[1*#?i"[n]/7

@orlp Thanks! Though the string is actually "biM1*#?[", because in "\16\17\13\7\6\5\9\15" the values are octal numbers, so 16 == 14 in decimal, 17 == 15 and so on.

!!(n&4) == n/4&1

n&2?n&1:-(n&1) == n%2*~-(n&2)

68 bytes

Desmos, 33 bytes
f(n)=mod(floor([4,2]^55/3^n),3)-1

Try it on Desmos!
The coordinate is returned as a 2 element list.

Yo welcome to code golf!! You are from the Desmos Discord, right?

@AidenChow thanks, yeah!

JavaScript (ES6), 41 36 bytes
r=>[1-(6800>>r*2&3),(425>>r*2&3)-1]

Uses two simple lookup tables which encode the 8 entries in base 4 after adding one to each "digit". Alternate version, using simpler lookup tables:
r=>["22100012"[r]-1,"12221000"[r]-1]

Old version (4 bytes shorter thanks to @Neil):
r=>[r>2&r<6?-1:r<2|r>6,r>4?-1:r%4&&1]

Naive approach using some simple calculations to find the X and Y coordinates separately...

Your current version gives incorrect answers for 4 and 5 but I think either r&&(r<4)-(r>4) or r%4&&1-(r&4)/2 save a byte on your old version.

@Neil Hmm, I don't think that's an easy fix so I'll just switch to an alternate version. Thanks for the other tip though :-) It looks golfable, but I don't see how...

I think I've shaved a bit more off, still not quite short enough yet though: r=>[r>2&r<6?-1:r<2|r>6,r>4?-1:r%4&&1]

You can save a byte with n=>[(s='22100012')[n]-1,s[n+6&7]-1].

APL, 21 bytes
{×¯4 4+1 ¯1×2*⍨⍵-4 2}

Welcome to Code Golf!

TI-Basic, 23 bytes
Prompt X
e^(i(pi)X/4
round({real(Ans),imag(Ans)},0

Assumes your calculator is in radian mode; if that needs to be in the program, then it's 25 bytes.

I think radian mode is on by default, so you should be fine.

Jelly, 13 12 bytes
I am still fairly confident there is shorter, but I have not found anything yet, so thought I'd post this
+2,ị6400b3¤’

Try it online! or see a test suite
How?
+2,ị6400b3¤’ - Main link: n                        e.g. 7
+2           - n+2                                      9
  ,          - paired with n: [n+2,n]                   [9,7]
          ¤  - nilad followed by link(s) as a nilad      9th         7th
    6400     -     6400                                  v           v
        b3   -     to base 3: [2,2,2,1,0,0,0,1]         [2,2,2,1,0,0,0,1]
   ị         - index into (1-indexed and modular)       [2,0]
           ’ - decrement (vectorises)                   [1,-1]

An alternative method, also 12 bytes:
_/,+/Ṡ  - Link 1: get next coordinate: current coordinate (list) e.g. [-1,-1]
_/      - reduce by subtraction                                       0
   +/   - reduce by addition                                         -2
  ,     - pair                                                        [0,-2]
     Ṡ  - sign (vectorises)                                           [0,-1]

2BÇ⁸¡ - Main link: n
2B    - 2 in binary: [1,0]
    ¡ - repeat
   ⁸  - left argument (n) times:
  Ç   -     last link (1) as a monad

C, 66 bytes
f(n){printf("%d %d\n",(n-2)%4?n>2&n<6?-1:1:0,(n-4)%4?n>4?-1:1:0);}

test code
main(i)
{for(i=0;i<8;++i) f(i);}

results
1 0
1 1
0 1
-1 1
-1 0
-1 -1
0 -1
1 -1

JavaScript (Node.js), 34 bytes
e=>[434,5].map(n=>(85*n>>2*e&3)-1)

Try it online!

C, 56 bytes
d(n){printf("%d,%d",n+2&3?n+2&4?-1:1:0,n&3?n&4?-1:1:0);}

Simple binary search done twice. The first search is done on n shifted by 2.
Online output on Ideone.
C, 53 bytes
r;p(n){r?0:p(r=n+2);r=!printf("%d ",n&3?n&4?-1:1:0);}

Output without a comma was able to be compacted even more using a recursive call.
Online output on Ideone.