title: Gravity simulator

text:
# Question
Title: Gravity simulator
### Statement

You are given a still of a series of balls falling in a 2D grid. This grid is surrounded by immutable and unbreakable walls so all the action is contained within them. Your task is to determine what the state of the scenario will be after gravity does all it's work.

### Elements inside grid

* `-` Floor, doesn't alter the direction of falling balls.
* `\` Right slide, alters the path of the ball one (1) position right.
* `/` Left slide, alters the path of the ball one (1) position left.
* `o` A ball.

### Rules

* Balls fall.
* Floors and slides **don't fall**.
* If the ball hits a slide that would make it go through a wall (`\#`or`#/`), or cross through a floor the slide will act as a floor.
* When a ball hits another ball the will become one ball, but increase their power to the sum of both balls.
* New balls (joined) will continue to behave as usual.
* When a ball can't move anymore, it's replaced by its power.
* The power of a ball will always be at most 9.

### Input

The grid will be given in a string variable with whatever name is shortest in your language of choice. By default we will use `a` as the input. A sample of an input, exactly as received:

```
##########\n# \      #\n#o       #\n#  - -\o #\n#/-    \ #\n#  \oo-/\#\n#-/ \   /#\n#   \ \  #\n#       /#\n##########

```

For random grids generated use https://repl.it/B1j3/2. Use my generated page instead (no ads, no crap, just the input and the output)

**Note** line breaks are `\n`. Printing the input to screen (not required for the challenge) would show things like this. Although I've put four puzzles alongside to safe space.

```
##########  ##########  ##########  ##########
# \      #  # o    -/#  #       o#  #-o /    #
#o       #  #    \   #  # o     -#  #-- \ /\ #
#  - -\o #  #-  \    #  #    - \o#  # - -- o-#
#/-    \ #  #        #  #o /\    #  #/ \     #
#  \oo-/\#  #o  -o-  #  # /    -o#  #/ /o oo/#
#-/ \   /#  #   -/-  #  # -  o  -#  #o/      #
#   \ \  #  #    \\  #  #   \o  /#  #o-o    o#
#       /#  # \o\  /\#  #     \o #  # -\o o /#
##########  ##########  ##########  ##########

```

### Output

The same grid, printed to screen with the final result of ball power. A valid answer would be one (1) of the following puzzles, each one corresponds to the input at the same position, of course if the input is different you should adjust the output. Not limit it to those four!

```
##########  ##########  ##########  ##########
# \      #  #      -/#  #       1#  #-1 /    #
#        #  #    \   #  #       -#  #-- \ /\ #
#1 - -\  #  #-  \    #  #    - \ #  # - --  -#
#/-    \1#  #        #  #  /\    #  #/ \     #
#  \  -/\#  #   -1-  #  # /    -2#  #/ /    /#
#-/ \   /#  #   -/-  #  # -     -#  # /      #
#   \ \  #  #    \\  #  #   \   /#  # -      #
#    2  /#  #1\2\  /\#  #2   2\1 #  #2-\3 23/#
##########  ##########  ##########  ##########

```

### Score

Languages will compete against themselves so feel free to use nongolf languages. To validate a solution I must be able to test it somewhere to see it works!.

Score is number of bytes. In the event of a tie, the first answer to reach the tied score wins.

### Warnings

* If unsure of how a ball should react, ask me and I'll clarify, I've been as clear as I could but I'm sure there are cases that are confusing.
* Slides are only ridden **if you can exit them**, think about it like a real slide. There's a guy at the top that doesn't let you through the ball unless it will exit through the other side.

### Clarifying examples of ball movement

```
######                       ######
#-o- #    BALL WOULD GO RD   #- - #
# \  #                       # \o #
######                       ######

######                       ######
#-o- #     BALL WOULD STAY   #-o- #
# \\ #                       # \\ #
######                       ######

######                       ######
#  -o#     BALL WOULD STAY   #  -o#
#   \#                       #   \#
######                       ######

######                       ######
#  o #     BALL WOULD STAY   #  o #
#  \/#                       #  \/#
######                       ######

######                       ######
#-o- #    BALL WOULD GO LD   #- - #
# /\ #                       #o/\ #
######                       ######

```

### How can I test if my answer is valid?

I've set up a simple page in one of my sites that will give you a random puzzle, and its answer. Take the input and check it against the output. My solution, without worrying too much about golfing is `389b` `355b` in python (generator, and page also python)

### Leaderboard

```
var QUESTION_ID=64359,OVERRIDE_USER=8478;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```

```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```

# Answer
> 17 votes
# Marbelous, 19561 bytes

(Not that I tried to optimize the size.)

This claims the final bounty here.

This expects a trailing newline in the input. It works for boards up to 15x15 (including the edges) but I feel like this is reasonable as that is a direct result of the num size limit being 255. Please use my interpreter as I can make no guarantees about other interpreters. It is based on the one here but with a few bug fixes and an added debugger.

To solve the boards in the example takes about 330000 ticks. That is mostly due to the difficulty of arbitrary data storage. Marbelous is not turning complete so I have to use a big rotating tape to store the board. The code is divided into roughly three sections. (Separated by those four big lines of %%).

1. This gets the full input and converts it to the encoding expected by the rest of the code. It also populates the initial fields of the main processing loop.
2. This function takes a t of values (ie one square and the three below it) and figures out the state after one tick. It then outputs all the values that need to be sent to the memory tape or terminates the program if we are complete.
3. This is the memory tape. It is possible to read or write to it by sending values to the appropriate portals.

Overall this is an interesting language that could be fun if it is made turning complete. I do feel that the coding can get a bit repetitive (it is mostly just lots of `&0`s) but it is still fun.

