title: Implement the Thanos sorting algorithm

text:
# Question
Title: Implement the Thanos sorting algorithm
The sorting algorithm goes like this:

While the list is not sorted, snap half of all items (remove them from the list). Continue until the list is sorted or only one item remains (which is sorted by default). This sorting algorithm may give different results based on implementation.

The item removal procedure is up to the implementation to decide, but the list should be half as long as before after one pass of the item removal procedure. Your algorithm may decide to remove either the first half or the list, the last half of the list, all odd items, all even items, one at a time until the list is half as long, or any not mentioned.

The input list can contain an arbitrary amount of items (within reason, let’s say up to 1000 items), not only perfectly divisible lists of 2^n items. You will have to either remove (n+1)/2 or (n-1)/2 items if the list is odd, either hardcoded or decided randomly during runtime. Decide for yourself: what would Thanos do if the universe contained an odd amount of living things?

The list is sorted if no item is smaller than any previous item. Duplicates may occur in the input, and may occur in the output.

Your program should take in an array of integers (via stdin or as parameters, either individual items or an array parameter), and return the sorted array (or print it to stdout).

Examples:

```
// A sorted list remains sorted
[1, 2, 3, 4, 5] -> [1, 2, 3, 4, 5]

// A list with duplicates may keep duplicates in the result
[1, 2, 3, 4, 3] -> [1, 3, 3] // Removing every second item
[1, 2, 3, 4, 3] -> [3, 4, 3] -> [4, 3] -> [3] // Removing the first half
[1, 2, 3, 4, 3] -> [1, 2] // Removing the last half

```

`[1, 2, 4, 3, 5]` could give different results:

```
// Removing every second item:
[1, 2, 4, 3, 5] -> [1, 4, 5]

```

or:

```
// Removing the first half of the list
[1, 2, 4, 3, 5] -> [3, 5] // With (n+1)/2 items removed
[1, 2, 4, 3, 5] -> [4, 3, 5] -> [3, 5] // With (n-1)/2 items removed

```

or:

```
// Removing the last half of the list
[1, 2, 4, 3, 5] -> [1, 2] // With (n+1)/2 items removed
[1, 2, 4, 3, 5] -> [1, 2, 4] // With (n-1)/2 items removed

```

or:

```
// Taking random items away until half (in this case (n-1)/2) of the items remain
[1, 2, 4, 3, 5] -> [1, 4, 3] -> [4, 3] -> [4]

```

# Answer
> 20 votes
# Python 3, ~~38~~ ~~42~~ 39 bytes

```
q=lambda t:t>sorted(t)and q(t[::2])or t

```

Try it online!

`-3 bytes` thanks to @JoKing and @Quuxplusone

# Answer
> 19 votes
# , 41 bytes

```
x=scan();while(any(x-sort(x)))x=x[!0:1];x

```

Try it online!

# Answer
> 14 votes
# Python 2, 39 bytes

```
f=lambda l:l>sorted(l)and f(l[::2])or l

```

Try it online!

# Answer
> 12 votes
# Brachylog (v2), 6 bytes

```
≤₁|ḍt↰

```

Try it online!

This is a function submission. Input from the left, output to the right, as usual. (The TIO link uses a command-line argument that automatically wraps the function into a full program, so that you can see it in action.)

## Explanation

```
≤₁|ḍt↰
≤₁       Assert that {the input} is sorted {and output it}
  |      Handler for exceptions (e.g. assertion failures):
   ḍ     Split the list into two halves (as evenly as possible)
    t    Take the last (i.e. second) half
     ↰   Recurse {and output the result of the recursion}

```

## Bonus round

```
≤₁|⊇ᵇlᵍḍhtṛ↰

```

Try it online!

The snap's meant to be random, isn't it? Here's a version of the program that choses the surviving elements randomly (while ensuring that half survive at each round).

```
≤₁|⊇ᵇlᵍḍhtṛ↰
≤₁            Assert that {the input} is sorted {and output it}
  |           Handler for exceptions (e.g. assertion failures):
   ⊇ᵇ         Find all subsets of the input (preserving order)
     lᵍ       Group them by length
       ḍht    Find the group with median length:
         t      last element of
        h       first
       ḍ        half (split so that the first half is larger)
          ṛ   Pick a random subset from that group
           ↰  Recurse

```

This would be rather shorter if we could reorder the elements, but whyever would a sorting algorithm want to do *that*?

# Answer
> 10 votes
# Perl 6, 30 bytes

```
$!={[<=]($_)??$_!!.[^*/2].&$!}

```

Try it online!

Recursive function that removes the second half of the list until the list is sorted.

### Explanation:

```
$!={                         }    # Assign the function to $!
    [<=]($_)??                    # If the input is sorted
              $_                  # Return the input
                !!                # Else
                  .[^*/2]         # Take the first half of the list (rounding up)
                         .&$!     # And apply the function again

```

# Answer
> 9 votes
# C# (Visual C# Interactive Compiler), 76 bytes

```
g=>{while(!g.OrderBy(x=>x).SequenceEqual(g))g=g.Take(g.Count()/2);return g;}

```

Try it online!

# Answer
> 8 votes
# Wolfram Language (Mathematica), 30 bytes

```
#//.x_/;Sort@x!=x:>x[[;;;;2]]&

```

Try it online!

@Doorknob saved 12 bytes

# Answer
> 8 votes
# Java 10, ~~106~~ 97 bytes

```
L->{for(;;L=L.subList(0,L.size()/2)){int p=1<<31,f=1;for(int i:L)f=p>(p=i)?0:f;if(f>0)return L;}}

```

-9 bytes thanks to *@OlivierGrégoire*.

Try it online.

Only leave the first halve of the list every iteration, and removes \\$\frac{n+1}{2}\\$ items if the list-size is odd.

**Explanation:**

```
L->{               // Method with Integer-list as both parameter and return-type
  for(;;           //  Loop indefinitely:
      L=L.subList(0,L.size()/2)){
                   //    After every iteration: only leave halve the numbers in the list
    int p=1<<31,   //   Previous integer, starting at -2147483648
        f=1;       //   Flag-integer, starting at 1
    for(int i:L)   //   Inner loop over the integer in the list:
      f=p>(p=i)?   //    If `a>b` in a pair of integers `a,b`:
         0         //     Set the flag to 0
        :          //    Else (`a<=b`):
         f;        //     Leave the flag the same
    if(f>0)        //   If the flag is still 1 after the loop:
      return L;}}  //    Return the list as result

```

# Answer
> 7 votes
# JavaScript (ES6),  ~~49~~  48 bytes

*Saved 1 byte thanks to @tsh*

Removes every 2nd element.

```
f=a=>a.some(p=c=>p>(p=c))?f(a.filter(_=>a^=1)):a

```

Try it online!

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

```
[Ð{Q#ιн

```

-1 byte thanks to *@Emigna*.

Removes all odd 0-indexed items every iteration, so removes \\$\frac{n-1}{2}\\$ items if the list-size is odd.

Try it online or verify some more test cases (or verify those test cases with step-by-step for each iteration).

**7 bytes alternative by *@Grimy***:

```
ΔÐ{Ê>äн

```

Removes the last \\$\frac{n}{2}\\$ items (or \\$\frac{n-1}{2}\\$ items if the list-size is odd) every iteration.

Try it online or verify some more test cases (or verify those test cases with step-by-step for each iteration).

**Explanation:**

```
[        # Start an infinite loop:
 Ð       #  Triplicate the list (which is the implicit input-list in the first iteration)
  {Q     #  Sort a copy, and check if they are equal
    #    #   If it is: Stop the infinite loop (and output the result implicitly)
  ι      #  Uninterweave: halve the list into two parts; first containing all even-indexed
         #  items, second containing all odd-indexed items (0-indexed)
         #   i.e. [4,5,2,8,1] → [[4,2,1],[5,8]]
   н     #  And only leave the first part

Δ        # Loop until the result no longer changes:
 Ð       #  Triplicate the list (which is the implicit input-list in the first iteration)
  {Ê     #  Sort a copy, and check if they are NOT equal (1 if truthy; 0 if falsey)
    >    #  Increase this by 1 (so 1 if the list is sorted; 2 if it isn't sorted)
     ä   #  Split the list in that many parts
      н  #  And only leave the first part
         # (and output the result implicitly after it no longer changes)

```

# Answer
> 6 votes
# TI-BASIC (TI-84), ~~47~~ ~~42~~ ~~45~~ 44 bytes

*-1 byte thanks to @SolomonUcko!*

```
Ans→L1:Ans→L2:SortA(L1:While max(L1≠Ans:iPart(.5dim(Ans→dim(L2:L2→L1:SortA(L1:End:Ans

```

Input list is in `Ans`.
Output is in `Ans` and is implicitly printed out.

**Explanation:**

```
Ans→L1                  ;store the input into two lists
Ans→L2
SortA(L1                ;sort the first list
                        ; two lists are needed because "SortA(" edits the list it sorts
While max(L1≠Ans        ;loop until both lists are strictly equal
iPart(.5dim(Ans→dim(L2  ;remove the latter half of the second list
                        ; removes (n+1)/2 elements if list has an odd length
L2→L1                   ;store the new list into the first list (updates "Ans")
SortA(L1                ;sort the first list
End
Ans                     ;implicitly output the list when the loop ends

```

---

**Note:** TI-BASIC is a tokenized language. Character count does *not* equal byte count.

# Answer
> 6 votes
# Ruby, 37 bytes

```
->r{r=r[0,r.size/2]while r.sort!=r;r}

```

Try it online!

# Answer
> 4 votes
# Jelly, 7 bytes

```
m2$⁻Ṣ$¿

```

Try it online!

# Answer
> 3 votes
# Gaia, ~~9~~ 8 bytes

```
eo₌⟨2%⟩↻

```

Try it online!

Explanation:

```
e		| eval input as a list
       ↻	| until
 o		| the list is sorted
  ₌		| push additional copy
   ⟨2%⟩  	| and take every 2nd element
```

# Answer
> 3 votes
# Octave, 49 bytes

```
l=input('');while(~issorted(l))l=l(1:2:end);end;l

```

Try it online! This was a journey where more boring is better. Note the two much more interesting entries below:

### 50 bytes

```
function l=q(l)if(~issorted(l))l=q(l(1:2:end));end

```

Try it online! Instead of the uninteresting imperative solution, we can do a recursive solution, for only one additional byte.

### 53 bytes

```
f(f=@(g)@(l){l,@()g(g)(l(1:2:end))}{2-issorted(l)}())

```

Try it online! Yep. A recursive anonymous function, thanks to @ceilingcat's brilliant answer on my question. An anonymous function that returns a recursive anonymous function by defining itself in its argument list. I like anonymous functions. Mmmmm.

# Answer
> 3 votes
# Haskell, ~~57~~ 55 bytes (thanks to ASCII-only)

```
f x|or$zipWith(>)x$tail x=f$take(div(length x)2)x|1>0=x

```

Try it online!

---

Original Code:

```
f x|or$zipWith(>)x(tail x)=f(take(div(length x)2)x)|1>0=x

```

Try it online!

---

Ungolfed:

```
f xs | sorted xs = f (halve xs)
     | otherwise = xs

sorted xs = or (zipWith (>) xs (tail xs))

halve xs = take (length xs `div` 2) xs

```

# Answer
> 3 votes
# Julia 1.0, 30 bytes

```
-x=x>sort(x) ? -x[1:2:end] : x

```

Try it online!

Takes every second element of the array if not sorted.

# Answer
> 3 votes
# K (oK), ~~22~~ 20 bytes

**Solution:**

```
{(*2 0N#x;x)x~x@<x}/

```

Try it online!

Iterate over the input until it's sorted... if it's not sorted take first n/2 items.

```
{(*2 0N#x;x)x~x@<x}/ / the solution
{                 }/ / lambda that iterates
                <x   / indices that sort x ascending (<)
              x@     / apply (@) these indices back to x
            x~       / matches (~) x? returns 0 or 1
 (       ; )         / 2-item list which we index into
          x          / original input (ie if list was sorted)
       #x            / reshape (#) x
   2 0N              / as 2 rows
  *                  / take the first one

```

**Edits:**

* **-2** bytes thanks to ngn

# Answer
> 2 votes
# MATL, 11 bytes

```
tv`1L)ttS-a

```

Try it online!

This works by removing every second item.

### Explanation

```
t      % Take a row vector as input (implicit). Duplicate
v      % Vertically concatenate the two copies of the row vector. When read with
       % linear indexing (down, then across), this effectively repeats each entry
`      % Do...while
  1L)  %   Keep only odd-indexed entries (1-based, linear indexing)
  t    %   Duplicate. This will leave a copy for the next iteration
  tS   %   Duplicate, sort
  -a   %   True if the two arrays differ in any entry
       % End (implicit). A new iteration starts if the top of the stack is true
       % Display (implicit). Prints the array that is left on the stack

```

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

