title: Read color in my way

text:
# Question
Title: Read color in my way
Different systems have different ways to describe colors, even if all of them are speaking in R-G-B-A space. A front-end developer who is familiar with CSS may prefer `#RRGGBBAA`. But Android developers may prefer `#AARRGGBB`. When handling AAS file format, `#AABBGGRR` is needed. That's too confusing. Maybe we need a program which can convert between different color formats.

**Input:**

The input contains 3 parts:

* The color to be transformed (e.g. `#1459AC0F`), a string starting with sharp sign `#` followed by 8 hex digits.
* The format of the given color (e.g. `#RRGGBBAA`), a string starting with `#` followed by 8 letters which fall into 4 different groups and each group is one of `RR`/`GG`/`BB`/`AA`.
* The format to convert to.

**Output:**

* Output the color in converted format

**Test Cases:**

```
Color, OriginalFormat, TargetFormat -> Result
#12345678, #RRGGBBAA, #AARRGGBB -> #78123456
#1A2B3C4D, #RRGGBBAA, #AABBGGRR -> #4D3C2B1A
#DEADBEEF, #AARRGGBB, #GGBBAARR -> #BEEFDEAD

```

Input / output are case insensitive. You may input / output in any acceptable way.

**Rules:**

This is code golf, shortest (in byte) codes of each language win

# Answer
> 10 votes
# APL (Dyalog Unicode), 6 bytesSBCS

Full program. Prompts on STDIN for Original, then Target, then Color. Prints Result to STDOUT.

```
⍞[⍞⍋⍞]

```

Try it online!

prompt for Original

`⍞⍋` prompt for Target and find the indices into Original that would make Original into Target

`⍞[``]` prompt for Color and use the above obtained indices to reorder Color

# Answer
> 8 votes
# JavaScript (ES6), ~~53~~ 52 bytes

*Saved 1 byte thanks to @tsh*

Takes input as 3 distinct parameters: `(Color, From, To)`.

```
(C,F,T)=>T.replace(/\w/g,(x,i)=>C[F.search(x)-~i%2])

```

Try it online!

# Answer
> 5 votes
# Stax, 8 bytes

```
ç▼☺↔kàÅJ

```

Run and debug it

This program takes input in this format.

```
"{Color}" "{OriginalFormat}" "{TargetFormat}"

```

Here's the commented ungolfed unpacked version of the same program.

```
u       drop duplicated characters from target format
{       for each character remaining in target format, map using block...
  [     duplicate original format at second position in stack
  |I    get all indices of target character in original format
  xs@   retrieve characters from those indices from the color string
m       perform map
        output implicitly when complete

```

Run this one

# Answer
> 4 votes
# Python 2, 59 bytes

```
lambda c,o,t:'#'+''.join(c[o.find(v):][:2]for v in t[1::2])

```

Try it online!

# Answer
> 4 votes
# Retina 0.8.2, 33 bytes

```
(.)(?<=(..).{7}\1\1.*)\1
$2
.*#
#

```

Try it online! Link includes test cases. Explanation:

```
(.)(?<=(..).{7}\1\1.*)\1
$2

```

For each pair of identical characters, look back for another copy of that pair, and then the 9th and 8th characters before that, and replace the pair with those characters. This is only possible for the pairs of characters in the target format, and replaces them with the desired result.

```
.*#
#

```

Delete the colour and source format.

# Answer
> 3 votes
# Haskell, ~~108 104 100 94~~ 87 bytes

```
(s,(r@(x,y):z))!c|x==c=(s++[y],z)|(p,q)<-(s,z)!c=(p,r:q)
c%i=fst.(foldl(!)("",zip i c))

```

Try it online!

---

### Old version

Thanks to Laikoni for shortening 6 bytes by finding a shorter way to use `lookup`!

```
f(Just x)=x
p('#':z)=p z
p(x:y:z)=[x,y]:p z
p e=[]
c!i=('#':).(f.(`lookup`zip(p i)(p c))=<<).p

```

Try it online!

### Explanation:

* the `p` function "parses" a string by ignoring the leading `#` and returning groups (lists) of 2 chars.
* the `(!)` operator takes as input the color and the input format and returns a function that takes as a parameter the output format and returns the converted color. It turned out that the pointfree version was shorter, but I started with the more readable version:

`f c i o='#':concat[x#zip(p<$>[i,c])|x<-p o]`

Try it online!

# Answer
> 3 votes
# Perl 5 `-p`, ~~33~~ ~~32~~ 27 bytes

Give input in the order: target, original, number

```
#!/usr/bin/perl -p
s%.%$2x/(..)+$&(.){10}/g%eg

```

Try it online!

For each character in the input find the same character an even number of places forward then from there go 10 more characters forward and take that character as replacement. If you can't do these steps replace by nothing.

```
    +--even-+----10---+
    |       |         |
#AARRGGBB #RRGGBBAA #12345678
    |    >-will get removed-<
    v
    2

```

# Answer
> 2 votes
# Java 10, ~~179~~ ~~105~~ 102 bytes

```
(a,b,c)->{var r="#";for(int i=1,t;i<9;)r+=a.substring(t=b.indexOf(c.substring(i,i+=2)),t+2);return r;}

```

Whopping -77 bytes thanks to *@OlivierGrégoire*.

**Explanation:**

Try it online.

```
(a,b,c)->{            // Method with String as three parameters and return-type
  var r="#";          //  Result-String, starting at "#"
  for(int i=1,t;i<9;  //  Loop `i` from 1 to 9 (exclusive)
    r+=               //   Append the result with:
       a.substring(   //    A substring from the first input,
        t=b.indexOf(  //    where an index is determined in the second input
           c.substring(i,i+=2)),t+2);
                      //    based on a substring of the third input
    return r;}        //  Return the result-String

```

# Answer
> 2 votes
# 05AB1E, 10 bytes

```
2FI2ô™J}I‡

```

Try it online!

---

```
2F     }   # Loop twice...
  I        # First 2 inputs.
   2ô™     # Title case in pairs of 2.
      J    # Rejoin together.
        I  # Last input (The color).
         ‡ # Transliterate, put color in pattern from a into pattern from b.

```

This works because I change the input from:

```
AARRGGBB

```

To:

```
AaRrGgBb

```

So each value is mapped uniquely, then I can use transliterate.

The arguments are reversed.

# Answer
> 2 votes
# , 5 bytes

```
/:i./

```

The left argument is the color. The right argument is a character matrix where the first row is the target format and the second row is the original format. Try it online!

# Answer
> 1 votes
# CJam, 14 bytes

```
{'#\1f>2f/~er}

```

Try it Online!

Input is an array in the reverse order.

```
{
 `#\      e# Push '#'+[input array] on to stack
  1f>     e# Remove the '#' symbol from each input string
  2f/     e# Split each input string into an array of substrings of length 2.
  ~       e# Dump the substring-arrays from the container array onto the stack
  er      e# Perform a string replace operation
}

```

# Answer
> 0 votes
# Red, 154 120 114 bytes

```
func[c o t][g: func[q][parse q[skip collect 4 keep 2 skip]]
prin"#"foreach p g t[prin pick g c index? find g o p]]

```

Try it online!

# Answer
> 0 votes
# Python 2, 62 bytes

```
lambda c,s,e:[c[s.index(e[i]):][:2]for i in range(1,len(e),2)]

```

# Answer
> 0 votes
# Perl 6, ~~55~~ ~~51~~ 46 bytes

```
{[~] %(@^b Z=>@^a){@^c}}o*.map(*.comb(/\w?./))

