title: Shut down the computer!

text:
# Question
Title: Shut down the computer!
## Challenge:

In the programming language of your choice, shut down the machine that your code was executed on.

# Rules

* No shutting down by resource exhaustion (e.g.: forkbomb to force shutdown)
* You are allowed to write code that only works in a specific environment/OS, if you wish.
* Standard loopholes are forbidden

---

This is , thus the lowest amount of bytes wins!

# Answer
> 93 votes
# Assembly (x86/x64, Linux, as), ~~22~~ ~~21~~ 19 bytes

```
mov  $0x58,       %al  # 2 bytes: b0 58
mov  $0xfee1dead, %ebx # 5 bytes: bb ad de e1 fe
mov  $0x28121969, %ecx # 5 bytes: b9 69 19 12 28
mov  $0x4321fedc, %edx # 5 bytes: ba dc fe 21 43
int  $0x80             # 2 bytes: cd 80

```

Must be run as root.

**This is equivalent to pressing the power button and not a safe way to power off your PC.** Make sure you close all open applications and execute `sync` to flush all file system buffers before executing this program, to at least minimize the risk of file corruption.

### Test run

```
$ as -o poweroff.o poweroff.s
$ ld -o poweroff   poweroff.o
ld: warning: cannot find entry symbol _start; defaulting to 0000000000400078
$ sudo sh -c 'sync && ./poweroff'
root's password:

```

Followed by darkness.

### How it works

`int $0x80` invokes a software interrupt. It works on both x86 and x64, but has been deprecated for over a decade now and should not be used in production code. x64 code should use `syscall` instead. x86 should use `sysenter`, but it is too cumbersome for code golf.

The resulting action from the syscall depends on registers EAX - EDX, ESI, and EDI. The Linux Syscall Reference shows all syscalls that are available via `int $0x80`.

When EAX holds **0x58 (88)**, *reboot* is called, which can also be used to power off, put to sleep, or hibernate the computer, as well as switching kernels and disabling or enabling the **Ctrl - Alt - Del** key combo.

At the start of the program – and by compiling with `as` or `gcc -nostdlib`, we can make sure that we're actually at the start of the program – most registers are set to **0**. This includes EAX, so we can use `mov $0x58, %al` to set the lower 8 bits of EAX to **0x58**, thus setting EAX itself to **0x58**. This saves two bytes over manually zeroing the register with `xor %eax, %eax` and one more over the straighforward `mov $0x58, %eax` which encodes **0x58** in 32 bits.

The first two arguments to *reboot* are magic numbers, presumably to prevent accidental reboots, and are read from registers EBX and ECX. Unless these numbers are equal to certain constants, *reboot* refuses to perform any action.

* The first magic number must equal **0xfee1dead** (*feel dead*), probably referring to the power off / death of the PC.
* The second magic number can be equal to four different constants, although the latter three did not work in ancient versions of Linux. All of them seem to refer to the subsequent power on / birth of the PC.

+ **0x28121969** represents Linus Torvalds's birthday (December 28, 1969).
    + **0x05121996** represents Patricia Torvalds's birthday (December 5, 1996).
    + **0x16041998** represents Daniela Torvalds's birthday (April 16, 1998).
    + **0x20112000** represents Celeste Torvalds's birthday (November 20, 2000).

Patricia, Daniela, and Celeste Torvalds are Linus Torvalds's three daughters.
* The EDX register selects the type of "reboot" we want. **0x4321fedc** is *RB\_POWER\_OFF*, shutting the PC down and powering it off.
* Finally, the value of the ESI register is ignored for *RB\_POWER\_OFF*; the value of the EDI register is ignored entirely by *reboot*.

### Alternate version, x64-only, 19 bytes

On x64, we can use a proper syscall for the same byte count.

```
mov     $0xa9,       %al  # 2 bytes: b0 a9
mov     $0xfee1dead, %edi # 5 bytes: bf ad de e1 fe
mov     $0x28121969, %esi # 5 bytes: be 69 19 12 28
mov     $0x4321fedc, %edx # 5 bytes: ba dc fe 21 43
syscall                   # 2 bytes: 0f 05

```

The only differences lie in the instruction (`syscall` vs `int $0x80`), the value of *\__NR\_REBOOT* (**0xa9** vs **0x58**), and the involved registers.

# Answer
> 50 votes
# PowerShell, 13 bytes

```
Stop-Computer

```

Pretty self-explanatory? Doesn't work on PowerShell core, so it won't work on PowerShell for Linux/MacOS (already tried it on TIO :-D ).

## Bonus Garbage Submission, 12 bytes

```
gcm s*r|iex

```

In my testing, this works on Windows 2003 with PowerShell 2.0. It won't work on most of the newer versions, and it may not work depending on which modules are installed. It's quite terrible!

This searches the list of commands for any with the pattern `s*r` and then runs all of them! To be clear, **this is dangerous, don't do this!**

The trick of course, is getting a list of commands that don't have any mandatory parameters, otherwise PowerShell will prompt for a value.

On my 2003 machine, the 3 commands it returns are:

> ```
> CommandType     Name                                                Definition
> -----------     ----                                                ----------
> Application     scrnsave.scr                                        C:\WINDOWS\system32\scrnsave.scr
> Application     ssmarque.scr                                        C:\WINDOWS\system32\ssmarque.scr
> Cmdlet          Stop-Computer                                       Stop-Computer [[-ComputerName] <String[]>] [[-Cr...
>
> ```

Yes, it does launch the marquee screensaver, but no, it does not wait for it to complete before launching `Stop-Computer`.

This approach can work on newer machines, again depending on which modules are installed, but the best I could do on Windows 2012 and 2016 was **14 bytes**:

```
gcm sto*er|iex

```

(and yeah, sure, the winbatch submission will work in PowerShell and it's shorter, but.. that's no fun)

# Answer
> 40 votes
## Batch, 10 bytes

On windows, this would suffice

```
shutdown/s

```

This will set up a shutdown in one minute.

Alternatively, as @flashbang points out:

```
shutdown/p

```

This shuts down the computer immediately.

# Answer
> 35 votes
## x86 machine code, Lenovo Z510, DOS COM or Bootloader, 7 bytes

```
BITS 16

mov ax, (1 << 13) | (7 << 10)
mov dx, 1804h
out dx, ax

```

Assembled into `B8 00 3C BA 04 18 EF`

I'm exploiting "*You are allowed to write code that only works in a specific environment/OS, if you wish*" to the ultimate level: this will only work on Lenovo Z5101.

This writes `SLP_TYPa << 10 | SLP_EN` to the `PM1a_CNT` ACPI register, I dumped this values from the ACPI tables months ago for an answer about shutdown (where I give a bit of context to the code above).

This can be run either under DOS as a COM (just write the binary data into a file and change extension to "com") or as a bootloader.
For the latter write the standard signature and beware of the issues with modern firmware.

---

1 Not strictly true, any system that happens to have the same ACPI configuration will also shutdown.

# Answer
> 34 votes
# GRUB shell, 4 bytes

**Golfed**

```
halt

```

> Command: halt --no-apm
>
> The command halts the computer. If the --no-apm option is specified, no APM BIOS call is performed. Otherwise, the computer is shut down using APM.

**Bonus**

Here is a proof that GRUB shell is indeed Tur**n**ing-complete (see comments):

# Answer
> 33 votes
# 65C02 machine code, 1 byte

STP instruction (0xDB):

STP stops the clock input of the 65C02, effectively shutting down the 65C02 until a hardware reset occurs (i.e. the RES pin goes low). This puts the 65C02 into a low power state. This is useful for applications (circuits) that require low power consumption, but STP is rarely seen otherwise.

(Source: http://www.6502.org/tutorials/65c02opcodes.html)

xxd dump:

```
00000000: db                                       .

```

# Answer
> 25 votes
# Matlab, 21 Bytes

```
system('shutdown -s')

```

~~I haven't tried this (closing all programs to do a restart in the middle of the day isn't really tempting), but it should work.~~. This works...

I'll add a short explanation later, my laptop is currently off.

# Answer
> 21 votes
# MATLAB, 11 bytes

```
!shutdown/p

```