```
£=ëÃæÈeXñ

```

Try it

```
£=ëÃæÈeXñ     :Implicit input of array U
£             :Map
 =            :  Reassign to U
  ë           :  Every second element, starting with the first
   Ã          :End map
    æ         :Get the first element that returns true
     È        :When passed through the following function as X
      e       :  Test for equality with
       Xñ     :  X sorted

```

# Answer
> 2 votes
# Java (JDK), 102 bytes

```
n->{for(;n.stream().reduce((1<<31)+0d,(a,b)->a==.5|b<a?.5:b)==.5;n=n.subList(0,n.size()/2));return n;}

```

There's already a C# answer, so I decided to try my hand on a Java answer.

Try it online!

# Answer
> 2 votes
# Husk, ~~6~~ 5 bytes

*1 byte saved thanks to Zgarb*

```
ΩΛ<Ċ2

```

Try it online!

### Explanation

```
ΩΛ<Ċ2
Ω         Repeat until
 Λ<         all adjacent pairs are sorted (which means the list is sorted)
   Ċ2         drop every second element from the list

```

# Answer
> 2 votes
# Crystal, ~~59~~ 50 bytes

With `Array#sort` (**~~59~~ 50 bytes**):

```
def f(a);while a!=a.sort;a.pop a.size//2;end;a;end

```

Try it online!

Without `Array#sort` (**~~102~~ 93 bytes**):

```
def f(a);while a.map_with_index{|e,i|e>a.fetch i+1,Int32::MAX}.any?;a.pop a.size//2;end;a;end

```

Try it online!

# Answer
> 2 votes
# C++ (gcc), 103 bytes

I can't comment, but I improved the version from movatica by reducing the includes, and using auto.

-2 Bytes: ceilingcat
-2 Bytes: ASCII-only

```
#include<regex>
auto f(auto l){while(!std::is_sorted(l.begin(),l.end()))l.resize(l.size()/2);return l;}

```

Try it online!

# Answer
> 1 votes
# VDM-SL, 99 bytes

```
f(i)==if forall x in set inds i&x=1or i(x-1)<=i(x) then i else f([i(y)|y in set inds i&y mod 2=0])

```

Never submitted in vdm before, so not certain on language specific rules. So I've submitted as a function definition which takes a `seq of int` and returns a `seq of int`

A full program to run might look like this:

```
functions
f:seq of int +>seq of int
f(i)==if forall x in set inds i&x=1or i(x-1)<=i(x) then i else f([i(y)|y in set inds i&y mod 2=0])

```

# Answer
> 1 votes
# Pyth, 10 bytes

```
.W!SIHhc2Z

```

Try it online here. This removes the second half on each iteration, rounding down. To change it to remove the first half, rounding up, change the `h` to `e`.

```
.W!SIHhc2ZQ   Q=eval(input())
              Trailing Q inferred
  !SIH        Condition function - input variable is H
   SIH          Is H invariant under sorting?
  !             Logical not
      hc2Z    Iteration function - input variable is Z
       c2Z      Split Z into 2 halves, breaking ties to the left
      h         Take the first half
.W        Q   With initial value Q, execute iteration function while condition function is true

```

# Answer
> 1 votes
# C++ (gcc), ~~139~~ ~~137~~ 116 bytes

*-2 bytes thanx to ceilingcat, -21 bytes thanx to PeterZuger*

```
#include<regex>
auto f(std::vector<int>l){while(!std::is_sorted(l.begin(),l.end()))l.resize(-~l.size()/2);return l;}

```

Resize the vector to its first half until it's sorted.

Try it online!

# Answer
> 1 votes
# Julia 1.0, 33 bytes

```
-a=issorted(a) ? a : -a[1:end÷2]

```

Try it online!

# Answer
> 1 votes
## Python 2, 51 bytes

```
a=input()
while a!=sorted(a):a=a[:len(a)/2]
print a

```

nice!

# Answer
> 1 votes
# Husk, 7 bytes

```
ΩS=Oo←½

```

Try it online!

removes last half.

# Answer
> 1 votes
# Jelly, 6 bytes

```
m⁻Ṣ$¿2

```

Try it online!

Very similar to Erik's existing answer, but I came up with this independently, and Erik's no longer active.

## How it works

```
m⁻Ṣ$¿2 - Main link. Takes a list L on the left
    ¿  - Loop while the condition is false, updating L each time:
   $   -   Condition:
  Ṣ    -     L sorted
 ⁻     -     L ≠ L sorted
m    2 -   Body: Take every second element of L

```

# Answer
> 1 votes
# Pip `-xp`, ~~12~~ 11 bytes

```
$<=a?afVUWa

```

Takes the list as a command-line argument in Pip list format, e.g. `[1;2;4;3;5]`. The `-x` flag makes sure this is treated as a list rather than a string, and the `-p` flag formats the output list in the same way. Try it here!

(Pip Classic doesn't support the `-x` flag, but here's a simulated version: Try it online!)

### Explanation

A recursive solution:

```
$<=a?afVUWa
   a         ; First argument (the list)
$<=          ; Fold on <= (truthy if each element is <= the one after it)
    ?        ; If truthy, return:
     a       ;  The list unchanged
             ; Otherwise, return:
      f      ;  The main function
       V     ;  called with the following arglist:
        UWa  ;   Unweave the list into two sublists of every other element

```

For example, `UW[1;2;4;3;5]` returns `[[1;4;5];[2;3]]`. This list is passed as the arglist to the recursive call, as if we had called `f` with the arguments `[1;4;5]` and `[2;3]`. Since our function only uses its first argument, though, this is equivalent to simply recursing with an argument of `[1;4;5]`.

# Answer
> 0 votes
# Retina, 38 bytes

```
\d+
*
/(_+),(?!\1)/+`,_+(,?)
$1
_+
$.&

```

Try it online! Takes comma-separated numbers. Explanation:

```
\d+
*

```

Convert to unary.

```
/(_+),(?!\1)/+`

```

Repeat while the list is unsorted...

```
,_+(,?)
$1

```

... delete every even element.

```
_+
$.&

```

Convert to decimal.

# Answer
> 0 votes
# C (gcc), 66 bytes

Snaps off the second half of the list each iteration (`n/2+1` elements if the length is odd).

Try it online!

Takes input as a pointer to the start of an array of `int` followed by its length. Outputs by returning the new length of the array (sorts in-place).

```
t(a,n,i)int*a;{l:for(i=0;i<n-1;)if(a[i]>a[++i]){n/=2;goto l;}a=n;}

```

Ungolfed version:

```
t(a, n, i) int *a; { // take input as a pointer to an array of int, followed by its length; declare a loop variable i
  l: // jump label, will be goto'ed after each snap
  for(i = 0; i < n - 1; ) { // go through the whole array …
    if(a[i] > a[++i]) { // … if two elements are in the wrong order …
      n /= 2; // … snap off the second half …
      goto l; // … and start over
    }
  }
  a = n; // implicitly return the new length
}

```

# Answer
> 0 votes
# Clojure, 65 bytes

```
(defn t[l](if(apply <= l)l(recur(take(/(count l)2)(shuffle l)))))

```

Try it online!

# Answer
> 0 votes
# MATLAB, 57 bytes

Callable as `f(a)`, where `a=[1,2,3,4,5]`

```
f=@(x)eval('while~isequal(sort(x),x);x=x(1:end/2);end;x')

```

Example of usage:

```
>> a = [1, 2, 4, 3, 5];
>> f(a)

a =
     1     2

```

# Answer
> 0 votes
# Zsh, 51 bytes

***56 (+5)** to call the function, **47 (-4)** if not a function, but saved as an executable with a proper `#!` header (replace the recursive `f` call with `$0`).*

```
f(){[ "$*" = "${${(n)@}[*]}" ]&&<<<$@||f $@[0,#/2]}

```

Try it online!

There is no "is-sorted" builtin in zsh, but there are some "sort-array" builtins. We use the parameter expansion flag `n`, but `o` or `i` would also work. We then have to use `[*]` and quote to induce joining. This is shorter than alternatives (like zipping them together and comparing pairwise).

# Answer
> 0 votes
# TI-Basic (TI-84), ~~29~~ ~~30~~ 36 bytes

```
Ans->L₁
While 1<dim(L₁
If 0≤min(ΔList(L₁:Then
L₁
Return:End
iPart(.5dim(L₁->dim(L₁
End

```

Input and output are through `Ans`.

# Answer
> 0 votes
# C++ 17 , 589 bytes

I used recursion to solve it. Submitted this solution in codeforces and got accepted. Btw, I still can't stop laughing! I mean seriously, Thanos sort!

```
#include <bits/stdc++.h>
using namespace std;int n, *a; int f(int start123, int end123){int start, end;start = start123; end = end123;if(start == end){    return 1; }int ret=0, temp=0;bool flag  = true;for(int i=start; i<end; i++){ if(a[i]<=a[i+1]){   ret++; }else{    flag=false; break; } }int mid = (start+end)>>1; if(flag){    ret=ret+1; }else{ int a,b; a =  f(start, mid);b = f(mid+1, end);ret = max( a, b );}return ret;}int main(int argc, char const *argv[]){    cin>>n;a = new int[n+10];for(int i=1; i<=n; i++){cin>>a[i];}int ans = f(1,n);cout<<ans<<"\n";if(!a)delete[] a;return 0;}

```

# Answer
> 0 votes
# F# (.NET Core), ~~67~~ 61 bytes

```
let rec t l=if l=(List.sort l)then l else t l.[0..l.Length/2]

```

Try it online!

# Answer
> 0 votes
# Perl 6, 32 bytes

```
{($_,*[^*/2]...{[<=] @$_})[*-1]}

```

*-2 bytes thanks to Jo King*

Try it online!

# Answer
> 0 votes
# Perl 5 `-a`, 50 bytes

```
@b=sort{$a-$b}@F while"@b"ne"@F"&&($#F/=2);say"@F"

```

Try it online!

# Answer
> 0 votes
# Rust (2018 edition), ~~79~~ 78 bytes

```
|v:&mut Vec<_>|while{let q=&mut v.clone();q.sort();q<v}{v.resize(v.len()/2,0)}

```

Try it online!

This will be golfable if `slice::is_sorted` gets stabilized, but right now the required feature flag offsets all gains.

# Answer
> 0 votes
# PHP, 86 bytes

```
function t($a){for(;$n=$a[+$i++];$l=$n)$f|=$n<$l;return$f?t(array_slice($a,$i/2)):$a;}

```

Try it online!

# Answer
> 0 votes
# Python 3, 60 bytes

```
a=list(input())
while a!=sorted(a):a=a[0:len(a)//2]
print(a)

```

Try it online!

If it has to be a list:

```
a=[1,34,2,42,3,4,5,23,4,12,34,53,65]
while a!=sorted(a):a=a[0:len(a)//2]
print(a)

```

this one even has a self scrambling thingy!

```
import random
a=list(input())
random.shuffle(a)
while a!=sorted(a):a=a[0:len(a)//2]
print(a)

```

---

### Explanation:

```
a=list(input())       #ask for a string(that will be converted to a list)
while a!=sorted(a):   #while the actual sorted list *isn't* sorted,
    a=a[0:len(a)//2]  #it now equals the first half of it.
print(a)              #print it out!

```

# Answer
> 0 votes
# Factor, 50 bytes

```
[ [ dup [ <= ] monotonic? ] [ halves nip ] until ]

```

Try it online!

Removes the first half of the list, where the first half is shorter when there's an odd number of elements.

# Answer
> 0 votes
# Scala, 84 bytes

```
def q(t:List[Int]):List[Int]=if(t==t.sorted)t else q(t.grouped(2).map(_.max).toList)

```

Try it online!

---
Tags: code-golf, sorting
---


# Question
Title: Shortest Google Sheets formula to detect if cell contains an image
**Step one**

In a new google sheet insert an image into cell A1 with

Insert \> Image \> Image In Cell

**Step two**

Create a formula to return TRUE (if the cell contains an image) and FALSE (if the image is missing)

**Rules**

Only vanilla formulas are allowed. The shortest code in bytes wins.

# Answer
# 26

The shortest I've found, which I believe currently works, is:

```
=TYPE(A1)>64>ISFORMULA(A1)

```
> 4 votes

# Answer
Try this... The way it is checking is if there is an image no data(Text) could be found so....:

```
=IF(ISTEXT(IFERROR(IMPORTDATA(A1),FALSE)),IMAGE(A1),"There is no Image there")

```

