title: Tips for golfing in PowerShell

text:
# Question
Title: Tips for golfing in PowerShell
What general tips do you have for golfing in Windows PowerShell? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to PowerShell (e.g. "remove comments" is not an answer). Please post one tip per answer.

—taken nearly verbatim from marcog's question.

# Answer
> 28 votes
Powers of 10 literals with scientific notation:

```
4e6 = 4000000

```

Powers of 2 literals:

```
4KB = 4096
4MB = 4194304
4GB = 4294967296

# TB and PB suffixes also exist, but less useful for golf.

```

Could come in handy.

# Answer
> 24 votes
If you need to run a loop, and you know *exactly* how many times it needs to run every time, consider piping an array of contiguous integers into `ForEach-Object` via the `%` alias instead of using `for`.

`for($x=1;$x-le10;$x++){`...`}`

vs

`1..10|%{`...`}`

# Answer
> 20 votes
You can skip spaces *a lot* in PowerShell. If it feels like it might not be needed, it quite possibly isn't. This is particularly useful in comparisons.

Example:

```
$x-eq$i-and$x-ne9

```

vs.

```
$x -eq $i -and $x -ne 9

```

---

If you need to branch your script based on the result of a single test which may have multiple outcomes, `switch` can sometimes match or beat an if statement.

Example (switch vs. if/else - tie):

```
if($x%2-eq0){'even'}else{'odd'}

```

vs.

```
switch($x%2){0{'even'}1{'odd'}}

```

Or (switch vs. if/elseif/else - switch wins by 15):

```
if($x%2-eq0){'even'}elseif($x%2-eq1){'odd'}else{'error'}

```

vs.

```
switch($x%2){0{'even'}1{'odd'}2{'error'}}

```

If the switch is *actually* based on certain math results, like the modulo operation above, you can replace the switch entirely with an array. Here, it saves another 13 characters and is even shorter than the original two-option if/else statement. (Thanks to Danko Durbic for this bit.)

```
('even','odd','error')[$x%2]

```

If you will be using a particular command a lot, especially one without a pre-existing short-hand alias, set up a single-character alias early on.

Example:

```
nal g Get-Random;g 10;g 10;g 10

```

vs.

```
Get-Random 10;Get-Random 10;Get-Random 10

```

# Answer
> 16 votes
Encapsulating the command that defines a variable in parenthesis allows you to feed the variable's definition directly to other commands.

For example, you can set $x and then set $y based on the value of $x in one shot with this:

```
$y=($x=1)+1

```

Instead of this:

```
$x=1;$y=$x+1

```

You can set $h and output it with this:

```
($h='Hello World!')

```

Instead of this:

```
$h='Hello World!';$h

```

# Answer
> 15 votes
A switch can act like a loop, when given an array. For example:

```
$FooBarMeh='a','b','c'
switch ($FooBarMeh)
{
    'a'{'FOO'}
    'b'{'BAR'}
    default{'MEH'}
}

```

Will output:

> FOO
> BAR
> MEH

I'm not totally sure where this will be useful, but I expect it will be handy for someone some time.

# Answer
> 13 votes
Want to find the maximum or minimum of a collection of values? Tried

```
(...|measure -ma).Maximum

```

or

```
(...|measure -mi).Minimum

```

already?

Just sort and use the last or first item:

```
(...|sort)[-1]  # maximum
(...|sort)[0]   # minimum

```

# Answer
> 13 votes
Replace `[math]::pow` with multiplication. Instead of

```
[math]::pow($a,$b)

```

you can write

```
"$a*"*$b+1|iex

```

This works for integer exponents \>= 0.

# Answer
> 13 votes
# Shortening Property Names

Sadly, unlike parameters, properties/methods (anything accessed with a dot `.`) cannot usually be shortened down to its unambiguous form.

But certain cmdlets can operate on property names and take wildcards, and there are little-known parameter sets of `%` and `?` that can be useful.

Usually we pass in a scriptblock and refer to the item with `$_`, but there's another form of these that takes a property name, and it accepts a wildcard.

```
$o|select Le*
$o|%{$_.Length}

```

With a property like `.Length` we can't use the v3 magic that would normally work on an array because `Length` is a property of the array itself, so the above two could be used to get the lengths of the individual members. The `select` comes in a little bit shorter.

But `%` can take a property name directly and return that value:

```
$a|% Length

```

Which can be shortened with wildcards. The wildcard must resolve to a single property (or method, more on that later), so it will throw a helpful error if it doesn't, indicating exactly which members it could resolve to.

In the case of `Length`, `Le*` is typically the shortest. Even on a single string, this method is 1 byte shorter than just using the property.

```
$a.Length                # 9   #(doesn't work on array)
$a|%{$_.Length}          # 15
$a|% Le*                 # 8

```

But depending on what you're doing with this, this can be worse. You can do `$a.Length*5` but to do it with the pipeline expression you'd have to wrap it `($a|% Le*)*5`; might still be worth it if it's against an array, but the point is it's not always appropriate as a straight substitution.

It works with methods too, and you can leave off the `()` which makes a full name the same length, but same restriction as above about sometimes having to wrap it. ~~The method must have an overload that takes no parameters~~ (you can pass arguments by placing them after the method name, which is really nice):

```
$a.ToUpper()             # 12
$a|% *per                #  9

```

With arguments:

```
'gaga'-replace'g','r'    # 21
'gaga'|% *ce g r         # 16

```

These aren't strictly the same in that the `-replace` operator does a regex replace, but if you're just doing a string replace, it can (now) be shorter to use the method; it helps that the strings are cmdlet arguments instead of method arguments so they don't need to be quoted.

## Where-Object Properties

`?` can take (partial) property names as well, and apply an "operator" to it (in the form of switch parameters). Again this can be shorter than using the standard `Where-Object` scriptblock approach if the property name is sufficiently long and unique.

```
$a|?{$_.Length-gt5}      # 19
$a|? Le* -GT 5           # 14

($a|% Le*)-gt5           # 14 - Lengths, not objs

```

# Answer
> 12 votes
Comparison operators work on collections of values by returning matching values:

```
1..5 -gt 2

```

will yield `3`, `4` and `5`. In some cases this can help to save an otherwise longer `|?{$_...}`.

`-match` is a comparison operator too.

# Answer
> 12 votes
Use aliases whenever possible. There are a bunch of useful ones:

```
?        Where-Object
%        ForEach-Object
gu       Get-Unique
sort     Sort-Object
iex      Invoke-Expression

```

# Answer
> 10 votes
`for` loops can have anything between 0 and three statements in their header:

Endless loop:

```
for(){}

```

Loop with initialization:

```
for($n=0){}

```

Loop with initialization and end condition:

```
for($n=0;$n-lt7){}

```

In such cases the additional semicolons at the end may be omitted (it's explicitly stated in the language specification, so it's not an implementation detail) in contrast to C-like languages which always require exactly three statements.

This also makes `while` a bit shorter. Compare

```
while(...){}

```

and

```
for(;...){}

```

With the added bonus that you can stick in a previous line (if there is one) into the `for` as well without extra cost (and even saving a character).

# Answer
> 10 votes
Finding a sum the long way:

```
(...|measure -s).Sum

```

A shorter way:

```
...|%{$s+=$_};$s

```

And even shorter:

```
...-join'+'|iex

```

# Answer
> 9 votes
The `Get` verb is implied. This can shorten any `Get-Frob` to just `Frob`. Frequent contenders are `date` or `random`.

Note that this *won't* work properly in some cases because you might have GNU utilities in your path (or other native programs that clash). Order of command lookup in that case seems to prefer the native program before it considers cmdlets with the `Get-` removed:

```
PS Home:\> date

Freitag, 15. November 2013 07:13:45

PS Home:\> $Env:Path += ';D:\Users\Joey\Apps\GnuWin32\bin'
PS Home:\> date
Fr Nov 15 07:14:13 W. Europe Standard Time 2013

```

# Answer
> 9 votes
Semicolons and line breaks are interchangeable. Golfed code is often more readable if not jammed into a single line. And the length is still the same (provided you use U+000A as line break which PowerShell handles without problems).

# Answer
> 8 votes
Casting to string:

```
[string]$x

```

vs.

```
"$x"

```

Casting to string like this can also be used to flatten an array of strings, instead of joining it:

```
$a = @('a','b','c')
$a -join ' '

```

vs.

```
$a = @('a','b','c')
"$a"

```

Casting a string to a numeric type:

```
[int]$x     [float]$x

```

vs.

```
+$x

```

Also very useful to know that PowerShell *always* takes the type of the left operand to determine the final type of an expression and conversions to apply:

```
'1'+2    -> '12'
1+'2'    -> 3

```

which can help determining where needless casts are.

# Answer
> 8 votes
If you are assigning an array that you know will only have two values, don't use indexing.

Something like this:

```
$a="apple","orange"
$a[0] # apple
$a[1] # orange

```

Can easily be turned into this:

```
$a,$o="apple","orange"
$a # apple
$o # orange

```

This can also be useful for if you just need to the first element of an array:

```
$a,$b=1..10
$a # 1
$b # 2..10

```

# Answer
> 6 votes
When using a number as an argument to an operator that would otherwise require a string, you can use the number directly. Compare

```
...-join'0'

```

vs.

```
...-join0

```

Works with `-split` as well. The argument is always converted to a string first.

# Answer
> 6 votes
Don't forget that you don't always need to provide the full name of a parameter, and some parameters are positional.

```
Get-Random -InputObject (0..10)

```

...can be trimmed to...

```
Get-Random -I (0..10)

```

...because "I", in this case, is enough to uniquely identify `InputObject` from the other valid parameters for this command.

