# Question
Title: Maximum summed subsequences with non-adjacent items
## Introduction:

Inspired by these two SO questions (no doubt from the same class): print the elements in the subarray of maximum sum without adjacent elements java and Maximum sum of non adjacent elements of an array, to be printed.

## Challenge:

Given a list of integers, output a subsequence consisting of non-adjacent elements that have the highest sum. Here some examples:

* `[1,2,3,-1,-3,2,5]` would result in `[1,3,5]` (with a sum of `9`) at the 0-based indices `[0,2,6]`.
* `[4,5,4,3]` would result in either `[4,4]` (with a sum of `8`) at the 0-based indices `[0,2]` or `[5,3]` (also with a sum of `8`) at the 0-based indices `[1,3]`.
* `[5,5,10,100,10,5]` would result in `[5,100,5]` (with a sum of `110`) at either the 0-based indices `[0,3,5]` or `[1,3,5]`.

What's most important about these examples above, the indices containing the elements are at least 2 apart from each other. If we look at the example `[5,5,10,100,10,5]` more in depth: we have the following potential subsequence containing non-adjacent items; with their indices below it; with their sums below that:

```
[[5],[10],[100],[10],[5],[5],[100,5],[10,5],[10,10],[5,5],[5,10],[5,100],[5,5],[5,10],[5,100],[5,10],[5,100,5],[5,100,5],[5,10,5],[5,10,10]]   // non-adjacent subsequences
[[5],[ 4],[  3],[ 2],[1],[0],[  3,5],[ 2,5],[ 2, 4],[1,5],[1, 4],[1,  3],[0,5],[0, 4],[0,  3],[0, 2],[1,  3,5],[0,  3,5],[0, 2,5],[0, 2, 4]]   // at these 0-based indices
[  5,  10,  100,  10,  5,  5,    105,    15,     20,   10,    15,    105,   10,    15,    105,    15,      110,      110,      20,       25]   // with these sums
                                                                                ^         ^                        // and these two maximums

```

Since the maximum sums are `110`, we output `[5,100,5]` as result.

## Challenge rules:

* You are allowed to output key-value pairs of the index + value. So instead of `[5,100,5]` you can output `[[0,5],[3,100],[5,5]]` or `[[1,5],[3,100],[5,5]]` as result (or `[[1,5],[4,100],[6,5]]`/`[[2,5],[4,100],[6,5]]` when 1-based indexing is used instead of 0-based).
    + If you use key-value pairs, they can also be in reverse or random order, since it's clear which values are meant due to the paired index.
    + Outputting just the indices without values isn't allowed. It should either output the values, or the values/indices as key-value pairs (or two separated lists for 'keys' and 'values' of the same size if key-value pairs are not possible in your language of choice).
* You are allowed to output all possible subsequences with the maximum sum instead of just one.
* As you can see from the examples, the input-list can contain negative and duplicated values as well. You can assume the input-integers are within the range \\$\[-999,999\]\\$.
* The output-list cannot be empty and must always contain at least one element (if a list would only contain negative values, a list containing the single lowest negative value would then be output as result - see last two test cases).
* If there is one possible output but for multiple different indices, it's allowed to output both of them even though they might look duplicates. (i.e. the example above, may output `[[5,100,5],[5,100,5]]` for both possible index-combinations).

## Test cases:

```
Input:                   Possible outputs:       At 0-based indices:     With sum:

[1,2,3,-1,-3,2,5]        [1,3,5]                 [0,2,6]                 9
[4,5,4,3]                [4,4]/[5,3]             [0,2]/[1,3]             8
[5,5,10,100,10,5]        [5,100,5]               [0,3,5]/[1,3,5]         110
[10]                     [10]                    [0]                     10
[1,1,1]                  [1,1]                   [0,2]                   2
[-3,7,4,-2,4]            [7,4]                   [1,4]                   11
[1,7,4,-2]               [7]                     [1]                     7
[1,2,-3,-4,5,6,-7]       [2,6]                   [1,5]                   8
[800,-31,0,0,421,726]    [800,726]/[800,0,726]   [0,5]/[0,3,5]/[0,2,5]   1526
[-1,7,8,-5,40,40]        [8,40]                  [2,4]/[2,5]             48
[-5,-18,-3,-1,-10]       [-1]                    [3]                     -1
[0,-3,-41,0,-99,-2,0]    [0]/[0,0]/[0,0,0]       [0]/[3]/[6]/[0,3]/
                                                  [0,6],[3,6]/[0,3,6]    0

```

# Answer
> 3 votes
# Jelly, 8 bytes

```
ŒPm€2SÞṪ

```

Try it online!

This is a function submission (it's almost usable as a full program, which is what the TIO link does, but the output format is a little weird; when used as a function, though, it just outputs the list of elements from the subsequence).

## Explanation

I found a much terser algorithm (loosely inspired by my previous Brachylog answer), saving 6 bytes over the Jelly and Brachylog answers and 3 bytes over the current leading answer.

```
ŒPm€2SÞṪ
ŒP         On the set of all subsequences of {the input},
  m 2        remove every second element of
   €         each subsequence,
      ÞṪ     then {return} the resulting subsequence with the maximal
     S       sum

```

The basic idea is that we don't look for the subsequence we want directly; rather, we find a subsequence with an additional element inserted in between each of the elements we want. This is always possible if the elements of the subsequence we want are not adjacent in the original list (because there'll always be at least one in between to insert), and never possible if the elements of the subsequence we want are adjacent in the original list. So all we have to do is look at all the subsequences of the input, then take alternating elements from them, to get a list of all the non-adjacent-item subsequences of the input.

This algorithm will return many of the non-adjacent-item subsequences more than once, but that doesn't matter, because we're just looking for a maximal element, and repeating elements of the set we're taking a maximum of has no influence on the maximum.

# Answer
> 6 votes
# Husk, 11 bytes

```
►Σ†!¹mü≈tṖŀ

```

Try it online!

## Explanation

```
►Σ†!¹mü≈tṖŀ  Implicit input, say L=[4,5,3,4].
          ŀ  Indices: [1,2,3,4]
         Ṗ   Powerset: [[],[1],[2],[1,2],..,[1,2,3,4]]
        t    Tail (remove the empty list): [[1],[2],[1,2],..,[1,2,3,4]]
     m       For each,
      ü      de-duplicate by
       ≈     differing by at most 1.
             For example, [1,2,4] becomes [1,4].
  †          Deep map
   !¹        indexing into L: [[4],[5],[4],..,[5,4],[4,3]]
►            Maximum by
 Σ           sum: [5,4]

```

# Answer
> 6 votes
# , ~~136~~ 125 bytes

```
function(l,G=unlist(Map(combn,list(y<-seq(a=l)),y,c(function(x)'if'(all(diff(x)>1),l[x],-Inf)),F),F))G[which.max(Map(sum,G))]

```

Try it online!

*-6 bytes thanks to digEmAll*, who incidentally also outgolfed me.

Returns the shortest subsequence as a `list`, breaking ties on lexicographically first by indices.

Brute-force generates all index subsequences, then `Filter`s for those that are non-adjacent, i.e., where `all(diff(x)>1)`. Then subsets `[` into `l` using these indices, selecting `[[` the first one where the sum is the max (`which.max`).

~~I'm pretty sure this is the first R answer I've ever written that uses `Filter`!~~ sad, `Filter` is ungolfy, no wonder I've never used it...

# Answer
> 6 votes
# Haskell, 60 bytes

```
snd.([]%)
r%(h:t)=max(r%t)$(r++[h])%drop 1t
r%_=(sum r<$r,r)

```

Try it online!

The helper function `%` recursively branches on choosing whether the include the first element and drop the second, or to skip the first element. It takes the maximum of all outcomes, which are tuples whose first element is the sum, and whose second element is the corresponding list which is extracted for the output.

To handle the rule that the empty list is disallowed even if it would have the smallest trick, we do a cute trick of writing `sum r<$r` rather than `sum r`.This makes a list whose elements all are `sum r` and whose length is that of `r`. That way, when we choose the maximum, we prioritize any list over an empty `r`, but otherwise comparisons depend on the first element which is `sum r` .

# Answer
> 5 votes
# 05AB1E, 14 bytes

Saved 1 byte thanks to *Kevin Cruijssen*

```
ā<æʒĆ¥≠W}èΣO}θ

```

Try it online! or as a Test Suite

**Explanation**

```
ā<               # push [0 ... len(input)-1]
  æ              # compute powerset
   ʒ    }        # filter, keep lists where:
      ≠W         # no element is 1 in the
     ¥           # deltas
    Ć            # of the list with the head appended
         è       # index into the input with each
          ΣO}    # sort by sum
             θ   # take the last element

```

# Answer
> 5 votes
# Brachylog (v2), 14 bytes

```
{~ba~c∋₁ᵐ}ᶠ+ᵒt

```

Try it online!

Function submission; input from the left, output from the right, as usual. Very slow; a five-element list is probably the maximum for testing on TIO.

```
{~ba~c∋₁ᵐ}ᶠ+ᵒt
 ~b              Prepend an arbitrary element to the input
   a             Take a prefix or suffix of the resulting list
    ~c           Ordered partition into contiguous sublists
      ∋₁         Take the second element
        ᵐ          of each sublist
{        }ᶠ      Find all possible ways to do this
           +ᵒ    Sort by sum
             t   Take the greatest

```

The results we get from prefixes aren't incorrect, but also aren't interesting; all possible results are generated via taking a suffix (which is possibly the list itself, but cannot be empty), but "suffix" is more verbose in Brachylog than "prefix or suffix", so I went with the version that's terser (and less efficient but still correct). The basic idea is that for each element we want in the output list, the partition into contiguous sublists needs to place that element and the element before into the same sublist (because the element is the *second* element of the sublist), so two consecutive elements can't appear in the result. On the other hand, it's fairly clear that any list without two consecutive elements can appear in the result. So once we have all possible candidate lists, we can just take the sums of all of them and see which one is largest.

# Answer
> 3 votes
# Jelly, ~~16~~ 14 bytes

```
JŒPḊf’$ÐḟịµSÞṪ

```

Try it online!

Thanks to @EriktheOutgolfer for saving 2 bytes!

# Answer
> 3 votes
# JavaScript (ES6),  ~~138 132 130 129~~  126 bytes

Outputs key-value pairs.

```
a=>a.reduce((a,x,i)=>[...a,...a.map(y=>[[x,i],...y])],[[]]).map(m=a=>a.some(s=p=([v,i])=>p-(s=~~s+v,p=i)<2)|s<m||(r=a,m=s))&&r

```

Try it online!

### Step 1

We first compute the powerset of the input with \\$\[value, index\]\\$ pairs.

```
a.reduce((a, x, i) => // for each value x at position i:
  [                   //   update a[] to a new array consisting of:
    ...a,             //     all previous entries
    ...a.map(y =>     //     for each value y in a[]:
      [[x, i], ...y]  //       append [x, i], followed by all original entries
    )                 //     end of map()
  ],                  //   end of new array
  [[]]                //   start with a = [[]]
)                     // end of reduce()

```

### Step 2

We then look for the maximum sum \\$m\\$ among these sets, discarding sets with at least two adjacent elements. The best set is stored in \\$r\\$.

```
.map(m =              // initialize m to a non-numeric value
  a =>                // for each entry a[] in the powerset:
  a.some(s = p =      //   initialize s and p to non numeric values
    ([v, i]) =>       //   for each value v and each index i in a[]:
    p - (             //     compute p - i
      s = ~~s + v,    //     add v to s
      p = i           //     update p to i
    ) < 2             //     if p - i is less than 2, yield true
  ) |                 //   end of some()
  s < m ||            //   unless some() was truthy or s is less than m,
  (r = a, m = s)      //   save a[] in r[] and update m to s
) && r                // end of map(); return r[]

```

# Answer
> 3 votes
# T-SQL, ~~122~~ ~~119~~ 118 bytes

Input is a table variable.

This query picks all elements from the table variable, combining these with all non-adjacent elements with higher position values and show the text generated for the highest sum of these values.

```
WITH C(y,j,v)as(SELECT*,x*1FROM @
UNION ALL
SELECT y+','+x,i,v+x
FROM @ JOIN C ON~-i>j)SELECT
TOP 1y FROM C ORDER BY-v

```

**Try it online** ungolfed

# Answer
> 3 votes
## Haskell, ~~81~~ 80 bytes

```
snd.maximum.map((,)=<<sum).tail.f
f(a:b:c)=f(b:c)++map(a:)(f c)
f a=[]:map(:[])a

```

Try it online!

`f` builds all valid subsequences by either skipping the next element (`f(b:c)`) or using it and skipping the next (`map(a:)(f c)`) and recursively work on the rest. For the result, build all subsequences (`f`), drop the empty subsequence (which occurs first in the list: `tail`), make pairs `(<sum>,<subsequence>)` (`map((,)=<<sum)`), find the maximum (pairs are compared in lexicographical order) -\> `maximum`) and drop the sum (`snd`).

