# Question
Title: Write a program to display directory treehouse
Given a directory (such as `C:/`), given from stdin or read from a file, produce a directory tree, with each file/folder indented based on its depth.

### Example

If I have a `C:/` drive which only contains two folders `foo` and `bar`, and `bar` is empty while `foo` contains `baz.txt`, then running with input `C:/` produces:

```
C:/
    bar/
    foo/
        baz.txt

```

while running with input `C:/foo/` should produce

```
foo/
    baz.txt

```

As this is codegolf, lowest byte count wins. The file extensions (such as `baz.txt`) are optional. Extra notes: hidden files can be ignored, directories must actually exist, it can be assumed that files do not contain unprintable characters or new lines but all other printable ASCII characters are fine (file names with spaces must be supported). Output can be written to file or stdout. The indentations can be made up of either a tab character or 4 spaces.

# Answer
> 10 votes
## bash, ~~61~~ ~~58~~ 54 bytes

```
find "$1" -exec ls -Fd {} \;|perl -pe's|.*?/(?!$)|  |g'

```

Takes input as a command line argument, outputs on STDOUT.

Note that the spaces near the end before the `|g` are actually a tab character (SE converts them to spaces when displaying posts).

```
find              crawl directory tree recursively
"$1"              starting at the input directory
-exec             and for each file found, execute...
ls -Fd {} \;      append a trailing slash if it's a directory (using -F of ls)
|perl -pe         pipe each line to perl
'
s|                replace...
.*?/              each parent directory in the file's path...
(?!$)             that doesn't occur at the end of the string...
|    |            with a tab character...
g                 globally
'

```

Thanks to @Dennis for 4 bytes!

# Answer
> 2 votes
# Dyalog APL, 48 bytes

```
(⊂∘⊃,1↓'[^\\]+\\'⎕R'    ')r[⍋↑r←⎕SH'dir/s/b ',⍞]

```

prompt for character input

`'dir/s/b ',` prepend text

`⎕SH` execute in shell

`r←` store in *r*

make list of strings into character matrix

indices for ascending sorting

`r[`...`]` reorder *r* \[sorted\]

`(`...`)` on the standard out of the shell command, do:

`'[^\\]+\\'⎕R' '` regex replace backslash-terminated runs of non-backslashes by four spaces

`1↓` drop the first line

`⊂∘⊃,` prepend the enclosed first \[line\]

Result of inputting "\tmp" to the prompt begins as follows on my computer:

```
C:\tmp\12u64
            keyboards64.msi
            netfx64.exe
            setup.exe
            setup_64_unicode.msi
            setup_dotnet_64.msi
        AdamsReg.reg
        AdamsReg.zip
        qa.dws
        ride-experimental
            win32
                d3dcompiler_47.dll
                icudtl.dat
                libEGL.dll

```

# Answer
> 2 votes
## SML, 176 bytes

```
open OS.FileSys;val! =chDir;fun&n w=(print("\n"^w^n);!n;print"/";c(openDir(getDir()))(w^"\t");!"..")and c$w=case readDir$of SOME i=>(&i w handle _=>();c$w)|x=>()fun%p=(&p"";!p)

```

Declares (amongst others) a function `%` which takes a string as argument. Call with `% "C:/Some/Path";` or `% (getDir());` for the current directory.

I'm using the normally rather functionally used language StandardML whose `FileSys`-Library I discovered after reading this challenge.

The special characters `!`, `&`, `$` and `%` have no special meaning in the language itself and are simply used as identifiers; however they can't be mixed with the standard alphanumeric identifiers which allows to get rid of quite some otherwise needed spaces.

```
open OS.FileSys;
val ! = chDir;                       define ! as short cut for chDir

fun & n w = (                        & is the function name
                                     n is the current file or directory name
                                     w is a string containing the tabs
    print ("\n"^w^n);                ^ concatenates strings
    ! n;                             change in the directory, this throws an
                                     exception if n is a file name
    print "/";                       if we are here, n is a directory so print a /
    c (openDir(getDir())) (w^"\t");  call c with new directory and add a tab to w
                                     to print the contents of the directory n
    ! ".."                           we're finished with n so go up again
)
and c $ w =                          'and' instead of 'fun' must be used
                                     because '&' and 'c' are mutual recursive
                                     $ is a stream of the directory content
    case readDir $ of                case distinction whether any files are left
        SOME i => (                  yes, i is the file or directory name
            & i w handle _ => ();    call & to print i an check whether it's a
                                     directory or not, handle the thrown exception
            c $ w )                  recursively call c to check for more files in $
        | x    => ()                 no more files, we are finished

fun % p = (                          % is the function name,
                                     p is a string containing the path
    & p "";                          call & to print the directory specified by p
                                     and recursively it's sub-directories
    ! p                              change back to path p due to the ! ".." in &
)

```

Can be compiled like this with SML/NJ or with Moscow ML\* by prefixing with `load"OS";`.

\*See `mosml.org`, can't post more than 2 links.

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

```
namespace System.IO{class P{static int n;static void Main(String[]a){Console.WriteLine(new string('\t',n++)+Path.GetFileName(a[0]));try{foreach(var f in Directory.GetFileSystemEntries(a[0])){a[0]=f;Main(a);}}catch{}n--;}}}

```

Try it online!

---

The ungolf:

```
using System.IO;
using System;

class P
{
    static int n=0;
    static void Main(String[] a)
    {
        for (int i=0;i<n;i++) Console.Write("\t");
        Console.WriteLine(Path.GetFileName(a[0]));
        n++;

        if(Directory.Exists(a[0]))
            foreach (String f in Directory.GetFileSystemEntries(a[0]))
                Main(new String[]{f});
        n--;
    }
}

```

First time I ever recursed a `Main` function!

I believe a person that has fresher knowledge of C# can golf it more, as I didn't program on C# for some time!

# Answer
> 0 votes
## Batch, 237 bytes

```
@echo off
echo %~1\
for /f %%d in ('dir/s/b %1')do call:f %1 %%~ad "%%d"
exit/b
:f
set f=%~3
call set f=%%f:~1=%%
set i=
:l
set i=\t%i%
set f=%f:*\=%
if not %f%==%f:*\=% goto l
set a=%2
if %a:~0,1%==d set f=%f%\
echo %i%%f%

```