A1 = is the Image URL (https://....jpg)
> 1 votes

# Answer
## 13 bytes

```
=TYPE(A1)=128

```

The other answer is looking for other values. You asked for just a test true/false if an image in the cell.

https://support.google.com/docs/answer/3267375?hl=en-GB&sjid=11934302938886193323-NA
> 1 votes

---
Tags: code-golf
---


# Question
Title: Little Endian Number to String Conversion
## Introduction

During work with BMP (bitmap) generator I face problem of converting number to little endian hex string. Here is function which I create in JavaScript - but wonder how small code can works similarly

```
let liEnd= num => num.toString(16).padStart(8,'0').match(/../g).reverse().join``;
console.log(liEnd(304767)) // 304767 dec = 0x4a67f hex
```

## Challenge

Write function which will take 32bit unsigned integer number on input, and produce 8-digit hexadecimal string with little endian order. The example algorithm which do the job:

* convert numb to hex string e.g: `304767 -> '4a67f'`
* add padding zeros to get 8-char string: `'0004a67f'`
* split string to four 2-char pieces: `'00','04','a6','7f'`
* reverse order of pieces `'7f','a6','04','00'`
* join pieces and return as result: `'7fa60400'`

## Example Input and Output

Input number (or string with dec number) is on the left of `->`, output hex string is on the right

```
2141586432 -> 0004a67f
304767     -> 7fa60400

```

# Answer
> 8 votes
# 05AB1E, ~~10~~ 9 bytes

```
žJ+h¦2ôRJ

```

Try it online!

-1 byte by inspiration of the Jelly answer.

```
žJ+   add 2^32 to input
h     convert to hex
¦     drop leading 1
2ô    split in groups of 2
R     reverse groups
J     and join them

```

# Answer
> 6 votes
# , ~~54~~ 53 bytes

```
format.hexmode(scan()%/%256^(0:3)%%256%*%256^(3:0),8)

```

Try it online!

Each group of 2 characters is actually the hex representation of a digit in base 256. `scan()%/%256^(0:3)%%256` converts to a base 256 number with 4 digits reversed, `...%*%256^(3:0)` joins them as a single integer, and `format.hexmode(...,8)` converts that number to its hex representation with 8 digits.

# Answer
> 6 votes
# Python 3, 37 bytes

```
lambda n:n.to_bytes(4,"little").hex()

```

Try it online!

**Arithmetic-based recursive solution (~~50~~ 49 bytes, works also for Python 2)**:

```
f=lambda n,i=4:i*'1'and"%02x"%(n%256)+f(n>>8,i-1)

```

Try it online!

*-1 byte thanks to @JonathanAllan*

# Answer
> 5 votes
# JavaScript (ES7),  ~~59~~  57 bytes

String manipulation.

```
n=>(n+2**32).toString(16).match(/\B../g).reverse().join``

```

Try it online!

### How?

We first convert \\$n + 2^{32}\\$ to hexadecimal to make sure that all leading \\$0\\$'s are included:

```
(304767 + 2**32).toString(16) // --> '10004a67f'

```

Try it online!

We use the regular expression `/\B../g` to match all groups of 2 digits, ignoring the leading \\$1\\$ thanks to `\B` (non-*word boundary*).

```
'10004a67f'.match(/\B../g) // --> [ '00', '04', 'a6', '7f' ]

```

Try it online!

We `reverse()` and `join()` to get the final string.

---

# JavaScript (ES6), 61 bytes

Recursive function.

```
f=(n,k=4)=>k?[(x=n&255)>>4&&'']+x.toString(16)+f(n>>8,k-1):''

```

Try it online!

# Answer
> 5 votes
# C# (Visual C# Interactive Compiler), 54 bytes

```
x=>$"{(x=x>>16|x<<16)>>8&16711935|(x&16711935)<<8:x8}"

```

Saved 4 bytes thanks to @PeterCordes

Try it online!

### Explanation

```
x=>                                                    //Lambda taking in an uint
     (x=x>>16|x<<16)                                   //Swap the first two and the last two bytes of the uint (0x7fa60400 -> 0x04007fa6)
                    >>8&16711935|(x&16711935)<<8       //Swap each pair of bytes in every group of 2 bytes (0x04007fa6 -> 0x0004a67f)
  $"{                                           :x8}"  //Format as hex string, padded with leading zeroes to length 8

```

# Answer
> 5 votes
# Zsh, 46 bytes

```
i=$1
repeat 4 printf %02x $[j=i%256,i=i/256,j]

```

Try it online!

# Answer
> 5 votes
# x86 32-bit machine code, ~~24~~ 21 bytes

changelog: -3 bytes: replace standard add/cmp/jbe/add with a DAS hack by @peter ferrie

64-bit: still 24 bytes. Long mode removed the DAS opcode.
16-bit mode: the default operand-size is 16-bit but the problem spec is inherently 32-bit. Including hard-coded 8 hex digits.

---

**Byte-reverse with `bswap` then manual int-\>hex in standard order** (most-significant nibble first, writing hex digits to a char output buffer in ascending order.) This avoids needing to unroll the loop to switch order between nibbles within a byte vs. across bytes.

Callable as `void lehex(char buf[8] /*edi*/, uint32_t x /*esi*/);` like x86-64 System V, except this doesn't work in 64-bit mode. (It needs the output pointer in EDI for `stosb`. The input number can be in any register other than ECX or EAX.)

```
     1                             lehex:
     2 00000000 0FCE                   bswap  esi
     3 00000002 6A08                   push   8            ; 8 hex digits
     4 00000004 59                     pop    ecx
     5                             .loop:                ;do{
     6 00000005 C1C604                 rol    esi, 4       ; rotate high nibble to the bottom
     7
     8 00000008 89F0                   mov    eax, esi
     9 0000000A 240F                   and    al, 0x0f     ; isolate low nibble
    10 0000000C 3C0A                   cmp al, 10          ; set CF according to digit <= 9
    11 0000000E 1C69                   sbb al, 0x69        ; read CF, set CF and conditionally set AF
    12 00000010 2F                     das                 ; magic, which happens to work
    13
    14 00000011 AA                     stosb               ; *edi++ = al
    15 00000012 E2F1                   loop  .loop       ; }while(--ecx)
    16
    17 00000014 C3                     ret

```

size = 0x15 = 21 bytes.

TIO FASM 32-bit x86 test case with an asm caller that uses a `write` system call to write the output after calling it twice to append 2 strings into a buffer. Tests all hex digits 0..F, including 9 and A at the boundary between numeral vs. letter.

**The `DAS` hack** \- x86 has a half-carry flag, for carry out of the low nibble. Useful for packed-BCD stuff like the DAS instruction, intended for use after subtracting two 2-digit BCD integers. With the low nibble of AL being outside the 0-9 range, we're definitely abusing it here.

Notice the `if (old_AL > 99H) or (old_CF = 1)` THEN `AL ← AL − 60H;` part of the Operation section in the manual; sbb *always* sets CF here so that part always happens. That and the ASCII range for upper-case letters is what motivates the choice of `sbb al, 0x69`

* `cmp 0xD, 0xA` doesn't set CF
* sbb `0xD - 0x69` wraps to AL=`0xA4` as input to DAS. (And sets CF, clears AF)
* no AL -= 6 in the first part of DAS (because 4 \> 9 is false and AF=0)
* AL -= 0x60 in the second part, leaving `0x44`, the ASCII code for `'D'`

vs. a numeral:

* `cmp 0x3, 0xA` sets CF
* sbb `3 - 0x69 - 1` = AL = 0x99 and sets CF and AF
* AL -= 6 in the first part of DAS (9 \> 9 is false but AF is set), leaving 0x93
* AL -= 0x60 in the second part, leaving 0x33, the ASCII code for `'3'`.

Subtracting `0x6a` in SBB will set AF for every digit \<= 9 so all the numerals follow the same logic. And leave it cleared for every alphabetic hex digit. i.e. correctly exploiting the 9 / A split handling of DAS.

---

Normally (for performance) you'd use a lookup table for a scalar loop, or possibly a branchless 2x `lea` and `cmp/cmov` conditional add. But 2-byte `al, imm8` instructions are a big win for code-size.

---

**x86-64 version version**: just the part that's different, between `and al, 0xf` and `stosb`.

```
;; x86-64 int -> hex  in 8 bytes
    10 0000000C 0430                   add    al, '0'
    11 0000000E 3C39                   cmp    al, '9'
    12 00000010 7602                   jbe  .digit
    13 00000012 0427                     add    al, 'a'-10 - '0'     ; al =  al>9 ? al+'a'-10 : al+'0'
    14                             .digit:

```

Notice that the `add al, '0'` *always* runs, and the conditional add only adds the difference between `'a'-10` and `'0'`, to make it just an `if` instead of `if`/`else`.

Tested and works, using the same `main` caller as my C answer, which uses `char buf[8]` and `printf("%.8s\n", buf)`.

# Answer
> 5 votes
# Red, 37 bytes

```
func[x][reverse/skip form to-hex x 2]

```

This breaks TIO because of the outdated compiler it uses.

## Red, 43 bytes

```
func[x][load next mold reverse to-binary x]

```

Try it online!

# Answer
> 4 votes
# C (gcc), 30 bytes

```
f(x){printf("%.8x",htonl(x));}

```

Try it online!

# Answer
> 4 votes
# Japt `-P`, 10 bytes

```
sG ùT8 ò w

```

Try it

```
sG ùT8 ò w     :Implicit input of integer
s              :Convert to string
 G             :  In base-16
   ù           :Left pad
    T          :  With 0
     8         :  To length 8
       ò       :Split into 2s
         w     :Reverse
               :Implicitly join and output

```

# Answer
> 4 votes
# x86 SIMD machine code (AVX512-VBMI), 36 bytes

(16 bytes of which are a hex lookup table)

This is a function that takes an integer in `xmm0` and returns 8 bytes of ASCII char data in `xmm0`, for the caller to store wherever it wants. (e.g. to video memory after interleaving with attribute bytes, or into a string under construction, or whatever)

From C, call it as `__m128i retval = lehex(_mm_cvtsi32_si128(x))` with the x86-64 System V calling convention, or MS Windows `vectorcall`.

```
# disassembly with machine-code bytes (the answer) and NASM source code.
0000000000401000 <lehex>:
  401000:       c5 f1 72 d0 04          vpsrld      xmm1, xmm0, 4         ; AVX1
  401005:       c5 f1 60 c8             vpunpcklbw  xmm1, xmm1, xmm0      ; AVX1
  401009:    62 f2 75 08 8d 05 01 00 00 00 vpermb  xmm0, xmm1, [rel .hex_lut]
  401013:       c3                      ret

0000000000401014 <lehex.hex_lut>:
  401014:     30 31 ...  61 62 ...     .hex_lut:  db "0123456789abcdef"

```

Total = 0x24 = 36 bytes.

**See How to convert a number to hex? on SO for how this works.** (SSE2 for the shift / punpck, then `vpermb` saves work that we'd need for `pshufb`. AVX1 instead of SSE2/SSSE3 also avoids a `movaps` register copy.)

Notice that `punpcklbw` with the source operands in that order will give us the most-significant nibble of the low input byte in the lowest byte element, then the least-significant nibble of the lowest source byte. (In that SO answer, a `bswap` is used on the input to get a result in standard printing order with only SSE2. But here we *want* that order: high nibble in lower element within each byte, but still little-endian byte order).

If we had more data constants, we could save addressing-mode space by doing one `mov edx, imm32` then using `[rdx+16]` or whatever addressing modes. Or `vpbroadcastb xmm0, [rdx+1]`.

But I think a 16-byte hex LUT + `vpermb` is still better than implementing the `n>9 : n+'a'-10 : n+'0'` condition: that requires 3 constants and at least 3 instructions with AVX512BW byte-masking (compare into mask, `vpaddb`, merge-masked `vpaddb`), or more with AVX1 or SSE2. (See How to convert a number to hex? on SO for an SSE2 version of that). And each AVX512BW instruction is at least 6 bytes long (4-byte EVEX + opcode + modrm), longer with a displacement in the addressing mode.

Actually it would take at least *4* instructions because we need to clear high garbage with `andps`, (or EVEX `vpandd` with a 4-byte broadcast memory operand) before the compare. And each of those needs a different vector constant. AVX512 has broadcast memory operands, but only for elements of 32-bit and wider. e.g. EVEX `vpaddb`'s last operand is only `xmm3/m128`, not `xmm3/m128/m8bcst`. (Intel's load ports can only do 32 and 64-bit broadcasts for free as part of a load uop so Intel designed AVX512BW to reflect that and not be able to encode byte or word broadcast memory operands at all, instead of giving them the option to do dword broadcasts so you can still compress your constants to 4 bytes :/.)

**The reason I used AVX512VBMI `vpermb` instead of SSSE3 / AVX1 `pshufb` is twofold:**

* `vpermb` ignores high bits of the selectors. `(v)pshufb` zeros bytes according to the high bit of the control vector and would have needed an extra `pand` or `andps` to actually isolate nibbles. With XMM / 16-byte size, `vpermb` only looks at the low 4 bits of the shuffle-control elements, i.e. bits `[3:0]` in Intel's notation in the Operation section.
* `vpermb` can take the data to be shuffled (the lookup table) as a memory operand. `(v)pshufb`'s xmm/mem operand is the shuffle-control vector.

Note that AVX512VBMI is only available on CannonLake / Ice Lake so you probably need a simulator to test this, like Intel's SDE.

# Answer
> 4 votes
# Python 2, 43 bytes

```
lambda n:[("%08x"%n)[i^6]for i in range(8)]

```

Try it online!

*-4 bytes thanks to benrg*

Outputs a list of characters. Computed by retrieving, in order, the hex digits of the input at indices `6, 7, 4, 5, 2, 3, 0, 1`.

# Answer
> 3 votes
# C (gcc) endian agnostic, no standard libs, ~~92~~ 91 bytes

`h(n)` is a single-digit integer-\>hex helper function.
`f(x,p)` takes an integer and a `char[8]` pointer. The result is 8 bytes of `char` data. (*Not* 0-terminated unless the caller does that.)

Assumptions: ASCII character set. 2's complement `int` so right shift eventually brings down the sign bit, and converting a `uint32_t` to `int` doesn't munge the bit-pattern if the high bit is set. `int` is at least 32-bit. (Wider might let it work on 1's complement or sign-magnitude C implementations).

Non-assumptions: anything about implementation byte-order or signedness of `char`.

```
i;h(n){n&=15;return n>9?n+87:n+48;}f(x,p)char*p;{for(i=5;--i;x>>=8)*p++=h(x>>4),*p++=h(x);}

```

Try it online! including test caller using `printf("%.8s\n", buf)` to print output buffer without 0-terminating it.

**Ungolfed:**

```
int h(n){n&=15;return n>9 ? n+'a'-10 : n+'0';}      // single digit integer -> hex

int i;
void ungolfed_f(x,p)char*p;{
    for(i=5; --i; x>>=8)   // LS byte first across bytes
        *p++=h(x>>4),      // MS nibble first within bytes
        *p++=h(x);
}

```

Doing `n&=15;` inside `h(x)` is break-even; 6 bytes there vs. 3 each for `&15` to isolate the low nibble at both call sites.

`,` is a sequence point (or equivalent in modern terminology) so it's safe to do `*p++= stuff` twice in one statement when separated by the `,` operator.

`>>` on signed integer is implementation-defined as either arithmetic or logical. GNU C defines it as arithmetic 2's complement. But on any 2's complement machine it doesn't really matter because we never look at the shifted-in 0s or copies of the sign bit. The original MSB will eventually get down into the low byte unchanged. This is not the case on sign/magnitude, and I'm not sure about 1's complement.

So this may only be portable to 2's complement C implementations. (Or where `int` is *wider* than 32 bits so bit 31 is just part of the magnitude.) unsigned -\> signed conversion also munges the bit-pattern for negative integers, so `&15` on an `int` would only extract nibbles of the original unsigned value on 2's complement. Again, unless `int` was *wider* than 32-bit so all inputs are non-negative.

The golfed version has UB from falling off the end of a non-void function. Not to return a value, just to avoid declaring it `void` instead of default `int`. Modern compilers will break this with optimization enabled.

---

Motivation: I was considering an x86 or ARM Thumb asm answer, thought it might be fun to do it manually in C, maybe for compiler-generated asm as a starting point. See https://stackoverflow.com/questions/53823756/how-to-convert-a-number-to-hex for speed-efficient x86 asm, including an AVX512VBMI version that's only 2 instructions (but needs control vectors for vpmultishiftqb and vpshufb so wouldn't be great for golf). Normally it takes extra work for SIMD to byte-reverse into printing order on little-endian x86 so this byte-reversed hex output is actually easier than normal.

---

**Other ideas**

I considered taking the integer by reference and looping over its bytes with `char*`, on a little-endian C implementation (like x86 or ARM). But I don't think that would have saved much.

Using `sprintf` to do 1 byte at a time, 64 bytes after golfing:

```
int i;
void f(x,p)char*p;{
        for(i=4;sprintf(p,"%.2x",x&255),--i;x>>=8)
                p+=2;
}

```

But if we're using printf-like functions we might as well byte-swap and do a `%x` printf of the whole thing like @JL2210's answer.

# Answer
> 3 votes
# Scala, ~~58~~ ~~40~~ 36 bytes

```
"%08X"format Integer.reverseBytes(_)

```

Try it online!

Still uses the builtin to reverse the bytes of an `Int`, but uses `format` to format the `Int` as a Hex. No need to call `toHexString`.

Removed the parens on `format`. This now means that the argument can be taken implicitly using `_`.

# Answer
> 2 votes
# Forth (gforth), 52 51 40 bytes

```
: f hex 0 4. do <# # # 0. #> type loop ;

```

Try it online!

### Code explanation

```
: f           \ start a new word definition
  hex         \ set the current base to base 16
  0           \ convert the input number to a double-cell integer
  4. do       \ start a counted loop from 0 to 3
    <# # #    \ start a formatted numeric string and move last 2 digits to format area
    0.        \ move remaining digits down the stack
    #>        \ delete top two stack value and convert format area to string
    type      \ output string
  loop        \ end loop
;             \ end word definition

```

# Answer
> 2 votes
# APL+WIN, ~~36~~ 34 bytes

2 bytes saved by converting to index zero

Prompts for integer:

```
'0123456789abcdef'[,⊖4 2⍴(8⍴16)⊤⎕]

```

Try it online! Courtesy Dyalog Classic

# Answer
> 2 votes
# Jelly, 13 bytes

```
+Ø%b⁴Ḋs2Ṛ‘ịØh

```

Try it online!

A full program that takes an integer as its argument and prints a string.

# Answer
> 2 votes
# , 10 bytes

```
8{._1{3!:3

```

Try it online!

## how

`3!:3` is a J "foreign conjunction" for hex representation, documented here. That is, it's a builtin for converting to hex. However, it's output it not quite what we want. Eg, running:

```
3!:3 (304767)

```

produces:

```
e300000000000000
0400000000000000
0100000000000000
0000000000000000
7fa6040000000000

```

The meaning of the other lines is explained on the doc page I linked to above. In any case, it's clear we want the first 8 chars of the last line.

`_1{` get the last line.

`8{.` gets the first 8 characters of it.

# Answer
> 2 votes
# Excel, 91 bytes

```
=RIGHT(DEC2HEX(A1,8),2)&MID(DEC2HEX(A1,8),5,2)&MID(DEC2HEX(A1,8),3,2)&LEFT(DEC2HEX(A1,8),2)

```

# Answer
> 2 votes
# K4, ~~12~~ 11 bytes

**Solution:**

```
,/$|4_0x0\:

```

**Examples:**

```
q)k),/$|4_0x0\:304767
"7fa60400"
q)0W
"0004a67f"

```

**Explanation:**

Pretty much exactly what the question asks:

```
,/$|4_0x0\: / the solution
      0x0\: / split to bytes
    4_      / drop first 4 bytes
   |        / reverse
  $         / convert to string
,/          / flatten

```

**Notes:**

* **-1 byte** as K4 numbers are longs (64bit) by default, so dropping 4 bytes (32bits)

# Answer
> 2 votes
# PHP, 31 bytes

```
<?=unpack(H8,pack(V,$argn))[1];

```

Try it online!

Taking advantage of PHP's pack and unpack, I pack the unsigned input with "32 bit little endian byte order" format (`V`) into a binary string and then unpack it with "hex string, high nibble first" format (`H`) and print the result.

This seems to be one of the rare cases where PHP's built-ins are actually shorter than implementing a simple algorithm!

# Answer
> 1 votes
# Charcoal, 11 bytes

```
⪫⮌⪪﹪%08xＮ²ω

```

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

```
        Ｎ   Input as a number
   ﹪%08x    Format using literal string
  ⪪      ²  Split into pairs of characters
 ⮌          Reverse
⪫         ω Join
            Implicitly print

```

19 bytes without resorting to Python formatting:

```
⪫…⮌⪪⍘⁺Ｘ²¦³⁶Ｎ¹⁶¦²¦⁴ω

```

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

```
           Ｎ        Input as a number
     ⁺              Plus
       ²            Literal 2
      Ｘ             To power
         ³⁶         Literal 36
    ⍘               Convert to base
            ¹⁶      Literal 16
   ⪪           ²    Split into pairs of digits
  ⮌                 Reverse the list
 …               ⁴  Take the first 4 pairs
⪫                 ω Join together
                    Implicitly print

```

# Answer
> 1 votes
# Perl 5 (-p), 22 bytes

```
$_=unpack H8,pack V,$_

```

Try it online!

# Answer
> 1 votes
# Ruby, ~~31~~ 27 bytes

Ended up being a port of Night2's PHP answer because Ruby has the same pack/unpack functionality.

```
->*i{i.pack(?V).unpack'H8'}

```

Try it online!

My original 31-byte answer that didn't take advantage of the H8 unpack mode because I didn't know about it:

```
->*i{'%02x'*4%i.pack(?V).bytes}

```

Try it online!

# Answer
> 1 votes
## Windows Batch, 90 bytes

```
@for /l %%x in (24,-8,0)do @set/aa=%1^>^>%%x^&255&cmd/cexit !a!&<nul set/p=!=exitcode:~-2!
```

Run the command-line with /v to enable the delayed expansion.

# Answer
> 1 votes
# Rust, 34 bytes

```
|n|print!("{:08x}",n.swap_bytes())

```

Try it online!

Rust has built-in hex formatting, but it displays in big-endian format, so I reversed the byte order first. Capitalize the `x` if you want uppercase hex digits instead of lowercase ones.

# Answer
> 1 votes
# Python 3.11+, 34 bytes

```
lambda n:n.to_bytes(4)[::-1].hex()

```

This is a version of Joel's Python 3 solution that works only on Python 3.11 and higher. Pre-3.11, the `byteorder` argument to `int.to_bytes`/`int.from_bytes` was mandatory; in 3.11 it is now defaulted to `'big'`, so, golf-wise, you can omit it, let `to_bytes` produce the big-endian version, then reverse it with a slice, saving three characters.

(Side-note: The Attempt This Online link actually cheats and just uses Joel's solution when the Python version is below 3.11; ATO is still on 3.10.6 so it can't run this code as of April, 2023)

Attempt This Online!

---
Tags: code-golf
---


title: Generate All 8 Knight's Moves

text:
# Question
Title: Generate All 8 Knight's Moves
# Introduction

In chess, Knights can move two squares in one direction, and then one square in an orthogonal direction. On an x/y plane, these can be thought of as being a relative change of coordinates, such as (+1, -2).

# Challenge

Your task is to output all 8 possible moves as pairs of relative x/y coordinates, in any order.

You may output in any reasonable format. To decrease reliance on printing random separators, using the same separators for everything is fine, and no separators are also fine. Standard loopholes apply.

**Example Outputs:**

```
1,2 1,-2 -1,-2 -1,2 2,1 2,-1 -2,-1 -2,1

2-112-2-1-211-2-1-2-1221

1;2
-1;2
2;1
2;-1
-2;-1
1;-2
-1;-2
-2;1

```

This is code golf, so fewest bytes wins.

# Answer
> 15 votes
# Wolfram Language (Mathematica), 25 bytes

```
Solve[x^2y^2==4,Integers]

```

Try it online!

Outputs a list of `{x -> *x*, y -> *y*}`s.

# Answer
> 12 votes
# Python, 30 bytes

```
print((2*"2212-1-21-2-1")[2:])
```

Attempt This Online!

A mashup of my previous and the trivial solutions.

# Python, 41 bytes

```
a=1
for b in b"41030143":print(a,a:=b-50)
```

Attempt This Online!

Abuses the dual stringy/inty nature of `bytes` objects. Arranges items such that a sliding 2-window finds all required pairs.

# Answer
> 9 votes
# , 18 bytes

```
(,+)@(1j2*0j1^i.4)

```

Try it online!

A function taking any input and returning the list we want as complex numbers.

* `0j1^i.4` \\$i\\$ raised to 0, 1, 2, 3 -- gives the 4 compass directions in the complex plane: `1 0j1 _1 0j_1`.
* `1j2*` Multiply \\$(1 + 2i)\\$ times each of those, and we get \\$(1 + 2i)\\$ rotated 0, 90, 180, and 270 degrees: `1j2 _2j1 _1j_2 2j_1`.
* `(,+)` Take the complex conjugates of each of those, and append them: `1j2 _2j1 _1j_2 2j_1 1j_2 _2j_1 _1j2 2j1`.

# Answer
> 7 votes
# Jelly, 6 bytes

```
Ø+pḤUƬ

```

A niladic Link that yields this pair of lists of pairs of integers:

```
[[[1, 2], [1, -2], [-1, 2], [-1, -2]], [[2, 1], [-2, 1], [2, -1], [-2, -1]]]

```

**Try it online!**

### How?

```
Ø+pḤUƬ - Link: no arguments
Ø+     - literal [1,-1] - set as the left argument
   Ḥ   - double -> [2,-2]
  p    - ([1,-1]) Cartesian product ([2,-2]) -> [[1,2],[1,-2],[-1,2],[-1,-2]]
     Ƭ - collect up inputs while distinct, applying:
    U  -   reverse each

```

---

Original seven byter (not abusing the very lose IO):

```
Ø+pḤ;U$ - Link: no arguments
Ø+      - literal [1,-1] - set as the left argument
   Ḥ    - double -> [2,-2]
  p     - ([1,-1]) Cartesian product ([2,-2]) -> [[1,2],[1,-2],[-1,2],[-1,-2]]
      $ - last two links as a monad - f(X=that):
     U  -   reverse each of (X)
    ;   -   (X) concatenate (that)

```

Try it online!

# Answer
> 6 votes
# , ~~42~~ ~~35~~ ~~34~~ 33 bytes

```
round(2*exp((1:2+0:7%/%2*pi)/2i))

```

Try it online!

Outputs as complex numbers.

# Answer
> 6 votes
# , ~~37~~ ~~29~~ ~~26~~ 25 / 23\* bytes

*Edit: -1 byte thanks to pajonk*
**Edit 2: Or -2 more bytes with output as elements of a 2x4 matrix, thanks to Giuseppe*

```
(1+.5:-1*4i)*1i^(2:9%/%2)

```

Try it online!

Change of approach to try to compete with pajonk; now outputs as complex numbers.
~~Still frustratingly 3 bytes longer than~~ ~~Now the same length as~~ Satisfyingly now shorter than a hard-coded string...

# Answer
> 6 votes
# Jelly, ~~9~~ 8 bytes

```
Ø+p×Ø½UƬ

```

Try it online!

*-1 by stretching the output format a bit*

```
Ø+p         Cartesian product of [1, -1] with itself.
   ×Ø½      Multiply each pair with [1, 2],
      UƬ    and pair with the reversed pairs.

```

# Jelly, 9 bytes

```
ı*Ɱ4×2ıṠƬ

```

Try it online!

Port of Jonah's J solution.

# Jelly, 11 bytes

```
“ç©Ḅ’b5_2ṡ2

```

Try it online!

Port of loopy walt's Python solution.

# Jelly, 12 bytes

```
“œƇØj_’ṃ“21-

```

Try it online!

A fully hardcoded, no separator solution for comparison.

# Answer
> 6 votes
# Factor \+ `math.combinatorics math.unicode`, 47 bytes

```
{ 1 -1 2 -2 } 2 selections [ Σ odd? ] filter .

```

Try it online!

## How?

Generate all 2-selections of `{ 1 -1 2 -2 }`:

```
{ 1 1 }
{ 1 -1 }
{ 1 2 }
{ 1 -2 }
{ -1 1 }
{ -1 -1 }
{ -1 2 }
{ -1 -2 }
{ 2 1 }
{ 2 -1 }
{ 2 2 }
{ 2 -2 }
{ -2 1 }
{ -2 -1 }
{ -2 2 }
{ -2 -2 }

```

and keep only those with odd sums:

```
{ 1 2 }
{ 1 -2 }
{ -1 2 }
{ -1 -2 }
{ 2 1 }
{ 2 -1 }
{ -2 1 }
{ -2 -1 }

```

# Answer
> 6 votes
# Brachylog, 9 bytes

```
12ẹ{ṅ|}ᵐp

```

Try it online!

Generates each move.

```
   {  }ᵐ     For each element of
  ẹ          the digits of
12           12,
     |       maybe
    ṅ        negate it.
        p    Output a permutation of the result.

```

Although  maps over digits if given a raw integer, it also smashes the results back into an integer, which doesn't play nice with signs.

# Answer
> 5 votes
# MathGolf, 9 bytes

```
2╤ç■gÉ±~¡

```

Try it online.

**Explanation:**

```
2╤         # Push a list in the range [-2,2]: [-2,-1,0,1,2]
  ç        # Remove the 0 with a falsey filter
   ■       # Cartesian product with itself
    g      # Filter these pairs by,
     É     # using three characters as inner code-block:
      ±    #  Take the absolute values of the pair
       ~   #  Pop and push the values separated to the stack
        ¡  #  Check that they are NOT equal
           # (after which the entire stack is output implicitly as result)

```

# Answer
> 5 votes
# x86-64 machine code, 15 bytes

```
B8 01 02 FF FE AB 0F C8 AB C1 C8 18 73 F7 C3

```

Try it online!

Writes a size-8 array of size-2 arrays of 8-bit integers to an address given in RDI.

In assembly:

```
f:  mov eax, 0xFEFF0201 # Set EAX to this value; -2, -1, 2, 1 from top to bottom.
r:  stosd       # Write EAX to the output address, advancing the pointer.
    bswap eax   # Reverse the order of the bytes of EAX, getting 1, 2, -1, -2.
    stosd       # Write EAX to the output address, advancing the pointer.
    ror eax, 24 # Rotate right by 24 bits, getting 2, -1, -2, 1.
    jnc r       # Jump back if CF (set from the last bit rotated: the high bit) is 0.
                #  This is true the first time.
                # After the jump, the value is added to the output again,
                #  then reversing gives 1, -2, -1, 2, which is also added to the output,
                # and then rotating gives -2, -1, 2, 1, and CF is 1, ending the loop.
    ret         # Return.

```

# Answer
> 5 votes
# Nekomata, 3 bytes

```
į→ŋ

```

Attempt This Online!

```
į→ŋ
į       [0,1] or [1,0]
 →      Increment
  ŋ     Optionally negate each element

```

---

## Nekomata before v0.3.5.0, 6 bytes

```
2R↕ᵐᶜ_

```

Attempt This Online!

A port of @Unrelated String's Brachylog answer.

```
2R          Range from 1 to 2
  ↕         Permutation
   ᵐᶜ_      Optionally negate each element

```

# Answer
> 4 votes
# Regenerate `a`, 13 bytes

```
-?1-?2|-?2-?1

```

Not sure if this is golfable unless more features are added to the language lol... but please prove me wrong!

Prints like this:

```
12
1-2
-12
-1-2
21
2-1
-21
-2-1

```

Breakdown:

```
-?1-?2|-?2-?1
              Print every string that is
-?1             -1 or 1
   -?2          followed by -2 or 2
      |       or
       -?2      -2 or 2
          -?1   followed by -1 or 1

```

Attempt This Online!

# Answer
> 3 votes
# Python, 67 bytes

```
lambda:[z for i in range(99)if{*map(abs,z:=(i%5-2,i//5-2))}=={1,2}]
```

Attempt This Online!

Shorter than using `itertools.product`

# Answer
> 3 votes
# Wolfram Language (Mathematica), ~~41~~ 36 bytes

-5 bytes, thanks @att.

Selects the elements with odd element sum from the group of all length 2 tuples with elements from the set {1,-2,2,-2}:

```
{1,-1,2,-2}~Tuples~2~Select~OddQ@*Tr

```

# Answer
> 3 votes
# Vyxal, ~~16~~ 13 bytes

```
»1rKȮ8»`-12`τ

```

Try it online!
-3 thanks to Steffan

**7 bytes** (`o`, Port of this, also thanks to Steffan)

```
k-:dẊ…R

```

Try it online!

### 16 bytes (old)

```
»-∞ðO∩ß¹¶"⊍»0\-¢

```

Try it Online!

```
»-∞ðO∩ß¹¶"⊍»        # Compressed integer 201120201021102010201221
            0\-¢    # Replace 0 with -

```

Spent forever trying to find a cool answer but this is all my half asleep brain could come up with at the moment
There is a 0% chance this is optimal :P

# Answer
> 3 votes
# C (gcc), ~~74~~ 70 bytes

*-4 bytes thanks to @ceilingcat*

```
i;main(){for(;i<32;++i)putchar(i&1?(i/2^i/8)%2+49:i&4+6*(i&2)?45:43);}

```

Try it online!

Edit: it's obviosly longer than necessary, but it's the shortest way I found without printing directly the result.

# Answer
> 3 votes
# brainfuck, 68 bytes

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

```

Try it online!

Start is Similar to Pyautogui's answer, with a loop running `255/5=51` times to set a starting cell to `51`. But I set two cells to `51`, and use one for the characters `12` and the other one (hunt and peck style) for the character `-`.

The output `211-2-21122-1-12-2-1-1-2` consists of alternating pairs of `2`s and `1`s with interspersed `-` where necessary. The first two `1`'s are read from the cell which generates the `-` as the value descends from `51` through `49` to `45`. The rest of the `1`s are from the same cell as the `2`.

# brainfuck, 29 bytes

```
+.+..-..>--..+..-..<.+.>+..<.

```

Try it online!

A different interpretation of the rules outputting binary values `-2, -1, 1, 2` when run on a blank Brainfuck tape. For convenient verification the header initializes the two cells used on the tape to `48 = ASCII '0'` so that the outputs for `-2, -1, 1, 2` are `. / 1 2` respectively.

# Answer
> 3 votes
# C (gcc), 68 bytes

```
y;main(x){for(y=3;x--<-3?x=--y+6:x*x+y*y-5||printf("%d,%d;",x,y););}

```

Try it online!

# Answer
> 2 votes
# Charcoal, 16 bytes

```
ＩΦＥφ⁻↨ι⁵⁰χ⁼⁵ΣＸι²

```

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

```
   φ                Predefined variable `1000`
  Ｅ                 Map over implicit range
      ι             Current value
     ↨              Convert to base (i.e. divmod)
       ⁵⁰           Literal integer `50`
    ⁻               Vectorised subtract
         χ          Predefined variable `10`
 Φ                  Filtered where
              ι     Current pair
             Ｘ      Vectorised raised to power
               ²    Literal integer `2`
            Σ       Take the sum
          ⁼         Is equal to
           ⁵        Literal integer `5`
Ｉ                   Cast to string
                    Implicitly print

```

Using base conversion results in the invalid "pairs" `[]`, `[-9]`, `[-8]`, ... `[39]` but none of them have a Euclidean distance of `√5`. Boring string compression version for 11 bytes:

```
”{“↥?UV&✳¿>

```

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

# Answer
> 2 votes
# Excel, ~~49~~ 40 bytes

Saved 9 bytes thanks to JvdV

```
=CONCAT({1,-1}&2*{1;-1},2*{1,-1}&{1;-1})

```

Outputs pairs without delimeters.

---

# Excel, 27 bytes

```
="12-121-2-1-221-212-1-2-1"

```

... but that's too boring.

# Answer
> 2 votes
# Ruby, 33 bytes

```
x,y=1,2
4.times{p x,t=y,y=-x,x=t}

```

Try it online!

A straightforward rotation based on a concept of `y,x=-x,y` with some extra code to print in reverse as well.

# Answer
> 2 votes
# Burlesque, 18 bytes

```
{1-1}{2-2}cpJ)<-_+

```

Try it online!

```
{1-1} # {1 -1}
{2-2} # {2 -2}
cp    # Cart product
J     # Duplicate
)<-   # Reverse each in dup
_+    # Concat

```

# Answer
> 2 votes
# BQN, 19 bytes

```
(2|+´)¨⊸/⥊⋈⌜˜-⊸∾1‿2

```

Try it at BQN online

### Explanation

```
(2|+´)¨⊸/⥊⋈⌜˜-⊸∾1‿2
                  1‿2  List containing 1 and 2
                 ∾     Prepend
               -⊸      its negation
           ⋈⌜˜         Table of each item of that list paired with each item of that list
         ⥊             Deshape into a list of two-element lists
(    )¨                For each of those:
   +´                    Get its sum
 2|                      Mod 2
       ⊸/              Select the elements for which that result is 1

```

# Answer
> 1 votes
# (8-bit, wrapping) Brainfuck, 80 bytes

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

Attempt This Online!

Outputs in the example format: "2-112-2-1-211-2-1-2-1221". Originally, this was in severe need of a golf, having been made by an automated tool. I have now optimized it a little. It now uses a similar technique to Level River St's answer, though I arrived at it independently, and it differs in the details; instead of 51, the starting value is 50.

# Answer
> 1 votes
A reference for all the trivial approaches.

# Python, 33 bytes

```
print('2-112-2-1-211-2-1-2-1221')
```

Attempt This Online!

# , 26 bytes

```
'2-112-2-1-211-2-1-2-1221'

```

Try it online!

# Wolfram Language (Mathematica), 26 bytes

Assumes a notebook environment. If this is false `Echo@` can be added in front at the cost of 5 bytes.

```
"2-112-2-1-211-2-1-2-1221"

```

Try it online!

# Answer
> 1 votes
# A0A0, 39 bytes

```
O-1212212
O-1
O-2
O-11
O-2
O-1
O-2
O-21

```

Prints `-1212212-1-2-11-2-1-2-21`. This simply prints many negative numbers, of which the negative numbers form non-separated pairs of relative positions. Since there are eight negative numbers, we use eight different output instructions.

# Answer
> 1 votes
# JavaScript, 58 bytes

```
_=>[...'01234567'].map(i=>[((i&4)-2)/(m=i%2+1),(i&2)*m-m])

```

Try it online!

I know it's shorter to hardcode, but that feels cheaty...

# Answer
> 1 votes
# Headascii, 71 bytes

```
++++[]+^^^D^^^D^P]PD^P]+PD^P]+PD^P]PD^P]P+PPD^P]PPD^P]+PD^P]+P-PP+PP-P!

