title: "-rot" transform

text:
# Question
Title: "-rot" transform
## Background

**-rot transform** (read as "minus-rot transform") is a sequence transformation I just invented. This transform is done by viewing the sequence as a stack in Forth or Factor (first term on the top) and repeatedly applying `-rot +`. `-rot` is a command that moves the top of the stack to two places down, and `+` adds two numbers on the top of the stack.

For example, applying -rot transform to the sequence `[1, 2, 3, 4, 5, 6, 7, 8, 9]` looks like this (the right side is the top of the stack in this example, to match Forth/Factor conventions):

```
initial: 9 8 7 6 5 4 3 2 1 <--
-rot   : 9 8 7 6 5 4 1 3 2
+      : 9 8 7 6 5 4 1 5 <--
-rot   : 9 8 7 6 5 5 4 1
+      : 9 8 7 6 5 5 5 <--
-rot   : 9 8 7 6 5 5 5
+      : 9 8 7 6 5 10 <--
-rot   : 9 8 7 10 6 5
+      : 9 8 7 10 11 <--
-rot   : 9 8 11 7 10
+      : 9 8 11 17 <--
-rot   : 9 17 8 11
+      : 9 17 19 <--
-rot   : 19 9 17
+      : 19 26 <--

```

`-rot` does not work when there are only two items on the stack, so the operation stops there. Then the top of the stack at the initial state and after each `+` command are collected to form the resulting sequence of `[1, 5, 5, 10, 11, 17, 19, 26]`. Note that it is one term shorter than the input sequence.

## Task

Given a finite sequence of integers (of length ≥ 3), compute its -rot transform.

Standard rules apply. The shortest code in bytes wins.

## Test cases

```
[1, 2, 3] -> [1, 5]
[1, -1, 1, -1, 1, -1, 1, -1] -> [1, 0, 0, 1, -1, 2, -2]
[1, 2, 3, 4, 5, 6, 7, 8, 9] -> [1, 5, 5, 10, 11, 17, 19, 26]
[1, 2, 4, 8, 16, 32, 64, 128] -> [1, 6, 9, 22, 41, 86, 169]
[1, 0, -1, 0, 1, 0, -1, 0, 1] -> [1, -1, 1, 0, 1, -1, 1, 0]

```

# Answer
# Jelly, 8 bytes

```
Ä2œPF_@\

```

Try it online!

Based on the older approach below. `Ä` generates cumulative sums, and `2œPF` (ew) throws away the second one. Then `\` scanning by `_@` flipped subtraction gives:

```
    [a,
     a+b+c-(a),
     a+b+c+d-(a+b+c-(a)),
     a+b+c+d+e-(a+b+c+d-(a+b+c-(a))),
     ...]
    = [a, b+c, a+d, b+c+e, ...]

```

I feel like there has to be something shorter than `2œPF` to remove the 2nd element of a list.

# Jelly, ~~9~~ 8 bytes

```
Jḟ2b1^\ḋ

```

Try it online!

Based on rak1507's observation that when the input is \\$\[a,b,c,d,e,f...\]\\$, the answer is $$\[a, ~~b + c, ~~a + d, ~~b + c + e, ~~a + d + f, \dots\].$$

That is: cumulative sums of even and odd elements, but with the first two elements swapped.

That means we can calculate ( is dot product, padding the shorter argument with 0s at the end):

```
ḋ(input, [1]) = a
ḋ(input, [0, 1, 1]) = b + c
ḋ(input, [1, 0, 0, 1]) = a + d
ḋ(input, [0, 1, 1, 0, 1]) = b + c + e
ḋ(input, [1, 0, 0, 1, 0, 1]) = a + d + f
ḋ(input, [0, 1, 1, 0, 1, 0, 1]) = b + c + e + g
...

```

In this program, `Jḟ2b1^\` computes the triangle `[[1], [0,1,1], [1,0,0,1]…]` and  takes dot products with the input.

`Jḟ2` is `[1,3,4,5,…,n]`. `b1` generates lists of 1s of those lengths, and `^\` is a XOR scan.
> 13 votes

# Answer
# Python 3, ~~53~~ 47 bytes

```
f=lambda a,b,*r:(a,)+(r and f(b+r[0],a,*r[1:]))

```

A variadic function that takes the integers as separate arguments and returns a tuple. Try it online!

### Explanation

```
f=lambda a,b,*r:(a,)+(r and f(b+r[0],a,*r[1:]))
f=                                              # Define f to be
  lambda a,b,*r:                                # a function of at least two arguments
                                                # where a,b are the first two args
                                                # and any args beyond those are
                                                # put in a tuple and assigned to r
                (a,)                            # Tuple containing a
                    +                           # Add (concat) this tuple:
                     (r and                   ) # If r is falsey (empty), then r
                            f(               )  # Else, recursive call with:
                              b+r[0],           # The second arg plus the third
                                     a,         # followed by the first arg
                                       *r[1:]   # followed by all the rest

```
> 12 votes

# Answer
# Jelly, ~~11~~ 10 bytes

```
-œ?UŒœÄZFḊ

```

Thank you very much to caird/Dude/ChartZ for helping golf this in TNB.

-1 thanks to Lynn!

Explanation:

I tried to look for a pattern that could be used to solve this more easily, so a quick sage script did the trick.

From that, we get the pattern

```
[a, b + c]
[a, b + c, a + d]
[a, b + c, a + d, b + c + e]
[a, b + c, a + d, b + c + e, a + d + f]
[a, b + c, a + d, b + c + e, a + d + f, b + c + e + g]
[a, b + c, a + d, b + c + e, a + d + f, b + c + e + g, a + d + f + h]

```

From this, we can see it is an interleaved cumulative sum of \[a, d, f, h...\] and \[b, c, e, g...\]. Flipping a and b makes this nicer, \[b, d, f, h...\] and \[a, c, e, g...\].

```
-œ?UŒœÄZFḊ
-           -1
 œ?         -1th ordered permutation, i.e. second-from-last. This will always be the array reversed with the last 2 elements swapped
   U        un-reverse
    Œœ      uninterleave
      Ä     cumulative sum
       Z    zip
        F   flatten
         Ḋ  tail

```

Try it online!
> 9 votes

# Answer
# Prolog (SWI), ~~47~~ 46 bytes

*-1 byte thanks to Wheat Wizard*

```
[A,B|T]/[A|R]:-T=[C|U],S is B+C,[S,A|U]/R;T=R.

```

Try it online!

### Explanation

We define `/` as an infix predicate that takes a list as its left argument and sets its right argument to the -rot transformed list.

```
[A,B|T]/[A|R] :-

```

The left argument must have at least two elements, `A` and `B`. Any elements beyond the second are put in `T`. The right argument will always start with `A`; the rest of it will be `R`, which we calculate in one of two ways:

```
T=[C|U], S is B+C, [S,A|U]/R

```

Recursive case: if `T` has at least one element, we put the first element of `T` into `C` and the rest of `T` into `U`. Next, we calculate the sum of `B` and `C` and put it in `S`. Then we do a recursive call with the list `[S,A|U]`: the sum `S`, followed by the first element `A`, followed by all the elements in `U`. The result of that recursive call is put in `R`.

```
; T=R

```

If `T` is empty, the unification `T=[C|U]` fails, and we fall back to the base case: `R` is the empty list (i.e. `T`).
> 6 votes

# Answer
# convey, 55 bytes

```
 3!<
v<#/`:<
?:"  \&
v?~`"#:}
>#>>,^^
 ?v v^-1
 >+>,,\{

```

Try it online!

Lower right part is letting `length(input) - 1` elements to the output. Top right part buffers the input for too long inputs, as the row would otherwise attach to itself. Top left we get a `3` for each iteration: this splits off the first three elements and lets the head wait for 3 extra steps before copying it into the output and then rejoining with the main row. Because the head blocks the tile while waiting, the other 2 elements go into the `+` before joining the row again.
> 6 votes

# Answer
# Vyxal, 8 bytes

```
÷^!‹(…∇+

```

Try it Online!

Woo using a stack based language to solve a stack based problem. Outputs each item on a newline. 11 bytes to output as list: `÷^!‹(:⅛∇+)¾`

Also, look ma, no letters (and flags)! Funnily enough, I don't think there's any flag combination that would get this under 8 bytes.

## Explained

```
÷^!‹(…∇+
÷        # Push every item of the input onto the stack
 ^       # and reverse the stack to make the list indicative of the stack (Ṙ÷ achieves the same thing, but we're going 100% symbolic)
  !‹     # Push len(stack) - 1
    (    # and that many times:
     …   #    print the top of the stack without popping
      ∇  #    perform rot. Fun fact: I added rot to vyxal after seeing forth/factor as LoTM
       + #    add the top two items

```
> 4 votes

# Answer
# Python 3, ~~61~~ ~~58~~ 57 bytes

```
lambda a:[a[~i%2]+sum(a[i:1:-2])for i in range(1,len(a))]

```

Try it online!

-3 bytes thanks to @MarcMush

-1 byte thanks to @ovs, by shifting the range by 1

a is the original sequence and b is the -rot transform (both 0-based):

b is define like this :

`n` is even : `b(n) = a(0) + (sum of all odd terms from a(3) to a(n+1))`

`n` is odd : `b(n) = a(1) + (sum of all even terms from a(2) to a(n+1))`
> 4 votes

# Answer
# JavaScript, 42 bytes

Saved 4 bytes prior to posting by following DLosc's lead and taking the input integers as individual arguments rather than as a single array.

```
f=(x,y,z,...a)=>[x,...1/z?f(y+z,x,...a):a]

```

Try it online!

Or, if outputting a comma delimited string with a trailing comma is allowed then:

# JavaScript, 40 bytes

```
f=(x,y,z,...a)=>x+[,1/z?f(y+z,x,...a):a]

```

Try it online!
> 4 votes

# Answer
## Perl 5, ~~57~~ 56 + 4 (`-apl` options) = 60 bytes

```
$F[$_-1]+=$F[$_],$F[$_]=$F[$_-2]for 2..$#F;pop@F;$_="@F"

```

Try it online!
> 4 votes

# Answer
# C (clang), ~~44~~ 39 bytes

```
f(*a,l){for(;--l;a[1]=*a++)a[1]+=a[2];}

```

Try it online!

Saved 5 bytes thanks to AZTECCO!!!

Inputs a pointer to a finite sequence of integers and its length (since pointers in C carry no length info), and computes its -rot transform in place.
> 4 votes

# Answer
# Retina 0.8.2, 40 bytes

```
\d+
$*
+1`(1*),(1*,)(1*)
$1¶$3$2$1
%`\G1

```

Try it online! Link includes footer that spaces the results out. Takes input as a comma-separated list of non-negative integers due to limitations of unary, and outputs a newline-separated list (+4 bytes for newline-separated input or +5 bytes for comma-separated output). Explanation:

```
\d+
$*

```

Convert to unary.

```
+1`(1*),(1*,)(1*)
$1¶$3$2$1

```

Make a copy of the first number, then rotate it below the sum of the third and second numbers. Repeat until there are only two numbers left.

```
%`\G1

```

Convert the first number on each line to decimal. This outputs the initial first number and all of the copied sums, but avoids duplicating the penultimate sum.
> 3 votes

# Answer
# tinylisp, 75 bytes

```
(d F(q((S)(c(h S)(i(t(t S))(F(c(a(h(t S))(h(t(t S))))(c(h S)(t(t(t S))))))(

```

Defines a function `F` that takes a list and returns a list. Try it online!

### Explanation

Pretty straightforward, once you fight your way through all the parentheses:

```
(d F                      ; Define F
 (q                       ; to be a list representing a function
  ((S)                    ; that takes one argument, S:
   (c                     ;  Cons
    (h S)                 ;  the first element of S to the following list:
    (i (t (t S))          ;   If the tail of tail of S is not empty:
     (F                   ;    Call F recursively, with an argument of
      (c                  ;    cons...
       (a                 ;     the result of adding
        (h (t S))         ;     the second element of S and
        (h (t (t S))))    ;     the third element of S
       (c                 ;    ... to the cons of...
        (h S)             ;     the first element of S and
        (t (t (t S))))))  ;     S without its first three elements
     ()                   ;   Else, empty list

```

---

The same thing (but snazzier and less golfy) is **92 bytes** in tinylisp's descendant language Appleseed:

```
(def F(q((S)(cons(head S)(if(ttail S)(F(cons(sum(take 2(tail S)))(cons(head S)(drop 3 S))))(

```

Try it online!
> 3 votes

# Answer
# Ruby, ~~47 38~~ 34 bytes

```
->a,b,*l{l.map{|x|a,b=b+x,a;b}<<a}

```

Try it online!

Variadic function accepting at least 2 parameters.
> 3 votes

# Answer
# Haskell, 34 bytes

```
f(a:b:c:d)=a:f(b+c:a:d);f(a:_)=[a]

```

Try it online!

This takes the straight forward approach. All the other fancy approaches just don't really end up saving any bytes in Haskell.
> 3 votes

# Answer
# jq, 53 bytes

```
[while(.[1];.[1]+=.[2]|(.[2]//.[0])=.[0]|.[1:])|.[0]]

```

Try it online!

**Explanation:**

```
Based on example input: [1, 2, 3]

[
    while(                  While
        .[1]                the array has at least two items
    ;
        .[1]+=.[2]          add the second and third number and store them on second position.
        |(.[2]//.[0])       Choose third element if it is not null else first element
            =.[0]           and set its value to the value of the first number.
        |.[1:]              Drop the first element.
    )
    |                       Now we have the evolution of the updated array, e.g. [[1,2,3],[5,1]]
    .[0]                    take the first element of each array
]                           [1,5]

```
> 3 votes

