title: Count up diagonally!

text:
# Question
Title: Count up diagonally!
We have lots of horizontal axis for numbers, but I honestly think they're kind of boring. Your task today is to build me a portion of a diagonal axis between two distinct non-negative integers given as input.

## How to build a diagonal axis?

* Let's take an example, with the input `0, 5`. Our axis should look like this:

```
0
 1
  2
   3
    4
     5

```
* However, our axis should look nice for numbers that have more digits too! If the input is, for instance `0, 14`, the new axis should be:

```
0
 1
  2
   3
    4
     5
      6
       7
        8
         9
          10
            11
              12
                13
                  14

```
* The idea is that the first digit of next number on the axis must always be placed exactly after the last digit of the previous number. To understand the idea even better, here is another example with `997, 1004`:

```
997
   998
      999
         1000
             1001
                 1002
                     1003
                         1004

```

---

## Rules

* You may assume that input is in ascending or descending order (you may choose between `5,3` and `3,5`).
* You may also assume that the difference between the two integers is lower than 100.
* You may have a leading newline or a consistent leading space (on each line). Trailing spaces / newlines are fine as well.
* Default Loopholes are forbidden.
* You can take input and provide output by any standard mean.
* This is , so the shortest code in bytes in every language wins!

---

## Other Test Cases

* `1, 10`:

```
1
 2
  3
   4
    5
     6
      7
       8
        9
         10

```
* `95, 103`:

```
95
  96
    97
      98
        99
          100
             101
                102
                   103

```
* `999999, 1000009`:

```
999999
      1000000
             1000001
                    1000002
                           1000003
                                  1000004
                                         1000005
                                                1000006
                                                       1000007
                                                              1000008
                                                                     1000009

```

# Answer
> 19 votes
# 05AB1E, ~~8~~ ~~7~~ 6 bytes

Thanks to *Magic Octopus Urn* for saving a byte!

It somehow works, but honestly I have no idea why.

### Code

```
Ÿvy.O=

```

Uses the **05AB1E** encoding. Try it online!

### Explanation

```
Ÿ          # Create the range [a, .., b] from the input array
 vy        # For each element
   .O      #   Push the connected overlapped version of that string using the
                 previous version of that string. The previous version initially
                 is the input repeated again. Somehow, when the input array is
                 repeated again, this command sees it as 1 character, which gives
                 the leading space before each line outputted. After the first
                 iteration, it reuses on what is left on the stack from the
                 previous iteration and basically attaches (or overlaps) itself
                 onto the previous string, whereas the previous string is replaced
                 by spaces and merged into the initial string. The previous string
                 is then discarded. We do not have to worry about numbers overlapping
                 other numbers, since the incremented version of a number never
                 overlaps entirely on the previous number. An example of 123 and 456:

                 123
                    456

                 Which leaves us "   456" on the stack.
     =     #   Print with a newline without popping

```

# Answer
> 14 votes
# Python 2, 43 bytes

```
lambda a,b:'\v'.join(map(str,range(a,b+1)))

```

Makes use of vertical tab to make the ladder effect. The way thet `\v` is rendered is console dependent, so it may not work everywhere (like TIO).

# Answer
> 13 votes
# Charcoal, 9 8 bytes

```
Ｆ…·ＮＮ⁺¶ι

```

Try it online!

Link is to the verbose version of the code. Input in ascending order.

* 1 byte saved thanks to ASCII-only!

# Answer
> 7 votes
# R, ~~70~~ ~~69~~ 61 bytes

```
function(a,b)for(i in a:b){cat(rep('',F),i,'
');F=F+nchar(i)}

```

Function that takes the start and end variable as arguments. Loops over the sequence, and prints each element, prepended with enough spaces. `F` starts as `FALSE=0`, and during each iteration, the amount of characters for that value is added to it. `F` decides the amount of spaces printed.

Try it online!

-8 bytes thanks to @Giuseppe

# Answer
> 6 votes
# Python 2, ~~58~~ 54 bytes

```
def f(a,b,s=''):print s;b<a or f(a+1,b,' '*len(s)+`a`)

```

Try it online!

# Answer
> 6 votes
# C#, ~~90~~ ~~89~~ 85 bytes

```
s=>e=>{var r="";for(int g=0;e>s;g+=(s+++"").Length)r+="".PadLeft(g)+s+"\n";return r;}

```

*Saved 1 byte thanks to @LiefdeWen.*
*Saved 4 bytes thanks to @auhmaan.*

Try it online!

Full/Formatted version:

```
namespace System
{
    class P
    {
        static void Main()
        {
            Func<int, Func<int, string>> f = s => e =>
            {
                var r = "";
                for (int g = 0; e > s; g += (s++ + "").Length)
                    r += "".PadLeft(g) + s + "\n";

                return r;
            };

            Console.WriteLine(f(0)(5));
            Console.WriteLine(f(0)(14));
            Console.WriteLine(f(997)(1004));
            Console.WriteLine(f(1)(10));
            Console.WriteLine(f(95)(103));
            Console.WriteLine(f(999999)(1000009));

            Console.ReadLine();
        }
    }
}

```

# Answer
> 6 votes
# Mathematica, 59, bytes

```
Grid[(DiagonalMatrix@Range[1+##]/. 0->""+1)-1,Spacings->0]&

```

**input**

> \[10,15\]

-3 bytes @JungHwanMin
problem with 0 fixed (see comments for details)
thanx to @ngenisis

# Answer
> 5 votes
# Jelly, 9 bytes

```
rD⁶ṁ$;¥\Y

```

Try it online!

# Answer
> 5 votes
# C, ~~166~~ ~~134~~ ~~95~~ 82 Bytes

## New Answer

Just as a function not as a whole program.

```
f(a,b){int s=0,i;while(a<=b){i=s;while(i--)printf(" ");s+=printf("%i\n",a++)-1;}}

```

Thanks to Falken for helping knock off 13 Bytes (and fix a glitch)!

Thanks to Steph Hen for helping knock off 12 Bytes!

Thanks to Zacharý for help knock off 1 Byte!

## Old Answers

Got rid of the int before main and changed const char\*v\[\] to char\**v and got rid of return 0;

```
main(int c,char**v){int s=0;for(int a=atoi(v[1]);a<=atoi(v[2]);a++){for(int i=0;i<s;i++)printf(" ");printf("%i\n",a);s+=log10(a)+1;}}

int main(int c,const char*v[]){int s=0;for(int a=atoi(v[1]);a<=atoi(v[2]);a++){for(int i=0;i<s;i++)printf(" ");printf("%i\n",a);s+=log10(a)+1;}return 0;}

```

This is my first time golfing and I wanted to try something in C. Not sure if I formatted this correctly, but I had fun making it!

```
int main(int c, const char * v[]) {
    int s = 0;
    for(int a=atoi(v[1]); a<=atoi(v[2]); a++) {
        for(int i=0; i<s; i++) printf(" ");
        printf("%i\n",a);
        s += log10(a)+1;
    }
    return 0;
}

```

**Explanation**

```
int s = 0; // Number of spaces for each line

for(int a=atoi(argv[1]); a<=atoi(argv[2]); a++) { // Loop thru numbers

for(int i=0; i<s; i++) printf(" "); // Add leading spaces

printf("%i\n",a); // Print number

s += log10(a)+1; // Update leading spaces

```

**Usage**

# Answer
> 5 votes
# Mathematica, 48 bytes

```
Rotate[""<>Table[ToString@i<>" ",{i,##}],-Pi/4]&

```

since there are so many answers, I thought this one should be included

**input**

> \[0,10\]

**output**

# Answer
> 4 votes
# Retina, ~~81~~ 78 bytes

```
.+
$*
+`\b(1+)¶11\1
$1¶1$&
1+
$.& $.&
 (.+)
$.1$*
+1`( *)(.+?)( +)¶
$1$2¶$1$3

```

Try it online! Takes input as a newline-separated list of two integers. Edit: Saved 3 bytes by stealing the range-expansion code from my answer to Do we share the prime cluster? Explanation:

```
.+
$*

```

Convert both inputs to unary.

```
+`\b(1+)¶11\1
$1¶1$&

```

While the last two elements (a, b) of the list differ by more than 1, replace them with (a, a+1, b). This expands the list from a tuple into a range.

```
1+
$.& $.&

```

Convert back to decimal in duplicate.

```
 (.+)
$.1$*

```

Convert the duplicate copy to spaces.

```
+1`( *)(.+?)( +)¶
$1$2¶$1$3

```

Cumulatively sum the spaces from each line to the next.

# Answer
> 4 votes
# APL (Dyalog), ~~25~~ 24 bytes

-1 thanks to Zacharý.

Assumes `⎕IO←0` for zero based counting. Takes the lower bound as left argument and the upper bound as right argument.

```
{↑⍵↑⍨¨-+\≢¨⍵}(⍕¨⊣+∘⍳1--)

```

Try it online!

`(``)` apply the following tacit function between the arguments:

`-` subtract the upper lower from the upper bound

`1-` subtract that from one (i.e. 1 + ∆)

`⊣+∘⍳` left lower bound plus the integers 0 through that

`⍕¨` format (stringify) each

`{``}` apply the following anonymous on that (represented by ⍵):

`≢¨` length of each (number)

`+\` cumulative sum

`-` negate

`⍵↑⍨¨` for each stringified number, take that many characters from the end (pads with spaces)

mix list of strings into character matrix

# Answer
> 4 votes
## C++, ~~167~~ 165 bytes

-2 bytes thanks to Zacharý

```
#include<string>
#define S std::string
S d(int l,int h){S r;for(int m=0,i=l,j;i<=h;){for(j=0;j<m;++j)r+=32;S t=std::to_string(i++);r+=t;r+=10;m+=t.size();}return r;}

```

# Answer
> 3 votes
# Python 2, ~~65 63 62~~ 61 bytes

*-2 bytes Thanks to @Mr. Xcoder: `exec` doesn't need braces*

*-1 bye thanks to @Zacharý: `print s*' '` as `print' '*s`*

```
def f(m,n,s=0):exec(n-m+1)*"print' '*s+`m`;s+=len(`m`);m+=1;"

```

Try it online!

# Answer
> 3 votes
# Pyth, ~~14~~ 13 bytes

```
V}FQ
=k+*dlkN