You could trim it further to...

```
Get-Random (0..10)

```

...because `InputObject` is a positional parameter.

Piping is usually shorter than feeding objects as a parameter, especially when it can remove the need for parenthesis. Let's trim our random number generator further...

```
0..10|Get-Random

```

Also be on the lookout for other ways to accomplish the same thing, even if you can't change the command. For the above case, you could do this:

```
Get-Random 11

```

Or, incorporating another suggestion\*:

```
Random 11

```

\**Note: Omitting `Get-` from a command name can bloat the run time by about 50,000%. Not bad if you only need the command once, but be careful using it in long loops.\*

And that's how can knock a simple command down to a third of its size.

# Answer
> 6 votes
Automatic variables have booleans for True and False as `$true` and `$false` but you can get similar results using the logical not operator `!` and the integers 0 and 1( or any non-zero integer.)

```
PS C:\Users\matt> !1
False

PS C:\Users\matt> !0
True

```

Near all PowerShell expressions can be evaluated as booleans. So as long as you are aware of how certain data is evaluated you can get booleans and never need to explicitly cast them. Be aware of the LHS value when doing these.

* Integer 0 is false and non-zero integers are evaluated to true.
* non-zero length strings are true and empty or null (and nulls themselves) strings are false.

There are other examples but you can easily test by doing a cast

```
PS C:\Users\matt> [bool]@(0)
False

```

# Answer
> 6 votes
Fake ternary operator. You can assign straight from an `if` statement:

```
$z=if($x-eq$y){"truth"}else{"false"}

```

But you can use a 2-element array and use the test to index into it. $falsey results get element 0, $truthy results take element 1:

```
$z=("false","true")[$x-eq$y]

```

NB. that this is really doing array indexing, and if the test results in a value which *can* be cast to an integer, you'll ask for an item outside the bounds of the array and get $null back, and will need to do `!(test)` to force cast the result to a bool, with the options reversed.

