title: Print all Sundays in 2017

text:
# Question
Title: Print all Sundays in 2017
Print the dates of all the Sundays in 2017 in the following format : `dd.mm.yyyy`.
Expected Output:

```
01.01.2017
08.01.2017
15.01.2017
22.01.2017
29.01.2017
05.02.2017
12.02.2017
19.02.2017
26.02.2017
05.03.2017
12.03.2017
19.03.2017
26.03.2017
02.04.2017
09.04.2017
16.04.2017
23.04.2017
30.04.2017
07.05.2017
14.05.2017
21.05.2017
28.05.2017
04.06.2017
11.06.2017
18.06.2017
25.06.2017
02.07.2017
09.07.2017
16.07.2017
23.07.2017
30.07.2017
06.08.2017
13.08.2017
20.08.2017
27.08.2017
03.09.2017
10.09.2017
17.09.2017
24.09.2017
01.10.2017
08.10.2017
15.10.2017
22.10.2017
29.10.2017
05.11.2017
12.11.2017
19.11.2017
26.11.2017
03.12.2017
10.12.2017
17.12.2017
24.12.2017
31.12.2017

```

# Answer
> 16 votes
# Python 2, 81 bytes

```
x=0
exec"print'%05.2f.2017'%(x%30.99+1.01);x+=7+'0009ANW'.count(chr(x/7+40));"*53

```

Try it online!

No date libraries, computes the dates directly. The main trick is to treat the `dd.mm` as a decimal value. For example, `16.04.2017` (April 16) corresponds to the number `16.04`. The number is printed formatted as `xx.xx` with `.2017` appended.

The day and month are computed arithmetically. Each week adds 7 days done as `x+=7`. Taking `x` modulo `30.99` handles rollover by subtracting `30.99` whenever the day number gets too big. This combines `-31` to reset the days with `+0.01` to increment the month.

The rollover assumes each month has 31 days. Months with fewer days are adjusted for by nudging `x` upwards on certain week numbers with `+[8,8,8,17,25,38,47].count(x/7)`. These list is of the week numbers ending these short months, with `8` tripled because February is 3 days short of 31.

This list could is compressed into a string by taking ASCII values plus 40. The shift of `+40` could be avoided by using unprintable chars, and could be accessed shorter as a bytes object in Python 3.

# Answer
> 10 votes
# PHP, 48 bytes

```
while($t<53)echo gmdate("d.m.2017
",605e3*$t++);

```

### PHP, 46 bytes (for non-negative UTC offsets)

```
while($t<53)echo date("d.m.2017
",605e3*$t++);

```

# Answer
> 9 votes
# Python 2, ~~90~~ 79 bytes

-5 bytes with the help of xnor (avoid counting the weeks themselves)
-1 byte thanks to xnor (add back in e for 605000 as 605e3)

```
from time import*
i=0
exec"print strftime('%d.%m.2017',gmtime(i));i+=605e3;"*53

```

**Try it online!**

`0` seconds since epoch is 00:00:00 on the 1st of January 1970, which, like 2017 was not a leap year. `605000` seconds is 1 week, 3 minutes, 20 seconds. Adding 52 of these "weeks" does not take us beyond midnight.

# Answer
> 7 votes
# Bash + coreutils, 44 bytes

```
seq -f@%f 0 605e3 32e6|date -uf- +%d.%m.2017

```

may save 2 bytes `-u` if GMT is assumed

* Thanks Digital Trauma point out `-f` paramter for `date` which saves 10 bytes;
* And use 2017 in format string saves more bytes which idea is from the answer given by user63956

---

* `@0` is 1970-1-1
* `605000` is one week (`604800`) plus 200 sec
    + 200 sec. should just work since there are only 52 weeks in a year
* `@32000000` is just a little more than a year

# Answer
> 7 votes
# PowerShell, ~~51~~ 47

```
0..52|%{date((date 2017-1-1)+7.*$_)-u %d.%m.%Y}

```

Fairly straightforward. 2017-01-01 is a Sunday, so is every following seven days. We can save two bytes if we only need the script to be working in my lifetime:

```
0..52|%{date((date 17-1-1)+7.*$_)-u %d.%m.%Y}

```

# Answer
> 5 votes
Excel VBA ~~106~~ ~~91~~ ~~79 bytes~~

```
Sub p()
For i = #1/1/2017# To #12/31/2017#
If Weekday(i) = 1 Then MsgBox i
Next
End Sub

```

saved 15 bytes thanks to @Radhato

Assuming 1/1/2017 is Sunday it will save 12 more bytes.

```
Sub p()
For i = #1/1/2017# To #12/31/2017#
MsgBox i
i = i + 6
Next
End Sub

```

Thanks @Toothbrush **66 bytes**

```
Sub p:For i=#1/1/2017# To #12/31/2017#:MsgBox i:i=i+6:Next:End Sub

```

Edit: (Sub and End Sub is not necessary) **52 bytes**

```
For i=#1/1/2017# To #12/31/2017#:MsgBox i:i=i+6:Next

```

# Answer
> 4 votes
# PHP, 67 bytes

Using the fact the PHP automatically assign value 1 to undeclared loop variables, and using Linux epoch times,

```
<?php for(;54>$t+=1;)echo date("d.m.Y\n",604800*($t)+1482624000);?>

```

# Answer
> 4 votes
# k6, 32 bytes

```
`0:("."/|"."\)'$2017.01.01+7*!53

```

Brief explanation:

```
                2017.01.01+7*!53 /add 0, 7, 14, ..., 364 to January 1st
   ("."/|"."\)'$                 /convert to string, turn Y.m.d into d.m.Y
                                 /   split by ".", reverse, join by "."
`0:                              /output to stdout (or stderr), line by line

```

Alas, this seems to only work in the closed-source, on-request-only interpreter.

# Answer
> 4 votes
# Pyke, ~~26~~ 24 bytes

```
53 Fy17y"RVs6)c"%d.%m.%Y

```

Try it online!

```
53 F                     - for i in range(53):, printing a newline between each
    y17y"                -  Create a time object with the year 2017. (Month and days are initialised to 1.)
         RV  )           -  Repeat i times:
           s6            -   Add 1 week
              c"%d.%m.%Y -  Format in "dd.mm.yyyy" time

```

### Or 11 bytes

If allowed to ignore output format

```
y17y"52VDs6

```

Try it online!

```
y17y"       - Create a time object with the year 2017. (Month and days are initialised to 1.)
     52V    - Repeat 52 times:
        D   -  Duplicate the old time
         s6 -  Add 1 week

```

# Answer
> 3 votes
## JavaScript, ~~111~~ 106 bytes

```
for(i=14833e8;i<1515e9;i+=605e6)console.log(new Date(i).toJSON().replace(/(....).(..).(..).*/,'$3.$2.$1'))
```

Note: Stack Exchange's console isn't long enough to display the entire list, so here's the first half as a separate snippet:

```
for(i=14833e8;i<15e11;i+=605e6)console.log(new Date(i).toJSON().replace(/(....).(..).(..).*/,'$3.$2.$1'))
```

The custom format costs me 40 bytes...

# Answer
> 3 votes
## R, ~~79~~ ~~67~~ 58 bytes

```
cat(format(seq(as.Date("2017/01/01"),,7,53),"\n%d.%m.%Y"))

```

First of January being a sunday, this snippet creates a sequence of days, every 7 days starting from the 01-01-2017 to the 31-12-2017, format them to the desired format and print them.

# Answer
> 3 votes
# Befunge-98 (PyFunge), ~~99~~ ~~95~~ ~~93~~ 85 bytes, Leaves trailing newline

All the optimizations were made by @JoKing many thanks to them

```
s :1g2/10g\%:d1p10g\`+:b`#@_:1\0d1g#;1+:a/'0+,a%'0+,'.,j;a"7102"4k,d1g7+
>8><><>><><>

```

Try it online!

I felt like we were missing out on some esostericity here so I made a solution in my favourite Esosteric language.

**Explanation**:
`>8><><>><><>` Encodes the length of the 12 months
`s`  Store the old day in the blank space
`:1g2/` Get an ASCII value from the bottom row and divide it by two this gives us the length of a given month Ex: 8 = 56 in ASCII =\> 56/2 = 28 =\> The month (February) has 28 days
`10g\%` Get the previously saved day and modulo it by the length of the month which allows us to transition the date into the next month
`:d1p` Save a copy of the new updated day
`10g\`+` Test if old date \> new date =\> we transitioned into the next month =\> add 1 to the month counter
`:b``  Test if month counter \> 11 that means we reached the end of the year (using 0 indexing)
`#@_` Based on the previous if terminate the program
`:1\0d1g` Reorder the stack so it looks like this: `Month, 1, Month, 0, Day`
`#` skip the next insctruction (duh)
`1+:a/'0+,a%'0+,'.,` Convert the number to 1 indexing, print, add a `.` at the end
`j;` Use the 0 from the stack to not jump and use the `;` to go to to the print schedule again then use the 1 to jump over the `;` next time
`a"7102"4k,` Print `2017\n`
`d1g` Get the day value again `7+` Add a week before repeating

# Answer
> 2 votes
# Perl 5, 64 bytes

```
use POSIX;print strftime"%d.%m.%Y\n",0,0,0,7*$_+1,0,117for 0..52

```

Try it online!

The task given was 2017, not any year, so I hardcoded in:

* 117 (which is perlish for year 2017, 1900+117)
* +1 because 1st of January is a sunday in 2017
* 0..52 because 2017 have 53 sundays

POSIX is a core module and is always installed with Perl5. Doing the same without using modules in 101 bytes, removing whitespace:

```
$$_[5]==117&&printf"%02d.%02d.%d\n",$$_[3],$$_[4]+1,$$_[5]+1900
  for map[gmtime(($_*7+3)*86400)],0..1e4

```

# Answer
> 2 votes
# Mathematica ~~90~~ 84 bytes

Fairly wordy. numbermaniac and Scott Milner saved 5 and 1 bytes, respectively.

```
Column[#~DateString~{"Day",".","Month",".","Year"}&/@DayRange["2017","2018",Sunday]]

```

# Answer
> 2 votes
# Ruby, 75 bytes

Straightforward solution to figure out the dates with `Time`.

```
t=Time.new 2017
365.times{puts t.strftime("%d.%m.%Y")if t.sunday?
t+=86400}

```

# Answer
> 2 votes
## SAS, ~~52~~ 50 bytes

Saved 2 bytes thanks to @user3490.

```
data;do i=20820to 21184 by 7;put i ddmmyyp10.;end;

```

# Answer
> 1 votes
# C#, 138 111 102 bytes

*Saved 9 more bytes thanks to Johan du Toit!*

*Saved 27 bytes thanks to Kevin Cruijssen's suggestions!*

```
()=>{for(int i=0;i<53;)Console.Write(new DateTime(2017,1,1).AddDays(7*i++).ToString("dd.MM.yyyy\n"));}

```

Anonymous function which prints all Sundays in 2017.

Full program with ungolfed method:

```
using System;

class P
{
    static void Main()
    {
        Action f =
        ()=>
        {
            for (int i = 0; i < 53; )
                Console.Write(new DateTime(2017, 1, 1).AddDays(7 * i++).ToString("dd.MM.yyyy\n"));
        };

        f();
    }
}

```

# Answer
> 1 votes
# VBA, 81 bytes (maybe 64)

```
Sub p()
For i = 0 To 52
MsgBox format(42736 + i * 7, "dd.mm.yyyy")
Next i
End Sub

```

My first post. Building on newguy's solution by removing the check for weekdays and just specifying every 7th day. Removing the dates saves 12 bytes a piece. 42736 is 1/1/2017. Output date format depends on system setting. Is that allowed? If so, it's 64 bytes because you don't need the *format* method.

```
MsgBox #1/1/2017# + i * 7

```

# Answer
> 1 votes
# AHK, 67 bytes

```
d=20170101
Loop,52{
FormatTime,p,%d%,dd.MM.yyyy
Send,%p%`n
d+=7,d
}

```

Nothing magical happens here. I tried to find a shorter means than `FormatTime` but I failed.

# Answer
> 1 votes
# Java 8+, ~~104~~ ~~100~~ 99 bytes

```
()->{for(int t=0;t<53;)System.out.printf("%1$td.%1$tm.2017%n",new java.util.Date(t++*604800000L));}

```

# Java 5+, ~~109~~ ~~105~~ 104 bytes

```
void f(){for(int t=0;t<53;)System.out.printf("%1$td.%1$tm.2017%n",new java.util.Date(t++*604800000L));}

```

Uses the date-capabilities of the `printf` format.

Test it yourself!

## Savings

1. 104 -\> 100: changed the loop values and the multiplicand.
2. 100 -\> 99: golfed the loop

# Answer
> 1 votes
# T-SQL, 94 Bytes

```
DECLARE @ INT=0,@_ DATETIME='2017'W:SET @+=1SET @_+=7PRINT FORMAT(@_,'dd.MM.yyy')IF @<52GOTO W

```

if you don't like SQL GOTO or WHILE, here is a 122 bytes CTE solution

```
WITH C AS(SELECT CAST('2017'AS DATETIME)x UNION ALL SELECT x+7FROM C WHERE X<'12-31-17')SELECT FORMAT(x,'dd.MM.yyy')FROM C

```

# Answer
> 1 votes
# Ruby, 60+7 = 67 bytes

Uses the `-rdate` flag.

```
(d=Date.new 1).step(d+365,7){|d|puts d.strftime"%d.%m.2017"}

```

# Answer
> 1 votes
# Groovy, ~~81~~ ~~77~~ ~~63~~ ~~60~~ 56 bytes

```
d=new Date(0);53.times{printf('%td.%<tm.2017%n',d);d+=7}

```

The above can be run as groovy script.

My first code golf entry. Fortunately, the year 1970 was not a leap year, thus can use it as a base.

Thanks to Dennis, here's a: Try it online!

# Answer
> 1 votes
# C#, ~~110~~ 109 bytes

```
using System;()=>{for(int i=42729;i<43100;Console.Write(DateTime.FromOADate(i+=7).ToString("dd.MM.yyy\n")));}