Somewhat similar to Stewie Griffin's approach. However, MATLAB has ***way*** shorter ways of invoking system commands; in this case, `!` is used. Windows does not need `.exe` for command names, so that's left out as well. The `/` option is still supported (I'm running Windows 10), and negates the need for the space. Alternatives are:

```
system shutdown/p % 17 bytes; uses so-called 'command' syntax.
dos shutdown/p    % 14 bytes; the 'dos' command can be used just as well.

```

# Answer
> 19 votes
# SmileBASIC, ~~14~~ ~~11~~ 6 bytes

```
OPTION

```

Triggers a crash causing the 3DS to restart. I hope this counts.

Works in the most recent version.

# Answer
> 16 votes
# Bash, ~~7~~ 6 bytes

```
init 0

```

Assuming that the program is run as root.

# Answer
> 14 votes
# Python 2, 29 bytes

```
import os;os.system('init 0')

```

Works on Linux systems and needs root privileges.

**For Windows, 33 bytes**

```
import os;os.system('shutdown/p')

```

# Answer
> 14 votes
# Commodore 64, 11 bytes

```
0 sys64738

```

This is from the BASIC prompt. Or...

### Commodore 64, 6502 assembly, 3 bytes (assembled), 16 bytes (source)

```
*=8000
JMP $FCE2

```

# Answer
> 13 votes
# Java, 101 98 62 42 bytes

```
()->{Runtime.getRuntime().exec("init 0");}

```

As @Snowman pointed out, the question didn't specify if a full program was needed, so this should still be acceptable.

# Answer
> 12 votes
# C++, 51 40 bytes

-11 bytes thanks to Ingve!

```
#include<os>
int main(){OS::shutdown();}

```

Only works in IncludeOS (v0.10.0-rc.1)

Test:

```
$ pwd
/home/simon/IncludeOS/examples/demo_service

$ cat service.cpp
#include<os>
int main(){OS::shutdown();}

$ mkdir build && cd build && cmake .. && make && cd ..
[...]

$ boot build/IncludeOS_example
[...]
================================================================================
================================================================================
 IncludeOS v0.10.0-rc.1-9-g151a2b9
 +--> Running [ IncludeOS minimal example ]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

$

```

# Answer
> 12 votes
# AppleScript, 30 bytes

```
tell app "Finder" to shut down

```

Does exactly what it says: tells Finder to shut the computer off.

# Answer
> 12 votes
## TI-Nspire CX CAS, 3 bytes

```
" "+" "

```

*summing two empty strings.*

On an older version of the calculator, this would crash the device and cause it to reboot (there's no way to shutdown a device without reboot apart from physical button combinations).

Video by Adriweb

# Answer
> 10 votes
# AutoHotkey, ~~11~~ 10 Bytes

*Saved a byte thanks to Gurupad Mamadapur*

```
Shutdown,9

```

AHK Supports a Shutdown command by default. The `9` is a flag, consisting of `Shutdown=1` \+ `PowerDown=8`.

# Answer
> 10 votes
# Machine code (x86, boot loader) 18 bytes

```
b8 01 53 33 db cd 15 b8 07 53 bb 01 00 b9 03 00 cd 15

```

Disassembly:

```
mov ax, 0x5301 ; connect to real-mode APM services
xor bx, bx     ; device id 0 - APM BIOS
int 0x15       ; call APM
mov ax, 0x5307 ; set power state
mov bx, 0x0001 ; on all devices
mov cx, 0x0003 ; to Off
int 0x15       ; call APM

```

You can test it in Bochs' debugger with the following commands (after starting simulation, having some disk drive set up):

```
pb 0x7c00
c
setpmem 0x7c00 4 0x335301b8
setpmem 0x7c04 4 0xb815cddb
setpmem 0x7c08 4 0x01bb5307
setpmem 0x7c0c 4 0x0003b900
setpmem 0x7c10 2 0x15cd
c

```

This same machine code will also work as a DOS executable (`*.COM`).

# Answer
> 8 votes
## C#, 79 54 53 bytes

This works on Windows.

**79 bytes**:

```
class _{static void Main(){System.Diagnostics.Process.Start("shutdown","/s");}}

```

**53 bytes**, thanks to TheLethalCoder:

```
_=>System.Diagnostics.Process.Start("shutdown","/s");

```

# Answer
> 6 votes
# AutoIt, 11 bytes

```
Shutdown(1)

```

Shutdown function gets combination of following codes

```
0 = Logoff
1 = Shutdown
2 = Reboot
4 = Force
8 = Power down
16= Force if hung
32= Standby
64= Hibernate

```

To shutdown and power down, for example, the code would be 9 (shutdown + power down = 1 + 8 = 9).

# Answer
> 6 votes
# Windows - NativeAPI, 212 bytes

Ok this is not really the shortest version. But maybe interesting to some. This will *not* execute on the Win32 subsystem. However it will run when executed within the context of the native api (like autochk.exe does)

# Code

```
#define WIN32_NO_STATUS
#include <windef.h>
#include <winnt.h>
#include <ntndk.h>
NTSTATUS main() {
RtlAdjustPrivilege(SE_SHUTDOWN_PRIVILEGE,TRUE,FALSE,NULL);
return ZwShutdownSystem(ShutdownPowerOff);
}

```

# Build

To build this either use the WinDDK `build.exe` tool (with an appropriate `source` file for `NMAKE`)

Or use these commands to compile and link:

```
cl /Gd /D_X86_ /showIncludes /I%DDK_INC_PATH% /I%CRT_INC_PATH% /c main.c
link /verbose /nodefaultlib /subsystem:native /machine:X86 /entry:NtProcessStartup@4 C:\WinDDK\7600.16385.1\lib\win7\i386\nt.lib C:\WinDDK\7600.16385.1\lib\win7\i386\ntdllp.lib C:\WinDDK\7600.16385.1\lib\win7\i386\BufferOverflow.lib .\main.obj

```

Note: This will build an x86 native executable. Change the appropriate bits if you want to build this for a different architecture.

# Test

To test a native executable you have to execute it **before** the win32 subsystem is loaded. One common way to do it is to append the executable in the following registry key:

```
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\BootExecute

```

# Warning

If you do this however, you need to have an option to edit the registry hive of the target OS from another OS. Since **you will not be able to boot the target OS anymore!**

I did it on a VM where i could easily revert to a previous snapshot!

# Answer
> 5 votes
## Groovy, 23 bytes

```
'shutdown /p'.execute()

```

# Answer
> 5 votes
# J, 14 bytes

```
2!:0'poweroff'

```

Works on Linux systems. `2!:0` executes the string in `/bin/sh`.

# Answer
> 5 votes
## AppleScript, 44 bytes

```
tell application "Finder"
shut down
end tell

```

I don't know how AppleScript syntax works or anything, so if anybody knows how to shorten this, please tell.

Also, I'm doing this on my phone at school ("hacking"), so I can't test it.

At 14 fewer bytes (thanks to kindall) you can say

```
tell app "Finder" to shut down

```

# Answer
> 5 votes
# Most Linux shells, 15 bytes

```
# echo o>/p*/*ger

```

It could be made to be 11 bytes long, if you happen to be in the `/proc` directory:

```
# echo o>*ger

```

This is very straightforward (has no side effects, like unmounting filesystems or killing processes) and rather brutal.

# Answer
> 5 votes
## Android shell, 9 bytes

```
reboot -p

```

# Answer
> 4 votes
# Clojure, ~~40~~ 39 bytes

```
(.exec(Runtime/getRuntime)"shutdown/s")

```

-1 byte by changing the flag from `-s` to `/s`, which allowed me to get rid of the space.

Basically the Java answer.

Testing this was fun. Windows decided to do a firmware update on my Surface the second it shut down. Of course.

```
(defn shutdown []
  (.exec (Runtime/getRuntime) "shutdown -s"))

```

# Answer
> 2 votes
## C++, ~~48~~ 47 (Windows) ~~46~~ 45 (Linux) bytes

Removed 1 byte thanks to Snowman

```
#include<cstdlib>
main(){system("shutdown/p");}

```

This should shutdown the system for windows

```
#include<cstdlib>
main(){system("poweroff");}

```

This should shutdown the system for Linux

# Answer
> 2 votes
# Node.js, 39 bytes

Linux

```
require('child_process').exec('init 0')

```

# Answer
> 2 votes
## Bash 15 bytes

```
shutdown -h now

```

alternatively : `init 0`

# Answer
> 2 votes
## Mathematica on Windows 16 Bytes

Invoke the shell command with Run.

```
Run@"Shutdown/p"

```

# Answer
> 2 votes
## AHK, ~~19~~ 15 bytes

```
Run,Shutdown -s

```

Works on windows only.

# Answer
> 2 votes
## R, ~~20~~ 19 bytes

```
shell("shutdown/s")

```

---

Previous answer :

```
system("shutdown/s")

```

# Answer
> 2 votes
# TI-Basic, 3 bytes

```
ClrHome:"

```

Basically, this displays a blank screen and then waits for automatic timeout to kick in and shutdown the calculator, although you will not notice when this happens. The blank screen resembles a shutdown so you will not notice when the device actually shuts down.

# Answer
> 2 votes
# **PHP, 20 bytes**

```
shell_exec("init 0");

```

# Answer
> 2 votes
## DOS 7.1 (Windows 98) command prompt/batch, 5

```
WIN/P

```

Only works from real mode (MS-DOS command prompt).

# Answer
> 2 votes
# Assembly (Z80, Amstrad CPC), one byte

Amstrad CPC cannot be physically shut down by software, but system can be reset.

The following one-byte assembly program is enough to reset system:

```
C7    ;RST 0

```

It is a valid assembly program (in RAM) since no header of any kind is needed on this system.

You can install this program from BASIC e.g.:

```
poke 999,&c7

```

Then call it:

```
call 999

```

## Can I haz test?

You can test at once on CPCBox - Amstrad CPC emulator in Javascript.

# Answer
> 2 votes
# Lisp, 38 bytes

```
(trivial-shell:shell-command "init 0")

```

# Answer
> 2 votes
### Alternative Python on Linux + SysRQ, 47 42 bytes:

```
open("/proc/sysrq-trigger","w").write("o")

```

Can be run either from `python -c` or from script, and requires root privileges to write to the file. The idea isn't python-specific. Writing to that file on Linux can be done in any other way - bash, perl, ruby , etc.

Note that this isn't a graceful shutdown, so expect that there is potential for data to be lost. See the Wikipedia article for more info on sysrq keys.

# Answer
> 2 votes
# **EthOS Shell - 1 byte**

Just type the letter `r` to reboot, i.e.:

`r`

# Answer
> 1 votes
# Python 3, 53 bytes

```
import subprocess
subprocess.call(["shutdown", "/s"])

```

This does give a window and shutdown warning. If you wanted to shut it down immediately then you would use "/p".

You could also call the function from the USER library but this is a longer solution than the submitted version.

# Answer
> 1 votes
# JScript, 53 bytes

```
new ActiveXObject('WScript.Shell').Run("shutdown /s")

```

JScript is Microsoft's implementation of JavaScript. Run with `wscript scriptname.js`.

# Answer
> 1 votes
# VBScript, 46 bytes

```
CreateObject("WScript.Shell").Run "shutdown /s"

```

Run with `wscript scriptname.js`.

# Answer
> 1 votes
# Amstrad CPC Basic, 7 keypresses.

Amstrad CPC cannot be physically shut down by software, but system can be reset with this BASIC call:

```
call 0

```

## How it works

### General info

At the beginning of memory (either RAM or ROM, both are prepared for this), there is a table for Z80 `RST` instruction. These instructions, related to Z80 interrupt handling, are also used (even on machines other than Amstrad CPC, like TI-81) for other tricks because one-byte long assembly instruction is enough to reach any of the 8 entries.

On the Amstrad CPC they are used to space-efficiently call code in ROM, RAM, expansion RAM/ROM, see BIOS Function Summary - CPCWiki or ref page 8+. This is used extensively to make RAM-based indirections that allow easily calling ROM routines from RAM (even from BASIC, like `call &bd19` that waits for screen refresh) and also, by changing them, modifying system behavior even though system is in ROM (like changing how text is displayed, or even redirecting it to printer by changing two bytes of RAM). See `BB00` and following in BIOS Function Summary - CPCWiki or Firmware Guide

### Specific use

Entry zero jumps to a ROM-base routine that performs full machine reset. The simplest way to call it from BASIC it `call 0`.

## Variant

If you insist on a program that can be run rather than a direct command, it takes 8 keypresses:

```
1call 0

```

Then you can `run`.

## Can I haz test?

You can test at once on CPCBox - Amstrad CPC emulator in Javascript.

# Answer
> 1 votes
# Commodore 128 (from native mode), 6 characters including user response and return

```
GO64

```

You will then be prompted with:

```
ARE YOU SURE?

```

Press Y and enter. This shuts down the C128 native mode (I know it doesn't power off the computer, but that's as close as I can get).

# Answer
> 1 votes
# Machine code (x86 boot loader), 2 bytes

```
fa f4

```

Disassembly

```
cli ; disable all maskable interrupts
hlt ; stop the processor until an interrupt or hard reset happens

```

The HLT instruction causes the CPU to stop execution and enter low-power mode, until any interrupt (maskable or NMI) or hard reset happens. This doesn't power off the whole system, but the original IBM PC didn't have any way to power off without the user mechanically pressing the switch. Also, if there happens an NMI, and its handler returns, the program will resume and execute arbitrary code which happens after `f4`. This is unlikely though, since NMI usually signals about hardware faults.

This same code will work as a DOS `.COM` program.

# Answer
> 1 votes
# Perl 5 (on a unix-like OS), 6 bytes

```
`halt`

```

Requires you to be root.

# Answer
> 1 votes
# Jelly, 25 bytes

It makes use of the undocumented monad `ŒV`, which takes a list, concatenates it and evaluates it using Python's `eval`.

```
“WƒuUḤøMŒƁEḄV#ẆṄⱮṁƬṅȯV»ŒV

```

The compressed string translates to `import os;os.system("poweroff")` so it only works on Linux (with root). The following code was used for compressing.

```
Compress().dictionary('import')
          .string(' os;os.')
          .dictionary('system')
          .string('("')
          .dictionary('power')
          .dictionary('off')
          .string('")').go()

```

By changing the `poweroff` it can be extended to other systems (but `power` and `off` are in the dictionary so this will probably be the shortest). For example, following 33-byte version worked on a Mac.

```
“¡Ṁ\\meṾṭ£ȧ+⁾⁸}ḶṠȯƇọṣỴ\\Ḃ⁴8ġṢṾ»ŒV

```

# Answer
> 1 votes
# shortC, 10 bytes

```
A$shutdown

```

Explanation/ungolfed:

```
A           main function
 $          execute system command
  shutdown  shutdown

```

# Answer
> 1 votes
## AppleScript (45 bytes)

```
tell application "System Events" to shut down

```

# Answer
> 1 votes
## Vimscript (Linux Bash) 8 bytes

```
:!init 0

```

## Vimscript (Windows CMD) 12 bytes

```
:!shutdown/p

```

## Vimscript (Windows PowerShell) 15 bytes

```
:!Stop-Computer

```

Two dots `:` are required for the vim command, and the '!' redirects the command to the shell runing behind. You may require some extra permissions for this to work.

# Answer
> 1 votes
# ARM Thumb machine code, Nintendo DS, 30 bytes

```
05 48 05 49 00 23 02 88 12 0a fc d2 01 80 43 80
09 0c 40 23 f7 e7 c0 01 00 04 02 88 02 80

```

Thumb function. Runs at an address that is 2 byte aligned, 4 byte unaligned, **on the ARM7.** The ARM9 cannot access these registers.

This version follows the spec by writing the two halfwords separately, like the code in libnds. Known to work on DeSuMME (it will log it in the console menu) and melonDS, and should work on hardware.

Assembler source:

```
    .syntax unified
    .arch armv4t
    .thumb

    // Force misalignment to align PC load
    // Not part of function
    .p2align 2,0
    .hword 0
    // Begin code
    // void shutdown(void);
    .thumb_func
    .globl shutdown
shutdown:
    // Load address of SPI register
    ldr     r0, REG_SPICNT
    // Load packed SPI commands
    ldr     r1, SPI_COMMANDS
    // Set SPIDATA to select PM_CONTROL_REG
    movs    r3, #0x00
.Lloop:
    // Wait for REG_SPICNT & SPI_BUSY to clear
    ldrh    r2, [r0]
    // Test bit 7 by shifting into carry flag
    lsrs    r2, r2, #8
    bcs     .Lloop
    // Store the low 16 bits of the command to REG_SPICNT
    strh    r1, [r0]
    // Store data to REG_SPIDATA
    strh    r3, [r0, #2]
    // Shift in the next SPI command
    lsrs    r1, r1, #16
    // Set SPIDATA to PM_SYSTEM_PWR
    movs    r3, #0x40
    // Run again with the new commands
    // Then spin again until the SPI powers off the system.
    b       .Lloop

REG_SPICNT:
    // Address of ARM7 IO register
    .word   0x040001c0
    // Two packed halfwords
SPI_COMMANDS:
    // Start a command on the Power Management device,
    // read a byte to select the register
    // SPI_ENABLE | SPI_BAUD_1MHz | SPI_BYTE_MODE | SPI_CONTINUOUS | SPI_DEVICE_POWER
    .hword  0x8802
    // Finish the command on the Power Management device,
    // read a byte to run the action.
    // SPI_ENABLE | SPI_BAUD_1MHz | SPI_BYTE_MODE | SPI_DEVICE_POWER
    .hword  0x8002

```

---

# ARM Thumb machine code function, Nintendo DS, unsafe, 28 bytes

```
03 48 04 49 02 88 12 0a fc d2 01 60 02 49 f9 e7
c0 01 00 04 02 88 00 00 02 80 40 00

```

This function runs at a 4 byte aligned address on the ARM7.

This cheats 2 bytes by writing to SPICNT and SPIDATA at the same time in a full word write, something that has not yet been confirmed to work on hardware. It does not work on DeSuMME, but this might just be an emulator bug.

I am including this because it uses different code.

Assembler source:

```
    .syntax unified
    .arch armv4t
    .thumb

    // Force 4 byte alignment
    .p2align 2,0
    // Begin code
    .thumb_func
    .globl shutdown
shutdown:
    // address of SPI register
    ldr     r0, REG_SPICNT
    // Set SPI register bank
    ldr     r1, SPI_SELECT_PM_CONTROL_REG
.Lloop:
    // Wait for REG_SPICNT & SPI_BUSY to clear
    ldrh    r2, [r0]
    // Test bit 7 by shifting into carry flag
    lsrs    r2, #8
    bcs     .Lloop
    // Store to both SPICNT and SPIDATA
    str     r1, [r0]
    // Send SPI command
    ldr     r1, SPI_SEND_PM_SYSTEM_PWR
    // Loop again with the new value.
    b       .Lloop
    .p2align 2,0
REG_SPICNT:
    .word   0x040001c0
    // SPICNT = SPI_ENABLE | SPI_CONTINUOUS | SPI_BAUD_1MHz | SPI_DEVICE_POWER
    // SPIDATA = PM_CONTROL_REG
SPI_SELECT_PM_CONTROL_REG:
    // Combined halfwords
    .hword  0x8802
    .hword  0x0000
    // SPICNT = SPI_ENABLE | SPI_BAUD_1MHz | SPI_DEVICE_POWER
    // SPIDATA = PM_SYSTEM_PWR
SPI_SEND_PM_SYSTEM_PWR:
    // Combined halfwords
    .hword  0x8002
    .hword  0x0040

```

# Answer
> 0 votes
## AWK, 39 bytes

```
#!/bin/awk -f
BEGIN{"poweroff"|getline}

```

Assumes running on Linux and that `AWK` is located at `/bin/awk` and that the `poweroff` command is in the users path.

Since it uses the `BEGIN` block, no input is necessary. It simply pipes the output of the `poweroff` command into `getline` which it precedes to ignore.

Should work for `Windows` users provided they are in an environment similar to `Cygwin`.

# Answer
> 0 votes
## C, macOS, 18 bytes

```
main(){reboot(8);}

```

This is not a proper shutdown. Usual caveats apply. On my MacBook Air, this resulted in a black screen with a spinning indicator, then a shutdown after a few seconds.

## x64 Assembly, macOS, 11 bytes (untested)

From disassembling the `reboot` function in `libSystem`:

```
movl    $0x2000037, %eax   # b8 37 00 00 02
pushq   $0x08              # 6a 08
popq    %r10               # 41 5a
syscall                    # 0f 05

```

# Answer
> 0 votes
# Perl 5.x (on CentOS Linux), 27 bytes

```
system("shutdown -h now");

```

Make system call to shutdown in Linux to halt (`-h`) now.
Changing `-h` to `-r` will shutdown then reboot Linux.

# Answer
> 0 votes
# AutoIt (windows), 11 bytes:

```
Shutdown(1)

```

# Answer
> 0 votes
# Python, 53 bytes

```
import subprocess
subprocess.call(["shutdown", "/s"])

```

Pretty simple code but can do some damage if you haven't saved anything.

## Breakdown

```
import subprocess

```

This imports the `subprocess` module that comes with Python that can be used across the script.

```
subprocess.call(["shutdown", "/s"])

```

`subprocess.call` runs a process as if you pressed Win + R. It requires a list of strings that will be joined with a space between them and executes it on the PC's shell.

# Answer
> 0 votes
# VBA (32-Bit, Windows Only), 72 Bytes

An anonymous VBE immediate function that calls the declared windows function `ExitWindowsEx` from `user32.dll`.

*To be clear, this requires a 32-Bit version of MS Office, not a 32-Bit version of Windows*

### Declared Function

```
Declare Sub ExitWindowsEx Lib"user32"(ByVal A&,ByVal B&)

```

### Anonymous VBE immediate window function

```
ExitWindowsEx 1,0

```

# Answer
> 0 votes
## Burlesque - 22 bytes

```
"cmd"{"shutdown /s"}ex

```

Obviously you can not try this online.

On linux you can probably get away with `"shutdown"ex` if your distro offers the shutdown util.

# Answer
> 0 votes
# UEFI Shell - 16 bytes

`reset -s`

In ASCII it would be 8 bytes but since UEFI uses UCS-16, every character takes up 2 bytes.

# Answer
> 0 votes
# 05AB1E (legacy) prior to commit June 4th, 2018, 10 bytes

```
’À…„‹/p’.E

```

Try it online without the `.E`.

**Explanation:**

In the commit of June 4th, 2018, the builtin `.E` has been changed from `run_as_Bash_code` to `run_as_Python_code`. So this only works prior to this commit.

```
’À…„‹/p’    # Push dictionary string "shutdown/p"
        .E  # Run it as Bash code

```

# 05AB1E, 25 bytes

```
’£Ø os;os.‚«('À…„‹/p')’.E

```

Try it online without the `.E`.

**Explanation:**

The `.E` builtin is `eval_in_Python` in the current version of 05AB1E.

```
’£Ø os;os.‚«('À…„‹/p')’    # Push dictionary string "import os;os.system('shutdown/p')"
                       .E  # Evaluate as Python code

```

See this 05AB1E tips of mine (section *How to use the dictionary?*) to understand why `’À…„‹/p’` is `"shutdown/p"` and `’£Ø os;os.‚«('À…„‹/p')’` is `"import os;os.system('shutdown/p')"`.

*Note: Both work only on Windows. Could be modified to also work on other OS, i.e. `"init 0".E` and `’£Ø os;os.‚«('„‡ƒŸ')’.E` for Linux.*

---
Tags: code-golf, interactive
---


title: A pieceful standoff

text:
# Question
Title: A pieceful standoff
This challenge requires a small amount of knowledge about . A description of the details required can be found at the bottom if you are not familiar with chess or want a refresher.

For a certain board configuration consisting only of queens we can say that each queens *threat number* is the number of other queens it threatens.

Here is an example board with each queen labeled by their threat number:

```
. . . . . . . .
. . . . . . . .
. . . 2 . . . .
. . . . . . . .
. . . . . . . .
. 2 . 3 . . 2 .
. 1 . . . . . .
. . . . . . . 0

```

A board is at a peaceful standoff if every queen can only attack other queens with the same threat number as themselves.

For example:

```
. . . . . . . .
. . . . . . . .
. 2 . 2 . . . .
. . . . . . . .
. . . . . . . .
. 2 . 2 . . . .
. . . . . . . .
. . . . . . . .

```

Each queen can attack 2 others so it's a peaceful standoff.

As another example:

```
3 . . . . . . 3
. . . . . . . .
. 1 . . . . 1 .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
3 . . . . . . 3

```

Here not all queens have the same threat number. Some threaten 3 others and some only threaten 1 other. However none of the `3`s threaten a `1` (or vice versa) so it's peaceful.

## Task

You will take as input a chessboard and output whether it is a peaceful standoff. You may assume the input board is always the standard chess size of 8 units by 8 units and you may take it as a list of list of booleans, a list of piece locations or any other reasonable format.

You may not require the threat numbers to be pre-calculated in the input. They are shown in the above examples but they are not a part of the input.

You should output one of two consistent distinct values. One when the input is a peaceful standoff and the other when it is not.

This is so the goal is to minimize the size of your source code as measured in bytes.

## Test cases

### False

```
. . . . . . . .
. . . . . . . .
. . . Q . . . .
. . . . . . . .
. . . . . . . .
. Q . Q . . Q .
. Q . . . . . .
. . . . . . . Q

. . . . . . . .
. Q . Q . Q . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .

```

### True

```
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .

. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . Q . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .

. . . . . . . .
. . . Q . . . .
. . . . . . . .
. . . . . . . .
. Q . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .

. . . . . . . .
. . . . . . . .
. . Q Q . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .

. . . . . . . .
. . . . . . . .
. Q . Q . . . .
. . . . . . . .
. . . . . . . .
. Q . Q . . . .
. . . . . . . .
. . . . . . . .

Q . . . . . . Q
. . . . . . . .
. Q . . . . Q .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
Q . . . . . . Q

Q . . . . . . Q
. . Q . . Q . .
. Q . . Q . Q .
. . Q . . . . .
. . . . . Q . .
. Q . Q . . Q .
. . Q . . Q . .
Q . . . . . . Q

```

## Chess

Chess is a game played on an 8 by 8 square grid. Each location on the grid can have up to 1 piece. One such piece is the "queen". Queens can attack any piece that's located in the same row, column, or diagonal as they are, so long as there's not another piece between them an their target. If a piece can attack a piece it is considered to "threaten" that piece.

# Answer
> 8 votes
# JavaScript (ES6), 157 bytes

Expects a binary matrix. Returns an inverted Boolean value.

```
m=>(F=p=>m.some((r,y)=>r.some((v,x)=>!p*([s=0,..."1235678"].map(d=>(g=X=>((X+=d%3-1)|(Y+=~-(d/3)))&8?0:v*(V=m[Y][X])?s+=p|V!=v:g(X))(x,Y=y)),r[x]=s))))(F(1))

```

Try it online!

## How?

This code solves the puzzle in two passes:

* When called with \\$p=1\\$, \\$F\\$ computes the number of queens that interact with each queen, updates the matrix accordingly and returns \\$\text{false}\\$.
* When called with \\$p=\text{false}\\$, \\$F\\$ tests whether at least one queen interacts with a queen that interacts with a different number of queens.

## Commented

### Main wrapper

```
m => F(F(1))         // call F(1), then call F(false)

```

### Helper function F

```
F = p =>             // p = pass
m.some((r, y) =>     // for each row r[] at position y in m[]:
  r.some((v, x) =>   //   for each value v at position x in r[]:
    !p * (           //     do not trigger some() during the 1st pass
      [ s = 0,       //     initialize s to 0 and build the list
        ..."1235678" //     [ 0..3, 5..8 ]
      ].map(d =>     //     for each direction d in this list:
        g(x, Y = y)  //       invoke g with (X, Y) = (x, y)
      ),             //     end of map()
      r[x] = s       //     update m[y][x] to s
    )                //
  )                  //   end of inner some()
)                    // end of outer some()

```

### Helper function g

```
g = X =>             // X is passed explicitly,
                     // Y is passed implicitly
(                    //
  (X += d % 3 - 1) | // add dx = (d mod 3) - 1 to X
  (Y += ~-(d / 3))   // add dy = floor(d / 3) - 1 to Y
)                    //
& 8 ?                // if the resulting position is out of bounds:
  0                  //   stop the recursion
:                    // else:
  v *                //   force the test to fail if there's no queen
                     //   on the source square
  (V = m[Y][X])      //   let V be the value stored at (X, Y)
  ?                  //   if there's a queen there:
    s +=             //     increment s if:
      p |            //       this is the first pass
      V != v         //       or V is not equal to v
  :                  //   else:
    g(X)             //     keep testing this ray

```

# Answer
> 3 votes
# Python3, 301 bytes:

```
lambda b:all(all(len([*t(b,x,y)])==len([*t(b,X,Y)])for X,Y in t(b,x,y))for x in R(8)for y in R(8)if b[x][y])
R=range
def t(b,x,y):
 q=[(x,y,X,Y)for X in[-1,0,1]for Y in[-1,0,1]if X or Y]
 while q:
  x,y,X,Y=q.pop(0)
  A,B=x+X,y+Y
  if 0<=A<8 and 0<=B<8:
   if b[A][B]:yield(A,B)
   else:q+=[(A,B,X,Y)]

```

Try it online!

# Answer
> 3 votes
# Jelly, 30 bytes

-4 thanks to Kevin Cruijssen (remove an effectively redundant filter of the "direction" `[0,0]`, which also means there's no need to get the threatening queen separately.)

```
+8RĖ×Ɱ2Ż’p`¤¤f€ZḢ
ŒṪç€iƇẈEɗⱮ$Ạ

```

A monadic Link that accepts a list of lists of `1`s (queens) and `0`s (not queens) that yields `1` if there is a peaceful standoff or `0` if not.

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

### How?

```
+8RĖ×Ɱ2Ż’p`¤¤f€ZḢ - Helper Link = get queen & threatened queens(
                      queen coordinate, Q;
                      all queen coordinates, A
                    ):
            ¤     - nilad followed by links as a nilad:
 8                -   eight
  R               -   range -> [1,...,7,8]
   Ė              -   enumerate -> [[1,1],...,[7,7],[8,8]]
           ¤      -   nilad followed by links as a nilad:
      2           -     two
       Ż          -     zero-range -> [0,1,2]
        ’         -     decrement -> [-1,0,1]
          `       -     use as both arguments of:
         p        -       Cartesian product -> [[-1,-1],[-1,0],[-1,1],[0,-1],[0,0],[0,1],[1,-1],[1,0],[1,1]]
     Ɱ            -   map with:
    ×             -     multiply -> [[[-1,-1],...,[-7,-7],[-8,-8]],[[-1,0],...,[-7,0],[-8,0]],[[-1,1],...,[-7,7],[-8,8]], ... ... ... ,[[1,1],...,[7,7],[8,8]]]
+                 - (Q) add (vectorises) -> nine lists of potential locations in
                                            each of the eight lines of sight
                                            in proximity order plus the direction
                                            [0,0] which will all be Q
                                            (includes off-board locations)
             f€   - for each: filter keep (A) -> nine lists (eight are possibly empty)
               Z  - transpose
                Ḣ - head -> list of threatened queens and Q herself.

ŒṪç€iƇẈEɗⱮ$Ạ - Link = is peaceful?(board):
ŒṪ           - truthy multidimensional indices -> all queen coordinates
          $  - last two links as a monad - f(all queens):
  ç€         -   call the Helper link for each queen with all queens on the right
         Ɱ   -   map (across Q in all queens) with:
        ɗ    -     last three links as a dyad - f(Helper results, Q):
     Ƈ       -       keep those for which:
    i        -         first 1-indexed index of Q or 0 if not found
      Ẉ      -       length of each
       E     -       all equal?
           Ạ - all?

```

# Answer
> 3 votes
# , 82 71 bytes

```
[:(-:|:)@(*+/)@(=[:+/@(*]=&|[:<./"1|+_*0&=)]*"2(%|)=/~(%|)@1j1^i.@8)-/~

```

Try it online!

Takes input as a list of complex numbers.

We'll consider this example:

```
3 . . . . . . 3
. . . . . . . .
. 1 . . . . 1 .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
3 . . . . . . 3

```

which in complex numbers is `0j0 0j7 7j0 7j7 2j1 2j6`.

* `-/~` Table of differences:

```
  0 0j_7   _7 _7j_7 _2j_1 _2j_6
0j7    0 _7j7    _7  _2j6  _2j1
  7 7j_7    0  0j_7  5j_1  5j_6
7j7    7  0j7     0   5j6   5j1
2j1 2j_6 _5j1 _5j_6     0  0j_5
2j6 2j_1 _5j6 _5j_1   0j5     0

```
* `(%|)` Each of these differences divided by their magnitude, ie, as unit lengths. Pieces can attack each other only if these normalized vectors are equal to one of the 8 evenly spaced unit vectors:
* `=/~(%|)@1j1^i.@8` So, create a 3d table showing where each of the normalized vectors of the difference table is equal to each of the 8 "compass" unit vectors:

```
0 0 0 0 0 0
0 0 0 0 0 0
1 0 0 0 0 0   Differences that point E
0 1 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0

0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0  NE
1 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0

0 0 0 0 0 0
1 0 0 0 0 0
0 0 0 0 0 0  N
0 0 1 0 0 0
0 0 0 0 0 0
0 0 0 0 1 0

0 0 0 0 0 0
0 0 1 0 0 0
0 0 0 0 0 0  NW
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0

0 0 1 0 0 0
0 0 0 1 0 0
0 0 0 0 0 0  W
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0

0 0 0 1 0 0
0 0 0 0 0 0
0 0 0 0 0 0  SW
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0

0 1 0 0 0 0
0 0 0 0 0 0
0 0 0 1 0 0  S
0 0 0 0 0 0
0 0 0 0 0 1
0 0 0 0 0 0

0 0 0 0 0 0
0 0 0 0 0 0
0 1 0 0 0 0  SE
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0

```
* `]*"2` Use these as as filters for the original input:

```
0    0    0     0   0    0
0    0    0     0   0    0
7    0    0     0   0    0
0    7    0     0   0    0
0    0    0     0   0    0
0    0    0     0   0    0

0    0    0     0   0    0
0    0    0     0   0    0
0    0    0     0   0    0
7j7  0    0     0   0    0
0    0    0     0   0    0
0    0    0     0   0    0

0    0    0     0   0    0
0j7  0    0     0   0    0
0    0    0     0   0    0
0    0  0j7     0   0    0
0    0    0     0   0    0
0    0    0     0 0j5    0

0    0    0     0   0    0
0    0 _7j7     0   0    0
0    0    0     0   0    0
0    0    0     0   0    0
0    0    0     0   0    0
0    0    0     0   0    0

0    0   _7     0   0    0
0    0    0    _7   0    0
0    0    0     0   0    0
0    0    0     0   0    0
0    0    0     0   0    0
0    0    0     0   0    0

0    0    0 _7j_7   0    0
0    0    0     0   0    0
0    0    0     0   0    0
0    0    0     0   0    0
0    0    0     0   0    0
0    0    0     0   0    0

0 0j_7    0     0   0    0
0    0    0     0   0    0
0    0    0  0j_7   0    0
0    0    0     0   0    0
0    0    0     0   0 0j_5
0    0    0     0   0    0

0    0    0     0   0    0
0    0    0     0   0    0
0 7j_7    0     0   0    0
0    0    0     0   0    0
0    0    0     0   0    0
0    0    0     0   0    0

```
* The problem now is that only the shortest positive distance in each direction counts, because the others are blocked by the first piece. The next series of steps filters these blocked pieces.
* `(=[:+/@(*]=&|[:<./"1|+_*0&=)` Ignoring zeros, take the min of each row (using norm for comparison), and keep only entries equal to that min. These are attackable queens. Then sum the planes, which are guaranteed not to overlap, and check where those equal the normalized differences. This is adjanceny matrix of connected queens:

```
1 1 0 0 1 1
1 1 0 0 1 1
0 0 1 1 0 0
0 0 1 1 0 0
1 1 0 0 1 1
1 1 0 0 1 1

```
* `(-:|:)@(*+/)@` Multiply the rows by the column sums, and check if the matrix is symmetric around the main diagonal:

```
4 4 0 0 4 4
4 4 0 0 4 4
0 0 2 2 0 0
0 0 2 2 0 0
4 4 0 0 4 4
4 4 0 0 4 4

```

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

```
#define A(c)for(i=0;i<64;++i)for(m=j=0;j<64;++j)if(j-i&&b[i]>0&b[j]>0){x=i/8-j/8,y=i%8-j%8;t=0;x||(t=(y>0)+1);y||(t=(x>0)*4+4);abs(x)-abs(y)||(t=16<<((x>0)+(y>0)*2));if(t&&!(m&t)){c;}}
f(b,i,j,m,t,y,x)int*b;{A(b[i]++;m|=t)A(if(b[i]-b[j])return 0)return 1;}

```

Try it online!

# Answer
> 1 votes
# Charcoal, 70 bytes

```
Ｅ⁸Ｓ≔Ｅ⁸Ｅ⁸⟦⟧ηＦ⁸Ｆ⁸Ｆ⁸«Ｊικ≔⌕ＡＫＤ⁸✳λQθ¿∧№θ⁰⌈θ«Ｍ§θ¹✳λ⊞§§ηⅈⅉ§§ηικ»»⎚⬤η⬤ι⬤λ⁼ＬνＬλ

```

Try it online! Link is to verbose version of code. Takes input as a list of 8 strings of 8 `Q`s and `.`s. Explanation:

```
Ｅ⁸Ｓ

```

Input the board and print it to the canvas.

```
≔Ｅ⁸Ｅ⁸⟦⟧η

```

Start with no Queens being attacked.

```
Ｆ⁸Ｆ⁸Ｆ⁸«

```

Loop over each possible direction for each possible Queen.

```
Ｊικ≔⌕ＡＫＤ⁸✳λQθ

```

Look at the pieces at the current position in the current direction.

```
¿∧№θ⁰⌈θ«

```

If there is a Queen at the current position and at least one more Queen in the current direction, then...

```
Ｍ§θ¹✳λ⊞§§ηⅈⅉ§§ηικ

```

... move to the next Queen in the current direction, and add the current Queen to the list of Queens that are attacking it.

```
»»⎚⬤η⬤ι⬤λ⁼ＬνＬλ

```

Check that all lists of Queens have elements of the same length. Example: If there are Queens at a1, a8, h1 and h8, then let the lists at those positions be denoted by `a1`, `a8`, `h1` and `h8`, then we have `a1 = [a8, h1, h8]`, `a8 = [a1, h1, h8]`, `h1 = [a1, a8, h8]` and `h8 = [a1, a8, h1]`; each list `a1`, `h8`, `h1` and `h8` contains three elements and those three elements are also all lists of three elements. (Conveniently this is also vacuously true for the squares that don't contain Queens and are therefore empty lists.)

# Answer
> 0 votes
# Java 10, ~~248~~ ~~246~~ ~~241~~ ~~239~~ ~~237~~ ~~219~~ ~~217~~ 212 bytes

```
b->{boolean r=1>1,B;for(int m[]=new int[64],f=128,i,d,X,Y;f-->0;)for(d=9;b[i=f%64]&d-->0;m[i]+=B&&b[Y+=X*8]?f/64:0,r|=f<64&B&&m[i]!=m[Y])for(X=i/8,Y=f%8;(B=~(X+=d/3-1)%9<0&~(Y+=d%3-1)%9<0)&&!b[X*8+Y];);return!r;}

```

Inspired by *@Arnauld*'s JavaScript answer.
-25 bytes thanks to *@ceilingcat*.

Input as a flat boolean-array.

Try it online.

**Explanation:**

```
b->{                       // Method with boolean-array parameter & boolean return
  boolean r=0>1,           //  Result-boolean, starting at false
          B;               //  Flag whether we're still in boundary
  for(int m[]=new int[64], //  Array to keep track of queen's thread levels
      f=128,               //  Flag-integer
      i,                   //  Index-integer
      d,                   //  Direction-integer
      X,Y;                 //  X,Y-coordinate integers of a taken direction of a queen
      f-->0;)              //  Loop `f` in the range (128,0]:
    for(d=9;b[i=f%64       //   Set `i` to `f` modulo-64
                    ]&     //   If the `i`'th cell contains a queen:
             d-->0         //    Inner loop `d` in the range (9,0]:
        ;                  //      After every iteration of loop `d`:
         m[i]+=            //       Increase the current `i`'th threat value by:
          B                //        If we're still in bounds,
          &&b[Y+=X*8]?     //        and `X,Y` contains a threatening† queen:
           f/64            //         Increase it by `f` integer-divided by 64
                           //         (1 in the first 64 iterations, 0 in the second 64)
          :                //        Else:
           0,              //         Leave it unchanged by increasing with 0
         r|=               //        Also update the result to:
            f<64           //         If this is within the first 64 iterations
            &B             //         And we're still in bounds:
            &&m[i]!=m[Y])  //          Check whether the `i` and `X,Y` threat-levels
                           //          are NOT the same
      for(X=i/8,Y=f%8;     //     (Re)set `X,Y` based on `i` and `f`
          (B=~(X+=d/3-1)   //     Go to the next `X`-coordinate based on `d`
               %9<0        //     And check if it's still in bounds
          &~(Y+=d%3-1)%9<0)//     Do the same for the `Y`-coordinate
          &&               //     And if we're still in bound:
            !b[X*8+Y];);   //      Stop the inner-most loop if we've encountered a
                           //      threatening† queen
  return!r;}               //  Finally: return the inverse of result `r`

```

: Because we don't skip direction `d=4` (which means `x,y==X,Y`), every queen will have a tread-level one higher than in the challenge description, because it'll increase for its own position (a.k.a. every queen 'threatens' itself). But since this is done for *each* individual queen, it won't matter for the final output.

# Answer
> 0 votes
# Japt, 91 bytes

```
Jõ ïJõ
@VmA{8õ@Am*XÃ®íX'+Ãfe_>J©Z<8Ã£g$...$X
U=Ë£X©[EY]gW md x
Ëe@!Xª[EY]gW me_¥XªZ¥0Ãe}Ãe

```

Try it

Note that there should be an additional empty line in front of the code, but it's not displaying here. Takes input as a 2D array with Queens as `1` and empty spaces as `0`.

This is probably the worst Japt code I've ever written and I am certain there are a lot of improvements to make.

### Explanation

The first line is blank, because Japt automatically stores the result of each line in a variable. If the first line is not blank then its result would overwrite the input

```
            # Implicitly store input as U

```

The second line generates the 8 direction vectors a queen can move in, as well as `[0,0]` i.e. "not moving" which is unnecessary but ends up not mattering

```
Jõ ïJõ
Jõ     # The range [-1...1]
   ï   # Get every possible pair with:
    Jõ #  The range [-1...1] again
       # Store as V

```

The third line does the bulk of the work here. It declares a function which takes a pair of coordinates as input, and returns an array indicating the cells in U which are in each of the 9 "directions" relative to those coordinates.

```
@VmA{8õ@Am*XÃ®íX'+Ãfe_>J©Z<8Ã£g$...$X
@                                     # Declare a function:
 VmA{             Ã                   #  For each direction:
     8õ@Am*XÃ®íX'+                    #  (Get the coordinates for 8 cells in that direction)
     8õ@    Ã                         #   For each value X in the range [1...8]
        Am*X                          #    Multiply the direction vector by X
             ®                        #   For each resulting pair:
              íX'+                    #    Add the input coordinates
                   fe_>J©Z<8Ã         #  (Remove out-of-bounds coordinates)
                   f                  #   Keep only coordinates which where:
                    e_      Ã         #    Both parts:
                      >J              #     Are greater than -1
                        ©             #     And
                         Z<8          #     Are less than 8
                             £g$...$X #  (Get the values from U at those coordinates)
                             £        #   For each remaining coordinates X:
                              g       #    Get the value from U at:
                               $...$X #     Multi-dimensional coordinates X

```

The fourth line calls V on every pair of coordinates that has a queen, counts the number of directions which see another queen, then saves that count back in the same cell of U. Technically the number saved is 1 higher than the threat number since one of the directions is "don't move" but it doesn't affect anything.

```
U=Ë£X©[EY]gW md x
  Ë£              # For every cell X in U:
    X©            #  Return 0 if X is 0
      [EY]gW      #  Otherwise call W on the coordinates of X
             m    #  For each direction:
              d   #   True if there are any queens
                x #  Count the number of true directions
U=                # Save the results back into U

```

The fifth line uses W again to get the sightlines, then checks that every cell's sightlines only contain empty spaces and other queens with the same threat number.

```
Ëe@!Xª[EY]gW me_¥XªZ¥0Ãe}Ãe
Ë                        Ã  # For every row D of U:
 e@                     }   #  True if every cell X in that row returns true:
   !Xª                      #   Return true if X is 0
      [EY]gW                #   Otherwise call W on the coordinates of X
             m              #   For each direction:
              e_      Ã     #    True if every cell Z in that direction returns true:
                ¥X          #     Z == X
                  ª         #     Or
                   Z¥0      #     Z == 0
                       e    #   Return true if every direction returned true
                          e # Output true if every row returned true

```

# Answer
> 0 votes
# Raku, 122 bytes

```
{my%x=@^q.map:{$^q=>map {first(@q.any,($q,*+$^d...*)[1..7])//|()},((-1,0,1)X+(-i,0,i))};[&&] %x{*}.map:{[==] @^v,|%x{@v}}}

```

Try it online!

Input is a list of complex numbers, the queen coordinates.

* `my %x = @^q.map: { $^q => ... }` generates a hash from each queen to a list of the other queens that it threatens, storing it in the variable `%x`.
* `(-1, 0, 1) X+ (-i, 0, i)` crosses the real numbers -1, 0, and 1 with the complex numbers -i, 0, and i with addition, producing the nine complex numbers -1-i, -1, -1+i, -i, 0, i, 1-i, 1, and 1+i. These are the steps that will be followed from each queen, looking for another queen that it threatens. For brevity, we don't omit the step 0, so each queen will count as attacking itself. That doesn't change the final boolean answer.
* `first(@q.any, ($q, * + $^d ... *)[1..7]) // |()` takes up to seven steps from each queen, stopping when it encounters one of the other queens. `first` returns `Nil` if it doesn't find anything, so the `// |()` converts that into a Slip object, which doesn't leave anything in the output list.
* `[&&] %x{*}.map: { [==] @^v, |%x{@v} }` checks that each hash value `@^v` (that is, each list of threatened queens) satisfies the condition that its size is equal to the sizes of every other list of queens threatened by those queens.

---
Tags: code-golf, decision-problem, chess
---


title: Necklace stones puzzle

text:
# Question
Title: Necklace stones puzzle
Given a necklace with color stones (yellow, white, brown, etc.) of at least two different colors, we describe that necklace using letters that correspond to each color, choosing an arbitrary starting point.

We try to answer these questions:

* How many distinct colors does the necklace have?
* What's the length of the longest segment of contiguous stones of the same color?
* If necklace can be cut at any position, removing all contiguous stones of the same color immediately to the left and to the right of the cutting point, what's the biggest amount of stones which could be taken?

Note that the necklace is considered cyclical. Therefore, letters at the start and end of the given input string can form a single sequence (see second test case below).

### Test cases

```
aaaab -> 2 4 5
aabaa -> 2 4 5
uamaaauumaummuauamumummmmua -> 3 4 5

```

What's the shortest code to achieve this? Any language is welcome.

# Answer
# Ruby, 90 bytes

-2 bytes thanks to Sʨɠɠan

```
->a{[(a&a*=2).size,(c=a.slice_when{_1!=_2}.map &:size).max,c.each_cons(2).map(&:sum).max]}

```

Attempt This Online!
> 2 votes

# Answer
# CJam, 28 bytes

```
r__&,a\2*e`0f=_2ew::+]::e>S*

```

Try it online.

### How it works

```
r    e# Read a whitespace-separated token from STDIN.
__   e# Push two copies.
&    e# Intersect two of the copies (removes duplicates).
,a   e# Calculate the length and wrap it in an array.
\    e# Swap the array with the input string.
2*   e# Repeat the input string two times.
e`   e# Perform run-length encoding.
0f=  e# Keep only the repetitions.
_2ew e# Copy and push the overlapping slices of length two.
::+  e# Add the integers in the resulting slices.
]    e# Wrap the entire stack in an array.
::e> e# Compute the maximum of each of the three arrays.
S*   e# Join, separating by spaces.

```
> 7 votes

# Answer
# Pyth, 20 bytes

```
l{zeSJhCr+zz8eS+VJtJ

```

Try it online: Demonstration

### Explanation

```
                      implicit: z = input string
 {z                   set of z
l                     len and print
         +zz          z + z (because cyclic)
        r   8         run-length-encoding
      hC              zip and only use the first column (quantities)
     J                store in J
    S                 sort
   e                  take the maximal element and print
               +V     vectorized add of
                 JtJ  J and J[1:]
             eS       sort and print maximal element

```
> 7 votes

# Answer
# Haskell, ~~141~~ 137 bytes

```
import Data.List
l=length
m=maximum
v#w=l$v$group w
f n=(l$nub n,m$map l$group n,m[last#take i n+head#drop i n|i<-[1..l n-1]])
p n=f$n++n

```

Usage example:

```
*Main> map p ["aaaab","aabaa","uamaaauumaummuauamumummmmua"]
[(2,4,5),(2,4,5),(3,4,5)]

```

How it works: Like the other answers I deal with the cycle by working on the input string concatenated to itself.

* distinct colors: length of the list where duplicates are removed
* longest segment of the same color: group consecutive colors, get length of each group, take maximum
* split and take left and right segments: for each index `i`: split into left and right part at `i`, group consecutive colors in each part, add length of the last group of the left part and length of first group of the right part. Take maximum of the sums.
> 2 votes

# Answer
## JavaScript (ES6), ~~203~~ 199 bytes

Credit goes to this answer on Code Review SE for the array unique function.

```
f=w=>{for(x=Math.max,z=[],o=[[...w+=w].filter((x,p)=>w.search(x)==p).length],i=w.length-(c=1);i;)c=(w[i]!=w[--i]?(z.push(c)&0):c)+1;o.push(x.apply(0,z),x.apply(0,z.map((v,i)=>v+=z[i+1]|0)));return o}

```

### Demo

ES6, so Firefox only for now.

```
f = w => {
  for (x = Math.max, z = [], o = [
    [...w += w].filter((x, p) => w.search(x) == p).length
  ], i = w.length - (c = 1); i;)
    c = (w[i] != w[--i] ? (z.push(c) & 0) : c) + 1;

  o.push(x.apply(0, z), x.apply(0, z.map((v, i) => v += z[i + 1] | 0)));
  return o
}

// DEMO
console.log = x => document.body.innerHTML += x + "<br>";

console.log(f('aaaab'));
console.log(f('aabaa'));
console.log(f('uamaaauumaummuauamumummmmua'));
```
> 2 votes

# Answer
# Perl 5 `-n`, 96 bytes

```
$_.=$_;@k{/./g}++;/(.)\1+(.)\2+/;say for 0+keys%k,length$&,(sort{$b-$a}map y///c,/((.)\2+)/g)[0]

```

Try it online!

Changed the output order:

```
Number of unique colors
Longest after cutting
Longest contiguous string of one color

```
> 2 votes

# Answer
# Python 2, 124 bytes

```
from itertools import*
I=input()*2
r=[len(list(g))for _,g in groupby(I)]
print len(set(I)),max(r),max(map(sum,zip(r,r[1:])))

```

Try it online!
> 1 votes

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


# Question
Title: Find a matrix whose sliding sum is the input
Given a matrix like this:

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

```

By taking a 2×2 "sliding sum", where the sum of every 2×2 region of the matrix is one element of the resulting matrix, we get:

```
1  1  1
1 -1  1
1  1  1

```

We can do this for sliding windows of any size. For example, a 1×3 sliding sum of the same input matrix would be:

```
 5  2
 0 -4
 3  2
-1 -1

```

In this challenge, you'll be given an *output* matrix and a window size, and should return a matrix whose sliding sum with the given window size is the input. The window size will be at least 1×1, but there is no maximum size.

Inputs and outputs will consist only of integers. Note that there are arbitrarily many correct solutions for most window sizes.

This is , so shortest answer per language (in bytes) wins.

# Answer
# Python, 130 bytes

```
lambda A,m,n:[g(r,n)for r in zip(*(g(c,m)for c in zip(*A)))]
g=lambda A,k:A and g(A[:-1],k)+[sum(A[::-k])-sum(A[-2::-k])]or[0]*~-k

```

Attempt This Online!

This solves the problem dimension by dimension. The function `g` essentially implements multiplication by a pseudoinverse of the 1d convolution matrix which depending on dimensions looks somewhat like

\\$\begin{pmatrix}1&0&0&0&0&0\\\-1&1&0&0&0&0\\0&-1&1&0&0&0\\1&0&-1&1&0&0\\\-1&1&0&-1&1&0\\0&-1&1&0&-1&1\\1&0&-1&1&0&-1\\\-1&1&0&-1&1&0\end{pmatrix}\\$

which inverts

\\$\begin{pmatrix}1&1&1&0&0&0&0&0\\0&1&1&1&0&0&0&0\\0&0&1&1&1&0&0&0\\0&0&0&1&1&1&0&0\\0&0&0&0&1&1&1&0\\0&0&0&0&0&1&1&1\end{pmatrix}\\$
> 10 votes

# Answer
# Python3, 556 bytes:

```
from itertools import*
R=range
D=lambda l,y:l*y-(y-1)*(l-1)
def O(V,v):
 c=0
 while c:=c+1:
  for i in product(*[[R(-c,c+1),[a]][b]for a,b in V]):
   if sum(i)==v:return[*i]
def f(m,x,y):
 q=[([[[0,0]for _ in R(D(len(m[0]),y))]for _ in R(D(len(m),x))],0,0,[j for k in m for j in k])]
 while q:
  b,X,Y,v=q.pop(0)
  if[]==v:return[[a for a,_ in i]for i in b]
  r=O([b[j][k]for j in R(X,X+x)for k in R(Y,Y+y)],v[0])
  B=eval(str(b))
  for j in R(X,X+x):
   for k in R(Y,Y+y):B[j][k]=[r.pop(0),1]
  q+=[(B,[X+1,X][Y+y<len(b[0])],[0,Y+1][Y+y<len(b[0])],v[1:])]

```

Try it online!
> 3 votes

# Answer
# PARI/GP, 150 bytes

```
f(a,m,n)=b=matinverseimage(matrix(#a*H=#a~,(w=#a+n-1)*h=H+m-1,i,j,![m<=x=j--%h-i--%H,x<0,n<=y=j\h-i\H,y<0]),concat(Vec(a)));matrix(h,w,i,j,b[i+j--*h])

```

Attempt This Online!

Or 119 bytes if we can output a flatten array:

```
f(a,m,n)=matinverseimage(matrix(#a*H=#a~,(#a+n-1)*h=H+m-1,i,j,![m<=x=j--%h-i--%H,x<0,n<=y=j\h-i\H,y<0]),concat(Vec(a)))

```

Attempt This Online!
> 2 votes

# Answer
# Charcoal, ~~62~~ 53 bytes

```
Ｆ⊖η⊞υＥ⊖⁺ζＬ§θι⁰Ｆθ«≔Ｅ⊖ζ⁰ε⊞υεＦι⊞ε⁻κΣＥ…⮌υη↨¹✂λ⁻⊕Ｌεζ⊕Ｌε»Ｉυ

```

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

```
Ｆ⊖η⊞υＥ⊖⁺ζＬ§θι⁰

```

Generate zero rows of the final width which will pad the final matrix to the final height.

```
Ｆθ«

```

Loop over the rows of the input matrix.

```
≔Ｅ⊖ζ⁰ε

```

Start a new row of the output matrix with zeros which will pad the row to the final width.

```
⊞υε

```

Append the new row to the output matrix.

```
Ｆι

```

Loop over the cells of the current input matrix row.

```
⊞ε⁻κΣＥ…⮌υη↨¹✂λ⁻⊕Ｌεζ⊕Ｌε

```

Add the next entry to the output matrix row so that the sliding sum for this cell of the input matrix becomes correct. Note that "base 1" is used to sum the cells in a row because in the case of a window of width 1 the final row's cell does not exist yet.

```
»Ｉυ

```

Output the resulting matrix in default Charcoal format.

Example: For the given 2×2 sliding sum:

```
 1  1  1
 1 -1  1
 1  1  1

```

First a padding row is constructed, then a padding cell for the first input row:

```
 0  0  0  0
 0

```

To make the first sliding sum correct, a `1` is needed:

```
 0  0  0  0
 0  1

```

To make the second sliding sum correct, a `0` is needed:

```
 0  0  0  0
 0  1  0

```

To make the third sliding sum correct, another `1` is needed:

```
 0  0  0  0
 0  1  0  1

```

The new row starts again with a padding cell. To make the fourth sliding sum correct, a `0` is needed:

```
 0  0  0  0
 0  1  0  1
 0  0

```

To make the fifth sliding sum correct, a `-2` is needed:

```
 0  0  0  0
 0  1  0  1
 0  0 -2

```

Continuing in this way, the resulting matrix is as follows:

```
 0  0  0  0
 0  1  0  1
 0  0 -2  2
 0  1  2 -1

```
> 2 votes

---
Tags: code-golf, integer, matrix
---


title: Next Time Of Given Pattern

text:
# Question
Title: Next Time Of Given Pattern
## Introduction:

Some times using a 24-hour clock are formatted in a nice pattern. For these patterns, we'll have four different categories:

```
All the same (pattern A:AA or AA:AA):
 0:00
 1:11
 2:22
 3:33
 4:44
 5:55
11:11
22:22

```

```
Increasing (pattern B:CD or AB:CD, where D==C+1==B+2==A+3):
 0:12
 1:23
 2:34
 3:45
 4:56
12:34
23:45

```

```
Pair (pattern AB:AB):
10:10
12:12
13:13
14:14
15:15
16:16
17:17
18:18
19:19
20:20
21:21
23:23

```

```
Palindrome (pattern A:BA or AB:BA):
 0:10
 0:20
 0:30
 0:40
 0:50
 1:01
 1:21
 1:31
 1:41
 1:51
 2:02
 2:12
 2:32
 2:42
 2:52
 3:03
 3:13
 3:23
 3:43
 3:53
 4:04
 4:14
 4:24
 4:34
 4:54
 5:05
 5:15
 5:25
 5:35
 5:45
 6:06
 6:16
 6:26
 6:36
 6:46
 6:56
 7:07
 7:17
 7:27
 7:37
 7:47
 7:57
 8:08
 8:18
 8:28
 8:38
 8:48
 8:58
 9:09
 9:19
 9:29
 9:39
 9:49
 9:59
10:01
12:21
13:31
14:41
15:51
20:02
21:12
23:32

```

## Challenge:

Given a starting time and a category, output how many minutes should be added to the start time, for it to reach the closest (forward) time of the given category.

*For example:* if the start time is `14:47` and the category is `palindrome`, the smallest time after `14:47` in the palindrome category is `15:51`, so the output is `64` minutes (because 14:47 + 64 minutes = 15:51).

## Challenge Rules:

* As you may have noted: the times in the 'All the same' category are excluded from the 'Pair' and 'Palindrome' categories, even though they are technically also pairs/palindromes.
* We only look forward when we go to the closest time. So in the example above the output is `64` (time `15:51`) and not `-6` (time `14:41`).
* You may take the times in any reasonable format. May be a string, a (Date)Time-object, a pair of integers, etc.
* You may use any *reasonable* distinct input-values for the four categories. (Keep in mind this forbidden loophole!) May be four integers; may be the category-names as strings; may be an enum; etc.
* If the input-time is already valid for the given category, the result is `0` (so we won't look for the next one).
* We use an `A:BC` pattern for single-digit hours, so they won't be left-padded with a `0` to `0A:BC`.

## General Rules:

* This is , so the shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* Standard rules apply for your answer with default I/O rules, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
* Default Loopholes are forbidden.
* If possible, please add a link with a test for your code (e.g. TIO).
* Also, adding an explanation for your answer is highly recommended.

## Test Cases:

You don't need to output the time between parenthesis. Those are just added as clarification in the test cases below. Only the integer-output is required to be output.

```
Inputs: 14:47, palindrome
Output: 64   (15:51)

Inputs: 0:00, all the same
Output: 0    (0:00)

Inputs: 23:33, palindrome
Output: 37   (0:10)

Inputs: 23:24, pair
Output: 646  (10:10)

Inputs: 10:00, increasing
Output: 154  (12:34)

Inputs: 0:00, increasing
Output: 12   (0:12)

Inputs: 23:59, all the same
Output: 1    (0:00)

Inputs: 11:11, pair
Output: 61   (12:12)

```

# Answer
# Pyth, 82 bytes

```
L+%/b60 24%"%02d"%b60JiQ60KE-f@[q1l{yT!-.+CMyT1&%%T60 11q.*cyT2&%%T60 11q_yTyT)KJJ

```

Try it online!

A bit ham fisted, but it works. Expects time as an integer list \[hours, minutes\] and type as (ALL, INC, PAI, PAL) -\> (0, 1, 2, 3)

### Explanation

```
L+%/b60 24%"%02d"%b60                                                                 define y(b) to format a number of seconds to the string "(h)hmm"
                     JiQ60                                                            set J to the input time as a number of seconds
                          KE                                                          set K to the input mode
                            -                                                    J    subtract the input time from
                             f                                                  J     the first integer greater than or equal to the input which satisfies
                              @[                                              )K      mode selection
                                q1l{yT                                                formatted string only has one unique character (all)
                                      !-.+CMyT1                                       code point deltas are all 1 (inc)
                                               &%%T60 11q.*cyT2                       string splits into two equal parts but seconds are not 0 mod 11 (pai)
                                                               &%%T60 11q_yTyT        string is the same as itself backwards but seconds are not 0 mod 11 (pal)

```
> 5 votes

# Answer
# JavaScript (ES6), 126 bytes

*-2 bytes thanks to Kevin*

Expects `(type)(minutes, hours)`, with type in \\$\[0..3\]\\$ (*all the same*, *increasing*, *pair* and *palindrome* respectively).

```
t=>g=(m,h,T=10,d=m-h)=>[q=m%11|d&&d-h*T,d-12-T*(282%h^6?h:1),h<T|d,(h>9?m/T^h%T?T:h/T:h)^m%T][t]|!q*t&&1+g(m=-~m%60,(h+!m)%24)

```

Try it online!

## How?

All formulae are falsy if the criterion is met, or truthy if it's not.

If the first test is triggered, the other ones are forced to fail (this is `| !q * t` in the code). This enforces the rule about discarding pairs and palindromes with a unique digit.

### All the same

```
m % 11 | m - h && m - h * 11

```

We must have either:

* \\$m\bmod 11=0\\$ and \\$m=h\\$ (e.g. 22:22)
* or \\$m=h\times11\\$ (e.g. 4:44)

### Increasing

```
m - h - 12 - 10 * (282 % h ^ 6 ? h : 1)

```

We must have either:

* \\$m=h+12+10\\$ if \\$h\in\\{12,23\\}\\$
* or \\$m=h+12+10\times h\\$ if \\$h\notin\\{12,23\\}\\$

We have \\$282\bmod h=6\\$ if \\$h\in\\{12,23\\}\\$ and \\$282\bmod h\neq 6\\$ otherwise.

### Pair

```
h < 10 | h - m

```

We must have \\$h\ge9\\$ and \\$h=m\\$.

### Palindrome

```
(h > 9 ? m / 10 ^ h % 10 ? 10 : h / 10 : h) ^ m % 10

```

We must have either:

* \\$h=m\bmod 10\\$ if \\$h\le 9\\$
* or \\$\lfloor m/10\rfloor = h\bmod 10\\$ and \\$\lfloor h/10\rfloor = m\bmod 10\\$ if \\$h\>9\\$
> 4 votes

# Answer
# Jelly, 33 bytes

```
,_J$;,Ṛ,ŒHƲE€i1
“ð©½‘ḶŒpDF€ṙ⁸Ç€i’

```

A dyadic link that accepts the time of day in minutes as an integer on the left and the category as an integer on the right and yields the number of minutes until the clock will show a time with the given category.

| category | input value |
| --- | --- |
| all the same | 1 |
| increasing | 2 |
| palindrome | 3 |
| pair | 4 |

(Zero will give the time until no category too.)

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

### How?

```
,_J$;,Ṛ,ŒHƲE€i1 - Helper Link = categorise: Time as a list of three or four digits
   $            - last two links as a monad - f(Time):
  J             -   range of length (Time) -> [1,2,3] or [1,2,3,4]
 _              -   (Time) subtract (that) (vectorises)
,               - (Time) pair with (that)
          Ʋ     - last four links as a monad - f(Time):
      Ṛ         -   reverse (Time)
     ,          -   (Time) pair with (that)
        ŒH      -   split (Time) into two halves
       ,        -   ([Time, Reversed(Time)]) pair (that)
    ;           - concatenate
                  -> [Time, Time - Indices, [Time, Reversed(Time)], [Prefix, Suffix]]
            €   - for each:
           E    -   all equal? -> 1 or 0
             i1 - first 1-indexed index of 1, or 0 if none

“ð©½‘ḶŒpDF€ṙ⁸Ç€i’ - Link = time to next: time of day in minutes, M; category, C
“ð©½‘             - code-page indicies = [24,6,10]
     Ḷ            - lowered range -> [[0..23],[0..5],[0..9]]
      Œp          - Cartesian product -> [[0,0,0],...,[0,5,9],[1,0,0],...,[23,5,9]]
        D         - digits -> [...,[[2,3],[5],[9]]]
         F€       - flatten each -> [[0,0,0],...,[0,5,9],[1,0,0],...,[2,3,5,9]]
           ṙ⁸     - rotate (that) left by (M)
             Ç€   - call the helper Link (above) for each
               i  - first 1-indexed index of (C) in (that)
                ’ - decrement

```
> 4 votes

# Answer
# Japt, 73 bytes

```
@V¥[_e¥0}_e¥J}_ä+ e[TT]}_Î¥ZÌn «Zx}]b!gUì60_+60²+XÃÅvu24 gJ,_s ù'02Ã¬ä-}a

```

Try it

Input is `[hours, minutes], pattern` with `pattern` in the range \[0...3\] using the same order as they are listed in the question.

### Explanation:

Broad overview:

```
@                 }a # Find the smallest X that returns true:
           Uì...ä-   #  Calculate the time after X minutes and do some preprocessing
   [...]b!g          #  Find the first pattern that it matches
 V¥                  #  Check that it's the pattern we're looking for

```

Calculating times:

```
Uì60_+60²+XÃÅvu24 gJ,_s ù'02Ã¬ä-
Uì60_                            # Convert the input from base-60 to base-10
     +60²                        # Add 3600, forcing 3 digits of output
         +X                      # Add X minutes
           Ã                     # Convert back to base-60
            Å                    # Remove the extra digit we added
             v                   # Modify the first remaining digit:
              u24                #  Mod 24
                  gJ,_      Ã    # Modify the last digit:
                      s          #  Convert to a string
                        ù'02     #  Left-pad with 0 to length 2
                             ¬   # Join the digits to a string
                              ä- # Get the difference between consecutive digits

```

Check against the patterns:

```
[_e¥0}_e¥J}_ä+ e[TT]}_Î¥ZÌn «Zx}]b!g
                                  !g # Consecutive differences as Z
[                               ]b   # Index of first function that returns true:

 _   }                               #  Index 0: All the same
  e                                  #   Every item in Z
   ¥0                                #   Is 0

      _   }                          #  Index 1: Increasing
       e                             #   Every item in Z
        ¥J                           #   Is -1

           _        }                #  Index 2: Pair
            ä+                       #   Consecutive sums of Z
               e[TT]                 #   Is exactly [0,0]

                     _         }     #  Index 3: Palindrome
                      Î              #   The first item in Z
                       ¥  n          #   Is the opposite of
                        ZÌ           #   The last item in Z
                            «Zx      #   And the sum of Z is 0