Edit: -1 byte thanks to @Lynn.

# Answer
> 3 votes
# , 47 bytes

```
>@{:@(<@#~/:+/@#~)1(-#~0=1 1+/@E."1-)[:i.&.#.=~

```

Try it online!

*-7 bytes thanks to FrownyFrog*

# original

# , 54 bytes

```
[:(>@{:@/:+/&>)]<@#~"1[:(#~0=1 1+/@E."1])[:#:@}.@i.2^#

```

Try it online!

# Answer
> 2 votes
# Pyth, 19 bytes

```
esDm@LQdtf!q#1.+TyU

```

Try it online here, or verify all the test cases at once here.

```
esDm@LQdtf!q#1.+TyUQ   Implicit: Q=eval(input())
                       Trailing Q inferred
                  UQ   Generate range [0-len(Q))
                 y     Take the powerset of the above
         f             Filter keep elements of the above, as T, using:
              .+T        Take differences of consecutive elements of T
           q#1           Keep those differences equal to 1
          !              Logical NOT - empty lists evaluate to true, populated ones to false
                       Result of the filter is those sets without consecutive numbers
        t              Drop the first element (empty set)
   m                   Map the remaining sets, as d, using:
     L d                 For each element of d...
    @ Q                  ... get the element in Q with that index
 sD                    Order the sets by their sum
e                      Take the last element, implicit print

```

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

```
If[Max[a=#]>(d=Max[m=Tr/@(g=a[[#]]&/@Select[Subsets[Range[x=Length@#],{2,x}]&@#,FreeQ[Differences@#,1]&]&@a)]),{Max@a},g[[#]]&@@@Position[m,d]]&

```

Try it online!

# Answer
> 2 votes
# Wolfram Language (Mathematica), ~~70~~ 63 bytes

```
MaximalBy[Select[q=Rest@Subsets@#,!FreeQ[q,#~Riffle~_]&],Tr,1]&

```

Try it online!

High-level search

```
          Select[q=Rest@Subsets@#,                     ]        (*choose nonempty subsets of the input such that*)
                                  !FreeQ[q,          ]&         (*there exists a subset of the input which matches*)
                                           #~Riffle~_           (*this list, with an item inserted between adjacent elements*)
MaximalBy[                                              ,Tr,1]& (*and return one with the greatest total*)

```

`,1` is required so as not to inadvertently return invalid sets (otherwise, for example, an input of `{1,1,1}` would result in an output of `{{1,1},{1,1},{1,1}}`)

# Answer
> 2 votes
# Gaia, 24 bytes

```
e:w;ċz⟨ọ1>¦ẏ⟩⁇‼⁇E‡ev2%Σ⌠

```

Try it online!

Ugh, `E‡` does some weird stuff...according to the documentation, it *should* do something like "given length `i` set of lists `X` and length `j` set of indices `Y`, return `X[i][Y[j]]`", but instead returns `[X[i][Y[j]] X[i][Y[-j]]` where negative indexing represents the complement, so we have to do `ev2%` to extract only the ones we want.

```
e				| eval as a list l
 :				| dup
  w				| wrap as a list
   ;				| push l again
    ċ				| push [1..len(l)]
     z				| push all subsets of [1..len(l)] -- index powerset.
      ⟨      ⟩⁇			| filter this for:
       ọ			| deltas
        1>¦			| are greater than 1
           ẏ			| all (all deltas greater than 1)
	       ‼⁇		| filter for non-empty lists
		 E‡		| table extract elements. Given l and index set i, this pushes
				| [l[i] l[setdiff(1..l,i)]] for some reason
		   ev2%		| get the l[i] only by unlisting, reversing, and taking every other element
		       Σ⌠	| Get the one with the maximum sum

```

# Answer
> 2 votes
# , ~~108~~ 107 bytes

```
function(v,M=-Inf){for(j in J<-seq(a=v))for(i in combn(J,j,,F))if(all(diff(i)>1)&sum(v[i])>sum(M))M=v[i]
M}

```

Try it online!

-1 thanks to @Giuseppe

# Answer
> 1 votes
# Haskell, ~~300~~ 168 bytes

```
import Data.List
h[]=1>2
h(x:y)=fst$foldl(\a c->((fst a)&&(c-snd a>1),c))(1<2,x)y
z=snd.last.sortOn fst.map((,)=<<sum.snd).filter(h.fst).map unzip.subsequences.zip[0..]

```

Try it online!

-132 bytes thanks to all the feedback from @nimi :)

---

Original

### Ungolfed (original)

import Data.List
import Data.Function

f :: [Int] -> [(Int, Int)] -- attach indices for later use
f [] = []
f xs = zip xs [0..length xs]

g :: [[(Int, Int)]] -> [([Int], [Int])] -- rearrange into list of tuples
g [] = []
g (x:xs) = (map fst x, map snd x) : g xs

h :: [Int] -> Bool -- predicate that checks if the indices are at least 2 apart from each other
h [] = False
h (x:xs) = fst $ foldl (\acc curr -> ((fst acc) && (curr - snd acc > 1), curr)) (True, x) xs
j :: [([Int], [Int])] -> [([Int], [Int])] -- remove sets that don't satisfy the condition
j xs = filter (\(elements, indices) -> h indices) xs

k :: [([Int], [Int])] -> [(Int, ([Int], [Int]))] -- calculate some of elements
k xs = map (\(elements, indices) -> (foldl1 (+) elements, (elements, indices))) xs

l :: [(Int, ([Int], [Int]))] -> ([Int], [Int]) -- grab max
l xs = snd $ last $ sortBy (compare `on` fst) xs

z -- put things together
```
</code></pre>

# Answer
> 1 votes
# Charcoal, 46 bytes

```
≔⟦υ⟧ηＦθ«≔υζ≔Ｅη⁺κ⟦ι⟧υ≔⁺ζηη»≔Φ⁺υηιη≔ＥηΣιζＩ§η⌕ζ⌈ζ

```

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

```
≔⟦υ⟧η

```

The variable `u` is predefined with an empty list. This is put in a list which is assigned to `h`. These variables act as accumulators. `u` contains the sublists that include the latest element of the input `q` while `h` contains the sublists that do not (and therefore are suitable for appending the next element of the input).

```
Ｆθ«

```

Loop over the elements of the input.

```
≔υζ

```

Save the list of sublists that contain the previous element.

```
≔Ｅη⁺κ⟦ι⟧υ

```

Take all of the sublists that do not contain the previous element, append the current element, and save the result as the list of sublists that contain the current element. (I don't use `Push` here as I need to clone the list.)

```
≔⁺ζηη»

```

Concatenate both previous sublists into the new list of sublists that do not contain the current element.

```
≔Φ⁺υηιη

```

Concatenate the sublists one last time and remove the original empty list (which Charcoal can't sum anyway).

```
≔ＥηΣιζ

```

Compute the sums of all of the sublists.

```
Ｉ§η⌕ζ⌈ζ

```

Find an index of the greatest sum and output the corresponding sublist.

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

Ever have one of those challenges where you completely forget how to golf?!

```
ð¤à fÊk_än ø1Ã®mgUÃñx

```

Try it

```
ð¤à fÊk_än ø1Ã®mgUÃñx     :Implicit input of array U
ð                         :Indices of elements that return true when
 ¤                        :  Converted to a base-2 string (to account for 0s)
  à                       :Combinations
    f                     :Filter by
     Ê                    :  Length (to remove the empty combination)
      k_                  :Remove elements that return true
        än                :  Deltas
           ø1             :  Contains 1
             Ã            :End remove
              ®           :Map
               m          :  Map
                gU        :    Index into U
                  Ã       :End map
                   ñ      :Sort by
                    x     :  Sum
                          :Implicit output of last element

```

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

```
Êo à k_mÄ øZÃm!gU
fÊñx

```

Try it

# Answer
> 1 votes
# Python 2, ~~63~~ ~~70~~ 65 bytes

```
f=lambda a:a and max([a[:1],a[:1]+f(a[2:]),f(a[1:])],key=sum)or a

```

Try it online!

5 bytes thx to ArBo

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


title: Which side should I serve on?

text:
# Question
Title: Which side should I serve on?
# Introduction

In Tennis, the server alternates serving on the left side or the right side of the court every point, starting on the right. It is possible to figure out which side to serve on for that point just based on the score; if there have been an even number of points you serve on the right, and after an odd number of points, on the left. Scoring in tennis works as follows:

```
Points | Corresponding Call
       |
0      | Love
1      | 15
2      | 30
3      | 40

```

Once a player scores 4 points, they win the game. If the score is tied at 40-40, the call is "Deuce" rather than "40-40" or "40 all". At Deuce, the subsequent point is called as "Advantage \[x\]" or "Ad \[x\]" where x is the player who scored. If the opposite player scores next, the score returns to Deuce, but if the same player scores again, they win.

# The Challenge

Your task is to write a function that takes the score and returns a truthy or falsey value. The input may be a string containing the call or a list containing the scores. Love, Deuce, and Ad must be strings but the rest of calls may be any numerical type as well. Deuce may be represented by singleton list containing "Deuce" or a list with "Deuce" and another value of your choice. You may choose which side corresponds to truthy and falsey, but **you must specify which corresponds to which side in your answer**. The scores will be separated by a hyphen, except in the case of Deuce wherein it will be simply "Deuce". For advantage, the score will be "Ad-40" or "40-Ad".

# Winning

This is code golf, so the score is the number of bytes in your function and the answer with the lowest score wins. Standard loopholes are forbidden.

# Test Cases

```
Love-Love | True
Love-15   | False
Love-30   | True
Love-40   | False
15-Love   | False
15-15     | True
15-30     | False
15-40     | True
30-Love   | True
30-15     | False
30-30     | True
30-40     | False
40-Love   | False
40-15     | True
40-30     | False
Deuce     | True
Ad-40     | False
40-Ad     | False

```

These test cases are exhaustive, i.e. that list represents every possible input and its corresponding output. I used True for right and False for left.

# Answer
# Retina 0.8.2, 7 bytes

```
M`4|5
1

```

Try it online! Link includes test cases. Outputs `0` for right and `1` for left. Explanation:

```
M`[45]

```

The number of 4s and 5s...

```
1

```

... must equal 1 if the serve is on the left.
> 16 votes

# Answer
# Perl 5 (-p), ~~17~~, ~~11~~, 10 bytes

-6 using Neil's solution, -1 thanks to Dom Hastings re-ordering

```
$_=1^y;45;

```

Try it online!

0 for false, \<\>0 for true
> 5 votes

# Answer
# Python 2, 26 bytes

Takes input in the same format as the test cases. Output is inverted, `1` for falsey cases and `0` for truthy ones. Normal output would be 1 byte longer with a `-` preprended.

```
lambda s:hash(s)*199%421%2

```

Try it online!
> 4 votes

# Answer
# Haskell, 29 bytes

```
odd.sum.map(mod 882.fromEnum)

```

Try it online!

An anonymous function taking a hyphenated call and returning `True` or `False`, just like in the test cases.

Note: it looks like we're taking values "mod 882", but actually in Haskell `mod 882` is the function \\$y \mapsto (882 \bmod y)\\$. (That is: it's a partially-applied `mod x y`.)
> 4 votes

# Answer
# Haskell, 28 bytes

```
f s=[1|c<-s,elem c"45"]==[1]

```

Try it online!

Implement's Neil's method of checking that the string has exactly one 4 or 5. Test suite from Lynn.

Haskell doesn't have a nice way to count elements satisfying a property. We could do `filter(`elem`"45")`, but then it seems too long to check the resulting list is a single element, or check that it's one of `"4"` or `"5"`.

We use a list comprehension to make a list with a `1` for each character that's in `"45"`, and check if we end up with the list `[1]`. Any value could be used in place of `1` here, including `s` itself.
> 4 votes

# Answer
# JavaScript (ES6), 26 bytes

Using @Neil's method saves 4 more bytes.

Expects a string. Returns **0** for *left* or **1** for *right*.

```
s=>s.split(/4|5/).length%2

```

Try it online!

---

# JavaScript (ES6), 30 bytes

Expects a pair of string scores (or a singleton for `Deuce`). Returns **0** for *right* or **1** for *left*.

```
a=>parseInt(a.join`2`,36)%31%2

```

Try it online!

---

# JavaScript (ES6), 34 bytes

Expects a string. Returns **0** for *left* or **1** for *right*.

```
s=>parseInt(s[0]+s[3]+s[5],35)%3%2

```

Try it online!

### How?

Looking at the 1st and the 4th characters provides enough information, except if the score is `Love-X` in which case we need to look at the 6th character as well. To make things easier, we just look at these 3 positions in all cases and hash them.

Below is a summary of the process for each possible input.

```
 input       | s[0]+s[3]+s[5] | parsed as base-35 | mod 3 | mod 2