```

Outputs `-1-2-2-1-122-11-2-211221`

Try it Here by executing

```
erun("++++[]+^^^D^^^D^P]PD^P]+PD^P]+PD^P]PD^P]P+PPD^P]PPD^P]+PD^P]+P-PP+PP-P!")

```

I'm ashamed at how long this is. I have to make a golfier language.............................

# Answer
> 1 votes
# 05AB1E, 8 bytes

```
X®‚xâ˜Â«

```

Try it online!

```
X     push an integer variable, which is initialized to 1 (using 1 makes it a string, which makes the output look weird)
®     push the register, which is initialized to -1
‚     pair, to get [1, -1]
x     push tos and itself doubled, to get [1, -1], [2, -2]
â     Cartesian product, all pairs
˜     Flatten, to get a list of coordinates instead of a list of pairs
Â     Push tos and itself reversed
«     Concatenate

```

# Answer
> 1 votes
# Zsh, 26 bytes

```
echo {,-}2{,-}1 {,-}1{,-}2
```

Attempt This Online!

One byte shorter than the trivial solution `<<<2-112-2-1-211-2-1-2-1221`.

# Answer
> 1 votes
# Vyxal, ~~10~~ 9 bytes

-1 byte thanks to @lyxal

```
k□02vV:NJ