```
# ENCODING:
# 0 = empty square
# 1-9 = that many marbles
# A = wall
# B = right ramp
# C = left ramp
# D = reset count
# E = nothing

.. @B .. .. .. .. .. .. .. @C .. .. .. .. .. .. .. .. .. .. ..
.. 00 00 // // // // // // // .. .. .. .. .. .. .. .. .. .. ..
.. ge t_ in pu t_ +_ in it .. .. .. .. .. .. .. .. .. .. .. ..
.. @B @C .. .. &A .. .. @K .. .. .. .. .. .. .. .. .. .. .. ..
%% %% %% %% %% %% %% %% %% %% %% %% %% %% %% %% %% %% %% %% %%
.. .. .. .. .. .. .. \\ \\ \\ \\ .. .. .. .. .. .. .. .. .. ..
.. .. .. // .. .. \\ \\ \\ .. .. .. .. .. .. .. .. .. .. .. ..
.. .. .. .. .. \\ \\ %% @4 %% @9 %% .. .. .. .. .. .. .. .. ..
.. .. .. .. \\ %% @3 \\ .. .. &4 .. .. .. .. .. .. .. .. .. ..
.. .. .. .. @2 \\ \\ .. .. .. .. .. .. .. .. .. .. .. .. .. ..
.. .. %% @1 \\ \\ .. .. .. .. // .. @A .. .. .. .. .. .. .. ..
0A @0 \\ \\ \\ .. 01 .. .. .. .. // // .. .. .. .. .. .. .. ..
\\ \\ \\ \\ ti ck _r et ur n_ pr in t_ an d_ te rm in at e_ pg # ys: v0 v3
.. .. .. .. @0 @1 @2 @3 @4 .. &0 &1 &2 .. &0 &1 &2 &3 &4 &3 &4 # xs: v1 v2 l0 w sl
.. .. .. .. .. .. .. .. .. \\ \\ \\ @5 \\ \\ \\ @6 \\ @7 \\ @8 # @5 = write loc
.. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. # @6 = write val
.. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. # @7 = read loc
.. .. .. .. .. .. .. .. .. .. .. .. \/ .. .. .. \/ .. \/ .. \/ # @8 = read ret loc
%% %% %% %% %% %% %% %% %% %% %% %% %% %% %% %% %% %% %% %% %%
.. .. .. .. .. .. .. .. .. .. .. .. .. .. .. %% @D @E 01 .. %% # Acts as a switchboard
.. .. .. .. .. .. .. .. .. .. .. .. .. .. .. %% &5 &5 // .. %% # to activate the right
.. .. .. .. .. .. .. .. .. .. .. .. .. .. .. %% pl us .. .. %% # gate when a write is
.. .. .. .. .. .. .. .. .. .. .. .. .. .. .. %% =1 =2 =3 =4 %% # complete
.. .. .. .. .. .. .. .. .. .. .. .. .. .. .. %% &0 &1 &2 &3 %%
.. .. .. .. .. .. .. .. .. .. .. .. .. .. .. %% ++ ++ ++ eo %%
.. .. .. .. .. .. .. .. .. .. .. .. .. .. .. %% \\ \\ \\ @E %%
.. .. .. .. .. .. .. .. .. .. .. .. .. .. .. %% %% %% %% %% %%
.. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. ..
.. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. @G @K .. ..
.. .. @P 0E .. .. @O 0E .. .. @N 0E .. .. @M 0E .. \\ .. .. ..
.. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 .. ..
.. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E ..
.. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // ..
.. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E ..
.. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // ..
.. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E ..
.. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // ..
.. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E ..
.. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // ..
.. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E ..
.. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // ..
.. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E ..
.. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // ..
.. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E ..
.. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // ..
.. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E ..
.. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // ..
.. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E ..
.. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // ..
.. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E ..
.. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // ..
.. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E ..
.. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // ..
.. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E ..
.. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // ..
.. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E ..
.. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // ..
.. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E ..
.. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // ..
.. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E ..
.. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // ..
.. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E ..
.. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // ..
.. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E ..
.. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // ..
.. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E ..
.. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // ..
.. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E ..
.. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // ..
.. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E ..
.. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // ..
.. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E ..
.. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // ..
.. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E .. \\ &9 0E ..
.. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // .. 0E &9 // ..
.. \\ &9 0E .. \\ &9 .. .. \\ &9 .. .. \\ &9 .. .. \\ &9 .. ..
.. 0E &9 // .. .. @P .. .. .. @O .. .. .. @N .. .. .. @M .. ..
.. \\ &9 0E .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. ..
.. 0E &9 // .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. ..
.. \\ &9 0E .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. ..
.. 0E &9 // .. 0E .. .. .. .. .. .. .. .. .. .. .. .. .. .. ..
.. \\ &9 0E .. &A .. .. .. .. .. .. .. .. .. .. .. .. .. .. ..
.. 0E &9 // .. \\ \\ .. .. .. .. .. .. .. .. .. .. .. .. .. ..
.. \\ &9 0E .. .. // // .. .. .. .. .. .. .. .. .. .. .. .. ..
.. 0E &9 // .. \\ \\ .. .. .. .. .. .. .. .. .. .. .. .. .. ..
.. \\ &9 0E .. .. // // .. .. .. .. .. .. .. .. .. .. .. .. ..
.. 0E &9 // .. \\ \\ .. .. .. .. .. .. .. .. .. .. .. .. .. ..
.. \\ &9 0E .. .. // // .. .. .. .. .. .. .. .. .. .. .. .. ..
.. 0E &9 // .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. ..
.. \\ &9 0E .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. ..
.. 0E &9 // .. .. .. 01 .. .. .. .. .. .. .. .. .. .. .. .. ..
.. \\ &9 0E .. .. .. ng .. .. .. .. .. .. .. .. .. .. .. .. ..
.. 0E &9 // .. .. .. &A .. @5 .. @7 .. .. .. .. .. .. .. .. ..
.. \\ &9 0E .. .. .. .. .. du pe du pe .. .. .. .. .. .. .. ..
.. 0E &9 // .. .. .. .. .. ez @L ez .. .. .. .. .. .. .. .. ..
.. \\ &9 0E .. .. .. .. .. +2 .. +3 .. .. .. .. .. .. .. .. ..
.. 0E &9 // .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. ..
.. \\ &9 0E .. .. .. .. @H .. .. .. .. .. .. .. .. .. .. .. ..
.. 0E &9 // .. .. .. .. // // // // .. .. .. .. .. .. .. .. ..
.. \\ &9 0E .. .. .. .. .. @I .. .. .. @L .. .. .. .. .. .. ..
.. 0E &9 // .. .. .. .. .. // // // // // .. .. .. .. .. .. ..
.. \\ &9 0E .. .. @F .. .. .. @J @8 @6 .. .. .. .. .. .. .. ..
.. .. &9 // .. .. 00 01 00 00 // // // .. .. .. .. .. .. .. ..
.. .. \\ \\ \\ lo op er lo op er lo op .. .. .. .. .. .. .. ..
.. .. .. .. .. @G @F @H @I @J @D @9 @A .. .. .. .. .. .. .. ..
.. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. ..

# value, position, mode, w/r-location, input, wrote, read1, read2
#
# mode 0 = waiting
# mode 1 = inputing
# mode 2 = writing
# mode 3 = reading
:looper
# &6 = reset
# &5 = not reset
#
# &7 = writing and match
# &8 = writing and no match
#
# &9 = reading and match
# &A = reading and no match
#
# mode 1: output nothing
# mode 2:
}2 .. %% }0 .. %% 00 01 00 00 00 .. .. .. .. .. ..
>0 &0 %% =D &5 %% &1 &1 &1 &1 &1 .. .. .. .. .. ..
.. \/ %% &6 \/ %% {1 {2 {3 {4 \\ !! .. .. .. .. ..
>1 &1 %% \/ .. %% %% %% %% %% %% %% %% %% %% %% %%
.. \/ %% .. .. %% }1 }3 .. }4 }1 00 00 00 00 .. ..
>2 &2 %% %% %% %% &2 &2 .. .. ++ .. .. .. .. .. ..
.. \/ %% .. .. %% mi nu .. &7 &7 &7 &7 &7 &7 .. ..
>3 &3 %% .. .. %% =0 &8 .. {0 {1 {5 {3 {4 \\ !! ..
&4 \/ %% .. .. %% &7 .. .. .. .. .. .. .. .. .. ..
\/ .. %% .. .. %% .. .. }0 }0 }1 .. .. .. .. .. ..
.. .. %% .. .. %% .. .. .. ne wl 02 }3 }4 00 .. ..
.. .. %% .. .. %% .. .. &8 &8 .. &8 &8 &8 &8 .. ..
.. .. %% .. .. %% .. .. {0 {1 .. {2 {3 {4 \\ !! ..
.. .. %% .. .. %% %% %% %% %% %% %% %% %% %% %% %%
.. .. %% .. .. %% }1 }3 .. }0 }1 00 00 }4 }0 00 ..
.. .. %% .. .. %% &3 &3 .. .. ++ .. .. &9 &9 .. ..
.. .. %% .. .. %% mi nu .. &9 &9 &9 &9 se nd &9 ..
.. .. %% .. .. %% =0 &A .. {0 {1 {3 {4 {6 {7 \\ !!
.. .. %% .. .. %% &9 .. .. .. .. .. .. .. .. .. ..
.. .. %% .. .. %% .. .. }0 }0 }1 .. .. .. .. .. ..
.. .. %% .. .. %% .. .. .. ne wl 03 }3 }4 00 .. ..
.. .. %% .. .. %% .. .. &A &A .. &A &A &A &A .. ..
.. .. %% .. .. %% .. .. {0 {1 .. {2 {3 {4 \\ !! ..
.. .. %% .. .. %% .. .. .. .. .. .. .. .. .. .. ..
.. .. %% .. .. %% .. .. .. .. .. .. .. .. .. .. ..

:newl
# }0 = 0 -> same
# }0 = D -> 0
# else -> }1 + 1
}0 .. ..
=E =D ..
&0 &1 &2
\/ \/ \/
}1 00 }1
.. .. ++
&0 &1 &2
{0 {0 {0

# Tik, Return, Print, and Terminate Program
#
# 0,1,9-C,
#
:tick_return_print_and_terminate_pg
%% %% %% %% %% %% %% %% %% %% %% %% %%
%% }2 }3 }4 00 01 }2 }2 }2 }2 }2 }2 %% # Echo values that should be echoed
%% ++ .. .. .. .. ++ +2 .. -- .. ++ %%
%% .. .. .. .. .. .. }3 .. }3 }3 }3 %%
%% &0 &0 &0 &0 &0 &0 &0 &0 &0 &0 &0 %%
%% {2 {3 {4 {F {G {D {E {5 {6 {7 {8 %%
%% %% %% %% %% %% %% %% %% %% %% %% %%
%% .. .. .. .. %% .. }5 }0 }1 }6 .. %% # (left)  prints the cell
%% .. .. .. .. %% .. so lv ev ls .. %% # (right) solve the position
%% .. .. .. .. %% // // .. .. .. .. %%
%% .. }3 }2 .. /\ \\ .. .. .. .. .. %%
%% .. pr in tc %% .. &0 &0 &0 &0 .. %%
%% .. .. .. .. %% .. {9 {A .. du pe %%
%% .. .. .. .. %% .. .. .. // {C {1 %%
%% .. .. .. .. %% .. .. du pe .. .. %%
%% .. .. .. .. %% .. .. {B {0 .. .. %%
%% %% %% %% %% %% %% %% %% %% %% %% %%
%% .. }4 }2 .. .. .. .. .. .. .. 00 %% # Check if the program should terminate
%% .. mi nu .. .. .. .. }3 .. .. &1 %%
%% .. \\ \\ \\ =0 &0 .. &1 .. .. .. %%
%% .. .. .. .. &1 \/ .. pb .. .. .. %%
%% .. .. .. .. \/ .. .. .. .. .. !! %%
%% %% %% %% %% %% %% %% %% %% %% %% %%

# Get Input and Initlize
#
# gets the full board input
:get_input_+_init
# 1) }1 = 0 then print char }0++
# 2) }1 = 0 & char = \n then }1 = }0, }0 := 0
# 3) }1 != 0 & char != \n then }1++
# 4) eof then output stop
# 5) }0 = 1 or w-1 or w or w+1 & }1 != 0 output v
# 6) }1 != 0 output encoding
.. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. ..
.. 00 .. .. .. .. .. .. .. .. .. .. .. .. .. }0 }1 ..
.. ]] &1 .. .. .. .. .. .. .. .. .. .. .. .. mi nu ..
.. .. \/ .. .. }0 }1 .. .. .. .. .. .. .. .. -2 .. 0D
.. \\ \\ \\ c+ ge t_ in pu t_ +_ in .. .. .. &1 .. &1
.. .. .. .. // .. .. .. .. .. .. .. .. .. .. /\ {4 {7
.. .. .. /\ {0 {1 {2 {3 {4 {5 {6 {7 .. .. !! .. .. ..
.. .. !! .. .. .. .. .. .. .. .. .. .. .. .. .. .. ..
.. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. ..

# Char + Get Input and Initlize
#
# gets the full board input
:c+get_input_+_init
# &0 = no width
# &1 = width
# &2+&9 = newline
# &3+&8 = not newline
# &4 = no width & newline
# &5 = no width & !newline
# &6 = width & newline
# &7 = width & !newline
# &A/B/B = release v0/2/3
.. .. .. .. %% 00 00 %% .. .. .. .. .. .. .. .. .. .. .. .. ..
}2 .. .. .. %% &0 &0 %% }0 .. }1 00 .. 00 }1 }1 .. }0 }1 }2 ..
=0 &1 .. .. %% &2 &3 %% &0 .. &5 &5 .. &4 &4 &4 .. ec ++ .. ..
&0 \/ .. .. %% &4 &5 %% [[ .. ++ .. .. {0 {1 {3 .. &7 &7 &7 ..
\/ .. .. .. %% \/ \/ %% .. .. {0 {1 .. .. .. .. .. {7 {0 {1 ..
%% %% %% %% %% %% %% %% .. .. .. .. .. .. .. .. .. .. .. .. ..
}0 .. .. .. %% 00 00 %% }1 }2 .. }0 }0 }0 .. 23 .. .. .. .. ..
=A \\ du pe %% &1 &1 %% &6 &6 .. ec ec ec .. &4 .. .. .. .. ..
du pe &3 &8 %% &9 &8 %% {0 {1 .. &A &B &C .. [[ .. .. .. .. ..
&2 &9 \/ \/ %% &6 &7 %% .. .. .. {5 {2 {6 .. .. .. .. .. .. ..
\/ \/ .. .. %% \/ \/ %% .. .. .. .. .. .. .. .. .. .. .. .. ..
%% %% %% %% %% %% %% %% %% %% %% %% %% %% %% %% %% %% %% %% %%
}1 .. .. }1 .. .. }1 .. .. .. .. .. .. .. .. .. .. .. .. .. ..
&7 .. .. &7 }2 .. &7 }2 .. .. .. .. .. .. .. .. .. .. .. .. ..
=1 \/ .. mi nu .. mi nu .. .. .. .. .. .. .. .. .. .. .. .. ..
&A .. .. =1 \/ .. =2 \/ .. .. .. .. .. .. .. .. .. .. .. .. ..
\/ .. .. &B .. .. &C .. .. .. .. .. .. .. .. .. .. .. .. .. ..
.. .. .. \/ .. .. \/ .. .. .. .. .. .. .. .. .. .. .. .. .. ..
00 .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. ..
\\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ !!

# Encoding
#
# convert the char code to the encoding
:ec
}0 .. .. .. .. ..
++ .. .. .. .. ..
>> .. .. .. .. ..
>> .. .. .. .. ..
=S =B =C =N =9 ..
&0 &1 &2 &3 &4 &5
\/ \/ \/ \/ \/ \/
01 0A 0C 0B 0A 00
&0 &1 &2 &3 &4 &5
\\ \\ \\ {0 // //

# Print Bottom
#
# prints #\n then # repeated }0 times
:pb
0A .. @0 .. @1 ..
23 .. &0 .. &0 ..
[[ 23 /\ [[ -- ..
.. @0 .. }0 >0 \/
.. .. .. \\ @1 ..

# Print Cell
#
# }0 = the width of the board
# }1 = the position of the cell to print
# }2 = the cell to print
#
# prints the cell and a newline if needed
:printc
%% %% %% %% %% %% %% %% %% %% %% %% %% %% %% %% %% %% %% %% %% %% %%
%% }0 }1 %% .. %% }2 .. .. .. .. %% .. .. .. .. }2 %% }1 }0 %% .. %%
%% is bd %% 23 %% &0 .. .. .. .. %% 20 2D 5C 2F tn %% ++ .. %% 0A %%
%% =1 &0 %% &1 %% =0 =A =B =C <A %% &2 &3 &4 &5 &6 %% di vb %% &7 %%
%% &1 \/ %% [[ %% &2 &3 &4 &5 &6 %% [[ [[ [[ [[ [[ %% =1 \/ %% [[ %%
%% \/ .. %% .. %% \/ \/ \/ \/ \/ %% .. .. .. .. .. %% &7 .. %% .. %%
%% .. .. %% .. %% .. .. .. .. .. %% .. .. .. .. .. %% \/ .. %% .. %%
%% %% %% %% %% %% %% %% %% %% %% %% %% %% %% %% %% %% %% %% %% %% %%

# Is Border
#
# }0 = board width
# }1 = position
#
# {0 = 1 if on border else 0
:isbd
}1 }0 }1 }0
.. .. ++ ..
di vb di vb
\\ {0 // ..

# Solve Values
#
# takes input in a t:
# takes 4 cells in a t shape:
#       x    or    1
#      xxx        234
# and returns their values
# after 1 tick
:solvevls
# &0) center is space
# &1) center is wall
# &2) left slide & left is space
# &3) left slide & left isn't space
# &4) right slide & right is space
# &5) right slide & right isn't space
# &7) no ball
%% %% %% %% %% %% %% %% %% %% %%
%% }0 .. .. .. .. .. .. .. .. %% # Top Center
%% du pe 6x 6x 6x 6x .. .. .. %%
%% <A <A <A <A <A <A &7 .. .. %%
%% &0 &1 &2 &3 &4 &5 \/ .. .. %%
%% \/ \/ \/ \/ \/ \/ .. .. .. %%
%% %% %% %% %% %% %% %% %% %% %%
%% }1 .. .. .. .. .. .. .. .. %% # Bottom Left
%% du pe 6x 6x 6x 6x .. .. .. %%
%% .. .. <A >9 .. .. \/ .. .. %%
%% .. .. &2 &3 .. .. .. .. .. %%
%% \/ \/ \/ \/ \/ \/ .. .. .. %%
%% %% %% %% %% %% %% %% %% %% %%
%% }2 .. .. .. .. .. .. .. .. %% # Bottom Center
%% du pe 6x 6x 6x 6x .. .. .. %%
%% <A =A =C =C =B =B \/ .. .. %%
%% &0 &1 &2 &3 &4 &5 .. .. .. %%
%% \/ \/ \/ \/ \/ \/ .. .. .. %%
%% %% %% %% %% %% %% %% %% %% %%
%% }3 .. .. .. .. .. .. .. .. %% # Bottom Right
%% du pe 6x 6x 6x 6x .. .. .. %%
%% .. .. .. .. <A >9 \/ .. .. %%
%% .. .. .. .. &4 &5 .. .. .. %%
%% \/ \/ \/ \/ \/ \/ .. .. .. %%
%% %% %% %% %% %% %% %% %% %% %%
%% .. .. }0 .. %% .. .. .. .. %%
%% 00 }1 }2 }3 %% }0 }1 }2 }3 %%
%% &0 &0 &0 &0 %% &1 &1 &1 &1 %%
%% {0 {1 {2 {3 %% {0 {1 {2 {3 %%
%% %% %% %% %% %% %% %% %% %% %%
%% .. }0 .. .. %% .. .. .. .. %%
%% 00 }1 }2 }3 %% }0 }1 }2 }3 %%
%% &2 &2 &2 &2 %% &3 &3 &3 &3 %%
%% {0 {1 {2 {3 %% {0 {1 {2 {3 %%
%% %% %% %% %% %% %% %% %% %% %%
%% .. .. .. }0 %% .. .. .. .. %%
%% 00 }1 }2 }3 %% }0 }1 }2 }3 %%
%% &4 &4 &4 &4 %% &5 &5 &5 &5 %%
%% {0 {1 {2 {3 %% {0 {1 {2 {3 %%
%% %% %% %% %% %% %% %% %% %% %%
%% .. .. .. .. %% .. .. .. .. %%
%% }0 }1 }2 }3 %% .. .. .. .. %%
%% &7 &7 &7 &7 %% .. .. .. .. %%
%% {0 {1 {2 {3 %% .. .. .. .. %%
%% %% %% %% %% %% %% %% %% %% %%

# @0 set tape to position
#    @7 gets zero once complete
# @1 send current marble to location + advance one
# @2 write to current marble + advance one

# &0 = marble tape
# &1 = counter

# @3 counter loop
# @4, @5, @6

# .. .. .. .. .. .. .. .. .. .. .. .. .. .. ..
# .. .. .. 08 @5 .. .. .. .. .. .. .. .. .. ..
# .. 07 &0 // // .. .. .. .. .. .. .. .. .. ..
# .. \\ &0 06 .. .. .. .. .. .. .. .. .. .. ..
# .. 05 &0 // .. .. .. .. .. .. .. .. .. .. ..
# .. \\ &0 04 .. .. .. .. .. .. .. .. .. .. ..
# .. 03 &0 // .. .. .. .. .. .. .. .. .. .. ..
# .. \\ &0 02 .. .. .. .. .. .. .. .. .. .. ..
# .. 01 &0 // .. .. .. .. .. .. .. .. .. .. ..
# .. \\ &0 00 .. .. .. .. .. .. .. .. .. .. ..
# .. 00 &0 // .. .. .. .. .. .. .. .. .. .. ..
# .. \\ &0 00 .. .. .. .. .. .. .. .. .. .. ..
# .. 00 &0 // .. .. .. .. .. .. .. .. .. .. ..
# .. \\ &0 .. .. .. .. .. .. .. .. .. .. .. ..
# .. .. /\ @5 .. .. .. .. 00 .. .. .. .. .. ..
# .. >0 @8 .. .. .. .. .. .. .. .. .. .. .. ..
# .. &1 .. .. .. .. .. .. .. .. .. .. .. .. ..
# .. .. .. .. .. .. .. @8 .. @9 .. .. .. .. ..
# .. .. .. .. .. .. .. \\ &0 // .. .. .. .. ..
# .. .. .. .. .. .. .. .. \/ .. .. .. .. .. ..
# .. .. .. .. .. .. .. .. .. .. .. .. .. .. ..
# .. .. .. .. .. .. .. .. .. .. .. .. .. .. ..
# .. .. .. .. .. .. .. .. @3 00 .. .. .. .. ..
# .. .. .. .. .. .. .. .. &1 // .. .. .. .. ..
# .. .. .. .. .. .. .. .. ++ .. .. .. .. .. ..
# .. .. .. .. .. .. .. @3 /\ .. .. .. .. .. ..
# .. .. .. .. .. .. .. .. .. .. .. .. .. .. ..
# .. .. .. .. .. .. 05 @0 @4 .. .. .. .. .. ..
# .. .. .. .. .. .. \\ \\ te st .. .. .. .. ..
# .. .. .. .. .. .. .. .. @4 .. =0 \\ .. .. ..
# .. .. .. .. .. .. .. .. .. .. @9 .. .. .. ..
# .. .. .. .. .. .. .. .. .. .. .. .. .. .. ..
# .. .. .. .. .. .. .. .. .. .. .. .. \/ .. ..

# Test Equality
#
# if }0 == }1 sends 00 to {0 and 01 to {>
# else sends }0 to {0 and 00 to {>
:test
}0 }1 .. .. .. .. ..
mi nu .. .. }0 .. ..
=0 \\ \\ &0 &0 .. ..
du pe 3x \/ du pe 3x
ez eo .. .. .. .. ez
{0 {> !! .. !! {0 {>

### SIMPLE HELPERS ###

# Send
#
# sends }1 to {0 if }0 = 0 else {1
:send
}0 .. 00
=0 &1 ..
&0 \/ ..
\/ .. ..
}1 }1 ..
&0 &1 ..
{0 {1 !!

# Marker
#
# does nothing
:%%
}0
{0

## EQUALS ##

# Equals Max
#
# sends FF to {0
:em
}0 FF
.. {0

# Equal One
#
# sends 01 to {0
:eo
}0 01
.. {0

# Equal Zero
#
# sends 00 to {0
:ez
}0 00
.. {0

## DUPLICATE ##

# Duplicate 2 times
#
# sends }0 to {0 and {1
:dupe
.. }0 ..
{0 /\ {1

# Duplicate 3 times
#
# sends }0 to {0, {1, and {2
:dupe3x
.. }0 .. ..
.. /\ .. ..
.. .. /\ ..
.. .. .. //
{0 {1 {2 ..

# Duplicate 4 times
#
# sends }0 to {0, {1, {2, and {3
:dupe4x4x
.. }0 .. .. ..
.. /\ .. .. ..
.. .. /\ .. ..
.. .. .. /\ ..
.. .. .. .. //
{0 {1 {2 {3 ..

# Duplicate 6 times
#
# sends }0 to {0, {1, {2, {3, {4 and {5
:dupe6x6x6x6x
.. }0 .. .. .. .. ..
.. /\ .. .. .. .. ..
.. .. /\ .. .. .. ..
.. .. .. /\ .. .. ..
.. .. .. .. /\ .. ..
.. .. .. .. .. /\ ..
.. .. .. .. .. .. //
{0 {1 {2 {3 {4 {5 ..

### MATH ###

# Divisible By
#
# returns }0 % }1 == 0
:divb
}0 }1
mo du
=0 &1
&0 ..
01 00
&0 &1
{0 {0

# Modulo
#
# sends }0 % }1 to {0
#
# if }0 > }1 return modu }0 - }1 else }0
:modu
}0 }1
Gt eq # interpreter includes this
=1 &0
&1 \/
\/ ..
}0 ..
&0 ..
{0 ..
.. ..
}0 }1
mi nu
&1 }1
mo du
{0 ..

# To Number Char
#
# converts number 0-9 to a number character
:tn
}0
+F
+F
+F
+3
{0

# Plus
#
# sends }0 + }1 to {0
:plus
}0 .. }1
\\ {0 //

# Minus
#
# sends }0 - }1 to {0
:minu
.. }1
}0 ng
\\ {0

# Negative
#
# sends -}0 to {0
:ng
}0
~~
++
{0

```