Where \t represents the literal tab character. This version includes trailing `\`s on directories but 41 bytes can be saved if they are not needed.

# Answer
> 0 votes
# PHP, 180 bytes

* first argument: path must have a trailing slash (or backslash)
* second argument: level defaults to `NULL` and will be interpreted as `0` by `str_repeat`; will throw a warning if not provided

```
function d($p,$e){$s=opendir($p);echo$b=str_repeat("\t",$e++),$e?basename($p)."/":$p,"
";while($f=readdir($s))echo preg_match("#^\.#",$f)?"":is_dir($p.$f)?d("$p$f/",$e):"$b\t$f
";}

```
* displays hidden files and directories, but does not recurse hidden directories
add parentheses around `is_dir(...)?d(...):"..."` to remove hidden entries from output (+2)
replace `"#^\.#"` with `#^\.+$#` to display/recurse hidden entries but skip dot entries (+2)
* may throw errors when directories are nested too deep. Insert `closedir($s);` before the final `}` to fix (+13)
* will fail if a directory contains an entry with no name, prepend `false!==` to the while condition to fix (+8)

**with glob, 182 bytes** (probably 163 in future php)

```
function g($p,$e){echo$b=str_repeat("\t",$e),$e++?basename($p)."/":$p,"
";foreach(glob(preg_replace("#[*?[]#","[$1]",$p)."*",2)as$f)echo is_dir($f)?g($f,$e):"$b\t".basename($f)."
";}

```
* does not display or recurse hidden files/directories
* `2` stands for `GLOB_MARK`, will append a slash to all directory names, as does `ls -F`
* the `preg_replace` escapes glob special characters
I could have abused `preg_quote` for this (-19); but that would fail on Windows systems, as the backslash is the directory separator there.
* php *may* soon include a function glob\_quote, which will allow the same golfing as `preg_quote` and work on all systems.

**with iterators, 183 bytes**
(well, not purely iterators: I used implicit `SplFileInfo::__toString()` to golf `$f->getBaseName()` and `$f->isDir()` to the old PHP 4 functions.)

```
function i($p){echo"$p
";foreach($i=new RecursiveIteratorIterator(new RecursiveDirectoryIterator($p),1)as$f)echo str_repeat("\t",1+$i->getDepth()),basename($f),is_dir($f)?"/":"","
";}

```
* no trailing slash required
* displays and recurses hidden entries (`ls -a`)
* insert `,4096` or `,FilesystemIterator::SKIP_DOTS` before `),1` to skip dot entries (+5) (`ls -A`)
* flag `1` stands for `RecursiveIteratorIterator::SELF_FIRST`

# Answer
> 0 votes
# PowerShell, 147 bytes

```
param($a)function z{param($n,$d)ls $n.fullname|%{$f=$_.mode[0]-ne"d";Write-Host(" "*$d*4)"$($_.name)$(("\")[$f])";If(!$f){z $_($d+1)}}}$a;z(gi $a)1

```

Man, I feel like PS should be able to do something like the bash answer, but I'm not coming up with anything shorter than what I've got here.

Explanation:

```
param($a)                     # assign first passed parameter to $a
function z{param($n,$d) ... } # declare function z with $n and $d as parameters
ls $n.fullname                # list out contents of directory
|%{ ... }                     # foreach
$f=$_.namde[0]-ne"d"          # if current item is a file, $f=true
Write-Host                    # writes output to the console
(" "*$d*4)                    # multiplies a space by the depth ($d) and 4
"$($_.name)$(("\")[$f])"      # item name + the trailing slash if it is a directory
;if(!$f){z $_($d+1)}          # if it is a directory, recursively call z
$a                            # write first directory to console
z(gi $a)1                     # call z with $a as a directoryinfo object and 1 as the starting depth

```

# Answer
> 0 votes
# Python 2, 138 bytes

Modified from this SO answer. Those are tabs for indentation, not spaces. Input will be taken like `"C:/"`.

```
import os
p=input()
for r,d,f in os.walk(p):
    t=r.replace(p,'').count('/');print' '*t+os.path.basename(r)
    for i in f:print'   '*-~t+i

```

**Try it online** \- *It's pretty interesting that I'm allowed to browse the directory on Ideone...*

Same length:

```
from os import*
p=input()
for r,d,f in walk(p):
    t=r.replace(p,'').count(sep);print' '*t+path.basename(r)
    for i in f:print'   '*-~t+i

```

# Answer
> 0 votes
# Tcl, 116 bytes

```
proc L f {puts [string repe \t [expr [incr ::n]-1]][file ta $f];lmap c [glob -n -d $f *] {L $c};incr ::n -1}
L $argv

```

Try it online!

# Answer
> 0 votes
# Perl, 89 bytes

It's useful when there's a find module in the core distribution. Perl's File::Find module does not traverse the tree in alphabetic order, but the spec didn't ask for that.

```
/usr/bin/perl -MFile::Find -nE 'chop;find{postprocess,sub{--$d},wanted,sub{say" "x$d.$_,-d$_&&++$d&&"/"}},$_'

```

The script proper is 76 bytes, I counted 13 bytes for the command-line options.

# Answer
> 0 votes
# Java 8, 205 bytes

```
import java.io.*;public interface M{static void p(File f,String p){System.out.println(p+f.getName());if(!f.isFile())for(File c:f.listFiles())p(c,p+"\t");}static void main(String[]a){p(new File(a[0]),"");}}

```

This is a full program submission which takes input from its first command-line argument (not explicitly permitted, but done by many others) and prints output to standard out.

Try It Online (note different interface name)

## Ungolfed

```
import java.io.*;

public interface M {
    static void p(File f, String p) {
        System.out.println(p + f.getName());
        if (!f.isFile())
            for (File c : f.listFiles())
                p(c, p + "\t");
    }

    static void main(String[] a) {
        p(new File(a[0]), "");
    }
}

```

---
Tags: code-golf, string, file-system
---


title: Count the Matchsticks

text:
# Question
Title: Count the Matchsticks
Most people here are familiar with seven segment displays, which are also used in matchstick puzzles. Below are the digits `0` through `9` and letters `a` through `z`, except `k,m,t,v,w`, written in this format.

```
 _        _   _         _    _    _    _    _
| |   |   _|  _|  |_|  |_   |_     |  |_|  |_|
|_|   |  |_   _|    |   _|  |_|    |  |_|   _|

 _       _      _  _  _                        _   _      _               _
|_| |_  |   _| |_ |_ |   |_  |   | |   _   _  |_| |_|  _ |_      |_| |_|  _|
| | |_| |_ |_| |_ |  |_| | | | |_| |_ | | |_| |     | |   _| |_| | |   | |_

```

The challenge here is simple. Given an input string, output the number of matchsticks required to represent that string. If the string contains a character outside of the above representation, ignore it (count it as 0).

For example, for input `53`, a total of `10` matchsticks are required, `5` for the `5` and `5` for the `3`, so the output is `10`.

For input `hello` a total of `19` matchsticks are required, `h (4), e (5), l (3), l (3), o (4)`, so the output is `19`.

For clarity, here are the matchsticks required to build each character:

```
0 -> 6
1 -> 2
2 -> 5
3 -> 5
4 -> 4
5 -> 5
6 -> 6
7 -> 3
8 -> 7
9 -> 6
a -> 6
b -> 5
c -> 4
d -> 5
e -> 5
f -> 4
g -> 5
h -> 4
i -> 2
j -> 4
l -> 3
n -> 3
o -> 4
p -> 5
q -> 5
r -> 2
s -> 5
u -> 3
x -> 5
y -> 4
z -> 5

```

Now for the twist, and there are two of them.

* The first is that the input is considered case-*in*sensitive. That is, `A` and `a` should both count for `6` matchsticks, even though the visual representation looks like an uppercase `A`.
* Your score is your source code run through this algorithm, plus the length of your source code in bytes, lower is better. For example, if your source code was `abc123`, your score would be `6+5+4+2+5+5 = 27 + 6 = 33`. If your source code was `#&@()*`, your score would be `0 + 6 = 6`.

### Input/Output Examples

```
0    -> 6
53   -> 10
111  -> 6
112  -> 9
8888 -> 28
hello -> 19
PPCG  -> 19
Programming Puzzles & Code Golf -> 99
#&()mt!!~ -> 0
*DḌƤÆE%Ḅċ0 -> 16

```

## Rules

* If applicable, you can assume that the input/output will fit in your language's native Integer type.
* The input and output can be given by any convenient method.
* Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
* Standard loopholes are forbidden.

# Answer
# Python 2, 97 bytes + 237 matches = 334

```
lambda w:sum(map(('1ir'*2+'7lnu'*3+'4cfhjoy'*4+'235bdegpqsxz'*5+'069a'*6+'8'*7).count,w.lower()))

```

Try it online!

This works by generating a string where each buildable character appears the same amount of matchsticks required to build that character
> 8 votes

# Answer
# JavaScript (ES6), 198 (102 bytes + 96 matchsticks)

*Saved 5 points thanks to @l4m2*

```
v=>[...v].map(w=>t+=('{w__^_{]|{{_^__^_^w^~]~]^__w_~]~~_^_'[parseInt(w,36)]+v).charCodeAt()%9,t=+[])|t

```

Try it online!

### How?

We use the ASCII code modulo 9 of characters that do not add any penalty to encode the numbers of matchsticks.

```
 char. | code | modulo 9
-------+------+-----------------
   ~   |  126 |   0
   v   |  118 |   1  (not used)
   w   |  119 |   2
   ]   |   93 |   3
   ^   |   94 |   4
   _   |   95 |   5
   {   |  123 |   6
   |   |  124 |   7

```

We do not have to worry about the case because `parseInt()` is case-insensitive.

For characters that do not match **\[0-9A-Za-z\]**, `parseInt()` returns `NaN` and the string lookup results in `undefined`. Once coerced to a string, `"undefined".charCodeAt()` returns the ASCII code of `"u"`, which is **117**. Conveniently, **117** modulo **9** gives **0** as expected.
> 6 votes

# Answer
## Perl 5 with `-pF`, 95 bytes + 14, 109

```
eval~"Û£ÔÂ„…ÊÏÉÎÍÍÊÌÊËËÊÊÉÉÈÌÇÈÆÉžÉÊœË›ÊšÊ™Ë˜Ê—Ë–Í•Ë“Ì‘ÌËÊŽÊÍŒÊŠÌ‡Ê†ËÂÐÑÐ˜‚ÒÁ„Ô“œ‚™¿¹"}{
```

This is equivalent to:

```
$\+={z506122535445566738796a6b5c4d5e5f4g5h4i2j4l3n3o4p5q5r2s5u3x5y4=~/./g}->{+lc}for@F

```

but using the `~` operator we can use high-byte characters and avoid a lot of characters without really sacrificing bytes.

Still quite a way off Ton's score, even with assistance!

Try it online!

This solution contains unprintables so here's a reversible hex dump to verify the byte-count:

```
00000000: 6576 616c 7e22 dba3 d4c2 8485 cacf c9ce  eval~"..........
00000010: cdcd cacc cacb cbca cac9 c9c8 ccc7 c8c6  ................
00000020: c99e c99d ca9c cb9b ca9a ca99 cb98 ca97  ................
00000030: cb96 cd95 cb93 cc91 cc90 cb8f ca8e ca8d  ................
00000040: cd8c ca8a cc87 ca86 cbc2 81d0 d1d0 9882  ................
00000050: d2c1 84d4 939c 8299 908d bfb9 227d 7b    ............"}{

```
> 6 votes

# Answer
# Jelly, 42 bytes + 0 matchsticks = 42 points

```
“ṄḟṭkɗØæ⁶ṡ“£ƈṠ¤żȥṬ}ė$t¿ƬⱮȷ|çƓ’×/ṚṚæ.ċÐ€ØW$

```

*Thanks to @JonathanAllan for -2 points!*

Try it online!

### How it works

```
“ṄḟṭkɗØæ⁶ṡ“£ƈṠ¤żȥṬ}ė$t¿ƬⱮȷ|çƓ’

```

Literals that begin with  and end with  split on , replace the remaining characters with their 1-based indices in Jelly's code page, then convert from bijective base 250 to integer.

This particular literal encodes

```
[3096734725226860846495, 211369264881118657055472842435156679693648].

```

`×/` reduces by multiplication, yielding

```
654554542403034552503005456545545424030345525030054562554563760

```

(Encoding this integer directly would save 6 bytes, but cost 28 matchsticks.)

`ṚṚ` reverses twice; the first call promotes an integer to its digit array. This yields

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

```

`ċÐ€ØW$` counts (`ċ`) the occurrences of each (`Ð€`) character of **"A...Za...z0...9\_"** (`ØW`) in the input string.

Finally `æ.` takes the dot product, multiplying each character count by the corresponding cost in matchsticks, then taking the sum.
> 5 votes

# Answer
# Jelly, 34 bytes + 3 matches = 37

```
⁽[ɱ×“®-&]Ṙṙ£⁺ÐĊṂⱮɼ ’‘ḤṚæ.ŒlċÐ€ØWṚƊ

```

A monadic link accepting a list of characters and returning an integer.

**Try it online!**

### How?

Works in a similar way to Dennis' Jelly answer but took enough effort that I feel it warrants another answer. The core difference is that it lower-cases the input for a cost of three matches (`Œl` contains an `l`) which then allows for a much smaller number to be used to create the cost array. The tricky bit was finding a way to construct that number without matches while staying concise.

`ØW` yields `"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_"` so counting lower-cased input occurrences always starts with 26 zeros. We can reverse this and perform a dot-product with an array of length 37 instead of one of length 63.

```
⁽[ɱ×“®-&]Ṙṙ£⁺ÐĊṂⱮɼ ’‘ḤṚæ.ŒlċÐ€ØWṚƊ - Link: list of characters
⁽[ɱ                                - literal                                     23913
    “®-&]Ṙṙ£⁺ÐĊṂⱮɼ ’               - literal         136861653160003879166772353166783
   ×                               - multiply  = 3272772712015172762515027281277281879
                    ‘              - increment = 3272772712015172762515027281277281880
                     Ḥ             - double    = 6545545424030345525030054562554563760
                      Ṛ            - reverse (implicit decimal list) -> [0,6,7,3,6,5,4,5,5,2,6,5,4,5,0,0,3,0,5,2,5,5,4,3,0,3,0,4,2,4,5,4,5,5,4,5,6]
                                   -                     (to align with: _ 9 8 7 6 5 4 3 2 1 0 z y x w v u t s r q p o n m l k j i h g f e d c b a)
                                 Ɗ - last four links as a monad:
                         Œl        -   lower-case (the input)
                              ØW   -   word -> "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_"
                            Ð€     -   map across right:
                           ċ       -     count (right character in lower-cased input)
                                Ṛ  -   reverse (to align with the values as shown above)
                       æ.          - dot-product

```
> 4 votes

# Answer
# Perl 5 `-p`, ~~90~~ 64 code + 9 eval harness + 14 matchsticks = 87

Replace the hex codes by their literal 1 byte variant (***not*** UTF-8 as TIO tries to) for the claimed score

```
eval~"\xdb\xa3\xd4\xc2\x86\xd0\xcf\xd2\xc6\x9e\xd2\x85\xd0\xc9\xcd\xca\xca\xcb\xca\xc9\xcc\xc8\xc9\xc9\xca\xcb\xca\xca\xcb\xca\xcb\xcd\xcb\xcf\xcc\xcf\xcc\xcb\xca\xca\xcd\xca\xcf\xcc\xcf\xcf\xca\xcb\xca\xd0\x8d\x99\x90\x8d\xdf\x93\x9c\xc2\x81\xd0\xd1\xc0\xd0\x98"}{

```

Try it online!

Code Inside the complemented string:

```
$\+=y/0-9a-z/625545637665455454240303455250300545/rfor lc=~/.?/g

```
> 3 votes

# Answer
# PHP 176 bytes = 397 score

```
<?$n="6255456376";$l="065455454240303455250300545";$a=strtolower($argv[1]);for($i=0;$i<strlen($a);$i++)$t+=(is_numeric($a[$i])?$n[$a[$i]]:$l[max((ord($a[$i])-96),0)]);echo$t;

```

Try it online!
> 2 votes

# Answer
# SOGL V0.12, 34 bytes \+ 18 = 52

```
ā⁄,u{²²z+;W"⁾o∫k9÷│>Γ{σ¬μ┼“'=υ─wι+

```

Try it Here!

Golfed, but not scoring as much:

```
0,u{²²z+;W"⁾o∫k9÷│>Γ{σ¬μ┼“8─wι+

```
> 2 votes

# Answer
# Ruby, 125 bytes + 87 matchsticks = 212

```
->m{v=->w,k{w.scan(/./).map &k};v[m,->t{v["!#&&;&=$(==&;&&;&;#;!$!$;&&#&!$!!&;&",->k{k.ord%11}][t.to_i 36].to_i+(t==?0?6:0)}].sum}

```

Try it online!

Heavily inspired by Arnauld's Javascript answer.

Normally the cost of declaring a lambda to be used only twice is not worth it, but the matchstick weight of "`scanap`" in `.scan(/./).map` changed that. This was a fun challenge!

```
->m{
  v=->w,k{w.scan(/./).map &k};                # v is a lambda taking a string and a block
  v[m,->t{                                    # Transform each char t of the input:
    v["!#&&;&=$(==&;&&;&;#;!$!$;&&#&!$!!&;&", # Transform each char of this magic string
      ->k{k.ord%11}                           #  into a matchstick count ([0,2,5,5,4,5...])
    ][t.to_i 36]+                             # Parse t as a base 36 index into the counts
    (t==?0?6:0)                               # If t was "0", add 6 matchsticks
  }].sum                                      # Add the counts for all characters
}

```
> 2 votes

# Answer
# R, 112 bytes + 319 matches = 431 score

```
sum(strtoi(el(strsplit(chartr("0-9a-z","625545637665455454240303455250300545",tolower(scan(,""))),""))),na.rm=T)

```

Try it online!

Kudos to Giuseppe who came up with this improvement.

Old version, 143 bytes + 454 matches = 597 score

```
b=el(strsplit(chartr("0123456789abcdefghijlnopqrsuxyz","6255456376654554542433455253545",tolower(readline())),""))
sum(as.numeric(b[b%in%0:9]))

```

To make the `el()` function work on TIO, you need to use `library(methods)`.

Gosh dang it, is **R** verbose!
> 1 votes

# Answer
# MATL, score ~~166~~ 156

Code length 41 + output for code used as input 115.

```
'%p#21jgyDT7o?pe}['TIW:qZajk4Y22Y2h&mXz)s

```

Try it online!
> 1 votes

# Answer
# Python 3, 138 + 265 = 403 bytes

```
k='0123456789abcdefghijlnopqrsuxyz'
m=lambda t:sum([ord(''[k.index(v)])if v in k else 0for v in t.lower()])

```

Try it online!
> 1 votes

# Answer
# Perl 6, 87 bytes + 26 matchsticks = 113

```
{+[+] (~''.ords~~m:g/\w/)[m:g/<[/..{]-[\W_]>/>>.&{:٣٦(~$_)}]}

```

Try it online!

Uses some non-ASCII Unicode characters. The lookup table is encoded in a Unicode string:

```
say ''.ords;
# (625545 637665 455454 240303 455250 300545)

```

Characters are converted to indices with base-36 conversion using Arabic-Indic numerals:

```
:٣٦('z'); # is equivalent to
:36('z');

```
> 1 votes

# Answer
# sed, 367 (source code bytes) + 532 (amount of matchsticks for the source code) = 899

```
s/[^0-9a-jln-suxyz]//Ig;/^$/{s/.*/0/;b};s/.+/&; %1ir %%7lnu %%%4cfhjoy %%%%235bdegpqsxz %%%%%069a %%%%%%8/;:1;s/([^% ])(.+ (%+)[^ ]*\1)/%\3 \2/I;/ ;/!b1;s/;.+//;s/^/,;/;:2;s/(;[^%]*)(%+)/\2\1/;:3;s/,%{10}/%,/;s/^%/,&/;/%{10}/b3;/;.*%/b2;:4;s/,[;,]/,0,/;/,[;,]/b4;s/%{9}/9/g;s/%{8}/8/g;s/%{7}/7/g;s/%{6}/6/g;s/%{5}/5/g;s/%%%%/4/g;s/%%%/3/g;s/%%/2/g;s/%/1/g;s/[^0-9]//g

```

Try it Online

Multi-line version:

```
s/[^0-9a-jln-suxyz]//Ig
/^$/{s/.*/0/;b}
s/.+/&; %1ir %%7lnu %%%4cfhjoy %%%%235bdegpqsxz %%%%%069a %%%%%%8/
:1
s/([^% ])(.+ (%+)[^ ]*\1)/%\3 \2/I
/ ;/!b1
s/;.+//
s/^/,;/
:2
s/(;[^%]*)(%+)/\2\1/
:3
s/,%{10}/%,/
s/^%/,&/
/%{10}/b3
/;.*%/b2
:4
s/,[;,]/,0,/
/,[;,]/b4
s/%{9}/9/g
s/%{8}/8/g
s/%{7}/7/g
s/%{6}/6/g
s/%{5}/5/g
s/%%%%/4/g
s/%%%/3/g
s/%%/2/g
s/%/1/g
s/[^0-9]//g

```

# Explanation:

The above script reads standard input line by line (into the pattern space -- the usual "sed way") and, for each line, it outputs the amount of matchsticks necessary to represent all the matchstick-representable characters in that line. The computations for each line of input happen as follows:

---

```
s/[^0-9a-jln-suxyz]//Ig

```

First, we remove every character for which we don't have a corresponding matchstick representation (as given on the question) from the pattern space. That is, we remove every character which isn't either a numeral from "0" to "9", a letter from "a" to "j", "n" to "s", "l", "u", "x", "y" or "z". Uppercase and lowercase letters are treated the same.

```
/^$/{s/.*/0/;b}

```

If we end up with an empty pattern space, we print 0 (automatically followed by a newline, like sed always does unless you pass a special flag to it), skip all posterior lines of the script and proceed into next "sed cycle" (i.e., read the next line of input and repeat processing all over again from the first command until there are no more lines of input to be processed).

```
s/.+/&; %1ir %%7lnu %%%4cfhjoy %%%%235bdegpqsxz %%%%%069a %%%%%%8/

```

Otherwise, if the pattern space is not empty, we now divide it into two "sub-spaces" separated by a semicolon: first comes the *input space*, which is initially formed by all characters which weren't removed from the pattern space after the execution of line 1; next comes the semicolon, and after it the *map space*.

The map space tells us how many matchsticks beside 1 are needed to represent each relevant alphanumeric character. If we want to know how many matchsticks are necessary to represent any alphanumeric character in the map space, we look for the first sequence of contiguous %'s on the left of that character, and the answer will be the number of %'s in that sequence plus 1. So, for example, the number of matchsticks necessary to represent a "b" is 4 + 1 = 5; to represent a "4", 3 + 1 = 4, to represent a "y", 3 + 1 = 4; and so on.

```
:1
s/([^% ])(.+ (%+)[^ ]*\1)/%\3 \2/I
/ ;/!b1

```

This is a loop. Now we will replace every character in the input space by the (complete) sequence of %'s whose number indicates the necessary amount of matchsticks to represent that character, and follow that sequence by a white space character (again, uppercase and lowercase letters are given the same treatment). The criterion to determine whether the loop should end is to check whether there's a white space character on the immediate left of the semicolon in the pattern space: if that condition holds, we terminate the loop and continue into the next line.

```
s/;.+//
s/^/,;/

```

Those two lines remove the semicolon and everything after it from the pattern space and then insert a comma and a semicolon into the beginning of the pattern space. We now have the pattern space divided once again into two new sub-spaces: the *analog result space* before the semicolon, and the *analog input space* after it.

The analog input space is just what we have previously called the "input space", but in a different form: it now contains sequences of %'s separated by white space. The total number of such %'s in the analog input space is the same number of matchsticks necessary to represent the initial input character string, i.e., that number is the result. But we must print that result in decimal notation, not as a sequence of percent signs. The purpose of the *analog **result** space* is to hold an analog representation of each digit of the result while we compute that result by summing each contiguous sequence of %'s in the analog input space one by one. The next loop performs that sum:

```
:2
s/(;[^%]*)(%+)/\2\1/
    :3
    s/,%{10}/%,/
    s/^%/,&/
    /%{10}/b3
/;.*%/b2

```
1. First, after label **2**, we move the next contiguous sequence of %'s after the semicolon from the analog input space into the immediate left of the semicolon, in the analog result space;
2. Next, we step into a sub-loop (label **3**) which performs the following computations:

* If there's a contiguous sequence of ten %'s after a comma in the analog result space, we remove those %'s and put a single % immediately at the left of the comma. To put it simply, this indicates that one of the decimal places in the result has acquired more than 9 units, so we take 10 units away from that decimal place and add 1 unit to the next larger decimal place;
    * If a "%" is the first character in the pattern space, we insert a new comma immediately before it. This indicates that the sum has reached a value whose decimal representation has one more decimal place on the left than the previous value;
    * If there are still any contiguous sequence of ten %'s in the analog result space, we go back to label **3** and repeat this process. Otherwise, we exit this sub-loop and step into the next line.
3. Now, if there is still any "%" in the analog input space (i.e., after the semicolon), it means that there is still some number of matchsticks to be added to the total sum -- so we go back to label **2**.

Once the sum is complete, we step into the final loop of the code:

```
:4
s/,[;,]/,0,/
/,[;,]/b4

```

Here, we check every pair of characters formed by a comma on the left and either a semicolon or a comma on the right. We replace all such pairs of characters by a "0" inside two commas.

```
s/%{9}/9/g
s/%{8}/8/g
s/%{7}/7/g
s/%{6}/6/g
s/%{5}/5/g
s/%%%%/4/g
s/%%%/3/g
s/%%/2/g
s/%/1/g

```

The above piece of code is quite simple: we replace each contiguous sequence of %'s in the analog result space by a decimal digit character which corresponds to the number of %'s in each particular sequence.

```
s/[^0-9]//g

```

Finally, we remove every non-numeral character from the pattern space and what remains is the final result in the familiar decimal notation. That value is printed on standard output and the next sed cycle begins, if there are any more input lines to be processed.
> 1 votes

# Answer
# C (gcc), 134 bytes + 38 matchsticks = 172

```
v(t,w)char*t;{t=(w=*t++)?v(t)+(isalnum(w|=w>'@'&w<'['?' ':!w)?")%(('()&*))('(('('%'#&#&'((%(#&##('("[w-=w>'`'?'W':'_'-'/']-'#':!w):w;}

```

Try it online!
> 1 votes

# Answer
# Java 10, ~~452~~ ~~432~~ ~~416~~ 404 score (145 bytes + 259 matches)

```
k->{int m=0,t;for(var w:k)for(t=m-m;t<'';)m+="1ir 7lnu 4cfhjoy 235bdegpqsxz 069a 8".split(" ")[t++].contains((char)(w|32)+"")?-~t:t-t;return m;}

```

**Explanation:**

Try it online.

```
k->{                   // Method with character-array parameter and int return-type
  int m=0,             //  Result-integer, starting at 0
      t;               //  Index-integer
  for(var w:k)         //  Loop over the input String-array
    for(t=m-m;t<'';)   //   Inner loop over the parts array with index [0,6)
      m+="1ir 7lnu 4cfhjoy 235bdegpqsxz 069a 8".split(" ")[t++]
                       //     If the current part ordered by amount of matches (2-8)
         .contains((char)(w|32)+"")?
                       //     contains the current (lowercase) letter
          -~t          //      Increase the result by the index + 2
         :             //     Else:
          t-t;         //      The result remains the same by adding 0
  return m;}           //  Return the result

```
* ~~Variable names `$ραετ` are used instead of letters.~~ EDIT: Variable names `kmtvw` are now used instead, because they can't be formed by matches according to the challenge description.
* `''` (unprintable) is used instead of `6`.
* `m-m` and `t-t` are used instead of `0`.
* `(char)(w|32)+""` with character-array input used instead of `w.toLowerCase()` with String-array input.
> 1 votes

# Answer
# 05AB1E, 30 bytes + 70 matches = 100 score

```
žLÃlv•Ƶγ¤и©X´≠Ø&c3Íεç•žhA«ykèO

```

Try it online!

---

-5 thanks to Emgina
> 1 votes

# Answer
# AutoHotkey, 148 bytes + 345 matchsticks = 493

This one was a bit of a challenge to shorten.

```
n:=["1ir","7lnu","4cfhjoy","235bdegpqsxz","09a5",7+1]
Loop Parse,i
{r:=A_LoopField
Loop % n.Length()
{l:=A_Index
if InStr(n[l],r)
u+=l+1
}}
send % u

```
> 0 votes

# Answer
# Python 3, 123 bytes + 65 matches = 188

```
lambda w,m='',t='',k=ord:sum(~-k((m+t+m+''+t)[k(v)%77])*('/'<v<'{')for v in w)

```

An unnamed function accepting a string and returning an integer.

Contains many non-printable characters (specifically bytes one to eight).

**Try it online!**
> 0 votes

# Answer
# Charcoal, 48 bytes + 3 = 51

```
ＩΣＥθ⎇№α↥ιＩ§”)➙⊞←!Σw➙⊙↘⁴↘”⌕α↥ι∧№ＩＸ²φιＩ§”)⧴u↑$◨”Ｉι

```

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

```
ＩΣＥθ

```

Loop over the characters of the input, calculating the number of matchsticks of each, then sum the result, convert to string, and implicitly print.

```
⎇№α↥ι

```

If it's a letter...

```
Ｉ§”)➙⊞←!Σw➙⊙↘⁴↘”⌕α↥ι