\[ Edit: There's a genuine ternary operator in PowerShell 7+ in the C-language-style `cond ? 1 : 0` \]

# Answer
> 5 votes
Absolute value

With

```
$n=-123

```

Instead of

```
[math]::abs($n)

```

use

```
$n-replace'-'

```

Of course, the savings are cancelled if parentheses are needed.

# Answer
> 5 votes
If you need to silence errors, the obvious variant would be

```
try{ <# something that throws errors #> }catch{}

```

However, this is way too long. A shorter variant is to run the `try` block as a script block and just redirect the errors into an unset variable (`$null` would be the usual one, but that's still too long):

```
.{ <# something that throws errors #> }2>$x

```

This saves five valuable bytes (if not the world).

# Answer
> 5 votes
Use the `$ofs` special variable to change the **O**utput **F**ield **S**eparator used when stringifying an array. Useful if you're needing to transform arrays to strings multiple times.

For example:

```
$a=1,2,3,4
$a-join',';$a-join','
$ofs=',';"$a";"$a"

```

Saves 2+*n* characters on the 2nd `-join`, where *n* is the length of the separator, and saves an additional 5+*n* for the 3rd `-join` and each thereafter.

# Answer
> 5 votes
## **Use `[bigint]` instead of `[Math]::floor`**

The `bigint` datatype is a numeric type that can store arbitrarily large numbers and holds no decimal values. It always floors when using `[bigint]::new()`.

A suffix for it was added in PowerShell core but using the `n` prefix rounds normally instead of floor which doesn't work for this.

Example:

```
[bigint](.9)        # 0
[bigint]3/4         # 0
[bigint](.1)        # 0
[bigint]1/4         # 0
[bigint]10.5        # 10
[bigint]100/3       # 33

(.9)n               # 1
3/4n                # 1
(.1)n               # 0
1/4n                # 0
10.5n               # 11
100/3n              # 33

```

# Answer
> 4 votes
`Invoke-Expression` and `Get-Random` can also get pipeline input instead of arguments.

For `iex` this allows to save parentheses on some expressions:

```
iex 1..5-join'+'   # won't work
iex(1..5-join'+')  # does work, but has extra parentheses
1..5-join'+'|iex   # doesn't need the parentheses

```

In case of `random` this allows a common case to be optimized a bit:

```
random -mi 10 31   # gets a random integer between 10 and 30
10..30|random      # much better :-)
(random 21)+10     # if needed in another expression that doesn't require extra
                   # parentheses

```

The latter way of using it simply selects an item from a list. The `-c` argument can be given to allow more than a single selection.

# Answer
> 4 votes
Consider storing repeated script blocks in variables, instead of using functions.

I was going to use this to save some characters in my Rock, Paper, Scissors implementation before I realized that re-writing the function as a variable made even the variable unnecessary. This could still be useful for other scripts though, where you're actually running the same code multiple times.

```
function Hi{echo 'Hello, World!'};Hi

```

vs.

```
$Hi={echo 'Hello, World!'};&$Hi

```

# Answer
> 4 votes
Converting floating-point numbers to integers in PowerShell is a bit of a minefield. By default the conversion does Bankers Rounding which doesn't always trim off the decimal and leave the smaller whole number, or always round .5 up to the next number like people do casually, it rounds evens one way and odds another way - this can be surprising, e.g.

```
PS C:\> [int]1.5
2

PS C:\> [int]2.5
2

```

and break codegolf calculations. Many other common languages do truncation-rounding, therefore golf questions often require truncation. You might reach for `[Math]::Floor()` as the next best thing, but beware this only behaves the same as truncation for positive numbers, but it takes negative numbers lower - further away from zero. `[Math]::Truncate()` is what you need to bring PS behaviour in line with other language's default rounding, but it's a lot of characters.

Regex replacing digits after the decimal point can help save a couple of characters:

```
[Math]::Truncate(1.5)
[Math]::Floor(1.5)
1.5-replace'\..*'

[Math]::Truncate($a)
[Math]::Floor($a)
$a-replace'\..*'
$a.split('.')[0]        # literal character split, not regex pattern split

```

# Answer
> 4 votes
### Use variables to store .NET names

As outlined by cogumel0 in this answer, you can use variables to store .NET type names. For example, changing

```
param($a)$a-[math]::pow(2,[math]::floor([math]::log($a,2)))

```

into

```
param($a)$a-($m=[math])::pow(2,$m::floor($m::log($a,2)))

```

saved 3 bytes in this example.

# Answer
> 4 votes
You can use `$s|% t*y` instead `[char[]]$s` to split a string to char array. Given from TessellatingHeckler's answer: `% t*y` expands to `| ForEach-Object -Method ToCharArray` equiv. of `"$args".ToCharArray()`

For example, compare

```
$s|% t*y

```

and

```
[char[]]$s

```

and

```
$s.ToCharArray()

```

It's useful with `$args` especially: `$args|% t*y`

# Answer
> 4 votes
You can access static methods via instance:

```
$x=4,2,3
$x::Sort($x) # [Array]::Sort($x)
"$x" # 2 3 4
$x::Reverse($x) # [Array]::Reverse($x)
"$x" # 4 3 2

```

BigInteger suffix (`n`) introduced in PowerShell 7:

```
(0n)::Pow(4,5) # [bigint]::Pow(4,5)
(0n)::Abs(-3) # [bigint]::Abs(-3)
2*0n::Abs(-3) # some cases don't require parentheses

```

# Answer
> 3 votes
### Use Boolean logic in place of if-counters in a loop

Suppose you're adding all even numbers from 1 to 10 ... `2+4+6+8+10=30`

```
1..10|%{if($_%2-eq0){$o+=$_}};$o

```

You could use Boolean negation to shorten it to

```
1..10|%{if(!($_%2)){$o+=$_}};$o

```

to save a byte, but how about instead use implicit casting of Booleans to ints, and roll the conditional into the accumulator

```
1..10|%{$o+=$_*!($_%2)};$o

```

Saves 6 bytes in this example.

# Answer
> 3 votes
### Reversing an array

Comes in handy in a lot of challenges where the output is mirrored in some fashion.

Suppose you have

```
$a=1,2,3,4,5

```

The traditional reversal method is long, boring, and doesn't leave the array on the pipeline for immediate use.

```
[array]::reverse($a)

```

Indexing directly into the array in reverse order saves a few bytes, since it leaves the results on the pipeline, but is still rather long:

```
$a[($a.count-1)..0]

```

Instead, try a loop

```
$a|%{$a[-++$i]}

```

# Answer
> 3 votes
Starting with PowerShell Core 6, you can also use ranges for characters:

```
'a'..'z'

```

which can replace the much more cumbersome

```
0..25|%{[char]($_+97)}

```

# Answer
> 3 votes
A simple one but control-flow statements (as opposed to pipelines), such as `if`, `for`, and `while`, do not need a semi-colon after their braces.

E.g.

```
# Control-flow statements (All are valid)
if(...){...}"foo"
for(...){...}"foo"
while(...){...}"foo"
switch(...){...}"foo"

# Pipelines
1..2|%{...}"bar" #This will throw an error.
1..2|%{...};"bar" #This will work.

```

A free byte that's easy to miss.

# Answer
> 3 votes
# `SLS` instead `-match`

You can use an `sls` cmdlet (alias for Select-String) with `|% M*` as shortcut for property `Matches` instead a `-match` operator with a `$Matches` automatic variable. Compare:

`$args|sls 'pattern'|% M*`

vs.

`if("$args"-match'pattern'){$Matches}`

---

You can also use `sls` with `-a` parameter (`-AllMatches`) to find all matches:

`$args|sls 'pattern'-a|% M*`

---

Also, you can find all matched lines in a multiline string without explicitly line breaking. It need to use a regexp option `?(m)`. Compare:

`$args|sls '(?m)^pattern$'-a|% M*`

vs.

`$args-split"``n"|%{$_-match'^pattern$';$Matches}`

# Answer
> 3 votes
Rather than using `[bool]` for boolean conversion you can instead use `!!`

```
1         # 1
[bool]1   # True
!!1       # True

0         # 0
[bool]0   # False
!!0       # False
!!$null   # False

```

# Answer
> 2 votes
If you need an `if`/`else` at the end of the program (maybe to handle a special case differently), then instead of

```
if(foo){a}else{b}

```

do

```
if(foo){a;exit}b

```

which saves a character.

# Answer
> 2 votes
Declaring an anonymous function should come up alot. There are multiple variations of this that are covered here https://stackoverflow.com/questions/10995667/lambda-expression-in-powershell involving scripts blocks. I use a similar one to this

```
$a={iex([int[]][char[]]$args[0]-join"+")}
&$a 'abcd'

```

This would save a few character from declaring a function with a name and goes better if used more than once. The one above converts a string into a char array then into an int array. Then creates a string joined with + so that Invoke-Expression will add all the values.

# Answer
> 2 votes
When declaring a hard-coded list of strings, depending on the size of the strings and the number of them, it's often shorter to split a single string up by spaces, since space-delimited splitting doesn't require a delimiter provided as a parameter

For example,

Instead of

```
$numbers='one','two','three','four','five','six','seven','eight','nine','ten'

```

Do

```
$numbers=-split'one two three four five six seven eight nine ten'

```

You can further delimit with another character and split twice to hold shortened hard-coded multidimensional arrays

# Answer
> 2 votes
# Use `$x-shr$k` if you want to get the result of \\$ \big\lfloor{x\over2^k}\big\rfloor \\$.

The biggest application of this is getting the truncated int result of halving a positive number without having to deal with Banker's rounding.

Works on ints and floats, however it will cast floats to ints before shifting, resulting in the same banker problem as before. Whether or not this is acceptable will obviously depend. Below is a sample script that shows the results of `-5..10`. `3/2` and `7/2` demonstrate the difference in return value.

Try it online!

<sup>Inspired by this answer</sup>

# Answer
> 2 votes
# Get `Length` of elements of an array

You can write the name immediately after the point to get the value of the property or method.

```
$a=gci
$a.fullName

```

compare to:

```
$a|%{$_.fullName}

```

Both expressions returns array like this:

```
C:\Archive
C:\PerfLogs
C:\Pictures
C:\Program Files
C:\Program Files (x86)
C:\Users
C:\Windows

```

There is a property `Length` which is defined for the array itself. So the Powershell expression `$a.Length` returns the number of elements in an array. You can use the Shortening Names to get length of elements:

```
$s=@('22','55555','7777777')
$s|% Length       # 11 bytes

```

or shortcut:

```
$s|% Le*          # 8 bytes.

```

Compare to:

```
$s|%{$_.Length}   # 15 bytes

```

Result is the array `2,5,7`, not the number `3`.

# Answer
> 2 votes
# Use the `new()` method instead of `New-Object`

For example, instead of doing the following (37 bytes):

```
New-Object Drawing.Bitmap(1024,1024)

```

Try (32 bytes):

```
[Drawing.Bitmap]::new(1024,1024)

```

Kind of an edge case, but you can do this pretty much anytime you initialize a new .NET object. Sadly, there's no equivalent for COM objects so you still have to use `New-Object` for those :P

# Answer
> 2 votes
String multiplication:

```
"#"*5 ==> #####

```

# Answer
> 1 votes
If you're calling a command with a string argument, you don't need quotes unless there are spaces:

```
gci MyPath
gci 'My Path'

```

But that space cost you 2 extra bytes. You can save a single byte by escaping the space without quotes:

```
gci My` Path

```

This is only worth it when there's a single space, because there's no advantage with 2 or more.

# Answer
> 1 votes
If a path contains more than 1 space, you can do :

```
gci C:\My*Example*Path

```

instead of

```
gci 'C:\My Example Path'

```

or

```
gci C:\My` Example` Path

```

# Answer
> 1 votes
# Use Uppercase over lowercase when dealing with ASCII values

When given the choice, it's usually better to deal entirely with Uppercase. This is because their range is 65..90 vs lowercase's 97..122. For example, the one-liner to generate `ABCD...Z` in PS v5

```
-join([char[]](65..90))
-join([char[]](97..122))

```

This still applies when normalizing mix-case because using the `|%` short-property trick, ToUpper and ToLower shorten to `*per` and `*wer`, respectively.

```
"Lower to upper: "+-join([char[]](97..122))|% *per
"Upper to lower: "+-join([char[]](65..90))|% *wer

```

Try it online!

# Answer
> 1 votes
# Short way to convert bits to integer:

if you trust that `$args` contains `int` only (see Joey's comments below):

```
$args|%{$r+=$_+$r};$r

```

if you assume that `$args` is an array of `int` or `string` representation:

```
$args|%{$r+=+$r+$_};$r

```

`$args` is an array of `char` 48, 49:

```
$args|%{$r+=+$r+"$_"};$r

```

A sliding byte containing 8 bits from the array of `int`:

```
$args|%{($r=2*$r%256+$_)}

```

Compare to:

```
[Convert]::ToInt64($args,2)

```

# Answer
> 1 votes
If you're tackling a drawing/rendering problem that involves creating, manipulating, and then printing a 2D array, I've found it shorter character-wise to instead deal with a 1D array that you access with `$arr[$y*$width+$x]` rather than `$arr[$y][$x]`.

It's very simple and short to set up the array with blanks or zeroes with something like

```
$arr=@(" ")*$width*$height

```

Half the reason for using 1D arrays is that initialization is much shorter.

To easily print the 1D array as a "2D" array to console, you can use a width-based regular expression to split your array into rows. This will join your array into a string, and then split the string into equally sized chunks and print them in order, effectively printing your 1D array as a 2D array:

```
-join$arr-split"(.{$width})"|?{$_}

```

# Answer
> 0 votes
## Utilize subtraction and booleans in comparisons

If you are in need of an operation like `-ne` and `-gt` and you are counting down, you can use the subtraction operator, `-`, instead of using an extra two bytes

Example:

```
for($i=40;$i-10;$i--){$i}                                         # 40...11
for($i=40;$i-gt10;$i--){$i}                                       # 40...11
for($i=40;$i-ne10;$i--){$i}                                       # 40...11
"$(for($i=40;$i-10;$i--){$i})"`
-eq"$(for($i=40;$i-gt10;$i--){$i})"`
-eq"$(for($i=40;$i-ne10;$i--){$i})"                               # true

```

# Answer
> 0 votes
## Fake ternary operator for recursive invocations

If the fake ternary operator returns a code block and a function, it can be used to perform recursive invocations:

```
$f={&($f,{result})[condition]}

```

Notice the `{}` around the result and the `&` before the array instead of before the function variable `$f`

Example, a recursive function that returns only when `$r` has the value 1:

```
$f={if($r=(Get-Random)%2){$r}else{&$f}} # with an if else
$f={&($f,{$r})[($r=(Get-Random)%2)]}    # with a fake ternary operator recursive invocations

```

---
Tags: code-golf, tips, powershell
---


title: Multi-dimensional reversal

text:
# Question
Title: Multi-dimensional reversal
Given an N-dimensional orthogonal (non-ragged) array of non-negative integers, and an indication of which dimensions to reverse, return the array but reversed along those dimensions. The indication may be given as a Boolean list of length N or a list of a subset of the first N dimensions indexed from 0 or 1.

Please state your input formats. Code explanations are much appreciated.

## Walked-through example

We are given the 2-layer 3-row 4-column 3D-array

```
[[[ 1, 2, 3, 4],
  [ 5, 6, 7, 8],
  [ 9,10,11,12]],

 [[13,14,15,16],
  [17,18,19,20],
  [21,22,23,24]]]

```

and one of

`[true,false,true]` (Boolean list)
`[0,2]` (0-indexed list)
`[1,3]` (1-indexed list)

We need to reverse order of the first and last dimensions, that is the layers and the elements of the rows (the columns), but not the rows of each layer. First (the actual order you do this in does not matter) we reverse the order of the layers:

```
[[[13,14,15,16],
  [17,18,19,20],
  [21,22,23,24]],

 [[ 1, 2, 3, 4],
  [ 5, 6, 7, 8],
  [ 9,10,11,12]]]

```

and then we reverse the order of the elements of each row:

```
[[[16,15,14,13],
  [20,19,18,17],
  [24,23,22,21]],

 [[ 4, 3, 2, 1],
  [ 8, 7, 6, 5],
  [12,11,10, 9]]]

```

## Test cases

`[[[1,2,3,4],[5,6,7,8],[9,10,11,12]],[[13,14,15,16],[17,18,19,20],[21,22,23,24]]]`
`[true,false,true]`/`[0,2]`/`[1,3]`
↓
`[[[16,15,14,13],[20,19,18,17],[24,23,22,21]],[[4,3,2,1],[8,7,6,5],[12,11,10,9]]]`

---

`[[1,2,3],[4,5,6]]`
`[true,false]`/`[0]`/`[1]`
↓
`[[4,5,6],[1,2,3]]`

---

`[[1],[4]]`
`[true,false]`/`[0]`/`[1]`
↓
`[[4],[1]]`

---

`[[7]]`
`[true,true]`/`[0,1]`/`[1,2]`
↓
`[[7]]`

---

`[1,2,3,4,5,6,7]`
`[true]`/`[0]`/`[1]`
↓
`[7,6,5,4,3,2,1]`

---

`[]`
`[true]`/`[0]`/`[1]`
↓
`[]`

---

`[[],[]]`
`[false,false]`/`[]`/`[]`
↓
`[[],[]]`

---

`[[[[3,1,4,1],[5,9,2,6]],[[5,3,5,8],[9,7,9,3]]],[[[2,3,8,4],[6,2,6,4]],[[3,3,8,3],[2,7,9,5]]]]`
`[true,false,true,true]`/`[0,2,3]`/`[1,3,4]`
↓
`[[[[4,6,2,6],[4,8,3,2]],[[5,9,7,2],[3,8,3,3]]],[[[6,2,9,5],[1,4,1,3]],[[3,9,7,9],[8,5,3,5]]]]`

---

`[[[[3,1,4,1],[5,9,2,6]],[[5,3,5,8],[9,7,9,3]]],[[[2,3,8,4],[6,2,6,4]],[[3,3,8,3],[2,7,9,5]]]]`
`[false,true,false,false]`/`[1]`/`[2]`
↓
`[[[[5,3,5,8],[9,7,9,3]],[[3,1,4,1],[5,9,2,6]]],[[[3,3,8,3],[2,7,9,5]],[[2,3,8,4],[6,2,6,4]]]]`

---

`[[[[3,1,4,1],[5,9,2,6]],[[5,3,5,8],[9,7,9,3]]],[[[2,3,8,4],[6,2,6,4]],[[3,3,8,3],[2,7,9,5]]]]`
`[false,false,false,false]`/`[]`/`[]`
↓
`[[[[3,1,4,1],[5,9,2,6]],[[5,3,5,8],[9,7,9,3]]],[[[2,3,8,4],[6,2,6,4]],[[3,3,8,3],[2,7,9,5]]]]`

# Answer
> 9 votes
# APL (Dyalog), ~~20~~ 9 bytes

```
⊃{⌽[⍺]⍵}/

```

Try it online!

**How?**

`/` \- reduce - take the rightmost element in the input (the array) and apply the function with next left element as left argument

`{⌽[⍺]⍵}` \- reverse in the `left argument` () dimension

\- flatten the enclosed array

# Answer
> 9 votes
# APL (Dyalog Unicode), 9 bytes

```
⊃{⊖[⍺]⍵}⌿

```

Try it online!

It looks like Uriel edited into something almost identical first, but I developed it independently. I thought this input format is invalid.

# Answer
> 8 votes
# JavaScript (Node.js), ~~58~~ ~~55~~ ~~53~~ 45 bytes

*Saved 8 bytes thanks to @Shaggy*

Takes input as `(indications)(array)`, where *indications* is a Boolean list.

```
f=([r,...b])=>a=>1/r?a.sort(_=>r).map(f(b)):a

```

Try it online!

### Commented

```
f = (                // f is a function taking:
  [r,                //   r = next 'reverse' Boolean flag
      ...b]          //   b = array of remaining flags
) =>                 // and returning an anonymous function taking:
  a =>               //   a = array (or sub-array) to process, or atomic element
    1 / r ?          // if r is defined:
      a.sort(_ => r) //   reverse a if r = 1; leave it unchanged otherwise
      .map(f(b))     //   for each element in the resulting array: do a recursive call,
                     //   using f to generate a new callback function for the next flag
    :                // else:
      a              //   a must be an atomic element and is simply left unchanged

```

# Answer
> 6 votes
# Python 2, ~~56~~ 55 bytes

```
f=lambda a,t:t and[f(l,t[1:])for l in a][::1|-t[0]]or a

```

Try it online!

# Answer
> 5 votes
# Haskell, ~~120~~ 119 bytes

the function f takes the N-dimensional list and a list of bool as input

```
class F r where f::[Bool]->r->r
instance F Int where f=seq
instance F r=>F[r]where f(a:y)=last(id:[reverse|a]).map(f y)

```

# Answer
> 5 votes
# Jelly, 8 bytes

```
”€ẋ”ṚpFv

```

Takes a 0-indexed list of dimensions.

Try it online!

### How it works

```
”€ẋ”ṚpFv  Main link. Left arg: D (dimensions, 0-based), Right arg: A (array)

”€ẋ       Repeat '€' d times, for each d in D.
   ”Ṛp    Perform Cartesian product of ['Ṛ'] and each string of '€'s, prepending a
          'Ṛ' to each string of '€'s.
      F   Flatten the result.
          If, e.g., D = [0,2,4], we build the string "ṚṚ€€Ṛ€€€€".
       v  Eval the resulting string, using A as left argument.

```

# Answer
> 5 votes
# , ~~80~~ ~~78~~ 77 bytes

Create the call to R's extractor `[` by creating a list of sequences reversed where indicated. They actually contain zeros, which are silently ignored. The `drop=F` is needed to prevent R's default dropping of dimensions. We need the `rev` call to the dimension reverse indicator, because of the way R fills arrays.

-2 thanks @Giuseppe

-1 using in-line assignment.

```
function(x,a,d=dim(x))do.call("[",c(list(x),Map(seq,r<-d*rev(a),d-r),drop=F))

```

Try it online!

Honorable mention to @JayCe who came up with a variation that gets the same result in the same length:

```
function(x,a,d=dim(x))array(x[t(t(expand.grid(Map(seq,r<-d*rev(a),d-r))))],d)

```

Try it online!

# Answer
> 4 votes
# 05AB1E, ~~23~~ ~~11~~ 10 bytes

```
'€s×'R«J.V

```

Try it online.

-12 bytes thanks to *@Mr.Xcoder*.

Input as 0-indexed truthy-values (i.e. `[0,2,3]`), which is the first input.

**Explanation:**

```
'€s×           # Repeat "€" the indices amount of times
               #  i.e. [0,2,3] → ["","€€","€€€"]
    'R«        # Append each with "R"
               #  i.e. ["","€€","€€€"] → ["R","€€R","€€€R"]
        J      # Join them all together
               #  i.e. ["R","€€R","€€€R"] → R€€R€€€R
         .V    # Execute string as 05AB1E code

```

For example: if the indices input-list is `[0,2,3]`, it will create the following string:

```
R€€R€€€R

```

Which will:

```
    €€€R    # Reverse the items in the most inner (4th level) lists
 €€R        # Reverse the most inner (3rd level) lists themselves
            # Do nothing with the inner (2nd level) lists
R           # Reverse the entire outer (1st level) list

```

---

**Original 23 byte answer:**

```
ćURvy„ RèJ…εÿ}}„ RXèJ.V

```

Input as boolean-list (i.e. `[1,0,1,1]`), which is the first input.

Try it online.

**Explanation:**

```
ćU                 # Pop and save the first boolean in variable `X`
  R                # Reverse the remaining boolean-list
   v    }          # Loop `y` over each of them:
    „ Rè           #  Take the string "R ", and index the current boolean (0 or 1) in it
    J              #  Join it together with the string of the previous iteration
    …εÿ}           #  Surround it with "ε" and "}"
         „ RXè     # Index variable `X` also in "R "
              J    # Join it together with the rest