```
> 1 votes

# Answer
# Charcoal, 70 bytes

```
Ｉ⌕ＥＥ﹪⁺↨⁶⁰↨Ｎ¹⁰⁰…⁰φ¹⁴⁴⁰﹪%03d↨¹⁰⁰↨ι⁶⁰⌕⟦⁼⌊ι⌈ι⬤ι∨¬μ⁼λＩ⊕§ι⊖μ⁼⌊⪪ι²⌈⪪ι²⁼ι⮌ι⟧¹Ｎ

```

Try it online! Link is to verbose version of code. Takes the time as a 3- or 4-digit string (e.g. `2324`) and maps the categories to `0..3` for same, increasing, pair, palindrome. Explanation:

```
⁺↨⁶⁰↨Ｎ¹⁰⁰

```

Convert the input time into a number of minutes since midnight.

```
﹪...…⁰φ¹⁴⁴⁰

```

Create a range of 1000 minutes starting that that time, and wrapping around at midnight if necessary.

```
Ｅ...﹪%03d↨¹⁰⁰↨ι⁶⁰

```

Convert each time into that range back into a 3- or 4-digit string as appropriate.

```
Ｅ...⌕⟦...⟧¹

```

Find the category of each time, given as the index of the first of these expressions that evaluates to true: ...

```
⁼⌊ι⌈ι