```

Look up the number of matchsticks in the compressed string `65455454240303455250300545`.

```
∧№ＩＸ²φι

```

Else if it appears in the value of `2 ** 1000`...

```
Ｉ§”)⧴u↑$◨”Ｉι

```

Look up the number of matchsticks in the compressed string `6255456376`.
> 0 votes

# Answer
# PHP, 98+253=351

```
for(;$k=ord($argn[$v++]);)$m+=$k>64?_65455454240303455250300545[$k&31]:_6255456376[$k-47];print$m;

```

Run as pipe with `-nr` or try it online.
> 0 votes

---
Tags: code-challenge, counting
---


# Question
Title: Given a grid, starting at the center and spiraling out, and an Position what is the ID?
**Related:**

**Challenge:**

Given a grid, with an ID starting at the center and spiraling out, what is the ID given a position in the fewest number of bytes?

**Grid:**

```
+---------------+---------------+---------------+---------------+---------------+
| id:  20       | id:  19       | id:  18       | id:  17       | id:  16       |
| pos: (-2, -2) | pos: (-1, -2) | pos: (0, -2)  | pos: (1, -2)  | pos: (2, -2)  |
+---------------+---------------+---------------+---------------+---------------+
| id:  21       | id:  6        | id:  5        | id:  4        | id:  15       |
| pos: (-2, -1) | pos: (-1, -1) | pos: (0, -1)  | pos: (1, -1)  | pos: (2, -1)  |
+---------------+---------------+---------------+---------------+---------------+
| id:  22       | id:  7        | id:  0        | id:  3        | id:  14       |
| pos: (-2, 0)  | pos: (-1, 0)  | pos: (0, 0)   | pos: (1, 0)   | pos: (2, 0)   |
+---------------+---------------+---------------+---------------+---------------+
| id:  23       | id:  8        | id:  1        | id:  2        | id:  13       |
| pos: (-2, 1)  | pos: (-1, 1)  | pos: (0, 1)   | pos: (1, 1)   | pos: (2, 1)   |
+---------------+---------------+---------------+---------------+---------------+
| id:  24       | id:  9        | id:  10       | id:  11       | id:  12       |
| pos: (-2, 2)  | pos: (-1, 2)  | pos: (0, 2)   | pos: (1, 2)   | pos: (2, 2)   |
+---------------+---------------+---------------+---------------+---------------+