.V                 # Execute string as 05AB1E code

```

For example: If the boolean input-list is `[1,0,1,1]`, it will create the following string:

```
εεεR}R} }R

```

Which will:

```
  εR}         # Reverse the items in the most inner (4th level) lists
 ε   R}       # Reverse the most inner (3rd level) lists themselves
ε       }     # Do nothing with the inner (2nd level) lists
         R    # Reverse the entire outer (1st level) list

```

# Answer
> 3 votes
# JavaScript (Node.js), 60 bytes

*A different (recursive) approach. doesn't beat Arnauld's answer ... yet....*

Takes the input as `array, boolean list`

```
f=(a,r)=>r>[]?(r[0]?a.reverse():a).map(c=>f(c,r.slice(1))):a

```

```
f=(a,r)=>r>[]?(r[0]?a.reverse():a).map(c=>f(c,r.slice(1))):a

console.log(f([[[[3,1,4,1],[5,9,2,6]],[[5,3,5,8],[9,7,9,3]]],[[[2,3,8,4],[6,2,6,4]],[[3,3,8,3],[2,7,9,5]]]],[true,false,true,true]))
```

# Answer
> 3 votes
# Japt, ~~15~~ 14 bytes

With some inspiration from Arnauld's solution.

Takes the indications as the first input, as a boolean array of `1`s and `0`s.

```
Ê?Vn@ÎÃ£ßUÅX:V

```

Try it

---

## Explanation

```
                   :Implicit input of boolean array U=indications and multi-dimensional integer array V
Ê                  :Get the length of U
 ?                 :If truthy (i.e., >0)
  Vn               :  Sort V
    @ÎÃ            :   Function that gets the first element of U; 0 will leave the array untouched, 1 will reverse it.
       £           :  Map each X
        ß          :  Run the programme again with the following inputs
         UÅ        :   U with the first element removed
           X       :   X will serve as the new value of V
            :      :Else
             V     :  Just return V

```

# Answer
> 3 votes
# Pyth, 15 bytes

```
.v+jk.n*\_*L\ME

```

Try it here!

Annoyingly, handling the empty dimension list case takes no less than 2 bytes... I'd rather use `ss` in place of `jk.n` but :| Assumes that the list to be transformed can be given in native Pyth syntax, as a string. I've written a converter to Pyth syntax to make testing easier. In the unfortunate case that the OP chooses not to allow this, a 17-byter will "fix" it:

```
.v+jk.n*\_*L\ME\E

```

# Answer
> 3 votes
# Clean, ~~122~~ 112 bytes

```
import StdEnv
class$r::[Bool]->r->r
instance$r where$_=id
instance$[r]| $r where$[a:y]=if(a)reverse id o map($y)

