title: Encode the date in Christmas Eve format

text:
# Question
Title: Encode the date in Christmas Eve format
The day this post was published was Christmas Eve. Tomorrow will be Christmas. Yesterday was Christmas Eve Eve. In two days it will be

```
Christmas Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve

```

.

Your job is to take the date the program is run and encode it in Christmas Eve format.

* If your program is run on Christmas, it should output the string "Christmas".
* If your program is not run on Christmas, it should output the string "Christmas", followed by the string " Eve" repeated `n` times, where `n` is the number of days until Christmas.
    + Note that this must be based on the *next* Christmas. For example, if the day is April 26, 2019, you must do your calculation based on December 25, 2019, not any other Christmas.
    + Remember to count leap days.
* Christmas is December 25th of every year.

This is , so the shortest code wins! Note though that the goal is not to find the shortest program in any language, but to find the shortest program in every particular language. For example, if you find the shortest C++ program, then it wins this contest for C++, even if someone finds a shorter program in Python.

# Answer
> 58 votes
# SmileBASIC, ~~73~~ ~~71~~ 67 bytes

```
?"Christmas";
@L?" Eve"*(D!=P);
P=D
DTREAD OUT,M,D
IF M/D-.48GOTO@L

```

The program prints "Christmas", then prints " Eve" every time a day passes, until it is December 25th. (12/25 = 0.48)
May take up to a year to run.

# Answer
> 24 votes
# Excel formula, 59 bytes

```
="Christmas"&REPT(" Eve",DATE(YEAR(NOW()+6),12,25)-TODAY())

```

# Answer
> 12 votes
# Perl 6, ~~61~~ 47 bytes

~~say 'Christmas'~' Eve'x(Date.today...^{.month==12&&.day==25})~~

```
say 'Christmas'~' Eve'x(Date.today...^/12\-25/)

```

Try it online!

*-14 bytes (!) thanks to Jo King*

`Date.today ...^ /12\-25/` is the sequence of dates starting today and ending the day before Christmas. (The regular expression `/12\-25/` is matched against the string representation of the dates.) The string `" Eve"` is replicated a number of times equal to the length of that sequence, and is output after the string `"Christmas"`.

# Answer
> 8 votes
# , ~~112 106~~ 72 bytes

Via @digEmAll and @J.Doe

```
x=Sys.Date()-1;cat('Christmas');while(!grepl('12-25',x<-x+1))cat(' Eve')

```

Try it online!

My original answer was prior to the clarification that the code was to take the date on which the code is run as input. It could be modified as above to save many bytes but I won't bother.

```
function(x,z=as.Date(paste0(strtoi(format(x,"%Y"))+0:1,"-12-25"))-x)cat("Christmas",rep("Eve",z[z>=0][1]))

```

Try it online!

Explanation: everyone's at church so I have time to do this. Extract the year, coerce to integer. Make vector of that year's Xmas and the next year's Xmas and subtract the input date to get a vector of two differences between the input date and those two Xmases.

Pick the non-negative one and `cat` "Christmas" with that many "Eves".

# Answer
> 8 votes
# Windows PowerShell, ~~67~~ ~~64~~ 63 bytes

```
for(;1225-'{0:Md}'-f(date|% *ys $i)){$i++}'Christmas'+' eve'*$i

```

Try it online!

Managed to shave off ~~3 bytes~~ 4 bytes (thanks Cows quack) by using the `-f`ormat operator instead of `.ToString()`, and then subtracting the date string from the numerical value 1225 instead of doing a comparison with `-ne`. The resulting integer will be interpreted as a boolean for the conditional where `0` (which will happen on Christmas) is interpreted as `False` (don't enter the loop), and any other value is interpreted as `True` (enter the loop).

Since the integer is on the left now, the date string will be converted to the integer and math will be done, as opposed to the previous version where the `1225` integer was converted to string for the comparison.

### Original Version

---

# Windows PowerShell, 67 bytes

```
for(;(date|% *ys $i|% tost* Md)-ne1225){$i++};'Christmas'+' eve'*$i

```

Try it online!

Using a `for` loop as a `while` loop basically, because it's shorter. In the loop condition we check the current date (`date`, a shortened form of `Get-Date`), piped to `ForEach-Object`'s alias `%`, using the form that can invoke a method by wildcarded name; in this case the method is `AddDays()` on the `DateTime` object, and the value we give it is `$i`.

This gets piped to `ForEach-Object` again to invoke the `ToString()` method, with format string `Md` (month, then day, minimal digits since we don't care for what comes next). This string is then tested to see if it's not equal `-ne` to the number `1225`, which will be converted to a string for the comparison, saving me the quotes.

This is why it doesn't matter that the months and days are single digits, it will never be ambiguous because there's no other day of the year that would stringify to `1225`.

The loop continues until the string *is* `1225`. At the beginning of the program, `$i` will be zero so it will be comparing today's date, and the loop will never execute, but for any other day `$i` gets incremented in the loop body, so that we will have a count of how many days until the next Christmas, automatically accounting for leap years and whether or not Christmas passed this year.

After the loop we just output the string `Christmas` concatenated with the result of multiplying the string `eve` times the value of `$i` (which, on Christmas day, will be `0`, resulting in no `eve`s).

# Answer
> 7 votes
# C# (Visual C# Interactive Compiler), 89 bytes

```
Write("Christmas");for(var t=DateTime.Now;$"{t:Md}"!="1225";t=t.AddDays(1))Write(" Eve");

```

Try it online!

-3 bytes thanks to @JeppeStigNielsen!

My strategy is pretty straightforward:

1. Initialize a loop variable `t` to the current date
2. Print `Eve` if `t` is not Christmas
3. Add a day to `t` and repeat

I tried some fancier things, but this way required the fewest bytes.

# Answer
> 6 votes
# APL (Dyalog Unicode), ~~76~~ 63 bytesSBCS

Full program. Assumes `⎕IO←0` (zero-indexing).

```
⎕CY'dfns'
'Christmas',' Eve'⍴⍨4×12 25⍳⍨⍉2↑1↓⍉date(⍳366)+days⎕TS

```

Try it online!

`⎕CY'dfns'`**c**o**p**y in the dfns library

`⎕TS` current **t**ime **s**tamp as \[year,month,day,hour,min,sec,ms\]
`days`\[c\] find the number of days\[n\] since 1899-12-31 00:00:00.000
`(⍳366)` add the first 366 integers (0…365) to that
`date`\[c\] find the dates\[n\] that correspond to those numbers (366×7 table; one column per unit)
transpose (7×366 table; one row per unit)
`1↓` drop one row (the years)
`2↑` take the first two rows (months and days)
`12 25⍳⍨` find the index of the first Christmas
multiply that by four
`' Eve'⍴⍨` use that to reshape the character list
`'Christmas ',` append that to this

\[c\] code of that function
\[n\] notes for that function

# Answer
> 6 votes
## T-SQL, ~~92~~ 88 bytes

```
PRINT'Christmas'+REPLICATE(' Eve',DATEDIFF(D,GETDATE(),STR(YEAR(GETDATE()+6))+'-12-25'))

```

Edit: Saved 4 bytes thanks to @BradC.

# Answer
> 5 votes
# Python 2, ~~111~~ 103 bytes

```
from datetime import*
d=date.today()
print"Christmas"+" Eve"*(date((d+timedelta(6)).year,12,25)-d).days

```

Try it online!

Update inspired by Richard Crossley's answer.

Explanation:

```
from datetime import*
# get today as a date, so we don't have to worry about rounding errors due to time
d=date.today()
                              # get the year of the Christmas to compare to
                              # if the current date is after this year's Christmas, the 6 day offset will give the next year
                              # otherwise, returns this year
                              (d+timedelta(6)).year
                         # next Christmas minus the current date
                         date(.....................,12,25)-d
# Christmas, plus (number of days until next Christmas) " Eve"s
print"Christmas"+" Eve"*(...................................).days

```

# Answer
> 4 votes
# Ruby, 80 bytes

```
require'date'
t=Date.today
puts'Christmas'+' Eve'*(Date.new((t+6).year,12,25)-t)

```

Try it online!

Thanks to tsh for his idea

# Answer
> 4 votes
# PHP, 61 bytes

```
Christmas<?for($t=time();date(md,$t+=86400)-1226;)echo" Eve";

```

Run with `-n` or try it online.

# Answer
> 4 votes
# JavaScript, ~~135~~ ~~131~~ ~~121~~ ~~92~~ 88 bytes

My first (naïve) solution (**135b**):

```
t=new Date();n=new Date();n.setMonth(11);n.setDate(25);'Christmas'+' Eve'.repeat((n>=t?n-t:(n.setFullYear(n.getFullYear()+1)-t))/864e5)

```

It sets 2 dates: now and Xmas of this year. If the latter hasn't passed yet, it just diffs them, if it has passed, diffs to next year's Xmas. Uses either diffs for the number of repeats.

(Trying to) Think Outside the Box (**131b**):

```
i=0;f=_=>{t=new Date();if(t.getMonth()!=11||t.getDate()!=25){i++;setTimeout(f,864e5)}else{alert('Christmas'+' Eve'.repeat(i))}};f()

```

The challange specifies WHICH output is required when running the program on a given day, but doesn't specify WHEN to return it...

This will just 'sleep' for a day, increment a counter by 1, and repeat till it's Xmas in order to give the output.

Since JavaScript doesn't guarantee the 'sleep' time, the actual result might be off.

It is also ugly for using the `alert` function, which means wer'e actually not dealing with pure JavaScript, but with browser APIs as well (we can use `console.log` at the cost of 6 extra bytes).

A better approach (**121b**):

```
t=new Date();i=0;while(t.getMonth()!=11||t.getDate()!=25){t=new Date(t.valueOf()+864e5);i++};'Christmas'+' Eve'.repeat(i)

```

Starting from today, increment the date by a day until it's Xmas, then use that loop's counter for the number of repeats required.

Improving (including going through a minifier and using 12Me21's trick to shave extra 5b) (**92b**):

```
for(s='Christmas',t=new Date;t.getMonth()/t.getDate()-.44;)t=new Date(t*1+864e5),s+=' Eve';s

```

Final touches (**88b**):

```
for(s='Christmas',t=new Date;t.getMonth()/(d=t.getDate())-.44;t.setDate(d+1))s+=' Eve';s

```
* For all of the above, REPL is assumed.
* See Vadim's submission - much better than mine!

# Answer
> 4 votes
# Bash +GNU date, ~~72~~, ~~73~~, 67 bytes

```
for((d=7;`date +%-j -d$d\day`-1;d++));{ x+=\ Eve;};echo Christmas$x

```
* one byte saved replacing `!=` with `-`
* another removing extra space
* fix -3 bytes `d=0`, because `date -dday` is date+1 and doesn't work on 25/12
* 6 bytes saved thanks to Toby Speight using %-j format to avoid 0 padding (and octal conversion) and shorter than %d%m compared to 2512

Try it online

# Answer
> 4 votes
# Bash, ~~68~~ ~~65~~ 61 bytes

*Golfed 4 bytes thanks to Nahuel Fouilleul* by using ```` command substitution and `eval` in place of sed `e` and `xargs`

```
echo Christmas `eval date\ -d{0..366}day\;|sed /c.25/Q\;cEve`

```

Try it online!

Inside the ```` command substitution, we have

`eval` run the following string as shell commands

* `date\ -d{0..366}day\;` under brace expansion of `{0..366}`, this results in the string `date -d0day; date -d1day; date -d2day; ... date -d366day;`, each command in this string computing the date between 0 and 366 days from present resulting in output of the format `Wed Dec 26 18:22:33 UTC 2018`, with each in its own line

`|sed` upon which, call the following sed commands

* `/c.25/Q` if the regex `/c.25/` is matched, `Q`uit without printing
* `\;cEve` otherwise change the line to `Eve`

All the required number of `Eve`s are produced each on its own line. This output is captured in ````, and is subject to word splitting where words are split on newlines. Each word is fed as an argument to `echo`.

`echo Christmas `...``

Each argument to `echo` is printed by being separated by spaces, resulting in the desired output.

# Answer
> 3 votes
# Python 2, 128 bytes / Python 3, 130 bytes

of course, two less bytes with Python 2

```
from datetime import date as D
T=D.today()
Y=T.year
a=(D(Y,12,25)-T).days
print("Christmas"+" Eve"*[a,(D(Y+1,12,25)-T).days][a<0])

```

# Answer
> 3 votes
# VBA (Excel), 108 bytes

Copy in a blank module. Prints to the Immediate window:

```
Sub X:s="Christmas":d=Now:For t=1 To (DateSerial(Year(d+6),12,25)-d):s=s &" Eve":Next:Debug.Print s:End Sub

```

**Note:** Using `:` instead of line breaks saves two bytes per line.

Notice that the VBA editor will insert additional spaces between keywords, operators, etc... and parenthesis after the Sub definition, but if you copy and paste this code it will work (I couldn't get rid of that space before the `&`).

Not bad for VBA (for once).

# Answer
> 3 votes
## Python 3, 106 Bytes

```
from datetime import*
d=date.today()
print("Christmas"+" Eve"*(date((d+timedelta(6)).year,12,25)-d).days)

```

# Answer
> 2 votes
# Groovy, 66 bytes

```
d=[]as Date
print'Christmas'+' Eve'*(new Date((d+6).year,11,25)-d)

```

Try it online!

Courtesy of @ASCII-only

# Answer
> 2 votes
# C (gcc), 157 bytes

I thought that I would be able to avoid including `time.h` but that just gave segment faults.

```
#include <time.h>
*t,u;f(){time(&u);t=localtime(&u);t[5]+=t[4]>10&t[3]>25;t[4]=11;t[3]=25;u-=mktime(t);printf("Christmas");for(u/=86400;u++;printf(" Eve"));}

```

Try it online!

# Answer
> 2 votes
# Scala, ~~116~~ 113 bytes

```
var d=new java.util.Date
print("Christmas")
while(!(""+d).contains("c 25")){print(" Eve");d.setDate(d.getDate+1)}

```

Try it online!

Where `c 25` is short for `Dec 25`.

# Answer
> 2 votes
# JavaScript, ~~86~~ 77 bytes

Using REPL it would be

```
for(c='Christmas',d=new Date;!/c 25/.test(d);d=new Date(+d+864e5))c+=' Eve';c

```

Kudos to ASCII-only for **-9** bytes

# Answer
> 2 votes
# Lua, 137 118 bytes.

118 bytes

```
t,d,month,day=os.time,os.date,1,-6year=d"%Y"+(d"%D">"12/25"and 2or 1)print("Christmas",d" Eve":rep(d("%j",t(_G)-t())))

```

137 bytes (previous)

```
t,d=os.time,os.date a=d"*t"a.year,a.month,a.day=a.year+(d"%m%d">"1225"and 1 or 0),12,25 print("Christmas",("Eve "):rep((t(a)-t())/86400))

```

It's worth noting that it doesn't work in LuaJIT (syntax error)

# Answer
> 2 votes
# Julia 1.0, 91 bytes

```
using Dates
t=today()
print(:Christmas," Eve"^~-(tonext(==((12,26))∘monthday,t)-t).value)

```

Try it online!

* -1 byte thanks to @MarcMush: Substitute `1>0` for `true`
* -5 bytes thanks to @MarcMush: Substitute `_.value` for `Dates.value(_)`
* -1 byte thanks to @amelies: print symbol `:Christmas` rather than string `"Christmas"`
* -1 byte thanks to @MarcMush: compose functions with
* -7 bytes thanks to @MarcMush: use Boxing Day as the end date and subtract one in order to eliminate the `same=true` parameter

# Answer
> 1 votes
# MySQL, 102 bytes

pretty much the same as Neil´s T-SQL answer. There seems to be no shorter way in SQL.

```
select concat("Christmas",repeat(" Eve",datediff(concat(year(now()+interval 6 day),"-12-25"),now())));

```

Try it online.

# Answer
> 1 votes
# Scala, 123 bytes

Thanks to ASCII-only's work.

```
print("Christmas")
var d=new java.util.Date
while(d.getMonth()<11||d.getDate()!=25){print(" Eve");d.setDate(d.getDate()+1)}

```

Try it online!

# Scala \+ Joda-Time, 140 bytes

```
import org.joda.time._
var s="Christmas"
var d=DateTime.now
while(d!=d.withDate(d.year().get(),12,25)){d=d.plusDays(1);s+=" Eve"};println(s)

```

Does not run in TIO since it requires Joda-Time library.

# Answer
> 1 votes
# MATLAB, 91 bytes

```
n=datetime
x=datetime(year(n+6),12,25)
s='Christmas'
while days(x-n)>=1 n=n+1 s=[s,' Eve'] end

```

# MATLAB Non-looper, 100 bytes

```
x=datenum(datetime(floor((now+5)/365.2425),12,25))
d=x-now
['Christmas' repmat(' Eve',1,min(d(d>=0)))]

```

# Answer
> 1 votes
# 05AB1E, ~~93~~ ~~89~~ ~~87~~ 81 bytes

```
'ŒÎžfže«Ž9Ú.S©DΘžg+т‰0Kθ4ÖUi390že-X+ë®_i0ë•ΘÏF•º11£®ª₂+ā2QX*+13žf-.£Ože-]Fð'»ˆ}J™

```

Try it online or Try it online with an emulated self-specified date of 'today'.

**Old ~~93~~ ~~89~~ 87 bytes approach that loops over the days one by one:**

```
žežfžg)V'ŒÎ[Y¨JŽ9ÚQ#Y`т‰0Kθ4ÖUD<i\28X+ë<7%É31α}‹iY¬>0ëY1¾ǝDÅsD12‹i>1ë\1Dǝ¤>2}}ǝVð'»ˆ}J™

```

Try it online or Try it online with an emulated self-specified date of 'today'.

**Explanation:**

05AB1E doesn't have any builtins for dates, except for receiving the current year/month/day/hours/minutes/seconds/microseconds, so most bytes are used for manual calculations.

```
'ŒÎ           '# Push dictionary string "christmas"
žfže«          # Append the current month and current day together
        .S     # Compare it with
     Ž9Ú       # Compressed integer 1225
               # (1 if >1225; 0 if ==1225; -1 if <1225)
          ©    # Store this comparison in variable `®` (without popping)
D              # Duplicate it
 Θ             # Check if it's equal to 1 (1 if 1; 0 if 0 or -1)
  žf+          # Add the current year to it
     т‰0Kθ4Ö   # Check if this is a leap year:
     т‰        #  Divmod it by 100
       0K      #  Remove the 0s
         θ     #  Only leave the last item
          4Ö   #  Check if it's divisible by 4
            U  # Pop and store this is_leap_year in variable `X`
i              # If the comparison is 1:
 390že-        #  Push 390 minus the current day
               #  (390 is 31 for days in December and 259 for days of Christmas Day)
 X+            #  Add the is_leap_year check from variable `X`
ë®_i           # Else if the comparison is 0:
    0          #  Push 0
ë              # Else (the comparison is -1):
 •ΘÏF•         #  Push compressed integer 5254545
      º        #  Mirror it to 52545455454525
       11£     #  Only leave the first 11: 52545455454
          ®ª   #  Convert it to a list of digits, and append the -1:
               #   [5,2,5,4,5,4,5,5,4,5,4,-1]
            ₂+ #  Add 26 to each: [31,28,31,30,31,30,31,31,30,31,30,25]
 ā             #  Push a list in the range [1,length] (without popping):
               #   [1,2,3,4,5,6,7,8,9,10,11,12]
  2Q           #  Check which is equal to 2: [0,1,0,0,0,0,0,0,0,0,0,0]
    X*         #  Multiply each by the is_leap_year check of variable `X`
      +        #  Add the values at the same positions in the lists together
 13žf-         #  Push 13 minus the current month
      .£       #  Only leave that many items from the end of the list
        O      #  Sum them together
 že-           #  Subtract the current day
]              # Close the if-else statements
 F             # Loop that many times:
  ð            #  Push a space character " "
  '»ˆ         '#  Push dictionary string "eve"
 }J            # After the loop: join the entire stack together
   ™           # Titlecase each word
               # (after which the result is output implicitly)

