title: Parity of sum of other elements

text:
# Question
Title: Parity of sum of other elements
# Task

Given an array of positive integers, replace each element with the parity of the sum of the other elements. The array is guaranteed to have **at least** 2 elements.

# Definition

* Parity: whether a number is odd or even.

# Example

For the array `[1,2,3,1]`:

* Replace `1` with the parity of `2+3+1`, i.e. `even`.
* Replace `2` with the parity of `1+3+1`, i.e. `odd`.
* Replace `3` with the parity of `1+2+1`, i.e. `even`.
* Replace `1` with the parity of `1+2+3`, i.e. `even`.

Output: `[even, odd, even, even]`

# Input

An array of positive integer.

You may take it as a proper array, or as a linefeed-separated string of positive integers.

You may assume that the array and the values inside are within the handling capability of your language.

# Output

An array of **two consistent values**, one representing `odd`, one representing `even`.

You may output it as a linefeed-separated string of the two values.

# Testcases

Inputs:

```
[1, 2, 3, 1]
[1, 2, 3, 2, 1]
[2, 2]
[100, 1001]

```

Outputs:

```
[even, odd, even, even]
[even, odd, even, odd, even]
[even, even]
[odd, even]

```

Note: you may choose other consistent values other than `odd` and `even`.

# Scoring

This is . Shortest answer in bytes wins.

Standard loophole applies.

# Answer
# Jelly, 3 bytes

```
+SḂ

```

Try it online!

### How it works

```
+SḂ  Main link. Argument: A (array)

 S   Compute the sum of A.
+    Add the sum to each element of A.
     Using _ (subtraction) or ^ (bitwise XOR) would also work.
  Ḃ  Bit; compute the parity of each resulting integer.

```
> 17 votes

# Answer
# JavaScript (ES6), ~~38 36~~ 32 bytes

```
a=>a.map(b=>eval(a.join`+`)-b&1)

```

Uses `0` for even and `1` for odd.

# Test

```
f=
a=>a.map(b=>eval(a.join`+`)-b&1)
console.log(f([1, 2, 3, 1]))
console.log(f([1, 2, 3, 2, 1]))
console.log(f([100, 1001]))
```
> 8 votes

# Answer
## Haskell, 20 bytes

```
f x=odd.(sum x-)<$>x

```

Uses `True` for odd values and `False`for even values.

Try it online!

Subtract each element from the sum of the list and test if it's odd.

`f` turned to pointfree has also 20 bytes: `map=<<(odd.).(-).sum`.
> 8 votes

# Answer
# 05AB1E (legacy), ~~4~~ 3 bytes

```
O^È

```

Try it online!

```
O   # Sum
 ^  # XOR with (implicit) input
  È # Print 1 for even / 0 for odd

```
> 6 votes

# Answer
# MATL, ~~5~~, 4 bytes

```
ts-o

```

Try it online!

*One byte saved thanks to Dennis!*

This gives '1' for odd and '0' for even. Explanation:

```
t       % Duplicate the input
 s      % Get the sum of the input
  -     % Subtract it from the original input
   o    % Get the parity of each element

```
> 6 votes

# Answer
## Alice, ~~31~~ 28 bytes

```
/O.HQ\d$K@
\i#\ /d2-&+!w?+2%

```

Try it online!

The input format doesn't matter as long as the integers are separated. The output format is linefeed-separated.

The layout is probably still not optimal but I haven't found a way to shorten this further yet.

### Explanation

```
/     Reflect to SE. Switch to Ordinal.
i     Read all input as a string.
      Reflect off bottom boundary. Move to NE.
.     Duplicate the input string.
      Reflect off top boundary. Move to SE.
\     Reflect to N. Switch to Cardinal.
H     Implicitly convert the top copy of the input to the integers it
      contains and take the absolute value of the top-most one. (Taking
      the absolute value doesn't do anything, but we need the implicit
      conversion to integers.)
      The IP wraps back to the second line.
\     Reflect to SE. Switch to Ordinal.
      Immediately reflect off bottom boundary. Move to NE.
Q     Reverse the stack (this converts the integers back to strings but
      that's irrelevant). After this, we end up with all the individual
      integers on the bottom of the stack in reverse order and the other
      copy of the input string with all integers on top.
      Reflect off top boundary. Move to SE.
/     Reflect to E. Switch to Cardinal.
d     Push the stack depth, which is one more than the number of list
      elements (due to the other input string on the stack).
2-    Subtract 2.
&+    Run + that many times, which implicitly converts the second string
      to the integers it contains and then adds up all the list elements.
!     Store the sum on the tape.
w     Push the current IP position to the return address stack. This
      lets us return here repeatedly to implement a loop.

  ?+    Retrieve the input sum from the tape and add it to the current
        element.
  2%    Compute its parity. Other ways to do this are 1A and 0x. 2F would
        also work but it gives 0/2 instead of 0/1.
        The IP wraps the first column of the grid.
  \     Reflect to NE. Switch to Ordinal. The IP bounces diaginally up
        and down until it hits the next \.
  O     Implicitly convert the current parity to a string and print it
        with a trailing linefeed.
  #     Skip the next command (the H).
  \     Reflect to E. Switch to Cardinal.
  d     Push the stack depth. This is zero when we're done.
  $     Skip the next command if the stack depth is indeed zero, which
        exits the loop.

K     Jump to the return address on top of the return address stack without
      popping it (so that the next K will jump there again).

@     Terminate the program.

```
> 6 votes

# Answer
# Pyth, ~~7~~ 6 bytes

```
mi2-sQ

```

*-1 Byte thanks to @KZhang*

Outputs 1 for odd, 2 for even.

Try it!

### Explanation

```
m%-sQd2
m      Q    # For each element in the (implicit) input list
   sQ       # Take the sum of all the elements
  -  d      # subtract that element, so that we now have the sum of the other elements
 %    2     # modulo 2; 1=off, 0=even

```
> 6 votes

# Answer
# Python 2, ~~33~~ 31 bytes

-2 bytes thanks to Leaky Nun

```
lambda x:[sum(x)-z&1for z in x]

```

Try it online!
> 5 votes

# Answer
# R, 21 bytes

```
(sum(n<-scan())-n)%%2

```

reads the list from stdin and returns 0 for even, 1 for odd. binds the input to the variable `n` inside the call to `sum` instead of calling it outside, i.e., `n=scan();(sum(n)-n)%%2`

Try it online!
> 5 votes

# Answer
# , 6 bytes

```
2|]++/

```

Try it online!
> 4 votes

# Answer
## Mathematica, 13 bytes

```
#+Tr@#&/*OddQ

```

or

```
OddQ[#+Tr@#]&

```
> 3 votes

# Answer
## Clojure, 30 bytes

```
#(for[i %](odd?(apply - i %)))

```

Substracts all values from each value in turn, for example with input `[a b c d]` the 2nd calculated value is `b - a - b - c - d` = `-(a + c + d)`. Output is `false` for even and `true` for odd.

But you might as well use `+` and calculate each subsequent term twice so it doesn't affect the parity.
> 3 votes

# Answer
# CJam, 10 bytes

```
{_:+f+1f&}

```

This is an anonymous block (function) that takes the input from the stack and replaces it by the output.

Try it online!

### Explanation

Consider input `[1 2 3 1]`.

```
{         e# Begin block
          e#   STACK: [1 2 3 1]
  _       e#   Duplicate
          e#   STACK: [1 2 3 1], [1 2 3 1]
  :+      e#   Fold addition over the array: compute its sum
          e#   STACK: [1 2 3 1], 7
  f+      e#   Map addition over the array with extra parameter
          e#   STACK: [8 10 11 8]
  1       e#   Push 1
          e#   STACK: [8 10 11 8], 1
  f&      e#   Map bit-wise "and" over the array with extra parameter
          e#   STACK: [0 0 1 0]
}         e# End block

```
> 3 votes

# Answer
# APL (Dyalog Unicode), ~~19~~ 7 bytes

*Golfed 12 bytes thanks to @Adám*

```
2|+/-¨⊢

```

Try it online!
> 3 votes

# Answer
# Japt, 7 bytes

```
£x +X&1

```

Try it online!

### Explanation

```
 £   x +X&1
 mX{ x +X&1}  // Ungolfed
UmX{Ux +X&1}  // Variable introduction

UmX{       }  // Replace each item in the input array with
         &1   //   the parity of
    Ux        //   the sum of the input array
       +X     //   plus X.
              // Implicit: output result of last expression

```
> 2 votes

# Answer
# PHP, 50 Bytes

Online Versions

1 for odd , 0 for even

Output as string separated with `_`

```
<?foreach($_GET as$v)echo array_sum($_GET)-$v&1,_;

```

# PHP, 72 Bytes

Output as array use `array_map`

```
<?print_r(array_map(function($v){return array_sum($_GET)-$v&1;},$_GET));

```
> 2 votes

# Answer
# Perl 5, 31 bytes

```
sub{map$x+=$_,@_;map$x-$_&1,@_}

```

Outputs `1` for odd and `0` for even.
> 2 votes

# Answer
# Retina, ~~40~~ 38 bytes

```
\d+
¶$` $'
^¶

\d+
$*
+` |11

%M`1
¶

```

Try it online! Outputs 1 for odd and 0 for even. Explanation: The first two lines duplicate the input once for each number in the input, but without the element itself. This creates an extra blank line which is then deleted. The input is then converted from decimal to unary, the spaces are deleted and the parity computed. Even parity is then converted to zero and the results joined back in to one line. Edit: Saved 2 bytes thanks to @FryAmTheEggman. I tried some other versions which are conceptually more pleasing but which take far too many bytes to express:

```
\d\B

T`2468O`00001
T`d`10`^([^1]*1[^1]*1)*[^1]*1[^1]*$

```

Changes all inputs to their parity, then flips all their parities if the total has odd parity.

```
\d+
$*
^.*
$&¶$&
 (?=.*$)

11

\B
0
T`d`10`.*¶1
¶0

```

Sums a duplicate of the input, then takes the parity of everything, then inverts the parities if the sum is odd, then deletes the sum again.
> 2 votes

# Answer
# C, ~~68~~ 62 bytes

```
i;s;f(c,l)int*l;{while(i<c)s+=l[i++];while(i)l[--i]=s-l[i]&1;}

```

1 for odd, 0 for even

**Detailed** *Try Online*

```
f(int c, int * l)
{
    int i = 0, s = 0;

    while(i < c)
    {
        s = s + l[i];
        i = i + 1;
    }

    // assert(i == c)

    while(i > 0)
    {
        i = i - 1;
        l[i] = s - l[i]&1;
    }
}

```
> 2 votes

# Answer
# Ohm, 4 bytes

```
DΣ-é