```

Try it online!

Takes a (color, original, target) list as input. Splits each input string into components, creates a Hash mapping source keys to color values, looks up color values in target key order, then formats the result.

# Answer
> 0 votes
# SmileBASIC, 144 bytes

```
DEF R C,I,O
C[0]="&H
A=R+G+B
RGBREAD VAL(C)OUT VAR(I[1]),VAR(I[3]),VAR(I[5]),VAR(I[7])?"#";RGB(VAR(O[1]),VAR(O[3]),VAR(O[5]),VAR(O[7]))END

```

# Answer
> 0 votes
# Python 3, 102 bytes

```
lambda x,a,b:['#']+[[x[i:i+2]for i in range(1,len(x),2)][i]for i in[a[1::2].index(i)for i in b[1::2]]]

```

Try it online!

# Answer
> 0 votes
# Jelly, 6 bytes

```
ẹÐ€Qị⁵

```

Try it online!

Full program.

Argument 1: Original
Argument 2: Target
Argument 3: Color

# Answer
> 0 votes
# C (clang), 89 bytes

```
char *a,b[10],*i,*o;f(x,y){*b=*a;for(x=1;x<8;b[x++]=a[y=index(i,o[x])-i],b[x++]=a[y+1]);}

```

Try it online!

Takes input value in `a`, in format in `i` and out format in `o`. Returns out value in `b`

Minor cheat: storing result in `b` instead of printing to save bytes. Question doesn't disallow it.

~~C (clang), 100 bytes
```
char *a,b[10],*i,*o;f(x,y){*b=*a;for(x=1;x<8;b[x]=a[y=index(i,o[x])-i],b[x+1]=a[y+1],x+=2);puts(b);}

```
Try it online!
~~  ~~C (gcc), 181 bytes
```
char *a,*i,*o;c[4],x,y,z;g(x){x=x==82?0:x==71?1:x==66?2:3;}f(){a++;for(;z<2;z++){i=(z?o:i)+1;for(y=0;y<7;z?printf("%s%2X","#"+!!y,c[g(i[y])]):sscanf(a+y,"%2X",&c[g(i[y])]),y+=2);}}