```

---

```
žežfžg)V   # Get the current [day,month,year] and save it in variable `Y`
'ŒÎ       '# Push dictionary string "christmas"
[          # Start an infinite loop:
 Y¨J       #  Remove the year, and join the month and day together
       Q   #  Check if this is equal to
    Ž9Ú    #  Compressed integer 1225
        #  #   If this is truthy (thus it's December 25th): stop the infinite loop
 Y`т‰0Kθ4ÖUD<i\28X+ë<7%É31α}‹iY¬>0ëY1¾ǝDÅsD12‹i>1ë\1Dǝ¤>2}}ǝV
           #  Go to the next day, and set `Y` to it
 ð         #  Push a space " "
 '»ˆ      '#  Push dictionary string "eve"
}J         # After the infinite loop: join the entire stack together
  ™        # Titlecase each word
           # (after which the result is output implicitly)

```

See this 05AB1E answer of mine to understand the `is_leap_year` check.

See this 05AB1E answer of mine to understand how we go to the next day (with the second longer approach).

See this 05AB1E tip of mine (sections *How to use the dictionary?* and *How to compress large integers?*) to understand why `'»ˆ` is `"eve"`; `'ŒÎ` is `"christmas"`; `Ž9Ú` is `1225`; and `•ΘÏF•` is `5254545`.

# Answer
> 1 votes
# , 53 bytes

```
"Christmas",(4*(not 12 25~`mm`dd$.z.d+)(1+)/0)#" Eve"

```

# k, 50 bytes

```
"Christmas",(4*(~12 25~`mm`dd$.z.d+)(1+)/0)#" Eve"

```

Increment counter while the date is not Dec 25th, then take that number of copies of " Eve" and append to "Christmas".

# Answer
> 1 votes
# Go, 178 bytes

```
import(."time";."strings")
func f()string{n:=Now()
y:=n.Year()
if n.Month()>11&&n.Day()>25{y++}
return"Christmas"+Repeat(" Eve",int(Date(y,12,25,0,0,0,0,UTC).Sub(n).Hours())/24)}

```

Attempt This Online!

And a variant that takes a `Time` as input, 175 bytes:

```
import(."time";."strings")
func f(n Time)string{y:=n.Year()
if n.Month()>11&&n.Day()>25{y++}
return"Christmas"+Repeat(" Eve",int(Date(y,12,25,0,0,0,0,UTC).Sub(n).Hours())/24)}

```

Attempt This Online!

# Answer
> 0 votes
# C# (Visual C# Interactive Compiler), 141 bytes

```
var g=DateTime.Now;Write("Christmas"+string.Concat(Enumerable.Repeat(" Eve",(new DateTime(g.Year+(g.Day>25&g.Month>11?1:0),12,25)-g).Days)));

```

Try it online!

# Answer
> 0 votes
# Red, ~~89~~ ~~86~~ ~~84~~ ~~78~~ 76 bytes

-10 bytes thanks to ASCII-only!

```
does[a: now prin"Christmas"while[a/3 * 31 + a/4 <> 397][prin" Eve"a: a + 1]]

```

Try it online!

# Answer
> 0 votes
# Perl 5, 68 bytes

```
print"Christmas";print" Eve"while localtime($i++*86400+time)!~/c 25/

```

Try it online!

Where `c 25` is short for `Dec 25`.

# Answer
> 0 votes
# Japt `-S`, ~~39~~ 38 bytes

```
Ð
f
@f1V° UÎ¶B©25¶Uf}a Æ"Eve"Ãi`CËItµs

```

Test it

```
Ð\nf\n@f1V° UÎ¶B©25¶Uf}a Æ"Eve"Ãi`CËItµs
Ð                                            :Create date object for current date
 \n                                          :Assign to variable U
   f                                         :Get date value of U
    \n                                       :Assign to variable V
      @                                      :Function taking an integer X as argument
       f1                                    :  Set the date of U to (modifies U)
         V°                                  :  V, postfix incremented
            UÎ                               :  0-based month value of modified U
              ¶                              :  Check equality with
               B                             :    11
                ©                            :  Logical AND with
                 25¶                         :  Check equality between 25 and
                    Uf                       :    Date value of modified U
                      }                      :End function
                       a                     :Return the first value of X>=0 that returns true
                         Æ                   :Map the range [0,result)
                          "Eve"              :  Literal string
                               Ã             :End map
                                i            :Prepend
                                 `CËItµs     :  Compressed string "Christmas"
                                             :Implicit output joined with spaces

