text
stringlengths
180
608k
[Question] [ For golfing practice, I have been doing the assignments in my girlfriend's Intro to Python class. I found that for this assignment, there were multiple strategies that came very close in character count, and I'm sure people here can find even better ways. Although I am most interested in ways to do this in Python, I would like to know the most golfed this program can get, therefore this is code golf and shortest answer wins. ## The Rules: The assignment is outlined below. The user should be asked to input twice, although the prompts don't have to say anything, and can be in a different order. Standard loopholes apply. --- ### Assignment 3: Arrows Write a program that prompts the user for a number of columns, and them prints the pattern as seen below. You can assume that the user will supply positive numbers. Your program should handle both left and right arrows. Here are a few sample runnings: ``` How many columns? 3 Direction? (l)eft or (r)ight: r * * * * * How many columns? 5 Direction? (l)eft or (r)ight: l * * * * * * * * * ``` [Answer] # Pyth, 23 bytes ~~May or may not be valid, based on the answer to [this comment](https://codegolf.stackexchange.com/questions/59874/simple-printing-arrows#comment144045_59874). Regardless, I found this neat, and, if it is invalid, the other Pyth answers are also invalid. ;)~~ Well, [it's valid](https://codegolf.stackexchange.com/questions/59874/simple-printing-arrows?noredirect=1#comment144046_59874), because I apparently missed the blatantly obvious. :/ **EDIT:** I WON!!!! YESSS!!!! First time ever! :D ``` j+_J_Wqz\r.e+*dkb*\*QtJ ``` [Live demo.](https://pyth.herokuapp.com/?code=j%2B_J_Wqz%5Cr.e%2B%2adkb%2a%5C%2aQtJ&input=l%0A5&test_suite=1&test_suite_input=r%0A3%0Al%0A5&debug=1&input_size=2) [Answer] # Pyth, 27 ``` j<tQ_Wqz\l++Jm+*\ d\*Q_PJtJ ``` [Try it online](http://pyth.herokuapp.com/?code=j%3CtQ_Wqz%5Cl%2B%2BJm%2B%2A%5C%20d%5C%2AQ_PJtJ&input=r%0A5&debug=0) The basic idea here is to build one string that, for say 5, looks like this: ``` * * * * * * * * * * * * * ``` And then flip it upside down if we get `l` as our input. Then we take all but the last `input-1` lines of this string and print it out. [Answer] # Python 2, ~~81~~ 79 bytes ``` c=input() r=1 l=0 exec"print' '*(%sabs(c-r))+'*';r+=1;"%("c+~"*input())*(2*c-1) ``` Might still be golfable, but we'll see :) [Answer] # Pyth, ~~30~~ ~~28~~ 27 bytes ``` VtyQ+*+*tQJqz\r_WJ.a-hNQd\* ``` [Try it online.](https://pyth.herokuapp.com/?code=VtyQ%2B*%2B*tQJqz%5Cr_WJ.a-hNQd%5C*&input=r%0A3&debug=0) Apparently I'm currently tied with [FryAmTheEggman](https://codegolf.stackexchange.com/a/59884/30164) with a completely different approach. (I think that one is ingenious.) ### Example ``` $ python pyth.py spa.p r 3 * * * * * $ python pyth.py spa.p l 5 * * * * * * * * * ``` ### Explanation ``` tyQ (columns * 2) - 1 V loop N through range(the above) tQ columns - 1 (maximum number of spaces) * multiplied by qz\r 1 if direction == "r" else 0 J also save that 1 or 0 to J + plus .a-hNQ abs(N - columns + 1) _WJ negate that if direction == "r" * d that many spaces + \* add the star and print ``` [Answer] # PowerShell, ~~91~~ ~~85~~ 102 Bytes ``` $c=(Read-Host)-1;if(!$c){"*";exit}(@(0..$c+($c-1)..0),@($c..0+1..$c))[(Read-Host)-eq'l']|%{" "*$_+"*"} ``` * Gets the columns, stores it in `$c`. We subtract one because each column also has an `*` and we're only interested in how many spaces are required. * If the entered value was a `1`, print `*` and exit - rest of the script doesn't make a difference.+ * The next section first gets the direction and tests whether it's `-eq`ual to `l`, then creates an array based on indexing into an array of dynamically generated arrays based on the value of `$c`. Magic. Essentially, this is how many spaces per line we need. * For example, for `5 r` this collection would hold `(0,1,2,3,4,3,2,1,0)`. * Takes the array and pipes it into a Foreach-Object `%` loop, where we output a string of X number of spaces, then the `*` ### Example usage: ``` PS C:\Tools\Scripts\golfing> .\simple-printing-arrows.ps1 6 r * * * * * * * * * * * ``` Edit - removed variable `$e` by piping the collection directly Edit2 - correctly accounts for 1 column, now + If it's still mandatory to take input for direction for 1-column arrows (I contend it is not), we can swap the positioning of the `Read-Host` and lose a couple more bytes by re-introducing the `$d` variable, for **106**: ``` $c=(Read-Host)-1;$d=Read-Host;if(!$c){"*";exit}(@(0..$c+($c-1)..0),@($c..0+1..$c))[$d-eq'l']|%{" "*$_+"*"} ``` [Answer] ## TI-BASIC, ~~75~~ ~~65~~ ~~57~~ ~~54~~ ~~50~~ 47 Bytes Thanks to @ThomasKwa for the correct byte calculation and golfing **10 bytes**. Tested on my **TI-84+ Silver Edition.** First TI-BASIC submission, golfing suggestions welcome (I don't know many tricks yet). If name plays a factor in memory shown, this one's was 3 characters instead of 1 (I looked at the byte count on my calculator itself). This program is limited by the `output` function's restrictions (I think to arrows of length 4), but I could probably switch to `text`, which displays graphically if that is too low of a length. ``` Prompt L,Str1 Str1="R For(I,1,2L-1 Output(I,(1-2Ans)abs(I-L)+AnsL+1,"* End ``` Note that this also doesn't clear the screen or pause it. I really feel like the equation I'm using can be golfed more. It also feels so wrong to exclude the ending quotation mark. [Answer] # Python 2, 89 bytes ``` c=input()-1 d=raw_input()>'l' for j in range(2*c+1):print' '*(d*c-(2*d-1)*abs(c-j))+'*' ``` Works almost identically to my Pyth answer, just calculating the correct number of spaces on the fly. [Answer] ### PowerShell, 104 102 97 bytes ``` # 97 version: $o=@(($c=(read-host)-1))[(read-host)-eq'l'];($j=2*$c)..0|%{' '*[Math]::Abs($o++%($j+!$j)-$c)+'*'} 3 r * * * * * # Previous 102 version: $o=@(($c=(read-host)-1))[(read-host)-eq'l'];(2*$c)..0|%{ ' '*[Math]::Abs($o++%(2*($c+(!$c+0)))-$c)+'*'} ``` NB. if you want to run it again, open a new PowerShell, or `rv o` to reset the variable state. Compared to how terse the others are, this hurts. [Hurts less at 97 than it did at 122]. Two parts to it, neither of them very surprising; reads a number of columns, uses an array-index-ternary-operator-substitute to get an offset, and runs through a [wave function](https://stackoverflow.com/questions/1073606/is-there-a-one-line-function-that-generates-a-triangle-wave) starting at the offset (and a tweak so it doesn't fall over doing `mod 0`). (And ouch did I spend ages on that wave function, unable to spot my misunderstanding, and typing all the it's-not-LISP-,honest parens). [Answer] # Python 2, ~~98~~ 89 bytes ``` f=[' '*n+'*'for n in range(input())] if'l'==input():f=f[::-1] print'\n'.join(f+f[-2::-1]) ``` A little more lengthy. --- # Usage ``` $ python2 test.py 3 "l" * * * * * ``` [Answer] ## Perl, 85 bytes ``` ($-,$_)=<>;$,=$/;@}=map$"x$_.'*',0..--$-;@}=reverse@}if/l/;print@},map$}[$--$_],1..$- ``` Usage: ``` perl 59874.pl <<< '6 r' ``` [Answer] # PHP, 156 Bytes ``` <?for($c=1+fgets(STDIN);--$c;$s[-$c]=$t[]=sprintf("%{$c}s","*"));arsort($s);$a=fgetc(STDIN)==r?$s+$t:$t+$s;array_splice($a,count($a)/2,1)?><?=join(" ",$a); ``` Creates two arrays, like this: ``` $t = [ 0 => " *" 1 => " *" 2 => "*" ] $s = [ -1 => "*" -2 => " *" -3 => " *" ] ``` then uses array union `$s+$t` or `$t+$s` to combine them and `array_splice` to remove the element in the middle. Finally output using `<?=join()` [Answer] # Python 2, ~~111~~ ~~109~~ 104 bytes Pretty simple solution. I'm sure it can be golfed more. For those who don't know, `~x+n` is the same as `n-1-x`. ``` n=input() r=range(n) r+=r[-2::-1] for i in[r,[~x+n for x in r]]['r'>raw_input()]:print"*".rjust(i+1," ") ``` **[Try it online](http://ideone.com/bon4JR)** **Edit**: This was golfed into the last line: ``` if'r'>d:r=[~x+n for x in r] for i in r:print"*".rjust(i+1," ") ``` [Answer] # Matlab, ~~109~~ ~~105~~ 96 bytes *Thanks to @beaker for saving me 9 bytes*. ``` x=eye(input(''));if(input('','s')<114),x=fliplr(x);end x=x*10+32;disp(char([x;x(end-1:-1:1,:)])) ``` [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal) `j`, 14 bytes ``` ƛ×⁰\l=[↲¹]↳;øm ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=j&code=%C6%9B%C3%97%E2%81%B0%5Cl%3D%5B%E2%86%B2%C2%B9%5D%E2%86%B3%3B%C3%B8m&inputs=5%0Al&header=&footer=) [11 if 1/0 is allowed](http://lyxal.pythonanywhere.com?flags=j&code=%C6%9B%C3%97%E2%81%B0%5B%E2%86%B2%C2%B9%5D%E2%86%B3%3B%C3%B8m&inputs=5%0Al&header=&footer=) ``` ƛ ; # Map to... × # Asterisk ⁰\l=[ ] # If left... ↲¹ # Left justify, then push size to right-just by ↳ # Right-justify øm # Palindromise ``` [Answer] # Ruby, 118 bytes ``` 2.times{l,d=gets.split;l=l.to_i;a=(d=="r"?(0..l-1):(l-1).downto(0)).to_a;(a+a[0..-2].reverse).each{|x| puts "#{' '*x}*"}} ``` `2.times{` -- twice, of course... `l,d=gets.split;` -- get the input `l=l.to_i;` -- change length to an integer `a=(d=="r"?(0..l-1):(l-1).downto(0)).to_a;` -- create an array from the range of 0 to the length `(a+a[0..-2].reverse).each{|x| puts "#{' '*x}*"}` -- iterate, turn into the strings to make the arrows Not exactly the greatest golf ever, but, hey. [Answer] # PowerShell, ~~98~~ 94 Bytes ``` $c=(Read-Host)-1;$d=Read-Host;if($c){$c..0+1..$c|%{if($d-eq'r'){$_=$c-$_}' '*$_+'*'}}else{'*'} ``` If I could find a way to put the Read-Host for direction inside the foreach-object loop but only prompt for it once I might be able to save a few bytes. Edit: 94 bytes. Instead of testing for left, test for right (simplifies the loop). Original 98 byte: ``` $c=(Read-Host)-1;$d=Read-Host;if($c){0..$c+($c-1)..0|%{if($d-eq'l'){$_=$c-$_}' '*$_+'*'}}else{'*'} ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 15 bytes ``` =”ro⁹ạŒḄ}⁶ẋp”*Y ``` [Try it online!](https://tio.run/##ATwAw/9qZWxsef//PeKAnXJv4oG54bqhxZLhuIR94oG24bqLcOKAnSpZ/8OnImrigb7CtsK2//8icmwi/zMsIDU "Jelly – Try It Online") If we can use any values instead of `l` and `r`, then [this](https://tio.run/##ATQAy/9qZWxsef//b@G6ocWS4biEfeKBtuG6i3DigJ0qWf/DpyJq4oG@wrbCtv//MSwgMP8zLCA1) **11** byte program works for `1` being to the right and `0` to the left. If we can use any character rather than `*`, we can reduce the programs to **[14](https://tio.run/##ATkAxv9qZWxsef//PeKAnXJv4oG54bqhxZLhuIR94oG24bqLcDFZ/8OnImrigb7CtsK2//8icmwi/zMsIDU)** and **[10](https://tio.run/##ATEAzv9qZWxsef//b@G6ocWS4biEfeKBtuG6i3AxWf/DpyJq4oG@wrbCtv//MSwgMP8zLCA1)** bytes ## How it works ``` =”ro⁹ạŒḄ}⁶ẋp”*Y - Main link. Takes C on the left and n on the right ”r - "r" = - Is C = "r"? ⁹ - Yield n o - If C ≠ "r", yield n else 1 } - To n: ŒḄ - Bounce; Yield [1, 2, ..., n, ..., 2, 1] ạ - Absolute difference If C = "r", this yields [0, 1, ..., n-1, ..., 1, 0] If C ≠ "r", this yields [n-1, n-2, ..., 0, ..., n-2, n-1] Call the result B ⁶ - Yield a space ẋ - For each element k in B, repeat a space k times ”* - Yield "*" p - Cartesian product; This appends "*" to each element in B Y - Join on newlines ``` [Answer] # [><>](https://esolangs.org/wiki/Fish), 60 bytes ``` i"1l"i=&-:&*&:?!\:1-:}c0. ~/?:<-$?&::&;!?l<oao"*" 1/ \o" "- ``` 2 wasted bytes on the bottom line, how irritating! Due to how input works in ><>, it's not possible to 'wait' for input - the `i` command checks if an input character is available on STDIN. If there is, it pushes the ASCII value of that character, and pushes -1 if not. This means that, in order to use this program, the number and direction must already be ready on STDIN, e.g. `3r` for a size 3 arrow pointing to the right. I'm not sure if that disqualifies this entry, let me know your thoughts :o) I'll also write up a description if anyone wants one. [Answer] # PHP, 154 bytes It looks really repetitive, but it does the desired: ``` $c=$argv[1];$b=l==$argv[2]?1:0;$a=$b?$c:-1;function a($a){echo strrev(str_pad('*',$a))."\n";}while($b?--$a:++$a<$c)a($a+1);while($b?++$a<=$c:1<$a--)a($a); ``` Runs from command line like: ``` php arrow.php 5 l php arrow.php 5 r ``` [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-R`](https://codegolf.meta.stackexchange.com/a/14339/), 14 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Could save at least 3 bytes with looser I/O requirements. ``` õ@'*ùXÃê zVèÊÑ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVI&code=9UAnKvlYw%2bogelboytE&input=NQoibCI) ## 11 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Takes `0/1` as input for `r/l` and uses `1` instead of `*` ``` oç mÄ ê zVÑ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVI&code=b%2bcgbcQg6iB6VtE&input=NQox) ``` õ@'*ùXÃê zVèÊÑ :Implicit input of integer U & string V õ :Range [1,U] @ :Map each X '* : Literal "*" ùX : Left pad with spaces to length X à :End map ê :Palindromise z :Rotate clockwise 90° this many times ... Vè : Count the occurrences in U of Ê : "l" Ñ : Multiply by 2 :Implicit output joined with newlines ``` ``` oç mÄ ê zVÑ :Implicit input of integers U & V o :Range [0,U) ç :For each, repeat space that many times m :Map Ä : Append 1 ê :Palindromise zVÑ :Rotate clockwise 90° V*2 times :Implicit output joined with newlines ``` ]
[Question] [ This is a chess-KOTH with simplified rules (because chess itself is already complicated, playing it via a simple program doesn't make it easier). At the moment it is limited to java (version 8), but creating a wrapper-class isn't that difficult (in case someone wants to do this). ## Chessboard The chessboard in the control program uses a modified version of the [ICCF numeric notation](http://en.wikipedia.org/wiki/ICCF_numeric_notation). It is zero-based, meaning the bottom-left field is the position `0,0`, while the upper-right field is the position `7,7`. ## Modified rules * [*En passant*](http://en.wikipedia.org/wiki/En_passant) will be ignored. * [*Castling*](http://en.wikipedia.org/wiki/Castling) isn't possible. * The [*Fifty-move rule*](http://en.wikipedia.org/wiki/Fifty-move_rule) applies automatically (meaning the game ends in a draw). * Promotion of pawns to queens happen automatically when they reach the end of the board. * If a player needs longer than 2 seconds to move, he will lose the game. * Returning an invalid move will result in losing the game. * **To win, you have to capture the enemy king**. It isn't enough to checkmate the enemy. * This also allows you to move your king to fields where the enemy can capture you. * White begins the game. * White is placed "at the bottom" of the field (y=0), black is located at the top (y=7). * Accessing other ressources than your bot (internet, files, other bots, ...) is prohibited. ## Scoring * Winning grants you 3 points, a draw 1 point and losing 0 points. * Each submission will play against each other submission 10 times (5 times as white, 5 as black). ## Controller **[You can find the control program on github](https://github.com/CommonGuy/SimpleChess/)**. To participate, you have to create a class inside the `player` package and it has to be a subclass of `Player`. As an example, look at [TestPlayer](https://github.com/CommonGuy/SimpleChess/blob/master/src/player/TestPlayer.java) (which will also be included in the scoring). Each game, the controller will create a new instance of your player. Then, each turn you have to return a move. The controller provides you with a copy of the [Board](https://github.com/CommonGuy/SimpleChess/blob/master/src/controller/Board.java), which contains a 8x8 array of [Fields](https://github.com/CommonGuy/SimpleChess/blob/master/src/controller/Field.java). A field contains information about its color, its position and the [piece](https://github.com/CommonGuy/SimpleChess/blob/master/src/controller/Piece.java) on it, if there is one. The controller also provides you with information about the enemy player, such as `isCheck` and `getPieces()`. Calling `getMove()` on the enemy will get you disqualified. # Scoreboard ``` 01) AlphaBetaPV: 229 02) AlphaBeta: 218 03) PieceTaker: 173 04) Cheese: 115 05) ThreeMoveMonte: 114 06) StretchPlayer: 93 07) DontThinkAhead: 81 08) SimplePlayer: 27 09) TestPlayer: 13 ``` --- The contest is limited to java because it makes creating answers easier, since you can profit from the methods provided by the controller. However, if someone creates a wrapper, I will include other languages. [Answer] ## PieceTaker The code is a little bit of a mess, but it does work. Right now it wins against all other players, even if it is only given 400ms instead of the allowed 2000ms. I'm using alpha beta pruning with iterative deepening to make sure that the AI doesn't go over the time limit. The current heuristic is very simple (only lost/taken pieces are taken into considerations; not position on the board, etc). In the future I might also add killer heuristics and sort the moves before examining them. ``` package player; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Random; import controller.*; public class PieceTaker extends Player { private boolean DEBUG = false; private Player pieceTaker; private static final int MAXINT = Integer.MAX_VALUE / 2; private static final int MININT = Integer.MIN_VALUE / 2; private static final boolean ITERATIVE_DEEPENING = true; private static final int MAX_DEPTH = 6; // max depth if not using iterative // deepening private static int MAXTIME = 400; // max time for evaluation (if using // iterativeDeepening). We still need to // evaluate moves, so save time for // that. private long time; // time taken this turn @Override public Move getMove(Board board, Player enemy) { pieceTaker = this; // generate all possible moves List<Move> possibleMoves = new ArrayList<>(); List<Piece> pieces = this.getPieces(board); for (Piece piece : pieces) { Point[] destinations = piece.getValidDestinations(board); for (Point point : destinations) { possibleMoves.add(new Move(piece, point)); } } // rate moves Move best = getNextMove(board, possibleMoves, enemy); return best; } private Move getNextMove(Board board, List<Move> possibleMoves, Player enemy) { time = System.currentTimeMillis(); // wrap moves in node class and apply move List<Node> children = new ArrayList<>(); for (Move move : possibleMoves) { Node newNode = new Node(move, board, this, enemy, 0); newNode.applyAndRateMove(); children.add(newNode); } if (ITERATIVE_DEEPENING) { for (int depth = 1;; depth++) { List<Node> copy = new ArrayList<>(); // copy nodes (so that in case time is over we still have a valid set) for (Node node : children) { copy.add(node.copy()); } // rate copy rateMoves(copy, depth); if ((System.currentTimeMillis() - time) > MAXTIME) { break; } // copy rated nodes back children = new ArrayList<>(); for (Node node : copy) { children.add(node.copy()); } } } else { rateMoves(children, MAX_DEPTH); } return getBestMove(children); } // returns node with the highest score private Move getBestMove(List<Node> nodes) { if (DEBUG) { System.out.println("\n"); for (Node node : nodes) { System.out.println(node.toString()); } } Collections.sort(nodes, new ComparatorNode()); // get all nodes with top rating List<Node> best = new ArrayList<>(); int bestValue = nodes.get(0).getRating(); for (Node node : nodes) { if (node.getRating() == bestValue) { best.add(node); } } Random random = new Random(); Node bestNode = best.get(random.nextInt(best.size())); if (DEBUG) { System.out.println("using: " + bestNode.toString()); } return bestNode.getMove(); } private void rateMoves(List<Node> nodes, int depth) { if (nodes.size() == 1) { // nothing to rate. one possible move, take it. return; } for (Node node : nodes) { int alphaBeta = alphaBeta(node, depth, MININT, MAXINT); node.setRating(alphaBeta); } } protected int alphaBeta(Node node, int depth, int alpha, int beta) { Player currentPlayer = node.getCurrentPlayer(); Player otherPlayer = node.getOtherPlayer(); // game over if (node.getBoard().getKing(currentPlayer) == null) { if (currentPlayer == this) { return node.getRating() - 999; } else { return node.getRating() + 999; } } else { // TODO check for draw and rate draw (might be good to take it) } if (depth <= 0) { return node.getRating(); // the rating in the move is always as seen // for player, not current player } List<Node> children = getPossibleMoves(node); if (otherPlayer == this) { for (Node child : children) { if ((System.currentTimeMillis() - time) > MAXTIME) { break; // time over. } alpha = Math.max(alpha, alphaBeta(child, depth - 1, alpha, beta)); if (beta <= alpha) { break; // cutoff } } return alpha; } else { for (Node child : children) { if ((System.currentTimeMillis() - time) > MAXTIME) { break; // time over. } beta = Math.min(beta, alphaBeta(child, depth - 1, alpha, beta)); if (beta <= alpha) { break; // cutoff } } return beta; } } private List<Node> getPossibleMoves(Node node) { List<Node> possibleMoves = new ArrayList<>(); List<Piece> pieces = node.getOtherPlayer().getPieces(node.getBoard()); for (Piece piece : pieces) { Point[] destinations = piece.getValidDestinations(node.getBoard()); for (Point point : destinations) { Node newNode = new Node(new Move(piece, point), node.getBoard(), node.getOtherPlayer(), node.getCurrentPlayer(), node.getRating()); if (newNode.applyAndRateMove()) { possibleMoves.clear(); possibleMoves.add(newNode); return possibleMoves; // we won, return wining move } possibleMoves.add(newNode); } } return possibleMoves; } private class Node { private Move move; private Move originalMove; private Board board; private Player currentPlayer; private Player otherPlayer; private int rating; public Node(Move move, Board board, Player currentPlayer, Player otherPlayer, int rating) { super(); this.move = new Move(move.getPiece().copy(), move.getDestination() .copy()); this.originalMove = new Move(move.getPiece().copy(), move .getDestination().copy()); // copy board so changes only affect this node this.board = board.copy(); this.currentPlayer = currentPlayer; this.otherPlayer = otherPlayer; this.rating = rating; } @Override public String toString() { return " [" + originalMove.toString() + " (r: " + rating + ")] "; } public Node copy() { Node copy = new Node(new Move(originalMove.getPiece().copy(), originalMove.getDestination().copy()), board.copy(), currentPlayer, otherPlayer, rating); return copy; } public boolean applyAndRateMove() { // call rate before apply as it needs the unchanged board rateMove(); board.movePiece(move); if (getBoard().getKing(currentPlayer) == null) { return true; } else { return false; } } private void rateMove() { Point dest = move.getDestination(); Field destField = board.getFields()[dest.getX()][dest.getY()]; int value = 0; if (destField.hasPiece()) { PieceType type = destField.getPiece().getType(); switch (type) { case PAWN: value = 1; break; case KNIGHT: value = 3; break; case BISHOP: value = 3; break; case ROOK: value = 5; break; case QUEEN: value = 9; break; case KING: value = 111; break; default: value = 0; } } if (currentPlayer == pieceTaker) { this.rating += value; } else { this.rating -= value; } } public Player getOtherPlayer() { return otherPlayer; } public Player getCurrentPlayer() { return currentPlayer; } public Board getBoard() { return board; } public int getRating() { return rating; } public void setRating(int r) { this.rating = r; } public Move getMove() { return originalMove; } } private class ComparatorNode implements Comparator<Node> { @Override public int compare(Node t, Node t1) { return t1.getRating() - t.getRating(); } } } ``` [Answer] # StretchPlayer This bot plays just like me! By the way I am terrible at chess. The comments explain what it is actually doing. It's a lot like my thought process. As an added bonus, beats all other bots by a considerable margin. (so far) EDIT: now predicts opponent by running itself as the enemy! EDIT 2: The program made the mistake of not actually killing the king when it was wide open. It was reprimanded accordingly. ``` import java.util.List; import java.util.Set; import controller.*; public class StretchPlayer extends Player{ boolean avoidStackOverflow = false; @Override public Move getMove(Board board, Player enemy) { List<Piece> pieces = this.getPieces(board); for(Piece piece:pieces){ //first order of business: kill the enemy king if possible if(piece.getValidDestinationSet(board).contains(board.getKing(enemy).getPos())){ return new Move(piece,board.getKing(enemy).getPos()); } } //I suppose I should protect my king. for(Piece ePiece:enemy.getPieces(board)){ if(ePiece.getValidDestinationSet(board).contains(board.getKing(this).getPos())){ //ideally I would move my king. for(Point p:board.getKing(this).getValidDestinationSet(board)){ //but I don't want it to move into a spot where the enemy can get to. That would be suicide. boolean moveHere=true; for(Piece enemyPiece:enemy.getPieces(board)){ if(enemyPiece.getValidDestinationSet(board).contains(p)){ moveHere=false; } } if(moveHere){ return new Move(board.getKing(this),p); } } //so the king can't move. But I can fix this. There has to be a way! for(Piece myPiece:pieces){ for(Point possMove:myPiece.getValidDestinationSet(board)){ Board newBoard = board.copy(); newBoard.movePiece(new Move(myPiece,possMove)); if(!newBoard.isCheck(this, enemy)){ //Aha! found it! return new Move(myPiece,possMove); } } } //uh-oh. Better just go with the flow. I'll lose anyway. } } for(Piece piece:pieces){ Set<Point> moves = piece.getValidDestinationSet(board); for(Piece opponentPiece:enemy.getPieces(board)){ if(moves.contains(opponentPiece.getPos())){ Point futurePosition = null; //search for this illusive move (no indexOf(...)?) for(Point p:moves){ if(p.getX()==opponentPiece.getPos().getX()&&p.getY()==opponentPiece.getPos().getY()){ futurePosition = p; } } //it can now kill the enemies piece. But first, it should probably check if it is going to get killed if it moves there. boolean safe = true; for(Piece nextMoveOpponent:enemy.getPieces(board)){ if(nextMoveOpponent.getValidDestinationSet(board).contains(futurePosition)&&piece.getType()!=PieceType.PAWN){ safe = false; } //it would also be beneficial if the enemy didn't kill my king next round. if(nextMoveOpponent.getValidDestinationSet(board).contains(board.getKing(this).getPos())){ safe = false; } } if(safe){ return new Move(piece, futurePosition); } } } } //ok, so I couldn't kill anything. I'll just put the enemy king in check! for(Piece piece:pieces){ for(Point p:piece.getValidDestinationSet(board)){ Piece simulatedMove = piece.copy(); simulatedMove.setPos(p); if(simulatedMove.getValidDestinationSet(board).contains(board.getKing(enemy).getPos())){ return new Move(piece,p); } } } //hmmmm... What would I do if I was the enemy? if(!avoidStackOverflow){ avoidStackOverflow = true; Board copy = board.copy(); Move thinkingLikeTheEnemy = this.getMove(copy, this); avoidStackOverflow = false; Board newBoard = copy; //I wonder what piece it's targeting... Piece targeted =null; for(Piece p:pieces){ if(p.getPos().getX()==thinkingLikeTheEnemy.getDestination().getX()&&p.getPos().getY()==thinkingLikeTheEnemy.getDestination().getY()){ targeted=p; } } //better move that piece out of the way, if it doesn't hurt my king if(targeted!=null){ for(Point p:targeted.getValidDestinations(newBoard)){ newBoard = board.copy(); newBoard.movePiece(new Move(targeted,p)); for(Piece enemy2:enemy.getPieces(newBoard)){ if(!enemy2.getValidDestinationSet(newBoard).contains(p) && !newBoard.isCheck(this, enemy)){ return new Move(targeted,p); } } } newBoard.movePiece(new Move(targeted,thinkingLikeTheEnemy.getPiece().getPos())); if(!newBoard.isCheck(this, enemy)){ return new Move(targeted,thinkingLikeTheEnemy.getPiece().getPos()); } } } //well, I guess this means I couldn't kill anything. Or put the enemy in check. And the enemy didn't have anything interesting to do //I guess I should just push a pawn or something for(Piece piece:pieces){ if(piece.getType()==PieceType.PAWN){ if(piece.getValidDestinationSet(board).size()>0){ return new Move(piece,piece.getValidDestinations(board)[0]); } } } //What!?!? No Pawns? guess I'll just move the first thing that comes to mind. for(Piece piece:pieces){ if(piece.getValidDestinations(board).length>0){ //providing that doesn't put my king in danger Board newBoard = board.copy(); newBoard.movePiece(new Move(piece,piece.getValidDestinations(board)[0])); if(!newBoard.isCheck(this, enemy)){ return new Move(piece,piece.getValidDestinations(board)[0]); } } } //Oh no! I can make no moves that can save me from imminent death. Better hope for a miracle! for(Piece p:pieces){ if(p.getValidDestinations(board).length>0){ return new Move(p,p.getValidDestinations(board)[0]); } } //a miracle happened! (if it made it here) return null; } } ``` [Answer] # Three Move Monte This guy looks at the next three moves (mine,yours,mine) and picks the move that gives the highest score. If there are more than 60 available moves, it will just choose a random 60 on each step. Of course, if any single move (out of all of them, not the chosen 60) will end the game, I'll take it immediately. To score a board, I give each piece a base value. It's then modified by the piece's mobility, how many (and which) pieces it threatens, and how many pieces threaten it. Of course, mobile kings are not necessarily good in the early game, so I special case the values for them a bit. This runs fairly quickly, and can finish a game with the current crop in 3-4 seconds. It looks like there's room to bump it up a couple moves if need be. **update:** * adding scoring for "control the center" in early game * special case king scores * fixed a double-scoring bug in move simulation ``` package player; import java.util.*; import pieces.*; import controller.*; public class ThreeMoveMonte extends Player{ final static int TOSSES = 60; Random rand = new Random(); @Override public Move getMove(Board board, Player them){ List<Move> moves = getMoves(board, getTeam(), 0); for(Move move : moves) if(gameOver(apply(board, move))) return move; moves = getMoves(board, getTeam(), TOSSES); int highest = Integer.MIN_VALUE; Move best = moves.get(0); for(Move move : moves){ Board applied = apply(board, move); Move oBest = getBestMove(applied, getOpponent(getTeam()), 0); applied = apply(applied, oBest); if(!gameOver(applied)){ Move lBest = getBestMove(applied, getTeam(), TOSSES); Board lApplied = apply(applied, lBest); int score = eval(lApplied, getTeam()); if(score > highest){ best = move; highest = score; } } } return best; } boolean gameOver(Board board){ Field[][] fields = board.getFields(); int kings = 0; for(int x=0;x<fields.length;x++) for(int y=0;y<fields[x].length;y++){ Piece p = fields[x][y].getPiece(); if(p!=null&&p.getType().equals(PieceType.KING)) kings++; } return kings==2?false:true; } Move getBestMove(Board board, Color color, int breadth){ int highest = Integer.MIN_VALUE; Move best = null; List<Move> moves = getMoves(board, color, breadth); for(Move move : moves){ Board applied = apply(board, move); int score = eval(applied, color); if(score > highest){ best = move; highest = score; } } return best; } List<Move> getMoves(Board board, Color color, int breadth){ List<Move> moves = new ArrayList<Move>(); Set<Piece> pieces = getPiecesOfColor(board, color); for(Piece piece : pieces){ Set<Point> points = piece.getValidDestinationSet(board); for(Point point : points){ moves.add(new Move(piece, point)); } } Collections.shuffle(moves); if(breadth > 0) while(moves.size()>breadth) moves.remove(moves.size()-1); return moves; } Board apply(Board board, Move move){ Board copy = board.copy(); Piece piece = move.getPiece().copy(); Point src = piece.getPos(); Point dest = move.getDestination(); if(piece.getType().equals(PieceType.PAWN)){ if(piece.getTeam().equals(Color.WHITE)&&dest.getY()==7 || piece.getTeam().equals(Color.BLACK)&&dest.getY()==0) piece = new Queen(piece.getTeam(), piece.getPos()); } piece.setPos(dest); copy.getFields()[src.getX()][src.getY()].setPiece(null); copy.getFields()[dest.getX()][dest.getY()].setPiece(piece); return copy; } int eval(Board board, Color color){ int score = 0; List<Piece> mine = getPieces(board); Field[][] fields = board.getFields(); for(Piece piece : mine){ int value = getValueModified(board, piece); Set<Point> moves = piece.getValidDestinationSet(board); for(Point move : moves){ int x = move.getX(),y=move.getY(); if(fields[x][y].hasPiece()){ Piece other = fields[x][y].getPiece(); if(!other.getTeam().equals(getTeam())) value += getValue(other) / (other.getType()==PieceType.KING ? 1 : 30); } if(mine.size()>10) value += (int)(8 - (Math.abs(3.5-x) + Math.abs(3.5-y))); } int attackerCount = getAttackers(board, piece, false).size(); if(piece.getType()==PieceType.KING){ if(attackerCount > 0) value = -value; } else { for(int i=0;i<attackerCount;i++) value = (value * 90) / 100; } score += value; } return score; } Set<Piece> getPiecesOfColor(Board board, Color color){ Field[][] fields = board.getFields(); Set<Piece> out = new HashSet<Piece>(); for(int x=0;x<fields.length;x++){ for(int y=0;y<fields[x].length;y++){ Piece p = fields[x][y].getPiece(); if(p!=null&&p.getTeam().equals(color)) out.add(p); } } return out; } Set<Piece> getAttackers(Board board, Piece piece, boolean all){ Set<Piece> out = new HashSet<Piece>(); Color color = piece.getTeam(); Set<Piece> others = getPiecesOfColor(board, getOpponent(color)); if(all) others.addAll(getPiecesOfColor(board, color)); for(Piece other : others){ if(other.getValidDestinationSet(board).contains(piece.getPos())) out.add(other); } return out; } Color getOpponent(Color color){ return color.equals(Color.BLACK)?Color.WHITE:Color.BLACK; } int[] pieceValues = {100, 500, 300, 320, 880, 1500}; int getValue(Piece piece){ return pieceValues[piece.getType().ordinal()]; } int[] maxMoves = {3, 14, 8, 13, 27, 8}; int getValueModified(Board board, Piece piece){ int moves = piece.getValidDestinationSet(board).size(); double value = getValue(piece)*.9; double mod = getValue(piece)*.1*((double)moves/maxMoves[piece.getType().ordinal()]); if(piece.getType()==PieceType.KING) if(getPieces(board).size()>10) mod = -mod; return (int)(value + mod); } } ``` [Answer] ## AlphaBetaPV AlphaBetaPV stands for Alpha Beta with Principal Variation (it's not principal-variation search). With only a few more lines woven into the code of AlphaBeta.java, it beats AlphaBeta.java. And again, sorry, for only morphing and fusing codes from other internet sources into this JAVA code. * The principal variation is stored and used for the simplest move priority to accelerate the alpha beta cut off: + while iterative deepening and + for the next move. * Simple position evaluation: + Number of moves each party has (degree of freedom) to support the opening. + Pawn promotion to support the end game. * Still no quiescence search. Still playing boring. ``` package player; import java.util.Random; import controller.*; public class AlphaBetaPV extends Player { private static final int INFINITY = Integer.MAX_VALUE; private static final int MAXTIME = 1800; // max time for evaluation private static final Random random=new Random(); private static int seed=1; private long time; // time taken this turn private int iterativeDepth; private Player myOpponent; private int commitedDepth; private static Piece[] pieces = new Piece[20000]; private static Point[] points = new Point[20000]; private static int[] freedom = new int[20]; private static class PV { Move move; PV next; } private PV pv= new PV(); @Override public Move getMove(Board root, Player min) { time=System.currentTimeMillis(); seed++; myOpponent=min; // use last PV for an estimate of this move if (pv.next!=null) pv=pv.next; if (pv.next!=null) pv=pv.next; iterative_deepening(root); return pv.move; } private void iterative_deepening(Board root) { try { for (iterativeDepth = (commitedDepth=Math.max(2, commitedDepth-2));; iterativeDepth++) { alphaBeta(root, -INFINITY, +INFINITY, iterativeDepth, this, myOpponent, 0, 0, pv, pv); commitedDepth=iterativeDepth; } } catch (InterruptedException e) {} } //http://chessprogramming.wikispaces.com/Alpha-Beta private int alphaBeta(Board root, int alpha, int beta, int d, Player max, Player min, int begin, int level, PV pv, PV pline) throws InterruptedException { if (d==0 || root.getKing(max) == null) return evaluate(root, d, level); int end = allMoves(root, max, begin, level, pv); PV line= new PV(); for (int m=begin; m<end; m++) { Board board = root.copy(); board.movePiece(new Move(pieces[m].copy(), points[m])); int score = -alphaBeta(board, -beta, -alpha, d - 1, min, max, end, level+1, pline==null?null:pline.next, line); if (score >= beta) return beta; // fail hard beta-cutoff if (score > alpha) { pline.move=new Move(pieces[m].copy(), points[m]); // store as principal variation pline.next=line; line=new PV(); alpha = score; // alpha acts like max in MiniMax } } return alpha; } private int evaluate(Board board, int d, int level) throws InterruptedException { if ((System.currentTimeMillis() - time) > MAXTIME) throw new InterruptedException(); int minmax=2*((iterativeDepth-d)&1)-1; int king = 0, value=(level>1)?minmax*(freedom[level-1]-freedom[level-2]):0; Field[][] field = board.getFields(); for (int x = 0; x < 8; x++) { for (int y = 0; y < 8; y++) { Piece piece = field[x][y].getPiece(); if (piece==null) continue; int sign=(piece.getTeam()==getTeam())?-minmax:minmax; switch (piece.getType()) { case PAWN: value += ( 1000+2*(piece.getTeam()==Color.WHITE?y:7-y))*sign; break; case KNIGHT: value += 3000*sign; break; case BISHOP: value += 3000*sign; break; case ROOK: value += 5000*sign; break; case QUEEN: value += 9000*sign; break; case KING: king += (100000-(iterativeDepth-d))*sign; break; default: // value += 0; } } } return king==0?value:king; } private int allMoves(Board board, Player player, int begin, int level, PV pv) { random.setSeed(seed); int m=0; for (Piece piece : player.getPieces(board)) { for (Point point: piece.getValidDestinationSet(board)) { // shuffle and store int r=begin+random.nextInt(++m); points[begin+m-1]=points[r]; pieces[begin+m-1]=pieces[r]; points[r]=point; pieces[r]=piece; } } freedom[level]=m; if (pv!=null && pv.move!=null) { // push PV to front for (int i = 0; i < m; i++) { if (pv.move.getPiece().equals(pieces[begin+i]) && pv.move.getDestination().equals(points[begin+i])) { Point point = points[begin]; Piece piece = pieces[begin]; points[begin]=points[begin+i]; pieces[begin]=pieces[begin+i]; points[begin+i]=point; pieces[begin+i]=piece; break; } } } return begin+m; } } ``` [Answer] ## AlphaBeta Sorry, for having only morphed and fused code from other internet sources into this JAVA code. But it beats all other opponents (including PieceMaker) ... so far. * No move ordering. * No quiescence search. * No position evaluation. * Just raw brute force of alpha beta search. * Uses iterative deepening only for time management. And sorry, for playing so machine boring. ``` package player; import java.util.Random; import controller.*; public class AlphaBeta extends Player { private static final int INFINITY = Integer.MAX_VALUE; private static final int MAXTIME = 1800; // max time for evaluation private static final Random random=new Random(); private static int seed=1; private long time; // time taken this turn private int iterativeDepth; private Player myOpponent; private int best, candidate; @Override public Move getMove(Board root, Player min) { time=System.currentTimeMillis(); seed++; myOpponent=min; best=0; iterative_deepening(root); return allMoves(root, this)[best]; } private void iterative_deepening(Board root) { try { for (iterativeDepth = 2;; iterativeDepth++) { alphaBeta(root, -INFINITY, +INFINITY, iterativeDepth, this, myOpponent); best=candidate; } } catch (InterruptedException e) {} } //http://chessprogramming.wikispaces.com/Alpha-Beta private int alphaBeta(Board root, int alpha, int beta, int d, Player max, Player min) throws InterruptedException { if ((System.currentTimeMillis() - time) > MAXTIME) throw new InterruptedException(); if (d==0 || root.getKing(max) == null) return evaluate(root, d); Move[] allMoves = allMoves(root, max); Move move; for (int m=0; (move = allMoves[m])!=null; m++) { Board board = root.copy(); board.movePiece(move); int score = -alphaBeta(board, -beta, -alpha, d - 1, min, max); if (score >= beta) return beta; // fail hard beta-cutoff if (score > alpha) { alpha = score; // alpha acts like max in MiniMax if (d == iterativeDepth) candidate = m; } } return alpha; } private int evaluate(Board board, int d) { int minmax=2*((iterativeDepth-d)&1)-1; int value = 0, king=0; Field[][] field = board.getFields(); for (int x = 0; x < 8; x++) { for (int y = 0; y < 8; y++) { Piece piece = field[x][y].getPiece(); if (piece==null) continue; int sign=(piece.getTeam()==getTeam())?-minmax:minmax; switch (piece.getType()) { case PAWN: value += 1*sign; break; case KNIGHT: value += 3*sign; break; case BISHOP: value += 3*sign; break; case ROOK: value += 5*sign; break; case QUEEN: value += 9*sign; break; case KING: king += (100-(iterativeDepth-d))*sign; break; default: // value += 0; } } } return king==0?value:king; } private Move[] allMoves(Board board, Player player) { random.setSeed(seed); Move[] move = new Move[200]; int m=0; for (Piece piece : player.getPieces(board)) { for (Point point: piece.getValidDestinationSet(board)) { // shuffle int r=random.nextInt(++m); move[m-1]=move[r]; move[r]=new Move(piece.copy(), point); } } return move; } } ``` [Answer] # Not an answer, but a simulation to help I added a new class: GamePanel and edited Game and Controller ~~It isn't very pretty...yet.~~ Did you know Unicode had chess characters!?!? (totally awesome!) By the way, you need UTF-8 for these characters to show. It worked for me, but not sure how it will work on other operating systems. Fixed end of games bug (thanks to tim for pointing that out). GamePanel: ``` import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; import java.awt.Graphics; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.util.ArrayList; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; public class GamePanel extends JPanel{ private static final long serialVersionUID = 1L; JFrame container; Board currentBoard; Game currentGame; ArrayList<Game> games; public GamePanel(ArrayList<Game> Games){ games = Games; currentGame = games.get(0); currentBoard = currentGame.allBoards.get(0); container = new JFrame(); container.setSize(new Dimension(500,500)); container.setMinimumSize(new Dimension(150,150)); this.setMinimumSize(new Dimension(150,150)); JButton skipButton = new JButton("skip game"); skipButton.addMouseListener(new MouseListener(){ @Override public void mouseClicked(MouseEvent arg0) { nextGame(); } @Override public void mouseEntered(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mouseExited(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mousePressed(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mouseReleased(MouseEvent arg0) { // TODO Auto-generated method stub } }); JButton undoButton = new JButton("go back"); undoButton.addMouseListener(new MouseListener(){ @Override public void mouseClicked(MouseEvent e) { unStep(); } @Override public void mouseEntered(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseExited(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mousePressed(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseReleased(MouseEvent e) { // TODO Auto-generated method stub } }); JButton continueButton = new JButton("continue"); undoButton.setSize(40,40); skipButton.setSize(40,40); continueButton.setSize(40,40); continueButton.addMouseListener(new MouseListener(){ @Override public void mouseClicked(MouseEvent arg0) { step(); } @Override public void mouseEntered(MouseEvent arg0) { } @Override public void mouseExited(MouseEvent arg0) { } @Override public void mousePressed(MouseEvent arg0) { } @Override public void mouseReleased(MouseEvent arg0) { } }); JPanel buttonPanel = new JPanel(); buttonPanel.setLayout(new FlowLayout()); buttonPanel.add(continueButton); buttonPanel.add(undoButton); buttonPanel.add(skipButton); container.setLayout(new BorderLayout()); container.getContentPane().add(this,BorderLayout.CENTER); container.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); container.getContentPane().add(buttonPanel,BorderLayout.NORTH); container.setTitle("White: " + currentGame.players[0].getClass().getSimpleName() + " vs "+ "Black: " + currentGame.players[1].getClass().getSimpleName()); container.setVisible(true); container.invalidate(); container.repaint(); } private void unStep(){ if(currentBoard!=currentGame.allBoards.get(0)){ currentBoard=currentGame.allBoards.get(currentGame.allBoards.indexOf(currentBoard)-1); } container.invalidate(); container.repaint(); } private void unGame(){ if(currentGame != games.get(0)){ currentGame = games.get(games.indexOf(currentGame)-1); currentBoard = currentGame.allBoards.get(0); } container.invalidate(); container.repaint(); } private void step(){ if(currentGame.allBoards.indexOf(currentBoard)==currentGame.allBoards.size()-1){ nextGame(); } else{ currentBoard = currentGame.allBoards.get(currentGame.allBoards.indexOf(currentBoard)+1); } container.invalidate(); container.repaint(); } private void nextGame(){ container.setTitle("White: " + currentGame.players[0].getClass().getSimpleName() + " vs "+ "Black: " + currentGame.players[1].getClass().getSimpleName()); if(currentGame != games.get(games.size()-1)){ currentGame = games.get(games.indexOf(currentGame)+1); } else{ //games complete container.dispose(); } currentBoard = currentGame.allBoards.get(0); container.invalidate(); container.repaint(); } @Override public void paintComponent(Graphics g){ if(getWidth()>150 && getHeight() > 150){ int leftBounds,topBounds,width,height; topBounds = 50; leftBounds = 50; if(getWidth() > getHeight()){ width = (int) (getHeight()-100); height = (int) (getHeight()-100); } else{ width = (int) (getWidth()-100); height = (int) (getWidth()-100); } //draw grid java.awt.Color dark = new java.awt.Color(128, 78, 41); java.awt.Color light = new java.awt.Color(250, 223, 173); Field[][] feilds = currentBoard.getFields(); for(int x = leftBounds; x < leftBounds+width-width/8; x+=width/8){ for(int y = topBounds; y < topBounds+height-height/8; y+=height/8){ int xPos = (int)Math.round(((double)(x-leftBounds)/(double)width)*8); int yPos = (int)Math.round(((double)(y-topBounds)/(double)height)*8); String piece = ""; java.awt.Color stringColor = java.awt.Color.black; if(feilds[xPos][yPos].hasPiece()){ piece = getPiece(feilds[xPos][yPos].getPiece()); if(feilds[xPos][yPos].getPiece().getTeam()==Color.WHITE){stringColor = java.awt.Color.WHITE;} } if(yPos % 2 == 1){ if(xPos % 2 == 1){ g.setColor(dark); g.fillRect(x, y, width/8, height/8); } else{ g.setColor(light); g.fillRect(x, y, width/8, height/8); } } else{ if(xPos % 2 == 1){ g.setColor(light); g.fillRect(x, y, width/8, height/8); } else{ g.setColor(dark); g.fillRect(x, y, width/8, height/8); } } g.setColor(java.awt.Color.black); g.setFont(new Font(Font.SANS_SERIF, Font.BOLD, width/8)); g.drawString(piece, x, y+width/8); } } } } public String getPiece(Piece p){ if(p.getTeam() == Color.WHITE){ if(p.getType() == PieceType.BISHOP){return "\u2657";} if(p.getType() == PieceType.PAWN){return "\u2659";} if(p.getType() == PieceType.KING){return "\u2654";} if(p.getType() == PieceType.QUEEN){return "\u2655";} if(p.getType() == PieceType.ROOK){return "\u2656";} if(p.getType() == PieceType.KNIGHT){return "\u2658";} } else{ if(p.getType() == PieceType.BISHOP){return "\u265D";} if(p.getType() == PieceType.PAWN){return "\u265F";} if(p.getType() == PieceType.KING){return "\u265A";} if(p.getType() == PieceType.QUEEN){return "\u265B";} if(p.getType() == PieceType.ROOK){return "\u265C";} if(p.getType() == PieceType.KNIGHT){return "\u265E";} } return p.toString(); } } ``` Game: ``` import java.util.ArrayList; public class Game { private static final int MAX_TURNS_WITHOUT_CAPTURES = 100; //=50, counts for both teams private static final int MAX_MILLISECONDS = 2000; private Board board; Player[] players = new Player[2]; private int turnsWithoutCaptures = 0; private boolean draw = false; ArrayList<Board> allBoards = new ArrayList<Board>(); public Game(Player player1, Player player2) { board = new Board(); board.initialize(); players[0] = player1; players[0].setTeam(Color.WHITE); players[1] = player2; players[1].setTeam(Color.BLACK); allBoards.add(board.copy()); } int run() { int i = 0; while (!gameOver()) { if (!turnAvailable(players[i])) { draw = true; } else { makeTurn(players[i], players[(i+1) % 2]); i = (i + 1) % 2; } } if (loses(players[0]) && !loses(players[1])) { return Controller.LOSE_POINTS; } else if (loses(players[1]) && !loses(players[0])) { return Controller.WIN_POINTS; } else { return Controller.DRAW_POINTS; } } private boolean loses(Player player) { if (player.isDisqualified() || board.getKing(player) == null) { return true; } return false; } // player can make a turn private boolean turnAvailable(Player player) { for (Piece piece : player.getPieces(board)) { if (piece.getValidDestinationSet(board).size() > 0) { return true; } } return false; } private void makeTurn(Player player, Player enemy) { player.setCheck(board.isCheck(player, enemy)); enemy.setCheck(board.isCheck(enemy, player)); try { long start = System.currentTimeMillis(); Move move = player.getMove(board.copy(), enemy); if ((System.currentTimeMillis() - start) > MAX_MILLISECONDS) { player.setDisqualified(); } if (move.isValid(board, player)) { if (board.movePiece(move) || move.getPiece().getType() == PieceType.PAWN) { turnsWithoutCaptures = 0; } else { turnsWithoutCaptures++; } } else { player.setDisqualified(); //invalid move } } catch (Exception e) { player.setDisqualified(); e.printStackTrace(); System.out.println("Exception while moving " + player); } allBoards.add(board.copy()); } public boolean gameOver() { for (Player player : players) { if (player.isDisqualified() || board.getKing(player) == null || turnsWithoutCaptures >= MAX_TURNS_WITHOUT_CAPTURES || draw) { return true; } } return false; } } ``` Controller: ``` import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import players.*; public class Controller { public static final int WIN_POINTS = 3; public static final int DRAW_POINTS = 1; public static final int LOSE_POINTS = 0; private static final int GAMES_PER_PAIR = 10; private final Class[] classes = {StretchPlayer.class,TestPlayer.class}; private final Map<Class<? extends Player>, Integer> scores = new HashMap<Class<? extends Player>, Integer>(); public static void main(String... args) { new Controller().generateResult(); } public Controller() { for (Class player : classes) { scores.put(player, 0); } } ArrayList<Game> games = new ArrayList<Game>(); private void generateResult() { for (int i = 0; i < classes.length - 1; i++) { for (int j = i + 1; j < classes.length; j++) { for (int k = 0; k < GAMES_PER_PAIR; k++) { runGame(classes[i], classes[j], k>=GAMES_PER_PAIR); } } } GamePanel panel = new GamePanel(games); printScores(); } private void runGame(Class class1, Class class2, boolean switchSides) { if (switchSides) { //switch sides Class tempClass = class2; class2 = class1; class1 = tempClass; } try { Player player1 = (Player) class1.newInstance(); Player player2 = (Player) class2.newInstance(); Game game = new Game(player1, player2); games.add(game); int result = game.run(); addResult(class1, result, false); addResult(class2, result, true); } catch (Exception e) { System.out.println("Error in game between " + class1 + " and " + class2); } } private void addResult(Class player, int result, boolean reverse) { if (reverse) { if (result == WIN_POINTS) { result = LOSE_POINTS; } else if (result == LOSE_POINTS) { result = WIN_POINTS; } } int newScore = scores.get(player) + result; scores.put(player, newScore); } private void printScores() { int bestScore = 0; Class currPlayer = null; int place = 1; while (scores.size() > 0) { bestScore = 0; currPlayer = null; for (Class player : scores.keySet()) { int playerScore = scores.get(player); if (scores.get(player) >= bestScore) { bestScore = playerScore; currPlayer = player; } } System.out.println(String.format("%02d", place++) + ") " + currPlayer + ": " + bestScore); scores.remove(currPlayer); } } } ``` [Answer] ## DontThinkAhead This 'AI' doesn't like thinking ahead. If it sees that it can catch an enemy piece, it will do so immediately. If it cannot, it will just move a piece at random. It is slightly better than `SimplePlayer` and `TestPlayer` and I mainly wrote it to get a feel for the controller code and have something to test against. ``` package player; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Random; import controller.*; /** * Thinking ahead is hard, so lets not do it. */ public class DontThinkAhead extends Player { @Override public Move getMove(Board board, Player enemy) { List<Move> moves = new ArrayList<>(); List<Piece> pieces = this.getPieces(board); for (Piece piece : pieces) { Point[] destinations = piece.getValidDestinations(board); for (Point point : destinations) { moves.add(new Move(piece, point)); } } List<Node> ratedMoves = new ArrayList<>(); for (Move move : moves) { Point dest = move.getDestination(); Field destField = board.getFields()[dest.getX()][dest.getY()]; if (destField.hasPiece()) { int rating = 0; PieceType type = destField.getPiece().getType(); switch (type) { case PAWN: rating = 1; break; case KNIGHT: rating = 3; break; case BISHOP: rating = 3; break; case ROOK: rating = 5; break; case QUEEN: rating = 9; break; case KING: rating = 9999; break; default: rating = 0; } ratedMoves.add(new Node(move, rating)); } } if (!ratedMoves.isEmpty()) { Collections.sort(ratedMoves, new ComparatorNode()); return ratedMoves.get(0).getMove(); } else { // no good move possible, return random move return moves.get(new Random().nextInt(moves.size())); } } private class Node { private Move move; private int rating; public Node(Move move, int rating) { this.move = move; this.rating = rating; } public int getRating() { return rating; } public Move getMove() { return move; } } private class ComparatorNode implements Comparator<Node> { @Override public int compare(Node t, Node t1) { return t1.getRating() - t.getRating(); } } } ``` [Answer] # Cheese Yes, you read it right. A block of cheese, playing chess. ## Algorithm The cheese checks all possible moves and scores them accordingly. He (the cheese, and yes it's a male) uses the following guide to scoring his choices : ### Eating * King = **OVER 9000!!!!!!!!!!** * Queen = 18 * Rook = 10 * Bishop = 6 * Knight = 6 * Pawn = 2 ### Risk of getting eaten * King = **UNDER -9000!!!!!!!!!!!** * Queen = -16 * Rook = -8 * Bishop = -5 * Knight = -5 * Pawn = 0 ### Chance of eating next turn * King = 5 * Queen = 3 * Rook = 2 * Bishop = 1 * Knight = 1 * Pawn = 0 ## Pending Improvements * NOT ENOUGH SWAG (going to check on this possibility soon) * I checked my time and it seems that I run in 0-1 milliseconds. I think I can be more aggressive with my algorithms then. ## Bugs fixed * When checking for scores for possible targets to eat, I counted my own units. Now, I'm only scoring if I can eat an **enemy piece**. ``` package player; import pieces.Queen; import controller.*; public class Cheese extends Player { private final int[] eatingPriorities = { 9999, 18, 10, 6, 6, 2, 0 }; private final int[] gettingEatenPriorities = { -9000, -16, -8, -5, -5, 0, 0 }; private final int[] chanceToEatPriorities = {5,3,2,1,1,0,0}; @Override public Move getMove(Board board, Player enemy) { int maxScore = -10000; Move bestMove = null; int score = 0; Field[][] field = board.getFields(); Field fieldDest; // get best move for (Piece myPiece : this.getPieces(board)) { for (Point possibleDest : myPiece.getValidDestinationSet(board)) { score=0; fieldDest = field[possibleDest.getX()][possibleDest.getY()]; //if you're eating an enemy piece, SCORE! if(fieldDest.hasPiece() && fieldDest.getPiece().getTeam()!=this.getTeam()){ score += eatingPriorities[getPriorityIndex(fieldDest.getPiece().getType())]; } score+=getAftermoveRisk(board, enemy, new Move(myPiece, possibleDest)); if (maxScore < score) { maxScore = score; bestMove = new Move(myPiece,possibleDest); } } } return bestMove; } private int getAftermoveRisk(Board board, Player enemy, Move move){ int gettingEatenRisk=0, chanceToEatScore=0; Field[][] simField; Field field; Board simBoard = board.copy(); simField = simBoard.getFields(); this.simulateMovePiece(simField, move); //gettingEaten risk for (Piece enemyPiece : enemy.getPieces(simBoard)) { for (Point possibleDest : enemyPiece.getValidDestinationSet(simBoard)) { field = simField[possibleDest.getX()][possibleDest.getY()]; //if it's my piece that's in the line of fire, increase gettingEatenRisk if(field.hasPiece() && field.getPiece().getTeam()==this.getTeam()){ gettingEatenRisk += gettingEatenPriorities[getPriorityIndex(field.getPiece().getType())]; } } } //chanceToEat score for (Piece myPiece : this.getPieces(simBoard)) { for (Point possibleDest : myPiece.getValidDestinationSet(simBoard)) { field = simField[possibleDest.getX()][possibleDest.getY()]; //if it's their piece that's in the line of fire, increase chanceToEatScore if(field.hasPiece() && field.getPiece().getTeam()!=this.getTeam()){ chanceToEatScore += chanceToEatPriorities[getPriorityIndex(field.getPiece().getType())]; } } } return gettingEatenRisk + chanceToEatScore; } // Copied and edited from Board.movePiece public void simulateMovePiece(Field[][] fields, Move move) { Piece piece = move.getPiece(); Point dest = move.getDestination(); if (!dest.isOutside()) { // upgrade pawn if (piece.getType() == PieceType.PAWN && (dest.getY() == 0 || dest.getY() == 7)) { fields[dest.getX()][dest.getY()].setPiece(new Queen(piece.getTeam(), dest)); } else { fields[dest.getX()][dest.getY()].setPiece(piece); } //remove piece on old field fields[piece.getPos().getX()][piece.getPos().getY()].setPiece(null); } } private int getPriorityIndex(PieceType type) { int index = 0; switch (type) { case KING: index = 0; break; case QUEEN: index = 1; break; case ROOK: index = 2; break; case BISHOP: index = 3; break; case KNIGHT: index = 4; break; case PAWN: index = 5; break; default: index = 6; } return index; } } ``` [Answer] # SimplePlayer This player just makes sure he uses valid moves, but otherwise is pretty dumb. ``` package player; import java.util.List; import controller.*; public class SimplePlayer extends Player { @Override public Move getMove(Board board, Player enemy) { //get all pieces of this player List<Piece> pieces = this.getPieces(board); for (Piece piece : pieces) { Point[] destinations = piece.getValidDestinations(board); if (destinations.length > 0) { return new Move(piece, destinations[0]); } } //should never happen, because the game is over then return null; } } ``` ]
[Question] [ Your task here is to write two regular expressions, each of which matches the other one but does not match itself. Both regular expressions should have this form: ``` /pattern/optional-flags ``` This is also the form in which they should be matched. The shortest solution wins. The solution length is counted as the sum of characters in both regular expressions including slashes and flags. Use a regex syntax standard of your choice, or specify a programming language, when it makes a difference. Have fun! [Answer] # 4+6=score of 10 First regex: ``` /i$/ ``` Second regex: ``` /^.i/i ``` Hooray for flag abuse! :-P The first one matches anything that ends with `i` (therefore, any regex with the `i` flag). The second one matches anything with a second character of `i`. Alternative version: `/i$/g` and `/g$/i`. [Answer] ## PRCE with the A modifier: 9 chars ``` /A$/ /.A/A ``` Although this is a variant on Doorknob's `/modifier$/` answer, I think this innovation qualifies it as a separate answer rather than a comment on his: the modifier does double-duty. Rather than being there solely for the other regex to match, it anchors. The first regex matches any string ending in a literal `A`. The second regex matches any string whose second character is a literal `A`, using an anchor-to-start flag. [Online demo](http://ideone.com/iHaQrv) [Answer] ## JavaScript regexes, score: 18 First regex: ``` /^[^a]+$/ ``` Second regex: ``` /^[^b]+$/ ``` JavaScript test: ``` var regex1 = "/^[^a]+$/"; var regex2 = "/^[^b]+$/"; alert(/^[^a]+$/.test(regex2)); // true: regex1 matches regex2 alert(/^[^b]+$/.test(regex1)); // true: regex2 matches regex1 alert(/^[^a]+$/.test(regex1)); // false: regex1 doesn't match regex1 alert(/^[^b]+$/.test(regex2)); // false: regex2 doesn't match regex2 ``` Test online: <http://jsfiddle.net/99Sx6/> [Answer] ## Ruby regex, 15 Regular expressions: ``` /.{9}/ /^.{06}$/ ``` Just counting characters... [Online version](http://repl.it/PZc/1) ``` r1 = '/.{9}/' r2 = '/^.{06}$/' p r1 =~ /^.{06}$/ #0: r2 matches r1 p r2 =~ /.{9}/ #0: r1 matches r2 p r1 =~ /.{9}/ #nil: r1 doesn't match r1 p r2 =~ /^.{06}$/ #nil: r2 doesn't match r2 ``` [Answer] # 4 + 6 = 10 First regex: ``` /i$/ ``` Second regex: ``` /\/$/i ``` `i$` matches something that ends with `i`, the second one. `/$` matches something that ends with `/`, the first one. [Answer] # 5 + 5 = 10 Regex #1: ``` /0.$/ ``` Regex #2: ``` /^.0/ ``` The `0`s in both regexes can be replaced with any non-metacharacter and the regex still works. `0.$` matches anything whose second last character is `0`, and `^.0` matches anything whose second character is `0`. [Answer] # Score: 5 + 5 = 10 Took me half-an-hour to figure out but I am really happy that I did :) ### 1st is: `/j.$/` ### 2nd is: `/^.j/` The 1st matched a `j` occurring in the second position starting from the right. The 2nd matches a `j` occurring at the second-position starting from left. I haven't tested but I think that these RegExs are really versatile as the `j` can be replaced with any `\w` character (or more?) and still should work fine. P.S. This should (hopefully) work in any language. Though, if it does not work in any, please inform in the comments below :) [Test](http://jsbin.com/vimugula/1/edit) [Answer] ## JavaScript regexes, score: 13 First regex: ``` /\d/ ``` Second regex: ``` /^[^0]+$/ ``` Explanation: the first regex matches everything that contains a digit, and the second regex matches everything that doesn't contain a `0`. JavaScript test: ``` var regex1 = "/\d/"; var regex2 = "/^[^0]+$/"; alert(/\d/.test(regex2)); // true: regex1 matches regex2 alert(/^[^0]+$/.test(regex1)); // true: regex2 matches regex1 alert(/\d/.test(regex1)); // false: regex1 doesn't match regex1 alert(/^[^0]+$/.test(regex2)); // false: regex2 doesn't math regex2 ``` Test online: <http://jsfiddle.net/5VYjC/1/> [Answer] **12 chars** ;) JS regex ``` /\d/ /0?\/$/g ``` [Answer] ### PCRE using modifier x: 11 chars ``` /\s/ / s.$/x ``` The first matches any string with a whitespace character, but doesn't contain whitespace. The second contains whitespace, but it's ignored because of the `x` modifier; it matches any string whose penultimate character is `s`. ### PCRE and other engines using character classes: 11 chars ``` /\w+w/ /\Ww/ ``` The first matches any string with a "word" character (letter, digit, underscore) followed by a literal `w`; the second matches any string with a non-word character followed by a literal `w`. ### PCRE and other engines using character classes and word boundary anchor: 11 chars ``` /\w\w/ /\bw/ ``` The first matches any string with two consecutive "word" characters; the second any string with a non-word character or start of string followed by a literal `w`. [Answer] # ECMAScript (11 bytes): ``` /^\1?d/ /\d/ ``` # Other REGEXP Engines (14 bytes): ``` /^\\\\1?d/ /\d/ ``` The 1st matches \d[..] or \1d[..]. The second matches any string with a number. **EDIT:** Originally, this answer was posted as being compatible with all engines, but it was proven to be wrong. There was a problem with references to the capturing groups (for example, in php). ]
[Question] [ This is sequence [A054261](https://oeis.org/A054261). The \$n\$th prime containment number is the lowest number which contains the first \$n\$ prime numbers as substrings. For example, the number \$235\$ is the lowest number which contains the first 3 primes as substrings, making it the 3rd prime containment number. It is trivial to figure out that the first four prime containment numbers are \$2\$, \$23\$, \$235\$ and \$2357\$, but then it gets more interesting. Since the next prime is 11, the next prime containment number is not \$235711\$, but it is \$112357\$ since it's defined as the smallest number with the property. However, the real challenge comes when you go beyond 11. The next prime containment number is \$113257\$. Note that in this number, the substrings `11` and `13` are overlapping. The number `3` is also overlapping with the number `13`. It is easy to prove that this sequence is increasing, since the next number needs to fulfill all criteria of the number before it, and have one more substring. However, the sequence is not strictly increasing, as is shown by the results for `n=10` and `n=11`. ## Input A single integer `n>0` (I suppose you could also have it 0-indexed, then making `n>=0`) ## Output Either the `n`th prime containment number, or a list containing the first `n` prime containment numbers. The numbers I have found so far are: ``` 1 => 2 2 => 23 3 => 235 4 => 2357 5 => 112357 6 => 113257 7 => 1131725 8 => 113171925 9 => 1131719235 10 => 113171923295 11 => 113171923295 12 => 1131719237295 ``` Note that `n = 10` and `n = 11` are the same number, since \$113171923295\$ is the lowest number which contains all numbers \$[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]\$, but it also contains \$31\$. Since this is marked code golf, get golfing! Brute force solutions are allowed, but your code has to work for any input in theory (meaning that you can't just concatenate the first n primes). Happy golfing! [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes ``` ∞.ΔIÅpåP ``` [Try it online!](https://tio.run/##yy9OTMpM/f//Ucc8vXNTPA@3FhxeGvD/vxkA "05AB1E – Try It Online") **Explanation** ``` # from ∞ # a list of infinite positive integers .Δ # find the first which satisfies the condition: P # all IÅp # of the first <input> prime numbers å # are contained in the number ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes ``` ³ÆN€ẇ€µẠ$1# ``` [Try it online!](https://tio.run/##y0rNyan8///Q5sNtfo@a1jzc1Q4kD219uGuBiqHy////zQA "Jelly – Try It Online") Simple brute force. Not completely sure how `#`'s arity works, so there may be some room for improvement. ### How it works ``` ³ÆN€ẇ€µẠ$1# Main link. Input: Index n. 1# Find the first natural number N that satisfies: ³ÆN€ First n primes... ẇ€ ...are substrings of N µẠ$ All of them are true ``` [Answer] # Java 8, 143 bytes ``` n->{int r=1,f=1,c,i,j,k;for(;f>0;r++)for(i=2,f=c=n;c>0;c-=j>1?1+0*(f-=(r+"").contains(j+"")?1:0):0)for(j=i++,k=2;k<j;)j=j%k++<1?0:j;return~-r;} ``` [Try it online.](https://tio.run/##LZDBboMwDIbvfQoLaVKyAIJeJmECT7Beetx2yFKoEmioQqg0Vd2rM4dVii39f@zks626qcyehlWPap7hXRl33wEYFzrfK93BIcrNAM1idhzJeewozUEFo@EADiSsLmvuscDLMu0pdGpSmw7YT55h3xToheBRGLmnAi0danJ1Jm1TtqUoXlmfSeZFkvBcTy4Qy8xslG1ZFZxO7LbSCJEOco9DbZFbaV8GIeqyLSqLvguLd7@Zx8eKEfG6fI@E@CS9TeYEF3qXHYM37vzxBYr/D7iBEb2RJZpaviH9wrcbgOPPHLpLPi0hv1JbGB0zIqk@QyJcTlvhz5U81j8) NOTES: 1. Times out above `n=7`. 2. Given enough time and resources it only works up to a maximum of `n=9` due to the size limit of `int` (maximum of `2,147,483,647`). * With [+4 bytes changing the `int` to a `long`](https://tio.run/##LZDBasMwDIbvfQoRGNizE@JdBnGcvMDWS4/bDp6bFDupUxynMEr26pncFYTg/y3Jn@T0VefuOGxm1PMM79r62w7A@tiFXpsO9kkCjJM/gSHog6cSrXWHaY46WgN78KBg83lzu9cFJd54rwI33HLHB9lPgci@KWVgjCZh1UuqMMpLg7bJlWtEK1j5TPpckcCyjBZm8hF5ZuKSbEVVUozU7pRljA84RA61k9Qp9zQwVou2rJwMXVyC/82DXDeZMC/L94iYD9rrZI9wxsHkEIP1p48v0PR/yzsarmiVkLZWrxK/ofcXgMPPHLtzMS2xuGBbHD2xLKs@Y8Z8gZehj7Os2x8), the maximum is increased to an output below `9,223,372,036,854,775,807` (about `n=20` I think?) * By using `java.math.BigInteger` the maximum can be increased to any size (in theory), but it will be around +200 bytes at least due to the verbosity of `java.math.BigInteger`'s methods.. **Explanation:** ``` n->{ // Method with integer as both parameter and return-type int r=1, // Result-integer, starting at 1 f=1, // Flag-integer, starting at 1 as well c, // Counter-integer, starting uninitialized i,j,k; // Index integers for(;f>0; // Loop as long as the flag is not 0 yet r++) // After every iteration, increase the result by 1 for(i=2, // Reset `i` to 2 f=c=n; // Reset both `f` and `c` to the input `n` c>0; // Inner loop as long as the counter is not 0 yet c-= // After every iteration, decrease the counter by: j>1? // If `j` is a prime: 1 // Decrease the counter by 1 +0*(f-= // And also decrease the flag by: (r+"").contains(j+"")? // If the result `r` contains the prime `j` as substring 1 // Decrease the flag by 1 : // Else: 0) // Leave the flag the same : // Else: 0) // Leave the counter the same for(j=i++, // Set `j` to the current `i`, // (and increase `i` by 1 afterwards with `i++`) k=2; // Set `k` to 2 (the first prime) k<j;) // Inner loop as long as `k` is smaller than `j` j=j%k++<1? // If `j` is divisible by `k` 0 // Set `j` to 0 : // Else: j; // Leave `j` the same // (If `j` is unchanged after this inner-most loop, // it means `j` is a prime) return~-r;} // Return `r-1` as result ``` [Answer] # JavaScript (ES6), ~~105 ... 92~~ 91 bytes ``` n=>(k=1,g=(s,d=k++)=>n?k%d--?g(s,d):g(d?s:s+`-!/${n--,k}/.test(n)`):eval(s+';)++n'))`for(;` ``` [Try it online!](https://tio.run/##FcxBCoMwEIXhq6TQ4gwxiquCdvQqCSaGNjIpRtwUz57G1Q@Px/cxh0nz9v7uiqN1eaHMNEKgrvYEqbYUpEQaeQoPq9Tkrw17D3ZKfZJa3dr7j5Wqw9k2u0s7MGrs3WFWSLIaUEquEPUSNxh0vsKCRDcIFi8Sz9Liizlyiqtr1uhBGyjkieWmhRRLETH/AQ "JavaScript (Node.js) – Try It Online") ### How? We recursively build a concatenation of conditions based on the first \$n\$ primes: ``` "-!/2/.test(n)-!/3/.test(n)-!/5/.test(n)-!/7/.test(n)-!/11/.test(n)..." ``` We then look for the smallest \$n\$ such that all conditions evaluate to *false*: ``` eval('for(;' + <conditions> + ';)++n') ``` ### Commented ``` n => ( // main function taking n k = 1, // k = current prime candidate, initialized to 1 g = (s, // g = recursive function taking the code string s d = k++) => // and the divisor d n ? // if n is not equal to 0: k % d-- ? // if d is not a divisor of k: g(s, d) // recursive call to test the next divisor : // else: g( // recursive call with s updated and d undefined: d ? // if d is not equal to 0 (i.e. k is composite): s // leave s unchanged : // else (k is prime): s + // decrement n and add to s `-!/${n--,k}/.test(n)` // the next condition based on the prime k // the lack of 2nd argument triggers 'd = k++' ) // end of recursive call : // else (n = 0): eval(s + ';)++n') // complete and evaluate the code string )`for(;` // initial call to g with s = [ "for(;" ] ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 58 bytes ``` ->n,i=1{i+=1until Prime.take(n).all?{|x|/#{x}/=~"#{i}"};i} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y5PJ9PWsDpT29awNK8kM0choCgzN1WvJDE7VSNPUy8xJ8e@uqaiRl@5uqJW37ZOSbk6s1ap1jqz9r@GoZ6euaZeamJyRnVNSU2BQlp0SWzt/3/5BSWZ@XnF/3WLCkBGAQA "Ruby – Try It Online") Brute-force, works up to 7 on TIO. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 14 bytes Extremely, *extremely* slow, times out for \$n>5\$ on TIO. ``` f@I`M.fP_ZQ1y` ``` [Try it online!](https://tio.run/##K6gsyfj/P83BM8FXLy0gPirQsDLh/39TAA "Pyth – Try It Online") ``` f@I`M.fP_ZQ1y` Full program. Q is the input. f Find the first positive integer that fulfils the condition. @I`M.fP_ZQ1y` Filtering condition, uses T to refer to the number being tested. .f Q1 Starting at 1, find the first Q positive integers (.f...Q1) that P_Z Are prime. `M Convert all of those primes to strings. I Check whether the result is invariant (i.e. doesn't change) when... @ y` Intersecting this list with the powerset of T as a string. ``` --- # [Pyth](https://github.com/isaacg1/pyth), 15 bytes Slightly faster but 1 byte longer. ``` f.A/L`T`M.fP_ZQ ``` [Try it online!](https://tio.run/##K6gsyfj/P03PUd8nISTBVy8tID4q8P9/MwA "Pyth – Try It Online") ``` f.A/L`T`M.fP_ZQ Full program. Q is the input. f Find the first positive integer that fulfils the condition. .A/L`T`M.fP_ZQ Filtering condition, uses T to refer to the number being tested. .f Q Starting at 1, find the first Q positive integers (.f...Q) that P_Z Are prime. `M Convert all of those primes to strings. .A/L And make sure that they all (.A) occur in (/L)... `T The string representation of T. ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes ``` ³RÆNṾ€ẇ€ṾȦ Ç1# ``` [Try it online!](https://tio.run/##y0rNyan8///Q5qDDbX4Pd@571LTm4a52ELlz34llXIfbDZX///9vAgA "Jelly – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 42 bytes ``` ≔¹ηW‹LυIθ«≦⊕η¿¬Φυ¬﹪ηκ⊞υη»≔¹ηWΦυ¬№IηIκ≦⊕ηIη ``` [Try it online!](https://tio.run/##fY7LCsIwEEXXzVfMcgJx4cZNV1IQBCv9hdDGTjAmmocuxG@PDVZEEGdxYbicy@lJ@t5Jk/M6BD1aXAogXrMbaaMAdyqEKewYCRMX0MgQ8cI5hzurWnmeoa3tvTopG9Xwwit9ANy7iBttovKYBJSvdUMyDknAkZeDLgUqZWEe7KfC90Ljkp2yaNDbZ976o9N5/aF4nfMqL67mCQ "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ≔¹ηW‹LυIθ«≦⊕η¿¬Φυ¬﹪ηκ⊞υη» ``` Build up the first `n` prime numbers by trial division of all the integers by all of the previously found prime numbers. ``` ≔¹ηWΦυ¬№IηIκ≦⊕η ``` Loop through all integers until we find one which contains all the primes as substrings. ``` Iη ``` Cast the result to string and implicitly print. The program's speed can be doubled at a cost of a byte by replacing the last `≦⊕η` with `≦⁺²η` but it's still too slow to calculate `n>6`. [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~63~~ 59 bytes *-4 bytes thanks to nwellnhof* ``` {+(1...->\a{!grep {a~~!/$^b/},(grep &is-prime,2..*)[^$_]})} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwv1pbw1BPT0/XLiaxWjG9KLVAoTqxrk5RXyUuSb9WRwMsopZZrFtQlJmbqmOkp6elGR2nEh9bq1n7Py2/SAGo2UShmktBoTixUkFPLc2aq/Y/AA "Perl 6 – Try It Online") A brute force solutions that times out on TIO for numbers above 5, but I'm pretty sure it works correctly. Finds the first positive number that contains the first `n` primes. [Here's a solution](https://tio.run/##K0gtyjH7n1upoJamYKvwvxrIcki01UgvSi1QUMss1i0oysxN1THS09PSjI5TiY@11tYw1NPT07WLSaxWBKuqTqyrU9RXiUvSr9VxSKzVrP1fnFipkKZhpvkfAA) that doesn't time out for `n=6`. ### Explanation: ``` { } # Anonymous code block first 2..* # Find the first number ->\a{ } # Where: !grep # None of [^$_] # The first n (grep &is-prime,2..*) # primes {a~~!/$^b/}, # Are not in the current number ``` [Answer] # [Python 2](https://docs.python.org/2/), 131 bytes ``` f=lambda n,x=2:x*all(i in`x`for i in g(n,2))or f(n,x+1) def g(n,x):p=all(x%i for i in range(2,x));return[0]*n and[`x`]*p+g(n-p,x+1) ``` [Try it online!](https://tio.run/##PYzLCoMwEEX3/YpsCona0qaPhcUvEcG0RjsQJ2ESIX59Gl10ceHeGc5xa/halAlmZykwv/pDztnrQPqzkAeLBmYIXN6eD5HGxqj5PSiGVWxkHQtlDAcG2Md@tMS2yiaOlRQizzG3WF7FYdDjfo6ids3GxCOwP0AKJ81l/ooX6bAQtpeuQKZwaLO4K1yZ4ZPbXckRYMhqQLcELkS6/wA "Python 2 – Try It Online") `f` is the function. [Answer] # [Python 2](https://docs.python.org/2/), 91 bytes ``` n=input();l=[] P=k=1 while~-all(`x`in`k`for x in(l+[l])[:n]):P*=k*k;k+=1;l+=P%k*[k] print k ``` [Try it online!](https://tio.run/##BcG9CsMgEADg3adwKfhDh5ROkXsHdxHMkJDjjlPE0nTpq5vva79xVnnNKYDSPsPYwJCyikCwqO@JvP@fG7MpV0EpVI7a9aVRDPvE2aZVsl2jA3IUyMMS2EN8kEuUVesoQ9Oc7xs "Python 2 – Try It Online") [Answer] # SAS, 149 bytes ``` data p;input n;z:i=1;a=0;v+1;do while(a<n);i+1;do j=2 to i while(mod(i,j));end;if j=i then do;a+1;if find(cat(v),cat(i))=0 then goto z;end;end;cards; ``` Input is entered following the `cards;` statement, like so: ``` data p;input n;z:i=1;a=0;v+1;do while(a<n);i+1;do j=2 to i while(mod(i,j));end;if j=i then do;a+1;if find(cat(v),cat(i))=0 then goto z;end;end;cards; 1 2 3 4 5 6 7 ``` Outputs a dataset `p`, with the result `v`, with an output row for each input value. Should technically work for all the given test-cases (the max integer with full precision in SAS is 9,007,199,254,740,992), but I gave up after letting it think for 5 minutes on n=8. Explanation: ``` data p; input n; /* Read a line of input */ z: /* Jump label (not proud of this) */ i=1; /* i is the current value which we are checking for primality */ a=0; /* a is the number of primes we've found so far */ v+1; /* v is the final output value which we'll look for substrings in */ do while(a<n); /* Loop until we find the Nth prime */ i+1; do j=2 to i while(mod(i,j));end; /* Prime sieve: If mod(i,j) != 0 for all j = 2 to i, then i is prime. This could be faster by only looping to sqrt(i), but would take more bytes */ if j=i then do; /* If i is prime (ie, we made it to the end of the prime sieve)... */ a+1; if find(cat(v),cat(i))=0 then goto z; /* If i does not appear as a substring of v, then start all over again with the next v */ end; end; /* Input values, separated by newlines */ cards; 1 2 3 4 5 6 7 ``` [Answer] # [Haskell](https://www.haskell.org/), 102 bytes ``` import Data.List f n|x<-[2..n*n]=[a|a<-[2..],all(`isInfixOf`show a).take n$show<$>x\\((*)<$>x<*>x)]!!0 ``` [Try it online!](https://tio.run/##JY6xDoIwGIR3nuLHMLSgjTo4AZOLCcbBEZrwDyANpRBaQwfevRZcLndfLpfrUPeNlM6JYRpnA3c0yAqhTdCCWm16Kq@MqVjxrMQV/5EfUUpSC/1QrbCvttbduABSZrBvQEVbTKPcVhUhMd1cGueW8jA8uwGFggwGnJ5Apq95m7lQwOAzUigvjN04LF0zN4EnsDX3bQVJAgfIci/e7Yz4g9T9AA "Haskell – Try It Online") ## Explanation / Ungolfed Since we already have `Data.List` imported we might as well use it: Instead of the good old `take n[p|p<-[2..],all((>0).mod p)[2..p-1]]` we can use another way of generating all primes we need. Namely, we generate a sufficient amount of composites and use these together with `(\\)`: ``` [2..n*n] \\ ( (*) <$> [2..n*n] <*> [2..n*n] ) ``` Using `n*n` suffices because \$\pi(n) < \frac{n^2}{\log(n^2)}\$. The rest is just a simple list comprehension: ``` [ a | a <- [2..], all (`isInfixOf` show a) . take n $ enoughPrimes ] !!0 ``` [Answer] # Japt, ~~20~~ 18 bytes Far from my finest work, I was just happy to get it working after the day I've had. I'm sure I'll end up tapping away at it down the boozer later! ``` _õ fj ¯U e!øZs}aUÄ ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=X/UgZmogr1UgZSH4WnN9YVXE&input=Mw==) - takes 13 seconds to run for an input of `7`, throws a wobbly after that (the updated version craps out at `5` for me, but that might just be my phone). ]
[Question] [ # Background Most of you know what a [Fibonacci number](https://en.wikipedia.org/wiki/Fibonacci_number) is. Some of you may know that all positive integers can be represented as a sum of one or more distinct Fibonacci numbers, according to [Zeckendorf's Theorem](https://en.wikipedia.org/wiki/Zeckendorf%27s_theorem). If the number of terms in the optimal Zeckendorf Representation of an integer `n` is itself a Fibonacci number, we will call `n` "secretly" Fibonacci. For example: ``` 139 = 89 + 34 + 13 + 3 This is a total of 4 integers. Since 4 is not a Fibonacci number, 139 is not secretly Fibonacci 140 = 89 + 34 + 13 + 3 + 1 This is a total of 5 integers. Since 5 is a Fibonacci number, 140 is secretly Fibonacci ``` ## Notes * The optimal Zeckendorf Representation can be found using a greedy algorithm. Simply take the largest Fibonacci number <= n and subtract it from n until you reach 0 * All Fibonacci numbers can be represented as a sum of 1 Fibonacci number (itself). Since 1 is a Fibonacci number, all Fibonacci numbers are also secretly Fibonacci. # Challenge Your challenge is to write a program or function that takes an integer and returns whether that integer is secretly Fibonacci. ## Input You may take input in any reasonable format. You may assume the input will be a single positive integer. ## Output Output one of two distinct results for whether the input is secretly Fibonacci. Examples include `True`/`False`, `1`/`0`, etc. ## Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins! Standard loopholes are forbidden. # Test Cases ``` Truthy (secretly Fibonacci) 1 2 4 50 140 300099 Falsey (NOT secretly Fibonacci) 33 53 54 139 118808 ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 54 bytes ``` x=>g(g(x))<2;g=(x,i=1,j=1)=>j>x?x&&g(x-i)+1:g(x,j,i+j) ``` [Try it online!](https://tio.run/##ZclNDkAwEEDhvYPITJQoNn6mdu4hSNOJqCAyt6/u7V6@x/M738vlzic//LqFiYKQsWBBEIeqtwSiHGnFpJEMGxklTePNHWa6i6FYuYwx9Mnij9vvW7F7CxPoukX8YVNGDB8 "JavaScript (Node.js) – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 77 bytes ``` def f(n):z=[bin(x).count('1')for x in range(n*n+1)if x&2*x<1];print z[z[n]]<2 ``` [Try it online!](https://tio.run/##NcmxDsIgEIDh3ae4yXKVmB7UQa1PQhiqFmXwIAQT5OWxDg7/8n/xk5@BVWv3xYETjKd6MVfPouD@Ft6cRUcdupCggGdIMz8WwT3vCL2DslV9mcieY/KcoZpq2NpJtdcchZNgSIKSMEo4DBJoHCxu/qT1en@tSvposX0B "Python 2 – Try It Online") This makes use of the theorem that the two descriptions of [OEIS A003714](https://oeis.org/A003714) are equivalent: > > Fibbinary numbers: if \$n = F(i\_1) + F(i\_2) + \dots + F(i\_k) \$ is the Zeckendorf representation of \$n\$ (i.e., write \$n\$ in Fibonacci number system) then \$a(n) = 2^{i\_1} + 2^{i\_2} + \dots + 2^{i\_k}\$. **Also** numbers whose binary representation contains no two adjacent \$1\$'s. > > > We generate enough\* such numbers, and then use `z` as a mapping from non-negative integers to “how many terms are in the Zeckendorf representation of \$n\$?” by counting 1s in binary. Then it remains to check if `z[n]` is a Fibonacci number, i.e. `z[z[n]] == 1`. \*At least, \$n^2+1\$ *feels* like enough, and experimentally it seems to be enough. I'll prove this some time later. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 15 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ‘ÆḞ€fRṪạµƬL’Ɗ⁺Ị ``` A monadic link accepting a non-negative integer which yields `1` if "Secretly Fibonacci" and `0` otherwise. **[Try it online!](https://tio.run/##ATAAz/9qZWxsef//4oCYw4bhuJ7igqxmUuG5quG6ocK1xqxM4oCZxorigbrhu4r///8yMzI "Jelly – Try It Online")** (too inefficient for the larger test cases) ### How? ``` ‘ÆḞ€fRṪạµƬL’Ɗ⁺Ị - Link: integer, I µƬ - perform the monadic link to the left as a function of the current I, - collecting up all the inputs until the results are no longer unique: ‘ - increment I -> I+1 ÆḞ€ - nth Fibonacci number for €ach n in [1,I+1] R - range from 1 to I f - filter discard (discard Fibonacci numbers not in the range, i.e. > I) Ṫ - tail (get the largest) ạ - absolute difference with I - This gives us a list from I decreasing by Fibonacci numbers to 0 - e.g. for 88 we get [88,33,12,4,1,0] - because (88-33)+(33-12)+(12-4)+(4-1)+(1-0)=55+21+8+3+1=88 L - length (the number of Fibonacci numbers required plus one) ’ - decrement (the number of Fibonacci numbers required) Ɗ - treat the last three links (which is everything to the left) as a monad: ⁺ - ...and repeat it - i.e. get the number of Fibonacci numbers required for the number of - Fibonacci numbers required to represent I. - This is 1 if I is Secretly Fibonacci, and greater if not) Ị - insignificant? (is the absolute value of that <= 1?) ``` [Answer] # [R](https://www.r-project.org/), 83 bytes ``` function(n){T=1:0 while(n>T)T=c(T[1]+T[2],T) while(n){n=n-T[T<=n][1] F=F+1} F%in%T} ``` [Try it online!](https://tio.run/##PcrNCoJAFEDh/TyFEMIMXmGuo6DhBC2cVau6rcRFSJIgN@mHCPHZJxcVnN13br4Lyth3T24f/ZUlq4ksrrV4XfrhLHlDimwrqcYmojppgNSP1MSWY6qptNwsLpx1Ec7ChT2HNPv7aRyHt2wlQgIpZBow1WC01kWhoFPBKqD9sRL/zxjIllJAUwBinuv8@7nt7lD5Dw "R – Try It Online") [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 124 115 98 bytes ``` a=>{int n=0,b,c;for(;a>0;a-=b,n++)for(b=c=1;c<=a;b=c-b)c+=b;for(b=c=1;c<n;c+=b)b=c-b;return c==n;} ``` [Try it online!](https://tio.run/##hc/BSsUwEAXQtf2KLBvaSmKf0DJvCiK40pUL10lMJVAnkKSClH57bUXBhbxkFe49TCYmNsYHu83R0Rt7/ozJvgMzk4qR3bGliEklZ9jDTObsKNXa@2lgI24Kh2UPGKGodW1g9KEENQhQDeqaqoofiUaDEswZFezXRnNToYa/DcER8e8Wgk1zIGYQCdYNfl//8O6VPSlHJV@Kq3tP0U/2@iW4ZB8d2XIsJedQsJ/zH7jJgVMO3IqckKcsaYUQfX@oC@xyuw9ps7vmRfa/su2zRHad6A61rtsX "C# (.NET Core) – Try It Online") *-3 bytes: changed while loop to for (thanks to [Olivier Grégoire](https://codegolf.stackexchange.com/questions/174907/is-this-number-secretly-fibonacci/174922?noredirect=1#comment421548_174922))* *-6 bytes: switched returns to use variable, initialized b and c outside of loops (thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/questions/174907/is-this-number-secretly-fibonacci/174922?noredirect=1#comment421559_174922))* *-17 bytes: changed condition in second loop to move if out of loop and combine with return, reused b and c variables in last loop (thanks to [raznagul](https://codegolf.stackexchange.com/questions/174907/is-this-number-secretly-fibonacci/174922?noredirect=1#comment421577_174922))* Ungolfed: ``` a => { int n = 0, b, c; // initialize variables for(; a > 0; a -= b, n++) // increase n until a is 0 for(b = c = 1; c <= a; b = c - b) // set b and c to 1 for each a; set second largest Fibonacci number until largest Fibonacci number reaches a c += b; // set largest Fibonacci number of current sequence for(b = c = 1; c < n; c += b) // while e is less than or equal to n, continue incrementing largest (e) Fibonacci number in the sequence b = c - b; // increment second-largest (d) Fibonacci number return c == n; // if c equals n, a is a secret Fibonacci number } ``` [Answer] # [Perl 6](http://perl6.org/), 58 bytes ``` {(1,&[+]...*>$_)∋($_,{$^n-(1,&[+]...^*>$n).tail}...0)-1} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/WsNQRy1aO1ZPT0/LTiVe81FHt4ZKvE61SlyeLkIqDiiXp6lXkpiZUwvkGmjqGtb@L06sVFBSiVewtVOoTlNQia9VUkjLL1Iw1FEw0lEw0VEwNdBRMDQBEsYGBgaWlkDaGCgIwkBJQ2OggKGhhYWBxX8A "Perl 6 – Try It Online") `1, &[+] ... * > $_` is just the Fibonacci sequence, stopped at a convenient non-infinite place (the input number). `$_, { $^n - (1, &[+] ...^ * > $n).tail } ... 0` is a sequence of numbers, starting with the input number, and each successive element obtained by subtracting the largest Fibonacci number less than or equal to the previous element from the previous element. The sequence terminates when `0` is reached. For example, if `$_` is `140`, then this sequence is `140, 51, 17, 4, 1, 0`. Subtracting one from this sequence treats it as a number, its length, and the difference is the number of Fibonacci numbers which, added together, give the input number. Then this number is checked for membership in the first Fibonacci sequence. [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 48 bytes ``` {4>($_,{$_,{$_-(1,&[+]...*>$_)[*-2]}...^0}...1)} ``` [Try it online!](https://tio.run/##JYlBCoMwFET3PcUgQdTGkG/SEinmImJDF83K0mJXEnL29EsX84Z583lu67W8dtQRE0qyvhFBpn/6hmQ9nxelVOdFaOeuH5bM664PUpvL7fR97KhEwOSRIkTIFeJ7A0kMElbioiXIMozWehy5DcsjfJJhQeScduUH "Perl 6 – Try It Online") Transforms the input to a list of Zeckendorf Representation repeatedly until it reaches a single number and then checks if the length of the sequence was less than 4. The Zenckendorf function in the middle is mostly from [Sean's answer](https://codegolf.stackexchange.com/a/174924/76162) with a couple of improvements. ### Explanation: ``` {4>($_,{$_,{$_-(1,&[+]...*>$_)[*-2]}...^0}...1)} { } # Anonymous code block ... # Define a sequence: $_ # That starts at the input ,{ } # Each element is defined by: ... # Another sequence that: $_, # Starts at the previous element $_- # The previous element minus 1,&[+]...* # The Fibonacci sequence >$_ # Ending when it is larger than the previous element ( )[*-2] # The second from last element { }...^0 # Run until 0, discarding the last element # This returns the length of the Zeckendorf Representation ...1 # Run this until it is length 1 4>( ) # Return true if the length of the sequence is smaller than 4 ``` For example, the sequence for `2` is `2 1` since `2` is already a Fibonacci number. The sequence for `140` is `140 5 1`, and since 5 is a Fibonacci number this returns true. The sequence for `33` is `33 4 2 1`, and since `4` is not a Fibonacci number the sequence is of length 4. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 14 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ΔDÅFθ-¼}¾ÅF¾<å ``` [Try it online](https://tio.run/##yy9OTMpM/f//3BSXw61u53boHtpTe2gfkHlon83hpf//G5oYAAA). No test suite for all test cases, because the `counter_variable` cannot be reset to 0.. I verified all by hand though, and they are correct. **Explanation:** ``` Δ } # Loop until the top of the stack no longer changes D # Duplicate the top of the stack # (implicitly the input in the first iteration) ÅF # Get a list of all Fibonacci numbers lower than this number θ # Get the last item (largest one) - # Subtract it from the number ¼ # Increase the counter_variable by 1 every iteration ¾ # After the loop, push the counter_variable ÅF # Get all Fibonacci numbers below this counter_variable ¾< # Push the counter_variable again, and subtract 1 å # Check if this value is in the list of Fibonacci numbers # (and output implicitly) ``` NOTE: The `counter_variable` would be `5` for input `139` and `6` for input `140`, because in order for the `Δ`-loop to check the stack remained the same, it does of course an additional iteration. [Answer] # [Haskell](https://www.haskell.org/), 64 bytes ``` s=(<2).r.r f=1:scanl(+)1f r 0=0 r z=1+r(z-last(takeWhile(<=z)f)) ``` [Try it online!](https://tio.run/##ZYqxDoMgFAB3voLBAeKreU80kQb6Gx0aB9JqNFLagBM/T9l7udx0m0vH4n0pyQrTyy52ka2WrunpghetpJVFjhZrs6U2inzxLp3idMdy33a/CGOzXKUsb7cHbvnrw3jlG/dw8oYn09weBD0MMCLQgKAQUev5/1IKxuoApDQQTRNOc/kB "Haskell – Try It Online") [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 61 bytes ``` .+ $* M`((?>\2?)(\1|\G.))*..|. .+ $* ^(((?>\3?)(\2|^.))*.)?.$ ``` [Try it online!](https://tio.run/##Jcm7CoQwEEbh/n8OhYnCMJOJEBtTWu0bBHGLLWwsxDLvHi/bHA58x@/c9m9taV4r92g6fFaiNGWfHGUteWbnOubC@PNCL9vDviyvusRNrQqPADMMguFugNoIDQITkfFejVHiBQ "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` .+ $* ``` Convert to unary. ``` M`((?>\2?)(\1|\G.))*..|. ``` Count the number of Fibonacci numbers needed. The first alternation deals with Fibonacci numbers that are at least 2. On the first pass, `\2` does not exist yet, but fortunately it's optional, so we don't have to match it. `\1` doesn't exist either, but fortunately we have the alternative of `\G.` which matches a single character at the start of the match. Both `\2` and `\1` therefore take on the value 1. On subsequent passes, `\2` exists, so we try to match it. This time if it fails then `\1` also fails (since it is bigger than `\2`), but if it succeeds, the `(?>)` prevents backtracking, so if `\2` matches but `\1` does not we don't try just `\1`. (`\G1` always fails since we've advanced past the start of the patch.) Finally `\2` takes on the previous value of `\1` while `\1` takes on the sum of the two values. We therefore match as many Fibonacci numbers as we can, adding as we go. Since the partial sums of the sequence `1, 2, 3, 5...` are `0, 1, 3, 6, 11...` i.e. 2 less than the Fibonacci numbers we finish by matching 2 at the end. This obviously fails to match 1 itself so an alternation handles that case. ``` .+ $* ``` Convert to unary. ``` ^(((?>\3?)(\2|^.))*.)?.$ ``` Test whether this is a Fibonacci number. This uses the same idea as the first test but it uses `^` instead of `\G` and we also need to match exactly, so it uses an optional capture instead of an alternation as that's golfier (but it increases the capture numbers by 1). # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 35 bytes ``` .+ * 2}C`((?>\2?)(\1|\G.))*..|. ^1$ ``` [Try it online!](https://tio.run/##DcaxCoAgEAbg/X@OgrPguFMDXWpo8CUkbGhoaYhGe3Zr@fju4zmvXVtPlErjEQPsuxaiZc52MZS15sTGDMyVsWnXmsLCwzlMgunXQ12EeoETkfhXQ5DwAQ "Retina – Try It Online") Link includes test cases. Explanation: ``` .+ * ``` Convert to unary. ``` C`((?>\2?)(\1|\G.))*..|. ``` Count the number of Fibonacci numbers needed. (Looping both the conversion and count saves a whole byte over getting the count in unary in the first place.) ``` 2} ``` Perform the previous steps twice in total. This takes the count of Fibonacci numbers needed to sum to the count of Fibonacci numbers. ``` ^1$ ``` If the number was secretly Fibonacci then the result is 1. [Answer] # [Python 2](https://docs.python.org/2/), ~~146~~ 137 bytes ``` lambda a:len(g(len(g(a))))<2 f=lambda n:n<3or f(n-2)+f(n-1) def g(a,n=1):j=f(n-1);return[j]if a-j<1else[j]+g(a-j)if a-f(n)<0else g(a,n+1) ``` [Try it online!](https://tio.run/##bY3BDoIwDIbP7ikaTiyMZGOawISrT@BNPcy4CQSqmXDw6bGI8WBc0r9d@/fr/TnUN8ymujpOne3PFwvWdA7ja7yo5fTKjPnqM0aDpb4F8DGmGU/mpDi7OA9kFlgpbtpq6W6DG8aAh/bUeLBpWyrXPRx9E7KmLX93ycpLOQ8WQKL4dA8NDhDtwzjUTxMxT/dw7KFBOCgBmYC1gI0UoNYkWkpZFCfDVsseOQXUMSXO2AcVfaudpVO/UK2JNwdxlS5IVJ7L/C9zegE "Python 2 – Try It Online") f() is a recursive function that returns the value of the nth Fibonacci number. Taken from [this answer](https://codegolf.stackexchange.com/a/131578/73368). g() is a recursive function that returns the Zeckendorf Representation of the given number as a list of integers. Since all Fibonacci numbers will have a return length of one item from g(), h() checks if the length of the g() of g(n) == 1. **EDIT:** Saved 9 bytes thanks to [nedla2004](https://codegolf.stackexchange.com/users/59363/nedla2004). I keep forgetting that lambdas aren't always the best solution... [Answer] # [Husk](https://github.com/barbuz/Husk), 16 bytes ``` £İf←LU¡λ≠⁰→↑≤⁰İf ``` [Try it online!](https://tio.run/##yygtzv7//9DiIxvSHrVN8Ak9tPDc7kedCx41bnjUNulR28RHnUuAbKDs////DY0tAQ "Husk – Try It Online") ]
[Question] [ Define the "maximum sub-array" of a given array as "a (consecutive) sub-array that has the biggest sum". Note there's no "non-zero" requirement. Output that sum. Give a description of your code if possible. Sample input 1: ``` 1 2 3 -4 -5 6 7 -8 9 10 -11 -12 -13 14 ``` Sample output 1: `24` Description 1: The biggest sum is yielded by cutting `6 7 -8 9 10` out and summing up. Sample input 2: `-1 -2 -3` Sample output 2: `0` Description 2: It's simple :) An empty subarray is the "biggest". Requirement: * Don't read anything except stdin, and output should go to stdout. * Standard loopholes **restrictions** apply. Ranking: The shortest program wins this [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). [Answer] # [Husk](https://github.com/barbuz/Husk), ~~6~~ 4 bytes ``` ▲ṁ∫ṫ ``` [Try it online!](https://tio.run/##yygtzv7//9G0TQ93Nj7qWP1w5@r///9HG@oY6Rjr6Jro6JrqmOmY6@ha6FjqGBro6BoaArEREBvrGJrEAgA "Husk – Try It Online") ``` -- implicit input (list) xs - eg. [-1,2,3] ṫ -- get all tails of xs - [[-1,2,3],[2,3],[3],[]] ṁ∫ -- map & concat cumsum - [0,-1,1,4,0,2,5,0,3,0] ▲ -- get maximum - 5 ``` [Answer] # [Python 3](https://docs.python.org/3/), 61 bytes ``` a=b=0 for x in eval(input()):a=max(x,a+x);b=max(a,b) print(b) ``` [Try it online!](https://tio.run/##HcdNCoMwEAbQvafIMkO/gGPsnyUnkS4moDTQxiBpiadPxcVbvLTl1xJtreK8a5t5WVVRIarpJ28dYvpmTTSI@0jRBXIq9PBHBJ6atIaYtadaR0YHC9PDnHHBFeaGO7iFYd51Owvun38 "Python 3 – Try It Online") Algorithm stolen from [Wikipedia](https://en.wikipedia.org/wiki/Maximum_subarray_problem). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes ``` ẆS€;0Ṁ ``` [Try it online!](https://tio.run/##y0rNyan8///hrrbgR01rrA0e7mz4//9/tK6hjq6Rjq5xLAA "Jelly – Try It Online") [Answer] # [Pyth](https://pyth.readthedocs.io), 8 bytes ``` eS+0sM.: ``` **[Try it online!](http://pyth.herokuapp.com/?code=eS%2B0sM.%3A&input=%5B-1%2C+-2%2C+-3%5D%0A%5B1%2C+2%2C+3%2C+-4%2C+-5%2C+6%2C+7%2C+-8%2C+9%2C+10%2C+-11%2C+-12%2C+-13%2C+14%5D&test_suite=1&test_suite_input=%5B-1%2C+-2%2C+-3%5D%0A%5B1%2C+2%2C+3%2C+-4%2C+-5%2C+6%2C+7%2C+-8%2C+9%2C+10%2C+-11%2C+-12%2C+-13%2C+14%5D&debug=0)** --- # How? ``` eS+0sM.:Q - Q is implicit, meaning input. Let's say it's [-1, -2, -3]. .: - All contiguous non-empty sublists. We have [[-1], [-2], [-3], [-1, -2], [-2, -3], [-1, -2, -3]]. sM - Get the sum of each sublist. [-1, -2, -3, -3, -5, -6] +0 - Append a 0 to the sum list. [0, -1, -2, -3, -3, -5, -6] eS - Maximum element. S gives us [-6, -5, -3, -3, -2, -1, 0], while e returns 0, the last element. ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes ``` ÎŒ0M ``` [Try it online!](https://tio.run/##MzBNTDJM/f//cN/RSQa@//9H6xrrKOgaAbFhLAA "05AB1E – Try It Online") -1 thanks to [Adnan](https://codegolf.stackexchange.com/users/34388/adnan). [Answer] # [Haskell](https://www.haskell.org/), 28 bytes ``` maximum.scanl((max<*>).(+))0 ``` [Try it online!](https://tio.run/##FYrLCsIwFER/ZRYuEr0tvbU@CtYfURchGA0mITQKfr3xdjGHM8w8TXndQ6huutZovj5@YlusSUEpqaf1Wbdqo3Uno0@YkGef3ljB4cKEnrAlNINkR9gTDmJHwkjgTpR5Qb9Afjzc6s@6YB6lNjbnPw "Haskell – Try It Online") [Answer] ## C++, ~~197~~ ~~195~~ 187 bytes -10 bytes thanks to Zacharý ``` #include<vector> #include<numeric> int f(std::vector<int>v){int i=0,j,t,r=0;for(;i<v.size();++i)for(j=i;j<v.size();++j){t=std::accumulate(v.begin()+i,v.begin()+j,0);if(t>r)r=t;}return r;} ``` [Answer] # [R](https://www.r-project.org/), 54 bytes ``` a=b=0;for(x in scan()){a=max(x,a+x);b=max(a,b)};cat(b) ``` [Try it online!](https://tio.run/##HcdNCoAgEAbQ/XeKlg4lOPaPeJgxCFpkUC2E6OwmLd7inTmLD9649ThVqrZYXYtERfSI3yWp1EidyIU/0gR63SK3CpQZFi10B91jwAg9YQYbaObCFi24yx8 "R – Try It Online") Algorithm taken from: [Maximum subarray problem](https://en.wikipedia.org/wiki/Maximum_subarray_problem) # [R](https://www.r-project.org/), 65 bytes ``` y=seq(x<-scan());m=0;for(i in y)for(j in y)m=max(m,sum(x[i:j]));m ``` [Try it online!](https://tio.run/##K/r/v9K2OLVQo8JGtzg5MU9DU9M619bAOi2/SCNTITNPoVITxMyCMHNtcxMrNHJ1iktzNSqiM62yYkHK/xtyGXEZc@macOmacplxmXPpWnBZchkacOkaGgKxERAbcxma/AcA "R – Try It Online") * Read `x` from stdin. * Set `y` as index of `x`. * Iterate twice over all possible nonempty subsets. * Compare sum of a subset with `m` (initially `m=0`). * Store maximum value in `m`. * Print value of `m`. # [R](https://www.r-project.org/), 72 bytes ``` n=length(x<-scan());m=0;for(i in 1:n)for(j in i:n)m=max(m,sum(x[i:j]));m ``` [Try it online!](https://tio.run/##K/r/P882JzUvvSRDo8JGtzg5MU9DU9M619bAOi2/SCNTITNPwdAqTxPEyQJxMoGcXNvcxAqNXJ3i0lyNiuhMq6xYkJb/hlxGXMZcuiZcuqZcZlzmXLoWXJZchgZcuoaGQGwExMZchib/AQ "R – Try It Online") * Read `x` from stdin. * Do a full search over all possible nonempty subsets. * Compare sum of a subset with `m` (initially `m=0`). * Store maximum value in `m`. * Print value of `m`. # Other unsuccessful ideas ## 58 bytes ``` Reduce(max,lapply(lapply(seq(x<-scan()),tail,x=x),cumsum)) ``` ## 63 bytes ``` Reduce(max,lapply(seq(x<-scan()),function(i)cumsum(tail(x,i)))) ``` ## 72 bytes ``` m=matrix(x<-scan(),n<-length(x),n);max(apply(m*lower.tri(m,T),2,cumsum)) ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes -2 bytes thanks to Adnan ``` ÎŒOM ``` [Try it online!](https://tio.run/##MzBNTDJM/f//cN/RSf6@//9H6xrqKOgaAbFxLAA "05AB1E – Try It Online") [Answer] # Mathematica, 24 bytes ``` Max[Tr/@Subsequences@#]& ``` [Answer] # [Haskell](https://www.haskell.org/), 41 33 bytes ``` import Data.List g=maximum.concatMap(map sum.inits).tails ``` ``` maximum.(scanl(+)0=<<).scanr(:)[] ``` [Try it online!](https://tio.run/##FcxLDoIwGEXhuau4IQ4gpoQCvggswDUggz9QC7GtTYuP1Vvr4AzO5JvJ34VSQXbXoOmz6KfOUz@SUekuK7q2zfL/ubTJ@iG8yKGDJgsnaMIW74ebPBKOEhVYDbbHAUewE87gBRjnsTJWgdcJmgb9xaxCCjdsNC0matYtZo2URNTDd7wpkj6w0dof "Haskell – Try It Online") thanks to Laikoni [Answer] # [Gaia](https://github.com/splcurran/Gaia), 6 bytes ``` 0+ḋΣ¦⌉ ``` [Try it online!](https://tio.run/##S0/MTPz/30D74Y7uc4sPLXvU0/k/9VHbxP/RuoYKukYKusaxAA "Gaia – Try It Online") [Answer] # [k](https://en.wikipedia.org/wiki/K_(programming_language)), 14 bytes ``` |/,/+\'(1_)\0, ``` [Try it online!](https://tio.run/##y9bNz/7/P82qRl9HXztGXcMwXjPGQOd/moOelYFVwn9DBSMFYwVdEwVdUwUzBXMFXQsFSwVDAwVdQ0MgNgJiYwVDEwA "K (oK) – Try It Online") ``` 0, /prepend a zero (in case we're given all negatives) (1_)\ /repeatedly remove the first element, saving each result +\' /cumulative sum over each result, saving each result ,/ /flatten (fold concat) |/ /maximum (fold max) ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 11 bytes ``` £ãY mxÃc rw ``` [Try it online!](http://ethproductions.github.io/japt/?v=1.4.5&code=o+NZIG14w2Mgcnc=&input=WzEsIDIsIDMsIC00LCAtNSwgNiwgNywgLTgsIDksIDEwLCAtMTEsIC0xMiwgLTEzLCAxNF0=) ## Explanation ``` £ãY mxÃc rw m@ãY mx} c rw // Ungolfed m@ } // Map the input array by the following function, with Y=index ãY // Get all subsections in input array length Y mx // Sum each subsection c rw // Flatten and get max ``` ## Alternate method, 11 bytes From @ETHproductions; based on [Brute Forces' Husk answer](https://codegolf.stackexchange.com/a/138700/69583). ``` £sY å+Ãc rw ``` Gets all tails of the input array and cumulatively sums each. Then flattens the array and gets the max. [Try it online!](http://ethproductions.github.io/japt/?v=1.4.5&code=o3NZIOUrw2Mgcnc=&input=WzEsIDIsIDMsIC00LCAtNSwgNiwgNywgLTgsIDksIDEwLCAtMTEsIC0xMiwgLTEzLCAxNF0=) [Answer] # Ruby, ~~61~~ ~~59~~ 57 bytes I just started learning Ruby, so this is what I came up with. ``` s=0 p [gets.split.map{|i|s=[j=i.to_i,s+j].max}.max,0].max ``` I first saw this algorithm at the Finnish version of [this unfinished book](https://cses.fi/book.pdf). It is very well explained at the page 23. [Try it online!](https://tio.run/##KypNqvz/v9jWgKtAITo9taRYr7ggJ7NELzexoLoms6bYNjrLNlOvJD8@U6dYOysWKF5RCyJ0DMDs//8NFYwUjBV0TRR0TRXMFMwVdC0ULBUMDRR0DQ2B2AiIjRUMTQA) [Answer] # JavaScript, 58 bytes ``` m=Math.max;x=y=>eval("a=b=0;for(k of y)b=m(a=m(a+k,k),b)") ``` Golfed JS implementation of Kadane's algorithm. Made as short as possible. Open to constructive suggestions! **What I learnt from this post:** return value of `eval` - when its last statment is a `for` loop - is basically the last value present *inside* the loop. Cool! **EDIT:** saved four bytes thanks to Justin's and Hermann's suggestions. [Answer] # J, 12 bytes ``` [:>./@,+/\\. ``` Similar to zgrep's K solution: the scan sum of all suffixes (produces a matrix), raze, take max [Try it online!](https://tio.run/##LYxBCsIwFET3OcXDTRFL2p/EqoGI97DwF2IQNy669uwxqV0MDDNv5l3yQoqMVJV7vNrh1h@GebZlb3aWLqfY0fON5MWY5@P1YYJERh2CegIqrP5I@BMurESLPRpaM3FCz1yQsfIVFlflkW0ybqfSftWXHw "J – Try It Online") ### NOTE for not too many more bytes, you can get an efficient solution (19 bytes golfed): ``` [: >./ [: ({: - <./)\ +/\ ``` [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-h`](https://codegolf.meta.stackexchange.com/a/14339/), 4 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ãx ñ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWg&code=43gg8Q&input=WzEgMiAzIC00IC01IDYgNyAtOCA5IDEwIC0xMSAtMTIgLTEzIDE0XQ) ``` ãx ñ :Implicit input of array ã :Sub-arrays x :Reduced by addition ñ :Sort :Implicit output of last element ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~52~~ 51 bytes ``` f=lambda l:len(l)and max(sum(l),f(l[1:]),f(l[:-1])) ``` [Try it online!](https://tio.run/##PYzNCsIwEITvPkWPG5gFN6l/AZ@k9BCpQWETi1bQp48rgoeBGT6@md/L5VZ9a/moqZym1GnUcyV1qU5dSS96PIstZNJB4vgrkWV0rs33a10o0yDwCOAevMEWO/AeB8gaLGLxlgDpTVn9FTZiIHx/Pg "Python 2 – Try It Online") [Answer] # Common Lisp, 73 bytes ``` (lambda(a &aux(h 0)(s 0))(dolist(x a s)(setf h(max x(+ h x))s(max s h)))) ``` [Try it online!](https://tio.run/##HYpRCsIwEESvMl86QQLdtmo9ztYqKbRaTIS9fVw78AZmePdlzlvl9plfBaxcdB0npeKgX2NCE5i9Aqe3m4UGRfbvUZ5IXNVgPCHBQsj7zEjBU48UtOgQe8QzLrgiDrhBGkQRp3U6SP93fw) [Answer] # APL, ~~31~~ ~~29~~ 27 bytes ``` ⌈/∊∘.{+/W[X/⍨⍺≤X←⍳⍵]}⍨⍳⍴W←⎕ ``` [Try it online!](http://tryapl.org/?a=%7B%u2308/%u220A%u2218.%7B+/W%5BX/%u2368%u237A%u2264X%u2190%u2373%u2375%5D%7D%u2368%u2373%u2374W%u2190%u2375%7D1%202%203%20%AF4%20%AF5%206%207%20%AF8%209%2010%20%AF11%20%AF12%20%AF13%2014&run) (modified so it will run on TryAPL) ## How? * `∊∘.{+/W[X/⍨⍺≤X←⍳⍵]}⍨⍳⍴W←⎕` Generate sums of subvectors * `⌈/` Maximum [Answer] # CJam, 24 bytes ``` q~:A,{)Aew{:+}%}%e_0+:e> ``` Function that takes array of numbers as input. [Try it Online](http://cjam.aditsu.net/#code=q~%3AA%2C%7B)Aew%7B%3A%2B%7D%25%7D%25e_0%2B%3Ae%3E&input=%5B1%202%203%20-4%20-5%206%207%20-8%209%2010%20-11%20-12%20-13%2014%5D) ``` q~:A e# Store array in 'A' variable ,{)Aew e# Get every possible sub-array of the array {:+}% e# Sum every sub array }e_ e# flatten array of sums 0+ e# Add zero to the array :e> e# Return max value in array ``` [Answer] # [MY](https://bitbucket.org/zacharyjtaylor/my-language/src/031637f7e827bde8c06b68ddaf39d9773476667a?at=master), 11 bytes ``` ⎕𝟚35ǵ'ƒ⇹(⍐↵ ``` [Try it online!](https://tio.run/##y638//9R39QPc@fPMjY9vlX92KRH7Ts1HvVOeNS29f//aEMdIx1jHV0THV1THTMdcx1dCx1LHUMDHV1DQyA2AmJjHUOTWAA) MY is on TIO now! Woohoo! ## How? * `⎕` = evaluated input * `𝟚` = subvectors * `35ǵ'` = `chr(0x53)` (Σ, sum) * `ƒ` = string as a MY function * `⇹` = map * `(` = apply * `⍐` = maximum * `↵` = output with a newline. Sum was fixed (`0` on empty arrays) in order for this to work. Product was also fixed. [Answer] # Axiom, 127 bytes ``` f(a:List INT):Complex INT==(n:=#a;n=0=>%i;r:=a.1;for i in 1..n repeat for j in i..n repeat(b:=reduce(+,a(i..j));b>r=>(r:=b));r) ``` This would be O(#a^3) Algo; I copy it from the C++ one... results ``` (3) -> f([1,2,3,-4,-5,6,7,-8,9,10,-11,-12,-13,14]) (3) 24 Type: Complex Integer (4) -> f([]) (4) %i Type: Complex Integer (5) -> f([-1,-2,3]) (5) 3 Type: Complex Integer ``` [Answer] # Scala, 105 bytes ``` val l=readLine.split(" ").map(_.toInt);print({for{b<-l.indices;a<-0 to b+2}yield l.slice(a,b+1).sum}.max) ``` I didn't find any better way to generate the sublists arrays. [Answer] # Java 8, 242 bytes ``` import java.util.*;v->{List a=new Stack();for(String x:new Scanner(System.in).nextLine().split(" "))a.add(new Long(x));int r=0,l=a.size(),i=l,j,k,s;for(;i-->0;)for(j=l;--j>1;r=s>r?s:r)for(s=0,k=i;k<j;)s+=(long)a.get(k++);System.out.print(r);} ``` [Try it here.](https://tio.run/##LVBdTwIxEHznV0x8auVaOMUvavEPoDEx8cX4UI@CvSu9S7uHqOG3Y0GSTrqdZndnpjYbI9rOhnrR7N26ayOhzpzsyXl5rgCMRng2mW6XoE@Lj2@yomr7QINB5U1KeDQu/A4AF8jGpaksng5PYNO6BSr2erg2XGVul5FPIkOuwhMCNPYbMfudu0QwOtgvvJCpGsbVso3shaILK2ynx4/KhGAz@Z3IrqULXAa7pbkLlnGZOu@IneGMcyPNYsEOLfM2rNiWc5W1Iepx4bWRyf3khsJpX9RFU6TjJuWEmI0VP9S19kqIelaqqNMsPqRpPPIpD2i0U819rXgaaubz@LxtZYk1wyFXJ2VtT7LLwolFrnZ79W@66z98Nn3yfsxmnZM7eXx7h@H/sQVZsdB7f0psty9xgUuICcQVrnEDcYs7lGOIssy4yLhEOfkD) # 106 bytes without using STDIN/STDOUT requirement.. >.> ``` a->{int r=0,l=a.length,i=l,j,k,s;for(;i-->0;)for(j=l;--j>1;r=s>r?s:r)for(s=0,k=i;k<j;s+=a[k++]);return r;} ``` [Try it here.](https://tio.run/##jU/LboMwELznK/YIYo0wkFdd0y9oLjlGObjESQ3ERLaTqor4droh@YBKHss769nZadRNsf6ibXNox7pT3sOnMvY@AzA2aHdUtYbNo5wIqCO6d3tQsSBuINDxQQVTwwYsSBgVq@6Pr05m2EmVdtqewjca2WGDLXpx7F0kDGNVJuLHu5GdYKypuHDSV@7Dv7mJ9zSglUa0743wiVS7Nkn2sXA6XJ0FJ4ZRPP0v16@O/F9r3HpzgDOFiLbBGXuatn0m2P76oM9pfw3phVqhs5FN68jqH5hi3TnmWCArkc1xgUtkK1wjz5BxTsgJBfJyiKf0/5jHSEaq4qUYZsPIIYcCWAlsDgtYAlvBGngGZEHICQXw8g8) **Explanation:** ``` import java.util.*; // Required import for List, Stack and Scanner v->{ // Method with empty unused parameter and no return-type List a=new Stack(); // Create a List for(String x:new Scanner(System.in).nextLine().split(" ")) // Loop (1) over the STDIN split by spaces as Strings a.add(new Long(x)); // Add the String converted to a number to the List // End of loop (1) (implicit / single-line body) int r=0, // Result-integer l=a.size(), // Size of the List i=l,j,k, // Index-integers s; // Temp sum-integer for(;i-->0;) // Loop (2) from `l` down to 0 (inclusive) for(j=l;--j>1; // Inner loop (3) from `l-1` down to 1 (inclusive) r= // After every iteration: change `r` to: s>r? // If the temp-sum is larger than the current `r`: s // Set `r` to the temp-sum : // Else: r) // Leave `r` the same for(s=0, // Reset the temp-sum to 0 k=i;k<j;) // Inner loop (4) from `i` to `j` (exclusive) s+=(long)a.get(k++); // Add the number at index `k` in the List to this temp-sum // End of inner loop (4) (implicit / single-line body) // End of inner loop (3) (implicit / single-line body) // End of loop (2) (implicit / single-line body) System.out.print(r); // Print the result to STDOUT } // End of method ``` ]
[Question] [ [MATL](https://esolangs.org/wiki/MATL) is a golfing language created by [Luis Mendo](https://codegolf.stackexchange.com/users/36398/luis-mendo). MATL has proven to be highly competitive, often [beating](https://codegolf.stackexchange.com/a/75002/31516) submissions in other golfing languages such as Pyth, CJam and Jelly. What are some useful tips for golfing in MATL? (As always, one tip per answer, please!) * For the record, MATL can be [tested online here](http://matl.tryitonline.net). * Documentation can be found on [Github](https://github.com/lmendo/MATL) [Answer] # Know the predefined literals Although some of them keep information when copied to the clipboard, they all have a predefined value. * [`F`](http://matl.tryitonline.net/#code=Rg&input=), pushes **0** (actually *False*) * [`T`](http://matl.tryitonline.net/#code=VA&input=), pushes **1** (actually *True*) * [`H`](http://matl.tryitonline.net/#code=SA&input=), pushes **2** (predefined clipboard value) * [`I`](http://matl.tryitonline.net/#code=SQ&input=), pushes **3** (predefined clipboard value) * [`K`](http://matl.tryitonline.net/#code=Sw&input=), pushes **4** (predefined clipboard value) * [`J`](http://matl.tryitonline.net/#code=Sg&input=), pushes **0 + 1j** (predefined clipboard value) Not sure if I have covered all predefined values though. [Answer] # The `&` Meta-Function (Alternative Input / Output Specification) The traditional way to specify the number of input arguments to pass to a function is to use the `$` meta-function ``` 2$: % Two-input version of : ``` Similarly, to specify the number of output arguments you can use the `#` meta-function specifying either the number of output arguments, ``` 2#S % Two-output version of sort ``` or if you pass a number that is *greater than* the number of output arguments defined for a function, *only* the `mod(N, numberOfOutputs) + 1` output is supplied. ``` 4#S % Get only the second output of sort ``` You can additionally specify a logical array as the input to `#` to retrieve only specific output arguments. ``` TFT#u % Three output version of unique and discard the second output ``` All of these input / output specifications are handy *but* they drive up your byte-count very quickly. To deal with this, MATL introduced the `&` meta-function in the [17.0.0 release](https://github.com/lmendo/MATL/releases/tag/17.0.0). This `&` meta-function acts as a shortcut for a particular input or output specification for a function. Let's see what that means. In our example above, we wanted to use the two-input version of `:` (creates a vector of equally-spaced values). While the default number of input arguments to `:` is `1` (creates an array from `[1...N]`), it is *very* common that a user would want to specify the start value of the range which requires the second input. So for `:`, we have defined `&` to be a shortcut for `2$`. ``` 10 % Push 10 to the stack 12 % Push 12 to the stack 2$: % Create an array: [10, 11, 12] ``` Now becomes the following, *saving a byte*! ``` 10 12 &: ``` ## How can we determine what the alternate number of arguments is? The input / output specification that `&` translates to is **function specific** such that we optimize the byte-savings. The input / output argument section of the help description for each function has been updated to indicate what this alternative number of inputs / outputs is (if any). The possible number of input or output arguments are displayed as a range and the default values for each are shown in parentheses. The input / output spec that can be substituted with `&` is shown after the `/` character within the parentheses. Here is the input / output argument section of the help description for `:` ``` +- Min-Max range of # of inputs | +----- Alt. Default # of inputs | | V V 1--3 (1 / 2); 1 <--- Possible / Default # of outputs ^ | Default # of inputs ``` ## How did you determine what `&` means for each function? Very carefully. Using the [StackExchange API](https://api.stackexchange.com/), we were able to download all MATL answers that have ever been used in a PPCG challenge. By parsing each of the answers, we were then able to determine the frequency with which each input / output spec was used for each function. Using this information we were then able to objectively identify the input / output specification the `&` meta-function should represent for each function. Sometimes there was no clear winner, so many functions currently don't have `&` defined. [Here is the script we used (unfortunately it's written in MATLAB and *not* MATL).](https://gist.github.com/suever/157afa5d6407b14fc7f9f481050133d8) And here is an [example of the histogram](https://i.stack.imgur.com/zD5Pu.png) of `$`/`#` usage [Answer] # Move things from after the loop to within the loop, to exploit implicit end Loop `end` statements, `]`, can be **left out** if there is no code after them. They are filled by the MATL parser implicitly. So if you can move things from after the loop to within the loop you can to save the final `]`. As a specific example, the following code finds how many trailing zeros there are in the factorial of a number `N` (see it [here](https://codegolf.stackexchange.com/a/79780/36398)): * The code loops from `1` to `N`. * For each of those numbers it computes its prime factors, and determines how many times `5` is present. * The answer is the accumulated number of times `5` appears (this works because for each `5` there is at least one `2`). The first idea was `:"@Yf5=]vs` (note that there are statements after the loop): ``` : % Range from 1 to implicit input " % For each number in that vector @ % Push that number Yf % Vector of prime factors (with repetitions) 5= % True for entries that equal `5`, and `false` for the rest ] % End for v % Concatenate all vectors as a column vector s % Sum. Implicitly display ``` Since `v` by default concatenates all stack contents, it can be moved into the loop. And since addition is associative, `s` can be moved too. That leaves `]` at the end of the code, and thus it can be omitted: [`:"@Yf5=vs`](http://matl.tryitonline.net/#code=OiJAWWY1PXZz&input=MTAw): ``` : % Range from 1 to implicit input " % For each number in that vector @ % Push that number Yf % Vector of prime factors (with repetitions) 5= % True for entries that equal `5`, and `false` for the rest v % Concatenate all vectors so far as a column vector s % Sum. Inplicitly end loop and display ``` [Answer] # Get familiar with MATL's truthy/falsy definitions While `true` (`T`) and `false` (`F`) clearly represent truthy and falsy output, respectively, the [widely agreed upon definition of truthy/falsy](http://meta.codegolf.stackexchange.com/a/2194/51939) gives us a little bit more flexibility in MATL. The definition states: ``` if (x) disp("x is truthy"); else disp("x is falsy"); end ``` So we can write a quick MATL truthy/falsy test which will loop through all inputs and display whether they were considered to be truthy or falsy ``` ` ? 'truthy' } 'falsey' ]DT ``` [Here is an online version.](https://matl.suever.net/?code=%60%0A%3F%0A%27truthy%27%0A%7D%0A%27falsy%27%0A%5DDT%0A&inputs=1%0A0&version=19.2.0) **What this means in MATL** What this actually translates to in MATL (and therefore in MATLAB and Octave) is that a condition is considered to be true if **if it is non-empty and real components of all its values are non-zero**. There are two parts to this that should be emphasized. 1. **Non-zero**: This means precisely that, not equal to zero (`==`). This includes positive numbers, negative numbers, non-null characters, etc. You can easily check by converting a given value to a `logical` value (`g`) or you can use `~~` ``` F % Falsy T % Truthy 0 % Falsy 1 % Truthy 2 % Truthy -1 % Truthy 'a' % Truthy ' ' % Truthy (ASCII 32) char(0) % Falsy (ASCII 0) ``` 2. **All values**: Typically we think of scalars as being true or false, but in MATL, we can evaluate scalars, row vectors, column vectors, or even multi-dimensional matrices and they are considered to be truthy if and only if every single value is non-zero (as defined above), otherwise they are falsy. Here are a few examples to demonstrate ``` [1, 1, 1] % Truthy [1, 0, 0] % Falsey [1, 1, 1; 1, 1, 1] % Truthy [1, 0, 1; 1, 1, 1] % Falsey 'Hello World' % Truthy ``` The one edge case, as mentioned above, is an empty array `[]`, which is always considered to be falsy ([example](https://codegolf.stackexchange.com/questions/71698/to-be-or-not-to-be/71719#71719)) **How can I use this to golf better?** If the challenge simply mentions that your output should be truthy or falsy, you can likely exploit the definition above to shave a few bytes off of your answer. To save confusion, it is recommended that you include a link to the online truthy/falsy test above in your answer to help explain how MATL truthy/falsy values work. A couple of specific examples: * An answer ending in `A`. If the challenge requires a truthy or falsy output and you end your answer in `all` (`A`) to create a scalar, you can remove this last byte and your answer will remain correct (unless the output is `[]` since `[]` is `false` but `[]A` is `true`). * [Ensuring that an array contains only one unique value](https://codegolf.stackexchange.com/a/94963/51939): Uses `&=` in place of `un1=`. If all values in an array are equal, a broadcasted element-wise equality comparison will yield an `N x N` matrix of all ones. If all values are not equal, this matrix will contain some `0` values and therefore be considered falsy. [Answer] # Implicit Input Most functions accept some number of input. These inputs are taken from the top of the stack. If the top of the stack does not contain enough arguments, it will draw the remaining argument from the input. (See Section 7.3 in the documentation) I'd like to cite the original explanation: > > Implicit inputs can be viewed as follows: the stack is indefinitely extended below > the bottom, that is, at positions 0, −1, −2, ...with values that are not initially > defined, but are resolved on the fly via implicit input. These inputs are asked from > the user only when they are needed, in the order in which they are needed. If > several inputs are required at the same time they follow the normal stack order, > that is, the input that is deepest in the (extended) stack is entered first. > > > [Answer] # For loop of size n-1 Consider replacing ``` tnq:"... ``` with ``` td"... ``` to save up to an entire byte [or more](https://xkcd.com/870/). [Answer] # Logical arrays can often be used as numeric arrays You can often use "`TF`" notation instead of array literals of zeros and ones. For example, `FTF` is the same as `[0,1,0]`, only that `FTF` produces `logical` values, not `double` values. This is usually not a problem, as any arithmetical operation will treat logical values as numbers. For example, [`FTFQ`](http://matl.tryitonline.net/#code=RlRGUQ&input=) gives `[1,2,1]` (`Q` is "increase by 1"). In some cases, conversion of a number to binary may be shorter. For example, `[1,0,1]`, `TFT` and [`5B`](http://matl.tryitonline.net/#code=NUI&input=) are the same; again with the caution that the latter two are `logical` values. --- A case where the difference between `TF` (logical) and `[1 0]` (numeric) matters is when used as indices. An array of type `logical` used as an index means: pick elements corresponding to `T`, discard those corresponding to `F`. So [`[10 20]TF)`](http://matl.tryitonline.net/#code=WzEwIDIwXVRGKQ&input=) produces `10` (select the first element), whereas [`[10 20][1 0])`](http://matl.tryitonline.net/#code=WzEwIDIwXVsxIDBdKQ&input=) produces `[10 20]` (the index `[1 0]` has the interpretation of `1:end`, that is, pick all elements of the array). [Answer] # Some functions are extended compared with MATLAB or Octave If you come from MATLAB or Octave, you'll find many MATL functions are similar to functions in those languages. But in quite a few of them functionality has been extended. As an example, consider MATLAB's `reshape` function, which in MATL corresponds to `e`. The code snippets `reshape([10 20 30 40 50 60], 2, 3)` and `reshape([10 20 30 40 50 60], 2, [])` respectively mean "reshape the row vector `[10 20 30 40 50 60` into a 2×3 matrix", or "into a 2-row matrix with as many columns as needed". So the result, in both cases, is the 2D array ``` 10 30 50 20 40 60 ``` Something like `reshape([10 20 30 40 50 60], 2, 2)` or `reshape([10 20 30 40 50 60], 5, [])` would give an error because of incompatible sizes. However, MATL will remove elements in the first case ([try it online!](http://matl.tryitonline.net/#code=WzEwIDIwIDMwIDQwIDUwIDYwXUhIMyRl&input=)) or fill with zeros in the second ([try it online!](http://matl.tryitonline.net/#code=WzEwIDIwIDMwIDQwIDUwIDYwXTVl&input=)) to produce, respectively, ``` 10 30 20 40 ``` and ``` 10 60 20 0 30 0 40 0 50 0 ``` Other functions that have extended functionality in comparison with their MATLAB counterparts are (non-exhaustive list) `S` (`sort`), `Yb` (`strsplit`), `m` (`ismember`), `h` (`horzcat`), `v` (`vertcat`), `Zd` (`gcd`), `Zm` (`lcm`), `YS` (`circshift`), `YA` (`dec2base`), `ZA` (`base2dec`), `Z"` (`blanks`). [Answer] # Shorter way to define an empty numeric array, if the stack is empty To push an empty numeric array you normally use `[]`. However, if the stack is empty you can save a byte using `v`. This function by default concatenates all stack contents vertically, so if the stack is empty it produces the empty array. You can see it in action for example [here](https://codegolf.stackexchange.com/a/86018/36398). [Answer] # Get the index of the first non-zero element, if any The `f` function gives the indices of all non-zero elements of an array. Often you want the index of the *first* nonzero element. That would be `f1)`: apply `f` and pick its first element. But if the original array doesn't contain any non-zero value `f` will output an empty array (`[]`), and trying to pick its first element will give an error. A common, more robust requirement is to obtain the index of the first element *if there is at least one*, and `[]` otherwise. This could be done with an `if` branch after `f`, but that's byte-expensive. A better way is `fX<`, that is, apply the minimum function `X<` to the output of `f`. `X<` returns an empty array when its input is an empty array. [Try it online!](http://matl.tryitonline.net/#code=Zlg8&input=WzAgOCA3IDAgNV0) (Note that an empty array is not displayed at all). Or see an example of this at work [here](https://codegolf.stackexchange.com/a/77736/36398). [Answer] # Efficiently defining numeric array literals Here are a few ways that can be used to save bytes when defining numeric array literals. Links are given to example answers that use them. These have been obtained using the [analytics script](https://github.com/suever/matl-analytics) created by [@Suever](https://codegolf.stackexchange.com/users/51939/suever). ### Concatenation and predefined literals For arrays with small numbers you can sometimes use concatenation (functions `h` and `v`), as well as predefined literals to avoid using spaces as separators: compare `[2 4]`, `2 4h` and `2Kh`, all of which define the array `[2 4]`. Similarly, `2K1v` with an empty stack defines `[2; 4; 1]`. [Example](https://codegolf.stackexchange.com/a/105188/36398). ### Letters within numeric array literals For slightly larger numbers you can save spaces exploiting the fact that some letters have numeric meanings within array literals. So instead of `[3 5 2 7;-4 10 12 5]` you can use `[IAHC;dX12A]`. [Example](https://codegolf.stackexchange.com/a/157697/36398). Specifically, within array literals, * `O`, `l`, `H` `I` `K` have their usual meanings `0`, ..., `4` * `A`, ..., `E` mean `5`, ..., `9` * `X` means `10` * `a`, ... `d` mean `-1`, ..., `-4` * `J` and `G` mean `1j` and `-1j` * `P` means `pi` * `Y` means `inf` * `N` means `NaN`. ### String and consecutive differences For larger numbers, defining a string and computing its consecutive differences (with `d`) can help: instead of `[20 10 35 -6]` you can use `'!5?b\'d`. This works because `d` uses the code points of the chars for computing the differences. [Example](https://codegolf.stackexchange.com/a/103366/36398). [Answer] # Generate a range as long as a given array *TL;WR*: use `f` instead of `n:` if the array only has nonzero elements. --- It is often the case that one needs to generate an array `[1 2 ... L]` where `L` is the number of elements of a given array. The standard way to do that is `n:`. For example, the code [`tn:*`](https://matl.suever.net/?code=tn%3A%2a&inputs=%5B10+20+30%5D&version=20.2.2) takes a numeric vector as input and computes each entry multiplied by its index. If the given array is *guaranteed to only contain nonzero entries* (for example, it is formed by positive integers, or is a string with printable characters), `n:` can be replaced by `f`, which produces an array with the indices of nonzero entries. So the above code becomes [`tf*`](https://matl.suever.net/?code=tf%2a&inputs=%5B10+20+30%5D&version=20.2.2), which saves 1 byte. Some more elaborate examples: [1](https://codegolf.stackexchange.com/a/112963/36398), [2](https://codegolf.stackexchange.com/a/78407/36398), [3](https://codegolf.stackexchange.com/a/126478/36398). ]
[Question] [ The [Pareto Distribution](https://en.wikipedia.org/wiki/Pareto_distribution) is a probability distribution that comes up a lot in nature. It has lots of special properties, such as an infinite mean. In this challenge, you will output a number sampled from this distribution. The Pareto Distribution is defined to be greater than or equal to `x` with probability `1/x`, for all `x` greater than or equal to 1. Therefore, a number sampled from this distribution is greater than or equal to 1 with probability 1, greater than or equal to 2 with probability exactly 1/2, greater than or equal to 3 with probability exactly 1/3, greater than or equal to 11.4 with probability exactly 1/11.4, and so on. Since you will sample this distribution, your program or function will take no input, and output a random number, with the above probabilities. However, if your program doesn't perfectly match the above probabilities due to floating-point impression, that's OK. See the bottom of the challenge for more details. (This is called the Pareto Distribution with alpha 1 and lower bound 1, to be exact) Here's 10 example draws from this distribution: ``` 1.1540029602790338 52.86156818209856 3.003306506971116 1.4875532217142287 1.3604286212876546 57.5263129600285 1.3139866916055676 20.25125817471419 2.8105749663695208 1.1528212409680156 ``` Notice how 5 of them are below 2, and 5 are above 2. Since this is the average result, it could have been higher or lower, of course. Your answer only needs to be correct up to the limits of your floating point type, real number type, or whatever else you use, but you must be able to represent numbers at at least 3 decimal digits of precision, and represent numbers up to 1,000,000. If you're not sure whether something is OK, feel free to ask. This is code golf. --- Details about imprecision: * For each range `[a, b]`, where `1 <= a < b`, the ideal probability that the sample would fall in that range is `1/a - 1/b`. The probability that your program produces a number in that range must be with `0.001` of `1/a - 1/b`. If `X` is the output of your program, it is required that `|P(a <= X <= b) - (1/a - 1/b)| < 0.001`. * Note that by applying the above rule with `a=1` and `b` sufficiently large, it is the case that your program must output a number greater than or equal to 1 with at least probability 0.999. The rest of the time it may crash, output `Infinity`, or do whatever else. I'm fairly certain that the existing submissions of the form `1/1-x` or `1/x`, where `x` is a random float in `[0, 1)` or `(0, 1)` or `[0, 1]`, all satisfy this requirement. [Answer] # [MATL](https://github.com/lmendo/MATL), 3 bytes ``` 1r/ ``` [Try it online!](https://tio.run/##y00syfn/37BI//9/AA "MATL – Try It Online") Or [estimate the resulting probabilities](https://tio.run/##y00syflvaAAEVkr/DYv0/8eWGRpY2UXm/gcA) by running it 10000 times. ### Explanation ``` 1 % Push 1 r % Push random number uniformly distributed on the open interval (0,1) / % Divide. Implicitly display ``` [Answer] # [Actually](https://github.com/Mego/Seriously), 4 bytes ``` G1-ì ``` [Try it online!](https://tio.run/##S0wuKU3Myan8/9/dUPfwmv//AQ "Actually – Try It Online") Explanation: ``` G1-ì G random() 1- 1-random() ì 1/(1-random()) ``` [Answer] # R, 10 bytes ``` 1/runif(1) ``` Pretty straightforward. [Answer] # TI-Basic, 2 bytes ``` rand^-1 (AB 0C in hex) ``` For anyone who is wondering, `rand` returns a random value in (0,1]. "Due to specifics of the random number generating algorithm, the smallest number possible to generate is slightly greater than 0. The largest number possible is actually 1 ..." ([source](http://tibasicdev.wikidot.com/rand)). For example, seeding rand with 196164532 yields 1. [Answer] # [R](https://www.r-project.org/), 12 bytes ``` exp(rexp(1)) ``` [Try it online!](https://tio.run/##K/r/P7WiQKMIRBhqav7/DwA "R – Try It Online") [Verify the distribution](https://tio.run/##K/qfZ2toAAJcFTa6/1MrCjSKQESepub/tPwijUyFzDwFQytDA83kxBINpYAijQg7WyWdTB0lTSBVXJqrUWFnm6mpn6ejFJMHFEgtsFVS0vwPAA "R – Try It Online") This takes a different approach, exploiting [the fact](https://en.wikipedia.org/wiki/Pareto_distribution#Relation_to_the_exponential_distribution) that if `Y~exp(alpha)`, then `X=x_m*e^Y` is a Pareto with parameters `x_m,alpha`. Since both parameters are 1, and the default rate parameter for `rexp` is 1, this results in the appropriate Pareto distribution. While this answer is a fairly R- specific approach, it's sadly less golfy than [plannapus'](https://codegolf.stackexchange.com/a/150719/67312). # [R](https://www.r-project.org/), 14 bytes ``` 1/rbeta(1,1,1) ``` [Try it online!](https://tio.run/##K/r/31C/KCm1JFHDUAcINf//BwA "R – Try It Online") Even less golfy, but another way of getting at the answer. Another property of the exponential distribution is that if `X ~ Exp(λ) then e^−X ~ Beta(λ, 1)`, hence `1/Beta(1,1)` is a `Pareto(1,1)`. Additionally, a keen observer would recall that if `X ~ Beta(a,b)` and `a=b=1`, then `X~Unif(0,1)`, so this truly is `1/runif(1)`. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 10 bytes ``` I∕Xφ²⊕‽Xφ² ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwyWzLDMlVSMgvzy1SCNNR8FIU0dBW1sjKDEvJT8XWRgMrP///69blgMA "Charcoal – Try It Online") Link is to the verbose version: ``` Print(Cast(Divide(Power(f, 2), ++(Random(Power(f, 2)))))); ``` Comments: * Charcoal only has methods to get random integer numbers, so in order to get a random floating-point number between 0 and 1 we have to get a random integer between 0 and N and divide by N. * Previous version of this answer that used the `1/(1-R)` formula: In this case, N is set to 1000000 as the OP asks it to be the minimum. To get this number Charcoal provides a preset variable `f`=1000. So just calculating `f^2` we get 1000000. In the event that the random number is 999999 (the maximum), `1/(1-0.999999)=1000000`. * Neil's tip (saving 3 bytes): If I have `1/(1-R/N)` where `R` is a random number between 0 and N, it is the same as just calculate `N/(N-R)`. But considering that the random integers `N-R` and `R` have the same probability to occur, that is the same as just calculating `N/R` (being `R` in this last case a number between 1 and N inclusive to avoid division by zero). [Answer] # [Haskell](https://www.haskell.org/), ~~61~~ 56 bytes The function `randomIO :: IO Float` produces random numbers [in the interval](https://stackoverflow.com/a/47831399/2913106) `[0,1)`, so transforming them using `x -> 1/(1-x)` will produce pareto realizations. ``` import System.Random randomIO>>=print.(1/).((1::Float)-) ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/PzO3IL@oRCG4srgkNVcvKDEvJT@XKzcxM8@2CMz29Lezsy0oyswr0dMw1NfU09AwtLJyy8lPLNHU1fz/HwA "Haskell – Try It Online") [Answer] # Excel, 9 bytes ``` =1/rand() ``` Yay, Excel is (semi-)competitive for a change! [Answer] # Mathematica, 10 bytes ``` 1/Random[] ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b731A/KDEvJT83OvZ/QFFmXolD2n8A "Wolfram Language (Mathematica) – Try It Online") -4 bytes from M.Stern [Answer] # Ruby, ~~14~~ 8 bytes ``` p 1/rand ``` Trivial program, I don't think it can get any shorter. [Answer] # Excel VBA, 6 Bytes Anonymous VBE immediate window function that takes no input and outputs to the VBE immediate window ``` ?1/Rnd ``` [Answer] # [Python](https://python.org), 41 bytes ``` lambda:1/(1-random()) from random import* ``` [Try it online!](https://tio.run/##JYtBCoMwEADvvmKPu4WioTfBl7QiKUnagMmGNQp9fbricYaZ8qtfzo8WpldbbXo7O5oezV1sdpyQqAvCCS6EmApLvbXDrrvfYIJN0Tt8BiQILLBAzGf88WiGgWbd1Wp@@usaO4AiMVdUpvYH "Python 3 – Try It Online") --- Using the builtin is actually longer: # [Python](https://python.org), 43 bytes ``` lambda:paretovariate(1) from random import* ``` [Try it online!](https://tio.run/##JYtBCoQwDEX3niLL1pXiTvAkOgwZ2mrBNiVGYU5fI64@7/Ne@ctGeahhWuqO6edwLMhe6EKOKN70tglMCRiz04mpEEtbL9xPf8AEh6J3Zg7GQiCGL8T8yKumXWc/muur@vO/1dgAFI5ZjLKtNw "Python 3 – Try It Online") Both solutions work in both Python 2 and Python 3. [Answer] # [J](http://jsoftware.com/), 5 bytes ``` %-.?0 ``` ## How ot works: `?0` generates a random value greater than 0 and less than 1 `-.` subtract from 1 `%` reciprocal [Try it online!](https://tio.run/##y/qfbmulYKAAxP9VdfXsDf5rcinpKain2eqpK@go1FoppHNxpSZn5CukQSh1dSgdklpcolCeWZKhYGigUJaYU5paDJXS0QOZZGigbPAfAA "J – Try It Online") [Answer] # [Red](http://www.red-lang.org), 19 bytes ``` 1 /(1 - random 1.0) ``` [Try it online!](https://tio.run/##K0pN@R@UmqIQHatQUJSZV/LfUEFfw1BBV6EoMS8lP1fBUM9A8z9YRkFJSaEotSA1sUQhT8HQQCEaIopFfex/AA "Red – Try It Online") [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 5 bytes ``` ÷1-?0 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT////1Hf1EdtEw5vN9S1N/j/HwA "APL (Dyalog Unicode) – Try It Online") **How?** ``` ÷ 1- ?0 1÷ (1- random 0..1) ``` [Answer] # [Japt](https://github.com/ETHproductions/japt/), 6 bytes `1/1-Mr` is the same length but this felt a little less boring! ``` °T/aMr ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=sFQvYU1y&input=) --- ## Explanation Increment (`°`) zero (`T`) and divide by (`/`) its absolute difference (`a`) with `Math.random()`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes Jelly also doesn't have random float, so this uses `x/n` where `x` is an random integer in range `[1, n]` (inclusive) to emulate a random float in range `(0, 1]`. In this program `n` is set to be `108`. ``` ȷ8µ÷X ``` [Try it online!](https://tio.run/##ASEA3v9qZWxsef//yLc4wrXDt1j/4bmbwqIk4oG0w5DCoeG4iv8 "Jelly – Try It Online") ## Explanation ``` ȷ8 Literal 10^8. µ New monad. ÷ Divide by X random integer. ``` --- # [Enlist](https://github.com/alexander-liao/enlist), 3 bytes ``` ØXİ ``` [Try it online!](https://tio.run/##S83LySwu@f//8IyIIxv@/wcA "Enlist – Try It Online") Enlist beats Jelly! (TI-Basic not yet) ## Explanation ``` İ The inverse of... ØX a random float in [0, 1) ``` Of course this has nonzero probability of take the inverse of 0. [Answer] # IBM/Lotus Notes Formula, 13 bytes ``` 1/(1-@Random) ``` **Sample (10 runs)** [![enter image description here](https://i.stack.imgur.com/Ad3kt.png)](https://i.stack.imgur.com/Ad3kt.png) [Answer] # Java 8, ~~22~~ 18 bytes ``` v->1/Math.random() ``` (Old answer before the rules changed: `v->1/(1-Math.random())`) [Try it here.](https://tio.run/##LY7LbsJADEX3fMVdzgiRxzrQLwA2kbqpWLiTgQ5MPFHGiYQqvj01Bcm2ZOvoXF9ppk0aPF@72@Ii5YwDBf5dAYHFj2dyHsfnCnRp@o4eznym0GG2jV4f2lpZSILDEYwdlnnzUZcHkp9iJO5Sb@zSvLhBDcq98fnp6TXOtDIGvnydyL6izmk0mo@wq5qwrXWs1xZliX1KA@oKEnqf/1GgvWfxfZEmKQbVSGTDhTM8xWjfTz6WPw) [Answer] # JavaScript REPL, 15 ~~19~~ bytes ``` 1/Math.random() ``` [Answer] # [Pyt](https://github.com/mudkip201/pyt), 2 bytes ``` ṛ⅟ ``` Explanation: ``` ṛ Random number in [0,1) ⅟ Multiplicative inverse Implicit print ``` [Try it online!](https://tio.run/##K6gs@f//4c7Zj1rn//8PAA) [Answer] # J, 9 Bytes ``` p=:%@?@0: ``` I couldn't figure out how to make it take no input, since p=:%?0 would evaluate immediately and remain fixed. Because of this its sort of long. ### How it works: ``` p=: | Define the verb p 0: | Constant function. Returns 0 regardless of input. ?@ | When applied to 0, returns a random float in the range (0,1) %@ | Reciprocal ``` Evaluated 20 times: ``` p"0 i.20 1.27056 1.86233 1.05387 16.8991 5.77882 3.42535 12.8681 17.4852 2.09133 1.82233 2.28139 1.58133 1.79701 1.09794 1.18695 1.07028 3.38721 2.88339 2.06632 2.0793 ``` [Answer] # [Pyth](https://pythreadthedocs.io), 4 bytes ``` c1O0 ``` [Try it here!](https://pyth.herokuapp.com/?code=c1O0&debug=0) Alternative: `c1h_O0`. [Answer] # [Clean](https://clean.cs.ru.nl), 91 bytes ``` import StdEnv,Math.Random,System.Time Start w=1.0/(1.0-hd(genRandReal(toInt(fst(time w))))) ``` Clean doesn't like random numbers. Because the random generator (a Mersenne Twister) *needs* to be given a seed, I have to take the system timestamp to get something that differs passively per-run, and to do anything IO-related I *need* to use a whole `Start` declaration because it's the only place to obtain a `World`. [Try it online!](https://tio.run/##JcpBCsIwEIXhvafIMkIb9QDudFFQkMYLDE3SBjITaUZLL@@Y4lv88OAbkgcSzO6dvEKIJBFfeWZl2V3p09yBJ9MDuYyNXQt7NM@IfmcZKlrOJ3M86Jp2cnr0tMneQ9KcO2IdCmuuXC37bSLfISQYi7TdTS4rAcbhfx4JOOQZfw "Clean – Try It Online") ]
[Question] [ Write a program or function that takes in a positive integer N. When N is 1, output ``` /\ \/ ``` When N is 2, output ``` /\/\ \/ / / / \/ ``` When N is 3, output ``` /\/\/\ \/ / / / / / \/ / / / \/ ``` When N is 4, output ``` /\/\/\/\ \/ / / / / / / / \/ / / / / / \/ / / / \/ ``` For larger N the pattern continues, a new layer is added every time N is incremented. * "Output" means print the slash pattern or return it as a string. * A single trailing newline in the output is allowed. * Trailing spaces in the output are allowed but leading spaces are not. **The shortest code in bytes wins.** [Answer] # Pyth, 25 bytes ``` j_+t.iJ*R"/ "SQ+L\\J*Q"/\ ``` Try it online: [Demonstration](http://pyth.herokuapp.com/?input=2&code=j_%2Bt.iJ%2AR%22/%20%22SQ%2BL%5C%5CJ%2AQ%22/%5C&test_suite=0&test_suite_input=1%0A2%0A3%0A4) or [Test Suite](http://pyth.herokuapp.com/?input=2&code=j_%2Bt.iJ%2AR%22/%20%22SQ%2BL%5C%5CJ%2AQ%22/%5C&test_suite=1&test_suite_input=1%0A2%0A3%0A4) ### Explanation: ``` j_+t.iJ*R"/ "SQ+L\\J*Q"/\ implicit: Q = input number SQ create the list [1, 2, ..., Q] *R"/ " repeat "/ " accordingly to this numbers J assign this list of strings to J +L\\J create a 2nd list, which contains the same strings as in J, just with a "\" prepended .i interleave these two lists t remove the first element *Q"/\ repeat the string "/\" Q times + append it to the list _ reverse it j print each string on a separate line ``` [Answer] ## CJam, ~~32~~ ~~30~~ ~~29~~ 28 bytes ``` ri_"/\ /"2/f*)@,\f>+_z..e>N* ``` [Test it here.](http://cjam.aditsu.net/#code=ri_%22%2F%5C%20%2F%222%2Ff*)%40%2C%5Cf%3E%2B_z..e%3EN*&input=4) I was trying to help Reto golf his CJam answer but ended up with a solution that had nothing to do with his, so I figured I might as well post it myself. ### Explanation This makes use of the symmetry of the output. In particular, the fact that the output is the same as its transpose. First, we generate the first `N+1` lines, but without the left edge: ``` ri e# Read input and convert to integer N. _ e# Duplicate. "/\ /"2/ e# Push an array with two strings: ["/\" " /"] f* e# Repeat each of the two strings N times. That gives the first two rows. ) e# Detach the second row. @, e# Pull up the other copy of N and turn into range [0 1 ... N-1]. \f> e# For each element i in that range, discard the first i characters of e# the second row. + e# Add all those lines back to the first row. ``` Now we've got an array of strings representing the following grid: ``` /\/\/\/\ / / / / / / / / / / / / / / ``` The transpose of that looks like this: ``` / / / \/ / / / / \/ / / / / \/ / / / \/ ``` Together, these have all the non-space characters that we need. We can now make use of [Dennis's rad tip](https://codegolf.stackexchange.com/a/52627/8478) to combine two ASCII grids into one, by taking the maximum of each corresponding pair of characters. In all positions where the two grids differ, one will have a space (or nothing at all) and the other will have the character we're looking for. When one list in a vectorised operation is longer than the other, the additional elements of the longer list will simply be kept, which is just what we're looking for. In the other cases, the non-space character will always be the maximum of the two characters: ``` _z e# Duplicate the grid and transpose it. ..e> e# For each pair of characters in corresponding positions, pick the maximum. N* e# Join the lines by linefeed characters. ``` [Answer] # [Japt](https://github.com/ETHproductions/Japt), ~~46~~ ~~44~~ ~~41~~ 40 bytes ``` Uo-U £Y?"\\/"sYv)+" /"pU-Y/2 :"/\\"pU} · ``` [Try it online!](https://codegolf.stackexchange.com/a/62685/42545) ### Ungolfed and explanation ``` Uo-U mXYZ{Y?"\\/"sYv)+" /"pU-Y/2 :"/\\"pU} qR ``` The core of the program makes a list of `U * 2` items, maps each to one row of the pattern, then joins them with newlines: ``` Uo-U // Build an array of all integers in the range [-U, U). mXYZ{ // Map each item X and index Y in this array with the following function. ... } qR // Join the resulting array with newlines. ``` As for the pattern itself, here's how I have broken it up: ``` /\/\/\/\ \/ / / / / / / / \/ / / / / / \/ / / / \/ ``` As you can see here, this now devolves into three simple patterns. The first one is the easiest, generated with this code: ``` Y? ... : // If Y, the current index, is 0, "/\\"pU // return the pattern "/\" repeated U*2 times. ``` Now for the left half. Odd indices should map to `\/`, and even to `/`, so we use this code: ``` "\\/"s // Otherwise, slice the pattern "\/" at Yv) // if Y is even, 1; otherwise, 0. ``` This makes the right half way easier; all we need to do is repeat `/` a few times: ``` " /"p // Repeat the pattern " /" U-Y/2 // floor(U - (Y/2)) times. ``` Suggestions welcome! [Answer] # GNU Sed, 59 Score includes +2 for '-nr' options to `sed`. ``` s|1|/\\|gp y|/\\| /| s| |\\|p : s|\\(..)|\1|p s|/ |\\|p t ``` Input in unary as per [this meta answer](http://meta.codegolf.stackexchange.com/a/5349/11259). ### Test output: ``` $ sed -nrf slantcake.sed <<< 111 /\/\/\ \/ / / / / / \/ / / / \/ $ ``` [Answer] ## Python 2, 80 bytes ``` n=input() print"/\\"*n for i in range(n*2,1,-1):print"\\"*(1-i%2)+"/ "*(i/2+i%2) ``` [Answer] # CJam, ~~36~~ ~~35~~ 34 bytes ``` ri_"/\\"*N@,W%{'\'/@" /"*+_N\N}/;; ``` [Try it online](http://cjam.aditsu.net/#code=ri_%22%2F%5C%5C%22*N%40%2CW%25%7B'%5C'%2F%40%22%20%2F%22*%2B_N%5CN%7D%2F%3B%3B&input=4) Thanks to @NinjaBearMonkey for pointing out the extra `;`. While this looks relatively inelegant, I tried a couple of other options, and they did not end up any shorter. Explanation: ``` ri_ Get input, convert to integer, and copy. "/\\" Pattern for first line. *N Repeat N times, and add a newline. @, Rotate N to top, and create [0 .. N-1] sequence. W% Invert sequence to [N-1 .. 0]. { Loop over counts, creating two lines for each. '\ Leading character for first in pair of lines. Rest will be the same for both lines. '/ First character for repeated part. @ Rotate count to top. " /" Repetitive pattern. * Replicate it by count. + Concatenate with '/. _ Copy whole thing for use as second in pair of lines. N\ Put a newline between the pair of lines. N Add a newline after second line. }/ End of loop over counts. ;; Created an extra line, get rid of it. ``` [Answer] ## Mathematica, ~~123~~ ~~122~~ 121 bytes ``` ""<>(#<>" "&/@Normal@SparseArray[{{i_,j_}/;2∣(i+j)&&i+j<2#+3->"/",{i_,j_}/;i~Min~j<2&&2∣i~Max~j->"\\"},{2#,2#}," "])& ``` Could probably be golfed further. [Answer] ## Java - 141 bytes Not the shortest of course, but nice to have a Java solution : ``` String a(int a){String s="";int b=-1,c,e;for(a*=2;++b<a;){for(c=-1;++c<a;)s+=(e=b+c)>a?" ":e%2==0?"/":b==0||c==0?"\\":" ";s+="\n";}return s;} ``` --- ## Ungolfed ``` String a(int a){ String s =""; int b=-1,c,e; for (a*=2;++b < a;){ for (c = -1 ; ++c < a ;) s+= (e=b+c)>a?" ": e%2==0? "/" : b==0||c==0? "\\" : " "; s+="\n"; } return s; } ``` --- ## Input ``` System.out.println(a(5)); ``` ## Output ``` /\/\/\/\/\ \/ / / / / / / / / / \/ / / / / / / / \/ / / / / / \/ / / / \/ ``` [Answer] ## Pyth, 30 Bytes ``` *"/\\"QVr*2Q1+*\\!%N2*s.DN2"/ ``` Try it [here](https://pyth.herokuapp.com/). [Answer] # JavaScript, ~~128~~ ~~125~~ ~~123~~ 114 bytes ``` n=>{r='';for(i=0;i<n;i++)r+='/\\';for(j=0;j<2*n-1;j++){r+='\n'+(j%2?'':'\\');for(i=n-j/2;i>0;i--)r+='/ '}return r} ``` De-golf (also converted to ES5) + demo: ``` function c(n) { r = ''; for (i = 0; i < n; i++) r += '/\\'; for (j = 0; j < 2 * n - 1; j++) { r += '\n' + (j % 2 ? '' : '\\'); for (i = n - j / 2; i > 0; i--) r += '/ ' } return r } alert(c(prompt())); ``` [Answer] # Ruby, 50 bytes ``` ->n{s='/\\'*n n.times{|i|puts s,?\\+s='/ '*(n-i)}} ``` In test program: ``` f=->n{s='/\\'*n n.times{|i|puts s,?\\+s='/ '*(n-i)}} f[gets.to_i] ``` The loop prints 2 rows for every iteration from i=0 to i=n-1. The second row is always `'\'` followed by n-i incidences of `'/ '`. The first row is the same as the second row of the previous iteration, but with the `'\'` missing (so we store this value in `s` when we print the second row of the previous iteration.) The only exception is iteration zero, which is handled by initializing `s` to `'/\'*n`. [Answer] # Javascript (ES6), ~~107~~ ~~104~~ ~~100~~ ~~98~~ ~~97~~ ~~91~~ 90 bytes ``` p=>{s=`/\\`.repeat(p++)+` `;for(i=p;i>2;s+='\\'+o+o)o=`/ `.repeat(--i)+` `;return s+'\\/'} ``` *First post here!* [Used to use](https://codegolf.stackexchange.com/revisions/65262/5) [`Array(len)`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#Syntax)`.`[`join(str)`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join) [but now uses](https://codegolf.stackexchange.com/revisions/65262/6) [`String.repeat(len)`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/repeat), similar to Ruby's [`operator*(str,len)`](http://ruby-doc.org/core-2.2.3/String.html#method-i-2A). Ungolfed: ``` len => { var str = `/\\`.repeat(len++) + '\n'; for (var i = len, mid; i > 2; str += '\\' + mid + mid) { mid = `/ `.repeat(--i) + '\n'; } return str + '\\/'; } ``` *Thanks to:* *107 => 104 bytes: [@insertusernamehere](https://codegolf.stackexchange.com/users/41859/insertusernamehere)* *97 => 90 bytes: [@user81655](https://codegolf.stackexchange.com/users/46855/user81655)* [Answer] ## Python 2, 66 bytes ``` n=input();b=1 print'/\\'*n while~-n+b:print'\\'*b+'/ '*n;b^=1;n-=b ``` Pretty straightforward. The value `n` is the number of `/` on the line, and `b` says whether the line starts with `\`. The value of `b` alternates between 0 and 1, and `n` decreases every second step. The ugly termination condition stops when `n=1, b=0`. The alternative of an `exec` loop would have the issue of needing lots of escapes for `"'\\\\'"`. I was surprised to find this approach shorter than using a single number `k=2*n+b`. This is 68 bytes: ``` k=2*input()+1 print k/2*"/\\" while k>2:print k%2*'\\'+k/2*'/ ';k-=1 ``` An alternative strategy would avoid a separate `print` for the top line, but I didn't see a concise way. [Answer] ## [Minkolang 0.14](https://github.com/elendiastarman/Minkolang), 46 bytes I'm sure this could be golfed, but it's 4 am here and I need to go to bed. ``` n$z"/\"z$D$OlOz[" /"zi-$Dlr$d"\"zi1+-3&5$X$O]. ``` [Try it here.](http://play.starmaninnovations.com/minkolang/?code=n%24z%22%2F%5C%22z%24D%24OlOz%5B%22%20%2F%22zi-%24Dlr%24d%22%5C%22zi1%2B-3%265%24X%24O%5D%2E&input=5) ### Explanation ``` n$z Take number from input (n) and store it in the register (z) "/\" Push these characters (in reverse) z$D Push register value and duplicate the whole stack that many times $O Output whole stack as characters lO Output newline z Push n from register [ Open for loop that repeats n times " /" Push these characters (in reverse) zi- n - loop counter $D Pop k and duplicate whole stack k times l Push 10 (for newline) r Reverse stack $d Duplicate whole stack "\" Push this character zi1+- 0 if n = loop counter + 1, truthy otherwise 3& Do the next three characters if top of stack is 0 5$X Dump the bottom-most five items of the stack $O Output whole stack as characters ]. Close for loop and stop ``` [Answer] ## Batch, 121 bytes ``` @echo off set/an=%1-1 if %1==1 (echo /\%2) else call %0 %n% /\%2 set a=/\%2 echo \%a:\= % if not \%2==\ echo %a:\= % ``` Or if unary is acceptable, 107 bytes: ``` @echo off set a=%1 echo %a:1=/\% :a echo \%a:1=/ % set a=%a:~1% if not %a%1==1 echo / %a:1=/ %&goto a ``` Invoke with the appropriate number of 1s. [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), 27 bytes ``` `/\\`*,ɾṘƛ\/*fṄ;:ƛ\\p;$YṪ⁋, ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%60%2F%5C%5C%60*%2C%C9%BE%E1%B9%98%C6%9B%5C%2F*f%E1%B9%84%3B%3A%C6%9B%5C%5Cp%3B%24Y%E1%B9%AA%E2%81%8B%2C&inputs=4&header=&footer=) ``` `/\\` # '/\' *, # Input times ɾṘ # n...1 ƛ ; # Map... \/* # That many slashes fṄ # Joined by spaces : # Duplicate ƛ\\p; # Prepend a backslash to each $Y # Swap and interleave Ṫ # Cut off last ⁋, # Joined by newlines ``` [Answer] # Matlab, 122 bytes ``` M=2*input(''); z=zeros(M);[y,x]=ndgrid(1:M); z(~mod(x+y,2)&x+y<M+3)=1;v=2-mod(1:M,2); z(1,:)=v;z(:,1)=v;disp([15*z.^2+32,'']) ``` [Answer] # Haskell, 99 bytes Two solutions of equal length. Call `f`. ``` f n=mapM_ putStrLn$[[x?y|x<-[0..2*n-y-0^y]]|y<-[0..2*n-1]] x?y|mod(x+y)2==0='/'|x*y==0='\\'|0<1=' ' ``` and ``` f n=mapM_ putStrLn$[[x?y|x<-[y..2*n-0^y]]|y<-[0..2*n-1]] x?y|mod x 2==0='/'|mod y x==0='\\'|0<1=' ' ``` [Answer] ## Haskell, 96 ``` f=g.(*2) g m=unlines$t m(c"/\\"):[t n l|(n,l)<-zip[m,m-1..2]$c['\\':p,p]] p=c"/ " c=cycle t=take ``` This is not actually competitive against [the existing Haskell solution](https://codegolf.stackexchange.com/questions/65229/n-slab-slanted-slash-cake/65274#65274) because it saves 5 characters by returning instead of printing a string. I am posting it only to show how the infinite pattern approach compares to the coordinate-based approach. Notes: * `p` can be inlined for no change in length. * `[t n l|(n,l)<-...]` saves 2 over `(map(uncurry t)$...)`. [Answer] ## Ceylon, 100 ``` String s(Integer n)=>"\n".join{"/\\".repeat(n),for(i in 2*n+1..3)"\\".repeat(i%2)+"/ ".repeat(i/2)}; ``` This features an "named argument list" for `join` (without any named arguments, but an iterable comprehension instead), and several uses `String.repeat` (one of which actually means "include only for odd `i`"). Formatted: ``` String s(Integer n) => "\n".join{ "/\\".repeat(n), for (i in 2*n + 1 .. 3) "\\".repeat(i % 2) + "/ ".repeat(i / 2) }; ``` [Answer] ## PHP, 117 bytes ``` <?$n=$argv[1];$r=str_repeat;echo$r("/\\",$n);for(;$i++<$n*2-1;)echo"\n".($i%2?"\\":'').$r("/ ",$n-floor(($i-1)/2));?> ``` Assumes notices are turned off and input is taken from command line. Ungolfed: ``` <?php error_reporting(E_ALL & ~E_NOTICE); $n = $argv[1]; $r='str_repeat'; echo $r("/\\",$n); for(;$i++<$n*2-1;){ echo"\n".(($i%2)?"\\":'') . $r("/ ",$n-floor(($i-1)/2)); } ?> ``` Comments are welcome :) [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-R`](https://codegolf.meta.stackexchange.com/a/14339/), 24 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` õç'/ú2)cÈ·p'\+XÃÅÔiUç"/\ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVI&code=9ecnL/oyKWPIt3AnXCtYw8XUaVXnIi9c&input=NA) ]
[Question] [ **This question already has answers here**: [Say What You See](/questions/70837/say-what-you-see) (34 answers) Closed 8 years ago. The look and say sequence is a basic form of run length encoding. The sequence starts with the number 1 and each additional number encodes the number of digits that are repeated before each digit sequence. For example, "1" becomes "11", because there is one "1". Then "11" becomes "21", and so on. The first few numbers are 1, 11, 21, 1211, 111221, 312211 and 13112221. Write a program to output the first 20 numbers. The catch is you **may not use any number** in your program, including other bases than base 10. You can only use letters and symbols. Also, the program can't directly contain the numbers (or fetch them from a web server, or from a file); it must actually compute them. I will accept the answer which works and is the shortest; in case of a tie, vote counts will decide, and in case of a tie there, the winner will be chosen randomly. [Answer] ### Golfscript, 44 43 40 41 38 37 36 chars Since the criterion now requires golfing, here's the golfed version: ``` !:^;n).+{[^\{^$^$={;\)}^if\}*].n@}*; ``` The original, ungolfed, version actually dealt with strings rather than abusing Golfscript's formatting conventions for dumping the stack to stdout at program termination: ``` # Assumes nothing passed to stdin, so input length is zero ,):$''+ { .puts # Convert to an array of [count char count char ...] [$\{.@.@={;\)\}{\$\}if}*] # Convert to an array of [[count char] [count char] ...] $)/ # Form the next string ''\{(@\+\+}/ } # Nineteen times. There are a *lot* of ways of generating the number nineteen # but I like this one $).?.)*(* ``` [Answer] # Perl (60 characters) ``` perl -e'print,s#(.)\g{$y}*#$&=~y///c.$^N#egfor(++$y.$/)x($^F.$|)' ``` Look ma, no numbers. The algorithm is rather similar to the "chinese perl goth's" solution above with a few golf tweaks: * `$^F.$|` == "20" == 20 in numeric context * $^N == last bracket matched * for loop over `(1)x20` is much shorter than trying to use a range * `++$y == 1` and use it both as a backreference `\g{$y}` & to seed the generator * length is more cheaply spelt `y///c` I spent a bunch of time trying alternative short ways to write `length()` before settling on the usual `y///c` - numbers of the form x = nnnn...n (where there are k digits n) have a lovely property that k = x mod 9 / n. So you could write it as `$& % 9 / $^N`. But now you have to get rid of the 9. (Fun to golf again - thanks to MtvViewMark for roping me back) [Answer] # Mathematica ~~88~~ 82 ``` t=Flatten;x=b/b; g@n_:=Grid@NestList[t@Map[Reverse,t[Tally/@Split@#,x],x]&,{x},n-x] ``` --- **Usage** ``` g[9] ``` ![enter image description here](https://i.stack.imgur.com/SLJ6D.png) [Answer] ## PHP 67 bytes ``` <?for(;~Î/$s=preg_filter(~Ð×ÑÖ£ÎÕК,~£ÏÚÆÐ£ÎßÑߣÎ,$s)?:~Îõ;)echo$s; ``` The above may be copied directly, and saved in an ansi format. Alternatively, it may generated with the following script, and then piped to a file: ``` <?="<?for(;~\xce/\$s=preg_filter(~\xd0\xd7\xd1\xd6\xa3\xce\xd5\xd0\x9a,~\xa3\xcf\xda\xc6\xd0\xa3\xce\xdf\xd1\xdf\xa3\xce,\$s)?:~\xce\xf5;)echo\$s;"; ``` The script terminates when the current value of the series, `$s`, becomes larger than the largest representable floating point number, approximately `1e308`. This quite coincidentally occurs just after the 20th value. Sample usage: ``` $ php look-and-say.php 1 11 21 1211 111221 312211 13112221 1113213211 31131211131221 13211311123113112211 11131221133112132113212221 3113112221232112111312211312113211 1321132132111213122112311311222113111221131221 11131221131211131231121113112221121321132132211331222113112211 311311222113111231131112132112311321322112111312211312111322212311322113212221 132113213221133112132113311211131221121321131211132221123113112221131112311332111213211322211312113211 11131221131211132221232112111312212321123113112221121113122113111231133221121321132132211331121321231231121113122113322113111221131221 31131122211311123113321112131221123113112211121312211213211321322112311311222113311213212322211211131221131211132221232112111312111213111213211231131122212322211331222113112211 1321132132211331121321231231121113112221121321132122311211131122211211131221131211132221121321132132212321121113121112133221123113112221131112311332111213122112311311123112111331121113122112132113213211121332212311322113212221 11131221131211132221232112111312111213111213211231132132211211131221131211221321123113213221123113112221131112311332211211131221131211132211121312211231131112311211232221121321132132211331121321231231121113112221121321133112132112312321123113112221121113122113121113123112112322111213211322211312113211 ``` [Answer] # Javascript, 105 ``` z=c=+[];r=x="";s=i=-~c+r;for(e=-~s+r+c;e--;){alert(s);c=z;for(x=r;y=s[c++];++i)y!=s[c]&&(x+=i+y,i=z);s=x} ``` Output (change `alert` to `console.log`) ``` 1 11 21 1211 111221 312211 13112221 1113213211 31131211131221 13211311123113112211 11131221133112132113212221 3113112221232112111312211312113211 1321132132111213122112311311222113111221131221 11131221131211131231121113112221121321132132211331222113112211 311311222113111231131112132112311321322112111312211312111322212311322113212221 132113213221133112132113311211131221121321131211132221123113112221131112311332111213211322211312113211 11131221131211132221232112111312212321123113112221121113122113111231133221121321132132211331121321231231121113122113322113111221131221 31131122211311123113321112131221123113112211121312211213211321322112311311222113311213212322211211131221131211132221232112111312111213111213211231131122212322211331222113112211 1321132132211331121321231231121113112221121321132122311211131122211211131221131211132221121321132132212321121113121112133221123113112221131112311332111213122112311311123112111331121113122112132113213211121332212311322113212221 11131221131211132221232112111312111213111213211231132132211211131221131211221321123113213221123113112221131112311332211211131221131211132211121312211231131112311211232221121321132132211331121321231231121113112221121321133112132112312321123113112221121113122113121113123112112322111213211322211312113211 ``` [Answer] ## Haskell, 116 ``` import List l=length f=[l[f]]:map(((\x->[l x,head x])=<<).group)f main=mapM putStrLn$map(show=<<)$take(l['a'..'t'])f ``` The trick of using `['a'..'t']` to extract the right number of elements was lifted from MtnViewMark's solution. Obviously superior to my original choice of `"a really long string"`. [Answer] **C: 213 characters** ``` main(){char*a,*b=calloc(' ',' '),*c=calloc(' ',' '),*d,*e,*f;*b='Q'-' ';for(a=" ";*a;++a){printf("%s\n",b);e=f=b;d=c;while(*e){while(*f==*e){++f;}d+=sprintf(d,"%d%c",f-e,*e);e=f;}e=b;b=c;c=e;}} ``` [Answer] ## Perl (73) Named capture buffers rock. ``` perl -le '$_++;$c=a;$r="(?<f>.)\\$_*";print,s/$r/length($&).$+{f}/eg while$c++ne u' ``` A bit of explanation: `$_++;` incrementing `$_` which is undefined at the start, to make it contain `1`. `$c=a;` - abusing perl's barewords in a horrible way to make `$c` contain `'a'`. `$r="(?<f>.)\\$_*"` - constructing a regular expression matching repeated characters. normally i'd write it as `(.)\1*` but I can't use digits, so i've declared a capture buffer with the name of `f`. this also could be written as `(?<f>.)\k<f>*` but it'll make the regex one char longer, so I've used `\\$_` which evaluates to `\1`. `print,s/$r/length($&).$+{f}/eg while$c++ne u` Ungolfed: `while($c++ne u) {` - taking advantage of the fact that it's possible to increment strings in perl - incrementing a scalar containing `'a'` will make it contain `'b'`, and so on - so the loop will go from `'a'` to `'u'` `print;` - print `$_` `s/$r/length($&).$+{f}/eg` - operating on `$_`, replace whatever is matched by the previously constructed regular expression (repeated characters) by its length, followed by first char of it. `$&` means the whole match, `$+{f}` means "a named capture buffer with a name f". `}` [Answer] **Mathematica 62** ``` x=a/a;Grid@NestList[Join@@({Length@#,#〚x〛}&/@Split@#)&,{x},#]& ``` [Answer] ## Perl, 94 bytes ``` $_=$w=cos"a";for$a($w..(ord('<')-ord('('))){print"$_ ";eval"s/(\\d)\\$w*/length(\$&).\$$w/ge"} ``` [Answer] # C++ ### By *Chuck Morris* ``` /* This implements the power of ** C H U C K M O R R I S . */ #include <iostream> #include <vector> /* ** Deep within the murks ** Of an assembly programmer's heart ** Lies an ancient hatred ** Of recursion ** ** Yet a true C++ programmer ** Can appreciate the beauty ** And elegance ** Which the following manifests */ std::string stringpp(std::string sz, size_t last_digit=(size_t)'\0') { std::string bak = sz; if(last_digit < sz.length()) { char nextnum = sz[sz.length() - (size_t)'\x01' - last_digit]; ++nextnum; if(nextnum < ':') { sz = bak.substr((size_t)'\0', bak.length() - (size_t)'\x01' - last_digit); sz += nextnum; if(last_digit) sz += bak.substr(bak.length() - last_digit, last_digit); } else { nextnum = '0'; sz = bak.substr((size_t)'\0', bak.length() - (size_t)'\x01' - last_digit); sz += nextnum; if(last_digit) sz += bak.substr(bak.length() - last_digit, last_digit); sz = stringpp(sz, last_digit + (size_t)'\x01'); } } else { sz = "1"; sz += bak; } return(sz); } class ChuckMorris { private: std::string sz; public: ChuckMorris() { sz = "1"; } void next(); std::string get(); }; void ChuckMorris::next() { std::string num; std::string bak = sz; sz = ""; for(size_t i = (size_t)'\0'; i < bak.length();) { num = "0"; size_t i2 = i; for(; (i2 < bak.length()) && (bak.at(i) == bak.at(i2)); ++i2) num = stringpp(num); sz += num; sz += bak.substr(i, 1); i = i2; } } std::string ChuckMorris::get() { return(sz); } int main(int argc, char* argv[]) { ChuckMorris chucky; // std::cout << stringpp("999").c_str() << std::endl; for(char chucks = '\0'; chucks < '\x14';) { std::cout << chucky.get().c_str(); chucky.next(); ++chucks; if(chucks != '\x14') std::cout << ", "; } std::cout << std::endl; return(0); } /* And some elvish for elegance: ** A Elbereth Gilthoniel ** silivren penna míriel ** o menel aglar elenath! ** Na-chaered palan-díriel ** o galadhremmin ennorath, ** Fanuilos, le linnathon ** nef aear, sí nef aearon! */ ``` This is an elegance only *Chuck Morris* himself can achieve with C++ code. He coded it (for free) in less than zero seconds, while sleeping. It may not be as "elegant" as Golfscript/others, but it does everything... in a ***statically typed language!*** [Answer] ## Haskell, 109 characters ``` import List q=show.length l=q" ":map((>>=(\a->q a++[head a])).group)l main=mapM_(putStrLn.snd)$zip['a'..'t']l ``` Not a digit in sight, not even as a character in a string! Prints the first 20 numbers, one per line. --- * Edit (118 -> 109) used suggestion of `length` to generate the initial `1`, then factored out `show.length` [Answer] # Clojure, 251 chars ``` (def z`~(count ""))(def t(read-string(str z "xa")))(println(take(+ t t)(iterate(fn[x](#(reduce(fn[a b](+ b(* a t)))%)(mapcat(juxt count first)(partition-by identity(#(loop[u %,d()](if(zero? u)(seq d)(recur(quot u t)(cons(mod u t)d))))x)))))(inc z)))) ``` Heres the ungolfed version. This sure was fun to figure out. ``` (def z `~(count "")) (def ten (read-string (str z "xa"))) (defn num->digits [n] " Takes a number and returns a sequence containing its digits in ascending order e.g., 123 -> (1 2 3)" (loop [num n, digits ()] (if (zero? num) (seq digits) (recur (quot num ten) (cons (mod num ten) digits))))) (defn digits->num [seq] " Takes a sequence of digits and returns the number they represent e.g., (1 2 3) -> 123 " (reduce (fn [a b](+ b (* a ten))) seq)) (defn look-seq [n] " Returns a sequence containing the look-say representation for n" (digits->num (mapcat (juxt count first) (partition-by identity (num->digits n))))) (defn look-n-say " Returns a lazy sequence representing Conway's look-and-say sequence starting at n" ([] (look-n-say (inc z))) ([n] (iterate look-seq n))) (println (take (+ ten ten) (look-n-say))) ``` [Answer] # Clojure, 172 characters ``` (let[o(*)t(+ o o)f(+ t t)p partial c comp](dorun(take(+(Math/pow t f)f)(map(c println(p apply str))(iterate(c(p mapcat(juxt count first))(p partition-by identity))[o]))))) ``` This is using the trick that the multiplicative identity is 1; therefore, Clojure has `(*)` evaluate to 1. I let this be `o` (one), and then let `t` (two) be `(+ o o)`, and let `f` (four) be `(+ t t)`. I also alias `partial` and `comp` to one-letter names (hurrah for first class functions!). I then use math to find the number 20, so I can use it for taking this number of elements from an infinite sequence of look-and-say strings: 2^4 + 4 = 20. The actual algorithm for finding look-and-say numbers, unobfuscated, looks like this: ``` (iterate (comp (partial mapcat (juxt count first)) (partial partition-by identity)) [1]) ``` The above produces the infinite sequence of sequences of digits corresponding to look-and-say numbers. [Answer] # K, 62 ``` {,/,'[;?:'f]@$#:'f:(&~~':x)_x}\["J"$h,$"i"$"\t";,h:*$"i"$"\r"] ``` [Answer] ## JavaScript (102 characters) Requires support for [arrow functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/arrow_functions). This will work unmodified in [JavaScript Shell](http://www.squarefree.com/shell/shell.html) or otherwise when `print` is changed to `alert`. ``` for(j=k=l=-~'',j=++j+j,j*=++j;j--;)print(k=(''+k).replace(RegExp('(.)\\'+l+'*','g'),(a,b)=>a.length+b)) ``` [Answer] ## Ruby 1.9, 119 chars ``` num = "#{?b.ord-?a.ord}" one = num.to_i limit = ?U.ord-?A.ord loop { puts num num = num.gsub(/(?<digit>.)\k<digit>*/) { $&.size.to_s + $+ } break if (limit -= one) == one - one } ``` A golfed version: ``` k="#{?b.ord-?a.ord}" j=k.to_i i=?U.ord-?A.ord loop{puts k k=k.gsub(/(?<d>.)\k<d>*/){$&.size.to_s+$+} (i-=j)==j-j&&exit} ``` [Answer] ## Ruby 1.9+, 76 characters Like @daniero, I shamelessly stole @Lowjacker's regex. ``` s=$-W.to_s "\cT".ord.times{puts s;s.gsub!(/(?<d>.)\k<d>*/){$&.size.to_s+$+}} ``` [Answer] ## CJam, 11 bytes ``` X{NX$se`}J* ``` [Test it here.](http://cjam.aditsu.net/#code=X%7BNX%24se%60%7DJ*) This answer does not compete as CJam is much younger than this challenge (and `e`` is a fairly recent feature). However, I thought the solution is really neat so I wanted to add it for completeness. ### Explanation ``` X e# Push 1 as the start of the sequence. { e# Repeat this block 19 times... N e# Push a linefeed as a separator. X$ e# Copy the last value (which will be either a number or a nested array of numbers. s e# Convert it to a string, which will flatten the value if it's an array. e` e# Run-length encode the string. }J* ``` This works because `e`` happens to use the required order of run-length and value, and because the look-and-say sequence will never contain any "digits" greater than 3, so that we don't lose any information by simply flattening the RLE-result into a single string. [Answer] ## Lua, 138 bytes ``` p=#' 'm=p c=''..p f=#' 'for k=p,f*f+f do n=''o=#n while o<#c do q=o+p l=c:sub(q,q)i,o=c:find(l.."+",q)n=n..o-i+p..l end c=n print(n)end ``` [Answer] ## Python 2.x ``` from itertools import groupby s=`len(' ')` for x in' ': print s s=''.join(i+`len(list(j))` for i,j in groupby(s)) ``` and a version without the hacky strings ``` from math import * from itertools import groupby s=`int(log(e))` for x in s*int(e**pi-e): print s s=''.join(i+`len(list(j))` for i,j in groupby(s)) ``` note that e\*\*pi-pi is very close to 20 (19.99909997918947) but slightly smaller, so it's no good to use int with [Answer] # Ruby 2.0, 82 characters. I took [Lowjacker](https://codegolf.stackexchange.com/a/2326/4372)'s regex and put it into this one-liner. ``` (?(.ord>>p(n=??.size)).times{puts n=n.to_s.gsub(/(?<d>.)\k<d>*/){$&.size.to_s+$+}} ``` [Answer] ## C# - 209 ``` using System.Linq;class P{static void Main(){int i='a',N='b'-i,O=i-i, x=O;var C=N+"";while(i++<'u'){System.Console.WriteLine(C);var n="";(C+ " ").Aggregate((c,d)=>{x++;if(d!=c){n+=x+""+c;x=O;}return d;});C=n;}}} ``` Exploits the fact that char is implicitly convertible to int, and since a string is an IEnumerable collection of chars, I used the LINQ Aggregate() method to do the work. ``` using System.Linq; class P { static void Main() { int i = 'a', // start loop counter at the int value for 'a' N = 'b' - i, // N is now literally 1 ('b' - 'a') O = i - i, // O is now literally 0 (1 - 1) x = O; // number counter var C = N + ""; // C is the current string. start with "1". while (i++ < 'u') // if 'a' is 1, 'u' is 20 { // print the current string System.Console.WriteLine(C); var n = ""; // this will be our next string // aggregate the current string (C + " ").Aggregate((c, d) => { // increment the number counter x++; if (d != c) { // when a different number is found, update the next string n += x + "" + c; // reset the count x = O; } // the current number is passed back in as the aggregate (c) return d; }); // move next to current C = n; } } } ``` [Answer] # Haskell, 103/114 characters this solution prints the numbers inside lists, like so: ``` [1] [1,1] [2,1] ... ``` code: ``` import Data.List l=length main=mapM print$take(l['a'..'t'])$iterate((>>= \v->[l v,head v]).group)[l[l]] ``` this version prints them outside lists, but has more characters: ``` import Data.List l=length main=mapM(print.(>>=show))$take(l['a'..'t'])$iterate((>>= \v->[l v,head v]).group)[l[l]] ``` output: ``` "1" "11" "21" ... ``` [Answer] # K, 46 bytes ``` (-/_ic'"TA"){,/+(#:;*:)@'\:_[&o,~=':x]x}\,o:#` ``` A very old question, but I thought I could improve on the existing K solution. The phrase `-/_ic'"ta"` generates the constant 19- the difference between the ASCII characters "t" and "a". I also need the constant 1, so I use the length of the empty symbol. Without these contortions, the program would look like the following: ``` 19{,/+(#:;*:)@'\:_[&1,~=':x]x}\,1 ``` Only 33 bytes, and pretty easy to follow by K standards. For each term of the sequence, find the starting index of each run of identical values (`&1,~=':x`), slice the sequence into runs (`_`), and apply count (`#:`) and first (`*:`) to each element of the resulting sequence. (`@'\:`) Take the transpose (`+`) of that result to reshape it into a list of (count,item) tuples and then finally raze (`,/`) into a flat list. In action: ``` (-/_ic'"TA"){,/+(#:;*:)@'\:_[&o,~=':x]x}\,o:#` (,1 1 1 2 1 1 2 1 1 1 1 1 2 2 1 3 1 2 2 1 1 1 3 1 1 2 2 2 1 1 1 1 3 2 1 3 2 1 1 3 1 1 3 1 2 1 1 1 3 1 2 2 1 1 3 2 1 1 3 1 1 1 2 3 1 1 3 1 1 2 2 1 1 1 1 1 3 1 2 2 1 1 3 3 1 1 2 1 3 2 1 1 3 2 1 2 2 2 1 ... ``` ]
[Question] [ Given a binary number A as input with d > 1 digits, output a binary number B with d digits according to the following rules for finding the nth digit of B: * The first digit of B is zero if the first and second digits of A are equal; otherwise, it is one. * If 1 < n < d, then if the (n-1)th, nth and (n+1)th digits of A are equal, then the nth digit of B is zero; otherwise, it is one. * The dth digit of B is zero if the (d-1)th and dth digits of A are equal; otherwise, it is one. ## Rules String/list input/output format is fine. Another allowed way of input/output is an integer followed by the number of preceding zeros (or following the number of preceding zeros). Make your code as short as possible. ## Test Cases ``` 00 -> 00 01 -> 11 11 -> 00 010111100111 -> 111100111100 1000 -> 1100 11111111 -> 00000000 01010101 -> 11111111 1100 -> 0110 ``` [Answer] ## Haskell, ~~59~~ ~~58~~ 54 bytes ``` f s=[1-0^(a-b+a-c)^2|a:b:c:_<-scanr(:)[last s]$s!!0:s] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P02h2DbaUNcgTiNRN0k7UTdZM86oJtEqySrZKt5Gtzg5Ma9Iw0ozOiexuEShOFalWFHRwKo49n9uYmaegq1CSj6XgkJBUWZeiYKKQppCtIGOoQ4IQ6ABjB2LqgoiY4Ahahj7HwA "Haskell – Try It Online") ``` f s= -- input is a list of 0 and 1 s!!0:s -- prepend the first and append the last number of s to s scanr(:)[last s] -- make a list of all inits of this list a:b:c:_<- -- and keep those with at least 3 elements, called a, b and c 1-0^(a-b+a-c)^2 -- some math to get 0 if they are equal or 1 otherwise ``` Edit: @Ørjan Johansen saved 4 bytes. Thanks! [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` .ịṚjṡ3E€¬ ``` [Try it online!](https://tio.run/##y0rNyan8/1/v4e7uhztnZT3cudDY9VHTmkNr/v//H22go2CoowAh4cgAWSQWAA "Jelly – Try It Online") I/O as list of digits. Explanation: ``` .ịṚjṡ3E€¬ .ịṚ Get first and last element j Join the pair with the input list, thus making a list [first, first, second, ..., last, last] ṡ3 Take sublists of length 3 E€ Check if each has all its elements equal ¬ Logical NOT each ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes ``` ¥0.ø¥Ā ``` I/O is in form of bit arrays. [Try it online!](https://tio.run/##MzBNTDJM/f//0FIDvcM7Di090vD/f7SBjoKhjgKEhCMDZJFYAA "05AB1E – Try It Online") ### How it works ``` ¥ Compute the forward differences of the input, yielding -1, 0, or 1 for each pair. Note that there cannot be two consecutive 1's or -1's. 0.ø Surround the resulting array with 0‘s. ¥ Take the forward differences again. [0, 0] (three consecutive equal elements in the input) gets mapped to 0, all other pairs get mapped to a non-zero value. Ā Map non-zero values to 1. ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 11 bytes ``` ¬s¤)˜Œ3ù€Ë_ ``` [Try it online!](https://tio.run/##MzBNTDJM/f//0JriQ0s0T885Osn48M5HTWsOd8f//x9toKNgqKMAIeHIAFkkFgA "05AB1E – Try It Online") or as a [Test suite](https://tio.run/##MzBNTDJM/V9TVhn8/9Ca4kNLNE/POTrJ@PDOR01rDnfH//eqVDq830rh8H4lnf8GBlwGhlyGhkDSwBAIDEAkF5Ay4DKEArAUCAIA) **Explanation** ``` ¬ # get head of input s # move it to the bottom of the stack ¤ # get the tail of the input )˜ # wrap in list ([head,input,tail]) Œ3ù # get sublists of length 3 €Ë # check each sublists for equality within the list _ # logical negation ``` [Answer] # [Haskell](https://www.haskell.org/), ~~66~~ ~~61~~ 59 bytes ``` g t@(x:s)=map("0110"!!)$z(x:t)$z t$s++[last s] z=zipWith(+) ``` [Try it online!](https://tio.run/##PU3BCoMwDL3nK6J4sNRCch049hc7iIcehpaplLUH6di3d@2qe4@8JC88Mmv3fCxLjBP6W7tfnOhXbduamKmuKtGEZPrU0DdOymHRzqMbIfTB2LvxcytFXLXZsEf7MpvHBiccqOMuVyGd8whvBUSorkgExHlgBua/k/6mz1nL7ViSQioqZl4OlGDBL555RjNAfeIX "Haskell – Try It Online") Input is a list of zeros and ones, output is a string. Usage example: `g [0,1,0,1,1,1,1,0,0,1,1,1]` yields `"111100111100"`. --- ### Previous 61 byte solution: ``` g s=["0110"!!(a+b+c)|(a,b,c)<-zip3(s!!0:s)s$tail s++[last s]] ``` [Try it online!](https://tio.run/##PU7LCsMwDLvnK5zSQ0sSsNltrPuR0kNaRheWlTLntMe3Z8nSTsJCthHoavl28T7GGbjrKyTCSsrGqlFN7buxetRTezJPtx4alhKP3HIdrPPASvXecgAehni3boEO1odbAtQwQ4@adJ5C3P0gXkYggjkDokDKhkgQ/S@pQiqRtfy2JalIg@WYlw0lWPCLZ@7RDGE@8Qs "Haskell – Try It Online") [Answer] # [J](http://jsoftware.com/), ~~26~~ 14 bytes Credit to Emigna's 05AB1E solution ``` 2=3#@=\{.,],{: ``` [Try it online!](https://tio.run/##y/r/P81WT8HI1ljZwTamWk8nVqfa6n9qcka@QpqCgYIBF5xpCGMaIphAUTCGQAMYG6HSANkMJT0lAwV1QyhQRxU2MIRA9f8A) ### Original attempt ``` 2|2#@="1@|:@,,.@i:@1|.!.2] ``` [Try it online!](https://tio.run/##y/r/P81WT8GoxkjZwVbJ0KHGykFHR88h08rBsEZPUc8o9n9qcka@QpqCgYIBF5xpCGMaIphAUTCGQAMYG6HSANkMJT0lAwV1QyhQRxU2MIRA9f8A) ``` ,.@i:@1 -1, 0, 1 |.!.2] shift filling with 2 2 , add a row of 2s on top |: transpose #@="1 count unique elements in each row 2| modulo 2 ``` [Answer] # [Python 3](https://docs.python.org/3/), 58 bytes ``` lambda a:[len({*a[i and~-i:i+2]})-1for i in range(len(a))] ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHRKjonNU@jWisxOlMhMS@lTjfTKlPbKLZWU9cwLb9IIVMhM0@hKDEvPVUDpC5RUzP2f0FRZl6JRppGtIGOQaymJhcS3xCFb4jGB8rrgDAEGsDYaHpA4gbo5iBDrGZCMVDuPwA "Python 3 – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), ~~15~~ 11 bytes ``` Ẋȯ¬EėSJ§e←→ ``` Takes input as a list, [try it online!](https://tio.run/##yygtzv7//@GurhPrD61xPTI92OvQ8tRHbRMetU36//9/tIGOoQ4IQ6ABjB0LAA "Husk – Try It Online") Or [try this one](https://tio.run/##yygtzv7vdXhHbvGjpsbc/CLr/w93dZ1Yf2iN65HpwV6Hlqc@apvwqG3S////lQwMDQyBwABEKgEA "Husk – Try It Online") that uses strings for I/O. ### Explanation ``` Ẋ(¬Eė)SJ§e←→ -- implicit input, for example [1,0,0,0] SJ -- join self with the following §e -- listify the first and last element: [1,0] -- [1,1,0,0,0,0] Ẋ( ) -- with each triple (eg. 1 0 0) do the following: ė -- listify: [1,1,0] E -- are all equal: 0 ¬ -- logical not: 1 -- [1,1,0,0] ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes ``` I0;;0In0 ``` I/O is in form of bit arrays. [Try it online!](https://tio.run/##y0rNyan8/9/TwNrawDPP4P/DHZvCHjWtAaJDW4/uOdwOZGSB@A1zFHTtFB41zI38/9/AQMHAUMHQEEgaGAKBAYhUAFIGCoZQAJYCQQA "Jelly – Try It Online") ### How it works ``` I0;;0In0 Main link. Argument: A (bit array of length d) I Increments; compute the forward differences of all consecutive elements of A, yielding -1, 0, or 1 for each pair. Note that there cannot be two consecutive 1's or -1's. 0; Prepend a 0 to the differences. ;0 Append a 0 to the differences. I Take the increments again. [0, 0] (three consecutive equal elements in A) gets mapped to 0, all other pairs get mapped to a non-zero value. n0 Perform not-equal comparison with 0, mapping non-zero values to 1. ``` [Answer] # JavaScript (ES6), 45 bytes Takes input as an array of characters. Returns an array of integers. ``` a=>a.map((v,i)=>(i&&v^p)|((p=v)^(a[i+1]||v))) ``` ### Test cases ``` let f = a=>a.map((v,i)=>(i&&v^p)|((p=v)^(a[i+1]||v))) console.log(JSON.stringify(f([..."00"]))) // -> 00 console.log(JSON.stringify(f([..."01"]))) // -> 11 console.log(JSON.stringify(f([..."11"]))) // -> 00 console.log(JSON.stringify(f([..."010111100111"]))) // -> 111100111100 console.log(JSON.stringify(f([..."1000"]))) // -> 1100 console.log(JSON.stringify(f([..."11111111"]))) // -> 00000000 console.log(JSON.stringify(f([..."01010101"]))) // -> 11111111 console.log(JSON.stringify(f([..."1100"]))) // -> 0110 ``` ### Commented ``` a => // given the input array a a.map((v, i) => // for each digit v at position i in a: ( // 1st expression: i && // if this is not the 1st digit: v ^ p // compute v XOR p (where p is the previous digit) ) | ( // end of 1st expression; bitwise OR with the 2nd expression: (p = v) ^ // update p and compute v XOR: (a[i + 1] || // the next digit if it is defined v) // v otherwise (which has no effect, because v XOR v = 0) ) // end of 2nd expression ) // end of map() ``` [Answer] # Mathematica, 56 bytes ``` Boole[!Equal@@#&/@Partition[ArrayPad[#,1,"Fixed"],3,1]]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73yk/Pyc1WtG1sDQxx8FBWU3fISCxqCSzJDM/L9qxqCixMiAxJVpZx1BHyS2zIjVFKVbHWMcwNlbtf0BRZl6JQ1p0tYGOQW0sFxLXEJlriMoFyuqAMAQawNioOkDCBmiGIENsBkJxbex/AA "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 16 bytes ``` ḣ2W;ṡ3$;ṫ-$W$E€¬ ``` [Try it online!](https://tio.run/##y0rNyan8///hjsVG4dYPdy40VgGSq3VVwlVcHzWtObTm////BjoKhjoKEBKODJBFAA "Jelly – Try It Online") I was going to golf this but Erik has a shorter solution already and golfing mine would just bring mine closer to his. I'm still golfing but I won't update unless I can beat him or find a unique idea. # Explanation ``` ḣ2W;ṡ3$;ṫ-$W$E€¬ Main Link ḣ2 First 2 elements W Wrapped into a list (depth 2) ; Append ṡ3$ All overlapping blocks of 3 elements ; Append ṫ-$W$ Last two elements wrapped into a list E€ Are they all equal? For each ¬ Vectorizing Logical NOT ``` [Answer] # [Perl 5](https://www.perl.org/), 62 + 1 (`-n`) = 63 bytes ``` s/^.|.$/$&$&/g;for$t(0..y///c-3){/.{$t}(...)/;print$1%111?1:0} ``` [Try it online!](https://tio.run/##BcFBDkAwEAXQywxh0T8zERsWTuAKNoJIpG2qG8HVjffiko7W7OQJD4ippJK3fg2JciXAxcyza@qbcVN@KwA19zHtPpMWqjpoJ6@ZisgXYt6DP82NLUTFnP8B "Perl 5 – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), 10 bytes ``` Ẋo±≠↔Θ↔ΘẊ- ``` [Try it online!](https://tio.run/##yygtzv7//@GurvxDGx91LnjUNuXcDDABFNL9//9/tIGOoQ4IQ6ABjB0LAA "Husk – Try It Online") Thanks to Zgarb for -1 byte. [Answer] # [Japt](https://github.com/ETHproductions/japt/), ~~14~~ ~~13~~ 12 bytes Partly ported from Dennis' Jelly solution. Input & output are arrays of digits. ``` ä- pT äaT mg ``` Saved a byte thanks to ETHproductions. [Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=5C0gcFQg5GFUIG1n&input=WzAsMSwwLDEsMSwxLDEsMCwwLDEsMSwxXQotUQ==) --- ## Explanation Implicit input of array `U`. `ä-` gets the deltas of the array. `pT` pushes 0 to the end of the array. `äaT` first adds another 0 to the start of the array before getting the absolute deltas. `mg` maps over the elements of the array returning the sign of each element as -1 for negative numbers, 0 for 0 or 1 for positive numbers. [Answer] # [Python 3](https://docs.python.org/3/), 54 bytes ``` lambda x:[n^1in x[i-(i>0):i+2]for i,n in enumerate(x)] ``` I/O is in form of Boolean arrays. [Try it online!](https://tio.run/##K6gsycjPM/5fUJSZV6Kh8T8nMTcpJVGhwio6L84wM0@hIjpTVyPTzkDTKlPbKDYtv0ghUydPASiRmleam1qUWJKqUaEZ@19TI9otMac4VUchpKgUSKJwMEmoNA5VsZqa/wE "Python 3 – Try It Online") [Answer] # J, 32 Bytes ``` B=:2&(+./\)@({.,],{:)@(2&(~:/\)) ``` ### How it works: ``` B=: | Define the verb B 2&(~:/\) | Put not-equals (~:) between adjacent elements of the array, making a new one ({.,],{:) | Duplicate the first and last elements 2&(+./\) | Put or (+.) between adjacent elements of the array ``` I left out some @s and parenthesis, which just make sure it goes together nicely. A step by step example: ``` 2&(~:/\) 0 1 0 1 1 1 1 0 0 1 1 1 1 1 1 0 0 0 1 0 1 0 0 ({.,],{:) 1 1 1 0 0 0 1 0 1 0 0 1 1 1 1 0 0 0 1 0 1 0 0 0 2&(+./\) 1 1 1 1 0 0 0 1 0 1 0 0 0 1 1 1 1 0 0 1 1 1 1 0 0 B 0 1 0 1 1 1 1 0 0 1 1 1 1 1 1 1 0 0 1 1 1 1 0 0 ``` [Answer] # [Retina](https://github.com/m-ender/retina), 35 bytes ``` (.)((?<=(?!\1)..)|(?=(?!\1).))? $#2 ``` [Try it online!](https://tio.run/##K0otycxL/P9fQ09TQ8PexlbDXjHGUFNPT7NGwx7G0dS051JRNvr/38CAy8CQy9AQSBoYAoEBiOQCUgZchlAAlgJBAA "Retina – Try It Online") Link includes test cases. Explanation: The regex starts by matching each input digit in turn. A capture group tries to match a different digit before or after the digit under consideration. The `?` suffix then allows the capture to match 0 or 1 times; `$#2` turns this into the output digit. [Answer] # [Pyth](https://pyth.readthedocs.io), 15 bytes ``` mtl{d.:++hQQeQ3 ``` **[Try it here!](https://pyth.herokuapp.com/?code=mtl%7Bd.%3A%2B%2BhQQeQ3&input=%5B0%2C+1%2C+0%2C+1%2C+1%2C+1%2C+1%2C+0%2C+0%2C+1%2C+1%2C+1%5D&debug=0)** Alternatively: * `mtl{d.:s+hQeBQ3`. * `.aM._M.+++Z.+QZ`. This prepends the first element and appends the last element, then gets all overlapping substrings of length 3, and finally takes the number of distinct elements in each sublist and decrements it. This mess has been done on mobile at midnight so I wouldn’t be surprised if there are some easy golfs. [Answer] # [Gaia](https://github.com/splcurran/Gaia), 9 bytes ``` ọ0+0¤+ọ‼¦ ``` [Try it online!](https://tio.run/##S0/MTPz//@HuXgNtg0NLtIGMRw17Di37n/qobeL/aAMFQwUQhkADGDsWAA "Gaia – Try It Online") ### Explanation ``` ọ0+0¤+ọ‼¦ ~ A program accepting one argument, a list of binary digits. ọ ~ Deltas. 0+ ~ Append a 0. 0 ~ Push a zero to the stack. ¤ ~ Swap the top two arguments on the stack. + ~ Concatenate (the last three bytes basically prepend a 0). ọ ~ Deltas. ¦ ~ And for each element N: ‼ ~ Yield 1 if N ≠ 0, else 0. ``` ### [Gaia](https://github.com/splcurran/Gaia), 9 bytes ``` ọ0¤;]_ọ‼¦ ``` [Try it online!](https://tio.run/##S0/MTPz//@HuXoNDS6xj44GMRw17Di37n/qobeL/aAMFQwUQhkADGDsWAA "Gaia – Try It Online") [Answer] # [C](https://en.wikipedia.org/wiki/C_(programming_language)), **309 bytes** ``` #include<stdio.h> #include<stdlib.h> #include<string.h> int main(int argc,char** argv){int d=strlen(argv[1]);char b[d + 1];char a[d + 1];strcpy(a, argv[1]);b[d]='\0';b[0]=a[0]==a[1]?'0':'1';for(int i=1;i<d-1;i++){b[i]=a[i]==a[i+1]&&a[i]==a[i - 1]?'0':'1';}b[d-1]=a[d-1]==a[d-2]?'0':'1';printf("%s\n",b);} ``` Not exactly a language fit for golfing, but worth an answer none-the-less. Try it out [here](https://onlinegdb.com/Syx_B-ubfM)! **Explanation** ``` #include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, char** argv) { /* Find the number of digits in number (taken in as a command line argument) */ int d = strlen(argv[1]); /* d + 1 to account for d digits plus the null character */ char b[d + 1]; char a[d + 1]; /* Saves having to type argv[1] every time we access it. */ strcpy(a, argv[1]); /* Set the null character, so printf knows where our string ends. */ b[d] = '\0'; /* First condition */ /* For those not familiar with ternary operators, this means b[0] is equal to '0' if a[0] equals a[1] and '1' if they aren't equal. */ b[0] = a[0] == a[1] ? '0' : '1'; /* Second condition */ for(int i = 1; i < d - 1; i++) { b[i] = a[i] == a[i+1] && a[i] == a[i - 1] ? '0' : '1'; } /* Third condition */ b[d - 1] = a[d - 1] == a[d - 2] ? '0' : '1'; /* Print the answer */ printf("%s\n", b); } ``` [Answer] # APL+WIN, 29 bytes ``` (↑b),(×3|3+/v),¯1↑b←×2|2+/v←⎕ ``` Prompts for screen input as a vector of digits and outputs a vector of digits. Explanation ``` b←×2|2+/v signum of 2 mod sum of successive pairs of elements ×3|3+/v signum of 3 mod sum of successive triples of elements (↑b),...., ¯1↑b concatenate first and last elements of b for end conditions ``` [Answer] # [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), 273 bytes ``` I =INPUT D =SIZE(I) N P =P + 1 EQ(P,1) :S(S) EQ(P,D) :S(E) I POS(P - 2) LEN(2) . L I POS(P - 1) LEN(2) . R T Y =IDENT(L,R) Y 0 :S(C) Y =Y 1 C EQ(P,D) :S(O)F(N) S I LEN(1) . L I POS(1) LEN(1) . R :(T) E I RPOS(2) LEN(1) . L I RPOS(1) LEN(1) . R :(T) O OUTPUT =Y END ``` [Try it online!](https://tio.run/##dZCxCsIwEIbn5CluvMMqTXEqdGoiBEoSk3Soo7PYwfcnXkuFKjgd/33c98O9nvN9fpxLERY668KYpdDQJXszaEk6EaALcAAlhbliqBSJNmGiLeo1Go4Wgk8Y4AgNwWAc8jjBsAdqB6LMYuJGbVzGoYoEE9SLq2cXg4kb@08H8N7TBR3JxL5For7sm3ldRmgxkzSM4sIa@jmIfy688GPmB3C5NE6XolRdvwE "SNOBOL4 (CSNOBOL4) – Try It Online") ``` I =INPUT ;* read input D =SIZE(I) ;* get the string length N P =P + 1 ;* iNcrement step; all variables initialize to 0/null string EQ(P,1) :S(S) ;* if P == 1 goto S (for Start of string) EQ(P,D) :S(E) ;* if P == D goto E (for End of string) I POS(P - 2) LEN(2) . L ;* otherwise get the first two characters starting at n-1 I POS(P - 1) LEN(2) . R ;* and the first two starting at n T Y =IDENT(L,R) Y 0 :S(C) ;* Test if L and R are equal; if so, append 0 to Y and goto C Y =Y 1 ;* otherwise, append 1 C EQ(P,D) :S(O)F(N) ;* test if P==D, if so, goto O (for output), otherwise, goto N S I LEN(1) . L ;* if at start of string, L = first character I POS(1) LEN(1) . R :(T) ;* R = second character; goto T E I RPOS(2) LEN(1) . L ;* if at end of string, L = second to last character I RPOS(1) LEN(1) . R :(T) ;* R = last character; goto T O OUTPUT =Y ;* output END ``` [Answer] # [C (tcc)](http://savannah.nongnu.org/projects/tinycc), ~~64~~ ~~62~~ 56 bytes ``` c,p;f(char*s){for(p=*s;c=*s;p=c)*s=p-c==c-(*++s?:c)^49;} ``` I/O is in form of strings. The function **f** modifies its argument **s** in place. [Try it online!](https://tio.run/##RU7RasMwDHyOv0JkDGwnWe2xl9Z19yGlg6LErWFzjO28rOTbM2dpWgl0Ou6QDpuEOE1Ye2UoXs@BR3YzfaBe86hwHl4j41H7BrXGhvKqip87ZF8fWzVOL9bh99B2sI@ptf3b9UCIdQl@ztZRRm6kmI8CT8cTaFJkXpRClPU/ygWlXLmQucQ874pYvfJeT@fcq7a4RkVIkbMDHVy0F9e1YEGDUBn2EO1v1xtIsFlXnrJSVWyJ5UPObWj5Kt8jNAcoa0hHe2Iqa4Y@Vj@k@GBjfhi6NASXv5Bx@gM "C (tcc) – Try It Online") [Answer] # Common Lisp, 134 bytes ``` (lambda(a &aux(x(car a))(y(cadr a)))`(,#1=(if(= x y)0 1),@(loop for(x y z)on a while y if z collect(if(= x y z)0 1)else collect #1#))) ``` [Try it online!](https://tio.run/##PY1hCsIwDIWv8qCgr7Af2wEGHsXYdViIa9kUu11@tsokBL7kyyNOw5J2pjlMDtyp8rgNQsFJXpmZTmaItVwLDV@0Vzam6xlG9shYbYvONhdqjAljnFl22GycIHjfg/oyhhEbXFT17vkPlqMa9br4w8F0pnzYzywGtX/VHlzlBw) ]
[Question] [ Sometimes I see a claim like "80% of respondents agreed" and I think "what was your sample size? 5?" because, of course, with a sample size of 5 it's possible to get 80% to agree on something. If the claim is "47% of respondents agreed" then I know it must be a larger sample size.[1] ## challenge Given a positive integer x≤100, output the minimum number of respondents needed for an honest claim that "x% of respondents agreed". Input and output will be however integers (or numbers) are normally handled. This is code golf. Caveat: Note the effect of [rounding](//en.wikipedia.org/wiki/Rounding#Rounding_to_the_nearest_integer). For example, a claim of "12% of respondents agreed" can mean that there were 8 respondents, 1 agreed, and the claim is rounding half down. Likewise, "13% of respondents agreed" can mean there were 8 respondents, 1 agreed, and the claim is rounding half up. Assume numbers *closest* to an integer are rounded to that integer, but you must account for both of ways of rounding *half*. Thus, on an input of 12 *or* of 13, your algorithm should output 8. ## examples * 1 ↦ 67 * 2 ↦ 40 * 100 ↦ 1 --- [1] Of course, this is assuming that what I'm reading is telling the truth. [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 27 bytes ``` **&~`i$(199*%/:/&=69)-1.99* ``` [Try it online!](https://ngn.codeberg.page/k#eJxLs9LSUqtLyFTRMLS01FLVt9JXszWz1NQ11ANyubjS1A21FQ0NDACu6ggK) Based on the formula from the [OEIS entry](https://oeis.org/A239525): > > Find the smallest N such that there is some x > 0 with abs(100\*x/N - n) <= 0.5. > > > For golfing reasons this actually checks -1 < 1.99\*(100\*x/N - n) < 1, which happens to be equivalent on the domain of the problem. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~ 14 ~~ 12 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -2 thanks to Nick Kennedy! (Make a 100 by 100 table with values over 100% rather than a triangle of values.) ``` ạȷ2÷þפḤỊ§TḢ ``` A monadic Link that accepts a positive integer from \$[1,100]\$, the reported percentage, and yields another positive integer, the minimal number of respondents. **[Try it online!](https://tio.run/##ASUA2v9qZWxsef//4bqhyLcyw7fDvsOXwqThuKThu4rCp1ThuKL///80 "Jelly – Try It Online")** Or see [all 100](https://tio.run/##y0rNyan8///hroUnthsd3n543@Hph5Y83LHk4e6uQ8tDHu5Y9B8k3v6oac1/AA "Jelly – Try It Online"). ### How? ``` ạȷ2÷þפḤỊ§TḢ - Link: positive intger from [1..100], P ¤ - nilad followed by link(s) as a nilad: ȷ2 - 10^2 -> 100 þ - {[1..100]} x {[1..100]} table of: ÷ - divide × - multiply by {100} (vectorises) -> [[100],[50.0,100],[33.33,66.66,100],[25.0,50.0,75.0,100],...] ạ - {P} absolute difference (vectorises) {that} Ḥ - double (vectorises) Ị - is insignificant? (vectorises) - i.e. abs(x)<=1 § - sums T - truthy indices Ḣ - head ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 56 bytes ``` i;j;f(n){for(i=j=1;fabs(100.*j/i-n)>.5;j=--j?:++i);j=i;} ``` [Try it online!](https://tio.run/##VVBdb4IwFH33V9yQmLRKlfrB5jrcw7JfMX1gtXVlWg0lGZnhr49doOgkPW0595yT3ivZXsq6NiITmlh60aecmCRLuNDphyM8iiajbGqYpevJUmQJY9nL03hsKN6NqGpjCzimxhIKlwHg1xCqPCtZqN37FhK4xA8hLKIQZivEPASOJ48RC8QMwRFYR/qxXajnXhf7Mp7LzrHyxSbUZzUCb4t6ayXa18iTdQXIzzQf4a7kl8q7RwWb8m22KVeviGUQwv//eeDdOAwgTUPG7lSJtkj46zM486NOmvSt0qknRldGAM6pUdM2rBtPP6IC07qoMXBxV3JY0qSg96xC9jrX1rm9Cc45SjQJhjtga8B96DYWuypCcOG1cZckautjq0FV/0p9SPeuZt81Oxz/AA "C (gcc) – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), 45 bytes ``` x=>g=i=>(x-i%69/(y=i>>7)*100)**2<.26?y:g(-~i) ``` [Try it online!](https://tio.run/##DcnRDkNAEAXQr2kys6ziQVPM@hbBbm4jRpCGl/761nk9n/7b78OG9bCLjlP0Ek9xQSCOTotH9X7SJXDuxabIczambLOy6q46kP2Bo9eNIEWDVu5vkgQ86LLrPGWzBkLqCUzM8Q8 "JavaScript (Node.js) – Try It Online") [Answer] # [Vyxal 3](https://github.com/Vyxal/Vyxal/tree/version-3), 14 bytes ``` ₅Dᵒ÷×ṚTȧd1≤ᶤaꜝ ``` [Try it Online!](https://vyxal.github.io/latest.html#WyIiLCIiLCLigoVE4bWSw7fDl+G5mlTIp2Qx4omk4bakYeqcnSIsIiIsIjQiLCIzLjIuMCJd) Takes an integer argument and returns an integer argument. This is a Vyxal 3 translation of @JonathanAllan’s Jelly answer. It’s two bytes longer, partly because the outer modifier returns the result in the transposed reverse of what is needed for this problem. ``` ₅Dᵒ÷×ṚTȧd1≤ᶤaꜝ­⁡​‎‎⁡⁠⁡‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁢‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁣‏⁠‎⁡⁠⁤‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁢⁡‏‏​⁡⁠⁡‌⁢⁡​‎‎⁡⁠⁢⁢‏‏​⁡⁠⁡‌⁢⁢​‎‎⁡⁠⁢⁣‏‏​⁡⁠⁡‌⁢⁣​‎‎⁡⁠⁢⁤‏‏​⁡⁠⁡‌⁢⁤​‎‎⁡⁠⁣⁡‏‏​⁡⁠⁡‌⁣⁡​‎‎⁡⁠⁣⁢‏⁠‎⁡⁠⁣⁣‏‏​⁡⁠⁡‌⁣⁢​‎‎⁡⁠⁣⁤‏⁠‎⁡⁠⁤⁡‏‏​⁡⁠⁡‌⁣⁣​‎‎⁡⁠⁤⁢‏‏​⁡⁠⁡‌­ ₅ # ‎⁡100 D # ‎⁢Triplicate ᵒ÷ # ‎⁣Outer divide by using (100..1),(100..1) × # ‎⁤Multiply (by 100) Ṛ # ‎⁢⁡Reverse T # ‎⁢⁢Transpose ȧ # ‎⁢⁣Absolute difference with main input d # ‎⁢⁤Double 1≤ # ‎⁣⁡Less than or equal to 1 ᶤa # ‎⁣⁢Find first where any true ꜝ # ‎⁣⁣Increment by 1 💎 ``` Created with the help of [Luminespire](https://vyxal.github.io/Luminespire). [Answer] # APL+WIN, 35 bytes Prompts for input: ``` ⌊/(⎕=(⌈n-.5),⌊.5+n←100×÷m)/m,m←⍳100 ``` [Try it online! Thanks to Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcQJanP5BlyPWooz3t/6OeLn0NoJitxqOejjxdPVNNHaCQnql2HkiNgcHh6Ye352rq5@rkAvmPejcDhf4DNXL9T@My5ErjMgJiQzBhDCIMDLi4uAA "APL (Dyalog Classic) – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), ~~85~~ 72 bytes -13 bytes since I saw answers to other questions use a function ``` lambda x:[a for a in range(68)for b in range(a)if abs(x-100*b/a)<=.5][0] ``` [try it online!](https://tio.run/##RYxBCsIwEADP5hV7zApqiihS7EtKDxvqaiDZhCSH9vWRePEyMHOYtNdPlGvjSTdPwa4E2zgTcMxA4AQyyful7w/sxf4LoWMgW/R2Gow52gvhczrfltksDRXnGKDsBVxIMVcodXWi@sL3xU9HdUjZSdWsOz0ituEL "Python 3 – Try It Online"), or see [all the numbers](https://tio.run/##K6gsycjPM/6fZqvxPycxNyklUaHCKjpRIS2/SCFRITNPoSgxLz1Vw8xCEySShBBJ1MxMU0hMKtao0DU0MNBK0k/UtLHVM42NNoj9r8kVXVCUmVeikaaRo6kJNisHodNQB6hBM/Y/AA "Python 3 – Try It Online") pre-golf: ``` x=int(input()) for a in range(68): # for all denominators (starting from lowest) for b in range(a): # and numerators (bonus, doesn't let /0 through) if abs(x-100*b/a)<=.5: # is it within rounding range, up or down? print(a) # then print the denominator exit() # anything else will be bigger ``` credit to [oeis](https://oeis.org/A239525) for sequence and formula [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 15 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ∞.ΔтLт*s/α2zs@à ``` [Try it online](https://tio.run/##yy9OTMpM/f//Ucc8vXNTLjb5XGzSKtY/t9Goqtjh8IL//w2NAQ) or [verify all outputs](https://tio.run/##ATQAy/9vc2FiaWX/0YJFTj8iIOKGkiAiP07Cqf/iiJ4uzpTRgkzRgipzL8KuzrEyenNAw6D/fSz/). **Explanation:** ``` ∞ # Push an infinite positive list: [1,2,3,...] .Δ # Pop and find the first/smallest that's truthy for: тL # Push a list in the range [1,100] т* # Multiply each by 100: [100,200,...,10000] s/ # Divide each by the current integer α # Get the absolute difference of each with the (implicit) input 2zs@ # Check for each whether it's <= 0.5: 2 # Push 2 z # Pop and push 1/2 s # Swap so the list is at the top @ # >= check à # Pop and check if any in the list is truthy # (after which the result is output implicitly) ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 15 bytes ``` ∞.ΔDÝs/т*α2zs@à ``` [Try it online!](https://tio.run/##ASEA3v9vc2FiaWX//@KIni7OlETDnXMv0YIqzrEyenNAw6D//zE "05AB1E – Try It Online") Explanation: ``` ∞ Push infinite list .Δ Find first item in list where: D Duplicate item Ý Create an array 0-N s/ Switch last two and divide т* Multiply by 100 α Absolute difference (input is automatically in stack) 2zs Push 0.5 before the last item @ Compare 0.5 with list (>=) à Check if the list contains 1 ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 24 bytes ``` NθI⌊Φφ∧ιΦφ¬‹·⁵↔⁻θ∕×λ¹⁰⁰ι ``` [Try it online!](https://tio.run/##VYvLCsIwEEX3fkWWE4iSIq66EkUQtLjwB9I24EAeNjPp749xJZ7lPfdML1em7ILINb0rDzWOvsCi@82jYGI4OWK4Y8JYI1wwcLOdtdaoY5oBjfrbhsxw80SwO7TDSDlU9t@8EixGnXHF2cMToycIRrVIG4X6Ry/S7WW7hg8 "Charcoal – Try It Online") Link is to verbose version of code. Very slow as it does about 1,000 times as much work as necessary. Explanation: Uses the OEIS formula. ``` Nθ First input as a number φ Predefined variable `1000` Φ Filter on implicit range ι Current value ∧ Logical And φ Predefined variable `1000` Φ Filter on implicit range λ Inner value × ¹⁰⁰ Multiplied by `100` ∕ Divided by ι Outer value ↔⁻ Absolute difference with θ Input number ¬‹·⁵ Is less than or equal to `0.5` ⌊ Take the minimum I Cast to string Implicitly print ``` [Answer] # [R](https://www.r-project.org/), 53 bytes ``` f=\(n,x=1)`if`(all(abs(n-100*(1:x)/x)>.5),f(n,x+1),x) ``` [Try it online!](https://tio.run/##JYpbCoAgEACvs1tWWgRR2Fm0YEGQDXqAt9/SfmYYmFOELD283@FgYJWsQRfIgY8R/HYBN0brCsycsEu4tiMqyl9tUCUUggkXgj7jG4v@GApRXg "R – Try It Online") [Answer] # [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 66 bytes ``` {for(;i++<99;)for(j=0;j++<r=i;)if(.5>=(n=$1-100*j/i)&&n>=-.5)next} ``` [Try it online!](https://tio.run/##VZJBjhMxEEX3dYpS1BolzGToKttlF6HDBrbcgQUjdYgCao0EUtSnQOw4HRcJ9Q2biVqW26r3/89vf/r@5Xadp3GlK3H85qftsrt@W@bLM5/nB97sj5sHXuKZpvPybvPn98/Nm1h/xel5WTtznqdB/u2WaVBab9enr8v2MN/fv3U/7PBymsbDKd6XaT7swuSxHKftJbi9jOOr0@t5d3d3OU77x7K7fP7xvN4@fHz/P8YgL2MM@jLGoOtN2Cop55ESq1NmTVRYnIzFqLJkaixKziIkI8tIIuwkyo0kYclcSYJJJAZSKhtJ64BDRUcupAIt1WA1YVgzS1gXjtPOaQWiATZSD9HU7ZJgOilGUuLYZiRNBXgyMKlGjtSwOOgMwywYyIr0OYVczuGdC4Bs0MxhGHONNU6cU6EyslKRvlUcl4SRkjFeOlosVEoNvdKLKQ4bg6MJzA3NGJqxDMB6UDOEthr5rfV@HZq1/8UqIVcVdE1gasZIRTfVgNfap1t4V@8fBYZNUG9TIC1F661zrX@MZiHa0ExDM82D9W7nAsB7M56g5hlC3j@8G@6AV@T1hpvhjksS142F/gI "AWK – Try It Online") ]
[Question] [ [hgl](https://gitlab.com/WheatWizard/haskell-golfing-library/-/blob/master/src/P.hs) has a "scan" function called `sc`. What it does in general is a little bit abstract, so we will just talk about one specific way you can use it. If we want to take a list of integers and get the partial sums of every prefix we can scan with `+` for sums and `0` as a starting value: ``` ghci> sc (+) 0 [1,2,3,4,5,6] [1,3,6,10,15,21] ``` This moves left to right adding each value of the list to the accumulator and replacing it with the sum. We can also scan things other than lists. We can scan all sorts of trees and list-like things. hgl more or less builds the scan function based on the type we give it. One weirder example is ragged lists. These are lists that contain a mixture of values and other ragged lists. For example: ``` [1,2,3,[2,3,4],[],2,1,[4,8,[6],5],2] ``` The compiler has dreamed up a rather weird way to scan these. When the list contains values it behaves normally: ``` ghci> sc (+) 0 [1,2,3,[2,3,4],[],2,1,[4,8,[6],5],2] [1,2,3,[2,3,4],[],2,1,[4,8,[6],5],2] ^1 [1,3,3,[2,3,4],[],2,1,[4,8,[6],5],2] ^3 [1,3,6,[2,3,4],[],2,1,[4,8,[6],5],2] ^6 ``` but when it hits a list it splits the read head in two. One goes down that list and scans it, the other skips it and scans the rest of the outer list. ``` [1,3,6,[8,3,4],[],2,1,[4,8,[6],5],2] ^6 [1,3,6,[8,3,4],[],2,1,[4,8,[6],5],2] ^8 ^6 [1,3,6,[8,11,4],[],8,1,[4,8,[6],5],2] ^11 ^8 [1,3,6,[8,11,15],[],8,9,[4,8,[6],5],2] ^15 ^9 [1,3,6,[8,11,15],[],8,9,[4,8,[6],5],2] ^9 [1,3,6,[8,11,15],[],8,9,[13,8,[6],5],11] ^13 ^11 [1,3,6,[8,11,15],[],8,9,[13,21,[6],5],11] ^21 [1,3,6,[8,11,15],[],8,9,[13,21,[6],5],11] ^21 [1,3,6,[8,11,15],[],8,9,[13,21,[27],26],11] ^27 ^26 [1,3,6,[8,11,15],[],8,9,[13,21,[27],26],11] ``` This treats a ragged list as a sort of tree, where the main list forms a spine and each nested list is an offshoot from that spine. ## Task Take a ragged list of positive integers as input and perform the scan shown above (`sc (+) 0`) returning the scanned list. You may take and output a ragged list in any reasonable format. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so answers will be scored in bytes with minimizing the source size being the goal. ## Test cases ``` [] -> [] [8] -> [8] [1,2,3] -> [1,3,6] [1,1,1,1,1] -> [1,2,3,4,5] [[1],[1],[1]] -> [[1],[1],[1]] [1,[1],[1],[1]] -> [1,[2],[2],[2]] [1,2,3,[2,3,4],[],2,1,[4,8,[6],5],2] -> [1,3,6,[8,11,15],[],8,9,[13,21,[27],26],11] [[1,2,3,4],[1,2,3],[1,2,3]] -> [[1,3,6,10],[1,3,6],[1,3,6]] ``` [Answer] # [Python](https://www.python.org), ~~57~~ ~~54~~ 53 bytes ``` f=lambda x,a=0:[i*0==0and(a:=a+i)or f(i,a)for i in x] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3TdNscxJzk1ISFSp0Em0NrKIztQxsbQ0S81I0Eq1sE7UzNfOLFNI0MnUSNdOArEyFzDyFilioZuuCosy8Eo00jWhDHQUjHQVjHYVoCGUSC2TGggWBUtEmOgoWQMoMKGIKEo3V1IQYAXMHAA) Thanks to @ovs for -3 bytes. # [Whython](https://github.com/pxeger/whython), 42 bytes ``` f=lambda x,a=0:[(a:=a+i)?f(i,a)for i in x] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m728PKOyJCM_b8GCpaUlaboWN7XSbHMSc5NSEhUqdBJtDayiNRKtbBO1MzXt0zQydRI10_KLFDIVMvMUKmKhOqwLijLzSjTSNKINdRSMdBSMdRSiIZRJLJAZCxYESkWb6ChYACkzoIgpSDRWUxNiBMxyAA) Uses the `?` operator to catch `TypeError: unsupported operand type(s) for +: 'int' and 'list'` and recurse in that case. [Answer] # [BQN](https://mlochbaum.github.io/BQN/), 34 bytes[SBCS](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn) ``` {×≠𝕩?(⊑𝕩)𝕤{=𝕨?𝕩∾˜⋈𝔽𝕨;𝕨+0∾𝕩}𝕊1↓𝕩;𝕩} ``` [Run online!](https://mlochbaum.github.io/BQN/try.html#code=RuKGkHvDl+KJoPCdlak/KOKKkfCdlakp8J2VpHs98J2VqD/wnZWp4oi+y5zii4jwnZS98J2VqDvwnZWoKzDiiL7wnZWpffCdlYox4oaT8J2VqTvwnZWpfQoKCj7ii4jiiJhG4oiY4oCiSnPCqOKfqCJbOF0iCiJbMSwyLDNdIgoiWzEsMSwxLDEsMV0iCiJbWzFdLFsxXSxbMV1dIgoiWzEsWzFdLFsxXSxbMV1dIgoiWzEsMiwzLFsyLDMsNF0sW10sMiwxLFs0LDgsWzZdLDVdLDJdIgoiW1sxLDIsMyw0XSxbMSwyLDNdLFsxLDIsM11dIuKfqQ==) ``` {×≠𝕩?(⊑𝕩)𝕤{=𝕨?𝕩∾˜⋈𝔽𝕨;𝕨+0∾𝕩}𝕊1↓𝕩;𝕩} # Function taking a nested list as 𝕩 ×≠𝕩? ;𝕩 # If the list is empty, return it 1↓𝕩 # Tail of 𝕩 𝕊 # Recursive call on the tail # If that fails, return the tail (for the base case) ⊑𝕩 # The first element of the list 𝕤{ ... } # Call the inner function with parameters # - 𝕩: result of recursive call # - 𝕨: first element # - 𝔽: a reference to the outer function =𝕨?<list>;<int> # Conditional, the rank of 𝕨 is 0 for ints and 1 for lists 𝔽𝕨 # If 𝕨 is a list, call 𝔽 on that 𝕩∾˜⋈ # And insert the result in the front of 𝕩 0∾𝕩 # If 𝕨 is an integer, prepend 0 to the list 𝕩 𝕨+ # And add 𝕨 to each integer in the resulting nested list ``` I tried to handle the base case with `⎊` (Catch) instead of an explicit conditional, but couldn't get it to work properly. See [the revision history](https://codegolf.stackexchange.com/revisions/240620/2) for my failed attempts. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 39 bytes ``` a_~f~b___:=Join[{f@@a},0&@@a+f@b] _f={} ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78/z8xvi6tLik@Pt7K1is/My@6Os3BIbFWx0ANSGmnOSTFcsWn2VbX/g8oyswriVbWtQPKK8eq1QUnJ@bVVXNV1@pwVVuACEMdIx1jCAMKQZxqIAnFEDkMAaAunWoQYQIUrAVygWpMdCx0qs1qdUyBfIgpOjAVUGugdC1X7X8A "Wolfram Language (Mathematica) – Try It Online") Input `[list...]`. Inputting `[list]` works, but returns inside an extra layer of `{}`. ``` a_~f~b___:= when input is nonempty: f@@a recurse on first element (do nothing if it's an integer) Join[{ }, f@b] followed by recursion on remainder a+ with first element added 0&@@ (or 0 if it's a list) _f={} otherwise return empty list ``` --- ### [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 40 bytes ``` f=#/.{a_,b___}:>Join[{f@a},0&@@a+f@{b}]& ``` [Try it online!](https://tio.run/##ZU1NC8IwDL33bxR6MX5PGYKjZ0@CxzFKNiz2sArSW8j@em1pPUnIS97LSzJjeD1nDG7CGO1VbjeEBkZjDF@629v5nqxGhp3SGldW08iDiveP86GX685qOajlMaFfSBCDoDbDHg5wLE2NTChhzTL7E9IWUIYmiZxo8jTQAp0ZTomXK/Bz1De1suD4BQ "Wolfram Language (Mathematica) – Try It Online") Input `[list]`. [Answer] # [R](https://www.r-project.org/), ~~111~~ ~~107~~ ~~103~~ 98 bytes *Edit: -5 bytes each thanks to pajonk and Giuseppe* ``` `~`=function(x,t=0)`if`(length(x),`if`(is.list(y<-el(x)),c(list(y~t),x[-1]~t),c(y+t,x[-1]~y+t)),x) ``` [Try it online!](https://tio.run/##ZU5BDoIwELz7ChIv3bgYWxBqIn7EGDENKglBQ5cELnwdS1uNymlnZ3Zmpxm1utTnZ9XqbMyHPLu2taLyUbMOKdtAXl5zVhX1je6sA7RrqddVqYn1@7CoDAuomCMGAuyOIT9NQLF@RX41yJx1MJLimb2FhaaGfZ4zIwAsSAkny7kurJ44naMb8D/nvsT60rdPYORuJxB7HxjaR8YoHUgAt4aHYBmEh8C7I0ycKpFz5NuPX@LOV4hQ@CiRGr@J4XzeKrWtpGv1Ve3dyG4/eJ4hAcYX "R – Try It Online") [Answer] # [Pip](https://github.com/dloscutoff/pip) `-xp`, 27 bytes ``` b|:0FdacPB:xNd?b+:d(fdb)c|l ``` Recursive main program, takes the list as a command-line argument. [Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgebSSbkWBUuyCpaUlaboWu5NqrAzcUhKTA5ysKvxS7JO0rVI00lKSNJNrciAqoApvakQrRRtaG1kbW0eDCJNY6-hYINfQOtrE2sI62izW2hTIj4WbDAA) ### Explanation ``` b|:0FdacPB:xNd?b+:d(fdb)c|l a (1st arg) is the input list; b (2nd arg) is the starting number for the scan When the function is called as the main program, b is not specified, so it is nil b|:0 If b is falsey (nil or 0), set it to 0 instead c and d are also local variables which are nil b/c 3rd and 4th arguments are not given Fda For each element d in the input list: xNd Does d contain x (empty string)? ? If so, it's an integer: b+:d Add it to b in-place If not, it's a list of integers: (f ) Make a recursive call d using d as the new list b and the current value of b as the new starting point cPB: Take that result and push it onto the end of c (Pushing an element to a nil variable makes it a list) c After the loop, return c... | except if c is falsey, it's still nil... l so return empty list instead ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 39 bytes ``` f=->d,t=0{d.map{|x|x*0==0?t+=x:f[x,t]}} ``` [Try it online!](https://tio.run/##XU/RasMwDHz3V5jubbuWOGk7b@DtQ1Q9dGvCBmsoqQseSb49kxMnlGFk6U7nk9zcPn6HoXLrtxO8y9rT5ny8tF3owmPmXPbun1x4rSjAc98PRMTQxAyliWysbQIGOYpIGBTYL2Q6U0MU2GKXmiRsiti@h/PrfxIhcp7jfq7gaC08CxTZFha0Z5mFfFkKZGFkmd2os3gR3wJ5dH0WnciNWXbD7Jg@lvK06ehmspGNv50zs@JNefz8ajtfXj2a8nr78Z3SwVUUGVb6omMRc5Cr@a69Xj20wblJ3B/qQ71SWqleDX8 "Ruby – Try It Online") Ruby has the same operator `*` for Integer and Array which takes the same right operand type(number). If we multiply a number by 0 we get 0, if an Array we get an empty Array. [Answer] # [tinylisp](https://github.com/dloscutoff/Esolangs/tree/master/tinylisp), ~~116~~ ~~108~~ 96 bytes ``` (d S(q((L A)(i L(i(a(h L)1)(c(a(h L)A)(S(t L)(a(h L)A)))(c(S(h L)A)(S(t L)A)))L (d f(q((L)(S L 0 ``` [Try it online!](https://tio.run/##XYyxCsMwDER3f8WNpy1O0tC1uzZ/QWkpNZSSUC/9ekU2ptAgJO7diSv5/X3lz2rGOxI3UnERZigzr3xCJQpvXXqSWFz8WGqY/sPqavC@R@tzG4rBWDGiT2jIKDhs6H8jJrCe2W1xjOCMM7gITs62Aw "tinylisp – Try It Online") -8 bytes by removing `(load library` thanks to chunes [in chat](https://chat.stackexchange.com/transcript/message/60327802#60327802). -12 bytes thanks to some [type abuse](https://codegolf.stackexchange.com/a/242255/67312). [Answer] # [JavaScript (Node.js)](https://nodejs.org), 37 bytes ``` f=(v,a=0)=>v.map(z=>z.at?f(z,a):a+=z) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=bVFLDoIwEI1bT-HGpI1PtKBYNdWDNF00Cm5QTPwsuIobF3ooPY0DWIJCmsmk896b7-1xSLfR_f68nOOhfPVjxa6waszV6urt7ZFlapV59ryOWQbLF3agMl6S353bJj2c0iTyknTHYqYN58veaNTTpvuHyAqSDUzAR1DhAgHCFs731XikwgTTBlcLg69V7HqsmbtNQVHfOGvvmZC8BWIY-pJgAgkdGuoJ_u9A0BKC2p8WZIk51Qrg50VmRCaNEC2DwBUod-R8bawiuRgXUL445015I3fYDw) Port of several of the other answers. [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~25~~ 12 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) [emanresu's solution](https://codegolf.stackexchange.com/a/256309/58974) made me realise that, although I had the right method, my approach to it was *all* wrong - I honestly don't know *what* I was thinking!- so please upvote them if you're upvoting this. ``` ˶Ô?ßDÔV:V±D ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=y7bUP99E1FY6VrFE&input=WzEsMiwzLFsyLDMsNF0sW10sMiwxLFs0LDgsWzZdLDVdLDJdCi1R) ``` ˶Ô?ßDÔV:V±D :Implicit input of array U, with second input variable V defaulting to 0 Ë :Map each D in U ¶ : Is D strictly equal to Ô : Its reverse, if it's an array, or maximum, if it's an integer (see more detailed explanation below) ? : If true ß : Recursive call with arguments DÔ : U = D reversed (because reversing an array in JS mutates the original), and V : Current value of V : : Else V±D : Increment V by D ``` --- To (try to) explain how the `Ô` (which is a shortcut for the `w` method, without any arguments) allows us to differentiate between arrays & numbers by testing for strict equality: While it's true that in JavaScript 2 arrays containing the exact same elements are [not strictly equal](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&header=JE8ubyg&code=WzEsIDIsIDNdID09PSBbMSwgMiwgM10&footer=KSQ) as they are 2 distinct objects, an array assigned to a variable is, of course, [equal to itself](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&header=JE8ubygo&code=VSA9IFsxLCAyLCAzXSwKVSA9PT0gVQ&footer=KSQ). Add to that that the `reverse` method for arrays (`w` in Japt) [mutates the original array](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&header=JE8ubyhb&code=VSA9IFsxLCAyLCAzXSwKVS53KCk&footer=XS5xKFIpKSQ) and that explains how an array assigned to a variable (`D` in this case) can be [strictly equal to its reverse](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&header=JE8ubygo&code=VSA9IFsxLCAyLCAzXSwKVSA9PT0gVS53KCk&footer=KSkk). As to why a number does not equal its maximum, that's down to a peculiarity of Japt. Firstly, when applied to a number, Japt's `w` method [returns the maximum](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&header=JE8ubygo&code=VSA9IDgsClUudyg0LCAxMik&footer=KSkk) of that number and the arguments passed to the method, [as a `Number`](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&header=JE8ubygo&code=VSA9IDgsCnR5cGVvZiBVLncoNCwgMTIp&footer=KSkk). However, if *no* arguments are passed to the `w` method then the number it's applied to is [returned as excpected](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&header=JE8ubygo&code=VSA9IDgsClUudygp&footer=KSkk) but, [for some reason](https://github.com/ETHproductions/japt/blob/master/src/japt-interpreter.js#L220), Japt [converts the returned value to an `Object`](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&header=JE8ubygo&code=VSA9IDgsCnR5cGVvZiBVLncoKQ&footer=KSkk) and a `Number` cannot be [strictly equal to](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&header=JE8ubygo&code=VSA9IDgsClUgPT09IFUudygp&footer=KSkk) an `Object` --- ## Original, 25 bytes Preserving this version as Conor O'Brien awarded it an unexpected boubty. ``` W=Uv)?[W¶Ô?ßWÔ:V±W]cßUV:U ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=Vz1Vdik/W1e21D/fV9Q6VrFXXWPfVVY6VQ&input=WzEsMiwzLFsyLDMsNF0sW10sMiwxLFs0LDgsWzZdLDVdLDJdCi1R) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~30~~ 29 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 0U"εdiXćy+š¬ëXD¬šUy®.V}sU"©.V ``` [Try it online](https://tio.run/##yy9OTMpM/f/fIFTp3NaUzIgj7ZXaRxceWnN4dYTLoTVHF4ZWHlqnF1ZbHKp0aKVe2P//0YY6RjrGOtEgwiRWJzoWyDXUiTbRsdCJNovVMQXyY//r6ubl6@YkVlUCAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeV/g1Clc1tTMiOOtFdqH114aM3h1REuh9YcXRhaeWidXlhtcajSoZV6Yf91/kdHx@ooRFuACEMdIx1jCAMKQZxoIAnFEDkMAaAunWgQYQIUjAVygWpMdCx0os1idUyBfIgpOjAVUGugdGzsf13dvHzdnMSqSgA). **Explanation:** Unfortunately 05AB1E lacks recursive methods. We can however mimic this behavior by using `"recursive_function_here®.V"©.V`. One big disadvantage about this however, is that the variables will always be in the scope of the full program, rather than this recursive function. So instead, we use and modify a list as variable. ``` 0U # Start with X=[0] (or actually X=0, but it behaves as [0]) "..." # Push a string with the recursive function explained below © # Store this string in variable `®` (without popping) .V # Evaluate it as 05AB1E code # (after which the result is output implicitly) ε # Map each item `y` to: di # If `y` is a (non-negative) integer: X # Push list X ć # Extract its head; pop and push remainder-list and first item # separated to the stack y+ # Add the current integer `y` to this head š # Prepend it back to the remainder-list ¬ # Push this prepended head again (without popping the list) ë # Else (`y` is an inner list instead): X # Push `X` D # Push `X` again by duplicating ¬š # In this second `X`, prepend its own head U # Pop and replace `X` with this modified list y # Push the current list `y` ®.V # Do a recursive call with it } # After the if-else statement: s # Swap so the (potentially modified) `X` is at the top of the stack U # Pop and replace `X` with this modified list ``` [Answer] # Python3, 74 bytes: ``` f=lambda x,h=0:x and[int==type(x[0])and(h:=h+x[0])or f(x[0],h)]+f(x[1:],h) ``` [Try it online!](https://tio.run/##dY5NCsMgEIX3PUWWSmYRmx@C4EmGWaSkYqFNRLJITm9H2yySUkSc9703M/ptcfNU9z7EaM1zeN3GoVjBmUqvxTCN@JgWY5bN38WKFUlGwmnjyqzmUNjMwUkqU6l0qqMP3CesQAVXqKGBFjqS8nLimE0CJJYKsIEesCNoWR/iB9H/TjqR7zlQVLznc0/pf87@@eTkJfvLqfgG) [Answer] # [BQN](https://mlochbaum.github.io/BQN/), 44 bytes[SBCS](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn) ``` 0⊸{0=≠𝕩?𝕩;×≡⊑𝕩?(⋈𝕨𝕊⊑𝕩)∾𝕨𝕊1↓𝕩;a∾(a←𝕨+⊑𝕩)𝕊1↓𝕩} ``` [Run online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAgMOKKuHswPeKJoPCdlak/8J2VqTvDl+KJoeKKkfCdlak/KOKLiPCdlajwnZWK4oqR8J2VqSniiL7wnZWo8J2VijHihpPwnZWpO2HiiL4oYeKGkPCdlagr4oqR8J2VqSnwnZWKMeKGk/Cdlal9Cgo+KOKLiCBGKcKo4p+o4oCiSnMiW10iCuKAokpzIls4XSIK4oCiSnMiWzEsMiwzXSIK4oCiSnMiWzEsMSwxLDEsMV0iCuKAokpzIltbMV0sWzFdLFsxXV0iCuKAokpzIlsxLFsxXSxbMV0sWzFdXSIK4oCiSnMiWzEsMiwzLFsyLDMsNF0sW10sMiwxLFs0LDgsWzZdLDVdLDJdIgrigKJKcyJbWzEsMiwzLDRdLFsxLDIsM10sWzEsMiwzXV0i4p+p) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 51 bytes ``` ⊞υ⊞Oθ⁰Fυ«≔⊟ιηFLι«≔§ικζ¿⁼ζ⁺ζ⟦⟧⊞υ⊞Oζη«≧⁺ζη§≔ικη»»»⭆¹θ ``` [Try it online!](https://tio.run/##bY7LSgQxEEXX3V@RZQVKsHUUYVazcCEoNroMWYQx0wmGfuQh0jLfHivRBhdCSFF1b91TR6P8cVIu5z4FAwlZqc@z9ipOHhZkl5zv29PkGSTOvtrmEIIdRuinGSxHZkhtqvyoxyEaGlbb5jvEh/FNf4JF9k72tdgbe2JwvyTlAqxEdKlWITnt/nvHWkB1Vbuga37zpOYfxosdTISSQvm/F238v/hNOrf0zm3v7RjhNVIZKAs6ZAsxchaiwyu8RlG@nUQhqe1Q7PAOxa3EG@qlzBcf7hs "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ⊞υ⊞Oθ⁰ ``` Temporarily push the initial accumulator to the list and push that list to the list of lists. ``` Fυ« ``` Loop over all of the lists. ``` ≔⊟ιη ``` Remove the accumulator from the list. ``` FLι« ``` Loop over the elements of the list. ``` ≔§ικζ ``` Get the current element. ``` ¿⁼ζ⁺ζ⟦⟧ ``` Check whether it's a list. Adding an empty list to a list produces the original list, but adding it to an integer vectorises therefore producing the empty list rather than an integer. ``` ⊞υ⊞Oζη ``` If it's a sublist then temporarily push the accumulator to the sublist and push the sublist to the list of lists. ``` «≧⁺ζη§≔ικη ``` Otherwise add the value to the accumulator and replace the value with the total. ``` »»»⭆¹θ ``` Pretty-print the result as the default output format doesn't handle ragged lists very well. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 52 bytes ``` f=([h,...t],v=0)=>h?[h+0>h?f(h,v):v+=h,...f(t,v)]:[] ``` [Try it online!](https://tio.run/##bVDRDoIwDHz3K3wc4QQGihODfsjSB6PiNEaMkP3@LCgEhSxN095de93tYA/V8XV91otHeTo7V@RCGwRBUBNsHnn5zuy18SNOhTCwXmb9vCUUouaSMk3uWD6q8n4O7uVFFEKT523nYTjXNPtDVA@pESYRI@lxiQTpBOf7BjxWYYnViKsl4Rs9e9gbz55ScDemLqY9M9JYYAZxyYIlFHRK7Anx70HQCpLtr1qywoZ3JYibJWsms0bKiUPQLfj8UZcHZ7XDZdRCzcd1mdwb "JavaScript (Node.js) – Try It Online") ]
[Question] [ Given a list of integers find the "trajectory" that results from indefinitely moving the instructed steps to the right (left if negative), wrapping if necessary, starting at the first element. A "trajectory", here, is defined as a list containing the elements that are visited only one time, in the order they are visited, and a list containing those visited repeatedly, also in order i.e.: ``` [first, second, ...], [first_of_loop, second_of_loop, ...] ``` Note that: * Multiple elements may have the same value, yet these are distinct from each other when considering if they have been visited. * The empty list need not be handled (given an empty list your code may error). #### Example Given ``` [6, 0, -6, 2, -9 , 5, 3] ``` we * start at the first element, the `6` * step right \$6\$ to the `3`, * step right \$3\$ to the `-6`, * step left \$6\$ to the `2`, * step right \$2\$ to the `5`, * step right \$5\$ back to the `2`. Thus the trajectory is ``` [6, 3, -6], [2, 5] ``` ...where the second list shows the final loop (we first encounter `2`, then `5`, then loop forever). #### Test Cases ``` in out [0] [], [0] [3] [], [3] [-1, 2] [-1], [2] [5, 2, 4, 6, 7, 3, 1] [], [5, 3, 2, 6, 4, 1] [6, 0, -6, 2, -9 ,5 ,3] [6, 3, -6], [2, 5] [4, 5, 2, 6, -2, 7, 8] [4], [-2, 2] [6, 10, 10, 0, -9, -4, 6] [6, 6], [-4, 10, -9, 10] [9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9] [], [9, 9, 9, 9] ``` [Answer] # Haskell + [hgl](https://gitlab.com/WheatWizard/haskell-golfing-library), ~~61~~ ~~60~~ 58 bytes ``` (i:y)#x|i?>y=m(x!)&@sp(/=i)(rv y)|u<-(i+x!i)%l x:i:y=u#x ([0]#) ``` [hgl](https://gitlab.com/WheatWizard/haskell-golfing-library) is an experimental golfing library I am developing for Haskell. I started a few days ago and this is my first answer, and it's proof there is still a lot of room for improvement. From this post I've learned that: * I should probably make a dedicated function for `m.(!)`, since it is likely to come up more than just here. * I need versions of `sp` (`span`) and `bk` (`break`) that include the element that matches / doesn't match the predicate in the first part. I had to use a hack with `rv`, which is costly and only works in this specific scenario. * ~~I should make an infix version of `e` (`elem`). It would have saved me at least a byte here.~~ Turns out I had already done this (`(?>)`). Maybe what I actually need is better documentation that makes it easier to find this stuff. * ~~I should make an infix version of `jB`. It would have saved me at least 2 bytes here.~~ This also existed and I didn't realize (`(&@)`). There might be a pattern here. * It might be a good idea to make an infix of `sp`. It could have saved me a byte here if I hadn't made an infix of `jB`. * I have probably overall underestimated the usefulness of infixes and I should in general just make more of them. ### But here's how it actually works: Vocab: * `(?>)`: checks if a list contains an element (`elem`) * `m`: map (`fmap`) * `(!)`: index a list (sort of `(!!)`) * `(&@)`: maps function across both parts of a tuple. * `sp`: splits a list at the first element that matches a predicate (`span`) * `rv`: reverses a list (`reverse`) * `(%)`: modulo infix (`mod`, yes Haskell does not have a modulo infix) So this builds up a list of indices, when a index is added that is already in the list it stops and splits at the last occurrence of that index, and converts the indices to their values. [Answer] # [J](http://jsoftware.com/), 53 48 bytes *-5 thanks to Jonah!* ``` (_2{.{~</.~]+./\@e.r)(]~.@,r=.(#@[|]+{~){:)^:_&0 ``` [Try it online!](https://tio.run/##bY4xC8IwEIX3/oqHgmlojWlao00tFAQnJ1etGaStuAhdI/nrMRWii9wdPN777riHmzHSo1YgSMGh/CwZ9qfjwcVaGGbsbsVsm7DVpenYSOPWsiYdaxbPm/OrTYylRtGr0gvuaDR4vyKKVD2Nutv9iQE8iDwInUEEvYZAAYkNcmTBlP4JLX2iSw9894oPLaGFx7c/OONT84nW/lYIyv8VuTc "J – Try It Online") * `r=.(#@[|]+{~){:` take the last index (starting with 0 `&0`), get the corresponding value, add it to the index and take the mod. * `]~.@, … ^:_` append the new value to the indices list and repeat that process until the list does not change after removing duplicates * `]+./\@e.r` the next index is a duplicate, so we find it in the indices list and have a bitmask: 0 for visited once, 1 for loops. * `_2{.{~</.~` group the values based on the indices. Because there might be no items that are visited once, we can pad the output with taking the last two items `_2{.` Another approach would be to not build a list, but just repeat the index-shift-mod-loop `<@#` times, keeping the results, and then search for the loop. But I didn't get it shorter than this. [Answer] # JavaScript (ES6), 92 bytes ``` a=>[(g=p=>a=1/(i=g[p%=w=a.length])?[]:[q=a[p],...g(p+q+w*q*q,g[p]=k++)])(k=0).splice(0,i),a] ``` [Try it online!](https://tio.run/##lVHbboQgEH3vV8xLE1gHFG/tNmH7IYQHYl1r1yjWTffzLdDamDTRLGEe5sycM2fgw3yZqfps7ZX1w1s9n@Vs5EmRRlp5MlLEpJWNso/yJg3v6r65vmv6qvSLGqVRViPnvCE2GqPbYTyM6Hq1vEQR1ZRcZEL5ZLu2qkmCLUWj52rop6GreTc05Exg76hEUwpxDEqjTx7u5WdrfnYXXzGBkC58JrxCuqOgCkdByBFKhCeEDEGsHRQBSkM597UtOeWaEgRWBgY7AhaAfwuVQYqVwRZCse1MuWnFMpmlwdzzIpV7DQ9urecHiuQnvKujC7/nyk/w4kHx2yD@/Zhy6M5dv9cKnb8B "JavaScript (Node.js) – Try It Online") ### Commented ``` a => [ // a[] = input array ( g = p => // g is a recursive function taking a position p // the underlying object of g is also used to keep // track of the positions that are visited a = // update a[] 1 / ( // i = g[ // reduce the position modulo the length w of the p %= w = // array and load g[p] into i a.length // ] // ) ? // if i is defined: [] // we've found the loop: stop the recursion : // else: [ // update the output array: q = a[p], // load a[p] into q ...g( // do a recursive call: p + q + // add q to p w * q * q, // also add w*q² to make sure it's >= 0 g[p] = k++ // save the index k into g[p] and increment k ) // end of recursive call ] // end of array update )(k = 0) // initial call to g with p = k = 0 .splice(0, i), // extract the non-looping part a // append the looping part ] // ``` [Answer] # [Pip](https://github.com/dloscutoff/pip) -xp, 32 bytes ``` ^:iT(Yy+a@y%:#a)NiiPBya@i^@:i@?y ``` Takes the list (formatted like so: `[1;2;-3]`) as a command-line argument, and outputs a list of two lists. [Try it here!](https://replit.com/@dloscutoff/pip) Or, [verify all test cases](https://tio.run/##K8gs@F8dZpVoHe7@P84qM0QjslI70aFS1Uo5UdMvMzPAqTLRITPOwSrTwb7yf62Cr0L6/2iDWK5oYyDWNbRWMALSpkDKWsHEWsHMWsHcWsHYWsEQKArkGFgr6JqBJXUtrRVMFaxBuoDqIBqAMrpGYB0WEOWGBhBsAFGvCzIRKANkEkCx/3WLAgA "Pip – Try It Online") at TIO. ### Explanation ``` ^:iT(Yy+a@y%:#a)NiiPBya@i^@:i@?y a is cmdline input, eval'd (-x flag); i is 0, y is "" (implicit) ^:i Split i and assign back to i: i is now [0] T Loop until y current index +a@y plus number at current index %: mod #a length of list Y (yank into y, making this the new index) ( )Ni is already in the list of indices traversed: iPBy Push the new index onto the list of indices After the loop, we have the list of unique indices traversed in i and the first repeated index in y a@i Values from a at each index in i ^@: split at i@?y the index of y in i ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 42 bytes ``` ≔⁰ζW¬№υζ«⊞υζ≔﹪⁺ζ§θζLθζ»≔⌕υζζUMυ§θιI⟦…υζ✂υζ ``` [Try it online!](https://tio.run/##TY/NCsIwEITP9ily3EIKoihITyUgCFYKHksPoQ1NIE20SfzFZ4@pUfC0OzP7Lbstp2OrqfS@MEb0CuYYPdI8uXIhGYKDtkC0Uxbc5KcpeiazyhkedZ7MvlipOyc1VNIZeGBU2J3q2A3OHwqjPVO95XCe@gl7JV9uK1QXd8WgpCeih4FG92@NSENajSKcQqixUJN7Kxnh@vTDj1K0LIomDHtf12uMwj9ZKItQNhitMFo2jc8u8g0 "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ≔⁰ζ ``` Start at index 0. ``` W¬№υζ« ``` Repeat until a duplicate index is found. ``` ⊞υζ ``` Save the current index. ``` ≔﹪⁺ζ§θζLθζ ``` Calculate the new index. ``` »≔⌕υζζ ``` Find the position of the repeat. ``` UMυ§θι ``` Replace the indices with the values. ``` I⟦…υζ✂υζ ``` Output the values before and after the repeat as separate arrays. [Answer] # [Ruby](https://www.ruby-lang.org/), 91 bytes ``` ->l{*r=a=b=0;r<<a until b=r.index(a=(a+l[a])%l.size);[z=r[0,b],r-z].map{|x|l.values_at *x}} ``` [Try it online!](https://tio.run/##DcXRCoIwFADQX7kvgdrdGEVB6O1Hxog7miAskeliTf325Xk5Idpf6amIp1@bQEyWVBu6jiGOy@DBUpDD@HapYqr47DWb@uTlPGRXtzpT0AqtwSCykR@e1i1tXn7ZRze/eIEm7XuZoAet7wgKQRxdjh6AcEO4GlP@ "Ruby – Try It Online") [Answer] # [C (clang)](http://clang.llvm.org/), 137 bytes ``` a,i,j; #define f(l,z){int t[z]={i=j=0},h[z];for(;!(a=t[i]);i=(z+i+l[i]%z)%z)h[j]=l[i],t[i]=++j;for(i=0;i<j;)printf("! %d"+!!--a,h[i++]);} ``` [Try it online!](https://tio.run/##hZHtaoMwFIb/exXRUVA8oUn8mmS5kpAf0tU10rnSOhgWr92dpMWu3WAayDnvefKefGzoZt/0b/PcgIVOBk@v29b2W9LGexiTs@0HMujRqLNVnWIT7DCR7ccxlmHcqEFbk0ir4jG16R6T1Zjg2OnOKJeCA1Sadn6JVUzal04mhyP6tnEUktVrlIYhpQ0a2zRFs2l2Pd8b25M4OQfE72B7GjTuoQTCgFCcBE41AVIAySZ5pZhj2JJyl96qwqWUg1iUzCmFN8uBoGuFbkD4AhQOyH0X4QEqPPS8EOV1W5wBDga0BppDudQrV6@B/DOQD/DKB3RJDp/DKY6iRHqF/1IEiAclg@qmrNegC8hAQAk5cOMJvL@fjNeK@1U6N0C0O6C4rCkf6iWUBjSejvtjcnbBKuDivnsN/jfBNOu/X8wErsCBuOtG4QsjF2JnzVzs8cxF@OEDcPMN "C (clang) – Try It Online") ``` l : list , z : length int t[z] : kinda sieve, every step sets the visited item to step number h[z] : save the trajectory values in order for output for(;!(a=t[i]) : we iterate until we find a visited item, saving in a the first already visited ;i=(z+i+l[i]%z)%z) : modulo hack at each iteration : h[j]=l[i] : add item to output list ,t[i]=++j; : and update sieve Output for(i=0;i&ltj) : j is the number of items visited printf("! %d"+!!--a,h[i++]) a is the beginning of loop so we put a separator by including '!' in format string ``` [Answer] # [Husk](https://github.com/barbuz/Husk), ~~32~~ ~~29~~ ~~25~~ 23 bytes *Edit: -2 bytes thanks to Razetime* ``` †!¹G-§eoUṠ-UUm←¡Sṙo!¹←ŀ ``` [Try it online!](https://tio.run/##yygtzv7//1HDAsVDO911Dy1PzQ99uHOBbmho7qO2CYcWBj/cOTMfKAXkHG34//9/tJmOgY6umY6Rjq6ljqmOcSwA "Husk – Try It Online") Outputs loop first, then first-visited. **Piece by piece:** Make an infinite list of lists of indices by repeatedly shifting by the input value indexed by the first element: ``` ¡Sṙo!¹←ŀ ``` And get the first element of each of these: this is the list of indices: ``` m← ``` Now, get the longest non-repeating prefix (this includes one copy of the repeating elements): ``` U ``` And get the repeating indices: ``` oUṠ-U ``` Join these together into a list of 2 lists: ``` §e ``` And remove the first (the repeating indices) from the second (the prefix): ``` G- ``` Finally, use these to index into the original input: ``` †!¹ ``` [Answer] # [Python 3](https://docs.python.org/3/), 116 bytes ``` f=lambda a,i=0,k=[]:i in k and[[a[q]for q in x]for x in[k[:k.index(i)],k[k.index(i):]]]or f(a,(i+a[i])%len(a),k+[i]) ``` [Try it online!](https://tio.run/##hZBNb4JAEIbP@ismJk1262D4EFpJOFkOXhrT2KbJZg9rxLgBESm29tfTna3EfhwgLDvz7DvzDlt9NrtDGbTtNinUfr1RoFAnLuaJkLEGXUIOqtwIocRRbg81HImdbXg2ochFnE90ucnOTHOJubhmsZTSyLZMIdNjJbTkN0VWMsUxH1PWfux0kcGqPmXxcKAQ1pDAXlUse1cFmu7VqWF88tbUuqK9KnTDRgAjzoeDqtalyRaPy@dVPEJQV5a@LtP5Kn0gfLu@8qd0ni5eLtyMxXkLfY9wpflIpGDYrw46ddCjFo6H4EsbkN7/pxehESBMESKEO4QAweu6hzb17dGU@O9iYbCL4ERW48wAQ0A7WmQLnchaIoR/XYXpFnadHd8a31PhlCoI/B6UGnru9yLHmVk08cXL@hDwLoeeuUVh9p63@88f5As "Python 3 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 26 bytes ``` L‘0ị+ị¥%L}ɗƬɗƬ%LḊḣ2fQ,ḟʋ/ị ``` [Try it online!](https://tio.run/##y0rNyan8/9/nUcMMg4e7u7WB@NBSVZ/ak9OPrQFhVZ@HO7oe7lhslBao83DH/FPd@kAV/w@3P9y5T4XrcPujpjWR//9Hc0UbxOpwRRuDCF1DHQUjEMMUSOsomOgomOkomOsoGOsoGIKEgTwDHQVdM7CsrqWOAlAdWKMJmGkEVq9rBNZjAdVgaADBBhAduiBDQVJANgEUyxULAA "Jelly – Try It Online") A monadic link taking a list of integers and returning two lists of integers, with the looped integers first. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 22 bytes ``` 0¸Δ¤DIsè+Ig%©ªÙ}D®QÅ¡è ``` [Try it online!](https://tio.run/##yy9OTMpM/f/f4NCOc1MOLXHxLD68QtszXfXQykOrDs@sdTm0LvBw66GFh1f8/x9tpqNgaADBQKRrCcQmOgpmsQA "05AB1E – Try It Online") [Answer] # [PowerShell Core](https://github.com/PowerShell/PowerShell), ~~156~~ 145 bytes ``` for($v=@();!(($s=$v.IndexOf($i))+1);$i%=$l){$v+=,+$i $t+=,($u=$args[+$i]) $i+=$u+($l=$args.Count)}if(--$l*$s){$t[$s..$l],$t[0..--$s]}else{$t,@()} ``` [Try it online!](https://tio.run/##fZJfa9swFMXf9Snuwt0qzZLrP4m3EASG0sGeWtbHEIbnyquHWmeWnXVk/uzZlZ0mfRhDxtx7zu@eK7C3zS/TugdjrSqb1hyw0vtD1bQcdzrnYvWGc3Qad@Hnp3vzfFNxrIUIYrHC@q1GK/a4C7QMsGbYUcGx11i0392apI1gWAca@4CjneTwqumfOjHUFVcK7Xt0lNCt0YUh2o2kMgpDctxmMNYZ8iTdYjgMjOWcMWou4BKiCwkRiJc2pTbnqTgqKiYtIU3FMjlTC0ghgQzmEJO3kImcy0x@kKmMj1BGhMr8MCwIyWQkVUacWsqFTI/QnHyVjPlz6VMyqRKK@XgK8QmKtkSglvQek@LIP5GPUrT2fKvldAhayn8eQpmAP/Cpaa@L8kHdfPthyg72jAGged5SY@4loK1dBxrwq9dt02xJ69rCw037m5x3WEHuKT@5vr276l3XPE5xm3xPIsBdX5bGOV9qmL2ev5xCZ6DMz/Pe1Th1W7TFo@noPxqntqd2NvlfjOttB/9JnbjrY@rInXaQRV9/YIe/ "PowerShell Core – Try It Online") Takes a list as parameter. Returns two lists: loop first then trajectory Saved: * 2 bytes by swapping the loop / trajectory in the result * 2 bytes by reusing `$args[$i]` as `$u` * 1 byte by merging the declaration and first usage of `$l` * 3 bytes by not initialising `$i` anymore * 3 bytes thanks to *mazzy*! #### Not golfed: ``` $index = 0 $length = $args.Count for ($indices = @(); ($truncateAt = $indices.IndexOf($index)) -eq -1) { $indices += , $index $trajectory += , $args[$index] $index = ($index + $args[$index] + $length) % $length } if (--$length -and $truncateAt) { ($trajectory[0..--$truncateAt] -join ','), ($trajectory[++$truncateAt..$length] -join ',') } else { '', ($trajectory -join ',') } ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~ 23 ~~ 22 [bytes](https://github.com/DennisMitchell/jelly/iki/Code-page) Quite possibly still beatable... ``` ĖUṙFḢƊƬḢ€⁺JœṖ€$§ṪọɗƇLṪ ``` A monadic Link that accepts the list and yields a list of lists. **[Try it online!](https://tio.run/##y0rNyan8///ItNCHO2e6Pdyx6FjXsTVA6lHTmkeNu7yOTn64cxqQrXJo@cOdqx7u7j05/Vi7D5D5/3A7UPjopIc7ZwDpyP//o6MNYrl0oo1BhK6hjoIRiGEKpHUUTHQUzHQUzHUUjHUUDEHCQJ6BjoKuGVhW11JBx1RBB6wRqBKiBSilawTWYwHVYGgAwSCNlkAMMhQkBWQTQLFcsQA "Jelly – Try It Online")** ### How? ``` ĖUṙFḢƊƬḢ€⁺JœṖ€$§ṪọɗƇLṪ - Link: list of integers A=[a,b,...,x,y,...] Ė - enumerate -> [[1,a],[2,b],...,[n,x],[m,y],...] U - upend -> [[a,1],[b,2],...,[x,n],[y,m],...] Ƭ - collect until a repeat under: Ɗ - last three links as a monad, f(current=[[x,n],[y,m],...]): F - flatten (current) -> [x,n,y,m,...] ṙ - rotate (current) left by (each of [x,n,y,m,...]) Ḣ - head -> rotation by x Ḣ€ - head each -> leftmost of each, [[a,1],...,[x,n],...] ⁺ - repeat Ḣ€ -> visited elements in order, [a,...,x,...,last_of_loop] $ - last two links as a monad, f(V=[a,...,x,...,last_of_loop]): J - range of length -> [1,2,...,length(V)] œṖ€ - partition (V) before each (of those) indices Ƈ - filter (all of these 2-partitions) keeping if: L - use length (of A) on the right of... ɗ - last three links as a dyad, f(partition, length(A)): § - sums Ṫ - tail -> length of the potential loop ọ - how many times is that divisible by length(A)? (positive (truthy) if an actual loop, else 0 (falsey)) Ṫ - tail ``` [Answer] # [R](https://www.r-project.org/), ~~121~~ ~~118~~ ~~108~~ ~~102~~ ~~101~~ 99 bytes *-10 bytes and another -6 thanks to [@Dominic van Essen](https://codegolf.stackexchange.com/users/95126/dominic-van-essen)* ``` function(a,t=1){while(!(t=(t+a[t]-1)%%sum(a|1)+1)%in%T)T=c(T,t) split(a[T],cut(cumsum(T==t),-1:1))} ``` [Try it online!](https://tio.run/?fbclid=IwAR1DVml-S6X2G9FaLKvkNJy0r39FC1Pqq2Fi0Lp4mvQZ1e1Megiil4wdFSM##hY3NCoMwDMfvPkV3EBJMwfqxzUHfojfxIGUyQd2YKTtse3bXqvdBvn//JM@l00vnJsv9fYKWWCt8v279cIUDsAZO2pobqTCOZzdC@1GY@KafYoNGWzDEGM2PoWdoa9OQdQzWjUFrtGYkqS4K8bt0YOFIIiUhfcp8qgSJkkSOGHWQhiDzEC1IRRluZblqCxJ@6eTFJNROinU7W4nMVnrekZ@odPPwr/IeLuzUt38McfkB "R – Try It Online") The outputted lists have weird names (two intervals), but it I hope it's ok. [Answer] # [jq](https://stedolan.github.io/jq/), 146 bytes ``` length as$l|def x:((.[0]+.[1][-1])%$l+$l)%$l;def n:x as$x|.[1]|index($x);. as$i|[0,[],[]]|until(n;[$i[x],.[1]+[x],.[2]+[$i[x]]])|.[2][:n],.[2][n:] ``` [Try it online!](https://tio.run/##hU3basMwDH3vV@jBg4TIIU7Xbk0@ReihtGnnYdyNZuAHf/s8Kf6AgQ46Ohf787tQCUu8rx9wfpqQr8sN0tQ0PQ3c9eSYrOP2xYTOBF2zBuKUNJ2yBrKP1yU1JrVzr6rPNCCxDOefuPrQxJmMp8So8a6SUcgmMrdZT5pi1SlOXLjI/zvaC6xDGGUfZCG8IhwR3hD2CE5UOQYEe9xMewI8AGpLcrUgjh23xnuNu6FCayeBviiO0H@Gd7@Pr9U/4rPYyx8 "jq – Try It Online") [Answer] # [BQN](https://mlochbaum.github.io/BQN/), 39 bytes[SBCS](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn) ``` ↕∘≠⊸{⊏⟜𝕩¨2↑⊒⊸/⊸(+`⊑⊸=)⊸⊔0∾⊑˜⍟𝕨⟜⊑≠⊸|𝕨+𝕩} ``` [Try it here](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAg4oaV4oiY4omg4oq4e+KKj+KfnPCdlanCqDLihpHiipLiirgv4oq4KCtg4oqR4oq4PSniirjiipQw4oi+4oqRy5zijZ/wnZWo4p+c4oqR4omg4oq4fPCdlagr8J2VqX0KCkbCqOKfqDDin6nigL/in6gz4p+p4oC/4p+owq8xLCAy4p+p4oC/4p+oNSwgMiwgNCwgNiwgNywgMywgMeKfqeKAv+KfqDYsIDAsIMKvNiwgMiwgwq85ICw1ICwz4p+p4oC/4p+oNCwgNSwgMiwgNiwgwq8yLCA3LCA44p+p4oC/4p+oNiwgMTAsIDEwLCAwLCDCrzksIMKvNCwgNuKfqeKAv+KfqDksIDksIDksIDksIDksIDksIDksIDksIDksIDksIDksIDnin6kK). ``` ↕∘≠⊸{⊏⟜𝕩¨2↑⊒⊸/⊸(+`⊑⊸=)⊸⊔0∾⊑˜⍟𝕨⟜⊑≠⊸|𝕨+𝕩} # 𝕩 is input, 𝕨 is indices 0,1,..,length-1 ↕∘≠⊸{ } # pass indices into the main function as 𝕨 ≠⊸|𝕨+𝕩 # add indices to the input mod the length ⊑˜⍟𝕨⟜⊑ # traverse from the first element a number # of steps equal to the length, # accumulating results 0∾ # prepend 0 ⊒⊸/⊸(+`⊑⊸=)⊸⊔ # find the first value to repeat and # partition by occurrences 2↑ # take the first 2 groups ⊏⟜𝕩¨ # and use them to index into the input ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~115~~ 131 bytes ``` f(r,n,o,l,j)int*r,**o,*l;{int*t=malloc(4*n);for(*l=j=0;j+=o[0][(t[j]=++*l)-1]=r[j],!t[j=(j%n+n)%n];);*l-=l[1]=t[j]-1;o[1]=*o+l[1];} ``` [Try it online!](https://tio.run/##fZHbbtswDIavq6dgDWSQZGmwnDRtp/lJDF0Enj3IUKVAcYFiRZ49I@UMS7dhPgAk9ZH8SQ36@zBcLhPPKqqkgpqFj4vMSsqkZLDv5C3dyyGENPCdjMJOKXMZurlr7Fx3qW9cz5d@dl1dyyC0cV1GT91jrOPzJtZRbKKzwsqgu9DjOdHa2ES2TDXF7PlyzNjrkDOnloCGArQgjFG8s7tyOvGqr4Rld6gBiAOPKvxXZKyvawG/qM23jfx8qhRW6b1TvjbEqApK9vF1OfHKkX1mLwcfOXagatGy03CIpUClPuGwjKa1ELW2AlAGUdJHBUGB5Ol16VsnFIlEA0vfpgfq5SN0cF1fkCf/Y0wTKRd0SPmN@w/w55zrlDdNcEW1LyS/qsKaRU8Z9LoOwMfHLzT9zZYVhSHcgsc8Tv7tI7iKXGc07mPZkNLxb9pc6cb93vZ6bXkcsbGwUKy1crmF8@WJGdbgv2Ut0wZa9sgeoIUd7OERtmDQ30MDeo9B/QwPsMXIDojZg24ReiqIaehriNGYzEzLnuGf708 "C (gcc) – Try It Online") Outputs `[prefix, loop]` into `o` and `[len(loop), len(prefix)]` into `l`. Expects these to have allocated enough memory to fit the output (though `o[1]` is discarded). ]
[Question] [ For this challenge, a list is considered valid if and only if it consists entirely of integers and valid lists (recursive definitions \o/). For this challenge, given a valid list and an integer, return a list of all depths at which the integer can be found. # Example Let's consider list `[1, [2, [3, [1, 2, 3], 4], 1], 1]` and integer `1`. Then, we can draw out the list like this: ``` Depth 0 1 2 3 Num 1 2 3 1 2 3 4 1 1 ``` You'll notice that `1` shows up at depths `0, 1, 3`. Thus, your output should be `0, 1, 3` in some reasonable format (order does not matter). The depth may be either 0- or 1-indexed, but please specify in your submission which one it is. # Test Cases (0-indexed) For list `[1,[2,[3,4],5,[6,7],1],[[[[5,2],4,[5,2]]],6],3]`: ``` 1 -> [0, 1] 2 -> [1, 4] 3 -> [0, 2] 4 -> [2, 3] 5 -> [1, 4] 6 -> [1, 2] 7 -> [2] ``` For list `[[[[[1],0],1],0],1]`: ``` 0 -> 1, 3 1 -> 0, 2, 4 ``` For list `[11,22,[33,44]]`: ``` 11 -> [0] 22 -> [0] 33 -> [1] 44 -> [1] ``` Return an empty list if the search term does not exist in the list anywhere. Negative and zero values are valid in the input list and term. [Answer] # [Haskell](https://www.haskell.org/), ~~102~~ ~~93~~ ~~80~~ 76 bytes Thanks [Bruce Forte](https://codegolf.stackexchange.com/users/48198/bruce-forte) for saving some bytes, and [Laikoni](https://codegolf.stackexchange.com/users/56433/laikoni) for saving some more. Thanks [4castle](https://codegolf.stackexchange.com/users/74886/4castle) for saving 4 bytes. Haskell has no data type for this kind of list, so I made my own. This solution is `1-indexed` ``` import Data.List data T=E Int|L[T] E n%x=[0|x==n] L s%x=nub$map(+1).(%x)=<<s ``` [Try it online!](https://tio.run/##vY0/C4MwEMV3P8UNCkpFjH8Xs9Wh4OgmGVIsNFSjaAoOfnebs6UO3TokB4/3Lnf3u/P5ceu6bRP9OEwKzlzxoBKzslrtoKYlXKRaq6ZmVgnSWWgTrgulklkVzDrK59Xu@eieiBe4zuLRopi3ngsJFNrBAnzjJKQCG9yqKYH4qNGusV9CwrSke8y0yzESpvO78E@PYzfxj8iwkaHEzAMHiDFSZIwUGyMlxkipMVJmjJT/kI4DBMfCz92vw63wry2yvQA "Haskell – Try It Online") First I define (recursively) a data type `T` `T` has either type `E Int` (single element of type `Int`) or `L[L]` (list of type `T`). `(%)` is function that takes `2` arguments, on of type `T`, the list through which we are searching, and `x`, the `Int` we are looking for. Whenever `(%)` finds something that is a single element `E n`, it checks `n` for equality with `x` and returns `0` if True. When `(%)` is applied to an `L s` (where `s` has type `[T]`) it runs `(%)` on all the elements of `s` and increments the result (as the depth is increasing since we are looking inside `s`), and the concatenates the result. `nub` then removes the duplicates from the list NB. `import Data.List` is only for `nub`. [Answer] # Mathematica, 25 bytes ``` Tr/@Union[1^Position@##]& ``` (returns 1-indexed output) # Explanation ``` test {1, {2, {3, {1, 2, 3}, 4}, 1}, 1} Position[test,1] {{1}, {2, 2, 2, 1}, {2, 3}, {3}} 1^Position[test,1] {{1}, {1, 1, 1, 1}, {1, 1}, {1}} Union[1^Position[test,1]] {{1}, {1, 1}, {1, 1, 1, 1}} Tr/@Union[1^Position[test,1]] {1, 2, 4} ``` [Answer] # [Python 2](https://docs.python.org/2/), 68 bytes ``` f=lambda l,k,d=-1:l>[]and f(l[0],k,d+1)|f(l[1:],k,d)or{d}-{d+(l==k)} ``` [Try it online!](https://tio.run/##HY3LCoMwFAX3fsVdGjxC46tFSH8k3EVKahuMUYKbYv32tDqbw5zNLJ/1PYcqpUF5Mz2sIY8RVpWy93fNJlgacq8vfLyFFN/DZH@qmONm93KzRe6VGsWePCnSErqCrtEwWugOV4Zk6D8tKkaDc5nRMWrOsmGO5MgFiia8nrnETfQZ0RJdWI84yIn0Aw "Python 2 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~11~~ 8 bytes ``` WẎÐĿċ€IT ``` [Try it online!](https://tio.run/##y0rNyan8/z/84a6@wxOO7D/S/ahpjWfI/8PLD08Asoz0geLu//9HcylEG@pEG@lEG@uYxOqY6kSb6ZjH6hjG6kQDgamOUayOiQ6Yjo3VMYvVMY7VAWkw0gEqB6oGKwYaAQJAPQZgnRBSAR@INgApAdkNNAtkOdA4k1gCmsAaIRog6rliAQ "Jelly – Try It Online") ### How it works ``` WẎÐĿċ€IT Main link. Left argument: A (array). Right argument: n (integer) W Wrap; yield [A]. ÐĿ Repeatedly apply the link to the left until the results are no longer unique. Yield the array of all unique results. Ẏ Concatenate all elements at depth 1 in the array. The last array of the array of results is completely flat. ċ€ Count the occurrences of n in each intermediate result. I Compute all forward differences. T Truth; yield the array of all indices of non-zero differences. ``` ### Example run For left argument ``` [1, [2, [3, [1, 2, 3], 4], 1], 1] ``` `W` first yields the following array. ``` [[1, [2, [3, [1, 2, 3], 4], 1], 1]] ``` `ẎÐĿ` repeatedly concatenates all elements at depth **1**, reducing the depth of the array by **1** in each step. This yields the following array of intermediate results. ``` [ [[1, [2, [3, [1, 2, 3], 4], 1], 1]], [ 1, [2, [3, [1, 2, 3], 4], 1], 1 ], [ 1, 2, [3, [1, 2, 3], 4], 1, 1 ], [ 1, 2, 3, [1, 2, 3], 4, 1, 1 ], [ 1, 2, 3, 1, 2, 3, 4, 1, 1 ] ] ``` For right argument **1**, `ċ€` counts the occurrences of **1** in each intermediate result. ``` [0, 2, 3, 3, 4] ``` `I` now takes all forward differences. ``` [2, 1, 0, 1] ``` Non-zero differences correspond to steps in which at least one other **1** was added to depth **1**. Thus, a non-zero difference at index **k** indicates the presence of a **1** at depth **k**. `T` finds the indices of all truthy elements, yielding the desired result: ``` [1, 2, 4] ``` [Answer] # [R](https://www.r-project.org/), ~~101~~ ~~95~~ ~~92~~ 100 bytes ``` f=function(L,n,d=0)unique(unlist(Map(function(x)if(n%in%unlist(x))"if"(is.list(x),f(x,n,d+1),d),L))) ``` [Try it online!](https://tio.run/##PY7BDoJADER/hZCQtrEaUY/yB3jxunBAYU0TUpHdNfv3iBiZ4@TNy4zTtRTnk/M2sUHvXp6Kjrp30@PQjK5DXzxcuCFUlQGGfmYR@F/Vc0XAjuZMtlgNJSu3xZ6Cyit0GHTZXZoBVySSWNRMNIuUik1R3G6hIrHF@BVscuKWuFzk@PuJYHI@sDnyqa6BOMlp@gA "R – Try It Online") Recursive solution; it's quite inefficient in bytes, but R `lists` are super annoying to work with. Basically, takes `L`, and for each element `x` of `L`, (which is either a `list` or an `atomic` vector of one element), checks if `n` is `%in%` `x`, then checks if `x` is a `list`. If it isn't, then `x==n` so we return the depth `d`; otherwise we recursively call `f` on `x`, incrementing `d`. This, of course, returns a `list`, which we `unlist` and `unique` to ensure the right output (returning a vector of integer depths); returns `NULL` (an empty list) for invalid `n`. Apparently, `%in%` doesn't search recursively through a `list` like I thought, so I have to `unlist(x)` for +8 bytes :( [Answer] # [Python 2](https://docs.python.org/2/), 72 bytes ``` f=lambda l,k,d=0:set([d]*(k in l)).union(*[f(x,k,d+1)for x in l if[]<x]) ``` [Try it online!](https://tio.run/##HYzLDoIwEEX3fMUsW7wxlpeGyJdMZoGBakMpBDHBr6/C2dzFuTnzd31NIYvRNr4dH11LHgO65lK/@1VxJ6kayAXyWp8/wU1BpWzVtn9ORttpoe3Q5CzLfRMdPTXEBpyBcxSCElzhKjAC/lMiExQ4VgSVIJck2UNuDy1tePbK4KbrhGheXFjJKg9yOv4A "Python 2 – Try It Online") [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 39 bytes\* Full program. Prompts for list, then for number. Prints 1-based list to STDOUT. ``` ⌊2÷⍨⍸∨⌿⍞⍷⎕FMT⎕JSON⍠'Compact'0⊢⎕ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKPdJTW1IDg1sSg54/@jni6jw9sf9a541LvjUceKRz37H/XOe9S7/VHfVDffECDpFezv96h3gbpzfm5BYnKJusGjrkVAYZAx/xXAICezuORR2wSoWvVoQ51oI51oYx2TWB1TnWgzHfNYHcNYnWggMNUxitUx0QHTsbE6ZrE6xrHqXBBTEG7iAhnIZYhD3AiHuDEOcRMc4qY4xM1wiJtjisN9DAJALxqAPQom1bkMSFQP8y9GaBrqGIGCExieJrG4QwtncOEML2MA "APL (Dyalog Unicode) – Try It Online") `⎕` prompt for list `⊢` yield that (separates `0` and `⎕`) `⎕JSON⍠'Compact'0` convert to indented JSON string with newlines `⎕FMT` convert to matrix (one newline-delimited line per row) `⍞⍷` prompt for number as string and indicate where it begins in that `∨⌿` vertical OR reduction (i.e. which columns it begins in) `⍸` indices of those beginnings `2÷⍨` halve that (levels are indented with two spaces) `⌊` round down (because first data column is column 3) --- \* In Dyalog Classic, counting `⍸` as `⎕U2378` and `⍠` as `⎕OPT`. [Answer] # [PHP](https://php.net/), 117 bytes ``` $r;function z($a,&$r,$i=0){foreach($a as $v){is_int($v)?(@in_array($i,$r[$v])?:$r[$v][]=$i):z($v,$r,$i+1);}}z($s,$r); ``` [Try it online!](https://tio.run/##JYw/a8MwFMS/ioZHkegNcf4V4hpn6dAOaWm9FPEwwnWwMkhGSg1tyGd3H@ktd7/juHEY58d6HEZFubIF7BJ2hTVjA7vFA6NgWNEGS8YaN2fGlrHicqZUHr9Dd/YxqF9NDneUQL5amMsxpt51g5TKZUWTufjc@nDWEmu996F1KbkfTR6ULE1s6t1/sFyRNzv5m3C7uy9Meb0KZ2FTzn03RHXKMbR96OJXr2X18vF6aN/en5rmU@z50MjuDw "PHP – Try It Online") [Answer] ## JavaScript (ES6), ~~79~~ 68 bytes ``` f=(a,n,r=new Set,d=0)=>a.map(e=>e.map?f(e,n,r,d+1):e-n||r.add(d))&&r ``` Returns a Set. If this is unacceptable, use `&&[...r]` at a cost of 5 bytes. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~17~~ 16 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ⁴e®;©ȧ⁸ḟ⁴ẎµÐĿȧ®T’ ``` A full program taking two command line arguments the list and an element to check for, and printing the depth or depths (if any) at which the element exists. The results are 1-indexed. **[Try it online!](https://tio.run/##y0rNyan8//9R45bUQ@usD608sfxR446HO@YDBR7u6ju09fCEI/tPLD@0LuRRw8z///9HG@pEG@lEG@uYxOqY6kSb6ZjH6hjG6kQDgamOUayOiQ6Yjo3VMYvVMY79bwoA)** ### How? ``` ⁴e®;©ȧḟ⁴ẎµÐĿȧ®T’ - Main link: list, L µÐĿ - loop, collecting updated values of L, until a fixed point is reached: ⁴ - 4th argument (2nd program input) = the number e - exists in (the current version of) L? ® - recall value from the register (initially 0) ; - concatenate the two © - (copy this result to the register) ⁴ - 4th argument (2nd program input) again ḟ - filter out (discard any instances of the number) ȧ - logical and (non-vectorising) Ẏ - tighten (flatten the filtered L by one level to create the next L) ® - recall value from the register ȧ - logical and (non-vectorising) T - truthy indexes (1-indexed) ’ - decrement (account for the leading zero from the initial register) ``` [Answer] # JavaScript (ES6), ~~73~~ 74 bytes ``` f=(a,n,i=0,o={})=>a.map(e=>e.pop?f(e,n,i+1,o):e-n||o[i]++)&&Object.keys(o) ``` **Explanation:** ``` f=(a, //input array n, //input number to search i=0, //start at first level o={} //object to store the finds )=> a.map( //loop through the array e => e.pop ? //is this element an array? f(e, n, i+1, o) : //if so, recurse on it to the next level e-n || o[i]++ //otherwise, update o if element equals the number ) && Object.keys(o) //return o's keys ``` **Test cases** ``` f=(a,n,i=0,o={})=>a.map(e=>e.pop?f(e,n,i+1,o):e-n||o[i]++)&&Object.keys(o) var a = [1,[2,[3,4],5,[6,7],1],[[[[5,2],4,[5,2]]],6],3]; console.log(f(a,1)); console.log(f(a,2)); console.log(f(a,3)); console.log(f(a,4)); console.log(f(a,5)); console.log(f(a,6)); console.log(f(a,7)); console.log('___________'); var a = [[[[[1],0],1],0],1]; console.log(f(a,0)); console.log(f(a,1)); console.log('___________'); var a = [11,22,[33,44]]; console.log(f(a,11)) // [0] console.log(f(a,22)) // [0] console.log(f(a,33)) // [1] console.log(f(a,44)) // [1] console.log(f(a,55)) // empty set ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~123~~ ~~86~~ 82 bytes ``` def f(a,n,l=[],d=0): for e in a:l+=[d]*(e==n);0*e==[]and f(e,n,l,d+1) return{*l} ``` [Try it online!](https://tio.run/##Hcs7CsMwEEXR3quYUrJf4X/AQSsZpjBIIgYxNsIpQsjaFSe3OdU9Xudj16EUHyJFs0KRHAu8a@1SUdwzBdqU1iU1jr3UJjin9t7Wlyyr@usKvwu@6WxFOZzPrO86fUoiR9yBe/CAUTCBZ9wEnYCvJvSCEX9FMAsGqY686WmiSaDR2vIF "Python 3 – Try It Online") -37 bytes thanks to Hyper Neutrino and ovs -4 bytes thanks to Jonathan Frech [Answer] # [Octave](https://www.gnu.org/software/octave/), ~~126~~ 122 bytes ``` function n=r(p,t,l)n=[];if nargin<3 l=0;end for x=p if iscell(q=x{1})a=r(q,t,l+1);else a=l*find(q==t);end n=union(n,a);end ``` [Try it online!](https://tio.run/##HY3BCsMgEAXvfoVHbffQRHqy@yWlB0m0CLImxpSA@O3W5DrzhhenbH62NbfTlH0kTpjEAhmCJHx/tHecTPp6eikW8KEtzczFxA9cWHd@m2wIYsWjDFWa3q5nex@ktmGzzGC4OU9zX2CWV024Uz8SBOYC7YRJFAVlhCeUgasKY62gZPsD "Octave – Try It Online") For readability, I replaced spaces or `;`'s with line ends where possible. Explanation of ungolfed code: ``` function n=r(p,t,l) % Declare function with list p, integer t and optional recursion depth l n=[]; if nargin<3 l=0; % If l is not given (first iteration), set l to zero (or one for 1-indexing) end for x=p % Loop over list if iscell(q=x{1}) % If loop variable x is a cell, we must go down one level. a=r(q,t,l+1); % So recurse to l+1. else a=l*find(q==t); % Empty if q~=t (because find(false)==[], and l*[]==[]), else equal to l*1==l. end n=union(n,a); % Append to list of levels, make sure we only get distinct values. end ``` [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), ~~31~~ 30 bytes Function. Left arg `⍺` is the needle, right arg `⍵` is the haystack. ``` {×≢⍵:(⍳⍺∊⍵),1+⍺∇⊃,/⍵/⍨≢¨⍴¨⍵⋄⍬} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob2pm/qO2CQb/04Bk9eHpjzoXPerdaqXxqHfzo95djzq6gDxNHUNtMKf9UVezjj5QBIhXAFUeWvGodwuI2Pqou@VR75ra//8NFdIUNAw1jDSMNQwVjBSMNU00DYGQywwurmCiaaphpmAOFNUAAlMFI00TMKmpaaZprMllbAxWCtQNVAxUbaKpCQA "APL (Dyalog Classic) – Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 75 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 9.375 bytes ``` w⁽Þf↔ƛ⁰O;¯T ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyI9IiwiIiwid+KBvcOeZuKGlMab4oGwTzvCr1QiLCIiLCJbMSxbMixbMyw0XSw1LFs2LDddLDFdLFtbW1s1LDJdLDQsWzUsMl1dXSw2XSwzXVxuMSJd) Might be able to shave off a byte here, port of Jelly [Answer] # Java, 154 + 19 = 173 bytes ``` import java.util.*; ``` ``` Set<Long>f(List l,long n){Set s=new HashSet();if(l.contains(n))s.add(0l);for(Object o:l)if(o instanceof List)for(long d:f((List)o,n))s.add(d+1);return s;} ``` [Try It Online](https://tio.run/##jVPBbtswDD3bX8GjtHrG0nYdECcFehiwAR12yHHYQbVlV5kiGZKcLgj87Rkly0mWZO0Ohizy8ZGPIpdszd7rlqtl9WsnVq02DpZoyzsnZP6uSNO2e5KihFIya@EbEwq2uwV3s0etmvuaPArrQGYSb6DoFj1g54q/wBdmn/FGaCFqIvNSK4fBlihKbc6qinyQtKi1Id@flrx0oKeSIlIDghxTJdc1eHLqMYG@mtYk5KM627NUVxNaGO46o8AW/S5NWiPWzHFAFoeFH9T40NmQ7R4kXkS9idl//ARmDIVtmiSvBMAcvLQD4sEYtjmGoVykwJJhrwumB@5E1HAiEZVFX@JTBFE6sCQ9cGk5nMWMNZ/FjaLIAaHpX1xDgHs2@iVI@Solb5h8ME234sp9/l3y1gmtSIxKhy822POjvU@xy8NYxCavtahghe9LFs4I1YR@NnYo8LjFsYN7U6hnIjN/nDuS68Fz4rqRGdzKfnB9vAi5Q8inERL5@39luWC6aDsxYma4HnMkya3M/gMWz3jcHVd2Ey497txbQzi@s5@r/bwNK4jeiSzwnM2xAf7nCi1xUhYb6/gq153LcUuUk4r4Wv1WE5rXYX4yXONA2vuH7nd/AA) ## Ungolfed method ``` Set<Long> f(List l, long n) { Set s = new HashSet(); if (l.contains(n)) s.add(0l); for (Object o : l) if (o instanceof List) for (long d : f((List) o, n)) s.add(d + 1); return s; } ``` [Answer] # [ReRegex](https://github.com/TehFlaminTaco/ReRegex), 299 bytes ``` #import math (a[^<>\[\]]*?)\[/$1</(a.*?(_*)<[^<>\[\]]*?)\[/$1_$2</(a.*?(_*)<[^<>\[\]]*?)\]/$1$2>/(a.*?(_*)>[^<>\[\]]*?)\[/$1$2</(a.*?_(_*)>[^<>\[\]]*?)\]/$1$2>/a([^\[\]]*$)/bb$1/^(.*?)b(.*)b(.*?(_*)<[^<]*)\1/$1b$2,d<$4>b$3/^(.*?)b,?(.*)b(.(?!\1))*$/$2/(,|^)([^,<>\[\]]+)([^<>\[\]]*),\2/$1$2$3/#input ``` ## With comments ``` #import math # Count the depths of all braces (a[^<>\[\]]*?)\[/$1</ (a.*?(_*)<[^<>\[\]]*?)\[/$1_$2</ (a.*?(_*)<[^<>\[\]]*?)\]/$1$2>/ (a.*?(_*)>[^<>\[\]]*?)\[/$1$2</ (a.*?_(_*)>[^<>\[\]]*?)\]/$1$2>/ # Move to step b a([^\[\]]*$)/bb$1/ # Record all the depths of all instances of the input ^(.*?)b(.*)b(.*?(_*)<[^<]*)\1/$1b$2,d<$4>b$3/ # Move to finalize ^(.*?)b,?(.*)b(.(?!\1))*$/$2/ # Deduplicate (,|^)([^,<>\[\]]+)([^<>\[\]]*),\2/$1$2$3/ #input ``` [Try it online!](https://tio.run/##dY47bsMwDED3nCJBOIgqU0Gyky6GfRCKNiTEaD3kA8MFOuTujvJxOhjRQIh8fCT7tm@/279xXHeH86kflocw/CxU4LooPXsRXaFnA7YwKnzqSjUaixlswL3lkji48h@XM/1lN3M@6UFx/SgCmhjBmlolA2OK9/BaLRq9TVYER/sC8jJCNjVT9WxX1cpbRA0GnFF0qTHNp@fej1sy3YDk3f2GNGXdHc@/wzhutoEtsSPOKBfabIl39CVkhTi9lDuhnB4fEdoJZXIF "ReRegex – Try It Online") [Answer] # [Perl 5](https://www.perl.org/) `-a`, 65 bytes ``` $q=<>;s,-?\d+,$q-$&||$k{$`=~y/\[//-$`=~y/]//}++,ge;say for keys%k ``` [Try it online!](https://tio.run/##K0gtyjH9/1@l0NbGzrpYR9c@JkVbR6VQV0WtpkYlu1olwbauUj8mWl9fF8KM1dev1dbWSU@1Lk6sVEjLL1LITq0sVs3@/z/aUEchGggMY3UUDIAYToOYXIb/8gtKMvPziv/r@prqGRga/NdNBAA "Perl 5 – Try It Online") Result is 1-indexed. [Answer] # [Ruby](https://www.ruby-lang.org/), 63 bytes ``` f=->n,a,x=0{a.map{f[n,_1,x+1]rescue n==_1 ?x:p}.flatten-[p]|[]} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=VY9BDoJADEX3nIIlxs-EARRjMnqQpjEDYeJCJwQhwSAnceNCD-VtHBAXdtHmJ__3tfdn3ebXx-PVNibcvPdGhTsLjU5FvRZnXfWGLA4S3VJyXV6KtvStUgfp77ttNQhz0k1T2pAqvhEP85qXViRBMShByliB1sgYkkGuVogZKabJjDUjYS-QQmQLUeri2Fe-IYfUPHi5GhPkktGUn7oXRELIf3PuzIWjSsQj1nFTZm_WX_nnL37H_n7_AA) ]
[Question] [ # Background (Based on a true, heart-wrenching story) In my time, I've played around with Lisp and similar languages often. I've written with them, ran them, interpreted them, designed them, and made machines write with them for me... And if there is one thing that bothers me, it's seeing Lisp that does not comply with my specific formatting style. Unfortunately, some text editors (*cough* XCode *cough*) tend to strip my beautiful tabs and spaces whenever code is copied and pasted... Take this beautifully spaced Lisp-like syntax: ``` (A (B (C) (D)) (E)) ``` *(Where `ABCDE` are arbitrary functions)* *SOME* text editors butcher this lovely code to the following end: ``` (A (B (C) (D)) (E)) ``` What a mess! That's not readable! Help me out, here? # The Challenge Your goal in this challenge is to take a series of functions separated by newlines in a format described below and return a more beautiful arrangement that highlights readability and elegance. # The Input We define a function `F` of arity `N` arguments as a construct similar to the following: ``` (F (G1 ...) (G2 ...) (G3 ...) ... (GN ...)) ``` where `G1, G2, ..., GN` are all functions in and of themselves. An arity `0` function `A` is simply `(A)`, while an arity `2` function `B` is of the form `(B (...) (...))` Your code should take input as a series of functions with a single newline before every function's leading parenthesis (except for the first function). The example above is valid input. You may assume: * The parentheses are balanced. * A function will never have to be indented more than 250 times. * EVERY function is surrounded by parentheses: `()` * A function's name will only contain printable ASCII characters. * A function's name will never contain parentheses or spaces. * There is an optional trailing newline on input. # The Output Your code should output the **same** set of functions, where the only changes made are the additions of spaces or tabs before the leading parentheses of functions. Output should comply with the following rules: * The first function (and later top-level functions) given should have no preceding spaces * An argument to a function's horizontal location is exactly one tab to the right of that function's horizontal location. * A tab is implementation-defined, but must be at least 3 spaces. * You may optionally print a maximum of two spaces after each line. # Rules * This is code-golf: the shortest code wins! * [Standard Loopholes](http://meta.codegolf.stackexchange.com/q/1061/31054) are disallowed. # Examples *Input:* ``` (A (B (C) (D)) (E)) ``` *Output:* ``` (A (B (C) (D)) (E)) ``` *Input:* ``` (!@#$%^&* (asdfghjklm (this_string_is_particularly_long (...)) (123456789))) (THIS_IS_TOP_LEVEL_AGAIN (HERE'S_AN_ARGUMENT)) ``` *Output:* ``` (!@#$%^&* (asdfghjklm (this_string_is_particularly_long (...)) (123456789))) (THIS_IS_TOP_LEVEL_AGAIN (HERE'S_AN_ARGUMENT)) ``` *Input:* ``` (-:0 (*:0 (%:0 (Arg:6) (Write:0 (Read:0 (Arg:30)) (Write:0 (Const:-6) (Arg:10)))) (%:0 (Const:9) (/:0 (Const:-13) (%:0 (Arg:14) (Arg:0))))) (WriteArg:22 (-:0 (Const:45) (?:0 (Arg:3) (Arg:22) (Arg:0))))) ``` *Output:* ``` (-:0 (*:0 (%:0 (Arg:6) (Write:0 (Read:0 (Arg:30)) (Write:0 (Const:-6) (Arg:10)))) (%:0 (Const:9) (/:0 (Const:-13) (%:0 (Arg:14) (Arg:0))))) (WriteArg:22 (-:0 (Const:45) (?:0 (Arg:3) (Arg:22) (Arg:0))))) ``` [Answer] # Pyth, 24 20 19 18 bytes ``` FN.z+*ZC9N~Z-1/N\) ``` Increments a counter for every line, counts total number of closing parentheses encountered so far, and subtracts it from the counter. Then we indent by `counter` tabs. [Answer] # Common Lisp - ~~486~~ 414 bytes (Rube Goldberg version) ``` (labels((p(x d)(or(when(listp x)(#2=princ #\()(p(car x)d)(incf d)(dolist(a(cdr x))(format t"~%~v{ ~}"d'(t))(p a d))(#2# #\)))(#2# x))))(let((i(make-string-input-stream(with-output-to-string(o)(#1=ignore-errors(do(b c)(())(if(member(setq c(read-char))'(#\( #\) #\ #\tab #\newline):test'char=)(progn(when b(prin1(coerce(reverse b)'string)o))(#2# c o)(setq b()))(push c b))))))))(#1#(do()(())(p(read i)0)(terpri))))) ``` # Approach Instead of doing like everybody else and count parentheses by hand, let's invoke the Lisp reader and do it *The Right Way* :-) * Read from input stream and write to a *temporary* output stream. * While doing so, aggregate characters different from `(`, `)` or whitespace as strings. * The intermediate output is used to build a string, which contains syntactically well-formed Common-Lisp forms: nested lists of strings. * Using that string as an input stream, call the standard `read` function to build actual lists. * Call `p` on each of those lists, which recursively write them to the standard output with the requested format. In particular, strings are printed unquoted. As a consequence of this approach: 1. There are less restrictions on the input format: you can read arbitrarly formatted inputs, not just "one function per line" (ugh). 2. Also, if the input is not well-formed, an error will be signaled. 3. Finally, the pretty-printing function is well decoupled from parsing: you can easily switch to another way of pretty-printing S-expressions (and you should, if you value your vertical space). # Example Reading from a file, using this wrapper: ``` (with-open-file (*standard-input* #P"path/to/example/file") ...) ``` Here is the result: ``` (!@#$%^&* (asdfghjklm (this_string_is_particularly_long (...)) (123456789))) (THIS_IS_TOP_LEVEL_AGAIN (HERE'S_AN_ARGUMENT)) (-:0 (*:0 (%:0 (Arg:6) (Write:0 (Read:0 (Arg:30)) (Write:0 (Const:-6) (Arg:10)))) (%:0 (Const:9) (/:0 (Const:-13) (%:0 (Arg:14) (Arg:0))))) (WriteArg:22 (-:0 (Const:45) (?:0 (Arg:3) (Arg:22) (Arg:0))))) ``` *(it seems that tabs are converted to spaces here)* # Pretty-printed (golfed version) Contrary to the safer original version we expect input to be valid. ``` (labels ((p (x d) (or (when (listp x) (princ #\() (p (car x) d) (incf d) (dolist (a (cdr x)) (format t "~%~v{ ~}" d '(t)) (p a d)) (princ #\))) (princ x)))) (let ((i (make-string-input-stream (with-output-to-string (o) (ignore-errors (do (b c) (nil) (if (member (setq c (read-char)) '(#\( #\) #\ #\tab #\newline) :test 'char=) (progn (when b (prin1 (coerce (reverse b) 'string) o)) (princ c o) (setq b nil)) (push c b)))))))) (ignore-errors (do () (nil) (p (read i) 0) (terpri))))) ``` [Answer] # [Retina](https://github.com/mbuettner/retina), ~~89~~ 83 bytes ``` s`.+ $0<tab>$0 s`(?<=<tab>.*). <tab> +ms`^((\()|(?<-2>\))|[^)])+^(?=\(.*^((?<-2><tab>)+)) $0$3 <tab>+$ <empty> ``` Where `<tab>` stands for an actual tab character (0x09) and `<empty>` stands for an empty line. After making those replacements, you can run the above code with the `-s` flag. However, I'm not counting that flag, because you could also just put each line in its own source file, in which case the 7 newlines would be replaced by 7 penalty bytes for the additional source files. This is a full program, taking input on STDIN and printing the result to STDOUT. ## Explanation Every pair of lines defines a regex substitution. The basic idea is to make use of .NET's [balancing groups](https://stackoverflow.com/a/17004406/1633117) to count the current depth up to a given `(`, and then insert that many tabs before that `(`. ``` s`.+ $0<tab>$0 ``` First, we prepare the input. We can't really write back a conditional number of tabs, if we can't find them somewhere in the input string to capture them. So we start by duplicating the entire input, separated by a tab. Note that the `s`` just activates the single-line (or "dot-all") modifier, which ensures that the `.` also matches newlines. ``` s`(?<=<tab>.*). <tab> ``` Now we turn every character after that tab into a tab as well. This gives us a sufficient amount of tabs at the end of the string, without modifying the original string so far. ``` +ms`^((\()|(?<-2>\))|[^)])+^(?=\(.*^((?<-2><tab>)+)) $0$3 ``` This is the meat of the solution. The `m` and `s` activate multi-line mode (so that `^` matches the beginnings of lines) and single-line mode. The `+` tells Retina to keep repeating this substitution until the output stops changing (in this case, that means until the pattern no longer matches the string). The pattern itself matches a prefix of the input up to an unprocessed `(` (that is, a `(` that doesn't have any tabs before it, but should). At the same time it determines the depth of the prefix with balancing groups, such that the height of stack `2` will correspond to the current depth, and therefore to number of tabs we need to append. That is this part: ``` ((\()|(?<-2>\))|[^)])+ ``` It either matches a `(`, pushing it onto the `2` stack, or it matches a `)`, popping the last capturing from the `2` stack, or it matches something else and leaves the stack untouched. Since the parentheses are guaranteed to be balanced we don't need to worry about trying to pop from an empty stack. After we've gone through the string like this and found an unprocessed `(` to stop at, the lookahead then skips ahead to the end of the string, and captures tabs into group `3` while popping from the `2` stack until its empty: ``` (?=\(.*^((?<-2><tab>)+)) ``` By using a `+` in there, we ensure that the pattern only matches anything if at least one tab should be inserted into the match - this avoids an infinite loop when there are multiple root-level functions. ``` <tab>+$ <empty> ``` Lastly, we just get rid of those helper tabs at the end of the string to clean up the result. [Answer] # C: ~~95~~ 94 characters It's not very golfed yet, and from the question I'm unsure whether tabs are acceptable, which is what I use here. ``` i,j;main(c){for(;putchar(c=getchar()),c+1;i+=c==40,i-=c==41)if(c==10)for(j=i;j--;putchar(9));} ``` Ungolfed: ``` i,j; main(c){ for( ; putchar(c=getchar()), c+1; i+=c==40, i-=c==41 ) if(c==10) for( j=i; j--; putchar(9) ); } ``` Edit: Made it so that it quits on EOF. [Answer] # Julia, ~~103~~ ~~99~~ ~~97~~ ~~94~~ 88 bytes ``` p->(i=j=0;for l=split(p,"\n") i+=1;println("\t"^abs(i-j-1)*l);j+=count(i->i=='\)',l)end) ``` This defines an unnamed function that accepts a string and prints the indented version. To call it, give it a name, e.g. `f=p->...`. Note that the input must be a valid Julia string, so dollar signs (`$`) must be escaped. Ungolfed + explanation: ``` function f(p) # Set counters for the line number and the number of close parens i = j = 0 # Loop over each line of the program for l in split(p, "\n") # Increment the line number i += 1 # Print the program line with |i-j-1| tabs println("\t"^abs(i-j-1) * l) # Count the number of close parens on this line j += count(i -> i == '\)', l) end end ``` Example, pretending each set of four spaces is a tab: ``` julia> f("(A (B (C) (D)) (E))") (A (B (C) (D)) (E)) ``` Any suggestions are more than welcome! [Answer] # Haskell, ~~83~~ 81 ``` unlines.(scanl(\n s->drop(sum[1|')'<-s])$n++['\t'|'('<-s])"">>=zipWith(++)).lines ``` a very points free solution. [Answer] # Perl, 41 ``` $_="\t"x($i-$j).$_;$i+=y/(/(/;$j+=y/)/)/ ``` `40` characters `+1` for `-p`. Run with: ``` cat input.txt | perl -pe'$_="\t"x($i-$j).$_;$i+=y/(/(/;$j+=y/)/)/' ``` [Answer] # Python 2 - ~~88~~ 78 Bytes Fairly straightforward (and not very short) solution: ``` l=0 for x in raw_input().split():g=x.count;d=l*'\t'+x;l+=g("(")-g(")");print d ``` [Answer] # CJam, 20 bytes ``` r{_')e=NU)@-:U9c*r}h ``` Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=r%7B_')e%3DNU)%40-%3AU9c*r%7Dh&input=(!%40%23%24%25%5E%26*%0A(asdfghjklm%0A(this_string_is_particularly_long%0A(...))%0A(123456789)))%0A(THIS_IS_TOP_LEVEL_AGAIN%0A(HERE'S_AN_ARGUMENT))). ### How it works ``` r e# Read a whitespace-separated token R from STDIN. { }h e# Do, while R is truthy: _')e= e# Push C, the number of right parentheses in R. NU e# Push a linefeed and U (initially 0). )@- e# Compute U + 1 - C. :U e# Save in U. 9c* e# Push a string of U tabulators. r e# Read a whitespace-separated token R from STDIN. ``` ]
[Question] [ # Challenge Write a program or function that takes in a string `s` and integer `n` as parameters. Your program should print (or return) the string when transformed as follows: Starting in the top-left and moving down and to the right, write `s` as a wave of height `n`. Then, from top to bottom, combine each row as a string (without spaces). # Example Given the string "WATERMELON" and a height of 3: The wave should look like this: ``` W R O A E M L N T E ``` Then, combine the rows from top to bottom: ``` WRO AEMLN TE ``` So, your program should return the string "WROAEMLNTE" Likewise, "WATERMELON" with height 4 should produce the following wave: ``` W E A M L T R O E N ``` Your program should then return the string "WEAMLTROEN" # Rules ## Input Input can be taken in any reasonable format. The string can be in any case you prefer. You may assume that `0 < n <= s.length` ## Output Output should consist only of the transformed string (whether returned or printed to STDOUT), plus any trailing newlines. ## Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins! Standard loopholes are not allowed. # Test Cases ``` Input Output programmingpuzzles, 5 -> piermnlsomgzgapzru codegolf, 3 -> cgoeofdl elephant, 4 -> enlatehp 1234567, 3 -> 1524637 qwertyuiop, 1 -> qwertyuiop ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 16 bytes ``` Zv3L)t?yn:)2$S}i ``` [Try it online!](https://tio.run/##y00syfn/P6rM2EezxL4yz0rTSCW4NvP/f1Mu9YKi/PSixNzczLz0gtKqqpzUYnUA "MATL – Try It Online") Or [verify all test cases](https://tio.run/##y00syfmf8D@qzNhHs8S@Ms9K00gluDbzf2yES8h/Uy71gqL89KLE3NzMvPSC0qqqnNRidS5jLvXk/JTU9PycNHUuEy711JzUgozEvBKwjKGRsYmpmbk6lyGXemF5alFJZWlmfoE6AA). ### Explanation Consider inputs `5`, `'programmingpuzzles'`. ``` Zv % Input, implicit: number n. Symmetric range % STACK: [1 2 3 4 5 4 3 2 1] 3L % Push [1 -1+1j]. When used as an index, this means 1:end-1 % STACK: [1 2 3 4 5 4 3 2 1], [1 -1+1j] ) % Index. Removes last element % STACK: [1 2 3 4 5 4 3 2] t % Duplicate % STACK: [1 2 3 4 5 4 3 2], [1 2 3 4 5 4 3 2] ? % If non-empty and non-zero % STACK: [1 2 3 4 5 4 3 2] y % Implict input: string s. Duplicate from below % STACK: 'programmingpuzzles', [1 2 3 4 5 4 3 2], 'programmingpuzzles' n % Number of elements % STACK: 'programmingpuzzles', [1 2 3 4 5 4 3 2], 18 : % Range % STACK: 'programmingpuzzles', [1 2 3 4 5 4 3 2], [1 2 3 ··· 17 18] ) % Index modularly % STACK: 'programmingpuzzles', [1 2 3 4 5 4 3 2 1 2 3 4 5 4 3 2 1 2] 2$S % Two-input sort: stably sorts first input as given by the second % STACK: 'piermnlsomgzgapzru' } % Else. This branch is entered when n=1. The stack contains an empty array % STACK: [] i % Take input % STACK: [], [], 'programmingpuzzles' % End, implicit % Display stack, implicit. Empty arrays are not displayed ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 6 bytes ``` δÖK…¢ḣ ``` [Try it online!](https://tio.run/##ASQA2/9odXNr///OtMOWS@KApsKi4bij////NP8iV0FURVJNRUxPTiI "Husk – Try It Online") Works for `n = 1` as well. ## Explanation ``` δÖK…¢ḣ Implicit inputs, say n=4 and s="WATERMELON" ḣ Range: [1,2,3,4] ¢ Cycle: [1,2,3,4,1,2,3,4,1,2,3,4.. … Rangify: [1,2,3,4,3,2,1,2,3,4,3,2.. δÖK Sort s by this list: "WEAMLTROEN" Print implicitly. ``` The higher order function `δ` works like this under the hood. Suppose you have a higher order function that takes a unary function and a list, and returns a new list. For example, `Ö` takes a function and sorts a list using it as key. Then `δÖ` takes a binary function and two lists, zips the lists together, applies `Ö` to sort the pairs using the binary function as key, and finally projects the pairs to the second coordinate. We use `K` as the key function, which simply returns its first argument and ignores the second. [Answer] # [Haskell](https://www.haskell.org/), 64 bytes ``` s#n=[c|m<-[0..n],(c,i)<-zip s.cycle$[0..n-1]++[n-2,n-3..1],i==m] ``` [Try it online!](https://tio.run/##LY5LDsIgFAD3nsKgC4gPYq2fjXgCXbmsxBDESoRXLG2MjXev3@VkFjMXna7W@75PI5SFeYY1L6ZCoAJqwLE171wcJmEextvx1/BMTSYF8hkgz4XIFDgpg@odxrZJsqAk1lVZ6xAclrHtOm8TgQUDSkx1smXlzwTyD1pv40VjQ2D@wWyWzxfL1V/e7rZuHq2rIoGMqUHQDmXQcXekB5oAGd@8e/um3uL4/c5@@f4F "Haskell – Try It Online") [Answer] # [J](http://jsoftware.com/), 54, 29, 27 26 bytes -1 byte thanks to hoosierEE ``` ([\:#@[$[:}:|@i:@<:@]) ::[ ``` [Try it online!](https://tio.run/##bYzBCoJAFEX3fsWjgkmIQVMLHgnzH1OLSd@oMTriGIHkt08ULly0Pefe8/Da5RwiQIj8Xl5xK@RO4oxv0aC4oLiFgCh9GGw4MJ1zBgeYEbQLAipqC@ylRhpaMrZjoCH5S9OF9oOtBtW2TVf1z2ky5L42W2xhS6qs0esOGepr1Y3rSnxM0ux0Xs/UvSjpd4z9Bw "J – Try It Online") [Answer] # [R](https://www.r-project.org/), 68 bytes ``` function(s,n)intToUtf8(unlist(split(utf8ToInt(s),-(n:(2.9-n)-1)^2))) ``` [Try it online!](https://tio.run/##Xc5Na4QwEAbg@/4K8WICWvBjd9uCBw85FPwAsexlKYibZANxkmpCqX/eiod2m7nNvDzMO60sX5mFwQgFaA4BCzCdejfsGVmQYjZo1lIYZLdLp95g23EYIXhFydNLBDiK8UeCMV4Z8i9FR9qKlE3thyn2fifPveDSNgWpyrojwWHoDQquEOCDgzIXkaIqu7YhtYP0pPjUj6MAru2ySDr7oXfEO9KCTiPIWY184b1eJuvgQd0oV5Jt5LHljgeuqGI36RAqqb73YDaSeU5JCrI39K4dEidpdjyd3Sc7iY9JdkrPjvj8opP5tkLpDcX4n/jLHtD6Aw "R – Try It Online") * -10 bytes thanks to @Giuseppe * -17 bytes because I was silly * -9 bytes and `n=1` case fixed thanks to @J.Doe * -3 bytes thanks to @JayCe [Answer] # [Python 2](https://docs.python.org/2/), ~~119~~ ~~108~~ ~~98~~ ~~92~~ ~~91~~ ~~97~~ ~~93~~ ~~91~~ 90 bytes ``` lambda s,n:''.join(c*(j%(2*n-2or 1)in(i,2*n-i-2))for i in range(n)for j,c in enumerate(s)) ``` [Try it online!](https://tio.run/##dZBLb4MwEITPya9YqaqAyKnANpBUaqUcuOUhoUi99EKJIY7Atgw5lD9PndDW9JG97Wi@2dWo9/YoBe6Lp9e@yuq3QwYNEo@O83CSXLj5zD3du3gm5lhqCDwjcXRZ@Rx7XmE0DlyAzkTJXHEVTii/SEyca6azlrmN5/VKc9FC4Tovq32SbpL1busgkwd382e4jNWn/3vJyJvuVslmvd0nN7x05E1Wm/U@3SWjXKVlqbO65qJU566rWGOY0DKKM12LqpF12ZWZ6vTZsrk8sFJWxfCRnS82LyWTxaGyBKuYOmaiHf76SzBRmZaOyhIBJjSM4t8nvokgxDQi8dQS/ieyWP5syqcLCEgYLwFHk4kPASKAb2Cj0vzI3IgBG5osBy4EjCiQG@yoPN9cvN4DEgIdYBOFzG5CaP8B "Python 2 – Try It Online") -1 byte, thanks to Jonathan Frech [Answer] # [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~11~~ 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` Σ²Lû¨¾è¼ ``` Inspired by [*@LuisMendo*'s MATL answer](https://codegolf.stackexchange.com/a/174122/52210). -3 bytes thanks to *@Adnan* [Try it online.](https://tio.run/##AS0A0v8wNWFiMWX//86jwrJMw7vCqMK@w6jCvP//cHJvZ3JhbW1pbmdwdXp6bGVzCjU) (No test suite, because the legacy version of 05AB1E didn't had a reset for the `counter_variable`.) **Explanation:** ``` Σ # Sort the (implicit) input-string by: ²L # Create a list in the range [1, second input-integer] # i.e. 5 → [1,2,3,4,5] û # Palindromize it # i.e. [1,2,3,4,5] → [1,2,3,4,5,4,3,2,1] ¨ # Remove the last item # i.e. [1,2,3,4,5,4,3,2,1] → [1,2,3,4,5,4,3,2] ¾è # Index into it (with wraparound) using the counter_variable (default 0) # i.e. counter_variable = 0 → 1 # i.e. counter_variable = 13 → 4 ¼ # And after every iteration, increase the counter_variable by 1 ``` NOTE: The `counter_variable` is used, because in the Python Legacy version of 05AB1E, the `Σ` didn't had an index `N`, which it does have in the new Elixir rewrite version of 05AB1E. So why do I still use the Legacy version? Because in the Elixir rewrite it has a bug and doesn't sort for \$n=1\$, which would all result in an empty list `[]` after the indexing. All other test cases work as intended with `Σ²Lû¨Nè`: [try it online](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWVC6P9ziyN8Du8@tMLv8Ir/tTr/o6OVwh1DXIN8XX38/ZR0jGN1FFBFTMAiBUX56UWJubmZeekFpVVVOanFSjqmYJnk/JTU9PycNJje1JzUgozEvBKYTkMjYxNTM3OQdCwA), but the test case with \$n=1\$ times out without result, even with `--no-lazy` argument flag: [try it online](https://tio.run/##ASwA0/9vc2FiaWX//86jwrJMw7vCqE7DqP//cXdlcnR5dWlvcAox/y0tbm8tbGF6eQ). [Answer] # [Japt](https://github.com/ETHproductions/japt), 16 bytes ``` ¬üÏu´VÑ aV°ÃÔc q ``` [Test it online!](https://ethproductions.github.io/japt/?v=1.4.6&code=rPzPdbRW0SBhVrDD1GMgcQ==&input=IldBVEVSTUVMT04iCjM=) ### Explanation ``` ¬ üÏ u´ VÑ aV° Ã Ô c q Uq üXY{Yu--V*2 aV++} w c q Ungolfed Implicit: U = input string, V = size of wave Uq Split U into chars. üXY{ } Group the items in U by the following key function: Y Take the index of the item. u--V*2 Find its value modulo (V-1) * 2. aV++ Take the absolute difference between this and (V-1). This maps e.g. indices [0,1,2,3,4,5,6,7,...] with V=3 to [2,1,0,1,2,1,0,1,...] The items are then grouped by these values, leading to [[2,6,...],[1,3,5,7,...],[0,4,...]]. w Reverse the result, giving [[0,4,...],[1,3,5,7,...],[2,6,...]]. c Flatten. q Join back into a single string. ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) *6 byter fails for height 1; two bytes used to address it ...maybe a 7 can be found?* ``` ŒḄṖȯ1ṁỤị ``` A dyadic link accepting a positive integer and a list of characters which yields a list of characters. **[Try it online!](https://tio.run/##ATQAy/9qZWxsef//xZLhuIThuZbIrzHhuYHhu6Thu4v///81/yJwcm9ncmFtbWluZ3B1enpsZXMi "Jelly – Try It Online")** ### How? ``` ŒḄṖȯ1ṁỤị - Link: positive integer N; list of characters, T ŒḄ - bounce (implicit range of) N -> [1,2,3,...,N-1,N,N-1,...,3,2,1] Ṗ - pop off the final entry [1,2,3,...,N-1,N,N-1,...,3,2] ȯ1 - OR one if this is [] get 1 instead ṁ - mould like T (trim or repeat to make this list the same length as T) Ụ - grade-up (get indices ordered by value - e.g. [1,2,3,2,1,2] -> [1,5,2,4,6,3]) ị - index into T ``` [Answer] # JavaScript (ES6), 75 bytes *Shorter formula suggested by @MattH (-3 bytes)* Takes input as `(string)(n)`. ``` s=>n=>--n?[...s].map((c,x)=>o[x=x/n&1?n-x%n:x%n]=[o[x]]+c,o=[])&&o.join``:s ``` [Try it online!](https://tio.run/##Zc7RioMwEAXQ9/2KUliJtEas2kIh9kMk0JDGNCXOZBNtXX/ezT51cQfm5Q6HOw/xFEF644YM8KaWji2BNcCaLINLSykNnPbCESL3U8oabCc25ZAUF8imTzjH5ayNKec7uUfW8jRJkD7QwPV6DotECGgVtahJR7bOo/ai7w1oN86zVWGbkjpNN3m@cUb5HmzAXs9auNmPHyst44MabRdNGc17opYaFXY3uzbKKncXMERTrY0CKwZ1d2tTHMqqPp7@1fyaoj5Ux/K0Jl8v5Yfv0aCLqvijInnflh8 "JavaScript (Node.js) – Try It Online") --- # JavaScript (ES7), 78 bytes *Saved 4 bytes thanks to @ETHproductions* Takes input as `(string)(n)`. ``` s=>n=>--n?[...s].map((c,x)=>o[x=n*n-(x%(n*2)-n)**2]=[o[x]]+c,o=[])&&o.join``:s ``` [Try it online!](https://tio.run/##Zc7fasIwGAXw@z2FCJOk2kj/KQjpHqQUDDGNkfT7sqR1XV@@y64c3bk9/DjnIZ4iSG/ckALe1NLxJfAaeJ2m8NEwxkLLeuEIkYeJ8hqbiUMCKZneCSQ5TYEmSd7yJhZtu5cH5E1LdztkDzRwvV7CIhECWsUsatKRrfOoveh7A9qN82xV2FJSUbo5HjfOKN@DDdjrWQs3@/FtpWX8qNF20RTRvBK11Kiwu9m1UVa5u4AhmnJtFFgxqLtbmywvyup0/jfza7IqL0/FeU0@v5QfvkeDLqrsj4rk1S0/ "JavaScript (Node.js) – Try It Online") [Answer] # K ( [Kona](https://github.com/kevinlawler/kona) ), 23 bytes A translation of the [J answer by Galen](https://codegolf.stackexchange.com/a/174121/18872) ``` {y@<(#y)#-1_(!x),|!x-1} ``` [Answer] # [MBASIC](https://archive.org/details/BASIC-80_MBASIC_Reference_Manual), ~~146~~ ~~159~~ 155 bytes ``` 1 INPUT S$,N:DIM C$(N):P=1:D=1:FOR I=1 TO LEN(S$):C$(P)=C$(P)+MID$(S$,I,1) 2 IF N>1 THEN P=P+D 3 IF P=N OR P=1 THEN D=-D 4 NEXT:FOR I=1 TO N:PRINT C$(I);:NEXT ``` Updated to handle n=1 Output: ``` ? programmingpuzzles, 5 piermnlsomgzgapzru ? codegolf, 3 cgoeofdl ? elephant, 4 enlatehp ? 1234567, 3 1524637 ? WATERMELON, 4 WEAMLTROEN ? qwertyuiop, 1 qwertyuiop ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 49 bytes ``` ->\n{*.comb.sort({-abs n-1-$++%(2*n-2||1)}).join} ``` [Try it online!](https://tio.run/##ddDJbsIwFIXhfZ7iig6yQY5qZ2CBypOwMcExQZ5qJyoJ8OypaRGhC8726tOVfie8Kkfdw3sNnzCS9cac5mll9TYN1rfoRPg2gCGUvC4Wb4jNDWHnM8UXnB5sYy5j4D3UqMBo5ryVnmvdGOm6YVAizPAKXoCs4TrXCK@NClbLQXI3@C75s1m0ld0JaVV9FdPutpJW2HqnbiKPQijh9ty0T4Qwirdi7x5@UJblRbn8DyZBC5aX2fIGaARf38K3fddY92juYDonSQy4MTFgsfr16Ek1DMcjsI/xBw "Perl 6 – Try It Online") Takes input as a curried function. ### Explanation: ``` ->\n{*.comb.sort({-abs n-1-$++%(2*n-2||1)}).join} ->\n{ } # Take an number *.comb # Turn the string into a list of chars .sort({ }) # And sort them by $++ # The index of the char %(2*n-2||1) # Moduloed by 2*(n-1) or 1 if n is 0 n-1- # Subtract that from n-1 abs # get the absolute value - # And negate to reverse the list .join # and join the characters ``` The sequence that it is sorted by looks like this (for `n=5`): ``` (-4 -3 -2 -1 0 -1 -2 -3 -4 -3 -2 -1 0 -1 -2 -3 -4 -3 -2 -1) ``` [Answer] # [J](http://jsoftware.com/), 24 bytes ``` 4 :'x\:(#x)$}:|i:<:y'::[ ``` [Try it online!](https://tio.run/##bc1RC4IwEMDx9z7FUcEKKlJnwVGfpF7EbtOYbk0lG/XZTUNIo4N7@R8/7tpMN8AEHJHBCl4IW2i34YCsPuNiVi/nL3ymeMAHQzw1ywnFiQZmUrJZrgqdSScj42zFYI1tt1raKMvSXJrKOUUFAwFhr2KpSYuLYvCdTsX6QlIrMewCgl5RrqKSEvOrSJFJorwcK94rL/T5LtgPjx/l@QEPd@P@/XW7ky0fVaoH3zr1rwvwmjc "J – Try It Online") Explicit dyadic verb. Run it like `'codegolf' f 3`. ### How it works ``` 4 :'x\:(#x)$}:|i:<:y'::[ x: string, y: height 4 : Define a dyadic verb: i:<:y Generate a range of -(y-1) .. y-1 }:| Take absolute value and remove last (#x)$ 1) Repeat to match the string's length x\: Sort x by the decreasing order of above ::[ If 1) causes `Length Error`, return the input string instead ``` Normally, explicit function takes additional 5 bytes in the form of `n :'...'`. But if error handling is added, the difference goes down to 2 bytes due to the parens and space in `(tacit)<space>::`. [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), 23 bytes ``` {⍺[⍋(≢⍺)⍴(¯1↓⊢,1↓⌽)⍳⍵]} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v8/7VHbhOpHvbuiH/V2azzqXARkaj7q3aJxaL3ho7bJj7oW6YDpnr1A0c2PerfG1v7/r16eWJJalJuak5@nrpCmYMyFJmDCpV5QlJ9elJibm5mXXlBaVZWTWgySMOVST85PSU3Pz0mDakzNSS3ISMwrgWozNDI2MTUzh0omJiWnpIJVGgIA "APL (Dyalog Classic) – Try It Online") [Answer] # Powershell, ~~99~~ 95 bytes ``` param($s,$n)$r=,''*$n $s|% t*y|%{$r[((1..$n+$n..1)*$s.Length|gu)[$i++*($n-gt1)]-1]+=$_} -join$r ``` Test script: ``` $f = { param($s,$n)$r=,''*$n $s|% t*y|%{$r[((1..$n+$n..1)*$s.Length|gu)[$i++*($n-gt1)]-1]+=$_} -join$r } @( ,("1234567", 3 , "1524637") ,("qwertyuiop", 1 , "qwertyuiop") ,("codegolf", 3 , "cgoeofdl") ,("elephant", 4 , "enlatehp") ,("programmingpuzzles", 5 , "piermnlsomgzgapzru") ) | % { $s,$n,$e = $_ $r = &$f $s $n "$($r-eq$e): $r" } ``` Output: ``` True: 1524637 True: qwertyuiop True: cgoeofdl True: enlatehp True: piermnlsomgzgapzru ``` ## Explanation The script: * creates an array of rows, * fills rows with appropriate values, * and returns the joined rows. The expression `((1..$n+$n..1)*$s.Length|gu` generates a sequence like `1,2,3,3,2,1,1,2,3,3,2,1...` and removes adjacent duplicates. `gu` is alias for [Get-Unique](https://docs.microsoft.com/en-us/powershell/module/Microsoft.PowerShell.Utility/Get-Unique). * For `$n=3` the deduplicated sequence is: `1,2,3,2,1,2,3,2,1...` * For `$n=1` the deduplicated sequence is: `1` The expression `$i++*($n-gt1)` returns an index in the deduplicated sequence. `=$i++` if `$n>1`, otherwise `=0` [Answer] # [Ruby](https://www.ruby-lang.org/), ~~75~~ 65 bytes ``` ->s,h{a=['']*h;x=-k=1;s.map{|c|a[x+=k=h-x<2?-1:x<1?1:k]+=c};a*''} ``` [Try it online!](https://tio.run/##dc5Li4MwFIbh/fwKcSO0tRAvLdRmigt3XkCELsRFxsZEjCYTlbG2/e3OoikMhVmf5z18cvy6LhVczM9@Q28I5oZRrKg3QbOBwOu3LRK3e3lH@bSGDaTmdLROJjhMR3ACh6ZYw/LhoZVhPBahVbl@9rMgjYIwifVtSZHsN3ahQajp5zTxgyiMs0D/@Ec6SgZ@FGZpEsRKCsmJRG1bd0SM88xw/yrcZyFqLNuO9bwlM0FilqMqS37BhLPqbUtJOObVhSmFGRYUdcPbDtwxNGAqlAKW7bi7/dsr4FrOzt4r8/2D5XAday5eDDzZn8PyCw "Ruby – Try It Online") Takes input as an array of chars, returns string How it wokrs: * Create `h` strings * For each character in the input string, decide which string to put it in based on its index (the index of the string to be modified goes up until `h` and then down until `0` and so on) * Return all the strings joined together [Answer] # C, ~~142~~ 134 bytes *8 bytes saved thanks to Jonathan Frech* Code: ``` t;i;j;d;f(s,n)char*s;{for(t=strlen(s),i=0;i<n;i++)for(j=0;j+i<t;j=d+i+(n<2))d=j-i+2*~-n,putchar(s[i+j]),i>0&i<n-1&d<t&&putchar(s[d]);} ``` Explanation: ``` // C variable and function declaration magic t;i;j;d;f(s,n)char*s;{ // Iterate through each "row" of the string for(t=strlen(s),i=0;i<n;i++) // Iterate through each element on the row // Original index iterator here was j+=2*(n-1), which is a full "zig-zag" forward // The (n<2) is for the edge case of n==1, which will break the existing logic. for(j=0; j+i<t; j=d+i+(n<2)) // If j+i is the "zig", d is the "zag": Original index was d=j+i+2*(n-i-1) // Two's complement swag here courtesy of Jonathan Frech d=j-i+2*~-n, putchar(s[i+j]), // Short circuit logic to write the "zag" character for the middle rows i>0 & i<n-1 & d<t && putchar(s[d]); } ``` [Try it online!](https://ideone.com/yxer15) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 21 bytes ``` ⭆NΦη¬⌊E²﹪⁺μ⎇νι±ι∨⊗⊖θ¹ ``` [Try it online!](https://tio.run/##LYxNC8IwEETv/oocNxAP6tGT0AqCaYsWPKftUgP5qOtG8NfHFJzLPJjHjE9DYzQu545sYLhzqVmbBS5hSdwkPyCBVOJsHRd6KtFEBm2D9cnDKu6V0HFKLkLn0hu8Ej1SMPSFoIQtPs6GEayU5aYlqGIaHE5Q4UjoMXDh17rt5D/HnA@bx6mvb7q@tk3eftwP "Charcoal – Try It Online") Link is to verbose version of code. Works by noting that indices \$ m \$ of the characters on line \$ i \$ satisfy the relation \$ m \pm i = 0 \pmod {2n - 2} \$. Explanation: ``` N First input as a number ⭆ Map over implicit range and join η Second input Φ Filter over characters ² Literal 2 E Map over implicit range μ Character index ι ι Outer index ± Negate ν Inner index ⎇ Ternary ⁺ Plus θ First input ⊖ Decremented ⊗ Doubled ¹ Literal 1 ∨ Logical Or ﹪ Modulo ⌊ Minimum ¬ Logical Not Implicitly print ``` [Answer] # [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), 191 bytes ``` S =INPUT N =INPUT A =ARRAY(N) A<1> =EQ(N,1) S :S(O) I I =I + -1 ^ D S LEN(1) . X REM . S :F(O) A<I> =A<I> X D =EQ(I,N) 1 D =EQ(I * D,1) :(I) O Y =Y + 1 O =O A<Y> :S(O) OUTPUT =O END ``` [Try it online!](https://tio.run/##PY7LCsIwEEXXyVfcZaJVKHRVmkIgEQKaaFuh2QgKBRelFfT/41ikm3kezsx7mh/zWKTEWijnz9eOM79WGko3jY7CS2qqvIayF@GzXKJlZSuC5I45wrHFLscNhpPnaL0gYo8ejT1RJvbwY0nhSLHEnjOz2FzmJfK1wwaG/KwUTvLAIlQkOe0DVICuYv0/zMK1oydpyq03KQ3j8Hrepw8vvg "SNOBOL4 (CSNOBOL4) – Try It Online") Takes `S` then `N` on separate lines. ### Explanation: ``` S =INPUT ;* read S N =INPUT ;* read N A =ARRAY(N) ;* create array of size N A<1> =EQ(N,1) S :S(O) ;* if N = 1, set A<1> to S and jump to O I I =I + -1 ^ D ;* index into I by I + (-1)^D (D starts as '' == 0) S LEN(1) . X REM . S :F(O) ;* extract the first character as X and set S to the ;* remaining characters, jumping to O when S is empty A<I> =A<I> X ;* set A<I> to A<I> concatenated with X D =EQ(I,N) 1 ;* if I == N, D=1 D =EQ(I * D,1) :(I) ;* if I == D == 1, D = 0. Goto I O Y =Y + 1 ;* increment the counter O =O A<Y> :S(O) ;* concatenate the array contents until last cell OUTPUT =O ;* and print END ``` [Answer] # [Clean](https://github.com/Ourous/curated-clean-linux), ~~105~~ 84 bytes ``` import StdEnv,Data.List $s n=[c\\l<-[1..n],c<-s&m<-cycle([1..n]++[n-1,n-2..2])|m==l] ``` [Try it online!](https://tio.run/##JcxPC4IwGIDxe59iB8lCN9Cu7hDoIbA/ZNBh7vAyNQbba7gVCH32VuDx@R0eZXrAYMfuZXpiQWPQ9jlOnjS@q/CdluCB1dr5VeQIcqHa1hRUZIyhTFVB3doWVM3K9JsFk0QgzVKkOWO53H4s50aGxsP/yUlERHzf36rrsarPp1iSXfiqwcDDBXqoQzkjWK2WuBjwwzjZHw "Clean – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), 83 bytes ``` c=>g=(s,d=c*2-2,r=d,n=o='')=>s&&([...s].map((c,i)=>i%d%r?n+=c:o+=c),o)+g(n,r-1,r-2) ``` [Try it online!](https://tio.run/##bc5Rb8IgEAfw930KY6LCpJjSVhMT3AdZ9kCAIgY4Bq3L@uU7fHK6XXL38L/8cncRV5FlsnGoAig993yW/GQ4ykRx@coqRhJXJHDgmw3mp7xeo3dKaf6gXkSEJLEltSu1Sm9hy@URysAE8NagQFJVl2Z4lhAyOE0dGNSjDqNlTGCS8N4GE8dpcjovMV7sdotodfLBZfBmMiJOaXx51E3RsvxqwPU3c6@ipQENvXJPpi1GOx3PIgx/jA5ODPoc/7lTs6bt9odHcjN1x9p9c3gidSGfXzoN36OF@FsVcl/MPw "JavaScript (Node.js) – Try It Online") [Answer] # [Pyth](https://github.com/isaacg1/pyth), ~~22~~ 21 bytes ``` |seMhD,V*lz+PUQP_UQzz ``` Takes input as `n` followed by `s` on separate lines. Try it online [here](https://pyth.herokuapp.com/?code=%7CseMhD%2CV%2alz%2BPUQP_UQzz&input=3%0AWATERMELON&debug=0), or verify all the test cases at once [here](https://pyth.herokuapp.com/?code=%7CseMhD%2CV%2alz%2BPUQP_UQzz&test_suite=1&test_suite_input=5%0Aprogrammingpuzzles%0A3%0Acodegolf%0A4%0Aelephant%0A3%0A1234567%0A1%0Aqwertyuiop&debug=0&input_size=2). ``` |seMhD,V*lz+PUQP_UQzz Implicit: Q=eval(input()), z=remaining input UQ Range [0-Q) P All but last from the above e.g. for Q=3, yields [0,1] P_UQ All but last of reversed range e.g. for Q=3, yields [2,1] + Concatenate the previous two results e.g. for Q=3, yields [0,1,2,1] *lz Repeat len(z) times ,V z Vectorised pair the above with z, truncating longer to length of shorter e.g. for Q=3, z=WATERMELON, yields: [[0,'W'],[1,'A'],[2,'T'],[1,'E'],[0,'R'],[1,'M'],[2,'E'],[1,'L'],[0,'O'],[1,'N']] hD Sort the above by the first element Note this is a stable sort, so relative ordering between equal keys is preserved eM Take the last element of each s Concatenate into string Note that if n=1, the result of the above will be 0 (sum of empty array) | z If result of above is falsey, yield z instead ``` *Edit: saved a byte by moving the empty check to the end of processing. Previous version:* `seMhD,V*lz|+PUQP_UQ]0z` [Answer] # [Red](http://www.red-lang.org), 153 bytes ``` func[s n][i: v: m: 1 b: collect[foreach c s[keep/only reduce[v i c]v: v + m if all[n > 1(i: i + 1)%(n - 1)= 1][m: -1 * m]]]foreach k sort b[prin last k]] ``` [Try it online!](https://tio.run/##VYzNSgMxFIX38xSHgUJVisS2CoH6EG5DFmnmZhomfyaZkfblx7jQ4upyvnPul2lYP2gQsjN8NXPQoiBIYTkWDs/BcObQ0TnSVZiYSekLNIqYiNJzDO6KTMOsSSyw0LJ9LXiC76yBck4EvINtm842yh4224BduycwKZp@x/AIL6X8VU8oMVecRco2wKlSMUm5/qQKgz7lOGblvQ1jmm83R6XHsfurdRxojM702N8hOUoXFWqPwx2yl/3h@Pr2b/j5RbleZxtTD9at3w "Red – Try It Online") ## Explanation: ``` f: func [ s n ] [ ; s is the string, n is the height i: 1 ; index of the current character in the string v: 1 ; value of the "ladder" m: 1 ; step (1 or -1) b: collect [ ; collect the values in a block b foreach c s [ ; foreach character in the string keep/only reduce [ v i c ] ; keep a block of the evaluated [value index char] i: i + 1 ; increase the index v: v + m ; calculate the value if all [ n > 1 ; if height is greater than 1 and i % (n - 1) = 1 ; we are at a pick/bottom of the ladder ] [ m: -1 * m ] ; reverse the step ] ] foreach k sort b [ prin last k ] ; print the characters in the sorted block of blocks ] ``` [Answer] I have two solutions to the problem. The first solution I did first then I thought of another way to do it that I thought would save bytes but it didn't so I included it anyway. --- # Solution 1 ## [PHP](https://php.net/), ~~152~~ ~~144~~ 116 bytes ``` <?php for($i=0;$i<$n=$argv[2];$i++) for($j=$i;$s=$argv[1][$j];$j+=$n<2|(($f=!$f|!$i)?$i<$n-1?$n+~$i:$i:$i)*2) echo $s; ``` * 8 bytes thanks to @JoKing * 28 bytes thanks to @Shaggy [Try it online!](https://tio.run/##LcxLCsMgAIThqyQwC60UGqGbqniQkEUo8UWjorSLEHp1G0JhNj8fTHa5Namzy51JhcCrm4CXiApzsZ@RT0cyRk8MCl6g/mmYRoSDA1OIku@EwKgeZu/hqT5ProNGZF/4xzl64XR5utShitZaLsmWeV19tPm9ba@ltvsP "PHP – Try It Online") --- # Solution 2 ## [PHP](https://php.net/), 162 bytes ``` <?php $s=$argv[0]; $n=$argv[1]; $l=strlen($s); for($i=0;$i<$l;){ for($j=0;$j<$n&&$i<$l;) $a[$j++].=$s[$i++]; for($j=$n-2;$j>0&&$i<$l;) $a[$j--].=$s[$i++]; } echo join($a); ``` [Try it online!](https://tio.run/##VY1BC8IgAEb/yg4fY2MYa9DJuX6I7CCxnOJUtDos@u1m4aFuj8eD51ef0nj2q68QGUSQD36cKWzhIbNh8RbMYhvEll5daKBYT6FGGNo@v0J/hB5h67p4CA7ddfOBIXKoTLSUsGTI8dT/t4T8tq/lsrpKO5WvoqUpJR@cDGLblJX@vu9mien0Bg "PHP – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 84 bytes ``` ->s,n{r=['']*n;[*0...n,*(2-n)..-1].map{|x|r[x.abs]+=s.slice!(0)||''}while s[0];r*''} ``` [Try it online!](https://tio.run/##ZY7NaoNAFEb3PoVZjVq9aNS0RQx0kV2SQih0MczCmPEHxnGYidSoeXZrSa2LLu8558Inm/NtzOLR2Sqb9zLGCBGLR9hyAYDblrF2uAngeASqRPRDO0jcQnJW5ClWoFiZ0pXhmsOA0P2rKBnVFXZJJK3pHg0PIDDnR9FclZ5h9Pn2sTsddvv3I7L1lty1H6HNVsg6l0lVlTwXTdcxqqYqJH8@rS80r1k2UX@hlFFRJPw60WCh3toPws3zkmqGDxD@W@T@hi@vj0XjNw "Ruby – Try It Online") ]
[Question] [ Letter dice are common in word games. It can be fun to try to spell funny words with boggle dice, for instance. If you grab a handful of dice, chances are you won't be able to spell certain words. This challenge is a generalization of that idea. # Challenge Given a list of dice which each have at least 1 face and a word, your task is to determine if it is possible to spell that word using the given dice (in which case, it should return a truthy result). Only one letter from each die can be used and a die can be used only once. You do not need to use all of the given dice. # Examples In a trivial example, with the dice [[A], [C], [T]] and the string CAT, the result is true. BAT would, of course, return false since there are no dice with B on them If given [[A, E, I, O, U], [A, B, C, T], [N, P, R]] as the set of dice, you would return true for ART, TON, and CUR, but false for CAT, EAT, and PAN because those strings require reusing dice. It should also be fairly obvious that CRAB cannot be spelled with these dice since there are not enough dice. If given [[A, B, C], [A, E, I], [E, O, U], [L, N, R, S, T]] as the set of dice, you would be able to spell CAT, BEE, BEAN, TEA, BEET, and BAN, but you would not be able to spell LONE, CAB, BAIL, TAIL, BAA, or TON There may be multiples of the same die. If given [[A, B, C], [A, B, C], [A, B, C]], you would be able to spell CAB, BAA, AAA, etc... but obviously nothing without A, B, or C in it. # Rules * No exploiting standard loopholes * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code wins. * You may assume that both words and dice will only be made up of capital letters. * You may assume that the word will always be at least 1 letter long and that there will always be at least 1 die. * You may assume that a die will never have more than one of the same letter. * Input and output may be in any convenient format. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 5 bytes ``` ∋ᵐ⊇pc ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r//1FH98OtEx51tRck//8fHa3kqKSj5ATEzkqxOhCeKxB7gnkglj8Qh4J5PkCWHxAHAXEwEIcoxcb@V3JydfRTAgA "Brachylog – Try It Online") We use the input variable for the dice and the output variable for the word. It outputs `true.` when it's possible to spell the word and `false.` otherwise. ### Explanation ``` ∋ᵐ Map element: Take one side from each die ⊇ Subset p Permute c Concatenate into a string: will only succeed if it results in the output word ``` [Answer] # [Haskell](https://www.haskell.org/), ~~48~~ 44 bytes ``` import Data.List (.mapM id).any.(null.).(\\) ``` This is an anonymous function. Bound to some identifier `f` it can be used as `f "ART" ["AEIOU", "ABCT", "NPR"]`, which yields `True`. [Try it online!](https://tio.run/##JY7BDoIwEETvfsWm8dAG7R9gUpCDCQJBOImHRiA0QiG0xPj1lbant5nZ3ZmBq083jsaIaZlXDVeuOU2F0oc@xHTiyx1ESyiXP4rlNo6UUNw0xLTi3UEIT8SSW16jEyAWxZVlVpToddCd0sovOJWVDlWeWcR16eC9xKNg3itZtD@YuJD7vWuAGwXnCyybfug1lXAEBUEAyIrITmqYv4D7Xba9CAEXb/4 "Haskell – Try It Online") The non-point-free equivalent is ``` f word dice = any(\s -> null $ word\\s) $ mapM id dice ``` `mapM id` over a list of lists uses the `Monad` instance of list and can be seen as [non-deterministic choice](https://en.wikibooks.org/wiki/Haskell/Understanding_monads/List). Thus e.g. `mapM id ["AB","123"]` yields `["A1","A2","A3","B1","B2","B3"]`. For each of those dice combinations, we check if the list difference [`(\\)`](http://hackage.haskell.org/package/base-4.11.1.0/docs/Data-List.html#v:-92--92-) of the given word and the combination yields an empty list. [Answer] ## JavaScript (ES6), 68 bytes ``` f=([c,...w],a)=>!c||a.some((d,i)=>d.match(c)&&f(w,a.filter(_=>i--))) ``` ``` <div oninput=o.textContent=f(i.value,d.value.split`\n`)> <textarea id=d rows=9> ABC AEI EOU LNRST </textarea> <br> <input id=i value=BEAN> <pre id=o>true ``` [Answer] # [Python 2](https://docs.python.org/2/), 82 bytes ``` f=lambda d,w:w==''or any(w[0]in x>0<f(d[:i]+d[i+1:],w[1:])for i,x in enumerate(d)) ``` [Try it online!](https://tio.run/##HUrBCoMwFLvvK96tLSvD7VjmoEoPglTYulPx4KiyglZxjurXu3aBJC95mbblPbrLvndp3wwv04Chnvk0RWicoXEb9jqprYP1llw7bDSz9dFoezyzmnodlHRhaOkKYdS679DOzdJiQ8geHz7WKOcKMsEjJaj/IUITQllJATnPQihKUFEyzkFVEp0@U28XTNgBAqbZugU6rBHPckQBcVFEE9UzWinvD4VqCp7sPw "Python 2 – Try It Online") ``` f=lambda d,w:w=='' # Base case: we can spell '' with any dice. or any( for i,x in enumerate(d)) # Otherwise, we check if there is some die x such that... w[0]in x # the first letter is on this die, >0< # and f(d[:i]+d[i+1:],w[1:]) # we can spell the rest of the word with the rest of the dice. ``` The comparison chain `w[0]in x>0<f(...)` is equivalent to: `w[0]in x` **and** `x>0` **and** `0<f(...)`. The second of those is always true (`str` > `int`) and the third of those is equivalent to `f(...)`, so that the whole thing is a shorter way to write `w[0]in x and f(...)` [Answer] # JavaScript (ES6), 74 bytes Takes input in currying syntax `(w)(a)`, where **w** is the word we're looking for and **a** is a list of strings describing the dice. Returns **0** or **1**. ``` w=>P=(a,m='')=>w.match(m)==w|a.some((w,i)=>P(a.filter(_=>i--),m+`[${w}]`)) ``` [Try it online!](https://tio.run/##nZPRaoMwFIbv@xS9GCRh6htEOJEMBIni0iuRNThdLaYWdQtj27O7dmN0o2U0uTqQ5OM/OV@yVS9qrIZ2P/m7/rGeGzobGmYUK09ThAgNTaDVVG2wJpSadxWMva4xNl572MuwCpq2m@oBP9Cw9X3i6dt1cfNmPso1IXPV78a@q4Ouf8KokMPztHktEVn8Xm8wglwissQFAh6nK@QtEbBIHqvIclSSM0Cmwg6IVrklAD8tsejrOI@PhX/Dicjv5SWMce6GweFC1ph0TePSIY2BuCpt8df6nerGS9JPE75SCbcFMrB8JUkquMNgImBOGiBOXKS7YQzApcnTT/sXmz8B "JavaScript (Node.js) – Try It Online") ### Commented We turn each subset-permutation of the dice into a regular expression pattern and test them against the target word. ``` w => // w = target word P = // P = recursive function taking: (a, // a[] = list of dice m = '') => // m = search pattern w.match(m) == w | // force a truthy result if w matches m a.some((w, i) => // for each word w at position i in a[]: P( // do a recursive call: a.filter(_ => i--), // using a copy of a[] without the current element m + `[${w}]` // and adding '[w]' to the search pattern ) // end of recursive call ) // end of some() ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 5 bytes ``` ~V`¦Π ``` [Try it online!](https://tio.run/##yygtzv7/vy4s4dCycwv@//@v5OTqGqL0P1rJ0clZSUfJ0dUTSLr6hwJJH7@g4BClWAA "Husk – Try It Online") Returns a non-zero value if it's possible to spell the word, zero otherwise. ### Explanation ``` ~V`¦Π Arguments: word [Char], dice [[Char]] V Checks if any element of a list (2) satisfies a predicate (1) ~ Composes both arguments of the above function `¦ (1) Is the word a subset of the element? Π (2) Cartesian product of the dice list ``` [Answer] # [Perl 5](https://www.perl.org/) `-plF`, ~~48~~ 46 bytes *@DomHastings saved 2 bytes* ``` $_=grep/@{[sort@F]}/,map"@{[sort/./g]}",glob<> ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3ja9KLVA36E6uji/qMTBLbZWXyc3sUAJKqCvp58eW6ukk56Tn2Rj9/9/ZIALV3WETmRttbOOS221o46TTkDtv/yCksz8vOL/ur6megaGBv91C3LcAA "Perl 5 – Try It Online") ### Input: ``` word # The word to validate {A,B,C}{D,E,F} # Each die is surrounded by braces, commas between the letters ``` ### Output: `0` for a word that is not validated. Any positive integer for a word that is validated ### How? This explanation looks at the code in the order of execution, effectively right-to-left for this one-liner. ``` -F # The first line of input is automatically split by the -F command option into the @F array. glob<> # Read the rest of the input and enumerate all of the permutations of it map"@{[sort/./g]}", # Split the permutation into separate letters, sort them and put them back together /@{[sort@F]}/, # use the sorted letters of the target to match against $_=grep # check all of those permutations to see if the desired word is in them -p # Command line option to output the contents of $_ at the end ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 98 bytes ``` f=(s,d,u=[])=>d<1?s.every(t=>u.pop().match(t)):d.some((x,i)=>f(s,e=[...d],[...u,x],e.splice(i,1))) ``` [Try it online!](https://tio.run/##fcuxDoIwEIDh3RfpXXJewmosBo0rEoITYSC0aA1QQoHg09e6G6d/@b9Xvdaumcw47wertPetBEeKFllWKGN1jE6O9aqnN8wyXni0IyD39dw8YUY8KHa21wAbmbC3wWpZMrOq6JuFtoo0u7EzjQZDESL6xg7Odpo7@4AWvptI8kIEIZJrcbsLEsn5UoSkWS4qxN0PkSXpP@H9Bw "JavaScript (Node.js) – Try It Online") Assuming there's enough dice # [JavaScript (Node.js)](https://nodejs.org), 100 bytes ``` f=(s,d,u=[''])=>d<1?s.every(t=>u.pop().match(t)):d.some((x,i)=>f(s,e=[...d],[...u,x],e.splice(i,1))) ``` [Try it online!](https://tio.run/##lc5BC4IwGMbxe19k72C94DWasayridghwoO4WQt1w6nYp1/zHkGn/@X5wfOq5srVg7bjtjdSed9wcEyyid8JKSmP5T46OFSzGt4w8nhCayxQ7KqxfsJI6U6iM50CWJgO8yZoxe@IKEu2ZmJLyRQ62@pagWYRpdTXpnemVdiaBzSwzojICxIEEeficiWMiGNShKRZHm7QzReRifRPkYj0dPtlvP8A "JavaScript (Node.js) – Try It Online") # [JavaScript (Node.js)](https://nodejs.org), 99 bytes ``` s=>f=(d,u=[''])=>d<1?s.every(t=>u.pop().match(t)):d.some((x,i)=>f(e=[...d],[...u,x],e.splice(i,1))) ``` [Try it online!](https://tio.run/##lY1BC4IwGIbv/ZF9g/WB12jGsjyaiB1CPIibZagbTsV@/Vr3CDo98PI8vM9qqWw9tmbaDloqF3NnedhwkGzmBSEl5aHcBweLalHjCyYezmi0AYp9NdUPmCjdSbS6VwAra73egOIFIsqSfTCztWQKrenaWkHLAkqpq/Vgdaew03eI4aMRkeX@DQoizvnlShgRxyj3SNLM73TzJUlF8m8SieR0@xk59wY "JavaScript (Node.js) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~10~~ 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -1 thanks to Erik the Outgolfer (use `w` rather than `ẇ@` >.<) ``` Œ!Œp€Ẏw€Ṁ ``` A dyadic link accepting a list of lists of characters on the left (the dice) and a list of characters on the right (the word) which returns 1 if possible and 0 if not. **[Try it online!](https://tio.run/##y0rNyan8///oJMWjkwoeNa15uKuvHEzt@P//f7R6VJS6joK6s7OTp7criBXk7wOmfRyjXINADP/QEPXY/@rO/v4@6gA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8///oJMWjkwoeNa15uKuvHEzt@H94@eEJQCaY@P8/Wt3RyVldR0Hd0dUTRLn6h4IoH7@g4BD12P/R0erOjiEgESdXVwjl6AeiQ1wdoaIQWaBorI5CtLqPvx9YnbOjE0Tc0wesHEo7OYK1hfgDlccCAA "Jelly – Try It Online"). ### How? ``` Œ!Œp€Ẏw€Ẹ - Link: list of lists of characters Dice, list of characters Word Œ! - all permutations of the dice (i.e. all ways to order the dice) Œp€ - Cartesian product of €ach (i.e. all ways to roll each ordering) Ẏ - tighten (i.e. all ordered ways to roll the dice) € - for each: w - first index (of sublist W) in the result (positive if there, 0 otherwise) Ẹ - any truthy? (1 if it is possible to roll the word, 0 otherwise) ``` --- ### Faster algorithm (also 9 bytes): A dyadic link with the same input format which returns positive integer (truthy) when possible and 0 (falsey) otherwise. ``` Œpf€Ṣ€ċṢ} - Link: list of lists of characters Dice, list of characters Word Œp - Cartesian product of the dice (all rolls of the dice) f€ - filter keep for €ach (keep the rolled letters if they are in the word) Ṣ€ - sort €ach result Ṣ} - sort Word ċ - count occurrences ``` [Answer] # [R](https://www.r-project.org/), ~~192 185 135 117 111~~ 109 bytes ``` function(x,...)s(x)%in%apply(expand.grid(lapply(list(...),c,"")),1,s) s=function(x)paste(sort(x),collapse="") ``` [Try it online!](https://tio.run/##lU7RCoJAEHzvMxaEPdiE3vNBLSOIgrIPEDU5kPPwLri@3lZP6cWXHoaduZnZvX5o9tvh9VallZ1CR2EYCoNOBFIFhdbtB2unC1WFTS8rbP1TK43FMUklAQhBOzJiY6LfHqELY2s0XW9ZUNm1XDV1xOmhQReVCCkQxIwc2MdlpH7EvHUzB8fQgZEtFkHCmJOjc/Q0Y3paKeb/FpP5a9fVYjwVCc5ejvTGeHp5mXoEd8bDHxfDFw "R – Try It Online") -2 chars thanks to Giuseppe. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 8 bytes ``` ṖvÞ*Þf$c ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLhuZZ2w54qw55mJGMiLCIiLCJbW1wiQVwiLFwiQlwiLFwiQ1wiXSxbXCJBXCIsXCJFXCIsXCJJXCJdLFtcIkVcIixcIk9cIixcIlVcIl0sW1wiTFwiLFwiTlwiLFwiUlwiLFwiU1wiLFwiVFwiXV1cbltcIkNcIixcIk9cIixcIkFcIixcIkxcIl0iXQ==) Returns 1 for valid, 0 for invalid. ``` Ṗv Þf # over all permutations Þ* # Reduce by cartesian product $c # Check if the input contains that ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 21 bytes ``` .Em}eQdsm.ps.nd.U*bZh ``` [**Test suite**](https://pyth.herokuapp.com/?code=.Em%7DeQdsm.ps.nd.U%2abZh&test_suite=1&test_suite_input=%5B%22A%22%2C%22C%22%2C%22T%22%5D%2C%22CAT%22%0A%5B%22A%22%2C%22C%22%2C%22T%22%5D%2C%22BAT%22%0A%5B%22AEIOU%22%2C%22ABCT%22%2C%22NPR%22%5D%2C%22ART%22%0A%5B%22AEIOU%22%2C%22ABCT%22%2C%22NPR%22%5D%2C%22EAT%22%0A%5B%22ABC%22%2C%22AEI%22%2C%22EOU%22%2C%22LNRST%22%5D%2C%22BEAT%22%0A%5B%22ABC%22%2C%22AEI%22%2C%22EOU%22%2C%22LNRST%22%5D%2C%22BAIL%22%0A%5B%22ABC%22%2C%22ABC%22%2C%22ABC%22%5D%2C%22AAA%22%0A%5B%22ABC%22%2C%22ABC%22%2C%22ABC%22%5D%2C%22ANA%22&debug=0) Explanation: ``` .Em}eQdsm.ps.nd.U*bZhQ # Code with implicit variables .E # Print whether any of sm.ps d # all positive length permutations of each element in m .nd.U*bZhQ # the Cartesian product of the list of dice m}eQd # contain the target word ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 54 bytes ``` ->w,a{a.permutation.any?{/#{w.chars*".*,.*"}/=~_1*?,}} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsEiN9ulpSVpuhY3zXTtynUSqxP1ClKLcktLEksy8_P0EvMq7av1lavL9ZIzEouKtZT0tHT0tJRq9W3r4g217HVqa6G6FxQouEWrOwaFqOsoAGlXT_9QIEvd0ckZJKLuFxCkHhvLBVbk7EiEohBXR4giJ2ewEldPEOUK0eDjFxQcAlfq4-_nSlgtxJ0LFkBoAA) ]
[Question] [ Recently there have been a couple of ASCII pet snake challenges (e.g. [here](https://codegolf.stackexchange.com/questions/156369/code-golf-your-own-horizontal-pet-ascii-snake)) ``` 0 0 0 0 0 000 00 0 00 000 0 0 000 0 0 0 00 0 000 ``` This challenge is to take a randomly generated horizontal pet snake (height of five lines, length of 30), and verify that : * Each column has only one `0` * Each `0` is "connected" to the `0` before and after it (vertically spaced by 0 or 1 line only) Final output can be `true` or `1` if the snake is valid, or `false` or `0` if the snake is invalid ## Edit—Clarification Assume the input: * Is a string * Contains only ' ', '0', and '\n' * Has exactly 30 characters each line * Has exactly 5 lines I.e. verify whether the snake is connected, and that there are no stray chars. No need to validate the "canvas" that the snake is printed on. [Answer] # JavaScript (ES2018), ~~62~~ 54 bytes ``` s=>!/0(.{30}|.{60,62}(.{31})*)0|( .{30}){4} /s.test(s) ``` Input is a single string: * without trailing new line * contain only space, '0', and '\n' * 30 characters each line, 5 lines, 154 character in total Flag `s` means a dot match anything (including '\n'). This feature currently supported by Chrome 63+, Opera 50+, Safari 11.1+, based on [compat-table](https://kangax.github.io/compat-table/es2016plus/#test-s_(dotAll)_flag_for_regular_expressions). You may test this function with these supported browser. You will get an exception when loading the page if your browser do not support this feature. How it works: * No column with no `0`: + do not match `/( .{30}){4} /` * No two `0`s in one column: + do not match `/0.{30}(.{31})*0/` * No `0` not connect to its neighbors: + do not match `/0.{60}(.{31})*0/`, `/0.{62}(.{31})*0/` Merge all these regex, and you will finally got this one. ``` f = s=>!/0(.{30}|.{60,62}(.{31})*)0|( .{30}){4} /s.test(s) ``` ``` <textarea id=i style="width:100%;height:100px"> 0 0 0 0 0 000 00 0 00 000 0 0 000 0 0 0 00 0 000 </textarea> <button onclick="o.value=f(i.value.slice(0,154))">Validate</button> Result: <output id=o></output> ``` Thanks to Martin Ender point out that do a single `!` operator may save 8 bytes. [Answer] # [SnakeEx](http://www.brianmacintosh.com/snakeex/spec.html), 51 bytes This is obviously the right language for the task. :^D ``` s:({c<L>}{c<R>}0[(<R> <L>)(<L> <R>)_?])%{30} c:0 *$ ``` Matches the entire input if it is a valid snake; fails to match if it's not. [Try it here!](http://www.brianmacintosh.com/snakeex/) ### Explanation SnakeEx is a [2-D pattern matching language](https://codegolf.stackexchange.com/q/47311/16766). A program consists of a list of definitions for "snakes," which crawl around the input matching characters, changing directions, and spawning other snakes. In our program, we define two snakes, `s` and `c`. We'll start with `c` because it's simpler. Its definition is `0 *$`, which should be quite readable if you know regex: match `0`, followed by zero or more spaces, followed by the edge of the grid. The main catch here: this matching can proceed in any direction. We're going to use `c` both upward and downward from the snake, to verify that there are no extra `0`s in each column. Now for the main snake, `s`. It takes the form `(...)%{30}`, which means "match the contents of the parentheses 30 times"--once for each `0` in the snake. So far, so good. What goes inside the parentheses? ``` {c<L>} ``` This spawns a new `c` snake, turned left 90 degrees. The direction is relative to the `s` snake's direction, so the new snake moves toward the top of the grid (the main snake is moving toward the right). The `c` snake checks that the current grid cell is a `0` and that every cell above it is a space. If it fails, the whole match fails. If it succeeds, we continue with ``` {c<R>} ``` which does the same thing, only turned right (toward the bottom of the grid). Note that these spawns don't affect the position of the match pointer in the main snake. They're a bit like lookaheads in regex. (Maybe here we could call them "lookbesides"?) So after verifying that we're pointing to a `0` and the rest of the column contains only spaces, we need to actually match the `0`: ``` 0 ``` Now the match pointer is on the character to the right of the `0`. We need to check three different options: the snake angles down, the snake angles up, or the snake goes straight. For this, we can use an OR expression: ``` [...] ``` Inside our OR, we have three possibilities: ``` (<R> <L>) ``` Turn right, match a space, and turn left again (snake angles down). ``` (<L> <R>) ``` Turn left, match a space, and turn right again (snake angles up). ``` _? ``` Match zero or one underscores. Since there are no underscores in the input, this will always be an empty match (snake goes straight). After matching one of the above three options, the match pointer should be pointing to the `0` in the next column, ready to match the parenthesized expression again. [Answer] # [Husk](https://github.com/barbuz/Husk), 12 bytes Depending on rule clarifications, may be **11 bytes** or **13 bytes**. ``` ±Λ=;1Ẋ×≈mηfT ``` [Try it online!](https://tio.run/##yygtzv6v8Kip8dC2/4c2nptta234cFfX4emPOjtyz21PC/n//78CEjAAQlTApYAQAskaGKCo4DKAaYGLG8CFFAy40ASQbQGKcsEF0ADEFgA "Husk – Try It Online") Input is a list of lines containing only spaces and 0s; if a single string is required, prepend `¶` to the program to split into lines. The TIO link already does this for clarity. Output is 0 or 1; if any falsy and truthy values are fine, the `±` can be removed. ## Explanation ``` ±Λ=;1Ẋ×≈mηfT Implicit input: a list of lines. T Transpose into list of columns. m For each column, ηf get list of indices of truthy elements. In Husk, whitespace characters are falsy and other are truthy, so this gets us the indices of 0s on each column. Ẋ For each adjacent pair of these index lists, × for all pairs drawn from the two lists, ≈ give 1 if they differ by at most 1, otherwise 0. For each adjacent pair, this produces a list of 1s and 0s. Λ Do all of these lists =;1 equal [1]? Return either 0 or 30 (length of the outer list + 1). ± Signum; convert to 0 or 1. ``` The idea is to use `×≈` to guarantee that (a) all columns contain precisely one 0, and (b) their positions differ by at most one. As an example, consider the 8-column input ``` 0 0 0 000 0 00 0 ``` First, `mηfT` transforms it to the list of index lists ``` [[1],[2],[2,3],[1,2,3],[],[2],[1],[3]] ``` Then `Ẋ×≈` gives ``` [[1],[1,1],[1,1,0,1,1,1],[],[],[1],[0]] ``` Each `1` corresponds to a pair of indices that differ by at most 1, and each `0` corresponds to a pair that doesn't. Each result equals `[1]` precisely when both lists have one index, and the indices differ by at most 1. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 16 bytes ``` Zµi€”0IỊ;ċ€⁶=4ƊẠ ``` [Try it online!](https://tio.run/##y0rNyan8/z/q0NbMR01rHjXMNfB8uLvL@kg3iNe4zdbkWNfDXQv@P9y95XD7//8KSMAACFEBlwJCCCRrYICigssApgUubgAXUjDgQhNAtgUoygUXQAMQWwA "Jelly – Try It Online") Assumes that the input string will always only contain only spaces and zeros. Takes input as a list of strings (each representing a line), and outputs **1** if truthy, **0** otherwise. ## Explanation ``` Zµi€”0IỊ;ċ€⁶=4ƊẠ | Monadic full program. Z | Transpose. µ | Start a new monadic chain. i€”0 | Retrieve the first index of 0 in each column. IỊ | Check whether their increments are insignificant (element-wise). ; Ɗ | Append the result of the following: ċ€⁶ | In each list of characters, count the occurrences of a space. =4 | Check whether they equal 4 (returns a boolean array). Ạ | All. Check whether all the elements are truthy. ``` [Answer] # [CJam](https://sourceforge.net/p/cjam), ~~35~~ 34 bytes ``` {z_{'0e=1=}%:*\'0f#2ew::-[W0X]-!*} ``` [Try it online!](https://tio.run/##S85KzP1f6Kf/v7oqvlrdINXW0LZW1UorRt0gTdkotdzKSjc63CAiVldRq/Z/3X8FJGAAhKiASwEhBJI1MEBRwWUA0wIXN4ALKRhwoQkg2wIU5YILoAGILQA "CJam – Try It Online") Input is a rectangular array of arrays of characters. Assumes input only contains and `0`. ## Explanation: ``` {z_{'0e=1=}%:*\'0f#2ew::-[W0X]-!*} Function taking a character matrix: z Transpose. { }% Consider whether each row e= contains 1= exactly one '0 of the character '0'. :* This must be true for every row. # Next, find the position '0 of the character '0' f at every row _ \ in the original input. :- Find the differences between : each 2 pair ew of adjacent elements (in other words, compute the increments). For the snake to be valid, this array of increments must only contain {0, 1, -1}, so - Remove from this list [ ] the elements W -1, 0 0, X and 1, ! and then check whether the array is empty. * The previous code tested two different properties of the matrix; they both must be true for a valid snake. ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 18 bytes ``` ζDε0k}¥Ä2‹sεþg}ìPΘ ``` [Try it online!](https://tio.run/##MzBNTDJM/V/z/9w2l3NbDbJrDy093GL0qGFn8bmth/el1x5eE3Buxv//CkjAAAhRAZcCQggka2CAooLLAKYFLm4AF1Iw4EITQLYFKMoFF0ADEFsA "05AB1E – Try It Online") **Explanation** ``` ζ # transpose D # duplicate ε } # for each row in the first copy (column of input) 0k # get the index of the first 0 ¥Ä # calculate absolute delta's 2‹ # check that each is less than 2 sε } # for each row in the second copy (column of input) þg # calculate the length of the string with non-digits removed ì # concatenate the lists P # calculate product Θ # truthify (turn false values to 0) ``` [Answer] # [Python 2](https://docs.python.org/2/), 71 bytes ``` f=lambda s:s[1]<' 'or'0'in s[::31]in' %s '%s[1::31]in'%6s'%0*2*f(s[1:]) ``` [Try it online!](https://tio.run/##5ZOxDoJADIb3PsW/kIJhKJo4EFl9AjfDgAHiJQrmDgefHkEDilFiRFnsbV97ua9N73Aqtnk2Lcs02EX7TRzB@GbthQsG55qFVQaz9v2ZF6qMYRmwVeUbYM0NWzKZTlK7pqFTxkmKIjGFrdzc8Qk6SG3lEA5aZQW0q4MgJ7pUMDPhLqQ63SDcUJ0V6VSQNFdaLi2C0AO4f6Wi1IKHuL5S2dUduVjpY@KMYoxBxvKRsfQaS6@x9BpL09BzY/x@xvjhViyjnfmeMsZY5JfK8idTfle5@wOGKsugxcBoi1GeAQ "Python 2 – Try It Online") Takes input as a multiline string. Tests case [from Bubbler](https://codegolf.stackexchange.com/a/156440/20260). The first column is extracted as `s[::31]` and the second as `s[1::31]`, and they are checked for validity. We recurse on `s` removing the first character, causing successive pairs of columns to be checked. The check for two columns uses Python's comparison chaining for `in` combine multiple checks: * `'0'in s[::31]` checks that the first column has at least one `0` * `s[::31]in' %s '%s[1::31]` checks that the first column is a substring of the second column sandwiches between two spaces, which ensures the position of the `0` has shifted at most one space * `' %s '%s[1::31]in'%6s'%0*2` checks that the second column contains at most one `0`. The ending `*f(s[1:])` also forces the recursive case to be true. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~246~~ ~~245~~ ~~232~~ ~~215~~ 212 bytes ``` #define F)exit(1); #define L for(i=l=0;i<30;i++) #define X b[7][i] char b[8][31];k,j,l;main(i){for(;j++<5;){gets(b);L{if(i[*b]>47){if(X++F memset(b[j+1]+i-1,l=1,3);}else if(!X&b[j][i]F}k+=!!l;}if(k<5 F L if(!X F} ``` [Try it online!](https://tio.run/##dY7BioMwFEX3@YonAyWZWEhwSgeis8yqHyCELKoTO09jB6qLgvjtNpbWjou5IYF37r1Jyu2pLKfp7dtVeHagmbtiTyVT5IkOUP1eKGY@EwrTJBycs8XNoTB7a9CS8ud4CcOnNYm0qonr2Kv2iGeKbJhvUDXn6U6x4eT6jhZMHQasKJr3wn597Nk85JxraF3buZ4WpubSctzK2GcyTpgane8chFiUb4I7P6rHhmdR5NUYcJPuQIfv3hOgx2mCPxJhrUTgRWZTiFWAiGdj4WJBIMgDrEviHg6bwH96FG4 "C (gcc) – Try It Online") Figured I'd take my favorite language to this (even though as I can see from the many other, smaller entries it's probably far from ideal for this sort of challenge) and C what I could manage. The program's approach to the problem is relatively straightforward, just with a lot of byte penny-pinching; it takes the snake on stdin and gives its result in the return value of main (thus the exit code; ~~as requested in the problem 0 indicates an invalid snake and 1 valid even though for an exit code that's weird~~ as typical for exit codes 0 is a valid snake and 1 is an invalid snake). With the macros expanded and some nice whitespace it looks more like the following: ``` char b[8][31];l,j,k; //Declares a buffer to work in, initialized all to 0; l j and k default to int and as globals are init to 0 main(i) { //This is run no-args, so argc is 1 and the undeclared type defaults to int. for (; j++ < 5;) { //Iterating over each row, 1-indexed for convenience accessing the buffer gets(b); //Reads into b[0] because of stack array decl layout for (i = l = 0; i < 30; i++) { //j and l both init each time we begin this overall loop if (i[*b] > 47) { //Did we read a zero? if(b[7][i]++) exit(1); //If the snake already had a zero in this column, fail out memset(b[j+1] + i-1, l = 1, 3); //Expect them on the next row in the columns left and right of this one (also set l) } else if (!b[7][i] & b[j][i]) exit(1); //If we didn't read a zero, and we had reason to expect one this row, and there wasn't already a zero in this column, fail out } k+=!!l; //Adds 1 to k iff l is nonzero } if (k < 5) exit(1); //If less than 5 rows had zeroes in them, fail out for(i = l = 0 ; i < 30; i++) { //l isn't relevant in this loop but saves some bytes when sharing a macro with the other horizontal loop if(!b[7][i]) exit(1); //If any columns didn't have zeroes, fail out } //Else, snake is valid. main default returns 0. } ``` Lines of input are read into the first row of the buffer, the next five are for tracking what places are expected to (read: must) have zeroes in the row after each current one, and the last is for tracking whether a zero has already been read in a given column, in any row. The program processes each row in turn. It's not at all robust (`gets()` is only the beginning) and the input must contain all the relevant spaces (no left-off trailing whitespace for instance), and gcc spews warnings and notes about stdlib functionality left implicitly declared and so on, but, C la vie. It also assumes that the snake head need not be in the center row, and that a valid snake must have at least one zero in every row (i.e. no rows of all spaces in the 5 input rows). If the latter's not a requirement it can be made a bit shorter - everything to do with `k` and `l` in the program can be pared out or replaced with fewer bytes of code in that case. Thanks to user202729 for approx. 26 bytes saved. [Answer] # [Python 2](https://docs.python.org/2/) and [Python 3](https://docs.python.org/3/), 122 120 119 bytes ``` lambda s:s.count('0')<31and all(s[i-31*(i>30):31*(i<124)-~i:31].strip(' ')for i,x in enumerate(s,1)if' '<x)and' '<s[62] ``` [Try it online!](https://tio.run/##5ZPBbsMgDIbvPIVvwJRWJpl2iJId9wS9ZTmwBTSklESBSO1lr57RTs2aaoumbu2l5mJ@Y/xhmXbr3xobDzp/Hmq5fqkkuNQtX5veekaR8iwR0lYg65q5wiwSccfMY4I83XuZiO/54t2EXbl0vjMto0C5bjow0QaMBWX7teqkV8xFghsdwtmGhyt3jise4nKolAavnGcmanhKoO1MKK6Z4XnecEL2MUopgSPDsKZG4EvaRREnJwgeUkYdRwmQnAjHVYJKRuHEPqsEukKkZQSrrlf8KsTwJ2I8ixhniXGWGGeJ8fCg74nh8j2GC07Fk6zd/yHDNQb5R2S8kS7/Fnn6A85DHj4A "Python 2 – Try It Online") Input format is one string of length 154 (5 x 30 chars, 4 newlines): ``` ''' 0 0 0 0 0 000 00 0 00 000 0 0 000 0 0 0 00 0 000 '''[1:] # to exclude starting newline ``` --- # If the head doesn't have to be the center row The center-row-head requirement was in the original challenge, but I found that it's not the case here (at least it's not explicitly mentioned). # [Python 2](https://docs.python.org/2/) and [Python 3](https://docs.python.org/3/), 124 123 bytes ``` lambda s:s.count('0')<31and all(s[i-31*(i>30):31*(i<124)-~i:31].strip(' ')for i,x in enumerate(s,1)if' '<x)and'0'in s[::31] ``` [Try it online!](https://tio.run/##5ZPBbsMgDIbvPIVvwJRWptkpSnbsE/SW9cAW0JBSEgUidZe9ekY7NWuqLauyNZeZC/zG9odl6lf/UtlVp7PHrpS7p0KCS9zyuWqtZxQpT2MhbQGyLJnLzSIWd8w8xMiT4y4Vq3u@eDPhtF0635iaUaBcVw2YaA/GgrLtTjXSK@YiwY0O7nTPQ8qQPLhdnhxiu0Jp8Mp5ZqKKJwTqxgQAzQzPsooTcvRRSgmcGYY1NAKf0sGLOLhB8BTS69hLgORCOK8SVNILF/ZRJdDlItlGsGlaxWchhl8R4yRiHCXGUWIcJcbTg74mhqk9/pEYxolxduLrpwJuOMdrWbq/Q4Y5vt63yPhPunwt8vAHTEPu3gE "Python 2 – Try It Online") --- **Edit:** * Reduced 2 bytes by changing equals(`==`) into inequalities for each code. * Found mistakes in the less limiting version, and revised it. (Fortunately it's not too terrible, so I could keep all versions similar in length.) You can see additional test cases in the latter two TIO links. * Found a dangling byte in Py2 solutions, making the `all()` trick meaningless in Py3, so merged both versions. [Answer] # [MATL](https://github.com/lmendo/MATL), ~~18~~ 17 bytes ``` 32>&fun30=wd|2<vA ``` Input is a 2D char array. Any non-space character can be used for the snake. [Try it online!](https://tio.run/##y00syfn/39jITi2tNM/YwLY8pcbIpszx//9odQUkYACEqEDdWkFdASEKUmBgYICuwgCmES5lABdSMICYgSKGbB1QFKZCQQHDAVDr1GMB) ### Explanation ``` 32> % Implicit input. Transform non-space into 1, space into 0 &f % Push vector of row indices and vector of column indices of nonzeros u % Unique: vector of deduplicated entries n % Length 30= % Does it equal 30? (*) w % Swap. Moves vector of row indices to top d| % Absolute consecutive differences 2< % Is each value less than 2? (**) v % Concatenate results (*) and (**) vertically A % All: true if all entries are nonzero. Implicit display ``` [Answer] ## [Grime](https://github.com/iatorm/grime), ~~30~~ ~~26~~ 23 bytes *Thanks to Zgarb for saving 7 bytes and pointing out a bug.* ``` e`" 0/0 "oO|#29ddv&d#1+ ``` [Try it online!](https://tio.run/##Sy/KzE39/z81QUnBQN9AQSnfv0bZyDIlpUwtRdlQ@/9/BSRgAISogEsBIQSSNTBAUcFlANMCFzeACykYcKEJINsCFOWCC6ABiC0A "Grime – Try It Online") [Answer] ## [Slip](https://github.com/Sp3000/Slip/wiki), 28 bytes ``` ((\|/)?0(<(?| *$^)<){2}){30} ``` [Test it here.](https://slip-online.herokuapp.com/?code=%28%28%5C%7C%2F%29%3F0%28%3C%28%3F%7C%20%2a%24%5E%29%3C%29%7B2%7D%29%7B30%7D&input=%20%20%20%20%20%20%20%20%20%20%20%200%200%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%0A%20%200%20%20%20%20%20%20%20%200%200%20000%20%20%20%20%20%20%20%20%20%20%20%20%0A00%200%20%20%20%20%2000%20%20%20%20%20%20%20000%200%20%20%20%20%20%200%0A%20%20%20%20000%200%20%20%20%20%20%20%20%20%20%20%20%200%200%20%20%2000%20%0A%20%20%20%20%20%20%200%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20000%20%20%20&config=) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 19 bytes ``` Zn⁶T€L€=1$$;FIỊ$$$Ạ ``` [Try it online!](https://tio.run/##y0rNyan8/z8q71HjtpBHTWt8gNjWUEXF2s3z4e4uFRWVh7sW/P//P5pLSQEJGAAhKlDSAakwQFZgYGCArsIAphEuZQAXUjCAmIEihmwdUBSmQkEBwwFQ65RiAQ "Jelly – Try It Online") -2 bytes thanks to Mr. Xcoder # Explanation ``` Zn⁶T€L€=1$$;FIỊ$$$Ạ Main Link Z Transpose the matrix of characters (string -> list of chars in Jelly) n⁶ != " " (vectorizing) T€ For each column, get (row) indices of snake parts L€=1$$ For each index list, is its length 1? (that is, exactly one snake part per column) ; $ Append (helper part) FIỊ$$ helper part: F flatten index list I get increments/forward differences Ị are the values insignificant? (|z| <= 1) Ạ Are these all true? ``` Input is as a list of strings [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), (14?\*) 13 bytes ``` Zn⁶T€z-IỊ0-¦Ȧ ``` A monadic link taking a list of five strings\*, each of length 30 consisting of spaces and any other characters (e.g. `0`s), and returning an integer (1 if a snake as defined, 0 otherwise) \* If input must be a single string (list of characters) then prepend a `Ỵ` to split the string at line feeds. **[Try it online!](https://tio.run/##y0rNyan8/z8q71HjtpBHTWuqdD0f7u46sez////RSgpIwAAIUYGSDpeCkgJCGKTCwMAAQ4mBAVQzXM7AAG6aAdQUqHZMG4FK4UoUFDAcAbVRKRYA "Jelly – Try It Online")** ### How? ``` Zn⁶T€z-IỊ0-¦Ȧ - Link: list of lists of characters, Lines Z - transpose the lines -> columns ⁶ - literal space character n - not equal? -> 0 where there were spaces and 1 where there were "0"s T€ - truthy indices for each -> e.g. [0,0,1,0,0] -> [3] or [0,1,1,0,0] -> [2,3] - note: [0,0,0,0,0] -> [] - - literal minus one z - transpose with filler (-1) -> {valid: a single list of heights {top:1,...,bottom:5} - invalid: list of >1 lists, some of which contain -1 - ...OR an empty list (no 0s in the input at all)} I - differences -> {up:-1; down:1; flat:0; invalid:-6,-5,...,-2,2,...4} Ị - insignificant (abs(z)<=1) -? {up/down/flat:1; invalid:0} ¦ - sparse application/// 0 - ...action: literal zero - - ...to indices: [-1] -> make penultimate list into a zero (when one exists) Ȧ - any & all -> when flattened:{empty or contains a 0:0; otherwise:1} ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 20 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)CP437 ``` Å┴m▐◘5)ît╢V¼≥+╝╜►º½ê ``` 24 bytes when unpacked, ``` LM{'0|Ic%vChm:-{Jh!f%29= ``` [Run and debug online!](https://staxlang.xyz/#c=%C3%85%E2%94%B4m%E2%96%90%E2%97%985%29%C3%AEt%E2%95%A2V%C2%BC%E2%89%A5%2B%E2%95%9D%E2%95%9C%E2%96%BA%C2%BA%C2%BD%C3%AA&i=++++++++++++0+0+++++++++++++++%0A++0++++++++0+0+000++++++++++++%0A00+0+++++00+++++++000+0++++++0%0A++++000+0++++++++++++0+0+++00+%0A+++++++0++++++++++++++++000++%0A%0A++++++++++++0+0+++++++++++++++%0A++0++++++++++0+000++++++++++++%0A00+0+++++00+++++++000+0++++++0%0A++++000+0++0+++++++++0+0+++00+%0A+++++++0++++++++++++++++000++%0A%0A++++++++++++0+0+++++++++++++++%0A++0++++++++0+0+000++++++++++++%0A00+0+++++00+++++++000+0++++++0%0A++++000+0++++++++++++0+0+++00+%0A++++++00++++++++++++++++000++%0A&a=1&m=1) May not be the best golfed one but I think the method is novel and interesting. ## Explanation ``` LM Load the input string as a 2d array of characters, and transpose it { m Map array with block '0|I Get all indices of substring "0" c%vC Map to nothing if the indices are not unique h Otherwise map to the unique index :- Take pairwise difference { f Filter array with block Jh! Only keep 0, 1 and -1 %29= Check whether the final array has exactly 29 elements ``` [Answer] # [J](http://jsoftware.com/), 38, 37 30 bytes -8 bytes thanks to FrownyFrog ``` [:($e.~[:(-:*)2-/\])@:I.'0'=|: ``` [Try it online!](https://tio.run/##vVDLCsJADLzvVwxSiBW7DoqXwIIgCIInr@qhLS3Fiz8g/vq6ULasFm/FhJDJe8jdz6y0cArBEoQGKyz259PBX3SeNfYVXKGLfF2srrd8p0crFPdUnxuY0ukWG2aCRBj0W5gWyY8GxoEhzSHVuyROT5Cj9Ug2AGKqSQlieoK1sz@48c/P44ibaerugRZlBFUEdQT9cynGvwE "J – Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 14 bytes ``` ∩ȧvT:v₃$¯ȧ2<JA ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCLilqF2ZiIsIuKIqcindlQ6duKCgyTCr8inMjxKQSIsIiIsIiAgICAgICAgICAgIDAgMCAgICAgICAgICAgICAgIFxuICAwICAgICAgICAwIDAgMDAwICAgICAgICAgICAgXG4wMCAwICAgICAwMCAgICAgICAwMDAgMCAgICAgIDBcbiAgICAwMDAgMCAgICAgICAgICAgIDAgMCAgIDAwIFxuICAgICAgIDAgICAgICAgICAgICAgICAgMDAwICAgIl0=) Takes input as a list of char lists. ``` ∩ # Transpose the input ȧ # Remove whitespace (since this is a char list list, spaces become empty) vT # Truthy indices (indices of 0) of each JA # Are both... :v₃ # All elements are length 3 $¯ȧ # And all elements have absolute differences 2< # Less than 2. ``` [Answer] # [Pip](https://github.com/dloscutoff/pip) `-r`, ~~26~~ 24 bytes ``` $&ZgM{0Na<2>yAD#y*Ya@?0} ``` Takes the snake from stdin and outputs 0 for invalid or 1 for valid. [Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgWbSSbpFS7IKlpSVpuhY7VNSi0n2rDfwSbYzsKh1dlCu1IhMd7A1qIdJQVQtuzlJAAgZAiAq4FBBCIFkDAxQVXAYwLXBxA7iQggEXmgCyLUBRLrgAGoDYAnEiAA) ### Explanation This was fun. I went through several different versions, finally ending up with a solution that abuses the `y` variable delightfully and also shows off Pip's chaining comparison operators. ``` $&ZgM{0Na<2>yAD#y*Ya@?0} g is list of lines of stdin (-r flag); y is "" (implicit) Zg Zip g, transposing rows and columns M{ } To each sublist (column of the original input), map this function: 0Na The number of 0s in this column <2 is less than 2 > and 2 is greater than the following quantity: y The index of the 0 in the previous column, or "" if this is the first column AD Absolute difference with #y* len(y) times a@?0 the index of 0 in this column Y which we also store in y $& Fold the resulting list on logical AND ``` The expression `yAD#y*Ya@?0` warrants further explanation. We want to calculate the difference between the indices of 0s in consecutive columns. We calculate the index of 0 in the current column (`a@?0`) and store it in `y` by using the `Y`ank operator (`Ya@?0`). But then how can we access the previous column's index, which was stored in `y`? We'll have to access it *before* overwriting `y` with the new value. Since Pip expressions are always evaluated left-to-right, we can use the old value of `y` on the left side of the expression and update to the new value on the right. The first column presents another wrinkle. Here, when we access the old value of `y`, we haven't had a chance to set it to anything yet, and it still has its initial value of `""`. We want the first column to succeed no matter what its 0 index is, which means we need the difference to be between -1 and 1. So we multiply the new value by the length of the old value (`#y`). If `y` hasn't been set yet, this multiplies the new value by 0, making the difference 0. If `y` has been set, it will be a single-digit number (since there are only 5 rows in the input), and so multiplying by its length will leave the new value unchanged. [Answer] # [Python 2](https://docs.python.org/2/), 141 bytes ``` lambda g:(lambda a:all(map(len,a)+[-2<x-y<2 for b in[sum(a,[])]for x,y in zip(b,b[1:])]))([[i for i in range(5)if"0"==r[i]]for r in zip(*g)]) ``` [Try it online!](https://tio.run/##XY7BDoIwDIbvPEWzU6fTTBIvRJ5kcBhRsMmYy5iJ@PI4UFH4e2m@9kvr@nC92XSo82Iwuq3OGpoMP53OtDHYaofmYoXmW7VLT49df0qhvnmogKzq7i1qoUpejugh@gjhSQ4rUalDFjnnqBRNBo1Dr21zwSOnmkmW515RObn@a26aKA3Okw1Yo6EuvH@IjQDGGPxFxlomgR8ap1IuNhL5VWYuZwQyWYH/K5EmM1jlfSU@t@@coYCssIyPGV4 "Python 2 – Try It Online") Input is a grid of characters. [Answer] # Excel (VBA), 68 bytes Using Immediate Window, `Cell[A6]` as output. ``` [A1:AD5]="=CHOOSE(ROUND(RAND()+1,),0,"""")":[A6]="=COUNT(A1:AD5)=30" ``` [Answer] ## [Snails](https://github.com/feresum/PMA), 18 bytes ``` \0!(ud.,\0)raa7)30 ``` [Try it online!](https://tio.run/##K85LzMwp/v8/xkBRozRFTyfGQLMoMdFc09jg/38FJGAAhKiASwEhBJI1MEBWwWUA0wEXNoALASkuNBFkWwyg0goKGJZCbQEA "Snails – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 93 bytes ``` ->x{x.transpose.map{|x|x.count(?0)<2&&x.index(?0)}.each_cons(2).all?{|x,y|x&&y&&(x-y).abs<2}} ``` [Try it online!](https://tio.run/##XY/RCoMwDEXf@xV9qgqzFJ/d/BAZo7qKgrbFKqRov72rjDn1BgI5yeWSca6sb@4@fcACdBq5NFoZQQeulxVWoLWa5RQXLMkzQoB28i1gGx0VvG5ftZImzhLK@74IhptdgRBLSAypDbQyeeac17gpUYQPYqHOQviPti1jpwvEfpadsx1hhi7gmBIo2sFF35SI9p0U5vB1qwYdOh@Ne/oP "Ruby – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~128~~ 126 bytes Edited after input clarification stating that the input is "a string". ``` F=(a,l=29,r=0,t=/^( *)0 *$/.exec(a.split` `.map(p=>p[l]).join``),q=t&&~t[1].length)=>q&&(s=q-(r=r||q))>-2&s<2?l?F(a,l-1,q):1:0 ``` [Try it online!](https://tio.run/##XY3BbsMgDEDvfAWHCeGKUCe3tXN6y09UnUAZ6lKxAAFNO1T79azVtKzt8@3Z1jvZT5v7aYilGsObm@eOpFWemmc1EapC61fJV4B89bTW7sv10uoc/VAMM/rDRhmpjXt/AH0Kw2gMqERFiO@yrw/au/FY3oHaJITMlCo50XQ@J4C2akR@aXZ@111zVa0SbOoNzts@jDl4p304yk4afgNe5h7G/9V1i3h3wfDvZfG4KI7sQdxWLpYt4oHfigHYzj8 "JavaScript (Node.js) – Try It Online") [Answer] # [Python 3](https://python.org), ~~197~~ 185 bytes In command prompt do `verify.py<snake.txt` or in bash do `cat snake.txt | python verify.py`. Where `snake.txt` is a file containing a snake to verify. If the snake is correct nothing will be output. If it isn't correct Python will raise an index error. ``` import sys s=sys.stdin.read().split("\n") x=0 exec('t,y="",0\nwhile y<5:t+=s[y][x];y+=1\ns+=[t];x+=1;'*30) s=list(map(lambda l:len(l.rstrip()),s)) while y<35:"ee"[abs(s[y]-s[y+1])];y+=2 ``` ]
[Question] [ Given a string as argument, output the length of the longest(s) non-overlapping repeated substring(s) or zero if there is no such string. You can assume the input string is not empty. ## Examples `abcdefabc` : the substring `abc` is repeated at positions 1 and 7, so the program should output **3** `abcabcabcabcab` : `abcabc` or `bcabca` or `cabcab` are repeated, so the program should output **6**. (the substring `abcabcabcab` is also repeated, but the occurrences overlap, so we don't accept it). `aaaaaaa` : `aaa` is repeated at positions 1 and 4 for example, so the program should output **3** `abcda` : `a` is repeated, so the program should output **1** `xyz` : no repeated string → **0** `ababcabcabcabcab` : should return **6** This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so fewest bytes wins. [Answer] ## brainfuck, 226 bytes ``` ,[<<<,]+[>>->[[[[>>[>>>]<+<-<[<<<]>>+<-]>[<+>-]>[>>>]<<[>[<+>-]]>[[<+>-]>+[<<<]> >>-[+>[<<<]<[>+>[->]<<[<]>-]>[<+>>+<-]>>>[>>>]]>>]<]>+[,<<<+]->[<<<]>>>>>+[,+>>> +]-[>>>]->]<[+<<<]+<<<++[->>>]+>>>->]<[,<<<]<[>>>+<<<-]>+>,>>>]<<. ``` Formatted: ``` ,[<<<,] + [ for each suffix >>-> [ for each prefix [ for each suffix [ for each char while no mismatch [ >>[>>>] <+<-<[<<<] > >+<- ] >[<+>-] >[>>>] << [ mismatch >[<+>-] ] > [ [<+>-] >+[<<<] >>>- [ match +>[<<<] < [ >+>[->] <<[<] >- ] >[<+> >+<-] >>>[>>>] ] >> ] < ] >+[,<<<+] ->[<<<] >>> >>+[,+>>>+] -[>>>] -> ] <[+<<<] +<<<++[->>>] +>>>-> ] <[,<<<] <[>>>+<<<-] >+>,>>> ] <<. ``` Expects input with or without a trailing newline, and outputs the result as a [byte value](http://meta.codegolf.stackexchange.com/questions/4708/can-numeric-input-output-be-in-the-form-of-byte-values/4719#4719). [Try it online.](http://brainfuck.tryitonline.net/#code=LFs8PDwsXStbPj4tPltbW1s-Pls-Pj5dPCs8LTxbPDw8XT4-KzwtXT5bPCs-LV0-Wz4-Pl08PFs-WzwrPi1dXT5bWzwrPi1dPitbPDw8XT4-Pi1bKz5bPDw8XTxbPis-Wy0-XTw8WzxdPi1dPls8Kz4-KzwtXT4-Pls-Pj5dXT4-XTxdPitbLDw8PCtdLT5bPDw8XT4-Pj4-K1ssKz4-PitdLVs-Pj5dLT5dPFsrPDw8XSs8PDwrK1stPj4-XSs-Pj4tPl08Wyw8PDxdPFs-Pj4rPDw8LV0-Kz4sPj4-XTw8Lg&input=YWJjZGVmYWJj&debug=on) This checks each prefix to see whether it occurs later in the string, then chops off the first character and repeats the process until there are no more characters left. The tape is divided into 3-cell nodes, `c 0 f` where `c` is a character of the given string, and `f` is a flag that can be either one, negative one, or zero. Nonzero flags are placed between the two characters currently being compared, and negative ones are reserved for the cells after the end of the current prefix and before the beginning of the current suffix (i.e., before the index of the current potential match). The result is stored to the left of the string and is updated whenever a match is found. (The string is actually processed in reverse with a `\x01` appended to it.) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes ``` œ-QL€ ŒṖÇ€FṀ ``` [Try it online!](https://tio.run/nexus/jelly#@390sm6gz6OmNVxHJz3cOe1wO5Dp9nBnw/@Hu7eAOZH//ycmJaekpgFJLiBGQlyJEAASTknkqqisArJQlQAA "Jelly – TIO Nexus") ### How it works ``` ŒṖÇ€FṀ Main link. Argument: s (string) ŒṖ Generate all partitions of s. Ç€ Apply the helper link to each partition. F Flatten the resulting array of lengths. Ṁ Take the maximum. œ-QL€ Helper link. Argument: P (partition) Q Yield the elements of P, deduplicated. œ- Multiset subtraction; remove exactly one occurrence of each string in P. L€ Compute the lengths of the remaining strings. ``` [Answer] # [Perl 6](https://perl6.org), 36 bytes ``` {m:ex/(.*).*$0/.map(*[0].chars).max} ``` [Try it](https://tio.run/nexus/perl6#ZVBLboMwEN37FG@BKiCpQ1Upi7jkFN2lWbi2QyyBQRhaaESvTocAVaVa1mjm/axx6w0@9lwJ1lL3anwjWJVLh1gwVvR4UKU2SMdbcTDdLuRxxOMg2fFCVmF8Ss5cXWXtI5q7YbyUNXLrjA8j3BhQ4OBt5iupzH0GghfrqrY5AilOb5/xeUFr49uc4AnVmwkd6H1K6BHcHcR8r2axELOJmM1vwEpp4xUR4WzmlalzpMfVEvHMTouS2HpMGy7CaLtKtnOGYAPTpTOPDf2MdZkY5bvS5kIVz4zqn4s9k/OZKS3xxLr@CwlN/6RIfgA "Perl 6 – TIO Nexus") ## Expanded: ``` { # bare block lambda with implicit parameter 「$_」 m # match ( implicitly against 「$_」 :exhaustive # every possible way / (.*) # any number of characters ( stored in 「$0」 ) .* $0 / .map( *\ # the parameter to Whatever lambda [0]\ # the value that was in 「$0」 for that match .chars # the number of characters ).max } ``` [Answer] # [Retina](https://github.com/m-ender/retina), ~~35~~ ~~32~~ 30 bytes Pretty cool challenge. ``` M&!`(.*)(?=.*\1) M%`. O#^` G1` ``` [**Try it online**](https://tio.run/nexus/retina#@@@rppigoaelqWFvq6cVY6jJ5auaoMflrxyXwOVumPD/f2JSYlIyEgIA) **Explanation:** ``` M&!`(.*)(?=.*\1) # Prints overlapping greedy substrings occuring more than once M%`. # Replace each line with its length O#^` # Sort lines by number in reverse G1` # Return the first line ``` [Answer] ## JavaScript (ES6), ~~79~~ ~~68~~ 66 bytes ``` f=(s,r,l=s.match(/(.*).*\1/)[1].length)=>s?f(s.slice(1),l<r?r:l):r ``` ``` <input oninput=o.textContent=f(this.value)><pre id=o> ``` Edit: Saved ~~11~~ 13 bytes thanks to @Arnauld. [Answer] # [Haskell](https://www.haskell.org/), 79 bytes ``` (""%) (a:b)!(c:d)|a==c=1+b!d _!_=0 a%c@(e:d)=maximum[a!c,""%d,(a++[e])%d] _%_=0 ``` [Try it online!](https://tio.run/##HYtLCsIwGAb3uUWCgYRU0G3hB@9RS/jy0mBTglXowrMbg7OdmTu2R1yWlujalBBSM4XRaa78GPQHRJ7OxvHALLd0YpD@omJXVLDn8i4TuB/6FwYFY6Y4axlmZmWPW0FeqT7z@jok4QDs@CPa16cFt60dfa0/ "Haskell – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), ~~75~~ 72 bytes ``` f=lambda s,n=0:s[n:]and max(n*(s[:n]in s[n:]),f(s,n+1))or n and f(s[1:]) ``` [Try it online!](https://tio.run/nexus/python3#VY7BCsIwDEDP@hW5lDa6ib14KMwfKTt01kJhi2PZYfrzNdWLhiSElwdJSd0YpiEG4Ia6s2NPrg8UYQqboYNh76jPBB@OTTKiHS3iYwGC6gnxVlYlCWIQVYfhFu9JOkj9JIRvVCwHt@dLpn9Fn3ge82rQ7Xfzkmk1WrX2wtBeQUUNCuSBehMRyxs "Python 3 – TIO Nexus") [Answer] # [Husk](https://github.com/barbuz/Husk), 11 bytes ``` L►L§fo↓2`xQ ``` [Try it online!](https://tio.run/##yygtzv7/3@fRtF0@h5an5T9qm2yUUBH4//9/pcSkxKRkJKQEAA "Husk – Try It Online") Note: Husk is newer than this challenge. ## Explanation ``` L►L§fo↓2`xQ Implicit input, say x = "ababc" Q Nonempty substrings: ["a","b","ab",..,"ababc"] f Keep those that satisfy this: Take s = "ab" as an example. § `x Split x along s: ["","","c"] o↓2 Drop the first two pieces: ["c"] This is truthy (i.e. nonempty). Result is ["a","b","ab","a","b","ab"] ►L Take element with maximal length: "ab" If the list is empty, "" is used instead. L Length: 2 ``` [Answer] # JavaScript, 120 ``` function r(a,b,m){return b=-~b,t=a.slice(0,b),n=a.indexOf(t,b),m=b>m&&!~n?m:b,a!=t&&r(a,b,m)||(a?r(a.slice(1),m,m):~-m)} ``` [Answer] ## [Perl 5](https://www.perl.org/) with `-p`, 40 bytes ``` $_+=(sort map{y///c}/(?=(.+).*\1)/g)[-1] ``` [Try it online!](https://tio.run/##K0gtyjH9/18lXttWozi/qEQhN7GgulJfXz@5Vl/D3lZDT1tTTyvGUFM/XTNa1zD2///EpOSU1DQgyQXESIgrEQJAwimJXBWVVUAWqpJ/@QUlmfl5xf91C3IA "Perl 5 – Try It Online") [Answer] # Mathematica, ~~75~~ 65 bytes *10 bytes saved due to [@JingHwan Min](http://ppcg.lol/users/60043).* ``` Max@StringLength@StringCases[#,a___~~___~~a___:>a,Overlaps->All]& ``` Anonymous function. Takes a string as input, and returns a number as output. [Answer] # Pyth - 16 bytes I need to golf the converting all the strings to lengths and finding the max. ``` eSlM+ksmft/dTd./ ``` [Test Suite](http://pyth.herokuapp.com/?code=eSlM%2Bksmft%2FdTd.%2F&test_suite=1&test_suite_input=%22abcdefabc%22%0A%22aaaaaaa%22%0A%22abcda%22%0A%22xyz%22%0A%22ababcabcabcabcab%22&debug=0). [Answer] **Clojure, 112 bytes** ``` #(apply max(for[R[(range(count %))]j R i R](let[[b e](split-at i(drop j %))](if((set(partition i 1 e))b)i 0))))) ``` loops twice over numbers `0` to `n - 1` (`n` being length of the string), drops `j` characters and splits the remainder into "beginning" and "end" parts. Creates a set of all substrings at `e` of length `b` and uses it as a function to check if `b` is found from there. Returns the length of `b` if found and 0 otherwise, returns the max of these values. Would be interesting to see a shorter version. [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 24 bytes ``` L$v`(.*).*\1 $.1 N` G-1` ``` [Try it online!](https://tio.run/##K0otycxLNPyvquGe8N9HpSxBQ09LU08rxpBLRc@Qyy@By13XMOH//8Sk5JTUNCDJBcRIiCsRAkDCKYlcFZVVQBaqEgA "Retina – Try It Online") A warmup for me to learn the new features of Retina 1. ### Explanation ``` L$v`(.*).*\1 $.1 ``` A List stage, this returns all the matches for the regex `(.*).*\1`, wich matches any pattern of the form "ABA", where A and B are two arbitrary substrings (possibly empty). The additional options given to this stage are `v`, which considers overlapping matches, and `$` which applies a substitution to each of the matches before returning it: the substitution is indicated in the second line, and corresponds to the length (`.`) of the first capturing group (which would be the substring "A" in the previous example). ``` N` ``` We now have all the lengths of repeated substrings, this stage simply sorts them in numerical order, from the shortest to the longest. ``` G-1` ``` Finally, this grep stage (`G`) keeps only the last (`-1`) result, which is the length of the longest repeated substring. [Answer] ## Javascript, 165 bytes ``` function a(s){var l=s.length/2,z=1,f='';while(z<=l){var t=s.substr(0,z),c=0;for(var i=0;i<s.length;i++){if(s.substr(i,z)===t){c++;if(c>1){f=t}}}z++}return f.length} ``` Test Cases ``` console.log(a('abcabcabcabc')) // Output 6 console.log(a('xyz')) // Output 0 console.log(a('aaaaaaa')); // Output 3 console.log(a('abcdefabc')); // Output 3 ``` ]
[Question] [ # Introduction The **Parsons code** is just a simple way to describe *pitch variations* in a piece of music, whether a note is higher or lower than the previous one. Even if you suck at remembering tunes, you can still pretty much remember if a note goes up or down, thus the *Parsons code* can help you to identify a music using a search engine. --- ### Description Each variation is represented by a single character, which is one of the following: * `R` if the note is **the same** than the previous one (stands for *"**R**epeat"*) * `U` if the note is **higher** than the previous one (stands for *"**U**p"*) * `D` if the note is **lower** than the previous one (stands for *"**D**own"*) The initial note is written as `*`. --- ### Example Here is an example of Parsons code (beginning of *"Ode to Joy"*): ``` *RUURDDDDRUURDR ``` You can actually *visualize* it, like this: ``` *-* / \ * * / \ *-* * *-* \ / \ * * *-* \ / *-* ``` We'll call that a **contour** from now on. The rules for drawing such countours are considered *self-explained* by the above example. --- --- # Challenge Now comes the real challenge. ### Write a program that, given a contour as input, outputs its corresponding Parsons code. You are not asked to draw the contour, but the opposite actually. From the contour, find the original Parsons code. --- ### Rules * The usual rules for code golfing apply * **The shortest program in number of bytes wins** * The input is a contour, and the output shall be a valid Parsons code * Details about extra whitespace for the input are irrelevant, do whatever works best for you * You are not allowed to hardcode, one way or another, parts of the output and / or the program using extra whitespace because of the previous rule ### Notes * [**This might be useful for testing**](http://www.musipedia.org/melodic_contour.html) * The corresponding Parsons code for `*` is `*` * An empty string is not a valid contour * A Parsons code **always** starts with `*` [Answer] # CJam, 21 bytes ``` qN/:.e>(o2%:i"DRXU"f= ``` Fold the lines (`:`) by vectorizing (`.`) a character-wise maximum operation `e>`. Since there is only one non-space character in each column, this one will be the result, as space has a smaller ASCII code than all printable non-space characters. Unshift and print the first asterisk `(o`, then map every other (`2%`) remaining char to `UDR` using modular indexing. ## Old solution (29 bytes) ``` '*qN/z2%'*f#0+2ew);::-"RDU"f= ``` `qN/` gets input lines. `z` transposes this character matrix. `2%` drops every odd row. `'*f#` finds the index of the asterisk in each row. `0+2ew);` gets all successive pairs of indices. `::-` computes their differences, and `"RDU"f=` maps them to letters (via modular indexing: `0 → R`, `2 → U`, `-2 ≡ 1 → D`). The leading `'*` prepends the asterisk. **EDIT**: I changed `2ew` to `0+2ew);` to work around CJam not handling `ew` (successive slices) on lists that are too short. This makes the code work for the input string `*`. [Try it here](http://cjam.aditsu.net/#code=%27*qN%2Fz2%25%27*f%232ew%3A%3A-%22RDU%22f%3D&input=%20%20%20%20%20%20*-*%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%0A%20%20%20%20%20%2F%20%20%20%5C%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%0A%20%20%20%20*%20%20%20%20%20*%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%0A%20%20%20%2F%20%20%20%20%20%20%20%5C%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%0A*-*%20%20%20%20%20%20%20%20%20*%20%20%20%20%20%20%20%20%20*-*%20%20%20%20%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%5C%20%20%20%20%20%20%20%2F%20%20%20%5C%20%20%20%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20*%20%20%20%20%20*%20%20%20%20%20*-*%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%5C%20%20%20%2F%20%20%20%20%20%20%20%20%20%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20*-*%20%20%20%20%20%20%20%20%20%20), or watch it in action: ``` ![](https://i.stack.imgur.com/Joojm.gif) ``` [Answer] # Pyth - ~~28~~ ~~25~~ ~~27~~ 25 bytes *2 byes saved thanks to @Jakube.* ``` s+\*@L"RDU"-VFtBxR\*%2C.z ``` [Try it online here](http://pyth.herokuapp.com/?code=s%2B%5C%2a%40L%22RDU%22-VFtBxR%5C%2a%252C.z&input=++++++%2a-%2a++++++++++++++++++++%0A+++++%2F+++%5C+++++++++++++++++++%0A++++%2a+++++%2a++++++++++++++++++%0A+++%2F+++++++%5C+++++++++++++++++%0A%2a-%2a+++++++++%2a+++++++++%2a-%2a++++%0A+++++++++++++%5C+++++++%2F+++%5C+++%0A++++++++++++++%2a+++++%2a+++++%2a-%2a%0A+++++++++++++++%5C+++%2F+++++++++%0A++++++++++++++++%2a-%2a++++++++++&debug=0). [Answer] # Python 3, ~~129~~ ~~108~~ ~~98~~ 86 bytes There are probably several ways to golf this, but I rather like that I got it all down to one line. **Edit:** Now using `''.translate()` **Edit:** With many thanks to [wnnmaw](https://codegolf.stackexchange.com/users/30170/wnnmaw). **Edit:** I changed the input format to an array of strings instead of a newline-separated string to save bytes. Also, in the last edit, I mixed up `U` and `R`, so I fixed that. ``` lambda a:'*'+"".join(('UR'[j<'/']+'D')[j>'/']for l in zip(*a)for j in l if j in'-/\\') ``` Input must be an array of strings. For the example above, this looks something like: ``` [" *-* "," / \ "," * * "," / \ ","*-* * *-* "," \ / \ "," * * *-*"," \ / "," *-* "] ``` Ungolfed: ``` def f(a): s = '' for c in zip(*a): # transpose for d in c: # for each letter in column c if e in "-/\\": # if that letter is either -,/,\ if e < '/': # if < '/' (same as if == '-') s += "R" elif e > '/': # if > '/' (same as if == '\') s += "D" else: # if == '/' s += "U" return "*" + s # in the code we ''.join() it all together # in this ungolfing, we add to an empty string ``` [Answer] # Ruby, 87 bytes Requires trailing spaces in the input so that all lines are the same length. ``` $><<?*+$<.readlines.map(&:chars).transpose.join.gsub(/./,{?-=>:R,?/=>:U,?\\=>:D}).strip ``` [Answer] # Japt, 38 bytes ~~40 41 45 46 48~~ *Saved 2 bytes thanks to @ETHproductions* ``` '*+U·y £Yu ?"RUD"g1+(XrS c -47 g):P} q ``` If there was a trim command this would be only 38 bytes ;-; will add explanation when I'm done golfing. The `:P` is not the program trying to be funny, it's actually the program ignoring characters that aren't important. [Try it online](http://ethproductions.github.io/japt?v=master&code=JyorVbd5IG1AWXUgPyJSVUQiZyhYclNQIGMgLTQ3IGcgKzEgOlB9IHE=&input=IiAgICAgICotKiAgICAgICAgICAgICAgICAgICAgCiAgICAgLyAgIFwgICAgICAgICAgICAgICAgICAgCiAgICAqICAgICAqICAgICAgICAgICAgICAgICAgCiAgIC8gICAgICAgXCAgICAgICAgICAgICAgICAgCiotKiAgICAgICAgICogICAgICAgICAqLSogICAgCiAgICAgICAgICAgICBcICAgICAgIC8gICBcICAgCiAgICAgICAgICAgICAgKiAgICAgKiAgICAgKi0qCiAgICAgICAgICAgICAgIFwgICAvICAgICAgICAgCiAgICAgICAgICAgICAgICAqLSogICAgICAgICAgIg==) [Answer] ## Haskell, 89 bytes ``` import Data.List m '/'="U" m '-'="R" m '\\'="D" m _="" ('*':).(>>=(>>=m)).transpose.lines ``` Usage example: ``` *Main> ('*':).(>>=(>>=m)).transpose.lines $ " *-* \n / \\ \n * * \n / \\ \n*-* * *-* \n \\ / \\ \n * * *-*\n \\ / \n *-* " "*RUURDDDDRUURDR" *Main> ('*':).(>>=(>>=m)).transpose.lines $ "*" "*" ``` Transpose the input and replace the characters `/`/`-`/`\` with singleton strings `"U"`/`"R"`/`"D"`. All other chars are replaced by empty strings `""`, which later disappear by concatenating everything. Finally, prepend the asterisk `*`. [Answer] ## Mathematica, 103 bytes ``` "*"<>(Differences@Position[Thread@Characters@StringSplit[#," "],"*"][[;;,2]]/.{-2->"U",0->"R",2->"D"})& ``` Quite short, considering that this is a string-processing challenge. [Answer] # JavaScript (ES6) 90 An anonymous function. It scans the input string char by char, taking into accout the position in the current line. Doing this, it builds an output array subsituting `U D R` for `/ \ -` at the right place ``` c=>[...c].map(c=>c>'*'?t[i++]=c>'/'?'D':c<'/'?'R':'U':c<' '?i=0:++i,t=['*'],i=0)&&t.join`` ``` [Answer] # Matlab, 62 bytes ``` r=@(s)[85-(s<14)*3-(s>59)*17,''];@(p)r(sum(p(:,2:2:end)-32)) ``` This requires the input to be a rectangular (same number of characters in each row). E.g. ``` [' *-* '; ' / \ '; ' * * '; ' / \ '; '*-* * *-* '; ' \ / \ '; ' * * *-*'; ' \ / '; ' *-* ']; ``` ### Explanation ``` sum(p(:,2:2:end)-32) % exctract every second column, substract 32 (spaces->zeros) % and sum column wise (results in a vector of 3 different values) [85-(s<14)*3-(s>59)*17,''] % map each of the values to the corresponding value of the letter and convert back to characters ``` ]
[Question] [ **Monday Mini-Golf:** A series of short [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenges, posted (hopefully!) every Monday. (Sorry this one's a little late.) I'm sure most of you folks have heard of [Levenshtein distance](https://en.wikipedia.org/wiki/Levenshtein_distance), an algorithm for calculating the distance between two strings. Well, this challenge is about implementing a similar algorithm of my own invention\*, called **anagram distance**. The main difference is that the order of the characters doesn't matter; instead, only the characters that are unique to one string or the other are measured. # Challenge The goal of the challenge is to write a program or function that takes in two strings and returns the anagram distance between them. The main way to do this is to use the following logic: 1. Convert both strings to lowercase and (optionally) sort each one's characters alphabetically. 2. While the strings contain at least one equal character, remove the first instance of this character from each string. 3. Add the lengths of the remaining strings and return/output the result. ## Example If the inputs are: ``` Hello, world! Code golf! ``` Then, lowercased and sorted, these become: (by JS's default sort; note the leading spaces) ``` !,dehllloorw !cdefgloo ``` Removing all of the characters that are in both strings, we end up with: ``` ,hllrw cfg ``` Thus, the anagram distance between the original two strings = 6 + 3 = 9. # Details * The strings may be taken in any sensible format. * The strings will consist only of printable ASCII. * The strings themselves will not contain any whitespace other than regular spaces. (No tabs, newlines, etc.) * You need not use this exact algorithm, as long as the results are the same. # Test-cases **Input 1:** ``` Hello, world! Code golf! ``` **Output 1:** ``` 9 ``` **Input 2:** ``` 12345 This is some text. .txet emos si sihT 54321 ``` **Output 2:** ``` 0 ``` **Input 3:** ``` All unique characters here! Bdfgjkmopvwxyz? ``` **Output 3:** ``` 42 ``` **Input 4:** ``` This is not exactly like Levenshtein distance, but you'll notice it is quite similar. ``` **Output 4:** ``` 30 ``` **Input 5:** ``` all lowercase. ALL UPPERCASE! ``` **Output 5:** ``` 8 ``` # Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest valid code in bytes wins. Tiebreaker goes to submission that reached its final byte count first. ~~The winner will be chosen next Monday, Oct 12. Good luck!~~ **Edit:** Congrats to the winner, @isaacg, using Pyth (again) for an astounding **12 bytes!** \*If this algorithm has been used elsewhere and/or given another name, please let me know! I wasn't able to find it with a 20-minute search. [Answer] # Pyth, 12 bytes ``` ls.-M.prR0.z ``` [Test suite](https://pyth.herokuapp.com/?code=ls.-M.prR0.z&input=Hello%2C+world%21%0ACode+golf%21&test_suite=1&test_suite_input=Hello%2C+world%21%0ACode+golf%21%0A12345+This+is+some+text.%0A.txet+emos+si+sihT+54321%0AAll+unique+characters+here%21%0ABdfgjkmopvwxyz%3F%0AThis+is+not+exactly+like+Levenshtein+distance%2C%0Abut+you%27ll+notice+it+is+quite+similar.%0Aall+lowercase.%0AALL+UPPERCASE%21&debug=0&input_size=2) The operation in question is equivalent to Pyth's bagwise subtraction operator, `.-`, applied in both directions. You could call it bagwise xor, I suppose. The solution is: `.z`: get input as list of 2 strings. `rR0`: convert both to lowercase. `.p`: Form all permutations, i.e. normal and reversed. `.-M`: Map the `.-` operation over each ordering. `s`: Concatenate the results. `l`: Print the length. [Answer] # JavaScript (ES7), 92 bytes Defines an anonymous function. To test, run the snippet below. You can edit the code and click 'Test' to compare its output with the original. (Leave a comment if you find an improvement!) Input is like `"Hello, world!", "Code golf!"` in the input box. Thanks to @ETHproductions for saving 6 bytes! ``` (a,b)=>[for(v of a[t="toLowerCase"]())if((b=b[t]())==(b=b.replace(v,"")))v][l="length"]+b[l] ``` ``` <!-- Try the test suite below! --><strong id="bytecount" style="display:inline; font-size:32px; font-family:Helvetica"></strong><strong id="bytediff" style="display:inline; margin-left:10px; font-size:32px; font-family:Helvetica; color:lightgray"></strong><br><br><pre style="margin:0">Code:</pre><textarea id="textbox" style="margin-top:5px; margin-bottom:5px"></textarea><br><pre style="margin:0">Input:</pre><textarea id="inputbox" style="margin-top:5px; margin-bottom:5px"></textarea><br><button id="testbtn">Test!</button><button id="resetbtn">Reset</button><br><p><strong id="origheader" style="font-family:Helvetica; display:none">Original Code Output:</strong><p><div id="origoutput" style="margin-left:15px"></div><p><strong id="newheader" style="font-family:Helvetica; display:none">New Code Output:</strong><p><div id="newoutput" style="margin-left:15px"></div><script type="text/javascript" id="golfsnippet">var bytecount=document.getElementById("bytecount");var bytediff=document.getElementById("bytediff");var textbox=document.getElementById("textbox");var inputbox=document.getElementById("inputbox");var testbtn=document.getElementById("testbtn");var resetbtn=document.getElementById("resetbtn");var origheader=document.getElementById("origheader");var newheader=document.getElementById("newheader");var origoutput=document.getElementById("origoutput");var newoutput=document.getElementById("newoutput");textbox.style.width=inputbox.style.width=window.innerWidth-50+"px";var _originalCode=null;function getOriginalCode(){if(_originalCode!=null)return _originalCode;var allScripts=document.getElementsByTagName("script");for(var i=0;i<allScripts.length;i++){var script=allScripts[i];if(script.id!="golfsnippet"){originalCode=script.textContent.trim();return originalCode}}}function getNewCode(){return textbox.value.trim()}function getInput(){try{var inputText=inputbox.value.trim();var input=eval("["+inputText+"]");return input}catch(e){return null}}function setTextbox(s){textbox.value=s;onTextboxChange()}function setOutput(output,s){output.innerHTML=s}function addOutput(output,data){output.innerHTML+='<pre style="background-color:'+(data.type=="err"?"lightcoral":"lightgray")+'">'+escape(data.content)+"</pre>"}function getByteCount(s){return(new Blob([s],{encoding:"UTF-8",type:"text/plain;charset=UTF-8"})).size}function onTextboxChange(){var newLength=getByteCount(getNewCode());var oldLength=getByteCount(getOriginalCode());bytecount.innerHTML=newLength+" bytes";var diff=newLength-oldLength;if(diff>0){bytediff.innerHTML="(+"+diff+")";bytediff.style.color="lightcoral"}else if(diff<0){bytediff.innerHTML="("+diff+")";bytediff.style.color="lightgreen"}else{bytediff.innerHTML="("+diff+")";bytediff.style.color="lightgray"}}function onTestBtn(evt){origheader.style.display="inline";newheader.style.display="inline";setOutput(newoutput,"");setOutput(origoutput,"");var input=getInput();if(input===null){addOutput(origoutput,{type:"err",content:"Input is malformed. Using no input."});addOutput(newoutput,{type:"err",content:"Input is malformed. Using no input."});input=[]}doInterpret(getNewCode(),input,function(data){addOutput(newoutput,data)});doInterpret(getOriginalCode(),input,function(data){addOutput(origoutput,data)});evt.stopPropagation();return false}function onResetBtn(evt){setTextbox(getOriginalCode());origheader.style.display="none";newheader.style.display="none";setOutput(origoutput,"");setOutput(newoutput,"")}function escape(s){return s.toString().replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}window.alert=function(){};window.prompt=function(){};function doInterpret(code,input,cb){var workerCode=interpret.toString()+";function stdout(s){ self.postMessage( {'type': 'out', 'content': s} ); }"+" function stderr(s){ self.postMessage( {'type': 'err', 'content': s} ); }"+" function kill(){ self.close(); }"+" self.addEventListener('message', function(msg){ interpret(msg.data.code, msg.data.input); });";var interpreter=new Worker(URL.createObjectURL(new Blob([workerCode])));interpreter.addEventListener("message",function(msg){cb(msg.data)});interpreter.postMessage({"code":code,"input":input});setTimeout(function(){interpreter.terminate()},1E4)}setTimeout(function(){getOriginalCode();textbox.addEventListener("input",onTextboxChange);testbtn.addEventListener("click",onTestBtn);resetbtn.addEventListener("click",onResetBtn);setTextbox(getOriginalCode())},100);function interpret(code,input){window={};alert=function(s){stdout(s)};window.alert=alert;console.log=alert;prompt=function(s){if(input.length<1)stderr("not enough input");else{var nextInput=input[0];input=input.slice(1);return nextInput.toString()}};window.prompt=prompt;(function(){try{var evalResult=eval(code);if(typeof evalResult=="function"){var callResult=evalResult.apply(this,input);if(typeof callResult!="undefined")stdout(callResult)}}catch(e){stderr(e.message)}})()};</script> ``` [More about the test suite](http://meta.codegolf.stackexchange.com/questions/7113/a-golfing-snippet) **How it works** ``` //Define function w/ paramters a, b (a,b)=> //lowercase a //for each character v in a: [for(v of a[t="toLowerCase"]()) //lowercase b //remove the first instance of v in b //if b before removal equals b after removal (if nothing was removed): if((b=b[t]())==(b=b.replace(v,""))) //keep v in the array of a's values to keep v] //get the length of the computed array [l="length"] //add b's length +b[l] //implicitly return the sum ``` [Answer] # CJam, ~~23~~ 19 bytes ``` 2{'¡,lelfe=}*.-:z:+ ``` Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=2%7B'%C2%A1%2Clelfe%3D%7D*.-%3Az%3A%2B&input=All%20unique%20characters%20here!%0ABdfgjkmopvwxyz%3F). ### How it works ``` 2{ }* Do the following twice: '¡, Push the string of the first 161 Unicode charcters. lel Read a line from STDIN and convert it to lowercase. fe= Count the number of occurrences of each of the 160 characters in the lowercased line. .- Vectorized subtraction; push the differences of the occurrences of all 161 characters. :z Apply absolute value to each difference. :+ Push the sum of all results. ``` [Answer] # Ruby, 62 ``` #!ruby -naF| gets p$F.count{|c|!$_.sub!(/#{Regexp.escape c}/i){}}+~/$/ ``` There has to be a better way. Edit: 57 chars thanks to iamnotmaynard investigating a path I was too lazy to. ``` #!ruby -naF| gets.upcase! p$F.count{|c|!$_.sub!(c.upcase){}}+~/$/ ``` [Answer] # Python, ~~90~~ ~~87~~ ~~81~~ ~~80~~ 79 bytes ``` lambda a,b,s=str.lower:sum(abs(s(a).count(c)-s(b).count(c)))for c in{*s(a+b)})) ``` Python <3.5 version, 80 bytes ``` lambda a,b,s=str.lower:sum(abs(s(a).count(c)-s(b).count(c))for c in set(s(a+b))) ``` ### Explanation For each character in a or b, count up the number of occurrences in each string, and add the (positive) difference. Edit: Re-read rules, realized anonymous functions are acceptable, improved answer by getting rid of raw\_input. First golf, please be gentle! Thanks to sp3000 for the improvement of redefining str.lower and making me realize print was unnecessary. Also spaces. Still learning. Using python >=3.5, there's a shorter way of defining sets, so a byte can be saved over previous versions. [Answer] # Retina, ~~40~~ 20 bytes *20 bytes saved thanks to Martin Büttner.* Place each line in its own file and replace the `\n` with a literal newline. ``` +i`(.)(.*\n.*)\1 $2 . ``` [Answer] # [pb](https://esolangs.org/wiki/Pb), 648 bytes ``` ^w[B!0]{t[B]vb[T]^>}vb[-1]w[X!0]{<t[64]w[T!0]{w[B!0]{b[B-1]v}^[Y]t[T-1]}}w[B!-1]{w[B=0]{b[27]}t[26]w[T!0]{w[B!0]{b[B-1]v}^[Y]t[T-1]}>}b[0]w[X!0]{<w[B!0]{b[1]v}^[Y]w[B=0]{b[32]}w[B=1]{b[0]}}^w[B!0]{t[B]vb[B+T]^>}vb[1]<w[B!9]{t[B]b[0]vv<[X]w[B!0]{>}b[T]^^<[X]w[B!0]{>}<}b[0]<w[X!-1]{t[B]vb[1]^w[B!1]{>}vvw[X!-1]{w[B=T]{b[0]<[X]^w[B!1]{>}^b[0]vt[2]}<}^[Y]vw[B!1]{>}b[0]^<}t[0]w[B!1]{w[B!0]{t[T+1]b[0]}>}b[0]vvw[X!-1]{w[B!0]{t[T+1]b[0]}<}>b[11]^b[T]w[B!0]{vw[B!11]{>}t[B]b[0]>b[T]<[X]^t[B]b[0]vw[B!11]{>}<w[T!0]{t[T-1]b[B+1]w[B=11]{b[0]^<[X]b[B+1]vw[B!11]{>}<}}^<[X]}vw[B!11]{b[B+48]>}b[0]<w[B!0]{w[B!0]{>}<t[B]^^<[X]w[B!0]{>}b[T]<[X]vvw[B!0]{>}<b[0]<} ``` Takes input with a tab character separating the two strings. This one was a doozy. Actually implementing the algorithm wasn't the hard part, that came relatively easily. But I had to do two things that are difficult to do in pb: Case insensitivity and itoa. I happened to have a program for converting to lowercase just lying around (itself 211 bytes long) and everything else was tacked onto the end to do the work for this challenge specifically. [You can watch this program run on YouTube!](https://www.youtube.com/watch?v=RUbrhK1BIHY) There are a couple things you should keep in mind if you do: * This version of the program is slightly modified, weighing in at 650 bytes. The only difference is that 255 is used as a flag value instead of -1, because trying to print `chr(-1)` crashes the interpreter when running in watch mode. * The input in that video is `Hello, world!` and `Code golf.`. This is slightly different than one of the example inputs in the challenge; I used it because it was short but modified it so the correct output would be 10 instead of 9. This is just to show off that the number is printed correctly even if it's multiple digits, which is hard in pb. * The interpreter is awful, and it shows here. Notably, the tab character throws off the spacing so things aren't lined up for large portions of the video, whenever a byte is set to 10 it shows a line break even though the language still considers it to be one "line", and the fact that it just moves the cursor to the start instead of clearing the screen means that there are occasionally a number of characters in the video that aren't even really there, they just never went away from when they were there. There are some protections against this in pbi but the fact that `chr(10)` isn't handled properly makes them largely useless here. All that being said, I think it's almost kind of beautiful to watch. It's a huge mess of horrible code interpreting other horrible code, pieces of it breaking down in front of your eyes, and yet everything works just enough to get the right answer. It looks like garbage is being printed but if you watch closely enough with knowledge of the source you can make out what it's doing and why at any point. I feel like Cypher when I watch this video: `I... I don’t even see the code. All I see is blonde, brunette, red-head.` Without further ado, here's the code ungolfed. ``` ### UNTIL FURTHER NOTICE, ALL CODE YOU SEE HERE ### ### IS JUST A SIMPLE LOWERCASE PROGRAM. ALL INPUT ### ### IS PRINTED UNALTERED UNLESS ITS ASCII CODE IS ### ### IN [65, 90], IN WHICH CASE IT IS PRINTED WITH ### ### 32 ADDED TO IT. ### ^w[B!0]{t[B]vb[T]^>} # Copy entire input to Y=0 # (If the program ended here, it would be cat!) vb[-1] # Leave a flag at the end of the copy (important later) # Next, this program will set each of those bytes to 0 or 32, then add the input again. # A byte needs to be set to 32 iff it's in [65, 90]. # pb can't test > or <, only == and !=. # A workaround: # Set each byte to max((byte - 64), 0) w[X!0]{< # For each byte: t[64] # Set T to 64 as a loop variable w[T!0]{ # While T != 0: w[B!0]{ # While the current byte not 0: b[B-1]v # Subtract one from the current cell, then go down one # (guaranteed to be 0 and kill the loop) } ^[Y] # Brush is at Y=0 or Y=1 and needs to be at Y=0. # ^[Y] always brings brush to Y=0 t[T-1] # T-- } } # Bytes that are currently 0 need to be 0. # Bytes that are currently in [27, inf) need to be 0. # Bytes in [1, 26] need to be 32. # Set bytes that are equal to 0 to 27 # The only groups that have to be worried about are >26 and =<26. # Then set each byte to max((byte - 26), 0) w[B!-1]{ # Until we hit the flag: w[B=0]{b[27]} # Set any 0 bytes to 27 t[26] # T as loop variable again w[T!0]{ # While T != 0: w[B!0]{ # While the current byte not 0: b[B-1]v # Subtract one from the current cell, then go down one # (guaranteed to be 0 and kill the loop) } ^[Y] # Brush is at Y=0 or Y=1 and needs to be at Y=0. # ^[Y] always brings brush to Y=0 t[T-1] # T-- } >} b[0] # Clear the flag # Set bytes that are equal to 0 to 32 # All others to 0 w[X!0]{< # For each byte: w[B!0]{ # While the current byte not 0: b[1]v # Set it to 1, then go down one # (guaranteed to be 0 and kill the loop) } ^[Y] # Back to Y=0 no matter what w[B=0]{b[32]} # Set 0 bytes to 32 w[B=1]{b[0]} # Set 1 bytes to 0 } # Any byte that had a capital letter is now 32. All others are 0. # Add the original values to the current values to finish. ^w[B!0]{ # For each byte OF ORIGINAL INPUT: t[B]vb[B+T]^> # Add it to the space below } ### ABOVE IS THE ENTIRE LOWERCASE PROGRAM. THE ### ### REST OF THE CODE IMPLEMENTS THE ALGORITHM. ### vb[1] # Leave a flag after the end, guaranteed to be further right # than anything else <w[B!9]{ # Starting from the end, until hitting a tab: t[B]b[0] # Store the last byte and erase it vv<[X] # Go down two columns and all the way to the left w[B!0]{>} # Go right until reaching an empty space b[T] # Print the stored byte ^^<[X]w[B!0]{>} # Go back to the end of the first line < } b[0] # Erase the tab <w[X!-1]{ # For each byte in the first line: t[B] # Store that byte vb[1] # Mark that byte to be found later ^w[B!1]{>} # Find the flag at the end vvw[X!-1]{ # For everything in the other line: w[B=T]{ # If the current byte is the same as the saved byte: b[0] # Set it to 0 <[X]^ # Go to the beginning of line 2 w[B!1]{>} # Find the marker for where the program is working in line 1 ^b[0]v # Set that byte that the program is working on to 0 t[2] # Stay on line 2 and start looking for a 2 (will never appear) # (If this block was entered, it basically breaks the outer loop.) } < } ^[Y]v # Ensure that the brush is on Y=1 w[B!1]{>} # Find the marker for where the program is working in line 1 b[0]^< # Erase the marker and start working on the next byte } t[0] # Set T to 0. It's going to be used for counting the remaining bytes. w[B!1]{ # Until hitting the flag at the very right: w[B!0]{ # If the current byte is not 0: t[T+1] # Add 1 to T b[0] # Set the current byte to 0 } > } b[0] # Clear the flag vvw[X!-1]{ # Same as above, but for Y=2 w[B!0]{ t[T+1] b[0] } < } # T now contains the number that needs to be printed!! # Now, to print out a number in decimal... >b[11] # A flag that shows the end of the number # (so 0 digits aren't confused for other empty spaces on the canvas) ^b[T] # The number to be converted to digits w[B!0]{ # While the number to be converted is not 0: vw[B!11]{>} # Go to the flag t[B]b[0]>b[T] # Move it right <[X]^t[B]b[0] # Store the number to be converted to digits to T and clear its space on the canvas vw[B!11]{>}< # Go to the left of the flag w[T!0]{ # While T is not 0: t[T-1] # T-- b[B+1] # B++ w[B=11]{ # If B is 10: b[0] # Set it back to 0 ^<[X]b[B+1] # Add 1 to a counter to be converted after vw[B!11]{>}< # Go back to continue converting T } } ^<[X]} vw[B!11]{ # Add 48 to all digits to get correct ASCII value b[B+48]> } b[0] # Clear the flag value, 0s now appear as 48 instead of 0 so it is unnecessary <w[B!0]{ # While there are digits on Y=2: w[B!0]{>}< # Go to the last one t[B] # Save it to T ^^<[X] # Go to (0, 0) w[B!0]{>} # Go right until finding an empty space b[T] # Print the digit in T <[X]vvw[B!0]{>} # Go to the end of Y=2 <b[0] # Erase it < # Repeat until finished. :) } ``` [Answer] # C++ 199 bytes Uses an array to store the count of each character in the first string, minis the count in the second string. Next it finds the sum of the absolute values of the elements of the array: this is the distance. Golfed: ``` #define L(c) c<91&c>64?c+32:c int d(char*a,char*b){int l[128];int i=128,s=0;for(;i-->0;)l[i]=0;for(;a[++i];)l[L(a[i])]++;for(i=-1;b[++i];)l[L(b[i])]--;for(i=0;++i<128;)s+=i[l]>0?i[l]:-i[l];return s;} ``` Ungolfed: ``` #define L(c) (c<='Z' && c>='A' ? c+'a'-'A':c) //convert to lower case int dist(char a[],char b[]){ int l[128]; int i = 128, s = 0; for(;i-->0;) l[i]=0; for(;a[++i]!='\0';) l[L(a[i])]++; for(i=-1;b[++i]!='\0';) l[L(b[i])]--; for(i=0;++i<128;) s+=i[l]>0?i[l]:-i[l]; return s; } ``` [Answer] # PowerShell, 79 bytes ``` param($a,$b)$a=[char[]]$a.ToLower();$b=[char[]]$b.ToLower();(diff $a $b).Length ``` Almost the exact same code as my answer on [Anagram Code Golf](https://codegolf.stackexchange.com/a/54496/42963) ... but ... I'm getting some weird behavior if I just snip off the `-eq0` from that answer, so I wound up needing to explicitly `.ToLower()` and recast outside of the `param` declaration.+ Explanation also (mostly) copied from that answer -- Takes the two string inputs, makes them lowercase, and re-casts them as char-arrays. The `diff` function (an alias for `Compare-Object`) takes the two arrays and returns items that are different between the two. We leverage that by re-casting the return as an array with `()`, and then checking its length. +For example, I was getting bogus results with `param([char[]]$a,[char[]]$b)(diff $a $b).length` on the `all lowercase.`/`ALL UPPERCASE!` test. If I manually separated out the arrays (e.g., ran `(diff ('a','l','l'...`), it worked fine, but would fail every time there were capital/lowercase overlap with the casting. Everything I can read on the documentation states that `diff` is case-insensitive by default, so ... *shrug???* [Answer] # Bash, ~~68~~ 67 bytes ``` f()(fold -w1<<<"$1"|sort) diff -i <(f "$1") <(f "$2")|grep -c ^.\ ``` I *think* this works. Note the trailing space on the second line. ### Test cases ``` $ ./anagram "Hello, world!" "Code golf!" 9 $ ./anagram "12345 This is some text." ".txet emos si sihT 54321" 0 $ ./anagram "All unique characters here!" "Bdfgjkmopvwxyz?" 42 $ ./anagram "This is not exactly like Levenshtein distance," "but you'll notice it is quite similar." 30 $ ./anagram "all lowercase." "ALL UPPERCASE!" 8 ``` [Answer] **Perl, ~~52~~ 46 bytes + 3 switches (a,F,n) = ~~55~~ 49 bytes** ``` # 49 bytes (prefix 'x' to all characters so that values() could be removed) perl -naF -E 'END{$c+=abs for%a;say$c}$a{x.lc}+=2*$.-3 for@F' # 55 bytes perl -naF -E 'END{$c+=abs for values%a;say$c}$a{+lc}+=2*$.-3 for@F' ``` Takes input from STDIN with the input strings in their own lines, terminated by EOF. Switches: ``` -aF splits each input line into characters and stores this into @F -n loop over all input lines -E Execute the script from the next arg ``` Code: ``` # %a is the hash counting the occurances of the lowercase characters # $. has the line number. Thus, 2*$.-3 is -1 for line 1 and +1 for line 2 $a{+lc}+=2*$.-3 for @F # In the end (assuming 2 lines have been read), sum up the absolute values # from the hash %a. Note that if a character occured more times in string 1 # its value be negative, if more in string 2 then positive, otherwise 0. END { $c+=abs for values %a; say $c } ``` [Answer] # Bash + GNU utils, 53 ``` S(){ sed 's/./\L&\n/g'|sort;};S>1;S|comm -3 1 -|wc -l ``` `sed` transforms to lowercase and splits the string into lines for `sort`. Since we need to do this twice I put it into a function. `comm3 -3` filters out the relevant lines and `wc -l` produces the number. Input is via `STDIN`; since two commands read sequentially, you have to send `EOF` (Ctrl-D) twice, between the strings and at the end. Overwrites file `1`, if present. [Answer] # Matlab, 91 bytes ``` function r=f(s,t) s=lower(s);t=lower(t);u=unique([s t]);r=sum(abs(histc(s,u)-histc(t,u))); ``` [Try it online](http://ideone.com/qeicLU). This works as follows: 1. Converts the strings to lower case. 2. Finds the **unique characters** of the two strings together. That is, determines all characters that ever appear in the strings. 3. Computes the **histogram** of each string. That is, for each string finds how many times each of the characters obtained in step 2 appears. 4. **Subtracts** the histograms and takes the absolute value of the differences. This represents how many times a character appears in one string **more** than in the other. 5. The result is the sum of those absolute differences. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes ``` Œlœ^/L ``` [Try it online!](https://tio.run/##FczLDcIwEEXRVt5uNhE0kiU7PpIxT8rA4Ag8RrgNqCl1DUS623OvNOsRy8eW72k7RsRedpNW/Cuzg@@U3TpMb8TIF0udnFpw0eqpZA4yQM7N0ed2ELNVaSbU18WjqRNV72rpuZHjDw "Jelly – Try It Online") [Answer] # F#, ~~134~~ 126 bytes ``` let g=Seq.countBy Char.ToLower>>List.ofSeq let f a b=g a@g b|>Seq.groupBy fst|>Seq.sumBy(snd>>Seq.map snd>>Seq.reduce(-)>>abs) ``` **Explanation**: 1. Count the number of times each (lowercased) character appears in `a` and `b` separately. 2. Group the counts together by their common character 3. Reduce each group with the `-` operator, which has the following effect: * If only one value is found (i.e. the character appeared in only one input), that value is returned. * If two values are found (i.e. the character appeared in both inputs) subtract the second value from the first. 4. Sum the absolute value of the values from the previous step. [Answer] # [Scala](http://www.scala-lang.org/), 134 81 bytes Thanks @ASCII-only for their work. ``` (s,t)=>{var k::l::_=List(s,t)map(_.toLowerCase.toBuffer) ((k--l)++(l--k)).length} ``` [Try it online!](https://tio.run/##XZBda8IwFIbv/RVHb9ZiLej0puCGimODDsZ0V2NIbE9tbJrU5NSPjf12dyobDOFAwuH9SB6XCCXOZr3FhOBZSA14JNSpg0lVfbX2wkIWPdQ6IWn04H1BVupN8Hs8afoYnz0XkD@@@2q0RRSpKFqNY@nosi9F5a1CMrE5oJ0Jh3yf1lmG1m95XtHrKb/b9VSvV/h@qFBvKP8@V5xOSnuZ13lEpUwAB2NV2u4EnZlJETZGZe2O77f@CfuD2@EIlrl0wONMiUD8lZA9IR2RAEvDe8mTL2E0vB30rxImSkGt5a5GSHJhRUJoHeRosSmeptlmW5Sm2h@Op8/7K@9frzZcdGSrOoGSBUKMe9QuJ2SyKUMROsGA49Y1wcnUN9zJHpkgSGoCdrUk5DeWUgkbXrUIVqsGZNKA5JRJHMPby8v8dTZZzC9EWt/nHw "Scala – Try It Online") ]
[Question] [ There's a little improv warm up game where you arrange yourselves in a circle and send zips, zaps, and zops around by pointing to a person and saying the next word in the sequence, then they do the same until all of you are warmed up or whatever. Your task is to create a program that gives the next word in sequence given an input word. (Zip --> Zap --> Zop --> Zip) Since there's a lot of different ways to say these three words and flairs that can be added to them, your program should imitate case and letter duplication and carry suffixes. To elaborate, your input will be one or more `Z`s, then one or more `I`s, `A`s, or `O`s (all the same letter), then one or more `P`s, (all letters up to this point may be in mixed case) followed by some arbitrary suffix (which may be empty). You should leave the runs of `Z`s and `P`s, as well as the suffix exactly as received, but then change the `I`s to `A`s, `A`s to `O`s, or `O`s to `I`s, preserving case at each step. ## Example Test Cases ``` zip ==> zap zAp ==> zOp ZOP ==> ZIP ZiiP ==> ZaaP ZZaapp ==> ZZoopp zzzzOoOPppP ==> zzzzIiIPppP Zipperoni ==> Zapperoni ZAPsky ==> ZOPsky ZoPtOn ==> ZiPtOn zipzip ==> zapzip zapzopzip ==> zopzopzip zoopzaap ==> ziipzaap ``` ## Rules and Notes * You may use any convenient character encoding for input and output, provided that it supports all ASCII letters and that it was created prior to this challenge. * You may assume the input word is some variant of Zip, Zap, or Zop. All other inputs result in undefined behavior. + Valid inputs will full-match the regex `Z+(I+|A+|O+)P+.*` (in mixed case) Happy Golfing! [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~69 63 57~~ 54 bytes ``` s=>Buffer(s).map(c=>s|c%4<1?s=c:c+c*90%320%34%24-8)+'' ``` [Try it online!](https://tio.run/##ZZBBa8JAEIXv/opcwiaK2moOtjSK3nLaPee2rIlMazNDVgsN/vd0U4aIzoO9fHzsG96n/bHetUCXeYPHqq/z3ufbw7Wuqzbx6eLbUuLyrb@5OPt43fncvbuZm769xOtVeFm8yuabdKZU77DxeK4WZzwldaI6IBVx0jRaLqPO0uRZ2gtJC6nU5kkqCyMkgNFiyVppBUhcyVaJSPKuEI3aEBnFd4UUUAxEVhNVLTag7tVMhLo3/uv3oV8PRHhoLrp58GAgEznyuPM4ciDCCxRZZQ@ZCDXs0YWV1P1LgH/S/wE "JavaScript (Node.js) – Try It Online") ### How? We process the input string \$s\$ character by character. We reuse \$s\$ as a flag: as soon as a numeric value is stored in it, we know that we must not update anything else. To identify `"p"` (112) and `"P"` (80), we use the fact that their ASCII codes are multiples of \$4\$ and the ASCII codes of the other letters at the beginning of the string (`"z"`, `"Z"` and vowels) are not. To turn a vowel with ASCII code \$c\$ into its counterpart \$n\$ while leaving `z` and `Z` unchanged, we use the following function: $$n=c+((((90\times c) \bmod 320)\bmod 34)\bmod 24)-8$$ ``` letter | ASCII code | * 90 | % 320 | % 34 | % 24 | - 8 | new letter --------+------------+-------+-------+------+------+-----+----------------------- 'i' | 105 | 9450 | 170 | 0 | 0 | -8 | 105 - 8 = 97 -> 'a' 'a' | 97 | 8730 | 90 | 22 | 22 | 14 | 97 + 14 = 111 -> 'o' 'o' | 111 | 9990 | 70 | 2 | 2 | -6 | 111 - 6 = 105 -> 'i' 'z' | 122 | 10980 | 100 | 32 | 8 | 0 | 122 + 0 = 122 -> 'z' 'I' | 73 | 6570 | 170 | 0 | 0 | -8 | 73 - 8 = 65 -> 'A' 'A' | 65 | 5850 | 90 | 22 | 22 | 14 | 65 + 14 = 79 -> 'O' 'O' | 79 | 7110 | 70 | 2 | 2 | -6 | 79 - 6 = 73 -> 'I' 'Z' | 90 | 8100 | 100 | 32 | 8 | 0 | 90 + 0 = 90 -> 'Z' ``` ### Commented ``` s => // s = input string Buffer(s) // convert it to a Buffer of ASCII codes .map(c => // for each ASCII code c in s: s | // if s is numeric c % 4 < 1 ? // or c is either 'p' or 'P': s = c // turn s into a numeric value and yield c : // else: c + // update c c * 90 % 320 // by applying the transformation function % 34 % 24 // (see above) - 8 // ) + '' // end of map(); coerce the Buffer back to a string ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~81 ... 61 48~~ 46 bytes *Saved 2 bytes thanks to [@Grimy](https://codegolf.stackexchange.com/users/6484/grimy)* Port of my [JS answer](https://codegolf.stackexchange.com/a/180470/58563). Outputs by modifying the input string. ``` f(char*s){for(;*++s%4;*s+=*s*90%320%34%24-8);} ``` [Try it online!](https://tio.run/##lZI/a8MwEMX3fAqhYvCfuCmOhxa3hYyepDltB6HEydFUEpZLqUO@et1zERnkweqBBDq930MPncwPUg43oOTpc7cnj7bbgb49Pg9NLI@iTW1ybnQbV2mW2aisUps9pTZ9uIvWBa4yKsr8PqkuA6iOfAhQcULOC0JGltiXdfFW4cmaFu@b2C4J7cFQ4iqpCDZxd/c0sq@KLsnYIqsV6YXx6c0/aObTW8aD6W3NfRrgis/SQkxw7Bn3@ll8q7WZZMdimnFjOJ3NjlVDPWonKYzZt1oBDUnhtL7Hhtv378AobNT6Bpp3TAUawKidTtF1kAKmCLW@ATa185g10E7re@An9fipNOQRAH/axWX4kc1JHOyQf/0C "C (gcc) – Try It Online") ### Commented ``` f(char * s) { // f = function taking the input string s for(; // for each character *s in s: *++s % 4; // advance the pointer; exit if *s is either 'p' or 'P' (it's safe // to skip the 1st character, as it's guaranteed to be 'z' or 'Z') *s += // update the current character: *s * 90 % 320 // apply a transformation formula that turns % 34 % 24 // a vowel into the next vowel in the sequence - 8 // while leaving 'z' and 'Z' unchanged ); // end of for() } // end of function ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 19 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` Ç╛√êΣ%,╖FP╚`=Lh←⌡·ƒ ``` [Run and debug it](https://staxlang.xyz/#p=80befb88e4252cb74650c8603d4c681bf5fa9f&i=zip%0AzAp%0AZOP%0AZiiP%0AZZaapp%0AzzzzOoOPppP%0AZipperoni%0AZAPsky%0AZoPtOn%0Azipzip%0Azapzopzip%0Azoopzaap&a=1&m=2) [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 21 bytes ``` iT`Io`A\OIia\oi`^.+?p ``` [Try it online!](https://tio.run/##JYuxCsMwDER3/UegUMgvBE8lkzxkEqFYQwZRsI4kS/3zjprecHc8ePt2WtU@PF6l21JmL2nl2XR1K@/xOaH3ZqCWQMKZxCxKVBEsws4Z@HFg270aScrH50vi@eRK4d66ovn/eWzoFw "Retina 0.8.2 – Try It Online") Transliterates letters up to and including the first `p`, although the `z` and `p` aren't in the transliteration section so aren't affected. The first `O` is quoted because it normally expands to `13567` and the second `o` is quoted because it too is magic; in the first part of the transliteration it expands to the other string. The resulting transliteration is therefore from `IAOIiaoi` to `AOIiaoi` then removing the duplicate source letters results in `IAOiao` to `AOIaoi`. [Answer] # C, 43 bytes ``` f(char*s){for(;*++s%4;*s^=*s%16*36%98%22);} ``` [Try it online!](https://tio.run/##lZLNasMwEITveYpFwWA7SUOdElLcFnL0STq7PyCUOFmaSsJyKXXIq9eVi8hBPljdg0Cr@YYdtGJxEKKbohSnz90eHkyzQ3VzfOqqWBx5nZrkXKk6ztPZzER3eWreHlMT3a7T1Tq630RZluSXDmUDHxxlnMB5AtCDYJ5X2Wtub0bX9r2KzRxIi5qAqyQH27SneyeReZFkDn0Llktoufbp7T9o6tMlZcF0WTCfRrziozTnA9z2tJt@FC@V0oPstqiiTGtGRrPbKrDotYMUWu9rJZGEpHBa32PLzPt3YBTaa30DxRoqAw2w1w636LpIAVtktb6BbSrnMWqgnNb3sJ/U2k8lIUMg/mknl@5HVCd@MN3i6xc) Based on [Arnauld's answer](https://codegolf.stackexchange.com/a/180472/6484). I did a brute-force search to find the shortest formula that turns a => o, o => i, i => a, z => z. [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~22~~ 20 bytes -2 bytes thanks to [Oliver](https://codegolf.stackexchange.com/users/61613/oliver) ``` r"%v+"_d`i¬iao¯`pu}" ``` [Try it online!](https://tio.run/##y0osKPn/v0hJtUxbKT4lIfPQmszE/EPrEwpKa5X@/49WqsosUNJRqnIEkVH@ASAyMxNMRSUmFoDlgMA/3z@goAAiW1CQWpSflwliOwYUZ1eCGPkBJf55ILWZBVADEwuq8mHsfCALaBgu4Vgu3VwA "Japt – Try It Online") [Answer] # [R](https://www.r-project.org/), 110 76 bytes -36 bytes thanks to Krill This function takes an input of one string. ``` function(a)sub(s<-sub('z+(.+?)p.*','\\1',a,T),chartr('aioAIO','oaiOAI',s),a) ``` [Try it online!](https://tio.run//##Vc69DoIwEADg3adwK5WWxJ3EdHRqByfCcgKGiwl3KTDIy9dSMOotl@9@cueDL3V4zEMzIQ0ZyHG@Z2Op1ySWPCvyi@TiJJSo67NQoG5SNT34yWcCkMzVxhYBWnMVapQKZIidBVnI4xaH1ebflXUfJyLuTqoAOM6nxRiWrGN2W6FC5s7TgOt8Khg3Pl8/2@QmO3wdX9m@SQBeaPdWoMh4br@GrEG3XadbIt1CL2R4Aw "R – Try It Online") [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~41~~ 33 bytes ``` {S:i{.+?p}=$/~~tr/iaoIAO/aoiAOI/} ``` [Try it online!](https://tio.run/##XY@xCoMwEIbn3lNkKNJS0K1DwRbHTAl0y5ZB4WjrHepiRF/dntaK7Q0J3xfycz/n1fM8vloVFSpVY3e/YBefbtyn@2QYmipBTzoziSfMjE76saBKHZ5Y5vVRdbCrfaviqIB@DMjqO2l6VcEzhOzPGQZn7I9z2oJDtD/Oe5FyMm@kI2LJlDFkLLP9ZMpo1BNLDnNeUYlrzsLgMls/2k2YmRgc2caUG40Tg3RZ6yxdhGG6aHmZNS0MQVYLsu76AXHmNw "Perl 6 – Try It Online") Simple case-insensitive substitution to shift the vowel section. [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~81~~ 78 bytes ``` lambda s,p='iaoIAO':''.join(('aoiAOI'+c)[(p:=p*(ord(c)%4)).find(c)]for c in s) ``` [Try it online!](https://tio.run/##JYs9T8QwEER7/wo3yLscinRAgSKlSJnKqc0hZPJxt3fH7soJRfLngwNTzDyN9HSZL8Ivb5q2sTpt9/j91Uc7PWnlKEpTe1c6V1yFGMBFodo37tDhO2hZ6SNI6qHDh1fEYiTe@WOUZDtLbCfcdv7cOUU@D3B8xtJYTcQzjECsPzMg4raSmrVWE3xrAlGuEKPmL8eLb1X3X3VIwmRC3U63xQRpZ88mu3961FX@SfJm/Rc "Python 3.8 (pre-release) – Try It Online") # [Python 2](https://docs.python.org/2/), 98 bytes ``` lambda s:''.join(('aoiAOI'+c)[(-~-('p'in s[:i].lower())*'iaoIAO').find(c)]for i,c in enumerate(s)) ``` [Try it online!](https://tio.run/##ZY@xTsMwEIb3PIUVBttAI9GxUpAyZnLmlAqZ1CkHre/kpELNwKuHM2kUFW456ft8v/zTpX9Hvx7b/GU82tPb3opuI2X2geCVkhahMKV8aPRWrb5XSpIEL7rtBnbZEb9cUFrfS7BYFkbqrAW/V43etRgEPDaC3zp/Prlge6c6rccoXiMO1h@celrrTSIogO9Fq8DTuefAMR2AUjHPXZ4/i8FSkg7FP2wY16b6g@uyYgyw8AlbGzkvmoMmXiNSzOcxaCoiPpzyeUooI4mBRC6gh3QJvBKWRdV9Xm5STSRssOqNvzEQSRJrLk3nmkzY8MZZTgavhCX/duAO6XIG8Et@AA "Python 2 – Try It Online") [Answer] # [Java (JDK)](http://jdk.java.net/), 52 bytes ``` s->{for(int i=0;s[++i]%4>0;)s[i]^=s[i]%16*36%98%22;} ``` [Try it online!](https://tio.run/##bU1ba8IwFH7vrzgIgXorzg3Z7CqIz6MF31o6yGrrjtokJKlDxd@eJW0ZjC2Qc/ku5zvQM50edkeDteBSw8HuQaPxFIxC7w9WNazQyNm/pNKypLWjvOJElYI3igxuHoBoPk5YgNJU23bmuIPacv5WS2T7LAcq92rYSgE2nKmmLuVr8Ulllq@ggsio6epWcekj04DRLFTZeIw5eVrNwqHKMH@PXCUPi9Hjgrw8k/k8vJuwvedsXZCLWf7KAuhC2qYgcmSg@cZuaynpxR@Gva4KaFGUQvut8gfeXpQu64A3OhA2Qlf@gKglEEXYYOKuTYCVX9Dl997efPfcvxtzRWGua2HSODEpoi0ppcJi9sU8ToRwuBCl5AxNuk7U8WJSnuiYOW9rp@LKu4nbbu3f "Java (JDK) – Try It Online") * Port of Grimy's C answer. Make sure to upvote his answer! [Answer] # Perl 5, 31 bytes ``` s/.+?p/$&=~y,iaoIAO,aoiAOI,r/ei ``` [TIO](https://tio.run/##JYuhDgIxEET9fgfBXKEKSUjlqa2uq6jYHOlO2jNXwadTFhgxM3nJQ2nP25zdX5cH/Ol8fx1Osq6BXVYJvLrmi8w5BDQCKHGkJGKVcoYxCytH4MuB0rQKpRD7dlDSuHMlc396xtD/U1vT34pdtPZ5wQc) [Answer] # [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), 183 bytes ``` INPUT (BREAK('Pp') SPAN('Pp')) . P REM . S A P 'a' ='o' :S(A) Z P 'A' ='O' :S(Z)F(P) I P 'i' ='a' :S(I) K P 'I' ='A' :S(K)F(P) O P 'o' ='i' :S(O) L P 'O' ='I' :S(L) P OUTPUT =P S END ``` [Try it online!](https://tio.run/##Jc4xC8IwEAXgOfkVtyW3ODkJHU6MEFKTo2kHs9WtIEbw/xN76fQeH294v0991fe5NeUjLzPY6@QoWMNfg5CZ4lERTsAwuceeWZNiMKuBwVSjLtkS6iJEQqlTwbtl1F54E147e9RByAtRp3Ask3AV3jon1KNQEvKdRtSs0jLLz4H3Hy7eWivEOTz/ "SNOBOL4 (CSNOBOL4) – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 84 bytes ``` f=lambda s,r='':s[0]in'pP'and r+s or f(s[1:],r+('aoiAOI'+s[0])['iaoIAO'.find(s[0])]) ``` [Try it online!](https://tio.run/##RZCxbsUgDEXn9ivYnCioajtGSqWMTDAHMVClUa32YQvS4eXnUwJJy3TPvbYx8H39pPC678vw7W/vsxdJxgGgT/bZYQA24MMsYpcERbE0yb70TsauAU84agXdUdhaQE9q1PC0YJib4rl2X3IPBpaCflbOSlgLGzJIAZtncFJkHivrkydtDp6UORmxGt5fTpZcmqaJiK85@WjShrmUH6hQFTznMH9ECliHXVCz0aSvewl0UdUls@pQXCyq3oP8/4RDVTdr@gvogprlJbe8cokQq3auf3zgiGGtPwTD8JYLliZTu/8C "Python 2 – Try It Online") [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 60 bytes ``` n=>{for(int i=0;n[i]%4>0;)n[i]^=(char)(n[i++]%16*36%98%22);} ``` Based off of Grimy's C answer. [Try it online!](https://tio.run/##JUzfS8MwEH7PX9GXssRhmVOGo6ZQxAdBaNGBkNnBkWXuUC4hDcI69rfXq97Dd999P87217bHsbYJPT3YI8RtVx30SLo6H3yUSClDvShpi11@Vy1KNbGdllNUST7m8y6/WV3drvL1fb5cqvIyloKrDuxR/kDMIEPKnql4dbDf@CfaS1W8hW9McvZBM6XOYkolDcXG1zHCSSp@IBPje8TkXpCc7FNE@iwePVlI7LF5GQcMYqiDME0rDCKDAQis8TS@aUOY9BBc9ITC1G3/dRLGt6khwd2/OoTB/zPPm@u/ "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # C/C++ (VC++ compiler) 192bytes this is a rather naive try but anyway ``` void f(char*I){int c[]={-8,14,6},B=1,v[]={105,97,111},j=0;for(*I;*I>0&B;I++){if(*I==80|*I==112){B=0;break;}if(*I==90|*I==122){}else{for(j;j<3;j++){if(*I==v[j]|*I==v[j]-32){*I+=c[j];break;}}}}} ``` some slightly more readable Version is this ``` #include "stdafx.h" void f(char * theString) { signed int change[] = {'a'-'i','o'-'a','o'-'i'}; // add this to the vowel to get the next one char theVowels[] = {'i','a','o'}; int breaker = 1; printf("Input %s\n",theString); for (int i = 0;(theString[i] != '\0') && breaker; i++) { switch (theString[i]) { case 'Z': /*fall through*/ case 'z': break; case 'P': /*fall through*/ case 'p': breaker = 0; break; default: { for (int j = 0; j < 3; j++) { if ((theString[i] == theVowels[j]) || (theString[i]==(theVowels[j]-'a'+'A'))) { theString[i] += change[j]; break; } } } break; } } printf("Output %s\n",theString); } int main() { char theString[]= "zzzzIIIIp0815-4711"; // a test string f(theString); return 0; } ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 40 bytes ``` $_[$&]=$&.tr"IAOiao","AOIaoi"if/z+.+?p/i ``` [Try it online!](https://tio.run/##XY9BCsIwEEX3OUUJpRu1PUGVLLNK1hGRCAqD0BnaumgOb5zUWFpnkfBeyGd@/7pNMZbXc1ld2rKqx15qZcCj3EtltEeQ8GjCrt6dqIEYA1Dxm7Y9FsGTCOrPGRLO2I1z2goHYDfOe5Z8Eq2kQyTO5DFoLJH9ZvJo0Ik5h@jeYwdLTmbhlB2e0yrMJBYO7Wi6lYbEgrssdXIXZpEuzC@zxswi8GqB110@AMz8RhoBuyEe6AM "Ruby – Try It Online") [Answer] # [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/wiki/Commands), 22 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` l'pkIg‚£ć…iaoDÀ‚Du+`‡ì ``` [Try it online](https://tio.run/##MzBNTDJM/f8/R70g2zP9UcOsQ4uPtD9qWJaZmO9yuAHIdynVTnjUsPDwmv//ozILAlKL8vMyAQ) or [verify all test cases](https://tio.run/##MzBNTDJM/V9TVmmvpPCobZKCkn2ly/8c9YLsyvRHDbMOLT7S/qhhWWZivsvhBiDfpVQ74VHDwsNr/uv8r8os4KpyLOCK8g/gisrMBBJRiYkFQDEg8M/3DygoAIkXFKQW5edlckU5BhRnV3JF5QeU@OdxAfWCtScWVOVDWPlAGqgdAA). Can definitely be golfed a bit more.. Uses the legacy version of 05AB1E instead of the Elixir rewrite, because `+` merges fields in same-length lists, whereas the new version would need a [pair-zip-join `‚øJ`](https://tio.run/##yy9OTMpM/f8/R70g2zP9UcOsQ4uPtD9qWJaZmO9yuAHIdykFEod3eCU8alh4eM3//1GZBQGpRfl5mQA) instead. **Explanation:** ``` l # Lowercase the (implicit) input-string # i.e. "ZipPeroni" → "zipperoni" 'pk '# Get the index of the first "p" # i.e. "zipperoni" → 2 Ig‚ # Pair it with the length of the entire input-string # i.e. 2 and "zipperoni" → [2,9] £ # Split the (implicit) input-string into parts of that size # i.e. "ZipPeroni" and [2,9] → ["Zi","pPeroni"] ć # Extract head: push the head and remainder separately to the stack # i.e. ["Zi","pPeroni"] → ["pPeroni"] and "Zi" …iao # Push string "iao" DÀ # Duplicate, and rotate it once towards the left: "aoi" ‚ # Pair them up: ["iao","aoi"] Du # Duplicate and transform it to uppercase: ["IAO","AOI"] + # Python-style merge them together: ["iaoIAO","aoiAOI"] ` # Push both strings to the stack ‡ # Transliterate; replacing all characters at the same indices # i.e. "Zi", "iaoIAO" and "aoiAOI" → "Za" ì # Prepend it to the remainder (and output implicitly) # i.e. ["pPeroni"] and "Za" → ["ZapPeroni"] ``` [Answer] # PHP, 30 bytes too simple for a TiO: ``` <?=strtr($argn,oiaOIA,iaoIAO); ``` Run as pipe with `-nF`. For PHP 7.2, put the string literals in quotes. ]
[Question] [ # Challenge Given a list of positive integers, find if there exists a permutation where taking up to one bit from each of the integers, a binary number consisting of all `1`s can be created. The number of bits in the resulting binary number is equal to the highest [MSB](https://en.wikipedia.org/wiki/Most_significant_bit) in the list of integers. # Output Your code must output or return a [truthy/falsey](https://codegolf.meta.stackexchange.com/questions/2190/interpretation-of-truthy-falsey) value indicating if such a permutation exists. # Examples **Truthy:** With the list `[4, 5, 2]`, and its binary representation `[100, 101, 10]`, we can use the third, first, and second bits, respectively, to create `111`: ``` 4 -> 100 -> 1~~0~~~~0~~ -> 1 5 -> 101 -> ~~1~~~~0~~1 -> 1 2 -> 010 -> ~~0~~1~~0~~ -> 1 Result 111 ``` With the list `[3, 3, 3]`, all of the numbers have both first and second bits set as `1`, so we can take our pick with a number to spare: ``` 3 -> 11 -> 1~~1~~ -> 1 3 -> 11 -> ~~1~~1 -> 1 3 -> 11 -> ~~11~~ -> Result 11 ``` **Falsey:** With the list `[4, 6, 2]`, none of the numbers have the first bit set as `1`, so the binary number cannot be created: ``` 4 -> 100 6 -> 110 2 -> 010 ``` With the list `[1, 7, 1]`, only one of the numbers has the second and third bits set as `1`, and the number cannot be created: ``` 1 -> 001 7 -> 111 1 -> 001 ``` Obviously, if the maximum number of set bits exceeds the number of integers, the result number can never be created. # Test cases **Truthy:** ``` [1] [1, 2] [3, 3] [3, 3, 3] [4, 5, 2] [1, 1, 1, 1] [15, 15, 15, 15] [52, 114, 61, 19, 73, 54, 83, 29] [231, 92, 39, 210, 187, 101, 78, 39] ``` **Falsey:** ``` [2] [2, 2] [4, 6, 2] [1, 7, 1] [15, 15, 15] [1, 15, 3, 1] [13, 83, 86, 29, 8, 87, 26, 21] [154, 19, 141, 28, 27, 6, 18, 137] ``` # Rules [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. As this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest entry wins! [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes ``` BUT€ŒpṬz0PẸ ``` [Try it online!](https://tio.run/##bZAtEsIwEIU9p8gBIrqbhqQWg0WAykRimAosSAyec/QAFMtwkHKR8LYpKYKZ/Oxuvux7yWHftqeUVrvt@9K9bseh787VZnjc0/OKCsY6pRACRb1QKpBWnCOjlZmjktRa2cKAnsaU42ieuWYZMeHaUrhGK4dmFrnHzk2G2OCwAWkAMFUgvcNSoey8lKOAIUzCXCxI418/7o@Z2awdn/IFTDbhpQF0oSOiLGnpUWfTVMvPgGA3ChJCMi7G@AE "Jelly – Try It Online") ### How it works ``` BUT€ŒpṬz0PẸ Main link. Argument: A (array) Example: A = [4, 5, 2] B Binary; convert each n in A to base 2. [[1, 0, 0], [1, 0, 1], [1, 0]] U Upend; reverse all arrays of binary digits. [[0, 0, 1], [1, 0, 1], [0, 1]] T€ Truth each; for each binary array, get all indices of 1's. [[3], [1, 3], [2]] Œp Take the Cartesian product of all index arrays. [[3, 1, 2], [3, 3, 2] Ṭ Untruth; map each index array to a binary arrays with 1's at at the specified indices. [[1, 1, 1], [0, 1, 1]] z0 Zip/transpose the resulting 2D array, filling shorter rows with 0's. [[1, 0], [1, 1], [1, 1]] P Take the columnwise product. [1, 0] Ẹ Any; yield 1 if any of the products is non-zero, 0 otherwise. 1 ``` [Answer] # [J](http://jsoftware.com/), 30 bytes All credit goes to my colleague [Marshall](https://www.dyalog.com/meet-team-dyalog.htm#Marshall). Unnamed tacit prefix function. ``` [:+./ .*(1->./@${.|:)^:2@|:@#: ``` [Try it online!](https://tio.run/##TY5dCsIwEITfPcWAPrT@pN1NYv5Qeg9BkNJSfPEA9u5x04KUhOwyGeabd87jLeIRT6qBOlZ0uaumO3zVHOtn5G6O3T7moZ8@GDG8@gmUQOAEDb08ZRjYItF6ZLH/m2AZRAZX@QlwGtbAa3BIYE0IDB3A1IK8A7UE50XZbZHVmWtxF4TkrCS35SxoK12Kpku8F1uAh2SyrIvXlAJkpL0HOwkiL26Xfw "J – Try It Online") (`@` is function composition) `#:` antibase-2 `|:` transpose `(`…`)^:2` apply the following function twice:  `1-` Boolean negate  `>./` the maximum  `@` of the  `$` axis lengths  `{.` take (padding with zeros) from  `|:` the transposed argument `+./ .*` ["crazy determinant magic"](http://www.jsoftware.com/help/dictionary/d300.htm)\* `[:` don't hook (no-op – serves to compose the previous part with the rest) --- \* In Marshall's words. [Answer] # JavaScript (ES6), ~~104~~ ... ~~93~~ 83 bytes Returns `0` or `1`. ``` f=(a,m=Math.max(...a),s=1)=>s>m|a.some((n,i)=>n&s&&f(b=[...a],m,s*2,b.splice(i,1))) ``` ### Test cases ``` f=(a,m=Math.max(...a),s=1)=>s>m|a.some((n,i)=>n&s&&f(b=[...a],m,s*2,b.splice(i,1))) console.log('Truthy') console.log(f([1])) console.log(f([1, 2])) console.log(f([3, 3])) console.log(f([3, 3, 3])) console.log(f([4, 5, 2])) console.log(f([1, 1, 1, 1])) console.log(f([15, 15, 15, 15])) console.log(f([52, 114, 61, 19, 73, 54, 83, 29])) console.log(f([231, 92, 39, 210, 187, 101, 78, 39])) console.log('Falsy') console.log(f([2])) console.log(f([2, 2])) console.log(f([4, 6, 2])) console.log(f([1, 7, 1])) console.log(f([15, 15, 15])) console.log(f([1, 15, 3, 1])) console.log(f([13, 83, 86, 29, 8, 87, 26, 21])) console.log(f([154, 19, 141, 28, 27, 6, 18, 137])) ``` ### Method Given the input array **A = [a0, a1, ..., aN-1]**, we look for a permutation **[ap[0], ap[1], ..., ap[N-1]]** of **A** and an integer **x ≤ N** such that: * **s = 1 + (ap[0] AND 20) + (ap[1] AND 21) + ... + (ap[x-1] AND 2x-1) = 2x** * and **s** is greater than the greatest element **m** of **A** ### Formatted and commented ``` f = ( // f = recursive function taking: a, // - a = array m = Math.max(...a), // - m = greatest element in a s = 1 // - s = current power of 2, starting at 1 ) => // s > m // success condition (see above) which is | // OR'd with the result of this some(): a.some((n, i) => // for each element n at position i in a: n & s && // provided that the expected bit is set in n, f( // do a recursive call with: b = [...a], // b = copy of a m, // m unchanged s * 2, // s = next power of 2 b.splice(i, 1) // the current element removed from b ) // end of recursive call ) // end of some() ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 14 bytes ``` SöV≡ŀToṁ∂Pmo↔ḋ ``` [Try it online!](https://tio.run/##VU4xDsIwDNx5BSNIN9ROQpJfIIFYqu5IqKpExU4ZEIiVD/CJClYQD2k/EpwUBhTHse@cO6939SaMy0ndH5rt9NmGxatd9efbe7@sukfTnw7zsuqP1@5@CSHkVIxyAktWUENOr4ZJKCGdWBn8QjrDINKYCedhFYyGU2AvFCuCZygPpgzkLCgjWCdIZONN0vL7a2H/DAZXI4skVEVhJ6MeDiLGUg7jOnqTlvUd2IoaOZCyxQc "Husk – Try It Online") ## Explanation ``` SöV≡ŀToṁ∂Pmo↔ḋ Implicit input, say [4,5,2]. m ḋ Convert each to binary o↔ and reverse them: x = [[0,0,1],[1,0,1],[0,1]] P Take all permutations of x oṁ∂ and enumerate their anti-diagonals in y = [[0],[0,1],[1,0,0],[1,1],[1].. S T Transpose x: [[0,1,0],[0,0,1],[1,1]] ŀ Take the range up to its length: z = [1,2,3] Then z is as long as the longest list in x. öV Return the 1-based index of the first element of y ≡ that has the same length and same distribution of truthy values as z, i.e. is [1,1,1]. If one doesn't exist, return 0. ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~23~~ ~~22~~ 20 bytes *-1 byte thanks to Mr.Xcoder* True: 1, False: 0 ``` 2вí0ζœεvyƶNè})DgLQ}Z ``` [Try it online!](https://tio.run/##AS4A0f8wNWFiMWX//zLQssOtMM62xZPOtXZ5xrZOw6h9KURnTFF9Wv//WzEsIDcsIDFd "05AB1E – Try It Online") **Explanations:** ``` 2вí0ζœεvyƶNè})DgLQ}Z Full program (implicit input, e.g. [4, 6, 2]) 2в Convert each to binary ([1,0,0], [1,1,0], [1,0]) í Reverse each ([0,0,1], [0,1,1], [0,1]) 0ζ Zip with 0 as a filler ([0,0,0],[0,1,1],[1,1,0]) œ Get all sublists permutations ε } Apply on each permutation... vyƶNè} For each sublist... yƶ Multiply each element by its index Nè Get the element at position == sublist index ) Wrap the result in a list DgLQ 1 if equal to [1,2,...,length of item] Z Get max item of the list (1 if at least 1 permutations fill the conditions) -- implicit output ``` [Answer] ## [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 65 bytes ``` Max[Tr/@Permutations[n=PadLeft[#~IntegerDigits~2]]]==Tr[1^#&@@n]& ``` [Try it online!](https://tio.run/##bZBNi8MgEIbv/RUDhR4WoVWTmhwCHnpZ2IUcegtZkNakOcSCdWGhpH89O2qa9FBQ5@tx5tVeuYvuletOamyK8Vv9VUe7laW2/a/D9NXcKlOU6vylG1etH5/G6VbbQ9d27vZgdV0XxdFW9Ge9kdLUm7G0nXHyo4GthPsK4E4HEgwBFj1OgC/eHCQE0plBelpTjKVlx1zK0Kd4be@5nIDAZinGGVqWR4hxLOZIcgQY3SGZCTx2mBaZTw8EAvi0QQNMivavisQbOYvcNDzmCfAoI/MNcDJO8mOZD@ceSZRNE/83SDARBlJ0KRfDahj/AQ "Wolfram Language (Mathematica) – Try It Online") ### Explanation ``` #~IntegerDigits~2 ``` We start by converting all inputs to binary lists. ``` n=PadLeft[...] ``` Then we pad all those lists with zeros to the left to make the array rectangular. The result is stored in `n` for later. ``` Permutations[...] ``` Yay, brute force, let's get all possible permutations of the input. ``` Tr/@... ``` This gets the trace for each permutation, i.e. the sum of the diagonal elements in the permutation. In other words, we add up the MSB from the first number, the next-to-MSB from the second number and so on. If the permutation is valid, all of these will be **1** and there will be as many **1**s as the largest input number is wide. ``` Max[...] ``` We get the maximum trace, because the trace can never be *more* than that of a valid permutation. ``` ...==Tr[1^#&@@n] ``` The right-hand side is just a golfy version of `Length @ First @ n`, i.e. it gets the width of the rectangular array, and therefore the width of the largest input number. We want to make sure that the trace of some permutation is equal to this. [Answer] # PHP, ~~255~~ ~~243~~ 160 bytes -12 bytes, took out the sorting -83 bytes (!) thanks to Titus ``` <?function f($a,$v=NULL,$b=[]){($v=$v??(1<<log(max($a),2)+1)-1)||die("1");if($p=array_pop($a))while($p-=$i)($b[$i=1<<log($p,2)]|$v<$i)||f($a,$v-$i,[$i=>1]+$b);} ``` [Try it online!](https://tio.run/##bZFdT4MwFIbv/RVk9qLNSrKWIRBA/sDinVeEGJjDNZnQTEWN@NfFtwy2mpjwcT6e8563oPd6GJKsfmu2r6ptnJqSkpMuvbvfbDip0rxgXxQ56bKMiiQ5tE/0ufwAxbhkS8Fcwfr@Ue3oQixYrDCv0/J4LD8fdKsNxt736rBD2U2JYpRUOVHppEQ0RIqedAlafT8td4niBroVxZJULP4ermuai4LFV2PAHTnHHnc8O7bSNXd8i8TUdJ0raF/uuepLZALDN4aNuBNA1Ece4i0jg4GSHroRUA@EFCugYYDHCuUgNOVZ72xAWmaM/F9vwb/GbPP@eLwL5J0shUYIJrDUOJAmtZTWp0OItflqYGQwrhYIhReAG35abf78y@A2vw) Prints 1 for truthy, nothing for falsey. Original version ungolfed: ``` <?php unset($argv[0]); // remove filename from arguments $max = pow(2,floor(log(max($argv),2))+1)-1; // get target number (all bits set to 1) solve($argv,$max,[]); function solve($array,$value,$bits){ if(!$value){ // if we've reached our target number (actually subtracted it to zero) die("1"); // print truthy } if(count($array)){ // while there are arguments left to check $popped = array_pop($array); // get the largest argument while($popped > 0 && ($mybit = pow(2,floor(log($popped,2))))){ // while the argument hasn't reached zero, get the highest power of 2 possible $popped -= $mybit; // subtract power from argument if($value >= $mybit && !$bits[$i]){ // if this bit can be subtracted from our argument, and we haven't used this bit yet $copy = $bits; // create a copy to pass to the function $copy[$mybit] = 1; // mark the bit as used in the copy solve($array,$value-$mybit,$copy); // recurse } } } } ``` [Answer] # Lua 5.2, 85 bytes ``` m=math x=function(...)print(bit32.bor(...)==2^(m.floor(m.log(m.max(...),2))+1)-1)end ``` This sets x to be a function that accepts a variable number of inputs (expected to be 32 bit integers), and prints to stdout either "true" or "false". Usage: ``` x(13, 83, 86, 29, 8, 87, 26, 21) -- Prints "false" ``` [Answer] # PHP, 121 bytes ``` function f($a,$s=0){($v=array_pop($a))||(0|$g=log($s+1,2))-$g||die("1");for($b=.5;$v<=$b*=2;)$v&$b&&~$s&$b&&f($a,$s|$b);} ``` [Try it online](http://sandbox.onlinephpfunctions.com/code/89b93b9ff23bde8f958e75c9eb2bf2aa0d545cc0). **breakdown** ``` function f($a,$s=0) { ($v=array_pop($a)) # pop element from array || # if nothing could be popped (empty array) (0|$g=log($s+1,2))-$g # and $s+1 is a power of 2 ||die("1"); # then print "1" and exit for($b=.5;$v>=$b*=2;) # loop through the bits: $v&$b # if bit is set in $v &&~$s&$b # and not set in $s &&f($a,$s|$b); # then set bit in $s and recurse } ``` [Answer] # [J](http://jsoftware.com/), 49 bytes ``` g=.3 :'*+/*/"1+/"2((#y){.=i.{:$#:y)*"2#:(i.!#y)A.,y' ``` Do I need to count also the 'g=.'? I'm ready to add it. A long explicit verb this time. I tried a tacit one for the same algorithm, but it turned out to be even longer and uglier than this. Far away from Adám's solution. Explanation: (y is the right argument of the function) ``` ,y - adds a leading axis to the argument (if it's scalar becomes an array of length 1) .A - finds the permutations according to the left argument (i.!#y) - factorial of the length of the argument, for all permutations #: - convert each element to binary *"2 - multiply each cell by identity matrix ( ) - group =i.{:$#:y - identity matrix with size the length of the binary representation of the argument (#y){. - takes as many rows from the identity matrix as the size of the list (pad with 0 if neded) */"1+/"2 - sums the rows and multiplies the items to check if forms an identity matrix *+/ - add the results from all permutations and returns 1 in equal or greater then 1 ``` [Try it online!](https://tio.run/##ZVDLDsIgELz7FWNrQh9K3QUEmvTgtxjj4@K56cfXNabQKHCYnZ3JzvKc59ugDXrVtF3TFdR2BVdVOdaTHh566ndlP9ZNwWVfPfRW@LPej2rebK6X@ws3UALgBRqYFcyFhcsi@t5UuvQWyjGILE6iivAGziIYcFz6bAiRYSKYjqDgQUeCD8J8Jerwc1SyJpChTFqn8//ZVtGd7JX75hMsiD0iQHKwwJXbfhYgKz8UwF7GUBCPn98 "J – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 126 120 bytes Saved 6 bytes due to Mr. Xcoder ``` lambda x:g(x,max(map(len,map(bin,x)))-3) g=lambda x,n:n<0 or any(g(x[:i]+x[i+1:],n-1)for i in range(len(x))if x[i]&2**n) ``` [Try it online!](https://tio.run/##ZZHbboMwDIavx1NYvZgSmkpNAgug8SQUTekKLFJxEXBBn545UNpJk4jjw@ffVuju488N9Vznp/lq2/PFwpQ1bBKtnVhrO3atUPj77FBMnPOD5kGTb6jADD@PcOvB4p1RX5G5cj8Vbi@zUuBB8ppqDhxCb7GpvBwjGVcDQeW7CkPk81gN49e3HaoBciiCt0KWwlsBanG0AP10Nj8SEG8AkY9vDanwOksqVuRK6vnwVCrAkFBMcUK3ShdGaaqlBGqqK3kkMDFkjpQ2iU@v2Gq32V7zzx7m/xLPFeNl/UdZr7MT30zzSN8PUz7cBKJ1VRn5lyBAmWWWJFdqQ1AZBF3vcGSh/0W1eD0kF0PV5bsT7vj8Cw "Python 3 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 17 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` BUz0Œ!ŒD€Ẏ ṀBo1eÇ ``` A monadic link taking a list of numbers and returning `1` (truthy) or `0` (falsey). **[Try it online!](https://tio.run/##ASkA1v9qZWxsef//QlV6MMWSIcWSROKCrOG6jgrhuYBCbzFlw4f///80LDUsMg "Jelly – Try It Online")** This will time out on TIO for the longest of each of the test cases. ### How? ``` BUz0Œ!ŒD€Ẏ - Link 1, possibilities (plus some shorter ones & duplicates): list of numbers e.g. [4, 5, 2] B - to binary list (vectorises) [[1,0,0],[1,0,1],[1,0]] U - upend [[0,0,1],[1,0,1],[0,1]] 0 - literal zero 0 z - transpose with filler [[0,1,0],[0,0,1],[1,1,0]] Œ! - all permutations [[[0,1,0],[0,0,1],[1,1,0]],[[0,1,0],[1,1,0],[0,0,1]],[[0,0,1],[0,1,0],[1,1,0]],[[0,0,1],[1,1,0],[0,1,0]],[[1,1,0],[0,1,0],[0,0,1]],[[1,1,0],[0,0,1],[0,1,0]]] ŒD€ - diagonals of €ach [[[0,0,0],[1,1],[0],[1],[0,1]],[[0,1,1],[1,0],[0],[0],[1,0]],[[0,1,0],[0,0],[1],[1],[0,1]],[[0,1,0],[0,0],[1],[0],[1,1]],[[1,1,1],[1,0],[0],[0],[0,0]],[[1,0,0],[1,1],[0],[0],[0,1]]] Ẏ - tighten [[0,0,0],[1,1],[0],[1],[0,1],[0,1,1],[1,0],[0],[0],[1,0],[0,1,0],[0,0],[1],[1],[0,1],[0,1,0],[0,0],[1],[0],[1,1],[1,1,1],[1,0],[0],[0],[0,0],[1,0,0],[1,1],[0],[0],[0,1]] ṀBo1eÇ - Main link: list of numbers e.g. [4, 5, 2] Ṁ - maximum 5 B - to binary list [1,0,1] 1 - literal one 1 o - or (vectorises) [1,1,1] Ç - last link as a monad [[0,0,0],[1,1],[0],[1],[0,1],[0,1,1],[1,0],[0],[0],[1,0],[0,1,0],[0,0],[1],[1],[0,1],[0,1,0],[0,0],[1],[0],[1,1],[1,1,1],[1,0],[0],[0],[0,0],[1,0,0],[1,1],[0],[0],[0,1]] e - exists in? 1 --------------------------------------------------------------------------------------------------------------^ ``` [Answer] # [R](https://www.r-project.org/), ~~247 bytes~~ 221 bytes ``` function(i){a=do.call(rbind,Map(`==`,Map(intToBits,i),1));n=max(unlist(apply(a,1,which)));any(unlist(g(a[,1:n,drop=F],n)))} g=function(a,p){if(p==1)return(any(a[,1]));Map(function(x){g(a[x,,drop=F],p-1)},which(a[,p])*-1)} ``` [Try it online!](https://tio.run/##bZDLboMwEEX3@QqUlaeaVrEJBVp500V23WVXRYpLQmKJGsuAmijKt9NxeKVSJMDzuHPnGNfmss0bk9W6NEzDRcld@ZKpomDuW5sdfirLtlJub4E29br80HWFGpADvBv5o06sMYWuaqasLc5MIcffo86OQH1lzkP3wNQX8jeDO1daudqgIcF1dpDjdoUWLjpnVkoObl83jmpk4Oc2ZOYJRvEJLt7xhKOffeZw7Vb7EbuBJ19prSNsNl@7pj6e5zDLWcaIvTsxEH0YYhDehVO2xCCaZDTRP0OBmtPbFyNBCafJV69MMYjJMKI8oVOkvUqE1E1JGpJC8AVJk5g@CyrHiS@TcNbzr1RR7Qf@gUZMYH7ZP8z4EePdLaLbLUdJ2MEl3oRwaL1nET6dbJbdbfjS/ziSiPi2lVPIwxig/QM "R – Try It Online") Ungolfed version ``` f=function(i){ #anonymous function when golfed a=do.call(rbind,Map(`==`,Map(intToBits,i),1)) #convert integers to binary, then logical #bind results together in matrix n=max(unlist(apply(a,1,which))) #determine max number of bits any(unlist(g(a[,1:n,drop=F],n))) #apply recursive function } g=function(a,p){ if(p==1)return(any(a[,1])) #check if first bit is available still Map(function(x){g(a[x,,drop=F],p-1)},which(a[,p])*-1) #strip row used for current bit #and apply the function recursively } ``` I realized the no-row check was unnecessary with the `drop=F` arguments. Also removed some pesky whitespace. [Answer] # PHP, 152 bytes ``` <?function b($a,$b,$s){$a[$s]=0;$r=$b-1;foreach($a as$i=>$v)if($v&1<<$b)$r=max(b($a,$b+1,$i),$r);return$r;}$g=$argv;$g[0]=0;echo!(max($g)>>b($g,0,0)+1); ``` Prints nothing for false, 1 for true. Ungolfed: ``` <? // Search an array for a value having a bit set at the given bit index. // For each match, search for a next higher bit index excluding the current match. // This way it "climbs up" bit by a bit, finally returning the highest bit index reached. function bitSearch($valArr, $bitInd, $skipInd) { unset($valArr[$skipInd]); $result = $bitInd - 1; foreach ($valArr as $ind => $v) { if ($v & (1 << $bitInd)) { $result = max(bitSearch($valArr, $bitInd + 1, $ind), $result); } } return $result; } $argv[0] = 0; $r = bitSearch($argv, 0, 0); // Check if the highest bit index reached was highest in the largest value given. if (max($argv) >> ($r + 1)) { echo("False\n"); } else { echo("True\n"); } ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 17 bytes ``` BUz0×J$€ŒpṢ=JPƲ€Ẹ ``` **[Test suite.](https://tio.run/##y0rNyan8/98ptMrg8HQvlUdNa45OKni4c5GtV8CxTUDew107/h9uBzLc//@PNozViTbUUTACUsY6CsZQCsIy0VEwhUgBVUARiAMURGCgAEiFEUQhUIsZXIs5unqoSaZgGwxjAQ "Jelly – Try It Online")** [Answer] # C , 79 bytes ``` b,i;main(a){for(;~scanf("%d",&a);i++)b|=a;puts("false\0true"+(b==(1<<i)-1)*6);} ``` ]
[Question] [ The alphanumeric characters have ASCII-values: ``` 0-9 -> 48-57 A-Z -> 65-90 a-z -> 97-122 ``` Your challenge is to take an integer as input, and output how many characters can be made using consecutive digits of that number. The character codes may be overlapping. `666` should result in `2`, since you have `66` twice. **Test cases:** ``` Input: 5698 Possible characters: '8' (56), 'E' (69), 'b' (98) Output: 3 Input: 564693 Possible characters: '8' (56), 'E' (69) Output: 2 Input: 530923864209124521 Possible characters: '5' (53), 'V' (86), '4' (52) Output: 3 Input: 1111111 Possible characters: 'ooooo' (5*111) Output: 5 Input: 5115643141276343 Possible characters: '3' (51), '8' (56), 'L' (76), 's' (115) Output: 4 Input: 56789 Possible characters: '8' (56), 'C' (67), 'N' (78), 'Y' (89) Output: 4 Input: 94 Possible characters: '' Output: 0 Input: 1 Output: 0 ``` Input and output formats are optional (yes, you may take the integer as a string). [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~8~~ 7 bytes ``` žKÇIŒÃg ``` [Try it online!](https://tio.run/nexus/05ab1e#@390n/fhds@jkw43p///b2poaGpmYmxoYmhkbmZsYgwA "05AB1E – TIO Nexus") **Explanation** ``` žK # push [a-zA-Z0-9] Ç # convert to list of ascii codes IŒ # push all substrings of input à # keep only the subtrings which exist in the list of acsii codes g # push length of resulting list ``` [Answer] # [MATL](https://github.com/lmendo/MATL), ~~17~~ 13 bytes ``` 8Y2"G@oVXf]vn ``` [Try it online!](https://tio.run/nexus/matl#@28RaaTk7pAfFpEWW5b3/7@6qaGhqZmJsaGJoZG5mbGJsToAA "MATL – TIO Nexus") Or [verify all test cases](https://tio.run/nexus/matl#S4jwqvhvEWmk5OWQHxaRFluW998l5L@6qZmlhToXkDIxszQGMYwNLI2MLcxMjAwsDY1MTI0MgYKGEACSNjQEKjU2NDE0MjczNgHrMDO3sATSliYgleoA). ### Explanation ``` 8Y2 % Predefined literal: string with all letters, uppercase and lowercase, % and digits " % For each character in that string G % Push input, for example the string '5115643141276343' @ % Push current character, such as 'A' o % Convert to its ASCII code, such as 65 V % String representation, such as '65' Xf % Find string '65' within string '5115643141276343'. This gives a vector % (possibly empty) with indices of occurrences ] % End v % Concatenate all stack contents vertically n % Number of entries. Implicitly display ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 22 bytes ``` ∧Ạụ:Ạ:Ịcạ:?{tT&h∋~sT}ᶜ ``` [Try it online!](https://tio.run/nexus/brachylog2#@/@oY/nDXQse7l5qBaSsHu7uSn64a6GVfXVJiFrGo47uuuKQ2ofb5vz/b2poaGpmYmxoYmhkbmZsYvw/CgA "Brachylog – TIO Nexus") ### Explanation ``` c Concatenate together: ∧Ạụ: "ABCDEFGHIJKLMNOPQRSTUVWXYZ" Ạ: "abcdefghijklmnopqrstuvwxyz" Ị "0123456789" ạ Get the list of ASCII codes of that string :?{ }ᶜ Count the number of results, for input [list of codes, Input], of: tT Call the Input T &h∋ Take one ASCII code ~sT It is a substring of T ``` [Answer] # Java 8, ~~204~~ ~~197~~ ~~195~~ ~~186~~ 174 bytes ``` n->{int r=0,i=0,e=n.length()-1,t;for(;i<e;r+=t>47&t<57|t>64&t<91|t>96&t<100|(t=new Short(n.substring(i,i++>e-2?i:i+2)))>99&t<123?1:0)t=new Byte(n.substring(i,i+2));return r;} ``` -9 bytes thanks to *@ceilingcat*. [Try it online.](https://tio.run/##jVBBb8IgGL37K8gOS0ltUyi2IrYmu8@Lx2UHrKi4Sg396mK0v72j6m3JOhLI4@O9j/e@gzzL4LD56opS1jV6l9pcRwhpA8puZaHQsr/eC6jwVmC12SGDhSu2I3fUIEEXaIkMyjoT5NeeaLNorN1WmQlLZXaw93BAxiC2lfWEnith/Qxylr7CfJLeIE@YQ5w4xBOHSBTdPMiM@karfWXBM2HdrOv7554ea9/PVUAXeqZ9ijHOOe9FNF6QWYQfurcLqF8yRxZWQWMNsqLtRB/g1KxLF@CZ41zpDTq6ITyjfnwiiR8TWF1qUMewaiA8uScojetfeC@ThE9f8H0if5FYwuNhWhxxGk8TRiNOKJtQMighjzXcmhBnIiaM0DSJ2T@8JOmUD7I4G3b4ZLSjtvsB) **Explanation:** ``` n->{ // Method with String parameter and integer return-type int r=0, // Result, starting at 0 i=0, // Index e=n.length()-1, // Length of String -1 t; // Temp integer for(;i<e // Loop over the String using the index ; // After every iteration: r+= // Increase the result-sum by: t>47&t<57|t>64&t<91|t>96&t<100 // If two adjacent digits are a digit or letter | // or (t=new Short(n.substring(i,i++>e-2?i:i+2)))>99&t<123? // if three adjacent digits are a letter: 1 // Increase the sum by 1 : // Else: 0) // Keep the sum the same by adding 0 t=new Byte(n.substring(i,i+2)); // Set `t` to the substring of [i, i+2) converted to integer return r;} // Return the result-sum ``` [Answer] ## JavaScript (ES6), ~~71~~ 70 bytes ``` f=([a,...b])=>a?(a&(a+=b[0])+b[1]<123|a>47&a<58|a>64&a<91|a>96)+f(b):0 ``` ### Test cases ``` f=([a,...b])=>a?(a&(a+=b[0])+b[1]<123|a>47&a<58|a>64&a<91|a>96)+f(b):0 console.log(f("5698")) // 3 console.log(f("564693")) // 2 console.log(f("530923864209124521")) // 3 console.log(f("1111111")) // 5 console.log(f("5115643141276343")) // 4 console.log(f("56789")) // 4 console.log(f("94")) // 0 console.log(f("1")) // 0 ``` [Answer] # [Perl 5](https://www.perl.org/), 47 bytes 46 bytes of code + `-p` flag. ``` $"="|";$_=()=/(?=@{[48..57,65..90,97..122]})/g ``` [Try it online!](https://tio.run/nexus/perl5#JcrLCoJAFADQ/XzFbXShYKN33hcZ6j8qxMjCkBKzRVTfPgmd9UlWYzcNsB5jygP/8DptQpaHMtuE7XunvRDGFdYIQVVBTgiU8vDNy0usIW1ABOD7G4cErs/HDOf7BFPXntpjP/TzKxpLnhmrLSlmVEVSeatlRSi1kcjwjxnEJSnUKJ1VernWeWKkGf4A "Perl 5 – TIO Nexus") I couldn't find any shorter way to write that `48..57,65..90,97..122`: `map{ord}0..9,a..z,A..Z` (getting the ascii value of the characters) is one byte longer. And doing `for$c(0..122){$\+=chr($c)=~/\pl|\d/ for/(?=$c)/g}}{` (looking for all numbers, but keeping only those whose numbers corresponds to the ascii value of letters (`\pl`) or digits (`\d`)) will be 5 bytes longer (note that `\pl|\d` can't be replaced by `\w` as the latter also includes underscores)). --- Previous approach (49 bytes): ``` for$@(48..57,65..90,97..122){$\+=()=/(?=$@)/g}}{ ``` [Answer] # PHP, 68 Bytes ``` for(;a&($a=$argn)[$i];)$d+=ctype_alnum(chr($a[$i].$a[++$i]));echo$d; ``` [Online Version](http://sandbox.onlinephpfunctions.com/code/19f8f6270e4f8e1dd7f0db0ffc58f9e559b8a19c) [Answer] # JavaScript (ES), ~~165~~ ~~161~~ ~~156~~ ~~154~~ 153 bytes Yeah, RegEx definitely wasn't the right tool for the job here! ``` n=>[/\d{2}/g,/\d{3}/g].map(e=>eval("while(x=e.exec(n)){a.push(m=x[0]);e.lastIndex-=m.length-1}"),a=[])|a.filter(x=>x>47&x<58|x>64&x<91|x>96&x<123).length ``` --- ## Try It ``` f= n=>[/\d{2}/g,/\d{3}/g].map(e=>eval("while(x=e.exec(n)){a.push(m=x[0]);e.lastIndex-=m.length-1}"),a=[])|a.filter(x=>x>47&x<58|x>64&x<91|x>96&x<123).length console.log(f(5698))//3 console.log(f(564693))//2 console.log(f(530923864209124521))//3 console.log(f(1111111))//5 console.log(f(5115643141276343))//4 console.log(f(56789))//4 console.log(f(94))//0 console.log(f(1))//0 ``` [Answer] # [Retina](https://github.com/m-ender/retina), 52 bytes ``` &`1[01]\d|12[012]|4[89]|5[0-7]|6[5-9]|[78]\d|9[0789] ``` [Try it online!](https://tio.run/nexus/retina#JYvLDcMwDEPv2iNFLwFM/WxNkCFUAzlkDO/uqihPJN7j8b7u/bqRDfPzLHAVnktzxFyW7exzedpZK/v4KZGtF9zbPAaZq4eQSQuW4cotwGoMwj9kQEkCBXcXLdfrT6GELw "Retina – TIO Nexus") (includes test suite) [Answer] # Pyth, ~~19~~ ~~17~~ 14 bytes ``` l@jGUTmr0Csd.: ``` takes a string. *-3 Bytes thanks to @LeakyNun* [Try it!](https://pyth.herokuapp.com/?code=l%40jGUTmr0Csd.%3A&input=%225698%22&test_suite=1&test_suite_input=%225698%22%0A%22564693%22%0A%22530923864209124521%22%0A%221111111%22%0A%225115643141276343%22%0A%2256789%22%0A%2294%22%0A%221%22&debug=0) ### Explanation ``` l@jGUTmr0Csd.: UT # the list of digits [0,1,2,...,9] jG # join that on the lowercase alphabet (repetition doesn't matter) Q # implicit input .: # all substrings of the input m # for each of those substrings sd # Convert the string to a base 10 integer C # convert that integer to the character with that number r0 # make that character lowercase l@ # length of the intersection of those two list of chars we generated ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~74~~ ~~64~~ 62 bytes ``` f=lambda n:n and chr(n%10**(3-(n%1000>122))).isalnum()+f(n/10) ``` [Try it online!](https://tio.run/nexus/python2#JY3BDsIgEETP@hV7IYVKlV0ohSb2X1DS2KRdTdXvr6hzmJlkXjLbeJ7TcskJuGdInOF6WyULNHUtbfNrxgxIpJQ6Ts8083uR6jBKPqFR23hfgWFiaH0Murjz0Za0JpIN3pGJSK4l1IB/lRGxcBYdUuet@@K@C1FDdIXq97vHOvELKoEhQzOAyBUIkKyhvCq1fQA "Python 2 – TIO Nexus") [Answer] # Haskell, ~~161~~ ~~157~~ ~~138~~ ~~129~~ 126 bytes ``` import Data.List f x=sum[1|y<-nub$concat$words.concat<$>mapM(\c->[[c],c:" "])x,any(elem$read y)[[48..57],[65..90],[97..122]]] ``` I wonder if there is a better way to remove dupes of the list than importing Data.List for nub? [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes ``` ØBODf@ẆL ``` Input is a digit array. [Try it online!](https://tio.run/nexus/jelly#@394hpO/S5rDw11tPv///zfVMdYx0LHUMQLSFjpmOiZAFohvCKRNdEyBpCEA "Jelly – TIO Nexus") ### How it works ``` ØBODf@ẆL Main link. Argument: A (digit array) ØB Base 62; yield all alphanumeric ASCII characters. O Ordinal; get their code points. D Decimal; convert the code points into digit arrays. Ẇ Window; yield all contiguous subarrays of A. f@ Filter swapped; keep all elements of the result to the right that appear in the result to the left. L Length; count the matches. ``` [Answer] # Ruby, 50 bytes ``` p (0..~/$/).any?{|n|$_[n,2].to_i.chr=~/\p{Alnum}/} ``` Reads from standard input; requires the Ruby interpreter be invoked with the `-n` option (implicit `while gets` loop). Could be reduced to 43 bytes if it were allowed to match underscores. ``` p (0..~/$/).any?{|n|$_[n,2].to_i.chr=~/\w/} ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 24 bytes ``` ;è"(?={9ò ¬+B+C ¬mc q|}) ``` [Try it online!](https://tio.run/nexus/japt#@299eIWShr1tteXhTQqH1mg7aTsDqdxkhcKaWs3//5VMjQ0sjYwtzEyMDCwNjUxMjQyVAA "Japt – TIO Nexus") Alternate 27-byte version: ``` è"(?={#~o f_d f"%d|%l"Ãq|}) ``` [Try it online!](https://tio.run/nexus/japt#@394hZKGvW21cl2@Qlp8ikKakmpKjWqO0uHmwppazf//lUyNDSyNjC3MTIwMLA2NTEyNDJUA "Japt – TIO Nexus") ]
[Question] [ Write a program or function that takes in two positive integers, a width and a height, and draws an ASCII art [houndstooth](https://en.wikipedia.org/wiki/Houndstooth) grid pattern with those dimensions using this 25×26 text grid as the base cell: ``` .......#.....#####....... .......##.....#####...... .......###.....#####..... .......####.....####..... .......#####.....###..... .......######.....##..... .......#######.....#..... .......########.......... ####################..... .####################.... ..####################... ...####################.. ....####################. .....#################### #.....##############.#### ##.....#############..### ###....#############...## ####...#############....# #####..#############..... .#####.#############..... ..##################..... ........#####............ .........#####........... ..........#####.......... ...........#####......... ............#####........ ``` So if the input was `2,1` the output would be: ``` .......#.....#####..............#.....#####....... .......##.....#####.............##.....#####...... .......###.....#####............###.....#####..... .......####.....####............####.....####..... .......#####.....###............#####.....###..... .......######.....##............######.....##..... .......#######.....#............#######.....#..... .......########.................########.......... ####################.....####################..... .####################.....####################.... ..####################.....####################... ...####################.....####################.. ....####################.....####################. .....####################.....#################### #.....##############.#####.....##############.#### ##.....#############..#####.....#############..### ###....#############...#####....#############...## ####...#############....#####...#############....# #####..#############.....#####..#############..... .#####.#############......#####.#############..... ..##################.......##################..... ........#####....................#####............ .........#####....................#####........... ..........#####....................#####.......... ...........#####....................#####......... ............#####....................#####........ ``` And if the input was `5,4` the output would be: ``` .......#.....#####..............#.....#####..............#.....#####..............#.....#####..............#.....#####....... .......##.....#####.............##.....#####.............##.....#####.............##.....#####.............##.....#####...... .......###.....#####............###.....#####............###.....#####............###.....#####............###.....#####..... .......####.....####............####.....####............####.....####............####.....####............####.....####..... .......#####.....###............#####.....###............#####.....###............#####.....###............#####.....###..... .......######.....##............######.....##............######.....##............######.....##............######.....##..... .......#######.....#............#######.....#............#######.....#............#######.....#............#######.....#..... .......########.................########.................########.................########.................########.......... ####################.....####################.....####################.....####################.....####################..... .####################.....####################.....####################.....####################.....####################.... ..####################.....####################.....####################.....####################.....####################... ...####################.....####################.....####################.....####################.....####################.. ....####################.....####################.....####################.....####################.....####################. .....####################.....####################.....####################.....####################.....#################### #.....##############.#####.....##############.#####.....##############.#####.....##############.#####.....##############.#### ##.....#############..#####.....#############..#####.....#############..#####.....#############..#####.....#############..### ###....#############...#####....#############...#####....#############...#####....#############...#####....#############...## ####...#############....#####...#############....#####...#############....#####...#############....#####...#############....# #####..#############.....#####..#############.....#####..#############.....#####..#############.....#####..#############..... .#####.#############......#####.#############......#####.#############......#####.#############......#####.#############..... ..##################.......##################.......##################.......##################.......##################..... ........#####....................#####....................#####....................#####....................#####............ .........#####....................#####....................#####....................#####....................#####........... ..........#####....................#####....................#####....................#####....................#####.......... ...........#####....................#####....................#####....................#####....................#####......... ............#####....................#####....................#####....................#####....................#####........ .......#.....#####..............#.....#####..............#.....#####..............#.....#####..............#.....#####....... .......##.....#####.............##.....#####.............##.....#####.............##.....#####.............##.....#####...... .......###.....#####............###.....#####............###.....#####............###.....#####............###.....#####..... .......####.....####............####.....####............####.....####............####.....####............####.....####..... .......#####.....###............#####.....###............#####.....###............#####.....###............#####.....###..... .......######.....##............######.....##............######.....##............######.....##............######.....##..... .......#######.....#............#######.....#............#######.....#............#######.....#............#######.....#..... .......########.................########.................########.................########.................########.......... ####################.....####################.....####################.....####################.....####################..... .####################.....####################.....####################.....####################.....####################.... ..####################.....####################.....####################.....####################.....####################... ...####################.....####################.....####################.....####################.....####################.. ....####################.....####################.....####################.....####################.....####################. .....####################.....####################.....####################.....####################.....#################### #.....##############.#####.....##############.#####.....##############.#####.....##############.#####.....##############.#### ##.....#############..#####.....#############..#####.....#############..#####.....#############..#####.....#############..### ###....#############...#####....#############...#####....#############...#####....#############...#####....#############...## ####...#############....#####...#############....#####...#############....#####...#############....#####...#############....# #####..#############.....#####..#############.....#####..#############.....#####..#############.....#####..#############..... .#####.#############......#####.#############......#####.#############......#####.#############......#####.#############..... ..##################.......##################.......##################.......##################.......##################..... ........#####....................#####....................#####....................#####....................#####............ .........#####....................#####....................#####....................#####....................#####........... ..........#####....................#####....................#####....................#####....................#####.......... ...........#####....................#####....................#####....................#####....................#####......... ............#####....................#####....................#####....................#####....................#####........ .......#.....#####..............#.....#####..............#.....#####..............#.....#####..............#.....#####....... .......##.....#####.............##.....#####.............##.....#####.............##.....#####.............##.....#####...... .......###.....#####............###.....#####............###.....#####............###.....#####............###.....#####..... .......####.....####............####.....####............####.....####............####.....####............####.....####..... .......#####.....###............#####.....###............#####.....###............#####.....###............#####.....###..... .......######.....##............######.....##............######.....##............######.....##............######.....##..... .......#######.....#............#######.....#............#######.....#............#######.....#............#######.....#..... .......########.................########.................########.................########.................########.......... ####################.....####################.....####################.....####################.....####################..... .####################.....####################.....####################.....####################.....####################.... ..####################.....####################.....####################.....####################.....####################... ...####################.....####################.....####################.....####################.....####################.. ....####################.....####################.....####################.....####################.....####################. .....####################.....####################.....####################.....####################.....#################### #.....##############.#####.....##############.#####.....##############.#####.....##############.#####.....##############.#### ##.....#############..#####.....#############..#####.....#############..#####.....#############..#####.....#############..### ###....#############...#####....#############...#####....#############...#####....#############...#####....#############...## ####...#############....#####...#############....#####...#############....#####...#############....#####...#############....# #####..#############.....#####..#############.....#####..#############.....#####..#############.....#####..#############..... .#####.#############......#####.#############......#####.#############......#####.#############......#####.#############..... ..##################.......##################.......##################.......##################.......##################..... ........#####....................#####....................#####....................#####....................#####............ .........#####....................#####....................#####....................#####....................#####........... ..........#####....................#####....................#####....................#####....................#####.......... ...........#####....................#####....................#####....................#####....................#####......... ............#####....................#####....................#####....................#####....................#####........ .......#.....#####..............#.....#####..............#.....#####..............#.....#####..............#.....#####....... .......##.....#####.............##.....#####.............##.....#####.............##.....#####.............##.....#####...... .......###.....#####............###.....#####............###.....#####............###.....#####............###.....#####..... .......####.....####............####.....####............####.....####............####.....####............####.....####..... .......#####.....###............#####.....###............#####.....###............#####.....###............#####.....###..... .......######.....##............######.....##............######.....##............######.....##............######.....##..... .......#######.....#............#######.....#............#######.....#............#######.....#............#######.....#..... .......########.................########.................########.................########.................########.......... ####################.....####################.....####################.....####################.....####################..... .####################.....####################.....####################.....####################.....####################.... ..####################.....####################.....####################.....####################.....####################... ...####################.....####################.....####################.....####################.....####################.. ....####################.....####################.....####################.....####################.....####################. .....####################.....####################.....####################.....####################.....#################### #.....##############.#####.....##############.#####.....##############.#####.....##############.#####.....##############.#### ##.....#############..#####.....#############..#####.....#############..#####.....#############..#####.....#############..### ###....#############...#####....#############...#####....#############...#####....#############...#####....#############...## ####...#############....#####...#############....#####...#############....#####...#############....#####...#############....# #####..#############.....#####..#############.....#####..#############.....#####..#############.....#####..#############..... .#####.#############......#####.#############......#####.#############......#####.#############......#####.#############..... ..##################.......##################.......##################.......##################.......##################..... ........#####....................#####....................#####....................#####....................#####............ .........#####....................#####....................#####....................#####....................#####........... ..........#####....................#####....................#####....................#####....................#####.......... ...........#####....................#####....................#####....................#####....................#####......... ............#####....................#####....................#####....................#####....................#####........ ``` * The width argument must come first. Any reasonable input format (e.g. `w,h`, `w h`, `(w, h)`) is fine. * Print or return the result with an optional trailing newline. * You may use any two distinct [printable ASCII](https://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters) characters in place of `.` and `#`. * You can translate the base cell vertically or horizontally, as if it had [periodic boundary conditions](https://en.wikipedia.org/wiki/Periodic_boundary_conditions). Thus the top left corner of the output will not necessarily be a 7×8 rectangle of `.`'s. (**New rule!**) **The shortest code in bytes wins.** As a bonus, generate an image instead where each `.` is a pixel of one color and each `#` is a pixel of another color. [Answer] # Pyth, ~~61~~ ~~60~~ ~~55~~ 49 bytes ``` j*vwmjk*Qd++Rm012Jmms}k++Rhd5U-d4T=T13+Lm1T_mP_dJ ``` Try it online: [Demonstration](http://pyth.herokuapp.com/?code=j*vwmjk*Qd%2B%2BRm012Jmms%7Dk%2B%2BRhd5U-d4T%3DT13%2BLm1T_mP_dJ&input=5%0A4&debug=0) edit 1: Combine the two statements generating the band and the triangle (see below) edit 2: Didn't saw that we can use any symbols. Saved 5 bytes edit edit 3: @Calvin'sHobbies allowed translating the base image. Since my approach was based on this idea, this helped quite a lot. -6 bytes And for the **Cookie bonus**: ``` .w*vw*RQ++Rm012Jmm*K255}k++Rhd5U-d4T=T13+LmKT_mP_dJ ``` This is only 2 bytes longer (51 bytes) and generates the file `o.png`. For the input `5\n4` it generates the following picture: [![Houndstooth Pattern](https://i.stack.imgur.com/Uq9Jl.png)](https://i.stack.imgur.com/Uq9Jl.png) ## Explanation: The Houndstooth Pattern looks really quite irregular. But if we bring the left 7 columns to the right and the top 5 rows to the botton we get a much nicer pattern: ``` .#####................... ..#####.................. ...#####................. ....#####................ .....#####............... #.....#####.............. ##.....#####............. ###.....#####............ ####.....####............ #####.....###............ ######.....##............ #######.....#............ ########................. #############.....####### ##############.....###### ###############.....##### ################.....#### #################.....### ##################.....## #############.#####.....# #############..#####..... #############...#####.... #############....#####... #############.....#####.. #############......#####. #############.......##### ``` First I produce the top-left 13x13 block: ``` .#####....... ..#####...... ...#####..... ....#####.... .....#####... #.....#####.. ##.....#####. ###.....##### ####.....#### #####.....### ######.....## #######.....# ########..... ``` There are 2 simple inequalities, that describe the two `#`-areas. The band can be described by `y + 1 <= x <= y + 5` and the triangle can be described by `x <= y - 5`. I`ve combined these two conditions: ``` Jmms}k++Rhd5U-d4T=T13 =T13 T = 13 m T map each d of [0, 1, ..., 12] to: the list produced by m T map each k of [0, 1, ..., 12] to: +Rhd5 the list [d+1, d+2, ..., d+5] + extended by U-d4 the list [0, 1, ..., d - 5] }k test if k is in the list s and convert the boolean result to 1 or 0 J assign this 13x13 block to J ``` Then `+Rm012` adds 12 zeros at the end of each row , to get the upper 25x13 block. The lower 25x13 block is now really simple: ``` +Lm1T_mP_dJ m J map each row d of J to: P_d reverse the row and pop the last element _ reverse the order the rows +Lm1T add T ones at the beginning of each row. ``` All now left is to repeating the pattern and print it ``` j*vwmjk*Qd+upperlower implicit: Q = first input number +upperlower combine the two blocks to a 25x26 block m map each row d to: *Qd repeat d Q times jk and join to a string *vw read another number from input and repeat j join by newlines and print ``` The difference to the **Cookie bonus** code: * `255` instead of `1` * instead of `mjk*Qd` I use `*RQ`, since I don't want a string * `.w` saves this 2D-array to file (converts it to png implicitly) [Answer] # CJam, ~~106~~ ~~73~~ 71 bytes ``` 0000000: 71 7e 22 04 94 51 af 40 6e 73 b2 68 3a e1 7e 13 f2 a1 q~"[[email protected]](/cdn-cgi/l/email-protection):.~... 0000012: 3e 1d de f5 64 9c 6b 0f 27 4c 36 d7 81 3d 30 35 56 f8 >...d.k.'L6..=05V. 0000024: cd e8 cd 7c dc 90 31 59 40 8b 8c 22 32 35 36 62 32 32 ...|..1Y@.."256b22 0000036: 62 41 73 33 39 2a 2e 2a 73 32 35 2f 2a 66 2a 4e 2a bAs39*.*s25/*f*N* ``` Prints `1` and `0` instead of `.` and `#`. Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=q~%22%04%C2%94Q%C2%AF%40ns%C2%B2h%3A%C3%A1~%13%C3%B2%C2%A1%3E%1D%C3%9E%C3%B5d%C2%9Ck%0F'L6%C3%97%C2%81%3D05V%C3%B8%C3%8D%C3%A8%C3%8D%7C%C3%9C%C2%901Y%40%C2%8B%C2%8C%22256b22bAs39*.*s25%2F*f*N*&input=5%204). ### How it works ``` q~ e# Read and evaluate all input. This pushes W and H. "…" e# Push an encoding of run lengths of the characters in the output. 256b22b e# Convert from base 256 to base 22. As39* e# Push "10" and repeat it 39 times. .* e# Vectorized character repetition; multiply each base 22 digit (run e# length) by the corresponding character of "10…10". s25/ e# Flatten and split into chunks of length 25. * e# Repeat the resulting array of rows H times. f* e# Repeat each row W times. N* e# Join the rows, separating by linefeeds. ``` ### Cookie bonus ``` 0000000: 27 50 6f 31 70 71 7e 5d 5f 5b 32 35 5f 29 5d 2e 2a 5c 'Po1pq~]_[25_)].*\ 0000012: 7e 22 04 94 51 af 40 6e 73 b2 68 3a e1 7e 13 f2 a1 3e ~"[[email protected]](/cdn-cgi/l/email-protection):.~...> 0000024: 1d de f5 64 9c 6b 0f 27 4c 36 d7 81 3d 30 35 56 f8 cd ...d.k.'L6..=05V.. 0000036: e8 cd 7c dc 90 31 59 40 8b 8c 22 32 35 36 62 32 32 62 ..|..1Y@.."256b22b 0000048: 41 73 33 39 2a 2e 2a 73 32 35 2f 2a 66 2a 73 2b 4e 2a As39*.*s25/*f*s+N* ``` prints a Portable BitMap instead of ASCII art. Below is the output for input `24 13`, converted to PNG: ![output](https://i.stack.imgur.com/trpIM.png) [Answer] # [Befunge-93](http://www.quirkster.com/iano/js/befunge.html), ~~2120~~ 1967 bytes Here's some high quality befunge, with exception-handling for debugging! ``` &&00p10pv v < >94+2*20p v >00g| > v @ >10g>0020gv-1:< >:0`| , v $< + >v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v v_$1-:#^_$20g1-20p55^ >|>|>|>|>|>|>|>|>|>|>|>|>|>|>|>|>|>|>|>|>|>|>|>|>|>|>|>"!DAB"....@ ,: >^".......#.....#####......." < ^".......##.....#####......" < ^".......###.....#####....." < ^".......####.....####....." < ^".......#####.....###....." < ^".......######.....##....." < ^".......#######.....#....." < ^".......########.........." < ^"####################....." < ^".####################...." < ^"..####################..." < ^"...####################.." < ^"....####################." < ^".....####################" < ^"#.....##############.####" < ^"##.....#############..###" < ^"###....#############...##" < ^"####...#############....#" < ^"#####..#############....." < ^".#####.#############....." < ^"..##################....." < ^"........#####............" < ^".........#####..........." < ^"..........#####.........." < ^"...........#####........." < ^"............#####........" < ^ p00-1g00< ``` (Obviously, this is still very golfable. I just wanted to get an answer up here for now) So, this is made up of different parts. ``` &&00p10p ``` This is just the initializer, it takes in the values and stores them ``` >94+2*20p >00g| > @ ``` This section resets the row count, so we can print out another (width) pictures side by side. `94+2*` is calculating 26, the number of rows. Also, if the height is zero, the program will terminate. ``` >10g ``` This gets the width on the stack so we know how many to print ``` 0020gv-1:< >:0`| $ ``` This adds two dummy values to the stack to tell when we've finished an operation, as well as what row (n) we're on. This then adds n values to the stack ``` >v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v |>|>|>|>|>|>|>|>|>|>|>|>|>|>|>|>|>|>|>|>|>|>|>|>|>|>|>"!DAB"....@ < < < < < < < < < < < < < < < < < < < < < < < < < < < ``` This is a control section that will to the (26-n) row. This is the easiest way i could figure out how to do it. ``` ".......#.....#####......." ".......##.....#####......" ".......###.....#####....." ".......####.....####....." ".......#####.....###....." ".......######.....##....." ".......#######.....#....." ".......########.........." "####################....." ".####################...." "..####################..." "...####################.." "....####################." ".....####################" "#.....##############.####" "##.....#############..###" "###....#############...##" "####...#############....#" "#####..#############....." ".#####.#############....." "..##################....." "........#####............" ".........#####..........." "..........#####.........." "...........#####........." "............#####........" ``` This, obviously, is read and will pop whatever row is read onto the stack backwards. This means when we pop it off, it will print properly. ``` v_ ,: >^ ``` This will print until the stack hits a 0, which we left on earlier. ``` 1-:#^_ ``` This takes 1 off of the number of the specific line to print, then checks if it's zero or not. If it's non-zero, we go back to the fourth block of code. ``` , + 20g1-20p55^ ``` This subtracts 1 from the row (n), prints a newline, and goes back to block 3 ``` p00-1g00 ``` Once of all of the rows have printed, this subtracts one from the initial height and goes back to block 2. All the rest of the code is either control flow or stack management. Writing this mas more than I thought it would be, but I'm satisfied with how it looks. It's much more golfable, and that will likely remain a project for another day. **2120 -> 1967**: trimmed up some lines with a lot of wasted spaces [Answer] # Perl, 243 (One byte added for the `-n` switch to fetch input from stdin.) ``` ($w,$h)=split;for(1..$h){print((sprintf("%025b",hex)x$w).$/)foreach qw(20f80 307c0 383e0 3c1e0 3e0e0 3f060 3f820 3fc00 1ffffe0 fffff0 7ffff8 3ffffc 1ffffe fffff 107ffef 183ffe7 1c3ffe3 1e3ffe1 1f3ffe0 fbffe0 7fffe0 1f000 f800 7c00 3e00 1f00)} ``` This is fairly straightforward — all it does is convert an array of 26 hex numbers to binary and print them out the required number of times. ### Example: Input: ``` 3 2 ``` Output: ``` 000000010000011111000000000000001000001111100000000000000100000111110000000 000000011000001111100000000000001100000111110000000000000110000011111000000 000000011100000111110000000000001110000011111000000000000111000001111100000 000000011110000011110000000000001111000001111000000000000111100000111100000 000000011111000001110000000000001111100000111000000000000111110000011100000 000000011111100000110000000000001111110000011000000000000111111000001100000 000000011111110000010000000000001111111000001000000000000111111100000100000 000000011111111000000000000000001111111100000000000000000111111110000000000 111111111111111111110000011111111111111111111000001111111111111111111100000 011111111111111111111000001111111111111111111100000111111111111111111110000 001111111111111111111100000111111111111111111110000011111111111111111111000 000111111111111111111110000011111111111111111111000001111111111111111111100 000011111111111111111111000001111111111111111111100000111111111111111111110 000001111111111111111111100000111111111111111111110000011111111111111111111 100000111111111111110111110000011111111111111011111000001111111111111101111 110000011111111111110011111000001111111111111001111100000111111111111100111 111000011111111111110001111100001111111111111000111110000111111111111100011 111100011111111111110000111110001111111111111000011111000111111111111100001 111110011111111111110000011111001111111111111000001111100111111111111100000 011111011111111111110000001111101111111111111000000111110111111111111100000 001111111111111111110000000111111111111111111000000011111111111111111100000 000000001111100000000000000000000111110000000000000000000011111000000000000 000000000111110000000000000000000011111000000000000000000001111100000000000 000000000011111000000000000000000001111100000000000000000000111110000000000 000000000001111100000000000000000000111110000000000000000000011111000000000 000000000000111110000000000000000000011111000000000000000000001111100000000 000000010000011111000000000000001000001111100000000000000100000111110000000 000000011000001111100000000000001100000111110000000000000110000011111000000 000000011100000111110000000000001110000011111000000000000111000001111100000 000000011110000011110000000000001111000001111000000000000111100000111100000 000000011111000001110000000000001111100000111000000000000111110000011100000 000000011111100000110000000000001111110000011000000000000111111000001100000 000000011111110000010000000000001111111000001000000000000111111100000100000 000000011111111000000000000000001111111100000000000000000111111110000000000 111111111111111111110000011111111111111111111000001111111111111111111100000 011111111111111111111000001111111111111111111100000111111111111111111110000 001111111111111111111100000111111111111111111110000011111111111111111111000 000111111111111111111110000011111111111111111111000001111111111111111111100 000011111111111111111111000001111111111111111111100000111111111111111111110 000001111111111111111111100000111111111111111111110000011111111111111111111 100000111111111111110111110000011111111111111011111000001111111111111101111 110000011111111111110011111000001111111111111001111100000111111111111100111 111000011111111111110001111100001111111111111000111110000111111111111100011 111100011111111111110000111110001111111111111000011111000111111111111100001 111110011111111111110000011111001111111111111000001111100111111111111100000 011111011111111111110000001111101111111111111000000111110111111111111100000 001111111111111111110000000111111111111111111000000011111111111111111100000 000000001111100000000000000000000111110000000000000000000011111000000000000 000000000111110000000000000000000011111000000000000000000001111100000000000 000000000011111000000000000000000001111100000000000000000000111110000000000 000000000001111100000000000000000000111110000000000000000000011111000000000 000000000000111110000000000000000000011111000000000000000000001111100000000 ``` [Answer] # Rev 1, C, ~~118~~ 115 bytes ``` i,x,y;f(w,h){for(i=26*h*(w*=25);i--;i%w||puts(""))x=i%25,y=i/w%26,putchar(((y>x^y>x+5^x>y+4)&y/13==x/13^y/13)+34);} ``` 9 bytes saved due to new rule allowing translation of the cell. 3 bytes saved by use of `w*=25`. Rest of post remains unchanged. # Rev 0, C, 127 bytes ``` i,x,y;f(w,h){for(i=650*w*h;i--;i%(25*w)||puts(""))x=(i+20)%25,y=(i/25/w+8)%26,putchar(((y>x^y>x+5^x>y+4)&y/13==x/13^y/13)+34);} ``` This goes through the characters, printing them one by one. `i%(25*w)||puts("")` inserts a newline at the end of each line. My way of viewing the design is similar to Jakube's, but I bring the top 8 rows to the bottom and the 5 right columns to the left to get the following view. In the program this step is "reversed" by `+20` and `+8` in the expressions for x and y. ``` """""#################### #"""""################### ##"""""################## ###"""""################# ####"""""################ #####"""""############### "#####"""""############## ""#####"""""############# """#####""""############# """"#####"""############# """""#####""############# """"""#####"############# """""""################## """""""""""""#####""""""" """"""""""""""#####"""""" """""""""""""""#####""""" """"""""""""""""#####"""" """""""""""""""""#####""" """"""""""""#"""""#####"" """"""""""""##"""""#####" """"""""""""###"""""##### """"""""""""####"""""#### """"""""""""#####"""""### """"""""""""######"""""## """"""""""""#######"""""# """"""""""""########""""" ``` Apart from the "inversion of colours" it may look very similar, but there is an important difference: the diagonal stripes match up. (note that the original design does not have diagonal symmetry as it measures 25x26.) The expression `((y>x^y>x+5^x>y+4)^y/13)+34` produces the following, where the various comparison operators produce the stripes, the `^y/13` produces the "colour flip" half way up and the `+34` takes the resulting number `0,1` and boosts it to the ASCII range `34,35`. ``` """""#################### #"""""################### ##"""""################## ###"""""################# ####"""""################ #####"""""############### "#####"""""############## ""#####"""""############# """#####"""""############ """"#####"""""########### """""#####"""""########## """"""#####"""""######### """""""#####"""""######## ########"""""#####""""""" #########"""""#####"""""" ##########"""""#####""""" ###########"""""#####"""" ############"""""#####""" #############"""""#####"" ##############"""""#####" ###############"""""##### ################"""""#### #################"""""### ##################"""""## ###################"""""# ####################""""" ``` The term `&y/13==x/13` evaluates to false=0 in the top right and bottom left quarters, producing the square part of the pattern as shown previously. Note that because the program downcounts, the origin x=y=0 is at bottom right. This is handy as the square of `#` is 13 characters wide while the square of `"` is only 12 characters wide. [Answer] # [Befunge](https://esolangs.org/wiki/Befunge)-93, 968 bytes Yes, that's right! A competing Befunge answer! ``` &:&\00p10p:520pv:g00p02<v < # p1*45-1_v#:" " < v |`-1*65:g02$< , >:" "\39*\p:" "\47 *v +:"<"\39*\p:"v"\47*\p25^>\p 1 ".......#.....#####......."<v ".......##.....#####......" ".......###.....#####....." ".......####.....####....." ".......#####.....###....." ".......######.....##....." ".......#######.....#....." ".......########.........." "####################....." ".####################...." "..####################..." "...####################.." "....####################." ".....####################" "#.....##############.####" "##.....#############..###" "###....#############...##" "####...#############....#" "#####..#############....." ".#####.#############....." "..##################....." "........#####............" ".........#####..........." "..........#####.........." "...........#####........." "............#####........" ,,,,,,,,,,,,,,,,,,,,,,,,, v> > 10g1-:10p #v_@ " " \47*\p5:"<"v>:" "\39*\ p \*74 \"v":p\*93\< v,*5 2p ``` Explanation tomorrow, bed now. I will say, however, that I do clever stuff with moving a couple redirection arrows and I use the wrap-around property quite a bit too. Test it out in [this online interpreter](http://www.quirkster.com/iano/js/befunge.html). ]
[Question] [ *Too bad! I had such a beautiful equation, but I lost all my `=+-*`, so there is nothing left but a chain of digits, looking like a number: `7512`. But was it `7+5=12` or `7-5=1*2` or `7=5*1+2` or `7=5+1*2`? Or are there even more valid possibilities?* Your task: **For a given positive integer number, return the number of true equations containing the digits of that number in the given order, using plus and minus and multiplication operators.** * dot-before-dash calculation is used, so 1+2\*3 is 7, not 9 * plus and minus are only allowed as operators, not as (prefix) sign, so neither negative numbers in the equation nor superfluous plus padding * no division to keep rules simple * input numbers are integers ranging from `0` to `999999` * no leading zeroes, neither in input, nor in equations * operators are allowed to appear several times, but of course only exactly one `=` * a single digit as input leads to `0` as output, because you can't do any equation with it * the smallest number to return `1` is `11` (equation is `1=1`) * don't underestimate the possibilities for higher numbers like `1111` (`10`possible equations: `11=11 1*1=1*1 1+1=1+1 1-1=1-1 1=1*1*1 1=1-1+1 1=1+1-1 1*1*1=1 1-1+1=1 1+1-1=1` * you are free to use anything from brute force to intelligent algorithms, execution time is irrelevant, just *don't use many bytes of code*, because we are golfing Check your code with these examples: ``` 7 --> 0 42 --> 0 77 --> 1 101 --> 3 121 --> 1 1001 --> 12 1111 --> 10 7512 --> 5 12345 --> 5 110000 --> 203 902180 --> 37 ``` [Answer] # GNU `sed -E`, ~~214 200 181 171~~ 169 bytes For some not-so-obvious reason, I decided to solve this by myself in `sed`, misusing the shell for expression evaluation with the `e` flag of the GNU version of the tool: ``` G:1;s/(\S*[0-9])([0-9]\S*\n)/\1_\2\1==\2\1+\2\1-\2\1*\2/;t1;s/_//g;:2;s/(\n|^)[^=]+\n/\n/;s/\S*=\S+=\S*//;t2;s/\S*/+$((&))/g;s/\S*[ =*+-]0[0-9]\S*//g;s/.*/echo $((&))/e ``` **[Try it online!](https://tio.run/##NU27DsIwDPyVDgjloeAmWxtlRHxAx7jtAFVhSSqlbHw7wQkg2Wfd2XdOy02t4ZnzxfbaJmA4CN@qbuSsDqIYOKCe0aB2rqAsoAoINGD34psBVtubmhBeE/eTGyUGoCKNUhwOkloAGcxXAnlg7Mg5OSv3jRNSje3/MdTFScByvcfmd7vk3L3jtj9iSFmdPw "sed – Try It Online")** * `G` appends the (empty) hold space, so it adds a newline to the end, which is used as a separator * `:1;s/(\S*[0-9])([0-9]\S*\n)/\1_\2\1==\2\1+\2\1-\2\1*\2/;t1` loops to add operators or `==` between each pair of digits, marking already considered pairs by `_` * `s/_//g` removes the `_` markers * `:2;s/(\n|^)[^=]+\n/\n/;s/\S*=\S+=\S*//;t2` removes items without `==` or with more than one `==` * `s/\S*/+$((&))/g` turns each equation in to an arithmetic expansion `$(())` * `s/\S*[ =*+-]0[0-9]\S*//g` is needed to remove all equations including a leading zero * `s/.*/echo $((&))/e` finally evaluates the whole rubbish [Answer] # JavaScript (ES6), 107 bytes *-26 bytes (!) thanks to [@tsh](https://codegolf.stackexchange.com/users/44718/tsh)* ``` f=([c,...a],s,g=o=>f(a,[s]+c+o))=>c?g``+g`==`+g`+`+g`-`+g`*`:/^(?!.*\D0\d)[^=]*==[^=]*\d$/.test(s)&&eval(s) ``` [Try it online!](https://tio.run/##fc5tC4IwEAfw930KGxGb2txWYgWXb/oWPuCYDxTSoklf3zLCRKt78b@DH8fdWd6lUbfTtVlddF60bQk4Ui6lVCaucSvQcCixdCOTOMrRhMBBhVWWOVUG0KXTxaoLO9t7KQ7n1I6PLM5JlEJiA7xanC882hSmwYYsl8Vd1s@hVfpidF3QWle4xChAVleEWJ5nsdlINwL90SAYKB8rZxz1up6oGOiX3dfyW8WEn/Xh6V8@Fz3708vrjY9@6Y4JvmXo/XXQPgA "JavaScript (Node.js) – Try It Online") ### How? We recursively build all possible expressions obtained by adding `""`, `"=="`, `"+"`, `"-"` or `"*"` after each character. For each expression, we test whether it matches: ``` // .--------------------> no number may start with '0' // | .-------------> left part // | | .---------> comparison operator // | | | .------> right part (except the last character) // | | | | .--> we must end with a digit // _____|___ _|_ | _|_ | // / \/ \/\/ \/\ /^(?!.*\D0\d)[^=]*==[^=]*\d$/ ``` If it does, we can safely `eval()`'uate it and increment the final result if it's truthy. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 28 bytes ``` øṖ'⌊=A;ƛṄfð`+*-,`VΠEƛk-İ⁼]f∑ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m720rLIiMWdptJKjUuyCpaUlaboWN3UO73i4c5r6o54uW0frY7Mf7mxJO7whQVtLVych7NwC12Ozs3WPbHjUuCc27VHHxCXFScnFMJ360UrqCeamhkYJ6ko6QKahgaEhjGkIZ1oaGBlaGAA5MBsB) Semi-port of [Jonathan Allan's Jelly answer](https://codegolf.stackexchange.com/a/265130/100664), but much clunkier. The `A` flag runs testcases. ``` øṖ # Partitions ' ; # Where A # All substrings = # Are equivalent under ⌊ # Cast to integer ƛ ] # For each partition Π # Cartesian product of Ṅf # Join with spaces and flattening ð`+*-,`V # Then replacing spaces with "+*-," Π # Resulting in all combinations of the operators and strings E # Evaluate as Python ƛ ] # Map each to ⁼ # Whether it remains the same under k-İ # [x[-1], x[1]] - ensures it is a 2-item list with both items the same f∑ # Flatten and count truthy values ``` [Answer] # [Python](https://www.python.org), 178 bytes *-2 bytes, thanks to corvus\_192* ``` lambda s:len({*filter(eval,q(s,"=="))}) q=lambda s,c:[l+c+r for i in range(1,len(s))for l in e(s[:i])for r in e(s[i:])] e=lambda s:[s]*(s==str(int(s)))+q(s,"+")+q(s,"-")+q(s,"*") ``` [Attempt This Online!](https://ato.pxeger.com/run?1=XY5BDsIgFET3PQVhBW1NStVUSThJ7aIqKAmiApoY40ncNDF6AG_jbSxqTejf8Of9yTDXx-7k1lvd3ASb3Q9ODCavp6o382UNLFVco3MspHLcIH6sVbpHNoWMQYwvONqzzpkuaKmSRWKA2BoggdTA1HrFEUl9hsXYc-U5R7aksvoA0wFJK1xF_J9HS1vFyDJmnUFSO5-Ak8_nCfwtg26JIf41v-2MNwsEi7Zh9FejPJBFeCUZCXXe01nf0E4YOCZ5L2I4GgdkmuVkkrXoW7Vpvu8b) *Takes the string representation of the number as input* Generates all possible equations, uses `eval` to compare the results The `*(s==str(int(s)))` part prevents leading zeros [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~35 34 32~~ 31 bytes -3 thanks to [Unrelated String](https://codegolf.stackexchange.com/users/85334/unrelated-string)! (Filtering leading zero decimals with `ḌVÐṀ` rather than the somewhat clunky `ḌD$ƑƇḌ`. Also `Ṛṁ2ƊƑ` -> `.ị$Ƒ`) ``` DŒṖḌVÐṀżFŒV.ị$ƑʋⱮL’“*+,-”ṗƲ$€FS ``` A monadic Link that accepts a positive integer and yields the count. **[Try it online!](https://tio.run/##y0rNyan8/9/l6KSHO6c93NETdnjCw50NR/e4HZ0Upvdwd7fKsYmnuh9tXOfzqGHmo4Y5Wto6uo8a5j7cOf3YJpVHTWvcgv/rHG7XdP//P9pcR8HESEfBHEgbGhgCCSMQYQBmAgFQxtTQCCRsbGKqo2BpYGRoYRALAA "Jelly – Try It Online")** ### How? ``` DŒṖḌVÐṀżFŒV.ị$ƑʋⱮL’“*+,-”ṗƲ$€FS - Link: positive integer, N D - get a list of N's digits ŒṖ - all partitions of that list Ḍ - convert each part of each from base ten : e.g. [0,7,2] -> 72 ÐṀ - keep those maximal under: V - evaluate as Jelly code (e.g. [4,72,1]-> 4721) : i.e. those that had no leading zero digit € - for each DecimalisedPartition: $ - last two links as a monad: Ʋ - last four links as a monad: L - length ’ - decrement “*+,-” - "*+,-" ṗ - Cartesian power Ɱ - map across these operator lists with: ʋ - last four links as a dyad: ż - {DecimalisedPartition} zip {Operators} F - flatten ŒV - evaluate as Python code Ƒ - is {X=that} invariant under?: $ - last two links as a monad: . - 0.5 ị - index into {X} -> [last(X), first(X)] : i.e. is exactly two equal values? F - flatten S - sum ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 61 bytes ``` ⊞υωF⮌θ≔ΣEυ⁺ι⁺⎇∧κ∨⁼κ0∨⌕κ0⁻§κ¹IΣ§κ¹⟦+¦-¦*ω==⟧⟦ω⟧κυILΦυ∧⁼²№ι=UVι ``` [Attempt This Online!](https://ato.pxeger.com/run?1=VVCxTsMwEBUrH4EsTxdIpIQJqeoQoSIhUREBW5XBpG5j1TjU9iX0W1g6FME38TWc4yx4uJPfu3fv2Z8_TSts0wl9PH6h32Q3v2cXFboWMGVDMjvfdJbBk-yldRL2ScJK59TWwDO-wVK8h7FKowM19RdpjbAHKM0adil7tLDYo9AuXHjOkxG6U5GNwFIZEpb-3qzlR4ALAm-F86PJPzyelK34FSd5FsollYH6fM5rYoaa-F0cQ3pAZZXxMK57kGbrW3LXXtqQPISc4l2TZYc0qcIqHtTVwbedWfRCo_ASVDSfndxr46bP-l7xrNe8PhV5XkToDw) Link is to verbose version of code. Explanation: ``` ⊞υω ``` Start with an empty expression. ``` F⮌θ ``` Loop over the digits in reverse order. ``` ≔ΣEυ⁺ι⁺⎇∧κ∨⁼κ0∨⌕κ0⁻§κ¹IΣ§κ¹⟦+¦-¦*ω==⟧⟦ω⟧κυ ``` For each expression so far, prefix this digit, but if the expression is not empty, and it either does not being with `0` or the `0` is not part of a larger number, then also optionally insert an operator. ``` IΣEΦυ⁼²№ι=UVι ``` For each expression that contains exactly one equality operator, evaluate that as python, and output the the number of expressions for which everything is true. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 33 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` .œʒïJQ}ε©…-+*„==ªsg<ãε®s.ιJ]˜.EáO ``` [Try it online](https://tio.run/##AT8AwP9vc2FiaWX//y7Fk8qSw69KUX3OtcKp4oCmLSsq4oCePT3CqnNnPMOjzrXCrnMuzrlKXcucLkXDoU///zEwMDE) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaVLqNJ/vaOTT006vN4rIrD23NZDKx81LNPV1nrUMM/W9tCq4nSbw4uBouuK9c7t9Io9PUfP9fBC//9KemE6/6PNdUyMdMzNdQwNDHUMjYDYAMQAAh1zU0MjoJCxiamOpYGRoYVBLAA). **Explanation:** Step 1: Get all partitions of the input-integer, and remove all partitions that contain parts with leading 0s: ``` .œ # Get all partitions of the (implicit) input-integer ʒ # Filter the list of lists of parts by: ï # Cast each part to an integer, removing leading 0s J # Join all parts back together Q # Check whether it's equal to the (implicit) input-integer } # Close the filter ``` [Try just step 1 online.](https://tio.run/##yy9OTMpM/f9f7@jkU5MOr/cKrP3/39DAwBAA) Step 2: Create all possible equations of each partition using `-`,`+`,`*`,`==` delimiters: ``` ε # Map over each remaining partition: © # Store the current partition in variable `®` (without popping) …-+* # Push string "-+*" „==ª # Convert it to a list of characters, and append "==": ["-","+","*","=="] s # Swap so the partition is at the top again g # Pop and push its length < # Decrease it by 1 ã # Get the cartesian power of the ["-","+","*","=="] and this length-1 ε # Inner map each list of operators by: ® # Push partition `®` s # Swap so the current list of operators is at the top .ι # Interleave the two lists J # And then join them together to a single string ] # Close the nested maps ˜ # Flatten the list of list of equation-strings ``` [Try the first two steps online.](https://tio.run/##AToAxf9vc2FiaWX//y7Fk8qSw69KUX3OtcKp4oCmLSsq4oCePT3CqnNnPMOjzrXCrnMuzrlKXcuc//8xMDAx) Step 3: Evaluate each equation-string as Elixir code: `.E`. [Try the first three steps online.](https://tio.run/##ATwAw/9vc2FiaWX//y7Fk8qSw69KUX3OtcKp4oCmLSsq4oCePT3CqnNnPMOjzrXCrnMuzrlKXcucLkX//zEwMDE) Step 4: Count the amount of `"true"` values, which under the hood are all `1` (05AB1E's truthy value), making it difficult to find a correct and short way of distinguishing `"true"` from actual `1`s. To give some examples of why this works so weird: 1. Counting the amount of `"true"` in the list results in 0: [try it online](https://tio.run/##AUQAu/9vc2FiaWX//y7Fk8qSw69KUX3OtcKp4oCmLSsq4oCePT3CqnNnPMOjzrXCrnMuzrlKXcucLkUidHJ1ZSLCov//MTAwMQ); 2. Trying to convert it to a flattened list of characters results in an error, since it cannot convert the `"false"` / `"true"` items: [try it online](https://tio.run/##AT0Awv9vc2FiaWX//y7Fk8qSw69KUX3OtcKp4oCmLSsq4oCePT3CqnNnPMOjzrXCrnMuzrlKXcucLkVT//8xMDAx); 3. Filtering on 05AB1E-truthy values will keep both the `1` and `"true"`: [try it online](https://tio.run/##AT8AwP9vc2FiaWX//y7Fk8qSw69KUX3OtcKp4oCmLSsq4oCePT3CqnNnPMOjzrXCrnMuzrlKXcucLkXKkn3//zEwMDE) or [try it online](https://tio.run/##AT8AwP9vc2FiaWX//y7Fk8qSw69KUX3OtcKp4oCmLSsq4oCePT3CqnNnPMOjzrXCrnMuzrlKXcucLkVEw4///zEwMDE); 4. Sorting (after the truthy filter) does work correct, although an additional group-by not: [try it online](https://tio.run/##AUUAuv9vc2FiaWX//y7Fk8qSw69KUX3OtcKp4oCmLSsq4oCePT3CqnNnPMOjzrXCrnMuzrlKXcucLkXKkn17PQrOsyz//zEwMDE); 5. etc. Eventually I noticed the `þ` (keep all digits/numbers) and `á` (keep all letters/words) would correctly distinguish between the two, so I've used that to finish my program that utilizes Elixir-equations and evals: ``` á # Keep all letters/words (which will only keep all "false" and "true") O # Sum this list together, since they're 0 and 1 under the hood # (after which this count of "true" items is output implicitly as result) ``` [Answer] # [Python](https://www.python.org), 255 bytes ``` lambda s:len({q for r in range(len(s)+1)for o in combinations("+-*"*len(s),r)for p in permutations([*s,"==",*o])if match(f"{n}=={n}$",q:="".join(p))and s==sub("\D","",q)and eval(q)}) m="(0|[1-9]\d*)" n=f"{m}(\D{m})*" from itertools import* from re import* ``` [Attempt This Online!](https://ato.pxeger.com/run?1=TdBBTgMhFIDh_Zzi5dUFUGo6aqM2YddbdLpgLFjMAFNgNKb2JG6aGL2Tp9GZUmM3EL788BLev9rXtPHu8KFF9dklPbn7_mmkrdcS4rxRjuy2oH2AAMZBkO5RkUEjHZd0cD_4g7e1cTIZ7yLB8YQhyxEPx6gdolYF26VTtGSRoxDImV9Ro8HK9LAhGnduL0S_XCDfzgXi5ZM3jrSUSreGKETsaoLVAjn2wRHVs2zIlu5pYQWS6duynNyvqjWjWDjRP2j3pFr0K2VY6OAtmKRC8r6JYGzrQ2KZg_o7n77hpQ3GJTLloAneIqXFOdxc_UuZk7Pm-ijltBxolG2Wq1k53IQRJGNVBN8lDnWX-vmpCy7CLI8_HPL-Cw) [Answer] # [Ruby](https://www.ruby-lang.org/), ~~117~~ 113 bytes Takes a string as input. Creates every possible combination of operators and counts which ones have no leading zeroes and `eval` to `true`. This is probably the only time in Ruby golfing when `do`/`end` will ever be cheaper than the curly brace syntax, since that allows `rescue SyntaxError` without adding a `begin` block like it normally would require. (Inline `rescue` doesn't catch SyntaxError so the longer syntax is needed.) -4 from Dingus. ``` ->s{[p].product(*[%W"#{} == + - *"]*s.size).count do !p==eval(e=_1.zip(s.chars)*'')&&/0\d/!~e rescue$!.class;end} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=LY1daoNAFIXf7yquP03U4GTGJJhSptvogxEx45gINk4dp6URu5G-BNouKrvplPTAgY8DH-fzuzf798tXzXc_Zqjj7fUlftRjpnKi-q4yYgii7O7J9cYJOccFxhi5eaSJbs4yJKIzpwGrDhzFuXwt20DygpFzowJNxLHsdRjN5-FstqS7aul8SOilFkb6DhFtqfWDPFXT__Hq7di0Eg9y0IB-YfXuWTmAygwa3Trz_CJHjt5YZ5YmF6x7Uy_XRQrrBNIUGGXAElv6BzaQblhip9V6A_c0YVt6c34B) [Answer] # [JavaScript (Node.js)](https://nodejs.org), 96 bytes ``` f=([c,...a],s='',g=t=>f(a,s+t))=>/\b0\d/.test(s+=c)?0:a+a?g`+`+g`-`+g`*`+g``+g`===`:eval(s)===!0 ``` [Try it online!](https://tio.run/##fc5tC4IwEAfw930K25u2ZnObiSWcfpAMXD5RSEYbfn3TEBOtDu44@HHc/6YapdPn9WF29zrL27YAfEptxpg62xo2G7sEA2GBla2pIQRCJ77wOHOYybXBmkJKIh4oqqIyoQktk10/tv3oGwCSIG9UhTXp9jVv0/qu6ypnVV3iAiMfWX0RYjmOxVcz3Uv0R31/omKuggs0qrtQOdEvt@/jQeWCu/rwMpcn5Mje8rO799AvPXIpDhwNqf32BQ "JavaScript (Node.js) – Try It Online") Unlike Arnauld who tests if exactly one `==` exist, I use `===`: ``` 1 => 1 1===1 => true 1===1===1 => false 1===1===1===1 => false ``` so if it results in `true` it's an equation ]
[Question] [ # About the Series First off, you may treat this like any other code golf challenge, and answer it without worrying about the series at all. However, there is a leaderboard across all challenges. You can find the leaderboard along with some more information about the series [in the first post](https://codegolf.stackexchange.com/q/45302/8478). # Hole 8: Shuffle an infinite list You should write a function or program which takes an infinite list as input and returns a shuffled version of that list. ## About infinite I/O There are several ways you can take input and produce output for this challenge: * You can either take a list of positive integers, or a string representation thereof, or a string or list of printable ASCII characters (0x20 to 0x7E, inclusive). The output format must match the input format. I'll just refer to the data as "the list" from now on, regardless of which option you choose. * You can read the list from an infinite standard input stream and write the output continuously to an infinite standard output stream. The solution should not depend on any particular value or sequence of values to ensure that the output stream is regularly written and flushed (e.g. you can't just write output whenever there's a `5` in the input list). Of course, if you read a string representation of a list, it's fine to wait until encountering the list separator. * In languages that support them, you can write a function that takes and returns a lazy infinite list or string. * In languages that support them you may implement an infinite generator that takes another generator as input. * Alternatively, you can write a function which takes no arguments and returns one output value each time it is called. In this case, you can assume that a function has been defined which takes no arguments and returns the next input value each time it is called. You may freely choose that function's name. You may assume that your program runs forever and that infinite memory is available. (It's possible to solve this with a finite amount of memory, but what this means is that you're allowed to leak memory.) ## About the randomness For any value **v** which is read at a position **i** of the infinite input, there must be a positive probability for it to end up in any of the positions **i-9** to **i+9** of the infinite output (unless that position would be negative). These probabilities don't have to be the same for different output positions or even for different input positions. It's fine if your solution can also shuffle the values to other position that are further away. Hence, it's not necessary that your solution can shuffle the first value very far down the list, or that it can shuffle a very late value up to the first position, although it's fine if it does, as long as all positions 9 steps from the input are possible. E.g. if you took the following string as input, the `___` indicates all the positions the `X` must be able to end up in the output: ``` ___________________ abcdefghijklmnopqrstuvwxyzXabcdefghijklmnopqrstuvwxyz... ``` If your language lacks a built-in random number generator or you don't want to use it, you may take an additional seed value as input, and implement your own [suitable RNG](http://meta.codegolf.stackexchange.com/a/1325/8478) using the seed. [This page](http://en.wikipedia.org/wiki/Linear_congruential_generator#Parameters_in_common_use) may be helpful for that. Regardless of the actual distribution your solution uses, it must [almost surely](https://en.wikipedia.org/wiki/Almost_surely) produce the next value after a finite (but arbitrary) time. Please include a short explanation about how your implementation satisfies these requirements. ## Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest valid answer – measured in *bytes* – wins. # Leaderboard **[The first post of the series generates a leaderboard.](https://codegolf.stackexchange.com/q/45302/8478)** To make sure that your answers show up, please start every answer with a headline, using the following Markdown template: ``` # Language Name, N bytes ``` where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance: ``` # Ruby, <s>104</s> <s>101</s> 96 bytes ``` *(The language is not currently shown, but the snippet does require and parse it, and I may add a by-language leaderboard in the future.)* [Answer] # [Python 3](https://docs.python.org/3/), 78 bytes ``` from random import* l=[] while[shuffle(l)]:l[9:]and print(l.pop());l+=input(), ``` [Try it online!](https://tio.run/nexus/python3#DZBLamNRDETnZxUZ2klonqSrX0JWYjxo6JgYXuyH26GX776jAqGSTtXjdLt@P91@X/5MOX9v19v9mfXjcOTf13n9PPz9@jmd1s/duj@@rYd@O87Np@12vtx366/tuu32@/f15eN82X7uu/3r47EgKMbACZKikTkURBFDBuJIIIkU0uiCTo@ihg7U0UATLbSxBRNsnjRsYI4FllhhzVgYwlDG/DgYzghGMorR@IILrrjhE8jxwBMvvImFEEIJIwYxeYNIoogmF1JIJY0cpJMzTpJFNrVQQill1KCcCmqmLarphRZaaaMH7XTQSc8y@j8 "Python 3 – TIO Nexus") Takes input from STDIN (one per line), prints to STDOUT. Keeps a buffer `l` of up to 10 elements. The buffer is shuffled with each step. When its length is 10, the last element is printed and removed. If an element happens to be printed as soon as it was inserted, it has skipped ahead of 9 other elements waiting in the buffer, so it appears 9 spots left. An element can wait in the buffer arbitrarily long, so its position can move any amount right. There doesn't seem to be a nice way to produce and remove a random element from a list. Shuffling seems like overkill. It's 2 bytes longer to use `l.pop(randint(0,9))` (which uses that the list has 10 elements). ``` from random import* l=[] while 1:l+=input(),;l[9:]and print(l.pop(randint(0,9))) ``` It's no better to do `x=choice(l);l.remove(x)`.A language with `poprandom` like ``` poprandom = lambda l:l.pop(randrange(len(l))) ``` could very cleanly do ``` from random import* l=[] while 1:l+=input(),;l[9:]and print(poprandom(l)) ``` [Answer] # Befunge ([quirkster flavor](http://www.quirkster.com/iano/js/befunge.html)), 4 bytes ``` ?,?~ ``` `,` reads a character from the stream and pushes it onto the stack. `~` pops the top character from the stack (if present) and prints it. `?` randomizes which command is executed next. So the algorithm here is "In an infinite loop, with equal probability either push a character or pop a character." I think this satisfies the requirements: a character can see arbitrarily many characters added above it in the stack, so it can move arbitrarily far to the right, and it can be printed when the stack is arbitrarily big, so it can move arbitrarily far to the left. [Answer] # [C (gcc)](https://gcc.gnu.org/), 94 bytes ``` L;i;f(s){srand(s);int B[9]={0};for(L=0;;)L>9&&putchar(B[i=rand()%10]),B[L>9?i:L++]=getchar();} ``` [Try it online!](https://tio.run/nexus/c-gcc#@@9jnWmdplGsWV1clJiXAmRYZ@aVKDhFW8baVhvUWqflF2n42BpYW2v62FmqqRWUliRnJBZpOEVn2oLVa6oaGsRq6jhFA6XtM618tLVjbdNTIYo0rWv/K2fmJeeUpqQq2JRk5qbqZdhxgYzPTczM09Cs5lIAgjQNkIyGX6iPj6amNVft/8TilDRCGAA "C (gcc) – TIO Nexus") Ok, a TIO link doesn't make much sense. For ease of testing, I created the following C program that will output random ascii characters, or repeat an string infinitely. ``` #include <stdlib.h> #include <stdio.h> #include <time.h> int main(int argc, char** argv){ srand(time(NULL)); if(argc < 1) { for(;;){ printf("%c", rand() % 95 + 32); } } else { char* s = argv[1]; int i = 0; for(;;){ if(s[i] == 0) i = 0; printf("%c", s[i++]); } } } ``` This program will be referred to as `iro`. ## Program correctness What I do here is read `9` values into a buffer. After this, random indices are chosen from this array and are outputted, then replaced by the next character in the stream. [Answer] # [S.I.L.O.S](https://github.com/rjhunjhunwala/S.I.L.O.S), 149 bytes ``` b=1 lbla x=15+b*15 b=1 lblb readIO queue 0 i x-1 if x b a=0 lblx x=rand*2 queuePop 0 if x X printInt m a+1 b=15-a if b x GOTO a lblX queue 0 m GOTO x ``` [Try it online!](https://tio.run/nexus/silos#RU2xCoNQDNzzFZkrgnn62jo4Fyc7dHB9Dy0Iaq0ovL9PExU7JNxd7i7sC4Le9w5CQTbyF7JwSB7m1jVlBd@1XVtMsIMQE3RvDOjBFYmaguRmNzYXs9uenwmT3VPDNHfjUo4LDuAi0l4bOz16DPCoXhU67ajPD8OuBmYmTtnIJpNyznkuMDskeyIyMsRiyUQ1mlG2KRq7842vcqMD2Q3rmJNrkxXlz/Ul8dZMPw "S.I.L.O.S – TIO Nexus") Essentially it keeps taking input (on the online interpreter through arguments, but on the offline official interpreter it will allow you type into the console (infinitely)) in blocks of 15 at a time (30 the first block). It loads the input into a temporary queue and picks a lucky 15 (randomly, but not equally distributed in terms of probablity or distribution). The rest remain in as new inputs fill the queue, the first input could be shuffled all the way to the end, (basically I think the characters follow a normal distribution). It's interesting to note that this program is only twice as verbose as python and perhaps "golfier" than Java. --- To better see the results I have a non-compliant version which takes input as a string (however it can only take in 8,000 or so characters). [Try it online!](https://tio.run/nexus/silos#jVdNcxQ3EL3Pr@hKDpiwXmwqJjEFVFEUCa4imMIczMmlmdHsiNVIg6Tx7vqU/5B/mD/ivJbma@1AwoX1jNT9@nX3655bbUX5ThmZ3bx4cvI0y18cZzrXItu@OD55dJD/dHzyEA@P@GGeqRcrGegmu3l0nH3tZCfpiFS2PTzOVEVbyjORTm4zJ0xJT9KhD7alIz7h6DJrnTLhdS0cNZmAGTg8ORT8Nqdt9vv5p3MSbOJydNCkp9vb29tXue0ChVrShXRK@iz7TTkfyFbVgna2o0bsKDgp@JDypNVakjA7srjjqLClpJXVFRW10FqalVwQAxXGb/BeBdqoULOPjXVup8yKxOjSR5cE27i7pLd2I6@lW/A7JwneBGkpSulyKxxsFs56z2cnb35Jn4GyEIYqBb9sdu@OtnDJGMjbRlJj2bKprGtEUNbcR6NM/KuKNLTWh2WWvbVa0q/P6KLuqkozAWxDGRXgTfmQZQzCI05d0sbxY0FVZ4rowjpqnV050dCmVkVNQaw57DtGSLDzFmiYQCdD5wxT4JPTksCNj/YqIARpfAngUgpHU2ePz7PsU2RQOI4K14Smjdj5mFCmigHMfAFd2RWSYIcfgZyU7JHlZylAvipVTHy0IBJu4AFPKqhrNhrkCjgXHDWwB8cpd7J10ksTEucxv7baP4PfozWuaJGD6FcXr8/OGIcTRYBZOjjaPjmiYOlo@8ubBdwVuvNw/HBJiHkWAdJLTQd7@MGU10PA6d2Szh6gjr7wCScrjsjGQ6UIgjPxQ6wkAPqBKmcbMnZD1ixweIW60hKFCKQpn7aNYUV2a2u9XI50oXP6ouTYoqV53n0A/1ynCZvnTmtiTlIVhSmmwpqgTGc7r3cM9l/N9GeTnUSJt7qL8PryNDZQKVsJH1z@aOVWuKCKTkNBroWGQiAVXkIsDNdElR569imN75xM1TeD1sNGxYAdtgOEjD9IE2OpkKMaBXwgl6vlUIQPQmI/Bdpb2tTScMGmEnnA5X8ydGSiiHlEss@hOLZzHnIDoWOTkelvVRyiSMWK4wFmwZvkgDYCCtWBWI3YYBDVG6@PGfMS7Ihg3TI7M6SFWXVixWQwBb5rW@siFc1ibK57/Z/o6nt@3tla3OzuaABTHyP4L3@jOKum1bJBpHsVsQKPEfe@96Ta08tBcpbZK43QjeAm1rvvBDNXMIMqdKuOne@HZs2Y0VRRUvAlBQEG36wsLCwlmtD0SiM4k4NT4T2MJuQz1zXQ5hI1VUrOX/n/sHAqjdyGvn6@j@dzT2rlJGjouzkBGWCgeoxo0OLT6OTRbBsDTcD4ZFbRVMnPdY8xtgbXJweUxBIBqSTlckpbxDgMwChfuRxvQF6h1LnIlVZhF2Ua6GNbltS13CdxMiebgxdk@PCUT6lHp/f89Uk66ExUtBjoCG8T9SJn@laxMJLI@jkMnpil5WauxXVsqTyplgdHEWKpKsgr12fvbAKGt2h2c@dYytN4CkUydmxqdTdpWqwW7e0wJKPrSa9SuY8BpYICs1Xn4huBqcjjnZWuVwaWRyMLsCHcLt2473LuLS0Kfbol7lTQ0dJuzCgicc5FS0jX/LpIF7QIPWjOYj@Hxv0jQsdSpXmNWtUz/QIbMFhaiWmL1oibjkj70cTxKfREtj6NnklGmQUc8gpTFgy8YWHuhTRYu04QrNZ2w3LYi@qgFrFA6erqCn@WqgD85HW/7Pivy6mIeZzv1eo0QLBe0L1/V/f/ZbBSoPlXtfqy1o2x7VeQ1F1vtruby2@/Wi4hpn3lDIqKH8WaNTjvlA6HgJOamEzX5HOJnG3BceVBvZVljBBLlZe8lsXMTUqafdxbEThMLC8djpeKicy7YVuYVVXnOYuq31mEbiwPHwxbqNCwno1K1nusApcw9a18kMe05io4VO7DqG4A8wHbsJdpUSplXCd5hMhtCyrmK3CNBSdiGgdKeuvxn69UnEHc@w6bgXLxgIf9i8JybfDKCZFjKcUnwSF/EiwQXZIC9ihTk6jx0@DvP/@iBtgQI68/lO@4jPgpSo4tv5vW@LjQzlbygdd@Ze@TJe98MMDGJ4vUIW3T2hJDTBA8I9ugGhfUJpawRzE3sSt7mPHTQVANsxpNt0CmhgVh6o8/hFunlpcgD0hQ0T/Su6HW3kMLF/Q@hZhtori/Z65iDOomblmpHrq8UZ63fMheakekw1lIa3oPtmeDci1lSxYiHZ@P3y4T2HwXe3fdQ2YFcKwiS@I5BZ6xOBYJ7ccux9x/7l8eH/38/LF/mX4ex5@nT3vsB5yHsYdUksuicyzcqFTmE1qVD19URrX/AA "S.I.L.O.S – TIO Nexus") Just for fun, here is this post fed through the string version. ``` [.L.Ooy" 9beS.I.S],"14 ts b1 nly =ll x=1b 15 1 5b a*b= lb rd# + lb eaI O e x ifquu 1 0x b = e 0 i lblxa -d*2 quu x=rn x Xea p0 pnInt o r a mf = iePit ba 1 GTO 1 f b x+ Oa qe -lblX u0 m GOOue [rlT tnn5 !I.STii][S.LO ie htpsgthyx]:iub.om/jhujh.. tcraa.I.O.o /TytonieSu:wl/.L lnn!:tt/iS [ in hsto.un/nuslprxRUCoDsio/]:e#NzZn6j4c/2xNQFnF7y0aLzkrosd9Dov2yxJNx774HBrgPUdi9CySI09sCLw5TJwB7jlB1XVeQFE7m1VMsIQvDOjBmdtME3umNzYXs9unFbqRamVDfUDw@RT3NHoL7/i04bz16DCoP4eulOU7jPD8OmYjATpynkuMDuBPYmtnIJzseyyhaNkMyQgXG2R782vqMDIiUm6Kq4Q3mJkxlUsR1rrldPw./l28Z SL.XS – IONuscOT " senallyxMz.stiitkp ingN" eestaint on heeInliinrprt (oe e toghr tetgpnmntuon eruEuut r h ofi off,bhenecil inretea.atr ialoks tirilw upeitfleptly ty honso (e oote cenfine iwllbc 15 atly) nitloo aim( te)nikfte3 firs bck) hs 0It te lodshipo alauttt.mpra quuet i reanicks a lck eooy d randomyn p 15( u o equl,unbtty drbutedaynistinems oftrly ordisrprob ill abition h ibttmin.Tet ri) a nwit u ree nusfil th queusen pte ftip,ae uldsfuesis ob hl rlelth weual t tc hdyoend,f tbaaly thi an elnkhecarcthe(sc h o noreiItrolwaaldibtio lmiru.t' iereaf ) tsng tetntiottssht prasnon hogIms only twieatisi s vroscpythonadprs a hbapolfi" e r n e ehanava. tte s/"gt obterelIe tsvea non-omhTrehs a plntvesion hcahihk ine teuts sriprics at rwvritcaw aa g(hoee n onl kein n00 orscat ,0 cter). [Tyauoas it onine!hrhrys:.ru]p//o/lsslo#jVd(tinnexi3E@KDpit/LrhtwXwVEUuscxPmJjFFCaNimMzlHiQEcMmdVIT7vqs8mNgxU3mD/J1AwX q/ivbao1j@nb4I6/m93655bThmb4cy5TUX3xvI018cZzrXItuO5B@NX5JD/HzyE@G@D5eqrGem3l0HPGRutZfpi2PzVA@d3CVRTm4zJxnZdcFSTEO0JOT9KhDI6byjnLhS0cNmGz7hJrTdAgORT8Ndvv7DgZSbJdkp9v5al8qMyNCb9tXe0ChrShXRTOt@7fFgV3zTkbVbsD@JpKina2oKgNVakjsjLCpD29u7l0XVRWalVTyArF1FqypQAxXb/BedqUqpJGOPVyxOjLj0jXup8cE277L2I6@lSowK5pA7nGldRBiJwyKxF6z2c3kW/sJ4EYBbbpSuBxs55nyI9sdnu@nJJeGqtKprGEUbc6NDGMjjO2tN/KuKTWh2WWbbRRLVaq/P6KqkoMNWGRgTQZLlbXfQI050bY0rz0xmzCVZ4vowjpV0dCmkDFq0VNa5GSDzVn5Qw7idwPTxu5xTAtLQCDN/YIApfAn4dsDmYksCqUU27sRggpzRK4SmdjmPUPQO4j5FmgHMFRWS2eI1CfA2YIcf7JlylFjdZypVTH0IJu4ZJHiUviyBFKqhrkCjgXAAB8d710NhHgDwcJksuvPPprcfzHPTaJGFX8OIExW/cBZjaPiY7a4WD6rTYmOouBVucROlwvuBJiHWdJQjjbobNGTd7M1P6z8dw/A@GU02hgjCcrjjQHkAdS6r7UjQ6wAPqB@sIgxkKcbZDixeWS6mn160CKQpn7aUwGLK22u9I0oX6YIwPMhFVaX5uYon0AyoNTCZvnmtilVhV3/pgTGc7r39lIS5PmqM/NGnUSLnTw9eTJ7qqrNQKsJHz@Tt8mDZVWKCKTkBro1PuQAksDdN1yaVGiVXElRW9i5M11cINmxNGYAg9TD7sxtEDI2OkKMaBXgvO5dOplUQQIdpb2w66NePBScMmEnAX8ydGSiiHlss@hOLZzInnIoTevRtEm/TGHWOkly5ljMK4FkgDDSWCWBW3YwmEVYCIBV@GMIg3TZtGwMFWXVxQwBb5iD6PfS7h7Sric1ib5ZYIvW6n3tlaK7/6@3OAHy4LjOuW@tzaBP3@mFbJpHsVsQKPfeui/o1@aBcbZ4TK96T8tp3QjeA1vDXMKBIqdK@HZs2vsMlQE36YmrBEnVRUvAGNuCt44e0RB0sL0MkNu1Q5wOwliTT2JQzVrOnHAmSXIU//sqjdG6jdT2r1v@@lGjouzkGWoD4zhnzJBxo0OT6OTbBDgeDFRnY8TMXZbMPdxsCtbXeUxIBqST4VRwkpbgwChBcJxMx6hLIVZhfuylDvF1l26Nbl3xRLgQnatSCMigx@PCT6lcG1ebdk/86UBUFp9UkxjoCGSJnlxMtUdHf6IjkMnil5aua9L@xXsdHEKW@8JpVqlgKsr12bAKG2Typfv@Yy4CkUydETWphcdmdpWq7egtxqP8pYI2rSaSuYBwW0tNTdXn4qcjnZ9JKhuVwaWRycwCWt247LSflsCHsB3u0KoLTQJzL1uMl0duij/IF7LCc5FSpIPW7gcjOYj@jQdpQHv0WUz/IbMhS0XmFiWm1i0cTbxXjsjLxt6nGmQNQoKfREklc8pTFyHub7jUg8TR4QrZ2w3YjaLWNi@FFerCnNgY0LqgrA6qkWg8H/7Pv6YhtqeZzvoB0yD5Wm1eLL1Vf/SouI0Q/fox7eQlXieZB1F1v2/in/btqyVPtubWhDIKH8WaTlry43N6HgOEzX5HOjv1@lamBeZlJpqJnG3B2LZe8sXUafdAcVvVjBBlqxbEThCdjpelc7YVuYXOqM8MyVV3iPxbqYu@nmbHnoKpK1Eww11sA9aiwN8kMe0ioVO7qnucL1A8wHJ4wTsdltrm3CC4bpCd5hMhyDGXSdGgdKvnCKUpNB9nH@wXLgu5iUEcfJbDKZFjx6gI9i8fCcUFiQXxeSbKnwhT6@v/I6yS/Ew9k@tgI68/lO@4jjx0PZBpSo5vWLCDi4zb@TJejQQPtvlgde98MDGJ4vUW3T@iJTA89gGhUJIgy@MDBpaz3s7PT2ZIwStVANsxpCmhghh68huncD0VdumQt0lT/Su6HW3kMLFfo/FphQ0QhtoZ5iRN/@hZ/DmHq8UZEgiblprekkw1I366fMhePmDclSxirOlYH2Hwe3fom3aoe1@yaQYwi5ZPd2FcITXO7cu9@6tiHZJc7lKSB8e3/mXx34xYH/8F@TUxx/5vs5yHsYBL4ekscycqT1BnuV19/ "SFE/iRAIL.O NqUXAm. T3zDreu).S –IOxs."d ``` [Answer] # [Aceto](https://github.com/L3viathan/OIL), 24 bytes, non-competing *Non-competing because I had to fix a bug in the interpreter.* ``` ^ OYpO r^`! ?d0= > ``` Takes an infinite stream of lines and yields them in a random order. Every element has a chance of occurring at any random point. We start with a `?` in the bottom left corner, which moves us in a random direction. If that is down or left, we get pushed right back. If we're moved upwards, we `r`ead a value, shuffle the stack (`Y`), and jump back to the `O`rigin. If we're moved to the right, we `d`uplicate the top stack value, push a `0` and test for equality (since we're reading strings, we can't ever have the integer 0). If the values are equal, that means we've reached the bottom of the stack (from which we don't want to print). We *negate* the comparison (`!`), and `p`rint only if (```) the things were not equal. Then we also jump back to the `O`rigin. [Answer] # Ruby, 43 bytes ``` l=[];loop{l<<gets;l[9]&&$><<l.shuffle!.pop} ``` My original answer used a lazy-evaluated infinite list, but this is shorter. Oh well. [Answer] # [MATL](https://github.com/lmendo/MATL), 11 bytes ``` `rEkN*?D}iT ``` [Try it online!](https://tio.run/nexus/matl#@59Q5Jrtp2XvUpsZ8v@/IZcxlymXOZcllxGXCZcFkASJmAFZlkDSBM424jIyNgGqs@AyMQUKGnKZAQA "MATL – TIO Nexus") Port of [histocrat's Befunge answer](https://codegolf.stackexchange.com/a/120514/32352). Explanation: (Thanks to Luis Mendo for -1 byte) ``` ` T % Start do-while (`) .... true (T) rEk % 50-50 chance of outputting or inputting: % Random number between 0...1, multiplied by 2 and converted to logical. N % Check if there is anything on the stack to output *? % If there is anything on the stack and (*) we want to output: D % Output. Sadly, D errors when the stack is empty, requiring the N* }i % Else, input. ``` This outputs almost surely in finite time, and [almost surely requires only finite memory](https://mathoverflow.net/questions/60417/will-a-random-walk-on-0-inf-tend-to-infinity). For completeness, here is a 15-byte version which keeps a 10-element buffer and outputs a random element from that: ``` `htnt9>?Yr&)wDT ``` I like this version for the very idiomatic (as far as golfing languages can be idiomatic) `tn...Yr&)`, which pops a random element from the list and returns the list without that element. However, the particular logistics of this challenge add a lot of bytes (the required `w` for the display, the `t9>?` to check if the list is full enough...). [Answer] # [Alice](https://github.com/m-ender/alice), 7 bytes ``` a&IdU,O ``` [Try it online!](https://tio.run/nexus/alice#@5@o5pkSquP//7@hkbGJqZm5haXBKGuUNcpCZ33Ny9dNTkzOSAUA "Alice – TIO Nexus") This should work on an infinite input with infinite time and memory, but it's not so easy to test in practice :) ### Explanation ``` a&I Push 10 characters from the input to the stack. d Push the depth of the stack. U Pop a number (d), push a random number in [0,d) , Pop a number (n), move the element which is n elements below the top to the top of the stack. O Output the character on top of the stack. Execution loops back to the beginning of the line. ``` At each iteration 10 characters are read from input and only one goes to the output, so memory usage increases linearly during execution. With a finite input this quickly reaches EOF, from which ten -1 will be pushed to the stack at each iteration. Trying to output -1 as a character has no effect, but it's unlikely that all the characters of the input will be printed in a reasonable amount of time. Position *i* of the output can be taken by any character in the input up to position *10i*, this complies with the challenge requiring at least a range from *i-9* to *i+9*. [Answer] # C, 214 bytes ``` c;i;char B[19]={0};char*I; S(p,q){if(B[p]-B[q])B[p]^=(B[q]^=(B[p]^=B[q]));} R(n){while(n--)putchar(B[c]),B[c]=*I,c=++i%19,I++;} main(c,v)char**v;{srand(time(0));I=v[1];R(19);i=9;for(;;){S(i,rand()%19);R(1);i=++i%19;}} ``` **How it works** ![](https://i.stack.imgur.com/qjY3b.png) [**Try Online (UNIX)**](https://tio.run/nexus/c-gcc#dZFRa8IwFIWfm1@RIYNE67RjDEpXoWMMBK2gwgbSSdak64U2VttOWOlv79LoFMeWp5PvJuee3DQdkGFScoEf8oLD5iYeoQuUwPslKyUo3DI0GGAmIWUFbCTOMyE46nARgRTY88dTbzme@evFZPaC74ft@qPqz@ZTb4Lv/qs/e4slvj1UEXdCB5wwZjv8WEaR2K0sO3CrYa1ZF2RWFg5a7FlGMnNLK4jI8VwWXLlHuQ0oPtE3l5zwWbf8fJo6NZoLxomk1T6GRBDZ74@GVDVr2/5cCgNqnqR7CGOGbq8H15Zt6m2vp6xQykASkAVmu4/QxDp6V@lPiipkqJmChAJYAl96sMjId0xyUkAqyFCl4e7c85/WU@91YNkOMrS12xqsrMDRSS2bOuC2RW2YxypXInDKwliNFxmHZ1gUGZX6RMMo80SIjPz@FqoMDD1OMHUGOuCaHZpoCccXKl2jummabw) ``` #include <stdio.h> #include <unistd.h> // animation speed #define ANIMATION_SLOW 600000 #define ANIMATION_NORMAL 400000 #define ANIMATION_FAST 200000 c;i;char Buffer[19]={0};char*input; Swap(p,q){if(Buffer[p]!=Buffer[q])Buffer[p]^=(Buffer[q]^=(Buffer[p]^=Buffer[q]));} Read(n){while(n-->0)putchar(Buffer[c]),Buffer[c]=*input,c=++i%19,input++;} main(int argc, char**argv) { // initialization srand(time(0)); input=argv[1]; Read(19);i=9; // shuffle machine while(1) { usleep(ANIMATION_NORMAL); Swap(i,rand()%19); Read(1); i=++i%19; } } ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 13 bytes ``` [I)˜¼¾T›i.rć, ``` [Try it online!](https://tio.run/nexus/05ab1e#MzJw@6/gqXl6zqE9h/aFPGrYlalXdKRd5/9/Qy4jLmMuEy5TLjMucy4LLksuQwMuQ0MuQyMuQ2MuQxMuQ1MuQzMuQ3MuQwsuQ0suI4Ovefm6yYnJGakA "05AB1E – TIO Nexus") (modified to take 20 elements) ``` [ # Infinite loop I)˜ # Add the next element from input to the array ¼ # Increment the counter variable ¾T›i # If the counter variable is greater than 10... .r # Get a random permutation of the array ć, # Print and remove the first element ``` [Answer] # [Bash](https://www.gnu.org/software/bash/), 17 bytes ``` xargs -n9 shuf -e ``` [Try it online!](https://tio.run/nexus/bash#7cu5FYAgEEDB3Cp@AxRgOYgIXqAiXn0bYx@@nXzKpTeXUKEm@dyhbCmaBkOLpcPh6RkYmZgJRBZWNhI7mYOTi5unkiNHjhw5/z3lDVEZbbz9AA "Bash – TIO Nexus") xargs continuously takes 9 letters from STDIN and sends them to shuffle an infinite list can be generated by: ``` yes {a..z} ``` which prints a b c d e .. z infinite times. Test could be done by: ``` yes {a..z} | xargs -n9 shuf -e ``` [Answer] # R, 70 bytes ``` x=NULL;repeat{x=sample(c(x,scan()));if(sum(x|1)>9){cat(x[1]);x=x[-1]}} ``` Starts with an empty vector `x`. In an infinite loop, it takes a new value from STDIN, then shuffles the vector. Then it checks if the length of the built up list is 10 or higher. If it is, it can start printing. This way the vector has a buffer of 10 inputs, each getting shuffled in every iteration. So it is possible for input to be printed 10 places earlier, and infinitely many places later (following a geometric distribution with `p=1/10`). When the buffer is long enough, the first element is printed and removed from the vector. [Answer] # Javascript, 78 bytes ``` for(l=[];;){l.push(prompt());l.length==10&&alert(l.splice(Math.random()*9,1))};x.sort(()=>Math.random()<0.5);alert(x)} ``` Uses the same method as xnor's answer. [Answer] # [Perl 5](https://www.perl.org/), 39 bytes 38 bytes of code + `-n` flag. ``` print splice@F,rand 10,1if 9<push@F,$_ ``` [Try it online!](https://tio.run/nexus/perl5#Dci7CsIwAIbR/XuKiI4t5E@vAQcnX0NKjLRQYmjroztHz3jOpxy31dSp5G1Jh9nzuoR4u1fblJ5GttLyMv6aP/v8z8ujFOFoaOnoGRjxyCIhhxrUog71aEAj8jj7Te86TGGOPw "Perl 5 – TIO Nexus") Add each element to `@F` array (with `push@F,$_`). When `@F` contains 10 elements (`push` returns the number of elements in the array, hence `9<push...`), a random element is removed and printed (`splice@F,rand 10,1` to remove the element, `print` to print it). The output starts happening after then 10th element has been read. Hence, each element can start appearing at least 9 positions before its original one, and can be shifted to the right infinitely. [Answer] # SmileBASIC, ~~61~~ 58 bytes ``` @L B$=B$+R()IF I>8THEN R=RND(9)?B$[R];:B$[R]=" I=I+1GOTO@L ``` Each character of the infinite list is added to the end of the buffer. When the buffer length is 11, a random character is printed and removed. Function `R` generates the next character. [Answer] # Prolog, 70 bytes ``` s(L):-get0(C),(length(L,9)->random_select(H,L,R),put(H);L=R),s([C|R]). ``` ]
[Question] [ In 2015 [the Portland International Airport](https://en.wikipedia.org/wiki/Portland_International_Airport) began the replacement of [their iconic carpet](https://en.wikipedia.org/wiki/Portland_International_Airport_carpet). I want you to write a program to draw their old carpet in as few bytes as possible. The carpet: [![One tile](https://i.stack.imgur.com/SaxOD.png)](https://i.stack.imgur.com/SaxOD.png) ### Specifications * [Here](https://drive.google.com/file/d/0B5byekx04qAMTzM5d2R6RDY4dTQ/view?usp=sharing) is a link to a scalable pdf image of one tile. Your output should match the relative dimensions and placement of that image. * All colors in your final image should be within 15 of every RGB value in the specified image. These are listed below for your convenience. ``` Red Green Blue Teal: 0, 168, 142 Magenta: 168, 108, 185 Orange: 247, 58, 58 Light Blue: 90, 166, 216 Dark Blue: 0, 77, 117 ``` * Your output must be at least 150x150 pixels and should be square. If you choose to output in a scalable format like a vector image you should match the image exactly. * You may output the image in any preexisting image format. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so you should aim to minimize the number of bytes in your code. [Answer] # Tikz, ~~725~~ ~~693~~ ~~681~~ 671 bytes > > Some significant improvements can be made to this answer. If you would like to make major golfs then you should post your own answer with your modified version. For minor improvements that I just missed, and don't require large explanation, feel free to comment them. I would like to reward major improvements, and I will definitely upvote any answer that beats this. > > > --- ``` \documentclass{standalone}\usepackage{xcolor,tikz}\begin{document}\tikz[line width=20,every node/.style={minimum size=20}]{\definecolor{t}{RGB}{0,168,142}\definecolor{m}{RGB}{168,99,185}\definecolor{o}{RGB}{247,58,58}\definecolor{b}{RGB}{90,166,216}\definecolor{d}{RGB}{40,77,117}\fill[t](-7.5,-7.5)rectangle(7.5,7.5);\draw(-1,0)node[fill=o]{};\foreach\x in{1,...,7}{\draw(-\x,-1)node[fill=m]{};\draw(0,\x)node[fill=b]{};}\foreach\x in{1,...,3}{\draw(\x,\x)node[fill=d]{};\draw(3+\x,-3-\x)node[fill=d]{};\draw(-3-\x,3+\x)node[fill=d]{};\draw(4+\x,1)node[fill=o]{};}\draw[d](.65,0)--(7.35,0);\draw[d,dash pattern=on20off8.5on162.5off8.5](0,-7.35)--(0,3.35);}\end{document} ``` [Try it Online!](https://www.sharelatex.com/project/589fc7f90fc1f31f144f998e) ## Explanation A good deal of the code is a wrapper: ``` \documentclass{standalone}\usepackage{xcolor,tikz}\begin{document}\tikz{...}\end{document} ``` This is a slight variation on the standard Tikz wrapper in that it also has the line `\usepackage{xcolor}` so that we can create the colors properly. The first thing that is done is `line width=20,every node/.style={minimum size=20}]` which sets the lines and nodes to be the proper size. Once that is done we define the colors we will be using for the various parts of the image: ``` \definecolor{t}{RGB}{0,168,142}\definecolor{m}{RGB}{168,99,185}\definecolor{o}{RGB}{247,58,58}\definecolor{b}{RGB}{90,166,216}\definecolor{d}{RGB}{40,77,117} ``` Now that everything is set up we paint the background to our canvas teal: ``` \fill[t](-7.5,-7.5)rectangle(7.5,7.5); ``` *(I wont include an image of this because it is just a teal square, but I will be including images of each other step)* The first node we add is the orange node just left of the center of the canvas. ``` \draw(-1,0)node[fill=o]{}; ``` [![An Orange at Sea](https://i.stack.imgur.com/nJ2J7.png)](https://i.stack.imgur.com/nJ2J7.png) Now we will draw the light blue and magenta nodes. There are 7 blue nodes and 4 blue nodes, but we can draw extra nodes that will be covered up by lines later on so we will draw 7 of each. ``` \foreach\x in{1,...,7}{ \draw(-\x,-1)node[fill=m]{}; \draw(0,\x)node[fill=b]{}; } ``` [![Forked Paths](https://i.stack.imgur.com/cqSo0.png)](https://i.stack.imgur.com/cqSo0.png) Now we will draw all the groups of 3 dots using a single `\foreach` loop ``` \foreach\x in{1,...,3}{\draw(\x,\x)node[fill=d]{};\draw(3+\x,-3-\x)node[fill=d]{};\draw(-3-\x,3+\x)node[fill=d]{};\draw(4+\x,1)node[fill=o]{};} ``` [![Scattered dots](https://i.stack.imgur.com/a8omV.png)](https://i.stack.imgur.com/a8omV.png) Now we draw the right line. This line will be a simple line with offsets of `.35` in each direction to match the size of a node. ``` \draw[d](.65,0)--(7.35,0); ``` [![Collision](https://i.stack.imgur.com/mfdD3.png)](https://i.stack.imgur.com/mfdD3.png) Now we must draw in the dark blue lines and squares on the x-axis. We will draw them with one line using a custom dash pattern. This pattern is `[dash pattern=on20off8.5on162.5off8.5]` This creates a square with a long solid tail. Our line will start from the bottom and will not quite cover 2 cycles of the pattern. ``` \draw[d,dash pattern=on20off8.5on162.5off8.5](0,-7.35)--(0,3.35); ``` [![Final](https://i.stack.imgur.com/4FCBT.png)](https://i.stack.imgur.com/4FCBT.png) And now we are done. [Answer] ## Pure HTML, 873 bytes ``` <table width=152 height=152 bgcolor=#0a8><tr><td colspan=7><td bgcolor=#5AD><tr><td><td bgcolor=#057><td colspan=5><td bgcolor=#5AD><tr><td><td><td bgcolor=#057><td colspan=4><td bgcolor=#5AD><tr><td><td><td><td bgcolor=#057><td><td><td><td bgcolor=#5AD><tr><td colspan=7><td bgcolor=#057><td><td><td bgcolor=#057><tr><td colspan=7><td bgcolor=#057><td><td bgcolor=#057><tr><td colspan=7><td bgcolor=#057><td bgcolor=#057><td><td><td><td bgcolor=#F33><td bgcolor=#F33><td bgcolor=#F33><tr><td colspan=6><td bgcolor=#F33><td bgcolor=#057><td colspan=7 bgcolor=#057><tr><td bgcolor=#A6B><td bgcolor=#A6B><td bgcolor=#A6B><td bgcolor=#A6B><td bgcolor=#A6B><td bgcolor=#A6B><td bgcolor=#A6B><td rowspan=6 bgcolor=#057><tr><td><tr><td><tr><td colspan=11><td bgcolor=#057><tr><td colspan=12><td bgcolor=#057><tr><td colspan=13><td bgcolor=#057><tr><td colspan=7><td bgcolor=#057> ``` ## HTML + CSS, 625 bytes ``` #l{background:#5AD}th{background:#057}#o{background:#F33}#m>td{background:#A6B ``` ``` <table width=152 height=152 bgcolor=#0A8><tr><td colspan=7><td id=l><tr><td><th><td colspan=5><td id=l><tr><td><td><th><td colspan=4><td id=l><tr><td><td><td><th><td><td><td><td id=l><tr><td colspan=7><th><td><td><th><tr><td colspan=7><th><td><th><tr><td colspan=7><th><th><td><td><td><td bgcolor=#F33><td bgcolor=#F33><td bgcolor=#F33><tr><td colspan=6><td bgcolor=#F33><th><th colspan=7><tr id=m><td><td><td><td><td><td><td><th rowspan=6><tr><td><tr><td><tr><td colspan=11><th><tr><td colspan=12><th><tr><td colspan=13><th><tr><td colspan=7><th> ``` [Answer] # literal PNG file, ~~283~~, ~~234~~ 227 bytes **EDIT**: Using online image compression service <https://compress-or-die.com/>, this went down another 7 bytes. ``` albn@alexhij:~/tmp$ ls -l carpet3.png -rw-r--r-- 1 albn albn 227 15. Feb 12:01 carpet3.png albn@alexhij:~/tmp$ base64 carpet3.png iVBORw0KGgoAAAANSUhEUgAAAJgAAACYBAMAAADq7D0SAAAAD1BMVEUAqI4ATXWobLn3Ojpapthl S7nNAAAAj0lEQVR4Ae3ThRHCQBQGYVqgBVq4Fui/Jt4ILks8/80uLvkyOTlkd67EILHojtWEyxQT Sw6uFS5TTCw/uFa+TDGx/PjS3z+KiS2GcRtgzIqJdboDPomteniCxMTyatXtMiExMcB22amCJ7wG MbHpBWBiYmJiYmJwAjGx/ncAn0VMrP8dwL+KieXHFyImltoF6oWZiblRTNQAAAAASUVORK5CYII= ``` [![carpet3.png](https://i.stack.imgur.com/HwCYD.png)](https://i.stack.imgur.com/HwCYD.png) The 227 bytes are the actual size of the binary file carpet.png. When encoded in base64, as displayed in the quoted block above, it is a few bytes longer (308 bytes). Encapsulating that in an html snippet that renders the image rightaway will add another few bytes: # HTML, ~~414~~, ~~343~~, 336 bytes ``` <img src=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAJgAAACYBAMAAADq7D0SAAAAD1BMVEUAqI4ATXWobLn3OjpapthlS7nNAAAAj0lEQVR4Ae3ThRHCQBQGYVqgBVq4Fui/Jt4ILks8/80uLvkyOTlkd67EILHojtWEyxQTSw6uFS5TTCw/uFa+TDGx/PjS3z+KiS2GcRtgzIqJdboDPomteniCxMTyatXtMiExMcB22amCJ7wGMbHpBWBiYmJiYmJwAjGx/ncAn0VMrP8dwL+KieXHFyImltoF6oWZiblRTNQAAAAASUVORK5CYII ``` **Edit**: I removed the quotes and closing > as Shaggy suggested. Also compressed the image down another ~~17~~, 24 bytes [Answer] # Mathematica, 285 bytes ``` e={1,1};r=RGBColor["#"<>#]&;c=Cuboid;s=c[3#-e,3#+e]&;a=Array;b=a[s[{1,-1}#]&,3,#]&;Graphics@{r@"0a8",c[-23e,23e],r@"a6b",a[s@{-#,-1}&,7],r@"f33",a[s@{#,1}&,3,5],s@{-1,0},r@"5ad",a[s@{0,#}&,4,4],r@"057",a[s[e#]&,4,0],b@4,b[-6],s@{0,-7},{-1,2}~c~{1,10},{-1,-2}~c~{1,-19},{2,-1}~c~{22,1}} ``` Easier to read: ``` 1 c = Cuboid; e = {1, 1}; 2 s = c[3 # - e, 3 # + e] &; 3 a = Array; b = a[s[{1, -1} #] &, 3, #] &; 4 r = RGBColor["#" <> #] &; 5 Graphics@{ 6 r@"0a8", c[-23 e, 23 e], 7 r@"a6b", a[s@{-#, -1} &, 7], 8 r@"f33", a[s@{#, 1} &, 3, 5], s@{-1, 0}, 9 r@"5ad", a[s@{0, #} &, 4, 4], 10 r@"057", 11 a[s[e #] &, 4, 0], b@4, b[-6], s@{0, -7}, 12 {-1, 2}~c~{1, 10}, {-1, -2}~c~{1, -19}, {2, -1}~c~{22, 1} 13 } ``` Lines 1–3 define short names for functions, the most important of which is `s` which draws a square centered at the coordinates it receives (really 3 times its coordinates, for appropriate scaling). Line 4 defines a color function using Mathematica's "shortcut" RGB system: `RGBColor["#xyz"]`, where `xyz` are hexadecimal digits, stands for `RGBColor[{17x, 17y, 17z}]` (so that each coordinate has 16 equally spaced options running from 0 to 255). The first commands on lines 6–10 switch the current color, using the shortcut colors that are closest to the designated five colors (no value is off by more than 8 when we round to the nearest multiple of 17). Line 6 draws the large teal square. Line 7 draws the line of magenta squares, Line 8 draws the line of orange squares and the single orange square. Line 9 draws the line of light blue squares. Line 11 draws the three diagonal lines of dark blue squares, as well as the single dark blue square at the bottom. Finally, line 12 draws the three long dark blue rectangles. The output is below: [![Portland](https://i.stack.imgur.com/MhbIw.png)](https://i.stack.imgur.com/MhbIw.png) (Golf tip: the command `Cuboid`, which is intended for 3d graphics objects, works just fine in 2d and is shorter than `Rectangle`.) [Answer] # TikZ, ~~671>439>432>377>334~~>311 (282) bytes > > My original answer started from the code that [Ad Hoc Garf Hunter](https://codegolf.stackexchange.com/users/56656/ad-hoc-garf-hunter) provided above, cf. [Tikz, 671 bytes](https://codegolf.stackexchange.com/a/109796/95500). > > I took this code and my knowledge about general LaTeX to make some improvements to the length of it, saving a bit more than 1 out of every 3 bytes. > > However, two years later, I returned to this problem and gave it another try by starting from scratch. > > > --- Here's my all new, personal solution. Note that the solution uses non-printable single-byte characters. In the depiction of this solution, they are replaced by circled characters. The circled characters can be mapped by `0x(circled character)` with the help of an ASCII table. ``` \documentclass[tikz]{standalone}\begin{document}\tikz{\let~\def~Ⓒ{;\color[HTML]}~④{)rectangle++(.7}~Ⓕ{\fill(}~~#1#2{Ⓕ0x#1,0x#2④,.7);}Ⓒ{00a88e}Ⓕ.85,.85④+14.3,15)Ⓒ{004d75}~2E~3D~4C~BB~AA~99~88~C4~D3~E2~81Ⓕ8,2④,5.7)(8,9④,2.7)(9,8④+6,.7)Ⓒ{5aa6d8}~8F~8E~8D~8CⒸ{f73a3a}~D9~E9~F9~78Ⓒ{a86cb9}~17~27~37~47~57~67~77}\stop ``` [Try it Online!](https://www.overleaf.com/read/xmfkmmzqrjyv) ## Output [![TikZ](https://i.stack.imgur.com/AAZZN.png)](https://i.stack.imgur.com/AAZZN.png) ## Explanation Here's a more readable version of my personal new solution. ``` 01: \documentclass[tikz]{standalone}\begin{document}\tikz{ 02: \let~\def~Ⓒ{;\color[HTML]}~④{)rectangle++(.7}~Ⓕ{\fill(} 03: ~~#1#2{Ⓕ0x#1,0x#2④,.7);} 04: Ⓒ{00a88e}Ⓕ.85,.85④+14.3,15) 05: Ⓒ{004d75}~2E~3D~4C~BB~AA~99~88~C4~D3~E2~81 06: Ⓕ8,2④,5.7)(8,9④,2.7)(9,8④+6,.7) 07: Ⓒ{5aa6d8}~8F~8E~8D~8C 08: Ⓒ{f73a3a}~D9~E9~F9~78 09: Ⓒ{a86cb9}~17~27~37~47~57~67~77 10: }\stop ``` Let's start with the wrapper in lines 1 and 10. This is basically the standard TikZ-wrapper. In line 2, we assign a shorthand (`~`) to the command `\def` within the TikZ-scope. Note that the only available printable single-character command `~` (catcode=13) is now defined as a command within the `\tikz{}` scope. This helps us to define even more shorthands in a very compact way. We then assign a shorthand to `\color` that allows us to change the color that we use for `\fill`-commands later on. As we have five colors in total, we will use the command `Ⓒ` five times. Note that `Ⓒ` for `\color` is a mnemonic declaration. We assign a shorthand to a string that will be used quite a lot to draw rectangles. `④` for rectangle (with four sides) is a mnemonic assignment as well. It contains the closing bracket for the first and the opening bracket for the second coordinate as well as the most common value for the x-value of the second coordinate. In the end of the line, we define a shorthand for the `\fill` command. The assignment is again mnemonic: `Ⓕ`. Note that all of the three assignments to "circled characters" are really assignments to non-printable single-byte control characters (0xY, Y standing for the corresponding circled character, being interpreted as ASCII hex value). These characters are all active (catcode=13) characters. All those assignments are displayed as mid-dots in the "Try It Online"-version at Overleaf. This renders an actually sort of "unreadable" (but completely working!) code view that can be ameliorated if you just copy the code to another editor, e.g. [here.](https://zis.de/carpet) In line 3, we continue to redefine `~` and, from now on, use this command to draw little squares. We benefit from the fact that the whole tile can be divided in 15 by 15 squares which is less than 16 by 16. Therefore, we can use hexadecimal one-digit numbers to refer to a unique square with only two characters. In lines 4 and 6, we draw a huge square in teal and some rectangles, more exactly: all those not being square, in dark blue. We don't need to pick the color dark blue, since this happens in line 5, see below. Lines 5, 7, 8, and 9 draw all the squares in four different colors. As we pick dark blue as our color for the squares in line 5, we can keep it for the rectangles, see above. Thus, we only have to use the `Ⓒ`-command five times. ## We can make it even shorter! If you visited the "Try It Online"-link, you might have found a "hacky" version with 29 bytes less. This version produces the same output. However, it throws errors and has a white border. Therefore, the "hacky" version is non-competing. It differs from the version described above by two things: (A) We don't use `\begin{document}`. This produces errors, but we obtain an output nevertheless. We can save 16 bytes. (B) In the "hacky" definition of the final version of `~`, `~` calls itself. This helps us to save a lot of `~` characters in lines 6, 7, 8, and 9 (10+3+3+6 = 22, to be exact). However, we will have to introduce the `~` character in line 3 and one pair of curly braces for each of the lines 6, 7, 8, and 9 to make this work, leaving us with a difference of 13 bytes. ## Comments regarding [Ad Hoc Garf Hunter's](https://codegolf.stackexchange.com/users/56656/ad-hoc-garf-hunter) solution I did not like the fact that I didn't fully understand the dash pattern that the other solution is using. Also, I tried to avoid nodes and lines by concentrating on rectangles. Furthermore, I believe in the metric system. Thus, I refrained from using other units than mm or cm. ;-) I believe that my second approach is much cleaner now. ## Improvements Please feel free to comment and help me save more bytes. # Literal PNG file, 223 bytes I've created this PNG file from my TikZ output. [![PNG](https://i.stack.imgur.com/B74c5.png)](https://i.stack.imgur.com/B74c5.png) [Answer] # Python, 420 ``` from PIL import Image,ImageDraw B=0,77,117 I=Image.new('RGB',(300,300),(0,168,142)) r=ImageDraw.Draw(I).rectangle for x,y,c in['7172737a98cde670123456bcd70112233456666778888888bcde23232323331111300000003333'[x::26]for x in range(26)]:exec'r([W,W,14+W,14+W],[(168,108,185),(247,58,58),(90,166,216),B][%s]);'.replace('W','2+20*0x%s')%(x,y,x,y,c) r([162,142,296,156],B) r([142,82,156,136],B) r([142,162,156,276],B) I.show() ``` [Answer] # T-SQL, 680 bytes ``` CREATE TABLE g(c INT,s geometry) INSERT g SELECT c,geometry::Point(x,y,0).STBuffer(.4) FROM(VALUES(1,7,8),(1,13,9),(1,14,9),(1,15,9),(2,2,14),(2,3,13),(2,4,12) ,(2,8,8),(2,9,9),(2,10,10),(2,11,11),(2,8,1),(2,12,4),(2,13,3),(2,14,2) ,(3,1,7),(3,2,7),(3,3,7),(3,4,7),(3,5,7),(3,6,7),(3,7,7) ,(35,8,12),(35,8,13),(35,8,14),(35,8,15))a(c,x,y) INSERT g SELECT c,geometry::STLineFromText('LINESTRING('+v+')',0).STBuffer(.4) FROM(VALUES(0,'.8 .8,15.2 15.2'),(2,'8 2,8 7'),(2,'8 9,8 11'),(2,'9 8,15 8'))a(c,v); WITH t AS(SELECT 4n UNION ALL SELECT n+1FROM t WHERE n<34) INSERT g SELECT n,geometry::Point(1,1,0).STBuffer(.01)FROM t; SELECT c,geometry::UnionAggregate(s.STEnvelope())FROM g GROUP BY c ``` * Line breaks added for readability. * Make sure to `DROP TABLE g` after you run it, I didn't include that in the byte total. * Uses [geospatial features supported in SQL 2008 and higher](https://docs.microsoft.com/en-us/sql/relational-databases/spatial/spatial-data-sql-server?view=sql-server-2017). So, this doesn't *entirely* satisfy the color requirement, but as I explain below, that's not fully under my control. Let's call this the *faded carpet* version. Formatted/commented code and output: [![enter image description here](https://i.stack.imgur.com/b0te1.png)](https://i.stack.imgur.com/b0te1.png) Notes: * The points (and lines) in the table are expanded into a circle with `STBuffer`, then squared off with `STEnvelope`. * The SQL spatial results pane has a [fixed color palette](https://alastaira.wordpress.com/2011/03/31/more-drawing-fun-with-sql-server/), so I am limited in what colors I can display (no bright red, etc) * To get the colors I want, I have to select them *in the correct order*. Column *c* in my table defines the grouping order; the large teal square is group 0, the 4 blue squares are group 35. * To get *multiple* objects of the same color, I have to *combine them into a single object*, that's the purpose of the `UnionAggregate()` function at the end. * To "skip ahead" through the color palette to get to the light blue, I have to insert 31 dummy objects that are big enough to get assigned a color, but small enough not to show. To see more strange uses of SQL spatial features, see [draw the biohazard symbol](https://codegolf.stackexchange.com/a/191323/70172) and [draw the Easter Bunny](https://codegolf.stackexchange.com/a/184653/70172). [Answer] # HTML/SVG, ~~550~~ ~~542~~ 521 bytes ``` <svg><path fill=#0a8 d="M0 0h152v152H0z"/><path fill=#5ad d="M72 2h8v8h-8zm0 10h8v8h-8zm0 10h8v8h-8zm0 10h8v8h-8z"/><path fill=#057 d="M12 12h8v8h-8zm10 10h8v8h-8zm10 10h8v8h-8zm40 10h8v28h-8zm0 30h8v8h-8zm10-10h8v8h-8zm10-10h8v8h-8zm10-10h8v8h-8zM82 72h68v8H82zM72 82h8v58h-8zm0 60h8v8h-8zm40-30h8v8h-8zm10 10h8v8h-8zm10 10h8v8h-8z"/><path fill=#f33 d="M62 72h8v8h-8zm60-10h8v8h-8zm10 0h8v8h-8zm10 0h8v8h-8z"/><path fill=#a6b d="M2 82h8v8H2zm10 0h8v8h-8zm10 0h8v8h-8zm10 0h8v8h-8zm10 0h8v8h-8zm10 0h8v8h-8zm10 0h8v8h-8z" ``` [Answer] # HTML, 366 bytes [Sunday](https://codegolf.stackexchange.com/users/61199/sunday) got a Base64 [answer](https://codegolf.stackexchange.com/a/117693/58974) up while I was still working on this; if s/he chooses to use it then I'll delete this answer. ``` <img src=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAJgAAACYBAMAAADq7D0SAAAAD1BMVEUAqI4ATXWobLlaptj3OjrqGXAuAAAAp0lEQVRo3u3YQQqFMAxFUbeQLbiFbsH9r8k3y8CmTiKm7b2Dwv/CgUAD4jF3TYGBRdgKmRqPCQa28gaMZ20KDGz5DQhnbQoMTG2wAcPR/ScY2HeYVw4zBQYWYDUvbRLWFS/lBxhYhM3bpXzMcWBgEVa5U70cpsDAnkf1FxcwMDAwMLBczP8DAwuwmpc2HzMFBhY8qHlp8zFTYGCdyn8GKrhOYBtjv3QDvf+Zic+8bOsAAAAASUVORK5CYII ``` If the Base64 string on it's own is a valid answer then that's just 335 bytes: ``` iVBORw0KGgoAAAANSUhEUgAAAJgAAACYBAMAAADq7D0SAAAAD1BMVEUAqI4ATXWobLlaptj3OjrqGXAuAAAAp0lEQVRo3u3YQQqFMAxFUbeQLbiFbsH9r8k3y8CmTiKm7b2Dwv/CgUAD4jF3TYGBRdgKmRqPCQa28gaMZ20KDGz5DQhnbQoMTG2wAcPR/ScY2HeYVw4zBQYWYDUvbRLWFS/lBxhYhM3bpXzMcWBgEVa5U70cpsDAnkf1FxcwMDAwMLBczP8DAwuwmpc2HzMFBhY8qHlp8zFTYGCdyn8GKrhOYBtjv3QDvf+Zic+8bOsAAAAASUVORK5CYII ``` [Answer] # HTML/SVG + JavaScript (ES6), ~~500~~ 499 bytes An extra `>` is required in order for this to function as a Snippet, see [this Fiddle](https://jsfiddle.net/petershaggynoble/5sj6hpox/) for actual code. ``` [[t="5ad",2],[t,o=12],[t,p=22],[t,q=32],[,o,o],[,p,p],[,q,q],[,42,,28],[],[,v=62,s=82],[,52,92],[,42,102],[,,s,,68],[,s,,58],[,142],[,112,112],[,122,122],[,132,132],[t="f33",,v],[t,v,122],[t,v,132],[t,v,142],[t="a6b",s,2],[t,s,o],[t,s,p],[t,s,q],[t,s,42],[t,s,52],[t,s,v],["0a8",0,0,152,152]].map(x=>a(x[0],x[1],x[2],x[3],x[4]),a=(f="057",y=72,x=72,h=8,w=8)=>(c.after(r=c.cloneNode()),r.id++,r[s="setAttribute"]("fill","#"+f),r[s]("x",x),r[s]("y",y),r[s]("width",w),r[s]("height",h))) ``` ``` <svg><rect id=c> ``` --- ## Explanation An array of arrays is mapped to function `a`, creating clones of the `rect` in the HTML, inserting them after the initial `rect` and setting their `fill`, `x`, `y`, `width` & `height` attributes. Each array contains values for those attributes, in that order, with any missing values being set by the default parameters of `a`. The seemingly unnecessary `r.id++` allows the use of `cloneNode()` while ensuring there is only ever 1 `rect` with an `id` of c; this saves the need to use the ridiculously expensive `document.createElementNS("http://www.w3.org/2000/svg","rect")`. [Answer] # PHP+SVG, 425 Bytes ``` <svg><rect x=0 y=0 fill=#00a88e width=150 height=150 /><?foreach(["004d75"=>[[1,1],[2,2],[3,3],[7,14],[7,7],[8,6],[9,5],[10,4],[11,11],[12,12],[13,13],[7,4,0,2],[8,7,6,0],[7,8,0,5]],"5aa6d8"=>[[7,0],[7,1],[7,2],[7,3]],a86cb9=>[[0,8],[1,8],[2,8],[3,8],[4,8],[5,8],[6,8]],f73a3a=>[[6,7],[12,6],[13,6],[14,6]]]as$c=>$p)foreach($p as$v)echo"<rect x={$v[0]}1 y={$v[1]}1 width=".(8+10*$v[2])." height=".(8+10*$v[3])." fill=#$c />"; ``` expanded ``` <svg><rect x=0 y=0 fill=#00a88e width=150 height=150 /> <?foreach([ "004d75"=>[[1,1],[2,2],[3,3],[7,14],[7,7],[8,6],[9,5],[10,4],[11,11],[12,12],[13,13],[7,4,0,2],[8,7,6,0],[7,8,0,5]] ,"5aa6d8"=>[[7,0],[7,1],[7,2],[7,3]] ,a86cb9=>[[0,8],[1,8],[2,8],[3,8],[4,8],[5,8],[6,8]] ,f73a3a=>[[6,7],[12,6],[13,6],[14,6]] # Array containing color and position ,width, height of each rect without the background ]as$c=>$p) foreach($p as$v) echo"<rect x={$v[0]}1 y={$v[1]}1 width=".(8+10*$v[2])." height=".(8+10*$v[3])." fill=#$c />"; # Output the rects ``` The result of the code in a HTML snippet ``` <svg><rect x=0 y=0 fill=#00a88e width=150 height=150 /><rect x=11 y=11 width=8 height=8 fill=#004d75 /><rect x=21 y=21 width=8 height=8 fill=#004d75 /><rect x=31 y=31 width=8 height=8 fill=#004d75 /><rect x=71 y=141 width=8 height=8 fill=#004d75 /><rect x=71 y=71 width=8 height=8 fill=#004d75 /><rect x=81 y=61 width=8 height=8 fill=#004d75 /><rect x=91 y=51 width=8 height=8 fill=#004d75 /><rect x=101 y=41 width=8 height=8 fill=#004d75 /><rect x=111 y=111 width=8 height=8 fill=#004d75 /><rect x=121 y=121 width=8 height=8 fill=#004d75 /><rect x=131 y=131 width=8 height=8 fill=#004d75 /><rect x=71 y=41 width=8 height=28 fill=#004d75 /><rect x=81 y=71 width=68 height=8 fill=#004d75 /><rect x=71 y=81 width=8 height=58 fill=#004d75 /><rect x=71 y=01 width=8 height=8 fill=#5aa6d8 /><rect x=71 y=11 width=8 height=8 fill=#5aa6d8 /><rect x=71 y=21 width=8 height=8 fill=#5aa6d8 /><rect x=71 y=31 width=8 height=8 fill=#5aa6d8 /><rect x=01 y=81 width=8 height=8 fill=#a86cb9 /><rect x=11 y=81 width=8 height=8 fill=#a86cb9 /><rect x=21 y=81 width=8 height=8 fill=#a86cb9 /><rect x=31 y=81 width=8 height=8 fill=#a86cb9 /><rect x=41 y=81 width=8 height=8 fill=#a86cb9 /><rect x=51 y=81 width=8 height=8 fill=#a86cb9 /><rect x=61 y=81 width=8 height=8 fill=#a86cb9 /><rect x=61 y=71 width=8 height=8 fill=#f73a3a /><rect x=121 y=61 width=8 height=8 fill=#f73a3a /><rect x=131 y=61 width=8 height=8 fill=#f73a3a /><rect x=141 y=61 width=8 height=8 fill=#f73a3a /> ``` PHP+SVG, 375 Bytes This Byte count can be reach with compressing the SVG ``` <?=bzdecompress(base64_decode("QlpoNDFBWSZTWY2177gAASSZgEgA/+c/5B3gMAE5TQVtQeig0AAACU0VNMAAAEYIlEnpMKNlGahso2plh0zoaSEpIkukINaC3RWRF74IvArdRF1FcBXrSTFWXTorp2xvpb3k7FbaV62syISgiBEweHhxtWUmgWCsqqaKSEARyAOAEZJJOwYBQqTAWotSrmEXJbBRTYNhCg4RPaKOUUbAX+Fr4VfIrzzIQQkkJCWfMEEOOISTuDkOzgQzDQDNQKu/4K7AZh8L41DddV8iv2LQOBXv+iugriHAr6sK/IrUV1FeRXMV3FdhW8V9KugrmK8CvOQin+LuSKcKEhG2vfcA")); ``` [Answer] ## **HTML + Javascript(jQuery)** : 474(js)+ 22(HTML) => 496bytes ``` a=$("table"),a.append("<tr>".repeat(15)),$("tr").append("<td width='15' height='15'>".repeat(15)),o={g:"#0a8",b:"#057",c:"#5AD",r:"#F33",p:"#A6B"},z="14g,b,",s="7g,c,8g,b,5g,c,9g,b,4g,c,10g,b,3g,c,"+z+"2g,b,11g,b,g,b,12g,2b,3g,3r,6g,r,8b,7p,b,"+z+z+z+"3g,b,10g,b,4g,b,9g,b,5g,b,8g,b",m="",t=s.split(",");for(var i=0;i<t.length;i++)m+=t[i].length>1?t[i].charAt(1).repeat(t[i].match(/(\d+)/g)):t[i].charAt(0);for(i=0;i<225;i++)$("td:eq("+i+")").attr("bgcolor",o[m.charAt(i)]); ``` ``` <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <table bgcolor='#0A8'> ``` [Answer] # HTML + Javascript, 378 bytes ``` document.write`<canvas id=Y>` c=Y.getContext`2d` N=(w,o)=>[...w].map(d=>Number('0x'+d)*10+o) S=f=>c.fillStyle='#'+f T=(z,p,s)=>c.fillRect(...N(p,1),...N(s,8)) S('0a8');c.fillRect(0,0,150,150) U=(f,s)=>{S(f);s.replace(/../g,w=>T(0,w,'00'))} U('a6b','08182838485868') U('f33','67c6d6e6') U('5ad','70717273') U('057','112233bbccdd778695a47e') '740278058760'.replace(/(..)(..)/g,T) ``` ### Explanation ``` document.write`<canvas id=Y>` // draw a canvas element c=Y.getContext`2d` // Canvas2DContext N=(w,o)=>[...w].map(d=>Number('0x'+d)*10+o) // take a string, interpret each letter // as a hex number and add an offset S=f=>c.fillStyle='#'+f // set global fill color T=(z,p,s)=>c.fillRect(...N(p,1),...N(s,8)) // fill a rect // each x and y is (hex digit)*10 + 1, // each w and h is (hex digit)*10 + 8 S('0a8');c.fillRect(0,0,150,150) // draw background U=(f,s)=>{S(f);s.replace(/../g,w=>T(0,w,'00'))} // draw 8x8 squares U('a6b','08182838485868') // magenta squares, each represented // as two digits in the string U('f33','67c6d6e6') // orange squares U('5ad','70717273') // light blue squares U('057','112233bbccdd778695a47e') // dark blue squares '740278058760'.replace(/(..)(..)/g,T) // dark blue rects, each represented // as four digits in the string ``` ]
[Question] [ > > Consider the number 99999999. That number is obviously a palindrome. The largest prime factor of 99999999 is 137. If you divide 99999999 by 137, you get 729927. This number is also a palindrome. > > > The largest prime factor of 729927 is 101. 729927/101=7227 which again is a palindrome. > > > The largest prime factor of 7227 is 73. 7227/73=99 which again is a palindrome. > > > By further dividing by the largest prime factor, you get 9, 3 and finally 1, which, being one-digit numbers, are also palindromes. Since 1 has no prime factors, the procedure ends here. > > > Now generalizing this observation, I define a super-palindrome as a palindrome which is either 1, or which gives another super-palindrome if divided by its largest prime factor. > > > Credits: <https://math.stackexchange.com/questions/200835/are-there-infinitely-many-super-palindromes> Given a number *N*, determine if it is a super palindrome or not, and print a truthy or falsey value accordingly. Your program should print a truthy value for these inputs: ``` 1 101 121 282 313 353 373 393 474 737 919 959 1331 1441 2882 6446 7887 8668 9559 9779 ``` Your program should print a falsey value for these inputs: ``` 323 432 555 583 585 646 642 696 777 969 989 2112 3553 4554 5242 5225 5445 8080 8118 9988 ``` Remember, this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the code with the shortest amount of bytes wins. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~13~~ ~~12~~ ~~9~~ 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Æf×\D⁼U$ ``` [Try it online!](http://jelly.tryitonline.net/#code=w4Zmw5dcROKBvFUk&input=&args=OTk5OTk5OTk) or [verify all test cases](http://jelly.tryitonline.net/#code=w4Zmw5dcROKBvFUkCsOH4oKs4oKsRw&input=&args=W1sxLDEwMSwxMjEsMjgyLDMxMywzNTMsMzczLDM5Myw0NzQsNzM3LDkxOSw5NTksMTMzMSwxNDQxLDI4ODIsNjQ0Niw3ODg3LDg2NjgsOTU1OSw5Nzc5XSwKWzMyMyw0MTQsNTU1LDU3NSw1ODUsNjQ2LDY4Niw2OTYsNzc3LDk2OSw5ODksMjExMiwzNTUzLDQ1NTQsNTAwNSw1MjI1LDU0NDUsODAwOCw4MTE4LDk4ODldLApd). ### How it works ``` Æf×\D⁼U$ Main link. Argument: n Æf Yield all prime factors of n, with multiplicities and in ascending order. ×\ Take the cumulative product. D Decimal; convert each product into the array of its base 10 digits. $ Combine the two links to the left into a monadic chain. U Upend; reverse all arrays of decimal digits. ⁼ Test for equality. ``` [Answer] # Mathematica, 64 bytes ``` And@@PalindromeQ/@FixedPointList[#/FactorInteger[#][[-1,1]]&,#]& ``` Unnamed function, returning `True` or `False`. Forms a list by starting at the input, then iterating the function "me divided by my largest prime factor" until the output doesn't change. (Fortunately, Mathematica now thinks the largest prime factor of 1 is 1.) Then tests whether the list entries are palindromes (yay built-ins! boo function name length!) and `And`s them all together. [Answer] # Mathematica, 51 bytes ``` #<2||PalindromeQ@#&&#0[#/FactorInteger[#][[-1,1]]]& ``` Recursive anonymous function. Takes a number as input and returns `True` or `False` as output. [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~9~~ 8 bytes Saved a byte thanks to *Adnan*. ``` Ò.pPDíïQ ``` [Try it online!](http://05ab1e.tryitonline.net/#code=w5IucFBEw63Dr1E&input=NzI5OTI3) **Explanation** `n = 7227` used as example ``` Ò # prime factors with duplicates # STACK: [3, 3, 11, 73] .p # prefixes # STACK: [[3], [3, 3], [3, 3, 11], [3, 3, 11, 73]] P # product # STACK: [3, 9, 99, 7227] D # duplicate # STACK: [3, 9, 99, 7227], [3, 9, 99, 7227] í # reverse each # STACK: [3, 9, 99, 7227], ['3', '9', '99', '7227'] ï # convert to int # STACK: [3, 9, 99, 7227], [3, 9, 99, 7227] Q # check for equality # STACK: 1 # implicit output ``` [Answer] # Pyth - ~~15~~ 12 bytes ~~Beat Jelly :P~~ :/ Unfortunately, all those implicit maps do not get shorter when combined into an explicit one since the last one is an auto-splat. ``` .A_IM`M*M._P ``` [Test Suite](http://pyth.herokuapp.com/?code=.A_IM%60M%2aM._P&test_suite=1&test_suite_input=1%0A101%0A121%0A282%0A313%0A353%0A373%0A393%0A474%0A737%0A919%0A959%0A1331%0A1441%0A2882%0A6446%0A7887%0A8668%0A9559%0A9779%0A323%0A414%0A555%0A575%0A585%0A646%0A686%0A696%0A777%0A969%0A989%0A2112%0A3553%0A4554%0A5005%0A5225%0A5445%0A8008%0A8118%0A9889&debug=0). Gets all the prefixes of the prime factorization, the products of which will be the intermediate super palindromes, and checks if all of them are palindromes. [Answer] # Mathematica, ~~71~~ 63 bytes ``` And@@PalindromeQ/@FoldList[1##&,Join@@Table@@@FactorInteger@#]& ``` # Explanation ``` FactorInteger@# ``` Factor the input. (e.g. `8668 -> {{2, 2}, {11, 1}, {197, 1}}`; for each list in the output, the first element is the prime factor, and the second one is the power. ``` Join@@Table@@ ... ``` For each factor-power pair, duplicate the first element by the second element, and flatten the entire thing. (`{{2, 2}, {11, 1}, {197, 1}} -> {{2, 2}, {11}, {197}} -> {2, 2, 11, 197}`) ``` FoldList[1##&, ... ] ``` Iterate through the list, multiplying the elements. (`{2, 2, 11, 197} -> {2, 2 * 2, 2 * 2 * 11, 2 * 2 * 11 * 197} -> {2, 4, 44, 8668}`) ``` And@@PalindromeQ/@ ... ``` Check whether all of the resulting numbers are palindromes, and apply the `And` operator. (`{2, 4, 44, 8668} -> {True, True, True, True}` -> `True`) [Answer] # [Brachylog](http://github.com/JCumin/Brachylog), 14 bytes ``` 1|r?$ph:?r/:0& ``` [Try it online!](http://brachylog.tryitonline.net/#code=MXxyPyRwaDo_ci86MCY&input=OTk5OTk5OTk) ### Explanation This implements the formula explained in the challenge description. Computing all products of suffixes of the prime factorization and checking that they are all palindromes is 1 byte longer (`1|$p:@]f:{*.r}a`). ``` 1 Input = 1 | OR r? Reversing the Input results in the Input $p Get the prime factors of the Input h Take the first one (the biggest) :?r/ Divide the Input by that prime factor :0& Call this predicate recursively with that new number as input ``` [Answer] ## Racket 238 bytes ``` (define(p n)(=(string->number(list->string(reverse(string->list(number->string n)))))n)) (if(= n 1)#t(begin(let o((n n))(define pd(prime-divisors n))(if(null? pd)#f(begin(let((m(/ n(last pd)))) (cond[(= m 1)#t][(p m)(o m)][else #f]))))))) ``` Ungolfed: ``` (define (f n) (define (palin? n) ; define palindrome of number (=(string->number (list->string (reverse (string->list (number->string n))))) n)) (if(= n 1)#t (begin (let loop ((n n)) (define pd (prime-divisors n)) ; find prime divisors (if (null? pd) #f ; end if none- not superpalindrome (begin (let ((m (/ n (last pd)))) ; divide by largest prime divisor (cond ; test quotient [(= m 1) #t] ; end if 1: super-palindrome found [(palin? m) (loop m)] ; loop with quotient if palindrome [else #f] ; end if not palindrome )))))))) ``` Testing: ``` (f 1) (f 101) (f 121) (f 282) (f 313) (f 353) (f 373) (f 393) (f 474) (f 737) (f 919) (f 959) (f 1331) (f 1441) (f 2882) (f 6446) (f 7887) (f 8668) (f 9559) (f 9779) (f 99999999) ``` Output: ``` #t #t #t #t #t #t #t #t #t #t #t #t #t #t #t #t #t #t #t #t #t ``` [Answer] # J, 30 bytes ``` 0:`(%1>.{:@q:)@.((-:|.)@":)^:_ ``` Error for falsey, 1 for truthy. Initial attempt, does not error for falsey, 40 bytes: ``` 0:`(([:$:]%{:@q:)`[@.(1&=))@.((-:|.)@":) ``` ## Explanation ``` 0:`(%1>.{:@q:)@.((-:|.)@":)^:_ ^:_ repeat until convergent @.((-:|.)@":) if the number is palindromic: ( ) do the stuff inside, which is a 4-train {:@q: largest prime factor 1>. (or 1, if smaller than 1) % divide the original number by this value 0:` otherwise, return 0 (because of ^:_, this will be passed into q:, which will error because 0 cannot be factored.) ``` ## Test cases ``` NB. collect errors; 0 if errored, otherwise the result of the function NB. left arg: values; right arg: boxed name of function errors =: 4 : 0 f =. y`:6 l =: '' for_e. x do. try. l =. l , f e catch. l =. l , 0 end. end. l ) s =: 0:`(%1>.{:@q:)@.((-:|.)@":)^:_ t =: 1 101 121 282 313 353 373 393 474 737 919 959 1331 1441 2882 6446 7887 8668 9559 9779 f =: 323 432 555 583 585 646 642 696 777 969 989 2112 3553 4554 5242 5225 5445 8080 8118 9988 t ,. f 1 323 101 432 121 555 282 583 313 585 353 646 373 642 393 696 474 777 737 969 919 989 959 2112 1331 3553 1441 4554 2882 5242 6446 5225 7887 5445 8668 8080 9559 8118 9779 9988 (t ,. f) errors"1 0 <'s' 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 ``` [Answer] # [아희(Aheui)](http://esolangs.org/wiki/Aheui), 309 bytes (100 chars \* 3 bytes + 9 newlines) ``` 방빩반룸있쁏멐솔쌀잌 앟놂숙참뿔썁썸뻙솝셜 본서번분번뮴딸냥별쀼 슉눇번낢퉅쑫썬쌀본묳 뽇서본석첫삭뽑롷떵춤 분촐럶사눙읽숟뗘분뻨 듐삭빶쏘윙잉썩손뵬괆 쌰뭉쇼텰궮변번첳웅텩 뽇흶아희쾯볻훼윺엄솝 코드골프욉쁍숙쌉삼쏩 ``` I'm so happy that I actually finished it! I'm new to this language, so any tip on improving byte count is welcome. [Try it here! (copy and paste the code)](http://jinoh.3owl.com/aheui/jsaheui_en.html) **Cleaner version** ``` 방빠반루ㅇ쀼머솔쌀이 아노숙차뿌썁썸뻐솝셜 본서번분번뮤따냐별쀼 슉누번나투쑫썬쌀본묘 뽀서본석처삭뽀로떠추 분초러사누이숟뗘분뻐 듀삭빠쏘ㅇ이썩손뵬ㅇ 쌰뭉쇼텨이변번처우텨 뽀희ㅇㅇㅇ볻ㅇ유어솝 ㅇㅇㅇㅇㅇㅇ숙쌉삼쏩 ``` [Answer] # [Husk](https://github.com/barbuz/Husk), ~~9~~ 7 bytes ``` ΛS=↔G*p ``` [Try it online!](https://tio.run/##yygtzv7//9zsYNtHbVPctQr@//9vCQUA "Husk – Try It Online") -2 bytes from Jo King. [Answer] # Scala, 138 bytes ``` def?(n:Int):Int={val p=Stream.from(2).filter(n%_==0)(0) if(p==n)n else?(n/p)} def s(i:Int):Boolean=i<2||(i+"")==(i+"").reverse&&s(i/ ?(i)) ``` Ungolfed: ``` def largestFactor(n:Int):Int={ val p=Stream.from(2).filter(n%_==0).head if(p==n)n else largestFactor(n/p)} def superPalindrome(i:Int):Boolean=i<2||(i+"")==(i+"").reverse&&superPalindrome(i/ largestFactor(i)) ``` Explanation: ``` def?(n:Int):Int={ //define a method for the largest prime factor val p=Stream.from(2).filter(n%_==0)(0) //find the first factor of n if(p==n)n else?(n/p) //if it's n, return n else the next factor } def s(i:Int):Boolean= //method for the superprime i<2 //if s<2 return true || //else return: (i+"")==(i+"").reverse //is i a palindrome && //and s(i/ ?(i)) //is i divided by it's largestPrimeFactor a superpalindrome ``` [Answer] ## JavaScript (ES6), 78 bytes ``` (n,d=2,p=1)=>n%d?n<2||f(n,d+1,p):[...p=p*d+''].reverse().join``==p&&f(n/d,d,p) ``` Recursively builds the prime factorisation prefixes and checks them for palindromicity. [Answer] # Java 7, 133 bytes ``` int c(int a){int x=a,y=0,z=a,i=2;for(;x>0;y=y*10+x%10,x/=10);for(;z>1;i++)for(;z%i<1;z/=i);if(a<2)return 1;return y!=a?0:c(a/(i-1));} ``` # Ungolfed ``` static int c( int a ){ int x = a , y = 0 , z = a , i = 2 ; for ( ; x > 0 ; y = y * 10 + x % 10 , x /= 10 ) ; for ( ; z > 1 ; i++ ) for ( ; z % i < 1 ; z /= i ) ; if ( a < 2 ) return 1 ; return y != a ? 0 : c( a / ( i - 1 ) ) ; } ``` [Answer] # [Actually](http://github.com/Mego/Seriously), 29 bytes There are probably several sections of this code that could be golfed, though I'm not sure where yet. Golfing suggestions welcome. [Try it online!](http://actually.tryitonline.net/#code=4pWXMWBY4pWcJDtSPTvilZ3ilZx5TuKVnFw74pWXMTwqYOKVrFjilZxEWeKVmyo&input=OTk5OTk5OTk) ``` ╗1`X╜$;R=;╝╜yN╜\;╗1<&`╬X╜DY╛& ``` **Ungolfing** ``` Implicit input n. ╗ Save n to register 0. 1`...`╬ Run the following function on the stack while TOS is truthy. X Discard the previous truthy. ╜ Push n from register 0. $ Push str(n). ;R= Check if str(n) == str(n)[::-1], i.e. if n is a palindrome. ;╝ Save a copy of (is n a palindrome?) to register 1. ╜yN Get the largest prime factor of n. ╜\ Divide n by its largest prime factor. ;╗ Save a copy of n // l_p_f to register 0. 1< Check if 1 < n // l_p_f. This returns 0 only if n // l_p_f is 1. & Logical AND (is n a palindrome?) and (is n // l_p_f > 1?). This quits if we have reached a non-palindrome or we have reached 1. X Discard the falsey that ended the previous function. ╜ Get the last value saved to register 0 (could be 1 or a non-palindrome // l_p_f) DY This returns 1 if register 0 was a 1, else 0. ╛& Logical AND with register 1 (was the last n a palindrome?) to get our result. Implicit return. ``` ]
[Question] [ Following [last year's event](https://codegolf.meta.stackexchange.com/q/24068/78410), we're doing [**Code Golf Advent Calendar 2022**](https://codegolf.meta.stackexchange.com/q/25251/78410)! On each day from today (Dec 1) until Christmas (Dec 25), a Christmas-themed challenge will be posted, just like an Advent calendar. It is a free-for-all and just-have-fun-by-participation event, no leaderboards and no prizes for solving them fast or solving them in the shortest code. More details can be found in the link above. --- I've got an infinite supply of two kinds of weirdly shaped chocolate: * White chocolate, a square pyramid of side lengths 1 * Dark chocolate, a regular tetrahedon of side lengths 1 To celebrate the upcoming Christmas, I want to assemble them into a giant chocolate pyramid. When the base of the pyramid is a rectangle of size \$R \times C\$, the process to build such a pyramid is as follows: 1. Fill the floor with \$RC\$ copies of White chocolate. 2. Fill the gaps between White chocolate with Dark chocolate. 3. Fill the holes between Dark chocolate with White chocolate. Now the top face is a rectangle of size \$(R-1) \times (C-1)\$. 4. Repeat 1-3 until the top face has the area of 0. The diagram below shows the process for \$2 \times 3\$. It takes 8 White and 7 Dark chocolate to complete the first floor, and 10 White and 8 Dark for the entire pyramid. ![](https://upload.acmicpc.net/84e118fc-f246-4388-9f46-958758d01da5/-/preview/) Given the width and height of the base rectangle, how many White and Dark chocolate do I need to form the chocolate pyramid? You may assume the width and height are positive integers. You may output two numbers in any order. Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins. ## Test cases ``` (width, height) -> (white, dark) (2, 3) -> (10, 8) (10, 10) -> (670, 660) (10, 1) -> (10, 9) ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 14 bytes ``` gʁ$vεƛΠε∑;:›"Ṡ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJnyoEkds61xpvOoM614oiROzrigLpcIuG5oCIsIiIsIls1LCAzXSJd) The main observation here is that the amount of white chocolate \$w\$ and dark chocolate \$d\$ in a layer of size (a, b) is: $$ w = ab +(a-1)(b-1) = 2ab - a - b + 1\\ d = (a-1)b+(b-1)a = 2ab - a - b $$ In other words, the difference between white chocolate and dark chocolate for a layer is 1 ``` ʁ # Range from 0 to... g # Minimum dimension of input $vε # Subtract each from the input, creating a list of pairs of bases ƛ ; # Over each base pair [a, b] Π # Product ab ε # Take the absolute difference - [ab - a, ab - b] ∑ # Sum :›" # Create an incremented pair for white Ṡ # Sum each into the final amounts ``` [Answer] # [Desmos](https://desmos.com/calculator), ~~47~~ ~~46~~ 37 bytes *-1 byte thanks to emanresu A* *-9 bytes (!!!) thanks to alephalpha* ``` N=min(h,w) f(w,h)=Nhw-N(NN+2)/3+[N,0] ``` \$f(w,h)\$ takes in the width \$w\$ and the height \$h\$ and returns a two-element list, with the number of white chocolates in the first element and the number of dark ones in the second element. [Try It On Desmos!](https://www.desmos.com/calculator/zda2no9d8a) Made my own closed form formula because I figured it would be fun :) For those who are really curious, here’s some of the scratch work for how I came up with this formula (warning: it’s completely unreadable :P): [Scratch work](https://www.desmos.com/calculator/cdquopfsrb) [Answer] # [PARI/GP](https://pari.math.u-bordeaux.fr), 41 bytes ``` f(r,c)=if(r*c,[t=r*c+r--*c--,t-1]+f(r,c)) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMGCpaUlaboWNzXTNIp0kjVtM4G0VrJOdIktkNIu0tXVStbV1SnRNYzVhqjQhGpwSywoyKnUSFTQtVMoKMrMKwEylUAcJYU0jcRow1gdhcRoo1hNTR2F6GgjHQVjoEC0oYGOgqEBnBUbCzUN5gwA) --- # [PARI/GP](https://pari.math.u-bordeaux.fr), 41 bytes ``` f(r,c)=m=min(r,c);[t=1+3*r*c-m^2,t-3]*m/3 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMGCpaUlaboWNzXTNIp0kjVtc21zM_PATOvoEltDbWOtIq1k3dw4I50SXeNYrVx9Y6gGt8SCgpxKjUQFXTuFgqLMvBIgUwnEUVJI00iMNozVUUiMNorV1NRRiI420lEwBgpEGxroKBgawFmxsZoQ02DOAAA) ``` f(r,c)=m=min(r,c);[t=r*c*m+m/3-m^3/3,t-m] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMGCpaUlaboWNzXTNIp0kjVtc21zM_PATOvoEtsirWStXO1cfWPd3DhjfWOdEt3cWKgGt8SCgpxKjUQFXTuFgqLMvBIgUwnEUVJI00iMNozVUUiMNorV1NRRiI420lEwBgpEGxroKBgawFmxsZoQ02DOAAA) Using the closed form formula. [Answer] # [R](https://www.r-project.org), ~~42~~ 39 bytes *Edit: -3 bytes thanks to [@Giuseppe](https://codegolf.stackexchange.com/users/67312/giuseppe).* ``` \(r,c)-c(0,m<-min(r,c))+r*c*m+m/3-m^3/3 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhY31WM0inSSNXWTNQx0cm10czPzwHxN7SKtZK1c7Vx9Y93cOGN9Y6jy0DQNIx0FY01lBV07BQ1DAx0FC02uNA1jHQUjdDEQw9AAKmpmDuSZmRnAJZBUW2pCDF-wAEIDAA) Port of [alephalpha's answer](https://codegolf.stackexchange.com/a/255044/58563). [Answer] # [Ruby](https://www.ruby-lang.org/), ~~41~~ 40 bytes -1 byte thanks to [Sisyphus](https://codegolf.stackexchange.com/users/48931/sisyphus) Based on [alephalpha’s PARI/GP answer](https://codegolf.stackexchange.com/a/255044/11261). ``` ->a{r,c=a.sort [t=r/3+c*r*r-r**3/3,t-r]} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsEiN9ulpSVpuhY3NXTtEquLdJJtE_WK84tKuKJLbIv0jbWTtYq0inSLtLSM9Y11SnSLYmuh6tUKFNyio410FIxjY7nAbEMDHQVDAxRebCxE9YIFEBoA) [Answer] # [C (GCC)](https://gcc.gnu.org), ~~76~~ ~~72~~ 70 bytes * -4 bytes thanks to Conor O'Brien * -2 bytes thanks to Keven Cruijssen ``` #define C(n,c)n(a,b){a=a*b?c*--b+n(a,b):0;} C(f,a*b+--a)C(g,~-a*b+a--) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=hZBBCoJAGIX3nUIMYUb_ATOIcJIWQpdIkXF0ZBaNoeNK7CJt3HiTLtFtUkyoTcG_-d57PPjffeBJwXnfD40WZP88rbNcSJUbIVLAsUIMUtyygNnpkduEpM4s-S7tViESMBoOIQyHqIAbmYgRgt9tjwuTCuF2JZU2dF7rhLM6r89x0HqwhY27XEdFWaEpJQOXysOOSifwcHutRk0g08qMSFtZpMtG-8ZCyoSPUhl_kbOJQaCfPobiTwDTrpt_WRZ6AQ) `f(a,b)` returns the number of black chocolates while `g(a,b)` the number of white chocolates. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~20~~ 19 bytes ``` I⁺ΣE⌊θΣ⁻Π⁻θι⁻θι⟦⌊θ⁰ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEIyCntFgjuDRXwzexQMM3My8zF8gu1NRRAItl5gFlA4ryU0qTS6C8Qh2FTE2gPDJPEyQQjazbIBYoZv3/f3S0kY6CcWzsf92yHAA "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a tuple or list of (rows, columns). Explanation: ``` θ Input tuple ⌊ Minimum E Map over implicit range θ Input tuple ⁻ Vectorised minus ι Current value Π Take the product ⁻ Minus θ Input tuple ⁻ Vectorised minus ι Current value Σ Take the sum Σ Take the sum ⁺ Vectorised add ⟦ List of θ Input tuple ⌊ Minimum ⁰ Literal integer `0` I Cast to string Implicitly print ``` Edit: Saved 1 byte by porting @Ausername's formula. The best closed form formula I could find was 22 bytes, but adapting one of @alephalpha's versions saves 1 byte: ``` I⁻⁻×Πθ⌊θ÷⁻X⌊θ³⌊θ³⟦⁰⌊θ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwzczr7QYSoZk5qYWawQU5aeUJpdoFGrqKADFM3NLc4FsIMczr8QlsywzJRWqPCC/PLVIA6FER8EYXYsxiIg2QBaN1dTUtP7/PzraCCgdG/tftywHAA "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a tuple or list of (rows, columns). Explanation: ``` θ Input tuple Π Product × Multiplied by θ Input tuple ⌊ Minimum ⁻ Subtract θ Input tuple ⌊ Minimum X Raised to power ³ Literal integer `3` ⁻ Subtract θ Input tuple ⌊ Minimum ÷ (Integer) Divide by ³ Literal integer `3` ⁻ Vectorised subtract ⟦ List of ⁰ Literal integer `0` θ Input tuple ⌊ Minimum I Cast to string Implicitly print ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 14 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` _ⱮṂ‘PḤ_SƲ€S;ṂÄ ``` A monadic Link that accepts a list of two integers, the base dimensions, and yields a pair of integers, `[dark, white]`. **[Try it online!](https://tio.run/##y0rNyan8/z/@0cZ1D3c2PWqYEfBwx5L44GObHjWtCbYGCh1u@f//f7ShgY6hQSwA "Jelly – Try It Online")** --- ## 16 bytes ~~Probably~~ beatable with a constructive method, but I like it. ``` Ṃð‘c3×4+²×IAʋ;⁸Ä ``` A monadic Link that accepts a list of two integers, the base dimensions, and yields a pair of integers, `[dark, white]`. **[Try it online!](https://tio.run/##AS0A0v9qZWxsef//4bmCw7DigJhjM8OXNCvCssOXSUHKizvigbjDhP///1sxMCwxMF0 "Jelly – Try It Online")** ### How? ``` Ṃð‘c3×4+²×IAʋ;⁸Ä - Link: Dimensions Ṃ - minimum (Dimensions) ð - start a new dyadic chain - f(M=that, Dimensions) ‘ - increment (M) c3 - choose three -> (M-1)th triangular pyramidal number ×4 - times four (call this Q) ʋ - last four links as a dyad - f(M, Dimensions): ² - square (M) I - forward differences (Dimensions) -> [Height-Width] × - multiply -> [M*M*(Height-Width)] A - absolute value -> [M*M*|Height-Width|] + - (Q) add (that) -> [dark piece count] ⁸ - chain's left argument -> M ; - (dark piece count) concatenate (M) -> [dark piece count, M] Ä - cumulative sums -> [dark piece count, white piece count] ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` Wݨ€-DPαOD>‚O ``` Port of [*@emanresuA*'s Vyxal answer](https://codegolf.stackexchange.com/a/255045/52210), so make sure to upvote him/her as well! Input as a pair \$[width,height]\$; output as a pair \$[dark,white]\$. [Try it online](https://tio.run/##yy9OTMpM/f8//PDcQyseNa3RdQk4t9Hfxe5Rwyz///@jjXSMYwE) or [verify all test cases](https://tio.run/##S0oszvifnFiiYKeQnJ@SqpdfnJiUmapgY6Pg6u/GZa@k8KhtkoKS/f/ww3MPrXjUtEbXJeDcRn8Xu0cNs/z/63CBFHGVZ2TmpCoUpSamKGTmcaXkcyko6OcXlOhDzIJSaMbbKKiA1eal/o820jGO5Yo2NNAxNIDSsVwA). **Explanation:** ``` W # Get the minimum of the (implicit) input-pair Ý # Pop and push a list in the range [0,min] ¨ # Remove the last item to make the range [0,min) €- # Subtract each from the (implicit) input-pair D # Duplicate this list of pairs P # Get the product of each inner pairs α # Get the absolute difference with the values in the pairs O # Sum each inner pair D # Duplicate this list > # Increase each inner value by 1 ‚ # Pair the two lists together O # Sum each inner list # (after which this pair is output implicitly as result [dark,white]) ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 20 bytes ``` _-h=SQ sm+*FQ*F=tMQh ``` [Try it online!](https://tio.run/##K6gsyfj/P143wzY4kKs4V1vLLVDLzbbENxAoqmFooKNgaKAJAA "Pyth – Try It Online") Takes (width, height), outputs (white, dark) ### Explanation ``` =SQ sort the input, set to Q _-h output dark - min(Q) s sum of m hQ run min(Q) times: + add *FQ product of elements of Q =tMQ decrement each element of Q *F product of elements of Q ``` [Answer] # Python 3, 83 bytes: ``` f=lambda r,c,w=0,d=0:f(r-1,c-1,w+r*c+(r-1)*(c-1),d+r*(c-1)+c*(r-1))if r*c else(w,d) ``` [Try it online!](https://tio.run/##XYpBCsMgEEX3OYXLGZ2CNpsQ8DBGIxVsKpOA5PTGBrrp4sN7j1/O4/XZxqlwa9Fm916CE0yeqtUUrJ4j8MOQ76uKpVdfRQk9IIVeblJe3h1TFP0k1ryvUClgK5y2AyI8aUQcfmY0Gf3niO0C) [Answer] # JavaScript (ES7), 40 bytes Uses the closed form formula from [alephalpha's answer](https://codegolf.stackexchange.com/a/255044/58563). Expects `(w)(h)`. ``` w=>h=>[n=w*h*(w<h?w:w=h)+(w-w**3)/3,n-w] ``` [Try it online!](https://tio.run/##bchLDkAwEADQvVN0OVPq150YDiIW4lcirSDm@BVLicXbvLW7u7M/lv1S1g2jn8gzVYaqxhJLI4FLU3PBZDAEViylxkRHVnHre2dPt43x5maYQOQIQiMG385SfP21yBD9Aw "JavaScript (Node.js) – Try It Online") [Answer] # [Python](https://www.python.org), 50 bytes ``` lambda p,q:(y:=(x:=min(p,q))*(3*p*q+1-x*x)//3,y-x) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3jXISc5NSEhUKdAqtNCqtbDUqrGxzM_M0gHxNTS0NY60CrUJtQ90KrQpNfX1jnUrdCk2oTr-Cosy8Eo00DSMdBWNNHQUNQwMdBQtNTS6YOIhvaACSMTMHMs3MDNAlYbosgRIQUxcsgNAA) Same closed formula (@alephalpha's) everybody is using. [Answer] # [Lil](https://beyondloom.com/decker/lil.html), 59 bytes ``` on f x do r:min x t:(r/3)+(r*r*max x)-(r^3)/3 t,t-r end ``` [Try it online!](https://ktye.github.io/zoo/#lil) Same as alephalpha. [Answer] # [Pip](https://github.com/dloscutoff/pip) `-p`, 26 bytes ``` Y Ngy*a*b-y*(y*y+2)/3+[y0] ``` [Try It Online!](https://dso.surge.sh/#@WyJwaXAiLCIiLCJZIE5neSphKmIteSooeSp5KzIpLzMrW3kwXSIsIiIsIjEwIDEwIiwiLXAiXQ==) Port of my Desmos answer. [Answer] # [APL(Dyalog Unicode)](https://dyalog.com), 15 bytes [SBCS](https://github.com/abrudz/SBCS) ``` ⌊××+3÷⍨1 ¯2-⌊×⌊ ``` [Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=e9TTdXj64enaxoe3P@pdYahwaL2R7iOQGJAAAA&f=M1JIUzDmMjQAUoYGUBoA&i=AwA&r=tryapl&l=apl-dyalog&m=dfn&n=f) Closed form formula from alephalpha's [PARI/GP answer](https://codegolf.stackexchange.com/a/255044/). [Answer] # Raku, 49 bytes ``` {my (\r,\c)=.sort;my \t=-r**3/3+r/3+c*r*r;t,-r+t} ``` [Try it online!](https://glot.io/snippets/gfzb0fb4ir) [Answer] # [Perl 5](https://www.perl.org/), 68 + 3 (`-pla` option) = 71 bytes ``` ($i,$j)=@F;{$d+=$k=$i*$j*2-$i---$j--;$w+=$k+1;$i*$j&&redo}$_="$w $d" ``` [Try it online!](https://tio.run/##K0gtyjH9/19DJVNHJUvT1sHNulolRdtWJdtWJVNLJUvLSFclU1dXVyVLV9dapRwkoW1oDZZSUytKTcmvVYm3VVIpV1BJUfr/39BAwdCA619@QUlmfl7xf92CnEQA "Perl 5 – Try It Online") [Answer] # x86-64 machine code, 26 bytes ``` 92 39 F0 73 01 96 6A 03 59 F7 E1 29 F0 F7 E6 F7 E6 01 F0 F7 F1 AB 29 F0 AB C3 ``` [Try it online!](https://tio.run/##hVPBjtsgED3DV0xTuYK1HaW7UVWFppeee@mpUtMDCzgmtbEFeOsom1@vFxzvrtPLIuQZmPfejGdske@FGAbuaiDwY0FwsUG9KPegZJ@B4j1Gom6jE05OY3TgChyeME5fMG6D2s6VcMegbVqwItDqrgIVHdfdz/jj9ZXDpZzFpX6YaL5x8n/2dGmVx3RBGXbedsKDVa6rPJy08fC31F5lILn9w84MPzRaQkGugTc2gxF7MSVlw3ttRNVJBV@cl7pZll9xDNVcG0LxKaaeK1iGUWsDoiALgMdYCyoaCySSDrCFjyyYd8FGJ00phtl6Ziaf9eMigwOdqe1Mnqdv671o5M/rmqMvHD1y1sGJNaDwHrNEye2YXkfiG9WjkYoK8iG2bir5VStZ67CjmF1OA7DLOIIRdsZxv@bdme9clNooEI1Um7HwmLkPmVcZHMNRNnB66W@yuv0ZpI9bQjrj9N4oCaLk9oYW9Fefpr8pO8e5VwrIMZa96r/dzXsKJNFwf/TK0Z0JSn0Mho@oswZWDJ@Hf6Ko@N4Nef1pHR7hd9gGpqqeAA "C (gcc) – Try It Online") Following the standard calling convention for Unix-like systems (from the System V AMD64 ABI), this takes in RDI an address at which two 32-bit integers will be consecutively placed, for the white number and the dark number, in that order; and takes the width and height in ESI and EDX. In assembly: ``` f: xchg edx, eax # Switch one argument into EAX. cmp eax, esi # Compare the two arguments. jae s # Jump if EAX holds the higher value. xchg esi, eax # Otherwise, exchange the values. s: # (Now, EAX holds the higher value (which we will call m) # and ESI holds the lower value (which we will call n).) push 3; pop rcx # Set ECX to 3. mul ecx # Multiply EAX by ECX (3), producing 3m. # (Also, the high half of the product goes in EDX.) sub eax, esi # Subtract ESI (n) from EAX, producing -n+3m. mul esi # Multiply EAX by ESI (n), producing -n²+3mn. mul esi # Multiply EAX by ESI (n), producing -n³+3mn². add eax, esi # Add ESI (n) to EAX, producing -n³+3mn²+n. div ecx # Divide EDX:EAX by 3, producing (-n³+3mn²+n)/3. stosd # Write that value to the address EDI, advancing the pointer. sub eax, esi # Subtract ESI (n) from EAX, producing (-n³+3mn²-2n)/3. stosd # Write that value to the address EDI, advancing the pointer. ret # Return. ``` ]
[Question] [ A pyramidal matrix is a square matrix where all numbers increase or decrease from the center point, like the two matrices below: ``` 1 1 1 1 1 1 2 2 2 1 1 2 3 2 1 1 2 2 2 1 1 1 1 1 1 ``` Or: ``` 3 3 3 3 3 3 2 2 2 3 3 2 1 2 3 3 2 2 2 3 3 3 3 3 3 ``` Given a non-zero integer `n`, create a pyramidal matrix where the numbers goes from `1` to `n` either in increasing order (if n<0), or decreasing order (if n>0) from the center. **If `n` is even, then there will be 4 center numbers** (see the examples). **As always:** * Optional input and output format + Number of spaces, delimiter etc. is optional **Test cases:** ``` 1 1 -1 1 5 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 1 1 2 3 3 3 3 3 2 1 1 2 3 4 4 4 3 2 1 1 2 3 4 5 4 3 2 1 1 2 3 4 4 4 3 2 1 1 2 3 3 3 3 3 2 1 1 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1 -5 5 5 5 5 5 5 5 5 5 5 4 4 4 4 4 4 4 5 5 4 3 3 3 3 3 4 5 5 4 3 2 2 2 3 4 5 5 4 3 2 1 2 3 4 5 5 4 3 2 2 2 3 4 5 5 4 3 3 3 3 3 4 5 5 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 5 5 ``` ``` 2 1 1 1 1 1 2 2 1 1 2 2 1 1 1 1 1 -2 2 2 2 2 2 1 1 2 2 1 1 2 2 2 2 2 -4 4 4 4 4 4 4 4 4 4 3 3 3 3 3 3 4 4 3 2 2 2 2 3 4 4 3 2 1 1 2 3 4 4 3 2 1 1 2 3 4 4 3 2 2 2 2 3 4 4 3 3 3 3 3 3 4 4 4 4 4 4 4 4 4 ``` [Answer] # EXCEL: 126 bytes `=MAX(MIN(MIN(CELL("row",RC)-1,CELL("col",RC)-1),MIN(((ABS(R1C1)-1)*2+3)-CELL("row",RC),((ABS(R1C1)-1)*2+3)-CELL("col",RC))),0)` [Try it online](https://docs.google.com/spreadsheets/d/1vDNTouXw1UHoEoGGZFdxkuQTqABb84JywnYAT_U_EnQ/edit?usp=sharing)\* Note: this answer uses R1C1 Notation. If you're going to try this yourself. you need to turn that on in Excel options. the formula given needs to be in every cell present beyond (2,2). Put your desired pyramid size into (1,1). quick screen-cap of the formula in action: [![enter image description here](https://i.stack.imgur.com/wl8dS.png)](https://i.stack.imgur.com/wl8dS.png) Here is an [Additional picture of some fun with conditional formatting!](https://i.stack.imgur.com/8YoEC.jpg) \*It takes a very long time to update, currently. [Answer] # [MATL](http://github.com/lmendo/MATL), ~~26~~ 24 bytes ``` oXyG|to-:"TTYaQ]G0<?G+q| ``` [**Try it online!**](http://matl.tryitonline.net/#code=b1h5R3x0by06IlRUWWFRXUcwPD9HK3F8&input=NA) Or [**verify all test cases**](http://matl.tryitonline.net/#code=IkBYSwpvWHlLfHRvLToiVFRZYVFdSzA8P0srcXw&input=WzEgLTEgNSAtNSAyIC0yIC00XQ) (slightly modified code to serve as test suite). ### Explanation The code first builds the output array assuming positive input `n`. The array is initiallized as `1` for odd input or as the empty array for even input (this is created as an identity matrix with size equal to the parity of the input). Then the following is repeated `n` times for even input, and `n-1` times for odd input: extend the array with a frame containing `0`, and add `1` to all elements. For example, the steps for input `n` are: * Initial array: ``` 1 ``` * Extend with frame: ``` 0 0 0 0 1 0 0 0 0 ``` * Add `1`: ``` 1 1 1 1 2 1 1 1 1 ``` * Extend with frame: ``` 0 0 0 0 0 0 1 1 1 0 0 1 2 1 0 0 1 1 1 0 0 0 0 0 0 ``` * Add `1`: ``` 1 1 1 1 1 1 2 2 2 1 1 2 3 2 1 1 2 2 2 1 1 1 1 1 1 ``` This gives the correct output for positive input. If the input is negative, the array needs to be modified by adding the input minus `1` and taking the absolute value: ``` 3 3 3 3 3 3 2 2 2 3 3 2 1 2 3 3 2 2 2 3 3 3 3 3 3 ``` You can watch the array growing (modified code to show intermediate steps) at [**MATL Online!**](https://matl.suever.net/?code=oXytD1Y.XxG%7Cto-%3A%22TTYatD1Y.XxQtD1Y.Xx%5DG0%3C%3FG%2Bq%7C&inputs=-3&version=19.2.0) The interpreter is still a beta. If it doesn't work press "Run" again or reload the page. ### Commented code ``` o % Take input implicitly and push 0 if even or 1 if odd Xy % Identity matrix of that size. Gives either 1 or empty array G| % Absolute value of input to- % Subtract 1 if odd :" % For loop: repeat that many times TTYa % Add a frame of zeros in the two dimensions Q % Add 1 to all elements ] % End for G % Push input again 0> % is it negative? ? % If so G % Push input again + % Add q % Subtract 1 | % Absolute value % End if implicitly % Display implicitly ``` [Answer] ## Python 2, 109 99 98 ``` n=input() r=range(1,abs(n)+1) l=r+r[~n|-2::-1] for j in l:print[abs((n<0)*~-n+min(i,j))for i in l] ``` Create list ``` l = [1,2,3,4,5,4,3,2,1] ``` and play with it a little. --- edit: new way of creating list + thx Lynn for two bytes [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~18~~ 17 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` |1ŒḄfR«þ` AÇạẋ¡CG ``` [Try it online!](http://jelly.tryitonline.net/#code=fDHFkuG4hGZSwqvDvmAKQcOH4bqh4bqLwqFDRw&input=&args=Ng) or [verify all test cases](http://jelly.tryitonline.net/#code=fDHFkuG4hGZSwqvDvmAKQcOH4bqh4bqLwqFDRwrDh-KCrGrigJzCtsK2&input=&args=MSwgLTEsIDUsIC01LCAyLCAtMiwgLTQ). ### How it works ``` |1ŒḄfR«þ` Helper link. Argument: k (positive integer) |1 Take the bitwise OR with 1. This increments k if it is even. ŒḄ Bounce; yield [1, 2, ..., k | 1, ..., 2, 1]. fR Filter range; remove elements not in [1, ..., k] from the array. This results in [1, 2, ..., k, ..., 2, 1] if k is odd and in [1, 2, ..., k, k, ..., 2, 1] if k is even. ` Pass the last return value as left and right argument to: «þ Minimum table; take the minimum of each pair of elements in the generated array, returning a 2D array. AÇạẋ¡CG Main link. Argument: n A Take the absolute value of n. Ç Call the helper link on the result. C Complement; yield 1 - n. ¡ Conditional application: ẋ If repeating the return value of Ç 1 - n times results in a non- empty array, i.e., if n < 1: ạ Take the absolute differences of the generated integers and 1 - n. G Grid; join columns by spaces, rows by linefeeds. ``` [Answer] # Python 2.7: ~~123~~ ~~122~~ 120 Bytes probs can still save a few bytes... ``` from numpy import* n=input() N=abs(n) e=N*2-N%2 a=ones([e,e]) for i in range(N):a[i:e-i,i:e-i]=(i+1)*(n>0)or-n-i print a ``` edit1: `N=abs(n)` to save 1 byte edit2: `(i+1)*(n>0)or-n-i` to save 2 bytes [Answer] ## Haskell, ~~119~~ ~~113~~ ~~110~~ ~~104~~ ~~102~~ 101 bytes ``` f x|(h,t)<-splitAt(mod x 2)$[x,x-1..1]++[1.. -x]=foldl(\m n->(n#)<$>(n<$m)#m)[[y]|y<-h]t x#y=x:y++[x] ``` Returns the matrix as a list of lists of integers, for example: `f 2` -> `[[1,1,1,1],[1,2,2,1],[1,2,2,1],[1,1,1,1]]`. How it works: ``` [x,x-1..1]++[1.. -x] -- make list from x down to 1 followed by -- 1 to (-x). One of the sublists will be -- empty. The resulting list contains the -- numbers of the pyramid from inside to out. (h,t)<-splitAt(mod x 2) -- bind h to the first element if x is odd -- or to the empty list if x is even -- bind t to the rest (tail or full list) foldl ( ) [[y]|y<-h] t -- fold the following function into t with a -- starting value of [] if x is even or -- [[h]] if x is odd \m n -> -- the current matrix m with the next number -- n is transformed into a new matrix: (n#)<$>(n<$m)#m -- prepend and append a n to -- m prepended and append by a line of n's x#y=x:y++[x] -- helper function to prepend and append an -- element x to a list y ``` [Answer] ## Perl, 175 bytes Includes 1 bytes for `-p`. ``` ($t,$v,$w)=($_,(abs)x2);$k=$_.$k for 1..$v;map{$r.=$_ for(@v=1..$_-1),$_ x(2*$v---$w%2),reverse@v;$r.=$/}1..$v;$_=$r.~~reverse$r;eval"y/1-$w/$k/"if$t<0;$w%2&&s/ .*//||s; ; ``` (There is a trailing newline that I don't know how to show with the markdown, but you need it). Needs `-p` as well as `-M5.010` or `-E` to run : ``` perl -pE '($t,$v,$w)=($_,(abs)x2);$k=$_.$k for 1..$v;map{$r.=$_ for(@v=1..$_-1),$_ x(2*$v---$w%2),reverse@v;$r.=$/}1..$v;$_=$r.~~reverse$r;eval"y/1-$w/$k/"if$t<0;$w%2&&s/ .*//||s; ; ' <<< 5 ``` Damn, this is too long... I'll try some other approaches when I have some time. [Answer] # Python 2, 109 bytes ``` n=input() a=abs(n) s=a*2-a%2 r=range(s) for y in r:print[(min,max)[n<0](x+1,s-x,y+1,s-y)-(n<0)*s/2for x in r] ``` [Answer] # J, ~~29~~ 26 bytes ``` 1+**[:<./~**i.,2&|1&}.i.@- ``` ## Usage ``` f =: 1+**[:<./~**i.,2&|1&}.i.@- f 1 1 f _1 1 f 2 1 1 1 1 1 2 2 1 1 2 2 1 1 1 1 1 f _2 2 2 2 2 2 1 1 2 2 1 1 2 2 2 2 2 f 3 1 1 1 1 1 1 2 2 2 1 1 2 3 2 1 1 2 2 2 1 1 1 1 1 1 f _3 3 3 3 3 3 3 2 2 2 3 3 2 1 2 3 3 2 2 2 3 3 3 3 3 3 ``` ## Explanation The range `i.` verb outputs `[0, 1, ..., n-1]` for positive `n` and `[n-1, n-2, ..., 0]` for negative `n` which is useful here. ``` 1+**[:<./~**i.,2&|1&}.i.@- Input: integer n - Negate n i.@ Creates range for -n 2&| Take n modulo 2, returns 0 or 1 1&}. If n is odd, drop the first value from the range for -n Else do nothing and pass it unmodified , Append it to i. The range for n * Get the sign of n * Multiply elementwise with the joined ranges [:<./~ Form a table of the minimum values of the range * Get the sign of n * Multiply elementwise with the joined ranges 1+ Add 1 to each and return ``` [Answer] # Mathematica, 78 bytes ``` Abs[Fold[ArrayPad[#,1,#2]&,Table[0,#,#]&@Mod[#,2,1],Range[Abs@#-1]]+1~Min~-#]& ``` # Explanation ``` Table[0,#,#]&@Mod[#,2,1] ``` Make initial matrix: 1x1 if odd, 2x2 if even. ``` Range[Abs@#-1] ``` Generate a list from 1 to abs(input) - 1. ``` Fold[ArrayPad[#,1,#2]&, ..., ...] ``` Pad the initial array using the aforementioned list. ``` ... +1~Min~-# ``` Add 1 or -input, whichever is smaller. ``` Abs ``` Apply absolute value to the entire matrix. [Answer] # PHP, ~~177~~ 157 bytes ``` for($y=-$n=abs($z=$argv[1])+1;++$y<$n;)if($y&&($n&1||$y-1)){for($x=-$n;++$x<$n;)if($x&&($n&1||$x-1)){$v=max(abs($x),abs($y));echo$z<0?$v:$n-$v," ";}echo" ";} ``` run with `php -r '<code>` loops through rows and columns, prints the values depending on their distance to the center. * `$n=abs($z)+1`: The `+1` saves a couple of `+1` and `-1` in later expressions * loops go from `-$n+1` (pre-increment in the condition!) to `$n-1` (`-abs($z)` to `abs($z)`) * line/column 0 (and for odd `$n`: 1) are skipped (`$n&1` is true for even columns here! Remember the `+1`?) * The printing for positive $z also benefits from the `+1`. [Answer] # Haskell, ~~191~~ ~~183~~ ~~173~~ ~~169~~ 168 bytes ``` r=reverse;m=map x!y=(((++)<*>(x.r)).).zipWith(++).m y g n|n<0=m(m$abs.((n-1)+)).g$abs n|1<2=[id!id,tail!init]!!mod n 2=<<m r$r$m(\x->(x<$[1..x])++[x+1..n])[1..n] g.(0-) ``` Usage: ``` mapM_ print $ (g.(0-)) 3 [1,1,1,1,1] [1,2,2,2,1] [1,2,3,2,1] [1,2,2,2,1] [1,1,1,1,1] ``` Thanks to nimi for ~~2~~ ~~10~~ ~~20~~ 24 bytes! [Answer] ## JavaScript (ES6), 107 bytes ``` (n,l=Math.abs(n+n-n%2))=>[...Array(l--)].map((_,i,a)=>a.map((_,j)=>(j=Math.min(i,l-i,j,l-j),n<0?-n-j:j+1))) ``` `l` is the size of the array. The `n<0?-n-j:j+1` seems awkward but I can't find anything better. [Answer] # Vim, ~~152~~ 143 bytes I'm sure this could be golfed more, especially those last two lines, but my brain is fried. ``` D:let@z=@-/abs(@-) a"nywYp:s/\d/x/g<C-v> YggP:%s/.*/x \0 x<C-v> :%s/x\+/\=@n-@z/g<C-v> <Esc>v0"qda<C-r>=@z<0?1:@-*@z <Esc>@=@-%2?"":"YPJYp" @=@-*@z-1.(@-*@z>1?"@q":"") ``` [Try it online!](http://v.tryitonline.net/#code=RDpsZXRAej1ALS9hYnMoQC0pCmEibnl3WXA6cy9cZC94L2cWCllnZ1A6JXMvLioveCBcMCB4Fgo6JXMveFwrL1w9QG4tQHovZxYKG3YwInFkYRI9QHo8MD8xOkAtKkB6ChtAPUAtJTI_IiI6IllQSllwIgpAPUAtKkB6LTEuKEAtKkB6PjE_IkBxIjoiIik&input=LTU) Here it is in xxd format with unprintable characters: ``` 0000000: 443a 6c65 7440 7a3d 402d 2f61 6273 2840 D:let@z=@-/abs(@ 0000010: 2d29 0a61 226e 7977 5970 3a73 2f5c 642f -).a"nywYp:s/\d/ 0000020: 782f 6716 0a59 6767 503a 2573 2f2e 2a2f x/g..YggP:%s/.*/ 0000030: 7820 5c30 2078 160a 3a25 732f 785c 2b2f x \0 x..:%s/x\+/ 0000040: 5c3d 406e 2d40 7a2f 6716 0a1b 7630 2271 \=@n-@z/g...v0"q 0000050: 6461 123d 407a 3c30 3f31 3a40 2d2a 407a da.=@z<0?1:@-*@z 0000060: 0a1b 403d 402d 2532 3f22 223a 2259 504a ..@=@-%2?"":"YPJ 0000070: 5970 220a 403d 402d 2a40 7a2d 312e 2840 Yp".@=@-*@z-1.(@ 0000080: 2d2a 407a 3e31 3f22 4071 223a 2222 29 -*@z>1?"@q":"") ``` ## Explanation It builds the pyramid from the center out, surrounding the center number with `x`es: ``` x x x x 5 x x x x ``` Then it replaces the `x`es with the next number and surrounds it with `x`es again: ``` x x x x x x 4 4 4 x x 4 5 4 x x 4 4 4 x x x x x x ``` ...and so on. For even numbers it does the same thing but starts with a 2x2 base. Here's the code "ungolfed." It's somewhat unconventional in that I "record" a macro by typing it into a buffer (hence all the `<C-v>`s) and then deleting it into a register, which is the best way I found to compose a macro without actually executing the keystrokes. ``` D:let@z=@-/abs(@-)<CR> " Delete the input (into @-) and set @z to -1 if @- is negative; otherwise 1 a " Enter insert mode to compose the macro "nyw " Copy the number under the cursor to @n Yp " Copy this line and paste it below :s/\d/x/g<C-v><CR> " Replace digits in the copy with 'x' YggP " Copy this line and paste it at the top of the buffer :%s/.*/x \0 x<C-v><CR> " Add an 'x' before and after each line :%s/x\+/\=@n-@z/g<C-v><CR> " Replace all 'x'es (and 'xx'es etc.) with the next number <Esc>v0"qd " Done composing macro; delete it into @q (buffer is now empty) a<C-r>=@z<0?1:@-*@z " Append the center number (1 or abs(@-)) to the buffer <Esc>@=@-%2?"":"YPJYp" " If the input is even, make a 2x2 square @=@-*@z-1.(@-*@z>1?"@q":"") " Execute the macro abs(@-)-1 times if it's > 1 ``` [Answer] # PHP, 215 Bytes ``` for($i=0;$i<$m=($r=($s=abs($n=$argv[1]))*2-$s%2)**2;){$i%$r?:print"\n";$l=min(($x=$i%$r+1)<$s?$x:$x=$r-$x+1,($z=1+floor($i++/$r))<$s?$z:$z=$r-$z+1);$o=($n>0)?$l:$s+1-$l;echo str_pad(" ",1+strlen($s)-strlen($o)).$o;} ``` [Answer] # R, 112 bytes ``` k=abs(n);l=2*k;m=diag(l);for(i in 1:k){m[i:(l+1-i),i:(l+1-i)]=i};if(n%%2==1){m=m[-k,-k]};if(n<0){m=abs(m-1+n)};m ``` Needs integer `n` in workspace, otherwise run `n=scan()` for an extra 8 bytes. ``` k=abs(n) l=2*k m=diag(l) # Initialize quadratic 2*|n| matrix for(i in 1:k){ m[i:(l+1-i),i:(l+1-i)]=i # Assign values to matrix elements according # to their index } if(n%%2==1){ m=m[-k,-k] # If n is odd, delete middle row and column } if(n<0){ m=abs(m-1+n) # If n < 0, flip values } m # Print matrix ``` ]
[Question] [ This challenge was inspired by programming an Arduino microcontroller. I have 6 LEDs and 6 buttons connected to various pins on the board. In the code, each button and LED is assigned an ID number (1-6). Pin numbers (ranging from 0-13) corresponding to the ID numbers are looked up using a `switch` statement. Purely for amusement, I was wondering if these `switch`es could be circumvented with an arithmetic/other function just to horrify future code maintainers. ## The challenge Provide the function/functions that take the ID number (integer) as a parameter and return the pin number (integer) for the 6 LEDs and/or the 6 buttons, without using conditional statements (no `if`, no `switch` and no ternary). Return values for LEDs: ``` ID Pin 1 3 2 5 3 6 4 9 5 10 6 11 ``` Return values for buttons: ``` ID Pin 1 2 2 4 3 7 4 8 5 12 6 13 ``` ## Bonus challenge Provide a single function that takes an ID number (integer) and second parameter (any type) indicating whether LED or button pins are requested, and returns the corresponding pin (integer). ## Rules This is **not** an Arduino-specific challenge. Use **any language**, do **whatever** you want. Edit: at the suggestion of *steveverril*, this is now a **code golf** challenge. Good luck! (If you're still reading: although patently absurd and arbitrary by programming standards, the mappings are based on the Arduino Micro's pinout. Pins 0 and 1 are reserved for serial communication, LEDs are assigned to the 6 lowest-numbered PWM-capable pins, buttons are assigned to remaining pins) [Answer] # C, 28 bytes each ``` p(i){return"@cefijk"[i]&15;} b(i){return"@bdghlm"[i]&15;} ``` This is basically the same as the answer by kirbyfan64sos, but uses a char array instead of integers, and has a dummy first byte so there is no need to subtract 1 from the function parameter. [Answer] # Haskell, 24 bytes each ``` l 1=3 l n=n+l(div(n+2)3) ``` to check: ``` > map l [1..6] [3,5,6,9,10,11] ``` . ``` b 1=2 b n=n+b(div(n+1)2) ``` to check: ``` > map b [1..6] [2,4,7,8,12,13] ``` ## bonus, Haskell, 36 bytes ``` a f 1=f+2 a f n=n+a f(n+f+1`div`f+2) ``` to check: ``` > map (a 0) [1..6] [2,4,7,8,12,13] > map (a 1) [1..6] [3,5,6,9,10,11] ``` 0 for buttons, 1 for LEDs. [Answer] # C (math), 32 / ~~27~~ 26 bytes (45 for bonus challenge) Several people have posted various table-lookup solutions, but that seemed to me like taking the easy way out.. I wanted to see how well I could do with purely mathematical operations: ``` p(i){return~i&1|i*2^i*!(i%5-1);} b(i){return i/5*5+1^p(i);} ``` It wasn't clear whether one function calling the other was acceptable or not; if not, one can use this alternate definition of `b(i)` (33 bytes) instead: ``` b(i){return(i&1|i*2)+i/5-!(i/2);} ``` ### Bonus Challenge (45 bytes): ``` f(i,t){return(i&1|i*2)+i/5-!(i/2)^t+i/5*5*t;} ``` (pass `t=0` for buttons, `t=1` for LEDs) [Answer] # C, 36 bytes each (49 bytes for the bonus challenge) ``` p(i){return 3500459>>(4*(7+~i))&15;} b(i){return 2390221>>(4*(7+~i))&15;} ``` ~~I'm sorry...I just couldn't help it...~~ Ok, I put a real solution now. ## Bonus challenge, 49 bytes ``` f(i,t){return(2390221+t*1110238)>>(4*(7+~i))&15;} ``` Use `f(button,0)` and `f(pin,1)`. [Live demo at Ideone.](http://ideone.com/DGJQHV) [![Screenshot](https://i.stack.imgur.com/jnT9d.png)](https://i.stack.imgur.com/jnT9d.png) ## Originals: ``` p(i){int a[]={3,5,6,9,10,11};return a[i-1];} b(i){int a[]={2,4,7,8,12,13};return a[i-1];} ``` [Answer] # Pyth - 12 bytes each Base encodes the array. ``` @jC"Ý"14tQ (buttons) @jC"\r'"12tQ (leds) ``` The last one is actually twelve bytes except I can't write a carriage return so i escaped it. [Test Suite for Buttons](http://pyth.herokuapp.com/?code=%40jC%22%13%13%C3%9D%2214tQ&input=6&test_suite=1&test_suite_input=1%0A2%0A3%0A4%0A5%0A6&debug=0). [Test Suite for LEDS](http://pyth.herokuapp.com/?code=%40jC%22%5Cr%27%13%2212tQ&test_suite=1&test_suite_input=1%0A2%0A3%0A4%0A5%0A6&debug=0). [Answer] # Pyth, Bonus only: 20 bytes ``` M@jC"5i«$xÍ"16+*6HtG ``` param#2 is 0 for LEDs, 1 for Buttons. To get Pin# for LED4,`g4 0` I would have posted this as a comment to Maltysen's entry, but I just started, so lack the required reputation. I've just started using PYTH tonight, and admit that I shamelessly adapted his method of efficiently encoding a list. If this was inappropriate, my deepest apologies, and I'll remove my entry. [Answer] # MIPS, 16 bytes Bit shifting and bitmask. Input in `$a0`, output in `$v0`. ``` sll $t0, $a0, 2 li $t1, 0xba96530 srlv $t0, $t1, $t0 andi $v0, $t0, 0xf ``` For bonus, use immediate `0xdc87420` [Answer] # F#, 28+28 bytes I wanted to try this without a lookup table. ``` let L x=1+x*2-x%4/3-x/5-x/6 let B x=x*2+x/3-x/4+x%6/5*2 ``` [Answer] # SWI-Prolog, 34 bytes each ``` l(I,P):-nth1(I,[3,5,6,9,10,11],P). b(I,P):-nth1(I,[2,4,7,8,12,13],P). ``` `l/2` is for LEDs, `b/2` is for buttons. ### Bonus, 66 bytes ``` a(I,S,P):-nth1(I,[3:2,5:4,6:7,9:8,10:12,11:13],A:B),(S=0,P=A;P=B). ``` `S = 0` for LEDs, anything else for Buttons. [Answer] # q/k (18 bytes each) Simply a case of indexing: ``` L:0N 3 5 6 9 10 11 B:0N 2 4 1 8 12 13 ``` Example: ``` q) L[2] 5 q) B[6] 13 ``` ## Bonus (1 byte, given L & B defined) ``` @ ``` Example: ``` q) @[`L;2] 5 q) @[`B;6] 13 ``` [Answer] # CJam, 10 bytes each These are anonymous functions. The links to the online interpreter show then within a small test harness that executes the function for all input values. Function 1 (LEDs): ``` {5*3|4+3/} ``` [Try it online](http://cjam.aditsu.net/#code=6%2C%3A)%0A%7B5*3%7C4%2B3%2F%7D%0A%25S*) Function 2 (buttons): ``` {_6|5+*5/} ``` [Try it online](http://cjam.aditsu.net/#code=6%2C%3A)%0A%7B_6%7C5%2B*5%2F%7D%0A%25S*) I wrote a small program that generates and evaluates these expressions. For both of them, it found a number of solutions with 8 characters (counting the expression only without the braces), but none with less. [Answer] # Javascript (ES6), 26/27 bytes LEDs: ``` a=>`0 `.charCodeAt(a) ``` Buttons: ``` a=>`0\r`.charCodeAt(a) ``` If the above doesn't run (which is likely), here's a hexdump: ``` 00000000: 6C 3D 61 3D 3E 60 30 03 - 05 06 09 0A 0B 60 2E 63 |l=a=>`0 `.c| 00000010: 68 61 72 43 6F 64 65 41 - 74 28 61 29 0A 62 3D 61 |harCodeAt(a) b=a| 00000020: 3D 3E 60 30 02 04 07 08 - 0C 5C 72 60 2E 63 68 61 |=>`0 \r`.cha| 00000030: 72 43 6F 64 65 41 74 28 - 61 29 |rCodeAt(a)| ``` I couldn't get the second one to work with a raw CR so I had to use `\r` ### Bonus, 41 bytes ``` (a,b)=>`0 \r`.charCodeAt(a+b*6) ``` Hexdump ``` 00000000: 28 61 2C 62 29 3D 3E 60 - 30 03 05 06 09 0A 0B 02 |(a,b)=>`0 | 00000010: 04 07 08 0C 5C 72 60 2E - 63 68 61 72 43 6F 64 65 | \r`.charCode| 00000020: 41 74 28 61 2B 62 2A 36 - 29 |At(a+b*6)| ``` Second parameter is 0 for LEDs, and 1 for buttons. [Answer] # Brainf\*\*k, 107 bytes ``` ,>++++++++[>+>++++++<<-<------>]<[>+++<-[>++<-[>+<-[>+++<-[>>>+>+<<<[-]+<-]]]]]>>[<++++++>-]<.>>>[-[-]<-.>] ``` This being my first hand-coded BF program, I don't doubt that there are several optimizations to be made. But it's still awesome. :) I'm not sure if `[]` counts as a conditional, though... :/ [Answer] ### POWERSHELL - 27-27-72 **LED use 1..6 as args** ``` :\>wc -c LED.PS1 & cat LED.PS1 & echo.& powershell -nologo -f LED.PS1 1 27 LED.PS1 (0,3,5,6,9,10,11)[$args[0]] 3 ``` **button use 1..6 as args** ``` :\>wc -c button.PS1 & cat button.PS1 & echo.& powershell -nologo -f button.PS1 6 27 button.PS1 (0,2,4,7,8,12,13)[$args[0]] 13 ``` **LED or BUTTON use b 1 ; l 2 ; b 6 ; l 5 etc as args** ``` :\>wc -c ledbutt.PS1 & cat ledbutt.PS1 & echo.& powershell -nologo -f ledbutt.PS1 b 5 72 ledbutt.PS1 $a=@{"b"=(0,3,5,6,9,10,11);"l"=(0,2,4,7,8,12,13)};$a[$args[0]][$args[1]] 10 :\>powershell -nologo -f ledbutt.PS1 l 5 12 :\>powershell -nologo -f ledbutt.PS1 b 3 6 :\>powershell -nologo -f ledbutt.PS1 l 2 4 ``` [Answer] # Octave, 40 bytes (bonus challenge) Using an anonuymous function: ``` @(x,y)[3 2;5 4;6 7;9 8;10 12;11 13](x,y) ``` After defining this function, call this function as `ans(x,y)`, where `x` is the pin/button number and `y` indicates pin or button with values `1` and `2` respectively. [Try it online](http://ideone.com/U0c8O5) [Answer] # JavaScript ~~113~~ ~~74~~ ~~66~~ ~~59~~ ~~52~~ 33 (one function) Using bit shift to get 4bit values. Must be called with p(n, 195650864 or 231240736). ``` /* 11 10 9 6 5 3 1011 1010 1001 0110 0101 0011 0000 = 195650864 13 12 8 7 4 2 1101 1100 1000 0111 0100 0010 0000 = 231240736 b >> i * 4 xxxx & 15 1111 yyyy (matching 1s) */ // Where b = 195650864 for pins and 231240736 for buttons. function p(i,b){return b>>i*4&15} ``` Alternate. ``` /* Using bitwise * 4 for bitwise only. function p(i,b){return b>>(i<<2)&15} */ ``` [Answer] # Perl 4 (37 and 31 bytes) LEDs (37 bytes): ``` $c=pop;$c*2+($c~~[1,2,4,6]&&5.5<=>$c) ``` ... but it uses a lookup table. Buttons (31 bytes, no lookup): ``` $c=pop;2*($c+($c==5))+($c%3==0) ``` [Answer] # JavaScript(ES6) 18,22,44 **Edit** Shorter but boring ``` // LED l=i=>1-~' 134789'[i] // Buttons b=i=>[,2,4,7,8,12,13][i] // bonus f=(i,t)=>1-~[' 134789',[,0,2,5,6,10,11]][t][i] //Test out=x=>O.innerHTML+=x+'\n' for(i=1;i<=6;i++) out(i +' -> '+l(i) + ' '+b(i) +' '+f(i,0)+' '+f(i,1)) ``` ``` <pre id=O></pre> ``` [Answer] # Python, 31 Bytes Each Not exactly creative or anything, but it works! ``` l=lambda x:int(" 3569AB"[x],16) b=lambda x:int(" 2478CD"[x],16) ``` # Bonus, 44 Bytes ``` k=lambda x,y:int("3569AB2478CD"[x-1+6*y],16) ``` `y` should be 0 for LEDs, and 1 for buttons. [Answer] # Python, 60 + 58 = 118 bytes ``` p=lambda i:(2**i)*(i<3)+1+(i>2)*(5+3*(i-3))-(i>4)*(i-3+~i%2) b=lambda i:2**i-(i>2)-(i>3)*(2**(i-1)-1)-4*(i>4)-15*(i==6) ``` These are awful. i don't even know what I'm doing here... But they're pretty interesting nonetheless! :D [Answer] # Ruby, 45 Bytes ``` ->i,t{[3,5,6,9,10,11,2,4,7,8,12,13][t*6+i-1]} ``` # Test Inputs: ``` ->i,t{[3,5,6,9,10,11,2,4,7,8,12,13][t*6+i-1]}.call 1,0 => 3 ->i,t{[3,5,6,9,10,11,2,4,7,8,12,13][t*6+i-1]}.call 3,1 => 7 ``` [Answer] # Forth, 26 bytes each, 34 for bonus Similar to the C version by squeamish. ``` : P " CEFIJK" + C@ F AND ; : B " BDGHLM" + C@ F AND ; ``` Bonus: ``` : A " CEFIJKBDGHLM" + + C@ F AND ; ``` Use 0 for LEDs and 6 for buttons. And the parameter order doesn't matter [Answer] # Pyth, 19 bytes each ``` L.&.>3500459*4-6b15 L.&.>2390221*4-6b15 ``` For pins and buttons, respectively. ]
[Question] [ ### Introduction When building an electronics project, a schematic may call for a resistor of an unusual value (say, 510 ohms). You check your parts bin and find that you have no 510-ohm resistors. But you do have many common values above and below this value. By combining resistors in parallel and series, you should be able to approximate the 510-ohm resistor fairly well. ### Task You must write a function or program which accepts a list of resistor values (resistors you stock) and a target value (which you aim to approximate). The program must consider: * Individual resistors * Two resistors in series * Two resistors in parallel The program should compute all possible combinations of 1 and 2 resistors from the stock list (including two copies of the same resistor value), compute their series and parallel resistance, then sort the configurations according to how well they approximate the target value. The output format should be one configuration per line, with a `+` denoting series and `|` denoting parallel, and some space or an = sign before the net resistance. ### Formulas * The resistance of one resistor is `R1` * The net resistance of two resistors in series is `R1 + R2` * The net resistance of two resistors in parallel is `1 / (1/R1 + 1/R2)` * The distance between an approximated resistance value and the target value can be calculated as pseudo-logarithmic distance, not linear distance: `dist = abs(Rapprox / Rtarget - 1)`. For example, 200 is closer to 350 than it is to 100. * A better distance measure is true logarithmic distance `dist = abs(log(Rapprox/Rtarget))`, but since this was not specified in the original question, you are free to use either measurement. ### Scoring Score is measured in characters of code, per usual golf rules. Lowest score wins. ### Example We have the following resistors in stock `[100, 150, 220, 330, 470, 680, 1000, 1500, 2200, 3300, 4700]` and wish to target `510` ohms. The program should output 143 configurations, approximately as shown (you can change the format, but make sure the meaning is easily determined): ``` 680 | 2200 519.444 1000 | 1000 500. 150 + 330 480. 220 + 330 550. 470 470 680 | 1500 467.89 680 | 3300 563.819 100 + 470 570. 220 + 220 440. 100 + 330 430. 470 | 4700 427.273 680 | 4700 594.052 1000 | 1500 600. 470 | 3300 411.406 680 | 1000 404.762 150 + 470 620. ... many more rows ... 2200 + 4700 6900. 3300 + 4700 8000. 4700 + 4700 9400. ``` In this example, the best approximation of 510 ohms is given by 680- and 2200-ohm resistors in parallel. **Best of each language so far (1 June 2014):** 1. J - 70 char 2. APL - 102 char 3. Mathematica - 122 char 4. Ruby - 154 char 5. Javascript - 156 char 6. Julia - 163 char 7. Perl - 185 char 8. Python - 270 char [Answer] ## Mathematica, ~~151~~ 122 characters Expects the target resistance to be stored in `r` and the list of available resistors in `l`. ``` SortBy[Join[{#,#}&/@l,Join@@(#@@@Union[Sort/@N@l~Tuples~{2}]&/@{{"+",##,#+#2}&,{"|",##,#*#2/(#+#2)}&})],Abs[#[[-1]]/r-1]&] ``` Less golf: ``` SortBy[Join[{#, #} & /@ l, Join @@ (# @@@ Union[Sort /@ N@l~Tuples~{2}] & /@ {{"+", ##, # + #2} &, {"|", ##, #*#2/(# + #2)} &})], Abs[#[[-1]]/r - 1] &] ``` The output format differs from the suggested one but configurations are easily determinable. The output is a list of configurations. Each configuration is of one of the following forms: ``` {R1, Total} {"+", R1, R2, Total} {"|", R1, R2, Total} ``` So the first three elements of the output read ``` {{"|", 680., 2200., 519.444}, {"|", 1000., 1000., 500.}, {"+", 150., 330., 480.}, ...} ``` If you're fine with rational numbers, I could save two characters from omitting `N@`. That is, the first element (for instance) would be returned as `4675/9` instead of `519.444`. [Answer] # APL (102) ``` {V←{⊃¨⍺{⍺,⍺⍺,⍵,'=',⍺⍵⍵⍵}⍺⍺/¨Z/⍨≤/¨Z←,∘.,⍨⍵}⋄K[⍋|¯1+⍺÷⍨0 4↓K←↑('|'{÷+/÷⍺⍵}V⍵),('+'+V⍵),{⍵,' =',⍵}¨⍵;]} ``` This takes the target resistance as the left argument and a list of available resistors as the right argument. Explanation: * `V←{`...`}`: `V` is a function that: + `Z/⍨≤/¨Z←,∘.,⍨⍵`: finds every unique combination of two values in `⍵`, - `Z←,∘.,⍨⍵`: join each value in `⍵` with each value in `⍵`, store in `Z`, - `Z/⍨≤/¨Z`: select from `Z` those combinations where the first value is less than or equal to the second value + `⍺{`...`}⍺⍺/¨`: and then applies following function, bound with the left function (`⍺⍺`) on the right and the left argument (`⍺`) on the left, to each pair: - `⍺,⍺⍺,⍵,'=',⍺⍵⍵⍵`, the left argument, followed by the left bound argument, followed by the right argument, followed by `=`, followed by the right function (`⍵⍵`) applied to both arguments. (This is the formatting function, `X [configuration] Y [equals] (X [fn] Y)`.) + `⊃¨`: and then unbox each element. * `{⍵,' =',⍵}¨⍵`: for each element in `⍵`, make the configurations for the individual resistors. (`⍵`, nothing, nothing, `=`, `⍵`). * `('+'+V⍵)`: use the `V` function to make all serial configurations (character is `'+'` and function is `+`). * `'|'{÷+/÷⍺⍵}V⍵`: use the `V` function to make all parallel configurations (character is `'|'` and function is `{÷+/÷⍺⍵}`, inverse of sum of inverse of arguments). * `K←↑`: make this into a matrix and store it in `K`. * `0 4↓K`: drop the 4 first columns from `K`, leaving only the resistance values. * `|¯1+⍺÷⍨`: calculate the distance between `⍺` and each configuration. * `K[⍋`...`;]`: sort `K` by the distances. [Answer] # J - 86 71 70 char ``` ((]/:[|@<:@%~2{::"1])(;a:,<)"0,[:,/(<,.+`|,.+/;+&.%/)"1@;@((<@,.{:)\)) ``` I'm not going to bother to explain every little detail because a lot of the code is spent syncing up the results of different functions, but here's the gist of the golf: * `;@((<@,.{:)\)` makes every possible pair of resistors, to be connected either in parallel or in series. * `[:,/(<,.+`|,.+/;+&.%/)"1@` then connects them, in parallel and in series, making a big list of possible connections. * `(;a:,<)"0,` adds in the possibility of using only one resistor by itself to approximate. * `(]/:[|@<:@%~2{::"1])` sorts the list of combinations of resistors by the pseudolog distance (`|@<:@%`) between the target and the resultant resistance from each combination. And this is how to use it: ``` rouv =: ((]/:[|@<:@%~2{::"1])(;a:,<)"0,[:,/(<,.+`|,.+/;+&.%/)"1@;@((<@,.{:)\)) # 510 rouv 100 150 220 330 470 680 1000 1500 2200 3300 4700 NB. how many? 143 10 {. 510 rouv 100 150 220 330 470 680 1000 1500 2200 3300 4700 NB. view first 10 +---------+-+-------+ |680 2200 |||519.444| +---------+-+-------+ |1000 1000|||500 | +---------+-+-------+ |150 330 |+|480 | +---------+-+-------+ |220 330 |+|550 | +---------+-+-------+ |470 | |470 | +---------+-+-------+ |680 1500 |||467.89 | +---------+-+-------+ |680 3300 |||563.819| +---------+-+-------+ |100 470 |+|570 | +---------+-+-------+ |220 220 |+|440 | +---------+-+-------+ |100 330 |+|430 | +---------+-+-------+ ``` You don't have to only view the first 10 like I did above, but this is a function and the J REPL truncates very large return values, and the full output for this example has 287 lines. You can force it all to STDOUT with something like `tmoutput toCRLF , LF ,.~ ": blah rouv blah` on Windows—drop the `toCRLF` on Linux—but `rouv` is a function and internally, all the rows exist. ## Note: The question seems to have been changed right under our noses, and now the log distance is defined as `abs(log(Rapprox/Rtarget))` instead of `abs(Rapprox/Rtarget-1)`. To correct this in my golf, we can change the `|@<:@%` to `|@^.@%`: `<:` is Decrement while `^.` is Logarithm. [Answer] # Python 3 - ~~250~~ ~~247~~ 270 bytes ``` from itertools import* import sys r=sys.argv[1:] t=int(r.pop()) p=set(map(tuple,map(sorted,product(r,r)))) a=[('+'.join(b),sum(map(int,b)))for b in p]+[('|'.join(b),1/sum(map(lambda n:1/int(n),b)))for b in p] for s in sorted(a,key=lambda b:abs(float(b[1])/t-1)):print(s) ``` Run like this: ``` python resistors.py 100 150 220 330 470 680 1000 1500 2200 3300 4700 510 ``` (that is, a space-delimited list of resistors, with the target value at the end) Output: ``` ('2200|680', 519.4444444444445) ('1000|1000', 500.0) ('150+330', 480) ('220+330', 550) ('1500|680', 467.88990825688074) ('3300|680', 563.8190954773869) [snip] ('2200+4700', 6900) ('3300+4700', 8000) ('4700+4700', 9400) ``` ~~I would say that outputting, say, `680|2200` and `2200|680` separately is still pretty clear. If this is unacceptable, I can change it, but it'll cost me bytes.~~ Wasn't acceptable. Cost me bytes. Now I sort the tuples before chucking them into the set, otherwise the solution is identical. [Answer] # Ruby 2.1, ~~156~~ 154 bytes ``` s=->(a,z){c={};a.map{|e|a.map{|f|c[e]=e;c[e+f]="#{e}+#{f}";c[1/(1.0/f+1.0/e)]="#{e}|#{f}"}};c.sort_by{|k,|(k/z.to_f-1).abs}.map{|e|puts"#{e[1]}=#{e[0]}"}} ``` ## Ungolfed: ``` s =->(a,z) { c={} a.map{|e| a.map{|f| c[e]=e c[e+f]="#{e}+#{f}" c[1/(1.0/f+1.0/e)]="#{e}|#{f}" } } c.sort_by{|k,| (k/z.to_f-1).abs }.map{|e| puts "#{e[1]}=#{e[0]}" } } ``` ## What it does: * For each value `e` in `a`; + Iterate through `a`, computing single, series, and parallel values as keys to printed values in hash `c`; * Determine distance from `z` for each key in `c`; and, * For each value `e[1]` for each key `e[0]` in `c`, print `e[1]=e[0]`. ## Sample usage: `s[[100, 150, 220, 330, 470, 680, 1000, 1500, 2200, 3300, 4700], 510]` ## Sample output: ``` 2200|680=519.4444444444445 1000|1000=500.0 330+150=480 330+220=550 470=470 1500|680=467.88990825688074 3300|680=563.8190954773869 . . . 4700+1500=6200 3300+3300=6600 4700+2200=6900 4700+3300=8000 4700+4700=9400 ``` [Answer] # JavaScript (ECMAScript 6) - 186 Characters ``` f=(R,T)=>(D=x=>Math.abs(x[3]/T-1),r={p:(x,y)=>x*y/(x+y),s:(x,y)=>x+y},[...[[x,0,0,x]for(x of R)],...[[x,y,z,r[z](x,y)]for(x of R)for(y of R)for(z in r)if(x<=y)]].sort((a,b)=>D(a)-D(b))) ``` **Input:** * An array `R` of resistor strengths; and * `T`, the target resistance. **Output:** An array of arrays (sorted by distance from `T`) each containing: * the smaller resistor's value; * the higher resistor's value (or 0 if a solitary resistor); * `p`, `s` or 0 if the resistors are in parallel, serial or solitary; and * the net resistance. **Explanation:** ``` f=(R,T)=>( // Create a function f with arguments R & T D=x=>Math.abs(x[3]/T-1), // A function D to calculate relative // distance from the target value r={p:(x,y)=>x*y/(x+y),s:(x,y)=>x+y}, // An object containing the formulae // to calculate resistance in serial and parallel solitary = [[x,0,0,x]for(x of R)], // Create an array of solitary resistors pairs = // Use Array Comprehension to create the array of [[x,y,z,r[z](x,y)] // arrays for(x of R) // for each resistor value for(y of R) // for each resistor value (again) for(z in r) // for both serial & parallel if(x<=y)], // where the first resistor value is smaller than the second [ ...solitary, // Use the spread ... operator to combine ...pairs // the two arrays ] .sort((a,b)=>D(a)-D(b)) // Sort the arrays by minimum distance // and return. ) ``` [Answer] # Julia - ~~179~~ 163 bytes ``` f(t,s)=(\ =repmat;m=endof(s);A=A[v=(A=s\m).>=(B=sort(A))];B=B[v];F=[s,C=A+B,A.*B./C];n=sum(v);print([[s P=[" "]\m P;A [+]\n B;A [|]\n B] F][sortperm(abs(F-t)),:])) ``` This works the same as the old version, but the argument in the print statement has been organised slightly differently to reduce the number of square brackets necessary. Saves 4 bytes. Absorbing the spaces vector creation into the print argument saves an extra 2 bytes. It has also switched from using "find" to get the relevant indices to using the logical form. Saves 6 bytes. Absorbing the calculation of the index vector into the adjustment of A saved another 2 bytes. Finally, replacing endof(v) with sum(v) saved 2 more bytes. Total saving: 16 bytes. Old version: ``` f(t,s)=(\ =repmat;m=endof(s);A=s\m;v=find(A.>=(B=sort(A)));A=A[v];B=B[v];F=[s,C=A+B,A.*B./C];n=endof(v);P=[" "]\m;print([[s,A,A] [P,[+]\n,[|]\n] [P,B,B] F][sortperm(abs(F-t)),:])) ``` Within the function, here's what it's doing: ``` \ =repmat # Overloads \ operator to save lots of characters m=endof(s) # Length of input s ("Stock") A=s\m # Equivalent to repmat(s,m) (see first command) B=sort(A) # Same as A but sorted - rather than cycling through # the resistors m times, it repeats each one m times v=find(A.>=B) # Identify which pairs for A,B have A>=B A=A[v];B=B[v] # Remove pairs where A<B (prevents duplicates) F=[s,C=A+B,A.*B./C] # Constructs vector containing results for single resistor, # resistors in series, and resistors in parallel n=endof(v) # equivalent to n=(m+1)m/2, gets number of relevant pairs P=[" "]\m # Construct array of blank entries for use in constructing output print([[s,A,A] [P,[+]\n,[|]\n] [P,B,B] F][sortperm(abs(F-t)),:])) # The following are the components of the argument in the print statement: [s,A,A] # Set of resistor values for resistor 1 [P,[+]\n,[|]\n] # Operator column, prints either nothing, +, or | [P,B,B] # Set of resistor values for resistor 2 (blank for single resistor) F # Contains resulting equivalent resistance [sortperm(abs(F-t)),:] # Determines permutation for sorting array by distance from Target t # and applies it to array ``` Sample output: ``` julia> f(170,[100,220,300]) 300 | 300 150 100 + 100 200 300 | 220 126.92307692307692 220 220 220 | 220 110 100 100 300 | 100 75 220 | 100 68.75 100 | 100 50 300 300 220 + 100 320 300 + 100 400 220 + 220 440 300 + 220 520 300 + 300 600 ``` [Answer] # Javascript (E6) 156 ~~162 164 186~~ **Last Edit** Assuming all resistor values > 0, you can use them for the loop condition ``` F=(t,s)=>{D=a=>Math.abs(a[1]/t-1);for(i=r=[];a=s[j=i++];r[l]=[a,a])for(;b=s[j--];)l=r.push([a+'+'+b,c=a+b],[a+'|'+b,a*b/c]);return r.sort((a,b)=>D(a)-D(b))} ``` Usage : `F(510, [100, 150, 220, 330, 470, 680, 1000, 1500, 2200, 3300, 4700])` **Ungolfed** ``` F = (t,s) => { D = a => Math.abs(a[1]/t-1); for (i=r=[]; a=s[j=i++]; r[l]=[a,a]) for(; b=s[j--];) l = r.push([a+'+'+b, c=a+b], [a+'|'+b, a*b/c]); return r.sort((a,b) => D(a)-D(b)) } ``` [Answer] # Javascript, 248 bytes ``` function r(T,L){R=[],O="";for(i in L){R.push([a=L[i],a]);for(j=i;j<L.length;)b=L[j++],s=a+b,R.push([a+"+"+b,s],[a+"|"+b,a*b/s])}R.sort(function(a,b){A=Math.abs;return A(a[1]/T-1)-A(b[1]/T-1)});for(i in R)q=R[i],O+=q[0]+"="+q[1]+"\n";console.log(O)} ``` Usage : `r(510, [100, 150, 220, 330, 470, 680, 1000, 1500, 2200, 3300, 4700]);` ### Output ``` 670|2200=519.4444444444445 1000|1000=500 150+330=480 (...such rows...) 2200+4700=6900 3300+4700=8000 4700+4700=9400 ``` [Answer] # Perl, 213 199 185 bytes **213 bytes:** ``` $t=pop;sub t{abs 1-(split/=/,pop)[1]/$t}sub S{$_[0]+$_[1]}sub P{$_[0]*$_[1]/&S}$"=',';@i=@ARGV;say for sort{t($a)<=>t($b)}grep s!(..\b(\d+)\b,?\b(\d+)?\b\))=\K(??{$2<$3})!$1!ee&&/\d$/,<{S,P}({@i},{@i})= S({@i})=>; ``` **199 bytes:** ``` $t=pop;sub t{abs 1-(split/=/,pop)[1]/$t}sub S{$_[0]+$_[1]}sub P{$_[0]*$_[1]/&S}$"=',';@i=@ARGV;say for sort{t($a)<=>t($b)}grep/(..(\d+),?(\d+)?\))/&&$2>=$3&&($_.=eval$1),<{S,P}({@i},{@i})= S({@i})=>; ``` **185 bytes:** ``` $t=pop;sub t{abs 1-$_[0]=~s!.*=!!r/$t}sub S{$_[0]+$_[1]}sub P{$_[0]*$_[1]/&S}$"=',';$i="{@ARGV}";say for sort{t($a)<=>t$b}grep{my($x,$y)=/\d+/g;$_.='='.eval,$x>=$y}<{S,P}($i,$i) S($i)> ``` Pass all available resistors as arguments. The target resistance should be the last: ``` $ perl -E 'code' R1 R2 R3 ... Rn target ``` ### How it works (old code) * Define subroutines `S` and `P` to compute the sum and parallel values of two resistors. * Set [`$"`](http://perldoc.perl.org/perlvar.html) to "," to interpolate `@ARGV` inside the [`glob`](http://perldoc.perl.org/functions/glob.html) operator * `<{S,P}({@i},{@i})= S({@i})=>` generates a cartesian of all possibilities: S(100,100), S(100,150), S(100,220), ... P(100,100), P(100,150) ... S(100), S(150) ... * Combine `s///ee` with `grep` to evaluate the equivalent resistances and filter out unwanted repeats (performed by `(??{$2<$3})` and `/\d$/` * `sort` by fitness computed in subroutine `t` ### Changes in new code * Avoid use of `s///ee`, use shorter regex with conditional checking and `eval` inside `grep` * Replace repeats of `"{@i}" with`$i` * Introduce `$x`, `$y` instead of `$2`, `$3` * Replace `split/=/,pop` with `$_[0]=~s!!!r` * No need for trailing `;` * `eval;` is equivalent to `eval $_;` * Add `=` along with `eval`-ed answer instead of declaring it up front ### Output: `P` represents resistors in parallel, `S` represents resistors in series. ``` P(2200,680)=519.444444444444 P(1000,1000)=500 S(330,150)=480 S(330,220)=550 S(470)=470 P(1500,680)=467.889908256881 P(3300,680)=563.819095477387 S(470,100)=570 S(220,220)=440 S(330,100)=430 P(4700,470)=427.272727272727 P(4700,680)=594.052044609665 P(1500,1000)=600 P(3300,470)=411.405835543767 P(1000,680)=404.761904761905 S(470,150)=620 P(2200,470)=387.265917602996 S(220,150)=370 S(330,330)=660 P(1500,470)=357.868020304569 S(680)=680 P(680,680)=340 P(2200,1000)=687.5 S(330)=330 S(470,220)=690 S(220,100)=320 P(1000,470)=319.727891156463 P(4700,330)=308.349900596421 S(150,150)=300 P(3300,330)=300 P(2200,330)=286.95652173913 P(680,470)=277.913043478261 P(1500,330)=270.491803278689 P(1500,1500)=750 P(3300,1000)=767.441860465116 S(150,100)=250 P(1000,330)=248.12030075188 S(680,100)=780 P(470,470)=235 P(680,330)=222.178217821782 S(470,330)=800 S(220)=220 P(4700,220)=210.162601626016 P(3300,220)=206.25 S(100,100)=200 P(2200,220)=200 P(4700,1000)=824.561403508772 P(470,330)=193.875 P(1500,220)=191.860465116279 S(680,150)=830 P(1000,220)=180.327868852459 P(680,220)=166.222222222222 P(330,330)=165 S(150)=150 P(470,220)=149.855072463768 P(4700,150)=145.360824742268 P(3300,150)=143.478260869565 P(2200,150)=140.425531914894 P(1500,150)=136.363636363636 P(330,220)=132 P(1000,150)=130.434782608696 P(2200,1500)=891.891891891892 P(680,150)=122.89156626506 S(680,220)=900 P(470,150)=113.709677419355 P(220,220)=110 P(330,150)=103.125 S(100)=100 P(4700,100)=97.9166666666667 P(3300,100)=97.0588235294118 P(2200,100)=95.6521739130435 P(1500,100)=93.75 P(1000,100)=90.9090909090909 P(220,150)=89.1891891891892 P(680,100)=87.1794871794872 P(470,100)=82.4561403508772 S(470,470)=940 P(330,100)=76.7441860465116 P(150,150)=75 P(220,100)=68.75 P(150,100)=60 P(100,100)=50 S(1000)=1000 S(680,330)=1010 P(3300,1500)=1031.25 S(1000,100)=1100 P(2200,2200)=1100 P(4700,1500)=1137.09677419355 S(680,470)=1150 S(1000,150)=1150 S(1000,220)=1220 P(3300,2200)=1320 S(1000,330)=1330 S(680,680)=1360 S(1000,470)=1470 P(4700,2200)=1498.55072463768 S(1500)=1500 S(1500,100)=1600 S(1500,150)=1650 P(3300,3300)=1650 S(1000,680)=1680 S(1500,220)=1720 S(1500,330)=1830 P(4700,3300)=1938.75 S(1500,470)=1970 S(1000,1000)=2000 S(1500,680)=2180 S(2200)=2200 S(2200,100)=2300 S(2200,150)=2350 P(4700,4700)=2350 S(2200,220)=2420 S(1500,1000)=2500 S(2200,330)=2530 S(2200,470)=2670 S(2200,680)=2880 S(1500,1500)=3000 S(2200,1000)=3200 S(3300)=3300 S(3300,100)=3400 S(3300,150)=3450 S(3300,220)=3520 S(3300,330)=3630 S(2200,1500)=3700 S(3300,470)=3770 S(3300,680)=3980 S(3300,1000)=4300 S(2200,2200)=4400 S(4700)=4700 S(3300,1500)=4800 S(4700,100)=4800 S(4700,150)=4850 S(4700,220)=4920 S(4700,330)=5030 S(4700,470)=5170 S(4700,680)=5380 S(3300,2200)=5500 S(4700,1000)=5700 S(4700,1500)=6200 S(3300,3300)=6600 S(4700,2200)=6900 S(4700,3300)=8000 S(4700,4700)=9400 ``` ]
[Question] [ ## Task You are playing [Hangman](https://en.wikipedia.org/wiki/Hangman_(game)), and your opponent uses a simple but effective strategy: Each turn, from the remaining letters, they guess the letter that appears most frequently across all possible words. When multiple letters appear with the same maximum frequency, your opponent selects randomly among them. That is, your opponent knows which dictionary (list of words) you've chosen your word from, and has computed a table showing how many times each letter of the alphabet appears in this dictionary. Your opponent always chooses letters with higher frequency counts before letters with lower frequency counts. Your goal is to write a program that will select a word that maximizes their average number of guesses. This is code golf. ## Input / Output The input will be a list of words in any convenient format, per standard site IO rules (comma delimited string, array, lines of a file, etc). The output will be a single word from that list that maximizes your opponent's average number of guesses. If there is more than one such word, you may return any one of them. ## Worked Example If the input word list is: ``` one wont tee ``` The letter frequency table will be: ``` ┌─┬─┬─┬─┬─┐ │e│t│o│n│w│ ├─┼─┼─┼─┼─┤ │3│2│2│2│1│ └─┴─┴─┴─┴─┘ ``` Your opponent will always guess `e` first, since it occurs most frequently. Their second, third, and fourth guesses will be split randomly among the letters `t`, `o`, and `n`, and `w` will always be guessed last. Thus the word `wont` will always be completed last, on the 5th guess, and is the sole correct answer for this word list. ## Notes * Words will contain only the 26 letters `a` through `z`. * If you want, you can use the uppercase alphabet instead. * When there is more than one correct answer, you may return any of them. If you want, you can return all of them, but this is not required. ## Test Cases Each test case consists of two lines: 1. An input word list of space-separated words. 2. The expected output. This will be a single word when there is only one correct answer, and a space-separated list when there is more than one. Note that your program only needs to return one correct answer when there are multiple correct answers. ``` one wont tee wont aaa bbb ccc aaa bbb ccc oneword oneword thee lee thee tee lee tee lee three eon one holt three holt xeon threes eon one holt threes xeon threes eon one holt apple mango george any fine fine ``` [Answer] # [Python 2](https://docs.python.org/2/), 60 bytes ``` lambda l:min(l,key=lambda x:sorted(map(`l`.count,set(x)))+l) ``` [Try it online!](https://tio.run/##hZDRaoUwDIbv8xS5bJkc2C4F32RwTlqjltW21Ir69C6KO3BgYxdN/nz9k5SmrQwxfOxd87l7Gk1L6OvRBeWrL96aC631FHPhVo2U1MM/bjbOoVQTF7Vqrd@83pfBecb3GtCFVGGci8Q7NphpuQuai9K3KXknufoXAqbsQsFOCdAy8hy4x8C4ROGFGQ4BQERojEFr7YsG8S4xt88MZWBGL42HkPKnurLgLJKj7JI1Q/TlQqeE9bg5wfSLafrbgJSSfM1IoY/Yc8w9I4UNOxcYziAPRzJorD0OkAH4Bg "Python 2 – Try It Online") ### Explanation The idea is much like every other answer. In every word, we compute the frequency of each character. Then we take the word whose least frequent character occurs most often. In the code, we sort the array as opposed to finding the minimum. Here is an example to show how this works: `Input: thee lee baa`. For each word, we compute a frequency table (duplicates are ignored): `[(1, 1, 4), (1, 4), (1, 2)]`. After sorting, the lexiocgraphically smallest list is `(1, 1, 4)`, therefore the answer is `thee`. There is also an edge case to consider: `Input: a bc`, which gives the following frequency table: `[(1), (1, 1)]`. The lexicographically smallest list would be `(1)`, which is incorrect since the second list contains more `1`s. I'll leave out the specifics of how the code resolves this issue [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~25~~ ~~16~~ ~~13~~ ~~11~~ ~~13~~ 12 bytes -3 thanks to @pxeger -2 thanks to @ovs +2 for bug fix (for input `acb abc cb` and `aa ab bcc bcc`) -1 for another bug fix, noticed by @ovs ``` ΣISТWQÏ¢O}θ ``` [Try it online!](https://tio.run/##yy9OTMpM/f//3GLP4MMTDi0KDzzcf2iRf@25Hf//RyslJiYlJScnK@koKKWkgBixAA "05AB1E – Try It Online") # Legacy version, 10 bytes, thanks to [@ovs](https://codegolf.stackexchange.com/users/64121/ovs) ``` ΣIS.m¢O(}н ``` [Try it online!](https://tio.run/##MzBNTDJM/f//3GLPYL3cQ4v8NWov7P3/P1qpIjU/T0lHQakkoyg1tRjEggrk56WCqIz8nBIQnVhQkAMWyE3MS88HMdJT84vSwUKJeZUgKi0TqCUWAA "05AB1E (legacy) – Try It Online") [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), ~~35~~ ~~33~~ ~~28~~ ~~27~~ 20 bytes -2 bytes from shuffling things around -5 bytes from @Traws' improvement -1 byte from @bstrat's improvement -7 bytes from new approach ``` {*>+/'x#=/&/\#'=,/x} ``` [Try it online!](https://ngn.codeberg.page/k#eJyNkG1PwjAQx9/fp7gMI6BA1RdituAXwSVso3sIo51rkS1EP7t37SAhUeOb3sP/f9f2l4enu9d7Me5GK3Er3kbj1Ux0nwA2PN2s+682zBGxizZ6F002eVLVURf1UTuN2bOeBFrJIAqOWlkKVspgOlSxk5MkoX6apnRmWcYqt1ic8exRt1uSzpkfsqXkpbXf5qo48sqVwP1hoHWC1Movo7PUtfXj7cXXeYNrmb/85r8D9J2mqbncJ6rQFAup24IbierpzCvlHutiDCCgtLYxoRCZ3spC1/nC2CTbyS4raYNcZHov3g/S2EorI54elw/LpUjlVn5U9bzXh3bOPrptrpuGXqKsM708A1CFzB6JDHACQLCR6COxv8phIH6JwJiRyLqEynM1RHAMkAAgX8OfH1ouBSaFntMPJvO7AR1AdPjQw0NChwwM+PgGnMPXrg==) Modeled after [@xash's J answer](https://codegolf.stackexchange.com/a/217079/98547). * `#'=,/x` build a dictionary mapping characters to the number of times they appear across the entire input * `=/&/\` identify the least frequent character(s) * `+/'x#` sum up the number of times the most infrequent characters appear in each word of the input * `*>` filter the input down to the first word with the most infrequent character(s) [Answer] # [Stax](https://github.com/tomtheisen/stax), ~~20 18 10~~ 9 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ·╦Eà3ΩQù» ``` [Run and debug it](https://staxlang.xyz/#p=facb458533ea5197af&i=%5B%22one%22,+%22wont%22,+%22tee%22%5D%0A%5B%22aaa%22,%22bbb%22,%22ccc%22%5D%0A%5B%22oneword%22%5D%0A%5B%22thee%22,%22lee%22%5D%0A%5B%22tee%22,%22lee%22%5D%0A%5B%22three%22,%22eon%22,%22one%22,%22holt%22%5D%0A%5B%22xeon%22,%22threes%22,%22eon%22,%22one%22,%22holt%22%5D%0A%5B%22xeon%22,%22threes%22,%22eon%22,%22one%22,%22holt%22,%22apple%22,%22mango%22,%22george%22,%22any%22,%22fine%22%5D&m=2) ~~Explanation coming next year™.~~ Happy new Year! -8 bytes from recursive using the surprisingly fitting `multi-anti-mode` builtin. -1 more byte from recursive with an insane compression hack. Replacing `H` from [this version](https://staxlang.xyz/#c=%24%7C%21x%7Bn%7C%26%25oH&i=%5B%22one%22,+%22wont%22,+%22tee%22%5D%0A%5B%22aaa%22,%22bbb%22,%22ccc%22%5D%0A%5B%22oneword%22%5D%0A%5B%22thee%22,%22lee%22%5D%0A%5B%22tee%22,%22lee%22%5D%0A%5B%22three%22,%22eon%22,%22one%22,%22holt%22%5D%0A%5B%22xeon%22,%22threes%22,%22eon%22,%22one%22,%22holt%22%5D%0A%5B%22xeon%22,%22threes%22,%22eon%22,%22one%22,%22holt%22,%22apple%22,%22mango%22,%22george%22,%22any%22,%22fine%22%5D&m=2) with `E`(a lower codepoint), results in -1 byte due to packing magic. ## Explanation ``` $|!x{n|&%oE $ join the input together |! get the rarest characters(anti-mode) x push the input again { o and order by the following: n|& intersect with the anti-mode % and take the length E push all the elements onto stack implicitly print the last element ``` [Answer] # [J](http://jsoftware.com/), 32 bytes ``` {.@\:(~.(#~<./=])#/.~)@;+/@e."1> ``` [Try it online!](https://tio.run/##jYyxCsIwEEB3vyK0Q1vUVNe0lYDg5OSscGm8JkpNSg1UEfrrMe3i6nDw3r3j7j6iSUMqRhKyIhvCwqwp2Z@OB/@h/MzSkabxWNK8umRxTseMF8ucI422O58tVMVQasuLZqGINQiDNQ4cYlAhBNR1DVLKYGWog@2vAZ1GhHa@cT/SfWC0BqY32rYuLF@Tz@X5bwLRdS3CQxhlQaHtFYIwb2huBv0X "J – Try It Online") * `;` words razed to letters * `#/.~` number of occurrences of each letter * `~.` the letters deduplicated * `(#~<./=])` take only the most infrequent letters * `+/@e."1>` how many of these letters occur in each word? * `{.@\:` sort the words based on the amount and return the first one (the one with most infrequent letters) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 38 bytes ``` WS⊞υι≔Eβ№⪫υωιη≔EυLΦ⌕Aη⌊Φηλ№ι§βλζ§υ⌕ζ⌈ζ ``` [Try it online!](https://tio.run/##VY5BagMxDEX3PoWXMkxPkNUQKCQ0EOgJ3ESxBR558NjNdC7vSA1ZZCMJvc@TLtGXS/ap93ukhBYOPLf6XQtxAOfsuS0R2mDJ7cy4LBQYTn6Gn8Huc@MKx0ys/O40IyW@BwV9IYca4ZNSxSKNr2NKEAd7IqapTS8im@RU8TTTYMd64Cuuek2Jsk30Z3muwgvKBXXCJkK//gs3ze56XzGzqbEgLkbHzGhiTtX4eU5oJs8hm4C5BDSe/8yNJNA/ftMD "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` WS⊞υι ``` Input the words. ``` ≔Eβ№⪫υωιη ``` Get frequencies for all of the letters. ``` ≔EυLΦ⌕Aη⌊Φηλ№ι§βλζ ``` Find the letters with the lowest positive frequencies, then for each word count how many of those letters are contained. ``` §υ⌕ζ⌈ζ ``` Output the word with the highest count. Previous 84-byte longhand solution: ``` WS⊞υι≔υθ≔Eβ№⪫υωιη≔Eυ⁰ζW⌈η«≔⌕AηιεFε§≔ηκ⁰UMε§βκ≔EθΦκ¬№εμδUMζ⁺κ⎇§δλLεLΦε№§θλμ≔δθ»§υ⌕ζ⌈ζ ``` [Try it online!](https://tio.run/##XZBNbsMgEIXX4RQsQaJS911ZkSKlaipL7QVoPAEUDDaGxnHVs7uDf5q0GzTMfG/e0xy1DEcv7ThetLFA2d41Kb7FYJxinNMydZolQQ1/IkXXGeXyr739DrJhH4JufXKRPXszzS88K/DRf0EcPWJ3wO5id5C9qVPNNHp9kc3C7oyrCmuZzmsEBeQ3Jx8oA05npIh7V0GfiXNeigAabH1dS1cxEHQFMNuZ5/FdjFbQnbERAkPtq49sTo@qmvMcu/q3bxC0tKnL@DsEJ8OVrfsrQS0qXsCpqDHfb7k4wHqbVdDOgsnpPlg1n/WblHj7G55y1jnCeqthEo5jD96RqANAR3LpHRDtbSSyaSwQTK48UeCDAiLdlZwMAuPDp/0B "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` WS⊞υι ``` Input the words. ``` ≔υθ ``` Make a copy of the list. The letters will be removed from these words as they are guessed. ``` ≔Eβ№⪫υωιη ``` Get frequencies for all of the letters. ``` ≔Eυ⁰ζ ``` Start off with 0 guesses for all of the words. ``` W⌈η« ``` Repeat while there are still letters to guess. ``` ≔⌕Aηιε ``` Find the positions of the most frequent letters. ``` Fε§≔ηκ⁰ ``` Remove them from the list of frequencies. ``` UMε§βκ ``` Get the letter characters at those positions. ``` ≔EθΦκ¬№εμδ ``` Make a temporary copy of the words with all of those letters removed. ``` UMζ⁺κ⎇§δλLεLΦε№§θλμ ``` For words which still have some letters left, count all of the letters as guesses, otherwise just count the number of matching letters. This is the minimum number of guesses rather than the average but the sort order is the same. ``` ≔δθ ``` Update the list of words with the removed letters. ``` »§υ⌕ζ⌈ζ ``` Print the word that took the most guesses. [Answer] # [R](https://www.r-project.org/), ~~111~~ 110 bytes -1 byte thanks to Giuseppe ``` function(s)s[which.max(colSums(outer(names(x<-table(unlist(strsplit(s,""))))[x==min(x)],s,Vectorize(grepl))))] ``` [Try it online!](https://tio.run/##nY4xbsMwDEX3niLQRANuT1CfokCXIIOs0LYAiTREGlZ6eUeSg3avhk/i8ZFQOqbhmDZy6plAOrnui3fLR7QZHIevLQrwppiAbESB/PmudgwIGwUvCqJJ1uBL0xvTlXfNwxA9Qe5uvfTf6JST/0GYE66hCrdjAgeGCU1vFGvuTFqW39rAWlvQOI4lnXMnr/rO6W5eki5tMZTsflFqDJlKnucXDn@Hc5tcTlFq9wLNvfxDLtWua2ggWpq5NjNymhuy9Khl8lR/eTwB "R – Try It Online") Computes the table of number of occurrences of each letter, then the vector of letter(s) which occur the least often. These rare letters will be tried last (in random order), so we pick the word which maximises the number of distinct rare letters. If there are several optimal words, this returns the first one. We can return all of them [at a cost of 1 byte](https://tio.run/##nY4xbsMwDEX3nCLQRAPKDepTFOgSZJBV2hEgk4Yow3Iu71Jy0O7V8Ek8PhJKx9gf40o@ByYQu/ee4@c6C/CaMQG5GQXKxy27ISKsFINkkJxkiUEba0yn7176fg4EpXtYsV/oM6fwQpgSLrEKct/VcAX27nGM4MEwobEmY82NKeudSxs45xQNw6DpvT951TdO3@Yt5WdbjJrdL0qNIZPmef7J8e9waZPrKUrt3qC513/IWt2yxAZmRxPXZkJOU0OO9lrGQPWXxw8). [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~60~~ 56 bytes ``` #~MaximalBy~Union/*Map[c=Counts[Join@@#]]/*Count[Min@c]& ``` [Try it online!](https://tio.run/##jY7BaoRAEETvfkWjsAdJ2C/YINlbQAhITuKhp9PqgHbL2GF3CfHXzcwmhxxzaKhXVTQ1o408o3nCvT/txVbj1c84Pd@2N/Eqx7LGpaXTWT/E1vZFvVRV0XXH8u60dWTqDvtr8JGKx6e@Oo8YkIzDGouHqmwsZkOzTN62hlC2zyxXYbioGBhz/pDliAjOOSCihDG@aHhPMs5jmH5a9keOIQKrQHo16mTJvSbjHq3/zgCXZWKYUQaFgTUMDCg36L38TgN04IjS5dnX/g0 "Wolfram Language (Mathematica) – Try It Online") Input a list of character lists. [Answer] # [Ruby 2.7](https://www.ruby-lang.org/), 61 bytes ``` ->w{w.min_by{_1.chars.uniq.map{|c|(w*"").count c}.sort<<1e9}} ``` [Try it online!](https://tio.run/##hZDfSsUwDIfvfYpQEFSw4KVw5ouISBqzP7A1O21HHduefa5zPUdB8KKQX76vIcQNZlzLYn18iVPUXWPfzTjNfvaaanReD7Y56w77aab5Lj4oda9JBhuAFu3FhdPpiZ@XZe2hfL2NSixDlA0HZvUGRQEqRXVzcEQEYwwQ0YG3zoVuv6O4j4PklGmomaG9zE3xyn6jn6R2G2OxkHarpQ2HtJfZ@kzCrvq/3G/yrw3Y9y1Dh7YSqFhcxYB2hLKxebW9vF4D0IAhSi/fw6j1Cw "Ruby – Try It Online") Expects an array of words. Outputs the one with most rarest chars. TIO uses an older version of Ruby, whereas in Ruby 2.7, we've numbered parameters, which saves two bytes. [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-m`](https://codegolf.meta.stackexchange.com/a/14339/), 29 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ˬx@¬Ê/U¬èX p VíU nÏÎ-XgÃÎg1 ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LW0&code=CsuseECsyi9VrOhYIHAKVu1VIG7Pzi1YZ8POZzE&input=WwpbIm9uZSIsIndvbnQiLCJ0ZWUiXSwKWyJhYWEiLCJiYmIiLCJjY2MiXSwKWyJvbmV3b3JkIl0sClsidGhlZSIsImxlZSJdLApbInRlZSIsImxlZSJdLApbInRocmVlIiwiZW9uIiwib25lIiwiaG9sdCJdLApbInhlb24iLCJ0aHJlZXMiLCJlb24iLCJvbmUiLCJob2x0Il0sClsieGVvbiIsInRocmVlcyIsImVvbiIsIm9uZSIsImhvbHQiLCJhcHBsZSIsIm1hbmdvIiwiZ2VvcmdlIiwiYW55IiwiZmluZSJdCl0KCgpbd29udCwKYWFhIGJiYiBjY2MsCm9uZXdvcmQsCnRoZWUsCnRlZSBsZWUsCnRocmVlIGhvbHQsCnRocmVlcywKZmluZQpd) Not a great answer but a bit different approach. `ˬx@¬Ê/U¬èX p` \$\to\$ map each word by summing the weight of each letter. * Weight is number of all letters divided by occurrences of letter raised to a power (\$2\$) we can increase the power to get a more precise output at the cost of one byte. `VíU nÏÎ-XgÃÎg1` \$\to\$ sorts the input based on weights [Answer] # [R](https://www.r-project.org/), 100 bytes ``` function(s,S=colSums)s[order(S(t(a<-matrix(sapply(letters,grepl,s),,26))*(b=S(a))!=min(b[b>0])))][1] ``` [Try it online!](https://tio.run/##nZAxbsMwDEX3niLVRAYqkGbIFOcSHg0PlCI7BmTSkBQkOb0ryUG7d/kkHp8IQmEdmnW4s02TMETdNlZ8e58jxk7C1QVoIQGdv2ZKYXpCpGXxL/AuJReiHoNbvI6o9fGEuAfTtECIn808MZjOXA49Ivbdd78OYEEJO6VVciUfwkkhftQBEWVkjMlprd140R/5CvWW0q0@9DnxF4XKnHDObf1N/N/iZ53sNjGW7g2qu/uHnGv5hApm4lFKMzoJY0XEr1KGicuV6w8 "R – Try It Online") **How?** - ungolfed version: ``` f=function(s){ a<-sapply(letters,grepl,s) # a = matrix indicating which letters (columns) are present in which words (rows) a<-matrix(a,,26) # (force 'a' as a matrix in case there was only one word in the input) b<-colSums(a) # b = for each letter, the count of the words that it is in c<-t(a)*b # c = replace 'TRUE' elements of 'a' with the word counts from 'b' d<-colSums(c==min(b[b>0])) # d = the number of different letters in each word with the lowest overall nonzero word count s[which.max(d)] # output the (first) word that maximises d } ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 15 bytes ``` .Mms/L.m/sQbsQZ ``` [Try it online!](https://tio.run/##K6gsyfj/X883t1jfRy9XvzgwqTgw6v//aKWK1Pw8JR0FpZKMotTUYhALKpCflwqiMvJzSkB0YkFBDlggNzEvPR/ESE/NL0oHCyXmVYKotEygllgA "Pyth – Try It Online") ]
[Question] [ ### Introduction We have 22 Collatz conjecture-related challenges as of October 2020, but none of which cares about the restrictions on counter-examples, if any exists, to the conjecture. Considering a variant of the operation defined in the conjecture: $$f(x)= \cases{ \frac{x}{2}&for even x \cr \frac{3x+1}{2}&for odd x }$$ [The Wikipedia article](https://en.m.wikipedia.org/wiki/Collatz_conjecture) suggests that a modular restriction can be easily calculated and used to speed up the search for the first counter-example. For a pair of \$k\$ and \$b\$ where \$0\le b\lt2^k\$, if it is possible to prove that \$f^k(2^ka+b)<2^ka+b\$ for all sufficiently large non-negative integers \$a\$, the pair can be discarded. This is because if the inequality holds for the counter-example, we can find a smaller counter-example from that, contradicting the assumption that the counter-example is the first one. For example, \$b=0, k=1\$ is discarded because \$f(2a)=a<2a\$, while \$b=3, k=2\$ is not because \$f^2(4a+3)=9a+8>4a+3\$. Indeed, for \$k=1\$ we only have \$b=1\$ and for \$k=2\$, \$b=3\$, to remain (survive) after the sieving process. When \$k=5\$, though, we have 4 survivors, namely 7, 15, 27 and 31. ~~However, there are still 12,771,274 residues mod \$2^{30}\$ surviving, so just still about a 100x boost even at this level~~ ### Challenge Write a program or function, given a natural number \$k\$ as input, count the number of moduli mod \$2^k\$ that survives the sieving process with the operation applied \$k\$ times. The algorithm used must in theory generalize for arbitrary size of input. The sequence is indeed [A076227](https://oeis.org/A076227). ### Examples ``` Input > Output 1 > 1 2 > 1 3 > 2 4 > 3 5 > 4 6 > 8 7 > 13 8 > 19 9 > 38 10 > 64 15 > 1295 20 > 27328 30 > 12771274 ``` ### Winning criteria This is a code-golf challenge, so the shortest submission of each language wins. Standard loopholes are forbidden. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 18 [bytes](https://github.com/abrudz/SBCS) ``` +/∧/¨1<×\¨.5+,⍳⎕/2 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkGXGlAsvq/tv6jjuX6h1YY2hyeHnNohZ6pts6j3s2PerfqG/2v/Z92aAWQZ2gGAA "APL (Dyalog Unicode) – Try It Online") A full program. Fails to compute the answer for \$k>15\$ due to system limitations (rank of intermediate array). ### How it works If we call the \$\frac{x}{2}\$ the \$D\$-step and \$\frac{3x+1}{2}\$ as the \$U\$-step, it is known that each residue class \$0 \dots 2^k-1\$ modulo \$2^k\$ corresponds to exactly one \$UD\$-sequence of length \$k\$. In the original formula, the coefficient of \$a\$ is multiplied by \$\frac32\$ for the \$U\$-step, and \$\frac12\$ for the \$D\$-step, and it suffices to count the \$UD\$-sequences where the coefficient never drops under 1. The program computes this by generating all length-\$k\$ sequences of 0.5 and 1.5 (skipping the \$UD\$ part), and counts the ones where the multiplicative scan `×\` gives all numbers greater than 1. ``` +/∧/¨1<×\¨.5+,⍳⎕/2 ⍝ Full program; input: k ⎕/2 ⍝ k copies of 2 ,⍳ ⍝ indices in an array of shape 2 2 ... 2 ⍝ which generates all binary sequences of length k .5+ ⍝ Add 0.5 to get all sequences of 0.5 and 1.5 ×\¨ ⍝ Product scan 1< ⍝ Test if each number is greater than 1 ∧/¨ ⍝ ... for all numbers in each sequence +/ ⍝ Count ones ``` [Answer] # [Python 3](https://docs.python.org/3/), 154 bytes ``` lambda k:sum(min(g(2**k,b,q+1)for q in range(k))>=(2**k,b)for b in range(2**k)) g=lambda x,y,z:z and g(*(x+y)%2and(3/2*x,(3*y+1)/2)or(x/2,y/2),z-1)or(x,y) ``` [Try it online!](https://tio.run/##RY7RjsIgEEWfy1eQJpvMVFa3oG41qV@xj/tCldamtkXEbNH47V10cSWBnGHunTva2X3fibHMv8eDbIudpM36dG6hrTuogCdJwwp2nKRY9oYead1RI7tKQYO4yUP/0StevfsvIqnyMHFgjl3WFyq7Ha0ggWHi8I37CsSMJwMDkTifMOPYGxhmnDmP7PKePmrmcPzZ1wdFv8xZrUlkjfNvJJnPzGkrNdSdZQ84WTP1t9bMb6PPFnB60ofaQryJ0a8URdp4MZRxCVd5Q@@/liDxRkENWm2t2tFrccPYS9WwVdrekwqjZDOm9H42NCX8n0QgTuaBBFkEmpNloIx8Ph2CZE9ckdXTk5H04w@Xc5IugoCvFr8 "Python 3 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes ``` Ø.ṗ+.×\€ḞẠ€S ``` [Try it online!](https://tio.run/##y0rNyan8///wDL2HO6dr6x2eHvOoac3DHfMe7loAZAT/f9S49XA7kPUfAA "Jelly – Try It Online") Port of [Bubbler's approach](https://codegolf.stackexchange.com/a/213994/68942), which is really clever and seems to be unbeatable with a straightforward approach lol. Make sure you upvote that answer! ## Explanation ``` Ø.ṗ+.×\€ḞẠ€S Main Link Ø. [0, 1] ṗ Cartesian product; gives all k-length binary sequences +. Add 0.5 € For each sequence of 0.5, 1.5 ×\ Take the cumulative products Ḟ Floor (if it's less than 1, this returns 0; otherwise, it returns a positive/truthy value; 1 isn't a possible product at least for k up to a billion) € For each sequence Ạ 1 if they're all truthy (so all are greater than 1), 0 otherwise S Sum (counts the number of truthy results) ``` -1 byte thanks to Jonathan Allan with the observation that 1 is not a possible product (in practice up to like a billion, at least), so checking >=1 and >1 are the same, and you can do the former with floor, saving a byte. [Answer] # [Python 3 (PyPy)](http://pypy.org/), 49 bytes Port of [Bubbler's APL answer](https://codegolf.stackexchange.com/a/213994/64121). ``` f=lambda n,p=1:n<1or(p>2)*f(n-1,p/2)+f(n-1,p*3/2) ``` [Try it online!](https://tio.run/##LcexDsIgFEbh3af4l6aAEAvEpbF9EeOAQZTEXm5IF54eO7icfIfb/inkDTduvaflG7ZnDCDNi53pZksVvDqpkiBjNV@cPP@p/DE9lYqMTLirGuj9ElbDWnnkquEmDT895hPANdMuxsFFmBVDHDFAZI0kspSy/wA "Python 3 (PyPy) – Try It Online") --- # [Python 2 (PyPy)](http://pypy.org/), ~~138~~ ~~136~~ 134 bytes A (slow) golf of the [C implementation](https://tio.run/##hZPbboMwDIbv8xRep1aJaCcIPQrIk0yaqkJbJMJQgO6i6rMzh3aUXTiNEHbs/7PjIA6LQ7EvT133npeHok0ziOsmzb8/zor9D5WNjbEWnfXyq4G6NZf8ktV8iJg5DL4e@QVu0IdK3u2xkoKxK2OA6@ecFxl/43oWCJjNgGuVFFoIeOTtyo/c2PQVjJdw4wVCqSAC7SW6d25PaVbUmdUplVjF3dz69EOFxXSMHawqa1pTgh@NcpVMEnvAZ/rZ4BEYJseBdRwHc5ywN5X08H0f7@9A3kjuaRKIGMMm9nb0Pi@5uPYFKoORI59MZQoLBdP0s5zMAZGhpt9v8bGOwDI0JglMurGQwEI3tiSwpRtbEdjKja0JbO3GNgS2cWNbAtu6sR2B7dxY4FPf238BUpcZvLhNSXWULzqGFBj24Pgn8iN267pf) given on the [OEIS page](https://oeis.org/A076227). ``` f=lambda k,r=0,m=1,w=1,q=0:f(k,r+r%2*-~r>>1,r%2*2*m+m>>1,w,q)if(w<=m)>m&1else m>=w and(q==k or sum(f(k,x,m*2,w*2,q+1)for x in(r,r+m))) ``` [Try it online!](https://tio.run/##FY3BDoIwGIPvPkUv6AY/CZvxYtxexHjAwHSRf8LUTC6@Oo5Dk/Zr0o7z@/4Muh7ncV4WZ4aWr12LB0XTEBtFKWsyzdGJzKpY6LL@RWsVrVaXXPEaEk3SO5FOhqXlreqHVw@2JqENnZiMeeAZ8fqwWHe@xKWmlDVVSrrcfOGDiPmApZTLSnwmiG249UIRlJKocFYHgm4I@@Zy3ABj9OGNXaE71BZFt0MB4QlO@LzyBw "Python 2 (PyPy) – Try It Online") PyPy is used here because this is just annoyingly slow in CPython. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 13S;Iã€ηP1›PO ``` Port of [*@Bubbler*'s APL answer](https://codegolf.stackexchange.com/a/213994/52210), so make sure to upvote him! (This results in `0` for \$k=0\$.) [Try it online](https://tio.run/##yy9OTMpM/f/f0DjY2vPw4kdNa85tDzB81LArwB8oaAAA) or [verify all test cases \$n\leq15\$](https://tio.run/##yy9OTMpM/W9o6upnr6TwqG2SgpL9f0PjYGu/w4sfNa05tz3A8FHDrgD//zr/AQ). **Explanation:** ``` 13S # Push 13 as a list of digits: [1,3] ; # Halve each: [0.5,1.5] Iã # Take the cartesian product of this pair with the input-integer € # Map over each inner list: η # And get all its prefixes P # Take the product of each inner-most prefix 1› # Check for each value if it's larger than 1 (1 if truthy; 0 if falsey) P # Check if an entire inner-most list is truthy by taking the product O # Sum the list, to get the total amount of truthy values # (after which this sum is output implicitly as result) ``` Some equal-bytes alternatives for `13S;` could be `3ÅÉ;`; `₂€;;`; `₂S4/`; etc. [Answer] # [Haskell](https://www.haskell.org/), 45 bytes ``` (!1) n!p|p<1=0|n<1=1|d<-n-1=d!(p/2)+d!(p*1.5) ``` [Try it online!](https://tio.run/##FcVBDsIgEADAu69YEg8gBdkmvRV/0Be0PZBWlEg3G@uRt0v1MvMM@@uec41@qlKgOpHgwj16V@gnlrU3ZNCvQvK1Vfr/BW2n6hYSgYct8ABySmBuwO9EH5kaiJCUgjOMaC26WesRu6Z1c/0uMYfHXs3CfAA "Haskell – Try It Online") À la Bubbler. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~72~~ \$\cdots\$ ~~66~~ 65 bytes Saved ~~3~~ ~~6~~ 7 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!! ``` f(n){n=s(n,1.);}s(n,p)float p;{n=n--?(p>2)*s(n,p/=2)+s(n,p*3):1;} ``` [Try it online!](https://tio.run/##XVHRaoMwFH33Ky5CIdHr2sS2rsvsHsa@YsoQjZuwpaJ5kBW/3V2tlXbCNSfn5Bxyb/LgM8@HoWSGn03cMoPigat@BDUvv0@ZhVqRYoLghdVHyb1JWseS@xPyQv4kVD9UxsJPVhnGnbMD9I2E1a39MO8pxHAWCBIhRNgi7BD2CBHCI8IBQWyoiJO0hpteLX7d1Tq3ulgSbkPIKwgJCggJ74kS8jDGRKEcRRlFVNs5L//KGg@aS5SbdG8y6Q6vVDsX4XYfurOjPDVsvEVlCt2Ra6Nm@Axt9atPJbvej69nwlsYBb4/neZwmce1J0NJ81wmPVV3siV5fI17VhO7DOO/rW7oSMncVQHBEei/ahNDTRkEi9SxjmObzoG90w9/ "C (gcc) – Try It Online") Using [Bubbler](https://codegolf.stackexchange.com/users/78410/bubbler)'s method from his [APL answer](https://codegolf.stackexchange.com/a/213994/9481). # [C (gcc)](https://gcc.gnu.org/), ~~175~~ \$\cdots\$ ~~138~~ 135 bytes Saved a whopping 29 bytes thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs)!!! Saved ~~4~~ 7 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!! ``` f(n){n=s(1,0,1,0,n);}s(m,r,l,p,q)long m;{for(;~m&m>0;)r-=r&1?m+=m/2,~r/2:(m/=2,r/2);m=m<l?0:p-q?s(m+=m,r+m,l+=l,++p,q)+s(m,r,l,p,q):1;} ``` [Try it online!](https://tio.run/##XZHRboJAEEXf/YqJiQZkCOyiUl1XH5p@RTWNQbAk7IoLD6QEf50OFomWZGC4M/ewM0TuOYraNrG0XWtZWAx97ELboikshQYzzPFqZxd9BiXq5GIscVNTtfWFbVxppmynHKk8jjfj8bWlPMmRMlsoqTbZzl/n7nVHKGpC4yjMHJmh43RQ5/kLayaaNtUlqGOqLXtUj4CuTijjovzSnweQUDMEjhAgzBEWCEuEEOENYYXAfArSOD0DvxGDP67yOCrj00B4hpCXUcYIEFC@JInxVYcJA94VeRhSzHte9H00MzB/qPG@@uD7avVOsRgjPL8H497Rbaw7RapPcUUuX/TpBor0J74k1uN8ttcLs0ER4Dj3bhv@9vGYSROp38u9fhAv5ZLK3T99VWNSh2X8t@WGWhJrPDmBuwW6T4q9pqE0Qok0cSxleeiBzahpfwE "C (gcc) – Try It Online") Golf of [Phil Carmody](https://oeis.org/wiki/User:Phil_Carmody)'s C code on the OEIS [A076227](https://oeis.org/A076227) page. [Answer] # [Husk](https://github.com/barbuz/Husk), ~~15 14 13~~ 12 bytes ``` #ȯΛ⌊G*m+.πḋ2 ``` [Try it online!](https://tio.run/##ASQA2/9odXNr/23igoHhuKMxMP8jyK/Om@KMikcqbSsuz4DhuIsy//8 "Husk – Try It Online") -1 byte from Dominic van Essen. -1 more byte from Dominic van Essen. -1 more more byte from Dominic van Essen([Or is it?](https://codegolf.stackexchange.com/a/214009/80214)). Same method as Bubbler's answer. [Answer] # [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 107 bytes ``` : s ?dup if 1- fdup 2e f> abs fdup f2/ over recurse * swap 1.5e f* recurse + else fdrop 1 then ; : f 1e s ; ``` [Try it online!](https://tio.run/##PU1LCsMgFNx7iiHLFC0K3URIz5LG95pAqKKmPb59UuhqvsxwzHXTT@7Q2oSCezgTdobV4E4dgWcsj/KT7K6Ib8rItJ65EEaUz5JgzU2K49@@gA4BDjlKiLrRC15NkGGSFy9flUpVgLOSh4gdBmaAnjEIZ1FrxhFjUl71avsC "Forth (gforth) – Try It Online") [ovs](https://codegolf.stackexchange.com/a/213999/78410) and [Noodle9](https://codegolf.stackexchange.com/a/214010/78410) transformed the APL solution into a nice recursive function, so here is a translation of those into Forth. ``` \ recursive helper function : s ( n f:p -- cnt ) ?dup if \ if n is nonzero ( n f:p ) 1- \ ( n-1 f:p ) fdup 2e f> abs fdup f2/ \ ( n-1 p>2 ) ( f: p p/2 ) over recurse * \ ( n-1 p>2*cnt1 ) ( f: p ) *0.5 branch swap 1.5e f* recurse \ ( p>2*cnt1 cnt2 ) *1.5 branch + \ ( cnt ) else \ otherwise ( f:p ) fdrop 1 \ remove p and push 1 then ; : f ( n -- cnt ) 1e s ; \ main function; call s with p=1 ``` ]
[Question] [ Write a [proper quine](https://codegolf.meta.stackexchange.com/q/4877/48934) whose every rotation is itself a proper quine. For example, if your source code is `abcdef`, then: * `abcdef` would output `abcdef` * `bcdefa` would output `bcdefa` * `cdefab` would output `cdefab` * `defabc` would output `defabc` * `efabcd` would output `efabcd` * `fabcde` would output `fabcde` A rotation ["is made by splitting a string into two pieces and reversing their order"](https://codegolf.stackexchange.com/q/5083/48934). ## Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest answer in bytes wins. [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply. [Answer] # [Alice](https://github.com/m-ender/alice), ~~138~~ ~~128~~ ~~74~~ 70 bytes ``` <pp&a0Ra*880R9Z640R8Z5e0R7*a70R6Z060R5Z9e0R4Z4R20R3*79Y3Zea0eZ1R51!Z73 ``` Unfortunately, I had to fix a bug in the interpreter to make this work, so the current version doesn't work on TIO. [But you can try the 128-byte solution online.](https://tio.run/##S8zJTE79/9/CQkuvVDHRwMIoytLAxCzKwsAsNcrcwNA0yszA0lzL1MDMIMrEwNwkKMrYINU0yggkaGhgGmQYZWCQmKFWQKn@//8B "Alice – Try It Online") You can use [this Python script](https://tio.run/##rVC7bsIwFJ3xV1wyNEkLwTwS0kisHTt0qeQKVYY4xCrY1rUR5etTOxRE9072Pa97bHN2rVbzrpMHo9GBPdsRaEtILRrAo/o0qHfID8lW1yKtyOAkXQvaCJXEAYpHEJ/iFLiFpoImO6F04iImAxTuiMrHZaZ3RHjcnGGijZvwvdyKiVROoPEygRluINiiNEPB6yQlJIywCpUy62qpbkSjESRIBcjVTiR0tPfh/U7fEAC1405q5b0B/BjLav3U36qxXHuBEt/Ok/fPu3pST8vmohiublEhFsCgL/xHesWi/rBVdA@GkMvMrRX@c1/43gpCfi3vGr/sMEq7riwfeUvLGeN0UbBnWghW0mnOlrSkrKAFZTldLt7Ygoqczangr2wW0CnN36aMUt62D@ZfQn4A) to verify that it works for all rotations, but again you'll have to run it locally against an up-to-date interpreter for the latest version. (Thanks to Jo King for providing that.) ## Explanation (for 74-byte solution) [(Link to an explanation of the original 138-byte solution.)](https://codegolf.stackexchange.com/revisions/225545/1) I was trying find a 2D language for [Razetime's bounty](https://codegolf.meta.stackexchange.com/a/22293/8478) where this might be possible and it turned out that it's actually very feasible in Alice. Unfortunately, the solution is a one-liner, not making much use of the two dimensions. That said, I'd be *very* impressed if this is possible with an actual 2D program (in any language), because almost every rotation would have one line broken into two pieces (one at the start and one at the end). I imagine a language would have to have a) multiple explicit entry points and b) a way to determine where on the grid an instruction pointer is to pick one that starts in a "safe" region of the grid. And then you'd still have to implement a quine for this that can work out what the actual current rotation is. So... uhhh... ### Printing the quine Anyway, let's talk about this solution. I'm using grid manipulation (or self-modifying) command `p` to write our *actual* program into the grid. The main trick for letting me get below 100 bytes is to write that code *outside* the initial grid, specifically to the left of it (at negative **x** indices). This self-modification works regardless of the applied rotation (we'll get into why later), and prepends the following snippet to the code: ``` @o&J'h%p't" ``` This code will be executed from right to left. By the time we get here: * there might be some rubbish left on the stack (depending on the rotation) - in one case, there might be an iterator in the queue (more about that later) * in two cases (specifically those starting with a `p`) the first character of the original source code has been replaced with a null * otherwise the original source always remains unchanged. Before we get into how and why this self-modification works consistently, let's look at what the new code does. ``` " Toggle string mode. While in string mode, Alice records every codepoint the IP travels over (with some caveats that don't matter). Since there's only one " on the grid, we'll record every other cell, wrap around, and eventually hit " again. When we leave string mode again, all of the codepoints get pushed to the stack. There'll be a bunch of useless stuff at the bottom of the stack now but what's important is that the top 74 values are the original source code in reverse order. However, the leading 'p' might have been replaced with a null. Let's fix that. t Decrement. 'p% Modulo 112. Since 'p' is the biggest codepoint in the original source, this won't affect any value that corresponds to an actual character. But if we had a 0, -1 % 112 becomes 111. h Increment. We've now mapped 0 to 112 and left all values from 1 to 112 unchanged. 'J Push 74, which happens to be the length of the source code. &o Pop and print that many characters from the top of the stack. @ Terminate the program. ``` ### Generating the printing code On to the question of how we apply this source modification in the first place. Let's go back to half of the initial code: ``` <pp&ha0Na*880RaZ640R9Z5e0R8Z620R7Z060R6Z9e0R5Z4R20R4Z730R3Z060R2Zea0eZ1R51 ``` We start on a `<` which makes the instruction pointer (IP) move west instead of east. The IP wraps around the edges, so we really start executing the code from the end and should once again read this code in reverse. This makes use of `p`, which pops **y**, **x**, **v** and writes value/codepoint **v** to the location **(x, y)**. We use `ah&` to execute `p` 11 times, though the second `p` will add a 12th invocation. It's important for those to happen only in one place in the code for all rotations to work. All the other stuff before that just prepares the stack with inputs for these twelve invocations of `p`. Breaking the code down into `v, x, y` triples: ``` v x y ​1 5R1Z e 0 aeZ 2R 0 60Z 3R 0 37Z 4R 0 2R4Z 5R 0 e9Z 6R 0 60Z 7R 0 26Z 8R 0 e5Z 9R 0 46Z aR 0 88* aN 0 ``` Apart from pushing individual digits, there are only a few commands of note here. `e` pushes **-1**. `a` pushes **10**. `R` multiplies the top of the stack by **-1**. `N` computes the bitwise NOT. And then there's `Z`. You'll notice that most of them make use of it, the *zip* command. This command computes a bijection from a pair of integers to a single integer. The intended usage is to encode lists or other collections of numbers in a single number (to make it easier to store on the tape or the grid, for example), but it happens to be very useful for generating larger numbers in few characters. You can use [this Alice program](https://tio.run/##S8zJTE79/1/J0NhcX0FJISayTl/BHwgduPT@/wcA) to figure out which two numbers you need to get the desired result. Also note that there's an additional **1** at the bottom of the stack. This is the only relevant input for the 12th invocation of `p`. Since this is the **y** this writes some garbage somewhere on the second line of the program, which we'll never encounter. ### Rotating the source Finally, let's look at how various rotations of the source code behave. I'm going to shorten our "unrotated" source code to `<pp&haZYX` where `ZYX` represents the code that pushes all the constants. Let's go through the various possibilities: ``` pp&haZYX< ``` Here, we start on a `p`, which immediately reads three implicit zeros from the empty stack and replaces itself with a null. This is the reason any solution will *need* two `p`s, because the rotation which starts with `p` immediately loses it before it can do anything useful. For this particular rotation, we immediately run into another `p`, which does nothing and then `&haZYX` pushes a ton of random numbers we're never going to use. Finally `<` moves us left and we basically move through the exact same code as in the unrotated source, except we don't have the additional `p` any more (but that only wrote a useless character to the second line anyway). ``` p&haZYX<p ``` This one behaves a bit differently. The initial `p` still removes itself, so the behaviour isn't really different until we hit `<` move back and push all the constants. However, now when reach the left end of the code, our *actual* `p` hasn't been executed yet, so the quine-printing code doesn't exist yet. The IP wraps around and we finally modify the source with the `p` at the end. Then the IP moves through `ZYX` again, uselessly pushing the constants again. Finally, we end on `&ha` *just* before the `"`. String mode works such that it makes use of the iterator queue when *leaving* string mode. So what this does is that we end up pushing all of the grid codepoints to the stack 11 times instead of once. But since we're only working with the top 74 stack values anyway, we don't care about the other 10 copies at all and this rotation ends up working as well. Next: ``` &haZYX<pp ``` This is basically the same, except we don't replace a `p` with null (but do write a rubbish character to the second line). And finally, putting the rotation anywhere inside the code that pushes constants: ``` YX<pp&haZ ``` This isn't fundamentally different, we just push a smaller amount of rubbish to the stack before hitting the `<` and executing the proper code. [Answer] # [Motorola MC14500B Machine Code](http://www.brouhaha.com/~eric/retrocomputing/motorola/mc14500b/mc14500b_icu_handbook.pdf), 1 byte The 1 byte score is derived from two 4-bit instructions: ``` 0000 0010 ``` ## Explanation > > The Motorola MC145008 is a single chip, one-bit, static CMOS processor optimized for decision-oriented tasks. The processor is housed in a 16-pin package and features 16 four-bit instructions. The instructions perform logical operations on data appearing on a one-bit bidirectional data line and data in a one-bit accumulating Result Register within the ICU. All operations are performed at the bit level. > > > The pins of the processor are numbered: ![Pin assignment](https://i.stack.imgur.com/SfCi8.png) > > Instructions are presented to the chip on the 4 instruction pins, (`I0`, `I1`, `I2`, `I3`), and are latched into the Instruction Register, (IR), on the negative-going edge of X1. > > > In layman's terms, pins 4 through 7, are used to present the Instruction Register with an instruction, but the bits are interpreted in the reverse order. For example, the instruction `0001` would have pin #7 in the high state and pins 6 through 4 in the low state. > > The instructions, are decoded in the Control Logic (CTL), sending the appropriate logic commands to the LU. Further decoding is also performed in the CTL to send a number of output flags (`JMP`, `RTN`, `FLGO`, `FLGF`) to pins 9 through 12. These are used as external control signals and remain active for a full clock period after the negative-going edge of X1. > > > Or, put simply, pins 9 through 12 are the output flags `FLGF`, `FLGO`, `RTN`, and `JMP`, respectively. Note that data is typically multiplexed to the `WRITE` pin (pin #2). The output flag pins are similar to other language's exit codes. > > Each of the ICU's instructions execute in a single clock period. > > > ## Rotations ### Initial position ``` 0000 NOPO 0010 LDC ``` The clock periods: 1. The `NOPO` instruction puts pin #10 (`FLGO`) in the high state. Before the next clock period, the output flag pins are put back into the low state. 2. The `LDC` instruction loads the complement of the Data Bus' value to the Result Register, without affecting the output flag pins. So, during the program's two clock periods, the output flag pins have represented `0100 0000`, which, read in reverse (like the input pins), is `0000 0010`, or the original instructions. ### First rotation ``` 0010 LDC 0000 NOPO ``` The clock periods: 1. The complement of the Data Bus is loaded to the Result Register, with no effect of the output flag pins. 2. Pin #10 in switched to the high state. During these two clock periods, the output flag pins have represented `0000 0100`, which, when reversed, are the instructions `0010 0000`. ]
[Question] [ K is a programming language in the APL family designed by Arthur Whitney. While the official interpreter is closed-source and commercial, a trial version with a workspace limit of 32 bits of addressing space (which shouldn't pose problems for code golf) can be found at the [Kx Systems](http://kx.com/software-download.php) website. This version bundled as part of the kdb+ database is colloquially known as "K4". There are also open-source K implementations available, including [Kona](https://github.com/kevinlawler/kona), which is based on K3, and my own interpreter called [oK](https://github.com/JohnEarnest/ok), which is based on K5 and has a [browser based REPL](http://johnearnest.github.io/ok/index.html). Kx Systems has a [wiki](http://code.kx.com/wiki/Main_Page) with K4/kdb+/Q information, and the Kona GitHub page also has an [excellent collection](https://github.com/kevinlawler/kona/wiki) of reference materials. I have begun writing a [manual](https://github.com/JohnEarnest/ok/blob/gh-pages/docs/Manual.md) for oK/k5 which may be a useful reference. Like [J](http://www.jsoftware.com/) and APL, K is a very terse and powerful language, and can often make a good showing in code golf. Please share tips, tricks and idioms you discover, and if you haven't tried K before consider giving it a spin! Post one tip per answer, please! [Answer] # Calling a Dyad Assuming you had a dyadic (2-argument) function `f`: ``` f: {x+2*y} ``` You would ordinarily call it like so: ``` f[3;47] ``` You can save a character by instead currying in the first argument and then applying the resulting partial function to the second argument by juxtaposition: ``` f[3]47 ``` The same naturally works for array indexing: ``` z: (12 17 98;90 91 92) (12 17 98 90 91 92) z[1;2] 92 z[1]2 92 ``` [Answer] # Ranges Normally if you want to create a vector of sequential numbers you use `!`: ``` !5 0 1 2 3 4 ``` If you want to create a range that starts at a number other than zero, you'd then add an offset to the resulting vector: ``` 10+!5 10 11 12 13 14 ``` There are a few unusual approaches which could work better for a particular situation. For example, if your base and offset are already members of a list, you could use "where" twice: ``` &10 5 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 &&10 5 10 11 12 13 14 ``` For slower-growing sequences, consider combining "where" with "take": ``` 5#2 2 2 2 2 2 &5#2 0 0 1 1 2 2 3 3 4 4 ``` If you want to create a range of multiples, you could multiply the result of `!` or you could scan (`\`) a list of copies of the step size: ``` 2*!5 0 2 4 6 8 +\5#2 2 4 6 8 10 ``` If you're trying to avoid parentheses, the former is better if the length of the sequence is variable and the step size is fixed, while the latter is better if the step size is what tends to vary. Picking the right variation can save 1 or 2 characters. The off-by-one difference could also work in your favor. [Answer] # Printing newlines If your output *must* have a newline, you may be tempted to do this: ``` `0:whatever,"\n" ``` *Don't*. K2 (and likely other versions) has a neat feature where you can print a list of lines: ``` `0:("abc";"def") abc def ``` So, if you need to append a newline to the output, just do: ``` `0:,whatever ``` [Answer] # Trainify `(x;f x)` and `x f g x` *Works in ngn/k* You can use "n-times-scan" `1 f\x` for this. It is slightly (likely just 1 byte) longer but more reliable than converge scan `f\x` because it is guaranteed to return the two-item list `(x;f x)` even if `x~f x` or `~x~f f x`. For example, if you want to extract the first and last items of a list: ``` {(*x;*|x)} /10 bytes {*'(x;|x)} {*'1|:\x} /9 bytes *'1|:\ /6 bytes (8 if you need enclosing parens) ``` Note that `*'|:\` doesn't always work because the reverse might be identical to itself, in which case a 1-item list is returned instead of two. This trick extends to the case `x f g x`, which can be translated to `f/(x;g x)` and then `f/1 g\x`, though it actually saves bytes only if `g` does not require `(...)` in `g\`. For sorting a list of lists by the result of `-/` of each row: ``` {<x!-/'x} /9 bytes, or 10 with `@` <!/1-/'\ /8 bytes, or 10 with `(...)` ``` Both are real examples from [this answer](https://codegolf.stackexchange.com/a/231589/78410). --- Sometimes `f\` works unconditionally in place of `1 f\`. ``` /absolute value {x|-x} |/-:\ ``` `x f x` is shorter to trainify as `f/2#,` than `f/1::\`. ``` /equality table {x=/:x} =/:/2#, ``` `(f x)g x` is only one byte longer than `x g (f x)` as a train: `g/|1 f\`. ``` /extract first interval based on the indices computed by f {*(f x)_x} {*f[x]_x} *_/|1 f\ ``` [Answer] Casts from strings are expensive. Just use eval. This: ``` 0.0$a ``` can become just this: ``` . a ``` In K5, it's a byte shorter: ``` .a ``` [Answer] # Each Right Occasionally you may find yourself writing (or arriving at by simplification) a parenthesized expression applied via each-monad: ``` (2#)'3 4 5 (3 3 4 4 5 5) ``` It is one character shorter to convert this pattern into an application of each-right: ``` 2#/:3 4 5 (3 3 4 4 5 5) ``` [Answer] ## Cyclic Permutations Dyadic `!` in K2/K3 is "rotate": ``` 2!"abcd" "cdab" -1!"abcd" "dabc" ``` When "scan" (`\`) is provided with a monadic verb, it acts as a fixed-point operator. In K, fixed point operators repeatedly apply their verb to a value until the initial value is revisited or the value stops changing. Combining rotate with fixed-point scan provides a very convenient way of computing a set of cyclic permutations of a list: ``` ![1]\1 2 4 8 (1 2 4 8 2 4 8 1 4 8 1 2 8 1 2 4) ``` You can either curry `!` via brackets or parenthesize to create the verb train `(1!)`: ``` ![1]\ (1!)\ ``` (Note that `1!\` has an entirely different behavior!) Each of these is equivalent in length but the former may be more desirable if the rotation stride is something other than 1; in this case the brackets delimit a parenthesized subexpression "for free". As an example, here is a short program which tests via brute force whether a string x contains the substring y (cyclically!): ``` {|/(y~(#y)#)'![1]\x} ``` K5 users beware! K5 has changed the meaning of dyadic `!`, so this technique isn't so easy. It will work as expected in Kona. [Answer] ## Lists of Strings Some challenges call for a hardcoded list of strings, e.g.: ``` ("qwertyuiop";"asdfghjkl";"zxcvbnm") ``` Sometimes, a few bytes can be saved using an alternative form, i.e.: ``` ";"\:"qwertyuiop;asdfghjkl;zxcvbnm" ``` `k4` (and several other variants) can take advantage of the `symbol` datatype, so long as the hardcoded strings lack spaces. For example: ``` $`qwertyuiop`asdfghjkl`zxcvbnm ``` [Answer] # Avoid Conditionals K has a conditional construct (`:[`) which is equivalent to a Lisp-style `cond`: ``` :[cond1;result1; cond2;result2; cond3;result3; default] ``` You can have as many conditions as you like, and if none match the default value is returned. Sometimes (as in recursive programs or programs that otherwise rely on a sequence of side effects), there's no getting around using one of these. However, in situations where you can afford to do a bit of extra work, you can often replace a "cond" with list indexing. Consider the infamous [fizzbuzz](http://c2.com/cgi/wiki?FizzBuzzTest) program. Written in a conventional imperative programming style, we might go with: ``` {:[~x!15;"FizzBuzz";~x!3;"Fizz";~x!5;"Buzz";x]}'1+!100 ``` There's quite a bit of repetition here in the divisibility tests. A different approach recognizes that there are 4 cases (a number, divisibility by only 3, divisibility by only 5, divisibility by 3 and 5) and attempts to directly compute an index which chooses one of these cases from a list: ``` {(x;"Fizz";"Buzz";"FizzBuzz")@+/1 2*~x!/:3 5}'1+!100 ``` Two characters shorter, and a better use of the language. Knowing that list literals are evaluated right to left, we also gain some additional golfing opportunities for combining reused subexpressions. We couldn't have easily done this in the cond-based version, since the string cases aren't evaluated at all if they aren't selected: ``` {(x;4#t;4_ t;t:"FizzBuzz")@+/1 2*~x!/:3 5}'1+!100 ``` Now we've saved 5 characters overall. Incidentally, this particular example works out even nicer in k5, since we have the "pack" overload for `/` to handle the step of multiplying by a vector of coefficients and summing: ``` {(x;4_t;4#t;t:"FizzBuzz")@2 2/~3 5!\:x}'1+!100 ``` Also note that the behavior of "find" (`?`), which produces an index past the end of the key list if the item is not found, is specifically designed to support handling a "default" case in this kind of indexing. Consider this fragment to convert vowels to uppercase: ``` {("AEIOU",x)"aeiou"?x}' ``` Versus one of: ``` {t:"aeiou"?x;:[t<5;"AEIOU"t;x]}' {:[~4<t:"aeiou"?x;"AEIOU"t;x]}' ``` (I know which I'd rather read, too!) [Answer] # Handling unicode characters (ngn/k only) *Originally from [Bubbler](https://codegolf.stackexchange.com/users/78410/bubbler).* Putting unicode characters inside a string turns them into a byte sequence: ``` "⍺⍴⍵" 0xe28dbae28db4e28db5 ``` this often hinders the ability to use them as individual characters. However, you can use symbols instead: ``` `⍺`⍴`⍵ `0xe28dba`0xe28db4`0xe28db5 ``` Which will group them into appropriate characters. You can then retrieve the byte sequences with `$`, and concatenate them into the correct string. [Answer] # Uses of `$` This tip is written with ngn/k in mind, parts might apply to other versions * `$x string` applied on a string converts each character into its own string, making `$x` one byte shorter than `,'x` or `++x`. This transformation can be useful when replacing some characters with spaces in a string: Given a string `x` and a boolean vector `y` of the same length, `($x)@'y` inserts spaces at the indices of 1's in the boolean vector. ``` ($"Hello")@'0 1 1 0 1 "H l " ``` * `i$C` truncates strings if `i` is less than the length of string. On strings that case is identical to `i#C`, but when given lists of strings, `$` always applies to individual strings, potentially saving some `'`s. ``` 3$("Hello, ";"World") ("Hel";"Wor") ``` ]
[Question] [ An palindrome is a word that is its own reverse. Now there are some words that might look like palindromes but are not. For example consider the word `sheesh`, `sheesh` is not a palindrome because its reverse is `hseehs` which is different, however if we consider `sh` to be a single letter, then it's reverse is `sheesh`. This kind of word we will call a semi-palindrome. Specifically a word is a semi-palindrome if we can split up the word in to some number of chunks such that when the order of the chunks are reversed the original word is formed. (For `sheesh` those chunks are `sh e e sh`) We will also require no chunk contains letters from both halves of the word (otherwise every word would be a semi-palindrome). For example `rear` is not a semi-palindrome because `r ea r` has a chunk (`ea`) that contains letters from both sides of the original word. We consider the central character in an odd length word to be on neither side of the word, thus for words with odd length the center character must always be in it's own chunk. Your task will be to take a list of positive integers and determine if they are a semi-palindrome. Your code should output two consistent unequal values, one if the input is a semi-palindrome and the other otherwise. However the byte sequence of your code ***must be a semi-palindrome*** itself. Answers will be scored in bytes with fewer bytes being better. ## Test-cases ``` [] -> True [1] -> True [2,1,2] -> True [3,4,2,2,3,4] -> True [3,5,1,3,5] -> True [1,2,3,1] -> False [1,2,3,3,4,1] -> False [11,44,1,1] -> False [1,3,2,4,1,2,3] -> False ``` [Program to generate more testcases.](https://tio.run/##bZDBCoMwDIbvPsWP7KDIXkDoDhu7D3YUGdVVLNZ2qw4ve3eXqhXZFgJp/iRf2ta8a4RS41ghTRGdn@Ax2AEZz7H/DkdjVFCBo0CWA4xOjKHw0i3fSupUv3QDO4eoskb3SFHGAd6@SK1LnaFCNvUQ2FtW8LLZ5GSl0L2wDmH6WthBdsKXHGJdMy@IES38JFlo8YoYaF4EK5PmpZY9Sie51gmpeOekQHZX0coLV1LfrWnF39@a/uenc3paTj62XGpKH1bSHXdeRmhs4TwcPw "Haskell – Try It Online") --- [borrible](https://codegolf.stackexchange.com/users/2046/borrible) pointed out that these are similar to [generalized Smarandache palindromes](https://planetmath.org/generalizedsmarandachepalindrome). So if you want to do some further reading that's one place to start. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~85~~ 69 bytes ``` M`^(.+,)*(\d+,)?(?<-1>\1)*$(?(1)^)|M`^(.+,)*(\d+,)?(?<-1>\1)*$(?(1)^) ``` [Try it online!](https://tio.run/##K0otycxL/K@q4Z7w3zchTkNPW0dTSyMmBUjZa9jb6BraxRhqaqlo2GsYamrYK2pq1hCl6v9/LkMdAx1DHS5jHRMdIyAE0UCOKVAURAKlQWKGMAZIGsQx0DExAGsEAA "Retina 0.8.2 – Try It Online") Explanation: ``` M` ``` Selects Match mode. In fact, Retina defaults to Match mode for a single-line program, but the second copy of the code would always match if not for these extra characters. ``` ^ ``` Match must start at the beginning. ``` (.+,)* ``` Capture a number of runs of characters. Each run must end in a comma. ``` (\d+,)? ``` Optionally match a run of digits and a comma. ``` (?<-1>\1)* ``` Optionally match all of the captures in reverse order, popping each one as it is matched. ``` $ ``` Match must end at the end. ``` (?(1)^) ``` Backtrack unless all of the captures were popped. It works by requiring the match to still be at the start of the string if we have an unpopped capture, which is impossible. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~27~~ 23 bytes ``` ṖUṁ@Ƒ€ṚẸHḢŒŒHḢŒṖUṁ@Ƒ€ṚẸ ``` Returns **1** for semi-palindromes, **0** otherwise. [Try it online!](https://tio.run/##y0rNyan8///hzmmhD3c2Ohyb@KhpzcOdsx7u2uHxcMeio5OOToLQWBT8P9wOZAORgvv//9FcCsoKJUWlJRmVCiWpxSUKyYnFqcVcCtHRsToK0YYgwkjHUMcIxDDWMdExAkIgDeGaAmWAZGysDsiUtMScYnRDDMHKwcZAmCAzIFxDHRMgEyZnDJQFcYFqoMYVp@akgU0DmqNOjj/VgebEAgA "Jelly – Try It Online") ### How it works ``` ṖUṁ@Ƒ€ṚẸHḢŒŒHḢŒṖUṁ@Ƒ€ṚẸ Main link. Argument: A (array) Œ Invalid token. Everything to its left is ignored. ŒH Halve; divide A into two halves similar lengths. The middle element (if there is one) goes into the first half. Ḣ Head; extract the first half. ŒṖ Generate all partitions of the first half. U Upend; reverse each chunk of each partition. Let's call the result C. Ṛ Yield R, A reversed. Ƒ€ Fixed each; for each array P in C, call the link to the left with arguments P and R. Return 1 if the result is P, 0 if not. ṁ@ Mold swapped; replace the n integers of C, in reading order, with the first n integers of R. Ẹ Exists; check if one of the calls returned 1. ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~157~~ ~~153~~ ~~147~~ 143 bytes -4 bytes thanks to [tsh](https://codegolf.stackexchange.com/users/44718/tsh). ``` s=lambda x,i=0:len(x)<2or[]<x[i:]and(x[-i:]==x[:i])&s(x[i:-i])|s(x,i+1) s=lambda x,i=0:len(x)<2or[]<x[i:]and(x[-i:]==x[:i])&s(x[i:-i])|s(x,i+1) ``` [Try it online!](https://tio.run/##K6gsycjPM/r/v9g2JzE3KSVRoUIn09bAKic1T6NC08Yovyg61qYiOtMqNjEvRaMiWhfIsrWtiLbKjNVUK9YAyegCmTVApk6mtqEmF5XM@V9QlJlXolCsER2ryQVnG@oY6BgiCxjrmOgYASGQRhU2BaoEkqiaQeoMMYVAhgCF/wMA "Python 2 – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~59~~ ~~47~~ ~~43~~ 41 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 2äøø€.œ`âʒ`RQ}gĀIg_^q2äøø€.œ`âʒ`RQ}gĀIg_^ ``` -12 bytes thanks to *@Emigna*. [Try it online](https://tio.run/##yy9OTMpM/f/f6PCSwzsO73jUtEbv6OSEw4tOTUoICqxNP9LgmR4fV4hX9v//aGMdEx0jHQMgBrJiAQ) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaVL6H@jw0sO7zi841HTGr2jkxMOLzo1KSEosDb9SENEenzcf53/0dGxOgrRhjoGOoYghrGOiY4REAJpCNcUKAMkIYpA4oYIJgiaIAsYgYyBsMCCBjomBjCTQVYg80CqTSCqY2MB). **Explanation:** ``` 2ä # Split the input into two parts # i.e. [3,4,2,0,2,3,4] → [[3,4,2,0],[2,3,4]] øø # Zip twice without filler # This will remove the middle item for odd-length inputs # i.e. [[3,4,2,0],[2,3,4]] → [[3,2],[4,3],[2,4]] → [[3,4,2],[2,3,4]] €.œ # Then take all possible partitions for each inner list # i.e. [[3,4,2],[2,3,4]] # → [[[[3],[4],[2]],[[3],[4,2]],[[3,4],[2]],[[3,4,2]]], # [[[2],[3],[4]],[[2],[3,4]],[[2,3],[4]],[[2,3,4]]]] ` # Push both lists of partitions to the stack â # Take the cartesian product (all possible combinations) of the partitions # i.e. [[[[3],[4],[2]],[[2],[3],[4]]], # [[[3],[4],[2]],[[2],[3,4]]], # ..., # [[[3,4,2]],[[2,3,4]]]] ʒ } # Filter this list of combinations by: ` # Push both parts to the stack RQ # Check if the second list reversed, is equal to the first # i.e. [[3,4],[2]] and [[2],[3,4]] → 1 (truthy) gĀ # After the filter, check if there are any combinations left # i.e. [[[[3,4],[2]],[[2],[3,4]]]] → 1 (truthy) Ig_ # Check if the length of the input was 0 (empty input-list edge-case) # i.e. [3,4,2,0,2,3,4] → 7 → 0 (falsey) ^ # Bitwise-XOR # i.e. 1 XOR 0 → 1 (truthy) q # Stop the program (and then implicitly output the top of the stack) 2äøø€.œ`âʒ`RQ}gĀIg_^ # Everything after the `q` are no-ops to comply to the challenge rules ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 37 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) Utilizes roughly the same technique [Jonathan](https://codegolf.stackexchange.com/a/174095/59487) came up with. ``` .œʒ€gηOZ;îå}εÂQ}ZĀqĀZ}QÂε}åî;ZOηg€ʒ.œ ``` [Try it online!](https://tio.run/##AU4Asf9vc2FiaWX//y7Fk8qS4oKsZ863T1o7w67DpX3OtcOCUX1axIBxxIBafVHDgs61fcOlw647Wk/Ot2figqzKki7Fk///WzExLDQ0LDEsMV0 "05AB1E – Try It Online") --- ``` .œʒ€gηOZ;îå}εÂQ}ZĀqĀZ}QÂε}åî;ZOηg€ʒ.œ ``` Full program. Receives a list from STDIN, outputs **1** or **0** to STDOUT. ``` .œʒ } ``` Filter-keep the partitions that satisfy... ``` €gηOZ;îå ``` This condition: The lengths of each (`€g`) are stored in a list, whose prefixes (`η`) are then summed (`O`), hence giving us the cumulative sums of the lengths list. Then, the ceiled halve of the maximum of that list is pushed onto the stack – but keeping the original list on it as well (`Z;î`) and if it occurs (`å`) in the cumulative sums then the function returns truthy. ``` εÂQ} ``` For each, compare (`Q`) **a** with **a** reversed, which are pushed separately on the stack by `Â`. Returns a list of **0**s and **1**s. ``` ZĀq ``` Maximum. If any is truthy, then **1** else **0**. End execution. Everything that follows is completely ignored. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~33~~ 32 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -1 Thanks to Erik the Outgolfer Thanks also to Dennis for a bug fix and looking into changing an implementation detail in Jelly. ``` ẸƇŒḂƇƊ$ƊĊHṀċÄẈṖŒŒṖẈÄċṀHĊƊ$ƊƇŒḂƇẸ ``` Semi-palindromes yield `1`, others yield `0`. **[Try it online!](https://tio.run/##y0rNyan8///hrh3H2o9Oerij6Vj7sS6VY11Hujwe7mw40n245eGujoc7px2dBJTdOQ3IOdxypBso5XGkC6wQrg1oxP///6ONdYx1THRMdcx0wKxYAA "Jelly – Try It Online")** (slow as it's \$O(2^n)\$ in input length) Or see the [test-suite](https://tio.run/##y0rNyan8///hrh3H2o9Oerij6Vj7sS6VY11Hujwe7mw40n245eGujoc7px2dBJTdOQ3IOdxypBso5XGkC6wQrg1oxP@jew63P2paA1I6A0gDkfv//9HRsQpIQFlB107BkEsn2lDHQMcwFl3UWMdExwgIgXQssqgpUDWQjEU1AaQOagZY1AAuCjLHMBZJ1EDHxABmI1Q0FgA "Jelly – Try It Online"). The only chunks are the `ŒḂ`s ({3rd & 4th} vs {29th & 30th} bytes), just to allow the code to parse. ### How? All the work is performed by the right-hand side - the "Main Link": ``` ŒṖẈÄċṀHĊƊ$ƊƇŒḂƇẸ - Main Link: list ŒṖ - all partitions Ƈ - filter keep those for which this is truthy (i.e. non-zero): Ɗ - last three links as a monad: Ẉ - length of each $ - last two links as a monad: Ä - cumulative addition Ɗ - last three links as a monad: Ṁ - maximum H - halve Ċ - ceiling ċ - count Ƈ - filter keep those for which this is truthy: ŒḂ - is palindrome? Ẹ - any? ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~87~~ 79 bytes *-8 bytes with some tricks from Jo King's answer* ``` $!={/\s/&&/^(.+)\s[(.+)\s]*$0$/&&$1.$!}#$!={/\s/&&/^(.+)\s[(.+)\s]*$0$/&&$1.$!} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPtfRdG2Wj@mWF9NTT9OQ09bM6Y4GkLFaqkYqACFVQz1VBRrlYlU99@aqzixUiFNQyVeUyEtv4hLQ1OHS8NQx0DHEMQw1jHRMQJCIA3hmgJlgCREEUjcEMEEKYZwDXRMDMBGWP8HAA "Perl 6 – Try It Online") Port of tsh's JavaScript answer. Returns two different Regex objects. [Answer] # [Python 2](https://docs.python.org/2/), ~~275~~ ~~251~~ 205 bytes -24 bytes thanks to @KevinCruijssen -44 bytes thanks to @PostLeftGhostHunter -2 more bytes thanks to @KevinCruijssen ``` def s(x): l=len(x) if l<2:return 1>0 for i in range(1,l/2+1): if x[l-i:]==x[:i]:return s(x[i:l-i]) def s(x): l=len(x) if l<2:return 1>0 for i in range(1,l/2+1): if x[l-i:]==x[:i]:return s(x[i:l-i]) ``` Returns True for semi-palindrome, None otherwise [Try it online!](https://tio.run/##vY1BCgIxDEXX9hRZzmDFadVNsV6kdCHYaqBkhlqhnr5mFoqDewkkn5f/k@lZbiPp1i4hwr2rvRGQbArEUgBGSEdtciiPTKBOg4A4ZkBAgnyma@iUTFu9Vhxbsbm6tEHjra3OoH/n@KxDwxvfi/@8aVNGKkwcv/xoJQepvsFO7qXm4rnEB3ZyX4Znn/pF8xHG7QU "Python 2 – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 129 bytes ``` f=->l{!l[1]||(1...l.size).any?{|x|l[0,x]==l[-x,x]&&f[l[x..~x]]}}#f=->l{!l[1]||(1...l.size).any?{|x|l[0,x]==l[-x,x]&&f[l[x..~x]]}} ``` [Try it online!](https://tio.run/##KypNqvyfZlvAVWxrYxMc4h@gl5yRXwAU0bXLqVbMiTaMranRMNTT08vRK86sStXUS8yrtK@uqajJiTbQqYi1tc2J1q0AMtTU0qJzoiv09OoqYmNra5UpNeA/yC1cqWWJOQrFXFwFCmnR0bGxENpQx0DHEMYx1jHRMQJCII0QMgWqAJIIDSB5Q1QuSCNICCxWHPsfAA "Ruby – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), 139 bytes ``` f=a=>(s=(''+a).replace(/^(.*),((.*),)?\1$/,'$3'))!=a?f(s):/,/.test(s)//^(.*),((.*),)?\1$/,'$3'))!=a?f(s):/,/.test(s)f=a=>(s=(''+a).replace( ``` [Try it online!](https://tio.run/##lY3dDoIwDIXveQsTkrVaNyZ4Ixlc@RSIyYLDnxBG2OLr4xATr7wwTU6/0560D/3Urhnvg9/29mKmqVVaFeAUMLbRyEczdLoxIM7A10jwVixPMhbE4pQhrpQuW3B4ECS4N84HFv/Ff/yc8iqqaooqSQnJGVLKaBcq9MXuwyboEprn8otzeLEJZcnnRM1bOx51cwOvisb2znaGd/YKLXhEzKcX "JavaScript (Node.js) – Try It Online") [Answer] ## [C (gcc)](https://gcc.gnu.org/) (X86), 216 bytes ``` p(L,a,n)int*a;{return n?(memcmp(a,a+L-n,n*4)|p(L-2*n,a+n,L/2-n))&&p(L,a,n-1):1<L;} #define p(L,a)p(L,a,L/2)//p(L,a,n)int*a;{return n?(memcmp(a,a+L-n,n*4)|p(L-2*n,a+n,L/2-n))&&p(L,a,n-1):1<L;} #define p(L,a)p(L,a,L/2) ``` [Try it online!](https://tio.run/##vZNRa6NAFIXf8yvuWhIcM26a1G6hJg2lpFDwYaktLGRDmeqkFXQUxyyBbH579s41TQzmecGH8Z7v3nNmRiP3I4p2u8IOuOCKJapyhL8pZbUqFaipncksygpbcNEPXMWV47G/CLsjR2FJ8WAwchVjvd5@gjtkt8Nx4G87F7FcJkoCCayWkWaDwX80210kKkpXsYSxruL3PE@/f951TopJ3iqlybupdXQlqiQC0wYiTd8KoTVMoCpX0j@of/Ikhkrqysb9QCoVB7MQc1wu@L5ZaQabDtRvpTRTvhU2wYL5X8J@PukT04QucHTuTYigYlGiydK2uhrmFq87p2D9vA9DC27Berx/CixGaJQrXUH0KUpwYpkmGVpYFknLvASK7ayxKHxYwxgE9M02fOj313Xqpl03Rjsaw7GLsgMcxnKwTGXbjLgA9w66@rdC1WwNY5oTpJhLkWppcmKHyZGJRNm1KR3pJad88wXbbDkdPDmSNjxqw5Z4dRRHHBAdtZAfRwRpDxF6zLrFXp@w1zTRLFqg1wj1Nc6ko42e9T5gdYgzcHMm0p5H9mfAm5OpVzS4ho1Dg8eG/V93@LimMPv19PIWvj48zMIQ74ZezWf0@jzD@9n9Aw "C (gcc) – Try It Online") `p(L,a,n)` returns 0 if array `a` of length `L` is a semi-palindrome, 1 otherwise. Given that all prefixes of length `>n` are already checked, it compares the prefix of length `n` with the suffix of length `n`. `p(L,a)` is the entry point. Unfortunately, the more interesting solution is longer: ## 224 bytes ``` (f(L,a,n))//#define p(L,a)(n=L/2, int*a,n; {return n?(memcmp(a,a+L-n,n*4)|f(L-2*n,a+n,L/2-n))&&f(L,a,n-1):1<L;}//{return n?(memcmp(a,a+L-n,n*4)|f(L-2*n,a+n,L/2-n))&&f(L,a,n-1):1<L;} int*a,n; #define p(L,a)(n=L/2,f(L,a,n))//( ``` [Try it online!](https://tio.run/##rZNRa6NAFIXf/RV3LQmjGTeb1O5CTRpKyULBh6W2sJANZarjVtBR1CyBbH579s41jQbzuODDeO93zzkzo6HzOwwPBxYznwuuLGs8vopknCgJhS5ZTM398ZQbiaptBDxjV8p6UypQC5bJLMwKJrgY@Y7iynatvyjkTG2FJcVx0EHJ4fCo7kys28nM9/bj8f9QaTNdjNzZEjtcJSpMN5GEWVVHb3mefn6/M86KSd4rpcmbrhlVLeokBD0GIk1fC1FVMIe63Ejv1P2TJxHUsqoZxoJUKg56IVa4XPPjsKos2BnQvJVSq3wqGMHC8j4aR33qz/UQukDrPJwTQcWiRJOYmYMKViZvJhdg/rgPAhNuwfx@/@ibFqFhrqoawndRgh3JNMnQwjSpFeclUGx7i0XhwRZmIGCkt@HBaLRtUnftBhHakQzHKcoOcJLlYOrKvhtxDc4dDKpfCrt6axhTnyDFjEVaSZ0TJ3SOTCSKNaZ0pF845Vutrd2e08GTI/UmbW/Sa163zSkHRKc95GuLIO0iQo9e99ibM/aGFPWiB7qdUB9yOh1t9KL3CWtCXIC7mki7LtlfAL@dqV6TcANrhw6PA8f/8PRxLWD58/H5NXh5eFgGAd4NverP6OVpifdz@Ac "C (gcc) – Try It Online") Ungolfed: ``` (f(L,a,n)) //#define p(L,a)(n=L/2, int*a,n; { return n ? (memcmp(a, a+L-n, n*4) | f(L-2*n, a+n, L/2-n)) && f(L,a,n-1) : 1 < L; } // { ... } int*a,n; #define p(L,a)(n=L/2,f(L,a,n)) //( ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 66 bytes ``` @¯X eUsXn}a1 " ʧV?UÊ<2:ßUéV sVÑ @¯X eUsXn}a1 " ʧV?UÊ<2:ßUéV sVÑ ``` [Japt Interpreter](https://ethproductions.github.io/japt/?v=1.4.6&code=CkCvWCBlVXNYbn1hMSAiCsqnVj9VyjwyOt9V6VYgc1bRCkCvWCBlVXNYbn1hMSAiCsqnVj9VyjwyOt9V6VYgc1bR&input=W1tdLApbMV0sClsyLDEsMl0sClszLDQsMiwyLDMsNF0sClszLDUsMSwzLDVdLApbMSwyLDMsMV0sClsxLDIsMywzLDQsMV0sClsxMSw0NCwxLDFdLApbMSwzLDIsNCwxLDIsM10sCls0NDEsMiwxNDRdXQotbQ==) Big improvement this version, it actually beats most of the practical languages now. Now operates on an array of integers since the previous method had a bug. Explanation: ``` @ }a1 Find the first number n > 0 such that... ¯X the first n elements UsXn and the last n elements e are the same " ʧV?UÊ<2:ßUéV sVÑ String literal to make it a Semi-palindrome @¯X eUsXn}a1 " ʧV? If n >= length of input... UÊ<2 return true if the length is less than 2 : Otherwise... UéV move n elements from the end of the input to the start sVÑ remove the first 2*n elements ß and repeat on the remaining elements ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 81 bytes ``` ($!={/../&&/^(.+)(.*)$0$/&&$1.$!})o&chrs#($!={/../&&/^(.+)(.*)$0$/&&$1.$!})o&chrs ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPtfQ0XRtlpfT09fTU0/TkNPW1NDT0tTxUAFyFcx1FNRrNXMV0vOKCpWJlbhf2uu4sRKhTQNlXhNhbT8Ii4NTR0uDUMdAx1DEMNYx0THCAiBNIRrCpQBkhBFIHFDBBOkGMI10DExgBqhTnUnq@vlF6UUW/8HAA "Perl 6 – Try It Online") Returns the regex `/../` for True and the regex `/^(.+)(.*)$0$/` for False. Works similarly to [nwellnhof's answer](https://codegolf.stackexchange.com/a/174113/76162), but converts the list to a string beforehand. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 21 bytes ``` ḍ{|b}ᵗ~cᵐ↔ᵈḍ{|b}ᵗ~cᵐ↔ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRuX/2obcOjpuZHHcuVSopKU/WUakDMtMScYiC79uGuztqHWyf8f7ijt7omCcicXpcM5D9qm/Jwawem4P//0dGxOtGGQGykY6hjBKSNdUx0jIAQSIN5pkBxIAlSBRY1hLNAKsE8Qx0TIAsqYwyUA/GAKmJjAQ "Brachylog – Try It Online") ``` ḍ Split the input in half, with the second half longer if uneven. {|b}ᵗ Maybe remove the first element of the second half. ~cᵐ Partition both halves. ↔ᵈ Is it possible for one to be the other's reverse? ḍ{|b}ᵗ~cᵐ↔ The remainder of the program always succeeds. ``` [Answer] # PHP 237 bytes ``` function f($a){for($x=2>$c=count($a);++$i<=$c/2;)$x|=($s=array_slice)($a,0,$i)==$s($a,-$i)&f($s($a,$i,-$i));return$x;}#function f($a){for($x=2>$c=count($a);++$i<=$c/2;)$x|=($s=array_slice)($a,0,$i)==$s($a,-$i)&f($s($a,$i,-$i));return$x;} ``` recursive function, returns `true` (for input containing less than two elements) or `1` for truthy, `0` for falsy. [Try it online](http://sandbox.onlinephpfunctions.com/code/e2b41433d385050941b71dd63216e6051a62c958) (contains breakdown). Actual code length is 118 bytes; semi-palindrome created via code duplication. For better performance, replace `&` with `&&` and insert `!$x&&` before `++$i`. [Answer] # Scala, 252 bytes ``` def^(s:Seq[Int]):Int={val l=s.size;if(l>1)(1 to l/2).map(i=>if(s.take(i)==s.takeRight(i))^(s.slice(i,l-i))else 0).max else 1}//def^(s:Seq[Int]):Int={val l=s.size;if(l>1)(1 to l/2).map(i=>if(s.take(i)==s.takeRight(i))^(s.slice(i,l-i))else 0).max else 1} ``` [Try it online!](https://tio.run/##xU7BCsIwDL37FTm2MDc3PU068OhVj@KgblGrsau2yHDs22vUj5DAy8t7vCS@0aRjd7hgE6AD7APa1sPKORhii8da@HKL993ahr0sGdXw1ASkfOrNC5fmKKjKpcghdEBZIdObdsKoig2fBn1FYaRSP7oxp3PgWfLW1JNp2ExoygKSR5h9wj18eT5m2V/PR/cwNpAVteAHxDxZJAUXdynlZIxv "Scala – Try It Online") PS. Apparently, solution is 2 times longer just to satisfy a requirement that source code is semi palindrome as well. PPS. Not a code-golf candidate but purely functional solution using pattern matching: ``` def f(s:Seq[Int], i:Int=1):Int = { (s, i) match { case (Nil ,_) => 1 case (Seq(_), _) => 1 case (l, _) if l.take(i) == l.takeRight(i) => f(l.slice(i,l.size-i), 1) case (l, j) if j < l.size/2 => f(l, i+1) case (_, _) => 0 } } ``` ]
[Question] [ # Where am I now? Given a string `d`, containing only the letters `NSWE`, determine the coordinates I've traveled (from left to right, consuming greedily) and the final coordinate where I reside. The rules for reading coordinates from left-to-right: * ***If the next character is `N` or `S`***: + **If the character after the `N` or `S` is another `N` or `S`**: - Consume only the first `N` or `S`. - Output `[0,1]` for `N` - Output `[0,-1]` for `S` + **If the character after the `N` or `S` is `W` or `E`**: - Consume both the `N` or `S` and the `W` or `E`. - Output `[1,1]` or `[-1,1]` for `NE` and `NW`, respectively. - Output `[1,-1]` or `[-1,-1]` for `SE` and `SW`, respectively. * ***If the character is an `E` or `W` not preceded by an `S` or `N`***: + Consume the `E` or `W`. + Output `[1,0]` for `E`. + Output `[-1,0]` for `W`. --- # Worked Example ***NSWE*** ``` [0,1] (North N) [-1,-1] (South-west SW) [1,0] (East E) [0,0] (N+SW+E = Didn't actually move) ``` Note this can be in any format, here are other examples of valid output: ``` [[0,1],[-1,-1],[1,0],[0,0]] [[[0,1],[-1,-1],[1,0]],[0,0]] "0,1\n0,-1\n-1,0\n1,0\n0,0" ``` Etc... --- # More Examples ***SWSENNESWNE*** ``` [-1,-1] [1,-1] [0,1] [1,1] [-1,-1] [1,1] [1,0] ``` ***NNEESESSWWNW*** ``` [0,1] [1,1] [1,0] [1,-1] [0,-1] [-1,-1] [-1,0] [-1,1] [0,0] ``` **NENENEE** ``` [1,1] [1,1] [1,1] [1,0] [4,3] ``` **NEN** ``` [1,1] [0,1] [1,2] ``` **EEE** ``` [1,0] [1,0] [1,0] [3,0] ``` --- # Rules * You may output in any convenient format that doesn't violate loopholes. * You must consume greedily, `NWE` is never `N,W,E`, it is always `NW,E`. + This applies to: `SW*`, `SE*`, `NW*`, `NE*`. + You are consuming left to right, greedily. * The is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), lowest byte-count wins. [Answer] # [Python 2](https://docs.python.org/2/), 116 bytes ``` import re a=[(int(s,35)%5-3,('N'in s)-('S'in s))for s in re.findall('[NS][EW]?|.',input())] print a,map(sum,zip(*a)) ``` [Try it online!](https://tio.run/##JcyxCsMgFEDRPV/hUt57xWRoyFg6ubo4OIiD0IQK0YiaoaX/boXe6Uw3vevriLfWfEhHriyvg7sb9LFi4fNCl2WcOYIEH1mhEUH9RduRWWHdeZ02H59u3xGMVNYIbR/fCbiP6axIZIeU@485HlzCcgb@8Qmvjqg1kFIIJZTSWmrRUz34AQ "Python 2 – Try It Online") ## With output as `[(3+4j), 1, -1j, …]`, 91 bytes ``` lambda x:[sum(1j**(ord(c)%8%5)for c in s)for s in[x]+re.findall('[NS][EW]?|.',x)] import re ``` [Try it online!](https://tio.run/##Hca9CgIhAADgvadwOdQrDgqCCKLJ1cXBwRzsPMnDPzwDg97dpG/60qe8Yjg1c3s0p/xTK1CvYnt7dFzHEcWs0YyHy3DGJmYwAxvA9u/WK6rc52UyNmjlHIKCMikIl/fvBA8Vy531KeYC8tJStqEAgyClhDDCGOeUk451BOL2Aw "Python 2 – Try It Online") This lambda returns a list of [Gaussian integers](https://en.wikipedia.org/wiki/Gaussian_integer): the first is the final coordinate, and all others are the steps required to get there. [Answer] # [Attache](https://github.com/ConorOBrien-Foxx/attache), 80 bytes ``` V#Sum##{Chop[1-ToBase[22260446188,3],2][Sum@Ords=>MatchAll[_,/"[NS][WE]|."]%11]} ``` [Try it online!](https://tio.run/##dY9PSwMxFMTv/RQhq3tx/bOxlFJYiZb0IDRKU8zhETRks25h2w2bJx7Uz77GevDkbWb4vceMRbSu9WOzqManTL3ts@xj2fYByvNtf2ejB8bY7Go6nZXzeXFtCmYgUfxhqGN1s7bo2tuug@fikoJUBrQwnxfUnJal@Rql93WEkxDcq5lM0JFFRYBKpQUtCFVaCSmF0vJokxRKKKW11DThj8PugECBbOw7QR8xEpPyY7xNdpnKRWgKgs78wat@2FtEX/9/0jX5yxm/73eHvGv42gbY@DAY/jM7Z3zVWeS/b8dv "Attache – Try It Online") This is an anonymous function which takes one string argument. ## Explanation The first task is to implement the parsing phase of this question. I found it shortest to use a simple Regex to parse the input (`_`): ``` MatchAll[_,/"[NS][WE]|."] ``` This matches all occurrences of the regex `[NS][WE]|.`, as seen in many other answers. This greedily yields the requested directions. Now, we're going to apply a hash function to each direciton. We take the codepoints of each direction and sum them. This gives the following mapping: ``` Direction Ord-sum E 69 N 78 S 83 W 87 NE 147 SE 152 NW 165 SW 170 ``` We shall try to map these values to a smaller domain; modulo is useful for this, and we can [demonstrate that the smallest modulo which results in unique values for all given inputs](https://tio.run/##TYzLCsMgFET3fsVsCi2I9JWYLvySkIUBW6SxNVFLH@bbrQYKXdwDd2Y4U@hfKQ3aeaEecsBFeUcCNRAoIXP6rViw/r5eXiOfG3wQTSRA@I2MtCVUEQorGMy57Cclr2izqoM@I7Bw0@Oig/hzk5lY5FFKbX2i4A1Fc8jHKXbHgmqfUVcZfNt9AQ) is 11. Sorting by remainders, this gives us the following table: ``` Direction Ord-sum % 11 NW 165 0 N 78 1 E 69 3 NE 147 4 SW 170 5 S 83 6 SE 152 9 W 87 10 ``` Now, we have an input correspondence, as encoding by `Sum@Ords=>[...]%11`. Next, we have to transform these remainders into points. We shall try to derive another mapping, which means inserting "sparse-filling values" to hashes which do not correspond to directions shall be useful: ``` Direction Hash Coordinates NW 0 [-1, 1] N 1 [0, 1] -- (2) [0, 0] E 3 [1, 0] NE 4 [1, 1] SW 5 [-1, -1] S 6 [0, -1] -- (7) [0, 0] -- (8) [0, 0] SE 9 [1, -1] W 10 [-1, 0] ``` We currently have a series of points, which can gives a list indexable by the hash: ``` [-1, 1] [0, 1] [0, 0] [1, 0] [1, 1] [-1, -1] [0, -1] [0, 0] [0, 0] [1, -1] [-1, 0] ``` Now, we shall compress this, seeing as how its only composed of `-1`s, `0`s, and `1`s. Since the list represents pairs, we can flatten the list without losing data. Then, if we take each number `x` and calculate `1-x`, we get the following list: ``` 2 0 1 0 1 1 0 1 0 0 2 2 1 2 1 1 1 1 0 2 2 1 ``` We can convert this into a base 3 number: ``` 20101101002212111102213 ``` Converting to base 10: ``` 20101101002212111102213 ≡ 2226044618810 ``` To summarize, we've taken our points, un-paired them, took each element subtracted from `1`, and converted from base `3`, giving us `22260446188`. We can decompress as such: 1. Convert to base 3: `ToBase[22260446188,3]` 2. Take each number subtracted from one (self-inverse): `1-ToBase[22260446188,3]` 3. Re-pair the list: `Chop[1-ToBase[22260446188,3],2]` This gives us our original set of pairs. Then, we can perform the aforementioned indexing like this: ``` (chopped value)[hashes] ``` Since, in Attache, indexing by an array returns all elements corresponding to those indices. (So, `[1,2,3,4][ [0,0,-1,1] ] = [1,1,4,2]`.) Now, we have the directions of the path that the OP walked. What's left is to calculate the sum. So we capture this result in a lambda `{...}` and put it as the first function in a function composition (`a##b`), with the second being `V#Sum`. This is a fork, which, given input `x`, expands to be: ``` V[x, Sum[x]] ``` `Sum`, when given an 2D array, happens to sum every column in the array (as a result of vectorized summation). So, this pairs the directions with the final destination, and we have our final result. [Answer] # JavaScript (ES6), 102 bytes Returns a string. ``` s=>s.replace(/[NS][EW]|./g,s=>(D=d=>!!s.match(d),x+=h=D`E`-D`W`,y+=v=D`N`-D`S`,[h,v]+` `),x=y=0)+[x,y] ``` [Try it online!](https://tio.run/##dcqxDoMgFEDRvX/hJAbU/sBzkpXlDQyUBKKobawYMUaT/rulQ5cmHW/OfdjNhma5z2s@@dadHZwBqlAsbh5t40ipBGrFpX4VZc8ikRpaqJIkFE@7NgNpM7ZTGKA23OS1kYYdFLaY4pNomBrYpqm5mDjCAdeMqp0d@mz8FPzoitH3pCOpQMnTjKa3Kc0uP4YSuRAcpfi7RObIEaUU8vucbw "JavaScript (Node.js) – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), 45 bytes ``` 'NS' 'WE'Z*Z{2MhX{h'eklihfmj'X{YX9\3_2&YAqts ``` [Try it online!](https://tio.run/##y00syfn/X90vWF1BPdxVPUorqtrINyOiOkM9NTsnMyMtN0s9ojoywjLGON5ILdKxsCSiGKwcqBYA) Or [verify all test cases](https://tio.run/##y00syfmf8F/dL1hdQT3cVT1KK6rayDcjojpDPTU7JzMjLTdLPaI6MsIyxjjeSC3SsbAkovi/QXKESwhID1ADl3pweLCrn59rcLgfiAdkuQa7BgeHh/uFqwMA). ### Explanation (with example) Consider input `'NSWE'` as an example. ``` 'NS' 'WE' % Push these two strings % STACK: 'NS', 'WE' Z* % Cartesian product. Gives a 4×2 char matrix % STACK: ['NW'; 'NE'; 'SW'; 'SE'] Z{ % Cell array of rows (strings) % STACK: {'NW', 'NE', 'SW', 'SE'} 2M % Push again the inputs of the second-last function call % STACK: {'NW', 'NE', 'SW', 'SE'}, 'NS', 'WE' h % Concatenate horizontally % STACK: {'NW', 'NE', 'SW', 'SE'}, 'NSWE' X{ % Cell array of individual elements (chars) % STACK: {'NW', 'NE', 'SW', 'SE'}, {'N', 'S', 'W', 'E'} h % Concatenate horizontally % STACK: {'NW', 'NE', 'SW', 'SE', 'N', 'S', 'W', 'E'} 'eklihfmj' % Push this string % STACK: {'NW', 'NE', 'SW', 'SE', 'N', 'S', 'W', 'E'}, 'eklihfmj' X{ % Cell array of individual elements (chars) % STACK: {'NW','NE','SW','SE','N','S','W','E'},{'e','k','l','i','h','f','m','j'} YX % Implicit input. Regexp replace: replaces 'NW' by 'e', then 'NE' by 'k', etc. % Note that the two-letter combinations are replaced first, which implements % the greediness; and the target letters do not appear in the source, which % avoids unwanted interactions between replacements % STACK: 'hlj' 9\ % Modulo 9 (of codepoints), element-wise % STACK: [5, 0, 7] 3_2&YA % Convert to base 3 with 2 digits. Gives a 2-column matrix % STACK: [1, 2; 0, 0; 2, 1] q % Subtract 1, element-wise % STACK: [0, -1; -1, -1; 1, 0] tXs % Duplicate. Sum of each column % STACK: [0, -1; -1, -1; 1, 0], [0, 0] % Implicit display ``` [Answer] # [Java (JDK)](http://jdk.java.net/), 167 bytes ``` s->{var r="";int i=0,l=s.length,c,x=0,y=0,Y,X;for(;i<l;x+=X=c>1||i<l&&(c=~-s[i]/6%4)>1&&++i>0?c*2-5:0,r+=X+","+Y+" ")y+=Y=(c=~-s[i++]/6%4)<2?1-c*2:0;return r+x+","+y;} ``` [Try it online!](https://tio.run/##fVFbb4IwFH73V5w0mYEVmJptD9RiloW9jZc@oDE@dHirQyBtMRLn/ror4O7Z2pw057s032k3fMfdzfz5JLZFLjVsTO@VWqTeJen8wpZllmiRZzWZpFwpeOQig0MHoCifUpGA0lybY5eLOWwNZzEtRbaazoDLlbIbKcDD@Z5hsuZyOnNaUQBLoCflBocdlyApQkRkGgTtOSlVXrrIVnrtJM7eAJWpiTMmy1xaRAxTssd0TJOg//Jium7XSuirq6ZidnV7cW0H/W4XYxH0RsnlwL3xe440cowchCcYAbIrTCf03YNx6xoORn3XGPwekQtdygwk3jemihxPpJnkYzy9UFoBPQ9YLxSxOETOZ89iFkZRyOLoG2ygkIWMxXEUf8PDeoc/oK9t@IU9tnnq92gzNYn8Npf9EYtVSi@2Xl5qrzAqnWZWrcDIRzb5W7P0eFGkVaP1dH5vvu1OSl5Ztv2f7cwdO3UdT28 "Java (JDK) – Try It Online") ## Explanations Thanks to `c=~-s[i]/6%4`, the following mapping is done: ``` 'N' -> ascii: 78 -> -1 = 77 -> /6 = 12 -> %4 = 0 'S' -> ascii: 83 -> -1 = 83 -> /6 = 13 -> %4 = 1 'W' -> ascii: 87 -> -1 = 86 -> /6 = 14 -> %4 = 2 'E' -> ascii: 69 -> -1 = 68 -> /6 = 11 -> %4 = 3 ``` * `NS` is checked with `c<2` and mapped to `+1`/`-1` using `1-c*2`; * `EW` is checked with `c>1` and mapped to `+1`/`-1` using `c*2-5`. ## Credits * at the very least 9 bytes saved thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen). * -4 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat) [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 93 bytes ``` .+ $&¶$& \G[NS]?[EW]? $&¶ G`. W J %O`. +`EJ|NS m`^((J)?[EJ]*)((S)?[NS]*) $#2$*-$.1,$#4$*-$.3 ``` [Try it online!](https://tio.run/##K0otycxL/P9fT5tLRe3QNhU1rhj3aL/gWPto1/BYe7AYl3uCHlc4lxeXqj@QoZ3g6lXjF8zFlZsQp6HhpQlU6BWrpamhEQxkAjVqaXKpKBupaOmq6BnqqCibgFnG///7BbuGAwA "Retina 0.8.2 – Try It Online") Explanation: ``` .+ $&¶$& ``` Duplicate the input. ``` \G[NS]?[EW]? $&¶ ``` Split the first copy up into directions. ``` G`. ``` Remove extraneous blank lines created by the above process. ``` W J ``` Change `W` into `J` so that it sorts between `E` and `N`. (Moving `E` to between `S` and `W` would also work.) ``` %O`. ``` Sort each line into order. ``` +`EJ|NS ``` Delete pairs of opposite directions (this only affects the last line of course). ``` m`^((J)?[EJ]*)((S)?[NS]*) $#2$*-$.1,$#4$*-$.3 ``` Count the number of horizontal and vertical movements, adding signs where necessary. Those of you who know the differences between Retina 0.8.2 and Retina 1 will want to point out that I can save 2 bytes in Retina 1 because it uses `*` instead of `$*`. While I was there I tried to simplify the splitting process but I was unable to reduce the byte count further, I was only able to equal it with this: ``` L$`$(?<=(.*))|[NS]?[EW]? $&$1 ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~40~~ 32 [bytes](https://codegolf.meta.stackexchange.com/a/9429/78410) ``` 2((⊢,+/)1⊥¨0j1*⊢⊂⍨1,2≤/|)'NWS'∘⍳ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///30hD41HXIh1tfU3DR11LD60wyDLUAgo86mp61LvCUMfoUecS/RpNdb/wYPVHHTMe9W7@n/aobcKj3r5HXc2H1hs/apv4qG9qcJAzkAzx8Az@b6lgaAhUqPdoeneagrpfsGu4OheqWHB4sKufn2twuJ8ruhRQ2DXYNTg4PNwPQ5urq6s6AA "APL (Dyalog Unicode) – Try It Online") It turns out that we don't need PCRE. ### How it works ``` 2((⊢,+/)1⊥¨0j1*⊢⊂⍨1,2≤/|)'NWS'∘⍳ 'NWS'∘⍳ ⍝ V←Map 'NWSE' into 1,2,3,4 2( |) ⍝ Modulo 2 (1 if NS, 0 otherwise) 2≤/ ⍝ For each consecutive pair, ⍝ 0 if [NS][EW] combination, 1 otherwise 1, ⍝ Add a leading 1 ⊢⊂⍨ ⍝ Chunkify V at ones 0j1* ⍝ Power of imaginary unit 1⊥¨ ⍝ Sum within each chunk (⊢,+/) ⍝ Append the grand total to the vector ``` --- # [APL (Dyalog Unicode)](https://www.dyalog.com/), 40 [bytes](https://codegolf.meta.stackexchange.com/a/9429/78410) ``` (⊢,+/)1⊥¨0j1*(⊂'NWS')⍳¨'[NS][EW]|.'⎕S'&' ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///X@NR1yIdbX1Nw0ddSw@tMMgy1AKKNKn7hQeraz7q3XxohXq0X3BstGt4bI2e@qO@qcHqaur/0x61TXjU2/eoq/nQeuNHbRNB4kHOQDLEwzP4v6WCoeGjjhl6j6Z3pymo@wW7hqtzoYoFhwe7@vm5Bof7uaJLAYVdg12Dg8PD/TC0ubq6qgMA "APL (Dyalog Unicode) – Try It Online") Uses PCRE to divide into segments, and then the power of `0j1` (imaginary unit) to convert the directions to complex numbers. `EW` is mapped to the real part (`E` being positive) and `NS` to the imaginary part (`N` being positive). `9 11∘.○` in the footer converts the vector of complex numbers into a two-row matrix, by splitting each complex number into its real (top row) and imaginary (bottom row) parts. ### How it works ``` (⊢,+/)1⊥¨0j1*(⊂'NWS')⍳¨'[NS][EW]|.'⎕S'&' '[NS][EW]|.'⎕S'&' ⍝ Regex search; split into greedy segments (⊂'NWS')⍳¨ ⍝ Index of each char within 'NWS' (1 2 3) ⍝ 'E' becomes 4 since it is not found 0j1* ⍝ Power of imaginary unit 1⊥¨ ⍝ Sum within each segment (⊢,+/) ⍝ Append its sum on its right ``` [Answer] # Java 10, ~~269~~ ~~265~~ ~~243~~ ~~238~~ ~~224~~ 219 bytes ``` s->{var r="";int x=0,y=0,t,X,Y,a;for(;!s.isEmpty();r+=X+"|"+Y+" ",s=s.substring(t+1)){a=s.charAt(t=0);var b=s.matches("[NS][EW].*");x+=X=b?1-s.charAt(t=1)/70*2:a<70?1:-a/87;y+=Y=b|a>69&a<87?1-a%2*2:0;}return r+x+"|"+y;} ``` -10 bytes thanks to *@ceilingcat*. [Try it online.](https://tio.run/##jZBNb8IwDIbv/Aov0qaGftByGIwQ0A45rpccCkIc3FJGGRSUBEQF/e0sVGjaZWJKYiX2Yzt@13hEf734umYb1Bo@sCjPLYCiNLlaYpZDfHsCSKOK8hMy537RlFl/3cSs0QZNkUEMJXC4an90PqICxQlhthSceOhV9hhv4k09ZMudctiTDgottntTOZQpl09cciHu1CVAPM11oA@pbpo5xo0oPaP1ZStU78YxPKTs1iG1vi2abJVrh8xiOZ@JZB60CWUnW5Cn48j/lRTRTi9sdwc47IXjaOBjp99jlcunPL3g6PXtBYf9nk3B566lQlar3BxUCco9NX@rWH29jW33/pBu7MD3uY@7YgFbq91dntkckN6Fq7TJt8HuYIK9DZlN6ZRB5pBYJoLQRsW/IZlIEcdCJvFj1nJCCimTJE4ew@K2xH@4h4z4qVO36us3) **Explanation:** ``` s->{ // Method with String as both parameter and return-type var r=""; // Result-String, starting empty int x=0, // Ending `x`-coordinate, starting at 0 y=0, // Ending `y`-coordinate, starting at 0 t,X,Y,a; // Temp-integers for(;!s.isEmpty() // Loop as long as the input-String is not empty yet: ; // After every iteration: r+=X+"|"+Y+" ",// Append the current steps to the result-String s=s.substring(t+1)){ // Remove the first `t+1` characters from the input-String a=s.charAt(t=0); // Set `a` to the first character of the input to save bytes, // and reset `t` to 0 var b=s.matches("[NS][EW].*"); // Check if the input-String starts with N/S followed by E/W x+=X= // Set `X` to (and increase `x` by `X` afterwards): b? // If the boolean check was truthy: 1-s.charAt(t=1)/70*2 // Set `X` to 1 if 'E', -1 if 'W' // And set `t` to 1 : // Else: a<70?1:-a/87; // Set `X` to 1 if 'E', -1 if 'W', 0 if 'N' or 'S' y+=Y= // Set `Y` to (and increase `y` by `Y` afterwards): b|a>69&a<87?1-a%2*2 // Set `Y` to 1 if 'N', -1 if 'S' : // And if the boolean check was falsey: 0;} // Set `Y` to 0 if 'E' or 'W' return r+x+"|"+y;} // Append the ending coordinates, and return the result-String ``` [Answer] # [Perl 5](https://www.perl.org/) `-n`, ~~94~~ 74 bytes ``` map{say$v=/N/-/S/,',',$h=/E/-/W/;$y+=$v;$x+=$h}/[NS][EW]?|E|W/g;say"$x,$y" ``` [Try it online!](https://tio.run/##K0gtyjH9/z83saC6OLFSpcxW309fVz9YX0cdCFUybPVdgdxwfWuVSm1blTJrlQoglVGrH@0XHBvtGh5rX@NaE66fbg3Uq6RSoaNSqfT/f3B4sKufn2twuJ/rv/yCksz8vOL/ur6megaGBv918wA "Perl 5 – Try It Online") [Answer] ## JavaScript (ES6), 102 bytes ``` f= s=>s.replace(/((N)|(S))?((E)|(W))?/g,(m,v,n,s,h,e,w)=>(x+=h=!w-!e,y+=v=!s-!n,m?[h,v]+` `:[x,y]),x=y=0) ``` ``` <input oninput=o.textContent=/[^NSEW]/.test(this.value)?``:f(this.value)><pre id=o>0,0 ``` Returns a string. [Answer] # [Ruby](https://www.ruby-lang.org/), ~~75~~ 71 bytes ``` ->x{[*x.scan(/[NS][EW]?|./),x].map{|s|s.chars.sum{|c|1i**(c.ord%8%5)}}} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf166iOlqrQq84OTFPQz/aLzg22jU81r5GT19TpyJWLzexoLqmuKZYLzkjsahYr7g0t7omucYwU0tLI1kvvyhF1ULVVLO2tvZ/gUJatFJweLCrn59rcLifq1IsF1gIyHUNdg0ODg/3C4eLuYKgKxIXxnQFif4HAA "Ruby – Try It Online") -4 bytes thanks to benj2240. Since returning complex numbers looks to be an acceptable output format, I guess it won't get much golfier than just making a port of the very nice [Lynn's answer](https://codegolf.stackexchange.com/a/163310/78274). [Answer] # [F# (Mono)](http://www.mono-project.com/), 269 bytes ``` let f s= let l,h=(string s).Replace("NW","A").Replace("NE","B").Replace("SW","C").Replace("SE","D")|>Seq.map(function 'N'->0,1|'S'->0,-1|'W'-> -1,0|'E'->1,0|'A'-> -1,1|'B'->1,1|'C'-> -1,-1|'D'->1,-1)|>Seq.mapFold(fun(x,y) (s,t)->(s,t),(x+s,y+t))(0,0) Seq.append l [h] ``` [Try it online!](https://tio.run/##lZCxasMwEIZ3P8UhKJaIFOwHiMFJ1FFDNWgoHUwiNQZHdiMVEvC7uycR2nQpdNKn7@7nuHNBnEc/LstgIzgImwISDfy0oSFeev8Oga1f7DR0B0uJMoSTljwaiWb7aHTq2f0yqWdP2Nxo@7E@dxN1n/4Q@9FDqUrRVLyeS51BIBkkEDWv5lIiZmjvDsvb7BB2d5cy@yxF/TPjeRyOaQ698hsDGnhkoskPp9dV4LdVZIxWvGIFpEg3TdYfYYDX09tCHeAeWioltcEVGcxN7uqjvQCd8DDReSBPLQFWfH9JkYIYklpqbQye639Jqf4OLF8 "F# (Mono) – Try It Online") [Answer] # sed, 125 The *taking liberties with output format* version: Score includes +1 for the `-r` parameter to sed. ``` s/(N|S)(E|W)/\L\2,\1 /g s/N|S/,& /g s/E|W/&, /g s/N|E/A/gi s/S|W/a/gi p : s/(\S*),(\S*) (\S*),(\S*)/\1\3,\2\4/ t s/Aa|aA// t ``` [Try it online](https://tio.run/##TcqxCoNADAbg2TyInOVK0Hbq5pCtZMmQJYvQIi5Veo4@u9ecpVAC4fv/JD0fOScMvEkTaNMG7W5dtLbCERJ6jbH@2q9Yx19P2OM4OcXroXCBm8dgcmrisas/o7V2idbZFWH1t37Yhh7dObMoAYgKMZMoe3CQkIgqqycqQwcAqEjVexEpr7zPyzrNr5TP7w8). Output is as follows: * coordinate elements are comma-separated * each set of coordinates are TAB-separated * the final coordinate is on a new line * all numbers are in ℤ-unary: + a string of `A` characters represents the +ve integer `len(string)` + a string of `a` characters represents the -ve integer `-len(string)` + the empty string represents `0` For example: * `,` is [0,0] * `,AA` is [0,2] * `aaa,` is [-3,0] --- # [sed 4.2.2 including GNU exec extension](https://www.gnu.org/software/sed/), 147 The *sensible output format* version: Score includes +1 for the `-r` parameter to sed. ``` s/(N|S)(E|W)/\L\2 \1\n/g s/N|S/0 &\n/g s/E|W/& 0\n/g s/N|E/1/gi s/S|W/-1/gi p : s/(\S+) (\S+)\n(\S+) (\S+)/\1+\3 \2+\4/ t s/\S+/$[&]/g s/^/echo /e ``` Output is given as space-separated coordinates, one per line. There is an extra newline between the penultimate and ultimate sets of coordinates - not sure if that is problematic or not. [Try it online!](https://tio.run/##TYyxCsJADIb3PMUNUlpKSVud3LPJLRkyGF201C694nXss3vGQ0QC4fv@PyQO95Qiln7jqqRNKtST9k47nXGEiJZj64qv2QEWrv11hB2OkyFb0WRe4GheKteVy1vnP0Htat077Ws9IKx2aSnuzsUlf7zicHsEh0NKnoUAWJi8JxZvYkBMzCJezOgzlAGAiF5hWacwx9Q83w "sed 4.2.2 – Try It Online") [Answer] # PHP, 153 bytes let a regex do the splitting; loop through the matches, print and sum up the intermediate results: ``` preg_match_all("/[NS][EW]?|E|W/",$argn,$m);foreach($m[0]as$s){$x+=$p=strtr($s[-1],NEWS,1201)-1;$y+=$q=strtr($s[0],NEWS,2110)-1;echo"$p,$q ";}echo"$x,$y"; ``` Run as pipe with `-nR` or [try it online](http://sandbox.onlinephpfunctions.com/code/78d9cd6eb9c8892e3e9fdb036fe509e3fafc307d). [Answer] # [C (gcc)](https://gcc.gnu.org/), 173 bytes It's interesting doing this one in a language with no regex support! ``` f(char*s){char*t="[%d,%d]\n";int x[4]={0},i;for(;*s;*x=x[1]=!printf(t,x[1],*x))for(i=-1;i<5;)if(*s=="S NW E"[++i]){x[i/3+2]+=x[i/3]=i%3-1;i+=2-i%3;s++;}printf(t,x[3],x[2]);} ``` [Try it online!](https://tio.run/##TY69bsMwDIT3PIXqwoD@3NZ2MzHMljVLhgyqBkOOEwKNU1huYMDws6uSpy7kR/B4PFdcnQuv1Lvv3/bCdn5s6fF224eOu1szSC/mtY@YmbzVeWu/@gyoH9lkPi3OH4sm6B4DB@lBTjiZ0uLLzxAVHR91GrWchEgSwqIE2m1BUMelR8xO7Hhmh8woRVbMk6H3WlVW4UoWKa/ThcKqiAheKVj@Wdc2lsoKWEIKdG@o5wma4ep0Ss2kjPwUbN4wFn@mxb4UbKVnjCZgs4RwPJ0Pfw "C (gcc) – Try It Online") ]
[Question] [ Based on my previous question of the same type, [Build an adding machine using NAND logic gates](https://codegolf.stackexchange.com/questions/10845/build-an-adding-machine-using-nand-logic-gates), this time you're being asked to multiply instead of add. Build a diagram of (two-wire) NAND logic gates that will take the input wires `A1`, `A2`, `A4`, `B1`, `B2`, `B4`, representing two binary numbers `A` to `B` from 0 to 7, and return values on the output wires `C1`, `C2`, `C4`, `C8`, `C16`, and `C32`, representing `C`, which is the product of `A` and `B`. Your score is determined by the number of NAND gates you use (1 point per gate). To simplify things, you may use AND, OR, NOT, and XOR gates in your diagram, with the following corresponding scores: * `NOT: 1` * `AND: 2` * `OR: 3` * `XOR: 4` Each of these scores corresponds to the number of NAND gates that it takes to construct the corresponding gate. Lowest score wins. [Answer] # ~~60 55 50~~ 48 gates ![48-gate multiplier](https://i.stack.imgur.com/zSa1t.png) --- The original (60 gates) was the systematic approach - multiply each digit with each, and then sum them together. Namely, see [Wallace trees](http://en.wikipedia.org/wiki/Wallace_tree) and [Dadda trees](http://en.wikipedia.org/wiki/Dadda_tree) ![60-gate multiplier](https://i.stack.imgur.com/XJuJW.png) The top half is the multiplication network - multiply each digit with each, and group output digits with the same weight. Some bits have been left inverted to save gates. The second half is the adder network. Each box represents a single adder - either a half-adder (5 gates - 1x XOR and an inverter), or a full adder (9 gates - 2x XOR and NAND the inverted carry bits). The top are inputs, the bottom output is the sum, the left output is the carry-out. [see the previous challenge](https://codegolf.stackexchange.com/a/10848/7209) The 2x2 multiplier has then been hand-optimised to a custom-built 13-gate network, [which is the optimal size as found by](https://codegolf.stackexchange.com/questions/12261/build-a-multiplying-machine-using-nand-logic-gates/12263#comment23825_12261) [@boothby](https://codegolf.stackexchange.com/users/2180/boothby). Thanks! Pasting it into the low-bit corner and reoptimising the adder tree saves five gates (see revision #2). Pasting it into the high-bit corner as well, however, produces overlap. A little bit of math tells us, however, that dropping the low-bit of the high multiplier solves the overlap and what's left to do is to add the remaining two bits and sum up stuff. This alone, unfortunately, does not provide any savings, but it does open two optimisations. First, the two multipliers have two gates in common, and can be fused together. At this point, we're back at 55. Second, in the addition network, we don't need a half-adder because we know its carry will be zero. We can replace it with an OR. An OR is a NAND with its inputs inverted. This produces us with two 2-chains of NOTs on each branch, which can then be removed, for a total saving of five gates. Unfortunately, the half-adder at C16 still carries, so we cannot do the same there. Third, a full adder has a useful property: if you invert its inputs and its outputs, it still behaves the same. Since all its inputs are already inverted, we can just as well move the inverters behind it. Twice. We could have done the same in the original, but... oh well. We still have a half-adder with two inverted inputs. I want optimise this part more, but I doubt I can. Since we're pulling out a NOT from inside a component, we have to signify that somehow. We have obtained a half-adder with inverted carry (AKA tapped XOR) at a cost of four gates. In the meantime, we have also redrawn the diagram significantly. [Answer] # 39 gates I am quite sure there are no simpler designs than mine here. It was very difficult to make. I make other minimal circuits too. Transmission delay is indicated by downward position of each NAND gate on the sheet. ![Minimal 3 bit multiplier](https://i.stack.imgur.com/foczH.jpg) Verilog code and testing: ``` // MINIMAL 3 BIT MULTIPLICATOR // // The simplest 3 bit multiplicator possible, using 39 NAND gates only. // // I have also made multiplicators that are faster, more efficient, // use different gates, and multiply bigger numbers. And I also do // hard optimization of other circuits. You may contact me at // [[email protected]](/cdn-cgi/l/email-protection) // // This is my entry to win this hard Programming Puzzle & Code Golf // at Stack Exchange: // https://codegolf.stackexchange.com/questions/12261/build-a-multiplying-machine-using-nand-logic-gates/ // // By Kim Øyhus 2018 (c) into (CC BY-SA 3.0) // This work is licensed under the Creative Commons Attribution 3.0 // Unported License. To view a copy of this license, visit // https://creativecommons.org/licenses/by-sa/3.0/ module mul3x3 ( in_000, in_001, in_002, in_003, in_004, in_005, out000, out001, out002, out003, out004, out005 ); input in_000, in_001, in_002, in_003, in_004, in_005; output out000, out001, out002, out003, out004, out005; wire wir000, wir001, wir002, wir003, wir004, wir005, wir006, wir007, wir008, wir009, wir010, wir011, wir012, wir013, wir014, wir015, wir016, wir017, wir018, wir019, wir020, wir021, wir022, wir023, wir024, wir025, wir026, wir027, wir028, wir029, wir030, wir031, wir032; nand gate000 ( wir000, in_000, in_005 ); nand gate001 ( wir001, in_000, in_004 ); nand gate002 ( wir002, in_000, in_003 ); nand gate003 ( out000, wir002, wir002 ); nand gate004 ( wir003, in_004, in_001 ); nand gate005 ( wir004, wir003, wir003 ); nand gate006 ( wir005, in_003, in_002 ); nand gate007 ( wir006, wir000, wir005 ); nand gate008 ( wir007, in_004, in_002 ); nand gate009 ( wir008, in_001, in_005 ); nand gate010 ( wir009, wir008, wir007 ); nand gate011 ( wir010, in_001, in_003 ); nand gate012 ( wir011, wir001, wir010 ); nand gate013 ( wir012, out000, wir004 ); nand gate014 ( wir013, wir004, wir012 ); nand gate015 ( wir014, wir011, wir012 ); nand gate016 ( out001, wir014, wir014 ); nand gate017 ( wir015, in_002, in_005 ); nand gate018 ( wir016, wir015, wir015 ); nand gate019 ( wir017, out000, wir016 ); nand gate020 ( wir018, wir017, wir013 ); nand gate021 ( wir019, wir016, wir018 ); nand gate022 ( wir020, wir019, wir009 ); nand gate023 ( wir021, wir020, wir017 ); nand gate024 ( wir022, wir020, wir009 ); nand gate025 ( wir023, wir022, wir021 ); nand gate026 ( out005, wir022, wir022 ); nand gate027 ( wir024, wir016, wir022 ); nand gate028 ( wir025, wir006, wir018 ); nand gate029 ( wir026, wir025, wir006 ); nand gate030 ( wir027, wir025, wir018 ); nand gate031 ( out002, wir026, wir027 ); nand gate032 ( wir028, wir004, wir027 ); nand gate033 ( wir029, wir023, wir028 ); nand gate034 ( wir030, wir028, wir028 ); nand gate035 ( wir031, wir030, wir021 ); nand gate036 ( out004, wir031, wir024 ); nand gate037 ( wir032, wir029, wir031 ); nand gate038 ( out003, wir032, wir032 ); endmodule module mul3x3_test; reg [5:0] AB; // C=A*B wire [5:0] C; mul3x3 U1 ( .in_000 (AB[0]), .in_001 (AB[1]), .in_002 (AB[2]), .in_003 (AB[3]), .in_004 (AB[4]), .in_005 (AB[5]), .out000 (C[0]), .out001 (C[1]), .out002 (C[2]), .out003 (C[3]), .out004 (C[4]), .out005 (C[5]) ); initial AB=0; always #10 AB = AB+1; initial begin $display("\t\ttime,\tA,\tB,\tC"); $monitor("%d,\t%b\t%b\t%b",$time, AB[5:3], AB[2:0],C); end initial #630 $finish; endmodule // iverilog -o mul3x3_test mul3x3_test.v // vvp mul3x3_test ``` Kim Øyhus ]
[Question] [ I'm sure most, if not all, of you have [come across this](http://www.mrc-cbu.cam.ac.uk/people/matt.davis/Cmabrigde/) at some point or another: > > Aoccdrnig to a rscheeachr at Cmabrigde Uinervtisy, it deosn't mttaer > in waht oredr the ltteers in a wrod are, the olny iprmoetnt tihng is > taht the frist and lsat ltteer be at the rghit pclae. The rset can be > a toatl mses and you can sitll raed it wouthit porbelm. Tihs is > bcuseae the huamn mnid deos not raed ervey lteter by istlef, but the > wrod as a wlohe. > > > * Create a program that inputs any amount of text. For testing purposes, use the unscrambled version of the above text, found below. * The program must then randomly transpose the letters of each word with a length of 4 or more letters, except the first and last letter of each word. * All other formatting must remain the same (capitalization and punctuation, etc.). Testing text: > > According to a researcher at Cambridge University, it doesn't matter > in what order the letters in a word are, the only important thing is > that the first and last letter be at the right place. The rest can be > a total mess and you can still read it without problem. This is > because the human mind does not read every letter by itself but the > word as a whole. > > > As usual, this is a code-golf. Shortest code wins. [Answer] ## Ruby - 50 48 chars, plus `-p` command line parameter. ``` gsub(/(?<=\w)\w+(?=\w)/){[*$&.chars].shuffle*''} ``` Thanks @primo for -2 char. ## Test ``` ➜ codegolf git:(master) ruby -p 9261-cambridge-transposition.rb < 9261.in Acdrcinog to a racreseher at Cagribmde Ursvetniiy, it dsoen't mttaer in waht odrer the leertts in a word are, the olny ionarpmtt tnhig is that the fsirt and last letetr be at the rghit pcale. The rset can be a taotl mses and you can slitl raed it wthiuot perlbom. Tihs is buaecse the hmuan mind does not raed ervey lteetr by ietlsf but the word as a wlhoe. ``` [Answer] ## PHP 84 bytes ``` <?for(;$s=fgets(STDIN);)echo preg_filter('/\w\K\w+(?=\w)/e','str_shuffle("\0")',$s); ``` Using a regex to capture words that are at least ~~4~~ 3 letters long†, and shuffling the inner characters. This code can handle input with multiple lines as well. If only one line of input is required (as in the example), this can be reduced to **68 bytes** ``` <?=preg_filter('/\w\K\w+(?=\w)/e','str_shuffle("\0")',fgets(STDIN)); ``` --- † There's only one letter in the middle, so it doesn't matter if you shuffle it. [Answer] # Python, 118 Python is terribly awkward for things like this! ``` from random import* for w in raw_input().split():l=len(w)-2;print l>0and w[0]+''.join((sample(w[1:-1],l)))+w[-1]or w, ``` ### Bonus I tried some other things that I thought would be clever, but you have to import all sorts of things, and a lot of methods don't have return values, but need to be called separately as its own statement. The worst is when you need to convert the string to a list and then `join`ing it back to a string again. Anyways, here are some of the things that I tried: Regex! ``` import re,random def f(x):a,b,c=x.group(1,2,3);return a+''.join(random.sample(b,len(b)))+c print re.sub('(\w)(\w+)(\w)',f,raw_input()) ``` Permutations! ``` import itertools as i,random as r for w in raw_input().split():print''.join(r.choice([x for x in i.permutations(w)if w[0]+w[-1]==x[0]+x[-1]])), ``` You can't shuffle a partition of a list directly and `shuffle` returns `None`, yay! ``` from random import* for w in raw_input().split(): w=list(w) if len(w)>3:v=w[1:-1];shuffle(v);w[1:-1]=v print ''.join(w), ``` [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 10 bytes ``` ?V`\B\w+\B ``` [Try it online!](https://tio.run/##PZBNTsQwDIWv4h0LRiNxAsRwBWDVBW7qaSzlZ2Q7VD19cVKElIXj9/LZL0LGBV@O4/Xre7pN2/N0O463EKosXFawCghCSighkgAavGOehZeV4LPwD4my7Rdgg6WSlieDjGZu5QJbdL@T/GaRIFEXtCsIm/cBhS5DqiXtwPlRxbCYt/pwVi/QhuHOogZYFkjoxYmCmeBPF16jwSNhoCt89Aa5LWAZHs9hmCCT6mDstQ1NjVNyKy49wMYWa3OK1DlR7hxfwc9MAZvSGBRb9oeZndIDQ6l2Asj/Yv9fzNOYUrrD3M4Fz7zak8ea6PoL "Retina – Try It Online") Hey, this old challenge was made for the new Retina! ### Explanation `\B\w+\B` matches groups of letters between non-boundaries, that is groups of letters that don't begin or end a word. Since regexes are greedy, this will match all the letters of a word except the first and the last one. `V` is the "reverse" stage, that reverses the order of characters in each match of the regex. With the `?` option it scrambles them instead. [Answer] ## J (48) ``` ''[1!:2&4('\w(\w+)\w';,1)({~?~@#)rxapply 1!:1[3 ``` Explanation: * `1!:1[3`: read all input from stdin * `rxapply`: apply the given function to the portions of the input that match the regex * `({~?~@#)`: a verb train that shuffles its input: `#` counts the length, this gets applied to both sides of `?` giving N distinct numbers from 0 to N, `{` then selects the elements at those indices from the input array. * `('\w(\w+)\w';,1)`: use that regex but only use the value from the first group * `[1!:2&4`: send unformatted output to stdout * `''[`: suppress formatted output. This is necessary because otherwise it only outputs that part of the output that fits on a terminal line and then ends with `...`. [Answer] ## [Nibbles](http://golfscript.com/nibbles), 15 bytes This was a little awkward since nibbles doesn't have shuffle or even randomness (nor does it have regex). ``` +.%~@ \$a :@ ::`($ ++=~ `)\`'$ `# $ 0 $ ``` (Nibbles isn't on TIO yet). But use it like: ``` > nibbles cambridge.nbl < input.txt Aoinrccdg to a raeeercshr at Caibrmgde Uvteiinrsy, it doesn't mttaer in waht oerdr the ltteers in a word are, the olny itoanrmpt tinhg is taht the first and last ltteer be at the rihgt palce. The rest can be a ttoal mess and you can stlil raed it wutoiht poelbrm. Tihs is buaecse the huamn mind does not raed every ltteer by itelsf but the word as a wolhe. ``` That's the literate form which is 30 nibbles. That last $ could be left out but there is no point since this program is 30 nibbles (it would be 29 half bytes then rounded up) ### How? ``` +.%~@ \$a concat the map of the split by alpha numeric chars :@ append the value that preceded the split match ::`($ append the first value of the match to ++=~ concat the concat of the group by of `)\`'$ the tail of the reverse of the transpose of the tail of the match `# $ 0 hash of the char (0 says range is infinite) $ the head of the reversed thing from earlier ``` Essentially it selects groups of alphanums, then selects the inner part of that using uncons twice. Then for randomness does a group by (which also sorts by) the hash of a character. The transpose part is so that doing uncons on an empty string returns an empty string instead of null character (which becomes a space). You could leave it out but you'd get an extra space on 1 letter words like "a". [Answer] ## APL 107 Unfortunately my APL interpreter does not support regexs so here's a home rolled version where the text to be scrambled is stored in the variable t: ``` ⎕av[((~z)\(∊y)[∊(+\0,¯1↓n)+¨n?¨n←⍴¨y←(~z←×(~x)+(x>¯1↓0,x)+x>1↓(x←~53≤(∊(⊂⍳26)+¨65 97)⍳v←⎕av⍳,t),0)⊂v])+z×v] ``` Essentially the code partitions the text into words based on the letters of the alphabet only and then into the letters between the first and last letters of those words. These letters are then scrambled and the whole character string reassembled. [Answer] ## APL, ~~58~~ 49 I believe this works in IBM APL2 (I don't have IBM APL) ``` ({⍵[⌽∪t,⌽∪1,?⍨t←⍴⍵]}¨x⊂⍨~b),.,x⊂⍨b←' ,.'∊⍨x←⍞,' ' ``` --- If not, then in Dyalog APL, add to the front: ``` ⎕ML←3⋄ ``` which adds 6 chars --- [Answer] ## VBA, 351 373/409 ``` Sub v(g) m=1:Z=Split(g," "):j=UBound(Z) For u=0 To j t=Z(u):w=Len(t):l=Right(t,1):If Not l Like"[A-Za-z]" Then w=w-1:t=Left(t,w):e=l Else e="" If w>3 Then n=Left(t,1):p=w-1:s=Right(t,p):f=Right(t,1) For p=1 To p-1 q=w-p:r=Int((q-1)*Rnd())+1:n=n & Mid(s,r,1):s=Left(s,r-1) & Right(s,q-r) Next Else n=t:f="" End If d=d & n & f & e & " " Next g=d End Sub ``` Alternate (larger) Method: ``` Sub v(g) m=1:Z=Split(g," "):j=UBound(Z) For u=0 To j t=Split(StrConv(Z(u),64),Chr(0)):w=UBound(t)-1:l=Asc(t(w)):If l<64 Or (l>90 And l<97) Or l>122 Then e=t(w):w=w-1 Else e="" If w>3 Then n=t(0):p=w-1:s="" For i=-p To -1 s=t(-i) & s Next f=t(w) For p=1 To p-1 r=Int((w-p)*Rnd())+1:n=n & Mid(s,r,1):s=Left(s,r-1) & Right(s,w-p-r) Next n=n & s Else n=Z(u):f="":e="" End If d=d & n & f & e & " " Next g=d End Sub ``` Both of these methods change the value of the variable passed to the `Sub`. i.e. ``` Sub Test() strTestString = "This is a test." v strTestString Debug.Print strTestString End Sub ``` will output something like this: ``` "Tihs is a tset." ``` Also, this does randomize mid-word punctuation, so this may not fit the spec 100%. [Answer] # APL NARS 172 chars ``` r←g x;i;s;d;k s←⎕AV[98..123]∪⎕A i←1⋄v←''⋄r←''⋄k←⍴x A:d←''⋄→C×⍳i>k⋄d←x[i]⋄→C×⍳∼d∊s⋄v←v,d⋄i+←1⋄→A C:v←{t←¯2+⍴r←⍵⋄t≤1:r⋄r[1+t?t]←⍵[1+⍳t]⋄r}v r←∊r,v,d v←''⋄i+←1⋄→A×⍳i≤k g x←⍞ ``` 13+17+18+44+41+8+17+5+9=172; This function g() has input as a string; has output as a string. I add the input command because i don't know how insert \' in a quoted string. Commented ``` ∇r←g x;i;s;d;k ⍝ words are element of a-zA-Z separed from all other s←⎕AV[98..123]∪⎕A ⍝a-zA-Z ascii ⎕IO = 1 i←1⋄v←''⋄r←''⋄k←⍴x A: d←''⋄→C×⍳i>k⋄d←x[i]⋄→C×⍳∼d∊s⋄v←v,d⋄i+←1⋄→A C: v←{t←¯2+⍴r←⍵⋄t≤1:r⋄r[1+t?t]←⍵[1+⍳t]⋄r}v r←∊r,v,d v←''⋄i+←1⋄→A×⍳i≤k ∇ ``` result ``` g x←⍞ According to a researcher at Cambridge University, it doesn't matter in what order the letters in a word are, the only important thing is that the first and last letter be at the right place. The rest can be a total mess and you can still read it without problem. This is because the human mind does not read every letter by itself but the word as a whole. Androiccg to a rhraeecser at Cgirbdmae Uirevtsiny, it deson't mtetar in waht oderr the ltrtees in a wrod are, the olny intro apmt tinhg is taht the frsit and lsat lteter be at the rghit pacle. The rset can be a ttaol mses and you can siltl rae d it wtuhoit poeblrm. Tihs is bcsauee the hmaun mnid deos not raed eervy lteter by isletf but the wrod as a wolhe. ``` [Answer] # PHP 7.1, not competing, 80 bytes ``` for(;$w=$argv[++$i];)echo$w[3]?$w[0].str_shuffle(substr($w,1,-1)).$w[-1]:$w," "; ``` takes input from command line arguments. Run with `-nr`. (will obviously fail at punctuation) [Answer] # PHP, 94+1 bytes +1 for `-R` flag ``` <?=preg_replace_callback("/(?<=\w)\w+(?=\w)/",function($m){return str_shuffle($m[0]);},$argn); ``` Pipe input through `php -nR '<code>'`. Note: `preg_replace_callback` came to PHP in 4.0.5; closures were introduced in php 5.3; so this requires PHP 5.3 or later. Unfortunately, the match is always sent as an array, even if there are no sub patterns, thus I cannot just use `str_shuffle` as the callback, which would save 29 bytes. [Answer] # JavaScript, ~~76~~ 67 bytes thanks to [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld) for -9 bytes. ``` t=>t.replace(/\B\w+\B/g,m=>[...m].sort(_=>Math.random()-.5).join``) ``` [Try it online!](https://tio.run/##PVC7bsMwDPwVIkttNFGmjg7QdO7WTk3R0DJtKdAjkOgY/nqXsosCGije8XjHGz4w62TvfAixo6VvFm5OrBLdHWqqjpfzZXq@nI/D3jenL6WU/1Y5Jq5@mtM7slEJQxd9VR/US61u0YbrtV50DDk6Ui4OVV/tXrWOqbNhAI6AkCgTJm0oATK8oW@T7QaCz2AflLLleQ@WoYuUwxODR2ah2gCTEb4oyY8NgaMC5IIgTNIHTLRfoRjcDNbfxSkGllZZbrMUyCuhtykziHdwKMUmBS3BH57sYBjWIyj4KA0SmsawciQHowNPOa8acxxXLLN1TqjYlQCTZRNHUUmxdeSLjliQ15LGMdO6yIxeBr0VlRIYQuRNgOQW878xScOZXA/tuBnc8uaS3JRT7@p6@QU "JavaScript (Node.js) – Try It Online") --- ## Ungolfed ``` t => // function with a single argument t.replace( // Replace ... /\B\w+\B/g, // every match of the regex m => ... // with the return value of the replacement function ) / /g // Match all occurences of \w+ // 1 or more word chars ... \B \B // ... that aren't on the beginning or end of the word m => // Replacement function [...m] // convert matched string to a list of chars .sort(_ => Math.random()-.5) // sort with a random comparision function .join`` // join the list into a single string ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~22~~ 20 bytes ``` e€ØẠ+ƝỊŻœṗµḢ,ṪjW)ẎẊ€ ``` [Try it online!](https://tio.run/##PZA9TsNAEIWvMh1CRLkD4gog6rE98U60P9HuGMstZQoaCmiQECWiRSJJBwr3WC5iZm2EtMXsvLffzNs1WTuMI/3cvn095v3z2fdTPmyPh@N93j18vuePl0Xeva6vT/P@Lu@3ahvH8byuQ2zYtyABECIlwlgbioACF@iqyE1LcOX5hmJiGRbAAk2g5E8EHIqolT30Rv1K0psYAktFSEVB6LUPGGkxScHbAdhtQhT0oq0ynJMWKJNhxTEJoG/AohYzCiqCPz1yawQ2FmtawmVpkNpq9JNHcwhacJTSxBhCN2lJ2Fq1YlMC9CwmdEqJobLkCkdX0FNRjV2iaZDpnD50rJQSGHyQGUD6F8P/YppGEtkVVN284Jw3leQmWFr@Ag "Jelly – Try It Online") This was fun to make. Each non-alphabet character is grouped into a single character string, and the first and last characters of each word are grouped the same way as well. That way, taking a random permutation of those characters will not change their order. Made with a lot of help from caird coinheringaahing. -2 bytes from caird coinheringaahing. ## Explanation ``` e€ØẠ+2\ỊŻœṗ⁸µḢ,ṪjW)ẎẊ€ € for each character: e ØẠ check if it's in the alphabet +2\ add overlapping pairs Ị check if they are ≤ 1 œṗ⁸ and partition the input using that bitmask µ ) execute the following on each part: Ḣ,ṪjW get head, tail, and join with the modified list Ẏ join the list of triplets together Ẋ€ get a random permutation of each of the elements ``` [Answer] # [Python 3](https://docs.python.org/3/), 113 bytes *based on the original [python answer](https://codegolf.stackexchange.com/a/9355/86751) by [daniero](https://codegolf.stackexchange.com/users/4372/daniero)* ``` import re,random print(re.sub('(\w)(\w+)(\w)',lambda m:m[1]+''.join(random.sample(m[2],len(m[2])))+m[3],input())) ``` [Try it online!](https://tio.run/##PVDLboQwDLz3K3wDtAip3VtvVX@hPdE9GPBuXOWBEqeIr6dOqColke0Zjz1ZdzHBX4@D3RqiQKQ@ol@Ce1oje2kjDSlPbdN@bZ3eS3m6prfopgXBvbrx@XZpmuE7sG/PziGhWy21bny59ZZ8Dbquu7jxeuvZr1laTY/jbZ5DXNg/QAKgjk6EcTYUAQXedULk5UHw6fmHYmLZe2CBJVDyjYBDEaWyh80oX5U0E0NgqQCpIAib1gHVVYWCtzucTtGLlspwThqgVMKdYxJQG2BRg1MKJoI/PPLDCKwWZxrgoxRIaTP6ylEfghYcpVQ19pArloStVSouxcDG@uVZVWKYLLmioyvomWjGnKgOMtlpo2NVKYbBBzkFSP9i/19M3Ugie4cpnwueflNxboKl4Rc "Python 3 – Try It Online") [Answer] # [Stax](https://github.com/tomtheisen/stax), ~~15 14~~ 13 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` â#]ø\┘‼↕ip2╚_ ``` [Run and debug it](https://staxlang.xyz/#p=83235d005cd91312697032c85f&i=According+to+a+researcher+at+Cambridge+University,+it+doesn%27t+matter+in+what+order+the+letters+in+a+word+are,+the+only+important+thing+is+that+the+first+and+last+letter+be+at+the+right+place.+The+rest+can+be+a+total+mess+and+you+can+still+read+it+without+problem.+This+is+because+the+human+mind+does+not+read+every+letter+by+itself+but+the+word+as+a+whole.) Regex is busted. -2 bytes from recursive. [Answer] # [R](https://www.r-project.org/), 159 bytes ``` function(x){l=attr(w<-el(gregexpr("[a-zA-Z]+",x)),"m") Map(function(i,j)substr(x,i,j)<<-Reduce(paste0,sample(substring(x,r<-i:j,r))),s<-w[l>3]+1,s+l[l>3]-3) x} ``` [Try it online!](https://tio.run/##bZJPb5xADMXvfAqLS0E7RK1yq9hIUc@9VO2lUVSZwQsTzR80NoVt1c@@NZDmVImDx@/5jX9AvlkMXXb9QD8kY@QpMZ1vlzlacSlWa/3bn1EkV0vbkK@GTAOtU67KJ2x@PTbfn0@lWevalKGsi884VW@jzrzUPHess6vZDm3bfKF@tlRNyELvDWOYPFWHycVBfblt3McXk2uN5LZZnvzD/fPpg@GT38vmvi7WP7fDfy4frU251xIkAUImJsx2pAwo8OkfGXyL7idldnI14AT6RBzfCQQFU6uLsIzq1yQ9yUjgaRN4UxAW7QNmMruUor@CC1PKglG0tV3uWAuU3XBxmQUw9uCV8jUKOoJXPbthFJg8WrqDr1uD1GYx7h7lEPQQiHnPuKZ511ic92rFfgNYnIxp1pScOk9hy9EV9OnI4sy0XzTOQQeD05QNGGKSI4D0XVzfFlMaYfIX6OZjwYOXN/Ixebori@I//0h1fIK6uP0F "R – Try It Online") Posted before realizing that there was already [another](https://codegolf.stackexchange.com/a/9321/95126) [R](https://www.r-project.org/) answer, but pleasingly the two approaches are quite different... **Ungolfed code:** ``` cambridge_transpose= function(x){ # x is the input string, w=el(gregexpr("[a-zA-Z]+",x)) # w gets the words in x using a regex, l=attr(w,"match.length") # l gets the lengths of each word, s=w[l>3]+1 # s is the start letter to jumble in each word, e=s+l[l>3]-3 # e is the end letter to jumble in each word. Map(function(i,j) ... ,s,e) # Now, use this function on all elements i,j from s,e: substr(x,i,j)<<- # replace letters in x from i to j Reduce(paste0, # with these letters joined-together: sample( # a random sample of substring(x,r<-i:j,r))) # the letters in x from i to j. x} # Finally, return (modified) x. ``` [Answer] # Python3, 110 bytes: ``` lambda x:re.sub('(?<=\w)\w{3,}(?=\w)',lambda x:''.join(r.sample(g:=x.group(),len(g))),x) import re,random as r ``` [Try it online!](https://tio.run/##PVDLboQwDLz3K6y9ECTEZS/Vqquq6i@0t70YMJAqD@SYsqjqt1MHqpVycDzj8YynVcYYzs8Tb/31tjn0TYdwvzDVaW5MYV5frrelvC0/5@rXvOa6qB6soqi/og2G64R@cmSGy/VeDxznyZSVo2CGsiyre/lk/RRZgKliDF30gAl4m9gGMb05nU5vbRu5s2EAiYBKTITcjsSAAu@6kG03EHwG@02crKwVWIEuUgqFgEcRpdoAy6h8VdKfjASOMpAygrBoH1A97FAMboXDFwbRVl5ukxYoO6G3nATULjjU4pCChuAfZzuMApPDlmr4yA1SWoth52gOQQeeUto11jjvWBLrnFKxywEWq/efVYVj48hnHbWgr6EW50T7onH2OuitquTAEKIcAqS3WB/GNI0kcj0082HwyJty8jE6qvXMZbn9AQ) [Answer] ## R, 179 Using the function I wrote for the [randomize letters in a word problem](https://codegolf.stackexchange.com/questions/3293/how-to-randomize-letters-in-a-word): Input: ``` s <- "According to a researcher at Cambridge University, it doesn't matter in what order the letters in a word are, the only important thing is that the first and last letter be at the right place. The rest can be a total mess and you can still read it without problem. This is because the human mind does not read every letter by itself but the word as a whole." ``` Solution: ``` f=function(w){l=length;s=strsplit(w,"")[[1]];ifelse(l(s)<3,w,paste(c(s[1],sample(s[2:(l(s)-1)]),s[l(s)]),collapse=""))} g=Vectorize(f) paste(g(strsplit(s," ")[[1]]), collapse=" ") ``` Result: ``` [1] "Arioccdng to a reehaecrsr at Cabrgimde Uveirisnyt, it des'not mttear in waht odrer the lttrees in a wrod are, the olny inpotmart thnig is that the fsrit and lsat letetr be at the right palce. The rset can be a toatl mses and you can stlil raed it wutioht pmrlebo. This is bsuceae the hmuan mnid deos not read ervey lteetr by iesltf but the word as a wleho." ``` [Answer] # Pyth, 23 bytes ``` jdm?gld4++hd.<Ptd1eddcz ``` Non-competing because Pyth was made after this challenge was posted. [Try it online](http://pyth.herokuapp.com/?code=jdm%3Fgld4%2B%2Bhd.%3CPtd1eddcz&input=According+to+a+researcher+at+Cambridge+University%2C+it+doesn%27t+matter+in+what+order+the+letters+in+a+word+are%2C+the+only+important+thing+is+that+the+first+and+last+letter+be+at+the+right+place.+The+rest+can+be+a+total+mess+and+you+can+still+read+it+without+problem.+This+is+because+the+human+mind+does+not+read+every+letter+by+itself+but+the+word+as+a+whole.&debug=0) [Answer] # [Japt](https://github.com/ETHproductions/japt), 32 bytes ``` m@Xl ¨4?Xg0 +Xs1J ö(x) +XgJ:X}" ``` [Try it online!](https://tio.run/##PZBNTsQwDIWv8jQbQIxGILFiA2h2swapW7f1NEb5GSUuQxfchxNwADhYcVqElIXj9/LZL6900nkOj43H9@fdQzPc4Loptwf8fF2@X1k9HO6bjw3mefPUdSn3EgdoAiFzYcqd4wxS7Cm0WfqB8RLljXMRnbYQRZ@4xAtFIFWzSsTZmd9IdlPH8FyFUhXC2fqgzNtFStFPkHBKWSmqtepwKVaQLoaj5KKg2MOTFSsKLeNPzzI4xclTxzs81wabraO4eCyHkkfgUhbGlMZFKyrem5X6GuAs6tJolJxaz6FybAU7LXc0Fl4GuTHYwyBGqYERk64Atr@Y/hezNFrYH9GO64Jr3lKTu@R5t/kF "Japt – Try It Online") [Answer] **Java, ~~1557~~ 834 bytes** Thanks to @JoKing for tips. A bit late to the competition. Forgot that I had started on this problem. **Golfed** ``` import java.util.*;public class s{ public static void main(String[] args){ Scanner s=new Scanner(System.in);String a=s.next();String[] q=a.split("\\s+");for (int i=0;i<q.length;i++) { q[i]=q[i].replaceAll("[^\\w]", ""); }String f="";for (String z:q) { f+=scramble(z);f+=" "; }System.out.print(f); }private static String scramble(String w){if(w.length()==1||w.length()==2){return w;}char[]l=w.toCharArray();char q=l[w.length()-1];String e=Character.toString(l[0]);char[]n=new char[l.length-2];for(int i=0;i<l.length-2;i++){n[i]=l[i+1];}HashMap<Integer,Character>s=new HashMap<>();int c=1;for(char p:n){s.put(c,p);c++;}HashMap<Integer,Integer>o=new HashMap<>();Random z=new Random();for(int i=0;i<w.length()-2;i++){int m=z.nextInt(n.length);while(o.getOrDefault(m,0) == 1){m=z.nextInt(n.length);}e+=s.get(m+1);o.put(m,1);}return e+=q;}} ``` **Non-golfed** ``` import java.util.HashMap; import java.util.Random; public class SentenceTransposition { public static void main(String[] args) { String input = "According to a researcher at Cambridge University, it doesn't matter in what order the letters in a word are, the only important thing is that the first and last letter be at the right place. The rest can be a total mess and you can still read it without problem. This is because the human mind does not read every letter by itself but the word as a whole."; String[] words = input.split("\\s+"); for (int i = 0; i < words.length; i++) { words[i] = words[i].replaceAll("[^\\w]", ""); } String finalsentence = ""; for (String word : words) { finalsentence += scramble(word); finalsentence += " "; } System.out.println(finalsentence); } private static String scramble(String word) { if (word.length() == 1 || word.length() == 2) { return word; } char[] letters = word.toCharArray(); char lletter = letters[word.length()-1]; String endword = Character.toString(letters[0]); char[] nletters = new char[letters.length-2]; for (int i = 0; i < letters.length-2; i++) { nletters[i] = letters[i+1]; } HashMap<Integer, Character> set = new HashMap<>(); int count = 1; for (char nletter : nletters) { set.put(count, nletter); count++; } HashMap<Integer, Integer> chosen = new HashMap<>(); Random random = new Random(); for (int i = 0; i < word.length()-2; i++) { int cur = random.nextInt(nletters.length); while (chosen.getOrDefault(cur,0) == 1) { cur = random.nextInt(nletters.length); } endword += set.get(cur+1); chosen.put(cur, 1); } return endword += lletter; } } ``` [Answer] # [Sidef](https://github.com/trizen/sidef), ~~89~~ 85 bytes Block (anonymous callable): ``` {.words.map{[_[0],(_.len-1?([_[1..^(_.len-1)]].shuffle...,_[1]):'')].join}.join(' ')} ``` Output, when used like `{ ... }('..')`: ``` I hvae nveer not ocne in my life slleepd nhedatarnel crtreolcy I have never not once in my lfie sepelld naetadenrhl ccrtloery ``` Somewhat ungolfed ``` .words.map{ [ .first, (_.len-1 ? ( [ _[1..^(_.len-1)] ].shuffle..., .last ) : '') ].join }.join(' ') ``` [Answer] # [Perl 5](https://www.perl.org/) `-p`, 74 bytes ``` s|\pL\K\pL{2,}(?=\pL)|$,=$q=$&;$q=join'',shuffle$,=~/./g while$,eq$q;$q|ge ``` [Try it online!](https://tio.run/##PVHBTsMwDP0VHyoGUtcNpF2GKoQ4Mm7stovbuq1RmnSJy1Qx@HSK001IkeP4vTz7JT15s5mmcD70u8Orhq@H9Pv2Kdfs7pykeXLMk5tHjR@O7WKRhnaoa0OK/KyyVQOnluOJjslRWeeGpum5LJ2v2DYgDhA8BUJftuQBBV6wKzxXDcHe8if5wDKmwAKVo2AXAh2KKJWtSitflfQkLYGhCISIIJy0DugpnSFnzQjc9c4LWtFSbM5BE5SZULMPAmgrMKjJRQoKgivuuWkFeoMlZfAeC6S0Eu3MUR@CBjoKYdYY3TBjQdgYpWIVDZxYWjeoineFoS7q6Ai6CipxCDQ3aodOL3asKtEwWCcXAdK3GP8HUzcSyNRQDJcBL35DdN46Q9mv64WdDdPybZOt79e67zjIdrvXmfLrJ03L/g8 "Perl 5 – Try It Online") [Answer] # [Raku](https://github.com/nxadm/rakudo-pkg), 49 bytes Moved from the duplicate thread. ``` {S:g/(\w)(\w*)(\w)/{$0~$1.comb.pick(*).join~$2}/} ``` [Try it online!](https://tio.run/##HY2xDoIwFEV3v@KFEAOYgDo4QFzdnFxdHuUB1dI2bQkhBH69Fod7z3JuriYjbn6Yj@3dL6@yK5L3lIZke6XFEp@3@JIzNdS55uybZGn@UVxu8XUtVl8dLM7QJtFjlNAicyU8lXWgSWlBwFCCIWzAMoNDLaiBSZnGAloQSnY7XU/QchNGJxAYIMg5MsGRDehRMjei40oCGgIu/77hXR9OBDLKo7TyPw "Perl 6 – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 19 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` .γa}εDaićsD¨.rsθJ]J ``` [Try it online.](https://tio.run/##PZA9TgQxDIWv4o5mNXdAbLU1lBROxjuxlJ9V7GE0BTVXoUdI1Ih6rjQ4GYSUwvF7@eyXIuiY9n3YPvB1@zwj/7zJ@ft9qLJ9XZ4v@37vfakj5wm0AEIlIaw@UAVUeMDkKo8TwVPmF6rCup6AFcZCku8UEqqalTMswfxGspsGgkhNkKYgLNYHrHTqUslxBU63UhWzWqsNZ7ECtRuuXEUB8wgRrThQ4Aj@9MpTULhF9DTAY2uQ2Tzm7rEcihESiXTGWuauiXKMZsWxBVhYQ5mNUouLlBrHVrDjyOMs1AeFOdnDxEZpgSEXPQBkf7H@L2ZpVChewc3HgkdeaclDiTT8Ag) **Explanation:** ``` .γ # Consecutive group by: a # Is alphabetic (so all upper- and lowercase letters) }ε # After the group-by, map each string to: D # Duplicate the current string ai # If it's alphabetic: ć # Extract head; pop and push the remainder-string and first character # separated to the stack # i.e. "According" → STACK: "ccording","A" s # Swap so remainder-string is at the top again # STACK: "A","ccording" D # Duplicate it # STACK: "A","ccording","ccording" ¨ # Remove the last character from the copy # STACK: "A","ccording","ccordin" .r # Shuffle the remaining characters # STACK: "A","ccording","occdrni" s # Swap so the remainder-string is at the top again # STACK: "A","occdrni","ccording" θ # Only leave its last character # STACK: "A","occdrni","g" J # Join the three back together to a string again # STACK: "Aoccdrnig" ] # Close both the if-statement and map J # And join all strings in the list back together # (after which the result is output implicitly) ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 13 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` r"%B%w+%B"Èö¬ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=ciIlQiV3KyVCIsj2rA&input=IkFjY29yZGluZyB0byBhIHJlc2VhcmNoZXIgYXQgQ2FtYnJpZGdlIFVuaXZlcnNpdHksIGl0IGRvZXNuJ3QgbWF0dGVyIGluIHdoYXQgb3JkZXIgdGhlIGxldHRlcnMgaW4gYSB3b3JkIGFyZSwgdGhlIG9ubHkgaW1wb3J0YW50IHRoaW5nIGlzIHRoYXQgdGhlIGZpcnN0IGFuZCBsYXN0IGxldHRlciBiZSBhdCB0aGUgcmlnaHQgcGxhY2UuIFRoZSByZXN0IGNhbiBiZSBhIHRvdGFsIG1lc3MgYW5kIHlvdSBjYW4gc3RpbGwgcmVhZCBpdCB3aXRob3V0IHByb2JsZW0uIFRoaXMgaXMgYmVjYXVzZSB0aGUgaHVtYW4gbWluZCBkb2VzIG5vdCByZWFkIGV2ZXJ5IGxldHRlciBieSBpdHNlbGYgYnV0IHRoZSB3b3JkIGFzIGEgd2hvbGUuIg) [Answer] # [Go](https://go.dev), ~~248~~ 226 bytes ``` import(."math/rand";."regexp") func f(s string)string{return MustCompile(`(\w)(\w+)(\w)`).ReplaceAllStringFunc(s,func(S string)(e string){k:=S[1:len(S)-1] for _,i:=range Perm(len(k)){e+=k[i:i+1]} return S[:1]+e+S[len(S)-1:]})} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=jZLPjtMwEMYFxzzFKBJaW-0G9YaCirRaiRtoReDUVqybTBpT_yn2hG6p9kn2UiHxUMuRJ2GcbPeMlMTOzPjn7_P44dfGnx4vdqreqg2CVdpl2u58oCJvLeXPP6Qt5r97ai_fPP4dg6LIraLudVCuyd8WecAN3u1ymbW9q6EVESIF7TZyHI4BqQ8OPvSRrr3daYPiViz3kt9J-shbWXzCnVE1XhlTDYveM0rEaSKK6swTeJ4dt-W8WsxKg05U8nK2ylof4OtUl3NWxYZuMFiRslspjziZbxe61JPZ6j57UlMtytlqgpNqcWaUq3t5Pzr98_LF4CUdi5BwzCrERnz0eyGLL07fCSmzqpzn1CF873W9hXXwewetv4Nvvd1hA_4HBkh5o34eoPGbPLth6dSK_FVcuvm7pUvj0uVTqKZ8alVizvOruvahYY9AHhQEjKhC3TFMEVwruw66YX-sgjeImg5T0MR8jO6CWDARl2oH-47rmXRWgSkRU0bBnuOgAk6HlHfmAGNnlSMOpc115ImioaDVIRJws9kLT0YUrBGe8kFvOoKhfwV8TgHkslq5oYZ9kDJgMcaBcfD9kIukjeFS1SQDe02d75kS_NqgTRyWwM8aa9VHHDbqessLrWZKMgzO0whAPovDszB2QxFNC-t-FDj6jcl55w0W_9OKp5twOo3jPw) Embeds my [answer for "How to randomize letters in a word"](https://codegolf.stackexchange.com/a/257250/77309) within this answer. * -22 from `rand.Perm`, string slices, and named return. ]
[Question] [ In most programming languages, the string `Hello, World!` can be represented as `"Hello, World!"`. But if you want to represent `"Hello, World!"` you need to escape the double quotes with backslashes for `"\"Hello, World!\""`, and to represent *that* you also need to escape the backslashes resulting in `"\"\\\"Hello, World!\\\"\""`. Your challenge is to, given a printable ASCII string that's been escaped multiple times (such as `"\"\\\"Hello, World!\\\"\""`, find how many characters it is when fully unescaped. Specifically, you should remove a single pair of enclosing `"` and replace `\\` with `\` and `\"` with `"`, until there are no more enclosing `"` left. You can assume that the string will be syntactically valid - At all stages, as long as the string starts and ends with `"`, all other backslashes and double quotes will be properly escaped, and only `"` and `\` will be escaped. The input string will not be `"` at any level of escaping. If the string starts and ends with `"`, the last `"` cannot be escaped, so e.g. `"abc\"` won't occur. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest wins! ## Testcases ``` e -> 1 "hello" -> 5 "\"\\" -> 2 a""b"c -> 6 "c\d+e -> 6 "\"\\\"Hello, World!\\\"\"" -> 13 "c\\\"d\"" -> 5 "\"\"" -> 0 "r\"\"" -> 3 "\"hello\"+" -> 8 "\"\\\"\\\\\\\"\\\\\\\\\\\\\\\"Hello\\\\\\\\\\\\\\\"\\\\\\\"\\\"\"" -> 5 "\\\\\"" -> 3 [""] -> 4 ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 41 bytes ``` f=x=>/^".*"$/.test(x)?f(eval(x)):x.length ``` [Try it online!](https://tio.run/##XY3NTsMwEITvfoqwQordpk5LBapASW@IOwcuViXjbNIgExc7rcLTh9puqoq97My3P/MlT9Ip2x76RWcqHMe6GIoy3wGfwX3Oe3Q9Hdi2pniS@qzY88A1dk2/H18s/hxbizStXcq4RVm9thrffztFl1l67OtNwActFdJ8x2d0WySLMmH5d5MlriiV6ZzRyLVpaE0dY2xEv7AisEetDXjzSECAEEE/EAnwCcrrJwJKVHO8aL8j4M2fZcmHsbq680BAOFyt/fbZVxcQv0a9JGCvZu0HIV3APJDN9FzEmvpUMfQ/vOlwkxlYDPoD "JavaScript (Node.js) – Try It Online") Trivial [Answer] # [Jelly](https://github.com/DennisMitchell/jellylanguage), 11 bytes ``` ŒV.ị=”"ȦƲ¿L ``` [Try It Online!](https://jht.hyper-neutrino.xyz/tio#WyIiLCLFklYu4buLPeKAnVwiyKbGssK/TCIsIuG7tMWT4bmj4oCcIC0+IOKAnSTigqzDhz1WfcmXL+KCrCIsIiIsWyJlIC0+IDFcblwiaGVsbG9cIiAtPiA1XG5cIlxcXCJcXFxcXCIgLT4gMlxuYVwiXCJiXCJjIC0+IDZcblwiY1xcZCtlIC0+IDZcblwiXFxcIlxcXFxcXFwiSGVsbG8sIFdvcmxkIVxcXFxcXFwiXFxcIlwiIC0+IDEzXG5cImNcXFxcXFxcImRcXFwiXCIgLT4gNVxuXCJcXFwiXFxcIlwiIC0+IDBcblwiclxcXCJcXFwiXCIgLT4gM1xuXCJcXFwiaGVsbG9cXFwiK1wiIC0+IDhcblwiXFxcIlxcXFxcXFwiXFxcXFxcXFxcXFxcXFxcIlxcXFxcXFxcXFxcXFxcXFxcXFxcXFxcXFxcXFxcXFwiSGVsbG9cXFxcXFxcXFxcXFxcXFxcXFxcXFxcXFxcXFxcXFxcIlxcXFxcXFxcXFxcXFxcXCJcXFxcXFxcIlxcXCJcIiAtPiA1XG5cIlxcXFxcXFxcXFxcIlwiIC0+IDNcbltcIlwiXSAtPiA0Il1d) -2 bytes thanks to Jonathan Allan ## Explanation ``` ŒV.ị=”"ȦƲ¿L Main Link ------Ʋ Link Grouping (see below) ¿ While .ị the first and last (index at 0.5) Ȧ are all =”" equal to " ŒV Evaluate (Python) L Length ``` The footer runs all tests and prints `1` for any correct answers. `Ỵœṣ“ -> ”$€Ç=V}ɗ/€` means "split on newlines, split each string on substrings equal to `" -> "`, then for each pair, check that the result of the main link on the left side equals the right side evaluated (to convert to a number)". For the link grouping, `Ʋ` combines four links into a monad, so you'd think we'd need to use `$` to capture the fifth, but since `”"Ȧ` would be an [LCC](https://jht.hyper-neutrino.xyz/beginners#leading-constant-chains) (a chain that begins with a nilad and only has monads and dyad-nilad/nilad-dyad pairs after it, so a chain with a constant result), it doesn't count that as a link and therefore keeps going one extra time. This is an important tip when understanding the link combining quicks as **all** of them do this and it is easy to miscount or misunderstand the grouping because it may be taking more links than you expect. `ŒV.ị⁼⁾""Ʋ¿L` would also work where instead of `=”"Ȧ` to check that all are equal to `"`, we just check that it's equal to `['"', '"']`. This also makes the grouping a bit simpler because we don't have any potential LCCs so it just takes four links. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 47 bytes ``` +`(?=.*"$)(^"(?!$)|\\(.)|(?!^)"$)(?<=^".*) $2 . ``` [Try it online!](https://tio.run/##XYxBCsMgFET3nqIZLGgsLrpucNneoJuPJI1CC9KAdJm72xgVSmcz8x@fF/3n9Z7SUVzHpEZhBt2DS2EhTMflSiS0XLdtZcbmMljoXjJ@Zjolz/D0ISxgIBCBTcADM8NMTvkCCbf8cjrclxhclwEB@WVbbp@VxNpUpASFpqCS1i1F/Q9/ugr3E18 "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` (?=.*"$) ``` Ensure the string ends with a `"` before making any replacements. ``` (^"(?!$)|\\(.)|(?!^)"$) ``` Replace a leading `"`, an escaped character or a trailing `"`, but not a lone `"`. ``` (?<=^".*) ``` Ensure that the string starts with a `"` before making any replacements. ``` $2 ``` Unescape the character. ``` +` ``` Repeat until the string can't be unquoted further. ``` . ``` Get the length of the final string. If `"` is excluded as being an unsupported input, then ten bytes can be saved by removing `(?!$)` and `(?!^)`. [Answer] # Excel ms365, 138 bytes Assuming input in `A1`: ``` =LET(x,LAMBDA(f,s,IF(s<"",s,f(f,IFNA(SUBSTITUTE(SUBSTITUTE(MID(s,XMATCH("""*""",s,2)+1,LEN(s)-2),"\\","\"),"\""",""""),LEN(s))))),x(x,A1)) ``` It's a recursive LAMBDA that will keep calling itself untill no more starting+leading double quotes. --- # Google Spreadsheets, 107 bytes Again, assuming input in `A1`, applying the same recursive logic with a few slight changes making use of the regex-functions: ``` =LET(x,LAMBDA(f,s,IF(REGEXMATCH(s,""".*"""),f(f,REGEXREPLACE(s,"^""|""$|\\(\\|"")","$1")),LEN(s))),x(x,A1)) ``` [Answer] # [Perl 5](https://www.perl.org/) `-pl`, 45 bytes ``` s/\\(\\|")/$1/g while s/^"(.*)"$/$1/;$_=y///c ``` [Try it online!](https://tio.run/##XY1Pi8JADMXv8ynGRw/@2TatbmVB1rMXzx6MitsOKgzb0i4sgp/dsZm2IuaSX17y8kpT2dTVpMNlNA6IFg0zD5lvGFGQ0En/ny/W6Jr2GEbjEQJRF8Hh@0pEmXOmcepE4WysLSBDqsBg9jxVR@AHmfBcIeN8YjqWG8ZKbB96U1Q2H4jA8MZkJtfNnHdC@7XlWKF6DjNZ@HTGxCtf/XNuq@99taHv4kvHS6bXuqAtsBP6vBfl36X4rV24TqM4iV1Y2gc "Perl 5 – Try It Online") # [Perl 5](https://www.perl.org/) `-pl`, 54 bytes Handles the `"\"foo\\\""` testcase I proposed in the comments. If that's not a valid test case, then the shorter version above will suffice. ``` s/\\(\\|")/$1/g while s/^"(.*[^\\])"$/$1/;say;$_=y///c ``` [Try it online!](https://tio.run/##XU1Na8JAEL3vr9g@cvArmaQ2Ugj23EvPPTgqNtmqsHRDIojQ395tZpMU6Vzmfcy8V5vG5r4lHb8ks4io6DDzhPkbU4oyOurr6WyNbmmHSTLb7Ji3U0RiFe3hVkT79Y2ISu9NF6EzhZOx1kFIrsBgDvhRHYAPlIJXCiVXczNguWG8yttCv7vGVg8iMMJjtpTrjleD0Kf2OFVo/shSjNDOmAfleQznfsY9Tl/6X7zbuOsM2lC0AbaCnqTg07lg/bj6cnZfrY/f8iTNUh/X9hc "Perl 5 – Try It Online") [Answer] # [Python](https://docs.python.org/3.12/), ~~51~~ 52 bytes ``` f=lambda s:f(eval(s))if'"'==s[-1:]==s[:1]else len(s) ``` Not complicated, but it works well. **Explanation:** Define a function f that takes an argument s: ``` f=lambda s: ``` If the string begins and ends with `"`, return the value of the function with backslashes evaluated: ``` f(eval(s))if'"'==s[-1:]==s[:1] ``` Otherwise, output the length of the string: ``` len(s) ``` [Try it online!](https://tio.run/##K6gsycjPM7YoKPr/P802JzE3KSVRodgqTSO1LDFHo1hTMzNNXUnd1rY4WtfQKhZEWxnGpuYUpyrkpOYB5f8XFGXmlWikaWTmFZSWaGhqav5XilGKiQHjGCQaBpQ8UnNy8tEFkWigdiUA "Python – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~34~~ 33 bytes ``` W¬∨⌕θ"⌕⮌Φθλ"≔⪫⁻⪪✂θ¹±¹¦¹\\¦\¦\θILθ ``` [Try it online!](https://tio.run/##XU5BCsIwELz7ipDTBuqh555EEBGtYq@9hLq0C0tik1ifH5NWoTiX2d2ZYbYbtOus5hjfAzEKqG2Aq4MDmQeMhZCtlKoQ83rHCZ3HpHFAl1VW6mtJEDvvqTdwsmTgQubloXkyBWiYOsz2shA19joglClXztkEuQwrGlW1uTkyAfbaBzij6cMAYyqpYkx9OdQu@PEP8ojM9v@44vxu3E78AQ "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` W¬∨⌕θ"⌕⮌Φθλ" ``` Repeat while the string starts with `"` and ends with a different `"`... ``` ≔⪫⁻⪪✂θ¹±¹¦¹\\¦\¦\θ ``` ... remove those `"`s, split the string on `\\`, remove any remaining `\`s, then join the string on `\`, thus unquoting the string. ``` ILθ ``` Output the length of the final string. (Yes I could use eval to save 14 bytes but that's boring.) If `"` is excluded as being an unsupported input, then two bytes can be saved by replacing `Φθλ` with `θ`. [Answer] # [Python 3](https://docs.python.org/3/), ~~91~~90 bytes ``` f=lambda s:f(s[1:-1].replace('\\"','"').replace(r'\\','\\'))if'"'==s[-1:]==s[0]else len(s) ``` because `eval` is evil :P, with inspiration from Jakav [Try it online!](https://tio.run/##XYvBCkIhEEV/5TEbZ6AXSTvBff/wdGGlJEw@UVv09WZB8Wjg3gPnMvnZbms69h40u/v56qaqAtZFqlnaffGZ3cWjMAbEToCgnyrDDTWKKIYxaV2XWSr75sF6rn5in7BSzyWmhgFjyo@GRNTBgDGfmA2/ByfPvP7LDcc7vAA "Python 3 – Try It Online") [Answer] # [QBASIC](https://en.wikipedia.org/wiki/QBasic), 302 bytes ``` Q$ = CHR$(34): LINE INPUT T$: DO WHILE LEFT$(T$, 1) + RIGHT$(T$, 1) = Q$ + Q$: U$ = MID$(T$, 2, LEN(T$) - 2): T$ = "": C$ = "": FOR J = 1 TO LEN(U$): C$ = C$ + MID$(U$, J, 1): B = -(C$ <> "\"): T$ = T$ + RIGHT$(C$, B * ((INSTR("\\" + Q$, C$) > 0) + 2)): C$ = LEFT$(C$, 1 - B): NEXT: LOOP: PRINT LEN(T$) ``` A bit of nostalgia... **Explanation:** ``` 'Set quote mark because QBASIC doesn't have string escaping 'then get string Q$ = CHR$(34) LINE INPUT T$ 'Process the string while it starts and ends with quotes DO WHILE LEFT$(T$, 1) + RIGHT$(T$, 1) = Q$ + Q$ 'Strip enclosing quotes, assign to a temporary variable, 'prepare to rebuild the original string, 'and prepare to track current character(s) U$ = MID$(T$, 2, LEN(T$) - 2) T$ = "" C$ = "" 'Process string character by character. FOR J = 1 TO LEN(U$) 'Add current character to current status C$ = C$ + MID$(U$, J, 1) 'QBASIC boolean ops return -1 for true, 0 for false, 'so set B to 0 if current character is an escape char, to 1 otherwise. B = -(C$ <> "\") 'Add current character to string if not an escape char, 'de-escaping if appropriate T$ = T$ + RIGHT$(C$, B * ((INSTR("\\" + Q$, C$) > 0) + 2)) 'Clear current character unless it's an escape char C$ = LEFT$(C$, 1 - B) NEXT LOOP PRINT LEN(T$) ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` Δ¬'"Qi.E]g ``` [Try it online](https://tio.run/##yy9OTMpM/f//3JRDa9SVAjP1XGPT//9XUlKKVlKKBVIA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9TVmmvpPCobZKCkn3l/3NTDq1RVwrM1HOtrU3/r/M/lUspIzUnJ1@JSylGKSZGiStRSSlJKZlLKTkmRTsVIhij5AFSoqMQnl@Uk6IIEohRUgIpAbJSwEyoSBGUjoEYGqOkrQQzIgYCYDQMQIxGF0SioQaCuUpc0UpKsVxKAA). (Note: in the single TIO, the input is wrapped within `"""`-quotes to always have a string input.) **Explanation:** ``` Δ # Loop until the result no longer changes: ¬ # Push its first character (without popping the string) '"Qi '# If it's a double quote: .E # Evaluate the string as Elixir code ] # Close both the if-statement and changes-loop g # Pop and push the length of the reduced string # (which is output implicitly as result) ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 20 bytes ``` L?&b&qhbNqebNyvblbyw ``` [Try it online!](https://tio.run/##K6gsyfj/38deLUmtMCPJrzA1ya@yLCknqbL8/3@lGKWYGDCOQaJhQMkjNScnH10QiQZqVwIA "Pyth – Try It Online") Same approach as Jakav's Python solution. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal/tree/version-2) `l`, 70 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 8.75 bytes ``` Sλh\"=ßE;Ẋ ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2&c=1#WyJsfj0iLCIiLCJTzrtoXFxcIj3Dn0U74bqKIiwiIiwiZS0+IDFcblwiaGVsbG9cIiAtPiA1XG5cIlxcXCJcXFxcXCIgLT4gMlxuYVwiXCJiXCJjLT4gNlxuXCJjXFxkK2UtPiA2XG5cIlxcXCJcXFxcXFxcIkhlbGxvLCBXb3JsZCFcXFxcXFxcIlxcXCJcIiAtPiAxM1xuXCJjXFxcXFxcXCJkXFxcIlwiIC0+IDVcblwiXFxcIlxcXCJcIiAtPiAwXG5cInJcXFwiXFxcIlwiIC0+IDNcblwiXFxcImhlbGxvXFxcIitcIiAtPiA4XG5cIlxcXCJcXFxcXFxcIlxcXFxcXFxcXFxcXFxcXCJcXFxcXFxcXFxcXFxcXFxcXFxcXFxcXFxcXFxcXFxcIkhlbGxvXFxcXFxcXFxcXFxcXFxcXFxcXFxcXFxcXFxcXFxcXCJcXFxcXFxcXFxcXFxcXFwiXFxcXFxcXCJcXFwiXCIgLT4gNVxuXCJcXFxcXFxcXFxcXCJcIiAtPiAzXG5bXCJcIl0gLT4gNCJd) Bitstring: ``` 0110001110110011010000001101101101100000011010011000101001000111010000 ``` Port of 05ab1e except i had to add a "stringify" at the start for the final case ]
[Question] [ If we have a list of integers we can "squish" one of them by: * decrementing it * replacing adjacent values with its new value For example in this list: ``` [1,2,8,3,6] ``` If we squish the `8` we get: ``` [1,7,7,7,6] ``` The question is: **Given a starting array, what is the largest we can make its sum by repeatedly squishing values?** For example if we are given: ``` [1,5,1,1,9,1] ``` Here the starting sum is `18` but if we squish the `5` or the `9` it will go up. Squishing anything else will make it go down so we will squish them. ``` [4,4,4,8,8,8] ``` Now the sum is `36`, but it can still go up, if we squish the left-most `8` it will increase to `37`. ``` [4,4,7,7,7,8] ``` We can squish the left-most `7` but it won't change the sum. If we go back and try some other things we will find that the best sum possible is in fact `37`. So the answer here is `37`. ## Task Given a list of two or more positive integers as input give the maximum sum that can be attained by repeated squishing. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the goal is to minimize the size of your source code as measured in bytes. ## Test cases ``` [2,2,2] -> 6 [4,5] -> 9 [4,6] -> 10 [4,4,6] -> 14 [4,6,5] -> 15 [1,1,9] -> 21 [1,1,1,9] -> 25 [1,8,1,9,1] -> 38 [1,10] -> 18 [1,5,1,1,9,1] -> 37 [9,1,1,1] -> 25 [3,6,7,8,1] -> 31 ``` [Answer] # [MATL](https://github.com/lmendo/MATL "MATL – Try It Online"), ~~37~~ 35 bytes ``` ftnqZ^!"G@!"tt@)q@3:H-+GfX&(]]v!sX> ``` Brute force approach. It tries all possible sequences of up to *n*−1 squishes, where *n* is the length of the input. This is sufficient, because at that point all numbers will be equal and further squishing will decrease the sum. [Try it online!](https://tio.run/##y00syfn/P60krzAqTlHJ3UFRqaTEQbPQwdjKQ1fbPS1CTSM2tkyxOMLu//9oIwUgjAUA) Or [verify all test cases except the longest one](https://tio.run/##y00syfmf8D@tJK8wKk5Ryd1BUamkxEGz0MHYykNX2z0tQk0jNrZMsTjC7r9LVEXI/2gjBSCM5Yo2UTAFk2ZgEkabgUUNFQwVLKE0jGUBYikYQkQNgJQlWBIkYAzUZg5SEAsA). ### How it works ``` ftnqZ^ % Cartesian power of [1 2 ... n] with exponent n-1, where n is input length !" % For each Cartesian tuple G % Push input @!" % For each number k in the current tuple t % Duplicate the partially squished input array (*) t@)q % Push its k-th entry minus 1 (**) @3:H-+ % Push [k-1 k k+1] GfX& % Intersection with [1 2 ... n]. This handles the edges (***) ( % Write (**) at entries (***) of (*) ] % End ] % End v % Vertically concatenate all partially (or totally) squished arrays !s % Sum of each array X> % Maximum. Implicit display ``` [Answer] # JavaScript (ES6), ~~77~~ 76 bytes *Saved 1 byte thanks to @tsh* ``` f=(a,s=0)=>Math.max(...a.map((p,i)=>(s+=p,--p)&&f(a.map(q=>i*i--<2?p:q))),s) ``` [Try it online!](https://tio.run/##bc5LDoIwEAbgvadgRabaFkqAiLF4Ak9gWDQIWoO0WGK8fSUKGh4zm0n@LzNzE09h8ofULanVubC25CCw4T7i6VG0V3oXL6CUim7QABrLLgCz4RoTopHrlvCNGp7KtSRkHxz0rkEIYYNsrmqjqoJW6gIlnALcdeZ8CiHH85x4NSEhjnowkGRO4glh/tz8VW/ChT2/Y72JpoZhhpORCdiSGVRvlvb42fjnrX0D "JavaScript (Node.js) – Try It Online") (some test cases removed) [Faster version with a cache](https://tio.run/##bc/RDoIgFAbg@57CKwd1QDEta2FP0BM4L1hl2UopXOuidzcsrGnAxs7Gt//fOYm7UNtbIWtSVrt90@QcCVDcxzzJU5Hx9nk@N6I@0ot4IEqp0INESEKhDVITLoEQiV03R5@vK0@KcUHIKljL5RVjDAo326pU1XlPz9UB5SgNQN/MeR@MHc9zZqMBCSEyoCOLfzIbEOb/m58yJrTkfMuMiYaGAYNFzwTMZjpljCUnbg2wrDPT2JLjZ/29LCb6tOkkkzMfmqnea972/bpY8wI) (87 bytes, solving all test cases almost instantly) ### Commented ``` f = ( // f is a recursive function taking: a, // a[] = input array s = 0 // s = sum of the array, computed in the main loop ) => // Math.max( // return the maximum of ... ...a.map((p, i) => // for each value p at position i in a[]: ( // s += p, // update the sum --p // decrement p ) && // if p is not equal to 0: f( // do a recursive call: a.map(q => // pass a new array where the items a[i-1], i * i-- < 2 ? // a[i] and a[i+1] are set to p and p // everything else is left unchanged : // we do this by testing i² < 2 and q // decrementing i after each iteration ) // ) // end of recursive call ), // end of map() s // add the sum of the current array ) // end of Math.max() ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 20 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ā<ZиæεvDyè<2Ý<y+ǝ]Oà ``` Brute-force approach, so pretty slow the larger the input-list is. [Try it online](https://tio.run/##yy9OTMpM/f//SKNN1IUdh5ed21rmUnl4hU2lTaXd0R3H58b6H17w/3@0oQ4IWsYCAA) or [verify the shortest few test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeWhlf@PNNpEXdhxeNm5rYfWFZe5VB5eYWN0eK5NpfbxubW1/ocX/Nf5Hx1tomMaqwMkzYCkoY6hAZAy0gFCsCBEGEiCFQGldSyhNIRlCWYZgsUsQGJgtjFQvTmIDxY3hagG8mIB). **Explanation:** ``` ā # Push a list in the range [1,input-length] < # Decrease each by 1 to make the range [0,length) Z # Push the maximum/length-1 (without popping the list) и # Repeat the list that many times æ # Get the powerset of this list ε # Map over each inner list: v # Foreach over each index `y`: D # Duplicate the current list # (which will be the implicit input in the first iteration) yè # Pop the copy, and get its `y`'th value < # Decrease it by 1 2Ý # Push list [0,1,2] < # Decrease each to [-1,0,1] y+ # Add `y` to each: [y-1,y,y+1] ǝ # Insert the value-1 at these indices # (ignoring those that are out of bounds) ] # Close both the inner loop and outer map O # Sum each inner list à # Pop and push the maximum # (which is output implicitly as result) ``` `2Ý<y+` could alternatively be `y<y>Ÿ` or `y<DÌŸ` for the same byte-count. [Answer] # [R](https://www.r-project.org/), ~~116~~ 103 bytes Or **[R](https://www.r-project.org/)>=4.1, 89 bytes** by replacing two `function` appearances with `\`s. *Edit: -13 bytes thanks to [@Giuseppe](https://codegolf.stackexchange.com/users/67312/giuseppe).* ``` function(v)max(combn(rep(0:l,l),l<-sum(v|1),function(x){for(i in x)if(i)v[i-1:-1]=v[i]-1;sum(v[1:l])})) ``` [Try it online!](https://tio.run/?fbclid=IwAR1y_64hplcTdrMjeL36xvNoB3snqIeac8Rc_xFuIgIjIelzFruTN2lVu5s##TY7NCoNADITvPsWClwR2wfivrX0R8dBKFxb8KbaK0PbZrdpdlVwy30yGdJPMJtk35Uu1DQxYX0co2/rWQHd/gJNWvEJencWzr2H4EPItO@Jbth0opho2opKgcMiVoFRQkc1bIei0XuWUVgV@EScJJbh8HkSbiQsLrYX4PNA60TrUmhwNDsg3me2KghURJ55o5JJlMwMPONhwvGBO2vBiU@GY0niLBv@OPRxpK1kN2ssX6M2fRUu9SdP0Aw "R – Try It Online") Explanation outline: 1. Generate all possible sequences of indices to squish (`0` indicating "skip") - of length equal to length of input; possibly with duplicates, which don't matter. 2. Use `combn`'s `FUN` to apply on each one the squishings in a `for` loop. 3. During squishing, luckily we need to account only for the overflowing indices on the right (writing to index `0` is a no-op), hence the indexing in `sum(v[1:l])`. 4. Take `max` of all of the possible sums. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 22 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) Yowch, it took quite some effort circumventing Jelly's, usually useful, modular indexing nature! ``` J;-ṗLị@’¥’r‘RƇƲ}¦ƒ€⁸§Ṁ ``` A monadic Link accepting a list of positive integers that yields the maximal sum reachable (only revisiting previously squashed indices if better for the golf). **[Try it online!](https://tio.run/##AUEAvv9qZWxsef//Sjst4bmXTOG7i0DigJnCpeKAmXLigJhSxofGsn3CpsaS4oKs4oG4wqfhuYD///9bMSw4LDEsOSwxXQ "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8/9/LWvfhzuk@D3d3OzxqmHloKZAoetQwI@hY@7FNtYeWHZv0qGnNo8Ydh5Y/3Nnw/3A7kPf/f3S0kQ4QxipAgbKCrp2CGZdOtImOKVwQKmwJFjZDFzY0AIsjy0DETSDqkQyCiJsCxQ11DHUsUcWNDKHiCBmIOES9BUhcxzAWLm5sAVFvEIvmHoi4KcQksA6IenOguCVY1BDDfGOgO81BdiCZb8gVCwA "Jelly – Try It Online"). ### How? ``` J;-ṗLị@’¥’r‘RƇƲ}¦ƒ€⁸§Ṁ - Link: list of integers, A J - range of length of A -> [1,2,...,length(A)] - - literal -1 ; - concatenate -> [1,2,...,length(A),-1] -> our alphabet L - length of A ṗ - Cartesian power (all words of length length(A) with our alphabet) € - for each word ⁸ - ...using A as the right argument: ƒ - reduce [A]+word by: ¦ - sparse application } - ...to indices: using the right argument (next integer of word): Ʋ - last four links as a monad - f(I=integer): ’ - decrement I ‘ - increment I r - inclusive range -> [I-1, I, I+1] Ƈ - filer keep those (of [I-1, I, I+1]) for which: R - range (truthy for positive integers) ¥ - ...apply: last two links as a dyad - f(current state, I): @ - with swapped arguments: ị - index into -> our squish value ’ - decrement § - sums Ṁ - maximum ``` [Answer] # Python3, 505 bytes: ``` S=sum M=max def f(n): if any(i>1 for i in n): yield n;d={} for i in range(len(n)): if n[i]>1: k,j=n[:],0 k[i]-=1 if i:k[i-1]=k[i];j+=1 if i+1<len(k):k[i+1]=k[i];j+=1 d[j]=d.get(j,[])+[(n[i],k)] if 2 in d: T=[],[] for _,y in sorted(d[2],key=lambda x:x[0],reverse=True): T[S(y)>S(n)].append(y) for i in T[1]:yield from f(i) if T[0]:yield from f(M(T[0],key=S)) if M([t for t,_ in d[2]])==M(n):return if 1 in d: yield from f(M(d[1],key=lambda x:x[0])[1]) ``` [Try it online!](https://tio.run/##ZVNNb@IwED3Xv8LiUlsYhKG0kK75B@wFbq6FjOx0DYkTOaEiWu1vZ8dOyX5UOWTevDfPM5O47toflV@s6nC77URzKdFWlPqKjM1xTjzNEHY51r4jbsNxXgXssPM4EbhztjDYvxrx8xfAgQ3av1tSWA8GSRg9vHRqwxPCZ3YSXmaKzXoI1ETwFIPSZZCYcCVi/vU0/osZ82/R9kyjZPxFYuRJCTN9ty05ManoWJJ4LDtThZLBPLZnUhN7IRVoYhgbP7Auck0VWmuIkXOosp0odHk0Gl@zq5wphoP9sKGxYh8utp8M7@WOdHSzg1nVVNe19Qbw3TbtYy@5yvpl5aEqYbGOfm5lD7b/UlsSc@nwHb3LtkS2ya9lhzQC9KeoENv4iYJtL8H3A/I/A/7naqCJryNRyNJbI0ajEZJzBo/Ckw1@RvKJLVO4juFzCvksxgN6SsynjC@R5IyzdUJz3qMBJ3YVMeMps1glxawvTmDZF9wFL0iuU4YPFgs47iXa9AqOYtuurOGjYd20aNh47orWBvK98pbhZtrUhWvJ45t/jP/jg2b4iAUudU2gagqcDbo42A9dMOzu6ngE6NFDHZxvSZnFi0FyomlaI9wVCt6XksT3kd5@Aw) A bit of optimization to produce all the test case results quickly. --- # Python3, 392 bytes: @AnttiP has very cleverly taken my original solution above and has condensed it down, and although slower due to its leveraging of speculative execution, it is much shorter: ``` S=sum M=max def f(n): if M(n)<2:return yield n;d,T=[[]]*3,[[],[]] for i in range(len(n)): k=n[:];j=i>0;k[i]-=1;k[i-j]=k[i] if k[i+1:]:k[i+1]=k[i];j+=1 if n[i]>1:d[j]+=[(n[i],k)] for i in[T[S(y)>S(n)].append(y)for _,y in sorted(d[2])[::-1]]and T[1]:yield from f(i) if T[0]:yield from f(M(T[0],key=S)) if d[2]and M([t for t,_ in d[2]])==M(n):return if d[1]:yield from f(M(d[1])[1]) ``` [Try it online!](https://tio.run/##ZVLBjtowED2vv8LisnYxCMOyC6bmD@gFbq6FvIrTGhITOaFqvp7OOLtR1QpF8968NzO2mabvft7iatOkx@Oo23tNDrp2v0nhS1qyyBWhoaQHQF@XKvnuniKhffBVQeOuECdtjLVfVgKCAERoeUs00BBpcvGHZ5WPUItt6FVHo@zuosN@sbuaYGdaYpxdrEYKFhgFaCqVVTkOwu4y1XJQI9C9VIW52Kk2DKm48r/GmpM5sp7vjzDVzl3T@FgAR/ksejxXe0udL1hhlpYbpWbSWhcLejLSquFiZbrVcPnA891PZvGPcGCYE1ff6yMfTNgNuxyY6fJZOnHGYZi3XGt8wPH5sl/@1xRzHL9HqyeTCTFLAT9LZ3v6SsyLWGe4RfiaoVwgHtlLVj5sck2MFFJsM1vKgY08qxvkQubMapMdi6E4k/VQ8Gl4I2abM3JssYJxb9hmcEiCxw51Ay9MXduRcRfKUHU@sW@36AVt521ThY49f4/PuBlPTtB3qmntGgZVc9B8ctXZ/3KVoOHTjSPAT56aFGLHaoV7ykrmeP4nYHU59L7XDOM7f/wB) [Answer] # [Python 3](https://docs.python.org/3/), 105 bytes ``` f=lambda l,i=0:0<sum(l[i:])and max(f((l[:i][:-1]+[l[i]-1]*(3-(i<1))+l[i+2:])[:len(l)]),f(l,i+1))or sum(l) ``` [Try it online!](https://tio.run/##PY1BbsMgEEX3nAJlNVNjyzhOlKA4F0EsqGyrIwG2DK2a07uYVhWb9/4fZtZX@ljCed/nwVn/PlruBA2tah/x04PTpAzaMHJvv2GGHCgyWtXSVDqXJsMbnGugh0SsclJ1@YNWbgrg0KCYIe@rcrlsvGzEnfy6bInHV2RszrHjFA5rYhopNNtkR0dhioCKcRLL4O0K05d1wjVxdZTgVD9PiIyvG4UElI8QigV33RteP3nPdCfyK3JluheXgvcDrwVle/C/9aX5G5MXpqWQ4l6sk8Xa3@r2Aw "Python 3 – Try It Online") The squishing is surprisingly annoying, due to one-off errors near the edges. Bruteforce solution, which stops only when non-positive numbers have been encountered. The function calls itself two times. Once with the index `i` squished, and once with `i` incremented (but the list remains unsquished). The maximum of those calls are returned. There are two edge cases, one is when `i` is outside the list, and another one when we feel enough squishing has been done. We can check for both cases with `0<sum(l[i:])`. When this becomes less than one it can be for two reasons. One is that `i` is equal to the length of the list, which means that the sum of the empty list is taken (which is zero). Another possibility is that the elements of `l` are so squished that some of them are zero or even negative. Clearly at this point we have done more than enough squishing and can stop. # [Python 3](https://docs.python.org/3/), 171 bytes ``` L={};g=lambda l,i:0<sum(l[i:])and max(f((l[:i][:-1]+[l[i]-1]*(3-(i<1))+l[i+2:])[:len(l)]),f(l,i+1))or sum(l) def f(l,i=0):L[(i,*l)]=L.get((i,*l))or g(l,i);return L[(i,*l)] ``` [Try it online!](https://tio.run/##PY3LjoMgFIb3PAXpCioaqbUXWvsEfQPigonYngTRKJ1MM5lndwBnDJv/8p2f4e2evS3m@V59/1welVHdR6OwYSDy6/TqiJEgaqpsgzv1RVriAwG1FCmvE@nL2ostKVICV05p4pNk5w@kMNoSQ2vKWuLXEl/2I46LFDW6xTGucirukgDberS6Zw/tyOIC/QgIvYzavUaLV26GbuhHh6f3hFDrOYPBBpdNrgGbjVo1BqyeCBUIA@urTg1EfyrDTDYNBhzZpLcNpQgPI1jnZ1sClPV0ljvmX43TGz4guWdllOcgD1HyPOjV7WPzh/ESSc44O0e344tbfWxPwTMek@IUiXw5jqZcDv6BI5LnmPB1ovDfHcPMQvBf "Python 3 – Try It Online") Just a memoized version of the first submission. Is able to calculate all testcases in reasonable time. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 47 bytes ``` F⊖ΦEX⊕LθLθ↨ι⊕Lθ⌊ι«≔⮌θηFιUMη⎇‹¹↔⁻μκλ⊖§ηκ⊞υΣη»I⌈υ ``` [Try it online!](https://tio.run/##bU/LSgNBEDxnv6KPvdAegqCCpzUSCBhY1FvIYbLbZobMw8wjRsRvH2f2Yg65VXdVV1cNUvjBCZ3zh/OAzzx4Nmwjj7hUOrLHtfjE3n0VtLL/5AvbfZR4bFuCS/wkAqMiuK6tirWyyiSDqo7w08y6ENTe4iuf2JfjY9HI9rGZTYFUCyXAwhkj7IiS4J29Ff67mIaAc4JuF5xOkbH4poCG4DC90QSXZbq4siOfq0Plq3@fgsRE8FbCyLr5bXqvbMSFCLHUPk8xUxXnvNnc0h3d0wPNt9t8c9J/ "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` F⊖ΦEX⊕LθLθ↨ι⊕Lθ⌊ι« ``` Generate all possible squishing sequences of length up to the length of the input. ``` ≔⮌θη ``` Make a copy of the input. ``` FιUMη⎇‹¹↔⁻μκλ⊖§ηκ ``` Perform all of the squishing steps. ``` ⊞υΣη ``` Save the sum of the result. ``` »I⌈υ ``` Output the maximum sum. [Answer] # [Perl 5](https://www.perl.org/) List::Util, 112 bytes ``` sub f{my$s=sum@_;max$s,map f(@$_),grep{$s-2<sum@$_}map{@a=(0,@_,0);@a[$_..$_+2]=($_[$_]-1)x3;[@a[1..@_]]}0..$#_} ``` [Try it online!](https://tio.run/##XY5fT4MwFMXf@RQ32gUaO0LZ2B@wyrvGvegTkgZdIcSxIYU4Q/jsWMARNE2Tnt859/bkojg4bXwqDC0ACGyiTgjsDlYAIenZkjg92U7IqifUmqARLqe531nqjJASSrY9tOkfOOJpdtNhQntjsZnmrWHxlDnDlkt8PVrb3qD/1y9Uv3X3xZAf6uBaA8i@DZQSJDDzEfd6gBIWGz5KcSfzIj2W8dVMAoA45@K9FHsXZvZe6eRUXp7pMa@UUFOvxysCSDCGknv99KG7@tPuGXYPekfVTTyt0Sop4DGVpeu@lOkBPr@MLDqDrDLstbJ6g7hWNSRTwOeespAkWZRDV4tjkhQir5Gc27ddAPFGebUfMcMiPicW9vwoQNw0Eb@xQ2YgrlQ4p/i88AJlUdP0eRg2lkpc86ZtfwA "Perl 5 – Try It Online") [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 103 bytes Thanks to Kevin Cruijssen for -2 bytes! it's not a lambda! Pretty self-explanatory, pads with zero to avoid edge cases while copying x to y, squashes a digit in y by assignment, recurses if the digit is not less than 0. The sum is calculated on the input vector to each call and updated if any recursive call returns a larger result. This sum (`s`) is returned after trying all the digits. ``` def f(x): s=sum(y:=[0,*x,i:=0]) for v in x:y[i:i+3]=[v-1]*3;s=max(s,v<0 or f(y[1:-1]));i+=1 return s ``` [Try it online!](https://tio.run/##PY7BjoMgFEX3fMVLV9CikWqblg79EeLCRM28BJEANfr1DjKTyduck3tz89wWv2dbP5zf934YYaQrkwSCCp@JblLpip9XjlJVLSMwzh4WQAur3DRKvNSt0ksh2nP9CmrqVhr48lVBqo1000KmiLEXXpQg4If48RbCjpObfYSwBUKORXMsJitD7NGWfuh6g3YI9PgE@ZyGHR2WznBTBmcw0lPxPrH0j/NoI0U@UmR8ZrtuWije0BB95emy3Ilu@C3j88B7RlEd/G9NTv5q4ka04II/s11Ftuo3evwA "Python 3.8 (pre-release) – Try It Online") [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), ~~40~~ ~~39~~ 33 bytes *-1 thanks to [Unrelated String](https://codegolf.stackexchange.com/users/85334/unrelated-string); -6 thanks to [Fatalize](https://codegolf.stackexchange.com/users/41723/fatalize)* ``` ~b~k{{~c₃↺{Ṫ∋₁-₁ℕgj₃}ʰ↻c↰|}bk+}ᶠ⌉ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/vy6pLru6ui75UVPzo7Zd1Q93rnrU0f2oqVEXiB@1TE3PAkrUntrwqG138qO2DTW1SdnatQ@3LXjU0/n/f7ShjqGOWez/CAA "Brachylog – Try It Online") Brute force solution. *V e r y   s l o w*. For testing purposes, I suggest changing `ℕ` to `ℕ₁`, which helps significantly (but still not enough to solve most of the test cases in less than 60 seconds). ### Explanation This solution comes in layers, like an onion. Also like an onion, working on it made me want to cry. ``` ~b "Unbehead" the input list, prepending an uninitialized variable ~k Do the same at the other end ("unknife") {...}ᶠ Find all ways to satisfy this predicate (see next section) ⌉ Take the maximum {...} Apply this predicate (see next section) bk Remove the first and last elements of the resulting list + Sum | EITHER return the list unchanged, OR: ~c₃ Partition the list into three sublists ↺ Rotate so that the middle sublist is at the beginning {...}ʰ Apply this predicate (see next section) to that sublist ↻ Rotate so that the middle sublist is back in the middle c Concatenate back together ↰ Call the current predicate recursively on the result Ṫ The sublist must be a three-element list ∋₁ Get the element at index 1 -₁ Subtract 1 ℕ Assert that this is a nonnegative integer g Wrap it in a singleton list j₃ Join three copies of that list into a single 3-element list ``` [Answer] # Python, 157 bytes ``` f=lambda l:max([f((l[:max(i-1,0)]+[v-1]*(3-(0==i%(len(l)-1)))+l[i+2:])*((i>0 and v>l[i-1]+1)or(i<len(l)-1 and v>l[i+1]+1)))for i,v in enumerate(l)]+[sum(l)]) ``` [Try it online!](https://tio.run/##fZLfbpswFMbveQoLaZJPcSacNG2DRqVdrA@w9Y5alRfMZskYBE7UPX3qPwRMVQ0uMJ9/5zvHH/T/zN9O7y6XplS8/V1zpIqWv@GqwVhVfik3lOTAsuq8oewG7zY4L0v5BSuhsYINBYBMVTLbFgxuMJaPOeK6RudHK9qKjEI3YPntii@bmd8EaLoBSXJGUiOhT60YuBEWtR3HU@sWcDFiNK9HPooRlahKkL1wtSX2ZuQOyCTckj0jh@j1jhGaR@9BuY0JV0L3s0IJJQdGtnSlBC2mHpxGKCO7h5jMrVks7EOxB@9n/eBVurLc2VHuna0lXXOWJD0fR6n/2BM/DyeRNFwqUb@6KHwKLAnBOWGd3ZIWFN5evPXiaERty9xeRZmXB3EU8uzlxhdVOQO/0w9SG5w@O2tnhFKUodHY7wgr4MX8mKyLGbk2@0j@nLot5LU//Kdp6lIQdYpkEx2jXGYXypEhnDQYWVR35lM85OG7zek@cWsx63HMX3nfC13bUyeJNZ1Kinja70r5TFH4O6dpIXFjrcBfXStiMvQh0zOISzTxFACXdw "Python 3 – Try It Online") Finds all the moves that would result in at least 1 element increasing value, then recursively tests those moves and returns the maximum value achieved or the original value. ]
[Question] [ *(inspired by a [question](https://codereview.stackexchange.com/q/171190) over on Code Review)* Suppose two people are playing [Hangman](https://en.wikipedia.org/wiki/Hangman_(game)), but you've only overheard the game and want to draw the current status. Given two words as input, where the words each match `[A-Z]+` or `[a-z]+` (your choice), output the current state of the hangman game as ASCII art, following the below rules. * The first word is the word to be guessed, and the second word is the already-guessed letters. These can be taken as input in any order. * The word to be guessed is guaranteed non-empty, but the already-guessed letters may be empty (i.e., as if it's the start of the game). * The game will always be a valid hangman game (i.e., guessed letters won't be duplicated, letters won't be guessed past the end of the game, you'll only receive letters as input, etc.). * Below the hangman drawing must be the word to be guessed, with `_` in place of letters yet unknown, separated by spaces. For example, if the word to be guessed was `BOAT`, then below the hangman drawing must be `_ _ _ _`. If the word was `BOAT` with `A` guessed, then below the drawing must be `_ _ A _`. * Below the word to be guessed must be letters already guessed that are *not* in the word. These can be in any order, and can be separated by any non-alphabetical separator, if so desired. Here are the states of the hangman game, from initial start to game end. Each wrongly guessed letter advances the state by one. So the first wrongly guessed letter makes the head `O` appear, the next makes the body `|` appear, etc. ``` +---+ | | | | | | ========= +---+ | | O | | | | ========= +---+ | | O | | | | | ========= +---+ | | O | /| | | | ========= +---+ | | O | /|\ | | | ========= +---+ | | O | /|\ | / | | ========= +---+ | | O | /|\ | / \ | | ========= ``` ## Input * Two strings [in any convenient format](http://meta.codegolf.stackexchange.com/q/2447/42963), with the first guaranteed non-empty. * You can take the input in either order (e.g., word to guess and then guessed letters, or vice versa). Please state in your submission the input order. ## Output The resulting ASCII art representation of the hangman game in progress, as described above, again in any convenient format. ## Rules * Leading or trailing newlines or whitespace are all optional, so long as the characters themselves line up correctly. * Either a full program or a function are acceptable. If a function, you can return the output rather than printing it. * If possible, please include a link to an online testing environment so other people can try out your code! * [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) are forbidden. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so all usual golfing rules apply, and the shortest code (in bytes) wins. ## Examples ### #1 `BOAT` and `ATG` ``` +---+ | | O | | | | ========= _ _ A T G ``` ### #2 `ZEPPELIN` and ``` +---+ | | | | | | ========= _ _ _ _ _ _ _ _ ``` ### #3 `ZEPPELIN` and `EATOLINSHR` ``` +---+ | | O | /|\ | / \ | | ========= _ E _ _ E L I N A T O S H R ``` ### #4 `RHYTHM` and `ABCDE` ``` +---+ | | O | /|\ | / | | ========= _ _ _ _ _ _ EDCBA ``` ### #5 `BOAT` and `ATOB` ``` +---+ | | | | | | ========= B O A T ``` ### #6 `AIRPLANE` and `AJKEI` ``` +---+ | | O | | | | | ========= A I _ _ _ A _ E KJ ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~215~~ ~~192~~ ~~184~~ 183 bytes -8 bytes thanks to Raphaël Côté -1 byte thanks to Jonathan Frech ``` a,b=input() j=' '.join s=b-set(a) print""" +---+ | | %s | %s%s%s | %s %s | | ========= """%tuple('O/|\/\\'[:len(s)].ljust(6)),j(['_',i][i in b]for i in a),'\n',j(s) ``` [Try it online!](https://tio.run/##NY5BC4JAEIXv@ysGQWYXdxU6dAg8dBAKIqU65UooGK3IKu56CPzvtlq9YXjfwOMx/du@Or2Z55JXsdL9aCkjTYyAYdMpTUxcCVNbWjLSD0pbz/MAAiFEQAAmcOvcN1/wzTI/hB@tmkj8F3EVvh37tqaYRpOMpMR819aaGlaEbTMaS7eM8Ybm@ECuilyB0lAVz26AFUvGUWp0CcPmGe9JliWn4xn58igm@1vqruvhguwD "Python 2 – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~83~~ ~~69~~ 68 bytes ``` Fη¿№θι⁰«ι→⊞υι»←⸿Fθ«⎇№ηιι_→»←⸿×=⁸↖=←↑⁵←+←³↓+|FLυ≡ι⁰↓O¹←|²/|³\⁴⸿ /⁵ \« ``` [Try it online!](https://tio.run/##bZDfS8MwEICfl7/iyFOCHU7nQDr2IFpQqK7M@SIFKSVdArV1Sbshdn97TGxN5o@HEO677@64y3km8zortS5qCYRTEAWQ67qtGrINQFAKiRQmmFBgpWLwgUY9EHSORvf1jpFwJTa8sWHSKk5aWzZHB9R7YcyKJgCcSmzo15Qt9W3WTFaZfB9GcltrnvFfMP074f@mQyfxyhTBCxzAJXU0fHob3IVV@3aWHBsBzHw46Cf4N5p6cFPvK@t0bqeYVZvGLG8OpvaiyTmYC9k188xcbRLCz8qlLexzZy43TO587vw7h089nDrYpanHFw6nEo70mePQ6wetn6MkieK7BxRdrZfmf7xd6fFOj1X5CQ "Charcoal – Try It Online") Link is to verbose version of code. Edit: Saved 14 bytes by switching to `switch`. Saved 1 byte by printing the single `|` as a literal. Note: At the time the question was set, `switch` didn't work at all in Verbose mode and needed a trailing `«` in Succinct mode (the current version on TIO has neither bug, so it shows the Succinct translation as 67 bytes), while `Map`'s bugs prevented me from using `Print(Join(Map(q, Ternary(Count(h, i), i, "_")), " "));`. Fortunately I managed to come up with a kludge for the same length (and indeed I also tried switching the other loop to a Map but it too came out at the same length). Explanation: ``` Fη For each letter in the guess, ¿№θι⁰« if the word to be guessed does not contain the letter, ι→ print the failed guess, leave a gap, ⊞υι» and push the letter to the array. ←⸿ Move to the start of the previous line. Fθ« For each letter in the word to be guessed, ⎇№ηιι if the letter has been guessed then print it _ otherwise print a _. →» Either way, leave a gap. ←⸿ Move to the start of the previous line. ×=⁸ Print 8 =s ↖=← Print a 9th =, moving into position to ↑⁵ print 5 |s upwards, ←+←³ a + and 3 -s left, ↓+| and a + and a | down. FLυ Loop once for each incorrect guess. ≡ι Choose what to print based on the loop index. ⁰↓O For the first incorrect guess, print an O. ¹←| For the second incorrect guess, print a |. ²/ For the third incorrect guess, print a /. ³|\ For the fourth incorrect guess, print a \. ⁴⸿ / For the fifth incorrect guess, print a / on the next line. ⁵ \ For the sixth incorrect guess, print another \. ``` [Answer] # [Python 2](https://docs.python.org/2/), 220 bytes ``` x,y=input() x=[['_',k][k in y]for k in x] y-=set(x) s=''' +---+ | | 0 | 213 | 4 5 | | ''' for i in range(6):s=s.replace(`i`,[' ','O|/\\/\\'[i]][len(y)>i]) print s+'='*9+'\n'+' '.join(x)+'\n'+''.join(y) ``` [Try it online!](https://tio.run/##LU5dS8MwFH3Pr7hvJzHp1PkBEyL4UFAQN9Qn07ANiRo30tJUaGD/vabd4F7OB5zDaVL3U4f5MPQqaR@av44L1mtjsIbaWbMjHyjZr7qlifaWpUJH1/FesKgBEMmiKCQjOlD@jBdHnF9eTXhNN0efJj9H2Fjnx7p2G74dvxV3UcdZ65r99tPxjd8oA4LC8nBeVflgvLVm7wJP4t5bwZrWh46ihMbZQqIKkDkw@619yMNOxkknMQz4KFer8vnpBYrG8Sgf3pdZvj2@QvwD "Python 2 – Try It Online") -35 bytes thanks to Raphaël Côté -20 bytes using sets -1 byte thanks to micsthepick [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~72~~ 73 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) +1 fixing an ace game bug that showed the full hanged person (changed `LN` to `Lạ6` near the end) ``` e€a⁸o”_$,ḟ@©K€Y,@“¥[$⁼Ż⁸½c¤ṫȷṃl®ḌvNṂeL©?Ḥ’ṃ“ -¶|O/\=+”¤Y⁶“$"÷ȷñŒ‘ḣ®Lạ6¤¤¦ ``` A dyadic link taking the word on the left and the (unique and within-game) letters on the right and returning a list of characters, or a full program taking the input as command line arguments and printing the result. **[Try it online!](https://tio.run/##y0rNyan8/z/1UdOaxEeNO/IfNcyNV9F5uGO@w6GV3kDBSB2HRw1zDi2NVnnUuOfobqCSQ3uTDy15uHP1ie0PdzbnHFr3cEdPmd/DnU2pPodW2j/cseRRw0ygBFCTgu6hbTX@@jG22kBDDy2JfNS4DSiqonR4@4nthzcenfSoYcbDHYsPrfN5uGuh2aElQLjs////Tv6OIf8dQ9wB "Jelly – Try It Online")** ### How? Firstly: ``` “¥[$⁼Ż⁸½c¤ṫȷṃl®ḌvNṂeL©?Ḥ’ - base 250 number = 305169639782226039115281574830092231403740634016078676 ``` Is the numeric value of the full hanged person in base 9, where each of the 9 digits represent one of the characters: `<space>`, `<newline>`, `-`, `|`, `O`, `/`, `\`, `=`, or `+`. the rest of the program: ``` e€a⁸o”_$,ḟ@©K€Y,@“...’ṃ“...”¤Y⁶“...‘ḣ®Lạ6¤¤¦ - Main link word, letters e€ - exists in letters for €ach char in word a⁸ - and with word (word with 0 at un-guessed) o”_$ - or with '_' (word with _ at un-guessed) ḟ@ - filter remove (incorrect guesses) © - copy the result to the register and yield , - pair K€ - join €ach with spaces Y - join with (a) newlines ¤ - nilad followed by link(s) as a nilad: “...’ - the number described above “...” - list of chars " -¶|O/\=+" (¶ = a newline) ṃ - base decompress using the chars as digits ,@ - pair (using swapped @rguments) Y - join with (a) newlines ¦ - sparse application: ⁶ - of: a space character - to indexes: ¤ - nilad followed by links as a nilad: “...‘ - literal [36,34,28,26,27,19] ¤ - another nilad chain: ® - recall from register L - length (# of bad guesses) ạ6 - absolute difference with 6 ḣ - head (get the indexes to "erase" - by applying the space char) - as a full program: implicit print ``` [Answer] # [Japt v2](https://github.com/ETHproductions/japt), ~~94~~ ~~91~~ ~~83~~ 81 bytes *-3 bytes from some ideas from [@ETHproductions' approach to this](http://ethproductions.github.io/japt/?v=1.4.5&code=WyIgICstLS0rCiAgfCA5IDEgOTIzNDkyIDQ5ICAgICB8ImQ5IiAgfAogIiIlZCJAIiBPL3xcXCJnWCooV7A8VmtVIGzDJz2zs1Wso1b4WCA/WDonX8O4VmtVXbc=&input=IlpFUFBFTElOIgoiRUFUT0xJTlNSIg==).* *-8 bytes by using multiline string rotation.* *-2 bytes by using v2.* ``` ["+||||| - - - 35 +|01 24 "r\d_¨VkU l ?S:"O|/\\/\\"gZÃz '=³³¡VøX ?X:'_øVkU]· ``` Takes both word inputs as arrays of characters, with the guessing word first and guessed letters second. Incorrect letters are shown separated by `,`s. When there are no incorrect letters, the last line is blank (meaning output contains an extra trailing newline). [Try it online!](http://ethproductions.github.io/japt/?v=2.0&code=WyIrfHx8fHwKLQotCi0gIDM1Cit8MDEKICAgMjQKInJcZF+oVmtVIGwgP1M6Ik98L1xcL1xcImdaw3ogJz2zs6FW+FggP1g6J1/DuFZrVV23&input=WyJCIiwiTyIsIkEiLCJUIl0KWyJBIiwiVCIsIkciXQ==) ## Explanation Implicit: `U` and `V` are input char arrays. ``` ["..." ``` Start an array and push the hanging man format string, rotated left 90°. ``` r\d_ ``` Replace (`r`) every digit (`\d`) with the following function: ``` ¨VkU l ?S:"O|/\\/\\"gZà ``` If the digit is `>=` (`¨`) the amount of wrong guesses (`VkU l`), a space (`S`), otherwise, get the appropriate body part for that digit (`"..."gZ`). ``` z '=³³ ``` Rotate the hanging man right 90° and push `=` repeated 3\*3 (`³³`) times to the array. ``` ¡VøX ?X:'_à ``` Push the word-to-guess, with letters mapped (`¡`) to either themself (`X`) if contained in `V` (`VøX`), or `_` if not, and joined with spaces (`¸`), to the array. ``` VkU]· ``` Push the guessed-letters, with the letters in the word-to-guess removed (`k`), to the output array. Close the array and join with newlines (`·`). Rotation visualized: > > > ``` > +||||| +---+ > - | | > - -> 0 | > - 35 213 | > +|01 4 5 | > 24 > > ``` > > [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 83 bytes ``` •LO„Ÿ¼Ì‘Šη…ÔÆ#δʒΣ•6B4ÝJ"+ -|="‡²¹SK©Ùg"O/|\/\"s£v5y.;}7ô»„==«5ð:¹D²SKDg'_ׇSðý®Sðý» ``` [Try it online!](https://tio.run/##MzBNTDJM/f//UcMiH/9HDfOO7ji053DPo4YZRxec2/6oYdnhKYfblM9tOTXp3GKgEjMnk8NzvZS0FXRrbJUeNSw8tOnQzmDvQysPz0xX8tevidGPUSo@tLjMtFLPutb88JZDu4Em2toeWn1op8uhTcHeLunq8YenA/UFH95weO@hdRBqt@nhDVb//0e5BgS4@nj6cbk6hvj7eAZ7RAEA "05AB1E – Try It Online") --- # The Bitmap: # [05AB1E](https://github.com/Adriandmen/05AB1E), 18 bytes ``` •LO„Ÿ¼Ì‘Šη…ÔÆ#δʒΣ• # Push number described below in base-10. ``` [Try it online!](https://tio.run/##ATcAyP8wNWFiMWX//@KAokxP4oCexbjCvMOM4oCYxaDOt@KApsOUw4YjzrTKks6j4oCi//9CT0FUCkFO "05AB1E – Try It Online") This pushes the following bitmap plan: ``` 1102220 1131113 1151113 1555113 1515113 1111113 4444444 ``` --- Where the following additional bytes: # [05AB1E](https://github.com/Adriandmen/05AB1E), 13 bytes ``` 6B # Convert to base-6. 4ÝJ # Push 01234. "+ -|=" # Push that string. ‡ # Replace numbers with those letters. ``` [Try it online!](https://tio.run/##AUcAuP8wNWFiMWX//@KAokxP4oCexbjCvMOM4oCYxaDOt@KApsOUw4YjzrTKks6j4oCiNkI0w51KIisgLXw9IuKAof//Qk9BVApBTg "05AB1E – Try It Online") Replace the pieces of the bitmap with the appropriate characters, leaving the 5's for replacing the pieces of the hangman later: ``` +---+ | | 5 | 555 | 5 5 | | ======= ``` --- # The Hanged Man: Next, we calculate how many times the user guessed wrong by grabbing the letters that are in the second input, but not in the first input: # [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes ``` ²¹SK # Get wrong guesses. ©Ù # Store them, and get unique wrong letters. ``` [Try it online!](https://tio.run/##AVEArv8wNWFiMWX//@KAokxP4oCexbjCvMOM4oCYxaDOt@KApsOUw4YjzrTKks6j4oCiNkI0w51KIisgLXw9IuKAocKywrlTS8Kpw5n//0JPQVQKQU4 "05AB1E – Try It Online") --- Finally, we use a secondary bitmap to substitute in the hanged man, separating by newlines and preparing it for the final print: # [05AB1E](https://github.com/Adriandmen/05AB1E), 26 bytes ``` g # Get the number of "messups". "O/|\/\"s£ # Only that many chars of the hanged "bitmap". v5y.;} # Replace 5's with "bitmap". 7ô» # Split into rows. „==«5ð: # Remove additional 5's. ``` [Try it online!](https://tio.run/##AXMAjP8wNWFiMWX//@KAokxP4oCexbjCvMOM4oCYxaDOt@KApsOUw4YjzrTKks6j4oCiNkI0w51KIisgLXw9IuKAocKywrlTS8Kpw5lnIk8vfFwvXCJzwqN2NXkuO303w7TCu@KAnj09wqs1w7A6//9CT0FUCkFO "05AB1E – Try It Online") This results in the first pieces, the only remaining pieces being outputting the two words at the bottom in a diff format... --- # The Words Below: Print the first word without the missing guesses: # [05AB1E](https://github.com/Adriandmen/05AB1E), 15 bytes ``` ¹D²SK # Word without the missing guesses. Dg'_ׇ # Replace missing guesses with "_". Sðý # Join by spaces. ``` [Try it online!](https://tio.run/##AYgAd/8wNWFiMWX//@KAokxP4oCexbjCvMOM4oCYxaDOt@KApsOUw4YjzrTKks6j4oCiNkI0w51KIisgLXw9IuKAocKywrlTS8Kpw5lnIk8vfFwvXCJzwqN2NXkuO303w7TCu@KAnj09wqs1w7A6wrlEwrJTS0RnJ1/Dl@KAoVPDsMO9//9CT0FUCkFO "05AB1E – Try It Online") --- # [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes ``` ® # Print stored missing guesses. Sðý # Separated by spaces. » # Print everything in stack with newlines. ``` [Try it online!](https://tio.run/##MzBNTDJM/f//UcMiH/9HDfOO7ji053DPo4YZRxec2/6oYdnhKYfblM9tOTXp3GKgEjMnk8NzvZS0FXRrbJUeNSw8tOnQzmDvQysPz0xX8tevidGPUSo@tLjMtFLPutb88JZDu4Em2toeWm16eIPVoZ0uhzYFe7ukq8cfng7UG3x4w@G9h9ZBqN3//zv5O4ZwOfoBAA "05AB1E – Try It Online") Print the calculated missed guesses from earlier we stored in a register. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 86 bytes ``` 3ȷ6Dẋ6Ḍ+“Ȧṇ⁹c’ œ-Lḣ@“Ñæçðøþ‘⁵*$€×“µI,’D¤¤S+¢Dị“+-|/\O ”Us7Y,”=x9¤Y;⁷,œ-ðjɓi@€ị³;”_¤K;⁷ ``` [Try it online!](https://tio.run/##y0rNyan8/9/4xHYzl4e7us0e7ujRftQw58SyhzvbHzXuTH7UMJPr6GRdn4c7FjsAxQ9PPLzs8PLDGw7vOLzvUcOMR41btVQeNa05PB0od2irpw5QucuhJYeWBGsfWuTycHc3UFhbt0Y/xl/hUcPc0GLzSKCKubYVloeWRFo/atyuAzT68Iask5MzHYCmANUf2mwNVBB/aIk3SPr///9Kro4h/j6efsEeSv@VolwDAlyBHCUA "Jelly – Try It Online") Whew... this was fun. I've never used so many `¤` characters. **How it Works** ``` 3ȷ6Dẋ6Ḍ+“Ȧṇ⁹c’ (1) the literal 300000030000003000000300000030003001222100 3ȷ6 - literal 3*10^6 = 3000000 D - digits ẋ6 - repeat six times Ḍ - return to integer: 300000030000003000000300000030000003000000 + - add “Ȧṇ⁹c’ - literal 2998222100 œ-Lḣ@“Ñæçðøþ‘⁵*$€×“µI,’D¤¤S+¢Dị“+-|/\O ”Us7Y,”=x9¤Y,œ-;⁷ð,ɓi@€ị³;”_¤K;⁷ œ-Lḣ@“Ñæçðøþ‘⁵*$€×“µI,’D¤¤S - representation of the body parts œ-L - wrong letters length ḣ@ - get that many elements from the start of ¤¤ - the literal: “Ñæçðøþ‘ - [16, 22, 23, 24, 29, 31] ⁵*$€ - 10 to the power of each of them × - multiplies by “µI,’D - the list [6, 4, 3, 5, 4, 5] S - sum +¢Dị“+-|/\O ”Us7Y,”=x9¤;⁷ - complete the man + - add ¢ - the literal 3000000...1222100 calculated by link 1 D - digits ị“+-|/\O ” - index into the string “+-|/\O ” Us7Y - reverse, split into lines of 7, join by linefeeds , - append ”=x9¤;⁷ - the string “=========” ;⁷ - add a newline ,œ- - append missed letters: , - append œ- - set difference ð,ɓi@€ị³;”_¤K;⁷ - append the blanks ð,ɓ - append i@€ị³;”_¤ - each letter if it is included in guesses, _ otherwise K - join by spaces ;⁷ - add a newline ``` [Answer] # C#, ~~305~~ 296 bytes ``` using System.Linq;w=>g=>{var r=string.Concat(g.Where(c=>!w.Contains(c)));var n=r.Length;return$@" +---+ | | {(n>0?"O":" ")} | {(n>2?"/":" ")+(n>1?"|":" ")+(n>3?"\\":" ")} | {(n>4?"/":" ")} {(n>5?"\\":" ")} | | ========= {string.Join(" ",w.Select(c=>g.Contains(c)?c:'_'))} "+r;} ``` *Svaed 9 bytes thanks to @raznagul.* [Try it online!](https://tio.run/##nZFdT8IwFIbv@yvqiQlrBvP7hrlNwCkacASWGA2JWUqZS6CLa4EYtt@O3YZ8aGKI56Z9357n9JyWito05vFqJiIe4sGnkGxqol1ldCL@YSJEJ4EQuIeWCKsQMpARxfM4GuFuEHGNFHZ5mMfdjNNrIRNVqLovytW28RhbeLWw7NCyl/MgwYlVHhmtmNNAaqExYBNGpUYt@2iRu1LdJDRKHKoD1AEIMXOQW4nRYTyU72bC5CzhxzeAsV6r1XTVT6q6SdW61Lh96oCnQAwkK93cPHfgpDR1pc4cSLfqwoHhcEOsgcsNkBX66mdSESmyvgMt15M9xuqpVF51sTNbuD9avfJWISRDoCdmtjI3L7rZqGwRT5jxnESSqd9h2liDptfwgWjQ8O@BYB3DkAMx/2Ze3V7P7Tw85dy/ILfhe2o7aPcPxvvtF7/dLTpttm7dg7ntfF5zF/pF9VkwKqB1xQxlqy8 "C# (Mono) – Try It Online") Full/Formatted Version: ``` using System; using System.Linq; class P { static void Main() { Func<string, Func<string, string>> f = w=>g=> { var r = string.Concat(g.Select(c => !w.Contains(c) ? c + "" : "")); var n = r.Length; return $@" +---+ | | {(n > 0 ? "O" : " ")} | {(n > 2 ? "/" : " ") + (n > 1 ? "|" : " ") + (n > 3 ? "\\" : " ")} | {(n > 4 ? "/" : " ")} {(n > 5 ? "\\" : " ")} | | ========= {string.Join(" ", w.Select(c => g.Contains(c) ? c : '_'))} " + r; }; Console.WriteLine(f("BOAT")("ATG") + "\n"); Console.WriteLine(f("ZEPPELIN")("") + "\n"); Console.WriteLine(f("ZEPPELIN")("EATOLINSHR") + "\n"); Console.WriteLine(f("RHYTHM")("ABCDE") + "\n"); Console.WriteLine(f("BOAT")("ATOB") + "\n"); Console.ReadLine(); } } ``` This also works for 314 bytes (could probably be shorter still): ``` using System.Linq;w=>g=>{var r=string.Concat(g.Select(c=>!w.Contains(c)?c+"":""));var s=$@" +---+ | | 0 | 213 | 4 5 | | ========= {string.Join(" ",w.Select(c=>g.Contains(c)?c:'_'))} "+r;for(int i=0;i<6;++i)s=s.Replace(i+"",i<r.Length?i<1?"O":i<2?"|":i<3?"/":i<4?"\\":i<5?"/":"\\":" ");return s;} ``` [Answer] # JavaScript (ES6), ~~203~~ ~~196~~ ~~187~~ ~~186~~ ~~185~~ ~~184~~ ~~180~~ ~~177~~ 176 bytes Takes input as 2 arrays of individual characters in currying syntax. ``` a=>g=>` +---+ | | 1 | 324 | 5 6 | | ========= ${a.map(x=>g[s="includes"](x)?x:"_")} `.replace(/\d|,/g,m=>" O|/\\/\\"[!!w[~-m]*~~m],w=g.filter(x=>!a[s](x)))+w ``` --- ## ~~Try~~ Play it ``` o.innerText=(f= a=>g=>` +---+ | | 1 | 324 | 5 6 | | ========= ${a.map(x=>g[s="includes"](x)?x:"_")} `.replace(/\d|,/g,m=>" O|/\\/\\"[!!w[~-m]*~~m],w=g.filter(x=>!a[s](x)))+w)([...i.value="ZEPPELIN"])([...j.value=""]) oninput=_=>o.innerText=f([...i.value.toUpperCase()])([...j.value.toUpperCase()]) ``` ``` label,input{font-family:sans-serif;font-size:14px;height:20px;line-height:20px;vertical-align:middle}input{margin:0 5px 0 0;width:100px;} ``` ``` <label for=i>Word: </label><input id=i type=password><label for=j>Guesses: </label><input id=j><pre id=o> ``` [Answer] # [Vim](https://www.vim.org), 118 bytes ``` jYk:s/[^<C-r>0]/_/g :s/./& /g Yj:s/[<C-r>0]//g oO|/\/\ <esc>ka <esc>jv$r dd{P|i | <esc>la <esc>xpla <esc>lxpo <esc>:0,s/.*/ & |/ o<esc>9i=<esc>{O +---+ ``` [Try it online!](https://tio.run/##NY3BCoJAFEX38xV3ES6y6blNTJBwYUVKO8kKyQhHYURBBOffp8mh1T2cs7ij1iJv/IFuj@DA@9C705M@zIgtOTCUi1/8NyNkqqigAsF7eIVNaVeMqx5VNWeqhgKzsi3BFpi6trTUTp0EbPa9jXlZExxAEZOL3NX7ZecUcDnnrtZRcs3O0SVm0fEUJ0zz8Qs "V (vim) – Try It Online") [Answer] # Batch ~~853~~ ~~748~~ 736 bytes Run from the command line with 2 args: `%1` = word, `%2` = "doublequoted,delimited,list,of,letters" **edit: requires Windows 10 / Virtual terminal support** ``` Echo off&cls Set "$=Set " %$%O=Echo(&%$%F=For /L %%i in (&%$%P=^<nul Set/P &%$%"C=|findstr " %f:L=f%'%O%prompt $E^|cmd')do %$%\=%%i[ %$%n=^ Setlocal EnableDelayedExpansion %F:/L=%"e1=3;3HO" "e2=4;3H|" "e3=4;2H/" "e4=4;4H\" "e5=5;2H/" "e6=5;4H\" "D= +---+!n! | |!n!")Do %$%%%i %F%1 1 5)Do %$%D=!D! ^|!n! %O%!D!=========!n!&If "%~2"=="" Exit /b %$%W=%~1&%F:/L=%%~2)Do (%$%/A i+=1 %$%G!i!=%%i&%$%G=!G!/ic:"%%i" ) %F%30,-1,0)Do if not "!W:~%%i,1!"=="" If "!#!"=="" %$%"#=%%i" %O%%\%10;2H&%F%0 1 !#!)Do (%$%/A X=%%i+2 %P%"=%\%10;!X!H."&%O%"!W:~%%i,1!"%C%!G! >nul &&%P%"=%\%1D!W:~%%i,1!") %P%"=%\%11;2H"&%F%1 1 !i!)Do %O%!W!%C%/ic:"!G%%i!" >nul||(%P%"=!G%%i!"&%$%/A e+=1) %F%1 1 !e!)Do %P%"=%\%!e%%~i!" %O%%\%11;1H ``` How? macros are used for repeated commands * `Set` Variable assignment `%$%` * `For /L %%i in (` loops `%F%` + Substring modification is used to recycle the macro as `for /f` (`%F:L=f%`) or basic `for` loops (`%F:L=%`) * `Echo(` (output type 1) `%O%` * `< Nul Set /P` (output type 2) `%P%` * `Findstr` (String comparison used in testing guesses against letters in word) `%C%` The remarked ungolfed version: ``` @Echo off cls :# define VT escape character 0x027 For /f %%i in ('Echo(prompt $E^|cmd')do Set ESC=%%i[ :# define linefeed. empty lines required. must be expanded with delayed expansion (Set \n=^ %= ABOVE EMPTY LINES REQUIRED =%) :# enable environment to allow use of linefeed; modification of variables during code blocks and parsing of nested variables to emulate arrays Setlocal EnableDelayedExpansion :# define array of bodypart location and character representation 'incorrect.#'; define top 2 lines of Gallows For %%i in ("incorrect.1=3;3HO" "incorrect.2=4;3H|" "incorrect.3=4;2H/" "incorrect.4=4;4H\" "incorrect.5=5;2H/" "incorrect.6=5;4H\" "Gallows= +---+!\n! | |!\n!")Do Set %%i :# define and output the remaining elements of the Gallows For /L %%i in (1 1 5)Do Set "Gallows=!Gallows! |!\n!" Echo(!Gallows!=========!\n! :# Exit script if second argument empty [ no letters guessed ] If "%~2"=="" Exit /b :# assign word variable to facilitate substring assessment of word Set "Word=%~1" For %%i in (%~2)Do ( %= For each delimited letter in argument =% Set /A "Guess.index+=1" %= Increment count =% Set "Guess.letter!Guess.index!=%%i" %= Assign letter to Guess.letter array =% Set "Guess.letters=!Guess.letters!/ic:"%%i" " %= Build list of findstr search values =% ) :# Calculate word string length [ 0 indexed ] For /L %%i in (30,-1,0)Do if not "!Word:~%%i,1!"=="" If "!Word.Length!"=="" Set "Word.Length=%%i" :# move cursor to line 10 column 2 in advance of correct guess result output Echo(%ESC%10;2H For /L %%i in (0 1 !Word.Length!)Do ( %= For each character in word =% Set /A "Xpos=%%i+2" %= Assign X position offset for '.' output =% <nul Set/P "=%ESC%10;!Xpos!H." %= Output '.' denoting unguessed letter spaces =% Echo("!Word:~%%i,1!"| findstr !Guess.letters! >nul &&( %= Test letter in word against guessed letters list =% <nul Set/P "=%ESC%1D!Word:~%%i,1!" %= On match shift cursor left; overwrite unguessed marker '.' with matched letter =% ) ) :# move cursor to line 11 column 2 in advance of incorrect guess result output <nul Set/P "=%ESC%11;2H" For /L %%i in (1 1 !Guess.index!)Do ( %= For each guessed letter =% Echo(!Word!|findstr /ic:"!Guess.letter%%i!" >nul||( %= Test index of guess array for a match in word =% <nul Set/P "=!Guess.letter%%i!" %= On NO match output incorrectly guessed letter - =% Set /A "incorrect.guess.count+=1" %= and increment incorrect.guess.count =% ) ) :# For each index in incorrect.guess.count output incorrect.# array value - [ Y;Xcharacter ] For /L %%i in (1 1 !incorrect.guess.count!)Do <nul Set/P "=%ESC%!incorrect.%%~i!" Echo(%ESC%11;1H `` ``` [Answer] # [Scala](http://www.scala-lang.org/), ~~392~~ 389 bytes **This might *still* be heavily golfable.** This is inside a function taking `s` and `t` as parameters, with `s` the word to guess and `t` the string containing already tried letters. ``` var f=s.map(x=>if(t contains x)x else"_") mkString " " var o=""" +---+ | | 0 | 213 | 4 5 | | ========= """ var c=0 var g=t.filter(x=>if(s contains x){false}else{c match{case 0=>o=o.replace("0","o") case 1=>o=o.replace("1","|") case y if y==2|y==5=>o=o.replace(y+"","\\") case y if y==3|y==4=>o=o.replace(y+"","/") case _=>()} c+=1 true}) o.replaceAll("\\d"," ")+f+"\n"+g ``` EDIT: -1 byte: `t.contains(x) -> t contains x` -1 byte: `s.contains(x) -> s contains x` -1 byte: `.mkString(" ") -> mkString " "` [Try it online!](https://tio.run/##dZFfa8IwFMWfl09xuU8NVeffl0GEuskczCnqy4YgWUy1W5uWNhtK7Wd3abVzyiykJ9xzfpdDmwju8334/iGFhiH3FMiNlmqZgBNFKblZShfWXK0CrqzkbqpjT60q@nihR2Xp/pvH4LKkFvDI2rCu51oaRKi02ZjAhm5A@onEBVIIPg8QICDJsZAhIoBdrVZtArADc4zWD9pstAptQ@cwh2LOyocYuFgjWL3QFdM11/O1jI9Fkr9FUpebIlneJhUQcC3WqeCJhDrrhiysxTLyuZAW1rGCIVJSmI0Ls2HMXWluwXNhy1hzZ16d8@TWRhOdzy@zrTzb/i97W0YXrGvRjAibNYiOv2RGyW/W8X3LbF2aPCC1XRvnCu3VPiMkMt9W@8rC3siZQRWc2WPulf@wGBvMjJHSU3qu3vrjcf/56cUwMoj09owqTUNex/rObGRu08HkGntKXGyZDF5ng2Fet3f/0D/DD1ZeObdyjmT7Hw "Scala – Try It Online") [Answer] # PHP 7, 246 bytes ``` for($t=" +---+ | | 1 | 324 | 5 6 | | ========= ";$c=($w=$argv[1])[$i++];)$t.=strstr($g=$argv[2],$c)?"$c ":"_ ";for($t.=" ";$c=$g[$k++];)strstr($w,$c)?:$t.=$c.!++$n." ";for(;$p++<6;)$t=strtr($t,$p," O|/\/\\"[$p>$n?0:$p]);echo$t; ``` takes input from command line arguments. Run with `-nr` or [try it online](http://sandbox.onlinephpfunctions.com/code/84f65135a41f6a20e2804051963e57b00af8f36a). ``` for($t=" +---+\n | |\n 1 |\n 324 |\n 5 6 |\n |\n=========\n"; $c=($w=$argv[1])[$i++]; # 1. loop $c through word ) $t.=strstr($g=$argv[2],$c) # if guessed, ?"$c ":"_ "; # then append letter, else append underscore for($t.="\n";$c=$g[$k++];) # 2. loop through guesses strstr($w,$c)?: # if not in word $t.=$c.!++$n." "; # add to output, increment $n for(;$p++<6;) # 3. loop through possible false guesses $t=strtr($t,$p," O|/\/\\"[ # replace digit: $p>$n # if above no. of wrong guesses ?0:$p # then with space, else with hangman character ]); echo$t; # 4. print ``` ]
[Question] [ Given a string of digits or an integer as input, you will have to indexize it. This is how you modify the input. We will use `30043376111` as an example: First, find the sum of the indices of each occurrence of the respective digits: ``` 0: 1 + 2 = 3 1: 8 + 9 + 10 = 27 3: 0 + 4 + 5 = 9 4: 3 6: 7 7: 6 ``` Then, construct a new integer or string where the digits above go in the order of the sums of their indices. In the case that multiple digits yield the same sum, the smaller digit comes before the larger one: ``` 047631 ``` Finally, remove any leading zeroes, and return or print the result: ``` 47631 ``` You must write a program or function which returns or prints the input indexized. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins! More test cases can be added if requested. [Answer] # [J](https://www.jsoftware.com), 14 bytes ``` ~.".@/:1#.I.@= ``` Accepts a string, returns a number. [Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8FOJT31NAVbKwV1BR0FAwUrINbVU3AO8nFbWlqSpmuxrk5PSc9B38pQWc9Tz8EWIrhNkys1OSNfIU1B3djAwMTY2NzM0NBQHSK5YAGEBgA) ``` ~.".@/:1#.I.@= I.@= NB. = makes a boolean table of occurrences, each row is a unique item @ NB. monadic atop, f@g y => f g y I. NB. returns indices of 1s in each boolean list from = 1#. NB. sums each resulting list ~. NB. returns unique items from input ".@/: NB. /: sorts x by y @ NB. dyadic atop, x f@g y => f x g y ". NB. eval resulting indexized string ``` [Answer] ## Haskell, 69 bytes ``` import Data.List f x=0+read(nub$sortOn(\d->(sum$elemIndices d x,d))x) ``` Takes a string, returns a number. Usage example: `f "30043376111"` -> `47631`. [Try it online!](https://tio.run/nexus/haskell#@5@ZW5BfVKLgkliSqOeTWVzClaZQYWugXZSamKKRV5qkUgyU9c/TiEnRtdMoLs1VSc1JzfXMS8lMTi1WSFGo0EnR1KzQ/J@bmJmnYKtQUJSZV6KgopCmoGRsYGBibGxuZmhoqPQfAA "Haskell – TIO Nexus") Pretty straight forward: sort the digits of the input string first on the sum of their indices and the by the digit itself (-> pairs of (sum ...,d)), remove duplicates and convert to a number to remove leading `0`. The `0+` is needed to get the types right. [Answer] # [Stacked](https://github.com/ConorOBrien-Foxx/stacked), 59 bytes ``` :@q uniq[:q\eq q size:>*sum,]map[-1#]sortby[0#]map''#`'^0'- ``` [Try it online!](https://tio.run/nexus/stacked#U1E3NjAwMTY2NzM0NFT/b@VQqFCal1kYbVUYk1qoUKhQnFmVamWnVVyaqxObm1gQrWuoHFucX1SSVBltoAwSUVdXTlCPM1DX/Z@SWVzwHwA "Stacked – TIO Nexus") This takes a character string (like `$'1231231'`) as input from the top of the stack, and leaves a string on the stack. ## Explanation ``` :@q uniq[:q\eq q size:>*sum,]map stack: (str) : stack: (str str) @q stack: (str) ; store as `q` uniq stack: (str') ; de-duplicate [ ]map map the inner over each element : stack: (chr chr) q\eq stack: (chr q') ; `q'` is where equality occurs q size:> stack: (chr, q', k) ; `k` is range from 0, size(q') *sum stack: (chr, k') ; `k'` is sum of indices , stack: ((chr, k')) ``` Now we are left with pairs of (chr, sum of indices). ``` [-1#]sortby[0#]map''#`'^0'- [ ]sortby sort by the inner function - vectorized subtraction of two pairs 1# use the second element as the comparison [0#]map get the first element of each row ''#` join by the empty string '^0'- remove all leading zeroes ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~29~~ 28 bytes *-1 thanks to Riley* ``` TFN¹SQDg<ÝsÏON‚}){vyD0å_i1è, ``` [Try it online!](https://tio.run/nexus/05ab1e#ATMAzP//OcOddnnCuVNRRGc8w51zw49PTuKAmn0pe3Z5RDDDpV9pMcOoLP//MzAwNDMzNzYxMTE "05AB1E – TIO Nexus") ``` TFN } # Loop from 0 to 9. ¹SQ # Push 1 if index is same as `y`. Dg<ÝsÏ # Push index of the number instead of 1. ON‚ # Sum, combine with current `y`. ){ # Collect, sort 'em. vyD0å_i1è, # Only print the ones with a count above 0. ``` [Answer] # JavaScript (ES6), 98 bytes ``` n=>+[...new Set(n)].sort().sort((a,b)=>(s=d=>[...n].reduce((S,D,i)=>S+i*(d==D),0))(a)-s(b)).join`` ``` Takes a string `n`, then converts it to a Set and then to an Array of distinct digits. Sorts these digits in numerical order, then sorts again according to sums of indices. Concatenates the sorted Array to a String, and finally converts to a Number to remove leading zeros. ``` f= n=>+[...new Set(n)].sort().sort((a,b)=>(s=d=>[...n].reduce((S,D,i)=>S+i*(d==D),0))(a)-s(b)).join`` console.log(f('30043376111')) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Ġ’S$ÞịDFQḌ ``` **[Try it online!](https://tio.run/nexus/jelly#@39kwaOGmcEqh@c93N3t4hb4cEfP////jQ0MTIyNzc0MDQ0B "Jelly – TIO Nexus")** Takes and returns an integer. ### How? ``` Ġ’S$ÞịDFQḌ - Main link: n e.g. 30043376111 Ġ - group indices of n by value [[2,3],[9,10,11],[1,5,6],[4],[8],[7]] (implicitly treats the number as a decimal list) Þ - sort that by: $ - last two links as a monad: ’ - decrement (since Jelly is 1-indexed) S - sum [[2,3],[4],[7],[8],[1,5,6],[9,10,11]] (this leaves those indices of lower value to the left as required) D - decimal list of n [3,0,0,4,3,3,7,6,1,1,1] ị - index into [[0,0],[4],[7],[6],[3,3,3],[1,1,1]] F - flatten [0,0,4,7,6,3,3,3,1,1,1] Q - unique [0,4,7,6,3,1] Ḍ - cast to a decimal number 47631 ``` [Answer] # k, 7 bytes ``` .<+/'=$ ``` [online repl](https://johnearnest.github.io/ok/index.html) ``` $30043376111 / convert to string($) "30043376111" =$30043376111 / group(=) - return a mapping (dict) from unique chars to indices "304761"!(0 4 5 1 2 ,3 ,6 ,7 8 9 10) +/'=$30043376111 / sum(+/) each(') value in the dict "304761"!9 3 3 6 7 27 <+/'=$30043376111 / grade(<) ascending values - return keys from the dict "047631" .<+/'=$30043376111 / execute(.) the string - convert it to a number 47631 ``` Juxtaposition of functions is composition, so no explicit parameter or input is required. [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 88 bytes ``` $a=@{};[char[]]"$args"|%{$a[$_]+=$i++};+-join(($a.GetEnumerator()|Sort value,name).Name) ``` [Try it online!](https://tio.run/nexus/powershell#@6@SaOtQXWsdnZyRWBQdG6ukkliUXqxUo1qtkhitEh@rbauSqa1da62tm5WfmaehoZKo555a4ppXmptalFiSX6ShWROcX1SiUJaYU5qqk5eYm6qp5wci////r25sYGBibGxuZmhoqA4A "PowerShell – TIO Nexus") Sets an empty hashtable `$a`, then casts the input `$args` as a `char` array, and loops through each element `|%{...}`. We set the value at "the current element" of `$a` to be incremented by `$i++`, to count up our input's indices. For example, for input `300433766111`, the first loop `$a[3]` gets `+=0`; the next loop, `$a[0]` gets `+=1`; etc. Next, we need to `Sort` our hashtable. Unfortunately, due to an internal language quirk, this means we need to `$a.GetEnumerator()` before we can do the actual sorting. We sort by `value`, then by `name`, to satisfy the requirement of smaller digits get sorted first. We pull out the `.Name`s thereof (in sorted order), `-join` them together into a string, and cast that string as an int `+` to remove leading zeros. That's left on the pipeline and output is implicit. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 11 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ΣISQā<*O}Ùï ``` [Try it online.](https://tio.run/##yy9OTMpM/f//3GLP4MAjjTZa/rWHZx5e//@/sYGBibGxuZmhoSEA) Could be 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) if 1-based indexing is allowed by replacing `ā<*` with `ƶ`, in which case `4` would come before the `0` in the example, because `0: 2 + 3 = 5` and `4: 4`: [try it online](https://tio.run/##yy9OTMpM/f//3GLP4MBj2/xrD888vP7/f2MDAxNjY3MzQ0NDAA). **Explanation:** ``` Σ # Sort the digits of the (implicit) input by: I # Push the input S # Convert it to a list of digits Q # Check for each if it's equal to the current digit (resulting in 1s/0s) ā<* # Multiply each check by its 0-based index: ā # Push a list in the range [1,length] (without popping) < # Decrease each by 1 to make it the range [0,length) * # Multiply the values at the same indices in the two lists O # Sum the lists together }Ù # After the sort-by: uniquify the digits ï # Cast it to an integer to remove potential leading 0s # (after which the result is output implicitly) ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 77 bytes ``` {⍎⊃{⍺[⍋⍵]}/{(⊂⊂⍋⊃⍵)⌷¨⍵}↓⍉{⍺(+/⍵-1)}⌸⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24TqR719j7qagdSu6Ee93Y96t8bW6ldrPOpqAiGgQFczUEzzUc/2QyuAjNpHbZMf9XaClGto6wMFdA01ax/17ABJAQ1UNzYwMDE2NjczNDRUBwA "APL (Dyalog Unicode) – Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), ~~85~~ 62 bits1, ~~10.625~~ 7.75 [bytes](https://github.com/Vyxal/Vyncode/blob/main/README.md) ``` µ?f=T∑;Uṅ⌊ ``` [Try it Online! (link is to bitstring)](https://vyxal.pythonanywhere.com/?v=1#WyIhIiwiIiwiMTEwMDExMDAwMTEwMTEwMDExMDEwMTExMDAwMDAxMDAxMDAwMDEwMTAwMDEwMTAwMDEwMTAxMTAwMTAwMDAiLCIiLCIzMDA0MzM3NjExMSJd) *-2.875 bytes (2 characters) thanks to @lyxal* #### Explanation ``` µ?f=T∑;Uṅ⌊ # Implicit input (as a string) µ ; # Sort input string by: ?f # List of characters of input = # Equals the current character? T∑ # Sum of truthy indices Uṅ⌊ # Uniquify and convert to integer # Implicit output ``` Old: ``` fDÞzµ∑;İfU₀β # Implicit input fD # Convert to digit list and duplicate Þz # Group by indices µ∑; # Sort by sum İfU # Index in, flatten, uniquify ₀β # Convert from digit list # Implicit output ``` [Answer] # [Thunno 2](https://github.com/Thunno/Thunno2), 10 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md) ``` Þ$d=VS;UJN ``` Port of my Vyxal answer (suggested by @lyxal) #### Explanation ``` Þ$d=VS;UJN # Implicit input Þ ; # Sort the input string by: $d= # Vectorised equality with the input string's characters VS # Sum of truthy indices of that list UJN # Uniquify, join, and convert to integer # Implicit output ``` [Answer] # PHP, 103 Bytes ``` for(;$i<strlen($a="$argv[1]");)$r[$a[$i]]+=$i++;ksort($r);asort($r);echo ltrim(join(array_keys($r)),0); ``` [Answer] # Python 2, ~~102~~ 92 bytes *Thanks to Ben Frankel for saving 10 bytes!* ``` a={} for i,j in enumerate(input()):a[j]=a.get(j,0)+i print int(''.join(sorted(a,key=a.get))) ``` [Try it Online!](https://tio.run/nexus/python2#JcrBCsIwDADQ@76ityZYxkqHgrAvGR4CxpEO01Gzgwy/vQq@82s0HZ/uUaqTkJ2oY92fXMkYRLfdAPFKc75N1C9skMOAJ@m2Kmq/beB9n4sovEo1vgOFld//i4it@TSOQ0qXc4zRfwE) Takes input as a string and outputs an integer. Uses a dictionary to store the sum of indexes, then sorts it by value. Converts to an integer to strip off leading zeroes because `int` is shorter than `.lsplit('0')`. [Answer] # Python 3.5, ~~86~~ 85 bytes Thanks @Ben Frankel for saving a byte: ``` f=lambda s:int(''.join(sorted({*s},key=lambda d:sum(i*(c==d)for i,c in enumerate(s))))) ``` Old code: ``` lambda s:int(''.join(sorted({*s},key=lambda d:sum(i for i,c in enumerate(s)if c==d)))) ``` Anonymous function taking a string of digits and returning an integer [Answer] # [Pip](https://github.com/dloscutoff/pip), 18 bytes ``` +J:$+(a@*_)SKSNUQa ``` Takes the number as a command-line argument. [Try it online!](https://tio.run/nexus/pip#@6/tZaWirZHooBWvGewd7BcamPj//39jAwMTY2NzM0NDQwA "Pip – TIO Nexus") ### Explanation ``` a is 1st cmdline arg (implicit) UQa Get unique digits in a SN Sort (numerically) SK Then sort with this key function: a@*_ Find all indices of argument in a $+( ) and sum them J: Join the resulting list back into a string (: is used to lower the precedence of J) + Convert to number (eliminates leading 0) Print (implicit) ``` [Answer] # Scala, ~~123~~ 104 bytes ``` (_:String).zipWithIndex.groupBy(_._1).toSeq.sortBy(c=>c._2.map(_._2).sum->c._1).map(_._1).mkString.toInt ``` Example (using Scala REPL): ``` scala> (_:String).zipWithIndex.groupBy(_._1).toSeq.sortBy(c=>c._2.map(_._2).sum->c._1).map(_._1).mkString.toInt res0: String => Int = <function1> scala> res0("30043376111") res1: Int = 47631 ``` Pretty straightforward, using tuple as sorting predicate for secondary sort. [Answer] # Pyth, 9 bytes ``` sosxNcQ1{ ``` [Try it online](https://pyth.herokuapp.com/?code=sosxNcQ1%7B&input=%2230043376111%22&debug=0) Takes a string of digits as input. ``` sosxNcQ1{ sosxNcQ1{Q Implicit variable introduction {Q Unique digits o Order by cQ1 Chop input into list of individual characters. xN Find all indexes of the digit in question in the list. s Sum s Convert string to integer. ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 96 bytes I'm sure this can be golfed more. ``` ->a{(0..9).map{|n|[(0...a.size).select{a[_1]==n}.sum,n]}.select{_1[0]>0}.sort.map{_2}.join.to_i} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsEiN9ulpSVpuhY3E3TtEqs1DPT0LDX1chMLqmvyaqJBXL1EveLMqlRNveLUnNTkkurE6HjDWFvbvFq94tJcnbzYWphEvGG0QaydAZCfX1QCNiLeqFYvKz8zT68kPz6zFmLPngIFt-hoYx0DIDTRMQZCcx0zHUMQjI2FKFmwAEIDAA) [Answer] # [Japt](https://github.com/ETHproductions/japt) v2.0a0 [`-N`](https://codegolf.meta.stackexchange.com/a/14339/), 10 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ñ ñ@ðX xÃâ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&flags=LU4&code=8SDxQPBYIHjD4g&input=IjMwMDQzMzc2MTExIg) Input as a string Explanation: ``` ñ ñ@ðX xÃâ ñ # Sort the digits by value ñ@ Ã # Stable-sort the digits by this function: ðX # Find all indices where it appears in the input x # Sum them â # Remove repeated characters -N # Convert the string to number (removes leading 0) ``` [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), ~~16~~ 7 bytes ``` .<+/'=: ``` [Try it online!](https://ngn.codeberg.page/k#eJxLs9Kz0dZXt7Xi4kqLVjI2MDAxNjY3MzQ0VIoFAE/+BaY=) *Down 9 bytes thanks to ovs for the sum tip!* A pretty literal implementation of the challenge. Takes a string and output an integer. Explanations: ``` .<+/'=: Main function. Takes implicit input with : = Group, creates a dictionary with characters as the keys and their occurances position as the values ' In each of the key's values... +/ Sum < Sort by ascending order . Evaluate ``` [Answer] ## C#, 245 bytes ``` using System.Linq;s=>{var a=new int[10];for(int i=0,l=0;i<10;i++){a[i]=-1;while((l=s.IndexOf(i+"",l+1))!=-1)a[i]+=l;}return string.Concat(a.Select((c,i)=>new{c,i}).OrderBy(o=>o.c).ThenBy(o=>o.i).Where(o=>o.c>-1).Select(o=>o.i)).TrimStart('0');}; ``` Not happy with how long it ended up being and it can probably be shorter but this is what I ended up with. [Answer] # [Perl 6](https://perl6.org), ~~65 61~~ 52 bytes ``` {+[~] {}.push(.comb.map:{$_=>$++}).sort({.value.sum,.key})».key} ``` [Try it](https://tio.run/nexus/perl6#Hc1BCsIwEADAe16xlCAJLUtLREGpr/CmEmKNVGxM6TZCCfFj3vxYRU9znEAW9pbGLXMTLBp/sVDPMT@8ThAT9oFagY13Z3Sm30Su6x3P8ySR/DCKiE/TBYsUXIF3OyX5ef@dr36A7vawJCREBkBmAq4LyI5jVsCvEVxLlmZVlkul1quqqr4 "Perl 6 – TIO Nexus") ``` {+[~] {}.push(.comb.antipairs).sort({.value.sum,.key})».key} ``` [Try it](https://tio.run/nexus/perl6#Hc0xCsIwFADQvaf4lCIJlk9DRAfxFm4qJdaIpU1T@hMhhHgxNy8W0emNz5OGoya3L0yAVWdvGg45rk@vC8SEs6cHw86aK6rJ9bPqF@JIdnEs4lONXiN5U@OgQ@Kf9998twuM/aSJcYgFAKkAVVtDeXZlDb@CVS0vUpZNs5FytxVCfAE "Perl 6 – TIO Nexus") ``` {+[~] .comb.antipairs.Bag.sort({.value,.key})».key} ``` [Try it](https://tio.run/nexus/perl6#Ky1OVQhJLS6x5sqtVFBLzk9JVbD9X60dXReroJecn5ukl5hXklmQmFlUrOeUmK5XnF9UolGtV5aYU5qqo5edWlmreWg3mP6fll@kkJOZl1qsoalQzaWgUJxYqaASr6OgFFOipKMAMllDJV6Tq/a/sYGBibGxuZmhoSEA "Perl 6 – TIO Nexus") ## Expanded ``` { # bare block lambda with implicit parameter 「$_」 + # turn the following into a Numeric [~] # reduce the following using &infix:<~> (join) .comb # list of digits from 「$_」 (implicit method call) .antipairs # get a list of 「value => index」 pairs from above list .Bag # combine them together (does the sum) .sort( { .value, .key } # sort it by the sum of indexes, then by the digit )».key # get the list of digits from that } ``` [Answer] # [Scala](https://www.scala-lang.org/), 131 bytes Golfed version. [Try it online!](https://tio.run/##Jc5PS8NAEAXwez/F0NOMyNAQUQisIJ48iIfgSaRsspt2df/I7hRSSj973NDre79hXhm110safuwo8K5dhMti7AQTzl0v2cUDqbIaHpP3FbkU2YVwEj14y33KYk1vpfL9HeFHNnY94uGMaLrXo86knnFmF40bbeHJebEZZ9yTUoa4nMK9ISIOv7d3LOktygKwAViHhLoJdT6UDl5y1uevG/umDj6jE1BwqRLgr6biI064bXe7h7Z9emyaZktU2@vmuvwD) ``` def f(x:String)=scala.collection.immutable.SortedSet(x:_*)(Ordering.by((d:Char)=>(x.indices.filter(x(_)==d).sum,d))).mkString.toInt ``` Ungolfed version. [Try it online!](https://tio.run/##VY5NS8QwEIbv@RXDniYiYUtFoVBh8eRBPBRPIkvapLtx87EmqXSR/e112hXF0zDz5H3zpE5aOU3GHUPMkOZNdMFa3WUTvDDODVm2VouGuFaNzoyF9p0wPEnj4YsBKN2DowVl3KUKNjHK02uTo/G7N17BizcZ6uUlwJGu2XrscVWu1zdleXdbFMWKc6Jn9lPW41jBpYDyj/4v/iktpMWEWj8GTeBXbA5trzg@R6XnqGhPiKqCh72MHOp7wFEYr0ynk@iNzTriiFsiNSgu0uCuaS4i8O8P4Q4XF5EDuSyiZzZN3w) ``` import scala.collection.immutable.SortedSet object Main { def main(args: Array[String]): Unit = { println(f("30043376111")) } def f(x: String): Int = { val sortedUnique = SortedSet(x: _*)(Ordering.by((d: Char) => (x.indices.filter(x(_) == d).sum, d))) sortedUnique.mkString.toInt } } ``` ]
[Question] [ In this [fastest-code](/questions/tagged/fastest-code "show questions tagged 'fastest-code'") challenge, you take a positive integer as input, which represents the height of a sand pile, located at (0,0) on an infinite square grid. For example, if our input is `123`, the sand grid looks initially like this: \$\begin{matrix} \ddots & \vdots & \vdots & \vdots & \cdot^{\cdot^\cdot} \\ \cdots & 0 & 0 & 0 & \cdots\\ \cdots & 0 & 123 & 0 & \cdots \\ \cdots & 0 & 0 & 0 & \cdots \\ \cdot^{\cdot^\cdot} & \vdots & \vdots & \vdots & \ddots \end{matrix}\$ Now, piles of sand are unstable, so they topple if their height is 4 or greater. When sand piles topple, they send sand equally in all four directions, but due to the quantum nature of sand, the amount sent is an integer. Or in other words, if there is a pile of height `n`, it sends sand as follows: \$\begin{matrix} \ddots & \vdots & \vdots & \vdots & \vdots & \vdots & \cdot^{\cdot^\cdot} \\ \cdots & 0 & 0 & 0 & 0 & 0 &\cdots\\ \cdots & 0 & 0 & \lfloor\frac{n}{4}\rfloor & 0 & 0 & \cdots\\ \cdots & 0 & \lfloor\frac{n}{4}\rfloor & n\mod 4 & \lfloor\frac{n}{4}\rfloor & 0 & \cdots\\ \cdots & 0 & 0 & \lfloor\frac{n}{4}\rfloor & 0 & 0 & \cdots\\ \cdots & 0 & 0 & 0 & 0 & 0 &\cdots\\ \cdot^{\cdot^\cdot} & \vdots & \vdots & \vdots & \vdots & \vdots & \ddots \end{matrix}\$ This means that sand piles evolve step by step. For example, if we have this initial position, here's how the sand piles evolve (I've removed the dots for clarity). \$\begin{matrix} 0 & 0 & 0 & 0 \\ 0 & 0 & 6 & 0 \\ 0 & 2 & 7 & 0 \\ 0 & 0 & 0 & 0 \end{matrix}\$ \$\begin{matrix} 0 & 0 & 1 & 0 \\ 0 & 1 & 3 & 1 \\ 0 & 3 & 4 & 1 \\ 0 & 0 & 1 & 0 \end{matrix}\$ \$\begin{matrix} 0 & 0 & 1 & 0 \\ 0 & 1 & 4 & 1 \\ 0 & 4 & 0 & 2 \\ 0 & 0 & 2 & 0 \end{matrix}\$ \$\begin{matrix} 0 & 0 & 2 & 0 \\ 0 & 3 & 0 & 2 \\ 1 & 0 & 2 & 2 \\ 0 & 1 & 2 & 0 \end{matrix}\$ Now, since all the sand piles have less than 4 sand, this sand grid is stable. # Rules Your task is to take an positive integer \$i\$ as input, and output the eventually stable grid that the following initial position evolves to: \$\begin{matrix} \ddots & \vdots & \vdots & \vdots & \cdot^{\cdot^\cdot} \\ \cdots & 0 & 0 & 0 & \cdots\\ \cdots & 0 & i & 0 & \cdots \\ \cdots & 0 & 0 & 0 & \cdots \\ \cdot^{\cdot^\cdot} & \vdots & \vdots & \vdots & \ddots \end{matrix}\$ I will execute your code with the following command: `time ./your_executable i > /dev/null` The highest `i` where the time command reports a real time of `<=1 min` will be your score. I will run the programs on an AMD Ryzen 7 1800X linux system with 32 GB of ram. Your code should also compile in 10 minutes or less, and should be less than 60kb. This is simply to prevent calculating the output at comptime or including the output in the source code. Your program will choose some odd integer `l` and write to stdout `l*l` numbers ("0","1","2","3" meaning bytes 48, 49, 50 and 51) and nothing else (not even a trailing newline). These numbers represent the final state of the sand pile. `l` must be large enough to include the whole pile. Your code doesn't have to work for all inputs `i` (for example, you can only accept powers of two, or just a single specific number). Please explicitly state if this is the case in your answer. Also, if your code works significantly faster for some inputs, please also tell this in the answer, as I can't test all values of `i` and instead have to use a binary search or something similar. # Fractals If you plot the outputs, you get really amazing fractals. Here's an example for a sand pile of height \$3\times10^7\$: [![Sand fractal 3*10^7](https://upload.wikimedia.org/wikipedia/commons/e/ee/Sandpile_on_infinite_grid%2C_3e7_grains.png)](https://upload.wikimedia.org/wikipedia/commons/e/ee/Sandpile_on_infinite_grid%2C_3e7_grains.png) [Credit colt\_browning CC BY 4.0](https://commons.wikimedia.org/wiki/File:Sandpile_on_infinite_grid,_3e7_grains.png) What's amazing to me is that even though the rules are very simple and discrete, complex and organic behavior emerges both at a small and large scale. Feel free to include a picture of your sand piles. # Further reading These are called [Abelian sandpiles](https://en.wikipedia.org/wiki/Abelian_sandpile_model). Numberphile has a [video](https://www.youtube.com/watch?v=1MtEUErz7Gg) about them. # Leaderboard | Score | Language | Author | | --- | --- | --- | | 10000000 | C (clang -march=native -Ofast) | [Polichinelle](https://codegolf.stackexchange.com/a/242612/84290) | | 8388608 | Bash + xz + node (compressed) | [Community](https://codegolf.stackexchange.com/a/242526/84290) | | 4800000 | Rust (rustc -Copt-level=3 -Ctarget-cpu=native) | [alephalpha](https://codegolf.stackexchange.com/a/242598/84290) | | 1572864 | Python + numpy | [ovs](https://codegolf.stackexchange.com/a/242442/84290) | | 1376256 | C (clang -march=native -Ofast) | [AnttiP](https://codegolf.stackexchange.com/a/242610/84290) | | 1350000 | Rust (RUSTFLAGS="-Ctarget-cpu=native" cargo ...) | [Aiden4](https://codegolf.stackexchange.com/a/242695/84290) | | 410000 | C (clang -march=native -O3) | [astroide](https://codegolf.stackexchange.com/a/242446/84290) | [Answer] # [C (clang)](http://clang.llvm.org/), 8895 bytes, score 14000000 on TIO (revised again) This is a multithreaded version of my earlier revision, which is still available below. Please note: * The number of threads, which is set by `-DNUM_THREADS=...`, should be a power of two. I used two threads for the run on TIO. The default is eight. * The code uses spin locks. You can avoid this by compiling with the option `-DUSE_COND_VAR`, but the program becomes slower. * The program uses C11 threads, so you may have to compile with the library `-lpthread`. * For the run on TIO, I compiled with the flags `-Ofast -march=native`. ``` #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <stdbool.h> #include <assert.h> #include <stdatomic.h> #include <threads.h> typedef unsigned long long bitmask; #ifndef ALIGN #define ALIGN 4 #endif #ifndef GROUP_SIZE #define GROUP_SIZE 50 #endif // Number of threads should be a power of 2 #ifndef NUM_THREADS #define NUM_THREADS 8 #endif #define ORIG_MASK 0333333333333333333333ull #define XFER_MASK 0111111111111111111111ull #define HIGH_MASK 0444444444444444444444ull #define DIGS_PER_BM (8u * sizeof(bitmask) / 3u) #define LSH (3 * (DIGS_PER_BM - 1) - 2) #define RSH (3 * (DIGS_PER_BM - 1) + 2) #define SIZE(n) ((size_t)(n) * ((size_t)n + 1) * DIGS_PER_BM * ALIGN * ALIGN / 2) void one_round(const bitmask *src, bitmask *dest, size_t n, unsigned thd_num) { size_t na = n * ALIGN; const bitmask *s; bitmask *d; if (thd_num == 0) { *dest = (*src & ORIG_MASK) + + (*src << 1 & XFER_MASK) + (*src >> 5 & XFER_MASK) + (src[1] << LSH & XFER_MASK) + 2 * (src[na] >> 2 & XFER_MASK) + 3 * (*src >> 5 & 1); // Origin s = src + 1; d = dest + 1; for (size_t ct = na - 1; ct-- != 0; s++, d++) *d = (*s & ORIG_MASK) + (*s << 1 & XFER_MASK) + (s[-1] >> RSH) + (*s >> 5 & XFER_MASK) + (s[1] << LSH & XFER_MASK) + 2 * (s[na] >> 2 & XFER_MASK); } else { s = src + na; d = dest + na; } for (size_t k = n; k != 0; k--, s -= ALIGN, d -= ALIGN) { size_t kau = k * ALIGN; size_t ka = (k - 1) * ALIGN; if (((n - k) & (NUM_THREADS - 1)) != thd_num) { s += kau * (ALIGN * DIGS_PER_BM - (k == n)) + ALIGN; d += kau * (ALIGN * DIGS_PER_BM - (k == n)) + ALIGN; continue; } const bitmask *s1 = s; bitmask *d1 = d; for (size_t ct = kau * (ALIGN * DIGS_PER_BM - 1 - (k == n)); ct-- != 0; s1++, d1++) *d1 = (*s1 & ORIG_MASK) + (s1[-kau] >> 2 & XFER_MASK) + (*s1 << 1 & XFER_MASK) + (s1[-1] >> RSH) + (*s1 >> 5 & XFER_MASK) + (s1[1] << LSH & XFER_MASK) + (s1[kau] >> 2 & XFER_MASK); for (size_t ct = ALIGN - 1; ct-- != 0; s1++, d1++) *d1 = 0; *d1 = (*s1 & ORIG_MASK) + (s1[-kau] >> 2 & XFER_MASK); if (ka != 0) { *d1++ += (s1++)[1] << LSH & XFER_MASK; for (size_t ct = ka; ct-- != 1; s1++, d1++) *d1 = (*s1 & ORIG_MASK) + (s1[-kau] >> 2 & XFER_MASK) + (*s1 << 1 & XFER_MASK) + (s1[-1] >> RSH) + (*s1 >> 5 & XFER_MASK) + (s1[1] << LSH & XFER_MASK) + (s1[ka] >> 2 & XFER_MASK); *d1 = (*s1 & ORIG_MASK) + (s1[-kau] >> 2 & XFER_MASK) + (*s1 << 1 & XFER_MASK) + (s1[-1] >> RSH) + (*s1 >> 5 & XFER_MASK) + (s1[ka] >> 2 & XFER_MASK); } // Fix up main and left of main diagonals for (size_t yd = 0; yd != ALIGN; yd++, s++, d++) { if (yd != 0) d[-1] = 0; for (size_t yf = 0; yf != DIGS_PER_BM; yf++) { if (k == n && yd == 0 && yf == 0) continue; // Skip top row bitmask diag_mask = 3ull << (yf * 3); *d += s[-kau] >> 2 & XFER_MASK & diag_mask; *d += *s >> 5 & XFER_MASK & diag_mask; *d &= ~(diag_mask >> 3); s += kau; d += kau; } if (k != 1 || yd != ALIGN - 1) d[-kau] += s[1 - kau] << LSH & XFER_MASK; } } } int get_pixel(const bitmask *src, size_t n, size_t x, size_t y) { if (y > x) { size_t temp = x; x = y; y = temp; } size_t y_block = y / (ALIGN * DIGS_PER_BM); size_t y_remdr = y % (ALIGN * DIGS_PER_BM); x -= y - y_remdr; size_t block_start = n * y_block - y_block * (y_block - 1) / 2; return 3 & src[block_start * ALIGN * ALIGN * DIGS_PER_BM + y_remdr * (n - y_block) * ALIGN + x / DIGS_PER_BM] >> (3 * (x % DIGS_PER_BM)); } void print(const bitmask *src, size_t n) { long long np = n * ALIGN * DIGS_PER_BM - 1; for (long long y = -np; y <= np; y++) { for (long long x = -np; x <= np; x++) putchar('0' + get_pixel(src, n, llabs(x), llabs(y))); } } typedef struct { size_t n; unsigned long long weight; bitmask *grid; } Grid; void double_(Grid *p_g, bool add_one) { size_t ct = SIZE(p_g->n); for (bitmask *src = p_g->grid; ct-- != 0; src++) *src <<= 1; p_g->weight <<= 1; if (add_one) { (*p_g->grid)++; p_g->weight++; } } void expand(Grid *p_g) { size_t n = p_g->n; size_t new_n = ((size_t)(ceil(sqrt(p_g->weight) / 2.7) + 4) + DIGS_PER_BM * ALIGN - 1) / (DIGS_PER_BM * ALIGN); if (n < new_n) { size_t byte_size = SIZE(new_n) * sizeof(bitmask); bitmask *new_grid = (bitmask *)aligned_alloc(ALIGN * sizeof(bitmask), byte_size); assert(new_grid != NULL); memset(new_grid, 0, byte_size); bitmask *src = p_g->grid; bitmask *dest = new_grid; for (size_t k = n, l = new_n; k != 0; k--, l--) { for (size_t ct2 = ALIGN * DIGS_PER_BM; ct2-- != 0; ) { memcpy(dest, src, k * ALIGN * sizeof(bitmask)); src += k * ALIGN; dest += l * ALIGN; } } free(p_g->grid); p_g->n = new_n; p_g->grid = new_grid; } } void initial(Grid *p_g) { size_t byte_size = SIZE(1) * sizeof(bitmask); p_g->n = 1; p_g->weight = 0; p_g->grid = (bitmask *)aligned_alloc(ALIGN * sizeof(bitmask), byte_size); assert(p_g->grid != NULL); memset(p_g->grid, 0, byte_size); } void copy_empty(const Grid *p_g, Grid *p_h) { size_t byte_size = SIZE(p_g->n) * sizeof(bitmask); p_h->n = p_g->n; p_h->grid = (bitmask *)aligned_alloc(ALIGN * sizeof(bitmask), byte_size); assert(p_h->grid != NULL); } void free_grid(Grid *p_g) { free(p_g->grid); } bool is_done(const Grid *p_g) { size_t ct = SIZE(p_g->n); for (bitmask *src = p_g->grid; ct-- != 0; src++) if ((*src & HIGH_MASK) != 0) return false; return true; } // Common data between threads Grid grid_1; Grid grid_2; bool done_flag = false; #ifndef USE_COND_VAR atomic_ullong barr_ct; void barrier(unsigned long long *p_barr_ct2) { *p_barr_ct2 += NUM_THREADS; if (atomic_fetch_add(&barr_ct, 1) >= *p_barr_ct2 - 1) return; while (atomic_load(&barr_ct) < *p_barr_ct2) thrd_yield(); } #else unsigned long long barr_ct = 0; cnd_t cond; mtx_t mutex; void barrier(unsigned long long *p_barr_ct2) { *p_barr_ct2 += NUM_THREADS; int rv = mtx_lock(&mutex); assert(rv == thrd_success); if (++barr_ct >= *p_barr_ct2) { rv = mtx_unlock(&mutex); assert(rv == thrd_success); rv = cnd_broadcast(&cond); assert(rv == thrd_success); return; } for (;;) { rv = cnd_wait(&cond, &mutex); assert(rv == thrd_success); if (barr_ct >= *p_barr_ct2) { rv = mtx_unlock(&mutex); assert(rv == thrd_success); return; } } /*NOTREACHED*/ } #endif void process(unsigned thd_num, unsigned long long *p_barr_ct2) { for (int i = 0; i < GROUP_SIZE; i++) { one_round(grid_1.grid, grid_2.grid, grid_1.n, thd_num); barrier(p_barr_ct2); one_round(grid_2.grid, grid_1.grid, grid_1.n, thd_num); barrier(p_barr_ct2); } } int helper_thread(void *p_info) { unsigned long long barr_ct2 = 0; unsigned thd_num = *(unsigned *)p_info; for (;;) { barrier(&barr_ct2); if (done_flag) break; process(thd_num, &barr_ct2); } return 0; } int main(int argc, char **argv) { assert(sizeof(bitmask) == 8); assert(argc >= 2); size_t starting_pile = atol(argv[1]); size_t mask = 1; int rv; initial(&grid_1); while (mask << 1 <= starting_pile) mask <<= 1; #ifndef USE_COND_VAR atomic_init(&barr_ct, 0); #else rv = cnd_init(&cond); assert(rv == thrd_success); rv = mtx_init(&mutex, mtx_plain); assert(rv == thrd_success); #endif thrd_t thd_ids[NUM_THREADS - 1]; unsigned thd_num[NUM_THREADS - 1]; for (unsigned i = 0; i < NUM_THREADS - 1; i++) { thd_num[i] = i + 1; rv = thrd_create(&thd_ids[i], helper_thread, &thd_num[i]); assert(rv == thrd_success); } unsigned long long barr_ct2 = 0; for (; mask != 0; mask >>= 1) { double_(&grid_1, (mask & starting_pile) != 0); expand(&grid_1); copy_empty(&grid_1, &grid_2); for (;;) { barrier(&barr_ct2); process(0, &barr_ct2); if (is_done(&grid_1)) break; } free_grid(&grid_2); } done_flag = true; barrier(&barr_ct2); for (unsigned i = 0; i < NUM_THREADS - 1; i++) { rv = thrd_join(thd_ids[i], (int *)NULL); assert(rv == thrd_success); } #ifdef USE_COND_VAR cnd_destroy(&cond); mtx_destroy(&mutex); #endif print(grid_1.grid, grid_1.n); free_grid(&grid_1); return 0; } ``` [Try it online!](https://tio.run/##zVltb9vIEf6uX7FBUB2pl1h0cmgARQbS2GcHTeyDfWmLGgFBkStpa2qpklQsNef@9Koz@84XyU56B1SALXJ3dnb22WdmZ1bxME4jPt/tnjMep@uEkjdFmbDsxeKkU2lK2bTeljM@r7Yto3LRGDnNsrTaGBUFzcuGYFRmSxZXm8tFTqOkwMZOuV3RhM7ImhdszmlC0ozP5b8pK5dRcTfuwNAZR6G3H96fX3aewyPjVL6RV53nlCdsZqXOr68@/RzevP/7mRG1TeTHkRlwdEQu18spzUk2I8ooUiyydZqQKSURWWX3svPYar/89DH85eL67O3pjVHvtJHX1h7Ve3X9/jz8@Pbmz2T0su2zTlMj@7efzq6VbND2cWUv3p9fKNlXbR9X9vT9@U34M@j@00fivV6THinYv2g28xTIPjkiL9e@kf9wc0G8lyDmuSOHJPDh37GVu94v10c5I4jYe9wnnocTh6WPLz37ykE@wBZXT0/tsf4@Eiq/ZCwhGadhnq154sUZL0pNFtIr8nhg3xJalAMi5yB8YGlWLpKQr5d@52uHmP6ITAjXswHvCKkrH0ObVS5E2Ix4ShuZTMjIhzZUSuTsoJIQD80iXUsFgEeI6E9fibx5QwKQMzTwW6VOTsiPFSnsgY7b4DNqwM07oOMYcUdpHn1GVceHhMXeupMG/tgRABe6ytmc8Y4YV8BqURb2ciwaEmgQKJiWWZYTtekkRnQAdeDLGF6GQ/IMAByTot8fkKTf18b0EoEiGlIBsQlOE0ABze0wEEsFurYNasfzW9BsxxJX/EBoWlDDCYsQjxoQyaYHxNKF6Q5RGsOXROduOARKk@FE8hSQMs@We3potIbBd5bTlT7o8u6kt7qkl5z2PA5dEBm6xHMDHIr7aIpxIRzxVcFSkP5EzAqoaOethgaYEdyE@wiyYxQC8d1DwU1LxtdUvj/IRdR9N0DopYR1YWxM1Kob1DxoTOAaNLascHkcCCIHLpMDHRCCg1QugtshTP@4gwpN7awPDtM@2MP74GnER8F2C/fBKXFsOPsekEZKjYLsAGIH4XIYDYR/pgK0JWwPZ0bmeWiI3752paSVInYxQdtinrrn37Lr373vv8XO273fj/b/PdE7T16PE1DgsPuJbch6RZYR4yTikK3SWYkJomhIWDTPeJQWTf5vE8Fo/H6mHAFfkCzVw07TEvkqhUfW2ESs07pGbY6ZmmOGw5xghU2WkF@NOuETIoCRbleYCOPF48xkMiaq6QiLKNzcsRUpsxXJs/uOEdJBFWEIxdOEYHKLm@aByh55afkhDnXwumLP7sOz0TOujWk5sfeKdyfk3561CMZVjNDHlR2T1FoeOi5Y6OXk11/dfRQHortFYj1iaXhEiLe2iKKVP3SAXoyXZE7LcMU2NG1NaW0Oq5425mkrs1hBGXJCNo0soKTLFWzGRk66gcetfNzCI3bKtMPIb8NpmsW4f1vIudvOP@EYRjqnyyQX0n/YL73BLGULiCh5R4OYLSzKKC9VBq4tGJonOIdtY4D1yjFqyGm5zjmkqV1Mq25dTfXqoWJSLaSJKKAXAlNxO7PJjdqGbMAOR6vgsayHNoCFCwFg8KBqlxUU2eXBTZYbakthvnIrk2YqMtYZox2CWzvkK/B98gbG4oOMAV9tcLLSGy290dIbGzFW6zJeRLn3w@gHWLKlqTAZCJmm0bTwNr5@2voyIRLMtiV@UebruKwUXCjVUvnfUzZflJVaa54zSNMeyLn4ljgm2Xqa0tDDNtJbhXMo/LIsJVGShFAfVmo7cViLIhTkhifcN5C5OwAyolvMVklS8ljjoeq0iURdiEt7bSN6ojFCI@71jGq/35f@54yWTQ@GJHSzggPGrq1aqWpDueNFnN6H2GFL7Jgy2KV/5qXnTCRc58Uf8eR85Tc5feDTby3OK@Gv@TmqXg2oUb6GiZM30vBG0JpuSxris944Kda8uqil9CiGIJOJa5XdZj9KBd/CKAX3NuGqpnRg51cTyAsuz6gHYlx@@vBB9S7psqC2d0BGTQ17mVarSeStgVbVLJtFPQjOpoTqpWE6HFZziWrSemwy8V41SYAuw/dmsgALjFdbT12ooOffOfGohp5TD4lit1GCiqNSFL0TWEet66Fj/89ySj3rOI7bcLN82yb3vQKd9SjGWcmidI9LNegW7KGambzh/yIxq1ryv9JOkc6qdFmnOGc6G6TTK4@z1TaEY77cqlPHiZj6cXEYDRU190GykJDYmCSafmsQFg0Q9AqRJmLL67vb4A@MEIcEK8IE4nMdkN/p0BAXKuoS0Nzb@pX0XmUyM6gfqMhQVQOcmnQsT1JxZf0uWy4zKDaiMiJTWt5TyvXldacj1oGGhMBO@wKpklg0rjicpdEcbNYT6YvtTzdn4bury9PwL2@vOx15bx9C@i6u4qM8D@NSH7z4ymjutRzdgKESPpZQOg3o7M5Nkjkp5VQzCllGCMem11UDBpjnnUwqKsxpI9FBHfcLllKjJs0iq8GH06ViEY4EsJJwy2iaeJIPz8UNXaftJwg5UHp2zBPkRMYhrizLDTwv1yXd/A6gQDGQf4FJcRZMQb2umMl1BuyfyKUU6zimReGb2@h@X9tdBc8esUb7mtf1H57BDEYwpjlgHUdF6XURlacONxtnLzrH45ptqP4@YkrzgHyTgYjBfgTsoXYQhcencZeiSznId3qXV7/AVr67ODvtHUl6yd@DTPafoRKv/lPEgDyFOQIuJAiTxT4Dhttft@DdTfLtjyQyJLyQp4QMCe5L8ALyCX2fq9IRRWfHgHGb0pqe71JqSuAFTVc0D2U48wRcgADjs0yufr@LHuvTtw4rtPcs1j1fqhu3Uk@b160tGQllQqeO11OwUd016C01O9mtLc9G89FYrxWvjMRORvkcsimssEivBy9f5FoV/eq/0wEXX7uBAEcjy4/dklwUwIzPoVBL8QiH2Jii5Jfb4LMrp25pAht1ZBBRmVJX7qPvRFkxQtzCQbFTmUbiovqFzj1HCyEqVOM0TrAfYQRTsdgJA1LKBJjDXmlcWo4SDj0QDasU8H48gmpnVcdEKWjEkuK29hPI5zautQoJlhlJx21rwjXf1SoZXvgx@/uZWKGwLQYCltTragvZ50HVgYCHVsuTYqdg6qNOZlxH7rZMdtT12kSez3INukBXPBoo@nRrxJFpkLRPlb0u84ibvxpV8kF7qOPKNr7vc2frsKO6q2pv19mhtsNWuI7b2wpFpp6uSQJJN92Sadw@o76TJJYM/8ggmrhMEKGl5zsl6qNbD@7a5q3ohFir5dnW8UP0KdOqD07HfeQlV@upIDOVOm6BP67Fyd1uF7waic9/YoSx2A2vZpBv7IanDi6T490wXcLfStJ@N/wrlBfwn27KPILvFU0iXrJ4N1xGebyY8KhkX@huWJTJJA6C/wI "C (clang) – Try It Online") # [C (gcc)](https://gcc.gnu.org/), 6348 bytes, score 10500000 on TIO (revised) This is a revision of my earlier answers to take advantage of the eightfold symmetry of the square. Since I used the doubling trick, the sandpile heights never exceed seven, so they are stored as three-bit octal digits, 21 per `unsigned long long`. For TIO I compiled with the flags `-O3 -march=native`. ``` #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <stdbool.h> #include <assert.h> typedef unsigned long long bitmask; #ifndef ALIGN #define ALIGN 4 #endif #ifndef GROUP_SIZE #define GROUP_SIZE 50 #endif #define ORIG_MASK 0333333333333333333333ull #define XFER_MASK 0111111111111111111111ull #define HIGH_MASK 0444444444444444444444ull #define DIGS_PER_BM (8u * sizeof(bitmask) / 3u) #define LSH (3 * (DIGS_PER_BM - 1) - 2) #define RSH (3 * (DIGS_PER_BM - 1) + 2) #define SIZE(n) ((size_t)(n) * ((size_t)n + 1) * DIGS_PER_BM * ALIGN * ALIGN / 2) void one_round(const bitmask *src, bitmask *dest, size_t n) { size_t na = n * ALIGN; *dest = (*src & ORIG_MASK) + + (*src << 1 & XFER_MASK) + (*src >> 5 & XFER_MASK) + (src[1] << LSH & XFER_MASK) + 2 * (src[na] >> 2 & XFER_MASK) + 3 * (*src >> 5 & 1); // Origin const bitmask *s = src + 1; bitmask *d = dest + 1; for (size_t ct = na - 1; ct-- != 0; s++, d++) *d = (*s & ORIG_MASK) + (*s << 1 & XFER_MASK) + (s[-1] >> RSH) + (*s >> 5 & XFER_MASK) + (s[1] << LSH & XFER_MASK) + 2 * (s[na] >> 2 & XFER_MASK); for (size_t k = n; k != 0; k--, s -= ALIGN, d -= ALIGN) { size_t kau = k * ALIGN; size_t ka = (k - 1) * ALIGN; const bitmask *s1 = s; bitmask *d1 = d; for (size_t ct = kau * (ALIGN * DIGS_PER_BM - 1 - (k == n)); ct-- != 0; s1++, d1++) *d1 = (*s1 & ORIG_MASK) + (s1[-kau] >> 2 & XFER_MASK) + (*s1 << 1 & XFER_MASK) + (s1[-1] >> RSH) + (*s1 >> 5 & XFER_MASK) + (s1[1] << LSH & XFER_MASK) + (s1[kau] >> 2 & XFER_MASK); for (size_t ct = ALIGN - 1; ct-- != 0; s1++, d1++) *d1 = 0; *d1 = (*s1 & ORIG_MASK) + (s1[-kau] >> 2 & XFER_MASK); if (ka != 0) { *d1++ += (s1++)[1] << LSH & XFER_MASK; for (size_t ct = ka; ct-- != 1; s1++, d1++) *d1 = (*s1 & ORIG_MASK) + (s1[-kau] >> 2 & XFER_MASK) + (*s1 << 1 & XFER_MASK) + (s1[-1] >> RSH) + (*s1 >> 5 & XFER_MASK) + (s1[1] << LSH & XFER_MASK) + (s1[ka] >> 2 & XFER_MASK); *d1 = (*s1 & ORIG_MASK) + (s1[-kau] >> 2 & XFER_MASK) + (*s1 << 1 & XFER_MASK) + (s1[-1] >> RSH) + (*s1 >> 5 & XFER_MASK) + (s1[ka] >> 2 & XFER_MASK); } // Fix up main and left of main diagonals for (size_t yd = 0; yd != ALIGN; yd++, s++, d++) { if (yd != 0) d[-1] = 0; for (size_t yf = 0; yf != DIGS_PER_BM; yf++) { if (k == n && yd == 0 && yf == 0) continue; // Skip top row bitmask diag_mask = 3ull << (yf * 3); *d += s[-kau] >> 2 & XFER_MASK & diag_mask; *d += *s >> 5 & XFER_MASK & diag_mask; *d &= ~(diag_mask >> 3); s += kau; d += kau; } if (k != 1 || yd != ALIGN - 1) d[-kau] += s[1 - kau] << LSH & XFER_MASK; } } } int get_pixel(const bitmask *src, size_t n, size_t x, size_t y) { if (y > x) { size_t temp = x; x = y; y = temp; } size_t y_block = y / (ALIGN * DIGS_PER_BM); size_t y_remdr = y % (ALIGN * DIGS_PER_BM); x -= y - y_remdr; size_t block_start = n * y_block - y_block * (y_block - 1) / 2; return 3 & src[block_start * ALIGN * ALIGN * DIGS_PER_BM + y_remdr * (n - y_block) * ALIGN + x / DIGS_PER_BM] >> (3 * (x % DIGS_PER_BM)); } void print(const bitmask *src, size_t n) { long long np = n * ALIGN * DIGS_PER_BM - 1; for (long long y = -np; y <= np; y++) { for (long long x = -np; x <= np; x++) putchar('0' + get_pixel(src, n, llabs(x), llabs(y))); } } typedef struct { size_t n; unsigned long long weight; bitmask *grid; } Grid; void double_(Grid *p_g, bool add_one) { size_t ct = SIZE(p_g->n); for (bitmask *src = p_g->grid; ct-- != 0; src++) *src <<= 1; p_g->weight <<= 1; if (add_one) { (*p_g->grid)++; p_g->weight++; } } void expand(Grid *p_g) { size_t n = p_g->n; size_t new_n = ((size_t)(ceil(sqrt(p_g->weight) / 2.7) + 4) + DIGS_PER_BM * ALIGN - 1) / (DIGS_PER_BM * ALIGN); if (n < new_n) { size_t byte_size = SIZE(new_n) * sizeof(bitmask); bitmask *new_grid = (bitmask *)aligned_alloc(ALIGN * sizeof(bitmask), byte_size); assert(new_grid != NULL); memset(new_grid, 0, byte_size); bitmask *src = p_g->grid; bitmask *dest = new_grid; for (size_t k = n, l = new_n; k != 0; k--, l--) { for (size_t ct2 = ALIGN * DIGS_PER_BM; ct2-- != 0; ) { memcpy(dest, src, k * ALIGN * sizeof(bitmask)); src += k * ALIGN; dest += l * ALIGN; } } free(p_g->grid); p_g->n = new_n; p_g->grid = new_grid; } } void initial(Grid *p_g) { size_t byte_size = SIZE(1) * sizeof(bitmask); p_g->n = 1; p_g->weight = 0; p_g->grid = (bitmask *)aligned_alloc(ALIGN * sizeof(bitmask), byte_size); assert(p_g->grid != NULL); memset(p_g->grid, 0, byte_size); } void copy_empty(const Grid *p_g, Grid *p_h) { size_t byte_size = SIZE(p_g->n) * sizeof(bitmask); p_h->n = p_g->n; p_h->grid = (bitmask *)aligned_alloc(ALIGN * sizeof(bitmask), byte_size); assert(p_h->grid != NULL); } void free_grid(Grid *p_g) { free(p_g->grid); } bool is_done(const Grid *p_g) { size_t ct = SIZE(p_g->n); for (bitmask *src = p_g->grid; ct-- != 0; src++) if ((*src & HIGH_MASK) != 0) return false; return true; } int main(int argc, char **argv) { assert(sizeof(bitmask) == 8); assert(argc >= 2); size_t starting_pile = atol(argv[1]); size_t mask = 1; Grid grid_1, grid_2; initial(&grid_1); while (mask << 1 <= starting_pile) mask <<= 1; for (; mask != 0; mask >>= 1) { double_(&grid_1, (mask & starting_pile) != 0); expand(&grid_1); copy_empty(&grid_1, &grid_2); for (;;) { for (int i = 0; i < GROUP_SIZE; i++) { one_round(grid_1.grid, grid_2.grid, grid_1.n); one_round(grid_2.grid, grid_1.grid, grid_1.n); } if (is_done(&grid_1)) break; } free_grid(&grid_2); } print(grid_1.grid, grid_1.n); free_grid(&grid_1); return 0; } ``` [Try it online!](https://tio.run/##zVh7b9s2EP/fn4JFMU@yo8ZyWqyA4gAd1qbB0qZIUGxYUAiyRNuCZcqT5MRe6n30eXd8iNQr67YOmIDEFHkP3u@OxzuFzjwMD4enMQuTTUTJaV5EcfpscdarTCXxtD6XxWxenVsFxaLBOU3TpDoZ5DnNCpzrFbs1jeiMbFgezxmNSJKyufg3jYtVkC@9HnDOGBK9urw4f997CsOYUfFGnveeUhbFM011fn318YN/c/HL65JUT5EXI80gV6@uL879d69ufiSjk7ZnkyQl7c9vXl9LWrftMWnfXpy/lbTP2x6T9oeL8xv/A8j@/h2xXm7IgOTxbzSdWRIFmxyTk41d0l/evCXWCZBZJqdDXBv@jTXddTfdEOlKQgTHYjaxLFTsFza@DPQrA3oXZ0w5A@kE9XvMRd6lcURSRv0s3bDIClOWF8qbZJBn4ZF@i2heHBGhgzC799Aj5VtAJoQp2RAGRJDDLCEWyiF97TuwBwjUM5QEp6fEBarSa3YLzdkZeVGhwRVYuHU/IT8i3SlhjBAhLQs@oaBxNyl3gqnQtT29To6PyVUWz2OGdtYhA5ORETzgwaoGD@Y5InJhlmZE@ouEiBNACK724MVxyJMJGXkkHw6PSDQcis1xEQLOCph1mJpAcpBuHZebDVHWZGnH9ctRbceUx4Fp6BLt9OBH2Ld0HIgn4kxE2ICt5RiVPHBFijXYAPNSh1hlDZaspTgqZgw2veOiewSzdg1ORpKh4RdUDCaqw1M7mvAHiidglm17GhjTiS73oqvcSKRC7ki3y5PcMbl764D6x6NVutDtcLvb4feSrd317l/7Xm2xfYddcAocG5HeAdJIipGQPYLYo3BJKfEMnBVwlYLzQSsbDslwgjJgC@22SyGtIaKNcduM@VKf/x2v/2O/fw3Pa993o/2/D/TeF9uDBHthFeT@N/GWbNZkFcSMBAzKIDorSDoTE1EczFMWJHkz/ncRj2j8fSIPAr5gsFQzvQpLjFdBPNKbjbid@mjUdMykjhmyGckKp3RAPpTi@JngCYz0@3yLwM@HMz40UYJkWsRsQz1E4WYZr0mRrkmW3vdKIpVUEQafjyYEizJ0mgUiB@RExwe/0@DU5R3eh3Epx6vxtFxaneT9Cfnd0jsCvsomcpQHG9A8UW1m3zPBwlNOPn82/civHtNF3B5uGl4R/K0toyjh@x6EV8wKMqeFv463NGktxVS1VY625Wgn6jEeMuSMbBsXaEFXa3DGVijdwnAnhjsY4qLXE3tRAv1pkobovx3Uim33Hz8YJXVGV1HGqb/ppt7iBb8DRCS9IYFr8/MiyApZS6odOOUI7mE96WKdPUYJGS02GYOqrY@l160pqV71VrZUS2k8CyhDQBXTmsuyoo1lC/swpPI4FnX8FrAwIQAM9rLmXkNHVjzqZOFQ3WOxtVljN0uRsqrULOhah63h7JNT4MWByAEPOjlp6q2i3irqrc4Y600RLoLM@nb0LZisw5RvGQIySYJpbm1tNdrZoiDika17R@hEN2FRaR2QqqWlvKfxfFFUauh5FkOZtifn/FfgGKWbaUJ9C@fIYO3PoWGBJpYEUeRDX1PpUvhlzZsnoHPOmF1CZnoAaPgy11YpUrKwrMVFwzIRqHNysV89iSex3IRC3BqUou3hUJw/g1tM7csgods1XDDatmrPpTbKjFPE6L2PC7o1DGkMXvo1KyxDET86z77Dm/O53YzpR55ha1NZSX/N57ja0kouW8HEyKnYeCNpTXcF9XGsHCfImi13raRHMgSZTMxdaTfbQcLjzQ8SON5luqoJPdL6pQLxNcQqxUNgvP94eSlXV3SVU716REZNCZ2RVutJRPOsRHmNYoK3UnDYJFG9q0ocp1pLVIvWcVmJD6pFAiyV8d4sFsDAcL2z5IcAPPlLIx/V0DP6Id4QN7o3flXylngCdtSW9j39f5ZRaumDYxwbVpqv54TfK9DpExWzuIiDpONINcLN7Qi1Unnj/PPCrLqTfxt2Mui0SDPqZMyVi42gU5aH6XrnwzVf7OStY2RMNVw8jobMml2QLAQkOifxqa8NwqIBgrIQw4S7vO7dRvwAB78k4tyPID/XAfmPLg1MdepbWPm90a6U97KSmUH/QHmFKifg1qSeqhGxz7BwEGRzOIJ4LZPBAF7uxMYlVPWPklDNvzShRG5yNiFjs47jVVPM5nC7J@j3oEgTpLyDrtCkk6U9D3@OGxruu0fid8z3rs5aX6xx9vsFyrU4O@/j4Lqs6BRIyHWuQMHtiVkBqyzkJ@LeERlKlQJ9tRehpl9TIAAXCUNesOYOiXlSSlFiMLaNROx5LRkW3RKLFiyGW01/zIb3tvZLf3oVmp6JMyy0mS/uM2Yk1BpbjbKDzexiVOQry/XtPc1osPRq2VccKxME3g6LIrZLa6/J69pmVEOm3B8OB3f0YoTPH@EsCeb5wfkJMgP8p9siC@AXKscAGs/w4ORFNAld9@BcnRycVZCFiwkLiviOHpxk9Sc "C (gcc) – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/) + [numpy](https://numpy.org/), scores ~450000 on TIO ``` import math import sys import numpy as np def step(g): a = g>>2 g &= 3 g[1:] += a[:-1] g[:-1] += a[1:] g[:, 1:] += a[:, :-1] g[:, :-1] += a[:, 1:] g[0] += a[1] g[:, 0] += a[:, 1] def nd(g, n): for y in range(0, n): for x in range(0, n): if g[y, x] > 3: return True return False def grd(i, size): a = i>>2 if a: grid = grd(a, size)<<2 while nd(grid, size): for _ in range(a>>(a.bit_length()>>1)): step(grid) else: grid = np.zeros((size, size), dtype=np.ubyte) grid[0,0] = i&3 return grid def main(i): size = math.ceil(math.sqrt(i)/2.7)+3 grid = grd(i, size) for y in [*range(size-1, 0, -1), *range(size)]: print(*grid[y][:0:-1], *grid[y], sep='', end='') if __name__ == '__main__': i = int(sys.argv[1]) main(i) ``` [Try it online!](https://tio.run/##dVNNb6MwEL3zK@bUmNZhIWxVKQoc9xfsDSHLXRzHUnBc43RD/zw7xlBIq50L43nz8d7YmN6dLjofBtWai3XQcneKJr/ru9nV19b0wDvQJooacYTOCUNkvI8AjUMBsix340HCQwF5cKtsX8NTAbzab7N6ink3BBGdYxSWVArr7HD6hJaadO6ySk1XiXVgqhsiKeiJ6vFioQelwXItBUkXZEZv/0W9qSMO6incaighv8e8WeGuVsNvexXR6vyLnzsR@EjbEEWhUx9itT41rw8H8KWttKrxy8UaPtUcDrtP@O9JncWoEPPueq4VsUURL0vCk1fl2Flo6U4kLsssjr/rCPeLXeMREkj/Gyttkg9hLx0hfvA0nkLjeiMKBK@vvROh3ldUKcXrQakP@Xo1HgqbabnSRE1kfDNM9u8x@SPUmYxe92YdpvzYJS/xUx59WdG81vubrh6Ddg9tM3wjFLYZ8lyF43oRZ6zSjjyOjPu62qf@@WH2FMARwhSbDQWhG/zGUYRXxpjmrWAMigI2jHkljG1CU@U1Y0v8nRJu5Ts@2MBw0jsMw8/nFO0f "Python 3 – Try It Online") Takes the initial height of the sand pile as a command line argument. This stores and calculates only the bottom right quarter of the grid which can be used to construct the full output in the end. Some inspiration is taken from @alephalpha's comment and a better bound of the required space is taken from [their answer](https://codegolf.stackexchange.com/a/242477/64121). Many thanks to @att, who found a way to keep the values on the grid at all times below 255 (or below 7 to be exact), which allows using bytes as a integer datatype, which speeds up both memory access and computations. In rough terms this is achieved by recursively spreading higher powers of four first, then adding the lower ones. The timing on TIO is a bit strange, 450000 finishes in 15 seconds, but 500000 times out. Local timings: ``` $ time python3 run.py 1300000 > /dev/null python3 run.py 1300000 > /dev/null 59.94s user 0.32s system 99% cpu 1:00.33 total ``` [Answer] # Charcoal + tr, score circa 2560 on TIO ``` python3 /opt/charcoal/charcoal.py -c UB0FN«≔⟦Eχ⁰⟧υFυ«J⊟κ⊟κ≔﹪⊕ΣKK⁴θIθ¿¬θF⁴«M✳⁺³⊗λ⊞υ⟦ⅉⅈ -i $1 | tr -d \\n ``` [Try it online!](https://tio.run/##S0oszvj/v6CyJCM/z1hBP7@gRD85I7EoOT8xB87QK6hU0E1WeL9n6/s9iwze71n2fs@6Q6sfdU55NB/IXHq@/VHjhkfzl59vBUqdbz20@v2eVY@65p/bBSE6p7zfCeRPPbf4/R6g1OpHjVvO7Xi/Z@W5HYf2H1oDYi4DCoF0rX00Z/Ojxl2HNj/qmn5u96OueedbgTY8au181NqhoJupoGKoUKNQUqSgm6IQE5P3//9/MzMA "Bash – Try It Online") Verbose Charcoal source: [Try it online!](https://tio.run/##NY2xasMwEIZn@SlEphOo4NCQpVPbLA04CNKhJWRQbCURlnWOpMtS8uyuKlM4cZz4/@9rrzq0qN007U16021/CUi@g0W9EC/VGQOHDz9S2tFwMgGE4D8Ve43RXjwcGj3Cspa8FkfJKedZKVAJsS0N4yeCwhF6Ifm8/0L//QY7cpj5bTCD8cl0sKcBlDF9FuXKKr9baahgfYJ3HRPcZoY9c9hhOXmxrmYra/BuYGODaZNFD8pRhGfJN0gnlw0ukwuAKYpXIMkP35A9XyCO5f9R5XlM03o9Pd3dLw "Charcoal – Try It Online") Takes `i` as input and outputs a square grid. Explanation: Simply increments the centre cell `i` times, then when it overflows adds each orthogonally adjacent cell to the list of cells to increment. [Answer] # [Python 3](https://docs.python.org/3/), score circa 5120 on TIO ``` import collections import sys import numpy c = collections.Counter() c[0j] = int(sys.argv[1]) [(m, n)] = c.most_common(1) while n > 3: c[m] = n % 4 for d in [1, 1j, -1, -1j]: c[m + d] += n // 4 [(m, n)] = c.most_common(1) l = max(int(m.real) for m in c) print(end = ''.join(str(c[i + j * 1j]) for j in range(-l, l + 1) for i in range(-l, l + 1))) ``` [Try it online!](https://tio.run/##fY7BTgMhEIbvPMVcTMFuqaRNDyZ68THIxmxYbCHMsGGpuk@PsDXGg/FAAvN9P/9MS75EOpTicIopg4khWJNdpJl9j@bl50pXnBZm4Om3J1/ilbJNXDCjH3xfqaPMa0wO6fyuVS@Y5tgBicaMxDjnVxMRI3El2MfFBQsEz3B4ZABGY9MI7uBYn28xwVg/BK06UL6DnWrH981dbdjC2MO2Rfb7NfNfW6hDHD55WxFlskMQawe2DiPYlBqxNFZvs5E@OuJzTtxoV4s83Ncl@lvEt0ga6Gz5LnQQKlc34v4iQpRSTqcv "Python 3 – Try It Online") Explanation: Keeps track of the sand using a Counter indexed by Gaussian integers. The centre cell starts off with the program's argument and then the cell with the largest value gets overflowed each time until no cell has a value greater than 3. [Answer] # [C (gcc)](https://gcc.gnu.org/), 3282 bytes Not optimized at all, but it should still be quite fast, because it's C. ``` #include <stdio.h> #include <stdlib.h> #include <math.h> #define swap(a, b, TYPE) \ do { \ TYPE tmp = a; \ a = b; \ b = tmp; \ } while (0) long long int* data_a = NULL; long long int* data_b = NULL; int size_x = 3; int size_y = 3; void copy_a_into_b(int size) { for (int i = 0; i < size; i++) { data_b[i] = data_a[i]; } } void larger() { int new_size_x = size_x + 2; int new_size_y = size_y + 2; copy_a_into_b(size_x * size_y); data_a = (long long int*)realloc( data_a, new_size_x * new_size_y * sizeof(long long int)); for (int i = 0; i < new_size_x * new_size_y; i++) { data_a[i] = 0; } int offset_x = 1; int offset_y = 1; for (int i = 0; i < size_x; i++) { for (int j = 0; j < size_y; j++) { data_a[(i + offset_x) * new_size_y + j + offset_y] = data_b[i * size_y + j]; } } data_b = (long long int*)realloc( data_b, new_size_x * new_size_y * sizeof(long long int)); copy_a_into_b(new_size_x * new_size_y); size_x = new_size_x; size_y = new_size_y; } int is_stable() { for (int i = 0; i < size_x; i++) { for (int j = 0; j < size_y; j++) { if (data_a[i * size_y + j] > 3) { return 0; } } } return 1; } void zero(long long int* target, int size) { for (int i = 0; i < size; i++) { target[i] = 0; } } void add_a_into_b(int size) { for (int i = 0; i < size; i++) { data_b[i] += data_a[i]; } } void update() { zero(data_b, size_x * size_y); int should_grow = 0; for (int i = 0; i < size_x; i++) { for (int j = 0; j < size_y; j++) { if (data_a[i * size_y + j] > 3) { if (i <= 1 || j <= 1 || i >= size_x - 2 || j >= size_y - 2) { should_grow = 1; } int quarter = data_a[i * size_y + j] >> 2; data_a[i * size_y + j] = data_a[i * size_y + j] & 3; // data_b[i * size_y + j] = 0; data_b[(i - 1) * size_y + j] += quarter; data_b[(i + 1) * size_y + j] += quarter; data_b[i * size_y + j - 1] += quarter; data_b[i * size_y + j + 1] += quarter; } } } add_a_into_b(size_x * size_y); swap(data_a, data_b, long long int*); copy_a_into_b(size_x * size_y); if (should_grow) { larger(); } } int main(int argc, char* argv[]) { int height = atoi(argv[1]); int size = (int)sqrt((double)height) + 1; if (size % 2 == 0) { size++; } size_x = size; size_y = size; data_a = (long long int*)malloc(sizeof(long long int) * size_x * size_y); data_b = (long long int*)malloc(sizeof(long long int) * size_x * size_y); zero(data_a, size_x * size_y); zero(data_b, size_x * size_y); copy_a_into_b(size_x * size_y); int x = size / 2; int y = size / 2; data_a[x * size_y + y] = height; int q = 0; while (!is_stable()) { q++; update(); } for (int i = 0; i < size_x * size_y; i++) { printf("%d", (int)data_a[i]); } fflush(stdout); return 0; } ``` TIO link: [Try it online!](https://tio.run/##zVdLc5swEL7zK7bJpAPGbuzkSOJbb5m2h/bQSTOMeBllsGWDiENS//W6K0AgYUgybg7VwZZ3v12t9in7k4Xv7/endOUneRDCVcYDyj7Fc0MjJdTTaUvCY0ExToMwoqsQsi1Zm2QM3hi@//z22YJfBuAKGDxDd1UssQQU@HIN10AcnUWQ5jm9Uh6yUMjpsHawjWkSgjm1DCNhqwWUH3TFRxAQTlyh8suPmxunl@s1XKRBRp9C9xFJl8rvovptPDAagM/WhUtcZDLXMyXGgufSmIilUBIpykwd/Loq@bizbQkqPVSefUvvEFdZiXunupCxq89KSLoIU1PKCb2rcOs2RtYbGy6cQ0AhAUUL0I2vxUc1zKowjc9M3V1WGpIkYb6p3wGDr9g0Us@vFLNIV2TV5/S5akBTv/dI5b2p9Jr0AIuiLOSlg2ZOl1q01KFYuY8H5zXQ@wp6L6Fo2r0OVcwzKXpeWmPpvrFRR8Ms8B5Gt1xkhjTxETJ1irQX3rUx894cM@/YmOn5M6CjxjZZ2sIURqEyCkekfBmKzM048ZLQfK2i/j1KNAJTJpLuZJjDZRctVhryPF3JjNMD0Q1JjZ05TTU/hSnrxAe4qHA@hqP7SKWgUwnyRBIE79qq7Bd6Vb5GVhu28rIy2fobTWlQzPIkcBcp27YX@J9CLiTwfGwa8Pu3UF/vKMyb/juBi4o5bzoukvq0lemvXXnmHIB2h0bgBTc5SXmYKuOie4G57PI9ragLHtTyUUy6rpLz84Fu1Masp3Oh3yYwszoSmEP1VV4StI8S1K0Tpx8jZr8k1l/sWqH1Z3v5UpITUxZGp1u/fUiLtFQSSc01@WhQClTkz5LQVVkpyPbH4MckHYn9w@2d@r6IQ7qIuXiYcUbNkj@7UwsWrRBzRgyFbJNy0wxYjv3aqgQt4T3FRIE@w/K4xkRRjRQM21Ynt/ao6QyKljT4OFlWc653eEnn9T91vPfS1rY8Mn4VMtgV3xR9DIR0FZyrr7/igFrX@aOa4@K9UUe6Fd20xVw/qD8o01gN3kZGTizZ99VYDjfwxoqDTr5OUSAyT86Ck3GVXs2o0XVHSZ7FJv47YTmvOe1c3u33@9lUrD9@lJBFtp8ky/3ka0Qy/hc "C (gcc) – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 284 bytes, score ~150000 on TIO Fixed a bug thanks to @att. ``` With[{size = 2 Ceiling[Sqrt@#/2.7] + 3}, WriteString[$Output, ##] & @@ FixedPoint[ BitAnd[#, 3] + With[{q = BitShiftRight[#, 2]}, Sum[RotateLeft[q, d], {d, {1, -1, size, -size}}]] &, CenterArray[#, size^2]]] &@ToExpression[$ScriptCommandLine[[2]]] ``` [Try it online!](https://tio.run/##NY5Na8MwDIbv@xWClF3mfTRl7DRIF7ZTYaMe9GA8MLXaCGY7cRToVvLbMzvbBEIfPHpfOcMNOsO0N9O0I27UuadvhEcooUb6JH9UsotcFbflzYOGK1iNAi4AYBeJUXLMxOJ14HZgAUWh4RKqaibghU5o3wJ5VvMMT8Rrb1UhYJWlfpdJavbtkmkCZEMH3tKx4cyV@s9uDjk4tQ1sGDd4YNUJsFrA2aZcCrhOmZ9PXS7jqNMz/9c1esa4jtF8Zd0MfJQ6E9V7eD61EfueglcLuY/Uch2cM95uyKNSmZumaXl/l@IH "Wolfram Language (Mathematica) – Try It Online") [Answer] # [MATLAB](https://www.gnu.org/software/octave/), 310 bytes, score ~2^16-2^17 ``` function piles = sand(h) piles = h; while any(piles > 3,'all') piles = conv2([0 1/4 0; 1/4 0 1/4; 0 1/4 0],4*floor(piles/4)) + conv2([0 0 0; 0 1 0; 0 0 0],mod(piles,4).*(piles>=4)) + conv2([0 0 0; 0 1 0; 0 0 0],piles.*(piles<4)); piles(all(~piles,2),:) = []; piles(:,all(~piles,1)) = []; end ``` [Try it online!](https://tio.run/##hY7LDoMgEEX3fMXsBEsqWlZS/RHjgviIJhSaam266a9TlBLddRbzuDl3ck0zy6Wztn/qZh6NhvuougkKmKRu8UAQCsIgEHoN7gCp39irJVxoJJWKCAJXWwt8Y/SS4YpBmnBgwo@1C/hpNeVxr4x5@G8JJwROu4@tLof6wVb@ZlrPUk7OsV/L4r9vA4Ph6nixR8UuP/74rxmhOXHZq/oI5PSApCQAnW6t/QI "Octave – Try It Online") I did this on a relatively average PC, so I don't know if better hardware could get this done any faster. something on the order of 2^16 was the best I could get in less than a minute, 2^17 took almost 2 minutes. [Answer] # [C (clang)](http://clang.llvm.org/), score 1376256 ``` #include <stdio.h> #include <stdlib.h> #include <string.h> #define u8 unsigned char int main(int argc, char* argv[]) { if (argc != 2) { fprintf(stderr, "Please provide i (and only i)\n"); return -1; } int height = atoi(argv[1]); if (height < 1) { fprintf(stderr, "Please, only positive numbers\n"); return -1; } int maxm = 0; while (height >> ++maxm){}; // Whatever... These just have to be big enough int size = height + 1000; int width = height + 1000; u8* tmpbuf = malloc(width); u8* mainbuf = calloc(size, 1); // Null ptrs are zero, deal with it u8** bufptrs = calloc(__builtin_popcount(height) - 1, sizeof(u8*)); int bufptrsidx = 0; mainbuf[0] = 1; int index = height; int rcount = 0; int grandmax = 1; while (1) { int stuff_happening = 1; int lmax = grandmax; while (stuff_happening) { stuff_happening = 0; int p = 0; int l = 0; int next_lmax = 0; while (l < lmax) { int lw = l + 1; u8 contmask = 0; u8 carry = 0; for (int j = 0; j < lw; j++) { contmask|= mainbuf[p+j]; u8 k = mainbuf[p+j] / 4; mainbuf[p+j]%= 4; mainbuf[p+j]+= carry; if (j + 1 == lw) { mainbuf[p+j]+= carry; } else { mainbuf[p+1-lw+j]+= k; mainbuf[p+j]+= tmpbuf[j]; } if (j + 2 == lw) { mainbuf[p+1-lw+j]+= k; if (j == 0) { mainbuf[p+1-lw+j]+= 2*k; } } tmpbuf[j] = k; if (j > 0) { mainbuf[p+j-1]+= k; } if (j == 1) { mainbuf[p+j-1]+= k; } carry = k; } p+= lw; l+= 1; if (contmask >= 4) { if (l == lmax) { lmax+= 1; } next_lmax = l + 1; stuff_happening|= 1; } } if (lmax > grandmax) {grandmax = lmax;} lmax = next_lmax; } int tmp = index & 1; if (index/= 2) { // Double until largets power of two reached // If this is needed in the future, make a copy if (tmp) { bufptrs[bufptrsidx++] = memcpy(malloc(width), mainbuf, width); } for (int i = 0;i<size;++i){mainbuf[i]*= 2;} } else if (rcount < bufptrsidx) { // When that is done, add old arrays starting from 1 for (int i = 0;i<size;++i){mainbuf[i]+= bufptrs[rcount][i];} rcount+= 1; } else { // Exit break; } } for (int i = 0;i < bufptrsidx;i++){free(bufptrs[i]);} free(bufptrs); free(tmpbuf); for (int y = 0; y < grandmax*2-1; y++) { int yp = grandmax - y - 1; if (yp < 0){yp*=-1;} for (int x = 0; x < grandmax*2-1; x++) { int xp = grandmax - x - 1; if (xp < 0){xp*=-1;} int r,c; if (xp > yp) { r = xp; c = yp; } else { r = yp; c = xp; } int ro = r*(r+1)/2; u8 ch = mainbuf[ro+c]; putchar(ch + 48); } // Newlines for pretty print //putchar(10); } free(mainbuf); } ``` [Try it online!](https://tio.run/##tVfPb@s2DL73r@DesMGOkyYu3qFAfpy2wy7DDgPeoQsKxZZjtbJkyHKTvL787RllyY7tOFl7mFHAKUnx@0hJJB1NIk7E9nT6mYmIlzGFRaFjJu/T1V1HxNmmL1NMbCtZTBMmKJSPUIqCbQWNIUqJurtjQkNGmPDMD6K20bhSjMzvt6e1D@93gA9LwDNa@GkJD7XQPEmOGDrxEJ8qNYYvf3FKCgq5km8MSTBcJ2KQgh@A@f@IL/68WauoLpWASWhFR4uEPFLKtqmGJRAtmVcxCdduoWHi9AsIP0BlbMFzWTDN3iiIMttQVfwHlYZLRvYZMplZxS5lnDYEVisIAmPgvx/ndsl0Ct9SoukbVff39/B3SjEZL2WBQREE1xI2FDZsC1TIcps2MAX7ThHGOQ4gnM0cpNHuWKzTS3WlLx9HoLN8UyZokBHOZeRV9i48ozc7bA0ia2Dgxpi@M@s/S84h16rAnafwnSo5hpgSjtgIzXTtawToqLJrnD0/b0rGNRPPucwjWQrtEuTDBMJxFZtMPFzs@@eYnBsW7216K4Uj@jRbozCcn7eBiZjumwycvagK77xBRrZVeORwW6yL1rZ1jkuVdV0myXNK8pwKvCrnBbUBt25qj2el89hz0PZvnkv/s3nHwGDkw2I@LBZ0r58drZ7aceJ4MYxBn0zjeIdLuTlE8ws9FohICp2R4vXSf21AlDoMaxOpoKokL5UeX0hlh@8gGGJjnhrux7LZ/Dx4Wc8HjRH9FbqGMIWvw8Ztq1@WH7EKlja4YUtTeV5M2mCJ@dtdC@hzTo9AOVaIj7gKJ3xn/b3OP4psC8PTtXwebwb68JlAP8TOekavs1tOrzl@GN1wffxEgE1W4Cpby3R1m2gr2ZPwRui30ozJCP8/jPquDiy6XJAHZrsvLXmwHKoVhn9TLFZ4wa6FYQx5dZauVKUGCPXDWNcjbNfDK0VtoBL/GETpInT/q4IwMKumG2AorVZjlPPuGkeroXhGPHa6DJ5HNLMt7tdOC0pMOUXx1I5dplH/JssNlnnseowDx@GI6gKnmx1VIBPQO4nDDIlSGneo4MI/UJuyAvBPUBrjCMgESigkJQ4/OA5k5JUCwYqcHy5CR4pDO@ea@NO5mQeBuVUZzaL84HXGkXF9lsfQnk@G0910ElZ1ErYwQ8Q8CJj/Xt8Ith5hVlopd7XU0HVjwaI1Zbj0fUupiZpok4dYCoybxDig8hgHH0UOBR4VorTp1omSGYSfp4VHuM6L5bFGYe9oWEX3sNe9wND8fe9GribTuKuv/QPk5tQ@q07cc4bN9z1RlHo1K4bDtHXQFrv9qES2QtbjYePftn18LZpLMHrAoRkO3QZf2eatwQkHwYMZBrtHG00WWGHfD/loiV7OGWoA7ZSDrz7g/nKiqOx7oPsuaA28d8D7PnAzVo6jwVUrDGvoHiiE3eeXFSVC@aEnv9ry1YBx7aTvfICyRDM18lQQ@tOHrrWZ2tLW4KRkEPVGgrzU5sPPQ7sAvj76Q7XKfCbQHccvyaLaohw/mzR@WpnvrpZR7Sqc@e0vu@pgOQaoOJ5OJ/yM@Rc "C (clang) – Try It Online") This answer demonstrates some techniques that may be useful. First, we only do the calculations on one eighth of the grid, since there is eight-fold symmetry. The second technique we use is the doubling trick (first noticed by @att). If we wish to calculate the resulting sand pile for input \$2i\$, we can first calculate the resulting sand pile for input \$i\$, double every value, and iterate until we are done. Similarily, we can calculate the resulting sandpile for input \$a+b\$ by calculating \$a\$ and \$b\$ individually and then just adding them together and iterating. Combined with the observation that the maximum height of a sandpile doesn't increase (assuming you do "global" iterations), we can use just a byte to store the height of a sandpile, because the height of a sandpile never exceeds seven. Currently the two main easiest ways to make this answer faster are multi-threading and use of SSE instructions. For scoring, I used this manually unrolled version, since it was a bit faster when compiled with clang: ``` #include <stdio.h> #include <stdlib.h> #include <string.h> #define u8 unsigned char int main(int argc, char* argv[]) { if (argc != 2) { fprintf(stderr, "Please provide i (and only i)\n"); return -1; } int height = atoi(argv[1]); if (height < 1) { fprintf(stderr, "Please, only positive numbers\n"); return -1; } int maxm = 0; while (height >> ++maxm){}; // Whatever... These just have to be big enough int size = height + 1000; int width = height + 1000; u8* tmpbuf = malloc(width); u8* mainbuf = calloc(size, 1); // Null ptrs are zero, deal with it u8** bufptrs = calloc(__builtin_popcount(height) - 1, sizeof(u8*)); int bufptrsidx = 0; mainbuf[0] = 1; int index = height; int rcount = 0; int grandmax = 1; while (1) { int stuff_happening = 1; int lmax = grandmax; while (stuff_happening) { stuff_happening = 0; int p = 0; int l = 0; int next_lmax = 0; while (l < lmax && l < 4) { int lw = l + 1; u8 contmask = 0; u8 carry = 0; for (int j = 0; j < lw; j++) { contmask|= mainbuf[p+j]; u8 k = mainbuf[p+j] / 4; mainbuf[p+j]%= 4; mainbuf[p+j]+= carry; if (j + 1 == lw) { mainbuf[p+j]+= carry; } else { mainbuf[p+1-lw+j]+= k; mainbuf[p+j]+= tmpbuf[j]; } if (j + 2 == lw) { mainbuf[p+1-lw+j]+= k; if (j == 0) { mainbuf[p+1-lw+j]+= 2*k; } } tmpbuf[j] = k; if (j > 0) { mainbuf[p+j-1]+= k; } if (j == 1) { mainbuf[p+j-1]+= k; } carry = k; } p+= lw; l+= 1; if (contmask >= 4) { if (l == lmax) { lmax+= 1; } next_lmax = l + 1; stuff_happening|= 1; } } while (l < lmax && l >= 4) { // At least 5 int lw = l + 1; u8 contmask = 0; u8 carry = 0; for (int j = 0; j < 2; j++) { contmask|= mainbuf[p+j]; u8 k = mainbuf[p+j] / 4; mainbuf[p+j]%= 4; mainbuf[p+j]+= carry; if (j + 1 == lw) { mainbuf[p+j]+= carry; } else { mainbuf[p+1-lw+j]+= k; mainbuf[p+j]+= tmpbuf[j]; } if (j + 2 == lw) { mainbuf[p+1-lw+j]+= k; if (j == 0) { mainbuf[p+1-lw+j]+= 2*k; } } tmpbuf[j] = k; if (j > 0) { mainbuf[p+j-1]+= k; } if (j == 1) { mainbuf[p+j-1]+= k; } carry = k; } for (int j = 2; j < lw - 2; j++) { contmask|= mainbuf[p+j]; u8 k = mainbuf[p+j] / 4; mainbuf[p+j]%= 4; mainbuf[p+j]+= carry; if (j + 1 == lw) { mainbuf[p+j]+= carry; } else { mainbuf[p+1-lw+j]+= k; mainbuf[p+j]+= tmpbuf[j]; } if (j + 2 == lw) { mainbuf[p+1-lw+j]+= k; if (j == 0) { mainbuf[p+1-lw+j]+= 2*k; } } tmpbuf[j] = k; if (j > 0) { mainbuf[p+j-1]+= k; } if (j == 1) { mainbuf[p+j-1]+= k; } carry = k; } for (int j = lw - 2; j < lw; j++) { contmask|= mainbuf[p+j]; u8 k = mainbuf[p+j] / 4; mainbuf[p+j]%= 4; mainbuf[p+j]+= carry; if (j + 1 == lw) { mainbuf[p+j]+= carry; } else { mainbuf[p+1-lw+j]+= k; mainbuf[p+j]+= tmpbuf[j]; } if (j + 2 == lw) { mainbuf[p+1-lw+j]+= k; if (j == 0) { mainbuf[p+1-lw+j]+= 2*k; } } tmpbuf[j] = k; if (j > 0) { mainbuf[p+j-1]+= k; } if (j == 1) { mainbuf[p+j-1]+= k; } carry = k; } p+= lw; l+= 1; if (contmask >= 4) { if (l == lmax) { lmax+= 1; } next_lmax = l + 1; stuff_happening|= 1; } } if (lmax > grandmax) {grandmax = lmax;} lmax = next_lmax; } int tmp = index & 1; if (index/= 2) { // Double until largets power of two reached // If this is needed in the future, make a copy if (tmp) { bufptrs[bufptrsidx++] = memcpy(malloc(width), mainbuf, width); } for (int i = 0;i<size;++i){mainbuf[i]*= 2;} } else if (rcount < bufptrsidx) { // When that is done, add old arrays starting from 1 for (int i = 0;i<size;++i){mainbuf[i]+= bufptrs[rcount][i];} rcount+= 1; } else { // Exit break; } } for (int i = 0;i < bufptrsidx;i++){free(bufptrs[i]);} free(bufptrs); free(tmpbuf); for (int y = 0; y < grandmax*2-1; y++) { int yp = grandmax - y - 1; if (yp < 0){yp*=-1;} for (int x = 0; x < grandmax*2-1; x++) { int xp = grandmax - x - 1; if (xp < 0){xp*=-1;} int r,c; if (xp > yp) { r = xp; c = yp; } else { r = yp; c = xp; } int ro = r*(r+1)/2; u8 ch = mainbuf[ro+c]; putchar(ch + 48); } // Newlines for pretty print //putchar(10); } free(mainbuf); } ``` ``` [Answer] # [Java (JDK)](http://jdk.java.net/), 1418 bytes ``` import java.util.Scanner; import java.lang.Math; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int middleSize = scanner.nextInt(); int sideLength = 2 * (int) (Math.sqrt(middleSize) / 2) + 3; int[][] grid = new int[sideLength][sideLength]; int[][] tempGrid = new int[sideLength][sideLength]; for (int i = 0; i < sideLength; i++) { for (int j = 0; j < sideLength; j++) { if (i == (int) (sideLength / 2) && j == (int) (sideLength / 2)) { grid[i][j] = middleSize; tempGrid[i][j] = middleSize; } else { grid[i][j] = 0; tempGrid[i][j] = 0; } } } while (true) { for (int i = 0; i < sideLength; i++) { for (int j = 0; j < sideLength; j++) { tempGrid[i][j] = grid[i][j] % 4; if (i > 0) tempGrid[i][j] += (int) grid[i-1][j] / 4; if (i < sideLength - 1) tempGrid[i][j] += (int) grid[i+1][j] / 4; if (j > 0) tempGrid[i][j] += (int) grid[i][j-1] / 4; if (j < sideLength - 1) tempGrid[i][j] += (int) grid[i][j+1] / 4; } } boolean stable = true; for (int i = 0; i < sideLength; i++) { for (int j = 0; j < sideLength; j++) { grid[i][j] = tempGrid[i][j]; if (grid[i][j] > 3) stable = false; } } if (stable) break; } for (int i = 0; i < sideLength; i++) { for (int j = 0; j < sideLength; j++) { System.out.print(grid[i][j]); } } } } ``` [Try it online!](https://tio.run/##tVRNc4IwEL37K/bSDpSR@tGeqL12OlNPHh0OUSKGhmCTWPsx/na7gSAR61QPZRgCu@893m4@MvJOulnyutuxfFVIDRkGwrVmPJzMiRBURh03w4lIwzHRy6izWs84m8OcE6VgTJiA7w7YoNJE4/BesARyTHkTLZlIpzEQmSrfIMHqg7LjCATd1FFv8qk0zUMm/AixTGjIWZJwOmFfFKGWFAr6oZ@F9vYoxRL6QkWql4gawA14GPXBM55D9Sa11@j4cAsDHwIYGnYlMI3RZCrRd@XHhBrN2H2PHAZ6XT2dyULaopClMWBI6EU4PDjO8TsIqiY1yKxCZi1ktkcCWyASRqO6ZKcVZZ3X10bkVLpWKYufsniaxfjHpllRla0LPYnYAuWK/irWO6VhE9uOfWxNjzZLxil4Wq5puxd/du2Sth3bcUxfwZ01XXX3EXp@mxDULa143X4ZvW0x3f9DF/p/yQS/yWTnGMAYejhiXmoAY4Ers58dmBUFp0SYXT7jZjeaOYr@cYYOVtGha6dEB/UIQ7@xtyC4IttFGEaF8GEmKXmN6oX3L5vTnmfFWocrPAq147Y8u@y6x3u72/Xve3j9AA "Java (JDK) – Try It Online") I somehow managed to put together a functional answer to this challenge, in spite of my very limited Java knowledge. (So limited in fact that I had to look up the names of libraries which I knew about but whose names had been forgotten due to me barely ever using Java.) It seems to work correctly, and the score is likely around 150000 because it took 55 seconds with an input of 150000. Builds a grid with a size roughly the same as the input ("size" meaning area) and keeps tossing the sand around until no more sand can be tossed around. Not the most optimized, but 150000 is not a bad score. *BTW, I chose Java because it's a compiled language and usually compiled languages are faster.* [Answer] # [Rust](https://www.rust-lang.org/), 1903 bytes, score ~1000000 on TIO, ~3500000 on my computer A simple port of [@ovs's Python answer](https://codegolf.stackexchange.com/a/242442/9288), without @att's improvement. It is fast on TIO, but much slower than @ovs's answer on my computer. Now only compute one eighth of the grid, and borrow the trick in [@Aiden's answer](https://codegolf.stackexchange.com/a/242695/9288): first bring the maximum value to less than 256, and then switch to `u8`. ``` macro_rules! sandpile { ($grid:ident, $size:ident, $boundary:expr) => {{ let mut quater = $grid.clone(); while $grid.iter().any(|&x| x > $boundary) { quater.clear(); quater.extend($grid.iter().map(|&x| x >> 2)); $grid.iter_mut().for_each(|x| *x &= 3); $grid[0] += 4 * quater[1]; for i in 1..$size - 1 { for j in i + 1..$size - 1 { $grid[i * $size + j] += quater[(i + 1) * $size + j] + quater[i * $size + (j + 1)] + quater[(i - 1) * $size + j] + quater[i * $size + (j - 1)]; } $grid[i] += 2 * quater[i + $size] + quater[i + 1] + quater[i - 1]; $grid[i * $size + i] += 2 * quater[(i - 1) * $size + i] + 2 * quater[i * $size + (i + 1)]; } } $grid }}; } fn sandpile32(n: u32, size: usize) -> Vec<u32> { let mut grid = vec![0; size * size]; grid[0] = n; sandpile!(grid, size, 255) } fn sandpile8(grid32: &[u32], size: usize) -> Vec<u8> { let mut grid = Vec::with_capacity(grid32.len()); grid.extend(grid32.iter().map(|&x| x as u8)); sandpile!(grid, size, 3) } fn print(grid: &[u8], size: usize) { let isize = size as isize; for i in 1 - isize..isize { for j in 1 - isize..isize { let (i, j) = (i.abs() as usize, j.abs() as usize); let index = std::cmp::min(i, j) * size + std::cmp::max(i, j); print!("{}", grid[index]); } } } fn main() { let n = std::env::args() .nth(1) .and_then(|x| x.parse::<u32>().ok()) .expect("Give me a number"); let size = ((n as f32).sqrt() / 2.7) as usize + 3; let grid32 = sandpile32(n, size); let grid = sandpile8(&grid32, size); print(&grid, size); } ``` [Try it online!](https://tio.run/##pVVNc9owEL3zKxYmw8gB3GA3U0YpXHvsrReGYRRbBFEsHNlOnCb89ZKV5G9I25nqgqXdfe/taleoLElPp4gF6rBW2Z4nfUiYDGOx5/DaA1zk6kGJkIqQy3QMV4n4xavN/SGTIVMvlOexcmC@gFcbpNeepxBlKTxmLOUK5mCA3GB/kJw4d5Xf81aTWaNAT@K4TL6Qt2H@BjksahYHanC9LDACcqaagA0bz1MuQ9ICj1hcgS/AczCyFVo7r1E@BmwOas1ZsCVvGHSdw3AOfofOxCxvVjCaw2e4LuiX01XbDZFAgJAwdV1TSZjAtJNV6bfTfgJGf/Ot6QUSW88R7IyUQgYxME7LfBFHr1EZ1YQjO4PwD1HINflvLo3QKZ1ex17vg8xNtl5deJ2wwVs1OTCF1h5pLrCcF9PAX0yiQXmeuA5ri2okaa@kQ3/snX8ZOWZ3PN71sAQbWY2o7xFJIfO9MZi5hEz/ODBZwA8efEXDouiYchg1GI7iEw/6y5s7E4WqTKWslLKR5yCLuSjJ@kTbLNMYvNtbp6NmZhx8j8JwidSrD0TNPtCERkqfRbpdByxmgUhfCjx3zyVxnFpfOdaF@XyuWQLZrBrsywn4pfxYCZkakxE@6@quxQpTrrmtGnKYvZVVTzZ2gTl3XeteT2w11X/wKamIGMMOX1T8cNl9QhyTk1W@65x03iKjVIY810rTkNIgiimNhCww7XVj@zWMLLfGNpKpTJ8MXo@DsW0Mg7tquNk@PRaljBiyNCsmSw1cPlHK1APqrmJdmW7JtLHHe1qnW7xs/dDmbsxUwik1bYz3e/iJTVA7418OD1Iy@CaeOER4HyCz6J6rQaFO0xf3RYjUxdr4nuMmjwrfdPgEnvulLiFWw6/DbF9p6Y05s13htL0aPjMytHEtR9tcw7rx8Px4Op2mN2b9DjZ79pCcJt/fAQ "Rust – Try It Online") --- # [Rust](https://www.rust-lang.org/), 2044 bytes, score ~750000 on TIO, ~6500000 on my computer This one is a port of [@Polichinelle's C answer](https://codegolf.stackexchange.com/a/242612/9288), and borrow the trick in [@Aiden's answer](https://codegolf.stackexchange.com/a/242695/9288): first bring the maximum value to less than 256, and then switch to `u8`. It is slow on TIO. But it become much faster when compiled with `-Ctarget-cpu=native` on my computer. ``` macro_rules! sandpile { ($grid:ident, $size:ident, $boundary:expr) => {{ let mut buf = $grid.clone(); while $grid.iter().any(|&x| x > $boundary) { std::mem::swap(&mut $grid, &mut buf); $grid[0] = (buf[0] & 3) + (buf[1] & !3); for i in 1..$size - 1 { $grid[i] = (buf[i] & 3) + 2 * (buf[i + $size] >> 2) + (buf[i + 1] >> 2) + (buf[i - 1] >> 2); } for i in $size..$size * ($size - 1) { $grid[i] = (buf[i] & 3) + (buf[i + 1] >> 2) + (buf[i + $size] >> 2) + (buf[i - 1] >> 2) + (buf[i - $size] >> 2); } for i in 1..$size - 1 { $grid[i * $size] = (buf[i * $size] & 3) + 2 * (buf[i * $size + 1] >> 2) + (buf[(i + 1) * $size] >> 2) + (buf[(i - 1) * $size] >> 2); } for i in 1..$size { $grid[i * $size - 1] = 0; } } $grid }}; } fn sandpile32(n: u32, size: usize) -> Vec<u32> { let mut grid = vec![0; size * size]; grid[0] = n; sandpile!(grid, size, 255) } fn sandpile8(grid32: &[u32], size: usize) -> Vec<u8> { let mut grid = Vec::with_capacity(grid32.len()); grid.extend(grid32.iter().map(|&x| x as u8)); sandpile!(grid, size, 3) } fn print(grid: &[u8], size: usize) { let isize = size as isize; for i in 1 - isize..isize { for j in 1 - isize..isize { let (i, j) = (i.abs() as usize, j.abs() as usize); print!("{}", grid[i * size + j]); } } } fn main() { let n = std::env::args() .nth(1) .and_then(|x| x.parse::<u32>().ok()) .expect("Give me a number"); let size = ((n as f32).sqrt() / 2.7) as usize + 3; let grid32 = sandpile32(n, size); let grid = sandpile8(&grid32, size); print(&grid, size); } ``` [Try it online!](https://tio.run/##pVVNc9owEL3nVyxMxiM12AV7MmFM4dJDj731kmEYYUQQxcK15YQ04a/XXUn@AGdonKkutqy3u@/trtZpnqmiiFmU7hdpvuNZDzImV4nYcXi5Alzk@iEVq1CsuFQDuM7Eb15vlvtcrlj6HPJDklKYzuDFGum14wriXMEyX8MUjBcv2u0lJ3RSg542OpI9FIqnhHpMPpNX5/AKB5g1ISg0nvXK1CoMYx6HYfbEEuLoSMbNAJwyKoY5MzHH98M5siF4rN8cCCjc2O1Ib3tB22q9T0GAkDDyPKMeXBi1yDTeRe1dWO9vcHrdgA@fShhujNs5zGbgX8LX2FEnnFvjJmfA4wVthkGlD5nVQul/K/0g849kw@2cjVOf3TLSrdqYq9J1lYvmS7fql/CO@SEmkbQJ0sXCfWvxwRy8q9@WYgrDtuO3b8bS7I7HyRWGXst65AQ@kSHkgT8AM2cg1w8K7gx@8OgLHsxKLtVw0c4w7iOPevfDCZT9a5RaKs2dl@XFroL1iB0XGjwA//aWttiMDSDwQ3DuMfT8AqnxBU54GIZPQm0WEUtYJNRz6c/bcUkobfh5/KC4XFXH5RyMcayVc5BlkI8p/aeAoKKfpEIqc2SIj9u8G7LCpGtqs4YxzN7SanoASyvsdBCtXtCY7TuYKhQRA9hSfUuEx5YZoUaTZb5tfWl1p9HTI/2XY38AdduVl2Y7P0HbJjuWeYiZwDSfyJVaqv5tcPkYhix9wKC1rSfVhoxO9pjkhdpgpV51CbyEpRkPQ9ODWJz9T6xgA8b/H48U6X8TjxxiTCbIPF7ytF@y0@HLZBMitdJ14FMv@5UqpPgZfO@u0Y@ygsbMNoWmfnJJbEnpOeoEMyaOtTsD2s5wmq7B78eiKO5uh7j@ROsde8gK93vhflWYHq7cKMmnkilU9Rc "Rust – Try It Online") [Answer] # [F# 6](https://fsharp.org/), 3521 bytes, score ~ 33000 on my computer Requires .NET 6. TIO doesn't support it, so I can't provide a sample run of it. The algorithm is total junk, but I wanted to try and implement it in as pure a functional way as possible - no `mutable` keyword, all value/record types, no changing items in collections. Turns out that it's not a good idea, but it is a *lot* of fun. ``` namespace Sand open FSharp.Collections.ParallelSeq type Coordinates = { Row: int Column: int } type Adjustment = { Coordinates: Coordinates Value: int } module SandPile = let maxHeight = 4 let applyAdjustments (adjustments: Adjustment seq) = adjustments |> PSeq.groupBy (fun x -> x.Coordinates) |> PSeq.map (fun (_, changes) -> changes |> Seq.reduce (fun total next -> { total with Value = total.Value + next.Value }) ) let calculateDeltas (adjustments: Adjustment array) = adjustments |> PSeq.collect (fun originalAdjustment -> if originalAdjustment.Value >= maxHeight then let distribution = originalAdjustment.Value / maxHeight seq { yield { originalAdjustment with Value = (originalAdjustment.Value % maxHeight) } yield { Adjustment.Coordinates = { originalAdjustment.Coordinates with Row = originalAdjustment.Coordinates.Row - 1 }; Value = distribution } yield { Adjustment.Coordinates = { originalAdjustment.Coordinates with Column = originalAdjustment.Coordinates.Column - 1 }; Value = distribution } yield { Adjustment.Coordinates = { originalAdjustment.Coordinates with Row = originalAdjustment.Coordinates.Row + 1 }; Value = distribution } yield { Adjustment.Coordinates = { originalAdjustment.Coordinates with Column = originalAdjustment.Coordinates.Column + 1 }; Value = distribution } } else [ originalAdjustment ] ) |> PSeq.filter (fun adjustment -> adjustment.Value <> 0) let isStable (adjustments: Adjustment array) = adjustments |> PSeq.tryFind (fun x -> x.Value >= maxHeight) |> Option.isNone let printOut (adjustments: Adjustment array) = let rows = adjustments |> PSeq.map (fun x -> x.Coordinates.Row) |> Seq.sort |> Seq.toArray let columns = adjustments |> PSeq.map (fun x -> x.Coordinates.Column) |> Seq.sort |> Seq.toArray let lowRow = rows |> Array.head let highRow = rows |> Array.last let lowColumn = columns |> Array.head let highColumn = columns |> Array.last let gridDict = adjustments |> PSeq.groupBy (fun x -> x.Coordinates.Row, x.Coordinates.Column) |> Map.ofSeq seq { for row = lowRow to highRow do for column = lowColumn to highColumn do yield Map.tryFind (row, column) gridDict |> Option.map (fun x -> x |> Seq.head |> fun x -> x.Value |> string) |> Option.defaultValue "0" } |> String.concat " " |> printf "%s" let loop = (calculateDeltas >> applyAdjustments >> PSeq.toArray) module Program = [<EntryPoint>] let main argv = argv[0] |> int |> fun initialSeed -> { Adjustment.Coordinates = { Row = 0; Column = 0 }; Value = initialSeed } |> Array.singleton |> Seq.unfold (fun surface -> let isStable = SandPile.isStable surface if isStable then None else let newSurface = SandPile.loop surface Some (newSurface, newSurface) ) |> Seq.last |> SandPile.printOut 0 ``` [Answer] # [Rust](https://www.rust-lang.org/), 10667 bytes Significantly faster than my last answer, and comfortably handles 4000000 on my machine. The idea is still the same as my previous answer, by first reducing everything to under 255 and then operating on bytes. I dropped nalgebra and platform intrinsics this time and added a few nightly features, mainly for portable SIMD types. Additionally, only a quarter of the grid is calculated now. Building this one with just rustc instead of cargo is fine but ensure `-Ctarget-cpu=native` is passed to rustc. ``` #![feature(portable_simd)] #![feature(allocator_api)] #![feature(array_chunks)] use std::mem; use std::ops::{Index, IndexMut}; use std::ptr::NonNull; use std::{env::args, fmt::Debug, simd::*}; fn main() { let arg = args() .nth(1) .expect("No input provided") .trim() .parse::<u32>() .expect("Not parsable as an unsigned integer"); let mut sandpile = Mat::sandpile(arg); sandpile.topple::<255>(); let mut sandpile = sandpile.map(|n| n as u8); sandpile.topple::<3>(); sandpile.trim(); sandpile.unquarter(); sandpile.print(); } fn max_size(n: u32) -> usize { ((n as f64).sqrt() / 2.7).ceil() as usize + 3 } #[derive(Clone)] struct Mat<T> { data: Vec<T, AlignedAlloc<SIMD_ALIGN>>, row_size: usize, } impl<T> Index<(usize, usize)> for Mat<T> { type Output = T; fn index(&self, (x, y): (usize, usize)) -> &T { &self.data[x + y * self.row_size] } } impl<T> IndexMut<(usize, usize)> for Mat<T> { fn index_mut(&mut self, (x, y): (usize, usize)) -> &mut T { &mut self.data[x + y * self.row_size] } } impl<T> Mat<T> { fn row(&self, y: usize) -> &[T] { &self.data[y * self.row_size..(y + 1) * self.row_size] } fn row_mut(&mut self, y: usize) -> &mut [T] { &mut self.data[y * self.row_size..(y + 1) * self.row_size] } fn row_count(&self) -> usize { self.data.len() / self.row_size } fn row_windows(&self) -> RowWindows<'_, T> { RowWindows { data: &self.data, row_size: self.row_size, } } fn map<U: Default + Copy, F: Fn(T) -> U>(self, f: F) -> Mat<U> { let mut buf = Vec::with_capacity_in(self.data.len(), AlignedAlloc); buf.extend(self.data.into_iter().map(f)); let mut mat = Mat { data: buf, row_size: self.row_size, }; mat.pad(); mat } } macro_rules! make_topple { ($int:ty, $simd:ty, $lanes:literal) => { fn topple<const MAX: $int>(&mut self) { if !self.data.iter().any(|&x| x > MAX) { return; } let mut buf = self.clone(); let four = <$simd>::splat(4); loop { let mut max = <$simd>::splat(0); for ((up, center, down), buf) in self .row_windows() .zip(buf.data.chunks_exact_mut(self.row_size).skip(1)) { for (((((cur, left), right), up), down), buf) in center[1..] .array_chunks::<$lanes>() .zip(center.array_chunks::<$lanes>()) .zip(center[2..].array_chunks::<$lanes>()) .zip(up[1..].array_chunks::<$lanes>()) .zip(down[1..].array_chunks::<$lanes>()) .zip(buf[1..].array_chunks_mut::<$lanes>()) { let cur = <$simd>::from_array(*cur); let left = <$simd>::from_array(*left); let right = <$simd>::from_array(*right); let up = <$simd>::from_array(*up); let down = <$simd>::from_array(*down); let sum = left / four + right / four + up / four + down / four + cur % four; max = max.simd_max(sum); *buf = sum.to_array(); } } self.row(2)[1..] .array_chunks::<$lanes>() .zip(buf.row_mut(1)[1..].array_chunks_mut::<$lanes>()) .for_each(|(cur, buf)| { let cur = <$simd>::from_array(*cur); let tmp = <$simd>::from_array(*buf); let sum = tmp + cur / four; max = max.simd_max(sum); *buf = sum.to_array(); }); let col_max = (1..self.row_count() - 1) .map(|y| { buf[(1, y)] += self[(2, y)] / 4; buf[(1, y)] }) .max() .unwrap(); mem::swap(self, &mut buf); let max = max.reduce_max().max(col_max); if max <= MAX { break; } } } #[allow(dead_code)] // u32 version is unused fn trim(&mut self) { let mut num_rows = 0; for row in self.data.chunks_exact(self.row_size).skip(1) { if row.iter().all(|&x| x == 0) { break; } num_rows += 1; } let mut buf = Vec::with_capacity_in(num_rows * num_rows, AlignedAlloc); buf.extend(std::iter::repeat(0).take(num_rows * num_rows)); let mut new = Mat { data: buf, row_size: num_rows, }; for x in 0..num_rows { for y in 0..num_rows { new[(x, y)] = self[(x + 1, y + 1)]; } } *self = new; } }; } impl<T> Mat<T> where T: Debug + Default, { fn print(&mut self) { self.data.truncate(self.row_size * self.row_size); for n in self.data.iter() { print!("{n:?}"); } } } impl<T: Default + Copy> Mat<T> { fn pad(&mut self) { let round_mask = SIMD_ALIGN / mem::align_of::<T>() - 1; let padding = SIMD_ALIGN / mem::align_of::<T>(); let size = self.row_size; let aligned_size = if size & round_mask == 0 { size } else { (size & !round_mask) + padding }; let mut data = Vec::with_capacity_in( aligned_size * (aligned_size + padding), AlignedAlloc::<SIMD_ALIGN>, ); data.extend( std::iter::repeat_with::<T, _>(Default::default) .take(aligned_size * (aligned_size + padding)), ); let mut new = Mat { data, row_size: aligned_size + padding, }; for x in 0..self.row_size { for y in 0..self.row_count() { new[(x, y)] = self[(x, y)]; } } *self = new; } fn unquarter(&mut self) { let mut new = Mat { data: Vec::with_capacity_in( self.row_size * self.row_count() * 4, AlignedAlloc::<SIMD_ALIGN>, ), row_size: self.row_size * 2 - 1, }; new.data.extend( std::iter::repeat_with::<T, _>(Default::default) .take((self.row_size * 2 - 1).pow(2) - 1 + self.row_size * 2 - 1), ); let size = new.row_size; for x in 0..self.row_size { for y in 0..self.row_count() { new[((size - 1) / 2 + x, (size - 1) / 2 + y)] = self[(x, y)]; } } for x in 0..self.row_size { for y in 0..self.row_count() { new[(x, y)] = self[(self.row_size - 1 - x, self.row_count() - 1 - y)]; } } for x in 0..self.row_size { for y in 0..self.row_count() { new[((size - 1) / 2 + x, y)] = self[(x, self.row_count() - 1 - y)]; } } for x in 0..self.row_size { for y in 0..self.row_count() { new[(x, (size - 1) / 2 + y)] = self[(self.row_size - 1 - x, y)]; } } *self = new; } } impl Mat<u32> { fn sandpile(n: u32) -> Self { let size = max_size(n); let mut data = Vec::with_capacity_in(size * (size), AlignedAlloc::<SIMD_ALIGN>); data.extend(std::iter::repeat(0).take(size * size)); let mut mat = Mat { data, row_size: size, }; mat[(1, 1)] = n; mat.pad(); mat } make_topple!(u32, u32x8, 8); } impl Mat<u8> { make_topple!(u8, u8x32, 32); } pub struct RowWindows<'a, T> { data: &'a [T], row_size: usize, } impl<'a, T> Iterator for RowWindows<'a, T> { type Item = (&'a [T], &'a [T], &'a [T]); fn next(&mut self) -> Option<Self::Item> { if self.data.len() < self.row_size * 3 { return None; } let (first, rest) = self.data.split_at(self.row_size); self.data = rest; let (second, rest) = rest.split_at(self.row_size); let (third, _rest) = rest.split_at(self.row_size); Some((first, second, third)) } } impl<T: Debug> Debug for Mat<T> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { for i in 0..self.data.len() / self.row_size { for j in 0..self.row_size { write!(f, "{:?} ", self.data[i * self.row_size + j])?; } writeln!(f)?; } Ok(()) } } const SIMD_ALIGN: usize = mem::align_of::<u32x8>(); #[derive(Clone, Copy, Debug)] struct AlignedAlloc<const ALIGN: usize>; use std::alloc::{AllocError, Allocator, Global, Layout}; unsafe impl<const ALIGN: usize> Allocator for AlignedAlloc<ALIGN> { fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> { Global.allocate(layout.align_to(ALIGN).unwrap()) } unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) { Global.deallocate(ptr, layout.align_to(ALIGN).unwrap()) } fn allocate_zeroed(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> { Global.allocate_zeroed(layout.align_to(ALIGN).unwrap()) } unsafe fn grow( &self, ptr: NonNull<u8>, old_layout: Layout, new_layout: Layout, ) -> Result<NonNull<[u8]>, AllocError> { Global.grow( ptr, old_layout.align_to(ALIGN).unwrap(), new_layout.align_to(ALIGN).unwrap(), ) } unsafe fn grow_zeroed( &self, ptr: NonNull<u8>, old_layout: Layout, new_layout: Layout, ) -> Result<NonNull<[u8]>, AllocError> { Global.grow_zeroed( ptr, old_layout.align_to(ALIGN).unwrap(), new_layout.align_to(ALIGN).unwrap(), ) } unsafe fn shrink( &self, ptr: NonNull<u8>, old_layout: Layout, new_layout: Layout, ) -> Result<NonNull<[u8]>, AllocError> { Global.shrink( ptr, old_layout.align_to(ALIGN).unwrap(), new_layout.align_to(ALIGN).unwrap(), ) } } ``` [Playground](https://play.rust-lang.org/?version=nightly&mode=debug&edition=2021&gist=cf91931df67694bdeb6163bca46e7db8) I tried parallelizing this with rayon but the code got lost somewhere in synchronization primitives and took roughly ten times longer. I might return to this later and see if I can do better. This code is fully cross-platform, and in fact, I cross-compiled it for 32-bit arm at one point. Because this uses several nightly features it likely won't work on the latest nightly forever. If it doesn't, here's my current `rustc --version`: ``` rustc 1.66.0-nightly (57f097ea2 2022-10-01) ``` ]
[Question] [ Multi-dimensional chess is an extension of normal chess that is played on an 8x8x8x8... "board". In normal 2D chess, a knight's move is a movement by a vector of \$ \begin{bmatrix} \pm 2 \\ \pm 1 \end{bmatrix} \$ or \$ \begin{bmatrix} \pm 1 \\ \pm 2 \end{bmatrix} \$, as long as it doesn't cause the knight to go outside the \$ 8 \$ by \$ 8 \$ bounds. In \$ N \$-dimensional chess, a knight's move is a vector of $$ \begin{bmatrix} \vdots \\ \pm 2 \\ \vdots \\ \pm 1 \\ \vdots \end{bmatrix} \text{or} \begin{bmatrix} \vdots \\ \pm 1 \\ \vdots \\ \pm 2 \\ \vdots \end{bmatrix} $$ where \$ \begin{bmatrix} \vdots \end{bmatrix} \$ is any number of \$ 0 \$s (such that the vectors are \$ N \$ in rank), again as long as it doesn't go outside the \$ 8^N \$ bounds. ## Task Given a coordinate vector of length \$ N \$, output all possible coordinate vectors that are a knight's move away on an unobstructed \$ 8^N \$ chess board. You should assume the input vector will always be at least 2-dimensional (i.e., \$ N \ge 2 \$), and always within the bounds of the board. ## Test-cases Using 1-indexed coordinates (0-indexed available [here](https://tio.run/##dVRLdsMwCNznFD6A@14RkuAuftl33XbVy6dWAI9Q02w8IGbET/n5@ng8vj83etPt/U0ej4P2Te8bfkfZt37ft4P3Te63o@5bS@dt@OPcvjy@zb/d@QXf6v566p2fM7JckoecOsNhEhNkhwKop6bDmmBFQAWt@dUNUJ@QnZYhIYCikil5QEGpnCAhgM5ah9A4v2qdCBVw1OyQAfuT3Dw2Q0IAuQJ5erzCgoDobHExg4R@17n1t9ELnddjyPThuKpUF1cfdn9C8UaKe21sY5vIch6XXtvGqMPKD8sg44yQbwkhxllUaGHBM4kCq4BHcXvwCP2nuH10wnZQr8X1NVFn9tUiWJqs9lwkTbOYeIyt1mTZUCSdKTZyslpYnCzCpnUsRU0W4QZ7PZIi4waJrCsiFbtMLyxKkYRnLVCxajlZZFtYbdlG7LWFsiYkqSNtdfBKqZHO9MJ1dfSVIuufgqQirkz76iiJov4EZwdjtFNitmnZ0VOmGvPIjr5SsoNTLRod60ljKk6j67JSFM@c/3WUlVKSaPRDp1H@cfBKYfzn95S6jTI7Wkr9GnZPGq8cZaWUJDplWtNb0Gk/@uooydGThvhL@AU "Zsh – Try It Online")) ``` Input Output [1, 8] [2, 6], [3, 7] [4, 5] [5, 7], [3, 7], [3, 3], [5, 3], [6, 6], [2, 6], [2, 4], [6, 4] [6, 5, 2] [7, 7, 2], [5, 7, 2], [5, 3, 2], [7, 3, 2], [8, 6, 2], [4, 6, 2], [4, 4, 2], [8, 4, 2], [7, 5, 4], [5, 5, 4], [8, 5, 3], [4, 5, 3], [4, 5, 1], [8, 5, 1], [6, 6, 4], [6, 4, 4], [6, 7, 3], [6, 3, 3], [6, 3, 1], [6, 7, 1] [5, 1, 3] [6, 3, 3], [4, 3, 3], [7, 2, 3], [3, 2, 3], [6, 1, 5], [4, 1, 5], [4, 1, 1], [6, 1, 1], [7, 1, 4], [3, 1, 4], [3, 1, 2], [7, 1, 2], [5, 2, 5], [5, 2, 1], [5, 3, 4], [5, 3, 2] [8, 8, 8] [7, 6, 8], [6, 7, 8], [7, 8, 6], [6, 8, 7], [8, 7, 6], [8, 6, 7] [1, 1, 1, 1] [2, 3, 1, 1], [3, 2, 1, 1], [2, 1, 3, 1], [3, 1, 2, 1], [2, 1, 1, 3], [3, 1, 1, 2], [1, 2, 3, 1], [1, 3, 2, 1], [1, 2, 1, 3], [1, 3, 1, 2], [1, 1, 2, 3], [1, 1, 3, 2] [7, 3, 8, 2] [8, 5, 8, 2], [6, 5, 8, 2], [6, 1, 8, 2], [8, 1, 8, 2], [5, 4, 8, 2], [5, 2, 8, 2], [6, 3, 6, 2], [8, 3, 6, 2], [5, 3, 7, 2], [8, 3, 8, 4], [6, 3, 8, 4], [5, 3, 8, 3], [5, 3, 8, 1], [7, 2, 6, 2], [7, 4, 6, 2], [7, 1, 7, 2], [7, 5, 7, 2], [7, 4, 8, 4], [7, 2, 8, 4], [7, 5, 8, 3], [7, 1, 8, 3], [7, 1, 8, 1], [7, 5, 8, 1], [7, 3, 7, 4], [7, 3, 6, 3], [7, 3, 6, 1] [8, 4, 7, 8, 4] [7, 6, 7, 8, 4], [7, 2, 7, 8, 4], [6, 5, 7, 8, 4], [6, 3, 7, 8, 4], [7, 4, 5, 8, 4], [6, 4, 8, 8, 4], [6, 4, 6, 8, 4], [7, 4, 7, 6, 4], [6, 4, 7, 7, 4], [7, 4, 7, 8, 6], [7, 4, 7, 8, 2], [6, 4, 7, 8, 5], [6, 4, 7, 8, 3], [8, 3, 5, 8, 4], [8, 5, 5, 8, 4], [8, 6, 8, 8, 4], [8, 2, 8, 8, 4], [8, 2, 6, 8, 4], [8, 6, 6, 8, 4], [8, 3, 7, 6, 4], [8, 5, 7, 6, 4], [8, 2, 7, 7, 4], [8, 6, 7, 7, 4], [8, 5, 7, 8, 6], [8, 3, 7, 8, 6], [8, 3, 7, 8, 2], [8, 5, 7, 8, 2], [8, 6, 7, 8, 5], [8, 2, 7, 8, 5], [8, 2, 7, 8, 3], [8, 6, 7, 8, 3], [8, 4, 6, 6, 4], [8, 4, 8, 6, 4], [8, 4, 5, 7, 4], [8, 4, 8, 8, 6], [8, 4, 6, 8, 6], [8, 4, 6, 8, 2], [8, 4, 8, 8, 2], [8, 4, 5, 8, 5], [8, 4, 5, 8, 3], [8, 4, 7, 7, 6], [8, 4, 7, 7, 2], [8, 4, 7, 6, 5], [8, 4, 7, 6, 3] [3, 4, 2, 5, 7, 3, 2, 2, 4, 3, 6, 4, 5, 7, 5, 8, 8, 8, 7, 8, 3, 7, 5, 8, 7] https://gist.github.com/pxeger/8a44daec42d34d9507d7ca6431e2a9fc ``` ## Rules * Your code does not need to practically handle very high \$ N \$, but it must work in theory for all \$ N \$ * You may use 0-indexed (\$ [0, 7] \$) or 1-indexed (\$ [1, 8] \$) input and output, but this must be consistent * You may optionally take a second input, an integer \$ N \$, which is the length of the vector and the number of dimensions * You may use any [standard I/O method](https://codegolf.meta.stackexchange.com/q/2447) * [Standard loopholes](https://codegolf.meta.stackexchange.com/q/1061) are forbidden * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins [Answer] # [Ruby](https://www.ruby-lang.org/), ~~93~~ 81 bytes ``` ->a,n{w=*1..8;w.product(*[w]*~-n).select{|r|r.zip(a).sum{|x,y|(x-y).abs*8/3}==7}} ``` [Try it online!](https://tio.run/##LYjRCsIgFEDf@4oenVyNtdaEsB8RH9zaIKglbuJM7ddNopfDOcfY3ueJZ3JVMAfHcU0puziqzetmhxVh4ST@kLmiy/gYhzVEEw193zVSZdlniBv4iDbiK6r6BbNDkzjvUsp6PwlRA5NwlLtfnKEtDs0/GZygg0IJrcxf "Ruby – Try It Online") ### Quickly explained - old version Generate all possible positions as vectors of N numbers between 1 and 8, then check the differences between each vector and the starting position, the sorted array of absolute values of the components must be `[<bunch of 0s ...>, 1, 2]` ### And then: (Thanks [@dingledooper](https://codegolf.stackexchange.com/users/88546/dingledooper)): If we multiply the differences by 8 and divide them by 3, the vector becomes `[<bunch of 0s>, 2, 5]` and its sum is unequivocally 7, no other combination of numbers can produce the same sum, so we can simplify the check a lot and shave off 12 bytes. [Answer] # [JavaScript (V8)](https://v8.dev/), 114 bytes 0-indexed. Prints all valid vectors. ``` v=>v.map((x,i)=>v.map((y,j)=>j>i&&(g=n=>n--&&g(n,(V=[...v],x-(V[i]=n&7))**2+(y-(V[j]=n>>3))**2-5||print(V)))(64))) ``` [Try it online!](https://tio.run/##XY/BioMwFEX3fsVbDOGlkwS0tgol2c0vuJFARUYn0oliS2hp@@3OU8HFQEjuOe8mkK4K1bUe3XCTIZ8aPQVtgvqtBsS7cHyDh@gIOuMYw1Z7bbyUjLXoBRa6VEoFK@4Si9JZ7VnG@W6XfOJjNh0ZY/aLkofXaxidv2HBOcdjSvt0KiOAMhaQWzGnVMBhTUdKApIVKFFnv0JO7e1CvEzmtXJGtWWebGV6M1tUaiMbqaYfv6r6BwNoA0@gA9aP@ll4kBDzE9S9v/aXb3XpWzyXH8/wtmfSDYZ/Q8I3n/4A "JavaScript (V8) – Try It Online") ### How? Let \$v\$ be the input vector of length \$N\$. For each pair \$(i,j),\:0\le i<j<N\$ and each value \$n\in[0\dots 63]\$, we compute: $$X=n \bmod 8\\ Y=\lfloor n/8 \rfloor\\ V=[v\_0,\:\dots,v\_{i-1},\:X,\:v\_{i+1},\:\dots,v\_{j-1},\:Y,\:v\_{j+1},\:\dots,\:v\_{N-1}]$$ We print the output vector \$V\$ if: $$(v\_i-X)^2+(v\_j-Y)^2=5$$ [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes ``` 8RṗLạṢ¹ƇؽƑʋƇ ``` [Try it online!](https://tio.run/##ASsA1P9qZWxsef//OFLhuZdM4bqh4bmiwrnGh8OYwr3GkcqLxof///9bNiw1LDJd "Jelly – Try It Online") ## Explanation ``` 8RṗLạṢ¹ƇؽƑʋƇ Main monadic link 8R Range from 1 to 8 ṗ To the Cartesian power of L the length of the input Ƈ Filter by ʋ ( ạ Absolute difference with the input Ṣ Sort Ƈ Filter by ¹ identity ؽƑ Equals [1,2]? ʋ ) ``` It's a shame that `ṗ` doesn't automatically convert the left argument to a range, like other list functions… [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 12 bytes Takes `N` as first input and the current position as second input. ``` 8LIãʒα0K{2LQ ``` [Try it online!](https://tio.run/##yy9OTMpM/f/fwsfz8OJTk85tNPCuNvIJ/P/fmCvaQkcBhGIB "05AB1E – Try It Online") ``` 8L # push the range [1 .. 8] Iã # all N-tuples of integers in [1 .. 8] ʒ # only keep those for which ... α # ... the element-wise absolute difference to the current position 0K # ... without zeros { # ... sorted ascending 2L # ... and [1, 2] Q # ... are equal ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 47 bytes ``` Array[#~Norm~1#.#&@*List,0#+8,1-#]~Position~15& ``` [Try it online!](https://tio.run/##JYo9C4MwGIR3/8YLDu1ZGk1qlha7lyJ0FIcglWZIhJiliPnrqanccM99GOU/b6O8HlQcr/HunPp2FJ6TM4HRifLm8NCzx5mOEqygPrTTrL2ebGAij63T1ndU3MaG@jy8BmXDki0MckW2cIhkFwiUCQQYqgQScn8w/JWwRrW15T5z1Fvga7bGHw "Wolfram Language (Mathematica) – Try It Online") Returns a list of coordinates. The product of the taxicab distance and the squared Euclidean distance can only be 15 on knight's moves. ``` Array[ &@*List,0#+8 ] for the whole chessboard ,1-# offset so the input location is 0: #~Norm~1 taxicab distance times #.# squared Euclidean distance ~Position~15& find 15s ``` --- ### [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~64~~ 55 bytes ``` x/.Solve[0<x<9&&!#-2<x<#+2,x∈#~Sphere~√5,Integers]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7v0JfLzg/pyw12sCmwsZSTU1RWdcIyFLWNtKpeNTRoVwXXJCRWpRa96hjlqmOZ15JanpqUXGs2v@Aosy8kmhlXbs0B@VYtbrg5MS8umquakMdi1odrmoTHVMQZaZjqmMEYpjqGOoYgxgWOhYQFYY6YAhimusYA0WNINImOuZAjkktV@1/AA "Wolfram Language (Mathematica) – Try It Online") Returns a list of coordinates. `x/.` could be omitted (-3 bytes) for a slightly uglier output format (a list of `{x->*coord*}`s). ``` x/.Solve[ , ,Integers]& integer coordinates which are x∈#~Sphere~√5 √5 away from the input, 0<x<9 inside the chess board, &&!#-2<x<#+2 and 2 away on some dimension. ``` [Answer] # [Python](https://www.python.org), 115 bytes ``` lambda p,N:[i for i in[[*map(int,f"{j:0{N}o}")]for j in range(8**N)]if~-sum((k-l)**(2*N)for k,l in zip(i,p))==4**N] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=dVbNjtMwEL6ivgBXK6ekSpF_YntVqa_Q095CD0WbQHbTJGqzSLBaXoTLSgjeCZ4Gu7YzHrP04pnP843nz42__5q-zJ_G4eVHu3v_83FuNze_L_3x9OHuSKZyv6070o5n0pFuqOv16Tjl3TCXbfZ0v6VP--fxOSsO1uDeGJDzcfjY5Dfr9b44dO23zeXxlOcPm75Yr3NuQGv4UPbW9GtnPJVTUex2lbE_uKP_vHl7u8uyrKYl0QcCv5qVRB5KUvOSqMOqFiWp0H5l8bDvVm7Xyq_S8xmswuPC-DOLsWSLy1oZPxZwLiKRe1GBqI1PLwokCjAQQKv80RWI-ipyT8MiBQMaMomCB1FBqhyJFAyoydU6svtLrhFBgGhz9iIHUV7JlbfFIgUD6j1QHx5PRQYGobLMO3MihXqLuPQrWwsdj4d1Iy2wZKm9c-2bLa-i8oVUHnVts9NEXcz20GXaOOTh0g-aEznsUYiXBUcc9kKGzizwnAsGGgMeDacHHoX603C6rYSbQb0Mrh8T7Zky1ShoGmnVdZA06kXE4zDVGmmuKQrtaZjISKuCxpEW5oSBT3WNRaIRUej2KGQZTlAhagGWGmaZvqJRZBk0l5EATQLPadRNoXDDZm2XKVRpQApVpEoBnlJECCe64ToFZEpR6Z-CQkkskcoUYIii_RWMAQ6tjQJzk4YBiSLVoR8YkCkFAxzlokPFJPIRJadD1VVK0XDN-X8BllIYchrqoaNW_gPwlBIAEfITAOgUqFDoS7Ml8vEawFIKQ06jSAW6CzqaD5kCDAES-VD-Jpjv87vL1Hdz3w3NJS9WK_tdn-1X_Xa7Mn9DXTmSHbFvhebzsS_brp-bc943Qzk7Yp4RkhVFYY2ns3lQmKfAZTzPzV0-mgeBF1uDGlLeGcvCvQ9eXtz6Fw) #### Old [Python](https://www.python.org), 116 bytes ``` lambda p,N:[i for i in[[*map(int,f"{j:0{N}o}")]for j in range(8**N)]if 4**N+1==sum((k-l)**(2*N)for k,l in zip(i,p))] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=dVbNjtMwEL6ivgBXK6ekZJF_YntVqa_Q095CD0WbQHbTJGqzSLDaJ-FSCcE7wdNg13bGY5Ze_M3n-cYz9rjx91_T1_nzOFx-tNsPP5_m9ub299wfjh_vD2Qqd5u6I-14Ih3phrpeHw9T3g1z2WbPDxv6vHsZX7Jibx0ejAM5HYZPTX67Xu-KfdeSyoB3bLs9Px3z_PGmL9brnJs56_9Y9lbxrTMBy6ko9m7tP2_e3m2zLKtpSfSewK9mJZH7ktS8JGq_qkVJKjRfWT7Mu5HbsfKj9HoGo_C8MPHMYDzZErJWJo4lXIgIcg8VQG1ieigQFOAgQFb5pSuA-gq5l2FIwYGGSqLkASoolSNIwYGaWm0gO7_UGgkEQFuzhxygvIor74shBQfqI1CfHk8hA4ews8wHc5DCfot461d2L3TcHjaMtMRSpfbBtT9seYXKb6TyrDs2203U5WwXXbqNQx2u_GA5yGGOQr4sBOIwFyp0bkHnQjCwGOhoWD3oKOw_DavbnXA9qJfG9W2ivVKmFgVLI6u6NpJGZxHpOHS1RpY7FIXmNHRkZFXB4sgKfcIgprrmIlGLKHR7FPIMK6iQtQBPDb1MX7Eo8gyWq0iAJUHnLOq6ULhms75LF6o0IYV2pEoJnkpESCe64TolZCpR6Z-CQkUsmcqUYEii_RWMCQ5HGyXmOg0TEmWqw3lgQqYSTHBUiw47JlGMqDgddl2lEg3XnP-XYKmEoaBhP3R0lP8QPJUEQoT6BBA6JSqU-nLYEsV4jWCphKGgUaYC3QUd9YdMCYYIiWIofxPM9_n9eeq7ue-G5pwXq5X9os_2e363WZm_oa4cyZbYx0Lz5dCXbdfPzSnvm6GcnTDPCMmKorDO08m8KMwj4Dye5uY-HwvzYHCwNawR5Z3xLNz74HJx418) Takes the 0-based list and its length as inputs. Uses octal representation as a poor-man's `itertools.product` to generate all squares and then filters out the bad ones using a high-p Minkowski distance. [Answer] # Haskell, ~~132~~ ~~119~~ 118 Bytes ``` e!(o:x)=[z|o==0,z<-[e:x,-e:x]]++map(o:)(e!x) _!_=[] k p=filter(all(`elem`[0..7]))$zipWith(+)p<$>([0<$p]>>=(1!)>>=(2!)) ``` [Try it Online!](https://tio.run/##HYrLCoMwEADvfkUCOezig7Q9COL6Gz2EoDlsMRg1WA8i/ffUloGZy4zuPXEIKbGEtTmQzPlZiXRxtqXh5ijKS9bm@eziNSCwPDDrZU/GZpOI9PJh5w1cCDBw4Hkwuqpqi6hOH59@HyHH2KoOjG5VtF1HcJP4y10iptn5RZCIm192ocRk6kL/edj0BQ) -13 bytes thanks to Wheat Wizard -1 byte thanks to pxeger [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~134~~ 119 bytes ``` lambda v,d:[i for i in product(*[range(8)]*d)if[1,2]==sorted(abs(x-y)for x,y in zip(i,v)if x-y)] from itertools import* ``` [Try it online!](https://tio.run/##dctBDoIwEIXhPafosiVjAlSUaDhJ7aJYqpMAbUol4OWxxMSVZHbzvd8t4WkHXjm/mvq2dqpvtCIT6ItAYqwnSHAgzlv9ugeaCq@GR0srJlPN0IgcClnXo/Wh1VQ1I50PC9uyGZYtfKOjCFOckk1kYrztCYbWB2u7kWDvYpuuzuMQqKEig0xCwdj1@2HJTzgcd6SEI@QS@D87Q7xd43CKziWUjK0f "Python 3.8 (pre-release) – Try It Online") * Generate all possible coordinates. * Then, compute he list of the absolute difference between our vector and the coordinate. * Remove all `0` in this list an verify that the remaining contains exactly `1` and `2` Thanks to @ovs for -15 bytes [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 66 bytes ``` a->forvec(b=[[1,8]|i<-a],norml2(a-b)==5&&normlp(a-b)==2&&print(b)) ``` [Try it online!](https://tio.run/##LYxNCoMwEIWvMrgICSQLU63SNu57BsliLLUIVodgC4XePZ2kwsD7mY9HGCbzoDiCi2i6cQ3v@00Oru9L3frvdDHo9bKG52wlmkE5VwuRM@3ZCkFhWjY5KBWRaP5IBNPBvyyuC722ExQaUJ1hlKg0pHFoPZtKQ530yKrBJsvK30OyLVM7WOY2XUoNA/lnd4x3mlxU3qv4Aw "Pari/GP – Try It Online") For input \$a\$, find all coordinate vectors \$b\$ on the chessboard such that the \$l\_2\$ distance ([Euclidean distance](https://en.wikipedia.org/wiki/Euclidean_distance)) between \$a\$ and \$b\$ is \$\sqrt{5}\$, and the \$l\_\infty\$ distance ([Chebyshev distance](https://en.wikipedia.org/wiki/Chebyshev_distance)) between \$a\$ and \$b\$ is \$2\$. [Answer] # [JavaScript (V8)](https://v8.dev/), 96 bytes ``` a=>{for(i=a>>2;++i<a*4;)/[09]/.test(i)|[...a].map((n,j)=>s+=((i+'')[j]-n)**2,s=0)^s^5||print(i)} ``` [Try it online!](https://tio.run/##bc5LDoIwEIDhvadg15ZHEWyliuUiiEljxJRgIZSwEc@OrUZNTGf1L77JTCMmoc@D7MdoYkvNF8GLe90NUHJRFGkeBPIgfJKjuFzvqhiPFz1CieYSYywqfBM9hCpsEC90wCGUAQCobKpIId9PQ83X6KRPdJ77QSq7@FjOndJde8Ftd4XgqBK2Byj3PK@GIGEmV3@A0B8g1AG2NH0LA0w7BE02X2HaIRhjX2HaIRIzL2L/NOMg2YalH2LbdYdkjFhj79g2uTwB "JavaScript (V8) – Try It Online") Input is a string, for example, `[6, 5, 2]` is inputed as `"652"`. Output each answer per line to stdout. --- # [Python 2](https://docs.python.org/2/), 104 bytes ``` lambda a:[i for i in range(a/4,a*4)if sum((q in'90')*6+(int(p)-int(q))**2for p,q in zip(`a`,`i*10`))==5] ``` [Try it online!](https://tio.run/##TcxLDsIgEIDhvaeYXRnEaClUNOlJ1ASMoiSKWHWhl6/gg3Y2kz/fQHjejxfPO9usu5M5b3cGzHLlwF5acOA8tMYf9sRMBTNUoLNwe5wJuUYqFrMCaT0mzt9JwElaV0RKeXocWLqBlwtEG820o@VMIzaN3HShTbelYlAsCwZxbCzE0ReEHIKQGWrJs9hUWWRZDSRWFqXUQGJlKeP8yX4q07xSvKdU/X9irsTP7LcQuzc "Python 2 – Try It Online") Input `[6, 5, 2]` as an integer `652`. Output list of integers. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 46 bytes ``` FLθFLθF⊗¬⁼ικF²⊞υEθ⁺ν⁺×⁼ξι⊗∨λ±¹×⁼ξκ∨μ±¹IΦυ⁼ι﹪ι⁸ ``` [Try it online!](https://tio.run/##bY67CsJAEEV7v2LKWRgLrQRLH5XGFHYhxZqsyeIka/Yh/v2aYIIoDgPz4NzLLWppCyM5xquxgAfVVr7GTgj4e29NuLAqMTEed12Q7FAT3ISYgKWANLgaA8FR3rEjSDk4bMd51o1yk/JJoAXB5HmyyASJqqRXuBgsCX75W//rueab62s9S61uPW6k87jX7JUdMnwyHk0Z2Azb6i2IMcsWBGPneZw/@AU "Charcoal – Try It Online") Link is to verbose version of code. 0-indexed. Outputs using Charcoal's default array output of each element on its own line with separate results double-spaced from each other. Explanation: ``` FLθ ``` Loop over the possible `N` dimensions for the 2-step part of the knight's move. ``` FLθ ``` Loop over the possible `N` dimensions for the 1-step part of the knight's move. ``` F⊗¬⁼ικ ``` Loop over 2-step moves toward or away from the origin, but only if different dimensions were chosen. ``` F² ``` Loop over 1-step moves toward or away from the origin. ``` ⊞υEθ⁺ν⁺×⁼ξι⊗∨λ±¹×⁼ξκ∨μ±¹ ``` Calculate the coordinates of the move. ``` IΦυ⁼ι﹪ι⁸ ``` Output only those coordinates which stay within the bounds of the board. [Answer] # [Python 3](https://docs.python.org/3/), 230 210 bytes ``` v=lambda n:sum([[m.insert(i,0)or m for m in v(n-1)]for i in range(n)],[])if n>2else[[i,j//i]for i in[-2,-1,1,2]for j in[2,-2]] k=lambda*l:[p for p in[[*map(sum,zip(l,m))]for m in v(len(l))]if min(p)>0<9>max(p)] ``` Thanks to Jakque for the -20 [Try it online!](https://tio.run/##TY5BjsIwDEX3nCJLG7lAAzMaEPQiURYZERhDYqK2IODyJS0MYmP5Pdv6Trf27yTzrrtsgou/W6dk1ZwjGBMnLI2vW2Ca4alWUe2GyqIuIEWJtmfuuXay9yBoyVjknZJK@9B4Y5gO0ym/F02hqSipJD2oQ6@y0daOjq/4cViZNCSlfmrG0SXID9GdEwSK@Ix9vRG8QMgqZ0YWSFjN1ssqumtubZdqlhaOUJL6QRz944LU1wd@ZySlP0zGfDJH7B4 "Python 3 – Try It Online") Python 3 solution that does not use any external modules and calculates the possible moves by recursivly generating all possible moves before filtering out impossible ones. The original (non-golfed) code that I wrote: ``` def moves(n): # n is the number of dimensions out = [] if n > 2: # If higher then base dimension for i in range(n): # For each possible location that the 0 can be temp = [move for move in moves(n-1)] # Generate the previous dimension's move list for j in range(len(temp)): # Insert 0 in the same location for all moves temp[j].insert(i, 0) out.extend(temp) # Add to master move list else: # Base case, if n = 2 out = [[1, 2], [1, -2], [-1, 2], [-1, -2], [2, 1], [2, -1], [-2, 1], [-2, -1]] return out def knights_moves(*loc): n = len(loc) # count dimensions # Debug print(f"n: {n} n-out: {len(moves(n))}") pos_list = [] for move in moves(n): # Iterate through every move pos_list.append([a+b for a, b in zip(loc, move)]) # Add move elementwise with original location filtered = [pos for pos in pos_list if min(pos) > 0 and max(pos) < 9] # Check if the move ins return filtered ``` Any suggestions/tips or questions are very welcome! [Answer] # [Haskell](https://www.haskell.org/), 66 bytes ``` f a=[x|x<-mapM(\_->[1..8])a,sum[n^2*9`div`4|n<-zipWith(-)a x]==11] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P00h0Ta6oqbCRjc3scBXIyZe1y7aUE/PIlYzUae4NDc6L85IyzIhJbMswaQmz0a3KrMgPLMkQ0NXM1GhItbW1tAw9n9uYmaegq0CSH@8QkFRZl6JgopCmkK0uY6CsY6ChY6CUex/AA "Haskell – Try It Online") Essentially a port of G B and dingledooper's Ruby answer. ]
[Question] [ Interval notation is a way to write complicated range bounds more conveniently and concisely than writing an inequality. The challenge, should you choose to accept it, is to write a program or function that interprets a subset of interval notation. In this subset, intervals are a comma-separated pair of integers delimited by either brackets, parentheses, or both. The range starts from the first integer ends at the second integer, inclusive if delimited by a bracket or exclusive if by parentheses. Multiple ranges, delimited by `U`, may be chained together, in which case duplicate elements are removed. Input is a string in interval notation and output is a list of numbers contained in the specified interval. Only meaningful intervals are valid, so ranges may overlap, but the start will always be less than the end. Zero sized intervals should have an empty output. All integers in the interval must be displayed once and only once, but may be outputted in any particular order. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the lowest byte count wins. ## Other Details * Invalid inputs are undefined behavior * a `∪` or `⋃` symbol may be used instead of `U` * The `U` will always be between ranges, never in front or behind * If your language uses a character other than `-` to represent negative numbers that may be used instead ## Test Cases ``` [0,5] -> [0,1,2,3,4,5] (0,5] -> [1,2,3,4,5] [0,5) -> [0,1,2,3,4] (0,5) -> [1,2,3,4] [9,13] -> [9,10,11,12,13] [-5,-1] -> [-5,-4,-3,-2,-1] [-5,-1) -> [-5,-4,-3,-2] (-5,-1] -> [-4,-3,-2,-1] (-5,-1) -> [-4,-3,-2] [-3,2] -> [-3,-2,-1,0,1,2] [-3,2) -> [-3,-2,-1,0,1] (-3,2] -> [-2,-1,0,1,2] (-3,2) -> [-2,-1,0,1] [0,0] -> [0] (0,0] -> [] [0,0) -> [] (0,0) -> [] [1,2) -> [1] (1,2) -> [] [-3,0)U(0,3] -> [-3,-2,-1,1,2,3] [-3,0)U[0,3] -> [-3,-2,-1,0,1,2,3] [-3,0]U[0,3] -> [-3,-2,-1,0,1,2,3] [-3,0]U[2,5] -> [-3,-2,-1,0,2,3,4,5] [1,5]U[2,4] -> [1,2,3,4,5] [-5,-1]U[-6,-2] -> [-5,-4,-3,-2,-1,-6] [-5,-1]U[-6,0] -> [-6,-5,-4,-3,-2,-1,0] [-5,-1]U[-6,-2]U[-7,0] -> [-7,-6,-5,-4,-3,-2,-1,0] [1,2)U[2,3)U[3,4)U[4,5) -> [1,2,3,4] [2,1) -> Undefined U(5,10) -> Undefined [13,18)U -> Undefined ``` [Answer] # [Python 3](https://docs.python.org/3/), 79 bytes ``` lambda s:eval('{*range%s}'%s.translate({91:40,40:'(1+',93:'+1)',85:',*range'})) ``` [Try it online!](https://tio.run/##jZLRboMgFIav61MQkwZY0YjaZjXp3qJXrhd04mZirRG2rDE@uwNhlra72A0e/v/7Fc6xvciPc5OM5e51rNnpWDAgMv7FagT7p44173wpBrgUoVQbUTPJUb@lWRqRNMogoitItkkGVxRD8rzOIDEhOGA8Vqf23EkgLsLzynMH6qrhoGq0EApZVE3YcVYgHIq2rqR2BcKZt2AEHMFuwo2FfBC8AB97i7arGolKv2cD6Lj87BpegL5EDA8A8e@Wv0ktHAfs4zGPyPqgk6qgJCYJSZXgoVl2RM3iW9aQ2CUVtyU0MWlVKZYSGmvJy4M1CaixdJmSICFBrDXr4XtPfcENuQnkJmY8V8/Y0hYl03mthR8s/aZrxg0gJ3Cl1fUj27Pp/nZjDGxr5NS6NbZHypg35kAR3is2uTvx1MwZyB@B6AY5/AuJf4fqINfpUrVqJn0cvJnAPg82usV/jI8EG3tN/YZErSqq1vT@5/gB "Python 3 – Try It Online") -6 bytes thanks to ovs -3 bytes thanks to dingledooper [Answer] # [C++ (gcc)](https://gcc.gnu.org/), ~~139~~ ~~138~~ ~~134~~ ~~104~~ ~~101~~ 100 bytes Uses C++20 features which aren't enabled by default in GCC, but are standard. ``` int f(auto&s,auto&o){int x,y;for(char c,d;s>>c>>x>>d>>y>>d;s>>d)for(y-=d<42;y>x-c%2;o.insert(y--));} ``` [Try it online!](https://tio.run/##lZXRrqIwEIbveYqGzXpoLB5A3ZMV7c0@w7lSsyGluiRKCRSjMbz6ulMKUkRPsl4UOvP90@mUjizL3D1jt1uSSrRzolKKUUHqh8BXZTyTS7gTucP@RDliJA4LShmlZ0pjSi8wKkOMFXJxV/FyFoQXenbZ9yAUkyQteC7B4WIcVrdvScoOZczRMhGFzHl0pFZnK4amE2dS5D2IS2q9v6MIFZLnXMhLlrDogMSJ50wcswPMJI/Rr/EYSV5IBAILApdM1vM4khG6Wgh@TKTKL@PFAoAk3aMkzUoZvnDycwbZ8Di0qhAiRjJhDXWPq16K9Rat9ApXe@2R@dYmyPaITwIyJTMyJ3ZFtNdpvU98Son7yp4Om7pO9ZP40zokvIDSJ34AFgNw58T1a0K9zYg7JW4ApkcEPyLd6kaIZ3rH0A/Ea5gHWtsK9Qb7BB4QRvh7hGdyp5MPtVBUrzkOs5ja1qNwz@IMLGu/WcXMrLX19uLhT5BP@3vWB/fIrQec95Tc/g8ZNN@YQQ4/Nh8ghc5efo760D/X7g8IowPC25efkKa9F7D3Mjg8P1rZB/laqUquEp/CCCnDOBvcDXVf2wt7EklcX1Pn4eqO1Igt3Rnqa89EKdFyid7sN/VQ/kndINTM3tiLe0dYoI1t35nW2mAE5bwoD7KGwi58otuK7nlIP67dIpWBih4KaYH/agLQ45bQq2mz1G@Ya@/O0SJieHDjEjlqiqDaPRppAi1MtOmU6qeXVZtqQFUa8qaDVcOyaX4C6zu4KcUmhQJUlqX@Vo5RkjptvQe5qDTqZmpmUB9bmz6c6u0v2x2ifXFzYeEVG4@D6B8 "C++ (gcc) – Try It Online") Uses streams because I wanted to simulate`>>`a`>>`merge`>>`conflict instead of writing top `%p`ercentage `printf`/`scanf` calls. The input is an EOF terminated stream (I could adapt this to accept `'\n'` termination, though). It doesn't actually check the separator. The output is stored into a `std::set<int>` reference. It must be empty when called. Usage: ``` std::istringstream input{str}; std::set<int> output; f(input, output); // Output now contains the result ``` Ungolfed: ``` #include <set> // std::set #include <iostream> // streams (abstracted with abbreviated templates) // input: An EOF terminated std::basic_istream (e.g. std::istringstream) // output: stored into a reference to a std::set<int>. Must be empty. // Golfed code returns int, but doesn't actually return anything void interpret_interval(std::basic_istream &input, std::set<int> &output) { // Holders for our range int start, end; // read input for (char left, right, tmp /* overwrites left/right in golfed code */; // this will return false on EOF (or EOS) // [ -1 , 4 ) input >> left >> start >> tmp >> end >> right; // discard U, sets EOF bit on end input >> tmp) { // done indirectly in the golfed code if (left == '[') // golf check: '(' == 40, '[' == 91, do a modulo 2 start--; // one extra iteration if (right == ')') // golf check: ')' == 41, ']' == 93, less than 42 end--; // one less iteration // Loop from end to start, inserting all the numbers in the // range to output. // XXX: std::iota? Doubt it would be smaller due to the include. for (; end > start; end--) { output.insert(end); } } // output now contains the set of values. Due to it being a std::set, all values // are unique. :) } ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~23~~ 22 bytes ``` ṣ”Uµṙ1“(Ḋ)Ṗ,r”yḟØ[V)FQ ``` [Try it online!](https://tio.run/##jZKxasMwEIb3PEVGCU5gSU6gS8fuGRwoImOXkqlbttCl0DFDSSGlkKyZSgs23Rr6IPKLqHeWal/sDl1Op/u/X5bufHuzXK5C8NWhXr8UXx@@etb1eid8@Sh99QR3WF758vW0dXN5NQv@892Xb/X90Zd7jKcHDN8bX21xvQ7BZTBZjNXlGBMNBizkWBiJtsyKxMpzNpKSk8hdgLbRjRmyGrSh0sipCSgdJUpzUBaUoVrSZF/DL3ATdwjuaHGHq0l0QqG5b5LkQKKTOg83CGboaHx@lnrWvD9toiBTLlhOrUk9QqHdxAtlskDW9m7cNLMF3BDIzpDFvxDzO1SGdNPVGInJh4OPEyicmlKL/xgfqGl6Jp1gMaIVY97/OX4A "Jelly – Try It Online") -1 byte [thanks to](https://codegolf.stackexchange.com/questions/217297/interpret-interval-notation/217302?noredirect=1#comment506870_217302) [ovs](https://codegolf.stackexchange.com/users/64121/ovs) ## How it works ``` ṣ”Uµṙ1“(Ḋ)Ṗ,r”yḟØ[V)FQ - Main link. Takes a string S on the left ṣ”U - Split S on "U" µ ) - Over each section R in the split S: ṙ1 - Rotate by once, shifting the first character to the end “(Ḋ)Ṗ,r” - Yield "(Ḋ)Ṗ,r" y - Transliterate; Replace "(" by "Ḋ", ")" by "Ṗ" and "," by "r" Ø[ - Yield "[]" ḟ - Remove "[]" V - Eval as Jelly code F - Flatten Q - Deduplicate ``` ### Why `r`, `Ḋ` and `Ṗ`? As we only consider each individual range in the transliterate-then-eval stage, we'll just take a look at the four possible examples: ``` [0,5] -> 0r5 [0,5) -> 0r5Ṗ (0,5] -> 0r5Ḋ (0,5) -> 0r5ṖḊ ``` In Jelly, `r` in the infix inclusive range command, so `0r5 ⁼ [0,1,2,3,4,5]`. `Ḋ` is dequeue (i.e. remove first element) and `Ṗ` is pop (remove last element). So `r` generates the range, then we remove the first and/or last elements if necessary, creating exclusive ranges. [Answer] # [Perl 5](https://www.perl.org/) `-MList::Util=uniq -FU`, 53 bytes ``` say for uniq map{($a,$b)=/-?\d+/g;$a+/\(/..$b-/\)/}@F ``` [Try it online!](https://tio.run/##jZI9b4MwEIb3/AorYrAbH8Z8RGoQbSemdmQCBqJ@CCkNNNChqtqfXnoGFxzI0MU@3/u85nxH/XQ6BF1TfKwBYB1acQoyj74bQewrIUKlkOfqRN6P5Rt5LepPahXc2rNIwG32uBEvoVVsREaFbVt7EBkTX3dx16UOD3ICNwQDyV3ucR8TKzqmjaRi2Tk7kMwkkbvm0hvcGCEruXRVapVCwLHsXlKhz8Hj4Kqc1thcwy@YJtNBTceIp7i7mtYo7@vVEltI6qbJYxqoYZhofL6je9a/Xx8GgemYGrFqje4RCuNhKMhhCbLerOK@mSOQLgHnDMn/hbh/QzWQaboSV8X4y8EPE0hS2KoWXxgfh61@prrBwxWtuPrzn@OnqtuyOjYdPAS2Ix3c78um3e2StjxE6uftIE5@AQ "Perl 5 – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 66 bytes ``` ToExpression[(#/.{"["->"Range[","("->"Range[1+",")"->"-1]"})<>""]& ``` [Try it online!](https://tio.run/##bZDBSsQwEIbvfYwpLClONGlaUdCyIN5FvQ05hNJ1e9iutD0Iy@7Fo2/pi9SmcVoXPM0/X35m/snO9dtq5/q6dMPmfnjdP368t1XX1fuGRHx1eQACWcCza94qAgSxdPpi7BPfS23hmNwVAHY1PLV101Msi836YetaV/ZV261juzq9lK45HSIghbkFjECw8CRhMgm6RW3Cm8zRL5hlMC5ULJSkwdTO6tfJTMxs3Kc4geIEihMEQZoHsPAzVfL99Tl6jD0jdEbs/yTla/UoAsj@nuiRvEaZ2nl/cJmpGsymmvEXpRiu9oly1BzboL7xRoiOww8 "Wolfram Language (Mathematica) – Try It Online") Input a list of characters. [Answer] # [Ruby](https://www.ruby-lang.org/) `-nl`, 69 bytes ``` p eval"[*#{gsub /[(),U-\]]/,?(=>'1+',?)=>'-1',?,=>'..',?U=>',*'}]|[]" ``` [Try it online!](https://tio.run/##XY/NCsIwEITvPkXRQxPd2KRpBQ/ap@hp3YOCiCBa/ANRX9242VoFL7PfZNhhc7ysbiE0yfq63PVxOLhvTpdVkqHSUJsFUQaVms1TN0qh0gzGMQDDeMxQM8AwfdIDqR8CWiipp0Qja2Hdwyk4z0@mBOO6yeHHq49H4yGndsRUnGod11mptlJtpZoVc4ibTjZE47rVNceeOoM/Q38ml2Mda@Tie2WNZgImp7Y7Zp7VQ8Fa8Kdeh@a8PexPwex3bw "Ruby – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 22 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ṣ”UµØ(fOị⁾ṖḊvṖḊVr/Ʋ)ẎQ ``` A monadic Link accepting a list of characters which yields a list of integers. **[Try it online!](https://tio.run/##y0rNyan8///hzsWPGuaGHtp6eIZGmv/D3d2PGvc93Dnt4Y6uMggVVqR/bJPmw119gf8Ptx@d9HDnjP//laINdYw0Q6ONdIyBpLGOCZA00THVVAIA "Jelly – Try It Online")** (Footer formats the resulting Jelly list as a Python list.) Or see the [test-suite](https://tio.run/##y0rNyan8///hzsWPGuaGHtp6eIZGmv/D3d2PGvc93Dnt4Y6uMggVVqR/bJPmw119gf8f7tgEVNd@dNLDnTMe7lwbrun@/3@0gY5prIIGmASxNcFsTYVoSx1DY6CQrqmOriGMBkpC@RpQfrSusY5RLIQCyYJ5GhAe0DgDsNEGYKMNwEYDyWhDsFowCdJooBkKlDCOhXGiEZxYNI4R2JmGQBLENoG7LzRa10xH1ygWYjZIzhhIGuuYAEkToHcA "Jelly – Try It Online"). ### How? ``` ṣ”UµØ(fOị⁾ṖḊvṖḊVr/Ʋ)ẎQ - Link: list of characters, S ”U - literal character = 'U' ṣ - split (S) at ('U's) µ ) - for each part, P: Ø( - literal list of characters = "()" f - filter keep (characters of P which are one of "()") O - to ordinals - i.e. '(' -> 40 and ')' -> 41 ⁾ṖḊ - literal list of characters "ṖḊ" ị - index into ... -> 'Ḋ' -> 'Ṗ' Ʋ - last four links as a monad, f(P): Ṗ - pop - i.e. remove ']' or ')' from the right of P) Ḋ - dequeue - i.e. remove '[' or '(' from the left of P) V - evaluate as Jelly code - e.g. "-4,2" becomes the list [-4,2] / - reduce with: r - inclusive range ...and then [-4,-3,-2,-1,0,1,2] v - evaluate (the string of "ṖḊ" characters) as Jelly code with input (the inclusive range) Ẏ - tighten (to a single list) Q - de-duplicate ``` [Answer] # JavaScript (ES6), 104 bytes Returns a set. ``` s=>s.replace(/(\[?)(-?\d+),(-?\d+)(]?)/g,(_,a,b,c,d)=>(g=_=>b>c-!d||g(S.add(b++)))(b-=-!a),S=new Set)&&S ``` [Try it online!](https://tio.run/##pZTLjoIwFED38xXowtwbb3lrMovCRxBXSAwvyUyMGDEzG/@daR0ncWwpGllA0t7DKdzHZ/6Vd@Xx43Bi@7aq@y3vOx519rE@7PKyBgfWaYzA4nU1R7o@IYvRaQg2lFNBJVXII2j4hkdFVLJJdT43kNh5VUExnyMiFIyzSY6U8H39bSX1CWezpC/bfdfuanvXNrCFaerSIpsiWurlOJbY9cingEIR9XaHghkdBqUTH3BqjThqVH3v5AX6k0pM7AqlR54vwxSYLYh5WlrCcjckFhDzZZiexgdo9WNHxAYrjFiHlKlY9od/1J@PLhnS0/gQrTmx2WzQwoh20CkKzTWVvq78TIBWgE/Ew5PxsuBN7aAKzIA2oy6uxLmU9vmX0UvjDdHpGO2a@Ox13lfH1B0/OKg8sShfECppH5lwv727StlS9tktrA4NYkt9aqU5EHfhEPfwOvtuJ13/Aw "JavaScript (Node.js) – Try It Online") ### Commented ``` s => // s = input sequence s.replace( // match in s all occurrences of: /(\[?)(-?\d+),(-?\d+)(]?)/g, // (\[?) an optional opening bracket (a) // (-?\d+) a number preceded by an optional '-' (b) // , a comma // (-?\d+) another number in the same format (c) // (]?) an optional closing bracket (d) (_, a, b, c, d) => ( // g = _ => // g is a recursive function ignoring its input b > c - !d || // abort if b is greater than c, or greater than // c - 1 if d is not defined g(S.add(b++)) // otherwise: add b to S, increment b and do a // recursive call )(b -= -!a), // initial call to g; increment b if a is not defined S = new Set // initialize S to a set ) && S // end of replace(); return S ``` [Answer] # [J](http://jsoftware.com/), 60 bytes ``` [:~.@;'U'<@([:({:+[:i.0>.-/)(']('={:,{.)+3 1".@;@{;:);._1@,] ``` [Try it online!](https://tio.run/##lZPLSsQwFIb3PsXPbNIwacylHZjUkYLgypUwqxKyEAd14wMUfPWatqTXVGqgWX185@Sc/l/NgZMbLgYEDALGfynH0@vLc1OZH14W5EoeyqQySW2Olfnk4pGn9zQhNiGX2rCa06OGPHiyrAtDC@5kyWxD797fPr69TUJBI0OO8aQGN5BKsNySnotRgUsm3OhD1EcXPmz4AneG9EoJqSD10ndmUofCLofL4DScgpML0OXMyRi5arEjQ/GIcGxy7lwLF@TgDMJ@UovqmikbAxEBB@NaN6k9Na51czAYE2YEBaLL8UsUQUgIImdY4i6u9dGdvkl/crM/Ob7jT9@EG0bd/5WrUQt69eW1ja9QR/DqP7jdwieRm@NqXzD9LPKOzjZS4k7rlFwrd2JO2R1B7Wbd@rW/Ncv8nbXRbX4B "J – Try It Online") * `'U' ...;._1@, ]` - Prepend `'U',` to the input `]` and cut it using the first character `;._1`, ie `U`, as a delimiter, applying the verb defined by `...` to each piece. Now we'll breakdown what's in `...`: * First we turn it into boxed words `;:`, so for example `'(_5,2]'` becomes: ``` ┌─┬──┬─┬─┬─┐ │(│_5│,│2│]│ └─┴──┴─┴─┴─┘ ``` and we take elements from indexes 3 and 1 `3 1 ... {` (the numbers) and unbox and convert then to ints `".@;@`. We take them in reverse order, right endpoint first, because it ends up saving bytes in a later step. * `('](' = {: , {.) +` This adds an adjustment to each of the numbers, based on endpoint type. `{:,{.` returns the last and first character, and `](=` does an element-wise comparison, which will return 1 when equal, 0 otherwise. Thus the original input's right endpoint is incremented when it is `]`, and its left endpoint is incremented when it's `)`. * `({: + [: i. 0 >. -/)` The adjusted, reversed endpoints are now passed to this phrase, which sticks a minus sign between them `-/`, and takes the maximum of that result and 0 `0 >.` (this is to account for the `(0,0)` case, which would otherwise return `_1`). We then generate the integers up to, but not including, that result `i.` and add the original input's adjusted left endpoint `{:` to all of them. We now have the correct range of numbers for a single range. * `<@` And we box that up, to avoid fill when pieces of unioned input of different lengths are combined. * `[: ~.@;` Finally we unbox the combined result to get a single list `;` and dedup it `~.@`. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 46 bytes ``` FE⪪SU⪪ι,F…⁺IΦ§ι⁰λ№§ι⁰(⁺I⮌Φ⮌§ι¹λ№§ι¹]F¬№υκ⊞υκIυ ``` [Try it online!](https://tio.run/##bY8xC4MwEIX3/grJdIEUtKWTUxEKDi2iOIlDsKlKQ5R4kf77NDaIpXQ5ePfufXfXdFw3A5fWPgYdwJWPUIyyR0jVaLBA3asWKAtISVz1Vu8kI5TS4JPJuWoFZNJMkPAJ4dJLFBrOmKq7eC3ToYtK6koyGIW/DgGyeBsgF7PQk1hBq/yKRdQT/yGjBVlv590GBD9kWPBc2pmZOi/iXeYeRL/WUBpbW5Fqf2RhXVYHdqpJbfezfAM "Charcoal – Try It Online") Link is to verbose version of code. Uses `U` as the union operator. Explanation: ``` FE⪪SU⪪ι, ``` Split the input on `U` and then split each part on `,` and loop over each pair of parts. ``` F…⁺IΦ§ι⁰λ№§ι⁰(⁺I⮌Φ⮌§ι¹λ№§ι¹] ``` Form a range from the integer in the first part (excluding the first character) and the integer in the second part (excluding the last character), except increment the first integer if the first part contains a `(` and increment the second integer if the second part contains a `]`, and loop over the range. ``` F¬№υκ⊞υκ ``` Push any new integers to the predefined empty list. ``` Iυ ``` Print all of the collected integers. [Answer] # [R](https://www.r-project.org/), 148 bytes ``` function(s)unique(unlist(lapply(parse(t=chartr("[],","():",gsub(",(-?\\d))",",(\\1-1))",gsub("\\((-?\\d)","((1+\\1)",el(strsplit(s,"U")))))),eval))) ``` [Try it online!](https://tio.run/##RY3LDoIwEEX3foXpaiZOE8rDhdH4FawoC0RQkgaxDxO/HgeE0MX05Nw7rR3b/VmObehr3716cBj67h0aCL3pnAdTDYP5wlBZ14C/1M/KeguiKEmQADwJerhwA0Egr1rfEVkTaK2kmvgfag1LPC2BOnDO2Bhw3rrBdB4ciVzgfKj5VIbvseV/IspKgTtG2HCyuNkFC5lQhDmbZO0pXsmLmNJVyIykYiWPJOOtFePUSngmlPJM50fHHw "R – Try It Online") If there's a shorter way, I can't seem to think of it. [Answer] # [Zsh](https://www.zsh.org/), ~~89~~ 84 bytes ``` for i (${(s"U")1}){seq $[${${i%,*}#?}+1-#i&1] $[${${i#*,}%?}-!(##$i[-1]&4)]}|sort -u ``` [Try it online!](https://tio.run/##NcixDkAwEADQXyl3pKWXaGr3FaamI9FJKIu6bz@TN74nbyLrfqqkNBad67k2jk3Jy6EwYMGSGtsxTNw7gtS6@Dd0lpuJqdIAmAK52I4m8pv381J0i0ggbwcz68H6@AE "Zsh – Try It Online") [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell) for Windows, ~~133~~ 114 bytes ``` $(switch -r($args){'\('{$l++}','{$l+=+$n}'\)'{$n-=1}'\)|]'{$l..$n*($l-le$n) $l=0}\D{$n=''}'\d|-'{$n+=$_}})|sort -u ``` [Try it online!](https://tio.run/##jZRtb9owEMff51N4rbfY41zFhIdWVaROmybtVachXgVUUTAtVZqwPKjTIJ@dnZMAxhnT8iI53/1/9vl88Tp5U2n2rKJoR5ckIJsdZdnbKp8/E5EyOkufMr5xJ8zd0KjTKV2ojKBD49KdcBzEIpDa3E515OqKxh8ZjUSkaMwdGgVeOfmCqsB1UbXYCo10AvpQlnybJWlORLErHeeOOQ4wN/SgP3WBaENCF3zoaQfXMXaI2RFN8VPKYLjJ7IkbkH49GVpISZDdylWHRR@ErOPa7IHwQXQrnyHgtmC/qom3WGayp2CIg27DNRBUWzLjvBU/THykWygzUIvDqnlN0Y9lazyGhJsOZjt0gZtK7yUHj5G9x8eI@tYeq8M5VYVtldfWTf9f1913j6Gz2kiiqYW9M21WH@s4FIPqyKrJ0LQbhFyS@3Sh0nc25J1hwPv7CvgdHqAh/IPTpdaZ@/jGlPHdO9P42OWHQyHWc0nG8UItV7FaaO2Y9fHfqNUDGMI13BwhSxtKH@Q1H9dLot0DifQA5LBmTL3DyZa8JxtHT0SzPF3FT0Co@rVW81wt8BqiD3UsVVkR5ej4gLfTXa00I1@T9HWW18xFSFnjFi/JKsa7ik8vKnX4ffS5yPLk9f7xBZeY3m3IqJjPVZbpteyphPp5TOaWfIvXhU6hSfSW/Ngn1SJLp8SdLauxyGePkSLiU5Eno9VvtfsD "PowerShell – Try It Online") Less golfed: ``` $numbers = switch -Regex ($args){ '\(' {$left++} ',' {$left+=+$num} '\)' {$num-=1} '\)|]' {$left..$num*($left -le $num);$left=0} '\D' {$num=''} '\d|-' {$num+=$_} } $numbers|sort -u ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 137 133 bytes -4 bytes thanks to Mazzy, who has an even cooler PS solution to this challenge! ``` $r="'|% rep* '" "'('+('$args$r(','[1+$r)','-1]$r]','))$r[','(($r,' '),($r`U' ',')+',0)'"|iex|iex|%{$l,$n=$_;$l..$n*($n-ge$l)}|sort -u ``` [Try it online!](https://tio.run/##jVJRb5swEH7nVyDrOuNyRBCSthKyFKnapL2s1VqeUNQmmddmIpDZoFVK@O3pGULWF9paMj58n7/vu7O35T@lzbPK8wP8rotVtS4LuTuAlozvz1yttucuZw7jHvc9Dgv9ZEB7HHkW@aAFBUE0Bz2nQAjQGa2eBxq5ywVS8JhSRDmfYyg426/VSzvPdpAjFBIeEshHIyjOPSiCJwW5aPam1JUb1IfGgUqZ6nphlHGlO/Mcl8Zs1y52rIttXdnAJlkWTJHcpFlwgcHYrpcYzpk4wdXLVq0q9auFU9Li6MgEg5gO0Fny2IIbHBaJYoyuRDpEa9MTjKYYXWB0@SGdF5LmENfHZsJ3CvxELVR3KFLyEA@3qW9NhGOMP9EeHIs0s9A0i3FC3wlOBytsSQnV0TrCgXu6cCNt7f/v3r4W@/Oj3iyVllHTqUMrjdAz0mMaHbceRv1mh9TK1Hklv5zeuDtrkV3W1KuVMkayI44F6i870bIO1BrzZXZ7d12bqtzcLP9Qej7bcZvh8o1D30/ujpQ9d/LdypFCK8uSn52hk2LytS/ijXDjNMeG7L@VerOogvvFMleHVw "PowerShell – Try It Online") [Answer] # [QuadR](https://github.com/abrudz/QuadRS), 40 bytes Uses `∪` and `¯` instead of `U` and `-` ``` ⍎⍵ \[ \( , \) ] ( (1↓ {⍺+0,⍳0⌈⍵-⍺} -1) ) ``` [Try it online](https://tio.run/##KyxNTCn6//9Rb9@j3q1cMdFcMRpcOlwxmlyxXBpcGoaP2iZzVT/q3aVtoPOod7PBo54OoDJdoEAtl66hJpfm///Rh9ab6hxabxj7qGMVkG0GZBtB2eY6BrEA "QuadR – Try It Online") or [try them all](https://tio.run/##dVA7DsIwDN19kkS4UtK0fHZukWZAYkYCiQmxIVQJwsItWDogFsYeJRcJjluVDrDY7z2/@JPtfrXexRj8LfgXVBYqAQiVBAfVBgQIHc53OAT/nigM/qnCtSZnRsIRMi1BQricYrQKSweCY8KSsQS7QG1IapsS20Z/ERkGTQwaVQ3mrs/sYS56Tq0Vj1E8RvEYilazmyO/VTLUD6oZN@J2xN0vnvP6mmLHitHmSWmbKeH8h6r@ODs843rarutrOBssOBf8UTnS/WnpEjVfZFDPUz0uPw "QuadR – Try It Online")! Execute (`⍎`) it (`⍵`) after simple transliteration to APL: | In | Out | Explanation | | --- | --- | --- | | `[` | `(` | Open group | | `(` | `(1↓` | Open group but with first element (the start) removed | | `,` | `{⍺+0,⍳0⌈⍵-⍺}` | Anonymous infix lambda to compute range (see below) | | `)` | `-1)` | Close group but subtract one from the end | | `]` | `)` | Close group | The "try them all" link also replaces `\n` with APL's statement separator `⋄`, and runs in **D**ocument mode. ### The infix range lambda `{⍺+0,⍳0⌈⍵-⍺}` `{`…`}` "[dfn](https://apl.wiki/dfn)"; left and right arguments are `⍺` and `⍵`:  `⍵-⍺` difference  `0⌈` maximum of zero and that; nulls negative differences like `[3,3)` → `(3`…`3-1)`  `⍳` **ɩ**ndices one through that  `0,` prepend zero  `⍺+` add start point to all of those [Answer] # [Haskell](https://www.haskell.org/), 194 180 bytes ``` import Data.List a=init l=drop 1 t""=[] t c=nub$i v++t(l n)where(v,n)=span(/='U')c i('(':c)=l$i('[':c) i c|last c==')'=a$i$a c++"]"|1<2=f$span(/=',')c f(_:o,_:w)=[read$o..read$a w] ``` [Try it online!](https://tio.run/##lVNRa9swEH7XrziMIRKRu9hJCwvTHsZgDPo2@uSaojpuI@bawVabPfS/ZyfJSSQ7he3Flu77vpN0d99W9r@ruj4c1Muu7TR8l1pe3apeEylUozSpxaZrd5ASHUUiL4iGUjSvj7GCt/lc0xoatt9WXUXfeMNEv5MN/SRmdzNWEkVndLYumahjXOZmSRSU77XsTRYxYzMhYxVLKOfzqIje0y@ZeIqPObjJ8UQf1i1/WO@ZyLtKbuL26sr@JeyLQyn7qof1GnL6S3eqeeaQ/2x0wQriIAE5AaBRvuDXRYTogqc840u@wj1DiCNIj@AUMjoW6AIV81RnzWeeLm0@XKAu5WlmIic8ueZJaglmteLJkieZCYUMNmKcT/YSXFBTTz2W5rjNnHKQcfuykMDGBC/3SX9BTM/iiRIruHAd8CvoQgGJBRE6iZh6u7qfScdQ8IwFu0P1MnytbdaYlk9oi0vE4j@I2TBSHnEyWyluDHP10fC5Pt/lyY3p4XRgeHITlsVkW@IX8@B3NR7QgpAXqRp0xaZFWV1pUI2uujdZG6voIUaf23bD4VFuGEZ3stNKq7YBek9Vs3vVHKo/u6rUFeLJVy@FRUEID4/BGhEzI4QevW0wFP3AA9YQwXwO/bbdgzlwRPkmAwZexhK6CigjB@tnc3hgaEJPYS9oPRxyHZP5TORZ39pYaFwyNMJCI8sOGBtjeIIv8hXUV5zozpkuGFrTQWwCmUxnjS@gnuDMtg50dbDvHzYOYMOaems7Uq5GCJw27kJHd4XXcmYgvq8uPOlEKf6Jkh2besFMxHPRpPGhfy60zxiIfOCcYDj@Ag "Haskell – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 28 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 'U¡ε¦¨',¡ŸÙy„()©Ã®"¦¨"‡.V}˜ê ``` [Try it online](https://tio.run/##yy9OTMpM/f9fPfTQwnNbDy07tEJd59DCozsOz6x81DBPQ/PQysPNh9YpgSSUHjUs1AurPT3n8Kr//5WUlKJ1TXV0DWNDo3XNdHSNQLS5jkEsUAIA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeV/9dBDC89tPbTs0Ap1nUMLj@44PLPyUcM8Dc1DKw83H1qnBJJQetSwUC@s9vScw6v@6/yPVoo20DGNVdJR0oDSIL4mlA@ioy11DI3BErqmOrqGCBZYEVxMAy4WrWusYxQLY0BUQUU0YCJASwyglhpALTWAWgqmow2hOqE0yCgDzVCgtHEsghuNzI3F4BpBPWQIpEE8EyRfhEbrmunoGqGLGGBRAqTNoRIg14BMMgaSxjomQNIEFEixAA). **Explanation:** ``` 'U¡ '# Split the (implicit) input-string on "U" ε # Map over each interval: ¦¨ # Remove the first and last characters (the "[]()") ',¡ '# Split on "," Ÿ # Transform that pair of integers into a ranged list Ù # And uniquify it # (if a==b in [a,b], it will result in pair [a,a] instead of [a]) y # Push the interval-string we're mapping over again „() # Push string "()" © # Store it in variable `®` (without popping) à # Keep only the "()" in the interval-string (if any) ® # Push "()" from variable `®` again "¦¨" # Push "¦¨" ‡ # Transliterate "(" to "¦" and ")" to "¨" .V # Evaluate and execute it as 05AB1E code: # `¦`: Remove the first value from the list # `¨`: Remove the last value from the list }˜ # After the map: flatten the list of lists ê # And sort and uniquify the values # (after which the result is output implicitly) ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~107~~ 62 bytes ``` ⍎'\]' '\[' ',' '\(' '\)'⎕R')' '(' '{⍺+⍳0⌈1+⍵-⍺}' '(1↓' '-1)'⊢⎕ ``` [Try it online!](https://tio.run/##dZA9asNAEIV7nSLdSmQEO1rJJEdwZUi72kJgnMZgt8akdYSxTCDkAinTqAhpUuoocxF5VhJjS@Bm55s3P7ydYruOl7tivXlt6fw1X9DhQwdUvq9aqs4qd@pB5ZYf8BD6J1Lc@KIiZp/vqfp/pOpX06lEhr@YhTdfRDp8coyRJ47fPNTy3nYVKKshcypgCoW8FonWk30GNEO5qTNoahxnw8CoFo5q3GkgcTcsM6KHNzrb0GJNizUt1gayKJuEuv06ovKH@4ybaHaiuXtaIidBpl5JJ1fwalPPmBN39dP3mi4aSLuYyjETGG7iDWaA8hMD@OR71QU "APL (Dyalog Unicode) – Try It Online") Does a huge regex replacement and then executes the string. uses `∪` and `¯` for input. Uses `⎕IO←0` (0-indexing) -45 bytes by stealing a ton from [Adám's QuadR answer](https://codegolf.stackexchange.com/a/217443/80214)(It has a well-written explanation, go upvote it!). ]
[Question] [ Consider a one-dimensional sequence of numbers within a fixed range, i.e. ``` [1, 2, 4, 6, 8, 0, 2, 7, 3] in range [0, 10⟩ ``` The Ever-Increasing Graph\* \*\* is a line that connects all the points in this sequence left to right, and always goes upwards or stays level. If necessary, the line wraps around from top to bottom and continues going up from there to meet the next point. The goal of this challenge is to split the sequence in different subsequences that are all nondecreasing, so that when plotted together with a limited vertical axis they will form an Ever-Increasing Graph. This is done by adding an a point to the end of one subsequence and to the beginning of the next subsequence, so that the angle of the line that crosses the top boundary aligns with the line that crosses the bottom boundary, and the two crossing points have the same horizontal coordinate. The example above would give the following output: ``` [1, 2, 4, 6, 8, 10] [-2, 0, 2, 7, 13] [-3, 3] ``` And the corresponding graph will look as follows: [![The Ever-Increasing Graph which should actually be called Ever Nondecreasing Graph](https://i.stack.imgur.com/cby5a.png)](https://i.stack.imgur.com/cby5a.png) And with the axis extended for a better view: [![Ever-Increasing Graph which should actually be called Ever Nondecreasing Graph with extended vertical axis.](https://i.stack.imgur.com/OqLqA.png)](https://i.stack.imgur.com/OqLqA.png) The required output is a list of subsequences that form the parts of the Ever-Increasing Graph. Making a plot is not required but will earn you bonus points ;). The output must clearly separate the subsequences in some way. **Notes** * The range will be always have zero as the left (inclusive) boundary, and the right boundary will be some integer N. * The sequence will never contain values that are not within the range. * The first subsequence does not have an additional point at the beginning. * The last subsequence does not have an additional point at the end. * It is not required to provide the starting indices that would be required to plot the subsequences. **Test cases** ``` Input: [0, 2, 4, 6, 1, 3, 5, 0], 7 Output: [0, 2, 4, 6, 8], [-1, 1, 3, 5, 7], [-2, 0] Input: [1, 1, 2, 3, 5, 8, 3, 1], 10 Output: [1, 1, 2, 3, 5, 8, 13],[-2, 3, 11],[-7, 1] Input: [5, 4, 3, 2, 1], 10 Output: [5, 14],[-5, 4, 13],[-6, 3, 12],[-7, 2, 11],[-8, 1] Input: [0, 1, 4, 9, 16, 15, 0], 17 Output: [0, 1, 4, 9, 16, 32], [-1, 15, 17], [-2, 0] ``` **Scoring** This is code-golf, the shortest code in bytes wins. \*Not actual jargon \*\*Actually should be called Ever Non-Decreasing Graph, as @ngm pointed out, but that sounds less impressive. [Answer] # [**R**](https://www.r-project.org/about.html), 179 158 151 bytes ``` function(s,m){p=1;t=c(which(diff(s)<0),length(s));for(i in t){d=c(s[p]-m,s[(p+1):i],s[i+1]+m);if(p==1)d[1]=s[1];if(p==t[-1])d=head(d,-1);print(d);p=i}} ``` [Try it online!](https://tio.run/##LYrBCsMgEER/xeMuUei2FEqNXyIeisa60BiJlh5Cvj2VUpgZ3gyzHnFUR3xn33jJUOWMWzGkm/HwSewTBI4RKo4nlK8pP1vqBXVcVmDBWTTcQv9WW5yaZbVQBsI7u448kBtm1ByhGEMYLDlTe/yXZhU5DCZNjwBBKkJdVs4NQgfD@35E8EBSdJ2luEhxleL2A8LuEx5f) **Edit:** Code is now a function and takes input. (Thanks to Giuseppe, user202729 and JayCe for calmly pointing that out) **Edit:** -21 bytes suggested by Giuseppe. **Edit:** -7 bytes by removing `d=NULL;`. [Answer] # [Python 2](https://docs.python.org/2/), 60 bytes Input is N, followed by all points as individual arguments. Subsequences in the output are seperated by `0.5`. ``` f=lambda N,k,*l:(k,)+(l and(l[0]+N,.5,k-N)*(l[0]<k)+f(N,*l)) ``` [Try it online!](https://tio.run/##XY9BCoMwFET3nmKWif6WRGu1Uq@QC4gLi0hL0iiSTU@fxmBBupv582bgLx/3nG3u/dSa4f0YByjSlJqGaeIZMxjsyEwn@kzRuSR9UjyN/q55NjEVUM69Q4suAVgnCTnhQrgSaoKItiIUPUEKThESBygUCkIZ0EBUOyDjPf9FdRTyOFHGfhEh@bctY3YLYtvfp2XFkz5JpnmFISi8LFwTGsv6sg7bJwiv@C8 "Python 2 – Try It Online") --- # [Python 2](https://docs.python.org/2/), ~~92~~ ~~77~~ 68 bytes Subsequences are seperated by `[...]`. ``` l,N=input();r=[];k=0 for a in l:r+=[a+N,r,k-N]*(a<k)+[a];k=a print r ``` [Try it online!](https://tio.run/##TYxNDoIwEIX3PcWEFT9j0oIIir0CF2hYNIihgRTSYKKnr20h0d2bee/71s82Ljq3/fIYeBRFdsaWK72@tjhpDBddM3FKnosBCUrDfDMZFzJr0eB0ars0lvcpyYT0O0lWo/QGxjoRIcN76MF709IKhpAjnBEuCDUCDWeFUHQIjBJB/3q3LRBKt3JlRTy74/u3DoEdYBmoIvTsJ2PhfXXBCw8Xq74 "Python 2 – Try It Online") [Answer] # [Clean](https://github.com/Ourous/curated-clean-linux), ~~279~~ ~~269~~ 258 bytes ``` import StdEnv s=snd o unzip $[]=[] $l#(a,b)=span(uncurry(<))(zip2[-1:l]l) =[s a: $(s b)] ?l n#[h:t]= $l =[h:if(t>[])(?(map((+)n)(flatten t))n)t] @l n#l= ?l n =[[e-i*n\\e<-k]\\k<-[a++b++c\\a<-[[]:map(\u=[last u])l]&b<-l&c<-tl(map(\u=[hd u])l)++[[]]]&i<-[0..]] ``` [Try it online!](https://tio.run/##RZDLasMwEEX3@oqBmCDVUkj6BGM1WbSLQndZyrOQH2lEZNlYUiH9@LpKSunycO@5MNPYTru5H9poO@i1cbPpx2EKsA/tq/skXnrXwgDRfZmRZAqlQpLZBdW8ZtKP2tHomjhNZ1oyRlPpVolNYdEyIpUHXUBGPdQMydaCW6hjEVBCZlN6LMyBhmeFjG5pr0dKc@YYPVgdQucgsEQBye7iWQkXP1mqE@bGVVVXihNW1akUSud5nedNVekECovLVhWlstoHiMgsLutS2GVTimDpX3psrxnL8@QgLk2S16sV4rwPegpkAdYkX4Jac7jlcM/hkcOGwx2HBw5rTA0X@7qbUucpwSF9IpjBJdwR@Y/Xmd/m/N2k8z78LN7e55ez071p/A8 "Clean – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~104~~ 82 bytes ``` n=>a=>a.map((e,i)=>e>a[s.push(e),++i]&&s.push(a[r.push(s=[e-n]),i]+n),r=[s=[]])&&r ``` [Try it online!](https://tio.run/##dY5NDsIgEEb3noIVgXTalNb6E0MvQliQSiqmQgPq9RGxXZhoMos3kzcz31U9VRi8me@ldWcdRx4t71Wq6qZmQjQYynvdKxGq@REuRFMoCiMxXnol/AcCF7q0koKRhaXguUgTKSnGPg7OBjfpanIjGcmeElEDagBtAe0AMUAtoA5QLSk9bb5lViebZalZvUMG9s/u8uE2L/yUlgAse8cE7xDr//gC "JavaScript (Node.js) – Try It Online") Port of @ovs's Python answer. [Answer] # Haskell, ~~82~~ ~~81~~ 80 bytes This is a port of [my Clean answer](https://codegolf.stackexchange.com/a/165066/42682). ``` r!n|let f x(r@(a:_):s)|x>a=[x,n+a]:(x-n:r):s|y<-x:r=y:s=foldr f[[last r]]$init r ``` [Try it online!](https://tio.run/##HYhPC8IgHIa/yjvYwZGDraLiR0bXoFtHkRDamGQu1MjBvruNTs@fQYdnZ23OvnCz7SJ6JObPTNO9olDN6aSFTNyttCKWakd@2fN0rBN5MVEQ/WgfHr2UVocIr1RpnFkkv7RxEHh/4i36q0OJMIzfBbLlWHNsOXYcB47mn3uOjUIB1jYgwsXFKv8A "Haskell – Try It Online") -1, -1 thanks to [Laikoni](https://codegolf.stackexchange.com/users/56433/laikoni) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 20 bytes ``` ⁹;+⁴,N¤j.x>ṭḷ çƝF;Ṫ{ ``` [Try it online!](https://tio.run/##y0rNyan8//9R405r7UeNW3T8Di3J0quwe7hz7cMd27kOLz8218364c5V1f///4821FEAIiMdBWMdBVMdBQswwzD2v6EBAA "Jelly – Try It Online") Subsequences are splitted by `0.5`. [Answer] # [Clean](http://clean.cs.ru.nl), 92 bytes ``` import StdEnv @r n=foldr(\x[r=:[a:_]:s]|x>a=[[x,n+a]:[x-n:r]:s]=[[x:r]:s])[[last r]](init r) ``` [Try it online!](https://tio.run/##JYw9C8IwFAB3f8UbW4zQqqgEIh10ENw6xiCPfkggeZUkSgR/u7HV7e6Ga0yHlOzQPkwHFjUlbe@DC1CH9kjPWeWARD@Y1mWXKJ3gEvlVca/ecY9CyshojorLuCDupj61P@VSGvQBnFKZJj1CnuqA41tABbJksGSwZrBhsGNQ/HTLYKWgLNKn6Q3efFqczunwIrS68V8 "Clean – Try It Online") The operator argument to `foldr` is a lambda with guard; it is parsed as: ``` \x [r=:[a:_]:s] | x > a = [[x,n+a]:[x-n:r]:s] | otherwise = [[x:run]:s] ``` I ported this [to Haskell](https://codegolf.stackexchange.com/a/165069/42682). [Answer] # [Clean](https://github.com/Ourous/curated-clean-linux), ~~110~~ ~~109~~ ~~104~~ ~~100~~ 97 bytes ``` import StdEnv @[x:r]n=let$s=:[x:r]a|x<last a=[a++[n+x]: $s[last a-n]]= $r(a++[x]);$_ a=[a]in$r[x] ``` [Try it online!](https://tio.run/##JY2xCsIwFEV3v@INGZSm0KqoVAMddBDcOoYgj7ZKIHmVJEoEv92odTznHrit6ZGSHbq76cGipqTtbXABmtAd6DGpZaycImH6wLyoRsJX3Bn0AVBIzDJJWVQVMC//MielBDA3/W1RzbbsPJZKE3NfkZqA3wMBNciSw5zDksOKw4ZDMeKaw0JBWaR3ezF49Sk/ntL@SWh16z8 "Clean – Try It Online") *-1 byte thanks to [Keelan](https://codegolf.stackexchange.com/users/42682/keelan)* [Answer] # [Haskell](https://www.haskell.org/), 82 bytes ``` (x:r)#n|let b@(a:_)%s@(x:r)|x<a=(n+x:b):[a-n]%s|c<-x:b=c%r;a%_=[a]=reverse<$>[x]%r ``` [Try it online!](https://tio.run/##ZY/taoMwFIb/exUH2oCyCCa21WVm9AbGLiCEkpbAymyQaIcwd@0uiXP98tfxnOc958mHaj91XY9j3DObLMxQ6w7221ixXYLabegOfaV4bJ56tk@YUKmRqB0OVer@@QHZF4V2XCjJrf7SttXV8lX0EtnxpI4GOJxU8waNPZoOlhCB@wSIDAPFsMKwwUAw5BjWGDIJCygCgkGQMKHzsAwF8QjJZmYdduQBuxtlIe6mz67wV@YDZLogo@g7jd7PXXPu2K1QKV0@JVdmRehQv@ESeRQkucQB86bE14X3ukQcRla@P4lP/Gbi6R9P52x5m71/UE7/Nf3aa8X0Z/wF "Haskell – Try It Online") Port of my [Clean answer](https://codegolf.stackexchange.com/a/165061/56433). --- ### Alternative, also 82 bytes ``` (x:r)#n|let a%s@(x:r)|x<last a=(a++[n+x]):[last a-n]%s|c<-a++[x]=c%r;a%_=[a]=[x]%r ``` [Try it online!](https://tio.run/##ZY/rasMwDIX/5ykEnaElMkRO22RZDXuBsQcwZphSaFlqQpJCYNmzZ74s62X@Jel8Rzo@mu7zUNfTtByqdrWwY33owbDuNfTjsKtN5wZyadJU2XTQq0rFEbeadeN@x70yaLln7YthH1IZLV3P2ulsThYknE3zBk17sj08QQLuKVAZgkBYI2wRCCFH2CBkGhZQBARBUVDELJahII9QNjObsCMP2IOUBbtTn13hr8wHKF7QSfLFk/dL31z66j5QqZ2f002yIkyE33C1/A9IucaA@aTk68LnulocRms/j8Ejv428@OXF7C3vvY8fysVfTL/2NiL/nn4A "Haskell – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), 98 bytes ``` a=>m=>(r=[],b=[],a.map((e,i)=>e<a[--i]?(b[p](m+e),r[p](b),b=[a[i]-m,e]):b[p='push'](e)),r[p](b),r) ``` [Try it online!](https://tio.run/##dc7JDoIwEAbgu0/RGzNxSiiIe/FBmh4KNohhC6ivj7TRmBi9TP5kvlmu5mHGYqj6G2@7s51KORmZNTKDQSpNuSsmbEwPYKlCmdmjUZxX@gS56jU0S4s0uJSj00ZVmjdkNe7nvgz6@3gJNFj8qAGnomvHrrZh3ZVQgoqIxcRWxNbEBLGEWEos0ggbxMPiCwtv4jfb@iBmLKIfOvV7Ez/wF0V@5ex2c3A/vM4Ld396Ag "JavaScript (Node.js) – Try It Online") This is quite a bit longer than the other JS answer, but it uses a different approach. ## Ungolfed and simplified explanation ``` g=(a,m)=>{ // r is the final array of arrays to return. // b is the current subset of only ascending numbers. r=[],b=[]; a.map((e,i)=>{ if(e<a[i-1]){ // if the current value is less than the previous one, // then we're descending, so start a new array b. // add the proper value to b to match slopes with the next b.push(m+e); // add r to b, and restart b with the starter value and the current value in a r.push(b); b=[a[i-1]-m,e]; } else{ // otherwise, we're ascending, so just addd to to b. b.push(e); } }); r.push(b); // add the final b to r, and return r return r; } ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 48 bytes, arrays separated by `,,` ``` s=>n=>s.map(r=t=>(t<r?[t+n,,r-n,,]:``)+(r=t))+`` ``` [Try it online!](https://tio.run/##fc5NCsIwEAXgvaeYZUKnJWmt/6m7XqIUUmoRpSYlCV4/JkE3IsIwPJiP4d2H52BHc1tcrvRl8q3wVjRKNLZ4DAsxwomGuJM5dy5TiCYPqz9ISbN4ozST0o9aWT1PxayvpCUdQygR1ggbBI5QIdQIrKdkS@lx9YV5MuWH7VLgAXP2Q9fpb5Wm/ONY@hroPoRY492Axwr@BQ "JavaScript (Node.js) – Try It Online") # [JavaScript (Node.js)](https://nodejs.org), 50 bytes, arrays separated by `|` ``` s=>n=>s.map(r=t=>(t<r?t+n+`|${r-n},`:``)+(r=t))+`` ``` [Try it online!](https://tio.run/##fc5NCsIwEAXgvaeYhYuETEvSWv9Td72ECCm1iFKTkgQ36tljG3QjIsziwXw83qW@1a6x594n2hzbUMngZKll6dJr3RMrvSyJ39qdZ5qpx/RuE/1EtVaKsvFLKVMqNEY707VpZ06kInuOkCHMEOYIAiFHKBD4gZIFpZvJFxbRZB@2jEEMWPAfuoi9ebzsj@OxdaCrIYwz3gvEOCG8AA "JavaScript (Node.js) – Try It Online") ]
[Question] [ ## Task Write a function that accepts two integers \$a,b\$ that represent the Gaussian integer \$z = a+bi\$ (complex number). The program must return true or false depending on whether \$a+bi\$ is a [Gaussian prime or not](http://mathworld.wolfram.com/GaussianPrime.html). ## Definition \$a+bi\$ is a Gaussian prime if and only if it meets one of the following conditions: * \$a\$ and \$b\$ are both nonzero and \$a^2 + b^2\$ is prime * \$a\$ is zero, \$|b|\$ is prime and \$|b| = 3 \text{ (mod }4)\$ * \$b\$ is zero, \$|a|\$ is prime and \$|a| = 3 \text{ (mod }4)\$ ## Details You should only write a function. If your language does not have functions, you can assume that the integers are stored in two variables and print the result or write it to a file. You cannot use built-in functions of your language like `isprime` or `prime_list` or `nthprime` or `factor`. The lowest number of bytes wins. The program must work for \$a,b\$ where \$a^2+b^2\$ is a 32bit (signed) integer and should finish in not significantly more than 30 seconds. ## Prime list The dots represent prime numbers on the Gaussian plane (`x` = real, `y` = imaginary axis): ![enter image description here](https://i.stack.imgur.com/ntfCU.png) Some larger primes: ``` (9940, 43833) (4190, 42741) (9557, 41412) (1437, 44090) ``` [Answer] ## C, ~~149~~ 118 characters Edited version (118 characters): ``` int G(int a,int b){a=abs(a);b=abs(b);int n=a*b?a*a+b*b:a+b, d=2;for(;n/d/d&&n%d;d++);return n/d/d|n<2?0:(a+b&3)>2|a*b;} ``` This is a single function: * *G*(*a*,*b*) returns nonzero (true) if *a*+*bi* is a Gaussian prime, or zero (false) otherwise. It folds the integer primality test into an expression `n/d/d|n<2` hidden in the return value calculation. This golfed code also makes use of `a*b` as a substitute for `a&&b` (in other words `a!=0 && b!=0`) and other tricks involving operator precedence and integer division. For example `n/d/d` is a shorter way of saying `n/d/d>=1`, which is an overflow-safe way of saying `n>=d*d` or `d*d<=n` or in essence `d<=sqrt(n)`. --- Original version (149 characters): ``` int Q(int n){int d=2;for(;n/d/d&&n%d;d++);return n/d/d||n<2;} int G(int a,int b){a=abs(a);b=abs(b);return!((a|b%4<3|Q(b))*(b|a%4<3|Q(a))*Q(a*a+b*b));} ``` Functions: * *Q*(*n*) returns 0 (false) if *n* is prime, or 1 (true) if *n* is nonprime. It is a helper function for *G*(*a*,*b*). * *G*(*a*,*b*) returns 1 (true) if *a*+*bi* is a Gaussian prime, or 0 (false) otherwise. Sample output (scaled up 200%) for |*a*|,|*b*| ≤ 128: ![Sample128](https://i.stack.imgur.com/8epa2.png) [Answer] # Haskell - 77/108107 Chars usage: in both the solutions, typing a%b will return whether a+bi is a gaussian prime. the lowest i managed, but no creativity or performance (77 chars) ``` p n=all(\x->rem n x>0)[2..n-1] a%0=rem a 4==3&&p(abs a) 0%a=a%0 a%b=p$a^2+b^2 ``` this solution just powers through all numbers below n to check if it's prime. ungolfed version: ``` isprime = all (\x -> rem n x != 0) [2..n-1] -- none of the numbers between 2 and n-1 divide n. isGaussianPrime a 0 = rem a 4==3 && isprime (abs a) isGaussianPrime 0 a = isGaussianPrime a 0 -- the definition is symmetric isGaussianPrime a b = isprime (a^2 + b^2) ``` the next solution has an extra feature - memoization. once you checked if some integer n is prime, you won't need to recalculate the "primeness" of all numbers smaller than or equal to n, as it will be stored in the computer. (107 chars. the comments are for clarity) ``` s(p:x)=p:s[n|n<-x,rem n p>0] --the sieve function l=s[2..] --infinite list of primes p n=n==filter(>=n)l!!0 --check whether n is in the list of primes a%0=rem a 4==3&&p(abs a) 0%a=a%0 a%b=p$a*a+b*b ``` ungolfed version: ``` primes = sieve [2..] where sieve (p:xs) = p:filter (\n -> rem n p /= 0) xs isprime n = n == head (filter (>=n) primes) -- checks if the first prime >= n is equal to n. if it is, n is prime. isGaussianPrime a 0 = rem a 4==3 && isprime (abs a) isGaussianPrime 0 a = isGaussianPrime a 0 -- the definition is symmetric isGaussianPrime a b = isprime (a^2 + b^2) ``` this uses the sieve of Eratosthenes to compute an infinite list of all primes (called l for list in the code). (infinite lists are a well known trick of haskell). how is it possible to have an infinite list? at the start of the program, the list is unevaluated, and instead of storing the lists elements, the computer stores the way to compute them. but as the program accesses the list it partially evaluates itself up to the request. so, if the program were to request the fourth item in the list, the computer would compute all primes up to the forth that aren't already evaluated, store them, and the rest would remain unevaluated, stored as the way to compute them once needed. note that all of this is given freely by the lazy nature of the Haskell language, none of that is apparent from the code itself. both versions of the program are overloaded, so they can handle arbitrarily-sized data. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~36~~ ~~47~~ ~~48~~ ~~49~~ ~~47~~ ~~43~~ 28 bytes Takes an array of two integers `a b` and returns the Boolean value of the statement `a+bi is a Gaussian integer`. **Edit:** +11 bytes because I misunderstood the definition of a Gaussian prime. +1 byte from correcting the answer again. +1 byte from a third bug fix. -2 bytes due to using a train instead of a dfn. -4 bytes thanks to ngn due to using a guard `condition: if_true ⋄ if_false` instead of `if_true⊣⍣condition⊢if_false`. -15 bytes thanks to ngn due to finding a completely different way to write the condition-if-else as a full train. ``` {2=≢∪⍵∨⍳⍵}|+.×0∘∊⊃|{⍺⍵}3=4|| ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/6uNbB91LnrUsepR79ZHHSse9W4GMmprtPUOTzd41DHjUUfXo67mmupHvbtA4sa2JjU1/9OAOh/19kEM6Wo@tN74UdtEIC84yBlIhnh4Bv9PUzBWMOECkQZA0kDBGEgamkI5hqYgnoIRmGMAZhsCyUPrIQqA5ikYAAA "APL (Dyalog Unicode) – Try It Online") ### Explanation ``` {2=≢∪⍵∨⍳⍵}|+.×0∘∊⊃|{⍺⍵}3=4|| | ⍝ abs(a), abs(b) or abs(list) 3=4| ⍝ Check if a and b are congruent to 3 (mod 4) |{⍺⍵} ⍝ Combine with (abs(a), abs(b)) 0∘∊⊃ ⍝ Pick out the original abs(list) if both are non-zero ⍝ Else pick out (if 3 mod 4) |+.× ⍝ Dot product with abs(list) returns any of ⍝ - All zeroes if neither check passed ⍝ - The zero and the number that IS 3 mod 4 ⍝ - a^2 + b^2 {2=≢∪⍵∨⍳⍵} ⍝ Check if any of the above are prime, and return ``` [Answer] # Haskell -- 121 chars (newlines included) Here's a relatively simple Haskell solution that doesn't use any external modules and is golfed down as much as I could get it. ``` a%1=[] a%n|n`mod`a<1=a:2%(n`div`a)|1>0=(a+1)%n 0#b=2%d==[d]&&d`mod`4==3where d=abs(b) a#0=0#a a#b=2%c==[c]where c=a^2+b^2 ``` Invoke as `ghci ./gprimes.hs` and then you can use it in the interactive shell. Note: negative numbers are finicky and must be placed in parentheses. I.e. ``` *Main>1#1 True *Main>(-3)#0 True *Main>2#2 False ``` [Answer] # Python - 121 120 chars ``` def p(x,s=2): while s*s<=abs(x):yield x%s;s+=1 f=lambda a,b:(all(p(a*a+b*b))if b else f(b,a))if a else(b%4>2)&all(p(b)) ``` `p` checks whether `abs(x)` is prime by iterating over all numbers from 2 to `abs(x)**.5` (which is `sqrt(abs(x))`). It does so by yielding `x % s` for each `s`. `all` then checks whether all the yielded values are non-zero and stops generating values once it encounters a divisor of `x`. In `f`, `f(b,a)` replaces the case for `b==0`, inspired by **@killmous**' Haskell answer. --- **-1** char and bugfix from **@PeterTaylor** [Answer] # [Python 2.7](https://docs.python.org/2/), ~~341~~ ~~301~~ 253 bytes, optimized for speed ``` lambda x,y:(x==0and g(y))or(y==0and g(x))or(x*y and p(x*x+y*y)) def p(n,r=[2]):a=lambda n:r+range(r[-1],int(n**.5)+1);r+=[i for i in a(n)if all(i%j for j in a(i))]if n>r[-1]**2else[];return all(n%i for i in r if i*i<n) g=lambda x:abs(x)%4>2and p(abs(x)) ``` [Try it online!](https://tio.run/##Tc9LbsMgEAbgfU4xG0sMppXBuKmdOhdxvSCKH0TuJCKpZJ/eBdzXCr4Z5tdwWx7jldQ6Qg3v62Q@TmcDs1gqNtd1ZugMA1sQr44tv56jZ75A8M3f5nTh/tXu3PXeJFzdqBYrU38HUuVSZ2jomGueZCssPRhx/lxgKvHg0rqx0F8dWLAEhhHaHsw0MZtcYv2y1S1i6zt0jCmcq266d017cN3j01GcoORfkj96sNy@Ee6Gn13mypzu/g@JPqpt/8243lzYqxkZt/gX0jApZKZeUAArS50J0PlrngdqWQaqvZaxWxR7T6mlCpQ6D9RZmQVmQsYhWYjovT/aFtcv "Python 2 – Try It Online") ``` #pRimes. need at least one for r[-1] r=[2] #list of primes and other to-check-for-primarity numbers #(between max(r) and sqrt(n)) a=lambda n:r+list(range(r[-1],int(n**.5)+1)) #is_prime, using a(n) f=lambda n:all(n%i for i in a(n)) #is_prime, using r def p(n): global r #if r is not enough, update r if n>r[-1]**2: r+=[i for i in a(n) if f(i)] return all(n%i for i in r if i*i<n) #sub-function for testing (0,y) and (x,0) g=lambda x:abs(x)%4==3 and p(abs(x)) #the testing function h=lambda x,y:(x==0 and g(y)) or (y==0 and g(x)) or (x and y and p(x*x+y*y)) ``` Thanks: [40](https://tio.run/##XZDLboMwEEXX@CtmE2ls3AqDoxRU90cQC0e8LLlOZKhkvp4amhQpu7n3nnlo7ss83ly@rp5bVecNt2aaSaus/r62GibeVRa9dkOHsU4FpWR6hq4ybkbH2PuZEn24Pm3R12@i4RO62NAfkbYW3clAf/NgwDjQO9F2PdxjVZFksLertuBJYnpwX/scxvKYJD5V9UsrRKhHQxuS@G7@8dF93eA3xjDz6SgZnpeESl8nDPQklSpAuzau/3MoGf8hvlQYlMp2YMCFUohTcTms8LDCrpfHpMBCurCIr3e/vagekRl6nFRjWcqMgyw@ioJyQCnKTeYXKTZZns@XKIUU@SaFLDYpszKjTUPXXw "Python 2 – Try It Online")+48 -- entire golfing to [Jo King](https://codegolf.stackexchange.com/users/76162/jo-king) [Answer] # Perl - ~~110~~ ~~107~~ 105 chars I hope I followed the linked definition correctly... ``` sub f{($a,$b)=map abs,@_;$n=$a**(1+!!$b)+$b**(1+!!$a);(grep{$n%$_<1}2..$n)<2&&($a||$b%4>2)&&($b||$a%4>2)} ``` Ungolfed: ``` sub f { ($a,$b) = map abs, @_; $n = $a**(1+!!$b) + $b**(1+!!$a); (grep {$n%$_<1} 2..$n)<2 && ($a || $b%4==3) && ($b || $a%4==3) } ``` Explanation, because someone asked: I read the arguments (`@_`) and put their absolute values into `$a`,`$b`, because the function does not need their sign. Each of the criteria requires testing a number's primality, but this number depends on whether `$a` or `$b` are zero, which I tried to express in the shortest way and put in `$n`. Finally I check whether `$n` is prime by counting how many numbers between 2 and itself divide it without a remainder (that's the `grep...<2` part), and then check in addition that if one of the numbers is zero then the other one equals 3 modulo 4. The function's return value is by default the value of its last line, and these conditions return some truthy value if all conditions were met. [Answer] # [golflua](http://mniip.com/misc/conv/golflua/) ~~147~~ 141 The above count neglects the newlines that I've added to see the different functions. Despite the insistence to not do so, I brute-force solve primes within the cases. ``` \p(x)s=2@s*s<=M.a(x)?(x%s==0)~0$s=s+1$~1$ \g(a,b)?a*b!=0~p(a^2+b^2)??a==0~p(b)+M.a(b)%4>2??b==0~p(a)+M.a(a)%4>2!?~0$$ w(g(tn(I.r()),tn(I.r()))) ``` Returns 1 if true and 0 if not. An ungolfed Lua version, ``` -- prime number checker function p(x) s=2 while s*s<=math.abs(x) do if(x%s==0) then return 0 end s=s+1 end return 1 end -- check gaussian primes function g(a,b) if a*b~=0 then return p(a^2+b^2) elseif a==0 then return p(b) + math.abs(b)%4>2 elseif b==0 then return p(a) + math.abs(a)%4>2 else return 0 end end a=tonumber(io.read()) b=tonumber(io.read()) print(g(a,b)) ``` [Answer] # APL(NARS), 99 chars, 198 bytes ``` r←p w;i;k r←0⋄→0×⍳w<2⋄i←2⋄k←√w⋄→3 →0×⍳0=i∣w⋄i+←1 →2×⍳i≤k r←1 f←{v←√k←+/2*⍨⍺⍵⋄0=⍺×⍵:(p v)∧3=4∣v⋄p k} ``` test: ``` 0 f 13 0 0 f 9 0 2 f 3 1 3 f 4 0 0 f 7 1 0 f 9 0 4600 f 5603 1 ``` [Answer] # [Runic Enchantments](https://github.com/Draco18s/RunicEnchantments/tree/Console), 41 bytes ``` >ii:0)?\S:0)?\:*S:*+'PA@ 3%4A|'S/;$=?4/?3 ``` [Try it online!](https://tio.run/##KyrNy0z@/98uM9PKQNM@JhhMWmkFW2lpqwc4OnAZq5o41qgH61ur2Nqb6Nsb//9vrGAAAA "Runic Enchantments – Try It Online") Ended up being a lot easier than I thought and wasn't much room for golfification. The original program I blocked out was: ``` >ii:0)?\S:0)?\:*S:*+'PA@ 3%4A|'S/! S/;$= ``` I played around with trying to compare both inputs at the same time (which saved all of one 1 byte), but when that drops into the "one of them is zero" section, there wasn't a good way to figure out *which* item was non-zero in order to perform the last check, much less a way to do it without spending at least 1 byte (no overall savings). [Answer] # Mathematica, 149 Characters ``` If[a==0,#[[3]]&&Mod[Abs@b,4]==3,If[b==0,#[[2]]&&Mod[Abs@a,4]==3,#[[1]]]]&[(q=#;Total[Boole@IntegerQ[q/#]&/@Range@q]<3&&q!=0)&/@{a^2+b^2,Abs@a,Abs@b}] ``` The code doesn't use any standard prime number features of mathematica, instead it counts the number of integers in the list {n/1,n/2,...,n/n}; if the number is 1 or 2, then n is prime. An elaborated form of the function: ``` MyIsPrime[p_] := (q = Abs@p; Total[Boole@IntegerQ[q/#] & /@ Range@q] < 3 && q != 0) ``` Bonus plot of all the Gaussian Primes from -20 to 20: [![Plot of gaussian primes](https://i.stack.imgur.com/W5NVK.png)](https://i.stack.imgur.com/W5NVK.png) [Answer] # [Ruby](https://www.ruby-lang.org/) `-rprime`, ~~65~~ ~~60~~ 80 bytes Didn't notice the "can't use isPrime" rule... ``` ->a,b{r=->n{(2...n).all?{|i|n%i>0}};c=(a+b).abs;r[a*a+b*b]||a*b==0&&r[c]&&c%4>2} ``` [Try it online!](https://tio.run/##DcjRDoIgAEDRd7@CZTE1ZGRtPTjoQxhrYJRsig611pBfj3w5271uUd/4pLFkEinvaMmszyqMsc2x7LqbX81qD4aREOqGZvKotq@m2nFZbFEosa6yUJQSCB1vBITN4cKqED@t6TR46XlKwLjME9ilfn/HTTv0YwAlA6l/8kK/ZZft77kIu0TbR@QndBIJPyOySdB1s0KV@A3jbAY7xdKNzvT6Dw "Ruby – Try It Online") [Answer] # [Uiua](https://uiua.org), 24 [bytes](https://codegolf.stackexchange.com/a/265917/97916) ``` =1/+=0◿⇡./+×⍥(=3◿4)∊0..⌵ ``` [Try it online!](https://www.uiua.org/pad?src=ZiDihpAgPTEvKz0w4pe_4oehLi8rw5fijaUoPTPil780KeKIijAuLuKMtQriiZHiiYMgZiDih6EgMTFfMTEK) Straightforward implementation of the condition described on the Mathworld page. ``` =1/+=0◿⇡./+×⍥(=3◿4)∊0..⌵ input: a 2-element vector [a b] representing a+bi ⌵ absolute value of each ⍥( )∊0.. on a copy of it, if it contains 0, =3◿4 change it to v%4==3 /+× elementwise multiply and sum (gives a^2+b^2 if ab!=0, a or b if it is 3 mod 4 and the other is 0, 0 otherwise) =1/+=0◿⇡. primality test ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 78 bytes ``` a=>b=>P(a*a+b*b)|Math.abs(z=a?a*!b:b)%4+P(z)>3 P=(n,k=2)=>k*k>n||n%k&&P(n,k+1) ``` [Try it online!](https://tio.run/##ZctBboMwFATQPbfoIrE/hghjo4SQT05QiSvYFFpKhKN8VAHi7KWgbqpmlvNmPs2XofLR3Puwc2/VUuNiMLeYF9z4Rljfwvxq@o@DscQnNFfjv9izhZ0WBZ8gV16BvAtajAHz1m/zbp67XbvfF1srJCy1e/ARwzgjQsaC8ZJkpevI3arDzb1zIgiEGGGbDdtsuJwyIQYgEljzAfgIVybZmUXM8/4@a56mOgKu1UkpgH@mZbpZfNTyydIkOa4mtYyfTGq1mY7WOyzf7t43qy8h9aZsQ2qmCtPf/AA "JavaScript (Node.js) – Try It Online") # [JavaScript (Node.js)](https://nodejs.org), 93 bytes, slow ``` p=>q=>8==(g=(a,b,c,d)=>(a+n&&g(a-1,b,c,d))+(1/d?a*c-b*d==p&a*d+b*c==q:g(n,a,b,c)))(n=p*p+q*q) ``` [Try it online!](https://tio.run/##LcvhCoMgFEDht8l7vbatwSCqW89iWrIRajmGPX2jsb@H77z0RyezPeO79MFOx8xH5H7lvmYGx6DVqIyyyD1o8kXhQJfVvyFBdbWDlqYcpWWOhZaWRmmY18aBV78ZEcFzlJFWueIxhw12Lu9tSiyE2rtHa4JPYZkuS3CQEiqiHU@WT5a7uiXKmBLxDBlhx0FUohE3cXwB "JavaScript (Node.js) – Try It Online") Modified from vanilla definition of Gaussian prime: there's exactly 8 pairs of complex <x,y>, s.t. x\*y=input [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 136 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 17 bytes ``` ⋏A[|ȧ:4%3=]Þ•:‹¡›$%¬ ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyJBPSIsIiIsIuKLj0FbfMinOjQlMz1dw57igKI64oC5wqHigLokJcKsIiwiIiwiWy0zLDBdXG5bMSwxXVxuWzMsMF1cblswLDddXG5bMiwyXSJd) Bitstring: ``` 1100111001011011010111100100111010100100001111100100100011010011110001011011001001101101100000000000111110011101010011001000101011000001 ``` Literal interpretation of mathworld [Answer] # Python - ~~117 122~~ 121 ``` def f(a,b): v=(a**2+b**2,a+b)[a*b==0] for i in range(2,abs(v)): if v%i<1:a=b=0 return abs((a,b)[a==0])%4==3or a*b!=0 ``` ]
[Question] [ # Task Write a program/function that when given a positive integer \$n\$ splits the numbers from \$1\$ to \$n\$ into two sets, so that no integers \$a, b, c\$, satisfying \$a^2 + b^2 = c^2\$ are all in the same set. For example, if \$3\$ and \$4\$ are in the first set, then \$5\$ must be in the second set since \$3^2+4^2=5^2\$. Acceptable Output Formats: * One of the sets * Both the sets * An array of length \$n\$ where the \$i\$-th element (counting from 1) is one of two different symbols (e.g. 0 and 1, a and b, etc.) which represent which set \$i\$ belongs to.The reverse of this is also fine # Constraints You can expect \$n\$ to be less than \$7825\$. This is because \$7824\$ is [proven](https://www.cs.utexas.edu/%7Emarijn/ptn/) to be the largest number to have solution (which also implies that all numbers less than 7825 have a solution). # Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest bytes wins. # Sample Testcases ``` 3 -> {1} 3 -> {} 5 -> {1, 2, 3} 5 -> {1, 2, 3}, {4, 5} 5 -> [0, 0, 0, 1, 1] 5 -> [1, 1, 0, 0, 1] 10 -> {1, 3, 6} 10 -> {1, 2, 3, 4, 6, 9} 41 -> {5, 6, 9, 15, 16, 20, 24, 35} ``` A checker to verify your output can be found [here](https://tio.run/##hZDNCsIwEITveYoRL4l/kIgXwavgYwRNNaVuQxIFn75uQ9WKBw8Lw@zMlyXhkS8trbtuigOFW8a@jVebt2IK4ql8TBnJ8QR7dKyCiza7kxCEHTxl6fuaVEqIpNnirCy2QtVGeM5giKxSaHyJJjMko6Wzk3oBwhxaKSyRNJM@KMxmMB9U0tx@13@2hs@4l7JtGvnaz1EXoUBtLjmOjJBF14P2FduTHWrFJPOf9PX8iGTGJBFi/yn9aZZOYLDquo3QME8 "Python 3 – Try It Online") --- *Inspired by [The Problem with 7825 - Numberphile](https://www.youtube.com/watch?v=1gBwexpG0IY)* [Answer] # [J](http://jsoftware.com/), 37 bytes Brute forces through the possible sets, outputs the bit mask. ``` ((-&.#.+./@,)[(e.~+/~)/.*:@#\)^:_@#&1 ``` [Try it online!](https://tio.run/##DcNBCoAgEAXQfaf4JJiTOmbLiUAIWrVqW9SqoA7h1a0H7y01NzdGQQOHDvL3jGld5mKM16zYckiONnNxtiFT4FaS2umQMykdC5XK4MbwV4iweJjQdx8 "J – Try It Online") (Also outputs list as numbers for easier comparison.) ### How it works ``` ((-&.#.+./@,)[(e.~+/~)/.*:@#\)^:_@#&1 #&1 convert to list of N 1's ( )^:_ do until list does not change *:@#\ right: convert to 1,4,9…,N^2 [ left: the bit mask /. partition left based on right, for each set: +/~ make M*M addition table e.~ any element of that in the same set? +./@, OR all answers: 1 on conflict, 0 if finished -&.#. list: from base 2, subtract that^, to base 2 ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~132~~ 116 bytes ``` {1}.SatisfiabilityInstances[And@@(And[Or@@#,Nand@@#]&/@Map[x,Select[#~Tuples~3,{1,1,-1}.#^2==0&],{2}]),x/@#]&@*Range ``` [Try it online!](https://tio.run/##FYzLCsIwEAB/RQgUldU@9FpYjx58YL2FCGsaNdCG0kSohPbXY3qZw8BMS@6jWnJaUrj22jgefD5uq2jsS9NTN9r9jsY6MlJZfjA14jKSX3pEBmeaBRNJiifq@ACVapR0nE33b9coO@3A55DDJj7ZoyjLLBHgi1GsYEjnDtc3Mm8VcLHPRPgD "Wolfram Language (Mathematica) – Try It Online") This uses Mathematica's SAT solver to label the integers 1 through the input as `True` and `False`. * This is composed with `Range`, so what feeds into the main function is a list of the integers from 1 to the input. * `Select[#~Tuples~3,{1,1,-1}.#^2==0&]` generates all the Pythagorean triples (multiple times actually, but that's okay). * `And[Or@@#,Nand@@#]&` is true if at least one, but not all, of the elements of its input is true. * `{1}.SatisfiabilityInstances[...,x/@#]` uses the SAT solver. Since `SatisfiabilityInstances` returns a list containing one solution, we use `{1}.` to get its first element. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 18 bytes ``` œc3²SHeƊ$Ƈ ÇŒpÇÞḢQ ``` **[Try it online!](https://tio.run/##y0rNyan8///o5GTjQ5uCPVKPdakca@c63H50UsHh9sPzHu5Y9B/Eebhzxv//RiYA "Jelly – Try It Online")** (too inefficient for \$n>25\$ on TIO). ### How? Strategy: Find all Pythagorean triples using \$[1,n]\$ then find a way to pick 1 element from each of them such that the resulting set contains no Pythagorean triples. That way we have a set which both contains no Pythagorean triple and blocks the other set from having any. ``` œc3²SHeƊ$Ƈ - Link 1, find all Pythagorean triples: list of integers OR number œc3 - all combination of length 3 (given n uses [1..n]) Ƈ - keep those for which: $ - last two links as a monad: ² - square each of them Ɗ - last three links as a monad: S - sum (of the three squares) H - halved e - exists in (the squares)? ÇŒpÇÞḢQ - Main Link: n Ç - call Link 1 as a monad -> all Pythagorean triples using [1,n] Œp - Cartesian product -> all ways to pick one from each Þ - sort those by: Ç - call Link 1 as a monad (empty lists are less than non-empty ones) Ḣ - head Q - deduplicate (if n < 7825 this is a valid answer) ``` [Answer] # JavaScript (ES6), ~~118~~ 117 bytes Much slower for -1 byte. ``` f=(n,a=[],b=a)=>n?f(n-1,[n,...a],b)||f(n-1,a,[n,...b]):[a,b][E='every'](o=>o[E](x=>o[E](y=>o[E](k=>k*k-x*x+y*y))))&&b ``` [Try it online!](https://tio.run/##ZchBC8IgGIDhez9k06XSgi7BZ6f9CvHwuVzUho4thsL@uwl5id7LC88LN1z75Tm/ufN3m9IAxDEEpZkBpCDdbSCOt0w5JoTAzHTfv4QFjaZXhcxo1UFtN7vEWhMP0qtOk1Aey0eQYzPy0IRjbCLNVZVJvXern6yY/IMM5ELp4Vfa0x@dM6UP "JavaScript (Node.js) – Try It Online") --- # JavaScript (ES6), ~~122 119~~ 118 bytes Returns one of the sets as an array. ``` f=(n,a=[],b=a)=>[a,b][S='some'](o=>o[S](x=>o[S](y=>o[S](k=>k*k==x*x+y*y))))?0:n?f(n-1,[n,...a],b)||f(n-1,a,[n,...b]):b ``` [Try it online!](https://tio.run/##ZcyxDoIwFIXh3RehraUBowvJhYdgbDrcIhgt9Boxhia8eyWxi@Esf/IN54EfnLvX/fnOPV37GAdgXiJoIy0gh1qjtEa3kM009ZlhBDXp1rAlNaQ6qJ1wAItYjkEEvq0pKt8MzOel1F4qpXA75ev6I0xoDa9s7MjPNPZqpBsb2IXzw7@UxY5OezpvFL8 "JavaScript (Node.js) – Try It Online") Solution found locally for \$n=41\$: ``` [ 5, 6, 9, 15, 16, 20, 24, 35 ] ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 14 bytes Port of the 17 byte Jelly answer. (`Læ3ùʒDnO;tå}€н` is the same length) ``` Læ3ùʒnRćsOQ}€н ``` [Try it online!](https://tio.run/##ASEA3v9vc2FiaWX//0zDpjPDucqSblLEh3NPUX3igqzQvf//MjQ "05AB1E – Try It Online") ## Explanation ``` L Length range æ Powerset 3ù Pick truples (length-3 tuples) ʒ Filter: n Square all items R Reverse the list ć Head-extract (head on top) s Swap O Sum the remaining list Q} Equal? €н Take head of each ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~30~~ 26 bytes ``` œ|/L=³ Œc§œ& ŒP²ÇẸƊÐḟŒcÑƇḢ ``` [Try it online!](https://tio.run/##y0rNyan8///o5Bp9H9tDm7mOTko@tPzoZDUgI@DQpsPtD3ftONZ1eMLDHfOBMocnHmt/uGPR////TQE "Jelly – Try It Online") ## How? This does a more brute-force approach, filtering subsets of `[1..n]` based on whether they contain any Pythagorean triples. Then, it finds two triple-less subsets that have all `n` elements between them ``` œ|/L=³ # Test if a pair of sets unions to [1..n] œ|/ # Set intersection L # Is the length =³ # equal to n? Œc§œ& # Does a pair exist that sums to another? Œc # Compute all pairs of squares § # Sum each œ& # Set intersection with the set of squares (nonempty & truthy if a pair of squares sum to another square) ŒP²ÇẸƊÐḟŒcÑƇḢ # Main link ŒP # All subsets of 1..n ƊÐḟ # Remove those where: ² # of the squares, ÇẸ # a pair of the squares exists that sum to another square Œc # All pairs of these triple-less subsets ÑƇ # Filter the pairs by whether they union to [1..n] Ḣ # Head; get the first one ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 1664 bytes works for all n (1 to 7824) instantly ``` IntegerDigits[Uncompress@"1:eJwllsmRHDkMRXWVGfIAKwGYoKtMGAfG/5veT0V0dHVlkiDwN/av//7/87t+/vjhPfem6tm+K6+yqFft5e/e9fXzeH6W62050307NdsTzYtIe/mMApOd/mJY5G/Yn9FdxidPe95uu/lGRNu2+U2n1c6zypfbWza7m80S99pKerF625V9oeNuzW1ywnt92jfZUcXbV94eHrael5Evyo1vHazcy3LPpOa7fXNlmW6d0xF0QXvLBHP+ikf2mKuDBp+1v94BBtvQlEDVdrdRfES8pIPsR1mmfAOUUXdeN2f8DvZzxNFc64c5VWJjPGie0rHls/TaOo4TmoGXtwx4Ry/rHzwDEtbwMwYbMDW2xhkvg18BoPva04zBJqAwisL+AbcLa34OLdSBUGpa1VlDJp3G2wqtA+zTgmz4sTh7YxCVN1RCFYy7x3z5ivIghVhm/s3vBxM6F1S0KJO5k8GpRiuMbRCaRT1eF1NoRSGflb7OUYgJJSYNOoRzyIDMLEaCQgAxNFWsRkq5zPxGDYZLewakSRvgCRNrcJ92EFzis1FSIhnoZ8pYZ3HeA4TJfUwq+RiyB478gA7UA7QgUxl05yvcKDHgOonYOcLfciywwgKLC+ICNSWqFNaLYFEzQ6ANmsEBJ96ZhnEwE5prPX06RBYD20FJPVk6EyrYfOoK3dnniG+kCBBbCY1Ra/FGBfDtMzB/vEItgKMRAYiHqDREkghhA5KiC6jFTp8nGAycUCi+dg6B4ZdSGxMVXb8bGWLYOgQDzFe0fG3wztNPk/edjBV6v5m1uOgvMKCxOwBWtr5OoAYuFmUyTAkdkiNoytgrx32iBDDEjzsfsdQJltIFFnaAQztkUigpUtSiG+Y98Jz56Ejgv0eXhBAiwhtKBVYjqpJdqB8KHPQN60QCRj+gnFWejUKLrUQAuHIcwmUh/sQAYIqxlBAGcHCF2S+pCdPsY/hHMAZKEVBCn9AUeyB0wEcZZClbIEmXLkyZ5YMM5dSobQkJQbjyQoYAE4J05LbAcwpAlJQu8VIKW4M4PsccBJFi4TxOPiyRKUJMcc7LIO1JVgWiwpHoIWA4oTj0Ri2yAqsiQZS6Cm9QIXpLtwCGIU0lb3TzkcyM0iEvsA5mHPLi5OPH/SBx4zj6IeMfwxnC/HQ68ouCiGBS42nw6ErC/eIaJYEQoHIWgIFRSo7QA2ZomqcKfSEKyDdKcsUXPXAlYNf40HqfbCBMzgKVc5pFvs6nxodtJ9xV9+kOITFIVFAfdYMAWrfQY03joC+08pt2kZgpz584m4EWhA4x/I0WHNjo7xBP4ifFGfgf3VIIueRHe0jyaL+rkQhEk6xGhpXi8LlBu4YBYYyAnaAHw1MeBRUXMLoAfK5S3IfisZWE+7jYKN4EGG2SlkBlKICHzEOaLxFKWuMImiBA0bLMAi3IBR/wUNnByvhCD1uTcsJLN04oGBu9SaKGlJFAKs24krEs9NKZ7h0oxTkMTAYUyjn91xAKWMCFv8CZyock+EGWMjCutNANrdZOqY0Z0T66Yr2oJswJ+FBaKHORK8sOAbUuruSWkR5gRbZoLuYPer7CORkDULwUjQgHD++RLKBOR0p3EkvGh0VG4pbCOyt+QBs99V9DtuSl",2][[;;#]]& ``` [Try it online!](https://tio.run/##DdFXDqRWAkDRrYw80vxgCYoCCmxZ8nvknAooaPUHOYciw@Z7egf36PbxWuV9vNZp/Kv855c8rHmZz1xd1uvywxvSsZ/mfFn@/ePxV64cXbf0jsS1uvMJfLGQgXqI4aiuuggKESX3/I35WCb5XVtzh4HGO4q@UPq1IujeVFaR99TaIyqFXF@hWMkczZnic@cSFVA4RmJP7GVky/sOVzlHex1MZob2SkiKaDgwQnbWmZUz5LahnegYG454@PBIqfuaiiS441dPYy7DTGo@CxRO@syYG9sdPK5jWBm8KSIv/SQ@Q@TSHOcdye/X@Nil@E6vp2ZNZvwqPkbXB1SGnQJmf3YNShZStwXeqxsHJ@SxMwSE6253POdnc@YUvEtPsrU4j74vgOl5nyw38ILm9ug@DSGliJT0A6WxxDrHZqlb0HdsjsS7H8XPepyEc6GzdB8cvyaHfoSJzgX4WbV7@aDhaO0xRtxQ@YKjXjQEJKkWPwlTy1zoiVP88DtOmZ4ifnxXgNzvsr@J5V29wpP1jYfDCuH1Op83We9yWflVjy7PHZ46JTxcTFVMsqXFyak3PXHY2Hk/cuFhjI4rFl3yMr2wVBQ3NMzRuS@Z0zU@Zu0S/CYFi9N@yds6RS6MtPyIW9fZS9Yx5lRhcF646@UhuHI1jBE9hdFTygHxVgrv@CJOfUHiRZfg5YGXXXpnh5HXnqqcVJrjEJqpVqT1dRylqrGIzBpu8BWMWAsF/rYpYPQLDxWGiqqBP3hymq0PRjkw5HBMUCy/pfhrDgtzVJ/ZMNQi0rIQJmz4cGJUEGHBrfoN0Z2X11LVHRDW0pdz@LasKkCqNUs1wnuiBxFcqcfWSFZSkIgyVzx1/5PQiRhooVna3C3kWCE@j3s1rBbNswb61E72j80sd11lT/OAwTqT5gjCTei96w3arK2N8VrL@XziNeQ4vrmXYslspVtlQRhiYN9r69Xl5K3u7@yQoZWbpPim3LH8U0FQH9WqQj9svpOSfSGtSpZtUJjNOg1SDkKQN56qzZ4NNklOj96r0MUGofw9OwjEVGIF3EUmNrOWEK0kHUQq70N2YICXXxA7@DSK2C6R@f6jtVdEhrpOZu6Y2K1iJ81ljyHgCQUjtQSkxwQ6xd5oX1YDQiesJU2hItTE@zSt@nJUT9HT9KXJ5kPxy6A@JmmUA0CM7wZzavwC36W2I5die8aWP5O2Hqwoe1iXPN93m146VvP7AshesrSaNC0JdeFJ3A0l53pxnAOLSjZFjxtbi9Al8OGg@JlFczlWQt4eJTkoZcFxx5cN8Gjsv6lauLx6cZmaLt7H@oAuNAoCk75FwkL9LlU/JSdhX6jhHLNVYU6fQVpTfguyL4AiC3UQzIUdYs9mZBGMnla8jcrpJmmiJ/igAsSJylggGc34OqFF1IUgFmXx9GV5yx0px5or1pC5tSu@pU6xmj41rXVwI0IYhhf4vV06HnoOHe@jayMoVNJ9ykW9RAGPvJpQNQheFHG3a2Gnyqx082asnYIabLrc1xBgiaaD@ilDBz08Y4DXXrHcY3uni6IZGDGKcGPcWBU7RQDqghPtzC@MoUavChvPd6u/QehdzcA8TqAGOivsNBtdY9oivBjoDbutBjDmLDK/IRZhb4oKZ3xUlkNBBBirkumo9GKCxNvmzQ1ahyydJBq1LbTy@cWaTst52uE1dilxCOJoKjQdbHry7S5WmC8SU8Ka14rYcGEYn@HWze3@@BP/@ePH33//9@fP//2y5npY//Nv@eNF48TPX7/@Dw "Wolfram Language (Mathematica) – Try It Online") [Answer] # [R](https://www.r-project.org/), ~~99~~ 95 bytes ``` n=scan():1 f=function(j)outer(a<-n[j]^2,a,`+`)%in%a while(any(f(i<-sample(!0:1,n,T)),f(!i)))0 i ``` [Try it online!](https://tio.run/##DcdNCoNADAbQvbdwISQ0glO6cvQW3YliEIdG9FP8ofT0U9/u7TGiPgYFcel8qMOF4bQVNPF6neNOWuVoprZ7ikr/6DkzZOq/H5tHUvwokFX5oct2Py1KJ5A3swRKjZkLb/HlkgSNtfEP "R – Try It Online") Outputs a vector of `TRUE` and `FALSE` representing in reverse order which set each integer belongs to. (The footer of the TIO transforms this into a list of integers in the first set.) Works by random sampling: repeatedly draw a random subset of `1:n` until neither the subset nor its complement contain any Pythagorean triples (checked by the function `f`). It will finish in finite time for any input <7825, but will in expectation take a very long time for largeish `n`. TIO starts timing out around `n=90`. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 74 bytes ``` NθFθFιFκF⁼X⊕ι²ΣX⊕⟦κλ⟧²⊞υ⊕⟦ικλ⟧≔⁰ηW¬ⅉ«≔Eυ§κ÷ηX³λζ≦⊕η≔Xζ²ε¿¬⊙ε⊙ε№ε⁺κμI⁻Eθ⊕κζ ``` [Try it online!](https://tio.run/##bU87a8MwEJ6TX3HjGVToa@tk0g4eEgydSumg2kokLEuxHkmb0t@uniIXGqhAnMT3vE5y11muU2rMPoZNHN@Fw6l6WG6tA3rAeap5DvN8miLXHlt7JHZjOidGYYLoicjglu5zHP9BXwcG@u1MoQNt9BIjgwuKYlBY1KH2Xu0MXjOQ9DtKpQXgxgZ8waz/Wi5mxprvs1EdGtOLDxyyZ3hUB9ULlAxKkzuyzbkMTuS2IM2s/pNfkn5ti@5UVhIZUNtSoDafKCiwjJWNJuRHq6PP6WNVlQ2dImDFfcC1MoTlotPlxkNpRO7fKd3fpKuD/gE "Charcoal – Try It Online") Well, for `n<50`, otherwise it gets too slow. Link is to verbose version of code. Based on @JonathanAllen's answer. Explanation: ``` Nθ ``` Input `n`. ``` FθFιFκ ``` Loop through all potential Pythagorean triples. ``` F⁼X⊕ι²ΣX⊕⟦κλ⟧² ``` If this is indeed a triple, ``` ⊞υ⊕⟦ικλ⟧ ``` then push it to the empty list. ``` ≔⁰η ``` Start iterating through the ways of picking one element of each triple. ``` W¬ⅉ« ``` Repeat until output has been generated. ``` ≔Eυ§κ÷ηX³λζ ``` Pick one element from each triple. ``` ≦⊕η ``` Increment the loop counter. ``` ≔Xζ²ε ``` Square the elements. ``` ¿¬⊙ε⊙ε№ε⁺κμ ``` Check for Pythagorean triples. ``` I⁻Eθ⊕κζ ``` If none, then output one of the sets. ]
[Question] [ You are the roughest, toughest, coolest cowboy west of the Mississippi. However, some weird guy on a wacky nerd website decided that it would be cool to plop you into random unfinished landscapes and fight. No matter, you'll still win. However, to help you win those grueling gunfights you'll write home about, it's helpful to know how many bullets the coward lurking in the landscape has. How about you help this poor guy out. Given an ASCII landscape, find the gun inside it and tell him how many bullets are loaded into it. This is the gun: ``` (X) (X\ /X) (XVX) \X/ ``` Each `X` in the above picture is a potential slot for a bullet. The slot will either contain a space or one of `0,O,o` (may not be consistent - the cowboy may have loaded different types of bullets in his gun). There will always be exactly one gun, matching the above description, in the landscape. However, please note that the spaces around and inside the gun can contain anything. # Input You will be given a string containing printable ASCII (so not tabs) and newlines to separate lines. You may also take a list of strings, if you wish. Strings will all be padded with spaces, so they will all be the same length. The input will be at least 4 rows high and 7 columns wide. There will always be exactly one gun in the landscape. # Output You will output how many bullets (`0, O, o`) there are in the gun, so your output will always between `0` and `6`. # Test Cases ``` (0) ( ) (o\ /o( \ / ) (oVo) ( V ) \o/ \ / 0 ---------------------------- //////////////////////////// //////////////////////////// /////////////(o)//////////// ///////////(0\// )////////// ////////////( Vo)/////////// /////////////\ ///////////// //////////////////////////// ---------------------------- 3 ()()()()()()()()()()()()()()()()\)/)()()()()()()()()()()()() ()()()()()()()()()()()()()()()()(V)()()()()()()()()()()()()( ()()()()()()()(\0/)()()()()()()()()()()()()()()()()()()()()( ()()()()()()()()()()()()()()()()()()()()()()()( )()()()()()( ()()()()()()(o)()()()()()()()(00)()()()()()(( \(/0)()()()()( ()()()()()()()()()()()()()()()()()()()()()()(( V )()()()()() ()()()()()()()()()()()()()()()()()()()()()()()\O/()()()()()( 2 ------(0)--- ||||(0\|/0) -----(0V0)-- ||||||\0/ -------_------ |||||||-| ------|-| |||||||-| ------|-| 6 00ooOO(0)/\\/V ( ) ( \\/ ) ( V ) \\ / 00OOoo()()()()))) 0 (\) (0) (0\\/0) ( \0/ ) (0V0) ( V ) \\0/ \ / 1 (left gun is invalid because of the `\` in the bullet slot) -00(0)00\0 -(O\0/o)\ - (OVo)o\0 -o \ /oo/ 5 ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins. [Answer] # [Snails](https://github.com/feresum/PMA), 71 bytes [Try it online.](https://tio.run/##NYmhDsMwDAV5vsJjNomtcoN9wVjQU6S2aNKUgaoaSPPt2Qx27O6Otj5fx5z3BF0dsnxQvAMneOwO3UJ28DLOW@e2XfnKLYvXt9eHV6s0@r@OSnMSMYQCNklsgJoQE0xJ0i8Wi81UQhE5AOkX "Snails – Try It Online") ``` A \/a=\)2w\V={\\u\(}c=\/b={\\c\(2}u!{(nb|.|.n.)=^o=^O=^0^ }{nb|.|.n.}^ ``` [Answer] # Mathematica, 170 bytes ``` Catch@BlockMap[b="O"|"o"|"0";MatchQ[#,p=Characters@{" (X) ","(X\\ /X)"," (XVX) "," \\X/ "}/." "->_/."X"->$;p/.$->b|"X"|" "]&&Throw@Count[Pick[#,p,$],b,2]&,#,{4,7},1]& ``` Takes an array of strings/chars. Returns the number of bullets. [Answer] # JavaScript, ~~215~~ ~~211~~ 209 bytes Thanks to Shaggy for -4 bytes! ``` f= i=>[...i].map((_,x)=>eval(String.raw`a=i.match(/(\n|^).{${x}}..\(${Z='([oO0 ])'}\).*\n.{${x}}\(${Z}\\.\/${Z}\).*\n.{${x}}.\(${Z}V${Z}\).*\n.{${x}}..\\${Z}\//);a&&alert(a.filter(i=>/^[oO0]$/.test(i)).length)`)) tests = [[" (0) ( )\n(o\\ /o( \\ / )\n (oVo) ( V )\n \\o/ \\ /",0],["----------------------------\n////////////////////////////\n////////////////////////////\n/////////////(o)////////////\n///////////(0\\// )//////////\n////////////( Vo)///////////\n/////////////\\ /////////////\n////////////////////////////\n----------------------------",3],["()()()()()()()()()()()()()()()()\\)/)()()()()()()()()()()()()\n()()()()()()()()()()()()()()()()(V)()()()()()()()()()()()()(\n()()()()()()()(\\0/)()()()()()()()()()()()()()()()()()()()()(\n()()()()()()()()()()()()()()()()()()()()()()()( )()()()()()(\n()()()()()()(o)()()()()()()()(00)()()()()()(( \\(/0)()()()()(\n()()()()()()()()()()()()()()()()()()()()()()(( V )()()()()()\n()()()()()()()()()()()()()()()()()()()()()()()\\O/()()()()()(",2],["------(0)---\n||||(0\\|/0)\n-----(0V0)--\n||||||\\0/\n-------_------\n|||||||-|\n------|-|\n|||||||-|\n------|-|",6],["00ooOO(0)/\\\\/V\n\n ( )\n( \\\\/ )\n ( V )\n \\\\ /\n\n00OOoo()()()())))",0],[" (\\) (0)\n(0\\\\/0) ( \\0/ )\n (0V0) ( V )\n \\\\0/ \\ /",1]] alert = x => i = x; tests.forEach((t, index) => { i = 'Not Found' f(t[0]); document.getElementById('a').textContent += t[0] + '\n\n' + i + '\n\n'; if (i != t[1]) { document.getElementById('a').textContent += 'Failed test ' + index + '! Expected ' + t[1] + '\n\n'; document.getElementById('a').style = 'color: red' } }) ``` ``` <pre id="a"></pre> ``` Basically, tries to match a gun `n` characters after a line break, for `n` from `0` to the length of the string. [Answer] # Python 2, ~~219~~ ~~224~~ 227 bytes ``` import re f=lambda s:sum(sum(g>' 'for g in m.groups())for m in[re.match(r'.*@..\(X\)..@\(X\\./X\)@.\(XVX\).@..\\X/.*'.replace('X','([0Oo ])').replace('@',r'[^\n]*\n.{%d}'%i),'\n'+s,re.DOTALL)for i in range(0,s.find('\n'))]if m) ``` EDIT: Fixed a bug which cost me 5 bytes :(... found 3 bytes of extra `r''`s that weren't needed. And then Grrr!! Was not counting `\` chars in my code correctly, so added 6... Takes a string with newlines; retuns the number of bullets found. Basically, applies a regex that looks for the gun pattern with 0, 1, ... lineLength characters of pad at the beginning of the lines. [Answer] # [C (gcc)](https://gcc.gnu.org/), 357 351 bytes ``` #define M(F,C)F(i){i=s[i]==C;} b,i;char*s,c;M(L,'(')M(R,')')M(A,'/')M(D,'\\')M(V,'V')B(i){i=b=(c=s[i])==32?b:c==111?b+1:c==79?b+1:c==48?b+1:0;}(*t[])(int)={L,B,R,L,B,D,A,B,R,L,B,V,B,R,D,B,A};main(j,v,k,l)char**v;{for(s=v[1];s[l++]!=10;);for(;k=i,s[i++];){for(j=17;j--;)if(!(t[j])(k-=j==13?l-3:j==8?l-5:j==5?2:j==2?l-4:1))break;b=j<0?putchar(b+47):1;}} ``` [Try it online! (golfed)](https://tio.run/##nVRRj9owDH7Pr8hpD3UgVVLgxI0sQtyhezpU6R76QtBEO7gVGJmAsYcrf32dUwoqSLBjieQ4/mzHsWwn/luS5Pmnb5NpupzQATzzJ/YMKXtP9XqYjrR@UjsS81Ql38er2ponagAv3AOPDeCVe8ydPe4Jd/a5Z4xjIu5FHnvcu4k1JIUvpnWz0Y07idZBEHTjeuDY9ucD13ooOKl2UNsMRwzS5Ybp9xf@yF@5o33eO/JRwfWR9nbqxzhdwoxv@ZwvWBFobavep3YFa70dBiO1Hi7q9dGdDqRiysnVXKccg0KpYoXmTAdtNfN9xdIp3MFmOMMI5r6eYbTN7sJvdpB7QObeMffdhjsaeG91Asbi1WQ8V7GefZHdn782LgaI66026wRqt8vznFKQjCKlSAlYQ4UFipQyQsFGliEUIUgoNVagpsNo7l9ZRFxZN4Bg2SUQpBEY4gVLjPjE9NQtfuDjAV37Zw7s@jZMXMTIv4whugydGxspGHx0E2A3bXrZ2J7rSlm9YSGBkP/7clF3tyTsNPehqFzLesVaR4qFnuHCGspEUfykBCMHl2iWYVIpPaK@/7Ws7j2a@VkVPV6vormU1oYhhiGMEZFToOeLlM1YkWAejajKSNmUVYkpGvPEz7lnKcPQ2kNScLn2N3s3xRggmBPjcoIvyv0IcEkp5sN@CJhDVsoxICUaSmkk8SFEzDKDn6YQYgdaJ7VO0@Lk@JNMF@O3de7//gs "C (gcc) – Try It Online") [(expanded)](https://tio.run/##nVRbb9owFH6Of8Wp9oANjuL0onZkaOpF3UurSNXEC0FTEgIE0rjKha4q/PVlxyalAQnWzpFO7HP5js/nY4fmJAyryrLgRyIDP8mhzKMRBC8wKVMoorzISZwWEHCIHRJO/QzaOYfQIUTFlOmTnxW135dRNI7TCO7pLb9mcEtjBq@QRUWZpZAP4mGvd@3AitzTO96iLYaTB95ienLJW5ae3PCW5@lZn7f6OFF5rsokidZpyJWGJUaNG0APiGHQEP8qB4NeD06O4TsEXdSHanl6oZYde6M4/9pQ4Nq27XeFcMjqrTrQJcVFLFNC28VgyCiywXqvd/yKP3Alb/jlZt7XsxuUlytk6NGPUzrjCz7nCdPktdsLBwjuHuFvoiLKHhVhiRZROimmxBjLjOZYzGIwM@2hg0Ulnc7wqGcLhznE0KE/sxfAfY3idAK@Pim/gMgPp4DK6DdKKKYRPGVyEY/wOPMiQ9c1tgNzRI@5YguBHUYM3I9CvZNyDuiiYxUodoGiXGXR4Pqs5Vjb34nhEPjh/NnPRjniqBQzTGCfOzAzTQVvGPGYHtFiMEP65mDqAzOMmToJ@wSJT8yT7rvqQmvOGpoz1Bw31sfa47S7xrF1CgZBFvlzZF3X4qbJC8Rj8JOksdV1o0JehmEUITEcKVLdrQpKy8cgylR5ge42VYxqrhl8A4EJn8pCnSANOqfnrAs2nsUKG6WqKgAqGKAElIRKDyxJASUwAlT2JUNTH40EwJMWeiobVOaBgf23f3zCSCXbZ6TCQ6LYnkjc8VboNiwW8PENHaqzouzw5zFrr438K5j295t2gz1hMfrRj1D2qQ/2B8tdXyGaK2wkaon/zaz77jOEbXPvWo1l3a/Y6yix0Zc4sIeWlm5@Uhv7ylxbl0skFWBjNc1fdXevrUtz2bRulgetlRBSui5uw/I8q68cYHeQ@jI2NMijZzV1pL6UTY2nL@YWzi6yEK4r5RspONT199Yw@hkgyImnOMGMYv0EKFL0@7B@BLw3VupnQAgMFMITxKQu2iTzsGigLt5AqbRSeUp8Of6E48Sf5JX5/Bc "C (gcc) – Try It Online") [(357 golfed)](https://tio.run/##nVRfb@IwDH/Pp8h2OtUeqZKOTdstF6H90Z6GKu2hLwSdaAe7ArecYNo9UL76ek4pqCDBbZdIjuOf7TiW7Sx8zrKy/PI0HOUvQ96Fe3GL95DjIjfzXt435lYvWSpynf0czE7mItNdeBABBNiFRxGgP69FIP15JwJrPZOIIAnwZuUmNZBVvtCY9mknvcqMiaKok7Yiz158W3NnlxWn9BJOXnt9hPzlFc3iQdyIR@Hpnbje8EnF3RG9Xupfg/wFxuJNTMQUq0BP3vRi5GYwN2@9qK/nvWmr1T8ykdKovVxPTC4oKJJqrDRTE4mxiS70OAw15iM4gtfemKKYhGZMEbc707B9RdwlMeeeOe@c@uOU7mdXEWI6Gw4mmizH3xX@nlH0Izj@@nQs0jBCvVyysiw5B4WcKCfKwFkuHXCiHBkHlzgkKCGQcW6dJE2P8TI8sJg8sD4BgsN9ICgrKcQ9lhTxlum2W/rAxwM69M8S8PC2KPdi7F/GkOyHdo2tkggf3QzwU5vvN3a7uko1b1RIINX/vlzV3WcStp37WDaudb1SrROlQi9oUQ0Vsip@VoOJh2u0KCipnG/QMPxRV/cKLcKiiW6uB9FSKefimMKQ1srEK/DdxepmbEgoj1Y2ZaxuyqbEVo255WfXs1Jx7Nw6KbR8@9uVm2oMMMqJ9TmhF9VqBPikVPNhNQTsOiv1GFCKDJWyioUQE@bQ0qc5xNSBzkud13Q0Od6z0XTwPC/DP38B "C (gcc) – Try It Online") [(357 expanded)](https://tio.run/##nVRbb5swFH7Gv@K00xQ7NcL0onZl0dQ26l5aIVVTXkI0ASEJCcUTkHRVk78@dmxoSiIla2ckY5/vXD8fOzTHYViWlgXfExn4SQ7zPBpC8AzjeQpFlBc5idMCAg6xQ8KJn0E75xA6hCibefrLz4pa79MwGsVpBPf0lt8wuKUxgxfIomKepZD340Gnc@PAitzTO96iLYaLB95ienHFW5ZedHnL8/Sqx1s9XKg41/Mkiaow5Fq7JUbtN4AOEMOgIf5VDAadDpwcwzcILlEequ3phdoe2WvB@ZeGAPe2bb8JhENWr9WBLikuYpkS2i76A0aRDdZ5uePX/IGrucuv1uueXnVxvlohQ49@nNIpX/AZT5gmr91eOEAwe3TfjYooe1SEJXqK0nExIcZIZjTHYhb9qWkPHCwqOToaHHRs4TCHGNr0R/YMmNcwTsfg65PyC4j8cAIojH7jDMUkgl@ZXMRDPM68yFC18u3ADL3HXLGFjh1GDMxHeb2Tcgaoom2VU@wCRbmKop3rs5Yjjb8RwyHww9mTnw1z9KNCqDOxOUzV79yBqWmqKIYRj@gBLfpTZHEGpj43w5iqA7FPkP/EPLl8E11oyVlDcoaS48b@WGucXlZ@bB2CQZBF/gzJ1yW5afIM8Qj8JGlkXPUr5PMwjCLkhyNTqslVXen8MYgyVWWgm07VhHlP4SsIVumN6OHn4SEPTFsdyAq7pSxLAIo4zoAzodIDS1LAGRgBKnuSIdRDkAB40kJNhUFp7hnYhLvHB0Aq2S6QCg9pYjssMeMN0023WMD7E9pXZ0nZ/s9j1k6M/MuY9nZD28aesBh970co@9AHu43ltq4QzR02ErXE/0bWffcRwja5d63Gtu5X7HWcsdGXOLCHlpZuflKDPQXX6HKJpAKsUdP8WXd3hS7NZRNdb/eipRBSui6mYXme1VMKsD1IfRkbEuTRs5oyUl/KpsTTF3PDz7ZnIVxXyldScKjr71Vu9DNAkBNPcYIRRfUEKFL0@1A9At4rK/UzIAQaCuEJYlIXMck8LBqoizdQKqlUmhJfjj/hKPHHeWk@/QU "C (gcc) – Try It Online") I wondered how bad a solution would be in a language without built-in pattern matching. It came out a lot smaller than I feared. Basically, this approach breaks the gun down into a series of individual parts it expects to see in specific locations relative to a specific index. If all parts are found where they are expected, it's a gun! The bullet test increments a global counter to keep track of how many bullets were in it, which we print when we have found the one and only gun in the landscape. *Note 1: I padded the test cases with spaces to ensure consistent row widths.* *Note 2: Add 10 bytes if you don't like the [assign instead of return](https://codegolf.stackexchange.com/a/106067/71661) trick. For clarity, I used actual return statements in the expanded code.* ]
[Question] [ > > An [**emirp**](https://en.wikipedia.org/wiki/Emirp) is a ***non-palindromic*** prime which, when reversed, is also prime. > > > The list of base 10 emirps can be found on [**OEIS**](http://oeis.org/A006567). The first six are: ``` 13, 17, 31, 37, 71, 73 ``` However, due to the reversal rule, emirps are different in each base. For example, the first six binary emirps are: ``` Bin | 1011, 1101, 10111, 11101, 101001, 100101 Dec | (11 , 13 , 23 , 29 , 37 , 41 ) ``` ...and in hexadecimal, they are: ``` Hex | 17, 1F, 35, 3B, 3D, 53 Dec | (23, 31, 53, 59, 61, 83) ``` Fun Fact: there are no emirps in [unary](https://en.wikipedia.org/wiki/Unary_numeral_system) as every number is a palindrome. --- # The Challenge Your task is to create a function (or full program) which takes two parameters, \$ n \$ and \$ b \$, and generates a list of the first \$ n \$ emirps in base \$ b \$. **Rules/Details:** * \$ n \$ and \$ b \$ are both positive integers larger than \$ 0 \$. * You can assume \$ 2 ≤ b ≤ 16 \$: that is to say, the base will be between binary and hexidecimal. * You should be able to compute for values of \$ n \$ up to \$ ~100 \$. * The generated list can be in base \$ b \$, or your language's standard integer base, as long as you specify this in your answer. * Builtin emirp checks are not permitted (builtin primality tests are fine) * You cannot hard-code the emirps, or read from any external files. * Standard loopholes are banned, as always. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer (in bytes) wins. --- # Test Cases For each test case, I've included the list in base `b` and its base 10 equivalents. ``` B = 2, N = 10 BIN: [1011, 1101, 10111, 11101, 100101, 101001, 101011, 101111, 110101, 111101] DEC: [11, 13, 23, 29, 37, 41, 43, 47, 53, 61] B = 3, N = 5 BASE3: [12, 21, 102, 201, 1011] DEC: [5, 7, 11, 19, 31] B = 12, N = 7 BASE12: [15, 51, 57, 5B, 75, B5, 107] DEC: [17, 61, 67, 71, 89, 137, 151] B = 16, N = 4 HEX: [17, 1F, 35, 3B] DEC: [23, 31, 53, 59] ``` You can test your program further against my (ungolfed) Python example on [**repl.it**](https://repl.it/EPmq/1) [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 17 bytes Uses [CP-1252](http://www.cp1252.com) encoding. Input order is `n, b` Output is in base-10. ``` µN²BÂD²öpŠÊNpPD–½ ``` [Try it online!](http://05ab1e.tryitonline.net/#code=wrVOwrJCw4JEwrLDtnDFoMOKTnBQROKAk8K9&input=NwoxMg) **Explanation** ``` # implicit input a,b µ # loop until counter is a N²B # convert current iteration number to base b ÂD # create 2 reversed copies ²ö # convert one reversed copy to base 10 p # check for primality ŠÊ # compare the normal and reversed number in base b for inequality Np # check current iteration number for primality P # product of all D # duplicate – # if 1, print current iteration number ½ # if 1, increase counter ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 16 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` bµU,ḅ⁹QÆPḄ=3 ⁸ç# ``` **[TryItOnline!](http://jelly.tryitonline.net/#code=YsK1VSzhuIXigblRw4ZQ4biEPTMK4oG4w6cj&input=&args=MTY+Ng)** ### How? ``` bµU,ḅ⁹QÆPḄ=3 - Link 1, in-sequence test: n, b b - convert n to base b - a list µ - monadic chain separation U - reverse the list , - pair with the list ⁹ - link's right argument, b ḅ - convert each of the two lists from base b Q - get unique values (if palindromic a list of only one item) ÆP - test if prime(s) - 1 if prime, 0 if not Ḅ - convert to binary =3 - equal to 3? (i.e. [reverse is prime, forward is prime]=[1,1]) ⁸ç# - Main link: b, N # - count up from b *see note, and find the first N matches (n=b, n=b+1, ...) for: ç - last link (1) as a dyad with left argument n and right argument ⁸ - left argument, b ``` \* Note `b` in base `b` is `[1,0]`, which when reversed is `[0,1]` which is `1`, which is not prime; anything less than `b` is one digit in base `b` and hence palindromic. [Answer] ## Mathematica, 70 bytes ``` Cases[Prime@Range@437,p_/;(r=p~IntegerReverse~#2)!=p&&PrimeQ@r]~Take~#& ``` Works for `0 <= n <= 100` and `2 <= b <= 16`. From the list `Prime@Range@437` of the first `437` primes, find the `Cases` `p`where the `IntegerReverse` `r` of `p` in base `#2` is not equal to `p` and is also prime, then take the first `#` such `p`. Here's a 95 byte solution that works for arbitrary `n>=0` and `b>=2`: ``` (For[i=1;a={},Length@a<#,If[(r=IntegerReverse[p=Prime@i,#2])!=p&&PrimeQ@r,a~AppendTo~p],i++];a)& ``` [Answer] # Perl, 262 bytes ``` ($b,$n)=@ARGV;$,=',';sub c{my$z;for($_=pop;$_;$z=(0..9,a..z)[$_%$b].$z,$_=($_-$_%$b)/$b){};$z}sub d{my$z;for(;c(++$z)ne@_[0];){}$z}for($p=2;@a<$n;$p++){$r=qr/^1?$|^(11+?)\1+$/;(c($p)eq reverse c$p)||((1x$p)=~$r)||(1x d($x=reverse c($p)))=~$r?1:push@a,c($p);}say@a ``` Readable: ``` ($b,$n)=@ARGV; $,=','; sub c{ my$z; for($_=pop;$_;$z=(0..9,a..z)[$_%$b].$z,$_=($_-$_%$b)/$b){}; $z } sub d{ my$z; for(;c(++$z)ne@_[0];){} $z } for($p=2;@a<$n;$p++){ $r=qr/^1?$|^(11+?)\1+$/; (c($p)eq reverse c$p)||((1x$p)=~$r)||(1x d($x=reverse c($p)))=~$r?1:push@a,c($p) } say@a ``` `c` converts a given number into base `$b`, and `d` converts a given number from base `$b` back into decimal by finding the first number which returns said base-`$b` number when passed to `c`. The for loop then checks if it's a palindrome and if both of the numbers are prime using the composite regex. [Answer] # Mathematica 112 bytes ``` Cases[Table[Prime@n~IntegerDigits~#2,{n,500}],x_/;x!=(z=Reverse@x)&&PrimeQ[z~(f=FromDigits)~#2]:>x~f~#2]~Take~#& ``` --- **Example** Find the first 10 Emips in hex; return them in decimal. ``` Cases[Table[Prime@n~IntegerDigits~#2, {n, 500}], x_ /; x != (z = Reverse@x) && PrimeQ[z~(f = FromDigits)~#2] :> x~f~#2]~Take~# &[10, 16] {23, 31, 53, 59, 61, 83, 89, 113, 149, 179} ``` --- **Ungolfed** ``` Take[Cases[ (* take #1 cases; #1 is the first input argument *) Table[IntegerDigits[Prime[n], #2], {n, 500}], (* from a list of the first 500 primes, each displayed as a list of digits in base #2 [second argument] *) x_ /; (* x, a list of digits, such that *) x != (z = Reverse[x]) && PrimeQ[FromDigits[z, #2]] (* the reverse of the digits is not the same as the list of digits; and the reverse list, when composed, also constitutes a prime *) :> FromDigits[x, #2]], (* and return the prime *) #1] & (* [this is where #1 goes, stating how many cases to Take] *) ``` [Answer] # [Perl 6](http://perl6.org/), 91 bytes ``` ->\n,\b{(grep {.is-prime&&{$_ ne.flip &&.parse-base(b).is-prime}(.base(b).flip)},1..*)[^n]} ``` Returns the list of emirps in base 10. [Answer] # [Python 3](https://docs.python.org/3/), ~~232~~ ~~214~~ ~~191~~ 188 bytes * [Herman L](https://codegolf.stackexchange.com/users/70894/herman-l) -14 bytes * [Jo King](https://codegolf.stackexchange.com/users/76162/jo-king) -3 bytes ``` p=lambda n:all(n%i for i in range(2,n)) def f(b,n): s=lambda n:(''if n<b else s(n//b))+f'{n%b:X}';l=[];i=3 while n:i+=1;c=s(i);d=c[::-1];a=(c!=d)*p(i)*p(int(d,b));l+=[c]*a;n-=a return l ``` [Try it online!](https://tio.run/##RY9NboMwEIX3nGKqKsIOjoJxCRKuNyx6hkooCwOmseQ6CKiqqurZ6QAhWXje/HzzNO5@xsvVi2nqlNOfVaPB59o54ncW2msPFqyHXvsPQxLmKQ0a00JLKszzAIbHEglD24J/rcC4wcBA/PFYURq14a/fVfn7XyidKs/SKhHA98U6g0s2UlzWaiCWykbVZZ4f@FlqReon1dB9h/05@JE0DM2ki1RZn/da@oPSAfRm/Oo9uKnrZ6YlPGYnSuEZuGDAMwaC40PNUDMRbFzCeLxyMccJR2FLvhS3Kt668aZ8o2478Yqj3p0FS1fjhEGy4HOy2d8xHGcrlzJIcZrikWmBR2JdpDOdPeATe1lhhPgb/ggBUUz/ "Python 3 – Try It Online") [Answer] # C, ~~293~~ ~~286~~ 261 bytes Improved by [@ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat), 261 bytes: ``` v,t,i,j,c,g,s[9],r[9],b;main(n,a)int**a;{for(b=n=atoi(a[1]);g^atoi(a[2]);t|v|!wcscmp(s,r)||printf("%u ",n,++g)){i=j=0;for(c=++n;s[i]=c;c/=b)s[i++]=c%b+1;for(;r[j]=i;)r[j++]=s[--i];p(n);for(t=v;r[i];)c+=~-r[i]*pow(b,i++);p(c);}}p(n){for(j=1,v=0;++j<n;n%j||v++);} ``` [Try it online!](https://tio.run/##LY7RasUgDIZfZTtQ0BrZOsaB4nyOXZQObEZFaW2pnp6LY/foc1p2k@RPvvwJco2Y0g4BDFhA0OC7toethEHMyjjiQFHjQl0r8RiXjQzSSRUWQ1TX9FTor3/xlkWIe3y@o8d5JR42GuO65d2RXKrb0wUcMKYpfRhp5asoZigZc8J3ppco8EUONNeMZVUNrDkRsXW2l0bQnMvEd5ybXqzE0XMe5J6R3KHI5A8vZb0udzJANqKZQyqOo@Dn@1Y2sOfrjNkPJ1xlY9wLd6SUmmt6/8VxUtonPs2Jf7qFm3mdDJqQuA/fUrtb2/4B) (This person is like constantly following me around PPCG and improving my stuff in the comments, and as soon as I reply to thank him he just deletes the comment and vanishes lol. Welp, thanks again!) --- Improved by [@movatica](https://codegolf.stackexchange.com/users/86751/movatica), 286 bytes: ``` u,v,t,i,j,c,n,g;main(int x,char**a){char s[9],r[9],b=n=atoi(a[1]);x=atoi(a[2]);for(;g^x;){i=j=0;for(c=++n;c;c/=b)s[i++]=c%b+1;s[i]=c=0;for(;i;r[j++]=s[--i]);r[j]=0;p(n);t=v;for(;r[i];)c+=(r[i]-1)*pow(b,i++);p(c);t|v|!strcmp(s,r)?:printf("%u ",n,++g);}}p(n){for(u=1,v=0;++u<n;n%u?:v++);} ``` [Try it online!](https://tio.run/##NY/daoQwEIVfxS4IySahtZRCdxr2MXohFnRAG9EoSbSC66s3nfTnZjhn5sw3DKoOMcZFrjJII3uJ0soOxtpYZmzINokftTufa74nkfnypZIulUZbXYfJsLosKg7bv3kk006OQfe@Ad@N7vXDTwO1EBYQ8F433JdGiEpj3ogCyJD8i4EBV/Zp6EulDNHIVjScmeUQ9PqbcrQDHIVmSamCn@fpkzWSsJyiSNHbervzweE4My8dv15mRy@17JQv2YneFKLjcByJuyfmogu50iEhllcLNl@ulzXRjhhj8RyfvrAd6s5HNYxRvdlJmXEeDJrwDQ) --- My original answer, 293 bytes: ``` u,v,t,i,j,c,n,g;main(int x,char**a){char s[9],r[9],b=n=atoi(a[1]);x=atoi(a[2]);for(++n;g^x;++n){i=j=0;for(c=n;c;c/=b)s[i++]=c%b+1;s[i]=c=0;for(;i;r[j++]=s[--i]);r[j]=0;p(n);t=v;for(--i;r[++i];)c+=(r[i]-1)*pow(b,i);p(c);t|v|!strcmp(s,r)?:printf("%u ",n,++g);}}p(n){for(u=1,v=0;++u<n;n%u?:v++);} ``` Compile with `gcc emirp.c -o emirp -lm` and run with `./emirp <b> <n>`. Prints space-separated emirps in base-10. [Answer] ## JavaScript (ES6), ~~149~~ ~~148~~ ~~141~~ 140 bytes Returns a space-separated list of emirps in base b. (Could be 2 bytes shorter by returning a decimal list instead.) ``` f=(b,n,i=2)=>n?((p=(n,k=n)=>--k<2?k:n%k&&p(n,k))(i)&p(k=parseInt([...j=i.toString(b)].reverse().join``,b))&&k-i&&n--?j+' ':'')+f(b,n,i+1):'' ``` ### Test cases ``` f=(b,n,i=2)=>n?((p=(n,k=n)=>--k<2?k:n%k&&p(n,k))(i)&p(k=parseInt([...j=i.toString(b)].reverse().join``,b))&&k-i&&n--?j+' ':'')+f(b,n,i+1):'' console.log(f(2,10)); console.log(f(3,5)); console.log(f(12,7)); console.log(f(16,4)); ``` [Answer] # [Python 2](https://docs.python.org/2/), 133 bytes ``` p=lambda n:all(n%i for i in range(2,n)) b,n=input() i=b while n: j=i=i+1;r=0 while j:r=r*b+j%b;j/=b if(i-r)*p(i)*p(r):print i;n-=1 ``` [Try it online!](https://tio.run/##JYvBCoMwEAXv@Yq9CIlGqh6V/ZiEan0hXcNiKf361NLLHIaZ8jn3Q6ZaC@fwjPdAMoecrTSg7VACQUiDPFY7eXHORC8MKa/TOgOO5r0jr9dkKDEY3bgoD4b@Os3K2sYuNXFJt6smbBa9urZY/KBuLgo5CYv0PNY6@XEYvg "Python 2 – Try It Online") Outputs each number on a new line, in base 10 [Answer] # [Husk](https://github.com/barbuz/Husk), ~~20~~ 17 bytes ``` ↑fo§&ȯṗB⁰↔S≠↔B⁰İp ``` [Try it online!](https://tio.run/##yygtzv7//1HbxLT8Q8vVTqx/uHO606PGDY/apgQ/6lwApEC8IxsK/v//b/Tf0AAA "Husk – Try It Online") The type inference is odd here. -3 bytes from Jo King. [Answer] # APL(NARS), 87 chars, 174 bytes ``` r←a f w;i i←1⋄r←⍬ →2×⍳∼{∼0π⍵:0⋄k≡v←⌽k←{(a⍴⍨⌊1+a⍟⍵)⊤⍵}⍵:0⋄0πa⊥v:1⋄0}i+←1⋄r←r,i⋄→2×⍳w>≢r ``` The result will be in base 10. Test and results: ``` 3 f 1 5 2 f 10 11 13 23 29 37 41 43 47 53 61 3 f 5 5 7 11 19 31 12 f 7 17 61 67 71 89 137 151 16 f 4 23 31 53 59 ``` `{(⍺⍴⍨⌊1+⍺⍟⍵)⊤⍵}` would do conversion of `⍵` in base `⍺`, array integer result; `0π⍵` would return true[1] if `⍵` is prime else it would return 0. [Answer] # [Japt](https://github.com/ETHproductions/japt), 18 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) With decimal output. ``` È2¶[XXìV'w]â xj}jU ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=yDK2W1hY7FYnd13iIHhqfWpV&input=NgoxNg) ]
[Question] [ There was a discussion going on in TNB once about the best temperature scale, and we agreed on something: Take the average of all four main temperature scales! That is, [Celsius](https://en.wikipedia.org/wiki/Celsius), [Kelvin](https://en.wikipedia.org/wiki/Kelvin), [Fahrenheit](https://en.wikipedia.org/wiki/Fahrenheit), and [Rankine](https://en.wikipedia.org/wiki/Rankine_scale) (Sorry Réaumur). So, now the issue is, most people don't use this system. So, I need a program to convert back from this average! # Challenge Given the average of the Celsius, Fahrenheit, Kelvin, and Rankine representations of a certain temperature, output the individual standard representations, in any prespecified and consistent order. It turns out that this is possible, based on my whiteboard calculations. Input will be a single floating-point value in whatever range your language can handle, and output will be four floating-point values in any reasonable format. You can restrict the input to force the output to be in the range of your language, but you must be able to support down to Absolute Zero (thus, you need to be able to handle negative numbers). # Test Cases ``` input -> (Celsius, Fahrenheit, Kelvin, Rankine) 100 -> (-70.86071428571424, -95.54928571428565, 202.28928571428574, 364.12071428571437) 20 -> (-128.0035714285714, -198.4064285714286, 145.14642857142857, 261.2635714285714) -10 -> (-149.43214285714282, -236.97785714285715, 123.71785714285716, 222.69214285714287) 10000 -> (7000.567857142858, 12633.022142857144, 7273.717857142858, 13092.692142857144) ``` These values were generated with [Uriel's Python program](https://codegolf.stackexchange.com/questions/117462/un-average-temperatures/117464#117464), and I verified that they were correct. [Answer] ## JavaScript (ES6), 49 bytes ``` f= a=>[a=(a-199.205)/1.4,a+=273.15,a*=1.8,a-=459.67] ``` ``` <input oninput=f(this.value).map(function(x,i){o.rows[i].cells[1].textContent=x})> <table id=o> <tr><th>Celsius:</th><td></td></tr> <tr><th>Kelvin:</th><td></td></tr> <tr><th>Rankine:</th><td></td></tr> <tr><th>Fahrenheit:</th><td></td></tr> </table> ``` [Answer] # Python, 63 bytes ``` def f(a):x=(a+183.205)*5/7;m=x*9/5;return x-273.15,m-459.67,x,m ``` `a` is the average, returns a tuple of the results as `(celsius, fahrenheit, kelvin, rankine)` **Math involved:** ``` kelvin = x celsius = x - 273.15 fahrenheit = x * 9/5 - 459.67 rankine = x * 9/5 a = (x + x - 273.15 + x * 9/5 - 459.67 + x * 9/5) / 4 = x * 7/5 - 183.205 x = (a + 183.205) * 5/7 ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), ~~40~~ ~~37~~ 36 bytes ``` ~~-BJ+c36641 280c\*5Q7 273.15-B\*J1.8 459.67~~ ~~-BJc+916.025\*5Q7 273.15-B\*J1.8 459.67~~ -BJc+916.025*5Q7 273.15-B*1.8J459.67 ``` [Try it online!](http://pyth.herokuapp.com/?code=-BJc%2B916.025%2a5Q7+273.15-B%2a1.8J459.67&input=100&debug=0) ### Specs * Input: `100` * Output: `[Kelvin, Celcius]\n[Rankine, Fahrenheit]` ### Math ``` kelvin = (average*5+916.025)/7 ``` [Answer] # Dyalog APL, ~~46~~ 40 bytes *6 bytes saved thanks to @Adám* ``` 273.15 459.67 0 0-⍨4⍴63 35÷⍨45×183.205+⊢ ``` [Try it online!](http://tryapl.org/?a=f%u2190273.15%20459.67%200%200-%u23684%u237463%2035%F7%u236845%D7183.205+%u22A2%20%u22C4%20f%A8%20%u236A100%2020%20%AF10%20%AF200%2010000&run) Anonymous monad, uses the Dyalog Classic character set. [Answer] # PHP, 62 Bytes Order Kelvin , Celsius , Rankine , Fahrenheit ``` print_r([$t=($argn+183.205)/1.4,$t-273.15,$t*=1.8,$t-459.67]); ``` [Online Version](http://sandbox.onlinephpfunctions.com/code/42403661677c964f30a4332b964820d6828ca937) ## PHP, 64 Bytes Order Kelvin , Rankine , Fahrenheit , Celsius ``` print_r([$k=($argn+183.205)/1.4,$r=1.8*$k,$r-459.67,$k-273.15]); ``` [Online Version](http://sandbox.onlinephpfunctions.com/code/80b1bf69b00ae400d0440039ce8be0750b67ae0c) [Answer] # dc, 37 ~~38~~ bytes *[Edit 1: Added third form, per Neil's comment]* These *[first two]* are both the same length :( The first one produces Fahrenheit, Celsius, Kelvin, Rankine (top to bottom on the stack), and the second one produces Fahrenheit, Rankine, Celsius, Kelvin. ``` 9k?183.205+1.4/d1.8*rd273.15-d1.8*32+f 9k?183.205+1.4/d273.15-rd1.8*d459.67-f 9k?199.205-1.4/d273.15+d1.8*d459.67-f ``` Example outputs (`dc` uses \_ to signal negative numbers on input): *[from first two forms; see edit below for third form.]* ``` 20 -198.406428572 -128.003571429 145.146428571 261.263571427 20 -198.406428573 261.263571427 145.146428571 -128.003571429 _10 -236.977857144 -149.432142858 123.717857142 222.692142855 _10 -236.977857145 222.692142855 123.717857142 -149.432142858 ``` # How it works ``` 9k?183.205+1.4/d1.8*rd273.15-d1.8*32+f ``` `9k` sets 9-place arithmetic. `?` reads input from stdin, leaving it at top of stack (TOS). `183.205+` adds 183.205 to TOS `1.4/` divides TOS by 1.4 or 7/5, giving degrees Kelvin. `d` duplicates TOS. (Ie, duplicates degrees Kelvin) `1.8*r` computes Rankine from Kelvin, then reverses top two of stack. `d273.15-` duplicates TOS and subtracts 273.15 to get degrees Celsius. `d1.8*32+` duplicates TOS, multiplies by 9/5, and adds 32, for Fahrenheit. `f` prints contents of stack. --- *Edit 1, continued:* ``` 9k?199.205-1.4/d273.15+d1.8*d459.67-f ``` This form, suggested by Neil, begins by computing Celsius instead of Kelvin. This saves a rotate (an `r`) when computing Rankin from Kelvin. It computes Celsius = (Average - 199.205)\*5/7 via `199.205-1.4/`, adds 273.15 to get Kelvin, multiplies by 1.8 to get Rankin, and subtracts 459.67 to get Fahrenheit. For example: ``` 20 -198.406428571 261.263571429 145.146428572 -128.003571428 ``` [Answer] # [CJam](https://sourceforge.net/p/cjam), 38 bytes ``` rd5*916.025+7/_p_273.15-p1.8*_p459.67- ``` Kelvins = `(5*input+916.025)/7` Outputs as ``` Kelvin Celsius Rankine Fahrenheit ``` [Try it online!](https://tio.run/nexus/cjam#@1@UYqplaWimZ2Bkqm2uH18Qb2RurGdoqltgqGehFV9gYmqpZ2au@/@/oQEQAAA "CJam – TIO Nexus") [Answer] # [Whispers v2](https://github.com/cairdcoinheringaahing/Whispers), 168 bytes ``` > Input > 5 > 7 > 183.205 >> 2÷3 >> 1+4 >> 6⋅5 >> 7-11 >> 7⋅12 >> 9-13 > 273.15 > 1.8 > 459.67 >> Output 7 >> Output 8 >> Output 9 >> Output 10 >> Then 14 15 16 17 ``` [Try it online!](https://tio.run/##TY09DsIwDIV3TuEdNcrLn5MlOxMLV6hUlqqirTgBEwfiANyEiwS7Uwb7fe/Zsp/TfV3Gx@paq3SZl307VYpSLIXsjbPiKrnvx6viHFTS7/06ch6AQyWAUyoDZJMcewM9BJOlh1hMYp1f902@UM@549IxrJrbNM6EQIiERODWYO0f "Whispers v2 – Try It Online") Outputs as `Kelvin\nCelsius\nRankine\nFahrenheit` [Answer] **Python 3, 67 bytes** ``` c=(5*float(input())-996.025)/7;t=[c,c*1.8+32,c+273.15,c*1.8+491.67] ``` This code does some algebra to get the temperature in Celcius, then I convert it to the other temperature units. The temperatures are stored in the list `t`. ]
[Question] [ **Objective** Write a full program that outputs (to STDOUT or closest alternative) an arbitrary string of text, no more than 64 characters long. Simple enough, right? Well, here's the catch: You may not use any characters that were present in the previous answer's output. That's right, *none* of them. Thus, you are trying to be the last answer for a total of three days. That is, you want no one to answer the question in the 72 hours following the posting of your question. ## Some rules * Your answer (and output) may only contain printable ASCII characters, newlines (carriage returns included), and tabs. * Your answer's output may not be the same as another answer's output. Two output's are the same if and only if they use the exact same characters. * You may use any language that was not specifically made for this challenge, even if it was made after the challenge. (This language, of course, must be testable.) * You may not use any language that was previously used. * Your entry may not include comments. You may, of course, provide an extra commented program. * You *may not* answer twice in a row. * Your program must be at least 1 byte. ## Entry format Your answer should look generally like the following: ``` # {Language} Uses: `characters present in the output` Does not use: `characters used in the previous output` from [previous submission, language](link-to-previous-submission] {program} Outputs: {output} ``` An explanation with your answer is appreciated. [Answer] # Pyth Uses: `()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefg`. Doesn't use: `!"#$%&'()*+,-./0123456789:;<=>?@[\]^_`abcdefghijklnsm{|}~` from [previous submission in Octave](https://codegolf.stackexchange.com/a/67304/3852). Code: ``` pMCMryyTyyytytttT ``` Output: ``` ()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefg ``` [Answer] # Brainfuck Uses: `-.` Does not use: `!"%&')+,0123456789<=>ABCDEFGHIJKLNOPRSTWXYZ]`acefghjlnoprstux{|` [from CJam](https://codegolf.stackexchange.com/a/67296/45447). Thanks to SuperJedi ``` -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------.--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.-------------------------------------------------------------------------------------------.-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------. ``` Outputs: ``` ; (){}[]"' ``` [Answer] # CJam Uses: `0123456789:;_bc` Does not use: `!GSaefgimnoprstuw`, from [previous submission, MATLAB](https://codegolf.stackexchange.com/a/67293/25180) ``` 183185535513294435547695067785526290427932963043839368372854060721693597139131275368051870173845056551161192991350318233082749156998652_;128b:c ``` Outputs: ``` !"%&')+,0123456789<=>ABCDEFGHIJKLNOPRSTWXYZ]`acefghjlnoprstux{| ``` [Answer] # Octave Uses: `!"#$%&'()*+,-./0123456789:;<=>?@[\]^_``abcdefghijklnsm{|}~` and a newline in the output. Doesn't use: `ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"` from [previous submission in Microscript](https://codegolf.stackexchange.com/a/67299/31516). Code: ``` [' ':'@','[':'`','{':'~',('@'+' '):('>'+'/')] ``` Output: ``` ans = !"#$%&'()*+,-./0123456789:;<=>?@[\]^_`{|}~`abcdefghijklm ``` Explanation: This is a collection of consecutive ASCII-characters. The code is equivalent to: ``` [char(32:64) char(91:96) char(123:126) char(96:109)] ``` Where `char(32:64)` are the ASCII characters from 32 to 64 (space to @). In order to get the alphabet-part in the end of the output, I had to add characters, as I couldn't use `a` and `m`. `@+` equals 96 (``) and `>+/` equals 109 (m) [Answer] # Perl Uses: `0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz}` (with space) Does not use: `"#$%'()*+,-./123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`{|~` from [previous submission in Unreadable](https://codegolf.stackexchange.com/a/67380/30164) ``` eval q!print uc q&} abcdefghijklmnopqrstuvwxyz&!and eval q}print q&0abcdefghijklmnopqrstuvwxyz&}and eval q&print length for qw!a bc def ghij klmno pqrstu vwxyzab cdefghij klmnopqrs!& ``` Outputs: ``` } ABCDEFGHIJKLMNOPQRSTUVWXYZ0abcdefghijklmnopqrstuvwxyz123456789 ``` --- …the old joke about monkeys writing code comes to mind… [You can run the program online.](https://ideone.com/fTr98T) This program abuses the weird features of Perl to write code in just about any subset of ASCII: * Functions can be called without parentheses in some cases (unsure about exact rules) * `q#text#` where `#` can be almost any character is the same as `"text"` * `qw#word1 word2 word3#` like the above is the same as `["word1", "word2", "word3"]` * `for` loops and other things can be appended to lines, eliminating any punctuation [Answer] # Javascript ES6 Previous answer: <https://codegolf.stackexchange.com/a/67406/39022> Source does not contain `!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ`, space, or newline. ``` alert`abcdefghijklmnopqrstuvwxyz{}\\~_^[]|\`` ``` Output: ``` abcdefghijklmnopqrstuvwxyz{}\~_^[]|` ``` (Lowercase alphabet, curly brackets, backslash, tilde, underscore, carat, square brackets, pipe, and backtick) [Answer] # Ruby ``` $><<'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" ' ``` Does not use `abcdefghijklmnopqrstuvwxyz{}\~_^[]|`` from the [previous answer](https://codegolf.stackexchange.com/a/67414/3852). Prints, and hence uses, `ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"`, a space, and a newline. [Answer] # Python 3 Uses: `!CGaceilmnoprstw z`. ``` print("Germanic Capitalization is awesome!") ``` Simply prints `Germanic Capitalization is awesome!` with no restrictions. Good luck! [Answer] # Microscript II Previous answer: [here.](https://codegolf.stackexchange.com/questions/67286/the-complement-cat/67298#67298) Program does not use semicolon, space, parentheses, curly brackets, square brackets, single straight quotes, or double straight quotes. This program would be a lot shorter if it didn't have to avoid quotes. Output includes: `ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"`, and a newline. Program: ``` 97Kp98Kp99Kp100Kp101Kp102Kp103Kp104Kp105Kp106Kp107Kp108Kp109Kp110Kp111Kp112Kp113Kp114Kp115Kp116Kp117Kp118Kp119Kp120Kp121Kp122Kp""P65Kp66Kp67Kp68Kp69Kp70Kp71Kp72Kp73Kp74Kp75Kp76Kp77Kp78Kp79Kp80Kp81Kp82Kp83Kp84Kp85Kp86Kp87Kp88Kp89Kp90Kp123456789qh ``` Exact output: ``` abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ"123456789" ``` [Answer] # Unreadable Uses: `"#$%'()*+,-./123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`{|~` Does not use: `()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefg` from [previous submission in Pyth](https://codegolf.stackexchange.com/a/67313/46855) > > '"'""'""'"'""'"'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'""'"'""'"'""'"'""'"'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""" > > > Outputs: ``` "#$%'()*+,-./123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`{|~ ``` --- In case you are wondering, yes, programming by hand in this language is painful, so I made this script (in JavaScript) to generate the code: ``` var program = `"`, output = "\"#$%'()*+,-./123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`{|~"; for(var i = 1, c = 0; c < output.length; i++) { program = `'""` + program; if(i == output.charCodeAt(c)) { program = `'"` + program; c++; } } program; ``` I used the Python interpreter for Unreadable [here](https://esolangs.org/wiki/User:Marinus/Unreadable_Interpreter) to run the code. [Answer] # MATLAB Uses: `!GSaefgimnoprstuw` and newline. Does not use: `!CGaceilmnoprstw z` from [previous submission, Python 3](https://codegolf.stackexchange.com/a/67287/31516). ``` [83,116,101,119,105,101,32,71,114,105,102,102,105,110,32,105,115,32,97,32,112,114,111,109,105,110,101,110,116,32,103,101,110,105,111,117,115,33,''] ``` Prints: ``` ans = Stewie Griffin is a prominent genious! ``` [Answer] # GolfScript Uses: space, newline, `!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ`. Doesn't use `0-9A-Za-z{` or space from [previous submission in Perl](https://codegolf.stackexchange.com/a/67394/3852). The code: ``` '!'.!=('['.!=,>''+ ``` The output: ``` !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ ``` And a trailing newline. [Try it here.](http://golfscript.tryitonline.net/#code=JyEnLiE9KCdbJy4hPSw-Jycr&input=) ]
[Question] [ For many games played on a grid, hexagons are the Clearly Superior Choice™. Unfortunately, many free game art sites only have seamless tile sets for square maps. On a past project, I used some of these, and manually converted them to hexagons. *However*, I've gotten lazy in my old age. It should be easy to automate the process with a small script. *However*, I've gotten lazy in my old age. So I'm outsourcing it to you, and disguising it as a code golf challenge1. --- ## Input Input is a square image in any common image format capable of 24-bit RGB color. You may also take a filename as input instead of the image data itself. You may assume the image is square, and that the side length is a multiple of four. ## Output Output is the input tile, but converted to a hexagon (the image itself will be square, with transparent areas). You may save it to a file or display to the screen. Again, any common image format will do. If the format you're using supports transparency, background areas must be transparent. If it doesn't, you may use color #FF00FF (that horrible fuchsia one) as a stand-in. ## Method So how do we do it? The method I use2 squashes the image a bit vertically, but overall it looks pretty good for most things. We'll do an example with this input image: [![input](https://i.stack.imgur.com/gQAZh.png)](https://i.stack.imgur.com/gQAZh.png) * **Scale:** Scale the image to a 3:2 ratio. Since our images will be squares, this means you simply scale them to 75% width and 50% height. Our example input is 200x200, so we end up with this 150x100 image: [![squashed](https://i.stack.imgur.com/zNDfz.png)](https://i.stack.imgur.com/zNDfz.png) * **Tile:** Place down copies of your scaled image in a 2x2 grid: [![grid](https://i.stack.imgur.com/Wgpij.png)](https://i.stack.imgur.com/Wgpij.png) * **Crop:** Grab an appropriately sized hexagon from anywhere in this 2x2 grid. Now, for ease of tiling, this hexagon isn't exactly regular. After cropping a square of the original size (here 200x200), you then crop out the corners. The crop lines should run from (roughly) the center of each left/right side to one quarter from the edge on the top/bottom: [![hex](https://i.stack.imgur.com/KhoDY.png)](https://i.stack.imgur.com/KhoDY.png) And that's your output! Here's an example of what it might look like when tiled (zoomed out here): [![tiled](https://i.stack.imgur.com/ytYgR.png)](https://i.stack.imgur.com/ytYgR.png) This is code golf, so shortest code in bytes wins. Standard loopholes apply, etc and so on. --- 1 Feel free to believe this or not. 2 Method one from [this helpful site.](http://wiki.wesnoth.org/Turning_Square_Tiles_into_Hex) [Answer] # Mathematica, ~~231~~ ~~211~~ ~~209~~ ~~208~~ ~~201~~ ~~188~~ 173 bytes ``` ImageCrop[ImageCollage@{#,#,#,#},e,Left]~SetAlphaChannel~ColorNegate@Graphics[RegularPolygon@6,ImageSize->1.05e,AspectRatio->1]&@ImageResize[#,{3,2}(e=ImageDimensions@#)/4]& ``` This is an unnamed function which takes an image object and returns an image object: [![enter image description here](https://i.stack.imgur.com/2mp5U.png)](https://i.stack.imgur.com/2mp5U.png) I don't think there's a lot to explain here, but some details which are of note: * Normally, to tile an image 2x2, you'd use `ImageAssemble[{{#,#},{#,#}}]`, i.e. you hand `ImageAssemble` a 2x2 matrix with copies of the image. However, there's `ImageCollage` which is some sort of magic function which tries to arrange a bunch of pictures as "well" as possible (whatever that means... you can even give the individual images weights and stuff). Anyway, it you give it four images of equal size and with equal (or no) weights, it will also arrange them in a 2x2 grid. That allows me to save some bytes for the nesting of the matrix, as well as the function name. * The hexagon is rendered as a single polygon via `Graphics`. I'm using the built-in `RegularPolygon@6`, but enforce an aspect ratio of `1` to stretch it as necessary. Unfortunately, `Graphics` needs a couple of expensive options to avoid padding and such, and it also renders black on white instead of the opposite. The result is fixed with `ColorNegate` and then attached to the image's original channels with `SetAlphaChannel`. * `Graphics` puts a small amount of padding around the hexagon, but we want the alpha hexagon to cover the full size of the cutout. However, `SetAlphaChannel` can combine images of different sizes, by centring them on top of each other and cropping to the smallest size. That means, instead of manually setting `PlotRangePadding->0`, we can simply scale up the hexagon image a bit with `ImageSize->1.05e` (and we need the `ImageSize option anyway). [Answer] # Matlab, ~~223 215 209 184~~ 163 bytes The rescaling is quite straight forward. For cropping the corners I overlay a coordinate system over the pixels, and make a mask via four linear inequalities, which determine the area of the hexagon. ``` ​l=imread(input('')); u=size(l,1); L=imresize(l,u*[2 3]/4); L=[L,L;L,L];L=L(1:u,1:u,:); [x,y]=meshgrid(1:u); r=u/2;x=x*2; set(imshow(L),'Al',y<x+r&y+x>r&y+x<5*r&y>x-3*r) ``` [![enter image description here](https://i.stack.imgur.com/atg0j.png)](https://i.stack.imgur.com/atg0j.png) PS: This turned into a codegolf *nim* game with @MartinBüttner's submission: You alternatingly have to make your code shorter (while providing the same functionality) - the one that can make the last 'shortening' wins=) [Answer] # HTML5 + Javascript, 562 bytes ``` <html><form><input type=text></form><canvas><script>l=document.body.children;l[0].addEventListener("submit",e=>{e.preventDefault();c=l[1].getContext("2d");i=new Image();i.onload=q=>{l[1].width=l[1].height=d=i.width;c.scale(0.75,0.5);c.drawImage(i,0,0);c.drawImage(i,d,0);c.drawImage(i,0,d);c.drawImage(i,d,d);c.globalCompositeOperation="destination-in";c.scale(1/0.75,2);c.beginPath();c.moveTo(d/4,0);c.lineTo(d/4+d/2,0);c.lineTo(d, d/2);c.lineTo(d/4+d/2, d);c.lineTo(d/4, d);c.lineTo(0, d/2);c.closePath();c.fill();};i.src=e.target.children[0].value;})</script> ``` Takes input as an image URL via textbox (the URL hopefully counts as a filename). Outputs the data to canvas. ## Version which works across all browsers (580 bytes): ``` <html><form><input type=text></form><canvas><script>l=document.body.children;l[0].addEventListener("submit",function(e){e.preventDefault();c=l[1].getContext("2d");i=new Image();i.onload=function(){l[1].width=l[1].height=d=i.width;c.scale(0.75,0.5);c.drawImage(i,0,0);c.drawImage(i,d,0);c.drawImage(i,0,d);c.drawImage(i,d,d);c.globalCompositeOperation = "destination-in";c.scale(1/0.75,2);c.beginPath();c.moveTo(d/4, 0);c.lineTo(d/4+d/2,0);c.lineTo(d, d/2);c.lineTo(d/4+d/2, d);c.lineTo(d/4, d);c.lineTo(0, d/2);c.closePath();c.fill();};i.src=e.target.children[0].value;})</script> ``` Test it with the "blocks" image from earlier via this URL: <https://i.stack.imgur.com/gQAZh.png> [Answer] # Python 2 + PIL, 320 Reads the name of the image file from stdin. ``` from PIL import ImageDraw as D,Image as I i=I.open(raw_input()) C=A,B=i.size i,j=i.resize((int(.75*A),B/2)),I.new('RGBA',C) W,H=i.size for a,b in[(0,0),(0,H),(W,0),(W,H)]:j.paste(i,(a,b,a+W,b+H)) p,d=[(0,0),(A/4,0),(0,B/2),(A/4,B),(0,B)],lambda p:D.Draw(j).polygon(p,fill=(0,)*4) d(p) d([(A-x,B-y)for x,y in p]) j.show() ``` [Answer] ## PHP, 293 bytes I've added some newlines for readability: ``` function($t){$s=imagesx($t);imagesettile($i=imagecreatetruecolor($s,$s),$t=imagescale ($t,$a=$s*3/4,$b=$s/2));imagefill($i,0,0,IMG_COLOR_TILED);$z=imagefilledpolygon;$z($i, [0,0,$s/4,0,0,$b,$s/4,$s,0,$s],5,$f=imagecolorallocate($i,255,0,255));$z($i,[$s,0,$a, 0,$s,$b,$a,$s,$s,$s],5,$f);return$i;} ``` Here is the ungolfed version: ``` function squareToHexagon($squareImage) { $size = imagesx($squareImage); $tileImage = imagescale($squareImage, $size * 3/4, $size/2); $hexagonImage = imagecreatetruecolor($size, $size); imagesettile($hexagonImage, $tileImage); imagefill($hexagonImage, 0, 0, IMG_COLOR_TILED); $fuchsia = imagecolorallocate($hexagonImage, 255, 0, 255); imagefilledpolygon( $hexagonImage, [ 0, 0, $size/4, 0, 0, $size/2, $size/4, $size, 0, $size, ], 5, $fuchsia ); imagefilledpolygon( $hexagonImage, [ $size, 0, $size * 3/4, 0, $size, $size/2, $size * 3/4, $size, $size, $size, ], 5, $fuchsia ); return $hexagonImage; } header('Content-type: image/gif'); $squareImage = imagecreatefrompng('squareImage.png'); $hexagonImage = squareToHexagon($squareImage); imagegif($hexagonImage); ``` ]
[Question] [ Given a list of strings, replace each string by one of its non-empty substrings which is not a substring of any of the other strings in the list and as short as possible. ### Example Given the list `["hello","hallo","hola"]`, `"hello"` should be replaced by just `"e"` as this substring is not contained in `"hallo"` and `"hola"` and it is as short as possible. `"hallo"` could be replaced by either `"ha"` or `"al"` and `"hola"` by any of `"ho"`, `"ol"` or `"la"`. ### Rules * You can assume that the strings will be non-empty and only contain alphabetical characters of the same case. * You can assume that such a substring exists for each string in the list, i.e. no string in the list will be a substring of any of the other strings. * Input and output can be in any reasonable format. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so try to use as few bytes as possible in the language of your choice. ### Test Cases Only one possible output is given for most cases. ``` ["ppcg"] -> ["p"] (or ["c"] or ["g"]) ["hello","hallo","hola"] -> ["e","ha","ho"] ["abc","bca","bac"] -> ["ab","ca","ba"] ["abc","abd","dbc"] -> ["abc","bd","db"] ["lorem","ipsum","dolor","sit","amet"] -> ["re","p","d","si","a"] ["abc","acb","bac","bca","cab","cba"] -> ["abc","acb","bac","bca","cab","cba"] ``` --- Related: [Shortest Identifying Substring](https://codegolf.stackexchange.com/questions/49704/shortest-identifying-substring) - similar idea, but more involved rules and cumbersome format. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~12~~ 9 bytes ``` Ẇ€ŒpẇþÞ⁸Ḣ ``` **[Try it online!](https://tio.run/##y0rNyan8///hrrZHTWuOTip4uKv98L7D8x417ni4Y9H/w@3e//9HK2UAFeUr6ShlJELp/JxEpVgA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8///hrrZHTWuOTip4uKv98L7D8x417ni4Y9H/w@1AUff//6OjlQoKktOVYnW4FKKVMoB68pV0lDISoXR@TiJUKjEpGSiQlJwIIhOTUUQTk1KAZEoSTDQnvyg1FyiSWVBcCqJT8oEiQLo4swSkOje1BFV7chLUUJgFyYkgkeQkoOWxAA "Jelly – Try It Online") (takes ~35s) [Answer] # [Pyth](https://pyth.readthedocs.io), 12 bytes ``` mhf!ts}LTQ.: ``` [Try it here!](https://pyth.herokuapp.com/?code=mhf%21ts%7DLTQ.%3A&input=%5B%22abc%22%2C%22abd%22%2C%22dbc%22%5D&test_suite=1&test_suite_input=%5B%22ppcg%22%5D%0A%5B%22hello%22%2C%22hallo%22%2C%22hola%22%5D%0A%5B%22abc%22%2C%22bca%22%2C%22bac%22%5D%0A%5B%22abc%22%2C%22abd%22%2C%22dbc%22%5D%0A%5B%22lorem%22%2C%22ipsum%22%2C%22dolor%22%2C%22sit%22%2C%22amet%22%5D%0A%5B%22abc%22%2C%22acb%22%2C%22bac%22%2C%22bca%22%2C%22cab%22%2C%22cba%22%5D&debug=0) ### How it works Basicaly filters the substrings of each that only occur in one of the strings in the list (that is, it is unique to that string) and gets the first one. ``` mhf!ts}LTQ.: Full program, Q=eval(stdin_input()) m .: Map over Q and obtain all the substrings of each. f And filter-keep those that satisfy (var: T)... }LTQ ... For each string in Q, yield 1 if it contains T, else 0. !ts ... Sum the list, decrement and negate. h Head. Yields the first valid substring, which is always the shortest. ``` [Answer] # [Prolog (SWI)](http://www.swi-prolog.org), ~~175~~ 163 bytes ``` S/L/R:-sub_string(S,_,L,_,R). [H|T]+[I|R]:-string_length(H,L),between(1,L,X),H/X/I,T+R. R+R. L-R:-L+R,forall(member(E,L),findall(_,(member(F,R),\+ \+ E/_/F),[_])). ``` [Try it online!](https://tio.run/##fVDBisMgFLz3K0pOSl4ive5lTy0p5GR7KGSDqLGJYGIwll7679nn0p52t6AzMG/mOTgH73xfLHe7ridWM/5RLDcllhjs1JMTCKjxclpumupxbvPm@OAten7mwpmpjwOpoKagTLwbM5EdJi4UKnZhRzjnvNzwBHWBq@ucw9UH6RwZzahMIPsUvdqpS5qAl3zAJ@Er3@LZM8EOFBrRUlqun0WTzbPus7bgsL0HG42bSOqXJoNxzmeQDfLJ3sm/nVJpnCstE0r9ziRVh9ipf0zOBzOiwc7LLXGHHxqQFxtTeDTx7XKtng1ebbRMila/i6/f "Prolog (SWI) – Try It Online") Most of the things here should be fairly obvious, but: ### Explanation Signatures: (`+` = input, `?` = optional, `-` = output, `:` = expression) * `sub_string(+String, ?Before, ?Length, ?After, ?SubString)` * `string_length(+String, -Length)` * `member(?Elem, ?List)` * `between(+Low, +High, ?Value)` * `findall(+Template, :Goal, -Bag)` * `forall(:Cond, :Action)` `\+ \+` is just `not not` (i.e. converts a match to boolean (in this case, prevents it from matching both `p`s in `ppcg` separately)) [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 25 bytes Thanks ngn for [saving](https://chat.stackexchange.com/transcript/message/48103605#48103605) one byte ``` ⊃¨1↓≢~⍨/(,⍨(,∘↑⍳∘≢,/¨⊂)¨) ``` [Try it online!](https://tio.run/##TUw7DoJAEO09Bd1KgiEeaXYWkGTJbgQLGwtNCJCQaGysqbb3BnuUuQjOKiY07zfzHli9U2fQppjnnNo7DTfv9tQ@qZ8uNLp0mzAydC9qHzS@g@inJPWOhmvsXcy9iKWwFguxySNxyLQ2ghkWNhq@B5DIViIEBFxlIBWjkr9Mm2NWsS9tfQqsDCfMddmE3ypr1lWUy9x/GiEkKEF8AA "APL (Dyalog Unicode) – Try It Online") [Answer] # [J](http://jsoftware.com/), ~~30 29~~ 25 bytes ``` 1(|:(0{-.&,)"_1]\.)<\\.&> ``` [Try it online!](https://tio.run/##y/r/P81WT8FQo8ZKw6BaV09NR1Mp3jA2Rk/TJiZGT83uf2pyRr5CmoK6jnpyaYmCekZqTk6@TkYimMzPSVTnQlNQUJCcjiGYk1@UmquTWVBcmquTkg/k6RRnlugk5qaWqP//DwA) ``` <\\.&> a 3-dimensional array of substrings 1 |: transpose each matrix to sort the substrings by length 1 ]\. all choices where one word is missing (0{-.&,)"_1 for every matrix, flatten, remove substrings that are present in the corresponding complement, pick first ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes ``` Ẇ€ṙƬ1ḟ/Ḣ$€ ``` [Try it online!](https://tio.run/##y0rNyan8///hrrZHTWse7px5bI3hwx3z9R/uWKQCFPh/uB1Iuv//Hx2tVFCQnK4Uq8OlEK2UAdSUr6SjlJEIpfNzEqFSiUnJQIGk5EQQmZiMIpqYlAIkU5Jgojn5Ram5QJHMguJSEJ2SDxQB0sWZJSDVuaklqNqTk6CGwixITgSJJCcBLY8FAA "Jelly – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 116 bytes ``` def f(a):g=lambda s,S:s not in`set(a)-{S}`[3:]and min(s,g(s[1:],S),g(s[:-1],S),key=len)or S;return[g(s,s)for s in a] ``` [Try it online!](https://tio.run/##VZBLbsMgFEXHzSreDFvCg7QzqnQTHiKkPD7@qBgQkEEUde0u4EZVRhydq3tBhHtevHvfd20mmDrs2XyxuEmNkOjIEjifYXXXZHIJh8f4c@UfTKDTsK2uS3TuEj8zQce@IRvOjb/N/WKN632E8TOafIuOl5ymfioqlUlAsVfGypwTREKBSEkEBU5CUPNBi7HW12jBJ3iLR4ZStZI6uqheNEpdDy3/tPXRbNWsId0aaF9chbTm1thMfp1Q8rn8f4/CJpUsrxDs9Bbi6jIgJcMXofUPT/sv "Python 2 – Try It Online") [Answer] # JavaScript (ES6), 93 bytes ``` a=>a.map(s=>(L=s.length,g=n=>a.every(S=>S==s|!~S.search(u=s.substr(n%L,n/L+1)))?u:g(n+1))(0)) ``` [Try it online!](https://tio.run/##fU9Na8QgEL33V2yFgtJs0l4Lpn8gtxyXPYzGNSlGxTELhdK/nmo2JXTZ7cXnvI9h3gecAWUYfNxb16n5xGfgNZQjeIq8pg3H0iirY19obrOizip80pbXLef49fjdlqggyJ5OyYqTwBiofWoKWzXPr4yx9@lNU5u/9IWxWTqLzqjSOE1P9EC8l5ocGdtV1S5N5Phw7eiVMY4UpIcVnYEtoRZloW9kQcgkCZkNAuQWA5GYlb6bA9GltxN/csvCC38jaFxQYxIHj1PGziUmIQ4xLxxV3HaFfLvPpsWQ9funSLFW@K0jLxUEXB/3r3X@AQ "JavaScript (Node.js) – Try It Online") ### How? For each string **s** of length **L** in the input array **a[ ]** and starting with **n = 0**, we use the recursive function **g()** to generate all substrings **u** of **s** with: ``` u = s.substr(n % L, n / L + 1) ``` For instance, with **s = "abc"** and **L = 3**: ``` n | n%L | floor(n/L+1) | u ---+-----+--------------+------- 0 | 0 | 1 | "a" 1 | 1 | 1 | "b" 2 | 2 | 1 | "c" 3 | 0 | 2 | "ab" 4 | 1 | 2 | "bc" 5 | 2 | 2 | "c" 6 | 0 | 3 | "abc" 7 | 1 | 3 | "bc" 8 | 2 | 3 | "c" ``` Some substrings are generated several times, but it doesn't matter. What's important is that all substrings of length **N** have been generated before any substring of length **N+1**. We stop the process as soon as **u** cannot be found in any *other* string **S** in **a[ ]**, which is guaranteed to happen when **u == s** in the worst case, as per challenge rule #2: > > *no string in the list will be a substring of any of the other strings* > > > Therefore, in the above example, steps **7** and **8** will actually never be processed. [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 107 bytes ``` ($a=$args)|%{$(for($i=0;$i++-lt($g=($s=$_)|% Le*)){0..($g-$i)|%{$s|% s*g $_ $i}|?{!($a-match$_-ne$s)}})[0]} ``` [Try it online!](https://tio.run/##HYxBCsMgFAWvksIraIIh@yK9QG8QikhrE0Fr8Fu6SDz7r3Q5M7y3pa/LtLoQmAWshs0LyeO8Q7xSFvB6usAPgwpFYNECpGFa726ul3KfxrFpBf@fUPPULx1MB1@P635qlyra8lhh1NuBZK1ynu6VmUPKLrLf6BP5mRox@cI2uvID "PowerShell – Try It Online") ## Explanation For each string supplied (and assign the whole array to `$a`): * Do a `for` loop over each substring length (1 based) of the string (assigning the string itself to `$s` and the length to `$g`) * For each length (`$i`): + Make an index loop, from 0 to to length - `$i`, then for each index: - Get the substring of the current string (`$s`) at position `$_` (index) and of length `$i` - Pass that substring to `Where-Object` (`?`), and return it if: * The subset of array (`$a`) that does not contain the current string `$s`, does not have a match for the current substring `$_` Back at the string level, we have all of the substrings of this string that were not found in the others, so take the first one `[0]` since we only need one of them, then continue with the next string. [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 149 bytes ``` a=>a.Select(s=>{var t=s;for(int j=0,k,l=s.Length;j++<l;)for(k=-1;j+k++<l;)if(!a.Where(u=>s!=u&u.Contains(t=s.Substring(k,j))).Any())j=k=l;return t;}) ``` [Try it online!](https://tio.run/##jY89a8MwEIb3/ArHQ5GII9rZkSGUFgodCil0KB1OsmzLliWjj5YS8ttdiaRLG0iWe7n3nvvibs2dnB@D5punBx1GYYEpsXHeSt1WxRmvypqMzkArIDuhBPfI0Wr/CTbz1JWNsUhqn/X0thgKRR15Frr1XdmvVhtV4lQf6Pou5sPRkQ1aAnnrhBUo0MotabgJ5N5oD1I7FIeSXWDH5Wgoeowx2epvhHFPB6pKK3ywOvPlAc/lYvESOY8apMXX@8c@nybe5gdMXs3WWkhd/5lOKGXyIu/gpEbBpR5gPJKMQ4rAr8OB1THW7CKujBVjROXkQtLaRCeqkz6NGYW/ciFnp/t@b@WQHM7@Pjj/AA "C# (Visual C# Interactive Compiler) – Try It Online") Less golfed... ``` // a is an input array of strings a=> // iterate over input array a.Select(s=>{ // t is the result string var t=s; // j is the substring length for(int j=0,k,l=s.Length;j++<l;) // k is the start index for(k=-1;j+k++<l;) // LINQ query to check if substring is valid // the tested string is collected in t if(!a.Where(u=>s!=u&u.Contains(t=s.Substring(k,j))).Any()) // break loops j=k=l; // return result return t; }) ``` ]
[Question] [ Sometimes, when I'm idly trying to factor whatever number pops up in front of me¹, after a while I realize it's easier than I thought. Take `2156` for example: it eventually occurs to me that both `21` and `56` are multiples of `7`, and so certainly `2156 = 21 x 100 + 56` is also a multiple of `7`. Your task is to write some code that identifies numbers that are easier to factor because of a coincidence of this sort. ## More precisely: Write a program or function that takes a positive integer `n` as input, and returns a truthy value if there exists a divisor `d` (greater than `1`) such that `n` can be chopped in two to yield two positive integers, each of which is a multiple of `d`; return a falsy value if not. * "Chopped in two" means what you think: the usual base-10 representation of `n` partitioned at some point into a front half and a back half to yield two other base-10 integers. It's okay if the second integer has a leading zero (but note that it must be a positive integer, so splitting `1230` into `123` and `0` is not valid). * The truthy and falsy values can depend on the input. For example, if any nonzero integer is truthy in your language of choice, then you are welcome to return the divisor `d` or one of the "pieces" of `n` (or `n` itself for that matter). * For example, any even number with at least two digits in the set `{2, 4, 6, 8}` will yield a truthy value: just split it after the first even digit. Also for example, any prime number `n` will yield a falsy value, as will any one-digit number. * Note that it suffices to consider prime divisors `d`. * You may assume the input is valid (that is, a positive integer). This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins. But solutions in all languages are welcome, so we can strive for the shortest code in each language, not just the shortest code overall. ## Test cases (You only have to output a truthy or falsy value; the annotations below are just by way of explanation.) Some inputs that yield truthy values are: ``` 39 (3 divides both 3 and 9) 64 (2 divides both 6 and 4) 497 (7 divides both 49 and 7) 990 (splitting into 99 and 0 is invalid; but 9 divides both 9 and 90) 2233 (11 divides both 22 and 33) 9156 (3 divides both 9 and 156; or, 7 divides both 91 and 56) 11791 (13 divides both 117 and 91) 91015 (5 divides both 910 and 15) 1912496621 (23 divides both 1912496 and 621; some splittings are multiples of 7 as well) 9372679892 (2473 divides both 937267 and 9892; some splittings are multiples of 2 as well) ``` Some inputs that yield falsy values are: ``` 52 61 130 (note that 13 and 0 is not a valid splitting) 691 899 2397 9029 26315 77300 (neither 7730 and 0 nor 773 and 00 are valid splittings) 2242593803 ``` ¹ yes I really do this [Answer] ## [Retina](https://github.com/m-ender/retina), ~~31~~ 29 bytes ``` ,$';$` \d+ $* ;(11+)\1*,\1+; ``` [Try it online!](https://tio.run/nexus/retina#FcqxEYAgEETRfOvAEYWAvZPDGwqwCQID@28BNftv5i/xuidyWHu4MZ6EsKNHMm2Dex5MfU512IHDG9wLRFThrAayOVEFRlAL7NPpDtF/LfKVKesL "Retina – TIO Nexus") Outputs a positive integer for valid inputs and zero for invalid ones. I wouldn't recommend waiting for the larger test cases... ### Explanation ``` ,$';$` ``` At each position of the input insert a comma, then everything before that position, then a semicolon, then everything after this position. What does that do? It gives us all possible splittings of a number (split by `,`, separated by `;`), and then the input again at the end. So input `123` becomes ``` ,123;1,23;12,3;123,;123 ^ ^ ^ ``` where I've marked the original input characters (the stuff that isn't marked is what we inserted). Note that this creates invalid splittings that aren't actual splittings and it also doesn't care whether the trailing component is all zeros, but we'll avoid accepting those later. The benefit of creating the invalid splittings is that we know that each *valid* splitting has a `;` in front and after it, so we can save two bytes on word boundaries. ``` \d+ $* ``` Convert each number to unary. ``` ;(11+)\1*,\1+; ``` Match a splitting by matching both halves as multiples of some number that's at least 2. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog) (2), 8 bytes ``` ~c₂ḋᵐ∋ᵐ= ``` [Try it online!](https://tio.run/nexus/brachylog2#@1@X/Kip6eGO7odbJzzqAJG2//8bGppbGgIA "Brachylog – TIO Nexus") ## Explanation ``` ~c₂ḋᵐ∋ᵐ= ~c₂ Split the input into two pieces ᵐ ᵐ On each of those pieces: ḋ ∋ Choose a prime factor = such that both the chosen factors are equal ``` Clearly, if the same number (greater than 1) divides both pieces, the same *prime* number will divide both. Requiring the factor to be prime neatly disallows 1 as a factor. It also prevents a literal `0` being chosen as a segment of a number (because `0` has no prime factorization, and will cause `ḋ` to fail). There's no need to check against matching internal zeroes; if a split of `x` and `0y` is valid, `x0` and `y` will work just as well (and going the other way, if `x0` and `y` works, then we have a working solution regardless of whether `x` and `0y` would work or not). A Brachylog full program, like this one, returns a Boolean; `true.` if there's some way to run it without failure (i.e. to make choices such that no error occurs), `false.` if all paths lead to failure. That's exactly what we want here. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~14~~ ~~12~~ ~~11~~ 10 bytes ``` ŒṖḌo1g/€P> ``` *Thanks to @JonathanAllan for golfing off 1 byte!* [Try it online!](https://tio.run/nexus/jelly#HY0xDgJBCEVr9xQcgMQBZmBobG3tN1NbegcbGysLT@EBtDZ7kPUiI7OEBN5PePTlsX6e6/t@ofP@d32dDv17ixl97H2edrM4gmaE7IbgnhCYRWKloghE5jQgUQly4uyqPCIxVvPq3DA0hUMTMUkYdNxA9VCzDC944gEqQ7OVmaTtWebiUpO0qf0B "Jelly – TIO Nexus") ### How it works ``` ŒṖḌo1g/€P> Main link. Argument: n ŒṖ Compute all partitions of n's decimal digits. Ḍ Undecimal; convert each array in each partition back to integer. o1 OR 1; replace disallowed zeroes with ones. g/€ Reduce (/) each (€) partition by GCD (g). The last GCD corresponds to the singleton partition and will always be equal to n. For a falsy input, all other GCDs will be 1. P Take the product of all GCDs. > Compare the product with n. ``` [Answer] ## Mathematica, ~~63~~ 62 bytes (1 byte thanks to Greg Martin) ``` 1<Max@@GCD@@@Table[1~Max~#&/@Floor@{Mod[#,t=10^n],#/t},{n,#}]& ``` It's a function that takes an integer as input and returns `True` or `False`. If you test it on a big number, bring a book to read while you wait. Explanation: * `Floor@{Mod[#,t=10^n],#/t}` arithmetically splits the input into its last `n` digits and the remaining `m-n` digits (where `m` is the total number of digits). * `Table[1~Max~#&/@...,{n,#}]` does this for every `n` up to the input number. (This is way too big. We only need to do this up to the number of *digits* of the input, but this way saves bytes and still gives the correct result.) The `1~Max~#&/@` bit gets rid of zeroes, so numbers like `130 -> {13,0}` don't count as `True`. * `1<Max@@GCD@@@...` finds the greatest common divisor of each of these pairs, and checks if any of these divisors are more than 1. If they are, we've found a way to factor the number by splitting it. [Answer] # [Haskell](https://www.haskell.org/), 57 bytes ``` x#n|b<-mod x n=x>n&&(b>0&&gcd(div x n)b>1||x#(10*n)) (#1) ``` [Try it online!](https://tio.run/nexus/haskell#bY1BCoMwEEX3PcWAJcQyhcyMSRyoXqS4qBWKC6OUUlx4dxv33T0e/Pf3tUhbf7tO8wArpGZtkzG2b50xr@dgh/F76LJvadvWwpK7pLLcp8eYoIFhhhMALO8xfeAM02MBW1AJd1EMFVYaUdUhswgq@YBEUSmjI4@kxJWGwFlI5BC1Vu7@9zxjICRxGPK@VkWWI@44U5Bci1Hc8VSxV6mddPsP "Haskell – TIO Nexus") Usage: `(#1) 2156`, returns `True` or `False` [Answer] # C, ~~145~~ ~~142~~ ~~139~~ ~~138~~ 135 bytes ``` i,a,b;f(){char s[99];scanf("%s",s);for(char*p=s;*p++;)for(b=atoi(p),i=*p,*p=0,a=atoi(s),*p=i,i=1;i++<b;)*s=a%i-b%i|b%i?*s:0;return!*s;} ``` [Answer] ## JavaScript (ES6), ~~74~~ ~~71~~ 70 bytes ``` f=(s,t='',u)=>u?s%t?f(t,s%t,1):t:s&&f(t+=s[0],s=s.slice(1),1)>1|f(s,t) ``` ``` <input oninput=o.textContent=f(this.value)><span id=o> ``` Takes input as a string, which is handy for the snippet. Edit: Saved 3 bytes thanks to @user81655. [Answer] # Python 3, ~~133~~ ~~118~~ 117 bytes ``` i,j=int,input() from fractions import* print(any(i(j[k:])*i(j[:k])*~-gcd(i(j[k:]),i(j[:k]))for k in range(1,len(j)))) ``` Certainly not the shortest, probably could be shortened a bit. Works in `O(n)` time. Input is taken in format `\d+` and output is given in format `(True|False)` as per default Python boolean value -3 bytes thanks to Dead Possum -15 bytes thanks to ovs -1 byte thanks to This Guy [Answer] ## [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), ~~91~~ 90 bytes ``` ;_LA|[a-1|B=left$(A,b)┘C=right$(A,a-b)┘x=!B!┘y=!C![2,x|~(x>1)*(y>1)*(x%c=0)*(y%c=0)|_Xq}?0 ``` Explanation: ``` ; Get A$ from the command prompt _LA| Get the length of A$ and place it in a% (num var) [a-1| for b%=1; b% <= a%-1; b%++ B=left$(A,b) break A$ in two components on index b% C=right$(A,a-b) x=!B!┘y=!C! Convert both parts from string to num, assign to x% and y% [2,x| FOR c% = 2; c% <= x%; c%++ This next IF (~ in QBIC) is a bit ... iffy. It consists of a set of comparators. Each comparator yields a -1 or a 0. We take the product of these. At any failed comparison this will yield 0. When successful, it yields 1, which is seen as true by QBasic. ~(x>1)*(y>1) IF X>1 and Y>1 --> this stops '00' and '1' splits. *(x%c=0)*(y%c=0) Trial divide the splits on loop counter c%. |_Xq Success? THEN END, and PRINT q (which is set to 1 in QBIC) } Close all language constructs (2 FOR loops and an IF) ?0 We didn't quit on match, so print 0 ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~70~~ 69 bytes ``` import math f=lambda n,d=1:n>d and n%d*~-math.gcd(n//d,n%d)+f(n,10*d) ``` [Try it online!](https://tio.run/nexus/python3#JY3BboQwDETP5Ct8qZRs093EgQQjbX9kxSFtoEVaDEKo2lN/nSZbnzwznudjmtdl22GO@7cYr/c4f6QIrNPVdvyeIHICfkmn37dycf76TJIvl6Szp15HydqaU1LHuGzwgIlh@Il3uawDS6PO2xCTVKoTVcm55I8O1m3iXeauUqL6F@q4iermSIOvNdQUNBAZDYjO5dU2XoO1gWwRxjZZkcWavMdiuYA@UEvY64xpMGOybV0m@NKBljIaXeECGSzCu4J5TgjOPJ/V2JBrjetF/wc "Python 3 – TIO Nexus") [Answer] # [Perl 5](https://www.perl.org/), 46 bytes 43 bytes of code + 3 bytes for `-p` flag. ``` s~~$\|=grep!($`%$_|$'%$_),2..$`if$`*$'~ge}{ ``` [Try it online!](https://tio.run/nexus/perl5#U1YsSC3KUdAt@F9cV6cSU2ObXpRaoKihkqCqEl@jog4kNXWM9PRUEjLTVBK0VNTr0lNrq///NzQ0tzQEAA "Perl 5 – TIO Nexus") or try [this modified version](https://tio.run/nexus/perl5#FYtLCoNAEAX37xRKOpiERPqjM2nEs@jGSMCFKLgSr24mm0dR1Lvk87BM2WuezvU4aNvbcRnm/Eb9lbqdirT3p5Yl9d8P9Q8qjnFoqGtpa2hr@TzNESpUHuHOUDWDSx0gEl0SstSoFUEgxgjJvd2h9j@wegYNlpIYjRk/) allowing multiple inputs. You probably don't want to try this on the largest input, as it might take a (very long) while. **Explanations:** We iterate through each position in the word with `s~~~g`, with `$`` containing the numbers before and `$'` the numbers after. If `$`*$'` is true (it means that none is empty, and none is `0`), then we check if a number between 2 and `$`` divides both of them (with the `grep!(...),2..$``). If so, `$\|=..` will set `$\` to a non-zero value, which is implicitly printed at the end thanks to `-p` flag. [Answer] # [Python 2](https://docs.python.org/2/), 69 bytes ``` f=lambda n,d=10,k=2:k<d<n and(n/d%k+n%d%k<1<n%d)|f(n,d,k+1)|f(n,10*d) ``` Uses recursion instead of GCD built-ins. [Try it online!](https://tio.run/nexus/python2#JYzdDoIwDIWv4Sl6Y7LpovtRdASehBCDDpIFKWSMCxPfHYs2afvlnJ76YRpDhPk9p9THuY2hfS5h9iO@/OAjU5KKr135aoaHawCFK5UUfanzvnAFQoOO4cnt@gPuaBaqoM0/HaNL0R/UH5XcO/oyBriDR2BSgOR5mmwKborHaYmM5zAFjxEow9Pkx2tlrIDsLOBsrwKspazWxhCqS1an1UWTrQQoQ05mieBmKaKNvdZf "Python 2 – TIO Nexus") ### How it works When **f** is called with one to three arguments (**d** defaults to **10**, **k** to **2**), it first checks the value of the expression `k<d<n`. If the inequalities **k < d** and **d < n** both hold, the expression following `and` gets executed and its value is returned; otherwise, **f** will simply return *False*. In the former case, we start by evaluating the expression `n/d%k+n%d%k<1<n%d`. **d** will always be a power of ten, so `n/d` and `n%d` effectively split the decimal digits on **n** into two slices. These slices are both divisible by **k** if and only if `n/d%k+n%d%k` evaluates to **0**, which is tested by comparing the result with **1**. Since part of the requirements is that both slices must represent positive integers, the value of `n%d` is also compared with **1**. Note that **1** has no prime divisors, so the more expensive comparison with **0** is not required. Also, note that **d < n** already ensures that `n/d` will evaluate to a positive integer. Finally it recursively all `f(n,d,k+1)` (trying the next potential common divisor) and `f(n,10*d)` (trying the splitting) and returns the logical OR of all three results. This means **f** will return *True* if (and only if) **k** is a common divisor of **n/d** and **n%d** or the same is true for a larger value of **k** and/or a higher power of ten **d**. ]
[Question] [ ## Braid Description In this braid, when a strand crosses over the top of another strand it adds the other strand's value to itself and all other strand values pass through. The braid has three strands and each strand begins at 1. The first crossover is the leftmost strand crossing over the middle strand. The next crossover is the rightmost strand crossing over the new middle strand (previously the leftmost strand). These two steps of crossovers repeat. In other words, the first crossover is `[a, b, c] -> [b, a+b, c]` and the second is `[a, b, c] -> [a, b+c, b]`. Using these rules here are the first six levels of the braid: ``` 1,1,1 1,2,1 1,3,2 3,4,2 3,6,4 6,9,4 ``` ## Your task Write a golfed program or function that accepts an integer as the braid level and outputs the three values for that level of the braid. You must indicate if your levels are zero- or one-based. Input and output may come in any reasonable format and trailing white space is allowed. ## Test Cases (1-based) ``` 1 -> 1,1,1 2 -> 1,2,1 5 -> 3,6,4 10 -> 28,41,19 ``` [Answer] # [MATL](https://github.com/lmendo/MATL), ~~18~~ ~~17~~ 16 bytes ``` 7Bi:"2:4PB@EX!Y* ``` Input is 0-based. [**Try it online!**](https://tio.run/nexus/matl#@2/ulGmlZOpppevk4BqhGKn1/78lAA "MATL – TIO Nexus") Or [**verify all test cases**](https://tio.run/nexus/matl#S/hv7pRppWTqaaXr5OAaoRip9T/WJeS/AZchlwmXJQA). ### Explanation Given a row vector `[a b c]`, the next vector is obtained post-matrix-multiplying it by either ``` [1 0 0; 0 1 1; 0 1 0] ``` or ``` [0 1 0; 1 1 0; 0 0 1] ``` depending on whether the iteration index is odd or even. For example, the matrix product `[1 3 2]*[0 1 0; 1 1 0; 0 0 1]` gives `[3 4 2]`. Then `[3,4,2]*[1 0 0; 0 1 1; 0 1 0]` gives `[3 6 4]`, and so on. Note also that the second matrix equals the first rotated 180 degrees, which can be exploited to save a few bytes. ``` 7 % Push 7 B % Convert to binary. Gives [1 1 1]. This is the initial level i % Take input n : % Push range [1 2 ... n] " % For each 5 % Push 5 I: % Push range [1 2 3] - % Subtract, element-wise: gives [4 3 2] B % Convert to binary. This gives the matrix [1 0 0; 0 1 1; 0 1 0] @ % Push current iteration index E % Multiply by 2. Gives 2 in the firt iteration, 4 in the second etc X! % Rotate matrix 90 degrees either 2 or 0 times Y* % Matrix multiply % End. Implicitly display ``` [Answer] ## Haskell, 51 bytes ``` f p@(a,b,c)=p:(b,a+b,c):f(b,a+b+c,a+b) (f(1,1,1)!!) ``` This uses 0-based indexing. Usage example: `(f(1,1,1)!!) 10` -> `(28,60,41)`. `f` creates the infinite list of braid triples and `(f(1,1,1)!!)` picks the nth one. `f` itself is a simple recursion which makes a list of its argument, followed by the left crossover and a recursive call with left and right crossover. [Answer] ## Ruby, ~~60~~ 57 bytes ``` ->n{f=->x{x<2?1:f[x-1]+f[x-3]};[f[n-2|1],f[n],f[n-1&-2]]} ``` The levels are 1-based. Based on the following formula: ``` f(-1) = 1 f(0) = 1 f(1) = 1 f(x) = f(x-1) + f(x-3) braid(x) = { [f(x-1), f(x), f(x-2)] if x is even, [f(x-2), f(x), f(x-1)] if x is odd } ``` Thanks to [Neil](https://codegolf.stackexchange.com/users/17602/neil) for 3 bytes off with some nifty bitwise shenanigans. [Answer] # [Python 2](https://docs.python.org/2/), 57 bytes ``` f=lambda n,a=1,b=1,c=1:1/n*(c,b,a)or f(n-1,b,b+c,a)[::-1] ``` [Try it online!](https://tio.run/nexus/python2#NYwxDsIwDEVnOIWXqjZ1hcxoKSdBDE7aoEpgUNT7BzN0eG/4T/q9ppe982LgbEk4ByWJytUvWDiz0adBRZ@jcZ5KDHfVWR69RnDYHJr5c0VhECE9n75t8x3G4bYohA5GGADRmWD6/xH1Hw "Python 2 – TIO Nexus") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes ``` Ḋ+\;Ḣ 6BÇ⁸¡Ṛ⁸¡ ``` [Try it online!](https://tio.run/nexus/jelly#@/9wR5d2jPXDHYu4zJwOtz9q3HFo4cOds8D0f0MDoEjTGvf/AA "Jelly – TIO Nexus") ### How it works ``` 6BÇ⁸¡Ṛ⁸¡ Main link. Argument: n (integer) 6B Convert 6 to binary, yielding [1, 1, 0], which is the braid at index 0. Ç⁸¡ Call the helper link n times. Ṛ⁸¡ Reverse the resulting array n times. Ḋ+\;Ḣ Helper link. Argument: [a, b, c] (integer array) Ḋ Dequeue, yielding [b, c]. +\ Cumulative sum, yielding [b, b+c]. ;Ḣ Concatenate with the head of [a, b, c], yielding [b, b+c, a]. ``` [Answer] # TI-Basic, 58 bytes One-based. ``` Prompt N {1,1,1 For(I,1,Ans If fPart(I/2 Then {Ans(2),Ans(1)+Ans(2),Ans(3 Else {Ans(1),Ans(2)+Ans(3),Ans(2 End End ``` [Answer] # PowerShell 2+, 75 bytes 1-based index ``` $a=1,1,0;1..$args[0]|%{$d=(0,2)[$_%2];$a[1],$a[$d]=($a[1]+$a[$d]),$a[1]};$a ``` ### [Try it online!](https://tio.run/nexus/powershell#@6@SaGuoY6hjYG2op6eSWJReHG0QW6NarZJiq2GgY6QZrRKvahRrrZIYbRirAyRVUmJtNcA8bQhPUwfMqwUq@f//v6EBAA "PowerShell – TIO Nexus") or [Try all Test Cases!](https://tio.run/nexus/powershell#S8svSk1MzlDQUClJLS4JS8xRyMxTMNQx0jHVMTTQVKjmUkksSo8vLk1SsFWAKeFSCgEyFJITi1Ot4IJKXOq26lqGpv9VEm0NdQx1DKwN9fRgmmtUq1VSbDUMdIw0o1XiVY1irVUSow1jdYCkSkqsrQaYpw3haeqAebVAJf/VdUFGctX@/w8A "PowerShell – TIO Nexus") The loop always runs once so for the case of braid level `1` I simply start with an array of `1,1,0` so the result of the algorithm with make it `1,1,1`. `$a[1]` is always the middle, then I just determine whether the other element index (`$d`) is going to be `0` or `2` based on whether the current level is even or odd. PowerShell supports multiple assignments at once so swapping becomes as easy as `$x,$y=$y,$x` which is basically what I'm doing with the array elements, just embedding the addition within that assignment. [Answer] # Javascript (ES6), 55 bytes ``` x=>(f=y=>y<2?1:f(y-1)+f(y-3),[f(x-2|1),f(x),f(x-1&-2)]) ``` [repl.it](https://repl.it/EvUy/0) 1-based This is just a port of @Doorknob's Ruby answer with @Neil's awesome bitwise golf. [Answer] # Befunge, 64 bytes ``` 110p100p1&v 01:\_v#:-1<\p00<v\+g ..g.@>_10g \1-:!#^_\:00g+\v>10p ``` [Try it online!](http://befunge.tryitonline.net/#code=MTEwcDEwMHAxJnYKMDE6XF92IzotMTxccDAwPHZcK2cKLi5nLkA-XzEwZwpcMS06ISNeX1w6MDBnK1x2PjEwcA&input=MTA) **Explanation** ``` 110p Initialise a to 1 (at location 1;0). 100p Initialise c to 1 (at location 0;0). 1 Initialise b to 1 (on the stack, since it'll be most frequently used). &v Read n from stdin and turn down. < The main loop starts here, executing right to left. -1 Decrement n. _v#: Duplicate and check if zero; if not, continue left. \ Swap b to the top of the stack, leaving n below it. 01: g Make a duplicate copy, and read a from memory (at location 1;0). + Add a to b, the result becoming the new b. v\ Swap the original b to the top of the stack and turn down. >10p Turn around and save the original b as a (at location 1;0). \1- Swap n back to the top of the stack and decrement. :!#^_ Duplicate and check if zero; if not continue right. \ Swap b to the top of the stack, leaving n below it. :00g Make a duplicate copy, and read c from memory (at location 0;0). + Add c to b, the result becoming the new b. \v Swap the original b to the top of the stack and turn down. p00< Turn around and save the original b as c (at location 0;0). \ Swap n back to the top of the stack. < And repeat the loop from the beginning. > If either of the zero tests succeed, we end up on line 3 going right. _ This just drops the n that is now zero, and continues to the right. 10g Read the final value of a (at location 1;0). .. Output a along with the b that was already on the stack. g Read the final value of c (the 0;0 location is implied). .@ Output c and exit. ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 17 bytes ``` 6bSIF¬¸s¦.pOì}¹FR ``` [Try it online!](https://tio.run/nexus/05ab1e#@2@WFOzpdmjNoR3Fh5bpFfgfXlN7aKdb0P//hgYA "05AB1E – TIO Nexus") [Answer] # Java 8, 121 This uses one-based levels: ``` (int l)->{int a=1,b=a,c=a,i=a;while(i<l)if(i++%2>0){b^=a;a^=b;b=(a^b)+a;}else{b^=c;c^=b;b=(c^b)+c;}return a+","+b+","+c;} ``` Ungolfed, with test program: ``` import java.util.function.IntFunction; public class GolfANumericalGrowingBraid { public static void main(String[] args) { for (int level : new int[] { 1, 2, 5, 10 }) { output((int l) -> { int a = 1, b = a, c = a, i = a; while (i < l) { if (i++ % 2 > 0) { b ^= a; a ^= b; b = (a ^ b) + a; } else { b ^= c; c ^= b; b = (c ^ b) + c; } } return a + "," + b + "," + c; } , level); } } private static void output(IntFunction<String> function, int level) { System.out.println(function.apply(level)); } } ``` Output: > > 1,1,1 > > 1,2,1 > > 3,6,4 > > 28,41,19 > > > [Answer] # GameMaker Language, 113 bytes One-indexed, based on Doorknob's recursive solution. *Please don't ask why you can't initialize a primitive array all at once in GameMaker, I really don't know...* Main program (69 bytes): ``` a=argument0 if a mod 2c=1b[0]=a(a-c-1)b[1]=a(a)b[2]=a(a+c-2)return b ``` Subprogram `a` (46 bytes): ``` a=argument0 if a<2return 1return a(a-1)+a(a-3) ``` [Answer] # [Perl 6](http://perl6.org/), 60 bytes ``` {(1 xx 3,->[\a,\b,\c]{$++%2??(a,b+c,b)!!(b,b+a,c)}...*)[$_]} ``` Zero-based. Straight-forwardly generated the lazy infinite sequence, and then indexes it. There are likely better approaches. [Answer] ## Clojure, 98 bytes ``` #(ffirst(drop %(iterate(fn[[v[a b c d]]][[(v a)(+(v b)(v c))(v d)][b a d c]])[[1 1 0][0 1 2 1]]))) ``` Keeps track of current value `v` and from which positions the summation should be made for next round. Starts one state before the `[1 1 1]` to have 1-based indexing. [Answer] # C# ~~88~~ 86 Bytes ``` f(int n,int a=1,int b=1,int c=1)=>n>1?n--%2>0?f(n,b,a+b,c):f(n,a,b+c,b):a+","+b+","+c; ``` ## Explanation ``` f(int n,int a=1,int b=1,int c=1)=> //Using an expression bodied function to allow for defaults and remove return statement n>1? //recurse or return result n--%2>0? //get odd or even then decrement n f(n,b,a+b,c) //odd recursion :f(n,a,b+c,b) //even recursion :a+","+b+","+c; //build output ``` [Answer] # Mathematica, 68 bytes ``` If[#<3,{1,#,1},{{#,+##2,#2}&,{#2,#+#2,#3}&}[[Mod[#,2,1]]]@@#0[#-1]]& ``` Straightforward recursive definition of an unnamed function, taking a positive integer argument and returning an ordered list of three integers. ]
[Question] [ ## Background Countless generations of children have wondered where they would end up if they dug a hole directly downwards. It turns out that this would, unsurprisingly, be [rather dangerous](https://what-if.xkcd.com/135/), but anyway... Antipodes are points that are directly opposite each other on the Earth's surface. This means that if a line was drawn between the two points, it would pass through the centre of the Earth. ## Challenge Write a program or function that, given a point, finds its antipode. In this challenge, points are represented using the longitude-latitude system and degrees, arc minutes and arc seconds. To find the antipode, swap the directions of each ordinate (`N <-> S` and `W <-> E`) and subtract the longitude ordinate from `180` degrees. Example: Take the point `N 50 26 23 W 4 18 29`. Swap the directions to give `S 50 26 23 E 4 18 29`. Subtract the longitude ordinate from `180 0 0` to give `175 41 31`, leaving the antipode coordinates as `S 50 26 23 E 175 41 31`. ## Rules ### Input A set of latitude-longitude coordinates, **in any reasonable format**, where each ordinate contains a direction, a number of degrees, a number of arc minutes, and a number of arc seconds. ### Output The latitude-longitude coordinates of the antipode, **in any reasonable format**, where each ordinate contains a direction, a number of degrees, a number of arc minutes, and a number of arc seconds. **Take reasonable to mean that each part of the coordinate can be distinguished unambiguously.** ### Specs * The direction for the latitude ordinate is `N` or `S`, and that for the longitude ordinate is `W` or `E`. * All coordinate values are integers. The degree value will be between `0` and `90` for latitude, and between `0` and `180` for longitude. The arc minute and arc second values for both ordinates will be between `0` and `59`. * If all the values for an ordinate are `0`, either direction is acceptable. * There is no need to zero-pad any values. * **No latitude ordinate will ever be larger than `90` degrees, and no longitude ordinate will ever be larger than `180` degrees.** * [Standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply. ## Test cases ``` N 50 26 23 W 4 18 29 -> S 50 26 23 E 175 41 31 S 43 9 9 E 0 0 5 -> N 43 9 9 W 179 59 55 N 0 0 0 E 0 0 0 -> S/N 0 0 0 W/E 180 0 0 (either direction fine in each case) S 1 2 3 W 4 5 6 -> N 1 2 3 E 175 54 54 S 9 21 43 W 150 7 59 -> N 9 21 43 E 29 52 1 S 27 40 2 W 23 0 0 -> N 27 40 2 E 157 0 0 N 0 58 37 W 37 0 0 -> S 0 58 37 E 143 0 0 ``` ## Useful links * [Latitude and longitude](https://en.wikipedia.org/wiki/Geographic_coordinate_system#Geographic_latitude_and_longitude) * [Antipodes](https://en.wikipedia.org/wiki/Antipodes) * [Arc minutes and arc seconds](https://en.wikipedia.org/wiki/Minute_and_second_of_arc) This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins! [Answer] ## JavaScript (ES6), 88 bytes ``` (a,b,c,d,e,f,g,h)=>[a<'S'?'S':'N',b,c,d,e<'W'?'W':'E',!(g|h)+179-f,g|h&&!h+59-g,h&&60-h] ``` Takes 8 parameters and returns an array as the result. Expects `a` to be one of `N` or `S` and similarly `e` to be one of `W` or `E`. Calculations: * `f` needs to be subtracted from 179 if either `g` or `h` is nonzero but 180 if both `g` and `h` are zero (because there is no borrow), thus `!(g|h)` is added to the 179. * `g` needs to be zero if both `g` and `h` are zero, thus `g|h&&`, otherwise it needs to be subtracted from 59 if `h` is nonzero but 60 if `h` is zero (because there is no borrow), thus `!h` is added to the 59. * `h` needs to be zero if it was already zero, otherwise it is simply subtracted from 60. Another way to look at this is to notice that subtracting in binary is achieved by adding the 1s complement plus an additional 1. Translated to this problem, we take `179-f`, `59-g` and `59-h` and add 1. `59-h` + 1 is `60-h`, but if this is 60 then it carries, so the desired result is zero if `h` was originally zero. We add 1 to `59-g` if there's a carry from `h`, i.e. if `h` was originally zero. Again we have to allow for a carry, which this time happens if both `g` and `h` are zero, and we add 1 to `179-f` in this case. [Answer] # [MATL](https://github.com/lmendo/MATL), 51 bytes ``` 'NS'tPXEii'WE'tPXE648e3i60:qXJZA-JYAtn3-?2:&)wJZAwh ``` Input format: ``` 'N' [50 26 23] 'W' [4 18 29] ``` Output format: ``` S 50 26 23 E 175 41 31 ``` [**Try it online!**](http://matl.tryitonline.net/#code=J05TJ3RQWEVpaSdXRSd0UFhFNjQ4ZTNpNjA6cVhKWkEtSllBdG4zLT8yOiYpd0paQXdo&input=J04nCls1MCAyNiAyM10KJ1cnCls0IDE4IDI5XQ) ### Explanation ``` 'NS'tPXE % Take input (string) implicitly. Exchange 'N' and 'S' i % Take input (array) i'WE'tPXE % Take input (string). Exchange 'W' and 'E' 648e3 % Push 648000 i % Take input (array) 60:qXJ % Push [0 1 ... 59]. Copy into clipboard J ZA % Convert second input array from base 60 to decimal - % Subtract JYA % Convert to base 60 tn3-? % If length exceeds 3 2:&) % Split into first two elements and then the rest w % Swap JZA % Convert from base 60 to decimal wh % Swap, concatenate ``` [Answer] # Racket, 199 bytes ``` (λ(l)(cons(cons(if(eq?(caar l)'n)'s'n)(cdar l))(cons(if(eq?(cadr l)'e)'w'e)(list (- 180(+(caddr l)(sgn(foldl + 0(cdddr l)))))(modulo(- 60(+(fourth l)(sgn(fifth l))))60)(modulo(- 60(fifth l))60))))) ``` That's horribly long. There's probably some things I could do to shorten it further, but *shudders* I'm completely done. Takes a `cons` pair of two `lists`: one for the latitude and one for the longitude. Each list has the direction (as a lowercase Racket symbol) as its first item and following it the degrees, arc-minutes, and arc-seconds. Outputs in the same format Racket will interpret this pair of two lists as a single list with another list as its first element. This is perfectly fine, since you can still access both latitude and longitude as if they were two lists in a pair. Usage: ``` > ( (λ(l)(cons(cons(if(eq?(caar l)'n)'s'n)(cdar l))(cons(if(eq?(cadr l)'e)'w'e)(list (- 180(+(caddr l)(sgn(foldl + 0(cdddr l)))))(modulo(- 60(+(fourth l)(sgn(fifth l))))60)(modulo(- 60(fifth l))60))))) (cons (list 's 43 9 9) (list 'e 0 0 5))) '((n 43 9 9) w 179 59 55) ``` Which can be interpreted by future code as `'((n 43 9 9) (w 179 59 55))`, two lists. [Answer] # Pyth, ~~41~~ ~~45~~ ~~43~~ 35 bytes ``` K60-"NS"ww-"EW"wA.D-*3^K3iEKK+.DGKH ``` Uses base-60 conversion to turn degrees and minutes into seconds. I/O format: ``` N [1,2,3] E [4,5,6] ``` It prints a line every time you input a line, so to have a good-looking format, you can either use the CLI and pipe the input, or more conveniently, [use the online Pyth implementation](http://pyth.herokuapp.com/?code=K60-%22NS%22ww-%22EW%22wA.D-%2a3%5EK3iEKK%2B.DGKH&input=N%0A%5B3%2C2%2C1%5D%0AE%0A%5B7%2C5%2C4%5D&test_suite=1&test_suite_input=N%0A%5B50%2C26%2C23%5D%0AW%0A%5B4%2C18%2C29%5D%0AS%0A%5B43%2C9%2C9%5D%0AE%0A%5B0%2C0%2C5%5D%0AN%0A%5B0%2C0%2C0%5D%0AE%0A%5B0%2C0%2C0%5D%0AS%0A%5B1%2C2%2C3%5D%0AW%0A%5B4%2C5%2C6%5D%0AS%0A%5B9%2C21%2C43%5D%0AW%0A%5B150%2C7%2C59%5D%0AS%0A%5B27%2C40%2C2%5D%0AW%0A%5B23%2C0%2C0%5D%0AN%0A%5B0%2C58%2C37%5D%0AW%0A%5B37%2C0%2C0%5D&debug=0&input_size=4). In pseudocode: ``` K60 K = 60 -"NS"w "NS".remove(input()) w print(input()) -"EW"w "EW".remove(input()) A.D G,H = divmod( -*3^K3 3*K**3 - iEK baseToDec(input(),K)), K K) +.DGKH divmod(G,K)+H ``` [Answer] ## Python 2, ~~140~~ 122 bytes Updated: ``` def f(c):x=([180,0,0],[179,59,60])[1<sum(c[6:8])];print['NS'['N'in c]]+c[1:4]+['EW'['E'in c]]+map(lambda x,y:x-y,x,c[5:8]) ``` This uses a slightly different approach: setting the values to subtract from the longitude based on the minutes and seconds. If there are 0 mins and seconds, it subtracts 180 from the degrees, and if there are >0 mins and secs, it subtracts 179, 59, and 60 from the d, m, s respectively. Original: ``` def f(c):v=divmod;m,s=v((180-(c[5]+c[6]/60.+c[7]/3600.))*3600,60);d,m=v(m,60);print['NS'['N'in c]]+c[1:4]+['EW'['E'in c]]+map(round,[d,m,s]) ``` Takes input as a list: `f(['N', 0, 0, 0, 'E', 0, 0, 0])`, converts the longitude to decimal degrees, subtracts from 180, then converts back to degrees, minutes, seconds and re-constructs the list, flipping the directions in the process. Un-golfed: ``` def f(c): minutes,seconds=divmod((180-(c[5]+c[6]/60.+c[7]/3600.))*3600,60) degrees,minutes=divmod(minutes,60) print ['NS'['N'in c]]+c[1:4]+['EW'['E'in c]]+map(round,[degrees,minutes,seconds]) ``` [Try it](https://repl.it/C9Db/1) [Answer] # JavaScript, ~~138~~ ~~137~~ ~~129~~ ~~124~~ ~~112~~ 110 2 bytes improvement inspired by @Neil´s code ``` f=a=>a.map((v,i,a)=>i%4?i>6?v&&60-v:i>5?(59-v+!a[7])%60:i>4?179-v+!(a[7]|a[6]):v:'NEWS'[3-'NEWS'.indexOf(v)]); ``` * input = output = array containing 2x(1 uppercase char and 3 int) * tested in Firefox **ungolfed** ``` f=a=>a.map((v,i,a)=> i%4? i>6?v&&60-v // 7: invert seconds - old: (60-v)%60 :i>5?(59-v+!a[7])%60 // 6: invert minutes, increase if seconds are 0 :i>4?179-v+!(a[7]|a[6]) // 5: invert degrees, increase if seconds and minutes are 0 :v // 1,2,3: unchanged :'NEWS'[3-'NEWS'.indexOf(v)] // 0,4: swap directions ); ``` **tests** ``` <table id=out border=1><tr><th>in</th><th>out<th>expected</th><th>ok?</th></tr></table> <script> addR=(r,s)=>{var d=document.createElement('td');d.appendChild(document.createTextNode(s));r.appendChild(d)} test=(x,e,f)=>{var y,r=document.createElement('tr');addR(r,x);addR(r,y=('function'==typeof f)?f(x):f);addR(r,e);addR(r,e.toString()==y.toString()?'Y':'N');document.getElementById('out').appendChild(r)} samples=[ 'N',50,26,23,'W',4,18,29, 'S',50,26,23,'E',175,41,31, 'S',43,9,9,'E',0,0,5, 'N',43,9,9,'W',179,59,55, 'N',0,0,0,'E',0,0,0, 'S',0,0,0,'W',180,0,0, 'S',1,2,3,'W',4,5,6, 'N',1,2,3,'E',175,54,54, 'S',9,21,43,'W',150,7,59, 'N',9,21,43,'E',29,52,1, 'S',27,40,2,'W',23,0,0, 'N',27,40,2,'E',157,0,0, 'N',0,58,37,'W',37,0,0, 'S',0,58,37,'E',143,0,0, ]; while (samples.length) { x=samples.splice(0,8); e=samples.splice(0,8); test(x,e,h); test(e,x,h); } </script> ``` [Answer] # Python 3, ~~131~~ 130 bytes ``` def f(w,x,y,z):S=60;d=divmod;a,b,c=y;l,m=d(648e3-c-S*b-S*S*a,S);return w,"N" if x=="S" else "S",d(l,S)+(m,),"E" if z=="W" else "W" ``` Formats: angles are tuples of the form `(deg,min,sec)`, directions are of the form `N`. Outputs a quadruple of 2 angles, each followed by its direction. Ungolfed version: ``` def f(latitude,NS,longitude,EW): degree,minute,second=longitude minute,second=divmod(648000-second-60*minute-60*60*degree,60) return latitude, "N" if NS=="S" else "S", divmod(minute,60)+(second,), "E" if EW=="W" else "W" ``` [Answer] # C#, ~~310~~ 269 bytes ``` float[]t(string[]a,int n)=>a.Skip(n).Take(3).Select(float.Parse).ToArray();string A(string i){var s=i.Split(' ');var w=t(s,5);float a=180-(w[0]+w[1]/60+w[2]/3600),b=a%1*60;return(s[0][0]>82?"N":"S")+$" {string.Join(" ",t(s,1))} {(s[4][0]<70?'W':'E')} {a} {b} "+b%1*60;} ``` The input is one string. You can try it on [.NetFiddle](https://dotnetfiddle.net/W3lEVs). Code ``` float[]t(string[]a,int n)=>a.Skip(n).Take(3).Select(float.Parse).ToArray(); string A(string i) { var s=i.Split(' ');var w=t(s,5);float a=180-(w[0]+w[1]/60+w[2]/3600),b=a%1*60; return (s[0][0]>82?"N":"S") +$" {string.Join(" ",t(s,1))} {(s[4][0]<70?'W':'E')} {a} {b} "+b%1*60; } ``` --- If I don't take a `string` as input but a `char, float[], char, float[]`, I can do: # C#, ~~167~~ ~~166~~ ~~165~~ ~~163~~ ~~152~~ ~~148~~ ~~147~~ 139 bytes ``` (s,n,e,w)=>{float a=180-(w[0]+w[1]/60+w[2]/3600),b=a%1*60;return(s>82?"N":"S")+$" {string.Join(" ",n)} {(e<70?'W':'E')} {a} {b} "+b%1*60;}; ``` Code ``` (s,n,e,w) => { float a=180-(w[0]+w[1]/60+w[2]/3600),b=a%1*60; return(s>82?"N":"S")+$" {string.Join(" ",n)} {(e<70?'W':'E')} {a} {b} "+b%1*60; }; ``` Also I can remove the `3600` and use [`ฐ`](http://unicode-table.com/en/0E10/) instead to move to 164 characters and 166 bytes. Should I use it? --- # C#, 150 bytes ``` (s,n,m,p,e,w,x,y)=>{var t=new TimeSpan(180,0,0)-new TimeSpan(w,x,y);return(s>82?"N":"S")+$" {n} {m} {p} {(e<70?'W':'E')} {t.TotalHours} {t:%m\\ s}";}; ``` Code ``` (s,n,m,p,e,w,x,y) => { var z=new TimeSpan(180,0,0)-new TimeSpan(w,x,y); return(s>82?"N":"S")+$" {n} {m} {p} {(e<70?'W':'E')} {z.TotalHours} {z:%m\\ s}"; }; ``` A more .NET way! I delegate all the logic to the .NET `struct` `TimeSpan` and I ~~ab~~use the string formatting logic. Input is `char, int, int, int, char, int, int, int`. I share this one to give some ideas. Maybe someone will improve in a better way than me. [Answer] ## 05AB1E, ~~37~~ 34 bytes ``` `60©3L<Rm*O3°648*s-®‰`s®‰s‚˜)'€Ã‡ ``` **Explained** ``` ` # split input to 4 lines with longitude on top 60©3L<Rm*O # convert longitude to seconds 3°648* # longitude 180 0 0 in seconds s- # subtract our longitude from this ®‰` # get seconds part s®‰ # get minute and degrees part s‚˜) # join to list '€Ã‡ # translate directions ``` [Try it online](http://05ab1e.tryitonline.net/#code=YDYwwqkzTDxSbSpPM8KwNjQ4KnMtwq7igLBgc8Ku4oCwc-KAmsucKSfigqzDg8OC4oCh&input=WydzJyxbOSwgMjEsIDQzXSwndycsWzE1MCwgNywgNTldXQ) **Edit:** Saved 3 bytes thanks to [Adnan](https://codegolf.stackexchange.com/users/34388/adnan). [Answer] # Java, ~~199~~ 177 or 151 or 134 Bytes 177 Bytes solution which prints result ``` void t(int...a){int i=648000-(a[5]*3600+a[6]*60+a[7]);System.out.println(a[0]=='N'?"S":"N"+" "+a[1]+" "+a[2]+" "+a[3]+" "+(a[4]=='E'?"W":"E")+" "+i/3600+" "+i/60%60+" "+i%60);} ``` 151 Bytes solution which returns result as array ``` Object[]y(int...a){int i=648000-(a[5]*3600+a[6]*60+a[7]);return new Object[]{a[0]=='N'?"S":"N",a[1],a[2],a[3],a[4]=='E'?"W":"E",i/3600,i/60%60,i%60};} ``` 134 Bytes if we used lambda notation ``` a->{int i=648000-a[5]*3600-a[6]*60-a[7];return new Object[]{a[0]=='N'?"S":"N",a[1],a[2],a[3],a[4]=='E'?"W":"E",i/3600,i/60%60,i%60};} ``` [Answer] # C, 188 ``` main(int c,char**v){int n=*v[1]==78?83:78,e=*v[5]==69?87:69,b=648000-(atoi(v[6])*3600+atoi(v[7])*60+atoi(v[8]));printf("%c %s %s %s %c %d %d %d\n",n,v[2],v[3],v[4],e,b/3600,b/60%60,b%60);} ``` Requires 8 program arguments, will fail otherwise. Pass arguments like `N 50 26 23 W 4 18 29`. Direction indicators `N`, `S`, `E`, `W`, must be capitalized. [Answer] # PostGIS, 123 bytes The Tool-For-The-Job is disappointingly verbose, partly because of SQL wordiness and partly due to the need to cast to geometry and back: ``` CREATE FUNCTION f(p geography) RETURNS geography AS 'SELECT ST_Affine(p::geometry,1,0,0,-1,180,0)::geography' LANGUAGE sql; ``` On the other hand, this single function will transform points, collections of points, or more complex shapes (such as the entire coastline of Australia and New Zealand). [Answer] # PHP, 148 bytes same approach as [my JavaScript answer](https://codegolf.stackexchange.com/questions/84560/dig-to-australia-antipodes/84603/#84603), look there for a breakdown * +16 function overhead * +17 for `$` signs * +12 for parantheses (different operator precedence) * +4 for `foreach` because PHP´s `array_map` has a huge overhead * +1 for `(60-$v)%60` because `$v&&60-$v` casts to boolean in PHP * -8 by working on the original * -4 by using `chr`, `ord` and some arithmetics on the direction swap ``` function f(&$a){foreach($a as$i=>$v)$a[$i]=$i%4?($i>6?(60-$v)%60:($i>5?(59-$v+!$a[7])%60:($i>4?179-$v+!($a[7]|$a[6]):$v))):chr(($i?156:161)-ord($v));} ``` * function works on original * format: array with 2x (1 uppercase char, 3 int) **tests** ``` function out($a){if(!is_array($a))return$a;$r=[];foreach($a as$v)$r[]=out($v);return'['.join(',',$r).']';} function cmp($a,$b){if(is_numeric($a)&&is_numeric($b))return 1e-2<abs($a-$b);if(is_array($a)&&is_array($b)&&count($a)==count($b)){foreach($a as $v){$w = array_shift($b);if(cmp($v,$w))return true;}return false;}return strcmp($a,$b);} $samples=[ N,50,26,23,W,4,18,29, S,50,26,23,E,175,41,31, S,43,9,9,E,0,0,5, N,43,9,9,W,179,59,55, N,0,0,0,E,0,0,0, S,0,0,0,W,180,0,0, S,1,2,3,W,4,5,6, N,1,2,3,E,175,54,54, S,9,21,43,W,150,7,59, N,9,21,43,E,29,52,1, S,27,40,2,W,23,0,0, N,27,40,2,E,157,0,0, N,0,58,37,W,37,0,0, S,0,58,37,E,143,0,0, ]; while ($samples) { $xx=$x=array_splice($samples,0,8); $ee=$e=array_splice($samples,0,8); func($x); test($xx,$ee,$x); func($e); test($ee,$xx,$e); } ``` **abandoned ideas** * no loop approach with carry flags: +5 * loop backwards with carry flags: +7 * I could turn this into a program for PHP<5.4, but never mind: -3 [Answer] # Befunge, ~~122~~ ~~114~~ 111 Bytes (110 characters) ``` ~"N"-v v"N"_"S" v>,&.&.&.~"W"- _"E"v"W" +:v >,&"´"\-&"Z"*& v\_\[[email protected]](/cdn-cgi/l/email-protection)\"<".-1\ < >1-.:"Z"/"<"\-\"Z"%:#^_\..@ ``` Input format: ``` N 50 26 23W 4 18 29 ``` Notice the longitude direction and the arc seconds must be huddled together You may test the code [here](http://www.quirkster.com/iano/js/befunge.html) ]
[Question] [ Santa needs some help determining how many elves he will need to help him deliver gifts to each house. Coal is considerably heavier than presents, so santa will need three elves for every naughty person in the house. Only two elves are needed to help santa carry presents. On santa's map, a house is represented by a `*`, and each house is split by a `+`. There will be a number on either side of the house - the one on the left representing the number of naughty people in the house, and the one on the right representing the number of nice people in the house. If there is no number on one side it is interpreted as a 0. Santa doesn't visit those who are not in the christmas spirit (they don't even deserve coal), so sometimes, a house may not have a number on either side of it. In this case, santa doesn't need help from any elves For example, one of santa's maps may look like this ``` 1*3+2*2+1*+*2 ``` In the first house there is **1** naughty and **3** nice, santa will need **nine** elves. In the second, there are **2** naughty and **2** nice, santa will need **ten** elves. In the third house there is **1** naughty and **0** nice, santa will need **three** elves, and in the last house there are **0** naughty and **2** nice, santa will need **four** elves. This is an over-simplified version of one of santa's maps, though. Normally, santa's maps have multiple lines, and are in a square shape as to better fit on his list. A normal map might look something like this (a `\n` at the end of each line) ``` 1*2+*+*4+1* 2*4+3*+1*6+* *+*+4*2+1*1 *4+*3+1*+2*3 3*10+2*+*5+* ``` In this map, santa needs `((1 + 0 + 0 + 1 + 2 + 3 + 1 + 0 + 0 + 0 + 4 + 1 + 0 + 0 + 1 + 2 + 3 + 2 + 0 + 0) * 3) + ((2 + 0 + 4 + 0 + 4 + 0 + 6 + 0 + 0 + 0 + 2 + 1 + 4 + 3 + 0 + 3 + 10 + 0 + 5 + 0) * 2)` = **151** elves ## Challenge Help santa determine how many elves he needs to deliver goods to each house! **Houses** * A house is represented by a `*` * Houses are split by `+` * The number on the left of the house symbolizes the number of naughty people (no number means 0) * The number on the right symbolizes the number of nice people (no number means 0) * There may be newlines (`\n`) in the input, which should also be handled as a split **Elves** * Santa needs help from *three* elves for naughty people (coal is much heavier than presents) * Santa needs help from **two** elves for nice people * If there is no number on either side, santa will not visit that house, and therefor does not need any elves **What to do** Print the number of elves santa needs to help him deliver presents to the houses to. Because all Santa needs to know is how many elves to bring, you only need to print the added number of elves he needs for the list of houses ## Test Cases ``` 1*1 => 5 1*2 => 7 2*1 => 8 1* => 3 *1 => 2 * => 0 1*1+1*1 => 10 1*2+2*1 => 15 1*+*1 => 5 1*1+*+1*1 => 10 *+*+*+* => 0 ``` ## Rules * The input can be either taken as an argument in a function, or from **STDIN** or equivalent * The output can either be the return value of a function, or printed to **STDOUT** or equivalent * The input will only contain numbers, `+`, `*`, and newlines `\n` * The output should be only the total number of elves that Santa needs help from to deliver on Christmas * [Standard loopholes](https://codegolf.meta.stackexchange.com/q/1061/20634) apply ## Scoring Santa's sleigh is full of gifts giving him less space to run code, so he needs the shortest code he can get (don't worry if this doesn't make sense. If you question Santa's logic you'll end up on the naughty list). Due to Santa's ***CORRECT*** reasoning, the shortest submission in bytes wins! ## Leaderboard This is a Stack Snippet that generates both a leaderboard and an overview of winners by language. To ensure your answer shows up, please start your answer with a headline using the following Markdown template ``` ## Language Name, N bytes ``` Where N is the size, in bytes, of your submission If you want to include multiple numbers in your header (for example, striking through old scores, or including flags in the byte count), just make sure that the actual score is the *last* number in your header ``` ## Language Name, <s>K</s> X + 2 = N bytes ``` ``` var QUESTION_ID=67600;var OVERRIDE_USER=20634;function answersUrl(e){return"http://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"http://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] # JavaScript (ES6), 52 bytes ``` s=>eval(s.replace(/\D|$/g,m=>`.0*${m=="*"?3:2}+`)+0) ``` ## Explanation Converts the input into a valid JavaScript statement. Replaces all `*` with `.0*3+` and all other (non-digit) symbols with `.0*2+`. For example `8*9+*10` becomes `8.0*3+9.0*2+.0*3+10`. Finally it appends `.0*2` to the end for the last nice count. This works because `n.0` = `n` and `.0` = `0`. ``` s=> eval( // execute the formed equation s.replace(/\D|$/g, // replace each symbol (and also add to the end) with: m=>`.0*${m=="*"?3:2}+` // case * = ".0*3+", else replace with ".0*2+" ) +0 // add "0" to the end for the trailing "+" ) ``` ## Test ``` var solution = s=>eval(s.replace(/\D|$/g,m=>`.0*${m=="*"?3:2}+`)+0) ``` ``` <textarea id="input" rows="6" cols="30">1*2+*+*4+1* 2*4+3*+1*6+* *+*+4*2+1*1 *4+*3+1*+2*3 3*10+2*+*5+*</textarea><br /> <button onclick="result.textContent=solution(input.value)">Go</button> <pre id="result"></pre> ``` [Answer] ## Flex+C, ~~112~~ 90 bytes ``` m=3,t; %% [0-9]+ t+=m*atoi(yytext); \* m=2; [+\n] m=3; %% main(){yylex();printf("%d",t);} ``` The first character is a space. Compile with: ``` flex -o santa.c santa.l cc santa.c -o santa -ll ``` Reads from STDIN, writes to STDOUT. Input is terminated by EOF (Ctrl+D in console). [Answer] # Pyth, 21 bytes ``` ssMs*VCcR\*scR\+.z_S3 ``` [Multi-line example](https://pyth.herokuapp.com/?code=ssMs%2aVCcR%5C%2ascR%5C%2B.z_S3&input=1%2a2%2B%2a%2B%2a4%2B1%2a%0A2%2a4%2B3%2a%2B1%2a6%2B%2a%0A%2a%2B%2a%2B4%2a2%2B1%2a1%0A%2a4%2B%2a3%2B1%2a%2B2%2a3%0A3%2a10%2B2%2a%2B%2a5%2B%2a&debug=0) [Single-line test suite](https://pyth.herokuapp.com/?code=ssMs%2aVCcR%5C%2ascR%5C%2B.z_S3&test_suite=1&test_suite_input=1%2a1%0A1%2a2%0A2%2a1%0A1%2a%0A%2a1%0A%2a%0A1%2a1%2B1%2a1%0A1%2a2%2B2%2a1%0A1%2a%2B%2a1%0A1%2a1%2B%2a%2B1%2a1%0A%2a%2B%2a%2B%2a%2B%2a&debug=0) ``` ssMs*VCcR\*scR\+.z_S3 .z Take a input, as a list of lines. cR\+ Chop each line on '+'. s Flatten into list of strings. cR\* Chop each line on '*'. C Transpose, into a list of naughty and nice. *V _S3 Vectorized multiplication with [3, 2, 1]. This replicates the naughty list 3 times and the nice list 2 times. s Flatten. sM Convert each string to an int. s Sum. ``` [Answer] ## Mathematica, 70 bytes ``` a=Tr[FromDigits/@StringExtract[#," "|"+"->;;,"*"->#2]]&;3#~a~1+2#~a~2& ``` Uses `StringExtract` to extract the individual numbers. [Answer] ## CJam, 23 bytes ``` q'+NerN/{'*/3*5<:~~}%1b ``` [Test it here.](http://cjam.aditsu.net/#code=q'%2BNerN%2F%7B'*%2F3*5%3C%3A~~%7D%251b&input=1*2%2B*%2B*4%2B1*%0A2*4%2B3*%2B1*6%2B*%0A*%2B*%2B4*2%2B1*1%0A*4%2B*3%2B1*%2B2*3%0A3*10%2B2*%2B*5%2B*) ### Explanation ``` q e# Read all input. '+Ner e# Replaces all "+" with linefeeds. N/ e# Split the string around linefeeds (i.e. into houses). { e# Map this block over the list of house... '*/ e# Split the string around the "*". 3* e# Repeat the times. 5< e# Truncate to 5 elements, keeping 3 copies of the naughty number and 2 copies of e# the nice number. :~ e# Evaluate each number (which may be an empty string which pushes nothing). ~ e# Dump the list of numbers on the stack. }% 1b e# Sum all the numbers. ``` [Answer] ## Seriously, ~~38~~ 30 bytes ``` '*Ws`'0+'*@s'≈£M4rR*`MΣ+'+,WXX ``` Hex Dump: ``` 272a57736027302b272a407327f79c4d3472522a604de42b272b2c575858 ``` This new version breaks the online interpreter, but works fine locally. Here's an example run: ``` $ python2 seriously.py -f elves.srs 1*2+*+*4+1* 2*4+3*+1*6+* *+*+4*2+1*1 *4+*3+1*+2*3 3*10+2*+*5+* 151 ``` Explanation: ``` '* Push a "*" to make the stack truthy W W Repeat while the top of stack is truthy (A whole bunch of instructions just turn the "*" into a zero on the first pass, so I'll list them here in the order they actually accomplish useful things:) , Read in a line of input s '+ Split it on occurrence of "+" ` `M Map this function over the list of strings. '0+ Prepend a "0" to ensure a naughty number exists '*@s Split the string on "*" '≈£M Map over the string with int() to convert it to int 4rR Push [3,2,1,0] * Dot product Σ+ Sum all the houses, and add it to the results from the previous line of input XX Pop the "" and '+ from the stack, leaving only the result to be implicitly output. ``` ### Old Version: ``` '+ε'*`+'++,`╬Xs`≈`╗`'0+'*@s╜M[3,2]*`MΣ ``` Hex Dump: ``` 272bee272a602b272b2b2c60ce587360f760bb6027302b272a4073bd4d5b332c325d2a604de4 ``` [Try It Online](http://seriouslylang.herokuapp.com/link/code=272bee272a602b272b2b2c60ce587360f760bb6027302b272a4073bd4d5b332c325d2a604de4&input=1*3+2*2+1*+*2) Explanation: ``` ε'* Initialize with two strings so the first + works `+'++,`╬ Read in strings and compile them until "" is read X Throw away the "" '+ s Split on + `≈`╗ Chuck int function into reg0 to use within function ` `M Map this function over the list of houses '0+ Prepend a "0" to ensure a naughty number exists '*@s Split on * ╜M Convert the resulting list to ints with stored func [3,2]* Dot product with [3,2] Σ Sum all houses ``` This maybe could be shorter if I just converted each line separately and summed them all at the end. I'll look into it later. [Answer] ## PowerShell, 52 bytes Using variation of [user81655](https://codegolf.stackexchange.com/a/67605/48455)'s `.0` trick ``` $OFS='+';"$("$args"-replace'\*','.0*3+2*0'|iex)"|iex ``` ### Ungolfed version ``` $OFS='+' # Set Output Field Separator to '+' # So if $arr = 1,2,3 then "$arr" will output 1+2+3 " # Cast result of subexpression to string using $OFS $( # Subexpression "$args" # Input is an array of arguments. Casting it to string using "$args" # is shorter then acessing the first element using $args[0] # $OFS wouldn't affect this, because input has only 1 element. -replace '\*' , '.0*3+2*0' # Replace every * with .0*3+2*0 # Example: 1*+*1 becomes 1.0*3+2*0+.0*3+2*01 ) | Invoke-Expression # Execute a result of subexpression as PS code. # This will execute resulting multiline string line-by line # and return an array of values, e.g.: 18,38,21,29,45 " Cast the aray above to string using '+' as Output Field Separator, e.g: 18+38+21+29+45 | Invoke-Expression # Execute the string above as PS code to get final result. # E.g.: 18+38+21+29+45 = 151 ``` ### Usage example ``` $Map = @' 1*2+*+*4+1* 2*4+3*+1*6+* *+*+4*2+1*1 *4+*3+1*+2*3 3*10+2*+*5+* '@ PS > .\SantaMap.ps1 $Map 151 ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `Dad`, 12 bytes ``` ƛ‛\Wṡ⌊:ż∷2+* ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJEYWQiLCIiLCLGm+KAm1xcV+G5oeKMijrFvOKItzIrKiIsIiIsIjEqMisqKyo0KzEqXG4yKjQrMyorMSo2KypcbiorKis0KjIrMSoxXG4qNCsqMysxKisyKjNcbjMqMTArMiorKjUrKiJd) ``` ƛ # Map (multiline input) to... ‛\Wṡ # Split on non-word chars ⌊ # parse an integer from each :ż # 1...x.length ∷2+ # Modulo 2, + 1 results in array of 2s and 3s * # Multiply these # (d flag) deep sum of result ``` `D` makes sure the backslash in `‛\W` doesn't get removed, `a` is necessary for multiline input and `d` takes the deep sum of the result. [Answer] ## Swift 2, ~~283~~ 211 Bytes ``` func f(s:String)->Int{var r=0;for p in(s.characters.split{$0=="\n"}.map(String.init)){for v in p.utf8.split(43){let k="0\(v)".utf8.split(42);r+=(Int("\(k[0])")!)*3;r+=(k.count<2 ?0:Int("\(k[1])")!)*2}};return r} ``` This can be tested [on SwiftStub, here](http://swiftstub.com/660834156) ### Ungolfed ``` func f(s: String) -> Int{ var r = 0 //for every value in the input, split every "\n" and mapped //to a String array for p in (s.characters.split{$0=="\n"}.map(String.init)){ //for every value in the split input, split again at every + (Decimal 43) for v in p.utf8.split(43){ //change the value to "0" + v, which doesn't change the //input, but in the event that there is no input on the //left side, a "0" will be used // //then split on every * (Decimal 42) let k = "0\(v)".utf8.split(42) //add to the total count of elves the number on the left * 3 r+=(Int("\(k[0])")!) * 3 //add to the total count of elves the number on the left * 2 r+=(k.count < 2 ? 0 : Int("\(k[1])")!) * 2 } //return the number of elves return r } } ``` [Answer] # Python 3, ~~141~~ ~~114~~ 112 bytes Takes multi-line inputs like this `c("1*2+*+*4+1*\n2*4+3*+1*6+*\n*+*+4*2+1*1\n*4+*3+1*+2*3\n3*10+2*+*5+*")` ``` lambda s:sum(a and(3-z)*int(a)or 0for j in s.split("\n")for i in j.split("+")for z,a in enumerate(i.split("*"))) ``` **Ungolfed:** ``` def c(s): t = 0 for j in s.split("\n"): for i in j.split("+"): for z,a in enumerate(i.split("*")) if a == "": a = 0 else: a = int(a) t += (3-z) * a # alternate a*3 and a*2 return t ``` [Answer] I'm super late, but I wanted to give it a shot anyways. # [Ruby](https://www.ruby-lang.org/), ~~84~~ 55 bytes I found this question again after so many years and was thinking up a fresh answer before I realized I'd already answered this before. Whoops! Anyways, here's a drastically improved answer. ``` ->m{m.scan(/(\d*)\*(\d*)/).sum{|a,b|3*a.to_i+2*b.to_i}} ``` [Try it online!](https://tio.run/##HYyxDoIwFEX3foWDA9ynxdeik/ojYkwrkjBUDaWDAb69vjCdk3OTOyT/y90l769hCjo@3buoiqZF2WBFVeqYwjS7nZ8tnB4/j54M/CrLkr9pjJvutj3r4eXae2YYAqEmhjICC7ETQUmkWkYGK@mwYnJklQUfRAhHwh8 "Ruby – Try It Online") Old 84-byte answer from when I first answered this 2 years ago: ``` ->m{m.split(/[+\n]/).map{|h|b,g=h.split(?*).map &:to_i 3*(b||0)+2*(g||0)}.inject :+} ``` [Try it online!](https://tio.run/##LYzLDoIwEEX3/QoWxsCMFkrRBRH9ECQG5GksEigLQ/n2OhpX9@Sc5I5z8bZ1YvdntSg@Dc9Ou36K1z7zPa7yYTGtKXZN0v7bBX7a2cb6deuYBLcwJvAwBLf5wsq7/lHdtRPjaodZT06dbk58rPIyswJCBIQIBbCQRgLREYGRxIiiAMHIgySiS0n/IiBAOCB8AA "Ruby – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 96 bytes ``` lambda s:sum(int('0'+n)*(3-i%2)for i,n in enumerate(re.sub('[*\s]','+',s).split('+')));import re ``` [Try it online!](https://tio.run/##TVDLboMwELzzFVakavGjEWtDWqWiPxI4ENWoSMEgDId@Pd2FpI18WM/OwyOPP/P3ENzaltV6a/rrVyPiOS592oU5hQx0kCp1r92Lle0wic4E0QXhw9L7qZl9OvljXK4pXFQVazCgwUR5jOOtI7sGKeVH14/DNIvJr5ww@zhzBACgQlF@isKgsnx5M3bfvNOGpzM7tmaDGa1R313IyOq7AzlE/@ehVk9CYvhsGfTuo54BeU7E3qjcxoNhJUjixon/gakL1kZACUa0O85qKZNkF9jTH3dA5aiV1dzHHkizS7DAZ43lQjmJqmBpOq570oS4ab7ZkUCuKY2SrHJVcAozumlVaEXB6y8 "Python 3 – Try It Online") 101 bytes without regex ``` lambda s:sum(int('0'+n)*(3-i%2)for i,n in enumerate(s.replace('*','+').replace('\n','+').split('+'))) ``` [Try it online!](https://tio.run/##TVDLboMwELzzFVakavGjFWtDWkWiP1JyoK1RLYGDgBz69XQXkybisDuPHY8Yf5efS3RrVzdr3w6f362YT/N1yENccihAR6ly9xyerOwukwgmihCFj9fBT@3i8/ll8mPffvkcFBjQIO9EE3dmHvtAabRKuXLM4ueFcwAAFYr6XVQGleXl1djEvBHD05mErdlgQTTq/QoZWb1fIIfoex5q9WAkhb8tg969lTIgT5lIjept3BR2giRtnPhnsPSBZyOgBiO6hIuzlFmWDPb4rx1QOWplNfexB/IkC1b46LFcqCRTEy1Nx3WPmhA3LbdzJFBqSqMkq1wTncKCNq0qrSh4/QM "Python 3 – Try It Online") [Answer] # JavaScript (ES6), 47 bytes ``` x=>x.split(/\W/).reduce((y,x,i)=>y+x*(3-i%2),0) ``` [Try it online!](https://tio.run/##DclBDoIwFIThfe9h0s6DQls0buAablxAKpiaRgggKaevbzVf/vkMx7D5NSx7edzz1ObUdklvSwy7rJ6PSul1fP38KOVZpCKotjspQboyXKwqapX9/N3mOOo4v@UkewNLIDRkICyPA@tGEByp4dPACO5wLLJwwsHUDMKV0CuV/w "JavaScript (V8) – Try It Online") Beats the winning JS answer! ## How does it work? ``` x => // Defining a function taking an argument x x.split( // Split x on... /\W/ // The regex \W, matching non-word characters ) .reduce(( // Reduce by a function taking... y, // y - current total value x, // x - value of this one i // i - index in input ) => // and returning y + x * // y, plus x times... (3 - i % 2) // 3 if index is even (naughty) otherwise 2 , 0) // With initial value 0. ``` ]
[Question] [ The game of [Chinese checkers](http://en.wikipedia.org/wiki/Chinese_checkers) is played on a board with spaces in the shape of a six-pointed star: ![Board image](https://i.stack.imgur.com/vNW7w.png) [Image from Wikipedia](http://en.wikipedia.org/wiki/File:Chinese_checkers_start.png) We can create an ASCII-art representation of this board, using `.` for empty spots and the letters `GYORPB` for the six colored starting locations: ``` G G G G G G G G G G B B B B . . . . . Y Y Y Y B B B . . . . . . Y Y Y B B . . . . . . . Y Y B . . . . . . . . Y . . . . . . . . . P . . . . . . . . O P P . . . . . . . O O P P P . . . . . . O O O P P P P . . . . . O O O O R R R R R R R R R R ``` To make it more interesting, we can also change the size. We'll measure the size of a board by the side length of its triangular starting locations: the board above is size 4. Since it's really a pain to type all that by hand, let's write a program (or function) to do it! ## Details Your code should take a positive integer representing the size of the board, via STDIN, ARGV, or function argument. Output the checkerboard pattern to STDOUT (you may alternately return it as a string if your submission is a function). Output must either * have no trailing spaces at all, or * have exactly enough trailing spaces to fill out the pattern to a perfect rectangle of width 6 \* *N* + 1. Output may optionally have a trailing newline. No other extra (leading, trailing) whitespace is permitted. ## Examples Size 1: ``` G B . . Y . . . P . . O R ``` Size 2: ``` G G G B B . . . Y Y B . . . . Y . . . . . P . . . . O P P . . . O O R R R ``` Size 4: ``` G G G G G G G G G G B B B B . . . . . Y Y Y Y B B B . . . . . . Y Y Y B B . . . . . . . Y Y B . . . . . . . . Y . . . . . . . . . P . . . . . . . . O P P . . . . . . . O O P P P . . . . . . O O O P P P P . . . . . O O O O R R R R R R R R R R ``` ## Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"): the shortest code in bytes wins. [Answer] ## Python 2, 152 ``` n=input();x=N=2*n while~N<x:s='';y=n*3;exec"a=x+y;q=[0,a>N,x-y>N,-x>n,-a>N,y-x>N,x>n,1];s+=' BYROPG.'[q.index(sum(q)<~a%2*3)];y-=1;"*(y-~y);print s;x-=1 ``` This is, in retrospect, the wrong approach for Python, but I'm posting it here in case someone can make use of it. Rather than explaining this mess of code, I'll try to say the idea behind it. The idea is to use [triangular coordinates](https://stackoverflow.com/questions/2049196/generating-triangular-hexagonal-coordinates-xyz), in which the triangular lattice corresponds to integer triples `(a,b,c)` with `a+b+c=0`. ![enter image description here](https://i.stack.imgur.com/G0cgW.gif) (Here, the lattice points are drawn as hexagons.) We can convert Cartesian coordinates to triangular ones as ``` a = (x+y)/2 b = (x-y)/2 c = -x ``` noting that `x` and `y` must have the same parity, or otherwise it's off-checkerboard and we should print a space. In triangular coordinates, the bounding lines of the six-sided star have equations: `a==n, b==n, c==n, a==-n, b==-n, c==-n`. So, we can determine what region we're in by which of `[a,b,c,-a,-b,-c]` are greater than `n`. * If none are, we're in the center and print a dot. * If exactly one is, we're in one of the six outer triangles, and print the letter corresponding to the index. * If two or more are, we're outside the board, and print a space. The bounding rectangle requires that we do this for `x` in the closed interval [-2\*n,2\*n] and `y` in the closed interval [-3\*n,3\*n]. [Answer] # Python 2, 140 bytes ``` n=input() for k in range(4*n+1):x=abs(k-2*n);y=2*n-x;p,q,r=" BP G..R YO "[(k-~k)/(n-~n)::4];print(" "*y+" ".join(p*x+q*-~y+r*x)+" "*y)[n:-n] ``` Not great, but here's my initial bid. The whitespace rules added a lot of bytes. For comparison, here's a 120 byte Python 3 program which is only correct visually, and doesn't follow the whitespace rules: ``` def f(n): for k in range(4*n+1):x=abs(k-2*n);y=2*n-x;p,q,r=" BP G..R YO "[(k-~k)//(n-~n)::4];print(" "*y,*p*x+q*-~y+r*x) ``` And here's my slightly longer recursive 149 byte Python 3 attempt: ``` def f(n,k=0):x=2*n-k;s=" ".join(["B"*x+"."*-~k+"Y"*x,"G"*-~k][k<n]).center(6*n+1);print(s);k<n*2and[f(n,k+1),print(s.translate({71:82,66:80,89:79}))] ``` [Answer] # [Retina](https://github.com/mbuettner/retina), 234 bytes ``` . P .+ iP$0$0x$0j$0x$0Px$0kqw P(?=P*xP*j) s P(?=P*j) R P(?=P*xP*k) c P(?=P*k) O x +`i(s+R+)R is$1#$1R +`(s*)P(P*c*)(O*)O(?=k) $0#s$1$2c$3 j|k # s +`([^#]+#)q(.*) q$1$2$1 R(?=.*w) G P(?=.*w) B O(?=.*w) Y w[^#]*#|q|i \w $0 c . # # ``` Takes input in unary. Each line should go to its own file and `#` should be changed to newline in the file. This is impractical but you can run the code as is as one file with the `-s` flag, keeping the `#` markers and maybe changing them to newlines in the output for readability if you wish. The code has minimal regex-complexity. The main steps in the generation are the followings: * Create the last `G` line and the first `B.Y` line (delimited by markers `ijk` and actual used letetrs are `RPO`). * Duplicate the topmost `G` line with a plus space, minus a G until there is only one G. * Duplicate the bottom `B.Y` line with a plus space and dot, minus a `B` and `Y` until there are no `B` and `Y` left. * Copy all the lines in reverse order after the current string (with the help of the marker `q`). We keep a marker (`w`) in the middle. * We change the letters `RPO` to `GBY` if they are before the marker. * Add the missing in-between spaces. The results after each of the above points (delimited by `=`'s) for the input `1111 (unary 4)`: ``` 1111 ============================== isssssssssRRRRjPPPPcccccOOOOkqw ============================== issssssssssssR sssssssssssRR ssssssssssRRR sssssssssRRRRjPPPPcccccOOOOkqw ============================== issssssssssssR sssssssssssRR ssssssssssRRR sssssssssRRRRjPPPPcccccOOOO sPPPccccccOOO ssPPcccccccOO sssPccccccccO ssssccccccccckqw ============================== qi R RR RRR RRRR PPPPcccccOOOO PPPccccccOOO PPcccccccOO PccccccccO ccccccccc w ccccccccc PccccccccO PPcccccccOO PPPccccccOOO PPPPcccccOOOO RRRR RRR RR i R ============================== qi G GG GGG GGGG BBBBcccccYYYY BBBccccccYYY BBcccccccYY BccccccccY ccccccccc w ccccccccc PccccccccO PPcccccccOO PPPccccccOOO PPPPcccccOOOO RRRR RRR RR i R ============================== G G G G G G G G G G B B B B . . . . . Y Y Y Y B B B . . . . . . Y Y Y B B . . . . . . . Y Y B . . . . . . . . Y . . . . . . . . . P . . . . . . . . O P P . . . . . . . O O P P P . . . . . . O O O P P P P . . . . . O O O O R R R R R R R R R R ``` [Answer] # JavaScript (*ES6*) 228 Construction line by line. Incredibly long compared to @Sp3000 that does the same. Using template string to save 3 more bytes for newlines. All newlines are significant and counted. ``` f=w=>(i=>{r=(n,s=b=' ')=>s.repeat(n),l=c=>(c='GBYPOR'[c])+r(i,b+c),t=n=>r(w*3-i)+l(n)+` `,s=n=>r(w-1-i)+l(n)+b+r(w+w-i,'. ')+l(n+1)+` `;for(o='',q=r(w)+r(w+w,'. ')+`. `;++i<w;o+=t(0))q+=s(3);for(;i--;o+=s(1))q+=t(5)})(-1)||o+q // LESS GOLFED u=w=>{ r =(n,s=b=' ') => s.repeat(n), l = c => (c='GBYPOR'[c])+r(i, b+c), t = n => r(w*3-i) + l(n) + '\n', s = n => r(w-1-i) + l(n) + b + r(w+w-i,'. ') + l(n+1) + '\n', o = '', q = r(w) + r(w+w,'. ') + '.\n'; for(i=0; i<w; i++) o += t(0), q += s(3); for(;i--;) o += s(1), q += t(5); return o+q } go=()=> O.innerHTML=f(I.value|0) go() ``` ``` <input id=I value=5><button onclick='go()'>-></button><br> <pre id=O></pre> ``` [Answer] # Ruby, ~~141~~ 127 Returns a rectangular string ``` ->n{(-2*n..2*n).map{|i|j=i.abs k=j>n ?0:j (([i>0??P:?B]*k+[j>n ?i>0??R:?G:?.]*(2*n+1-j)+[i>0??O:?Y]*k)*" ").center(6*n+1)}*$/} ``` **Ungolfed in test program** ``` f=->n{ (-2*n..2*n).map{|i| #Iterate rows from -2*n to 2*n j=i.abs #Absolute value of i k=j>n ?0:j #Value of j up to n: for PBYO ( #An array of characters forming one line ([i>0??P:?B]*k+ #B or P * (k=j or 0 as appropriate) [j>n ?i>0??R:?G:?.]*(2*n+1-j)+ #R,G or . * (2*n+1-j) to form centre diamond [i>0??O:?Y]*k #O or Y * (k=j or 0 as appropriate) )*" " #Concatenate the array of characters into a string separated by spaces. ).center(6*n+1) #pad the string to the full width of the image, adding spaces as necessary. }*$/ #Concatenate the array of lines into a string separated by newlines. } puts f[gets.to_i] ``` ]
[Question] [ *Note: This challenge was inspired by [Joe Z's](https://codegolf.stackexchange.com/users/7110/joe-z) many excellent questions surrounding NAND golfing.* ## Description Your goal in this challenge, should you choose to accept it, is to implement a very simple ALU using just NAND gates. The ALU can only perform the the following four operations: 1. 00, meaning increment (wrapping at 15). 2. 01, meaning decrement (wrapping at 0). 3. 10, meaning logical left shift. 4. 11, meaning return zero. Your circuit should take six inputs and give four outputs. Inputs I0 and I1 denote the operation. Inputs I2 through I5 denote the value to be operated on. Outputs O0 through O3 denote the output value. ## Scoring Your score is the number of gates you utilize to create this circuit. Lower is better. ## Test cases | I0-I1 | I2-I5 | O0-O3 | | --- | --- | --- | | 00 | 0001 | 0010 | | 01 | 0000 | 1111 | | 10 | 0100 | 1000 | | 10 | 0011 | 0110 | | 11 | 1100 | 0000 | [Answer] # ~~71~~ ~~64~~ 49 gates First define a few additional boolean operations in terms of *NAND*: ``` NOT(x) := NAND(x,x) # 1 NAND AND(a,b) := NOT(NAND(a,b)) # 2 NANDs XOR(a,b) := NAND(NAND(t=NAND(a,b),a),NAND(t,b)) # 4 NANDs # AND(XOR(a,b), XOR(c,b)) in 7 NANDs: XAX(a,b,c) := NOT(NAND(NAND(NAND(NOT(a), b), NAND(c, a)), NAND(c, b))) ``` Then we can define the ALU with these operations: ``` ni0 = NOT(i0) ni1 = NOT(i1) double = AND(i0,ni1) o3 = AND(ni0,NOT(i5)) o2 = NAND(NAND(double,i5), NAND(ni0,XOR(XAX(o3,i5,i1),i4))) o1 = NAND(NAND(double,i4), NAND(ni0,XOR(XAX(o2,i4,i1),i3))) o0 = NAND(NAND(double,i3), NAND(ni0,XOR(XAX(o1,i3,i1),i2))) ``` [Try it online!](https://tio.run/##hVRda9swFH33r7gwgqyghjjJOgjNoLDHkcLYQ8GYoNhKK3AkI8tZP397dq@sJmmXspdYOvec@600j/7emulF89g87stati381F45Wc8TgEptYLXSRvvVKm1VvRFg5FZxsgEQMKI7LAIcBWon6056FQV4a6PAKd85E5D8IC6SpI@7vF7@@CRorTZegNN39/40NsEYmz5HMLAQDd//piSRefA1OvACIxDWb4Tg7xwjVpVdyOE6SSjc8uZ3@hACRBuVlj6IB97b6SbF@h0DJcsehzWPvJtf/9CIQlzJRdAcuLcnZCp/@Rbko5h@vEB9PB09XN@SQJRn8zr5ieHXlAIBpQDJTy7oEV1q03S@xUzyItlYBxq0ASfNnUovQ4S4OUwPKjbQCNS2xKamPA9rgaa4iWnYOST0LkeyaZSpenRv9JiGsAiZ6jFPjM5OgIwnle3WNUWi9PRYGALtFHoWgehDBPZXTNxOouVYce9BoDkWSQJqOLXMTtEg0KfQMyrcZp/qZ2f1EzT0@mnQjz/VT8/qMzT0@gnq91@gdAo3FLxEUT/aSpXvF7Lttunu6kpDmIzY0WyU6bbYbtxtp3bKtapCDSXU@bdJbph91q8MPsxzxoukcdr4lAEbfhMw7CeVT@aFYC/AxDA64ZHHcT1a79DnczoWYz5n2pRM4DnDM6aL5yzgfe3hSqYn5Sx7TfS2sc4D7Ye3tm7Dhjn7h3I6gKPG2aorfZqj20I41WBfFrUyaZ8eDx3BzHZUG73s1PLjC680Sp90E9kC3WM7Qu2W4sSSCvQRix9ctrjJVFiO5Hw@KQrsBR2pEcBeGF4pHp7hBQaTCi6@04fBAFIaUuTinOlGVHpYrWoWDICFN7ABWdcHYv8vFpu6/ws "Python 3 (PyPy) – Try It Online") This uses 9 NANDs, 3 NOTs, 2 ANDs, 3 XORs and 3 XAXs for a total of 49 NAND gates. There is one gate that could be saved by removing some of the abstraction (we could get `NOT(o3)` for free and use that in the first *XAX*), but until I find some larger improvement I'd like to keep it simple. The logic for the three higher bits might seem a bit intimidating, but with some transformations it is actually not bad: `NAND(NAND(...), NAND(...))` is equivalent to `OR(AND(...), AND(...))`. The left *AND* reads "operation is *double* and the bit to right in the input is set", and the right one flips the bit if *XAX(new value of bit to the right, old value of bit to the right, decrement)* evaluates to 1. And `XAX(a,b,c)` is equivalent to `a>b if c else a<b`. [Answer] # 42 gates ``` a, b, c, d, e, f = I na = NOT(a) nb = NOT(b) nc = NOT(c) nd = NOT(d) ne = NOT(e) nf = NOT(f) xa = NAND(NAND(a, ne), NAND(na, e)) xb = NAND(NAND(b, ne), NAND(nb, e)) xc = NAND(NAND(c, ne), NAND(nc, e)) o0 = NOT(NAND(na, nf)) M = NOT(NAND(ne, f)) nxa = NOT(xa) o1 = NAND(NAND(M, a), NAND(nf, XOR(xa, b, nxa, nb))) nxaxb = NAND(xa,xb) xaxb = NOT(nxaxb) o2 = NAND(NAND(M, b), NAND(nf, XOR(xaxb, c, nxaxb, nc))) nxaxbxc = NAND(xaxb, xc) xaxbxc = NOT(nxaxbxc) o3 = NAND(NAND(M, c), NAND(nf, XOR(xaxbxc, d, nxaxbxc, nd))) ``` [Try it online!](https://tio.run/##fVRLa9tAEL7rVyyUNhJVw74fhgQKveSQCEoPheAUPRuXeGVkl6qX/vV09mVbSamM7J2Zb@abmZ3x7vfhcbTsuesHdPfx7lNel6gpVhmCZ@oPPyeLiOZcKs6xYgobIYgk4iGv3zVFlnm36kteL11SpDpCvlaffeASWfixieBNxO9RjR5QE3W/HvupByC6Qn/qqKttB25O07ziSWQQtgwaz1MA9w143EvCtSFcGkKZFERRLMoMMakN41oTrjgxBDPKQEuwFgRTYahQhAgM9YJWEaUUJZwaLrSRXkedJ5aaaKy11zizkYoasc4qR0woNUpTw5SR2ChKtcYuGlNaCWYog0cTyajTUqIgB8@vNVdUM@ry4UwaJihhlFNIQuJ16Oihbp76/KZEVeylK/XmfrX6QNZedhlUZ/KTyygch3FC39DGoqm23/tc8hjCwy7r3a63XX5xcflj3Nh8f5jyzVtaeK@N8wIWui7Qe3QBH/j@D5CuIvDq@hV2TNjRYSu4rpSDv7XN9TU5C7U@Wn1rx2QNzqe69k5@CnWfqtpNG3vI9zARftC3NeQQiw5j2ZaoK1FfosG1MfMWP4FhuIPcRLmJchvlNspdlLso91HuozxEeSgCwewJFiPcpxF2e9LHnszNAtcscM0Zrl3g2gWuDTgPHHHM5Ehlh2S7XZhcR5LFzqkhc50CkQXjrdv4RDiUfu3nuPdz2NCzYKeywDbHpiY1sHhIIqIviZrXRHO4SBtOtl2SnboT7HN7Ypzbc05nCazsJWv7L9Y5TI9NZ9sdmeP/1P2IS2gWvBRetn6uthA5jGEWhhPGGhZ2C36n1d4Wz38B "Python 3 – Try It Online") 11 NOT's, 22 NAND's, 3 XOR's (`XOR(a,b)` is defined as `NAND(NAND(NOT(a), b),NAND(a, NOT(b)))` except we pass in `NOT(a)` and `NOT(b)`). [Answer] # 88 NAND Gates This is just the first thing i could think of, given the challenge specification... some obvious things might become apparent later. Here shown decrementing 6. [![Curcuit](https://i.stack.imgur.com/sIM6i.png)](https://i.stack.imgur.com/sIM6i.png) [Answer] # ~~46~~ 44 gates ``` input a[4] input c[2] tmp s[4] = a + {1,c[0],c[0],c[0]} // 1+9+9+8=27 tmp !c[1] // 1 tmp t[4] = {0,c[0]<s[0],c[0]<s[1],c[0]<s[2]} // 3+2 out {s[0]&!c[1],c[1]?t[1]:s[1],c[1]?t[2]:s[2],c[1]?t[3]:s[3]} // 11 ``` Maybe we need a checker s[0]: t+1 = t(!t), costing 1 `c[0]>=s[0]` is found when making `s` out: a?b:c = (a nand b) nand (!a nand c) You can try it by running [this code](https://tio.run/##7Zlvb9s2EMbf71MEeuOt8NQ7Hv@66IssSYcAhjcs7VAg8Asv1jJvjmTYSpoiyGfPaIlyk5aypVFeByxAEDnI3aPjQ1r8Uffn5GayuljOFvn3N/rh5YuH29d3vdEknf44uUoGR9erPLs6yq4WWZqk@YB6g95d9FfyMRpEFPWj1AbZj4fT6Xv71yxdXOeraHB@Fy1maflhPvktmdsQ@@8Ps2n@RzTA@/F9v4OIcT/KrvP6Ox7tFnzzD@45nU0ul5OraHAXpdk0KaPzj4u1D6PD0bFNuI0GTJp@ZF0i4rFQkpEGMkpr4tamqQ2FaH07Tx4UeSh1TJIhoDRaAxrh8rAmD6jIYxJjEqAVlyTBsCqN@dOIyzJNFGVKwRlJQsmVy6OaPM2LPAk8BmGkYkzROtWl8Zo0U7rCEWLDkRDsj9KiqlLUpBEWaQIgFsCYvRMHZIhVldKfx3WVp2MNilCBtcXevJoE5c/TqjRFmRiM4UyD5ExgNTj9OOt09GuZJKQoZ86YuBqPidYr5iJL0@Qin2Vuaa2y6@VFUi2g03Vg8c2JNqHZ8rSatCifLC@T/Ek0fBFpV9O6Jo@y8MU2VMVaVdZYFVvUSgGq9bW285a1qBca18ta1NtclfayDijY2zpl3qJevzI2Vq6vWTauV7SoVwWoduWvbFEvD1DFDlTV3taC2ku92h@5yGapAxC7ByAYty1CiRNBX2/dYiDNl59pYbxurFqSWAtpDJWu98KEStu9wU7ffa9fD8LsEQizTyDMOLeodsCaw7BsQLJfhm@D0LOfh6dvUToEErpckQJ94ElllBIlBnLyYuaGcQwwFwexlyydnkRwnMd9HPn@p1@q6kpqtTS30ePeSHJ0RY/oSnhrRBAlvlmW3YQ@AcQN51n8FBWP@ojw7GR4cvTWAbbgDu@UDwMfh5Iyn4WaulDBygIKfC@NB/@oyDlvgXszR@gdlZTllKPWVeCTOfrh3eh4eFItEIJy6tUmmMKgFTqAVg@KYgd86ZHlHQCmR1Y0lmVdyLL9eEthstQBYGIAtraylnXArBRAwtjFhIm9AKDYT7EybHWJDsBSBuBqKw@CqJJxt0uRqaVKanzAbUOVIoBVWRf@mGb@OHrhWOsPNvbHtPCHGh9KzH78QWhnEKs1qPkBAiHo@Y3NZbuxqA0hYPP9BttsuixEFjs4nyF5t7zgE5RPl@rthSBhXi/MgoRFvTB1cQT@7DA5TG6S@Wrw5t1weHh8XJwkt7QSSLl39BJiVMiIaSXX1x2tBNKulQAmNoQCpObFVW1vJRBzeVrFEiUnTWJ95dtbCZyqAxKLAUkaLcledzQSpOuTCGmztAF7EjPCXsX2RoLUpSfERYxuWMXwdnQSJKsOsBjrykd73dFIUNylcWulFEoQt89UsZ6YbX2EotFQWAKfzoxf@2z13BBo5@1zQyC8IYB7awiw54bAFn//Xw0B9vUbAv/qO///@tv58bY36CuLPefFY5Cice/@1e/Z8tvZwSw9uP1unl1M5mdWaXKZnM/Gr2/tr1ffPLx4@fA3) in console of nandgame.com and refresh [Answer] # ~~59~~ ~~56~~ ~~53~~ ~~52~~ ~~51~~ 50 gates I thought I'd create an actual ALU here, even though it ended up taking more gates than @ovs' answer. Edit: A true ALU would actually use identical lanes for all four bits of the form `Result = Input + ((Input & Mask) ^ Flip) + Carry`. This would provide for eight different operations: ``` Mask Flip Carry Result 0 0 0 Input 0 0 1 Input + 1 0 1 0 Input - 1 0 1 1 Input 1 0 0 Input * 2 1 0 1 Input * 2 + 1 (c.f. Z80 SLL "instruction") 1 1 0 -1 1 1 1 0 ``` Each lane (except the last, as the carry out is not required) would use 15 gates, and then 5 gates are needed to generate the desired carry in for the four operations, making a total of 64 gates. However my first approach actually special-cased the first lane, so that I could choose between the input and `1` as the RHS of the full adder: ``` 00: IIII -> IIII + 0001 01: IIII -> IIII - 0001 10: IIII -> IIII + IIII 11: IIII -> IIII - IIII ``` To get the RHS takes 8 gates: ``` R2 = NAND(NOT(I2), I0) R3 = NOT(NAND(I3, I0)) R4 = NOT(NAND(I4, I0)) R5 = NOT(NAND(I5, I0)) ``` To select between `+` and `-`, I perform 2's complement on the value. 1's complement takes 16 gates: ``` S2 = XOR(R2, I1) S3 = XOR(R3, I1) S4 = XOR(R4, I1) S5 = XOR(R5, I1) ``` To achieve 2's complement we simply add `I1` as part of the `IIII + SSSS` operation: ``` C0, O0 = ADD(I2, S2, I1) C1, O1 = ADD(I3, S3, C0) C2, O2 = ADD(I4, S4, C1) C3, O3 = ADD(I5, S5, C2) ``` This takes 36 gates for a grand total of 60 gates, except we don't need `C3` which saves a gate. Notes: * `NOT` takes 1 gate: ``` NOT(X) = NAND(X, X) ``` * `XOR` takes 4 gates: ``` XOR(X, Y) = _XOR2(X, Y, NAND(X, Y)) _XOR2(X, Y, W) = NAND(NAND(X, W), NAND(Y, W)) ``` * `ADD` takes 9 gates: ``` ADD(X, Y, Z) = _ADD2(X, Y, Z, NAND(Y, Z)) _ADD2(X, Y, Z, W) = _ADD3(X, W, _XOR2(Y, Z, W)) _ADD3(X, W, V) = _ADD4(X, W, V, NAND(X, V)) _ADD4(X, W, V, U) = NAND(W, U), _XOR2(X, V, U) ``` Edit: The LSB's adder's inputs have a lot of redundancy: ``` S2 = XOR(R2, I1) C0, O0 = ADD(I2, S2, I1) ``` But this means that `XOR(S2, I1)` is just `R2`, so we can write this as: ``` C0 = NAND(NAND(S2, I1), NAND(I2, XOR(S2, I1))) = NAND(NAND(S2, I1), NAND(I2, R2)) O0 = XOR(I2, XOR(S2, I1)) = XOR(I2, R2) = _XOR2(I2, R2, NAND(I2, R2)) ``` This saves three gates. Edit: Even more redundancy that I overlooked: ``` C0 = NAND(NAND(S2, I1), NAND(I2, XOR(S2, I1))) = NAND(NAND(S2, I1), NAND(I2, R2)) = NAND(NAND(XOR(R2, I1), I1), NAND(I2, R2)) = NAND(NAND(NOT(R2), I1), NAND(I2, R2)) ``` Although this costs a gate, it makes `S2` unnecessary which saves four gates for an overall saving of three gates. Edit: Found another redundant gate: ``` C0 = NAND(NAND(S2, I1), NAND(I2, XOR(S2, I1))) = NAND(NAND(S2, I1), NAND(I2, R2)) = NAND(NAND(XOR(R2, I1), I1), NAND(I2, R2)) = NAND(NAND(NOT(R2), I1), NAND(I2, R2)) = NAND(NAND(NOT(R2), I1), NAND(I2, NAND(NOT(I2), I0))) = NAND(NAND(NOT(R2), I1), NOT(I2)) ``` Although this seems to just change a shared `NAND` to a shared `NOT`, I computed `NOT(I2)` as part of the calculation for `R2`, so that gate can be shared too, thus saving another gate. Edit: This applies to `O2` as well, then further allowing for a further saving of one gate: ``` O0 = XOR(I2, XOR(S2, I1)) = XOR(I2, R2) = _XOR2(I2, R2, NAND(I2, R2)) = _XOR2(I2, R2, NAND(I2, NAND(NOT(I2), I0))) = _XOR2(I2, R2, NOT(I2)) = NAND(NAND(I2, NOT(I2)), NAND(R2, NOT(I2))) = NOT(NAND(R2, NOT(I2))) ``` Edit: One final gate can be saved by eliminating `R2`. ``` C0 = NAND(NAND(NOT(R2), I1), NOT(I2)) = NAND(NAND(NOT(NAND(NOT(I2), I0)), I1), NOT(I2)) = NAND(NAND(AND(NOT(I2), I0), I1), NOT(I2)) = OR(AND(AND(NOT(I2), I0), I1), I2) = OR(AND(I0, I1), I2) = NAND(NAND(I0, I1), NOT(I2)) O0 = NOT(NAND(R2, NOT(I2))) = NOT(NAND(NAND(NOT(I2), I0), NOT(I2))) = NOT(NAND(OR(I2, NOT(I0)), NOT(I2))) = NOT(NAND(NOT(I0), NOT(I2))) ``` ]
[Question] [ # Guidelines ### Task Given two notes, inputted as strings or lists/arrays, calculate how many semitones apart they are (inclusive of the notes themselves), outputting as a number. **Explanation of a semitone:** A semitone is one step up or down the keyboard. An example is C to C#. As you can see below the note C is on a white note and C# is the black note just one above it. Semitones are the leaps from a black note to the next white note, up or down, except for: * B to C * C to B * E to F * F to E ## [keyboard](https://i.stack.imgur.com/j125w.jpg) ### Examples `'A, C' -> 4` `'G, G#' -> 2` `'F#, B' -> 6` `'Bb, Bb' -> 13` --- ### Rules * The largest distance between two notes is 13 semitones. * The second inputted note will always be above the first inputted note. * You can take input as either a string, or an array/list. If you take it as a string, the notes will be comma-separated (e.g. `String -> 'A, F'`, `Array -> ['A', 'F']`). * You can assume that you will always be given two valid notes. * Sharps will be denoted as `#` and flats will be denoted as `b` * Your code must support enharmonic equivalents (e.g. It must support both F# and Gb) * Your code does not need to support notes that are named with, but can be named without a sharp or flat (i.e. You do not need to support E#, or Cb). Bonus points if your code does support it though. * Your code does not need to support double sharps or double flats. * You can assume that if you get the both the same notes, or same pitch (e.g. 'Gb, Gb' or 'A#, Bb'), the second not will be exactly one octave above the first. * This is code golf so the answer with the least amount of bytes wins. [Answer] # [Python 2](https://docs.python.org/2/), 66 bytes ``` r=1 for s in input():r=cmp(s[1:]+s,s)-ord(s[0])*5/3-r print-r%12+2 ``` [Try it online!](https://tio.run/##K6gsycjPM/qfWpGarKSk9L/I1pArLb9IoVghMw@ICkpLNDStimyTcws0iqMNrWK1i3WKNXXzi1KAXINYTS1TfWPdIq6Cosy8Et0iVUMjbaP/QGO0TP6rO6rrqDurc6m7A2l3ZSDDTRnIcgIynJJAjCR1AA "Python 2 – Try It Online") --- **[Python 2](https://docs.python.org/2/), 68 bytes** ``` lambda s,t:13-(q(s)-q(t))%12 q=lambda s:ord(s[0])*5/3+cmp(s,s[1:]+s) ``` [Try it online!](https://tio.run/##Vc9LDoIwEIDhfU8xgRhaKVEgbkhY8D4EsgCRSCLl0W48PdIxRtn8mXwzm5le6jEKb@3C6/qsh6atQXIVuL5DZyqZM1PF2MH1yBx@18G4tFSW54odLyffvg0TlVyWblDZkq1iVHcJIZRW1FgcrAhj6sYIsU6CQU1RUwxChpDp5BjUArXAmFZFyLT0QtGOGpHBwUgMxn5UaCrMneWmxnhncYPWaPwoId24gHChF4CvBARQvH8BvN3O@LbgHd0G4bH1DQ "Python 2 – Try It Online") [Answer] # JavaScript (ES6), 78 bytes *Saved 1 byte thanks to @Neil* Takes the notes in currying syntax `(a)(b)`. ``` a=>b=>((g=n=>'0x'+'_46280ab_91735'[parseInt(n+3,36)*2%37%14])(b)-g(a)+23)%12+2 ``` ### Test cases ``` let f = a=>b=>((g=n=>'0x'+'_46280ab_91735'[parseInt(n+3,36)*2%37%14])(b)-g(a)+23)%12+2 console.log(f('A')('C')) // 4 console.log(f('G')('G#')) // 2 console.log(f('F#')('B')) // 6 console.log(f('Bb')('Bb')) // 13 ``` ### Hash function The purpose of the hash function is to convert a note into a pointer in a lookup table containing the semitone offsets (C = 0, C# = 1, ..., B = 11), stored in hexadecimal. We first append a **'3'** to the note and parse the resulting string in base-36, leading to an integer **N**. Because **'#'** is an invalid character, it is simply ignored, along with any character following it. Then we compute: ``` H(N) = ((N * 2) MOD 37) MOD 14 ``` Below is a summary of the results. ``` note | +'3' | parsed as | base 36->10 | *2 | %37 | %14 | offset ------+------+-----------+-------------+-------+-----+-----+-------- C | C3 | c3 | 435 | 870 | 19 | 5 | 0x0 C# | C#3 | c | 12 | 24 | 24 | 10 | 0x1 Db | Db3 | db3 | 17247 | 34494 | 10 | 10 | 0x1 D | D3 | d3 | 471 | 942 | 17 | 3 | 0x2 D# | D#3 | d | 13 | 26 | 26 | 12 | 0x3 Eb | Eb3 | eb3 | 18543 | 37086 | 12 | 12 | 0x3 E | E3 | e3 | 507 | 1014 | 15 | 1 | 0x4 F | F3 | f3 | 543 | 1086 | 13 | 13 | 0x5 F# | F#3 | f | 15 | 30 | 30 | 2 | 0x6 Gb | Gb3 | gb3 | 21135 | 42270 | 16 | 2 | 0x6 G | G3 | g3 | 579 | 1158 | 11 | 11 | 0x7 G# | G#3 | g | 16 | 32 | 32 | 4 | 0x8 Ab | Ab3 | ab3 | 13359 | 26718 | 4 | 4 | 0x8 A | A3 | a3 | 363 | 726 | 23 | 9 | 0x9 A# | A#3 | a | 10 | 20 | 20 | 6 | 0xa Bb | Bb3 | bb3 | 14655 | 29310 | 6 | 6 | 0xa B | B3 | b3 | 399 | 798 | 21 | 7 | 0xb ``` ### About flats and sharps Below is the proof that this hash function ensures that a note followed by a **'#'** gives the same result than the next note followed by a **'b'**. In this paragraph, we use the prefix **@** for base-36 quantities. For instance, **Db** will be converted to **@db3** and **C#** will be converted to **@c** (see the previous paragraph). We want to prove that: ``` H(@db3) = H(@c) ``` Or in the general case, with **Y = X + 1**: ``` H(@Yb3) = H(@X) ``` *@b3* is *399* in decimal. Therefore: ``` H(@Yb3) = @Yb3 * 2 % 37 % 14 = (@Y * 36 * 36 + 399) * 2 % 37 % 14 = ((@X + 1) * 36 * 36 + 399) * 2 % 37 % 14 = (@X * 1296 + 1695) * 2 % 37 % 14 ``` *1296* is congruent to *1* modulo *37*, so this can be simplified as: ``` (@X + 1695) * 2 % 37 % 14 = ((@X * 2 % 37 % 14) + (1695 * 2 % 37 % 14)) % 37 % 14 = ((@X * 2 % 37) + 23) % 37 % 14 = ((@X * 2 % 37) + 37 - 14) % 37 % 14 = @X * 2 % 37 % 14 = H(@X) ``` A special case is the transition from **G#** to **Ab**, as we'd expect **Hb** in order to comply with the above formulae. However, this one also works because: ``` @ab3 * 2 % 37 % 14 = @hb3 * 2 % 37 % 14 = 4 ``` [Answer] # Perl, ~~39~~ 32 bytes Includes `+1` for `p` Give the start and end notes as two lines on STDIN ``` (echo "A"; echo "C") | perl -pe '$\=(/#/-/b/-$\+5/3*ord)%12+$.}{'; echo ``` Just the code: ``` $\=(/#/-/b/-$\+5/3*ord)%12+$.}{ ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 27 bytes ``` ®¬x!b"C#D EF G A"ÃrnJ uC +2 ``` [Test it online!](https://ethproductions.github.io/japt/?v=1.4.5&code=rqx4IWIiQyNEIEVGIEcgQSLDcm5KIHVDICsy&input=WydGIycsICdCJ10=) Takes input as an array of two strings. Also works for any amount of sharps or flats on any base note! ### Explanation ``` ®¬x!b"C#D EF G A"ÃrnJ uC +2 Let's call the two semitones X and Y. ® à Map X and Y by ¬ splitting each into characters, x then taking the sum of !b"C#D EF G A" the 0-based index in this string of each char. C -> 0, D -> 2, E -> 4, F -> 5, G -> 7, A -> 9. # -> 1, adding 1 for each sharp in the note. b -> -1, subtracting 1 for each flat in the note. B also -> -1, which happens to be equivalent to 11 mod 12. The sum will be -2 for Bb, 2 for D, 6 for F#, etc. Now we have a list of the positions of the X and Y. rnJ Reduce this list with reversed subtraction, starting at -1. This gets the difference Y - (X - (-1)), or (Y - X) - 1. uC Find the result modulo 12. This is 0 if the notes are 1 semitone apart, 11 if they're a full octave apart. +2 Add 2 to the result. ``` [Answer] # [Perl 5](https://www.perl.org/) + `-p`, 66 bytes ``` s/,/)+0x/;y/B-G/013568/;s/#/+1/g;s/b/-1/g;$_=eval"(-(0x$_-1)%12+2" ``` [Try it online!](https://tio.run/##K0gtyjH9/79YX0dfU9ugQt@6Ut9J113fwNDY1MxC37pYX1lf21A/HchI0tcFMVTibVPLEnOUNHQ1DCpU4nUNNVUNjbSNlP7/d9Rx5nLXcVfmclPWceJyStJxSvqXX1CSmZ9X/F@3IAcA "Perl 5 - Try It Online") Takes comma-separated values. Does also work for Cb, B#, E#, Fb and multiple #/b. Explanation: ``` # input example: 'G,G#' s/,/)+0x/; # replace separator with )+0x (0x for hex) => 'G)+0xG#' y/B-G/013568/; # replace keys with numbers (A stays hex 10) => '8)+0x8#' s/#/+1/g; s/b/-1/g; # replace accidentals with +1/-1 => '8)+0x8+1' $_ = eval # evaluate => 2 "(-(0x$_-1)%12+2" # add some math => '(-(0x8)+0x8+1-1)%12+2' ``` Explanation for eval: ``` ( - (0x8) # subtract the first key => -8 + 0x8 + 1 # add the second key => 1 - 1 # subtract 1 => 0 ) % 12 # mod 12 => 0 + 2 # add 2 => 2 # I can't use % 12 + 1 because 12 (octave) % 12 + 1 = 1, which is not allowed ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 56 bytes ``` ->a{a.map!{|s|s.ord*5/3-s[-1].ord/32} 13-(a[0]-a[1])%12} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y6xOlEvN7FAsbqmuKZYL78oRctU31i3OFrXMBbE0zc2qrU2NNbVSIw2iNVNjDaM1VQ1NKr9X6CQFq1aXu2o4K5cG/sfAA "Ruby – Try It Online") The letters are parsed according to their ASCII code times `5/3` as follows (this gives the required number of semitones plus an offset of 108) ``` A B C D E F G 108 110 111 113 115 116 118 ``` The last character (`#`, `b` or the letter again) is parsed as its ASCII code divided by 32 as follows ``` # letter (natural) b 1 { --- 2 --- } 3 ``` This is subtracted from the letter code. Then the final result is returned as `13-(difference in semitones)%12` [Answer] # [Stax](https://github.com/tomtheisen/stax), 25 24 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ╝─°U┤ƒXz☺=≡eA╕δ┴╬\¿☺zt┼§ ``` [Run and debug it online](https://staxlang.xyz/#c=%E2%95%9D%E2%94%80%C2%B0U%E2%94%A4%C6%92Xz%E2%98%BA%3D%E2%89%A1eA%E2%95%95%CE%B4%E2%94%B4%E2%95%AC%5C%C2%BF%E2%98%BAzt%E2%94%BC%C2%A7&i=%5B%22A%22%2C+%22C%22%5D%0A%5B%22G%22%2C+%22G%23%22%5D%0A%5B%22F%23%22%2C+%22B%22%5D%0A%5B%22Bb%22%2C+%22Bb%22%5D%0A%5B%22Ab%22%2C+%22G%23%22%5D&a=1&m=2) The corresponding ascii representation of the same program is this. ``` {h9%H_H32/-c4>-c9>-mrE-v12%^^ ``` Effectively, it calculates the keyboard index of each note using a formula, then calculates the resulting interval. 1. Start from the base note, A = 2, B = 4, ... G = 14 2. Calculate the accidental offset `2 - code / 32` where `code` is the ascii code of the last character. 3. Add them together. 4. If the result is > 4, subtract 1 to remove B#. 5. If the result is > 7, subtract 1 to remove E#. 6. Modularly subtract the two resulting note indexes, and add 1. [Answer] ## Batch, ~~136~~ 135 bytes ``` @set/ac=0,d=2,e=4,f=5,g=7,a=9,r=24 @call:c %2 :c @set s=%1 @set s=%s:b=-1% @set/ar=%s:#=+1%-r @if not "%2"=="" cmd/cset/a13-r%%12 ``` Explanation: The substitutions in the `c` subroutine replace `#` in the note name with `+1` and `b` with `-1`. As this is case insensitive, `Bb` becomes `-1-1`. The variables for `C`...`A` (also case insensitive) are therefore chosen to be the appropriate number of semitones away from `B=-1`. The resulting string is then evaluated, and @xnor's trick of subtracting the result from the value gives the desired effect of subtracting the note values from each other. Edit: Finally I use @Arnauld's trick of subtracting the modulo from 13 to achieve the desired answer, saving 1 byte. [Answer] # [Python 3](https://docs.python.org/3/), 95 bytes ``` lambda a,b:(g(b)+~g(a))%12+2 g=lambda q:[0,2,3,5,7,8,10][ord(q[0])-65]+" #".find(q.ljust(2)[1]) ``` [Try it online!](https://tio.run/##VcnLCoJAFADQvV8hI8G9eBMdsUJwkUF@xDSLGWTMMF/Zok2/PmlE4Pac/jVduza2JrvYRt11qVxFOoUKNPrvChTiJuI@d6rs10MqQuIUU0J7OlAUStGNJQwilLjdJdJnrscCU7ezBc3t@ZiAo4gk2n6s2wkMsCMjl50YovOnYqHCW9nZWzBfWa6/pme0Hw "Python 3 – Try It Online") -14 bytes thanks to user71546 [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 28 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` O64_ṠH$2¦ḅ-AḤ’d5ḅ4µ€IḞṃ12FṪ‘ ``` A monadic link accepting a list of two lists of characters and returning an integer. **[Try it online!](https://tio.run/##AUYAuf9qZWxsef//TzY0X@G5oEgkMsKm4biFLUHhuKTigJlkNeG4hTTCteKCrEnhuJ7huYMxMkbhuarigJj///9bIkYjIiwiQiJd "Jelly – Try It Online")** or see [all possible cases](https://tio.run/##y0rNyan8/9/fzCT@4c4FHipGh5Y93NGq6/hwx5JHDTNTTIEck0NbHzWt8Xy4Y97Dnc2GRm4Pd6561DDj/8Mdmx7unG50dM/hdqC0ysNdfUDKG4gj//93VnBWVnBJUnBRcFFWcE1ScFVwU3BTVnBPUnBXcFdWcExScFRwVFZwSlJwAgA "Jelly – Try It Online"). ### How? Performs some bizarre arithmetic on the ordinals of the input characters to map the notes onto the integers zero to twelve and then performs a base-decompression as a proxy for modulo by twelve where zero is then replaced by 12 then adds one. ``` O64_ṠH$2¦ḅ-AḤ’d5ḅ4µ€IḞṃ12FṪ‘ - Main link, list of lists e.g. [['F','#'],['B']] ...or [['A','b'],['G','#']] µ€ - for €ach note list e.g. ['F','#'] ['B'] ['A','b'] ['G','#'] O - { cast to ordinal (vectorises) [70,35] [66] [65,98] [71,35] 64 - literal 64 _ - subtract (vectorises) [-6,29] [-2] [-1,-34] [-7,29] ¦ - sparse application... 2 - ...to indices: [2] (just index 2) $ - ...do: last two links as a monad: Ṡ - sign [-6,1] [-2] [-1,-1] [-7,1] H - halve [-6,-0.5] [-2] [-1,-0.5] [-7,0.5] ḅ- - convert from base -1 5.5 -2 0.5 7.5 A - absolute value 5.5 2 0.5 7.5 Ḥ - double 11.0 4 1.0 15.0 ’ - decrement 10.0 3 0.0 14.0 d5 - divmod by 5 [2.0,2.0] [0,3] [0.0,0.0] [2.0,4.0] ḅ4 - convert from base 4 10.0 3 0.0 12.0 - } --> [10.0,3] [0.0,12.0] I - incremental differences [-7.0] [12.0] Ḟ - floor (vectorises) [-7] [12] ṃ12 - base decompress using [1-12] [[5]] [[1,12]] F - flatten [5] [1,12] Ṫ - tail 5 12 ‘ - increment 6 13 ``` --- ### Also at 28 bytes... A (not so direct) port of [xnor's Python 2 answer](https://codegolf.stackexchange.com/a/156233/53748)... ``` O×5:3z60_Ṡ¥2¦60U1¦Fḅ-‘N%12+2 ``` [Try all possible cases](https://tio.run/##y0rNyan8/9//8HRTK@MqM4P4hzsXHFpqdGiZmUGo4aFlbg93tOo@apjhp2popG30/@GOTQ93Tjc6uudw@6OmNSoPd/UBKW8gjvz/31nBWVnBJUnBRcFFWcE1ScFVwU3BTVnBPUnBXcFdWcExScFRwVFZwSlJwQkA "Jelly – Try It Online") [Answer] # [CJam](http://cjam.readthedocs.io/en/latest/index.html), 67 bytes ``` l',/~)@)@{ciW*50+_z/}_@\~@@~-@@{ci65- 2*_9>-_3>-}_@\~@@~12+\- 12%+) ``` Online interpreter: <http://cjam.aditsu.net/> [Answer] # [Raku](https://raku.org/), 121 bytes I write quite a lot of music in EDOs other than 12 so I implemented an option to choose a particular EDO. ``` {1+(round($^c*log2(3))*([-](map {m:P5/([A-G])(\#*)(b*)/;4613502.comb[$0.ord-65]+7*($1.comb-$2.comb)},($^b,$^a)))%$c||$c)} ``` No TIO link because TIO has an outdated Rakudo, so here are some examples: ``` f("A", "C", 12) # => 4 f("Bb", "Bb", 12) # => 13 f("F#", "B", 19) # => 9 f("G", "G#", 31) # => 3 f("C", "Dbb", 31) # => 2 ``` ]
[Question] [ A collection of positive integers `d_1 d_2 ... d_k` is a *factorisation* of a positive integer `n` if ``` d_1 * d_2 * ... * d_k = n ``` Each positive integer has a unique *prime factorisation*, but in general they also have factorisations in which some of the terms are composite. E.g. ``` 12 = 6 * 2 = 4 * 3 = 3 * 2 * 2 ``` Write a program, function, verb, or similar which takes as input a single positive integer and returns or prints a complete list of its distinct factorisations. The factorisations may be produced in any order, and their terms may be in any order, but no two should be permutations of each other. Factorisations may not include `1` with two exceptions: for input `n` you may give the factorisation `n*1` instead of `n`; and for input `1` you may give the factorisation `1` instead of the empty list. You may assume that the input will be in the range of a signed 32-bit integer. If the output is as a string, there should be a clear distinction between the delimitation of numbers within a factorisation and the delimitation of the factorisations, but it is not necessary (for example) for the factors to be joined with an `*`. Your code should be capable of handling any valid input within 10 minutes on a reasonable desktop machine. ### Examples ``` 1 [[]] or [[1]] or [[1 1]] 7 [[7]] or [[7 1]] or [[1 7]] 12 [[12] [6 2] [4 3] [2 3 2]] or variants 16 [[2 2 2 2] [2 2 4] [2 8] [4 4] [16]] or variants 901800900 a list of 198091 factorisations 1338557220 a list of 246218 factorisations ``` [Answer] # Haskell, 56 bytes ``` _!1=[[]] i!n=[j:f|j<-[i..n],mod n j<1,f<-j!div n j] (2!) ``` `(2!)(1338557220::Int)` prints in five minutes on my laptop, when compiled with `ghc -O3`. # Haskell, 62 bytes, but much faster ``` i!n|i*i>n=[[n]]|0<1=[i:f|mod n i<1,f<-i!div n i]++(i+1)!n (2!) ``` `(2!)(1338557220::Int)` prints in a quarter of a second on my laptop, when compiled with `ghc -O3`. [Answer] # Pyth, 29 bytes ``` Msam+Ldgd/Hdf!%HT>S@H2tG]]Hg2 M def g(G, H): @H2 square root of H S 1-indexed range up to floor > tG all but first G − 1 elements f filter for elements T such that: %HT H mod T ! is false (0) m map for elements d: gd/Hd g(d, H/d) +Ld prepend d to each element a ]]H append [[H]] s concatenate g2Q print g(2, input) ``` [Try it online](https://pyth.herokuapp.com/?code=Msam%2BLdgd%2FHdf%21%25HT%3ES%40H2tG%5D%5DHg2&test_suite=1&test_suite_input=1%0A7%0A12%0A16) Runs in twenty seconds for `1338557220` on my laptop. [Answer] # [Python](https://docs.python.org/2/), ~~252~~ ~~313~~ ~~312~~ ~~311~~ ~~145~~ ~~141~~ ~~137~~ ~~135~~ ~~103~~ ~~84~~ 83 bytes This is largely based on [Anders Kaseorg's Pyth answer](https://codegolf.stackexchange.com/a/86862/47581). Any golfing suggestions welcome. [Try it online!](https://tio.run/nexus/python2#FcpLCoAgEADQq8wm0JR@FETkSQYXxpQYOYV0f8vlg5e9uVzcyAHraIYFka1VeCoke9wJCAJDcux3EXXgV3BdN5NUvQwHcEVrX9ZZlhfckiZp85P@@XseO5k/ "Python 2 – TIO Nexus") **Edit:** 19 bytes golfed thanks to Dennis. Fixed a typo in the code and added a TIO link. ``` g=lambda n,m=2:[[n]]+[j+[d]for d in range(m,int(n**.5)+1)if n%d<1for j in g(n/d,d)] ``` **Ungolfed:** ``` def g(n, m=2): a = [[n]] s = int(n**.5) + 1 for d in range(m, s): if n%d == 0: for j in g(n/d, d): a.append([d]+j) return a ``` [Answer] ## JavaScript (ES6), 83 bytes ``` f=(n,a=[],m=2,i=m)=>{for(;i*i<=n;i++)n%i<1&&f(n/i,[...a,i],i);console.log(...a,n)} ``` Only borrowed @AndersKaseorg's square root trick because it ended up saving me bytes overall. Prints `1` for an input of `1`, otherwise doesn't print `1`s. [Answer] # Ruby 1.9+, ~~87~~ ~~89~~ 87 bytes This answer is based on [Anders Kaseorg's Pyth answer](https://codegolf.stackexchange.com/a/86862/47581). This code only works for versions after Ruby 1.9, as stabby lambdas `->` were only introduced in 1.9. Any golfing suggestions are welcome. ``` g=->n,m=2{(m..Math.sqrt(n)).select{|i|n%i<1}.flat_map{|d|g[n/d,d].map{|j|[d]+j}}+[[n]]} ``` **Ungolfed:** ``` def g(n, m=2) a = [[n]] s = (m..Math.sqrt(n)) t = s.select{|i|n%i<1} t.each do |d| g[n/d,d].each do |j| a.push([d]+j) end end return a end ``` [Answer] # J, 52 bytes ``` [:~.q:<@/:~@(*//.)"$~#@q:_&(;@]<@(,~"{~0,#\@~.)"1)}: ``` Not as efficient as it could be since some factorizations may be repeated and a final pass has to be done after sorting each factorization and then de-duplicating. [Try it online!](https://tio.run/nexus/j#@5@mYGulEG1Vp1doZeOgb1XnoKGlr6@nqaRSp@xQaBWvpmHtEGvjoKFTp1RdZ6CjHONQB5Q01Ky14uJKTc7IV0hTMDT7/x8A) (But try to keep the input values small). On my desktop, the timings are ``` f =: [:~.q:<@/:~@(*//.)"$~#@q:_&(;@]<@(,~"{~0,#\@~.)"1)}: timex 'r =: f 1338557220' 3.14172 # r 246218 timex 'r =: f 901800900' 16.3849 # r 198091 ``` ## Explanation This method relies on generating all set partitions for the prime factors of the input integer *n*. The performance is best when *n* is square-free, otherwise duplicate factorizations will be created. ``` [:~.q:<@/:~@(*//.)"$~#@q:_&(;@]<@(,~"{~0,#\@~.)"1)}: Input: integer n }: Curtail, forms an empty array q: Prime factorization #@ Length, C = count prime factors _&( ) Repeat that many times on x = [] ( )"1 For each row ~. Unique #\@ Enumerate starting at 1 0, Prepend 0 ,~"{~ Append each of those to a copy of the row <@ Box it ;&] Set x as the raze of those boxes These are now the restricted growth strings of order C q: Prime factorization ( )"$~ For each RGS /. Partition it */ Get the product of each block /:~@ Sort it <@ Box it [:~. Deduplicate ``` ]
[Question] [ ``` ⢣⠃⢎⠆⣇⡇⡯⡂⠈⡏⢰⢵⢐⡭⢸⠪⡀⢸⢐⡭⠀⢹⠁⢎⠆⢸⣱⢸⡃⢎⠰⡱⢸⣱⢸⡃⠈⡏⢸⡃⡱⡁⢹⠁⢸⡀⡇⡗⢅⢸⡃⠈⡏⢸⢼⢸⢐⡭⠀ ⣇⢸⡃⢹⠁⢹⠁⣟⢸⢕⢐⡭⠀⡮⡆⡯⡂⣟⠀⡯⠰⡱⢸⣸⢸⢕⠀⣏⡆⢎⠆⢹⠁⣪⠅⢸⢼⢸⠰⣩⢸⢼⠀⡮⡆⡗⢼⢸⣱⠀⢎⠆⡯⠀⢇⠇⡮⡆⡯⡂⡇⡮⡆⣟⡆⣇⢸⡃⠸⡰⡸⢸⢸⣱⠈⡏⢸⢼⠀ ⢎⠆⡗⢼⢸⡃⢸⡃⡗⠔⡇⡯⠂⢹⠁⢣⠃⠸⡸⢸⡃⡯⡂⢹⠁⡇⢎⢰⢵⢸⡀⢸⡀⡇⡗⢼⢸⡃⢐⡭⢸⡃⡯⠂⡮⡆⡯⡂⡮⡆⢹⠁⣟⢐⡭⠀⢎⢸⢼⢰⢵⢸⢕⢰⢵⠰⡁⢹⠁⣟⢸⢕⢐⡭⠀ ⡮⡆⢐⡭⢸⠕⢰⢵⠰⡁⣟⠀⡇⣪⠅⢈⣝⢸⡃⡯⡂⢎⠆⠸⡰⡸⢸⢸⣱⠈⡏⢸⢼⠀ ⣪⠅⢎⠆⢸⠈⡏⠀⣇⠰⡱⠰⡱⢸⠪⡀⣪⠅⢸⡀⡇⡗⢅⢸⡃⠸⡰⡸⠰⡱⢸⢕⢸⣱⢐⡭⠀⡮⡆⡯⡂⣟⠀⣪⠅⣟⢸⠕⢰⢵⢸⢕⢰⢵⠈⡏⢸⡃⣏⡆⢸⣳⠘⡜⠀⢹⠁⢇⢆⠇⢎⠆⢸⡀⡇⡗⢼⢸⡃⣪⠅ ⡇⡗⢼⢸⠕⢸⣸⠈⡏⠀⡇⣪⠅⢰⢵⠀⣪⠅⢹⠁⡯⡂⡇⡗⢼⠰⣩⠀⢎⠰⡱⢸⠢⡇⢹⠁⡮⡆⡇⡗⢼⢸⢸⠢⡇⢎⡅⢸⠅⡮⡆⣇⡇⡱⡁⢸⣳⢸⢕⢰⢵⢸⢸⡀⣇⢸⡃⠰⡱⢸⠅ ⢎⠆⡗⢼⢸⡀⢣⠃⢸⡃⡗⢼⠰⣩⢸⡀⡇⣪⠅⡧⡇⢸⣸⢸⠕⢸⠕⢸⡃⡯⡂⢎⢰⢵⢐⡭⢸⡃⢸⡀⣟⠈⡏⠈⡏⢸⡃⡯⡂⣪⠅⢰⢵⢸⠢⡇⣏⡆⢐⡭⢸⠕⢰⢵⠰⡁⣟⢐⡭⠀ ⡮⡆⣟⡆⢎⢸⣱⢸⡃⡯⠰⣩⢸⢼⢸⢀⠇⡗⢅⢸⡀⡗⠔⡇⡗⢼⠰⡱⢸⠕⠰⣩⡆⡯⡂⣪⠅⢹⠁⣇⡇⢇⠇⢇⢆⠇⡱⡁⢣⠃⣩⡃ ⢎⠆⣇⡇⢹⠁⡯⠂⣇⡇⢹⠁⢸⠢⢺⢰⢵⠘⡜⠀⣟⡆⣟⠀⣇⡇⡯⠂⡯⠂⣟⢸⢕⠀⢎⠆⡯⡂⢸⡀⢎⠆⢇⢆⠇⣟⢸⢕⠰⡁⡮⡆⣪⠅⣟⠀ ⣪⠅⡧⡇⢎⠆⡯⡂⢹⠁⣟⢐⡭⠈⡏⠀⢇⢆⠇⡇⡗⢼⢐⡭⠀ ⡗⢼⠰⡱⠀⣇⠰⡱⠰⡱⢸⠕⢸⢼⠰⡱⢸⡀⣟⢐⡭⠀ ``` [ASCII version of the above](https://codegolf.stackexchange.com/questions/149119/#comment364435_149119) [`⡯⡂⣟⢸⡀⡮⡆⢹⠁⣟⢸⣱⠀`](https://codegolf.stackexchange.com/questions/140624/braille-graphics) # About Braille characters A Braille character packs a 4 by 2 rectangle of dots, which can be viewed as a Boolean matrix. The concatenation of all such matrices is a 4 by 2\*n boolean matrix, where n is the length of the input string. You should look for vertical lines without any dots in them, and use those as separators to split the big matrix into smaller matrices for each character. Then, look for patterns to convert them to letters of the English alphabet or spaces. Note that after removing the separators (vertical empty lines), a space is a 4 by 0 matrix. Below is a description of the alphabet in ASCII: ``` A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | X | Y | Z ----+-----+----+-----+----+----+-----+-----+---+----+------+----+-------+------+-----+-----+------+-----+-----+-----+-----+-----+-------+-----+-----+---- .#. | ##. | .# | ##. | ## | ## | .## | #.# | # | .# | #.#. | #. | #...# | #..# | .#. | ##. | .##. | ##. | .## | ### | #.# | #.# | #...# | #.# | #.# | ### #.# | ### | #. | #.# | ## | #. | #.. | #.# | # | .# | ##.. | #. | ##.## | ##.# | #.# | #.# | #..# | #.# | #.. | .#. | #.# | #.# | #.#.# | .#. | #.# | ..# ### | #.# | #. | #.# | #. | ## | #.# | ### | # | .# | #.#. | #. | #.#.# | #.## | #.# | ##. | #.## | ##. | .## | .#. | #.# | #.# | #.#.# | .#. | .#. | .#. #.# | ### | .# | ### | ## | #. | .## | #.# | # | #. | #..# | ## | #...# | #..# | .#. | #.. | .### | #.# | ##. | .#. | ### | .#. | .#.#. | #.# | .#. | ### ``` # Specification * The input is a sequence of Unicode code points in the range U+2800..U+28FF represented as the usual string type in your language (e.g. char array, char pointer) in any popular encoding supported (UTF-8, UCS-2, etc). * Trailing spaces in the output are fine. --- *EDIT:* apologies to those whose browsers misrender the dots, it's supposed to look like this (image): [![faux-braille](https://i.stack.imgur.com/MIv7C.png)](https://i.stack.imgur.com/MIv7C.png) [Answer] # [Python 3](https://docs.python.org/3/), ~~181~~ ~~179~~ ~~171~~ ~~167~~ ~~161~~ 159 bytes Input by UTF-16 little-endian bytes without BOM. First decompose into columns using bit shifts, split by empty column, then hash them into a lookup table. *-2 bytes thanks to [ngn](https://codegolf.stackexchange.com/users/24908/ngn). -5 bytes thanks to [Mr. Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder).* ``` lambda h,j=''.join:j(' ZAQV;JWP;MBOS;YRKCGXDF;ILHUENT'[int('0'+i,27)%544%135%32]for i in j(chr(64|i&7|i>>3&8)+chr(64|i>>3&7|i>>4&8)for i in h[::2]).split('@')) ``` [Try it online!](https://tio.run/##dVDLTsJAFN37Fd3AtAGJQAFTAvH9fr8VWSCPUIItQVyYsAAJ4EpdaFw6M11JosLCBBO@5v5InaHloYnJ5ObOmTnn3HMLN6WsrvnNTOTczCcuL1IJIevORRDy5HRVU3IiEs5md4/Ca8c74c257f3w6d76/PLJwlJ4dWPlcHHrAMVUrSSiKeRS3b6Q5AjIssPrDzj8vnhGLwqqoGpCTkxmi2JQLqvOUFmNRv3Oack1gPi1j8oMHVKyMUXxxSXPVSGvMvkZJElmocitMiICagCuAb0H3ACjCYSdTyC3gO@APABtA/0C@gjkHWgXcAtIhTcWgln/Dbhq0xludHgllmAbSOcXaGv2e/ZEqgN6l8ty6xeg9b@faW/oiDxpLamn0iK6LmUmvUEkxXxKXJImRnnIBxCW5JVXNsS4PQvGZjLexkQrgMddK7zHT4NReqMM@NnmMllrQUYLcN0OYC2ONrkaq7TRl7US9vfLibX/pjd/AA "Python 3 – Try It Online") [Answer] # JavaScript (ES6), ~~148 146 143~~ 142 bytes *Saved 1 byte thanks to @ngn* ``` s=>[...s].map(c=>g((k=c.charCodeAt()/8)&8|k*8&7)&g(k&7|k/2&8),o=x='',g=n=>x=n?x*27+n:!(o+=' DZQGYWXNHJ.CSTIO.AFB.LPVE..KUMR'[x%854%89%35]))&&o ``` [Try it online!](https://tio.run/##lVRbTxNBFH7nV1QStrsUlwQlVJPFIN7v9xvy0FSoWuwSSkwfeCgQWp7ABxt80DCz@2AkUSDGpBp/zfkjdWbOmUuhDTFpJtPZc/3Od763hfeFanHpzeLy6Ur8aq4zH3Wq0eRMGIbV2fBdYdEvRpMl3y9HxbD4urA0LWymlv1gNB94@ZXycN6bCLySX/YmVsqjY14@GImjWpTNjpSiSjRZiyoXasNjE7nK@VN@nIuymUsv7l99/vTZnWs3wumHj67fDaeuXAxv3XtyOQxvPr79IDtTG8qPnx3Knxs6Mz4bBJ4Xd4pxpRovzIULcckfyGTm/UFIUmDrkGwBa0DaBC5@@8DXgG0C34bkAJJfkHwA/h2SNrA94HV5wRcm7r@BrZK7eE8P5ckx4AHww65Hiqnu4hNf1e5tGVam3oFk46hx8tfNOBhkcpnsy0o2k6MORNWUE4OpM91VTi1bKf8BvEHNia/yZd@psU324j3dlpbUE0bbA7ZhaxFe6Tf6ayPv0FfRrgRGucsU4t4E1uwqgOu/ohLesC0wcYqSsBgM5cDQq3vKo5NLGBDfHWAfaZxsTWOjhi2TtLWZKge/CmMRjUbepknbwZj4mg3oLoJ3dabudgiGKFsaPx1fDkfd5RD6zu14x5TBcLI7DI22qWe2CemX7l4VYP8PNMXTTEdzyZYmschwCbfEcKYHtXVy4yIbxkXpT1cMiACZprtwdNaLOCxi/gT2CfhnZ1nFmBuSkKaX4zNWuXpA71ixFu2NQcKCjuUYDJBdhvgqAu4QLYpBLlEkRHsEwMloDbaAKyxFcFojVC7UFNW0Cwz68rqzZybjxskrVdciqRfLlG@ww0b5V1WdVhNECE@XfkdElVa2rsaMWLo6iQxwcDUw0Iz7L8JJO4Tig5tpRBpV0eibPOtKvgyB6464aDAIzRb5Wuo6DMAhoRgaEtLMFMDScb3fPMhbc0nIjvuCoCR/NASa8qSvu7SpRg8pwq5VfSPYckg4ddwPXak1VvgShHop@0sGscINf0Qd9QJZUAzr@0/QQb63CrW0mOkXpJgNORB0/gE "JavaScript (Node.js) – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), ~~305~~ ~~302~~ ~~301~~ ~~286~~ ~~251~~ ~~198~~ 182 bytes ``` def f(s,A=''): for c in s:l=bin(ord(c))[-8:];A+='7'+l[5:]+l[1]+'7'+l[2:5]+l[0] print(''.join('K.L.SXC PRU.NYEOGZVJIW..HFBTAQDM'[int('7'+c,22)%141%109%35]for c in A.split('70000'))) ``` [Try it online!](https://tio.run/##fVRbT1NBEH7nV5wXcnoCnlCQqDU81Lt4v19IXyw21pCWAC@@FQgtT@CDDT5ounvOg5FEgRiTavw180fq7M7s7B4Em2azZ3fm25lvvpnld2tv2q2Z0WjxdSNqlFYnq3NxnFTGokZ7JapHzVa0Wlmae9Vsldori6V6kiycOV@pXaxOzMXn4omlhdlKDddybYI@pyuz5nuqNhYtrzRba6U4Tt@20Tu@ld5OHz2/HN1/@CS9@@Lqvesvn87ffJamN65delx9cOVOvGDNEaU@OT2djJfPlsfLUxfGZ2ZrEko1XV1eahqrKfzFSZKMGqUYshzUJmQ7oLqQ90Dj/wD0Bqht0LuQHUL2E7L3oL9BNgS1D7pjNnSicP8L1Dq743l@ZFZNgIegjwqHjGn3eKXXnfvQwJqn9yDbOm6c/ZEX42TMxIxx8ivkbtd8YM36Pjb9HXSX08Fbc3IQRDVkezzPd40lZ0Fo@6C2/OvolX/lT4@8x7eYoKHCupsncN8D1SsEoN0nRqK7PgWFK4ZEwRCUT5zzZWT3nEmcONwD9YFLpjYcG7agBnbozGwAdIvGiMZlHXI1PfmC7ypO7gheyMXuPe0ihh3HmMM35bB7Q/vJleIcGVOUVnTk8vVcXbYh/1zMzlL0XzIRwemHQJxoycbIoMfyEJGQ4EUMJ6jUvSguJi/S/Ok6JEDiQTIt0BV0CosTMX@A@gj6U9B3WM2uUZrk8m8p7VuO5OBK9bkLJH1PL8UgiZNyRMYWgTqCZS90ZVZgZE9ZBy96gx3QlkAE56agyUMzwWYaskG@uhN0jby4dUqPdNxkc50iMQtLlJ3@YkNyA4FooTVU17FJyD3YsQUlAsPhRrUOyJTcuZqn69zJptAXNDSov2Sc0jSTuWTWjh07os9OMCIcA8xbn329MoNaUzloiInGuDqWVeO4WWCeXZxUcGKEJ5R@9tsl62TMw3DA3SejjBEGfkTLdDXloPqS5l143tgyybxxoxUanyseAh4bZa4jfO4i43BkBZSePD36bvK4ExIMg4z@Ag "Python 3 – Try It Online") ]
[Question] [ Bubble-wraps are maximum-level entertainment. Everyone can agree to that. Now, you will make even computers enjoy bubble-wraps. # Specs You will be given two integers, w, and h.(each are responsively width and height) Your program should output all w\*h phases waiting 1 second between each one and terminate. Every bubble-wrap starts with all cells full. For example, a 4\*6 bubble-wrap starts like: ``` O_O_ _O_O O_O_ _O_O O_O_ _O_O ``` And each phase, a random non-popped cell is popped.For example, ``` O_O_ _O_O O_X_ _O_O O_O_ _O_O ``` The program should terminate when all the cells are popped. aka. ``` X_X_ _X_X X_X_ _X_X X_X_ _X_X ``` # Examples ``` (4,6) (5,5) (6,2) (10,10) (7,9) ``` [Answer] # C (Windows), ~~260~~ 248 bytes ``` #import<windows.h> i,j,l,r;b(w,h){char*s=malloc(l=w*h+h);for(i=h;i--;*s++=10)for(j=w;j--;*s++=i%2^j%2?79:45);*(s-1)=0;s-=l;for(srand(time(0));j>system("cls")+puts(s)-2;j>-1?s[j]=88:0)for(Sleep(1000),r=rand(),j=-2,i=r+l*2;--i-r;j=s[i%l]==79?i%l:j);} ``` [![enter image description here](https://i.stack.imgur.com/8nWg1.gif)](https://i.stack.imgur.com/8nWg1.gif) [Answer] # [Python 3](https://docs.python.org/3/), ~~222~~ 220 bytes This is my first time answering, so please be gentle (and point out mistakes that I have made). ``` import time,random as t def f(c,r): p=print;a='0_'*c;d=((a[:c]+'\n'+a[1:c+1]+'\n')*r)[:-~c*r] for i in[1]*((r*c+r%2*c%2)//2): p(d);k=1 while d[k]!='0':k=t.randrange(len(d)) d=d[:k]+'X'+d[k+1:];time.sleep(1) p(d) ``` [Try it online!](https://tio.run/nexus/python3#JY/LqsMgEIb3eYo5i@KtN7M0@B4FK0XU9EgSI1Ohu756auhi4B/4@C9bWsqKFWpa4hFdDusC7gW1C3GEkeLRM9VB0QVTroPT5Pog3A9BU@qM8laQeybCGam8kL@PcWRGnT6eo@1gXBESpGyk5ZQi9wIPPfeHnl0u/e4NhQY2TFo2@f5Pc4RgJvvXkoiadD3vpdo9I51jbihrXNDBqKnF3YhotJDKDvuC82uOsVDZmN11274 "Python 3 – TIO Nexus") How it works: 1. Chain a lot of '0\_''s together 2. Chop into '0\_0\_...\n' and '\_0\_0...\n' parts and concatenate 3. Generate random indices until the char at the index is a '0' 4. Create new string with the char at the generated index is replaced with a 'X' (Damn you python for non-mutable strings!) 5. Repeat `r*c+r%2*c%2` times: There are `r*c` bubbles in the pattern, unless r and c are both odd, in which case there are `r*c+1`. [Answer] ## Mathematica (145 bytes) Anonymous function, takes height and width as input (in that order — if that's a problem, replace `{##}` with `{#2,#}` in the middle of the code for an extra 2 bytes). Code: ``` Monitor[Do[Pause@1,{i,NestList[RandomChoice@StringReplaceList[#,"O"->"X"]&,""<>Riffle["_"["O"][[Mod[#+#2,2]]]&~Array~{##}," "],Floor[##/2]]}],i]& ``` Explanation: * `""<>Riffle[Array["_"["O"][[Mod[#+#2,2]]]&,{##}],"\n"]` creates the initial, unpopped bubble-wrap, by making an array of "\_"s and "O"s and then StringJoining them between newlines. * `NestList[RandomChoice@StringReplaceList[#,"O"->"X"]&,..., Floor[##/2]]` repeatedly chooses one of the "O"s to replace with an "X", as many times as there are "O"s (which is Floor[width \* height / 2] — thanks to @JonathanAllan for the idea of putting "\_" instead of "O" in the top left corner, otherwise this would be `Ceiling` instead and thus 2 bytes more). * `Monitor[Do[Pause@1,{i,...}],i]` makes `i` take the values in the list we just calculated, for 1 second each, and dynamically prints `i`. Example output: [![GIF of Mathematica popping bubble-wrap](https://i.stack.imgur.com/icXHF.gif)](https://i.stack.imgur.com/icXHF.gif) [Answer] # [MATL](https://github.com/lmendo/MATL), 37 bytes ``` :!i:+o`T&Xxt3:q'_OX'XEcD2y1=ft&v1Zr(T ``` The upper-left corner is always an underscore (allowed by the challenge). The screen is cleared between phases. I could save a byte by not clearing the screen, but it looks better this way. The program exits with an error ([allowed by default](http://meta.codegolf.stackexchange.com/q/4780/36398)) after displaying all phases. Try it at [**MATL Online!**](https://matl.io/?code=%3A%21i%3A%2Bo%60T%26Xxt3%3Aq%27_OX%27XEcD2y1%3Dft%26v1Zr%28T&inputs=4%0A5&version=19.8.0) (If it doesn't work after a couple of seconds, please refresh the page and try again). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~30~~ 29 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` =”OTX +þ⁹++µị⁾_OYµṄœS1”XǦµÐL ``` [![Example run](https://i.stack.imgur.com/OLEPx.gif)](https://i.stack.imgur.com/OLEPx.gif) Calls the link as a dyad with the program arguments and then quits with a message (the code for which is `çṛ“\'=ṙMḋḌẓ(ėo»`) *Nuance:* the bottom-right "cell" will always be a bubble (rather than the top-left like the example in the question), this is to ensure that when all bubbles are popped the random choice returns 0 which will be the `"X"` at the end of the list - replacing that then makes no change to the value and breaks the loop. *Note:* does not clear the screen (was not specified, and I'm not sure how to do so). ### How? ``` =”OTX - Link 1, choose a random O index or 0: string e.g. "_O_\nX_O" ”O - "O" = - equals (vectorises over the string) e.g. [0,1,0,0,0,0,1] T - truthy indexes e.g. [2,7] X - random choice (if empty this returns 0) +þ⁹++µị⁾_OYµṄœS1”XǦµÐL - Main link: w, h e.g. 3, 2 - left argument (implicit), w e.g. 3 ⁹ - right argument, h e.g. 2 þ - outer product with + - addition e.g. [[2,3,4],[3,4,5]] - left argument (implicit), w e.g. 3 + - add e.g. [[5,6,7],[6,7,8]] - right argument (implicit), h e.g. 2 + - add e.g. [[7,8,9],[8,9,10]] µ - monadic chain separation ⁾_O - "_O" ị - index into (1-based & mod) e.g. [['_','O','_'],['O','_','O']] - note: the additions above assure the last entry is an 'O'. Y - join with line feeds e.g. ['_','O','_','\n','O','_','O'] µ µ - monadic chain separations ÐL - loop until the results are no longer unique: Ṅ - print with a trailing line feed and yield œS1 - sleep for 1 second and yield ¦ - apply to index Ç - given by calling the last link (1) as a monad - (a random O index or 0 if none exists) ”X - an "X" ( ... which will be an X already) ``` [Answer] # [Scala](https://www.scala-lang.org/), 764 bytes ``` object B{ def main(a: Array[String]):Unit={ val v=false val (m,l,k,r,n)=(()=>print("\033[H\033[2J\n"),a(0)toInt,a(1)toInt,scala.util.Random,print _) val e=Seq.fill(k, l)(v) m() (0 to (l*k)/2-(l*k+1)%2).foldLeft(e){(q,_)=> val a=q.zipWithIndex.map(r => r._1.zipWithIndex.filter(c=> if(((r._2 % 2) + c._2)%2==0)!c._1 else v)).zipWithIndex.filter(_._1.length > 0) val f=r.nextInt(a.length) val s=r.nextInt(a(f)._1.length) val i=(a(f)._2,a(f)._1(s)._2) Thread.sleep(1000) m() val b=q.updated(i._1, q(i._1).updated(i._2, !v)) b.zipWithIndex.map{r=> r._1.zipWithIndex.map(c=>if(c._1)n("X")else if(((r._2 % 2)+c._2)%2==0)n("O")else n("_")) n("\n") } b } } } ``` ### How it works The algorithm first fills a 2D Sequence with false values. It determines how many iterations (open boxes) exist based on the command line arguments put in. It creates a fold with this value as the upper bound. The integer value of the fold is only used implicitly as a way to count how many iterations the algorithm should run for. The filled sequence we created previously is the starting sequence for the fold. This is used in generating a new 2D sequence of false values with their cooresponding indecies. For example, ``` [[false, true], [true, false], [true, true]] ``` Will be turned into ``` [[(false, 0)], [(false, 1)]] ``` Note that all lists that are completely true (have a length of 0) are omitted from the result list. The algorithm then takes this list and picks a random list in the outermost list. The random list is chosen to be the random row we pick. From that random row, we again find a random number, a column index. Once we find these two random indices, we sleep the thread we are on for 1000 miliseconds. After we're done sleeping, we clear the screen and create a new board with a `true` value updated in the random indices we have created. To print this out properly, we use `map` and zip it with the index of the map so we have that in our context. We use the truth value of the sequence as to whether we should print an `X` or either an `O` or `_`. To chose the latter, we use the index value as our guide. ### Interesting things to note To figure out if it should print an `O` or an `_`, the conditional `((r._2 % 2) + c._2) % 2 == 0` is used. `r._2` refers to the current row index while `c._2` refers to the current column. If one is on an odd row, `r._2 % 2` will be 1, therefore offsetting `c._2` by one in the conditional. This ensures that on odd rows, columns are moved over by 1 as intended. Printing out the string `"\033[H\033[2J\n"`, according to some Stackoverflow answer I read, clears the screen. It's writing bytes to the terminal and doing some funky stuff I don't really understand. But I've found it to be the easiest way to go about it. It doesn't work on Intellij IDEA's console emulator, though. You'll have to run it using a regular terminal. Another equation one might find strange to see when first looking at this code is `(l * k) / 2 - (l * k + 1) % 2`. First, let's demystify the variable names. `l` refers to the first arguments passed into the program while `k` refers to the second one. To translate it, `(first * second) / 2 - (first * second + 1) % 2`. The goal of this equation is to come up with the exact amount of iterations needed to get a sequence of all X's. The first time I did this, I just did `(first * second) / 2` as that made sense. For every `n` elements in each sublist, there are `n / 2` bubbles we can pop. However, this breaks when dealing with inputs such as `(11 13)`. We need to compute the product of the two numbers, make it odd if it's even, and even if it's odd, and then take the mod of that by 2. This works because rows and columns that are odd are going to require one less iteration to get to the final result. `map` is used instead of a `forEach` because it has less characters. ### Things that can probably be improved One thing that really bugs me about this solution is the frequent use of `zipWithIndex`. It's taking up so many characters. I tried to make it so that I could define my own one character function that would just perform `zipWithIndex` with the value passed in. [But it turns out that Scala does not allow an anonymous function to have type parameters.](https://stackoverflow.com/questions/2554531/how-can-i-define-an-anonymous-generic-scala-function) There is probably another way to do what I'm doing without using `zipWithIndex` but I haven't thought too much about a clever way to do it. Currently, the code runs in two passes. The first generates a new board while the second pass prints it out. I think that if one were to combine these two passes into one pass, that would save a couple of bytes. This is the first code golf I've done so I'm sure there is a lot of room for improvement. [If you'd like to see the code before I optimized for bytes as much as possible, here it is.](https://gist.github.com/ColdSauce/332f89c84f06cceca20c4a473536457a) [Answer] ## JavaScript (ES6), ~~246~~ 229 bytes ``` document.write(`<pre id=o></pre>`) setInterval(_=>{(a=o.innerHTML.split(/(O)/))[1]?a[Math.random()*~-a.length|1]=`X`:0;o.innerHTML=a.join``},1e3) f=(w,h)=>o.innerHTML=[...Array(h)].map((_,i)=>`O_`.repeat(w+h).substr(i,w)).join` ` ``` ``` <div oninput=f(+w.value,+h.value)><input id=w type=number min=1><input id=h type=number min=1> ``` [Answer] # Python - 290 bytes I've never done one of these before - so any constructive criticism would be appreciated :) Main trick here is just annoyingly nested list comprehensions. I could save a few characters by not having a newline between the pops but that just looks ugly. ``` r=range q=print import random as n,time def f(H,W): def p(b): q("\n".join(["".join(["O"if(i,j)in b else"X"if(i,j)in X else"_"for j in r(H)])for i in r(W)]));time.sleep(1);q() b=[(i,h)for h in r(H)for i in r(h%2,W,2)];n.shuffle(b);X=[] while len(b)>0: p(b);X+=[b.pop()] p(b) ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~49~~ ~~46~~ 39 bytes (noncompeting) ``` UONNO_¶_OAKAαA№αOβHWψβ«A§α§⌕AαO‽βXA№αOβ ``` ## Verbose ``` Oblong(InputNumber(), InputNumber(), "O_\n_O") Assign(PeekAll(), a) Assign(Count(a, "O"), b) RefreshWhile (k, b) { AssignAtIndex(a, AtIndex(FindAll(a, "O"), Random(b)), "X") Assign(Count(a, "O"), b) } ``` [Answer] # [APL (Dyalog)](https://www.dyalog.com/), ~~61~~ 59 bytes ``` ⎕←m←'O_'[2|-/¨⍳⎕] (b/,m)[?+/b←'O'=,m]←'X' ⎕DL 1 →2/⍨'O'∊⎕←m ``` `⎕←` output `m←` *m*, where *m* is `'O_'[`…`]` these characters indexed by…  `2|` the division-remainder-when-divided-by-two of  `-/¨` the difference between each of  `⍳` all the coordinates (indices) in an array of shape  `⎕` numeric input (the number of rows and columns) `(`…`)[`…`]←'X'` assign the character X to one of the…  `b/` filtered-by-*b* (to be defined)  `,m` raveled elements of m, specifically…  `?` a random element (lit. number) in the range one to  `+/` the sum of  `b←` *b*, where *b* is  `'O'=` Boolean for where the letter equals  `,m` *m* raveled `⎕DL 1` **D**e**l**ay one second `→2` Go to line 2 `/⍨` if (lit. filtered by) `'O'∊` whether the letter is a member of `⎕←m` the outputted value, where the outputted value is *m* [Try it online!](https://tio.run/nexus/apl-dyalog#NY1BSwJREMfv71MMBL2i1U2LbhKhBYHhQYNCJN7qbC3te2/Z90yjvImJsRJBx05ePHTrG/RR3hexWbPDDDP/@f3/47JPONNxrAeRuoU4UghS3KOByAIKE2EKVkNf9TA1Vqge2DsE3bdJ33qQ75EymFoDAmwkkRiZgEiSVA@LgA@YPoLBrlY9D4yGAUJXKFJwnUOO/CuGIXYt23LZnLv5R/WacyNiyzm41zE8jVCJIMbmSb21EQhqnhYvqxc1zgM9BK2gEFbybipSDP@NhNXqUHKzBU1u8ka91Ry5bFE62HbZ1xoi7bxBt33OmJu@QLj6YyUVb9zwdvm54P8sXfZNeoftBL4nd9vHe36wBnjFk518uuJs8465yXvZd9mSrm4628StKHwVsiM4/AU "APL (Dyalog Unicode) – TIO Nexus") --- From version 16.0 it will be shorter: `{0::→⋄'X'@(⊂(?∘≢⊃⊢)⍸'O'=⍵⊣⎕DL 1)⊢⎕←⍵}⍣≡'O_'[2|-/¨⍳⎕]` [Answer] # Python 3, ~~195~~ 188 bytes ``` import time,random def f(w,h): a=bytearray(b'0-'*w*h);b=[*range(0,w*h,2)];random.shuffle(b); while 1:print(*(a.decode()[w*i:w*i+w]for i in range(h)),sep='\n');a[b.pop()]=88;time.sleep(1) ``` Using `bytearray` and `decode` seems to be shorter than slicing and reassembling a string a la `a[:i]+'X'+a[i+1:]`. ``` import time,random def f(w,h): x=[*range(1,h*w,2)];random.shuffle(x) while 1: for i in range(w*h): print('-X0'[(i%w%2!=i//w%2)+(i in x)],end='\n'[i%w<w-1:]) print();time.sleep(1);x.pop() ``` [Answer] # Java 7, 317 bytes ``` void c(int w,int h)throws Exception{String r="";int x=0,j=0,i;for(;j++<h;x^=1,r+="\n")for(i=0;i<w;r+=(i+++x)%2<1?"_":"O");for(System.out.println(r);r.contains("O");System.out.println(r=r.substring(0,x)+'X'+r.substring(x+1))){Thread.sleep(1000);for(x=0;r.charAt(x)!='O';x=new java.util.Random().nextInt(r.length()));}} ``` **Explanation:** ``` void c(int w, int h) throws Exception{ // Method with two integer parameters (throws Exception is required for the Thread.sleep) String r = ""; // String we build to print int x=0, j=0, i; // Some temp values and indexes we use for(; j++<h; // Loop over the height x^=1, // After every iteration change the flag `x` every iteration from 0 to 1, or vice-versa r += "\n") // And append the String with a new-line for(i=0; i<w; // Inner loop over the width r += (i++ + x)%2 < 1 ? "_" : "O") // Append the String with either '_' or 'O' based on the row and flag-integer ; // End inner width-loop (implicit / no body) // End height-loop (implicit / single-line body) for( // Loop System.out.println(r); // Start by printing the starting wrap r.contains("O"); // Continue loop as long as the String contains an 'O' System.out.println(r= // Print the changed String after every iteration r.substring(0,x)+'X'+r.substring(x+1))){ // After we've replaced a random 'O' with 'X' Thread.sleep(1000); // Wait 1 second for(x=0; r.charAt(x) != 'O'; // Loop until we've found a random index containing still containing an 'O' x = new java.util.Random().nextInt(r.length())) // Select a random index in the String ; // End loop that determines random index containing 'O' (implicit / no body) } // End loop } // End method ``` **Test gif (4,6)** [![enter image description here](https://i.stack.imgur.com/aIi9x.gif)](https://i.stack.imgur.com/aIi9x.gif) [Answer] ## Perl, 148 bytes 146 bytes of code + `-pl` flags. ``` $_=O x($x=$_+1);s/O\K./_/g;for$i(1..($y=<>)){$b.=($i%2?$_:_.s/.$//r).$/}}print$_="\e[H$b";while(/O/){$r=0|rand$y*$x+3;s/.{$r}\KO/X/s||redo;sleep 1 ``` To run it: ``` perl -ple '$_=O x($x=$_+1);s/O\K./_/g;for$i(1..($y=<>)){$b.=($i%2?$_:_.s/.$//r).$/}}print$_="\e[H$b";while(/O/){$r=0|rand$y*$x+3;s/.{$r}\KO/X/s||redo;sleep 1' <<< "6 4" ``` [Answer] # MATLAB (R2016b), 172 bytes **Code:** ``` x=input('');m=[eye(x(2),x(1)) ''];m(:)='O';m(1:2:end,2:2:end)='_';m(2:2:end,1:2:end)='_';o=find(m=='O');r=o(randperm(nnz(o)));disp(m);for i=r';pause(1);m(i)='X';disp(m);end ``` Recommendations are always welcome! [Try it online!](https://tio.run/nexus/octave#TY27CsMwDEV/xZsk8GJns9E3dC2EUAJ2wIMfOA24@XnXoaV00tVB96g3DqkcTwQgG3n2L48NNcmGikgALDaiIYYbjKCMNj45qT9z4MeFv6tU/zjzFpLDyFeXbOWMdU2u@BoxpRMzEVkX9oKR7JarCFzBlvXY/Xg9rGF47vA7GeLe50lMyxs) **Program Output:** [![enter image description here](https://i.stack.imgur.com/WM2fX.gif)](https://i.stack.imgur.com/WM2fX.gif) **Explanation:** ``` x = input( '' ); % Input m = [ eye( x( 2 ), x( 1 ) ) '' ]; % Character Matrix m( : ) = 'O'; % Fill Matrix with "Bubbles" m( 1:2:end, 2:2:end ) = '_'; % Alternate Spaces Between Bubbles (Part 1) m( 2:2:end, 1:2:end ) = '_'; % Alternate Spaces Between Bubbles (Part 2) o = find( m == 'O' ); % Index Bubble Locations r = o( randperm( nnz( o ) ) ); % Randomize Bubble Locations disp( m ); % Display Initial Bubble Wrap Phase for i = r' pause( 1 ); % Pause for 1 Second m( i ) = 'X'; % Pop Bubble disp( m ); % Display Subsequent Bubble Wrap Phase end ``` ]
[Question] [ The residents of Flapus use a base-8 number system. The numbers are: 0 - Kuzla 1 - Ponara 2 - Boqkel 3 - Colopee 4 - Vruenat 5 - Foham 6 - Stikty 7 - Kricola For numbers over 7, the full name of the last digit comes first, followed by apostrophe and the first characters of the other digit(s), up to and including the first vowel: *11 - Ponara(1)'po(1) 13 - Colopee(3)'po(1)* 64 - Vruenat'sti 55 - Foham'fo 47 - Kricola'vru As the numbers go up, the formula stays the same - the full name last digit comes first, followed by an apostrophe and the first characters of the other digits, up to and including the first vowel. Note that apart from the final digit (first word), the order remains the same. *123 - Colopee(3)'po(1)bo(2) 205 - Foham(5)'bo(2)ku(0)* 1123 - Colopee'popobo 7654 - Vruenat'kristifo The exception to the rule is for numbers ending in 0. Here the word begins with Ku and is completed with the first letters of the other digits, up to and including the first vowel. No apostrophe is used. 10 - Kupo 70 - Kukri 350 - Kucofo 630 - Kustico 1000 - Kupokuku ### Challenge Write a program or function that accepts a valid base-8 number, and outputs the spoken equivalent. You may assume you will always receive a valid number. Trailing whitepace / single newline after your answer is ok. The first character needs to be upper-case, as per examples. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest code in bytes wins. Standard loopholes apply. Answers whose lengths are converted and additionally submitted in Flapussian get extra cookies. ### Test cases 0 -> Kuzla 1 -> Ponara 2 -> Boqkel 3 -> Colopee 4 -> Vruenat 5 -> Foham 6 -> Stikty 7 -> Kricola 10 - > Kupo 11 -> Ponara'po 23 -> Colopee'bo 56 -> Stikty'fo 70 -> Kukri 100 -> Kupoku 222 -> Boqkel'bobo 2345 -> Foham'bocovru [Answer] ## [Retina](https://github.com/mbuettner/retina/), Colopee'pokri, ~~165~~ ~~157~~ ~~143~~ ~~127~~ 123 bytes ``` (.+)(.) $2'$1 0 Kuzla 1 Ponara 2 Boqkel 3 Colopee 4 Vruenat 5 Foham 6 Stikty 7 Kricola (?<='.*[iou])[a-z]+ T`L`l`'.+ zla' ``` The trailing linefeed is significant. [Try it online!](http://retina.tryitonline.net/#code=KC4rKSguKQokMickMQowCkt1emxhCjEKUG9uYXJhCjIKQm9xa2VsCjMKQ29sb3BlZQo0ClZydWVuYXQKNQpGb2hhbQo2ClN0aWt0eQo3CktyaWNvbGEKKD88PScuKltpb3VdKVthLXpdKwoKVGBMYGxgJy4rCnpsYScK&input=MAoxCjIKMwo0CjUKNgo3CjEwCjExCjIzCjU2CjcwCjEwMAoyMDUKMjIyCjExMjMKMjM0NQo3NjU0) ### Explanation ``` (.+)(.) $2'$1 ``` We start by bringing the trailing digit to the front and inserting an apostrophe after it. Note that this leaves single-digit numbers unchanged, since the regex doesn't match - so those never get an apostrophe in the first place. ``` 0 Kuzla 1 Ponara 2 Boqkel 3 Colopee 4 Vruenat 5 Foham 6 Stikty 7 Kricola ``` This replaces each digit with its full name, regardless of where it appears. ``` (?<='.*[iou])[a-z]+ ``` This shortens all the digit names that appear after an apostrophe. Note that only the vowels `iou` appear first in a digit name, so we check a position that is right after one of those, *and* after an apostrophe and then match (and remove) all lower case letters that follow that position. Since we've inserted the digit names in title case, this will stop before the next digit. ``` T`L`l`'.+ ``` This uses transliteration to turn all upper case characters, `L`, into their lower case counterpart, `l`, provided they are found in a match that starts with `'` (in order to leave the leading capital untouched). ``` zla' ``` The only thing that's left is correctly handling multiples of (octal) 10. In that case, we'll have a result starting with `Kuzla'`, which we want to start with `Ku` instead. So we simply remove all occurrences of `zla'`. [Answer] ## Pyth, 117 bytes (Kricola'popo) ``` Jc"Ku Po Bo Co Vru Fo Sti Kri";K+kc"nara qkel lopee enat ham kty cola";=TsezIszp@JTp@KTp?&T>sz7\'kVPzpr@JsN0;.?"Kuzla ``` Hand-transpiled to pythonic pseudocode: ``` z = input() # unevaluated, raw k = "" Jc"Ku Po Bo Co Vru Fo Sti Kri"; J = "Ku Po...Kri".split() K+kc"nara qkel lopee enat ham kty cola"; K = k + "nara...cola".split() # k casted to [""] =Tsez T = int(end(z)) # end(z) means z[-1] Isz if int(z): p@JT print(J[T]) p@KT print(K[T]) p?&T>sz7\'k print("'" if T and s > z else k) VPz for N in z[:-1]: # P(z) is z[:-1] pr@JsN0 print(J[int(N)].lower()) .? else: "Kuzla print("Kuzla") ``` [Answer] # JavaScript (ES6), 171 ``` n=>(x='Kuzla Ponara Boqkel Colopee Vruenat Foham Stikty Kricola ku po bo co vru fo sti kri'.split` `,r=x[d=+(n=[...n]).pop()],n.map(d=>r+=x[+d+8],n[0]?r=d?r+"'":'Ku':0),r) ``` **Test** ``` F=n=>( x='Kuzla Ponara Boqkel Colopee Vruenat Foham Stikty Kricola ku po bo co vru fo sti kri'.split` `, r=x[d=+(n=[...n]).pop()], n.map(d=>r+=x[+d+8],n[0]?r=d?r+"'":'Ku':0), r ) console.log=x=>O.textContent+=x+'\n' o='' for(i=0;i<999;i++) o+=i.toString(8) +':'+ F(i.toString(8))+(i%8!=7?' ':'\n') console.log(o) ``` ``` #O { font-size:12px } ``` ``` <pre id=O></pre> ``` [Answer] ### Java (1.8) - Vruenat'fobo (~~486~~ 340 bytes) Just when I thought I couldn't possibly golf this any more, I found another 33 bytes! Very pleased! Biggest savings were from switching to char arrays (shorter to upper/lowercase), and reusing the input string array for the words. Discovering loads of golfing tricks, down to under 400! In theory I could still reduce this more, as I said a function would be ok in the rules, whereas this is a full program. **Updated** Using Martin Büttner's approach, I refactored to use regex instead. Managed to save another 10 bytes! Thanks Martin. ``` interface F{static void main(String[]n){String t="",o,a=n[0];n="Kuzla,Ponara,Boqkel,Colopee,Vruenat,Foham,Stikty,Kricola".split(",");int i=0,l=a.length()-1;char f=a.charAt(l);o=n[f-48]+(l>0?"'":"");while(i<l)t+=n[a.charAt(i++)-48];o+=t.replaceAll("(?<=.*[iou])[a-z]+","").toLowerCase();if(f==48)o=o.replace("zla'","");System.out.print(o);}} ``` ### Ungolfed ``` interface Flapus { static void main(String[] names) { String temp="",out, a = names[0]; names = "Kuzla,Ponara,Boqkel,Colopee,Vruenat,Foham,Stikty,Kricola".split(","); int i=0, last = a.length()-1; char lastchar = a.charAt(last); out=names[lastchar-48]+(last>0?"'":""); while(i<last) { temp+=names[a.charAt(i++)-48]; } out+=temp.replaceAll("(?<=.*[iou])[a-z]+", "").toLowerCase(); if (lastchar==48) { out=out.replace("zla'",""); } System.out.print(out); } } ``` [Answer] ## Python (3.5) ~~225~~ ~~222~~ ~~217~~ 202 bytes A working solution with list comprehension in python ``` s=input() d="Kuzla,Ponara,Boqkel,Colopee,Vruenat,Foham,Stikty,Kricola".split(',') r=d[int(s[-1])]+"'"if s[-1]!='0'else'Ku' d=[i[:2+(i[2]in'ui')].lower()for i in d] for i in s[:-1]:r+=d[int(i)] print(r) ``` ## Explanation ``` d="Kuzla,Ponara,Boqkel,Colopee,Vruenat,Foham,Stikty,Kricola".split(',') ``` Win 3 bytes with the split version (previous version: `d="Kuzla","Ponara",...`) ``` r=d[int(s[-1])]+"'"if s[-1]!='0'else'Ku' ``` Initialisation of the result in function of the last digit ``` d=[i[:2+(i[2]in'ui')].lower()for i in d] ``` Change the d list to keep first 2 or 3 characters and put in lower case ``` for i in s[:-1]:r+=d[int(i)] ``` Cat the string [Answer] # Javascript ES6, ~~231~~ ~~228~~ ~~225~~ ~~222~~ 204 bytes ``` a=[...prompt(c="Kuzla,Ponara,Boqkel,Colopee,Vruenat,Foham,Stikty,Kricola".split`,`)];b=c[a.pop()];a.length?b=b==c[0]?"Ku":b+"'":0;for(;a.length;)b+=c[a.shift()].match(/.+?[iou]/)[0].toLowerCase();alert(b) ``` Saved a bunch of bytes thanks to Neil. [Answer] ## F#, ~~364~~ ~~288~~ 250 bytes (Kubofo) ``` let M="Ku-Ponara-Boqkel-Colopee-Vruenat-Foham-Stikty-Kricola".Split '-' let m="Ku-Po-Bo-Co-Vru-Fo-Sti-Kri".Split '-' let rec r a=function|0->a|i->r(m.[i%10].ToLower()::a)(i/10) fun i->String.concat""<|M.[i%10]::((if(i%10)=0 then""else"'")::r[](i/10)) ``` Returns a function that takes an integer and returns its Flapus equivalent. =D [Answer] ## Python 3 - ~~181~~ 177 bytes (Ponara'bosti) ``` a='Ku Po Bo Co Vru Fo Sti Kri zla nara qkel lopee enat ham kty cola'.split() *y,x=map(int,input()) u=x>0 v=y>[] print(a[x]+a[x+8]*u**v+"'"*(u&v)+''.join(a[i].lower()for i in y)) ``` Beware of the most amazing use of `pow` you will ever see in your entire life. `u**v` is equivalent on boolean context as `u|(not v)` which was previously golfed to the nice `~v+2|u` expression! ]
[Question] [ ## Task Given an integer \$n\in[0,10^{12})\$ in any convenient format, return the number of strokes needed to write that character in simplified Chinese. ### Background Chinese numerals are expressed in base 10 with a system of digits and places, with an important distinction that digits are in groups of four, rather than three. The individual characters used to write Chinese can be described at the lowest level as a collection of strokes, laid out in a certain order and manner. The number of strokes required to write a character is that character's stroke count. The (simplified) characters used to write numbers in Chinese are: ``` num char  strokes 0 零* 13 1 一 1 2 二** 2 3 三 3 4 四 5 5 五 4 6 六 4 7 七 2 8 八 2 9 九 2 10 十 2 100 百 6 1000 千 3 10^4 万 3 10^8 亿 3 * 0 can also be written 〇, but we won't use that here. ** 两 is largely interchangeable with 二, apart from never appearing before 十. We won't consider it here for simplicity, but 两 is very common in actual usage. ``` For example, 9 8765 4321 is 九亿八千七百六十五万四千三百二十一: nine hundred-million (九 亿), eight thousand seven hundred sixty-five ten-thousand (八千七百六十五 万), four thousand three hundred twenty-one (四千三百二十一). In all, 53 strokes are needed to write this out. There are additionally some special rules involving the digits `0` and `1`. These can vary slightly between dialects, but we'll choose these: * When there are non-trailing `0`s in a 4-digit group, they are combined into a single `零`. No place marker is used. (This is because e.g. 一百二 is a common way to say 120. We won't consider that form.) + 1020 is 一千零二十. + 6 0708 is 六万零七百零八. + 3 0000 4005 is 三亿四千零五. + 0 is 零. * If the number would begin with `一十`, the `一` is omitted. + Powers of 10 are 一, 十, 一百, 一千, 一万, 十万, 一百万, etc. + 111 is 一百一十一. --- ## Test Cases ``` n strokes chinese 0 13 零 10 2 十 236 17 二百三十六 7041 26 七千零四十一 50010 23 五万零一十 100000 5 十万 860483 42 八十六万零四百八十三 4941507 52 四百九十四万一千五百零七 51001924 38 五千一百万一千九百二十四 105064519 70 一亿零五百零六万四千五百一十九 300004005 31 三亿四千零五 987654321 53 九亿八千七百六十五万四千三百二十一 1240601851 56 十二亿四千零六十万一千八百五十一 608726402463 79 六千零八十七亿二千六百四十万二千四百六十三 ``` @user202729 provided a script in the sandbox to help with reading the Chinese numbers: [Try it online!](https://tio.run/##TVLLattAFF1XXzFoE5sWMyPNjKRAvySkUCyFiKaSkVRKKAEHUYLB3XlThL@geFtsL5KfaSn5CvfM0/LKZ@655557rhb33W1dxadT/v5bEL4Ov8PLkBJCwndB@Ge/BGIOHddAka@tgGKL/g4DEPfMDZBwte87IOn7eqDE134Bpa522AJlrvbjUU2nBv37@awRtbXeIGo0nzT6wM30F4NSoIeg/Lyom460921wUzdkTspKgVnb5WU1a4qP@WR6GbyxT/WXbva1Kbtikl/Nr/HSlIvJ9O0FuSDljWnOSXHXFmQ@PZ3I@VcRAnL9qWgJmd@WVdEWwaiMLVhs/yPkUUktGDmAnc@lKEZoLLEI8SMDxA4OIvW0hHJcKJKOtu8RDkbgJGDihI4pKNWzYi@4QXBggnOeqzJFyESMLIFmq6mkPIUAd45xQOPHSGEoTJpHWDVdPONMUOwhfJem4dyqdxjQqz30sIR3banXvQJ2WBbhw4rTs23F3C91Gq7xsFXwuDaCgV5EUMkFy1REPpwlvg6l7wYZ5zorO92kAUElEqswOKVII2ZeZAUR02KkFDNLEyl4HIElfMKHrWKqNGC418nslLhO3g7dr7xzcywWcSopS4WSkqMrHNfjuVbKJYApWmdjdSRNk0hyGnEJO0nm77Vz7eZG2PpFT4fCTjm0n82TfbQHNbNW/wE "Python 3 – Try It Online") [Answer] ## [Python 2](https://docs.python.org/2/), ~~163~~ ~~162~~ ~~155~~ 151 bytes -1 thanks to [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld), -7 thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs) Hexdump: ``` 00000000: efbb bf65 7865 6322 789c 1dcb c10e c220 ...exec"x...... 00000010: 0cc6 f157 e1c2 d2c2 88b4 6359 34c2 bb20 ...W......cY4.. 00000020: b893 7689 274f 3ebb 65a7 36bf 7cff 3dbf ..v.'O>.e.6.|.=. 00000030: eafb d1ab 91b9 e578 1353 a543 fc32 734a .......x.S.C.2sJ 00000040: ebc2 d44b 114b d1a5 8956 f430 7e5d 9866 ...K.K...V.0~].f 00000050: 93bb 5a62 bba1 5fdc e067 1ace 1b97 d226 ..Zb.._..g.....& 00000060: c240 ca40 67ec 75ad 2de8 b92f 7852 440c .@[[email protected]](/cdn-cgi/l/email-protection)../xRD. 00000070: 2039 0f62 f43b c885 e21c 7e5c 728f 8fd1 9.b.;....~\r... 00000080: 343a d7fe d154 254b 222e 6465 636f 6465 4:...T%K".decode 00000090: 2827 7a69 7027 29 ('zip') ``` Unpacked: ``` f=lambda n,c=0:n and(0x222445321d>>n%10*4&15)+(n%10and c%4*9%12%7)+3*(n%1e4and 272>>c&1)-13*((1>n%10+c%4)+((c%4<3)>n%100))-(n==c%4<2)+f(n/10,-~c)or 13*0**c ``` [Try it online!](https://tio.run/##HY/BbsIwEETP5Sv2ErAT0@6u106CmvxI1UMIjYpUDAIqtUL019M1vsxq5o00Pv1eP4@J53nqvobDdjdAcmOHmwRD2hn8YWaR4Jl2fZ8KwlKWFGxl8q0EjIWUbUFc1LbyZbY/JPtcc9@PS7JrUtvQo1wprV2j8urtw0Jr1yZ1XbbYVpNJL4Ru/Tfa4xm0imU5zun7cIEO3tCBhsA@OqhRyEFApIebn4MmojTegbRCAWvNNaGWJSMBowRqHfgMC2Jw0DZ1DKLfU4AFI1IT9I7Y1BwFWaJ/X0w6RSfAPmW5bBZPp/M@Xc1qMre71WG3@@pZocNwNQo4mLJYa@d/ "Python 2 – Try It Online") ### Commented version ``` f=lambda n,c=0:n and # If n is not zero, sum the following: # The strokes of the current digit (0x222445321d>>n%10*4&15) # [13,1,2,3,5,4,4,2,2,2][n%10] # The 10/100/1000 marker stroke count, if # the currrent digit is zero + (n%10and c%4*9%12%7) # [0, 2, 6, 3][n%10 and c%4] # The 10^4 / 10^8 marker stroke count + 3*(n%1e4and 272>>c&1) # 3*(n%10000 and c in [4,8]) - 13*( # Subtract 13 because we overcounted the zeros if # It's a trailing zero in a group of four (1>n%10+c%4) # (n%10 == 0 and c%4 == 0) # and/or if it's part of a group of zeros +((c%4<3)>n%100) # (n%100 == 0 and c%4 != 3) ) # Subtract 1 if we lead a group of four with 10 - (n==c%4<2) # (n==1 and c%4==1) + f(n/10,-~c) # Recurse on next digit # Else if n=0, return 13 if we are at the first or 13*0**c # digit, else 0 ``` We also use the `exec"...".decode('zip')` to compress our code to save a few bytes. [Answer] # JavaScript (ES6), ~~148 145~~ 139 bytes ``` f=(n,i=0,z=n/1e4|0)=>n?f(z,3)-!(n/10^1)+(g=d=>~~d?n%1e4&&(q=n/d%10,x=296/~~q%5^20>>q&1,x?z=x+=3064/d&7:z*q&&(z=0,13))+g(d/10):i)(1e3):!i*13 ``` [Try it online!](https://tio.run/##bZBdS8MwFIbv9yuOsI9ky7Z8t52kQ1BBFLzwUhwrazcrI926IqNq//o8wVsDITk5z/u@h3xkn9lpU5eHZuqrvLhcto54VjrOWufnotDfnLrUL7ekZYpOrwg@8pWgE7JzuUu7Ll/6AWLDITmiIB8Izs5OJnbedceBWUmepsehYOdl684Tp7jV83wYLdrxESUt5ghF6WRHcvSli5ISUSi6uCrHQl1KfwAHr5wBuoJUlkHEtQhlWAxiy3WsGOhEC8MjBgY7IpE6IAazjEgYqABrzg2DJI6s0UoGD6m55SI2eLc8jqTVXGqr3q57dXEKuQKdJYLoKzEa5RpLg1vFYRI8UWuQMmGyBJU9HHm2req7bPNO8COhpODSHsCm8qdqX8z21Y6s@19@1lQvTV36HaGzQ5a/NFndECHpD3Qp9L@2xNN/kUCQvz44Bzjpa/kGSxg9P45gAaP7m4enu9vRD13THr38Ag "JavaScript (Node.js) – Try It Online") ### Black magic * The number of strokes in the Chinese character for a single decimal digit \$1\le q\le 9\$ can be obtained with: ``` 296 / q % 5 ^ 20 >> q & 1 ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/Lb9Io1DBVsHQWqFQwcZWwRJIa2trKlRzKShUAMWNLM0U9IFSqgqmCnEKRgYKdnZAnhpQPVBBcn5ecX5Oql5OfrpGgkp1Ya2Chkq10pMdDU929TzZ0fl09uwnu6Y8bV37ZEfz09bVT3bOVYouVNBVMIyt1VSos1NQqa6oVSguKcrPTtUo1kzQtOaq/f8fAA "JavaScript (Node.js) – Try It Online") This formula returns \$0\$ for \$q=0\$, which is actually what we want because zeros have to be processed separately anyway. * The number of strokes in the Chinese character for a multiplier \$d\in\{1,10,100,1000\}\$ can be obtained with: ``` 3064 / d & 7 ``` [Try it online!](https://tio.run/##JYlBCoJAGEb3nuJjkJjRSsOohdlFRFDUopJ/wpEQhgmidQfoMt0mOsY00erx3jtWl0rV/eE8zEg2rbU72XNChjgFYZMhcQxDAe0BjeuLGEEASp2OTpN4tUTkzgTrX6slKdm1807ueenrxoD7OmcUVWwK9n7cfvg8X3@7syKnwghct/D1aKCGXp5arkQpUs9Y@wU "JavaScript (Node.js) – Try It Online") ### Commented ``` f = ( // f is a recursive function taking: n, // n = input i = 0, // i = number of strokes for either 10^4 or 10^8 // (0 for the first iteration, then 3) z = n / 1e4 | 0 // z = next 4-digit block, also used as a flag to ) => // tell whether zeros must be inserted n ? // if n is not equal to 0: f(z, 3) // do a recursive call with the next 4-digit block - !(n / 10 ^ 1) // subtract 1 if n is the range [10...19] to account + // for a leading '10' where the '1' must be omitted ( g = d => // g is a recursive function taking a divisor d ~~d ? // if d greater than or equal to 1: n % 1e4 && // abort if the entire block is 0 ( // otherwise: q = n / d % 10, // q = (n / d) mod 10 x = 296 / ~~q % 5 // compute the number of strokes x for this ^ 20 >> q & 1, // decimal digit (i.e. the integer part of q) x ? // if it's not a zero: z = // set z to a non-zero value x += // add to x ... 3064 / d & 7 // ... the number of strokes for d : // else: z * q && // if both z and q are non-zero: (z = 0, 13) // add 13 strokes and set z to 0 so that ) // other contiguous zeros are ignored + g(d / 10) // add the result of a recursive call with d / 10 : // else: i // add i to account for either 10^4 or 10^8 )(1e3) // initial call to g with d = 1000 : // else: !i * 13 // stop the recursion; add 13 if the input was zero ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~60~~ 59 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` Rv•мΛ~?•ÁyèyĀiŽAΘÁNè]IR4ô¤¤sg*2Q(sεÔ0Û}©J0¢I_+13*ŽE₃Á®¦ĀOèO ``` [Try it online](https://tio.run/##AWsAlP9vc2FiaWX//1J24oCi0LzOm34/4oCiw4F5w6h5xIBpxb1BzpjDgU7DqF1JUjTDtMKkwqRzZyoyUShzzrXDlDDDm33CqUowwqJJXysxMyrFvUXigoPDgcKuwqbEgE/DqE///zMwMDAwNDAwNQ) or [verify all test cases](https://tio.run/##FYy7SgNBFIZfJaQK8RTnzJy5bLWksLEwmFZEFCSkslgITLFhV8EHEAshXQiyNlbamWZO0i4@w77IOvtXH//tsbi7Xz3065CPR93L62ich36x7qrd32@73eQJpA7ShGO1Oh1m7bvUl9KUZViwfMd93BfLqbqaFO2PvKFsy/h5gXEXbs9IT0@H8@7pWer4FT@O1VyaeQ/9NQIhKG3BIVPiQeAtstfAGZNBBybZlClOsUHLhjLQQ48RDWTeWcNapbFitEjeEFj0TllGxVYD0XCsMLkO/c0/). **Explanation:** Here a run-down of what each part of the code accomplishes, which we'll sum with `O` at the very end to get the result: * Convert each digit to the amount of strokes used, except for edge case 0: `Rv•мΛ~?•Áyè]` * Get the strokes of 10, 100, 1000 per part of four digits if the current digit is not a 0: `RvyĀiŽAΘÁNè]` * Subtract 1 in case there is a leading `一十`→`十` conversion, by separating the number into parts of four digits, and checking if the first part starts with a `1` and contains just two digits: `IR4ô¤¤sg*2Q(` * Add 13 for each 0, excluding those that are adjacent to other 0s, or trailing in every part of four digits: `IR4ôεÔ0Û}©J0¢13*` * Take care of edge case \$n=0\$: `I_+13*` * Get the strokes of the \$10^4\$ and \$10^8\$, excluding parts that consist solely of 0s: `ŽE₃Á®¦ĀOè` ``` R # Reverse the (implicit) input-integer v # Loop over each of its digits `y`: •мΛ~?• # Push compressed integer 1235442220 Á # Rotate it once to the right: 0123544222 yè # Index the current digit `y` into 0123544222 yĀi # If `y` is NOT 0: ŽAΘ # Push compressed integer 2630 Á # Rotate it once to the right: 0263 Nè # Index the loop-index `N` into 0263 (modulair 0-based) ] # Close both the if-statement and loop IR # Push the reversed input-integer again 4ô # Split it into parts of size 4, where the last part might be smaller ¤ # Push the last part (without popping the list itself) ¤ # Push the last digit (without popping the number itself) s # Swap so the number is at the top of the stack again g # Pop and push its length * # Multiply it to the digit 2Q # Check if length * digit is equal to 2 (1 if truthy; 0 if falsey) ( # Negate that s # Swap so the list of parts of 4 is at the top of the stack again ε # Map each part to: Ô # Connected uniquify each digit (i.e. 0030 becomes 030) 0Û # Remove any leading 0s }© # After the map: store this list in variable `®` (without popping) J # Join it together to a single string 0¢ # Count the amount of 0s left in the string I_ # Check if the input-integer is 0 (1 if 0; 0 otherwise) + # Add that to the count of 0s 13* # Multiply it by 13 ŽE₃ # Push compressed integer 3660 Á # Rotate it once to the right: 0366 ® # Push the list from variable `®` ¦ # Remove the first item Ā # Truthify each part ("" becomes 0; everything else becomes 1) O # Sum this list è # Index it into the 0366 O # And finally sum all values on the stack # (after which this sum is output implicitly as result) ``` [See this 05AB1E tip of mine (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `•мΛ~?•` is `1235442220`; `ŽAΘ` is `2630`; and `ŽE₃` is `3660`. [Answer] ## [Setanta](https://try-setanta.ie/), ~~243~~ ~~236~~ ~~235~~ 234 bytes ``` gniomh(n){gniomh S(n,c){gniomh Q(t){s:=0ma t s=1toradh s}toradh(n&[13,1,2,3,5,4,4,2,2,2][n%10]+[0,2,6,3][n%10&c%4]+3*Q((c==4|c==8)&n%10000)-13*(Q(n%10==0&c%4==0)+Q(n%100==0&c%4!=3))-Q(n==1&c%4==1)+S(n//10,c+1))|13*Q(!c)}toradh S(n,0)} ``` [Try it here!](https://try-setanta.ie/editor/EhEKBlNjcmlwdBCAgIDA9cOMCg) Notes: * This is a port of the [Python 2 solution](https://codegolf.stackexchange.com/a/210121/14109). * The correct keywords for 'function' and 'if' are `gníomh` and `má`, respectively, but Setanta allows spelling them without the accents so I did that to save some bytes. * I had to define the `Q` function above because [Setanta doesn't coerce booleans to integers](https://try-setanta.ie/editor/EhEKBlNjcmlwdBCAgICgpcSCCg). As far as I know, there's nothing equivalent to ternary expressions in this language. * There are no bitwise operations as far as I know, so I had to stick to array lookups. ]
[Question] [ *Based on [this](https://www.youtube.com/watch?v=W20aT14t8Pw) Numberphile video* A self-locating string is a number (or set of numbers) in a decimal expansion which corresponds to its location, from the start of the decimal. For example, take the number: ``` .2734126393112 ``` Here, we can identify certain items quickly, e.g: ``` .27 _3_ _4_ 1263 _9_ 3112 ``` There are a few more complex cases in here though, too. For instance, the numbers `11` and `12` both appear *starting* in their respective positions: ``` .2734126393112 123456789ABCD ^ 11 ^ 12 ``` So the list of self-locating strings in this case would be `[3, 4, 9, 11, 12]`, as even though some of them overlap, they both start in the correct places. If we sum these up, we get 39, or the *self-reference index* (SRI) of this terminating decimal. ## Input A terminating decimal, either an array of digits (after the point) or a decimal type with `0.` at the start/`.`. ## Output The SRI of the input number. ## Rules * In the case that there are no self-referential numbers, the SRI is 0. This must be returned/printed, as opposed to exiting or returning undefined. * The decimal expansion can be assumed to terminate, and will be no more than 128 digits in length. * The counting of the indexes should be 1-based, e.g the first decimal is at position `1`, etc. * Standard I/O rules + standard loopholes apply. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins ## Test cases ``` 0.1207641728 -> 3 .12345678910 -> 55 0.1234567890112 -> 68 .0 -> 0 0.654321 -> 0 .54321 -> 3 ``` [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 16 bytes ``` +/⍬∘⍋(⍸⊣⊃¨⍕⍛⍷¨)⊂ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qG@qc6R6cWJOifqj7pbUvMSknNRgR58QIAcoFeyqF@rs66KelF@RmZeukJ@n/l9b/1HvmkcdMx71dms86t3xqGvxo67mQyse9U591Dv7Ue/2Qys0H3U1/U971DbhUW8f0AxPf5CC9caP2iaCTAxyBpIhHp7B/9MU1A2NjE1MzcwtLA0MDY3UucAiBuZmJobmRhZgrpmpibGRoToA "APL (Dyalog Extended) – Try It Online") Takes a string of digits. ### How it works ``` +/⍬∘⍋(⍸⊣⊃¨⍕⍛⍷¨)⊂ ⍝ Input: character vector of digits ⍬∘⍋ ⍝ X←Array of 1-based indices ( ⍕⍛ ¨) ⍝ Stringify each of X ( ⍷¨)⊂ ⍝ And for each of above, build a boolean array where ⍝ substring matches are marked as 1 ⍝ e.g. '10'⍷'10428104' is [1 0 0 0 0 1 0 0] ⊣⊃¨ ⍝ Extract X-th indices from each of above ⍸ ⍝ Convert ones to its 1-based locations +/ ⍝ Sum ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes ``` āʒ.$yÅ?}O ``` [Try it online!](https://tio.run/##yy9OTMpM/f//SOOpSXoqlYdb7Wv9///XMzI3NjE0MjO2NDY0NPoPAA "05AB1E – Try It Online") [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~60~~ 56 bytes ``` param($n)1..128|%{$o+=$_*($_-eq$n.indexOf("$_",$_))};+$o ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/vyCxKDFXQyVP01BPz9DIoka1WiVf21YlXktDJV43tVAlTy8zLyW1wj9NQ0klXklHJV5Ts9ZaWyX/////6kANxiamZuYWlgaGhkbqAA "PowerShell – Try It Online") Takes input `$n` as a string (else you'll get floating point inaccuracies), then constructs a range from `1` to `128`. We then loop through those numbers (the `|%{...}`) and each iteration we're accumulating into `$o` the current number times if the current number `$_` is `-eq`ual to the `.indexOf` the current number `"$_"` starting at position `$_` in the input string `$n`. In other words, if the current number matches the first index starting at that position, the current number is added to our output. After the loop, we tack on a `+` at the front to account for the zero case (i.e., no numbers in the collection). That result is left on the pipeline and output is implicit. *-4 bytes thanks to inspiration from ElPedro.* [Answer] # [R](https://www.r-project.org/), 1̶0̶2̶, 99 bytes Thanks to @Giuseppe for 99 bytes ``` U=`[` `[`=Map sum(which(paste0[U[list(x<-scan()),`+`[(L=seq(x))-1,seq[nchar(L)]]],collapse=""]==L)) ``` [Try it online!](https://tio.run/##nVBBasMwELzrFYt62aVysRTHTqDqC9xbc3INFkLFAsdxJYUaSt/uKj310ksXhp0Z2GGZsG0nPXQDy9DPZmHxesaP0dsRFxOTK7tTN/mYcH0sojUzEonhfuiw1dG940pUSJFZN9vRBGyp73thL9Nklug0573WLdGmoIEdVCBBQZ3ZMUPeFGN38OJiAmuii@ztEgA9@BksSlU2dSUbdRAg1a7a183hKMtfopRSCchOva92Sgr4WUTwyQBW0GDiw3w9u@AtopswphCXySfM/u1dY5ML6ElwTnnykTUJvQBePHEBf1bxnwpy6OvMiX1t2zc "R – Try It Online") Few bytes can be saved if there is a second 2-byte 3-argument operator like `[`. First time messing with `[`, it is fun. [Answer] # JavaScript (ES6), ~~ 50 ~~ 48 bytes Takes input as a string. A recursive approach. ``` f=(s,n=1)=>s?+s.match('^'+n)+f(s.slice(1),n+1):0 ``` [Try it online!](https://tio.run/##XclBDsIgEADAu8/opbuhEhdqjSbYnzQhCNoGF@M2fh977lxn8T8v4Tt/1iOXR6w1OZCOHaG7y6hEv/0aXtBOrWJUCURLnkMEwo4V4e1UQ2EpOepcnpCgMRfbkxns1RKZBvGw@@HcW0Nb1D8 "JavaScript (Node.js) – Try It Online") `s.match('^'+n)` is either *null* or a singleton array holding \$n\$ as a string. By applying the unary `+`, these values are coerced to \$0\$ or \$n\$ respectively. --- # JavaScript (ES6), 52 bytes Takes input as a string. ``` s=>[...s].reduce(t=>t+!(i-s.indexOf(i+1,i))*++i,i=0) ``` [Try it online!](https://tio.run/##XclLDoIwEADQvbeQVcfCxLYIYVGu4AGMC9KPGUJaw1Tj7atr3/aty3tht9OzdCn7UKOtbOcbIvId9@BfLohi5yKPgjpGSj58rlGQVC0BnKSkluwZqsuJ8xZwyw8RRaNH0ys9mMkopRuAw98Pl95o9Yv6BQ "JavaScript (Node.js) – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~112~~ \$\cdots\$ ~~52~~ 51 bytes Saved 9 bytes thanks to [ElPedro](https://codegolf.stackexchange.com/users/56555/elpedro)!!! Saved a byte thanks to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan)!!! Saved ~~3~~ 4 bytes thanks to [Poon Levi](https://codegolf.stackexchange.com/users/79630/poon-levi)!!! ``` f=lambda s,i=0:s>s[:i]and(s[:i]+`i`in s)*i+f(s,i+1) ``` [Try it online!](https://tio.run/##XY7NasMwEITvfoplT1KtBkn@jUA59gl6C4GotUwEqWwkFVpKn91VYhdKb9/OzA4zf6bL5OWyjPpq3l4GA5E5zVU8xKNyJ@MHcofy7M7OQ6QPrhxJzpSCLkF/PYd3q9BEZPBkrtEqQD8lyMJ3MU4Bko2J2Y/ZvibI/6QAgjshedfWopM9soqyTavqpu36veC5q2n@y1wImY2234xbim/cNnUlxR/h976XU1XAHJxP6xh8PCAbyY0pC8eNtF5HnhiuYAdcfgA "Python 2 – Try It Online") Takes a number in the form `.abc...` as string input and returns its SRI. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~9~~ 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ṫJw"Jẹ1S ``` A monadic Link accepting a list of the digits after the decimal point which yields an integer. **[Try it online!](https://tio.run/##y0rNyan8///hztVe5UpeD3ftNAz@//9/tJGOuY6xjomOoY6RjhmQZQnEhiBeLAA "Jelly – Try It Online")** ### How? ``` ṫJw"Jẹ1S - Link: list of digits, A e.g. [3,2,1,0,5] J - range of length (of A) [1,2,3,4,5] ṫ - tail from index (vectorises) [[3,2,1,0,5],[2,1,0,5],[1,0,5],[0,5],[5]] J - range of length (of A) [1,2,3,4,5] " - zip with: w - first index of substring or 0 [3,1,0,0,1] Note: w has implicit decimalisation of its right argument, so [7,6,5,4]w65 is equivalent to [7,6,5,4]w[6,5] = 2 1 - literal one 1 ẹ - indexes of [2,5] S - sum 7 ``` [Answer] # [J](http://jsoftware.com/), ~~30~~ 29 bytes ``` 1#.#\(=#])(<:,:#@":)@#\".;.0, ``` [Try it online!](https://tio.run/##Xc29CsIwFAXgPU9xSYY0EMO9@TcaKAhOTs51Eou49P2nVEgd6nCGc77hfBo3coZaQIIGhPLNwcDlfrs2EkZMQxUPNZyLLmLkRY1i4uZkUDfFGHs93ws4qDCDJIspeko2y76H8APnQ0z5SLhJzH@CRHYz7IT7GoN3luTusE9tBQ "J – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), ~~46~~ 44 bytes ``` ->n{r=0;n.chars.sum{n[r+=1,r]=~/^#{r}/?r:0}} ``` [Try it online!](https://tio.run/##VcjRCsIgFIDhV4l1mblznNOtsB5EDFYwupmMMwaGs1c3rKvu/u@n9f7Ko8nHi49k4Oz54znQwpd1it7SwSAjZ971bR8p1Vc6QUrZVhwFaCVRi65iRY1sle56hD8Coijje1UrG4GlfuH4NMxxC9u8s4GNNjiX8gc "Ruby – Try It Online") Thanks Value Ink, as usual, for -2 bytes. [Answer] # [Perl 5](https://www.perl.org/) `-pl`, 27 bytes Requires input to be in the format `.####...`: ``` $\+=++$a*/\G$a/ while/./g}{ ``` [Try it online!](https://tio.run/##K0gtyjH9/18lRttWW1slUUs/xl0lUV@hPCMzJ1VfTz@9tvr/fz1DI2MTUzNzC0tDg3/5BSWZ@XnF/3V9TfUMDA3@6xbkAAA "Perl 5 – Try It Online") ## Original version below handles input with or without a leading `0`. ### [Perl 5](https://www.perl.org/) `-pal`, 34 bytes ``` s/^0//;$\+=++$a*/\G$a/ while/./g}{ ``` [Try it online!](https://tio.run/##K0gtyjH9/79YP85AX99aJUbbVltbJVFLP8ZdJVFfoTwjMydVX08/vbb6/389QyNjE1MzcwtLQ4N/@QUlmfl5xf91fU31DAwN/usWJOYAAA "Perl 5 – Try It Online") [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~31~~ 30 bytes ``` {sum m:ex/\d+<!{$/-$/.from}>/} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwv7q4NFch1yq1Qj8mRdtGsVpFX1dFXy@tKD@31k6/9n9xYqWCHlBlWn6RQk5mXmrxfz1DIwNzMxNDcyMLLiDb2MTUzNzC0tAAiWNgaGjEpQcUMTM1MTYy5NIDUwA "Perl 6 – Try It Online") ### Explanation: ``` { } # Anonymous code block returning sum # The sum of m:ex/ / # All possible matches \d+ # Of numbers <!{$/- }> # That are equal $/.from # To their position in the string ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 29 bytes ``` ¶$.`$.`$*;$'¶ Gm`^(.+);+\1 ; ``` [Try it online!](https://tio.run/##K0otycxL/K@q4Z7wn@vQNhW9BBDSslZRP7SNyz03IU5DT1vTWjvGkMv6/389I3NjE0MjM2NLY0NDIy49QyMDczMTQ3MjCxDb2MTUzNzC0tAAiWMAVgcUMTM1MTYy5NIDUwA "Retina 0.8.2 – Try It Online") Link includes test cases. Assumes input begins with the decimal point. Explanation: ``` ¶$.`$.`$*;$'¶ ``` For each offset in the string, list the offset in decimal, then again in unary, then the suffix starting at that offset, wrapping the whole thing in newlines so that the characters in the input string don't contaminate the data. ``` Gm`^(.+);+\1 ``` Keep only the lines where the suffix starts with the offset. ``` ; ``` Take the total of the matching unary offsets. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 18 bytes ``` IΣELθ×ι⁼Iι✂θι⁺ιLIι ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEI7g0V8M3sUDDJzUvvSRDo1BTRyEkMze1WCNTR8G1sDQxpxiiLhMoEZyTmZyqUaijAJQLyCkFq4Hqg6qBAev///WMzI1NDI3MjC2NDQ2N/uuW5QAA "Charcoal – Try It Online") Link is to verbose version of code. Assumes input begins with the decimal point. Explanation: ``` θ Input string L Length E Map over implicit range ι Current index I Cast to string L Length ι Current index ⁺ Added ι Current index θ Input string ✂ Sliced ι Current index I Cast to string ⁼ Equals ι Current index × Multiplied Σ Take the sum I Cast to string for implicit print ``` [Answer] # [Haskell](https://www.haskell.org/), 71 bytes ``` import Data.List f l=sum[i|(i,x)<-zip[0..]$tails l,show i`isPrefixOf`x] ``` [Try it online!](https://tio.run/##XYm7CsIwFED3fsWlOLRQQ5I@Bbs5KrqXYjM09GLShiZiEf89DnFyO49J2MeolPeozbI6OAknyBmtiySo1j51h58Esy097t9oOkpIv3MClQWV2Wl5AQ5ob@socbvKYeu9FjhDC1qYyx0Ss@LsgIBMoYsgJozTuipYzZs4C54XZVU3B0b/AmWMh/Q7VVnknAUO2Psv "Haskell – Try It Online") [Answer] # Java 8, 86 bytes ``` s->{int r=0,i=0;for(;i<s.length();)r+=s.substring(i++).startsWith(i+"")?i:0;return r;} ``` To the point approach. Will see if I can find something shorter later on. Also, this is probably the first time I've used `startsWith` in Java (either in or outside codegolfing). ;) Input as a String. [Try it online.](https://tio.run/##jY8xb8IwEIX3/IpTJlsplu2EBOqm/QVlYehQdTAhUNPgIJ@DVKH89tRJGbpUsJx07z699@6gz3p22H4NVaMR4VUbe4kAjPW12@mqhtW4TgJUZO2dsXtAqoLYR2Gg195UsAIL5YCz58sIupI/mJKrXeuIMk/Imtru/SehirqkRIbdBicnYpKEsuDhPL6ZQJgkjumLeeTK1b5zFpzqBzUGnbpNE4KueefWbOEYyl4rvX@Apr9N19/o6yNrO89O4eQbSyyrSCyLNBMyT5epEDKm0wv/00LyIs9EIRd3oGk2z4vFUvD7WX5Pidt@@TxLpbiJ/aX6qB9@AA) **Explanation:** ``` s->{ // Method with String parameter and integer return-type int r=0, // Result-sum, starting at 0 i=0;for(;i<s.length();) // Loop `i` in the range [0,input-length): r+= // Increase the result-sum by: s.substring(i++) // Take the substring of the input, starting at index `i` // And increase `i` by 1 afterwards with `i++` .startsWith(i+"")? // If this substring starts with `i` (converted to String): i // Increase the result-sum by `i` : // Else: 0; // Leave the result-sum the same by increasing with 0 return r;} // And return the sum as result ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~64~~ 60 bytes ``` lambda i:sum(x for x in range(len(i))if`x`==i[x:x+len(`x`)]) ``` [Try it online!](https://tio.run/##VYnRCoIwFEDf@4r7tl2C6G6mTtiXWOAiVxd0ylJYX78KhOi8nXPm1/KYgsrenvPgxuvNATfPdZQJ/BQhAQeILtx7OfRBMiL7LnXWcpuatP@2j@IF8xw5LOClOKhKF6RKbTSRErj7HbNRb/xNUro4lVVt6CgwvwE "Python 2 – Try It Online") The `0` result works because an empty list in Python is equivalent to `False` which is equivalent to `0` and when you `sum(0)` you very conveniently get `0`. [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 74 bytes ``` a=>Enumerable.Range(1,a.Length).Sum(x=>a.Remove(0,x).StartsWith(x+"")?x:0) ``` [Try it online!](https://tio.run/##jcw7D4IwGIXh3V9hmNqITVuuXsDB6MSEA3MlBZrIR9IW039fmdwkruc8eVuzb43y9xnas7FaQR8qsOW2K7woyhvMo9Ti@ZKkFtBLxEJBKgm9HTB5zCNyRSlILcfpLREN3TJaoa1plB2Q2wUBvrgjxf60uU5gpiXTaGVlpUCiDgWEcZqlMct4HmD8G0Vxkmb5gdF/FGWMr7i1RprEEWcr4Pv7Dw "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # T-SQL, 103 bytes ``` SELECT number+1FROM spt_values WHERE type='P'and-~number=substring(concat(@,''),number+3,len(number+1)) ``` **[Try it online](https://rextester.com/VRZL76178)** [Answer] # [Zsh](https://www.zsh.org/), 43 bytes ``` repeat $#1 ((r+=0${(M)1[++i,-1]#$i})) <<<$r ``` [Try it online!](https://tio.run/##RY7NCsIwEITv@xQL2UNiVLLpr6V9BJ@gFOqhpb1UiZ4MefYYquBl@GCGmXk/lzhLJaObHtPthSQYpXS6M@TlVXGv9Xo88SBoDUpB27bkogKY7w43lMDWVGXOla0TZnlRVvWFzZ8NswUDZZFnluGrCn0qQNoAAuyV/T5GnsXhHAR523EIOl3gRo9kkPzPazhgSlvNwxiG@AE "Zsh – Try It Online") Takes input as a string. Repeatedly `(M)`atches the part of the string string at position `++i` to `-1` that `#`starts with `$i`, and adds it to `$r`. The `0` ensures that a valid number is added in the case of no match, so `$r` is set to a value before being printed. [Answer] # [Python 2](https://docs.python.org/2/), 53 bytes ``` f=lambda s,i=0:s>''and(s.find(`i`)==0)*i+f(s[1:],i+1) ``` A recursive version of a previous version of [Noodle9's Python 2 answer](https://codegolf.stackexchange.com/a/199838/53748). **[Try it online!](https://tio.run/##VYzBDoMgEETv/QpuQLWGRUVLgj/SNJHGkm7SohEu/XqKeupcdt7sZJZvfM1epuTM234ekyWhRCN0GCi1fmKhcpjPiCM3RvAzFo6FG@h7iQXw5OaVxGeIBD1htAIpOtVAJ3takg3rplVdfwXxzwJA7smRq7apJez2cFyfSNayoo/7fn5dhlxwbCOefg "Python 2 – Try It Online")** [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 49 bytes `[Double]` has [15 to 17 significant decimal digits precision](https://en.wikipedia.org/wiki/Double-precision_floating-point_format), so we can consider a finite number of digits ``` param($n)1..99|%{$s+=$_*($n-match"^.{$_}$_")} +$s ``` [Try it online!](https://tio.run/##XY9bC4JAFITf91cc5JhuXnC9Gwj9ksRswwc180KB@tttRS3o7cw3Mwemfrx40@a8KGa8QwzDXKdNWqpYUWaaUTTKA7ZajMlRIKNMuyyXLuaAyYSJRCeiYTtPhJxVoquKyWwr8F0W2KGig0M35rieH4QRswT0vD9qMWYL7ocrXzLWevqe69jsp3cp/lIYQYaBAGDVl1fe6ID8XfOs4zcxApPFaXjbF52QB7FsywkuobpZBn9@W/S0FyQyzR8 "PowerShell – Try It Online") --- # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 54 bytes any string representation of decimal number ``` param($n)$n|% t*y|%{$s+=++$i*($n-match"^.{$i}$i")} +$s ``` [Try it online!](https://tio.run/##XY/hCoJAEIT/31MsspaXGt6ppwVBT1KYXSSomWdUqM9uJ1lB/3a@mVmY6nKXtTrLPB/wBBtohyqpk8LCkmLZmdAsnp3ZorI3to3ZQnO3SJr0bOyWLWY9ZgbtiY1q6AnZWsSx5kvGvUgELOLx3AGfTswPQhHFK@ZpGIZ/1GOMay7iNx8z3vsUYeBz9tMfqf9S6MCElgBgeSsOsnYA5aOSaSOPegnuR6eW6pY3Ws70vCmnuYHWZLny@m3R9adgkH54AQ "PowerShell – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt) `-x`, 12 bytes ``` ÊÇ¥UtZZsl¹*Z ``` [Try it online!](https://tio.run/##y0osKPn//3DX4fZDS0NLoqKKcw7t1Ir6/19Jz9DI2MTUzNzC0sDQ0EiJS7cCAA "Japt – Try It Online") ]
[Question] [ This challenge is about finding the smallest disk that contains some given points. This is made somewhat trickier, however, by the fact that in this challenge, the disk's coordinates and radius must both be integers. Your input will be a list of points with integer coordinates `x` and `y`. You can take this as a list of tuples, a list of lists, or any other way to represent a collection of pairs. `x` and `y` will both be (possibly negative) integers. Every point is guaranteed to be unique, and there will be at least one point. Your output will be a disk in the form of three numbers, `X`, `Y`, and `R`. `X`, `Y`, and `R` are all integers, `X` and `Y` represent the disk's center and `R` represents its radius. The distance between every given point and the center must be less than or equal to `R`, and there must not exist such a disk with a smaller `R` that also satisfies this condition. It is possible that there will be multiple possible solutions for a given input, your code must output at least one of them in this case. You can use any kinds of geometry builtins your language supports if there are any, and input/output may be through built-in point/disk objects instead of just numbers. ## Test Cases ``` Input (Possible) Output(s) (x,y) (X,Y,R) ------------------------- (0,0) (0,0,0) ------------------------- (0,1) (0,0,1) (1,0) (1,1,1) ------------------------- (1,4) (4,4,3) (3,2) (4,1) (4,5) (5,2) (7,4) ------------------------- (-1,0) (0,0,2) (2,0) (1,0,2) ------------------------- (-1,0) (1,0,2) (2,1) (0,1,2) ------------------------- (0,0) (1,0,1) (1,1) (0,1,1) ``` Fewest bytes wins. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog) v2, 19 bytes ``` ;Az{\-ᵐ~√ᵐ+}ᵐ≤ᵛ√;A≜ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/39qxqjpG9@HWCXWPOmYBKe1aIPGoc8nDrbOBAtaOjzrn/P8fHW2oYxirE22kYxwb@z8KAA "Brachylog – Try It Online") This program was easy to write ­– Brachylog's almost perfect for this sort of problem – but hard to golf. It wouldn't surprise me if there was a byte saving somewhere here, as few things I did seemed to have any effect (and it contains nested map instructions, normally a sign that you should be using member/findall, but I can't see a way to do it). This is a function submission. Input is from the left argument to the function in the format `[[x,y],[x,y],…]`, output from the right argument in the form `[r,[[x,y]]]`. (If you want to try negative numbers in the input, note that Brachylog uses `_` for the minus sign, not `-`. This is confusing because the function → full program wrapper that Brachylog ships with, requested using the command-line argument `Z`, will present negative numbers in the *output* with a regular minus sign.) ## Explanation ``` ;Az{\-ᵐ~√ᵐ+}ᵐ≤ᵛ√;A≜ ;A Append something z to every element of the input { }ᵐ such that for each resulting element: - Subtracting \ ᵐ corresponding elements {of the (input, appended) element} ~√ and un-squarerooting ᵐ {the result of} each {subtraction} + and summing {the resulting square numbers} ≤ {lets us find} a number at least as large as ᵛ every element {of the list of sums} √ which can be square-rooted; ;A append the same list as initially to it. ≜ Find the first integer solution to the above, lexicographically. ``` This is interesting in that we're asking Brachylog to find a value of certain properties (in this case, the radius of a disk centred at point `A` that fits all the input points), but hardly placing any requirements on it (all we require is that the radius is a number). However, Brachylog will internally calculate the radius in question symbolically rather than trying to use concrete numbers, so when the final `≜` is reached, it accomplishes two things at once: first, it ensures that only integers are used for the coordinates of `A` and for the radius (forcing the squared radius to be a square number, and explaining the use of `≤ᵛ` to find a "maximum or greater"); second, it finds the smallest possible viable radius (as the radius comes first in the output). One thing that isn't specified in the program at all is that all the points are measured against the same centre of a disk; as written, there are no constraints that we don't use a different centre for each point. However, the tiebreak order (which in this case is set by the third `ᵐ`, and which as a structure constraint will be evaluated before the value constraint implied by `≜`) wants `A` to be as short as possible (i.e. a single element, so we use the same centre each time; it tries a zero-length `A` first but that obviously doesn't work, so it tries a singleton list next). As a result, we end up getting a useful constraint (that we only have one disk) "for free". This solution [happens to generalise to any number of dimensions](https://tio.run/##SypKTM6ozMlPN/r/39qxqjpG9@HWCXWPOmYBKe1aIPGoc8nDrbOBAtaOjzrn/P8fHW2oY6RjHKsTbaJjqmMGpE11jHUMY2P/RwEA), with no changes to the source code; there are no assumptions here that things are two-dimensional. So if you happen to need the smallest integer sphere, you can have that too. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~25~~ ~~24~~ ~~22~~ ~~21~~ ~~20~~ 18 bytes ``` «/r»/Œpµ³_²§½ṀĊ,)Ṃ ``` *Thanks to @EriktheOutgolfer for letting me know about `)`, saving 1 byte.* *Thanks to @Dennis for saving 2 bytes.* [Try it online!](https://tio.run/##y0rNyan8///Qav2iQ7v1j04qOLT10Ob4Q5sOLT@09@HOhiNdOpoPdzb9//8/WsNQx0RTR8NYxwhImugYgklTIGkKFjEHysYCAA "Jelly – Try It Online") ### Explanation ``` «/r»/Œpµ³_²§½ṀĊ,)Ṃ Main link. Arg: points e.g. [[1,4],[3,2],[3,1]] «/ Find minimums by coordinate e.g. [1,1] »/ Find maximums by coordinate e.g. [3,4] r Inclusive ranges by coordinate e.g. [[1,2,3],[1,2,3,4]] Œp Cartesian product of the x and y ranges e.g. [[1,1],[1,2],[1,3],[1,4],...,[3,4]] µ Chain, arg: center e.g. [1,3] ³ Get the original points e.g. [[1,4],[3,2],[3,1]] _ Subtract the center from each e.g. [[0,1],[2,-1],[2,-2]] ² Square each number e.g. [[0,1],[4,1],[4,4]] § Sum each sublist e.g. [1,5,8] ½ Square root of each number e.g. [1,2.24,2.83] Ṁ Find the maximum e.g. 2.83 Ċ Round up e.g. 3 , Pair with the center point e.g. [3,[1,3]] ) Do the above for all points e.g. [[3,[1,1]],[3,[1,2]],[3,[1,3]],...,[3,[3,4]]] Ṃ Find the lexicographically smallest pair e.g. [3,[1,1]] ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 81 bytes ``` {min [X]([Z]($^p)>>.minmax).map:{$p.map({(@_ Z-$_)>>².sum**.5}).max.ceiling,$_}} ``` [Try it online!](https://tio.run/##RYxRCoJAEIbfO8U@LDET4@KaFgRJxwjFREJDcG1RAkW8VEfoYtuuEj3983/zzeiyaw5GjWxbsbOZVN2y9JpBmmTAbxrjWFikigGFKvRp4tolTHDJWeLx3Aqft@hfarcT0eykQdzLuqnbB/F8nk1fjEzY39Wz2wD45CMhLZNEYiAtWLqk0PU9BS7CdRtS5CJa4dEqi@u5KwuC3/EfSETzBQ "Perl 6 – Try It Online") Takes a list of points as 2-element lists `((X1, Y1), (X2, Y2), ...)`. Returns a list `(R, (X, Y))`. Uses the same approach as Pietu1998's Jelly answer: ``` [X]([Z]($^p)>>.minmax) # All possible centers within the bounding box .map:{ ... } # mapped to $p.map({(@_ Z-$_)>>².sum**.5}).max # maximum distance from any point .ceiling # rounded up, ,$_ # paired with center. min # Find minimum by distance. ``` The `minmax` method is useful here as it returns a `Range`. The Cartesian product of ranges directly yields all points with integer coordinates. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 26 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` øεWsàŸ}`âεUIεX-nOt}àîX‚}{н ``` Port of [*@Pietu1998*'s Jelly answer](https://codegolf.stackexchange.com/a/175406/52210). [Try it online](https://tio.run/##yy9OTMpM/f//8I5zW8OLDy84uqM24fCic1tDPc9tjdDN8y@pPbzg8LqIRw2zaqsv7P3/Pzpa10RH1zRWJ1rXUEfXBEQb6@gagWhzKB8obwiiTUHisQA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWVY5P/DO85tDS8@vODojtqEw4vObQ2NPLc1QjfPv6T28ILD6yIeNcyqrb6w97/O/@joaAMdg9hYHQUQwzBWJ9oQxjXUMQFyjXWMgKQJWMpExxRImoJFzIGyYGW6IA060UYwbXC@IaYxxjBBXRMdXZBZQMW6IGldYx1dkAJdcygfKA@yUdcUJB4bCwA). **Explanation:** ``` ø # Zip the (implicit) input, swapping the rows and column # i.e. [[1,4],[3,2],[3,1]] → [[1,3,3],[4,2,1]] ε } # Map each to: W # Push the smallest value (without popping the list) # i.e. [[1,3,3],[4,2,1]] → [1,1] s # Swap so the list is at the top of the stack again à # Pop the list and push the largest value # i.e. [[1,3,3],[4,2,1]] → [3,4] Ÿ # Take the inclusive range of the min and max # i.e. [[1,2,3],[1,2,3,4]] ` # After the map, push both lists separated to the stack â # And take the cartesian product of the two lists # i.e. [[1,2,3],[1,2,3,4]] # → [[1,1],[1,2],[1,3],[1,4],[2,1],[2,2],[2,3],[2,4],[3,1],[3,2],[3,3],[3,4]] ε } # Map each pair to: U # Pop and store the current value in variable `X` I # Push the input ε } # Map each pair in the input to: X # Push variable `X` - # Subtract it from the current pair # i.e. [3,2] - [1,3] → [2,-1] n # Take the square of each # i.e. [2,-1] → [4,1] O # Sum the lists # i.e. [4,1] → 5 t # Take the square-root of each # i.e. 5 → 2.23606797749979 à # Pop the converted list, and push its largest value # i.e. [[3.0,2.23606797749979,2.0],[2.0,2.0,2.23606797749979],...,[2.0,2.0,3.0]] # → [3.0,2.23606797749979,...,3.0] î # Round it up # i.e. [3.0,2.23606797749979,...,3.0] → [3.0,3.0,3.0,4.0,4.0,3.0,3.0,4.0,4.0,3.0,3.0,3.0] X‚ # Pair it with variable `X` # i.e. [[3.0,[1,1]],[3.0,[1,2]],...,[3.0,[3,4]]] { # After the map, sort the list н # And take the first item (which is output implicitly) # i.e. [[3.0,[1,1]],[3.0,[1,2]],...,[3.0,[3,4]]] → [3.0,[1,1]] ``` [Answer] # Matlab, 73 bytes ``` function g(x);[r,~,d]=fminimax(@(a)pdist2(x,a),[0 0]);[round(r) ceil(d)] ``` Simply find the smallest solution (floating point) and round to nearest point and ceil the radius (worst case for the minimax problem). I don't know for sure if that yields the correct solution for all possible cases (within the precision), but for the test cases it should work (if I didn't make a typing error). Call it with ``` g([1 4;3 2;4 1;4 5;5 2;7 4]) ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), ~~34~~ 33 bytes ``` hSm+.EeSm@s^R2-Vdk2Qd*Fm}FhM_BSdC ``` Output is in the form `[R,x,y]` Try it online [here](https://pyth.herokuapp.com/?code=hSm%2B.EeSm%40s%5ER2-Vdk2Qd%2AFm%7DFhM_BSdC&input=%5B%5B1%2C4%5D%2C%5B3%2C2%5D%2C%5B4%2C1%5D%2C%5B4%2C5%5D%2C%5B5%2C2%5D%2C%5B7%2C4%5D%5D&debug=0), or verify all the test cases at once [here](https://pyth.herokuapp.com/?code=hSm%2B.EeSm%40s%5ER2-Vdk2Qd%2AFm%7DFhM_BSdC&test_suite=1&test_suite_input=%5B%5B0%2C0%5D%5D%0A%5B%5B0%2C1%5D%2C%5B1%2C0%5D%5D%0A%5B%5B1%2C4%5D%2C%5B3%2C2%5D%2C%5B4%2C1%5D%2C%5B4%2C5%5D%2C%5B5%2C2%5D%2C%5B7%2C4%5D%5D%0A%5B%5B-1%2C0%5D%2C%5B2%2C0%5D%5D%0A%5B%5B-1%2C0%5D%2C%5B2%2C1%5D%5D&debug=0). ``` hSm+.EeSm@s^R2-Vdk2Qd*Fm}FhM_BSdCQ Implicit: Q=eval(input()) Trailing Q inferred CQ Transpose (group x and y coordinates separately) m Map each in the above, as d, using: Sd Sort d _B Pair with its own reverse hM Take the first element of each, yielding [min, max] }F Generate inclusive range *F Cartesian product of the above two lists, yielding all coordinates in range m Map each coordinate in the above, as d, using: m Q Map each coordinate in input, as k, using: -Vdk Take the difference between x and y coordinates in d and k ^R2 Square each s Sum @ 2 Take the square root eS Take the largest of the result .E Rounded up + d Prepend to d S Sort the result, first element as most significant h Take first element ``` *Edit: Saved a byte by rearranging output format, previous version:* `heDm+d.EeSm@s^R2-Vdk2Q*Fm}FhM_BSdC` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 66 bytes Here's a brute force approach. I considered the much shorter `BoundingRegion[#,"MinDisk"]&` function but there is no way to force integer coordinates & radius. ``` Minimize[{r,RegionWithin[{x,y}~Disk~r,Point@#]},{x,y,r},Integers]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73zczLzM3syo1urpIJyg1PTM/LzyzJCMzL7q6Qqeyts4lszi7rkgnID8zr8RBObZWBySsU1Sr45lXkpqeWlQcq/Y/oAgoGZ3mUF1tqGMCVGGsYwQkTXQMwaQpkDQFi5gDZWtjrf8DAA "Wolfram Language (Mathematica) – Try It Online") [Answer] # Java 10, ~~283~~ ~~279~~ ~~277~~ 257 bytes ``` C->{int M=1<<31,m=M,X=M,Y=M,x=M-1,y=x,t,a,b,r[]={x};for(var c:C){x=(t=c[0])<x?t:x;X=t>X?t:X;y=(t=c[1])<y?t:y;Y=t>Y?t:Y;}for(;y<=Y;y++)for(t=x;t<=X;r=m<r[0]?new int[]{m,t,y}:r,m=M,t++)for(var c:C){a=c[0]-t;b=c[1]-y;a*=a;m=(a=(int)Math.ceil(Math.sqrt(a+=b*=b)))>m?a:m;}return r;} ``` -20 bytes thanks to *@nwellnhof*'s tip of using [`Math.hypot`](https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#hypot-double-double-). The result-array is in the order `[R,X,Y]`. [Try it online.](https://tio.run/##jVJLb@IwEL73V/hoq3ZECqgSjkErzumll0SIg2vSbdg8kDOwsSL/dnYc0mql3UV78Hje8/nzHPVFi@Phx9VUuutIqstmeCCkbKCw79oU5CWYo2O3J4aON2pbJtHvH1B0oKE05IU0RJHrVqwHTCKpipNkHvNapTzDk@PpVSpi7lTPgWtud3s19F6@t5ZetCVmtWVDrygos5vtWdJvYNXLTME6Qy2T7haKMeTQ4WSOoRy1XPrQQ7pE5dI9PrJggeolJCqTVtWJxYabpvh5e8ZQ43znV3YEB1PBJ4RaUa3CO1mq4SMyRVnRUftwpxZowCaABxzCMcbW9UavamkLONuGWOmvMpByOr9VSMrEzaUtD6RGbukr2LL5jgRqdiMWig7oFzQEN8z4zPuR3r9HY8@H@G5OzBeYM@dPKBdj/oIvUS5HzzNG/10rQms@PN0d8JUU/yeK@d1MseAi4MO2ItSIORehSjxPNsbDK8Qy@P0fqzfSO7b9XE/TtvZQNhqdE8@vroOijtozRCf8AqgaesTdj85QVtE3a7XrImhv30ObyNDfW7BppL/@Ag) **Explanation:** ``` C->{ // Method with 2D int-array as parameter & int-array as return-type int M=1<<31, // Minimum `M`, starting at -2,147,483,648 m=M, // Temp integer, starting at -2,147,483,648 as well X=M, // Largest X coordinate, starting at -2,147,483,648 as well Y=M, // Largest Y coordinate, starting at -2,147,483,648 as well x=M-1, // Smallest X coordinate, starting at 2,147,483,647 y=x, // Smallest Y coordinate, starting at 2,147,483,647 as well t,a, // Temp integers, starting uninitialized r[]={x}; // Result-array, starting at one 2,147,483,647 for(var c:C){ // Loop over the input-coordinates x=(t=c[0])<x?t:x; // If the X coordinate is smaller than `x`, change it X=t>X?t:X; // If the X coordinate is larger than `X`, change it y=(t=c[1])<y?t:y; // If the Y coordinate is smaller than `y`, change it Y=t>Y?t:Y;} // If the Y coordinate is larger than `Y`, change it for(;y<=Y;y++) // Loop `y` in the range [`y`,`Y`]: for(t=x;t<=X // Inner loop `t` in the range [`x`,`X`]: ; // After every iteration: r=m<r[0]? // If `m` is smaller than the first value: new int[]{m,t,y} // Replace the result with `m,t,y` : // Else: r, // Leave `r` unchanged m=M, // Reset `m` to -2,147,483,648 for the next iteration t++) // And increase `t` by 1 for(var c:C) // Inner loop over the input-coordinates m=(a=(int)Math.ceil(Math.hypot(c[0]-t,c[1]-y))) // Subtract `t` from the X coordinate; // subtract `y` from the Y coordinate; // take the hypot (<- sqrt(x*x+y*y)) of those // ceil it // And set `a` to this value >m? // If `a` is larger than `m`: a // Set `m` to `a` : // Else: m; // Leave `m` unchanged return r;} // Return the result `r` ``` [Answer] # Javascript, 245 bytes ``` a=>{[b,c,d,e]=a.reduce(([j,k,l,m],[h,i])=>[j>h?j:h,k<h?k:h,l>i?l:i,m<i?m:i],[,,,,]);for(f=c;f<b;f++){for(g=e;g<d;g++){s=a.reduce((o,[p,q])=>o>(r=(p-f)**2+(q-g)**2)?o:r);n=n?n[2]>s?[f,g,s]:n:[f,g,s]}}return [n[0],n[1],Math.ceil(Math.sqrt(n[2]))]} ``` (Somewhat) more readable version: ``` a=>{ [b,c,d,e]=a.reduce(([j,k,l,m],[h,i])=>[j>h?j:h,k<h?k:h,l>i?l:i,m<i?m:i],[,,,,]); for(f=c;f<b;f++){ for(g=e;g<d;g++){ s=a.reduce((o,[p,q])=>o>(r=(p-f)**2+(q-g)**2)?o:r); n=n?n[2]>s?[f,g,s]:n:[f,g,s] } } return [n[0],n[1],Math.ceil(Math.sqrt(n[2]))] } ``` Just finds the bounding box, and tests each coordinate in that box for whether it's the best. I could save 8 bytes with an approximate answer, by replacing: `Math.ceil(Math.sqrt(n[2]))` with `~~(n[2]+1-1e-9)` [Answer] # [Ruby](https://www.ruby-lang.org/), 113 bytes ``` ->l{a=l.flatten;(z=*a.min..a.max).product(z).map{|x,y|[l.map{|u,v|(((x-u)**2+(y-v)**2)**0.5).ceil}.max,x,y]}.min} ``` [Try it online!](https://tio.run/##JYzBDoMgEER/pUew66ZaTQ/G/gjhQK0mJtQSIwYUvp2u9rBvZ2eyM9uXT0Ob8qfeVatx0GpZ@qlhW5sp/IwTIi3lOJr5@7bdwjZOt9mDAx@E/msLa2CMudzyLCuvzOfrIWhuWHPs@lHHowXoScajNiZzGYQQBVQSxB1KYgXFyZpYn86DUinTDw "Ruby – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 65 bytes ``` ≔Eθ§ι¹ζ≔Eθ§ι⁰ηF…·⌊η⌈ηF…·⌊ζ⌈ζ⊞υ⟦ικ⟧≔Eυ⌈EθΣEιX⁻§λξν²ηI§υ⌕η⌊ηI⌈X⌊η·⁵ ``` [Try it online!](https://tio.run/##fY8xa8MwEIV3/wqNJ1BLnMR06BQCgQwGk47Cg3BU64giJ5aVGv95RYpdtxnag@Mdx8e9d5USbdUI7f3GWqwN5OICV0Y23d4cZQ/ISEopIwN9T/4kFpFQgfhsWgJ7U2ln8SYPwtQScjR4dmdQgclFP82Ukv/g4Rc8RLhwVoFjhAe7U/kcxv2wU7aPaQxw0XzJNt51Fr4ja0b6YGBCL@mjxvhFi6aDrbDdjIbbOzRHUMFjfiTWE72VqNHUMJvNHy9eswftPecJT9m6ZAlfsWWUNUtHyaJk4/ItIElZ@pebvgM "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ≔Eθ§ι¹ζ ``` Get the y-coordinates into `z`. ``` ≔Eθ§ι⁰η ``` Get the x-coordinates into `h`. ``` F…·⌊η⌈ηF…·⌊ζ⌈ζ⊞υ⟦ικ⟧ ``` Loop over the inclusive ranges from the minimums to the maximums of `h` and `z` generating the list of all potential disc centres. ``` ≔Eυ⌈EθΣEιX⁻§λξν²η ``` Loop over all the disc centres, then loop over all of the original points, then loop over both coordinates, subtract, square, sum, take the maximum, and save the resulting list. ``` I§υ⌕η⌊η ``` Find the position of the minimal maximum diameter and print the corresponding disc centre. ``` I⌈X⌊η·⁵ ``` Print the minimal maximum diameter, but round it up to the next integer. ]
[Question] [ # Drunkard's Journey Home In this challenge you are to write a program which simulates a drunkard stumbling his way home from the bar. ### Input: The input will be an adjacency matrix (representing a directed graph) which represents paths the drunkard can take. At each location, the drunkard will choose one path at random (Each option has an approximately equal chance and is independent of prior choices) to follow. Assume that the drunkard always starts at the bar (first row in the adjacency matrix). If the drunkard enters a dead-end it can be assumed that he has either made his way home or has been arrested for public intoxication and the program should return his path. It can be assumed that the graph will always contain at least one dead-end. It can also be assumed that the drunkard will always be able to exit the bar (the first row will not be all zeroes) and that if the drunkard would be stuck in a location, that the row would be represented by all zeroes. ### Output: The output will be the path the drunkard took in his attempt to make his way home. The values for the locations can be either zero or one indexed. ### Examples: ``` Input [1,0,1,1] [0,0,0,0] [1,0,0,0] [1,1,1,1] Possible Outputs [0,2,0,3,2,0,0,3,1] [0,3,0,3,1] Input [0,1,1,1,0,1] [1,0,1,0,1,1] [0,0,0,0,0,0] [0,0,0,0,0,1] [1,0,0,0,0,0] [0,0,0,0,0,0] Possible outputs [0,1,5] [0,5] [0,1,4,0,2] [0,3,5] [0,3,0,1,4,0,5] Deterministic path: Input [0,0,1,0] [0,0,0,1] [0,1,0,0] [0,0,0,0] Output [0,2,1,3] ``` [Answer] ## Mathematica, 72 bytes ``` {1}//.{r___,x_}:>{r,x,n=1;Check[RandomChoice[#[[x]]->(n++&/@#)],##&[]]}& ``` This is a function takes the matrix as an argument and returns a list, and it uses 1-indexing. The basic idea is to start with ``` {1}//. ``` which repeatedly applies the rule that follows to the list `{1}` until it stops changing. The rule matches the pattern ``` {r___,x_}:> ``` which means "a list with zero or more elements called `r` followed by an element called `x`." This gives `x` as the last element in the current list, and we replace the list with ``` {r,x,<stuff>} ``` which is the original list with `<stuff>` appended. The stuff in question is ``` RandomChoice[#[[x]]->(n++&/@#)] ``` which takes `#[[x]]` (the `x`th element of the input matrix) as a list of weights and maps them to `n++&/@#`, which is short for `Range@Length@#` (i.e. `{1,2,3,...}` with the appropriate length). This will throw an error if the weights are all zero, which is why it's wrapped in a ``` Check[...,##&[]] ``` which will return `##&[]` if an error message is generated. This is just a fancy way of writing `Sequence[]`, which acts as a "nothing" element (`{1,2,Sequence[],3}` evaluates to `{1,2,3}`) and therefore leaves the list unchanged, causing the `//.` to stop replacing. [Answer] # [R](https://www.r-project.org/), ~~72~~ ~~69~~ 66 bytes ``` function(m,o=1)while({print(o);any(x<-m[o,])})o=sample(which(x),1) ``` [Try it online!](https://tio.run/##TYoxCoQwFAWvot1/8AUDdqsnEYsQDAY2@RIjZlk8e9Rm2WZmionFVn1T7B5MchLIswwKx@LeM33X6EIiwUuHD@W@8aPwhBMybNqv93F/ZqEMViiWvE7RZaprQ4pbVvyw/aufwR13QLkA "R – Try It Online") Takes input as a `logical` matrix, and prints the 1-based indices to the console. [Answer] # [Perl 5](https://www.perl.org/) `-a0`, ~~53~~ 51 bytes Give input matrix as separate tight strings on STDIN ``` $!/usr/bin/perl -a0 $n=!say$%;$F[$%]=~s:1:($%)=@-if 1>rand++$n:eg&&redo ``` [Try it online!](https://tio.run/##K0gtyjH9/18lz1axOLFSRdVaxS1aRTXWtq7YytBKQ0VV09ZBNzNNwdCuKDEvRVtbJc8qNV1NrSg1Jf//fwNDQ0MDQy4gBrK4DAyAtAEXiABSYNKAywBC/csvKMnMzyv@r2uQ@F/X11TP0EDPAAA "Perl 5 – Try It Online") Damages `@F` during the loop body but it gets repaired by `redo` [Answer] # [MATL](https://github.com/lmendo/MATL),15 bytes ``` 1`GyY)ft?th1ZrT ``` Output is 1-based. Try it online! [First input](https://tio.run/##y00syfn/3zDBvTJSM63EviTDMKoo5P//aEMdBQMdBSBpaA1iQJG1giEqG4piAQ). [Second input](https://tio.run/##y00syfn/3zDBvTJSM63EviTDMKoo5P//aAMdBUMYArGtYQwYCRQx0EFFGCJwXXjUGMQCAA). [Third input](https://tio.run/##y00syfn/3zDBvTJSM63EviTDMKoo5P//aAMdBSAyBJLWChA2iGsNE0QVN4gFAA). ### Explanation ``` 1 % Push 1: initial value of current row index ` % Do...while G % Push input matrix y % Duplicate from below: pushes copy of current row index Y) % Get that row f % Find: push (possibly empty) array of indices of non-zero entries t % Duplicate ? % If non-empty th % Attach a copy of itself. This is needed in case the array % contains a single number n, because then the randsample % function would incorrectly treat that as the array [1 2 ... n] 1Zr % Randsample: pick 1 entry at random with uniform probability T % Push true % End (implicit) % End (implicit). Proceed with a new iteration if the top of the % stack is truthy. This happens if the current row had some % non-zero entry, in which case true was pushed (and is now % consumed). If the current row was all zeros, the top of the stack % is an empty array that was produced by the find function, which is % falsy (and is also consumed now). In that case the loop is exited, % and then the stack contains a collection of numbers which % collectively describe the path % Implicit display ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 38 bytes ``` {0,{.[$^l].grep(?*,:k).roll}...^!*.kv} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/2kCnWi9aJS4nVi@9KLVAw15LxypbU68oPyenVk9PL05RSy@7rPZ/cWKlQpqGSrymQlp@ERenRrShjoGOoY5hrE60gQ4YAlmGSCwwjNXUAak1gPBAOqCqMHRD9SF4hgjzMOQM4OaCTYLLQcwzRFUfq/kfAA "Perl 6 – Try It Online") [Answer] # Python, 136 bytes Using zero indexing, assuming randrange has been imported. Takes an input m as the adjacency matrix **113 no imports** `s=lambda m,c=0,p=[0],x=0:1 in m[c]and(m[c][x]and s(m,x,p+[x],randrange(len(m)))or s(m,c,p,randrange(len(m))))or p` **136 with imports** `import random as r;s=lambda m,c=0,p=[0],x=0:1 in m[c]and(m[c][x]and s(m,x,p+[x],r.randrange(len(m)))or s(m,c,p,r.randrange(len(m))))or p` [Answer] # [Ruby](https://www.ruby-lang.org/), ~~70 67~~ 65 bytes ``` f=->m,i=0{m[i].sum<1?[]:m[i][x=rand(m.size)]<1?f[m,i]:[x]+f[m,x]} ``` Thanks to [benj2240](https://codegolf.stackexchange.com/users/77973/benj2240) for saving 2 bytes! [Try it online!](https://tio.run/##KypNqvyfZhsDxLp2uTqZtgbVudGZsXrFpbk2hvbRsVYgXnSFbVFiXopGrl5xZlWqZixQJi0aqDjWKroiVhvErIit/c9VoJAWHR1tqGOgY6hjGKvDpQAC0QY6YAjnG2LwwTA2NpbrPwA "Ruby – Try It Online") [Answer] # JavaScript (ES6), 87 bytes ``` f=(a,y=0)=>[y,.../1/.test(r=a[y])?f(a,(g=_=>r[k=Math.random()*r.length|0]?k:g())()):[]] ``` [Try it online!](https://tio.run/##fZBBCsIwEEX3PUWWiYxpojsh9QSeIAQb2rRGayJpEArevbaKlmKRmc0fPu9/5qzvui2CvcW186Xp@0pgDZ1gRGSyA0ppylMaTRtxEFp2iuyrwYBrcRRZkBdx0PFEg3alv2KyCrQxro6nB1P7y67GhAy7k0r1hXetbwxtfI0rLBOEJAcGHLiCUTB4zVvwuXiNShShZ29dDjlJkgUeextH6oRZCpnY04HPkpcc7H8DlKYIlyaacLXOttEW6Db8Bq0zxGAzdNiSD4/P4d9y/Cd2Ftk/AQ "JavaScript (Node.js) – Try It Online") --- # Alternate version, 81 bytes Takes input as an array of binary strings. The maximum supported size is 16x16. ``` f=(a,y=0)=>[y,...+(r=a[y])?f(a,(g=_=>+r[k=Math.random()*r.length|0]?k:g())()):[]] ``` [Try it online!](https://tio.run/##fY9BCsIwEEX3PUV2TTSNie6EtCfwBCFoaNOaWhNJg1Dw7jUqpRbE4S8@M8z7M626q7705hYy6yo91jwKKjxwinguBkwIWUPPlRgkKuo4gQ0/8nztxYUfVDgTr2zlrhCtPOm0bcL5QWVx2TcQoai9kHIsne1dp0nnGlhDkQCQMspYil@Oxvo4NrtYaSIRaZ2xJ3xCSfKDERERM@0uiRPpbdnMX/Tp/wyw2QBY6aD91VjTB1OCW/wYZDmgeIsZ3qEPis3Q6QT2HbSIGZ8 "JavaScript (Node.js) – Try It Online") [Answer] # Java 10, 135 bytes ``` m->{var R="0 ";for(int r=0,c,t;;R+=(r=c)+" "){t=0;for(int x:m[r])t+=x;if(t<1)return R;for(t=c=m.length;m[r][c*=Math.random()]<1;)c=t;}} ``` 0-indexed **Explanation:** [Try it online.](https://tio.run/##jVPLboMwELz3K1ac7IYgfI3rSD32kKhKj1EOrkNap2Ais6SpEN9OjSFNaUlVmYe83t2ZYYe9PMrpfvvWqFQWBSykNtUNgDaY2J1UCSzbLcATWm1eQBF3st6sN5BR7g5qd7urQIlawRIMCGiy6bw6SgsrEcQQ8F1u2yqwIg5ViJyvJoJYoegkgIBWKOKvlNMsW9sNxYk4cb0jeMeoTbC0BlY@B4USWZQm5gVfeZu6VrdiIfE1stJs84zQzR3jVAnkdd3wjtyhfE4duZ7jMddbyJxM0klyUiTtNGJSIDHJO/QauyhAxcI4ZCGrw3MgDv26BNjvgF@139f@W/0BEHfZLcyw5zXkIdglyH5RupYZ/5uaZ/GzxYASGwUZAvjHec5asJiDnk7n7kX7umsURgYwMoKRIfwcw5nM0LTeEB77Yu3e8x8FJlmUlxgdnFUwNSR4MIcSZ863/Lug1kQwc4U9zkjl3v1oUYk6je6tlR9FhHlnQCJp32wM7zEvCv2cJuCiA@SRZBMpkv3RrBdfN58) ``` m->{ // Method with integer-matrix parameter and String return-type var R="0 "; // Result-String, starting at "0 " for(int r=0, // Row-integer, starting at 0 c, // Column-integer t; // Temp-integer ; // Loop indefinitely R+= // After every iteration: Append the result with: (r=c)+" "){ // The current column and a delimiter-space, // And set the current row to this column at the same time t=0; // (Re-)set `t` to 0 for(int x:m[r]) // Loop over the values of the current row t+=x; // And add them to `t` if(t<1) // If the entire row only contained zeroes: return R; // Return the result for(t=c=m.length; // Set `t` (and `c`) to the size of the matrix m[r][c*=Math.random()]<1;) // Loop until we've found a 1, // picking a random column in the range [0,`c`) c=t;}} // Reset the range of `c` to `t` (the size of the matrix) ``` [Answer] # [Haskell](https://www.haskell.org/), ~~123~~ 118 bytes ``` import System.Random i#m|sum(m!!i)<1=pure[]|1<2=do{x<-randomRIO(0,length m-1);[i#m,x#m>>=pure.(x:)]!!(m!!i!!x)} f=(0#) ``` [Try it online!](https://tio.run/##bY29DoIwFIX3PsVtWGhSSOuolN3JBMemAwmgjdxCSkkw4rMjqYuD59tOzs@9nh5t32@bxXHwAa7PKbSYV7VrBiQ2wXWaMUVKLSukGmffarPK4qCa4bUUmY@56nxJBe9bdwt3wEyyk96bfEmwLGMnT5cjM5TGIUoX9iadSkXCNuvGOSitJRdccmk4ga@04JEfR/5xIsYQgrV1oKCDuAj7MYzeurB9AA "Haskell – Try It Online") [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 32 ~~34~~ bytes ``` t←⎕ {}{s[?≢s←⍸⍵⊃t]}⍣{~0∊t⊃⍨⎕←⍵}1 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKM97X/Jo7YJj/qmclXXVhdH2z/qXFQMEujd8ah366Ou5pLY2ke9i6vrDB51dJUA@Y96VwAVg1VsrTUEmfA/jetR22QTBZNHvVsMFQwUDBVAJAQawmkw5HrUOxdsHQnq0Z2F7ggk90FdXPuoa5EhAA "APL (Dyalog Unicode) – Try It Online") Takes a nested binary array as input. Outputs each iteration on separate lines. [Answer] # [Python](https://docs.python.org), ~~97~~ 94 bytes ``` f=lambda a,i=0,j=0:sum(a[i])and[i]*a[i][j]+f(a[:],(i,j)[a[i][j]],id(a)**7%~-2**67%len(a))or[i] ``` [Try it online!](https://tio.run/##bYxBCsIwEEXX9hTZCEkcJVFQKPQkYRaRtjilTUtbhW68ek1iLShmJvl5fz7TTeOtdad5LrPaNtfcMguUKagylQ73hltDKKzLvcjwNxXuSu@mCJygEmYxESjnVkh52T73RynPl21dOO@ItveJmZqu7Uc2TENStj2ryRWMXODDMObk0oT50/XkRl7y4mFrHjJCiM1sjAamgPlXIzCjIoUOpH9pacTE@KiO5RXBRI03kIK1vuiT/DdTy9a4Z528t@nvNOIL "Python 3 – Try It Online") --- See [this answer](https://codegolf.stackexchange.com/a/160171/20064) for more explanation about the random number generator: ``` id(a)**7%~-2**67 ``` ]
[Question] [ # Play the Fruit Box Game ## Intro Fruit Box is a game consisting of a 10x17 grid of numbers, each between 1 and 9, where the goal is to clear as many numbers as possible in a two-minute time window. In order to clear numbers, one selects a rectangle aligned with the grid, and if the numbers inside of it sum to 10, they are cleared off the field. At the start of the game, the grid is randomly populated, with the only requirement being that the sum of all numbers in the field is a multiple of 10. Several examples are shown below: [![Starting Field with Possible Clears](https://i.stack.imgur.com/f0pIX.png)](https://i.stack.imgur.com/f0pIX.png) This is an example starting field, with several, but not all, valid possible clears shown. [![In-progress Field with Possible Clears](https://i.stack.imgur.com/x9YJX.png)](https://i.stack.imgur.com/x9YJX.png) This is a field partway through the game, with new possible clears being opened as a result of previous numbers being taken off the field. Notice that, for example, if the 6-3-1 rectangle in the bottom left were cleared, it would open the possibility to clear two 9-1 pairs horizontally which are currently blocked. Perhaps the easiest way to familiarize yourself with the game is to play several rounds, which can be done here: [Fruit Box](https://en.gamesaien.com/game/fruit_box/) ## The Challenge If you haven't guessed by now, the challenge is to write a program which plays the above game as optimally as possible, where optimal means clearing the most numbers. ### Input The input will be the starting grid of numbers. It can be taken in any *reasonable* representation, meaning you can take it in as a string, an array of 10 17-length integers, a 2D array of 170 integers, or any other similar form. Use your best judgement as to what *reasonable* means, but in the spirit of the challenge, it should be some representation of the starting grid of numbers. Please specify in your answer exactly how input should be passed. ### Output The output should be the final score achieved (numbers cleared), as well as the list of moves to achieve this score. Again, the exact form of this output is up to you, but it should be such that given the list of moves, one can unambiguously replay the game from the same starting configuration to end up at the given final score. For example, one could output the top left and bottom right coordinate of each rectangle cleared in order. Beyond the above, the normal input/output rules, as well as forbidden loopholes apply. If you are unsure about any of the specifications, leave a comment and I will clarify. ## Scoring The score on a particular board is given by how many numbers are cleared over the course of the game. For example, if there are 14 numbers left at the end of the game, regardless of their values, the final score will be 170-14 = 156. Since each starting board will have a different optimal score, all answers will be run on the same set of 10 boards for evaluation, which I will keep hidden. At the bottom of this post, I will maintain a leaderboard of the current top submissions, based on their average performance across these 10 boards. The answer which is at the top of the leaderboard one month after the first submission will be accepted. Edit: If the algorithm is not deterministic, the average-of-5 will be used for each of the 10 boards. ## Other Rules * Since the original game gives you 2 minutes, the submission must run in under 2 minutes on my machine (a 4 core, 2017 MacBook Pro with 16GB of RAM). A small amount of leeway will be given to account for typical variations. * You must use a language which is free to use and can be found online. (This should not disqualify any typically-used languages) # Leaderboard ## One month has passed, and the leaderboard is now closed. Congratulations to dingledooper for taking the win! 1. [dingledooper](https://codegolf.stackexchange.com/a/240596/49311): **147.2 Points** 2. [M Virts](https://codegolf.stackexchange.com/a/240583/49311): **129.0 Points** 3. [Luis Mendo](https://codegolf.stackexchange.com/a/240563/49311): **126.0 Points** 4. [Ajax1234](https://codegolf.stackexchange.com/a/240553/49311): **119.6 Points** 5. [Richard Neumann](https://codegolf.stackexchange.com/a/240566/49311): **118.0 Points** ### Example Boards Here are 3 valid example boards. Each board also includes the score achieved by naively clearing rectangles in order until none remain, as a lower bound on the possible score. ``` Board 1: Optimal Score >= 104 --------------------------------- 7 8 3 8 4 4 3 1 4 5 3 2 7 7 4 6 7 6 4 3 3 3 7 1 5 1 9 2 3 4 5 5 4 6 9 7 5 5 4 2 2 9 1 9 1 1 1 7 2 2 4 3 3 7 5 5 8 9 3 6 8 5 3 5 3 2 8 7 7 3 5 8 7 8 6 3 5 6 8 9 9 9 8 5 3 5 8 3 9 9 7 6 7 3 6 9 1 6 8 3 2 5 4 9 5 7 7 5 7 8 4 4 4 2 9 8 7 3 5 8 2 1 7 9 1 7 9 6 5 4 1 3 7 6 9 6 2 3 5 6 5 6 3 9 6 6 3 6 9 7 8 8 1 1 8 5 2 2 3 1 9 3 3 3 3 7 8 7 4 8 Board 2: Optimal Score >= 113 --------------------------------- 5 4 3 6 7 2 3 5 1 2 8 6 2 3 8 1 7 3 8 7 5 4 6 6 1 6 5 7 5 4 3 8 8 1 7 9 9 3 1 7 1 8 9 1 8 4 9 8 7 1 7 5 4 6 3 1 3 1 5 4 7 4 1 5 8 1 1 5 3 3 4 3 8 7 6 5 8 6 3 2 8 4 6 6 6 7 2 2 8 9 9 7 7 7 7 3 9 1 2 7 2 4 4 1 1 5 7 7 9 2 3 6 9 2 7 5 7 7 1 9 6 7 1 7 9 8 7 3 2 8 9 8 6 1 6 8 1 3 9 6 4 5 5 3 4 9 4 1 9 2 6 9 1 6 9 6 3 1 5 8 2 3 5 4 2 6 4 5 3 5 Board 3: Optimal Score >= 116 --------------------------------- 9 2 2 7 6 6 1 7 1 9 7 6 9 3 8 8 3 2 2 4 8 6 9 8 4 8 3 8 1 1 2 7 4 9 8 5 1 8 9 5 5 1 7 7 5 1 3 4 6 5 1 5 2 9 2 2 1 7 5 4 5 9 5 6 4 2 9 7 4 9 6 3 6 2 3 9 2 1 2 8 8 7 9 4 7 1 9 7 2 2 2 6 2 1 2 5 6 2 5 6 7 8 8 8 4 4 9 5 7 2 3 8 2 4 8 1 4 7 3 9 4 7 2 3 7 2 8 4 6 9 8 3 8 5 2 9 4 8 1 3 9 1 6 6 6 7 2 1 4 5 2 6 2 3 7 3 8 1 2 1 8 1 8 3 3 2 3 2 7 4 ``` [Answer] # [C++ (gcc)](https://gcc.gnu.org/) Performs a brute force search. Its strategy is to greedily choose rectangles that yield the least amount of points. Although counter-intuitive, this strategy is seemingly effective. To give the search more variation, the branch size is also limited to 4. Memoization is used to prevent the same board state from re-occurring (due to applying the same operations in a different order). As for calculating the rectangle sums, a two-pointer approach is taken to remove a linear factor from the time complexity. It outputs a chain of length-4 tuples `(r0,c0,r1,c1)`, where `r0,c0` and `r1,c1` are the top-left and bottom-right row-column coordinates. Compiled with `g++ -std=c++17 -O2`. ``` #include <chrono> #include <iostream> #include <ext/pb_ds/assoc_container.hpp> constexpr int ROWS = 10, COLS = 17; // Program auto-exits by default after two minutes constexpr int TIMEOUT = 120; using Grid = std::array<std::array<int, COLS + 1>, ROWS + 1>; struct Move { int cleared = 256, r0, c0, r1, c1; }; struct Sol { int score = 0; std::vector<Move> moves; Grid grid; }; __gnu_pbds::gp_hash_table<long long, __gnu_pbds::null_type> cache; std::vector<Move> moves; const auto start = std::chrono::system_clock::now(); long long get_hash(Grid &grid) { long long hsh = 0; for (int r = 1; r <= ROWS; r++) for (int c = 1; c <= COLS; c++) hsh = hsh * 33 + grid[r][c] + 1; return hsh; } void print_solution(Sol &sol) { std::cout << sol.score << ": "; bool begin = true; for (auto &[_, r0, c0, r1, c1] : sol.moves) { if (!begin) std::cout << " -> "; begin = false; std::cout << "(" << r0 << ',' << c0 << ',' << r1 << ',' << c1 << ")"; } std::cout << "\n"; } void search(Grid grid, Sol &sol, int score = 0) { const auto now = std::chrono::system_clock::now(); if (std::chrono::duration<double>(now - start).count() > TIMEOUT) { std::cout << TIMEOUT << " seconds elapsed. Exiting...\n"; print_solution(sol); exit(EXIT_SUCCESS); } const long long hsh = get_hash(grid); if (cache.find(hsh) != cache.end()) return; cache.insert(hsh); if (score > sol.score) sol = {score, moves, grid}; Grid csum; for (int c = 1; c <= COLS; c++) csum[0][c] = 0; for (int r = 1; r <= ROWS; r++) for (int c = 1; c <= COLS; c++) csum[r][c] = csum[r - 1][c] + grid[r][c]; Move mv0, mv1, mv2, mv3; for (int r0 = 1; r0 <= ROWS; r0++) { const auto &p0 = csum[r0 - 1]; for (int r1 = r0; r1 <= ROWS; r1++) { const auto &p1 = csum[r1]; int sum = 0; for (int c0 = 1, c1 = 0; c0 <= COLS; c0++) { while (c1 < COLS && sum < 10) ++c1, sum += p1[c1] - p0[c1]; if (sum == 10) { int cleared = 0; for (int r = r0; r <= r1; r++) for (int c = c0; c <= c1; c++) cleared += grid[r][c] != 0; if (cleared < mv0.cleared) mv3 = mv2, mv2 = mv1, mv1 = mv0, mv0 = {cleared, r0, c0, r1, c1}; else if (cleared < mv1.cleared) mv3 = mv2, mv2 = mv1, mv1 = {cleared, r0, c0, r1, c1}; else if (cleared < mv2.cleared) mv3 = mv2, mv2 = {cleared, r0, c0, r1, c1}; else if (cleared < mv3.cleared) mv3 = {cleared, r0, c0, r1, c1}; } sum -= p1[c0] - p0[c0]; } } } for (const auto &m : {mv0, mv1, mv2, mv3}) { const auto &[cleared, r0, c0, r1, c1] = m; if (cleared == 256) break; auto ngrid = grid; for (int r = r0; r <= r1; r++) for (int c = c0; c <= c1; c++) ngrid[r][c] = 0; moves.push_back(m); search(ngrid, sol, score + cleared); moves.pop_back(); } } int main() { // comment out this line to input via STDIN freopen("input.txt", "r", stdin); Grid grid; for (int r = 1; r <= ROWS; r++) for (int c = 1; c <= COLS; c++) std::cin >> grid[r][c]; Sol sol; search(grid, sol); auto end = std::chrono::system_clock::now(); print_solution(sol); std::cout << "Time elapsed: " << std::chrono::duration<double>(end - start).count() << "s\n"; return 0; } ``` [Try it online!](https://tio.run/##tVdtb9pIEP7uXzHhpNQ@CLEhBAKEL210inS9nC6p7qRchMyygBW/ab1OE0X89tzMrI0NJFXba7FY78u8PDM7szsWaXq0FOLl5ZcgFmE@lzAWK5XEycSqZoIk00r6UX1OPurjdDadZ8d@liViKpJY@0EsVXuVphPLwnGm5WOqIIg1/HX19zWcg@e24P3V79ztjyzr@Bj@VMlS@RH4uU6O5GOgM5g9wVwu/DzU4C@0VKA/JxAFca5lBnavB4tEwc3llbOj5Oby48XVpxsU3uuh8DwL4iX8poI5zmR6Phz6SvlP41oXuQpATfAmLQOTusiOJudCw8fkQcIzyxeh9JUkaZ3eaQsUGiPwrzx8eyNYV0zXSQjPFuCP@DKRKIlc7oinWP@DFDpRY5I@gQjbzCwy3CU2I4vkTafLOJ@ms3k2HC7T6crPVlPtz0I5DhM0jpoW1IniPAyn@ilFqcIXKzmy3lRnvMeOR0y@0qWbTAAMh9kTOjeaijAR9yg5@Ww7yLVRDEupGZHNoA8JtVOYXRGtslVlOm2cTS5RFAEjfI3P2enYbTYdptmiE4ZOEB3tE3brdPQzCqj9Fbpd3D3CcavubsUdbaVRrKTOVUxU6FfLekgQcKpQwzRLwlwHSWzTnh3iqDTBuCLJNYzHgPNts404aAyhYcTOEmSayWUQIwTcelkzk/16eDvdDZQ7GLI43oVSGYfKAuwDFuZsK2/A0aTUyFoLhQs/zGQ1vc1jN@ilXGrftd7RS9QHyquv8KDhFErW@w5o/Bs3KtdlmAii2HdydwtK77W2I760rxZqGEdfFWilS7Yo57nyabfG8yTHLJjYJO3IhK/TRrCxth2YlEdB3b1b5pRHBXs3kwhvnoEM/TST8zZc4DGEZ0e73WarSwk7AUOxUi3S0WVf/HN5M73@9P79xfW1U/qy5oDdtNhkEOdOZTOnbnsRxHMbCR04ODfZ3JY441Txb8La8BmCIM6k0sw1siof8n5MqjCuROAUAnnm2ZY5Glq8p@uCnzdZZHm0k8KvpyZT3rqcfT817VmPKvSYAQaCV6R9dQYUVvAxHj1gFkYPHjUdarq7@NwCoFtD6JJZVRzVQvkwdTfKXdY@2rcFE@0chYw44zZCvW2he4K9jWCvNGFzTlCC5VHl3n33sRl02DARJ/7Gke6@Zvp9XgWhxMhDkOZGPDxkLWO8tJ09avo1mwJ1EE3zHFLvlo62I0hd6uxA3sQhwaYy4DUEpW3VNbtj375rS8@SecrbiaY32Si6hFuEF93c4ktsvDUFJDS0drscMMLX7aAkLpjGFHftYvS2HoxGxFUEZoe7HKgedzlwaVufC0G718r6dV9JvCL20Hj/D82PgND5Dgg/Qm/3a/V@g7L13gzF@ZFJCrdMCvdum7PiWtcvCo7S@lEQYb3wvH9yrd86k27fAE7nZDSyXovQc65oHZhhkX9fi2hzXy9NBW2K0u/IwW/Mu7iWYdsJxpdTO82xBp754t6OatdvUZHEphrhQsRces0yeWvEhaAkNXI2NzVuAeGM8DvGLt2LnygiiSKJ81Q76FWQQYjfOYCuCeIUpx4CH65vPlz@UdIvlExSGdsNXm/rR91oQUNhgzUIVnf1i7Xy6s@4JE3Ng8XiZLJ/JVLJho4qPkqM/zbuK0FyCGDV8dUl25tF0nY5eRNEsiy4sJzmGvuLhR5h2Cv0SFLGNVq9yseYWb@8nEEHnz6c4uPh24MzHp1BFwb4dC1aP8EezQ24RysePsR3AmfWAHo4GuB6j3t9fOjdxdVT6lk9pDWaPF47wT9Rn2KPVvoWysFRF/8dbM@YssMI@jg6QQqDrMPPabHe4x61fRhYA8Z3wpL7LGdQYPdIAtrCknilz9JPCquIkjFahpoQeOyTU6b0GDHrtYjXeKDDVnvM32Wp7JH/AA) [Answer] # Python3, 659 bytes: ``` from time import* r,l=range,len s=lambda v:[(t,x,y)for x in r(l(v))for y in r(x+1,l(v)+1)if(t:=sum(v[x:y]))<=10 and any(v[x:y])] def f(b,p=[]): u=[] for x in r(l(b)): for q,w,e in s(b[x]): if q==10:u+=[(x,x+1,w,e)] elif n:=next((y for y in r(l(b)+1)if y>x and sum(sum(m[w:e])for m in b[x:y])==10),0):u+=[(x,n,w,e)] for g in sorted(u,key=lambda x:(x[1]-x[0])*(x[3]-x[2])): yield from f(b[:g[0]]+[d[:g[2]]+([0]*(g[3]-g[2]))+d[g[3]:] for d in b[g[0]:g[1]]]+b[g[1]:],p+[g]) if not u: yield sum(sum(not i for i in j)for j in b),p def e(b,s=120): t,r,w=time(),[],f(b) while time()-t<s and(n:=next(w,0)):r.append(n) return max(r,key=lambda x:x[0]) ``` [Try it online!](https://tio.run/##VVPbcpswEH2uvmInL5GMkjFgG8yEfkJ/QGU6MAiHlFsEjuHr3d3FTprRCPZy9uzRCoZleu27MB7c9Vq5voWpbi3U7dC7aSOcblKXdyerG9uJMW3ytihz@EiMnPSsF1X1DmaoO3CykR@K/WX1Z8/XFPN8VVdyStLx3MoPMydLptRL6m8h70rcyz2YidJWUMlCD6nJVCLgjG8B33oUihIce9cXbSk@ysLMXABQV/CeInly9lIjZ00qEIbkmLQNprsk7ew8SbnAf2qJmZXC8nNmZSSXdmsuic34ZC1hi1UtNVF6q@6NunsbAp5YFo7QlvKs/9rlPrk5kbPxs6fZbDO1QTskO8jWUy21bUrga8AxmOSEqMwzJVkBWhL9jTxR0YmLvNKQl2TctVzlURUW@BlWkOdjXg@eOWVK0Hy6foLzV7v7OSlcM09NPG984jemVHrgu7F4N2O635LYSTt9SelrkUqbTKNgpL@81o2FNfo0vYw0SXmf@AXHpRL3nA@DpTDinZ3OroM2n6X7Piee0HX9EBEmij53Zfrw8HCEAFcEB1w@vn04sneEEGJcoaD8Di2KxWxRxsdFdTs4ihj26MWY37MV4aJ3iNkDWWKP2LWTz7kdbkIf0KJMJJAHvRB3gM8jIwNWEKG3Q8SqLOB1uOX3bNEzgljErG/HzBHzxDftPjHgWZiJMxGz726nIiRrFCuaFPg8kwMjfVbMfQXVrhMI@NQ@14fMyhPBqfL9Tv0fHrMc8YZ/3O7GmE2bD7LuJo338FzVXZk3jXz8XXqPGmqlss9vpqqbyTr5q@@shvF5HJp6QmD3iCAhCki/OvBTicEhr7T0W1//AQ) (with a 50 second maximum time limit) ### Input This solution takes in a list of lists with the integers representing the board (i.e `[[9, 2, 2, 7, 6, 6, 1, 7, 1, 9, 7, 6, 9, 3, 8, 8, 3], ..., [3, 7, 3, 8, 1, 2, 1, 8, 1, 8, 3, 3, 2, 3, 2, 7, 4]]` for the last example). In the TIO link, I have included in the footer a Python function to convert a string representation of the board to the required list of lists (see `to_board`). The input is passed to the function `e`, along with an optional time limit, set to the maximum for this challenge (two minutes). After running for the maximum period of time, or until all possible boards have been produced, the optimal result is returned. ### Output `e` returns a tuple containing the score (the first element), and the path to produce the score. The path contains each move (the area of the input that sums to 10), which is represented as a tuple. The first two elements form the vertical range, and the last two elements comprise the horizontal range. For example, the move `(0, 1, 8, 10)` selects the `1` and `9` from the first row of the input board (rows `0` to `1`, noninclusive, with indices `8` to `10`, noninclusive). ### Note The use of the time limit is solely to produce as high a score as possible. Without a time limit, the maximum score of the first `100` iterations of the generator will still result in a value above the optimal cutoff. [Answer] # [Octave](https://www.gnu.org/software/octave/). Purely random approach This applies moves randomly until no further moves are possible. Then tries a new sequence of moves until a time limit is reached. The best sequence of moves is chosen output. Pseudo-code: 1. Generate all possible rectangle sizes. 2. Permute the list of rectangle sizes randomly with uniform distribution. Set `s` to `0`. 3. Increase `s`. If `s` exceeds the number of possible rectangle sizes (no further moves are possible): compute score and go to step **6**. Else: continue normally. 4. Perform 2D convolution with the `s`-th size. This computes all sums in a sliding rectangle of that size. 5. If there are sums that equal `10`: choose one randomly with uniform distribution. Set the corresponding entries in the board to `0`, store the move, and go to step **2**. Else: go to step **3**. 6. If the current score is better than the best so far: update best score and list of moves. 7. If time allows: go to step **2** (to try a new sequence of moves). Else: output best score and list of moves. The code is a function that takes the board and time limit as inputs, and produces the score and sequence of moves as outputs (a third, optional output gives the number of tries). The board is defined as an Octave matrix. The sequence of moves is a 4-column matrix, ``` [ up1 down1 left1 right1 up2 down2 left2 right2 ··· ] ``` `up1` to `down1` is the 1-based, inclusive range that defines the vertical span of the first rectangle in matrix coordinates; and similarly `left1` and `right1` define its horizontal span. `up2` etc refer to the second move, and so on. ``` function [score, moves, num_tries] = fruit_box(board_input, time_limit) tic % start timer target_sum = 10; sizes_rect = {[], []}; [sizes_rect{:}] = ndgrid(1:size(board_input, 1), 1:size(board_input, 2)); sizes_rect = reshape(cat(3, sizes_rect{:}), [], 2).'; % each column defines a rectangle size sizes_rect = sizes_rect(:, 2:end); % remove first column: [1; 1], which never gives a valid move score = 0; moves = []; num_tries = 0; while toc < time_limit num_tries = num_tries + 1; board_try = board_input; % initiallize board for current try moves_try = []; % initiallize moves for current try done = false; while ~done done = true; for size_rect = sizes_rect(:,randperm(end)) sums = conv2(board_try, ones(size_rect.'), 'valid'); [up, left] = find(sums==target_sum); if up % at least one move is possible ind = randi(numel(up)); moves_try(end+1, :) = [up(ind) up(ind)+size_rect(1)-1 left(ind) left(ind)+size_rect(2)-1]; % store move board_try(moves_try(end,1):moves_try(end,2), moves_try(end,3):moves_try(end,4)) = 0; % set to zero done = false; % further moves may be possible in current try break end end end score_try = nnz(board_try==0); % the score is the number of zeros if score_try > score % update solution if better score = score_try; moves = moves_try; end end ``` [**Try it online!**](https://tio.run/##fVbrbpswFP7vp/CfqlhlVU1ubVj2IlEVOWASa2CQbbK11fbq3bFJySFuhxRjzuU7t8@EtnDiJN/fq14XTrWabm3RGpnSpj1Jm1LdNztnlLTPdEMr0yu327e/k30rTLlTuutdSp1q5K5WjXKMEKcKekOtE8YFhQGRMAfpdrZvAIM/5IRY9SrtzsjCgeRt@5zS7fOfnGwv8rf1Hx9RlwejyoSvvWYalTP4fSLPGMunAYy0R9HJpBAumaV0EoT50N7p/jaHvKUojrRo677RtJSV0tJSQb2t0IdaBt8p@OUhWQPOWuqSeSQjfQdppYx1Z8Q13fKccgj366ggjpYnaehBnUKQk6hVGdoO/fEzAHDoVZgDbLfPORmHMagABVJybUG/oxkQChe2vOzvKM@DemiYMy@gRs3zeSutnBJ1DWUNKlq1hha9MVLDRM1LAAhZnQEgsyu/IefP/MpW@7oqUVs5pDIU8dcrwjOycqY/G/nLw/lmf9p4I3TZSdMkvv1s9PEX0M53oWj1KUvGwlMKMWwyAt7fAhNuwwxuWT4B2PZdSmtZuXAElC4TD7nZXGh95aAq2nfQEuHATcD4fTmBDcrSrrVW7Ws58QheuvRchUJUAiOTddJ37Ap50npf6x1P6Zr5IfRdAgiMnu93Y2UJZ994yH8wGHfIJAOTMEXrPPECCa/jjq1LJhmknK2ngoyl0yTT2bXJnLFAYR9RAjta@ipNG4WcsAVsq964IxyZgV@NeKF7OTYUGhjRbZK/keLnRAqZkOv9xz2cwDPBtX69EGezeQjnGxIZjPxQ/QPMbA@5tVWoxZIzEy5AP872NzCjUjhwh7dCeOeC2V46B@/KkbTnF8DofeHBxwth7Gg@Jv7xIzdwEYJOtmfIgPAU1gytq7Au0cqRnCMvbDlIZmF9ROuMRAHmSI2dHyMthuNoxYkO9k8EmS6Q6SMKsIi0K7Ri@QxBL7GWoIfsiwbyCHSO9jiVJdJitBXBpSHTGdpnSPIUhc@iSayQ5RyHiUeaRevyiwCLSIslA9ojiXKZR/UtovB4@DFxOK4DM@0pUmC4VdSc@Rc8nEWEyjDT4lzwJHh0hpZReB5RY9JqEmUdn4YsIjqPKphFPZieHviOIJOPvP982S0W8AdUKtslwYEN@@DF3t//AQ) (with 55-second limit). [Answer] # [Python](https://www.python.org), 2013 bytes Uses numpy and ffts to generate moves by convolution, then starts a depth first search of all possible moves, with a timeout to limit the search (definitely not terminating any time soon without that). Caches move generation and step results based on the input board. Prefers small moves first to knock out large numbers. I also tried random weights but it doesn't seem to do well consistently. I'm using a list of rows (lists) as input, should also work with tuples and other iterables. ``` import time import random import numpy as np import sys sys.setrecursionlimit(10000) def go(b): timeout=115 # seconds, set to 5 on ATO r = len(b) c = len(b[0]) fftshape = (2*r,2*c) shapes = [(i,j) for i in range(1,r) for j in range(1,c) if i*j!=1] kernels = [np.ones(s) for s in shapes] ffts = np.stack([np.conj(np.fft.fft2(k,fftshape)) for k in kernels],axis=2) def _getmoves(b): ba = np.asarray(b) kres = np.real(np.fft.ifft2(((np.fft.fft2(ba,fftshape)[:,:,np.newaxis]*ffts)),axes=(0,1))) res = [kres[:,:,i] for i in range(kres.shape[2])] ix = [np.argwhere(np.all(np.stack((r>9.5,r<10.5),axis=2),axis=2)) for r in res] moves = [((i[0],i[0]+s[0]),(i[1],i[1]+s[1])) for s,ix in zip(shapes,ix) for i in ix if i[0]+s[0] <= ba.shape[0] and i[1]+s[1] <= ba.shape[1] ] return moves movec = {} def getmoves(b): if b not in movec: movec[b] = _getmoves(b) # print("miss") return movec[b] def _step(b): nonlocal timeout nonlocal start_time moves = getmoves(b) ba = np.asarray(b) if moves and not time.time() - start_time > timeout: rl=[] best=(0,) for m in sorted(moves,key=lambda m:(m[0][1]-m[0][0])*(m[1][1]-m[1][0])): bac = ba.copy() bac[m[0][0]:m[0][1],m[1][0]:m[1][1]]=0; score,bar,ml=step((*map(tuple,bac.tolist()),)); if score > best[0]: best = (score,bar,[m]+ml) return best else: score = (ba.shape[0]*ba.shape[1])-(ba>0).sum() return score,ba,[] stepc = {} def step(b): if b not in stepc: stepc[b] = _step(b) return stepc[b] start_time = time.time() score,baf,movelist = step((*map(tuple,b),)) print(f"Score: {score}") print(movelist) print(baf) return score,movelist,baf ``` [Attempt This Online!](https://ato.pxeger.com/run?1=hVZLjuM2EEVWAXQKxrOhPGzDkv_OqC-RpSMMZJl2s60fSDrTzmBOks1kkRwqQO6SqiJpy3YDkSCJrM-rx6oi7T_-7s72pW2-f__rZPdPy39-_FfVXasts6qWkR_rotm1dZg1p7o7s8KwpgsiczYRPCMjrZblSRvVNpWqleXJGK44inZyzw4t38briMGF6O3JZjP2gRlZts3OCNZVsjAS5hC9ZUkyY_tWMyuNVc2B3OilWcYq2QAWTcsw3Yzz-Gq131vzUnQStDwdapEOS6clqQHxhivxGlMMxVSDqzxIngjtZK99WRkztWdq-PpTluQEc5S6kRXhNN2obaThxjkadHRR8gsVsAMzY4vyyNEBlvzK4Qs6fFJ-FIFx7GCOCOOj5KJ4UyZLIZGXBWJGPx-krdvfIHZILF7bwkUrTKF1cQ6JItZaeipaFlUgoIgBv-GzLa6ENmuxFqBs5BfkkQ9RE8dASpqMj0USx9cQLsIGI5Gfyu9TjKoRIW_SPM4vnurNZ7PQhy8vUkskVFRE02WO6-fVaCb0p2Q8msUhKeHr8qYpUMg9XpQhKjhX0CQCXx8NtosAQYKCBAVJ7iGMACqA8rvquCskCHqdglrohgDDPmWQc78imMJuYRfIGyVM816i7Ek3jp2rKw6xnb9-u1T43QJD8C1rWotcyOequsBstjkg9RuEbD5crDqtGssHtTJm4PvqjhVhQLdd281Y2d0waWCft2VRhQ39qIDCafuZTpP7etxz-5_ehVU7T8wvrh5BR_jiMXvqBWLsOfC5TYyusk1-I9nC4YIdHN9IsdA17WI43OSOU1hxlOesKurtrmD1mtdQaajnE32hlYYgSbwkIUl8G9ytDssL7VC23ZnH7-k3HnDtAwgPt_bweTb--cHPlK2WYltoUVcZFYkP66Lj9gRnKsjLkW0rZSyHTRvHj_6QWoKAxGFGMNyDTUgXHqjXeJs6_1hXtyvxLUTGzJ9WeMFBJm9xXVAA7G2fYW-3xE-geR7HI3Oq-btBAhMBhXXHO6z-bg89dG1__5D9HSsU-f3jfe-3RzC5Hse99sv6nRn167MX2EpYCTB6rBMWh-zd3twPfkG_NftK_t8GfWUA6ssggJveJCdYYnz_K__Dn1v81cSOwPC-q9_WVxHAibeR6Sr4DR-wARzwYjAYrFgK94LN4U7gm7AVzVZswpZwTyLUT2GEsiWNUJPAjX5TtoqWbAazJehnNFrAjd8JaOc4imZg6yIlpJvCg9ZzGKFmEQEOzCbwpPBekWVKDBYwm4KFY5bSPff6GY3wvWDLaEn8poS8IJyl554gAqyFkEizIPSpXxVaEsfIWSODhHIyJ8uEGFPcCH1dBlJadUL-E0KljEBWQ5p_bTDPUUT_k1ylwv-y_wA) [Answer] # C++ ``` #include <algorithm> using std::sort; #include <functional> using std::reference_wrapper; #include <initializer_list> using std::initializer_list; #include <iostream> using std::cout; using std::ostream; #include <numeric> using std::accumulate; #include <vector> using std::vector; struct Cell { unsigned short number; explicit Cell(unsigned short number) : number(number) { } friend unsigned short operator+(unsigned short lhs, Cell const & cell) { return lhs + cell.number; } friend ostream & operator<<(ostream & out, Cell const & cell) { out << cell.number; return out; } }; struct Point { size_t x, y; Point(size_t x, size_t y) : x(x), y(y) { } friend ostream & operator<<(ostream & out, Point const & point) { out << point.x << "x" << point.y; return out; } }; struct Frame { Point start, end; Frame(Point start, Point end) : start(start), end(end) { } friend ostream & operator<<(ostream & out, Frame const & step) { out << step.start << " -> " << step.end; return out; } }; struct Result { vector<Frame> steps; unsigned short score; Result(vector<Frame> const & steps, unsigned short score) : steps(steps), score(score) { } friend ostream & operator<<(ostream & out, Result const & result) { for (auto const & step : result.steps) out << step << "\n"; out << "Score: " << result.score; return out; } }; auto sum(vector<reference_wrapper<Cell>> const & selection) { return accumulate(selection.begin(), selection.end(), 0); } auto getWeight(vector<reference_wrapper<Cell>> const & selection) { unsigned int weight = 0; for (Cell const & cell : selection) weight += cell.number << cell.number; return weight / selection.size(); } class Grid { private: vector<vector<Cell>> cells; unsigned short targetValue; public: Grid(initializer_list<initializer_list<unsigned short>> list, unsigned short targetValue) : targetValue(targetValue) { for (auto const & inner : list) { vector<Cell> row; for (auto const & number : inner) row.emplace_back(number); cells.push_back(row); } } Grid(initializer_list<initializer_list<unsigned short>> list) : Grid(list, 10) { } [[nodiscard]] auto size() const { return cells.size() * cells.at(0).size(); } [[nodiscard]] auto startPoints() const { vector<Point> points; for (auto y = 0; y < cells.size(); y++) for (auto x = 0; x < cells.at(y).size(); x++) points.emplace_back(x, y); return points; } [[nodiscard]] auto endPoints(Point const & startPoint) const { vector<Point> points; for (auto y = startPoint.y; y < cells.size(); y++) for (auto x = startPoint.x; x < cells.at(y).size(); x++) points.emplace_back(x, y); return points; } [[nodiscard]] auto getFrames() const { vector<Frame> frames; for (auto const & start : startPoints()) for (auto const & end : endPoints(start)) frames.emplace_back(start, end); return frames; } auto getCells(Frame const & step) { vector<reference_wrapper<Cell>> selection; for (unsigned short y = step.start.y; y <= step.end.y; y++) for (unsigned short x = step.start.x; x <= step.end.x; x++) selection.emplace_back(cells.at(y).at(x)); return selection; } [[nodiscard]] auto filterFrames(vector<Frame> const & frames) { vector<Frame> result; for (auto const & frame : frames) if (sum(getCells(frame)) == targetValue) result.push_back(frame); return result; } [[nodiscard]] unsigned short numbersLeft() const { unsigned short counter = 0; for (auto const & row : cells) for (auto const & cell : row) if (cell.number != 0) counter++; return counter; } void sortFrames(vector<Frame> & frames) { sort(frames.begin(), frames.end(), [this] (Frame const & lhs, Frame const & rhs) { return getWeight(getCells(lhs)) > getWeight(getCells(rhs)); }); } bool reduceCells(vector<reference_wrapper<Cell>> const & selection) { if (sum(selection) == targetValue) { for (Cell & cell : selection) cell.number = 0; return true; } return false; } auto reduce(Frame const & frame) { return reduceCells(getCells(frame)); } friend ostream & operator<<(ostream & out, Grid const & grid) { for (auto const & row : grid.cells) { for (auto const & cell : row) out << cell << " "; out << " \n"; } return out; } }; auto resolve(Grid & grid) { vector<Frame> log, steps; while (true) { auto frames = grid.getFrames(); auto candidates = grid.filterFrames(frames); if (candidates.empty()) break; grid.sortFrames(candidates); auto candidate = candidates.at(0); if (grid.reduce(candidate)) log.push_back(candidate); } return Result(log, grid.size() - grid.numbersLeft()); } int main() { Grid grid1 = { {7, 8, 3, 8, 4, 4, 3, 1, 4, 5, 3, 2, 7, 7, 4, 6, 7}, {6, 4, 3, 3, 3, 7, 1, 5, 1, 9, 2, 3, 4, 5, 5, 4, 6}, {9, 7, 5, 5, 4, 2, 2, 9, 1, 9, 1, 1, 1, 7, 2, 2, 4}, {3, 3, 7, 5, 5, 8, 9, 3, 6, 8, 5, 3, 5, 3, 2, 8, 7}, {7, 3, 5, 8, 7, 8, 6, 3, 5, 6, 8, 9, 9, 9, 8, 5, 3}, {5, 8, 3, 9, 9, 7, 6, 7, 3, 6, 9, 1, 6, 8, 3, 2, 5}, {4, 9, 5, 7, 7, 5, 7, 8, 4, 4, 4, 2, 9, 8, 7, 3, 5}, {8, 2, 1, 7, 9, 1, 7, 9, 6, 5, 4, 1, 3, 7, 6, 9, 6}, {2, 3, 5, 6, 5, 6, 3, 9, 6, 6, 3, 6, 9, 7, 8, 8, 1}, {1, 8, 5, 2, 2, 3, 1, 9, 3, 3, 3, 3, 7, 8, 7, 4, 8} }; Grid grid2 ={ {5, 4, 3, 6, 7, 2, 3, 5, 1, 2, 8, 6, 2, 3, 8, 1, 7}, {3, 8, 7, 5, 4, 6, 6, 1, 6, 5, 7, 5, 4, 3, 8, 8, 1}, {7, 9, 9, 3, 1, 7, 1, 8, 9, 1, 8, 4, 9, 8, 7, 1, 7}, {5, 4, 6, 3, 1, 3, 1, 5, 4, 7, 4, 1, 5, 8, 1, 1, 5}, {3, 3, 4, 3, 8, 7, 6, 5, 8, 6, 3, 2, 8, 4, 6, 6, 6}, {7, 2, 2, 8, 9, 9, 7, 7, 7, 7, 3, 9, 1, 2, 7, 2, 4}, {4, 1, 1, 5, 7, 7, 9, 2, 3, 6, 9, 2, 7, 5, 7, 7, 1}, {9, 6, 7, 1, 7, 9, 8, 7, 3, 2, 8, 9, 8, 6, 1, 6, 8}, {1, 3, 9, 6, 4, 5, 5, 3, 4, 9, 4, 1, 9, 2, 6, 9, 1}, {6, 9, 6, 3, 1, 5, 8, 2, 3, 5, 4, 2, 6, 4, 5, 3, 5} }; Grid grid3 = { {9, 2, 2, 7, 6, 6, 1, 7, 1, 9, 7, 6, 9, 3, 8, 8, 3}, {2, 2, 4, 8, 6, 9, 8, 4, 8, 3, 8, 1, 1, 2, 7, 4, 9}, {8, 5, 1, 8, 9, 5, 5, 1, 7, 7, 5, 1, 3, 4, 6, 5, 1}, {5, 2, 9, 2, 2, 1, 7, 5, 4, 5, 9, 5, 6, 4, 2, 9, 7}, {4, 9, 6, 3, 6, 2, 3, 9, 2, 1, 2, 8, 8, 7, 9, 4, 7}, {1, 9, 7, 2, 2, 2, 6, 2, 1, 2, 5, 6, 2, 5, 6, 7, 8}, {8, 8, 4, 4, 9, 5, 7, 2, 3, 8, 2, 4, 8, 1, 4, 7, 3}, {9, 4, 7, 2, 3, 7, 2, 8, 4, 6, 9, 8, 3, 8, 5, 2, 9}, {4, 8, 1, 3, 9, 1, 6, 6, 6, 7, 2, 1, 4, 5, 2, 6, 2}, {3, 7, 3, 8, 1, 2, 1, 8, 1, 8, 3, 3, 2, 3, 2, 7, 4} }; vector<reference_wrapper<Grid>> grids = {grid1, grid2, grid3}; unsigned short gridNumber = 0; for (auto & grid : grids) { cout << "Grid #" << ++gridNumber << "\n"; auto result = resolve(grid); cout << result << "\n"; cout << grid << "\n"; } } ``` [Try it online](https://tio.run/##xVlZb@NGEn73r2A8wIKKPM6QEnXYsl8CJC/BIsgCm4fJYEBTbZkITQo8xnIG/u2z1VVdzeomZTveBVYgZLK7zq@OLsrZfv8@K9Jy9@3bu7zMim6rgk1a7Ko6b@/ur0@6Ji93QdNuLy6aqm4vT056stuuzNq8KtPCoavVrapVmanPD3W636vaYcrLvM3TIv9L1Z@LvGkdVn/T5ayatlapa1RWdUAlFgyRw1l296rOM4cxzbLuvivSVjmkX1TWVrVDSUtABZK7rA1@VEURfD0J4NOVTb4r1TZo7gCcAPTcoLt6Tx32RZ7lRB@OUk6QUH8uzEooN0jHE4m7rXNVbn2NFcCbgnVTX0Fx15yRpVlVNm3wjyCDBylXf2rVdnWpiYMpEpyzC0PNBliQxEo3m1Asdu0rFAJVsNkMVQljMKCk/qkH/dcqL1sjqIH8@NwGh7Pg0WCNu2G/bu4eJcCH8DABjvDxOLivcZEMYR/3@umIk7h3ftC3p4fTfuXxlS7/VKf3yoglrU2b1mACmGr8RpLQ2aQHIJG@416I3xPkDy3BW3Eg6xiHplX7IzDorXNUjUgE76@DU7uOrrwKjd9U0xWcAVSSG7ThGiU1l2MF2WRVrQxWJCB0WaX9UDBj7C6OQBbiN@CI26EgeiuWxjc2psZHH87bqg7CtGsrx2gwisjPySpL7kUAsf@jPDVgiN3Tf2kHLigoLItwez4waEvT3TOkg76/0e3gWoCsCoUHxuSE3DJy@1YcWpLzG7XLy1CjbJd03sLCh8nlyZNRv1Pt7yrf3bVvN8LGXNfNAwoLroIPBihEfdDWdCr0chgmwzy9kv1t0O6k54bjB@Gkbl0heQjnctMEP9f5FtJgX@dfAKELmf/mD3sIf8bLAIoPgPp3WnQQ1H13A@cSydGyQ//QHRzRG1ccqNKrZ89okTUjlsMByXPpnZclwHeByiaCUgCAngd19SDSelyYOV9BHIp16wQjUj2cq/t9kULq3KTZn3wSe5IR5PN919wRFbBN@kJ5Oum//xtsJX4ohwCPPoz0mY8fy2qbN1labz99CqgoMYfI9/ETn9wwdN@bx7QNP0xsAr6gQjd0PGuaI5pMiJDmmo6@RoDZh@gRyw3@bByzYGU6nRwJ64F4DpYHbH@0tgcHn1N/yAQ3yHqGkCE28LC1z2MA/cgg4A4FPTb/A2R6YTA4/H2QBPvh/40XlD4euy9kjDmab5F0FBcHaB5vOBknL3QCfShfiNjRVDR0n/S77vcD2AgIbLAAgd3WfaoJXx6ZXjrE7DHhw@K1YkocnrtM4lzZkQsXRvPGk3Nw5VAGCTmHI6kjzmwJn0w9@D5MRlAULj6fTbd50araJNT4VEcRmTybZjTxPJtmKAZyRorjT34bhHoGskFGoskkuLoaPxB7d3HS6k8SYhwCwgYeRWP01bL5Rd22R@rMY4BX6BKQFEPPOAxw1AEIGMOXaszMSPpwHDiuEZPz0Xegd0iFZy0ZNp0OQTFbDipfKhiU9I8UozlxLBs0Q2hq3c6cXPs0cH5s7/LmU@DVL75hu0v1XeMPKsbefk61iQL8kCbXY1tajpwq3NP4pqoKkLvtMkXkbxh9XQw4iXsCP309r/qp@Ll5WM5MHG03yQRC8Jan5CA16K5p0ahhcyUcvNBQKY1PPhI4v2jf@rMHjuisfAcPLw@3VEya9pwqagzhV9eU@FmFXrJPPZD5XS/AV8DjKI@94kEDqoovKkQv2b@x9/Ci2p3xyzhuP9zlhQpCHVrpH7VvLDHIB8RAjAaXLl2Wltt8C28@ltZp/KaohbvYXyyTPoDaR38quIHo/Sl4UK5oHT3/UXPAGqEFR2fPCBRq8tOSeoYAZOII6KmcTDSxMT9gIMpkMI3v7@nJ6fv0AqmH0vtUtzSDPoZQU0dgfh@Qr8uzYHUWzPB7jhfcR3iT4H18FizxgpUF3Dyd9cwLZqBriZwJfq@Rc8aCEuKXzGtksHsxXmtmjvha8tZcMluFxL9CnhlauGLLrf0rz@wlb69QxArZaGXBsugysiRzwoARxZJQYeVk@YJpQHkimedIkTCkCeuf8xWzWmOjZF7hNkGyFjcLhjBiUMgQB@1YeJiww8S8EMaTOXBFkjliJGKOasSAy@CvOE9W5m340k29OLj66gA5Z81LlkvJE3NQYk7NyAvhjLUlnJgLRj4R67NRd5YcvBmjGHHYIw6HjYKv2SqcMeARa1tyFBK2OfJCOOOSsPYvmHohstV6tPDMjpnCJp@9Zmx/zHDOvcyL2LYlZ04sIh@LjFx6gK05SDbnbIZac1YiBCsveWyq2WYwY5DnoluY@vE6zFqgTVDZVJkzm@1WyXjmzdymt2YklyJ1lmyJLSCbPTOvkmLKcqZb8eNMxD3mfFh7NZyIdEv40faDiLGhxIi81IsZK9sJEvZ@zYVt28hy2HpsrccclVhU3IrDO/eYLTAxXwvBmfBjwnmy8ny2Lc52P1vZFsuIa2jmpd5cMCzdElkL2A06ns8rhtR25oXoOPagMx55tboUIY05bBHrnLFRJtRO6h2dzHVOwmSus1LPNV/xTKZjPaY/s6fRn3L11j/9UbofFmk8M5OlM1RmPAJiObzDX/unUyHO/oPAmXfo7RN08RSI49/lQKyhGwjhfTTL2YUJ8@Tbt/8A) The algorithm weighs the selections based on their amount of high numbers and size. [Answer] # Rust Uses breadth-first beam search, with a heuristic evaluation based on greedily eliminating as many entries as possible while ignoring newly-created boxes. Solves each board in parallel. You can reduce `beam_size` in `solve` if you need to in order to meet the time budget (I know it should really be a command-line flag). ### `src/main.rs` ``` use fnv::FnvHashMap; use rayon::prelude::*; type Fruit = [[i16; 17]; 10]; type Rect = [u8; 4]; type ClearedMask = [u8; 22]; fn check_entry(mask: &ClearedMask, i: usize, j: usize) -> bool { let k = 17 * i + j; return (mask[k / 8] & (1 << (k % 8))) == 0 } fn remove_entry(mask: &mut ClearedMask, i: usize, j: usize) { let k = 17 * i + j; mask[k / 8] |= 1 << (k % 8); } fn find_rects(output_rects: &mut Vec<(Rect, u8)>, mask: &ClearedMask, fruit: &Fruit, cum_sums: &mut [[i16; 18]; 11]) { for i in 0..11 { cum_sums[i][0] = 0; } for j in 0..18 { cum_sums[0][j] = 0; } for i in 0..10 { for j in 0..17 { cum_sums[i + 1][j + 1] = if check_entry(mask, i, j) {fruit[i][j]} else {0}; } } for i in 0..10 { for j in 0..17 { cum_sums[i + 1][j + 1] += cum_sums[i][j + 1]; } } let mut table = [0u16; 1530]; for i0 in 0..10 { for i1 in i0..10 { let mut s = 0i16; let k = ((i0 << 4) | i1) as u16; for j1 in 0..17 { table[s as usize] = (k << 8) | (j1 as u16); unsafe { s += cum_sums.get_unchecked(i1 + 1).get_unchecked(j1 + 1) - cum_sums.get_unchecked(i0).get_unchecked(j1 + 1); } if s < 10 { continue; } let j0 = unsafe { *table.get_unchecked((s - 10) as usize) as usize }; if (j0 >> 8) as u16 != k { continue; } let j0 = j0 & 255; let r = [i0 as u8, j0 as u8, i1 as u8, j1 as u8]; let mut a = 0; for i2 in i0..=i1 { for j2 in j0..=j1 { if check_entry(mask, i2, j2) { a += 1; } } } output_rects.push((r, a)) } } } } fn heuristic(rects: &Vec<(Rect, u8)>) -> u16 { let mut collision_info = Vec::with_capacity(rects.len()); for _ in 0..rects.len() { collision_info.push((0u128, 0u16)); } let mut s = 0; for idx0 in 0..rects.len() { let [_, j00, i10, j10] = rects[idx0].0; for idx1 in (idx0 + 1)..rects.len() { let [i01, j01, _, j11] = rects[idx1].0; if i01 > i10 { break; } if (j00 <= j11) & (j10 >= j01) { collision_info[idx0].0 |= 1 << idx1; collision_info[idx1].0 |= 1 << idx0; collision_info[idx0].1 += 1; collision_info[idx1].1 += 1; } } } let mut used = 0u128; let mut sort_idx: Vec<(u32, usize)> = (0..rects.len()).map(|i| (((collision_info[i].1 as u32) << 8) | (255 - rects[i].1) as u32, i)).collect(); sort_idx.sort(); for &(_, i) in sort_idx.iter() { if used & (1 << i) != 0 { continue; } used |= collision_info[i].0; s += rects[i].1 as u16; } return s; } fn solve(fruit: &Fruit) -> (Vec<Rect>, u16) { let mut cum_sums = [[0i16; 18]; 11]; let mut output_rects = Vec::new(); let mut heuristic_rects = Vec::new(); let mut queue = Vec::new(); let mut next_queue = Vec::new(); let mut parent_map: FnvHashMap<ClearedMask, (ClearedMask, Rect)> = FnvHashMap::default(); let rng = 18; queue.push((0, 0, rng, [0u8; 22])); let mut max_cleared = 0; let beam_size = 6500; let mut best_mask = [0u8; 22]; while !queue.is_empty() { for (_, cleared, _, mask) in queue.iter() { find_rects(&mut output_rects, &mask, &fruit, &mut cum_sums); for (r, a) in output_rects.iter() { let mut mask1 = mask.clone(); for i in r[0]..=r[2] { for j in r[1]..=r[3] { remove_entry(&mut mask1, i as usize, j as usize); } } if parent_map.contains_key(&mask1) { continue; } parent_map.insert(mask1, (*mask, *r)); let cleared1 = cleared + (*a as u16); find_rects(&mut heuristic_rects, &mask1, &fruit, &mut cum_sums); let h = heuristic(&heuristic_rects); heuristic_rects.clear(); next_queue.push((cleared1 + h, cleared1, rng, mask1)); if cleared1 > max_cleared { max_cleared = cleared1; best_mask = mask1; } } output_rects.clear(); } std::mem::swap(&mut queue, &mut next_queue); if queue.len() > beam_size { queue.sort_by(|p, q| q.cmp(p)); queue.truncate(beam_size); } next_queue.clear(); } let mut moves = Vec::new(); let mut mask = best_mask; while let Some((parent_mask, r)) = parent_map.get(&mask) { moves.push(*r); mask = *parent_mask; } return (moves, max_cleared) } fn main() { let fruit0 = [ [7, 8, 3, 8, 4, 4, 3, 1, 4, 5, 3, 2, 7, 7, 4, 6, 7], [6, 4, 3, 3, 3, 7, 1, 5, 1, 9, 2, 3, 4, 5, 5, 4, 6], [9, 7, 5, 5, 4, 2, 2, 9, 1, 9, 1, 1, 1, 7, 2, 2, 4], [3, 3, 7, 5, 5, 8, 9, 3, 6, 8, 5, 3, 5, 3, 2, 8, 7], [7, 3, 5, 8, 7, 8, 6, 3, 5, 6, 8, 9, 9, 9, 8, 5, 3], [5, 8, 3, 9, 9, 7, 6, 7, 3, 6, 9, 1, 6, 8, 3, 2, 5], [4, 9, 5, 7, 7, 5, 7, 8, 4, 4, 4, 2, 9, 8, 7, 3, 5], [8, 2, 1, 7, 9, 1, 7, 9, 6, 5, 4, 1, 3, 7, 6, 9, 6], [2, 3, 5, 6, 5, 6, 3, 9, 6, 6, 3, 6, 9, 7, 8, 8, 1], [1, 8, 5, 2, 2, 3, 1, 9, 3, 3, 3, 3, 7, 8, 7, 4, 8], ]; let fruit1 = [ [5, 4, 3, 6, 7, 2, 3, 5, 1, 2, 8, 6, 2, 3, 8, 1, 7], [3, 8, 7, 5, 4, 6, 6, 1, 6, 5, 7, 5, 4, 3, 8, 8, 1], [7, 9, 9, 3, 1, 7, 1, 8, 9, 1, 8, 4, 9, 8, 7, 1, 7], [5, 4, 6, 3, 1, 3, 1, 5, 4, 7, 4, 1, 5, 8, 1, 1, 5], [3, 3, 4, 3, 8, 7, 6, 5, 8, 6, 3, 2, 8, 4, 6, 6, 6], [7, 2, 2, 8, 9, 9, 7, 7, 7, 7, 3, 9, 1, 2, 7, 2, 4], [4, 1, 1, 5, 7, 7, 9, 2, 3, 6, 9, 2, 7, 5, 7, 7, 1], [9, 6, 7, 1, 7, 9, 8, 7, 3, 2, 8, 9, 8, 6, 1, 6, 8], [1, 3, 9, 6, 4, 5, 5, 3, 4, 9, 4, 1, 9, 2, 6, 9, 1], [6, 9, 6, 3, 1, 5, 8, 2, 3, 5, 4, 2, 6, 4, 5, 3, 5], ]; let fruit2 = [ [9, 2, 2, 7, 6, 6, 1, 7, 1, 9, 7, 6, 9, 3, 8, 8, 3], [2, 2, 4, 8, 6, 9, 8, 4, 8, 3, 8, 1, 1, 2, 7, 4, 9], [8, 5, 1, 8, 9, 5, 5, 1, 7, 7, 5, 1, 3, 4, 6, 5, 1], [5, 2, 9, 2, 2, 1, 7, 5, 4, 5, 9, 5, 6, 4, 2, 9, 7], [4, 9, 6, 3, 6, 2, 3, 9, 2, 1, 2, 8, 8, 7, 9, 4, 7], [1, 9, 7, 2, 2, 2, 6, 2, 1, 2, 5, 6, 2, 5, 6, 7, 8], [8, 8, 4, 4, 9, 5, 7, 2, 3, 8, 2, 4, 8, 1, 4, 7, 3], [9, 4, 7, 2, 3, 7, 2, 8, 4, 6, 9, 8, 3, 8, 5, 2, 9], [4, 8, 1, 3, 9, 1, 6, 6, 6, 7, 2, 1, 4, 5, 2, 6, 2], [3, 7, 3, 8, 1, 2, 1, 8, 1, 8, 3, 3, 2, 3, 2, 7, 4], ]; let boards = [&fruit0, &fruit1, &fruit2]; let results: Vec<(Vec<Rect>, u16)> = boards.into_par_iter().map(solve).collect(); for (board_index, (fruit, (moves, score))) in boards.iter().zip(results.iter()).enumerate() { println!("Board {:?}: {:?} fruit cleared!\n\n", board_index, score); let mut mask1 = [0; 22]; for r in moves.iter().rev() { for i in r[0]..=r[2] { for j in r[1]..=r[3] { remove_entry(&mut mask1, i as usize, j as usize); } } println!("({:?}, {:?}), ({:?}, {:?})\n\n", r[0], r[1], r[2], r[3]); for i in 0..10 { for j in 0..17 { let s = if check_entry(&mask1, i, j) {fruit[i][j]} else {0}; print!("{:?} ", s); } println!(""); } } } println!(""); for (board_index, (_, score)) in results.iter().enumerate() { println!("Board {:?}: {:?} fruit cleared!\n", board_index, score); } } ``` ### `Cargo.toml` ``` [package] name = "fruitbox" version = "0.1.0" edition = "2018" [dependencies] rayon = "1.5.1" fnv = "1.0.3" ``` ]
[Question] [ # Introduction Cacti come in various different sizes, shapes and colors. However, the most iconic cactus and must-have in every Western has to be the [saguaro](https://en.wikipedia.org/wiki/Saguaro). Important features are its size and arms, which have defined the stereotypical cactus appearance. Your task is to bring the saguaro in the ASCII world. However, -- as in the real world -- no saguaro is like another, so your program has to be able to generate saguaros with varying arm configurations. # An example saguaro > > * Input: `[0b10, 0b11]` (`[2, 3]` in decimal, input length of `2`) > > > ``` _ / \ _ | | / \ | | | | | | \ \_| | \__ | \ | _ | | _ / \ | | / \ | | | | | | \ \_| |_/ / \__ __/ \ / | | | | ``` # Specifications A saguaro always has a base and a top, with variable amounts of stem in between. The stem parts can have no arms, an arm on the right, one on the left or two arms. Saguaro growth patterns are given as an input list containing two-bit values. `00` means no arms, `01` an arm on the right, `10` an arm on the left and `11` two arms (all in binary). The input list's length determines the saguaro's height. Saguaro sections look like the following. Cactus parts are surrounded by octothorps, `#`, for clarity which shall not be printed. A saguaro's height is always equal to `4+6*k` characters for nonnegative integers `k`. ``` ############# # _ # Saguaro top # / \ # ############# # _ | | _ # Stem, both arms #/ \ | | / \# Stem id: 11 #| | | | | |# #\ \_| |_/ /# # \__ __/ # # \ / # ############# # _ | | # Stem, left arm #/ \ | | # Stem id: 10 #| | | | # #\ \_| | # # \__ | # # \ | # ############# # | | _ # Stem, right arm # | | / \# Stem id: 01 # | | | |# # | |_/ /# # | __/ # # | / # ############# # | | # Stem, no arms # | | # Stem id: 00 # | | # # | | # # | | # # | | # ############# # | | # Saguaro base # | | # ############# ``` # Input As previously said, the input consists of a list of two-bit values (`0, 1, 2, 3` in decimal). It can be given in any reasonable format. The list's first element corresponds to the saguaro's highest stem part, the second element to its second highest stem part, etc. If you want, you can require the input list's length as an additional input. Please specify it in your answer if you do so. # Output Your output ASCII saguaro should be built using the exact stem parts as described above. Trailing spaces on a line and trailing new lines are ignored; you may print more, fewer or as many as specified above. # Rules * Standard [loopholes](https://codegolf.meta.stackexchange.com/q/1061/73111) apply * This being [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), a program's byte count should be minimal # Test cases > > * An outlier. Input: `[0b01, 0b00, 0b01, 0b11]` > > > ``` _ / \ | | _ | | / \ | | | | | |_/ / | __/ | / | | | | | | | | | | | | | | _ | | / \ | | | | | |_/ / | __/ | / _ | | _ / \ | | / \ | | | | | | \ \_| |_/ / \__ __/ \ / | | | | ``` --- > > * Alternating arms. Input: `[0b10, 0b01, 0b10]` > > > ``` _ / \ _ | | / \ | | | | | | \ \_| | \__ | \ | | | _ | | / \ | | | | | |_/ / | __/ | / _ | | / \ | | | | | | \ \_| | \__ | \ | | | | | ``` --- > > * An abundance of arms. Input: `[0b11, 0b11]` > > > ``` _ / \ _ | | _ / \ | | / \ | | | | | | \ \_| |_/ / \__ __/ \ / _ | | _ / \ | | / \ | | | | | | \ \_| |_/ / \__ __/ \ / | | | | ``` --- > > * No arms, also known as a spear. Input: `[0b00]` > > > ``` _ / \ | | | | | | | | | | | | | | | | ``` --- > > * No body, some call it a young cactus. Input: `[]` > > > ``` _ / \ | | | | ``` --- [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~50~~ 49 bytes ``` ↘_\¶/F²«J¹¦²Fθ¿﹪÷Iκ⁺¹ι²”{➙∧⊟≕δaL7YF¬⊕ρ↥↖_K”↓⁶↓²‖T ``` [Try it online!](https://tio.run/##VY4xC8IwFIRn@yuOTglUais46KiLglBKx0AoNbXBmGib1sH622Oqi/Ie78Edx3dVU7aVKZVzWSu1JeudeehcnhsbIeSMMR2HdBPUpgVJKZ7B7NBfb4UhSYTUG7OPc6eQNcjRnHplyF7bnRzkSZBt2VlyoREy1XdTRFI65Si@tHAEONMjYkyoEX784zFipsG5v35DCqE6gZ@GEVYT/E/51MlFrURli7bUna92JV58OZcslqmbD@oN "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ↘_\¶/ ``` Draw the top. ``` F²« ``` Loop over each side. ``` J¹¦² ``` Jump to just under the right side of the top. ``` Fθ ``` Loop over each stem part. ``` ¿﹪÷Iκ⁺¹ι² ``` Test whether there is an arm. ``` ”{➙∧⊟≕δaL7YF¬⊕ρ↥↖_K” ``` If so print an arm. ``` ↓⁶ ``` Otherwise just print a vertical line. ``` ↓² ``` After printing the stem, print the base. ``` ‖T ``` Reflect ready to draw the other side. Once both sides are drawn, the sides are then reflected back into their final position. [Answer] # JavaScript (ES6), 210 bytes I spent far too long on another solution before realising there was a better way, which didn't leave me as much time as I would've liked to work on this. ``` a=>` _ / \\`+a.map(([x,y])=>` 1 | | 2 3 5 | | 4 6 7 7 | | 8 8 5 51| |24 4 511${`| `[x]} ${`| `[y]}224 ${`|\\`[x]} `.replace(/\d/g,m=>` _/\\|`[m%2?x*-~m/2:y*m/2])+`|/`[y],s=` | |`).join``+s+s ``` --- ## Try it ``` o.innerText=(f= a=>` _ / \\`+a.map(([x,y])=>` 1 | | 2 3 5 | | 4 6 7 7 | | 8 8 5 51| |24 4 511${"| "[x]} ${"| "[y]}224 ${"|\\"[x]} `.replace(/\d/g,m=>` _/\\|`[m%2?x*-~m/2:y*m/2])+"|/"[y],s=` | |`).join``+s+s )(i.value=["11","10","01","00"]);oninput=_=>o.innerText=f(i.value.split`,`) ``` ``` <input id=i><pre id=o> ``` [Answer] # [Python 2](https://docs.python.org/2/), 189 bytes ``` lambda l:' _\n / \\\n'+'\n'.join((' |',' /|\ _ \ \|\_ __ |||| \\'[j::6])[i/2]+' '+('|','|||| / __ /|/_ _ / \|/'[j::6])[i%2]for i in l for j in range(6))+'\n | |'*2 ``` [Try it online!](https://tio.run/##RU7RCsIwDPyVvEhaN6xW2EPBL1lGmei0Y2ZjzAeh/17T@uA9XC4kd9zy2Z4z2zRcKE3963rrYXIIGZ44DwNExFih0GGcAytV7hFrBBNJHmWTQZF88XmIArFhOzrXdLoNxnYVAlYKs62cze9VIowvESZHmL9nZ7thXiFAYJggyzHLtefHXTVa50aliFTZ27SsgTcYVODlvSmtkzrVcKxB@Ky/ "Python 2 – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~256~~ ~~253...205~~ ~~203~~ 199 bytes ``` r=[(' _',''),('/','\ ')] for a in input()+[0]:r+=zip(*[['|'*6,'_| |_,,/| \/ |\,,|| || ||,,\| _\/_ |/,,\ ____ /,,\/'[i::2].split(',')][2-i&a>0]for i in 0,1]) for l in r[:-4]:print'%5s %s'%l ``` [Try it online!](https://tio.run/##JY7BDgIhDETvfkUva0GrwEY9kOiPACF6MJJsVsKuBw3/vhadtJPXQzOT3/PjOfbLUs5OIDRFJERJAhWDB5RhdX8WuEIaefJrFnLrdLBle/6kLDbOYcXNiTDW9l4jkWLyitkTVeb/EvkK0asIVTFDZEEjhS5Z24f9lIc0C46VwfW7tL5edGjZqWVrMkH@qgztLM7uDsHmksYZu@ME3YTdsCxO34wmfdM/M2zGhC8 "Python 2 – Try It Online") [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 235 bytes ``` param($a)' _ / \' ($a|%{((,'1|'*6),('1| _ 1| / \ 1|2 1|_/ / 1 __/ 1/'),(' _ 2 / \2 | |2 \ \_| | \__ | \ |'),(' _ 2 _ / \2 / \ | |22 \ \_| |_/ / \__ __/ \ /'))[$_]})-replace1,' | '-replace2,' | |' ,' | |'*2 ``` [Try it online!](https://tio.run/##PU9BDgIhDLz3FT2sAQwGwcSz/xBDiCHxsMbNevAgvh2n6G4TOs0wM4Xp8Srz81bGsbUpz/muh2wUSyWS7jgqAlk3b62t8lVtj8ZqDKJAhwAQcJJjR54TkLxTouLEgaAIVBmayDFhIEBiQVTkukolUtQ9VByrpWf/bLLg78QScx7S5WN2c5nGfC3e9sdXVgsTwCBA0XKDH4TW2knvrbfBHswX "PowerShell – Try It Online") PowerShell doesn't have a `map` or `zip` or a real easy way to reverse strings, so we're left with something else -- simple replacements of repeated sections. The first two lines take input as an array of integers and output the top of the cactus. Then we loop through `$a` and select into an array of four strings based on the current value. Those strings are left on the pipeline and then we use our `-replace` to fill in the appropriate spots. We then put the bottom of the cactus onto the pipeline as well. Everything is gathered from the pipeline and an implicit `Write-Output` happens at program completion, inserting a newline between every element. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~76~~ 75 bytes ``` „ _…/ \‚4ú»,v6F'|4ú"_ |/\"•Aö¡Èèj{^ë•5вèJ5ôNè©‚y1›èð'|®∞2äθ‚yÉèJ,}}„| 4úû=, ``` [Try it online!](https://tio.run/##MzBNTDJM/f//UcM8hfhHDcv0FWIeNcwyObzr0G6dMjM39RogUyleoUY/RulRwyLHw9sOLTzccXhFVnXc4dVAAdMLmw6v8DI9vMXv8IpDK4E6Kw0fNew6vOLwBvWaQ@sedcwzOrzk3A6Q@OFOoEKd2lqgRTUKQEMP77bV@f/fyNjAEAA "05AB1E – Try It Online") [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), ~~626~~ ~~566~~ ~~499~~ ~~466~~ ~~398~~ ~~312~~ ~~310~~ 308 bytes Can be golfed a tonne ``` a->{String r=" |,",g=" |",n=" _, / \\,";boolean j,k;for(int e:a)n+=((k=e>1)?" _ |":g)+((j=e%2>0)?" | _,":r)+(k?"/ \\ |":g)+(j?" | / \\,":r)+(k?"| | |":g)+(j?" | | |,":r)+(k?"\\ \\_|":g)+(j?" |_/ /,":r)+(k?" \\__ ":g)+(j?" __/,":r)+(k?" \\":g)+(j?" /,":r);return(n+g+r+g+r).replace(",","\n");} ``` [Try it online!](https://tio.run/##VZFNi4MwEIbv/oohsJCgtftxq6u97W1PPdYiqU0lahOJsUup/nZ3UpXuDuSD95mZhHdKfuUr3QhVnqpRXhptLJSohZ2VdXjuVG6lVuHXfIk8r@mOtcwhr3nbwjeXCu4eYLSWW9SXzE@p7P4QwM4aqYoEFMQw8lVynwQwMYE@IEGBJ0ZPAjXdIAvcvoY0DUh01LoWXEEZVNFZG4pdQWw4U35MaRWL5I1tCWSuwaZgPqVlLF7ek1en9q4X2RiUqy1xDZes8kGnJxbeo/IP9@5/C8XaNM3@8mwN6yd3NIMnhiz7SzHS9EknFBlhO6Oo8gvfuMVCI5qa54ISdIakirBoGF0x@u6O2fvZ6quWJ7jgBOjk6f4A3BQtmwfiYndrrbiEurNhgym2xtdC3jT1jSrxA48Z3T8GxqJHyeAN4y8 "Java (OpenJDK 8) – Try It Online") [Answer] # [SOGL V0.12](https://github.com/dzaima/SOGL), ~~56~~ ~~54~~ 53 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` 5⁷yΙ‚‘∑≡`a#¾‘O.{@.2%i»¹{"⁸G‘6∙;?X"j1>ζ╔²i[n¹‘5n}┼±↔}O ``` [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=NSV1MjA3N3kldTAzOTkldTIwMUEldTIwMTgldTIyMTEldTIyNjElNjBhJTIzJUJFJXUyMDE4Ty4lN0JALjIlMjVpJUJCJUI5JTdCJTIyJXUyMDc4RyV1MjAxODYldTIyMTklM0IlM0ZYJTIyajElM0UldTAzQjYldTI1NTQlQjJpJTVCbiVCOSV1MjAxODVuJTdEJXUyNTNDJUIxJXUyMTk0JTdETw__,inputs=NCUwQTAlMEExJTBBMiUwQTM_) Explanation: ``` ..‘ push the ending part - " | |\n | |" ..‘O output the starting part - " _ \n / \" .{ input times do @ push a space .2% push input%2 i» push floor(prevInput/2) ¹ wrap the two in an array { } for each of the two numbers "..‘ push "| " - base stem 6∙ multiply vertically 6 times ;? } if the current item iterating over is truthy (i.e. != 0) X remove ToS - the regular stem - from the stack "..‘ push "| _ | / \| | ||_/ / __/ / " - stem with an arm 5n split it into line lengths of 5 ┼ add that horizontally to the space pushed earlier (or whatever it's become) ±↔ reverse ToS - the stem currently - horizontally O output the array of the current part ``` ]
[Question] [ Write a program or function that given an integer radius *r* returns the number of unit squares the circle with radius *r* centered at the origin passes through. If the circle passes exactly through a point on the grid that does not count as passing through the adjacent unit squares. Here's an illustration for *r = 5*: [![illustration](https://i.stack.imgur.com/dX9ge.png)](https://i.stack.imgur.com/dX9ge.png) Illustration by Kival Ngaokrajang, found on OEIS Examples: > > 0 → 0 > > 1 → 4 > > 4 → 28 > > 5 → 28 > > 49 → 388 > > 50 → 380 > > 325 → 2540 > > 5524 → 44180 > > 5525 → 44020 > > > [Answer] # [Python 2](https://docs.python.org/2/), 54 bytes ``` f=lambda r,x=0:r-x and-~((r*r-x*x)**.5%1>0)*4+f(r,x+1) ``` [Try it online!](https://tio.run/nexus/python2#DYpBCoMwEEXX9RR/IyTjWBJrFhX0LikSEHRahi6y6tXT2fzHe/xW1jNfrz1Dua5h0bEiyz7@nFMyoeqJ7qmPW/A0D8XZbYi@lbdCcAgCIzJmRrJ9Giw8prR0t48e8oUwihPf/g) Less golfed (55 bytes) ([TIO](https://tio.run/nexus/python2#HYhBCsIwEEXXeoq/EZIhSlszoIXcxE1EIwU7lVEht49TN@//9woSLu2Z5@stQ8cT6T7S@zs7p3YrVU904F2fUlcWRcUk0CyPu1Pv25pkTV1AHxAD2Hi2sXAcTJiH@CeP281LJ/lAAooT334 "Python 2 – TIO Nexus")) ``` lambda r:8*r-4*sum((r*r-x*x)**.5%1==0for x in range(r)) ``` This estimates the output as `8*r`, then corrects for vertex crossings. The result is `8*r-g(r*r)`, where `g(x)` counts the [number of ways to write `x` as a sum of two squares](https://codegolf.stackexchange.com/q/64812/20260) (except `g(0)=0`). If the circle never went through any vertices, the number of cells touched would equal the number of edges crossed. The circle passes through `2*r` vertical gridlines and `2*r` horizontal gridlines, passing each one in both directions, for a total of `8*r`. But, each crossing at a vertex counts as two edge crossings while only entering one new cell. So, we compensate by subtracting the number of vertex crossings. This includes the points on axes like `(r,0)` as well as Pythagorean triples like `(4,3)` for `r=5`. We count for a single quadrant the points `(x,y)` with `x>=0` and `y>0` with `x*x+y*y==n`, then multiply by 4. We do this by counting the numer of `sqrt(r*r-x*x)` that are whole number for `x` in the interval `[0,r)`. [Answer] ## Mathematica, 48 bytes ``` 4Count[Range@#~Tuples~2,l_/;Norm[l-1]<#<Norm@l]& ``` Looks at the first quadrant and counts the number of grid cells for which the input falls between the norms of the cell's lower left and upper right corners (multiplying the result by 4, of course). [Answer] # [Python 2](https://docs.python.org/2/), 72 bytes ``` lambda n:sum(0<n*n-x*x-y*y<2*(x-~y)for x in range(n)for y in range(n))*4 ``` [Try it online!](https://tio.run/nexus/python2#S1OwVYj5n5OYm5SSqJBnVVyaq2Fgk6eVp1uhVaFbqVVpY6SlUaFbV6mZll@kUKGQmadQlJiXnqqRBxaoRBbQ1DL5DxLMAwka6CgY6iiYAJGljoIpkGdsZGrFxVlQlJlXopAGVP0fAA "Python 2 – TIO Nexus") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~21~~ ~~13~~ ~~12~~ 11 bytes ``` R²ạ²Æ²SạḤ×4 ``` [Try it online!](https://tio.run/nexus/jelly#@x90aNPDXQsPbTrcdmhTMJD1cMeSw9NN/h/dc7j9UdMa9///DXQUDHUUTHQUTIGkJZACChgbATmmpkYmYNIUAA "Jelly – TIO Nexus") ### How it works ``` R²ạ²Æ²SạḤ×4 Main link. Argument: r R Range; yield [1, 2, ..., r]. ² Square; yield [1², 2², ..., r²]. ² Square; yield r². ạ Absolute difference; yield [r²-1², r²-2², ..., r²-r²]. Ʋ Test if each of the differences is a perfect square. S Sum, counting the number of perfect squares and thus the integer solutions of the equation x² + y² = r² with x > 0 and y ≥ 0. Ḥ Un-halve; yield 2r. ạ Subtract the result to the left from the result to the right. ×4 Multiply by 4. ``` [Answer] # Perl 6, 61 bytes ``` ->\r{4*grep {my &n={[+] $_»²};n(1 X+$_)>r²>.&n},(^r X ^r)} ``` ### How it works ``` ->\r{ } # Lambda (accepts the radius). (^r X ^r) # Pairs from (0,0) to (r-1,r-1), # representing the bottom-left # corners of all squares in # the top-right quadrant. grep { } # Filter the ones matching: my &n={[+] $_»²}; # Lambda to calculate the norm. n(1 X+$_)>r² # Top-right corner is outside, >.&n # and bottom-left is inside. 4* # Return length of list times 4. ``` [Answer] ## AWK, 90 bytes ``` {z=$1*$1 for(x=$1;x>=0;x--)for(y=0;y<=$1;y++){d=z-x*x-y*y if(d>0&&d<2*(x+y)+2)c++}$0=4*c}1 ``` Usage: ``` awk '{z=$1*$1 for(x=$1;x>=0;x--)for(y=0;y<=$1;y++){d=z-x*x-y*y if(d>0&&d<2*(x+y)+2)c++}$0=4*c}1' <<< 5525 ``` Just a simple search through quadrant 1 to find all boxes that will intersect the circle. Symmetry allows for the multiply by 4. Could go from `-$1 to $1`, but that would take a more bytes and be less efficient. Obviously this is not the most time efficient of algorithms, but it only takes about 16 seconds to run the 5525 case on my machine. [Answer] # Haskell, 74 bytes ``` f n=sum[4|x<-[0..n],y<-[0..n],(1+n-x)^2+(1+n-y)^2>n^2,(n-x)^2+(n-y)^2<n^2] ``` Pretty straightforward, count the number of squares between (0,0) and (n,n) where the bottom left is inside the circle and the top right is outside the circle, then multiply by 4. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 29 bytes ``` Lsm*ddb*4lf}*QQrhyTym+1dT^UQ2 ``` [Try it!](https://pyth.herokuapp.com/?code=Lsm%2addb%2a4lf%7D%2aQQrhyTym%2B1dT%5EUQ2&input=2&test_suite=1&test_suite_input=0%0A1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9%0A10%0A49&debug=1) ### Explanation ``` Lsm*ddb*4lf}*QQrhyTym+1dT^UQ2 # implicit input: Q Lsm*ddb # define norm function s # sum m b # map each coordinate to *dd # its square ^UQ2 # cartesian square of [0, 1, ..., Q - 1] # -> list of coordinates of all relevant grid points f # filter the list of coordinates T where: }*QQ # square of Q is in r # the range [ hyT # 1 + norm(T), # ^ coordinate of lower left corner ym+1dT # norm(map({add 1}, T)) # ^^^^^^^^^^^^^^^ coordinate of upper right corner # ) <- half-open range l # size of the filtered list # -> number of passed-through squares in the first quadrant *4 # multiply by 4 # implicit print ``` [Answer] ## Batch, 147 bytes ``` @set/an=0,r=%1*%1 @for /l %%i in (0,1,%1)do @for /l %%j in (0,1,%1)do @set/a"i=%%i,j=%%j,a=i*i+j*j-r,i+=1,j+=1,a&=r-i*i-j*j,n-=a>>31<<2 @echo %n% ``` Somewhat inspired by the AWK and Haskell answers. [Answer] # [Bash](https://www.gnu.org/software/bash/) + Unix utilities, 127 bytes ``` c()(d=$[(n/r+$1)**2+(n%r+$1)**2-r*r];((d))&&echo -n $[d<0]) r=$1 bc<<<`for((n=0;n<r*r;n++));{ c 0;c 1;echo;}|egrep -c 01\|10`*4 ``` [Try it online!](https://tio.run/nexus/bash#NcsxDsIwDEDRvafwECo7UUSCYHJyklKpIgkwucgr5eyhDGxfX3q9IGHNZkI5qjORrD05lMO/vVqdGbESjWMrzxW8gJlqCjMNmk0cbiWltNxXRZQcWNIuWJwj4jcUCFwg8k/yZ2sPbS/w@43XLYbFnnvvly8 "Bash – TIO Nexus") Just go through all the points in the first quadrant, count them up, and multiply by 4. It can be very slow, but it works. [Answer] # JavaScript (ES7), 76 bytes ``` n=>4*(G=k=>k<n?Math.ceil((n**2-k++**2)**0.5)-(0|(n**2-k**2)**0.5)+G(k):0)(0) ``` ]
[Question] [ ### Background: Jack is a pumpkin that enjoys spooking the citizens of the villages near his pumpkin patch every Halloween. However, every year after someone lights the candle inside of him, he has a limited amount of time to spook everyone before the candle burns out, thus being unable to spook any more villagers because nobody can see him. In past years, he has only been able to spook a small amount of villages due to his poor decision making, but now that he has you to help him, he will be able to spook as many villages as possible! ### Task: Given a list of village locations and a candle lifespan, output the maximum number of villages Jack can visit. You do not have to print the path itself. ### Input: The lifespan of the candle and a list of village locations in a Cartesian coordinate system. The pumpkin patch Jack originates from will always be at 0,0. You may format the input in anyway you wish. To simplify Jack's movements, he can only move horizontally, vertically, or diagonally, meaning his candle will either lose 1 or 1.5 (he takes a bit longer diagonally) units of life every move. The candle burns out when the lifespan is less than or equal to 0. ### Output: An integer equal to the maximum number of villages Jack can visit before the candle burns out. ### Rules: This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins. Standard loopholes are not allowed. ### Test cases: ``` // Format [lifespan] [list of village coordinates] -> [maximum visit-able villages] 4 -1,0 1,0 2,0 3,0 4,0 5,0 -> 3 4 1,1 2,2 3,3 -> 2 5 1,1 2,1 3,1 4,1 5,0 5,1 -> 4 ``` [Answer] # Jelly, ~~30~~ ~~29~~ ~~27~~ 25 bytes ``` _AṢæ.. 0,0ṭṚç2\+\<S Œ!ç€Ṁ ``` [Try it online!](http://jelly.tryitonline.net/#code=X0HhuaLDpi4uCjAsMOG5reG5msOnMlwrXDxTCsWSIcOn4oKs4bmA&input=&args=W1stMSwwXSxbMSwwXSxbMiwwXSxbMywwXSxbNCwwXSxbNiwwXV0+NA) Apparently Jelly's dot product just ignores a list size mismatch and doesn't multiply the extra elements of the other array, just adds them. Shaves off 2 bytes. ### Explanation ``` _AṢæ.. Helper link to calculate distance. Arguments: a, b _ subtract the vertices from each other A take absolute values of axes Ṣ sort the axes æ.. dot product with [0.5] 0,0ṭṚç2\+\<S Helper link to calculate max cities. Arguments: perm, max 0,0 create pair [0,0] ṭ append that to the permutation Ṛ reverse the permutation (gets the [0,0] to the beginning) ç2\ find distances of each pair using the previous link +\ find all partial sums < see if each sum was less than the max S sum to count cases where it was Œ!ç€Ṁ Main link. Arguments: cities, max Œ! get permutations of cities ç€ find max cities for each permutation using the previous link Ṁ take the maximum ``` [Answer] # Java 7, ~~206~~ 201 bytes *Thanks to @KevinCruijssen for saving 5 bytes* ``` int f(float e,int[]a,int[]b){int x=0,y=0,c=0,d=0,t;float s;for(int i:a){s=(i!=x&b[c]==y)|(i==x&b[c]!=y)?Math.sqrt((t=i-x)*t+(t=b[c]-y)*t)*1:Math.abs(i-x)*1.5;d+=e-s>=0?1:0;e-=s;x=i;y=b[c++];}return d;} ``` # Ungolfed ``` class Travellingpumpkin { public static void main(String[] args) { System.out.println(f( 5 ,new int[] { 1,2,3,4,5,5 } , new int[] { 1,1,1,1,0,1 } )); } static int f( double e , int[]a , int[]b ) { int x = 0 , y = 0 , c = 0 , d = 0 , t; double s ; for ( int i : a ) { s = ( i != x & b[c] == y )|( i == x & b[c] != y ) ? Math.sqrt( ( t = i - x ) * t + ( t = b[c] - y ) * t ) * 1 : Math.abs( i - x ) * 1.5 ; d += e-s >= 0 ? 1 : 0 ; e -= s ; x = i ; y = b [ c++ ] ; } return d ; } } ``` [Answer] # Scala, 196 bytes ``` def f(l:Int,c:(Int,Int)*)=c.permutations.map(x=>((0,0)+:x sliding 2 map{p=>val Seq(c,d)=Seq((p(0)._1-p(1)._1)abs,(p(0)._2-p(1)._2)abs).sorted c*1.5+(d-c)}scanLeft 0d)(_+_)takeWhile(_<l)size).max-1 ``` Ungolfed: ``` def g (l: Int, c: (Int, Int)*) = { c.permutations .map { x => ((0, 0) +: x).sliding(2).map({ p => val Seq(c, d) = Seq((p(0)._1 - p(1)._1) abs, (p(0)._2 - p(1)._2) abs).sorted c * 1.5 + (d - c) }).scanLeft(0d)(_ + _).takeWhile(_ < l).size }.max - 1 } ``` Explanantion: ``` def f(l:Int,c:(Int,Int)*)= //defien a function with an int and a vararg-int-pait parameter c.permutations //get the permutations of c, that is all possible routes .map(x=> //map each of them to... ((0,0)+:x //prepend (0,0) sliding 2 //convert to a sequence of consecutive elemtens map{p=> //and map each of them to their distance: val Seq(c,d)=Seq( //create a sequence of (p(0)._1-p(1)._1)abs, //of the absolute distance between the x points (p(0)._2-p(1)._2)abs //and he absolute distance between the y coordinates ).sorted //sort them and assign the smaller one to c and the larger one to d c*1.5+(d-c) //we do the minimum difference diagonally } //we now have a sequence of sequence of the distances for each route scanLeft 0d)(_+_) //calculate the cumulative sum takeWhile(_<l) //and drop all elements that are larger than the candle lifespan size //take the size ).max-1 //take the maximum, taht is the size of the largest route and subtract 1 because we added (0,0) at the beginning ``` [Answer] # JavaScript (ES6), 145 Anonymous recursive function, parameter `s` is the candle lifespan, parameter `l` is the village coordinate list. A *Depth First Search*, stopping when the distance reachs the candle lifespan ``` f=(s,l,x=0,y=0,v=0,A=Math.abs,X=Math.max)=>X(v,...l.map(([t,u],i,[h,...l],q=A(t-x),p=A(u-y),d=(l[i-1]=h,p+q+X(p,q))/2)=>s<=d?v:f(s-d,l,t,u,1+v))) ``` *Less golfed* see the snippet below **Test** ``` f=(s,l,x=0,y=0,v=0,A=Math.abs,X=Math.max)=> X(v,...l.map( ([t,u],i,[h,...l],q=A(t-x),p=A(u-y),d=(l[i-1]=h,p+q+X(p,q))/2)=> s<=d?v:f(s-d,l,t,u,1+v) )) // ungolfed version F=(s, l, x=0, y=0, // current position v=0 // current number of visited sites ) => Math.max(v, ...l.map( ( [t,u], i, [h,...l], // lambda arguments q = Math.abs(t-x), p = Math.abs(u-y), // locals d = (p+q+Math.max(p,q))/2 ) => ( l[i-1] = h, s <= d ? v : F(s-d, l, t, u, v+1) ) )) ;[[4,[[-1,0],[1,0],[2,0],[3,0],[4,0],[5,0]], 3] ,[4, [[1,1],[2,2],[3,3]], 2] ,[5, [[1,1],[2,1],[3,1],[4,1],[5,0],[5,1]], 4] ].forEach(test=>{ var span=test[0],list=test[1],check=test[2], result = f(span, list) console.log(result==check?'OK':'KO',span, list+'', result) }) ``` [Answer] # [MATL](http://github.com/lmendo/MATL), 27 bytes ``` EH:"iY@OwYc!d|]yyXl++Ys>sX> ``` *EDIT (26 nov 2016): Due to changes in the `Xl` function, it has to be replaced in the above code by `2$X>`. The links below incorporate that modification.* [Try it online!](http://matl.tryitonline.net/#code=RUg6ImlZQE93WWMhZHxdeXkyJFg-KytZcz5zWD4&input=NQpbMSAyIDMgNCA1IDVdClsxIDEgMSAxIDAgMV0) Or [verify all test cases](http://matl.tryitonline.net/#code=YApFSDoiaVlAT3dZYyFkfF15eTIkWD4rK1lzPnNYPgpEVA&input=NApbLTEgMSAyIDMgNCA1XQpbMCAwIDAgMCAwIDBdCjQKWzEgMiAzXQpbMSAyIDNdCjUKWzEgMiAzIDQgNSA1XQpbMSAxIDEgMSAwIDFdCg). ### Explanation The *pumpkin distance* between two cities separated Δ*x* and Δ*y* in each coordinate can be obtained as ( |Δ*x*| + |Δ*y*| + max(|Δ*x*|, |Δ*y*|) ) / 2. The code follows these steps: 1. Generate all permutations of *x* coordinates and of *y* coordinates, and prepend a to each 0. Each permutation represents a possible path. 2. Compute absolute consecutive differences for each path (these are |Δ*x*| and |Δ*y*| above). 3. Obtain the pumpkin distance for each step of each path. 4. Compute the cumulative sum of distances for each path. 5. Find, for each path, the number of steps before the accumulated distance reaches the chandle lifespan. 6. Take the maximum of the above. Commented code: ``` E % Input candle lifespan implicitly. Multiply by 2 H:" % Do thie twice i % Input array of x or y coordinates Y@ % All permutations. Gives a matrix, with each permutation in a row OwYc % Prepend a 0 to each row ! % Transpose d| % Consecutive differences along each column. Absolute value ] % End yy % Duplicate the two matrices (x and y coordinates of all paths) Xl % Take maximum between the two, element-wise ++ % Add twice. This gives twice the pumpkin distance Ys % Cumulative sum along each column > % True for cumulative sums that exceed twice the candle lifespan s % Sum of true values for each column X> % Maximum of the resulting row array. Inmplicitly display ``` [Answer] # **[Python 2.7](https://www.python.org/download/releases/2.7/), 422 bytes** ### thanks to NoOneIsHere for pointing out additional improvements! ### thanks to edc65 for noting not to save the list but use iterators instead! [**Try it online!**](http://ideone.com/w8fkvv "You can edit the code to try out other inputs") ``` from itertools import permutations def d(s,e): d=0 while s!=e: x=1 if s[0]<e[0] else -1 if s[0]>e[0] else 0 y=1 if s[1]<e[1] else -1 if s[1]>e[1] else 0 s=(s[0]+x,s[1]+y) d+=(1,1.5)[x and y] return d l,m=4,0 for o in permutations([(1,1),(2,2),(3,3)]): a,c=l-d((0,0),o[0]),1 for j in range(len(o)-1): a-=d(o[j],o[j+1]) c+=(0,1)[a>0] m=max(c,m) print m ``` # **Explanation:** The function calculates the distance between two points according to the given rules, the loop iterates through all permutations generated by the generator of the input and calculates the distance, if the distance is lesser than the candle lifespan it subtracts it and adds the place to the counter, if that counter is greater than the current max it substitutes it. # **ungolfed:** ``` from itertools import permutations def distance(start_pos, end_pos): distance = 0 while start_pos != end_pos: mod_x = 1 if start_pos[0] < end_pos[0] else -1 if start_pos[0] > end_pos[0] else 0 mod_y = 1 if start_pos[1] < end_pos[1] else -1 if start_pos[1] > end_pos[1] else 0 start_pos = (start_pos[0] + mod_x, start_pos[1] + mod_y) distance += (1, 1.5)[mod_x and mod_y] return distance lifespan, max_amount = 4, 0 for item in permutations([(1,1), (2,2), (3,3)]): lifespan_local, current = lifespan - distance((0,0), item[0]), 1 for j in range(len(item) - 1): lifespan_local -= distance(item[j], item[j + 1]) current += (0, 1)[lifespan_local > 0] max_amount = max(current, max_amount) print max_amount ``` [Answer] # PHP, 309 bytes ``` function j($x,$y,$c,$v){if($s=array_search([$x,$y],$v))unset($v[$s]);for($c--,$i=4;$c>0&&$i--;)$m=($n=j($x+[1,0,-1,0][$i],$y+[0,1,0,-1][$i],$c,$v))>$m?$n:$m;for($c-=.5,$i=4;$c>0&&$i--;)$m=($n=j($x+[1,-1,-1,1][$i],$y+[1,1,-1,-1][$i],$c,$v))>$m?$n:$m;return$s?++$m:$m;}echo j(0,0,$argv[1],array_chunk($argv,2)); ``` Absolutely brute force and not even very short. Use like: ``` php -r "function j($x,$y,$c,$v){if($s=array_search([$x,$y],$v))unset($v[$s]);for($c--,$i=4;$c>0&&$i--;)$m=($n=j($x+[1,0,-1,0][$i],$y+[0,1,0,-1][$i],$c,$v))>$m?$n:$m;for($c-=.5,$i=4;$c>0&&$i--;)$m=($n=j($x+[1,-1,-1,1][$i],$y+[1,1,-1,-1][$i],$c,$v))>$m?$n:$m;return$s?++$m:$m;}echo j(0,0,$argv[1],array_chunk($argv,2));" 5 1 1 2 1 3 1 4 1 5 0 5 1 ``` With more whitespace and saved in a file: ``` <?php function j( $x, $y, $c, $v) { if( $s = array_search( [$x,$y], $v ) ) unset( $v[$s] ); for( $c--, $i=4; $c>0 && $i--;) $m = ( $n=j($x+[1,0,-1,0][$i],$y+[0,1,0,-1][$i],$c,$v) )>$m ? $n : $m; for( $c-=.5, $i=4; $c>0 && $i--;) $m = ( $n=j($x+[1,-1,-1,1][$i],$y+[1,1,-1,-1][$i],$c,$v) )>$m ? $n : $m; return $s ? ++$m : $m; } echo j( 0, 0, $argv[1], array_chunk($argv,2) ); ``` [Answer] ## Python, 175 bytes ``` def f(c,l): def r(t):p=abs(t[0]-x);q=abs(t[1]-y);return p+q-.5*min(p,q) v=0;x,y=0,0 while c>0 and len(l)>0: l.sort(key=r);c-=r(l[0]);x,y=l.pop(0) if c>=0:v+=1 return v ``` `c` is the lifespan of the candle, `l` is a list of tuples - village coordinates, `v` is the number of visited villages, `(x,y)` is pair of coordinates of the village Jack is currently in. `r(t)` is a function which calculates the distance to the current position and is used to sort the list so that the closest becomes `l[0]`. The formula used is |Δx| + |Δy| - min(|Δx|, |Δy|) / 2. [Try it here!](https://ideone.com/qkVSK6) [Answer] ## Racket ``` (define (dist x1 y1 x2 y2) ; fn to find distance between 2 pts (sqrt(+ (expt(- x2 x1)2) (expt(- y2 y1)2)))) (define (fu x1 y1 x2 y2) ; find fuel used to move from x1 y1 to x2 y2; (let loop ((x1 x1) (y1 y1) (fuelUsed 0)) (let* ((d1 (dist (add1 x1) y1 x2 y2)) ; horizontal movement (d2 (dist x1 (add1 y1) x2 y2)) ; vertical movement (d3 (dist (add1 x1) (add1 y1) x2 y2)) ; diagonal movement (m (min d1 d2 d3))) ; find which of above leads to min remaining distance; (cond [(or (= d2 0)(= d1 0)) (add1 fuelUsed)] [(= d3 0) (+ 1.5 fuelUsed)] [(= m d1) (loop (add1 x1) y1 (add1 fuelUsed))] [(= m d2) (loop x1 (add1 y1) (add1 fuelUsed))] [(= m d3) (loop (add1 x1) (add1 y1) (+ 1.5 fuelUsed))])))) (define (f a l) (define u (for/list ((i l)) (fu 0 0 (list-ref i 0) (list-ref i 1)))) ; find fuel used for each point; (for/last ((i u)(n (in-naturals)) #:final (>= i a)) n)) ``` Testing: ``` (f 4 '((1 1) (2 2) (3 3))) ;-> 2 (f 5 '((1 1) (2 1) (3 1) (4 1) (5 0) (5 1))) ;-> 4 ``` Output: ``` 2 4 ``` However, above code does not work for negative values of x and y. ]
[Question] [ You live inside a terminal that is 80 characters wide. You are bored, so you decide to play dominoes. No, not the boring kind that look like Scrabble, the fun kind where you spend an hour setting them to watch them fall in a second. In terminals, dominoes look like this: ``` | upright domino \ left-tilted domino / right-tilted domino __ fallen domino ``` As we all know, if a tilted domino touches an upright one, the second domino gets tilted as well. The only exception to this is if *two* tilted dominoes touch it: ``` |\ --> \\ /| --> // /|\ --> /|\ ``` Adjust your terminal's gravitational constant so this transition takes 100 ms. If a tilted domino is supported by another domino or the terminal's walls, its journey ends. None of the tilted dominoes in ``` \||||____||||/__ /|\ /\ /|\ __\||||____||||/ ``` (80 characters) will move, since the two outmost tilted dominoes are supported by the terminal's walls and all others are supported by other dominoes. However, if the space in the tilting direction is empty, the domino falls down: ``` | \\ --> |__\ // | --> /__| ``` Terminal. Gravitational constant. You get the point… Finally, there's a slight wind from the left, so right-tilted dominoes fall faster than left-tilted ones: ``` |/ \| --> |__\| ``` ### Task Write a program/function that shows an animation of playing dominoes in a terminal. Your code should do the following: 1. Read a string from input, representing the initial state of the dominoes. This string will contain no more than 80 characters and consist solely of the dominoes described above and empty spaces. 2. Print the state and wait for 100 ms. 3. Transform the state as explained above. 4. If the state changed, go back to 2. ### Additional rules * The length of the input string does not affect the terminal's width; even if the string is shorter than 80 characters, the walls of the terminal are still 80 characters apart. * Each time step 2 is executed, the state should get printed to the same location, overwriting the previous state. * Since some languages are incapable of waiting *exactly* 100 ms, feel free to wait any amount between 50 and 1000 ms. * Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. ### Examples * For the initial state ``` ||\/|| ``` print the following (one over the other): ``` ||\/|| |\\//| \\\/// __\\//__ ``` * For the initial state ``` /||||\ ``` print the following ``` /||||\ //||\\ ///\\\ ``` * For the initial state ``` /|||\ ``` print the following ``` /|||\ //|\\ ``` * For the initial state ``` |/ \|/ \|/ \|/ \| ``` print the following: ``` |__\|__\|__\|__\| ``` * For the initial state (80 characters) ``` \||||____||||/__ /|\ /\ /|\ __\||||____||||/ ``` print the following ``` \||||____||||/__ /|\ /\ /|\ __\||||____||||/ ``` [Answer] # [Retina](https://github.com/mbuettner/retina), ~~87~~ ~~86~~ 85 bytes *Thanks to Dennis for saving 1 byte.* ``` ^.{0,79}$ $0 :`^ <ESC>c (`/ | \\ __ /\|(?!\\) //a (?<!/)\|\\ \\ $ aaaaa a aaaa (a+)+b|a <empty> ``` `<ESC>` should be replaced by the actual control character (0x1B). `<empty>` represents an empty trailing line. You can then run the above code from a single file with the `-s` flag. The code requires a terminal which supports ANSI escape codes. I can't suppress the line feed in Retina's output so I need to clear the entire console with `<ESC>c` each time. I've tested the code in bash using Mono to run Retina. ## Explanation ``` ^.{0,79}$ $0 ``` We start by appending a space if the input contains fewer than 80 characters. This is so that a `/` at the right end does not have to be treated separately. ``` :`^ <ESC>c ``` Now we prepend `<ESC>c` to the string, which is the ANSI escape code for clearing the terminal. So every time the string is printed it will do so at the top of the terminal. The `:`` instructs Retina to print out the result of this substitution, i.e. the initial configuration. ``` (`/ | \\ __ ``` `(`` begins a loop. Since there is no matching `)`, the loop is assumed to go until the last stage of the program. Each iteration will simulate one step of the dominoes falling and then "sleep" a bit. This first stage replaces `/` and `\` next to a space into `__`. This automatically handles the `/ \` case correctly, because matches cannot overlap and are searched for from left to right. So the `/<sp>` would be matched and turned into `__` such that the `\` can't be matched, and we get the correct `__\`. ``` /\|(?!\\) //a ``` This turns `/|` into `//` provided there's no `\` next to it. We append an `a` such that this new `/` doesn't mess with the next stage (which shouldn't "know" about this change yet). ``` (?<!/)\|\\ \\ ``` The opposite situation: turn `|\` into `\\` provided there's no `/` next to it. We don't need to put an `a` here, because we're done with this step of the simulation. Now the sleeping part... ``` $ aaaaa ``` Appends 5 more `a`s to the end of the code. ``` a aaaa ``` Turns each `a` into 4 `a`s, so we get 20 `a`s at the end. ``` (a+)+b|a <empty> ``` Now the fun part... we sleep for a bit with the help of [catastrophic backtracking](https://stackoverflow.com/a/13179439/1633117). There is an exponential amount of ways to split up a match of `(a+)+` between repetitions of the group. Because the `b` causes the match to fail, the engine will backtrack and try every single one of those combinations before deciding that `(a+)+b` can't match. For the twenty `a`s at the end that takes something like half a second. At the same time, we allow the regex to match a single `a`, but only *after* doing the backtracking. When that matches, we replace it with an empty string, removing all the `a`s we inserted for one reason or another from the string. That leaves printing the string at the end of the loop iteration. Here it comes in handy that I haven't fixed the printing behaviour of loops in Retina yet. Currently, there is only one flag for each stage, which says "print" or "don't print". The default is "don't print" except for the last stage in the program, which defaults to "print". But the stage is looped, so that means it actually prints the current string on each iteration. Normally, that is really annoying, and you almost always need to include an additional empty stage at the end if you only want the final result, but here it lets me save four bytes. [Answer] # Javascript (ES6), ~~206~~ ~~148~~ ~~129~~ 158 bytes I'd finally gotten it down to a nicely low point, but it wouldn't clear the console or append an extra space; these problems have been fixed now. ``` c=console;d=s=>{c.clear(s[79]||(s+=' ')),c.log(s),t=s[R='replace'](/\/ | \\/g,'__')[R](/\/\|/g,'//a')[R](/\|\\/g,'\\\\')[R](/a/g,'');t!=s&&setTimeout(d,99,t)} ``` Alternate 153 byte version which should work in Node.JS: ``` d=s=>{s[79]||(s+=' '),console.log("\033c"+s),t=s[R='replace'](/\/ | \\/g,'__')[R](/\/\|/g,'//a')[R](/\|\\/g,'\\\\')[R](/a/g,'');t!=s&&setTimeout(d,99,t)} ``` IMHO, it's quite fun to play with. Try an HTML version here: ``` output=document.getElementById("output"),console.log=a=>output.innerHTML=a; d=s=>{s[79]||(s+=' ');console.log(s),t=s[R='replace'](/\/ | \\/g,'__')[R](/\/\|/g,'//a')[R](/\|\\/g,'\\\\')[R](/a/g,'');t!=s&&setTimeout(d,99,t)} s=n=>{n=n||15,r='';for(i=0;i<n;i++)r+=(i%2?'|'.repeat(Math.random()*16|0):'\\ /'[Math.random()*3|0].repeat(Math.random()*3+1|0));return r} // randomizer input=document.getElementById("input"); input.addEventListener("keydown",e=>e.keyCode==13?(e.preventDefault(),d(input.value)):0); ``` ``` <p>Enter your dominoes here:</p> <textarea id="input" rows="1" cols="80">|||\ |||\ /|\ /||||||||\ /|||| /|||</textarea> <button id="random" onclick="input.value=s()">Randomize</button><button id="run" onclick="d(input.value)">Run</button> <p>Result:</p> <pre id="output"></pre> ``` There's probably a good bit more room for golfing. Suggestions welcome! [Answer] # C#, 335 bytes Not a great choice of language. I abused the delay being allowed between 50 and 1000 to select a two-digit number. New lines and indentation added for clarity: ``` namespace System.Threading{ class P{ static void Main(string[]z){ var c=@"/|\,/|\,/|,//,|\,\\,/ ,__, \,__".Split(','); for(string a=z[0].PadRight(80),b="";a!=b;){ Console.Clear(); Console.Write(b=a); Thread.Sleep(99); a=""; for(int i,j;(i=a.Length)<80;) a+=(j=Array.FindIndex(c,d=>b.Substring(i).StartsWith(d)))%2==0 ?c[j+1] :b.Substring(i,1); } } } } ``` [Answer] # Perl 5, ~~154~~ 146 Had to use a temporary character to maintain the state between 2 regexes. To deal with the risk that something like / | | | \ would end up as / / / \ \ instead of / / | \ \ . ``` $_=substr(pop.' ',0,80);$|++;while($}ne$_){print"$_\r";$}=$_;s@ \\|/ @__@g;s@/\|(?=[^\\])@/F@g;s@([^/])\|\\@$1\\\\@g;tr@F@/@;select($\,$\,$\,0.1)} ``` ### Test ``` $ perl dominos.pl '|\ |\/|||\/|' |\__\//|\\/__ ``` [Answer] [# ES6](http://es6-features.org/#Constants), 220 218 195 bytes Minified ``` f=d=>{var e,c=console;if(!d[79])d+=' ';c.clear();c.log(d);e=d;d=d[R='replace'](/\/\|\\/g,'a')[R](/\/ | \\/g,'__')[R](/\/\|/g,'//')[R](/\|\\/g,'\\\\')[R]('a','/|\\');if(e!=d)setTimeout(f,100,d);}; ``` More Readable ``` f=d=> { var e, c=console; if(!d[79]) d+=' '; c.clear(); c.log(d); e=d; d = d[R='replace'](/\/\|\\/g, 'a') //Substitute '/|\' with 'a' so it doesn't get replaced [R](/\/ | \\/g, '__') //Replace '/ ' and ' \' with '__' [R](/\/\|/g, '//') //Replace '/|' with '//' [R](/\|\\/g, '\\\\') //Replace '|\' with '\\' [R]('a', '/|\\'); //Put '/|\' back if(e!=d) setTimeout(f,100,d); }; ``` [Answer] # PHP, 175 bytes ``` $i=sprintf("%-80s",$argv[1]);$p='preg_replace';do{echo($o=$i)."\r";$i=$p('(/\|\\\\(*SKIP)(?!)|(?|(/)\||\|(\\\\)))','$1$1',$p('(/ | \\\\)','__',$i));usleep(1e5);}while($i!=$o); ``` Un-minified: ``` $input = sprintf("%-80s",$argv[1]); do { echo $input."\r"; $old = $input; $input = preg_replace('(/ | \\\\)','__',$input); $input = preg_replace('(/\|\\\\(*SKIP)(?!)|(?|(/)\||\|(\\\\)))','$1$1',$input); usleep(100000); } while( $input != $old); ``` Basically regex golf. First flattens any falling dominoes that have space (and due to left-to-right matching order, the "wind" blows). Then comes the ugly part (curse you slashes!) * Match `/|\`, then skip it. * Match `(/)|` and replace with `//` * Match `|(\)` and replace with `\\` This makes the dominoes fall. Finally, just wait 100ms for the next step. Using `()` as delimiters on the regex means the `/`s don't need escaping, which helps minimally! [Answer] # POSIX shell+sed, 144 ``` sed 's/^.\{1,79\}$/& /;s/.*/printf '"'&\\r'"';sleep .1/;h;:;s,/|\\,/:\\,g;s,\(/ \| \\\),__,g;s,/|,//,g;s,|\\,\\\\,g;H;t;x;y/:/|/;s/\\/\\\\/g'|sh ``` This is in two parts. The main work of toppling the dominoes is standard `sed` pattern replacement, accumulating lines into hold space. We temporarily turn `/|\` into `/:\` to protect it, recovering at the end. ``` s/^.\{0,79\}$/& / h : s,/|\\,/:\\,g s,\(/ \| \\\),__,g s,/|,//,g s,|\\,\\\\,g H t x y/:/|/ ``` Since `sed` hasn't got any way of inserting delays (I looked into terminfo/termcap, but couldn't find any standard way), I wrap each line in `printf "...\r"; sleep .1` to print a line every 100ms. I actually do this first, when we have just one line, as the characters in the command won't be touched by any of the substitutions of toppling. All tested using `dash` and GNU `coreutils`, with `POSIXLY_CORRECT` set in the environment. ]
[Question] [ ## Task: Your program is given a [proper](//en.wikipedia.org/wiki/Fraction_(mathematics)#Proper_and_improper_fractions), positive [simple fraction](//en.wikipedia.org/wiki/Fraction_(mathematics)#Simple.2C_common.2C_or_vulgar_fractions) in the format `<numerator>/<denominator>`. For this input, it must find two fractions. 1. A fraction that is less than the input. 2. A fraction that is greater than the input. Both fractions must have a lower denominator than the input. Of all possible fractions, they should have the lowest difference to the input. ## Output: Your program's output must be: * A fraction that is smaller than the input, in the format `<numerator>/<denominator>`. * Followed by a space character (ASCII-code 32). * Followed by a fraction that is greater than the input, in the format `<numerator>/<denominator>`. As follows: ``` «fraction that is < input» «fraction that is > input» ``` ## Rules: * All fractions outputted must be [in lowest terms](//en.wikipedia.org/wiki/Irreducible_fraction). * All fractions outputted must be proper fractions. * If there are no proper fractions possible that are allowed by the rules, you must output `0` instead of a fraction < input, and `1` instead of a fraction > input. * You can choose whether you want to receive the fraction as a command-line argument (e.g. `yourprogram.exe 2/5`) or prompt for user input. * You may assume your program won't receive invalid input. * The shortest code (in bytes, in any language) wins. * Any non-standard command-line arguments (arguments that aren't normally required to run a script) count towards the total character count. * What your program **must not** do: + Depend on any external resources. + Depend on having a specific file name. + Output anything other than the required output. + Take exceptionally long to run. If your program runs over a minute for fractions with a 6-digit numerator and denominator (e.g. `179565/987657`) on an average home user's computer, it's invalid. + Output fractions with `0` as the denominator. You can't divide by zero. + Output fractions with `0` as the numerator. Your program must output `0` instead of a fraction. + Reduce an inputted fraction. If the fraction given as input is reducible, you must use the fraction as it is inputted. * Your program must not be written in a programming language for which there did not exist a publicly available compiler / interpreter before this challenge was posted. ## Examples: **Input:** `2/5` **Output:** `1/3 1/2` **Input:** `1/2` **Output:** `0 1` **Input:** `5/9` **Output:** `1/2 4/7` **Input:** `1/3` **Output:** `0 1/2` **Input:** `2/4` **Output:** `1/3 2/3` **Input:** `179565/987657` **Output:** `170496/937775 128779/708320` [Answer] # Python 2.7 - 138 ``` x,y=n,d=map(int,raw_input().split('/')) while y:x,y=y,x%y def f(p,a=d): while(a*n+p)%d:a-=1 print`(a*n+p)/d`+('/'+`a`)*(a>1), f(-x);f(x) ``` I started with the obvious brute-force solution, but I realized that since the OP wanted to be able to solve instances with six digit numerators and denominators in under a minute, I need a better solution than trying a trillion possibilities. I found a handy formula on the Wikipedia page for the Farey sequence: If a/b, c/d are neighbors in one of the Farey sequences, with `a/b<c/d`, then `b*c-a*b=1`. The while loop inside f in my program extends this fact to non-reduced numbers, using the gcd, which the other while loop calculates. I've golfed this pretty hard already, but I'd love to hear any suggestions. ## Edits: 166->162: Removed `a` and `b` from the outer program. They were unnecessary. 162->155: `str()` -> `` 155->154: Added `k`. 154->152: Removed `x` from inside the function, passed it as an argument instead. 152->150: Gave `a` a default value instead of passing it as an argument. 150->146: Changed the initialization of `x` and `y`. 146->145: Removed `k`. ## Test cases: ``` 2/5 1/3 1/2 1/2 0 1 2/4 1/3 2/3 179565/987657 170496/937775 128779/708320 12345678/87654321 12174209/86436891 11145405/79132382 ``` The second to last test took under a second on my computer, while the last one took about 5-10 seconds. [Answer] ## Mathematica, 163 bytes ``` {a,b}=FromDigits/@InputString[]~StringSplit~"/";r=Range[b-1];""<>Riffle[#~ToString~InputForm&/@(#@DeleteCases[#2[a/b*r]/r,a/b]&@@@{{Max,Floor},{Min,Ceiling}})," "] ``` This is severely limited by the input/output requirement as user input and strings. Dealing with strings is really cumbersome in Mathematica (at least when you want to golf). Doing this the natural way in Mathematica, (using just integers and rationals) I'd probably get this down to 50% of the size. It can do 6-digit numbers in a few seconds on my machine. Slightly more readable (not really ungolfed though): ``` {a, b} = FromDigits /@ InputString[]~StringSplit~"/"; r = Range[b - 1]; "" <> Riffle[#~ToString~ InputForm & /@ (#[DeleteCases[#2[a/b*r]/r, a/b]] & @@@ {{Max, Floor}, {Min, Ceiling}}), " "] ``` For the fun of it, doing this "the natural way", i.e. as a function taking numerator and denominator and returning two rationals, this is only **84 characters** (so my 50% estimate was actually pretty close): ``` f[a_,b_]:=#@DeleteCases[#2[a/b*(r=Range[b-1])]/r,a/b]&@@@{{Max,Floor},{Min,Ceiling}} ``` [Answer] ## Sage – ~~119~~ 117 ``` x,X=map(int,raw_input().split('/')) a=0 A=c=C=1 while C<X:exec("ab,,AB"[c*X>C*x::2]+"=c,C");c=a+b;C=A+B print a/A,b/B ``` Sage is only needed in the last line, which takes care of the output. Everything else also works in Python. Replace `raw_input()` with `sys.argv[1]` to have the input read from a command-line argument instead of a prompt. This does not change the character count. (Does not work in Python without importing `sys` first.) This essentially recursively constructs the respective [Farey sequence](http://en.wikipedia.org/wiki/Farey_sequence) using mediants of the existing elements, but restricts itself to those elements closest to the input. From another point of view, it runs a nested-interval search on the respective Farey sequences. It correctly processes all of the examples in less than a second on my machine. Here is an ungolfed version: ``` x,X = map(Integer,sys.argv[1].split('/')) x = x/X a = 0 c = b = 1 while c.denominator() < X: if c > x: b = c else: a = c c = ( a.numerator() + b.numerator() ) / ( a.denominator() + b.denominator() ) print a,b ``` [Answer] # Julia - ~~127~~ 125 bytes I've approached this from a mathematical perspective to avoid need for loops, so this code runs quite fast for large inputs (note: if a/b is the input, then a\*b must fit within Int64 (Int32 on 32 bit systems), otherwise nonsense answers are generated - if a and b are both expressible in Int32 (Int16 on 32 bit systems), no problems occur). UPDATE: There's no longer a need to overload backslash for div, by using ÷, a net saving 2 bytes. ``` a,b=int(split(readline(),"/"));k=gcd(a,b);f=b-invmod(a÷k,b÷k);d=2b-f-b÷k;print(a*d÷b,d<2?" ":"/$d ",a*f÷b+1,"/$f"^(f>1)) ``` Ungolfed: ``` a,b=int(split(readline(),"/")) # Read in STDIN in form a/b, convert to int k=gcd(a,b) # Get the greatest common denominator f=b-invmod(a÷k,b÷k) # Calculate the denominator of the next biggest fraction d=2b-f-b÷k # Calculate the denominator of the next smallest fraction print(a*d÷b,d<2?" ":"/$d ",a*f÷b+1,"/$f"^(f>1)) # Calculate numerators and print ``` Basic idea: find the largest d and f less than b that satisfies ad-bc=gcd(a,b) (next smallest) and be-af=gcd(a,b) (next largest), then calculate c and e from there. Resulting output is c/d e/f, unless either d or f is 1, in which case the /d or /f is omitted. Interestingly, this means that the code also works for positive improper fractions, so long as the input is not an integer (that is, gcd(a,b)=a). On my system, inputting `194857602/34512958303` takes no perceivable time to output `171085289/30302433084 23772313/4210525219` [Answer] ## JavaScript, 131 With fat arrow notation and `eval` calls : ``` m=>{for(e=eval,n=e(m),i=p=0,q=1;++i</\d+$/.exec(m);)if(n*i>(f=n*i|0))g=f+1,p=f/i>e(p)?f+'/'+i:p,q=g/i<e(q)?g+'/'+i:q;return p+' '+q} ``` The `179565/987657` stress test is executed in approximately **35 seconds** on Firefox, a lot more on Chrome (~ 6 minutes) Faster method and without `eval` and fat arrow notation ``` for(n=eval(m=prompt(a=i=p=0,b=c=d=q=1));++i<m.match(/\d+$/);)if(n*i>(f=n*i|0))g=f+1,p=f*c>i*a?(a=f)+'/'+(c=i):p,q=g*d<i*b?(b=g)+'/'+(d=i):q;alert(p+' '+q) ``` The `179565/987657` stress test is executed in approximately 5 seconds. Not golfed : ``` m=prompt(); //get input a=0; c=1; //first fraction b=1; d=1; //second fraction n=eval(m); //evaluate input for (i=1; i<m.match(/\d+$/); i++) { //loop from 1 to input denominator f=Math.floor(n*i); if (n*i > f) { //if fraction not equal to simplification of input g=f+1; // f/i and g/i are fractions closer to input if (f/i>a/c) a=f, c=i; if (g/i<b/d) b=g; d=i; } } alert(a+'/'+c+' '+b+'/'+d); //output values handling 0 and 1 correctly ``` [Answer] # perl, 142 bytes (155 without CPAN) ``` use bare A..Z;$/="/";N=<>;D=<>;F=N/D;K=G=1;for$H(1..D){J<F&&J>E?(E,I):J>F&&J<G?(G,K):()=(J=$_/H,"$_/$H")for(Z=int F*H)..Z+1}print I||0," $K\n" ``` Or if CPAN modules are disallowed / 3-4 times faster code is needed: ``` $/="/";$N=<>;$D=<>;$F=$N/$D;$g=$G=1;for$d(1..$D){$f<$F&&$f>$E?($E,$e):$f>$F&&$f<$G?($G,$g):()=($f=$_/$d,"$_/$d")for($z=int$F*$d)..$z+1}print$e||0," $g\n" ``` The former version takes 9.55 seconds on my machine, the latter version 2.44 seconds. Less unreadable: ``` ($N, $D) = split(m[/], <>); $F = $N / $D; $G = 1; foreach $d (1 .. $D) { $z = int $F * $d; foreach $_ ($z .. $z + 1) { $f = $_ / $d; ($f < $F && $f > $E ? ($E, $e) : ($f > $F && $f < $G ? ($G, $g) : ())) = ($f, "$_/$d"); } } print $e || 0, ' ', $g || 1, "\n"; ``` ]
[Question] [ Write a program that inputs the dimensions of a painting, the matting width, and the frame width for a framed portrait. The program should output a diagram using the symbol `X` for the painting, `+` for the matting, and `#` for the framing. The symbols must be space-separated. Trailing whitespace is alright, as long as the output visually matches the criteria. The inputs can be `0`. INPUT: 3 2 1 2 (Width, Height, Matte Width, Frame Width) OUTPUT: [![First 3 and 2 are painting width and height. 1 is the matte width around it. 2 is the frame width around the whole thing.](https://i.stack.imgur.com/gVcgW.png)](https://i.stack.imgur.com/gVcgW.png) In text form: ``` # # # # # # # # # # # # # # # # # # # # + + + + + # # # # + X X X + # # # # + X X X + # # # # + + + + + # # # # # # # # # # # # # # # # # # # # ``` The winning code completes the conditions in the least possible bytes. [Answer] # [Python 2](https://docs.python.org/2/), 98 bytes ``` w,h,a,b=input() a*='+' b*='#' for c in b+a+h*'X'+a+b:print' '.join(min(c,d)for d in b+a+w*'X'+a+b) ``` [Try it online!](https://tio.run/##NcqxCoAgFEDR3a8QGp7mI8i2oP9o1SQ06ClhSF9vNjRc7nLSk30kXWtBjwbtEijdWUhm@gUUMNvWAdvjxTceiFtllO9hhXY7pytQBg7DEQOJs7Whkx92Py4/lrVOqHFE/QI "Python 2 – Try It Online") Prints a space-separated grid, strictly following the spec. I'm amused that `*=` is used to convert `a` and `b` from numbers to strings. Python 3 can save some bytes by avoiding `' '.join`, maybe more by using f-strings and assignment expressions. Thanks to Jo King for -2 bytes. **[Python 3](https://docs.python.org/3/), 93 bytes** ``` def f(w,h,a,b):a*='+';b*='#';[print(*[min(c,d)for d in b+a+w*'X'+a+b])for c in b+a+h*'X'+a+b] ``` [Try it online!](https://tio.run/##Pci7CoAgFADQXxEaro@7pFvRfwTR4CPRIRMJoq83CWo6cPJ9hiOpWt3miacXBtRo2KD5BAJG0@hgXHKJ6aR82WOiFh3zRyGOxESM0OLiMEPTrO/b78P/1VOFEnuUrD4 "Python 3 – Try It Online") [Answer] # JavaScript (ES6), ~~118 113~~ 107 bytes ``` (w,h,M,F)=>(g=(c,n)=>'01210'.replace(/./g,i=>c(i).repeat([F,M,n][i])))(y=>g(x=>'#+X'[x<y?x:y]+' ',w)+` `,h) ``` [Try it online!](https://tio.run/##VcuxCoMwFEDRvV9R6JD38FWNpUtp7ObWvSCCIY0xRRJRqfr1qY7dLgfuR37lqAbbT2fn3zo0IsBMLT2pQJGDEaDIbcVSnvGUxYPuO6k0JHFiyIpcgcUdtZygLLbNVaWtEBFWkRtYtvMUvVi53NfHcluriB0ZzRjVh5paDMq70Xc67ryBBi6UEacM8fDv112JI4Yf "JavaScript (Node.js) – Try It Online") ### Commented ``` (w, h, M, F) => ( // given the 4 input variables g = ( // g = helper function taking: c, // c = callback function returning a string to repeat n // n = number of times the painting part must be repeated ) => // '01210' // string describing the picture structure, with: .replace( // 0 = frame, 1 = matte, 2 = painting /./g, // for each character in the above string: i => // i = identifier of the current area c(i) // invoke the callback function .repeat // and repeat the result ... ([F, M, n][i]) // ... either F, M or n times ) // end of replace() )( // outer call to g: y => // callback function taking y: g( // inner call to g: x => // callback function taking x: '#+X' // figure out which character to use [x < y ? x : y] // according to the current position + ' ', // append a space w // repeat the painting part w times ) // end of inner call + '\n', // append a line feed h // repeat the painting part h times ) // end of outer call ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 24 bytes ``` &l,ithYaQ]'#+X'w)TFX*cYv ``` Input is: Height, Width, Matte Width, Frame Width. [Try it online!](https://tio.run/##y00syfn/Xy1HJ7MkIzIxMFZdWTtCvVwzxC1CKzmy7P9/Iy5jLkMuIwA) ### Explanation ``` &l % Take height and width implicitly. Push matrix of that size with all % entries equal to 1 , % Do twice i % Take input th % Duplicate, concatenate: gives a 1×2 vector with the number repeated Ya % Pad matrix with those many zeros vertically and horizontally Q % Add 1 to each entry ] % End '#+X' % Push this string w) % Index into the string with the padded matrix TF % Push row vector [1 0] X* % Kronecker product. This inserts columns of zeros c % Convert to char again. Char 0 is will be displayed as space Yv % Remove trailing spaces in each line. Implicitly display ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 142 bytes ``` (t=(p=Table)["# ",2(c=#4+#3)+#2,2c+#];p[t[[i,j]]="+ ",{j,z=#4+1,c+#3+#},{i,z,c+#3+#2}];p[t[[i,j]]="X ",{j,#3+z,c+#},{i,#3+z,c+#2}];""<>#&/@t)& ``` [Try it online!](https://tio.run/##VcuxCsIwFIXhVym5UBJyofTGTSN9BAcHIWSIodSUVopkaumzx7Tq4Hj4vzO6@GhHF4N3qdOJR80nfXX3oRWGQcGQuNdwkKCEBELyEuxxMtGYgL21mslslh7nDdWYs5Kw4hJw/g5a/w@3zyGnXez2NzbL2OkMZdVEUabLKzxjUTVFZxQS1kg2pTc "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~48~~ ~~47~~ 44 bytes ``` ≔×NXθ≔×NXηFE+#×Nι«≔⁺ι⁺θιθ≔⁺ι⁺ηιη»Eη⪫⭆θ⌊⟦ιλ⟧ ``` [Try it online!](https://tio.run/##hY2xDoIwEIZneYpLXa4RB3FkctQEQ6KDiXFAgnJJW6ClLsZnrwcykrjcJf99/31lXdiyKVQIO@foafBMunK4N63vj17fK4syBnERPDuZRv@pmqlHYwGzokWxWooYZmmSUsI7Wkwfc@UdUgzj7sbzzzgL1BMwyD5Rbsn0o4/zQ0MGTz1HzyHhVxkZ0l7jldvqNtQECLanIWwhgQ0kYf1SXw "Charcoal – Try It Online") Link is to verbose version of code. Note: Trailing space. Edit: Now uses @xnor's algorithm. Explanation: ``` ≔×NXθ≔×NXη ``` Input the width and height and convert them into strings of `X`s. ``` FE+#×Nι ``` Loop over the characters `+` and `#`, converting them into strings of length given by the remaining two inputs. Then loop over those two strings. ``` «≔⁺ι⁺θιθ≔⁺ι⁺ηιη» ``` Prefix and suffix the painting with the strings for the matting and framing. ``` Eη⪫⭆θ⌊⟦ιλ⟧ ``` Loop over the strings, taking the minimum of the horizontal and vertical characters, and then double-spacing the rows, implicitly printing each row on its own line. [Answer] # [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/wiki/Commands) / [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands) `--no-lazy`, ~~32~~ 31 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` и'Xׄ+#vyI©×UεX.ø}®FDнgy×.ø]€S» ``` Takes the input in the order `height, width, matte, frame`. If the input order specified in the challenge is strict (still waiting on OP for verification), a leading `s` (swap) can be added for +1 byte. Required the `--no-lazy` Elixir compiler flag in the new version of 05AB1E, since Elixir has some odd behavior due to lazy evaluation for nested maps/loops ([here the result without this flag](https://tio.run/##AT8AwP9vc2FiaWX//9C4J1jDl@KAnisjdnlJwqnDl1XOtVguw7h9wq5GRNC9Z3nDly7DuF3igqxTwrv//zMKNwozCjI)). [Try it online in the legacy version of 05AB1E.](https://tio.run/##AT8AwP8wNWFiMWX//9C4J1jDl@KAnisjdnlJwqnDl1XOtVguw7h9wq5GRNC9Z3nDly7DuF3igqxTwrv//zMKNwozCjI) [Try it online in the new version of 05AB1E with added `--no-lazy` flag.](https://tio.run/##AUkAtv9vc2FiaWX//9C4J1jDl@KAnisjdnlJwqnDl1XOtVguw7h9wq5GRNC9Z3nDly7DuF3igqxTwrv//zMKNwozCjL/LS1uby1sYXp5) **Explanation:** ``` и # Repeat the second (implicit) input the first (implicit) input amount of # times as list 'X× '# Repeat "X" that many times „+#v # Loop `y` over the characters ["+","#"]: y # Push character `y` I # Push the next input (matte in the first iteration; frame in the second) © # And store it in the register (without popping) × # Repeat character `y` that input amount of times U # Pop and store that string in variable `X` εX.ø} # Surround each string in the list with string `X` ®F # Inner loop the value from the register amount of times: Dнg # Get the new width by taking the length of the first string y× # Repeat character `y` that many times .ø # And surround the list with this leading and trailing string ] # Close both the inner and outer loops €S # Convert each inner string to a list of characters » # Join every list of characters by spaces, and then every string by newlines # (and output the result implicitly) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 17 bytes ``` ;ŒB“#+X+#”xʋⱮ«Ɱ/G ``` [Try it online!](https://tio.run/##y0rNyan8/9/66CSnRw1zlLUjtJUfNcytONX9aOO6Q6uBhL77////o410FAxj/0cb6ygYxQIA "Jelly – Try It Online") Argument 1: `[Frame width, Matte width]` Argument 2: `[Width, Height]` [Answer] # [Canvas](https://github.com/dzaima/Canvas), 24 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md) ``` X;«[lx*e⤢} X×*+⁸#⁸ *J ×O ``` [Try it here!](https://dzaima.github.io/Canvas/?u=JXVGRjM4JXVGRjFCJUFCJXVGRjNCJXVGRjRDJXVGRjU4JXVGRjBBJXVGRjQ1JXUyOTIyJXVGRjVEJTBBWCVENyV1RkYwQSsldTIwNzglMjMldTIwNzglMjAldUZGMEEldUZGMkElMjAlRDcldUZGMkY_,i=MyUwQTIlMEExJTBBMg__,v=8) Should be 5 bytes shorter, but isn't because Canvas is buggy.. [Answer] # [R](https://www.r-project.org/), 119 bytes ``` function(w,h,m,f)write(Reduce(function(x,y)rbind(y,cbind(y,x,y),y),rep(c("+","#"),c(m,f)),matrix("X",w,h)),1,w+2*f+2*m) ``` [Try it online!](https://tio.run/##PYzBCsIwEER/RdbLrp0ejFe/wpPXmiY1h0RZUtJ@fUygCDMMvIGndTndx@rXZHP4JC54I8JL0ZAdP9y8Wsf/d8Mu@gpp5h322M561H3ZMg0EOpPActcI4pQ1bExPQnM3cEUZzMW3RqkL32AaMlJ/ "R – Try It Online") [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~116~~ ~~115~~ 113 bytes ``` lambda a,b,c,d:"\n".join((g:=['#'*(a+2*c+2*d)]*d+[(h:='#'*d)+'+'*(a+c*2)+h]*c)+[h+'+'*c+'X'*a+'+'*c+h]*b+g[::-1]) ``` [Try it online!](https://tio.run/##LYnLCsMgEEV/JaQLZxxbiNkUwf8oGBc@QkxpjYRs@vXWhi7u4XJO@Rxpy@O97HXWU325t4@uc8KLIKLqp9zfntuaARalDbswDo4kD20RLY9kICn98xGJ0ZkDl0jJ8oBk0ikDsQfj7v9b8rQYpa6DxVr2NR8wwyg6KbqhEbF@AQ "Python 3.8 (pre-release) – Try It Online") First attempt at golfing, will be improved soon. `a` is width, `b` is height, `c` is matte width, and `d` is frame width. *-1 bytes using the `:=` operator to define `h` as `e * d`* *-2 bytes thanks to Jo King suggesting me to remove the e and f parameters* **EXPLANATION:** ``` lambda a,b,c,d: Define a lambda which takes in arguments a, b, c, and d (The width of the painting, the height of the painting, the padding of the matte, and the padding of the frame width, respectively). "\n".join( Turn the list into a string, where each element is separated by newlines (g:= Define g as (while still evaling the lists)... ['#'*(a+2*c+2*d)]*d+ Form the top rows (the ones filled with hashtags) [(h:='#'*d)+'+'*(a+c*2)+h]*c Form the middle-top rows (uses := to golf this section) )+ [h+'+'*c+'X'*a+'+'*c+h]*b+ Form the middle row g[::-1] Uses g to golf the code (forms the entire middle-bottom-to-bottom) ) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~35~~ ~~31~~ ~~28~~ 24 bytes ``` Dịx@“#+X+#” ⁽-Fç«þ⁽-ȥç$G ``` [Try it online!](https://tio.run/##y0rNyan8/9/l4e7uCodHDXOUtSO0lR81zOV61LhX1@3w8kOrD@8DMU8sPbxcxf3///9GOiY6ZjpGAA "Jelly – Try It Online") Takes the input in the order frame, matte, width, height; comma separated. Outputs the ASCII-art picture with frame and matte. If the input order is strict I’d need to add more bytes (as per my original post). Couple of golfs based on @EriktheOutgolfer’s answer; I’d realised the characters were in ASCII order but hadn’t thought how best to take advantage of that, and had forgotten about `G`. His is still a better answer though! [Answer] # [Husk](https://github.com/barbuz/Husk), ~~29~~ 25 bytes ``` mm;₁'#⁰₁'+²RR'X ‼‼(m↔Tm+R ``` [Try it online!](https://tio.run/##yygtzv7/PzfX@lFTo7ryo8YNIFr70KagIPUIrkcNe4BII/dR25SQXO2g////G/43@m/83wgA "Husk – Try It Online") Ah, this was convoluted. The input order is `Matte,Frame,Width,Height`. -4 bytes after simplifying function 2 & 3. ## Explanation ``` Function ₁: framing function ‼‼(m↔Tm+R parameters a(char),n(int),m(matrix) m+R add a side T Transpose m↔ reverse each row ‼‼( repeat that 3 more times Function ₀: main mm;₁'#⁰₁'+²RR'X RR'X make width × height matrix of 'X'es ₁'+² add the matte of '+'es ₁'#⁰ add the frame of '#'es mm; nest each character(adds spaces) ``` [Answer] # Javascript, 158 bytes ``` (w,h,m,f)=>(q="repeat",(z=("#"[q](w+2*(m+f)))+` `)[q](f))+(x=((e="#"[q](f))+(r="+"[q](m))+(t="+"[q](w))+r+e+` `)[q](m))+(e+r+"X"[q](w)+r+e+` `)[q](h)+x+z) ``` Can probably be trimmed down a little bit ``` f= (w,h,m,f)=>(q="repeat",(z=("# "[q](w+2*(m+f))+` `)[q](f))+(x=((e="# "[q](f))+(r="+ "[q](m))+(t="+ "[q](w))+r+e+` `)[q](m))+(e+r+"X "[q](w)+r+e+` `)[q](h)+x+z) console.log(f(3,2,1,2)) ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 98 bytes ``` {map(&min,[X] map (($_='#'x$^d~'+'x$^c)~'X'x*~.flip).comb,$^a,$^b).rotor($b+2*($c+$d)).join("\n")} ``` [Try it online!](https://tio.run/##JYfRCoIwFEDf@4qxhrtXx8AJvYj/IVTGpg0mzon1oET@@lLicDic6TkPl@hXklhSkfjxeoLEu1Fc6zvZhwCwR8XPfGFNt/HsaIsbr/mSbtIObkLZBm8Ea/SuQTmHd5iBmUylwNqMdYiyD24EehspfuNLr8RCIZTIhcLydDyl/1pQotjJsYw/ "Perl 6 – Try It Online") This is a port of [xnor's Python answer](https://codegolf.stackexchange.com/a/181785/76162). # [Perl 6](https://github.com/nxadm/rakudo-pkg), 115 bytes ``` ->\a,\b,\c,\d{$_=['#'xx$!*2+a]xx($!=c+d)*2+b;.[d..^*-d;d..^a+$!+c]='+'xx*;.[$!..^*-$!;$!..^a+$!]='X'xx*;.join(" ")} ``` [Try it online!](https://tio.run/##JcvLCsIwEAXQfb8iicHmMS00BTchfofQVEkbC4ovdJMifntMWmZx7@Uwr/P7tov3GW0nZFCs9taBHcCOYP2XnkxXbsoQKBZKuj4ERrEZpedpDrrufF0fReV1TicplmNvSpkeREKKF6VYLy170sOq1@flwUhB@C9@3Iwm1oKCBhTXRd6ErDkxBW26huv4Bw "Perl 6 – Try It Online") Roughly golfed anonymous codeblock utilising Perl 6's multi-dimensional list assignment. For example, `@a[1;2] = 'X';` will assign `'X'` to the element with index 2 from the list with index 1, and `@a[1,2,3;3,4,5]='X'xx 9;` will replace all the elements with indexes `3,4,5` of the lists with indexes `1,2,3` with `'X'`. ### Explanation: First, we initialise the list as a `a+2*(c+d)` by `b+2*(c+d)` rectangle of `#`s. ``` $_=['#'xx$!*2+a]xx($!=c+d)*2+a; State: # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ``` Then we assign the inner rectangle of `+`s ``` .[d..^*-d;d..^a+$!+c]='+'xx*; State: # # # # # # # # # # # # # # # # # # # # + + + + + # # # # + + + + + # # # # + + + + + # # # # + + + + + # # # # # # # # # # # # # # # # # # # # ``` Finally, the innermost rectangle of `X`s. ``` .[$!..^*-$!;$!..^a+$!]='X'xx*; # # # # # # # # # # # # # # # # # # # # + + + + + # # # # + X X X + # # # # + X X X + # # # # + + + + + # # # # # # # # # # # # # # # # # # # # ``` [Answer] # Perl 5, 115 bytes ``` $_=(X x$F[0].$/)x$F[1];sub F{s,^|\z,/.*/;$_[0]x"@+".$/,ge,s/^|(?= )/$_[0]/gm while$_[1]--}F('+',$F[2]);F('#',$F[3]) ``` [TIO](https://tio.run/##K0gtyjH9/18l3lYjQqFCxS3aIFZPRV8TxDKMtS4uTVJwqy7WiauJqdLR19PSt1aJB6qoUHLQVgIq00lP1SnWj6vRsLfl0tQHS@mn5yqUZ2TmpAJ5hrG6urVuGura6jpA44xiNa2BHGUwxzhW8/9/YwUjBUMFIy5DBRMgy@hffkFJZn5e8X/dxIIcAA) [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 132 bytes ``` param($w,$h,$m,$f)filter l{"$(,'#'*$f+,$_[0]*$m+,$_[1]*$w+,$_[0]*$m+,'#'*$f)"}($a=@('##'|l)*$f) ($b=@('++'|l)*$m) @('+X'|l)*$h $b $a ``` [Try it online!](https://tio.run/##TcrBCgIhFIXhvU8h4wF1vIuamGXQYwQR4YBioDRY4KJ6dsvctPvPx1lvxeV7cDHWutpsk0IhBEIieO2v8eEyj88BiqSQI7whXE6b84j0q@23yr/1lx7eCnZ/UFII@Yq6EVNYmhjTJWnW1rGvwLAw2FrrzCe@49MH "PowerShell – Try It Online") ]
[Question] [ ​Your task is to write a program or function that outputs the first character of its source code, then the second, then the third... each time it is run. For example, if your program was `foo` in language `bar` in file `baz.bar`, then you should get output similar to this: ``` λ bar baz.bar f λ bar baz.bar o λ bar baz.bar o ``` Your program can do anything once its done printing its source code in this fashion. You may modify the source code for the file, but remember that the source code to be printed is the *original* source code. This is a code-golf, so the shortest program in bytes wins. [Answer] # Javascript - 26 bytes Defines `f()` that returns the source code character by character. ``` n=0;f=x=>("n=0;f="+f)[n++] ``` Returns undefined after it runs out of characters. ``` n=0;f=x=>("n=0;f="+f)[n++] for(i=0;i<30;i++){console.log(f())} //test harness ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes ``` “;⁾vṾ®ȯ©Ḣ”vṾ ``` This is a niladic link. [Try it online!](https://tio.run/nexus/jelly#@/@oYY71o8Z9ZQ937ju07sT6Qysf7lj0qGEuiP//0CJrQug/AA "Jelly – TIO Nexus") (Includes code to call the link twelve times.) ### How it works ``` “;⁾vṾ®ȯ©Ḣ”vṾ Niladic link. “;⁾vṾ®ȯ©Ḣ” Set the left argument and the return value to s =: ';⁾vṾ®ȯ©Ḣ'. Ṿ Uneval; yield r =: '“;⁾vṾ®ȯ©Ḣ”', a string representation of s. v Eval; execute s as a Jelly program with argument r. ⁾vV Yield 'vṾ'. ; Concatenate r and 'vṾ', yielding q =: '“;⁾vṾ®ȯ©Ḣ”vṾ'. ®ȯ Take the flat logical OR of the register (initially 0) and q. This replaces 0 with q in the first run, but it will yield the content of the register in subsequent runs. © Copy the result to the register. Ḣ Head; pop and yield the first character of the register. This modifies the string in the register, so it holds one fewer character after each call. ``` As an added bonus, since the register will hold an empty string after the twelveth call, it is once again falsy and the link is ready to start over. Calling the link 24 times will output the source code twice, calling it 36 times thrice, etc. [Answer] # [stacked](https://github.com/ConorOBrien-Foxx/stacked/), noncompeting, 34 bytes ``` [tostr ':!' + execCounter # out]:! ``` A variation on the standard quine. This is a full program. This uses `execCounter` to get how many times this program specifically was run. Errors after outputting everything. [Try it here!](https://conorobrien-foxx.github.io/stacked/stacked.html) [Answer] # [Pip](https://github.com/dloscutoff/pip), 31 bytes ``` {Y"{Y (yRsRPy++v)}"(yRsRPy++v)} ``` An anonymous function. [Test it on TIO!](https://tio.run/nexus/pip#@59mVR2pVB2poFEZVBwUUKmtXaZZq4TM4fJRMDbkUvBX0EhTMND8/x8A "Pip – TIO Nexus") ### Explanation Start with this standard Pip quine: ``` Y"Y yRsRPy"yRsRPy Y"Y yRsRPy" Yank that string into y yRsRPy In y, replace the space with repr(y) ``` Wrap this in curly braces to make it a function. Now, instead of returning the whole source, we need to index into it. Using a global variable for the index and incrementing it each time will fulfill the "next character each time it's called" requirement. `v` is the best candidate because it is preinitialized to `-1`. Incrementing it the first time gives an index of `0`, next time `1`, etc. Pip has cyclical indexing, so once the function prints its last character, it will start over at the beginning. [Answer] # Python, 90 bytes An extension on the standard Python quine (golfing tips welcome): ``` def f(n=0,s='def f(n=0,s=%r):\n while 1:yield(s%%s)[n];n+=1'): while 1:yield(s%s)[n];n+=1 ``` This is a python [generator function](https://wiki.python.org/moin/Generators), meaning that you iterate over it, and each iteration provides the next character in the source code. When all the characters have been returned, this crashes with `IndexError`. For testing, simply append this script to the end of the program: ``` source = '' try: # Call generator, add characters to the string for char in f(): source += char except IndexError: # Generator has reached end of source code pass print(source) ``` ## Or [**try it online!**](https://tio.run/nexus/python3#ZY7LisMwDEX3/ooLJSShXbTbFK/KMPQbZrowtlIHghwkl2m/PuO@aKHaiXN1j@ZAPfqG7Xqltn5fKmm7X8ZfHEbCprsMNIZGq0rbHz5seWk3dduZD/7Cs6aTeIJFXZsslxLGAjs3jjgSk7icZAUXAnx04nwmUeSEHAmaZeBjOeiT3DAGLp9dhWUexUt7Q4bOnqaMPQc6f4kkuZu@nxJEpxByPlIAcUDqnxU@BSrhyakaMxVnbkrA3mk7/wM) [Answer] ## [\*><>](https://esolangs.org/wiki/Starfish), ~~13~~ 21 bytes ``` " r:2+a1Fi1+:1F1+[ro; ``` Creates a file named `\n` to keep track of the index. This may be able to be golfed more, but nothing immediately jumps out at me ... ### Output ``` $ starfish incrementalquine.sf "$ starfish incrementalquine.sf $ starfish incrementalquine.sf r$ starfish incrementalquine.sf :$ starfish incrementalquine.sf 2$ starfish incrementalquine.sf +$ starfish incrementalquine.sf a$ starfish incrementalquine.sf 1$ starfish incrementalquine.sf F$ starfish incrementalquine.sf i$ starfish incrementalquine.sf 1$ starfish incrementalquine.sf +$ starfish incrementalquine.sf :$ starfish incrementalquine.sf 1$ starfish incrementalquine.sf F$ starfish incrementalquine.sf 1$ starfish incrementalquine.sf +$ starfish incrementalquine.sf [$ starfish incrementalquine.sf r$ starfish incrementalquine.sf o$ starfish incrementalquine.sf ;$ starfish incrementalquine.sf ``` ### Explanation ``` " r:2+ build the quine a1F open file named "\n" i1+: read input, increment by 1, duplicate 1F save incremented input to file 1+[ increment input, copy that many values to a new stack ro output the character at the beginning of the new stack ; end ``` ### Cheating Incremental Quine ``` a1Fi1+:0go1F; ``` **Explanation** ``` a1F open file named "\n" i1+ read input and add 1 to it :0g push the value at (input,0) to the stack o output the value 1F save the incremented input to the file ; exit ``` [Answer] # Mathematica, 91 bytes Comments very welcome; I'm still learning the ropes about what quines are proper quines. ``` (If[!NumberQ[q], q = 0]; StringTake[ToString[#0]<>FromCharacterCode[{91, 93}], {++q}]) & [] ``` Defines a function called repeatedly with no arguments. After the 91st call, it throws a big error and returns unevaluated. There were two issues to overcome: first, I wanted to just use `StringTake[ToString[#0]<>"[]"]`, but `ToString[]` seems to erase the quotation marks; so I had to replace `"[]"` by `FromCharacterCode[{91, 93}]`. Second, Mathematica variables start out uninitialized, so I can't call `++q` before `q` is defined; this is why the initial `If[!NumberQ[q], q = 0]` is needed. Irrelevant coda: while looking up `NumberQ`, I learned that Mathematica has a function called `TrueQ` ... which, yes, returns `True` if the argument is `True` and `False` if the argument is `False`! (The utility is that it returns `False` on all other arguments as well.) [Answer] # Microscript II, ~~40~~ 33 bytes A code block literal, the language's closest equivalent to a function: ``` {ss1K+>K>s#<v{o}sl*v!(123v)lKp<o} ``` After running, it puts itself back into `x` to make it easier to invoke again. [Answer] # Bash (and zsh, ksh), 39-bytes ``` a=`<$0`;pwd>>0;echo ${a:`wc -l<0`-1:1} ``` It prints nothing after once the program is printed out. Ensure `0` does not exists in the current directory and run: ``` bash iquine.bash ``` ]
[Question] [ The [Chinese Remainder Theorem](http://en.wikipedia.org/wiki/Chinese_remainder_theorem) tells us that we can always find a number that produces any required remainders under different prime moduli. Your goal is to write code to output such a number in polynomial time. Shortest code wins. For example, say we're given these constraints: * \$n \equiv 2 \mod 7\$ * \$n \equiv 4 \mod 5\$ * \$n \equiv 0 \mod 11\$ One solution is \$n=44\$. The first constraint is satisfied because \$44 = 6\times7 + 2\$, and so \$44\$ has remainder \$2\$ when divided by \$7\$, and thus \$44 \equiv 2 \mod 7\$. The other two constraints are met as well. There exist other solutions, such as \$n=814\$ and \$n=-341\$. **Input** A non-empty list of pairs \$(p\_i,a\_i)\$, where each modulus \$p\_i\$ is a distinct prime and each target \$a\_i\$ is a natural number in the range \$0 \le a\_i < p\_i\$. You can take input in whatever form is convenient; it doesn't have to actually be a list of pairs. You may not assume the input is sorted. **Output** An integer \$n\$ such that \$n \equiv a\_i \mod p\_i\$ for each index \$i\$. It doesn't have to be the smallest such value, and may be negative. **Polynomial time restriction** To prevent cheap solutions that just try \$n=0, 1, 2, \dots\$, and so on, your code must run in polynomial time in the *length of the input*. Note that a number \$m\$ in the input has length \$Θ(\log m)\$, so \$m\$ itself is not polynomial in its length. This means that you can't count up to \$m\$ or do an operation \$m\$ times, but you can compute arithmetic operations on the values. You may not use an inefficient input format like unary to get around this. **Other bans** Built-ins to do the following are not allowed: Implement the Chinese Remainder theorem, solve equations, or factor numbers. You may use built-ins to find mods and do modular addition, subtraction, multiplication, and exponentiation (with natural-number exponent). You *may not* use other built-in modular operations, including modular inverse, division, and order-finding. **Test cases** These give the smallest non-negative solution. Your answer may be different. It's probably better if you check directly that your output satisfies each constraint. ``` [(5, 3)] 3 [(7, 2), (5, 4), (11, 0)] 44 [(5, 1), (73, 4), (59, 30), (701, 53), (139, 112)] 1770977011 [(982451653, 778102454), (452930477, 133039003)] 68121500720666070 ``` [Answer] # Mathematica, ~~55~~ ~~51~~ 45 Modular inverse is banned, but modular exponentiation is allowed. By Fermat's little theorem, `n^(-1) % p == n^(p-2) % p`. ``` (PowerMod[x=1##&@@#/#,#-2,#]x).#2&@@Thread@#& ``` Example: ``` In[1]:= f = (PowerMod[x=1##&@@#/#,#-2,#]x).#2&@@Thread@#&; In[2]:= f[{{5, 3}}] Out[2]= 3 In[3]:= f[{{7, 2}, {5, 4}, {11, 0}}] Out[3]= 1584 In[4]:= f[{{5, 1}, {73, 4}, {59, 30}, {701, 53}, {139, 112}}] Out[4]= 142360350966 ``` --- Just for fun: ``` ChineseRemainder@@Reverse@Thread@#& ``` [Answer] ## Python 2, ~~165~~ ~~101~~ ~~99~~ ~~98~~ 85 bytes Using Fermat's little theorem like the other answers. Doesn't bother with keeping final sum within modular range, since we're not interested in the smallest solution. Thanks Volatility for saving 13 bytes. ``` l=input();x=reduce(lambda a,b:a*b[0],l,1) print sum(x/a*b*pow(x/a,a-2,a)for a,b in l) [(5, 3)] 3 [(7, 2), (5, 4), (11, 0)] 1584 [(5, 1), (73, 4), (59, 30), (701, 53), (139, 112)] 142360350966 ``` [Answer] # Pyth, 40 37 36 29 ``` M*G.^G-H2Hsm*edg/u*GhHQ1hdhdQ ``` Uses Fermat's little theorem, thanks to alephalpha. Computes using [this formula](http://en.wikipedia.org/wiki/Chinese_remainder_theorem#General_case). [Answer] **Ruby, 129** Well, comrades, it seems Ruby solutions must be longer because modular exponentiation is not available without loading openssl library and doing conversions to OpenSSL::BN. Still, had fun writing it: ``` require("openssl") z=eval(gets) x=1 z.map{|a,b|x*=a} s=0 z.map{|a,b|e=a.to_bn;s+=(x/a).to_bn.mod_exp(e-2,e).to_i*b*x/a} puts(s) ``` [Answer] # Python 2, 61 ``` n=P=1 for p,a in input():n+=P*(a-n)*pow(P,p-2,p);P*=p print n ``` This employs a variation of [the product construction](http://en.wikipedia.org/wiki/Chinese_remainder_theorem#General_case) that other answers use. The idea is to loop over the constraints and update the solution `n` to meet the current constraint without messing up the prior ones. To do so, we track the product `P` of the primes seen up to now, and observe that adding a multiple of `P` has no effect modulo any already-seen prime. So, we just need to change `n` to satisfy `n%p == a` by adding the right multiple of `P`. We solve for the coefficient `c`: `(n + P*c) % p == a` This requires that `c = (a-n) * P^(-1)`, where the inverse is taken modulo `p`. As others note, the inverse can be computed by Fermat's Little Theorem as `P^(-1) = pow(P,p-2,p)`. So, `c = (a-n) * pow(P,p-2,p)`, and we update `n` by `n+= P * (a-n) * pow(P,p-2,p)`. [Answer] # Haskell, ~~68~~ 100 bytes ``` f l=sum[p#(m-2)*n*p|(m,n)<-l,let a#0=1;a#n=(a#div n 2)^2*a^mod n 2`mod`m;p=product(map fst l)`div`m] ``` Usage: `f [(5,1), (73,4), (59,30), (701,53), (139,112)]` -> `142360350966`. Edit: now with a fast "power/mod" function. Old version (68 bytes) with inbuilt power function: ``` f l=sum[l#m^(m-2)`mod`m*n*l#m|(m,n)<-l] l#m=product(map fst l)`div`m ``` ]
[Question] [ **Background:** I originally posted this question last night, and received backlash on its vagueness. I have since consulted many personnel concerning not only the wording of the problem, but also its complexity (which is not O(1)). This programming problem is an evil spin on an Amazon interview question. **Question:** Given a String of randomly concatenated integers [0, 250), 0 to 250 exclusive, there is ONE number missing in the sequence. Your job is to write a program that will calculate this missing number. There are no other missing numbers in the sequence besides the one, and that is what makes this problem so difficult, and possibly computationally hard. Doing this problem by hand on smaller Strings, such as examples 1 and 2 below are obviously very easy. Conversely, computing a missing number on incredibly large datasets involving three-digit or four-digit numbers would be incredibly difficult. The idea behind this problem is to construct a program that will do this process FOR you. **Important Information:** One thing that appeared as rather confusing when I posted this problem last night was: what exactly a missing number is defined as. A missing number is the number INSIDE of the range specified above; NOT necessarily the digit. In example 3, you will see that the missing number is 9, even though it appears in the sequence. There are 3 places the DIGIT 9 will appear in a series of [0, 30): “9”, “19”, and “29”. Your objective is to differentiate between these, and discover that 9 is the missing NUMBER (inside of example 3). In other words, the tricky part lies in finding out which sequences of digits are complete and which belong to other numbers. **Input:** The input is a String S, containing integers from 0 to 249 inclusive, or 0 to 250 exclusive (in other words, [0, 250)). These integers, as stated above, are scrambled up to create a random sequence. There are NO delimiters (“42, 31, 23, 44”), or padding 0’s (003076244029002); the problems are exactly as described in the examples. **It is guaranteed that there is only 1 solution in the actual problems. Multiple solutions are not permitted for these.** **Winning Criteria:** Whoever has the fastest, and lowest memory usage will be the winner. In the miraculous event that a time ties, lower memory will be used for the time breaker. Please list Big O if you can! **Examples:** *Examples 1 and 2 have a range of [0, 10)* *Examples 3 and 4 have a range of [0, 30)* (Examples 1-4 are just for demonstration. Your program needn't to handle them.) *Examples 5 has a range of [0, 250)* ``` 1. 420137659 - Missing number => 8 2. 843216075 - Missing number => 9 3. 2112282526022911192312416102017731561427221884513 - Missing number => 9 4. 229272120623131992528240518810426223161211471711 - Missing number => 15 5. 11395591741893085201244471432361149120556162127165124233106210135320813701207315110246262072142253419410247129611737243218190203156364518617019864222241772384813041175126193134141008211877147192451101968789181153241861671712710899168232150138131195104411520078178584419739178522066640145139388863199146248518022492149187962968112157173132551631441367921221229161208324623423922615218321511111211121975723721911614865611197515810239015418422813742128176166949324015823124214033541416719143625021276351260183210916421672722015510117218224913320919223553222021036912321791591225112512304920418584216981883128105227213107223142169741601798025 - Missing number => 71 Test Data: Problem 1: 6966410819610521530291368349682309217598570592011872022482018312220241246911298913317419721920718217313718080857232177134232481551020010112519172652031631113791105122116319458153244261582135510090235116139611641267691141679612215222660112127421321901862041827745106522437208362062271684640438174315738135641171699510421015199128239881442242382361212317163149232839233823418915447142162771412092492141987521710917122354156131466216515061812273140130240170972181176179166531781851152178225242192445147229991613515911122223419187862169312013124150672371432051192510724356172282471951381601241518410318414211212870941111833193145123245188102 Problem 2: 14883423514241100511108716621733193121019716422221117630156992324819917158961372915140456921857371883175910701891021877194529067191198226669314940125152431532281961078111412624224113912011621641182322612016512820395482371382385363922471472312072131791925510478122073722091352412491272395020016194195116236186596116374117841971602259812110612913254255615723013185162206245183244806417777130181492211412431591541398312414414582421741482461036761192272120204114346205712198918190242184229286518011471231585109384415021021415522313136146178233133168222201785172212108182276835832151134861116216716910511560240392170208215112173234136317520219 Problem 3: 1342319526198176611201701741948297621621214122224383105148103846820718319098731271611601912137231471099223812820157162671720663139410066179891663131117186249133125172622813593129302325881203242806043154161082051916986441859042111711241041590221248711516546521992257224020174102234138991752117924457143653945184113781031116471120421331506424717816813220023315511422019520918114070163152106248236222396919620277541101222101232171732231122301511263822375920856142187182152451585137352921848164219492411071228936130762461191564196185114910118922611881888513917712153146227193235347537229322521516718014542248813617191531972142714505519240144 Problem 4: 2492402092341949619347401841041875198202182031161577311941257285491521667219229672211881621592451432318618560812361201172382071222352271769922013259915817462189101108056130187233141312197127179205981692121101632221732337196969131822110021512524417548627103506114978204123128181211814236346515430399015513513311152157420112189119277138882021676618323919018013646200114160165350631262167910238144334214230146151171192261653158161213431911401452461159313720613195248191505228186244583455139542924222112226148941682087115610915344641782142472102436810828123731134321131241772242411722251997612923295223701069721187182171471055710784170217851 ``` [Answer] # [Clingo](https://potassco.org/clingo/), ≈ 0.03 seconds This is too fast to be accurately measured—you’ll need to allow larger input cases rather than artificially stopping at 250. ``` % cat(I) means digits I and I+1 are part of the same number. {cat(I)} :- digit(I, D), digit(I+1, E). % prefix(I, X) means some digits ending at I are part of the same % number prefix X. prefix(I, D) :- digit(I, D), not cat(I-1), D < n. prefix(I, 10*X+D) :- prefix(I-1, X), digit(I, D), cat(I-1), X > 0, 10*X+D < n. % Every digit is part of some prefix. :- digit(I, D), {prefix(I, X)} = 0. % If also not cat(I), then this counts as an appearance of the number % X. appears(I, X) :- prefix(I, X), not cat(I). % No number appears more than once. :- X=0..n-1, {appears(I, X)} > 1. % missing(X) means X does not appear. missing(X) :- X=0..n-1, {appears(I, X)} = 0. % Exactly one number is missing. :- {missing(X)} != 1. #show missing/1. ``` ### Example input Input is a list of (*k*, *k*th digit) pairs. Here is problem 1: ``` #const n = 250. digit(0,6;1,9;2,6;3,6;4,4;5,1;6,0;7,8;8,1;9,9;10,6;11,1;12,0;13,5;14,2;15,1;16,5;17,3;18,0;19,2;20,9;21,1;22,3;23,6;24,8;25,3;26,4;27,9;28,6;29,8;30,2;31,3;32,0;33,9;34,2;35,1;36,7;37,5;38,9;39,8;40,5;41,7;42,0;43,5;44,9;45,2;46,0;47,1;48,1;49,8;50,7;51,2;52,0;53,2;54,2;55,4;56,8;57,2;58,0;59,1;60,8;61,3;62,1;63,2;64,2;65,2;66,0;67,2;68,4;69,1;70,2;71,4;72,6;73,9;74,1;75,1;76,2;77,9;78,8;79,9;80,1;81,3;82,3;83,1;84,7;85,4;86,1;87,9;88,7;89,2;90,1;91,9;92,2;93,0;94,7;95,1;96,8;97,2;98,1;99,7;100,3;101,1;102,3;103,7;104,1;105,8;106,0;107,8;108,0;109,8;110,5;111,7;112,2;113,3;114,2;115,1;116,7;117,7;118,1;119,3;120,4;121,2;122,3;123,2;124,4;125,8;126,1;127,5;128,5;129,1;130,0;131,2;132,0;133,0;134,1;135,0;136,1;137,1;138,2;139,5;140,1;141,9;142,1;143,7;144,2;145,6;146,5;147,2;148,0;149,3;150,1;151,6;152,3;153,1;154,1;155,1;156,3;157,7;158,9;159,1;160,1;161,0;162,5;163,1;164,2;165,2;166,1;167,1;168,6;169,3;170,1;171,9;172,4;173,5;174,8;175,1;176,5;177,3;178,2;179,4;180,4;181,2;182,6;183,1;184,5;185,8;186,2;187,1;188,3;189,5;190,5;191,1;192,0;193,0;194,9;195,0;196,2;197,3;198,5;199,1;200,1;201,6;202,1;203,3;204,9;205,6;206,1;207,1;208,6;209,4;210,1;211,2;212,6;213,7;214,6;215,9;216,1;217,1;218,4;219,1;220,6;221,7;222,9;223,6;224,1;225,2;226,2;227,1;228,5;229,2;230,2;231,2;232,6;233,6;234,0;235,1;236,1;237,2;238,1;239,2;240,7;241,4;242,2;243,1;244,3;245,2;246,1;247,9;248,0;249,1;250,8;251,6;252,2;253,0;254,4;255,1;256,8;257,2;258,7;259,7;260,4;261,5;262,1;263,0;264,6;265,5;266,2;267,2;268,4;269,3;270,7;271,2;272,0;273,8;274,3;275,6;276,2;277,0;278,6;279,2;280,2;281,7;282,1;283,6;284,8;285,4;286,6;287,4;288,0;289,4;290,3;291,8;292,1;293,7;294,4;295,3;296,1;297,5;298,7;299,3;300,8;301,1;302,3;303,5;304,6;305,4;306,1;307,1;308,7;309,1;310,6;311,9;312,9;313,5;314,1;315,0;316,4;317,2;318,1;319,0;320,1;321,5;322,1;323,9;324,9;325,1;326,2;327,8;328,2;329,3;330,9;331,8;332,8;333,1;334,4;335,4;336,2;337,2;338,4;339,2;340,3;341,8;342,2;343,3;344,6;345,1;346,2;347,1;348,2;349,3;350,1;351,7;352,1;353,6;354,3;355,1;356,4;357,9;358,2;359,3;360,2;361,8;362,3;363,9;364,2;365,3;366,3;367,8;368,2;369,3;370,4;371,1;372,8;373,9;374,1;375,5;376,4;377,4;378,7;379,1;380,4;381,2;382,1;383,6;384,2;385,7;386,7;387,1;388,4;389,1;390,2;391,0;392,9;393,2;394,4;395,9;396,2;397,1;398,4;399,1;400,9;401,8;402,7;403,5;404,2;405,1;406,7;407,1;408,0;409,9;410,1;411,7;412,1;413,2;414,2;415,3;416,5;417,4;418,1;419,5;420,6;421,1;422,3;423,1;424,4;425,6;426,6;427,2;428,1;429,6;430,5;431,1;432,5;433,0;434,6;435,1;436,8;437,1;438,2;439,2;440,7;441,3;442,1;443,4;444,0;445,1;446,3;447,0;448,2;449,4;450,0;451,1;452,7;453,0;454,9;455,7;456,2;457,1;458,8;459,1;460,1;461,7;462,6;463,1;464,7;465,9;466,1;467,6;468,6;469,5;470,3;471,1;472,7;473,8;474,1;475,8;476,5;477,1;478,1;479,5;480,2;481,1;482,7;483,8;484,2;485,2;486,5;487,2;488,4;489,2;490,1;491,9;492,2;493,4;494,4;495,5;496,1;497,4;498,7;499,2;500,2;501,9;502,9;503,9;504,1;505,6;506,1;507,3;508,5;509,1;510,5;511,9;512,1;513,1;514,1;515,2;516,2;517,2;518,2;519,3;520,4;521,1;522,9;523,1;524,8;525,7;526,8;527,6;528,2;529,1;530,6;531,9;532,3;533,1;534,2;535,0;536,1;537,3;538,1;539,2;540,4;541,1;542,5;543,0;544,6;545,7;546,2;547,3;548,7;549,1;550,4;551,3;552,2;553,0;554,5;555,1;556,1;557,9;558,2;559,5;560,1;561,0;562,7;563,2;564,4;565,3;566,5;567,6;568,1;569,7;570,2;571,2;572,8;573,2;574,4;575,7;576,1;577,9;578,5;579,1;580,3;581,8;582,1;583,6;584,0;585,1;586,2;587,4;588,1;589,5;590,1;591,8;592,4;593,1;594,0;595,3;596,1;597,8;598,4;599,1;600,4;601,2;602,1;603,1;604,2;605,1;606,2;607,8;608,7;609,0;610,9;611,4;612,1;613,1;614,1;615,1;616,8;617,3;618,3;619,1;620,9;621,3;622,1;623,4;624,5;625,1;626,2;627,3;628,2;629,4;630,5;631,1;632,8;633,8;634,1;635,0;636,2). ``` ### Example output ``` $ clingo missing.lp problem1.lp clingo version 5.2.2 Reading from missing.lp ... Solving... Answer: 1 missing(148) SATISFIABLE Models : 1+ Calls : 1 Time : 0.032s (Solving: 0.00s 1st Model: 0.00s Unsat: 0.00s) CPU Time : 0.032s ``` [Answer] # C++, 5000 random test cases in 6.1 seconds This is practically fast, but there may exist some testcases that make it slow. Complexity unknown. If there are multiple solutions, it will print them all. [Example](https://tio.run/##jVZNb@M2ED3bv4JBgcSqE4NDfceOgT3tZbt7Kwq4biArcsKsIxmy3C1q@K83fUNSipxkuw0cmBoNZ968eRw6326v7vP8@fknXeab/V0hZvlT1jzMhy@GlW52RdO37Jpal/d9y59F3lR135K/ddIVbEX21Ldlm/uq1s0DjMO8KneN0GUjfv3w6faXD7@JG6FCOe29@PTlo3uxqe5JjlrHK0GeGAuaDvc7ZBWrqtrs4LVr7q6vbQEz5zufDofGvM10Pdvpv4vb5lLY77nIq33ZjGxC42XLOMdDfSnesTdZfV803vAwHNgYIis5s7wU1XqNvHa9rTo4duf1dQnbdDhYV7UYTcWo88b7yVqXdyMbuo3jeeLsvQicbzxuM1jf8dhD5Lpo9nVptzxlX4tbrngEd@MMj@NwyESJu/Vu1IJvqRCrk3Jtg2e99HPHiaH6XOQlkHKLLBd6LUYrcWOqWWTLCQcdoYSMoa6Yk6l1ypxT5@FQN/W@QKcGHHLr/A1VbNDGgK9Zqwg8oGiBzCbqSVbOsPLECtr7iigDDrcVPwuSkIxzXazG46X4Q1zIC6bOBNkifCuw83NxhhIX2yUvt9yKxqYbOPONgzywm5lTkAkWrXKYnuZ1ef3d62yzM6bjkD/Oz1mPrNl6nzeiymtOyyxsLgUif8Qe08VqW9QZN8nJF57nQnuui4c280bMhZ5spuI4PIJgDpRnm9H3utxr8pseY/VZ9LsHKP04QDAXRuXv986R@6p3zIheGtyNLi1NvHG9ye6dEAY9hO4EtqerqW6tfaRNI5mvsvrGyw7Co4XwCAif8dUmH2T7phI5XtopwMp4XF62R7xr7cggGcMN57TeQQdzHj@dvmwV7TskR8RDPtkVqOgOUnAriM9GduRdisej67@JcGbSQG0NC1i/kQ77aCNEdrLs3DAQMD7Z7ncPt6ss/zpCfs/oD6S@iPRoT98Z@7Yn79ARW9Wm@smquNclI@OHAiMJy8XyvfGYvTscV97Bgc7aszgTq1YsR0Opc@DzgjkpT8@LQTrsoWK8HSp@MKheC@9EwJtd084ObjDOhLg2A7BTnBt@np7Uwgh@oScfl68nUndAT8T3tLUnwG3Zr7AeIVA3ReDRm0PkpNYKHW8X0g2e5dtUgzc@vTnDQingKE7TeFxxTwB2/ld/FuxjqBp0eOvC7ME8sFS/pgmOLzTp/6hD/7AK/eMa9A8r0J7D6VLw5IJvTy9HO9KeMpaIuZV73cLXd0fUiRkhYK6rVWvPdSnmcxfA3EkLklzIwYr2/c9x@j8GXzuZ8oesxky6fjvHcKQXj4678biNafy7Jm0X2nlcXcHj8FanJyOwB4Zkh2Pw7UFvCtx8mBVXVx7v6rVB9@7Hu8r1n6@Pl182lTYie5mCp1eoUzJmFscxBPfi52bfUTgQJmRZ/NXc4mJ72jdZo6vS6LwbAPxgB4D3MtNM1FOlWniY6o2YzUxahoHlxe/lxbTVq@Q78aRh18bXay8miO0APo/uPmQE3JyT4LoLCyk@P1MqQ0khUZikIfkpRWGiVBwnpPwgVDGRpDRSfhj7RGlCfqwoiH2fVJRESahkEAeUUAxzqhReUxISfIMwUJSoKFRBQIooDpQPX0KSlAJfIYAfhalPfqBkrKRvnGDEmmIJQBQRgiJGkJCU5PsqYJiE3ZEK/TSICAlDQKDQD4hghSWNUhWQjPBMiR8iRhKnJBOZIhb7kw@kQRolSBApBE6SJKAoDgnOSoYcNkhJJQkcIwVYSQpcKqEwIB/cSMQnGTATKDEKVEpxRKgySmKpUEDoJ2RqVgEwBBTGhPJQEoiWUaJQlkxTSSA3QmKSsKQJMCnA9kMkTWOFTiSRwp@P/zDyQxCkAMcP0A/QmKJogFGpj6VEmyiRSiZoGgF9wm2jSIK6kBGnAINOxBHeglBJEXxiipk9BEfuMGYaABgv0QewEPkR4KAZYYSUKADERnEcIGaquFPgPQXLUA78QQHMqBJ8wR3QuP@gQKFxyJ8yMC4AigBwrIFV/ZPzz4Ld89UX/18). **Explanation:** 1. Count the occurrences of digits. 2. List all possible answers. 3. Check if a candidate is a valid answer: 3-1. Try to split the string(s) by numbers which only occur once and mark it as identified, except the candidate. For example, `2112282526022911192312416102017731561427221884513` has only one `14`, so it can be split into `211228252602291119231241610201773156` and `27221884513`. 3-2. If any split string has length 1, mark it as identified. If any contradiction is made (identified more than once), the candidate is not valid. If we cannot find the candidate in the string, the candidate is valid. 3-3. If any split is made, repeat step 3-1. Otherwise, do a brute force search to check if the candidate is valid. ``` #include <cmath> #include <bitset> #include <string> #include <vector> #include <cstring> #include <iostream> #include <algorithm> const int VAL_MAX = 250; const int LOG_MAX = log10(VAL_MAX - 1) + 1; using bools = std::bitset<VAL_MAX>; std::pair<size_t, size_t> count(const std::string& str, const std::string& target) { size_t ans = 0, offset = 0, pos = std::string::npos; for (; (offset = str.find(target, offset)) != std::string::npos; ans++, pos = offset++); return std::make_pair(ans, pos); } bool dfs(size_t a, size_t b, const std::vector<std::string>& str, bools& cnt, int t) { // input: string id, string position, strings, identified, candidate if (b == str[a].size()) a++, b = 0; if (a == str.size()) return true; // if no contradiction on all strings, the candidate is valid int p = 0; for (int i = 0; i < LOG_MAX; i++) { // assume str[a][b...b+i] is a number if (str[a].size() == b) break; p = p * 10 + (str[a][b++] ^ '0'); if (p < VAL_MAX && !cnt[p] && p != t) { //if no contradiction cnt[p] = true; if (dfs(a, b, str, cnt, t)) return true; // recursively check cnt[p] = false; } } return false; } struct ocr { int l, r, G; bool operator<(const ocr& i) const { return l > i.l; } }; int cal(std::vector<std::string> str, bools cnt, int t) { // input: a list of strings, whether a number have identified, candidate // try to find numbers that only occur once in those strings int N = str.size(); std::vector<ocr> pos; for (int i = 0; i < VAL_MAX; i++) { if (cnt[i]) continue; // try every number which haven't identified int flag = 0; std::string target = std::to_string(i); ocr now; for (int j = 0; j < N; j++) { // count occurences auto c = count(str[j], target); if ((flag += c.first) > 1) break; if (c.first) now = {c.second, c.second + target.size(), j}; } if (!flag && t == i) return true; // if cannot find the candidate, then it is valid if (i != t && flag == 1) pos.push_back(now), cnt[i] = true; // if only occur once, then its position is fixed, mark as identified } if (!pos.size()) { // if no number is identified, do a brute force search std::sort(str.begin(), str.end(), [](const std::string& a, const std::string& b){return a.size() < b.size();}); return dfs(0, 0, str, cnt, t); } std::sort(pos.begin(), pos.end()); std::vector<std::string> lst; for (auto& i : pos) { // split strings by identified numbers if ((size_t)i.r > str[i.G].size()) return false; std::string tmp = str[i.G].substr(i.r); if (tmp.size() == 1) { // if split string has length 1, it is identified if (cnt[tmp[0] ^ '0']) return false; // contradiction if it is identified before cnt[tmp[0] ^ '0'] = true; } else if (tmp.size()) lst.push_back(std::move(tmp)); str[i.G].resize(i.l); } for (auto& i : str) { // push the remaining strings; same as above if (i.size() == 1) { if (cnt[i[0] ^ '0']) return false; cnt[i[0] ^ '0'] = true; } else if (i.size()) lst.push_back(std::move(i)); } return cal(lst, cnt, t); // continue the split step with new set of strings } int main() { std::string str; std::vector<ocr> pos; std::vector<int> prob; std::cin >> str; int p[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; for (int i = 0; i < VAL_MAX; i++) for (char j : std::to_string(i)) p[j ^ '0']++; for (char i : str) p[i ^ '0']--; // count digit occurrences { std::string tmp; for (int i = 0; i < 10; i++) while (p[i]--) tmp.push_back(i ^ '0'); do { // list all possible candidates (at most 4) int c = std::stoi(tmp); if (c < VAL_MAX && tmp[0] != '0') prob.push_back(c); } while (std::next_permutation(tmp.begin(), tmp.end())); } if (prob.size() == 1) { std::cout << prob[0] << '\n'; return 0; } // if only one candidate, output it for (int i : prob) // ... or check if each candidate is valid if (cal({str}, bools(), i)) std::cout << i << '\n'; } ``` [Try it online!](https://tio.run/##jVbbbuM2EH22v4JBgcSqE4M33WLHwD7ty3b3rSjguoGsyAmzjmTIcreo4V9veoakFDnJdhsYMTUanjlzZjh0vt1e3ef58/NPpsw3@7uCzfKnrHmYD18MK9PsiqZv2TW1Ke/7lj@LvKnqviV/62Qq2IrsqW/LNvdVbZoHGId5Ve4aZsqG/frh0@0vH35jN0yGfNp78enLR/9iU90LPmodr5gI2JiJ6XC/Q1S2qqrNDl675u762iUw877z6XBozdvM1LOd@bu4bS6Z@56zvNqXzcgFtF4ujXM81JfsHXuT1fdFEwwPw4HDYFlJkfklq9ZrxHXrbdXRcTuvr0vYpsPBuqrZaMpGnTfeT9amvBs56BYnCNjZewgUbzxuIzjf8TgAcl00@7p0W56yr8UtZTyCu3WGx3E4JKHY3Xo3asm3UrDVSbquwLNe@LnXxEp9zvISTKlETguzZqMVu7HZLLLlhEBHSCEjqivSZOqcMu/UeXjWTb0vUKkBQW69v5WKDMYa8DVrOwIPSJohskU9iUoRVgFbofe@AmVAcFv2MxMcLeNdF6vxeMn@YBf8gqSzIFvAtw12fs7OkOJiu6TllkrRuHADb77xlAduM2kKMaGi6xySp3mdXn/3OtvsrOk4pI/389Yj9Wy9zxtW5TWFJRU2lwzIH7HHVrHaFnVGRfLtC89zZgJfxUMbecPmzEw2U3YcHiEwAeXZZvS9KveK/KbGWH1m/eqBSh8HDObMdvn7tfPivqodKWKWlndjSicTbVxvsnvfCIMeQ38C29PVVLfOPjK2kKRXWX2jZUfh0VF4BIXP@GqDD7J9U7EcL90UoM54XF62R7wr7cgyGcMN57TeoQ/mNH66/nJZtO8QHIiHfLIrkNEdWsGv0HwO2Yt3yR6Pvv4W4cyGQbc11MDmTeuQj7GNSE5OnRsiAsUn2/3u4XaV5V9HiB/Y/oOoL016dKfvjHzbk3fohK1qm/1kVdybkpjRQ4GRhOVi@d54zN4djqvg4Eln7VmcsVXbLEcrqXeg84I5yU/Pi2U67LEivh0rerCsXjfeSQNvdk07O6jAOBPs2g7AruP88AvMpGa24Rdm8nH5eiJ1B/Sk@Z627gT4LfsV1iMAdVMEHr05JHyrtY2OtwvuB8/ybajBG5/enKFGKeDITsMElHGvAdz8r/4syMdKNej41oXdg3ngpH4tExxfZDL/kYf5YRbmxzmYH2ZgAs/Th6DJBd9evxzdSHvKqEXsrdyrFr6@O6JOzICAua5WrT03JZvPPYC9kxaCUyIH17Tvf47T/zH42smUP2Q1ZtL12zmGI7149NqNxy2m9e@KtF0Y73F1BY/D2z49GYE9MoJ3PAbfHsymwM2HWXF1FdCuXhlM7368q3z96fp4@WVTGdtkL1Pw9Ar1nYyZRThW4B5@bvcdmSdhIcvir@YWF9vTvskaU5W2z7sBQA9uAAQvM82innaqo4ep3rDZzIYlGlhe/F5eTNt@5XQnnhTs2voG7cWEZjtAz6O/D4kBFecE3HSwaMXnZ6G0VCINZSTSRMRRJITkIsZHi1QnMo0jKfCRQguJP60SJXgodCK4SnSUSB4LmFKeJrESMhZAiLhIsUPFgNax4GkqpUqEhLMI4SGjWMSSR5ESKtWCYyXiNEmFtQghABlJnQoFxBCukZSJUGGKx1RxqWSYAI4rqWXCI66VCDUCcwQIETpKk0hrkYQp19LCCYkwWsAgkYtOYAlFFOoolILYhTFS49KmDRelhUrSVMR4DWZSa9DWKgpBNxSJFsiNBAB2pAmd4oBsyCMtYcDLCISl5CALcyiExgPpzFOR4IlDYiQLfI5ME6mQolRplIo0klzGMRISnCSn/0oihxh4iIh/UBHfkUqwjsNU8iSMEEAgrUQCExzDJARHFcoUZhQLvFBPZALUGBhJqiKhOKqrUbBUhBHqHUEycEsRUiRQBW@gc5IQFsTAPhGioqAai1RJFSodh6gyigIJJUkKBlzoENlqbEWMmMDRHzE6CNt0yKEGeMBL/5PTr4Ld89UX9S8 "C++ (gcc) – Try It Online") [Answer] # [Clean](http://clean.cs.ru.nl/Clean), ~0.3s Fixed a huge bug in the algorithm, need to re-optimize it now. ``` module main import StdEnv import StdLib import System.CommandLine maxNum = 250 sample = "11395591741893085201244471432361149120556162127165124233106210135320813701207315110246262072142253419410247129611737243218190203156364518617019864222241772384813041175126193134141008211877147192451101968789181153241861671712710899168232150138131195104411520078178584419739178522066640145139388863199146248518022492149187962968112157173132551631441367921221229161208324623423922615218321511111211121975723721911614865611197515810239015418422813742128176166949324015823124214033541416719143625021276351260183210916421672722015510117218224913320919223553222021036912321791591225112512304920418584216981883128105227213107223142169741601798025" case1 = "6966410819610521530291368349682309217598570592011872022482018312220241246911298913317419721920718217313718080857232177134232481551020010112519172652031631113791105122116319458153244261582135510090235116139611641267691141679612215222660112127421321901862041827745106522437208362062271684640438174315738135641171699510421015199128239881442242382361212317163149232839233823418915447142162771412092492141987521710917122354156131466216515061812273140130240170972181176179166531781851152178225242192445147229991613515911122223419187862169312013124150672371432051192510724356172282471951381601241518410318414211212870941111833193145123245188102" case2 = "14883423514241100511108716621733193121019716422221117630156992324819917158961372915140456921857371883175910701891021877194529067191198226669314940125152431532281961078111412624224113912011621641182322612016512820395482371382385363922471472312072131791925510478122073722091352412491272395020016194195116236186596116374117841971602259812110612913254255615723013185162206245183244806417777130181492211412431591541398312414414582421741482461036761192272120204114346205712198918190242184229286518011471231585109384415021021415522313136146178233133168222201785172212108182276835832151134861116216716910511560240392170208215112173234136317520219" case3 = "1342319526198176611201701741948297621621214122224383105148103846820718319098731271611601912137231471099223812820157162671720663139410066179891663131117186249133125172622813593129302325881203242806043154161082051916986441859042111711241041590221248711516546521992257224020174102234138991752117924457143653945184113781031116471120421331506424717816813220023315511422019520918114070163152106248236222396919620277541101222101232171732231122301511263822375920856142187182152451585137352921848164219492411071228936130762461191564196185114910118922611881888513917712153146227193235347537229322521516718014542248813617191531972142714505519240144" case4 = "2492402092341949619347401841041875198202182031161577311941257285491521667219229672211881621592451432318618560812361201172382071222352271769922013259915817462189101108056130187233141312197127179205981692121101632221732337196969131822110021512524417548627103506114978204123128181211814236346515430399015513513311152157420112189119277138882021676618323919018013646200114160165350631262167910238144334214230146151171192261653158161213431911401452461159313720613195248191505228186244583455139542924222112226148941682087115610915344641782142472102436810828123731134321131241772242411722251997612923295223701069721187182171471055710784170217851" failing = "0102030405060708090100101102103104105106107108109110120130140150160170180190200201202203204205206207208209210220230240249248247246245244243242241239238237236235234233232229228227226225224223222221219218217216215214213212211199198197196195194193192191189188187186185184183182181179178177176175174173172171169168167166165164163162161159158157156155154153152151149148147146145144143142141139138137136135134133132131129128127126125124123122121119118117116115114113112111999897969594939291898887868584838281797877767574737271696867666564636261595857565554535251494847464544434241393837363534333231292827262524232221191817161514131211987654321" dupes = "19050151158951391658227781234527110196235731198137214733126868520474181772192213718517314542182652441211742304719519143231236593134207203121171237201705111617211824810013324511511436253946122155201534113626129692410611318356178791080921122151321949681166200188841675156120546124912883216212189712281541382202411041372421642917614416870223753814121124318415710310515010682172099012716167102179894920613516297239186222232225635312262134019719915382229399107111802082341491811011604815220291125247641482401691871755205639495788414314011714616366130175601931092467744819271230159131158714761192105218019822421812423322919341426216523821428232" :: Position :== [Int] :: Positions :== [Position] :: Digit :== (Char, Int) :: Digits :== [Digit] :: Number :== ([Char], Positions) :: Numbers :== [Number] :: Complete :== (Numbers, [Digits]) numbers :: [[Char]] numbers = [fromString (toString n) \\ n <- [0..(maxNum-1)]] candidates :: [Char] -> [[Char]] candidates chars = moreCandidates chars [] where moreCandidates :: [Char] [[Char]] -> [[Char]] moreCandidates [] nums = removeDup (filter (\num = isMember num numbers) nums) moreCandidates chars [] = flatten [moreCandidates (removeAt i chars) [[c]] \\ c <- chars & i <- [0..]] moreCandidates chars nums = flatten [flatten [moreCandidates (removeAt i chars) [ [c : num] \\ num <- nums ]] \\ c <- chars & i <- [0..]] singletonSieve :: Complete -> Complete singletonSieve (list, sequence) | (list_, sequence_) == (list, sequence) = reverseSieve (list, sequence) = (list_, sequence_) where singles :: Numbers singles = filter (\(_, i) = length i == 1) list list_ :: Numbers list_ = [(a, filter (\n = not (isAnyMember n (flatten [flatten b_ \\ (a_, b_) <- singles | a_ <> a]))) b) \\ (a, b) <- list] sequence_ :: [Digits] sequence_ = foldr splitSequence sequence (flatten (snd (unzip singles))) reverseSieve :: Complete -> Complete reverseSieve (list, sequence) # sequence = foldr splitSequence sequence (flatten (snd (unzip singles))) # list = [(a, filter (\n = not (isAnyMember n (flatten [flatten b_ \\ (a_, b_) <- singles | a_ <> a]))) b) \\ (a, b) <- list] # list = [(a, filter (\n = or [any (isPrefixOf n) (tails subSeq) \\ subSeq <- map (snd o unzip) sequence]) b) \\ (a, b) <- list] = (list, sequence) where singles :: Numbers singles = [(a, i) \\ (a, b) <- list, i <- [[subSeq \\ subSeq <- map (snd o unzip) sequence | isMember subSeq b]] | length i == 1] splitSequence :: Position [Digits] -> [Digits] splitSequence split sequence = flatten [if(isEmpty b) [a] [a, drop (length split) b] \\ (a, b) <- [span (\(_, i) = not (isMember i split)) subSeq \\ subSeq <- sequence] | [] < max a b] indexSubSeq :: [Char] Digits -> Positions indexSubSeq _ [] = [] indexSubSeq a b # remainder = indexSubSeq a (tl b) | startsWith a b = [[i \\ (_, i) <- take (length a) b] : remainder] = remainder where startsWith :: [Char] Digits -> Bool startsWith _ [] = False startsWith [] _ = False startsWith [a] [(b,_):_] = a == b startsWith [a:a_] [(b,_):b_] | a == b = startsWith a_ b_ = False missingNumber :: String -> [[Char]] missingNumber string # string = [(c, i) \\ c <-: string & i <- [0..]] # locations = [(number, indexSubSeq number string) \\ number <- numbers] # digits = [length (indexSubSeq [number] [(c, i) \\ c <- (flatten numbers) & i <- [0..]]) \\ number <-: "0123456789"] # missing = (flatten o flatten) [repeatn (y - length b) a \\ y <- digits & (a, b) <- locations] # (answers, _) = hd [e \\ e <- iterate singletonSieve (locations, [string]) | length (filter (\(a, b) = (length b == 0) && (isMember a (candidates missing))) (fst e)) > 0] # answers = filter (\(_, i) = length i == 0) answers = filter ((flip isMember)(candidates missing)) ((fst o unzip) answers) Start world # (args, world) = getCommandLine world | length args < 2 = abort "too few arguments\n" = flatlines [foldr (\num -> \str = if(isEmpty str) num (num ++ [',' : str]) ) [] (missingNumber arg) \\ arg <- tl args] ``` Compile with `clm -h 1024M -s 16M -nci -dynamics -fusion -t -b -IL Dynamics -IL Platform main` This works by taking every number the string has to contain, and counting the number of places the required digit sequence is present in the string. It then repeatedly does these steps: * If number has no possible positions, that's the answer * Remove every number with one possible position (call these `singles`) * Remove every position from all remaining numbers which overlaps with any positions from the previously removed numbers (the `singles`) [Answer] # Rust Port of [@Colera Su's C++ answer](https://codegolf.stackexchange.com/a/150002/110802) in Rust. \$ \color{red} {\text{But I made some mistakes, the result of the rust code is not correct.}} \$ \$ \color{red} {\text{variable `prob` seems to be consistent, the logic that produces `prob` seems to be consistent. }} \$ Any help would be appreciated. [Try it online!](https://tio.run/##1VhLb@NGEr7rV7RzcMgZmeluviXbixwWu4ckE2AGwQJeQaDklk0vRTIkNc7sxL998lXzIT6kibO3FQRJ3V311buqqeJQVl@@HErFyup@sdhmSaK2VZyl5WLxz6h8/DHKl7Pj8T5fLN4V96qI04flbPbdd2wL0or98v0P6x@//9eCHcr4v4rdMOny5fH4h3f/qI93noNDoyFnUal3rpiwuGkl2YPghsne0nI5@xryCLY9s6HTrKyKw7Zi77YF@zxjeCUNwVyvisHqoVu9zGbxPk/Yz1FRxVHy91/ZLit6KLuUqV@Ny1IluznLqkcFoMv3WJns6pZtsixpCOlFVFbCbm5qSivRJy@dkD76SDDcO5Wc12drBOCsCu9yitt1G57bnjrvs70ytE4EoDlNc6TSSblfldcI6slpjLU6NivpiSG87JBWRgkYRGnOqqh4UFW90phGHYw6JmYbP1Wx/aGqmRFlxL@/nURltY7Te/Xb9Czb7UrV8OiD58c4UfpY@0SzmTgv72pSy1pZO@watWpmz7ha/NsbJpZHg2t8bNYKvG1MshKVGuaRbqBjzbRsHKO/DA0@79GZjcfud6URtUmqbdp0K3iNXPmL2l6/r3TM52ybkj@Jrinf64aYMhTn1aJ17jBr4x3bUL4S5l20qg3oWb85Orchj6hQW5YJvS41VR2KlKEe1ZHzpW93G6f8iE45uIY7GbespsCpT9Ql/rmvwFBVKLIZyd8UKvrPWDK9SFzO3jDBYYPR4kTlevOpUqVh3m1WR5lXbPMt/7Zb96K6GWUDdMrZdduy2OUlu3iDeFgqrYpPRm5aWYHglqqojF2UlIgBSHJ2ccOqkebE1VDmc@3AnthGlM4MxLXOAx15kI5jcDYOQ49MhdYaTuOmY0RnbUlHCXlwwQZpqOuVUvGvZWGXD1mJEAFxsUjVM1VSlxtxkxutlwcpQSag/IzL2LQO6XMR5eusMC5rW6xtkqVqkqWYJVWcTlO01aeuaKgTW1W2LrWFg9pudN4l0cOwSNqTNHvGgW6sNIz4nIYQPjF8OHs50pN5xpOOp0lW4tuKK1UYJlLosFdFVE3VJyFbwDetldrqZdO8hsHW@iFhtxaf5JI@u0U5T5NnVETTtCG3Wxzc/AT3yPStJbTx@B71Su2Np743hpJeZmN1UfCcCqiiX/HrW0@DEdd1B4AWbWw9ktDKD@WjASNGvuyVSjypz0GHo54AnLhcq31efRqEr80PBI3pNtpm6BGLNsusqNCZjN@p2n9nUe2weshu6oXZY2lMp/aAHMO7nrWXTUlSjxjMHlKPRLRiu7laVqMafIXOXYVSBQ9KM7YK5AgY7mLrYfW1eaGr9Ww17vNarobBR0Ej@2RhQiioj@NBnKicj1FyoJsjEfb6Pz/f/ye186ZrOhrsROM535JHpn61J2v0abIxBQjS44JsOJln2tiyqpMZVOYp53aRgYB0S50mxu1t2e/6bWwp9qPYvsrJ8f@9i@NXODg@MzRpUIKoG9TN/NxH8bEShtVVT9NB@enHsDhbLPCD@Cx05/t1EqMCLxvG1jv9ij1WKyD3YBsUzOQq9lFtL@74Evej1fIVg5dOn@h0MCGt7WNUlBM/5XdP/cD3474a3adeziTfCeT8Lj6PetWhjq6ddTM54ea@vYKPTG1vp5C5GhlHJaiTwKjVCTDlKLVNWpHWZ3Kjc36RbU413SzLR3Nj2zQtPBmWarGo71e3xjj47YAeXkuJsfGhlarfqh4bTUXy3iho0Ks2bGue68yNQ@sCb7SLUyREU/EDhS46Sq3AOlcF@CN6gp1kzNlr/DB8uyLbrw/VLjA67LE32okHhipJL4xvPi/@9vLNnKxry4DmNRl7sqEdGf@Nu8WjQo8pD0nFYjyG1VCaGb1tMo9PNlId7uEFFk1CV19vsq7m7S26SYo5iydV9eeanepLcEh@2KDhRXHFfkIgfj7G4fgvwCRCdavp//exbP9HuP5wOwEie@8@rGbPj6pQGvTDgv4@mM/@iojRw5/@d0EH6ZrJV14kJvkaU1c8Il31u0/9V0GsL7aoGSJDkwHJit3eNMtx/ce9XjMSqa@c@s76P@r69Ke6PpFicafs04pd3wz0Hkp@Oq@sllM@o3LwOKKZ@3dSjUjXrkJ9VGg/3QzRRYnh2WXXly/CdqQtQld6IgyE73lCSC58vB0ROoEMfU8KvKVwhMTLsQNbcFc4geB24HiB5L7AVsjDwLeF9AUQPC5CcNg@oB1f8DCU0g6EBLFwQSE9X/iSe54t7NARHL@EHwah0DtCCEB60gmFDUQXpJ6UgbDdEMvQ5tKWbgA4bktHBtzjji1cB4I5BLgQ7YWB5zgicEPuSA0nJMQ4AhsStjgBdlzhuY7nSkHauT5M41KbDRLbEXYQhsLHMTSTjgO1Hdtzoa4rAkfANnIAsD2H0EkOlHW550hs4NCDwlJyKIttVwgHC/IzD0WAFYeLYSzwOSwNpA0TpR16oQg9yaXvwyDByeX0aUvY4AMPEvEBL@LbswP89t1Q8sD1IEDArEACEzq6gQsdbVeG2EawoBfiCUuA6gMjCG1P2BzRdRCwULge4u3BZdAthEgRwCs4gZ@DgLDgDPAJFxGFqr4IbWm7tuO7iDKCAhdKcik04MJxYa0DVsjwCRz54SODwOa4HN6AHqBy/gA) ``` use std::collections::HashMap; use std::cmp::Ordering; // const VAL_MAX: usize = 250; // const LOG_MAX: f64 = (VAL_MAX as f64 - 1.0).log10() + 1.0; const VAL_MAX: usize = 250; const LOG_MAX: usize = 3; struct Ocr { l: usize, r: usize, g: usize, } impl PartialEq for Ocr { fn eq(&self, other: &Self) -> bool { self.l == other.l } } impl Eq for Ocr {} impl PartialOrd for Ocr { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) } } impl Ord for Ocr { fn cmp(&self, other: &Self) -> Ordering { other.l.cmp(&self.l) } } fn count(s: &str, target: &str) -> (usize, usize) { let mut count = 0; let mut last_index = 0; let mut offset = 0; while let Some(index) = s[offset..].find(target) { count += 1; offset += index + target.len(); last_index = offset; } (count, last_index) } fn dfs(a: usize, mut b: usize, strs: &Vec<String>, cnt: &mut HashMap<usize, bool>, t: usize) -> bool { if b == strs[a].len() { b = 0; if a + 1 == strs.len() { return true; } } let mut p = 0; for _ in 0..LOG_MAX as usize { if strs[a].len() == b { break; } p = p * 10 + (strs[a].as_bytes()[b] as usize - b'0' as usize); b += 1; if p < VAL_MAX && !*cnt.entry(p).or_insert(false) && p != t { cnt.insert(p, true); if dfs(a, b, strs, cnt, t) { return true; } cnt.insert(p, false); } } false } fn cal(str: Vec<String>, mut cnt: HashMap<usize, bool>, t: usize) -> bool { let mut pos = Vec::new(); for i in 0..VAL_MAX { if cnt.get(&i).unwrap_or(&false).clone() { continue; } let target = i.to_string(); let mut flag = 0; let mut now = Ocr { l: 0, r: 0, g: 0 }; for (j, str) in str.iter().enumerate() { let c = count(str, &target); flag += c.0; if flag > 1 { break; } if c.0 > 0 { now = Ocr { l: c.1, r: c.1 + target.len(), g: j }; } } if flag == 0 && t == i { return true; } if i != t && flag == 1 { pos.push(now); cnt.insert(i, true); } } if pos.is_empty() { let mut str = str.clone(); str.sort_by(|a, b| a.len().cmp(&b.len())); return dfs(0, 0, &str, &mut cnt, t); } pos.sort(); let mut lst = Vec::new(); let mut str = str.clone(); for i in pos { if i.r > str[i.g].len() { return false; } let tmp = str[i.g][i.r..].to_string(); if tmp.len() == 1 { let value = tmp.as_bytes()[0] as usize - b'0' as usize; if *cnt.get(&value).unwrap_or(&false) { return false; } cnt.insert(value, true); } else if !tmp.is_empty() { lst.push(tmp); } str[i.g].truncate(i.l); } for i in str { if i.len() == 1 { let value = i.as_bytes()[0] as usize - b'0' as usize; if *cnt.get(&value).unwrap_or(&false) { return false; } cnt.insert(value, true); } else if !i.is_empty() { lst.push(i); } } cal(lst, cnt, t) } fn main() { let mut str = String::new(); std::io::stdin().read_line(&mut str).unwrap(); let str = str.trim().to_string(); let mut p = vec![0; 10]; for i in 0..VAL_MAX { for j in i.to_string().chars() { p[j as usize - '0' as usize] += 1; } } for i in str.chars() { p[i as usize - '0' as usize] -= 1; } let mut tmp = String::new(); for i in 0..10 { for _ in 0..p[i] { tmp.push((i as u8 + b'0') as char); } } let mut prob = Vec::new(); loop { let c = tmp.parse::<usize>().unwrap(); if c < VAL_MAX && tmp.chars().next().unwrap() != '0' { prob.push(c); } let mut tmp_bytes = tmp.into_bytes(); if !tmp_bytes.next_permutation() { break; } tmp = String::from_utf8(tmp_bytes).unwrap(); } println!("{:?}",prob); if prob.len() == 1 { println!("\n the result is: {:?}", prob[0]); return; } for i in prob { if cal(vec![str.clone()], HashMap::new(), i) { println!("\n the result is: {:?}", i); } } } pub trait NextPermutation { fn next_permutation(&mut self) -> bool; } impl<T> NextPermutation for [T] where T: Ord, { fn next_permutation(&mut self) -> bool { if self.len() < 2 { return false; } let mut i = self.len() - 1; while i > 0 && self[i - 1] >= self[i] { i -= 1; } if i == 0 { return false; } let mut j = self.len() - 1; while j >= i && self[j] <= self[i - 1] { j -= 1; } self.swap(j, i - 1); self[i..].reverse(); true } } ``` ]
[Question] [ Given an input of a list of integers representing dates, output an ASCII art timeline like the following: ``` <-----------------------------> A B C D E ``` The above timeline is the output for input `[1990, 1996, 1999, 2011, 2016]`. Note several things about the timeline: * The first line of output is a less than sign (`<`), a number of dashes equal to `dateOfLastEvent - dateOfFirstEvent + 3` (because one must be added to include the last date, and then two more for padding), and then a greater than sign (`>`). * In the second line of output, each event is placed at position `dateOfEvent - dateOfFirstEvent + 2` (assuming zero-indexing). Hence, the first event is placed at position `2`, two characters to the right of the `<`, and the last event is similarly two characters to the left of the `>`. * Each event is represented by a letter. Event 1 is `A`, event 2 is `B`, etc. There will never be more than 26 events. You may use lowercase letters if you would like. * There is no trailing whitespace. The only extra whitespace allowed is a trailing newline at the end of the program. Furthermore, * The events are not necessarily given in order. Dates are still labelled according to their position in the array, though. For example, an input of `[2, 3, 1, 5, 4]` must output ``` <-------> CABED ``` * You may be given one or more events as input. For example, an input of `[12345]` must output ``` <---> A ``` * You may assume that the input will never contain duplicate dates. Input may be given as either an array/list of integers/strings or a single string separated by any non-numerical character. The allowable range of dates that will be provided as input is `1 ≤ x ≤ 32767`. Since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest code in bytes will win. Test cases: ``` 32767 32715 32716 32750 32730 32729 32722 32766 32740 32762 <-------------------------------------------------------> BC G FE I D J HA 2015 2014 <----> BA 1990 1996 1999 2011 2016 <-----------------------------> A B C D E 2 3 1 5 4 <-------> CABED 12345 <---> A ``` [Answer] ## Pyth, ~~37~~ ~~36~~ ~~35~~ 34 bytes ``` :*dlp++\<*\-+3-eJSQhJ"> "mhh-dhJQG ``` Explanation: (for this the newline will be replaced by `\n` for simplicity) ``` :*dlp++\<*\-+3-eJSQhJ">\n"mhh-dhJQG - autoassign Q = eval(input()) - G = "abcdefghijklmnopqrstuvwxyz" p++\<*\-+3-eJSQhJ">\n" - print out the first line +3-eJSQhJ - Get the number of dashes SQ - sorted(Q) J - autoassign J = ^ e - ^[-1] - - ^-V hJ - J[0] +3 - ^+3 *\- - ^*"-" +\< - "<"+^ + ">\n" - ^+"-->\n" p - print(^) *dl - work out the number of spaces to print l - len(^) *d - ^*" " : G - For i in V: ^[i] = G[i] mhh-dhJQ - Work out the positions of the characters m Q - [V for d in Q] hJ - J[0] -d - d-^ hh - ^+2 ``` [Try it here!](http://pyth.herokuapp.com/?code=%3A%2adlp%2B%2B%5C%3C%2a%5C-%2B3-eJSQhJ%22%3E%0A%22mhh-dhJQG&input=%5B5%2C+2%2C+4%2C+3%2C+1%5D&debug=0) [Answer] ## PowerShell, ~~120~~ 108 bytes ``` param($a)$n,$m=($a|sort)[0,-1];"<$('-'*($b=$m-$n+3))>";$o=,' '*$b;$i=97;$a|%{$o[$_-$n+2]=[char]$i++};-join$o ``` Takes input `$a` then sets `$n` and `$m` to the minimal and maximal values, respectively. We output the timeline with the next section, by executing a code block `$(...)` inside the string to generate the appropriate number of `-` characters. We then generate an array of the same length containing only spaces, and set our output character to `$i`. Then, we loop through the input `$a` with `|%{...}`. Each loop we set the appropriate `$o` value. Finally, we `-join` `$o` together to form a string. Since that is left on the pipeline, output is implicit. Edited to remove the `.TrimEnd()` command, as the last character of `$o` is always guaranteed to be a letter. ### Example ``` PS C:\Tools\Scripts\golfing> .\draw-a-timeline.ps1 2015,2014,2000 <------------------> c ba ``` [Answer] # C - 294 287 220 191 184 178 174 bytes After staring out with a somewhat insane code I at least have gotten it down a bit ... ***Note:*** *First loop has the requirement that the execution of the binary gives 0 as result from `atoi()` on `argv[0]`. If not, this would result in the binary (name) being included as an event. Examples that invalidates:* ``` $ 42/program 1 2 3 # 42/program gives 42 from argv[0], fail. $ 1program 3 2 9 # 1program gives 1 from argv[0], fail. $ 842 3 2 9 # 842 gives 842 from argv[0], fail. ``` *Not sure if this is a valid requirement.* ``` char y[32769];n,m;main(i,a)char**a;{for(;n=atoi(a[--i]);y[n>m?m=n:n]=64+i);for(;!y[++i];);printf("<");for(n=i;i<=m;i+=printf("-"))!y[i]?y[i]=' ':0;printf("-->\n %s\n",y+n);} ``` Run: ``` ./cabed 32767 32715 32716 32750 32730 32729 32722 32766 32740 32762 <-------------------------------------------------------> BC G FE I D J HA ./cabed 2 1 3 5 4 <-------> BACED ./cabed 2016 <---> A ./cabed 130 155 133 142 139 149 148 121 124 127 136 <-------------------------------------> H I J A C K E D GF B ``` Ungolfed: ``` #include <stdio.h> #include <stdlib.h> char y[32769]; /* Zero filled as it is in global scope. */ int n, m; int main(i, a) char**a; { /* Loop argv and set y[argv[i] as int] = Letter, (Event name). * Set m = Max value and thus last data element in y. */ for ( ; n = atoi(a[--i]); y[n > m ? m = n : n] = 64 + i) ; /* i = 0. Find first element in y that has a value. (Min value.) */ for (; !y[++i]; ) ; printf("<"); /* Save min value / y-index where data starts to n. * Print dashes until y-index = max * Build rest of event string by filling in spaces where no letters.*/ for (n = i; i <= m; i += printf("-")) !y[i] ? y[i] = ' ' : 0; printf("-->\n %s\n", y + n); return 0; } ``` [Answer] # [MATL](https://esolangs.org/wiki/MATL), 40 ~~41~~ bytes ``` 0lY2in:)GtX<-I+(t~32w(ctn45lbX"60hP62hcw ``` [**Try it online!**](http://matl.tryitonline.net/#code=MGxZMmluOilHdFg8LUkrKHR-MzJ3KGN0bjQ1bGJYIjYwaFA2Mmhjdw&input=WzMyNzY3IDMyNzE1IDMyNzE2IDMyNzUwIDMyNzMwIDMyNzI5IDMyNzIyIDMyNzY2IDMyNzQwIDMyNzYyXQ) ``` 0 % array initiallized to 0 lY2 % string 'ABC...Z' in:) % input array. Take as many letters as its length GtX<-I+ % push input again. Duplicate, subtract minimum and add 3 ( % assign selected letter to those positions. Rest entries are 0 t~32w( % replace 0 by 32 (space) c % convert to char tn45lbX" % duplicate, get length. Generate array of 45 ('-') repeated that many times 60hP62h % prepend 60 ('<'), postpend 62 ('>') c % convert to char w % swap. Implicit display ``` [Answer] # Ruby, 83 characters ``` ->a{n,m=a.minmax s=' '*(d=m-n+3) l=?@ a.map{|i|s[i-n+2]=l.next!} puts ?<+?-*d+?>,s} ``` Sample run: ``` irb(main):001:0> ->a{n,m=a.minmax;s=' '*(d=m-n+3);l=?@;a.map{|i|s[i-n+2]=l.next!};puts ?<+?-*d+?>,s}[[32767,32715,32716,32750,32730,32729,32722,32766,32740,32762]] <-------------------------------------------------------> BC G FE I D J HA ``` [Answer] # JavaScript (ES6), 124 ``` l=>(l.map(v=>r[v-Math.min(...l)]=(++i).toString(36),r=[],i=9),`<-${'-'.repeat(r.length)}-> `+[...r].map(x=>x||' ').join``) ``` **TEST** ``` F= l=>(l.map(v=>r[v-Math.min(...l)]=(++i).toString(36),r=[],i=9),`<-${'-'.repeat(r.length)}-> `+[...r].map(x=>x||' ').join``) console.log=x=>O.textContent+=x+'\n' test= [[32767,32715,32716,32750,32730,32729,32722,32766,32740,32762], [2015,2014],[1990,1996,1999,2011,2016],[2,3,1,5,4],[12345]] test.forEach(x=>console.log(x+'\n'+F(x)+'\n')) ``` ``` <pre id=O></pre> ``` [Answer] # PHP, ~~129~~ ~~126~~ ~~125~~ ~~121~~ ~~117~~ 115 bytes Uses ISO 8859-1 encoding. ``` $l=min([$h=max($z=$argv)]+$z)-3;echo~str_pad(Ã,$h-$l,Ò).~ÒÁõ;for(;$l<$h;)echo chr((array_search(++$l,$z)-1^32)+65); ``` Run like this (`-d` added for aesthetics only): ``` php -r '$l=min([$h=max($z=$argv)]+$z)-3;echo~str_pad(Ã,$h-$l,Ò).~ÒÁõ;for(;$l<$h;)echo chr((array_search(++$l,$z)-1^32)+65);' 1990 1996 1999 2016 2011 2>/dev/null;echo ``` Ungolfed version: ``` // Get the highest input value. $h = max($z = $argv); // Get the lowest value, setting the first argument (script name) to the highest // so it is ignored. $l = min([$h] + $z); // Output the first line. echo "<".str_repeat("-",$h - $l + 3).">\n "; // Iterate from $l to $h. for(;$l <= $h;) // Find the index of the current iteration. If found, convert the numeric // index to a char. If not found, print a space. echo ($s = array_search($l++, $z)) ? chr($s+64) : " "; ``` * Saved 3 bytes by printing leading spaces from the loop and changing `<=` to `<`. * Saved a byte by using `str_pad` instead of `str_repeat`. * Saved 4 bytes by using bitwise logic to convert 0 (`false`) to 32, and everything above 0 to 97 onwards. Then convert that number to char. * Saved 4 bytes by using negated extended ASCII to yield `<`, `-`, `>` and newline * Saved 2 bytes by negating string after padding instead of before [Answer] # Perl, 109 bytes *includes +1 for `-p`* ``` $l=A;s/\d+/$h{$&}=$l++/ge;($a,$z)=(sort keys%h)[0,-1];$o.=$h{$_}//$"for$a..$z;$_='<'.'-'x($z-$a+3).">$/ $o" ``` Expects input on stdin: space separated numbers. Example: ``` $ echo 2016 2012 2013 | perl -p file.pl <-------> BC A ``` Somewhat readable: ``` $l=A; # Intialize $l with the letter A s/\d+/$h{$&}=$l++/ge; # construct %h hash with number->letter ($a,$z) = (sort keys %h)[0,-1]; # grab min/max numbers $o .= $h{$_} // $" for $a..$z; # construct 2nd line: letter or space $_= '<' . '-' x ($z-$a+3) . ">$/ $o" # construct 1st line, merge both lines to $_ output ``` [Answer] ## Python 2, ~~173~~ ~~172~~ 182 bytes since Python is missing yet, here is my first post: ``` import sys d=dict([(int(v),chr(65+i))for(i,v)in enumerate(sys.argv[1:])]) k=sorted(d.keys()) f=k[0] s=k[-1]-f+3 o=list(" "*s) for i in k:o[i-f+2]=d[i] print "<"+"-"*s+">\n"+"".join(o) ``` the original looks following: ``` import sys dates = dict([(int(v), chr(65+i)) for (i,v) in enumerate(sys.argv[1:])]) keys = sorted(dates.keys()) first = keys[0] out_size = keys[-1] - first + 3 out = list(" " * out_size) for date in keys: out[date - first + 2] = dates[date] print "<" + "-" * out_size + ">\n" + "".join(out) ``` [Answer] # Groovy, ~~106~~ 99 characters ``` {n=it.min() o=[l="A"] it.each{o[it-n]=l++} "<${"-"*(it.max()-n+3)}>\n "+o.collect{it?:" "}.join()} ``` Sample run: ``` groovy:000> print(({n=it.min();o=[l="A"];it.each{o[it-n]=l++};"<${"-"*(it.max()-n+3)}>\n "+o.collect{it?:" "}.join()})([32767,32715,32716,32750,32730,32729,32722,32766,32740,32762])) <-------------------------------------------------------> BC G FE I D J HA ``` ]
[Question] [ Input: ``` 1 X X X X XX XXXXXX X X X X XX XXXXXX X X X XXX X XX XXXXXX X X X XXX X XX XXXXXX X X X ``` Output: ``` X. X.. X... X.... XX. XXXXXX. X.X.X. X..... XX.. XXXXXX.. X.X.X.. XXX. X......XX... XXXXXX... X.X.X... XXX.. X......XX....XXXXXX.... X.X.X.... ``` Input: ``` 2 XX XX XX XX XX XX XX XX XX XX XX XX XX ``` Output: ``` .XX ..XX ...XX ....XX .....XX ..XX..XX ...XX..XX ....XX..XX .....XX..XX ``` Specification: * You must take as input 1. A flag signifying whether the light is coming from the top left or top right. This can be `1` or `2`, `-1` or `1`, `0` or `65536`, or whatever is convenient for you, as long as both flags are integers. 2. Rows composed of either `X` or , all of the same length in characters (i.e. padded with ) + All `X`s will either be on the last row or have an `X` under them (meaning no floating buildings) * You must output the rows (buildings) with shadows added. This is done with the following procedure: + If the light is coming from the top left, draw a right triangle of `.`s with the same height and width as the height of the building, starting from one space past its right edge and going rightwards. + Otherwise, if it's from the top right, do the same thing but start from one space past its left edge and pointing left. + Remember, do not alter `X`s by changing them to `.`s; leave them as they are. + There will always be "room" for your shadows, i.e. if there's a 3-space tall building at the end there will be at least 3 spaces of padding after it. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes will win! [Answer] # Perl - 85 ``` BEGIN{$d=-<>}$d?s/X /X./g:s/ X/.X/g;s/ /substr($p,$+[0]+$d,1)eq'.'?'.':$&/ge;$p=$_; ``` EDIT: I totally forgot about the `-p` flag this needs to be run with. Added 2 to char count. The flag specified at the first line is `0` for shadows going left and `2` for shadows going right. [Answer] ### GolfScript, 67 characters ``` n%(~:S\zip\%.0=\{.' '3$);+{{\(@[\].~<=}%+}:M~'X'/'.'*@@M}%S%zip\;n* ``` 1/-1 for shadows going right/left. Run the example [online](http://golfscript.apphb.com/?c=OyIxCiAgICAgIFggICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICBYICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgWCAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgIFggICAgICBYWCAgICBYWFhYWFggICAgIFggWCBYICAgIAogICAgICBYICAgICAgWFggICAgWFhYWFhYICAgICBYIFggWCAgICAKWFhYICAgWCAgICAgIFhYICAgIFhYWFhYWCAgICAgWCBYIFggICAgClhYWCAgIFggICAgICBYWCAgICBYWFhYWFggICAgIFggWCBYICAgICIKCm4lKH46U1x6aXBcJS4wPVx7LicgJzMkKTsre3tcKEBbXF0ufjw9fSUrfTpNfidYJy8nLicqQEBNfSVTJXppcFw7bioK&run=true): ``` X. X.. X... X.... XX. XXXXXX. X.X.X. X..... XX.. XXXXXX.. X.X.X.. XXX. X......XX... XXXXXX... X.X.X... XXX.. X......XX....XXXXXX.... X.X.X.... ``` [Answer] # Python 3 - 233 Well, that turned out longer than expected... 1 for shadows going right, -1 for shadows going left. ``` d,x=int(input()),[1] while x[-1]:x+=[input()] x,o,l,h=list(zip(*x[1:-1]))[::d],[],0,len(x)-1 for i in x:o+=[''.join(i[:len(i)-l])+''.join(i[len(i)-l:]).replace(' ','.')];l=max(l-1,i.count('X')) for i in zip(*o[::d]):print(''.join(i)) ``` EDIT: Didn't see the either side padding in the rules. Ehehe. ^^' [Answer] # JavaScript - 14 ``` eval(prompt()) ``` The flag on the first line is `for(p='';l=prompt();)console.log(p=l.replace(/ /g,function(a,b){return p[b+1]=='.'||p[b]=='.'||l[b+1]=='X'?'.':a}));` for shadows facing the left or `for(p='';l=prompt();)console.log(p=l.replace(/ /g,function(a,b){return p[b-1]=='.'||p[b]=='.'||l[b-1]=='X'?'.':a}));` for shadows to the right. This *might* abuse the "whatever is convenient for you" rule for the flag :P --- **Edit:** without abuse (127): ``` c=prompt();for(p='';l=prompt();)console.log(p=l.replace(/ /g,function(a,b){return p[b+c]=='.'||p[b]=='.'||l[b+c]=='X'?'.':a})); ``` The flag for this is `1` or `-1` [Answer] ## Python 2.7 - 229 ``` p,s,M,J,L=input(),__import__('sys').stdin.readlines(),map,''.join,len n,s,r,f=L(s),M(str.strip,M(J,zip(*s[::-1]))),0,[] for l in s[::p]:f,r=f+[(l+'.'*(r-L(l))+' '*n)[:n]],max(r-1,L(l)) print'\n'.join(M(J,zip(*f[::p])[::-1])) ``` **Ungolfed Version** ``` def shadow(st, pos): _len = len(st) st = map(str.strip, map(''.join,zip(*st[::-1]))) prev = 0 res = [] for line in st[::[1,-1][pos-1]]: res +=[(line+'.'*(prev-len(line)) + ' '*_len)[:_len]] prev = max(prev - 1, len(line)) return '\n'.join(map(''.join,zip(*res[::[1,-1][pos-1]])[::-1])) ``` ]
[Question] [ The solar year is 365 days, 5 hours, 48 minutes, 45 seconds, and 138 milliseconds, according to [this video](https://www.youtube.com/watch?v=qkt_wmRKYNQ). With the current Gregorian calendar, the rules for leap years are as follows: ``` if year is divisible by 400, LEAP YEAR else if year is divisible by 100, COMMON YEAR else if year is divisible by 4, LEAP YEAR else, COMMON YEAR ``` Unfortunately, this method is off by one day every 3216 years. One possible method of reforming the calendar is the following rule: ``` if year is divisible by 128, COMMON YEAR else if year is divisible by 4, LEAP YEAR else, COMMON YEAR ``` This has the benefit of not requiring us to change our calendars again for another 625,000 years, give or take. Say the entire world decides that, starting now, we use this system of every fourth year is a leap year except every 128th year, changing our calendars as follows: ``` YEAR GREGORIAN 128-YEAR 2044 LEAP LEAP 2048 LEAP COMMON 2052 LEAP LEAP ... 2096 LEAP LEAP 2100 COMMON LEAP 2104 LEAP LEAP ... 2296 LEAP LEAP 2300 COMMON LEAP 2304 LEAP COMMON 2308 LEAP LEAP ``` How would this affect our day of the week algorithms? **The challenge** * Given a date from the year 2000 to the year 100000, find the day of the week under this new calendar. * Any input and output format is allowed as long as you clearly specify which formats you are using. * This is code golf so try to make your solutions as golfy as possible! **Test cases** ``` "28 February 2048" -> "Friday" "March 1, 2048" -> "Sat" (2100, 2, 29) -> 0 # 0-indexed with Sunday as 0 "2100-02-29" -> 7 # 1-indexed with Sunday as 7 "28 Feb. 2176" -> "Wednesday" "1-Mar-2176" -> "Th" "28/02/100000" -> "F" # DD/MM/YYYYYY "Feb. 29, 100000" -> 6 # 1-indexed with Sunday as 7 "03/01/100000" -> 1 # MM/DD/YYYYYY and 1-indexed with Sunday as 1 ``` Suggestions and feedback on the challenge are welcome. Good luck and good golfing! [Answer] # [C (gcc)](https://gcc.gnu.org/), 60 bytes ``` f(m,d,y){y-=m<3;return(y+y/4-y/128+"-bed=pen+mad."[m]+d)%7;} ``` [Try it online!](https://tio.run/##bY3BCoIwAIbP9RRjIGxsS51ChtmxW09QHeY2y8OGDD0M8dmXQSVRx//7@fgku0kZQoMMVdTj0bPK7LPS6X5wFnni45z5OOUFgazWquq0JUaoDTybK1E42pZTaG0PjGgtwmBcrzo37wbBo67dIJwHvKCAJ3kB2AFE7cVCChrE6YdjXC7WSTh5B@kfI6Nv/CUsmd38pknyk3nxpzWFBw "C (gcc) – Try It Online") Simple modification of [Sakamoto's method](https://en.wikipedia.org/wiki/Determination_of_the_day_of_the_week#Sakamoto.27s_methods). Takes input as integer arguments in the order `month, day, year`, and outputs the number of the day (0-indexed on Sunday). [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~57~~ ~~55~~ 53 bytes ``` DayName@{m=#~Mod~128;6+Mod[(9#-m)/8-6Clip@m,28],##2}& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78H1CUmVcS/d8lsdIvMTfVoTrXVrnONz@lztDIwtpMG8iK1rBU1s3V1LfQNXPOySxwyNUxsojVUVY2qlX77@DgoFBdbWRgYqFjBBSu1VGAcIx1DMFsQwMDkIQlhGNuhlAF4kBVARUZQNQBpWA8kFxt7H8A "Wolfram Language (Mathematica) – Try It Online") Takes three inputs: the year, the month, and the day, in that order. For example, if you save the above function as `fun`, then `fun[2048,2,28]` tells you the day of week of February 28, 2048. ## How it works The formula `m=#~Mod~128;6+Mod[(9#-m)/8-6Clip@m,28]` converts the year into an equivalent year (a year with exactly the same days of week) between 6 AD and 33 AD. To do this, we subtract an offset and then take the year mod 28; but the offset changes every 128 years, and for years divisible by 128, we have to make a further adjustment because the equivalent year shouldn't be a leap year. Anyway, once that's done, we look up the month and day in that equivalent year using the built-in `DayName`. [Answer] # [Python 2](https://docs.python.org/2/), 67 bytes ``` def f(m,d,y):y-=m<3;return(y+y/4-y/128+int("0032503514624"[m])+d)%7 ``` [Try it online!](https://tio.run/##ZYo5DsMgEAD7vAJZssQKLC8LTsj1kigdRkkBsRAp9vXYLlKlmGZmFq6vT6bWwhxFlEkHzXDh4Z5u9lrm@i1ZsuLRDTwa8uqdq@wQLU1oJ@OO5LpHeoIK0J/aUvYcJWlBfgOdBzj8rNXC/Ml9PW8YRIC2Ag "Python 2 – Try It Online") `int("..."[m])` can be replaced by `ord("-bed=pen+mad."[m])`. [Answer] # JavaScript, ~~65~~ 59 bytes ``` (d,m,y)=>(y-=m<3,(+"0032503514624"[m]+y+(y>>2)-(y>>7)+d)%7) ``` ``` (d,m,y)=>(y-=m<3,(+"0032503514624"[m]+~~y+~~(y/4)-~~(y/128)+d)%7) ``` Uses Sakamoto's method. Gives `0=Sunday, 1=Monday, 2=Tuesday...` *-2 bytes thanks to Misha Lavrov -4 bytes thanks to Arnauld* [Answer] # [Actually](https://github.com/Mego/Seriously), 37 bytes This is a port of [notjagan's modification](https://codegolf.stackexchange.com/a/149600/47581) of [Sakamoto's algorithm](https://en.wikipedia.org/wiki/Determination_of_the_day_of_the_week#Sakamoto.27s_methods), but with a few stack-based tricks as described below. Input format is `day, year, month`. Output format is `0-indexed with Sunday as 0`. Golfing suggestions welcome! [Try it online!](https://tio.run/##S0wuKU3Myan8/99aycDA2MjUwNjU0MTMyETJNVPT2O7QRm3rQ3t8gBgI9/oc2ph9brG5g@r//0YWXEYGJkACAA "Actually – Try It Online") ``` ;"0032503514624"Ei)3>±+;¼L;¼¼½L±kΣ7@% ``` **Explanation** ``` Implicit input: day, year, month (month is at TOS) ;"0032503514624"Ei) Get the month code, convert to float, rotate to bottom of the stack 3>±+ If 3>month, add -1 to year ;¼L Push floor(year/4) to stack ;¼¼½L± Push floor(year/4) and append -floor(year/128) to stack. kΣ Wrap the stack (y/128, y/4, y, month_code, d) in a list and sum 7@% Get the sum modulo 7 Implicit return ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~32~~ ~~31~~ ~~30~~ 28 bytes Another port of [notjagan's modification](https://codegolf.stackexchange.com/a/149600/47581) of [Sakamoto's algorithm](https://en.wikipedia.org/wiki/Determination_of_the_day_of_the_week#Sakamoto.27s_methods) but with a base-250 number in place of `032503514624` (don't need the extra `0` because Jelly is 1-indexed). Input format is `month, year, day`. Output format is `0-based with Sunday as 0`. Golfing suggestion are very welcome as the way the links were tough to arrange and may still be golfable. [Try it online!](https://tio.run/##AUIAvf9qZWxsef//Mz5fQMK1w6bCuzcsMkkrwrXigJzhub7igbXhuKQ5e@KAmUTCs@G7iyvigbUrJTf///8y/zIwNDj/Mjg "Jelly – Try It Online") **Edit:** -1 byte from using bit shift instead of integer division. -1 byte from rearranging the beginning and the input format. -2 bytes thanks to Erik the Outgolfer and caird coinheringaahing. ``` 3>_@µæ»7,2I+µ“Ṿ⁵Ḥ9{’D³ị+⁵+%7 ``` **Explanation** ``` Three arguments: month, year, day 3>_@ Subtract (month<3) from year. Call it y. µ Start a new monadic chain. æ»7,2 Bit shift y by both 7 and 2 (equivalent to integer division by 128 and by 4). I+ y + y/4 - y/128 µ Start a new monadic chain. “Ṿ⁵Ḥ9{’ The number 732573514624 in base 250. D The list [7, 3, 2, 5, 7, 3, 5, 1, 4, 6, 2, 4]. ³ị Get the month code from the list (1-based indexing). +⁵+ Add y, our month code, and day together. %7 Modulus 7. ``` ]
[Question] [ ## Background Inspired by [I'm a palindrome. Are you?](https://codegolf.stackexchange.com/questions/110582/im-a-palindrome-are-you), where it is presented the [shocking](https://www.reddit.com/r/Showerthoughts/comments/5vkrg5/) fact that “`()()` is not a palindrome, but `())(`”, I asked myself what instead is `()()` and the answer is simply: it is a string with a vertical symmetry axis! ### The task Write a program or function that takes a string S (or the appropriate equivalent in your language) as input, checks for symmetry along the vertical axis, and returns a [truthy or falsy](http://meta.codegolf.stackexchange.com/a/2194) value accordingly. You can use [any reasonable means](http://meta.codegolf.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) to take the input and provide the output. ### Reflectional symmetry Reflectional symmetry around a vertical axis (or left-right symmetry) means that if you put a mirror vertically at the exact center of the string, the reflected image of the first half of the string is identical to the second half of the string. For example, the following strings are reflectional symmetric around a vertical axis: ``` ()() ()()() [A + A] WOW ! WOW OH-AH_wx'xw_HA-HO (<<[[[T*T]]]>>) (:) )-( ())(() qpqp ``` while the following are not: ``` ())( ((B)) 11 +-*+- WOW ! wow (;) qppq ``` ### Rules of the contest • Your program or function will receive only printable ASCII characters. You can include or not the empty string, (which is symmetric, of course!) as legal input, which is better for you. • The ASCII characters that can be considered symmetric with respect to the vertical axes are the following (note the initial space, and the difference between uppercase and lowercase letters): ``` !"'+*-.:=AHIMOTUVWXY^_ovwx| ``` The ASCII characters that can be considered “mirrored” and their corresponding characters are: ``` ()<>[]{}qpbd/\ ``` Note that, since they are mirrored, you can have both `()` as well as `)(`, `/\` and `\/`, etc. All the other ASCII printable characters must be considered asymmetric and without a mirrored corresponding character. • This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge: the shorter your program is, measured in bytes, the better, in any programming language. • Kudos to people that will produce a symmetric program! **Note**: this question is not a duplicate of ["Convenient Palindrome”](https://codegolf.stackexchange.com/questions/28190/convenient-palindrome-checker), that requires to check for palindromic strings in which parentheses are flipped. This question is different for two reasons: 1) it is a restriction of the other question for what concerns non-parentheses characters, since only symmetric characters can appear in reverse order. 2) Since it is based on the concept of symmetry, and not on a concept of “convenient palindrome”, mirrored characters can appear in both order, i.e. `[]` and `][`, and this makes the program to solve it different from programs that solve the other problem. [Answer] ## JavaScript (ES6), ~~130~~ ~~125~~ 113 bytes ``` f= s=>s==[...s].reverse(s=`()<>[]{}qpbd/\\`).map(c=>s[s.indexOf(c)^1]||/[- !"'+*.:=AHIMOT-Y^_ovwx|]/.exec(c)).join`` ``` ``` <input oninput=o.textContent=f(this.value)><pre id=o> ``` Edit: Saved 5 bytes thanks to @Arnauld. Saved a further 11 bytes thanks to @YairRand. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~69~~ 62 bytes ``` “(<[{qb/“ !"'+*-.:=AHIMOTUVWXY^_ovwx|“)>]}pd\”,Ṛ$F©f@ð®œs2¤yU⁼ ``` [Try it online!](https://tio.run/##y0rNyan8//9RwxwNm@jqwiR9IEtBUUldW0tXz8rW0cPT1z8kNCw8IjIuPr@svKIGKK1pF1tbkBLzqGGuzsOds1TcDq1Mczi84dC6o5OLjQ4tqQx91Ljn/8PdWw63P2pa8/@/hqaGJheIAFLRjgraCo6xXOH@4QqKCkCSy99D19EjvrxCvaI83sNR18OfS8PGJjo6OkQrJDY21s4OqNVKk0tTVwNohKYG0AhdXV2uwoLCAjCfS0PDSVOTy9CQS1tXS1sXam55fjmXhrUmUFlBIZeVCwA "Jelly – Try It Online") [All test cases](https://tio.run/##y0rNyan8//9RwxwNm@jqwiR9IEtBUUldW0tXz8rW0cPT1z8kNCw8IjIuPr@svKIGKK1pF1tbkBLzqGGuzsOds1TcDq1Mczi84dC6o5OLjQ4tqQx91Ljn/8PdWw63P2pa8/@/hqaGJheIAFLRjgraCo6xXOH@4QqKCkCSy99D19EjvrxCvaI83sNR18OfS8PGJjo6OkQrJDY21s4OqNVKk0tTVwNohKYG0AhdXV2uwoLCAjCfS0PDSVOTy9CQS1tXS1sXam55fjmXhrUmUFlBIZeVCwA "Jelly – Try It Online") *-7 bytes thanks to @JonathanAllan* **How it Works** ``` “(<[{qb/“ !"'+*-.:=AHIMOTUVWXY^_ovwx|“)>]}pd\”,Ṛ$F©f@ð®œs2¤yU⁼ main link “(<[{qb/“ !"'+*-.:=AHIMOTUVWXY^_ovwx|“)>]}pd\” The literal list of strings ['(<[{qb/', ' !"\'+*-.:=AHIMOTUVWXY^_ovwx|', ')>]}pd\\'] $ Last two links (if not part of an LCC) as a monad Ṛ Reverse array Does not vectorize. , Pair; return [x, y]. © Copy link result to register (® atom to retrieve). F Flatten list. f Filter; remove the elements from x that are not in y. @ Swaps operands. ð Start a new dyadic chain ¤ Nilad followed by links as a nilad. 2 The literal integer 2 ® Restore; retrieve the value of the register. Initially 0. œs Split x into y chunks of similar lengths. y Translate the elements of y according to the mapping in x. U Upend; reverse an array. ⁼ Equals. Does not vectorize. ``` [Answer] # Python 3, ~~211~~ ~~208~~ 195 bytes ``` lambda S,p="()<>[]{}qpbd\/",s=" !\"'+*-.:=AHIMOTUVWXY^_ovwx|":(S==S.translate({ord(s[2*x]):s[2*x+1]for s in(p,p[::-1])for x in range(7)})[::-1])*(~len(S)%2*s[len(S)//2]in s)*(not set(S)-set(p+s)) ``` Saved 13 bytes thanks to Jonathan Allan. [Answer] # [SOGL V0.12](https://github.com/dzaima/SOGL), 88 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` "el²┘N!←8mYdDm⁵╔C⅛┌6▼ģη⁷fņ‘;W‽0←}C l»{Kα}lalh=‽;KCø;{:↔³↔=?"qpbd”⁴²+:GW:2%«H+W}:h=?:CΚ}= ``` [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JTIyZWwlQjIldTI1MThOJTIxJXUyMTkwOG1ZZERtJXUyMDc1JXUyNTU0QyV1MjE1QiV1MjUwQzYldTI1QkMldTAxMjMldTAzQjcldTIwNzdmJXUwMTQ2JXUyMDE4JTNCVyV1MjAzRDAldTIxOTAlN0RDJTBBbCVCQiU3QksldTAzQjElN0RsYWxoJTNEJXUyMDNEJTNCS0MlRjglM0IlN0IlM0EldTIxOTQlQjMldTIxOTQlM0QlM0YlMjJxcGJkJXUyMDFEJXUyMDc0JUIyKyUzQUdXJTNBMiUyNSVBQkgrVyU3RCUzQWglM0QlM0YlM0FDJXUwMzlBJTdEJTNE,inputs=JTI4JTI5JTI5) ~24 bytes to add `qpbd` mirroring and 6 bytes for `(x-1 XOR 1) + 1` :/ [Answer] # [Kotlin](https://kotlinlang.org) 1.1, ~~201~~ 199 bytes ``` {var R="(<[{qb/\\dp}]>)" var m=HashMap<Any,Any>() "\"!'+*-.:=AHIMOTUVWXY^_ovwx| ".map{m[it]=it} R.indices.map{m[R[it]]=R[R.length-(it+1)]} it.zip(it.reversed()).filter{m[it.first]!=it.second}.none()} ``` ## Beautified ``` { var R = "(<[{qb/\\dp}]>)" var m = HashMap<Any, Any>() "\"!'+*-.:=AHIMOTUVWXY^_ovwx| ".map { m[it] = it } R.indices.map { m[R[it]] = R[R.length - (it + 1)] } it.zip(it.reversed()).filter { m[it.first] != it.second }.none() } ``` ## Test ``` var i:(String)->Boolean = {var R="(<[{qb/\\dp}]>)" var m=HashMap<Any,Any>() "\"!'+*-.:=AHIMOTUVWXY^_ovwx| ".map{m[it]=it} R.indices.map{m[R[it]]=R[R.length-(it+1)]} it.zip(it.reversed()).filter{m[it.first]!=it.second}.none()} fun main(args: Array<String>) { var GOOD = listOf("()()", "()()()", "[A + A]", "WOW ! WOW", "OH-AH_wx'xw_HA-HO", "(<<[[[T*T]]]>>)", "(:)", ")-(", "())(()", "qpqp") var BAD = listOf("())(", "((B))", "11", "+-*+-", "WOW ! wow", "(;)", "qppq") GOOD.filterNot { i(it) }.forEach { throw AssertionError(it) } BAD.filter { i(it) }.forEach { throw AssertionError(it) } println("Test Passed") } ``` **Can't run on TIO because 1.1 is not supported** [Answer] # [Python 2](https://docs.python.org/2/), ~~182~~ ~~167~~ ~~163~~ ~~162~~ ~~160~~ 158 bytes ``` lambda s:s[::-1]==s.translate(m(t+w,w+t),m("","").translate(None," !\"'+*-.:=AHIMOTUVWXY^_ovwx|"+t+w)) from string import* m=maketrans t=")>[{/qd" w="(<]}\pb" ``` [Try it online!](https://tio.run/##XY9NT8MwDIbv/RWeL0uaZmgcyzKpnMoBehkM1IWp01qYWJq2icgQ8NtLP5CY8MF@Lft9ZFcf9lWXl20hNu0xU7t9BiY0aRjyuRTCzGyTleaY2ZwoYpkLHLM0UAQxQKRn0ztd5gHCZINT5vNZKKL45jZZ3T@sH5@et/rdnb6QdQBKvaLRCoxtDuULHFSlG@t7SqjsLR9wnhVIl@nnRb1HzwkkC/m9qXbYFroBA4cSUiSUUAxgqKNKI2AQyV6ukzVMoMt9k8Q8irfuND25bRzxOBlsi0Wapit/JaVcLkdSOBTKycilZOTWVV2hDD3oIjMmbywUxHRPnB9DRxO5poNnPu8z4z7jf/c47Yalq19sVf/DlnpEtz8 "Python 2 – Try It Online") *Saved 2 bytes thanks to Jonathan Allan* **Explanation** First, we need to build the list of all chars that don't have a symmetric (the char itself : `A`, ... or another char `(` for `)`, ...): * `m("","")` returns a string with all the available chars. * `m("","").translate(None," \t!\"'+*-.:=AHIMOTUVWXY^_ovwx|"+t+w))` removes from all the available chars the chars that have a symmetric. Then, we map every char to its symmetric char and remove the chars that don't have a symmetric with `s.translate(m(t+w,w+t),<chars that don't have a symmetric>)` If the result equals to the reversed string, we have a symmetric string. [Answer] # [Perl 5](https://www.perl.org/), 102 + 1 (-p) = 103 bytes ``` $_=!/[^ !"'+*.:=AHIMOT-Y^_ovwx|()<>[\]{}qpbd\/\\-]/&&$_ eq reverse y|()<>[]{}qpbd/\\|)(><][}{pqdb\\/|r ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3lZRPzpOQVFJXVtLz8rW0cPT1z9ENzIuPr@svKJGQ9PGLjomtrq2sCApJUY/JkY3Vl9NTSVeIbVQoSi1LLWoOFWhEqIKqgiopkZTw84mNrq2uqAwJSkmRr@m6P//rOiC/MLYrH/5BSWZ@XnF/3ULAA "Perl 5 – Try It Online") [Answer] # [Scala](http://www.scala-lang.org/), 140 bytes ``` s.zip(s.reverse).forall(c=>(" !\"'+*-.:=AHIMOTUVWXY^_ovwx|".flatMap(x=>x+""+x)+"()<>[]{}qpbd/\\\\/dbpq}{][><)(").indexOf(c._1+""+c._2)%2==0) ``` [Try it online!](https://tio.run/##RZHBToNAEIbP9Cmmm5rudoXaHiuQ4EU8VBKtoqFIKCwJhsDCkoIiz44LTXQPM3OY@f75d0QUZuFQnD5ZVMM@THNgbc3yWIDFOXQz5Rxm8MUEGPDMSowwwQRdT2kqPAsoWL6sXMeFOcgoa8dWLTto2mXbBLal2s44ouue5x1WB9/3TXOC7MZIVDwBCZ6AJS85IhfdvPiXJVMXviNj02YjA1VXVP0TbopmbLi9MHgpGTMlKSrAAnR1skCpJJLR1ESvJbwbhPadciy0ip1ZJRjR5EyYZTgyTIxgfkRLulK1nWHZD3vn8PLqvr1/BMW5aX@QlmRhvQ85bg2zpQjRllC5qW56fteX/BSvj/Kt4xMv@873TF16IFqax6x1EhxpwWYcknlLrraGcUMGRenlcrxK8zrLsUALAaoJixrwoksTwNKFFhV5Le8ksCBgGFATQFFRVfJ@CFgmGCD3yXm8n6OejP/Yz/rhFw "Scala – Try It Online") ]
[Question] [ As [everyone knows](https://pics.me.me/i-am-mr-clever-am-ovin-fact-adding-inator-3000-to-anything-makes-12173475.png), adding `inator-3000` to the end of any noun makes it way cooler. But what else can make a word cooler? Given an ASCII string as input, output the ***coolness*** of the word. ## Calculating the coolness There are 4 elements to calculating the coolness of a word. * The word itself. The base score is the number of capital letters multiplied by 1000 * The end number. A number at the end of the word (such as burninator-**3000**) is added to the base score, **but** if the number is more than 4 digits, they're being too greedy and the number should be ignored. * The connector. A space before the end number adds 1000, while a hyphen adds 2000, any other symbol, or no symbol at all, has no effect. * The suffix. If the word ends in `ator`, double the final score. If it ends in `inator`, triple the score. These are case insensitive. So for example `Burninator-3000` can be calculated as follows: ``` 1 Capital letter - Base Score: 1000 (1000(base) + 3000(number) + 2000(hyphen)) * 3(suffix) = 18000 ``` ## Testcases ``` Burninator-3000 -> 18000 Burnator3000 -> 8000 BurNinator 100 -> 9300 BuRnInAtOr-7253 -> 42759 burn -> 0 burn- -> 0 bUrn-1 -> 3001 inator-7 -> 6021 ator 56 -> 2112 burninators 1000 -> 2000 burn_1000 -> 1000 BURNINATOR-9999 -> 65997 burninator 99999 -> 3000 burninator_99999 -> 0 Code Golfinator-3000 -> 21000 inator ator hello world-1000 -> 3000 javaiscool_99999 -> 0 hypen-ated -> 0 1000 -> 1000 -1000 -> 3000 10000 -> 0 -10000 -> 2000 BURN1N470R-3000 -> 11000 ``` ## Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so fewest bytes **in each language** wins! [Answer] ## JavaScript (ES6), ~~138~~ ~~133~~ 128 bytes ``` s=>(([,a,b,,c,d]=s.match(/((in)?ator)?((\D?)(\d+))?$/i),s.split(/[A-Z]/).length-1+(c=='-'?2:c==' '))*1e3+(d<1e4&&+d))*(b?3:2-!a) ``` ### How? The number of capital letters is given by: ``` s.split(/[A-Z]/).length - 1 ``` All other criteria are deduced from the result of the following regular expression, which is split into 4 variables: ``` /((in)?ator)?((\D?)(\d+))?$/i criterion | code | outcome \_________/ \___/\___/ -----------+-------------------------+---------- a c d end number | d < 1e4 && +d | 0 or +d \___/ connector | c == '-' ? 2 : c == ' ' | 0, 1 or 2 b suffix | * (b ? 3 : 2 - !a) | 1, 2 or 3 ``` ### Test cases ``` let f = s=>(([,a,b,,c,d]=s.match(/((in)?ator)?((\D?)(\d+))?$/i),s.split(/[A-Z]/).length-1+(c=='-'?2:c==' '))*1e3+(d<1e4&&+d))*(b?3:2-!a) let test = s => console.log((s + ' '.repeat(32)).slice(0, 32), f(s)); test("Burninator-3000") // -> 18000 test("Burnator3000") // -> 8000 test("BurNinator 100") // -> 9300 test("BuRnInAtOr-7253") // -> 42759 test("burn") // -> 0 test("burn-") // -> 0 test("bUrn-1") // -> 3001 test("inator-7") // -> 6021 test("ator 56") // -> 2112 test("burninators 1000") // -> 2000 test("burn_1000") // -> 1000 test("BURNINATOR-9999") // -> 65997 test("burninator 99999") // -> 3000 test("burninator_99999") // -> 0 test("Code Golfinator-3000") // -> 21000 test("inator ator hello world-1000") // -> 3000 test("javaiscool_99999") // -> 0 test("hypen-ated") // -> 0 test("1000") // -> 1000 test("-1000") // -> 3000 test("10000") // -> 0 test("-10000") // -> 2000 test("BURN1N470R-3000") // -> 11000 ``` [Answer] # Vanilla C, 447 bytes (Wrapped for readability) ``` #include<stdio.h> int main(int c,char**a){char*v=a[1];while(*v++);int m=0,i= 0,bn=0,s=0,b=0,mul=1;char l[256],*lp=l;v--;while(a[1]<v--) {if(!m){i=!i?1:(i*10),('0'<=*v&&*v<='9')?(bn=bn+i*(*v-'0') ):m++;}if(m==1){(*v=='-'||*v==' ')?(s+=bn?((*v=='-')?2000: 1000):0,v--):0,m++;}if(m==2){(*v>='A'&&*v<='Z')?(s+=1000,* v+=32):0,*lp++=*v;}}s+=(bn<10000)?bn:0;for(i=0;i<lp-l;i++) {if(*(l+i)=="rotani"[i]){mul=(i==5)?3:((i==3)?2:mul);}}s*= mul;printf("%d\n",s);} ``` ...or even... Friday mood! *(I didn't use any tools for alying the code. Actually, I'm really lucky I picked right column widths without any precalculations. And it even compiles!)* # Vanilla C, 789 bytes ``` #include<stdio.h> int main(int c, char**a){char *v=a[1];while (*v++);int m=0,i= 0,bn=0, s=0, b=0, mul=1 ;char l[256], *lp=l; v--; while (a[1]< v--) {if(! m){i=!i ?1:(i* 10), ('0' <=*v&& *v<= '9')? (bn=bn+ i*(*v- '0')):m++;}if( m==1) {(*v== '-'|| *v== ' ')?(s +=bn?( (*v=='-')?2000 :1000) :0,v-- ):0,m ++;} if(m==2 ){(*v >='A'&& *v<= 'Z')? (s+= 1000, *v+=32) :0,*lp ++=* v;}}s +=(bn< 10000 )?bn: 0;for(i =0;i< lp-l; i++){ if(*(l +i)== "rot" "ani"[i] ){mul= (i==5) ?3: ((i ==3)?2:mul);} } s *= mul; printf("%d\n",s);} ``` Original code: ``` #include <stdio.h> #include <math.h> int main(int argc, char** argv) { char *v = argv[1]; while(*v++); int m=0,i=-1; int bonus_number=0; int score=0; int b=0; int mul=1; char letters[256]; char* lp=letters; v--; while(argv[1]<v--) { printf(" * %c %x\n", *v, *v); if (m == 0) { if ('0'<=*v&&*v<='9') { bonus_number=bonus_number+powl(10,++i)*(*v-'0'); printf("Digit, bonus is now %d\n", bonus_number); } else { m++; } } if (m == 1) { if (*v=='-'||*v==' ') { printf("Dash/space\n"); if (bonus_number) score += (*v=='-') ? 2000 : 1000; v--; } m++; } if (m == 2) { if(*v>='A'&&*v<='Z') { printf("Upper letter\n"); score += 1000; *v += 32; } *lp++ = *v; } } score += (bonus_number<10000)?bonus_number:0; for(i=0;i<lp-letters;i++) { // printf("%d: %c\n\n", i, *(letters+i)); if (*(letters+i) == "rotani"[i]) { if (i == 3) { printf("2x!\n"); mul = 2; } if (i == 5) { printf("3x!\n"); mul = 3; } } } score *= mul; printf("Score: \n%d\n", score); } ``` After 1st minimization: ``` #include <stdio.h> int main(int c, char** a) { char *v = a[1];while(*v++); int m=0,i=0,bn=0,s=0,b=0,mul=1; char l[256],*lp=l; v--; while(a[1]<v--) { if (!m) { i=!i?1:(i*10), ('0'<=*v&&*v<='9') ? (bn=bn+i*(*v-'0')) : m++; } if (m == 1) { (*v=='-'||*v==' ') ? (s += bn ? ((*v=='-') ? 2000 : 1000) : 0, v--):0,m++; } if (m == 2) { (*v>='A'&&*v<='Z') ? (s += 1000, *v += 32):0, *lp++ = *v; } } s += (bn<10000)?bn:0; for(i=0;i<lp-l;i++) { if (*(l+i) == "rotani"[i]) { mul=(i==5)?3:((i==3)?2:mul); } } s *= mul; printf("%d\n", s); } ``` # Test cases ``` #!/usr/bin/env python3 import subprocess TESTCASES = ''' Burninator-3000 -> 18000 Burnator3000 -> 8000 BurNinator 100 -> 9300 BuRnInAtOr-7253 -> 42759 burn -> 0 burn- -> 0 bUrn-1 -> 3001 inator-7 -> 6021 ator 56 -> 2112 burninators 1000 -> 2000 burn_1000 -> 1000 BURNINATOR-9999 -> 65997 burninator 99999 -> 3000 burninator_99999 -> 0 Code Golfinator-3000 -> 21000 inator ator hello world-1000 -> 3000 javaiscool_99999 -> 0 hypen-ated -> 0 1000 -> 1000 -1000 -> 3000 10000 -> 0 -10000 -> 2000 BURN1N470R-3000 -> 11000 ''' TESTCASES = dict(map(lambda x: x.split(' -> '), filter(None, TESTCASES.split('\n')))) def process(arg): return subprocess.Popen(['./a.out', arg], stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()[0].strip().split(b'\n')[-1].decode('utf-8') for key, value in TESTCASES.items(): assert value == process(key), '"{}" should yield {}, but got {}'.format( key, value, process(key) ) ``` [Answer] # C#, ~~322~~ 317 bytes ``` namespace System.Linq{s=>{var m=Text.RegularExpressions.Regex.Match(s,"(.*?)([- ])?(\\d+)$");string t=m.Groups[1].Value.ToLower(),c=m.Groups[2].Value,n=m.Groups[3].Value;return(s.Count(char.IsUpper)*1000+(n.Length>4|n==""?0:int.Parse(n))+(c==" "?1000:c=="-"?2000:0))*(t.EndsWith("inator")?3:t.EndsWith("ator")?2:1);}} ``` [Try it online!](https://tio.run/##jVRtb9owEP7OrzhF/WBTYvGyrmo7QB3qKiRKKwbrB4oqLzEkU7CpbSgV47czOyG8lIhxH@zzc3fPXXJne8odCy5WKzDC6ZipCfUY/PxQmo1JK@RvOWtZxKsVL6JKwdPmvLVYUZrq0IOZCH14oCFHeM@872zlx5R735SWIR8VIOS6BkOogoJq7cD1MNjKjEoYm5Aum2vSYaNpROXdfCKZUqHgykJsTh6o9gKkCuAgkq9j1HdhgOvo5cU/x2cOvsmkTsoCbdjH5F6K6UT1SwPyi0ZTRrqiJd6ZRLgA3q5Dee1QAL4LV9bwYabM1JLpqeSAMo27JZKGmHKNvIBK0lS9yYRJDHkoFYtFOP9fNOKkxfhIB1CDL/DXVlwFx4E6FOHadoM8UakY4hifQObF0WDD4/TXkCCuRcoJUsRHaY5b84A0ueO@eg51gJyQUy2kgw17xVDvmjaGsjGUMtq7vMnlstvdH4BmSjeoYmYKTxxC57vpVlKPWzFf6hQSyAI753biYn9PgnR4k9/qR@leli8qTiGb@7chsu52d2OlZ5SS1dYpL60eM198TT0Tk4pbcYz5tZTW1@u0m@3b7mPHvTKyzwNXh9jrGsvmbgifwb2Ihp9@y5ovXgIWRQLehYx8Ny3jD53RUHlCRMf5g48J4y7VzLdRafSGxu5bpOicNAFDIRn1AkDpzV8PgrkK26HAJ85Ew7w@ImLkWYaamYeUoTNnkbIswa3BYojSM15mPULL3NGHIs3QYdSPE3yi2IYn2nK1@gc "C# (Mono) – Try It Online") Full/Formatted Version: ``` namespace System.Linq { class P { static void Main() { Func<string, int> f = s => { var m = Text.RegularExpressions.Regex.Match(s, "(.*?)([- ])?(\\d+)$"); string t = m.Groups[1].Value.ToLower(), c = m.Groups[2].Value, n = m.Groups[3].Value; return ( s.Count(char.IsUpper) * 1000 + (n.Length > 4 | n == "" ? 0 : int.Parse(n)) + (c == " " ? 1000 : c == "-" ? 2000 : 0) ) * (t.EndsWith("inator") ? 3 : t.EndsWith("ator") ? 2 : 1); }; string[] testCases = { "Burninator-3000", "Burnator3000", "BurNinator 100", "BuRnInAtOr-7253", "burn", "burn-", "bUrn-1", "inator-7", "ator 56", "burninators 1000", "burn_1000", "BURNINATOR-9999", "burninator 99999", "burninator_99999", "Code Golfinator-3000", "inator ator hello world-1000", "javaiscool_99999", "hypen-ated", "1000", "-1000", "10000", "-10000" }; foreach (string testCase in testCases) { Console.WriteLine($"{testCase} -> {f(testCase)}"); } Console.ReadLine(); } } } ``` Splitting the regex off into it's own method is now 4 bytes longer (unless I missed something) due to only being allowed one lambda. This it comes in at 321 bytes: ``` namespace System.Linq{string m(string s,int n)=>Text.RegularExpressions.Regex.Match(s,"(.*?)([- ])?(\\d+)$").Groups[1].Value.ToLower();s=>{string t=m(s,1),c=m(s,2),n=m(s,3);return(s.Count(char.IsUpper)*1000+(n.Length>4|n==""?0: int.Parse(n))+(c==" "?1000:c=="-"?2000:0))*(t.EndsWith("inator")?3:t.EndsWith("ator")?2:1);}} ``` [Answer] ## Perl, 108 bytes **107 bytes code + 1 for `-p`.** ``` $\+=1e3*y/A-Z//;s/( |-)?(\d+)$//;$\+=$2*($2<1e4);$\+={$",1e3,"-",2e3}->{$1};s/(in)?ator$//i&&($\*=$1?3:2)}{ ``` [Try it online!](https://tio.run/##HctLCsIwFAXQrUh5lKTtIz@dqDXoMiQTwQwCJQltHUjM1o2Nw/s50c7ToRQw/Sis6t7sinfGTgsjuw9STcyzp7AV9QCyIyDPwu7pPydohg0NDTaDtCrjJYHI1TpP9WMN8yZd2xIw3QhCq6OkOZVye83e@bqj4px/Q1xd8EvB@AM "Perl 5 – Try It Online") [Answer] # PHP>=7.1, 165 bytes ``` preg_match("#((in)?ator)?((\D)?(\d+))?$#i",$argn,$m);[,$a,$i,,$c,$d]=$m;echo($d*($d<1e4)+(preg_match_all("#[A-Z]#",$argn)+($c!="-"?$c==" "?:0:2))*1e3)*($a?$i?3:2:1); ``` [Testcases](http://sandbox.onlinephpfunctions.com/code/0aca245ecf661c510d96c2ba23f0320f0ec9106e) ]
[Question] [ ## Introduction Let's define a new arithmetical operation, which I call *zipper multiplication*. To zipper multiply two nonnegative integers, you add leading zeros to make the lengths match, multiply the corresponding base-10 digits of the numbers, add leading zeros to the results to get 2-digit numbers, concatenate them, and finally drop leading zeros. Here's an example with **A = 1276** and **B = 933024**: ``` 1. Add leading zeros A = 001276 B = 933024 2. Multiply digit-wise A = 0 0 1 2 7 6 B = 9 9 3 0 2 4 -> 0 0 3 0 14 24 3. Pad to 2 digits -> 00 00 03 00 14 24 4. Concatenate -> 000003001424 5. Drop leading zeros -> 3001424 ``` The operation is extended to all integers with the usual sign rules: positive times negative is negative, negative times negative is positive and so on. ## The task Your inputs are two integers, and your output is their zipper multiplication. You should be able to handle arbitrarily large inputs. Input and/or output can be in string format (and indeed must be, if your language doesn't support arbitrarily large integers). Note that `-0` is not a valid input or output. ## Rules and scoring You can write a full program or a function, and the lowest byte count wins. ## Test cases ``` 0 0 -> 0 302 40 -> 0 302 -40 -> 0 -4352 448 -> -122016 0 6623 -> 0 0 -6623 -> 0 20643 -56721 -> -1000420803 63196 21220 -> 1203021800 1276 933024 -> 3001424 -1276 933024 -> -3001424 -1276 -933024 -> 3001424 5007204555 350073039 -> 12001545 -612137119 -8088606033 -> 816060042000327 3389903661 -6619166963 -> -18180881090018543603 -23082746128560880381 1116941217 -> -8050600723200060807 -668336881543038127783364011867 896431401738330915057436190556 -> -485448120906320001351224000900090235004021121824000900403042 402878826066336701417493206805490000415 312487283677673237790517973105761463808 -> 120004325656161618004242182118140007280900200921180018080025285400000000320040 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~11~~ 10 bytes ``` ƓDUz0P€Uḅ³ ``` [Try it online!](https://tio.run/nexus/jelly#@39ssktolUHAo6Y1oQ93tB7a/P@/oZGxjompmbkFAA "Jelly – TIO Nexus") I couldn't get this down to 10 bytes by myself, but @Pietu1998 pointed me to an atom I'd missed, this giving this 10-byte solution. Unusually for Jelly, this one takes input from standard input (in the form `1276,933024`), not from the command line (this enables the use of the `³` command, which returns the command line argument, defaulting to 100). Explanation: ``` ƓDUz0P€Uḅ³ Ɠ read standard input D convert to base 10 U reverse elements z0 transpose, padding the end with zeroes P€ take the product of each (€) inner list U reverse elements back b³ convert from base 100 ``` The use of base 100 is a simple way to implement the "pad to 2 digits, then convert to base 10" technique. The only other subtle thing here is the reversing; we want to pad with zeroes at the start of the number, but Jelly's `z` command pads at the end, so reversing the lists means that `z` will pad correctly. [Answer] # Python 2, 99 bytes ``` a,b=input();o=0;p=1-2*(a*b<0);a,b=abs(a),abs(b) while a:o+=a%10*(b%10)*p;p*=100;a/=10;b/=10 print o ``` A lot of the bytes are there to account for the sign in case of negative input. In Python, `n%d` is always non-negative if `d` is positive1. In my opinion this is generally desirable, but here it seems inconvenient: removing the calls to `abs` would break the above code. Meanwhile `p` keeps track of the "place value" (ones, hundreds, etc.) and also remembers the desired sign of the output. The code is basically symmetric in `a` and `b` except in the `while` condition: we keep going until `a` is zero, and terminate at that time. Of course if `b` is zero first, then we'll end up adding zeroes for a while until `a` is zero as well. --- 1 For example, `(-33)%10` returns `7`, and the integer quotient of `(-33)/10` is `-4`. This is correct because `(-4)*10 + 7 = -33`. However, the zipper product of `(-33)` with `33` must end in `3*3 = 09` rather than `7*3 = 21`. [Answer] ## JavaScript (ES6), 44 bytes ``` f=(x,y)=>x&&f(x/10|0,y/10|0)*100+x%10*(y%10) ``` Conveniently this automatically works for negative numbers. [Answer] # C, 77 bytes -2 bytes for removing redundant braces (`*` is associative). ``` r,t;f(a,b){t=1;r=0;while(a|b)r+=t*(a%10)*(b%10),a/=10,b/=10,t*=100;return r;} ``` `t`=1,100,10000,... is used for padding. As long as `a` or `b` is not zero keep multiplicating the last digit `%10` with `t` and accumulate. Then erease the last digit of `a` and `b` (`/=10`) and shift `t` by 2 digits (`*=100`). Ungolfed and usage: ``` r,t; f(a,b){ t=1; r=0; while(a|b) r+=t*(a%10)*(b%10), a/=10, b/=10, t*=100; return r; } main(){ printf("%d\n", f(1276,933024)); } ``` [Answer] # [Actually](https://github.com/Mego/Seriously), ~~23~~ 19 bytes Input is taken as two strings. Also, apparently attempting to convert from base 100, as ais523 does in their Jelly answer, doesn't work so well in Actually. Would have saved 9 bytes too if it worked :/ Golfing suggestions welcome! [Try it online!](https://tio.run/nexus/actually#ATEAzv//a2DimYLiiYhSYE3ilKzDsWBpz4TilaRAz4AqYE3Oo///IjEyNzYiCiI5MzMwMjQi "Actually – TIO Nexus") **Edit:** -4 bytes from changing how the result is built up into a new number. ``` k`♂≈R`M┬ñ`iτ╤@π*`MΣ ``` **Ungolfing** ``` Implicit input a and b. k Wrap a and b into a list. `...`M Map over the list of strings. ♂≈ Convert each digit to its own int. R Reverse for later. ┬ Transpose to get pairs of digits from a and b. ñ enumerate(transpose) to get all of the indices as well. `...`M Map over the transpose. i Flatten (index, pair) onto the stack. τ╤ Push 10**(2*index) == 100**index to the stack. @π Swap and get the product of the pair of integers. * Multiply the product by 100**index. Σ Sum everything into one number. Implicit return. ``` [Answer] ## Mathematica 66 Bytes ``` i=IntegerDigits;p=PadLeft;FromDigits@Flatten@p[i/@Times@@p[i/@#]]& ``` Ungolfed: ``` IntegerDigits/@{1276,933024} PadLeft[%] Times@@% IntegerDigits/@% PadLeft[%] Flatten@% FromDigits@% ``` where % means the previous output yields ``` {{1,2,7,6},{9,3,3,0,2,4}} {{0,0,1,2,7,6},{9,3,3,0,2,4}} {0,0,3,0,14,24} {{0},{0},{3},{0},{1,4},{2,4}} {{0,0},{0,0},{0,3},{0,0},{1,4},{2,4}} {0,0,0,0,0,3,0,0,1,4,2,4} 3001424 ``` [Answer] # R, ~~182~~ ~~110~~ ~~107~~ 86 bytes No longer the longest answer (thanks, Racket), and in fact shorter than the Python solution (a rare treat)! An anonymous function that takes two integers as input. ``` function(a,b)sum((s=function(x)abs(x)%%10^(99:1)%/%(e=10^(98:0))*e)(a)*s(b))*sign(a*b) ``` Here's how it works. The zipper multiplication involves splitting the input numbers into their constituent digits.We take the absolute value of number and carry out modulo for descending powers of 10: ``` abs(x) %% 10^(99:1) ``` So here we're taking one number, `x`, and applying modulo with 99 other numbers (`10^99` through `10^1`). R implicitly repeats `x` 99 times, returning a vector (list) with 99 elements. (`x %% 10^99`, `x %% 10^98`, `x %% 10^97`, etc.) We use `10^99` through `10^1`. A more efficient implementation would use the value of number of digits in the longest number (check the edit history of this post; previous versions did this), but simply taking `99..1` uses fewer bytes. For `x = 1276` this gives us ``` 1276 1276 1276 ... 1276 276 76 6 ``` Next, we use integer division by descending powers of 10 to round out the numbers: ``` abs(x) %% 10^(99:1) %/% 10^(98:0) ``` This yields ``` 0 0 0 ... 1 2 7 6 ``` which is exactly the representation we want. In the code, we end up wanting to use `10^(98:0)` again later, so we assign it to a variable: ``` abs(x) %% 10^(99:1) %/% (e = 10^(98:0)) ``` (Wrapping an expression in parentheses in R generally evaluates the expression (in this case, assigning the value of `10^(98:0)` to `e`), and then also returns the output of the expression, allowing us to embed variable assignments within other calculations.) Next, we perform pairwise multiplication of the digits in the input. The output is then padded to two digits and concatenated. The padding to two digits and concatenating is equivalent to multiplying each number by `10^n`, where `n` is the distance from the right edge, and then summing all the numbers. ``` A = 0 0 1 2 7 6 B = 9 9 3 0 2 4 -> 0 0 3 0 14 24 -> 00 00 03 00 14 24 -> 0*10^6 + 0*10^5 + 3*10^4 + 0*10^3 + 14*10^2 + 24*10^1 = 000003001424 ``` Notably, because multiplication is commutative, we can perform the multiplication by `10^n` *before* we multiply **A** by **B**. So, we take our earlier calculation and multiply by `10^(98:0)`: ``` abs(x) %% 10^(99:1) %/% 10^(98:0) * 10^(98:0) ``` which is equivalent to ``` abs(x) %% 10^(99:1) %/% (e = 10^(98:0)) * e ``` After applying this to **A**, we would then want to repeat this whole operation on **B**. But that takes precious bytes, so we define a function so we only have to write it once: ``` s = function(x) abs(x) %% 10^(99:1) %/% (e=10^(98:0)) * e ``` We do our embedding-in-parentheses trick to allow us to define and apply a function at the same time, to call this function on **A** and **B** and multiply them together. (We could have defined it on a separate line, but because we're eventually going to put all of this into an anonymous function, if we have more than one line of code then everything needs to be wrapped in curly braces, which costs valuable bytes.) ``` (s = function(x) abs(x) %% 10^(99:1) %/% (e=10^(98:0)) * e)(a) * s(b) ``` And we take the sum of all of this, and we're nearly finished: ``` sum((s = function(x) abs(x) %% 10^(99:1) %/% (e=10^(98:0)) * e)(a) * s(b)) ``` The only thing to consider now is the sign of the input. We want to follow regular multiplication rules, so if one and only one of **A** and **B** is negative, the output is negative. We use the function `sign` which returns `1` when given a positive number and `-1` when given a negative number, to output a coefficient that we multiply our entire calculation by: ``` sum((s = function(x) abs(x) %% 10^(99:1) %/% (e=10^(98:0)) * e)(a) * s(b)) * sign(a * b) ``` Finally, the whole thing is wrapped into an anonymous function that takes `a` and `b` as input: ``` function(a, b) sum((s = function(x) abs(x) %% 10^(99:1) %/% (e=10^(98:0)) * e)(a) * s(b)) * sign(a * b) ``` Remove the whitespace and it's 86 bytes. [Answer] # [Python 3](https://docs.python.org/3/), ~~92 bytes~~, 119 bytes ``` lambda m,n:(1-(n*m<0)*2)*int(''.join([f"{int(a)*int(b):02}"for a,b in zip(str(abs(n))[::-1],str(abs(m))[::-1])][::-1])) ``` [Try it online!](https://tio.run/##NcxLCsIwFIXhrYROem9JJA9RDLqS2kGCBCPmprSZqLj2aNGODv83OOOjXDOZGk7nenfJXxxLnCwoAdSlo8ROYxepQNtubjkS9KF5Le1@7NFK/W5CnpjjnkVizzjCXCZwfgZC7K0VauCrpFVw@C/WcVqeAgil9zt@MEbq7Zc/ "Python 3 – Try It Online") *Fix for handling negative numbers cost 29 bytes :/* [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` Tвí0ζPRтβ ``` Port of [*@user62131*'s Jelly answer](https://codegolf.stackexchange.com/a/102647/52210) [Try it online](https://tio.run/##yy9OTMpM/f8/5MKmw2sNzm0LCLrYdG7T///RuoZG5mY6lsbGBkYmsQA) or [verify all test cases](https://tio.run/##bVA7TkNBDLxKlHpX8thef6pcASG6pxQgUVBRICGlpeAA3IMmBRegj@AKXOThjYCKrWbGnrG99w/XN3e36@Nht918Pb9strvDevVxfH@l09vF5efT6bi2dVmo0b4tQtz0F/Qz6iqjRI3C1MxYzqD/ICZTaX2YM4qaIK0xmKcX7NZSKkxn0n@0//FB5Ew6xmgysZDkbDMwxIFsPSjCyEjmZJHIJDHDXAYJs7RZ6CwU7FrGGFYWkkADYKmV5edQCxGLwFCZZXafghIQ5i2yrkIxl5IpMWi4Sk2hMawClDg8gmsbK58TFK4p9R1BQ5PqKeoSsIZzVIubC4t7RcDTBRVpUJO6ar//Bg). **Explanation:** ``` Tв # Convert both integers in the (implicit) input-pair to a base-10 list í # Reverse each inner list ζ # Zip/transpose; swapping rows/columns, 0 # using 0 as filler for unequal length lists P # Take the product of each inner pair R # Reverse the list of integers тβ # Convert it from a base-100 list to a base-10 integer # (after which the result is output implicitly) ``` [Answer] # [Julia](https://julialang.org), ~~70~~ 64 bytes Big thanx to @MarcMush for his advices! ``` ~=digits∘abs a\b=evalpoly(big(100),prod.(zip(~a,~b)))sign(a*b) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=bVNBbttADDz0FL1CRnuQilVBLrnc3YOBJN9IcpDhxHCRxkbsFGgPOfcJBXrJJY9qj31Jh3JSNGgkyF4OyeFwLP94_Hh3vR4ffr2ZLcf9OD9rzqgNFFq6CM2ZUAytvoiGv-GgkjytBSjHSGwOI20W5akI0fBPGMkU5yFZjuxtRKSRColnTbhaaKOThZYjYSIXmjo5ZqSqANLQChFr1EnGi8zR8H9qeKUrEeVImlIC7IGQ1GkmcdI0dRtHlswMfChUipGRQH1hP7luIol5skZKrSRmPO3Llc2q-aZc2HuZKphLUrHDrkMUKjErhpRkqCApaGZmq4rBGasUSj4oR_FRKKJ8EGZFxEAKOm-LOTugxFwsQ2CFy4wwC3CqnChlTOZKKVlojgaFEkUjVNlEzpLguuJUpye6KQr7IaU844ofRKNLQKbkUiKMMEzO8JWzVlAZRKtzkLJ7y1FLjgU12bJEyRkiONcsDFHGagJ_oMmtJ5WYLBn7Xdxi9fFYi10CeFwGCqtjbig8oZhgoeeny9dRf2UumrdtJnzMxvlyvVrvd924wNP3wMbzxfzy83i93Vx_6RbrVYc3sQ-fxm23vd0sw9f1tpuNYbbo-363Xt104_tF_3i3vxrKz-P7J7rf376DsHmdymk-dM5zP4b713jeXW1u2-4knIZNP_c_X3N0PO52l7f79uT8dD7fNJc3y0Ptw8Ph-w8) [Answer] ## Pyke, 16 bytes ``` FY_),FBw�+`t)_sb ``` [Try it here!](http://pyke.catbus.co.uk/?code=FY_%29%2CFB100%2B%60t%29_sb&input=%5B1276%2C+933024%5D) Where � is the byte `0x84` or `132` [Answer] # PHP, 84 bytes ``` for(list(,$a,$b)=$argv,$f=1;$a>=1;$a/=10,$b/=10,$f*=100)$r+=$a%10*($b%10)*$f;echo$r; ``` slightly longer with string concatenation (86 bytes): ``` for(list(,$a,$b)=$argv;$a>=1;$a/=10,$b/=10)$r=sprintf("%02d$r",$a%10*($b%10));echo+$r; ``` [Answer] ## Racket 325 bytes ``` (let*((g string-append)(q quotient/remainder)(l(let p((a(abs a))(b(abs b))(ol'()))(define-values(x y)(q a 10)) (define-values(j k)(q b 10))(if(not(= 0 x j))(p x j(cons(* y k)ol))(cons(* y k)ol)))))(*(string->number (apply g(map(λ(x)(let((s(number->string x)))(if(= 2(string-length s)) s (g "0" s))))l)))(if(<(* a b)0)-1 1))) ``` Ungolfed: ``` (define (f a b) (let* ((sa string-append) (q quotient/remainder) (ll (let loop ((a (abs a)) (b (abs b)) (ol '())) (define-values (x y) (q a 10)) (define-values (j k) (q b 10)) (if (not(= 0 x j)) (loop x j (cons (* y k) ol)) (cons (* y k) ol))))) (*(string->number (apply sa (map (λ (x) (let ((s (number->string x))) (if (= 2 (string-length s)) s (sa "0" s)))) ll))) (if (< (* a b) 0) -1 1)))) ``` Testing: ``` (f 1276 933024) (f 302 40) (f 0 6623) (f 63196 21220) (f 20643 -56721) ``` Output: ``` 3001424 0 0 1203021800 -1000420803 ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~153~~ 151 bytes ``` param($a,$b)do{$x,$y=$a[--$i],$b[$i]|%{if($_-eq45){$s+=$_;$_=0}$_} $r=(+"$x"*"$y"|% t*g "00")+$r}while($x+$y)$s+$r-replace'(?<!\d)0+(?=\d)|--|-(?=0+$)' ``` [Try it online!](https://tio.run/##fVRhb9owEP3Or8gidyQFS3e@89nehrr/0U2Itulaiaks7VQq4Lezs4GCtnZBJM69d@@e7yIvHp67/vGum8@35raaVKvtYtbPfjZmNjZX7c3DyizH5mViZpfWmvvvGrzUx/psdX/bmKntfrFvV@ZxNDHTz2Y6gY2ZbgamnzSj2izr89q81Ouz6un8R1UD1O3I9Jvnu/t515jlyLy0mml623eL@ey6GzYXXz58u2lh1FxM9Lm2dm11CSPTDrebweBrM6j0GjdDGI4rvVXl3h6iBC7H@T3A/otYJr9L4lgwi84BypFRSok4@ju1APYtxIEwFdRLcLjXBQB2EIGORCFMkokuVy08dKBuMcKJHrpQWIkU4kIjAGRdHzfyBsm@z7L/0/IAwQF77zOV8isBpYM/QM/@RFPQIQXEVIQjxCggQLu2RMwveecA5MLJTCimBCSC@z5iQpEktG9XxKyEkLRe9Exy2jjrCKILrKWjF@UBxaKDiJJYDYWdTASfywdH2YAyIZw6l0gkWkX1s4ILIQcYEKOErBeTjhI1EEgRSOjBBzWDCbyXXQ1We6zJalVKGSSv82RdpfJ3uYWsU1Vf8RBnnTO7oxnFY4jRabtEPQSdCQZOKii6Cc5KwLibCDqOwUVlBQnkKAS1gyEFQrUnyELavNd5AZPz4gXzL@ZhcDaim8RsRpWyISWmHMv91j6B89rbjJcrb4zzN9lW6@qsWhXb5ZQYm2656K6fuhs9P8x0B/Td4@/5kwY@6rFiZpW5KvHaNHtIj47XvPbTIaEebLZ/AA "PowerShell – Try It Online") Less golfed: ``` param($a,$b) do{ $x,$y=$a[--$i],$b[$i]|%{ if($_-eq45){ # [char]45 is '-' $signs+=$_ $_=0 } $_ # a digit or $null } $res=(+"$x"*"$y"|% toString "00")+$res # "00" is the custom format to get 2-digit number } while($x+$y) $signs+$res-replace'(?<!\d)0+(?=\d)|--|-(?=0+$)' # cleanup and return ``` [Answer] # [Perl 5](https://www.perl.org/) `-MList::Util=min`, 140 bytes ``` @a=<>=~/\S/g;@F=<>=~/\S/g;$q=1+min$#a,$#F;say+('-'x("@a@F"=~y/-//%2).sprintf'%02d'x$q,map$F[$_]*$a[$_],-$q..-1)=~s/^-?\K0+//r=~s/^-0*$//r||0 ``` [Try it online!](https://tio.run/##TY47D4IwGEV3fwZ@BHmUthgY0CoTizoZJ1FTo5ImyKsMkBh@urXGxencc5d763tbhEolnC1XbMTZHueLJP0TaBh1n6KEKfdgmi4kH9yZhax@ZiQ8SQ02DhhhbAa2L@tWlN3DMklws3povCevIT3C5eQA/8JD0Pg@ojYbJT6jdbYhLsbtz4gDOr9eRCk6QVEUzN9V3YmqlArtQp9QorkVsovjQycKpj/p4ipyvalQ8QE "Perl 5 – Try It Online") ]
[Question] [ A [highly composite number](https://en.wikipedia.org/wiki/Highly_composite_number) is a positive integer that has more divisors than any smaller positive integer has. This is [OEIS sequence A002182](https://oeis.org/A002182). Its first 20 terms are ``` 1, 2, 4, 6, 12, 24, 36, 48, 60, 120, 180, 240, 360, 720, 840, 1260, 1680, 2520, 5040, 7560 ``` For example, `4` is in the sequence because it has 3 divisors (namely 1, 2, 4), whereas 3 only has 2 divisors, 2 also has 2 divisors, and 1 has 1 divisors. ### Challenge Given a positive integer input *n*, output either the *n*-th highly composite number or the first *n* highly composite numbers, at your choice (but the choice must be the same for every input *n*). ### Rules The program or function should theoretically work for arbitrarily large inputs given infinite time and memory, and without considering data type limitations. Essentially, this means no hardcoding a finite number of values. In practice, the program or function should run in a reasonable amount of time, say less than 1 minute, for *n* up to 20. Maximum input or output may be limited by your language standard data type (but again, the algorithm should theoretically work for arbitrarily large numbers). Any reasonable input and output format is allowed, including unary. Code golf. Fewest bytes wins. [Answer] # Jelly, 15 bytes ``` ,®ÆDL€ṛ©0>/?µƓ# ``` For input **n**, this prints the first **n** highly composite numbers. For **n = 20**, it takes less than two seconds on [Try it online!](http://jelly.tryitonline.net/#code=LMKuw4ZETOKCrOG5m8KpMD4vP8K1xpMj&input=MjA) ### How it works ``` ,®ÆDL€ṛ©0>/?µƓ# Main link. No implicit input. µ Push the chain to the left on the local link stack. Ɠ Read an integer n from STDIN. # Execute the chain for k = 0, 1, 2, ..., until it returned a truthy value n times. Return the list of matches. ,® Pair k with the value in the register (initially 0). ÆD Compute the divisors of k and the register value. L€ Count both lists of divisors. ? If >/ k has more divisors than the register value: ṛ© Save k in the register and return k. 0 Else: Return 0. ``` ## Alternate version, 13 bytes (non-competing) While the below code worked in the latest version of Jelly that precedes this challenge, the implementation of `M` was very slow, and it did not comply with the time limit. This has been fixed. ``` ÆDL®;©MḢ’>µƓ# ``` [Try it online!](http://jelly.tryitonline.net/#code=w4ZETMKuO8KpTeG4ouKAmT7CtcaTIw&input=MjA) ### How it works ``` ÆDL®;©MḢ’>µƓ# Main link. No implicit input. µ Push the chain to the left on the local link stack. Ɠ Read an integer n from STDIN. # Execute the chain for k = 0, 1, 2, ..., until it returned a truthy value n times. Return the list of matches. ÆD Compute the divisors of k. L Count them. ®; Append the count to the list in the register (initially 0 / [0]). © Save the updated list in the register. M Obtain all indices the correspond to maximal elements. Ḣ Retrieve the first result. ’> Subtract 1 and compare with k. This essentially checks if the first maximal index is k + 2, where the "plus 2" accounts for two leading zeroes (initial value of the register and result for k = 0). ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~15~~ 14 bytes The input in zero-indexed. That means that `n = 0` gives `1`, `n = 1` gives `2`, etc. Code: ``` $µ>DÑgD®›i©¼}\ ``` Explanation: ``` $ # Pushes 1 and input µ # Counting loop, executes until the counting variable is equal to input > # Increment (n + 1) DÑ # Duplicate and calculate all divisors gD # Get the length of the array and duplicate ® # Retrieve element, standardized to zero ›i } # If greater than, do... © # Copy value into the register ¼ # Increment on the counting variable \ # Pop the last element in the stack ``` Calculates *n = 19*, which should give `7560` in about 10 seconds. [Try it online!](http://05ab1e.tryitonline.net/#code=JMK1PkTDkWdEwq7igLppwqnCvH1c&input=MTk) Uses **CP-1252** encoding. [Answer] # [MATL](https://esolangs.org/wiki/MATL), ~~26~~ 24 bytes ``` ~XKx`K@@:\~s<?@5MXKx]NG< ``` [**Try it online!**](http://matl.tryitonline.net/#code=flhLeGBLQEA6XH5zPD9ANU1YS3hdTkc8&input=MTA) The current largest number of divisors found is kept in clipboard K. Highly composite numbers (HCN) are kept directly on the stack. A loop keeps testing candidates to HCN. When one is found it is left on the stack, and clipboard K is updated. The loop exits when the desired number of HCN have been found. ``` ~ % take input implicitly (gets stored in clipboard G). Transform into a 0 % by means of logical negation XKx % copy that 0 into clipboard K, and delete ` % do...while K % push largest number of divisors found up to now @ % push iteration index, i: current candidate to HCN @: % range [1,...,i] \ % modulo operation ~s % number of zeros. This is the number of divisors of current candidate < % is it larger than previous largest number of divisors? ? % if so: a new HCN has been found @ % push that number 5M % push the number of divisors that was found XKx % update clipboard K, and delete ] % end if N % number of elements in stack G< % is it less than input? This the loop condition: exit when false % end do...while implicitly % display all numbers implicitly ``` [Answer] ## Perl, ~~60~~ 57 + 1 = 58 bytes ``` $,++;$==grep$,%$_<1,1..$,;$_--,$m=$=if$=>$m;$_?redo:say$, ``` Requires `-n` and the free `-M5.010`|`-E`: ``` $ perl -nE'$,++;$==grep$,%$_<1,1..$,;$_--,$m=$=if$=>$m;$_?redo:say$,' <<< 10 120 ``` How it works: ``` $,++; $==grep$,%$_<1,1..$,; # Calculate total numbers of divisors for `$,` $_--,$m=$=if$=>$m; # Set `$m`ax divisors to `$=`ivisors if `$m>$=` $_?redo:say$, # Repeat or print ``` [Answer] # JavaScript (ES6) 72 Straightforward implementation. Time near 20 sec for input 20 ``` x=>{for(i=e=n=0;i<x;d>e&&(++i,e=d))for(d=1,j=++n;--j;)n%j||++d;return n} ``` The eval trick could save a byte doubling the run time ``` x=>eval("for(i=e=n=0;i<x;d>e&&(++i,e=d))for(d=1,j=++n;--j;)n%j||++d;n") ``` **Less golfed** ``` x=>{ for(i = e = 0, n = 1; i < x; n++) { for(d = 1, j = n; --j; ) { if (n%j == 0) ++d; } if (d > e) ++i, e = d; } return n; } ``` [Answer] # Pyth, ~~17~~ 16 bytes *1 byte thanks to Jakube* ``` uf<Fml{yPd,GTGQ1 ``` [Test suite](https://pyth.herokuapp.com/?code=uf%3CFml%7ByPd%2CGTGQ1&test_suite=1&test_suite_input=0%0A9%0A19&debug=0) Takes a 0-indexed **n**, and returns the **nth** highly composite number. Explanation: ``` uf<Fml{yPd,GThGQ1 Input: Q = eval(input()) u Q1 Apply the following function Q times, starting with 1. Then output the result. lambda G. f hG Count up from G+1 until the following is truthy, lambda T. ,GT Start with [G, T] (current highly comp., next number). m Map over those two, lambda d. Pd Take the prime factorization of d, with multiplicity. y Take all subsets of those primes. { Deduplicate. At this point, we have a list of lists of primes. Each list is the prime factorization of a different factor. l Take the length, the number of factors. <F Check whether the number of factors of the previous highly composite number is smaller than that of the current number. ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes ``` 1Æd€<Ṫ$PƊ# ``` [Try it online!](https://tio.run/##y0rNyan8/9/wcFvKo6Y1Ng93rlIJONal/P@/KQA "Jelly – Try It Online") Returns the first \$n\$ highly composite numbers. My guess is that this uses features unavailable when Dennis first posted a [Jelly answer](https://codegolf.stackexchange.com/a/74512/66833), but this uses a sufficiently different algorithm that I thought it was ok to post as a separate answer ## How it works ``` 1Æd€<Ṫ$PƊ# - Main link. Takes no arguments 1 Ɗ# - Read an integer n from STDIN and run the following over k = 1, 2, 3, ... until n return true: € - Generate the range [1, 2, ..., k] and do the following over each: Æd - Calculate the divisor count of each, yielding [σ₀(1), σ₀(2), ..., σ₀(k)] $ - Group the previous two commands together: Ṫ - Remove σ₀(k) from the list and return it < - Generate [σ₀(1)<σ₀(k), σ₀(2)<σ₀(k), ..., σ₀(k-1)<σ₀(k)] P - Are all values true? ``` [Answer] # Ruby, ~~70~~ ~~69~~ ~~67~~ ~~66~~ ~~64~~ 62 ``` ->n{r=k=0 0until(r<t=(1..k+=1).count{|d|k%d<1})&&1>n-=t/r=t k} ``` Straightforward implementation. [Answer] # C, 98 bytes ``` f,i,n,j;main(m){for(scanf("%d",&n);n--;printf("%d ",i))for(m=f;f<=m;)for(j=++i,f=0;j;)i%j--||f++;} ``` Try it [here](http://ideone.com/EyeFyl). ## Ungolfed ``` f,i,n,j; main(m) { for(scanf("%d",&n); /* Get input */ n--; /* Loop while still HCN's to calculate... */ printf("%d ",i)) /* Print out the last calculated HCN */ for(m=f;f<=m;) /* Loop until an HCN is found... */ for(j=++i,f=0;j;) /* Count the number of factors */ i%j--||f++; } ``` [Answer] # Python 3, 97 bytes ``` i=p=q=0;n=int(input()) while q<n: c=j=0;i+=1 while j<i:j+=1;c+=i%j==0 if c>p:p=c;q+=1 print(i) ``` A full program that takes input from STDIN and prints the output to STDOUT. This returns the `n`th 1-indexed highly composite number. **How it works** This is a straightforward implementation. The input `n` is the highly composite number index. The program iterates over the integers `i`. For each integer `j` less than `i`, `i mod j` is taken; if this is `0`, `j` must be a factor of `i` and the counter `c` is incremented, giving the number of divisors of `i` after looping. `p` is the previous highest number of divisors, so if `c > p`, a new highly composite number has been found and the counter `q` is incremented. Once `q = n`, `i` must be the `n`th highly composite number, and this is printed. [Try it on Ideone](https://ideone.com/tax8lp) (This takes ~15 seconds for `n = 20`, which exceeds the time limit for Ideone. Hence, the example given is for `n = 18`.) [Answer] # Python 2, 207 bytes ``` n,i,r,o=input(),1,[],[] while len(o)<n: r+=[(lambda n:len(set(reduce(list.__add__,([i,n//i]for i in range(1,int(n**0.5)+1)if n%i==0)))))(i)];h=max(r) if r.index(h)>i-2 and r.count(h)<2:o+=[i] i+=1 print o ``` Uses the same method as Dennis' Jelly answer. Calculates the first 20 terms in `<2` seconds. ]
[Question] [ ### Groups In abstract algebra, a *[group](https://en.wikipedia.org/wiki/Group_(mathematics))* is a tuple \$(G,\ast)\$, where \$G\$ is a set and \$\ast\$ is a function \$G\times G\rightarrow G\$ such that the following holds: * For all \$x, y, z\$ in \$G\$, \$(x\ast y)\ast z=x\ast(y\ast z)\$. * There exists an element \$e\$ in \$G\$ such that for all \$x\$ in \$G\$, \$x\ast e=x\$. * For each \$x\$ in \$G\$, there exists an element \$y\$ in \$G\$ such that \$x\ast y=e\$. The *order* of a group \$(G,\ast)\$ is defined as the number of elements of \$G\$. For each strictly positive integer \$n\$, there exists at least one group of order \$n\$. For example, \$(C\_n,+\_n)\$ is such a group, where \$C\_n=\{0,...,n-1\}\$ and \$x+\_ny=(x+y)\mod n\$. ### Isomorphic groups Let \$G:=\{1,2\}\$ and define \$\ast\$ by \$x\ast y=(x\times y)\mod3\$. Then \$1\ast1=1=2\ast2\$ and \$1\ast2=2=2\ast1\$. Likewise, \$0+\_20=0=1+\_21\$ and \$0+\_21=1=1+\_20\$. Although the elements and operations of the groups \$(G,\ast)\$ and \$(C\_2,+\_2)\$ have different names, the groups share the same structure. Two groups \$(G\_1,\ast\_1)\$ and \$(G\_2,\ast\_2)\$ are said to be *[isomorphic](https://en.wikipedia.org/wiki/Group_isomorphism)* if there exists a bijection \$\phi:G\_1\rightarrow G\_2\$ such that \$\phi(x\ast\_1y)=\phi(x)\ast\_2\phi(y)\$ for all \$x,y\$ in \$G\_1\$. Not all groups of the same order are isomorphic. For example, the [Klein group](https://en.wikipedia.org/wiki/Klein_four-group) is a group of order 4 that is not isomorphic to \$(C\_4,+\_4)\$. ### Task Write a program or function that accepts a non-negative integer **n** as input and prints or returns the number of non-isomorphic groups of order **n**. ### Test cases ``` Input Output 0 0 1 1 2 1 3 1 4 2 5 1 6 2 7 1 8 5 9 2 10 2 11 1 12 5 13 1 14 2 15 1 16 14 17 1 18 5 19 1 20 5 ``` (taken from [OEIS A000001](https://oeis.org/A000001)) ### Additional rules * There are no limits on execution time or memory usage. * Built-ins that trivialize this task, such as Mathematica's [`FiniteGroupCount`](https://reference.wolfram.com/language/ref/FiniteGroupCount.html), are not allowed. * Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. [Answer] # CJam, ~~189~~ 187 bytes This one's gonna be tough to explain... Time complexity is guaranteed to be `O(scary)`. ``` qi:N_3>{,aN*]N({{:L;N,X)-e!{X)_@+L@@t}%{X2+<z{_fe=:(:+}%:+!},}%:+}fX{:G;N3m*{_~{G@==}:F~F\1m>~F\F=}%:*},:L,({LX=LX)>1$f{\_@a\a+Ne!\f{\:M;~{M\f=z}2*\Mff==}:|{;}|}\a+}fX]:~$e`{0=1=},,}{!!}? ``` If you're brave enough, [try it online](http://cjam.aditsu.net/#code=qi%3AN_3%3E%7B%2CaN*%5DN(%7B%7B%3AL%3BN%2CX)-e!%7BX)_%40%2BL%40%40t%7D%25%7BX2%2B%3Cz%7B_fe%3D%3A(%3A%2B%7D%25%3A%2B!%7D%2C%7D%25%3A%2B%7DfX%7B%3AG%3BN3m*%7B_~%7BG%40%3D%3D%7D%3AF~F%5C1m%3E~F%5CF%3D%7D%25%3A*%7D%2C%3AL%2C(%7BLX%3DLX)%3E1%24f%7B%5C_%40a%5Ca%2BNe!%5Cf%7B%5C%3AM%3B~%7BM%5Cf%3Dz%7D2*%5CMff%3D%3D%7D%3A%7C%7B%3B%7D%7C%7D%5Ca%2B%7DfX%5D%3A~%24e%60%7B0%3D1%3D%7D%2C%2C%7D%7B!!%7D%3F&input=4). On my crappy laptop I can get up to 6 with the Java interpreter or 5 in the online interpreter. # Explanation I don't have a big math background (just finished high school, starting CS at uni next week). So bear with me if I make mistakes, state the obvious, or do things in horribly inefficent ways. My approach is a brute force, though I tried to make it a little more clever. The main steps are: 1. Generate all the possible operands **∗** for a group of order **n** (i.e., enumerate all groups of order **n**); 2. Generate all the possible bijections **φ** between two groups of order **n**; 3. Using the results from steps 1 and 2, determine all isomorphisms between two groups of order **n**; 4. Using the result from step 3, count the number of groups up to isomorphism. Before looking at the how each step is done, let's get some trivial code out of the way: ``` qi:N_ e# Get input as integer, store in N, make a copy 3>{...} ? e# If N > 3, do... (see below) {!!} e# Else, push !!N (0 if N=0, 1 otherwise) ``` The following algorithm doesn't work correctly with **n < 4**, the cases from 0 to 3 are handled with a double negation. From now on, the elements of a group will be written as **{1, a, b, c, ...}**, where **1** is the identity element. In the CJam implementation, the corresponding elements are **{0, 1, 2, 3, ...}**, where **0** is the identity element. Let's start from step 1. Writing all possible operators for a group of order **n** is equivalent to generating all the valid **n×n** [Cayley tables](https://en.wikipedia.org/wiki/Cayley_table). The first row and column are trivial: they are both **{1, a, b, c, ...}** (left-to-right, up-to-down). ``` e# N is on the stack (duplicated before the if) ,a e# Generate first row [0 1 2 3 ...] and wrap it in a list N* e# Repeat row N times (placeholders for next rows) ] e# Wrap everything in a list e# First column will be taken care of later ``` Knowing that a Cayley table is also a reduced [Latin square](https://en.wikipedia.org/wiki/Latin_square) (due to the cancellation property) allows to generate the possible tables row-by-row. Starting from the second row (index 1), we generate all the unique *permutations* for that row, keeping the first column fixed to the value of the index. ``` N({ }fX e# For X in [0 ... N-2]: { }% e# For each table in the list: :L; e# Assign the table to L and pop it off the stack N, e# Push [0 ... N-1] X) e# Push X+1 - e# Remove X+1 from [0 ... N-1] e! e# Generate all the unique permutations of this list { }% e# For each permutation: X)_ e# Push two copies of X+1 @+ e# Prepend X+1 to the permutation L@@t e# Store the permutation at index X+1 in L {...}, e# Filter permutations (see below) :+ e# Concatenate the generated tables to the table list ``` Not all those permutations are valid, of course: each row and column must contain all the elements exactly one time. A filter block is used for this purpose (a truthy value keeps the permutation, a falsy one removes it): ``` X2+ e# Push X+2 < e# Slice the permutations to the first X+2 rows z e# Transpose rows and columns { }% e# For each column: _fe= e# Count occurences of each element :( e# Subtract 1 from counts :+ e# Sum counts together :+ e# Sum counts from all columns together ! e# Negate count sum: e# if the sum is 0 (no duplicates) the permutation is kept e# if the sum is not zero the permutation is filtered away ``` Note that I am filtering inside the generation loop: this makes the code a bit longer (compared to distinct generation and filtering), but greatly improves performance. The number of permutations of a set of size **n** is **n!**, so the shorter solution would require a lot of memory and time. A list of valid Cayley tables is a great step towards enumerating the operators, but being a 2D structure, it can't check for associativity, which is a 3D property. So next step is filtering out non-associative functions. ``` { }, e# For each table, keep table if result is true: :G; e# Store table in G, pop it off the stack N3m* e# Generate triples [0 ... N-1]^3 { }% e# For each triple [a b c]: _~ e# Make a copy, unwrap top one { }:F e# Define function F(x,y): G@== e# x∗y (using table G) ~F e# Push a∗(b∗c) \1m> e# Rotate triple right by 1 ~ e# Unwrap rotated triple F\F e# Push (a∗b)∗c = e# Push 1 if a∗(b∗c) == (a∗b)∗c (associative), 0 otherwise :* e# Multiply all the results together e# 1 (true) only if F was associative for every [a b c] ``` Phew! Lots of work, but now we have enumerated all groups of order **n** (or better, the operations on it - but the set is fixed, so it's the same thing). Next step: find isomorphisms. An isomorphism is a bijection between two of those groups such that **φ(x ∗ y) = φ(x) ∗ φ(y)**. Generating those bijections in CJam is trivial: `Ne!` will do it. How can we check them? My solution starts from two copies of the Cayley table for **x ∗ y**. On one copy, **φ** is applied to all elements, without touching the order of rows or columns. This generates the table for **φ(x ∗ y)**. On the other one the elements are left as they are, but rows and columns are mapped through **φ**. That is, the row/column **x** becomes the row/column **φ(x)**. This generates the table for **φ(x) ∗ φ(y)**. Now that we have the two tables, we just have to compare them: if they are the same, we have found an isomorphism. Of course, we also need to generate the pairs of groups to test isomorphism on. We need all the *2-combinations* of the groups. Looks like CJam has no operator for combinations. We can generate them by taking each group and combining it only with the elements following it in the list. Fun fact: the number of 2-combinations is **n × (n - 1) / 2**, which is also the sum of the first **n - 1** natural numbers. Such numbers are called triangular numbers: try the algorithm on paper, one row per fixed element, and you'll see why. ``` :L e# List of groups is on stack, store in L ,( e# Push len(L)-1 { }fX e# For X in [0 ... len(L)-2]: LX= e# Push the group L[X] LX)> e# Push a slice of L excluding the first X+1 elements 1$ e# Push a copy of L[X] f{...} e# Pass each [L[X] Y] combination to ... (see below) e# The block will give back a list of Y for isomorphic groups \a+ e# Append L[X] to the isomorphic groups ] e# Wrap everything in a list ``` The code above fixes the first element of the pair, **L[X]**, and combines it with other groups (let's call each one of those **Y**). It passes the pair to a isomorphism test block that I'll show in a moment. The block gives back a list of values of **Y** for which **L[X]** is isomorphic to **Y**. Then **L[X]** is appended to this list. Before understanding why the lists are set up in such a way, let's look at the isomorphism test: ``` \_@ e# Push a copy of Y a\a+ e# L[X] Y -> [L[X] Y] Ne! e# Generate all bijective mappings \f{ } e# For each bijection ([L[X] Y] extra parameter): \:M; e# Store the mapping in M, pop it off the stack ~ e# [L[X] Y] -> L[X] Y { }2* e# Repeat two times (on Y): M\f= e# Map rows (or transposed columns) z e# Transpose rows and columns e# This generates φ(x) ∗ φ(y) \Mff= e# Map elements of L[X], generates φ(x ∗ y) = e# Push 1 if the tables are equal, 0 otherwise :| e# Push 1 if at least a mapping was isomorphic, 0 otherwise {;}| e# If no mapping was isomorphic, pop the copy of Y off the stack ``` Great, now we have a list of sets like **[{L[0], Y1, Y2, ...}, {L[1], Y1, ...}, ...]**. The idea here is that, by transitive property, if any two sets have at least one element in common then all the groups in the two sets are isomorphic. They can be aggregated into a single set. As **L[X]** will never appear in the combinations generated by **L[X+...]**, after aggregating each set of isomorphisms will have one unique element. So, to get the number of isomorphisms, it's sufficient to count how many groups appear exactly once in all sets of isomorphic groups. To do this, I unwrap the sets so they look like **[L[0], Y1, Y2, ..., L[1], Y1, ...]**, sort the list to create clusters of the same group and finally RLE-encode it. ``` :~ e# Unwrap sets of isomorphic groups $ e# Sort list e` e# RLE-encode list { }, e# Filter RLE elements: 0= e# Get number of occurrences 1= e# Keep element if occurrences == 1 , e# Push length of filtered list e# This is the number of groups up to isomorphism ``` That's all, folks. [Answer] # CJam, 73 bytes ``` 0ri:Re!Rm*{:Tz0=R,=[R,Te_]m!{~ff{T==}e_}/=&},{:T,e!{:PPff{T==P#}}%$}%Q|,+ ``` The time complexity of the above code is worse than **O(n!n)**. Input **n=4** is already to much for the [online interpreter](http://cjam.aditsu.net/#code=0ri%3ARe!Rm*%7B%3ATz0%3DR%2C%3D%5BR%2CTe_%5Dm!%7B~ff%7BT%3D%3D%7De_%7D%2F%3D%26%7D%2C%7B%3AT%2Ce!%7B%3APPff%7BT%3D%3DP%23%7D%7D%25%24%7D%25Q%7C%2C%2B&input=3). Using the [Java interpreter](https://sourceforge.net/p/cjam/wiki/Home/), input **n=5** could be possible, if you have enough RAM and patience. ### Finding groups Given a group **(G, ∗)** of order **n**, we can pick an arbitrary bijection **φ : G -> Cn** such that **φ(e) = 0**. **φ** will become an isomorphism of **(G, ∗)** and **(Cn, ∗')** if we define **∗'** by **x ∗' y = φ(φ-1(x) ∗ φ-1(y))**. This means that it suffices to study all group operators in **Cn** such that **0** is the neutral element. We will represent a group operator **∗** in **Cn** by a rectangular array **T** of dimensions **n × n** such that **T[x][y] = x ∗ y**. To generate such an array, we can start by picking a permutation of **Cn** for each of its **n** rows. This way, **0** will be present in all *rows* (but not necessarily all *columns*), meaning that the third condition (existence of an inverse) will be fulfilled, whatever **e** may be. We can fix **e = 0** by requiring that the first *column* of **T** is equal to **Cn**. In particular, the second condition (existence of a neutral element) will hold. To verify that **T** corresponds to a group operator, all that's left to do is verifying that the first condition (associativity) holds. This can be done exhaustively by checking that **T[T[x][y]][z] == T[x][T[y][z]]** for all **x, y, z** in **Cn**. ### Counting non-isomorphic groups The above method for finding groups will yield some isomorphic groups. Rather than identifying which ones are isomorphic, we generate the family of all isomorphic groups for every one of them. This can done achieved by iterating over all bijections **φ : Cn -> Cn**, and determining the associated array **Tφ**, defined by **Tφ[x][y] = φ-1(T[φ(x)][φ(y)])**. All that's left to do is counting the number of distinct families. ### What the code does ``` 0 e# Push 0. For input 0, the remaining code will crash, leaving e# this 0 on the stack. ri:R e# Read an integer from STDIN and save it in R. e! e# Push all permutations of [0 ... R-1]. Rm* e# Push all arrays of 6 permutations of [0 ... R-1]. { e# Filter; for each array: :T e# Save it in T. z0=R,= e# Check if the first column equals [0 ... R-1]. [R,Te_] e# Push [0 ... R-1] and a flattened T. m!{ e# For both pairs (any order): ~ e# Unwrap the pair. ff{ e# For each X in the first: For each Y in the second: T== e# Push T[X][Y]. } e# }/ e# = e# Check for equality, i.e., associativity. & e# Bitwise AND with the previous Boolean }, e# Keep T iff the result was truthy. { e# For each kept array: :T e# Save it in T ,e! e# Push all permutations of [0 ... R-1]. { e# For each permutation: :PP e# Save it in P. Push a copy. ff{ e# For each X in P: For each Y in P: T== e# Push T[X][Y]. P# e# Find its index in P. } e# }% e# $ e# Sort the results. }% e# Q|, e# Deduplicate and count. + e# Add the result to the 0 on the stack. ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~515~~ 507 bytes * Saved eight bytes thanks to [Dennis](https://codegolf.stackexchange.com/users/12012/dennis). ``` def F(n): def f(k,*s):n==len(set(s))and S.add(s);{k and f(~-k,j,*s)for j in I} def c(k,*G):k and{s in G or c(~-k,s,*G)for s in S}or(I in G)&all((o(x,y)in G)&any(I==o(z,x)for z in G)for x in G for y in G)and A.add(G) S=set();A=S-S;I=tuple(range(n));o=lambda x,y:tuple(y[x[j]]for j in I);i=lambda G,H:any(all(o(H[B[i]],H[B[j]])==H[B[[k for k in I if G[k]==o(G[i],G[j])][0]]]for i in I for j in I)for B in S);f(n);c(n);K=list(A);[G in K and{G!=H and i(G,H)and K.remove(H)for H in K}for G in A];return len(K) ``` [Try it online!](https://tio.run/##TVGxboMwEN3zFe5S3VUkqip1wfJAhhjEyIg80ACtA7ERkAoSpb9OfaZVu8Cz33t3787dPH5Y87IsZVWzAxgMN4xgDU3wNGBohGgrA0M1woBYmJJlu6Is3YHfGkbnGr62TXAidW17dmLasOS@VjlSFYmhV94GoiRzoqP3DMSRxxPZ3faQeAk@Fm0LYGEKZvy5MDMkQli4BpP3XFclwWmtS3BebylX5HNK3LBMUHzkkci2GU/EeOnaCvrCvFduYORWtMX5rSyYaxeu5JxP@Umpv4GQ61@VDOKQ4lBGC3G@z7VSAf2dA4UglDc@TuO9TNdM5o2i@NKJA@mUqPJntXbQq@pfM4J7vxTktcvIj/RJRauHESLkuSQy9VuVDyL2D6HBJfOjp7u@OtvPCmJfKfbiO0HvixTvq/HSG0ZPm@LS9dqM7Fx0cAjYupdXxOUb "Python 2 – Try It Online") --- Using the equivalence between the number of non-isomorphic subgroups of order \$n\$ of \$\ \Sigma\_n\$ and the number of isomorphic equivalence classes of finite groups of order \$n\$. Link to [verbose version](https://tio.run/##dVSxbuMwDJ3tr2DRRULdDgfcksBDOtQJMua2wIMT07YSW/JJcpGg6P16jpTdS4r2gCASJfKRfI9yf/aN0T8ulxIreBFazuLoHoq2hR5tN/jCK6NdAm7Y1dYMvQNTgbElWtBxtEkdeiHni3TzuIkjDlUlaq/8@TY@jlapH/oWhS10jZRFjs41arSFxy8J44jrqcQxcamQcqbTtEUtOJuTstAlbJ6KsiRj/nYEtivx55G8H8QhkbIyFg6gNKzex0SVIhdO8n0fnGxPybKQLAC@OY7PyIduGDp7EG6CDlebd9rVIgvVLEI12UdbnAFMz71RNyBuWoO96XrjFO/J3aRt0e3KAuqkmY0cNdt6e8jzaw8TqkfnQVVUk3JQjEnG0rkK0u2GfTLIcwXa@NDGzKIfrIaXonVIl/Rj/NN4SVYwz1eTsPatOQwWg0VgRpySs/wfYIC88UvT1WxnsTjG09U94Ek5j3qPTL3Sr2gdArbYUcmOXZCgvil0OvllB5xGzJnO2L5RrgukJCwk0ZKGdUnrJKkSWbL8YEZ7tD1hwQYKB75BoGniUngsduqA@2nyAhXPQeJ/zKhk1GIreCchnPHBONA8m9nN2H06zT8IDUPIiY/kU@IpoPim8JBtj3maGpFtVZ6QdchliGGH4xfAEY@55jhIqe/byCvv0ZS4Ib4@MXbVarl9psg84ZWGTsJdCrw/5vkV51aYUYYbXSalPj3nTQKLBHaDaktYg9HtmWpoS6Xrq3h74p0HDn8PRftvDliQRRxV9I2Y7/lvnbY0NmIh59uMmViHx5ndpcvw7EeJebd@stiZVxTLoMMyOL/zNsQt8rHGqWqisvZNHF1NsZaX3tKYQFf04iWZOP8p5eUv). ]
[Question] [ Write a function that accepts a rectangular grid of ids in any reasonable format, for example a multi-line string: ``` IIILOO ILLLOO ``` and a string or list of box drawing charcters such as: ``` ' ═║╔╗╚╝╠╣╦╩╬' ``` or ``` [0x20, 0x2550, 0x2551, 0x2554, 0x2557, 0x255a, 0x255d, 0x2560, 0x2563, 0x2566, 0x2569, 0x256c'] ``` (see below for more details) and returns a pretty printed version, as such: ``` ╔═══════════╦═══╦═══════╗ ║ ║ ║ ║ ║ ╔═══════╝ ║ ║ ║ ║ ║ ║ ╚═══╩═══════════╩═══════╝ ``` i.e. a rectangle made out of the box drawing characters, where each border indicates the border of each polyomino. ``` ╔═══════════╦═══╦═══════╗ ║ I I I ║ L ║ O O ║ ║ ╔═══════╝ ║ ║ ║ I ║ L L L ║ O O ║ ╚═══╩═══════════╩═══════╝ ``` # Rules Shortest submission in bytes per language wins. Standard rules apply. Note that to leave room for annotations and as the characters used are half width each unit square is 2x4 (3x5 but boundary fields are shared with neighbouring squares) characters in the output. You may assume that input is clean rectangular and ids are unique to orthogonally connected regions. To avoid any unicode related issues I have decided to provide the box drawing characters as an input. This may be any flat container holding the characters in any order as long as it contains 1. each character exactly once and 2. only these characters (no fillers) 3. access is sequential or per index only (no sophisticated lookup tables) # More examples: In: ``` XXXSS RXSSL ROOOL RROLL ' ═║╔╗╚╝╠╣╦╩╬' ``` Out: ``` ╔═══════════╦═══════╗ ║ ║ ║ ╠═══╗ ╔═══╝ ╔═══╣ ║ ║ ║ ║ ║ ║ ╠═══╩═══════╣ ║ ║ ║ ║ ║ ║ ╚═══╗ ╔═══╝ ║ ║ ║ ║ ║ ╚═══════╩═══╩═══════╝ ``` In: ``` 1220003 2240503 2444666 ' ═║╔╗╚╝╠╣╦╩╬' ``` Out: ``` ╔═══╦═══════╦═══════════╦═══╗ ║ ║ ║ ║ ║ ╠═══╝ ╔═══╣ ╔═══╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ╔═══╝ ╚═══╬═══╩═══╩═══╣ ║ ║ ║ ║ ╚═══╩═══════════╩═══════════╝ ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~147~~ ~~129~~ ~~80~~ ~~78~~ ~~76~~ ~~75~~ ~~71~~ 65 bytes ``` ≔⁺SψθWSF²⊞υ⁺⭆ι×⁴λψ⊞υ⭆⌊υψEυ⭆EιE⁴§§υ⁻κ÷ν²⁻μ∨⁼ν¹⁼ν²§θ﹪×⁷↨²Eλ⁼ν§λ⊕ξ⁹⁵ ``` [Try it online!](https://tio.run/##VY/BSgMxEIbvfYo5TiDCNm4r0lNFDz0UC/oCSzd2g9lsd5PU@hYKBkEQBEEQfKq8yDbputYewiR8/3wzWRZZs6wy2bZTrcVK4UJajTO1tubGNEKtkFB4DKcmk8FDISSHY0rgrmoAGYGF1QVaCntDh@fZGgWFW1FyjSkFSfa2oOrDh9xcKFHaEu1fJBCDER3nOmcswTg1M5XzLfY1RIMoLHBPYabMpdiInKOiwEic3bGSwnWDV7XNpI5sGMjhFZMx2yvr0FblVlbY/eOMwkWmObJuCfm/t@@Rcfqy4SVXhue4/VWej/YXMmlb7368@/Luw7sX7769e/LuzbtP7169ewbv3gdDxpIkOR0wliajWNM0HY/H7clG7gA "Charcoal – Try It Online") Link is to verbose version of code. Expects the box-drawing characters first in the order `╬╦╠╔╩═╚╣╗║ ╝` followed by the newline-terminated grid of strings. Edit: Saved 6 bytes by stealing @Arnauld's cool mapping. Explanation: ``` ≔⁺Sψθ ``` Append a null byte to the box drawing character string as this gives us a free modulo 13 due to Charcoal's cyclic indexing. ``` WSF²⊞υ⁺⭆ι×⁴λψ⊞υ⭆⌊υψ ``` Read in the grid, duplicating it vertically and quadruplicating it horizontally, plus suffix a row and column of null bytes of padding. ``` Eυ⭆EιE⁴§§υ⁻κ÷ν²⁻μ∨⁼ν¹⁼ν²§θ﹪×⁷↨²Eλ⁼ν§λ⊕ξ⁹⁵ ``` Map over the expanded grid, collecting a `2×2` square for each character, then comparing the characters in that square pairwise, treating the comparison results as base 2, and hashing into the box-drawing characters. Previous 129 byte canvas-based version: ``` ≔⁺SψθWS⊞υιυUE¹¦¹F⊕⊗LυF⊕⊗Lη«J⊖κ⊖ι≔KMζ¿﹪ⅉ²¿﹪ⅈ²§θ﹪×⁷↨²E⁴⁼§ζ⊗λ§ζ⊗⊕λ⁹⁵F¬⁼§ζ¹§ζ⁵§θ⁵¿﹪ⅈ²F¬⁼§ζ³§ζ⁷§θ⁹»UMKA⎇№θιιψUE¹F⊕LυF⊗Lη«J⊖⊗κ⊖⊗ι§KV⊕⊗κ ``` [Try it online!](https://tio.run/##hVLdSsMwGL22T5HLFCpstdsYXs3phaJj4BC9rOu3rSxNtrbRqewdFAyCIAiCIPhUeZH6pdu006qFkOT7OTnn6@mP/LgvfJZlrSQJh5x2mUzoPp/I9DiNQz6ktkOucE3tbetyFDIg61mbdGUyotIhIVZ0MZhSiae9WQo8oFWHVPE2ELHp68cQAU8hoLtCnjPcD4EPU2y38SP/VY3yqhtr40BGk56gu/BVOkaOxXto47MbK1EA4yMhYjBqrk0iHBB6JALJBD0zQReBC7HTVWwhqJXu8wBmdOqQZUEvjCChDYfs@AlQF@P@hHoO2ZtKnyWfDddIaqmB2QhZEi/qZQ5p1pAdsAQW0@iIlP7ErK5D1fK5/KBay0eQY5VJ@wN/ax2/UY7fNPhzC5W3RRT5@LfNnFuMmRd6EHM/vqJtIbFrauyBy3ipYI4yZxQcsaBYYoJfPLCqHNvfzLBKoCnMSNaVGNIngndAogZuuJdZcGznvfMs0@pdqzetXrR60upVq1utHrR61upRqzui1b1Vdd1KpbJlua5XqZnd87x6vW5lmxfsAw "Charcoal – Try It Online") Link is to verbose version of code. Expects the box-drawing characters first in the order `╬╩╣╝╦═╗╠╚║ ╔` followed by the newline-terminated grid of strings. Explanation: ``` ≔⁺Sψθ ``` Append a null byte to the box drawing character string as this gives us a free modulo 13 due to Charcoal's cyclic indexing. ``` WS⊞υιυ ``` Read and print the grid. ``` UE¹¦¹ ``` Double-space the grid horizontally and vertically. ``` F⊕⊗LυF⊕⊗Lη«J⊖κ⊖ι ``` Loop through each cell of the extended grid, including the border. ``` ≔KMζ ``` Get the contents of the adjacent cells. ``` ¿﹪ⅉ²¿﹪ⅈ²§θ﹪×⁷↨²E⁴⁼§ζ⊗λ§ζ⊗⊕λ⁹⁵ ``` If this is a cell e.g. between 4 ids then calculate which box-drawing character to draw. ``` F¬⁼§ζ¹§ζ⁵§θ⁵ ``` If this is a row divider and the two ids differ then print a `═`. ``` ¿﹪ⅈ²F¬⁼§ζ³§ζ⁷§θ⁹ ``` If this is a column divider and the ids differ then print a `║`. ``` »UMKA⎇№θιιψ ``` Delete all non-box-drawing characters. ``` UE¹ ``` Double-space the grid horizontally. ``` F⊕LυF⊗Lη«J⊖⊗κ⊖⊗ι§KV⊕⊗κ ``` Duplicate the row dividers. [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~282~~ ~~243~~ 219 bytes Thanks @Arnauld for the idea that the values can be directly mapped to the output characters! I've made a code that finds such an expression by brute force. The `*7%95%13` is single shortest expression. -24 bytes thanks @Arnauld for "width 4w+1 and height 2h+1" before sliding over the input string. ``` param($t,$s)$n=($s=$s-replace'.',('$0'*4)|%{$_;$_})|% Le*|Sort -b 1 $s=$s+,''|% *ht($n+1) $s|%{-join(0..$n|%{$x=$_,--$_ $b,$a,$d,$c=$s[--$y,++$y]|%{$_[$x]} $t[(!($a-$b)+2*!($a-$c)+4*!($b-$d)+8*!($c-$d))*7%95%13]});$y++} ``` [Try it online!](https://tio.run/##ZVJdi9pAFH2fXzEN105iJpJJov1YBMuyD0IgoC@CiB01Yko2SZORKpr/0EJDoVAoFAqF/qr8ETszu0jbzcPcc@eec@4dbor8Q1xWuzhNL7Adni4FL/m9CYJCZUE2NKEaQuWUcZHydUx6hJoEXNINrHPnBMsbWNYS4TDunqd5KbCzwgxpjU0JkZXuTpiQ2cySt1LivMuTzHR7PciUwWEIS@o4sESwosApbCispXgu747UtuG40H3mcFjUCMTcfGYCd2Bl2V73Aa4tO1Bw5cDGsl8quFbQ6r7ovOp3mL@orRs42nZ9qREamQjJJ9wd@H2RxpgROiJoPB6HUYTGYagCGVn/cDzNmc1m0ymayCNEkyiK5DmJwvAJ29ds5nmu6/rI8wK3r2IQBIPB4Mrm2RFXO17EFGe5wPsseb@PcbKpCMUjA2Et12rP87Q6QMaj9rUlWxiIMaZa@L70ZViSfOb6ku4zds2x68u@/T5j11zzlam2s/AZd04Iyw82cbUuk0IkeUYxyFnwEMvF6NpjpoJTFWkisPE2Mx5q25SL2zwTPMniUrJI2/xum@9t86NtPrXNr7b52jbf2uZn23xumy@4bT6qH0PktztevilLfpQrNmBpyPVowzKu9qmQTs9h@7@9GgE9mfdvHaovfwA "PowerShell – Try It Online") Less golfed: ``` param($t,$s) $s=$s-replace'.',('$0'*4)|%{$_;$_} # magnify to 4*width and 2*heght $n=$s|% Length|sort -b 1 # find max length $s=$s+,''|% PadRight($n+1) # add +1 to width and height $s|%{ # (in addition, we got a rectangle) -join(0..$n|%{ $x=$_,--$_ $b,$a,$d,$c=$s[--$y,++$y]|%{$_[$x]} # I need to golf $i=!($a-$b)+2*!($a-$c)+4*!($b-$d)+8*!($c-$d) # this 2 lines cxxx|;:;:;:;:;:;:> $t[7*$i%95%13] }) $y++ } ``` ## Main idea Let a square of 4 characters slide over the input string "magnified 4 times in width and twice in height". ``` .. ..IILOO ILLLOO .. ..ILOO ILLLOO .. I..LOO ILLLOO .~.~.~.~.~. ..IILOO ..LLLOO ..IILOO ..LLLOO I..ILOO I..LLOO II..LOO IL..LOO .~.~.~.~.~. IIILOO ..LLLOO .. .~.~.~.~.~. IIILOO ILLLO.. .. ``` Let's name the points in the square as a,b,c,d. The expression `(a=b)+2*(a=c)+4*(b=d)+8*(c=d)` returns numbers in range 0..15, which correspond to the border chars: ``` 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 ---------------------------------------------------------------- ab aa ab aa ab aa ab aa ab aa ab aa ab aa aa aa cd cd ad ad cb ca ab aa cc cc aa aa bb aa aa aa 0 1 2 3 4 5 6 15 8 9 10 15 12 15 15 15 - the expression results ╬ ╦ ╠ ╔ ╣ ╗ ║ ╩ ═ ╚ ╝ - related border chars. the space char for 15 0 7 1 8 2 9 3 4 11 5 6 10 - *7%95%13 - index in the "flat container" 012345678901 ╬╠╣║╩╚╝╦╔╗ ═ - the flat container ``` The script draws the border char for each position of the sliding square. Plus draws middle row between input lines. The script expectes the flat container with border chars in order `╬╠╣║╩╚╝╦╔╗ ═`. [Answer] # JavaScript (ES6), ~~164 154~~ 143 bytes Expects `(a)('╬╩╠╚╣╝║╦═╔ ╗')`, where `a` is a list of strings. ``` a=>c=>[...a,...a,a[0]].map((r,y)=>[...r+r+r+r+0].map((v,x)=>c[g=d=>v==(v=(a[y-d%2>>1]||0)[x-~x-d>>3]),(g``,8*g(1)|g(3)|4*g(2)|2*g``)*7%95%13])) ``` [Try it online!](https://tio.run/##RZDdSsNAEIXv9ymWQslOmyxpmlZFNncKhUCguSmkhS75M5ImNYmlxegzKLgIgiAIguBT7YvUNC3IwDkHvjMMzC3f8NIvknWlZXkQ7iO258zymeVRSrnaCvf0xYKu@JqQQt3BkRX94@gnslG3DfG9mAXM2jBGNoxwb6cFXcOyBou61sHbak9bLbCs4QJUEi@X6nkvJgOoYzKE2myyAbXRawD0zroXo@6gKcK@CO/ukyIkSlQqQIuQB9dJGrq7zCc60Cp3qyLJYgK0XKdJRTrzbJ51gEZ5ccX9G1JiZuEHhHEaVphjhsv/YgcuT2DVgIhwIIoUv1L8SPEpxbsUX1J8SPEixbcUz1K8YinelHbLz7MyT0Oa5jFZtT9oL5X0Nk8yoigApzTPFMB93Dp6hP1kMrEdB01s@2BoNpu5Lpo2YqOp4ziNTh3bRmhgGLquD5FhmPro4KZpjsfjPw "JavaScript (Node.js) – Try It Online") ### How? Given a matrix \$M\$ of size \$w\times h\$, we build an expanded matrix \$M'\$ of width \$4w+1\$ and height \$2h+1\$ filled with the original values of \$M\$ magnified 4 times in width and twice in height. The extra column and extra row are filled with undefined values. For instance: ``` AB ==> AAAABBBB? CD AAAABBBB? CCCCDDDD? CCCCDDDD? ????????? ``` For each cell \$(x,y)\$ in \$M'\$, we extract \${M'}\_{x,y}\$ and 3 adjacent cells: $$\begin{pmatrix}v\_3={M'}\_{x-1,y-1}&v\_1={M'}\_{x,y-1}\\ v\_2={M'}\_{x-1,y}&v\_0={M'}\_{x,y}\end{pmatrix}$$ Using these results, we build a 4-bit value as follows: ``` 8 4 2 1 | | | | | | | +--> set if v3 = v1 | | +----> set if v2 = v0 | +------> set if v3 = v2 +--------> set if v1 = v0 ``` We may get all values from \$0\$ to \$15\$ except the ones with exactly 3 bits set: \$7\$, \$11\$, \$13\$ and \$14\$ (because if 3 equalities are satisfied, the 4th one must be satisfied as well). The 12 remaining values can be directly mapped to the output characters. We use the expression \$((n\times7)\bmod 95)\bmod 13\$ to force all them into \$[0\dots 11]\$ ([Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/2kDHUMdIx1jHRMdUx0zHQsdSxxAoZKRjaBqrl5Zf5JqYnKGRp2Brp5Ccn1ecn5Oql5OfDhTQVlBX0LUDEtoKQJ6WgrmCqoKlKZAwNNbU1Pz/HwA "JavaScript (Node.js) – Try It Online")). ]
[Question] [ You would simply take this image and make every color added one to every hexadecimal digit. For example, `#49de5f` would become `#5aef60` (with the `9` looping to an `a`, and the `f` looping to a `0`.) [![Color #49de5f](https://i.stack.imgur.com/CU4Ez.png)](https://i.stack.imgur.com/CU4Ez.png)[![Color #5aef60](https://i.stack.imgur.com/JKsUY.png)](https://i.stack.imgur.com/JKsUY.png) This would also mean that all white (`#ffffff`) would become black (`#000000`) because all `f` loops back to `0`, but all black will become a lighter shade of black (`#111111`). [![Color #000000](https://i.stack.imgur.com/IpNyi.png)](https://i.stack.imgur.com/IpNyi.png)[![Color #111111](https://i.stack.imgur.com/xng8i.png)](https://i.stack.imgur.com/xng8i.png) Scoring is based on the least number of bytes used, as this is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") question. Use the below image as the input image for your code, and put the output image of your code into your answer. [![Input image](https://i.stack.imgur.com/m7Qmg.png)](https://i.stack.imgur.com/m7Qmg.png) If you want to, you can also use this other rainbow image: [![Another optional input image](https://i.stack.imgur.com/bJ7US.jpg)](https://i.stack.imgur.com/bJ7US.jpg) [Answer] ## Mathematica, 78 bytes ``` Image@Apply[16#+#2&,Mod[IntegerDigits[#~ImageData~"Byte",16,2]+1,16]/255,{3}]& ``` Takes and returns an image object (to create an image object, just paste the image into Mathematica). Result for the test case: [![enter image description here](https://i.stack.imgur.com/cBLKf.png)](https://i.stack.imgur.com/cBLKf.png) [Taking input](http://meta.codegolf.stackexchange.com/a/9103/8478) and [returning output](http://meta.codegolf.stackexchange.com/a/9104/8478) as a 3D array of integer channel values, this reduces to **51 bytes**: ``` Apply[16#+#2&,Mod[IntegerDigits[#,16,2]+1,16],{3}]& ``` But those meta posts don't have an overwhelming amount of support yet, so I'm going with the 78-byte version for now. [Answer] ## Pyke, ~~17~~ 13 bytes ``` .Fh16j%ijcjs 8{ ``` [Try it here!](http://pyke.catbus.co.uk/?code=.Fh16%25i16%2B%2B8%7B&input=%5B%5B%5B0%2C31%2C15%5D%2C%5B0%2C0%2C0%5D%5D%2C%5B0%2C0%2C255%5D%2C%5B0xef%2C0xee%2C0xf0%5D%5D%0A) ``` .F - for i in deep_for(input): h16% - (i+1)%16 + - ^+V i16+ - (i+16) 8{ - unset_bit(8, ^) ``` Takes input as a 3d integer array of pixels and outputs in the same format [![RAINBOWZ (No unicorn :()](https://i.stack.imgur.com/O6xVq.png)](https://i.stack.imgur.com/O6xVq.png) [Answer] # Verilog, 220 bytes: > > * Programs may take input as an array of RGB pixel values with dimensions > * Programs may output via an array of RGB pixel values with dimensions > > > It's currently not clear as to how the dimensions are to be provided and if the array is to be streamed or provided all at once. I'm going to stream it 8 bits at a time using a clock signal (with a valid-data flag that goes low after the entire image has been processed) and input/output the dimensions as 32-bit integers: ``` module a(input[31:0]w,input[31:0]h,input[7:0]d,input c,output[31:0]W,output[31:0]H,output reg[7:0]D,output reg v=0);assign W=w;assign H=h;reg[65:0]p=1;always@(posedge c) begin v<=(p<3*w*h); p<=p+v; D<=d+17; end endmodule ``` [Answer] ## Python, 226 bytes Now, it's valid ! Use the Pillow library. ``` from PIL import Image m=Image.open(input()).convert("RGB") for y in range(m.size[1]): for x in range(m.size[0]): t=m.getpixel((x,y)) h=t[0]+(t[1]<<8)+(t[2]<<16)+1118481 m.putpixel((x,y),(h&255,h>>8&255,h>>16&255)) m.show() ``` Output:[![Output](https://i.stack.imgur.com/BzBck.png)](https://i.stack.imgur.com/BzBck.png) Thanks to @TuukkaX for saving 9 bytes ! Thanks to @mbomb007 for saving 18 bytes ! [Answer] # [Dyalog APL](http://goo.gl/9KrKoM), ~~21~~ 15 [bytes](http://meta.codegolf.stackexchange.com/a/9411/43319) > > Programs may output as a matrix of RGB pixel values > > > I assume output may be in the same format. ### New solution takes matrix of values [[*r*,*g*,*b*,*r*,*g*,*b*],[*r*,*g*,*b*,… ``` 16⊥16|1+16 16⊤⎕ ``` **Explanation** `⎕` get numeric input `16 16⊤` convert to 2-digit base 16 `1+` add 1, i.e. 0 → 1, 1 → 2, 15 → 16 `16|` modulus 16, i.e. 16 → 0 `16⊥` convert from base 16 **Example** ``` ⊢m←2 6⍴90 239 96 255 255 255 0 0 0 239 239 239 90 239 96 255 255 255 0 0 0 239 239 239 16⊥16|1+⎕⊤⍨2/16 ⎕: m 107 240 113 0 0 0 17 17 17 240 240 240 ``` --- ### Old 21 byte solution takes matrix of [["RRGGBB","RRGGBB"],["RRGGBB",… ``` {n[16|1+⍵⍳⍨n←⎕D,⎕A]}¨ ``` Needs `⎕IO←0`, which is default on many systems. **Explanation** `{`…`}¨` for each RGB 6-char string, represent it as `⍵` and do: `n←⎕D,⎕A` assign "0…9A…Z" to *n* `⍵⍳⍨` find indices of the individual characters in *n* `1+` add one to the index, i.e. 0 → 1, 1 → 2, 15 → 16 `16|` modulus 16, i.e. 16 → 0 `n[`…`]` use that to index into *n* **Example** ``` f←{n[16|1+⍵⍳⍨n←⎕D,⎕A]}¨ ⊢p←2 2⍴'5AEF60' 'FFFFFF' '000000' 'EFEFEF' ┌──────┬──────┐ │5AEF60│FFFFFF│ ├──────┼──────┤ │000000│EFEFEF│ └──────┴──────┘ f p ┌──────┬──────┐ │6BF071│000000│ ├──────┼──────┤ │111111│F0F0F0│ └──────┴──────┘ ``` [Answer] # C - ~~114~~ ~~113~~ ~~70~~ ~~66~~ ~~61~~ ~~72~~ 67 bytes Here's the code (with support for **Martin Ender**'s test case (without it's 60b)): ``` main(c,b){for(;~(b=getchar());putchar(c++<54?b:b+16&240|b+1&15));} ``` And here is less obfuscated version: ``` main( c, b ) //Defaults to int { //Get characters until EOF occurs //Copy first 54 bytes of header, later add 1 to each hexadecimal digit for ( ; ~( b = getchar( ) ); putchar( c++ < 54 ? b: b + 16 & 240 | b + 1 & 15 ) ); } ``` Compile and run with `gcc -o color colorgolf.c && cat a.bmp | ./color > b.bmp` This code supports works with **bitmaps**. To convert `png` files to `bmp`, I used following command: `convert -flatten -alpha off png.png a.bmp` Code assumes, that `bmp` header is 54 bytes long - in this case it works, but I'm not sure if I'm not discreetly breaking something. Also, this is the rainbow: [![It looks sad now... :(](https://i.stack.imgur.com/jH746.png)](https://i.stack.imgur.com/jH746.png) [Answer] # Java 142 bytes ``` public BufferedImage translateColor(BufferedImage image){ for(int i=-1;++i<image.getWidth();) for(int j=-1;++<image.getHeight();) image.setRGB(i,j,image.getRGB(i,j)+1118481); return image; } ``` Golfed: ``` BufferedImage t(BufferedImage i){for(int x=-1;++x<i.getWidth();)for(int y=-1;++y<i.getHeight();)i.setRGB(x,y,i.getRGB(x,y)+1118481);return i;} ``` [Answer] # R, 302 bytes Far from perfect, but here goes: ``` a<-as.raster(imager::load.image(file.choose()));l=letters;n=as.numeric;d=a;f=function(x){if(suppressWarnings(is.na(n(x)))){if(x=="F")"0" else{l[match(x,toupper(l))+1]}}else{if(x==9)"A" else as.character(n(x)+1)}};for(o in 1:90){for(g in 1:200){for(h in 2:7){substr(d[o,g],h,h)<-f(substr(a[o,g],h,h))}}} ``` Explanation: ``` a<-as.raster(imager::load.image(file.choose())); //chooses file l=letters;n=as.numeric;d=a; //shortens some names and creates duplicate variable to modify f=function(x){ //creates a function that takes in a if(suppressWarnings(is.na(n(x)))){ character type and checks whether it is if(x=="F")"0" a number or letter. else{l[match(x,toupper(l))+1]}} Returns the converted letter or number. else{ if(x==9)"A" else as.character(n(x)+1)} }; for(o in 1:90){ //loops through every single hex digit and applies for(g in 1:200){ the converting function, modifying the duplicate for(h in 2:7){ variable. Now you have 2 images =D substr(d[o,g],h,h)<-f(substr(a[o,g],h,h)) } } } ``` [![a beautiful rainbow](https://i.stack.imgur.com/s8kRm.png)](https://i.stack.imgur.com/s8kRm.png) ]
[Question] [ Here's a deceptively challenging geometry puzzle for you! Given a circle `A`, and `n` other circles `B[n]`, find the total area contained within `A` that is *not* within any circle of `B`. Your code should be as short as possible. # Input Your input should contain the following information: * A floating-point number to represent the radius of circle `A`. * A list of floating-point numbers to represent the radii of circles in `B`. * A list of the centers of circles in `B`. Your program may expect the centers in either polar or Cartesian coordinates. * Optionally, you may receive the number `n` of circles in B. **This input is not required.** It shall be assumed that the center of circle `A` is the origin, that is, the point `(0, 0)`. It is guaranteed that no two circles in `B` are identical, but it is **not** guaranteed that: all circles of `B` intersect `A`, all centers of `B` are outside `A`, or no two circles in `B` intersect each other. Ensure that your solution can handle various edge cases. You may receive input in any order, and in the form of text input (through stdin or your language's equivalent), function parameters, or command-line arguments. If you choose to receive text input, there should be one or two-character printable ASCII delimiters between pieces of input. # Output Your program or function should output a single floating-point number representing the total area of `A` not within any of the circles of `B`. Your answers should be accurate to at least three significant figures for all test cases. General [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. Your solution should not rely on sampling points within the circles to determine an area. Built-ins that automatically locate intersections of circles, find areas within intersections of circles, or solve this problem immediately are disallowed. # Test Cases In each image, circle `A` is outlined in blue, with circles `B` outlined in green and filled black. The area that should be returned is filled red. (Special thanks to [Rainer P.](https://codegolf.stackexchange.com/users/48165/rainer-p) for checking my solutions) **Test case 1:** ``` A = {x: 0, y: 0, rad: 50} B[0] = {x: 0, y: 0, rad: 100} ``` [![Test case 1](https://i.stack.imgur.com/L67Sl.png)](https://i.stack.imgur.com/L67Sl.png) ``` Result: 0.00 ``` **Test case 2:** ``` A = {x: 0, y: 0, rad: 100.000000} B[0] = {x: 100.000000, y: 0.000000, rad: 50.000000} B[1] = {x: 30.901699, y: -95.105652, rad: 50.000000} B[2] = {x: -80.901699, y: -58.778525, rad: 50.000000} B[3] = {x: -80.901699, y: 58.778525, rad: 50.000000} B[4] = {x: 30.901699, y: 95.105652, rad: 50.000000} ``` [![Test case 2](https://i.stack.imgur.com/98UtH.png)](https://i.stack.imgur.com/98UtH.png) ``` Result: 1.3878e+04 ``` **Test case 3:** ``` A = {x: 0, y: 0, rad: 138} B[0] = {x: 100, y: 0, rad: 100} B[1] = {x: -50, y: -86, rad: 100} B[2] = {x: -93, y: 135, rad: 50} ``` [![Test case 3](https://i.stack.imgur.com/CR8gg.png)](https://i.stack.imgur.com/CR8gg.png) ``` Result: 1.8969e+04 ``` **Test case 4:** ``` A = {x: 0, y: 0, rad: 121.593585} B[0] = {x: 81.000000, y: 107.000000, rad: 59.841457} B[1] = {x: -152.000000, y: -147.000000, rad: 50.000000} B[2] = {x: 43.000000, y: -127.000000, rad: 105.118980} B[3] = {x: 0.000000, y: -72.000000, rad: 57.870545} B[4] = {x: -97.000000, y: -81.000000, rad: 98.488578} B[5] = {x: -72.000000, y: 116.000000, rad: 66.468037} B[6] = {x: 2.000000, y: 51.000000, rad: 50.000000} ``` [![Test case 4](https://i.stack.imgur.com/XCkpq.png)](https://i.stack.imgur.com/XCkpq.png) ``` Result: 1.1264e+04 ``` **Test case 5:** ``` A = {x: 0, y: 0, rad: 121.605921} B[0] = {x: 0.000000, y: -293.000000, rad: 250.000000} B[1] = {x: 0.000000, y: -56.000000, rad: 78.230429} B[2] = {x: 0.000000, y: -102.000000, rad: 100.000000} ``` [![Test case 5](https://i.stack.imgur.com/qslIi.png)](https://i.stack.imgur.com/qslIi.png) ``` Result: 2.6742e+04 ``` Suggested reading: Fewell, M. P. "Area of Common Overlap of Three Circles." Oct. 2006. Web. <http://dspace.dsto.defence.gov.au/dspace/bitstream/1947/4551/4/DSTO-TN-0722.PR.pdf>. [Answer] # Python 2, 631 bytes ``` from cmath import* C=input() O,R=C[0] def I(p,r,q,s): try:q-=p;d=abs(q*q);x=(r*r-s*s+d)/d/2;return[p+q*(x+z*(r*r/d-x*x)**.5)for z in-1j,1j] except:return[] S=sorted V=S(i.real for p,r in C for c in C for i in[p-r,p+r]+I(p,r,*c)if-R<=(i-O).real<=R) A=pi*R*R for l,r in zip(V,V[1:]): H=[] for p,t in C: try: for s in-1,1:a,b=[p.imag+s*(t*t-(p.real-x)**2)**.5for x in l,r];H+=[a+b,a,b,s,t,p], except:0 a,b=H[:2];H=S(H[2:]);n=0;c=a for d in H: s=d[3];z=.5;H*=d<b for q,w,e,_,t,y in(c,min(d,b))*(n-s<(a<d)or[0]*n>H):\ g=phase((l+w*1j-y)/(r+e*1j-y));A-=abs(g-sin(g)).real*t*t/2-z*q*(r-l);z=-z n-=s if(a<d)*s*n==-1:c=d print A ``` *Line-breaks preceded by `\` are for easy reading, and aren't counted in the score.* Reads input through STDIN as a list of `(center, radius)` pairs, where `center` is a complex number in the form `X+Yj`. The first circle in the list is *A* (whose center doesn't have to be at the origin), and the rest of the list is *B*. Prints the result to STDOUT. **Example** ``` Input: (0+0j, 138), (100+0j, 100), (-50+-86j, 100), (-93+135j, 50) Output: 18969.6900901 ``` ## Explanation This is a (longer, and much uglier :P) variation on my [solution](https://codegolf.stackexchange.com/a/47640/31403) to Martin Büttner's [Area of a Self-Intersecting Polygon](https://codegolf.stackexchange.com/q/47638/31403) challenge. It uses the same trick of breaking the problem down into small-enough pieces, for which it becomes more manageable. We find the points of intersection between all pairs of circles (considering both *A*, and the circles in *B*), and pass a vertical line through each of them. Additionally, we pass all the vertical lines tangent to any of the circles. We throw away all the lines that don't intersect *A*, so that all the remaining lines are between the left and right tangents of *A*. [![Figure 1](https://i.stack.imgur.com/d2uK5.png)](https://i.stack.imgur.com/d2uK5.png) We're looking for the area of the intersection of *A* and the union of the circles in *B*—the dark red area in the illustration above. This is the area that we have to subtract from *A* to get the result. Between each pair of consecutive vertical lines, this area can be broken down into a set of vertical trapezoids (or triangles, or line segments, as special cases of trapezoids), with an "excess" arc segment next to each leg. The fact that we pass as many vertical lines as we do guarantees that the bounded area is indeed no more complicated than that, since otherwise there would have to be an additional point of intersection, and hence an additional vertical line, between the two lines in question. [![Figure 2](https://i.stack.imgur.com/BVY0C.png)](https://i.stack.imgur.com/BVY0C.png) To find these trapezoids and arc segments, for each pair of consecutive vertical lines, we find the arc segments of each of the circles that properly lie between these two lines (of course, some circles may have no arc segment between a given pair of lines.) In the illustration below, these are the six (bright and dark) yellow arc segments, when considering the two red vertical lines. Note that, since we pass all vertical lines tangent to the circles, if a circle has an arc segment between the two lines, it necessarily intersects both lines, which simplifies the rest of the algorithm. Not all of these arcs are relevant; we're only interested in the ones that are on the boundary of the intersection between *A* and the union of *B*. To find those, we sort the arcs top-to-bottom (note that the arcs may not properly intersect each other, since this would imply the existence of another vertical line between the two we're considering, and so it makes sense to talk about an arbitrary arc being above, or below, any other one.) [![Figure 3](https://i.stack.imgur.com/3v34G.png)](https://i.stack.imgur.com/3v34G.png) We traverse the arcs, in order, while keeping count of the number of *B* circles we're currently inside, *n*. If *n* changes from 0 to 1 while we're inside *A*, or if we're at the top arc of *A* while *n* is nonzero, then the current arc corresponds to one leg of a trapezoid. If *n* changes from 1 to 0 while we're inside *A*, or if we're at the bottom arc of *A* while *n* is nonzero, then the current arc corresponds to the other leg of the same trapezoid. Once we find such a pair of arcs (the two bright yellow arcs in the above illustration), we calculate the area of the corresponding trapezoid, and of the two arc segments, and add it to the total area to be subtracted from *A*. Calculating the area of *A*, as well as the areas of the trapezoids, is fairly straight forward. The area of each arc segment is the area of the corresponding circular sector, minus the area of the triangle whose vertices are the two endpoints of the arc segment, and the center of the corresponding circle. [![Figure 4](https://i.stack.imgur.com/unffa.png)](https://i.stack.imgur.com/unffa.png) [Answer] # [Desmos](https://desmos.com/calculator), ~~458~~ 438 bytes ``` g(P,R,n)=E(P,R)-E(P[2...],R[2...]) I=[1...n] M=[1,-1] w=join(P.x+R,P.x-R,[P[u].x+h(V.xA+V.yS(4DR[u]^2-AA)^h)/DforS=M,u=I,v=I]) X=w[w=w].sort a=X[t] b=X[t+1] J=I[a-R<P.x<b+R] Y(s)=(P.y+s(RR-(P.x-h(a+b))^2)^h)[J] E(P,R)=[\total((s(b-a)P.y+hRR(U((b-P.x)/R)-U((a-P.x)/R)))[J[0=\sum_{j=1}^n\{J=J[j]:0,Y(-1)[j]<Y(s)<Y(1)[j],0\}]])\for s=M,t=[1...X.\length]].\total U(x)=xp+arctan(x/p) p=(1-xx)^h A=D+R[u]^2-R[v]^2 D=V.x^2+V.y^2 V=P[v]-P[u] h=.5 ``` [Try it on Desmos!](https://www.desmos.com/calculator/n9npb38t1g) *-20 bytes thanks to [@Aiden Chow](https://codegolf.stackexchange.com/users/96039/aiden-chow). Besides syntax, main optimization was converting `D=distance(V,(0,0))` to `D=V.x^2+V.y^2`, which saved a bunch since (old) `D` was squared a few times.* The main function is `g(P,R,n)`, where `n` is the number of points (including A), `P` is the list of points (starting with A), and `R` is the corresponding list of radii. This takes a similar approach as [Ell](https://codegolf.stackexchange.com/a/69135/68261) (with the vertical slices). One big difference is that I ignore A pretty much immediately: the desired area is the area of the union of the discs, minus the area of the unions of the discs excluding A. Not sure if this saves bytes. For reference, the [graph before diving deep into syntax-golfing](https://www.desmos.com/calculator/mauyarkegl), and the [graph when it only calculated the area of the union of discs](https://www.desmos.com/calculator/zs0tcddrgt), with readable variable names. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 73 bytes ``` RegionMeasure@RegionDifference[Disk[{0,0},#1],RegionUnion[Disk@@#&/@#2]]& ``` [Try it online!](https://tio.run/##XY2xCsMgFEX3foUQyGTsM8U0DgWHrIVS6BQcJGgrJRaSdBK/3YpZki6X@ziHd0e1vPSoFjuoaC7xrp/2465azd9Ji/XqrDF60m7QfWfnd@8BQ8AFlXjlD5ciIyGK8iiKWsoy3ibrFmF6CkAw8t6vBUjAiOX0/gSEA204x6jijFBgDasTOSCUnKxU7cZhLTmfW1az/CPg5O2Nf2G/sZ1INMj4Aw "Wolfram Language (Mathematica) – Try It Online") Input: `RMax, {{{xc1, yc1}, r1}, {{xc2, yc2}, r2},...}` ]
[Question] [ Over at <https://math.stackexchange.com/questions/33094/deleting-any-digit-yields-a-prime-is-there-a-name-for-this> the following question is asked. How many primes are there that remain prime after you delete any one of its digits? For example `719` is such a prime as you get `71`, `19` and `79`. While this question is unresolved I thought it make a nice coding challenge. **Task.** Give the largest prime you can find that remains a prime after you delete any one of its digits. You should also provide the code that finds it. **Score.** The value of the prime you give. You can use any programming language and libraries you like as long as they are free. To start things off, `99444901133` is the largest given on the linked page. **Time limit.** I will accept the largest correct answer given exactly one week after the first correct answer larger than `99444901133` is given in an answer. **Scores so far.** **Python (primo)** `4444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444000000000000000000000000000000000000000000000000000000000000000000000000000000001111111111111111111111111111111` **J (randomra)** (This answer started the one week timer on 21st Feb 2013.) ``` 222223333333 ``` [Answer] ## 274 digits ``` 4444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444000000000000000000000000000000000000000000000000000000000000000000000000000000001111111111111111111111111111111 ``` This took about 20 hours of CPU time to find, and about 2 minutes per prime to prove. In contrast, the 84 digit solution can be found in around 3 minutes. ### 84 digits ``` 444444444444444444444444444444444444444444444444441111111113333333333333333333333333 ``` **77777777999999999999999777777777** (32 digits) **66666666666666622222222222222333** (32 digits) **647777777777777777777777777** (27 digits) **44444441333333333333** (20 digits) **999996677777777777** (18 digits) **167777777777777** (15 digits) *I recommend this tool if you want to confirm primality: [D. Alpern's ECM Applet](http://www.alpertron.com.ar/ECM.HTM)* Also using a repdigit approach, which seems to be the approach most likely to find large values. The following script algorithmically skips over most numbers or truncations which will result in multiples of *2, 3, 5* and now *11* c/o [PeterTaylor](https://codegolf.stackexchange.com/questions/10739/#comment20305_10746) (his contribution increased the efficiency by approximately 50%). ``` from my_math import is_prime sets = [ (set('147'), set('0147369'), set('1379')), (set('369'), set('147'), set('1379')), (set('369'), set('0369'), set('17')), (set('258'), set('0258369'), set('39')), (set('369'), set('258'), set('39'))] div2or5 = set('024568') for n in range(3, 100): for sa, sb, sc in sets: for a in sa: for b in sb-set([a]): bm1 = int(b in div2or5) for c in sc-set([b]): if int(a+b+c)%11 == 0: continue for na in xrange(1, n-1, 1+(n&1)): eb = n - na for nb in xrange(1, eb-bm1, 1+(~eb&1)): nc = eb - nb if not is_prime(long(a*(na-1) + b*nb + c*nc)): continue if not is_prime(long(a*na + b*(nb-1) + c*nc)): continue if not is_prime(long(a*na + b*nb + c*(nc-1))): continue if not is_prime(long(a*na + b*nb + c*nc)): continue print a*na + b*nb + c*nc ``` `my_math.py` can be found here: <http://codepad.org/KtXsydxK> Alternatively, you could also use the `gmpy.is_prime` function: [GMPY Project](https://code.google.com/p/gmpy/) Some small speed improvements as a result of profiling. The primality check for the longest of the four candidates has been moved to the end, `xrange` replaces `range`, and `long` replaces `int` type casts. `int` seems to have unnecessary overhead if the evaluated expression results in a `long`. --- ## Divisibility Rules Let *N* be a postitive integer of the form *a...ab...bc...c*, where *a*, *b* and *c* are repeated digits. **By 2 and 5** - To avoid divisibility by *2* and *5*, *c* may not be in the set *[0, 2, 4, 5, 6, 8]*. Additionally, if *b* is a member of this set, the length of *c* may be no less than 2. **By 3** - If *N = 1 (mod 3)*, then *N* may not contain any of *[1, 4, 7]*, as removing any of these would trivially result in a multiple of *3*. Likewise for *N = 2 (mod 3)* and *[2, 5, 8]*. This implementation uses a slightly weakened form of this: if *N* contains one of *[1, 4, 7]*, it may not contain any of *[2, 5, 8]*, and vice versa. Additionally, *N* may not consist solely of *[0, 3, 6, 9]*. This is largely an equivalent statement, but it does allow for some trivial cases, for example *a*, *b*, and *c* each being repeated a multiple of *3* times. **By 11** - As [PeterTaylor](https://codegolf.stackexchange.com/questions/10739/#comment20305_10746) notes, if *N* is of the form *aabbcc...xxyyzz*, that is it consists only of digits repeated an even number of times, it is trivially divisible by *11*: *a0b0c...x0y0z*. This observation eliminates half of the search space. If *N* is of odd length, then the length of *a*, *b* and *c* must all be odd as well (75% search space reduction), and if *N* is of even length, then only one of *a*, *b* or *c* may be even in length (25% search space reduction). - *Conjecture*: if *abc* is a multiple of *11*, for example *407*, then all odd repetitions of *a*, *b* and *c* will also be multiples of *11*. This falls out of the scope of the above divisibility by *11* rule; in fact, only odd repetitions are among those which are explicitly allowed. I don't have a proof for this, but systematic testing was unable to find a counter-example. Compare: *444077777*, *44444000777*, *44444440000077777777777*, etc. ~~Anyone may feel free to prove or disprove this conjecture.~~ [aditsu](https://codegolf.stackexchange.com/questions/10739/#comment20454_10746) has since demonstrated this to be correct. --- ## Other Forms **2 sets of repeated digits** Numbers of the form that [randomra](https://codegolf.stackexchange.com/a/10745/4098) was pursuing, *a...ab...b*, seem to be much more rare. There are only 7 solutions less than *101700*, the largest of which is 12 digits in length. **4 sets of repeated digits** Numbers of this form, *a...ab...bc...cd...d*, appear to be more densely distributed than those I was searching for. There are 69 solutions less than *10100*, compared to the 32 using 3 sets of repeated digits. Those between *1011* and *10100* are as follows: ``` 190000007777 700000011119 955666663333 47444444441111 66666622222399 280000000033333 1111333333334999 1111333333377779 1199999999900111 3355555666999999 2222233333000099 55555922222222233333 444444440004449999999 3366666633333333377777 3333333333999888883333 4441111113333333333311111 2222222293333333333333999999 999999999339999999977777777777 22222226666666222222222299999999 333333333333333333339944444444444999999999 559999999999933333333333339999999999999999 3333333333333333333111111111111666666666611111 11111111333330000000000000111111111111111111111 777777777770000000000000000000033333339999999999999999999999999 3333333333333333333333333333333333333333333333336666666977777777777777 666666666666666666611111113333337777777777777777777777777777777777777777 3333333333333333333888889999999999999999999999999999999999999999999999999933333333 ``` There's a simple heuristic argument as to why this should be the case. For each digital length, there is a number of repeated sets (i.e. 3 repeated sets, or 4 repeated sets, etc.) for which the expected number of solutions will be the highest. The transition occurs when the number of additional possible solutions, taken as a ratio, outweighs the probability that the additional number to be checked is prime. Given the exponential nature of the possibilities to check, and the logarithmic nature of prime number distribution, this happens relatively quickly. If, for example, we wanted to find a 300 digit solution, checking 4 sets of repeated digits would be far more likely to produce a solution than 3 sets, and 5 sets would be more likely still. However, with the computing power that I have at my disposal, finding a solution much larger than 100 digits with 4 sets would be outside of my capacity, let alone 5 or 6. [Answer] ## 222223333333 (12 digits) Here I only searched aa..aabb..bb format up to 100 digits. Only other hits are 23 37 53 73 113 311. J code (cleaned up) (sorry, no explanation): ``` a=.>,{,~<>:i.100 b=.>,{,~<i.10 num=.".@(1&":)@#~ p=.(*/"1@:((1&p:)@num) (]-"1(0,=@i.@#)))"1 1 ]res=./:~~.,b (p#num)"1 1/ a ``` [Answer] ## Javascript (Brute Force) **Has not yet found a higher number** <http://jsfiddle.net/79FDr/4/> Without a bigint library, javascript is limited to integers `<= 2^53`. Since it's Javascript, the browser will complain if we don't release the execution thread for the UI to update, as a result, I decided to track where the algorithm is in its progression in the UI. ``` function isPrime(n){ return n==2||(n>1&&n%2!=0&&(function(){ for(var i=3,max=Math.sqrt(n);i<=max;i+=2)if(n%i==0)return false; return true; })()); }; var o=$("#o"), m=Math.pow(2,53),S=$("#s"); (function loop(n){ var s = n.toString(),t,p=true,i=l=s.length,h={}; if(isPrime(n)){ while(--i){ t=s.substring(0,i-1) + s.substring(i,l); // cut out a digit if(!h[t]){ // keep a hash of numbers tested so we don't end up testing h[t]=1; // the same number multiple times if(!isPrime(+t)){p=false;break;} } } if(p) o.append($("<span>"+n+"</span>")); } S.text(n); if(n+2 < m)setTimeout(function(){ loop(n+2); },1); })(99444901133); ``` [Answer] A link to an analysis of the problem was posted, but I thought it was missing a few things. Let's look at numbers of m digits, consisting of k sequences of 1 or more identical digits. It was shown that if we split digits into the groups { 0, 3, 6, 9 }, { 1, 4, 7 }, and { 2, 5, 8 }, a solution cannot contain digits from both the second and third group, and it must contain 3n + 2 digits from one of these groups. At least two of the k sequences must have an odd number of digits. Out of the digits { 1, 4, 7 } only 1 and 7 can be the lowest digit. None of { 2, 5, 8 } can be the lowest digit. So there are either four (1, 3, 7, 9) or two (3, 9) choices for the lowest digit, six choices of digits for the other sequences of equal digits (7 digits but not the same as the previous sequence) except on average about 5 1/7 choices for the highest digit (0 is excluded giving only 5 choices, except when the second largest sequence contained zeroes). How many candidates are there? We have m digits split in k sequences of at least 1 digit. There are (m - k + 1) over (k - 1) ways to choose the lengths of these sequences, which is about (m - 1.5k + 2)^(k - 1) / (k - 1)!. There are either 2 or 4 choices for the lowest digit, six in total. There are six choices for the other digits, except 36/7 choices for the highest digit; the total is (6/7) \* 6^k. There are 2^k ways to pick whether the length of a sequence is even or odd; k + 1 of these are excluded because none or only one are odd; we multiply the number of choices by (1 - (k + 1) / 2^k), which is 1/4 when k = 2, 1/2 when k = 3, 11/16 when k = 4 etc. The number of digits from the set { 1, 4, 7 } or { 2, 5, 8 } must be 3n + 2, so the number of choices are divided by 3. Multiplying all these numbers, the number of candidates is ``` (m - 1.5k + 2)^(k - 1) / (k - 1)! * (6/7) * 6^k * (1 - (k + 1) / 2^k) / 3 ``` or ``` (m - 1.5k + 2)^(k - 1) / (k - 1)! * (2/7) * 6^k * (1 - (k + 1) / 2^k) ``` The candidate itself and k numbers which are created by removing a digit must all be primes. The probability that a random integer around N is prime is about 1 / ln N. The probability for a random m digit number is about 1 / (m ln 10). However, the numbers here are not random. They have all been picked to be not divisible by 2, 3, or 5. 8 out of any 30 consecutive integers are not divisible by 2, 3, or 5. Therefore, the probability of being a prime is (30 / 8) / (m ln 10) or about 1.6286 / m. The expected number of solutions is about ``` (m - 1.5k + 2)^(k - 1) / (k - 1)! * (2/7) * 6^k * (1 - (k + 1) / 2^k) * (1.6286 / m)^(k + 1) ``` or for large m about ``` (1 - (1.5k - 2) / m)^(k - 1) / (k - 1)! * 0.465 * 9.772^k * (1 - (k + 1) / 2^k) / m^2 ``` For k = 2, 3, 4, ... we get the following: ``` k = 2: 11.1 * (1 - 1/m) / m^2 k = 3: 108 * (1 - 2.5/m)^2 / m^2 k = 4: 486 * (1 - 4/m)^3 / m^2 k = 10: 10,065 * (1 - 13/m)^9 / m^2 ``` From k = 10 onward, the number gets smaller again. ]
[Question] [ ## Introduction Given a set of percentages of choices in a poll, calculate the minimum number of voters there must be in the poll to generate those statistics. Example: What is your favorite pet? * Dog: `44.4%` * Cat: `44.4%` * Mouse: `11.1%` Output: `9` (minimum possible # of voters) ## Specs Here are the requirements for your program/function: * You are given an array of percentage values as input (on stdin, as function argument, etc.) * Each percentage value is a number rounded to one decimal place (e.g., `44.4 44.4 11.1`). * Calculate the minimum possible number of voters in the poll whose results would yield those exact percentages when rounded to one decimal place (on stdout, or function return value). * **Bonus**: -15 characters if you can solve in a "non-trivial" way (i.e., doesn't involve iterating through every possible # of voters until you find the first one that works) ## Example ``` >./pollreverse 44.4 44.4 11.1 9 >./pollreverse 26.7 53.3 20.0 15 >./pollreverse 48.4 13.7 21.6 6.5 9.8 153 >./pollreverse 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1 99.6 2000 >./pollreverse 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1 98.7 667 >./pollreverse 0.2 0.2 0.2 0.2 0.2 0.2 0.2 0.2 0.2 98.7 2000 >./pollreverse 0.2 0.2 0.2 0.2 0.2 0.2 0.2 0.2 0.2 97.8 401 ``` ## Scoring This is code-golf, so shortest possible characters wins. Any bonuses are further subtracted from the total character count. [Answer] # Python, 154 ``` def p(x): n=[1]*len(x);d=2;r=lambda z:round(1000.*z/d)/10 while 1: if(map(r,n),sum(n))==(x,d):return d d+=1 for i in range(len(x)):n[i]+=r(n[i])<x[i] ``` It works for the last example now. Example runs: ``` >>> p([44.4, 44.4, 11.1]) 9 >>> p([26.7, 53.3, 20.0]) 15 >>> p([48.4, 13.7, 21.6, 6.5, 9.8]) 153 >>> p([0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 99.6]) 2000 >>> p([0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 98.7]) 667 >>> p([0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 98.7]) 2000 >>> p([0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 97.8]) 401 ``` [Answer] ## J, 57 characters ``` t=:".>'1'8!:0|:100*%/~i.1001 {.I.*/"1(t{~i.#t)e."1~1!:1[1 ``` Used the trivial method. It takes input from the keyboard. `t` creates a lookup table and the second line looks for the input within the table. I can provide an expanded explanation of the code if anyone's interested. I had looked into using the percentage to create a fraction then get the lowest form of the fraction to figure out the number, but I couldn't figure out a way to make it work with the rounding of the results. [Answer] # Python, 154 ``` def r(l): v=0 while 1: v+=1;o=[round(y*v/100)for y in l];s=sum(o) if s: if all(a==b for a,b in zip(l,[round(y*1000/s)/10for y in o])):return s ``` [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), ~~48~~ 43 bytes *-5 bytes by [Adám](https://codegolf.stackexchange.com/users/43319/ad%c3%a1m)* ``` +/0(⊢+{(⌈/⍷⊢)⍺-⍵÷+/⍵})⍣{z≡⍎3⍕⍺÷+/⍺}⍨z←.01×⎕ ``` Full program taking input from stdin. [Try it online!](https://tio.run/##lY6/DsFQFMb3PsUZK02Pe3urf2YLkwQv0JAgaUJiQWOSCOIKg5ixdDOJxMibnBepUx4Aw/mS7/v9hhMNYrs9juJ@x27F0XDYa2VZYhWFSauTlZi0XhRJ37gUSN9t0tfnzeLlOuV@Tia0PJLeKNJ7xh90n5JOJzTfopDPQ65mXW6s0WZfrdFq9rgomu@4Neplzmal2shGwA6YrosuvENKlAUwHQ99KClU4AgUPLhBDhWvjkQPPCxBiAEDgRK@XRii96saoP9WHfh2/6g@/2oY3UcKoxc "APL (Dyalog Classic) – Try It Online") Link is to dfn version. ### Ungolfed ``` normalize ← ⊢ ÷ +/ find_max ← {⍵⍷⍨⌈/⍵} round ← {⍎3⍕⍵} increase ← {find_max ⍺ - normalize ⍵} vote_totals ← {z←⍺ ⋄ ⍺ (⊢+increase)⍣{z ≡ round normalize ⍺} ⍵} h ← {+/ (.01×⍵) vote_totals 0} ``` [Try it online!](https://tio.run/##lY9NToRAEIX3nKKWEEJBA8PPaSYdQIeEAQNoRgg7Y/xr48a4VjdzATPJLJ2b9EWw6c5EdqOLqqTfe/1VFb0orPSaFtW5lRS0afJkHMuqXtMi7zLgty/AHz7gsAPT1s7yMl2u6UbKPWdfnO042/KnO1s8Bq2uLsv0aD7HMXicvUonL5M6o40C9r8ctgcLZuOm7FXVZsu2amnRqHgn@pTkjzfyhy42Mo9Eg7PPvgN@/w5q/Jy2HxRypUCmDTo65PAmRAPmc5xhHNVZuu@jD7IRgsQA3Q0whIWHHrgOOkLwo8n0hOoSDCDABcQYCcNBAqcqjjH4azTCUEZdOFX/iYZiV01bfW9h8wM "APL (Dyalog Classic) – Try It Online") * `normalize` divides (`÷`) all elements of its right argument (`⊢`) by its sum (`+/`). * `round(y)` rounds y to 3 decimal places by formatting (`⍕`) and then evaluating (`⍎`) each element of y. * `find_max(y)` returns an array with 1 where max(y) is found and 0 elsewhere. * `increase(x,y)` takes x (the goal percentages) and y (the array of current vote totals) and calculates where to add 1 in y to bring the percentages closer to x. * `vote_totals(x,y)` takes x (the goal percentages) and y (the starting vote totals) and executes f repeatedly, adding votes until the percentages round to x. + The syntax `f ⍣ g` means to execute `f` repeatedly until `g(y,f(y))` is true. In this case we ignore `f(y)`. * `h(x)` sets y to 0 (equivalent to an array of 0s due to vectorization), executes g, and sums the final vote totals. [Answer] # VBA - 541 This has got some glaring errors, but it was my attempt to find a non-trivial/looping-until-I-get-the-right-number solution. I have not fully golfed it, though I don't think there's much to add in that regard. However, I've spent too much time on this, and it hurts my head now. Not to mention, the rules are probably very broken and apply more or less to these examples only. This does very well for a lot of simple tests I ran, (i.e. even totals, 2 or 3 inputs) but it fails for some of the tests presented by the challenge. However, I found that if you increase the decimal precision of the input (outside the scope of the challenge), the accuracy improves. Much of the work involves finding the gcd for the set of numbers provided, and I sort of got that through `Function g()`, though it is for sure incomplete and likely a source of at least some of the errors in my outputs. Input is a space-delimited string of values. ``` Const q=10^10 Sub a(s) e=Split(s) m=1 f=UBound(e) For i=0 To f t=1/(e(i)/100) m=m*t n=IIf(n>t Or i=0,t,n) x=IIf(x<t Or i=0,t,x) Next h=g(n,x) i=(n*x)/(h) If Int(i)=Round(Int(i*q)/q) Then r=i ElseIf (n+x)=(n*x) Then r=(1/(n*x))/h/m ElseIf x=Int(x) Then r=x*(f+1) Else z=((n+x)+(n*x)+m)*h y=m/(((m*h)/(f+1))+n) r=IIf(y>z,z,y) End If Debug.Print Round(r) End Sub Function g(a,b) x=Round(Int(a*q)/q,3) y=Round(Int(b*q)/q,3) If a Then If b Then If x>y Then g=g(a-b,b) ElseIf y>x Then g=g(a,b-a) Else g=a End If End If Else g=b End If End Function ``` **Testcases** (input ==> expected/returned): ``` Passed: "95 5" ==> 20/20 "90 10" ==> 10/10 "46.7 53.3" ==> 15/15 "4.7 30.9 40.4 23.8" ==> 42/42 "44.4 44.4 11.1" ==> 9/9 "26.7 53.3 20.0" ==> 15/15 "48.4 13.7 21.6 6.5 9.8" ==> 153/153 "0.05 0.05 0.05 0.05 0.05 0.05 0.05 0.05 0.05 99.55" ==> 2000/2000 "0.15 0.15 0.15 0.15 0.15 0.15 0.15 0.15 0.15 98.65" ==> 2000/2000 "0.149925 0.149925 0.149925 0.149925 0.149925 0.149925 0.149925 0.149925 0.149925 98.65067" ==> 667/667 Failed: "0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1 99.6" ==> 2000/1000 "0.2 0.2 0.2 0.2 0.2 0.2 0.2 0.2 0.2 98.7" ==> 2000/5000 "0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1 98.7" ==> 667/1000 "0.14 0.14 0.14 0.14 0.14 0.14 0.14 0.14 0.14 98.65" ==> 667/10000 "0.2 0.2 0.2 0.2 0.2 0.2 0.2 0.2 0.2 97.8" ==> 401/500 "0.24 0.24 0.24 0.24 0.24 0.24 0.24 0.24 0.24 97.75" ==> 401/235 "0.249377 0.249377 0.249377 0.249377 0.249377 0.249377 0.249377 0.249377 0.249377 97.75561" ==> 401/14010 ``` [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 286 bytes ``` double M(string[]a){var p=a.Select(double.Parse).ToList();var n=p.Select(x=>1d).ToList();var c=2;for(;;){Func<double,double>f=x=>Math.Round(x*1000/c,(MidpointRounding)1)/10;if(n.Select(f).Zip(p,(x,y)=>x==y).All(z=>z)&&c==n.Sum())return c;c++;n=n.Zip(p,(x,y)=>x+(f(x)<y?1:0)).ToList();}} ``` [Try it online!](https://tio.run/##tVRba9swFH6Of4XoQ5AWT7WdS5s58hilHYNmlDYw2NiDZ8utwJEySW6Thvz27Ch2lqRjtHRML8c@@i5HR5fMvM2U5uvKCHmLbhbG8mns7f/RM1WWPLNCSUM/csm1yJ4gLoX8GXvIm1U/SpGhrEyNQVda3ep06i29VpM3NrUQ7pXI0TgVEhurQeXbd5TqW0O8FkBbZ2CjSk6/aGE5CHM8xpI/AGiJjno92jvydzEMaXiEVgQxhoYkfo4eDeiJo/W7tOtiFNBgSw/7z/N7p41tt9aJQjpwcUD7Lgzp6U6t@7xcAMX7rw/DIbg3flEQBP/f8BSW3RgOBicv8Ytq@uvCvt9LF/hvhie7HewFofNbwbFu1QfXQ@tcwUnmaPz75KZkeZ9qNGMpveHuluAaQq9SbTihE3UpjMUkdijJZlvUnCVh/mQ6Y1FcKI3jmCwvKpmNaim/DknBgDRO7R29VpXM8fxNCD05znw8FvlMCWk3eSiLhOQ4DGJRYLn1Kwj9KmZ45uO5vyAsmTO2IPRDWeJHljySdjtjDMDVFBOiua20RFmcdTqxhPQhs4MLPCejxfvwXUD2lrBarV2zmktevwHnsppynbqeeUvkIRiHb8GnHWI0ueamKm2CwG80uRDaWB9NbnimZA4fzSy2d8Ic8jbQBBU142CqZifINCqbvv5VGxUwTeo6m3LdcJsjeIhYbQGPoG08LGwXiZ8iI0DWhn9AvR324U5AWzAI07G655/5HLqI2m0nsJchO4YbC8HLHDVb5MrdCJxVWnMJS3Lc5mdb1wp5q/Uv "C# (.NET Core) – Try It Online") Saved lots of bytes thanks to [Peter Taylor](https://codegolf.stackexchange.com/users/194/peter-taylor) and [Embodiment of Ignorance](https://codegolf.stackexchange.com/users/84206/embodiment-of-ignorance) [Answer] # [Python 3](https://docs.python.org/3/), ~~140~~ ~~139~~ 137 bytes ``` f=lambda l,m=1,i=0,c=0,x=0:round(x*100,1)-l[i]and(x<1and f(l,m,i,c,x+1/m)or f(l,m+1))or l[i+1:]and f(l,m,i+1,c+x)or c+x-1and f(l,m+1)or m ``` [Try it online!](https://tio.run/##pY/NboMwDIDveQqrXGC4GYGWtmg8SdUDg6BFyg8KqUSfnpkirdtOlRrJdmR/X6wMt/DlbDFHugKtxsAiU0FwodFgr@ZTenA9DNINWrJIrQwo28mJRW0FrbvasEKbldqAnAZJQMeiiYCr99IGCP4GvfOrCooxZQbnA4y3kVHwUQYvCR6Vs1oZFWKR0UnmvtaN@ewa0GhqgarOsKWY6qzytLyLpzciUSRbfVaXZml8CCrQx2SgwhanVLybhJbfW6lIljvRqaguv8hUYJtOy4zK9vEGCdQz8@CVDXEfn3c7vkNYsxBcXJKE/Qzzkh8Q9gUvEPKMZ8sweqjHu1QsTC54iVDyPcKJH/9yGRcIz6bTiZev6Ed@@K/ny@y59Kp@uP99/gY "Python 3 – Try It Online") Gives the right answer for the first two test cases, and runs into Python's recursion limits for the others. This is not very surprising, since *every* check is made on a new recursion level. It's short, though... (An explanation of the used variables can be found in the TIO link) ``` f=lambda l,m=1,i=0,c=0,x=1:round(x*100,1)-l[i]and(x and f(l,m,i,c,x-1/m)or f(l,m+1))or l[i+1:]and f(l,m,i+1,c+x)or c+x-1and f(l,m+1)or m ``` should work for **136** bytes, but doesn't due to float precision. ]
[Question] [ ## Non-math explanation *This is an explanation that is meant to be approachable regardless of your background. It does unfortunately involve some math, but should be understandable to most people with a middle school level of understanding* A pointer sequence is any sequence such that \$a(n+1) = a(n-a(n))\$. Lets pick apart this formula a little bit to understand what it means. This just means to figure out the next term in the sequence we look at the last term, take that many steps back and copy the term we find. For example if we had the sequence so far to be ``` ... 3 4 4 4 3 ? ``` We would take 3 steps back from `3` ``` ... 3 4 4 4 3 ? ^ ``` making our result `4`. Now normally we play this game on a tape that is infinite in both directions, but we can also play it on a wheel where after a certain number of steps we get back to the beginning of the sequence. For example here is an visualization of the sequence `[1,3,1,3,1,3]` [![Wheel](https://i.stack.imgur.com/0Rhpk.png)](https://i.stack.imgur.com/0Rhpk.png) Now we might notice that any number, \$x\$ in a wheel that exceeds the number of cells in the wheel, \$n\$, might as well be \$x\$ modulo \$n\$ because every complete circuit around the wheel is the same as doing nothing. So we will only consider wheels with all members being less than the size of the wheel. ## Math explanation A pointer sequence is any sequence such that \$a(n+1) = a(n-a(n))\$. Usually these are defined from the integers to the integers, however you might notice that the only things needed in this definition are a successor function and an inverse function. Since all cyclic groups have both of these we can actually consider pointer sequences on any cyclic groups. If we start looking for these types of functions we will notice that for each function there are a couple of similar functions. For example on \$\mathbb{Z}\_3\$ the following 3 are all functions that fit our requirements. ``` f1 : [1,2,2] f2 : [2,1,2] f3 : [2,2,1] ``` *(Here a list is used to represent a function to get the result just index the list by the input)* We might notice that these functions are all "rotations" of each other. To formalize what I mean by rotation, a function \$b\$ is a rotation of \$a\$ iff \$ \exists n : \forall m : a(m+n) = b(m) \$ We can actually show that if \$a\$ is a pointer sequence every rotation of \$a\$ is also a pointer sequence. Thus we will actually consider any sequences that are rotations of each other to be equivalent. ## Task Given \$n\$ as input output the number of pointer sequences that have size \$n\$. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so answers will be scored in bytes with less bytes being better. ## Testcases Currently these testcases are lacking a bit, I have a computer program to generate these but it is inordinately slow at doing so. If anyone would like to contribute larger testcases (that they can verify correct) they are free to do so. Below some tests is a list of all the functions that I found, this might be useful for debugging. I can't add these for the larger ones because of character limits. If you want the code I used to generate these [here it is](https://tio.run/##ZVI9b8IwEN39Kw6JwVYVRMYi0q1Dt24dIgMmcRsLx7YSQ6Hiv6dn7KSILjnfu4/37i6N6A9S62E4yU59XkCr3oMhcIUW1pmW5ss3ESyimc2AtrYGap5yBi2D4l8gG30TEghR/btVxstubCS0pnd8rFwuFndUWc4JqeVe9BIMBBP0mKJYYm3Jg2N9I7tvhQkFBNKYtkpFtFanBLFYT1xU0CNcQC3ro4OyXF7P66zMFwvDOYc5fCodVP7pnSBqrH/VsoUlm7fCAd1Fqh2OWJoNzpwzbLMxSXvoXzWyOsgaFSNlch5C1Fu3OprksjCZMBegnfXCi72WgAlsSh@Vj/5U@biSmHbrPva@Sya39hJWK3gzHrIXKAVPZoxto@xyAgycewR@lPtQeKfKGjwlrTvrMESrS4Vizz1j@EkEN/0C9lglw@r2uM6xPE6I1wnb50h83cZLpN9AcD60Qt2OZQlo6cHhe7riMwHX4Rtbpgo3Im74BQ "Haskell – Try It Online") ``` 1 -> 1 [[0]] 2 -> 2 [[1,1],[0,0]] 3 -> 4 [[2,2,2],[2,2,1],[1,1,1],[0,0,0]] 4 -> 7 [[3,3,3,3],[3,3,3,2],[2,2,2,2],[3,3,3,1],[3,1,3,1],[1,1,1,1],[0,0,0,0]] 5 -> 12 [[4,4,4,4,4],[4,4,4,4,3],[3,3,3,3,3],[4,4,4,4,2],[4,3,4,4,2],[2,2,2,2,2],[4,4,4,4,1],[4,3,4,4,1],[4,4,2,4,1],[4,4,1,4,1],[1,1,1,1,1],[0,0,0,0,0]] 6 -> 35 [[5,5,5,5,5,5],[5,5,5,5,5,4],[5,5,4,5,5,4],[4,4,4,4,4,4],[5,5,5,5,5,3],[5,4,5,5,5,3],[5,5,5,3,5,3],[5,3,5,3,5,3],[3,3,3,3,3,3],[5,5,5,5,5,2],[5,4,5,5,5,2],[5,3,5,5,5,2],[5,5,4,5,5,2],[5,5,2,5,5,2],[5,5,2,5,2,2],[5,3,2,5,2,2],[5,2,2,5,2,2],[4,2,2,4,2,2],[2,2,2,2,2,2],[5,5,5,5,5,1],[5,4,5,5,5,1],[5,3,5,5,5,1],[5,5,4,5,5,1],[5,5,2,5,5,1],[5,5,1,5,5,1],[5,5,5,3,5,1],[5,3,5,3,5,1],[5,5,5,2,5,1],[5,5,5,1,5,1],[5,3,5,1,5,1],[5,1,5,1,5,1],[3,1,3,1,3,1],[2,2,1,2,2,1],[1,1,1,1,1,1],[0,0,0,0,0,0]] 7 -> 80 [[6,6,6,6,6,6,6],[6,6,6,6,6,6,5],[6,6,6,5,6,6,5],[5,5,5,5,5,5,5],[6,6,6,6,6,6,4],[6,5,6,6,6,6,4],[6,6,6,5,6,6,4],[6,6,6,6,4,6,4],[6,5,6,6,4,6,4],[6,4,6,6,6,4,4],[4,4,4,4,4,4,4],[6,6,6,6,6,6,3],[6,5,6,6,6,6,3],[6,4,6,6,6,6,3],[6,6,5,6,6,6,3],[6,6,4,6,6,6,3],[5,6,6,5,6,6,3],[6,6,6,6,4,6,3],[6,5,6,6,4,6,3],[6,6,4,6,4,6,3],[6,4,4,6,4,6,3],[6,6,6,6,3,6,3],[6,6,4,6,3,6,3],[3,3,3,3,3,3,3],[6,6,6,6,6,6,2],[6,5,6,6,6,6,2],[6,4,6,6,6,6,2],[6,3,6,6,6,6,2],[6,6,5,6,6,6,2],[6,6,4,6,6,6,2],[6,6,6,5,6,6,2],[6,4,6,5,6,6,2],[6,3,6,5,6,6,2],[6,6,6,3,6,6,2],[6,4,6,3,6,6,2],[6,3,6,3,6,6,2],[6,6,6,2,6,6,2],[6,6,2,6,6,3,2],[6,6,6,2,6,2,2],[6,6,4,2,6,2,2],[6,6,3,2,6,2,2],[2,2,2,2,2,2,2],[6,6,6,6,6,6,1],[6,5,6,6,6,6,1],[6,4,6,6,6,6,1],[6,3,6,6,6,6,1],[6,6,5,6,6,6,1],[6,6,4,6,6,6,1],[6,6,2,6,6,6,1],[6,6,6,5,6,6,1],[6,4,6,5,6,6,1],[6,3,6,5,6,6,1],[6,6,6,3,6,6,1],[6,4,6,3,6,6,1],[6,3,6,3,6,6,1],[6,6,6,2,6,6,1],[6,6,6,1,6,6,1],[6,6,6,6,4,6,1],[6,5,6,6,4,6,1],[6,3,6,6,4,6,1],[6,6,4,6,4,6,1],[6,4,4,6,4,6,1],[6,6,2,6,4,6,1],[6,6,1,6,4,6,1],[6,6,6,6,3,6,1],[6,6,4,6,3,6,1],[6,6,2,6,3,6,1],[6,6,1,6,3,6,1],[6,6,6,6,2,6,1],[6,5,6,6,2,6,1],[6,3,6,6,2,6,1],[6,6,6,6,1,6,1],[6,5,6,6,1,6,1],[6,3,6,6,1,6,1],[6,6,4,6,1,6,1],[6,6,2,6,1,6,1],[6,6,1,6,1,6,1],[3,6,1,6,6,3,1],[1,1,1,1,1,1,1],[0,0,0,0,0,0,0]] 8 -> 311 [[7,7,7,7,7,7,7,7],[7,7,7,7,7,7,7,6],[7,7,7,6,7,7,7,6],[7,7,7,7,6,7,7,6],[6,6,6,6,6,6,6,6],[7,7,7,7,7,7,7,5],[7,6,7,7,7,7,7,5],[7,7,7,6,7,7,7,5],[7,7,7,5,7,7,7,5],[7,7,7,7,6,7,7,5],[7,6,7,7,6,7,7,5],[7,7,7,7,7,5,7,5],[7,6,7,7,7,5,7,5],[7,7,7,5,7,5,7,5],[7,5,7,5,7,5,7,5],[7,5,7,7,7,7,5,5],[7,5,7,6,7,7,5,5],[7,5,7,7,7,6,5,5],[5,5,5,5,5,5,5,5],[7,7,7,7,7,7,7,4],[7,6,7,7,7,7,7,4],[7,5,7,7,7,7,7,4],[7,7,6,7,7,7,7,4],[7,7,5,7,7,7,7,4],[6,7,7,6,7,7,7,4],[5,5,7,5,7,7,7,4],[7,7,7,7,6,7,7,4],[7,6,7,7,6,7,7,4],[7,7,5,7,6,7,7,4],[7,7,7,7,4,7,7,4],[7,6,7,7,4,7,7,4],[7,7,7,7,7,5,7,4],[7,6,7,7,7,5,7,4],[7,5,7,7,7,5,7,4],[7,7,6,7,7,5,7,4],[7,7,4,7,7,5,7,4],[7,7,7,7,7,4,7,4],[7,7,6,7,7,4,7,4],[7,7,4,7,7,4,7,4],[7,4,7,7,7,7,5,4],[7,4,7,7,4,7,5,4],[4,4,4,4,4,4,4,4],[7,7,7,7,7,7,7,3],[7,6,7,7,7,7,7,3],[7,5,7,7,7,7,7,3],[7,4,7,7,7,7,7,3],[7,7,6,7,7,7,7,3],[7,7,5,7,7,7,7,3],[7,7,4,7,7,7,7,3],[7,7,7,6,7,7,7,3],[7,5,7,6,7,7,7,3],[7,4,7,6,7,7,7,3],[7,7,7,5,7,7,7,3],[7,5,7,5,7,7,7,3],[7,4,7,5,7,7,7,3],[7,7,7,3,7,7,7,3],[6,7,7,7,6,7,7,3],[6,7,7,3,6,7,7,3],[7,7,7,7,7,5,7,3],[7,6,7,7,7,5,7,3],[7,5,7,7,7,5,7,3],[7,7,6,7,7,5,7,3],[7,7,4,7,7,5,7,3],[7,7,7,5,7,5,7,3],[7,5,7,5,7,5,7,3],[7,7,5,5,7,5,7,3],[7,6,5,5,7,5,7,3],[7,4,5,5,7,5,7,3],[7,7,7,3,7,5,7,3],[7,5,7,3,7,5,7,3],[7,7,7,7,7,4,7,3],[7,7,6,7,7,4,7,3],[7,7,4,7,7,4,7,3],[7,7,7,5,7,4,7,3],[7,7,7,3,7,4,7,3],[7,7,7,7,7,3,7,3],[7,6,7,7,7,3,7,3],[7,5,7,7,7,3,7,3],[7,7,7,5,7,3,7,3],[7,5,7,5,7,3,7,3],[7,7,7,3,7,3,7,3],[7,5,7,3,7,3,7,3],[7,3,7,3,7,3,7,3],[7,3,5,7,7,7,5,3],[7,3,5,3,7,3,5,3],[5,3,5,3,5,3,5,3],[7,7,7,3,7,7,3,3],[7,5,7,3,7,7,3,3],[7,4,7,3,7,7,3,3],[7,7,4,3,7,7,3,3],[7,7,3,3,7,7,3,3],[7,7,7,3,7,6,3,3],[7,5,7,3,7,6,3,3],[7,7,4,3,7,6,3,3],[7,7,3,3,7,6,3,3],[7,6,3,3,7,6,3,3],[7,7,3,3,7,3,3,3],[7,6,3,3,7,3,3,3],[7,4,3,3,7,3,3,3],[7,3,3,3,7,3,3,3],[6,3,3,3,6,3,3,3],[5,3,3,3,5,3,3,3],[3,3,3,3,3,3,3,3],[7,7,7,7,7,7,7,2],[7,6,7,7,7,7,7,2],[7,5,7,7,7,7,7,2],[7,4,7,7,7,7,7,2],[7,3,7,7,7,7,7,2],[7,7,6,7,7,7,7,2],[7,7,5,7,7,7,7,2],[7,7,4,7,7,7,7,2],[7,7,7,6,7,7,7,2],[7,5,7,6,7,7,7,2],[7,4,7,6,7,7,7,2],[7,3,7,6,7,7,7,2],[7,7,7,5,7,7,7,2],[7,5,7,5,7,7,7,2],[7,4,7,5,7,7,7,2],[7,3,7,5,7,7,7,2],[7,7,7,3,7,7,7,2],[7,5,7,3,7,7,7,2],[7,4,7,3,7,7,7,2],[7,3,7,3,7,7,7,2],[7,7,7,2,7,7,7,2],[7,7,7,7,6,7,7,2],[7,6,7,7,6,7,7,2],[7,4,7,7,6,7,7,2],[7,3,7,7,6,7,7,2],[7,7,5,7,6,7,7,2],[7,7,4,7,6,7,7,2],[7,7,7,7,4,7,7,2],[7,6,7,7,4,7,7,2],[7,4,7,7,4,7,7,2],[7,3,7,7,4,7,7,2],[7,7,5,7,4,7,7,2],[7,7,4,7,4,7,7,2],[7,5,4,7,4,7,7,2],[7,7,7,7,3,7,7,2],[7,7,5,7,3,7,7,2],[7,7,4,7,3,7,7,2],[7,7,7,7,2,7,7,2],[7,6,7,7,2,7,7,2],[7,4,7,7,2,7,7,2],[7,3,7,7,2,7,7,2],[4,7,7,7,7,4,7,2],[4,7,6,7,7,4,7,2],[4,7,4,7,7,4,7,2],[4,7,7,5,7,4,7,2],[4,7,7,2,7,4,7,2],[3,3,7,7,7,3,7,2],[3,3,7,5,7,3,7,2],[3,3,7,7,4,3,7,2],[3,3,7,7,3,3,7,2],[3,3,7,6,3,3,7,2],[3,3,7,3,3,3,7,2],[3,3,7,2,3,3,7,2],[7,7,2,7,7,7,4,2],[7,7,2,7,4,7,4,2],[7,7,2,7,3,7,4,2],[7,7,7,2,7,7,3,2],[7,7,3,2,7,7,3,2],[7,4,7,2,4,7,3,2],[3,3,3,2,3,3,3,2],[7,7,7,7,2,7,2,2],[7,6,7,7,2,7,2,2],[7,4,7,7,2,7,2,2],[7,7,7,5,2,7,2,2],[7,4,7,5,2,7,2,2],[7,7,7,4,2,7,2,2],[7,4,7,4,2,7,2,2],[2,2,2,2,2,2,2,2],[7,7,7,7,7,7,7,1],[7,6,7,7,7,7,7,1],[7,5,7,7,7,7,7,1],[7,4,7,7,7,7,7,1],[7,3,7,7,7,7,7,1],[7,7,6,7,7,7,7,1],[7,7,5,7,7,7,7,1],[7,7,4,7,7,7,7,1],[7,7,2,7,7,7,7,1],[7,7,7,6,7,7,7,1],[7,5,7,6,7,7,7,1],[7,4,7,6,7,7,7,1],[7,3,7,6,7,7,7,1],[7,7,7,5,7,7,7,1],[7,5,7,5,7,7,7,1],[7,4,7,5,7,7,7,1],[7,3,7,5,7,7,7,1],[7,7,7,3,7,7,7,1],[7,5,7,3,7,7,7,1],[7,4,7,3,7,7,7,1],[7,3,7,3,7,7,7,1],[7,7,7,2,7,7,7,1],[7,7,7,1,7,7,7,1],[7,7,7,7,6,7,7,1],[7,6,7,7,6,7,7,1],[7,4,7,7,6,7,7,1],[7,3,7,7,6,7,7,1],[7,7,5,7,6,7,7,1],[7,7,4,7,6,7,7,1],[7,7,2,7,6,7,7,1],[7,7,7,7,4,7,7,1],[7,6,7,7,4,7,7,1],[7,4,7,7,4,7,7,1],[7,3,7,7,4,7,7,1],[7,7,5,7,4,7,7,1],[7,7,4,7,4,7,7,1],[7,5,4,7,4,7,7,1],[7,7,2,7,4,7,7,1],[7,4,7,2,4,7,7,1],[7,7,7,7,3,7,7,1],[7,7,5,7,3,7,7,1],[7,7,4,7,3,7,7,1],[7,7,2,7,3,7,7,1],[7,7,7,7,2,7,7,1],[7,6,7,7,2,7,7,1],[7,4,7,7,2,7,7,1],[7,3,7,7,2,7,7,1],[7,7,7,7,1,7,7,1],[7,6,7,7,1,7,7,1],[7,4,7,7,1,7,7,1],[7,3,7,7,1,7,7,1],[7,7,7,7,7,5,7,1],[7,6,7,7,7,5,7,1],[7,5,7,7,7,5,7,1],[7,3,7,7,7,5,7,1],[7,7,6,7,7,5,7,1],[7,7,4,7,7,5,7,1],[7,7,2,7,7,5,7,1],[7,7,1,7,7,5,7,1],[7,7,7,5,7,5,7,1],[7,5,7,5,7,5,7,1],[7,3,7,5,7,5,7,1],[7,7,5,5,7,5,7,1],[7,6,5,5,7,5,7,1],[7,4,5,5,7,5,7,1],[7,7,7,3,7,5,7,1],[7,5,7,3,7,5,7,1],[7,3,7,3,7,5,7,1],[7,7,7,2,7,5,7,1],[7,7,7,1,7,5,7,1],[7,5,7,1,7,5,7,1],[7,7,7,7,7,4,7,1],[7,7,6,7,7,4,7,1],[7,7,4,7,7,4,7,1],[7,7,2,7,7,4,7,1],[7,7,1,7,7,4,7,1],[7,7,7,5,7,4,7,1],[7,7,7,3,7,4,7,1],[7,7,7,2,7,4,7,1],[7,7,7,1,7,4,7,1],[7,7,4,7,2,4,7,1],[7,7,7,7,7,3,7,1],[7,6,7,7,7,3,7,1],[7,5,7,7,7,3,7,1],[7,3,7,7,7,3,7,1],[7,7,7,5,7,3,7,1],[7,5,7,5,7,3,7,1],[7,3,7,5,7,3,7,1],[7,7,7,3,7,3,7,1],[7,5,7,3,7,3,7,1],[7,3,7,3,7,3,7,1],[7,7,7,2,7,3,7,1],[7,7,7,1,7,3,7,1],[7,5,7,1,7,3,7,1],[7,3,7,1,7,3,7,1],[7,3,7,7,3,3,7,1],[7,3,7,6,3,3,7,1],[7,3,7,2,3,3,7,1],[7,7,7,7,7,2,7,1],[7,6,7,7,7,2,7,1],[7,5,7,7,7,2,7,1],[7,3,7,7,7,2,7,1],[7,7,6,7,7,2,7,1],[7,7,4,7,7,2,7,1],[7,7,2,7,7,2,7,1],[7,4,2,7,7,2,7,1],[7,7,1,7,7,2,7,1],[7,7,2,7,2,2,7,1],[7,5,2,7,2,2,7,1],[7,4,2,7,2,2,7,1],[7,7,7,7,7,1,7,1],[7,6,7,7,7,1,7,1],[7,5,7,7,7,1,7,1],[7,3,7,7,7,1,7,1],[7,7,6,7,7,1,7,1],[7,7,4,7,7,1,7,1],[7,7,2,7,7,1,7,1],[7,7,1,7,7,1,7,1],[7,7,7,5,7,1,7,1],[7,5,7,5,7,1,7,1],[7,3,7,5,7,1,7,1],[7,7,7,3,7,1,7,1],[7,5,7,3,7,1,7,1],[7,3,7,3,7,1,7,1],[7,7,7,2,7,1,7,1],[7,7,7,1,7,1,7,1],[7,5,7,1,7,1,7,1],[7,3,7,1,7,1,7,1],[7,1,7,1,7,1,7,1],[5,1,5,1,5,1,5,1],[4,7,1,7,7,7,4,1],[4,7,1,7,7,5,4,1],[3,7,7,1,7,7,3,1],[3,7,3,1,3,7,3,1],[3,5,7,1,7,5,3,1],[3,5,3,1,3,5,3,1],[3,3,3,1,3,3,3,1],[3,1,3,1,3,1,3,1],[1,1,1,1,1,1,1,1],[0,0,0,0,0,0,0,0]] 9 -> 1049 10 -> 4304 ``` *Last case calculated by @HyperNeutrino* [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~18~~ 17 bytes ``` J_ịṙ1⁼ ṗṙ€RṂ€QÇ€S ``` [Try it online!](https://tio.run/##y0rNyan8///hzpl1QKx7dJJLJtfDndOB7EdNa4Ie7mwCUoGH24Fk8H@zoENbj@4Bc9z/AwA "Jelly – Try It Online") ### How it works ``` ṗṙ€RṂ€QÇ€S Main link. Argument: n ṗ Cartesian power; yield all vectors of n elements of [1, ..., n]. R Range; yield [1, ..., n]. ṙ€ Rotate each vector 1, ..., and n units to the left. Ṃ€ Take the minimum of each array of rotations of the same vector. Q Unique; deduplicate the resulting array. Since each vector is replaced by its lexicographically minimal rotation, no resulting vector will be a rotation of another vector. Ç€ Map the helper link over the remaining vectors. Vectors that represent pointer sequences map to 1, others to 0. S Take the sum. J_ịṙ1⁼ Helper link. Argument: v = (v1, ..., vn) J Indices; yield [1, ..., n]. _ Subtract v, yielding [1 - v1, ..., n - vn]. ị Index into v, yielding [v(1 - v1), ..., v(n - vn)]. ṙ1 Rotate the result one unit to the left. ⁼ Compare the result with v. ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~162~~ ~~156~~ ~~152~~ ~~146~~ 143 bytes ``` lambda n:len({min(l[i:]+l[:i]for i in R(n))for l in product(*[R(n)]*n)if all(l[-~i-n]==l[i-l[i]]for i in R(n))}) from itertools import* R=range ``` [Try it online!](https://tio.run/##XYyxDgIhEET7@4ot4QyNjQkJP3HtSYEe6CbLQhAvMcb7dTwsLaZ4kzeTX/We@NiCOTdy8bI4YE2exTsiC5pR2wPNGm1IBRCQYRIsZSfqlEtantcqxrn3dmSJARzRPlUbKrbG7Cdqj/27@MghlBQBqy81JXoAxpxKHYfJFMc337q/dv@H4iR1LsgVglDbKtsX "Python 2 – Try It Online") More or less brute force: * Generates all permutations `product(r,repeat=n)` * Checks valid lists. `all(l[-~i-n]==l[i-l[i]]for i in r)` * Generates a set of the minimum (lexicographical) rotation of the valid lits `min(l[i:]+l[:i]for i in r)` --- **Recursive function that short circuits a bit:** This version is longer, but is able to calculate `f(10)` in ~19 secs on [tio.run](https://tio.run/##VY0xDoMwDEV3TpHRhlABY1R6EZohVRPqiBoU6IAQvTpNhkrt4C8P//03rctj5OZw7fUYzPN2N4LVYBl6YAllLTFnxCy0wXBvs779lqSRvq3UbBdAcsLwCgnbImK68k0l6/hQGU/rHS@NG4MgQSwCeEQ7zFZE@PRiGhnyLvlMp7wugCQWpvNFrbSMiT8ko042f2aRFrYnMUSD0hFQpP@auB9TIF6Eg7rC4wM) On my machine, I've found: * `f(11) = 16920` * `f(12) = 78687` # [Python 2](https://docs.python.org/2/), 209 bytes ``` lambda n:len(g(n,(-1,)*n)) r=range g=lambda n,a,j=0:set()if any(len({-1,a[-~i-n],a[i-a[i]]})>2for i in r(j))else set.union(*[g(n,a[:j]+(i,)+a[j+1:],j+1)for i in r(n)])if j<n else{min(a[i:]+a[:i]for i in r(n))} ``` [Try it online!](https://tio.run/##VY4xDsIwDEV3TpENmzqIMEaUi5QMQaTFUXGrUAaE4OolGRAw2LKl//w83qfzINu5rQ9z7y/Hk1di@yDQgRBoQ7gSxEWqk5cuLLr6EyJPsd7Ya5gAuVVe7lCwR0Z8o1@sxeWBdS7nnrjftkNSrFhUgogY@mtQGV7fhAeBVVN8vrHRVcCElW9iZayj3PGHFHTFFneiyoXHhQWywboMWHZ/SXzO3718D4aMQTsmlkkxLfV@SS0wzm8 "Python 2 – Try It Online") **Explanation:** ``` f=lambda n:len(g(n,(-1,)*n)) #calls the recursive function, and gets length. #The initial circle is all -1, and is built recursively r=range g=lambda n,a,j=0: #if any of the indexes so far break the pointer rule (ignored if 'empty'), stop recursion. if any(len({-1,a[-~i-n],a[i-a[i]]})>2for i in r(j)) return set() else if j<n: #recursively call g with a+ all numbers in range ie.(a+[0], a+[1], ..) return set.union(*[g(n,a[:j]+(i,)+a[j+1:],j+1)for i in r(n)]) else # if recursion depth == n, we are done. Return the smallest (lexicographically) rotation. return {min(a[i:]+a[:i]for i in r(n))} ``` [Answer] # CJam, 37 ``` ri:M_m*{:XM,Xfm<:e<=M{(_X=-X=}%X=&},, ``` [Try it online](http://cjam.aditsu.net/#code=ri%3AM_m*%7B%3AXM%2CXfm%3C%3Ae%3C%3DM%7B(_X%3D-X%3D%7D%25X%3D%26%7D%2C%2C&input=5) Pretty much brute force, and it feels kinda clumsy. It gets very slow after 6. Replace the last comma with a `p` to print the wheels. [Answer] # Pyth, 28 bytes ``` l{mS.>LdQf!fn@ThY@T-Y@TYUQ^U ``` [Test suite](https://pyth.herokuapp.com/?code=l%7BmS.%3ELdQf%21fn%40ThY%40T-Y%40TYUQ%5EU&test_suite=1&test_suite_input=3%0A4%0A5%0A6&debug=0) First, we generate all sequences of the appropriate length with the appropriate elements. Second, we check whether there are any pointer failures. Third, map to all sorted rotations. Fourth, deduplicate and count. [Answer] # [Haskell](https://www.haskell.org/), ~~117 112~~ 104 bytes ``` f k|x<-[1..k]=sum[1|y@(h:t)<-mapM(x<$f)x,t++[h]==[y!!mod(n-a)k|(n,a)<-zip x y],and[y<=drop n y++y|n<-x]] ``` Brute force, so pretty slow for large inputs. [Try it online!](https://tio.run/##Fc1BCsMgEEDRq0ygC8UYyK4UhV4gJxApghXFOJEkBS3e3Tb7z/veHPG9rr07iK0IruZpiloen6TmVp/EP04qeDJ5IUXcHC3jyZjyWkpVhyFtliA3NDaCo/mH35ChQNWjQauqkHbfMiBUxmpDwYvWPZmAIOEiX0DyHvCECRyFa33X/Qc "Haskell – Try It Online") -5 bytes thanks to Laikoni. -5 bytes thanks to Ørjan Johansen. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~150~~ 123 bytes ``` nCount[Tuples[r=Range@n-1,{n}],l_/;l==Sort[l~RotateLeft~#&~Array~n][[1]]&&And@@(!1!-!0//.!a_:>l[[Mod[#+a,n,1]]]&/@r)] ``` [Try it online!](https://tio.run/##Jc1NCoJAFADgswzC0M@YuWlRTIy0TQhr9xjikWMJ41OmcRGRh/AGdUGPYEH7D74K/c1U6MsLjoUcaejfu7olD6e2seYOTmZIV6MojMWTXlrYc7SxUh5r58F2We3Rm70pfBfwLnEOHx1pgFhrzhPKlZqweOg/LGTLKFowPK@3FiCtcwjmKEj8oOaRclM9ptjAwZXk1awQ/3Wlxy8 "Wolfram Language (Mathematica) – Try It Online") -27 bytes thanks to att. Explanation from 150 byte version: ``` p=Part[#,Mod[#2,Length@#,1]]&; -helper function to take part of circular list n|-> Count[ -count all the Tuples[Range@n-1,{n}], -possible sequences _?(l|-> -where l==Sort[Array[RotateLeft[l,#]&,n]][[1]] -the sequence is the first of all rotations of that sequence && -and And@@Array[p[l,#+1]==p[l,#-p[l,#]]&,n] -the pointer property holds for all elements in that sequence )] ``` ]
[Question] [ Write a program to draw a 2-D diagram of a knot based on the knot's structure. A knot is exactly what it sounds like: a loop of rope that's tied up. In mathematics, a knot diagram shows where a piece of rope crosses over or under itself to form the knot. Some example knot diagrams are shown below: [![enter image description here](https://i.stack.imgur.com/Upkbw.jpg)](https://i.stack.imgur.com/Upkbw.jpg) There's a break in the line where the rope crosses over itself. Input: the input describing the knot is an array of integers. A knot where the rope crosses over itself *n* times can be represented as an array of *n* integers, each with a value in the range [0, n-1]. Let's call this array *K*. To get the array describing a knot, number each of the segments 0 through n-1. Segment 0 should lead to segment 1, which should lead to segment 2, which should lead to segment 3, and so on until segment n-1 loops back and leads to segment 0. A segment ends when another segment of rope crosses over it (represented by a break in the line in the diagram). Let's take the simplest knot - the trefoil knot. After we've numbered the segmnents, segment 0 ends when segment 2 crosses over it; segment 1 ends when segment 0 crosses over it; and segment 2 ends when segment 1 crosses over it. Thus, the array describing the knot is [2, 0, 1]. In general, segment *x* starts where segment *x-1 mod n* left off, and ends where segment *K[x]* crosses over it. The below image show knot diagrams, with labeled segments and the corresponding arrays that describe the knot. [![enter image description here](https://i.stack.imgur.com/CFkY7.jpg)](https://i.stack.imgur.com/CFkY7.jpg) The top three diagrams are true knots, while the bottom three are loops of rope that cross over themself but aren't actually knotted (but which still have corresponding codes). Your task is to write a function which takes an array of integers *K* (you could call it something different) that describes a knot (or loop of rope that's not actually knotted), and which produces the corresponding knot diagram, as described in the above examples. If you can, provide an ungolfed version of your code or an explanation, and also provide sample outputs of your code. The same knot can often be represented in multiple different ways, but if the knot diagram your function outputs satisfies has the input as one of it's possible representations, your solution is valid. This is code-golf, so shortest code in bytes wins. The line representing the rope can have a thickness of 1 pixel, however under and over-crossings must be clearly distinguishable (the size of the break in the rope should be greater than the thickness of the rope by at least a pixel on either side). I will upvote answers that rely on built-in knot theory capabilities, but the one that's selected in the end can't rely on built-in knot theory capabilities. **Everything I know about my notation:** I believe that there are sequences of values that don't seem to correspond to any knot or unknot. For example, the sequence [2, 3, 4, 0, 1] seems to be impossible to draw. Aside from that, suppose that you take a crossing and, starting from that crossing, follow the path of the rope in one direction and label every unlabeled crossing that you come across with succesively greater integral values. For alternating knots, there is a simple algorithm to convert my notation into such a labeling, and for alternating knots it's trivial to convert this labeling into a Gauss Code: ``` template<size_t n> array<int, 2*n> LabelAlternatingKnot(array<int, n> end_at) { array<int, n> end_of; for(int i=0;i<n;++i) end_of[end_at[i]] = i; array<int, 2*n> p; for(int& i : p) i = -1; int unique = 0; for(int i=0;i<n;i++) { if(p[2*i] < 0) { p[2*i] = unique; p[2*end_of[i] + 1] = unique; ++unique; } if(p[2*i+1] < 0) { p[2*i+1] = unique; p[2*end_at[i]] = unique; ++unique; } } return p; } template<size_t n> auto GetGaussCode(array<int, n> end_at) { auto crossings = LabelAlternatingKnot(end_at); for(int& i : crossings) ++i; for(int i=1;i<2*n;i+=2) crossings[i] = -crossings[i]; return crossings; } ``` [Answer] # GNU Prolog, ~~622~~ ~~634~~ 668 bytes in code page 850 **Update**: The previous version of the program was sometimes making crossings so tight that they wouldn't render properly, which violates the spec. I've added in some extra code to prevent that. **Update**: Apparently PPCG rules require extra code to make the program exit and restore the state exactly as it was at the start. This makes the program somewhat longer and adds no algorithmic interest to it, but in the interests of rule compliance, I've changed it. ## Golfed program Using GNU Prolog because it has a constraint solver syntax that's slightly shorter than portable Prolog's arithmetic syntax, saving a few bytes. ``` y(A,G):-A=1;A= -1;A=G;A is-G. z(A/B,B,G):-y(A,G),y(B,G),A=\= -B. v(D,E,G):-E=1,member(_-_,D),p(D);F#=E-1,nth(F,D,M),(M=[_];M=L-S/R,z(L,O,G),J is F+O,nth(J,D,I/U-T/Q),(I=O,Q#=R-1,S=T;K is J+O,R=0,n(S-T-V),y(U,G),U\=O,U=\= -O,I=U,nth(K,D,O/_-V/_))),v(D,F,G). i([H|K],S):-K=[]->assertz(n(S-H-0));T#=S+1,assertz(n(S-H-T)),i(K,T). t([],1,_):-!. t(D,R,G):-S#=R-1,t(E,S,G),H#=G-1,length(F,H),append(F,[[x]|E],D). s(1,2). s(-1,1). s(S,T):-S>1->T=3;T=0. r(I/O-_,C):-s(I,J),s(O,P),N#=J*4+P+1,nth(N,"│┐┌?└─?┌┘?─┐?┘└│",C). r([X],C):-X\=y->C=10;C=32. p([]). p([H|T]):-r(H,C),put_code(C),!,p(T). g(4). g(G):-g(H),G#=H+1. m(K):-i(K,0),g(G),t(D,G,G),length(D,L),v(D,L,G),abolish(n/1). ``` ## Algorithm This is one of those problems where it's hard to know how to start. It's not obvious how to work out the shape of the knot from the notation given, because it doesn't let you know whether you're meant to bend the line to the left or the right at any given location (and as such, the notation might be ambiguous). My solution was, effectively, to use the old golfing standby: write an incredibly inefficient program which generates all possible outputs and then see if they match the input. (The algorithm used here is slightly more efficient, as Prolog can throw out the occasional dead end, but it doesn't have enough information to improve the computational complexity.) The output is via terminal art. GNU Prolog seems to want a single byte character set that's consistent with ASCII, but doesn't care which one is used (as it treats characters with the high bit set as opaque). As a result, I used IBM850, which is widely supported and has the line drawing characters we need. ## Output The program searches all possible knot images, in the order of the size of their bounding box, then exits when it finds the first. Here's what the output looks like for `m([0]).`: ``` ┌┐ ┌│┘ └┘ ``` This took 290.528 seconds to run on my computer; the program isn't very efficient. I left it running for two hours on `m([0,1])`, and ended up with this: ``` ┌┐┌┐ └─│┘ └┘ ``` ## Ungolfed version with comments Stack Exchange's syntax highlighter seems to have the wrong comment symbol for Prolog, so instead of `%` comments (which Prolog actually uses), this explanation uses `% #` comments (which are of course equivalent due to starting with `%`, but highlight correctly). ``` % # Representation of the drawing is: a list of: % # indelta/outdelta-segment/distance (on path) % # and [x] or [_] (off path; [x] for border). % # A drawing is valid, and describes a knot, if the following apply % # (where: d[X] is the Xth element of the drawing, % # k[S] is the Sth element of the input, % # n[S] is S + 1 modulo the number of sections): % # d[X]=_/O-S-R, R>1 implies d[X+O]=O/_-S-(R-1) % # d[X]=_/O-S-0 implies d[X+O]=_/_-k[S]-_ % # and d[X+O*2]=O/_-n[S]-_ % # all outdeltas are valid deltas (±1 row/column) % # not technically necessary, but makes it possible to compile the % # code (and thus makes the program faster to test): :- dynamic([n/1]). % # legal delta combinations: y(A,G):-A=1;A= -1; % # legal deltas are 1, -1, A=G;A is-G. % # grid size, minus grid size z(A/B,B,G):-y(A,G),y(B,G), % # delta components are valid A=\= -B. % # doesn't U-turn % # z returns the outdelta for convenience (= byte savings) later on % # We use v (verify) to verify the first E-1 elements of a drawing D. % # nth is 1-indexed, so we recurse from length(D)+1 down to 2, with % # 1 being the trivial base case. After verifying, the grid is printed. % # This version of the program causes v to exit with success after % # printing one grid (and uses p to do the work of deciding when that is). v(D,E,G):-E=1, % # base case: member(_-_,D), % # ensure the grid is nonempty p(D); % # print the grid (and exit) % # otherwise, recursive case: F#=E-1,nth(F,D,M), % # check the last unchecked element ( M=[_]; % # either it's not on the path; or M=L-S/R, % # it's structured correctly, and z(L,O,G), % # it has a valid delta; J is F+O, % # find the outdelta'd element index nth(J,D,I/U-T/Q), % # and the outdelta'd element ( I=O,Q#=R-1,S=T; % # if not an endpoint, points to next pixel K is J+O, % # else find segment beyond the path: R=0, % # it's an endpoint, n(S-T-V), % # it points to the correct segment, y(U,G), % # ensure we can do NOT comparisons on U U\=O,U=\= -O, % # the line we jump is at right angles I=U, % # the line we jump is straight nth(K,D,O/_-V/_) % # the pixel beyond has a correct indelta, % # and it has the correct segment number ) ), v(D,F,G). % # recurse % # We use i (init) to set up the k, n tables (k and n are fixed for % # any run of the program, at least). S is the number of elements that % # have been removed from K so far (initially 0). To save on characters, % # we combine k and n into a single predicate n. i([H|K],S):-K=[]-> % # if this is the last element, assertz(n(S-H-0)); % # section 0 comes after S; T#=S+1, % # otherwise, add 1 to S, assertz(n(S-H-T)), % # that section comes after S, i(K,T). % # and recurse. % # We use t (template) to create a template drawing. First argument is % # the drawing, second argument is the number of rows it has plus 1, % # third argument is the number of columns it has plus 1. t([],1,_):-!. t(D,R,G):-S#=R-1,t(E,S,G), % # recurse, H#=G-1,length(F,H), % # F is most of this row of the grid append(F,[[x]|E],D). % # form the grid with F + border + E % # We use s (shrink) to map a coordinate into a value in the range 0, 1, 2, 3. s(1,2). s(-1,1). s(S,T):-S>1->T=3;T=0. % # We use r (representation) to map a grid cell to a character. r(I/O-_,C):-s(I,J),s(O,P),N#=J*4+P+1,nth(N,"│┐┌?└─?┌┘?─┐?┘└│",C). r([X],C):-X\=y->C=10;C=32. % # We use p (print) to pretty-print a grid. % # The base case allows us to exit after printing one knot. p([]). p([H|T]):-r(H,C),put_code(C),!,p(T). % # We use g (gridsize) to generate grid sizes. g(4). g(G):-g(H),G#=H+1. % # Main program. m(K):-i(K,0), % # initialize n g(G), % # try all grid sizes t(D,G,G), % # generate a square knot template, size G length(D,L), % # find its length v(D,L,G), % # verify and print one knot % # Technically, this doesn't verify the last element of L, but we know % # it's a border/newline, and thus can't be incorrect. abolish(n/1). % # reset n for next run; required by PPCG rules ``` ]
[Question] [ > > Given a list of points, find the shortest path that visits all points and returns to the starting point. > > > The [Travelling Salesman Problem](http://en.wikipedia.org/wiki/Travelling_salesman_problem) is well-known in the computer science field, as are many ways to calculate/approximate it. It's been solved for very large groups of points, but some of the largest take many CPU-years to finish. > > Don't get burned by the potato. > > > [Hot Potato](http://en.wikipedia.org/wiki/Hot_potato_%28game%29) is a game where 2+ players pass a "potato" around in a circle while music plays. The object is to pass it to the next player quickly. If you are holding the potato when the music stops, you're out. --- The object of **Hot Potato Salesman** is: > > Given a set of **100 unique points**, return those points in a better order (*shorter total distance as defined further down*). This will "pass" the problem to the next player. They have to improve it and pass it to the next, etc. If a player cannot improve it, they are out and play continues until one player is left. > > > To keep this from being a "brute-force-me-a-path" competition, there are these stipulations: * You cannot take more than **one minute** to pass the potato. If you haven't found and passed a shorter solution by the time one minute is up, you're out. * You cannot change the position of more than **25** points. To be exact, `>= 75` points must be in the same position as you received them. It does not matter *which* ones you decide to change, just the *amount* you change. When only one player is left, he is the winner of that game, and receives one point. A tourney consists of `5*n` games, where `n` is the number of players. Each game, the starting player will be *rotated*, and the remaining player order will be *shuffled*. The player with the most points at the end is the winner of the tourney. If the tourney ends with a tie for first place, a new tourney will be played with only those contestants. This will continue until there is no tie. The starting player for each game will receive a set of pseudorandomly selected points in no particular order. Points are defined as a pair of integer `x,y` coordinates on a cartesian grid. Distance is measured using [Manhattan distance](http://en.wikipedia.org/wiki/Taxicab_geometry), `|x1-x2| + |y1-y2|`. All coordinates will lie in the `[0..199]` range. ## Input Input is given with a single string argument. It will consist of 201 comma-separated integers representing the number of current players(`m`) and 100 points: ``` m,x0,y0,x1,y1,x2,y2,...,x99,y99 ``` The order of these points is the current path. The total distance is obtained by adding the distance from each point to the next (`dist(0,1) + dist(1,2) + ... + dist(99,0)`). *Don't forget to return to start when calculating total distance!* Note that `m` is *not* the number of players that started the game, it is the number that are still in. ## Output Output is given in the same way as input, minus `m`; a single string containing comma-separated integers representing the points in their new order. ``` x0,y0,x1,y1,x2,y2,...,x99,y99 ``` The control program will wait for output for one minute only. When output is received, it will verify that: * the output is well-formed * the output consists of *only* and *all* the 100 points present in the input * `>=75` points are in their original positions * the path length is less than the previous path If any of these checks fail (or there is no output), you are out and the game will proceed to the next player. ## Control Program You can find the control program [at this link](https://bitbucket.org/Geobits/hotpotatosalesman/src). The control program itself is deterministic, and is posted with a dummy seed of `1`. The seed used during scoring will be different, so don't bother trying to analyze the turn order/point lists it spits out. The main class is `Tourney`. Running this will do a full tournament with contestants given as arguments. It spits out the winner of each game and a tally at the end. A sample tourney with two SwapBots looks like: ``` Starting tournament with seed 1 (0) SwapBot wins a game! Current score: 1 (1) SwapBot wins a game! Current score: 1 (1) SwapBot wins a game! Current score: 2 (1) SwapBot wins a game! Current score: 3 (0) SwapBot wins a game! Current score: 2 (1) SwapBot wins a game! Current score: 4 (1) SwapBot wins a game! Current score: 5 (1) SwapBot wins a game! Current score: 6 (1) SwapBot wins a game! Current score: 7 (1) SwapBot wins a game! Current score: 8 Final Results: Wins Contestant 2 (0) SwapBot 8 (1) SwapBot ``` If you want to test just one game at a time, you can run the `Game` class instead. This will run one game with players in the order given as arguments. By default, it will also print a play-by-play showing the current player and path length. Also included are a few test players: `SwapBot`, `BlockPermuter`, and `TwoSwapBot`. The first two will not be included in scoring runs, so feel free to use and abuse them during testing. `TwoSwapBot` **will** be included in judging, and he's no slouch, so bring your A-game. ## Miscellany * You cannot save state information, and each turn is a separate run of your program. The only information you will receive each turn is the set of points. * You cannot use external resources. This includes network calls and file access. * You cannot use library functions designed to solve/assist with the TSP problem or its variants. * You cannot manipulate or interfere with other players in any way. * You cannot manipulate or interfere with the control program or any included classes or files in any way. * Multi-threading is allowed. * One submission per user. If you submit more than one entry, I will only enter the first one submitted. If you want to change your submission, edit/delete the original. * The tournament will be running on Ubuntu 13.04, on a computer with an [i7-3770K CPU](http://ark.intel.com/products/65523/Intel-Core-i7-3770K-Processor-8M-Cache-up-to-3_90-GHz) and 16GB RAM. It will not be run in a VM. Anything I perceive as malicious will immediately disqualify the current **and** any future entry you submit. * All entries must be runnable from the command line with free ([*as in beer*](http://en.wikipedia.org/wiki/Gratis_versus_libre#.22Free_beer.22_vs_.22free_speech.22_distinction)) software. If I have problems compiling/running your entry, I will request aid in the comments. If you do not respond or I cannot ultimately get it running, it will be disqualified. ## Results (22 May 2014) New results are in! UntangleBot has beaten the competition quite soundly. TwoSwapBot managed seven wins, and SANNbot snuck a victory in as well. Here's a scoreboard, and a [link to the raw output](http://pastebin.com/wFePpbiU): ``` Wins Contestant 22 (2) ./UntangleBot 7 (0) TwoSwapBot 1 (5) SANNbot.R 0 (1) BozoBot 0 (3) Threader 0 (4) DivideAndConquer ``` As it stands *now*, **UntangleBot** has won the checkmark. Don't let that discourage you from entering, though, since I'll run the tournament as more contestants appear and change the accepted answer accordingly. [Answer] # UntangleBot (formerly NiceBot) A C++11 bot that uses two strategies. At first it will try to "untangle" the path if possible, by detecting intersections between paths that are closer than 25 points (since untangling implies modifying all points in-between). If the first strategy fails, it randomly swaps points to find better distances until a better path has been found. This bot consistently beats TwoSwapBot with an approximate ratio of five victories for one loss in my test tourneys. ``` // g++ -std=c++11 -O3 -o UntangleBot UntangleBot.cpp #include <algorithm> #include <chrono> #include <cmath> #include <iostream> #include <iterator> #include <random> #include <set> #include <sstream> const int NPOINTS = 100; struct Point { int x, y; Point():x(0),y(0) {} Point(int x, int y):x(x),y(y) {} int distance_to(const Point & pt) const { return std::abs(x - pt.x) + std::abs(y - pt.y); } }; std::ostream & operator<<(std::ostream & out, const Point & point) { return out << point.x << ',' << point.y; } int total_distance(const Point points[NPOINTS]) { int distance = 0; for (int i = 0; i < NPOINTS; ++i) { distance += points[i].distance_to(points[(i+1)%NPOINTS]); } return distance; } bool intersects(const Point & p1, const Point & p2, const Point & p3, const Point & p4) { double s1_x, s1_y, s2_x, s2_y; s1_x = p2.x - p1.x; s1_y = p2.y - p1.y; s2_x = p4.x - p3.x; s2_y = p4.y - p3.y; double s, t; s = (-s1_y * (p1.x - p3.x) + s1_x * (p1.y - p3.y)) / (-s2_x * s1_y + s1_x * s2_y); t = ( s2_x * (p1.y - p3.y) - s2_y * (p1.x - p3.x)) / (-s2_x * s1_y + s1_x * s2_y); return s >= 0 && s <= 1 && t >= 0 && t <= 1; } int main(int argc, char ** argv) { Point points[NPOINTS]; using Clock = std::chrono::system_clock; const Clock::time_point start_time = Clock::now(); // initialize points if (argc < 2) { std::cerr << "Point list is missing" << std::endl; return 1; } std::stringstream in(argv[1]); int players; char v; in >> players >> v; for (int i = 0; i < NPOINTS; ++i) { in >> points[i].x >> v >> points[i].y >> v; } int original_distance = total_distance(points); // detect intersection between any 4 points for (int i = 0; i < NPOINTS; ++i) { for (int j = i+1; j < NPOINTS; ++j) { Point & p1 = points[i]; Point & p2 = points[(i+1)%NPOINTS]; Point & p3 = points[j]; Point & p4 = points[(j+1)%NPOINTS]; // points must all be distinct if (p1.distance_to(p3) == 0 || p1.distance_to(p4) == 0 || p2.distance_to(p3) == 0 || p2.distance_to(p4) == 0) { continue; } // do they intersect ? if (!intersects(p1, p2, p3, p4)) { continue; } // can modify less than 25 points ? if (std::abs(j-i) > 25) { continue; } // swap points for (int m = 0; m < std::abs(j-i)/2; ++m) { if (i+1+m != j-m) { std::swap(points[i+1+m], points[j-m]); //std::cerr << "untangle " << i+1+m << " <=> " << j-m << '\n'; } } int new_distance = total_distance(points); if (new_distance < original_distance) { std::copy(std::begin(points), std::end(points)-1, std::ostream_iterator<Point>(std::cout, ",")); std::cout << points[NPOINTS-1]; return 0; } else { // swap points back for (int m = 0; m < std::abs(j-i)/2; m++) { if (i+1+m != j-m) { std::swap(points[i+1+m], points[j-m]); } } } } } // more traditional approach if the first fails std::mt19937 rng(std::chrono::duration_cast<std::chrono::seconds>(start_time.time_since_epoch()).count()); std::uniform_int_distribution<> distr(0, NPOINTS-1); while (true) { // try all possible swaps from a random permutation int p1 = distr(rng); int p2 = distr(rng); std::swap(points[p1], points[p2]); for (int i = 0; i < NPOINTS; ++i) { for (int j = i+1; j < NPOINTS; ++j) { std::swap(points[i], points[j]); if (total_distance(points) < original_distance) { std::copy(std::begin(points), std::end(points)-1, std::ostream_iterator<Point>(std::cout, ",")); std::cout << points[NPOINTS-1]; return 0; } else { std::swap(points[i], points[j]); } } } // they didn't yield a shorter path, swap the points back and try again std::swap(points[p1], points[p2]); } return 0; } ``` [Answer] ### SANNbot (a simulated annealing bot in **R**) Should be called with `Rscript SANNbot.R`. ``` input <- strsplit(commandArgs(TRUE),split=",")[[1]] n <- as.integer(input[1]) # Number of players init_s <- s <- matrix(as.integer(input[-1]),ncol=2,byrow=TRUE) # Sequence of points totdist <- function(s){ # Distance function d <- 0 for(i in 1:99){d <- d + (abs(s[i,1]-s[i+1,1])+abs(s[i,2]-s[i+1,2]))} d } gr <- function(s){ # Permutation function changepoints <- sample(1:100,size=2, replace=FALSE) tmp <- s[changepoints[1],] s[changepoints[1],] <- s[changepoints[2],] s[changepoints[2],] <- tmp s } d <- init_d <- totdist(s) # Initial distance k <- 1 # Number of iterations v <- 0 t <- n*(init_d/12000) # Temperature repeat{ si <- gr(s) # New sequence di <- totdist(si) # New distance dd <- di - d # Difference of distances if(dd <= 0 | runif(1) < exp(-dd/t)){ # Allow small uphill changes d <- di s <- si v <- v+2 } k <- k+1 if(k > 10000){break} if(d > init_d & v>20){s <- init_s; d <- init_d; v <- 0} if(v>23){break} } cat(paste(apply(s,1,paste,collapse=","),collapse=",")) ``` The idea is relatively simple: each turn is one "cooling step" of a [simulated annealing](http://en.wikipedia.org/wiki/Simulated_annealing) with the number of players still in the game as "temperature" (modified by the current distance over 12000, i.e. roughly the initial distance). Only difference with a proper simulated annealing is that I checked that i don't permute more than 25 elements and if i used up 20 moves but the resulting sequence is worth than the initial then it start over again. [Answer] # BozoBot Utilizes the complex logic behind [Bozosort](http://projecteuler.net/problem=367) to find a better path. It looks like this. * Swap random points * If we improved + Return the answer * Otherwise + Try again ~~BozoBot has now been improved with **Multithreading**! Four minions now aimlessly juggle points until they stumble upon an improvement. The first one to find a solution gets a cookie!~~ Apparently I fail at multithreading. ``` import java.util.Random; public class BozoBot { public static String[] input; public static void main(String[] args) { input = args; for(int i = 0; i < 4; i++) new Minion().run(); } } class Minion implements Runnable { public static boolean completed = false; public static synchronized void output(int[] x, int[] y) { if(!completed) { completed = true; String result = x[0]+","+y[0]; for (int i = 1; i < 100; i++) result+=","+x[i]+","+y[i]; System.out.print(result); // receiveCookie(); // Commented out to save money } } public void run() { String[] args = BozoBot.input[0].split(","); int[] x = new int[100]; int[] y = new int[100]; for (int i = 1; i < 201; i+=2) { x[(i-1)/2] = Integer.parseInt(args[i]); y[i/2] = Integer.parseInt(args[i+1]); } int startDistance = 0; for (int i = 1; i < 100; i++) startDistance += Math.abs(x[i-1]-x[i]) + Math.abs(y[i-1]-y[i]); int r1, r2, r3, r4, tX, tY, newDistance; Random gen = new java.util.Random(); while (true) { r1 = gen.nextInt(100); r2 = gen.nextInt(100); r3 = gen.nextInt(100); r4 = gen.nextInt(100); tX = x[r1]; x[r1] = x[r2]; x[r2] = tX; tY = y[r1]; y[r1] = y[r2]; y[r2] = tY; tX = x[r3]; x[r3] = x[r4]; x[r4] = tX; tY = y[r3]; y[r3] = y[r4]; y[r4] = tY; newDistance = 0; for (int i=1; i < 100; i++) newDistance += Math.abs(x[i-1]-x[i]) + Math.abs(y[i-1]-y[i]); if(newDistance < startDistance) break; tX = x[r1]; x[r1] = x[r2]; x[r2] = tX; tY = y[r1]; y[r1] = y[r2]; y[r2] = tY; tX = x[r3]; x[r3] = x[r4]; x[r4] = tX; tY = y[r3]; y[r3] = y[r4]; y[r4] = tY; } output(x,y); } } ``` [Answer] # TwoSwapBot An upgrade to `SwapBot`, this guy checks for every pair of swaps. First, he checks if any single swap will shorten the path. If it does, it returns immediately. If not, he checks each to see if *another* swap will shorten it. If not, he just dies. While the path is still semi-random, it normally returns in about 100ms. If he has to check each and every 2-swap (roughly 25M), it takes about 20 seconds. At the time of submission, this beat all other competitors in test rounds. ``` public class TwoSwapBot { static int numPoints = 100; String run(String input){ String[] tokens = input.split(","); if(tokens.length < numPoints*2) return "bad input? nope. no way. bye."; Point[] points = new Point[numPoints]; for(int i=0;i<numPoints;i++) points[i] = new Point(Integer.valueOf(tokens[i*2+1]), Integer.valueOf(tokens[i*2+2])); int startDist = totalDistance(points); Point[][] swapped = new Point[(numPoints*(numPoints+1))/2][]; int idx = 0; for(int i=0;i<numPoints;i++){ for(int j=i+1;j<numPoints;j++){ Point[] test = copyPoints(points); swapPoints(test,i,j); int testDist = totalDistance(test); if( testDist < startDist) return getPathString(test); else swapped[idx++] = test; } } for(int i=0;i<idx;i++){ for(int k=0;k<numPoints;k++){ for(int l=k+1;l<numPoints;l++){ swapPoints(swapped[i],k,l); if(totalDistance(swapped[i]) < startDist) return getPathString(swapped[i]); swapPoints(swapped[i],k,l); } } } return "well damn"; } void swapPoints(Point[] in, int a, int b){ Point tmp = in[a]; in[a] = in[b]; in[b] = tmp; } String getPathString(Point[] in){ String path = ""; for(int i=0;i<numPoints;i++) path += in[i].x + "," + in[i].y + ","; return path.substring(0,path.length()-1); } Point[] copyPoints(Point[] in){ Point[] out = new Point[in.length]; for(int i=0;i<out.length;i++) out[i] = new Point(in[i].x, in[i].y); return out; } static int totalDistance(Point[] in){ int dist = 0; for(int i=0;i<numPoints-1;i++) dist += in[i].distance(in[i+1]); return dist + in[numPoints-1].distance(in[0]); } public static void main(String[] args) { if(args.length < 1) return; System.out.print(new TwoSwapBot().run(args[0])); } class Point{ final int x; final int y; Point(int x, int y){this.x = x; this.y = y;} int distance(Point other){return Math.abs(x-other.x) + Math.abs(y-other.y);} } } ``` [Answer] # Threader This bot 1. Splits the 100 points up in ~~4~~**10** pieces of ~~25~~**10** points 2. Starts a thread for each piece 3. In the thread, randomly shuffle the array, while keeping the start- and endpoint fixed 4. If distance of new array is shorter, keep it 5. After 59s, the main thread collects the results and prints it out The idea is to find the best improvement to the path, so that the other bots will fail with their logic. ``` import java.util.Arrays; import java.util.Collections; public class Threader { public static final int THREAD_COUNT = 10; public static final int DOT_COUNT = 100; private final Dot[] startDots = new Dot[THREAD_COUNT]; private final Dot[] endDots = new Dot[THREAD_COUNT]; private final Dot[][] middleDots = new Dot[THREAD_COUNT][DOT_COUNT/THREAD_COUNT-2]; private final Worker worker[] = new Worker[THREAD_COUNT]; private final static long TIME = 59000; public static void main(String[] args) { Threader threader = new Threader(); //remove unnecessary player count to make calculation easier threader.letWorkersWork(args[0].replaceFirst("^[0-9]{1,3},", "").split(",")); } public void letWorkersWork(String[] args) { readArgs(args); startWorkers(); waitForWorkers(); printOutput(); } private void readArgs(String[] args) { final int magigNumber = DOT_COUNT*2/THREAD_COUNT; for (int i = 0; i < args.length; i += 2) { Dot dot = new Dot(Integer.parseInt(args[i]), Integer.parseInt(args[i + 1])); if (i % magigNumber == 0) { startDots[i / magigNumber] = dot; } else if (i % magigNumber == magigNumber - 2) { endDots[i / magigNumber] = dot; } else { middleDots[i / magigNumber][(i % magigNumber) / 2 - 1] = dot; } } } private void startWorkers() { for (int i = 0; i < THREAD_COUNT; i++) { worker[i] = new Worker(startDots[i], endDots[i], middleDots[i]); Thread thread = new Thread(worker[i]); thread.setDaemon(true); thread.start(); } } private void waitForWorkers() { try { Thread.sleep(TIME); } catch (InterruptedException e) { } } private void printOutput() { //get results Worker.stopWriting = true; int workerOfTheYear = 0; int bestDiff = 0; for (int i = 0; i < THREAD_COUNT; i++) { if (worker[i].diff() > bestDiff) { bestDiff = worker[i].diff(); workerOfTheYear = i; } } //build output StringBuilder result = new StringBuilder(1000); for (int i = 0; i < THREAD_COUNT; i++) { result.append(startDots[i]); Dot middle[] = middleDots[i]; if (i == workerOfTheYear) { middle = worker[i].bestMiddle; } for (int j = 0; j < middle.length; j++) { result.append(middle[j]); } result.append(endDots[i]); } result.replace(0, 1, ""); //replace first comma System.out.print(result); } } class Worker implements Runnable { public Dot start; public Dot end; private Dot[] middle = new Dot[Threader.DOT_COUNT/Threader.THREAD_COUNT-2]; public Dot[] bestMiddle = new Dot[Threader.DOT_COUNT/Threader.THREAD_COUNT-2]; public static boolean stopWriting = false; private int bestDist = Integer.MAX_VALUE; private final int startDist; public Worker(Dot start, Dot end, Dot[] middle) { this.start = start; this.end = end; System.arraycopy(middle, 0, this.middle, 0, middle.length); System.arraycopy(middle, 0, this.bestMiddle, 0, middle.length); startDist = Dot.totalDist(start, middle, end); } @Override public void run() { while (true) { shuffleArray(middle); int newDist = Dot.totalDist(start, middle, end); if (!stopWriting && newDist < bestDist) { System.arraycopy(middle, 0, bestMiddle, 0, middle.length); bestDist = newDist; } } } public int diff() { return startDist - bestDist; } private void shuffleArray(Dot[] ar) { Collections.shuffle(Arrays.asList(ar)); } } class Dot { public final int x; public final int y; public Dot(int x, int y) { this.x = x; this.y = y; } public int distTo(Dot other) { return Math.abs(x - other.x) + Math.abs(y - other.y); } public static int totalDist(Dot start, Dot[] dots, Dot end) { int distance = end.distTo(start); distance += start.distTo(dots[0]); distance += end.distTo(dots[dots.length - 1]); for (int i = 1; i < dots.length; i++) { distance += dots[i].distTo(dots[i - 1]); } return distance; } @Override public String toString() { return "," + x + "," + y; } } ``` [Answer] # Divide And Conquer + Greedy Bot **NOTE:** I looked at your code for `Game` which includes the following in Game.parsePath: ``` for(int i=0;i<numPoints;i++){ test[i] = new Point(Integer.valueOf(tokens[i*2]), Integer.valueOf(tokens[i*2+1])); if(test[i].equals(currentPath[i])) same++; ``` However, there is no `catch(NumberFormatException)` block, so your program will likely crash when a player program outputs a string (as demonstrated at the end of my program's `main` method). I advise you fix this, because programs could output exceptions, stack traces, or the like. Otherwise, comment out that line in my program before you run it. ## Back to the topic This implementation (in Java) splits the list of points into chunks of 25, randomly spaced on the list. Then, it creates threads to shorten the path between the points in each chunk (Hence, "Divide and Conquer"). The main thread monitors the others and makes sure to present the shortest solution within the time limit. If a thread dies with or without a solution, it starts another thread off again on a different chunk. Each thread uses the "greedy" algorithm, which starts off on a random point, goes to the closest point, and repeats until all the points are covered (Hence, "greedy"). ### Notes * This will run through the full 1 minute (I gave 3 seconds for program startup/shutdown and JVM startup - you never know what the JVM startup routines get caught up on next...) * Even if it has found solutions, it will keep searching and after the 1 minute is up it presents the best solution it found. * I'm not sure if this implementation is actually any good. I had some fun coding it though :) * Since a lot of things are random, this may not give the same output for the same input. Just compile and use `java DivideAndConquer.class` to run. ``` public class DivideAndConquer extends Thread { static LinkedList<Point> original; static Solution best; static LinkedList<DivideAndConquer> bots; static final Object _lock=new Object(); public static void main(String[] args){ if(args.length != 1) { System.err.println("Bad input!"); System.exit(-1); } // make sure we don't sleep too long... get the start time long startTime = System.currentTimeMillis(); // parse input String[] input=args[0].split(","); int numPlayers=Integer.parseInt(input[0]); original=new LinkedList<Point>(); for(int i=1;i<input.length;i+=2){ original.add(new Point(Integer.parseInt(input[i]), Integer.parseInt(input[i+1]))); } // start threads bots=new LinkedList<DivideAndConquer>(); for(int i=0;i<6;i++) bots.add(new DivideAndConquer(i)); // sleep try { Thread.sleep(57000 - (System.currentTimeMillis() - startTime)); } catch(Exception e){} // should never happen, so ignore // time to collect the results! Solution best=getBestSolution(); if(best!=null){ best.apply(original); String printStr=""; for(int i=0;i<original.size();i++){ Point printPoint=original.get(i); printStr+=printPoint.x+","+printPoint.y+","; } printStr=printStr.substring(0, printStr.length()-1); System.out.print(printStr); } else { System.out.println("Hey, I wonder if the tournament program crashes on NumberFormatExceptions... Anyway, we failed"); } } // check the distance public static int calculateDistance(List<Point> points){ int distance = 0; for(int i=0;i<points.size();i++){ int next=i+1; if(next>=points.size())next=0; distance+=points.get(i).distance(points.get(next)); } return distance; } public static void solutionFound(Solution s){ // thanks to Java for having thread safety features built in synchronized(_lock){ // thanks to Java again for short-circuit evaluation // saves lazy programmers lines of code all the time if(best==null || best.distDifference < s.distDifference){ best=s; } } } public static Solution getBestSolution(){ // make sure we don't accidentally return // the best Solution before it's even // done constructing synchronized(_lock){ return best; } } List<Point> myPoints; int start; int length; int id; public DivideAndConquer(int id){ super("DivideAndConquer-Processor-"+(id)); this.id=id; myPoints=new LinkedList<Point>(); start=(int) (Math.random()*75); length=25; for(int i=start;i<start+length;i++){ myPoints.add(original.get(i)); } start(); } public void run(){ // copy yet again so we can delete from it List<Point> copied=new LinkedList<Point>(myPoints); int originalDistance=calculateDistance(copied); // this is our solution list List<Point> solution=new LinkedList<Point>(); int randomIdx=new Random().nextInt(copied.size()); Point prev=copied.get(randomIdx); copied.remove(randomIdx); solution.add(prev); while(copied.size()>0){ int idx=-1; int len = -1; for(int i=0;i<copied.size();i++){ Point currentPoint=copied.get(i); int dist=prev.distance(currentPoint); if(len==-1 || dist<len){ len=dist; idx=i; } } prev=copied.get(idx); copied.remove(idx); solution.add(prev); } // aaaand check our distance int finalDistance=calculateDistance(solution); if(finalDistance<originalDistance){ // yes! solution Solution aSolution=new Solution(start, length, solution, originalDistance-finalDistance); solutionFound(aSolution); } // start over regardless bots.set(id, new DivideAndConquer(id)); } // represents a solution static class Solution { int start; int length; int distDifference; List<Point> region; public Solution(int start, int length, List<Point> region, int distDifference){ this.region=new LinkedList<Point>(region); this.start=start; this.length=length; this.distDifference=distDifference; } public void apply(List<Point> points){ for(int i=0;i<length;i++){ points.set(i+start, region.get(i)); } } } // copied your Point class, sorry but it's useful... // just added public to each method for aesthetics static class Point{ int x; int y; Point(int x, int y){ this.x = x; this.y = y; } Point(Point other){ this.x = other.x; this.y = other.y; } public boolean equals(Point other){ if(this.x==other.x && this.y==other.y) return true; return false; } public int distance(Point other){ return Math.abs(x-other.x) + Math.abs(y-other.y); } } } ``` ]
[Question] [ Scoring a [Go](http://en.wikipedia.org/wiki/Go_(game)) game is a task that is not all too easy. In the past there have been several debates about how to design rules to cover all the strange corner cases that may occur. Luckily, in this task you don't have to do complicated stuff like life and death or seki detection. In this task, you have to implement a program that scores a game according to the [Tromp-Taylor rules](http://senseis.xmp.net/?TrompTaylorRules) without Komi. The scoring procedure is pretty simple: > > a point P, not colored C, is said to reach C, if there is a path of (vertically or horizontally) adjacent points of P's color from P to a point of color C. > > A player's score is the number of points of her color, plus the number of empty points that reach only her color. > > > For example, consider the following board. `X`, `O` and `-` denote black, white and uncoloured intersections: ``` - - - X - O - - - - - - X - O - - - - - - X - O - - - - - - X O - - O - X X X O - O O - - - - - X O - - O O - - - X - O - - - - - - X - O - X - - - - - - O - - - ``` Applying the scoring rule yields the following result. `x`, `o` and `-` represent uncoloured intersections that are counted as black, white and nobody's points. ``` x x x X - O o o o x x x X - O o o o x x x X - O o o o x x x X O o o O o X X X O o O O o o - - - X O - - O O - - - X - O - - - - - - X - O - X - - - - - - O - - - ``` According to the diagram, black has 23 points, white has 29 points of territory. Thus, your program should print `W+6` for this board. I hope it is clear enough this way. ## Input and output The input is a string that contains exactly *n²* of the characters `X`, `O`, `-` where *n* is not known at compile time. Your program should ignore all other characters in the input stream. Behavior is undefined if there is no integer *n* such that the amount of `XO-` characters equals *n²*. You may assume that *n* is in *[0, 255]*. The sequence of characters is to be interpreted as a Go-board of *n* rows and columns. The output is the absolute value of the difference of the total amount of points of white and black in decimal representation. If white has more points, it is prefixed by `W+`, if black has more points it is prefixed by `B+`. In the case that both players have an equal amount of points, the output is `Jigo`. Input is to be read in an implementation defined manner. Input may not be part of the source code. ## Winning conditions This is code-golf. Usual code-golf conventions apply. The submission with the least amount of characters in its source wins. Only programs that fully implement the specification may win. ## Test cases Input: ``` - - - X - O - - - - - - X - O - - - - - - X - O - - - - - - X O - - O - X X X O - O O - - - - - X O - - O O - - - X - O - - - - - - X - O - X - - - - - - O - - - ``` Output: `W+6` Input: ``` Xavier is insane -- says Oliver ``` Output: `Jigo` Inpout: ``` Code-Golf ``` Output: `Jigo` Input: ``` -XXXXXXX-XOOOOOOOXXO-OXXXOXXXOX--XOXXOOX - XOOXXOX--XOXXXOXXXO-OXXOOOOOOOX-XXXXXXX- ``` Output: `B+21` Input: ``` - - X O O O O X X - - - - - - X O O - - X X O X O X X O X X X X X X - X O - - X O O X X X - O O O X O O X X X O - - X O O O X X O O O O O O X X X O - - - - X X O X - X X X X O O O O O O O - - - X O O X X X - X X X O O O X X O - - - X O - O X O X O O O O O X X X O - - X O O - O O O X X X X X O O X O - - - X X X O - - - O X O X X X O X O - - X O O O O - - O - O O O O X X X O O - X X O - - - O - - O O X X - - X X O O X O O O - - O - O O X - - - - X O O X - X X X O O X O O X X - - - - X X X X X - X X X O X X O O X - - X X O X O O X X O O X O X O X X - - - X O O O O - X O - O X X X O X - - - - - X O - - - O O - O X O O O O X X - X X X X O - - O O - O O O X O X X - - X - X X O - - - - O - - O X X X - - - - X O O O - - ``` Output: `B+6` More testcases will come soon. ## reference implementation I have created a [reference implementation](http://goo.gl/hI5X2) written in ANSI C. This implementation reads input from the standard input and writes output to the standard output. ``` /* http://codegolf.stackexchange.com/q/6693/134 * reference implementation * by user FUZxxl */ #include <stdio.h> #include <stdlib.h> #define MAXBOARD 256 /* bit 0x01: black colour * bit 0x02: white colour * bit 0x04: there is a stone on the intersection */ enum colour { UNCOLOURED = 0x0, BLACK_REACHED = 0x1, WHITE_REACHED = 0x2, BOTH_REACHED = 0x3, HAS_STONE = 0x4, BLACK = 0x5, WHITE = 0x6 }; static enum colour board[MAXBOARD * MAXBOARD] = { 0 }; static int bsize = 0; static void read_input(void); static void fill_board(void); static void show_score(void); int main() { read_input(); fill_board(); show_score(); return EXIT_SUCCESS; } static void read_input(void) { int n = 0; int invalue; while ((invalue = getchar()) != EOF) { switch (invalue) { case '-': board[n++] = UNCOLOURED; break; case 'X': board[n++] = BLACK; break; case 'O': board[n++] = WHITE; break; } } while (bsize * bsize < n) bsize++; /* your program may exhibit undefined behaviour if this is true */ if (bsize * bsize != n) exit(EXIT_FAILURE); } static void fill_board(void) { int i,j; int changes; enum colour here, top, bottom, left, right, accum; do { changes = 0; for (i = 0; i < bsize; ++i) { for (j = 0; j < bsize; ++j) { here = board[i * bsize + j]; if (here >= BOTH_REACHED) continue; top = i == 0 ? UNCOLOURED : board[(i - 1) * bsize + j]; left = j == 0 ? UNCOLOURED : board[i * bsize + j - 1]; bottom = i == bsize-1 ? UNCOLOURED : board[(i + 1) * bsize + j]; right = j == bsize-1 ? UNCOLOURED : board[i * bsize + j + 1]; accum = here | top | bottom | left | right; accum &= ~HAS_STONE; changes |= board[i * bsize + j] != accum; board[i * bsize + j] = accum; } } } while (changes); } static void show_score(void) { int w = 0, b = 0, n; for (n = 0; n < bsize*bsize; ++n) switch (board[n] & ~HAS_STONE) { case BLACK_REACHED: ++b; break; case WHITE_REACHED: ++w; break; } if (b != w) printf("%s%i\n",b>w?"B+":"W+",abs(b-w)); else printf("Jigo\n"); } ``` [Answer] # C (~~438~~ ~~434~~ ~~413~~ ~~382~~ ~~364~~ ~~336~~ ~~322~~ ~~298~~ ~~294~~ ~~292~~ 290 characters) ``` #define I b[d*g+e a;b[65536];c;d;e;f;g;main(){for(;d=getchar()+1;f++)b[f]=d-80?d-89?d-46&& f--:5:6,g+=g*g<f;while(!c--)for(d=g;d--;)for(e=g;e--;)I]<3?a=3&(I]|!!d*I -g]|!!e*I-1]|(d<g-1)*I+g]|(e<g-1)*I+1]),c&=I]==a,I]=a:0;while(f--)c+=b[f ]%2-b[f]/2%2;printf(c?"%c+%i":"Jigo",c>0?66:87,abs(c));} ``` All newlines except the first one inserted for enhanced legibility. A commented and slightly more legible version can be found [here](https://gist.github.com/fuzxxl/746cee8fb79eaf2e1a11). This answer is essentially the reference solution but with all that useless stuff (such as types [who needs something different from `int` anyway?] and standards compliance [return value of main? please!]) ## Corrections and improvements ### 438 → 434 Dropped explicit initialization of variables after I convinced myself that they are automatically initialized to `0` according to standard. ### 434 → 413 Removed case statement: If an uncoloured intersection is reachable from both black and white, we can count it as one point for both to simplify the program. Switch of logical branches to avoid negation. ### 413 → 382 Assign `d` to `getchar()+1` to save one pair of parenthesis. Under the assumption that `b` is initialized to zeroes, reorder `case` statements, discarding all `break` statements. `(a>b?c:0)` is longer than `(a>b)*c`. `(d+1)*g+e` is longer than `d*g+e+g`. ### 382 → 364 Improved looping, no newlines in the output, shorter output routines. ### 364 → 336 Got rid of that `switch` statement. (Thanks, Howard!), track difference of points for two characters. Negate `c` for one character. four characters in the big or clause. ### 336 → 323 Replacing `&` by `%` allows removal of braces for four characters. Fused the square-root with the input loop for nine or so characters (yeah!), removed an `if` for one char. ### 323 → 298 Introduced the macro `H` to replace the often occuring and bulky `b[d*g+e]` construct. ### 298 → 294 Change `a&=~4` to `a&=3` as we only every observe the lowest three bytes of `a`. Also changed to loop body from `((a=I])<3)?a|=...` to `I]<3?a=I]|...` which is two characters shorter. Also, introduce `h` instead of reusing `c`, which is one character shorter. ### 294 → 292 Eliminate `h` variable. If we test `c` with `!c--` instead of `!c++`, `c` equals 0 at the end of the flood-fill loop and can thus be used for the purpose `h` was used before (i.e. score keeping). ### 292 → 290 Replace the construct `d-46?f--:0` with `d-46&&f--` which is shorter by a character and combine the two assignments to `a` in the inner loop. [Answer] ## J (~~140~~ ~~136~~ ~~131~~ ~~129~~ ~~119~~ ~~117~~ 116 characters) After ramping up my J skills, I can finally provide a submission in J. It's a little bit long though. ``` exit echo>(*{'Jigo';('B+',":);'W+',":@|)+/,-/1 2=/(]OR(0=[)*[:OR((,.|.)0,i:1)|.!.0])^:_~($~,~@%:@#)3-.~'-XO'i:1!:1]3 ``` The algorithm implemented by this submission is very similar to the reference implementation but different in the way occupied fields are handled. Here is the solution split up into more parts for easier understandability. The golfed solution is slightly different from that, but the difference isn't very large. ``` input =. 3 -.~ '-XO' i: 1!:1 ] 3 board =. ($~ ,~@%:@#) input NB. shift up, down, left, right rotm =. (,. |.) 0 , i: 1 fill =. ] OR (0 = [) * [: OR rotm |.!.0 ] filledboard =. fill^:_~ board score =. +/ , -/ 1 2 =/ filledboard echo > (* { 'Jigo' ; ('B+' , ":) ; ('W+', ":@|)) score exit 0 ``` [Answer] ### GolfScript, 190 characters ``` {"XO-"?)},:v,.),\{\.*=}+,~:s.*:`0\,{s%!\2*+}/:r;88{0v@{=\2*+}+/}:%~79%1${{:<.r|r^2*|<2/r|r^|<2s?:h/|<h*|1$|1$^2`?(&}`*}:a~@@a\;.2$|2${^2*)2base{+}*}:m~@2$|@m-.{"BW"1/1$0>="+"@abs}{;"Jigo"}if ``` The script became much longer than I thought in the beginning. Pass any input on STDIN and the output will then be printed when the program terminates. [Answer] ## GolfScript (105 bytes) ``` {'-XO'?}/]-1-.{2*3%}%{.,:N),{.*N=}?/{{[{.2$+1={+.}*}*]}%zip}N*[]*.1--,\}2*-.{.0>'W+B+'2/=\abs}{;'Jigo'}if ``` [Online demo](http://golfscript.apphb.com/?c=OyctIC0gLSBYIC0gTyAtIC0gLQotIC0gLSBYIC0gTyAtIC0gLQotIC0gLSBYIC0gTyAtIC0gLQotIC0gLSBYIE8gLSAtIE8gLQpYIFggWCBPIC0gTyBPIC0gLQotIC0gLSBYIE8gLSAtIE8gTwotIC0gLSBYIC0gTyAtIC0gLQotIC0gLSBYIC0gTyAtIFggLQotIC0gLSAtIC0gTyAtIC0gLScKCnsnLVhPJz99L10tMS0uezIqMyV9JXsuLDpOKSx7LipOPX0%2FL3t7W3suMiQrMT17Ky59Kn0qXX0lemlwfU4qW10qLjEtLSxcfTIqLS57LjA%2BJ1crQisnMi89XGFic317OydKaWdvJ31pZg%3D%3D). Flood-fill adapted from [this earlier answer of mine](https://codegolf.stackexchange.com/a/40204/194). The solution flood-fills one copy of the original board with X, and another with O. Thus empty cells which are reachable by both colours are scored for both, but cancel in the subtraction. [Answer] # Ruby (314) could be made shorter with some more time: ``` q={?-=>0,?X=>5,?O=>6};b=[];$<.chars{|c|(t=q[c])&&b<<t} z=Math.sqrt b.size loop{c=b.each_with_index.map{|h,i| next h if h>2 x=i%z y=i/z u=y<1?0:b[i-z] l=x<1?0:b[i-1] d=y>z-2?0:b[i+z] r=x>z-2?0:b[i+1] ~4&(h|u|d|l|r)} break if c==b b=c} b.map!{|h|h&~4} s=b.count(1)-b.count(2) puts s==0?"Jigo":s>0?"B+#{s}":"W+#{-s}" ``` ]