```
Try it online!
~~

~~Creates a `RGBA` value in `c[]` array based on format `i`, then prints in `o` format~~

# Answer
> 0 votes
# Clojure 1.8, 156 bytes

```
(fn[c o t](reduce #(str %(val %2))""(sort-by key(reduce-kv #(let[s(clojure.string/index-of t(nth o %2))](assoc %(if(contains? % s)(inc s)s)%3)){}(vec c)))))

```

Ungolfed

```
  (fn [c o t]
    (reduce
     #(str % (val %2))
     ""
     (sort-by key
              (reduce-kv
               #(let [s (clojure.string/index-of t (nth o %2))]
                  (assoc %
                         (if (contains? % s) (inc s) s)
                         %3))
               {}
               (vec c)))))

```

Try it online does not have Clojure 1.8 support. Very strange!

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


# Question
Title: Minimize Least Used Binary Bits in Fractions
## Introduction

For a given rational number `r`, find a pair of integers `p,q` so that `p/q=r` and the number of less used bits in `p` and `q` are minimized (details below).

## Challenge

A positive rational number `r` can be expressed as the ratio of two positive integers, `r=p/q`. The representation is not unique. For each of these representations, both `p` and `q` can be expressed in its binary form and the number of `0`s and `1`s in the representation can be counted (not including leading zeros).

We count the number of appearance of the less appeared digit for both `p` and `q` (denoted `g(p)` and `g(q)`) and finally define `f(p,q)=max(g(p),g(q))`.

For example, the number `35` can be written as `35/1` or `175/5`, and we convert both the numerator and the denominator to binary. Then we can count

```
35 -> 100011, 3 zeros, 3 ones. g(35)=min(3,3)=3
 1 ->      1, 0 zero ,  1 one.  g(1)=min(1,0)=0

f(35,1)=max(g(35),g(1))=3.

```

And for `175/5`

```
175 -> 10101111. 2 zeros, 6 ones. g(175)=min(2,6)=2
  5 ->      101. 1 zero,  2 ones.   g(5)=min(1,2)=1.

f(175,5)=max(g(175),g(5))=2.

```

Therefore, if we want to minimize `f(p,q)` while keeping the rate of `p/q` constant, `p=175,q=5` is a better choice than `p=35,q=1`. An even better choice is `p=1015,q=29` since `f(1015,29)=1`. It is also easy to prove that there are no valid choice that makes `f(p,q)` equals `0`, so this the optimal choice.

Your task is to write a full program or function that computes a choice of `(p,q)` for a given rational number `r` such that `f(p,q)` is minimized (sub-optimal solutions are OK but there are penalties), while keeping the program as short as possible.

## Test cases

The outputs are not unique.

```
Input
Output

63/1
63/1 0

17/9
119/63 1

35/1
1015/29 1

563/1
2815/5 2

```

You may also wish to see whether you can get an answer without penalty(see below) for `595/1`.

## Scoring

Your score will be composed of two parts: the code-length and the penalties. The code-length is measured in bytes.

The penalties are calculated by running your program on all test cases in the given test set. For each `r` in the test set, if your program outputs `p,q`, you get a penalty of `max(f(p,q)-2,0)`. That is, you get no penalty (nor bounty) for any answer that gives a `f` value less than or equal to `2`.

The final score is calculated by `final_penalty*codelength^(1/4)`, with lower score better.

## Test set

The test set for calculating the penalty can be found in this pastebin.

Basically, it contains all rational numbers which when expressed in reduced fraction `p/q` has the property `128>p>q` (and of course, `(p,q)` coprime), along with all integers from `128` to `1023`(inclusive). The second column in the pastebin are the `f(p,q)` calculated by a naive method. The final line in the pastebin shows the total penalty of this naive method. It is `2343`.

## Specs

* Input can be given in any reasonable form. For example, a rational if your program supports it, or a tuple or a list of the numerators and denominators in any order (and you should assume them to be coprime). Same flexiblility for output.
* You need to output `p` and `q` in a reasonable form and also `f(p,q)` (To avoid 0-byte programs, thanks to @Lynn).
* You should be able to score your own program (Thanks for the suggestion by @user202729). So in your answer, please specify all of the following: the final penalty, the code length in bytes, and the score. Only the score needs to be included in the title of your answer.

# Answer
# Node.js, Score = 7873

This is both naive and rather long...

* Code size = 129 bytes
* Total penalty = 2336
* Score = round(1291/4 * 2336) = 7873

Takes input as **\[p, q\]**. Returns **\[p', q', f(p, q)\]**.

```
f=(a,r=[k=6e3])=>k--?f(a,(i=Math.max(...a.map(n=>(g=n=>n?g(n>>1,n&1?++o:++z):o<z?o:z)(a=(p=a,n*k),o=z=0))))>r[2]?r:[p,a,i],k--):r

```

Try it online! for the test cases

or compute the total penalty by processing the whole test set

---

# Alternate version, Score = 8426

A modified version to reach a total penalty of 2330. But it's not worth it...

* Code size = 171 bytes
* Total penalty = 2330
* Score = round(1711/4 * 2330) = 8426

Same I/O format as the main version.

```
f=(a,r=[k=5e3])=>k--?f(a,(i=Math.max(...a.map(n=>(g=n=>n?g(n>>1,n&1?++o:++z):o<z?o:z)(a=(p=a,n*([7007,7901,16239,32695,130527,261599][k]||k-5)),o=z=0))))>r[2]?r:[p,a,i]):r

```

Try it online!

It includes some hardcoded values for the highest multipliers. They were found by generating all bitmasks **m** with up to 32 bits and no more than 5 0's, keeping the values for which **m mod p = 0**, checking the score of **q * m / p** and finally doing the same operation with the inverted bitmask of **m** of the same length (no more than 5 1's with all other bits set to 0).
> 3 votes

# Answer
# Julia 0.6, Score = 7702

```
g(x,b=[bin(x)...])=min(sum(b.=='0'),sum(b.=='1'))
f(a,b)=((r,i)=findmin(map(i->max(g(a*i),g(b*i)),1:10^5));[r,a*i,b*i])

```

Try it online!

A naive and slow solution. Output of `f` is `[f(p,q),p',q']`

* Length = 119 bytes
* Penalty = 2332
* Score = round(119^.25\*2332) = 7702

To run this on the test set, I've downloaded the paste bucket as a `txt` file called `results.txt` and removed the last row. I used this code to evaulate the penalty using all cores of my machine:

```
all_res = open("results.txt","r") do f
    map(row->parse.(Int,split(split(row," ")[1], "/")), readlines(f))
end

addprocs(7)
@everywhere g(x,b=[bin(x)...])=min(sum(b.=='0'),sum(b.=='1'))
@everywhere f(a,b)=((r,i)=findmin(map(i->max(g(a*i),g(b*i)),1:10^5));[r,a*i,b*i])

penalty = @parallel (+) for iter in all_res
    max(f(iter[1],iter[2])[1]-2,0)
end

```
> 2 votes

# Answer
# C++ (GCC), score = 11222

* Length: 538 (\<-- less verbose than Java)
* Penalty: 2330

```
#import<bits/stdc++.h>
using namespace std;uint32_t f(uint32_t x){int s=__builtin_popcount(x);return min(s,32-__builtin_clz(x)-s);}int i(vector<int>const&a,vector<int>const&b){int i=0,j=0;while(i<a.size()&j<b.size()){if(a[i]==b[j])return a[i];else++(a[i]<b[j]?i:j);}return 0;}int main(){vector<array<vector<int>,6>>T(1024);int p,q,a;for(a=1;a<1024;++a){for(unsigned m=1;m<500000;++m)for(p=f(a*m);p<6;++p)T[a][p].push_back(m);}while(cin>>p>>q){for(a=1;;++a){unsigned m=i(T[p][a],T[q][a]);if(m){cout<<p*m<<' '<<q*m<<' '<<a<<'\n';break;}}}}

```

Runs in 5 seconds on my machine.

Input format: something like this

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

```

Output format: something like this

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

```

(`p', q', f(p', q')` on each line)

---

Ungolfed code:

```
/* the program will not work without END_ANS and END_INPUT being
correctly set but it can be easily calculated by a naive algorithm
END_ANS must be greater than all of the answers,and END_INPUT
must be greater than all of the inputs */
int constexpr END_ANS=6,//<-- according to the naive algorithm
END_INPUT=1024,END_M=4194304;
/* END_M is an parameter to the algorithm. As this gets larger,
the algorithm takes more resource but the answer gets better.
NOTE: (END_INPUT-1) * (END_M-1) must not overflow integer.
*/

static_assert((END_INPUT-1)*(long long)(END_M-1)<4294967296LL);

#include<iostream>
#include<vector>
#include<array>
#include<algorithm>

uint32_t f(uint32_t x){
    uint32_t len=32-__builtin_clz(x),
    sum=__builtin_popcount(x);
    return std::min(sum,len-sum);
}

/**Return a common value between two vectors,or 0 if not found.
The input vectors must be sorted.*/
int intersect(std::vector<int>const&a,std::vector<int>const&b){
    int i=0,j=0;
    while(i<a.size()&j<b.size()){
        if(a[i]==b[j])return a[i];
        else++(a[i]<b[j]?i:j);
    }
    return 0;
}

int main() {
    std::vector<std::array<std::vector<int>,END_ANS>>T(END_INPUT);
    //T[i][f1] = all values of m s.t. f(i*m) <= f1
    for(int i=1;i<END_INPUT;++i){
        for(unsigned m=1;m<END_M;++m)
            for(int fi=f(i*m);fi<END_ANS;++fi)
                T[i][fi].push_back(m);
    }

    // THIS PART IS USED FOR CALCULATING SCORE
    int score=0;

    int p,q;while(std::cin>>p>>q){
        for(int ans=1;;++ans){
            unsigned m=intersect(T[p][ans],T[q][ans]);
            if(m){
                std::cout<<p*m<<' '<<q*m<<' '<<ans<<'\n';

                // THIS PART IS USED FOR CALCULATING SCORE
                score+=std::max(ans-2,0);

                break;
            }
        }
    }

    // THIS PART IS USED FOR CALCULATING SCORE
    std::cerr<<score<<'\n';

}

```

---

Note: There are some hardcoded constants in the program (maximum input value, maximum `ans`, etc.) I assume it's allowed because otherwise most programs can work in 32-bit integer range anyway.

For each `(p,q)` pair, the program tests all pairs `(p×m,q×m)` for all `m` in range `[1,MAX_M[` and find the optimal value, in a smart way.

Because the result is the same for `MAX_M=500000` and `MAX_M=4194304` (the largest value such that all intermediate computations still fit in an `uint32_t` (unsigned 32-bit integer)), I just use `MAX_M=500000` so the program runs faster.

Bash+Jelly script to calculate score:

```
jelly eun 'ỴḲṛ/VƊ€_2»0S' "'''$(cat result.txt)'''" # <- weird input format

```

---

tl;dr: Tested all values of `m` up to `4194304` (exclusive), best penalty so far = `2330`.
> 1 votes

# Answer
# Jelly, 7437

* Code size = 10 bytes
* Total penalty = 4182
* Score = round(101/4 * 4182) = 7437

Takes input as **\[p, q\]**, returns **\[f(p, q), \[p', q'\]\]**.

```
BC,Bḅ1ZṀṂ,

```

Try it online!

### How?

This code simply computes **f(p, q)** without trying to apply any multiplier.

```
BC,Bḅ1ZṀṂ, - main link taking [p, q]              --> e.g. [61, 40]
B          - convert to binary                    --> [[1,1,1,1,0,1], [1,0,1,0,0,0]]
 C         - 1-complement                         --> [[0,0,0,0,1,0], [0,1,0,1,1,1]]
   B       - convert to binary again              --> [[1,1,1,1,0,1], [1,0,1,0,0,0]]
  ,        - pair                                 --> [ [[0,0,0,0,1,0], [0,1,0,1,1,1]],
                                                        [[1,1,1,1,0,1], [1,0,1,0,0,0]] ]
    ḅ1     - convert from unary base,             --> [[1, 4], [5, 2]]
             which effectively sums the lists
      Z    - zip, so that number of 0-bits and    --> [[1, 5], [4, 2]]
             number of 1-bits are paired together
       ṀṂ  - maximum of the minimum               --> max(min(1, 5), min(4, 2)) =
                                                      max(1, 2) =
                                                      2
         , - pair with the input to comply with   --> [2, [61, 40]]
             the expected output format

```
> 1 votes

---
Tags: code-challenge, optimization, math
---


title: Is this a truncated triangular number?

text:
# Question
Title: Is this a truncated triangular number?
Related OEIS sequence: A008867

## Truncated triangular number

A common property of triangular numbers is that they can be arranged in a triangle. For instance, take 21 and arrange into a triangle of `o`s:

```
     o
    o o
   o o o
  o o o o
 o o o o o
o o o o o o

```

Let's define a "truncation:" cutting triangles of the same size from each corner. One way to truncate 21 is as follows:

```
     .
    . .
   o o o
  o o o o
 . o o o .
. . o o . .

```

(The triangles of `.` are cut from the original).

There are 12 `o`s remaining, so 12 is a truncated triangle number.

# Task

Your job is to write a program or a function (or equivalent) that takes an integer and returns (or use any of the standard output methods) whether a number is a truncated triangle number.

# Rules

* No standard loopholes.
* The input is a non-negative integer.
* A cut cannot have a side length exceeding the half of that of the original triangle (i.e. cuts cannot overlap)
* A cut can have side length zero.

# Test cases

Truthy:

```
0
1
3
6
7
10
12
15
18
19

```

Falsy:

```
2
4
5
8
9
11
13
14
16
17
20

```

**Test cases for all integers up to 50: TIO Link**

This is , so submissions with shortest byte counts in each language win!

# Answer
> 8 votes
## Haskell, ~~46~~ 45 bytes

```
f n|t<-scanl(+)0[1..n]=or[x-3*y==n|x<-t,y<-t]

```

Try it online!

# Answer
> 7 votes
# Haskell, 46 bytes

```
f n=or[mod(gcd(p^n)(4*n-1)-5)12<3|p<-[1..4*n]]

```

Try it online!

Having thrown a bunch of number theory at the problem (thanks @flawr), I found this characterization:

> **n** is a truncated triangular number exactly if in the prime factorization of **4n-1**, any prime of the form **5 mod 12** or **7 mod 12** appears an even number of times.

This means, for instance, that **4n-1** may not be divisible by 5 unless it's further divisible by **52=25** and the total number of **5** factors is even.

Haskell doesn't have a factorization-built-in, but we can improvise. If we work with factorizations into primes powers like **12=3\*4**, we can use the equivalent statement:

> **n** is a truncated triangular number exactly if the factorization of **4n-1** into prime powers has no terms of form **5 mod 12** or **7 mod 12**.

We can extract the power of a prime **p** appearing in **k** as `gcd(p^k)k`. We then check that the result **r** is not 5 or 7 modulo 12 as `mod(r-5)12>2`. Note that **r** is odd. We also check composites as **p**, lacking a way to tell them from primes, but the check will pass as long as its factors do.

Finally, negating `>2` to `<3` and switching `True`/`False` in output saves a byte by letting us use `or` instead of `and`.

---

A related characterization is that the divisors of **4n-1** taken modulo 12 have more total 1's and 11's than 5's and 7's.

**53 bytes**

```
f n=sum[abs(mod k 12-6)-3|k<-[1..4*n],mod(4*n)k==1]<0

```

Try it online!

# Answer
> 6 votes
# Python 2, 52 bytes

```
f=lambda n,b=1:b>n+1or(8*n-2+3*b*b)**.5%1>0<f(n,b+1)

```

Try it online!

Outputs `True`/`False` flipped. Uses this characterization:

> **n** is a truncated triangular number exactly if **8n-2** has form **a2-3b2** for some integers **a,b**.

We check whether any `8*n-2+3*b*b` is a perfect square for any `b` from `1` to `n+1`. We avoid `b=0` because it gives an error for a square root of a negative when `n==0`, but this can't hurt because only odd `b` can work.

Done non-recursively:

**Python 2, 53 bytes**

```
lambda n:0in[(8*n-2+3*b*b)**.5%1for b in range(~n,0)]

```

Try it online!

# Answer
> 6 votes
# Jelly, 10 bytes

```
0r+\ð_÷3f⁸

```

A monadic link accepting an integer and returning a truthy value (a non empty list) or a falsey value (an empty list).

**Try it online!** (footer performs Python representation to show the `[0]` results as they are)
...or see a test-suite (runs for 0 to 20 inclusive)

### How?

Given N, forms the first N triangle numbers, subtracts N from each, divides each result by 3 and keeps any results that are one of the first N triangle numbers.

```
0r+\ð_÷3f⁸ - Link: integer, N             e.g. 7
0r         - zero inclusive range N            [    0, 1, 2,   3,    4, 5,   6,   7]
  +\       - cumulative reduce with addition   [    0, 1, 3,   6,   10,15,  21,  28]
    ð      - start a new dyadic link with that, t, on the left and N on the right
     _     - t subtract N (vectorises)         [   -7,-6,-3,  -1,    3, 8,  14,  21]
      ÷3   - divide by three (vectorises)     [-2.33,-2,-1.33,-0.33,1,2.67,4.67, 7]
         ⁸ - chain's left argument, t          [    0, 1, 3,   6,   10,15,  21,  28]
        f  - filter keep                       [                     1             ]
                                               - a non-empty list, so truthy

```

# Answer
> 5 votes
# , ~~45~~ 43 bytes

*-2 bytes thanks to Vlo*

```
(n=scan())%in%outer(T<-cumsum(0:n),3*T,"-")

```

Try it online!

I'm fairly sure we only need to check the first `n` triangular numbers for this; brute force checks if `n` is in the pairwise differences of the triangular numbers and their triples.

# Answer
> 4 votes
# Pyt, 10 bytes

```
Đř△Đ3*ɐ-Ƒ∈

```

Try it online!

Explanation:

```
        Implicit input
Đ       Duplicate input
ř       Push [1,2,...,input]
△       For each element k in the array, get the kth triangle number
Đ       Duplicate the top of the stack
3*      Multiply by 3
ɐ       ɐ - All possible:
 -                       subtractions between elements of the two arrays
Ƒ       Flatten the nested array
∈       Is the input in the array

```

# Answer
> 3 votes
# Haskell, 48 bytes

```
f a|u<-[0..a]=or[x^2+x-3*(y^2+y)==2*a|x<-u,y<-u]

```

Try it online!

# Answer
> 3 votes
# , 22 bytes

```
e.[:,@(-/3*])2![:i.2+]

```

Try it online!

Straightforward and somewhat-poorly-golfed approach.

# Explanation

```
e.[:,@(-/3*])2![:i.2+]
             2![:i.2+]  Range of triangular numbers up to N
      (-/3*])           All possible subtractions of 3T from T
                        where T is triangular up to the Nth triangular number
    ,@                  Flattened into a single list
e.                      Is N in the list?

```

# Answer
> 3 votes
# MATL, 12 bytes

```
tQ:qYst!3*-m

```

Outputs `1` for truthy, `0` for falsy.

Try it online! Or verify all test cases.

### How it works, with example

Consider input `6`

```
t      % Implicit input. Duplicate
       % STACK: 6, 6
Q:q    % Increase, range, decrease element-wise. Gives [0 1 ... n]
       % STACK: 6, [0 1 ... 6]
Ys     % Cumulative sum
       % STACK: 6, [0 1 3 6 10 15]
t!     % Duplicate, transpose
       % STACK: 6, [0 1 3 6 10 15], [0;
                                     1;
                                     3;
                                     6;
                                     10;
                                     15]
3*     % Times 3, element-wise
       % STACK: 6, [0 1 3 6 10 15 21 28 36 45 55], [0;
                                                    3;
                                                    9;
                                                    18;
                                                    30;
                                                    45]
-      % Subtract, element-wise with broadcast
       % STACK: 6, [  0   1   3   6  10  15  21;
                     -3  -2   0   3   7  12  18;
                     -9  -8  -6  -3   1   6  12;
                    -18 -17 -15 -12  -8  -3   3;
                    -30 -29 -27 -24 -20 -15  -9;
                    -45 -44 -42 -39 -35 -30 -24;
                     -63 -62 -60 -57 -53 -48 -42]
m      % Ismember. Implicit display
       % STACK: 1

```

# Answer
> 2 votes
# Ruby, ~~65 57 52~~ 48 bytes

```
->n,b=0{b+=1;(8*n-2+3*b*b)**0.5%1==0||b<n&&redo}

```

Try it online!

Inspired by xnor's python answer

# Answer
> 2 votes
# Python 3, 84 bytes

```
lambda n:1in set([((8*(n+(i*(i+1)/2)*3)+1)**0.5)%4==1for i in range(n)])or n in[0,1]

```

Try it online!

# Answer
> 1 votes
# 05AB1E, 11 bytes

```
ÅT3*+8*>Å²Z

```

Try it online!

**Explanation**

```
ÅT            # get a list of triangle numbers upto input
  3*          # multiply each by 3
    +         # add input to each
     8*       # multiply each by 8
       >      # increment each
        Å²    # check each for squareness
          Z   # max

```

This is based on the fact that a number **T** is triangular if `8T+1` is an odd perfect square.
We start on the list of triangles we could truncate, calculate the possible larger triangles based on them and check if it in fact is triangular.

# Answer
> 1 votes
# Japt, 16 bytes

```
ò å+ d@Zd_-3*X¶U

```

Try it | Check all test cases

---

## Explanation

```
                     :Implicit input of integer U
ò                    :Range [0,U]
  å+                 :Cumulative reduction by addition
     d@              :Does any X in array Z return true when passed through this function?
       Zd_           :  Does any element in Z return true when passe through this function?
          -3*X       :    Subtract 3*X
              ¶U     :    Check for equality with U

```

---

## Alternative

```
ò å+ £Zm-3*XÃdøU

```

Try it

# Answer
> 1 votes
# Add++, 36 bytes

```
D,g,@,.5^di=
L,ßR¬+A↑>3€*A€+8€*1€+ºg

```

Try it online!

---
Tags: code-golf, math, decision-problem, number-theory, integer
---


title: Weaving in ASCII

text:
# Question
Title: Weaving in ASCII
Imagine a rectangular grid of `|` characters represents the taut strings on a loom (the warp) that other threads (the weft), which we will represent as `-`, can be woven around.

Here is the unwoven warp of a 7×4 loom:

```
|||||||
|||||||
|||||||
|||||||

```

There are a number of ways the weft can be woven into the warp, the simplest being the plain weave.

In the first row of a plain weave the weft starts above the first warp string, goes below the second string, then above the third string, then below the fourth, and so on.

The second weft row is identical to the first but offset to the right by one warp string, so it starts under then goes over, and so on.

On our 7×4 loom the plain weave looks like this:

```
-|-|-|-
|-|-|-|
-|-|-|-
|-|-|-|

```

We can describe the plain weave by saying that the weft goes over the warp *1* time, then under *1* time, and each subsequent row is shifted *1* string to the right.

A generalized weave can be described by having the weft go over the warp *v* times, then under *u* times, with each subsequent row shifted by *s* strings to the right. (All values are integers, *s* may be 0 or negative, *u* and *v* must be non-negative.)

A 7×4 loom with *v = 1*, *u = 2*, *s = 2*, a type of twill weave:

```
-||-||-
||-||-|
|-||-||
-||-||-

```

# Challenge

Your task is to write the shortest program (in bytes) that produces a woven pattern of bars and dashes given *v*, *u*, *s*, the width and height of the loom, and the *initial shift*.

The *initial shift* is the number of strings the first row in the weft is shifted to the right (0 in the examples above). Each subsequent row is shifted by *s* more strings.

Your program should take in these 6 numbers in some easy to use format (stdin, a function call, etc.) and output the woven grid of bars and rectangles to stdout. You may assume all input is valid. (All values are integers, width and height must be positive, *initial shift* may be anything.)

# Examples

*width = 5, height = 4, initial shift = 0, v = 1, u = 3, s = -2:*

```
-|||-
||-||
-|||-
||-||

```

*width = 5, height = 4, initial shift = 3, v = 1, u = 3, s = -2:*

```
|||-|
|-|||
|||-|
|-|||

```

*width = 5, height = 4, initial shift = 1, v = 1, u = 1, s = 0:*

```
|-|-|
|-|-|
|-|-|
|-|-|

```

*width = 5, height = 4, initial shift = 0, v = 1, u = 0, s = 0:*

```
-----
-----
-----
-----

```

# Notes

* The pattern always starts with the weft over the warp at the top left corner of the grid (unless initially shifted).
* All the weft threads come in from the left. They **do not** spiral like this.
* *u + v* is not necessarily a multiple of the grid width.
* *u* and *v* may not both be 0

# Answer
## Ruby, 72 bytes

```
w,h,v,u,s,i=$*.map &:to_i;h.times{puts ((?-*v+?|*u)*w)[-i%(u+v),w];i+=s}

```

Not a lot to say about this. I build one repetition of `-` and `|`, repeat it `w` times (just to be sure), and the I slice out the appropriate section for each line.
> 5 votes

# Answer
# JavaScript (ES 6) 128

```
F=(w,h,i,v,u,s)=>{for(x=('-'[R='repeat'](v)+'|'[R](u))[R](w*h),l=v+u,i=-i%l+l,s=-s%l+l;h--;i+=s)console.log(x.substr(i,w)+'\n')}

```

**Test**

```
F(11,8,2,5,3,-2)

||-----|||-
-----|||---
---|||-----
-|||-----||
||-----|||-
-----|||---
---|||-----
-|||-----||

```
> 3 votes

# Answer
# Python, 92 bytes

```
w,h,i,v,u,s=eval(A)
x=('|'*u+'-'*v)*w
while h:print(x[-i:]+x[:-i])[-w:];x=x[-s:]+x[:-s];h-=1

```

Hmm... So tempted to learn ruby now.

Input by assigning a string variable in this format: "width, height, initial shift, v, u, s".
Paste before the program:

```
A="80,80,0,2,2,-9"

```
> 2 votes

# Answer
# JavaScript (ES6), 111 bytes

A slightly different ES6 approach, using the functional Array.from.

`f` takes arguments `(w,h,i,v,u,s)` and returns a string. Newlines added to code and literal newline in string replaced by `\n` for clarity; neither reflected in byte count.

```
f=(w,h,i,v,u,s)=>(A=Array).from(A(h),(_,j)=>A.from(A(w),
(_,k)=>(j*((x=v+u)-s)+x+k-i)%x<v?'-':'|').join``).join`\n`

```

## Usage

```
console.log(f(5,4,0,1,3,-2)) /*

-|||-
||-||
-|||-
||-||

*/

```

## Ungolfed version with explanation

I saved some bytes by creating an alias for Array, which is not reflected in the ungolfed version.

```
// take input and create an array of length h (height):
f = (w,h,i,v,u,s) => Array.from( Array(h),

    // in each row position j, create an array of length w (width):
    (_,j) => Array.from( Array(w),

        // in each cell, place - or | depending on the pattern (i,v,u,s)
        // and current position (j,k):
        (_,k) => ( j * ( ( x = v + u ) - s ) + x + k - i ) % x < v ? '-' : '|'

    // turn each row into a string:
    ).join``

// join rows with newlines:
).join`\n`

```
> 1 votes

# Answer
# C, 357 bytes

```
#include<stdio.h>
int w,h,t,v,u,s,i,j,l,f;int main(){scanf("%d %d %d %d %d %d",&w,&h,&t,&v,&u,&s);l=v+u;char g[l];g[l]='\0';f=0;while(u--){g[v+u]='|';}while(v--){g[v]='-';}for(i=0;i<h;i++){for(j=0;j<w;j++){printf("%c",g[abs(t+f+j)%l]);}printf("\n");f-=s;}}

```

"It's more comfortable than it looks." "It would have to be." -- Gia and Eidon (No one's going to get this reference. Hint: "Weave Mat")

So I've been working on and off on this for about five hours now, and I give up. I have no idea how to get this code to work. It keeps going backwards after the first row, and then gets entirely wrong (7 4 0 2 2 1).

Here's the simpler version you can read more easily. All I do is retrieve input, make the template array, and then print within the loops.

```
#include<stdio.h>
int w,h,t,v,u,s,i,j,l,f;
int main(){
    scanf("%d %d %d %d %d %d",&w,&h,&t,&v,&u,&s);
    l=v+u;char g[l];g[l]='\0';f=0;
    while(u--){g[v+u]='|';}while(v--){g[v]='-';}
    for(i=0;i<h;i++){
        for(j=0;j<w;j++){
            printf("%c",g[abs(t+f+j)%l]); // THIS is the line that needs help.
        }
        printf("\n");
        f-=s;
    }
}

```

You can easily test it here: http://www.compileonline.com/compile\_c\_online.php using "7 4 0 1 1 1" in the STDIN Input box at the bottom. Start editing the numbers, and you'll see the problems.

Sorry I couldn't come up with a working solution; I'm hating myself for this. I've spent too much time to not upload it to have someone else fix.

I've been using this printf for a while to further separate the top row (easy) to the rest of them (the problem rows): `printf("%c",g[i?abs(t+f+j)%l:abs(t+j)%l]);`
> 0 votes

# Answer
# Haskell, 126 bytes

```
f w h i v u s=putStr.unlines$take h$take w<$>(iterate(drop(mod s(u+v)))$drop(mod(-i)(u+v)).cycle$('-'<$[1..v])++('|'<$[1..u]))

```
> 0 votes

---
Tags: code-golf, ascii-art
---


title: The symmetry of months

text:
# Question
Title: The symmetry of months
# Introduction

Some months are **completely symmetric**, meaning they have *central symmetry* as well as *reflection symmetry*, like `February of 2010`:

```
     February 2010
┌──┬──┬──┬──┬──┬──┬──┐
│  │  │  │  │  │  │  │
├──┼──┼──┼──┼──┼──┼──┤
│  │  │  │  │  │  │  │
├──┼──┼──┼──┼──┼──┼──┤
│  │  │  │  │  │  │  │
├──┼──┼──┼──┼──┼──┼──┤
│  │  │  │  │  │  │  │
└──┴──┴──┴──┴──┴──┴──┘

```

Some months have **only** central symmetry, like `February of 1996` or current month, the `April of 2018`:

```
      February 1996
          ┌──┬──┬──┬──┐
          │  │  │  │  │
 ┌──┬──┬──┼──┼──┼──┼──┤
 │  │  │  │  │  │  │  │
 ├──┼──┼──┼──┼──┼──┼──┤
 │  │  │  │  │  │  │  │
 ├──┼──┼──┼──┼──┼──┼──┤
 │  │  │  │  │  │  │  │
 ├──┼──┼──┼──┼──┴──┴──┘
 │  │  │  │  │
 └──┴──┴──┴──┘

       April 2018  ┌──┐
                   │  │
 ┌──┬──┬──┬──┬──┬──┼──┤
 │  │  │  │  │  │  │  │
 ├──┼──┼──┼──┼──┼──┼──┤
 │  │  │  │  │  │  │  │
 ├──┼──┼──┼──┼──┼──┼──┤
 │  │  │  │  │  │  │  │
 ├──┼──┼──┼──┼──┼──┼──┤
 │  │  │  │  │  │  │  │
 ├──┼──┴──┴──┴──┴──┴──┘
 │  │
 └──┘

```

And some are **asymmetric**, like the previous month, the `March of 2018`:

```
      March 2018
         ┌──┬──┬──┬──┐
         │  │  │  │  │
┌──┬──┬──┼──┼──┼──┼──┤
│  │  │  │  │  │  │  │
├──┼──┼──┼──┼──┼──┼──┤
│  │  │  │  │  │  │  │
├──┼──┼──┼──┼──┼──┼──┤
│  │  │  │  │  │  │  │
├──┼──┼──┼──┼──┼──┼──┘
│  │  │  │  │  │  │
└──┴──┴──┴──┴──┴──┘

```

# Task

Take an input in form of a **date**, e.g.:

* `2018.04`
* `2018.03`
* `2010.02`
* `1996.02`

Output the corresponding **symmetry**, e.g.

* `2018.04` -\> `centrally symmetric`
* `2018.03` -\> `asymmetric`
* `2010.02` -\> `symmetric`
* `1996.02` -\> `centrally symmetric`

# Rules

* This is code golf, so the smallest number of bytes wins.
* Standard loopholes are obviously not allowed.
* Assume that the week starts with Monday (thanks to Angs and Arnauld for suggestion).
* Consider only years between 1900 and 2100 (**inclusive**).
* The input and output formatting rules are **permissive**, meaning you can use any equivalent format that is native to the language of your choice.
* Base your solution on the Gregorian calendar.

# Answer
> 22 votes
# JavaScript (ES6), 55 bytes

*Saved 6 bytes thanks to @Neil*

Takes input in currying syntax `(year)(month)`. Returns `false` for asymmetric, `true` for centrally symmetric and `0` for completely symmetric.

```
y=>m=>(n=(g=_=>new Date(y,m--,7).getDay())()+g())&&n==7

```

Try it online!

## How?

We define the function **g()** which returns the weekday of **yyyy/mm/01**, as an integer between **0** = Monday and **6** = Sunday.

```
g = _ => new Date(y, m--, 7).getDay()

```

Because **getDay()** natively returns **0** = Sunday to **6** = Saturday, we shift the result to the expected range by querying for the 7th day instead.

Then we define:

```
n = g() + g()

```

Because the constructor of *Date* expects a 0-indexed month and because **g()** decrements **m** *after* passing it to *Date*, we actually first compute the weekday of the first day of the *next* month and then add that of the current one.

### Completely symmetric months

Completely symmetric months start with a Monday and are followed by a month which also starts with a Monday. This is only possible for February of a non-leap year.

```
- Feb --------------    - Mar --------------
Mo Tu We Th Fr Sa Su    Mo Tu We Th Fr Sa Su
--------------------    --------------------
01 02 03 04 05 06 07    01 02 03 04 05 06 07
08 09 10 11 12 13 14    08 09 10 11 12 13 14
15 16 17 18 19 20 21    15 16 17 18 19 20 21
22 23 24 25 26 27 28    22 23 24 25 26 27 28
                        29 30 31

```

This leads to **n = 0**.

### Centrally symmetric months

Centrally symmetric months are months for which the sum of the weekday of their first day and that of the next month is **7**.

```
- M ----------------    - M+1 --------------
Mo Tu We Th Fr Sa Su    Mo Tu We Th Fr Sa Su
--------------------    --------------------
 0  1 [2] 3  4  5  6     0  1  2  3  4 [5] 6
--------------------    --------------------
      01 02 03 04 05                   01 02
06 07 08 09 10 11 12    03 04 05 06 07 07 09
13 14 15 16 17 18 19    ...
20 21 22 23 24 25 26
27 28 29 30 31

```

Hence the second test: **n == 7**.

---

# No built-in, 93 bytes

Uses Zeller's congruence. Same I/O format as the other version.

```
y=>m=>(n=(g=_=>(Y=y,((m+(m++>2||Y--&&13))*2.6|0)+Y+(Y>>2)-6*~(Y/=100)+(Y>>2))%7)()+g())&&n==7

```

Try it online!

# Answer
> 7 votes
# T-SQL, 213 bytes (strict I/O rules)

```
SET DATEFIRST 1SELECT CASE WHEN a+b<>8THEN'a'WHEN a=1THEN''ELSE'centrally 'END+'symetric'FROM(SELECT DATEPART(DW,f)a,DATEPART(DW,DATEADD(M,1,f)-1)b FROM (SELECT CONVERT(DATETIME,REPLACE(s,'.','')+'01')f FROM t)y)x

```

The above query considers the strict input/output formatting rules.

The input is taken from the column `s` of a table named `t`:

```
CREATE TABLE t (s CHAR(7))
INSERT INTO t VALUES ('2018.04'),('2018.03'),('2010.02'),('1996.02')

```

Ungolfed:

```
SET DATEFIRST 1
SELECT *, CASE WHEN a+b<>8 THEN 'a' WHEN a=1 AND b=7 THEN '' ELSE 'centrally ' END+'symetric'
FROM (
    SELECT *,DATEPART(WEEKDAY,f) a,
        DATEPART(WEEKDAY,DATEADD(MONTH,1,f)-1) b
    FROM (SELECT *,CONVERT(DATETIME,REPLACE(s,'.','')+'01')f FROM t)y
) x

```

SQLFiddle 1

# T-SQL, 128 bytes (permissive I/O rules)

```
SET DATEFIRST 1SELECT CASE WHEN a+b<>8THEN 1WHEN a=1THEN\END FROM(SELECT DATEPART(DW,d)a,DATEPART(DW,DATEADD(M,1,d)-1)b FROM t)x

```

If the format of the input and of the output can be changed, I would choose to input the first day of the month, in a `datetime` column named `d`:

```
CREATE TABLE t (d DATETIME)
INSERT INTO t VALUES ('20180401'),('20180301'),('20100201'),('19960201')

```

The output would be 1 for asymetric, 0 for symetric, NULL for centrally symetric.

If we can run it on a server (or with a login) configured for BRITISH language, we can remove `SET DATEFIRST 1` saving 15 more bytes.

SQLFiddle 2

# Answer
> 5 votes
# Haskell, 170 bytes

```
import Data.Time.Calendar
import Data.Time.Calendar.WeekDate
a%b=((\(_,_,a)->a).toWeekDate.fromGregorian a b$1)!gregorianMonthLength a b
1!28=2
4!29=1
7!30=1
3!31=1
_!_=0

```

Returns 2 for centrally symmetric, 1 for symmetric and 0 for asymmetric

# Answer
> 5 votes
# Python 2, ~~118~~ 104 bytes

Thanks to Jonathan Allan and Dead Possum for the improvements!

```
from calendar import*
def f(*d):_=monthcalendar(*d);print all(sum(_,[]))+(_[0].count(0)==_[-1].count(0))

```

---

# Python 3, ~~122~~ 105 bytes

```
from calendar import*
def f(*d):_=monthcalendar(*d);print(all(sum(_,[]))+(_[0].count(0)==_[-1].count(0)))

```

---

### Input

* First is the **year**
* Second is the **month**

---

### Output

* 0 = no symmetry
* 1 = central symmetry
* 2 = complete symmetry

# Answer
> 4 votes
# Red, 199, 168 161 bytes

```
func[d][t: split d"."y: do t/1 m: do t/2 a: to-date[1 m y]b: a + 31
b/day: 1 b: b - 1 if(1 = s: a/weekday)and(7 = e: b/weekday)[return 1]if 8 - e = s[return 2]0]

```

Try it online!

0 - asymmetric

1 - symmetric

2 - centrally symmetric

## More readable:

```
f: func[d][                  ; Takes the input as a string
    t: split d "."           ; splits the string at '.'
    y: do t/1                ; stores the year in y
    m: do t/2                ; stores the month in m
    a: to-date[1 m y]        ; set date a to the first day of the month
    b: a + 31                ; set date b in the next month
    b/day: 1                 ; and set the day to 1st
    b: b - 1                 ; find the end day of the month starting on a
    s: a/weekday             ; find the day of the week of a
    e: b/weekday             ; find the day of the week of b
    if(s = 1) and (e = 7)    ; if the month starts at Monday and ends on Sunday
        [return 1]           ; return 1 fo symmetric
    if 8 - e = s             ; if the month starts and ends on the same day of the week
        [return 2]           ; return 2 for centrally symmetric
    0                        ; else return 0 for assymetric
]

```

# Answer
> 2 votes
# Mathematica, 137 bytes

```
a=#~DateValue~"DayName"&;b=a/@{2}~DateRange~{3};Which[{##}=={0,6},1,+##>5,0,1>0,-1]&@@(Position[b,a@#][[1,1]]~Mod~7&)/@{{##},{#,#2+1,0}}&

```

Pure function. Takes the year and the month as input and returns `-1` for asymmetric months, `0` for centrally symmetric months, and `1` for fully symmetric months. Not sure why this language can't convert from a weekday to a number by default...

# Answer
> 2 votes
# Bash \+ GNU utilities, 70

```
date -f- +%u<<<"$1/1+1month-1day
$1/1"|dc -e??sad8*la-55-rla+8-d*64*+p

```

Input is formatted as `YYYY/MM`.

Output is numeric, as follows:

* less than 0: centrally symmetric
* exactly 0: symmetric
* greater than 0: asymmetric

I assume this output format is acceptable for this question.

Try it online!

# Answer
> 1 votes
# C, 111 bytes

```
a;g(y,m){y-=a=m<3;return(y/100*21/4+y%100*5/4+(13*m+16*a+8)/5)%7;}f(y,m){a=g(y,m)+g(y,m+1);return(a>0)+(a==7);}

```

Invoke `f(year, month)`, 0 for completely symmetric, 1 for asymmetric, 2 for centrally symmetric.

# Answer
> 1 votes
# Perl 6, 74 bytes

```
{{{$_==30??2!!$_%7==2}(2*.day-of-week+.days-in-month)}(Date.new("$_-01"))}

```

Bare block, implicitly a function of 1 argument, a string like `"2012-02"`. Returns:

```
2     # Fully symmetric
True  # Centrally symmetric
False # Asymmetric

```

When the pattern is symmetric, as .day-of-week increases by 1, .days-in-month would need to move by 2 in order to still match (the month would be starting a day later but need to end a day earlier), so `2 * .day-of-week + .days-in-month` gives us a measure of that gap. Modulo 7 it should be 1 to get symmetry, but we can first cheaply check for the non-leap February by checking that total before modulo (Monday and 28 days per month is the minimum possible combination).

I'm surprised that this takes so many bytes, but fully 36 bytes are needed for just making a date and getting the day of the week and days in that month.

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


title: Output numbers, more or less

text:
# Question
Title: Output numbers, more or less
## The Challenge

Given an input string (or array) consisting of `<` and `>`, output a sequence (array or string) of integers such that:

* the operators are all correct when applied in order between consecutive numbers in the output
* all integers are positive (1 or greater)
* the sum of the integers is as small as is mathematically possible

Inputs can vary to match "greater than" and "less than" in your chosen language.

As an alternative output, just specify the sum of the numbers in the output. State which version you're solving in your Answer title.

Usual exclusions and rules apply, smallest bytes wins.

You can assume that the input string will never lead to an integer overflow in your language, if that helps.

## Examples

* `>` gives `2 1` which sums to `3`
* `>>>` gives `4 3 2 1` which sums to `10`
* `><` gives `2 1 2` which sums to `5`
* gives `1` which sums to `1`
* `>>>>>>>>>` gives `10 9 8 7 6 5 4 3 2 1` which sums to `55`
* `>><<>><>>>` gives `3 2 1 2 3 2 1 4 3 2 1` which sums to `24`
* `><>><>><>` gives `2 1 3 2 1 3 2 1 2 1` which sums to `18`
* `<<<<>` gives `1 2 3 4 5 1` which sums to `16`
* `<<<<><<>` gives `1 2 3 4 5 1 2 3 1` which sums to `22`
* `>><<` gives `3 2 1 2 3` which sums to `11`

# Answer
> 3 votes
# Jelly, 19 bytes

```
0;+×¥@\
=”<µCṚÇṚ»Ç‘

```

Try it online!

The value of each number is **max(** number of `>` immediately to the right of it **,** number of `<` immediately to the left of it **) + 1** .

---

Alternatively...

Try it online!

# Answer
> 8 votes
# \>\<\>, ~~40~~ 38 bytes

```
1v!rnr~<oa
?\i:0(?^3%\+$
{/?:-{:}-1/1:

```

Try it online!

An appropriate language. For reference `><>` itself yields 2,1,2,1.

### How it Works:

```
1v   Initialise the stack as 1 and enter loop
 \i:0(?^  If we're out of input, go to the first line
        3%\ Otherwise mod the input by 3, yielding 0 for < and 2 for >
        -1/Subtract 1 to get -1 and 1 respectively
    -{:}   Copy the previous number and subtract the above from it

 /?:    If the number is not 0, repeat the loop

?\        \+$  Otherwise:
                Increment each number until we reach the original 0
{/        /1:   And enter the first loop again

      ~<    When we're out of input, pop the extra -1 from EOF
   rnr      Output the first number
1v!         Push a 1
        oa  Print a newline and repeat, popping the extra 1 each time

```

# Answer
> 5 votes
# Haskell, 119 bytes

```
n%">"=r[1..n]
n%"<"=[1..n]
n%(c:b)|c==b!!0=(n+1)%b|a:s<-2%b,e:z<-r$n%[c]=r z++last(max:[min|c>'<'])a e:s
r=reverse
(2%)

```

Try it online!

## Explanation

The idea here is that we have runs of either `>`s or `<`s, which each map to ascending and descending ranges. So we use `group` to split the string into groups of consecutive characters. Our job is to then stitch these together in the proper fashion.

When we have `<>` we want to stitch the two lists together taking the larger end value for example

```
<<<<<<>>

```

is split

```
<<<<<<  >>

```

mapped to ranges

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

```

Then when we stitch we drop `3` because it is smaller (`3` isn't larger than `7`).

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

```

When we have `><` we do the opposite, we drop the larger value.

The actual code attains this by making an operator `%`. The definition of `%` is quite complex, but basically it reads from left to right keeping track of how many consecutive characters are the same. It does this in the left had value of the operator. When we reach a place where the characters change we perform the stitching as I described.

# Answer
> 5 votes
# Python 3, 93 bytes

```
k=0
for r in input().split('<'):p=len(r);print(max(k,p)+1,*range(p,0,-1),end=' ');k=1+(p<1)*k

```

Try it online!

Unscrambled:

```
# offset, will be explained later
k = 0
for run in input().split('<'):
    # p = length of sequence of '>'s, which will produce p+1 decreasing integers
    p = len(run)
    # will print:
    # p+1 p p-1 ... 1    or    k+1 p p-1 ... 1
    print(max(k, p) + 1, *range(p, 0, -1), end=' ')
    # offset of the next sequence: (i.e. -1 + the minimal value of the first integer)
    k = 1 + (k if p > 0 else 0)

```

# Answer
> 4 votes
# Retina 0.8.2, 36 bytes

```

1
{`\b(1+)>\1
1$&
}`(1+)<\1\b
$&1
1

```

Try it online! Link includes test cases. Explanation:

```

1

```

Insert `1`s before, between and after the `<`s and `>`s.

```
{`\b(1+)>\1
1$&
}`(1+)<\1\b
$&1

```

Repeatedly increment integers until all the comparisons are satisfied.

```
1

```

Sum the integers and convert to decimal.

# Answer
> 3 votes
# Java 10, ~~198~~ ~~181~~ 180 bytes

```
s->{var p=s.split("(?<=(.))(?!\\1)");int l=p.length,L[]=new int[l],i=l,r=0,a,b;for(;i-->0;r-=a*~a/2+(i<l-1?p[i].charAt(0)<61?a<(b=L[i+1])?a:b:1:0))a=L[i]=p[i].length()+1;return r;}

```

-1 byte thanks to *@ceilingcat*.

Try it online.

**Explanation:**

```
s->{                     // Method with String parameter and integer return-type
  var p=s.split("(?<=(.))(?!\\1)");
                         //  Split the String into parts
                         //  (i.e. ">><<>><>>>" becomes [>>, <<, >>, <, >>>])
  int l=p.length,        //  Get the amount of parts
      L[]=new int[l],    //  Create an integer-array of the same size
      i=l,               //  Index-integer, starting at this size
      r=0,               //  Result-integer, starting at 0
      a,b;               //  Two temp integers to reduce the byte-count
  for(;i-->0;            //  Loop downwards over the array; range: (`l`,0]
      ;r-=               //    After every iteration: decrease the result with:
          a*~a/2         //     The negative triangle number of the current item
        +                //     And add to that negative triangle number before subtracting:
         (i<l-1?         //      If it's not the last item:
           p[i].charAt(0)<61?
                         //       And the order of the current and previous is "<>":
            a<(b=L[i+1])?//        If the current item in `L` is smaller than the previous:
             a           //         Add the current item
            :            //        Else (the current is equal or larger than the previous):
             b           //         Add the previous item
           :             //       Else (the order of the two parts is "><" instead):
            1            //        Add 1
          :              //      Else (it's the last item in `L`):
           0))           //       Leave the result `r` unchanged by adding 0
    a=L[i]=              //   Set both `a` and the current item in `L` to:
     p[i].length()+1;    //    The length of the part + 1
  return r;}             //  Return the result

```

# Answer
> 3 votes
# Haskell, 87 bytes

```
r=reverse
s#c=(+1).length.takeWhile(==c)<$>scanr(:)[]s
f s=zipWith max(s#'>')$r$r s#'<'

```

Try it online!

A port of my Jelly answer.

# Answer
> 2 votes
# Perl 5 `-p`, 53 bytes

```
#!/usr/bin/perl -p
s//1/g;1while s/(?=\b(1+)>\1)|(1+)<\2\b\K/1/;$_=y/1//

```

Try it online!

# Answer
> 2 votes
# Stax, 21 bytes

```
éda╓~/└↨☺∟╒←║ç Γφ5←9h

```

Run and debug it

It works by run-length encoding the input, and then concatenating generated ranges together. Unpacked, ungolfed, and commented, it looks like this.

```
|R      run-length encode
{       begin block
  H^R   range from [1 .. run length]
  _hh|1 -1 ** (character code / 2)
  *     multiply run; this will reverse it iff character is '>'
m       map runs using preceding block
O       push a 1 under the top of stack
{       begin block
  h|M   get the start of the generated range, and take max of it and top of stack
  _DE   push the rest (tail) of the generated range to the stack
F       foreach generated range
L|+     sum of all values on the stack

```

Run this one

# Answer
> 1 votes
# Red, 185 bytes

```
func[s][repeat n 1 + length? s[l: 0 i: n - 1 while[i > 0 and(s/(i) = #"<")][i:  i - 1 l: l + 1]r: 0 i: n while[(i <= length? s)and(s/(i) = #">")][i: i + 1 r:
r + 1]prin[1 + max l r""]]]

```

After user202729's explanation...

Try it online!

```
f: func[s][
   repeat n 1 + length? s[
       l: 0
       i: n - 1
       while [i > 0 and (s/(i) = #"<")][
           i: i - 1
           l: l + 1
        ]
        r: 0
        i: n
        while [(i <= length? s) and (s/(i) = #">")][
            i: i + 1
            r: r + 1
        ]
        prin[1 + max l r ""]
    ]
]

```

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