# Answer
# APL (Dyalog Classic), 50 bytes

```
{⎕←1↑⍵⋄({(3↓⍵),⍨(+/2↑1⌽3↑⍵),1↑⍵}⍣{⎕←1↑⍺⋄(⍴⍺)<3})⍵}

```

Try it online!

Explanation:

```
(+/2↑1⌽3↑⍵),1↑⍵ take the first three elements, rotate them, sum the first two and stick the third (which was originally the first element) on the end again so (a b c) -> (b c a) -> (b+c a)
(3↓⍵),⍨ concatenate this with the rest of the list
⍣{⎕←1↑⍺⋄(⍴⍺)<3} the above gets run until the list is less than 3 elements

```

Note: locally this seems to iterate one more time, but in tio.run it does not, unsure why. This is my first code golf attempt so certainly a lot to be improved on! Happy to hear from APL experienced users how this could be better, I dont like my use of ⎕ in this solution
> 3 votes

# Answer
# Jelly, 16 bytes

```
ḣ2S;ɗḢṄ$ḷ"ƊḊḊ$¿Ḣ

```

Try it online!

Blegh. Full program, outputs each on a separate line

## How it works

```
ḣ2S;ɗḢṄ$ḷ"ƊḊḊ$¿Ḣ - Main link. Takes a list L on the left
              ¿  - While:
             $   -   Condition:
           ḊḊ    -     The list is non-empty after dequeuing twice
          Ɗ      -   Body:
       $        -     Last 2 links as a monad f(L):
     Ḣ          -       First element, X
      Ṅ         -       Print and return
    ɗ           -     Last 3 links as a dyad f(L[1:], X):
ḣ2              -       First 2 elements
  S             -       Sum
   ;            -       Concat with X
        ḷ"      -     Replace the first 2 elements of L with this pair
              Ḣ - Get the first element of the final pair

```
> 2 votes

# Answer
# Charcoal, ~~31~~ ~~25~~ 22 bytes

```
≔ΦＥθΣ…θ⊕κ⊖κθＩＥθ↨…θ⊕κ±¹

```

Try it online! Link is to verbose version of code. Explanation: Now a port of @Lynn's Jelly answer.

```
≔ΦＥθΣ…θ⊕κ⊖κθ

```

Calculate the cumulative sums of the input, i.e. the sums of all of its nontrivial prefixes, but then remove the second sum.

```
ＩＥθ↨…θ⊕κ±¹

```

Calculate their cumulative differences, which is done by interpreting their nontrivial prefixes in base `-1`.
> 2 votes

# Answer
# Keg, 16 bytes

```
÷^(!;|④
,&""&''+

```

Try it online!

## Explained

```
÷^     # Push all items of the input onto the stack and reverse the stack
(!;|   # len(stack) - 1 times:
④      #     print the top of the stack without popping
,      #     and print a newline too
&""&'' #     perform rot
+      #     and add the top two items

```
> 2 votes

# Answer
# Julia 1.0, 37 bytes

```
a\b=a
\(a,b,c,r...)=[a;\(b+c,a,r...)]

```

Inspired by DLosc's answer

the numbers are taken as separate arguments, and Julia's multiple dispatch makes it really easy to separate between 2 arguments (first method) and 3 or more arguments (second method)

Try it online!
> 2 votes

# Answer
# Scala, 66 bytes

```
s=>Seq.iterate(s,s.size-1)(s=>s(1)+s(2)::s(0)::s.drop(3))map(_(0))

```

Try it in Scastie!
> 2 votes

# Answer
# Japt, 8 bytes

```
å+
j1
ån

```

Try it
> 2 votes

# Answer
# BQN, 9 bytesSBCS

```
-˜`⊑∾2↓+`

```

Try it here.

Based on Lynn's solution.

```
-˜`⊑∾2↓+`
     2↓+` # drop 2 elements from the plus scan
    ∾     # joined to
   ⊑      # first element of input
-˜`       # swapped subtraction scan

```
> 2 votes

# Answer
# C++14 (or newer), 81 bytes

```
[](auto&v){for(int i=1,t;++i<v.size();v[i]=t)t=v[i-2],v[i-1]+=v[i];v.pop_back();}

```

A lambda function that modifies the passed `std::vector` by reference.

Tests: https://coliru.stacked-crooked.com/a/759a69be8a6398f1
> 1 votes

# Answer
# Python 2, 65 bytes

```
l=input();print l[0]
while l[2:]:k=l[1]+l[2];print k;l[:3]=k,l[0]

```

Try it online!

-17 thanks to @ovs -3 from me on ovs improvement
> 1 votes

# Answer
# Perl 5, 54 bytes

```
sub f{my($a,$b,$c,@r)=@_;($a,@r?f($b+$c,$a,@r):$b+$c)}

```

Try it online!
> 1 votes

# Answer
# , 16 bytes

```
1{1-/\.&.|.\.+/\

```

Try it online!

Translated from Lynn’s Jelly solution
> 1 votes

# Answer
# Zsh, ~~72~~ 50 bytes

```
for _ ({2..$#}){printf $1\ ;2=$[$3+$2];3=$1;shift}

```

Used shell parameters instead of variables, saved 22 bytes!

try it online! ~~72 bytes~~
> 1 votes

# Answer
# 05AB1E, 10 bytes

```
R`[=.g<#Š+

```

Try it online or verify all test cases.

A port of *@Lynn*'s top Jelly answer is **10 bytes** as well:

```
ηO¯1ǝ˜Å»s-

```

Try it online or verify all test cases.

**Explanation:**

```
R           # Reverse the (implicit) input-list
 `          # Pop and dump all items separated to the stack
  [         # Start an infinite loop:
   =        #  Print the top item with trailing newline (without popping)
    .g      #  Get the amount of items on the stack
      <     #  If this is 2:
       #    #   Stop the infinite loop
    Š       #  Triple swap the top three items (a,b,c to c,a,b)
     +      #  Add the top two items together

η           # Get the prefixes of the (implicit) input-list
 O          # Sum each inner prefix together
            # Remove the second item by:
  ¯1ǝ       #  Replacing the second item (at index 1) with an empty list
     ˜      #  And then flatten the list of lists
      Å»    # Cumulative left-reduce the list by:
        s   #  Swapping the two items
         -  #  And subtracting them from one another
            # (after which the list is output implicitly as result)

```
> 1 votes

# Answer
# Whitespace, 58 bytes (12 bytes in Binary Whitespace)

```
LSSTLSLSTLSTSSLSLTTTSLSSLTSSSSLSTLSTSSLTTTSLTSSLSLTTTSLSLL

```

where S is space (ASCII 32), T is tab (ASCII 9), and L is line feed (ASCII 10).

Whitespace is a stack-based language, which would seem ideal for this challenge, however it provides very limited stack instructions—none of which can modify the stack below the top two elements. The heap can be used as scratch space though. For this challenge, only one heap address is needed, which we'll call the accumulator `acc` in the pseudocode.

The program ends once the stack underflows. Label `1` is not necessary, but it makes the program a callable procedure to follow Code Golf rules.

Formatted as readable Whitespace Assembly:

```
1:                  # LSSTL
    dup printi      # SLS TLST
    0 swap store    # SSL SLT TTS
_:                  # LSSL
    + dup printi    # TSSS SLS TLST
    0 retrieve swap # SSL TTT SLT
    0 swap store    # SSL SLT TTS
    jmp _           # LSLL

```

Notes on syntax:

* `_` represents a label with no digits. It is unique from label `0`.
* A raw digit literal represents a `push` instruction.

Pseudocode:

```
func f(stack) {
  print(stack.top())
  var acc = stack.pop()  # heap address 0
  loop {
    var x = stack.pop() + stack.pop()
    print(x)
    acc, x = x, acc
    stack.push(x)
  }
}

```

## Binary Whitespace, 12 bytes

Whitespace has a trinary alphabet (space, tab, LF), but it can be represented with a binary alphabet with a simple mapping. Space becomes `0`, tab becomes `10`, and LF becomes `11`. All trailing zeros on the last byte are ignored. If the final character ends with `0` (i.e. space or tab), then append a `1` to the bit stream. This encoding is implemented by Nebula.

If other code golf languages can pick arbitrary encodings, then this should be fair :).

```
11000110 11010110 10001101 11010100
11001110 00001101 01101000 11101010
01110001 10111010 10011011 11000000

```

## Running

These are the five provided test cases. Run the program with one of these prefixed. Digits are outputted without delimiters to save bytes.

1. `SSSTTL SSSTSL SSSTL LSTTL`
2. `SSTTL SSSTL SSTTL SSSTL SSTTL SSSTL SSTTL SSSTL LSTTL`
3. `SSSTSSTL SSSTSSSL SSSTTTL SSSTTSL SSSTSTL SSSTSSL SSSTTL SSSTSL SSSTL LSTTL`
4. `SSSTSSSSSSSL SSSTSSSSSSL SSSTSSSSSL SSSTSSSSL SSSTSSSL SSSTSSL SSSTSL SSSTL LSTTL`
5. `SSSTL SSL SSTTL SSL SSSTL SSL SSTTL SSL SSSTL LSTTL`

```
3 2 1                call 1  # => 15
-1 1 -1 1 -1 1 -1 1  call 1  # => 1001-12-2
9 8 7 6 5 4 3 2 1    call 1  # => 1551011171926
128 64 32 16 8 4 2 1 call 1  # => 169224186169
1 0 -1 0 1 0 -1 0 1  call 1  # => 1-1101-110

```

The interpreter must allow empty labels and argument literals. The reference interpreter wspace (and thus TIO) does not support this; Nebula and Whitelips do.
> 1 votes

# Answer
# APL (Dyalog Unicode), 18 bytes

```
{|-\(+\⍵)[2~⍨⍳⍴⍵]}

```

Try it online!

```
{|-\(+\⍵)[2~⍨⍳⍴⍵]}        ⍝ Monadic function, Takes arg ⍵ on left
    (+\⍵)                 ⍝ Cumulative sum (fold by add) of ⍵
         [2~     ]        ⍝ Takes indices which are not 2 on
             ⍳⍴⍵          ⍝ Range to length of ⍵
            ⍨             ⍝ Swap 2 with range and pass to filter
  -\                      ⍝ Deltas (fold by minus)
 |                        ⍝ Absolute values

```
> 0 votes

---
Tags: code-golf, sequence, array, integer
---


title: So is that maximum?

text:
# Question
Title: So is that maximum?
Given a map from arrays of integers of same size to single integers, determine if there is a set of indices such that the output is equal to the maximum of the elements at those indices for every corresponding pair.

You can take the input as a map if your language support, arrays of pairs, separated 2D array of input and its output, or other reasonable format. Shortest code wins.

## Test cases

```
input => output
input => output  ->  truthy/falsey

[1,2,3] => 2
[2,1,3] => 2
[3,2,1] => 3 -> true (maximum of pos 1 and pos 2)

[1,2,3] => 2
[2,3,1] => 2
[3,3,2] => 2 -> false (Whatever positions chosen, 3 must at least appeared in output)

[1,2,3] => 2 -> true (maximum of pos 2, or maximum of pos 1 and 2)

[1,2,3] => 0 -> false (no way maximum of some of 1, 2 and 3 result in 0)

```

# Answer
# Jelly, 9 bytes

```
ZŒPZ€Ṁ€€i

```

Try it online!

Outputs `0` for falsey, non-zero for truthy

-3 bytes thanks to hyper-neutrino!

## How it works

```
ZŒPZ€Ṁ€€i - Main link. Takes a list of inputs I on the left and outputs O on the right
Z         - Transpose I
 ŒP       - Powerset of the columns
   Z€     - Transpose each
       €  - Over each column powerset:
     Ṁ€   -   Get the maximum of each column
        i - Index of O in this list of lists, or 0 if not found

```
> 4 votes

# Answer
# JavaScript (ES6), 70 bytes

Returns `false` for valid, or `true` for invalid.

```
a=>a.some(b=([a,m])=>a.every((v,i)=>v-m|b[i],a.map((v,i)=>b[i]|=v>m)))

```

Try it online!
> 1 votes

# Answer
# Wolfram Language (Mathematica), 28 bytes

```
Times@@Max/@(Sign[#-#2])&

```

Try it online!

Input `[inputs, outputs]`. Returns `0` for truthy, and nonzero (`1` or `-1`) otherwise.

```
             Sign[#-#2]     categorize indices for each i/o (-1 <, 0 =, 1 >)
       Max/@(          )   take max for each index across i/o s
Times@@                     0 present (solutions exist)?

```
> 1 votes

# Answer
# 05AB1E, 7 bytes

```
øæʒø€àQ

```

Port of *@cairdCoinheringaahing*'s Jelly answer, so make sure to upvote him!

Outputs an empty list `[]` as falsey, and a non-empty list (containing one or multiple matrices of integers) as truthy.

Try it online or verify all test cases.

**Explanation:**

```
ø        # Zip/transpose the (implicit) first input-matrix, swapping rows/columns
 æ       # Get the powerset of these columns
  ʒ      # Filter this list of matrices by:
   ø     #  Zip/transpose the current matrix, swapping rows/columns
    €    #  For each inner list:
     à   #   Pop and leave the maximum
      Q  #  Check if this list is equal to the (implicit) second input-list
         # (after which the filtered list of matrices is output implicitly as result)

```
> 1 votes

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


