title: Print a letter Fibonacci

text:
# Question
Title: Print a letter Fibonacci
Given *N* (2 \<= *N*), print *N* lines of the letter Fibonacci series like this (i.e. *N* = 5) First, start with `a` and `b`:

```
a
b

```

Next, add the two lines.

```
a
b
ab

```

Keep adding the last two lines.

```
a
b
ab
bab

```

Keep going...

```
a
b
ab
bab
abbab

```

And we're done.

Remember, this is , so the code with the fewest bytes wins.

# Answer
# Python 2, 41 bytes

*Saved 3 bytes thanks to @xnor*

```
a,b="ab";exec"print a;a,b=b,a+b;"*input()

```

Test on Ideone

Simply follows the recursive definition.
> 11 votes

# Answer
## Haskell, ~~29~~ ~~35~~ 32 bytes

```
a%b=a:b%(a++b)
(`take`("a"%"b"))

```

Simple recursion.

For reference: the old version (an adaption of this answer), concatenated the strings in the wrong order, so I had to add a `flip(...)` which made it too long (35 bytes).

```
f="a":scanl(flip(++))"b"f
(`take`f)

```
> 8 votes

# Answer
# 05AB1E, ~~12~~ 11 bytes

Thanks to *Emigna* for saving a byte!

```
'a='b¹GD=Š«

```

Uses the **CP-1252** encoding. Try it online!
> 6 votes

# Answer
# JavaScript (ES6), ~~43~~ 42 bytes

*Saved a byte thanks to @Arnauld*

```
f=(n,a="a",b="b")=>n&&f(n-!alert(a),b,a+b)

```
> 5 votes

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

```
”a”bṄ;¥@¡f

```

Try it online!

### How it works

```
”a”bṄ;¥@¡f  Main link. Argument: n

”a          Set the return value to 'a'.
  ”b    ¡   Call the link to the left n times, with left argument 'b' and right
            argument 'a'. After each call, the right argument is replaced with the
            left one, and the left argument with the return value. The final
            return value is yielded by the quicklink.
      ¥       Combine the two atoms to the left into a dyadic chain.
    Ṅ           Print the left argument of the chain, followed by a linefeed.
     ;          Concatenate the left and right argument of the chain.
       @      Call the chain with reversed argument order.
         f  Filter the result by presence in n. This yields an empty string
            and thus suppresses the implicit output.

```
> 5 votes

# Answer
# Java 7, 69 bytes

```
String c(int n,String a,String b){return n--<1?"":a+"\n"+c(n,b,a+b);}

```

### ungolfed

```
 class fibb {

public static void main(String[] args) {
    System.out.println( c( 7, "a" , "b" ) );

}
static String c(int n,String a,String b) {

    return n-- < 1  ? "" : a + "\n" + c(n,b,a + b);

}
}

```
> 5 votes

# Answer
# Emacs, ~~26~~, 25-ish keystrokes

### Program

`#n` to be read as key with digit(s) *n*:

`A``RET``B``RET``F3``UP``UP``C-SPACE``C-E``M-W``DOWN``DOWN``C-Y` `UP``C-A``C-SPACE``C-E``M-W``DOWN``C-E``C-Y``RET``F4``C-#(n-2)``F4`

## Explanation

```
command(s)               explanation                      buffer reads (| = cursor aka point)
-----------------------------------------------------------------------------------------------
A<RET> B<RET>            input starting points            "a\nb\n|"
<F3>                     start new macro                  "a\nb\n|"
<UP><UP>                 move point two lines up          "|a\nb\n"
C-<SPACE> C-E M-W        copy line at point               "a|\nb\n"
<DOWN><DOWN>             move point two lines down        "a\nb\n|"
C-Y                      yank (paste)                     "a\nb\na|"
<UP>                     move point one line up           "a\nb|\na"
C-A C-<SPACE> C-E M-W    copy line at point               "a\nb|\na"
<DOWN>                   move point one line down         "a\nb|\na|"
C-E C-Y <RET>            yank (paste) and add new line    "a\nb|\nab\n|"
<F4>                     stop macro recording             "a\nb|\nab\n|"
C-#(n-3) <F4>            apply macro n-3 times            "a\nb|\nab\nbab\nabbab\n|"

```

## With n=10

```
a
b
ab
bab
abbab
bababbab
abbabbababbab
bababbababbabbababbab
abbabbababbabbababbababbabbababbab
bababbababbabbababbababbabbababbabbababbababbabbababbab

```
> 5 votes

# Answer
# CJam, ~~19~~ 17 bytes

```
'a'b{_@_n\+}ri*;;

```

explanation

```
"a": Push character literal "a" onto the stack.
"b": Push character literal "b" onto the stack.
{_@_p\+}
    {: Block begin.
    _: duplicate top element on the stack
    @: rotate top 3 elements on the stack
    _: duplicate top element on the stack
    n: print string representation
    \: swap top 2 elements on the stack
    +: add, concat
    }: Block end.
r: read token (whitespace-separated)
i: convert to integer
*: multiply, join, repeat, fold (reduce)
;: pop and discard
;: pop and discard

```
> 4 votes

# Answer
# , 18 bytes

```
ia
bkÀñyjGpgJkñdj

```

Try it online!

Or, the more readable version:

```
ia
b<esc>kÀñyjGpgJkñdj

```

Explanation:

```
ia
b<esc>          " Insert the starting text and escape back to normal mode
k               " Move up a line
 Àñ       ñ     " Arg1 times:
   yj           "   Yank the current line and the line below
     G          "   Move to the end of the buffer
      p         "   Paste what we just yanked
       gJ       "   Join these two lines
         k      "   Move up one line
           dj   " Delete the last two lines

```
> 3 votes

# Answer
# Python 2, 55 bytes

```
def f(n):m='a','b';exec'print m[-2];m+=m[-2]+m[-1],;'*n

```
> 3 votes

# Answer
# MATL, 14 bytes

```
97c98ci2-:"yyh

```

Try it online!

```
97c     % Push 'a'
98c     % Push 'b'
i2-     % Input number. Subtract 2
:"      % Repeat that many times
  yy    %   Duplicate the top two elements
  h     %   Concatenate them

```
> 3 votes

# Answer
## Retina, 33 bytes

```
.+
$*
^11
a¶b
+`¶(.+?)1
¶$1¶$%`$1

```

Try it online!

Saved 10 (!) bytes thanks to @MartinEnder!

### Explanation

Converts the input to unary, subtracts `2` and adds the `a` and the `b`, then recursively replaces the remaining `1`s with the concatenation of the two previous strings.
> 3 votes

# Answer
## Batch, ~~102~~ 93 bytes

```
@set a=a
@set b=b
@for /l %%i in (2,1,%1)do @call:l
:l
@echo %a%
@set a=%b%&set b=%a%%b%

```

Fortunately variables are expanded for every line before assignments take effect, so I can set both `a` and `b` using their old values without needing a temporary. Edit: Saved 9 bytes thanks to @nephi12.
> 2 votes

# Answer
# Perl, 45 +1 = 46 bytes

+1 byte for -n flag

```
$a=a,$b=b;say($a),($a,$b)=($b,$a.$b)for 1..$_

```

Slight improvement over the existing 49-byte solution, but developed separately. The parentheses for `say($a)` are necessary because otherwise, it interprets `$a,($a,$b)=($b,$a.$b)` as the argument of `say` which outputs more junk than we need.

# Perl, 42 bytes

```
$b=<>;$_=a;say,y/ab/bc/,s/c/ab/g while$b--

```

A separate approach from the above solution:

```
$b=<>;                                       #Read the input into $b
      $_=a;                                  #Create the initial string 'a' stored in $_
           say                               #Print $_ on a new line
               y/ab/bc/                      #Perform a transliteration on $_ as follows:
                                   #Replace 'a' with 'b' and 'b' with 'c' everywhere in $_
                        s/c/ab/g             #Perform a replacement on $_ as follows:
                                   #Replace 'c' with 'ab' everywhere in $_
              ,        ,         while$b--   #Perform the operations separated by commas
                                   #iteratively as long as $b-- remains truthy

```

I'm not yet convinced I can't combine the transliteration and replacement into a single, shorter operation. If I find one, I'll post it.
> 2 votes

# Answer
# Stack my Golf, 63 bytes

Get my language here: https://github.com/cheertarts/Stack-My-Golf.

```
($1=(_(a))($2=(_(b))($2-f:1-f,)?)?)f\($1=(f)($1-p(\n),:f,)?)p\p

```

There is probably a shorter way but this is the most obvious.
> 2 votes

# Answer
# SOML, 8 bytes

```
 a b.{;t⁴+

```

explanation:

```
 a b.{;t⁴+                                        stack on 1st cycle
 a              push "a"                               ["a"]
   b            push "b"                               ["a","b"]
    .{          repeat input times                     ["a","b"]
      ;         swap the two top things on the stack   ["b","a"]
       t        output the top thing on the stack      ["b","a"]
        ⁴       copy the 2nd from top thing from stack ["b","a","b"]
         +      join them together                     ["b","ab"]

```

This language is still in development and I did add a couple new functions while writing this.

Also, 1st post on PPCG!
> 2 votes

# Answer
# Perl, ~~36~~ 35 bytes

Includes +3 for `-n`

Give count on STDIN

```
perl -M5.010 fibo.pl <<< 5

```

`fibo.pl`

```
#!/usr/bin/perl -n
$_=$'.s/1//.$_,say$`for(a1.b)x$_

```
> 2 votes

# Answer
# Swift 3, 76 Bytes

```
func f(_ n:Int,_ x:String="a",_ y:String="b"){if n>1{print(x);f(n-1,y,x+y)}}

```
> 1 votes

# Answer
## Perl, 48 bytes

**47 bytes code + 1 for `-n`.**

Simple approach. Try using an array slice originally `$a[@a]="@a[-2,-1]"` but that necessitates `$"=""` or similar :(. Save 1 byte thanks to @Dada!

```
@;=(a,b);$;[@;]=$;[-2].$;[-1]for 3..$_;say for@

```

### Usage

```
perl -nE '@;=(a,b);$;[@;]=$;[-2].$;[-1]for 3..$_;say for@' <<< 5
a
b
ab
bab
abbab

```
> 1 votes

# Answer
# PHP, ~~63~~ 62 bytes

Recursive version:

```
function f($n,$a=a,$b=b){return$n--?"$a
".f($n,$b,$a.$b):'';}

```
> 1 votes

# Answer
# **C**, 156 bytes (without indent)

```
void f(int n)
{
    char u[999]="a",v[999]="b",*a=u,*b=a+1,*c=v,*d=c+1,*e,i;
    for(i=0;i<n;++i)
    {
        printf("%s\n",a);
        for(e=c;*b++=*e++;);
        e=a;a=c;c=e;e=b+1;b=d;d=e;
    }
}

```

Two buffers (u & v) store the last two lines. The newest line (tracked with two pointers: start=c, end=d) is appended to the oldest one (start=a, end=b). Swap (a,b) and (c,d), and loop. Pay attention to buffer size before requesting too much lines. Not so short (as expected of a low-level language), but was fun to code.
> 1 votes

# Answer
# 05AB1E, 15 bytes

```
'a'bVUFX,XYUYJV

```
> 1 votes

# Answer
# Python 2, 56 bytes

```
a,b="ab"
for i in range(input()):
	print(a+b)
	a,b=b,a+b

```

Try it online!

# Python 2, 44 bytes

```
a,b="ab"
exec"print(a+b);a,b=b,a+b;"*input()

```

Try it online!
> 1 votes

# Answer
# Pyth, 17 bytes

```
J,\a\bjP.U=+Js>2J

```

A program that takes input of an integer and prints the result.

Try it online!

**How it works**

```
J,\a\bjP.U=+Js>2J  Program. Input: Q
 ,\a\b             Yield the two element list ['a', 'b']
J                  Assign to J
        .U         Reduce over [0, 1, 2, 3, ..., Q] (implicit input):
          =J+        J = J +
              >2J     the last two elements of J
             s        concatenated
       P           All of that except the last element
      j            Join on newlines
                   Implicitly print

```
> 0 votes

# Answer
# Pyth - ~~16~~ 15 bytes

```
A"ab" m=H+
~GHH

```

Try it online here.
> 0 votes

# Answer
# APL, 30 bytes.

`⎕IO` must be `1`.

```
{⎕←⍵}¨{⍵∊⍳2:⍵⌷'ab'⋄∊∇¨⍵-⌽⍳2}¨⍳

```
> 0 votes