```

# Answer
> 0 votes
# jq -jn, 60 bytes

```
"Christmas",(now|while(gmtime[1:3]!=[11,25];.+86400)|" Eve")

```

Try it online!

# Answer
> 0 votes
# Lua, 87 bytes

```
w=io.write w'Christmas't=os.time()while os.date('%d%m',t)~='2512'do t=t+86400w' Eve'end

```

Try it online!

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


# Question
Title: Find the nearest Date, given a TargetDate and Day of Week
Find the nearest Date to a TargetDate for a given Day of Week.

For example, given a date of `20161219` and a day of week of `Friday (6)`, the answer is `20161216`.

Another example, given a date of `20161219` and a day of week of `Wednesday (4)`, the answer is `20161221`.

A final example, given a date of `20161219` and a day of week of `Monday (2)`, the answer is `20161219`.

**Rules:**

* The Date format for the input and output must match. In the examples, I used `yyyymmdd`, but you may use any format as long as the year (at least two digits), month, and day of month are "human readable".
* Day of Week is input as an integer. In my example, Sunday is the first day of the week, therefore it is day of week number `1`. You can have any Day of Week numbering, as long as you note it when it differs from the example.
* Years 1970 through 2030 must be accommodated.
* Common language date tools and libraries are allowed, but street cred is given to those that choose not to use them.
* Least number of *bytes* wins.

# Answer
# Perl 6, 46 bytes

```
{~first *.day-of-week==$^b,Date.new($^a)-3..*}

```

A lambda that accepts two arguments: A date string in `yyyy-mm-dd` format, and a weekday number between `1`=Monday and `7`=Sunday.

Explanation:

```
                           Date.new($^a)       # Construct Date object from first argument.
                                        -3     # Subtract 3 days.
                                          ..*  # Construct a Range from that, to infinity.
  first                   ,                    # Iterate the range, and return first date...
        *.day-of-week==$^b                     # whose weekday number equals the second arg.