```

... all the digits are the same; ...

```
⬤ι∨¬μ⁼λＩ⊕§ι⊖μ

```

... each digit is one more than the previous; ...

```
⁼⌊⪪ι²⌈⪪ι²

```

... the time is composed of two equal pairs; or...

```
⁼ι⮌ι

```

... the time equals its reverse.

```
Ｉ⌕...Ｎ

```

Find the index of the first time in the desired category.
> 1 votes

---
Tags: code-golf, date, pattern-matching
---


title: Triangular honeycomb numbers

text:
# Question
Title: Triangular honeycomb numbers
From the infinite triangular array of positive integers, suppose we repeatedly select all numbers at Euclidean distance of \\$\sqrt{3}\\$, starting from 1:

$$ \underline{1} \\ \\;2\\; \quad \\;3\\; \\ \\;4\\; \quad \\;\underline{5}\\; \quad \\;6\\; \\ \\;\underline{7}\\; \quad \\;8\\; \quad \\;9\\; \quad \underline{10} \\ 11 \quad 12 \quad \underline{13} \quad 14 \quad 15 \\ 16 \quad \underline{17} \quad 18 \quad 19 \quad \underline{20} \quad 21 \\ \underline{22} \quad 23 \quad 24 \quad \underline{25} \quad 26 \quad 27 \quad \underline{28} \\ \cdots $$

Alternatively, you may think of it as "leave centers of a honeycomb pattern and cross out boundaries".

The resulting sequence (not yet on OEIS, unlike the polkadot numbers) is as follows:

```
1, 5, 7, 10, 13, 17, 20, 22, 25, 28, 31, 34, 38, 41, 44, 46, 49, 52, 55, 58, 61, 64,
68, 71, 74, 77, 79, 82, 85, 88, 91, 94, 97, 100, 103, 107, 110, 113, 116, 119,
121, 124, 127, 130, 133, 136, 139, 142, 145, 148, 151, 155, 158, 161, 164, 167, 170,
172, 175, 178, 181, 184, 187, 190, ...