-------------+----------------+-------------------+-------+-------
 "Love-Love" | "LeL"          |             26236 |   1   |   1
 "Love-15"   | "Le1"          |             26216 |   2   |   0
 "Love-30"   | "Le3"          |             26218 |   1   |   1
 "Love-40"   | "Le4"          |             26219 |   2   |   0
 "15-Love"   | "1Lv"          |              1991 |   2   |   0
 "15-15"     | "11undefined"  |  2906423713803553 |   1   |   1
 "15-30"     | "13undefined"  |  3064054991147303 |   2   |   0
 "15-40"     | "14undefined"  |  3142870629819178 |   1   |   1
 "30-Love"   | "3Lv"          |              4441 |   1   |   1
 "30-15"     | "31undefined"  |  8423518420834803 |   0   |   0
 "30-30"     | "33undefined"  |  8581149698178553 |   1   |   1
 "30-40"     | "34undefined"  |  8659965336850428 |   0   |   0
 "40-Love"   | "4Lv"          |              5666 |   2   |   0
 "40-15"     | "41undefined"  | 11182065774350428 |   1   |   1
 "40-30"     | "43undefined"  | 11339697051694176 |   0   |   0
 "Deuce"     | "Dcundefined"  | 36875963981381680 |   1   |   1
 "Ad-40"     | "A4undefined"  | 27969796811459804 |   2   |   0
 "40-Ad"     | "4Aundefined"  | 11891406522397304 |   2   |   0

```
> 2 votes

# Answer
# Jelly, 6 bytes

```
OP%25Ḃ

```

A monadic Link accepting a list of characters which yields `1` if serving from the right or `0` if serving from the left.

**Try it online!**

### How?

```
OP%25Ḃ - Link: list of characters  e.g. "15-30"
O      - ordinals                       [49,53,45,51,48]
 P     - product                        286085520
   25  - twenty-five                    25
  %    - modulo                         20
     Ḃ - modulo-2                       0

```

---

Also 6 bytes using Neil's observation (inverted result):

```
f⁾45LḂ - Link: list of characters, S
 ⁾45   - list of characters = "45"
f      - filter (S) keep (those characters)
    L  - length -> 0, 1, or 2; but only 1 when serving from the left
     Ḃ - modulo-2

```
> 2 votes

# Answer
# Raku, 12 bytes

```
{1-m:g/1|4/}

```

Try it online!

An anonymous function that returns zero for left and non-zero for the right. This uses Neil's observation that there must be exactly one `1` or `4` for it to be the left side's serve.
> 2 votes

# Answer
# Pyth, 10 bytes

```
%%CSz287 2

```

Try it online!

### Explanation, A little different to the others here...

```
%%CSz287 2
   Sz        - Sort the input string, (so that Love-15 and 15-Love provide the same string)
  CSz        - Get the 256 base int value of the string.
 % ^ 287     - Modulo that number by 287
%  ^     2   - Return whether that number is odd or even.

```
> 2 votes

# Answer
# Scala, ~~30~~ 29 bytes

```
_.matches("[^45]*[45][^45]*")

```

Try it online!

My solution uses false for right and true for left.
> 2 votes

# Answer
# Jelly, 7 bytes

```
Ṣ“Œọ‘ḥḂ

```

Try it online! (the footer tests the program on all possible inputs)

Takes input in the form of a list of strings, e.g. `["Love","15"]`, `["40","Ad"]`, or `["Deuce"]`. Outputs 0 or 1, in the opposite sense from the table of test cases in the question (i.e. 0 = right, 1 = left).

This is using much the same idea as the other answers: we simply find a hash function that happens to map each possible input to the correct output. In order to make it more likely that a randomly selected hash function would produce the correct result (therefore reducing the number of bytes needed to specify which hash function we want), the input list is sorted before hashing it (thus almost halving the number of cases we need to match; a score of *X*-*Y* always produces the same answer as a score of *Y*-*X*).

There wasn't any skill that went into the selection of the hash function; there was a 2<sup>-12</sup> probability that any given hash function would work, which is fairly high, so I simply tried Jelly's built-in hash functions in order from shortest to longest configuration, and picked the first one that worked. This is hash function \[19,221\]. Because configuring the hash function to output booleans would require a substantially larger configuration string, I just used the default output format (this one outputs numbers in the range 1…221) and took the least significant bit of the output as my output.

## Explanation

```
Ṣ“Œọ‘ḥḂ
Ṣ          Sort {the input list}
     ḥ     Hash {the sorted list}, with configuration
 “Œọ‘        [19, 221] (compressed representation)
      Ḃ    Take the least significant bit of the output

```
> 1 votes

# Answer
# Bash, 20 bytes

```
[[ $[$1] = *[14]* ]]

```

Try it online!

In Bash, any unset variables are 0 in `$[arithmetic mode]`. A quick test revealed that if the input was evaluated in arithmetic mode, the following pattern emerges:

```
Result:  0  10 -10  15 -15  25 -25  30 -30  40 -40
  Side:  R   L   L   L   L   R   R   R   R   L   L

```

Thus, if the arithmetic result contains a 1 or a 4, it is a left serve, otherwise it is a right serve.
> 1 votes

# Answer
# Husk, 9 bytes

```
%2`%25Πmc

```

Try it online!

Same method as Jonathan Allan's answer.
> 1 votes

# Answer
## Batch, 32 bytes

```
@set/an=(%1)/10%%3^&1
@echo %n%

```

Takes input on the command line and outputs `1` for serves on the left and `0` for serves on the right. Explanation: Based on @GammaFunction's answer, by performing arithmetic evaluation on the input, and assuming that the variables `Love`, `Ad` and `Deuce` are unset and therefore zero, the tens digit of the result is `1` or `4` for serves on the left and `0`, `2` or `3` for serves on the right. This is then further reduced via modulo with `3` and bitwise and with `1` to produce the desired result.
> 1 votes

# Answer
# Charcoal, 9 bytes

```
⁼¹ＬΦθ№45ι

```

Try it online! Link is to verbose version of code. Output is a Charcoal boolean, where `-` (True) means you serve on the left and empty output (False) means you serve on the right. Explanation:

```
   Φθ       Filter input where
     №45ι   Literal string `45` contains character
  Ｌ         Length
⁼¹          Equals literal `1`
            Implicitly print

```

Longer than Retina, sigh... (I found several formulations for 9 bytes, but none shorter that weren't buggy.)
> 0 votes

# Answer
# 05AB1E, 6 bytes

```
45S¢O≠

```

Port of *@Neil*'s Retina answer, so make sure to upvote him!!

Try it online or verify all test cases.

**Explanation:**

```
45S     # Push 45, and convert it to a list of digits: [4,5]
   ¢    # Count both of those in the (implicit) input-string
    O   # Take the sum of this pair of counts
     ≠  # And check that it's NOT equal to 1
        # (after which the result is output implicitly)

```
> 0 votes

# Answer
# MathGolf, 7 bytes

```
▒$ε*N%¥

```

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

Try it online.

**Explanation:**

```
▒        # Convert the (implicit) input-string to a list of characters
 $       # Convert each character to its codepoint integer
  ε*     # Take the product of this list (reduce by multiplication)
    N%   # Modulo-25
      ¥  # Modulo-2
         # (after which the entire stack joined together is output implicitly as result)

```
> 0 votes

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


title: A factorization game

text:
# Question
Title: A factorization game
# Input

A single integer \\$1 \leq x \leq 10^{15}\\$.

# Output

The maximum number of distinct positive integers that have the product \\$x\\$.

# Examples

Input: 1099511627776. Output: 9. One possible optimal list of factors is: (1, 2, 4, 8, 16, 32, 64, 128, 4096).

Input: 127381. Output 4. One possible optimal list of factors is: (1, 17, 59, 127).

Related to this old question.

# Answer
# Wolfram Language (Mathematica), 52 bytes

```
Max[Length/@Cases[Subsets@Divisors@#,{a__}/;1a==#]]&

```

Try it online!

*4-bytes saved thanks to @attinat*

Here is also a **153 bytes** version that calculates `1099511627776` and `10^15`

```
Max[Length/@Table[s=RandomSample@Flatten[Table@@@FactorInteger[#]];Last@Select[Times@@@TakeList[s,#]&/@IntegerPartitions@Length@s,DuplicateFreeQ],5!]]+1&

```

Try it online!

The result for `10^15` is **12**

> {1, 2, 4, 5, 10, 16, 25, 40, 50, 100, 125, 250}
> 5 votes

# Answer
# Wolfram Language (Mathematica), 38 bytes

```
(c=n=#;If[i∣n,n/=i,--c]~Do~{i,n};c)&

```

Try it online!

Greedy algorithm. Times out on TIO on larger inputs such as `1099511627776`.
> 4 votes

# Answer
# 05AB1E, 9 bytes

Very inefficient. Will time out on TIO for numbers with a large amount of divisors.

```
ÑæʒPQ}€gZ

```

Try it online!

**Explanation**

```
Ñ          # push a list of divisors of the input
 æ         # push the powerset of that list
  ʒPQ}     # filter, keep only the lists whose product is the input
      €g   # get the length of each
        Z  # take the maximum

```
> 3 votes

# Answer
# Jelly, 9 bytes

```
ŒPP=³ƊƇẈṀ

```

Try it online!

-1 byte thanks to someone

-2 bytes thanks to ErikTheOutgolfer
> 2 votes

# Answer
# Perl 6, 38 bytes

```
{$!=$_;+grep {$!%%$_&&($!/=$_)},1..$_}

```

Try it online!

Takes the greedy approach to selecting divisors.
> 2 votes

# Answer
# Javascript (ES6), 39 bytes

```
f=(n,i=0)=>n%++i?n>i&&f(n,i):1+f(n/i,i)

```

There's probably a few bytes that can be saved here and there. Just uses the greedy algorithm for the factors.
> 2 votes

# Answer
# Japt `-h`, 13 bytes

```
â à f_×¶UÃmÊn

```

Try it
> 2 votes

# Answer
# Brachylog, 8 bytes

```
f;?⟨⊇×⟩l

```

Try it online!

(The naive approach, `{~×≠l}ᶠ⌉`, generates an infinite number of solutions with extra 1s before eliminating them with , and thus fails to actually terminate. It's not a problem, though, since it's for the same byte count!)

Takes input through the input variable and output through the output variable. The header on TIO contains a copy of most of the code for the sake of showing you what the factor list is, but this works perfectly fine without it. Since  gives larger sublists first, this predicate essentially does the same thing as most other answers, but without explicitly generating and filtering the complete powerset of the factors, thanks to backtracking.

```
            The output
       l    is the length of
    ⊇       a sublist (the largest satisfying these constraints)
f           of the factors of
            the input
 ; ⟨  ⟩     which
     ×      with its elements multiplied together
  ?         is the input.

```
> 2 votes

# Answer
# Gaia, ~~10~~ 9 bytes

```
Π=
dz↑⁇(l

```

Try it online!

Follows the same "algorithm" as seen elsewhere -- filter the divisor powerset for the longest with product equal to the number and return its length.

```
	| helper function
Π=	| is prod(list)==n (implicit)?
	|
	| main function; implicitly takes n
dz	| divisor powerset (in decreasing order of size)
  ↑⁇	| filter by helper function
    (l	| take the first element and take the length (implicitly output)

```
> 1 votes

# Answer
# Scala, 77 bytes

```
def f(n:Long)={var(m,c,i)=(n,1,2L);while(i<=m){if(m%i==0){m/=i;c+=1};i+=1};c}

```

Try it online!
> 1 votes

# Answer
# Clam, 15 bytes

```
p}_`nq#:;qQ@s~Q

```

TIO link coming soon (when dennis pulls)

Basically a port of @Emigna's 05AB1E solution.

## Explanation

```
                - Implicit Q = first input
p               - Print...
 }              - The last element of...
  _             - Sorted...
   `nq          - Lengths of... (map q => q.len)
           @s   - Items in powerset of
             ~Q - Proper divisors of Q
      #         - Where... (filter)
        ;q      - Product of subset
       :        - Equals...
          Q     - Q

```
> 0 votes

# Answer
# C# (Visual C# Interactive Compiler), 54 bytes

```
int f(int n,int i=0)=>n%++i<1?1+f(n/i,i):n>i?f(n,i):0;

```

Uses the same approach as @vrugtehagel's and @JoKing's answers.

Try it online!
> 0 votes

# Answer
# Ruby, 34 bytes

Obviously times out on that massive number, but will eventually time out if given enough time on another machine.

```
->n{(1..n).count{|e|n%e<1?n/=e:p}}

```

Try it online!
> 0 votes

# Answer
# Husk, 10 bytes

```
▲mLfo=¹ΠṖḊ

```

Try it online! A port of Emigna's answer.
> 0 votes

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


title: The bouncing sequence