```

---

Using the date and weekday format used in the examples, it would be 88 bytes:

```
{S:g/\-//with ~first *.day-of-week==($^b-2)%7+1,Date.new(|($^a~~/(....)(..)(..)/))-3..*}

```
> 1 votes

# Answer
# Perl 6, 83 bytes

```
->$_,\w{~(Date.new(|m/(....)(..)(..)/)-3...*.day-of-week%7+1==w)[*-1]~~{S:g/"-"//}}

```

Try it

## Expanded

```
->     # pointy block lambda
  $_,
  \w
{
  ~(  # turn into a Str

    Date.new( |m/(....)(..)(..)/ ) - 3 # three days earlier
    ...                                # generate a sequence
    *.day-of-week % 7 + 1 == w         # stop when the right day is found

  )[*-1]  # the last one

  ~~      # apply the following block

  {
    S:g/"-"//  # remove ｢-｣
  }
}

```
> 2 votes

# Answer
## JavaScript (ES6), 93 bytes

```
(s,n,d=new Date(s))=>d.setDate(d.getDate()+(n+9-d.getDay())%7-3)&&d.toISOString().slice(0,10)

```

Uses `%Y-%m-%d` date format. If `%a %b %d %Y` is an acceptable date format, then for 82 bytes:

```
(s,n,d=new Date(s))=>d.setDate(d.getDate()+(n+9-d.getDay())%7-3)&&d.toDateString()

```

I could save a further 2 bytes by requiring Sunday = 10 to Saturday = 16, but that's a silly day of week mapping. Previous ~~142~~ 141 bytes (thanks to @Guedes) version that used the specific YYYYMMDD date format, with its explanation:

```
(s,n,d=new Date(s.replace(/(?=..(..)?$)/g,'-')))=>d.setDate(d.getDate()+(n+9-d.getDay())%7-3)&&d.toISOString().replace(/-(..)-(..).*/,'$1$2')

```

This feels far too long. Explanation: First, inserts `-`s into the date to get it into ISO format which `new Date` can then parse. Then, compares the desired day with the actual day to get a value between `-3` and `3` for the actual offset. The magic `9` comes from `7` (because `%` is CPU modulo, not true modulo) plus `3` (for the `-3` offset) minus `1` (because `n` is 1-indexed and `getDay` is 0-indexed). The date is then converted back into ISO format and the unwanted characters removed.
> 2 votes

# Answer
# Bash + coreutils, 50

```
date -d$1+$[($2-`date -d$1 +%u`+9)%7-3]day +%Y%m%d

```

Try it online.

* `date -d$1 +%u` gives the day of week (1..7); 1 is Monday
* This is subtracted from the input day of week to give a difference of day indexes. We want to add a factor between in the range \[-3, 3\] to the input date to get the closest date, so we add a magic factor 9, take the modulo 7, then subtract 3. The magic factor 9 is `3 + 7 - 1`. The 3 adjusts the input range for range \[-3, 3\], and is subtracted again after the modulo. The 7 is required because bash modulo is the same as CPU modulo and can give -ve results - adding 7 adjusts into the right range. The -1 is because in the input, 1 is Sunday, but with the %u output, 1 is Monday.
* The outer `date` then parses `<input date> + <magic factor>days` and presents it in the YYYYMMDD format.
> 2 votes

# Answer
# Python, ~~150~~ 149 bytes

```
from datetime import*
lambda s,n,t='%Y%m%d':[d for d in[datetime.strptime(s,t)+timedelta(o-3)for o in range(7)]if(n-2)%7==d.weekday()][0].strftime(t)

```

Oouuf, 149. **repl.it**

Unnamed function that takes a string `s`, the date as specified (using format string `t='%Y%m%d'` for both input and output) and a number in \[1,7\], `n`.
Inspects the seven days from three days prior to three days after that given for the day of the week requested.
The week in `datetime` starts on Monday and is zero based, so the test is `(n-2)%7==d.weekday()`.
> 1 votes

# Answer
## R, 119 77 56 bytes

Unnamed function that takes two inputs, the date `D` (string) and the day `d` (numeric).

```
function(D,d,s=-3:3+as.Date(D))s[lubridate::wday(s)==d]

```

Uses the function `wday()` from the `lubridate` package. It can conveniently convert `Date` objects into week days with `1` being treated as Sunday by default.

Edit: I/O is now the default of the `as.Date()` function: `"YYYY-mm-dd"`

**Ungolfed and Explained**

```
function(D,d){
    D=as.Date(D);            # Format input date
    s=-3:3+D;                # Generate sequence of +- 3 days
    s[lubridate::wday(s)==d] # Match the weekday that equals to target day
}

```

Edit: Now creates a sequence of `+-3` days for which any given weekday is guaranteed to be found in. Subsequently we only have to match one day which made the problem much easier.
> 1 votes

# Answer
# SAS Macro Language, 110 Bytes

```
%macro s(d,a);%put %sysfunc(putn(%sysfunc(intnx(week.&a.,%eval(%sysfunc(putn(&d,8.))-4),1)),yymmddn8.));%mend;

```

A terrible golfing language but here's the explanation (from the inside out):

Create a macro `s` that accepts a date input `d` and a numeric weekday `a`. Then `%eval(%sysfunc(putn(&d,8.))-4)` converts the date to a SAS numeric date and decrements it by 4 days. The `intnx` function then returns the next occurrence of the specified weekday. `putn` then formats the date back to yyyymmdd and `%put` prints the output to the log.
> 1 votes

# Answer
## Mathematica, ~~85~~ 49 bytes

```
#~DatePlus~Mod[#2-#~DateValue~"ISOWeekDay",7,-3]&

```

The input format for dates is either a list like `{2016, 12, 16}` or an actual `DateObject` (I think a few others work as well, but I've tested these). In either case, the output format will match automatically. The day numbering starts from `1` on Mondays.

The idea is to compute the difference between the input weekday and the target weekday with `#2-#~DateValue~"ISOWeekDay"` and then to map it into `[-3, 3]` using a modulo with offset (i.e. `Mod[...,7,-3]`). The result is simply added to the input date (the default unit for date object addition is days).
> 1 votes

# Answer
# Shell + GNU date, 43 bytes

```
date +%F -d$1-3day`date -d$1+$2day +%w`day

```

I wish I could explain how this works, but there was so much trial-and-error tweaking it no longer makes sense even to me! We start by subtracting three days so that adding a number in range 0-6 gives the nearest. But why adding the desired weekday to the target date gives the necessary offset has slipped my grasp.

Input as in the question; output format is YYYY-MM-DD.

Online test
> 0 votes

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


title: Consecutive Distance Rating

text:
# Question
Title: Consecutive Distance Rating
We'll call the consecutive distance rating of an integer sequence the sum of the distances between consecutive integers. Consider `2 9 3 6 8 1`.

```
2 9 3 6 8 1
<----5---->
<-2->
  <--3-->

```

\\$2\\$ and \\$1\\$ are consecutive integers, and their distance apart in the sequence is \\$5\\$.
\\$2\\$ and \\$3\\$ are consecutive integers, and their distance apart in the sequence is \\$2\\$.
\\$9\\$ and \\$8\\$ are consecutive integers, and their distance apart in the sequence is \\$3\\$.
The consecutive distance rating is the sum of these distances: \\$10\\$.

## Challenge

Given a possibly empty list of positive, **unique** integers, find its consecutive distance rating.

## Format

You must accept a list of integers and output an integer in any reasonable format.

## Rules

## Test cases

```
[] -> 0
[33] -> 0
[65 57 78 32 81 19 50 24 85 3 97 43 10 73] -> 0
[1 2] -> 1
[2 1] -> 1
[1 2 3] -> 2
[1 3 2] -> 3
[31 63 53 56 96 62 73 25 54 55 64] -> 26
[54 64 52 39 36 98 32 87 95 12 40 79 41 13 53 35 48 42 33 75] -> 67
[94 66 18 57 58 54 93 53 19 16 55 22 51 8 67 20 17 56 21 59] -> 107

```

# Answer
> 10 votes
# Python 2, 60 bytes

```
lambda l:sum(abs(l.index(x)-l.index(x+(x+1in l)))for x in l)

```

Try it online!

# Answer
> 8 votes
# Jelly, 8 bytes

```
iⱮ‘aạ¥JS

```

Try it online!

-1 byte thanks to Unrelated String!

## How it Works

```
iⱮ‘aạ¥JS - Main link. Takes a list L on the left
  ‘      - Increment all elements in L
 Ɱ       - Over each incremented element:
i        -   Get its 1-based index in L, or 0 if not present
           Call this list of indices I
      J  - Indices of L; [1, 2, 3, ..., len(L)]
     ¥   - Last 2 links as a dyad f(I, J):
    ạ    -   Absolute difference, element wise, between I and J
   a     -   And; Where there are non-zeroes in I, replace the value with corresponding difference
       S - Sum

```

# Answer
> 8 votes
# , 22 bytes

```
[:+/&,|@(#\-/#\)*1=-/~

```

Try it online!

Consider `f 2 9 3 6 8 1`:

* `-/~` Table of differences:

```
0 _7 _1 _4 _6 1
7  0  6  3  1 8
1 _6  0 _3 _5 2
4 _3  3  0 _2 5
6 _1  5  2  0 7
_1 _8 _2 _5 _7 0

```
* `1=` Where are they 1?

```
0 0 0 0 0 1
0 0 0 0 1 0
1 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0

```
* `|@(#\-/#\)` Table of absolute value of index differences:

```
0 1 2 3 4 5
1 0 1 2 3 4
2 1 0 1 2 3
3 2 1 0 1 2
4 3 2 1 0 1
5 4 3 2 1 0

```
* `*` Elementwise product of those tables:

```
0 0 0 0 0 5
0 0 0 0 3 0
2 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0

```
* `[:+/&,` Sum of that table flattened:

```
10

```

# Answer
> 5 votes
# 05AB1E, 8 bytes

```
ãʒÆ}kÆÄO

```

Try it online!

```
ã          # all pairs of integers from the input
 ʒ }       # keep those where the following results in 1:
  Æ        #   reduce by subtraction
    k      # for each integer in each pair get the index in the input list
     Æ     # reduce each pair of indices by subtraction
      Ä    # take absolute value
       O   # sum all distances

```

# Answer
> 5 votes
# Red, ~~88~~ 77 bytes

```
func[b][s: 0 forall b[s: s + absolute offset? b any[find head b 1 + b/1 b]]s]

```

Try it online!

Uses @xnor's method \- don't forget to upvote it!

# Answer
> 5 votes
# , 45 bytes

```
sum(abs(seq(a<-scan())-match(a+1,a)),na.rm=T)

```

Try it online!

Merged solutions: mine and @Dominic's.

---

Previous solution:

### , 48 bytes

```
x=scan();`*`=match;sum(abs(x*x-(x+1)*x),na.rm=T)

```

Try it online!

# Answer
> 5 votes
# , 47 bytes

```
sum(abs(seq(a<-scan())-(b=match(a+1,a,0)))*!!b)

```

Try it online! with test wrapper stolen from pajonk's answer stolen from Kirill L's answer

# Answer
> 4 votes
# JavaScript (Node.js), 60 bytes

```
n=>n.map((e,i)=>z+=(j=n.indexOf(e+1))+1?j>i?j-i:i-j:0,z=0)|z

```

Try it online!

# Answer
> 4 votes
# , 48 bytes

```
`?`=diff;sum(abs(?o<-order(x<-scan()))*!1<?x[o])

```

Try it online!

# Answer
> 4 votes
# Ruby, ~~50~~ 48 bytes

```
->a{r=-1;a.sum{((a.index(a[r+=1]+1)||r)-r).abs}}

```

Try it online!

Thanks @ovs for -2 bytes.

# Answer
> 4 votes
# Brachylog, 15 bytes

```
sᶠ{↻h₂-ȧ1&b}ˢcl

```

Try it online!

```
sᶠ                 Find every substring of the input.
  {        }ˢ      Keep only those for which
       ȧ           the absolute value of
      -            the difference of
   ↻h₂             the first and last elements
        1          is 1,
         &b        and remove their first elements.
             c     Concatenate them,
              l    and output their combined length.

```

# Answer
> 4 votes
# Julia 1.0, 63 55 bytes

Inspired by the answer of xnor

Improved version, thanks @MarcMush:

```
!x=sum(abs,[(I=indexin)(i,x)-I(i+(i+1∈x),x) for i=x])

```

Try it online!

First version:

```
!x=sum(abs.([indexin(i,x)-indexin(i+(i+1 in x),x) for i in x]))

```

Try it online!

# Answer
> 3 votes
# Vyxal `s`, 13 bytes

```
›vḟv›ƛ&›[¥ε|0

```

Try it Online!

A port of the jelly answer, and I think the best I'm gonna get.

## Attempted port of Jonas, 21 bytes

```
Ẋƛ÷ε1=;?Lɾƛ?Lɾ-ȧ;f*∑½

```

Try it Online!

## Old version, 23 bytes

```
L²(⁰Ẋni÷ε1=[n6ḋ÷ε&+])¥½

```

Try it Online! I still think there's a bit more I can do.

## Older version, 28 bytes

```
L(x|L(←x i⁰niε1=[n←xε&+]))¥½

```

Try it Online!

This. Is. Horrible.

# Answer
> 3 votes
# Charcoal, 15 bytes

```
Ｉ↨¹Ｅθ↔↨¹⁻⌕Ａθ⊕ικ

```

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

```
    θ           Input array
   Ｅ            Map over elements
             ι  Current value
            ⊕   Incremented
         ⌕Ａ     Find all (i.e. at most one) matches
           θ    In input array
        ⁻       Vectorised subtract
              κ Current index
      ↨¹        Take the sum
     ↔          Take the absolute value
 ↨¹             Take the sum
Ｉ               Cast to string
                Implicitly print

```

Note that base 1 conversion is used to sum as this works on empty lists.

# Answer
> 3 votes
# Red, 129 bytes

```
func[a][s: 0
b: sort copy a
while[b/2][s: s + either b/2 - b/1 = 1[absolute(index? find a b/2)- index? find a b/1][0]b: next b]s]

```

Try it online!

sorts the array, and adds the index difference to `s` if pair of elements has an absolute difference of 1.

Not sure how to shorten the reuse of `index? find`, but I think it can be shortened. `abs` alias for `absolute` is not available, even in version 0.6.4.

# Answer
> 3 votes
# Excel, 52 bytes

```
=LET(x,A:A,SUM(IFERROR(ABS(ROW(x)-XMATCH(x-1,x)),)))

```

Input numbers in column A. For each number x in column A look for x-1. If found add the difference in rows between x and x-1.

# Answer
> 3 votes
# MATL, 9 bytes

```
tQ!=&f-|s

```

Try it online! Or verify all test cases.

### How it works

Consider input `[2 9 3 6 8 1]` as an example.

```
tQ   % Implicit input. Duplicate, add 1; element-wise
     % STACK: [2 9 3 6 8 1], [3 10 4 7 9 2]
!    % Transpose
     % STACK: [2 9 3 6 8 1], [3; 10; 4; 7; 9; 2]
=    % Test for equality (element-wise with broadcast)
     % STACK: [0 0 1 0 0 0;
               0 0 0 0 0 0;
               0 0 0 0 0 0;
               0 0 0 0 0 0;
               0 1 0 0 0 0;
               1 0 0 0 0 0]
&f   % Two-output find: row and column indices of nonzeros
     % STACK: [6; 5; 1], [1; 2; 3]
-|   % Minus, absolute value (element-wise)
     % STACK: [5; 3; 2]
s    % Sum. Implicit display
     % STACK: 10

```

# Answer
> 3 votes
# Japt `-mx`, ~~16~~ ~~11~~ 10 bytes

Inspired by xnor's solution.

```
VaWbU+WøUÄ

```

Try it

```
VaWbU+WøUÄ     :Implicit map of each U at 0-based index V in input array W
Va             :Absolute difference of V and
  Wb           :  Index in W of
    U+Wø       :    U + Does W contain
        UÄ     :      U+1
               :Implicit output of sum of resulting array

```

# Answer
> 2 votes
# Python 3, 91 bytes

```
def f(l):c=sorted(l);return sum(abs(l.index(x)-l.index(y))for x,y in zip(c,c[1:])if y-x==1)

```

Try it online!

# Answer
> 2 votes
# Japt `-x`, ~~20 17~~ 12 bytes

```
ã_ÎaZo)¥1©ZÊ

```

Try it

* saved 5 thanks to @Shaggy!

```
    ã_  - subsections passed trough
    ÎaZo) * abs difference of 1st
            and last element(then removed)
    ¥1    * == 1?
    ©ZÊ   * take lenght/else 0
    -x flag to sum

```

# Answer
> 2 votes
# Wolfram Language (Mathematica), 42 bytes

```
Tr@Abs[s@@@Outer[s=#-#2&,#,#]~Position~1]&

```

Try it online!

Essentially a port of Jonah's J answer.

# Answer
> 2 votes
# JavaScript (V8), 54 bytes

```
$=([o,...a])=>o?a.indexOf(o+1)+a.indexOf(o-1)+2+$(a):0

```

Try it online!

# Answer
> 1 votes
# Thunno, \\$ 24 \log\_{256}(96) \approx \\$ 19.75 bytes

```
2zPgAu-1=keez0AhEeAuADES

```

Attempt This Online!

#### Explanation

```
2zP       # All pairs in the input
   g      # Filtered by:
    Au-   #  Does the difference
       1= #  Equal 1?
k         # End filter
 e        # Map over the list:
  e       #  Map over the pair
   z0Ah   #   Get the index in the input
       E  # End both maps
e         # Map over this list:
 AuAD     #  Get the absolute difference
     E    # End map
      S   # Sum this list
          # Implicit output

```

# Answer
> 1 votes
# Scala 3, 122 bytes

Golfed version. Attempt This Online!

```
l=>l.flatMap(x=>l.indexOf(x+(if(l.contains(x+1))1 else 0))match{case -1=>None;case i=>Some(Math.abs(l.indexOf(x)-i))}).sum

```

Ungolfed version. Attempt This Online!

```
def calculate(list: List[Int]): Int = {
  list
    .flatMap(x =>
      list.indexOf(x + (if (list.contains(x + 1)) 1 else 0)) match {
        case -1 => None
        case i  => Some(Math.abs(list.indexOf(x) - i))
      }
    )
    .sum
}

```

# Answer
> 0 votes
# Uiua, 12 bytes

```
/+⌵/-⍉⊚=1⊞-.

```

Try it!

```
/+⌵/-⍉⊚=1⊞-.
         ⊞-.  # difference table
      ⊚=1     # coordinates of ones
     ⍉        # transpose
  ⌵/-         # absolute difference of columns
/+            # sum

```

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


# Question
Title: Column-wise summation of overlapping slices
## Task

Given a list of integers **L** and another integer **s**, the goal is to compute the column-wise sums of all **s**-length (potentially overlapping) slices of **L**, while pertaining their positions relative to **L** (see below).

## Definitions

The **s**-length *(overlapping) slices* of the list **L** are all the contiguous subsequences (without wrapping) of **L** that are of length **s**.

In order to *pertain the positions* of the slices **s** relative to **L**, you can imagine building a "ladder", where each slice **si** has an offset of **i** positions from the beginning.

---

## Specs

* **s** is an integer higher than **1** and strictly smaller than the length of **L**.
* **L** will always contain at least 3 elements.
* 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.

## Examples and Test Cases

Here is a worked example:

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

[1, 2, 3]
   [2, 3, 4]
      [3, 4, 5]
         [4, 5, 6]
            [5, 6, 7]
               [6, 7, 8]
                  [7, 8, 9]
-------------------------------- (+)  | column-wise summation
[1, 4, 9, 12, 15, 18, 21, 16, 9]

```

And some more test cases:

```
[1, 3, 12, 100, 23], 4         -> [1, 6, 24, 200, 23]
[3, -6, -9, 19, 2, 0], 2       -> [3, -12, -18, 38, 4, 0]
[5, 6, 7, 8, 2, -4, 7], 3      -> [5, 12, 21, 24, 6, -8, 7]
[1, 2, 3, 4, 5, 6, 7, 8, 9], 3 -> [1, 4, 9, 12, 15, 18, 21, 16, 9]
[1, 1, 1, 1, 1, 1, 1], 6       -> [1, 2, 2, 2, 2, 2, 1]
[1, 2, 3, 4, 5, 6, 7, 8, 9], 6 -> [1, 4, 9, 16, 20, 24, 21, 16, 9]

```

# Answer
> 12 votes
# , 11, 9 8 bytes

-1 byte thanks to miles!

```
[:+//.]\

```

## How it works?

The left argument is s, the right one - L

`]\` \- splits L into sublists with length s

`/.` \- extracts the oblique diagonals (anti-diagonals)

`+/` \- adds them up

`[:` \- makes a fork from the above verbs

Here's an example J session for the first test case:

```
   a =. 1 2 3 4 5 6 7 8 9

   ] 3 ]\ a
1 2 3
2 3 4
3 4 5
4 5 6
5 6 7
6 7 8
7 8 9

   ] </. 3 ]\ a
┌─┬───┬─────┬─────┬─────┬─────┬─────┬───┬─┐
│1│2 2│3 3 3│4 4 4│5 5 5│6 6 6│7 7 7│8 8│9│
└─┴───┴─────┴─────┴─────┴─────┴─────┴───┴─┘

   ] +//. 3 ]\ a
1 4 9 12 15 18 21 16 9

```

Try it online!

# Answer
> 9 votes
# Haskell, ~~59~~ 56 bytes

```
s#n=[x*minimum[n,i,length s+1-max i n]|(i,x)<-zip[1..]s]

