# Question
Title: Generating a single string with an Oxford comma from a list
What are some clever (brief and idiomatic) approaches to taking a list of strings and returning a single properly punctuated string built from the list, with each element quoted.

This came up for me while experimenting with Groovy, for which my too-literal, but illustrative solution is

```
def temp = things.collect({"\'${it}\'"})
switch (things.size()) {
    case 1:
        result = temp[0]
        break
    case 2:
        result = temp.join(" and ")
        break
    default:
        result = temp.take(temp.size()-1).join(", ") + ", and " + temp[-1]
        break
}

```

That is, `['1']` should yield `'1'`, `['1','2']` should yield `'1 and 2'`, \[see what I did there?\] and `['1','2','3']` should yield `'1, 2, and 3'`.

I have some good answers for Groovy, but I'd like to see what other languages can do.

What are some *compact* clever approaches in various languages that take advantage of the features and idioms of those languages?

# Answer
# CSS, ~~132~~ ~~116~~ 115 bytes

```
a:not(:last-child):nth-child(n+2):after,a:nth-last-child(n+3):after{content:","}a+:last-child:before{content:"and "
```

```
<p>
  <a>one</a>
</p>
<p>
  <a>one</a>
  <a>two</a>
</p>
<p>
  <a>one</a>
  <a>two</a>
  <a>three</a>
</p>
<p>
  <a>one</a>
  <a>two</a>
  <a>three</a>
  <a>four</a>
</p>
```

```
a:not(:last-child):nth-child(n+2):after,a:nth-last-child(n+3):after{content:","}a+:last-child:before{content:"and "

```

CSS is not seen too often in code golf because it can only format text, but it actually works for this challenge and I thought it would be fun to do. See it in action using the snippet above (click "Show code snippet").

List should be in a linked HTML file with each element surrounded by `<a>` tags and separated by line breaks. The list items should be the only elements in their parent element, e.g.

```
<a>one</a>
<a>two</a>
<a>three</a>

```

## Explanation

```
a:not(:last-child):nth-child(n+2)::after,
a:nth-last-child(n+3)::after {
    content: ",";
}

a + :last-child::before {
    content: "and ";
}

```