```

Try it Online!

```
    k□   # [[0,1],[1,0],[0,-1],[-1,0]]
   02vV # replace all 0 with 2 in elements of list (v applies next operation to elents of list)
    :    # duplicate
    N  # negation (* -1) in  elements of list
    J    # join it

```

# Answer
> 1 votes
# Curry (KiCS2), 28 bytes

```
f 4
f(x#y)=(x,y)
x#y=x^2*y^2

```

Attempt This Online!

A port of @att's Mathematica answer.

This does not work on PAKCS.

KiCS2 is able to search for integer solutions of mathematical equations. This is done by an internal binary representation of numbers.

# Answer
> 1 votes
# Thunno `j`, \\$ 17 \log\_{256}(96) \approx \\$ 13.99 bytes

```
1DnZPD2*Z!D.rA+.J

```

Attempt This Online! Prints `21 2-1 -21 -2-1 12 -12 1-2 -1-2`.

#### Explanation

```
1         # Push 1                  STACK: 1
 Dn       # Duplicate and negate    STACK: 1, -1
   ZP     # Pair                    STACK: [1, -1]
     D2*  # Duplicate and double    STACK: [1, -1], [2, -2]
Z!        # Cartesian product       STACK: [[2, 1], [2, -1], [-2, 1], [-2, -1]]
  D.r     # Duplicate and reverse   STACK: [[2, 1], [2, -1], [-2, 1], [-2, -1]], [[1, 2], [-1, 2], [1, -2], [-1, -2]]
     A+   # Concatenate             STACK: [[2, 1], [2, -1], [-2, 1], [-2, -1], [1, 2], [-1, 2], [1, -2], [-1, -2]]
       .J # Join each inner list    STACK: ['21', '2-1', '-21', '-2-1', '12', '-12', '1-2', '-1-2']
          # j flag joins this list  STACK: '21 2-1 -21 -2-1 12 -12 1-2 -1-2'
          # Implicit output

```

# Answer
> 1 votes
# Scala, 41 bytes

Golfed version. Try it online!

```
println(("2212-1-21-2-1"*2).substring(2))

```

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


# Question
Title: Calculate the number of topologies on {1,2,...,n}
## Task

> Write a function/program which takes \\$n\\$ as a parameter/input and prints/returns the number of topologies (which is demonstrated below) on the set \\$\\{1,2,...,n\\}\\$.

## Definition of Topology

Let \\$X\\$ be any finite set, and assume that \\$T\\$, which is subset of the power set of \\$X\\$ (i.e. a set containing subsets of \\$X\\$), satisfy these conditions:

1. \\$X\\$ and \\$\emptyset\\$ are in \\$T\\$.
2. If \\$U, V\\$ are in \\$T\\$, then the union of those two sets is in \\$T\\$.
3. If \\$U, V\\$ are in \\$T\\$, then the intersection of those two sets is in \\$T\\$.

...then \\$T\\$ is called the topology on \\$X\\$.

## Specifications

1. Your program is either:

* a function which takes \\$n\\$ as a parameter
* or a program which inputs \\$n\\$

and prints or returns the number of (distinct) topologies on the set \\$\\{1,2,...,n\\}\\$.

2. \\$n\\$ is any non-negative integer which is less than \\$11\\$ (of course there's no problem if your program handles n bigger than \\$11\\$), and the output is a positive integer.
3. Your program should not use any kinds of library functions or native functions which calculates the number of topology directly.

Example input (value of n) : `7`

Example output/return : `9535241`

You may check your return value at here or here.

Of course, shortest code wins.

---

The winner is decided, however, I may change the winner if shorter code appears..

# Answer
# Haskell, 144 characters

```
import List
import Monad
p=filterM$const[True,False]
f n=sum[1|t<-p$p[1..n],let e=(`elem`t).sort,e[],e[1..n],all e$[union,intersect]`ap`t`ap`t]

```

Almost a direct implementation of the specification, modulo some monad magic.

Extremely slow for `n > 4`.
> 4 votes

# Answer
## Python, 147 chars

```
N=input()
S=lambda i,K:1+sum(0if len(set(j&k for k in K)-K)-1 else S(j+1,K|set(j|k for k in K))for j in range(i,2**N))
print S(1,set([0,2**N-1]))

```

Quick for N\<=6, slow for N=7, unlikely N\>=8 will ever complete.

Individual sets are represented by integer bitmasks, and topologies by sets of bitmasks. `S(i,K)` computes the number of distinct topologies you can form by starting with `K` and adding sets with bitmasks \>= `i`.
> 5 votes

# Answer
# Python, 131 chars

```
lambda n:sum(x&(x>>2**n-1)&all((~(x>>i&x>>j)|x>>(i|j)&x>>(i&j))&1 for i in range(2**n)for j in range(2**n))for x in range(2**2**n))

```

Expanded version:

```
def f(n):
    count = 0
    for x in range(2**2**n): # for every set x of subsets of [n] = {1,...,n}
        try:
            assert x & 1 # {} is in x
            assert (x >> 2 ** n - 1) & 1 # [n] is in x
            for i in range(2**n): # for every subset i of [n]...
                if x >> i & 1: # ...in x
                    for j in range(2**n): # for every subset j of [n]...
                        if x >> j & 1: # ...in x
                            assert (x >> (i | j)) & 1 # their union is in x
                            assert (x >> (i & j)) & 1 # their intersection is in x
            count += 1
        except AssertionError:
            pass
    return count

```

For example, suppose n = 3. The possible subsets of \[n\] are

```
0b000
0b001
0b010
0b011
0b100
0b101
0b110
0b111

```

where the ith bit indicates whether i is in the subset. To encode *sets* of subsets, we notice that each of these subsets either belongs or does not belong to the set in question. Thus, for example,

```
x = 0b10100001
0b000 # 1
0b001 # 0
0b010 # 1
0b011 # 0
0b100 # 0
0b101 # 0
0b110 # 0
0b111 # 1

```

indicates that x contains {}, {2}, and {1,2,3}.
> 1 votes

# Answer
## Zsh, 83 characters

This solution matches the letter of your requirements (but not, of course, the spirit). There's undoubtedly a way to compress the numbers even more.

```
a=(0 3 S 9U 5CT 4HO6 5ODFS AMOZQ1 T27JJPQ 36K023FKI HW0NJPW01R);echo $[1+36#$a[$1]]

```
> 0 votes

# Answer
# Jelly, 28 bytes

```
ŒP⁺f,œ|ɗþ`ẎẎṢe¥€Ʋ;ẠCaiʋẠʋ€RS

```

Try it online!

*So, incredibly,* slow. Times out on TIO for all \\$n \ge 4\\$, and running it locally with \\$n = 4\\$ still didn't produce an output after 15 minutes. That is because this answer has a time complexity of \\$O(2^{2^n})\\$, as we calculate \\$\mathcal P(\mathcal P(\\{1, 2, ..., n\\}))\\$ and filter on topologies.

## How it works

```
ŒP⁺f,œ|ɗþ`ẎẎṢe¥€Ʋ;ẠCaiʋẠʋ€RS - Main link. Takes n on the left
ŒP                           - Powerset of X = [1, 2, ..., n]
  ⁺                          - Powerset of that
                        ʋ    - Last 4 links as a dyad f(T, X):
                Ʋ            -   Last 4 links as a monad g(T):
       ɗ                     -     Last 3 links as a dyad h(U, V):
   f                         -       U ∩ V
     œ|                      -       U ∪ V
    ,                        -       [U ∩ V, U ∪ V]
        þ`                   -     For all U ∈ T, V ∈ T, calculate h(U, V)
          ẎẎ                 -     Flatten into a list of unions and intersections
              ¥              -     Last 2 links as a dyad k(Z, T):
            Ṣ                -       Sort Z
             e               -       Is Z ∈ T?
               €             -     For each Z in the list of unions and intersections, find k(Z, T)
                      ʋ      -   Last 4 links as a dyad l(T, X):
                  Ạ          -     Are all elements of T truthy?
                   C         -     Complement; are any falsey?
                     i       -     Index of X in T, or 0 if not present
                    a        -     And; are both true?
                 ;           -   Concatenate the list of k(Z, T)s with l(T, X)
                       Ạ     -   Are all true?
                          R  - X = [1, 2, ..., n]
                         €   - Over each T ∈ P(P(X)), calculate f(T, X)
                           S - Count the truthy elements

```
> 0 votes

# Answer
# Scala, ~~450~~ 343 bytes

Thanks to the comment, saved 107 bytes using some trivial tricks.

---

rewrite @user76284's solution into scala.

Using scala for calculation is so slow! On TIO, I only use one case `f(4)=355`

---

Golfed version. Try it online!

```
def f(n:Int)={var c=0;for(x<-0 until math.pow(2,math.pow(2,n)).toInt){try{assert((x&1)!=0);assert((x>>((math.pow(2,n)-1).toInt)&1)!=0);for(i<-0 until math.pow(2,n).toInt){if(((x>>i)&1)!=0){for(j<-0 until math.pow(2,n).toInt){if(((x>>j)&1)!=0){assert(((x>>(i|j))&1)!=0);assert(((x>>(i&j))&1)!= 0);}}}}; c+=1;}catch{case _:AssertionError=>;}};c}

```

Ungoled version. Try it online!

```
object Main {
  def f(n: Int): Int = {
    var count = 0
    for (x <- 0 until math.pow(2, math.pow(2, n)).toInt) {
      try {
        assert((x & 1) != 0)
        assert((x >> ((math.pow(2, n) - 1).toInt) & 1) != 0)
        for (i <- 0 until math.pow(2, n).toInt) {
          if ( ((x >> i) & 1) != 0) {
            for (j <- 0 until math.pow(2, n).toInt) {
              if ( ((x >> j) & 1) != 0) {
                assert( ((x >> (i | j)) & 1) != 0)
                assert( ((x >> (i & j)) & 1) != 0)
              }
            }
          }
        }
        count += 1
      } catch {
        case _: AssertionError =>
      }
    }
    count
  }

  def main(args: Array[String]): Unit = {
    val n =4
    val result = f(n)
    println(s"f($n) = $result")
  }
}

```
> 0 votes

---
Tags: code-golf, math, set-theory
---


title: Calculate a square and a square root!

text:
# Question
Title: Calculate a square and a square root!
You must make a that outputs the square of the input in one language and the square root of the input in another. The shortest answer in bytes wins!

You must have a precision of at least 3 decimal places, and the input will always be a positive float.

# Answer
> 49 votes
# Jolf and MATL, 1 byte

```
U

```

Square root in Jolf, square in MATL.

Try it online! (MATL)

Try the Jolf code. Only works on Firefox.

These are both 1 byte, as MATL and Jolf both use ASCII/extended ASCII codepages, so all commands are 1 byte.

# Answer
> 98 votes
# C and C++, ~~68~~ 65 bytes

```
#include<math.h>
float f(float n){auto p=.5;return pow(n,2-p*3);}

```

Original answer:

```
#include<math.h>
float f(float n){return pow(n,sizeof('-')-1?2:.5);}

```

For both versions, C produces `n^2` and C++ produces `sqrt(n)`.

# Answer
> 55 votes
# Python 2 & Python 3, ~~23~~ 21 bytes

```
lambda n:n**(1/2or 2)

```

Python 2.x produces `n^2`, Python 3.x produces `sqrt(n)`.

2 bytes saved thanks to @Dennis!

# Answer
> 34 votes
# 2sable / Jelly, 2 bytes

```
*.

```

2sable computes the square. Try it online!

Jelly computes the square root. Try it online!

## How it works

### 2sable

```
*   Read the input twice and compute the product of both copies.
    This pushes the square of the input.
 .  Unrecognized token (ignored).

```

### Jelly

```
 .  Numeric literal; yield 0.5.
*   Raise the input to the power 0.5.
    This yields the square root.

```

# Answer
> 19 votes
# C (clang) and Python, ~~109~~ ~~107~~ ~~69~~ 53 bytes

```
#/*
lambda n:n**.5;'''*/
float a(i){return i*i;}//'''

```

C: Try it online!

Python: Try it online!

Works by using comments to polyglot. The rest is pretty explanatory.

First time using C!

* Saved quite a few bytes thanks to @Riker.
* Saved 2 bytes by removing unnecessary whitespace.
* Saved very many bytes by using a function for C instead of STDIN/OUT.
* Saved 16 bytes thanks to @Delioth by removing import statement at the top.

# Answer
> 18 votes
# Ohm and Jelly, 3 bytes

Outputs the square in Ohm, the square root in Jelly.

Ohm and Jelly use different single-byte codepages, so the program will appear differently in each encoding.

xxd hexdump of the program:

```
00000000: fd7f 0a                                  ...

```

### Jelly

Using Jelly's codepage, it appears like this:

```
’
½

```

Jelly takes the bottom most line to be its main link, and ignores the other links unless specifically called. So here it just does the square root (`½`) and implicitly outputs it.

### Ohm

Using Ohm's codepage (CP437), it appears like this:

```
²⌂◙

```

`²` is the square function, and  and  are both undefined, so the program just squares the implicitly read input and implicitly outputs it.

# Answer
> 14 votes
# C89 and C99, 47+3 = 50 bytes

```
float f(float n){return n//*
/sqrt(n)//*/1*n
;}

```

Requires `-lm` flag (+3)

C89 produces `n^2`, C99 produces `sqrt(n)`. To test in C89, Try it online!

---

Getting C89 to do the `sqrt` version ought to take less code, but it insists on implicitly declaring the `sqrt` function with `int`s, so this is the best I could manage.

# Answer
> 13 votes
# Octave / MATLAB, ~~31~~ 29 bytes

```
 @(x)x^(2-3*any(version>60)/2)

```

This outputs the square in Octave, and the square root in MATLAB.

**Explanation:**

The syntax is of course identical in MATLAB and Octave (for this little piece of code at least).

This creates an anonymous function:

```
@(x)                                 % Take x as input
    x^(                     )        % Raise x to the power of ...
               version                 % Returns the version number
                                       % 4.2.0 in Octave,
                                       % '9.2.0.538062 (R2017a)' in MATLAB
               version>60              % 'R' is larger than 60. All others are smaller
         3*any(version>60)/2           % Checks if there is an 'R' and multiplies it by 1.5 if it is.
       2-3*any(version>60)           % 2-1.5*(is there an 'R')

```

# Answer
> 12 votes
# Basic / Delphi – 6 characters

```
sqr(x)

```

Square root in Basic and square in Delphi.

You can use a debugger to inspect the expression, thereby fulfilling any output requirements!

# Answer
> 11 votes
# 05AB1E / Fireball, 3 bytes

The following bytes make up the program:

```
FD B9 74

```

05AB1E calculates square root, Fireball squares.

Explanation (05AB1E - `ý¹t`):

```
ý       Pushes an empty string to the stack (not entirely sure why)
 ¹      Push first input
  t     Square root

```

Explanation (Fireball - `²╣t`):

```
²       Square input
 ╣      Unassigned
  t     Unassigned

```

Sometimes, it helps to have an incomplete language ;)

# Answer
> 10 votes
# PHP7 + JavaScript, ~~62~~ ~~61~~ 58 bytes

This was actually more challenging than I expected! I am quite surprised of how long my code is.

```
eval(['alert((_=prompt())*_)','echo$argv[1]**.5'][+![]]);
```

---

**How does it work?**

This works by selecting the code to run, from the array.
PHP and JavaScript detection is made with `+![]`.

In PHP, `[]` (empty array) is a falsy value, while in JavaScript it is a truthy value (objects (except `null`) are always truthy, even `new Boolean(false)` is truthy!).
But, I need to get it to a numeric value, so, I just use a `not` (`!`) and convert it to integer (with the `+`).
Now, PHP yields the value `1`, while JavaScript yields `0`.
Placing the code inside an array, at those indexes, will allow us to select the right code for the desired language.
This can be used as `[JS,PHP][+![]]`, to get the code of the right language.

On previous polyglots, I've used `'\0'=="\0"`, which is `true` in JavaScript (since `\0` is parsed as the NULL-byte) and `false` in PHP (the `'\0'` won't be parsed as the NULL-byte, comparing the literal string `\0` with the NULL-byte).
I'm happy that I've managed to reduce this check to `+!'0'`.
I'm even more happy about @rckd, which reduced it to the current version!

