# Question
Title: Java is to JavaScript as Car is to Carpet
Title ~~stolen~~ inspired by Greg Hewgill's answer to What's the difference between JavaScript and Java?

# Introduction

Java and JavaScript are commonly used languages among programmers, and are currently the most popular tags on Stack Overflow. Yet aside from similar names, the two have almost nothing in common.

In honor of one of programming's most infamous debates, and inspired by my recent frustrations in tag searching, I propose the following:

# Challenge

Write a program which takes in a string as input. Return `car` if the string begins with "Java" and *does not* include "JavaScript". Otherwise, return `carpet`.

# Example Input and Output

### car:

```
java
javafx
javabeans
java-stream
java-script
java-8
java.util.scanner
java-avascript
JAVA-SCRIPTING
javacarpet

```

### carpet:

```
javascript
javascript-events
facebook-javascript-sdk
javajavascript
jquery
python
rx-java
java-api-for-javascript
not-java
JAVASCRIPTING

```

# Notes

* Input matching should be case insensitive
* Only possibilities for output should be `car` or `carpet`
* Imaginary bonus points if your answer uses Java, JavaScript, or Regex
* Alternate Title: *Java is to JavaScript as ham is to hamster*

# Answer
# Java/JavaScript Polyglot, ~~108~~ ~~107~~ 106 bytes

```
//\u000As->s.matches("(?i)(?!.*javascript)java.*"/*
a=>/(?!.*javascript)^java/i.test(a/**/)?"car":"carpet"

```

## Run as Java

```
//\u000As->s.matches("(?i)(?!.*javascript)java.*"/*
a=>/(?!.*javascript)^java/i.test(a/**/)?"car":"carpet"

```

Try it online!

Note: don't trust the highlight as it's incorrect. The real Java, properly interpreted looks like below because `\u000A` is interpreted in the very first step of the compilation as `\n`, de facto ending the comment that started with the line comment (`//`).

```
//
s->s.matches("(?i)(?!.*javascript)java.*"/*
a=>/(?!.*javascript)^java/i.test(a/**/)?"car":"carpet"

```

## Run as JavaScript

```
//\u000As->s.matches("(?i)(?!.*javascript)java.*"/*
a=>/(?!.*javascript)^java/i.test(a/**/)?"car":"carpet"

```

Credits to @CowsQuak for the JS version.

```
let f=

//\u000As->s.matches("(?i)(?!.*javascript)java.*"/*
a=>/(?!.*javascript)^java/i.test(a/**/)?"car":"carpet"

var a=["java","javafx","javabeans","java-stream","java-script","java-8","java.util.scanner","javascript","java-avascript","javascript-events","facebook-javascript-sdk","javajavascript","jquery","python","rx-java","java-api-for-javascript","not-java"];

for(var s of a) console.log(s.padStart(a.reduce((x,y)=>x.length>y.length?x:y).length) + "=>" + f(s));
```

How many imaginary bonus points for this answer?

-1 byte thanks to @Nevay in the Java answer.
> 109 votes

# Answer
# JavaScript, ~~50~~ 49 bytes

*Saved 1 byte thanks to @ValueInk by rearranging the regex*

```
a=>/javascript|^(?!java)/i.test(a)?"car":"carpet"

```

### Test snippet

```
let f=

a=>/javascript|^(?!java)/i.test(a)?"carpet":"car"

var a=["java","javafx","javabeans","java-stream","java-script","java-8","java.util.scanner","java-avascript","javascript","javascript-events","facebook-javascript-sdk","javajavascript","jquery","python","rx-java","java-api-for-javascript","not-java"];

for(var s of a) console.log(s.padStart(a.reduce((x,y)=>x.length>y.length?x:y).length) + "=>" + f(s));
```
> 18 votes

# Answer
# Java (OpenJDK 8), ~~92~~ ~~82~~ ~~72~~ ~~58~~ 57 bytes

```
s->s.matches("(?i)(?!.*javascript)java.*")?"car":"carpet"

```

Try it online!

1 byte saved thanks to @Nevay!
> 15 votes

# Answer
# C (only calling puts), 131 bytes

```
f(int*s){char r[]="carpet";~*s&'AVAJ'||(r[3]=0);for(;*s&255;*(int*)&s+=1)~*s&'AVAJ'||~s[1]&'IRCS'||~s[2]&'TP'||(r[3]='p');puts(r);}

```

It does have its problems, but it passes all of the testcases provided :)

```
g(int* s)
{
  char r[] = "carpet";
  ~*s&'AVAJ' || (r[3]=0);
  for(;*s & 255; *(int*)&s +=1)
    ~*s&'AVAJ' || ~s[1]&'IRCS' || ~s[2]&'TP' || (r[3]='p');
  puts(r);
}

```

> Imaginary bonus points if your answer uses Java, Javascript, or Regex

well... no thanks
> 11 votes

# Answer
# Python 2, 68 bytes

```
k=input().lower();print'car'+'pet'*(k[:4]!='java'or'javascript'in k)

```

Try it online!

-11 bytes thanks to notjagan
-2 bytes thanks to Dennis
> 8 votes

# Answer
# 05AB1E, 21 bytes

```
lD'¦‚å≠sη'îáå*„¾„ƒ´#è

```

Try it online!
> 8 votes

# Answer
# C#, ~~80~~ 78 bytes

```
s=>(s=s.ToLower()).StartsWith("java")&!s.Contains("javascript")?"car":"carpet"

```
> 4 votes

# Answer
# ~~EXCEL~~ Google Sheets, ~~89~~ 86 Bytes

Saved 3 bytes thanks to Taylor Scott

```
=LEFT("carpet",6-3*ISERR(SEARCH("javascript",A1))+3*ISERR(IF(SEARCH("java",A1)=1,1,1/0

```

Takes an input on A1

### Explanation

```
=LEFT("carpet",6-3*ISERR(SEARCH("javascript",A1))+3*ISERR(IF(SEARCH("java",A1)=1,1,1/0)))

 SEARCH("javascript",A1)        #Case-Insensitive Find, returns error if not found
 ISERR(                         #Returns string true if error, False if not
 3*ISERR(                       #Forces TRUE/False as integer, multiplies by 3
 IF(SEARCH("java",A1)=1,1,1/0)  #If java found, returns integer. if 1, java begins string
                                #so returns 1, which will be turned into 0 by iserr.
                                #Else returns 1/0, which will be turned into 1 by iserr.
 LEFT(                          #Returns digits from the left, based upon count.

```
> 4 votes

# Answer
# Jelly, 27 bytes

```
,“Ẋṣ“®Ẓȷ»ŒlwÐ€/Ḅn2‘×3“¢Ẹị»ḣ

```

Try it online!
> 4 votes

# Answer
# Common Lisp, ~~131~~ 125 bytes

```
(lambda(s)(format()"car~@[pet~]"(or(<(length s)4)(not(#1=string-equal"java"(subseq s 0 4)))(search"javascript"s :test'#1#))))

```

Try it online!

Size reduced thanks to the #n= “trick” of Common Lisp.

**Explanation**

```
(lambda (s)                 ; anonymous function
  (format                   ; use of format string to produce the result
    ()                      ; the result is a string
    "car~@[pet~]"           ; print "car", then print "pet" when:
    (or (< (length s) 4)    ; the string is less then 4 characters or
        (not (string-equal "java" (subseq s 0 4)))     ; does not start with java or
        (search "javascript" s :test 'string-equal)))) ; contains javascript

```
> 3 votes

# Answer
# Retina,  ~~44~~  37 bytes

```
Ai`^(?!.*javascript)java
.+
pet
^
car

```

*Thanks to @MartinEnder for golfing off 7 bytes!*

Try it online!
> 3 votes

# Answer
# vim, 58 bytes

```
gUU:s/.*JAVASCRIPT.*/Q/g
:s/^JAVA.*/car
:s/[A-Z].*/carpet

```

Try it online!
> 3 votes

# Answer
# Ruby, 42+1 = 43 bytes

Uses the `-p` flag.

```
$_="car#{"pet"if~/javascript|^(?!java)/i}"

```

Try it online!
> 3 votes

# Answer
# C (tcc), ~~144~~ 136 bytes

```
a;f(s){char*t=s;for(;*t;a=!strncmp(s,"java",4))*t=tolower(*t++);for(t=s;*t;)s=strncmp(t++,"javascript",10)&&s;puts(a*s?"car":"carpet");}

```

Try it online!

**Unrolled:**

```
a;
f(s)
{
    char *t = s;
    for (; *t; a = !strncmp(s, "java", 4))
        *t = tolower(*t++);
    for (t=s; *t;)
        s = strncmp(t++, "javascript", 10) && s;
    puts(a*s ? "car"  :"carpet");
}

```
> 2 votes

# Answer
# Python 2, 69 bytes

```
f=input().lower().find
print'car'+'pet'*(f('java')!=~f('javascript'))

```

Currently 1 byte longer than the shortest Python 2 solution.

Try it online!
> 2 votes

# Answer
# Excel VBA, 76 Bytes

Anonymous VBE immediate window function that takes input from range `[A1]` and outputs is `car`/`carpet` status to the VBE immediate window

Does not use RegExp

```
?"car"IIf(InStr(1,[A1],"Java",1)*(InStr(1,[A1],"JavaScript",1)=0),"","pet")

```
> 1 votes

# Answer
# JAISBaL, 36 bytes

```
℠℘(?!.*javascript)^java.*}͵Ucar½Upet

```

Verbose/explanation:

```
# \# enable verbose parsing #\
tolower                           \# [0] convert the top value of the stack to lowercase #\
split (?!.*javascript)^java.*}    \# [1] split the top value of the stack by (?!.*javascript)^java.*} #\
arraylength                       \# [2] push the length of the array onto the stack #\
print3 car                        \# [3] print car #\
!if                               \# [4] if the top value on the stack is falsy, skip the next statement #\
print3 pet                        \# [5] print pet #\

```

JAISBaL was my first attempt at designing a golfing language, so it's rather quirky... there's no matches or contains, regex or otherwise, so instead we have to split and check the resulting array length... because JAISBaL has a split-by-regex... but no other regex support.... because reasons.

Regex ~~stolen~~ borrowed from @Cows Quack's answer.
> 1 votes

# Answer
# Excel, 84 bytes

```
="car"&IF(AND(ISERR(SEARCH("javascript",A1)),IFERROR(SEARCH("java",A1),2)=1),,"pet")

```
> 1 votes

# Answer
# Python 3, 95 bytes

```
g=lambda s:(lambda r:'car' if r[:4]=='java' and 'javascript' not in r else 'carpet')(s.lower())

```

Try it online!

Yeah, it could be shorter but I wanted to try using a nested lambda!
> 1 votes

# Answer
## Perl, **42 bytes**

I believe the answer by stevieb has an incorrect output (tried that one myself - it returns car for 'javajavascript'). This should work:

```
say/^java/i&&!/javascript/i?'car':'carpet'

```
> 1 votes

# Answer
# Bracmat, 66 bytes

```
(f=.pet:?b&@(low$!arg:(? javascript ?|java ?&:?b|?))&str$(car !b))

```

Try it online!
> 1 votes

# Answer
# Go, 134 bytes

```
import."strings"
func f(s string)string{T,o:=ToLower,"car"
if Contains(T(s),"javascript")||!HasPrefix(T(s),"java"){o+="pet"}
return o}