# Answer
# Mathematica, 49 bytes

```
f@1="a";f@2="b";f@n_:=f[n-2]<>f[n-1];g=f~Array~#&

```

Defines a function `g` taking the single numerical input; returns a list of strings. Straightforward recursive implementation, using the string-joining operator `<>`.

# Mathematica, 56 bytes

```
NestList[#~StringReplace~{"a"->"b","b"->"ab"}&,"a",#-1]&

```

Unnamed function, same input/output format as above. This solution uses an alternate way to generate the strings: each string in the list is the result of simultaneously replacing, in the previous string, all occurrences of "a" with "b" and all occurrences of "b" with "ab".
> 0 votes

# Answer
# PHP, ~~61~~ 57 bytes

```
<?=$c=a;for($b=b;--$argv[1];$b=$c.$b,$c=$a)echo"
",$a=$b;

```

~~come php 7.1 you can save 3 bytes by changing to:~~ an "old" version that I wish was short:

```
<?=$a=a;for($b=b;--$argv[1];[$a,$b]=[$b,$a.$b])echo"
$b";

```

If a trailing new line is acceptable then:

```
for($b=b;$argv[1]--;$a=$b,$b=$c.$b)echo$c=$a?:a,"
";

```

is only 52 bytes.

edit: 4 bytes saved (on both usable versions) thanks to Titus.
> 0 votes

# Answer
# Groovy, 79 Bytes

```
{println("a\nb");x=['a','b'];(it-2).times{println(y=x.sum());x[0]=x[1];x[1]=y}}

```
> 0 votes

# Answer
# C++11, ~~89~~ 98 bytes

+7 bytes for *all* lines, not only the last one. +2 bytes more for `N` being the number of lines printed, not some 0-based stuff.

```
#include<string>
using S=std::string;S f(int n,S a="a",S b="b"){return n-1?a+"\n"+f(n-1,b,a+b):a;}

```

Usage:

```
f(5)

```
> 0 votes

# Answer
# PHP, 53 bytes

```
for($a=b,$b=a;$argv[1]--;$a=($_=$b).$b=$a)echo$b.'
';

```
> 0 votes

# Answer
# Ruby (1.9+) 46 bytes

```
a,b=?a,?b;ARGV[0].to_i.times{puts a;a,b=b,a+b}

```
> 0 votes

# Answer
# Pyth - 14 bytes

(yeah, another pyth answer)

```
A<G2VQG=H+~GHH

```

Try it online

**Explanation**

```
A<G2              - take "ab" from the var G, dump "a" into G and "b" into H.
    VQ            - for N in range(Q)
      G           - print G
          ~GH     - like =GH but returns the previous G
         +   H    - concatenate the old G with the current H
       =H         - put that value back into H

```
> 0 votes

# Answer
# Actually, 16 bytes

There might be a shorter way to duplicate the top two elements of the stack in Actually, but I'm not sure what that way is. Golfing suggestions welcome. Try it online!

```
'a'b,¬`2╟2αio`na

```

**Ungolfing**

```
'a'b     Push "a" then "b" to the stack.
,        Explicitly take input n.
¬        Push n-2.
`...`n   Run the following function n-2 times.
  2╟2α     Push a list that repeats the top two elements of the stack twice.
  i        Flatten that list to the stack. Stack: b, a, b, a, prev_iterations
  o        Append b to the end of a. Stack: ab, b, a, prev_iterations
a        Reverse the stack so that the strings will print in the correct order.
         Implicit print all of the elements in the stack.

```

**A different approach**

This is also 16 bytes. Try it online!

```
'a'b,¬`│ok╔Ri`na

```

**Ungolfing**

The main difference is the function in the middle, so I'll only ungolf that here.

```
`...`n   Run the following function n-2 times.
  │        Duplicate the stack.
  o        Append the last item to the end of the second-to-last item.
  k╔       Uniquify the stack by wrapping the stack in a list and then calling uniquify().
  Ri       Reverse that list before returning everything to the stack
            so that the last items are at TOS again.

```
> 0 votes

# Answer
# Java 8 40 bytes

Same answer as @Numberknot only written as a lambda in Java 8 which makes it smaller.

```
c=(n,a,b)->n--<1?"":a+"\n"+c.f(n,b,a+b);

```

Ungolfed version:

```
interface Function
{
    String f(int n, String a, String b);
}

public class Main
{
    static Function c; //c needs to be a member or static variable in order
                       //to reference it recursively inside the lambda

    public static void main(String[] args)
    {
        c=(n,a,b)->n--<1?"":a+"\n"+c.f(n,b,a+b);
    }
}

```
> 0 votes

# Answer
# R, 82 bytes

This can surely be golfed.

```
x=c("b","a");for(i in 2:scan()-2)x=c(paste0(x[2],x[1]),x);cat(rev(x[-1]),sep="\n")

```
> 0 votes

# Answer
# C#, 142 Bytes

*Edit: only had it printing the last line out... V2:*

Golfed:

```
string L(int n){var r=new List<string>(){"a","b"};int i=3;while(i<=n){r.Add(string.Concat(r[i-3],r[i-2]));i++;}return string.Join("\r\n", r);}

```

Ungolfed:

```
public string L(int n)
{
  var r = new List<string>() { "a", "b" };

  int i = 3;

  while (i <= n)
  {
    r.Add(string.Concat(r[i-3], r[i-2]));
    i++;
  }

  return string.Join("\r\n", r);
}

```

Test:

```
var printALetterFibonacci = new PrintALetterFibonacci();
Console.WriteLine(printALetterFibonacci.L(5));

a
b
ab
bab
abbab

var printALetterFibonacci = new PrintALetterFibonacci();
Console.WriteLine(printALetterFibonacci.L(7));

a
b
ab
bab
abbab
bababbab
abbabbababbab

```
> 0 votes

# Answer
# GNU sed, 43 Bytes

Includes +2 for `-rn`.

```
s/1/a\nb\n/
:
P
s/(.*)\n(.*\n)./\2\1\2/
t

```

Takes input in unary (see this consensus).

Try it Online!

**Explanation:**

```
s/1/a\nb\n/              # prepend an 'a' and a 'b' on their own lines and remove a '1'
:                        # nameless label
P                        # print everything before the first newline
s/(.*)\n(.*\n)./\2\1\2/  # replace the first two lines and the next character
                         # (one of the '1's) with the second line then the first line
                         # concatenated with the second
                         # E.g.
                         #     a           b
                         #     b      ->   ab
                         #     11111       1111
t                        # loop to the label if there was a '1' left (i.e. there was
                         # a substitution)

```
> 0 votes

# Answer
# Powershell 1.0+, 41 51 :( Bytes

```
$x,$y='a','b';0..(read-host)|%{$x;$x,$y=$y,($x+$y)}

```

4 \*nix goto https://github.com/PowerShell/PowerShell

Corrected for user input :)
> 0 votes

# Answer
# Thunno `d`, \\$17\log\_{256}(96)\approx\\$ 13.99 bytes

```
'aX'bYR{xDZKyAx+Y

```

Attempt This Online!
> 0 votes

# Answer
# Japt `-R`, 12 bytes

```
@Zä+ Ì}ha¬pb

```

Try it
> 0 votes

# Answer
# Thunno 2 `--`, 11 bytes

```
'aß'bß${Ɓ+ß

```

Try it online!

Given `n`, prints the first `n` terms (as the challenge asks).

## Thunno 2, 7 bytes

```
`abdµµ+