From there on, it simply `eval`s the code required.

**PHP**

PHP will execute `echo$argv[1]**.5` (equivalent to `echo sqrt($argv[1]);`, square-root the number), receiving the value from the 2nd argument and displays it in the standard output.

**JavaScript**

JavaScript executes `alert((_=prompt())*_)`, which displays the squared number in an `alert`.

---

---

Thank you to @rckd for saving 1 byte, and @user59178 for saving 3 bytes!

# Answer
> 7 votes
# 05AB1E and Jelly, 4 bytes

```
nqƓ½

```

(05AB1E) \- (Jelly)

```
nq   # Ignored by Jelly, push n**2 in 05AB1E then quit.
  Ɠ½ # Ignored by 05AB1E due to quit, push sqroot of input in Jelly.

```

---

Someone else made a good point, I guess since the UTF-8 characters do not share the same operation across code pages that they are technically 2-bytes each to encode. However, when looking at this in terms of the hex dump:

```
6e 71 93 0a

```

In 05AB1E's CP1252 encoding this results in:

```
nq“\n

```

Meaning it will still output the square and quit, ignoring the rest. When these bytes are encoded using Jelly's codepage:

```
nqƓ½

```

Which is the original intended code, when executed, results in the desired result of taking the input and taking the sqrt.