```

Attempt This Online!
> 1 votes

# Answer
# GolfScript, ~~53~~ ~~49~~ 44 bytes

```
{32|}%"java"/(,\{6<"script"=+}/"carpet".3<if

```

Try it online!

This was my second GolfScript submission so after writing a couple more I was able to revisit this and shave a couple bytes.

Previously, this mapped over a list, then summed it, then added it to a base value. Now, it just loops over the list, adding to the base value on each iteration.

Here's an explanation of how the code works:

```
{32|}%           # Convert the string to lowercase

"java"/          # Split on "java".
(,               # Extract the first item, and push its length
                 # (0 iff string starts with java).
\                # Swap so the rest of the list is on top of the stack.

{6<"script"=+}/  # Check if any start with "script":
{            }/  #   Loop over each item:
 6<              #     Take the first 6 characters.
   "script"=     #     Are they equal to "script"? (0 or 1)
            +    #     Add this to the top of the stack.

# After this loop, the stack will be 0 iff the string started
# with "java" and does not contain "javascript".

"carpet".3<     # Push "carpet" and its first 3 characters.
if              # If the value is 0, "car", otherwise "carpet".

```
> 1 votes

# Answer
# Lua, 88 bytes

```
s=io.read():lower()print(s:sub(1,4)=='java'and not s:find'javascript'and'car'or'carpet')

```

Attempt This Online!
> 1 votes

# Answer
# Mathematica, 82 bytes

regex

```
If[#~StringMatchQ~RegularExpression@"(?i)(?!.*javascript)^java.*","Car","Carpet"]&

```
> 0 votes

# Answer
# Perl, ~~98~~ ~~84~~ 62 Bytes

```
sub a{"car".($_[0]=~/javascript/i||$_[0]!~/^java/i?'pet':'');}

```

Try it online!

Thanks to bytepusher
> 0 votes

# Answer
## Batch, 91 bytes

```
@set/ps=
@set t=%s:~0,4%
@if "%t:java=%%s:javascript=%"=="%s%" (echo car)else echo carpet

```

Takes input on STDIN. Batch doesn't have a case insensitive comparison operator but it does have case insensitive string replacement so I can assign a temporary to the first four characters and then case insensitively replace java, which should then result in the empty string. Meanwhile I case insensitively replace javascript in the original string, which should leave it unchanged.
> 0 votes

# Answer
# Lua, 96 bytes

```
function(x)return x:lower():match"^java"and not x:lower():match"javascript"and"car"or"carpet"end

```
> 0 votes

# Answer
# Dart VM, ~~104 bytes~~ 102 bytes

```
main(p){p=p[0].toLowerCase();print("car${p.indexOf('java')==0&&p.indexOf('javascript')<0?'':'pet'}");}

```

**Explanation**:

Degolfed:

```
main(p)
{
    p = p[0].toLowerCase();
    print("car${p.indexOf('java') == 0 && p.indexOf('javascript') < 0 ? '' : 'pet'}");
}

```

We have our usual main function

We replace `p` with `p[0].toLowerCase();` so that we don't have to declare a new variable (`var` plus a space would be 4 extra bytes)

We then proceed to do the actual printing

We print `car` unconditionally and we use inline statements for checking whether to print `pet` after it or not. If it has the string 'java' at index 0 and does not have 'javascript' in it, we do nothing (we actually append an empty string but it does not have any effect) and otherwise we append `pet`.
> 0 votes

# Answer
# Rust, 97 bytes

```
let s=if Regex::new(r"^javascript|^!java$").unwrap().is_match("javascript"){"carpet"}else{"car"};

```

I'm pretty sure that there is a shorter solution but it's my first try :)
> 0 votes

# Answer
# PowerShell, 81 bytes

```
$a={param($s)$s.StartsWith('java')-and(!s.contains('javascript'))?'car':'carpet'}

```

Try it online!
> 0 votes

# Answer
# Perl 5 `-p`, 38 + 1 = 39 bytes

```
$_=car.pet x!(/^java/i*!/javascript/i)

```

Try it online!
> 0 votes

# Answer
# Perl, 36 bytes

```
say/^java(?!script)/i?"car":"carpet"

```

Run it as such:

```
perl -nE 'say/^java(?!script)/i?"car":"carpet"' java.txt

```
> -1 votes

---
Tags: code-golf, string, decision-problem, pattern-matching
---


title: Orthodiagonal steps

text:
# Question
Title: Orthodiagonal steps
It's a common problem to navigate in a 2D matrix. We've seen it many times and will see again. So let's help future us and develop the shortest solutions to generate all eight possible steps in a 2D matrix.

## Challenge

Your code must output the following 8 pairs of -1,0,1 in any order:

```
(0,1)
(0,-1)
(1,0)
(-1,0)
(1,1)
(1,-1)
(-1,1)
(-1,-1)

```

## Rules

1. There is no input.
2. Output order is not relevant
3. Output is flexible. Pairs of numbers just need to be distinguishable
4. This is , so shortest answer in bytes wins

# Answer
# Octave, 24 bytes

```
dec2base([0:3,5:8],3)-49

```

Try it online!

I haven't seen this approach yet.

Creates a list of integers `[0, 1, 2, 3, 5, 6, 7, 8]`, and converts it to ternary, returning a character array:

```
00
01
02
10
12
20
21
22

```

Subtracting `49` (ASCII-value for `1`) from all characters gives a numeric array:

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

```
> 20 votes

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

```
a=({0,-1,1},{0,-1,1})
echo ${a[@]:1}

```

Try it online!

---

# Bash with Sed, 35

```
printf %s\\n {-1..1},{-1..1}|sed 5d

```

Try it online!
> 9 votes

# Answer
# T-SQL, ~~80~~ 78 bytes

```
SELECT-1n INTO t;INSERT t VALUES(0),(1)SELECT*FROM t,t z WHERE t.n<>0OR z.n<>0

```

Creates a (permanent) table **t** containing `(-1,0,1)`, and performs a self-join with a `WHERE` clause that excludes the `0,0` row. The table **t** is not cleaned up by my code, you must drop it yourself.

Sadly nearly twice as long as the boring solution (**44 bytes**), since SQL allows returns in strings:

```
PRINT'0,1
0,-1
1,0
-1,0
1,1
1,-1
-1,1
-1,-1'

```
> 9 votes

# Answer
# , ~~26~~ 24 bytes

Credits to @JDoe for saving two more bytes with a direct approach:

```
paste(-1:1,-3:5%/%3)[-5]

```

Try it online!

The original asnwer:

```
outer(-1:1,-1:1,paste)[-5]

```

Try it online!

Or for 27 bytes

```
sapply(-1:1,paste,-1:1)[-5]

```

Try it online!

Or for 34 bytes with factors:

```
(gl(3,3,,-1:1):gl(3,1,9,-1:1))[-5]

```

Try it online!

This last solution might be the golfiest if the output could be from 1 to 3 rather than from -1 to 1.

See the other R answer for alternate solutions with `expand.grid` or with `cbind`.
> 7 votes

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

```
3p_2ẸƇ

```

Try it online!

My first ever Jelly answer! Much thanks to Dennis for the final piece of the puzzle.

Now, let's see if I can explain it ... lol.

```
3p_2ẸƇ   Main program, takes no input.
3p       Product with Range 3, yields [[1,1], [1,2], [1,3], [2,1], [2,2], ...]
  _2     Decrement twice, vectorizes, yields [[-1,-1], [-1,0], [-1,1], [0,-1], ...]
    ẸƇ   Comb, removes those that contain only falsey values, the [0,0]
         Implicit output

```

*-1 byte thanks to Erik; -1 byte thanks to Mr Xcoder and Dennis*
> 7 votes

# Answer
# Python 2, 33 bytes

```
i=9;exec"print-i%3-1,i/5;i-=2;"*8

```

Try it online!

Dennis saved ~~3~~ 5 bytes, wow. Thanks!
> 7 votes

# Answer
# Haskell, 22 bytes

```
_:l=mapM(:[1,-1])[0,0]

```

Try it online!

*Laikoni saved 1 byte.*
> 7 votes

# Answer
# Japt `-Q`, ~~15~~ 13 bytes

I'm sure there's a shorter way, but I liked this approach.

```
##ü80ì3 mÉ ò
##ü80        // Take 14425280
     ì3      // and turn it into an array of base-3 numbers.
        mÉ   // Subtract one from each digit
           ò // and then split them pairwise.

```

Shaved off two bytes thanks to Shaggy.

Try it online!
> 6 votes

# Answer
# Japt, ~~13~~ ~~12~~ 11 bytes

*Saved a byte thanks to @Shaggy*

```
9ó8_ìJõ é)Å

```

Try it online! Uses `-R` flag to put each item on its own line.

### Explanation

```
9ó8_ìJõ é)Å
9ó8             Create the range [9, 9+8). [9, 10, ..., 16]
   _            Map each item in this range through this function:
     Jõ é)        Generate the range [-1...1] and rotate to get [1, -1, 0].
    ì             Convert the item to an array of base-3 digits,
                  mapping [0,1,2] to [1,-1,0]. [[-1, 1, 1], [-1, 1,-1], [-1, 1, 0],
                                                [-1,-1, 1], [-1,-1,-1], [-1,-1, 0],
                                                [-1, 0, 1], [-1, 0,-1]]
          Å       Remove the first item (gets rid of the leading -1).

```
> 6 votes

# Answer
# Java 8, ~~83~~ 42 bytes

```
v->"1,1 1,0 1,-1 0,1 0,-1 -1,1 -1,0 -1,-1"

```

-41 bytes thanks to *@AdmBorkBork* by hard-coding..

Try it online.

---

Non hard-coded version as reference (**~~83~~ ~~72~~ ~~70~~ 68 bytes**):

```
v->{for(int i=9;i-->1;)System.out.println(~i%3+1+","+(~(i/3)%3+1));}

```

-11 bytes thanks to *@OlivierGrégoire*.
-2 bytes creating a port of *@ETHproductions*'s JavaScript (ES6) answer.

Try it online.
> 5 votes

# Answer
# Perl 6, 23 bytes

```
{(1,-1,0 X 1,-1,0)[^8]}

```

Try it online!
> 5 votes

# Answer
# 05AB1E, ~~8~~ 7 bytes

```
2Ý<ãʒĀZ

```

Try it online!

**Explanation**

```
2Ý<     # Range of 2 decremented, yields [-1, 0, 1]
   ã    # Cartesian product of the list with itself
    ʒ   # Filter by ...
     ĀZ # Maximum of the truthified values, yields 0 only if both values are 0.

```

-1 byte thanks to Emigna !
> 5 votes

# Answer
# Husk, ~~7~~ 6 bytes

There are a lot of different ways (the tricky/costly part is getting rid of `[0,0]`), ~~7 bytes is the shortest I could come up~~ thanks to Leo for pointing out to use decimal conversion (`d`) as a filter:

```
fdπ2ṡ1

```

Try it online!

### Explanation

```
fdπ2ṡ1  -- constant function (expects no arguments)
    ṡ1  -- symmetric range [-n..n]: [-1,0,1]
  π2    -- cartesian power of 2: [[-1,-1],[-1,0],[0,-1],[-1,1],[0,0],[1,-1],[0,1],[1,0],[1,1]]
f       -- filter only elements that are truthy when
 d      -- | decimal conversion (interpret as polynomial and evaluate at x=10)
        -- : [[-1,-1],[-1,0],[0,-1],[-1,1],[1,-1],[0,1],[1,0],[1,1]]

```

---

## Alternative, 7 bytes

```
tπ2ṙ1ṡ1

```

Try it online!

### Explanation

```
tπ2ṙ1ṡ1  -- constant function (expects no arguments)
     ṡ1  -- symmetric range [-n..n]: [-1,0,1]
   ṙ1    -- rotate by 1: [0,1,-1]
 π2      -- cartesian power of 2: [[0,0],[0,1],[1,0],[0,-1],[1,1],[-1,0],[1,-1],[-1,1],[-1,-1]]
t        -- tail: [[0,1],[1,0],[0,-1],[1,1],[-1,0],[1,-1],[-1,1],[-1,-1]]

```
> 5 votes

# Answer
# MATL, 12 bytes

```
9:q4X-3YA49-

```

Try it online!

Because it's MATL month, here's a MATL port of @Stewie's Octave answer. The sequence \[0 1 2 3 5 6 7 8\] is generated as the set difference between \[0 ... 8\] and 4.
> 5 votes

# Answer
# , 27 bytes

```
expand.grid(-1:1,-1:1)[-5,]

```

Try it online!

30 and 35 bytes:

```
cbind(-1:1,rep(-1:1,e=3))[-5,]
expand.grid(rep(list(-1:1),2))[-5,]

```
> 4 votes

# Answer
# Haskell, ~~28~~ 27 bytes

```
tail.mapM id$[0,1,-1]<$"ao"

```

Try it online!
> 4 votes

# Answer
# JavaScript (ES6)

Two alternate methods, both longer than hardcoding.

## 49 bytes

```
_=>[...'11202200'].map((n,i,a)=>[~-n,~-a[i+3&7]])

```

Try it online!

## 51 bytes

```
f=(n=1679887e3)=>n?[n%4-1,~-(n/4%4)]+' '+f(n>>4):''

```

Try it online!
> 4 votes

# Answer
# , ~~18~~ 16 bytes

```
echo}.,{;~0 1 _1

```

Try it online!
> 4 votes

# Answer
# PowerShell, 41 bytes

```
(1..-1|%{$i=$_;1..-1|%{"$i,$_"}})-ne'0,0'

```

Try it online!

Double-for loop over the range `1..-1`, with a `-n`ot`e`quals at the end to pull out the extraneous `0,0` entry. They're each individually left on the pipeline and implicit `Write-output` at program completion gives us newlines for free.

---

Sadly, just the barebones string output is two bytes shorter:

```
'1,1
1,0
1,-1
0,1
0,-1
-1,1
-1,0
-1,-1'

```

But that's boring.
> 3 votes

# Answer
## Perl 5, 31 bytes

```
map/1/&&say,<{-1,0,1},{-1,0,1}>

```

Try it online!
> 3 votes

# Answer
# CJam, 13 bytes

```
3,:(2m*{2b},`

```

Try it online!

## Explanation

```
3,    e# Range [0,3):       [0 1 2]
:(    e# Decrement each:    [-1 0 1]
2m*   e# Cartesian square:  [[-1 -1] [-1 0] [-1 1] [0 -1] [0 0] [0 1] [1 -1] [1 0] [1 1]]
{     e# Filter by
 2b   e#   conversion to binary:
},    e#                    [[-1 -1] [-1 0] [-1 1] [0 -1] [0 1] [1 -1] [1 0] [1 1]]
`     e# Stringify:         "[[-1 -1] [-1 0] [-1 1] [0 -1] [0 1] [1 -1] [1 0] [1 1]]"

```
> 3 votes

# Answer
# Python 2, 39 bytes

```
n=6;exec'n+=~(n==2);print n/3,n%3-1;'*8

```

Try it online!
> 3 votes

# Answer
# Haskell, 27 bytes

```
tail$(,)<$>t<*>t
t=[0,1,-1]

```

Try it online!

The output is `[(0,1),(0,-1),(1,0),(1,1),(1,-1),(-1,0),(-1,1),(-1,-1)]`.
> 3 votes

# Answer
# F# (Mono), 54 bytes

```
let f=Seq.where((<>)(0,0))(Seq.allPairs[-1..1][-1..1])

```

Try it online!

44 bytes - thanks to Laikoni:

```
let f=Seq.tail(Seq.allPairs[0;-1;1][0;-1;1])

```
> 3 votes

# Answer
# Befunge-93, 24 bytes

```
11#v91090~9~19~<
9.._@#,

```

Try it online!

I feel like this challenge is missing answers from 2D languages, even if most don't move diagonally. This outputs space separated numbers, each pair separated by tabs.
> 3 votes

# Answer
# Brachylog, 8 bytes

```
Ċ{ṡᵐ≜}ᶠb

```

Try it online!

### Explanation

```
Ċ           Couple: take a list of two elements [A,B]
 {   }ᶠ     Find all…
    ≜         …possible values of…
  ṡᵐ          …signs of A and B
       b    Behead: remove the first one which is [0,0]

```
> 3 votes

# Answer
## Bash, 30 bytes

```
echo "
"{-1..1},{-1..1}|grep 1

```

Try it online!

Prints a trailing space on each line but the last. (Thanks to @Neil \- this originally printed a leading space, but a trailing space is better as per their comment)
> 3 votes

# Answer
# MATL, 12 bytes

```
3:qq2Z^[]5Y(

```

Try it at MATL Online!

My first ever serious MATL answer! Thanks a lot to Luis Mendo, Sanchises and DJMcMayhem for the help.

### How it works

```
3:qq2Z^[]5Y( – Full program. Outputs to STDOUT.
3:           – Range 3. Push [1 2 3] to the stack.
  qq         – Decrement by 2. Yields [-1 0 1].
    2Z^      – Cartesian power of 2.
         5Y( – Replace the row at index 5 with...
       []    – An empty vector.

```
> 3 votes

# Answer
## Batch, 77 bytes

```
@for %%x in (-1 0 1)do @for %%y in (-1 0 1)do @if not %%x%%y==00 echo %%x %%y

```

63 bytes if a nonstandard separator is allowed:

```
@for %%x in (-1/-1 -1/0 -1/1 0/-1 0/1 1/-1 1/0 1/1)do @echo %%x

```
> 2 votes

# Answer
# Jelly, 6 bytes

```
;Ø+p`Ḋ

```

Try it online!

-1 thanks to Dennis.
> 2 votes

# Answer
# Pyth, ~~11~~ 9 bytes

```
t^+U2_1 2

```

Try it here

### Explanation

```
t^+U2_1 2
  +U2_1     [0, 1, -1]
 ^      2   Product with itself.
t           Exclude the first.

```

Equivalently, we could use `t*J+U2_1J`, but that's not any shorter.
> 2 votes

# Answer
# JavaScript (ES6), 45 bytes

```
f=(n=8)=>n?[...f(n-1),[1+~n%3,1+~(n/3)%3]]:[]

```

Try it online!

Another alternative to hardcoding, still not as short though...
> 2 votes

# Answer
# Japt, ~~14~~ 13 bytes

```
[J1T]ê à2 s1J

```

Try it online!
> 2 votes

# Answer
# Stax, 10 bytes

```
τÄêdD┘│çû╢

```

Run and debug it

Explanation (unpacked):

```
1:r2|^{|af|u Full program
1:r          Push [-1, 0, 1]
   2|^       Join with self
   c|*        Alternative: copy and join
      {  f   Filter:
       |a      Any truthy (not 0)?
          |u Representation

```
> 2 votes

# Answer
## PHP, 79, 76, 73 Bytes

76 Bytes thanks to Dom Hastings

Try it online (79 Bytes) using base 16 (**Original answer**)

Try it online (77 Bytes) using base 36

Try it online (73 Bytes) using base 36

**Tried to avoid any kind of loop**

```
<?=strtr(chunk_split(base_convert("18qfremyq6",36,4),3,"
"),[2=>-1,',']);
//as the starting index is 2, next will be 3, no need for 3=>','

```

**Output**

```
1,0
-1,0
1,1
1,-1
-1,1
-1,-1
0,1
0,-1

```

**Explanation**

Basically `"72c75eb6e34e"` `18qfremyq6` is the base 16 36 representation of a base 4 number `130230131132231232031032`, every `3` represents a `","` and `2` a `-1`

Chunk split, adds a line break every 3 characters.

**Shorter with an output without the comma, 79 Bytes**

```
<?=strtr(chunk_split(base_convert("10fcb5c",16,3),2,"
"),[2=>-1]);

```

**Output**

```
10
-10
11
1-1
-11
-1-1
01
0-1

```
> 2 votes

# Answer
# Gaia, 8 bytes

```
3…(¦:×ỵ⁈

```

Try it online!

This generates the list in this order:

```
[[-1 -1] [-1 0] [-1 1] [0 -1] [0 1] [1 -1] [1 0] [1 1]]

```

### Explanation

```
3…(¦:×ỵ⁈ – Full program. Outputs to STDOUT.
3…       – Push [0 1 2] to the stack.
  (¦     – Decrement each; yields [-1 0 1].
    :    – Duplicate.
     ×   – Cartesian product.
       ⁈ – Filter-reject those that:
      ỵ  – Have no truthy element.

```

An alternative to this would be `3…(¦2*ỵ⁈`.
> 2 votes

# Answer
# Japt, ~~9~~ 7 bytes

4 Japt solutions to one challenge; that has to be a first :)

```
Jõ ï fd

```

Test it

---

## Original, 9 bytes

```
4#ô²ìJõ)ò

```

Test it

---

### Explanation

Using the number Nit found for his solution (`14425280`) as a starting point, I converted it to base-3, split it to an array of 2 character strings and then tested each permutation to see if any of them produced a perfect square or cube when rejoined to a string and converted back to base-10. That gave me the perfect squares `15366400`, `18011536` & `18421264` and, of those, only `18011536` had a square root that would allow me to save a byte thanks to Japt's trick of using `#` to build numbers, that being `4244`.

```
4#ô           :4244
   ²          :Square
     Jõ       :Array [-1,0,1]
    ì  )      :Convert to a digit array in that base
        ò     :Split on every second element

```
> 2 votes

# Answer
# Ruby, 40 bytes

```
([*-1..1]*2).permutation(2).uniq-[[0,0]]

```

Try it online!
> 2 votes

# Answer
# brainfuck, 86 bytes

```
+[[<+>->->>---<<<]>]>---.>.<.>.<-.+.>.-.<-.>.+.<.>..<.+.>..<-.>.<+.>.<-.>.-.<.>.<+.>+.

```

Try it online!

Prints pairs of numbers separated by commas.
> 2 votes

# Answer
# K (ngn/k), 15 bytes

```
{(+1-!x#3)^,&x}

```

Try it online!

```
 x:2 / for testing
 x#3 / that many 3s
3 3
 !x#3 / all vectors of 0 1 2 as the columns of a matrix
(0 0 0 1 1 1 2 2 2
 0 1 2 0 1 2 0 1 2)
 +!x#3 / transpose
(0 0
 0 1
 0 2
 1 0
 1 1
 1 2
 2 0
 2 1
 2 2)
 &x / that many 0s
0 0
 (+!x#3)^,&x / remove the all-zero vector
(0 1
 0 2
 1 0
 1 1
 1 2
 2 0
 2 1
 2 2)

```
> 1 votes

# Answer
# Wolfram Language (Mathematica), 29 bytes

```
Print@Rest@Tuples[{0,1,-1},2]

```

Try it online!
> 1 votes

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

```
_=>`1,1
1,0
1,-1
0,1
0,-1
-1,1
-1,0
-1,-1`

```

Try it online!

# Explanation :

Does nothing basically no input and prints the string separated by new lines using string literal.
> 1 votes

# Answer
# Retina, 24 bytes

```
K`_ _
_
_$"0
+0`_
1$%"-1

```

Try it online!
> 1 votes

# Answer
# GolfScript, ~~26~~ ~~19~~ 18 bytes

```
9,[4]-{.3/(\3%(n}/

```

Try it online!

My first GolfScript submission, any help is appreciated! Outputs one element per line, and removes the `0, 0` element.

For nicer printing, I found this 20 byte solution:

```
9,[4]-{[.3/(\3%(]p}%

```

which prints one array per line.
> 1 votes

# Answer
# TI-Basic, 32 bytes

```
For(A,-1,1
For(B,-1,1
If A≠2B
Disp A,B,"
End
End

```

Prints pairs as two lines, separated by empty lines.

TI-Basic is a tokenized language, all tokens used here are one-byte.

Explanation:

```
For(A,-1,1 # First number from -1 to 1 (inclusive)
For(B,-1,1 # Second number from -1 to 1 (inclusive)
If A≠2B    # If the pair is not 0,0
Disp A,B," # Print the first number, then the second, then
           # an empty string (each on its own line)
End        # End second number loop
End        # End first number loop

```

Output

```
-1
-1

-1
0

-1
1

0
-1

0
1

1
-1

1
0

1
1

```
> 1 votes

# Answer
# Yabasic, 49 bytes

An anonymous function that takes no input and outputs to the console.

```
For i=-1To 1
For j=-1To 1
If i Or j?i,j
Next
Next

```

Try it online!

### Output

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

```
> 1 votes

# Answer
# VBA, 66 bytes

An anonymous function that takes no input and outputs to the console.

```
For i=-1To 1:For j=-1To 1:?IIf(i Or j,i &" "&j &vbCr,"");:Next j,i

```

### Output

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

```
> 1 votes

# Answer
# Ruby, 31 bytes

```
p (w=*-1..1).product(w)-[[0,0]]

```

Try it online!
> 1 votes

# Answer
# Julia 0.6, 24 bytes

```
[(A=[0:3;5:8])%3 A÷3]-1

```

Try it online!

Generate `[0,1,2,0,2,0,1,2]` in the first column and `[0,0,0,1,1,2,2,2]` in the second (excluding 4%3 and 4÷3 to avoid `0 0`), then subtract 1 from all the values.

Other methods I tried:

`[(i,j)for i=-1:1,j=-1:1 if i|j!=0]`

`[[s...].-'1'for s=base.(3,[0:3;5:8],2)]` (based on Stewie Griffin's Octave solution)

`[(i,j)for i=-1:1,j=-1:1][(1:9).!=5]`
> 1 votes

# Answer
# JavaScript (Most browsers), ~~42~~ 40 bytes

```
for(x=9;x;)--x-4&&alert([~(-x/3),x%3-1])

```

Only works in DevTools in browsers. As per New users' guides to golfing rules in specific languages this should be valid (Full browser JS program).

### If the one above is anyway considered a snippet, then ~~47~~ 45 bytes:

```
_=>{for(x=9;x;)--x-4&&alert([~(-x/3),x%3-1])}

```
> 1 votes

# Answer
# MathGolf, ~~7~~ 5 bytes

```
1╤╫■╞

```

-2 bytes by porting *@ბიმო*'s second Husk answer, so make sure to upvote him!

Try it online.

**Explanation:**

```
1╤     # Push list [-1,0,1] (push 1; pop and push a list in the range [-n,n])
  ╫    # Rotate it once towards the left: [0,1,-1]
   ■   # Take the cartesian product with itself, creating all possible pairs
    ╞  # Discard the first item of this list (the [0,0] pair)
       # (after which the entire stack joined together is output implicitly)

```
> 1 votes

# Answer
# 05AB1E, 6 bytes

```
T®šã¨

```

Port of *@ბიმო*'s second Husk answer, so make sure to upvote him!

Try it online.

**Explanation:**

```
T      # Push 10
 ®š    # Prepend -1 as list: [-1,1,0]
   ã   # Take the cartesian product of this list with itself, generating all pairs
    ¨  # Remove the last one, which is the [0,0]
       # (after which the result is output implicitly)

```
> 1 votes

# Answer
# Whitespace, 219 bytes

```
[S S S T    T   N
_Push_3][S S T  T   N
_Push_-1][S S S N
_Push_0][S S S T    T   N
_Push_3][S S T  T   N
_Push_-1][S S S T   N
_Push_1][S S S T    T   N
_Push_3][S S S N
_Push_0][S S S T    T   N
_Push_3][S S T  T   N
_Push_-1][S S S T   N
_Push_1][S S S T    T   N
_Push_3][S S T  T   N
_Push_-1][S S S N
_Push_0][S S S T    T   N
_Push_3][S S S T    N
_Push_1][S S S T    T   N
_Push_3][S S S N
_Push_0][S S S T    T   N
_Push_3][S S S T    N
_Push_1][S S S T    S N
_Push_2][S S S N
_Push_0][S S S T    T   N
_Push_3][S S T  T   N
_Push_-1][S S S T   N
_Push_1][S S S T    S N
_Push_2][S S S N
_Push_0][S S S T    T   N
_Push_3][S S S T    N
_Push_1][S S S T    T   N
_Push_3][S S T  T   N
_Push_-1][S S S N
_Push_0][S S S T    S N
_Push_2][S S S T    N
_Push_1][S S S T    T   N
_Push_3][S S S N
_Push_0][S S S T    S N
_Push_2][N
S S N
_Create_Label_LOOP][S S S T S T T   T   S N
_Push_46][T S S S _Add_top_two][T   N
S S _Print_as_character][N
S N
N
_Jump_to_Label_LOOP]

```

Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only.
`[..._some_action]` added as explanation only.

Try it online (with raw spaces, tabs and new-lines only).

Prints with a `.` delimiter between each number, and `/` between each pair of numbers. Since the codepoints of both `.` and `/` are between `-` and `01`, these are the shortest delimiters to use with this approach.

Uses this Whitespace tip of mine to print the output. The optimal constant `46` is generated by this Java program.

NOTE: Hard-coded with tab and newline delimiters (since their codepoints are pretty short, being `9` and `10` respectively) would be **332 bytes** instead.
> 1 votes

# Answer
# Deadfish~, 238 bytes

```
{iiiii}ddc{d}ddddddc{ii}dddcdddddciiiic{d}ddddddc{i}iiiciiiicdddddciiiiic{dd}iiic{i}iiiiiicddddciciiiic{dd}iiic{i}iiiiiicddddciiiiic{dd}iiic{ii}dddcdddddciiiiic{dd}iiic{i}iiiciiiicdddddciciiiic{dd}iiic{ii}dddcdddddciciiiic{dd}iiic{ii}dddc

```

Try it online!
> 1 votes

# Answer
# Pxem, Filename: 39 bytes + Content: 0 bytes = 39 bytes.

* Filename: `0 1;0 -1;1 0;-1 0;1 1;1 -1;-1 1;-1 -1.p`
* Content is empty.

How would you do that by control flowing although we don't have negative constants nor the way to obtain negative value without `.i` or `._`!
> 1 votes

# Answer
# Vyxal, ~~10~~ 7 bytes

```
1u0W2↔Ṫ

```

Try it Online!

### Explained

```
1u0W2↔Ṫ
1u0W    # list of [1,-1,0]
    2↔  # combinations of length 2
      Ṫ # remove tail which is [0,0] which is not needed in the challenge

```
> 1 votes

# Answer
# Tcl, 44 bytes

```
puts "-1 -1
0 -1
1 -1
-1 0
1 0
-1 1
0 1
1 1"

```

Try it online!

---

~~Tcl, 77 bytes
```
set j -1
time {set i -2
time {puts [expr [incr i]|$j?"$i $j":""]} 3
incr j} 3

```
Try it online!<br>~~
> 0 votes

# Answer
# Uiua, 10 bytes

```
↘1/⊂⊞⊂.∸~1

```

Try it!

```
↘1/⊂⊞⊂.∸~1
       ∸~1  # the list [0 ¯1 1]
      .     # duplicate
    ⊞⊂      # cartesian product
  /⊂        # decrement rank
↘1          # drop first row which is [0 0]

```
> 0 votes

---
Tags: code-golf, kolmogorov-complexity, matrix
---


title: Alternating bit smearing

text:
# Question
Title: Alternating bit smearing
## Introduction

This challenge requires you to set the trailing zeros of an integers binary representation to `010101…`, this is best explained with an example:

Given the integer `400`, the first step is to convert it to binary:

```
110010000

```

As we can see the fifth bit is the least significant `1` bit, so starting from there we replace the lower zeros by `0101`:

```
110010101

```

Finally we convert that back to decimal: `405`

## Challenge

Given a positive integer return/output the corresponding resulting value of the above defined process.

## Rules

* This sequence is only defined for integers with at least one `1` bit, so the input will always be ≥ 1
* You may take input as a string, list of digits (decimal) instead
* You don't have to handle invalid inputs

## Testcases

Here are some more testcases with the intermediary steps (you don't have to print/return these):

```
In -> … -> … -> Out
1 -> 1 -> 1 -> 1
2 -> 10 -> 10 -> 2
3 -> 11 -> 11 -> 3
4 -> 100 -> 101 -> 5
24 -> 11000 -> 11010 -> 26
29 -> 11101 -> 11101 -> 29
32 -> 100000 -> 101010 -> 42
192 -> 11000000 -> 11010101 -> 213
400 -> 110010000 -> 110010101 -> 405
298 -> 100101010 -> 100101010 -> 298

```

# Answer
> 12 votes
# Python 3, 20 bytes

```
lambda n:(n&-n)//3+n

```

Try it online!

## Explanation

Take `192` as an example. Its binary form is `11000000`, and we need to convert it to `11010101`.

We note that we need to add `10101` to the number. This is a geometric series (`4^0 + 4^1 + 4^2`), which has a closed form as `(4^3-1)/(4-1)`. This is the same as `4^3//3` where `//` denotes integer division.

If it were `101010`, then it would still be a geometric series (`2×4^0 + 2×4^1 + 2×4^2`), which is `2×4^3//3` for the reasons above.

Anyway, `4^3` and `2×4^3` would just be the least significant bit, which we obtain by `n&-n`:

We notice that the complement of `n` is `00111111`. If we add one, it becomes `01000000`, and it only overlaps with `n=11000000` at the least significant digit. Note that "complement and add one" is just negation.

# Answer
> 8 votes
# Jelly, 5 bytes

```
&N:3+

```

Try it online!

This time a port of Leaky Nun's approach (at least I helped him golf it down a bit :P)

# Jelly, 7 bytes

```
^N+4:6ạ

```

Try it online!

Uses JungHwan Min's fantastic approach, with indirect help from Martin Ender.

# Answer
> 6 votes
# Wolfram Language (Mathematica), ~~36~~ ~~28~~ ~~26~~ 24 bytes

-8 bytes thanks to @MartinEnder and -2 bytes thanks to @Mr.Xcoder

```
#+⌊(#~BitAnd~-#)/3⌋&

```

Try it online!

We only need to find the number of the trailing zeroes in the input, and find the number with alternating `0`s and `1`s with length one less than that, and add it to the input.

So, `400 -> 11001000 -> 110010000 + 0000 -> 110010101 + 101 -> 405`

The explicit formula for `n`th number with alternating `1`s and `0`s was given in A000975 on OEIS. We can use the `n`th number since no two different numbers can the same length in binary and have alternating digits.

# Answer
> 5 votes
# , ~~19~~ 18 bytes

```
+(2|-.i.@#.-.)&.#:

```

Try it online!

# Quick Explanation

This is an old answer, but it is very similar in nature to the current one, it just counts the trailing zeroes differently. See the comments for a link explaining how it works.

```
+(2|i.@i.&1@|.)&.#:
                 #:  Convert to binary list
       i.&1@|.       Index of last 1 from right
            |.         Reverse
       i.&1            Index of first 1
    i.               Range [0, index of last 1 from right)
  2|                 That range mod 2
               &.    Convert back to decimal number
+                    Add to the input

```

### Other Answers:

Previous answer (19 bytes).

```
+(2|i.@i.&1@|.)&.#:

```

Longer than it should be because `\` goes right-to-left.

```
+(2|#*-.#.-.)\&.(|.@#:)

```

# Answer
> 4 votes
# Julia 0.6, 12 bytes

```
!n=n|n&-n÷3

```

Try it online!

# Answer
> 3 votes
# JavaScript (ES6), ~~40~~ 39 bytes

Takes input as a 32-bit integer.

```
n=>n|((n&=-n)&(m=0xAAAAAAAA)?m:m/2)&--n

```

### Test cases

```
let f =

n=>n|((n&=-n)&(m=0xAAAAAAAA)?m:m/2)&--n

console.log(f(1))   // 1 -> 1 -> 1
console.log(f(2))   // 10 -> 10 -> 2
console.log(f(3))   // 11 -> 11 -> 3
console.log(f(4))   // 100 -> 101 -> 5
console.log(f(24))  // 11000 -> 11010 -> 26
console.log(f(29))  // 11101 -> 11101 -> 29
console.log(f(32))  // 100000 -> 101010 -> 42
console.log(f(192)) // 11000000 -> 11010101 -> 213
console.log(f(400)) // 110010000 -> 110010101 -> 405
console.log(f(298)) // 100101010 -> 100101010 -> 298
```

# Answer
> 2 votes
# , ~~71~~ 58 bytes

*thanks to NofP for -6 bytes*

```
function(n){n=n%/%(x=2^(0:31))%%2
n[!cumsum(n)]=1:0
n%*%x}

```

Try it online!

Assumes input is a 32-bit integer. R only has signed 32-bit integers (casting to `double` when an integer overflows) anyway and no 64-bit or unsigned ints.

# Answer
> 2 votes
# 05AB1E, ~~13~~ ~~8~~ 5 bytes

Saved 5 bytes thanks to *Mr. Xcoder* and JungHwan Min's neat formula
Saved another 3 thanks to *Mr. Xcoder*

```
(&3÷+

```

Try it online!

**Explanation**

```
(      # negate input
 &     # AND with input
  3÷   # integer divide by 3
    +  # add to input

```

# Answer
> 2 votes
# brainfuck, 120 bytes

```
>+<[[>-]++>[[>]>]<[>+>]<[<]>-]>[-<+>[-<[<]<]>]>[>]<[>+<[->+<]<[->+<]<]>>[<]+>[-[-<[->+<<+>]>[-<+>]]<[->++<]<[->+<]>>>]<<

```

Try It Online!

Starts with the value in the current cell and ends on the cell with the output value. Obviously won't work on numbers above 255 as that's the cell limit for typical brainfuck, but will work if you assume infinite cell size.

# Answer
> 1 votes
# Python 3, 56 bytes

```
lambda n:eval((bin(n).rstrip("0")+"01"*n)[:len(bin(n))])

```

Try it online!

Not really happy with this yet, but I really didn't want to use the formula... -2 thanks to Rod. -1 thanks to Jonathan Frech.

# Answer
> 1 votes
# PowerShell, 168 bytes

```
param($n)$a=($c=[convert])::ToString($n,2);if(($x=[regex]::Match($a,'0+$').index)-gt0){$c::ToInt32(-join($a[0..($x-1)]+($a[$x..$a.length]|%{(0,1)[$i++%2]})),2)}else{$n}

```

Try it online!

Ouch. Conversion to/from binary and array slicing are not really PowerShell's strong suits.

Takes input `$n` as a number. We immediately `convert` that to binary base `2` and store that into `$a`. Next we have an if/else construct. The if clause tests whether a `regex` `Match` against 1 or more `0`s at the end of the string (`'0+$'`) has its `index` at a location greater than `0` (i.e., the start of the binary string). If it does, we have something to work with, `else` we just output the number.

Inside the `if`, we slice of the `x`th first digits, and array-concatenate `+` those with the remaining digits. However, for the remaining digits, we loop through them and select either a `0` or `1` to be output instead, using `$i++%2` to choose. This gets us the `010101...` pattern instead of `0`s at the end. We then `-join` that back together into a string, and `$c`onvert it back into an `Int32` from base `2`.

In either situation, the number is left on the pipeline and output is implicit.

# Answer
> 1 votes
# C, 56 bytes

```
i,k;f(n){for(k=i=1;n>>i<<i==n;k+=++i&1)k*=2;return n|k;}

```

Try it online!

# C (gcc), 50 bytes

```
i,k;f(n){for(k=i=1;n>>i<<i==n;k+=++i&1)k*=2;k|=n;}

```

Try it online!

**~~51~~  48 bytes using Arnauld's solution:**

*Thanks to @l4m2 for saving three bytes!*

```
m;f(n){return n|((n&-n)&(m=-1u/3*2)?m:m/2)&n-1;}

```

Try it online!

**43 with gcc:**

```
m;f(n){m=n|((n&-n)&(m=-1u/3*2)?m:m/2)&n-1;}

```

Try it online!

# Answer
> 1 votes
# PowerShell, ~~41~~ 36 bytes

```
param($n)$n+(($x=$n-band-$n)-$x%3)/3

```

Try it online! or Verify all test cases

Port of Leaky Nun's Python answer.

*Saved 5 bytes thanks to Leaky Nun*

# Answer
> 1 votes
# APL+WIN, 43 bytes

```
p←+/^\⌽~n←((⌊1+2⍟n)⍴2)⊤n←⎕⋄2⊥((-p)↓n),p⍴0 1

```

Prompts for screen input

# Answer
> 1 votes
# PHP, 47 bytes

```
<?php function b($a){echo(int)(($a&-$a)/3)+$a;}

```

Try it online!

Really just another port of @Leaky Nun's solution

# Answer
> 1 votes
# Perl 5, 54 bytes

```
$_=sprintf'%b',<>;1while s/00(0*)$/01$1/;say oct"0b$_"

```

Try it online!

# Answer
> 1 votes
# Rust, 18 bytes

A port of Leaky Nun's approach

```
|n:i32|(n&-n)/3+n;

```

Try it online!

# Answer
> 1 votes
# Ruby, 15 bytes

Another port of Leaky Nun's approach.

```
->k{(k&-k)/3+k}

```

Try it online!

# Answer
> 1 votes
# AWK, 24 bytes

A port of JungHwan Min's Mathmatica answer

```
$0=int(and($0,-$0)/3+$0)

```

Try it online!

# Answer
> 1 votes
# JavaScript ES6, 13 bytes

```
n=>(n&-n)/3|n

```

```
f =
n=>(n&-n)/3|n
;
console.log (f(8));
console.log (f(243));
console.log (f(1048576));
console.log (f(33554432));
```

# Answer
> 1 votes
# Pari/GP, 19 bytes

A port of Leaky Nun's approach.

```
n->n+bitand(n,-n)\3

```

Try it online!

# Answer
> 1 votes
# Vyxal, 39 bitsv2, 4.875 bytes

```
N⋏3ḭ+

```

Try it Online!

Bitstring:

```
011000110010011000101101101111111101001

```

# Answer
> 0 votes
# Jelly, 13 bytes

```
BŒgṪµ2Ḷṁ×CḄ+³

```

Try it online!

**Explanation**

Take 24 as an example input.

```
BŒgṪµ2Ḷṁ×CḄ+³
B                Binary representation of the input → 11000
 Œg              Group runs of equal length → [[1,1],[0,0,0]]
   Ṫ             Tail → [0,0,0]
    µ            New monadic link
     2Ḷ          [0,1] constant
       ṁ         Mold [0,1] to the shape of [0,0,0] → [0,1,0]
        ×        Multiply [0,1,0] by...
         C       1-[0,0,0]. If last bit(s) of the original input are 1 this will add nothing to the original input
          Ḅ      Convert to decimal from binary → 2
           +³    Add this with the original input → 26

```

---
Tags: code-golf, sequence, binary, bitwise
---


# Question
Title: Rebuild a rectangular array from a corner
I once had a beautiful rectangular array. It was very symmetrical, but unfortunately it has fallen apart and now I only have the top left corner. Your task will be to rebuild the original array.

Your program will receive a 2 dimensional array of integers. For ease of parsing, you may assume they are all between 1 and 9. Your task is to reverse the array's columns, its rows, and both, stitch together the resulting corners, and return the resulting array.

You can assume the array dimensions will be at least 1x1.

Test cases:

```
Input:
1 2 3
4 5 6

Output:
1 2 3 3 2 1
4 5 6 6 5 4
4 5 6 6 5 4
1 2 3 3 2 1

```

---

```
Input:
1

Output:
1 1
1 1

```

---

```
Input:
9
9
9

Output:
9 9
9 9
9 9
9 9
9 9
9 9

```

This is , fewest bytes wins!

# Answer
# Canvas, 1 byte

Try it here!

Outputs as a multiline string
> 19 votes

# Answer
## Haskell, ~~25~~ 24 bytes

```
r=(++)<*>reverse
r.map r

```

Try it online!
> 12 votes

# Answer
# Python 3, 38 bytes

```
lambda a:[b+b[::-1]for b in a+a[::-1]]

```

Try it online!

Takes a list of lists and returns a list of lists.

Explanation:

```
lambda a:                              # anonymous lambda function
                   for b in a+a[::-1]  # for each row in the array and the upside-down array
          b+b[::-1]                    # the row with its reverse appended
         [                           ] # return in a list

```
> 5 votes

# Answer
# Husk,  ~~7~~  6 bytes

Coincidentally, Erik had posted the exact same code in the Husk chatroom about a minute before I posted this.

```
‼oTS+↔

```

Try it online!

Pervious version, **7 bytes**:

```
mS+↔S+↔

```
> 5 votes

# Answer
# 05AB1E, 2 bytes

```
∞∊

```

Try it online!

---

```
   # Input:Array of String | ['12','34']
---#-----------------------+------------------------------------------
∞  # Mirror horizontally.  | [12,34]       -> [1221,3443]
 ∊ # Mirror vertically.    | [1221,3443]   -> [1221\n3443\n3443\n1221]

```

---

Credit for Mr. Xcoder pointing out that arrays of string may count as 2D arrays and Pavel for confirming it.
> 5 votes

# Answer
## Retina, 13 bytes

```
\%`$
$^$`
Vs`

```

Try it online!

### Explanation

```
\%`$
$^$`

```

On each line (`%`), match the end of the line (`$`), and insert the reverse (`$^`) of the entire line (`$``) and print the result with a trailing linefeed (`\`). This does the reflection along the vertical axis and prints the first half of the output.

```
Vs`

```

This just reverses the entire string, which is equivalent to a 180° degree rotation, or in our case (due to the horizontal symmetry) a reflection along the horizontal axis. This way this works is that `V`'s (reverse) default regex is `(?m:^.*$)`, which normally matches each line of the string. However, we activate the singleline option `s`, which makes `.` match linefeeds as well and therefore this default regex actually matches the entire string.

The result of this is printed automatically at the end of the program, giving us the second half of the output.
> 5 votes

# Answer
# Jelly, 5 bytes

```
m€0m0

```

Try it online!
> 3 votes

# Answer
# MATL, 5 bytes

```
,tPv!

```

Try it online!

Explanation:

```
(implicit input)
,               # do twice:
 t              # dup top of stack
 P              # flip vertically
 v              # vertically concatenate
 !              # transpose
(implicit output)
```
> 3 votes

# Answer
# Octave,  ~~33~~  29 bytes

*Thanks to @Giuseppe for golfing four bytes!*

```
@(A)[B=[A;flip(A)] fliplr(B)]

```

Try it online!
> 3 votes

# Answer
# Ruby, 35 bytes

```
->a{r=->b{b+b.reverse}
r[a].map &r}

```

Try it online!

A lambda accepting a 2D array and returning a 2D array. It's straightforward, but here's the ungolfed version anyway:

```
->a{
  r=->b{ b+b.reverse } # r is a lambda that returns the argument and its reverse
  r[a].map &r          # Add the array's reverse, then add each row's reverse
}

```
> 3 votes

# Answer
# JavaScript (Node.js), ~~62~~ ~~55~~ ~~49~~ 46 bytes

```
A=>(j=x=>[...x,...[...x].reverse()])(A).map(j)

```

Try it online!

Because `Array.prototype.reverse()` reverses the array in place, I have to make a shallow copy somewhere first. `A=>(j=x=>[...x,...x.reverse()])(A).map(j)` does not work.
> 3 votes

# Answer
# , 12 bytes

```
(,|.)@,.|."1

```

Try it online!

## Explanation

```
         |."1 - reverse each row
       ,.     - and stitch them to the input
 (   )@       - and
  ,|.         - append the rows in reversed order

```
> 3 votes

# Answer
# awk, 88 bytes

```
{s="";for(i=NF;i>0;i--)s=" "$i s" "$i;a[FNR]=s;print s}END{for(i=NR;i>0;i--)print a[i]}

```
> 3 votes

# Answer
# Triangularity, 31 bytes

```
...)...
..IEM..
.DRs+}.
DRs+...

```

Try it online!

## Explanation

Removing the characters that make up for the padding, here is what the program does:

```
)IEMDRs+}DRs+ – Full program. Takes a matrix as a 2D list from STDIN.
)             – Push a 0 onto the stack.
 I            – Take the input at that index.
  E           – Evaluate it.
   M    }     – For each row...
    DR        – Duplicate and replace the second copy by its reverse.
      s+      – Swap and append.
         DR   – Duplicate the result and replace the second copy by its reverse.
           s+ – Swap and append.

```
> 2 votes

# Answer
# , 57 bytes

```
function(m)rbind(N<-cbind(m,m[,ncol(m):1]),N[nrow(N):1,])

```

Try it online!
> 2 votes

# Answer
# APL+WIN, 11 bytes

Prompts for a 2d array of integers.

```
m⍪⊖m←m,⌽m←⎕

```
> 2 votes

# Answer
# Stax, 5 bytes

```
:mm:m

```

Run and debug it online

`:m` means mirror, which is `input.concat(reverse(input))`. `m`, in this context means output each line after applying...

So, mirror the array of rows, and then mirror each row and output.
> 2 votes

# Answer
# SNOBOL4 (CSNOBOL4), ~~119~~ 113 bytes

```
	T =TABLE()
I	X =X + 1
	I =INPUT	:F(D)
	OUTPUT =T<X> =I REVERSE(I)	:(I)
D	X =X - 1
	OUTPUT =GT(X) T<X>	:S(D)
END

```

Try it online!

Takes input as strings on STDIN, without spaces. This only works because the digits are `1-9` and would fail otherwise.
> 2 votes

# Answer
# Add++, 30 bytes

```
D,f,@,bU€{r}B]{r}
D,r,@,dbR+

```

Try it online!

The footer simply transforms the nested array into the format in the question. Defines a function `f`, which expects a matrix (nested array) as an argument.
> 2 votes

# Answer
# Japt, 6 bytes

```
mê1 ê1

```

Try it here

---

## Explanation

```
           :Implicit input of 2D array
m          :Map
 ê1        :  Mirror sub array
    ê1     :Mirror main array

```
> 2 votes

# Answer
# Charcoal, 5 bytes

```
θ‖Ｃ→↓

```

Try it online!

Thanks to ASCII-only for a better input format.
> 2 votes

# Answer
# Mathematica, 29 bytes

```
(g=#~Join~Reverse@#&)@*Map[g]

```

Try it online!
> 2 votes

# Answer
# SOGL V0.12, 2 bytes

*-1 byte thanks to dzaima.*

```
╬ø

```

Try it here!
> 2 votes

# Answer
# APL (Dyalog Classic), 7 bytes

```
⍪∘⊖⍨⊢,⌽

```

Try it online!
> 2 votes

# Answer
# C (gcc), ~~114~~ 111 bytes

```
j,i;f(A,w,h)int*A;{for(i=h+h;i-->0;puts(""))for(j=w+w;j-->0;)printf("%d,",A[(i<h?i:h+h+~i)*w+(j<w?j:w+w+~j)]);}

```

Try it online!

# C (gcc), 109 bytes (abusing ease of parsing)

* Thanks to Kevin Cruijssen for suggesting to only allow one-digit input integers; saved two bytes.

```
j,i;f(A,w,h)int*A;{for(i=h+h;i-->0;puts(""))for(j=w+w;j-->0;)putchar(A[(i<h?i:h+h+~i)*w+(j<w?j:w+w+~j)]+48);}

```

Try it online!
> 2 votes

# Answer
# Java 8, ~~140~~ 131 bytes

```
m->{String r="";for(int a=m.length,b=m[0].length,i=a+a,j;i-->0;r+="\n")for(j=b+b;j-->0;)r+=m[i<a?i:a+a+~i][j<b?j:b+b+~j];return r;}

```

**Explanation:**

Try it online.

```
m->{                      // Method with integer-matrix parameter and String return-type
  String r="";            //  Result-String, starting empty
  for(int a=m.length,     //  Amount of rows of the input-matrix
          b=m[0].length,  //  Amount of columns of the input-matrix
          i=a+a,j;        //  Index integers
      i-->0;              //  Loop over double the rows
      r+="\n")            //    After every iteration: append a new-line to the result
     for(j=b+b;j-->0;)    //   Inner loop over double the columns
       r+=                //    Append the result with:
          m[i<a?          //     If `i` is smaller than the amount of rows
             i            //      Use `i` as index in the input-matrix
            :             //     Else:
             a+a+~i]      //      Use `a+a+i-1` as index instead
           [j<b?          //     If `j` is smaller than the amount of columns
             j            //      Use `j` as index in the input-matrix
            :             //     Else:
             b+b+~j];     //      Use `b+b+j-1` as index instead
  return r;}              //  Return the result-String

```
> 2 votes

# Answer
# , 11 bytes

Anonymous tacit prefix function.

```
|:@(,|.)^:2

```

Try it online!

`|:` transpose

`@(…)` the result of:

`,` the argument followed by

`|.` its reverse

`^:2` and all this done twice
> 2 votes

# Answer
# Uiua, 9 bytes

```
⍥(⍉⊂∶⇌.)2

```

Try it!

```
⍥(⍉⊂∶⇌.)2
⍥(     )2  # run a function twice
      .    # duplicate
     ⇌     # reverse
   ⊂∶      # prepend
  ⍉        # transpose

```
> 2 votes

# Answer
# , 12 bytes

```
yGæGPÎy$æ_|P

```

Try it online!

Explanation:

```
yG              " Yank every line
  æG            " Reverse the order of the lines
    P           " Paste what we yanked
     Î          " On every line:
      y$        "   Yank the whole line
        æ_      "   Reverse the whole line
          |     "   Move to the beginning of the line
           P    "   Paste what we yanked

```
> 1 votes

# Answer
# Julia 0.6, ~~55~~ 49 bytes

```
~i=i:-1:1
!x=[x x[:,~end];x[~end,:] x[~end,~end]]

```

Try it online!

`~(i)` is a function to create slice from `i` down to `1`.
So `~end` gives the slice `end:-1:1`

`!(x)` is the function to do the rebuilding of the array.
> 1 votes

# Answer
# Python 3, 49 bytes

```
def f(a):o=[i+i[::-1]for i in a];return o+o[::-1]

```

Where `a` is the input array. This function will return a 2D array.
> 1 votes

# Answer
# Clojure, 56 bytes

```
(fn[i](map #(concat %(reverse %))(concat i(reverse i))))

```

Creates an anonymous function which takes the two dimensional list and returns the fixed rectangle as two dimensional list.

Try it online!
> 1 votes

# Answer
# Perl 5 `-lp` `-Mfeature=say`, 36 bytes

```
unshift@l,$_.=reverse;END{say for@l}

```

Deparsed:

```
BEGIN { $/ = "\n"; $\ = "\n"; }
use feature 'say';
LINE: while (defined($_ = readline ARGV)) {
    chomp $_;
    unshift @l, $_ .= reverse;
    sub END {
        say $_ foreach (@l);
    }
}
continue {
    die "-p destination: $!\n" unless print $_;
}

```

Try it online!
> 1 votes

# Answer
# Proton, 29 bytes

```
a=>[b+b[by-1]for b:a+a[by-1]]

```

Try it online!

There are a few other interesting approaches though:

# Proton, 29 bytes

```
a=>map(g,(g=x=>x+x[by-1])(a))

```

Try it online!

You can define the mirror sub-function `g` in-line, because Proton. It's not shorter though.

# Proton, 36 bytes

```
(a=>[x[0]for x:zip(*(a+a[by-1]))])*2

```

Try it online!

This should be `(a=>zip(*(a+a[by-1])))*2` which is 24 bytes, but the zip function is completely broken. Basically, you mirror it and zip, and then do that twice (you can multiply a function by a positive integer to apply the function multiple times).
> 1 votes

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


# Question
Title: Index of the row with most non-zero elements
**This is a simple one:** Take a matrix of integers as input, and output the index of the row with the most non-zero elements. You may assume that there will only be one row with the most non-zero elements.

### Test cases:

These are 1-indexed, you may choose if you want 0 or 1-indexed.

```
1
0
row = 1
---
0  -1
0   0
row = 1
---
1   1   0   0   0
0   0   5   0   0
2   3   0   0   0
0   5   6   2   2
row = 4
---
0   4   1   0
0   0  -6   0
0   1   4  -3
2   0   0   8
0   0   0   0
row = 3

```

# Answer
# MATL, 6 bytes

```
!gs&X>

```

Input is a matrix, with `;` as row separator.

Try it online! Or verify all test cases.

### Explanation

```
!     % Transpose
g     % Logical: convert non-zeros to 1
s     % Sum of each column, or sum of row if there's a single row
&X>   % Arg max. Implicitly display

```
> 8 votes

# Answer
# Mathematica, 23 bytes

```
Ordering[Count@0/@#,1]&

```
> 6 votes

# Answer
# , 31 bytes

```
pryr::f(which.min(rowSums(!m)))

```

returns an anonymous function which takes a matrix:

```
function(m)which.min(rowSums(!m))

```

`rowSums` sums the rows, with `!m` transforming 0 to 1 and everything else to 0. `which.min` returns the 1-based index of the first row which contains the min sum (i.e., which row has the fewest zeros).

Try it online!
> 6 votes

# Answer
# 05AB1E, ~~8~~ 6 bytes

```
ΣĀO}θk

```

Try it online!

-2 Bytes thanks to Erik the Outgolfer

### Explanation

```
ΣĀO}θk
Σ  }   # Sort input by following code
 Ā      # Is element not 0? (vectorized)
  O     # Sum
    θk # Get index of "largest" element
       # Implicit print

```
> 6 votes

# Answer
## Haskell, ~~46~~ ~~42~~ 41 bytes

```
snd.minimum.(`zip`[1..]).map(filter(==0))

```

Try it online!

How it works

```
    map                    -- for each row
        (filter(==0))      -- collect the 0s
    (`zip`[1..])           -- pair with row index  (<#0s>, <index>)
  minimum                  -- find the minimum
snd                        -- extract index from pair

```
> 5 votes

# Answer
# C#, 69 bytes

```
using System.Linq;m=>m.IndexOf(m.OrderBy(r=>r.Count(n=>n!=0)).Last())

```

Takes a `List<int[]>` as input and returns the 0-indexed result.
> 4 votes

# Answer
## Python 3, ~~54~~ 48 bytes

```
lambda a:a.index(min(a,key=lambda r:r.count(0)))

```

Shaved off 6 bytes. Old solution:

```
lambda a:min(range(len(a)),key=lambda i:a[i].count(0))

```
> 3 votes

# Answer
# Actually, 9 bytes

```
0@♀cñ♂RmN

```

Try it online!

Explanation:

```
0@♀cñ♂RmN
0@♀c       count zeroes in each row
    ñ♂R    enumerate and reverse each row (each row becomes [count, index] pair)
       m   minimum
        N  last element (the index)

```
> 3 votes

# Answer
# APL (Dyalog), 11 bytes

```
(⊢⍳⌈/)+/0≠⎕

```

Try it online!

`0≠⎕` Boolean matrix where non-zero

`+/` sum rows

`(` apply the following tacit function to the list of sums

`⌈/` the maximum's

index

in the argument list

`)`
> 3 votes

# Answer
# Brachylog, 17 bytes

```
{{∋0}ᶜ}ᵐA;.∋₎~⌋A∧

```

Try it online!
> 3 votes

# Answer
# Jelly, 5 bytes

```
TL$€M

```

Try it online!

1-indexed.

So many 5-byte versions...

`TL$€M`, `T€L€M`, `TJ$€M`, `T€J€M`, `¬¬Ṣ€M`, `ṠAṢ€M`, `ṠAS€M`, `AṠṢ€M`, `AṠS€M`, `¬ċ€0M`, ...
> 2 votes

# Answer
## Clojure, 64 bytes

This one works also with negative numbers in the input, luckily the same length as the original:

```
#(nth(sort-by(fn[i](count(filter #{0}(% i))))(range(count %)))0)

```

Original:

```
#(last(sort-by(fn[i](count(filter pos?(% i))))(range(count %))))

```
> 2 votes

# Answer
# 05AB1E, 5 bytes

```
€ĀOZk

```

Try it online!

0-indexed.
> 2 votes

# Answer
# Haskell - ~~69~~ 68 Bytes

*Saved one byte thanks to Siracusa!*

Rows are zero indexed

```
g=filter
m y=head$g((==maximum y).(y!!))[0..]
f=m.map(length.g(0/=))

```

## Usage

```
f [[1,1,0,0,0],[2,3,0,0,0],[0,5,6,2,2],[1,1,1,1,1]]

```

Try it online!
> 2 votes

# Answer
# CJam, 11 bytes

```
{0fe=_:e<#}

```

Try it online!

-2 thanks to Challenger5.
> 2 votes

# Answer
# q/kdb+, ~~25~~ ~~17~~ 16 bytes

**Solution:**

```
(*)(<)sum(+)0=/:

```

**Example:**

```
q)(*)(<)sum(+)0=/:enlist(1;0)
0
q)(*)(<)sum(+)0=/:(0 -1;0 0)
0
q)(*)(<)sum(+)0=/:(1 1 0 0 0;0 0 5 0 0;2 3 0 0 0;0 5 6 2 2)
3
q)(*)(<)sum(+)0=/:(0 4 1 0;0 0 -6 0;0 1 4 -3;2 0 0 8;0 0 0 0)
2

```

**Explanation:**

```
first iasc sum flip 0=/:  / ungolfed
                      /:  / each right, apply a function to each item to the right
                    0=    / returns boolean 1b or 0b if item in each list is equal to zero
               flip       / flip (rotate) the output
           sum            / sum these up
      iasc                / return indices if we were to sort ascending
first                     / take the first one

```

**Notes:**

~~The problem is fairly straightforward, this solution feels overly complicated.~~ As soon as I hit submit I realised the error of my ways.

**Bonus:**

Here's a k solution that weights in at ~~16~~ ~~10~~ 9 bytes - almost exactly the same but 7 bytes shorter due to the fact we don't need brackets when using the k built-ins, and as a result some become shorter than the q keywords (e.g. `+/` for `sum` (would be `(+/)` in q)).

```
*<+/+0=/:

```
> 2 votes

# Answer
# Jelly, 7 bytes

```
ċ0$ÞḢi@

```

Try it online!

```
ċ0$ÞḢi@  Main link
   Þ     Sort by
ċ0$              the number of occurences of 0
    Ḣ    Take the first element
     i@  Index in the original array

```
> 1 votes

# Answer
# Python 2, 62 bytes

```
lambda m:max(range(len(m)),key=lambda n:len(filter(abs,m[n])))

```

Try it online!
> 1 votes

# Answer
# Python 2, ~~64 55 52~~ 48 bytes

* **Thanks to @Rod for shaving 9 bytes!!**: count `0`s and use `min()` instead of `max()`
* @Rod saved yet another 3 bytes: use `input()` instead of `def`
* **@ovs saved 4 bytes**: use of `lambda` and hash-map

```
lambda x:x.index(min(x,key=lambda n:n.count(0)))

```

Try it online!
> 1 votes

# Answer
# JavaScript (ES6), 62 bytes

0-indexed. Takes a 2D array as input.

```
a=>(a=a.map(x=>x.filter(y=>y).length)).indexOf(Math.max(...a))

```
> 1 votes

# Answer
# PHP, 58 bytes

0-Indexed

```
<?=array_search(max($a=array_map(array_filter,$_GET)),$a);

```

Try it online!
> 1 votes

# Answer
# , 18 bytes

```
òø0
jòÚDuu/"
dGØ¾

```

Try it online!

Unlike most V answers, this is 0-indexed.

```
00000000: f2f8 300a 6af2 da44 7575 2f12 220a 6447  ..0.j..Duu/.".dG
00000010: d8be                                     ..

```

Not bad for a language with no numeric support! `;P`

I also have discovered that the uppercase variant of the *count* command, that is `Ø`, is horribly broken.
> 1 votes

# Answer
# Python 3, 92 bytes

```
def f(x):
    for e in x:
        e.sort()
    y=x[:]
    y.sort()
    return x.index(y[-1])

```

First sort each row such that the entrys are `[0,0,..,0,x,x,x]` then sort the whole matrix, so that the last entry in `y` is the row we are looking for. The copy `y=x[:]` is necessary, since `.sort()` works inplace, hence we don't know the original index after sorting.

I appreciate any help how to golf this solution further. Most bytes are lost because of the whitespaces in each line. The code itself is only 68 bytes long.

Try it online!
> 1 votes

# Answer
# Pyth, 6 bytes

```
xQh/D0

```

Demonstration

Instead of finding the row with the most non-zero elements, I find the row with the least zero elements.

`/D0`: Order (`D`) by count (`/`) of zeros (`0`). Implicitly applied to `Q`, the input.

`h`: Take the first, and minimum, element.

`xQ`: Find the index (`x`) in the input (`Q`) of that element.
> 1 votes

# Answer
# Retina, 46 bytes

```
%M`\b0
m`(?<=(¶.+)*)$
;$#1
O#`.+
!`(?<=^.+;).+

```

Try it online!

0-indexed. Works with positive and negative integers (and 0). Assumes no leading zeros.
> 1 votes

# Answer
# , 16 bytes

```
0{[:/:@:+/@|:0=]

```

Try it online!
> 1 votes

# Answer
# Java (OpenJDK 8), ~~119~~ 101 bytes

```
m->{int i=m.length,M=0,I=0,c;for(;i-->0;){c=0;for(int x:m[i])if(x!=0)c++;if(c>M){M=c;I=i;}}return I;}

```

Try it online!

Java, that sweet verbose language :)

Thanks for saving 18 bytes, @KevinCruijssen ;)
> 1 votes

# Answer
# Java 8, 145 bytes

```
import java.util.*;m->{int t=0,s=0,i=0,r=0;for(;i<m.size();i++){List l=(List)m.get(i);for(;l.remove(0L););s=l.size();if(s>t){t=s;r=i;}}return r;}

```

Ugly, but it works..

**Explanation:**

Try it here.

```
import java.util.*;         // Required import for List

m->{                        // Method with List parameter and integer return-type
  int t=0,s=0,i=0,          //  Temp integers
      r=0;                  //  Result integer
  for(;i<m.size();i++){     //  Loop over the List of Lists
    List l=(List)m.get(i);  //   Get the inner List
    for(;l.remove(0L););    //   Remove all zeros
    s=l.size();             //   Get the size of the List
    if(s>t){                //   If this size is larger than the previous
      t=s;                  //    Set `t` to this size
      r=i;                  //    And set the result to the index of this row
    }
  }                         //  End of loop
  return r;                 //  Return result-integer
}                           // End of method

```
> 1 votes

# Answer
# JavaScript (ES6), 51 Bytes

```
m=>m.reduce((a,e,i)=>e.filter(x=>x).length>a?i:a,0)

```

where `m` is a 2D array and the index returned is 0-indexed

**Test cases:**

```
f=
m=>m.reduce((a,e,i)=>e.filter(x=>x).length>a?i:a,0)

console.log(f([[1], [0]]))
console.log(f([[0,-1], [0,0]]))
console.log(f([[1,1,0,0,0], [0,0,5,0,0], [2,3,0,0,0], [0,5,6,2,2]]))
console.log(f([[0,4,1,0], [0,0,-6,0], [0,1,4,-3], [2,0,0,8], [0,0,0,0]]))
```
> 1 votes

# Answer
# Python 2, 51 bytes

```
def f(x,i=0):print i;x[i].remove(0);f(x,-~i%len(x))

```

Try it online!

This version removes 0s progressively through the arrays, printing the current index, and crashes when there are no more zeros to remove. Last printed index is the answer.

# Python 2, 57 bytes

```
lambda x,i=0:0in x[i]>x[i].remove(0)and f(x,-~i%len(x))|i

```

Try it online!

Wanted to try a different approach from what's already here. So here I recursively iterate over the array removing one 0 at a time until the current array no longer has any zeroes - and then output the index of that array.
> 1 votes

# Answer
# Java 8, 100 bytes

```
m->m.indexOf(m.stream().map(z->{z.removeIf(x->x==0);return z;}).max((q,r)->q.size()-r.size()).get())

```

## Explanation

The power of Lists and Streams! (and without the imports, to boot!)

Let's break this little lambda down into chunks:

```
m.stream().map(z->{z.removeIf(x->x==0);return z;}

```

We turn our List of Lists (the matrix in the question) into a Stream and go through each element, removing all of those pesky zeroes from each sub-List. We need to explicitly return the sublist each time here, because `Stream.map()` converts each object in the Stream to whatever the mapping returns, and we don't want to change them.

```
.max((q,r)->q.size()-r.size()).get()

```

We go through our newly de-zeroed sublists, and simply check how big they are next to each other, getting us the biggest sublist. The `.get()` is because the `Stream.max()` returns an Optional, requiring that extra function call.

```
m.indexOf()

```

We take that biggest sublist, and find where it is in the main List, giving us our result!

## Notes

This breaks if the outer list is empty, but I'm taking

> You may assume that there will only be one row with the most non-zero elements.

to imply that there will always be at least one row. Correct me if I'm wrong.
> 1 votes

# Answer
# Japt, 7 bytes

0-indexed. Takes input as an array of arrays.

```
mè
bUrw

```

Test it

---

## Explanation

Implicit input of array `U`.
`[[0,4,1,0],[0,0,-6,0],[0,1,4,-3],[2,0,0,8],[0,0,0,0]]`

Map (`m`) over `U` returning the count of truthy (non-zero) elements in each sub-array. Implicitly assign this new array to `U`.
`[2,1,3,2,0]`

```
Urw

```

Reduce (`r`) array `U` by getting the greater of the current value and the current element.
`3`

```
b

```

Get the first index in `U` where the element equals that value and implicitly output the result.
`2`
> 1 votes

# Answer
# Vyxal, 34 bitsv2, 4.25 bytes

```
vT@ÞM

```

Try it Online!

Bitstring:

```
1000101100100011101101110100011000

```

optimally encoded solution
> 1 votes

# Answer
# Uiua, 7 bytes

```
⊢⍖/+≠0⍉

```

Try it!

```
⊢⍖/+≠0⍉
      ⍉  # transpose
    ≠0   # where is it not equal to zero?
  /+     # sum columns
⊢⍖       # index of maximum

```
> 0 votes

# Answer
# Perl 5 `-pa`, 25 bytes

```
$;[grep$_,@F]=$.}{$\=pop@

```

Try it online!
> 0 votes

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


title: Count the contiguous submatrices

text:
# Question
Title: Count the contiguous submatrices
*Migrated from chat*

Given two non-empty non-negative integer matrices ***A*** and ***B***, answer the number of times ***A*** occurs as a contiguous, possibly overlapping, submatrix in ***B***.

## Examples/Rules

### 0. There may not be any submatrices

***A***:
`[[3,1],`
`[1,4]]`

***B***:
`[[1,4],`
`[3,1]]`

Answer:
`0`

### 1. Submatrices must be contiguous

***A***:
`[[1,4],`
`[3,1]]`

***B***:
`[[3,**1,4**,0,5],`
`[6,**3,1**,0,4],`
`[5,6,3,0,1]]`

Answer:
`1` (marked in bold)

### 2. Submatrices may overlap

***A***:
`[[1,4],`
`[3,1]]`

***B***:
`[[3,**1,4**,5],`
`[6,**3,*1****,4*],`
`[5,6,*3,1*]]`

Answer:
`2` (marked in bold and in italic respectively)

### 3. A (sub)matrix may be size 1-by-1 and up

***A***:
`[[3]]`

***B***:
`[[**3,**1,4,5],`
`[6,**3**,1,4],`
`[5,6,**3**,1]]`

Answer:
`3` (marked in bold)

### 4. Matrices may be any shape

***A***:
`[[3,1,3]]`

`[[**3,1,*3****,1,**3*****,1,*3****,1,3*]]`

Answer:
`4` (two bold, two italic)

# Answer
> 8 votes
# Brachylog (v2), 10 bytes

```
{{s\s\}ᵈ}ᶜ

```

Try it online!

I like how clear and straightforward this program is in Brachylog; unfortunately, it's not that short byte-wise because the metapredicate syntax takes up three bytes and has to be used twice in this program.

## Explanation

```
{{s\s\}ᵈ}ᶜ
  s         Contiguous subset of rows
   \s\      Contiguous subset of columns (i.e. transpose, subset rows, transpose)
 {    }ᵈ    The operation above transforms the first input to the second input
{       }ᶜ  Count the number of ways in which this is possible

```

# Answer
> 5 votes
# Jelly, 7 bytes

```
ZẆ$⁺€Ẏċ

```

Try it online!

### How it works

```
ZẆ$⁺€Ẏċ  Main link. Arguments: B, A

  $      Combine the two links to the left into a monadic chain.
Z          Zip; transpose the matrix.
 Ẇ         Window; yield all contiguous subarrays of rows.
   ⁺     Duplicate the previous link chain.
    €    Map it over the result of applying it to B.
         This generates all contiguous submatrices of B, grouped by the selected
         columns of B.
     Ẏ   Tighten; dump all generated submatrices in a single array.
      ċ  Count the occurrences of A.

```

# Answer
> 4 votes
# MATL, 12 bytes

```
ZyYC2MX:=XAs

```

Inputs are **A**, then **B**.

Try it online! Or verify all test cases.

### Explanation

Consider inputs `[1,4; 3 1]`, `[3,1,4,5; 6,3,1,4; 5,6,3,1]`. The stack is shown with the most recent element below.

```
Zy    % Implicit input: A. Push size as a vector of two numbers
      % STACK: [2 2]
YC    % Implicit input: B. Arrange sliding blocks of specified size as columns,
      % in column-major order
      % STACK: [3 6 1 3 4 1;
                6 5 3 6 1 3;
                1 3 4 1 5 4;
                3 6 1 3 4 1]
2M    % Push input to second to last function again; that is, A
      % STACK: [3 6 1 3 4 1;
                6 5 3 6 1 3;
                1 3 4 1 5 4;
                3 6 1 3 4 1],
               [1 4;
                3 1]
X:    % Linearize to a column vector, in column-major order
      % STACK: [3 6 1 3 4 1;
                6 5 3 6 1 3;
                1 3 4 1 5 4;
                3 6 1 3 4 1],
               [1;
                3;
                4;
                1]
=     % Test for equality, element-wise with broadcast
      % STACK: [0 0 1 0 0 1
                0 0 1 0 0 1;
                0 0 1 0 0 1;
                0 0 1 0 0 1]
XA    % True for columns containing all true values
      % STACK: [0 0 1 0 0 1]
s     % Sum. Implicit display
      % STACK: 2

```

# Answer
> 3 votes
# Dyalog APL, ~~6~~ 4 bytes

```
≢∘⍸⍷

```

This is nearly a builtin (thanks H.PWiz and ngn).

```
  ⍷       Binary matrix containing locations of left argument in right argument
≢∘⍸       Size of the array of indices of 1s

```

Alternative non-builtin:

```
{+/,((*⍺)≡⊢)⌺(⍴⍺)*⍵}

```

Dyadic function that takes the big array on right and subarray on left.

```
                  *⍵       exp(⍵), to make ⍵ positive.
    ((*⍺)≡⊢)⌺(⍴⍺)        Stencil;
                            all subarrays of ⍵ (plus some partial subarrays
                            containing 0, which we can ignore)
               ⍴⍺             of same shape as ⍺
     (*⍺)≡⊢                   processed by checking whether they're equal to exp(⍺).
                           Result is a matrix of 0/1.
   ,                     Flatten
 +/                      Sum.

```

Try it here.

# Answer
> 2 votes
# 05AB1E, 10 bytes

```
øŒεøŒI.¢}O

```

Try it online!

```
øŒεøŒI.¢}O     Full program. Takes 2 matrices as input. First B, then A.
øŒ             For each column of B, take all its sublists.
  ε     }      And map a function through all those lists of sublists.
   øŒ          Transpose the list and again generate all its sublists.
               This essentially computes all sub-matrices of B.
     I.¢       In the current collection of sub-matrices, count the occurrences of A.
         O     At the end of the loop sum the results.

```

# Answer
> 2 votes
# Uiua, <sup> ~~4~~ </sup> 3 bytes

```
⧻⊚⌕

```

Try it!

-1 thanks to Razetime

```
⧻⊚⌕
  ⌕  # find
 ⊚   # where
⧻    # length

```

# Answer
> 1 votes
# Charcoal, ~~36~~ 27 bytes

```
ＩΣ⭆η⭆ι⁼θＥ✂ηκ⁺Ｌθκ¹✂νμ⁺Ｌ§θ⁰μ¹

```

Try it online! Much shorter now that Equals works for arrays again. Explanation:

```
   η                        Input array B
  ⭆                         Mapped over rows and joined
     ι                      Current row
    ⭆                       Mapped over columns and joined
       θ                    Input array A
      ⁼                     Is equal to
          η                 Input array B
         ✂                  Sliced
                ¹           All elements from
           κ                Current row index to
             Ｌ              Length of
              θ             Input array A
            ⁺               Plus
               κ            Current row index
        Ｅ                   Mapped over rows
                  ν         Current inner row
                 ✂          Sliced
                          ¹ All elements from
                   μ        Current column index to
                     Ｌ      Length of
                       θ    Input array A
                      §     Indexed by
                        ⁰   Literal 0
                    ⁺       Plus
                         μ  Current column index
 Σ                          Digital sum
Ｉ                           Cast to string
                            Implicitly printed

```

# Answer
> 1 votes
# Clean, ~~118~~ ~~97~~ 95 bytes

```
import StdEnv,Data.List
?x=[transpose y\\z<-tails x,y<-inits z]
$a b=sum[1\\x<- ?b,y<- ?x|y==a]

```

Try it online!

# Answer
> 1 votes
# JavaScript (ES6), 93 bytes

Takes input as `(A)(B)`.

```
a=>b=>b.map((r,y)=>r.map((_,x)=>s+=!a.some((R,Y)=>R.some((v,X)=>v!=(b[y+Y]||0)[x+X]))),s=0)|s

```

Try it online!

# Answer
> 1 votes
# , 95 bytes

```
function(A,B,x=dim(A),D=dim(B)-x){for(i in 0:D)for(j in 0:D[2])F=F+all(B[1:x+i,1:x[2]+j]==A);F}

```

Try it online!

# Answer
> 1 votes
# Python 2, 101 bytes

```
lambda a,b:sum(a==[l[j:j+len(a[0])]for l in b[i:i+len(a)]]for i,L in e(b)for j,_ in e(L))
e=enumerate

```

Try it online!

# Answer
> 1 votes
# Nekomata \+ `-n`, 5 bytes

```
qŤqŤ=

```

Attempt This Online!

```
qŤqŤ=
q       Choose a contiguous subsequences
 Ť      Transpose
  q     Choose a contiguous subsequences
   Ť    Transpose
    =   Check equality

```

`-n` counts the number of solutions.

# Answer
> 0 votes
# Python 2, 211 bytes

```
a,b=input()
l,w,L,W,c=len(a),len(a[0]),len(b),len(b[0]),0
for i in range(L):
 for j in range(W):
  if j<=W-w and i<=L-l:
   if not sum([a[x][y]!=b[i+x][j+y]for x in range(l)for y in range(w)]):
    c+=1
print c

```

Try it online!

Fairly straightforward. Step through the larger matrix, and check if the smaller matrix can fit.

The only even slightly tricky step is the list comprehension in the 6th line, which relies on Python's conventions for mixing Boolean and integer arithmetic.

# Answer
> 0 votes
# Groovy, 109 bytes

```
{a,b->(0..<b.size()).sum{i->(0..<b[i].size()).count{j->k=i-1
a.every{l=j;k++
it.every{(b[k]?:b)[l++]==it}}}}}

```

Try it online!

# Answer
> 0 votes
# Scala, 151 bytes

```
(a,b)=>{(0 to b.size-a.size).map(i=>(0 to b(0).size-a(0).size).count(j=>{var k=i-1
a.forall(c=>{var l=j-1;k+=1
c.forall(d=>{l+=1
b(k)(l)==d})})})).sum}

```

Try it online!

---
Tags: code-golf, array, matrix, search
---