```

Try it online!

Defines a function `(#)` which takes a list `s` and and a number `n` as arguments.

This is based on the observation that for `s = [1, 2, 3, 4, 5, 6, 7, 8, 9]` and `n = 3`

```
[1, 2, 3]
   [2, 3, 4]
      [3, 4, 5]
         [4, 5, 6]
            [5, 6, 7]
               [6, 7, 8]
                  [7, 8, 9]
---------------------------- (+)
[1, 4, 9,12,15,18,21,16, 9]

```

is the same as

```
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 3, 3, 3, 3, 2, 1]
---------------------------- (*)
[1, 4, 9,12,15,18,21,16, 9]

```

To generate this initially increasing, then constant and finally decreasing list, we can start with

```
[minimum[i, length s + 1 - i] | i<-[1..length s]]

```

which yields `[1, 2, 3, 4, 5, 4, 3, 2, 1]`. Adding `n` as additional constraint into the `minimum` expression yields the correct list `[1, 2, 3, 3, 3, 3, 3, 2, 1]`answer for `n = 3`, though for `n = 6` (or in general any `n > lengths s/2`) the additional constraint `length s + 1 - n` is needed:

```
[minimum[i, n, length s + 1 - i, length s + 1 - n] | i<-[1..length s]]

```

or shorter:

```
[minimum[i, n, length s + 1 - max i n] | i<-[1..length s]]

```

For the pairwise multiplication `[1..length s]` is zipped with `s`, and because `zip` truncates the longer list to the length of the shorter one the infinite list `[1..]` can be used:

```
[x * minimum[i, n, length s + 1 - max i n] | (i,x)<-zip[1..]s]

```

# Answer
> 6 votes
# JavaScript (ES6), ~~65~~ ~~62~~ 58 bytes

*Saved 4 bytes thanks to @Shaggy*

Takes input in currying syntax `(a)(n)`.

```
a=>n=>a.map((v,i)=>v*Math.min(++i,n,a.length+1-(n>i?n:i)))

```

### Test cases

```
let f =

a=>n=>a.map((v,i)=>v*Math.min(++i,n,a.length+1-(n>i?n:i)))

console.log(JSON.stringify(f([1, 3, 12, 100, 23]        )(4))) // [1, 6, 24, 200, 23]
console.log(JSON.stringify(f([3, -6, -9, 19, 2, 0]      )(2))) // [3, -12, -18, 38, 4, 0]
console.log(JSON.stringify(f([5, 6, 7, 8, 2, -4, 7]     )(3))) // [5, 12, 21, 24, 6, -8, 7]
console.log(JSON.stringify(f([1, 2, 3, 4, 5, 6, 7, 8, 9])(3))) // [1, 4, 9, 12, 15, 18, 21, 16, 9]
console.log(JSON.stringify(f([1, 1, 1, 1, 1, 1, 1]      )(6))) // [1, 2, 2, 2, 2, 2, 1]
console.log(JSON.stringify(f([1, 2, 3, 4, 5, 6, 7, 8, 9])(6))) // [1, 4, 9, 16, 20, 24, 21, 16, 9]
```

# Answer
> 6 votes
# Java 8, 83 bytes

```
L->s->{for(int i=0,l=L.length+1,t,u;++i<l;u=l-(s>i?s:i),L[i-1]*=t<u?t:u)t=i<s?i:s;}

```

That first test case (and the last two I've added) screwed me over multiple times, but it finally works now.. :D

Modifies the input array instead of returning a new one.

**Explanation:**

Try it online.

```
L->s->{                  // Method with int-array and int parameters, and no return-type
  for(int i=0,           //  Index-integer, starting at 0
      l=L.length+1,      //  The length of the input-array + 1
      t,u;               //  Two temp integers
      ++i<l              //  Loop `i` from 1 to the length (inclusive)
      ;                  //    After every iteration:
       u=l               //     Set temp integer `u` to the length plus 1,
          -(s>i?s:i),    //     minus the highest of `s` and `i`
       L[i-1]*=t<u?t:u)  //     And replace the item with the lowest of `t` and `u`
    t=i<s?i:s;}          //   Set temp integer `t` to the lowest of `i` or `s`

```

# Answer
> 6 votes
# APL (Dyalog Unicode), ~~19~~ 14 bytesSBCS

-5 thanks to ngn.

Anonymous tacit infix function taking **s** as left argument and **L** as right argument. Assumes `⎕IO` (**I**ndex **O**rigin) to be `0` as is default on many systems.

```
+⌿∘↑((0,⊢)\,/)

```

Try it online!

**Explanation with example case `[1,3,12,100,23]`**

`(``)` apply the following anonymous tacit function:

`,/` overlapping windows of that size; `[[1,3,12],[3,12,100],[12,100,23]]`

`(``)\` cumulatively apply this tacit the following anonymous tacit function:

the right(most) argument

`0,` with a zero on the left

Cumulative reduction means that we insert the function into every "space" between successive terms, working our way from right to left. For each "space", the function will discard the left argument but append an additional zero. Effectively, this appends as many zeros to each term as there are "spaces" to its left, so the first term gets zero spaces, the second gets one, and the third gets two: `[[1,3,12],[0,3,12,100],[0,0,12,100,23]]`

up the rank by combining the lists into a single matrix, padding with zeros;
`┌ ┐`
`│1 3 12 0 0│`
`│0 3 12 100 0│`
`│0 0 12 100 23│`
`└ ┘`
then
`+⌿` sum vertically; `[1,6,36,200,23]`

# Answer
> 5 votes
# 05AB1E, 12 bytes

```
)IŒIùvyNÅ0ì+

```

Try it online!

# Answer
> 5 votes
# MATL, 8 bytes

```
YCPT&Xds

```

Try it online! Or verify all test cases.

### Explanation

Consider inputs `[1, 3, 12, 100, 23]` and `4`.

```
YC     % Implicit inputs: row vector L and number s. Create matrix of
       % overlapping blocks of L with length s, where each block is a column
       % STACK: [  1   3;
                   3  12;
                  12 100;
                 100  23]
P      % Flip vertically
       % STACK: [100  23;
                  12 100;
                   3  12;
                   1   3]
&TXd   % Extract all diagonals, starting from bottom-left, and arrange them as
       % columns of a matrix, with zero padding
       % STACK: [1   3  12 100   0;
                 0   3  12 100  23]
s      % Sum of each column. Since s is less than the length of L, there are
       % at least two rows. Thus function `s` can be used instead of `Xs`.
       % Implicit display
       % STACK: [1   6  24 200  23]

```

# Answer
> 4 votes
# Jelly, 6 bytes

```
JṡṬS×ḷ

```

Try it online!

### How it works

```
JṡṬS×ḷ  Main link. Left argument: A (array). Right argument: n (integer)

J       Indices; yield [1, ..., len(A)].
 ṡ      Split the indices into overlapping slices of length n.
  Ṭ     Untruth; map each array of indices to a Boolean vector, with 1's at the
        specified indices and 0's elsewhere.
        For example, [3, 4, 5] maps to [0, 0, 1, 1, 1].
   S    Sum the rows, essentially counting how many times each index appears in
        the arrays returned by the ṡ atom.
     ḷ  Left; yield A.
    ×   Multiply the counts to the left with the integers to the right.

```

# Answer
> 3 votes
# Japt, 13 bytes

It took far too long to get this working when `s` \> `L/2`!

```
Ë*°EmVUÊÄ-EwV

```

Try it

---

## Explanation

```
                 :Implicit input of array U and integer V
Ë                :Map over each element at 0-based index E in U
 *               :  Multiply by
    m            :  The minumum of
  °E             :    E incremented,
     V           :    V,
          EwV    :    and the maximum of E & V
         -       :    subtracted from
      UÊÄ        :    the length of U plus 1

```

# Answer
> 3 votes
# Husk, 4 bytes

```
mΣ∂X

```

Try it online!

Uses the idea from Galen Ivanov's J answer.

### Explanation

```
     -- implicit input number n and list s, e.g. s = [1,2,3,4,5,6] and n = 4
   X -- get sublists of length n of list s           [[1,2,3,4],[2,3,4,5],[3,4,5,6]]
  ∂  -- anti-diagonals                               [[1],[2,2],[3,3,3],[4,4,4],[5,5],[6]]
mΣ   -- get the sum of each of the lists             [1,4,9,12,10,6]

```

# Answer
> 2 votes
# Wolfram Language (Mathematica), 42 bytes

```
Min[i,#2,l+1-{i,#2}]~Table~{i,l=Tr[1^#]}#&

```

Try it online!

# Answer
> 2 votes
# Julia, 41 bytes

```
a\n=(a[L=end];a.*min(1:L,L:-1:1,n,L-n+1))

```

Try it online!

* Redefine `\` operator.
* `a[L=end]` is a shorter alternative to `L=length(a)`.
* Uses Laikoni's method.

# Answer
> 2 votes
# Japt, ~~13~~ 12 bytes

*-1 byte thanks to @ETHproductions*

```
ãV
ËEÆÃcDÃyx

```

Try it online!

# Answer
> 1 votes
# , ~~52~~ 51 bytes

```
function(l,s)l*pmin(s,x<-seq(l),y<-rev(x),y[1]+1-s)

```

Try it online!

This is equivalent to Laikoni's answer.

`seq(l)` produces the indices `1...length(l)` since `length(l)>1` (otherwise it would produce `1...l[1]`). I save it as `x`, save its reverse as `y`, and take the first element of `y` (`length(l)`) to neatly port Laikoni's answer and save a byte!

### Original answer, 52 bytes

```
function(l,s,L=sum(l|1)+1)l*pmin(s,x<-2:L-1,L-x,L-s)

```

Try it online!

The output is `l` elementwise multiplied by the minimum of `s`, the 1-based index of the element `x`, `length(l)-x+1`, and `length(L)-s+1`.

This is also equivalent to Laikoni's answer, using `L-x` instead of `rev(x)` as it's shorter.

# Answer
> 1 votes
# APL+WIN, 25 bytes

Prompts for screen input of L followed by s

```
+/(1-⍳⍴z)⌽¨(⍴L)↑¨s←⎕,/L←⎕

```

Explanation:

```
L←⎕ prompt for screen input of L

s←⎕,/ prompt for screen input of s and create nested vector of successive s elements of L

(⍴L)↑¨ pad each element of the nested vector with zeros to the length of L

(1-⍳⍴z)⌽¨ incrementally rotate each element of the nested vector

+/ sum the elements of the nested vector

```

# Answer
> 1 votes
# K (oK), 30 bytes

**Solution:**

```
{+/t,'(y':x),'|t:(!1-y-#x)#'0}

```

Try it online!

**Example:**

```
{+/t,'(y':x),'|t:(!1-y-#x)#'0}[3 -6 -9 19 2 0;2]
3 -12 -18 38 4 0

```

**Explanation:**

Don't think I can compete with **J** on this one. Generate a list of zeros to be appended and prepended to the sliding-window list, then sum up:

```
{ t,'(y':x),'|t:(!(#x)+1-y)#'0 }[1 2 3 4 5 6 7 8 9;3]
(1 2 3 0 0 0 0 0 0
 0 2 3 4 0 0 0 0 0
 0 0 3 4 5 0 0 0 0
 0 0 0 4 5 6 0 0 0
 0 0 0 0 5 6 7 0 0
 0 0 0 0 0 6 7 8 0
 0 0 0 0 0 0 7 8 9)