# Answer
> 5 votes
# Python 2 and Forth, ~~43~~ 33 bytes

```
( """ )
fsqrt
\ """);lambda n:n*n

```

**Try it online: Python 2 (square) | Forth (sqrt)**

This evaluates to an anonymous function in Python, and a built-in function `fsqrt` in Forth. Python can have a named function `f` for 2 bytes more by putting `f=` in front of the lambda.

The Forth program takes a floating point literal, which in Forth must be written in scientific notation. Pi truncated to 3 decimal places (`3.141`) would be written like this:

```
3141e-3

```

# Answer
> 5 votes
# CJam / MATL, 8 bytes

```
ld_*GX^!

```

Computes the square in CJam (Try it online!) and the square root in MATL (Try it online!).

### Explanation of square in CJam

```
ld    e# Read input line and interpret as a double
_     e# Duplicate
*     e# Multiply. Pops the input number twice, pushes its square
G     e# Push 16
X     e# Push 1
^     e# Bitwise XOR. Pops 16 and 1, and pushes 17
!     e# Negate. Pops 17, pushes 0
      e# Implicitly display. This prints the squared input with decimals,
      e# immediately followed by the 0 coming from the negate operation
      e# Even if the square of the input number is an integer, say 5,
      e# it is displayed as 5.0, so including an extra 0 always gives a
      e# correct result

```

### Explanation of square root in MATL

```
l      % Push 1. This is a number or equivalently a 1×1 array
d      % Consecutive differences. Pops 1, pushes [] (empty array)
_      % Negate (element-wise). This leaves [] as is
*      % Implicitly input a number and push it. Multiply (element-wise):
       % pops [] and the input number, pushes []
G      % Push input number again
X^     % Square root. Pops number, pushes its square root
!      % Transpose. For a number (1×1 array) this does nothing
       % Implicitly display. The stack contains [] and the result; but
       % [] is not displayed at all

```

# Answer
> 5 votes
# JavaScript (ES6) / JavaScript (ES7), 52 bytes

```
f=a=>eval(`try{eval("a**2")}catch(e){Math.sqrt(a)}`)

```

Returns the square of the input in ES7 and the square root in ES6. Quite difficult to test, unless you have an older browser which support ES6 but not ES7.

```
f=a=>eval(`try{eval("a**2")}catch(e){Math.sqrt(a)}`)

console.log(f(4));
```

# Answer
> 5 votes
# C, Operation Flashpoint scripting language, 52 bytes

```
;float f(float x){return sqrt(x);}char*
F="_this^2";

```

In an OFP script, a semicolon at the beginning of a line makes that line a comment, whereas C doesn't care about the additional semicolon.

**C:**

Try it online!

**OFP scripting language:**

Save as `init.sqs` in the mission folder, then call it with `hint format["%1", 2 call F]`.

Result:

# Answer
> 5 votes
# Vyxal, Grok ~~10~~ 12 bytes

*Edit: In my first version, I forgot that casting to `int` would remove precision in the Vyxal code. Added +2 bytes to fix it.*

```
I√`#:Yp*zq`_

```

Vyxal (Square Root):

```
              # Implicit input
I             # Cast to int
 √            # Square root
  `#:Yp*zq`   # Push string
           _  # Delete string
              # Implicit output

```

Try it Online in Vyxal!

Grok (Square):

```
I√            # Push '√' to the register
  `#          # Skip ‘#’ command
    :         # Take input from STDIN
     Yp       # Duplicate
       *z     # Multiply and output as int
         q    # Quit
          `_  # Never gets executed

```

Try it Online in Grok!

# Answer
> 4 votes
# PHP and CJam, ~~30~~ ~~29~~ 25 bytes

```
ECHO"$argv[1]"**2;#];rdmq

```

Calculates the square in PHP and the square root in CJam. Has to be run using `-r` in PHP.

### PHP

Raises the first command line argument (`$argv[1]`) to the power 2 and outputs it. Here `$argv[1]` is actually put as an inline variable in a string, which is cast to a number before doing the exponentiation. This is because `v` is not a valid instruction in CJam and will cause it to error out while parsing, but putting it in a string won't cause any problems.

`#` starts a comment, so everything after is ignored.

Try it online!

### CJam

The first part of the code, `ECHO"$argv[1]"**2;#` pushes a bunch of values and does a bunch of operations, all of which are thoroughly useless. The only important thing is that they doesn't cause any errors, because right afterwards is `];`, which wraps the entire stack in an array and then discards it.

After that, it reads a double from input (`rd`), and gets its square root (`mq`), and implicitly outputs it.

Try it online!

# Answer
> 4 votes
# Desmos and Pip, 12 bytes

```
YRTa
f(y)=yy

```

Run in Desmos

Run in Pip

### Desmos

The first line is four undefined variables multiplied together. Desmos complains about it, but ultimately it's a no-op.

The second line defines a function `f(y)` as `y` times `y` (with an implicit multiplication operator). This function can be used in other lines and will return the square of any argument number. As a bonus, we also get to see a graph of `x = f(y)`.

### Pip

`RTa` calculates the square root of the command-line argument `a`, and `Y` stores the result in `y`. The second line parses as three expressions:

* `f` (evaluates to the main function)
* `(y)=y` (evaluates to `1` because `y` always equals itself)
* `y` (evaluates to the value stored in `y` previously)