```

**Tests:**

```
f(0, 0) = 0
f(1, 1) = 2
f(0, -1) = 5
f(2, 0) = 14
f(-2, -2) = 20

f(x, y) = id

```

### Notes:

* Grid will always be square (height == width)
* Grid can be infinite in size

# Answer
# JavaScript (ES6), 64 bytes

Takes input in currying syntax `(x)(y)`.

```
x=>y=>(d=(A=Math.abs)(A(x)-A(y))+A(x)+A(y))*d+(d-x+y)*(-y>x||-1)

```

Try it online!

Heavily inspired by this answer from math.stackexchange.com.
> 1 votes

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

```
y=>x=>(m=Math.max)(4*x*x-m(x+y,3*x-y),4*y*y+m(-x-y,x-3*y))

```

Try it online!

Use the formula from my previous answer, with some edit (because Javascript doesn't vectorize).

I came up with the formula myself. Basically, knowing that the formula must be quadratic in each 1/4 grid section, I find out the formula mostly by trial-and-error and then find a way to fit those together.
> 1 votes

# Answer
# MATL, 15 bytes

```
|sQtE1YLqwG+X{)

```

Try it online! Or verify all test cases.
> 0 votes

# Answer
# , 37 bytes

```
(g@[-+<.-+[+[)>.(g=:4**:)@]-+>.]+]+-~

```

Try it online!

My first J answer! Use the formula from my Javascript answer.

1. Precedence rules are weird. (at least I don't need to memorize too much, but it's counterintuitive)
2. More than half of the characters are BF keywords.
3. `-+>` and `:)`.
> 0 votes

---
Tags: code-golf
---


# Question
Title: Find out if this a valid Stack Cats program, in Stack Cats style!
# Background

Stack Cats is a reversible esoteric language made by Martin Ender. Each command in Stack Cats is either the inverse of itself (represented as a symmetric character, such as `-_:T|`), or has its inverse command (represented as the mirror image, such as `()` `{}` `[]` `<>`). **Stack Cats has a strong syntactic requirement that the whole program should be the mirror image of itself.** Note that this means any valid Stack Cats program is a natural mirror-image ambigram.

Here is the whole command set of Stack Cats:

* Self-symmetric: `!*+-:=ITX^_|`
* Symmetric pairs: `()` `{}` `[]` `<>` `\/`

Any other characters are invalid; any input having a character not in the character set above should output false.

The language has additional constraint that `()` and `{}` pairs must be always balanced, but for the sake of simplicity, you don't have to check for this condition.

The following are some examples of a **valid Stack Cats program** (again, note that you don't check for balanced parens):

```
{[+]==[+]}
[)>^<(]
({T)}|{(T})
<(*]{[:!-_:>}<[<)*(>]>{<:_-!:]}[*)>