title: Setting up Al's R session

text:
# Question
Title: Setting up Al's R session
Al wanted to use my computer to do some simple calculations, so I lent him the use of my R terminal for a bit. He complained though, saying it wasn't set up how he liked it. I said "No problem Al, set it up how you like and I'll just revert it later." This suited Al, and I left him to it. Al isn't a big fan of online R implementations like TIO, they don't seem to support his preferred way of coding.

After a few minutes, I came back and asked how it went. "everything fine", he said. I glanced at his session and it didn't look fine to me — only one of the four results looked correct! But Al knows R inside out, he must have been telling the truth.

Here is a transcript of Al's R session, as it appeared on the screen (Al uses RStudio 1.1.463 and R 3.6.3 if it matters, but I don't think it does here). The question is, how did Al "set up" his session to produce this output?

```
## what did Al type here?
32+55
[1] 87
14*21
[1] 294
91/7
[1] 13
12-21
[1] -9

```

rules:

* Al only typed one function call which is somewhere in the standard R libraries.
* the function didn't import any code or refer to any external files (no `source`, `install.packages`, `library` etc..).
* Al didn't type `cat("55+23\n[1]......-9")`, it is something that could reasonably be interpreted as "setting up an R session"

scoring:

* the primary scoring criterion is the number of bytes in the answer. Ties will be broken in ASCII-order, that is, if two valid answers are the same length the winner is the one which is first "alphabetically" (according to ASCII ordering).

# Answer
```
options(prompt="\U202E")

```

Uses RTL Override at the end to make all following input appear reversed. I tried entering the raw character in a string but it turns into a period for some reason. Tested with RStudio 1.2.1335 and R 3.6.3 on Ubuntu 20.04, but does not work in my terminal GNOME Terminal 3.36.2 which appears to do some kind of character stripping unless the character is printable. Note that default R prompt is "\> " which works in GNOME Terminal and can be replicated to make it less suspicious.

Also Al and R sound like "L" and "R".
> 8 votes

# Answer
# , 28 bytes

```
Sys.setlocale("LC_ALL","ja")

```