```

Try it online!

A version of Damien's Haskell answer using Clean's golfier type system. Really shows the extensive similarities between the two languages.

Explained:

```
import StdEnv                 // import basic stuff
class $ r :: [Bool] -> r -> r // $ takes a boolean list and returns a function on r to r
instance $ r                  // instance on all types, taken when no more specific instances exist
    where $ _ = id            // return the identity function for all arguments
instance $ [r] | $ r          // instance for lists of a type which has an instance itself
    where $ [a: y]
        = if(a) reverse id    // reverse if the head of the argument is true
            o map ($ y)       // composed with the map function acting on $ applied to the tail

```

# Answer
> 2 votes
# Ruby, 54 bytes

```
f=->a,d{r,*z=d;r&&a.reverse!;d==[]?a:a.map{|w|f[w,z]}}

```

Try it online!

# Answer
> 1 votes
# Mathematica, 7 bytes

```
Reverse

```

Function. Give it a nested list as the first argument, and the 1-based list of levels/dimensions to reverse as the second argument. Try it online!

Finally, another challenge where Mathematica has a builtin!

# Answer
> 1 votes
(untested but I *think* correct. compiler asm output looks like what I expect. Will update if/when I find time to write a test harness that creates and prints this data structure.)

# GNU C++ (portable) 148 bytes

```
#include<algorithm>
#include<cstdint>
struct m{intptr_t d,l,a[];void R(int*r){if(*r)std::reverse(a,a+l);for(int i=0;d&&i<l;((m*)a[i++])->R(r+1));}};

```

# GNU C++ (int=pointer and falls off a non-void function UB) 120 bytes

```
#include<algorithm>
struct m{int d,l,a[],R(int*r){if(*r)std::reverse(a,a+l);for(int i=0;d&&i<l;((m*)a[i++])->R(r+1));}};

```

This is a struct of depth counter, length, array of {integers or pointers}. In the bottom level of this non-binary tree (`depth==0`), the array of `intptr_t` is an array of integers. In higher levels, it's a `struct m*` stored in `intptr_t`. Traversal takes a cast.

The `R()` reverse function is a member function because that saves declaring an arg, and saves a lot of `p->` syntax to reference the struct members vs. the implicit `this` pointer.

**The only GNU extension is the C99 flexible array member to make a variable-sized struct**, which is supported in C++ as a GNU extension. I could have used a `*a` member pointing to a separately-allocated array and have this be plain ISO C++. (And that would actually save a byte without requiring any other changes). I wrote this as a mockup / reference implementation for an asm version.

---

The shorter version with just `int` also declares `R()` as returning `int` instead of `void`. These two bits of hackery are unrelated; this is just the "works on at least one implementation" version.

It should work fine on 32-bit targets (where `int` can hold a pointer), as long as you compile with gcc7 or older, or disable optimizations. (`gcc8 -O3` assumes that execution can't reach the bottom of a non-`void` function because that would be UB.) x86 `gcc -m32 -O3` should work fine with gcc7, like on Godbolt where I included both versions (in different namespaces) and a non-member-function version.

### Ungolfed

**The function arg, `int r[]`, is an array of 0 / non-zero integers that indicate whether a given depth should be swapped, starting with the outer-most level.**

```
#include<algorithm>  // for std::reverse
#include<cstdint>    // for intptr_t.  GNU C defines __intptr_t, so we could use that...

struct m{
    __intptr_t d,l,a[];    // depth = 0 means values, >0 means pointers.
    // l = length
    //__intptr_t a[];  // flexible array member: array contiguous with the struct

    void R(int r[]) {
        if(*r)
            std::reverse(a, a+l);   // *r && std::reverse() doesn't work because it returns void.

        if(d) // recurse if this isn't the bottom depth
            for(int i=0 ; i<l ; i++)  // tree traversal
                ((m*)a[i])->R(r+1);   // with the rest of the depth list
    }

}; // struct m

```

When we recurse, we pass `r+1`, so checking the current depth is always `*r`.

An earlier version just passed `r` unchanged, and checked `r[d]`. With a flexible array member, I needed to store some kind of last-level indicator because `a[]` is not a pointer, it's a true array with no indirection. But with a `intptr_t *a` member, I couldn't just have that be `nullptr` for the leaf level, because I want it to be values.

Reversing the current level before or after the tree traversal shouldn't matter. I didn't try to do it *during*.

I'm not *sure* that `std::reverse` is worth the byte count vs. a manual loop, especially if I can work in calling `R()` on each pointer exactly once somewhere inside that loop. But only if `d!=0`

# Answer
> 1 votes
# Uiua SBCS, 6 bytes

```
∧(⍉⍥⇌)

```

Try it!

Takes the array and a mask of which dimensions to reverse like `[1 0 1]`.

```
∧(⍉⍥⇌)
∧(   )  # fold over mask and array, using array as accumulator
   ⍥⇌   # reverse the array either 0 or 1 times
  ⍉     # transpose

```

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


title: Horsey sightseeing

text:
# Question
Title: Horsey sightseeing
A knight's tour is a sequence of moves of a knight on a chessboard such that the knight visits every square only once. For those who are not aware of how knights in chess work, knights are capable of moving in an L shape (see *fig. 1*). (Or a ߆ shape, or even a \ shape depending on who you ask.) Essentially, in one move, a knight moves two squares on one axis and one square on the other.

Tours generally apply to a regular chessboard but it can be calculated for other sizes. For example, see *fig. 2* for a possible knight's tour on a chessboard of size \\$5\\$. The knight starts in the top-left square, denoted by a \\$1\\$ and works its way through every square until it finally ends in the \\$25th\\$ square it visits, in the very center. A tour's validity is not necessarily affected by the squares it starts and ends in.

|  |  |
| --- | --- |
| *fig. 1* | *fig. 2* |

For grid size \\$n = 5\\$, that is only one of \\$1728\\$ options. A regular chessboard, where \\$n = 8\\$, has slightly more possible tours, with a total of \\$19,591,828,170,979,904\\$. This is OEIS A165134.

## Challenge

Write a **program/function** that takes a **grid size** \\$n\\$ and outputs either a possible valid **board of integers** or **list of coordinates**.

### Specifications

* Standard I/O rules **apply**.
* Standard loopholes are **forbidden**.
* \\$n \> 4\\$, as there are no valid tours for those grid sizes.
* Your solution **can either be 0-indexed or 1-indexed** for either step count and coordinates but please specify the format and indexing.
* This challenge is not about finding the shortest approach in all languages, rather, it is about finding the **shortest approach in each language**.
* Your code will be **scored in bytes**, unless otherwise specified.
* Built-in functions that compute knight's tours (guessing it's just Mathematica here) are **allowed** but including a solution that doesn't rely on a built-in is encouraged.
* Explanations, even for "practical" languages, are **encouraged**.

### Potential outputs

Considering how many possible tours there are, test cases would serve no real purpose. Instead, a couple possible knight's tours have been provided below for the sake of understanding the format options. Note that the chosen delimiters for the following are **not mandatory**.

| \\$n\\$ | Board | List |
| --- | --- | --- |
| \\$5\\$ | ```  1 24 13 18  7 <br>14 19  8 23 12<br> 9  2 25  6 17<br>20 15  4 11 22<br> 3 10 21 16  5 ``` | `0,0 1,2 0,4 2,3 4,4 3,2 4,0 2,1 0,2 1,4 3,3 4,1 2,0 0,1 1,3 3,4 4,2 3,0 1,1 0,3 2,4 4,3 3,1 1,0 2,2` |
| \\$8\\$ | ```  1 50 15 32 55 28 13 30<br>16 33 54 57 14 31 64 27<br>51  2 49 44 61 56 29 12<br>34 17 60 53 58 47 26 63<br> 3 52 45 48 43 62 11 40<br>18 35 20 59 46 41  8 25<br>21  4 37 42 23  6 39 10<br>36 19 22  5 38  9 24  7 ``` | `0,0 2,1 4,0 6,1 7,3 6,5 7,7 5,6 7,5 6,7 4,6 2,7 0,6 1,4 0,2 1,0 3,1 5,0 7,1 5,2 6,0 7,2 6,4 7,6 5,7 3,6 1,7 0,5 2,6 0,7 1,5 0,3 1,1 3,0 5,1 7,0 6,2 7,4 6,6 4,7 5,5 6,3 4,4 2,3 4,2 5,4 3,5 4,3 2,2 0,1 2,0 4,1 3,3 1,2 0,4 2,5 1,3 3,4 5,3 3,2 2,4 4,5 3,7 1,6` |

### Validators

**For output as a board** using spaces between columns and newlines between rows. **For output as a coordinate list** using commas between axes and spaces between coordinates.

This challenge was sandboxed. For over five years.

# Answer
# Python 3.8 (pre-release), 170 bytes

```
def f(n,P=[(0,0)]):
 for j in range(8):
  x,y=P[0];q=x+~(j%2)*~-(j&2),y-(2-j%2)*~-(j//2&2)
  if(q in P)-(n>q[0]>-1<q[1]<n)<0and len(R:=f(n,[q]+P))==n*n:return R
 return P

```

Try it online!

Some people were really dedicated into golfing this, thanks to everyone!

* *-4 bytes* thank to @movatica by using a `-` instead of a `*` when validating a position, and replacing `all` with a chained comparison between tuple elements
* *-3 bytes* thank to @Arnauld by removing intermediate variables `a` and `b` when creating `q`
* *-3 bytes* thank to @Mukundan314 by moving `x` and `y` to inside the loop and building the tour in reverse

# Python 3.8 (pre-release), ~~205~~ ~~192~~ ~~188~~ ~~186~~ 180 bytes

Original version, with not-so-clever golfings :)

```
def f(n,P=[(0,0)]):
 x,y=P[-1]
 for j in range(8):
  a=j%2+1;b=3-a;q=x+a-a*(j&2),y+b-b*(j&4)//2
  if(q not in P)*all(n>v>=0for v in q)and len(R:=f(n,P+[q]))==n*n:return R
 return P

```

Try it online!

* *-4 bytes* by calculating `a` using addition instead of indexing, and inlining `b`
* *-2 bytes* thank to @xnor's nice remark about replacing `&` with `%` when calculating `a`
* *-4 bytes* thank to @Mukundan314's improvements regarding returning directly instead of breaking, using list concatenation instead of unpacking, and removing `()` when creating `q`
* *-15 bytes* thank to @movatica's amazing improvements regarding bitwise operations, reordering some declarations, and removing `V` completely (using only arithmetic)

---

*Extremely* inefficient, but it works in theory. It can run \\$n = 5\\$ on TIO, but it takes ~8 minutes to run \\$n = 6\\$ on my local interpreter.

A function that accepts \\$n\\$ as first argument and returns a list of sized-2 tuples.

**How it works?**

The algorithm always start on the top-left corner and uses `P` as a `list[tuple[int, int]]`.

A horse can have 8 movements, so they can be encoded in an integer (for example, `0b101`):

1. if the first bit is set, then the horse moves 1 piece horizontally and 2 pieces vertically. Otherwise, it moves 2 pieces horizontally and 1 piece vertically
2. if the second bit is set, then the horse moves up. Otherwise, it moves down
3. if the third bit is set, then the horse moves left. Otherwise, it moves right

Therefore, for each movement a horse can make (`for j in range(8):`), decode `a` and `b` as the movement offsets on the board (by reading the first bit of `j`) and calculate `q`, a sized-2 tuple containing the new position of the horse on the board (decoding the movement directions by reading the second and third bits of `j`).

It then checks if the new calculated position is within the board (`all(0<=v<n for v in q)`) and if that position is not already occupied (`q not in P`). If it's valid, then it calls `f` again with that position stored in `P`. If, in any step of the recursion, `P` contains exactly \\$n^2\\$ elements (i.e. all positions in the board are occupied), then return it.

It outputs

* `[(0, 0), (1, 2), (2, 4), (4, 3), (3, 1), (1, 0), (2, 2), (0, 3), (1, 1), (3, 0), (4, 2), (3, 4), (1, 3), (0, 1), (2, 0), (4, 1), (3, 3), (1, 4), (0, 2), (2, 1), (4, 0), (3, 2), (4, 4), (2, 3), (0, 4)]` for \\$n=5\\$
* `[(0, 0), (2, 1), (4, 0), (3, 2), (1, 1), (3, 0), (5, 1), (4, 3), (5, 5), (3, 4), (1, 3), (0, 1), (2, 0), (1, 2), (3, 1), (5, 0), (4, 2), (5, 4), (3, 5), (1, 4), (0, 2), (1, 0), (2, 2), (4, 1), (5, 3), (4, 5), (3, 3), (5, 2), (4, 4), (2, 5), (0, 4), (2, 3), (1, 5), (0, 3), (2, 4), (0, 5)]` for \\$n=6\\$
> 6 votes

# Answer
# Vyxal 3, ~~14~~ ~~13~~ 12 bytes

-1 byte thanks to Mukundan314

```
ẊṖΩᵃȧᵛΠ2p≈}h