text:
# Question
Title: The bouncing sequence
Let us define a sequence. We will say that \\$a(n)\\$ is the smallest number, \\$x\\$, that has the following properties:

* \\$x\\$ and \\$n\\$ are co-prime (they share no factor)
* \\$x\\$ does not appear earlier in the sequence
* \\$|n - x| \> 1\\$

Unlike most sequences the domain and range of our sequence are the integers *greater than* 1.

---

Let us calculate the first couple of terms.

\\$a(2)\\$, must be at least **4**, but **4** and **2** share a factor of **2** so \\$a(2)\\$ must be **5**.

\\$a(3)\\$, must be at least **5** but **5** is taken by \\$a(2)\\$, so it is at least **6**, but **6** shares a factor with **3** so it must be at least **7**, **7** fulfills all three requirements thus \\$a(3)=7\\$.

\\$a(4)\\$

* **2** Shares a factor
* **3** Too close
* **4** Too close
* **5** Too close
* **6** Shares a factor
* **7** Taken by **a(3)**
* **8** Shares a factor
* **9** is good

\\$a(5)\\$

* **2** is good

---

## Task

In this challenge you are to write a program that takes a number greater than 1 and returns \\$a(n)\\$.

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

## Test Cases

Here are the first couple terms of the sequence (They are of course 2 indexed):

```
5,7,9,2,11,3,13,4,17,6,19,8,23,22,21,10,25,12,27,16,15,14

```

## ~~Bonus~~ Fun fact

As proven by Robert Israel on Math.se (link) this sequence is its own inverse, that means that \\$a(a(n)) = n\\$ for all n.

## OEIS

After asking this question I submitted this sequence to the OEIS and after a few days it was added.

OEIS A290151

# Answer
# Haskell, 61 bytes

```
f n=[i|i<-[2..],gcd i n<2,all((/=i).f)[2..n-1],abs(n-i)>1]!!0

```

Try it online!

I'm fairly new to Haskell, so any golfing tips are appeciated.

Thanks to Wheat Wizard for 2 bytes and nimi for 4 bytes

Explanation:

```
f n=[i|i<-[2..],gcd i n<2,all((/=i).f)[2..n-1],abs(n-i)>1]!!0
f n=                                                          -- define a function f :: Int -> Int
    [i|i<-[2..],                                              -- out of positive integers greater than two
                gcd i n<2,                                    -- gcd of i and n is 1
                          all((/=i).f)[2..n-1],               -- i isn't already in the sequence
                                               abs(n-i)>1]    -- and |n-i| > 1
                                                          !!0 -- take the first element

```
> 8 votes

# Answer
# Alice, 42 bytes

```
/oi
\1@/2-&whq&[]w].q-H.t*n$K.qG?*h$KW.!kq

```

Try it online!

### Explanation

```
/oi
\1@/.........

```

This is a standard template for programs that take a number as input, and output a number, modified to place a 1 on the stack below the input number.

The main part of the program places each number `k` in slot `a(k)` on the tape. The inner loop computes a(k), and the outer loop iterates over k until a(n) is computed.

```
1       push 1
i       take input
2-&w    repeat n-1 times (push return address n-2 times)
h       increment current value of k
q&[     return tape to position 0
]       move right to position 1
w       push return address to start inner loop
]       move to next tape position
.q-     subtract tape position from k
H       absolute value
.t*     multiply by this amount minus 1
n$K     if zero (i.e., |k-x| = 0 or 1), return to start of inner loop
.qG     GCD(k, x)
?       current value of tape at position: -1 if x is available, or something positive otherwise
*       multiply
h$K     if not -1, return to start of inner loop
W       pop return address without jumping (end inner loop)
.!      store k at position a(k)
k       end outer loop
q       get tape position, which is a(n)
o       output
@       terminate

```
> 2 votes

# Answer
# Mathematica, 111 bytes

```
(s={};Table[m=2;While[m<3#,If[CoprimeQ[i,m]&&FreeQ[s,m]&&Abs[i-m]>1,s~AppendTo~m;m=3#];m++],{i,2,#}];s[[#-1]])&

```

Try it online! 2..23 (range mode)

Try it online! or 150 (distinct values)
> 1 votes

# Answer
# VB.NET (.NET 4.5), 222 bytes

```
Function A(n)
Dim s=New List(Of Long)
For i=2To n
Dim c=2
While Math.Abs(i-c)<2Or g(c,i)>1Or s.Contains(c)
c+=1
End While
s.Add(c)
Next
Return s.Last
End Function
Function g(a, b)
Return If(b=0,a,g(b,a Mod b))
End Function

```

I had to roll your own GCD. I also couldn't figure out how to get it to not be an entire function.

GCD is always \>= 1, so only need to ignore 1

Took out short-circuiting in the golf because it's shorter

Un-golfed

```
Function Answer(n As Integer) As Integer
    Dim seqeunce As New List(Of Integer)
    For i As Integer = 2 To n
        Dim counter As Integer = 2
        ' took out short-circuiting in the golf because it's shorter
        ' GCD is always >= 1, so only need to ignore 1
        While Math.Abs(i - counter) < 2 OrElse GCD(counter, i) > 1 OrElse seqeunce.Contains(counter)
            counter += 1
        End While
        seqeunce.Add(counter)
    Next
    Return seqeunce.Last
End Function

' roll your own GCD
Function GCD(a, b)
    Return If(b = 0, a, GCD(b, a Mod b))
End Function

```
> 1 votes

# Answer
# Japt, 33 bytes (non-competing?)

```
ò2 rÈc_aY >1«XøZ «Yk øZk}a+2}[] o

```

Try it online!

<sub> I fixed a bug in the Japt Interpreter while working on this solution. This meta post from a year ago deems this answer non-competing, but this newer meta post is pushing for more freedom in this. Regardless, I spent too much time on this to scrap it.</sub>
> 1 votes

# Answer
# 05AB1E, 26 bytes

```
2IŸεDU°2Ÿ¯KʒX¿}ʒXα1›}θDˆ}θ

```

Try it online or output the first \\$n\\$ terms as list. (NOTE: `°` is obviously extremely slow, so replaced with `T*` in the TIO links (\\$10\*n\\$ instead of \\$10^n\\$).)

**Explanation:**

```
2IŸ               # Create a list in the range [2, input]
   ε              # Map each value `y` to:
    DU            #  Store a copy of `y` in variable `X`
    °2Ÿ           #  Create a list in the range [10**`y`,2]
       ¯K         #  Remove all values already in the global_array
       ʒX¿}       #  Only keep values with a greatest common divider of 1 with `X`
       ʒXα1›}     #  Only keep values with an absolute difference larger than 1 with `X`
             θ    #  After these filters: keep the last (the smallest) element
              Dˆ  #  And add a copy of it to the global_array
   }θ             # After the map: only leave the last value
                  # (and output the result implicitly)

```
> 0 votes

# Answer
# Husk, 22 bytes

```
!¡λḟ§&oε⌋o>1≠→L¹`-N);1

```

Try it online!
> 0 votes

# Answer
# Japt, 21 bytes

It pains me to have to invoke a function without a shortcut - can't remember the last time I had to, if ever - but it worked out shorter than any other method I could come up with.

```
@W{WjY «ZøW ©ÓWaY}a}g

```

Try it
> 0 votes

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


# Question
Title: The pirate world's rules of distribution
There is an existing "game" where pirates rationally divide gold coins according to certain rules. Quoting from Wikipedia:

> There are 5 rational pirates, A, B, C, D and E. They find 100 gold coins. They must decide how to distribute them.
>
> The pirates have a strict order of seniority: A is superior to B, who is superior to C, who is superior to D, who is superior to E.
>
> The pirate world's rules of distribution are thus: that the most senior pirate should propose a distribution of coins. The pirates, including the proposer, then vote on whether to accept this distribution. In case of a tie vote the proposer has the casting vote. If the distribution is accepted, the coins are disbursed and the game ends. If not, the proposer is thrown overboard from the pirate ship and dies, and the next most senior pirate makes a new proposal to begin the system again.
>
> Pirates base their decisions on three factors. First of all, each pirate wants to survive. Second, given survival, each pirate wants to maximize the number of gold coins each receives. Third, each pirate would prefer to throw another overboard, if all other results would otherwise be equal. The pirates do not trust each other, and will neither make nor honor any promises between pirates apart from a proposed distribution plan that gives a whole number of gold coins to each pirate.

# Challenge

Take as input an integer `n`, 1\<=n\<=99, where `n` is the number of pirates - and output the distribution of coins, starting with the first pirate.

## Test cases (first line is input; the second output):

```
1
100

2
100 0

3
99 0 1

5
98 0 1 0 1

```

This is , so the shortest solution in bytes wins.

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

```
R%2ḊµSȷ2_;

```

Try it online! or verify all test cases at once.

### How it works

For input **n**, the task boils down to creating the list **x, 0, 1, 0, …** of length **n** whose sum is **100**.

```
R%2ḊµSȷ2_;  Main link. Input: n

R           Yield [1, 2, ..., n].
 %2         Replace each integer by its parity. Yields [1, 0, 1, 0, ...].
   Ḋ        Dequeue; remove the first 1. This yields the list a = [0, 1, ...].
    µ       Begin a new, monadic link. Argument: a
     S      Compute the sum of a.
      ȷ2_   Subtract the sum from 100. (ȷ2 is 1e2 in Python syntax)
         ;  Prepend the difference to a.

```
> 12 votes

# Answer
## Python, 33 bytes

```
lambda n:([-n/2+101]+[0,1]*n)[:n]

```

Computes the first value, appends some `0, 1, 0, 1...`, truncates to length `n`.

Note that `-n/2+101` can't be shortened to `101-n/2` because unary and binary `-` have different precedence: the former is parsed as `(-n)/2` and the latter as `101-(n/2)`.

Recursion was much longer (45):

```
f=lambda n,i=100:1/n*[i]or f(n-1,i-n%2)+[n%2]