```

You can enjoy this program online here

In this soluion we :

* Use OLE Automation Date (OADate) to avoid "AddDay()" from datetime.
`FromOADate()` seem big but it's equal to `new DateTime(2017,1,1)`
* Start the loop on the last sunday of 2016. to allow us to increment with operator `+=` only. This operator return the value after the increment is done.
* Increment by 7 days to jump from sunday to sunday before printing the date.
* We stop once the last sunday of 2017 has been hit.
* ~~Use `Debug` instead of `Console` to save two characters~~
* Avoid having explicit variable declaration and assignment

# Answer
> 1 votes
# TSQL, ~~112~~ 105 bytes

```
SELECT CONVERT(VARCHAR,DATEADD(d,number*7,42734),104)FROM master..spt_values WHERE type='p' AND number<53

```

Demo

T-SQL Convert Syntax

# Answer
> 1 votes
# T-SQL, ~~79~~ 77 Bytes

After helping Salman A improve his answer. I decided to write my own using a loop and `PRINT`.

I ended with this 90 bytes solution.

```
DECLARE @d DATETIME=42734 WHILE @d<43100BEGIN PRINT CONVERT(VARCHAR,@d,104)SET @d=@d+7 END

```

Then I looked at the current leader in T-SQL which was 94 bytes from WORNG ALL with this answer. This guy had found very good tricks.

1. Name the variable only `@`
2. Loop with `GOTO` instead of actual LOOP
3. Save one character using `FORMAT` instead of `CONVERT`. (SSMS2012+ only)

Using these tricks, this solution was trimmed down to the solution below which is 79 bytes.

```
DECLARE @ DATETIME=42734G:PRINT FORMAT(@,'dd.MM.yyy')SET @+=7IF @<43100GOTO G

```

# Answer
> 1 votes
# JavaScript (ES6), 123 bytes

It's my first post here, hello!

```
a=x=>`0${x}.`.slice(-3);[].map.call('155274263153',(x,i)=>{for(j=0;j<4+(2633>>i&1);j++)console.log(a(+x+j*7)+a(i+1)+2017)})

```

This solution uses hardcoded data and is designed to work specifically for the year 2017. It relies on no date/time APIs.

As for the digits in the string `155274263153`, each digit is a number of its own and denotes the first Sunday of each consecutive month. Output for the entire year can be generated by successively adding 7 to those.

What about the magic number, `2633`, used in the loop?
Well... `2633` (decimal) is `101001001001` in binary. Now what could those `1`s mean? Starting from the right, the 1st, 4th, 7th, 10th and 12th bit are set. This corresponds to months which happen to have five Sundays, as opposed to those that have only four. Golfed down to this neat expression, it initially looked like this: `for(j=0;j<4+ +[0,3,6,9,11].includes(i);j++)`.

I guess the remaining parts are fairly self-explanatory.

# Answer
> 1 votes
# Octave, 37 bytes

A lot shorter than all other non-golfing languages, and it's even tied with Jelly! Way to go Octave! :)

```
disp(datestr(367:7:737,'DD.mm.2017'))

```

Try it online!

Luckily, year `2 AD` looks exactly the same as year `2017 AD`. Both starts and ends at a Sunday, and neither is a leap year. This saves a lot of bytes, since `367:7:737` is quite a bit shorter than `736696:7:737060`.

This converts the number of days since `01.01.0001`, to a string on the format `DD.mm`, with a trailing `.2017`.

# Answer
> 1 votes
# Haskell, ~~133~~ 130 bytes

```
import Data.Time.Calendar
((\[f,g,h,i,j]->i:j:'.':f:g:".2017\n").drop 5.show)=<<take 53(iterate(addDays 7)$fromGregorian 2017 1 1)

```

Try it online!

### Without a calendar library, ~~148~~ ~~144~~ 140 bytes

```
(\l->last l!l++length l!l++"2017\n").fst.span(>0).(<$>scanl((+).(+28))0[3,0,3,2,3,2,3,3,2,3,2]).(-)=<<[1,8..365]
a!_=['0'|a<=9]++show a++"."

```

This is funny since using an operator for the padding function saves two bytes even though the second argument is unused, because less parentheses are needed – `p(last l)` is longer than `last l!l`. Works by calculating `day/month` pairs by subtracting the cumulative month start dates from the day of the year. The month start dates are compressed as (`scanl((+).(+28))0[3,0,3,2,3,2,3,3,2,3,2]`). Month number is the number of positive elements and day number is the last positive element.

Try it online!

# Answer
> 0 votes
## C#, 116 114 113 bytes

`for(long i=(long)636188256e9;i<636502857e9;i+=(long)605e10)Out.Write(new DateTime(i).ToString("dd.MM.yyyy\n"));`

Can be run in the interactive windows of Visual Studio (or any other C# REPL based on Roslyn)

Down to 113 bytes: thanks to Kevin Cruijssen.

# Answer
> 0 votes
# Java 7, ~~145~~ ~~144~~ 142 bytes

```
void c(){for(long x=604800000,i=-x;i<52*x;)System.out.println(new java.text.SimpleDateFormat("dd.MM.2017").format(new java.util.Date(i+=x)));}

```

-2 bytes thanks to Cliffroot due to a stupid mistake of me..

Try it here.

**Explanation:**

```
void c(){                                  // Method
  for(long x=604800000,                    //  Initialize `x` as 604,800,000
           i=-x;                           //  Initialize `i` as `-x` / -604,800,000 as starting number
      i<52*x;)                             //  Loop over all 52 weeks
    System.out.println(new java.text.SimpleDateFormat("dd.MM.2017")
      .format(new java.util.Date(i+=x)));  //   Raise `i` by `x` and then print it in the format `dd.MM.2017`
                                           //  End of loop (implicit / single-line body)
}                                          // End of method

```

# Answer
> 0 votes
# SpecBAS - 61 bytes

```
1 FOR i=42736 TO 43100 STEP 7: ?DATE$(i,"dd.mm.yyyy"): NEXT i

```

Dates are a decimal number starting at 30-Dec-1899, so had to work out what 1 Jan 2017 and 31 Dec 2017 were, then just step through those values adding 7 days each time.

# Answer
> 0 votes
# Java 7, 126 bytes

```
void e(){for(int i=0,j=1,k;i<12;j%=k)for(k="(%('('(('('(".charAt(i++)-9;j<k+1;j+=7)System.out.format("%02d.%02d.2017\n",j,i);}

```

Computes everything manually. The string `"(%('('(('('("` encodes number of days in month. Outer loop goes from 0 to 11 (number of months), inner loops goes until the number representing day is greater than number of days in this month.

See it online

# Answer
> 0 votes
## SQL (PostgreSQL), 74 Bytes

```
SELECT to_char(generate_series('170101'::date,'171231','7d'),'DD.MM.YYYY')

```

If output must be in a single string rather than individual records then the query can be run from psql with the -tA options, making it 76 bytes.

# Answer
> 0 votes
## REXX, 91 bytes

```
do n=1 to 365
  if date(w,n,d)='Sunday' then say left(translate(date(e,n,d),.,'/'),6)2017
  end

```

# Answer
> 0 votes
## c, ~~119~~ ~~116~~ 114 bytes

```
y=2017,m=1,d=1,i=53,v;main(){for(;i--;)printf("%02d.%02d.%d\n",d,m,y),v=m^2?m%2^m<8?30:31:28,(d+=7)>v?++m,d-=v:0;}

```

Try it online

# Answer
> 0 votes
# SQL (Oracle), 137 bytes

```
select substr(d,1,10)
from (select to_char(sysdate-1e4+rownum,'DD.MM.YYYYdy') d from dual connect by rownum<=2e4)
where d like '%2017s%';

```

# Answer
> 0 votes
# Jelly,  ~~38~~  37 bytes

-1 thanks to user202729 (use the  quick I implemented about a month after this answer.)

```
Ḋ€;⁽¥Ñj”.
“£hṅ’ṃ“þœ÷‘R,€"J$;/m7+³DÇ€Y

```

Jelly currently has no date type or way of representing a date natively, so a purely numeric approach is required.

**Try it online!**

### How?

```
Ḋ€;⁽¥Ñj”. - Link 1, format helper: list of lists   e.g. [[x,0,2],[x,0,7]] (for 2nd July)
Ḋ€        - dequeue €ach                                [[0,2],[0,7]]
   ⁽¥Ñ    - literal 2017                                2017
  ;       - concatenate                                 [[0,2],[0,7],2017]
       ”. - character '.'
      j   - join                                        [0,2,'.',0,7,'.',2017]
              which has the representation:             "02.07.2017"

“£hṅ’ṃ“þœ÷‘R,€"J$;/m7+³DÇ€Y - Main link: no arguments
“£hṅ’                       - base 250 compressed number 213991
      “þœ÷‘                 - code-page indexes [31,30,28]
     ṃ                      - base decompression: 213991 base length([31,30,28])
                                = [1,0,1,2,1,2,1,1,2,1,2,1]; indexed into [31,30,28]
                                = [31,28,31,30,31,30,31,31,30,31,30,31]
           R                - range (vectorises): [[1,2,...,31],[1,2,...,28],...]
                $           - last two links as a monad:
               J            -     range(length): [1,2,3,4,5,6,7,8,9,10,11,12]
              "             -     zip with:
            ,€              -         pair for €ach: [[[1,1],[2,1],...,[31,1]],[[1,2],[2,2],...,[28,2]],...]
                 ;/         - reduce with concatenation: [[1,1],[2,1],...,[31,1],[1,2],[2,2],...,[28,2],...]
                   m7       - every 7th item: [[1,1],[8,1],...,[24,12],[31,12]]
                      ³     - 100
                     +      - add (vectorises): [[101,101],[108,101],...[124,112],[131,112]]
                       D    - to decimal (vectorises): [[[1,0,1],[1,0,1]],[[1,0,8],[1,0,1]],...,[[1,2,4],[1,1,2]],[[1,3,1],[1,1,2]]]
                        Ç€  - call last link as a monad for €ach: [[0,1,'.',0,1,'.',2017],[0,8,'.',0,1,'.',2017],...,[2,4,'.',1,2,'.',2017],[3,1,'.',1,2,'.',2017]]
                          Y - join with line feeds: [0,1,'.',0,1,'.',2017,'\n',0,8,'.',0,1,'.',2017,'\n',...,'\n',2,4,'.',1,2,'.',2017,'\n',3,1,'.',1,2,'.',2017]
                            - implicit print

```

# Answer
> 0 votes
# Python 3.6, 94 bytes

```
from datetime import*
for x in range(53):print(f"{datetime(1,1,1)+timedelta(x*7):%d.%m.2017}")

```

I wanted to try using high-level features. Well, it's still readable but not that short…

# Answer
> 0 votes
# T-SQL, 141 bytes

```
SELECT FORMAT(d,'dd.MM.yyyy')FROM(SELECT DATEADD(ww,ROW_NUMBER()OVER(ORDER BY name)-1,'20170101')d FROM sys.stats)a WHERE 2017=DATEPART(yy,d)

```

Try it here

# Answer
> 0 votes
## k, 36 Bytes

Same approach as zgrep. 2017.01.01+0 7 14..., string it, split it on ".", reverse each and join back on "." - finally print the list of strings e.g. `-1@("Print";"me");`

```
-1@"."/:'|:'"."\:'$2017.01.01+7*!53;

```

# Answer
> 0 votes
# Oracle SQL, 89 bytes

```
    select to_char(to_date('25-DEC-16')+level*7,'DD.MM.YYYY') from dual connect by level < 54

```

Explanation: You can just add an integer to a date and it's treated as a number of days. Exploiting connect by we're generating 53 rows for the 53 sundays which occur in 2017. Setting the starting date as the last sunday of 2016 saves me two bytes because I don't have to subtract 7 to compensate `level` starting at 1.

# Answer
> 0 votes
**Microsoft Sql Server, 114 bytes**

```
with v as(select 0 n union all select n+7 from v where n<364)select format(dateadd(d,n,'2017'),'dd.MM.yyyy')from v

```

Check It Online

# Answer
> 0 votes
# 05AB1E, ~~81~~ 79 bytes

```
•8tåxвÓÈCм∞º²áÝViΣþ1₄É¨Å9”ÓU2Èn¶äΔb'Î?™Íćεr$Ã]7¤¶¸M•11BR'A¡vy2ôN>".ÿ.2017"«})˜»

```

Try it online!

No date built-ins.

---

```
01081522A05121926A05121926A0209162330A07142128A04111825A0209162330A06132027A03101724A0108152229A05121926A0310172431

```

Is the compressed base-11 number at the beginning, when split on A's you get:

```
['01081522', '05121926', '05121926', '0209162330', '07142128', '04111825', '0209162330', '06132027', '03101724', '0108152229', '05121926', '0310172431']

```

Which is the days of each month that are Sundays, in order. Then, we split each one into pieces of two, and concatenate the index of those days plus 2017 to each.

Finally we just flatten and return the list separated by newlines.

# Answer
> 0 votes
# Tcl, 80 bytes

```
time {puts [clock format [expr 1482624000+[incr i 604800]] -format %d.%m.%Y]} 53

```

Try it online!

# Answer
> 0 votes
# Japt `-R`, ~~25~~ ~~21~~ 15 bytes

Locale dependent - You'll need to set your browser's locale to (among others, I'm sure) Romania (`RO`), Russia (`RU`) or Turkey (`TR`) for the dates to be formatted correctly.

```
#5ÆÐ#É7TX*7Ä s7

```

Test it

---

## Explanation

Takes advantage of the fact that if you provide JavaScript's date construct a value for the day that's higher than the number of days in the month you've provided, it will rollover to the next month.

```
#5                        :53
  Æ                       :Create the range [0,53) and pass each integer X through a function
    #É7                   :  2017
       T                  :  0
        X*7Ä              :  X*7+1
   Ð                      :  new Date() with those 3 arguments as year, month & day
             s7           :  Convert to date string, locale formatted

```

# Answer
> 0 votes
# JavaScript, 80 bytes

```
(f=x=>x?[...f(--x),new Date(2017,0,x*7+1).toLocaleDateString()]:[])(53).join`
`