```

(Don’t) Try it Online! (link is to literate version) because it's way too slow.

This brute-forces solutions, so it’s horribly inefficient. It times out on the online interpreter very quickly, and hits Scala's garbage collection limit with the native build after a few minutes.

The last 2 bytes can be removed if outputting all possible solutions instead of just the first one is OK.

### Explanation

```
ẊṖΩᵃȧᵛΠ2p≈}h
Ẋ             ##  Treating the input as the range [1, it], take the
              ##    cartesian product with itself. This gives the
              ##    list of coordinates of the n*n chessboard.
 Ṗ            ##  Take the permutations (all orders of the elements)
              ##    of the board. This is the slow part.
  Ω           ##  Filter the permutations, only keeping those for
              ##    which the following function returns true:
   ᵃ          ##      Apply the following to each pair (including
              ##        those which overlap):
    ȧ         ##          Absolute difference.
     ᵛ        ##      Apply to each resulting pair:
      Π       ##          Take the product of the list. This will
              ##            be 2 if and only if the two pieces were
              ##            a knight's move away.
       2p     ##      Prepend a 2 to this list.
         ≈    ##      Are all elements of the list equal?
          }   ##  Close the filter function.
           h  ##  Return the first successful solution.

```

Created with the help of Luminespire.

Independently derived from, but using a very similar method to, @Mukundan314’s solution.
> 5 votes

# Answer
# Vyxal 3, ~~19~~ 14 bytes

-4 bytes thanks to @noodleman

```
ẊṖΩᵃȧᵛSu2ɾw₌}h

```

This program involves exhaustively examining every coordinate list, making it impractical to run within a reasonable timeframe, even for the smallest input value of \\$n = 5\\$.

Should output a 1-indexed coordinate list.

Try it Online!

### Explanation

```
ẊṖΩᵃȧᵛSu2ɾw₌}h
                # implicitly push input onto stack
Ẋ               # generate all coordinates (cartesian product of [1;n] with [1;n])
 Ṗ              # all permutations of the coordinates
  ΩᵃȧᵛSu2ɾw₌}   # filter for knight tours:
   ᵃȧ           #   absolute difference between adjacent coordinates
     ᵛS         #   sort each coordinate
       u        #   uniquify all coordinates
         ɾw₌    #   equals [[1, 2]]
             h  # first element of filtered permutations

```

Created with the help of Luminespire.

---

Note: This is one of my first Vyxal programs, and given that it won't run in a reasonable amount of time for even the smallest input, it is very possible I have made a mistake in the code
> 4 votes

# Answer
# JavaScript (ES6), 141 bytes

Returns a list of 0-indexed coordinates as a single string.

```
f=(n,x=0,y=0,o="",k=n*n)=>x/n|y/n||(o+=p=` ${[x,y]} `).match(p+".|-")?0:--k?[...s="01344310"].some((d,i)=>f(n,d-2+x,s[i+6&7]-2+y,o,k))&&O:O=o

```

Try it online!

### Commented

```
f = (                   // f is a recursive function taking:
  n,                    //   n = input
  x = 0, y = 0,         //   (x, y) = current position
  o = "",               //   o = output string
  k = n * n             //   k = move counter
) =>                    //
x / n |                 // if x >= n
y / n ||                // or y >= n
( o += p =              // or the updated output obtained by adding
  ` ${[x,y]} `          // the new position p = x,y surrounded by spaces
).match(                // contains:
  p + ".|-"             //   either p followed by any character
                        //   or the minus sign
) ?                     // then:
  0                     //   abort
:                       // else:
  --k ?                 //   decrement k; if it's not 0:
    [...s = "01344310"] //     s = offset sequence
    .some((d, i) =>     //     for each value d at index i in s:
      f(                //       do a recursive call:
        n,              //         pass n unchanged
        d - 2 + x,      //         update x
        s[i + 6 & 7] -  //         use the shifted sequence "10013443"
        2 + y,          //         to update y
        o,              //         pass the new output
        k               //         pass the updated counter
      )                 //       end of recursive call
    )                   //     end of some()
    && O                //     if truthy, return O
  :                     //   else:
    O = o               //     success: save o in O

```

---

# JavaScript (ES8), 151 bytes (faster)

Returns a matrix with 0-based indexing.

```
n=>(m=[...s="".padEnd(n)].map(_=>[...s]),g=(x,y,k)=>!(m[y][x]=--k)|m.some((r,Y)=>r.some((v,X)=>v|(X-x)**2+(Y-y)**2-5?0:g(X,Y,k)))?m:m[y][x]=0)(0,0,n*n)

```

Try it online!
> 3 votes

# Answer
# Charcoal, 77 bytes

```
ＮθＦθＦθ⊞υ⟦⁰ικ⟧Ｆυ⊞ιΦυ⁼⁵ΣＸＥι∧ν⁻§κνμ²≔⟦§υ⁴⟧υ≔⟦⟧ηＷ⌊υ«⊞ηι≔⁻⊟ιηυＦυ§≔κ⁰Ｌ⁻§κ³η»Ｅη⭆¹✂ι¹

```

Try it online! Link is to verbose version of code. Outputs a list of `0`-indexed coordinates. Explanation: Uses Warnsdorff's rule, but always starting from `[0, 4]`, because the rule won't work starting at the corner of the size `11` board.

```
ＮθＦθＦθ⊞υ⟦⁰ικ⟧

```

Input `n` and create a "board" of  squares, with each square initially represented by its unvisited neighbour count and co-ordinates.

```
Ｆυ⊞ιΦυ⁼⁵ΣＸＥι∧ν⁻§κνμ²

```

Loop over the board, calculating the list of neighbours of each square.

```
≔⟦§υ⁴⟧υ

```

Start with `[0, 4]` as a potential next square, to work around the case of the size `11` board. (Otherwise this line of code would have been unnecessary.)

```
≔⟦⟧η

```

Start with no squares visited yet.

```
Ｗ⌊υ«

```

Until there are no squares left to visit, get the one with the fewest unvisited neighbours.

```
⊞ηι

```

Save this to the tour of visited squares.

```
≔⁻⊟ιηυ