Let's consider the ungolfed version above. If you're not familiar with how CSS works, everything outside the curly braces is a selector that determines the set of HTML elements to which the declarations inside the braces apply. Each selector-declaration pair is called a *rule*. (It's more complicated than that but will suffice for this explanation.) Before any styling is applied, the list appears separated by only spaces.

We want to add commas after every word except the last, except for two-word lists, which get no commas. The first selector, `a:not(:last-child):nth-child(n+2):after`, selects all elements except the first and the last. `:nth-child(n+2)` is a shorter way of saying `:not(:first-child)`, and it basically works by selecting elements whose index (starting at 1) is greater than or equal to 2. (Yes, it still confuses me a little. The MDN docs might help.)

Now we just need to select the first element to get a comma *if* there are three or more elements total. `a:nth-last-child(n+3):after` works like `:nth-child`, but counting from the back, so it selects all elements except the last two. The comma takes the union of the two sets, and we use the `:after` pseudo-element to add `content` immediately after each selected element.

The second rule is easier. We need to add "and" before the last element in the list, unless it is a single element. In other words, we need to select the last element that is preceded by another element. `+` is the adjacent sibling selector in CSS.
> 77 votes

# Answer
# Haskell: ~~81, 77~~ 74 chars

```
f[x]=x
f[x,y]=x++" and "++y
f[x,y,z]=x++", "++f[y++",",z]
f(x:y)=x++", "++f y

```

Haskell features: Pattern matching
> 13 votes

# Answer
## Ruby, 47 bytes

```
q=" and ";p$*[2]?(a=$*.pop;$**", "+?,+q+a):$**q

```

### Explanation

* The input are the command line arguments (`$*`).
* When `$*` has a third element (`$*[2]` does not return nil), take all elements minus the last one and turn them into a comma-separated String using `Array#*`. Finally add an extra comma, the string `" and "` and the last command line argument.
* When `$*` has no third element, two, one, or zero arguments were given. The arguments can safely be joined with the string `" and "` and produce the correct result.
> 7 votes

# Answer
# Python 2 (61)

```
s=input()
d=s.pop()
print", ".join(s)+", and "[8-7*len(s):]+d

```

The main trick is to cut off part of the final joiner `", and "` for one and two elements. For one, all of it is cut out, and for two, the comma is removed. This is done by slicing out `[8-7*len(s):]` (noting that `s` is one shorter after the `pop`).

Unfortunately, `d` cannot just be replaced with its expression or the `pop` would happen too late.
> 6 votes

# Answer
# Perl (v 5.10+) - ~~37~~ ~~35~~ ~~34~~ 28

```
@F>2&&s/ /, /g;s/.* \K/and /

```

to be run with `perl -ape`, with the list supplied space separated on `STDIN`.

Output for various inputs:

```
$ perl -ape '@F>2&&s/ /, /g;s/.* \K/and /'
oxford
oxford
oxford cambridge
oxford and cambridge
oxford cambridge comma
oxford, cambridge, and comma
oxford cambridge comma space
oxford, cambridge, comma, and space

```
> 6 votes

# Answer
# CSS, ~~62 chars~~ 112 chars

Inspired by the other entries, even shorter. Note that it requires that A elements are not separated by white spaces:

```
a+a:before{content:", "}a+a:last-child:before{content:", and "

```

http://jsfiddle.net/olvlvl/1Ls79ocb/

Fix for the "one and two", as pointed at by Dennis:

```
a+a:before{content:", "}a+a:last-child:before{content:", and "}a:first-child+a:last-child:before{content:" and "

```

http://jsfiddle.net/olvlvl/1Ls79ocb/3/
> 6 votes

# Answer
# GNU sed - 69 chars including 1 for `-r` flag

```
s/ /, /g
s/( [^ ]+)( [^ ]+)$/\1 and\2/
s/^([^,]+),([^,]+)$/\1 and\2/

```

Takes a space-separated list (fairly idiomatic for shell scripts).

## Example

```
$ sed -r -f oxfordcomma.sed <<< "1"
1
$ sed -r -f oxfordcomma.sed <<< "1 2"
1 and 2
$ sed -r -f oxfordcomma.sed <<< "1 2 3"
1, 2, and 3
$

```
> 4 votes

# Answer
# Javascript (63)

`l=a.length;l>2&&(a[l-1]='and '+a[l-1]);a.join(l>2?', ':' and ')`

Cases:

* `a = [1]` =\> `1`
* `a = [1, 2]` =\> `1 and 2`
* `a = [1, 2, 3]` =\> `1, 2, and 3`

Caveat: this will modify the last element in an array with length \> 2.
> 4 votes

# Answer
## Groovy, ~~47 43~~ 57 characters , JavaScript ES6 56 characters

**Groovy:**

```
(a[1]?a[0..-2].join(", ")+(a[2]?",":"")+" and ":"")+a[-1]

```

Since the array is filled with characters, we can replace `a.size>1` by `a[1]`

**JavaScript, ES6:**

```
a.join(', ').replace(/,([^,]+)$/,`${a[2]?',':''} and$1`)

```

Both cases assume that variable a has the array in question.
> 3 votes

# Answer
# Python 2 - ~~71, 70~~ 68

```
s=input()
l=len(s)-1
print', '.join(s[:l])+', and '[l<2:]*(l>0)+s[l]

```

Character count including both, `input` and `print`.
> 3 votes

# Answer
# CJam, ~~35~~ ~~30~~ ~~28~~ 27 bytes

```
q~)\_"and "L?@+a+_,2=", ">*

```

This is a program that reads from STDIN and prints to STDOUT. Try it online.

### How it works

```
q~                                     " Q := eval(input())                               ";
  )                                    " P := Q.pop()                                     ";
   \_"and "L?@+                        " P := (Q ? 'and ' : '') + P                       ";
                a+                     " Q += [P]                                         ";
                  _,2=", ">            " J := ', '[(len(Q) == 2):]                        ";
                           *           " R := J.join(Q)                                   ";
                                       " print R (implicit)                               ";

```

### Example run

```
$ cjam <(echo 'q~)\_"and "L?@+a+_,2=", ">*') <<< '["1"]'; echo
1
$ cjam <(echo 'q~)\_"and "L?@+a+_,2=", ">*') <<< '["1""2"]'; echo
1 and 2
$ cjam <(echo 'q~)\_"and "L?@+a+_,2=", ">*') <<< '["1""2""3"]'; echo
1, 2, and 3
$ cjam <(echo 'q~)\_"and "L?@+a+_,2=", ">*') <<< '["1""2""3""4"]'; echo
1, 2, 3, and 4

```
> 3 votes

# Answer
## Ruby, 57 bytes

```
f=->l{s=l*', ';s.sub(/,(?!.*,)/,(l.size<3?'':?,)+' and')}

```

I'm joining the string with `,` and then I'm replacing the last comma in the string with an `and` (and optional comma depending on list length).
> 3 votes

# Answer
# Cobra - 60

```
do(l as String[])=l.join(', ',if(l.length<3,'',',')+' and ')

```

Cobra's `List<of T>.join` function lets you specify a different separator for the final two elements of the list, which is what makes this so short.
> 3 votes

# Answer
## Batch - 151 Bytes

```
@echo off&set f=for %%a in (%~1)do
%f% set/aa+=1
%f% set/ac+=1&if !c!==1 (set o=%%a)else if !c!==!a! (set o=!o!, and %%a)else set o=!o!, %%a
echo !o!

```

Note; you have to call the script from `cmd` with the `/v` switch set as `on`, this is so I don't have to include the lengthy `setLocal enableDelayedExpansion` in the script. Otherwise add 30 to the byte count, and call the script normally.

```
h:\uprof>cmd /von /c test.bat "1 2 3"
1, 2, and 3

h:\uprof>cmd /von /c test.bat "1 2 3 4 5"
1, 2, 3, 4, and 5

```
> 3 votes

# Answer
# PHP, ~~192~~ ~~167~~ ~~146~~ 136 characters:

```
$n=' and ';$s=count($a);echo ($s<3)?join($n,$a):join(', ',array_merge(array_slice($a,0,$s-2),Array(join(",$n",array_slice($a,-2,2)))));

```

Based on a function I wrote years ago at http://www.christopherbloom.com/2011/05/21/join-implode-an-array-of-string-values-with-formatting/
> 3 votes

# Answer
# Perl - 59

```
sub f{$a=join', ',@_;$#_&&substr$a,(@_>2)-3,@_<3,' and';$a}

```

Joins the list with commas, then if the list has more than one element, either adds `' and'` after the last comma (if length \>= 3), or replaces the last comma with it (if length == 2).
> 3 votes

# Answer
# PHP, ~~86~~ 84 chars

```
$a = ['one', 'two', 'three', 'four', 'five'];

```

With the array initialized, we start counting:

```
$L=count($a)-1;$S=', ';$L<2?($S=' and '):($a[$L]='and '.$a[$L]);echo implode($S,$a);

```

Prettified:

```
$last_index = count($a) - 1;
$separator = ', ';
if ($last_index < 2) {
    $separator = ' and ';
} else {
    $a[$last_index] = 'and '.$a[$last_index];
}
echo implode($separator, $a);

```

The last item in the list is modified. This should be OK because in PHP, array assignment and function calls perform copies.
> 3 votes

# Answer
# Google Sheets, ~~67~~ ~~68~~ ~~67~~ 92 bytes

```
=SUBSTITUTE(JOIN(", ",FILTER(A:A,A:A<>"")),",",IF(COUNTA(A:A)>2,",","")&" and",COUNTA(A:A)-1

```

The input starts at cell `A1` and continuing down for however many entries exist.
`JOIN` merges them all into a string with a comma-space between each.
`FILTER` removes any non-blanks so you don't end up with infinite commas at the end.
`SUBSTITUTE` replaces the last comma (found by `COUNTA` counting the non-blank inputs).

It's not very exciting but it's doable in a single cell.
> 3 votes

# Answer
# Vyxal, 27 bytes

```
ṫ$:[`λ¬ `pJ:Ḣ₃[÷ð$Ṡ|‛, j]|_

```

Try it Online!

```
ṫ                           # Tail extract (x[:-1], x[-1] )
 $:[                        # If length > 1
    `λ¬ `p                  # Prepend a 'and '
          J                 # Merge
           :Ḣ₃[             # If length = 2
               ÷ð$Ṡ         # Add in a space and join
                   |    ]   # Else...
                    ‛, j    # Join by ', '
                         |_ # Else pop

```
> 3 votes

# Answer
# JavaScript (ES6) 60

Assuming no empty strings in input array

```
f=(a,b=a.pop())=>a[0]?a.join(', ')+(a[1]?',':'')+' and '+b:b

```

**Test** In FireFox/Firebug console

```
console.log(f(['We invited the stripper','JFK','Stalin']))

```

*Output*

```
 We invited the stripper, JFK, and Stalin

```
> 2 votes

# Answer
# JavaScript - ~~60~~ ~~56~~ ~~71~~ ~~67~~ 63

Not exactly an idiomatic approach, but I had fun writing it and I like regex.

Assuming the array is stored in `var a`:

```
a.join((a.length>2?',':'')+' ').replace(/([^,\s])$/,"and $1")

```

Shortened by simply checking for index `[2]`: (yay boolean coercion)

```
a.join((!!a[2]?',':'')+' ').replace(/([^,\s])$/,'and $1')

```

Apparently I suck at testing and skipped a single-entry test. Here's the fixed version:

```
a.join((!!a[2]?',':'')+' ').replace(/([^,\s])$/,(!!a[1]?'and ':'')+'$1')

```

Shaved off 2 chars by inverting my booleans and 3 more by moving the space from the concatenation into the then/else of the first ternary:

```
a.join((!a[2]?' ':', ')).replace(/([^,\s])$/,(!a[1]?'':'and ')+'$1')

```

Thanks to @tomsmeding for reminding me that I don't have to coerce my booleans because JS does that for me. I also realised I forgot to remove the parentheses separating the first ternary from the concatenation inside the `join()`:

```
a.join(a[2]?', ':' ').replace(/([^,\s])$/,(a[1]?'and ':'')+'$1')

```

Did I do that right? Obligatory new golfer apology.
> 2 votes

# Answer
## Golfscript - 31 39 34 30

Hello, World! I am a long time lurker, first time poster. Here is my 30 byte solution in Golfscript (given the array such as \[1 2 3\] is already on the stack).

```
.,3<" and ":A{~A(;\+]", "}if*

```

The results are proper for all test cases.

EDIT: Take that, CJam!
> 2 votes

# Answer
# Xojo, ~~52~~ ~~71~~ 83 chars

```
dim i as int8=ubound(L)
L(i)=if(i=0,"","and ")+L(i)
Return L.Join(if(i=1," ",", ")

```

Note that UBound is one less than the array length.
> 2 votes

# Answer
# Excel VBA, 108 Bytes

Anonymous VBE immediate window function that takes input as space delimited array from range `A1` and outputs to the VBE immediate window.

```
x=Split([A1]):y=UBound(x):For i=0To y-2:?x(i)", ";:Next:If y>0Then?x(i)IIf(y>1,",","")" and "x(i+1)Else?[A1]

```
> 2 votes

# Answer
# Racket 87

```
(define(f x)(string-join(map ~a x)", "#:before-last(if(= 2(length x))" and "", and ")))

```
> 1 votes

# Answer
# Python 62 chars

Assuming that i is the list of strings:

```
(" and", ", and")[len(i) < 2].join(", ".join(i).rsplit(",",1))

```
> 1 votes

# Answer
**C# 102 Chars**

```
var i=m.Count(),l=i;if(l>2)l--;var r=string.Join(", ",m.Take(l));if(l!=i)r+=" and "+m.Last();return r;

```
> 1 votes

# Answer
# Julia (53)

```
print(join(ARGS,", ",(endof(ARGS)>2?",":"")" and "))

```

Takes args from STDIN and outputs to STDOUT

Solution using Base.join(items, delim\[, last\])

Edit:

Test cases

```
julia oxfordComma.jl 1

```

1

```
julia oxfordComma.jl 1 2

```

1 and 2

```
julia oxfordComma.jl 1 2 3

```

1, 2, and 3
> 1 votes

# Answer
# Rant (108)

```
[$[l:@b]:[r:each][s:[cmp:[rc];2;[is:different;,]]\s][before:[last:[notfirst:and\s]]][sync:;ordered][arg:b]]

```

Ungolfed:

```
[$[l:@b]:
    [r:each]                            # Repeat for each item
    [s:[cmp:[rc];2;[is:different;,]]\s] # Separate by comma if n > 2
    [before:[last:[notfirst:and\s]]]    # Insert "and" before last item
    [sync:;ordered]                     # Force forward order
    [arg:b]                             # Read list
]

```

Usage:

```
[$l:{A|B|C|D|E}]

```

Try it online
> 1 votes

# Answer
# Pyth, 28

```
j>", "qlQ2+_t_Q+?"and "tQkeQ

```

### Examples:

```
$ pyth programs/oxford.pyth <<< "['1']"
1

$ pyth programs/oxford.pyth <<< "['1','2']"
1 and 2

$ pyth programs/oxford.pyth <<< "['1','2','3']"
1, 2, and 3

```
> 1 votes

# Answer
# Haskell, 67 bytes

```
f[n]=n
f[m,n]=m++" and "++n
f n=(init n>>=(++", "))++"and "++last n

```

Abuses the list monad a bit

## Explanation

Doing this later
> 1 votes

# Answer
# Python, 79 chars

Note: the char count does not include the list declaration.

```
l=['1','2','3']
print l[0] if len(l)<2 else (', '.join(l[:-1])+(',' if len(l)>2 else '')+' and '+l[-1])

```

Output for various inputs:

```
1
1 and 2
1, 2, and 3
...

```
> 0 votes

# Answer
# Golfscript (61)

The fact that Javascript and others score better pretty much shows that this is probably not done very efficiently in terms of golfing.

```
.,.2={;' and '*}{(\{\(.{.)', '''if}{', and '}if@\+print}/;}if

```

Examples with link to try it out:
> 0 votes

# Answer
# Perl 5 + Moose, 70 bytes

```
sub english_list{@_<3?join" and ",@_:do{$_="and ".pop;join", ",@_,$_}}

```

Not many people seem to know it, but Moose, the popular OO framework for Perl 5, has a function to do this built in. (Moose uses it internally in its error messages, but exposes it as a documented, public function.)

```
my @l = (1 .. 3);
use Moose;
print Moose::Util::english_list(@l);

```

Excluding the definition of the list `@l`, that can be easily golfed down to 41 characters. If you allow the use of the `say` function which was introduced in Perl 5.10, you can knock off two more characters. (I'll leave it as an exercise for the reader.)

Now, looking at the definition of the `english_list` function itself, the best I've been able to golf it down to is 70 characters:

```
sub english_list{@_<3?join" and ",@_:do{$_="and ".pop;join", ",@_,$_}}

```

... though obviously by choosing a shorter function name, that could be reduced further. (59 characters if you choose a one-letter function name.)
> 0 votes

# Answer
## Groovy - 221 chars

This is not a compact implementation, but the usage is tight: it overrides `toString()` for `ArrayList` via meta-class functionality (and maps - no conditionals here!).

This is powerful stuff, but idiomatic when writing a framework. That is, the change is transparent to the client.

Golfed (assumes variable `a` is defined):

```
q={s->"'$s'"}
r={q a[it]}
f={"${it[0..-2].join ", "}, and ${it[-1]}"}
m=[:].withDefault{f}
m[0]={""}
m[1]={r 0}
m[2]={"${r 0} and ${r 1}"}
ArrayList.metaClass.toString={->m[delegate.size()].call(delegate.collect{q(it)})}

```

Sample assertions:

```
a=['oxford','cambridge','comma','space']
assert "'oxford', 'cambridge', 'comma', and 'space'" == a.toString()

a=['oxford','cambridge']
assert "'oxford' and 'cambridge'" == a.toString()

a=['oxford']
assert "'oxford'" == a.toString()

a=[]
assert "" == a.toString()

```

Ungolfed:

```
q = {s->"'$s'"}
r = {q a[it]}

f = {"${it[0..-2].join ", "}, and ${it[-1]}"}
m = [:].withDefault{f}
m[0] = {""}
m[1] = {r 0}
m[2] = {"${r 0} and ${r 1}"}

ArrayList.metaClass.toString = { ->
    m[ delegate.size() ].call( delegate.collect{q(it)} )
}

```
> 0 votes

# Answer
# bash (79)

```
(($#<3))&&echo $1 ${2/#/and }||{ Y=${@/%/,};L=${@: -1};echo ${Y/%$L,/and $L}; }

```

## Explaination

For 1 or 2 parameters

* echo $1 and, if $2 exists, prefix $2 with "and ".

Otherwise

* suffix all parameters with a comma and join together
* get last parameter
* replace "$L," with "and $L"
> 0 votes

# Answer
# PHP, 67

```
if($c=count($a)-1)$a[$c]='and '.$a[$c];echo join($c-1?', ':' ',$a);

```

If there's more than one item, prepend the last with `'and '`. (store the count minus one in `$c`).

Next, join on space or comma space, depending on whether the count is two.

```
if ($c = count($a) - 1) {
    $a[$c] = 'and '.$a[$c];
}
echo join($c - 1 ? ', ' : ' ', $a);

```
> 0 votes

# Answer
# SmileBASIC, 80 bytes

```
DEF L A
L=LEN(A)WHILE LEN(A)>1?SHIFT(A);","*(L>2);" ";
WEND?"and "*(L>1);A[0]END

```
> 0 votes

# Answer
# Ruby, 44 bytes

```
->*f,l{f[0]?f*', '+(f[1]??,:'')+' and '+l:l}

```

Try it online!
> 0 votes

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


title: Histogram generation

text:
# Question
Title: Histogram generation
Write the shortest program that generates a histogram (a graphical representation of the distribution of data).

**Rules:**

* Must generate a histogram based on the character length of the words (punctuation included) input into the program. (If a word is 4 letters long, the bar representing the number 4 increases by 1)
* Must display bar labels that correlate with the character length the bars represent.
* All characters must be accepted.
* If the bars must be scaled, there needs to be some way that is shown in the histogram.

**Examples:**

```
$ ./histogram This is a hole in one!
1 |#
2 |##
3 |
4 |###

$./histogram Extensive word length should not be very problematic.
1 |
2 |#
3 |#
4 |##
5 |
6 |##
7 |
8 |
9 |#
10|
11|
12|#

./histogram Very long strings of words should be just as easy to generate a histogram just as short strings of words are easy to generate a histogram for.
1 |##
2 |#######
3 |#
4 |#######
5 |###
6 |#
7 |##
8 |##
9 |##

```

# Answer
> 3 votes
# K, 35

```
{(1+!|/g)#`$(#:'=g:#:'" "\:x)#'"#"}

```

.

```
k){(1+!|/g)#`$(#:'=g:#:'" "\:x)#'"#"}"Very long strings of words should be just as easy to generate a histogram just as short strings of words are easy to generate a histogram for."
1| ##
2| #######
3| #
4| #######
5| ###
6| #
7| ##
8| ##
9| ##

```

.

A longer example

```
k){(1+!|/g)#`$(#:'=g:#:'" "\:x)#'"#"}"Please write a specification rather than giving a single example which, solely by virtue of being a single example, cannot express the range of acceptable output styles, and which doesnt guarantee to cover all corner cases. Its good to have a few test cases, but its even more important to have a good spec."
1 | #####
2 | ######
3 | #######
4 | ########
5 | ######
6 | ##############
7 | ###
8 | #
9 | ##
10| #
11|
12|
13| #

```

# Answer
> 6 votes
# R, ~~55~~ 47 characters

```
hist(a<-sapply(scan(,""),nchar),br=.5+0:max(a))

```

Luckily R comes with a plot function `hist` for histograms, here supplied with a `breaks` argument where the breaks are 0.5, 1.5, ... until max(input)+0.5. `sapply(scan(,""),nchar)` takes an input (as stdin), separates it following the spaces and count the number of characters of each element.

Examples:

```
hist(a<-sapply(scan(,""),nchar),br=.5+0:max(a))
1: Extensive word length should not be very problematic.
9:
Read 8 items

```

```
hist(a<-sapply(scan(,""),nchar),br=.5+0:max(a))
1: Very long strings of words should be just as easy to generate a histogram just as short strings of words are easy to generate a histogram for.
28:
Read 27 items

```

### Edit:

A variation at **71 characters** with an axis label at each possible value:
```
hist(a<-sapply(scan(,""),nchar),br=.5+0:max(a),ax=F);axis(1,at=1:max(a))

```

# Answer
> 5 votes
## Python - 83 characters

Seems that we can take input from anywhere, so this takes input during execution, rather than from the command line, and uses Ejrb's suggestion to shorten it by 8.

```
s=map(len,raw_input().split())
c=0;exec'c+=1;print"%3d|"%c+"#"*s.count(c);'*max(s)

```

### Python - 91 characters

This will fall over with quotes.

```
import sys;s=map(len,sys.argv[1:])
for i in range(1,max(s)+1):print"%3d|"%i+'#'*s.count(i)

```

Input:

```
> python hist.py Please write a specification rather than giving a single example which, solely by virtue of being a single example, cannot express the range of acceptable output styles, and which doesnt guarantee to cover all corner cases. Its good to have a few test cases, but its even more important to have a good spec.

```

Output:

```
  1|#####
  2|######
  3|#####
  4|##########
  5|######
  6|#############
  7|####
  8|#
  9|##
 10|#
 11|
 12|
 13|#

```

# Answer
> 4 votes
## Haskell - 126 characters

```
p[d]=[' ',d];p n=n
h l=[1..maximum l]>>= \i->p(show i)++'|':(l>>=($"#").drop.abs.(i-))++"\n"
main=interact$h.map length.words

```

This takes the input from `stdin`, not the command line:

```
& head -500 /usr/share/dict/words | runhaskell 15791-Histogram.hs
 1|##
 2|##
 3|######
 4|###############
 5|################################################
 6|###############################################################
 7|###################################################################
 8|###########################################################################
 9|#############################################################
10|##########################################################
11|#########################################################
12|#########################
13|#######
14|###
15|#####
16|###
17|#
18|
19|#
20|#

```

# Answer
> 3 votes
## Perl, 56

```
$d[y///c].='#'for@ARGV;printf"%2d|$d[$_]
",$_ for+1..$#d

```

Added @manatwork's rewrite and literal newline suggestion, thank you very much! Added @chinese\_perl\_goth's updates.

Usage: save as hist.pl and run `perl hist.pl This is a test`

Example output:

```
$perl ~/hist.pl This is a test of the histogram function and how it will count the number of words of specific lengths. This sentence contains a long word 'complexity'.
 1|##
 2|#####
 3|####
 4|######
 5|##
 6|#
 7|
 8|#####
 9|#
10|
11|#

```

# Answer
> 3 votes
## APL (42)

```
⎕ML←3⋄K,⊃⍴∘'▓'¨+⌿M∘.=K←⍳⌈/M←↑∘⍴¨I⊂⍨' '≠I←⍞

```

Could be shorter if I could omit lines where the value is 0.

Explanation:

* `⎕ML←3`: set the migration level to 3 (this makes  (partition) more useful).
* `I⊂⍨' '≠I←⍞`: read input, split on spaces
* `M←↑∘⍴¨`: get the size of the first dimension of each item (word lengths), and store in `M`
* `K←⍳⌈/M`: get the numbers from 1 to to the highest value in `M`, store in `K`
* `+⌿K∘.=M`: for each value in `M`, see how many times it is contained in `K`.
* `⊃⍴∘'▓'¨`: for each value in that, get a list of that many s, and format it as a matrix.
* `K,`: prepend each value in `K` to each row in the matrix, giving the labels.

Output:

```
      ⎕ML←3⋄K,⊃⍴∘'▓'¨+⌿M∘.=K←⍳⌈/M←↑∘⍴¨I⊂⍨' '≠I←⍞
This is a hole in one!
1 ▓
2 ▓▓
3
4 ▓▓▓
      ⎕ML←3⋄K,⊃⍴∘'▓'¨+⌿M∘.=K←⍳⌈/M←↑∘⍴¨I⊂⍨' '≠I←⍞
Very long strings of words should be just as easy to generate a histogram just as short strings of words are easy to generate a histogram for.
1 ▓▓
2 ▓▓▓▓▓▓▓
3 ▓
4 ▓▓▓▓▓▓▓
5 ▓▓▓
6 ▓
7 ▓▓
8 ▓▓
9 ▓▓

```

# Answer
> 3 votes
# Python 3.3 (93)

```
a=[len(i) for i in input().split()]
for i in range(1,max(a)+1):
 print(i,'|',"#"*a.count(i))

```

Output:
(the first line is the input string)

```
Very long strings of words should be just as easy to generate a histogram just as short strings of words are easy to generate a histogram for.
1 | ##
2 | #######
3 | #
4 | #######
5 | ###
6 | #
7 | ##
8 | ##
9 | ##

```

It doesn't justify numbers as Lego Stormtroopr's Python solution (which is also shorter than mine), but it's my first entry ever in a golfing contest, so I might as well leave it here I guess :)

# Answer
> 3 votes
## J, 48 47 46 45 43 characters

```
(;#&'#')/"1|:((],[:+/=/)1+[:i.>./)$;._1' ',

```

Usage:

```
   (;#&'#')/"1|:((],[:+/=/)1+[:i.>./)$;._1' ','Very long strings of words should be just as easy to generate a histogram just as short strings of words are easy to generate a histogram for.'
┌─┬───────┐
│1│##     │
├─┼───────┤
│2│#######│
├─┼───────┤
│3│#      │
├─┼───────┤
│4│#######│
├─┼───────┤
│5│###    │
├─┼───────┤
│6│#      │
├─┼───────┤
│7│##     │
├─┼───────┤
│8│##     │
├─┼───────┤
│9│##     │
└─┴───────┘

```

# Answer
> 2 votes
# Ruby, ~~98~~ 85

```
a=$*.group_by &:size
1.upto(a.max[0]){|i|b=a.assoc i
puts"%-2i|#{b&&?#*b[1].size}"%i}

```

Not golfed much. Will golf more later.

```
c:\a\ruby>hist This is a test for the histogram thingy. yaaaaaaaaaaaay
1 |#
2 |#
3 |##
4 |##
5 |
6 |
7 |#
8 |
9 |#
10|
11|
12|
13|
14|#

```

# Answer
> 2 votes
## Powershell, ~~97~~ 93

```
$a=@{};$args-split ' '|%{$a[$_.length]++};1..($a.Keys|sort)[-1]|%{"{0,-2} |"-f $_+"#"*$a[$_]}

```

Example:

```
PS Z:\> .\hist.ps1 This is an example of this program running
1  |
2  |###
3  |
4  |##
5  |
6  |
7  |###

```

# Answer
> 2 votes
# Mathematica 97

```
Histogram["" <> # & /@ StringCases[StringSplit[InputString[]], WordCharacter] /.
a_String :> StringLength@a]

```

When I input text of the Declaration of Independence as a single string (through cut and paste, of course), the output generated was:

# Answer
> 2 votes
## Ruby, 79

```
(1..(w=$*.group_by &:size).max[0]).map{|i|puts"%2i|#{?#*w.fetch(i,[]).size}"%i}

```

Example run:

```
$ ruby hist.rb Histograms, histograms, every where, nor any drop to drink.
 1|
 2|#
 3|##
 4|#
 5|#
 6|##
 7|
 8|
 9|
10|
11|##

```

Please see my Forth submission for a laugh.

# Answer
> 2 votes
## Forth, 201

This was fun but my Ruby submission is more competitive. ;-)

```
variable w 99 cells allot w 99 cells erase : h begin
1 w next-arg ?dup while swap drop dup w @ > if dup w
! then cells + +! repeat w @ 1+ 1 ?do i . 124 emit i
cells w + @ 0 ?do 35 emit loop cr loop ; h

```

Sample run:

```
$ gforth histo.fth Forth words make for tough golfing!
1 |
2 |
3 |#
4 |#
5 |###
6 |
7 |
8 |#

```

Max word length is 99.

# Answer
> 2 votes
**Ruby 1.8.7, 74**

A slightly different take than the other ruby solutions:

```
i=0;$*.map{|v|v.size}.sort.map{|v|$><<(i+1..v).map{|n|"
%2i:"%i=n}+['#']}

```

output:

```
ruby hist.rb `head -400 /usr/share/dict/words`

 1:#
 2:###
 3:######
 4:#############################
 5:#####################################################
 6:############################################################
 7:########################################################################
 8:######################################################
 9:############################################################
10:########################
11:###########################
12:######
13:#####

```

# Answer
> 1 votes
# JavaScript (159 133)

Definitely not competitive, but so far the only JavaScript solution. Thanks to @manatwork for the tip on using `String.replace`.

```
prompt(o=[]).replace(/\S+/g,function(p){o[l=p.length]=(o[l]||'')+'#'});for(i=1;i<o.length;)console.log(i+(i>9?"|":" |")+(o[i++]||""))

```

### Input

> Code Golf is a question and answer site for programming puzzle enthusiasts and code golfers. It's built and run by you as part of the Stack Exchange network of Q&A sites. With your help, we're working together to build a library of programming puzzles and their solutions.

### Output

```
1 |##
2 |#######
3 |#########
4 |########
5 |######
6 |###
7 |####
8 |####
9 |
10|#
11|###

```

# Answer
> 1 votes
### Pure bash, ~~120~~ 107 bytes

```
d=$*;d=${d//[ -z]/#};for a;do((b[${#a}]++));done;e=${!b[*]};for((i=0;i++<${e##* };)){ echo $i ${d:0:b[i]};}

```

or

```
d=$*
d=${d//[ -z]/#}
for a;do((b[${#a}]++));done
e=${!b[*]}
for((i=0;i++<${e##* };)){
echo $i ${d:0:b[i]}
}

```

or

```
d=$*;d=${d//[ -z]/#};for a;do((b[${#a}]++));done;e=${!b[*]}
for((i=0;i++<${e##* };)){ echo $i ${d:0:b[i]};}

```

Sample:

```
./histogram.sh Very long strings of words should be just as easy to generate a histogram just as short strings of words are easy to generate a histogram for.
1 ##
2 #######
3 #
4 #######
5 ###
6 #
7 ##
8 ##
9 ##

```

# Answer
> 1 votes
## PHP, 162

```
<?php error_reporting(0);$b=0;while($argv[$b])$c[strlen($argv[++$b])]++;for($t=1;$t<=max(array_keys($c));$t++)echo $t.'|'.($c[$t]?str_repeat('#',$c[$t]):'')."\n";

```

Usage:

```
php histogram.php Very long strings of words should be just as easy to generate a histogram just as short strings of words are easy to generate a histogram for.
1|##
2|#######
3|#
4|#######
5|###
6|#
7|##
8|##
9|##

```

# Answer
> 1 votes
# 8th, 162 bytes

**Code**

```
a:new ( args s:len nip tuck a:@ ( 0 ) execnull rot swap n:1+ a:! ) 0 argc n:1- loop
a:len n:1- ( dup . "|" . a:@ ( 0 ) execnull "#" swap s:* . cr ) 1 rot loop bye

```

**Usage**

```
$ 8th histogram.8th Nel mezzo del cammin di nostra vita mi ritrovai per una selva oscura

```

**Output**

```
1|
2|##
3|####
4|#
5|##
6|###
7|
8|#

```

**Ungolfed code** (**SED** is Stack Effect Diagram)

```
a:new               \ create an empty array
(
    args s:len      \ length of each argument
                    \ SED: array argument lengthOfArgument
    nip             \ SED: array lengthOfArgument
    tuck            \ SED: lengthOfArgument array lengthOfArgument
    a:@             \ get item array at "lengthOfArgument" position
    ( 0 ) execnull  \ if null put 0 on TOS
                    \ SED: lengthOfArgument array itemOfArray
    rot             \ SED: array itemOfArray lengthOfArgument
    swap            \ SED: array lengthOfArgument itemOfArray
    n:1+            \ increment counter for the matching length
    a:!             \ store updated counter into array
) 0 argc n:1- loop  \ loop through each argument
\ print histogram
a:len n:1- ( dup . "|" . a:@ ( 0 ) execnull "#" swap s:* . cr ) 1 rot loop
bye                 \ exit program

```

# Answer
> 1 votes
# Husk, 28 bytes

```
Ṡz+öTT' msŀSomȯ:'|R'##oḣ▲mLw

```

Try it online!

Husk is an ASCII art language.

# Answer
> 0 votes
# APL (Dyalog Unicode), 31 bytes (SBCS)

Anonymous tacit prefix function.

```
(I,'#'⍴⍤0⍨1⊥⊢∘.=I←⍳⌈/)'\S+'⎕S 1

```

Try it online!

`'\S+'⎕S 1`**S**earch for runs of non-**S**pace characters, returning the length of each

`(``)` apply the following tacit function to that list of lengths:

`⌈/` the largest number (lit. maximum reduction)

the indices 1…that

`I←` let `I` denote that function

`⊢∘.=` equality table of word lengths vertically and possible word lengths horizontally

`1⊥` sum the columns (lit. evaluate in base 1, with each row representing a digit)

`'#'⍴⍤0⍨` use each element to reshape the hash character, then stack the results and pad

`I,` prepend the result of `I` (i.e. all the possible lengths) as an additional column on the left

---
Tags: code-golf, graphical-output, generation
---


# Question
Title: Graphical Representation of Koch Snowflake
# Generate a Koch Snowflake

A Koch snowflake is a triangle that for each `n`, another equilateral point is added in the middle of each side: http://en.wikipedia.org/wiki/Koch\_snowflake#Properties

We already had a Koch Snowflake challenge for `n=4`. The new challenge is to draw a Koch snowflake with any `n` between `1` and `10`.

# Rules

> The snowflakes may not be hardcoded in the program or in files - they must be generated by your program.
>
> Your program must support all sized `n` between 1 and 10.
>
> The number of sides must be input by the user through std-in.
>
> You must print a graphical representation of the snowflake to the screen.

Sample Koch Snowflakes with `n` equaling 1, 2, 3, and 4 (green lines for clarity only, do not reproduce them):

In the event of a tie-breaker, the program with the highest number of upvotes wins (pop-contest).

# Answer
> 7 votes
**Mathematica 72**

```
Region@Line@AnglePath[Nest[Join@@({#,1,4,1}&/@#)&,{4,4,4},Input[]-1]π/3]

```

n=3

Thanks for alephalpha.

# Answer
> 16 votes
# MATLAB, ~~119~~ 115

In an unusual turn of events, I found that this program actually worked better as I golfed it. First, it became much faster due to vectorization. Now, it displays a helpful prompt `~n:~` reminding the user of which quantity to enter!

Newlines are not part of the program.

```
x=exp(i*pi/3);
o='~n:~';
P=x.^o;
for l=2:input(o);
P=[kron(P(1:end-1),~~o)+kron(diff(P)/3,[0 1 1+1/x 2]) 1];
end;
plot(P)

```

n = 9:

`o` is an arbitrary string which is equal to `[0 2 4 0]` modulo 6. eiπ/3 raised to these powers gives the vertices of an equilateral triangle in the complex plane. The first `kron` is used to make a copy of the list of points with each one duplicated 4 times. `~~o` is the convenient way to get a vector of 4 ones. Secondly `diff(P)` finds the vector between each pair of consecutive points. Multiples of this vector (0, 1/3, (1 + e-iπ/3)/3, and 2/3) are added to each of the old points.

# Answer
> 10 votes
# LOGO: 95

```
to w:c ifelse:c=1[fd 2 lt 60][w:c-1 w:c-1 lt 180 w:c-1 w:c-1]end
to k:c repeat 3[w:c rt 180]end

```

Defines function `k` with a single level parameter.

### Edit

In the this online editor http://www.calormen.com/jslogo/ you can add `k readword` to use prompt for input, but for some reason this command does not support the standard abbreviation `rw`.

The 102 characters solution below works in USBLogo with standard input as specified in the question. However the code needed slight changes as UCBLogo has some weird parser. It requires `to` and `end` to be in separate lines and space before `:` is required but on the other hand `:` are optional.

```
to w c
ifelse c=1[fd 2 lt 60][w c-1 w c-1 lt 180 w c-1 w c-1]
end
to k c
repeat 3[w c rt 180]
end
k rw

```

# Answer
> 10 votes
## T-SQL: 686 (excluding formatting)

For SQL Server 2012+.

Even though this will never be a contender, I had to see if I could get it done in T-SQL. Gone for the approach of starting with the three initial edges, then recursing through each edge and replacing them with 4 edges for each level. Finally unioning it all up into a single geometry for the level specified for @i

```
DECLARE @i INT=8,@ FLOAT=0,@l FLOAT=9;
WITH R AS(
    SELECT sX,sY,eX,eY,@l l,B,1i
    FROM(VALUES(@,@,@l,@,0),(@l,@,@l/2,SQRT(@l*@l-(@l/2)*(@l/2)),-120),(@l/2,SQRT(@l*@l-(@l/2)*(@l/2)),@,@,-240))a(sX,sY,eX,eY,B)
    UNION ALL
    SELECT a.sX,a.sY,a.eX,a.eY,l/3,a.B,i+1
    FROM R
        CROSS APPLY(VALUES(sX,sY,sX+(eX-sX)/3,sY+(eY-sY)/3,sX+((eX-sX)/3)*2,sY+((eY-sY)/3)*2))x(x1,y1,x2,y2,x3,y3)
        CROSS APPLY(VALUES(x2+((l/3)*SIN(RADIANS(B-210.))),y2+((l/3)*COS(RADIANS(B-210.)))))n(x4,y4)
        CROSS APPLY(VALUES(x1,y1,x2,y2,B),
            (x3,y3,eX,eY,B),
            (x2,y2,x4,y4,B+60),
            (x4,y4,x3,y3,B-60)
        )a(sX,sY,eX,eY,B)
WHERE @i>i)
SELECT Geometry::UnionAggregate(Geometry::Parse(CONCAT('LINESTRING(',sX,' ',sY,',',eX,' ',eY,')')))
FROM R
WHERE i=@i

```

# Answer
> 10 votes
# Mathematica - 177

```
r[x_, y_] := Sequence[x, RotationTransform[π/3, x]@y, y]
Graphics@Polygon@Nest[
 ReplaceList[#, {___, x_, y_, ___}  Sequence[x,r[2 x/3 + y/3, 2 y/3 + x/3], y]
  ] &, {{0, 0}, {.5, √3/2}, {1, 0}, {0, 0}}, Input[]]

```

Bonus clip of varying the angle of middle piece

# Answer
> 8 votes
# BBC BASIC, 179

**REV 1**

```
INPUTn
z=FNt(500,470,0,0,3^n/9)END
DEFFNt(x,y,i,j,a)
LINEx-36*a,y-21*a,x+36*a,y-a*21PLOT85,x,y+a*42IFa FORj=-1TO1FORi=-1TO1z=FNt(x+24*a*i,y+j*14*a*(i*i*3-2),i,j,-j*a/3)NEXTNEXT
=0

```

As before, but in black and white, in ungolfed (but streamlined) and golfed versions. Not a winner, despite the fact that doing it ths way avoids the need for a special treament for n=1.

```
  INPUTn
        REM call function and throw return value away to z
  z=FNt(500,470,0,0,3^n/9)
  END

        REM x,y=centre of triangle. a=scale.
        REM loop variables i,j are only passed in order to make them local, not global.
  DEFFNt(x,y,i,j,a)

        REM first draw a line at the bottom of the triangle. PLOT85 then draws a filled triangle,
        REM using the specified point (top of the triangle) and the last two points visited (those used to draw the line.)
  LINEx-36*a,y-21*a,x+36*a,y-21*a
  PLOT85,x,y+42*a

        REM if the absolute magnitude of a is sufficient to be truthy, recurse to the next level.
        REM j determines if the triangle will be upright, inverted or (if j=0) infinitely small.
        REM i loops through the three triangles of each orientation, from left to right.
  IFa FORj=-1TO1 FORi=-1TO1:z=FNt(x+24*a*i,y+j*14*a*(i*i*3-2),i,j,-j*a/3):NEXT:NEXT

        REM return 0
  =0

```

**REV 0**

According to the OP's answer to @xnor, filled in snowflakes are OK. This answer was inspired by xnor's comment. The colours are just for fun and to show the way it is constructed. Take a triangle (magenta in this case) and overplot with 6 triangles 1/3 of the base.

```
  INPUTn
  z=FNt(500,470,n,1,0,0)
  END

  DEFFNt(x,y,n,o,i,a)
  a=3^n/22
  GCOLn
  MOVEx-36*a,y-o*21*a
  MOVEx+36*a,y-o*21*a
  PLOT85,x,y+o*42*a
  IFn>1FORi=-1TO1:z=FNt(x+24*a*i,y+14*a*(i*i*3-2),n-1,-1,i,a):z=FNt(x+24*a*i,y-14*a*(i*i*3-2),n-1,1,i,a)NEXT
  =0

```

# Answer
> 6 votes
# Python 3 - 139

Uses the turtle graphics library.

```
from turtle import*
b=int(input())
a=eval(("FR"*3)+".replace('F','FLFRFLF')"*~-b)
for j in a:fd(9/b*("G">j));rt(60*(2-3*("Q">j))*("K"<j))])

```

# Answer
> 4 votes
# Python 3, 117 bytes

```
from turtle import*
ht();n=int(input())-1
for c in eval("'101'.join("*n+"'0'*4"+")"*n):rt(60+180*(c<'1'));fd(99/3**n)

```

Method:

* The solution uses Python's turtle graphics.
* `n` is `input - 1`
* Starting from the string `0000` we join its every character with `101` `n` times iteratively with the eval trick (thanks to @xnor for that).
* For every character in the final string we turn 60 degrees right or 120 degrees left based on the character value (`1` or `0`) and then move forward a length (`99/3^n`) which guarantees a similar size for all `n`'s.
* The last `0` in the string will be useless but it just redraws the same line the first `0` draws.

Example output for `input = 3`:

# Answer
> 2 votes
## R: ~~240~~ 175

Because I trying to get my head around R, here's another version. There's likely to be lot better ways to do this and I'm happy to receive pointers. What I've done seems very convoluted.

```
n=readline();d=c(0,-120,-240);c=1;while(c<n){c=c+1;e=c();for(i in 1:length(d)){e=c(e,d[i],d[i]+60,d[i]-60,d[i])};d=e};f=pi/180;plot(cumsum(sin(d*f)),cumsum(cos(d*f)),type="l")

```

# Answer
> 2 votes
*Wise fwom youw gwave...*

I knew I'd want to try implementing this in Befunge-98 using TURT, but I couldn't figure out how to go about it and I sat on it for several months. Now, only recently, I figured out a way to do it without using self-modification! And so...

# Befunge-98 with the TURT fingerprint, 103

```
;v;"TRUT"4(02-&:0\:0\1P>:3+:4`!*;
>j$;space makes me cry;^
^>1-:01-\:0\:01-\:0
0>I@
^>6a*L
^>ca*R
^>fF

```

Let's get some implementation details out of the way first:

* I tested this using CCBI 2.1, whose implementation of TURT (the turtle graphics fingerprint) makes `I` "print" the image to a SVG file. If you run this in CCBI without the command-argument `--turt-line=PATH`, it will come out as a file named CCBI\_TURT.svg by default. This is the closest I could come to *"print a graphical representation of the snowflake to the screen"* with available Funge interpreters I could find. Maybe someday there will be a better interpreter out there that has a graphical display for the turtle, but for now...
* There has to be a newline at the end for CCBI to run it without hanging (this is included with the character count). I know, right?

Basically, this works by using the stack as a sort of makeshift L-system and expanding it on the fly. On each pass, if the top number on the stack is:

* -2, then it prints and stops;
* -1, the turtle turns counterclockwise 60 degrees;
* 0, it turns clockwise 120 degrees;
* 1, it moves forward (by 15 pixels here, but you can change it by modifying the `f` on the last line);
* some number *n* that's 2 or greater, then it is expanded on the stack to `n-1, -1, n-1, 0, n-1, -1, n-1`.

For `n = 10`, this process takes a *very long time* (a couple of minutes on my system), and the resulting SVG is ~10MB in size and invisible when viewed in the browser because you can't adjust the size of the brush using TURT. IrfanView seems to work decently if you have the right plugins. I'm not super familiar with SVG, so I don't know what the preferred method is for viewing those files (especially when they're really big).

Hey, at least it *works* \- which, considering it's Befunge, is something to be thankful for on its own.

# Answer
> 2 votes
# APL(Dyalog Extended), 57 bytes SBCS

```
'A=↑1 +=⌽¯60 -=⌽60'⌂turtle'A' 'A-A++A-A'⌂lsys⍣⎕⊢'A++A++A'

```

APL has builtins for generation of fractal L-systems and drawing them using turtle graphics.

Requires Dyalog for Windows.

# Answer
> 1 votes
# Python 2, 127 bytes

```
from turtle import *
def L(l,d=input()-1):
 for x in[1,-2,1,0]:[L(l,d-1),rt(60*x)] if d>0 else fd(l)
for i in'lol':lt(120);L(9)

```

---
Tags: code-golf, graphical-output, fractal
---


title: Is this a circular step sequence?

text:
# Question
Title: Is this a circular step sequence?
## Background

We define a **circular step sequence** of order \\$n\\$ as follows:

$$ a\_1, a\_2, \dots, a\_n = \text{Permutation of } 1 \dots n \\ b\_i = \min ( |a\_{i+1} - a\_i|, n-|a\_{i+1} - a\_i| ), 1 \le i \< n \\ \text{Circular step sequence} \stackrel{\text{def}}{=} b\_1, b\_2, \dots, b\_{n-1} $$

Informally, it is the \\$n-1\\$ distances between \\$n\\$ points evenly spaced on a circle, given a permutation of those points.

For example, if we choose a permutation \\$1, 3, 6, 2, 4, 5 \\$ for \\$n = 6\\$, we get a circular step sequence of \\$2, 3, 2, 2, 1\\$. (Refer to the circular layout below.)

```
 1 2
6   3
 5 4

```

On the other hand, a circular step sequence of order 6 cannot have a substring of \\$2, 2, 2\\$. Regardless of where you start and in which direction you go first, you'll get stuck at the third 2.

## Task

Given the value of \\$n\\$ and a sequence \\$b\_1, b\_2, \dots, b\_{n-1}\\$ of positive integers, determine if the given sequence can be a circular step sequence of order \\$n\\$, i.e. there exists a permutation \\$a\_1, \dots, a\_n\\$ which leads to the given sequence \\$b\\$.

## Input and output

The elements \\$b\_i\\$ of the input sequence are guaranteed to satisfy \\$ 1 \le b\_i \le n/2 \\$ and \\$ b\_i \in \mathbb{Z}^+ \\$. Also, you can assume \\$n \ge 1\\$. If \\$ n = 1 \\$, the only possible \\$b\\$ is a zero-length sequence. You can omit the number \\$n\\$ from the input.

For output, you can use truthy/falsy values for your language (swapping is allowed). If such a convention is not defined, you can use two distinct values to represent true/false respectively.

## Scoring and winning criterion

Standard rules apply. The shortest code measured in bytes wins.

## Test cases

### True

```
1, []              # permutation: [1]
2, [1]             # permutation: [1, 2]
3, [1, 1]          # permutation: [1, 2, 3]
4, [1, 1, 1]       # permutation: [1, 2, 3, 4]
4, [1, 2, 1]       # permutation: [1, 2, 4, 3]
4, [2, 1, 2]       # permutation: [1, 3, 2, 4]
5, [1, 2, 2, 1]    # permutation: [1, 2, 5, 3, 4]
6, [2, 3, 2, 2, 1] # permutation: [1, 3, 6, 2, 4, 5]

```

### False

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

```

# Answer
# JavaScript (ES7),  ~~99 79 74~~  72 bytes

Takes input as `(n)(b)`. Returns a Boolean value.

```
n=>g=([d,...b],x=0,m=2**n-2)=>d?[x+d,x-d+n].some(y=>g(b,y%=n,m^1<<y)):!m

```

Try it online!

### How?

Instead of using an array for \\$a\_i\\$, we use a bitmask \\$m\\$ initialized to \\$2^n-2\\$ and a bit pointer \\$x\\$ initialized to \\$0\\$ (i.e. pointing to the least significant bit).

For instance: for \\$n=4\\$, we start with \\$m=4^2-2=14=1110\_2\\$. Because the LSB is our starting position, it is cleared right away to mark it as visited.

The main part of the code is a recursive search in a binary tree: for each \\$b\_i\\$, we move the bit pointer to either \\$x+b\_i\\$ or \\$x-b\_i\\$ (wrapping around modulo \\$n\\$) and toggle the bit at the new position in \\$m\\$.

We have \\$m=0\\$ on a leaf node iff all positions have been reached exactly once.
> 8 votes

# Answer
# Jelly, 9 bytes

```
Œ!Iæ%H{Aċ

```

Try it online!

A dyadic link taking \\$n\\$ as its left argument and the input sequence \\$b\\$ as its right argument. Returns a truthy value (positive integer) for True and a falsy value (zero) for False.

## Explanation

```
Œ!        | Permutations of 1..n
  I       | Differences (vectorises)
   æ%H{   | Symmetric mod half of n (for n=6, [-5,-4,-3,-2,-1,0,1,2,3,4,5] will map to [1,2,3,-2,-1,0,1,2,3,-2,-1])
       A  | Absolute
        ċ | Count occurrences of b

```
> 5 votes

# Answer
# APL (Dyalog Unicode), ~~28~~ 26 bytes

```
⊣∊⊣{≢∪⍺|+\⍵}¨⊂⍤,×¯1*2⍳⍤⍴⍨⊣

```

Try it online!

TIO is only on 17.1, so I've implemented the  operator from 18.0 manually. Takes \\$n\\$ as the left argument, and the sequence as the right.

### Explanation

```
                 ¯1*2⍳⍤⍴⍨⊣    ⍝ Get all possible combinations of ¯1 1 with length n
             ⊂⍤,×             ⍝ Multiply it by n concatenated with the array (it doesn't matter what the starting value is)
  ⊣{       }¨                 ⍝ Map each to
        +\⍵                   ⍝ The cumulative sum
      ⍺|                      ⍝ Modulo n
    ≢∪                        ⍝ Then get the number of unique values
⊣∊                            ⍝ Is one of these n?

```
> 4 votes

# Answer
# Japt `-x`, ~~11~~ 10 bytes

Outputs `0` for `false` or an integer `>0` for `true`.

```
õ á Ëäa eV

```

Try it

```
õ á Ëäa eV     :Implicit input of integer U & array V
õ              :Range [1,U]
  á            :Permutations
    Ë          :Map
     ä         :  Consecutive pairs
      a        :    Reduced by absolute difference
        eV     :  Is equal to V?
               :Implicit output of sum of resulting array

```
> 3 votes

# Answer
# Wolfram Language (Mathematica), 84 bytes

```
(y=#;!FreeQ[(x=#;Abs[#-#2]&@@@Array[x[[{#,#+1}]]&,y-1])&/@Permutations@Range@y,#2])&

```

Try it online!
> 3 votes

# Answer
# Python 3,  ~~90~~  89 bytes

-1 thanks to FryAmTheEggman

```
f=lambda n,a,v=[0]:a and any(f(n,a[1:],[(v[0]+x*a[0])%n]+v)for x in(-1,1))or len({*v})==n

```

**Try it online!**
> 3 votes

# Answer
# Ruby, ~~99 81~~ 71 bytes

```
f=->n,s,w=[0]{w[-n]||(a=s.pop)&&[a,-a].any?{|g|f[n,s,w|[(w[-1]+g)%n]]}}

```

Try it online!
> 2 votes

# Answer
# 05AB1E, 13 bytes

```
Lœ€üαD¹αÅLJIå

```

Try it online!
> 2 votes

# Answer
# Python 3, 100 bytes

```
f=lambda n,b,i=[0]:b and(f(n,b[1:],[(i[0]+b[0])%n]+i)+f(n,b[1:],[(i[0]-b[0])%n]+i))or len(set(i))==n

```

Try it online!

Returns a non-zero integer (`n>1`) / True (`n==1`) for True and False for False.

**Explanation**

`i` is the list of visited numbers in reverse order. At each step of the recursion, we remove the first entry of `b`, move either forwards or backwards by the corresponding amount (modulo `n`) and append the new position at the 0th position of `i`. Terminates when `b=[]`, for which the function evaluates to True if `i` has exactly `n` distinct numbers and False otherwise.
> 2 votes

# Answer
# Python, 77 bytes

```
f=lambda n,l,m=1:all(f(n,l[1:],m<<d*l[0]|1)for d in[1,n-1])if l else m%~-2**n

```

Try it online!

Outputs True/False swapped.

The idea to store visited values as a bitmask is from Arnauld.

But, instead of storing our current position on the tape of bits and updating it after we move, we simply move the whole tape so that we're located at the end. We treat the tape as unrolled, so that every n-th position is the same, and we always move the tape left with `<<` by converting each rightwards move to an equivalent leftwards move modulo `n`.

In the end, we collapse the tape to its last `n` positions by taking the numerical value modulo `2**n-1`. The only way to get a result of zero is if every position modulo `n` was hit exactly once.
> 2 votes

# Answer
# Scala, ~~88~~ ~~82~~ 80 bytes

```
n=>d=>1.to(n).permutations.map(l=>(l.zip(l.tail)).map(_-_)map(_.abs))contains(d)

```

Try it online!

* -6 thanks to user!
> 2 votes

# Answer
# K (ngn/k), 29 bytes

```
{|/x=#'?'+x!+\-1 1[!x#2]*x,y}

```

Try it online!

Takes `n` as `x` and `b` (the sequence) as `y`. A port of @Jo King's APL answer.

* `-1 1[!x#2]` generate all combinations of -1 and 1 with length `n`
* `*x,y` multiply these by `n` prepended to the sequence `b`
* `x!+\` take the column-wise cumulative sums, mod'ing them by `n`
* `+` transpose the result
* `#'?'` calculate the number of distinct values in each row
* `|/x=` are any of those equal to `n`?
> 2 votes

# Answer
# , ~~21~~ 17 bytes

```
e.2|@-/\"1!A.&i.]

```

Try it online!

*-4 bytes thanks to Bubbler*

Literal translation of the question: Is the given list and element of `e.` the adjacent differences of every possible perm?
> 1 votes

# Answer
# Python 2, 101 bytes

```
lambda n,b:n in map(len,map(set,reduce(lambda Q,k:[q+[(q[-1]+v)%n]for q in Q for v in-k,k],b,[[0]])))

```

Try it online!

Returns `True`/`False` if b is/isn't a circular set sequence.
> 1 votes

# Answer
# Python 3, ~~120~~ ~~115~~ 90 bytes

```
f=lambda n,l,x=0,m=0:all(f(n,l[1:],y%n,m^1<<y%n)for y in[x+l[0],x-l[0]])if l else m-2**n+2

```

You can try it online! Outputs False for CSS and True otherwise.

This is a port of Arnauld's answer (who saved me almost 20 bytes!). Go upvote his answer because it looks better than this one!
> 1 votes

# Answer
# Python 3, 101 bytes

```
lambda n,a,r=range:n in(len({sum([a[j]*(k>>j&1or-1)for j in r(i)])%n for i in r(n)})for k in r(1<<n))

```

Try it online!
> 1 votes

# Answer
# Wolfram Language (Mathematica), 54 bytes

```
Or@@(0!=##&@@@Mod[Accumulate/@Tuples[{#,-#}&/@#2],#])&

```

Try it online!

See all possible permutations: Try it online!
> 1 votes

# Answer
# Python 3.8 (pre-release), ~~137~~ \\$\cdots\\$ ~~119~~ 118 bytes

Saved a byte thanks to Surculose Sputum!!!

```
lambda n,b:any(b==[min(i:=abs(a-b),n-i)for a,b in zip(p,p[1:])]for p in permutations(range(n)))
from itertools import*

```

Try it online!
> 0 votes

# Answer
# Charcoal, 41 bytes

```
⬤ＥＸ²ＬθＥ⊕Ｌθ﹪∨ΣＥ…◧⍘ι²Ｌθλ×∨Σλ±¹§θμ⁰⊕Ｌθ⊙ι⊖№ιλ

```

Try it online! Link is to verbose version of code. Outputs `-` only if the input is *not* a circular step sequence. Explanation:

```
ＥＸ²Ｌθ

```

Outer loop to `2ⁿ⁻¹` (exclusive).

```
Ｅ⊕Ｌθ

```

Inner loop to `n` (exclusive)

```
…◧⍘ι²Ｌθλ

```

Convert the outer loop index to binary with `n-1` digits, but only take the first inner loop index bits.

```
Ｅ...×∨Σλ±¹§θμ

```

Replace the `1` bits with the values from the input and the `0` bits with the negated values respectively.

```
﹪∨Σ...⁰⊕Ｌθ

```

Take the sum modulo `n`. Because only the first inner loop index bits were used, each result takes one more bit into account, resulting in a list of the partial sums of the possibly negated values.

```
⬤...⊙ι⊖№ιλ

```

Check that all resulting lists contain duplicate elements. This will be true if the input is *not* a circular step sequence.
> 0 votes

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


title: Roll up a D&D character, with options

text:
# Question
Title: Roll up a D&D character, with options
I'd like to roll up the ability scores for my Dungeons and Dragons character. But I'd also like them to be balanced (and slightly better than average).

Typically, a character's stats are created by rolling four 6-sided dice, adding together the three highest results, and doing this 6 times. A 6 sided die has the numbers 1 to 6, with equal probability of landing on each. The 6 scores can be in any order, and are typically displayed out in an array. Unfortunately, this has a slight pitfall, namely that some players' stats can be much higher than other players' stats.

So for this generator, the stats should be a little more balanced, namely that at least one stat should be less than or equal to a certain threshold, at least one stat should be greater than or equal to a certain threshold, and the total should be greater than or equal to a certain threshold. However, the randomness should still be preserved. If a generated stat array does not qualify, the entire array should be rerolled.

Given 3 inputs, `l`, `h`, and `t`, respectively corresponding to the low threshold, the high threshold, and the total threshold, output 6 stats (in any order) that meet the criteria. All 6 stats must be included. The stats should be randomly generated, using the stat generation described above.

For example:

```
l   h   t   | low example       | high example
10  15  75  | 6  14 18 12 10 15 | 10 18 18 18 18 18
8   18  80  | 10 18 16 13 8  15 | 18 18 18 8  18 18
18  18  108 | 18 18 18 18 18 18 | 18 18 18 18 18 18

```

The code doesn't need to be fast, it just needs to get there eventually. Note that formatting doesn't much matter. Assume valid inputs.

# Answer
> 10 votes
# Japt, 28 bytes

Takes input as `t`, `l` & `h`.

```
@§Xx*Xd§V*Xd¨W}a@6Æ4ÆÒ6öÃÍÅx

```

Try it

```
@§Xx*Xd§V*Xd¨W}a@6Æ4ÆÒ6öÃÍÅx     :Implicit input of integers U=t, V=l & W=h
@                                :Left function, taking an array X as input
 §                               :  Is U less than or equal to ...
  Xx                             :  X reduced by addition after
    *                            :    Multiplying each element by ...
     Xd                          :    Any in X
       §                         :      Less than or equal to ...
        V*                       :      V multiplied by ...
          Xd                     :      Any in X
            ¨W                   :        Greater than or equal to W
              }                  :End left function
               a                 :Repeatedly run the right function and return the first result that returns true when passed through the left function
                @                :Right function
                 6Æ              :  Map the range [0,6)
                   4Æ            :    Map the range [0,4)
                     Ò           :      Negate the bitwise NOT of (i.e., increment)
                      6ö         :      Random integer in the range [0,6)
                        Ã        :    End map
                         Í       :    Sort
                          Å      :    Slice off the first element
                           x     :    Reduce by addition

```

# Answer
> 5 votes
# APL (Dyalog Unicode), 40 bytes

Full program. Prompts for total, then high, then low.

```
{(+/-⌊/)?6 4⍴6}⍣((∨/⎕≥⊣)∧(∨/⎕≤⊣)∧⎕≤1⊥⊣)⍬

```

Try it online!

`{``}` apply the following lambda to the empty list dummy argument:

`6 4⍴6` cyclically reshape `6` into a 6-row, 4-column matrix

`?` roll those dice

`(``)` apply the following tacit function to that:

`+/-⌊/` the sum minus the minimum (lit. plus-reduction minus smallest-reduction

`⍣(``)` keep applying that function to its results until the following holds true:

the results

`1⊥` evaluated as unary (i.e. summed)

`⎕≤` is the input (total) less than or equal to that?

`(``)∧` and:

the results

`⎕≤` is the input (high) less than or equal to those?

`∨/` are any true? (lit. OR-reduction)

`(``)∧` and:

the results

`⎕≥` is the input (low) greater than or equal to those?

`∨/` are any true? (lit. OR-reduction)

# Answer
> 5 votes
# Troll, 135 bytes

Right tool for rolling dice, but not necessarily for golfing.

```
function s(x)=w:=x pick1;x:=x--w;'w<>x&call s(x)
function f(l,h,t)=call s(repeat x:=6#sum largest3 4d6until h<=max x&l>=min x&t<=sum x)

```

Try it online! (Click on `Make random rolls.` and the result will appear a bit further down.)

The first function generates a shuffled string from a collection of numbers. This is necessary as collections in *Troll* are generally unordered and printed in ascending order.

slightly ungolfed:

```
function shuffle(x) =
  w := x pick 1;
  x := x -- w;                  \ --  multiset difference
  'w <> (x & call shuffle(x))   \ <>  vertically concat strings

function f(l, h, t) =
  call s(
    repeat
      x := 6 # sum largest 3 4d6
    until
      h<=max x & l>=min x & t<=sum x
  )

call f(10, 15, 75)

```

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

```
(l,h,t)=>eval(F="while(F||S-3<t)[F=3,S=3,...A=[3,3,3,3]].map(n=>(A.map(m=_=>n+=m<(v=Math.random()*6|0)?v:m=v),S+=n-=m,F&=n>l|2*(n<h),n))")

```

Try it online!

As pointed out by @Shaggy, a recursive version is shorter (134 bytes). But it will fail when the odds are low ... whereas the above version will just take forever to find a solution. :-)

### Commented

The main function initializes `F` to a truthy value and invokes an `eval()` ...

```
(l, h, t) => eval(F = "...")

```

... whose content is:

```
while(F || S - 3 < t)     // while F is truthy or S - 3 is less than t:
  [ F = 3,                //   start with F = 3 (boundary flags)
    S = 3,                //   start with S = 3 (sum of all die + 3)
    ... A = [3, 3, 3, 3]  //   append 4 more 3's
  ]                       //
  .map(n => (             //   for each entry, starting with n = 3:
    A.map(m =             //     repeat 4 times, starting with m non-numeric:
      _ =>                //
      n += m < (          //       update n:
        v = Math.random() //         pick a dice value v in [0 .. 5]
            * 6 | 0       //
      ) ? v               //         and add it to n
        : m = v           //         update m to min(m, v)
    ),                    //     end of inner map()
    S += n -= m,          //     subtract m from n and add the result to S
    F &= n > l |          //     clear the bit #0 of F if n <= l
         2 * (n < h),     //     clear the bit #1 of F if n >= h
    n                     //     yield n
  ))                      //   end of outer map()
                          // implicit end of while()

```

# Answer
> 4 votes
# R 4.1, 112 bytes

Using the new shorthand notation of defining functions (`\(x) expr`):

```
r=\(l,h,t){x=l;while(sum(x)<t|min(x)>l|max(x)<h){x=matrix(sample(6,24,r=T),nr=6);x=rowSums(x)-apply(x,1,min)};x}

```

**Explanation**

Generate 6x4 matrix (nrow=6) with random number 1-6:

```
x=matrix(sample(6,24,r=T),nr=6)

```

Calculate the sum over the rows and subtract the row-minimum to get the sum of the largest three values:

```
x=rowSums(x)-apply(x,1,min)

```

And repeat as long criteria not met:

```
while(sum(x)<t|min(x)>l|max(x)<h)

```

Initialise `x` to a value that violates criteria (could also have chosen `0`)

```
x = l

```

Edit: added explanation

# Answer
> 3 votes
# Factor \+ `dice math.unicode combinators.short-circuit.smart`, 153 bytes

```
[ [ 6 [ 4 [ ROLL: 1d6 ] replicate natural-sort rest Σ ] replicate 3dup { [ Σ <= nip ] [ nip minmax '[ _ _ between? ] ∀ ] } && ] [ drop ] until 2nip ]

```

Try it online!

It's a quotation (anonymous function) that takes a low-high pair (like `{ 10 15 }`) and a sum target from the data stack as input and leaves a sequence of 6 stat values on the data stack as output.

## Explanation:

* `[ ... 3dup ... ] [ drop ] until 2nip` Keep making stats (and discarding them) until one of them is valid.
* `6 [ ... ] replicate` Create a sequence with 6 values given by a quotation.
* `4 [ ROLL: 1d6 ] replicate` Roll 1d6 4 times and collect the results in a sequence.
* `natural-sort rest Σ` Sort, remove the first (lowest) value, and sum.
* `{ [ Σ <= nip ] [ nip minmax '[ _ _ between? ] ∀ ] } &&` Check if the sum is \>= the target sum, and check whether both elements in the low-high pair are between the minimum and maximum value (inclusive) in the stats.

# Answer
> 3 votes
# Charcoal, 36 bytes

```
Ｗ∨›Ｉζ↨υ¹∨›Ｉη⌈υ‹Ｉθ⌊υ≔ＥＥ⁶Ｅ⁴⊕‽⁶⁻Σκ⌊κυＩυ

```

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

```
Ｗ∨›Ｉζ↨υ¹∨›Ｉη⌈υ‹Ｉθ⌊υ

```

Repeat until the initially empty predefined list fails to satisfy any of the conditions that its total is less than the third input, its highest member is less than the second input or its lowest member is greater than the third input. The total is checked first because using base 1 instead of Sum allows the check to run on the empty list.

```
≔ＥＥ⁶Ｅ⁴⊕‽⁶⁻Σκ⌊κυ

```

Generate 6 sets of four dice, subtract the minimum of each set from their sums, and replace the predefined list with them.

```
Ｉυ

```

Output the valid list.

# Answer
> 3 votes
# Python 3, ~~139~~ 137 bytes

Recursive function which returns a tuple of integers.

```
from random import*
f=lambda l,h,t,*k:k*(t<=sum(k)>max(k)>=h>=l>=min(k))or f(l,h,t,*eval('sum(sorted(map(randint,[1]*4,[6]*4))[1:]),'*6))

```

Try it online!

# Answer
> 2 votes
# Ruby, 91 bytes

```
->l,h,t{1while(w=(k=*1..6).map{(k*4).sample(4).sort[1,3].sum};w.min>l||w.max<h||w.sum<t);w}

```

Try it online!

# Answer
> 1 votes
# Python 3.8 (pre-release), 198 bytes

```
from random import*
def g(l,h,t,r=range):
 while sum(k:=list(sum(sorted(randint(1,6)for _ in r(4))[1:])for _ in r(6)))<t or(n:=list(map(sum,zip(*((i<=l,i>=h)for i in k)))))[0]*n[1]!=1:pass
 return k

```

Not fast but gets the job done. It is quite possible that the last test won't finish as it needs perfect rolls.

On TIO the additional output is a check that the sum is greater or equal than the `t` and the count of numbers less than or equal to `l` and greater or equal to `h`.

Try it online!

# Answer
> 1 votes
# Python 3, 138 bytes

```
from random import*
def f(l,h,t):
 while l<min(s:=[3+sum(d:=choices(range(6),k=4))-min(d)for _ in[0]*6])or h>max(s)or t>sum(s):0
 return s

```

# Answer
> 1 votes
# Java (JDK), 175 bytes

```
(l,h,t)->{int r[]=new int[6],i,j,m,d,s,x=0,T=0;for(;x<3|T<t;)for(x=T=i=0;i<6;T+=r[i++]=s-=m,x|=s<h?s>l?0:1:2)for(m=7,s=j=0;j++<4;s+=d+=Math.random()*6,m=d<m?d:m)d=1;return r;}

```

Try it online!

# Answer
> 1 votes
# Ly, 104 bytes

```
n`n,n,>1[p6[>&p<6[>16?<,]p>arppp&+s>l<p<,]p>>&s<&l<<&s>>>>&p&l<a0Isp>rlGfp<s>flLfp<&+sp>rlLfp**sp<<<l!]>

```

Try it online!

The specific steps in this code are pretty straightforward, the only trick is keeping the data organized on the stacks.

Here's how the stacks are used:

```
s0: low-high-total values (adjusted)
s1: loop control numbers (three nested loops share one stack)
s2: dice rolls and temp storage of stats
s3: stats accumulator and workspace
s4: low-high-test work area

```

Also, the input parameter are incremented/decremented to make the comparisons to the generated stats easier. The operators available in `Ly` are less than `<` and greater then `>` and the criteria allow the stat to equal the threshold. Adjusting the threshold was shorter than adding logic to check "greater than or equal", etc...

```
# Step 0: Read in low, high, sum thresholds, setup for comps
n`n,n,>
n`      # Read line one, low thresh, increment
  n,    # Read line two, high thresh, decrement
    n,  # Read line three, sum of stats, decrement

# Step 1: Loop until a set of stats meets all criteria
1[p  ...  l!] # The iteration check is pulled from the backup cell

# Step 2: Generate a set of 6 stats
6[>&p<6[>16?<,]p>arppp&+s>l<p<,]p
6[                            ,]p # Loop once for each stat

# Step 2.1: Generate 6 random dice rolle
>&p<6[>16?<,]p
>&p<           # Clear the stack to hold the rolls
    6[     ,]p # Loop 6 times
      >16?<    # Push random 1-6 on the dice roll stack

# Step 2.2: Compute the stat from the 6 dice rolls
>arppp&+s>l<p<
>a              # Switch to dice stack, sort entries
  rppp          # Reverse stack, pop 3 entries (lowest rolls)
      &+s       # Sum the remaining 3 (highest) and stash
         >l     # Switch stacks and load sum (stat)
           <p   # Switch back to dice stack and clear it
             <  # Switch back to the loop iterator stack

# Step 3: Check to see if stats meet criteria
>>&s<&l<<&s>>>>&p&l<a0Isp>rlGfp<s>flLfp<&+sp>rlLfp**sp<<<

# Step 3.1: Save a "ready to print" copy of the stats
>>&s<&1
>>&s     # Switch to the stats stack, stash on the backup cell
    <&1  # Switch to an empty stack and restore from backup

# Step 3.2: Init test stack, copy in low/high/sum thresholds
<<&s>>>>&p&l
<<&s         # Switch to rules stack, copy to backup cell
    >>>>&p&l # Switch to test stack, clear, load from backup

# Step 3.3: Check minimum stat against threshold
<a0Isp>rlGfp
<a           # Switch to stats stack, sort entries
  0Is        # Pull smallest entry to top, save in backup
     p       # Clean-up stack (pop duplicate)
      >r     # Switch to test stack, reverse entries
        lG   # Load min stat, do "min-stat>min-thresh" comp
          fp # Stack cleanup, delete min-thresh

# Step 3.4: Check maximum stat against threshold
<s>flLfp
<s        # Save largest stats to backup cell
  >f      # Switch to test stack, flip max-thresh to top
    lL    # Load max stat, do "max-stat<max-thresh" comp
      fp  # Stack cleanup, delete max-thresh

# Step 3.5: Check sum of stats against threshold
<&+sp>rlLfp
<&+s        # Sum stats, stash in back cell
    p>      # Cleanup stack, switch to test stack
      r     # Reverse stack, puts sum-thresh on top
       lL   # Load sum, do "sum-stat<sum-thresh" comp
         fp # Stack cleanup, delete sum-thresh

# Step 3.6: Consolidate test results
**sp<<<
**sp     # Multiple all three comps, stash the result
    <<<  # Switch to the iterator stack

#Step 4: Print the result
>  # Switch to stack with copy "ready to print" of stats

```

# Answer
> 1 votes
# 05AB1E, ~~35~~ 34 bytes

```
[6Lε₄ε6LΩ}{¦O}©O¹@i®δ.SεN‹NQà}P#]®

```

Can probably be shorter, but this will do for now.

First input is `t`, second input is a pair `[l,h]`.

Try it online or try it online with added debug lines.

**Explanation:**

```
[               # Start an infinite loop:
 6L             #  Push list [1,2,3,4,5,6]
   ε            #  Map each value to:
    ₄           #   Push 1000
     ε          #   Map each digit to:
      6L        #    Push list [1,2,3,4,5,6]
        Ω       #    Pop and leave a random item from this list
     }{         #   After the inner map: sort the four values from lowest to highest
       ¦        #   Remove the first/lowest
        O       #   And sum the remaining three together
   }©           #  After the outer map: save this list of six values in variable `®` (without popping)
     O          #  Sum the list
      ¹@i       #  If the sum is larger than or equal to the first input:
         ®      #   Push the list from variable `®` again
          δ     #   Apply double-vectorized with the (implicit) second input-pair:
           .S   #    Compare: -1 if a<b; 0 if a==b; 1 if a>b
         ε      #   Map this list of lists to:
          N‹    #    Check for each value if it's smaller than the 0-based map-index
            NQ  #    Then check if the result (0 or 1) is equal to the 0-based map-index
              à #    Check if any is truthy by leaving just the maximum
         }P     #   After the map: check if both are truthy by taking the product
           #    #   If this is truthy: stop the infinite loop
]               # Close the if-statement and infinite loop
 ®              # Push list `®`
                # (after which it is output implicitly as result)

```

# Answer
> 0 votes
# Vyxal, 29 bytes

```
÷ʀ℅$19r℅":∑⁰$-:£4ḭw3ẋf:∑¥$-Wf

```

Try it Online!

---
Tags: code-golf, random, game
---


# Question
Title: Make a GUI window in any language using minimum "different characters"
I want you to make a gui window like this:

* if you're thinking, the \[quit\] button closes the window

in any language using minimum "different" characters.. AND remember that the gui window must use native widgets instead of custom icons and buttons

like I have Windows 8, so my GUI window looks like this:

### If you didn't understand what i mean by 'minimum "different characters"'..

I meant, like this hello world code:

```
print("Hello, World!")

```

has these characters:

```
()",! HWdeilnoprt

```

total 17 different characters..

likewise, make a gui window with native widgets of your OS in any language using least "different" characters..

The same gui window in python (tkinter used here) will be:

```
import tkinter as tk
from tkinter import ttk
root = tk.Tk()
label = tk.Label(root,text='Hello, World')
label.pack()
button = ttk.Button(root,text='quit', command= root.quit)
button.pack()
root.mainloop()

```

with a total of 32 different characters

NOTE: case-sensative (A != a), all characters like "\n", "\t", "\b", " ", etc. are counted..

use any language... python, java, js, css, html, ts, brainfk, ada, lua, blah.. blah.. blah..

# Answer
# Befunge-98 \+ zenity, 3 unique characters (9246 characters total)

```
[encoded data, 9246 characters]

```

Try it online! (won't actually show a GUI window because TIO doesn't have zenity installed)

This program should be portable to any Befunge-98 installation where `=` runs shell commands (which is most of them), and where `zenity` is the shell command for running zenity (the usual configuration when you have it installed, as it's meant to be run from a shell).

I didn't write this program by hand; I generated it with this Jelly program, which I did write by hand.

## Explanation

None of the usual suspects that are Turing-complete off 1 or 2 unique characters seem to have GUI or shell support, but you can do it in three.

This actually mostly isn't a translation of arbitrary Befunge into the `1-p` universal character set; `1-` let us put arbitrary data on the stack directly using arithmetic, so we use that to put the ASCII codes of the shell command to run onto the stack (with the start of the string at the top of the stack, as is the usual Befunge convention), and simply use the universal `1-p` encoding to generate a very small program `=@` that runs our shell command (`=`) and exits (`@`). (The `=@` are placed into the top-left corner of the playfield, overwriting the start of the program, and run when the pointer wraps back around. We can do this with `1-p` because `1-` are sufficient to encode any number arithmetically, as \\$1-(1-1-\cdots-1)\\$, and we can use those numbers as arguments to `p` to place an arbitrary character anywhere on the playfield, which will be interpreted as a command if the instruction pointer runs into it. Befunge uses reverse-polish notation, so the equations are encoded as `111-1-1-…1--`.)

The zenity command used here is:

```
zenity --info --text "Hello, world!" --ok-label Quit

```

This basically just shows a simple dialog box, with the text and the button label overridden. (zenity is a program intended for showing dialog boxes, like the one the question asks for. It's designed to be run from shell scripts, but you can run it from zenity just as easily.)
> 4 votes

# Answer
# HTML, 24 unique characters, 50 bytes

```
Hello, world!<button onclick=document.write``>quit

```

I hope this counts.

This isn’t a popup window, it’s a website but it’s close enough I guess.

The quit button removes all text from the website. Closing the tab seems like a better idea but that takes more code (I think so, a least)

I had to use JS template literals in the document.write because `document.write()` increases the unique character count because of the closing bracket.

I wonder if html entities can help decrease the count.

Try it on JSFiddle

Technically you haven’t stated that I have to use the ‘!’ in the hello world, so that would decrease both the counts by 1.

Also I can change the button tag into something else like h5 because buttons aren’t the only tags where onclick events work. (But buttons are the only html tags that actually look like buttons as far I have searched) (using h5 doesn’t decrease the unique character count)
> 3 votes

# Answer
# PowerShell, 35 unique characters, 378 bytes

```
add-type -assemblyname system.windows.forms
$f=new-object system.windows.forms.form
$p=new-object system.windows.forms.tablelayoutpanel
$f.controls.add($p)
$l=new-object system.windows.forms.label
$l.text="Hello, World"
$p.controls.add($l,$false,$false)
$b=new-object system.windows.forms.button
$b.text="quit"
$p.controls.add($b,$false,$true)
$f.cancelbutton=$b
$f.showdialog()

```

I used a table layout panel to add the button and label because positioning them manually would have required digits thus increasing the character count. Apart from newline and space, the 33 other characters required are `"$(),-.=HWabcdefghijlmnopqrstuwxy`.
> 3 votes

---
Tags: code-challenge, graphical-output
---


title: Rows of the Collatz tree

text:
# Question
Title: Rows of the Collatz tree
Consider a binary tree built the following way:

* The root node is \\$1\\$
* For a given node \\$n\\$:
    + If \\$n\\$ is odd, its only child is \\$2n\\$
    + If \\$n\\$ is even, one of its children is \\$2n\\$. If \\$\frac {n-1} 3\\$ is an integer and not already part of the tree, its right child is \\$\frac {n-1} 3\\$
* Recursively and infinitely define the tree this way, beginning from the root node.

The resulting tree begins like this:

and continues forever, conjectured to contain all positive integers. If you choose any integer on this tree and work your way up through its parents, you'll find the Collatz path to \\$1\\$ for that integer. This is called a *Collatz graph*

This is that tree to a depth of 20.

We can read this tree as rows, from left to right, to create a list of lists:

```
[[1], [2], [4], [8], [16], [32, 5], [64, 10], [128, 21, 20, 3], [256, 42, 40, 6], [512, 85, 84, 80, 13, 12], [1024, 170, 168, 160, 26, 24], [2048, 341, 340, 336, 320, 53, 52, 48], ...

```

Flattened, this is A088976.

Your program should take a positive integer \\$n\\$ and output the first \\$n\\$ rows of this tree. You may output in any format that clearly and consistently shows a separation between each element in the row, and a distinct separation between the rows themselves. For example, spaces for the elements, and newlines for the rows.

This is a sample program (ungolfed) that takes an integer and outputs each list on a line.

This is , so the shortest code in bytes wins.

# Answer
> 16 votes
# K (ngn/k), <sup>~~37~~</sup> 35 bytes

```
{x#x(,/{(4=6!x*4<x)(-6!)\2*x}')\,1}

```

Try it online!

### How it works

"n is even and `(n-1)/3` is an integer" is equivalent to "n is 4 mod 6".

Avoiding the cycles is achieved by simply not allowing 4 to generate 1:

**Claim:** A cycle cannot be formed midway into the tree. Any cycle in the tree must include the root, i.e. the number 1.

**Proof:** Let's assume a node \\$a\_0\\$ has a child \\$a\_1\\$, which has a child \\$a\_2\\$, ..., which has a child \\$a\_n\\$, which in turn has a child \\$a\_0\\$. Also, let's call the Collatz \\$3n+1\\$ function \\$f(x)\\$. Then the following holds:

$$ f(a\_1) = a\_0, f(a\_2) = a\_1, \cdots, f(a\_n) = a\_{n-1}, f(a\_0) = a\_n $$

If \\$a\_0\\$ has a parent (let's call it \\$a\_{-1}\\$), then \\$f(a\_0) = a\_{-1}\\$, which implies \\$a\_{-1} = a\_n\\$, and therefore \\$a\_{-1}, a\_0, \cdots, a\_{n-1}\\$ is also a cycle (which is one level closer to the root of the tree than \\$a\_0, \cdots, a\_n\\$). The same logic can be applied to \\$a\_{-1}\\$, \\$a\_{-2}\\$, ..., until the highest node reaches the root. Therefore, every cycle that exists in this tree goes through the root, i.e. the number 1. \\$\blacksquare\\$

The only cycle that involves the number 1 is the `[1, 2, 4]` cycle. Therefore, it suffices to prevent this cycle (i.e. stop 4 from generating 1) to prevent all cycles in the tree.

```
{x#x( ... )\,1}    start with [1], iterate x times and collect values,
                   and take first x values...
,/{ ... }'           apply to each number and flatten...
2*x                    start with twice the input,
(-6!)\                 and append its floor division by 6 if
(4=6!x*4<x)            the original input is 4 mod 6 and it is over 4

```

# Answer
> 6 votes
# Jelly, 23 bytes

```
ḤḤ,’÷3ƊƊḂ?€FḞƑƇ>Ƈ1
1ÇÐ¡

```

Try It Online!

I doubt this is optimal; I kind of ended up patching together like three fixes in a row on my original idea. Might retry later if I have time and remember.

# Answer
> 4 votes
# JavaScript (ES10), 70 bytes

```
f=(n,a=[1])=>n--?a+`
`+f(n,a.flatMap(x=>x%6-4|x<5?2*x:[2*x,~-x/3])):''

```

Try it online!

# Answer
> 4 votes
# Python 2, ~~77~~ ~~75~~ 72 bytes

-5 bytes thanks to Dude coinheringaahing, G B and xnor!

```
r=1,
exec'print r;r=sum([[2*i]+[i/3][:i%6==4<i]for i in r],[]);'*input()

```

Try it online!

---

Assuming the Collatz conjecture holds, we can generate the tree by sorting Collatz paths. This is a lot longer, but maybe a bit more interesting:

```
c=lambda x:-1/x*[x]or c([x/2,3*x-1][x%2])+[x]
k=0
exec'print[-w[k]for w in sorted(c(p)for p in range(-2**k,0)if-~k==len(c(p)))];k+=1;'*input()

```

Try it online!

# Answer
> 3 votes
# , 48 bytes

```
<6&(([:;<@(((],<.@%~)+:)#~1,(4<])*4=|)"0)&.>)<@1

```

Try it online!

Just a port of Bubbler's nice K answer into J, to see how they'd compare.

The required boxing to handle ragged arrays, as well as some other details, made it harder to golf in J.

# Answer
> 3 votes
# Perl 5, 60 bytes

```
$_=1;for$x(2.."@F"){s,\d+,2*$&.($&%6-4|$&<5?'':(1-$&)/3),ge}

```

Try it online!

For each input line:

```
$_=1;               # init output string $_ with '1'
for$x(2.."@F"){     # do input-1 times, input number is in "@F" due to -a
  s,\d+,            # search-replace all positive ints in $_ with:
     2*$&           # 2 * the current int now in $&
     .              # and possibly also another number
     (
       $&%6-4|$&<5  # ...if $& % 6 == 4 and $& > 4
       ? ''
       : (1-$&)/3   # negative x where x = ($&-1)/3 using '-' as separator
     )
   ,ge              # g=global, e=replacement from code not string
}

```

# Answer
> 3 votes
# Wolfram Language (Mathematica), 58 bytes

```
NestList[If[#~Mod~6==4<#,##&,#&][2#,--+#/3]&/@#&,{1},#-1]&

```

Try it online!

Returns a list of row-lists.

# Answer
> 3 votes
# Ruby, ~~66~~ 64 bytes

```
->n{[a=[1]]+(2..n).map{a=a.flat_map{|x|[x*2,x%6==4?x/3:1]-[1]}}}

```

Try it online!

# Answer
> 3 votes
# Haskell, ~~69~~ 57 bytes

```
(`take`iterate(>>=g)[1])
g n=2*n:[n`div`3|n`mod`6==4,n>4]

```

Try it online!

* saved 12 bytes thanks to @DelfadOr !
* Based on @ovs answer

57 bytes alternative provided by @xnor

```
(`take`iterate(>>=g)[1])
g n=2*n:[k|k<-[2,4..n],3*k+4==n]

```

Try it online!

# Answer
> 2 votes
# Charcoal, 38 bytes

```
⊞υ¹ＦＮ«Ｉυ↓≔υη≔⟦⟧υＦη«⊞υ⊗κ¿∧›κ⁴⁼⁴﹪κ⁶⊞υ÷κ³

```

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

```
⊞υ¹

```

Start with the first row of just `1`.

```
ＦＮ«

```

Loop over the desired number of rows.

```
Ｉυ

```

Output each element on its own line.

Leave a blank line between rows.

```
≔υη

```

Save the current row.

```
≔⟦⟧υ

```

Start a new row.

```
Ｆη«

```

Loop over the saved row.

```
⊞υ⊗κ

```

Add the current element, doubled.

```
¿∧›κ⁴⁼⁴﹪κ⁶

```

If the current element is greater than 4 but equal to 4 modulo 6, then...

```
⊞υ÷κ³

```

... add the current element, integer divided by 3.

# Answer
> 2 votes
## Perl 5, 63 bytes

```
@n=1;map{say"@n";@n=map{$_*2,$_<5||$_%6-4?():($_-1)/3}@n}0..pop

```

Try it online!

# Answer
> 1 votes
# Julia 1.0, 67 bytes

```
>(n,a=[1])=show(a),0<n-1>[(a.|>j->[2j;~-j÷3][1:1+(j%6==4<j)])...;]

```

Try it online!

based on ovs's answer

output is in the form

```
[1][2][4][8][16][32, 5][64, 10][128, 21, 20, 3]...

```

---
Tags: code-golf, sequence, arithmetic, binary-tree
---


title: Could you massage this stack for me?

text:
# Question
Title: Could you massage this stack for me?
Forth is one of the few non-esoteric stack-based languages. For this challenge, we will use a small subset of Forth, which simply executes a sequence of words in a linear fashion — without any definitions or loops.

In good Forth code, each word definition includes a **stack effect** comment, which explains the layout of the stack before and after the word's execution. For example, `+` has the stack effect `a b -- sum`, `swap` has the stack effect `a b -- b a`, and `fill` does `ptr len byte --`. Both before and after the `--`, the top of the stack is to the right, and thus the stack elements are written in the order in which you'd have to push them.

Note that, if the word only manipulates the order of elements on stack, the stack effect is a complete specification of its behavior. **Your task** is to write a program or function that takes such a stack effect as input, and emits an implementation of it in the subset of Forth described below.

## The Forth subset

Your output may make use of the words `drop`, `dup`, `swap`, `>r` and `r>`. Three of those are fully specified by their stack effect:

```
drop ( a -- )
dup ( a -- a a )
swap ( a b -- b a )

```

The last two make use of the **return stack**. Apart from the main **data stack**, Forth also has another stack, which is used to save return addresses while calling user-defined words. However, since Forth implementers are trusting people, the programmer may also store their own data on the return stack within one procedure, as long as they clean it up before returning.

To use the return stack, we have the last two words:

* `>r ( x -- ; R: -- x )` moves an item from the data stack to the return stack
* `r> ( -- x ; R: x -- )` moves an item from the return stack back to the data stack

Your code must use the return stack on in a balanced manner.

## Example

Let's take a close look at one of the programs you could output given the input `c a b -- b a b`.

```
      Data stack    Return stack
      c a b
swap  c b a
>r    c b           a
swap  b c           a
drop  b             a
dup   b b           a
r>    b b a
swap  b a b

```

Here, `swap >r swap drop dup r> swap` would be your output.

## Input and output

Your input will consist of two lists of names, describing the before and after states of the stack. The names in the first list will all be unique. The names in the second list all occur in the first one.

The output list may contain duplicates, and it does not need to include every name from the input list.

Parsing is not a part of the challenge, so you may use any reasonable format for these lists. Some examples of the input formats you can choose:

```
"a b -- b a"
"a b", "b a"
"ab:ba"
["a", "b"], ["b", "a"]
[2, 7], [7, 2]

```

In particular, you are allowed to reverse the ordering, taking the top of the stack to be the *beginning* of each list.

Your output, which represents a Forth program, can also use any way of encoding a sequence of instructions. For example:

```
"drop swap dup >r swap r>"
"xsd>s<"
"earwax"
[3, 2, 1, 0, 2, 4]

```

## Test cases

Each test consists of two lines. The first is the input, but since the solution isn't unique, the second line is merely an example of what the output can look like. You can use this Python program to check that the programs you are generating are correct.

If you'd like to generate some larger test cases, use this script.

```
a b -- a b a
>r dup r> swap

a b -- b a b
swap >r dup r> swap

c a b -- b a b
swap >r swap drop dup r> swap

a b c -- c b a
swap >r swap r> swap

a b c -- b c a
>r swap r> swap

a b c d -- d a c
swap >r swap drop swap r>

a b c d -- d c b a
swap >r swap >r swap r> swap r> swap >r swap r>

```

# Answer
# K (ngn/k), 42 bytes

```
{,//a,({(x#2;|!3;x#,3 0)}'x?y),2+a,2+a:~x}

```

Try it online!

Verify the test cases!

Takes the input as two lists of positive integers (or chars). Returns a list of integers, where `0 1 2 3 4` is mapped to `>r dup r> swap drop` respectively.

### How it works

This uses a simple, highly systematic approach. First, all items are moved to the return stack. Then the return stack is used like a "variable stack", so each requested item is fetched in order, preserving the return stack after each fetch. Finally, the return stack is cleared.

Using `( a b -- a b a )` as an example:

```
>r >r     Move a and b to the return stack
          a is the top (zeroth) item on the R-stack, b is the next one
r> dup >r               Fetch a
r> r> dup >r swap >r    Fetch b
r> dup >r               Fetch a
r> r> drop drop    Clear the return stack

```

In general, in order to fecth n-th item (0-based), the following sequence is used:

```
n+1 copies of r>    Move n+1 items from return stack to main stack
dup >r              Copy nth item and move one copy back to return stack
n copies of (swap >r)   Move the unneeded items to return stack

```
> 9 votes

# Answer
# Julia 0.7, 188 bytes

```
b>a=push!(a,pop!(b))
a\b=for i=1:-1%UInt,j=Iterators.product(fill(1:5,i)...)
try
s=+a;r=[];z=[]
j.|>k->k<2?s>z:k<3?[s[end]]>s:k<4?(s>z;s>r;z>s;r>s):k<5?s>r:r>s
s==b&&return j
catch;end
end

```

Try it online!

brute-force approach.

`b>a=push!(a,pop!(b))` is used a lot to shorten the code. `r` is the return stack, and `z` is a stack used for `swap` and `drop`

inputs are 2 lists of numbers, output is a list of number, where:

```
1: drop
2: dup
3: swap
4: >r
5: r>

```

last test case takes over 1 minute for TIO to compute

Bubbler's answer is probably smarter but let's say my program gives the shortest answer possible
> 2 votes

# Answer
# Zsh `-e`, 86 bytes

```
echo $(for x<<<A
for y (`<i`)(<<<G\ A;for x;{<<<F;((x-y));<<<S\ A})|sort
for x<<<F\ X)
```

Attempt This Online!

It's hard to cut down on the `<<<` repetition.

Uses almost the same method as Bubbler's answer, except it ends with `r> drop r> drop ...` instead of `r> r> ... drop drop ...`.

Names are integers. Expects the input stack on the command-line and the output stack in a file called `i`.

Output encoding:

```
A  >r
F  r>
G  dup
S  swap
X  drop

```

The second line loops over the output stack and produces instructions to retrieve each item. The strange letter choices are to finagle the possible outputs into the right orders so that `sort` can arrange them correctly into the order of instructions Bubbler describes:

> To fetch the n'th item (0-indexed), the following sequence is used:
>
> ```
> n+1 copies of (r>)      Move n+1 items from return stack to main stack
> (dup >r)                Copy nth item and move one copy back to return stack
> n copies of (swap >r)   Move the unneeded items to return stack
>
> ```

This saves over a `repeat` loop and finding the index using Zsh's builtin `${@[(i)$y]}` (which is quite a mouthful)

I use `((x-y))` to manually find the index of the item `y`. If `x` equals `y` then `x-y` is zero, the `(())` exits with a "failure" status code, and thanks to the `-e` option, that failure implicitly exits and breaks out of the loop, but only until the innermost layer of `()`. This is a much shorter than `break`.

`echo $()` collapses all newlines into spaces.
> 1 votes

# Answer
# Jelly, (26?) 27 bytes

<sup>26 if the result need not be flat (while still consistent) - remove trailing `F`</sup>

```
iⱮ’“¡©“®¢‘xⱮj€12b4;,a"4,1ɗF

```

A dyadic Link that accepts the starting data stack in reverse on the left and the final data stack in reverse on the left and yields a list of integers:

```
0 >r
1 r>
2 swap
3 dup
4 drop

```

**Try it online!** (Footer formats like the question does.)

Or see the Python suite of test results.

### How?

This builds the reverse of the final data stack in the return stack one item at a time by "copying" the item from the data stack, leaving the data stack unaffected, then it drops all of the original items from the data stack and pulls all the copied items back.

To "copy" an item it pushes all those above it, then repeatedly pulls and swaps so that all the original main items are back on the data stack with the required item on top, then duplicates and pushes and then performs the conjugate of everything before the duplication to get main back to how it started.

For example, to push `d` from `abcd...` (where `a` is on top):

```
>r >r >r r> swap r> swap r> swap dup >r swap >r swap >r swap >r r> r> r>

```

...or

```
(>r)*3 (r> swap)*3 (dup >r) (swap >r)*3 (r>)*3

```

Where `3` is three because there are three items on top of `d`.

##### Code breakdown

```
iⱮ’“¡©“®¢‘xⱮj€12b4;,a"4,1ɗF - Link: starting (reversed); final (reversed)
 Ɱ                          - map with:
i                           -   first index of (final item) in (starting items)
  ’                         - decrement -> 0-based indices
   “¡©“®¢‘                  - code-page indices = [[0,6],[8,1]]
           Ɱ                - map with:
          x                 -   times - e.g. 3 -> [[0,0,0,6,6,6],[8,8,8,1,1,1]]
            j€12            - join each with twelves
                b4          - convert from base four
                                0->[0]; 6->[1,2]; 12->[3,0]; 8->[2,0]; 1->[1]
                         ɗ  - last three links as a dyad - f(starting, final):
                   ,        -   pair -> [starting, final] e.g. ["abc","ba"]
                      4,1   -   [4,1]                          [4,1]
                     "      -   zip with:
                    a       -     logical AND                  [[4,4,4],[1,1]]
                  ;         - concatenate
                          F - flatten

```
> 0 votes

---
Tags: code-golf, code-generation, stack
---