```

Try it online!

# Answer
> 3 votes
# LOGO, 53 bytes

```
[for[i ? ?2][repeat ycor[type "\ ]pr :i fd count :i]]

```

There is no "Try it online!" link because all online LOGO interpreter does not support template-list.

That is a template-list (equivalent of lambda function in other languages).

Usage:

```
apply [for[i ? ?2][repeat ycor[type "\ ]pr :i fd count :i]] [997 1004]

```

(`apply` calls the function)

will print

```
997
   998
      999
         1000
             1001
                 1002
                     1003
                         1004

```

Note:

This uses turtle's `ycor` (Y-coordinate) to store the number of spaces needed to type, therefore:

* The turtle need to be set to home in its default position and heading (upwards) before each invocation.
* `window` should be executed if `ycor` gets too large that the turtle moves off the screen. Description of `window` command: `if the turtle is asked to move past the boundary of the graphics window, it will move off screen.`, unlike the default setting `wrap`, which `if the turtle is asked to move past the boundary of the FMSLogo screen window, it will "wrap around" and reappear at the opposite edge of the window.`

Explanation:

```
for[i ? ?2]        Loop variable i in range [?, ?2], which is 2 input values
repeat ycor        That number of times
type "\            space character need to be escaped to be typed out.
pr :i              print the value of :i with a newline
fd count :i        increase turtle's y-coordinate by the length of the word :i. (Numbers in LOGO are stored as words)

```

# Answer
> 3 votes
# Japt, 12 bytes

```
òV
£¯Y ¬ç +X

```

Takes input in either order and always returns the numbers in ascending order, as an array of lines.

Try it online! with the `-R` flag to join the array with newlines.

## Explanation

Implicit input of `U` and `V`.

```
òV
£

```

Create inclusive range `[U, V]` and map each value to...

```
¯Y ¬ç

```

The values before the current (`¯Y`), joined to a string (`¬`) and filled with spaces (`ç`).

```
+X

```

Plus the current number. Resulting array is implicitly output.

# Answer
> 3 votes
# JavaScript (ES8), ~~69~~ ~~67~~ 62 bytes

Takes input as integers, in ascending order, using currying syntax. Returns an array of strings.

```
x=>y=>[...Array(++y-x)].map(_=>s="".padEnd(s.length)+x++,s="")

```

---

## Try it

```
o.innerText=(f=

x=>y=>[...Array(++y-x)].map(_=>s="".padEnd(s.length)+x++,s="")

)(i.value=93)(j.value=105).join`\n`
oninput=_=>o.innerText=f(Math.min(i.value,j.value))(Math.max(i.value,j.value)).join`\n`
```

```
label,input{font-family:sans-serif}input{margin:0 5px 0 0;width:100px;}
```

```
<label for=i>x: </label><input id=i type=number><label for=j>y: </label><input id=j type=number><pre id=o>
```

# Answer
> 3 votes
# 05AB1E, 8 bytes

```
Ÿʒ¾ú=þv¼

```

Try it online!

-2 thanks to Adnan.

# Answer
> 2 votes
# C (gcc), ~~41~~ 38 bytes

*-3 bytes Thanks to ASCII-only*

```
t(x,v){while(x<=v)printf("%d\v",x++);}

```

Works on RedHat6, accessed via PuTTY

Try it online!

# Answer
> 2 votes
# Python 2, 78 77 79 bytes

```
def f(a,b):
 for i in range(a,b+1):print sum(len(`j`)for j in range(i))*' '+`i`

```

Try it online!

`f(A, B)` will print the portion of the axis between A and B inclusive.

First time I answer a challenge!

Uses and abuses Python 2's backticks to count the number of spaces it has to add before the number.

-1 byte thanks to Mr.Xcoder

+2 because I forgot a `+1`

# Answer
> 2 votes
# JavaScript, 57 bytes

```
f=(x,y,s='')=>y>=x?s+`
`+f(x+1,y,s.replace(/./g,' ')+x):s

```

# Answer
> 2 votes
# Python 2, 60 59 bytes

-1 byte thanks to Mr.Xcoder for defining my s=0 as an optional variable in my function.

```
def f(l,u,s=0):
 while l<=u:print' '*s+`l`;s+=len(`l`);l+=1

```

Try it online!

I think it is possible to transfer this into a lambda version, but I do not know how. I also think that there is some sort of mapping between the spaces and the length of the current number, but this I also did not figure out yet. So I think there still is room for improvement.

What i did was creating a range from the lowerbound `l`to the upper bound `u` printing each line with a space multiplied with a number `s`. I am increasing the multiplier with the length of the current number.

# Answer
> 2 votes
# MATL, 11 bytes

```
vii&:"t~@Vh

```

**Try it online!**

### Explanation

This works by generating a string for each number and concatenating it with a logically-negated copy of the previous string. Thus char 0 is prepended 0 as many times as the length of the previous string. Char 0 is displayed as a space, and each string is displayed on a different line

```
v       % Concatenate stack (which is empty): pushes []
ii      % Input two numbers
&:      % Range between the two numbers
"       % For each
  t     %   Duplicate
  ~     %   Logical negation. This gives a vector of zeros
  @     %   Push current number
  V     %   Convert to string
  h     %   Concatenate with the vector of zeros, which gets automatically
        %   converted into chars.
        % End (implicit). Display stack (implicit), each string on a diferent
        % line, char 0 shown as space

```

# Answer
> 2 votes
# D, ~~133~~ ~~127~~ ~~126~~ ~~125~~ ~~121~~ 119 bytes

```
import std.conv,std.stdio;void f(T)(T a,T b,T s=0){for(T j;j++<s;)' '.write;a.writeln;if(a-b)f(a+1,b,s+a.text.length);}

```

Jelly and APL were taken.

Try it online!

If you're fine with console-dependent results (goes off the same principle as Giacomos's C answer) here's one for ~~72~~ 71 bytes:

```
import std.stdio;void f(T)(T a,T b){while(a<=b){a++.write;'\v'.write;}}

```

## How? (Only D specific tricks)

* `f(T)(T a,T b,T s=0)` D's template system can infer types
* `for(T j;j++<s;)` Integers default to `0`.
* `' '.write;a.writeln` D lets you call `fun(arg)` like `arg.fun` (one of the few golfy things D has)
* `a.text.length` Same as above, and D also allows you to call a method with no parameters as if it was a property (`text` is conversion to string)
* One thing that might be relevant (I didn't use this though) newlines can be in strings!

# Answer
> 2 votes
# , 16 bytes

```
ÀñÙywÒ $pça/jd

```

Try it online!

This would be way easier if I could take `start` `end - start` but I think that's changing the challenge a bit too much.

This takes the start number as input in the buffer and the end number as an argument. It actually creates the ladder from `start` to `start + end` and then deletes everything after the end number.

# Answer
> 2 votes
## Perl, 19 bytes

**Note: `\x0b` is counted as one byte.**

Along with others, I thought using cursor movements would be the shortest route, this does mean it doesn't work on TIO:

```
print"$_\x0b"for<>..<>

```

### Usage

```
perl -e 'print"$_\x0b"for<>..<>' <<< '5
10'
5
 6
  7
   8
    9
     10

```

# Answer
> 2 votes
# Swift 4, 115 bytes

I think nobody would have posted a Swift solution anyway...

```
func f(l:Int,b:Int){for i in l...b{print(String(repeating:" ",count:(l..<i).map{String($0).count}.reduce(0,+)),i)}}

```

Try it online!

# Answer
> 2 votes
# Japt, ~~10~~ 9 bytes

```
òV åÈç +Y

```

Test it online! Returns an array of lines; `-R` flag included to join on newlines for easier viewing.

### Explanation

```
 òV åÈ   ç +Y
UòV åXY{Xç +Y}   Ungolfed
                 Implicit: U, V = inputs, P = empty string
UòV              Create the range [U, U+1, ..., V-1, V].
    åXY{     }   Cumulative reduce: Map each previous result X and current item Y to:
        Xç         Fill X with spaces.
           +Y      Append Y.
                 Implicit: output result of last expression

```

---

Old version, 10 bytes:

```
òV £P=ç +X

```

Test it online!

```
 òV £  P= ç +X
UòV mX{P=Pç +X}  Ungolfed
                 Implicit: U, V = inputs, P = empty string
UòV              Create the range [U, U+1, ..., V-1, V].
    mX{       }  Map each item X to:
         Pç        Fill P with spaces.
            +X     Append X.
       P=          Re-set P to the result.
                   Implicitly return the same.
                 Implicit: output result of last expression

```

# Answer
> 2 votes
# Java 8, 79 bytes

```
(a,b)->{for(String s="";a<=b;System.out.printf("%"+s.length()+"d\n",a++))s+=a;}

```

Try it online!

# Answer
> 2 votes
# Haskell, 39 bytes

```
a%b=scanl((.show).(++).(' '<$))""[a..b]

```

Try it online!

# Answer
> 2 votes
# NotQuiteThere, 5 bytes

```
yr-11

```

Try it online!

Uses the vertical tab trick in Rod's python answer, so doesn't really work on TIO. Input is taken in descending order (`11, 7`)

# Answer
> 1 votes
# QBIC, 25 bytes

```
[:,:|A=space$(_lA|)+!a$?A

```

Explanation:

```
[:     FOR a = <input 1 from cmd line>
,:|    TO <input 2 from cmd line>
A=         SET A$ to
 space$      a number of spaces equal to
 (_lA|)      the current length of A$ (starts as "" = 0)
+!a$         and add a cast-to string of the current loop iterator
?A     PRINT A$
           Loop auto-closed by QBIC

```

# Answer
> 1 votes
# Ruby, 18 bytes

```
->a,b{[*a..b]*?\v}

```

Just for reference, but does not work on TIO:

Try it online!

# Answer
> 1 votes
# PowerShell, 49 bytes

```
$a,$b=$args;$a..$b|%{$l=($z=" "*$l+$_).length;$z}

```

Try it online!

Takes input as two command-line arguments, `$a` and `$b`, forms a range `..` out of them, then loops `|%{}` over that range. Each iteration, we construct a string `$z` of a certain number of spaces `" "*$l` concatenated with our current number `$_`. We then pull out the `.length` of that, re-store it into `$l` for next time, and leave `$z` on the pipeline. Output is implicit.

# Answer
> 1 votes
# Bash + coreutils, 10

```
seq -s^K $@

```

Here `^K` is a literal vertical tab and control character. The xxd dump of this script is as follows - use `xxd -r` to regenerate the actual script:

```
00000000: 7365 7120 2d73 0b20 2440                 seq -s. $@

```

Input range is given as two integers at the command-line.

Not sure if much of an explanation is needed here - `seq` simply does the counting (from `a` to `b`, passed in the `$@` parameter), with `-s` specifying the separator as a vertical tab. This causes the next number to be printed after the previous one, down one line, as required.

# Answer
> 1 votes
# Haskell, 46 bytes

```
a%b=[([a..x-1]>>=show>>" ")++show x|x<-[a..b]]

```

Try it online! Usage: `0%20`. Returns a list of lines. Use `putStr . unlines $ 0%20` for pretty-printing.

# Answer
> 1 votes
# dc, 51 bytes

```
sj0skp[32Plkll1+dsl<S]sS[0sldZlk+sklSx1+pdlj>M]dsMx

```

Try it online!

This pretty much has to be suboptimal, my brain is clearly still in Monday mode. Pretty much just macro `S` printing spaces, and macro `M` doing the rest of the work. Register `l` restarts at zero spaces before running `S`, and compares against register `k`, which we always increment by the number of digits of top-of-stack.

# Answer
> 1 votes
# Perl 5, ~~43~~ ~~42~~ 31 + ~~1 (-a)~~ 0 = ~~43~~ 31 bytes

```
map{say$l=$l=~y// /cr.$_}<>..<>

```

Try it online!

# Answer
> 1 votes
# WendyScript, 50 bytes

```
<<f=>(x,y){<<s=""#i:x->y+1{s+i#i!=0{s+=" "i\=10}}}

f(95, 103)

```

Try it online!

Only issue is once you get past 100000, numbers are outputted in scientific notation (which I should probably change to always display in full form). The online syntax highlighter also dislikes `""` but it *is* parsed correctly.

# Answer
> 1 votes
# Tcl, 80 bytes

```
proc P a\ b {while \$a<=$b {puts [format %[incr i [string len $a]]d $a];incr a}}

```

Try it online!

# Answer
> 1 votes
# SmileBASIC, 43 bytes

```
INPUT A,B
FOR I=A TO B?" "*C;I;
C=CSRX?NEXT

```

**Explanation**

```
?" "*C;I;    'Print C (initially 0) spaces followed by I, with no newline.
C=CSRX       'Set C to the horizontal cursor position.
?            'Print a newline.

```

# Answer
> 1 votes
# SNOBOL4 (CSNOBOL4), 85 bytes

```
	M =INPUT
	N =INPUT
O	OUTPUT =S M
	S =S DUPL(' ',SIZE(M))
	M =LT(M,N) M + 1 :S(O)
END

```

Try it online!

# Answer
> 1 votes
# PHP 7.1, 66 bytes

```
for([,$i,$z]=$argv;$i<=$z;)printf("%".($e+=strlen($i))."d
",$i++);

```

Run with `-nr` or try them online.

# Answer
> 0 votes
# Python 3, 85 bytes

```
f=lambda a,b,n,z:'\n'+' '*(a+n-z)+str(a)+f(a+1,b,n+len(str(a))-1,z) if a!=b+1 else ''

```

Try it online!

# Answer
> 0 votes
K3, 29 bytes

```
{`0:{(1_0+\#:'$:'x)$'x}x+!y-x}

```

example:

```
  {`0:{(1_0+\#:'$:'x)$'x}x+!y-x}[1;15]
1
 2
  3
   4
    5
     6
      7
       8
        9
         10
           11
             12
               13
                 14

```

# Answer
> 0 votes
# JavaScript (ES6) + CSS, 72 + 12 = 84 bytes

```
a=>b=>{for(i=0;a<=b;)document.write(`<x>${"<br>".repeat(i++)+a++}</x>`)}

```

```
x{float:left

```

Takes input in currying syntax with the smaller number first. Outputs the result to the page in HTML.

## Test Snippet

```
let f=

a=>b=>{for(i=0;a<=b;)document.write(`<x>${"<br>".repeat(i++)+a++}</x>`)}

f(0)(8)
f(5)(14)
f(998)(1003)
```

```
x{float:left
```

# Answer
> 0 votes
# Excel VBA, 41 Bytes

Anonymous VBE immediate window function that takes input from range `A1:B1` and outputs to the VBE immediate window

```
For i=[A1]To[B1]:?spc(j)i:j=j+len(i):Next

```

# Answer
> 0 votes
# Sinclair ZX81/Timex TS1000/1500 BASIC ~73 tokenized BASIC bytes

```
 1 LET X=SGN PI
 2 LET Y=CODE "="
 3 LET A=NOT PI
 4 FOR I=X TO Y
 5 PRINT TAB A;I
 6 LET A=A+LEN STR$ I
 7 NEXT I

```

This newer solution has fewer bytes but slightly slower. `SGN PI` is `1`, `CODE "="` is `20` and `NOT PI` is `0`; the `PRINT TAB` command does what you might expect, except a `TAB` in ZX81 land is 1 space; `A` is increased by the length of the `I` variable once converted to a string.

### Old answer (~98 tokenized bytes)

```
 1 LET X=1
 2 LET Y=20
 3 LET A$=""
 4 FOR I=X TO Y
 5 PRINT A$;I
 6 FOR T=1 TO LEN STR$ I
 7 LET A$=A$+" "
 8 NEXT T
 9 NEXT I

```

I'm using the most expensive methods here in terms of bytes (i.e., `SGN PI` is 1, and counts as two bytes in ZX81 land, whereas `1` counts as four bytes), so I could cut the byte count by increasing the typing and making the listing less readable, and slower.

The 'spacing' works by converting the I number to a string and taking the string literal length, using that in a `FOR/NEXT` loop as the destination \[line 6\]. `X` is the start number, and `Y` is the end number.

There are a few limitations to consider, such as only having a 32 columns display by default, and only allowing 22 rows without some `POKE`ing. Also, the screen doesn't scroll when it is full unless you tell it to, with the command `SCROLL`.

# Answer
> 0 votes
# \>\<\>, 56+3 = 59 bytes

```
1</+1$,a\.0e:/o" "\
:1>$:a)?/~}r+\1-:?/~r:n&:&:&=?;&1+ao

```

Try It Online

+3 bytes for -v. Not sure whether I actually need to add this for a function, but better to err on the side of caution

### How It Works

```
1<................\     Initialises the stack with the space counter on top of the inputted numbers
................../~...

...................                  Print the first number
....................r:n&:&:&=?;&1+ao If the first number is equal to the end, exit program. Otherwise increment the first number and print a newline

../+1$,a\... Count the number of digits in the number
:1>$:a)?/... By incrementing a counter and dividing the number by 10 until it's below 10

........\.0e:/... Add the amount of digits to the counter
.......?/~}r+\...

............./o" "\     Print the counter amount of spaces and loop around again
.............\1-:?/~...

```

# Answer
> 0 votes
# Python 3.8 (pre-release), 61 bytes

```
def f(a,b,n=-1):
 for a in range(a,b+1):print(" "*(n:=n+1),a)

```

Try it online!

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


title: Multiplication for geometric algebra

text:
# Question
Title: Multiplication for geometric algebra
The basis vectors for geometric algebra are

$$(e\_0=1), e\_1, e\_2,\dots,e\_n$$

They all square to 1 (we do not consider vectors which square to -1 or zero)

$$e\_i \cdot e\_i = 1$$

They are associative and anticommutative (except \\$e\_0=1\\$ which is associative and **commutative**)

$$e\_i \cdot e\_j =-e\_j \cdot e\_i \\: \\; (i\neq j); \\;and\\; i,j \> 0$$

For example, this product is simplified to

$$e\_1 \cdot e\_3 \cdot e\_3 \cdot e\_5\cdot e\_4 \cdot e\_5 \\ = e\_1 \cdot (e\_3 \cdot e\_3) \cdot (e\_5\cdot e\_4) \cdot e\_5 \\ = e\_1 \cdot (1) \cdot (-e\_4\cdot e\_5) \cdot e\_5 \\ = e\_1 \cdot (-e\_4) \cdot (e\_5 \cdot e\_5) \\ = e\_1 \cdot (-e\_4) \cdot (1) \\ = - e\_1 \cdot e\_4$$

(note that the simplified product is sorted by the index of \\$e\\$)

**Challenge**

If a product of basis vectors is represented by a signed integer where each bit is 1 if the vector is present, or 0 if the vector is not present

$$\begin{align} 0101011 & = e\_0 \cdot e\_1 \cdot e\_3 \cdot e\_5 \\ & = e\_0^1 \cdot e\_1^1 \cdot e\_2^0 \cdot e\_3^1 \cdot e\_4^0 \cdot e\_5^1 \cdot e\_6^0 \\ -0101011 & = -e\_0 \cdot e\_1 \cdot e\_3 \cdot e\_5 \end{align}$$

**Given two signed integers \\$a\\$, \\$b\\$ (you can choose the numeric encoding for negative values), output the product \\$c= a \\:. b\\$**

The input is only 2 signed integers. There are many ways to encode signed integers. You can pick anyone, but the input is only 2 variables.

Note that \\$| c |= |a|\\; XOR \\; |b|\\$ , but the tricky part is to find the sign.

If the language doesn't allow its integer type to encode signed zeros (\\$-00000\\$), the code should return \\$-00001\\$ (because \\$-e\_0^0=-e\_0^1=-1\\$)

Because \\$x=e\_0 \cdot x=x \cdot e\_0\\$, then \\$x=x \\;OR\\; 1\\$, so is equally valid to return 0 or 1 for \\$e\_0\\$

You should at least calculate for 4 basis vectors \\$e\_0=1, e\_1, e\_2, e\_3\\$

Here is a multiplication table generator (to check the right answers), which also offers code in C++, C#, Python and Rust (the webpage requires to manually specify how many vectors square to 1,-1 and 0. You can set 3 (or more) positive, 0 negative, and 0 Zero)

Here is Rosetta code in many languages for geometric algebra

Example:

given a, b: $$a=e\_1 \cdot e\_2=00110$$

$$b=e\_2 \cdot e\_3=01100$$

possible products are:

$$c=a.b=e\_1 \cdot e\_3=01010$$

$$c=b.a=-e\_1 \cdot e\_3=-01010$$

note that $$b.b=-e\_0^0=-1 =-00000$$

So, the sign has to be calculated even if the number is 00000, because \\$+00000 \neq -00000\\$

Example: \\$a=-e\_2=-00100\\ b=-e\_1 \cdot e\_2=-00110\\ c=a.b=(-1 \cdot e\_2)(-1 \cdot e\_1 \cdot e\_2)\\ =(-1) \cdot (e\_2)(-1) \cdot (e\_1 \cdot e\_2)\\ = (e\_2 \cdot e\_1)\cdot e\_2\\ =(-e\_1 \cdot e\_2)\cdot e\_2\\ =(-e\_1) \cdot (e\_2\cdot e\_2)\\ =-e\_1=-00010\\$

but \\$b.a=00010\\$

\\$e\_0=1\\$ and -1 are scalars and commute with any basis vector (do not anticommute), so negative signs on the input can be treated as in standard multiplication of integers: \\$-\*-=+\\ +\*-=-\*+=-\\$

Example: \\$a=e\_1\cdot e\_2 \cdot e\_3=01110\\ b=-e\_1 \cdot e\_2=-00110\\ c=a.b=(e\_1e\_2e\_3)(-e\_1e\_2)\ =-(e\_1e\_2e\_3)(e\_1e\_2)\\ =-(-e\_1e\_2e\_1e\_3e\_2)\\ =-(e\_1e\_1e\_2e\_3e\_2)\\ =-(e\_1e\_1)(-e\_2e\_2e\_3)\\ =e\_3=01000\\ \\ b.a=e\_3=01000\\$

Note that on this case, \\$b.a=a.b\\$, so the basis vectors \\$e\_i\\$ anticommute, but it doesn't means that always \\$b.a=-a.b\\$

---

This is not part of the challenge, but I would appreciate suggestions on how should be encoded vectors which square to -1 or 0

This Pyhton code generates the right answers

# Python 3, 11427 bytes

```

"""3D Projective Geometric Algebra.

Written by a generator written by enki.
"""

__author__ = 'Enki'

import math

class R300:
    def __init__(self, value=0, index=0):
        """Initiate a new R300.

        Optional, the component index can be set with value.
        """
        self.mvec = [0] * 8
        self._base = ["1", "e1", "e2", "e3", "e12", "e13", "e23", "e123"]
        #self._base = ["0001", "0010", "0100", "1000", "0110", "1010", "1100", "1110"]
        if (value != 0):
            self.mvec[index] = value

    @classmethod
    def fromarray(cls, array):
        """Initiate a new R300 from an array-like object.

        The first axis of the array is assumed to correspond to the elements
        of the algebra, and needs to have the same length. Any other dimensions
        are left unchanged, and should have simple operations such as addition
        and multiplication defined. NumPy arrays are therefore a perfect
        candidate.

        :param array: array-like object whose length is the dimension of the algebra.
        :return: new instance of R300.
        """
        self = cls()
        if len(array) != len(self):
            raise TypeError('length of array must be identical to the dimension '
                            'of the algebra.')
        self.mvec = array
        return self

    def __str__(self):
        if isinstance(self.mvec, list):
            res = ' + '.join(filter(None, [("%.7f" % x).rstrip("0").rstrip(".") + (["",self._base[i]][i > 0]) if abs(x) > 0.000001 else None for i,x in enumerate(self)]))
            #res = ' + '.join([x for i,x in enumerate(self)])
        else:  # Assume array-like, redirect str conversion
            res = str(self.mvec)
        if (res == ''):
            return "0"
        return res

    def __getitem__(self, key):
        return self.mvec[key]

    def __setitem__(self, key, value):
        self.mvec[key] = value

    def __len__(self):
        return len(self.mvec)

    def __invert__(a):
        """R300.Reverse

        Reverse the order of the basis blades.
        """
        res = a.mvec.copy()
        res[0] = a[0]
        res[1] = a[1]
        res[2] = a[2]
        res[3] = a[3]
        res[4] = -a[4]
        res[5] = -a[5]
        res[6] = -a[6]
        res[7] = -a[7]
        return R300.fromarray(res)

    def Dual(a):
        """R300.Dual

        Poincare duality operator.
        """
        res = a.mvec.copy()
        res[0] = -a[7]
        res[1] = -a[6]
        res[2] = a[5]
        res[3] = -a[4]
        res[4] = a[3]
        res[5] = -a[2]
        res[6] = a[1]
        res[7] = a[0]
        return R300.fromarray(res)

    def Conjugate(a):
        """R300.Conjugate

        Clifford Conjugation
        """
        res = a.mvec.copy()
        res[0] = a[0]
        res[1] = -a[1]
        res[2] = -a[2]
        res[3] = -a[3]
        res[4] = -a[4]
        res[5] = -a[5]
        res[6] = -a[6]
        res[7] = a[7]
        return R300.fromarray(res)

    def Involute(a):
        """R300.Involute

        Main involution
        """
        res = a.mvec.copy()
        res[0] = a[0]
        res[1] = -a[1]
        res[2] = -a[2]
        res[3] = -a[3]
        res[4] = a[4]
        res[5] = a[5]
        res[6] = a[6]
        res[7] = -a[7]
        return R300.fromarray(res)

    def __mul__(a,b):
        """R300.Mul

        The geometric product.
        """
        if type(b) in (int, float):
            return a.muls(b)
        res = a.mvec.copy()
        res[0] = b[0] * a[0] + b[1] * a[1] + b[2] * a[2] + b[3] * a[3] - b[4] * a[4] - b[5] * a[5] - b[6] * a[6] - b[7] * a[7]
        res[1] = b[1] * a[0] + b[0] * a[1] - b[4] * a[2] - b[5] * a[3] + b[2] * a[4] + b[3] * a[5] - b[7] * a[6] - b[6] * a[7]
        res[2] = b[2] * a[0] + b[4] * a[1] + b[0] * a[2] - b[6] * a[3] - b[1] * a[4] + b[7] * a[5] + b[3] * a[6] + b[5] * a[7]
        res[3] = b[3] * a[0] + b[5] * a[1] + b[6] * a[2] + b[0] * a[3] - b[7] * a[4] - b[1] * a[5] - b[2] * a[6] - b[4] * a[7]
        res[4] = b[4] * a[0] + b[2] * a[1] - b[1] * a[2] + b[7] * a[3] + b[0] * a[4] - b[6] * a[5] + b[5] * a[6] + b[3] * a[7]
        res[5] = b[5] * a[0] + b[3] * a[1] - b[7] * a[2] - b[1] * a[3] + b[6] * a[4] + b[0] * a[5] - b[4] * a[6] - b[2] * a[7]
        res[6] = b[6] * a[0] + b[7] * a[1] + b[3] * a[2] - b[2] * a[3] - b[5] * a[4] + b[4] * a[5] + b[0] * a[6] + b[1] * a[7]
        res[7] = b[7] * a[0] + b[6] * a[1] - b[5] * a[2] + b[4] * a[3] + b[3] * a[4] - b[2] * a[5] + b[1] * a[6] + b[0] * a[7]
        return R300.fromarray(res)
    __rmul__ = __mul__

    def __xor__(a,b):
        res = a.mvec.copy()
        res[0] = b[0] * a[0]
        res[1] = b[1] * a[0] + b[0] * a[1]
        res[2] = b[2] * a[0] + b[0] * a[2]
        res[3] = b[3] * a[0] + b[0] * a[3]
        res[4] = b[4] * a[0] + b[2] * a[1] - b[1] * a[2] + b[0] * a[4]
        res[5] = b[5] * a[0] + b[3] * a[1] - b[1] * a[3] + b[0] * a[5]
        res[6] = b[6] * a[0] + b[3] * a[2] - b[2] * a[3] + b[0] * a[6]
        res[7] = b[7] * a[0] + b[6] * a[1] - b[5] * a[2] + b[4] * a[3] + b[3] * a[4] - b[2] * a[5] + b[1] * a[6] + b[0] * a[7]
        return R300.fromarray(res)

    def __and__(a,b):
        res = a.mvec.copy()
        res[7] = 1 * (a[7] * b[7])
        res[6] = 1 * (a[6] * b[7] + a[7] * b[6])
        res[5] = -1 * (a[5] * -1 * b[7] + a[7] * b[5] * -1)
        res[4] = 1 * (a[4] * b[7] + a[7] * b[4])
        res[3] = 1 * (a[3] * b[7] + a[5] * -1 * b[6] - a[6] * b[5] * -1 + a[7] * b[3])
        res[2] = -1 * (a[2] * -1 * b[7] + a[4] * b[6] - a[6] * b[4] + a[7] * b[2] * -1)
        res[1] = 1 * (a[1] * b[7] + a[4] * b[5] * -1 - a[5] * -1 * b[4] + a[7] * b[1])
        res[0] = 1 * (a[0] * b[7] + a[1] * b[6] - a[2] * -1 * b[5] * -1 + a[3] * b[4] + a[4] * b[3] - a[5] * -1 * b[2] * -1 + a[6] * b[1] + a[7] * b[0])
        return R300.fromarray(res)

    def __or__(a,b):
        res = a.mvec.copy()
        res[0] = b[0] * a[0] + b[1] * a[1] + b[2] * a[2] + b[3] * a[3] - b[4] * a[4] - b[5] * a[5] - b[6] * a[6] - b[7] * a[7]
        res[1] = b[1] * a[0] + b[0] * a[1] - b[4] * a[2] - b[5] * a[3] + b[2] * a[4] + b[3] * a[5] - b[7] * a[6] - b[6] * a[7]
        res[2] = b[2] * a[0] + b[4] * a[1] + b[0] * a[2] - b[6] * a[3] - b[1] * a[4] + b[7] * a[5] + b[3] * a[6] + b[5] * a[7]
        res[3] = b[3] * a[0] + b[5] * a[1] + b[6] * a[2] + b[0] * a[3] - b[7] * a[4] - b[1] * a[5] - b[2] * a[6] - b[4] * a[7]
        res[4] = b[4] * a[0] + b[7] * a[3] + b[0] * a[4] + b[3] * a[7]
        res[5] = b[5] * a[0] - b[7] * a[2] + b[0] * a[5] - b[2] * a[7]
        res[6] = b[6] * a[0] + b[7] * a[1] + b[0] * a[6] + b[1] * a[7]
        res[7] = b[7] * a[0] + b[0] * a[7]
        return R300.fromarray(res)

    def __add__(a,b):
        """R300.Add

        Multivector addition
        """
        if type(b) in (int, float):
            return a.adds(b)
        res = a.mvec.copy()
        res[0] = a[0] + b[0]
        res[1] = a[1] + b[1]
        res[2] = a[2] + b[2]
        res[3] = a[3] + b[3]
        res[4] = a[4] + b[4]
        res[5] = a[5] + b[5]
        res[6] = a[6] + b[6]
        res[7] = a[7] + b[7]
        return R300.fromarray(res)
    __radd__ = __add__

    def __sub__(a,b):
        """R300.Sub

        Multivector subtraction
        """
        if type(b) in (int, float):
            return a.subs(b)
        res = a.mvec.copy()
        res[0] = a[0] - b[0]
        res[1] = a[1] - b[1]
        res[2] = a[2] - b[2]
        res[3] = a[3] - b[3]
        res[4] = a[4] - b[4]
        res[5] = a[5] - b[5]
        res[6] = a[6] - b[6]
        res[7] = a[7] - b[7]
        return R300.fromarray(res)

    def __rsub__(a,b):
        """R300.Sub

        Multivector subtraction
        """
        return b + -1 * a

    def smul(a,b):
        res = a.mvec.copy()
        res[0] = a * b[0]
        res[1] = a * b[1]
        res[2] = a * b[2]
        res[3] = a * b[3]
        res[4] = a * b[4]
        res[5] = a * b[5]
        res[6] = a * b[6]
        res[7] = a * b[7]
        return R300.fromarray(res)

    def muls(a,b):
        res = a.mvec.copy()
        res[0] = a[0] * b
        res[1] = a[1] * b
        res[2] = a[2] * b
        res[3] = a[3] * b
        res[4] = a[4] * b
        res[5] = a[5] * b
        res[6] = a[6] * b
        res[7] = a[7] * b
        return R300.fromarray(res)

    def sadd(a,b):
        res = a.mvec.copy()
        res[0] = a + b[0]
        res[1] = b[1]
        res[2] = b[2]
        res[3] = b[3]
        res[4] = b[4]
        res[5] = b[5]
        res[6] = b[6]
        res[7] = b[7]
        return R300.fromarray(res)

    def adds(a,b):
        res = a.mvec.copy()
        res[0] = a[0] + b
        res[1] = a[1]
        res[2] = a[2]
        res[3] = a[3]
        res[4] = a[4]
        res[5] = a[5]
        res[6] = a[6]
        res[7] = a[7]
        return R300.fromarray(res)

    def ssub(a,b):
        res = a.mvec.copy()
        res[0] = a - b[0]
        res[1] = -b[1]
        res[2] = -b[2]
        res[3] = -b[3]
        res[4] = -b[4]
        res[5] = -b[5]
        res[6] = -b[6]
        res[7] = -b[7]
        return R300.fromarray(res)

    def subs(a,b):
        res = a.mvec.copy()
        res[0] = a[0] - b
        res[1] = a[1]
        res[2] = a[2]
        res[3] = a[3]
        res[4] = a[4]
        res[5] = a[5]
        res[6] = a[6]
        res[7] = a[7]
        return R300.fromarray(res)

    def norm(a):
        return abs((a * a.Conjugate())[0]) ** 0.5

    def inorm(a):
        return a.Dual().norm()

    def normalized(a):
        return a * (1 / a.norm())

e1 = R300(1.0, 1)
e2 = R300(1.0, 2)
e3 = R300(1.0, 3)
e12 = R300(1.0, 4)
e13 = R300(1.0, 5)
e23 = R300(1.0, 6)
e123 = R300(1.0, 7)

if __name__ == '__main__':
    #print("e1*e1         :", str(e1*e1))
    #print("pss           :", str(e123))
    #print("pss*pss       :", str(e123*e123))

    a = [R300(1.0, i) for i in range(0, 8) ]
    b = [-1 * x for x in a]
    a = a + b
    print("Vectors:")
    [print(str(x)) for x in a ]
    print("Products")

    def javascriptCode(a,b):
        def ArnauldEncoding(x):
            answer= str(x)
            if answer[0]=="-":
                return answer[1:]+"1"
            else:
                return answer+"0"
        return "".join(["console.log(\"0b",ArnauldEncoding(a) , "\",\"*\",\"0b" , ArnauldEncoding(b),"\",\"=\",","f(0b" , ArnauldEncoding(a) , ")(0b" , ArnauldEncoding(b) , ").toString(2), \"== \",\"" , ArnauldEncoding(a * b),"\")"])

    def RubyCode(a,b):
        return "".join(["[","0b",str(a),",","0b",str(b),"],"]).replace("0b-","-0b")

    if True:
        Productos = ["".join([str(x),"*",str(y),"=",str(x * y)]) for x in a for y in a]
        #Productos = [javascriptCode(x,y) for x in a for y in a]
        #Productos = [RubyCode(x,y) for x in a for y in a]
        #Productos = [str(x*y) for x in a for y in a]

        Origen = ["1e1", "1e2", "1e3", "1e12", "1e13", "1e23", "1e123"]
        Destino = ["0010", "0100", "1000", "0110", "1010", "1100", "1110"]

        Reemplazo = dict(zip(Origen, Destino))
        Binario = Productos
        for key in sorted(Reemplazo, key=len, reverse=True): # Through keys sorted by length
            Binario = [x.replace(key,Reemplazo[key]) for x in Binario]
        [print(x) for x in Binario]
    a = a

```

Try it online!

# Answer
# JavaScript (ES6),  ~~73~~  65 bytes

Expects `(a)(b)`, two integers where the least significant bit holds the sign (\\$0\\$ for positive, \\$1\\$ for negative) and all other bits are used to store the absolute value.

Returns the product \\$c\\$ in the same format.

```
a=>b=>a^b^(g=a=>(b/=2)&&(h=n=>b&!!n&&!h(n&~-n))(a)^g(a>>1))(a>>2)

```

Try it online!

### How?

We compute the product \\$p\\$ of \\$a\\$ and \\$b\\$ as follows:

* We start with \\$p=a\operatorname{xor}b\\$. This immediately gives the correct absolute value and initializes the sign according to the signs of \\$a\\$ and \\$b\\$.
* For each set bit in \\$b\\$ at index \\$i\>0\\$, we invert the sign bit of \\$p\\$ if there's an odd number of set bits in \\$a\\$ at an index greater than \\$i\\$.

### Commented

```
a => b =>         // (a, b) = input integers
a ^ b ^ (         // compute a XOR b XOR ...
  g = a =>        // ... the result of the recursive function g, taking a:
    (b /= 2) &&   //   divide b by two; this is shorter than a right shift
                  //   and will eventually evaluate to zero because of
                  //   arithmetic underflow
    ( h = n =>    //   h is another recursive function counting the bits
                  //   set in n, provided that the LSB of b is set:
      b & !!n &&  //     stop if the LSB of b is not set or n = 0
      !h(n & ~-n) //     otherwise, invert the result and do a recursive
                  //     call where the least significant bit set in n
                  //     is cleared
    )(a) ^        //   initial call to h with n = a
    g(a >> 1)     //   XOR the result with a recursive call to g with
                  //   floor(a / 2)
)(a >> 2)         // initial call to g with floor(a / 4), which discards
                  // the sign bit and the 1st bit of the absolute value

```
> 4 votes

# Answer
# JavaScript (ES6), 42 bytes

(standing on Arnauld's shoulders)

Using same encoding as Arnauld. That is: Expects `(a)(b)`, two integers where the least significant bit holds the sign (\\$0\\$ for positive, \\$1\\$ for negative) and all other bits are used to store the absolute value. Returns the product \\$c\\$ in the same format.

```
a=>b=>a^b^(g=x=>x&&x^g(x/2))(g(a/4)&b/2)&1

```

Explanation:

* really it's `a=>b=>a^b^(g=x=>x&&x^g(x>>1))(g(a>>2)&(b>>1))&1` but using divisions instead of rightshifts to save a char each (taking advantage of the fact that the recursion stops on arithmetic underflow-- same crazy trick as Arnauld-- and that fractional parts are discarded by bitwise operators
* since (b\>\>1) was changed to (b/2), the parens can be removed around the b/2 since / binds tighter than &
* and & binds tighter than ^ so no parens needed there either
* start with `a^b`, same explanation as Arnauld.
* `g(x)` is "xor of all rightshifts of x", i.e. `g(x) = x^(x>>1)^(x>>2)^...`
* note that `g(x)&1` is the parity of the number of bits set in `x`
* each bit position in `g(a>>2)&(b>>1)` is the parity of the number of swaps involving that position in (the magnitude part of) `b`, so the desired parity of the total number of swaps will be the parity of the number of bits set in `g(a>>2)&(b>>1)`; that is, `g(g(a>>2)&(b>>1))&1`.
> 3 votes

# Answer
# Python 3, 69 bytes

```
def g(a,b):
 r=a^b;b&=-2
 while a:a>>=1;r^=a&b&1;b=b>>1^b&1
 return r

```

Try it online!

The lowest bit is the sign. There is no test script and all GA packages I found are really hard to apply here, so I did not test this thoroughly. Please let me know if this is incorrect.

I'm not a code golfer, but anyone feel free to use this solution and code-golfify it.

It took me a while to come up with this algorithm... a bit hard to explain.

Does it makes sense to store the sign bit? In the end positive and negative have to be combined anyway?

Some explanation:

```
def g(a, b):
    r = a ^ b
    b &= -2             # I think the sign bit needs to be cleared
    while a:
        a >>= 1         # iterate through all bits
        r ^= a & b & 1  # modify sign of result
        b = (b >> 1) ^ (b & 1)  # iterate through bits of b, but lowest bit is XOR or all bits so far
    return r

```

The lowest bit of `b` is used as an aggregator of all its bits with XOR. It's tracking the parity - comparable to counting tail bits in more direct solutions. It took some thought to show that this equivalent.
> 3 votes

# Answer
# Ruby, ~~98 ...~~  62 bytes

```
->c,w,d,x{[c^d,w*x*(~k=0)**((0..c+d).sum{|x|c[x]*k+=d[x-1]})]}

```

Try it online!

Input: `[abs(a),sign(a),abs(b),sign(b)]`

Output: `[abs,sign]`

Thanks Arnauld for the idea of splitting input and for shaving a couple of bytes.

### How it works:

The sign is determined by the number of hops: example: `e3*(e1e2) = -e1e3*(e2) = (-e1)*(-e2e3) = e1e2e3`

In this case e3 must "hop" over e1 and e2 to get to its own place, and for an even number of hops the sign is positive.
> 2 votes

# Answer
# 05AB1E (legacy), 35 bytes

```
bD€¨0ìï©C`^s€θ·<P®€S`.sR‚ζOÆ.±!P*¨ì

```

Input as two integers where the trailing bit of its binary representation represents the negative (`0`) or positive (`1`) (i.e. input `24` is `-12`/`-1100` and input `25` is `12`/`1100`).

Try it online or verify some more test cases.

**Explanation:**

```
b                    # Convert both integers in the (implicit) input-pair to a binary
                     # string
 D                   # Duplicate this pair of binary strings
  €¨                 # Remove the trailing bit from each
    0ìï              # Prepend a "0", and cast it to an integer
                     # (empty strings become "0", everything else remains the same)
       ©             # Store this in variable `®` (without popping)
        C            # Change these binary strings to integers
         `           # Pop and push both values separated to the stack
          ^          # Bitwise-XOR them together
 s                   # Swap to get the pair of binary strings again
  €θ                 # Leave just the trailing bits
                     # Convert the 0 to -1:
    ·                #  Double both: 0→0; 1→2
     <               #  Decrease both by 1: 0→-1; 2→1
      P              # Take the product of this as our starting sign
  ®                  # Push the binary string from `®` again
   €S                # Convert both to a list of bits
     `               # Pop and push the lists separated to the stack
      .s             # Get the suffices of the second one
        R            # Reverse this list of suffices
         ‚           # Pair the two lists together
          ζ          # Zip/transpose, swapping rows/columns,
                     # implicitly using a space filler if they're of unequal lengths
           O         # Sum each inner-most list
                     # (the spaces are counted as 0 in the legacy version)
            Æ        # Reduce both lists by subtracting
             .±      # Get the sign of this (-1 if <0; 0 if ==0; 1 if >0)
               !     # Get the factorial of this: -1 if -1; 1 if 0 or 1)
                P    # Take the product of these values
                 *   # Multiply it to our initial sign value
                  ¨  # Remove the trailing "1" from this sign value
                   ì # And prepend this "" or "-" in front of the XOR-ed value
                     # (after which it is output implicitly as result)

```
> 2 votes

# Answer
# Retina, 102 bytes

```
\d\b
0
^'0P`\d+
(.+)-
-$1
+r`((0|(?<-3>1)|(1))*)((0)|1)((?<-7>.)*\*.*)1(?=(.)*)
$#3*-$1$#5$6_
--|\*.+

```

Try it online! Link includes test cases. Assumes the input is in the binary form as generated by the program linked in the question. (Save 9 bytes if the inputs are always padded and 7 bytes if they never include e₀). Explanation:

```
\d\b
0

```

Remove e₀ if it appears.

```
^'0P`\d+

```

Pad both numbers to the same length. (Note that when run on a test suite, all of the numbers in the suite are padded to the same length.)

```
(.+)-
-$1

```

If the second number is negative, negate both numbers.

```
+r`((0|(?<-3>1)|(1))*)((0)|1)((?<-7>.)*\*.*)1(?=(.)*)
$#3*-$1$#5$6_

```

For each `1` bit in the second number, working from e₁ upwards, use a .NET balancing group to find the matching bit in the first number and another .NET balancing group to count the parity of the `1` bits before that bit. If the parity is odd, negate the first number. Toggle the matching bit in the first number and replace the `1` bit in the second number with a `_` (golfier than a `0`).

```
--|\*.+

```

Remove any double negatives and the second number (which is now zero at this point).
> 1 votes

# Answer
# Python 3, 768 bytes

i got a bit stuck on this one, wanted to post anyways in case someone else has an idea.

instead of counting bits this uses 'rewriting rules' and a dictionary to rewrite substrings of the e-string iteratively until the expression is simplified and cant be rewritten anymore.

the main problem im having is converting from integer to string and back takes a lot of bytes. the second problem is encoding the dictionary takes a lot of bytes.

main function is m(), the for -15 to 16 loop is a test loop. note i consider 0000 to be equivalent to 0001 since \\$e\_0^0 = e\_0^1\\$

```
rules = {'11':'','22':'','33':'','10':'-01','13':'-31','20':'-02','21':'-12','30':'-03','31':'-13','32':'-23','3-':'-3','2-':'-2','1-':'-1','0-':'-0','--':'',}
def dorules(s):
  for r in rules.keys():
    s=s.replace(r,rules[r]).replace(' ','')
  return s
def b2e(x):
  s='-' if x<0 else ''
  for i in range(1,3):
    if abs(x) & (2**i):
        s += str(i)
  return s
def e2b(x):
  s=0
  for i in x:
    try: s|=2**int(i)
    except: pass
  b=bin(s)[2:].zfill(4)
  if x=='': return b
  if x=='-': return '-'+b
  if int(x)<0: return '-'+b
  return b
def m(i,j):
  s=['',b2e(i)+b2e(j)]
  while True:
    s += [dorules(s[-1])]
    if s[-2] == s[-1] or s[-3] == s[-1]: break
  return s[-1]
def sign(x): return '-' if int(x)<0 else ''
for i in range(-15,16):
  for j in range(-15,16):
    c=e2b(m(i,j))
    print(sign(i)+bin(abs(i))[2:].zfill(4)+'*'+sign(j)+bin(abs(j))[2:].zfill(4)+'='+c)

```
> 0 votes

---
Tags: code-golf, math, abstract-algebra
---


title: Generate Random Boggle Board

text:
# Question
Title: Generate Random Boggle Board
Generate a 4x12 grid of letters / spaces:

Each die should appear precisely once, location randomly chosen. Locations should be approximate a uniform random permutation of the dice. Display a random (again, approximately uniform) face of each die. Left-justify the face in the 3-character window. For example,

```
A  E  A  A
E  C  D  E
D  A  Qu E
E  A  H  D

```

Is a non-randomized board in the format I want. Trailing space is allowed.

The dice:

```
A  A  E  E  G  N
E  L  R  T  T  Y
A  O  O  T  T  W
A  B  B  J  O  O
E  H  R  T  V  W
C  I  M  O  T  U
D  I  S  T  T  Y
E  I  O  S  S  T
D  E  L  R  V  Y
A  C  H  O  P  S
H  I  M  N  Qu U
E  E  I  N  S  U
E  E  G  H  N  W
A  F  F  K  P  S
H  L  N  N  R  Z
D  E  I  L  R  X

```

Amusing fact: there is only 1 K in the set. What other letter exclusively shares that die?

This is so the program with the shortest bytecount wins!

# Answer
> 5 votes
## GolfScript, 116 bytes

Since the scoring is in bytes, I figure that means we can use *all* bytes in the solution. Going outside the printable ASCII set allows a somewhat shorter solution than Peter Taylor's, at the cost of making the code harder to display here. Without the unprintable data, my code looks like this:

```
'57 BYTES OF BINARY DATA HERE'256base 26base 6/{;9.?rand}${6rand=65+.81='  u '2/=}%8/n*

```

It's pretty similar to Peter Taylor's solution, and I admit to shamelessly borrowing bits of it (such as the `.81=' u '2/=` trick), although I think I managed to shorten his shuffle slightly, even after spending an extra ~~char~~ byte for better randomness.

The binary string in the beginning of the script contains unprintable characters, and so cannot be directly pasted here. Instead, I'll provide the script as a hex dump:

```
0000000: 2701 8302 7c56 97d5 ec9c 52e3 462e 44d7  '...|V....R.F.D.
0000010: a8d2 81c9 6115 fc80 4da4 6cd3 b06f a6d8  ....a...M.l..o..
0000020: 4e7e 2029 12a9 f331 0b83 3481 de36 81e2  N~ )...1..4..6..
0000030: 41b4 534d dee8 13f7 ccfd 2732 3536 6261  A.SM......'256ba
0000040: 7365 2032 3662 6173 6520 362f 7b3b 392e  se 26base 6/{;9.
0000050: 3f72 616e 647d 247b 3672 616e 643d 3635  ?rand}${6rand=65
0000060: 2b2e 3831 3d27 2020 7520 2732 2f3d 7d25  +.81='  u '2/=}%
0000070: 382f 6e2a                                8/n*

```

On Linux, or any system with the `xxd` utility installed, this hex dump can be turned back into a working 116-byte GolfScript program by passing it through `xxd -r`.

**Edit:** Replaced `999rand` with `9.?rand` for *much* better randomness. The shuffle should now be about as close to perfect as the underlying RNG allows.

# Answer
> 4 votes
## Python 2.7, ~~253 229~~ 215 chars

```
from random import*
j=0
for x in map(choice,sample("AAEEGN ELRTTY AOOTTW ABBJOO EHRTVW CIMOTU DISTTY EIOSST DELRVY ACHOPS HIMNQU EEINSU EEGHNW AFFKPS HLNNRZ DEILRX".split(),16)):j+=1;print x+' u'[x=='Q']+'\n'[j%4:],

```

Most of the characters are just the dice themselves. I didnt want to spend too much time trying to reduce it too much

minor edit: removed 2 unnecessary bytes (extra spaces)

edit2: down to 229

edit3: down to 215

# Answer
> 3 votes
## GolfScript (141 139 137 charsbytes)

Of which 94 expand to the string containing the dice. Figure doesn't include the unnecessary newline inserted to make it wrap so that the code can be seen without scrolling:

```
'Y
ISY
XIAOOW
VYAAEEGNABBJOOEHRTVWCIMOTUEIOSSTACHOPSHIMNQUEEINSUEEGHNWAFFKPSHLNNRZ'n/'TTELRD'*
6/{[6rand=99rand\]}%${1=.81='  u '2/=}%8/n*

```

# Answer
> 2 votes
## Powershell, 234 characters

```
$d=(0..15|%{@{'AAEEGNELRTTYAOOTTWABBJOOEHRTVWCIMOTUDISTTYEIOSSTDELRVYACHOPSHIMNQUEEINSUEEGHNWAFFKPSHLNNRZDEILRX'[6*$_+(random)%6]=random}.GetEnumerator()}|sort Value|%{$_.Key})
0..3|%{($d[($_*4)..($_*4+3)])-join"   "-replace'Q ','Qu'}

```

Here's the same code with extra whitespace, in an attempt at improving readability :-)

```
#########################################
# roll the 16 dice and shuffle them     #
#########################################

$d=(
        0..15 | % {
                    @{
                       'AAEEGNELRTTYAOOTTWABBJOOEHRTVWCIMOTUDISTTYEIOSSTDELRVYACHOPSHIMNQUEEINSUEEGHNWAFFKPSHLNNRZDEILRX'[6*$_+(random)%6]=random
                     }.GetEnumerator()
                  } | sort Value | % {
                                        $_.Key
                                     }
    )

############################################
# add the 16 results to the 4 by 4 grid    #
############################################

0..3 | % {
            ($d[($_*4)..($_*4+3)]) -join "   " -replace 'Q ','Qu'
         }

```

I'm not aware of a built in `shuffle` feature in powershell, so I turned each result into a key-value pair - the key equalling a dice result and the value equalling a random number. Then it was just a case of sorting these pairs by the value then outputting the keys.

# Answer
> 2 votes
## Ruby, ~~201~~ 197 chars

```
%W(AAEEGN ELRTTY AOOTTW ABBJOO EHRTVW CIMOTU DISTTY EIOSST DELRVY ACHOPS HIMNQU EEINSU EEGHNW AFFKPS HLNNRZ DEILRX).sample(16).map{|c|c[rand 6]}.each_slice(4){|x|puts x.join("  ").gsub(/Q ?/,"Qu")}

```

(and it's a one-liner)

Edit 1: Used %W() to avoid the .split and a pair of quotes.

Edit 2: Made it to spec (two spaces between each output column)

# Answer
> 1 votes
## Perl, 179 chars

```
@d=(Qu,map"$_ ",HIMNUAAEEGNELRTTYAOOTTWABBJOOEHRTVWCIMOTUDISTTYEIOSSTDELRVYACHOPSEEINSUEEGHNWAFFKPSHLNNRZDEILRX
=~/./g);print+(splice@d,6*int rand@d/6,6)[rand 6],@d%24?$":$/while@d

```

Here's a verbose version of the program:

```
my $fullset = "HIMNUAAEEGNELRTTYAOOTTWABBJOOEHRTVWCIMOTUDISTTY"
           . "EIOSSTDELRVYACHOPSEEINSUEEGHNWAFFKPSHLNNRZDEILRX";
my @dice = ("Qu");
push @dice, "$_ " for split //, $fullset;
while (@dice) {
    my @die = splice @dice, 6 * (int rand @dice / 6), 6;
    print $die[rand 6];
    print @dice % 24 ? " " : "\n";
}

```

# Answer
> 1 votes
# Vyxal, 85 bytes

```
«3꘍Ẋʀɖ>¯ɖ\4ȧḊ#⅛F>ẇ#₂⟑†ql~-ṡ²<vŻ%)∆₆U÷↵ʁʀeµṘbD{⇧½⁰ṙ⟩ĊI3≥⁰?λ«16/v℅Ṗ℅4ẇƛ÷W‛  j;⁋⇧‛Q ‛QuV

```

Don't try it Online! Because it breaks the interpreter trying to handle 16! permutations of the dice at once. Would work given enough memory + time though. Try this one that doesn't shuffle online!

```
«...«                           # Compressed string
     16/                        # Into 16 pieces
        v℅                      # Random choice from each
          Ṗ℅                    # Shuffle
            4ẇ                  # Split into four pieces
              ƛ      ;          # Foreach...
               ÷W               # To list of characters
                 ‛  j           # Joined by double spaces
                      ⁋⇧        # Joined by newlines and uppercased
                        ‛Q ‛QuV # Replace `Q ` with `Qu`

```

# Answer
> 0 votes
# Perl 5, 157 bytes

```
@d{JobaotwHTVErHnZlRIXDeLtYrDELVyDItsHOPCafKPsIeUneagWeHnQUHImCIOUtEOsI=~s/[a-z]/\U$&$&/gr=~/.{6}/g}++;print$_=(/./g)[rand 6],/Q/?u:$",++$-%4?$":$/for keys%d

```

Try it online!

## Explanation

This solution builds up the dice from the long string, replacing occurrences of lowercase letters with two of their uppercase companions (`s/[a-z]/\U$&$&/gr`) resulting in an ordering of 16 sets of 6 characters (`/.{6}/g`) which are then used as hash keys and set to `1` (`@d{...}++`). Since keys aren't stored in a particular order in Perl, this gives the ordering of the dice the required randomness.

Then for each of the `keys` in `%d`, `print` a `rand`omly selected char from the list, either `u` or `$"` (which defaults to space) depending on whether or not the randomly selected letter was `Q`, and either `$"` or `$/` (which defaults to newline) depending on whether or not we're working on a multiple of 4.

I quite enjoyed playing with the ordering to maximise saved characters, making sure that each dice ends with a letter that the next starts with and keeping other doubles in the middles of each set of 6. 68 bytes of data, but the decoding is a little expensive. Maybe it'll help someone else though!

# Answer
> 0 votes
# Batch 252 bytes

Note: script = 243 bytes + 9 bytes required to invoke script with Delayed expansion enabled from cmd.exe:

```
Cmd/Von/Cboggle.bat

```

**boggle.bat**

```
@Set c=0&For %%G in (AAEEGN ELRTTY AOOTTW ABBJOO EHRTVW CIMOTU DISTTY EIOSST DELRVY ACHOPS HIMNQU EEINSU EEGHNW AFFKPS HLNNRZ DEILRX)Do @Set D=%%G&Set/ac+=1&For /f %%i in ('Set/A!random!%%6')Do @<nul Set/p=!D:~%%i,1! &If !c!==4 (Echo(&Set c=0)

```

---
Tags: code-golf, random, boggle
---


title: Insist on an answer

text:
# Question
Title: Insist on an answer
At runtime, keep prompting for *a line of input* until the user inputs something (other than an empty newline), i.e. does not just press `Enter` or `OK`. Output or result is neither required nor prohibited.

### Pseudo-code 1

```
myform = new form("GUI")
myform.mytxt = new editfield("")
myform.ok = new button("OK")
repeat
  waitfor(myform.ok,"click")
until myform.mytxt.content <> ""

```

### Pseudo-code 2

```
LET TEXT = ""
WHILE TEXT = "" DO
  TEXT = PROMPT("")
ENDWHILE

```

### Example 1

Program runs and immediately pops up a form with a single text field and an `OK` button.
User clicks the `OK` button.
Nothing happens.
User pastes "hello world" into the text field and clicks the `OK` button.
Program terminates.

### Example 2

Function is called and immediately displays a blank line and a blinking cursor.
User presses `Enter`.
Cursor moves down one line.
User presses `Enter`.
Cursor moves down one line.
User presses `P``P``C``G``Enter`
Function returns.

# Answer
# TI-BASIC, 2 bytes

```
:Prompt X

```

TI-BASIC does this automatically. Once input is given, it will quit.

Here is a GIF:

Watch the count on the `enter` key in the Key Press History. Created with **TI-SmartView CE** and ezgif.com.
> 16 votes

# Answer
# Python 3, 18 bytes

```
while''==input():0

```

Try it online!
> 16 votes

# Answer
# JavaScript, ~~37~~ ~~22~~ 17 bytes

```
while(!prompt());

```

```
while(!prompt());
```

## Explanation

The `while` keyword starts the `while` loop. In the condition of the loop, `!prompt()` asks for input and checks whether it is given or not. If it isn't given, the body of the loop is executed, which in our case is empty, then the interpreter goes back to the loop condition. The same process happens over and over again until the user gives the input.
> 16 votes

# Answer
# sed, 4

```
/./q

```

Waits for a line of input that has 1 or more characters, then quits.

Try it online. But it works better on a live shell:

```
sed '/./q'

```
> 15 votes

# Answer
# HTML5, ~~33~~ 22 bytes

```
<form><input required>

```

```
<form><input required>
```

## Explanation

The `required` attribute on the `<input>` causes the browser to inform the user "this field is required"-sort-of-message, if they do not enter a value. However, when they enter a value, the value is sent to the URL of the `action` attribute of the `<form>` (which in our case is the current file itself, since we haven't specified any value explicitly).

This was tested on the latest version of Google Chrome (version 55.0). May work in other browsers and versions.
> 9 votes

# Answer
# Java, 55 bytes

```
void f()throws Exception{while(System.in.read()==10);}}

```

If I remember correctly (it's been a while since I've been active on PPCG), my program can just be a function.

This is system specific; it only works on systems where the end-of-line character is a single newline. If the end-of-line character is instead a carriage return, replace the `10` with `13`. On Windows, this doesn't work, as end-of-line on windows is `\r\n`.

This makes use of the fact that I can read directly from `System.in`.
> 9 votes

# Answer
# Jelly, 3 bytes

```
ɠṆ¿

```

Not much to look at on TIO, I'm afraid.

Try it online!

### How it works

This is a niladic program, meaning that it takes no input arguments. The implicit argument and return value are both **0** in this case.

`¿` (while) is a quick that pops two links from the link stack: a condition () and a body.

is a monadic atom: flat logical NOT. If the previous return value is falsy (here, **0** or an empty string), it returns **1** and the body is called.

`ɠ` is a niladic atom; it reads a raw line from STDIN and returns the result.

Once `ɠ` reads a non-empty line,  returns **0** and we break out of the loop.
> 8 votes

# Answer
# Pyth, 3 bytes

```
W!w

```

Try it online!

Translated to Python:

```
while Pnot(input()):
 pass

```
> 8 votes

# Answer
# brainfuck, 26 bytes

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

```

Try it online!
> 6 votes

# Answer
# C, ~~52 bytes~~, ~~33 bytes~~, 29 bytes

-19 bytes thanks to Justin

-4 bytes thanks to Christoph

```
main(){while(getchar()==10);}

```

10 is equal to '\n' - In case this isn't obvious.
> 5 votes

# Answer
# Perl 5, 8+1 (-p or -n flag) bytes

```
/./&&die

```

Takes input from stdin and dies as soon as the regex matches anything except a newline.
> 5 votes

# Answer
# R, ~~27~~ ~~24~~ ~~23~~ 22 bytes

```
while(!sum(scan()^0))t

```

Takes input from stdin, and repeat as long as input is of length 0. Cut off some bytes due to Jarko Dubbeldam and MickyT. Replaced the `{}` with `t` to save another byte.
> 5 votes

# Answer
## Bash, 51 bytes (39 without "#!/bin/bash")

It's my first time participating in PPCG, so dont be to rude ;D

```
#!/bin/bash
read a
while [ -z "$a" ]
do
read a
done

```
> 5 votes

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

```
class C{static void Main(){for(;System.Console.ReadLine()!="";);}}

```

Try it online!

-6 bytes thanks to raznagul.
> 4 votes

# Answer
# Java, ~~128~~ 126 bytes

2 bytes thanks to Kevin Cruijssen.

```
import java.util.*;class a{public static void main(String[]a){for(Scanner s=new Scanner(System.in);s.nextLine().isEmpty(););}}

```

Try it online!
> 4 votes

# Answer
# AWK, 8 11 bytes

```
NF{exit}

```

Wait for input. If the number of fields in input is more than 0, exit.

**EDIT:**

I've just realized that this doesn't work for input containing whitespace characters only. IFS needs to be set to empty string using `-F ""` command line option. Therefore +3 bytes.

Try it online!
> 4 votes

# Answer
## QBasic 4.5, 15 bytes

```
INPUT a$:IF a$=""THEN RUN

```

Asks for input, then checks if any was given. If not, `RUN` restarts the program.
> 4 votes

# Answer
# Ruby, 13 bytes

```
gets until/./

```

I wish `gets` took a Regexp argument.
> 4 votes

# Answer
# PHP, 18 bytes

```
while(!readline())

```
> 3 votes

# Answer
# Perl, 15 12 bytes (11 + -n flag)

-3 bytes thanks to manatwork

```
1/0if$/ne$_

```

Explanation:

The -n flag places a read loop around the program, turning it into:

```
LINE:
while (<>) {
    1/0 if $/ ne $_  # Spaces added for clarity.
}

```

Where "\<\>" reads a line from stdin to the variable $\_. If the line contained more than the ending newline (ne is string inequality, $/ is the input record separator which defaults to newline), a division by zero is performed which causes the program to output an error message and terminate.
> 3 votes

# Answer
# Mathematica, ~~26~~ 20 bytes

```
For[,Input[]==Null,]

```
> 3 votes

# Answer
# SpecBAS - 34 bytes

```
1 DO : INPUT a$: LOOP UNTIL a$<>""

```

Just loops until non-empty string is entered.
> 3 votes

# Answer
## Haskell, ~~19~~ 17 bytes

```
f=do""<-getLine;f

```

Defines a function `f` that if it reads the empty line calls itself again. When reading a non-empty line an exception is raised and the recursion is stopped.

Edit: @Laikoni replaced the parameter with a pattern match and saved 2 bytes. Thanks!
> 3 votes

# Answer
# Java, ~~66~~ ~~64~~ 60 bytes

```
int a(){return!System.console().readLine().isEmpty()?0:a();}

```

My first Java answer, would love some tips!
> 3 votes

# Answer
# Aceto, ~~9~~ ~~5~~ 4 bytes

`r`ead a value, negate it (`!`; implicitly casting to a boolean), and mirror horizontally if the value is truthy (`|`).

```
!
r|

```
> 3 votes

# Answer
# Charcoal, 4 bytes

```
Ｗ¬Ｓω

```

## Explanation

```
Ｗ      While
  ¬Ｓ   Logical not of string input
     ω  Print ""

```
> 2 votes

# Answer
# 05AB1E, 5 bytes

```
[IõÊ#

```

Explanation:

```
[     Start infinite loop
 I    One line of input
   Ê  Not equal to
  õ   Empty string
    # Break if true

```

Try it online!
> 2 votes

# Answer
# PowerShell, 20 Bytes

```
for(;!(read-host)){}

```

runs a for loop,

`read-host` prompts for input

if read-host returns nothing it evals to false, so we invert that `!(...)` and use that as the loop end check.

much shorter than any `do{$a=read-host}while($a-eq"")` type solution involving variables.
> 2 votes

# Answer
# MATL, 4 bytes

```
`jn~

```

This needs to be executed with the MATL interpreter running in Octave (not in Matlab). The reason is that in Matlab, unlike in Octave, the underlying function `input('','s')` (unevaluated input) interprets an input consisting of only spaces as empty input.

Gif or it didn't happen:

### Explanation

```
`     % Do...while loop
  j   %   Take input as a string
  n   %   Number of elements
  ~   %   Negate. Gives true if number of elements was zero, and false otherwise
      % End loop (implicit). If top of the stack is true: next iteration. Else: Exit

```
> 2 votes

# Answer
# Swift, 22 bytes

```
while readLine()==""{}

```
> 2 votes

# Answer
# CJam, 5 bytes

```
{l!}g

```

Try it online! (TIO doesn't really show the proper behaviour)

**Explanation**

```
{      e# Do:
 l     e#  Read next line of input
  !    e#  Boolean negate (empty strings are falsy)
   }g  e# Pop the top of stack, if truthy, repeat.

```
> 2 votes

# Answer
# Clojure, 32 bytes

```
(some seq(repeatedly read-line))

```

`some` returns the first true value of (seq x).

`seq` gives a sequence for a collection (e.g. a String) or `nil` if the collection is empty.

`nil` counts as false for `some`, so it will ignore any empty input, completing when a non-empty string is entered.
> 2 votes

# Answer
# Red, ~~20~~ 16 Bytes

```
until[""<>ask""]

```

## Explanation:

```
until   does the code that's inside the [blocks] until it's true
<>      checks empty string "" isn't returned by rest of code
ask ""  prompts with "" (empty msg), returns user input

```

Thanks to @endo64 for the code

-4 bytes thanks to @sqlab
> 2 votes

# Answer
# Ruby, 8 bytes (7 + '-n' flag)

```
~/./&&a

```

Try it online!
> 2 votes

# Answer
## ZX81 BASIC, 20 bytes

```
10 INPUT A$
20 IF NOT LEN A$ THEN RUN

```

Because ZX81 BASIC is tokenised, `NOT LEN A$` is a byte shorter then `A$<>""`. Program lines count 5 bytes each including the line number.
> 2 votes

# Answer
# Bash \+ line, 16 bytes

```
[ "`line`" ]||$0

```

Backticks are short for `$()`, to execute a command. `line` reads a line. If line is empty, then `[` will return false, and thus `$0` will be executed - the 0th argument which refers to itself. If there is any non-zero string, `[` will return true and because of lazy evaluation `$0` won't be executed (`||` is a logical OR).

### *Notes*

Instead of `line` you can also use `head -n1`, which is more common (but also longer).

In all cases I tested for empty lines, which behaves accordingly. And the following special inputs that may break the behavior (but did not ;) ):

* `-x`
* `aoeu aoeu aoeu`
* `!`

The only thing that breaks it is escaping the newline with `\`, or using a character. But how to handle these special characters is not mentioned in the original question.
> 2 votes

# Answer
# Pure Bash, 19 bytes

A pure Bash solution using recursion in which a line is read into the variable `$a` (19 bytes):

```
read a;[ "$a" ]||$0

```

### *Notes*

In all cases I tested for empty lines, which behaves accordingly. And the following special inputs that may break the behavior (but did not ;) ):

* `-x`
* `aoeu aoeu aoeu`
* `!`

The only thing that breaks it is escaping the newline with `\`, or using a character. But how to handle these special characters is not mentioned in the original question.
> 2 votes

# Answer
# x86 Assembler (NASM - Linux), 227 bytes

```
SECTION .bss
i: resb 5

SECTION .text
global  _start

_start:
    mov     edx, 5
    mov     ecx, i
    mov     ebx, 0
    mov     eax, 3
    int     80h
    cmp byte [ecx], 0xa
    je _start
    mov     eax, 1
    int     80h

```
> 2 votes

# Answer
# x86 machine code on DOS, 13 bytes

```
00000000  43 b4 01 cd 21 3c 0d 75  f7 4b 74 f4 c3           |C...!<.u.Kt..|
0000000d

```

Commented assembly:

```
    org 100h

section .text

    ; notice: on virtually every DOS bx starts at 0 at program start
    ; see http://www.fysnet.net/yourhelp.htm
start:
    inc bx      ; bx counts the number of read characters; increment it
    mov ah,1
    int 21h     ; read a character into al
    cmp al,0dh  ; check if it's a newline
    jne start   ; repeat if it's not
    dec bx      ; got a newline; decrement the counter
    jz start    ; if the counter became 0, it means that we only read the
                ; newline; restart (with bx being 0, as on startup)
    ret         ; otherwise quit

```
> 2 votes

# Answer
## VBScript, 26 bytes

```
while InputBox("")=""
wend

```

This one is sort of fun because the only way to stop the programs asking for an answer is either giving one or killing 'wscript.exe' in the task manager.
> 2 votes

# Answer
# APL (Dyalog Unicode), 10 bytes

Doesn't seem to work in TIO, works for me in Dyalog APL 18.0

```
{0=≢⍞:∇0}0

```

Try it online!
> 2 votes

# Answer
# *Acc!!*, 33 bytes

```
N
Count i while _/10*(10/_) {
N
}

```

(Don't) Try it online!

### Explanation

`N` reads a character into the accumulator. If it is 10 (newline), we want to halt, otherwise keep looping. The loop condition `_/10*(10/_)` accomplishes this: `_/10` is 0 if `_` is less than 10, and `10/_` is 0 if `_` is greater than 10. The only way their product can be truthy (nonzero) is if `_` is exactly 10.

If the input is guaranteed to be printable ASCII (and not contain, for example, the tab character), the loop condition could be `10/_` for -7 bytes.
> 2 votes

# Answer
# QBasic, 34 bytes

```
INPUT A$
WHILE A$=""
INPUT A$
WEND

```

I think nothing can be more self-explanatory than that. To test, go to this website and copy-paste the following code in their text-editor :

```
10 INPUT A$
20 WHILE A$=""
30 INPUT A$
40 WEND

```

The reason why line numbers are required is that their website only supports unstructured BASIC.
> 1 votes

# Answer
## C#, 36 bytes

```
_=>while(System.Console.Read()==13);

```

Compiles to a `Action<int>`.

Or if a full program is required, **62 bytes**.

```
class P{static void Main(){while(System.Console.Read()==13);}}

```
> 1 votes

# Answer
## Batch, 35 bytes

```
@set s=
@set/ps=
@if "%s%"=="" %0

```

Rather unfortunately, Batch doesn't clear the variable if you don't enter anything.
> 1 votes

# Answer
## Kotlin, ~~38~~ ~~35~~ 29 bytes

-3 bytes by negating `any()` rather than calling `isEmpty()`
-6 bytes thanks to Adám pointing out the function doesn't need to be named to be called

```
{while(!readLine()!!.any());}

```

called like so:

```
{while(!readLine()!!.any());}()

```

Try it online!
> 1 votes

# Answer
## Lithp, 90 bytes

```
((import readline)(readline "?" #A::((f A)))(def f #A::(if(== "" A)((readline "?"(get f/1)

```

Try it online! (Also works on command line in node)

A side effect of the current parser is that not all trailing `)` brackets are required. The very last one is, but the rest can be omitted saving quite a few bytes.

The `readline` module works in browser and via command line, and uses a callback. We exploit this to call `readline` before defining `f`, and save many bytes not needed all the closing brackets to invoke `f` after it's defined.
> 1 votes

# Answer
# AHK, 19 bytes

```
While !a
InputBox,a

```

Not very interesting, I'm afraid.
> 1 votes

# Answer
## QBIC, ~~7~~ 5 bytes

```
≈A|_?

```

Saved 2 bytes because empty string is falsy.

Explanation:

```
≈ |     WHILE <condition>
 A      A$ gets set by _? below. Empty string is false, so it stays in the WHILE
   _?   Ask the user for input, implicitly assign to A$

```
> 1 votes

# Answer
## Ruby, 19 bytes

```
while gets==?\n;end

```
> 1 votes

# Answer
# Scala, 21 bytes

```
while(readLine==""){}

```

Scala can run code as a script without the need for a class/main method so this is a complete program.

`readLine` is deprecated since Scala 2.11 but it's still available in 2.12
> 1 votes

# Answer
# Mathematica, 20 bytes

```
While[Input[]==Null]

```
> 1 votes

# Answer
## REXX, 24 bytes

```
do until n>''
  pull n
end

```
> 1 votes

# Answer
# Tcl, 26

```
while {![gets stdin t]} {}

```

demo
> 1 votes

# Answer
## Excel VBA 25 bytes

```
while Inputbox(0)="":wend

```

You can run it via immediate window. It's a simple while loop with inputbox.
> 1 votes

# Answer
# Pure Bash, 21 bytes

A pure Bash solution using shift and recursion with parameter (21 bytes):

```
shift||(read a;$0 $a)

```

`shift` shifts the arguments (and defaults to shifting 1). Which fails if there is no argument, upon which it will try to execute itself again with the next read line as the first argument.

Note that double quotes are here not needed if the line contains spaces, because it does not matter if it's just one word or multiple.

### *Notes*

In all cases I tested for empty lines, which behaves accordingly. And the following special inputs that may break the behavior (but did not ;) ):

* `-x`
* `aoeu aoeu aoeu`
* `!`

The only thing that breaks it is escaping the newline with `\`, or using a character. But how to handle these special characters is not mentioned in the original question.
> 1 votes

# Answer
# Bash + line, 16 bytes

Another approach using recursion with parameter (16 bytes), using `shift`:

```
shift||$0 `line`

```

`shift` shifts the arguments (and defaults to shifting 1). Which fails if there is no argument, upon which it will try to execute itself again with the next read line as the first argument.

### *Notes*

Instead of `line` you can also use `head -n1`, which is more common (but also longer).

In all cases I tested for empty lines, which behaves accordingly. And the following special inputs that may break the behavior (but did not ;) ):

* `-x`
* `aoeu aoeu aoeu`
* `!`

The only thing that breaks it is escaping the newline with `\`, or using a character. But how to handle these special characters is not mentioned in the original question.
> 1 votes

# Answer
# Pyke, 2 bytes

```
W!

```

Try it online!

See the debug output to show it's actually reading input

```
W  - do v
 ! -  not(input())
   - while ^

```
> 1 votes

# Answer
**Javascript, 17 bytes**

```
for(;!prompt(););

```

A for alternative to the while answer already here
> 1 votes

# Answer
# C, 83 bytes

```
e(char*t){*t>32?1+e(t+1):0;}
f(){size_t l;char*t;getline(&t,&l,stdin)+1&&e(t)&&f();}

```

The above answer will read full lines, and check if the read line has content beside spaces\tabs.

**shorter non-conforming version, 23 bytes**

```
f(){getchar()-10?:f();}

```
> 1 votes

# Answer
# Java, 79 bytes

```
boolean f(){System.console().readLine().replaceAll("\\t| ","").isEmpty()&&f();}

```

The above answer will read full lines, and check if the read line has content beside spaces\tabs.

**shorter non-conforming version, 38 bytes**

```
void f(){if(System.in.read()==10)f();}

```
> 1 votes

# Answer
# C, 31 Bytes

p\[99\];main(){for(;!\*gets(p););}

Try it online
> 1 votes

# Answer
# Python 3, 26 bytes

```
a=""
while not a:a=input()

```

Try it online!
> 1 votes

# Answer
# Batch 31 bytes

```
@Set $=&Set/p$=&Set $ 2>nul||%0

```
> 1 votes

# Answer
# APOL, 7 bytes

`w(!(i))`

This simply repeats until i returns a non-empty string.
> 1 votes

# Answer
# Pip, 4 bytes

```
T#q0

```

Replit! (Leave command-line arguments blank; when prompted to enter your program, type `T#q0` followed by a newline and Ctrl-D.)

### Explanation

```
T     Loop till
 #     length of
  q    read a line of stdin
      is truthy (nonzero):
   0   No-op

```

The shorter `Tq0` doesn't work because an input like `0` will still be falsey and fail to terminate the loop.
> 1 votes

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


# Question
Title: Calculate the truncated log2 of some unsigned integer
# Definition

Given some number, *x* calculate the smallest number *i* such that 2<sup>*i*</sup>*x*. This is not a duplicate of this question. It is slightly different in that an input of 16 should yield an output of 4 whereas 16 returns 5 in the linked question.

# Input

Input will be an unsigned 32-bit integer.

# Output

Output will be an unsigned integer (8-bit, 16-bit, 32-bit etc. are all ok)

# Test Cases

| Input | Output |
| --- | --- |
| 0 | 0 |
| 1 | 0 |
| 2 | 1 |
| 15 | 4 |
| 16 | 4 |
| 65536 | 16 |

# Example (C# 51 bytes)

```
uint A(uint x) => (uint)Math.Ceiling(Math.Log2(x));

```

This is code-golf, so the shortest answer in bytes wins! Standard loopholes and rules apply. Tie goes to first poster.

# Answer
# Vyxal, 5 bytes

```
≬E?≥ṅ

```

Try it Online!

Quite literally returns the first number where 2\**n \>= input
> 4 votes

# Answer
# Charcoal, 10 bytes

```
ＩＬ↨⌈⟦⁰⊖Ｎ⟧²

```

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

```
       Ｎ    Input as a number
      ⊖     Decremented
     ⁰      Literal `0`
    ⟦   ⟧   List of the above
   ⌈        Maximum
  ↨         Convert to base
         ²  Literal `2`
 Ｌ          Length
Ｉ           Cast to string
            Implicitly print

```

Charcoal converts `0` to `[]` so giving the correct log for an input of `1`, but `0` as input needs to be special-cased.
> 0 votes

# Answer
# Pari/GP, 23 bytes

```
n->if(n,#binary(n-1),0)

```

Try it online!
> 0 votes

# Answer
# Retina 0.8.2, 26 bytes

```
.+
$*
^((1+)(?=\2))*1*
$#1

```

Try it online! Link includes test cases. Explanation:

```
.+
$*

```

Convert the input to unary.

```
^((1+)(?=\2))*1*

```

Divide by two as many times as possible, rounding up each time, until `1` is reached. (The leading `^` and trailing `*` are needed to handle the edge case of zero input.)

```
$#1

```

Output the number of rounded divisions made.
> 0 votes

---
Tags: code-golf, bitwise
---