```

Try it online!

Basically a direct port of the MATL and 05AB1E answers. Uses `true` for even and `false` for odd.
> 2 votes

# Answer
# Clojure(Script), 36 bytes

Output is `true` for odd and `false` for even. Both output and input are sequences.

```
(fn[l](map #(odd?(-(apply + l)%))l))

```
> 2 votes

# Answer
# Julia 1.0, 17 bytes

```
x->(sum(x).-x).%2

```

Try it online!
> 2 votes

# Answer
# k, 9 bytes

```
{2!x-+/x}

```

The output is a `1` for `odd`, and a `0` for even. Try it online.

Converted to pseudocode, it would be:

```
for number in x:
    yield (number - sum(x)) % 2

```
> 1 votes

# Answer
# Scala, 19 bytes

```
x=>x.map(x.sum-_&1)

```

Try it online!
> 1 votes

# Answer
# Java, ~~81~~ 78 bytes

3 bytes thanks to Kevin Cruissen

```
void f(int[]a){int s=0,i=a.length;for(int x:a)s+=x;for(;i-->0;a[i]=s-a[i]&1);}

```

Try it online!

Modifies the array in-place.
> 1 votes

# Answer
# Brain-Flak, ~~94~~ ~~68~~ 66 bytes

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

```

Try it online!

This seems a little long for the task. There might be a more convenient way to do this.

## Explanation

First we calculate the sum of the stack with:

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

```

The we go through the entire stack adding that result to each element and determine the pairity

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

```

---

This uses a pretty cool mod 2 algorithm I came up with for this challenge.

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

```

This pushes 1 under the input decrements until the input reaches zero each time performing `1-n` to the 1 we placed earlier, it then removes the input.
> 1 votes

# Answer
# Wise, ~~54~~ 52 bytes

```
::^:??[:!^:?^:!^:?^?]|!::^??[!:?^:><^!:?^:!^:?^?]!&|

```

Try it online!

## Explanation

This code would be a lot shorter if it didn't take so many bytes to swap the top two elements. The current record is

```
:?^:!^:?^!

```

This unfortunately constitutes the majority of the code.

---

First we take the XOR sum of the stack

```
::^:??[:!^:?^:!^:?^?]|!

```

We then XOR this with every element and the element with it last bit zeroed

```
::^??[!:?^:><^!:?^:!^:?^?]!&|

```
> 1 votes

# Answer
# Swift - 55 bytes

*Finally beats C!* **Also, 0 for even, 1 for odd**

```
func g(a:[Int]){for i in a{print((a.reduce(0,+)-i)%2)}}

```

A function, with usage: `g(a: [1,2,3,2,1] // => 0 1 0 1 0`

**Check it out!**
> 1 votes

# Answer
# Axiom, 45 bytes

```
f(a)==[(reduce(+,a)-a.j)rem 2 for j in 1..#a]

```

no check for input type, possible recalculation of sum "a" each element...tests

```
(27) -> [[a,f(a)] for a in [[1,2,3,1], [1,2,3,2,1], [2,2], [100, 1001] ]]
   (27)
   [[[1,2,3,1],[0,1,0,0]], [[1,2,3,2,1],[0,1,0,1,0]], [[2,2],[0,0]],
    [[100,1001],[1,0]]]

```
> 1 votes

# Answer
# AWK, 64 bytes

```
{for(i=0;++i<=NF;print s[i]%2)for(j=0;++j<=NF;)if(i!=j)s[i]+=$j}

```

Try it online!

Outputs a `0` for even sums and `1` for odd sums separated by newlines. The only even slightly out-of-the-box thinking was placing the `print` command inside the `for` "increment" step. I tried a few "clever" ways to print, but they didn't save bytes.

Just for giggles, if you don't want newlines:

```
{for(i=0;++i<=NF;m=m,s[i]%2)for(j=0;++j<=NF;)if(i!=j)s[i]+=$j}1

```

which has the same byte-count as above, but is a bit more obtuse.
> 1 votes

# Answer
# Japt, 6 bytes

```
®nUx)v

```

Try it

```
®nUx)v     :Implicit input of array U
®          :Map
 n         :Subtract from
  Ux       :  Sum of U
    )      :End subtraction
     v     :Divisible by 2?

```
> 1 votes

# Answer
# Python 2, 32 bytes

```
map(lambda x:sum(s)-x&1,input())

```

Try it online!
> 1 votes

# Answer
# TI-Basic, 9 bytes

```
fPart(.5(sum(Ans)+Ans

```

Takes input in `Ans`. Output is stored in `Ans` and displayed. Outputs `.5` for odd numbers and `0` for even ones.
> 1 votes

# Answer
# Fig, \\$4\log\_{256}(96)\approx\\$ 3.292 bytes

```
%2-S

```

`1` for odd, `0` for even.

Try it online!

```
%2-S
   S  # sum
  -   # minus each item of input array
%2    # mod each by 2

```
> 1 votes

# Answer
## C#, ~~142~~ 121 bytes

---

### Data

* **Input** An array of 32-byte signed integers
* **Output** An array of 32-byte signed integers where `0` represents `even` and `1` represents `odd`

---

### Golfed

```
(int[] i)=>{var l=i.Length;var o=new int[l];var s=0;foreach(int x in i)s+=x;for(int x=0;x<l;x++)o[x]=s-i[x]&1;return o;};

```

---

### Ungolfed

```
( int[] i ) => {
   var l = i.Length;
   var o = new int[ l ];
   var s = 0;

   foreach( int x in i )
      s += x;

   for( int x = 0; x < l; x++ )
      o[ x ] = s - i[ x ] & 1;

   return o;
};

```

---

### Ungolfed readable

```
// Takes an array of Int32 objects ( 32-byte signed integers )
( int[] i ) => {
   // Save the length of the array to save on byte count
   var l = i.Length;

   // Initialize an array with the same size the the input array
   var o = new int[ l ];

   // Initialize a var to store the sum of all numbers
   var s = 0;

   // Cycle through every number from the input
   foreach( int x in i )

      // Sum all of them
      s += x;

   // Cycle again through every number
   for( int x = 0; x < l; x++ )

      // Subtracts the number for the sum
      //    and performs a bitwise and
      o[ x ] = s - i[ x ] & 1;

   // Return the array with odds and evens
   return o;
};

```

---

### Full code

```
using System;
using System.Collections.Generic;

namespace Namespace {
   class Program {
      static void Main( String[] args ) {
         Func<Int32[], Int32[]> f = ( int[] i ) => {
            var l = i.Length;
            var o = new int[ l ];
            var s = 0;

            foreach( int x in i )
               s += x;

            for( int x = 0; x < l; x++ )
               o[ x ] = s - i[ x ] & 1;

            return o;
         };

         List<Int32[]>
            testCases = new List<Int32[]>() {
               new Int32[] { 1, 2, 3, 1 },
               new Int32[] { 1, 2, 3, 2, 1 },
               new Int32[] { 2, 2 },
               new Int32[] { 100, 1001 },
            };

         foreach( Int32[] testCase in testCases ) {
            Console.WriteLine( $" Input: {String.Join( ",", testCase )}\nOutput: {string.Join( ",", f( testCase ) )}\n" );
         }

         Console.ReadLine();
      }
   }
}

```

---

### Releases

* **v1.1** \- `-21 bytes` \- Changed the output to an array of `int`s to reduce the byte count thanks to Arthur Rey's comment. Changed the ternary verification to a bitwise operation, thanks to Cyoce's suggestion
* **v1.0** \- `142 bytes` \- Initial solution.

---

### Notes

* None
> 0 votes

# Answer
# Ruby, ~~47~~ ~~33~~ 31 Bytes

```
->a{a.map{|x|a.inject(:+)-x&1}}

```

It `map`s through each element, determining the parity of the sum of all elements minus the current element (thus making it 0).
> 0 votes

# Answer
# Perl 6, 16 bytes

```
{(.sum X-$_)X%2}

```

Try it

This results in a list where `0` represents `even` and `1` represents `odd`.

## Expanded:

```
{  # bare block lambda with implicit parameter $_
  (
    .sum  # the sum of the input array
    X[-]  # crossed using &infix:« - »
    $_    # the input

    # this produces the sum of the other elements

  )
  X[%]    # cross that using &infix:« % » the modulus operator
  2       # with 2
}

```
> 0 votes

# Answer
# Factor \+ `math.unicode`, ~~32~~ 27 bytes

```
[ dup Σ v-n [ odd? ] map ]

```

Try it online!

Outputs `t` for odd and `f` for even.

```
               ! { 1 2 3 1 }
dup            ! { 1 2 3 1 } { 1 2 3 1 }
Σ              ! { 1 2 3 1 } 7
v-n            ! { -6 -5 -4 -6 }
[ odd? ] map   ! { f t f f }

```
> 0 votes

# Answer
# Arturo, 24 bytes

```
$[a][map a=>[%&-∑a 2]]

```

Try it
> 0 votes

# Answer
# Thunno 2, 3 bytes

```
S+ɗ

```

Try it online!

#### Explanation

```
S+ɗ  # Implicit input
S    # Sum the input
 +   # Add to input
  ɗ  # Parity of each
     # Implicit output

```
> 0 votes

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


# Question
Title: Smallest palindrome divisible by the input
Given a positive integer `N`, output the smallest positive integer such that this number is a palindrome (i.e. is its own reverse) and is divisible by `N`.

The palindrome (i.e. the output) must not need a leading zero to be a palindrome, e.g. `080` is not the valid answer for `16`.

The input will never be a multiple of 10, because of the previous reason.

Your program may take as much time as necessary, even if in practice it would be way too long to output the answer.

### Inputs and outputs

* You may take the input through `STDIN`, as a function argument, or anything similar.
* You may print the output to `STDOUT`, return it from a function, or anything similar.
* Inputs and outputs must be in the decimal base.

### Test cases

```
N        Output
1        1
2        2
16       272
17       272
42       252
111      111
302      87278
1234     28382

```

### Scoring

This is , so the shortest answer in bytes wins.

# Answer
# 2sable / 05AB1E, 6 / 7 bytes

**2sable**

```
[DÂQ#+

```

**Explanation**

```
[         # infinite loop
 D        # duplicate current number
  Â       # bifurcate
   Q#     # if the number is equal to its reverse, break loop
     +    # add input
          # implicitly print

```

Try it online

**05AB1E**

```
[DÂQ#¹+

```

The difference to the 2sable code is that input is only implicit once in 05AB1E, so here we need `¹` to get the first input again.

Try it online

Saved 1 byte with 2sable as suggested by Adnan
> 9 votes

# Answer
# Haskell, ~~45~~ ~~37~~ 34 bytes

```
(+)>>=until((reverse>>=(==)).show)

```
> 14 votes

# Answer
# Pyth, 7 bytes

```
*f_I`*Q

```

Try it online: Demonstration

### Explanation

```
*f_I`*QT)Q   implicit endings, Q=input number
 f      )    find the first number T >= 1, which satisfies:
     *QT        product of Q and T
    `           as string
  _I            is invariant under inversion (=palindrom)
*        Q   multiply this number with Q and print

```
> 13 votes

# Answer
# **Java, ~~164~~ ~~159~~ ~~126~~ ~~108~~ 94 bytes**

Golfed version:

```
int c(int a){int x=a;while(!(x+"").equals(new StringBuffer(x+"").reverse()+""))x+=a;return x;}

```

Ungolfed version:

```
int c(int a)
{
    int x = a;
    while (!(x + "").equals(new StringBuffer(x + "").reverse() + ""))
        x += a;
    return x;
}

```

Shoutout to Emigna and Kevin Cruijssen for contributing improvements and cutting the bytes almost in half :)
> 7 votes

# Answer
**C#, 103 80 Bytes**

```
int f(int p){int x=p;while(x+""!=string.Concat((x+"").Reverse()))x+=p;return x;}

```

**Ungolfed**

```
int f(int p)
{
   int x = p;
   while (x + "" != string.Concat((x + "").Reverse()))
      x += p;
   return x;
}

```
> 7 votes

# Answer
# Brachylog, 8 bytes

```
:L#>*.r=

```

Try it online! (around 5 seconds for `1234`)

Verify all testcases. (around 20 seconds)

```
:L#>*.r=
?:L#>*.r=.   Implicitly filling Input and Output:
             Input is prepended to every predicate,
             Output is appended to every predicate.

?:L  *.      Input*L is Output,
  L#>        L is positive,
      .r .   Output reversed is Output,
        =.   Assign a value to Output.

```
> 6 votes

# Answer
# Python 2, 46 bytes

```
f=lambda x,c=0:`c`[::-1]==`c`and c or f(x,c+x)

```

Ideone it!

Recursive solution with `c` as counter.

The case for `0` is interesting, because although `c=0` satisfies the palindrome condition, it would not be returned, because `ccc and 0 or xxx` always returns `xxx`.
> 6 votes

# Answer
# Javascript (ES6), ~~55~~ 51 bytes

**4 bytes thanks to Neil.**

```
f=(x,c=x)=>c==[...c+""].reverse().join``?c:f(x,x+c)
```

```
<input type=number min=1 oninput=o.textContent=this.value%10&&f(+this.value)><pre id=o>
```
> 5 votes

# Answer
# PHP, 39 bytes

```
while(strrev($i+=$argv[1])!=$i);echo$i;

```
* Takes number N as argument $argv\[1\];
* `;` after while to do nothing
* `strrev` return string backward

Same length with for-loop

```
for(;strrev($i+=$argv[1])!=$i;);echo$i;

```
> 5 votes

# Answer
## Pyke, ~~11~~ 9 bytes

```
.f*`D_q)*

```

Try it here!
> 4 votes

# Answer
# R, ~~117~~ ~~113~~ ~~109~~ 101 bytes

```
D=charToRaw;P=paste;S=strtoi;a=P(i<-scan()+1);while(!all(D(a)==rev(D(a))&&S(a)%%i==0)){a=P(S(a)+1)};a

```

**Ungolfed**

```
i<-scan()        #Takes the input

D=charToRaw      #Some aliases
P=paste
S=strtoi
a=P(i+1)         #Initializes the output

while(!(all(D(a)==rev(D(a)))&&(S(a)%%i==0))) #While the output isn't a palindrom and isn't
                                             #divisible by the output...
    a=P(S(a)+1)

a

```

`all(charToRaw(a)==rev(charToRaw(a)))` checks if at each position of `a` the value of `a` and its reverse are the same (i.e., if `a` is palindromic).
It might be possible to golf out some bytes by messing around with the `types`.
> 4 votes

# Answer
# Actually, ~~15~~ 14 bytes

Asked to answer by Leaky Nun. Golfing suggestions welcome. Try it online!

```
╖2`╜*$;R=`╓N╜*

```

**Ungolfing**

```
          Implicit input n.
╖         Save n in register 0.
2`...`╓   Push first 2 values where f(x) is truthy, starting with f(0).
  ╜*$       Push register 0, multiply by x, and str().
  ;R        Duplicate str(n*x) and reverse.
  =         Check if str(n*x) == reverse(str(n*x)).
          The map will always result in [0, the x we want].
N         Grab the last (second) value of the resulting list.
╜*        Push n and multiply x by n again.
          Implicit return.

```
> 4 votes

# Answer
# C, ~~217~~ 189 bytes

Standalone version :

```
int a(char*b){int c=strlen(b);for(int i=0;i<c/2;i++)if(b[i]!=b[c-i-1])return 0;}int main(int e,char **f){int b,c;char d[9];b=atoi(f[1]);c=b;while(1){sprintf(d,"%d",c);if(a(d)&&(c/b)*b==c)return printf("%d",c);c++;}}

```

Call to a function version :

```
int s(char*a){int b=strlen(a);for(int i=0;i<b/2;i++)if(a[i]!=a[b-i-1])return 0;}int f(int a){int b;char c[9];b=a;while(1){sprintf(c,"%d",b);if(s(c)&&(b/a)*a==b)return printf("%d",b);b++;}}

```

Ungolfed :

```
#include <stdlib.h>
#include <string.h>
#include <stdio.h>

int check_palindrome(char *str) {
  int length = strlen(str);

  for (int i = 0; i < length / 2; i++) {
    if (str[i] != str[length - i - 1])
      return 0;
  }
  return 1;
}

int main(int argc, char **argv) {
  int number;
  int pal;
  char string[15];

  number = atoi(argv[1]);
  pal = number;
  while (1) {
    sprintf(string, "%d", pal);
    if (check_palindrome(string) && (pal / number) * number == pal)
      {
        printf("%d\n", pal);
        return 1;
      }
    pal++;
  }
  return 0;
}

```

Call to a function ungolfed :

```
int s(char *a) {
  int b = strlen(a);

  for (int i = 0; i < b / 2; i++) {
    if (a[i] != a[b - i - 1])
      return 0;
  }
  return 1; //We can remove it, it leads to a undefined behaviour but it works
}

int f(int a) {
  int b;
  char c[9];

  b = a;
  while (1) {
    sprintf(c, "%d", b);
    if (s(c) && (b / a) * a == b)
      {
        printf("%d\n", b); //no need for the \n
        return 1; //just return whatever printf returns, who cares anyway ?
      }
    b++;
  }
  return 0; //no need for that
}

```

I included the standalone version for historicity.

This is my first codegolf, any comment is welcome !
> 4 votes

# Answer
# Haskell, ~~64 63~~ 56 bytes

```
x!n|mod x n==0,s<-show x,reverse s==s=x|y<-x+1=y!n
(1!)

```

Call with `(1!)16` or simply `1!16`. Try it on Ideone.
> 3 votes

# Answer
**VBSCRIPT, 47 bytes**

```
do:i=i+1:a=n*i:loop until a=eval(strreverse(a))

```

**ungolfed**

```
do                     #starts the loop
i=i+1                  #increments i, we do it first to start at 1 instead of 0
a=                     #a is the output
n*i                    #multiply our input n by i
loop until
a=eval(strreverse(a))  #end the loop when our output is equal to its reverse

```
> 3 votes

# Answer
# Perl, 25 bytes

Includes +2 for `-ap`

Run with the input on STDIN:

```
palidiv.pl <<< 16

```

`palidiv.pl`:

```
#!/usr/bin/perl -ap
$_+="@F"while$_-reverse

```
> 3 votes

# Answer
# S.I.L.O.S, 109 bytes

```
readIO
n = 0
lbla
n + i
a = n
r = 0
lblb
m = a
m % 10
r * 10
r + m
a / 10
if a b
r - n
r |
if r a
printInt n

```

Try it online!
> 3 votes

# Answer
# Japt, 14 bytes

```
V±U s w ¥V?V:ß

```

Try it online!

Thank you ETHproductions for the help! :)
> 3 votes

# Answer
# MATL, 10 bytes

```
0`G+tVtP<a

```

Try it online!

```
0      % Push 0
`      % Do...while
  G+   %   Add the input. This generates the next multiple of the input
  tV   %   Duplicate, convert to string
  tP   %   Duplicate, reverse
  <a   %   Is any digit lower than the one in the reverse string? This is the
       %   loop condition: if true, the loop proceeds with the next iteration
       % End do...while
       % Implicitly display

```
> 2 votes

# Answer
# MATLAB, 76 bytes

```
function s=p(n)
f=1;s='01';while(any(s~=fliplr(s))) s=num2str(n*f);f=f+1;end

```

Call format is `p(302)` result is a string.

Nothing clever here. It does a linear search, using the `num2str()` and `fliplr()` functions.

This ugly arrangement is a touch shorter than using a `while(1) ... if ... break end` pattern.

Ungolfed

```
function s = findFirstPalindromeFactor(n)
  f = 1;                        % factor
  s = '01';                     % non-palindromic string for first try
  while( all(s ~= fliplr(s)) )  % test s not palindrome
    s = num2str( n * f );       % factor of input as string
    f = f + 1;                  % next factor
  end

```
> 2 votes

# Answer
## PowerShell v2+, 72 bytes

```
for($i=$n=$args[0];;$i+=$n){if($i-eq-join"$i"["$i".Length..0]){$i;exit}}

```

Long because of how reversing is handled in PowerShell -- not very well. ;-)

Takes input `$args[0]`, stores into `$i` (our loop variable) and `$n` (our input). Loops infinitely, incrementing `$i` by `$n` each time (to guarantee divisibility).

Each iteration, we check whether `$i` is a palindrome. There's some trickery happening here, so let me explain. We first take `$i` and stringify it with `"$i"`. That's then array-indexed in reverse order `["$i".length..0]` before being `-join`ed back into a string. That's fed into the right-hand side of the `-eq`uality operator, which implicitly casts the string back into an `[int]`, since that's the left-hand operand. Note: this casting does strip any leading zeros from the palindrome, but since we're guaranteed the input isn't divisible by `10`, that's OK.

Then, `if` it is a palindrome, we simply place `$i` onto the pipeline and `exit`. Output is implicit at the end of execution.

### Test Cases

```
PS C:\Tools\Scripts\golfing> 1,2,16,17,42,111,302,1234|%{"$_ -> "+(.\smallest-palindrome-divisible-by-input.ps1 $_)}
1 -> 1
2 -> 2
16 -> 272
17 -> 272
42 -> 252
111 -> 111
302 -> 87278
1234 -> 28382

```
> 2 votes

# Answer
## Mathematica, 49 bytes

```
(c=#;Not[PalindromeQ@c&&c~Mod~#==0]~While~c++;c)&

```

Starts the search at `c = N`, and increments `c` if not a palindrome and not divisible by `N`. When conditions are met, outputs `c`.
> 2 votes

# Answer
# Jelly, 12 bytes

```
¹µ+³ßµDU⁼Dµ?

```

Try it online!

Explanation:

This link takes 1 argument. The `µ`s split it into 4 parts. Starting from the last and moving left:

```
           ? The three parts in front of this are the if, else, and
             condition of a ternary expression.
      DU⁼D  This condition takes a number n as an argument. It converts
            n to an array of decimal digits, reverses that array, and
            then compares the reversed array to the decimalization of
            n (ie is n palindromic in decimal?)
  +³ß  This is the else. It adds the original input argument to n
       and then repeats the link with the new value of n.
¹  This is the if. It returns the value passed to it.

```
> 2 votes

# Answer
## Python 2, 66 65 bytes

`i` is input and `x` is (eventually) output

```
def f(i,x):
    y=x if x%i==0&&`x`==`x`[::-1]else f(i,x+1)
    return y

```

After scrolling through other answers I found a shorter Python 2 answer but I put the effort into my solution so might as well throw it here. ¯\\\_(ツ)\_/¯
> 2 votes

# Answer
# Elixir, 75 bytes

```
def f(p,a\\0),do: if'#{a+p}'|>Enum.reverse=='#{a+p}',do: a+p,else: f(p,a+p)

```
> 2 votes

# Answer
# REXX, 46 bytes

```
arg a
do n=a by a until reverse(n)=n
end
say n

```
> 2 votes

# Answer
## QBIC, 29 bytes

```
:{c=a*q~!c$=_f!c$||_Xc\q=q+1

```

Explanation:

```
:      Get cmd line param as number 'a'
{      DO
c=a*q  multiply 'a' by 'q' (which is 1 at the start of a QBIC program) and assign to 'c'
~      IF
!c$    'c' cast to string
=      equals
_f!c$| 'c' cast to string, the reversed
|      THEN
_Xc    Quit, printing 'c'
\q=q+1 ELSE increment q and rerun
       DO Loop is auto-closed by QBIC, as is the IF

```
> 2 votes

# Answer
# Python 2, 44 bytes

```
x=lambda n,m=0:m*(`m`==`m`[::-1])or x(n,m+n)

```

Try it online!

I know that the question was posted over six months ago, but this was shorter than any other Python submission.
> 2 votes

# Answer
# Perl 6, 35 bytes

```
->\N{first {$_%%N&&$_==.flip},N..*}

```

```
->\N{first {$_==.flip},(N,N*2...*)}

```

```
->\N{(N,N*2...*).first:{$_==.flip}}

```

## Explanation:

```
-> \N {
  # from a list of all multiples of the input
  # ( deduced sequence )
  ( N, N * 2 ... * )

  # find the first
  .first:

  # that is a palindrome
  { $_ == .flip }
}

```
> 1 votes

# Answer
## Perl 6, 39 bytes

```
my &f={first {.flip==$_},($_,2*$_...*)}

```

(33 not including the `my &f=`)
> 1 votes

# Answer
# Mathematica, ~~34~~ 28 bytes

```
#//.x_/;!PalindromeQ@x:>x+#&

```

Unnamed function taking a positive integer input and returning a positive integer. To be read as: "Starting with the function argument `#`, repeatedly replace any `x` we see that is not a palindrome with `x+#`." Yes, Virginia, there is a `PalindromeQ`! It only works in base 10 though.

Original submission:

```
(i=1;While@!PalindromeQ[++i#];i#)&

```
> 1 votes

# Answer
**C, not 83, 80 bytes**

```
f(n,b,k,z){for(b=1;;){for(z=0,k=b*n;z+=k%10,k/=10;z*=10);if(b++*n==z)return z;}}

```

For say the true i had seen in one other puzzle one programmer use the same algo number=swapped(number) =\> number is palindrome. How is possible to edit barred text?

```
#include <stdio.h>
main()
{unsigned  a[]={0,1,2,3,16,17,42,111,302,1234}, i;
 for(i=0;i<10;++i)
   printf("f(a[%u])=f(%u)=%u\n", i, a[i], f(a[i], 0, 0, 0));
 return 0;
}

/*
 f(a[0])=f(0)=0
 f(a[1])=f(1)=1
 f(a[2])=f(2)=2
 f(a[3])=f(3)=3
 f(a[4])=f(16)=272
 f(a[5])=f(17)=272
 f(a[6])=f(42)=252
 f(a[7])=f(111)=111
 f(a[8])=f(302)=87278
 f(a[9])=f(1234)=28382
 */

```
> 1 votes

# Answer
## dc, ~~85~~ ~~78~~ 76 bytes

```
[pq]sq?ddsI[dddZ0sR[1-dsD10r^rdsN10%*lR+sRlN10/lDd0<@]ds@xlR++=q+lIrlLx]dsLx

```

**Run:**

```
dc -f program.dc <<< "16"

```

**Output:**

```
272

```

**Previously submitted code and explanation:**

```
    # loads register 'q' with an exit function
[pq]sq
    # register '@' contains an iterative function to reverse a number (312 to 213),
#by calculating one coefficient at a time of the new base 10 polynomial
[1-dsD10r^rdsN10%*lR+sRlN10/lDd0<@]s@
    # register 'L' implements the logic. It iteratively compares the current value
#with the generated reversed one, exiting if equal, otherwise increments the value
#by N and repeats.
[dddZ0sRl@xlR++=q+lIrlLx]sL
    # the "main". It reads the input, then calls the solver function from 'L'.
?ddsIlLx

```
> 1 votes

# Answer
## Racket 174 bytes

```
(let((p?(λ(m)(equal? m(string->number(list->string(reverse(string->list(number->string m)))))))))
(let loop((N n))(cond[(and(p? N)(= 0(modulo N n)))N][else(loop(add1 N))])))

```

Ungolfed:

```
(define (f1 n)
  (let ((p? (λ (m)(equal? m
                          (string->number
                           (list->string
                            (reverse
                             (string->list
                              (number->string m)))))))))
    (let loop ((N n))
      (cond
        [(and (p? N) (= 0 (modulo N n))) N]
        [else (loop (add1 N))]
        ))))

```

Testing:

```
(f 1)
(f 2)
(f 16)
(f 17)
(f 42)
(f 111)
(f 302)
(f 1234)

```

Output:

```
1
2
272
272
252
111
87278
28382

```
> 1 votes

# Answer
# Ruby, 50 bytes

```
->n{a=n;while(s=a.to_s;s!=s.reverse)do a+=n;end;a}

```

It's horrible, I know.
> 1 votes

# Answer
# RProgN, 31 Bytes

```
►x=01¿1+]x*]''.S.\''.≡!}x*

```

## Explained

```
►x=01¿1+]x*]''.S.\''.≡!}x*  # ► Defines spaceless segment.
 x=                         # Define the input as x
   01                       # Push 0, 1 to the stack. 1 is used as a truthy for the while, 0 is our incrementing product.
     ¿                 }    # While the value on top of the stack (popped) is truthy.
      1+                    # Increment the product by one.
        ]x*                 # Duplicate the producter, multiply by the input.
           ]''.S.\''.≡!     # Check to see if the result is a palindrome.
           ]''.             # Push a duplicate of the multiplied number, convert to a string.
               S.           # Convert it to a stack and re-concatinate it. This reverses the string.
                 \''.≡!     # Flip the top two values, exposing the original product. Conver it to a string and test inverse equality.
                        x*  # Once the loop ends, the last number times the input will be a palindrome. Thus, do that.

```

The equality sugar was only added after the discovery of this challenge, as was the bugfix that allowed strings to be used in spaceless segments.

Try it Online!
> 1 votes

# Answer
## Clojure, 71 bytes

```
#(first(for[i(rest(range))i[(str(* % i))]:when(=(seq i)(reverse i))]i))

```

Just one long `for` with a two-step generation of `i`.
> 1 votes

# Answer
## Mathematica, 28 bytes

```
#//.x_/;!PalindromeQ@x:>x+#&

```

### Explanation

```
#//....

```

Repeatedly apply the following substitution to the input.

```
x_/;!PalindromeQ@x

```

Match a value which is not a palindrome.

```
...:>x+#

```

And replace that value with itself plus the input. This repeated substitution therefore searches through consecutive multiples of the input until it finds a palindrome.
> 1 votes

# Answer
# Japt, 12 bytes

```
_s ê¬©ZvU}a1

```

Try it

---

## Alternative

```
_¥sw «ZuU}aÄ

```

Try it
> 1 votes

# Answer
# Vyxal, 6 bytes

```
{:Ḃ≠|+

```

Try it Online!

Same as my Thunno 2 answer.

#### Explanation

```
{:Ḃ≠|+  # Implicit input
{       # While loop
 :      # (condition)  duplicate current number
   ≠    #              not equal to
  Ḃ     #              its reverse
    |+  # (body)  add the input
        # Implicit output

```
> 1 votes

# Answer
# Thunno 2, 5 bytes

```
(ḲQ;+

```

Try it online!

#### Explanation

```
(ḲQ;+  # Implicit input
(      # While loop
  Q    # (condition)  not equal to
 Ḳ     #              its reverse
   ;+  # (body)  add the input
       # Implicit output

```
> 0 votes

---
Tags: code-golf, number, palindrome, integer, division
---


title: Analyze the flow

text:
# Question
Title: Analyze the flow
On a toroidal square grid (you can wrap around) where each cell indicates one direction (`^` `>` `v` `<`) if we pick a cell and start to walk following these directions, we will eventually get stuck in a loop.
We may end up in a different loop, depending on our starting cell.

Not all the cells we encounter constitute our terminal loop: these are said to be *tributary* to that loop.

# Task

Given a square grid configuration, count for each loop \\$L\_i\\$:

* How many cells is it made up with? \\$n\_i\\$
* How many *tributary* cells does it have? \\$t\_i\\$

# Input

You choose the **set** of 4 printable characters or integers you'll use as directions.

* A square matrix having **set** elements as entries (can be a string)

# Output

* List of \\$(n\_i,t\_i)\\$ for each \\$L\_i\\$

The pairs can be in any order.

# Example

***input*** `urdrurllruuuulrududllurdu`

*-vivid color: loop
-pale color: tributary
In this configuration there are 3 loops (orange, blue, green) of lengths (2, 2, 6) with (0, 10, 5) tributary cells.*

***output*** `6 5 2 10 2 0`

```
Alternative inputs:
    1232124421111421313441231
    [[^,>,v,>,^],[>,<,<,>,^],[^,^,^,<,>],[^,v,^,v,<],[<,^,>,v,^]]

Valid outputs:
    2 10 2 0 6 5
    (2, 10), (6, 5), (2, 0)

Non valid outputs:
    10 2 2 0 6 5
    (0, 2), (10, 2), (6, 5)

```

This is , so the shortest code wins.

# Answer
# Java 10, ~~374~~ ~~371~~ 364 bytes

```
import java.util.*;m->{var L=new HashSet<Set>();int l=m.length,R=l*l,r,c,d;for(Set S;R-->0;S.add(r==R/l&c==R%l?-1:-2),L.add(S))for(S=new TreeSet(),r=R/l,c=R%l;S.add(r*l+c);r=(r-(d-d%3*d)/2+l)%l,c=(c-(d<2?1-2*d:0)+l)%l)d=m[r][c];for(Set z:L){if(z.remove(-1)){c=0;for(Set q:L)if(q.remove(-2)){if(q.containsAll(z))c++;q.add(-2);}System.out.println(z.size()+","+c);}}}

```

-10 bytes thanks to *@ceilingcat*.

Uses a matrix of integers `0,1,2,3` for `<,>,v,^` respectively.

Try it online.

**Explanation:**

```
import java.util.*;        // Required import for Set, HashSet, and TreeSet
m->{                       // Method with integer-matrix parameter and no return-type
  var L=new HashSet<Set>();//  Create a Set of Sets `L`, starting empty
  int l=m.length,          //  Set `l` to the dimensions of the input-matrix
      R=l*l,               //  Index integer `R` to loop over the cells
      r,c,                 //  Temp-integers `r,c` for the row and column
      d;                   //  Temp-integer `d` for the direction
  for(Set S;               //  Temp Set `S`, starting uninitialized
      R-->0                //  Loop `R` in the range (`l*l`, 0] over all cells:
      ;                    //     After every iteration:
       S.add(r==R/l&c==R%l?//      If `r,c` is still cell `R`:
              -1           //       Add -1 to Set `S`
             :             //      Else:
              -2),         //       Add -2 instead
       L.add(S))           //      And then add `S` to Set `L`
      for(S=new TreeSet(), //    Set `S` to a new empty sorted-Set
          r=R/l,c=R%l;     //    Set `r,c` to cell `R`
          S.add(r*l+c)     //    Add `r,c` as cell-index to Set `S` every iteration
                           //    and continue looping as long as it wasn't in `S` yet:
          ;                //      After every iteration:
           r=(r-(d-d%3*d)/2//       If `d` is 3:
                           //        Go to the cell above
                           //       Else-if `d` is 2:
                           //        Go to the cell below
              +l)%l        //       Adjust row wraparounds when we're out of bounds
           c=(c-(d<2?1-2*d:0)
                           //       Else-if `d` is 0:
                           //        Go to the cell left
                           //       Else-if `d` is 1:
                           //        Go to the cell right
             +l)%l         //       Adjust column wraparounds when we're out of bounds
        d=m[r][c];         //     Set `d` to the current direction of cell `r,c`
  // After we've determined all paths per cell:
  for(Set z:L){            //  Loop `z` over each path of Set `L`:
    if(z.remove(-1)){      //   Remove a -1 (if present),
                           //   and if it indeed contained a -1 (infinite path):
      c=0;                 //    Use `c` as counter, starting at 0
      for(Set q:L)         //    Inner loop `q` over each path of Set `L`:
        if(q.remove(-2)){  //     Remove a -2 (if present),
                           //     and if it indeed contained a -2 (tributary path):
          if(q.containsAll(z))
                           //      If `q` contains all values of `z`:
            c++;           //       Increase the counter by 1
          q.add(-2);}      //      Add -2 back to `q` for the next iteration of loop `z`
      System.out.println(  //    Print with trailing newline:
        z.size()           //     The size of path `z`
        +","+c);}}}        //     and the counter (comma-separated)

```
> 11 votes

# Answer
# K (ngn/k), ~~99~~ 81 bytes

thanks @bstrat for -18 bytes!

```
{l,'(#'.c)-l:#'!c:={x@<x:(x?a@*|x)_x}'{?x,a@x}/'a::s/s!'(+(,/-:\=2)@,/x)+!s:2##x}

```

Try it online!

down,right,up,left in the input are encoded as 0 1 2 3
> 7 votes

# Answer
# Jelly,  ~~44~~  41 bytes

-3 as the grid is guaranteed to be square.

```
ŒṪœịı*ÆiƊ+⁸ʋƬ⁺⁹ɗ€⁸%LḞQ€LÞḢṢƲ€¹ƙ$Ẉ€µḟṂLṭṂ)

```

A monadic Link accepting a list of lists of integers which yields a list of lists of integers (each being a `[loop_size, tributary_count]` \- i.e. \\$(n\_i, t\_i)\\$).

The directions in the input are:

```
^  2
>  1
V  4
<  3

```

**Try it online!**

### How?

```
ŒṪœịı*ÆiƊ+⁸ʋƬ⁺⁹ɗ€⁸%L...  - Link: list, X
ŒṪ                       - truthy multi-dimensional indices -> [[1,1],[1,2],...,[h,w]]
                €        - for each:
               ɗ         -   last three links as a dyadic chain:
              ⁹          -     use chain's right argument as right argument
            Ƭ            -     collect up until no change occurs with:
           ʋ             -       last four links as a dyadic chain:
  œị                     -         multi-dimensional index into X
        Ɗ                -         last three links as a monadic chain:
    ı                    -           square root of -1
     *                   -           exponentiate
      Æi                 -           [real part, imaginary part] -> move deltas
          ⁸              -         chain's left argument -> the current position
         +               -         add together -> the new position
             ⁺           -     repeat the Ƭ-collection, use the entire result
                   L     - length of X
                  %      - modulo -> making all results have the same domain

```

```
...ḞQ€LÞḢṢƲ€¹ƙ$Ẉ€µḟṂLṭṂ) - ...continued
   Ḟ                     - floor (we had a mix of ints and floats, but ƙ uses
                                  Python's repr, this makes them all ints again)
    Q€                   - deduplicate each
              $          - last two links as a monadic chain:
            ¹ƙ           - group by:
           €             -   for each
          Ʋ              -     last four links as a monadic chain:
       Þ                 -       sort by...
      L                  -       length
        Ḣ                -       head
         Ṣ               -       sorted
               Ẉ€        - length of each of each
                 µ     ) - for each:
                   Ṃ     -   minimum -> loop length
                  ḟ      -   filter discard (keeping only tributary lengths)
                    L    -   length -> number of tributaries
                      Ṃ  -   minimum -> loop length
                     ṭ   -   tack -> [loop length, number of tributaries]

```
> 4 votes

# Answer
# Python 2, ~~250 247~~ 235 bytes

*Thanks Arnauld for pointing out that the grid is guaranteed to be square, saving 12 bytes!*

```
G=input()
n=len(G)
N={}
T={}
t=0
exec"j=t%n;i=t/n;A=[]\nwhile(i,j)not in A:A=[(i,j)]+A;d=G[i][j];i+=d/3-1;j+=d%3-1;i%=n;j%=n\nk=A.index((i,j))+1;x=min(A[:k]);N[x]=k;T[x]=T.get(x,[])+A[k:];t+=1;"*n*n
for x in N:print N[x],len(set(T[x]))

```

Try it online!

Takes input as a 2D list from `STDIN`, where up, right, down, left are encoded as the integers `1, 5, 7, 3` respectively.

For each cell in the grid, the program follows the directions starting from that cell until a loop is found. The loop length is stored in the dictionary `N`, and the list of tributary cells is stored in the dictionary `T`. The keys for both dictionaries are the min indices of each loop.
> 3 votes

# Answer
# JavaScript (Node.js), 196 bytes if width=height

```
m=>m[Q='flatMap'](U=(y,I)=>y[Q]((x,j)=>U[T=[...m+0,Y=m.length,i=I][Q](_=>0+[j=(c=m[i][j]-2,j+Y-~c%2)%Y,i=(i+Y+c%2)%Y])[k=0,Q](S=c=>(S[c]=-~S[c])==2&&++k&&c).sort()]?(++U[T][0],[]):[U[T]=[1-k,k]]))

```

Try it online!

# JavaScript (Node.js), 205 bytes

```
m=>m[Q='flatMap'](U=(y,I)=>y[Q]((x,j)=>U[T=[...m+0,Y=m[W='length'],X=m[W],i=I][Q](_=>0+[j=(c=m[i][j]-2,j+Y-~c%2)%Y,i=(i+Y+c%2)%Y]).sort().filter(S=c=>(S[c]=-~S[c])==2)]?(++U[T][1],[]):[U[T]=[k=T[W],1-k]]))

```

Try it online!

Ungolfed version

```
m=>m.flatMap(
  U=(y,I)=>y.flatMap(
    (x,j)=>
      U[
        T=[...m+0,Y=m.length,X=y.length,i=I].map(_=>(
          c=m[i][j],c%2?(i=(i+Y-2+c)%Y):(j=(j+X-1+c)%X),
          i*X+j
        )).sort().filter((c,k,S)=>S[k-1]!=c&S[k+1]==c)
      ]?(++U[T][1],[]):[U[T]=[k=T.length,1-k]]
  )
)

```

Try it online!
> 3 votes

# Answer
# , 78 bytes

```
[:(#~1<{."1)@((=([,-~)&(+/)0=|)"{~~.)@,](]*.[{"p..0|:((,-)=0 1)|.])^:_ p:@i.@$

```

Try it online!

### How it works

We map each index to the corresponding prime `p:@i.@$`:

```
 2  3  5  7 11
13 17 19 23 29
31 37 41 43 47
53 59 61 67 71
73 79 83 89 97

```

Then shift this board by the 4 directions `((,-)=0 1)|.])`, and calculate the least common multiple between the tile `x` and the direction `x` is heading `]*.[{"p..0|:`. We do this until the board does not change anymore `(…)^:_`:

```
461677248802 62985        20995    3162172937  3162172937
         221   221         4199 2109169348979 91703015173
        6851  8177       172159       7402837      321997
      363103  4661     10501699    3162172937  3162172937
230838624401  4661 262460353771    3162172937  3162172937

```

For each unique `~.` number we can then count how often it occures and how many other tiles it divides: `= …&(1#.,) 0=|`. We need the first number and the difference for the result: `([,-~)`:

```
…
6  5
2 10
1  5
…
2  0
1  0

```

We then take only the ones where the first column is greater than 1 `(#~1<{."1)`:

```
6  5
2 10
2  0

```
> 2 votes

# Answer
# ~~435 414 395~~ 390 bytes

Entering the excursion map as a matrix, e.g.

```
n=3;M=matrix(sample(1:4,n^2,rep=T),n)

```

where 1,2,3,4 stand for `down`, `up`, `right`, and `left`, the following heavy-going code produces rows of lengths and tributaries for the different loops

```
j=cbind;l=sum;a=apply
m=l(!!M);n=m^.5
g=function(A,r=M[A])A+c((r<2)*(1-n*(A[,1]==n))-(r==2)*(1-n*(A[,1]<2)),(r==3)*(1-n*(A[,2]==n))-(r>3)*(1-n*(A[,2]<2)))
I=c()
for(i in d<-1:n)I=rbind(I,j(i*d/d,d))
for(t in b<-1:m)I=g(I)
p=function(i)i[,1]+n*i[,2]-n-1
K=matrix(0,m,m)
for(t in b)K[b+m*p(I<-g(I))]=1
s=o=a(u<-unique(K),1,l)
for(k in 1:l(!!s))s[k]=l(!a(!!sweep(K,2,u[k,],'-'),1,l))
j(o,s-o)

```

Try it online!

Some comments

```
m=l(!!M);n=m^.5 #m=n^2
#moving all points in the square by the corresponding moves in M
g=function(A,r=M[A])A+cbind((r<2)*(1-n*(A[,1]==n))-(r==2)*(1-n*(A[,1]<2)),(r==3)*(1-n*(A[,2]==n))-(r>3)*(1-n*(A[,2]<2)))
#matrix of the (i,j) coordinates for all points in the square
I=c()#NULL
for(i in 1:n)I=rbind(I,cbind(rep(i,n),1:n))
#move long enough to remove transient points
for(t in b<-1:m)I=g(I)
#turns 2D coordinates into a single integer
p=function(i)i[,1]+n*i[,2]-n-1
K=matrix(0,m,m) #matrix of visited coordinates
for(t in b)K[b+m*p(I<-g(I))]=1
#loop length (o) and associated number of transients (s)
s=o=apply(u<-unique(K),1,sum)
#sum over all loops (length(o))
for(k in 1:sum(!!s))s[k]=sum(!a(!!sweep(K,2,u[k,],'-'),1,sum))
cbind(o,s-o)

```

Now, I spent too much time on this code already but I fear the parts

```
I=c()
for(i in 1:n)I=rbind(I,cbind(rep(i,n),1:n))

```

creating the matrix of all starting coordinates and

```
p=function(i)i[,1]+n*i[,2]-n-1

```

switching from the coordinates to a single index could be further code-golfed!
> 1 votes

# Answer
# Scala, 415 bytes

415 bytes, maybe more. It can be golfed much more.

Port of @Kevin Cruijssen' Java 10 answer in Scala.

---

Golfed version. Try it online!

```
val L=new HashSet[Set[Int]]()
val l=m.length
val R=l*l
for(i<-0 until R){var r=i/l
var c=i%l
val S=new TreeSet[Int]()
do{S.add(r*l+c)
val d=m(r)(c)
r=(r-(d-d%3*d)/2+l)%l
c=(c-(if(d<2)1-2*d else 0)+l)%l}while(S.add(r*l+c))
if(r==i/l&&c==i%l)S.add(-1)else S.add(-2)
L.add(S)}
for(z<-L.asScala){if(z.remove(-1)){var c=0
for(q<-L.asScala){if(q.remove(-2)){if(q.containsAll(z))c+=1
q.add(-2)}}
println(s"${z.size},$c")}}

```

Ungolfed version. Try it online!

```
import java.util.{HashSet, TreeSet, Set}
import scala.collection.JavaConverters._

object Main {

  trait N {
    def c(m: Array[Array[Int]]): Unit
  }

  val n: N = new N {
    def c(m: Array[Array[Int]]): Unit = {
      val L = new HashSet[Set[Int]]()
      val l = m.length
      val R = l * l

      for (i <- 0 until R) {
        var r = i / l
        var c = i % l
        val S = new TreeSet[Int]()
        do {
          S.add(r * l + c)
          val d = m(r)(c)
          r = (r - (d - d % 3 * d) / 2 + l) % l
          c = (c - (if (d < 2) 1 - 2 * d else 0) + l) % l
        } while (S.add(r * l + c))
        if (r == i / l && c == i % l) S.add(-1) else S.add(-2)
        L.add(S)
      }

      for (z <- L.asScala) {
        if (z.remove(-1)) {
          var c = 0
          for (q <- L.asScala) {
            if (q.remove(-2)) {
              if (q.containsAll(z)) c += 1
              q.add(-2)
            }
          }
          println(s"${z.size},$c")
        }
      }
    }
  }

  def main(args: Array[String]): Unit = {
    test(Array(Array(3, 1, 2, 1, 3), Array(1, 0, 0, 1, 3), Array(3, 3, 3, 0, 1), Array(3, 2, 3, 2, 0), Array(0, 3, 1, 2, 3)))
    test(Array(Array(1, 2), Array(3, 0)))
    test(Array(Array(1, 2, 2), Array(3, 0, 0), Array(1, 0, 2)))
  }

  def test(m: Array[Array[Int]]): Unit = {
    println(s"Input: ${m.map(_.mkString(",")).mkString("Array(", ", ", ")")}")
    println("Pretty-printed: ")
    prettyPrint(m)
    println("Output: ")
    n.c(m)
    println()
  }

  def prettyPrint(m: Array[Array[Int]]): Unit = {
    for (r <- m) {
      println(r.map(v => "<>v^".charAt(v)).mkString)
    }
  }
}

```
> 1 votes

---
Tags: code-golf, grid, counting
---


title: Am I an Automorphic Number?

text:
# Question
Title: Am I an Automorphic Number?
An Automorphic number is a number which is a suffix of its square in base 10. This is sequence A003226 in the OEIS.

## Your Task:

Write a program or function to determine whether an input is an Automorphic number.

## Input:

An integer between 0 and 10^12 (inclusive), that may or may not be an Automorphic number.

## Output:

A truthy/falsy value indicating whether or not the input is an Automorphic number.

## Examples:

```
0           -> truthy
1           -> truthy
2           -> falsy
9376        -> truthy
8212890625  -> truthy

```

## Scoring:

This is , lowest score in bytes wins.

# Answer
# Brachylog, 5 bytes

```
~√a₁?

```

Try it online!

## How it works

```
~√a₁?
~√      the input is the square root of a number
  a₁    whose suffix is
    ?   the input

```
> 12 votes

# Answer
# Python 2, 24 bytes

```
lambda n:`n*1L`in`n**2L`

```

Try it online!

For the first time in history, Python 2's appending an `L` to the repr of longs is a feature rather than a bug.

The idea is to check if say, `76^2=5776` ends in `76` by checking if `76L` is a substring of `5776L`. To make the `L` appear for non-huge numbers, we multiply by `1L` or have `2L` as the exponent, since an arithmetic operation with a long with produces a long.
> 40 votes

# Answer
# Python 2, 31 bytes

Out-golfed by xnor... (this happens every single time) \>\< But hey, it's surprisingly Pythonic for .

People don't tend to remember Python has `str.endswith()`...

```
lambda n:str(n*n).endswith(`n`)

```

Try it online!
> 9 votes

# Answer
# 05AB1E, 5 bytes

```
n.s¹å

```

Try it online!
> 5 votes

# Answer
# Retina, 44 bytes

```
$
;918212890625;81787109376;0;1;
^(\d+;).*\1

```

Try it online!

There are exactly 4 solutions to the 10-adic equation `x*x = x`.
> 5 votes

# Answer
# Python 2, ~~37~~ ~~33~~ ~~30~~ 29 bytes

```
lambda n:n*~-n%10**len(`n`)<1

```

Saved 4 bytes thanks to @LeakyNun. Saved 3 bytes by noticing that the input is lower than 10^12 so `n` doesn't end with an "L". Saved 1 byte thanks to @Dennis because I miscounted in the first place.

Try it online! (TIO link courtesy of @Dennis).
> 4 votes

# Answer
## Alice, 17 bytes

```
/o.z/#Q/
@in.*.L\

```

Try it online!

Outputs nothing (which is falsy in Ordinal mode) or `Jabberwocky` (which is non-empty and therefore truthy in Ordinal mode; it's also the canonical truthy string value).

### Explanation

```
/.../#./
....*..\

```

This is a slight modification of the general framework for linear Ordinal mode programs. The `/` in the middle is used to have a single operator in Cardinal mode in between (the `*`) and then we need the `#` to skip it in Ordinal mode on the way back. The linear program is then:

```
i..*.QLzno@

```

Let's go through that:

```
i    Read all input as a string and push it to the stack.
..   Make two copies.
*    This is run in Cardinal mode, so it implicitly converts the top two
     copies to their integer value and multiplies them to compute the square.
.    Implicitly convert the square back to a string and make a copy of it.
Q    Reverse the stack to bring the input on top of the two copies of its square.
L    Shortest common supersequence. This pops the input and the square from
     the top of the stack and pushes the shortest string which begins with
     the square and ends with the input. Iff the square already ends with the
     input, this gives us the square, otherwise it gives us some longer string.
z    Drop. Pop the SCS and the square. If the square contains the SCS (which
     would mean they're equal), this removes everything up to the SCS from
     the square. In other words, if the SCS computation left the square
     unchanged, this gives us an empty string. Otherwise, it gives us back
     the square.
n    Logical not. Turns the empty string into "Jabberwocky" and everything
     else into an empty string.
o    Print the result.
@    Terminate the program.

```
> 4 votes

# Answer
# Mathematica, 31 bytes

```
Mod[#^2,10^IntegerLength@#]==#&

```

Try it online! Mathics prints an extra message but the answer is correct
> 4 votes

# Answer
# Ruby, 22 bytes

```
->n{"#{n*n}"=~/#{n}$/}

```

Try it online!
> 4 votes

# Answer
# C (gcc), 57 bytes

```
f(__int128 n){n=n*n%(long)pow(10,printf("%u",n))==n;}

```

Based on @betseg's answer, this is a function that returns **1** or **0**. It produces garbage output to STDOUT, which is allowed by default.

The score contains **+4 bytes** for the compiler flag `-lm`.

Try it online!
> 3 votes

# Answer
# Charcoal, 12 11 bytes

```
Ｉ¬⌕⮌ＩＸＩθ²⮌θ

```

Try it online!

Returns `False` as `falsey` and `True` as `truthy`.

* 1 byte saved thanks to ASCII-only! (How could I miss the `Power` function?)
> 3 votes

# Answer
# C# (.NET Core), 47 bytes

```
n=>$"{BigInteger.Multiply(n,n)}".EndsWith(n+"")

```

Try it online!
> 3 votes

# Answer
# R, 28 bytes

```
pryr::f(x^2%%10^nchar(x)==x)

```

Creates a function:

```
function (x)
x^2%%10^nchar(x) == x

```

Takes the modulus of `x^2` such that we keep the last digits, which we compare to `x`.
> 3 votes

# Answer
# JavaScript (ES6), 23 bytes

```
n=>`${n*n}`.endsWith(n)

```

---

## Try it

Wrote this Snippet up on my phone, so please edit if it's not working correctly.

```
f=
n=>`${n*n}`.endsWith(n)
oninput=_=>o.innerText=f(+i.value);o.innerText=f(i.value=1)
```

```
<input id=i type=number><pre id=o>
```
> 2 votes

# Answer
# Jelly, 6 bytes

```
²ṚwṚ⁼1

```

Try it online!
> 2 votes

# Answer
# Kotlin, 36 bytes

```
fun a(i:Int)="${i*i}".endsWith("$i")

```
> 2 votes

# Answer
# C, 77 + 4 (`-lm`) = 81 bytes

```
#import<tgmath.h>
i;f(long double n){i=fmod(n*n,pow(10,(int)log10(n)+1))==n;}

```

Try it online!
> 2 votes

# Answer
# Perl 5, 15 + 1 (-p) = 16 bytes

```
$_=$_**2=~/$_$/

```

Try it online!
> 2 votes

# Answer
# Jelly, 7 bytes

```
²_ọæċ⁵$

```

Try it online!

Positive number for yes, 0 for no.
> 1 votes

# Answer
# PHP, 41 bytes

```
<?=preg_match("#$argn$#",bcpow($argn,2));

```

PHP Sandbox Online

# PHP, 42 bytes

without Regex

```
<?=strtr(bcpow($argn,2),[$argn=>X])[-1]>A;

```

# PHP, 44 bytes

Use the levenshtein distance

```
<?=!levenshtein($argn,bcpow($argn,2),0,1,1);

```
> 1 votes

# Answer
# Retina, ~~47~~ 33 bytes

14 bytes thanks to Martin Ender.

```
.+
$*
$
¶$`
\G1
$%_
M%`1
(.+)¶\1$

```

Try it online!
> 1 votes

# Answer
# Dyvil, 26 bytes

```
x=>"\(x*x)".endsWith"\(x)"

```

Usage:

```
let f: int->boolean = x=>"\(x*x)".endsWith"\(x)"
print(f 20) // false

```
> 1 votes

# Answer
## Batch, 122 bytes

```
@set/an=%1,t=f=1
:l
@set/at+=t,f*=5,n/=10
@if %n% gtr 0 goto l
@cmd/cset/a"(!(%1%%t)|!(~-%1%%t))&(!(%1%%f)|!(~-%1%%f))

```

Algorithm is limited only by the integer type used for variables. In the case of Batch, this is 32-bit signed integers, so the maximum is 2147483647. Works by testing both n and n-1 for necessary powers of 2 and 5 as factors. (Except when n is 0 or 1, n and n-1 will have one factor each.)
> 1 votes

# Answer
# Pyth, ~~10~~ 9 bytes

-1 byte thanks to isaacg.

```
x_`^vz2_z

```

Returns 0 when the number is automorphic, anything else if it is not.

Test it online!

**Explanations**

```
x_`^vz2_z

   ^vz2      # Evaluate the input to a number, compute the square
  `          # Convert the squared number to a string
 _           # Reverse it
x      _z    # Find the index of the first occurrence of the reversed input in the reversed square. That's basically equivalent of doing an endswith() in Python
             # Implicit input of the index. If 0, then the reversed square starts with the reversed input

```
> 1 votes

# Answer
## \>\<\>, 30 bytes

```
1&0}\{n;
:&(?\:::*&a*:&%={+}:&

```

Try it online, or watch it at the fish playground!

Assumes the input number *x* is already on the stack.

Explanation: The fish takes the quotient of *x*2 by increasing powers of 10, and counts how many times this equals *x*. When the power of 10 gets larger than *x*, it prints the count and halts. The count will be 1 if *x* is automorphic, and 0 if it isn't.
> 1 votes

# Answer
# Pari/GP, 23 bytes

```
n->n^2%10^#digits(n)==n

```

Try it online!
> 1 votes

# Answer
# Rexx (Regina), 48 bytes

```
numeric digits 25
arg n
say right(n*n,length(n))=n

```

Try it online!
> 1 votes

# Answer
# Haskell, 45 bytes

```
f=reverse.show
g a=and$zipWith(==)(f a)$f$a^2

```

Try it online!

# Haskell \+ Data.Function, 42 bytes

```
g a=and$on(zipWith(==))(reverse.show)a$a^2

```

Try it online!

```
and.(on(zipWith(==))(reverse.show)<*>(^2))

```

Try it online!

# Haskell \+ Data.Function \+ Control.Monad, 40 bytes

```
and.ap(on(zipWith(==))$reverse.show)(^2)

```

Try it online!
> 1 votes

# Answer
# PowerShell Core, ~~36~~ 34 bytes

```
param([bigint]$a)""+$a*$a|% En* $a

```

Try it online!

Could be 8 bytes shorted if passing a `bigint` as parameter was allowed

-2 bytes thanks to *Zaelin Goodman*!
> 1 votes

# Answer
# Vyxal `r`, 3 bytes

```
²øf

```

Try it Online!

First time using the `r` flag.
> 1 votes

# Answer
# Python 3, ~~40~~ 35 bytes

-@Nick A saved 5 bytes: use of `endswith()`

```
lambda x:str(x*x).endswith(str(x))

```

Try it online!

# Python 2, 31 bytes (Does not work for large numbers)

```
lambda x:`x*x`[-len(`x`):]==`x`

```

Try it online!
> 0 votes

# Answer
# Perl 6, 15 bytes

```
{$^x²~~/$^x$/}

```

Try it online!

Returns a truthy Match object for automorphic inputs, and a falsy Nil value for other numbers.
> 0 votes

# Answer
## Clojure, 59 bytes

```
#(apply = true(map =(reverse(str %))(reverse(str(* % %)))))

```

This seems overly verbose.
> 0 votes

# Answer
# MATL, 10 bytes

```
UUVG36hXXn

```

This works for numbers up to `floor(sqrt(2^53))`, as per `double` precision limitations.

Output is a positive number (which is truthy) if automorphic, or empty (which is falsy) if not.

**Try it online!**

### Explanation

Funny that this answer uses the two overloaded versions of `U`: with string input it evaluates as a number, and with number input it computes the square.

```
U      % Implicitly input a string. Evaluate as a number
U      % Square of number
V      % Convert number to string representation
G      % Push input string again
36h    % Post-pend '$'
XX     % Regexp match. Gives cell array of matching substrings.
n      % Number of elements. Implicitly display

```
> 0 votes

# Answer
# Java 8, 36 bytes

```
n->(n.multiply(n)+"").endsWith(n+"")

```

Input is a `java.math.BigInteger`, output a `boolean`.

**Explanation:**

Try it here.

```
n->                   // Method with BigInteger parameter and boolean return-type
  (n.multiply(n)+"")  //  Return if the String representation of n*n
   .endsWith(n+"")    //  ends with the String representation of n
                      // End of method (implicit / single-line body)

```
> 0 votes

# Answer
# Factor, 37 bytes

```
[ [ sq ] keep [ present ] bi@ tail? ]

```

Try it online!

* `[ sq ] keep` Square the input, but also retain a copy of the input on top of the stack. (Identical length to `dup sq swap`.)
* `[ present ] bi@` Convert both numbers to strings.
* `tail?` Is top-of-stack a suffix of next-on-stack?
> 0 votes

# Answer
# Husk, 7 bytes

```
§€d(ṫd□

```

Try it online!

§        # fork:
 €       # index of arg1 in arg2, or zero if absent:
  d      # arg1: digits of input
   (     # arg2:
    ṫ    # tails = all suffixes of
     d   # digits of
      □  # square of input
```
</code></pre>
> 0 votes

# Answer
# ARM Thumb machine code, 20 bytes

```
01 22 0a 23 5a 43 81 1a fc d2 40 43 80 1a fd d2
08 1a 70 47

```

Since ARM uses 32-bit arithmetic, this can only handle up to \\$2^{16}-1\\$. This is OK according to the OP's comment, and the calculations would still be correct with larger integers (which is confirmed with equivalent AArch64 code)...although it would be pretty slow due to the subtraction loop.

```
    .syntax unified
    .arch armv7-a
    .thumb
    .globl  automorphic
    .thumb_func
    // input: r0, output: r0 (zero for true)
    // C calling convention
automorphic:
    // Calculate power of 10 larger than the digits
    // by repeatedly multiplying by 10.
    movs    r2, #1                                         @ pow10 = 1;
    movs    r3, #10                                        @ TEN = 10;
.Llog10:                                                   @ do {
    // Multiply by 10.
    muls    r2, r3                                         @     pow10 *= TEN;
    // Multiple purpose:
    //   - The SUBS sets the flags as if we were doing
    //        do { pow10 *= TEN; } while (x >= pow10);
    //   - This saves x to another register so we can square
    //     with narrow MULS which overwrites the source.
    //   - This pre-subtracts pow10 to compensate for the
    //     below modulo loop which runs an extra iteration.
    subs    r1, r0, r2                                     @    tmp = x - pow10;
    bhs     .Llog10                                        @ } while (x >= pow10);
.Llog10_end:
    // Square x.
    muls    r0, r0                                         @ x2 = x * x;
    // Naive modulo loop by repeated subtraction, which is
    // always shorter than udiv+mul+sub. As stated before,
    // this actually calculates x2 % pow10 - pow10.        @ mod = x2;
.Lmodulo:                                                  @ do {
    subs    r0, r2                                         @     x2 = mod; mod = x2 - pow10;
    bhs     .Lmodulo                                       @ } while (x2 >= pow10);
    // Subtract to get a 3-way comparison, with 0 being true
    subs    r0, r1, r0                                     @ result = tmp - mod;
    // Return
    bx      lr                                             @ return result;

```

This function uses the AAPCS calling convention, and can be called from C.

It returns zero for true and non-zero for false.

```
int32_t automorphic(uint32_t x);

```
> 0 votes

# Answer
# Prolog (SWI), 83 bytes

```
\N:-S is N*N,N+D,S+P,prefix(D,P).
N+[H|D]:-N>9,H is N mod 10,R is N//10,R+D.
N+[N].

```

Try it online!

For whatever reason the last test case (`8212890625`) doesn't work on TIO, but it does work everywhere else I've tried.
> 0 votes

# Answer
# Thunno 2, 4 bytes

```
²$ø>

```

Try it online!

#### Explanation

```
²$ø>  # Implicit input
²     # The input squared...
  ø>  # ...ends with...
 $    # ...the input?
      # Implicit output

```
> 0 votes

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


title: Hexadecimal Counter

text:
# Question
Title: Hexadecimal Counter
**Hexadecimal** is a base 16 counting system that goes from `0` to `f`. Your job is to make a counter that will display these numbers.

**Example:**

```
$ python counter.py
1 2 3 4 5 6 7 8 9 a b c d e f 10 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 20 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f 30

```

**Rules:**

* The numbers may be separated by spaces, tabs, or new lines.
* The minimum number you must go to is `30` (48 in decimal).
    + You may also make the program print numbers forever until it is stopped.
* Letters may be in uppercase or lowercase (`A` or `a`).
* No built in functions allowed (that directly affect hexadecimal conversions/counting).
* Leading zeros are allowed
* It may start from `1` or `0`
* Shortest code wins!

# Answer
> 5 votes
# Pyth - 12 bytes

Uses cartesian product, and sorts at the end to get in correct order, then joins by spaces. Prints `00-ff` inclusive.

```
jdS^s+<G6UT2

```

Try it online here.

```
jd             Join by spaces
 S             Sort lexiographically
  ^    2       Cartesian product repeat twice
   s+          Append then concatenate entire list
    <G6        First six of alphabet
    UT         Range 0-9

```

# Answer
> 7 votes
# Pure Bash, 26

Counts from 0x0 to 0x3F:

```
echo {0..3}{{0..9},{A..F}}

```

Try it online!

# Answer
> 6 votes
# CJam, ~~21~~ 14 bytes

```
A,_6,'Af++m*S*

```

Prints the numbers 00 to 9F.

Try it online in the CJam interpreter.

### How it works

```
A,             e# Push [0 ... 9].
  _            e# Push a copy.
   6,          e# Push [0 ... 5].
     'Af+      e# Add 'A' to each. This pushes "ABCDEF".
         +     e# Concatenate. This pushes [0 ... 9 'A' ... 'F'].
          m*   e# Cartesian product. This pushes [[0 0] ... [9 'F'].
            S* e# Join, separating by spaces.

```

# Answer
> 5 votes
# Python 2, 52

```
a=0
for b in'0123456789ABCDEF'*4:print`a`+b;a+=b>'E'

```

Prints `00` to `3F`. Takes advantage of the fact that the first digit `a` is always a number in this range. Loops through four cycles of the second digit `b`, incrementing `a` whenever the second digit is `F`.

This is one char shorter than the more direct

```
for a in'0123':
 for b in'0123456789ABCDEF':print a+b

```

# Answer
> 5 votes
## JavaScript (ES6), 57 bytes

Same approach as the Python ones I suppose.

```
for(i of c='0123456789ABCDEF')for(j of c)console.log(i+j)

```

# Answer
> 4 votes
# TI-Basic, 63 bytes

```
:For(I,0,4,16⁻¹
:Disp sub(" 0123456789ABCDEF",1+16fPart(I),2
:Output(7,1,int(I
:End

```

This is 63 bytes, according to the memory management screen on my calculator, a TI-84+. Make sure to start the program with a partially filled home screen!

# Answer
> 4 votes
## **Befunge-93, 57 bytes**

```
<_v#-*44:+1,*84,g2:\,g2:\
^ >$1+:9-!#@_0
0123456789ABCDEF

```

Prints numbers from `00`to `8F`. If you prefer your programs to run forever, the version below is non-terminating and will continually output all numbers from `00` to `FF`.

```
<_v#-*44:+1,*84,g2:\,g2:\
^ >$1+:35*`!*0
0123456789ABCDEF

```

# Answer
> 2 votes
# CJam, 22 bytes

```
1{_GbA,6,'af++f=oNo)}h

```

This runs forever, and thus is probably one of the rare times where it's a good idea *not* to include a permalink.

# Answer
> 2 votes
# C, ~~78~~ 75 bytes

```
x(y){return y+48+y/10*7;}f(j){for(j=0;printf("%c%c ",x(j/16),x(15&j++)););}

```

We define a function `f()` to be called with no arguments for printing, and a helper function `x(int)`. This breaks at `FF`.

Amazingly, this is one byte shorter than the more obvious:

```
char*s="0123456789ABCDEF";h(j){for(j=0;printf("%c%c ",s[j/16],s[15&j++]););}

```

*Warning: it is not recommended to run this code outside of a debug environment...*

Testing:

```
int main(int argc, char** argv) {
    f();
    return 0;
}

```

Output:

```
00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F 10 11 12 13 14 15 16 17 18 19 1A 1B 1C 1D 1E 1F 20 21 22 23 24 25 26 27 28 29 2A 2B 2C 2D 2E 2F 30 31 32 33 34 35 36 (...)

```

Of course, the more robust (and cheat-y) approach is this 34-byte function:

```
g(i){for(i=0;printf("%x ",i++););}

```

# Answer
> 2 votes
# Pyth, 17 bytes

```
VJs++kUT<G6FYJ+NY

```

Try it here

## How it works:

```
         <G6         # "abcdef"
       UT            # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
      k              # an empty string (so + means concatenation, not addition)
   s++               # join them all ("0123456789abcdef")
  J                  # call this J
 V                   # for each N in J...
            FYJ      # for each Y in J...
               +NY   # print N and Y

```

# Answer
> 2 votes
# Javascript ES6, 67 62 bytes

```
(x=''.replace.bind('0123456789ABCDEF',/./g))(n=>x(o=>' '+n+o))

```

# Answer
> 2 votes
# J, 22 bytes

```
>{;~'0123456789abcdef'

```

Counts to `ff`. Prints an extra newline between each block of `0x10` numbers, like so:

```
...
0d
0e
0f

10
11
...

```

# Answer
> 2 votes
# Mumps - 65 bytes

```
S Q="0123456789ABCDEF" F I=1:1:16 F J=1:1:16 W $E(Q,I),$E(Q,J),!

```

Nope... Mumps ain't dead yet! :-)

# Answer
> 2 votes
# TheC64Mini and Commodore BASIC (C64/128, PET, VIC-20, C16/+4) - 164 BASIC and Tokenized bytes used

```
 0 fOd=.to255:n=d:fOi=1to.stE-1:h%(i)=n/(16^i):n=n-(h%(i)*(16^i)):nEi:h$=""
 1 fOi=1to.stE-1:ifh%(i)<10tHh$=h$+cH(48+h%(i))
 2 ifh%(i)>9tHh$=h$+cH(55+h%(i))
 3 nEi:?h$"  ";:nEd

```

Prints a double-space after the hex number to nicely align the printing at 40/80 columns as well as the 22 columns on the VIC-20.

# Answer
> 2 votes
# Malbolge, 900 bytes

To be improved...

```
D'``@"\7}|X9E1gwuR21=p(:9%IZYEg}eA/ya>O_)([Zvotm3qponmfN+Lbg`ed]\"CB^W\Uy<;WVONSLp3ONMLEDhH*)?>b%A@?87[;:9876/S3,P0/.-&J$)"'~D|{"y?}|utyr8potmrqpi/mfN+Lbg`e^$bDZ_^]VzZSXQVUTSLp3ONMLEDhH*)EDCB;@?8\6|:32V6v.32+O)o'&J*)i'&%|Bcb~w|u;yxwvutVrkj0nmfN+iKg`_%cE[`Y}@V[ZYXWPtT6LKJImM/KJIBAe(D=<A:98\[;{32V6v.-,P0).',%I)"!E%|#"y?w_{ts9Zvutsrkpi/mfNjihg`e^$b[Z~X]\[ZYRv98TSLKoO10FKDh+GFE>CB;_?>=}|49870/.R2+*Non&%I#"!&%${A!~}_u;yxqpo5mrqpoh.lkdibgf_%]\[!_XW{[ZYXQPt7SRQPOHGkKJIHAF?cC<;@?8\6;492V6v.-,P*p.'K+$j"'~D|#"y~wv<]yxqvutsrk1onmfN+cba`&d]#DZ_^]VzTSXQVOs65QJINGkE-IBAe(D=<A:98\654981Uv.32+*)M-,%k#(!E}$#"!x>v{t:xwputm3kpoh.fN+Lbg`ed]\"!Y^]VzZYXQVOsS54JImMFKJIHAe?>C<`@?87[;{32V05.-2+O)o-,+$H('&}Cdzy~wv<]sxqvonm3k1oQmf,jihgfeG]#a`_X|V[TxXQPUTMLp3ONMLEDhH*)ED=a;@?>76;4X816/43,P*).',%I#i!&}|Bcb~w|u;yxwputm3qSong-kjihgfH%]\a`_XW{UTYXQuUTMRKPOHlFKDhBAe?>=B;_9>=6Z:981Uv.32+*)M-,%k#(!E%$#c!x>|u;yxZpo5srqSi/z

```

Try it online!

# Answer
> 2 votes
# brainfuck, 2902 bytes

Easy to outgolf, but worth giving a shot

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

```

Try it online!

# Answer
> 2 votes
# PowerShell 6, 40 bytes

```
($l=0..9+'A'..'F')|%{$1=$_;$l|%{"$1$_"}}

```

Try it online!

Starts at `00` and counts up to `FF`.

# Answer
> 2 votes
## MUMPS, 57 bytes

```
f i=1:1:48 w $tr(i\16,0),$e("0123456789abcdef",i#16+1),!

```

Output

```
>d ^xmsdgolf
1
2
3
4
5
6
7
8
9
a
b
c
d
e
f
10
11
..
28
29
2a
2b
2c
2d
2e
2f
30

```

Explanation

```
f i=1:1:48                     ; loop from 1 to 48
w $tr(i\16,0)                  ; print i div 16, and ditch any zeros
$e("0123456789abcdef",i#16+1)  ; extract the nth character from the string, where n is i mod 16 + 1
!                              ; crlf

```

# Answer
> 1 votes
# Python 2, ~~66~~ 55 Bytes

This should really have been the most obvious approach to me..

```
a='0123456789ABCDEF'
for x in a:
 for y in a:print x+y

```

**Old (66 Bytes)**: Technically this causes an error after `FF`, but it does reach `30`.

```
n=1;a='0123456789ABCDEF'
while 1:print a[n/16]*(n>15)+a[n%16];n+=1

```

I assumed string formatting wasn't allowed since I'm pretty sure it would go through base conversion, but if it was allowed, this would be 29 bytes:

```
n=1
while 1:print"%x"%n;n+=1

```

# Answer
> 1 votes
# Java, 104 bytes

```
char t[]="0123456789abcdef".toCharArray(),i;void f(){for(;i<99;)System.out.println(""+t[i/16]+t[i++%16]);}

```

If the `i<99` is removed, it still reaches 30, but eventually crashes. I'm not sure if that's acceptable.

# Answer
> 1 votes
## J, 47 bytes

```
'0123456789abcdef'{~([:|:2 256$(]#i.),256$i.)16

```

prints 00 to ff

# Answer
> 1 votes
# JavaScript ~~74~~ ~~72~~ ~~65~~ 60

```
//for(i=0,a="0123456789ABCDEF";i++<49;)console.log(a[i>>4]+a[i%16])
for(i=0;i++<48;)console.log((i>>4)+"0123456789ABCDEF"[i%16])
```

# Answer
> 1 votes
# jq 1.5: ~~65~~ 59 characters

(56 characters code + 3 characters command line option.)

```
[range(10)]+"a b c d e f"/" "|{a:.[],b:.}|"\(.a)\(.b[])"

```

Sample run:

```
bash-4.3$ jq -n -r '[range(10)]+"a b c d e f"/" "|{a:.[],b:.}|"\(.a)\(.b[])"' | head
00
01
02
03
04
05
06
07
08
09

```

On-line test (Passing `-r` through URL is not supported – check Raw Output yourself.)

# jq 1.5: 56 characters

(53 characters code + 3 characters command line option.)

```
[[range(10)]+"a b c d e f"/" "|"\(.[])\(.[])"]|sort[]

```

This produces correct output, however is not exactly a counter: it not generates the values in order, just sorts them after.

On-line test (Passing `-r` through URL is not supported – check Raw Output yourself.)

# Answer
> 1 votes
## Ruby, 64 bytes

```
h='0123456789abcdef'.split //;h.each{|i|h.each{|j|print i,j,?\s}}

```

Explanation:

```
h = '0123456789abcdef'.split // # Split string of hex chars at
                                # matches of //, returns array
                                # splits array by characters
h.each { |i|                    # loop 1
  h.each { |j|                  # loop 2
    print i,j,?\s               # print() can take multiple params,
                                # and it is the same as printing
                                # each one using a separate print().
                                # ?x is the same as 'x', so ?\s is
                                # the same as "\s", which is " ".
  }
}

```

# Answer
> 1 votes
# Dyalog APL, 12 bytes

```
       ∘.,⍨16↑⎕D,⎕A
 00  01  02  03  04  05  06  07  08  09  0A  0B  0C  0D  0E  0F
 10  11  12  13  14  15  16  17  18  19  1A  1B  1C  1D  1E  1F
 20  21  22  23  24  25  26  27  28  29  2A  2B  2C  2D  2E  2F
 30  31  32  33  34  35  36  37  38  39  3A  3B  3C  3D  3E  3F
 40  41  42  43  44  45  46  47  48  49  4A  4B  4C  4D  4E  4F
 50  51  52  53  54  55  56  57  58  59  5A  5B  5C  5D  5E  5F
 60  61  62  63  64  65  66  67  68  69  6A  6B  6C  6D  6E  6F
 70  71  72  73  74  75  76  77  78  79  7A  7B  7C  7D  7E  7F
 80  81  82  83  84  85  86  87  88  89  8A  8B  8C  8D  8E  8F
 90  91  92  93  94  95  96  97  98  99  9A  9B  9C  9D  9E  9F
 A0  A1  A2  A3  A4  A5  A6  A7  A8  A9  AA  AB  AC  AD  AE  AF
 B0  B1  B2  B3  B4  B5  B6  B7  B8  B9  BA  BB  BC  BD  BE  BF
 C0  C1  C2  C3  C4  C5  C6  C7  C8  C9  CA  CB  CC  CD  CE  CF
 D0  D1  D2  D3  D4  D5  D6  D7  D8  D9  DA  DB  DC  DD  DE  DF
 E0  E1  E2  E3  E4  E5  E6  E7  E8  E9  EA  EB  EC  ED  EE  EF
 F0  F1  F2  F3  F4  F5  F6  F7  F8  F9  FA  FB  FC  FD  FE  FF

```

# Answer
> 1 votes
# Perl 6, 34 bytes

The shortest that I can come up with that doesn't use any sort of conversion is:

```
put [X~] (|(0..9),|('A'..'F'))xx 2 # 34 bytes

```

prints `00` ... `FF` space separated in order.
If you want more you can swap `2` for a larger number.
(don't use a number bigger than 4 as it concatenates the values together before outputting anything, so it would use a significant amount of RAM )

---

Shortest that will never stop writing hex values

```
put [R~] (|(0..9),|('A'..'F'))[.polymod: 16 xx*]for 0..* # 56 bytes

```

---

If `printf` were allowed

```
printf "%X ",$_ for 0..* # 24 bytes

```

If a base conversion function were allowed

```
put .base(16)for 0..* # 21 bytes

```

# Answer
> 1 votes
# Matlab: 47 bytes

```
q=[48:57,97:102,''];fliplr(char(combvec(q,q)'))

```

I don't know if it would be considered as counter. The code generates vector of hex numbers from `00` to `ff`. `q` is a string `'0123456789abcdef'` in `double` format. Combvec generates all possible pairs between `q` and `q`. Char converts it to string format and `fliplr` flips the columns to get:

```
00
01
...
08
09
0a
0b
0c
0d
0e
0f
10
11
...
fd
fe
ff

```

# Answer
> 1 votes
## C++14 - 135

```
#include<string>
#include<iostream>
void f(){std::string a="0123",b="0123456789ABCDEF";for(char c:a)for(char d:b)std::cout<<c<<d<<" ";}

```

# Answer
> 1 votes
# GFortran, ~~93~~ 83 bytes

Prints `00` through `ff`. Saved 10 bytes using `print` loops instead of `do.. enddo`.

Try it Online!

```
character(16)H;H='0123456789abcdef'
print*,((H(i:i)//H(j:j),' ',j=1,16),i=1,16)
end

```

Old version: 93 bytes

# Answer
> 1 votes
# Zsh, ~~44~~ 29 bytes

***-15****, via GammaFunction* try it online!

```
h=({0..9} {a..f});echo $^h$^h

```

Original (44 bytes): `g=0123456789abcdef;h=(${(s::)g});echo $^h$^h`

# Answer
> 1 votes
# Ahead, 42 bytes

Prints hex numbers starting at 0 forever. Will eventually overflow, though.

```
>t>:16;r
Cvn:/61\<
 >$>:10/7*v
^oNndo++0'<

```

Try it online!

# Answer
> 1 votes
# Scala, 84 bytes

```
val l=(0 to 9)++"A,B,C,D,E,F".split(",")
l.foreach(x=>l.foreach(y=>println(x+""+y)))

```

Slightly better built version, using what you could call a cartesian product. Try it online! Output goes with leading `0`s and a trailing newline. Starts at `00` and counts up to `FF` (`255` in base 10).

# Scala, 89 bytes

```
for(x<-1 to 48)println(if(x%16>9)x/16+"a,b,c,d,e,f".split(",")(x%16-10)else x/16+""+x%16)

```

First answer, because why not, I like its hacks. Try it online! Output goes with leading `0`s and a trailing newline. Starts at `01` and counts up to `30` (`48` in base 10).

# Answer
> 1 votes
# 8088 Assembly, IBM PC DOS, 34 bytes

**Bytes `xxd`:**

```
00000000: 43e8 0900 e806 00b0 20cd 10eb f3b1 04d2  C....... .......
00000010: c38a c324 0f3c 0a7c 0204 0704 30b4 0ecd  ...$.<.|....0...
00000020: 10c3

```

**Unassembled:**

```
        BYTE_LOOP:
43          INC  BX             ; increment counter
E8 0009     CALL HB             ; display high byte
E8 0006     CALL HB             ; display low byte
B0 20       MOV  AL, ' '        ; display space delimiter
CD 10       INT  10H            ; call BIOS, write char to console
EB F3       JMP  BYTE_LOOP      ; keep looping forever
        HB PROC
B1 04       MOV  CL, 4          ; set up bitshift for 4 bits
D2 C3       ROL  BL, CL         ; shift counter left 4 bits
8A C3       MOV  AL, BL         ; put counter into AL
24 0F       AND  AL, 0FH        ; isolate nibble
3C 0A       CMP  AL, 0AH        ; is nibble A-F?
7C 02       JL   NOT_ALPHA      ; if not, skip adjustment
04 07       ADD  AL, 'A'-'9'-1  ; adjust ASCII value to A-F
        NOT_ALPHA:
04 30       ADD  AL, '0'        ; decimal to binary convert
B4 0E       MOV  AH, 0EH        ; BIOS tty function
CD 10       INT  10H            ; call BIOS, write char to console
C3          RET                 ; return to program
        HB ENDP

```

Standalone PC DOS exactable, output is to console and will keep displaying until program is stopped. Just a scratch ASCII manipulating program here. There are just no built-ins or convenience methods in x86 or DOS/BIOS APIs to convert binary values to strings for output.

**Output:**

# Answer
> 1 votes
# Pip `-s`, 8 bytes

```
_TB16M,h

```

Try it online!

## Explanation

```
_TB16M,h
      ,h range 0...99
     M   map using lambda:
_TB16    convert to hexadecimal
         join with spaces(-s flag)

```

# Answer
> 1 votes
# Perl 5, 35 bytes

```
//,map{say$',$_}@,for@,=(0..9,a..f)

```

Try it online!

# Answer
> 1 votes
# Julia - 58 bytes

```
a="0123456789abcdef"
for i in a
        for j in a
                print(i*j*" ")
        end
end

```

# Answer
> 1 votes
# Thunno 2 , 4 bytes

```
kfDṖ

```

Try it online!

#### Explanation

```
kfDṖ  # Implicit input
kf    # Push "0123456789ABCDEF"
  DṖ  # Cartesian product with itself
      # Join on spaces
      # Implicit output

```

# Answer
> 0 votes
# Haskell, 52 bytes

```
a="0123456789abcdef";main=mapM putStrLn$mapM id[a,a]

```

# Answer
> 0 votes
# Python 2 - 57 bytes

```
h='0123456789ABCDEF'
' '.join([i+j for i in h for j in h])

```

This outputs 00 to FF, with spaces between.

# Answer
> 0 votes
## Python 3, 157 bytes

As far as I can tell, this is the only submission so far that can keep counting upwards forever. (Of course, I can't read Haskell or Mumps, but they all *seem* to be doing a two-character loop...) **EDIT:** Okay, not the only one, but perhaps the only one in a non-golfy language?

```
n=bytearray(b'0')
while 1:
 print(repr(n)[12:-2]);p,o=len(n),1
 while o:
  p-=1;m=n[p];n[p]={57:65,70:48}.get(m,m+1);o=m==70
  if o and p==0:p=1;n[:0]+=b'0'

```

Proof of correctness (wraps the above in a function, changing only `print` to `yield`, and then loops as high as you like):

```
def golfed_code():
 n=bytearray(b'0')
 while 1:
  yield(repr(n)[12:-2]);p,o=len(n),1
  while o:
   p-=1;m=n[p];n[p]={57:65,70:48}.get(m,m+1);o=m==70
   if o and p==0:p=1;n[:0]+=b'0'

TEST_LIMIT = 100000

for n, h in enumerate(golfed_code()):
 assert hex(n).upper()=='0X'+h,'{} != {}'.format(hex(n).upper(),'0X'+h)
 if n == TEST_LIMIT:
  break

```

(Thanks to Sp3000 for saving me 3 bytes.)

---
Tags: code-golf, hexadecimal
---