The last of these expressions ends the program and is therefore autoprinted.

# Answer
> 4 votes
# Python / PARI/GP, 60 bytes

```
#/*
n=int(input());print(n**2);"""*/
print(sqrt(input))\\"""

```

Basically a modification from the C / Python answer.
Python does square. PARI/GP does square root.
Takes input from `stdin`.

Python: Try It Online!

PARI/GP: Try It Online!

# Answer
> 3 votes
## QBIC / QBasic, ~~26~~ 18 bytes

```
input a
?a^2'^.25

```

In **QBasic**, it takes a number, and prints that number squared. The rest of the code is ignored because QBasic sees it as a comment (`'`).

**QBIC** uses the same input statement. It then goes on to print that same number squared, then raised to the power of a quarter, effectively rooting it twice. This is because `'`is seen as a code literal: Pure QBasic code that is not parsed by QBIC.

# Answer
> 3 votes
# Reticular / Befunge-98, 15 bytes

2D languages!

```
/&:*.@
>in:o#p;

```

## Befunge-98

```
/&:*.@

/          divide top two (no-op)
 &         read decimal input
  :        duplicate
   *       square
    .      output
     @     terminate

```

## Reticular

```
/           mirror up, then right
>in:o#p;

 i          read line of input
  n         cast to number
   :o#      square root
      p     print
       ;    terminate

```

# Answer
> 3 votes
## GolfScript/Befunge, 15 bytes

```
#>&:*.@
~2-1??
```

Befunge:

```
#>&:*.@
#>      // jumps over the arrow
  &     // takes an integer as input
   :*   // multiplies the top of the stack by itself
     .  // outputs as integer
      @ // halts
~2-1??  // is not executed

```

GolfScript:

```
#>&:*.@ // is a comment
~2-1??
~       // evaluates the input string
 2-1?   /* calculates 2^-1 = 1/2 (GolfScript does not support non-integers, but
           due to a missed int cast in the interpreter, they can be generated with
           the exponent function */
     ?  // calculates x^1/2 = sqrt(x)
        // the stack is output implicitly

```

This is my first golf, please let me know if I'm doing something wrong :)

* Edited to be more portable, thanks to Wzl

# Answer
> 3 votes
# Vyxal and \>\<\> (Fish), 10* bytes

```
<?√,;n*:

```

Try it in Vyxal (Square root)

*\*this is 8 bytes in Vyxal but 10 in \>\<\>. I'm scoring them both in UTF-8.*

Try it in \>\<\> (Square)

# Explanation

What Vyxal sees:

```
<       # less than
 ?      # push input
  √     # sqrt
   ,    # print that sqrt
        # (rest doesn't matter)

```

What \>\<\> sees:

```
<     # point left and wrap around executing the following
 :    # dup
  *   # multiply
   n  # output
    ; # end execution

```

# Answer
> 3 votes
# Thunno 2 and Vyxal, 4 bytes

Thunno 2 encoding:

```
Ẋ,$ƭ

```

Vyxal encoding:

```
²,$₃

```

This looks like two different programs, since Thunno 2 and Vyxal have different encodings, but it's really the same sequence of bytes.

(Thunno 2: square root)

Try it Online! (Vyxal: square)

#### Explanation

```
Ẋ,$ƭ  # Implicit input
Ẋ,    # (No effect)
  $   # Push the input
   ƭ  # Square root
      # Implicit output

²,$₃  # Implicit input
²     # Square the input
 ,    # Print the result
  $₃  # (No effect)

```

# Answer
> 2 votes
## \>\<\> / Jelly, 9 bytes (7 bytes code + 2 for the '-v' flag in \>\<\>)

Man, I'm really having fun with the Jelly link structure.

```
:*n;
½

```

Calculates the square in \>\<\> , and the square root in Jelly.

# Answer
> 2 votes
# Python 3 + JavaScript, 101 bytes

```
0//1or exec("function=lambda a:(lambda b:a);x=0")
y=2//2/2
f=(function(x)(x**y))//1 or(lambda x:x**y)

```

Square root in JS, square in Python.

Works on Firefox (tested on FF 52) and requires `(function(x) x)(42) === 42` being valid syntax. Also requires ES7 for the `**` operator.

# Answer
> 2 votes
# bash and sh, 48 bytes

*Update: I must concede defeat. Digital Trauma's bash/sh answer is far more elegant than this one.*

---

```
bc -l<<<"sqrt($1^(($(kill -l|wc -l)*3-3)/7+1))"

```

bash produces `n^2`, sh produces `sqrt(n)`.

---

`bc` is only needed so that `sqrt` can be calculated. The difference in behaviour is between bash and sh.

OK, technically the "sh" I'm using is still bash, but bash in "POSIX" mode (which happens if you invoke `/bin/sh` instead of `/bin/bash` on systems where `/bin/sh` is an alias for bash). If this is the case on your system, you can test with:

```
/bin/bash prog.sh 4
/bin/sh prog.sh 4

```

---

This is based on one of the differences explained here: https://www.gnu.org/software/bash/manual/html\_node/Bash-POSIX-Mode.html

# Answer
> 2 votes
# macOS Bash and sh, 24 bytes

```
p=^4 :
bc<<<"sqrt($1)$p"

```

On the Mac, `sh` is `bash` running in Posix mode, and in this case as per https://www.gnu.org/software/bash/manual/html\_node/Bash-POSIX-Mode.html:

> Assignment statements preceding POSIX special builtins persist in the shell environment after the builtin completes

Thus for `sh`, the variable `p` has the value `^4` after the `:` is run, but for `bash`, the variable `p` only has this value while `:` is run, and is empty afterwards.

Being still really `bash` under the covers, some bashisms such as `<<<` herestrings still work for both the bash and sh cases.

---

# Bash and dash (and GNU utils), 27

On Ubuntu 16.01, `sh` is a symlink to `dash`, which doesn't do `<<<` herestrings. So we have this instead:

```
p=^4 :
echo "sqrt($1)$p"|bc

```

Try it online.

# Answer
> 2 votes
# Python 3 and Python 2, 18 bytes

I took inspiration from this answer

```
(1/2or 2).__rpow__

```

### Python 3 : Try it online!

`1/2` is evaluated to `0.5` so `1/2or 2` is equal to `0.5` =\> sqrt

### Python 2 : Try it online!

`1/2` is evaluated to `0` so `1/2or 2` is equal to `2` =\> ^2

# Answer
> 2 votes
# Java and Groovy, 50 bytes

```
double f(int a){return Math.pow(a, 1/2==0?2:0.5);}

```

Try Java online!

Try Groovy online!

Java squares, Groovy roots. Inspiration taken from this answer, although it is unfortunate that Java does not have type coercion like Python and that Groovy has different lambdas than Java does. This works because in Java, `1/2` is equal to `0`, while in Groovy it is `0.5`.

# Answer
> 2 votes
# C and C#, 56 bytes

```
double f(double x){return//\
System.Math.Sqrt(x);
x*=x;}

```

C# doesn't use `\` as a line continuation character, at least not for line comments.

Try it in C!
Try it in C#!

I was originally going to do Swift + something else, since `/*/**/this// */` is only a comment in Swift, but it ended up being shorter to abuse C's line continuation and use another language with the same syntax.

# Answer
> 1 votes
# Jelly / Pip, 6 bytes

*EDIT: It's a byte shorter to reverse operations.*

```
RTa
²

```

Try Jelly online!

Jelly starts execution at the bottom of the code (its 'main link') and sees if it needs anything higher: it sees the command to square and takes care of input and output implicitly.

Try Pip online!

Pip executes the top line, squaring the (implicitly read from the cmd line) var a and implicitly prints that. The bottom line is ignored.

# Answer
> 1 votes
# Wolfram Language / PHP, 25 bytes

Get the square of a number in Wolfram Language and get the square root in PHP;

```
n^2
echo sqrt(_GET["n"]);

```

First line is Wolfram Language. First, you are the ones to change n in the searchbar in Wolfram Alpha so the code is also the input. Then it's will generate the answer upon pressing enter

```
n^2

```

Second line is PHP, It gets the square root of the n which is to be inputted in the address bar (eg. ppcg.php.net?n=213, where 213 is n's value)

```
echo sqrt($_GET["n"]);

```

# Answer
> 1 votes
# PHP 5.6 and PHP 7, 55 bytes

```
function f($n){list($a[],$a[])=[.5,2];echo $n**$a[0];}

```

PHP 5.6 produces `n^2`, PHP 7 produces `sqrt(n)`.

# Answer
> 1 votes
# Swift 5.0 and Swift 5.1, 112 bytes

```
func f(_ x:Any)->Double{let y=x as!Double
return y*y}
func f<T>(_ x:T)->Double{return(x as!Double).squareRoot()}

```

SwiftFiddle link

Swift 5.1 changed overload resolution for functions with unlabelled arguments, so `f(_:)` resolves as the square function in Swift 5.0 and as the square root in Swift 5.1. The permissive argument types are required for this to work; if you don't pass it a double, this will compile but crash at runtime.

The lack of argument labels is required: if you remove the underscores to make this `f(x:)`, it will print the square root in both versions.

# Swift 4 and Swift 5, ~~125~~ 113 bytes

```
import Foundation
func s(x:Double)->Double{return pow(x,Double("\(try?{()throws->Int?in 0}())".count)*0.15-1.15)}

```

SwiftFiddle link

The function `s(x:)` computes the square in Swift 4 and the square root in Swift 5.

The original answer had the throwing function on its own line, rather than being an inline IIFE.

This was harder than I expected.

The `try?` operator is one of three legal prefixes for a call to a throwing function -- the others being `try` and `try!`. `try` requires a `catch`, `try!` promotes errors to fatal errors, and `try?` ignores errors and returns `nil` instead. For example, consider the following code snippet:

```
func foo() throws -> Int {
    // ...
}

let bar = try? foo()

```

The type of `bar` is now `Optional<Int>`, since it might be `nil`.

What if `foo()` already returns `Optional<Int>`? In Swift 5, the optionals are flattened, and `bar` is still `Optional<Int>`. In Swift 4, this is not the case, and `bar` is now `Optional<Optional<Int>>`.

When you convert an optional value to a string, it wraps it in `"Optional("...")"`. So, the following code:

```
func foo() throws -> Int? {
    return 0
}

print("\(try? foo())")

```

Prints `Optional(0)` in Swift 5 and `Optional(Optional(0))` in Swift 4. (If you don't wrap it in the string interpolation, it fails to compile. I have no idea why.)

From there, I use `.count` to get the length of the string, and do some simple arithmetic to get `2.0` in Swift 4 and `0.5` in Swift 5.

# Swift 4 and Swift 5, cheating, 85 bytes

```
func s(x:Double)->Double{#if swift(>=5)
return x.squareRoot()#else
return x*x#endif
}

```

I shouldn't have to explain this.

# Answer
> 0 votes
# Octave / Cardinal, 28 bytes

This program squares the input in Cardinal and gets the square root in Octave

```
 %:=t.
disp(sqrt(input("")))

```

Try it online! (Octave)

Try it online! (Cardinal)

So % is single line comment in Octave so it just gets input and prints the square root

```
disp(sqrt(input("")))

```

So that the Cardinal program doesn't encounter a divide by 0 error and die, the program

```
%:=t.

```

has been shifted with a space, which is ignored by both programs

## Explanation of the Cardinal program:

The program starts at the %
It receives input and stores the value as active :
It sets the inactive to be equal to the active =
It multiplies the active by the inactive t
Finally it outputs the active value .

# Answer
> 0 votes
# PHP / JavaScript, 43 bytes

```
<body onload=alert(<?=$x*$x.')>'.sqrt($x)?>

```

Input goes like:

```
<?php $x = 10; ?>

```

Kinda self-explaining, but does it fit the rules? My first code golf tho :-)

# Answer
> 0 votes
# CGL (CGL Golfing Language) / JS (ES6), 13 bytes(non-competing)

Non-competing because:

1. CGL was released after this question.
2. ~~CGL is not a valid language.~~ Because of  and , CGL is technically a valid language.

## Code:

```
 x=>x**2
//-₂

```

## JS:

Simple: an anonymous arrow function that returns its first argument squared. The unnamed language code is commented out.

# CGL:

The *non-breaking space* before the first line acts like a comment. The `/`s are no-ops. The `-` in the second line means to decrement the current stack number, which by default is 0. That then sets it to -1, where input is stored. The  replaces the first item in the current stack with its square root, which is now where input is placed. By default, the current stack is outputted, outputting the square root of the input.

# Answer
> 0 votes
# Python 2 and \>\<\> 23 bytes

```
#n*:i
print input()**.5

```

Python: Try it online!

\>\<\>: Try it online!

---
Tags: code-golf, math, polyglot
---