```

Get the list of unvisited neighbours of the current square.

```
Ｆυ§≔κ⁰Ｌ⁻§κ³η

```

Update the number of unvisited neighbours for each unvisited neighbour.

```
»Ｅη⭆¹✂ι¹

```

Pretty-print the final tour.
> 3 votes

# Answer
# Haskell + hgl, 37 bytes

```
g1(mF(fe[(1,2),(2,1)])<δ')<pm<j2q<e1

```

This is *horrendously* slow. It's time complexity is \\$\mathcal O(4^n! 4^n)\\$ (careful analysis might show that this bound could be lowered) on the number of bits in input. I've only been able to get it to halt for cases where \\$n \< 4\\$, so I've never observed it produce a correct output.

## Explanation

* `e1`: enumerate from `1` to the input
* `j2q`: get the cartesian product of this with itself to get the coordinates of the board
* `pm`: get all permutations of the input
* `g1`: get the first permutation satisfying a predicate
* `δ'`: get the absolute difference between consecutive elements
* `mF$fe[(1,2),(2,1)]`: check if they are `(1,2)` or `(2,1)`.

In summary this searches through all the permutations for one that consists solely of knights moves.

### Reflection

At some point in the future there will be some graph utility functions, which would be able to handle this sort of thing not only shorter, but faster. But that's a bit of a long term requirement.

Here are some short term possibilities:

* There should be something along the lines of "apply this function or not", currently it seems the way to do this is `ap[f,id]` which is pretty long.
* There should be a function to determine if all elements of one list belong to another.
> 2 votes

# Answer
# Python 3.8 (pre-release), 123 bytes

```
f=lambda n,x=0,*p:x%(y:=n+2)<n>x/y>=(x in p)<1and max((f(n,x+b,x,*p)for a in(n+4,n,n+n+5,n+n+3)for b in(a,-a)),key=len)or p

```

Try it online!

Brute force approach, an adaptation of my answer to Holey Knight's Tour.

Essentially, the board is a 1D-representation of a 2D padded grid. The horsey will hop recursively over the board while avoiding the padding and keeping track of the current (`x`) and previously visited (`p`) squares.

Coordinates are 0-indexed and 1-dimensional from left to right and top to bottom, with a gap of 2 indices at the edges. That is, for a 5x5 grid:

```
 0  1  2  3  4
 7  8  9 10 11
14 15 16 17 18
21 22 23 24 25
28 29 30 31 32

```
> 1 votes

---
Tags: code-golf, number, chess, open-ended-function
---


title: Follow the path

text:
# Question
Title: Follow the path
The challenge is to follow (draw) the path:

* `^n` \- up by n lines
* `vn` \- down by n lines
* `>n` \- right by n character positions
* `<n` \- left by n characters positions

---

* `n` is an integer, greater than zero (i.e. you can't receive a command like `>-2`).
* There're no separators between the commands, the well-formed input looks like this: `>5v8<10^3`, no other form of input allowed.
* The number of commands is unlimited.
* No more characters are supposed to creep into the input.

Examples.

1. Input is an empty string, output:

```
*

```
2. Input is either `>3` or `<3`: note that this doesn't make any difference to the output:

```
****

```
3. Similar for `^3` and `v3`:

```
*
*
*
*

```
4. Input: `>1v2`, output:

```
**
 *
 *

```
5. Input: `^4>3v2<1`, output:

```
****
*  *
* **
*
*

```
6. If you go back and use the same path, don't draw anything new. E.g. `>5<5`

```
******

```
7. ...though you don't draw anything new, you obviously change the position. Hence, if your input looks like this: `>4<2v3`, the output is:

```
*****
  *
  *
  *

```
8. This is a more complex example: 1) the path can cross itself 2) note that the last three steps of the last command shift the whole path to the right. Input: `v6>4^3<7`, output:

```
   *
   *
   *
********
   *   *
   *   *
   *****

```
9. Input:

```
^2v2>3<3v3>4^5v5>3^5>4v2<4v3>4^3v3>3^5>4v2<4v3>7^5>4v2<4v3>9^3<2^2v2>4^2v2<2v3>8^5>2v4>2^4v5<3>6^5>5<5v2>5<5v2>5<4v1>8^3<1^2v2>1v2>2^3v3>2^2>1^2v2<1v3<3>11^3<2^2v2>4^2v2<2v3>5^5>5<5v2>5<5v2>5<4v1>7^5>4v2<4v3>4^3v3>3^5>4v2<3v1<1v2>3^1>1v1

```

Output:

```
*   *  *****  *****  *****  *   *     *** *  ******  *     *    *   *  ******  *****  *****
*   *  *   *  *   *  *   *  *   *     * * *  *       *  *  *    *   *  *       *   *  *   *
*****  *****  *****  *****  *****     * * *  ******  ** * **    *****  ******  *****  *****
*   *  *   *  *      *        *       * * *  *        * * *       *    *       *   *  **
*   *  *   *  *      *        *       * ***  ******   *****       *    ******  *   *  *  **
*******************************************************************************************

```

# Answer
# MATL, 71 bytes

```
1thj'.\d+'XX"@Z)XK6L)U:"K1)XK118=K94=-K62=K60=-hv]]YstY)X<1--lqg10*32+c

```

Uses current release (6.0.0) of the language/compiler. Works in Matlab and in Octave.

*EDIT (June 21, 2016): due to changes in the language, the code requires a few modifications to run in current release (16.0.0). You can try it online including the needed modifications.*

### Examples

```
>> matl
 > 1thj'.\d+'XX"@Z)XK6L)U:"K1)XK118=K94=-K62=K60=-hv]]YstY)X<1--lqg10*32+c
 >
> ^4>3v2<1
    ****
    *  *
    * **
    *
    *

>> matl
 > 1thj'.\d+'XX"@Z)XK6L)U:"K1)XK118=K94=-K62=K60=-hv]]YstY)X<1--lqg10*32+c
 >
> ^2v2>3<3v3>4^5v5>3^5>4v2<4v3>4^3v3>3^5>4v2<4v3>7^5>4v2<4v3>9^3<2^2v2>4^2v2<2v3>8^5>2v4>2^4v5<3>6^5>5<5v2>5<5v2>5<4v1>8^3<1^2v2>1v2>2^3v3>2^2>1^2v2<1v3<3>11^3<2^2v2>4^2v2<2v3>5^5>5<5v2>5<5v2>5<4v1>7^5>4v2<4v3>4^3v3>3^5>4v2<3v1<1v2>3^1>1v1
  *   *  *****  *****  *****  *   *     *** *  ******  *     *    *   *  ******  *****  *****
  *   *  *   *  *   *  *   *  *   *     * * *  *       *  *  *    *   *  *       *   *  *   *
  *****  *****  *****  *****  *****     * * *  ******  ** * **    *****  ******  *****  *****
  *   *  *   *  *      *        *       * * *  *        * * *       *    *       *   *  **
  *   *  *   *  *      *        *       * ***  ******   *****       *    ******  *   *  *  **
  *******************************************************************************************

```

### Explanation

The program has four main steps:

1. Read input string and split into its components.
2. Build a 2-column matrix where each row describes a unit displacement in the appropriate direction. For example, `[0 -1]` indicates one step to the left. The first row is the origin of the path, `[1 1]`
3. Compute the cumulative sum of that matrix along the first dimension . Now each row describes the coordinates of a `*`. Normalize to minumum value `1`
4. Create a new matrix that contains `1` at the coordinates indicated by the matrix from step 3, and `0` otherwise. This is then transformed into a char matrix.

Code:

```
1th                         % row vector [1 1]. Initiallize matrix of step 2
j                           % (step 1) read input string
'.\d+'XX                    % split into components. Creates cell array of substrings
"                           % (step 2) for each component
   @Z)XK                    % unbox to obtain substring and copy
   6L)U:                    % obtain number and build vector of that size
   "                        % repeat as many times as that number
      K1)                   % paste substring. Get first character: '^', 'v', '>', '<'
      XK118=K94=-           % vertical component of unit displacement: -1, 0 or 1
      K62=K60=-             % horizontal component of unit displacement: -1, 0 or 1
      h                     % concatenate horizontally
      v                     % append vertically to existing matrix
   ]                        % end
]                           % end
Ys                          % (step 3) cumulative sum along first dimension
tY)X<1--                    % normalize to minimum value 1
lqg                         % (step 4) build matrix with 0/1
10*32+c                     % replace 0 by space and 1 by asterisk

```
> 2 votes

# Answer
# JavaScript (ES6), 204 ~~211 210~~

**Edit 1** Bug fix - output '\*' for void input
**Edit 2** Simpler decoding of direction to x and y diff

Here is my answer to The treasure map, revised to fulfill the specs.

```
F=m=>(m.replace(/\D(\d+)/g,(d,z)=>{for(;z--;r=[...r],r[x]=m,p[y]=r.join``)for(d<'>'?--x:d<'^'?++x:d<'v'?--y:++y,p=~x?~y?p:[y=0,...p]:p.map(r=>' '+r,x=0),r=p[y]||'';!r[x];)r+=' '},x=y=0,p=[m='*']),p.join`
`)

```

**Less golfed** and explained more or less