# Answer
> 7 votes
# JavaScript (ES6), 157 ~~196~~

**Edit** char by char instead of row by row, much better result

```
g=>(s=~g.search`
`,g=[...g]).map((c,i)=>c<' '?0:g[[0,1,-1].map(d=>!d|'\\ /'[d+1]==g[d+=i]&&+g[d+=s]?g[v+=+g[d],d+v-v]=' ':0,v=c>'a'?1:+c),i]=v?v:c)&&g.join``

```

Note: does not handle ball values \> 9. But it could, with a 18 bytes cost. See basic code below.

**TEST snippet** (better full page)

```
F=g=>(s=~g.search`
`,g=[...g]).map((c,i)=>c<' '?0:g[[0,1,-1].map(d=>!d|'\\ /'[d+1]==g[d+=i]&&+g[d+=s]?g[v+=+g[d],d+v-v]=' ':0,v=c=='o'?1:+c),i]=v?v:c)&&g.join``

// Basic code, starting point before golfing
B=g=>{
  s = ~g.search('\n');
  (g=[...g]).map((c,i)=>{
    v = c == 'o' ? 1 : +c
    if (c>=' ' // skip newlines
        && !isNaN(v)) // digit or space
    {
      if (w=+g[i+s]) v += w, g[i+s]=' '
      if (g[i-1]=='\\' && (w=+g[i+s-1])) v += w, g[i+s-1]=' '
      if (g[i+1]=='/' && (w=+g[i+s+1])) v += w, g[i+s+1]=' '
      if (v) g[i] = v
    }
  })
  // return g.join``
  // To handle values > 9 ...
  return g.map(v=>+v?v%10:v).join``
}

function test() {
  O.textContent = F(I.value)
}

test()
```

```
textarea,pre { width: 15em; height: 15em; display: block; margin: 0; }
iframe { height: 25em; width: 15em}
td { vertical-align: top }
```

```
<table>
  <tr>
    <th>Test cases</th>
    <th>Input</th>
    <td></td>
    <th>Output</th>
  </tr><tr>
    <td>
    Copy/paste test cases from here <br>(courtesy of OP)
    <button onclick="T.src='http://bohem.io/wadus/index.php'">reload</button><br>
    <iframe id=T src="http://bohem.io/wadus/index.php"></iframe>
    </td>
    <td><textarea id=I>##########
#  o  o o#
# o\o o  #
#oo o/   #
#       o#
#     /o #
#\o   o  #
# o /-   #
#   o  - #
##########</textarea></td>
    <td><button onclick='test()'>Test</button></td>
    <td><pre id=O></pre></td>
  </tr>
</table>
```

# Answer
> 6 votes
# Javascript (ES6), ~~453~~ ~~426~~ ~~409~~ ~~306~~ ~~290~~ 286 bytes

The first and most obvious solution that came to my mind is one that looks around the slides and then merges or replaces.

```
a=>{a=a.split`
`.map(b=>[...b.replace(/o/g,'1')]);for(r=1;r<a.length-1;r++){d=a[r];for(c=1;c<d.length-1;c++){e=a[r+1];f=e[c]=='\\'?c+1:e[c]=='/'?c-1:!isNaN(+e[c])?c:null;(''+d[c]).match(/[0-9]/g)&&f!=null&&!isNaN(+e[f])?(e[f]=+e[f]+ +d[c],d[c]=' '):0}}return a.map(b=>b.join``).join`
`}

```

Ungolfed:

```
func = state => {
    state = state.split `
`.map(line => [...line.replace(/o/g, '1')]);

    for (r = 1; r < state.length - 1; r++) {
        thisState = state[r];
        for (c = 1; c < thisState.length - 1; c++) {
            nextState = state[r + 1];
            nc = nextState[c] == '\\' ? c + 1 : nextState[c] == '/' ? c - 1 : !isNaN(+nextState[c]) ? c : null;

            ('' + thisState[c]).match(/[0-9]/g) && nc != null && !isNaN(+nextState[nc]) ? (
                nextState[nc] = +nextState[nc] + +thisState[c],
                thisState[c] = ' '
            ) : 0;
        }
    }

    return state.map(line => line.join ``).join `
`;
}

```

Test like:

```
func(`##########
# -- o - #
# \\\\\\ -  #
#-       #
# o  o   #
#o \\\\ /-\\#
#      \\ #
#/-  //  #
#   /- o #
##########`)

```

*Thanks to: @edc65*

# Answer
> 5 votes
## Java, ~~Too Many~~ ~~1102~~ 987 bytes

Because, Java.

\o/ It's under 1000!

```
class G{class T{char s;int p=0;T(char c){s=c;}}T A=new T(' ');T[][]o;boolean i(){for(int i=1;i<o.length;i++)for(int j=1;j<o[i].length;j++)if(o[i][j].p>0){if(m(i,j,i+1,j)||o[i+1][j].s=='/'&&m(i,j,i+1,j-1)||o[i+1][j].s=='\\'&&m(i,j,i+1,j+1))return 1>0;int w=o[i][j].p;o[i][j]=new T(Integer.toString(w).charAt(0)){{p=w;}};}return 1<0;}boolean m(int a,int b,int c,int d){if(o[c][d]==A||o[c][d].p>0){o[a][b].p+=o[c][d].p;o[c][d]=o[a][b];o[a][b]=A;return 1>0;}return 1<0;}String s(){String s="";for(T[]r:o){for(T t:r)s+=t.s;s+="\n";}return s;}void f(String s){String[]r=s.split("\\\\n");o=new T[r.length][r[0].length()];for(int i=0;i<o.length;i++)for(int j=0;j<o[i].length;j++)switch(r[i].charAt(j)){case'-':o[i][j]=new T('-');break;case'\\':o[i][j]=new T('\\');break;case'/':o[i][j]=new T('/');break;case'o':o[i][j]=new T('o'){{p=1;}};break;case'#':o[i][j]=new T('#');break;default:o[i][j]=A;}}public static void main(String[]a){G g=new G();g.f(a[0]);while(g.i());System.out.println(g.s());}}

```

A side goal was being able to print every iteration of the board: just remove the middle `;` in `while(g.i())` `;` `System.out.print(g.s());` (Though this does disable the last print which has the 0-\>power conversion). Unfortunately, in this version, gravity works in strangely. Each pass I take the first non-stuck ball and move it. Short circuiting `iterate()` there is less bytes than going over the whole board then returning if anything changed.

This is a complete main class, compile and run on the command line with argument:

```
java -jar G.jar "##########\n# o-/    #\n#-  / -/ #\n# oo   o #\n# /   \o #\n# o   o \#\n#    o   #\n#   -\o  #\n#\  \\ o/#\n##########"

```

"Readable" version:

```
class GravitySimulator {
    class Token {
        char symbol;
        int power = 0;

        Token(char c) {
            symbol = c;
        }
    }

    Token A = new Token(' ');

    Token[][] board;

    boolean iterate() {
        for (int i=1; i<board.length; i++)
            for (int j=1; j<board[i].length; j++)
                if (board[i][j].power>0) {
                    if (move(i,j,i+1,j) || board[i+1][j].symbol=='/' && move(i,j,i+1,j-1) || board[i+1][j].symbol=='\\' && move(i,j,i+1,j+1)) return true;
                    int pow = board[i][j].power;
                    board[i][j] = new Token(Integer.toString(pow).charAt(0)){{power=pow;}};
                }
        return false;
    }

    boolean move(int x1, int y1, int x2, int y2) {
        if (board[x2][y2] == A || board[x2][y2].power>0) {
            board[x1][y1].power += board[x2][y2].power;
            board[x2][y2] = board[x1][y1];
            board[x1][y1] = A;
            return true;
        } return false;
    }

    String string() {
        String s = "";
        for (Token[] row : board) {
            for (Token token : row) s+=token.symbol;
            s+="\n";
        }
        return s;
    }

    void fromString(String s) {
        String[] rows = s.split("\\\\n");
        board = new Token[rows.length][rows[0].length()];
        for (int i=0; i<board.length; i++)
            for (int j=0; j<board[i].length; j++)
                switch(rows[i].charAt(j)) {
                    case '-': board[i][j]=new Token('-');break;
                    case '\\':board[i][j]=new Token('\\');break;
                    case '/': board[i][j]=new Token('/');break;
                    case 'o': board[i][j]=new Token('o'){{power=1;}};break;
                    case '#': board[i][j]=new Token('#');break;
                    default:  board[i][j]=A;
                }
    }

    public static void main(String[] args) {
        GravitySimulator g = new GravitySimulator();
        g.fromString(args[0]);
        while(g.iterate());
        System.out.println(g.string());
    }
}

```

# Answer
> 2 votes
## Python3, 355b

```
g=g.replace("o","1").split("\n")
r=1
while r:
 r=0
 for y in range(len(g)):
  for x in range(len(g[y])):
   if g[y][x].isdigit():
    h=g[y+1]
    m={"/":-1,"\\":1}
    j=x+m[h[x]]if h[x]in m else x
    if("0"+h[j].strip()).isdigit():
     r=1
     g[y+1]=h[:j]+str(int(g[y][x])+int("0"+h[j]))+h[j+1:]
     g[y]=g[y][:x]+' '+g[y][x+1:]
print("\n".join(g))