```

The task is to output this sequence.

I/O rules apply. You can choose to implement one of the following:

* Given the index \\$n\\$ (0- or 1-based), output the \\$n\\$th term of the sequence.
* Given a positive integer \\$n\\$, output the first \\$n\\$ terms of the sequence.
* Take no input and output the entire sequence by
    + printing infinitely or
    + returning a lazy list or a generator.

Standard rules apply. The shortest code in bytes wins.

# Answer
# Python, 34 bytes

Takes as input an integer \\$ n \\$, and outputs the \\$ n \\$-th term of the sequence (0-indexed).

```
lambda n:3*n-~((n*24+1)**.5%6%5<1)

```

Try it online!

### Python 3, 43 bytes

Outputs the sequence forever.

```
n=1
while[print(n//8-~(n**.5%6%5<1))]:n+=24

```

Try it online!
> 10 votes

# Answer
# Haskell, 45 bytes

-2 bytes thanks to @Grain Ghost.

```
[sum[0..n]+k|n<-[0..],k<-[0..n],mod(n+k)3==1]

```

Attempt This Online!
> 4 votes

# Answer
# JavaScript (V8), 55 bytes

Prints the sequence forever.

```
for(n=i=1;;i++)for(j=0;j<=i*3;n+=3+!j-(j++==i))print(n)

```

Try it online!
> 3 votes

# Answer
# Charcoal, ~~24~~ 17 bytes

```
Ｉ…⌕Ａ⭆⊕θ⭆⊕ι﹪⁺ιλ³1Ｎ

```

Try it online! Link is to verbose version of code. Outputs the first `n` terms. Explanation: Now a port of @JonathanAllan's Jelly answer, but taking some inspiration from @Steffan's Vyxal answer to save a byte.

```
      θ             Input `n`
     ⊕              Incremented
    ⭆               Map over implicit range and join
         ι          Current value
        ⊕           Incremented
       ⭆            Map over implicit range and join
            ι       Outer value
           ⁺        Plus
             λ      Inner value
          ﹪         Modulo
              ³     Literal integer 3
  ⌕Ａ                Find all indices of
               1    Literal string `1`
 …                  Truncated to length
                Ｎ   Input `n` as an integer
Ｉ                   Cast to string
                    Implicitly print

```
> 3 votes

# Answer
# Vyxal, 10 bytes

```
Þ::ʀ+3ḊfT›

```

Try it Online!

Outputs the infinite sequence.

-6 bytes (compared to my previous answer below) thanks to porting @Jonathan Allan's Jelly answer, so make sure to upvote that!

```
Þ::ʀ+3ḊfT›
Þ:         # Push an infinite list of non-negative integers
  :        # Duplicate
   ʀ+      # For each n in this list, add n to each item in a range [0..n]. This produces an infinite list like [[0], [1, 2], [2, 3, 4], [3, 4, 5, 6], ...]
     3Ḋ    # For each inner item, is it divisible by three?
       f   # Flatten
        T  # Get truthy (0-based) indices
         › # Increment

```

Previously:

## Vyxal, 16 bytes

```
Þ∞ƛʀ+'ǒ1=;nɽ∑+;f

```

Try it Online!

Outputs the infinite sequence.

```
Þ∞ƛʀ+'ǒ1=;nɽ∑+;f
Þ∞ƛ               # Map n over positive integers:
   ʀ+             #  For each in [0..n], add n
     '            #  Filter for:
      ǒ           #   Modulo 3
       1=         #   Equals one?
         ;        #  Close filter
          nɽ∑+    #  For each, add the sum of [0..n-1]
              ;   # Close map
               f  # Flatten

```

# Vyxal, 12 bytes

```
24*›√6%₅$T+›

```

Try it Online!

Outputs the \\$n\\$th element of the sequence. Port of @dingledooper's answer, so uvpote that!

```
24*›√6%₅$T+›
24*          # Multiply the input by 24
   ›         # Increment
    √        # Square root
     6%      # Modulo 6
       ₅     # Is it divisible by 5? (Returns 1 or 0)
        $T+  # Add input * 3
           › # Increment

```
> 2 votes

# Answer
# Ruby, ~~35~~ ~~30~~ 29 bytes

-5 bytes thanks to Sʨɠɠan
-1 byte thanks to G B

Returns `n`th item of the sequence. Same technique as Python and Vyxal answers; give them upvotes.

```
->n{3*n-~33[(n*24+1)**0.5%6]}

```

Attempt This Online!
> 2 votes

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

Ports of *@Sʨɠɠan*'s Vyxal answers, where the first is a port of *@JonathanAllan*'s Jelly and the second is a port of *@dingledooper*'s Python answer, so make sure to upvote them as well!

Given no input, it'll output the infinite sequence as list (**11 bytes**):

```
∞<DÝ+˜3Öƶ0K

```

Try it online.

Given \\$n\\$, it'll output the 0-based \\$n^{th}\\$ term (**12 bytes**)

```
Ð$24*>t6%5ÖO

```

Try it online or verify the first 25 items.

**Explanation:**

```
∞             # Push an infinite list of positive integers: [1,2,3,...]
 <            # Decrease each by 1 to make it non-negative: [0,1,2,...]
  D           # Duplicate this infinite list
   Ý          # Map each to a [0,val]-ranged list in the copy
    +         # Add the values of the lists at the same positions together
     ˜        # Flatten this list of lists
      3Ö      # Check for each integer whether it's divisible by 3
        ƶ     # Multiply each check by its 1-based index
         0K   # And then remove all 0s (the falsey checks)
              # (after which the infinite list is output implicitly as result)

```

```
Ð             # Triplicate the (implicit) input-integer
 $            # Push 1 and the input-integer yet again
  24*         # Multiply the top input by 24
     >        # Increase it by 1
      t       # Take the square-root of that
       6%     # Modulo-6
         5Ö   # Check if that is divisible by 5
           O  # And then sum all five values on the stack together:
              #  input + input + input + 1 + (sqrt(input*24)%6%5==0)
              # (which is output implicitly as result)

```
> 2 votes

# Answer
# Jelly, 9 bytes

```
ŻrḤ$3ḍFTḣ

```

A monadic Link that accepts a non-negative integer, \\$n\\$, and yields the first \\$n\\$ triangular honeycomb numbers.

**Try it online!**

### How?

The triangle's \\$i^{\text{th}}\\$ row contributes every third element starting with the \\$(3 - (i+1\pmod 3))^{\text{th}}\\$ element...

```
ŻrḤ$3ḍFTḣ - Link: integer, n    e.g. 4
Ż         - zero-range (n)           [ 0,  1,    2,      3,        4]
   $      - last two links as a monad:
  Ḥ       -   double                 [ 0,  2,    4,      6,        8]
 r        -   inclusive range        [[0],[1,2],[2,3,4],[3,4,5,6],[4,5,6,7,8]]
    3     - three                    3
     ḍ    - divides?                 [[1],[0,0],[0,1,0],[1,0,0,1],[0,0,1,0,0]
      F   - flatten                  [ 1,  0,0,  0,1,0,  1,0,0,1,  0,0,1,0,0]
       T  - truthy indices           [ 1,          5,    7,   10,     13    ]
        ḣ - head (to index n)        [1,5,7,10]

```
> 2 votes

# Answer
# MathGolf, 12 bytes

```
M*)√6%5%┬ΓΣ)

```

Port of *@dingledooper*'s Python answer.
Given \\$n\\$, it'll output the 0-based \\$n^{th}\\$ term.

Try it online.

Unfortunately `÷` (*is divisible by* builtin) is incorrectly implemented and doesn't support a float argument, otherwise the `5%┬` could have been  for -1 byte.

**Explanation:**

```
M*            # Multiply the (implicit) input-integer by 24
  )           # Increase it by 1
   √          # Take the square-root of that
    6%        # Modulo-6
      5%┬     # Check if it's divisible by 5:
      5%      #  Modulo-5
        ┬     #  Check if it's equal to 0.0
         Γ    # Wrap the top four values into a list
              # (which uses the implicit input three times)
          Σ   # Sum this list together
           )  # Increase it by 1
              # (after which the entire stack is output implicitly as result)