```
f=m=>(
  x=y=0, // starting position
  p=['*'], // output string array (initialized with minimum output)
  m.replace( /\D(\d+)/g,
  (d,z) => // execute the following for each group direction/length. Length in z, direction in d[0]
  {
    while( z--)  // repeat for the len
    {
      // check d to change values of x and y
      // all the comparison are with > and <, not equal
      // so that they work with the whole d, not just d[0]
      d<'>'?--x:d<'^'?++x:d<'v'?--y:++y,
      // now if x or y are < 0 then p must be adjusted
      p = ~x
        ? ~y
          ? p // both x and y are >= 0, p is not changed
          : [y = 0, ...p] // y < 0, shift p by on adding a 0 element and set y to 0
        : p.map(r=> ' ' + r, x = 0); // x < 0, add a space to the left for each row in p and set x to 0
      r = p[y] || ''; // get current row in r
      for( ; !r[x]; ) // if the current row is empty or too short
        r += ' '; // ... add spaces up to position x
      // set character in x position
      r = [...r], // the shorter way is converting to array ...
      r[x] = '*', // setting the element
      p[y] = r.join`` // and the back to string using join
    }
  }),
  p.join`\n` // return output array as a newline separated string
}

```

**Test**

```
F=m=>(m.replace(/\D(\d+)/g,(d,z)=>{for(;z--;r=[...r],r[x]='*',p[y]=r.join``)for(d<'>'?--x:d<'^'?++x:d<'v'?--y:++y,p=~x?~y?p:[y=0,...p]:p.map(r=>' '+r,x=0),r=p[y]||'';!r[x];)r+=' '},x=y=0,p=['*']),p.join`
`)

// TEST
console.log = x => O.textContent += x + '\n';

console.log(F('')+'\n')

console.log(F('v6>4^3<7')+'\n')

console.log(F('^2v2>3<3v3>4^5v5>3^5>4v2<4v3>4^3v3>3^5>4v2<4v3>7^5>4v2<4v3>9^3<2^2v2>4^2v2<2v3>8^5>2v4>2^4v5<3>6^5>5<5v2>5<5v2>5<4v1>8^3<1^2v2>1v2>2^3v3>2^2>1^2v2<1v3<3>11^3<2^2v2>4^2v2<2v3>5^5>5<5v2>5<5v2>5<4v1>7^5>4v2<4v3>4^3v3>3^5>4v2<3v1<1v2>3^1>1v1'))
```

```
<pre id=O></pre>
```
> 8 votes

# Answer
# Perl, 174 bytes

```
@M=(['*']);pop=~s/(.)(\d+)/($z=ord$1)&64?($y+=$z&8?-1:1)<0&&unshift@M,[$y++]:($x+=($z&2)-1)<0?@M=map{[$x=0,@$_]}@M:0,$M[$y][$x]='*'for1..$2/gre;print map{map{$_||$"}@$_,$/}@M

```

Expects input as commandline argument. *Be sure to quote the argument!*
Example: `perl 177.pl "<1^2>3v4<5^6>7v8<9^10>11"`

**Somewhat readable:**

```
@M=(['*']);                                 # output origin/starting position

pop=~                                       # apply regex to cmdline arg
s!(.)(\d+)!                                 # match $1=direction, $2=count

    ($z=ord$1)                              # get ASCII code for char
    &64                                     # 'v^' have this bit set, '<>' don't

        ?                                   # adjust y:
            ($y += $z&8 ? -1 : 1)           # '^' has bit set, 'v' doesn't
            < 0 &&                          # negative y?
            unshift @M, [$y++]              # prepend row; abuse [] for $y++ saving 3 bytes

        :                                   # adjust x:
            ($x+= ($z&2) -1 )               # '>' has bit set: 2-1=1, '<' hasn't: 0-1=-1
            < 0 ?                           # negative x?
                @M = map{ [$x=0,@$_] } @M   # prepend column, reset x
                :0                          # '?:0' shorter than '&&()'
        ,                                   # oh, and also:
        $M[$y][$x]='*'                      # output current position.

    for 1..$2                               # iterate count
!grex;

print map{ map{$_||$"} @$_, $/ } @M         # iterate rows/cols, print '*' or space

```
> 1 votes

# Answer
# Vyxal `?`, 197 bitsv2, 24.625 bytes

```
kdFf`^>v<`kd√Ŀ?f⌊0€Ḣṅ⌊›×?[ø^

```

Try it Online!

Bitstring:

```
10000000000001110010111101000000110111011010110000000000100001111110101111001000101011110011001101001000011000101100010101000011110111000110001011100110000011001111111111010010100100111110001000000

```

```
kdFf`^>v<`kd√Ŀ?f⌊0€Ḣṅ⌊›×?[ø^
kdFf                          # remove all digits from input and flatten
                              # to give list of directions
    `^>v<`                    # arrows in canvas directions
          kd√                 # even digits (02468)
             Ŀ                # transliterate directions to corresponding canvas directional number (ignores the 8) [1]
              ?f⌊             # flatten the input and get the numbers
                 0€Ḣ          # split on 0 and remove the first element (always an empty list due to input format)
                    ṅ⌊        # join sublists by nothing and convert to number(deals with multi digit numbers)
                      ›       # increment (no idea why i need this but the entire program breaks without it) [2]
                       ×      # literal "*"
                        ?[    # if the input is true
                          ø^  # draw on the canvas using directions defined in [1] lengths defined in [2] and printing the text as "*"
# otherwise, implicitly print "*"

```

Created with the help of Luminespire.
> 1 votes

# Answer
# 05AB1E, 27 bytes

```
">^v<"žCÍS1ú‡#¦εć)>}ø`'*s<Λ

```

Try it online! (2020 is close enough so why not)
> 0 votes

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


# Question
Title: Print Goodbye World instead of Hello World
Make a cat program, with a catch. The program must refuse under all circumstances to output "Hello World", instead outputting "Goodbye World", with matching spacing (but matching casing is not required).

"Hello World" must never appear as a substring of the output, regardless of casing, not even if the two words are (or are not) separated by newlines, spaces, tabs, or even multiple executions of the program.

# Rules

These are all forbidden:

```
Hello World

HelloWorld

Hello   world

HELLOWORLD

I want to wish you hello world

HeLlOwOrLd and all who inhabit it

Hello
world

I said hello
world news

```

Instead, the output should read:

```
Goodbye World

GoodbyeWorld

Goodbye   world

GOODBYEWORLD

I want to wish you goodbye world

Goodbyeworld and all who inhabit it

Goodbye
world

I said goodbye
world news

```

However, other characters that separate hello and world will cause the string to not be matched. These should be repeated verbatim:

```
Hello, world
hello happy world
HELLO2THEWORLD

```

If the program is run twice in sequence (for example, in a batch script), first against the string "hello" and then against the string "world", the output should be:

```
goodbye
world

```

But if it is run against "hello" and then "friends", the output should be:

```
hello
friends

```

You can choose whether to abstain from printing hello until the next run (this means if that command never comes, it will never print, which is acceptable), or to change it retroactively, if possible. The program does not have to take into account the possibility of other programs being run between runs.

# Examples

Here's a quick .sh I put together to test it (I named my binary goodbye):

```
echo hello world | ./goodbye
echo hello friends | ./goodbye
echo HeLlO wOrLd | ./goodbye
(echo hello; echo world) | ./goodbye
(echo hello; echo friends) | ./goodbye
echo helloworld | ./goodbye
echo "hello     world" | ./goodbye
echo I say hello | ./goodbye
echo world | ./goodbye
echo hello | ./goodbye
echo friends of mine | ./goodbye
echo hello happy world | ./goodbye
echo hello2theWORLD | ./goodbye

```

This is code golf, so lowest byte count (per language) wins!

# Answer
> 1 votes
It seems there's some confusion over whether this is possible, so here's an example answer in...

# FLEX/C (557 bytes)

```
%option noyywrap
%{#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#define p(X) printf(X)
#define s(X) strncat(w,X,99)
#define g(X) if(l==1){X}
#define d w[0]='\0';p(t);l=0;
#define t yytext
int l = 0;char *w;
%}
%%
[hH][eE][lL][lL][oO] {l=1;}
[wW][oO][rR][lL][dD] {g(p("goodbye");)p(w);d}
[\r\n\t ] {g(s(t);)else{p(t);}}
. {g(p("hello");)p(w);d}
%%
main(int c,char **a){w=malloc(99);w[0]='\0';if(access("f",F_OK)==0){l=1;remove("f");s("\n");}yylex();if(l==1){FILE* f=fopen("f","w");fclose(f);}else{p("\n");}}

```

Here's the ungolfed version:

```
%option noyywrap

%{
    #include <stdio.h>
    #include <string.h>
    #include <unistd.h>
    #include <fcntl.h>

    #define FLAG_FILE "goodbye.flg"

    int last = 0;
    char *whitespace;
%}

%%

[hH][eE][lL][lL][oO]    { last = 1; }
[wW][oO][rR][lL][dD]    { if (last == 1) { printf("goodbye"); } printf(whitespace); whitespace[0] = '\0'; printf(yytext); last = 0; }
[\r\n\t ]               { if (last == 1) { strncat(whitespace, yytext, 100); } else { printf(yytext); } }
.                       { if (last == 1) { printf("hello"); } printf(whitespace); whitespace[0] = '\0'; printf(yytext); last = 0; }

%%

main(int argc, char **argv)
{
    whitespace = malloc(1000);
    whitespace[0] = '\0';
    if (access(FLAG_FILE, F_OK) == 0)
    {
        last = 1;
        remove(FLAG_FILE);
        strncat(whitespace, "\n", 100);
    }
    yylex();
    if (last == 1)
    {
        FILE* file_ptr = fopen(FLAG_FILE, "w");
        fclose(file_ptr);
    }
    else
    {
        printf("\n");
    }
}

```

It chooses the abstain option, which as noted in the question, allows it to abstain from printing the last word if the last word in the input is "hello", and then decide on the next run whether to print "hello" or "goodbye" based on whether the following word is "world."

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