```

Attempt This Online!

Prints the infinite sequence (probably not allowed).

#### Explanation

```
'aß'bß${Ɓ+ß  # Implicit input
'aß         '# Print "a" without popping
   'bß      '# Print "b" without popping
      ${     # Repeat (input - 2) times:
        Ɓ    #  Without popping,
         +   #  concatenate the last two items
          ß  #  Print without popping

```

```
`abdµµ+  # Full program
`abd     # Starting from ["a", "b"],
    µµ   # construct an infinite sequence
      +  # by concatenating the last two terms
         # Implicit output

```
> 0 votes

# Answer
# Javascript (ES6), 35 bytes

```
f=v=>v&&v-1?f(v-2)+f(v-1):v?'b':'a'

```
> -1 votes

---
Tags: code-golf, string, fibonacci
---


# Question
Title: Return the integers with square digit-sums
## Introduction and Credit

We all know and love our awesome rules to test whether a number is divisble by 11 or 3, which is just some clever sum over the digits of the number. Now this challenge takes this to a new level, by requiring you to compute the sum of the digits and then checking whether the result is a perfect integer square, neither of which operations usually can be done very short. As this property is also very hard to see when looking at a number, we want this to be done for entire lists of numbers so we can save human work. So this is *your* challenge now!

This was an assignment at my university functional programming course. This assignment is now closed and has been discussed in class and I have my professor's permission to post it here (I asked explicitely).

## Specification

### Input

Your input is a list of non-negative integers, in any standard I/O format.
You may choose the list format as your language needs it

### Output

The output is a list of integers, in any standard I/O format.

### What to do?

Filter out every integer from the input list for which the sum of the digits *is not* a a square (of an integer).
The order of the elements may not be changed, e.g. if you get `[1,5,9]` you may *not* return `[9,1]`

### Potential corner cases

0 *is* a non-negative integer and thus a valid input and 0 is also a valid integer root, e.g. 0 counts as an integer square.
The empty list is a valid input and output as well.

### Who wins?

This is code-golf so the shortest answer in bytes wins!
Standard rules apply of course.

## Test Cases

```
[1,4,9,16,25,1111] -> [1,4,9,1111]
[1431,2,0,22,999999999] -> [1431,0,22,999999999]
[22228,4,113125,22345] -> [22228,4,22345]
[] -> []
[421337,99,123456789,1133557799] -> []

```

### Step-by-Step Example

```
Example input: [1337,4444]
Handling first number:
Sum of the digits of 1337: 1+3+3+7=14
14 is not an integer square, thus will be dropped!
Handling second number:
Sum of the digits of 4444: 4+4+4+4=16
16 is an integer square because 4*4=16, can get into the output list!
Example output: [4444]

```

# Answer
## Pyke, 6 bytes

```
#s,DBq

```

Try it here!

```
#      - Filter list on truthiness:
 s     -    digital_root(^)
  ,    -   sqrt(^)
    Bq -  int(^) == ^

```
> 10 votes

# Answer
# Mathematica, ~~39~~ 36 bytes

An anonymous function:

```
Select[AtomQ@√Tr@IntegerDigits@#&]

```

LLlAMnYP saved a byte. Thank you!

Martin Ender saved three more by replacing `IntegerQ` with `AtomQ`. Clever! (The result of  will be exact, so it returns a compound expression like `Sqrt[5]` if its argument isn’t a square.)
> 5 votes

# Answer
# Jelly, ~~8~~ 7 bytes

1 byte thanks to @Sp3000.

```
DSÆ²ðÐf

```

Test suite.

### Explanation

```
DSÆ²ðÐf  Main monadic chain. Argument: z

     Ðf  Filter for truthiness:
D            convert to base 10
 S           sum
  Æ²         is perfect square

```
> 4 votes

# Answer
# Brachylog v2, 8 bytes

```
{ẹ+√ℤ&}ˢ

```

Try it online!

## Explanation

```
{ẹ+√ℤ&}ˢ
{     }ˢ  Map the following operation over {the input}, discarding elements that error:
 ẹ         Split into a list of digits
  +        Sum that list
   √       Take its square root
    ℤ      Assert that the result is an integer
     &     Return to the original value

```

The `&` means that the elements output are the same as those in the input list, but the  will error out if the block's input isn't a square number, so we get the input list with elements with non-square digit sums discarded.

Note that there might at first seem to be a floating point inaccuracy issue here (some very large non-square integers have integer square roots due to rounding). However, Brachylog supports bignum arithmetic, and actually has this behaviour factored into its implementation of : a number which is a perfect square will have its square root reported as an integer, whereas a number which is not a perfect square (but close enough that its square root is integral) will have its square root reported as a float with an integral value. Conveniently,  only permits the former sort of return value, giving an assertion failure for the latter.
> 4 votes

# Answer
# Pyth, 10 bytes

```
fsI@sjT;2Q

```

Test suite.

### Explanation

```
fsI@sjT;2Q

f        Q  Filter for the following in Q(input):
     jT;        convert to base 10
    s           sum
   @    2       square-root
 sI             is integer (is invariant under flooring)

```
> 3 votes

# Answer
# CJam, 14 bytes

Thanks to @FryAmTheEggman for saving one byte!

```
{{Ab:+mq_i=},}

```

Try it online!

This is an unnamed block that expects the input list on the stack and leaves the filtered list on it.

## Explanation

```
{    e# start a new block
 Ab  e# convert to base 10 -> split number into digits
 :+  e# sum th digits
 mq  e# get the square root
 _   e# duplicate the result
 i   e# convert to integer
 =   e# check if the converted square root and the original one are equal
}    e# end block
,    e# filter the input list

```
> 3 votes

# Answer
# PowerShell, ~~64~~ 54 bytes

```
$args|?{!([math]::Sqrt(([char[]]"$_"-join'+'|iex))%1)}

```

Try it online!

*-10 bytes thanks to mazzy*

Takes input as command-line arguments (see examples below), which gets processed in PowerShell into the array `$args`. We pipe that to `?` an alias for `Where-Object` (functions similar to `filter`) in order to select our output. Our selection is based on the .NET call `[math]::Sqrt()` of the digit-sum of the number is an integer with `!(...%1)`. Integers will result in 0, which when `not`ed becomes `True` while non-integer roots become `False`.

As mentioned elsewhere "returning" an empty array is meaningless, as it's converted to `$null` as soon as it leaves scope, so the output for an empty input is nothing.

### Examples

```
PS C:\Tools\Scripts\golfing> .\return-integers-with-square-digit-sums.ps1 1 4 9 16 25 1111
1
4
9
1111

PS C:\Tools\Scripts\golfing> .\return-integers-with-square-digit-sums.ps1 1431 2 0 22 999999999
1431
0
22
999999999

PS C:\Tools\Scripts\golfing> .\return-integers-with-square-digit-sums.ps1 22228 4 113125 22345
22228
4
22345

PS C:\Tools\Scripts\golfing> .\return-integers-with-square-digit-sums.ps1

PS C:\Tools\Scripts\golfing> .\return-integers-with-square-digit-sums.ps1 1337 4444
4444

```
> 3 votes

# Answer
## 05AB1E, ~~19~~ 10 bytes

```
vySOtDï->—

```

**Explanation**

```
vy                     # for each int in list
  SO                   # digit sum
    tDï-               # difference between sqrt() and int(sqrt())
        >              # increase by 1 giving 1 (true) when equal
         —             # print current int in list if truthy

```

Try it online

Edit: Saved 9 bytes thanks to @Adnan
> 3 votes

# Answer
# Haskell - 70 60 59 bytes

```
f=filter(\x->elem(sum.map(read.pure).show$x)$map(^2)[0..x])

```

Usage:

```
> f [0..100]
[0,1,4,9,10,13,18,22,27,31,36,40,45,54,63,72,79,81,88,90,97,100]

```

Quite straightforward; computes the sum of digits and checks if floor(sqrt(y))^2 == y

Edit: Stole the idea of checking list of squares from C. Quilley
> 3 votes

# Answer
# , ~~57~~ 55 bytes

Use `Filter` on the vector. Assumes 32 bit integers so 10 digits max.

Corner cases: returns `NULL` for the empty vector and `numeric(0)` for a vector with no valid numbers. These both have length zero so should be acceptable.

-2 thanks to @Giuseppe

```
Filter(function(n)!sum(n%/%10^(0:10)%%10)^.5%%1,scan())

```

Try it online!
> 3 votes

# Answer
# Javascript 66 bytes

```
a=>a.filter(b=>(e=Math.sqrt((b+"").split``.reduce((c,d)=>c-+-d)))==(e|0))

```

Thanks for SergioFC for saving 7 bytes
> 2 votes

# Answer
# J, ~~33~~ 27 bytes

6 bytes thanks to @miles.

```
#~[:(=<.)@%:+/"1@(10&#.inv)

```

In online interpreters, `inv` is not instored. Change that to `^:_1` instead.

### Usage

```
>> f =: #~[:(=<.)@%:+/"1@(10&#.inv)
>> f 1 4 9 16 25 1111 0
<< 1 4 9 1111 0

```

Where `>>` is STDIN and `<<` is STDOUT.

### Slightly ungolfed

```
to_base_10 =: 10&#.^:_1
sum        =: +/"1
sqrt       =: %:
floor      =: <.
itself     =: ]
equals     =: =
of         =: @
is_integer =: equals floor
test       =: is_integer of sqrt
copies_of  =: #
f =: copies_of~ [: test (sum of to_base_10)

```

## Previous 33-byte version

```
(]=*:@<.@%:)@(+/"1@(10#.^:_1]))#]

```

### Usage

```
>> f =: (]=*:@<.@%:)@(+/"1@(10#.^:_1]))#]
>> f 1 4 9 16 25 1111 0
<< 1 4 9 1111 0

```

Where `>>` is STDIN and `<<` is STDOUT.

### Slightly ungolfed

```
to_base_10 =: 10#.^:_1]
sum        =: +/"1
sqrt       =: %:
floor      =: <.
square     =: *:
itself     =: ]
equals     =: =
of         =: @
test       =: itself equals square of floor of sqrt
copies_of  =: #
f =: (test of (sum of to_base_10)) copies_of itself

```
> 2 votes

# Answer
# Python 2, 76 bytes

```
lambda l:filter(lambda n:eval(("sum(map(int,`n`))**.5==int("*2)[:-6]+")"),l)

```

Try it here!

Some abuse of eval to check for a square number, rest is pretty unspectacular.
The eval statement evaluates to `sum(map(int,`n`))**.5==int(sum(map(int,`n`))**.5)`
> 2 votes

# Answer
# Oracle SQL 11.2, 213 bytes

```
WITH v AS(SELECT a,SQRT(XMLQUERY(REGEXP_REPLACE(a,'(\d)','+\1')RETURNING CONTENT).GETNUMBERVAL())s FROM(SELECT TRIM(COLUMN_VALUE)a FROM XMLTABLE(('"'||REPLACE(:1,',','","')||'"'))))SELECT a FROM v WHERE s=CEIL(s);

```

Un-golfed

```
WITH v AS
(
  SELECT a,SQRT(XMLQUERY(
                   REGEXP_REPLACE(a,'(\d)','+\1')  -- Add a + in front of each digit
                   RETURNING CONTENT
               ).GETNUMBERVAL())s                  -- Evaluate the expression generated by the added +
  FROM
  (SELECT TRIM(COLUMN_VALUE)a FROM XMLTABLE(('"'||REPLACE(:1,',','","')||'"'))) -- Split string on ','
)
SELECT a FROM v WHERE s=CEIL(s) -- Is a square if square has no decimal part

```
> 2 votes

# Answer
# Brachylog, 26 bytes

```
:1f.
e.(:ef+~^[X:2]h>0;.0)

```

Example:

```
?- run_from_file('code.brachylog',[1431:2:0:22:999999999],Z).
Z = [1431, 0, 22, 999999999]

```

### Explanation

This is a situation where something works a bit too well... the `~^[X:2]` part is true for both positive and negative `X`, so to avoid duplicates I have to specify that `X > 0`.

The `;.0` part is here due to a bug (enumerate doesn't work on the integer 0).

* Main predicate

```
:1f.                Find all values of Input which satisfy predicate 1

```
* Predicate 1

```
e.                  Unify output with an element of the input
(
  :ef               Find all elements of Output (i.e. all digits)
     +              Sum the digits
      ~^[X:2]       True if that sum is the result of X², whatever X is
             h>0    Impose that X > 0
;                   OR
  .0                True if Output is 0
)

```
> 2 votes

# Answer
# Python 2, 53 bytes

```
lambda x:[n for n in x if sum(map(int,`n`))**.5%1==0]

```

Test it on Ideone.
> 2 votes

# Answer
# Perl 5, 42 bytes

41, plus 1 for `-pe` instead of `-e`

```
my$s;map$s+=$_,/./g;$_ x=sqrt$s==~~sqrt$s

```

Explanation:

* `-p` gets each input integer on a new line and assigns `$_` to that string.
* `my$s` initializes the variable `$s` to nothing, anew for each input integer.
* `map$s+=$_,/./g` grabs each numeric character and numerically adds it to `$s`. (The newline becomes 0 when numified.)
* `sqrt$s==~~sqrt$s` tests whether `$s` has a nonintegral square root, and `$_ x=` makes `$_` into itself or the empty string depending on that test.
* `-p` prints `$_`

Thanks to Brad Gilbert b2gills for saving three bytes.

Also 41 plus 1:

```
my$s;s/./$s+=$&/ger;$_ x=sqrt$s==~~sqrt$s

```
* `s/./$s+=$&/ger` adds each numeric character to `$s` (and the newline is 0 as above)
> 2 votes

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

```
a=>a.filter(b=>eval([...b+""].join`+`)**.5%1==0)

```

Try it online!

# Explanation

```
a =>                                  // lambda function taking one argument
    a.filter(                         // filter the list
        eval(                         // begin eval
            [...b+""]                 // convert number to array of digits
                .join`+`              // join them with + sign
            )                         // close eval. we achieved sum of all digits of number
        **.5                          // square root of number
        %1==0                         // check for perfect square
    )                                 // end filter and return value

```
> 2 votes

# Answer
# MATL, ~~16~~ ~~14~~ 13 bytes

```
"@tV!UsX^1\?x

```

**Try it Online!**

**Explanation**

```
        % Implicitly grab input
"       % For each number in the input
  @t    % Get this element and duplicate
  V     % Convert to it's string representation
  !     % Transpose the string so each digit is on it's own row
  U     % Convert each row to a number (separates the digits)
  s     % Compute the sum of the digits
  X^    % Compute the square root
  1\    % mod with 1 to determine if the square root is an integer
  ?x    % If there is a remainder, then remove this element from the stack
        % Implicitly display the stack contents

```
> 1 votes

# Answer
# Julia - 38 bytes

```
!X=filter(i->√sum(digits(i))%1==0,X)

```

It's pretty easy to see what this does. `digits` converts a number into a list of its digits, `sum` thus calculates the digit-sum,  will then produce a whole number if the number is a square, otherwise there will be a fractional part. `%1` will return only the fractional part, and if it's zero (`==0`), `filter` will keep it on the list, otherwise it gets filtered out.

Used as `![22228,4,113125,22345]`
> 1 votes

# Answer
# Jolf, 8 bytes

Try it here!

```
ψxd!iUuH

```

## Explanation

```
ψxd!iUuH
ψxd       filter the input according to the input
      uH  digit sum of H (element)
     U    sqrt of
   !i     is an integer?

```
> 1 votes

# Answer
# MATLAB, ~~52~~ ~~43~~ 42 bytes

```
@(x)x(~mod(sum(dec2base(x,10)'-48).^.5,1))

```

Creates an anonymous function named `ans` that can be called with an array as input: `ans([22228,4,113125,22345])`.

**Online Demo**. The online demo is in Octave which doesn't work for the empty input, but MATLAB does.

**Explanation**

We convert each element in the input array to base 10 which will yield a 2D character array where each row contains the digits of a number in the array. To convert these characters to numbers, we subtract 48 (ASCII for `'0'`). We then sum across the rows, take the square root, and determine whether each value is a perfect square `~mod 1`. We then use this boolean to filter the input array.
> 1 votes

# Answer
# C, 143 141 bytes

* saved 2 bytes, @user6188402

```
i;q(char*n){double m=0;while(*n)m+=*n++-48;m=sqrt(m)-(int)sqrt(m);return !m;}s(n,s)char**n;{i=-1;while(++i<s)if(q(n[i]))printf("%s\n",n[i]);}

```

**Ungolfed** try online

```
int q(char*n)
{
    double m=0;

    while(*n) // sum digits
        m+=*n++-48;

    // get the decimal part of its square root
    m=sqrt(m)-(int)sqrt(m);

    // true if decimal part is zero
    return !m;
}

// input is text, can be a file
void s(char**n, int s)
{
    int i=-1;

    while(++i<s) // for each number in input
        if(q(n[i])) // if is square
            printf("%s\n",n[i]); // output is terminal
}

```
> 1 votes

# Answer
# Clojure, 110 bytes

```
(fn[t](filter(fn[x](let[a(reduce +(*(count(str x))-48)(map int(str x)))](some #(=(* % %)a)(range(inc a)))))t))

```

Calculates the sum of number digits and then filters out those for which there doesn't exist a number which squared is equal to the sum.

You can see the result here – https://ideone.com/ciKOje
> 1 votes

# Answer
# Perl 6,  ~~38~~  35 bytes

```
~~{.grep: {($/=sqrt [+] .comb)==$/.Int}}
{.grep: {($/=.comb.sum.sqrt)==$/.Int}}~~
{.grep: {($/=sqrt [+] .comb)==^$/}}
{.grep: {($/=.comb.sum.sqrt)==^$/}}
```

### Test:

```
#! /usr/bin/env perl6

use v6.c;
use Test;

my @tests = (
  [1,4,9,16,25,1111] => [1,4,9,1111],
  [1431,2,0,22,999999999] => [1431,0,22,999999999],
  [22228,4,113125,22345] => [22228,4,22345],
  [] => [],
  [421337,99,123456789,1133557799] => [],
);

plan +@tests;

my &sq-digit-sum = {.grep: {($/=sqrt [+] .comb)==^$/}}

for @tests -> $_ ( :key($input), :value($expected) ) {
  is sq-digit-sum($input), $expected, .gist
}

```

```
1..5
ok 1 - [1 4 9 16 25 1111] => [1 4 9 1111]
ok 2 - [1431 2 0 22 999999999] => [1431 0 22 999999999]
ok 3 - [22228 4 113125 22345] => [22228 4 22345]
ok 4 - [] => []
ok 5 - [421337 99 123456789 1133557799] => []

```
> 1 votes

# Answer
# Retina, 69

Because testing for perfect squares in retina. This can be modified for generalised integer square root calculation.

```
.+
$&a$&
+`\b\d
$*b

\bb
$&:
+`(\bb+):(bb\1)
$1 $2:
G`(:a|0$)
.*a

```

Input is a newline-separated list.

Try it online.

* Stage 1 - repeat the number on each line, and separate with `a`
* Stage 2 - convert each digit before the `a` to unary expressed as `b`s, separated with spaces
* Stage 3 - remove spaces - each unary now represents the digit sum
* Stage 4 and 5 - Use the fact that perfect squares may be expressed 1 + 3 + 5 + 7 + ... . Split each unary up accordingly
* Stage 6 - grep filter just the ones that exactly split into the above form
* Stage 7 - discard all but the original number
> 1 votes

# Answer
# K (oK), ~~19~~ ~~17~~ 13 bytes

**Solution:**

```
(~1!%+/.:'$)#

```

Try it online!

**Explanation:**

```
(~1!%+/.:'$)# / the solution
(          )# / apply function to list
          $   / convert to string
       .:'    / value (.:) each (')
     +/       / sum
    %         / square-root
  1!          / modulo 1
 ~            / not

```

**Notes:**

* -2 bytes with smarter way of identifying squares
* -4 bytes thanks to ngn
> 1 votes

# Answer
# Ruby, 39 bytes

```
->a{a.reject{|x|x.digits.sum**0.5%1>0}}

```

Try it online!
> 1 votes

# Answer
# MathGolf, ~~5~~ 4 bytes

```
gÅΣ°

```

Try it online!

### Explanation:

```
gÅ    Filter by the next two instructions
  Σ   The digit sum
   °  Is a perfect square?

```

MathGolf is still in development, ~~so I assume implicit input is coming soon to shave off that first byte.~~ Yay!
> 1 votes

# Answer
# Vyxal, 5 bytes

```
'f∑∆²

```

Try it Online!

```
'        # Keep elements in input list
 f∑      # Whose sum of digits is
   ∆²    # A perfect square

```
> 1 votes

# Answer
## q - 53 characters

`{x where({(sum({"J"$x}')($:)x)in((!:)x+1)*(!:)x+1}')x}`

The interesting bit is the inner lambda, which casts to a string, sums the digit (by casting each of them to an int), and then checks if they are a in a list of squares.
> 0 votes

# Answer
## Javascript, 61 ~~65~~

```
f=
a=>a.filter(x=>(r=Math.sqrt(eval([...`${x}`].join`+`)))==~~r)

j=JSON.stringify;
console.log([
[1,4,9,16,25,1111],
[1431,2,0,22,999999999],
[22228,4,113125,22345],
[],
[421337,99,123456789,1133557799]
].map(x=>j(x)+' -> '+j(f(x))).join`
`)
```
> 0 votes

# Answer
## JavaScript (ES7), 56 bytes

```
a=>a.filter(n=>[...''+n].reduce((x,y)=>+x+ +y)**.5%1==0)

```
> 0 votes

# Answer
## C#, 103 bytes

```
int[] f(int[] a){return a.Where(n=>Math.Sqrt((n+"").Select(m=>int.Parse(m+"")).Sum())%1==0).ToArray();}

```

Its really sad i have to turn chars and ints into strings all the time to work on them, i wish there was a better solution than adding an empty literal "" to cast into string.

any help on golfing this down appreciated
> 0 votes

# Answer
## Hoon, 78 bytes

```
|*
*
%+
skim
+<
|=
@ui
=(0 q:(sqt (roll (scan (slag 2 <+<>) (star dit)) add)))

```

`++skim` only keeps the elements of the list that the function returns yes for. We cast all the atoms in the list to `@ui` in the sample, for the sole reason that Urbit's integers have mandatory group seperators: if you try to cast 1.000 to a string, it will return `"1.000"` instead of `"1000"`. `<`@ui`1.000>`, however, gives `"0i1000"`, so we cast and then cut off the first two letters of the string.

We then parse the string with the parser combinator `(star dit)`, which is like the `[0-9]*` regex but also converts the character to an atom. We fold over the resulting list with `add`.

We call `sqt` on the number. In Hoon, the only data types are atoms or tuples, so it returns two atoms intead of a float: the nearest perfect square root, and the remainder. We can then just test if the remainder is 0.
> 0 votes

# Answer
### TXR Lisp: ~~85 81~~ 72 byte `(op ...)` denoting anon. function:

```
~~(op keep-if (opip tostring (mapcar chr-digit) (apply +) (= @1 [[dup *] (isqrt @1)])))~~
~~(op keep-if (opip `@1` (mapcar chr-digit) (apply +) (= @1 [[dup *] (isqrt @1)])))~~
(op keep-if(opip`@1`(mapcar chr-digit)(apply +)(=@1[[dup *](isqrt@1)])))

```

```
$ txr -i
1> (op keep-if(opip`@1`(mapcar chr-digit)(apply +)(=@1[[dup *](isqrt@1)])))
#<interpreted fun: lambda #:rest-0117>
2> [*1 '(1 4 9 16 25 1111)]
(1 4 9 1111)
3> [*1 '(1431 2 0 22 999999999)]
(1431 0 22 999999999)
4> [*1 ()]
nil
5> [*1 '(22228 4 113125 22345)]
(22228 4 22345)
6> [*1 '(421337 99 123456789 1133557799)]
nil
7>

```

`isqrt` is integer square root. This will handle large integers; no floating-point hacks here.

TXR Lisp is fundamentally a Lisp-2 dialect, like ANSI Common Lisp or Emacs Lisp. However, the square brackets `[whatever ...]` notation is syntactic sugar for the operator `(dwim whatever ...)` which evaluates using a form of Lisp-1 namespace semantics rather than Lisp-2: functions and variable bindings in one space rather than separate spaces. `dwim` is "deep"; it's not a macro transforming Lisp-2 to Lisp-2; it has visibility into the lexical environments to deliver the actual Lisp-1-like semantics.

In `[dup *]`, the `dup` combinator takes a binary function (or a function that can be used as binary), and returns a unary function which applies two copies of its argument to that function as two arguments; i.e `[dup *]` denotes a squaring function.

`op` is a rich partial evaluation macro, and `opip` combines left-to-right pipeline with `op`: *op pipe*. `(op mapcar +)` curries the `mapcar` function. In `(opip (mapcar +) ...),`mapcar`is similarly curried (the`op\` is implicit), and part of a pipeline.

The TXR Lisp REPL allows numbered references to prior results, modulo 100: `*1` is the value produced in the most recent command line numbered 1, or 101, or 201, ...
> 0 votes

# Answer
## C: ~~113~~  111 — based on other C answer.

This is a complete program with `main`. The input list is the argument list.

Old style C is used, but with the C99 `fmod` function.

```
~~q(char*n){double m=0;while(*n)m+=*n++-48;return!fmod(sqrt(m),1);}main(c,v)char**v;{while(*++v)if(q(*v))puts(*v);}~~
q(char*n){double m=0;while(*n)m+=*n++-48;return!fmod(sqrt(m),1);}main(c,v)char**v;{while(*++v)q(*v)&&puts(*v);}

```

Run:

```
$ gcc golf.c -o golf -lm
golf.c:1:1: warning: data definition has no type or storage class [enabled by default]
golf.c: In function ‘q’:
golf.c:1:52: warning: incompatible implicit declaration of built-in function ‘fmod’ [enabled by default]
golf.c:1:57: warning: incompatible implicit declaration of built-in function ‘sqrt’ [enabled by default]
$ ./golf 1 4 9 16 25 1111
1
4
9
1111
$ ./golf
$ ./golf 421337 99 123456 1133557799
$
```
> 0 votes

# Answer
## Actually, 12 bytes

```
`$♂≈Σ;√≈²=`░

```

Try it online!

Explanation:

```
`$♂≈Σ;√≈²=`░
`$♂≈Σ;√≈²=`░  filter list, taking only values where the following function is true:
 $♂≈Σ           to string, map int, sum (digital sum, we'll call this n)
     ;√≈²=      compare equality to int(sqrt(n))**2

```
> 0 votes

# Answer
# Neim, 4 bytes

```
Λq

```

Explanation:

```
Λ    Keep if
    sum of digits
    is in
  q  square numbers

```

Try it online!
> 0 votes

# Answer
## F#, 95 bytes

```
let s n=Seq.exists(fun x->x*x=n){1..n}
let i x=Seq.filter(string>>Seq.sumBy(int>>(+)(-48))>>s)x

```

Try it online!

Makes a lot of use of the `>>` operator (the function composition operator) which chains functions together. `s` determines if there is an integer square for `n`.

The main function `i` maps each number into a `string`, then sums the digits in the string. Each digit is the character's integer representation minus 48 (e.g. `'4' |> int = 52 - 48 = 4`). Then it uses `s` to determine if the digit sums has an integer square. If it does, it's included in the returned sequence. If it does not, then it's excluded (`Seq.filter`).
> 0 votes

# Answer
# Attache, 18 bytes

```
`\&:(IsSquare@Sum)

```

Try it online!

## Explanation

``\` is the filter operator and `&:` applies the function `IsSquare@Sum` as it's predicate.
> 0 votes

# Answer
# Japt, 8 bytes

```
f_õ²øZìx

```

Try it

```
f_ìx ¬v1

```

Try it
> 0 votes

# Answer
# Thunno 2, 4 bytes

```
æSÆ²

```

Try it online!

#### Explanation

```
æSÆ²  # Implicit input
æ     # Filter by:
 S    #  Digit sum
  Æ²  #  Is a perfect square
      # Implicit output

```
> 0 votes

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


# Question
Title: Implement "tac": Print lines from a file in reverse
Between the kitten question and seeing this question at U&L about some `sed` magic, how about implementing `tac`?

---

# Objective

Implement a program that will reverse and print the lines in a file.

---

# Input

A file, provided as a name or via standard input

---

# Output

The lines, reversed, to standard out.

---

# Scoring

Bytes of source code.

# Answer
## GS2, 3 bytes

```
* +

```

The three bytes are, in order, split lines, reverse, and join lines.
> 15 votes

# Answer
# Perl, 11 bytes

```
$\=$_.$\}{

```

Behaves exactly like `tac`. This code requires the `-p` switch, which I have counted as 1 byte.

### Test runs

```
$ echo -en 'a\nb' | perl -pe'$\=$_.$\}{' | xxd -g 1
0000000: 62 61 0a                                         ba.
$ echo -en 'a\nb\n' | perl -pe'$\=$_.$\}{' | xxd -g 1
0000000: 62 0a 61 0a                                      b.a.

```

### How it works

As explained here, the `-p` switch basically wraps `while (<>) { ... ; print }` around the program, so the source code is equivalent to

```
 while(<>)
 {
   $\ = $_ . $\
 }
 print

```

For each line of input, we prepend the current line (`$_`) to `$\` (initially undefined), updating the latter with the result.

After all lines have been processed, `print` prints the value of the local variable `$_` (undefined in this scope), followed by the output record separator (`$\`).
> 9 votes

# Answer
# Pyth, 4 bytes

```
j_.z

```

`.z` is the input separated by lines as a list, `_` reverses it and `j` joins it by a character, which by default is `\n`.
> 8 votes

# Answer
# FlogScript, 2 bytes

```
)"

```

(Try it on anarchy golf.)

The `)` enables `--in-out-line-array` mode, and the rest of the program is `"`, reversing the array of lines.
> 8 votes

# Answer
# Retina, 7 bytes

```
!rm`.*$

```

With a single regex, Retina runs in Match mode. This normally just prints the number of matches, but with `!` we configure it to print the actual matches instead (separated by linefeeds).

The actual regex is merely `.*$`. `.*` matches any line (potentially empty), because `.` can match any character except linefeeds. I'll get to the `$` in a minute.

How do we make it print the matches in reverse? By making use of .NET's right-to-left matching mode, activated with the `r`. This means the regex engine starts at the end of the string when looking for matches and works backwards.

Finally, the `m` makes the `$` match the end of a *line* instead of the end of the string. Why do we even need that? The trouble is that `.*` generates extraneous matches. Consider the regex substitution

```
s/a*/$0x/

```

applied to the input `baaababaa`. You'd think this would yield `baaaxbaxbaax`, but it actually gives you `baaaxxbaxxbaaxx`. Why? Because after matching `aaa` the engine's cursor is between the `a` and the `b`. Now it can't match any more `a`s, but `a*` is also satisfied with an empty string. This means, after every single match you get another empty match.

We don't want that here, because it would introduce additional empty lines, so we discard those extraneous matches (which are at the *beginnings* of the lines, due to the right-to-left mode) by requiring that matches include the end of the line.
> 7 votes

# Answer
# Haskell, 34 bytes

```
main=interact$concat.reverse.lines

```

\[edit\]

Saved one byte by replacing `unlines` with `concat`.
> 6 votes

# Answer
# CJam, 7 bytes

```
qN/W%N*

```

Reads stdin, prints to stdout.

Explanation:

```
q       Get input.
N/      Split at newlines.
W%      Reverse list.
N*      Join with newlines.

```
> 4 votes

# Answer
# Pyth, 5 bytes

```
jb_.z

```

This reverses the order of the lines with a simple split-reverse-join approach, but not quite like tac.

Try it online.
> 4 votes

# Answer
# Python 2, 52 bytes

```
import sys;print''.join(sys.stdin.readlines()[::-1])

```
> 4 votes

# Answer
# Befunge-93, 17 bytes

```
~:1+!#v_
>:#,_@>$

```

Nothing fancy here; just put everything on the stack, then pop it off.
> 4 votes

# Answer
# Pure Bash (no external utilities), 56

```
mapfile a
for((i=${#a[@]};i--;));{
printf %s "${a[i]}"
}

```

This is one of the few answers to do exact `tac` emulation, as asked about in Dennis' comment:

```
$ echo -en 'a\nb' | ./tacemu.sh | xxd -g 1
0000000: 62 61 0a                                         ba.
$ echo -en 'a\nb\n' | ./tacemu.sh | xxd -g 1
0000000: 62 0a 61 0a                                      b.a.
$

```
> 4 votes

# Answer
# Ruby, 16 bytes

```
puts [*$<].reverse

```
> 4 votes

# Answer
## Perl, 16 bytes

```
print reverse<>

```
> 3 votes

# Answer
## sed, 9 bytes

```
1!G;h;$!d

```

No upvote wanted, this is a famous sed one-liner.
> 3 votes

# Answer
# Powershell, 41 bytes

```
$a=$args|%{gc $_};[array]::Reverse($a);$a

```

Stores the content of a file line by line in `a`, reverses `a` and finally prints it.
> 3 votes

# Answer
# GolfScript, 7 bytes

```
n/-1%n*

```

Online test here.
> 3 votes

# Answer
# Burlesque, 6 bytes

```
ln<-uN

```

`ln` splits lines, `<-` reverses, `uN` joins lines and formats for raw output.
> 3 votes

# Answer
# C#, ~~179~~ 171 bytes

```
using B=System.Console;class A{static void Main(){var a=new System.Collections.Stack();string b;while((b=B.ReadLine())!=null)a.Push(b);foreach(var c in a)B.WriteLine(c);}}

```

Reads lines, placing them in a stack, and then writes them backwards. I would use Mathematica for this, but it has no sense of EOF.
> 3 votes

# Answer
# Bash, ~~48~~ 43 characters

(Inspired by Digital Trauma's Bash answer. Upvotes for the idea should go to him.)

```
mapfile -c1 -C's=$2$s;set'
printf %s "$2$s"

```

Sample run:

```
bash-4.3$ echo -en 'a\nb' | bash tac.sh | xxd -g 1
0000000: 62 61 0a                                         ba.

bash-4.3$ echo -en 'a\nb\n' | bash tac.sh | xxd -g 1
0000000: 62 0a 61 0a                                      b.a.

```
> 3 votes

# Answer
# JavaScript (SpiderMonkey Shell), 38 bytes

```
[...read(readline())].reverse().join``

```

Pretty simple

---

`read()` reads a file

`readline()` reads a string from STDIN

`[...*str*]` will split *str* into an array of chars

`reverse()` will reverse the array

`join``` will collpase the array into a string
> 3 votes

# Answer
# GNU Awk, 27 characters

(Inspired by Ed Morton's GNU Awk answer. CW as I not intended to hijack his solution.)

```
{s=$0RT s}END{printf"%s",s}

```

Note that by changing `RT``RS` this becomes portable standard Awk but looses the ability to preserve the absence of the final newline.

Sample run:

```
bash-4.3$ echo -en 'a\nb' | awk '{s=$0RT s}END{printf"%s",s}' | xxd -g 1
0000000: 62 61 0a                                         ba.

bash-4.3$ echo -en 'a\nb\n' | awk '{s=$0RT s}END{printf"%s",s}' | xxd -g 1
0000000: 62 0a 61 0a                                      b.a.

```
> 3 votes

# Answer
# SNOBOL, 42 bytes

```
S S =INPUT CHAR(10) S :S(S)
 OUTPUT =S
END

```
> 3 votes

# Answer
# Gema, 25 characters

```
*\n=@set{s;$0${s;}}
\Z=$s

```

Sample run:

```
bash-4.3$ echo -en 'a\nb' | gema '*\n=@set{s;$0${s;}};\Z=$s'
ba

bash-4.3$ echo -en 'a\nb\n' | gema '*\n=@set{s;$0${s;}};\Z=$s'
b
a

```
> 2 votes

# Answer
# Hassium, 90 Bytes 86 Bytes

```
use IO;func main(){c=File.readLines(args[0]);for(x=c.length-1;x>=0; println(c[x--]))0;

```

See expanded here
> 2 votes

# Answer
# JavaScript(Node.js), 91 Bytes

```
console.log(require('fs').readFileSync(process.argv[2])+"".split(d="\n").reverse().join(d))

```
> 2 votes

# Answer
# sed, 7 bytes

```
G;h;$!d

```

This works for me (and it's the shortest solution elsewhere), but I don't really want to find out why. I just messed around with the famous 9-byte trick until I found this. I guess `G`ing the first line does nothing?
> 2 votes

# Answer
# Bash + common utilities, 25

```
tr \\n ^G|rev|tr ^G \\n|rev

```

Here the `^G` is a literal `BEL` character. I'm assuming the input is only printable ascii.

This `tr`ansforms the entire input to one line by replacing newlines with BELs, then `rev`erses that line, then `tr`ansforms back to multiline, then `rev`erses each line again, to get the desired output.
> 2 votes

# Answer
# MATLAB, 44

```
@(x) strjoin(fliplr(strsplit(x,'\n')),'\n');

```

Splits the string at new lines, flips the resulting array, then rejoins with new line characters.
> 2 votes

# Answer
# Julia, 65 bytes

```
open(s->print(join(reverse([l for l=readlines(s)]),"")),ARGS[1])

```

This takes a file as a command line argument and prints its lines in reverse order. Trailing newlines are moved to the front, unlike `tac`, which is legit.

Ungolfed:

```
function p(s::Stream)
    # Create a vector of the lines of the input stream
    L = [l for l in readlines(s)]

    # Reverse the vector and join it back into a string
    j = join(reverse(L), "")

    # Print the string to STDOUT
    print(j)
end

# Open the file specified in the first command line argument
# and apply the function p to its contents
open(p, ARGS[1])

```
> 2 votes

# Answer
# Pip, 3 + 2 = 5 bytes

Uses the `r` and `n` flags; reads from stdin.

```
RVg

```

The `r` flag reads stdin and stores it as a list of lines in `g` (which is normally a list of command-line ar**g**s). We then reverse that list, and it is auto-printed. The `n` flag causes lists to be output with newline as a separator.
> 2 votes

# Answer
# \>\<\>, 55 bytes

```
0i:1+?!v:a=?v}1+!
0.20r}~<    >~}00
oa]~~.?)2l2dor[;!?l

```

It first counts the length of each line so it can isolate them in a separate stack when it browses back the lines to display them.

It can probably get shorter, I may work on it later.
> 2 votes

# Answer
# Jelly, ~~10~~ 9 bytes

```
Ḋ;ƈ$ÐLỴṚY

```

Try it online!

Thanks to Dennis for -1.
> 2 votes

# Answer
# Addict, 67 bytes

```
a g
 t _[_]
 p
 o
a p
 i _
 g
 d
a o
 d _
 s
 d
a s
 c _[_]
 o
 d
g

```

Copy and paste the code here to try it.
> 2 votes

# Answer
## STATA, 46 bytes

```
inf str99 v using a.b
g a=-_n
so a
l v,noo noh

```

Expects input as a file called a.b, with each line no more than 99 characters. Reads in a file and labels the variable v. Makes a new variable called a with the negative index of it. Sort by the negative index (i.e. reverse order) and then list every thing in sorted (i.e. reverse) order.

For a longer length of lines, put quotes around each line and use (42 bytes):

```
insheet using a.b
g a=-_n
so a
l v,noo noh

```
> 1 votes

# Answer
# Scala, ~~53~~ 52 bytes

```
(io.Source.stdin.getLines():\0){(a,b)=>println(a);0}

```

Bastardizing/side-effecting `foldRight` (`:\`) to deal with iterators (as returned by `getLines`) not having `reverse`
> 1 votes

# Answer
# GNU command line environment, 41 40 37 bytes

```
cat -n|sort -nr|sed 's/^[^ ]* //'

```
> 1 votes

# Answer
# Python, 80 72 bytes

It isn't the best solution, but I guess it's something.

```
a=lambda x: f=open(x,'r');l=f.readlines();for o in reversed(l): print(o)

```

Any tips on golfing it further?
> 1 votes

# Answer
# q, 35 bytes

```
-1 each reverse read0 hsym`$.z.x 0;

```
> 1 votes

# Answer
# C#, 145 bytes

Not as short as I hoped.. But I tried!

## Golfed

```
using System.Linq;class c{static void Main(string[]a){foreach(var s in System.IO.File.ReadAllLines(a[0]).Reverse())System.Console.WriteLine(s);}}

```

## Ungolfed

```
using System.Linq;
class c
{
    static void Main(string[]a)
    {
        foreach(var s in System.IO.File.ReadAllLines(a[0]).Reverse())
            System.Console.WriteLine(s);
    }
}

```
> 1 votes

# Answer
# Vim, 6 bytes:

```
!Grev<cr>

```

Filters every line through the external command: `rev`. Must be run on linux.

Try it online!
> 1 votes

# Answer
# tcl, 52

File is named `F`

```
puts [join [lreverse [split [read [open F]] \n]] \n]

```

# demo
> 1 votes

# Answer
# Pyth, 4 bytes

```
j_.z

```

Try it!

Takes input from STDIN

## explanation

```
j_.z
  .z    # Input as list of lines
 _      # reverse
j       # join on newline

```
> 0 votes

# Answer
# Thunno 2 `N`, 2 bytes

```
¤r

```

Try it online!

* `¤` \- lines of input
* `r` \- reverse
* `N` \- join on newlines
> 0 votes

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


title: Solve quadratic equations when 1+1=0

text:
# Question
Title: Solve quadratic equations when 1+1=0
There already have been multiple challenges about carryless multiplication, this challenge will work with the same calculation rules.

You task is given a quadratic polynomial `ax²+bx+c`, to find an integer `r` such that `a*r*r+b*r+c` is zero, with `+` meaning exclusive or and `*` being carryless multiplication (use xor to add up the numbers in binary long multiplication).

Input: Polynomial `ax²+bx+c` for instance given as an coefficient vector

Goal: find a number `r` such that `a*r*r+b*r+c=0` with `*` being multiplication without carry and `+` being exclusive or.

Rules:

* You may assume there is an integral solution
* You only need to return a **single solution** of the equation
* The returned solution may be different if the program is called multiple times
* This is the shortest solution (per language) wins

Examples:

```
x²+x         -> x=0 or x=1
x²+3x+2      -> x=1 or x=2
x²+5         -> x=3
x²+7x+12     -> x=3 or x=4
5x²+116x+209 -> x=25
x²+12x+45    -> x=5 or x=9

```

# Answer
> 4 votes
# 05AB1E, ~~30~~ 28 bytes

```
àÝʒUεXN.DNFV0sbv·yY*^}}}.«^_

```

Takes a reversed polynomial triplet as input (if this is not allowed, a single `R` can be added between the ).

Try it online or verify all test cases.

**Explanation:**

`0sbv·yY*^}` is taken from my answer for one of the resulted challenges.

```
à               # Push the maximum of the (implicit) input-list
 Ý              # Pop and push a list in the range [1,max]
  ʒ             # Filter this list by:
   U            #  Pop and store the current value in variable `X`
   ε            #  Map over the (implicit) input-list of the reversed polynomial
                #   (implicitly push the current polynomial integer of the map)
    XN.D        #   Push the 0-based map-index amount of copies of value `X`
    NF          #   Loop the 0-based map-index amount of times:
      V         #    Pop and store the current top value in variable `Y`
      0         #    Push a 0
       s        #    Swap so the next value is at the top of the stack
        b       #    Convert it to a binary-string
         v      #    Pop and loop over each of its bits `y`:
          ·     #     Double the current value
           y    #     Push the current bit `y`
            Y*  #     Multiply it to value `Y`
              ^ #     Bitwise-XOR the two together
         }      #    Close the foreach-loop
     }          #   Close the ranged loop
   }            #  Close the map
    .«          #  Reduce the list by:
      ^         #   Bitwise-XOR
       _        #  Check if the final result is 0
                # (after which the filtered list is output implicitly as result)

```

# Answer
> 4 votes
# Haskell, ~~108~~ ~~102~~ 101 bytes

```
import Data.Bits
a%b=xor a b
0!_=0
a!b=(2*div a 2!b)%(mod a 2*b)
f a b c=head[x|x<-[0..],1>a!x%b!x%c]

```

Try it online!

# Answer
> 3 votes
# PARI/GP, 90 bytes

```
a->[subst(lift(t-x),y,2)|t<-factor(Pol([Pol(Mod(binary(i),2),y)|i<-a]))[,1],deriv(t,x)==1]

```

Attempt This Online!

Coverts the input to a polynomial in \\$\mathbb{F}\_2\[y\]\[x\]\\$, and then factors it to find the roots.

# Answer
> 2 votes
# JavaScript (ES6), 63 bytes

*-3 bytes thanks to @Neil*

```
(a,b,c)=>(g=r=>(m=n=>n&&n%2*r^2*m(n>>1))(m(a)^b)^c?g(r+1):r)(0)

```

Try it online!

### Commented

```
(a, b, c) =>  // input triplet (a, b, c)
( g = r => (  // g is a recursive function taking r
  m = n =>    // m is a recursive function taking n and
              // computing the carryless multiplication n * r
  n &&        //   stop if n = 0
  n % 2 * r ^ //   otherwise XOR the LSB of n multiplied by r
  2 *         //   with twice the result of
  m(n >> 1)   //   a recursive call with floor(n / 2)
)(m(a) ^ b)   // compute ((a * r) XOR b) * r
^ c           // XOR it with c
?             // if the result is not 0:
  g(r + 1)    //   try again with r + 1
:             // else:
  r           //   stop and return r
)(0)          // initial call to g with r = 0

```

# Answer
> 2 votes
# Python3, 338 bytes:

```
E=enumerate
def C(a,b):
 d={}
 for x,A in E(a[::-1]):
  for y,B in E(b[::-1]):
   if'11'==A+B:d[x+y]=int(d.get(x+y,0)==0)
 return''.join(str(d.get(i,0))for i in range(0,max(d or[0])+1))[::-1]
def f(p):
 r=0;A,B=bin(p[0])[2:],bin(p[1])[2:]
 while 1:
  if p[2]==int(''.join(C(C(A,J:=bin(r)[2:]),J)),2)^int(''.join(C(B,J)),2):return r
  r+=1

```

Try it online!

# Answer
> 2 votes
# Charcoal, 57 bytes

```
Ｆ³⊞υ⌕Ａ⮌⍘Ｎ²1Ｗ⊙Ｅ⟦⌕Ａ⮌⍘ⅈ²1⟧⁺§υ²∧κΣＥκ⁺μ⁺§υ¹ΣＥκ⁺ξ§υ⁰⊙κ﹪№κμ²Ｍ→Ｉⅈ

```

Attempt This Online! Link is to verbose version of code. Explanation:

```
Ｆ³⊞υ⌕Ａ⮌⍘Ｎ²1

```

Read in the three coefficients, then decompose them as a sum of powers of `2`.

```
⌕Ａ⮌⍘ⅈ²1

```

Decomposing the trial result as a sum of powers of `2`, ...

```
Ｅ⟦...⟧⁺§υ²∧κΣＥκ⁺μ⁺§υ¹ΣＥκ⁺ξ§υ⁰

```

... compose the decomposed values together by matrix sum, then flatten and join the matrices together, ...

```
Ｗ⊙...⊙κ﹪№κμ²

```

... and while any power of two appears an odd number of times, ...

```
Ｍ→

```

... increment the trial result.

```
Ｉⅈ

```

Output the final result.

By representing an integer as a list of powers of `2`, the sum of integers is equivalent to the concatenation of the lists with duplicates removed, while the product of integers is equivalent to the Cartesian product of the lists, where each entry is reduced by sum, and then duplicates removed (note that in both cases triplicates become single entries). However it's not actually necessary to remove the duplicates, merely to check that there would be no left over entries.

I don't know whether there's a mathematical or computing term for creating an `N`-dimensional matrix where each entry is the sum of the relevant entries of `N` vectors, but `numpy.add.outer` performs the equivalent operation when `N=2`.

# Answer
> 1 votes
# Ruby, ~~68~~ 65 bytes

Utilizes the multiplication function from Arnauld's JavaScript answer. -3 bytes from @Neil.

```
->a,b,c{(0..).find{|x|m=->a{a>0?a%2*x^2*m[a/2]:0}
m[m[a]^b]^c<1}}

```

Attempt This Online!

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


title: Language Word Checker

text:
# Question
Title: Language Word Checker
Develop a program to check if a given word is part of a language defined by the following rules:

* The language has a set of rules.
* The empty string is considered a valid word in the language.
* Two words from the language can be concatenated to create a new word in the language.
* If X is a word in the language, then "A" + X + "A" is also a word in the language.
* If X is a word in the language, then "A" + X + "C" is also a word in the language.
* If X is a word in the language, then "B" + X + "A" is also a word in the language.
* If X is a word in the language, then "B" + X + "C" is also a word in the language.

You can assume all inputs only consist of the characters A, B and C.

Examples:

* The word "CB" doesn't belong to the language. There is no way to arrive at this word from the above rules.
* The word "BAAC" belongs to the language.

Reasoning: The empty string is a valid word. Applying the "A" + X + "A" rule, we get "AA". Now we apply the "B" + X + "C" rule to get "BAAC".
* The word "BCBC" belongs to the language.

Reasoning: The empty string is a valid word. Applying the "B" + X + "C" rule, we get "BC". Now we apply the concatenation rule to get "BCBC". The concatenation rule can be used to concatenate a word with itself.

## Test cases

```
CBAA ---> false
CBBB ---> false
BCCA ---> false
CCAC ---> false
ABAC ---> true
ACAB ---> false
AAAC ---> true
BBAC ---> true
CABC ---> false
CCAB ---> false

```

This is a problem. While the language looks random, I hope you can find a pattern in the language to write the shortest code possible. Hint: It is possible to check in linear time.

# Answer
# Jelly, ~~18~~ ~~15~~ 16 bytes

```
,UċƤ"⁾CBḤ«ƑJ>LḂ$

```

Try it online!

Validated against tsh's Python demonstration and against JvdV's regex. (But, I neglected to check extremely unbalanced odd cases...) Checks that no more than half of the symbols in every prefix are `C` and that no more than half of the symbols in every suffix are `B`.

```
,U                  Pair the input with its reverse.
    "⁾CB            For the original and C, and the reverse and B:
  ċƤ                Count how many times the symbol occurs in each prefix.
        Ḥ           Double the counts.
         «Ƒ         Are all elements less than or equal to
           J        their 1-indices?
            >LḂ$    Also, reject any odd-length inputs.

```
> 7 votes

# Answer
# Python, 63 bytes

```
lambda x:bool(match('^([AB](?1)*[AC])*$',x))
from regex import*

```

See an online demo

This is based on the *PCRE* regex pattern:

```
^([AB](?1)*[AC])*$

```

See an online demo. I was unsure if we were allowed to simply post the pattern for 18 bytes.

---

# Excel (ms365), 120 bytes

Formula in `B1`:

```
=REDUCE(A1,ROW(A:A),LAMBDA(a,b,IFERROR(REPLACE(a,MIN(IFERROR(FIND({"AC","BA","BC"},a),"")),2,),SUBSTITUTE(a,"AA",))))=""

```

The idea here is to 1st replace any of the compound words that are not a copy of itself. If not found, try to replace 'AA'. Check if the final result after the last iteration is empty.
> 4 votes

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

```
f=([x,...y],z)=>x?x<'C'&f(y,-~z)|x!='B'&z>0&f(y,~-z):!z

```

Try it online!

This question can be solved in linear time, however we do prefer golf instead of time complexity.
> 3 votes

# Answer
# Retina 0.8.2, 28 bytes

```
^((A|B)|(?<-2>A|C))*$(?(2)^)

```

Try it online! Link includes test cases. Explanation:

```
^(

```

Starting at the beginning of the string, ...

```
(A|B)|

```

match either of `A` or `B`, or...

```
(?<-2>A|C)

```

... match a previously matched `A` or `B` with an `A` or `C`, removing the knowledge of the match, so that a subsequent `A` or `C` has to match a previous `A`or `B`, ...

```
)*$

```

... repeating until the end of the string, ...

```
(?(2)^)

```

without leaving any unmatched leading `A`s or `B`s.
> 3 votes

# Answer
# Go, ~~125~~ 134 bytes

```
import."strings"
func f(s string)bool{l:=s
for _,e:=range[]string{"BA","AC","BC","AA"}{l=ReplaceAll(l,e,"")}
return l==""||l!=s&&f(l)}

```

Attempt This Online!

Recursive function that repeatedly replaces the `A[empty string]B` pairs with an empty string.

### Explanation, slightly ungolfed

```
import."strings"      // boilerplate
func f(s string)bool{ // function that maps string -> bool
l:=s                  // init
for _,e:=range[]string{"BA","AC","BC","AA"}{
                      // replace these pairs in this exact order
l=ReplaceAll(l,e,"")} // with an empty string
return l==""||l!=s&&f(l)} // ok if empty, not ok if non-empty

```

### Changelog

* +9 bytes for matching `AACC`, using a different approach.
> 3 votes

# Answer
# 05AB1E, 17 bytes

```
„AB„ACâIgиæõδ.;õå

```

Try it online or verify all test cases. The test suite contains a `;` (halve) after the `g` to speed it up substantially.

**Explanation:**

```
„AB„ACâ     # Push ["AA","AC","BA","BC"] by taking the cartesian product of "AB" & "AC"
 Ig         # Push the length of the input-string
   и        # Repeat the earlier list of strings that many times as single list,
            # so each individual pair is repeated the input-length amount of times
    æ       # Get the powerset of this list
      δ     # Map over each inner list:
     õ .;   #  Replace every first occurrence of the pairs one by one with an empty
            #  string in the (implicit) input-string
         õå # Check if the resulting list contains an empty string
            # (after which the result is output implicitly)

```

Minor note: for an explicit empty string input, it'll do the following steps: `„AB„ACâIgи`=`[]``æ`=`[[]]``õδ.;`=`[""]``õå`=`1` (truthy). This is different than if no input is provided, since `õδ.;` would then keep `[[]]` and the result is falsey: try it online with explicit empty string input vs try it online without any input.
> 2 votes

# Answer
# Charcoal, 33 bytes

```
⊞υＳＦυＦABＦACＦ⌕Ａι⁺κλ⊞υΦι∧⁻ξμ⁻ξ⊕μ¬⌊υ

```

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

```
⊞υＳ

```

Start a breadth-first search with the input string.

```
Ｆυ

```

Loop over all of the found strings.

```
ＦABＦAC

```

Loop over `AB`, `AC`, `BA` and `BC`.

```
Ｆ⌕Ａι⁺κλ

```

Loop over all of the indices of those substrings in the string being considered.

```
⊞υΦι∧⁻ξμ⁻ξ⊕μ

```

Push the string with the substring at that index removed to the list of strings to consider.

```
¬⌊υ

```

See whether we were able to end up with the empty string.
> 2 votes

# Answer
# Scala, 74 bytes

Golfed version. Try it online!

```
f={case(x::y,z)=>(x<'C'&f(y,z+1))|(x!='B'&z>0&f(y,z-1));case(Nil,z)=>z==0}

```

Ungolfed version. Try it online!

```
object Main {

  def f(chars: List[Char], z: Int): Boolean = chars match {
    case x :: y =>
      (x < 'C' && f(y, z + 1)) || (x != 'B' && z > 0 && f(y, z - 1))
    case Nil => z == 0
  }

  def main(args: Array[String]): Unit = {
    val testcases = List(
      ("AA", true),
      ("CBAA", false),
      ("CBBB", false),
      ("BCCA", false),
      ("CCAC", false),
      ("ABAC", true),
      ("ACAB", false),
      ("AAAC", true),
      ("BBAC", true),
      ("CABC", false),
      ("CCAB", false)
    )

    for ((i, e) <- testcases) {
      val result = f(i.toList, 0)
      println(if (result == e) "v" else "x", result)
    }
  }

}

```
> 2 votes

# Answer
# K (ngn/k), ~~43~~ ~~41~~ ~~36~~ 29 bytes

```
~&/0{(0>)_,/x+/:1-2*&2 2\-y}/

```

Try it online!

-2 bytes : Better lookup
-5 bytes : Even better thanks to @ngn
-7 bytes : Fairly sizeable overhaul by @ngn (go team ngn/k!!)
> 2 votes

---
Tags: code-golf, decision-problem, balanced-string
---


title: ASCII Expansion

text:
# Question
Title: ASCII Expansion
# Introduction

Every number can be represented as ASCII. For example, \\$0\\$ comes in ASCII is \\$48\\$, \\$1\\$ is \\$49\\$, and so on. Using this method of translating numbers to other numbers, it is possible to infinitely expand a number, by replacing all its digits with their ASCII values and doing the same for the result. For example, if you started with \\$0\\$, you would expand to \\$48\\$, then to \\$5256\\$, and so on.

# Challenge

* You will be given a single digit and a number as input. You can assume the digit will be in the range \\$0-9\\$, or \\$48-57\\$ in ASCII. You can assume the digit will always be of length 1, and will be a string. The number will always be a positive integer, greater than -1. If it is 0, you do not expand at all. Other than that, there are no guarantees about its value. If, and only if your language has no method of input, you may store the input in two variables or in a list.
* You must output the ASCII expansion of the digit if you expand it \\$n\\$ times, n being the number that was the input. If your language has no method of output, you may store it in a variable.

# Example I/O

* `Digit = 0, N = 3`

`Output = 53505354`
* `Digit = 2, N = 2`

`Output = 5348`
* `Digit = 5, N = 0`

`Output = 5`

# Rules

This is , so shortest answer (in bytes) wins!

# Answer
> 11 votes
# Perl 6, 28 bytes

```
{($^a,*.ords.join...*)[$^b]}

```

Try it online!

### Explanation:

```
{                          }  # Anonymous codeblock
 (               ...*)[$^b]   # Index into an infinite list
  $^a,                        # Starting from the given number
      *                       # Where each element is
       .ords.join             # The ordinal values joined

```

# Answer
> 8 votes
# 05AB1E, 3 bytes

```
FÇJ

```

Takes `N` as first input and the digit as second.

Try it online or verify all test cases.

**Explanation:**

```
F    # Loop the (implicit) first input (N) amount of times
 Ç   #  Convert the characters in the string at the top of the stack to its unicode values
     #  (which will take the second input implicitly in the first iteration)
  J  #  Join these unicode integers together to a single string
     # (after the loop, the result is output implicitly)

```

# Answer
> 6 votes
# Python 2, 55 bytes

```
f=lambda s,n:f(`ord(s[0])`,n-1)+f(s[1:],n)if n*s else s

```

Try it online!

---

**56 bytes**

```
lambda s,n:eval("''.join(`ord(c)`for c in"*n+" s"+")"*n)

```

Try it online!

Generates and evaluates monstrosities like:

```
''.join(`ord(c)`for c in''.join(`ord(c)`for c in''.join(`ord(c)`for c in s)))

```

---

**56 bytes**

```
f=lambda s,n:s*0**n or''.join(`ord(c)`for c in f(s,n-1))

```

Try it online!

# Answer
> 5 votes
# Brachylog, 7 bytes

```
{ṫạc}ⁱ⁾

```

Try it online!

```
{   }ⁱ     Repeat
 ṫ         stringifying,
  ạ        converting to a list of codepoints,
   c       and concatenating
      ⁾    a number of times equal to the last element of the input.

```

# Answer
> 5 votes
# Jelly, ~~7~~ 5 bytes

```
ṾOVƊ¡

```

Try it online!

-2 bytes after a friend helped me figure out what's wrong with `O`

For some reason, to run all test cases with a footer, an extra byte is required for the explicit  nilad: Try it online!

```
Ṿ        Stringify the input
 O       and convert each character to a codepoint,
  V      then concatenate them and eval the result,
   Ɗ¡    repeated a number of times equal to the right argument.

```

# Answer
> 5 votes
# , ~~14~~ 13 bytes

```
[:,":@u:~"+&3

```

Try it online!

### How it works

The "bind" operator `&` is commonly used to bind a constant to a dyad, so that it can be used as a monad. However, the same form can be used as a dyad: `x n&v y` (where `n` is a noun and `v` is a dyadic verb) or `x v&n y` applies monadic `n&v` or `v&n` to `y` **repeatedly `x` times**. Using this feature, we can design the target function like this:

```
x some_constant&some_dyad y
run `some_constant some_dyad y` x times
... or ...
x some_dyad&some_constant y
run `y some_dyad some_constant` x times

```

In this case, there is an obvious choice for the `some_constant`, which is `3` for `3 u: y`.

And here goes the full explanation:

```
[:,":@u:~"+&3
           &   Apply this function x times...
      u:~   3  Convert chars of y to ASCII values (3 u:)
   ":@   "+    Convert each number back to string
[:,            Flatten the array to get a single string

```

# Answer
> 4 votes
# Ruby, 30 bytes

```
->s,n{n.times{s=s.bytes*''};s}

```

Try it online!

# Answer
> 4 votes
# JavaScript (ES6),  ~~43~~  40 bytes

*Thanks to @tsh for reminding me that I didn't use currying this time :p (-3 bytes)*

Takes input as `(N)(digit)`.

```
n=>g=k=>n--?g(k.replace(/./g,c=>c^48)):k

```

Try it online!

### How?

This is a simple recursive function. The only trick in there is `c^48`. Because `c` is a string, we need to coerce it to an integer. We could do `+c+48`, but that would be 1 byte longer. Using a bitwise XOR is safe here, as \\$48\\$ is \\$110000\_2\\$ and `c` is less than \\$10000\_2\\$.

# Answer
> 4 votes
# C# (.NET Core), ~~174~~ 147 bytes

```
class Z{static void Main(string[] a){for(int n=int.Parse(a[1]);n-->0;){var x="";foreach(char c in a[0])x+=c-0;a[0]=x;}System.Console.Write(a[0]);}}

```

Big help from Jo King.

Try it online!

# Ungolfed

```
class Z
{
   static void Main(string[] a)
    {
        int n = int.Parse(a[1]);
        for (; n-- > 0;)
        {
            var x = "";
            foreach (char c in a[0])
                x += c - 0; //c-0 gets converted to int, and then the int is
                                   //automatically converted to a string
            a[0]=x;
        }
        System.Console.Write(a[0]);
    }
}

```

# Answer
> 3 votes
# Python 2, ~~63~~ 57 bytes

```
f=lambda i,n:n and f(''.join(`ord(c)`for c in i),n-1)or i

```

Try it online!

-6 bytes due to Jonathan Allan noting that the input can be a string.

Takes input as single digit string and an integer number of repetitions.

# Answer
> 3 votes
# Haskell, ~~30~~ ~~35~~ 30 bytes

```
(!!).iterate(>>=show.fromEnum)

```

Try it online!

+5 then -5 bytes from Jo King clarifying the rules and then working it into pointfree.

My first Haskell golf so I've probably done something horribly wrong. In addition to having misspelled golf, I tried to import `ord` without putting it in my byte count!

```
    .                             The composition of
     iterate                      infinitely iterating, starting with the argument,
            (>>=             )    concatenating the results of mapping
                show              finding the string representation of
                    .fromEnum     the codepoint of the argument,
(!!)                              with indexing into the resulting infinite list.

```

# Answer
> 3 votes
# Japt `-h`, 5 bytes

```
VÆ=mc

```

Try it

```
VÆ=mc   V = number of times, U = digit
VÆ      V times do: (Collects each result into an array)
  =mc     Map every digit of U to it's ASCII value, and make that the new U
-h      Take last element

```

# Answer
> 3 votes
# Perl 5, 22 bytes

```
eval's/./ord$&/ge;'x<>

```

Try it online!

# Answer
> 3 votes
# , 18 bytes

```
([:,3":@u:"0])@[&0

```

Try it online!

From the J dictionary:

> The phrase x f@\[&0 y is equivalent to f^:x y , apply the monad f x times to y.

That is, it's a shortcut for power of `^:` applied as many times as the left arg. Which explains the

```
(  )@[&0

```

part of the code. Now for what's in the parentheses:

`3 u:]` converts to a unicode code point, but unfortunately has infinite rank, and we want to apply it with 0 rank, hence the added `"0`. The code point is a number, and we convert it back to a string with format `":`. Finally, we flatten `,` this list of strings.

# Answer
> 3 votes
# K (oK), ~~13~~ 9 bytes

-4 bytes thanks to ngn

```
(,/$`i$)/

```

Try it online!

# Answer
> 3 votes
# PowerShell, ~~51~~ 49 bytes

 -2 bytes thanks to mazzy

```
param($s,$n),1*$n|%{$s=-join($s|% t*y|%{+$_})};$s

```

Try it online!

# Answer
> 3 votes
# Bracmat, 63 bytes

```
get':%?a %?n&whl'(!n+-1:~<0:?n&str$vap$((=.asc$!arg).!a):?a)&!a

```

Try it online!

# Answer
> 2 votes
# Haskell, 30 bytes

```
(!!).iterate(show.fromEnum=<<)

```

Try it online!

# Answer
> 2 votes
# Charcoal, 9 bytes

```
ＦＮ≔⭆η℅κηη

```

Try it online! Link is to verbose version of code. Takes `N` as the first input and the digit as the second input. Explanation:

```
ＦＮ

```

Repeat `N` times...

```
≔⭆η℅κη

```

Map each character to its ordinal and concatenate.

```
η

```

Output the final result.

Sadly `ＦＮ≦℅ηη` doesn't work...

# Answer
> 2 votes
# Lua, 55 bytes

```
a,N=...for i=1,N do a=a:gsub('.',('').byte)end
print(a)

```

Try it online!

Take input as arguments. Explanation is fairly obvious.

# Alternative solution: Lua, 60 bytes

```
a,N=...for i=1,N do a=table.concat{a:byte(1,-1)}end
print(a)

```

Try it online!

# Answer
> 2 votes
# QuadR, 8 bytes

Translation of Nahuel Fouilleul's solution. Thanks to Veskah for pointing it out.

```
.
⎕UCS⍵M

```

Try it online!

`.` replace any character

`⎕UCS` with the Universal Character Set ordinal of the
`⍵M` Match

This is equivalent to the Dyalog APL expression `'.'⎕R{⍕⎕UCS⍵.Match}⍣⎕⊢⍞`. Try it online!

# Answer
> 2 votes
# Lua, 67 bytes

```
i=io.read d=i(1)for _=1,i()do
d=d:gsub(".",string.byte)end
print(d)

```

Try it online!

Let `d` be the digit we will transform (always of length 1, so we ask to read 1 character with `io.read(1)`). If `N > 0`, replace each character by its byte value. Return the digit.

# Answer
> 2 votes
# Thunno 2, 3 bytes

```
{CJ

```

Try it online!

#### Explanation

```
{CJ  # Implicit input
{    # Repeat N times:
 C   #  Get ASCII codes
  J  #  Join into a string
     # Implicit output

```

# Answer
> 1 votes
# Wolfram Language (Mathematica), 41 bytes

```
""<>ToString/@ToCharacterCode@#&~Nest~##&

```

Try it online!

# Answer
> 1 votes
# APL (Dyalog Unicode), 16 bytes

```
{(∊⍕¨∘⎕UCS)⍣⍵⊢⍺}

```

Try it online!

Left input is a one-digit string, right input is the number of iteration. Returns the string representation of the result.

### How it works

```
{(∊⍕¨∘⎕UCS)⍣⍵⊢⍺}
{              }  Dyadic dfn, ⍺=digit string, ⍵=iteration
             ⊢⍺   Start with ⍺
 (        )⍣⍵     Repeat ⍵ times...
      ⎕UCS        Convert each char to Unicode codepoint
   ⍕¨∘            Convert each number back to string
  ∊               Enlist (flatten) all chars into one string

```

# Answer
> 1 votes
# PHP, 58 bytes

```
for([,$a,$b]=$argv;$b--;)$a=strtr($a,range(48,57));echo$a;

```

Try it online!

Input digit and number are two command arguments (`$argv`) in same order.

### Comented

```
for(
  [,$a,$b]=$argv;  // $a is input digit and $b is number
  $b--;            // loop $b times
)
  $a=              // set $a to
    strtr(         // strtr in array mode, replaces keys with values
      $a,          // replace in $a itself
      range(48,57) // an array with keys 0...9 and values 48...57
    );
echo$a;            // at the end, output $a

```

# Answer
> 1 votes
# C# (Visual C# Interactive Compiler), 55 bytes

```
a=>b=>{for(;b-->0;a=a.SelectMany(l=>l-0+""));return a;}

```

Try it online!

# Answer
> 1 votes
# Python 3, ~~69~~ 60 bytes

```
f=lambda n,i:i and f(''.join(str(ord(c))for c in n),i-1)or n

```

Try it online!

# Answer
> 1 votes
# Icon, ~~72~~ 63 bytes

Inspired by @xnor's Python 2 solution

```
procedure f(d,n)
return(*d*n<1&d)|f(48+!d,n-1)||f(d[2:0],n)
end

```

Try it online!

# Answer
> 1 votes
# Red, ~~62~~ 57 bytes

```
func[d n][loop n[parse d[any[change p: skip(0 + p/1)]]]d]

```

Try it online!

Explanation:

```
f: func [ d n ] [                  ; a function with 2 parameters
    loop n [                       ; repeat n times
        parse d [                  ; parse the string with the following rules
            any [                  ; one ore more
                change p: skip     ; change any string with length 1 (a single digit)
                (0 + p/1)          ; with its representation as a number 48..57
            ]
        ]
    ]
    d                              ; return the altered string
]

```

# Answer
> 1 votes
# Retina, 21 bytes

```
.+¶

"$+"+`.
$.(*_48*

```

Try it online! Takes `N` as the first input and the digit as the second input. Explanation:

```
.+¶

```

Delete `N` from the output.

```
"$+"+`

```

Repeat `N` times.

```
.
$.(*_48*

```

Replace each digit with its ASCII code.

# Answer
> 1 votes
# C (gcc), 88 bytes

Thanks ceilingcat and peter cordez for their contributions.

```
z(v,n){for(sprintf(o,"%d",v);n--;)for(strcpy(t,o),v=0;t[v];)sprintf(o+v++*2,"%d",t[v]);}

```

Try it online!

# Answer
> 1 votes
# Zsh, 55 bytes

```
(($2*#1))&&<<<`$0 $[#1] $[$2-1]``$0 "${1:1}" $2`||<<<$1

```

Try it online!

A port of @xnor's Python 2 solution, it came in just two bytes below my first solution. We require quotes around `${1:1}`, otherwise it is removed when empty, turning `$2` into `$1` on the recursive call.

---

If the repeated expansion never grows past 2^63, **53 bytes** with a recursive math function:

```
(){s=
for c (${(s::)1})s+=$[#c]
(($2?$0(s,$2-1):$1))}

```

Try it online!

# Answer
> 1 votes
# dc, 64 bytes

```
dsi[A~48+lrZAr^*lr+srdZ1<P]sP[0srA*lPxlPxlrI3^/li1-dsi0<M]sM0<Mp

```

Try it online!

I wouldn't be surprised if I could golf this down a bit. It's more verbose than anticipated due to handling a lot of edge cases, etc. Put the 'digits' to transform on the stack first, then the number of iterations.

`dsi` stores the number of iterations in `i`. Macro `P` does one iteration of the transformation. `A~` to divide w/ remainder by 10, `48+` to give us ASCII. Variable `r` holds our result. `lrZAr^*` loads this variable for the sake of finding how many digits it currently has. It shifts our ASCII value left (decimal) this many places (48 becomes 4800), then `lr+sr` adds our old value `r` and stores the result back into `r`. Here's tricky situation number one: `dZ1<P` says to keep running `P` as long as our source material is at least one digit. But, we need to do a final run when we hit 1 digit as well.

Macro `M` is our main. `0sr` initializes `r` to 0, and then... the rest of this I'm going to explain a bit out of order. For each iteration, we need to run `P` twice, because of the aforementioned single-digit thing. So, `lPxlPx`. However, this screws us up when our original value is only a single digit. Plus, we often get left with an extra 0 at the right side. `A*` multiplies the original by ten, and `I3^/` at the end divides by a thousand. This is pretty goofy, but it ensures all values work ok. `li1-dsi0<M` keeps running `M` until `i`, our number of iterations, is complete. We can't do `dsMx` as per usual to save & run a macro, because this won't work if our number of iterations is 0. So we test for that, leaving us with the longer `sM0<M`. Finally, we `p`rint.

# Answer
> 1 votes
# Wren, 54 bytes

One iteration is simply `x.bytes.join()`....

```
Fn.new{|x,y|
for(i in 1..y)x=x.bytes.join()
return x
}

```

Try it online!

# Answer
> 1 votes
# Vyxal, 5 bytes

```
(SCfṅ

```

Try it Online!

```
(     # Input times...
 S    # Stringify
  C   # Charcodes
   fṅ # Join together (Should just be ṅ, but bugs)

```

# Answer
> 1 votes
# J-uby, 20 bytes

Takes curried arguments with \\$n\\$ first and \\$digit\\$ second, i.e. `F[n][digit]`.

```
:**&(S|:bytes|:join)

```

Attempt This Online!

## Explanation

The function `S|:bytes|:join` converts to a string, gets the character codes, then joins them. The `:**` operator applies that function \\$n\\$ times.

# Answer
> 1 votes
# Setanta, ~~106~~ 94 bytes

```
gniomh(d,n){le i idir(0,n){i=""le j idir(0,fad(d)){i+=go_teacs(48+go_uimh(d[j]))}d=i}toradh d}

```

Requires `d` to be passed in as a string.

Try it here!

# Answer
> 1 votes
# V (vim), 20 bytes

```
ÀñÓ./½submatch(0)+48

```

Try it online!

Input is given as buffer input and an argument. It runs `:s/./\=submatch(0)+47/g` the arg number of times

# Answer
> 1 votes
# Racket, 110 bytes

```
(define(a x n)(if(< n 1)x(a(string->number(string-join(for/list([c(~a x)])(~a(char->integer c)))""))(- n 1))))

```

Try it online!

Also, as a bonus, it works with bigger numbers as well! For example: `(a 11 3)` and `(a 123456789 10)` (this gives a number with 9216 digits) are both valid inputs.

---

## Explanation

1. We receive two inputs `x` (the number to expand) and `n` the number of expansions.
2. If `n` is less than 1, we return `x` as is.
3. We iterate through all the digits of `x` by converting `x` to a string. During each iteration, we obtain the string representation of each digit's ASCII value and append it to the list.

1. `for/list` handle all list appending for us, so all we need to do is return the string at the end of the iteration.
4. Once the list is obtained, we join it to a string without any spaces between all the values.
5. We convert the final string back into a number, pass it to step 1 as the new `x` and pass `n - 1` as the `n` argument.

1. Repeat steps 1-5 until step 2 is executed.

```
(define (expand-to-ascii x n)
  (if (< n 1)
      x
      (a (string->number
           (string-join
             (for/list ([c (~a x)])
               (~a (char->integer c)))
             ""))
         (- n 1))))

```

*Have an awesome week ahead!*

# Answer
> 1 votes
# Factor, 33 bytes

```
[ [ [ >dec ] map-concat ] times ]

```

Attempt This Online!

* `[ ... ] times` call `[ ... ]` the number of times denoted by the number on top of the stack
* `[ >dec ] map-concat` map over each character in a string, convert it to a string, and flatten

# Answer
> 0 votes
# Gema, 57 characters

```
* *=@set{d;*}@repeat{*;@set{d;@x{$d}}}$d
x:?=@char-int{?}'

```

Sample run:

```
bash-5.0$ echo -n '0 3' | gema '* *=@set{d;*}@repeat{*;@set{d;@x{$d}}}$d;x:?=@char-int{?}'
53505354

```

Try it online!

# Answer
> 0 votes
# Husk, 9 bytes

```
~!ȯ¡ṁosc→

```

Try it online!

Mostly a translation of the Haskell answer, with some combinator stuff thrown in to deal with 1-indexing.

```
 !           Index into
  ȯ¡         the infinite list of iterations of
    ṁ        concat-mapping
      s      show
     o       .
       c     ord
~            starting with the first argument, and with the index being the second argument
        →    incremented.

```

# Answer
> 0 votes
# Ceylon, 75

```
String?x(String d,Integer n)=>loop(d)((s)=>"".join(s*.hash)).skip(n).first;

```

Try it online!

Here is the long version, which might be more understandable:

```
"""convert a string of digits (or other characters) into a string of the digits'
   ASCII values, represented themselves as decimal ASCII digits (without any
   separator).
"""
String asciify(String input) {
    // maps each character of the string into its ASCII value (actually unicode,
    // but that's the same for the relevant range), and this to decimal digits.
    {String*} asciiDecimals = input.map((Character c) => c.integer.string);
    // concatenate all those strings
    return String.sum(asciiDecimals);
}

"""expand a digit (or a string) into its ASCII representation several times."""
String asciiExpand(String digit, Integer times) {
    // infinite (lazy) list of all the expansions
    {String*} allExpansions = loop(digit)(asciify);
    // take the entry `times` steps from the first.
    return allExpansions.getFromFirst(times)
          // If that is null (which can't happen, as we have an infinite list),
          // throw an exception instead.
          else nothing;
}

```

Tricks used to make it shorter:

* one-letter function and variable names
* no comments/doc-strings
* inline the intermediate `{String*}` variables
* use the fat-arrow syntax (`=>`) instead of blocks with just one `return` for the functions
* inline the `asciify` function → then we can use type interference, and don't need to write `String` again for parameter and return type
* use `"".join(...)` instead of `String.sum(...)`. Possibly a bit less efficient, but a slightly shorter (+ next point).
* `join` takes an iterable of *any* objects, not just strings, and will apply `.string` on each element, so we don't need to write down `.string` ourselves.
* use `.hash` instead of `.integer` to get the ASCII/Unicode values – Character's hash code happens to be implemented just the right way.
* replace `s.map((Character c)=>c.hash)` with `s*.hash` (a spread attribute) – the first one is lazy (returns an iterable), the second one is non-lazy (returns a sequence – it's the equivalent for `s.collect(...)`), but this difference doesn't matter here (as we join the strings shortly after anyways), and the second one is a lot shorter.
* replace `.getFromFirst(n)` with the slightly shorter `.skip(n).first`. (This might get a different result for negative `n`, but those are outside of the specified input range anyways.)
* instead of adding `else nothing` for the return (to convince the compiler that this is not nullable), we can just declare the nullable return type `String?`. It won't happen anyways for valid inputs.
* remove non-essential whitespace

I also thought I found a shorter way of writing this (which works for finite iterables), but it actually doesn't work here, because `loop` returns an infinite iterable, and trying to convert it into a sequence (with `[* ... ]`)will run forever until it runs out of memory:

```
String?y(String d, Integer n)=>[*loop(d)((s)=>"".join(s*.hash))][n];

```

# Answer
> 0 votes
# Arturo, 46 bytes

```
$=>[&do.times:&->join to[:integer]to[:char]<=]

```

Try it!

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