```
> 1 votes

# Answer
# Nibbles, 8.5 bytes (17 nibbles)

```
`?+.,~.+$,$%$3 2

```

Somewhat modified port of Jonathan Allan's Jelly answer: upvote that.
Outputs the infinite sequence.

```
`?+.,~.+$,$%$3 2
    ,~              # 1..infinity
   .                # map over each n
         ,$         #   1..n
       +$           #   add n
      .    %$3      #   each modulo 3
  +                 # now flatten this list-of-lists
`?                  # and get indices of
               2    # all elments equal to 2

```
> 1 votes

# Answer
# C (clang), 59 bytes

```
j,i;main(x){for(;i%3||printf("%d ",x);i=++i>j*2?++j:i)++x;}

```

Try it online!

Full program.

Iterate x=\[1..\] combined with growing series *i..* of lines of the pyramid where starting value *j* increases by one.
When *i%3 == 0* prints *x*

```
0 12 234 3456 45678 56789..
1 ..  5..7.10..13,  17, 20

```
> 0 votes

# Answer
# Haskell, 43 bytes

```
[y-x+sum[1..x]|x<-[1..],y<-[1,4..x*2],y>=x]

```

Try it online!

Using similar approach of my C answer
> 0 votes

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


title: What is the longest trampoline?