Try it online! (doesn't work)

I give it a try even if I don't know R and cannot test it on my computer.. If this doesn't work, please tell me and I will delete the answer, because it spoils the trick Al used
> 2 votes

---
Tags: code-golf, programming-puzzle, r
---


# Question
Title: Bijection between \$ \mathbb N \$ and at-most-\$n\$-ary trees
## Background

Related: a golflang theory I posted in TNB a while ago

**At-most-\\$n\\$-ary trees** are rooted trees where each internal node has between 1 and \\$n\\$ children (inclusive). Two trees are considered identical only if the shapes exactly match without re-ordering each node's children. In other words, the left-to-right order of children matters.

For example, the following is an example of an at-most-ternary tree (each node is marked with its out-degree, the leaves being zeros):

```
    2
   / \
  1   2
  |  / \
  3  0 1
 /|\   |
0 0 0  0

```

Related OEIS sequences: A006318 is the number of at-most-binary trees having \\$n\\$ internal nodes, and A107708 is for at-most-ternary trees.

Note that a single-node tree is a valid at-most-\\$n\\$-ary tree for any value of \\$n\\$, since it has no internal nodes.

## Challenge

Write a function or program that, given a positive integer \\$n\\$ (1st input), maps a natural number (2nd input) to a unique at-most-\\$n\\$-ary tree. It must be a bijection; every tree must have a unique natural number that maps to the tree. Only the code going from a number to a tree is considered for scoring, but it is recommended to provide the opposite side to demonstrate that it is indeed a bijection.

The output format for the tree is flexible (nested arrays, string/flat array representations including parentheses or prefix notation). You can also choose the "natural number" to start at 0 or 1.

Standard rules apply. The shortest code in bytes wins.

# Answer
# Python 3, 107 bytes

```
def f(n,x):
 def g(m):r=y[0]%m;y[0]//=m;return[g(n+1)for i in y*r]
 y=[x-1];return x and g(n)+[f(n,*y)]or[]

```

Try it online!

Naturals start at 0. Inverse map:

```
def g(n,t):
 x=0;y=1;q=t,
 while q:*q,u=q;x+=len(u)*y;y*=n+bool(q);q+=u[::-1]
 return x

```

Try it online!
> 8 votes

# Answer
# Jelly, 32 bytes

```
⁴‘ßƊḢd¥ɼṪ$Ð¡Ḋ
¹©ṛ’ɼ⁴çƊḢɼÐ¿ḊṚṭƒ“”

```

Try it online!

A dyadic link taking \\$n\\$ as the right argument and a natural number as the left argument and returning a nested list.

This uses the same algorithm as @AndersKaseorg’s Python answer (so be sure to vote that one up too!). However, despite Jelly’s Python base, this was not trivial to translate. The main function was changed from using recursion to a while loop followed by a `reduce`, but a recursive method was preserved for the subsidiary function (`g()` in the Python code).

Full explanation to follow.
> 5 votes

# Answer
# Python 3, 83 bytes

```
f=lambda n,x:[f(n,int(str(~-x//n)[~i::~(x%n)][::-1]or 0))for i in range(x%n+(x>0))]

```

Try it online!

0 yields the trivial tree with only one node. Other numbers are broken down into \\$ 1 \le k \le n\\$ and \\$ x' \ge 0\\$ using modulo; \\$ k\\$ is used as the number of children of the root, and the decimal digits of \\$ x' \\$ are distributed among those children by taking every \\$ k \textrm{th} \\$ digit starting from different low places, recursively applying the same procedure for each child.

Inverse:

```
import itertools
def invf(n, l):
    assert type(n) == int and n > 0 and type(l) == list and len(l) <= n
    return 0 if not l else int(''.join(''.join(t) for t in itertools.zip_longest(*[str(invf(n, m))[::-1] for m in l], fillvalue='0'))[::-1]) * n + (len(l) - 1 or n)

```

Try it online!
> 3 votes

---
Tags: code-golf, math, open-ended-function
---


title: Create a sudoku solution CHECKER

text:
# Question
Title: Create a sudoku solution CHECKER
# Create a Sudoku solution CHECKER

There are oodles of Sudoku SOLVERS here, but I want you to create a solution CHECKER as small as humanly possible (code-golf).

* A valid entry will be able to either take a 9x9 array as an argument (passed by reference, serialized on the command line, or however you want to take it) or accept an input file that is nine lines of nine numbers for the final grid. See examples of input below.
* Valid input should be base-10 numbers (1-9)
* Missing, empty, extra, non-numeric positions, or positions with numbers outside of 1-9 should be rejected as invalid input by returning a non-zero result, printing an error, or both.
* Your program needs to test whether each number appears once per column, once per line, and once per 3x3 sub-grid. If it passes, return "0" and if not, return a non-zero result.
* Use of external resources (websites, etc.) is to be avoided.
* If your solution is a stand-alone program, exiting with a exit status of, or printing, "0" or non-zero for "Pass" or "Fail", respectively, is ok.

Let the smallest answer win!

# Input Examples:

c array:

```
int input[9][9]={{1,2,3,4,5,6,7,8,9},
                 {4,5,6,7,8,9,1,2,3},
                 {7,8,9,1,2,3,4,5,6},
                 {2,3,1,5,6,4,8,9,7},
                 {5,6,4,8,9,7,2,3,1},
                 {8,9,7,2,3,1,5,6,4},
                 {3,1,2,6,4,5,9,7,8},
                 {6,4,5,9,7,8,3,1,2},
                 {9,7,8,3,1,2,6,4,5}
                };

```

file:

```
123456789
456789123
789123456
231564897
564897231
897231564
312645978
645978312
978312645

```

The 9 sub-grids:

```
+---+---+---+
|123|456|789|
|456|789|123|
|789|123|456|
+---+---+---+
|231|564|897|
|564|897|231|
|897|231|564|
+---+---+---+
|312|645|978|
|645|978|312|
|978|312|645|
+---+---+---+

```

# Answer
### GolfScript, 39 characters

```
.zip.{3/}%zip{~}%3/{[]*}%++{$10,1>=!},,

```

It takes an array of arrays as input (see online example) and outputs `0` if it is a valid grid.

*Short explanation of the code*

```
.zip         # Copy the input array and transpose it
.{3/}%       # Split each line into 3 blocks
zip{~}%      # Transpose these blocks
3/{[]*}%     # Do the same for the lines themselves and join again
++           # Make one large list of 27 9-element arrays
             # (9 for rows, 9 for columns, 9 for blocks)
{$10,1>=!},  # From those 27 select the ones which are not a permutation of [1 2 3 ... 9]
             #   $      -> sort
             #   10,1>  -> [1 2 3 ... 9]
             #   =!     -> not equal
,            # Count after filtering

```
> 6 votes

# Answer
## Python, 103

I hate sudoku.

```
b = [[1,2,3,4,5,6,7,8,9],
     [4,5,6,7,8,9,1,2,3],
     [7,8,9,1,2,3,4,5,6],
     [2,3,1,5,6,4,8,9,7],
     [5,6,4,8,9,7,2,3,1],
     [8,9,7,2,3,1,5,6,4],
     [3,1,2,6,4,5,9,7,8],
     [6,4,5,9,7,8,3,1,2],
     [9,7,8,3,1,2,6,4,5]]

e=enumerate;print 243-len(set((a,t)for(i,r)in e(b)for(j,t)in e(r)for a in e([i,j,i/3*3+j/3]*(0<t<10))))

```

How it works: each row, column, and block must have each number from 1 to 9. So for each `0 <= i, j < 9`, the cell `i,j` is in block `3*floor(i/3) + floor(j/3)`. Thus, there are 243 requirements to satisfy. I make each requirement a tuple `((item index,item type number),symbol)` where `item index` is a number between 0 and 8 (inclusive), `item type number` is 0,1, or 2 to denote row, column or block respectively, and `symbol` is the entry `b[i][j]`.

Edit: I mistakenly didn't check for valid entries. Now I do.
> 11 votes

# Answer
## APL (46)

```
{∧/,↑∊∘Z¨(/∘(,⍵)¨↓Z∘.=,3/3⌿3 3⍴Z←⍳9),(↓⍵),↓⍉⍵}

```

This takes a 9-by-9 matrix. The example one can be entered on TryAPL like so:

```
     sudoku ← ↑(1 2 3 4 5 6 7 8 9)(4 5 6 7 8 9 1 2 3)(7 8 9 1 2 3 4 5 6)(2 3 1 5 6 4 8 9 7)(5 6 4 8 9 7 2 3 1)(8 9 7 2 3 1 5 6 4)(3 1 2 6 4 5 9 7 8)(6 4 5 9 7 8 3 1 2)(9 7 8 3 1 2 6 4 5)
     {∧/,↑∊∘Z¨(/∘(,⍵)¨↓Z∘.=,3/3⌿3 3⍴Z←⍳9),(↓⍵),↓⍉⍵} sudoku
1

```

Explanation:

* `↓⍉⍵`: get the columns of ,
* `↓⍵`: get the rows of ,
* `3/3⌿3 3⍴Z←⍳9`: make a 3-by-3 matrix containing the numbers `1` to `9`, then triplicate each number in both directions, giving a 9-by-9 matrix with the numbers `1` to `9` indicating each group,
* `Z∘.=`: for each number `1` to `9`, make a bitmask for the given group,
* `/∘(,⍵)¨`: and mask  with each, giving the groups of .
* `∊∘Z¨`: for each sub-array, see if it contains the numbers `1` to `9`,
* `∧/,↑`: take the logical `and` of all of these numbers together.
> 9 votes

# Answer
## Java/C# - 183/180 181/178 173/170 bytes

```
boolean s(int[][]a){int x=0,y,j;int[]u=new int[27];for(;x<(y=9);x++)while(y>0){j=1<<a[x][--y];u[x]|=j;u[y+9]|=j;u[x/3+y/3*3+18]|=j;}for(x=0;x<27;)y+=u[x++];return y==27603;}

```

(Change `boolean` to `bool` for C#)

Formatted:

```
boolean s(int[][] a){
    int x=0, y, j;
    int[] u=new int[27];
    for(;x<(y=9);x++)
        while(y>0){
            j=1<<a[x][--y];
            u[x]|=j;
            u[y+9]|=j;
            u[x/3+y/3*3+18]|=j;
        }

    for(x=0;x<27;)
        y+=u[x++];

    return y==27603;
}

```

The method creates an array `u` with 27 bitmasks, representing the digits found in the nine rows, columns and squares.

It then iterates over all cells, performing the operation `1 << a[x][y]` to create a bitmask representing the digit and ORs its column, row and square bitmask with it.

It then iterates over all 27 bitmasks, ensuring that they all add up to 27594 (1022\*9, 1022 being the bitmask for all digits 1-9 being present). (Note that `y` ends up as 27603 due to it already containing 9 following the double loop.)

Edit: Accidentally left in a `%3` that's no longer necessary.

Edit 2: Inspired by Bryce Wagner's comment, the code has been compressed a bit more.
> 5 votes

# Answer
# python = 196

Not the most golfed, but the idea is there. Sets are pretty useful.

Board:

```
b = [[1,2,3,4,5,6,7,8,9],
     [4,5,6,7,8,9,1,2,3],
     [7,8,9,1,2,3,4,5,6],
     [2,3,1,5,6,4,8,9,7],
     [5,6,4,8,9,7,2,3,1],
     [8,9,7,2,3,1,5,6,4],
     [3,1,2,6,4,5,9,7,8],
     [6,4,5,9,7,8,3,1,2],
     [9,7,8,3,1,2,6,4,5]]

```

Program:

```
n={1,2,3,4,5,6,7,8,9};z=0
for r in b:
 if set(r)!=n:z=1
for i in zip(*b):
 if set(i)!=n:z=1
for i in (0,3,6):
 for j in (0,3,6):
  k=j+3
  if set(b[i][j:k]+b[i+1][j:k]+b[i+2][j:k])!=n:z=1
print(z)

```
> 3 votes

# Answer
# Java - 385 306 328 260 characters

**Edit:** I foolishly misread the instructions that the answer *had* to be a complete program. Since it can be just a valid function, I've rewritten and minimized to be a function, and rewritten my solution introduction with that in mind.

So, as a challenge to myself I thought I'd try to make the smallest Java solution checker.

To achieve this I assume that the sudoku puzzle will be passed in as a java multidimensional array, like so:

```
s(new int[][] {
    {1,2,3,4,5,6,7,8,9},
    {4,5,6,7,8,9,1,2,3},
    {7,8,9,1,2,3,4,5,6},
    {2,3,1,5,6,4,8,9,7},
    {5,6,4,8,9,7,2,3,1},
    {8,9,7,2,3,1,5,6,4},
    {3,1,2,6,4,5,9,7,8},
    {6,4,5,9,7,8,3,1,2},
    {9,7,8,3,1,2,6,4,5}});

```

Then, we have the actual solver, which returns "0" if valid solution, "1" if not.

Fully golfed:

```
int s(int[][] s){int i=0,j,k=1;long[] f=new long[9];long r=0L,c=r,g=r,z=45L,q=r;for(f[0]=1L;k<9;){f[k]=f[k-1]*49;z+=f[k++]*45;}for(;i<9;i++){for(j=0;j<9;){k=s[i][j];r+=k*f[i];c+=k*f[j];g+=k*f[j++/3+3*(i/3)];q+=5*f[k-1];}}return (r==z&&c==z&&g==z&&q==z)?0:1;}

```

Readable:

```
    int s(int[][] s) {
        int i=0,j,k=1;
        long[] f=new long[9];
        long r=0L,c=r,g=r,z=45L,q=r;
        for(f[0]=1L;k<9;){f[k]=f[k-1]*49;z+=f[k++]*45;}
        for(;i<9;i++) {
            for (j=0;j<9;) {
                k=s[i][j];
                r+=k*f[i];
                c+=k*f[j];
                g+=k*f[j++/3+3*(i/3)];
                q+=5*f[k-1];
            }
        }
        return (r==z&&c==z&&g==z&&q==z)?0:1;
    }

```

So how does this work? I basically just create my own number base with sufficient resolution in each digit that I only have to do three numeric comparisons after passing through the puzzle once to know if it's valid. I chose base 49 for this problem, but any base larger than 45 would be sufficient.

A (hopefully) clear example: imagine that every "row" in the sudoku puzzle is a single digit in a base-49 number. We'll represent each digit in the base-49 number as a base-10 number in a vector for simplicity. So, if all rows are "correct" we expect the following base-49 number (as a base-10 vector):

```
(45,45,45,45,45,45,45,45,45)

```

or converted to a single base-10 number: `1526637748041045`

Follow similar logic for all the columns, and same for the "sub-grids". Any value encountered in the final analysis that doesn't equal this "ideal number" means the puzzle solution is invalid.

Edit to solve all-5s vulnerability and other related issues: I add a fourth base-49 number, based on the idea that there should be 9 of each number in every puzzle. So, I add 5 to each digit in the base-49 number for each occurrence of the base-10 number that represents the digit's index. An example, if there are 10 9's and 9 8's, 9 7's, 8 6's, and 9 of all others, you'd get a base-49 number (as a base-10 vector of size 10 to deal with overflow):

```
(1, 1, 45, 45, 40, 45, 45, 45, 45, 45)

```

Which will fail when compared against our "ideal" base-49 number.

My solution takes advantage of this mathematical solution, to avoid as much as possible looping and comparison. I simply use a `long` value to store each base-49 number as a base-10 number and use a lookup array to get the "factors" for each base-49 digit during column/row/subgrid check value computation.

As Java isn't designed to be concise, being careful in the mathematical construction was the only way I figured I could construct a concise checker.

Let me know what you think.
> 3 votes

# Answer
## R 145

```
function(x)colSums(do.call(rbind,lapply(list(R<-row(b<-matrix(1,9,9)),C<-col(b),(R-1)%/%3+1+3*(C-1)%/%3),sapply,`==`,1:9))%*%c(2^(x-1))==511)==27

```

The de-golfed code (more or less) can be found here https://stackoverflow.com/a/21691541/1201032.
> 3 votes

# Answer
## J 52 54

```
-.*/,(9=#)@~.@,"2(0 3 16 A.i.4)&|:(4#3)($,)".;._2]0 :0

```

Takes it's argument pasted on the command line, ended with a ) as:

```
1 2 3 4 5 6 7 8 9
4 5 6 7 8 9 1 2 3
7 8 9 1 2 3 4 5 6
2 3 1 5 6 4 8 9 7
5 6 4 8 9 7 2 3 1
8 9 7 2 3 1 5 6 4
3 1 2 6 4 5 9 7 8
6 4 5 9 7 8 3 1 2
9 7 8 3 1 2 6 4 5
)

```

Returns 1 if passed, 0 if not.

Internally, it converts the 9x9 grid to a 3x3x3x3 grid, and does some permutations on the axes to get the wanted unit (rows, lines and boxes) in the last 2 dimensions.

After doing that, it is checked that each unit has has 9 unique values.

Probably far from perfect, but beats the majority already ;-)
> 3 votes

# Answer
# Javascript ES6, 150 chars

Takes input as a 81-char string without any delimeters.

```
s=>s.match("^(?=(#.{0,8}#.{9})+$)(?=(#(.{9}){0,8}#.){9})((#.?.?(.{9}){0,2}#...){3}.{18})+$".replace(/#(.*?)#/g,"123456789".replace(/./g,"(?=$$1$&)")))

```

Function returns `null` as negative answer and an array with original string in first element as a positive one. Can change to bool by adding `!!` to the function begining.

Test (see related challenge for more detais):

```
f=s=>s.match("^(?=(#.{0,8}#.{9})+$)(?=(#(.{9}){0,8}#.){9})((#.?.?(.{9}){0,2}#...){3}.{18})+$".replace(/#(.*?)#/g,"123456789".replace(/./g,"(?=$$1$&)")))
;`123456789456789123789123456231564897564897231897231564312645978645978312978312645
725893461841657392396142758473516829168429537952378146234761985687935214519284673
395412678824376591671589243156928437249735186738641925983164752412857369567293814
679543182158926473432817659567381294914265738283479561345792816896154327721638945
867539142324167859159482736275398614936241587481756923592873461743615298618924375
954217683861453729372968145516832497249675318783149256437581962695324871128796534
271459386435168927986273541518734269769821435342596178194387652657942813823615794
237541896186927345495386721743269158569178432812435679378652914924813567651794283
168279435459863271273415986821354769734692518596781342615947823387526194942138657
863459712415273869279168354526387941947615238138942576781596423354821697692734185
768593142423176859951428736184765923572389614639214587816942375295837461347651298`
.split`
`.every(f)
&&
`519284673725893461841657392396142758473516829168429537952378146234761985687935214
839541267182437659367158924715692843624973518573864192298316475941285736456729381
679543182158926473432817659567381294914256738283479561345792816896154327721638945
867539142324167859159482736275398684936241517481756923592873461743615298618924375
754219683861453729372968145516832497249675318983147256437581962695324871128796534
271459386435168927986273541518734269769828435342596178194387652657942813823615794
237541896186927345378652914743269158569178432812435679495386721924813567651794283
168759432459613278273165984821594763734982516596821347615437829387246195942378651
869887283619214453457338664548525781275424668379969727517385163319223917621449519
894158578962859187461322315913849812241742157275462973384219294849882291119423759
123456789456789123564897231231564897789123456897231564312645978645978312978312645
145278369256389147364197258478512693589623471697431582712845936823956714931764825`
.split`
`.every(s => !f(s))

```
> 3 votes

# Answer
# Haskell (Lambdabot), 65 bytes

```
k x=and$(all$([1..9]==).sort)<$>[x,transpose x,join$chunksOf 3 x]

```
> 3 votes

# Answer
## Perl, 193 bytes

```
for(@x=1..9){$i=$_-1;@y=();push@y,$a[$i][$_-1]for@x;@y=sort@y;$r+=@y~~@x;@y=();push@y,$a[3*int($i/3)+$_/3][3*($i%3)+$_%3]for 0..8;@y=sort@y;$r+=@y~~@x}for(@a){@y=sort@$_;$r+=@y~~@x}exit($r!=27)

```

Input is expected in array form:

```
@a=(
    [1,2,3,4,5,6,7,8,9],
    [4,5,6,7,8,9,1,2,3],
    [7,8,9,1,2,3,4,5,6],
    [2,3,1,5,6,4,8,9,7],
    [5,6,4,8,9,7,2,3,1],
    [8,9,7,2,3,1,5,6,4],
    [3,1,2,6,4,5,9,7,8],
    [6,4,5,9,7,8,3,1,2],
    [9,7,8,3,1,2,6,4,5]
);

```

Exit code is 0, if `@a` is a solution, otherwise `1` is returned.

**Ungolfed version:**

```
@x = (1..9);
for (@x) {
    $i = $_ - 1;
    # columns
    @y = ();
    for (@x) {
        push @y, $a[$i][$_-1];
    }
    @y = sort @y;
    $r += @y ~~ @x;
    # sub arrays
    @y = ();
    for (0..8) {
        push @y, $a[ 3 * int($i / 3) + $_ / 3 ][ 3 * ($i % 3) + $_ % 3 ];
    }
    @y = sort @y;
    $r += @y ~~ @x
}
# rows
for (@a) {
    @y = sort @$_;
    $r += @y ~~ @x
}
exit ($r != 27);

```

Each of the 9 rows, 9 columns and 9 sub arrays are put into a sorted array and checked, whether it matches the array `(1..9)`. The number `$r` is incremented for each successful match that must sum up to 27 for a valid solution.
> 2 votes

# Answer
# Mathematica, ~~84~~ 79 chars

```
f=Tr[Norm[Sort@#-Range@9]&/@Join[#,Thread@#,Flatten/@Join@@#~Partition~{3,3}]]&

```

**Examples:**

```
f[{{1,2,3,4,5,6,7,8,9},
   {4,5,6,7,8,9,1,2,3},
   {7,8,9,1,2,3,4,5,6},
   {2,3,1,5,6,4,8,9,7},
   {5,6,4,8,9,7,2,3,1},
   {8,9,7,2,3,1,5,6,4},
   {3,1,2,6,4,5,9,7,8},
   {6,4,5,9,7,8,3,1,2},
   {9,7,8,3,1,2,6,4,5}}]

```

> 0

```
f[{{2,1,3,4,5,6,7,8,9},
   {4,5,6,7,8,9,1,2,3},
   {7,8,9,1,2,3,4,5,6},
   {2,3,1,5,6,4,8,9,7},
   {5,6,4,8,9,7,2,3,1},
   {8,9,7,2,3,1,5,6,4},
   {3,1,2,6,4,5,9,7,8},
   {6,4,5,9,7,8,3,1,2},
   {9,7,8,3,1,2,6,4,5}}]

```

> 2

```
f[{{0,2,3,4,5,6,7,8,9},
   {4,5,6,7,8,9,1,2,3},
   {7,8,9,1,2,3,4,5,6},
   {2,3,1,5,6,4,8,9,7},
   {5,6,4,8,9,7,2,3,1},
   {8,9,7,2,3,1,5,6,4},
   {3,1,2,6,4,5,9,7,8},
   {6,4,5,9,7,8,3,1,2},
   {9,7,8,3,1,2,6,4,5}}]

```

> 3
> 2 votes

# Answer
# R, ~~63~~ 50 bytes

Assumes the input `m` is a 9x9 matrix of numbers.

```
all(apply(m,1,match,x=1:9),apply(m,2,match,x=1:9))

```

I was right that further golfing was possible.

### Explanation:

```
    apply(m,1,match,x=1:9),

```

Take `m`, and for each row, apply the `match` function. We specify a further argument `x=1:9` to be passed to `match`. `x` is the default first position argument, and therefore each row is placed in the second argument position, which is `table`. The function `match` looks for instances of `x` in `table`. In this case, then, it's looking for `1:9` (the numbers 1 through 9) in each row. For each of `1:9`, it will return `TRUE` (or `FALSE`) if that number is found (or not).

So, this yields a series of 81 boolean values.

```
                           apply(m,2,match,x=1:9)

```

Repeat the above for each column of the input.

```
all(                                             )

```

Finally, `all` checks if every element of the list of booleans is `TRUE`. This will be the case if and only if the solution is correct (i.e. each number `1:9` is present only once in each column and each row).

### ~~Old approach:~~

~~```
for(i in 1:2)F=F+apply(m,i,function(x)sort(x)==1:9);sum(F)==162

```~~

~~It takes each row, sorts it, and then compares it to `[1, 2, ... 9]`. A correct row should match exactly. Then it does the same for each column. In total, we should have 162 exact matches, which is what the final portion checks for. There is likely some scope for further golfing here...~~
> 2 votes

# Answer
## Haskell - 175

```
import Data.List
c=concat
m=map
q=[1..9]
w=length.c.m (\x->(x\\q)++(q\\x))
b x=c.m(take 3.drop(3*mod x 3)).take 3.drop(3*div x 3)
v i=sum$m(w)[i,transpose i,[b x i|x<-[0..8]]]

```

The function `v` is the one to call. It works by getting the difference of each rows, column and block against the list `[1..9]` and summing up the lengths of those difference lists.

Demo using the example Sudoku:

```
*Main> :l so-22443.hs
[1 of 1] Compiling Main             ( so-22443.hs, interpreted )
Ok, modules loaded: Main.
*Main> v [[1,2,3,4,5,6,7,8,9],[4,5,6,7,8,9,1,2,3],[7,8,9,1,2,3,4,5,6],[2,3,1,5,6,4,8,9,7],[5,6,4,8,9,7,2,3,1],[8,9,7,2,3,1,5,6,4],[3,1,2,6,4,5,9,7,8],[6,4,5,9,7,8,3,1,2],[9,7,8,3,1,2,6,4,5]]
0

```
> 1 votes

# Answer
# Javascript - 149 Characters

```
r=[];c=[];g=[];for(i=9;i;)r[o=--i]=c[i]=g[i]=36;for(x in a)for(y in z=a[x]){r[v=z[y]-1]-=y;c[v]-=x;g[v]-=3*(x/3|0)+y/3|0}for(i in r)o|=r[i]|c[i]|g[i]

```

Expects an array `a` to exist and creates a variable `o` for output which is `0` on success and non-zero otherwise.

Works by checking that the sum of the position at which each value occurs for each row, column and 3\*3 grid equals 36 (0+1+2+3+4+5+6+7+8).

**Testing**

```
a=[
    [1,2,3, 4,5,6, 7,8,9],
    [4,5,6, 7,8,9, 1,2,3],
    [7,8,9, 1,2,3, 4,5,6],

    [2,3,1, 5,6,4, 8,9,7],
    [5,6,4, 8,9,7, 2,3,1],
    [8,9,7, 2,3,1, 5,6,4],

    [3,1,2, 6,4,5, 9,7,8],
    [6,4,5, 9,7,8, 3,1,2],
    [9,7,8, 3,1,2, 6,4,5]
  ];

```

Gives 'o=0'

```
a=[
    [1,2,3, 4,5,6, 7,8,9],
    [4,5,6, 7,8,9, 1,2,3],
    [7,8,9, 1,2,3, 4,5,6],

    [2,3,1, 5,6,4, 8,9,7],
    [5,6,4, 8,9,7, 2,3,1],
    [8,9,7, 2,3,1, 5,6,4],

    [3,1,2, 6,4,5, 9,7,8],
    [6,4,5, 9,7,8, 3,1,2],
    [9,7,8, 3,1,2, 6,5,4]
  ];

```

(Last 2 digits swapped)

Gives `o=-1`

```
a=[
    [5,5,5, 5,5,5, 5,5,5],
    [5,5,5, 5,5,5, 5,5,5],
    [5,5,5, 5,5,5, 5,5,5],

    [5,5,5, 5,5,5, 5,5,5],
    [5,5,5, 5,5,5, 5,5,5],
    [5,5,5, 5,5,5, 5,5,5],

    [5,5,5, 5,5,5, 5,5,5],
    [5,5,5, 5,5,5, 5,5,5],
    [5,5,5, 5,5,5, 5,5,5]
  ];

```

Gives `o=-284`
> 1 votes

# Answer
# Haskell, ~~121~~ ~~130~~ 127 bytes (87 Lambdabot)

```
import Data.List
import Data.List.Split
c=concat
t=transpose
k=chunksOf
p x=all(==[1..9])$(sort<$>)=<<[x,t x,k 9.c.c.t$k 3<$>x]

```

uses:

```
-- k 9.c.c.t$k 3<$> x = chunksOf 9 $ concat $ concat $ transpose $ map chunksOf 3 x

let ts = k 9$[10*a+b|a<-[1..9],b<-[1..9]] --yep, this is ugly
in k 9.c.c.t$k 3<$>ts
-- prints:
--[[11,12,13,21,22,23,31,32,33],[41,42,43,51,52,53,61,62,63],[71,72,73,81,82,83,91,92,93],[14,15,16,24,25,26,34,35,36],[44,45,46,54,55,56,64,65,66],[74,75,76,84,85,86,94,95,96],[17,18,19,27,28,29,37,38,39],[47,48,49,57,58,59,67,68,69],[77,78,79,87,88,89,97,98,99]]

```

Lambdabot loads Data.List and Data.List.Split by default (I don't think BlackCap's solution checks the boxes).

Ideas for improvement welcome

//Edit: I messed up :)
//Edit: 3 bytes saved by BlackCap
> 1 votes

# Answer
# 05AB1E, 36 bytes

```
|©vy3ô})3ôøvyJvyê}}®øvyê}®vyê})êžh¦Q

```

Try it online!

1 is true, anything else is false.
> 1 votes

# Answer
# JavaScript (Node.js), 143 bytes

```
A=>A.map((_,i)=>(c=d=>new Set(d).size==9)(A[i])&&c(A.map(b=>b[i]))&&c([0,0,0].reduce((a,_,O)=>a.concat(A[~~(i/3)*3+O].slice(l=i%3*3,l+3)),[])))

```

Try it online!
> 1 votes

# Answer
# J, 56 chars

Reads 9 lines of digits from ARGV and does magic:

```
echo-.*/,(b~:0),,(2 2$3)(-:~.)&,;.3 b=:"."0>cutLF{:>ARGV

```

Part of this is infused with an older script I wrote for a similar challenge elsewhere, so I don't remember what everything does. What I *do* remember is that `;.3` is really the funny magic here, because it "divides" the matrix of numbers into smaller "squares" according to the value `2 2$3` (I don't remember what it means, but pretend it's important).

Try it online!
> 1 votes

# Answer
**Clojure, 151 bytes**

Quite long, but others seem to be as well. Also annoying that union of sets requires a `require`, so I used a concat of vectors instead.

Iterates over each row and column and if the value is between 1 and 9 it emits three vectors, one for row, col and 3x3 cell. Returns 0 on success and `nil` otherwise, with two extra characters could return 1 on fail. Handles numbers outside of 1 - 9 by returning `nil` but will crash on other anomalies such as non-integer values. Quotients are 0 - 2 so it is safe to use values `8` and `9` to differentiate cell values from rows and columns.

```
(fn[s](if(= 243(count(set(apply concat(for[i(range 9)j(range 9)](let[v(nth(nth s i)j)q #(quot % 3)](if(<= 1 v 9)[[8 v i][9 v j][(q i)(q j)v]])))))))0))

```

Input is a nested vector of vectors (so that `nth` works):

```
(def sudoku [[1 2 3 4 5 6 7 8 9]
             [4 5 6 7 8 9 1 2 3]
             [7 8 9 1 2 3 4 5 6]
             [2 3 1 5 6 4 8 9 7]
             [5 6 4 8 9 7 2 3 1]
             [8 9 7 2 3 1 5 6 4]
             [3 1 2 6 4 5 9 7 8]
             [6 4 5 9 7 8 3 1 2]
             [9 7 8 3 1 2 6 4 5]])

```

Ungolfed:

```
(defn f [s]
  (->> (for [i (range 9) j (range 9)]
         (let [v (-> s (nth i) (nth j)) q #(quot % 3)]
           (if (<= 1 v 9)
             [[:row v i] [:col v j] [:cell [(q i) (q j)] v]])))
    (apply concat)
    set
    count
    (#(if (= 243 %) :pass :fail))))

```
> 0 votes

# Answer
# PHP, ~~196~~ 190 bytes

```
while($i<9){for($b=$c=$k=$y="";$y++<9;)$b.=($a=$argv)[$y][$i];for(;$k<3;)$c.=substr($a[++$k+$i-$i%3],$i%3*3,3);if(($u=count_chars)($a[++$i],3)<($d=123456789)|$u($b,3)<$d|$u($c,3)<$d)die(1);}

```

Program takes 9 separate command line arguments (one string of digits for each line of the grid);
exits with `1` (error) for invalid, `0` (ok) for valid.

Run with `php -nr '<code>' <row1> <row2> ...`.

**breakdown**

```
while($i<9)
{
    for($b=$c=$k=$y="";$y++<9;)$b.=($a=$argv)[$y][$i];  // column to string
    for(;$k++<3;)$c.=substr($a[$i-$i%3+$k],$i%3*3,3);   // sub-grid to string
    if(($u=count_chars)($a[++$i],3)<($d=123456789)      // check row
        |$u($b,3)<$d                                    // check column
        |$u($c,3)<$d                                    // check sub-grid
    )die(1);                                            // test failed: exit with 1
}

```

**explanation**

`count_chars` counts characters in a string and usually creates an array with ascii codes as keys and character count as values; but with `3` as mode parameter, it creates a sorted string from the characters; and that can easily be compared to the number with the wanted digits.

The comparison does not only check for duplicates, but also includes the check for invalid characters. And it only requires `<`, not `!=`, because this is numeric comparison: PHP will interpret the string as a number as far as it can. `123e56789`, `0x3456789` or similar cannot appear, because the characters are sorted; and any pure integer with a digit missing is smaller than `123456789` ... and `.23456789` too, of course.

`$a=$argv` saves one byte, `$d=123456789` saves nine and `$u=count_chars` saves 13.
> 0 votes

# Answer
# C# - 306 298 288 characters

The following Console program was used to call the checking function;

```
static void Main(string[] args)
    {
        int[,] i={{1,2,3,4,5,6,7,8,9},
             {4,5,6,7,8,9,1,2,3},
             {7,8,9,1,2,3,4,5,6},
             {2,3,1,5,6,4,8,9,7},
             {5,6,4,8,9,7,2,3,1},
             {8,9,7,2,3,1,5,6,4},
             {3,1,2,6,4,5,9,7,8},
             {6,4,5,9,7,8,3,1,2},
             {9,7,8,3,1,2,6,4,5}
            };

            Console.Write(P(i).ToString());
    }

```

All this does is initialise the array and pass it into the checking function P.

The checking function is as below (in Golfed form);

```
private static int P(int[,]i){int[]r=new int[9],c=new int[9],g=new int[9];for(int p=0;p<9;p++){r[p]=45;c[p]=45;g[p]=45;}for(int y=0;y<9;y++){for(int x=0;x<9;x++){r[y]-=i[x,y];c[x]-=i[x,y];int k=(x/3)+((y/3)*3);g[k]-=i[x,y];}}for(int p=0;p<9;p++)if(r[p]>0|c[p]>0|g[p]>0)return 1;return 0;}

```

Or in fully laid out form;

```
    private static int P(int[,] i)
    {
        int[] r = new int[9],c = new int[9],g = new int[9];
        for (int p = 0; p < 9; p++)
        {
            r[p] = 45;
            c[p] = 45;
            g[p] = 45;
        }

        for (int y = 0; y < 9; y++)
        {
            for (int x = 0; x < 9; x++)
            {
                r[y] -= i[x, y];

                c[x] -= i[x, y];

                int k = (x / 3) + ((y / 3) * 3);
                g[k] -= i[x, y];
            }
        }

        for (int p = 0; p < 9; p++)
            if (r[p] > 0 | c[p] > 0 | g[p] > 0) return 1;

        return 0;
    }

```

This uses the idea that all columns, rows and sub-grids should add up to 45. It works through the input array and subtracts the value of each position from it's row, column and sub-grid. Once complete it then checks that none of the rows, columns or sub-grids still have a value.

As requested returns a 0 if the array is a valid Sudoku solution and non-zero (1) where it's not.
> -1 votes

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


title: When's the Listening Party?

text:
# Question
Title: When's the Listening Party?
A listening party is an event where a bunch of people get together to listen to some music (like a viewing party, but for music). In the age of the internet you can do Listening Parties online with friends, where you just all hit play together.

The problem is on the internet everyone is in different time-zones so you can't just say "Let's start at 5:35". As a solution we just type `x`s in the hours position. So `xx:35` means whenever the minute hand is next at 35. If the minute hand is already at that value then the party happens in 1 hour. If you need to specify more than one hour ahead you can add `1+`, `2+` etc. to the beginning. So `1+xx:35` is an hour after the next time the minute hand is at 35.

Your task is to take the current local time, and a string representing when the listening party happens in the above format and output when the listening party will occur in local time.

# IO

You can take and output the local time either as a 24 hour string with the minutes and hours separated by a colon (e.g. `19:45`), as a tuple of the minutes and hours or as some native time type when available. If you take a string you may assume a leading zero when the hour hand is a one digit number otherwise. The two should be the same format. You can take the string representing when the listening party will happen either as a native string type or as a list of chars. The string will always match the following regex:

```
([1-9]+\d*\+)?xx:[0-5]\d

```

# Scoring

This is so answers will be scored in bytes with fewer being better.

# Test cases

```
5:35 xx:45 -> 5:45
19:12 xx:11 -> 20:11
5:15 1+xx:35 -> 6:35
12:30 1+xx:15 -> 14:15
8:29 3+xx:12 -> 12:12
4:30 xx:30 -> 5:30
23:59 xx:01 -> 0:01
15:30 25+xx:12 -> 17:12
12:09 xx:08 -> 13:08

```

# Answer
> 5 votes
# Jelly, ~~22~~ 20 bytes

```
Ṗ+<¬Ṫɗ+%"24ɓṣ”:f€ØDV

```

Try it online!

Takes the time as `[hh, mm]` on the left and the `xx` string on the right.

-2 bytes thanks to Lynn by a clever exploitation of Jelly's vectorising atoms!

## How it works

This uses the `ɓ` chaining structure to group a series of links to act only on the string, then we run the main links on the result of those links and on `[hh, mm]`. The `ɓ` splits the program into two links: `Ṗ+<¬Ṫɗ+%"24` and `ṣ”:f€ØDV`. The first one is dyadic (as two arguments are passed to the program), and the second one is dyadic but with the arguments in the opposite order as the first.

For a program that consists of two dyadic links `x (f g) y`, we calculate `x f (x g y)`. Non-notationally, this means that we run the second dyad on the two arguments, returning a value `z`. We then run the first dyad with `x` on the left and `z` on the right. The standard way of writing this would be `f ð g`. Using `ɓ` however, we reverse the arguments to `g`, so `f ɓ g` is `x f (y g x)`.

`g` is `ṣ”:f€ØDV`, run dyadically with the string `S` on the left and the time `T` on the right. `g` consists of 5 atoms: , `”:`, `f€`, `ØD`, `V`, which can be grouped into `ṣ”:`, `f€ØD`, `V`, a series of dyad-nilad pairs and a monad. This means that the right argument to the link is essentially ignored, and only the left argument is modified. We could try to use a monadic link for this, but by reversing the arguments implicitly with `ɓ`, we can avoid any quicks to indicate that a monadic link should be run on `S`.

`g`, given `S`, extracts the offset and minutes from the string, returning `[offset, mins]` as a pair of integers. `f` is then run as a dyadic link, with `T` (the time) on the left and `[offset, mins]` on the right.

Lynn noticed a clever exploitation of Jelly's vectoriser that allows us to save 2 bytes here. Essentially, if we have a list and an integer, `[a, b] + x` will vectorise across that list, yielding `[a+x, b+x]`, and if we have two lists `[a,b,c] + [x,y]`, we'll get `[a+x,b+y,c]`. The `"` (*vectorise*) quick will take a dyad `h` and force this behaviour.

Therefore, if we want to apply a dyad to just the first element of a list, we can use `"` and turn the right argument into a singleton list. For example: `[a, b] +" x ⁼ [a+x, b]`. Here, we calculate whether or not the `mins` is already past the current `minutes` of `T`. If so, we add `1` to `hours`. Therefore, we remove `minutes` from `T`, yielding `[hours]` and add this to the comparison, to yield `[hours + (mins ≥ minutes)]`. We then add this to `[offset, mins]`, to yield `[hours + (mins ≥ minutes) + offset, mins]`. Finally, we use `"` on `%24` so that we only modulo the first element by 24.

### How it works, in detail

```
Ṗ+<¬Ṫɗ+%"24ɓṣ”:f€ØDV - Main link. Takes [h, m] on the left and S on the right
           ɓṣ”:f€ØDV - Dyadic chain with S on the left, [h,m] on the right:
            ṣ”:      -   Split S on ”:
                €    -   Over each half:
               f ØD  -     Only keep digits
                   V -   Evaluate each as integers, [a, b]
Ṗ+<¬Ṫɗ+%"24ɓ         - Links to the left as a dyadic chain g([h,m], [a,b]):
Ṗ                    -   Pop; Yield [h]
     ɗ               -   Last 3 links as a dyad f([h,m], [a,b]):
  <¬                 -     [¬(h < a), ¬(m < b)]
    Ṫ                -     ¬(m < b)
 +                   -   [h + ¬(m < b)]
      +              -   [h + ¬(m < b) + a, b]
       %"24          -   [(h + ¬(m < b) + a) % 24, b]

```

# Answer
> 4 votes
# Retina 0.8.2, ~~81~~ 76 bytes

```
\d+
$*
:(1*) (1*).*:((?!1\1))?
$#3$*1$2:
+`1{24}:
:
1*
$.&
\B0\b

\b\d\b
0$&

```

Try it online! Link includes test cases. Edit: Saved 5 bytes thanks to @user41805. Explanation:

```
\d+
$*

```

Convert to unary.

```
:(1*) (1*).*:((?!1\1))?
$#3$*1$2:

```

Add the extra hours, plus check whether the minutes are behind and if not add another hour.

```
+`1{24}:
:

```

Reduce the hours modulo 24.

```
1*
$.&
\B0\b

```

Convert the hours and minutes to decimal. Due to the way `1*` matches again at the end of a row of `1`s, this actually ends up multiplying the result by 10, so the trailing 0 needs to be deleted in this case (but not in the `0` case, as that just becomes `0` as expected).

```
\b\d\b
0$&

```

Add leading zeros to single digits.

# Answer
> 4 votes
# JavaScript (ES6), 52 bytes

I/O format: tuple of integers

```
([h,m],s)=>[([H,M]=s.split(/\D+/),h-~H-(M>m))%24,+M]

```

Try it online!

# Answer
> 4 votes
# Haskell, 77 bytes

```
(h,m)%s|[(b,_:c)]<-reads s=(h+b,m)%c|n<-read$drop 3s=(mod(h+sum[1|m>=n])24,n)

```

Try it online!

# Answer
> 4 votes
# Perl 5 (`-p`), 56 bytes

```
s/(.+):(.+) (.+\+)?xx:(.+)/(($1+$3+($4<=$2))%24).":$4"/e

```

Try it online!

We match the input regex and do some fun math. The minute hand of the result is always `$4` (the fourth capture group). The hour hand is the initial hour hand (`$1`), plus the time offset (`$3`), plus one extra if we've already passed the minute in the current hour (`$4<=$2`), mod 24.

Perl's numerical coercion rules help us a lot here. `$4<=$2` coerces to zero or one, which is the exact number we need to add to the hour hand. `$3` is the offset value, such as `2+`, which coerces to `2` under numerical coercion. If there's no offset, then `$3` is undefined which conveniently coerces to zero.

# Answer
> 3 votes
# Python 3, 62 bytes

```
lambda t,s:(str((eval(s[:-5]+t[0])+(t[1]>=s[-2:]))%24),s[-2:])

```

Try it online!

Inputs and outputs a tuple of strings.

# Answer
> 3 votes
# 05AB1E, ~~19~~ 18 bytes

```
':¡€þø``©@ªþO24%®‚

```

Try it online or verify all test cases.

I/O of the times as pairs of `[HH,mm]`; input-order is the string followed by the pair.

**Explanation:**

```
':¡               '# Split the first (implicit) input-string on ":"
   €þ              # Only leave the digits of both parts (will be "" for "xx")
     ø             # Zip the pair with the second (implicit) input-pair
      `            # Pop and push both pairs separated to the stack
       `           # Pop and push both minutes separated to the stack
        ©          # Store the minutes of the string in variable `®` (without popping)
         @         # Check if the minutes from the input-pair are larger than or equal
                   # to the minutes of the input-string
          ª        # Append this 1 or 0 to the pair of hours
           þ       # Only leave the numbers (to potentially remove the "")
            O      # Sum this list
             24%   # Modulo-24
                ®‚ # And pair it with minutes `®`
                   # (after which the result is output implicitly)

```

# Answer
> 3 votes
# jq, 123 bytes

```
.[2]|=[scan("\\d+")|tonumber]|.[0]+=((.[2][-1]>.[1]//1)?+0//0)+(.[2]|length-1|./.?//0)*.[2][0]|.[1]=.[2][-1]|.[0]%=24|.[:2]

```

Try it online!

Takes input as `[hh,mm,string]` and returns `[hh,mm]`.

jq does not have a way to cast a boolean, so the try statements are used(thanks ovs). The modification ops are quite convenient, though.

-5 bytes from ovs.

# Answer
> 2 votes
# Vyxal, 19 bytes

```
0p\:€⌊Z÷÷:£≥J∑24%¥"

```

Try it Online!

# Answer
> 2 votes
# , ~~111~~ ~~108~~ ~~105~~ 102 bytes

```
function(t,x,k=scan(t=el(regmatches(s<-paste0(0,x),gregexpr("\\d+",s)))))c(el(t+k+rev(t>=k))%%24,k[2])

```

Try it online!

---

Slightly different solution with the same byte-count:

### , 102 bytes

```
function(t,x,k=scan(t=el(regmatches(s<-paste0(0,x),gregexpr("\\d+",s)))))c(k,(t+k+rev(t>=k))%%24)[3:2]

```

Try it online!

---

is terrible in string challenges...

# Answer
> 2 votes
# V (vim) `-v` calling `bc`, 105 bytes

Thanks to caird coinheringaahing for filling in some V documentation gaps.
One could reduce the byte count by using raw byte source code instead of `-v`: 81 bytes courtesy of Aaroneous Miller.
As user41805 pointed out in chat, using `bc` is most likely inferior to V's built-ins.

```
f:x"adt x"bdt:s
<esc>"cddo<esc>"apA+1<esc>"cpA+0<esc>Vk:sort
dd0dt+k"bPhxxJI(<esc>A)%24<esc>:.!bc
"cpkJr:

```

Try it online!, Test it online!

# Answer
> 1 votes
# C (gcc), <sup>~~144~~</sup> 143 bytes

```
n;h;m;o;x,y;f(t,p)char*p,*t;{x=sscanf(p,"%d+xx:%d"+y*3,(y=*p>58)?&m:&o,&m);sscanf(t,"%d:%d",&h,&n);printf("%d:%02d",(h+(y?x:o+1)-(n<m))%24,m);}

```

Try it online!

*Saved a byte thanks to ceilingcat!!!*

# Answer
> 1 votes
# Python 2, ~~83~~ 65 bytes

```
a,b=input();print(eval(b[:-5]+a[:-3])+(a[-2:]>=b[-2:]))%24,b[-2:]

```

Try it online!

pretty simple

Thanks @caird for changing language and saving 18 bytes! (That's a lot of bytes!)

# Answer
> 0 votes
# Charcoal, 32 bytes

```
≔⪪Ｓ:θ≔⪪Ｓ:ηＩ﹪⁺¬›⊟θ§η¹Σ⁺§η⁰⊟θ²⁴:⊟η

```

Try it online! Link is to verbose version of code. Could output in `HH:mm` format at a cost of 4 bytes. Explanation:

```
≔⪪Ｓ:θ

```

Input the local time and split on `:`.

```
≔⪪Ｓ:η

```

Input the party time and split on `:`. This means that the hours still contains the `xx`.

```
Ｉ﹪⁺¬›⊟θ§η¹Σ⁺§η⁰⊟θ²⁴

```

Compare the two sets of minutes. Concatenate the party hours with the local time, resulting in something like `1+xx5`. Because it contains non-digit characters, taking its sum actually extracts all of the embedded integers and sums those, giving us the resulting local hour (after the potential minutes adjustment).

```
:⊟η

```

Output the `:` and party minutes.

---
Tags: code-golf, string, date
---


title: Let's go for a rollercodester ride

text:
# Question
Title: Let's go for a rollercodester ride
# Let's go for a rollercodester ride

The objective of this challenge is to create a program that is run recursively through several languages of your choice. The output of the first iteration becomes the code for the second iteration, et. cetera.

* You choose the language sequence, but each **unique** language may be used only once. Unique languages will be determined using CGCC standards (different compiler flags =\> different languages!)
* Each step must be a complete program that terminates before the next step will be executed.
* The entire output of stdout (not including stderr) will be considered code for the next step.
* Other than executing and producing output, your programs can do whatever they want but every byte that your program reads contributes a byte to it's scored code length.
* Each step executes in a theoretically clean environment, no actions of prior steps can be accessed by the current step.
* Please score your submission as best as you can, I anticipate some difficulty validating submissions (no fancy scoring tool yet...).

## Scoring

Thanks to ovs for creating a score calculator: TIO Link

* The curvature of any three consecutive steps in the submission is the difference of the difference of each step's code length.
* Any three consecutive steps in the submission earn score points equal to their absolute curvature divided by the total source length of all three steps.
* Each scored step will be rounded (x\>=5e-7 becomes 1e-6, x\<5e-7 becomes 0) to the nearest 1e-6, to make scoring exact.
* The goal is to achieve the highest score.
* In the unlikely event of a tie, the shortest initial (just the first step) submission in bytes wins (it's gotta have some sort of golf, right???).

To discuss scoring consistently we can call the first step "Step 1", and assign scored points to the last step that contributes to those points. The first two steps (1 and 2) are not scorable because there isn't enough data to calculate a score, then each step after that has a score calculated from itself and the two prior steps. i.e. in the working example below, step 3 scores .566038, step 4 scores .536082

## Scoring example

* Step 1 (original submission) : 50 bytes
* Step 2: 25 bytes -25 change
* Step 3: 50 bytes +25 change +50 curvature / 50+25+50 bytes = 0.4 score
* Step 4: 40 bytes -10 change -35 curvature / 25+50+40 bytes = 0.304348 score
* Step 5: 30 bytes -10 change +0 curvature / 50+40+30 bytes = 0 score

total score: (0.4+0.304348+0) = 0.704348

## Working example

Here's a working example, code is below the score. I can maximize my score by increasing the repeating parts of the Octave and Python 1 code, but can never get more than a score of 2 in any step.

4 steps:

1. Python 3 - 107
2. Octave - 166
3. C (gcc) - 45
4. Python 1 - 80

scoring:

```
step  diff  curve  total_len score
107   -     -
166   +59   -
45    -121  -180   318       0.566038
80    +35   +156   291       0.536082

total:                       1.102120

```

# Python 3, 107 bytes

```
print(f"""disp("main(){'{for(int i=0;i<10;i++)puts(""print 1"");}'}")
{'''
'''.join(['%commented']*10)}""")

```

Try it online!

# Octave, 166 bytes

```
disp("main(){for(int i=0;i<10;i++)puts(""print 1"");}")
%commented
%commented
%commented
%commented
%commented
%commented
%commented
%commented
%commented
%commented

```

Try it online!

# C (gcc), 45 bytes

```
main(){for(int i=0;i<10;i++)puts("print 1");}

```

Try it online!

# Python 1, 80 bytes

```
print 1
print 1
print 1
print 1
print 1
print 1
print 1
print 1
print 1
print 1

```

Try it online!

# Answer
# 9 langs, score 7.090470.

## Deadfish~, 10000001377 bytes

```
{{i}}iic{i}dciiic{{d}iii}ddddc{iiiiii}iiiiic{dddd}ddddc{d}dddc{i}ic{iiii}iiiiiic{dddd}dddddc{d}dcdcc{i}ic{iiii}iiiiiic{dddddd}ddccddcdc{iiiiii}dc{dddd}iic{iiii}ddc{i}iicdciiiiicddddcdddc{d}iiic{ddddd}dddddc{iiiiii}iiciiic{d}iic{dddddd}ddcdcdcddddc{iiiiii}iiiic{i}iicddcc{d}iic{i}dciiiiiic{{d}ii}iiiciic{ii}ddc{iiii}c{dddddd}icdc{iiiii}iic{ii}iciic{d}iciiiiiciiiiiic{{d}iii}ddddddcddddddcic{iiiiii}iiiic{i}iicddcc{d}iic{i}dciiiiiic{{d}ii}ddc{i}dddc{d}ic{{i}ddd}c{i}dciiic{{d}ii}ddc{{i}ddd}iiic{{d}iii}dddc{{i}ddd}iiiciiiiic{{d}ii}iic{{i}dd}iic{dd}iiic{i}iiic{d}iiicddc{dddddd}dc{i}dcdccc{d}iiic{iiiii}iic{ddd}ddddc{ddd}iiic{{i}dd}ciic{d}iciiiiiciiiiiic{{d}iii}ddddddcddddddc{iiiiii}iic{ddddd}icdddddc{iiiii}iiiic{ddddd}ddc{iiiiii}iiic{dddddd}iic{d}ic{iiiii}iiiiiic{ii}iiiic{dd}ddddc{i}ic{dddddd}iic{d}iiiciicdddc{iiiii}iiiiic{ddddd}ddddciiiiic{iiiii}dc{ddddd}ddc{iiiii}iic{dddddd}dc{{i}ddd}ciiiiic{d}dc{i}dc{i}dc{dd}iiicic{{d}iii}ic{iii}ddc{iiiii}iiiiicic{d}ddddddciiiiiciiiiiic{dddddd}dddddc{iiiiii}ddc{dddd}ddc{iii}iiiic{ddddd}ddc{iiiii}iic{i}dciiiiiciiiiiic{{d}ii}ddddc{{i}dd}dddc{d}ddc{i}ddciiiiic{{d}iii}cic{{i}dd}iic{d}dciiiiicdcdc{{d}iii}dddddc{iiiii}iicc{dddddd}iic{{i}dd}ddciiiiicdcdc{{d}ii}dddciiiiic{{i}ddd}iiiiiic{dd}ddc{ddddd}iic{iiiii}ddc{ddddd}iiciiic{iiiii}dddccdcc{dddddd}iic{i}dddc{ii}ddc{iiiiii}iiiiiic{ddd}ic{ddddd}ddc{d}c{i}dddcddciiciiiiiicc{iii}iiiicccccc

```

Try it online!

With \\$10^{10}\\$ `h` at the end.

## HQ9+, 192 bytes

```
for(i=0;i<100;i++)(c=console.log)('#comment');c('[print("#comment") for i in range(1000)]; print("`/*`,k1(`x`k1*,)`*/`,`#include <stdio.h>`,`int main(){puts(\\"puts %q[+[+.]]\\");}`,")')//QQQQQQ

```

Try it online! (code will need to be pasted in)

Note: Extraneous content has been simplified in the below snippets, and removed from the TIOs - if you add it back it'll work fine.

## JavaScript (Node.js), 1164 bytes

```
for(i=0;i<100;i++)(c=console.log)('#comment');c('[print("#comment") for i in range(1000)]; print("`/*`,k1(`x`k1*,)`*/`,`#include <stdio.h>`,`int main(){puts(\\"puts %q[+[+.]]\\");}`,")')//QQQQQQ

```

Repeated 6 times.

Try it online!

## Python 3, 1033 bytes

```
#comment
[print("#comment") for i in range(1000)]; print("`/*`,k1(`x`k1*,)`*/`,`#include <stdio.h>`,`int main(){puts(\"puts %q[+[+.]]\");}`,")

```

Try it online!

The `#comment` is repeated 100 times.

## Vyxal, 9081 bytes

```
#comment
`/*`,k1(`x`k1*,)`*/`,`#include <stdio.h>`,`int main(){puts("puts %q[+[+.]]");}`,

```

The `#comment` is repeated 1000 times.

Try it Online!

## C (gcc), 914699 bytes

```
/*x*/
#include <stdio.h>
int main(){puts("puts %q[+[+.]]");}

```

Try it online!

The `x` is actually 1000 newline-separated copies of 1000 more `x`.

## Ruby, 14 bytes

```
puts %q[+[+.]]

```

Try it online!

## brainfuck, 5 bytes

```
+[+.]

```

Try it online!

## PHP, 382 bytes

```

 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ

```

Try it online!

~~No idea what my score is.~~ Thanks to @ovs for calculating my score.
> 9 votes

# Answer
# Score 20

~~Have I misunderstood this question? I'm not quite sure what's happening here. Please leave a comment if this is not allowed by the rules, and I will then delete it.~~

The basic idea is try to find out if any languages accept an empty program and output something (non-empty stdout). And this could be extended as long as you spend some more time on esolang wiki and find out more languages and append them to this chain...
> 6 votes

---
Tags: code-challenge
---


title: Golf Text into DNA

text:
# Question
Title: Golf Text into DNA
# Text to DNA golf

## Challenge

Convert input into a DNA output.

## Algorithm

* Convert text into ASCII code points (e.g. `codegolf` -\> `[99, 111, 100, 101, 103, 111, 108, 102]`)
* String the ASCII codes together (e.g. `99111100101103111108102`)
* Convert to binary (e.g. `10100111111001101001011010001000011001101011011110000110010111111011000000110`)
* Pad `0`s onto the end to make an even number of characters (e.g. `101001111110011010010110100010000110011010110111100001100101111110110000001100`)
* Replace `00` with `A`, `01` with `C`, `10` with `G`, and `11` with `T` (e.g. `GGCTTGCGGCCGGAGACGCGGTCTGACGCCTTGTAAATA`)
* Output

## Test Cases

```
codegolf > GGCTTGCGGCCGGAGACGCGGTCTGACGCCTTGTAAATA
ppcg > GGCTAATTGTCGCACTT
} > TTGG (padding)

```

## Specifications

* This is
* Your program must accept spaces in input.
* Your program must work for `codegolf`.

# Answer
# Jelly, ~~15~~ 13 bytes

```
OVBs2UḄị“GCTA

```

Try it online! or verify all test cases.

### How it works

```
OVBs2UḄị“GCTA    Main link. Argument: s (string)

O                Ordinal; replace each character with its code point.
 V               Eval. This converts the list to a string before evaluating, so it
                 returns the integer that results of concatenating all the digits.
  B              Binary; convert from integer to base 2.
   s2            Split into chunks of length 2.
     U           Upend; reverse the digits of each chunk.
                 Reversing means that we would have to conditionally PREPEND a zero
                 to the last chunk, which makes no difference for base conversion.
      Ḅ          Unbinary; convert each chunk from base 2 to integer.
                 `UḄ' maps:
                     [0, 1   ] -> [1,    0] -> 2
                     [1, 0(?)] -> [0(?), 1] -> 1
                     [1, 1   ] -> [1,    1] -> 3
                     [0, 0(?)] -> [0(?), 0] -> 0
       ị“GCTA    Replace each number by the character at that index.
                 Indexing is 1-based, so the indices are [1, 2, 3, 0].

```
> 17 votes

# Answer
## CJam, ~~24~~ 23 bytes

*Thanks to Dennis for saving 1 byte in a really clever way.* :)

```
l:isi2b2/Wf%2fb"AGCT"f=

```

Test it here.

### Explanation

Very direct implementation of the specification. The only interesting bit is the padding to an even number of zeros (which was actually Dennis's idea). Instead of treating the digits in each pair in the usual order, we make the second bit the most significant one. That means, ending in a single bit is identical to appending a zero to it, which means we don't have to append the zero at all.

```
l          e# Read input.
:i         e# Convert to character codes.
si         e# Convert to flat string and back to integer.
2b         e# Convert to binary.
2/         e# Split into pairs.
Wf%        e# Reverse each pair.
2fb        e# Convert each pair back from binary, to get a value in [0 1 2 3].
"AGCT"f=   e# Select corresponding letter for each number.

```
> 9 votes

# Answer
# Python 2, ~~109~~ 103 bytes

```
lambda s,j=''.join:j('ACGT'[int(j(t),2)]for t in
zip(*[iter(bin(int(j(`ord(c)`for c in s))*2)[2:])]*2))

```

Test it on Ideone.
> 9 votes

# Answer
# Ruby, 59 bytes

```
$_='%b0'.%$_.bytes*''
gsub(/../){:ACGT[$&.hex%7]}
chomp'0'

```

A full program. Run with the `-p` flag.
> 6 votes

# Answer
# Python 3, 130 bytes.

Saved 2 bytes thanks to vaultah.
Saved 6 bytes thanks to Kevin Lau - not Kenny.

I hate how hard it is to convert to binary in python.

```
def f(x):c=bin(int(''.join(map(str,map(ord,x)))))[2:];return''.join('ACGT'[int(z+y,2)]for z,y in zip(*[iter(c+'0'*(len(c)%2))]*2))

```

Test cases:

```
assert f('codegolf') == 'GGCTTGCGGCCGGAGACGCGGTCTGACGCCTTGTAAATA'
assert f('ppcg') == 'GGCTAATTGTCGCACTT'

```
> 4 votes

# Answer
# Python 3, 126 bytes

```
lambda v:"".join(["ACGT"[int(x,2)]for x in map(''.join,zip(*[iter((bin(int("".join([str(ord(i))for i in v])))+"0")[2:])]*2))])

```
> 4 votes

# Answer
# Ruby, 80 bytes

```
->s{s=s.bytes.join.to_i.to_s 2;s+=?0*(s.size%2)
s.gsub(/../){"ACGT"[$&.to_i 2]}}

```
> 3 votes

# Answer
# Mathematica, 108 bytes

```
{"A","C","G","T"}[[IntegerDigits[Mod[Floor@Log2@#,2,1]#&@FromDigits[""<>ToString/@ToCharacterCode@#],4]+1]]&

```

Takes a string as input, and outputs a list of bases.
> 3 votes

# Answer
# Vyxal, 17 bytes

```
Cṅb₅∷[0J]B`ACGT`τ

```

Try it Online!

A mess.

```
C                 # Charcodes
 ṅ                # Concatenated
  b               # To binary
   ₅∷[  ]         # If length is odd
      0J          # Append a 0
         B        # To base10
          `ACGT`τ # Convert to custom base `ACGT` (convert to base4, replace 0-3 with corresponding item of "ACGT")

```
> 3 votes

# Answer
# Pyth, 25 bytes

```
sm@"ACGT"id2Pc.B*4sjkCMQ2

```

Try it here!

### Explanation

Burrowing the padding trick from Martins CJam answer.

```
sm@"ACGT"id2Pc.B*4sjkCMQ2    # Q = input

                     CMQ     # Map each character of Q to its character code
                  sjk        # Join into one string and convert to an integer
              .B*4           # Mulitply with 4 and convert to binary
             c          2    # Split into pairs
            P                # Discard the last pair
 m                           # Map each pair d
         id2                 # Convert pair from binary to decimal
  @"ACGT"                    # Use the result ^ as index into a lookup string
s                            # Join the resulting list into on string

```
> 2 votes

# Answer
# 05AB1E, 23 bytes

Code:

```
SÇJb00«2÷¨C3210"TGCA"‡á

```

Uses **CP-1252** encoding. Try it online!.
> 2 votes

# Answer
# Java, 194 bytes

```
String a(int[]a){String s="",r=s;for(int i:a)s+=i;s=new BigInteger(s).toString(2)+0;for(int i=0,y,n=48;i<(s.length()/2)*2;r+=s.charAt(i++)==n?y==n?'A':'G':y==n?'C':'T')y=s.charAt(i++);return r;}

```

### Ungolfed

```
String a(int[] a) {
    String s = "", r = s;
    for (int i : a) s += i;
    s = new BigInteger(s).toString(2) + 0;
    for (int i = 0, y, n = 48; i < (s.length() / 2) * 2;
        r += s.charAt(i++) == n
                 ? y == n
                 ? 'A'
                 : 'G'
                 : y == n
                 ? 'C'
                 : 'T')
        y = s.charAt(i++);
    return r;
}

```

### Note

* Input is an array of chars (which should count as a form of String), parameter is of type `int[]` because thats one byte saved over `char[]`.

### Output

```
Input:  codegolf
Output: GGCTTGCGGCCGGAGACGCGGTCTGACGCCTTGTAAATA

Input:  .
Output: GTG

Input:  }
Output: TTGG

Input:  wow
Output: TGATAGTTGTGCTG

Input:  programming puzzles
Output: GTGTCAGAGTTGAAGGCCGTTCCGCAGTGCATTTGGCTCGTCTGGTGTCTACTAGCCTGCGAGAGGAGTTACTTTGGATCCTTGACTTGT

```
> 2 votes

# Answer
# Python 2.7, 135 bytes

```
def f(A):g=''.join;B=bin(int(g(map(str,map(ord,A)))))[2:];B+=len(B)%2*'0';return g('ACGT'[int(B[i:i+2],2)] for i in range(len(B))[::2])

```

Ungolfed:

```
def f(A):
    g = ''.join
    B = bin(int(g(map(str,map(ord,A)))))[2:] # convert string input to binary
    B += len(B)%2 * '0' # add extra 0 if necessary
    return g('ACGT'[int(B[i:i+2],2)] for i in range(len(B))[::2]) # map every two characters into 'ACGT'

```

# Output

```
f('codegolf')
'GGCTTGCGGCCGGAGACGCGGTCTGACGCCTTGTAAATA'

```
> 2 votes

# Answer
# MATL, 21 bytes

```
'CGTA'joV4Y2HZa2e!XB)

```

**Try it online!**

### Explanation

```
'CGTA'   % Push string to be indexed into
j        % Take input string
o        % Convert each char to its ASCII code
V        % Convert to string (*). Numbers are separated by spaces
4Y2      % Push the string '0123456789'
H        % Push number 2
Za       % Convert string (*) from base '0123456789' to base 2, ignoring spaces
2e       % Reshape into a 2-column matrix, padding with a trailing 0 if needed
!        % Transpose
XB       % Convert from binary to decimal
)        % Index into string with the DNA letters. Indexing is 1-based and modular

```
> 2 votes

# Answer
# Factor \+ `grouping.extras`, 95 bytes

```
[ [ present ] f map-as concat dec> >bin 2 48 pad-groups 2 group [ bin> "ACGT" nth ] "" map-as ]

```

Doesn't work on TIO because `pad-groups` postdates build 1525, the one TIO uses. Here's a picture of running it in build 2101:

There is no build where whitespace can be omitted after strings and `pad-groups` exists, but `pad-groups` makes it worth it.

## Explanation:

It's a quotation (anonymous function) that accepts a string from the data stack as input and leaves a string on the data stack as output. Assuming `"ppcg"` is on the data stack when this quotation is called...

| Snippet | Output |
| --- | --- |
| `[ present ] f map-as` | `{ "112" "112" "99" "103" }` |
| `concat` | `"11211299103"` |
| `dec>` | `11211299103` |
| `>bin` | `"1010011100001111101101100100011111"` |
| `2 48 pad-groups` | `"1010011100001111101101100100011111"` (append zeros so length is divisible by 2.) |
| `2 group` | `{ "10" "10" "01" "11" "00" "00" "11" "11" "10" "11" "01" "10" "01" "00" "01" "11" "11" }` |
| `[ bin> ] map` | `{ 2 2 1 3 0 0 3 3 2 3 1 2 1 0 1 3 3 }` |
| `[ "ACGT" nth ] "" map-as` | `"GGCTAATTGTCGCACTT"` |
> 2 votes

# Answer
# Pyth, 23 bytes

```
sm@"AGCT"i_d2c.BsjkCMQ2

```

Try it online!

### Explanation

Borrowing the trick from Dennis' Jelly answer.

```
sm@"AGCT"i_d2c.BsjkCMQ2
                   CMQ   convert each character to its byte value
                sjk      convert to a string and then to integer
              .B         convert to binary
             c        2  chop into pairs
 m         d             for each pair:
          _                  reverse it
         i  2                convert from binary to integer
  @"AGCT"                    find its position in "AGCT"
s                        join the string

```
> 1 votes

# Answer
# Groovy, 114 bytes

```
{s->'ACGT'[(new BigInteger(((Byte[])s).join())*2).toString(2).toList().collate(2)*.with{0.parseInt(it.join(),2)}]}

```

Explanation:

```
{s->
    'ACGT'[ //access character from string
        (new BigInteger( //create Big Integer from string
           ((Byte[])s).join() //split string to bytes and then join to string
        ) * 2) //multiply by 2 to add 0 at the end in binary
        .toString(2) //change to binary string
        .toList() //split to characters
        .collate(2) //group characters by two
        *.with{
            0.parseInt(it.join(),2) //join every group and parse to decimal
        }
     ]
}

```
> 1 votes

# Answer
# Julia 0.4, 77 bytes

```
s->replace(bin(BigInt(join(int(s)))),r"..?",t->"AGCT"[1+int("0b"reverse(t))])

```

This anonymous function takes a character array as input and returns a string.

Try it online!
> 1 votes

# Answer
# J, 52 bytes

```
 3 :'''ACGT''{~#._2,\#:".,&''x''":(,&:(":"0))/3&u:y'

```

Usage: `3 :'''ACGT''{~#._2,\#:".,&''x''":(,&:(":"0))/3&u:y' 'codegolf'` ==\> `GGCTTGCGGCCGGAGACGCGGTCTGACGCCTTGTAAATA`
> 1 votes

# Answer
# Javascript ES7, ~~105~~ 103 bytes

```
s=>((+[for(c of s)c.charCodeAt()].join``).toString(2)+'0').match(/../g).map(x=>"ACGT"['0b'+x-0]).join``

```

The ES7 part is the `for(c of s)` part.

## ES6 version, ~~107~~ 105 bytes

```
s=>((+[...s].map(c=>c.charCodeAt()).join``).toString(2)+'0').match(/../g).map(x=>"ACGT"['0b'+x-0]).join``

```

## Ungolfed code

```
dna = (str)=>{
  var codes = +[for(c of str)c.charCodeAt()].join``;
  var binaries = (codes.toString(2)+'0').match(/../g);
  return binaries.map(x=>"ACGT"['0b'+x-0]).join``
}

```

This is my first try at golfing on PPCG, feel free to correct me if something's wrong.

Thanks @AlexA for the small improvement.
> 1 votes

# Answer
## Hoon, ~~148~~ 138 bytes

```
|*
*
=+
(scan (reel +< |=({a/@ b/tape} (weld <a> b))) dem)
`tape`(flop (turn (rip 1 (mul - +((mod (met 0 -) 2)))) |=(@ (snag +< "ACGT"))))

```

"abc" is a list of atoms. Interpolate them into strings (`<a>`) while folding over the list, joining them together into a new string. Parse the number with `++dem` to get it back to an atom.

Multiply the number by (bitwise length + 1) % 2 to pad it. Use `++rip` to disassemble every two byte pair of the atom into a list, map over the list and use the number as an index into the string "ACGT".

```
> =a |*
  *
  =+
  (scan (reel +< |=({a/@ b/tape} (weld <a> b))) dem)
  `tape`(flop (turn (rip 1 (mul - +((mod (met 0 -) 2)))) |=(@ (snag +< "ACGT"))))
> (a "codegolf")
"GGCTTGCGGCCGGAGACGCGGTCTGACGCCTTGTAAATA"
> (a "ppcg")
"GGCTAATTGTCGCACTT"
> (a "}")
"TTGG"

```
> 1 votes

# Answer
## Common Lisp (Lispworks), 415 bytes

```
(defun f(s)(labels((p(e f)(concatenate'string e f)))(let((b"")(d""))(dotimes(i(length s))(setf b(p b(write-to-string(char-int(elt s i))))))(setf b(write-to-string(parse-integer b):base 2))(if(oddp #1=(length b))(setf b(p b"0")))(do((j 0(+ j 2)))((= j #1#)d)(let((c(subseq b j(+ j 2))))(cond((#2=string="00"c)(setf d(p d"A")))((#2#"01"c)(setf d(p d"C")))((#2#"10"c)(setf d(p d"G")))((#2#"11"c)(setf d(p d"T")))))))))

```

ungolfed:

```
(defun f (s)
  (labels ((p (e f)
             (concatenate 'string e f)))
  (let ((b "") (d ""))
    (dotimes (i (length s))
      (setf b
            (p b
               (write-to-string
                (char-int (elt s i))))))
    (setf b (write-to-string (parse-integer b) :base 2))
    (if (oddp #1=(length b))
        (setf b (p b "0")))
      (do ((j 0 (+ j 2)))
          ((= j #1#) d)
        (let ((c (subseq b j (+ j 2))))
          (cond ((#2=string=  "00" c)
                 (setf d (p d "A")))
                ((#2# "01" c)
                 (setf d (p d "C")))
                ((#2# "10" c)
                 (setf d (p d "G")))
                ((#2# "11" c)
                 (setf d (p d "T")))))))))

```

Usage:

```
CL-USER 2060 > (f "}")
"TTGG"

CL-USER 2061 > (f "golf")
"TAAAAATTATCCATAAATA"

```
> 1 votes

# Answer
# PowerShell Core, ~~143~~ 121 bytes

```
filter d{if($_){"$(($_-($i=$_%2))/2|d)$i"}}-join([regex]"(..)"|% s* "$(-join($args|%{+$_})|d)0"|?{$_[1]}|%{"ACGT"[$_%8]})

```

Try it online!

## Explanations

Takes as an input a string transformed as a char array using splatting

First, a filter to convert decimal to binary as Powershell can't do it for number larger than `long`

```
filter d{if($_){"$(($_-($i=$_%2))/2|d)$i"}}

```

This converts the char array to an int array, joins them as a string, splits with binary string concatenated with the padding in strings of length 2.
It converts each substring to a number, and using modulus 8, finds the correct char in the `ACGT` string.

```
-join([regex]"(..)"|% s* "$(-join($args|%{+$_})|d)0"|?{$_[1]}|%{"ACGT"[$_%8]})

```
> 1 votes

# Answer
# Perl, ~~155~~ ~~148~~ 137 + 1 (`-p` flag) = 138 bytes

```
#!perl -p
s/./ord$&/sge;while($_){/.$/;$s=$&%2 .$s;$t=$v="";$t.=$v+$_/2|0,$v=$_%2*5
for/./g;s/^0// if$_=$t}$_=$s;s/(.)(.)?/([A,C],[G,T])[$1][$2]/ge

```

Test it on Ideone.
> 0 votes

# Answer
# Perl 6, 57 + 1 (`-p` flag) = 58 bytes

```
$_=(+[~] .ords).base(2);s:g/..?/{<A G C T>[:2($/.flip)]}/

```

Step by step explanation:

`-p` flag causes Perl 6 interpreter to run code line by line, put current line `$_`, and at end put it back from `$_`.

`.ords` \- If there is nothing before a period, a method is called on `$_`. `ords` method returns list of codepoints in a string.

`[~]` \- `[]` is a reduction operator, which stores its reduction operator between brackets. In this case, it's `~`, which is a string concatenation operator. For example, `[~] 1, 2, 3` is equivalent to `1 ~ 2 ~ 3`.

`+` converts its argument to a number, needed because `base` method is only defined for integers.

`.base(2)` \- converts an integer to a string in base 2

`$_=` \- assigns the result to `$_`.

`s:g/..?/{...}/` \- this is a regular expression replacing any (`:g`, global mode) instance of regex `..?` (one or two characters). The second argument is a replacement pattern, which in this case in code (in Perl 6, curly brackets in strings and replacement patterns are executed as code).

`$/` \- a regex match variable

`.flip` \- inverts a string. It implicitly converts `$/` (a regex match object) to a string. This is because a single character `1` should be expanded to `10`, as opposed to `01`. Because of that flip, order of elements in array has G and C reversed.

`:2(...)` \- parses a base-2 string into an integer.

`<A G C T>` \- array of four elements.

`...[...]` \- array access operator.

What does that mean? The program gets list of all codepoints in a string, concatenates them together, converts them to base 2. Then, it replaces all instances of two or one character into one of letters A, G, C, T depending on flipped representation of a number in binary.
> 0 votes

# Answer
# Python 3, 117 bytes

This answer ignores padding. Looks like it could be shorter.

```
lambda x:''.join('ACGT'[h//4]+'ACGT'[h%4]for h in [int(h,16)for h in hex(int(''.join(map(str,x.encode()))))[2:]])[1:]

```

Try it online!
> 0 votes

# Answer
# Python 3.8 (pre-release), 92 90 bytes

Does not handle padding, but is under 100.

```
lambda x,s='':f(x,'ACGT'[v%4]+s)if (v:=int(''.join(map(str,x.encode())))>>len(s)*2) else s

```

Try it online!

# Python 3, 113 110 bytes

Spending almost 1/5 bytes on padding.

```
def f(x):
	v=int(''.join(map(str,x.encode())));v<<=len(bin(v))%2;c=''
	while v:c='ACGT'[v%4]+c;v>>=2
	return c

```

Try it online!

# Python 3.8 (pre-release), 110 bytes

```
f=lambda x,s='':f(x,'ACGT'[v%4]+s)if(v:=(u:=int(''.join(map(str,x.encode()))))<<len(bin(u))%2>>len(s)*2)else s

```

Try it online!
> 0 votes

---
Tags: code-golf, string, conversion
---