```

These are not:

```
b<+>d
())(
({[<++<]})

```

# Challenge

Write a program or function that determines if the given string is a valid Stack Cats program. **Your code should also be a natural mirror-image ambigram**, which means:

* Your code should be a mirror image of itself.
    + Your code may have one or more newlines, as long as the whole code, displayed naturally, is a mirror image of itself.
    + You can omit or add trailing whitespaces on each line, since it doesn't change the display.
    + Tab characters are not allowed since they have some ambiguity on display.

**Note:** your code does **not** have to be a valid Stack Cats program; it may contain certain extra characters that are not allowed in Stack Cats. (See below for the complete list.)

For example, the following two programs are symmetric (and thus a **valid submission**), while the third is not:

```
({bTd})
[<q|p>]
```

```
({bTd})
  IXI
```

```
({bTd})
IXI
```
* Regarding "mirror symmetry", only Stack Cats-style vertical symmetry is considered (e.g. `({IH})` is not a valid submission, even though it has horizontal mirror symmetry).
* Your code can only contain these sets of characters, plus newline:
    + Self-symmetric: space (`0x20`) + `!"'*+-.8:=AHIMOTUVWXY^_ovwx|`
    + Symmetric pairs: `()` `/\` `<>` `[]` `bd` `pq` `{}`

The character set is chosen to be strictly symmetric or self-symmetric when displayed as code on SE.

# Input and Output

The input range is any **one-line string of printable ASCII characters**.

You can choose to take input as a string, a list of chars, or a list of ASCII values.

You can choose to output either:

* Any of the truthy/falsy values as defined by the language of your choice
    + The actual result values may differ between inputs (e.g. output 1 for a truthy input and 2 for another truthy one).
    + Swapping truthy and falsy values is not allowed.
* Any two constant values for true/false respectively
    + In this case, the result values should exactly be one of the two constant values.

You should specify your input method and output values in your submission.

# Winning Condition

This is , so lowest bytes in each language wins.

# Notes

* Standard loopholes are forbidden as usual.
* Of course you can solve this in Stack Cats, but the catch is that you can't use a flag that allows you to reduce your code size by half. And it's a seriously hard language to pick up. :P

# Answer
## JavaScript (ES6), ~~487~~ ~~467~~ ~~378~~ ~~298~~ ~~292~~ ~~280~~ ~~266~~ 264 bytes

*Saved 14 bytes thanks to @Bubbler*

```
I=>(V=v=>!I[v]||((T=o=>[[]][+!!A[o]]||[(I[v]!=A[o]||A)[o^o<88/8]]+T(++o))(8-8)==I.pop())*V(++v))(V|(A='(){}[]<>\\/ !*+-:=ITX^_|'))//\\(('|_^XTI=:-+*! \//<>[]{}()'=A)|V)((v++)V*(()qoq.I==(8-8)((o++)T+[[8\88>o^o](A||[o]A=![v]I)]||[[o]A!!+][[]]<=o=T))||[v]I!<=v=V)<=I

```

Defines an anonymous function that takes an array of chars and returns the desired output. Output is truthy/falsy; usually `1`/`0`, but the empty string gives `true`.

## How?

The most obvious trick is to use `//\\` as a center point to comment out the mirrored version of the code. After that, it becomes a game of figuring out the shortest way to solve the problem using only the charset given.

The first issue we run into is the lack of keywords and built-ins. We miraculously still have `.pop()`, but everything else will have to be done via the allowed operators (which includes `a[b]` and `f(c)`), with recursion to emulate loops.

The second issue is the lack of logical operators. Neither `&` and `?` are allowed, which means the *only* decision-making operator we can use is `||`. Therefore, we have to carefully structure our logic to account for this.

The first thing I did was to define a function `T` that mirrors an individual character. The basic idea is to loop through each character in a string of mirror-able chars, testing each for equality with the given char. If it is equal, we return its mirror—the char at `index^1` for `(){}[]<>\/`, or the char itself for the rest.

The first problem I ran into here was getting either the mirrored char or a falsy value on each iteration. The solution I eventually came up with was `(x!=A[o]||A)[o^o<88/8]`, where `x` is the input character, `A` is the mirroring alphabet, and `o` is the current index. If `x` is not the same as `A[o]`, this gives `true`, and the index expression evaluates to `undefined`; otherwise, the `||A` is activated, and we end up getting `A[o^(o<11)]`.

The second problem is how to terminate the recursion. I found that the best way to do this is to simply concatenate the results of every iteration, returning the empty string when the end of `A` is reached. This presents us with two further problems: converting the `undefined`s to empty strings, and returning the empty string `||` something. These can be solved with array abuse: `[a]+""` gives the string representation of `a`, or the empty string if `a` is undefined. As a bonus, `[]` is truthy but stringifies to the empty string, so we can conveniently use this as a "truthy empty string".

Now we can use the `T` function to mirror any single character. We do this recursively, comparing the mirror of `I[v++]` to `I.pop()` until the end of the array of chars is reached. We can't use `&&` or `&` to check if all of the comparisons are truthy, but so use `*` instead. Multiplying all of these results together gives `1` if every character is the mirror of the one opposite, or `0` if any comparison fails.

And that is basically how this answer works. I probably didn't explain it very clearly, so please ask any questions you may have and point out any mistakes I have made.
> 18 votes

# Answer
# Stax, ~~76~~ 70 bytes

```
:Wx^^MH_=_"{([</!*+-:=ITX^_|":W-!*pq*!-W:"|_^XTI=:-+*!\>])}"_=_HM^^xW:

```

Run and debug it

Stax is friend of Stack Cats and has internals to generate the later half of a Stack Cats program from the first half. If we don't care about the restriction on the source and don't need to check the charset, here is a 4-byte solution:

## 4 bytes

```
:R_=

```

Run and debug it

## Explanation

```
:Wx^^MH_=_"{([</!*+-:=ITX^_|":W-!*pq...
:W                                         "Mirror" the string
                                           Equivalent to appending the reverse of the string to itself
                                           And map `{([</\>])}` to its mirror in the appended string
  x^^                                      2, but we can't just use `2` here ...
     MH                                    Partition the "mirror"ed string to two parts, take the later part.
       _=                                  The string is the same as the original one (*)
                                           `:Wx^^MH_=` is just `:R_=`, but we can't use `R` here ...
         _                                 Input string
          "{([</!*+-:=ITX^_|":W-           Remove valid characters from input
                                !          The final string is empty (**)
                                 *         (*) and (**)
                                  p        Pop and print result
                                   q       Peek stack and print
                                           Since the stack is now empty, this causes the program to terminate
                                    ...    Not executed

```
> 5 votes

---
Tags: code-golf, restricted-source
---


title: "Hello, name!";

text:
# Question
Title: "Hello, name!";
# Challenge

Your challenge is to make a simple program that takes the \[input\] and formats it as "Hello, \[input\]!"

## Input

Either a function call variable or STDIN, this is the name. Can contain any character, UTF-8, and can be empty - would result in `Hello,!`. Also newlines in the input are fine -

```
On a new
line
->
Hello, On a new
line!

```

**Why? Because the challenge is not about if the message makes sense or not, it's about 'how quickly can you *format*?'.**

## Output

Hello, !

# Example

Here would be a program in CJam:

```
"Hello, %s!"qae%

lolad -> Hello, lolad!

John Smith -> Hello, John Smith!

this is a
new line ->
Hello, this is a
new line!

<null> -> Hello, !

```

# Winner

The winner is the answer with the shortest bytes, as always.

# Answer
> 2 votes
## Retina, 13 bytes

```
'!>`^
Hello,

```

Try it online!

### Explanation

```
^
Hello,

```

This part prepends the `Hello,` (and a space) to the input. Then `>` lets us configure the implicit output of the program and with `'!` we can append the exclamation mark to the output (basically a generalisation of printing with a trailing linefeed).

# Answer
> 2 votes
# pl, 9 bytes

```
Hello, _!

```

Try it online!

# Answer
> 1 votes
# Java 8, 18 bytes

```
s->"Hello, "+s+"!"

```

Try it online.

# Answer
> 1 votes
# 05AB1E, ~~8~~ 7 bytes

```
”Ÿ™, ÿ!

```

Try it online!

# Answer
> 0 votes
# Perl 5, 19 bytes

```
say"Hello, ",<>,"!"

```

Try it online!

# Answer
> 0 votes
# Elixir, 23 bytes

```
fn a->"Hello, #{a}!"end

```

Try it online!

# Elixir, 32 bytes

```
IO.puts"Hello, #{IO.read :all}!"

```

Try it online!

# Answer
> 0 votes
# Add++, 21 bytes

```
x:"Hello, "
+?
+"!"
O

```

Try it online!

# Answer
> 0 votes
# Japt, 12 bytes

Couldn't think of a simpler solution.

```
"Hello, {N}!

```

Try it online!

# Answer
> 0 votes
# AWK, 21 bytes

```
{print"Hello, "$0"!"}

```

Try it online!

# Answer
> 0 votes
# sed, 15 bytes

```
s/.*/Hello, &!/

```

Try it online!

# Answer
> 0 votes
# ReRegex, 17 bytes

Trivial and probably as short as it can get.

```
Hello, (?#input)!

```

Try it online!

# Answer
> 0 votes
# JavaScript, 17 bytes

```
s=>`Hello, ${s}!`

```

# Answer
> 0 votes
# , 111 bytes

```
3.6009960199602996207252062002020200052062009020200152052062012020200252062044520620325207218215217219620335204

```

Try it online!

Nothing too special going on here. This is just a glorified cat program.

# Answer
> 0 votes
# Ruby, 33 bytes

A lambda, accepting a string and returning a string:

```
->s{"Hello,#{s.size>0?' '+s:s}!"}

```

Try it online!

# Ruby \+ `-p`, 16 bytes (not fully compliant)

A full program, which does not support empty inputs (prints nothing) or inputs containing newlines (treats each line as a separate input):

```
$_="Hello, #$_!"

```

Try it online!

The fun trick here: when string interpolation is done on a variable name starting with `$`, the curly braces can be dropped from the normal `#{}` wrapper.

# Answer
> 0 votes
# Haskell, 21 bytes

```
("Hello, "++).(++"!")

```

Try it online!

# Answer
> 0 votes
# / vim, 11 bytes

```
iHello, <esc>A!

```

`<esc>` is a literal escape character

Try it online! (V)

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


title: Implement Lazy Drop Sort

text:
# Question
Title: Implement Lazy Drop Sort
This challenge already describes dropsort. However, I'm kinda lazy and I really only need my array to be a bit more sorted than before, it doesn't need to be sorted *all the way*.

In Drop Sort, we drop every element less than *any* element before it. In Lazy Drop Sort, we drop every element less than the one *strictly preceding* it.

Here's an example. Consider the following array:

```
8 6 9 9 7 2 3 8 1 3

```

Let's mark every element less than the one before it.

```
8 6 9 9 7 2 3 8 1 3
  ^     ^ ^     ^

```

Notice how neither `3` was marked, nor the last `8`. They are all larger than the single element to the left of them.

Completing the algorithm, removing the marked elements, we get:

```
8 9 9 3 8 3

```

That *basically* looks more sorted. Kinda. I'm lazy.

Your task, as you may have already deduced, is to implement this algorithm.

Input is an array of at least 1 positive integer between 1 and 9, so you can take a string of digits as well.

This is , fewest bytes wins!

Additional test cases:

```
1
1

1 2 3
1 2 3

5 3 1
5

1 2 3 2 1
1 2 3

1 1 1 9 9 9 1 1 1 9 9 9 1 1 1
1 1 1 9 9 9 1 1 9 9 9 1 1

9 9
9 9

5 2 4 2 3
5 4 3

```

# Answer
> 7 votes
# Husk, 4 bytes

```
m←ġ<

```

Try it online!

### Explanation

```
m←ġ<
  ġ<    Group the numbers into decreasing sequences
m←      Keep the first element of each sequence

```

# Answer
> 15 votes
# JavaScript (ES6), ~~28~~ 25 bytes

*Saved 3 bytes thanks to @Shaggy*

```
a=>a.filter(n=>~-a<(a=n))

```

Try it online!

# Answer
> 6 votes
# , 27 bytes

```
(l=scan())[c(T,diff(l)>=0)]

```

Try it online!

# Answer
> 6 votes
# MATL, ~~9~~ 8 bytes

Saved one byte thanks to Giuseppe.

```
0yd0<h~)

```

Try it online!

---

**Explanation:**

```
0                 % Push a zero
 y                % Implicitly grab the input and duplicate it.
                  % Stack: [8 6 9 9 7 2 3 8 1 3], 0, [8 6 9 9 7 2 3 8 1 3]
  d               % The difference between each number of the last element:
                  % Stack: [8 6 9 9 7 2 3 8 1 3], 0, [-2, 3, 0, -2, -5, 1, 5, -7, 2]
   0<             % Which are negative?
                  % Stack: [8 6 9 9 7 2 3 8 1 3], 0, [1 0 0 1 1 0 0 1 0]
     h            % Concatenate. Stack: [8 6 9 9 7 2 3 8 1 3], [0 1 0 0 1 1 0 0 1 0]
      ~           % Negate. Stack: [8 6 9 9 7 2 3 8 1 3], [1 0 1 1 0 0 1 1 0 1]
       )          % Index. Stack: [8 9 9 3 8 3]

```

# Answer
> 5 votes
# Perl 5.10.0 + `-nl`, 16 bytes

```
$f>$_||say;$f=$_

```

Try it online!

# Answer
> 5 votes
# Haskell, 29 bytes

```
f s=[b|(a,b)<-zip(0:s)s,a<=b]

```

just a simple list comprehension.

# Answer
> 4 votes
# Japt, ~~8~~ 7 bytes

*Saved 1 byte thanks to @Oliver*

```
k@>(U=X

```

Test it online!

Alternatives:

```
f@T§(T=X
k@ä>0 gY
i0 ò> mÅ c

```

# Answer
> 4 votes
# Java 8, ~~66~~ ~~55~~ 48 bytes

```
l->{for(int i=0;;)if(i>(i=l.next()))l.remove();}

```

-11 bytes after a tip from *@OlivierGrégoire*.
-7 more bytes thanks to *@OlivierGrégoire*.

**Explanation:**

Try it online.

```
l->{                     // Method with Integer-ListIterator parameter and no return-type
  for(int i=0;;)         //  Loop over all items
    if(i>(i=l.next()))   //   If the current item is larger than the next
      l.remove();}       //    Remove this next item

```

# Answer
> 4 votes
# Stax, 5 bytes

```
âÿ╠╦░

```

Run and debug this online

Unpacking, ungolfing, and commenting the code, we get this.

```
Z   Push a zero under the input
f   Use the rest of the program as a filter on the input.  Output passing elements.
>   Current element is greater than previous?
_~  Push current element to the input stack; when the main stack is empty, pops fall back to this
!   Logical not; applies to the result of the greater-than

```

Run this one

The ordering of the instructions is awkward but there's a reason for it. Stax source code packing doesn't always yield the same size output for the same size input. Basically, you have a chance to save a byte if the last character of source has a lower character code. Well, `!` has one of the lowest codes you can get for a printable character. (33 specifically) Many 6 byte ASCII stax programs can't pack any smaller. But if they end with a `!`, then they can. So the reason for this particular ordering of instructions is to ensure that the logical not ends up at the end of the program.

# Answer
> 4 votes
# J, 12 Bytes

```
#~1,2&(<:/\)

```

### Explanation:

```
#~1,2&(<:/\)    | Whole function, executed as a hook
       <:/      | Distribute <: (greater or equal) over an array
    2&(   \)    | Apply to each sub array of length 2
  1,            | Append a 1 to the front
#~              | Choose elements from the original array

```

### Examples:

```
    2&(<:/\) 8 6 9 9 7 2 3 8 1 3
0 1 1 0 0 1 1 0 1
    1,2&(<:/\) 8 6 9 9 7 2 3 8 1 3
1 0 1 1 0 0 1 1 0 1
    (1 0 1 1 0 0 1 1 0 1) # 8 6 9 9 7 2 3 8 1 3
8 9 9 3 8 3
    f =: #~1,2&(<:/\)
    f 8 6 9 9 7 2 3 8 1 3
8 9 9 3 8 3

```

Try it online!

# Answer
> 4 votes
# Jelly, 6 bytes

```
>Ɲ0;¬×

```

I/O is on strings.

Try it online!

# Answer
> 4 votes
# Octave, 21 bytes

```
@(x)x(~[0,diff(x)<0])

```

Try it online!

**Explanation:**

Take a vector `x` as input, and create a vector `[0, diff(x)<0]`, where `diff(x)` is a vector with the difference between all adjacent elements. Keep only those that are negative by comparing it to zero, giving us a list of all the elements we want to drop.

We then select the elements from the input vector that we want to keep.

# Answer
> 4 votes
# , 25 bytes

```
òjälá k$yl+@"òç-/d
ç /dw

```

Try it online!

Hexdump:

```
00000000: f26a e46c e120 6b24 796c 2b40 2218 f2e7  .j.l. k$yl+@"...
00000010: 2d2f 640a e720 2f64 77                   -/d.. /dw

```

Worst language for the job. But I did it for a dare.

# Answer
> 4 votes
# SWI-Prolog, 44 bytes

```
[A,B|C]-[A|E]:-B<A,[B|C]-[B|E];[B|C]-E. L-L.

```

Usage: Call "*List*-X" where *List* is a bracket-enclosed, comma-separated list e.g. \[1,4,5,1,11,6,7\].

# Answer
> 3 votes
# Python 2, ~~52~~ ~~46~~ ~~45~~ 42 bytes

```
lambda a:[v for v,w in zip(a,[1]+a)if v/w]

```

Try it online!

---

Saved:

* -3 bytes, thanks to Rod

# Answer
> 3 votes
# Triangularity, 71 bytes

```
.....).....
....IEL....
...)rFD)...
..2+)IE)w..
.+h)2_stDO.
={M)IEm}...

```

Try it online!

## How it works?

```
)IEL)rFD)2+)IE)w+h)2_stDO={M)IEm} – Full program.
)IE                               – Get the 0th input I and evaluate it.
   L)r                            – And push the range [0 ... length of I).
      F                   {       – Filter the integers in this range which satisfy:
       D)2+)IE)w+h)2_stDO=        – This condition. Runs each element E on a separate
                                    stack and discard those that don't meet the criteria.
       D)2+                       – Duplicate and add 2 to the second copy.
           )IE                    – Retrieve I again.
              )                   – Push a 0 onto the stack.
               w                  – Wrap the 0 in a list. [0]
                +                 – Prepend it to I.
                 h                – Head. Trim the elements after index E+2.
                  )2_             – Literal -2.
                     st           – Tail.
                       DO=        – Check whether the result is invariant over sorting.
                           M)IEm} – Last part: indexing into the input.
                           M    } – For each index that satisfies the conditions:
                            )IEm  – Retrieve the element of I at that position.

```

# Answer
> 3 votes
# Wonder, 27 bytes

```
-> ':1.!> 'sS#<=.cns2.++[0]

```

Usage example:

```
(-> ':1.!> 'sS#<=.cns2.++[0])[8 6 9 9 7 2 3 8 1 3]

```

# Explanation

Ungolfed version:

```
(map get 1).(fltr sS <=).(cns 2).(++ [0])

```

Prepend `0`, get list of consecutive pairs, keep list items where first number \<= second number, get second number of each pair.

# Answer
> 3 votes
# Python, 40 bytes

```
f=lambda h,*t:t and h+f(*t)[h>t[0]:]or h

```

Try it online!

Input as tuple of characters.

---

# Python 3, 41 bytes

```
p=''
for x in input():x<p or print(x);p=x

```

Try it online!

String input.

---

# Python 2, 41 bytes

```
for x in input():
 if x>=id:print x
 id=x

```

Try it online!

String input, just because strings are greater than `id` but numbers are smaller.

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

```
Pick[#,Arg[#-{0}~Join~Most@#],0]&

```

Try it online!

## How it works

The code `# - {0}~Join~Most@#` turns an array `{a,b,c,d,e,f}` into `{a,b-a,c-b,d-c,e-d,f-e}`. Applying `Arg` to this sets negative numbers to `Pi` and nonnegative numbers to `0`.

`Pick[#, ..., 0]&` picks out the entries of `#` where `...` has a `0`: in our case, exactly the elements that yield a nonnegative number when you subtract the previous element. In other words, these are exactly the entries we want to keep when lazydropsorting.

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

```
#&@@@Split[#,##>0&]&
(* or *)
Max/@Split[#,##>0&]&

```

Try it online!

### Explanation

`Input = {8, 6, 9, 9, 7, 2, 3, 8, 1, 3}`

```
Split[#,##>0&]

```

Group consecutive elements that are strictly decresasing: `{{8, 6}, {9}, {9, 7, 2}, {3}, {8, 1}, {3}}`

```
#&@@@

```

Take the first element of each: `{8, 9, 9, 3, 8, 3}`

# Answer
> 2 votes
# APL+WIN, 14 bytes

Prompts for screen input of a vector of integers.

```
(1,1>2-/v)/v←⎕

```

# Answer
> 2 votes
# 05AB1E, 6 bytes

```
ĆÁü›_Ï

```

Try it online!

**Explanation**

```
Ć        # append the head of the list
 Á       # rotate right
  ü›     # apply pair-wise greater-than
    _    # logical negate each
     Ï   # keep elements of input that are true in this list

```

# Answer
> 2 votes
# C# (.NET Core), 33 + 18 = 51bytes

```
x=>x.Where((a,n)=>n<1||x[n-1]<=a)

```

Try it online!

basically the statement is where x is the first int in the array, or is greater than or equal to the previous number, keep it. Else drop it.

# Answer
> 2 votes
# Kotlin, 39 bytes

```
a->a.filterIndexed{i,v->i<1||v>=a[i-1]}

```

Try it online!

Filter items that are either the first item (index==0, or even shorter index\<1) OR the current Value is greater than or equal to the previous item (a\[i-1\]).

# Answer
> 2 votes
# APL (Dyalog Unicode), 11 bytes

```
{⍵⌿⍨1⍪2≤⌿⍵}

```

Try it online!

This is actually pretty similar to Graham's answer, but in Dyalog, and independently developed. Also, more symmetric.

# Answer
> 2 votes
# K4, 10 bytes

**Solution:**

```
x_/|&<':x:

```

**Example:**

```
q)k)x_/|&<':x:8 6 9 9 7 2 3 8 1 3
8 9 9 3 8 3

```

**Explanation:**

Find indices where element is less than preceding, remove these indices from the input

```
x_/|&<':x: / the solution
        x: / store input as x
     <':   / less-than each-previous
    &      / indices where true
   |       / reverse
 _/        / drop-over
x          / the input

```

# Answer
> 2 votes
# Attache, 24 bytes

```
{Mask[1'(Delta!_>=0),_]}

```

Try it online!

## Explanation

`Mask` selects all elements from its second argument which correspond to truthy elements in its first argument. `1'(Delta!_>=0)` calculates the indices which correspond to elements that are supposed to be in the final array.

## Other attempts

28 bytes (pointfree): `~Mask#(1&`'##Delta#`>=#C[0])`

32 bytes: `{Mask[1'(&`<= =>Slices[_,2]),_]}`

# Answer
> 1 votes
# Jelly, 9 bytes

```
0;>ƝżµḢÐṂ