text:
# Question
Title: What is the longest trampoline?
In this challenge we are going to consider lists of integers such that for every member \\$x\\$ at index \\$i\\$ then the indexes \\$i+x\\$ and \\$i-x\\$ have the value \\$x+1\\$ or are out of bounds for the list. We will call these trampoline lists.

If we play around with these for a while we can notice that if we start a list with a certain value there is a limit on how long the list can be. For example let's start with `3` at the first value.

```
[3,...

```

Now we want to make this as long as possible. If we make it 4 long or longer we know the 4th value has to be `4`.

```
[3,?,?,4,...

```

That tells us that the 8th value (if it exists) has to be `5`

```
[3,?,?,4,?,?,?,5,...

```

That tells us the value at 3 is `6`

```
[3,?,6,4,?,?,?,5,...

```

Which tells us the value at 9 is `7`

```
[3,?,6,4,?,?,?,5,7,...

```

Which tells us the value at 2 is `8`

```
[3,8,6,4,?,?,?,5,7,...

```

Which tells us the value at 10 is `9`

```
[3,8,6,4,?,?,?,5,7,9...

```

Which tells us the value at 1 is `10`. But we already filled in that as `3`. So there can't be a 10th value otherwise things break down. The longest it can ever be is 9. That tells us that the maximal trampoline list starting with 3 looks like:

```
[3,8,6,4,?,?,?,5,7]

```

Where the `?`s can take on multiple values.

# Task

Given a postive integer \\$n\\$ as input output a maximal valid trampoline list starting with \\$n\\$.

This is a challenge, see the tag wiki for a description on defaults for IO. This challenge follows the defaults there.

This is so the goal is to minimize the size of your program's source code as measured in bytes.

# Test cases

In the first column we have the input. In the second we have a template with `?`s where there are multiple possible correct outputs. In the last we have an example of a correct output for the given input.

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

```

If your answer matches the template *and* is a valid trampoline list it is correct. You should not output the template itself.

# Answer
> 7 votes
# Jelly,  ~~15~~  14 bytes

```
×3Ṗ+×ɗRṚ;$m2;@

```

A monadic Link that accepts a positive integer and yields a longest trampoline as a list of positive integers.

**Try it online!**

### How?

Trampolines are \\$3n\\$ long, start with \\$n\\$ and are then filled at the leftmost then rightmost available slots starting at \\$3n-1\\$ descending until \\$n\\$ slots are left, which need filling with numbers that will go out of bounds in both directions.

i.e. the template is:

```
[n, 3n-1, 3n-3, ..., <n ?'s>, ..., 3n-4, 3n-2]

```

The code starts with a list from \\$1\\$ to \\$3n-1\\$ and adds \\$3ni\\$ to the entries at indices \\$i\leq n\\$ (the ones that will end up at the `?`s in the template). It then prefixes this with its reverse, appends the forward version, discards every other element, and prefixes with \\$n\\$ to give a trampoline.

```
×3Ṗ+×ɗRṚ;$m2;@ - Link: integer, n       e.g. 3
×3             - multiply (n) by three       9
      R        - range (n)                   [1,2,3]
     ɗ         - last three links as a dyad:
  Ṗ            -   pop (3n)                  [1,2,3,4,5,6,7,8]
    ×          -   (3n) multiply (range n)   [9,18,27]
   +           -   add                       [10,20,30,4,5,6,7,8]
         $     - last two links as a monad:
       Ṛ       -   reverse                   [8,7,6,5,4,30,20,10]
        ;      -   concatenate               [8,7,6,5,4,30,20,10,10,20,30,4,5,6,7,8]
           2   -   two
          m    -   modulo slice              [8,  6,  4,   20,   10,   30,  5,  7]
             @ - with swapped arguments:
            ;  -   (n) concatenate           [3,8,6,4,20,10,30,5,7]

```

# Answer
> 4 votes
# JavaScript (ES6), 70 bytes

```
f=(n,i=(a=Array(w=n*3).fill(w),0))=>a[i]?f(n+1,i-n,f(n+1,i+=a[i]=n)):a

```

Try it online!

### Commented

```
f = (            // f is a recursive function taking:
  n,             //   n = input
  i = (          //   i = position, initialized to 0
    a = Array(   //   build an array a[]
      w = n * 3  //   of w = n * 3 entries
    ).fill(w),   //   filled with w
    0            //
  )              //
) =>             //
a[i] ?           // if we're not out of bounds:
  f(             //   do a recursive call:
    n + 1,       //     use n + 1 as the value
    i - n,       //     use i - n as the position
    f(           //     do another recursive call:
      n + 1,     //       use n + 1 as the value
      i +=       //       use i + n as the position
        a[i] = n //       and set a[i] to n
    )            //     end of recursive call
  )              //   end of recursive call
:                // else:
  a              //   return a[]

```

# Answer
> 0 votes
# Python, 100 bytes

```
def g(a,n,i):
 if len(a)>i>=0:g(a,n+1,i+n);a[i]=n;g(a,n+1,i-n)
def f(n):g(a:=[3*n]*3*n,n,0);print(a)

```

Attempt This Online!

Uses the same recursive concept as Arnauld's answer.

# Answer
> 0 votes
# 05AB1E, 14 bytes

```
4*ŸI·._¦ÂìιнI†

```

Inspired by *@JonathanAllan*'s Jelly answer.

Try it online or verify all test cases.

**Explanation:**

```
                #  example input: 3
4*              # Multiply the (implicit) input by 4
                #  STACK: 12
  Ÿ             # Pop and push a list in the range [(implicit) input, 4*input]
                #  STACK: [3,4,5,6,7,8,9,10,11,12]
   I·           # Push the input doubled
                #  STACK: [3,4,5,6,7,8,9,10,11,12],6
     ._         # Rotate the list that many times towards the left
                #  STACK: [9,10,11,12,3,4,5,6,7,8]
       ¦        # Remove the first value
                #  STACK: [10,11,12,3,4,5,6,7,8]
        Â       # Bifurcate it; shorter for Duplicate & Reverse copy
                #  STACK: [10,11,12,3,4,5,6,7,8],[8,7,6,5,4,3,12,11,10]
         ì      # Prepend the second list to the first
                #  STACK: [8,7,6,5,4,3,12,11,10,10,11,12,3,4,5,6,7,8]
          ι     # Uninterleave it into two parts
                #  STACK: [[8,6,4,12,10,11,3,5,7],[7,5,3,11,12,10,4,6,8]]
           н    # Pop and only leave the first inner list
                #  STACK: [8,6,4,12,10,11,3,5,7]
            I†  # Filter the input to the front of the list
                #  STACK: [3,8,6,4,12,10,11,5,7]
                # (after which the result is output implicitly)

```

# Answer
> 0 votes
# Charcoal, 27 bytes

```
Ｎθ≔Ｅθ⁺θ⊗ιηＩ⁺⁺⮌⊞Ｏ⊕ηθＥθ×³θ✂η¹

```

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

```
Ｎθ

```

Input `n`.

```
≔Ｅθ⁺θ⊗ιη

```

Create a range from `n` to `3n-2` in steps of 2.

```
Ｉ⁺⁺⮌⊞Ｏ⊕ηθＥθ×³θ✂η¹

```

Increment that range (giving `n+1`, `n+3`, ... `3n-1`), append `n`, reverse the result (giving `n`, `3n-1`, `3n-3`, ... `n+1`), append `n` copies of `3n`, then append the range excluding the first element. This outputs `n`, `3n-1`, `3n-3`, ... `n+1`, `3n`, ... `3n`, `n+2`, ... `3n-2` as desired.

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