```

# Answer
> 0 votes
# Pyth, 122 bytes

```
jm+X2d\.".2017"c+\0`i."0Z|´&ÓäßæÅJÈD@ßÍTû=´}¾}Zàe+ñðºâ$Ã°Gzdüä#Ò×ûíO^©¢Q Óýo`Åi2ÓàÀ{9¢à>«+íø#o^Mý"36 4

```

Try it online!

### The code uses unprintable characters that are not displayed properly on Stack Exchange. Use the link to get the working version.

Pyth doesn't have a way to check whether a date is a Sunday, so this is the Kolmogorov version.
It uses a MAGIC STRING which represents this integer.

Explanation:
```
jm+X2d\.".2017"c+\0`i."…"36 4 # Code with MAGIC STRING replaced with …
                   `          # String representation of
                      "…"     # THE MAGIC STRING
                     ."       # Decompressed
                    i    36   # To int from base 36
                +\0           # With a 0 in front
               c            4 # Chopped into strings of length 4 as a list
 m                            # With each member
   X2d\.                      #  with . inserted at index 2
  +     ".2017"               #  and appended with .2017
j                             # Joined with newlines

```

# Answer
> 0 votes
# Red, 107 bytes

```
f: func[n][n: pad/left/with to-string n 2 #"0"]d: 1-1-2
loop 53[print rejoin[f d/3":"f d/4":"2017]d: d + 7]

```

Try it online!

# Answer
> 0 votes
## Groovy, 52 bytes

```
53.times{printf('%td.%<tm.2017%n',new Date(0)+it*7)}

```

Building on Krystian's groovy answer above with an optimisation dropping another four bytes. Uses the fact that the epoch year 1970 matches 2017 weekdays and months.

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


title: Golfing out the haters

text:
# Question
Title: Golfing out the haters
## The setup:

A social network reports the number of votes a post has in two ways: the number of **net upvotes** (total upvotes - total downvotes), and the **% of votes that were upvotes**, rounded to the nearest integer (.5 rounds up). The number of net upvotes is an integer (not necessarily positive), and the second is guaranteed to be an integer between 0 and +100 inclusive. The number of upvotes and the number of downvotes are both either zero or positive 32-bit integers (you can specify signed or unsigned). Assume that if there are zero total votes, the percentage upvoted is reported as zero.

## The challenge:

Given these two integers (net upvotes and % upvoted), what is the shortest program you can write which determines the lowest number of **total upvotes** the post received, with all the constraints above satisfied?

Input constraints are guaranteed. If the input does not satisfy the constraints above, the program behavior is up to you. Bonus kudos if it doesn't enter an infinite loop or otherwise crash. Consider returning a negative number if you want more guidance.

## General rules:

* This is , so the shortest valid solution (measured in bytes) wins.
* Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language. Bonus kudos for a client-side Web language like Javascript.
* If you have interesting solutions in multiple languages, post them separately.
* Standard rules apply for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, or full programs. Your call.
* Default loopholes are forbidden.
* If possible, please add a link with a test for your code.
* Also, please add an explanation of how the code works.
* Keep in mind that if you are doing an integer division operation that *truncates* (e.g. 20/3=6) rather than *rounds*, that might not be fully correct.
* Additional test cases that explore the edge cases in the above constraints are welcome.
* While the expected return type is numeric, boolean "false" can be used in place of 0.

## Example test cases:

The first column is just a reference number included to facilitate discussion.

```
ref net  %up    answer
1   0    0   => 0
2   -5   0   => 0
3   -4   17  => 1
4   -3   29  => 2
5   -2   38  => 3
6   -1   44  => 4
7   0    50  => 1
8   5    100 => 5
9   4    83  => 5
10  3    71  => 5
11  2    63  => 5
12  1    56  => 5
13  1234 100 => 1234
14  800  90  => 894  (tip: don't refer to this as the "last test case;" others may be added.)

```

# Answer
# JavaScript (ES6), 47 bytes

Takes input in currying syntax `(n)(p)`, where **n** is the number of net upvotes and **p** is the percentage of upvotes. May return `false` for `0`.

```
n=>p=>(g=u=>u/(u-n/2)*50+.5^p?g(u+1):u)(n>0&&n)

```

Try it online!

### Commented

```
n => p => (          // given n and p
  g = u =>           // g = recursive function taking u = number of upvotes
    u / (u - n / 2)  //   compute u / (total_votes / 2)
    * 50 + .5        //   turn it into a percentage, add 1/2
    ^ p ?            //   XOR it with p, which gives 0 if the integer parts are matching
                     //   if the result is not equal to 0:
      g(u + 1)       //     try again with u + 1
    :                //   else:
      u              //     stop recursion and return u
)(n > 0 && n)        // initial call to g() with u = max(0, n)

```

### Edge cases

Let **Fn(u) = u / (u - n / 2) * 50 + 0.5**

* If **u = 0** and **n = 0**, then **Fn(u) = NaN** and **Fn(u) XOR p = p**. So, we return **u = 0** if **n = p = 0** (first iteration of the first test case) or continue with the recursion if **p != 0** (first iteration of the 7th test case).
* If **u \> 0** and **u = n / 2**, then **Fn(u) = +Infinity** and -- again -- **Fn(u) XOR p = p**. Unless **p = 0**, we just go on with the next iteration. (This happens in the 9th and 11th test cases.)
> 10 votes

# Answer
# Stax, 17 bytes

```
ëI╩½• ╠☺Vì∞«S↑♠αS

```

Run and debug it

This is brute force. It starts with 0 for candidate upvotes, and increments until it satisfies the formula.

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

```
0       push zero
{       start filter block...
        candidate upvotes is on the stack
  cHx-  calculate candidate downvotes for denominator (upvotes * 2 - net)
  c1?   if denominator is zero, replace it with 1
  :_    floating point division
  AJ*   multiply by 100
  j     round to integer
  ;=    is equal to second input?
        increment until a match is found
}gs

```

Run this one
> 7 votes

# Answer
# Clean, ~~114~~ ~~107~~ 104 bytes

```
import StdEnv
? =toReal o toInt
$a d#e= ?d
= ?a+until(\c#b= ~c*e/(e-100.0)
= ?(?100*b/(?b+c))==e)inc 0.0

```

Try it online!

Defines the function `$ :: Int Int -> Real`, where the arguments are signed integers and the return value is a double-precision float exactly representable by a 32-bit signed integer.

It checks every value of `c` in the equation `b=-cd/(d+1)` to find a `b` satisfying `a+c=b` and `b/(b+c)=d`, since the smallest `c` results in the smallest `b`, take the first element of the set of all solutions.
> 2 votes

# Answer
# 05AB1E, 13 bytes \[mildly broken\]

```
*²·т-/ò²т;Qi1

```

Try it online!

Explanation:

To solve this, I assumed inputs a, b and expected result x. Given the info in the setup, that gave me the equation:

```
 2x         100x
———— - a = ——————
 a           b

```

Rearranging for x gives

```
        ab
x = ——————————
     2b - 100

```

The only test case this doesn't work for is 0, 50 - I simply hardcoded to check for this.

```
*²·т-/ò²т;Qi1     Implicit Inputs: a, b              STACK (bottom to top)
*                 Multiply the inputs together       [ab]
 ²·               Take the second input * 2          [ab, 2b]
   т-             Subtract 100                       [ab, 2b - 100]
     /ò           Divide and round                   [round(ab/(2b-100))]
       ²т;Qi1     If 2nd input = 50, push 1 to stack
                  { Implicitly output top item of stack [either 1, or round(...)] }

```
> 2 votes

# Answer
# Go 1.10, 154 bytes

```
func h(n,u float64)float64{if u==50{return 1};r:=Round(n*u/(2*u-100));s:=Round(n*(u+.5)/(2*u-99));v:=s/(2*s-n);if v>1||Round(v*100)!=u{return r};return s}

```

Try it on Go Playground! (TIO runs Go 1.9, which doesn't have math.Round)

Ungolfed version

```
func haters(n, u float64) float64 {
    if u == 50 {
        return 1
    }
    r := Round(n * u / (2*u - 100))
    //Test the case where we were given a percentage that was rounded down (e.g. 90.4% given as 90%)
    //We test this by adding 0.5% to u. The denominator is just a simplified form of 2*(u+0.5) - 100
    s := Round(n * (u + .5) / (2*u - 99))
    //Check if s is a valid result
    v := s / (2*s - n)
    if v > 1 || Round(v*100) != u {
        return r
    }
    //s is strictly less than r, so we don't need to check the minimum.
    return s
}

```

In the interests of adding an explanation, the above formula for r can be derived by simultaneously solving `n=v-d` and `u = 100 * v/(v + d)` for v, where v and d are the number of upvotes and downvotes respectively. The derived formula is undefined for v = 50, so we have to handle that case (which we do with the first if statement).
> 0 votes

---
Tags: code-golf, math, arithmetic
---


title: Return every N-th word of a string

text:
# Question
Title: Return every N-th word of a string
Your goal is to write a program that, given a number *N* and a string as input, will return a string containing every *N*th word of the original string, starting from the first word.

Sample inputs/outputs:

```
N = 2, str = "This is a sentence"

"This a"
--
N = 2, str = "The quick brown fox jumped over the lazy dog."

"The brown jumped the dog."
--
N = 7, str = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa."

"Lorem elit. massa."

```

You're allowed to assume that the input will always contain at least *N+1* words, and that words will always be delimited by the space character ` `.

This is , so the shortest answer in bytes wins.

# Answer
> 7 votes
# Pyth, 6

```
jd%Qcz

```

Splits on spaces, takes every Nth element, joins on spaces.

Try it online

# Explanation

```
jd          : join on spaces
  %Q        : take every Qth character (Q will have read the input with N)
    cz      : chop the other input on whitespace

```

# Answer
> 4 votes
# CJam, 7 bytes

```
q~S/%S*

```

Test it here. This reads a number and a string (in that order) from STDIN.

## Explanation

```
q~      e# Read and eval input.
  S/    e# Split on spaces.
    %   e# Take every Nth element.
     S* e# Join the words back together with spaces.

```

# Answer
> 3 votes
# Python, 35 characters

```
lambda n,s:' '.join(s.split()[::n])

```

# Answer
> 2 votes
# KDB(Q), 26 bytes

```
{" "sv#[0N,y;" "vs x][;0]}

```

# Explanation

```
             " "vs x         / cut x string by space
      #[0N,y;       ]        / cut list by y length
                     [;0]    / take first of each list
 " "sv                       / combine with space
{                        }   / lambda

```

# Test

```
q){" "sv#[0N,y;" "vs x][;0]}["The quick brown fox jumped over the lazy dog.";2]
"The brown jumped the dog."

```

# Answer
> 1 votes
# Julia, 38 bytes

```
(n,s)->join(split(s," ")[1:n:end]," ")

```

This creates an anonymous function that accepts an integer and string as input and returns the required output. To call it, give it a name, e.g. `f=(n,s)->...`.

Ungolfed + explanation:

```
function f(n, s)
    # Split the string into words
    words = split(s, " ")

    # Get every nth word starting at 1
    every_nth = words[1:n:end]

    # Join into a single string separated with a space
    join(every_nth, " ")
end

```

Examples:

```
julia> f(2, "The quick brown fox jumped over the lazy dog.")
"The brown jumped the dog."

julia> f(2, "This is a sentence.")
"This a"

```

# Answer
> 1 votes
# Jelly, 3 bytes (language postdates challenge?)

```
ḲmK

```

splits the first input on spaces; `m` takes every nth element; then `K` joins on spaces again. `m` is missing a second argument, so it takes the second input by default.

Try it online!

# Answer
> 0 votes
# 12-basic, 42 bytes

```
?JOIN(INPUT$().SPLIT(" ")STEP INPUT()," ")

```

Try

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


title: Generate a US License Plate

text:
# Question
Title: Generate a US License Plate
Given one of the following as input:

```
AK,AR,AS,AZ,CA,CT,DC,FL,GA,IL,IN,IA,KS,KY,LA,MD,MI,MN,MS,NV,NH,NJ,NM,NY,NC,ND,MP,OH,OK,OR,PA,PR,RI,SC,TN,TX,UT,VT,VA,WA,WI

```

(with quotes)

```
"AK","AR","AS","AZ","CA","CT","DC","FL","GA","IL","IN","IA","KS","KY","LA","MD","MI","MN","MS","NV","NH","NJ","NM","NY","NC","ND","MP","OH","OK","OR","PA","PR","RI","SC","TN","TX","UT","VT","VA","WA","WI"

```

Generate and output a (uniformly) random license plate of the format matching the input. If there are multiple (comma separated) formats, use a (uniformly) random format:

```
AK, IA, MS, MP, VT: AAA 000
AS: 0000
AZ, GA, WA: AAA0000
AR, KS, KY, LA, ND, OR: 000 AAA
CA: 0AAA000
CT: AA-00000
DC: AA-0000
FL: AAA A00
IL: AA 00000
IN: 000A,000AA,000AAA,AAA000
MD: 0AA0000
MI: AAA 0000,0AA A00,AAA 000
MN: 000-AAA
NV: 00A-000
NH: 000 0000
NJ: A00-AAA
NM: 000-AAA,AAA-000
NY, NC, PA, TX, VA, WI: AAA-0000
OH: AAA 0000
OK: 000AAA
PR: AAA-000
RI: 000-000
SC: AAA 000,000 0AA
TN: A00-00A
UT: A00 0AA

```

Where `A` means a random character in the uppercase alphabet minus `IOQ` and `0` means a random single digit number (`0` to `9`).

All information from Wikipedia. These (states) were all of the ones that I understood and that didn't have wonky rules.

This is , so shortest answer in bytes wins!

# Answer
> 3 votes
# Perl 6, ~~492~~ 350 bytes

```
{$_=('AKIAMSMPVT:7 3AS:4AZGAWA:74ARKSKYLANDOR:3 7CA:173CT:6-5DC:6-4FL:7 52IL:6 5IN:35,36,37,73MD:164MI:7 4,16 52,7 3MN:3-7NV:25-3NH:3 4NJ:52-7NM:3-7,7-3NYNCPATXVAWI:7-4OH:7 4OK:37PR:7-3RI:3-3SC:7 3,3 16TN:52-25UT:52 16'~~/$^a
[..]*?\:(<[\d]+[-\ ]>+)+%\,/)[0].pick;s:g/<[567]>/{[~]
(('A'..'Z')∖<I O Q>).pick xx($/-4)}/;S:g/\d/{[~] (^10).pick xx$/}/}

```

Try it online!

I was so far ahead after my first attempt, I didn't make much of an effort to pare the code down. Now I have.

In my encoding of the license plate patterns, the numbers 1-4 indicate a run of that many random digits, and the numbers 5-7 indicate of run of random permitted letters, of length four less than the number.

# Answer
> 6 votes
# Python3, ~~861~~ ~~821~~ ~~819~~ ~~714~~ ~~678~~ ~~674~~ ~~670~~ ~~662~~ ~~661~~ ~~658~~ ~~596~~ ~~591~~ ~~561~~ ~~555~~ ~~551~~ 536 bytes.

-8 bytes thanks to @DestructibleLemon (`b=a+`... and `d=B`...), -15 bytes thanks to @Felipe Nardi Batista (useless lambda and variable)

And thanks to everyone over in chat who helped golf this!

```
from random import*
C=choice
Z='000'
A='AAA'
B=A+'-0'+Z
a=A+' '+Z
b=A+'0'+Z
c=a[::-1]
d=B[1:]
print(C(''.join(C(['ABCDEFGHJKLMNPRSTUVWXYZ','0123456789',i]['A0'.find(i)])for i in([a]*5+[Z+'0',b,b,b]+[c]*6+['0'+A+Z,d,d+'0',A+' A00','AA 00'+Z,Z+'A,000AA,000AAA,'+A+Z,'0AA0'+Z,a+'0,0AA A00,'+a,Z+'-'+A,'00A-'+A,Z+' 0'+Z,'A00-'+A,Z+'-AAA,AAA-'+Z]+[B]*6+[a+'0',Z+A,B[:-1],Z+'-'+Z,a+','+c,'A00-00A','A00 0AA'])[[*zip('AIMMVAAGWAKKLNOCDCFIIMMMNNNNNNPTVWOOPRSTU','KASPTSZAARSYADRACTLLNDINVHJMYCAXAIHKRICNT')].index(tuple(input()))]).split(',')))

```

Try it online

Any golfing suggestions are welcome (and wanted). And, please, if you spot any errors, just tell me via the comments!

# Answer
> 6 votes
## JavaScript (ES6), ~~374~~ 368 bytes

```
s=>(P=n=>parseInt(n,36),R=Math.random,g=F=>F?(' -'+(R()*10|0)+'ABCDEFGHJKLMNPRSTUVWXYZ'[R()*23|0])[F&3]+g(F>>2):'')(P('8cf,4q,8fz,ch6,8hq,xpb,8f3,8jj,xov,6i|ru|356|24f,8fy,xmn|8ji|8cf,ciy,8e2,xm2,ciz,ciy|8e7,xof,xmn,356,8e7,8dm,8cf|ca2,bjf,ca3'.split`,`[P('1k3600d2mha35h7bi00jc000o03000000809l002003n0h3032e0fh4g0h'[P(s)%159%131%70%58])].split`|`.sort(_=>R()-.5)[0]))

```

### Formatted and commented

In the following code, data sections have been truncated. Missing parts are marked with `(...)`.

```
s => (                                  // given the state s
  P = n => parseInt(n, 36),             // P = base-36 parsing function
  R = Math.random,                      // R = random generator
  g = F =>                              // g = recursive function taking an encoded format F
    F ?                                 // if the format has not been yet fully processed:
      (                                 //   build a string consisting of:
        ' -' +                          //     0: space, 1: hyphen
        (R() * 10 | 0) +                //     2: a random digit
        'ABCD(...)YZ'[R() * 23 | 0]     //     3: a random uppercase letter (minus I, O, Q)
      )[F & 3] +                        //   pick the next character from this string
      g(F >> 2)                         //   recursive call, dropping the 2 consumed bits
    :                                   // else:
      ''                                //   stop recursion
  )(                                    // initial call to g():
    P(                                  //   base-36 decoding of a format picked from
      '8cf,4q,(...),ca3'.split`,`[      //     a list of binary encoded formats
        P(                              //       accessed through a base-36 decoded index
          '1k36(...)0h'[                //         picked from a lookup-table of 58 entries
            P(s) % 159 % 131 % 70 % 58  //           based on a hash of the state
          ]                             //         end of lookup-table access
        )                               //       end of lookup-table index decoding
      ].split`|`                        //     end of list access / split it on '|'
      .sort(_ => R() - .5)[0]           //     randomly pick a format from this list
    )                                   //   end of format decoding
  )                                     // end of call

```

### Demo

```
let f =

s=>(P=n=>parseInt(n,36),R=Math.random,g=F=>F?(' -'+(R()*10|0)+'ABCDEFGHJKLMNPRSTUVWXYZ'[R()*23|0])[F&3]+g(F>>2):'')(P('8cf,4q,8fz,ch6,8hq,xpb,8f3,8jj,xov,6i|ru|356|24f,8fy,xmn|8ji|8cf,ciy,8e2,xm2,ciz,ciy|8e7,xof,xmn,356,8e7,8dm,8cf|ca2,bjf,ca3'.split`,`[P('1k3600d2mha35h7bi00jc000o03000000809l002003n0h3032e0fh4g0h'[P(s)%159%131%70%58])].split`|`.sort(_=>R()-.5)[0]))

;[
  'AK','AR','AS','AZ','CA','CT','DC','FL','GA','IL','IN','IA','KS','KY',
  'LA','MD','MI','MN','MS','NV','NH','NJ','NM','NY','NC','ND','MP','OH',
  'OK','OR','PA','PR','RI','SC','TN','TX','UT','VT','VA','WA','WI'
]
.forEach(s => console.log(s + ' --> ' + f(s)))
```

# Answer
> 5 votes
# T-SQL, ~~1104 1100 797~~ 657 bytes

```
DECLARE @ CHAR(8)SELECT @=STUFF(value,1,2,'')FROM STRING_SPLIT(CAST(DECOMPRESS(CAST('H4sIAAAAAAAEAEWPUQ6DMAiGr2JCwlM9BKnZ7LTV2E7n7n+QlRbYC3yl8PNDCyIOAOACKcVstCudRYkytPSthUZPUrqM6KhxqC+3ZKNbaSWlNCltNuEJuozzdekITXDygu6xshNkx2u3xJhqREmWGUQqTiDWYpBLGEGkrOgij47N21k1eKdLM3trI+mF+h2tMSJK441qM3nDnQzLx/D8V69guM3mblvkiP1Q/SPwTqbs1XD2zVztKwnbL7p3wV77AcxSbMHfAQAA'as XML).value('.','varbinary(max)'))AS varchar(max)),','),t WHERE s=LEFT(value,2)ORDER BY NEWID()WHILE CHARINDEX('&',@)>0SET @=STUFF(@,CHARINDEX('&',@),1,SUBSTRING('ABCDEFGHJKLMNPRSTUVWXYZ',CAST(1+23*RAND()AS INT),1))WHILE CHARINDEX('#',@)>0SET @=STUFF(@,CHARINDEX('#',@),1,CAST(10*RAND()AS INT))PRINT @

```

EDIT 1: Saved over 300 bytes by changing `VALUES()` to `STRING_SPLIT()` (only available in SQL 2016 and later)

EDIT 2: Saved another 140 bytes by using GZIP compression as described here. We've already restricted ourselves to SQL 2016 and later, so these functions are available.

Input is via pre-existing table **t** with the State code in column **s**, per our IO standards.

After expanding the compressed string, here's the formatted code, with the super long list of states snipped:

```
DECLARE @ CHAR(8)
SELECT @=STUFF(value,1,2,'')
FROM STRING_SPLIT('AK&&& ###,IA&&& ###,MS&&& ###,...
                         (long string continues)
                   ...,SC### #&&,TN&##-##&,UT&## #&&',','),t
WHERE s=LEFT(value,2)ORDER BY NEWID()

WHILE CHARINDEX('&',@)>0
    SET @=STUFF(@,CHARINDEX('&',@),1,
        SUBSTRING('ABCDEFGHJKLMNPRSTUVWXYZ',CAST(1+23*RAND()AS INT),1))

WHILE CHARINDEX('#',@)>0
    SET @=STUFF(@,CHARINDEX('#',@),1,
        CAST(10*RAND()AS INT))

PRINT @

```

So I created a huge in-memory table consisting of all the possible pairs of (state, pattern). Note that I'm not combining rows, each state is separate, and states like IN will have 4 rows, one for each pattern.

When I join that in-memory table to the input table, I sort by `NEWID()`, which randomizes the order and returns a random matching pattern to the variable `@`.

I then just replace each `&` with a random letter, and each `#` with a random digit and return the result.

# Answer
> 4 votes
## \>\<\>, ~~967~~ ~~860~~ 851 bytes

```
</b:++d**d85-*i9*i2
v\+?\"00A AAA"
 /5:/
v\+?\"00000 AA"
 /4:/\
v\+?\x"000-AAA"
 /f:/
v\+?\>"AAA-000"
 /1:/
v\+ ?\"A00-00A"
v/cb:/\/"A000"
v\++?\xx"AA000"
v/88:/\x"000AAA"
v\+-?\ >"AAA000"
 /2f:/v\
v\*-?\xx"0000 AAA"
v/8c:/\x"00A AA0"
v\*-?\x>"000 AAA"
v/7c:/\"AA0 000"
v\*+?\"0000"
 /6b:/
v\*-?\"0000-AA"
 /5f:/
v\*-?\"0000AA0"
 /bc:/
v\+-?\"AAA-00A"
 /59:/
v\*+?\"000-AAA"
 /4a:/
v\*- ?\"000-000"
 /*a8:/
v\2+-?\"000AAA0"
 /*a8:/
v\9++?\"00000-AA"
 /*a8:/
v\5++?\"000-A00"
 /*a4:/
v\1+-?\"0000 000"
 /*a4:/
v\3+-?\"0000 AAA"
 /*a5:/
v\3++?\"AA0 00A"
 :63*+\:9a*4+-:aa*6++:73*+
 /*+9:/
v\***?\"000 AAA"
 8*-*$\::9a*-:4
 /7*ae/
v\++*?\"0000AAA"
 :4a*3\:aa*-:cb++:ca*4++:a7++:b+
v/**++/"0000-AAA"
v\***?/"AAA 000"
<ov?="A":v?="0":;?=1l
~!/0\v[0<
 l<1x/?=]!5
 +*2_/?= 1l
 -8::/*(~!*d2$**-2:-6:
^    >?!^"A"+o]
]~</0\v[0<
 l <1x/?=4
 + *2_<v?=1l
^n^?)9:<

```

Try it online, or watch it at the fish playground!

This code has two parts: matching the state to the pattern, then replacing the pattern with the random characters. Neither of these things is easy in \>\<\>.

First of all, we read in two characters, and compute 2 *c*1 \- 9 *c*2 \+ 533, where *c*1 and *c*2 are the two character codes. The 2 and the 9 were chosen so that the formula gives each state a unique value, and the offset of 533 was chosen to maximise the number of these values that can be made using only 3 \>\<\> instructions — it ended up being 28 out of 41 of them. We then send the fish zig-zagging down through the code until it finds the right value, at which point it escapes the zig-zag, reads the appropriate pattern and enters the fast stream in the leftmost column down to Part 2. Some of the states, particularly the ones with a choice of multiple patterns, needed some special consideration, but I managed to reuse some pieces of the code to save a few bytes.

Next, aka Part 2, we have to replace the "A"s and "0"s with random letters and numbers respectively. The only random command in \>\<\> is `x`, which sets the fish's direction randomly out of up, down, left and right — not conducive to choosing something uniformly out of 10 digits or 23 letters. Let's look at the numbers bit to see how the fish does it:

```
]~</0\v[0<
 l <1x<v?=4
 l 1=_?\2*+
^n^?)9:<

```

The fish enters from the top right. The fish sets up an empty stack — `0[` — then randomly pushes `1` or `0` with equal probability until the stack has length 4:

```
   /0\v
 l <1x<v?=4
     _

```

It then combines the four `1`s and `0`s together as if they were binary digits — `l1=?\2*+` — giving a number from 0 to 15. If the result is greater than 9, it discards all the work it just did and tries again; otherwise, it prints the number and continues:

```
]~<   v[0<
     x<

^n^?)9:<

```

Making the random letters is much the same, except we also check that the result isn't "I", "O" or "Q" with `::8-:6-:2-**`.

# Answer
> 3 votes
# Mathematica, ~~635~~ ~~507~~ 470 bytes

```
p=RandomChoice;a_±b_:=a<>b;r=""±Characters@"ABCDEFGHJKLMNPRSTUVWXYZ"~p~#&;j=""±ToString/@0~Range~9~p~#&;m=r@3;o=j@3;x=r@2;u=j@2;z=r@1;t=j@1;k=z±u±"-";w=m±" ";AS=y=j@4;AZ=GA=WA=m±y;CT=x±"-"±j@5;DC=x±"-"±y;FL=w±z±u;IL=x±" "±j@5;IN=p@{o±z,o±x,OK=o±m,s=m±o};CA=t±s;MD=t±x±y;MI=p@{OH=w±y,t±x±" "±z±u,AK=IA=MS=MP=VT=w±o};NV=u±z±"-"±o;NH=o±" "±y;NM=p@{MN=o±"-"±m,PR=m±"-"±o};NY=NC=PA=TX=VA=WI=m±"-"±y;RI=o±"-"±j@3;SC=p@{AR=KS=KY=LA=ND=OR=o±" "±m,VT};NJ=k±m;TN=k±u±z;UT=k±t±x;#&

```

***-165 bytes from @JungHwanMin***

**input form**

> \[NV\]

# Answer
> 1 votes
# PHP (Phar), 495 bytes

The binary Phar file can be downloaded here and can be run with `php uslic.phar <state code>`.

The base code used to generate the Phar is as follows (820 bytes):

```
<?$f=[AK=>'AAA 111',IA=>'AAA 111',MS=>'AAA 111',MP=>'AAA 111',VT=>'AAA 111','AS'=>'1111',AZ=>'AAA1111',GA=>'AAA1111',WA=>AAA1111,AR=>'111 AAA',KS=>'111 AAA',KY=>'111 AAA',LA=>'111 AAA',ND=>'111 AAA','OR'=>'111 AAA',CA=>'1AAA111',CT=>'AA-11111',DC=>'AA-1111',FL=>'AAA A11',IL=>'AA 11111',IN=>'111AX111AAX111AAAXAAA111',MD=>'1AA1111',MI=>'AAA 1111X1AA A11XAAA 111',MN=>'111-AAA',NV=>'11A-111',NH=>'111 1111',NJ=>'A11-AAA',NM=>'111-AAAXAAA-111',NY=>'AAA-1111',NC=>'AAA-1111',PA=>'AAA-1111',TX=>'AAA-1111',VA=>'AAA-1111',WI=>'AAA-1111',OH=>'AAA 1111',OK=>'111AAA',PR=>'AAA-111',RI=>'111-111',SC=>'AAA 111X111 1AA',TN=>'A11-11A',UT=>'A11 1AA'];$a=str_split(ABCDEFGHJKLMNPQRSTUVWXYZ);$n=range(0,9);$p=explode(X,$f[$argv[1]]);shuffle($p);for(;$i<strlen($p[0]);){$c=$p[0][$i++];echo$c==A?$a[rand(0,22)]:($c>0?$n[rand(0,9)]:$c);}

```

If you want to generate the Phar yourself from that code, you will need to do the following:

```
<?php
$phar = new Phar('uslic.phar', 0, 'u');
$phar->setSignatureAlgorithm(Phar::MD5);
$phar->addFile('s');
$phar['s']->compress(Phar::GZ);
$phar->setStub('<?include"phar://u/s";__HALT_COMPILER();');

```

Interestingly enough, this compresses better than a more golfed version.

The hexdump of the file is:

```
3C 3F 69 6E 63 6C 75 64 65 22 70 68 61 72 3A 2F
2F 75 2F 73 22 3B 5F 5F 48 41 4C 54 5F 43 4F 4D
50 49 4C 45 52 28 29 3B 20 3F 3E 0D 0A 30 00 00
00 01 00 00 00 11 00 00 00 01 00 01 00 00 00 75
00 00 00 00 01 00 00 00 73 34 03 00 00 26 C8 A9
59 76 01 00 00 E3 82 AE C9 B6 11 00 00 00 00 00
00 55 90 5D 6F 82 30 14 86 FF 8A 17 4D 0A B1 26
E2 9D 43 34 1D 4C 45 04 19 20 A2 84 2C 04 41 4D
0C 12 74 CB 92 65 FF 7D A5 AD A3 DC 34 7D CE C7
FB 9E 73 26 33 50 68 31 B6 B4 29 C4 18 F7 14 45
81 C8 C4 22 D9 7E 87 5C 91 C2 40 24 88 7D 48 58
A1 80 0F 2C C5 68 81 45 DA 11 E2 80 B0 C7 5A 7A
24 00 91 E5 77 68 2F D2 1A 8B E4 18 22 C1 8D 07
45 D6 69 2D F3 20 C4 C6 1C 28 CC DE D0 5B 84 68
BE E6 3B 60 BA 3B A3 1E 2F 35 1D A6 8A A3 E6 E1
2F 8E 9E C2 B6 C1 6C 58 B1 6D B6 D7 50 22 85 49
46 ED E9 B8 D6 80 CD 1F 52 A2 53 10 5A F2 E9 99
92 B3 6A 94 FE 4B ED B6 B1 91 E3 2D 7B E6 C6 D7
70 F4 0E BA B8 83 41 D4 C1 B0 9B DD 99 1D DC 2C
85 3D 08 5A FC 06 CD 2C AE D7 96 42 E4 99 7C 32
4A BE DE F6 45 74 99 A6 23 70 F8 2E 44 01 A2 6D
C0 88 E6 12 15 A4 DA FD 51 7F DC AB EB E5 21 E1
57 DD 78 9B 2F 96 2B 6B 6D 3B EE BB E7 07 DB 70
17 ED 0F B2 0A 4A AD 4E CB 53 2E 0D D1 98 50 A5
E5 DF D5 F5 76 CC A5 08 81 22 06 69 7D FA 8A 95
24 91 D5 FB F9 B3 28 AE B9 04 2A 59 2D 6E B5 A4
82 CB 84 18 5C F3 92 84 E2 21 A9 90 7F 40 A6 D1
7F 0C 2E FD 7E A2 E6 D9 F9 46 42 1A 9E 81 34 26
2E 47 62 32 1A C9 C9 8B 04 B2 E9 70 06 CA 67 70
4C 62 20 93 D5 DF 3F A0 DB 74 9C 07 ED A5 F7 4D
BA 32 97 A2 E7 9C 83 01 00 00 00 47 42 4D 42

```

# Answer
> 1 votes
# PHP, 609 bytes

```
<?$k='9 3';$l='3 9';$m='9-4';$f=[AK=>$k,IA=>$k,MS=>$k,MP=>$k,VT=>$k,'AS'=>4,AZ=>94,GA=>94,WA=>94,AR=>$l,KS=>$l,KY=>$l,LA=>$l,ND=>$l,'OR'=>$l,CA=>193,CT=>'8-5',DC=>'8-4',FL=>'9 72',IL=>'8 5',IN=>'37X38X39X93',MD=>184,MI=>'9 31X18 72X9 3',MN=>'3-9',NV=>'27-3',NH=>'3 4',NJ=>'72-9',NM=>'3-9X9-3',NY=>$m,NC=>$m,PA=>$m,TX=>$m,VA=>$m,WI=>$m,OH=>"$k1",OK=>39,PR=>'9-3',RI=>'3-3',SC=>"$kX3 18",TN=>'72-27',UT=>'72 18'];$a=str_split(ABCDEFGHJKLMNPRSTUVWXYZ);$n=range(0,9);$p=explode(X,$f[$argv[1]]);shuffle($p);for(;$c=$p[0][$i++];){if($c<1)echo$c;else for($j=0;$j<$c%6;$j++){echo$c>5?$a[rand(0,22)]:$n[rand(0,9)];}}

```

The main idea is to encode the license plate pattern with digits that indicate how many repetitions of a digit or letter follow. 1 to 5 refer to the number of digits while 7, 8 and 9 refer to 1, 2 or 3 letters, respectively. Multiple patterns are separated by an X, spaces and dashes are kept as-is. The state lookup is a simple array key lookup, redundant strings are put into variables to save space.

Ungolfed:

```
<?php
$f=[
    AK=>'9 3',
    IA=>'9 3',
    MS=>'9 3',
    MP=>'9 3',
    VT=>'9 3',
    'AS'=>4,
    AZ=>94,
    GA=>94,
    WA=>94,
    AR=>'3 9',
    KS=>'3 9',
    KY=>'3 9',
    LA=>'3 9',
    ND=>'3 9',
    'OR'=>'3 9',
    CA=>193,
    CT=>'8-5',
    DC=>'8-4',
    FL=>'9 72',
    IL=>'8 5',
    IN=>'37X38X39X93',
    MD=>184,
    MI=>'9 31X18 72X9 3',
    MN=>'3-9',
    NV=>'27-3',
    NH=>'3 4',
    NJ=>'72-9',
    NM=>'3-9X9-3',
    NY=>'9-4',
    NC=>'9-4',
    PA=>'9-4',
    TX=>'9-4',
    VA=>'9-4',
    WI=>'9-4',
    OH=>'9 31',
    OK=>39,
    PR=>'9-3',
    RI=>'3-3',
    SC=>'9 3X3 18',
    TN=>'72-27',
    UT=>'72 18'
];
$a=str_split(ABCDEFGHJKLMNPRSTUVWXYZ);
$n=range(0,9);
$p=explode('X',$f[$argv[1]]);
shuffle($p);
for ($i = 0; $i < strlen($p[0]); $i++) {
    $c=$p[0][$i];
    if ($c < 1)
        echo $c;
    else {
        for ($j = 0; $j < $c % 6; $j++){
            echo $c > 5 ? $a[rand(0,22)] : $n[rand(0,9)];
        }
    }
}

```

# Answer
> 1 votes
# C (gcc), ~~473~~ 469 bytes

Thanks to ceilingcat for -4 bytes.

A first feeble attempt. I suspect there is a way to shorten the strings substantially.

```
n,c,d,i;f(char*s){n=0;for(s=strstr("AKnIAnMSnMPnVTnAS`AZrGArWArARfKSfKYfLAfNDfORfCAlCTtDCsFLpILmINbcdqMDkMInojMNhNViNHgNJuNMhxNYyNCyPAyTXyVAyWIyOHoOKdPRxRIaSCoeTNvUTw",s)+2;s[n]>90;n++);for(s="4    3-3  3A   3B   3C   3 1B 3 C  3 4  3-C  2A-3 1B A21B4  1BA3 B 5  C 3  C 4  C A2 C3   C4   B-4  B-5  A2-C A2-2AA2 1BC-3  C-4  "+(s[rand()%n]-96)*5,n=5;d=c=*s++,n--;)for(c>57?i=c-64,c=65:c>47?i=c-48,c=48:(i=1);i--;putchar(d))while(i&&index("IOQ",d=rand()%(c>57?26:10)+c));}

```

Try it online!

# Answer
> 1 votes
## Clojure, ~~502~~ 501 bytes

```
#(apply str(for[E[repeatedly]c(rand-nth(cond('#{AK IA MS MP VT}%)["D 3"]('#{AR KS KY LA ND OR}%)["3 D"]('#{AZ GA WA}%)["D4"]1(case % AS["4"]CA["1D3"]CT["C-5"]DC["C-3"]FL["D B1"]IL["C 4"]IN["3B""3C""3D""D2"]MD["1C3"]MI["D 4""1C B2""D 2"]MN["3-C"]NV["2B-2"]NH["3 3"]NJ["B2-C"]NM["3-D""D-2"]OH["D 3"]OK["3C"]PR["D-2"]RI["3-2"]SC["D 3""3 1B"]TN["B2-2"]UT["B2 1B"]["D-4"])))r(cond((set"BCD")c)(E(-(int c)65)(fn[](rand-nth"ABCDEFGHJKLMNPRSTUVWXYZ")))((set"1234")c)(E(-(int c)48)(fn[](rand-int 10)))1[c])]r))

```

The input argument is a symbol, not a string. This let me avoid many double-quotes. `B` \- `D` encode repetitions `A` \- `AAA`, `1` \- `4` encode repetitions `0` \- `0000`.

# Answer
> 1 votes
# Python 2, 438 bytes

```
import re,random
lambda s,R=range,C=random.choice:re.sub('\d',lambda c:''.join(C(['0123456789','ABCDEFGHJKLMNPRSTUVWXYZ'][c.group()>'4'])for _ in R(int(c.group())%5+1)),C("063;6-3;072;3;7 2,2 06;6-4;51-15;2-7,7-2;7 2;;7 3;;6 4;2 7;2 7;2-2;25,26,27,72;2 7;;7 3,06 51,7 2;7 2;73;;2 3;;7 51;;73;7 2;2 7;;27;2 7;;7 2;7-2;;73;;51-7;;51 06;;2-7;15-2;7 2;;7-3".split(";")["MDCASCTNMSOHILARINDMIAZNHFLWAKSOKYMPRGANJUTMNVTOR".find(s)].split(",")))

```

Try it online!

Readable version: Try it online!

Note how the `states` string is only 49 letters long. I folded overlapping letters into one as much as possible (`MD``DC``CA``AS``SC`…) and omitted `NY, NC, PA, TX, VA, WI` which thus all map to `-1`.

In the list of `codes`, `12345` mean that many digits and `678` mean (that−5) many letters.

---
Tags: code-golf, random, generation
---


# Question
Title: TyPe LiKe ThIs AnD iRrItAtE yOuR fRiEnDs
Your goal is to alternate uppercase and lowercase letters, while ignoring non-alphaneumeric characters.

```
Input => Output
abc => aBc OR AbC
a c => A c OR a C
abc123abc => AbC123aBc OR aBc123AbC

```

Shortest answer wins.

# Answer
> 0 votes
# JavaScript, 116

```
s=>{x=!0;return s.split("").map(e=>{if(e.match(/[a-zA-Z]/))x=!x;return x?e.toUpperCase():e.toLowerCase()}).join("")}

```

Saved two bytes thanks to NTCG

---
Tags: code-golf
---


title: Determine Season

text:
# Question
Title: Determine Season
## Introduction:

In the **northern hemisphere** (i.e. Europe, North America, etc.), the seasons are divided like this:
\- **Spring:** March, April, May
\- **Summer:** June, July, August
\- **Autumn:** September, October, November
\- **Winter:** December, January, February

In the **southern hemisphere** however (i.e. Australia, South America, etc.), the seasons are divided like this:
\- **Spring:** September, October, November
\- **Summer:** December, January, February
\- **Autumn:** March, April, May
\- **Winter:** June, July, August

This difference is due to the position of the sun regarding the equator, where the northern and southern hemispheres have opposite seasons.

## Input:

In this challenge, we'll take two inputs:

* One for the month (`1 <= m <= 12` or `0 <= m <= 11`) (examples and test cases are all 1-indexed).
* And one for the five 'position-groups' at the latitudes of Earth (`-2 <= p <= 2`), where `-2` is the Antarctic, `-1` is the southern hemisphere excluding the Antarctic, `0` are the Tropics in proximity of the equator, `1` is the northern hemisphere excluding the Arctic, and `2` is the Arctic.
Although the Arctic, Antarctic and Tropics of course still have seasons, for the sake of this challenge we'll say the Arctic and Antarctic are in a constant state of `Winter`, and the Tropics are in a constant state of `Summer`.

Here a visual representation of these five groups, where `-2` is the Antarctic Circle; `-1` between the Tropic of Capricorn and Antarctic Circle; `0` between the Tropic of Capricorn and Tropic of Cancer; `1` between the Arctic Circle and Tropic of Cancer; and `-2` the Arctic Circle.

Source: COSMOS - The SAO Encyclopedia of Astronomy

## Output:

One of `Spring`, `Summer`, `Autumn`, or `Winter`, following these rules:

* Is the position input `2` or `-2` (Arctic or Antarctic), always output `Winter`.
* Is the position input `0` (Tropics), always output `Summer`.
* Is the position input `1` (northern hemisphere), output one of the four seasons based on the month input: `Spring` (`m = [3,5]`); `Summer` (`m = [6,8]`); `Autumn` (`m = [9,11]`); `Winter` (`m = 12 or m = [1,2]`).
* Is the position input `-1` (southern hemisphere), output one of the four seasons based on the month input: `Spring` (`m = [9,11]`); `Summer` (`m = 12 or m = [1,2]`); `Autumn` (`m = [3,5]`); `Winter` (`m = [6,8]`).

## Challenge rules:

* Output any four distinct values of your choice indicating `Spring`, `Summer`, `Autumn`, or `Winter` (please state what you've used in your answer).
**-15 bytes bonus** if you output `Spring`, `Summer`, `Autumn`, or `Winter` as text (case-insensitive, so can be fully lowercase or fully uppercase as well, instead of the used title-case).
* Month input can be in any reasonable format. Can be either a 0-indexed or 1-indexed integer, Date-object, Month-String, etc.
* Position input will always be one of these possible five inputs `-2`, `-1`, `0`, `1`, `2`.

## General rules:

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

## Test cases:

```
Position    1-indexed Month    Output

-2          8  (August)        Winter
-2          12 (December)      Winter
-1          3  (March)         Autumn
-1          5  (May)           Autumn
-1          8  (August)        Winter
-1          12 (December)      Summer
0           1  (January)       Summer
0           7  (July)          Summer
1           1  (January)       Winter
1           4  (April)         Spring
1           7  (July)          Summer
1           12 (December)      Winter
2           2  (February)      Winter
2           9  (September)     Winter

```

# Answer
> 10 votes
# Ruby, ~~33 27~~ 25 bytes

```
->m,l{[6,m,0,m+6][l]/3%4}

```

Try it online!

Return values are:

0 -\> winter

1 -\> spring

2 -\> summer

3 -\> autumn

# Answer
> 6 votes
# Python 2, 29 bytes

```
lambda p,m:[0,m+6,6,m][p]/3%4

```

Try it online!

A port of G B's Ruby approach, which turned out to be a few bytes shorter than my own:

### 32 bytes

```
lambda p,m:(p%2*(p+m/3+5)or p)%4

```

Try it online!

An anonymous function that returns the seasons as the numbers 0 to 3, where they represent Summer, Autumn, Winter and Spring in that order.

As for printing the actual season names:

### 63 - 15 = 48 bytes

```
lambda p,m:"SAWSuuipmtnrmutiemenrnrg"[(p%2*(p+m/3+5)or p)%4::4]

```

Try it online!

There's the combined string if anyone wants it.

# Answer
> 3 votes
# C (gcc), 78 75 (-15 bonus) = 60 bytes

Using 1-based months.

*Edit:* Rearranged mathematical operators and reduced.

```
f(m,a){puts("Summer\0Autumn\0Winter\0Spring"+7*(a*a&1?(++a+m/3)%4:2*!!a));}

```

Try it online!

# Answer
> 2 votes
# 05AB1E, 26 - 15 = 11 bytes

Uses the approach found by G B

```
6¹¾¹6+)sè3÷4%“–„Ž¹Ž€È±“#sè

```

Try it online! or as a Test suite

---
Tags: code-golf, number
---


title: Find arsonist's lullaby

text:
# Question
Title: Find arsonist's lullaby
Imagine an arsonist walking around the town and picking its victims according to a very specific pattern (Or, alternatively, *Imagine a bee flying around the garden and picking its flowers to pollenize according to a very specific pattern*). Let's say the town is an **N × N** matrix, where **N** is an integer higher than or equal to **2**. The arsonist starts from the upper-left corner and successively sets the house **M** spots in front of them (where **M** is the number of the house they're currently in), while changing the direction it's moving in after each fire, in the order East ⟶ South ⟶ West ⟶ North ⟶ East ⟶ South... and so on. The *lullaby* of the arsonist is the value of **M** that makes them exit the town (i.e. the last house they visit before stopping the abomination). This is way easier to understand with an example. Take the following matrix for instance:

```
3 2 3 2 7
3 1 4 1 6
2 5 3 1 1
4 4 3 2 4
1 1 1 1 1

```
* We start in the upper-left corner, so **M = 3** (`X` marks the current and previous positions of the arsonist):
```
X 2 3 2 7
3 1 4 1 6
2 5 3 1 1
4 4 3 2 4
1 1 1 1 1

```
* According to the known order, it first goes east **M (3)** spots and lands on a **2** so **M** changes accordingly:
```
X 2 3 X 7
3 1 4 1 6
2 5 3 1 1
4 4 3 2 4
1 1 1 1 1

```
* Then it goes south **2** spots and **M** is now **1**:
```
X 2 3 X 7
3 1 4 1 6
2 5 3 X 1
4 4 3 2 4
1 1 1 1 1

```
* Now it moves **1** spot to the West and **M** becomes **3**:
```
X 2 3 X 7
3 1 4 1 6
2 5 X X 1
4 4 3 2 4
1 1 1 1 1

```
* After it moves **3** spots north, it exits the town! Therefore, **3** is this arsonist's lullaby:
```
    X
X 2 3 X 7
3 1 4 1 6
2 5 X X 1
4 4 3 2 4
1 1 1 1 1

```

Given an **N × N** matrix (you can optionally take **N** as input too), find the lullaby of the arsonist. I've written a program with which you can generate more test cases and visualise the path of the arsonist: Try it online!

* You may assume that the arsonist *does* have a lullaby (that is, it can actually get out of the matrix).
* The matrix will only contain positive integers less than or equal to **9** (digits), for simplicity. Solutions that handle any positive integer are completely welcome.
* Note that the arsonist *can* land on a spot they've already burned, in case the sense they're moving in is different from the first time. In such a scenario, just take the value of that element and move again as usual.
* You can compete in any programming language and can take input and provide output through any standard method, while taking note that these loopholes are forbidden by default. This is , so the shortest submission (in bytes) for *every language* wins.

## Test cases

```
-------------
9 2 3
1 7 2
8 7 6

Lullaby: 9
-------------
2 1 2 1
3 1 1 2
1 2 2 1
1 1 1 3

Lullaby: 2
-------------
3 2 3 2 7
3 1 4 1 6
2 5 3 1 1
4 4 3 2 4
1 1 1 1 1

Lullaby: 3
-------------
1 2 1 2 1 2
1 2 1 2 1 2
1 2 1 2 1 2
1 2 1 2 1 2
1 2 1 2 1 2
1 2 1 2 1 2

Lullaby: 2
-------------
3 2 1 2 1 1 1
2 3 2 3 2 1 1
2 1 1 1 3 1 2
3 1 1 1 1 1 1
4 5 2 3 1 1 1
1 2 1 2 1 2 2
1 2 2 3 2 1 2

Lullaby: 3
-------------

```

The matrices in a different format:

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

```

The fifth test case is very interesting to visualise.

# Answer
> 11 votes
# MATL, 32 bytes

```
JQ6*`G5thYay&Zj3$)wyJ2@-^*+8M]b&

```

Try it online! Or verify all test cases.

### How it works

The input matrix is padded with a frame of five zeros, so for example

```
3 2 3 2 7
3 1 4 1 6
2 5 3 1 1
4 4 3 2 4
1 1 1 1 1

```

becomes

```
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 3 2 3 2 7 0 0 0 0 0
0 0 0 0 0 3 1 4 1 6 0 0 0 0 0
0 0 0 0 0 2 5 3 1 1 0 0 0 0 0
0 0 0 0 0 4 4 3 2 4 0 0 0 0 0
0 0 0 0 0 1 1 1 1 1 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

```

The frame of zeros is used to detect when the ~~arsonist~~ bee has exited the matrix. The extension with five zeros ensures that a *modular* displacement of length up to `9` in any direction from any of the nonzero entries will correctly land in a zero without wrapping around to some non-zero entry.

In matrix coordinates, the bee starts at entry `(6,6)` of the extended matrix. It reads that entry, and updates the coordinates as required, applying a (modular) displacement of the read length in the corresponding direction. This is repeated in a loop until the read value is `0`. The entry that was read before that one (i.e. the last non-zero entry) is the output.

The coordinates are actually stored as a complex number, so for example `(6,6)` becomes `6+6j`. This way the four cyclic directions can be realized as powers of the imaginary unit. The corresponding power (`j`, `1`, `-j` or `-1`) is multiplied by the read entry to obtain the complex displacement which is used for updating the coordinates.

The successively read values are kept on the stack. When the loop is exited, the stack contains all non-zero read values in order, then the last read value which is `0`, then the latest complex coordinates. So the third-top element is the required output.

# Answer
> 7 votes
# JavaScript (ES6), ~~70~~ 68 bytes

```
m=>(g=d=>(n=(m[y]||0)[x])?g(--d&3,x-=d%2*(y+=--d%2*n,L=n)):L)(x=y=0)

```

Try it online!

### Commented

```
m => (                        // given m = input matrix
  g = d =>                    // g = recursive function taking the direction d
    (n = (m[y] || 0)[x]) ?    // let n be the content of the current cell; if it's defined:
      g(                      //   do a recursive call:
        --d & 3,              //     with the next direction (0 = E, 3 = S, 2 = W, 1 = N)
        x -=                  //     update x by subtracting ...
          d % 2 * (           //       ... ((d - 1) % 2) * n
            y += --d % 2 * n, //       and update y by adding ((d - 2) % 2) * n
            L = n             //       save n into L
          )                   //     end of x update
      )                       //   end of recursive call
    :                         // else:
      L                       //   stop recursion and return L
)(x = y = 0)                  // initial call to g() with x = y = d = 0

```

Given that the sign of the modulo in JS is that of the dividend, the direction is updated this way:

```
 d | d' = --d&3 | dx = -(d%2)  | dy = --d%2 | direction
---+------------+--------------+------------+------------------
 0 |     3      | -(-1%2) = +1 | -2%2 =  0  | (+1,  0) = East
 3 |     2      | -( 2%2) =  0 |  1%2 = +1  | ( 0, +1) = South
 2 |     1      | -( 1%2) = -1 |  0%2 =  0  | (-1,  0) = West
 1 |     0      | -( 0%2) =  0 | -1%2 = -1  | ( 0, -1) = North

```

# Answer
> 4 votes
# Charcoal, ~~25~~ 18 bytes

```
ＰＳ↶ＷＫＫ«≔ιθ×Ｉι¶↷»⎚θ

```

Try it online! Link is to verbose version of code. Explanation:

```
ＰＳ

```

Print the input string, but don't move the print position.

Rotate the pivot left, so that the print direction is now up.

```
ＷＫＫ«

```

Repeat while there is a character under the print position.

```
≔ιθ

```

Save the character in a variable.

```
×Ｉι¶

```

Cast the character to a number and print that many newlines. As the print direction is now up, this ends up printing horizontally. The upshot is that we've moved the print position in the desired direction by the amount given by the number under the print position.

```
↷»

```

Rotate the pivot so that the next newlines move the print position in the next direction clockwise for the next pass of the loop.

~~```
Ｆ⟦ωθ⟧¿ιι⎚

```~~

~~Unfortunately we still have the input cluttering our canvas, and even more unfortunately, if we clear the canvas we also clear our variable. So, this is a bit of a trick: a list of the empty string and the variable is looped over. On the first pass of the loop, the loop variable is empty, so the canvas and the loop variable and the result variable are all cleared. But the loop is not finished! On the second pass of the loop, we still get to access our variable carefully preserved in our loop list. It simply remains to print it.~~

```
⎚θ

```

Clear the canvas and print the saved variable. (Thanks to @ASCII-only for the fix to Charcoal.)

# Answer
> 2 votes
# Python 2, ~~85~~ 84 bytes

```
a=input();x=y=e=0;d=1
while-1<y<len(a)>x>=0:v=a[y][x];x+=v*d;y+=e*v;d,e=-e,d
print v

```

Try it online!

Tip o' the hat to Mr. Xcoder for 1 byte.

# Answer
> 2 votes
# Charcoal, ~~50~~ ~~49~~ ~~46~~ ~~34~~ ~~33~~ 26 bytes

```
ＮθＥθＳＭθ↑ＷＫＫ«ＭＩι✳⊗Ｌυ⊞υι»⎚⊟υ

```

Try it online

Link is to the verbose version of the code

Input must be **N** on its own line, then the lines of the array on separate lines after that.

Any ways to knock off bytes are welcome and wanted, as I am not a good golfer in Charcoal!

-12 bytes thanks to @Neil! -1 byte thanks to @ASCII-only! -7 bytes thanks to @ASCII-only (changed a bug that made `Clear` reset variables)

# Answer
> 1 votes
# Red, 145 bytes

```
func[b][h:[0 1 0 -1 0]x: y: 1 i: 0
until[y: h/(i: i % 4 + 1) *(t: b/(y)/(x)) + y x: h/(i + 1) * t + x none = b/(y) or(x < 1 or(x > length? b))]t]

```

Try it online!

## More readable:

```
f: func[b][
    h: [0 1 0 -1 0]                                ; step lengths (combined for x and y)
    x: y: 1                                        ; starting coords (1,1)
    i: 0                                           ; step counter
    until[
        y: h/(i: i % 4 + 1) * (t: b/(y)/(x)) + y   ; next y; t stores the lullaby
        x: h/(i + 1) * t + x                       ; next x
        none = b/(y) or (x < 1 or (x > length? b)) ; until x or y are not valid indices
    ]
    t                                              ; return the lullaby
]

```

# Answer
> 1 votes
# Perl 6, 62 bytes

```
{$^w;$^m[0,{$_+$m[$_]*(1,$w,-1,-$w)[$++%4]}...{!$m[$_]}][*-2]}

```

Try it online!

Takes the matrix as flat list and width.

# Answer
> 1 votes
# Clean, 141 bytes

```
import StdEnv
d=[0,1,1,0,0,-1,-1,0:d]
$m[x,y]n[a,b:l]#r=size m
#u=x+a*n
#v=y+b*n
|0>u||0>v||u>=r||v>=r=n= $m[u,v]m.[u,v]l
?m= $m[0,0]m.[0,0]d

```

Try it online!

Defines the function `? :: {#{#Int}} -> Int`, taking an unboxed array of unboxed arrays of integers and returning the result.

# Answer
> 1 votes
# Java 8, 121 bytes

```
m->{int l=m.length,x=0,y=0,f=0,r=0;for(;x*y>=0&x<l&y<l;x+=f<1?r:f==2?-r:0,y+=f==1?r:f>2?-r:0,f=++f%4)r=m[y][x];return r;}

```

Try it online.

Alternative with same **121 bytes** byte-count:

```
m->{int l=m.length,x=0,y=0,f=0,r=0;try{for(;;x+=f<1?r:f==2?-r:0,y+=f==1?r:f>2?-r:0,f=++f%4)r=m[y][x];}finally{return r;}}

```

Uses try-finally instead of checking if the `x,y`-coordinate is still within bounds.

Try it online.

**Explanation:**

```
m->{                   // Method with integer-matrix parameter and integer return-type
  int l=m.length,      //  Dimensions of the matrix
      x=0,y=0,         //  x,y coordinate, starting at [0,0]
      f=0,             //  Direction-flag, starting at 0 (east)
      r=0;             //  Result-integer
  for(;x*y>=0&x<l&y<l  //  Loop as long as the x,y coordinates are still within bounds
      ;                //    After every iteration:
       x+=f<1?         //     If the direction is east:
           r           //      Increase the `x` coordinate by `r`
          :f==2?       //     Else-if the direction is west:
           -r          //      Decrease the `x` coordinate by `r`
          :            //     Else (it's north/south):
           0,          //      Leave the `x` coordinate the same
       y+=f==1?        //     If the direction is south:
           r           //      Increase the `y` coordinate by `r`
          :f>2?        //     Else-if the direction is north:
           -r          //      Decrease the `y` coordinate by `r`
          :            //     Else:
           0,          //      Leave the `y` coordinate the same
       f=++f%4)        //     Go to the next direction (0→1→2→3→0)
    r=m[y][x];         //   Set `r` to the value of the current cell
  return r;}           //  Return the last `r` before we went out of bounds

```

# Answer
> 0 votes
# Perl 5, 92 bytes

```
sub b{1while eval join'&&',map{/./;map"(\$$_$&=".'$n=$_[$y][$x])'.$',x,'y'}'+<@_','->=0';$n}

```

Try it online!

## How?

The set of nested maps and the join produce this:

```
($x+=$n=$_[$y][$x])<@_&&($y+=$n=$_[$y][$x])<@_&&($x-=$n=$_[$y][$x])>=0&&($y-=$n=$_[$y][$x])>=0

```

which is then evaluated to determine if the loop ends. Because the Boolean is evaluated left to right, the value of `$n` actually changes (up to) four times during the evaluation. Because Boolean logic short-circuits in Perl, the value of `$n` is the lullaby when the loop is exited.

# Answer
> 0 votes
# Python 3, ~~85~~ 84 bytes

xcoder: -1 (I never remember the +~ trick)

```
def f(x):
 r=c=0
 while-1<r:d=x[r][c];r,c=len(x)-c+~d,r;x=[*zip(*x)][::-1]
 return d

```

Try it online!

Instead of moving in different directions (E,S,W,N), this solution always moves east and rotates the grid counter clockwise after every move. After rotating, what was the last column is now the first row, so if the row index is less than zero it means we ran off the board.

# Answer
> 0 votes
# Retina, 161 bytes

```
.
 $.%`*_#$&*
(?<=(.+¶)+|^)
A ¶A$#1*
~(K`{`^X\1YZ¶1S$4¶1XYZ¶2$4$2$4$3¶2XYZ¶3S¶3XY\1Z¶S
X
(_$*)(A_$*)
Y
( _$*)
Z
(?=\n\D$*\2\b.$*\3#(_+))
)`S
$$4$$2$$3
L$0`_+
$.0

```

Try it online!

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


# Question
Title: Give a permutation with no two consecutive integers next to each other
**Challenge**

Given an integer **n ≥ 4**, output a permutation of the integers **\[0, n-1\]** with the property that no two consecutive integers (integers with absolute difference 1) are next to each other.

**Examples**

* **4****\[1, 3, 0, 2\]**
* **5****\[0, 2, 4, 1, 3\]**
* **6****\[0, 2, 4, 1, 3, 5\]**
* **7****\[0, 2, 4, 1, 5, 3, 6\]**

You may use 1-indexing instead (using integers **\[1, n\]** instead of **\[0, n-1\]**).

Your code must run in polynomial time in **n**, so you can't try all permutations and test each one.

# Answer
# Jelly, ~~3~~ 2 bytes

```
ḂÞ

```

Sorts the integers in **\[1, ..., n\]** by their LSB.

Try it online!
> 32 votes

# Answer
# Python 2, 32 bytes

```
lambda n:(range(n|1)*2)[1:n*2:2]

```

Try it online!
> 16 votes

# Answer
# Python 3, ~~40~~, 38 bytes

```
lambda n:[*range(1,n,2),*range(0,n,2)]

```

Try it online!

This runs in `O(n)` time.

Thanks to Dennis for saving 2 bytes!
> 8 votes

# Answer
# Python 2, 34 bytes

```
lambda n:range(1,n,2)+range(0,n,2)

```

Try it online!

**Python 2, 40 bytes**

```
lambda n:[(k-~k)%(n|1)for k in range(n)]

```

Try it online!
> 6 votes

# Answer
# Octave, 17 bytes

```
@(x)[2:2:x,1:2:x]

```

Try it online!

This uses the same approach as many others. Concatenate two vectors, one with all the even number in the inclusive range **2 ... x**, and all the odd numbers in the inclusive range **1 ... x**. The syntax should be fairly obvious, so I won't explain that.
> 6 votes

# Answer
## Haskell, 22 bytes

f is a function of n that returns an appropriately ordered list. I am using the 1-indexing option.

```
f n=[2,4..n]++[1,3..n]

```
> 6 votes

# Answer
# Gaia, 2 bytes

```
r∫

```

Try it online!

This simply (stable) orts the integers in the range **\[1, input\]** by their pa**r**ity.
> 5 votes

# Answer
# , ~~39~~ ~~36~~ 35 bytes

```
function(x)c(seq(2,x,2),seq(1,x,2))

```

Try it online!
> 5 votes

# Answer
# 05AB1E, 3 bytes

Port of DJMcMayhem's Python answer and Dennis's Jelly answer

```
ÝΣÉ

```

**Try it online!**

### How?

```
ÝΣÉ - implicitly take input onto stack  e.g. 7
Ý   - pop a and push range(a)               [0,1,2,3,4,5,6]
 Σ  - sort by (stable):
  É -   is even? (x%2==0 ?)                 [1,3,5,0,2,4,6]
    - implicit print of top of stack

```
> 4 votes

# Answer
## JavaScript (ES6), 40 bytes

```
f=
n=>[...Array(i=n)].map(_=>(i+--i)%(n|1))
```

```
<input type=number min=4 oninput=o.textContent=f(+this.value).join`\n`><pre id=o>
```

Edit: Saved 1 byte thanks to @Arnauld.
> 4 votes

# Answer
# Japt, 4 bytes

You could also replace `u` with `v` to get a different order.

```
õ ñu

```

Try it

Or, if we can ouput an array of 2 arrays:

```
õ ó

```

Try it
> 4 votes

# Answer
# Mathematica, 50 -\> 47 -\> 42 bytes

```
p = Join[Range[2, #, 2], Range[1, #, 2]] &

```

Try it online!

Thanks to user202729 for pointing out the twofold optimization potential Join\[\] insteaed of Flatten\[\] and using pure functions.

I'd like to add two remarks.

1) It is fairly straightforward to construct a specific permutation with no falling or rising succession for n\>=4 as requested n the OP.

It consists of two consecutive list.

For even n these are:
list1 = (2,4,...,n/2)
list2 = (1,3,...,n/2-1)

For odd n we have:
list1 = (2,4,...,Floor\[n/2\])
list2 = (1,3,...,Floor\[n/2\])

For this "algorithm" just one decision must be made (n even or odd), the rest is just writing down n numbers.

A possible Mathematica solution is provided at the top.

2) A related question is how many such permuations exist as a function of n.

# Mathematica, 124 Bytes

```
a[0] = a[1] = 1; a[2] = a[3] = 0;
a[n_] := a[n] = (n + 1)*a[n - 1] - (n - 2)*a[n - 2] - (n - 5)*a[n - 3] + (n - 3)*a[n - 4]

```

Try it online!

Example:

```
a[#] & /@ Range[4, 12]

```

> {2, 14, 90, 646, 5242, 47622, 479306, 5296790, 63779034}

To count the number of such permutations is a standard problem.

For n = 4 there are 2: {{2,4,1,3},{3,1,4,2}}

For n = 5 there are 14: {{1,3,5,2,4},{1,4,2,5,3},{2,4,1,3,5},{2,4,1,5,3},{2,5,3,1,4},{3,1,4,2,5},{3,1,5,2,4},{3,5,1,4,2},{3,5,2,4,1},{4,1,3,5,2},{4,2,5,1,3},{4,2,5,3,1},{5,2,4,1,3},{5,3,1,4,2}}

The number a(n) of these permutations rises quickly: 2, 14, 90, 646, 5242, 47622, 479306, 5296790, 63779034, ...

For large n the ratio a(n)/n! seems to approach the limit 1/e^2 = 0.135335... I have no strict proof but it is just a conjecture from numerical evidence. You can test this by trying to run the program online.

The program above (based on the reference given below) calculates these numbers.

You can find more information in the relevant sequence on OEIS: A002464. Hertzsprung's problem: ways to arrange n non-attacking kings on an n X n board, with 1 in each row and column. Also number of permutations of length n without rising or falling successions.
> 3 votes

# Answer
# Ruby, 27 bytes

```
->n{[*2.step(n,2)]|[*1..n]}

```

Try it online!

Using 1-indexing
> 2 votes

# Answer
# Whitespace, 161 bytes

Here is the official, uncommented submission: Try it online!

```
push_0
read_n
		push_0
retreive_n			push_1
subtract	   dup_and_out[

 	]label_s'

'push_2
subtract	   dup[
 ]jump_next_if_neg:

:dup_and_out[

 	]else_jump_back:

:label_ss'

'push_0
retreive_n			push_2
subtract	   dup_and_out[

 	]dup[
 ]jump_next:

:label_ssss'

'push_2
subtract	   dup[
 ]jump_end_if_neg:

:dup_and_out[

 	]else_jump_back:

:label_sss'

'end

```

Try it online!

I sacrificed a few bytes so that the program would execute without any errors, I believe that I could lose around 7-8 bytes, and it would still output correctly, but it would also output error messages, and nobody wants that.

### Full Byte Explanation:

```
[Space][Space][Space][N]                   Push a 0 on the stack
[Tab][Tab][N][Tab][Tab][Tab][Tab]          Read input value and store in heap
[Space][Space][Space][N]                   Push a 0 on the stack again
[Tab][Tab][Tab]                            Retrieve the value from the heap
[Space][Space][Tab][Tab][N]                Push a -1 on the stack
[Tab][Space][Space][Space]                 Add -1 to value
[Space][N][Space]                          Duplicate
[Tab][N][Space][Tab]                       Output
[N][Space][Space][Space][N]                Set First Label
[Space][Space][Tab][Tab][Space][N]         Push a -2 on the stack
[Tab][Space][Space][Space]                 Subtract 2 from value
[Space][N][Space]                          Duplicate
[N][Tab][Tab][Space][Space][N]             If negative, jump to second label
[Space][N][Space]                          Duplicate
[Tab][N][Space][Tab]                       Output
[N][Space][N][Space][N]                    Jump back to first label
[N][Space][Space][Space][Space][N]         Set Second Label
[Space][Space][Space][N]                   Push a 0 on the stack
[Tab][Tab][Tab]                            Retrieve input value from heap again
[Space][Space][Tab][Tab][Space][N]         Push a -2 on the stack
[Tab][Space][Space][Space]                 This time, Add a -2 to the value
[Space][N][Space]                          Duplicate
[Tab][N][Space][Tab]                       Output
[Space][N][Space]                          Duplicate
[N][Space][N][Space][Tab][N]               Jump to third label
[N][Space][Space][Space][Tab][N]           Set third label
[Space][Space][Tab][Tab][Space][N]         Push a -2 on the stack
[Tab][Space][Space][Space]                 Subtract 2 from value
[Space][N][Space]                          Duplicate
[N][Tab][Tab][Space][Space][Space][N]      Jump to end if negative
[Space][N][Space]                          Duplicate
[Tab][N][Space][Tab]                       Output
[N][Space][N][Space][Tab][N]               Jump back to third label
[N][Space][Space][Space][Space][Space][N]  Set fourth label/end
[N][N][N]                                  Terminate

```
> 2 votes

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

```
n=>(f=i=>i<n?[i,...f(i+2)]:i&1?[]:f(1))(0)

```

Try it online!

# JavaScript (Node.js), 47 bytes

```
n=>(f=i=>i--?[n--*2%(N|1)+N%2,...f(i)]:[])(N=n)

```

Try it online!
> 1 votes

# Answer
# F# (Mono), 27 bytes

```
let f n=[2..2..n]@[1..2..n]

```

Try it online!
> 1 votes

# Answer
# Gol\>\<\>, 14 bytes

```
FL:2%Z}:3=?$|B

```

Try it online!

### Example full program & How it works

```
1AGIE;GDlR~
FL:2%Z}:3=?$|B

1AG          Register row 1 as function G
   IE;       Take number input; halt on EOF
      GD     Call G and print the stack
        lR~  Empty the stack
             Repeat indefinitely

F           |   Repeat n times...
 L              Push loop counter (0..n-1)
  :2%Z}         If even, move to bottom of the stack
       :3=?$    If top == 3, swap top two
                  This is activated only once to make [2 0 3 1]
             B  Return

```
> 1 votes

# Answer
# , 10 bytes

```
i./:2|1+i.

```

Try it online!

## Explanation:

```
  /:          sort
i.            the numbers in the range 0..n-1
    2|        according the remainder mod 2 of
      1+i.    the numbers in the range 1..n

```
> 1 votes

# Answer
# Java 8, 56 bytes

```
n->{for(int i=n;i>0;)System.out.println((i+--i)%(n|1));}

```

Port of *@Neil*'s JavaScript (ES6) answer.

Try it online.

---

**Old 66 bytes answer:**

```
n->{String[]r={"",""};for(;n-->0;)r[n%2]+=n+" ";return r[0]+r[1];}

```

Try it online.

**Explanation:**

```
n->{                  // Method with integer parameter and String return-type
  String[]r={"",""};  //  Result-Strings, both starting empty
  for(;n-->0;)        //  Loop in the range (n, 0]
    r[i%2]+=i+" ";    //   Append `i` and a space to one of the two result-Strings,
                      //   depending on if it is even (first) or odd (second)
  return r[0]+r[1];}  //  Return the two result-Strings appended to each other

```
> 1 votes

# Answer
# Ruby, 27 bytes

```
->n{(1..n).sort_by{|i|i&1}}

```

As in this answer, `n` first integers are sorted by their least significant bit.

Try it online!
> 1 votes

---
Tags: code-golf, restricted-complexity
---


title: Code 39 barcode encoder

text:
# Question
Title: Code 39 barcode encoder
Write a function or program that encodes a string into a Code 39 format barcode, where each character is encoded as five bars separated by four gaps. Either two of the bars and one of the gaps are wide and others are narrow (10\*4 codes), or three of the gaps are wide and none of the bars are (4 codes). This gives 44 different codes, from which one is a reserved code that is used to denote the start and end of the encoded string.

## The challenge

The input is a string containing only characters from the set

```
1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ-. +/$%

```

The output is the string encoded as a barcode string. The narrow gap and intercharacter gaps are a single space and a wide gap is three spaces. The narrow bar is the UTF-8 byte sequence for the Unicode character "Full block", █, i.e. `0xE2 0x96 0x88` and wide bar is three such byte sequences / characters (`███`). The full list of codes is:

```
      Spaces
      0100 0010 0001 1000 1011 1101 1110 0111
Bars
00000                       +    /    $   %
10001   1    A    K    U
01001   2    B    L    V
11000   3    C    M    W
00101   4    D    N    X
10100   5    E    O    Y
01100   6    F    P    Z
00011   7    G    Q    -
10010   8    H    R    .
01010   9    I    S  space          1=wide
00110   0    J    T  start/end      0=narrow

```

The bars and spaces are interleaved, starting at a bar, so for example Q is

```
bar   0 0 0  1     1
code  █ █ █ ███   ███
space  0 0 0    1

```

After encoding all the characters, the string is delimited at both ends with `█ █ ███ ███ █`. The intercharacter gap, a single space, is inserted between every letter. Your solution may output trailing spaces and a trailing newline (in that order).

## Examples

```
""     → "█   █ ███ ███ █ █   █ ███ ███ █"

"A"    → "█   █ ███ ███ █ ███ █ █   █ ███ █   █ ███ ███ █"

"C++"  → "█   █ ███ ███ █ ███ ███ █   █ █ █   █ █   █   █ █   █ █   █   █ █   █ ███ ███ █"

"GOLF" → "█   █ ███ ███ █ █ █ █   ███ ███ ███ █ ███ █   █ █ ███ █ █   ███ █ ███ ███   █ █ █   █ ███ ███ █"

```

Standard input/output formats are allowed and standard loopholes are disallowed. This is , so the shortest code measured in bytes wins!

# Answer
> 1 votes
# Charcoal, 90 bytes

```
⪫ＥＥ⪫**Ｓ⌕⁺⁺⭆…αχ﹪⊕μχα-. *+/$%ι⪫Ｅ⁵⁺⎇μ× ∨⁼›ι³⁹⁼²﹪⁻÷ι∨›ι³⁹χμ⁴¦³ω×█∨›ι³⁹∨§↨℅§.6':+3<-59ι²⊕μ³ω

```

Try it online! Note: Trailing space. Link is to verbose version of code. Explanation:

```
⪫ＥＥ⪫**Ｓ...⪫Ｅ⁵⁺...ω

```

Wrap the input string in `*`s and then map over it twice, finally joining the result with spaces. For the second map, there is then an additional map over the implicit range `0..4`, where two substrings are concatenated, and those results are then joined with the predefined empty string constant.

```
⌕⁺⁺⭆…αχ﹪⊕μχα-. *+/$%ι

```

For the first inner map, create a string formed by taking the incremented digits, the uppercase alphabet, and the symbols `-. *+/$%`, and look up the position of the mapped input character. For example, `C++` would map to `[12, 40, 40]`.

```
⎇μ× ∨⁼›ι³⁹⁼²﹪⁻÷ι∨›ι³⁹χμ⁴¦³ω

```

The first substring represents the spaces before the bars. There is nothing before the first bar, but the other bars depend on the position of the mapped input character: if it is over 39, then only one place has a single space, while if it is under 40, then only one place has three spaces, and the position is also converted to a column by dividing it by 10. If the column and the loop index differ by 2 (modulo 4) then that is the odd place out.

```
×█∨›ι³⁹∨§↨℅§.6':+3<-59ι²⊕μ³

```

The second substring represents the bars. If the position is over 39 then there is always one bar otherwise the position is looked up in an array of bits mapped to characters. For instance, if the position is 12, then that is circularly indexed to the character `'`, which is `100111` in binary, indicating wide bars in columns 1 and 2. (The leading `1` is ignored, it simply ensures a consistent bit count.)

# Answer
> 7 votes
# JavaScript (ES6), ~~225~~ 212 bytes

*Saved 4 bytes thanks to @l4m2*

```
s=>`#${s}#`.replace(/./g,c=>'0202020202'.replace(/./g,(j,k)=>[C='█',C+C+C,' ','   '][(i="%+/$U1AKV2BLW3CMX4DNY5EOZ6FP-7GQ.8HR 9IS#0JT".indexOf(c),[170,257,260,5,272,17,20,320,65,68,80][i>>2]^2<<i%4*2)>>k&1|j]))

```

Try it online!

### How?

The table can be rearranged such that the 9-bit binary mask of the character is quickly deduced from its row and column using the following formula:

```
n = m XOR (2 << k)

```

with:

```
  m  | k: 0   2   4   6
-----+------------------      Examples:
 170 |    %   +   /   $
 257 |    U   1   A   K         'G' = 320 XOR (2 << 4) = 320 XOR 32 = 352
 260 |    V   2   B   L
   5 |    W   3   C   M         '+' = 170 XOR (2 << 2) = 170 XOR 8  = 162
 272 |    X   4   D   N
  17 |    Y   5   E   O
  20 |    Z   6   F   P
 320 |    -   7   G   Q
  65 |    .   8   H   R
  68 |   spc  9   I   S
  80 |    #   0   J   T

```

# Answer
> 3 votes
# Red, 452 445 bytes

```
func[s][q: func[x y z][append/dup x y z]append insert s"*""*"b:
func[n][v: copy[]until[append v n % 2 * 2 + 1
1 > n: n / 2]q v 1 5 - length? v
reverse v]a: q":1234567890:ABCDEFGHIJ:KLMNOPQRST:UVWXYZ-. *"" "44
a/45: #"+"a/56: #"/"a/67: #"$"a/78: #"%"foreach t s[i: index? find a t
k: b pick[0 17 9 24 5 20 12 3 18 10 6]either 0 = j: i % 11[11][j]m:
b pick[8 4 2 16 22 26 28 14]i - 1 / 11 + 1 z: copy""repeat n 5[q z"█"k/(n)
q z" "m/(n)]prin z]]

```

Try it online!

I'll try to golf it further, but I don't expect much from this naive solution.

# Answer
> 2 votes
# C (gcc), ~~311~~, 303 bytes

```
(*P)()=printf;i;j;w;m[]={170,257,260,5,272,17,20,320,65,68,80};char*b=" \0\xE2\x96\x88",*t="%+/$U1AKV2BLW3CMX4DNY5EOZ6FP-7GQ.8HR 9IS#0JT",*c;p(x){j=256;w=2;while(j){P(b+w);if(x&1){P(b+w);P(b+w);}x/=2;j>>=1;w=2*!w;}P(" ");}f(char*_){p(82);for(c=_;*c;c++){i=strchr(t,*c)-t;p(m[i>>2]^(2<<(i&3)*2));}p(82);}

```

Try it online!

-8 thanks to ceilingcat

Uses encoding strategy from Arnauld's answer. TIO link includes `-w` switch and boilerplate to remove warnings, these are unnecessary and thus not included in the score.

Aside from the encoding scheme as explained by Arnauld, the other trick here is to maintain the `w` variable as toggling between 2 and 0 (`w=2*!w`). This allows me to choose between the first and second strings in `b`. The first is a space, the second is the filled rectangle.

# Answer
> 2 votes
# Java 10, 455 bytes

```
s->{String r="",R=r;for(var c:("~"+s+"~").split(""))r+=r.format("%9s",Long.toString(new int[]{148,289,97,352,49,304,112,37,292,100,52,265,73,328,25,280,88,13,268,76,28,259,67,322,19,274,82,7,262,70,22,385,193,448,145,400,208,133,388,196,138,162,168,42}["~1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ-. +/$%".indexOf(c)],2)).replace(' ','0');for(int l=r.length(),i=0,c;i<l;R+=""+(i%9%2<1?c<49?"█":"███":c<49?" ":"   ")+(i%9>7&++i<l?" ":""))c=r.charAt(i);return R;}

```

Try it online.

**Explanation:**

```
s->{                     // Method with String as both parameter and return-type
  String r="",           //  Temp-String, staring empty
         R=r;            //  Result-String, starting empty as well
  for(var c:("~"+s+"~")  //  Prepend and append "~" to the input
            .split(""))  //  And loop over each character
    r+=r.format("%9s",Long.toString(
                         //   Convert the following integer to a 9-bit binary String:
       new int[]{148,289,97,352,49,304,112,37,292,100,52,
                 265,73,328,25,280,88,13,268,76,28,259,67,322,
                 19,274,82,7,262,70,22,385,193,448,145,400,208,
                 133,388,196,138,162,168,42}
                         //    Array containing all decimal values of the binary Strings
       ["~1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ-. +/$%".indexOf(c)]
                         //    with the index based on the current character
   ,2)).replace(' ','0');
                         //   (also part of the integer to 9-bit binary String conversion)
  for(int l=r.length(),i=0,c;i<l;
                         //  Loop `i` over the temp-String
      R+=                //    After every iteration: append the following to the result:
         ""+(i%9%2<1?    //     If `i` modulo-9 modulo-2 is 0:
              c<49?      //      And `c` is '0':
               "█"       //       Append a single block
              :          //      Else:
               "███"     //       Append three blocks
             :c<49?      //     Else-if `c` is '0':
              " "        //      Append a single space
             :           //     Else:
              "   ")     //      Append three spaces
         +(i%9>7         //     If `i` modulo-9 is 8,
           &++i<l?       //     and this is not the very last character
            " "          //      Append a space delimiter
           :             //     Else:
            ""))         //      Append nothing more
    c=r.charAt(i);       //   Set `c` to the current character in `r`
  return R;}             //  Return the result

```

# Answer
> 2 votes
# C (gcc), ~~241 239 227 213~~ 207 bytes

```
#define P printf(i%2?" ":"█")
i;p(x){for(i=9;i--;x/=2)P,x&1&&P+P;P;}f(char*_){p(82);for(char*t="%+/$U1AKV2BLW3CMX4DNY5EOZ6FP-7GQ.8HR 9IS#0JT";*_;p(L"ªāĄ\5Đ\21\24ŀADP"[i/4]^2<<i%4*2))i=index(t,*_++)-t;p(82);}

```

Try it online!

Based on @LambdaBeta's implementation.

Slightly less golfed:

```
#define P printf(i%2?" ":"█")
i;
p(x){
 for(i=9;i--;x/=2)
  P,
  x&1&&
   P+
   P;
 P;
}
f(char*_){
 p(82);
 for(char*t="%+/$U1AKV2BLW3CMX4DNY5EOZ6FP-7GQ.8HR 9IS#0JT";*_;p(L"ªāĄ\5Đ\21\24ŀADP"[i/4]^2<<i%4*2))
  i=index(t,*_++)-t;
 p(82);
}

```

# Answer
> 1 votes
## Perl 5, 244 bytes

```
$l="{ ,   ,...,.........}"x9;@h{$",qw($ % + - . /),0..9,'',A..Z}=(<"$l">)[q{..=9...Z.>>...J=9..j.%r1...=).[.>=-..Ux?V.^=8.>.6o+ax_.=(..B=,..Yx6..b=(..#r'p.^...G.<=,..Sx5B.\=(.V.It..z:..-z.=<6.}=~s/./ord$&/gre=~/.{6}/g];s/^|./$h{$&} /g;$\=$h{''}

```

Try it online!

Contains many unprintables and high-byte characters, TIO link provides an `xxd` representation. I'd hoped this would have ended up smaller, and I might still be able to pack the data in a more efficient way so I'll see how I go. This builds up all permutations of `" "," ","█","███"` and then maps the indicies of the list to the corresponding characters.

# Answer
> 1 votes
# Haskell, ~~275~~ 270 bytes

```
z=0:z
x!0=[]
x!n=mod n x:x!div n x
e c|Just a<-lookup c.zip"W3YZ56C$EF. 89*HM/ORU1QGNTDJ7%40LSBIP2-+XVKA".((++)<*>(reverse<$>))$take 9.(++z).(2!)<$>scanl(+)7(67!0x117CDBC49F9EEEF11C3A659CACB31236)=zipWith(\l c->c<$[1..2*l+1])(a++[0])(cycle"█ ")>>=id
f s='*':s++"*">>=e

```

Try it online!

The operator `x!n` that calculates the x-base digits of n, is used twice to decompress the codes. The codes are compressed first as binary strings with wide = 1 and narrow = 0, with no regard to color, e.g. `R↔10000110↔262`. These numbers are then sorted and differenced to get numbers in the range \[3,66\], which are compressed with reverse of the binary digit algorithm as `0x117CDBC49F9EEEF11C3A659CACB31236`. This contains only half of the codes, the rest are reverses of these.

Ungolfed:

```
z=0:z                       -- infinite zeroes for padding
x!0=[]                      -- digits of n in base x, recursion base case
x!n=mod n x:x!div n x       -- digits of n in base x
e c | Just a                -- read upwards from (*)
  <-lookup c                -- lookup code, given letter
  . zip"W3YZ56C$EF. 89*HM/ORU1QGNTDJ7%40LSBIP2-+XVKA"
                            -- combine codes with correct letters
  . ((++)<*>(reverse<$>))   -- concatenate list and list with reverse codes
  $ take 9                  -- take nine
  . (++z)                   -- pad with infinite zeroes on right
  . (2!)                    -- convert to binary digits – [[1,1,1],[1,0,1,1]…]
  <$> scanl (+) 7           -- cumulative sum starting from 7 – [7,13,19,22,25…]
        (67!0x117CDBC49F9EEEF11C3A659CACB31236)
                            -- (*) digits in base 67 – [6,6,3,3,3,9,5,7…]
  = zipWith
      (\l c->c<$[1..2*l+1]) -- combine width and color, length is 2*l+1
      (a++[0])              -- list of widths as 0/1, 0 added for interchar gap
      (cycle"█ ")           -- infinite list of bar colors, leftovers are unused
  >>=id                     -- concatenate
f s='*':s++"*">>=e          -- surround string with delimiters, map e and concat

```

---
Tags: code-golf
---