```

Try it online!

This feels pretty bulky, wouldn't be that surprised if there is a better way.

```
0;>ƝżµḢÐṂ
   Ɲ       For each adjacent pair in the input...
  >        ...is the first element greater than the second? (yields a list of 0/1)
0;         prepend a zero to this list (always keep the first element)
    ż      zip with the input
     µ     new monadic link
       ÐṂ  keep elements of the list with minimal value of... (Ðḟ would have worked here and been slightly more clear but I'll leave it as it is)
      Ḣ    ...their first element

```

# Answer
> 1 votes
# Swift 4, ~~56~~ 55 bytes

```
{var l=0;print($0.filter{($0>=l,l=$0).0})}as([Int])->()

```

Try it online!

## Explanation

```
{var l=0;           // Declare variable l
print($0.filter{(   // Print every element e in the input
  $0>=l,            //   where e >= l
  l=$0).0})         //   And set l to e
}as([Int])->()      // Set the input type to integer array

```

# Answer
> 1 votes
# Brain-Flak, ~~136~~, 120 bytes

```
((())){{}([{}]({}))([({}<(())>)](<>)){({}())<>}{}{((<{}>))<>{}}{}<>{}{{}(({})<>)(())(<>)}{}([][()])}{}{}<>{{}({}<>)<>}<>

```

Here it is formatted and *"readable"*.

```
((()))
{
    {}

    ([{}]({}))

    ([({}<(())>)](<>)){({}())<>}{}{((<{}>))<>{}}{}<>{}

    {
        {}(({})<>)(())(<>)
    }

    {}

    ([][()])

}{}{}<>

{
    {}
    ({}<>)<>
}<>

```

Try it online!

# Answer
> 1 votes
**SHELL** ( **45 Bytes**)

**Solution 1** : output on 1 line ( **57 Bytes**)

```
L(){ for i in $*;do(($i>=$o))&&echo $i;o=$i;done|xargs;}

```

Test :

```
>L 8 6 9 9 7 2 3 8 1 3
8 9 9 3 8 3

```

**Solution 2** : output 1 element / line ( **51 Bytes**)

```
L(){ for i in $*;do(($i>=$o))&&echo $i;o=$i;done;}

```

Test :

```
>L 8 6 9 9 7 2 3 8 1 3
8
9
9
3
8

```

**Solution 3** : with bc ( **51 Bytes**)

```
 L(){ for i in $*;do bc<<<"if($i>$o)$i";o=$i;done;}

```

**Solution 4** : optimisation ( suppression in $\*, thanks user17752 ) ( **45 Bytes**)

```
 L(){ for i;do bc<<<"if($i>$o)$i";o=$i;done;}

```

# Answer
> 1 votes
# Python 2, ~~50~~ 49 bytes

```
f=lambda s:s and f(s[:-1])+s[-1]*(s[-2:]<s[-1]*3)

```

I/O is on strings.

Try it online!

# Answer
> 1 votes
# Retina 0.8.2, ~~32~~ 31 bytes

```
\d
$*
r`(?<=1\1) (1+)\b

1+
$.&

```

Try it online! Link includes test cases. Explanation: The first and last stages are simply unary conversion. The middle stage deletes the numbers that are preceded by a larger number. A right-to-left match is used so that the lookbehind can be placed at the start of the regex, saving 1 byte.

# Answer
> 1 votes
# Fortran (GFortran), 74 bytes

```
SUBROUTINE D(I,J)
INTEGER I(J)
DO1 K=1,J
1 IF(I(K)>=I(K-1))PRINT*,I(K)
END

```

This is my entry in this lovely language. It simply prints the "sorted" array, doesn't return it. `I` is the array to be "sorted" and `J` is its length. The TIO link below shows a complete program (with 160 bytes) using the subroutine. The input array is hardcoded in the main program.

Actually, I think that there might be some way to get an unknown length array as input, even from `STDIN`, using allocatable arrays, but it would be a really ugly program. Anyway, it seems fair to be lazy while implementing a lazy algorithm in a aged (and, therefore, tired) programming language :).

Conclusion: Fortran is an awesome language for arrays, as far as you know their lengths.

Try it online!

# Answer
> 1 votes
# C, 82 bytes

```
f(a,c,i,j)int*a;{for(i=-1;++i<c;j=a[i])printf("%d "+3*(i&&j>a[i]),a[i]);puts("");}

```

Try it online!

I used the usual tricks (using K&R-style functions, indexing into a constant string, etc.) and because I don't like ending output on the same line as the next program added a newline. To make sure that the 1-element arrays were handled correctly, I special-cased it.

# Answer
> 1 votes
# C (clang), 53 bytes

```
x,c;f(char *s){for(x=0;c=*s++;x=c)c>=x?putchar(c):0;}

```

Try it online!

Takes input as string of digits, For all digits, prints it if greater than previous.

---
Tags: code-golf, array, sorting
---


title: Make a valid error maker!

text:
# Question
Title: Make a valid error maker!
We've been twice challenged to make 'error quines' (see Make an error quine! and Make a slow error quine maker!), so why don't we try the opposite?

## Instructions

1. Write a "program" that, when run, produces an error.
2. Copy the error message into a new program, and run it.
3. Repeat Step 2 until the program runs without producing an error.

## Rules

* All of your programs must be run in the same language.
* None of your programs can be shorter than 1 byte long.
* The error(s) should be printed to STDERR.

## Winning criteria

Your score is the **number of programs run** minus **the length in bytes of your initial program**. Highest score wins.

---

An example in monochrome TI-83+/84+ BASIC:

*Initial program:* `{"`
This creates a list with a string inside it, throwing an `ERR:DATA TYPE`.

*Program 2:* `ERR:DATA TYPE`
The space causes the interpreter to throw an `ERR:SYNTAX`.

*Program 3:* `ERR:SYNTAX`
The letters are treated as variable multiplication, and the colon as a newline. This runs successfully.

This chain's score is **3** (number of programs) **minus 2** (length in bytes of `{"`, the initial program), totaling `1`.

# Answer
# Pip 0.15.05.29, over 10100,000

(Subtracting the 51 bytes of source code is negligible for such a large number.)

This is a version of my answer to Make a slow error quine maker. Requires the `-w` flag for warning output.

```
i:5**6**7d:"i:1d: Ssi?dRo--iRsRPdx"Ssi?dRo--iRsRPdx

```

The exact number of steps depends only on the value assigned to `i`, so it could be arbitrarily large (until the Python interpreter runs out of memory). Also, it would take longer than the age of the universe to complete the above sequence.

**Explanation:**

Example here uses an `i`-value of `5` for purposes of explanation.

```
i:5d:"i:1d: Ssi?dRo--iRsRPdx"Ssi?dRo--iRsRPdx

```

After setting `i`, store a string in `d` and then attempt to execute the `S`wap statement. Swap expects two variables (more accurately, lvalues). `s` is fine, but the second expression is `i?dRo--iRsRPdx`. If `i` is true (nonzero, for our purposes), the ternary evaluates to `dRo--iRsRPd`, which uses `d` from earlier to form a near-quine--only with `i` decremented. This expression is not an lvalue, so Pip complains:

```
Attempting to swap non-lvalue i:4d:"i:1d: Ssi?dRo--iRsRPdx"Ssi?dRo--iRsRPdx

```

... which then starts the whole thing over again. (`Attempting to swap non-lvalue` is a bunch of no-ops: `At` calculates the ASCII value of `t = 10`, `n-l` subtracts newline minus each value of an empty list, and all the lowercase letters are just variables.)

The process continues in like fashion all the way down to:

```
Attempting to swap non-lvalue i:0d:"i:1d: Ssi?dRo--iRsRPdx"Ssi?dRo--iRsRPdx

```

When this is run, `i` is now false. The ternary expression evaluates to the else branch `x`--which is an lvalue. Thus, swap simply swaps the values of `s` and `x`. The program then exits with no output.

(The only thing that's changed from the previous answer is using `x`, which is a predefined variable, instead of `a`, which is undefined if there were no command-line arguments and thus triggers a different error when `i` gets down to zero.)
> 6 votes

# Answer
# Bash, 9223372036854775809 - 75 = 9223372036854775734

This is a previous broken version of my answer to Make a slow error quine maker, which in fact works as what this question have specified.

```
a='"2>/dev/null;(((i=$((i-1)))>0))&&$(declare -p a)&&$a" #'
i=2**63
eval $a

```

It should be run with `bash < file.sh`, or use the same file name for each program, to get rid of the different file names in the error messages.

The first few errors are (with `LANG=C`):

```
bash: line 3: 2>/dev/null;(((i=9223372036854775807)>0))&&declare -- a="\"2>/dev/null;(((i=\$((i-1)))>0))&&\$(declare -p a)&&\$a\" #"&&"2>/dev/null;(((i=$((i-1)))>0))&&$(declare -p a)&&$a" #: No such file or directory

```

```
bash: line 1: 2>/dev/null;(((i=9223372036854775806)>0))&&declare -- a="\"2>/dev/null;(((i=\$((i-1)))>0))&&\$(declare -p a)&&\$a\" #"&&"2>/dev/null;(((i=$((i-1)))>0))&&$(declare -p a)&&$a" #: No such file or directory

```

```
bash: line 1: 2>/dev/null;(((i=9223372036854775805)>0))&&declare -- a="\"2>/dev/null;(((i=\$((i-1)))>0))&&\$(declare -p a)&&\$a\" #"&&"2>/dev/null;(((i=$((i-1)))>0))&&$(declare -p a)&&$a" #: No such file or directory

```
> 1 votes

# Answer
# SmileBASIC, 2 - 6 = -4

Code must be run in the console so a line number isn't printed in the error message.

Initial program:

```
WHILE.

```

Program 2:

```
WHILE without WEND

```
> 0 votes

---
Tags: code-challenge, busy-beaver, error-message
---


title: Running gene crossover algorithm

text:
# Question
Title: Running gene crossover algorithm
Your task is to accept as input two gene sequences, and a sequence of "cross over points", and return the gene sequence that results from the indicated cross overs.

What I mean by this is, say you have the sequences `[A, A, A, A, A, A, A]` and `[Z, Z, Z, Z, Z, Z, Z]`, and cross over points of `2` and `5`. The resulting sequence would be `[A, A, Z, Z, Z, A, A]`, because:

```
Cross Here:   V     V
Indices:  0 1 2 3 4 5 6

Genes 1:  A A A A A A A
Genes 2:  Z Z Z Z Z Z Z

Result:   A A Z Z Z A A
              ^     ^

```

Note that while I'm using letters here for clarity, the actual challenge uses numbers for genes.

The result is the first sequence until a cross over point is encountered, then the result takes from the second sequence until another cross over point is encountered, then the result takes from the first sequence until a cross over point is encountered...

# Input:

* Input can be any reasonable form. The two sequences can be a pair, with the points as the second argument, all three can be separate arguments, a single triplet of `(genes 1, genes 2, cross-points)`, a map with named keys...
* The cross points will always be in order, and will always be inbounds. There won't be duplicate points, but the list of cross over points may be empty.
* Gene sequences will always be the same length, and will be non-empty.
* Indices can be 0 or 1 based.
* Genes will always be numbers in the range 0-255.
* It doesn't matter which argument is "genes 1" or "genes 2". In the case of no cross over points, the result can either be either entirely "genes 1" or "genes 2".

---

# Output

* Output can be any reasonable form that isn't ambiguous. It can be a array/list of numbers, an array of string numbers, a *delimited* string of numbers (some non-numeric character must separate the numbers)...
* It can be returned or printed to the std-out.

---

Entries can by full programs or functions.

---

# Test Cases `(genes 1, genes 2, cross points) => result`:

```
[0], [1], [0] => [1]
[0, 1], [9, 8], [1] => [0, 8]
[0, 2, 4, 6, 8, 0], [1, 3, 5, 7, 9, 1], [1, 3, 5] => [0, 3, 5, 6, 8, 1]
[1, 2, 3, 4], [5, 6, 7, 8], [] => [1, 2, 3, 4]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 2, 3, 6, 8] => [1, 1, 0, 1, 1, 1, 0, 0, 1, 1]

```

This is Code Golf.

# Answer
> 1 votes
# Jelly, ~~12~~ 10 bytes

```
ṁ⁹L‘¤ḣ"ḷ"/

```

Try it online!

Argument 1: seq1, seq2
Argument 2: cross points (0-indexed)

# Answer
> 4 votes
# JavaScript (ES6), ~~47~~ 45 bytes

*Saved 2 bytes thanks to @ETHproductions*

Takes input as a triplet **\[a, b, c\]** where **a** and **b** are the gene sequences and **c** is the list of 0-indexed cross-points.

```
x=>x[i=j=0].map(_=>x[(j+=x[2][j]==i)&1][i++])

```

Try it online!

### Commented

```
x =>                    // given x = [ geneSeqA, geneSeqB, crossPoints ]
  x[i = j = 0]          // initialize i = gene sequence pointer and j = cross point pointer
  .map(_ =>             // for each value in the first gene sequence:
    x[(                 //   access x[]
      j += x[2][j] == i //     increment j if i is equal to the next cross point
    ) & 1]              //   access either x[0] or x[1] according to the parity of j
    [i++]               //   read gene at x[0][i] or x[1][i]; increment i
  )                     // end of map()

```

# Answer
> 4 votes
## Haskell, ~~58~~ ~~53~~ ~~51~~ 45 bytes

```
(fst.).foldl(\(a,b)p->(take p a++drop p b,a))

```

The two gene sequences are taken as a pair of lists and the cross points as a second argument.

Try it online!

```
foldl           -- fold the pair of genes into the list of
                -- cross points and on each step
    \(a,b) p -> -- let the pair of genes be (a,b) and the next cross point 'p'
      (take p a++drop p b,a)
                -- let 'b' the new first element of the pair, but
                --   drop the first 'p' elements and
                --   prepend the first 'p' elements of 'a'
                -- let 'a' the new second element
fst             -- when finished, return the first gene

```

# Answer
> 3 votes
# APL (Dyalog 16.0), 26 bytes

```
+/a⎕×(~,⊢)⊂≠\d←1@⎕⊢0⍴⍨≢a←⎕

```

Try it online!

Input is **a**, **c**, then **b**. **c** is `1` indexed.

**How?**

`a←⎕` \- get **a**.

`0⍴⍨≢` \- create array of `0`s at its length.

`1@⎕⊢` \- take **c** and change the `0`s to `1`s on the indices.

`d←` \- assign to **d**.

`⊂≠\d` \- expand **d** with **xor** to create the selection sequence (`0` for **a**, `1` for **b**), and enclose.

`(~,⊢)` \- take **d** and its inverse.

`a⎕×` \- and multiply respectively with inputted **b** and **a**.

`+/` \- sum each pair of elements, yielding the **a**s on `0`s and **b**s on `1`s.

# Answer
> 3 votes
# Python 2, 43 bytes

```
def f(a,b,l):
 for p in l:a[p:],b=b[p:],a*1

```

Try it online!

Outputs by modifying the argument `a`. Instead as a program:

**50 bytes**

```
a,b,l=input()
for p in l:a[p:],b=b[p:],a*1
print a

```

Try it online!

# Answer
> 2 votes
# Python 3, ~~61~~ 60 bytes

```
f=lambda a,b,c,d=0:c and a[d:c[0]]+f(b,a,c[1:],c[0])or a[d:]

```

Try it online!

-1 byte from Jonathan Frech

Explanation:

```
f=lambda a,b,c,d=0:c and a[d:c[0]]+f(b,a,c[1:],c[0])or a[d:]
f=lambda a,b,c,d=0:
 # recursive lambda: a and b are the two lists,
 # c is the crossovers, and d is where to start
                   c and
 # if there is at least one crossover left
 #  then
                         a[d:c[0]]
 #  return the items of the first list from the
 #  starting point up to the first crossover
                                  +f(b,a,c[1:],c[0])
 #  plus the result of the inverted lists with
 #  the remaining crossovers, starting where
 #  the first part left off
                                                    or
 # else
                                                       a[d:]
 #  the first list from the starting point to the end

```

# Answer
> 2 votes
# Perl 5 `-a`, ~~45~~ 40 bytes

Give input in the order "control", "second sequence", "first sequence" as separate lines on STDIN

```
#!/usr/bin/perl -alp
@{$.}=@F}for(map${$.^=$%~~@1}[$%++],@2){

```

Try it online!

# Answer
> 2 votes
# , ~~84~~ 79 bytes

```
function(G,K){o=G[,1]
m=1:nrow(G)
for(i in K)o[m>=i]=G[m>=i,match(i,K)%%2+1]
o}

```

Try it online!

Takes input as a matrix of 2 columns and a `vector`.

# Answer
> 2 votes
# , 24 bytes

```
4 :'(2|+/\1 x}I.#{.y)}y'

```

Try it online!

I don't count the `f=:` chars, because it works equally well as an anonymous function (as demonstrated in a TIO sample)

Note: It doesn't work for empty list of cross over points!

An explicit oneliner, `x` is the left argument - the list of cross over points, `y` is the right argument, a two-row table of the sequences.

## Explanation:

`4 :' ... '` \- a dyadic verb

`(...)}y` \- Each atom of operand (...) selects an atom from the corresponding positions of the items of y

`#{.y` \- takes the first sequence and find its length

```
    #{. 0 2 4 6 8 0,: 1 3 5 7 9 1
6

```

`I.` creates a list of zeros with length the argument

```
   I.6
0 0 0 0 0 0

```

`1 x}` changes the items of the rigth argument (a list of zeroes) to 1 at indices indicated by `x` (the list of cors over points)

```
   1(1 3 5)}I.6
0 1 0 1 0 1

```

`+/\` running sums of a list

```
   +/\ 0 1 0 1 0 1
0 1 1 2 2 3

```

`2|` modulo 2

```
   2|+/\ 0 1 0 1 0 1
0 1 1 0 0 1

```

Assembled:

```
    0 1 1 0 0 1 } 0 2 4 6 8 0 ,: 1 3 5 7 9 1
0 3 5 6 8 1

```

# Answer
> 2 votes
# SWI-Prolog, 78 bytes

```
A/B/[0|C]/D:-B/A/C/D. [H|A]/[_|B]/C/[H|D]:-maplist(succ,E,C),A/B/E/D. A/_/_/A.

```

Usage: Call "Genes1/Genes2/CrossoverPoints/X" where "Genes1", "Genes2", "CrossoverPoints" are bracket-enclosed, comma-separated lists.

# Answer
> 1 votes
# Jelly, 13 bytes

```
ṬœṗÐ€ż/JḂị"ƊF