```

Test here

# Answer
> 1 votes
# PHP, ~~228 204 197~~ 194 bytes

```
for($a=strtr($a,o,1);$c=$a[$i];$i++)$c>0&&(($d=$a[$t=$i+strpos($a,"
")+1])>" "?$d!="/"?$d!="\\"?$d>0:$a[++$t]<"!"||$a[$t]>0:$a[--$t]<"!"||$a[$t]>0:1)&&$a[$t]=min($a[$t]+$c,9).!$a[$i]=" ";echo$a;

```

yields warnings in PHP 7.1. Insert `(int)` before `$a[$t]+$c` to fix.

Run with `php -nr '$a="<string>";<code>'` or try it online.

**breakdown**

```
for($a=strtr($a,o,1);   # replace "o" with "1"
    $c=$a[$i];$i++)     # loop through string
    $c>0                    # if character is numeric
    &&(($d=$a[                  # and ...
        $t=$i+                  # 3: target position = current position + 1 line
            strpos($a,"\n")+1   # 2: width = (0-indexed) position of first newline +1
    ])>" "                  # if target char is not space
        ?$d!="/"                # and not left slide
        ?$d!="\\"               # and not right slide
        ?$d>0                   # but numeric: go
        :$a[++$t]<"!"||$a[$t]>0     # right slide: if target+1 is space or ball, then go
        :$a[--$t]<"!"||$a[$t]>0     # left slide: if target-1 is space or ball, then go
    :1                              # space: go
    )&&                     # if go:
        $a[$t]=min($a[$t]+$c,9) # move ball/merge balls
        .!$a[$i]=" "            # clear source position
    ;
echo$a;                 # print string

```

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


title: Complex Binary Numbers

text:
# Question
Title: Complex Binary Numbers
Let's create a simple, surjective mapping from positive integers to Gaussian integers, which are complex numbers where the real and imaginary parts are integers.

Given a positive integer, for example `4538`, express it in binary with no leading `0`'s:

```
4538 base 10 = 1000110111010 base 2

```

Remove any trailing `0`'s:

```
100011011101

```

Replace any runs of one or more `0`'s with a single `+`:

```
1+11+111+1

```

Replace all `1`'s with `i`'s:

```
i+ii+iii+i

```

Evaluate the resulting complex expression and output the simplified Gaussian integer:

```
i+ii+iii+i = i+i*i+i*i*i+i = 2i+i^2+i^3 = 2i+(-1)+(-i) = -1+i

```

The output can be expressed in a traditional mathematical way, or given as two separate integers for the real and complex parts. For the `4538` example, any of these would be fine:

```
-1+i
i-1
-1+1i
(-1, 1)
-1 1
-1\n1

```

For inputs like `29`, mathy formatted outputs such as `0`, `0i`, or `0+0i` are all fine.

Using `j` (or something else) instead of `i` is fine if that is more natural for your language.

The shortest code in bytes wins.

# Answer
# MATL, 7 bytes

```
BJ*Y'^s

```

Try it online!

### How it works

Consider input `4538` for example.

```
B     % Implicit input. Convert to binary
      % STACK: [1 0 0 0 1 1 0 1 1 1 0 1 0]
J*    % Multiply by 1i
      % STACK: [1i 0 0 0 1i 1i 0 1i 1i 1i 0 1i 0]
Y'    % Run-length encoding
      % STACK: [1i 0 1i 0 1i 0 1i 0], [1 3 2 1 3 1 1 1]
^     % Power, element-wise
      % STACK: [1i 0 -1 0 -1i 0 1i 0]
s     % Sum of array. Implicit display
      % STACK: -1+1i

```
> 22 votes

# Answer
# Jelly, 8 bytes

```
BŒgaıP€S

```

Try it online!

### How it works

```
BŒgaıP€S  Main link. Argument: n (integer)

B         Convert to binary.
          If n = 4538, this yields [1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 0].
 Œg       Group equal elements.
          This yields [[1], [0, 0, 0], [1, 1], [0], [1, 1, 1], [0], [1], [0]].
   aı     Logical AND with the imaginary unit.
          This yields [[ı], [0, 0, 0], [ı, ı], [0], [ı, ı, ı], [0], [ı], [0]].
     P€   Product each.
          This yields [ı, 0, -1, 0, -ı, 0, ı, 0].
       S  Sum.
          This yields -1+ı.

```
> 13 votes

# Answer
## Python 2, 53 bytes

```
f=lambda n,k=0:(n and f(n/2,n%2*(k or 1)*1j))+~n%2*k

```

Been trying to golf this and it seems golfable but I'm out of ideas atm...
> 10 votes

# Answer
# Mathematica, ~~44~~ 38 bytes

```
Tr[1##&@@@Split[I*#~IntegerDigits~2]]&

```

# Explanation

```
#~IntegerDigits~2

```

Convert the input into base 2. (`4538` becomes `{1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 0}`)

```
I*

```

Multiply by `I` (`{1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 0}` becomes `{I, 0, 0, 0, I, I, 0, I, I, I, 0, I, 0}`)

```
Split

```

Split by runs (`{I, 0, 0, 0, I, I, 0, I, I, I, 0, I, 0}` becomes `{{I}, {0, 0, 0}, {I, I}, {0}, {I, I, I}, {0}, {I}, {0}}`)

```
1##&@@@ ...

```

Find the product at level 2. (`{{I}, {0, 0, 0}, {I, I}, {0}, {I, I, I}, {0}, {I}, {0}}` becomes `{I, 0, -1, 0, -I, 0, I, 0}`)

```
Tr

```

Sum the result. (`{I, 0, -1, 0, -I, 0, I, 0}` becomes `-1 + I`)
> 6 votes

# Answer
# Python, ~~199~~ ~~129~~ ~~124~~ ~~116~~ ~~94~~ ~~90~~ ~~71~~ ~~63~~ 61 bytes

```
print sum(1j**len(s)for s in bin(input())[2:].split('0')if s)

```

Input is just the number itself.
Output is in the format `(a+bj)`, where `j` is the imaginary unit. `0j` will be output instead of `(0+0j)`

First convert to binary. Truncate the `'0b'` off. Kill the trailing zeros. Split using a block of zero(s) as a delimiter. Map each block to `1j ** len`. Then, take the sum of the entire thing.

**-70 bytes** by not converting to pluses.
*-5 bytes* regex is shorter.
*-8 bytes* by getting rid of the two unnecessary variables that were only being called once.
*-22 bytes* by using complex numbers instead of my weird thing. Thanks to @Dennis' answer for informing me of complex numbers!
*-4 bytes* by realizing that `map` is just a fancy way of doing list comprehensions, except longer.
*-19 bytes* by switching to a slightly arcane method of avoiding errors with `j ** 0` and avoiding regex. Inspired by @Griffin's comment. Thanks! :)
*-8 bytes* by moving the `if` part to the end.
*-2 bytes* Thanks to @Griffin for saving 2 bytes by removing the square brackets to make it a generator expression instead!
> 5 votes

# Answer
# JavaScript (ES6), ~~67~~ 64 bytes

```
f=(n,q=0,a=[0,0])=>q|n?f(n/2,n&1?q+1:q&&0*(a[q&1]+=1-(q&2)),a):a
```

```
<input oninput="O.innerHTML=f(this.value)" type="number" step=1 min=0 value="4538">
<pre id=O></pre>
```

Outputs as a 2-element array.

### Explanation

Since JavaScript doesn't have imaginary numbers, we have to keep track of the real and imaginary parts in separate variables. The easiest way to do this is in a single array, with the real part first. **i** is represented as **\[0,1\]**, **i2** (or **-1**) as **\[-1,0\]**, **i3** (or **-i**) as **\[0,-1\]**, and **i4** (or **1**) as **\[1,0\]**.

First, we repeatedly divide the number by 2, collecting each run of ones in its binary representation. Each run of **n** ones corresponds to **in**. This corresponds to adding **1 - (n & 2)** to the item at index **n & 1** in the two-item array. So that's we do.

I should probably add more explanation, but I can't think of what else needs explaining. Feel free to comment with any questions you might have.
> 5 votes

# Answer
# Python 2, ~~77~~ ~~76~~ 71 bytes

```
p=r=0
for n in bin(input()*2):t=n=='1';r-=p*~-t;p=p*t*1jor t*1j
print r

```

*Thanks to @ZacharyT for golfing off 1 byte!*

Try it online!
> 5 votes

# Answer
# MATLAB, 58 bytes

```
@(x)eval([strrep(strrep(dec2bin(x),48,43),49,'i*1'),'.0'])

dec2bin(x) % converts the decimal value to a binary string of 1s and 0s.
strrep(dec2bin(x),48,43) % Substitutes ASCII character 48 with 43 (0s become +)
strrep(___,49,'i*1')     % Substitutes ASCII character 49 with 'i*1'
                         % 1s become 'i*1' (this is the gem)
eval([___,'.0']          % Appends .0 in the end and evaluates the expression.

```

Let's use `285` to illustrate the process:

```
temp1 = dec2bin(285)
      = 100011101

temp2 = strrep(temp1,48,43)
      = 1+++111+1

```

Luckily `1+++1` behaves just as `1+1` in MATLAB, so the above evaluates to: `1+111+1`.

```
temp3 = strrep(temp2,49,'i*1')
      = i*1+++i*1i*1i*1+i*1

```

Now this `strrep`-call is the real gem! By inserting `i*1` for `1` we get something really nice. If there's only one `1`, we simply get `i*1` which is `i`. If there are more than one then `i*1` gets repeated and concatenated into a sequence: `i*1i*1i*1i*1`. Since `i==1i` in MATLAB and `1i*1==i` this is simply: `i*i*i*i`.

```
temp4 = [temp3,'.0']
      = i*1+++i*1i*1i*1+i*1.0

```

Appending `.0` seems unnecessary here, but it's needed if the last character of `temp3` is a `+`. We can't append just a zero, since that would give `i*10` in the case above and therefore the wrong result.

And finally:

```
eval(temp4)
0.0000 + 1.0000i

```

This doesn't work in Octave for several reasons. `strrep` can't take ASCII-values as input, it needs the actual characters (`'0'` instead of `48`). Also, `+++` doesn't evaluate to just `+` in Octave, as that would break the increment/decrement shortcuts `x++` and `x--`.
> 4 votes

# Answer
# Pyth - 15 bytes

Frustratingly long.

```
s^L.j)hMe#r8jQ2

```

Test Suite.
> 3 votes

# Answer
# Mathematica, 84 bytes

```
ToExpression[#~IntegerString~2~StringTrim~"0"~StringReplace~{"0"..->"+","1"->"I "}]&

```

Anonymous function. Takes a number as input and returns a complex number as output.
> 2 votes

# Answer
# Mathematica, 75 bytes

```
ToExpression[#~IntegerString~2~StringReplace~{"1"->"I ","0"..->"+"}<>"-0"]&

```

Independently came up with almost the same solution that LegionMammal978 posted 23 minutes ago! Replacing `1` with `I`  (which is Mathematica's internal symbol for the square root of -1) works because spaces are treated as multiplication of neighboring expressions. The place I saved on the other solution, namely by avoiding the need for `StringTrim`, is by always appending `-0`: if the binary number ends in `1`, then this expression ends in `...I-0` which doesn't affect its value; while if the binary number ends in '0', then this expression ends in `...+-0` which is parsed as "add negative 0" and thus gets rid of the trailing plus sign.
> 2 votes

# Answer
# Matlab, 99 Bytes

```
function c=z(b)
c=0;b=strsplit(dec2bin(b),'0');for j=1:numel(b)-isempty(b{end});c=c+i^nnz(b{j});end

```

Test cases:

```
z(656) = 3i
z(172) = -1 + 2i
z(707) = -2 + i
z(32)  = i
z(277) = 4i

```
> 2 votes

# Answer
# Haskell, ~~102~~ ~~91~~ ~~89~~ 87 bytes

```
0%a=a
n%c@[a,b]|odd n=div n 2%[-b,a]|d<-div n 2=zipWith(+)c$d%[mod d 2,0]
(%[0,0]).(*2)

```

Repeatedly divides by two and checks the bit. Keeps an accumulator of `i^(number of odds)` where `a+b*i` is encoded as `[a,b]` and `*i` is `[a,b]↦[-b,a]` (rotation by 90 degrees). The initial `(*2)` is to avoid a lookup for the first bit.

Usage (thanks to @OwenMorgan for the examples):

```
(%[0,0]).(*2)<$>[656,172,707,32,277]
[[0,3],[-1,2],[-2,1],[0,1],[0,4]]

```
> 2 votes

# Answer
# Java, 172 bytes

```
l->{int i=0,j=i;for(String x:l.toString(2).split("0")){int a=x.length();j+=a&1>0?(a&3>2?(a-3)/-4+1:(a-3)/4+1):0;i+=a&1<1?(a&3>1?(a-3)/4+1:(a-3)/-4+1):0;}return i+"|"j+"i";}

```
> 1 votes

# Answer
# Clojure, 183 bytes

```
#(loop[x(clojure.string/split(Integer/toString % 2)#"0+")y[0 0]a 0](if(= a(count x))y(recur x(let[z([[1 0][0 1][-1 0][0 -1]](mod(count(x a))4))][(+(y 0)(z 0))(+(y 1)(z 1))])(inc a))))

```

Am I allowed to do this?

Use the function like so:

```
(#(...) {num}) -> (Wrap the # function in brackets first!)

```
> 1 votes

# Answer
# Actually, 35 bytes

```
├'0' aÆô' @s"j+"j'jo`"1j*1"'1τ(Æ`Y≡

```

Try it online!

Explanation:

```
├'0' aÆô' @s"j+"j'jo`"1j*1"'1τ(Æ`Y≡
├                                    binary representation of input
 '0' aÆ                              replace 0s with spaces
       ô                             trim leading and trailing spaces
        ' @s                         split on spaces
            "j+"j                    join with "j+"
                 'jo                 append "j"
                    `"1j*1"'1τ(Æ`Y   do until the string stops changing (fixed-point combinator):
                     "1j*1"'1τ(Æ       replace "11" with "1j*1"
                                  ≡  evaluate the resulting string to simplify it

```

Roughly equivalent Python 3 code:

```
a='j+'.join(bin(eval(input()))[2:].replace('0',' ').strip().split())+'j'
b=0
while a!=b:b,a=a,a.replace("11","1j*1")
print(eval(a))

```

Try it online!
> 1 votes

# Answer
# Jelly, 10 bytes

This isn't better than Dennis's Jelly answer, but I wanted to try my hand at a Jelly answer anyway. Golfing suggestions welcome! Try it online!

```
BŒrm2Ṫ€ı*S

```

**Ungolfing**

```
BŒrm2Ṫ€ı*S   Main link. Argument: n (integer)

B            Convert n to binary.
 Œr          Run-length encode the binary list.
   m2        Every 2nd element of the run_length encoding, getting only the runs of 1s.
     Ṫ€      Tail each, getting only the lengths of the runs.
       ı*    The imaginary unit raised to the power of each run (as * is vectorized).
         S   Sum it all into one complex number.

```
> 1 votes

# Answer
# Actually, 15 bytes

Golfing suggestions welcome! Try it online!

```
├'0@s``░`lïⁿ`MΣ

```

**Ungolfing:**

```
         Implicit input n.
├        Convert n to binary.
'0@s     Split by '0's.
``░      Filter out non-truthy values.
`...`M   Map over the filtered result, a list of runs of '1's.
  l        Yield the length of the run of '1's.
  ïⁿ       Yield the imaginary unit to the power of that length.
Σ        Sum all of this into one complex number.

```
> 1 votes

# Answer
# Axiom, ~~140, 131, 118~~ 108 bytes

```
b(x)==(s:=0;repeat(x=0=>break;r:=x rem 2;repeat(x rem 2=1=>(r:=r*%i;x:=x quo 2);break);s:=s+r;x:=x quo 2);s)

```

%i is the imaginary costant.Ungolfed

```
sb(x:NNI):Complex INT==
  r:Complex INT;s:Complex INT:=0
  repeat
    x=0=>break
    r:=x rem 2
    repeat
       x rem 2=1=>(r:=r*%i;x:=x quo 2)
       break
    s:=s+r
    x:=x quo 2
  s

```

results

```
(3) -> b 4538
   The type of the local variable r has changed in the computation.
   We will attempt to interpret the code.
   (3)  - 1 + %i
                                                    Type: Complex Integer
(4) -> b 29
   (4)  0
                                                    Type: Complex Integer
(5) -> sb 299898979798233333333333333339188888888888888888222
   Compiling function sb with type NonNegativeInteger -> Complex Integer
   (5)  - 7 + 12%i
                                                    Type: Complex Integer
(6) -> b 299898979798233333333333333339188888888888888888222
   (6)  - 7 + 12%i
                                                    Type: Complex Integer

```
> 0 votes

# Answer
# Perl 6,  ~~40~~  46 bytes

I came up with this fairly quickly

```
*.base(2).comb(/1+/).map(i***.chars).sum

```

Unfortunately it is currently inaccurate in the Rakudo implementation on MoarVM.
`say i ** 3; # -1.83697019872103e-16-1i`

So I had to do the next best thing:

```
*.base(2).comb(/1+/).map({[*] i xx.chars}).sum

```

## Expanded:

```
*\             # Whatever lambda
.base(2)       # convert to a Str representation in base 2
.comb(/ 1+ /)  # get a list of substrings of one or more ｢1｣s
.map({         # for each of those

  [*]            # reduce using ｢&infix:<**>｣
    i xx .chars    # ｢i｣ list repeated by the count of the characters matched

}).sum          # sum it all up

```

## Test:

```
.say for (4538, 29).map:

    *.base(2).comb(/1+/).map({[*] i xx.chars}).sum

# -1+1i
# 0+0i

```
> 0 votes

# Answer
# PHP, 87 bytes

```
for($n=$argv[1];$n|$i;$n>>=1)$n&1?$i++:($i?$i=0*${$i&1}+=1-($i&2):0);echo"(${0},${1})";

```

Almost the same as ETHproductions´ solution; only iterative instead of recursive.
Takes input from command line, sets variables `${0}` and `${1}`.
> 0 votes

# Answer
# TI-Basic (TI-84 Plus CE), 70 bytes

```
Prompt X
0→S
0→N
While X
If remainder(X,2
Then
N+1→N
int(X/2→X
Else
S+i^Nnot(not(N→S
X/2→X
0→N
End
End
S+i^Nnot(not(N

```

There's no builtin to convert to a binary string, (nor is there to parse a string), so this program manually divides by 2, incrementing N each time it sees a 1 and adding i^N to S (N\>0) and resetting N if it sees a zero.
> 0 votes

# Answer
# Java, 100 bytes

```
int[]f(int n){int c=2,r[]=new int[2];for(;n>0;r[c&1]+=n%4==1?(c&2)-1:0,n/=2)c=n%2<1?2:c+1;return r;}

```

Try it online!
> 0 votes

# Answer
# , 54 bytes

```
function(n,x=rle(n%/%2^(0:log2(n))%%2))sum(1i^x$l*x$v)

```

Try it online!

`n%/%2^(0:log2(n))%%2` computes a vector of the binary digits. Using the run-length encoding, we use R's `complex` type to compute the appropriate sum, multiplying by the `x$values` to remove zeros.

Returns a `complex` vector of one element.
> 0 votes

# Answer
# APL(Dyalog Extended), 13 bytes SBCS

```
+/×/¨0j1×⊆⍨⊤⎕

```

Try it on APLgolf!

A tradfn submission which takes a decimal number.
> 0 votes

---
Tags: code-golf, arithmetic, binary, integer, complex-numbers
---


title: Hermitian matrix?

text:
# Question
Title: Hermitian matrix?
**Note that this challenge requires no handling or understanding of complex numbers.**

Given a non-empty square matrix where every element is a two-element (Re,Im) integer list, determine (giving any truthy/falsy values or any two consistent values) whether this represents a Hermitian matrix.

Note that the input is a 3D array of integers; not a 2D array of complex numbers. If your language cannot take a 3D array directly, you may take a flat list (and the n×n or n×n×2 shape if that helps).

A matrix is Hermitian if it equals its own conjugate transpose. In other words, if you flip it across its top-left to bottom-right diagonal and negate the second element of all the two-element leaf-lists, it is identical to the input matrix. Note that the order of flipping and negating is irrelevant, so you may negate first, and flip afterwards.

### Walk-though example

This example uses JSON with superfluous white-space to ease reading:

```
[[ [2, 0] , [2, 1] , [4, 0] ],
 [ [2,-1] , [3, 0] , [0, 1] ],
 [ [4, 0] , [0,-1] , [1, 0] ]]

```

Transpose (flip across NW—SE diagonal):

```
[[ [2, 0] , [2,-1] , [4, 0] ],
 [ [2, 1] , [3, 0] , [0,-1] ],
 [ [4, 0] , [0, 1] , [1, 0] ]]

```

Negate second elements of leaf-lists:

```
[[ [2, 0] , [2, 1] , [4, 0] ],
 [ [2,-1] , [3, 0] , [0, 1] ],
 [ [4, 0] , [0,-1] , [1, 0] ]]

```

As this is identical to the input, the matrix is Hermitian.

## Test cases

### Hermitian

`[[[2,0],[2,1],[4,0]],[[2,-1],[3,0],[0,1]],[[4,0],[0,-1],[1,0]]]`

`[[[1,0],[2,0]],[[2,0],[1,0]]]`

`[[[1,0],[2,-3]],[[2,3],[1,0]]]`

`[[[42,0]]]`

### Non-Hermitian

`[[[2,0],[2,1],[4,0]],[[2,-1],[3,0],[0,1]],[[4,0],[0,-1],[1,-1]]]`

`[[[0,1],[0,2]],[[0,2],[0,1]]]`

`[[[1,0],[2,3]],[[2,3],[1,0]]]`

`[[[3,2]]]`

# Answer
# R, ~~71~~ ~~48~~ 47 bytes

```
function(A)all(Conj(t(B<-A[,,1]+A[,,2]*1i))==B)

```

Takes a 3D array of real numbers, make a 2D array of imaginary numbers, transpose, conjugate and compare.

Thanks to @Giuseppe for reducing the byte count by an astounding 23 bytes, and to @Vlo for the final 1!

Try it online!

Example:

```
> A <- array(c(2,2,4,2,3,0,4,0,1,0,-1,0,1,0,-1,0,1,0),dim=c(3,3,2))
> A
, , 1

     [,1] [,2] [,3]
[1,]    2    2    4
[2,]    2    3    0
[3,]    4    0    1

, , 2

     [,1] [,2] [,3]
[1,]    0    1    0
[2,]   -1    0    1
[3,]    0   -1    0

> f <- function(A)all(Conj(t(B<-A[,,1]+A[,,2]*1i))==B)
> f(A)
[1] TRUE

```
> 10 votes

# Answer
# Octave, ~~39~~ ~~34~~ 31 bytes

```
@(x)(y=x(:,:,1)+j*x(:,:,2))==y'

```

Try it online!

Saved 3 bytes thanks to Luis Mendo who informed me about the clarifications in the challenge text.

### Explanation:

In MATLAB and Octave, `'` is the conjugate complex transpose, not the "regular" transpose.

We create a variable `y` inline that's the first layer of the 3D matrix plus the second layer multiplied with the complex unit `j`, i.e. a complex matrix where the real term is the first "layer", and the imaginary is the second "layer". We then check if it equals itself complex conjugate transposed.

This will output a matrix containing only `1` if true, and a matrix containing at least one `0` if false. These are considered true and false in Octave (Proof).
> 7 votes

# Answer
# Python 2, 50 bytes

```
lambda m:[[[a,-b]for a,b in l]for l in zip(*m)]==m

```

Try it online!
> 6 votes

# Answer
# APL (Dyalog Unicode), ~~22~~ ~~15~~ ~~9~~ 7 bytes

```
⍉≡⊢∘-\¨

```

Try it online!

Tacit prefix function.

Thanks to Adám for 7 bytes on the Dfn, and to both Adám and ErikTheOutgolfer for ~~putting up with my stupidity~~ helping me find the tacit version.

Thanks to ngn for 2 bytes on the tacit version.

### How?

```
⍉≡⊢∘-\¨ ⍝ Anonymous tacit function.
      ¨ ⍝ Apply to each element of the argument:
     \  ⍝ Cumulative reduction, using
  ⊢∘-   ⍝ Ignore the first element, then negate the second
 ≡      ⍝ And match
⍉       ⍝ To the argument's transposition.

```
> 5 votes

# Answer
# Wolfram Language (Mathematica), ~~45~~ ~~34~~ ~~33~~ ~~26~~ ~~21~~ 18 bytes

```
#==#&[#.{1,I}]&
```

Try it online!
> 5 votes

# Answer
# Java 8, ~~137~~ ~~136~~ ~~134~~ ~~126~~ ~~119~~ 116 bytes

```
m->{int r=1,l=m.length,i=l*l,j,k;for(;i-->0;)r=m[j=i/l][k=i%l][0]!=m[k][j][0]|m[j][k][1]!=-m[k][j][1]?0:r;return r;}

```

-3 bytes thanks to *@ceilingcat*.

Returns `1` if Hermitian, `0` otherwise.

**Explanation:**

Try it online.

```
m->{                 // Method with 3D integer-array as parameter and boolean return-type
  int r=1,           //  Flag-integer `r`, starting at 1
      l=m.length,    //  The size of the 3D input array
      i=l*l,j,k;     //  Index-integers
  for(;i-->0;)       //  Loop over the rows and columns
    r=m[j=i/l][k=i%l][0]!=m[k][j][0]
                     //   If the first numbers diagonally aren't equal,
      |m[j][k][1]!=-m[k][j][1]?
                     //   or the second numbers aren't negatives of each other:
       0             //    Set the flag `r` to 0
      :              //   Else:
       r;            //    Leave the flag `r` the same
  return r;}         //  Return the flag `r`

```
> 4 votes

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

```
Z×Ø+⁼

```

A monadic link returning `1` for a Hermitian input and `0` otherwise.

**Try it online!**

### How?

```
Z×Ø+⁼ - Link: list of lists of lists, M
Z     - transpose
  Ø+  - literal = [1,-1]
 ×    - multiply (vectorises)
    ⁼ - equal to M?

```
> 3 votes

# Answer
# Haskell, 50 bytes

*-7 bytes thanks to H.PWiz.*

```
(==)<*>map(map((0-)<$>)).foldr(zipWith(:))e
e=[]:e

```

Try it online!
> 3 votes

# Answer
# , 14 bytes

```
[:(+-:|:)j./"1

```

Try it online!

## Explanation

```
[:(+-:|:)j./"1  Input: 3d array
         j./"1  Reduce by complex combine at rank 1
[:              Cap, operate on the 2d array of complex values
   +              Conjugate
      |:          Transpose
    -:            Match?

```
> 3 votes

# Answer
# 05AB1E, 9 bytes

```
øεεX®‚*]Q

```

Try it online!

**Explanation**

```
ø           # transpose
 ε          # apply to each 2-d array
  ε         # apply to each pair
   X®‚*     # multiply by [1,-1]
       ]    # end apply(s)
        Q   # compare to input for equality

```
> 2 votes

# Answer
# Ruby, 46 bytes

```
->m{m.transpose.map{|l|l.map{|a,b|[a,-b]}}==m}

```

Try it online!

Port of my Python answer
> 2 votes

# Answer
# Husk, 7 bytes

```
=¹mmṀ_T

```

Try it online!

# How?

Note that  should work instead of `mm` , but there's an annoying bug that prevents me from using it :(

```
=¹mmṀ_T – Full program. Takes input from Command line args, as a list of lists of tuples.
  m   T – For each list in the input's tranpose...
   mṀ_  – ... Negate the last value of each tuple they contain.
=¹      – Check whether this is the same as the input.

```
> 1 votes

# Answer
# Perl 5, -a0 48 bytes

Old counting: 50 bytes (`+2` for `a0`). Not bad for a language that has no builtin transpose (I'm not jealous at all, no sirree)

Give the input matrix on STDIN with `,` between the real and imaginary part, so e.g.:

```
2,0 2,1 4,0
2,-1 3,0 0,1
4,0 0,-1 1,0

```

Will print `1` for hermitian, nothing otherwise

```
#!/usr/bin/perl -a0
say@F~~[map/(\S+,)(\S+)/gc?$1.-$2:(),(/.+/g)x@F]

```

Try it online!
> 1 votes

# Answer
# C (gcc), ~~107~~ ~~103~~ 100 bytes

* Saved four bytes thanks to Steadybox; golfed `A[0]` to `*A` twice.
* Saved three bytes thanks to ceilingcat.

```
j,k,r;f(A,s)int***A;{for(r=0,j=s;j--;)for(k=s;k--;)r|=*A[j][k]-*A[k][j]|A[j][k][1]+A[k][j][1];A=!r;}

```

Try it online!
> 1 votes

# Answer
# JavaScript (ES6), 53 bytes

*Saved 2 bytes thanks to @Neil*

Returns `false` for Hermitian or `true` for non-Hermitian.

```
m=>m.some((r,y)=>r.some(([a,b],x)=>m[x][y]!=a+[,-b]))

```

Try it online!
> 1 votes

# Answer
# C,  ~~111~~   ~~110~~  108 bytes

*Thanks to @Jonathan Frech for saving a byte and thanks to @ceilingcat for saving two bytes!*

```
i,j,r;f(A,n)int*A;{for(r=i=0;i<n*2;i+=2)for(j=n*2;j;r|=A[i*n+j]-A[j*n+i]|A[i*n-~j]+A[j*n-~i])j-=2;return!r;}

```

Try it online!

# C (gcc),  ~~106~~  104 bytes

```
i,j,r;f(A,n)int*A;{for(r=i=0;i<n*2;i+=2)for(j=n*2;j;r|=A[i*n+j]-A[j*n+i]|A[i*n-~j]+A[j*n-~i])j-=2;A=!r;}

```

Try it online!
> 0 votes

# Answer
# Actually, 13 bytes

```
┬⌠⌠Çá╫k⌡M⌡Mß=

```

Try it online!

## How it works?

This submission **actually** makes use of complex numbers. If taking input as a matrix of complex entries was allowed, then it would be 8 bytes.

```
┬⌠⌠Çá╫k⌡M⌡Mß=  –> Full program.
┬              –> Transpose.
 ⌠       ⌡M    –> For each list in the input's transpose do the following:
  ⌠    ⌡M         –> For each two-element list of the form [a, b]...
   Ç              –> Turn it into a complex number (a+bi).
    á             –> Find its complex conjugate: Push (a-bi).
     ╫k           –> Push [Re(N), Im(N)], so [a, -b].
           ß=  –> Check whether the result equals the input.

```
> 0 votes

# Answer
# Pyth, 9 bytes

```
qCmm,hk_e

```

Explanation:

```
qCmm,hk_ekdQQ  Autofill variables
    ,hk_ek     [a,-b]...
  mm      dQ    ...for each [a,b] in the input (m...Q)'s rows (m...d).
 C             Transpose.
q           Q  Is this result equal to the original?

```

Test suite.
> 0 votes

# Answer
# Actually, 13 bytes

```
;┬⌠⌠d±@q⌡M⌡M=

```

Try it online!

Explanation:

```
;┬⌠⌠d±@q⌡M⌡M=
;              make a copy
 ┬             transpose copy
  ⌠⌠d±@q⌡M⌡M   for each row:
   ⌠d±@q⌡M       for each cell in row:
    d              remove last element from list
     ±             swap sign
      @q           insert at end of list
            =  compare equality with original

```
> 0 votes

# Answer
# Stax, 9 bytes

```
ü♦╧Γ♥├eï∞

```

Run and debug it
> 0 votes

---
Tags: code-golf, math, decision-problem, matrix, complex-numbers
---


title: Approximate the Score of a 2048 Game

text:
# Question
Title: Approximate the Score of a 2048 Game
A game of 2048 goes like this:

* Every move you get another piece - either `2` 90% of the time, or `4` 10% of the time
* for each 2 equal pieces combined you get a piece of the sum of the two and the sum gets added to your score

# Your task

given a board of a 4x4 game, give the average score of what A game like that would result in.

To calculate it, go the other way around of the game. For example, if there's an `8` piece, it's made from `4`s. The average score of a 4 piece is 4\*90% (90% of the time it's made from combining two `2` pieces together and it the other 10% a `4` isn't made, but ) = 3.6. As to make an `8` you need two `4`s, and then you need to combine them to an `8`, the result is 3.6\*2 + 8 = 15.2.

In pseudocode a calculation for one number could be this:

```
function value (x) {
  if (x > 4) return value(x / 2) * 2 + x
  else if (x == 4) return 4*90%
  else return 0
}

```

but you're free to choose any approach as long as it works the same.

## Clarifications

* The input board will always be from a 4x4 board.
* You can take in the board as an array of the 16 values, as 16 different inputs or even a 2D array if that somehow helps you.
* The input numbers will always be zero or 2 to the power of a positive integer.
* You can discard any errors due to floating point operations (but theoretically the program must implement a correct algorithm).
* This is , the shortest code wins!

## Test-cases

```
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] -> 0
[2,4,2,4,4,2,4,2,2,4,2,4,4,2,4,2] -> 28.8
[4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4] -> 57.6
[0,0,0,4,0,0,0,8,0,0,0,16,2,2,0,2048] -> 20340.4
[2,16,2048,4096,4,32,1024,8192,8,64,512,16384,16,128,256,32768] -> 845465.2
[8,8,4,4,0,0,0,0,0,0,2,2,2048,65536] -> 996799.2

```

# Answer
> 4 votes
# Python 3, 51 48 bytes

<sup> -3 bytes thanks to Mr. Xcoder!</sup>

```
lambda b:sum(n*max(0,len(bin(n))-4.1)for n in b)

```

Try it online!

# Answer
> 1 votes
# C# (.NET Core), 101 100 bytes

```
n=>{double k=0,l=0;for(int i=0,j;i<n.Length;l+=k,++i)for(j=4;j<=n[i];j*=2)k=j>4?k*2+j:3.6;return l;}

```

Try it online!

Lambda function. Takes in an array for the board, and returns a double for the score

# Answer
> 1 votes
# APL (Dyalog Extended), 18 bytes

```
+/{⍵×0⌈2.1-⍨≢⊤⍵}¨⎕

```

Try it online! or Verify all test cases

Full program submission.

Port of the Python answer.

## Explanation

```
+/{⍵×0⌈2.1-⍨≢⊤⍵}¨⎕
                ¨⎕ to each element of the input:
              ⊤⍵   convert to base 2 digits
       2.1-⍨≢      length - 2.1
     0⌈            maximum with 0
   ⍵×              times the element
+/                 sum the resulting array

```

# Answer
> 1 votes
# JavaScript (V8), 58 bytes

```
b=>b.reduce((a,n)=>a+(z=x=>x>4?z(x/2)*2+x:x-4?0:3.6)(n),0)

```

---
Tags: code-golf
---


title: Bake me some moji

text:
# Question
Title: Bake me some moji
Given a string, character list, byte stream, sequence… which is both valid UTF-8 and valid Windows-1252 (most languages will probably want to take a normal UTF-8 string), convert it from (that is, *pretend* it is) Windows-1252 to UTF-8.

### Walked-through example

The UTF-8 string
`I`  `U``T``F``-``8`
is represented as the bytes
`49` `20``E2 99 A5``20` `55` `54` `46` `2D` `38`
these byte values in the Windows-1252 table gives us the Unicode equivalents
`49` `20` `E2 2122 A5` `20` `55` `54` `46` `2D` `38`
which render as
`I``â``¥``U``T``F``-``8`

### Examples

`£``Â£`

`Â£``Ã‚Â£`

`Ã‚Â£``Ãƒâ€šÃ‚Â£`

`I ♥ UTF-8``I â™¥ UTF-8`

`árvíztűrő tükörfúrógép``Ã¡rvÃztÅ±rÅ‘ tÃ¼kÃ¶rfÃºrÃ³gÃ©p`

# Answer
> 23 votes
## bash, 14 bytes

```
iconv -fCP1252

```

Try it online!

# Answer
> 20 votes
# Java 8, ~~72~~ ~~66~~ ~~36~~ 25 bytes

```
s->new String(s,"cp1252")

```

Try it online.

```
s->  // Method with byte-array (UTF-8 by default) as parameter and String return-type
  new String(s,"cp1252")
     //  Pretend this UTF-8 input is (and convert it to) Windows-1252,
     //  and return it as UTF-8 String (by default) as well

```

`cp1252` is an alias for `Windows-1252`. This alias `cp1252` is the Canonical Name for the `java.io` and `java.lang` APIs, while the full name `Windows-1252` is the Canonical Name for the `java.nio` API. See here for a full list of supported Java encodings, where we'd always want to use the shortest of the two for codegolfing.

# Answer
> 9 votes
# 3.5.0 or higher, ~~32~~ 20 bytes

```
scan(,"",e="latin1")

```

Try it online!

Oddly short for a challenge in R... *thanks to JayCe for golfing down 12 more bytes!*

`scan` optionally takes an `encoding` argument to set the encoding of the input string. `latin1` corresponds to, according to the documentation of `Encoding`

> There is some ambiguity as to what is meant by a ‘Latin-1’ locale, since some OSes (notably Windows) make use of character positions used for control characters in the ISO 8859-1 character set. How such characters are interpreted is system-dependent but as from R 3.5.0 they are if possible interpreted as per Windows codepage 1252 (which Microsoft calls ‘Windows Latin 1 (ANSI)’) when converting to e.g. UTF-8.

# Answer
> 6 votes
# Python 2, ~~40~~ 38 bytes

-2 bytes thanks to Erik the Outgolfer.

```
lambda s:s.decode('1252').encode('u8')

```

Try it online!

u8 is an alias for `utf-8`.

# Answer
> 4 votes
# Ruby, 31 bytes

```
->s{s.encode("UTF-8","CP1252")}

```

Try it online!

Tests cases are included in the TIO

# Answer
> 4 votes
# Python 3, ~~38 36~~ 34 bytes

```
lambda s:s.encode().decode('1252')

```

Try it online!

*note: After I had a working function I used ovs's python2 answer answer to learn about the header and footer fields for tio, so the header and footer are the same*

*edit: Trimmed it a little thanks to python3 defaulting to utf8 and a tip from ovs's submission :)*

# Answer
> 3 votes
# C#, 81 bytes

```
using e=System.Text.Encoding;s=>e.GetEncoding(1252).GetString(e.UTF8.GetBytes(s))

```

Try it online!

Thanks to Schmalls for 3 bytes

# Answer
> 3 votes
# 180 bytes, machine code (16-bit x86)

I noticed most answers use builtin encode/decode (which I believe is perfectly fine), but I thought I'll continue my 16-bit quest.

As with previous ones, this was done **without compiler** using mostly HT hexeditor and ICY's hexplorer.

```
00000000: eb40 ac20 0000 1a20 9201 1e20 2620 2020  .@. ... ... &
00000010: 2120 c602 3020 6001 3920 5201 0000 7d01  ! ..0 `.9 R...}.
00000020: 0000 0000 1820 1920 1c20 1d20 2220 1320  ..... . . . " .
00000030: 1420 dc02 2221 6101 3a20 5301 0000 7e01  . .."!a.: S...~.
00000040: 7801 89f7 4646 89fa 89d9 4143 4bb4 3fcd  x...FF....ACK.?.
00000050: 2185 c074 288a 053c 8073 05e8 1700 ebec  !..t(..<.s......
00000060: 3ca0 721a d440 0d80 c050 86c4 e806 0058  <.r..@...P.....X
00000070: e802 00eb d7b4 4088 05b3 01cd 21c3 2c80  ......@.....!.,.
00000080: d0e0 89c3 8b00 89cb 85c0 74c0 3dff 0773  ..........t.=..s
00000090: 08c1 c002 c0e8 02eb cd50 c1e8 0c0c e0e8  .........P......
000000a0: d3ff 5825 ff0f c1c0 02c0 e802 0d80 8050  ..X%...........P
000000b0: 86c4 ebb8                                ....

```

## Dissection

Implementation is pretty straight-forward, although I haven't given much thought to flow upfront so there is SOME spaghetti there.

I'll mix order a bit, to make it easier to follow...

```
0000 eb40               jmp         0x42

```

Skip over table that maps chars \>= 0x80 \< 0xa0, to unicode codes.

```
data db ACh,20h, 00h,00h, 1Ah,20h, ...

```

Invalid ones are encoded as 0, they are not mapped to anything

```
0075 b440               mov         ah, 0x40
0077 8805               mov         [di], al
0079 b301               mov         bl, 0x1
007b cd21               int         0x21
007d c3                 ret

```

Helper function used to print char in `al`, will be called few times.

```
0042 89f7               mov         di, si
0044 46                 inc         si
0045 46                 inc         si
0046 89fa               mov         dx, di
0048 89d9               mov         cx, bx
004a 41                 inc         cx
004b 43                 inc         bx

```

Prepare registers. Data will be read into 0x100, let `si` point into translation table above.

```
004c 4b                 dec         bx
004d b43f               mov         ah, 0x3f
004f cd21               int         0x21
0051 85c0               test        ax, ax
0053 7428               jz          0x7d

```

Read char from stdin, jump to 0x7d if EOF.

Sidenote: This actually is a small (but pretty well known) trick, 0x7d contains `ret`, this will cause `pop sp`, `sp` at start points to end of a segment, there's `00 00` there, and `cs:0` in DOS contains `CD 20`, which causes application to exit.

```
0055 8a05               mov         al, [di]
0057 3c80               cmp         al, 0x80
0059 7305               jnc         0x60
005b e81700             call        0x75
005e ebec               jmp         0x4c

```

If char is \< 0x80, just print it out, and go to beginning of loop (because helper function is setting BX to 1 - stdout, jumps will go to `dec bx`)

```
0060 3ca0               cmp         al, 0xa0
0062 721a               jc          0x7e
0064 d440               aam         0x40
0066 0d80c0             or          ax, c080
0069 50                 push        ax
006a 86c4               xchg        ah, al
006c e80600             call        0x75
006f 58                 pop         ax
0070 e80200             call        0x75
0073 ebd7               jmp         0x4c

```

This part deals with chars \>= 0xa0, splits ascii code into "high" two bits and "low" 6 bits and applies utf-8 mask c080 for two bytes, then prints both of them

```
007e 2c80               sub         al, 0x80
0080 d0e0               shl         al, 0x1
0082 89c3               mov         bx, ax
0084 8b00               mov         ax, [bx+si]
0086 89cb               mov         bx, cx
0088 85c0               test        ax, ax
008a 74c0               jz          0x4c
008c 3dff07             cmp         ax, 07ff
008f 7308               jnc         0x99
0091 c1c002             rol         ax, 0x2
0094 c0e802             shr         al, 0x2
0097 ebcd               jmp         0x66

```

This part deals with chars \>= 0x80 \< 0xa0, it finds proper utf-8 code in the table at the top, if code equals 0, just skip to beginning, if it's below 0x7ff (ergo: fits on two UTF-8 bytes), just adjust the value and re-use previous code at 0x166.

```
0099 50                 push        ax
009a c1e80c             shr         ax, 0xc
009d 0ce0               or          al, e0
009f e8d3ff             call        0x75
00a2 58                 pop         ax
00a3 25ff0f             and         ax, 0fff
00a6 c1c002             rol         ax, 0x2
00a9 c0e802             shr         al, 0x2
00ac 0d8080             or          ax, 8080
00af 50                 push        ax
00b0 86c4               xchg        ah, al
00b2 ebb8               jmp         0x6c

```

Final part, deals with codes that are above 0x7FF, drop low 12 bits, apply 0xE0 (see UTF-8 encoding description for reference) and print it out, adjust lower 12 bits and apply 8080 mask and again reuse part that spits out two chars.

# Answer
> 2 votes
# JavaScript, 64 bytes

```
x=>new TextDecoder('cp1252').decode(new TextEncoder().encode(x))

```

```
f =
x=>new TextDecoder('cp1252').decode(new TextEncoder().encode(x))
```

```
<p><input id=i oninput="o.value=f(i.value)" style="width:100%" /></p>
<p><output id=o></output></p>
```

Even longer than Java answer. So sad. :(

# Answer
> 1 votes
## PHP+mbstring, ~~63~~ 49 bytes

`<?=mb_convert_encoding($argv[1],'UTF8','CP1252');`

It doesn't work on TIO due to the lack of mbstring. The third parameter force mbstring to interpret the string as Windows-1252 encoded

-14 bytes thanks to Ismael Miguel

# Answer
> 0 votes
# C (gcc) \+ `libiconv`, 119 117 bytes

```
*f(s,t,u)void*s,*t,*u;{long i=strlen(s),j=i*4;u=t=malloc(j);iconv(iconv_open("UTF8","CP1252"),&s,&i,&u,&j);return t;}

```

Try it online!

# Answer
> 0 votes
# Scala 3, 18 bytes

Simply a port of Kevin Cruijssen's Java answer

```
String(_,"cp1252")

```

Try it in Scastie!

Ordinarily, I wouldn't post such a trivial answer, but this demonstrates Scala 3's universal apply methods, which let you omit `new`.

---
Tags: code-golf, string, conversion, unicode, encoding
---


title: What valence does this APL train have?

text:
# Question
Title: What valence does this APL train have?
# Context

In APL, trains are tacit sequences of monadic/dyadic functions that can be called with one or two arguments. We'll code something to check if a given train follows the correct structure we need in order to have a sound train.

# Task

Given the sequence of function arities in the train, determine if the train is valid as a monad and/or as a dyad. Don't forget that APL reads from right to left, so when I mention the "start" I mean the end of the array! A train is valid as a monad if

* is starts with an arbitrary number of `DM` (0 or more) and then ends in 1 or 2 monadic functions; e.g. `MM`, `MDM`, `MMDM` and `MDMDM` are valid monadic trains.

A dyadic train is valid if

* the train starts with an odd number of dyadic functions, possibly ending with a monadic function; e.g. `D`, `MDDD` and `DDDDD` are valid dyadic trains.

# Input

Your input is going to be a non-empty list of the arities of the functions in the train, where said list contains up to 3 different elements; one for purely monadic functions, another for purely dyadic functions and another for functions that can be either monadic or dyadic, depending on usage.

The input list can be taken in any sensible format and likewise the elements can be whatever 3 distinct elements you choose. E.g. take a string with the letters `MDB` or take a list of integers `0,1,2`. I don't mind you play around with this, just let us know what your answer uses.

APL reads from right to left and we will embody this in the challenge; input *cannot* be reversed.

# Output

Your function should adhere to one of the two output formats:

* output one of 4 distinct values; one for a train that only works monadically, one for a train that works dyadically, one for a train that works both ways and yet another one for a train that doesn't work in any way; any consistent 4 distinct values will do;
* output two Truthy/Falsy values, with respect to the standard Truthy/Falsy defaults of your language, where the first value flags if the train works monadically and the second to flag if the train works dyadically, or vice-versa.

# Test cases:

The pair `(a, b)` is used, where `a` says if the train is valid to be used monadically and `b` says if the train is valid dyadically.

```
DB
(False, False)
DD
(False, False)
DM
(False, False)
MBDBMDD
(False, False)
DDBB
(False, False)
DMMDDM
(False, False)
DBDDBDMMD
(False, False)
BMDBDD
(False, False)
MMMDD
(False, False)
MMBMBMMBM
(False, False)
DDBBMDDMMD
(False, False)
DDMB
(False, False)
D
(False, True)
MD
(False, True)
BD
(False, True)
BBBDBDDBD
(False, True)
MDBBBBDB
(False, True)
M
(True, False)
MM
(True, False)
BM
(True, False)
MMDM
(True, False)
MDM
(True, False)
BDM
(True, False)
MMBBDMDB
(True, False)
MBM
(True, False)
B
(True, True)
MB
(True, True)
BB
(True, True)
BBB
(True, True)
BBBB
(True, True)
BBBBB
(True, True)
MBBBBBBB
(True, True)
BDBBBBBDB
(True, True)

```

Generated and tested with this Python code. Feel free to use the TIO link and edit the final printing loop to print all the test cases in a format that is easier for you to use in your answer.

# Answer
# Haskell, 61 bytes

```
f t=[and$zipWith(/=)t$[2|even$length t]++cycle[x,0]|x<-[2,0]]

```

Try it online!

Takes a list of: `0` for monad, `1` for both, `2` for dyad. Returns `[a,b]`.

The valid monad trains are:

```
M
MM
MDM
MMDM
MDMDM
MMDMDM
...

```

And the valid dyad trains are:

```
D
MD
DDD
MDDD
DDDDD
MDDDDD
...

```

So we check the input against this pattern, first for `x=M` and then `x=D`:

```
x
Mx
xDx
MxDx
xDxDx
MxDxDx
...

```

To generate the pattern, we start with `M` if the length is even, then alternate `x` and `D`. (Haskell's laziness lets me use `cycle`, which creates an infinite alternating list, rather than specify how long to alternate for: `zipWith` will only consume the pattern until it hits the end of `t`.)

I use `(/=)` and invert the pattern to support `B` as a wildcard.
> 10 votes

# Answer
# APL (Dyalog Unicode), 59 bytes (SBCS)

Anonymous tacit prefix function. Returns `[]` if invalid, `[[]]` if dyadic, `[0]` if monadic, and `[0,[]]` if both.

```
R←'\pL'⎕R'[&B]'
((R'^M(DM)*M?$')⎕S 3,(R'^D(D{2})*M?$')⎕S⍬)⌽

```

Try it online!

`R←` define helper function to expand regexes:
`'\pL'⎕R`… PCRE **R**eplace characters with the **p**roperty **L**etter with…
`'[&B]` with open-bracket, the letter, "b", close-bracket (makes any letter represent itself or "B")

reverse the train (to work from right to left)
`(``,``)` concatenate the results of applying the following two functions:
1. `(``)⎕S 3` PCRE **S**earch for the following regex (`[0]` if found, else `[]`):
`R'^M(DM)*M?$'` the function `R` applied to the string: `^[MB]([DB][MB])*[MB]?$`
2. `(``)⎕S⍬` PCRE **S**earch for the following regex (`[[]]` if found, else `[]`):
`R'^D(D{2})*M?$'` the function `R` applied to the string: `^[DB]([DB]{2})*[MB]?$`
> 8 votes

# Answer
# 05AB1E, ~~36~~ ~~34~~ ~~30~~ 27 bytes

```
$DgÈić≠s}WĀs2Å€É}Ā¬_sDÔQ*‚*

```

Input as a string where `D=1,M=0,B=2`, output as a pair of truthy/falsey values `[isDyadic, isMonadic]`.

Try it online or verify all test cases.

**Explanation:**

```
$                   # Push 1 and the input
 Dg                 # Duplicate the input, and pop and push its length
   Èi               # If this length is even:
     ć              #  Extract head; pop and push remainder-string and head separated
      ≠             #  Check that this head is NOT 1 (thus NOT "D")
       s            #  Swap so the remainder-string is at the top
    }W              # After the if-statement: get the smallest digit (without popping)
      Ā             # Check that this digit is NOT 0 (thus NOT "M") (0 if 0; 1 if 1 or 2)
       s            # Swap so the string is at the top again
        2Å€         # For every 2nd digit (0-based indices 0,2,4,etc.):
           É        #  Replace all 2s with 0s ("B" to "M"), by checking whether the
                    #  digit is odd (1 if 1; 0 if 0 or 2)
          }         # Close the even-map, which changed the string to a digit-list
           Ā        # Replace all remaining 2s with 1s ("B" to "D"), by python-style
                    # truthifying each digit (1 if 1 or 2; 0 if 0)
            ¬       # Get the first digit (without popping the list itself)
             _      # Check that it's equal to 0 (thus "M")
            s       # Swap so the list is at the top again
             D      # Duplicate this list
              Ô     # Connected uniquify; remove any digits equal to its neighbor
               Q    # Check that the two lists are equal (thus it was alternating)
                *   # Multiply it by the head=="M"
                 ‚  # Pair it together with the minimum!="M"
                  * # And multiply both to the head!="D"
                    # or the 1 we pushed initially with `$` if the length was odd
                    # (after which the result is output implicitly)

```
> 4 votes

# Answer
# JavaScript (ES6),  ~~67 64~~  61 bytes

Expects an integer with `123` for `MDB`. Returns **1** for monadic, **2** for dyadic, **3** for both, or **0** for neither.

```
f=(n,d=2,q=m=1)=>n<4?q&n|(n^m&&d):f(n/10,d&n%5,n%5&m&&q,m^=3)

```

Try it online!

### How?

We use the following variables:

* \\$n\\$ is the input, which is divided by \\$10\\$ between each iteration. (The result is not rounded to save a few bytes, but the rest of the code was tuned to behave as if it were.)
* \\$d\\$ is a flag initialized to \\$2\\$ and set to \\$0\\$ as soon as a monadic-only function is extracted, thus breaking a dyadic train.
* \\$q\\$ is a flag initialized to \\$1\\$ and set to \\$0\\$ as soon as the dyadic/monadic pattern is no longer met, thus breaking a monadic train.
* \\$m\\$ is a mask initialized to \\$1\\$ and switching between \\$1\\$ and \\$2\\$ between each iteration. It is used to update \\$q\\$ and for the final test of the dyadic train.

In order to save two bytes on the update of \\$d\\$ and \\$q\\$, we use the fact that:

$$(n\bmod 10) \operatorname{AND} 3 = (n\bmod 5) \operatorname{AND} 3,\\:n\bmod 10\<4$$

We stop the recursion as soon as there's only one digit left, which is therefore stored in the final value of \\$n\\$.

The train is monadic if:

> \\$q\\$ is still set to \\$1\\$ and \\$n\\$ is odd

The train is dyadic if:

> \\$d\\$ is still set to \\$2\\$ and \\$n\\$ is not equal to \\$m\\$

This last condition (\\$n\neq m\\$) can be interpreted as follows:

* If \\$m=n=1\\$, it means that we had an even number of dyadic functions so far and the last function is monadic-only.
* If \\$m=n=2\\$, it means that we had an odd number of dyadic functions so far and the last function is dyadic-only.
> 4 votes

# Answer
# Jelly, 26 25 bytes

```
LḂ
¹;2ṙ1ƊÇ?µnJḂ$Ạð,µḢnÇaẠ

```

Try it online!

Input is a list of numbers: 0 = M, 1 = D, 2 (or any other number) = B. Output is a pair of 0 or 1, representing the possibility of a monad/dyad respectively.

I really wanted to beat the 05AB1E submission and it seems that I succeeded.

## Explanation

```
LḂ   Auxiliary link
L    Length
 Ḃ   Parity

¹;2ṙ1ƊÇ?µnJḂ$Ạð,µḢnÇaẠ   Main link accepting a list L
       ?                 If
      Ç                  previous link (the length of L is odd)
¹                        then do nothing
     Ɗ                   else (
 ;2                        Append 2
   ṙ1                      Rotate left by 1
                         )
        µ                Now we have a new list L'
          JḂ$            The parities of indices of L' ([1,0,1,0,...])
         n               Doesn't equal L' (for each element)
             Ạ           All?
              ð,         Pair this all with
                µ        the following:
                 Ḣ       Head of L [removing it from L]
                  n      Doesn't equal
                   Ç     previous link (the parity of the length of [the new] L)
                    a    And
                     Ạ   all elements of [the new] L are truthy

```

*-1 byte by extracting an auxiliary link. Sometimes you need to follow good coding practices even in code golf…*
> 3 votes

# Answer
# Retina 0.8.2, 50 bytes

```
^(?=(\S\S?(\D\S)*$))?(?=(\S?\D(\D\D)*$))?.*
$#1$#3

```

Try it online! Takes input as a string of characters where `#` represents `B`,  represents `D` and `0` represents `M`, however the link's header translates `BDM` for you if necessary. Output is a pair of bits. Explanation:

```
(?=(\S\S?(\D\S)*$))?

```

Try to match a monadic chain.

```
(?=(\S?\D(\D\D)*$))?

```

Try to match a dyadic chain.

```
^.*
$#1$#3

```

Replace the input with the results of the two match attempts.
> 2 votes

# Answer
# APL (Dyalog Unicode), 49 bytes

```
'MD'∘.{''≡(∊'^[MB]?(['⍺'B][DB])*['⍺'B]$')⎕R''⊢⍵}⊂

```

Try it online!

Testing harness borrowed from Adám's answer, which you should upvote.

Outputs `[0, 0]` for invalid trains, `[0, 1]` for dyadic trains, `[1, 0]` for monadic trains, and `[1, 1]` for trains that could be both. This basically just checks if it matches the regex `/^[MB]?([aB][DB])*[aB]$/`, where `a` is `M` or `D`.
> 1 votes

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


title: Possible periods of input

text:
# Question
Title: Possible periods of input
**Background:**

Take this input as an example:

```
1 1 2 1 1 2 1 3 1 3

```

If you look only at the first few digits, between `1 1 2` and `1 1 2 1 1 2 1`, this input appears to consist of the pattern `1 1 2` repeating indefinitely. This would make its period 3, as there are 3 numbers in the pattern.

Given only the first number, the period appears to be 1, as only the number `1` is in the input. Given the first two numbers, it still appears to be the number `1` repeating, so the period does not change.

**Task:**

Given an array of numbers (or strings, or similar), determine the period of each prefix of the array, and return the unique ones. For example, the above input would have periods of:

```
1 1 3 3 3 3 3 8 8 10

```

Thus, the output would be:

```
1 3 8 10

```

**I/O:**

Input should be an array of any set of a large number of different values. For example, numbers, strings, natural numbers, or pairs of integers. Booleans wouldn't be allowed, but chars/bytes would.

Output can be any reasonable representation of the numbers, such as an array/list, or a string with the numbers joined by newlines.

**Test cases:**

```
1                     ->  1
1 2 1 1 2 1           ->  1 2 3
1 1 2 1 1 2 1         ->  1 3
1 2 1 2 1 2 1 2 4     ->  1 2 9
1 2 3 4 1 2 3 1 2 1   ->  1 2 3 4 7 9
4 4 4 4 4 4 4 4 4 4   ->  1

```

# Answer
> 9 votes
# , ~~88~~ ~~82~~ 81 bytes

```
unique(Map(function(i)Find(function(j)all(a[1:i]==a[1:j]),1:i),seq(a=a<-scan())))

```

Try it online!

Thanks to Giuseppe for fixing a mistake and -6 bytes.

# Answer
> 9 votes
# , 23 bytes

```
1+[:~.(i.~]{~#\|/i.@#)\

```

Try it online!

We do the heavy lifting of creating the periods using integers, and then use those to index into our input. Specifically...

* `(...)\` For each prefix:

+ `#\|/i.@#` Create a table of indexes to represent the possible periods. An example should make this clear:

    ```
      (#\|/i.@#) 1 1 2 3 1 1 2 3
    0 0 0 0 0 0 0 0
    0 1 0 1 0 1 0 1
    0 1 2 0 1 2 0 1
    0 1 2 3 0 1 2 3
    0 1 2 3 4 0 1 2
    0 1 2 3 4 5 0 1
    0 1 2 3 4 5 6 0
    0 1 2 3 4 5 6 7

    ```
    + `]{~` Pull these indexes from the input:

    ```
    1 1 1 1 1 1 1 1
    1 1 1 1 1 1 1 1
    1 1 2 1 1 2 1 1
    1 1 2 3 1 1 2 3   <-- Input matches here, index 3.
    1 1 2 3 1 1 1 2
    1 1 2 3 1 1 1 1
    1 1 2 3 1 1 2 1
    1 1 2 3 1 1 2 3

    ```
    + `i.~` And find the index of the original input within this list. In this case, that index is `3`.
* `[:~.` De-dup.
* `1+` And add one.

# original approach, 24 bytes

```
[:~.1+i.&1@(-:"1#$&><\)\

```

Try it online!

# Answer
> 9 votes
# Jelly, 6 bytes

```
ṁƤi$ƤQ

```

A monadic Link accepting a list that yields a list of the unique period lengths.

**Try it online!** Or see the test-suite.

### How?

```
ṁƤi$ƤQ - Link: list, A
    Ƥ  - for each prefix (p in A):
   $   -   last two links as a monad - f(p):
 Ƥ     -     for each prefix (x in p):
ṁ      -       mould like (p)
             -> Z = list of copies of x each "extended" to the length of p
  i    -     first 1-indexed index (of p in Z)
     Q - de-duplicate

```

# Answer
> 7 votes
# Jelly, 10 bytes

```
¹Ƥṁ€ẹƊṂ$ƤQ

```

Try it online!

## Explanation

```
¹Ƥṁ€ẹƊṂ$ƤQ  Main Link
[....].$    Group these two into one monad so Ƥ runs the whole link
            to its left

[][].Ɗ      Group these three into one monad so it accepts the link
            left argument as the right argument to ẹ instead of
            grouping ẹṂ into a dyad-monad monadic link

        Ƥ   For each prefix of the list: let it be the "sublist":
¹Ƥ          Map identity over prefixes; get all prefixes of the
            sublist
  ṁ€        Mold each prefix to the shape of the sublist; repeat
            elements until the two lists are the same length
    ẹ       Find all indices of the original sublist in the list
            of looped prefixes; essentially, find all prefixes
            that work for the period
      Ṃ     Take the minimum of these; this returns the period
         Q  Deduplicate; find only unique potential periods

```

# Answer
> 6 votes
# JavaScript (Node.js), 69 bytes

```
a=>a.flatMap(x=>(j=1/a.some(v=>v-a[++j],j=i++)+j)>p?(p=j,i):[],i=p=0)

```

Try it online!

```
a=>a.flatMap(x=>                   // for i := 1 to a.length do
(j=1/a.some(v=>v-a[++j],j=i++)+j)  //   j := prefix size of repeating first i elements;
>p?(p=j,i):[]                      //   if j > p then p := j; add `i` to answer; endif;
,i=p=0)                            // endfor

```

# Answer
> 5 votes
# Stax, 15 bytes

```
┼↓Φ:'ñ╪⌐ñ∟M╕LbN

```

Run and debug it

Output is as a string representing the codepoints of each period. Pretty printed with spaces for verification.

## Explanation

```
|[{c|[{n%:mn=}j%mu
|[                 prefixes of input
  {             m  map to
   c|[             dup and take prefixes
      {      }j    first element which satisfies:
       n%:m        when extended to current iteration length
           n=      equals the current iteration?
               %   take the length
                 u uniquify

```

# Answer
> 5 votes
# 05AB1E, 13 bytes

```
ηε¼ηÅΔ¾∍Å?]>Ù

```

Try it online!

**Commented:**

```
η              # push all prefixes of the input
 ε        ]    # iterate over all prefixes:
  ¼            #   increment the counter variable
   ηÅΔ    ]    #   find the index of the first prefix of the prefix which satisifies:
      ¾∍       #     if extended to the length of the outer prefix (value of the counter variable)
        Å?     #     this is a prefix of the (implicit) input
               #     (and therefore equal to the outer prefix)
           >   # increment the 0-based indices
            Ù  # only keep unique ones

```

# Answer
> 5 votes
# JavaScript (ES6), 73 bytes

Returns a set.

```
a=>new Set(a.map((_,i)=>(g=m=>a.some((v,j)=>j<=i&&v^a[j%m])?g(-~m):m)``))

```

Try it online!

### Commented

```
a =>                   // a[] = input array
new Set(               // build a set from the following array:
  a.map((_, i) =>      //   for each value at position i in a[]:
    ( g = m =>         //     g is a recursive function taking a modulo value m
      a.some((v, j) => //       check if there's some element in a[]:
        j <= i &&      //         that it is not located beyond the position i
        v ^ a[j % m]   //         and is not equal to the element at j modulo m
      ) ?              //       end of some(); if truthy:
        g(-~m)         //         recursive call with m + 1
      :                //       else:
        m              //         return m
    )``                //     initial call to g with m zero'ish
  )                    //   end of map()
)                      // end of Set()

```

# Answer
> 4 votes
# Brachylog, ~~18~~ 14 bytes

```
{a₀{ġz₁=ᵐ!}l}ᵘ

```

Try it online!

*-4 because I remembered which zip I was using*

```
{           }ᵘ    Find every unique output from:
 a₀               for some prefix of the input,
    ġ             split it into groups of the same length except the last can be shorter
   {     !}       with that length being the smallest possible for which
     z₁           the non-cycling zip of the groups
       =ᵐ         contains only elements all elements of which are equal;
           l      output the length.

```

# Answer
> 4 votes
# K (ngn/k), ~~19 17~~ 21 bytes

```
1+?{((#x)#',\x)?x}',\

```

Try it online!

Modeled after @Jonah's J answer.

* `{...}',\` for each prefix of the (implicit) input...
* `((#x)#',\x)` expand each prefix (of the current passed-in prefix) to the full length of that prefix (e.g., transform `1 1 2` from `(1;1 1;1 1 2)` into `(1 1 1;1 1 1;1 1 2)`)
* `(...)?x` get the index of the first transformed prefix that matches the prefix itself
* `1+?{...}` add one to the distinct indices

# Answer
> 4 votes
# APL (Dyalog Unicode), 50 bytes

```
{∪{1⍳⍨⍵[⍴⍵]≡¨⍵}¨{L←⍴,⊃⌽⍵⋄L⍴¨⍵}¨{⍺,⍵}\¨{⍺,⍵}\⊂∘⍕¨⍵}

```

I'm fairly certain there's room for improvement, but it's just out of my reach, for the moment.

```
∪ ⍝ list unique values
 1⍳⍨ ⍝ get the index value of the first occurrence of 1 in the bit mask
   ⍵[⍴⍵]≡¨⍵ ⍝ create a bit mask by checking which padded strings match the last string in the expansion
     ¨ ⍝ for each list of padded strings
       L←⍴,⊃⌽⍵ ⍝ assign length of last string in expansion to L
          ⋄ ⍝ statement separator
            L⍴¨⍵ ⍝ for each string, reshape to length of longest string
               ¨ ⍝ for each list of strings
                 {⍺,⍵}\¨{⍺,⍵}\ ⍝ expand twice. (A, B, C) -> (A, AB, ABC) -> ((A), (A, AB), (A, AB, ABC))
                    ⊂∘⍕¨⍵ ⍝ for each element, encode as string and enclose

```

Try it online!

# Answer
> 4 votes
# Haskell, 77 bytes

```
nub.map(\x->[p|p<-[1..],and.zipWith(==)x$drop p x]!!0).inits
import Data.List

```

Try it online!

Implicit function, taking a list of integers as input and returning a list of integers as output.

Not really satisfied with this answer, but I can't seem to avoid importing `Data.List`.

## How?

```
nub.                                -- remove duplicates from
map(\x->                            -- the list obtained replacing each x with
        [p|p<-[1..],                --     the integer p>=1
        and.zipWith(==)x$drop p x]  --     such that x is periodic of period p
    !!0).                           --   take the smallest such p
inits                               -- where x ranges over the prefixes of the input list

```

# Answer
> 4 votes
# Python 2, 92 bytes

```
def f(l):r=[];p=i=1;exec"while l[p:i]!=l[:i-p]:p+=1\ni+=1;r+=[p][p in r:]\n"*len(l);return r

```

Try it online!

This uses the fact that the periods of prefices are non-decreasing.

Ungolfed a bit:

```
def f(l):
 r=[];p=i=1
 for _ in l:                       # for each prefix of l (tracked by i)
  while l[p:i]!=l[:i-p]:p+=1       # find the next p s.t. removing a length p prefix or a length p suffix result in equal lists
  i+=1;r+=[p][p in r:]             # then add p to the return value if its not already there
 return r

```

# Answer
> 3 votes
# Scala 3, 119 bytes

```
_.inits.toSeq.reverse.tail.map{a=>1.to(a.size).find(Seq.fill(a.size)(_)flatMap a.take zip a forall(_==_)).get}.distinct

```

Try it in Scastie!

This is annoyingly long.

```
_                 //The input
  .inits          //Iterator of all prefixes (biggest to smallest)
  .toSeq          //Conver to Seq so we can do stuff to it
  .reverse        //Reverse so the smallest prefixes are first
  .tail           //Drop the first prefix, which is empty
  .map { a =>     //Map each prefix a to its possible period
    1.to(a.size)         //Range of possible possible periods
      .find(             //Find an i such that
        Seq.fill(a.size)(_)  //when you make a.size copies
          flatMap a.take     //of the first i elements of a
          zip a              //and zip those with a, dropping extra elements
          forall(_ == _)     //they all equal the corresponding elements in a
      ).get             //Unwrap the Option to get the possible period
  }.distinct      //Remove duplicates

```

# Answer
> 3 votes
# Haskell, ~~110~~ 133 bytes

Sorry, got longer, fixed bug.

```
h v=l<$>(l v#v)
1#v=[1!v]
n#v=(n-1)#v++[[i!v|i<-[2..n],n!v==r n(i!v)]!!0|notElem(n!v)$r n<$>(n-1)#v]
r n=(n!).cycle
(!)=take
l=length

```

Try it online!

# Answer
> 2 votes
# Charcoal, 27 bytes

```
Ｗ⁻⊕Ｅθ⌕Ｅ⊕λ……θ⊕μ⊕λ…θ⊕λυ⊞υ⌊ιＩυ

```

Try it online! Link is to verbose version of code. Takes input by default as a character array, but it's also possible to feed it integer or string arrays by using JSON format. Explanation:

```
⊕Ｅθ⌕Ｅ⊕λ……θ⊕μ⊕λ…θ⊕λ

```

Loop over all prefixes of prefixes, extending them to the original prefix and finding indices of the first prefix where this results in the original prefix, then adjusting to give the periods.

```
Ｗ⁻...υ

```

While the list of periods contains a value not in the deduplicated list...

```
⊞υ⌊ι

```

... push the smallest missing value to the deduplicated list.

```
Ｉυ

```

Output the deduplicated list.

# Answer
> 2 votes
# Ruby, ~~79~~ 75 bytes

```
->x{(1..x.size).map{|i|(1..i).find{|j|i.times.all?{|k|x[k]==x[k%j]}}}.uniq}

```

Accepts an array (e.g. of strings or integers) and returns an array of ints.

Previous code:

```
->x{(1..x.size).map{|i|(1..i).find{|j|x[0...j].cycle.first(i)==x[0...i]}}.uniq}

```

Try it online!

# Answer
> 2 votes
# Haskell, ~~96 95~~ 92 bytes

```
import Data.List
r=tail.inits
f=nub.map(\p->[length x|x<-r p,and$zipWith(==)p$cycle x]!!0).r

```

Try it online!

* saved 1 thanks to @Unrelated String

r=tail.inits

* all prefixes(excludes empty)

f=nub.map(\p-\> ... ).r

* we map every prefix(.r`list`) by doing the job below and we return unique elements.

\[length x|x\<-r p, .. \]!!0

* list of prefixes of the current prefix being tested (x\<-r p), which satisfy condition below. We take the length and we return first element (shorter)

and$zipWith(==)p$cycle x

* True if difference of each elements of prefix and `possible period` is 0

# Answer
> 0 votes
# Java, 105 bytes

```
a->{var s=new java.util.TreeSet();int p=1,i=0;for(int c:a)s.add(p=a[i++%p]==c?p:a[0]==c?i-1:i);return s;}

```

Try it online!

---
Tags: code-golf, counting
---