```

Breakdown is as follows... though this still feels clumsy.

```
{+/t,'(y':x),'|t:(!1-y-#x)#'0} / the solution
{                            } / lambda taking x and y implicitly
                          #'0  / take (#) each (') zero
                 (       )     / do this together
                       #x      / count (#) length of x
                     y-        / take count away from length y
                   1-          / take that result from 1
                  !            / til, generate range to that number
               t:              / save in variable t
              |                / reverse it
            ,'                 / join with each
      (y':x)                   / sliding window size y over x
    ,'                         / join with each
   t                           / prepend t
 +/                            / sum up

```

# Answer
> 1 votes
# Ruby, 62 bytes

```
->a,l{a.map.with_index{|x,i|x*[i+1,l,a.size-[l-1,i].max].min}}

```

Try it online!

Essentially a port of Arnauld's javascript answer, except that needing `with_index` is a lot more painful.

In the time it took for me to decide to actually submit this, I golfed down from this 70-byte version, which is closer to Dennis's algorithm.

```
->a,l{c=a.map{0};(0...a.size).each_cons(l){|h|h.map{|i|c[i]+=a[i]}};c}

```

# Answer
> 1 votes
# Uiua, 14 bytes

```
⬚0/+⊐≡(⊂⊚)⇡⧻.◫

```

Try it!

```
⬚0/+⊐≡(⊂⊚)⇡⧻.◫
             ◫  # windows
          ⇡⧻.   # range of length
    ⊐≡(  )      # apply function to each row of both arrays, boxing as required
        ⊚       # where (n zeros)
       ⊂        # join
⬚0/+            # sum columns, filling missing elements with zero

```

# Answer
> 0 votes
# Perl, ~~45~~ 44 bytes

Includes +4 for `-ai` Also notice that this code gives 2 perl warnings on startup. You can suppress these at the cost of one stroke by adding the `X` option

Give the mask length after the `-i` option and the array on one line on STDIN:

```
perl -ai4 -E 'say$_*grep$_~~[$^I..@F],$a..$^I+$a++for@F' <<< "1 3 12 100 23"

```

Just the code:

```
say$_*grep$_~~[$^I..@F],$a..$^I+$a++for@F

```

# Answer
> 0 votes
# C (gcc), ~~100~~ 89 bytes, using `-lm`

```
j;f(L,l,s)int*L;{for(j=l;j--;L[j]*=j<s&j<l-s?1+j:j>s&j>l-s?l-j:fmin(s<l-j?s:l-j,l+1-s));}

```

Try it online!

# Answer
> 0 votes
# Python 2, ~~68~~ 66 bytes

-2 bytes thanks to Laikoni

```
lambda l,n:[v*min(n,i+1,len(l)-max(i,n-1))for i,v in enumerate(l)]

```

Try it online!

# Answer
> 0 votes
# C (gcc), ~~83~~ ~~81~~ 79 bytes

There are basically three "phases" to the manipulation of the list: ramp-up, sustain, and cool-off. As we go along the list, we will increase our factor until we reached some maximum. If a full run of slices can fit into the list, this maximum will be the same as the length of the slices. Otherwise, it will be the same as the number of slices that fit. At the other end, we will decrease the factor again, to land at 1 on the last element.

The length of the ramp-up and cool-down phases that bookend this plateau is one less than that maximum factor.

The ungolfed loops before combining them hopefully makes it clearer (R = length of ramp-up phase):

```
for (r = 1; r <= R; r++) L[r - 1] *= r;
for (; r < n - R; r++)   L[r - 1] *= R + 1;
for (; r < n; r++)       L[r - 1] *= n - r + 1;

```

Three loops is much too much, so deciding the factor based on r gives us the one loop (using s for R to save some bytes):

```
r;f(L,n,s)int*L;{for(r=0,s=2*s-1>n?n-s:s-1;r++<n;)*L++*=r>s?r<n-s?s+1:n-r+1:r;}

```

Try it online!

# Answer
> 0 votes
# Perl 5, 63 bytes

```
$b=<>;map{say$_*=$n+$b>@F?$n-$b<0?$i:--$i:$i<$b?++$i:$i;++$n}@F

```

Try it online!

# Answer
> 0 votes
## Clojure, 72 bytes

```
#(let[R(range 1(inc(count %)))](map *(map min(repeat %2)R(reverse R))%))

```

# Answer
> 0 votes
# Pyt, 106 bytes

```
ĐŁĐ←⇹řĐ↔Đ04ȘĐ04Ș>Đ04Ș03Ș¬*07ȘážÁ*+04Ș⇹Đ3ȘĐ3Ș-⁺Đ4Ș⇹ŕĐ3Ș<Đ¬3Ș*3Ș*+⇹ĐŁ⑴04Ș3Ș⇹04Ș*Đ04ȘĐ04Ș<Đ04Ș*06ȘážÁ03Ș¬*++*

```

Takes L on the first line as an array, and takes s on the second line

Explanation:

```
                     Implicit input (L)
Đ                    Duplicate L
ŁĐ                   Get length of L (len) and push it twice
←                    Get s
⇹ř                   Push [1,2,...,len]
Đ↔Đ                  Push [len,...,2,1] twice
04ȘĐ                 Push 0, flip top 4 on stack, and duplicate top [1,2,...,len]
04Ș>                 Is [len,...,2,1]>[1,2,...,len] (element-wise) [boolean array]
Đ                    Duplicate top of stack
04Ș03Ș¬*             Pushes [1,2,...,ceil(len/2),0,...,0]
07ȘážÁ               Push 0, flip top seven on stack, and remove all 0s from stack
*                    Pushes [0,0,...,0,floor(len/2),floor(len/2)-1,...,1]
+                    Adds top two on stack element-wise

The top of the stack is now:
     [1,2,...,ceil(len/2),floor(len/2),...,2,1] (let's call it z)

04Ș                  Push zero and swap top four on stack
⇹                    Swap top two on stack
Đ3ȘĐ3Ș-⁺Đ4Ș⇹ŕĐ3Ș<Đ¬3Ș*3Ș*+     Pushes min of (len-s+1,s) [let's call it m]
⇹ĐŁ⑴04Ș3Ș⇹04Ș*                Pushes an array [m,m,...,m] with length len
Đ04ȘĐ04Ș<Đ04Ș*06ȘážÁ03Ș¬*++    Pushes element-wise min of [m,m,...,m] and z
*                              Element-wise multiplication of above with L

```

Try it online!

# Answer
> 0 votes
# Python + numpy, 64 bytes

```
from pylab import *
lambda l,N:convolve(*ones((2,len(l)-N-1)))*l

```

Call this with l as the list, and N as the length.

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


title: Make a k-skip-j range

text:
# Question
Title: Make a k-skip-j range
On the Mathematica Stack Exchange, 100xln2 asks:

> I need a list of integers \[…\] The list contains integers and is characterized by \[three\] parameters, lets call them k and j \[and listmax\], which should be variable.
>
> If `k=1` and `j=1` then the list would look like this: {1,3,5,7,9,11,....until listmax}
>
> If `k=2` and `j=3` then the list would look like this: {1,2,6,7,11,12,16,17,.....until listmax}
>
> Generally speaking, the List contains the first k integers, then doesn't contain the next j integers, then contains the next k integers, then doesn't contain the next j integers and so on and so on.

Let's help them out! (I hope they're okay with Jelly, Vyxal, or Befunge code instead of Mathematica…)

Given three positive integers \\$(k, j, \text{listmax})\\$, make a list of integers as described above, sorted in increasing order.

For \\$(3,2,6)\\$ you should return `[1,2,3,6]` rather than `[1,2,3]` or `[1,2,3,6,7,8]`. You can imagine you're generating an infinite “include 3, skip 2” list, and taking elements from it as long as they're ≤ 6.

# Rules

This is . Write the shortest possible answer, measured in bytes.

Standard I/O methods apply, which means valid submissions include:

* a three-parameter function that returns a list of numbers,
* a three-parameter function that prints each number in the list,
* a full program that reads inputs and prints each number in the list,
* and so on.

# Tests

In the format `k j listmax --> output`:

```
1 1 11 --> [1, 3, 5, 7, 9, 11]
2 13 19 --> [1, 2, 16, 17]
2 13 16 --> [1, 2, 16]
1 4 49 --> [1, 6, 11, 16, 21, 26, 31, 36, 41, 46]
2 4 22 --> [1, 2, 7, 8, 13, 14, 19, 20]
2 10 13 --> [1, 2, 13]
5 15 10 --> [1, 2, 3, 4, 5]
1 13 27 --> [1, 15]
7 4 31 --> [1, 2, 3, 4, 5, 6, 7, 12, 13, 14, 15, 16, 17, 18, 23, 24, 25, 26, 27, 28, 29]
99 99 1 --> [1]

```

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

```
lambda k,j,l:[x+1for x in range(l)if x%(k+j)<k]

```

Attempt This Online!

-5 by Lynn

-1 by Ethan C
> 11 votes

# Answer
# Jelly, ~~6~~ 5 bytes

```
Ø+xṁM

```

Try it online!

Takes input as `[k, j]` on the left, and `listmax` on the right.

-1 byte thanks to Lynn pushing me to save a byte!

## How it works

```
Ø+xṁM - Main link. Takes [k, j] on the left, listmax on the right
Ø+    - [1, -1]
  x   - Repeat 1 k times and -1 j times
   ṁ  - Mold this list of length k+j to length listmax
    M - Maximal indices, i.e. indices of the 1s

```
> 9 votes

# Answer
# , ~~12~~ 11 bytes

```
>:@I.@$1-I.

```

Attempt This Online!

Takes input as `listmax f (k, j)`.

-1 byte thanks to ngn by taking `k,j` instead of `j,k`.

```
>:@I.@$1-I.
         I.  k copies of 0 and j copies of 1
       1-    change 0 to 1 and 1 to 0
      $      take listmax cyclically
   I.@       convert each occurrence of 1 to its index (0-based)
>:@          add 1

```

# K (ngn/k), 10 bytes

```
{1+&x#~&y}

```

Try it online!

Takes input as `f[listmax;k,j]`. Pretty much a built-in-to-built-in translation of the J solution above.
> 8 votes

# Answer
# , ~~32~~ 31 bytes

```
\(k,j,m)which((1:m-1)%%(k+j)<k)

```

Attempt This Online!

Indexes of elements of `0..(listmax-1)` that are less than `k` after modulo-`(k+j)`.
> 7 votes

# Answer
# Dyalog APL, 6 bytes

Thanks @Lynn for -6

```
⍸1=⍴∘⍸
⍸       # At what indices
     ⍸  # is the list of k 1's and j 2's
   ⍴    # cycled to length listmax
 1=     # equal to 1?

```

Created with the help of Luminespire.

left argument listmax, right argument pair of k and j
> 6 votes

# Answer
# Octave / MATLAB, 30 bytes

```
@(k,j,m)find(mod(0:m-1,k+j)<k)

```

Try it online!

### Explanation

```
@(k,j,m)find(mod(0:m-1,k+j)<k)

@(k,j,m)                         % Define anonymous function of k, j, m
                 0:m-1           % Range [0 1 2 ... m-1]
             mod(     ,k+j)      % Modulo k+j (element-wise)
                           <k    % Less than k? (element-wise)
        find(                )   % (1-based) Indices of true entries

```
> 6 votes

# Answer
# C (gcc), 54 bytes

```
i;f(a,b,m){for(i=0;i<m;i++%(a+b)<a&&printf("%d ",i));}

```

Try it online!
> 6 votes

# Answer
# C (gcc), 62 bytes

```
i,j;f(a,b,m){for(i=j=0;m/++i;j-->b&&printf("%d ",i))j=j?:a+b;}

```

Try It Online!

Ungolfed:

```
i,j;
f(a,b,m)
{
    for(i=j=0;m/++i;j-->b&&printf("%d ",i))
        j=j?:a+b;
}

```

`i` is the counter, and the loop ends when it's greater than `m`, which is the maximum value. `j` is initialized to `0`, but is reinitialized to `a+b` before it is read from. It's decremented once for each iteration of the loop, and `i` is only printed when `j` is greater than `b`, so only the first `a+b` \- `b` = `a` values are printed. When `j` reaches 0 after `b` more iterations, it's set to `a+b` again.
> 5 votes

# Answer
# Zsh, 59 bytes

```
for ((;i<$1&&i++<$3;))l+=({$i..$3..$[$1+$2]})
echo ${(on)l}

```

Attempt This Online!

I really think there's some gains to be had from another method, but that method eludes me.

This loops, iterating the starting point of a brace expansion `{$start..$end..$skip}` until it reaches the first or third argument (j or listmax). Each brace expansion is appended to the list `l`. Finally, the `(on)` flag sorts the list numerically.

**-8 bytes** if the output does not need to be sorted. (`<<<$l`)
> 5 votes

# Answer
# Husk, 7 bytes

```
ṁ↑³Cḣ⁰+

```

Try it online!

Same approach as my Nibbles answer. Takes arguments in order `k`,`listmax`,`j`.

```
ṁ↑³Cḣ⁰+
   C     # cut
    ḣ⁰   #  the range from 1..middle argument
         # into sublists of length
      +  #  sum of other arguments
ṁ        # then map over this list-of-lists
 ↑       #  taking
  ³      #  first-arg elements from each
ṁ        # and flatten the result

```

---

**Alternative approach, also 7 bytes**

```
f¢Ṙ⁰ḋ2ḣ

```

Try it online!

Takes arguments in order `[k,j]`,`listmax`.

```
f¢Ṙ⁰ḋ2ḣ
  Ṙ      # repeat
    ḋ2   #  the binary digits of 2 (so: [1,0])
   ⁰     #  each by number given in arg 1
 ¢       # and repeat this list infinitely;
f        # now use this to filter elements of
      ḣ  #  1..arg 2

```
> 4 votes

# Answer
# Nibbles, 5.5 bytes

```
|,_-@%-$~+@

```

Attempt This Online!

Find all numbers \\$n\\$ from \\$1\\$ to \\$m\\$ such that \\$(n-1) \bmod (k+j) \< k\\$.

```
|,_-@%-$~+@
|           filter
 ,           range
  _           max number
            by the following value being strictly positive:
   -         subtract
    @         k (number of elements to keep)
     %        modulo
      - ~      subtract 1 from
       $        the element
         +     add
          @     k (number of elements to keep)
                j (number of elements to drop)

```
> 3 votes

# Answer
# Excel, 68 bytes

```
=LET(a,TOROW(SEQUENCE(,A1)+(A1+B1)*SEQUENCE(C1,,0)),FILTER(a,a<=C1))

```

`k`, `j` and `listmax` in `A1`, `B1` and `C1` respectively. Outputs a horizontal array.
> 3 votes

# Answer
# Nibbles, 5.5 bytes (11 nibbles)

```
+.`/+@$,_<@

```

Attempt This Online!

Different approach to xigoi's Nibbles answer, but still 5.5 bytes...

```
+.`/+@$,_<@
  `/         # make chunks of size
    +@$      #  sum of first two arguments
       ,_    # from the range 1..third argument
 .           # then, for each chunk
         <@  #  take first arg elements
+            # and flatten the list of chunks

```
> 3 votes

# Answer
# Ruby, ~~41~~ 37 bytes

-4 bytes thanks to Dingus

```
->k,j,m{m.times{p _1+1if _1%(k+j)<k}}

```

Attempt This Online!
> 3 votes

# Answer
# JavaScript (ES6), 46 bytes

Expects `(k)(j)(listmax)`.

```
k=>j=>g=m=>m--?m%(k+j)<k?[...g(m),m+1]:g(m):[]

```

Try it online!

### Commented

```
k =>                 // 1st function taking k
j =>                 // 2nd function taking j
g = m =>             // 3rd recursive function taking m
m-- ?                // if m is not 0 (decrement it afterwards):
  m % (k + j) < k ?  //   if m modulo (k + j) is less than k:
    [...g(m), m + 1] //     append the result of a recursive call,
                     //     followed by m + 1
  :                  //   else:
    g(m)             //     just do a recursive call and append nothing
:                    // else:
  []                 //   stop

```
> 3 votes

# Answer
# Vyxal, 6 bytes

```
øḊ⁰ẎT›

```

Try it Online!

(or 5.5 bytes if you're using vyncode)

```
øḊ     # Perform dyadic run length decoding - creates a list of
       # [[list_max] * k, [0] * j]
  ⁰Ẏ   # Slice to length list_max
    T› # Truthy indices + 1

```
> 3 votes

# Answer
# Minecraft Function, 307 bytes

```
scoreboard players operation r d = c d
execute if score c d matches 0 run scoreboard players operation j d += k d
scoreboard players operation r d %= j d
scoreboard players add c d 1
execute if score r d < k d run tellraw @a {"score":{"name":"c","objective":"d"}}
execute if score c d < m d run function a:b

```

Must be run as a function named `b` in a data pack named `a`. The function increments `c` in a loop while `c < m`. Each iteration, if `c % (k + j) < k`, it prints `c`.

`k`, `j`, and `listmax` are input as scoreboard players `k`, `j`, and `m` for objective `d`. To set up the inputs, run the commands:

```
/scoreboard objectives add d dummy
/scoreboard players set k d <value>
/scoreboard players set j d <value>
/scoreboard players set m d <value>

```

The above commands could be considered part of the program, but since they are necessary to provide input they have not been counted.
> 3 votes

# Answer
# Swift, 40 bytes

```
{k,j,l in(1...l).filter{($0-1)%(k+j)<k}}

```

Try it on SwiftFiddle!
> 2 votes

# Answer
# \>\<\> (Fish), 48 bytes

```

```

Hover over any symbol to see what it does

Try it

Unformatted version of code if above looks broken:

```
i:i+i0v/
v   1+>$:@$:@(?;:r:}$:}$r$@%)?
\1+:nao\

```
> 2 votes

# Answer
# Charcoal, ~~15~~ 12 bytes

```
Ｉ⊕⌕Ａ…⭆²⭆ＮιＮ0

```

Try it online! Link is to verbose version of code. Would have been 1 fewer byte with 0-indexing. Explanation: Now a port of @lyxal's Vyxal answer.

```
      ²         Literal integer `2`
     ⭆          Map over implicit range and join
        Ｎ       Next input
       ⭆        Map over implicit range and join
         ι      Outer value
    …           Cyclically extended to length
          Ｎ     Third input as a number
  ⌕Ａ            Find all occurrences of
           0    Literal string `0`
 ⊕              Vectorised increment
Ｉ               Cast to string
                Implicitly print

```
> 2 votes

# Answer
# 05AB1E, 8 bytes

```
LI¹и£ιн˜

```

Inputs as \\$max, \[k,j\]\\$.

Try it online or verify all test cases.

Here an alternative 8 bytes approach:

```
LDIÅΓ¹∍Ï

```

Try it online or verify all test cases.

**Explanation:**

```
L         # Push a list in the range [1, first (implicit) input `max`]
 I        # Push the second input-pair [`k`,`j`]
  ¹и      # Repeat it the first input amount of times as list
    £     # Split the first list into parts of those sizes,
          # containing empty trailing lists if it's out of bounds
     ι    # Uninterleave this list of lists into two parts
      н   # Pop and only keep the first part
       ˜  # Flatten it
          # (after which the result is output implicitly)

```

```
L         # Push a list in the range [1, first (implicit) input `max`]
 D        # Duplicate this list
  I       # Push the second input-pair [`k`,`j`]
   ÅΓ     # Pop the top two lists, and run-length decode it,
          # resulting in `k` amount of 1s followed by `j` amount of 2s
     ¹∍   # Shorten/extend it to a length equal to the first input `max`
       Ï  # Only leave the values in the ranged list at the truthy positions
          # (only 1 is truthy in 05AB1E)
          # (after which the result is output implicitly)

```
> 2 votes

# Answer
# \>\<\> (Fish), 43 bytes

```

```

Hover over any symbol to see what it does

In plaintext:

```
ii:i+0v1
)r}:r:<\v?)%{@:&@:$}:&;?
1+:nao^+>

```

Try it
> 2 votes

# Answer
# Arturo, 31 bytes

```
$[k j l]->select l=>[k>%&-1k+j]

```

Try it!

```
$[k j l]->          ; a function taking three args
    select l=>[     ; select elts in [1..l], assign current elt to &
        k>          ; is k greater than...
        %&-1        ; current elt minus one modulo...
        k+j         ; k plus j?
    ]               ; end select

```
> 2 votes

# Answer
# Desmos, 36 bytes

```
l=[1...m]
f(k,j,m)=l[mod(l-1,k+j)<k]

```

Uses the same modulo trick that some other answers here have done to filter for the appropriate numbers.

Try It On Desmos!

Try It On Desmos! - Prettified
> 2 votes

# Answer
# Java (JDK), 71 bytes

Output is an IntStream if that's acceptable.

```
(k,j,l)->java.util.stream.IntStream.range(1,l+1).filter(i->--i%(k+j)<k)

```

Try it online!

---

If that's not acceptable, then here's a more classic solution with an array as output (**81 bytes**) :

```
(k,j,l)->{var r="";for(int i=0;i<l;)r+=i++%(k+j)<k?i+",":"";return r.split(",");}

```

Try it online!
> 2 votes

# Answer
# Scala, 48 bytes

```
(k,j,l)=>for(i<-0 until l if i%(k+j)<k)yield i+1

```

Try it online!

Same modulo trick.
> 2 votes

# Answer
# Bash+coreutils, 41 bytes

```
seq 1 $3|xargs -n$[$1+$2]|cut -d\  -f1-$1

```

Try it online!

~~59 bytes~~: `c=$3;for((i=1;i<=c;i+=$1+$2)){ seq $i $[k=i+$1-1,k<c?k:c];}`
> 2 votes

# Answer
# Vyxal, 46 bitsv2, 5.75 bytes

```
₀fẋfẎT›

```

Try it Online!

Vyncode!!!

## Explained

```
₀fẋfẎT›
₀fẋ      # A list of [[1] * k, [0] * j]
   f     # flattened
    Ẏ    # with the first listmax items taken, wrapping if needed
     T›  # truthy indices + 1

```

Created with the help of Luminespire.
> 1 votes

# Answer
# Go, 79 bytes

```
func(k,j,n int)(o[]int){for i:=0;i<n;i++{if i%(k+j)<k{o=append(o,i+1)}}
return}

```

Attempt This Online!

Port of @SanguineL's answer.
> 1 votes

# Answer
# Nim, 60 bytes

```
proc r(k,j,m:int)=
 for n in 1..m:
  if(n-1)%%(j+k)<k:echo n

```

Attempt This Online!
> 1 votes

# Answer
# Zsh `--extendedglob`, 52 bytes

```
for i ({1..$3})<<<${$(((i-1)%($1+$2)<$1?i:0))/(#s)0}

```

Try it online!

Using the modulo technique, but still not understanding how it works!
> 1 votes

# Answer
# Perl 5 (`-p`), 43 bytes

```
/ \d+/;$_=join$",grep{$i++%($`+$&)<$`}1..$'

```

Try it online!
> 0 votes

# Answer
# C++, 125 bytes

It's never going to be a code-golf winner, but with C++23 nearing standardisation, it's interesting to showcase what the new `std::views` classes offer us:

```
#include<ranges>
auto f(int a,int b,int n){using namespace std::views;return
iota(1,n+1)|chunk(a+b)|transform(take(a))|join;}

```

This simply divides the input range into chunks of size `a+b`, taking the first `a` elements from each chunk, and then reassembles the chunks back into a single range.

Self-test of the question's examples:

```
#include <algorithm>
#include <iterator>
#include <vector>
auto k_skip_j(int a,int b,int n)
{
#ifdef __cpp_lib_ranges_to_container
    return f(a,b,n) | std::ranges::to<std::vector>();
#else
    auto r = f(a,b,n);
    auto result = std::vector<int>();
    std::ranges::copy(r, std::back_inserter(result));
    return result;
#endif
}

#include <gtest/gtest.h>

TEST(k_skip_j, three_two_six) {
    auto result = k_skip_j(3, 2, 6);
    auto expected = std::vector{1,2,3,6};
    EXPECT_EQ(result, expected);
}

TEST(k_skip_j, one_one_twelve) {
    auto result = k_skip_j(1, 1, 12);
    auto expected = std::vector{1,3,5,7,9,11};
    EXPECT_EQ(result, expected);
}

TEST(k_skip_j, two_three_twenty) {
    auto result = k_skip_j(2, 3, 20);
    auto expected = std::vector{1,2,6,7,11,12,16,17};
    EXPECT_EQ(result, expected);
}

```

---

For comparison, the C++20 version weighs 140 bytes:

```
#include<ranges>
auto f(int a,int b,int n){return
std::views::iota(1,n+1)|std::views::filter([n=-1,a,b](auto)mutable{return(++n%=a+b)<a;});}

```
> 0 votes

# Answer
# Japt, 9 bytes

0-based output. Add 1 byte for 1-based output.

```
o kgVcÈÇY

```

Try it
> 0 votes

# Answer
# Rust, 88 bytes

```
|k:usize,j:usize,l:usize|->Vec<usize>{(0..l).filter(|x|x%(k+j)<k).map(|x|x+1).collect()}

```

Attempt This Online!
> 0 votes

# Answer
# Wolfram Language (Mathematica), 67 bytes

Try it online!

```
f[k_,j_,l_]:=Table[If[Mod[x,k+j]<k,x+1],{x,0,l-1}]~DeleteCases~Null

```
> 0 votes

---
Tags: code-golf, sequence
---


# Question
Title: Lead your team to win the wrestlers world championship!
You are the captain of a world-famous wrestling team. An Olympic-grade match is coming up, and you are determined not to let your team down. You also happen to be a competent programmer, so you are going to write a program to help your team win!

You have access to the strength ratings for each of your own team wrestlers, and each of the opponent wrestlers. A wrestler will win their match only when their strength rating is greater than their opponent's strength rating. You have to write a program that will calculate the optimum pairing for each of your own wrestlers against each of the opponent wrestlers, and then output the maximum number of matches that can be won as a result.

# Input

Your program will take as input three arguments:

1. The number of members per team, there will be an equal number of wrestlers on each team. (Optional)
2. The strength rating of each of your team wrestlers, which is a number between 1 and 10.
3. The strength rating of each of the opponent wrestlers, which is a number between 1 and 10.

# Output

Calculate the optimum pairing for each of your own wrestlers against each of the opponent wrestlers, and then output the maximum number of matches that can be won as a result.

# Test cases

Test case 1:

```
Input:
5
2  4 6 2 6
3 10 6 7 7

Output: 1

```

Test case 2:

Input:
10
1  9 5 5 1 6 2 8  3  6
6 10 2 8 2 3 5 6 10 10

Output: 6
```
</code></pre>

# Answer
> 4 votes
# Jelly, 5 bytes

```
Œ!>§Ṁ

```

Try it online!

The second test case times out on TIO, but I have verified it locally. Takes your lineup as the left argument and theirs as the right.

```
Œ!       Find every permutation of your lineups' strengths,
  >      compare each matchup for each permutation,
   §     sum your wins for each permutation,
    Ṁ    and return the maximum number of wins.

```

# Answer
> 11 votes
# Python 2, ~~59~~ 57 bytes

*-2 bytes thanks to @dingledooper!*

```
lambda a,b:sum(b.sort()<b<[x]>b.pop(0)for x in sorted(a))

```

Try it online!

A function that takes 2 lists as arguments, and returns the maximum number of matches that can be won.

### Approach

For each opponent (from weakest to strongest), match that opponent with the weakest available member of my team that can win.

For example, let's say the strength of 2 teams (sorted) are as follow:

```
No.       1  2  3  4  5
Me       [2, 2, 4, 5, 8]
Opponent [3, 6, 7, 7, 9]

```
* The 1st opponent has strength 3, so we need to match that with our 3rd team member.
* The 2nd opponent has strength 6, so we match that with our 5th.

We cannot win any more match. So in total we can win at most 2 matches.

### Ungolfed code

```
a,b=map(sorted,input())  # sorted strength of my team and opponent team
s = 0                    # number of matches that can be won
for x in a:              # loop through my team, in order of increasing strength
  if x > b[0]:             # if current member can beat the weakest opponent left
    s += 1                   # then match those two
    b.pop(0)                 # and remove the weakest opponent
                           # (otherwise, current member is useless)
print s

```

# Answer
> 6 votes
# C (gcc) -zexecstack, <sup>~~124~~ \\$\cdots\\$ ~~105~~</sup> 103 bytes

Saved a whopping ~~2~~ ~~17~~ ~~19~~ 21 bytes thanks to ceilingcat!!!

```
#define q(x)qsort(x,i=n,4,L"\x62b078bǃ");
i;j;f(a,b,n)int*a,*b;{q(a)q(b)for(j=0;i--;j+=*a++>b[j]);i=j;}

```

Try it online!

**How**

Sorts the two teams from weakest to strongest. Then goes through our side, starting from weakest, comparing it to the \\$j^{\text{th}}\\$ member of the opponent's team starting at \\$j=0\\$, their weakest wrestler. If we are ever stronger than the \\$j^{\text{th}}\\$ member we increment \\$j\\$. After we go through all our wrestlers, \\$j\\$ will be the maximum number we can beat.

# Answer
> 4 votes
# , <sup>25</sup> <sup>22</sup> 20 bytes

```
0(]+>)/@|.@,I.&(/:~)

```

Try it online!

*-3 bytes thanks to Bubbler*

*Thanks to Dominic van Essen for spotting a subtle bug (now fixed)*

---

This could be shorter using brute force, but I wanted to see how short I could make an efficient solution.

Our team = right arg, their team = left arg.

Using 2nd test case an example:

```
6 10 2 8 2 3 5 6 10 10 f 1 9 5 5 1 6 2 8 3 6

```
* `&(/:~)` Sort both arguments:

```
2 2 3 5 6 6 8 10 10 10
1 1 2 3 5 5 6  6  8  9

```
* `I.` Uses Interval Index to determine how many of their players each of our players beats:

```
0 0 0 2 3 3 4 4 6 7

```
* `0...|.@,` Prepend a 0 and reverse:

```
2 3 3 4 4 6 7

```
* `(]+>)/` Now reduce from the right as follows: Take the right arg `]` (the running sum, seeded at `0`), compare the two args using `>` (returns 1 if left arg is greater than running sum, 0 otherwise), and add the two.

This means the running sum will increment exactly when "the number of opponents the current wrestler can beat" is greater than "opponents already beaten by other teammates".

The final result will be the total number of players our team can beat.

# Answer
> 4 votes
# APL (Dyalog Extended), 16 bytes

```
(+/⊢≥⍋)0~⍨1⊥<\⍥∧

```

Try it online!

An almost direct port of Jonah's J answer. But unfortunately, I found that, despite having the same name "interval index", J's `I.` and APL's  don't have the identical behavior; J finds the indices *before* identical elements, but APL does *after* them.

* J: `echo 1 3 5 I. 0 1 2 3 4 5 6` gives `0 0 1 1 2 2 3`
* APL: `⎕←1 3 5 ⍸ 0 1 2 3 4 5 6` gives `0 1 1 2 2 3 3`

That makes  hard to use for this problem, so I had to fall back to outer product (which is used in the previous version of Jonah's answer).

### How it works

```
(+/⊢≥⍋)0~⍨1⊥<\⍥∧  ⍝ Left: opponent strengths, Right: ours
              ⍥∧  ⍝ Ascending sort both args
          1⊥<\    ⍝ Outer product by < and then sum;
                  ⍝ count the opponents who each of ours can win against
       0~⍨  ⍝ Remove zeros
(    ⍋)     ⍝ Grade up; this is identical to ⍳∘≢ here since the arg is sorted
   ⊢≥       ⍝ Check if each number is at least its index
 +/         ⍝ Sum; count ones

```

# Answer
> 4 votes
# 05AB1E, 5 bytes

Coincidental port of Unrelated String's Jelly answer.

```
œ€‹Oà

```

Try it online!

## Explanation

```
œ     All permutations to your team's combination
 €‹   Does your team win at this position?
   O  Sum the resulting lists to get all wins
    à Return the largest item of the list

```

# Answer
> 3 votes
# , ~~58~~ 54 bytes

```
function(a,b){for(i in sort(a))F=F+(i>sort(b)[F+1]);F}

```

Try it online!

Algorithm based on *Noodle9*'s solution; this could be made shorter than my own original recursive solution 76 bytes or than one based on the elegant algorithm of *Surculose Sputum* 73 bytes in R

# Answer
> 3 votes
# Io, 66 bytes

Algorithm based on Noodle9's solution.

```
method(x,y,F :=0;x sort map(i,F=F+if(i>y sort at(F+1),1,0))last+1)

```

Try it online!

## Explanation

```
method(x, y,      // Take 2 arguments.
    F := 0        // Initialize the counter to 0.
    x sort map(i, // For every item in sorted x:
        F = F + if( // Add the counter by:
            i>y sort at(F+1), // if the current item is larger than sorted y at the same position
            1,0)    // converted to an integer
    ) last + 1)     // Add the last item of the map by 1

```

# Answer
> 2 votes
# JavaScript (ES6), 61 bytes

A shorter version inspired by @SurculoseSputum's answer.

```
a=>b=>(g=a=>a.sort((a,b)=>a-b))(a).map(x=>k+=x>g(b)[k],k=0)|k

```

Try it online!

That would be 31 bytes if the arrays were already sorted in ascending order:

```
a=>b=>a.map(x=>k+=x>b[k],k=0)|k

```

---

# JavaScript (ES6),  ~~85~~  75 bytes

Takes input as two lists of integers `(team, opponents)`.

```
a=>b=>a.map(x=>(b[i=b.sort((a,b)=>b-a).findIndex(y=>x>y)]=a,~i&&++k),k=0)|k

```

Try it online!

# Answer
> 2 votes
# Charcoal, 41 bytes

```
≔Ｉ⪪η η≔Ｉ⪪ζ ζＷΦη›κ⌊ζ«§≔η⌕η⌊ι⁰§≔ζ⌕ζ⌊ζχ»Ｉ№η⁰

```

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

```
≔Ｉ⪪η η

```

Input the ratings of your wrestlers.

```
≔Ｉ⪪ζ ζ

```

Input the ratings of your opponents.

```
ＷΦη›κ⌊ζ«

```

Repeat while at least one of your wrestlers can beat one of your opponents.

```
§≔η⌕η⌊ι⁰

```

Set the strength of the weakest such wrestler to 0, so it will no longer be considered.

```
§≔ζ⌕ζ⌊ζχ

```

Similarly set the strength of its opponent to 10, so it will also no longer be considered.

```
»Ｉ№η⁰

```

Count and output the number of wins.

If the input was sorted, the calculation could be done in 19 bytes. Unfortunately it takes me 30 bytes to sort the input...

# Answer
> 2 votes
# Wolfram Language (Mathematica), 48 bytes

```
Max[t=#2;Tr@Boole@Thread[#>t]&/@Permutations@#]&

```

Try it online!

Unnamed function taking two arguments as input (first our team, then their team), each as comma-separated lists such as `{2,4,6,2,6}`. Brute-force check over all `Permutations` of the input, taking the `Max`. Mathematica doesn't automatically compare lists elementwise, but `Thread[#>t]` forces it to; `Boole` converts `True`s and `False`s to `0`s and `1`s, respectively, so that `Tr` counts the number of wins. Mathematica is bad with currying when it's not programmed into the builtins, so I couldn't see a better way to handle the arguments than `t=#2;`.

# Answer
> 2 votes
# k4, 27 bytes

```
{{x+y>x}/binr/{x@<x}'(y;x)}

```

Another port of Jonah's J answer, this time to k4.

If the input can be taken as a single list of two vectors, e.g. `(3 10 6 7 7;2 4 6 2 6)` (with the opposing team as the first list item, and our team as the second), the code can be simplified to 22 bytes as:

```
{{x+y>x}/binr/x@'<:'x}

```

# Answer
> 1 votes
# Japt `-h`, 10 bytes

```
á Ëí>V xÃn

```

Try it

# Answer
> 1 votes
# Scala, 168 bytes

Golfed version. Attempt this online!

```
def f(a:Array[Int],b:Array[Int])={var B=b.sorted;var sA=a.sorted;sA.foldLeft(0){(s,x)=>val C=B.dropWhile(_<x);val c=C.nonEmpty&&C(0)==x;if(c){B=B.drop(1);s+1}else s}-1}

```

Ungolfed version. Attempt this online!

```
def f(a: Array[Int], b: Array[Int]): Int = {
  var sortedB = b.sorted
  var sortedA = a.sorted
  sortedA.foldLeft(0) { (sum, x) =>
    val removedB = sortedB.dropWhile(_ < x)
    val condition = removedB.nonEmpty && removedB.head == x
    if (condition) {
      sortedB = sortedB.drop(1)
      sum + 1
    } else sum
  } - 1
}

```

But the scala code fails at the case `val input3 = Array(Array(10), Array(3,6,7,5,3,5,6,2,9,1), Array(2,7,0,9,3,6,0,6,2,6))`. Any help would be appreciated.

---
Tags: code-golf
---