```

A dyadic link accepting the (1-indexed) crossover points on the left and a list of the two sequences on the right which returns the resulting list.

**Try it online!**

### How?

```
ṬœṗÐ€ż/JḂị"ƊF - Link: list, C; list, S     e.g. [2,4,6]; [[0,2,4,6,8,0],[1,3,5,7,9,1]]
Ṭ             - untruth C                       [0,1,0,1,0,1]
   Ð€         - map across S with:
 œṗ           -   partition at truthy indices   [[0],[2,4],[6,8],[0]]  /  [[1],[3,5],[7,9],[1]]
      /       - reduce with:
     ż        -   zip                           [[[0],[1]],[[2,4],[3,5]],[[6,8],[7,9]],[[0],[1]]]
           Ɗ  - last three links as a monad:
       J      -   range of length               [1,2,3,4]
        Ḃ     -   bit (modulo by 2)             [1,0,1,0]
          "   -   zip with:
         ị    -     index into                  [[0],[3,5],[6,8],[1]]
            F - flatten                         [0,3,5,6,8,1]

```

# Answer
> 1 votes
# Charcoal, 19 bytes

```
ＡθＡηＥ§θ⁰§§θＬΦ⊕κ№ηλκ

```

Try it online! Link is to verbose version of code. Takes input as a pair of string gene sequences and a 0-indexed list of crossing points. Explanation:

```
Ａθ                  Input the pair of gene sequences into `q`
  Ａη                Input the list of crossing points into `h`
    Ｅ§θ⁰            Loop over one of the gene sequences
              κ     Current index
             ⊕      Incremented
            Φ  №ηλ  Intersect implicit range with crossing points
           Ｌ        Take the length
         §θ         Cyclically index into the pair of gene sequences
        §         κ Take the appropriate element of that sequence
                    Implicitly output on separate lines

```

Alternatively,  could be subsituted for  to print the result as a string. Try it online!

# Answer
> 1 votes
# C (clang), 79 bytes

```
*g[2],*c,l,m;f(i,j,k){for(i=j=k=0;i<l;g[0][i++]=g[k][i])m&&c[j]==i?k=!k,j++:0;}

```

Try it online!

Inputs:
`g[0]` is gene-sequence 1,
`g[1]` is gene-sequence 2,
`c` is cross-over points.
`l` is length of `g[0]` and `g[1]`
`m` is length of `c`
All array inputs are arrays of integers with 0-based index.
Outputs:
Output is stored in `g[0]`

macro a() in footer does pretty-printing of test-cases and result

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


title: Put an array into bins

text:
# Question
Title: Put an array into bins
In this simple challenge you are given an input array `L` of non-negative integers and a number of bins `b` greater than 0 but no more than the length of `L`. Your code must return a new array `M` whose length is `b` and which has binned the array `L`. This is easiest explained with examples.

`L = [1,0,5,1]` and `b = 2` returns `M = [1,6]`.

`L = [0,3,7,2,5,1]` and `b = 3` returns `M = [3,9,6]`.

So far, so simple. However in this question `b` doesn't necessarily have to divide `len(L)`. In this case the last bin will just have fewer numbers to make it up.

Each bin except possibly the last one must have the same number of numbers contributing to its total. The last bin must have no more numbers contributing to it than the other bins. The last bin must have as many numbers contributing to it as possible subject to the other rules.

`L = [0,3,7,2,5,1]` and `b = 4` returns `M = [3,9,6,0]`. `M = [10,8,0,0]` is not an acceptable output as the third bin does not have the name number of numbers contributing to it as bins `1` and `2`.

`L = [0,3,7,2,5]` and `b = 2` returns `M = [10,7]`. `M = [3, 14]` is not an acceptable output as the last bin will have `3` elements contributing to it but the first has only `2`.

`L = [1,1,1,1,1,1,1]` and `b = 3` returns `M = [3,3,1]`.

As a final rule, your code must run in linear time.

You may use any language or libraries you like and can assume the input is provided in any way you find convenient.

---

It turns out that there are some inputs which can't be solved. For example `[1,1,1,1,1]` and `b=4`. Your code can output whatever it likes for those inputs.

# Answer
> 5 votes
# APL (Dyalog), 19 bytes

```
{+/⍺(⌈⍺÷⍨≢⍵)⍴⍵,⍺⍴0}

```

Try it online!

We append **b** zeros to the array before reshaping it into equal parts of `⌈⍺÷⍨≢⍵` (**⌈ length of L ÷ b ⌉**) and summing them, as depicted in `,⍺⍴0`, since any amount of blank spots (which are not part of the original array) larger than **b - 1** would be filled with at least **b - 1** elements from other chunks, which makes the balancing point of the last group at maximum **b - 1** difference from the rest. We use **b \> b - 1** because it is code golf.

For example, **L** with **15** elements and **b = 3** wouldn't be grouped as

```
x x x x x x
x x x x x x
x x x 0 0 0

```

but rather as (note how the rightmost 2 `x`s "fills in" the leftmost zeros)

```
x x x x x
x x x x x
x x x x x

```

while a **16** elements array would be filled with **2** (**3 - 1**) blank spots, like

```
x x x x x x
x x x x x x
x x x x 0 0

```

# Answer
> 3 votes
# , ~~75~~ ~~71~~ ~~70~~ 63 bytes

```
function(L,b)colSums(matrix(L[1:(ceiling(sum(L|1)/b)*b)],,b),T)

```

Try it online!

This pads `L` with `NA` until the length is a multiple of `b`, then takes the column sums of `L` as a matrix with `b` columns, removing `NA` values.

Explaining as a stack-based language:

```
function(L,b){
      (ceiling(sum(L|1)/b*b)  # push the next multiple of b >= length(L), call it X
    1:..                      # push the range 1:X
  L[..]                       # use this as an index into L. This forces L
                              # to be padded to length X with NA for missing values
        matrix(..,,b)         # create a matrix with b columns, using L for values
                              # and proceeding down each column, so
                              # matrix(1:4,,2) would yield [[1,3],[2,4]]
colSums(.., na.rm = T)        # sum each column, removing NAs

```

# Answer
> 3 votes
# Python 2, 65 bytes

```
f=lambda l,n:n and[sum(l[:len(l)/n+1])]+f(l[len(l)/n+1:],n-1)or[]

```

Try it online!

# Answer
> 3 votes
# Ruby, ~~54~~ 53 bytes

Saved a byte thanks to @Kirill L.

```
->l,b{s=1.0*l.size/b;(1..b).map{l.shift(s.ceil).sum}}

```

Try it online!

# Answer
> 3 votes
# MATL, 6 bytes

```
vi3$es

```

Try it online! Or verify all test cases.

### Explanation

Consider input `4`, `[0,3,7,2,5,1]` as an example.

```
v       % Vertically concatenate stack contents. Gives the empty array, []
        % STACK: []
i       % Input b
        % STACK: [], 4
        % Implicitly input L at the bottom of the stack
        % STACK: [0,3,7,2,5,1], [], 4
3$e     % 3-input reshape. This reshapes L with [] rows and b columns, in
        % column-major order (down, then across). [] here means that the
        % number of rows is chosen as needed to give b columns. Padding
        % with trailing zeros is applied if needed
        % STACK: [0 7 5 0;
                  3 2 1 0]
s       % Sum of each column
        % STACK: [3 9 6 0]
        % Implicitly display

```

# Answer
> 2 votes
# C (gcc), 107 bytes

```
j,k,t,Q;f(A,l,b)int*A;{for(j=~0;b>++j;printf("%d,",t))for(t=k=0;(Q=!!(l%b)+l/b)>k;t+=Q<l?A[Q]:0)Q=k+++Q*j;}

```

Try it online!

# Answer
> 2 votes
# Haskell, 61 bytes

```
l#0=[]
l#n|o<-length l`div`n+1=sum(take o l):(drop o l)#(n-1)

```

Try it online!

# Answer
> 2 votes
# Java 10, ~~96~~ ~~89~~ 86 bytes

```
a->b->{int r[]=new int[b],i=0,n=a.length;for(;i<n;)r[i/((n+b-1)/b)]+=a[i++];return r;}

```

Try it online here.

Found a shorter way to write `i/(n/b+(n%b==0?0:1)` here: `i/((n+b-1)/b)`

Thanks to Olivier Grégoire for golfing 3 bytes.

Ungolfed version:

```
input -> bins -> { // input is int[] (original array), bins is int (number of bins)
    int result[] = new int[bins], // resulting array, initialized with all 0
    i = 0, // for iterating over the original array
    n = a.length; // length of the original array
    for(; i < n ;) // iterate over the original array
        result[i / ((n + bins - 1) / bins)] += input[i++]; // add the element to the right bin; that's bin n/bins if bins divides n, floor(n/bins)+1 otherwise
    return result;
}

```

# Answer
> 1 votes
# Elixir, 98 bytes

```
fn l,b->Enum.map Enum.chunk(l++List.duplicate(0,b-1),round Float.ceil length(l)/b),&Enum.sum/1 end

```

Try it online!

The best Elixir has is splitting into parts with a length of **n**. And it cannot ceil division as integer very well, so we do float division, round it up. Unfortunately the only way to do this results in a float, so we round it again to an integer.

# Answer
> 1 votes
# Perl 6,  ~~52 51~~  50 bytes

52 bytes: Test it

```
->\L,\b{L.rotor(:partial,ceiling L/b)[^b].map: &sum}

```

51 bytes: Test it

```
{@^a.rotor(:partial,ceiling @a/$^b)[^$b].map: &sum}

```

50 bytes: Try it

```
{map &sum,@^a.rotor(:partial,ceiling @a/$^b)[^$b]}

```

---

47 bytes non-competing Test it

```
{@^a.rotor(:partial,ceiling @a/$^b)[^$b]».sum}

```

It's non-competing as `».sum` is allowed to do the calculations in parallel. So it may or may not be in linear time.

---

## Expanded:

```
{  # bare block with two placeholder parameters ｢@a｣ and ｢$b｣

  map                   # for each sublist

    &sum,               # find the sum

    @^a                 # declare and use first parameter

    .rotor(             # break it into chunks

      :partial,         # include trailing values that would be too few otherwise

      ceiling @a / $^b # the number of elements per chunk

    )[ ^$b ]           # get the correct number of chunks if it would be too few

}

```

# Answer
> 1 votes
# PHP, 88 bytes

```
function($a,$b){return array_map(array_sum,array_chunk($a,~-count($a)/$b+1))+[$b-1=>0];}

```

anonymous function, takes array and integer, returns array

The only golfing potential this had was replacing `ceil(count($a)/$b))` with `(count($a)-1)/$b+1` and abbreviating `(count($a)-1)` with `~-count($a)`. The resulting float is implicitly cast to integer in the `array_chunk` call.

Try it online.

# Answer
> 1 votes
# Charcoal, 22 bytes

```
ＮθＡηＷ﹪Ｌηθ⊞η⁰Ｅ⪪η÷ＬηθＩΣι

```

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

```
Ｎθ

```

Input `b`.

```
Ａη

```

Input `L`.

```
Ｗ﹪Ｌηθ⊞η⁰

```

Push a `0` to `L` until `L`'s length is divisible by `b`.

```
Ｅ⪪η÷ＬηθＩΣι

```

Divide `L`'s length by `b` and split `L` into sections of that length, then sum each section and cast to string for implicit output on separate lines.

# Answer
> 1 votes
# JavaScript (Node.js), 71 bytes

```
L=>b=>Array(b).fill().map((v,i)=>L.slice(s=i*b,s+b).reduce((x,y)=>x+y))

```

Try it online!

# Answer
> 1 votes
# C (clang), 58 bytes

```
i;f(*L,l,b,*m){b=l/b+!!(l%b);for(i=0;i<l;m[i++/b]+=L[i]);}

```

Try it online!

`f()` takes parameters as follows:
`L`: pointer to input array
`l`: length of input array
`b`: number of bins
`m`: pointer to buffer that receives new array

Following is a re-entrant version @ 60 bytes:

```
f(*L,l,b,*m){b=l/b+!!(l%b);for(int i=0;i<l;m[i++/b]+=L[i]);}

```

---
Tags: code-golf, restricted-complexity
---