```
> 7 votes

# Answer
# MATL, 12 bytes

```
:2\ts_101+l(

```

This uses current version (9.2.2) of the language/compiler, which is earlier than this challenge.

### Example

```
>> matl :2\ts_101+l(
> 5
98  0  1  0  1

```

### Explanation

```
:         % implicitly input number "n". Generate vector [1, 2, ..., n]
2\        % modulo 2. Gives [1, 0, 1, ...]
ts        % duplicate and compute sum
_101+     % negate and add 101
l(        % assign that to first entry of [1, 0, 1, ...] vector. Implicitly display

```
> 4 votes

# Answer
## Pyth, 13 bytes

```
+-100sJ%R2tQJ

```

Test suite.
> 3 votes

# Answer
# Python, ~~62~~ 58 bytes

EDIT: Glad I made it a one-liner. But I lose for Python. Therefore, this is just for reference. Thanks @Zgarb

```
def x(i):n=[~j%2for j in range(i)];n[0]=101-sum(n);print n

```

It takes the input, creates a list pf parity of all numbers from 1 to i. Then sets the first element in i to 101-sum(n) and prints.

Try it here
> 3 votes

# Answer
# Javascript ES6, 45 bytes

```
a=>[...Array(a)].map((x,y)=>y?--y%2:202-a>>1)

```

Thanks to @Neil for 1 byte saved!
> 3 votes

# Answer
# , 14 chars / 26 bytes

```
⩥ï⒨?‡$%2:ỉ-ï»1

```

`Try it here (Firefox only).`

Not bad, but not good either...

# Explanation

```
⩥ï⒨?‡$%2:ỉ-ï»1 // implicit: ï=input, ṥ=101
⩥ï⒨            // map over a range [0,ï) and return:
    ?‡$%2       // (if mapitem>0) then ($-1) mod 2
         :ỉ-ï»1 // (else) 202-ï>>1
                // implicit output

```
> 3 votes

# Answer
# Seriously, ~~23~~ 17 bytes

**EDIT**: Thanks @quintopia

```
,R`2@%`M;Σ2╤u-0(T

```

Uses the same approach as my Python answer, but I do the modulo 2 using mapping, and several times, I rotate my stack.

**Explanation**:

This code pushes input (I will call it `i`). Next pushes `range(1,i+1)` and makes a function. Then pushes 2, rotates stack, and finally takes modulo.

Next, map this function onto the range iterable. This gives the parity of each element in the list.

Finally, duplicates the stack, sums the parity list, push 2, 10^2, and 100+1, and subtracts the sum (let me call this value `n`). Next the code pushes 0, rotates the stack by 1, and sets the list's index 0 element to n. The resulting list is implicitly printed.
> 2 votes

# Answer
# Japt, 14 bytes

Yet another challenge where I find myself wishing for a built-in I had just considered adding...

```
1oU mv u#Ê-UÁ1

```

Try it online!

```
1oU mv u#Ê-UÁ1  // Implicit: U = input integer
1oU             // Create the range [1, U).
    mv          // Map each item to 1 if even, 0 otherwise.
       u        // Unshift (add to the beginning of the array)
        #Ê-UÁ1  //  the char code of Ê (202), minus U >>> 1 (floor of U / 2).

```
> 1 votes

# Answer
## Actionscript 3, 87 bytes

`function x(n){var l=[],i=1;for (l[0]=int(101-n/2);i<n;){l[i]=++i%2;}return l.join(" ")}`

It's not the best golfing language, but I enjoy posting as3 answers.
> 1 votes

# Answer
# 05AB1E, 12 bytes (Non-comp)

```
<LÈDOTns-s)˜

```

Try it online!
> 1 votes

# Answer
# Japt `-S`, 8 bytes

```
ov hL-Uz

```

Try it
> 1 votes

# Answer
## Perl ~~51~~ ~~49~~ 44 bytes

```
$,=$";@"=map{$i++%2}2..<>;say 100-(@">>1),@"

```

Need the following perlrun options `-E`

```
$ perl -E'$,=$";@"=map{$i++%2}2..<>;say 100-(@">>1),@"'<<<5
98
0
1
0
1

```
> 0 votes

# Answer
## QBIC, ~~28~~ 25 bytes

```
:?100-(a-1)'\`2[2,a|?b%2

```

Explanation

```
:               Get command line parameter, assign to 'a'
                Determine the part of the treasure for the crew:
      (a-1) \ 2 Integer Divide 'a'-1 by 2. The -1 compensates for even cases.
           ' `  Make \ a direct command for QBasic instead of substituting it for ELSE.
?100-           Print 100 coins, minus the crew-share --> Captain's booty.
[2,a|           FOR b=2; b <= a; b++; ie for every other crew member
?b%2            Give every odd crewman a coin.
                [FOR loop implicitly closed by QBIC]

```
> 0 votes

# Answer
# Arn, 13 bytes

```
¾*†^…wu½►♦ž]#

```

Try it!

# Explained

Unpacked: `[101-:^:-_{!}->`

```
[           Begin sequence
          --First entry--
     101    Literal `101`
 -          Subtract
   :^       Ceiling
     :-     Halve
       _    A variable ≡ STDIN
          --Other entries--
    {       Block
      !     Boolean NOT
        _   Implied; last entry
    }       End block
  ->        To final length of
    _       Implied
]           End sequence; implied

```

I am pretty sure this can be golfed further, but I'm leaving it here for now.
> 0 votes

# Answer
# Husk, 13 bytes

```
Ṡ:o`-100Σt↑İ¬

```

Try it online!
> 0 votes

---
Tags: code-golf
---


title: N-Dimensional Cartesian Product

text:
# Question
Title: N-Dimensional Cartesian Product
# Introduction

The Cartesian product of two lists is calculated by iterating over every element in the first and second list and outputting points. This is not a very good definition, so here are some examples: the Cartesian product of `[1, 2]` and `[3, 4]` is `[(1, 3), (1, 4), (2, 3), (2, 4)]`. The product of `[1]` and `[2]` is `[(1, 2)]`. However, no one said you could only use two lists. The product of `[1, 2]`, `[3, 4]`, and `[5, 6]` is `[(1, 3, 5), (1, 4, 5), (1, 3, 6), (1, 4, 6), (2, 3, 5), (2, 4, 5), (2, 3, 6), (2, 4, 6)]`.

# Challenge

Given a number of lists, your program must output the Cartesian product of the lists given.

* You can assume that there will always be more than 1 list, and that each list will have the same length. No list will ever be empty. If your language has no method of stdin, you may take input from command line arguments or a variable.
* Your program must output the Cartesian product of all the input lists. If your language has no stdout, you may store output in a variable or as a return value. The output should be a list of lists, or any other iterable type.

# Example I/O

> Input: `[1, 2] [3, 4]`
> Output: `[(1, 3), (1, 4), (2, 3), (2, 4)]`
>
> Input: `[1, 2] [3, 4] [5, 6]`
> Output: `[(1, 3, 5), (1, 4, 5), (1, 3, 6), (1, 4, 6), (2, 3, 5), (2, 4, 5), (2, 3, 6), (2, 4, 6)]`
>
> Input: `[1, 2, 3] [4, 5, 6]`
> Output: `[(1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6)]`

# Rules

This is so shortest answer in bytes wins!

# Answer
# , 1 byte

Courtesy of ngn

```
{

```

Try it online!

'tis called Catalogue
> 12 votes

# Answer
# Haskell, 7 bytes

```
mapM id

```

Try it online!

## Built-in, 8 bytes

```
sequence

```

Try it online!

## Less boring, 33 bytes

Out-golfed by xnor's answer. Go upvote that instead!

```
f[]=[[]]
f(h:t)=[i:j|i<-h,j<-f t]

```

Try it online!
> 10 votes

# Answer
# Haskell, 23 bytes

```
foldr((<*>).map(:))[[]]

```

Try it online!

Without using `mapM` or `sequence` or the like.
> 7 votes

# Answer
# Python 3, 56 bytes

```
def f(M,*l):M and[f(M[1:],*l,x)for x in M[0]]or print(l)

```

Try it online!

No itertools. This is one of those weird functions that prints. Thanks to Unrelated String for -2 bytes with `def`.
> 6 votes

# Answer
# Japt `-R`, 2 bytes

A simple reduction by Cartesian product.

Try it
> 5 votes

# Answer
# Python 2, ~~60~~ 59 bytes

```
f=lambda A,*x:[[v]+u for v in A for u in x and f(*x)or[[]]]

```

Try it online!

1 byte thx to ovs.

Look Ma! No `itertools`!
> 5 votes

# Answer
# Jelly, ~~4~~ 2 bytes

```
Œp

```

Try it online!

Output is "pretty printed" in the TIO link
> 4 votes

# Answer
# Brachylog, 1 byte

Try it online!

A slightly less boring generator solution:

# Brachylog, 2 bytes

```
∋ᵐ

```

Try it online!
> 4 votes

# Answer
# K (oK), ~~31~~ 15 bytes

```
{x@'/:+!(#:)'x}

```

Try it online!
> 4 votes

# Answer
# Perl 6, ~~8~~ 4 bytes

```
&[X]

```

Try it online!

Simple reduce by cross product. ~~It would be nice if I could return the meta-operator by itself, but I've never figured out how to do that.~~ Turns out it works for cross product?
> 4 votes

# Answer
# Ruby, 20 bytes

```
->i,*j{i.product *j}

```

Try it online!
> 3 votes

# Answer
# Retina, ~~54~~ ~~39~~ 32 bytes

This took really long to write (as I tried to golf it too) (unsurprisingly, all the golfing ideas only appeared after I finally posted this). Takes input as a list of strings of alphanumeric characters and underscores (whatever `\w` matches in your universe), each preceded by a semicolon (I assume characters are as acceptable in Retina as numbers are in everything else; in fact, the challenge never actually specified numbers). Outputs the list of the resulting strings, each preceded by a comma.

```
^
,
+w`,(\w*)[^;]*;\w*(\w)
,$1$2

```

Explanation:

```
^                       match the beginning of the string
,                       add a comma there
+w`,(\w*)[^;]*;\w*(\w)  solve the rest of the problem
,$1$2                   replace with a comma, group 1 and group 2

```

The third and fourth lines are in a convergence loop (run until no change) (declared by the `+`). The regular expression in the 3rd line works on lines like `, ac, bc, ad, bd;ef;gh` and matches all substrings starting at a comma and ending at a character after the first semicolon, where the group 1 is the string after the comma and group 2 is the last character.

Try it online!
> 3 votes

# Answer
# , ~~54~~ 47 bytes

```
f=function(x)split(j<-expand.grid(x),1:nrow(j))

```

Try it online!

If you consider data.frame rows iterable:

# , 27 bytes

```
f=function(x)expand.grid(x)

```

Try it online!
> 3 votes

# Answer
# Python 3 (Cython), ~~46~~ ~~44~~ 31 bytes

```
__import__('itertools').product

```

Try it online!

This doesn't need more explanation, right?

(-13 bytes thanks to Jo King; -2 bytes thanks to caird coinheringaahing)
> 3 votes

# Answer
# Wolfram Language (Mathematica), 6 bytes

```
Tuples

```

Try it online!
> 3 votes

# Answer
## Julia 1.0, 34 bytes

No imports used, iterators in Base has this. It actually makes a lazy form of this, but to print them all it will collect each one.

```
println.(Iterators.product(l...))

```

where l is the list of lists.
> 2 votes

# Answer
# Zsh, 30 bytes

```
for l;a=($^a\ ${^${=l}})
<<<$a

```

Try it online!

Split `=` and cartesian product `^` for each element. Our base case adds an extra space, which cleanly separates our output lists.
> 2 votes

# Answer
# 05AB1E, 3 bytes

```
.»â

```

Outputs `[[a,b],[c,d],[d,e]]` in the format `[[[a,c],d], [[a,c],e], ...]`. To output in the format `[[a,[c,d]], [a,[c,e]], ...]`, replace the `»` with `«`.

Try it online or try it online with right- instead of left-reduce.

**Explanation:**

```
.»   # (Left-)reduce by (or right-reduce with `.«`):
  â  #  Taking the cartesian product of the two lists
     # (after which the resulting list is output implicitly)

```
> 2 votes

# Answer
# Husk, 1 byte

```
Π

```

Try it online! `Π` takes the Cartesian product of a list of lists.
> 2 votes

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

Returns a list of lists.

```
f=([a,...b],o=[])=>a?a.flatMap(x=>f(b,[...o,x])):[o]

```

Try it online!

---

# JavaScript (V8), 52 bytes

Prints the results.

```
f=([a,...b],o)=>a?a.map(x=>f(b,o?o+[,x]:x)):print(o)

```

Try it online!
> 1 votes

# Answer
# Erlang, 57 bytes

```
c([]) -> [[]];
c([H|T]) -> [[X|Y] || X <- H, Y <- c(T)].

```
> 1 votes

# Answer
# Japt, 2 bytes

Try it

```
Reduces input by combination with initial value of 1st element

```

Duplicate of @Shaggy answer, I was solving this while he just posted the same solution. I hope I can leave my answer too because it's awesome
> 1 votes

# Answer
# Charcoal, 22 bytes

```
ＩＥΠＥθＬιＥθ§λ÷ιΠ∨Ｅ…θμＬν¹

```

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

```
    θ                   Input list
   Ｅ                    Map over elements
      ι                 Current element
     Ｌ                  Length
  Π                     Product
 Ｅ                      Map over implicit range
        θ               Input list
       Ｅ                Map over elements
          λ             Current element
         §              Cyclically indexed by
            ι           Outer index
           ÷            Integer divide
                 θ      Input list
                …       Truncated to length
                  μ     Inner index
               Ｅ        Map over elements
                    ν   Current element
                   Ｌ    Length
              ∨      ¹  Replace empty list with literal 1
             Π          Product
Ｉ                       Cast to string
                        Implicitly print double-spaced on separate lines

```
> 1 votes

# Answer
# APL(NARS), chars 11, bytes 22

```
{,↑(∘.,)/⍵}

```

test for product of sets:

```
  f←{,↑(∘.,)/⍵}
  ⎕fmt (1 2)(3 4)
┌2────────────┐
│┌2───┐ ┌2───┐│
││ 1 2│ │ 3 4││
│└~───┘ └~───┘2
└∊────────────┘
  ⎕fmt f (1 2)(3 4)
┌4──────────────────────────┐
│┌2───┐ ┌2───┐ ┌2───┐ ┌2───┐│
││ 1 3│ │ 1 4│ │ 2 3│ │ 2 4││
│└~───┘ └~───┘ └~───┘ └~───┘2
└∊──────────────────────────┘
  ⎕fmt f (1 2)(3 4)(5 6)
┌8──────────────────────────────────────────────────────────────────────┐
│┌3─────┐ ┌3─────┐ ┌3─────┐ ┌3─────┐ ┌3─────┐ ┌3─────┐ ┌3─────┐ ┌3─────┐│
││ 1 3 5│ │ 1 3 6│ │ 1 4 5│ │ 1 4 6│ │ 2 3 5│ │ 2 3 6│ │ 2 4 5│ │ 2 4 6││
│└~─────┘ └~─────┘ └~─────┘ └~─────┘ └~─────┘ └~─────┘ └~─────┘ └~─────┘2
└∊──────────────────────────────────────────────────────────────────────┘
  ≢f (1 2)(3 4)(5 6)
8
  f (⍳3)(4 5 6)
 1 4  1 5  1 6  2 4  2 5  2 6  3 4  3 5  3 6

  ⎕fmt f (4 5 6)
┌1───────┐
│┌3─────┐│
││ 4 5 6││
│└~─────┘2
└∊───────┘

```
> 1 votes

# Answer
# Python 3.8, 136 bytes

```
import re
from itertools import*
print(list(product(*[[int(i) for i in i.split(', ')] for i in re.findall(r'\[([0-9, ]+)\]',input())])))

```

Try it online!
> -1 votes

---
Tags: code-golf, math, sequence, set-theory
---


# Question
Title: Day of Week - Natural language processing and date parsing
You'll get a human-readable question *matching one of the following syntaxes*, and are expected to print/return the corresponding result. Finding similarities between the human-readable inputs and matching them with minimum size code is explicitly part of the task, so I won't give a formal definition.

* "Will October begin on a Thursday if this year is a leap year, this month is January and this month begins on a Wednesday?" \> **"Yes."**
* "If this month begins on a Friday, this month is October and this year is not a leap year, will December start on a Tuesday?" \> **"No, it will be a Wednesday."**
* "If this month is August, this month begins on a Wednesday and this year is not a leap year, will October start on a Sunday?" \> **"No, it will be a Monday."**
* "Will December start on a Monday if this month begins on a Friday, this year is a leap year and this month is November?" \> **"No, it will be a Sunday."**

**"Formal" definition:**

Input will always be generated by picking one of the above lines and swapping day names, month names, and the "not " in and out of "is \*a leap year"

**Further notes:**

* Each question will consider only one calendar year, i.e. you won't be asked for a date of the following or previous calendar year.
* This is **codegolf**, shortest answer in bytes in each language wins.
* In case you need it, remember leaps years are *not* strictly every 4 years.
* No answer will be accepted.
* Standard loopholes apply.
* You can input and output in any reasonable way.

**Just for reference:**

* 'January', 'February','March','April', 'May','June','July','August', 'September','October','November','December'
* 'Monday','Tuesday', 'Wednesday','Thursday', 'Friday','Saturday', 'Sunday'

Inspired by Squarish's Kata on codewars.com

# Answer
> 11 votes
# JavaScript (ES6), 254 bytes

```
s=>(F=e=>'0x'+'0A39135?2B?8602467'[parseInt(s.match(e+' ([A-Z]\\w+)')[1],33)%234%81%19],n=(F`s.{5}`-(g=m=>new Date(~F`(no|le).*`,m).getDay())(F`s`)+g(F`l`)+7)%7)-F` .{9}a`?`No, it will be a ${'Sun,Mon,Tues,Wednes,Thurs,Fri,Satur'.split`,`[n]}day.`:`Yes.`

```

Try it online!

### How?

Given the leading part `e` of a regular expression, the helper function `F` looks for the capitalized word that immediately follows and turns it into either a 0-indexed day (from 0 = Sunday to 6 = Saturday) or a 0-indexed month (from 0 = January to 11 = December).

```
F = e =>                // e = regular expression part, as a string
  '0x' +                // parse as hexadecimal
  '0A39135?2B?8602467'[ // a digit between '0' and 'B'
    parseInt(           //   selected by 1) parsing
      s.match(          //     the sub-string in s that matches
        e +             //       the leading part of the regular expression
        ' ' +           //       followed by a space
        '([A-Z]\\w+)'   //       followed by a capturing group for
      )[1],             //       a capitalized word (which is what we keep)
      33                //     in base 33
    )                   //   end of parseInt()
    % 234 % 81 % 19     //   and 2) applying a modulo chain
  ]                     // end of digit lookup

```

Try the hash function online!

We invoke `F` with:

* `"s.{5}"` to match `"begin**s on a [day]**"`
* `"s"` to match `"i**s [month]**"`
* `"l"` to match `"wil**l [month]**"` (the `w` may also be capitalized)
* `" .{9}a"` to match either `" **start on a [day]**"` or `" **begin on a [day]**"`
* `"(no|le).*"` to match either `"**no**t"` or `**"le**ap"`, whichever comes first (this is a special case where the capitalized word is put in a 2nd capturing group and ignored)

The helper function `g` takes a month and returns a week day in `[0..6]`:

```
g = m => new Date(~F`(no|le).*`, m).getDay()

```

The expression `~F`(no|le).*`` in there evaluates to `-1` if `"no"` is matched (not leap) or to `-4` if `"le"` is matched (leap). This works as expected because the year `-4` is leap1 and the year `-1` is not.

Using `g` and the data collected above, we create two dates in the same reference year and look for the difference between the corresponding week days, modulo 7. This allows us to answer the question.

---

*1: At least that's what JS thinks. But this is apparently not true.*

# Answer
> 5 votes
# Retina 0.8.2, 292 bytes

```
no.*
$&~
Feb(?=.*~)|Mar|N|Sa
4
F|Au
3
Ma|Th
2
O|We
1
A|Jul|T
0
Se|D|M
6
Ju|S
5
J(?=.*(~))?
$#1
(.+)(w.+)
$2$1
( is \d)(.+)
$2$1
.+(\d).+(\d).+(\d).+(\d).*
$2;$2$4,777$1$3
\d
$*
(1*),\1

1*;(1{7})+$
Yes.
;

(1{7})+(1*)
No, it will be a $.2day.
6
Mon
5
Sun
4
Satur
3
Fri
2
Thurs
1
Wednes
0
Tues

```

Try it online! Link includes test cases. Explanation:

```
no.*
$&~

```

If this is no(t) a leap year, then suffix a `~`, so that we can adjust the relative offsets of January and February.

```
Feb(?=.*~)|Mar|N|Sa
4

```

The relative offset of February, when not in a leap year, is the same as March and November.

```
F|Au
3

```

But in a leap year, it's the same as August. And with my arbitrary numbering convention based on Tuesday, it's also the relative offset of Friday.

```
Ma|Th
2
O|We
1
A|Jul|T
0
Se|D|M
6
Ju|S
5

```

Similarly for the remaining months and days of the week.

```
J(?=.*(~))?
$#1

```

January's offset is simply the count of `~`s.

```
(.+)(w.+)
$2$1

```

If the `will (Month) start on (Day)` is not at the beginning, then move it there.

```
( is \d)(.+)
$2$1

```

If the `month is (Month)` is not at the end, then move it there. This means that the order is now (target month offset), (target day offset), (source day offset), (source month offset).

```
.+(\d).+(\d).+(\d).+(\d).*
$2;$2$4,777$1$3

```

Form the values (target day offset); (target day offset) + (source month offset), 11 + (target month offset) + (source day offset). The 21 ensures that the difference is at least 7.

```
\d
$*
(1*),\1

```

Convert the values to unary so that the difference between the sums of offsets can be taken.

```
1*;(1{7})+$
Yes.

```

If the difference is zero (modulo 7), then the offsets matched, so that the target day is correct.

```
;

```

Add the difference to the target day offset to get the correct day offset.

```
(1{7})+(1*)
No, it will be a $.2day.

```

Convert the day offset (modulo 7) back to decimal.

```
6
Mon
5
Sun
4
Satur
3
Fri
2
Thurs
1
Wednes
0
Tues

```

Decode it into a day of the week.

# Answer
> 1 votes
# CJam, ~~331~~ ~~318~~ ~~316~~ ~~289~~ 290 bytes

*-13 bytes by having the weekday function spit out a string which can be compared directly to the natural-language word given.*

*-2 bytes by removing a -2 offset in weekday calculation.*

*-27 bytes with an alternate method of converting a month name to a number from 1 to 12.*

*+1 byte to correct a typo.*

```
l);" and if"4/{/',*}/',/{S/(;}/_0='w#{]:\}&[)\-4={A="bMAanlseovc"#))}:R~]])\{_-2=0="lia"#"3=c'a=W=R:M;W=:O;"6/=~}/:L;[M0]{))+_{[~_2$3<_!-2*@@- 4/_25/_4/\W*](23*9/+:+7%"Fri Satur Sun Mon Tues Wednes Thurs"S/="day"+}:T~\_1=1e2md_4%!\!@4%!*-L=@O=*!}g)@(\@+T_@="Yes"@"No, it will be a "\+?\;'.+

```

Try it online!

Oh boy. This was a doozy.

Quick write-up:

```
l);                    e# Read input, and remove question mark.
" and if"4/{/',*}/',/  e# Replace " and" and " if" with commas, then split into clauses.
{S/(;}/                e# Split each clause into words, and remove the first "word".
                       e# (It will be "If" or "Will" if they are capitalized, empty otherwise.)
_0='w#                 e# If "w" is not the last clause's first word's first character...
{]:\}&                 e# ...the "will" clause is not on top; bring it to the top.
[                      e# We will parse its month and weekday, and put them in an array.
)                      e# Raw weekday string from input.
\-4={A="bMAanlseovc"#))}:R~  e# Month to number by looking up the character "at" index 10.
                       e# (If month name is less than 11 chars, the index wraps around.)
]                      e# Now we've collected these into an array.
])\                    e# Collect clauses in array and bring to top.
{_-2=0="lia"#          e# Use the first character of the second-to-last word in the clause...
"3=c'a=W=R:M;W=:O;"6/  e# ...to index into one of three pieces of 6(-ish)-character code...
=~}/                   e# ...to run on each clause to extract the relevant information.
:L;                    e# Now O has the weekday, M the month, and L the leap-year status.
[M0]{                  e# We'll use M to get the first year that matches the criteria.
))+_                   e# Increment the year, and put it back in the array.
{[~_2$3<_!-2*@@- 4/_25/_4/\W*](23*9/+:+7%"Fri Satur Sun Mon Tues Wednes Thurs"S/="day"+}:T~  e# Weekday of day 1, given [month year].
                       e# (Algorithm adapted from http://cadaeic.net/calendar.htm)
\_1=1e2md_4%!\!@4%!*-  e# Check if year is leap year.
L=@O=*!}g              e# Run this loop until leap-year and weekday criteria match the year.
)@(\@+T                e# Get weekday of requested month with calculated year...
_@=                    e# ...then compare it with requested weekday.
"Yes"@"No, it will be a "\+?\;'.+  e# Choose the right string based on the weekday.

```

### Alternate 290-byter

This works in almost the same way, except it uses a LUT to determine the month offset in the weekday calculation, instead of math.

```
l);" and if"4/{/',*}/',/{S/(;}/_0='w#{]:\}&[)\-4={A="bMAanlseovc"#}:R~]])\{_-2=0="lia"#"3=c'a=W=R:M;W=:O;"6/=~}/:L;[M0]{))+_{[~_2$1<- 4/_25/_4/\W*](2457931901 7b=+:+7%"Fri Satur Sun Mon Tues Wednes Thurs"S/="day"+}:T~\_1=1e2md_4%!\!@4%!*-L=@O=*!}g)@(\@+T_@="Yes"@"No, it will be a "\+?\;'.+

```

Try it online!

### Random snippets

Some fun little snippets to experiment with on your own:

`[~_2$3<_!-2*@@- 4/_25/_4/\W*](23*9/+:+7%` \- takes `[month year]` on stack, returns weekday with Friday=0 to Thursday=6

`1e2md_4%!\!@4%!*-` \- takes `year` on stack, if result is nonzero then that is a leap year

`60b73%W*7,=` \- takes capitalized weekday string on stack, returns index into week with Wednesday=0 to Tuesday=6

`134b395%7%` \- same as above, but with Tuesday=0 to Monday=6

`75b501%8%` \- same as above, but with Saturday=0 to Friday=6

`4b502%9%` \- same as above, but with Sunday=0 to Saturday=6

`A="bMAanlseovc"#` \- takes `month` on stack, returns month number with January=-1 to December=10

---
Tags: code-golf, string, parsing, natural-language
---


# Question
Title: Draw a times table (also called modular multiplication circle) of a number \$n\$ with \$k\$ vertices
Not to be confused with this question.

You need to draw a times table (also known as Cremona's method for cardioid generation) as shown in this video. The number \\$n\\$ and \\$k\\$ will be the inputs.

**In the video n and k are 2 and 10 respectively.**

---

### How to draw?

1. Draw a circle, divide its perimeter into equal spaced parts with \\$k\\$ points and number them with \\$0, 1, 2, \dots, k-1\\$ .
2. Draw \\$k\\$ line segments between \\$i\\$ and \\$i\times n \mod k\\$ for all integers \\$i\\$, \\$0 \le i \< k\\$.

---

You can use any graphing library that your language allows.

Remember this is a so keep the answer short and sweet.

---

### Examples

```
Input : n = 2 and k = 27

```

```
Input : n = 5 and k = 10

```

You can also play around with it here. The modulus/points is \\$k\\$ while multiplication factor is \\$n\\$.

---

### Challenge

You need to draw at least the circle and the lines.

You can output any file format (svg, png, jpeg) and HTML rendering is also allowed.

You can also write the image to STDOUT

---

Best of luck because you are going to need it!

# Answer
> 3 votes
# Python 2 with pylab, ~~133~~ 129 bytes

```
from pylab import*
n,k=input()
gca().add_patch(Circle((0,0),1))
a=2*pi/n
for i in range(n):c=i*a,k*i*a;plot(cos(c),sin(c))
show()

```

Saved 4 bytes thanks to Mr. Xcoder.

# Answer
> 4 votes
# Python 2, ~~280~~ ~~241~~ ~~235~~ 233 bytes

```
from math import*
n,k=input()
a=2*pi/k
s='<svg viewBox="-49 -49 98 98"><circle r="49"/><path d="'
p=0;exec"s+='M%f,%f L%f,%f '%(49*cos(p),49*sin(p),49*cos(p*n),49*sin(p*n));p+=a;"*k
open('c.svg','w').write(s+'" stroke="red"/></svg>')

```

Try it online!

Saved 35 bytes due to removing `xmlns` attribute at the encouragement of qwr; and 4 more since `%k` was not required. 4 more by using `exec` instead of `for i in range(k)`.

Writes an SVG file named `c.svg`. Look, ma! No graphics library! :)

# Answer
> 3 votes
## JavaScript (ES6), ~~207~~ 206 bytes

```
with(Math)f=(k,n,g=i=>[cos(i*=PI*2/k),sin(i)])=>`<svg viewBox=-1,-1,2.01,2.01><circle r=1 fill=none${s=` stroke=#000 stroke-width=.01 `}/><path d=M${[...Array(k)].map((_,i)=>g(i)+`L`+g(i*n)).join`M`}${s}/>`
;o.innerHTML=f(27,2)
```

```
<div oninput=o.innerHTML=f(+k.value,+n.value)><input type=number min=2 value=27 id=k><input type=number min=2 value=2 id=n><div id=o>
```

Output of the function is an HTML5-compatible SVG snippet. The function itself is the first line of the snippet, the rest of the snippet merely serves to demonstrate the function. Edit: Saved 1 byte thanks to @Arnauld.

# Answer
> 3 votes
# , 160 bytes

```
function(n,k,C=cospi,S=sinpi){par(pty="s")
plot(S(z<-0:2e4/1e4),C(z),'l',xaxt='n',yaxt='n',an=F,ax=F,xla="",yla="")
a=2/k*1:k
segments(C(a),S(a),C(a*n),S(a*n))}

```

Try it online!

... or play with it if you want (change the code and press execute)

* -2 bytes thanks to @JayCE

Here's the appearance :

# Answer
> 2 votes
## Javascript 146 bytes + HTML 113 + Js Library cardioidjs = 259 bytes

Note: I dont think this is allowed but acording to OP

> You can use any graphing library that your language allows.

Program ask for `k` and `n` and uses the lib to create the table

```
_=document.getElementById('a');l=prompt;c=new Cardioid(_,{iterations:1000,pieces: (t=l("k"))%2?t-1:+t,fun1:l("n"),initialRotation: 180});c.draw()
```

```
<script src="https://mircot.github.io/js/cardioid.js"></script>
<canvas id="a" width="500" height="500"></canvas>
```

# Answer
> 2 votes
# Python 3 + `turtle`, ~~126~~ 118 bytes

Just learn about `clone`. This version creates a turtle for each line drawn, so it clutters the screen a bit. Calling `ht()` will help.

```
from turtle import*
n,k=eval(input())
a=clone()
exec('a.circle(99,360*n/k);circle(99,360/k);clone().goto(a.pos());'*k)

```

A direct port of my LOGO solution. However Python multi-turtle support is a bit different (they're named, not numbered), so turtle 0 in LOGO solution is the default turtle, and turtle 1 is `a`.

`[*map(goto,[a.pos(),pos()])]` is exactly 1 byte shorter than `p=pos();goto(a.pos());goto(p)`, and obviously much less readable...

---

This exits immediately after the drawing is done. To prevent that, adds `done()` at the end.

Because the drawing may be too slow, add `speed(0)` at the beginning (after the `import` statement)

I don't have Python 2 installed, but this (111 bytes) should work.

# Answer
> 2 votes
# Desmos, 58 bytes

```
r=1
p=[0,...,k-1]2\pi/k
s=-cot(p/2+mod(np,k)/2)
sx+sinp-scosp

```

View it on Desmos, includes other functions for better visualization

Had more golfability than most Desmos answers, fun to work on. Note: since the link in the submission is broken, you can use this as an interactive tool to play around with them now!

Explanation:

```
r=1                       Draw circle
p=[0,...,k-1]2\pi/k       Generate list of angles (note: switching to degrees sould save a byte here, but we can't do that as it's not possible through code alone)
s=-cot(p/2+mod(np,k)/2)   Calculate slope of the line for each angle pair
sx+sinp-scosp             Draw the lines

```

# Answer
> 1 votes
# FMSLogo, ~~80~~ 77 bytes

```
[repeat ?[arc2 360/? 99 foreach list ask 1[arc2 360/?*?2 99 pos]pos "setpos]]

```

### Usage

This is an explicit-slot template, which can be used by typing, for example

```
apply [...] [54 2]

```

into the Logo prompt, replacing `[...]` with the program above.

It can be used to draw the circle anywhere on the screen, but the radius is hardcoded (99).

To clear the screen use `cs`.

### Images

(FMSLogo also has a convenient command `bitcopy` for copying to clipboard. Example run:

```
pu bk 100 bitcopy 200 200 home pd

```

)

# Answer
> 1 votes
# Excel VBA, 167 bytes

An immediate window function that takes input and output onto the `Sheet1` object.

```
Set s=Sheet1.Shapes:s.AddShape(9,0,0,1E2,1E2).ShapeStyle=7:f=50:c=[2*Pi()/B1]:For i=0To[B1]:j=i*[A1]:s.AddLine f+f*Cos(c*i),f+f*Sin(c*i),f+f*Cos(c*j),f+f*Sin(c*j):Next

```

### Ungolfed and Commented

```
Set s=Sheet1.Shapes                                             ''  On the Sheet1 Object
s.AddShape(9,0,0,1E2,1E2).ShapeStyle=7                          ''  Add a blue circle
f=50                                                            ''  Hold var as 50
c=[2*Pi()/B1]                                                   ''  Calc Rads Splitting circle into k slices
For i=0To[B1]                                                   ''  Iterate from 0 to k
j=i*[A1]                                                        ''  Calculate Next Point
s.AddLine f+f*Cos(c*i),f+f*Sin(c*i),f+f*Cos(c*j),f+f*Sin(c*j)   ''  Draw a line from i to i*n Mod k
Next                                                            ''  Loop

```

### Output

# Answer
> 1 votes
# Small Basic, 218 bytes

A Script that takes input from the `TextWindow` and outputs to the `GraphicsWindow` Object

```
n=TextWindow.Read()
k=TextWindow.Read()
GraphicsWindow.DrawEllipse(0,0,100,100)
f=50
c=2*Math.Pi/k
For i=0To k
GraphicsWindow.DrawLine(f+f*Math.Cos(c*i),f+f*Math.Sin(c*i),f+f*Math.Cos(c*i*n),f+f*Math.Sin(c*i*n))
EndFor

```

Try it at SmallBasic.com! *Requires IE/Silverlight*

### Output

Input `3`,`24`

# Answer
> 1 votes
# Lua (love2d Framework),281 bytes

```
j,p,z,w,v=love,math,100,200,90 g,r=j.graphics,p.rad c=g.circle function j.load(b)n,k=b[1],b[2]m= 360/k::t::a=function(i)return z*p.sin(r(m*i +v))+w,z*p.cos(r(m*i+v))+w end c("line",w,w,z)for i=1,k do x,y=a(i)c("fill",x,y,3)l=(i*n)%k d,e=a(l)g.line(x,y,d,e)end g.present()goto t end

```

If this is copied in a main.lua file and run it will show it on screen

output for n=2,k=22

also beware if you run it, that it will probably tell you that it is frozen because it is in an endless draw function in the load function but it will show it on the screen.

Also here is a clean version

```
--definitions of everything
j,p,z,w,v=love,math,100,200,90
g,r=j.graphics,p.rad c=g.circle
function j.load(b)
  --get the parameters
  n,k=b[1],b[2]
  m= 360/k
  --goto label
  ::t::
  --function which takes a point number as input and outputs the x,y adds also 90 to it because why ever love starts
   a=function(i)return z*p.sin(r(m*i +v))+w,z*p.cos(r(m*i+v))+w end
   --draw the circle
   c("line",w,w,z)
   for i=1,k do
     --get point position and draw it
     x,y=a(i)
     c("fill",x,y,3)
     --calculate and print the line to the other point
     l=(i*n)%k
     d,e=a(l)
     g.line(x,y,d,e)
   end
   --show it on screen
   g.present()
   goto t
end

```

If someone also wants to play around with it here a version which you can change the n with up and down and the k with left and right arrows :)

```
--definitions of everything
j,p,z,w,v=love,math,100,200,90
g,r=j.graphics,p.rad c=g.circle
function j.load(b)
  --get the parameters
  n,k=b[1],b[2]

end

function u(n,k)
--function which takes a point number as input and outputs the x,y adds also 90 to it because why ever love starts
   a=function(i)return z*p.sin(r(m*i +v))+w,z*p.cos(r(m*i+v))+w end
   --draw the circle
   m= 360/k

   c("line",w,w,z)
   for i=1,k do
     --get point position and draw it
     x,y=a(i)
     c("fill",x,y,3)
     --calculate and print the line to the other point
     l=(i*n)%k
     d,e=a(l)
     g.line(x,y,d,e)
   end
end

function j.draw()
  --n=n+0.001
  --k=k+0.01
  u(n,k)
  love.graphics.print("n: "..n.."\nk: "..k,0,0)
end

function j.keypressed(ke,s)
  k=k*1
  if ke== "up"then
    n=n+1
  elseif ke=="down" then
    if n >1 then n=n-1 end
  elseif ke=="right" then
    k=k+1
  elseif ke=="left" then
    if k>1 then
      k=k-1
    end
  end

end

```

# Answer
> 1 votes
# APL (dzaima/APL), 57 bytes

*No MATL answer here yet! yay!*

```
{n←⍺⋄P5.G.circle 3⍴30⋄{P5.G.ln↑30×1+2 1○ᑈ1n×⍵×○2÷k}¨⍳k←⍵}

```

Made with help from dzaima.

Draws a 30x30 circle with the times table for `n` and `k`.

Function submission which takes arguments as `n f k`, and will display properly on a default sized canvas.

This uses the formula from user58543's answer.

You can test this out using this file and dzaima's APLP5 engine.

## Explanation:

```
{n←⍺⋄P5.G.circle 3⍴30⋄{P5.G.ln↑30×1+2 1○ᑈ1n×⍵×○2÷k}¨⍳k←⍵}
{n←⍺⋄                                                   k←⍵} store left arg in n and right arg in k
      P5.G.circle 3⍴30⋄                                      Draw circle of radius 30

                                                        ⍳k   generate range 1..k
                       {                              }¨     Execute the following for each number i:
                                            1n×⍵×○2÷k        Multiply [1,n] with i×2π/k
                                      2 1○ᑈ                  Take cos and sin of each of those
                                30×1+                        Multiply 30, add 30 to them
                              ↑                              Convert to matrix
                        P5.G.ln                              Plot a line using those coordinates

```

### Output for `n=5, k=10`:

# Answer
> 1 votes
# MATL, ~~39~~ ~~37~~ ~~35~~ ~~33~~ ~~31~~ 29 bytes

```
:qG/ti*vO9Wt:w/h,18L*ZeXG1IZG

```

Inputs are `k`, then `n`.

Try at **MATL Online**!

## How it works

```
:         % Implicit input: k. Range: [1 2 ... k]
q         % Subtract 1, element-wise: [0 1 ... k-1]
G/        % Push k again; divide element-wise: [0 1/k ...(k-1)/k]
t         % Duplicate
i*        % Input: n. Multiply element-wise: gives [0 n/k ... n*(k-1)/k]
v         % Concatenate vertically: gives 2-row matrix [0 1   ... k-1;
          %                                             0 n/k ... n*(k-1)/k]
O         % Push 0
9W        % Push 9; exponential with base 2: gives 512
t         % Duplicate
:         % Range: gives [1 2 ... 512]
w         % Swap: moves copy of 512 to top
/         % Divide, element-wise: gives [1/512 2/512 ... 1]
h         % Concatenate: gives [0 1/512 2/512 ... 1]
,         % Do the following twice
  18L     %   Push 2*pi*j (predefined literal)
  *       %   Multiply, element-wise
  Ze      %   Exponential with base e, element-wise. Each imaginary number
          %   becomes a point in the unit circle
  XG      %   Plot. Since the input is complex, this plots in the complex
          %   plane. The first time this plots the 2-row matrix defining the
          %   lines, with each column of the matrix plotted separately. The
          %   second time it plots the 512-vector with points in the circle
  1IZG    %   Hold on. This causes the next plot to be added, instead of
          %   overwriting the previous one

```

# Answer
> 0 votes
# Small Basic \+ Turtle, 390 bytes

A Script that takes input from the `TextWindow` and outputs to the `GraphicsWindow` Object

```
n=TextWindow.Read()
k=TextWindow.Read()
For i=0To 360
Turtle.Angle=i
Turtle.Move(2.618)
EndFor
r=150
c=2*Math.Pi/k
For i=0To k
Turtle.PenUp()
Turtle.MoveTo(470+r*Math.Cos(c*i),240+r*Math.Sin(c*i))
Turtle.PenDown()
Turtle.MoveTo(470+r*Math.Cos(c*i*n),240+r*Math.Sin(c*i*n))
EndFor
GraphicsWindow.DrawLine(f+f*Math.Cos(c*i),f+f*Math.Sin(c*i),f+f*Math.Cos(c*i*n),f+f*Math.Sin(c*i*n))
EndFor

```

Try it at SmallBasic.com! *Requires IE/Silverlight*

### Ungolfed and Commented

```
n=TextWindow.Read()                                         ''  Take Input, n
k=TextWindow.Read()                                         ''  Take Input, k
For i=0To 360                                               ''  Draw a Circle of Radius 150
  Turtle.Angle=i                                            ''  By turning 1 degree
  Turtle.Move(2.618)                                        ''  And moving Pi*300/360 Units
EndFor                                                      ''  360 times
r=150                                                       ''  Hold Radius variable
c=2*Math.Pi/k                                               ''  Hold Rad Constant
For i=0To k                                                 ''  Iterate over i
  Turtle.PenUp()                                            ''  Stop Drawing
  Turtle.MoveTo(470+r*Math.Cos(c*i),240+r*Math.Sin(c*i))    ''  Move to Position i
  Turtle.PenDown()                                          ''  Start Drawing again
  Turtle.MoveTo(470+r*Math.Cos(c*i*n),240+r*Math.Sin(c*i*n))''  Move to Position (i*n)Mod k
EndFor                                                      ''  Loop

```

### Output

Input `3`,`72`

---
Tags: code-golf, math, graphical-output, geometry
---


title: Collapsing Matrices

text:
# Question
Title: Collapsing Matrices
*Related: Let's design a digit mosaic, Print/Output the L-phabet. Sandbox post here*

Given 2 inputs `C = columns and rows, S = starting point` output a matrix as follow:

```
Input 4, 3

1   2   3   0
2   2   3   0
3   3   3   0
0   0   0   0

```

**Explanation**

**Given** `C = 4, S = 3`

1) Create a `C x C` matrix filled with `0`

```
         4 columns
4     _____|____
     |          |
r  --0  0   0   0
o |  0  0   0   0
w |  0  0   0   0
s  --0  0   0   0

```

2) Fill with `S` values within row and column `S`, then subtract 1 from `S` and repeat until `S = 0`. This case `S = 3`

```
             Column 3
S = 3           |
                v
        0   0   3   0
        0   0   3   0
Row 3-->3   3   3   0
        0   0   0   0

         Column 2
S = 2       |
            v
        0   2   3   0
Row 2-->2   2   3   0
        3   3   3   0
        0   0   0   0

     Column 1
S=1     |
        v
Row 1-->1   2   3   0
        2   2   3   0
        3   3   3   0
        0   0   0   0

Final Result

1   2   3   0
2   2   3   0
3   3   3   0
0   0   0   0

```

---

**Rules**

* Assume `C >= S >= 0`
* The output can be a matrix, list of lists, array (1-dimensional or 2-dimensional) etc.
* You can take inputs via any default I/O format
* Your program, function, etc... may be 1-indexing or 0-indexing. Please specify which one is.

**Note** Explanation is 1-indexing

---

Winning criteria

# Answer
# ,  ~~47~~ 41 bytes

```
function(C,S,m=outer(1:C,1:C,pmax))m*!m>S

```

Try it online!

1-indexed. Generates the outputs for `S==C` (no zeros) then zeroes cells which have a value `>S` using matrix multiplication (thanks Giuseppe for 4 bytes!).
> 6 votes

# Answer
# Jelly, 8 bytes

```
»>⁴¬×»µþ

```

Try it online!

## How it works

**Jelly's Outer Product Atom (`þ`)**

You can think of Jelly's outer product atom, `þ`, as a quick (operator) that, given integer arguments \\$X\\$ and \\$Y\\$ (in this case \\$X=Y=\text{first argument }\\$), produces the following matrix of tuples:

$$\left\[\begin{matrix} (1, 1) & (2, 1) & (3, 1) & \cdots & (X, 1) \\ (1, 2) & (2, 2) & (3, 2) & \cdots & (X, 2) \\ \vdots & \vdots & \vdots & \ddots & \vdots \\ (1, Y) & (2, Y) & (3, Y) & \cdots & (X, Y) \end{matrix}\right\]$$

It also applies the link right before it to all pairs, let's call it \\$\\:f\\$, which behaves like a function which takes two arguments, producing something like this:

$$\left\[\begin{matrix} f(1, 1) & f(2, 1) & f(3, 1) & \cdots & f(X, 1) \\ f(1, 2) & f(2, 2) & f(3, 2) & \cdots & f(X, 2) \\ \vdots & \vdots & \vdots & \ddots & \vdots \\ f(1, Y) & f(2, Y) & f(3, Y) & \cdots & f(X, Y) \end{matrix}\right\]$$

**How is it relevant to the task at hand?**

This works by noticing that every value in the expected output is just a table of maximal indices, or \\$0\\$ if this maximum exceeds our second argument. Therefore, we can create the following link to perform this mapping:

```
»>⁴¬×» – Dyadic (2-argument) link.
»      – Maximum of the X, Y coordinates.
 >⁴    – Check if this exceeds the second argument of the program.
   ¬   – Negate this boolean.
    ×» – And multiply by the maximum, computed again.

```
> 6 votes

# Answer
# Octave, 31 bytes

```
@(C,S)(u=max(t=1:C,t')).*(u<=S)

```

Anonymous function that returns a matrix. Uses 1-based indexing.

Try it online!
> 5 votes

# Answer
# Haskell, ~~47~~ 45 bytes

-2 bytes by changing the output format to one-dimensional list.

```
c&s|x<-[1..c]=[sum[j|j<=s]|j<-x>>=(<$>x).max]

```

Try it online!

## Explanation

The term `x >>= (<$> x) . max` is a golfed version of

```
concat [ max i <$> x | i <- x ]

```

which evaluates to `[1,2,3,4..c, 2,2,3,4..c, 3,3,3,4..c, ..., c,c,c,c..c]`. Now we only need to force the values to `0` once they exceed `s` which we achieve with `sum [ j | j <= s]`.
> 5 votes

# Answer
**APL(Dyalog Classic), 12 bytes**

```
{⍺ ⍺↑∘.⌈⍨⍳⍵}

```

Try it online!

Any tips on turning this into a train are welocome.
> 5 votes

# Answer
# JavaScript (ES6), 61 bytes

Takes input in currying syntax `(c)(s)`, where *s* is 1-indexed. Returns a 1-dimensional array.

```
c=>s=>[...Array(c*c)].map((_,k)=>(k=k%c>k/c?k%c:k/c)<s?-~k:0)

```

Try it online!
> 3 votes

# Answer
# APL (Dyalog), 12 bytes

```
o×⎕≥o←∘.⌈⍨⍳⎕

```

Try it online!
> 3 votes

# Answer
# Jelly, 6 bytes

```
⁴Ri»µþ

```

A full program\* taking integers `C` and `S` which prints the Jelly representation of a list of lists of integers as defined (1-indexed).

**Try it online!** (formats the result of the dyad as a grid of numbers for easier reading)

### How?

```
⁴Ri»µþ - Main Link: C, S
     þ - outer product with:
    µ  -   the monadic function (i.e. f(x,y) for x in [1..C] for y in [1..C]):
   »   -     maximum (of x and y)
⁴      -     program's 4th argument = 2nd input = S
 R     -     range = [1,2,3,...S]
  i    -     first index of (the maximum) in (the range) or 0 if not found
       - as a full program: implicit print

```

---

* The reason this is a full program is down to the use of the program argument access, . As a dyadic link this code would rely on how the program which is using it is called.
Reusable dyadic link in 8 bytes (taking S on the left and C on the right): `RiⱮⱮ»þ`}`
Reusable dyadic link in 8 bytes (taking C on the left and S on the right): `RiⱮⱮ⁹»þ¤`
> 3 votes

# Answer
# Stax, 10 bytes

```
▓╜.→,cΘ○╤æ

```

Run and debug it

How it works:

```
R(Xm]i*xit+J Full program, implicit input.
R            1-based range of S
 (           Right-pad with zeroes to length C
  X          Save to X register
   m         Map (same as here):
    ]          Wrap in list
     i*        repeat by iteration index
       xit     Remove first  elements from X register
          +    Append
           J   Stringify each element, and join by space

```
> 2 votes

# Answer
# Java 10, 88 bytes

```
C->S->{var r=new int[C][C];for(;S>0;)for(int s=S--;s-->0;)r[S][s]=r[s][S]=S+1;return r;}

```

Try it online.

**Explanation:**

```
C->S->{                     // Method with two int parameters and int-matrix return-type
  var r=new int[C][C];      //  Result-matrix of size `C` by `C`
  for(;S>0;)                //  Loop as long as `S` is not 0 yet:
    for(int s=S--;s-->0;)   //   Inner loop `s` in the range (`S`, 0]
                            //   (and decrease `S` by 1 in the process with `S--`)
      r[S][s]=r[s][S]=S+1;  //    Set the values at both {`S`,`s`} and {`s`,`S`} to `S+1`
  return r;}                //  Return the result

```
> 2 votes

# Answer
# PHP, 92 bytes

This is "1-indexing".

```
<?list(,$c,$s)=$argv;for(;$i++<$c;print"\n")for($j=0;$j++<$c;)echo$s<$i||$s<$j?0:max($i,$j);

```

To run it:

```
php -n <filename> <c> <s>

```

Example:

```
php -n collapsing_matrice.php 8 6

```

Or Try it online!
> 2 votes

# Answer
# Excel VBA, 65 bytes

An immediate window function that takes input from `[A1:B1]` and outputs to the range `[C1].Resize([A1],[A1])`.

```
[C1].Resize([A1],[A1])=0:For s=-[B1]To-1:[C1].Resize(-s,-s)=-s:Next

```

### Input / Output

Input is in range `[A1:B1]`
> 2 votes

# Answer
# MATLAB, 58 bytes (Thanks to anonymous user)

```
function o=f(c,s);o=zeros(c);for j=s:-1:1;o(1:j,1:j)=j;end

```

Just filling the elements of matrix with appropriate number, running a loop. Maybe possible to be cleverer with `arrayfun`
> 2 votes

# Answer
# , 18 bytes

```
,~@[{.[:>./~1+i.@]

```

Much longer than both APL solutions.

Try it online!
> 2 votes

# Answer
# C# (.NET Core), 85 bytes

```
c=>s=>{var r=new int[c,c];for(;s>0;)for(int j=s--;j-->0;)r[s,j]=r[j,s]=s+1;return r;}

```

Try it online!

A port of Kevin Cruijssen's answer, which was much better than mine.
> 1 votes

# Answer
# Python 2, 58 bytes

```
lambda C,S:[-~max(i%C,i/C)*(i%C<S>i/C)for i in range(C*C)]

```

Try it online!

Outputs a 1D list of length `C*C`.
> 1 votes

# Answer
# Charcoal, 19 bytes

```
Ｅθ⪫ＩＥＥθ⌈⟦ιλ⟧∧‹λη⊕λ

```

Try it online! Link is to verbose version of code. 3 bytes used to convert the output to decimal and format it nicely. Explanation:

```
 θ                  Input `C`
Ｅ                   Map over implicit range
      θ             Input `C`
     Ｅ              Map over implicit range
          λ         Inner index
         ι          Outer index
       ⌈⟦  ⟧        Maximium
    Ｅ               Map over results
              λ     Current value
               η    Input `S`
             ‹      Less than
                 λ  Current value
                ⊕   Incremented
            ∧       Logical AND
   Ｉ                Cast to string
  ⪫                 Join with spaces
                    Implicitly print on separate lines

```
> 1 votes

# Answer
# Clean, 67 bytes

```
import StdEnv
$n s=[[if(i>s||j>s)0(max i j)\\i<-[1..n]]\\j<-[1..n]]

```

Try it online!

Defines `$ :: Int Int -> [[Int]]` giving an answer using 1-based indexing.
> 1 votes

# Answer
# Perl 6, 37 bytes

```
{((^$^c+1 Xmax^$c+1)Xmin$^s+1)X%$s+1}

```

Try it online!

Returns the matrix as 1-dimensional array.
> 1 votes

# Answer
# Mathematica 44 bytes

```
Table[If[i <= s && j <= s, Max[i, j], 0], {i, c}, {j, c}]

```
> 1 votes

# Answer
# Husk, 11 bytes

```
T0:´ṪYḣ⁰`R0

```

Try it online! The function takes `S` followed by `C`.
> 1 votes

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