title: Converting "0xUsernames"

text:
# Question
Title: Converting "0xUsernames"
# 0xUsernames

There's so many people using a messaging service that they're running out of space to store all the usernames! To fix this, they are going to start storing usernames as hexadecimal, where possible.

If a username consists of only the characters `0123456789ABCDEF` (case insensitive), it can be converted to a hexadecimal and stored as an integer. For example, the username `ba5eba11` can be interpreted as `0xBA5EBA11`, a hexadecimal integer.

But what about `05AB1E`? That's got a leading zero, which would be lost. So, whenever we convert a username, we make sure to prepend a `1` before reading it as an integer.

---

## The Challenge

Your task is to write a program or function which, given a non-empty username as a string, 'hexa-compresses' the username:

* If it can be interpreted as a hexadecimal integer, prepend a 1, interpret as hexadecimal, and then print the result **as base 10.**
* Otherwise, just return the string unmodified.

This is , so the shortest solution (in bytes) wins! Built-in base conversion functions are permitted.

---

## Test Cases

You can assume that any resulting integers with be within your language's standard integer range.

As with usernames on most messaging systems, the input strings will only contain alphanumerics and underscores.

Remember, you always need to add a leading `1` before conversion!

```
"ba5eba11" -> 7421737489
"05AB1E"   -> 17148702
"dec0de"   -> 31375582
"Beef"     -> 114415
"da7aba5e" -> 7960443486
"500"      -> 5376

"DENNIS" -> "DENNIS"
"Garth"  -> "Garth"
"A_B_C"  -> "A_B_C"
"0x000"  -> "0x000"

```

For reference, here is a Python 3 implementation I used for the test cases (ungolfed):

```
import re

def convert_name(name):
    if re.fullmatch('^[0-9A-Fa-f]+$', name):
        return int('1' + name.upper(), base = 16)
    else:
        return name

```

# Answer
# 05AB1E, 4 bytes

```
D1ìH

```

## Explanation

```
D    Duplicate input
 1ì  Prepend 1
   H Interpret as hexadecimal and implicitly display the value in base 10

```

If the input has invalid hex characters, `H` won't push anything so the last value on the stack will be the duplicated input, that's why the program prints its input in case of invalid input.

Try it online!
> 26 votes

# Answer
# JavaScript (ES6), 15 bytes

```
s=>'0x1'+s-0||s

```

### How it works

`'0x1'+s` converts the input into a literal hexadecimal string with a prepended `1`, e.g. `0x105ab1e`. Then `-0` casts the result to a number. JavaScript sees the `0x` at the beginning and implicitly tries to convert from hexadecimal; if `s` contains any non-hexadecimal chars, this returns `NaN`. Since this is falsy (and output `0` can never be given because of the prepended `1`), we can use `||s` to return `s` if the hex conversion failed.

### Test snippet

```
f = s=>'0x1'+s-0||s

for(i of [
  "ba5eba11", "05AB1E", "dec0de", "Beef", "da7aba5e", "500",
  "DENNIS", "Garth", "A_B_C", "0x000"
]) console.log(i + ":", f(i));
```
> 19 votes

# Answer
# Python 2, 44 bytes

Takes input as a quoted string. -2 bytes thanks to Rod!

```
a=input()
try:exec'a=0x1'+a
except:1
print a

```

As we're guaranteed that the input will only contain alphanumerics and underscores, there's no way to create valid Python after `0x1` other than having a hex string. If the input is anything else, the error is ignored, and printing as it originally was.

I couldn't seem to make a regex match any shorter than `try/except`. In fact, regex turned out to be terribly verbose:

```
import re
lambda n:re.match('^[0-9A-F]+$',n,2)and int('1'+n,16)or n

```
> 10 votes

# Answer
# Perl 6, 19 bytes

```
{:16(1~S/_/Z/)//$_}

```

Test it

## Expanded:

```
{   # bare block lambda with implicit parameter ｢$_｣

    :16(     # convert from base 16
      1
      ~      # Str concatenated
      S/_/Z/ # replace an underscore with an invalid base 16 character
    )

  //         # defined or

    $_       # the input unchanged

}

```
> 8 votes

# Answer
## Perl, 27 bytes

*-1 byte thanks to @ardnew.*

26 bytes of code + `-p` flag.

```
$_=hex"1$_"if!/[^0-9a-f]/i

```

Supply the input *without* final newline. With `echo -n` for instance:

```
echo -n 05AB1E | perl -pe '$_=hex"1$_"if!/[^0-9a-f]/i'

```

**Explanation**
This is pretty straight forward: `/[^0-9a-f]/i` is true if the input contains a character other than those allowed inside hexadecimal numbers. If it's false, `$_` (which contains the input) it is set to the converted value (the conversion is done by the builtin `hex`).
And `$_` is implicitly printed thanks to `-p` flag.
> 7 votes

# Answer
# Pyth \- 9 bytes

```
.xi+1z16z

```

Same idea as fliptack's answer. Try hexadecimal-decimal conversion else output the input.

Try it here!
> 4 votes

# Answer
## Common Lisp, 71

```
(lambda(n)(or(ignore-errors(parse-integer(format()"1~A"n):radix 16))n))

```

## Tests

Define function

```
CL-USER> (lambda(n)(or(ignore-errors(parse-integer(format()"1~A"n):radix 16))n))
#<FUNCTION (LAMBDA (N)) {10041D213B}>

```

Quote a list of expected inputs, as given by the question:

```
CL-USER> '("ba5eba11" -> 7421737489
"05AB1E"   -> 17148702
"dec0de"   -> 31375582
"Beef"     -> 114415
"da7aba5e" -> 7960443486
"500"      -> 5376

"DENNIS" -> "DENNIS"
"Garth"  -> "Garth"
"A_B_C"  -> "A_B_C"
"0x000"  -> "0x000")
("ba5eba11" -> 7421737489 "05AB1E" -> 17148702 "dec0de" -> 31375582 "Beef" ->
 114415 "da7aba5e" -> 7960443486 "500" -> 5376 "DENNIS" -> "DENNIS" "Garth" ->
 "Garth" "A_B_C" -> "A_B_C" "0x000" -> "0x000")

```

Parse it and collect results

```
CL-USER> (loop for (in _ out) on * by #'cdddr
               collect (list in out (funcall ** in)))
(("ba5eba11" 7421737489 7421737489) ("05AB1E" 17148702 17148702)
 ("dec0de" 31375582 31375582) ("Beef" 114415 114415)
 ("da7aba5e" 7960443486 7960443486) ("500" 5376 5376)
 ("DENNIS" "DENNIS" "DENNIS") ("Garth" "Garth" "Garth")
 ("A_B_C" "A_B_C" "A_B_C") ("0x000" "0x000" "0x000"))

```

Check that the expected outputs match the actual ones:

```
CL-USER> (every (lambda (x) (equalp (second x) (third x))) *)
T

```
> 3 votes

# Answer
# Batch, 33 bytes

```
@(cmd/cset/a0x1%1 2>nul)||echo %1

```

## How it works

A string is passed in as an argument, 1 is prepended to it, and the string is implicitly converted to decimal and printed. If the string is not valid hexadecimal, it is simply displayed.

It should be noted that since batch math uses signed 32-bit integers, the biggest allowed username is `FFFFFFF`.

`cmd /c` takes the next command, runs it in a new terminal, and exits.

`set /a` performs math and implicitly displays the result in decimal when not stored to a variable.

`0x1%1` tells set to prepend a 1 to the first argument (this is easy since all batch variables are strings) and indicates that the string should be treated as hexadecimal.

`2>nul` silences any errors resulting from an invalid hexadecimal number

`||` is a logical OR and performs the command on the right if the command on the left is not successful. The parentheses make everything up to this point one command.

`echo %1` simply displays the first argument.
> 3 votes

# Answer
# Python 2 - ~~63~~, ~~52~~, ~~50~~, 46 Bytes

```
n=input()
try:n=int("1"+n,16)
except:1
print n

```

This uses Python's `int()` which converts any string with its appropriate base into base 10. In this case, the string is the number 1 attached to the input. If the input is invalid (has characters other than `0123456789ABCDEF` (case-insensitive), it returns `ValueError`:

```
n = input()                   # Get input (with quotes)
try:                          # Trying conversion to base 10
    n = int("1"+n,16)
except:                       # If invalid string for base 36,
    1                         # do nothing to n
print n                       # Print result

```

Try it here!

Thanks to @FlipTack for saving 15 bytes!
> 2 votes

# Answer
## C, 108 bytes

```
i;f(char*s){char*S=malloc(strlen(s)+2);*S=49;strcpy(S+1,s);sscanf(S,"%x%c",&i,&i)<2?printf("%d",i):puts(s);}

```

This is a function that takes the string as an argument and prints the result to STDOUT.

```
i;                           // declare i as an int
f(char*s){
char*S=malloc(strlen(s)+2);  // allocate space for a new string with 1 more char
*S=49;                       // set the first char to '1' (ASCII 49)
strcpy(S+1,s);               // copy the original string to the remainder
sscanf(S,"%x%c",&i,&i)       // scan a hex integer followed by any char
<2?                          // if less than 2 items were scanned (i.e. the hex
                             // integer made up the entire string),
printf("%d",i)               // output the hex integer
:puts(s);}                   // otherwise, output the original string

```
> 2 votes

# Answer
# JavaScript: ~~46~~ 41 bytes

```
s=>/[^\dA-F]/i.test(s)?s:parseInt(1+s,16)

```
> 2 votes

# Answer
# PHP, 42 bytes

hex2bin() returns false if the input is not a valid hex string. This is shorter than using regex to look for non hex digits, but we need the @ operator because it's not silent when it fails.

```
<?=@hex2bin($s=$argv[1])?hexdec("1$s"):$s;

```
> 2 votes

# Answer
# bash, ~~46~~ ~~35~~ 31 bytes

```
(echo $[0x1$1])2> >(:)||echo $1

```

Save as a script, and pass the username as an argument.
> 2 votes

# Answer
# Dyalog APL, 37 bytes

Uses no built-in validation or hex-dec conversion. Requires `⎕IO←0` which is default on many systems.

```
{∧/(u←1(819⌶)⍵)∊d←⎕D,6↑⎕A:16⊥1,d⍳u⋄⍵}

```

Ungolfed:

```
{
    d ← ⎕D , 6 ↑ ⎕A
    u←1 (819⌶) ⍵
    ∧/ u ∊ d: 16 ⊥ 1 , d ⍳ u
    ⍵
}

```

`d ← ⎕D , 6 ↑ ⎕A`*d* gets **D**igits followed by the first 6 elements of the **A**lphabet

`u ← 1 (819⌶) ⍵`*u* gets uppercased (819 ≈ "Big") argument

`∧/ u ∊ d:` if all elements of *u* are members of *d*, then:
`16 ⊥ 1 , d ⍳ u` find the indices of *u* in *d*, prepend a 1, and evaluate as base 16

else: return the (unmodified) argument

TryAPL online:

1. Set `⎕IO` to zero, define a replacement for  (forbidden on TryAPL for security reasons), and set `⎕PP` (**P**rint **P**recision) to 10 for the large results
2. Try all the test cases
> 2 votes

# Answer
# Ruby, ~~47~~ 44 bytes

```
p gets=~/^[a-f\d]+\s$/i?('1'+$&).to_i(16):$_

```

~~I *could* remove 3 bytes by changing `puts` for `p`, but I feel like the output would be considered wrong since it has a newline at the end.~~

Edit: Changed `puts` for `p` as trailing newlines are typically accepted, thanks @Mego.
> 1 votes

# Answer
# REXX, ~~49~~ 48 bytes

```
signal on syntax
pull a
a=x2d(1||a)
syntax:
say a

```

The `signal on syntax` tells the interpreter to jump to the label `syntax` whenever a syntax error occurs. The program tries to reassign `a` with a hex-to-decimal converted version with a leading 1, but jumps to the `syntax` label if that fails. If the conversion does pass, it simply ignores the label and outputs the reassigned variable.
> 1 votes

# Answer
## Japt, 11 bytes

```
+`0x1{U}`ªU

```

Try it Online!

Big thanks to ETHproductions!
> 1 votes

# Answer
# Vyxal, 8 bytes

```
k6↔=[1pH

```

Try it Online!

```
k6↔      # Remove non-hex chars from input
   =[    # If it equals the original
     1p  # Prepend a 1
       H # Convert from hexadecimal

```
> 1 votes

# Answer
# Whython, 34 bytes

```
lambda n:eval("_"in n or"0x1"+n)?n
```

Attempt This Online!

### Explanation

The `?` operator in Whython returns the value of its left operand, unless the left operand raised an error during execution, in which case it returns the value of its right operand. So in theory, all we have to put on the left is `eval("0x1" + n)`: prepend a `1` and evaluate as a hexadecimal literal.

In practice, since Whython is based on Python 3, we run afoul of the Python 3 feature that underscores can be used as separators in numeric literals. Thus, an input like `A_B_C` does not error, but is treated as if it were `ABC`. That's not what we want. We need to make inputs with underscores cause errors too. Thus, we pass the following to `eval`:

```
"_" in n or "0x1" + n

```

If `n` contains any underscores, `"_" in n` is `True`, the `or` short-circuits, and we're left with `eval(True)`, which errors because `eval` expects a string. If there are no underscores, `"_" in n` is `False`, and we go on to eval the hex-literal string as usual.
> 1 votes

# Answer
# PowerShell, 35 bytes

```
param($v)(($h="0x1$v"|iex),$v)[!$h]

```

Try it online! or **Run all test cases!**

### Explanation

1. Take parameter (`$v`)
2. Create a two-element array where the first element (`0`) is the result of a string containing `0x1$v` piped into `Invoke-Expression` (`iex`), while simultaneously assigning this value to `$h`. If the conversion fails, `$h` will remain `$null`.
3. The second element of the array is the original parameter.
4. Index into the array with the boolean `-not` value of `$h`. Whatever `$h` is will be implicitly converted to `[bool]` (`$null` in the case of an invalid conversion will become `$false`, a positive integer in the case of successful conversion will become `$true`) before being negated, which is then implicitly converted to `[int]` by the array indexer `[]` (`$true` will be `1`, `$false` will be `0`), thus resulting in the first element of the array (the conversion result) chosen if the conversion was successful, and the second element chosen if the conversion was unsuccessful.
> 0 votes

# Answer
# Scala, 40 bytes

```
s=>try{BigInt("1"+s,16)}catch{case e=>s}

```

Usage:

```
val f:(String=>Any)=s=>try{BigInt("1"+s,16)}catch{case e=>s}
f("ba5eba11") //returns 7421737489

```

Explanation:

```
s=>                //define a anonymous function with a parameter called s
  try {              //try...
    BigInt("1"+s,16)   //to contruct a BigInt from "1" prepended to the number, parsing it as base 16
  } catch {          //if the constructor throws an exception
    case e =>          //in case of an execption which we'll call e
      s                  //return s
  }

```
> 0 votes

# Answer
# C#, 58 bytes

```
u=>{try{u=Convert.ToInt64("1"+u,16)+"";}catch{}return u;};

```

Ungolfed with test cases:

```
using System;
class Class
{
    public static void Main()
    {
        Func<string, string> convert =
            u=>
            {
                try
                {
                    u = Convert.ToInt64("1" + u, 16) //Prepends "1" and tries to convert the string to and integer using base 16.
                        + ""; //Appending an empty string converts the integer to a string. Shorter than calling .ToString()
                }
                catch { } //If the conversion fails catch the exception and discard it.
                return u; //Return the result, or the unmodified input if the conversion failed.
            };

        Console.WriteLine(convert("ba5eba11"));
        Console.WriteLine(convert("05AB1E"));
        Console.WriteLine(convert("dec0de"));
        Console.WriteLine(convert("Beef"));
        Console.WriteLine(convert("da7aba5e"));
        Console.WriteLine(convert("500"));
        Console.WriteLine(convert("DENNIS"));
        Console.WriteLine(convert("Garth"));
        Console.WriteLine(convert("A_B_C"));
        Console.WriteLine(convert("0x000"));
        Console.Read();
    }
}

```

Try online
> 0 votes

# Answer
## Dart, 51 bytes

```
(s)=>int.parse('1$s',radix:16,onError:(_)=>null)??s

```

Try it here

Most of the overhead comes from named parameters... Oh well!

At least Dart lets you be dynamically typed, if you want to :D
> 0 votes

# Answer
# 05AB1E, 19 bytes

```
"0x1ÿ".EDн>ΘI'_å~_×

```

Try it online!
> 0 votes

---
Tags: code-golf, string, base-conversion, compression, hexadecimal
---


title: Shrinking numbers

text:
# Question
Title: Shrinking numbers
The input is an array of (at least 3, maximum 20) different integers. Each integer is greater than -1000 and smaller than 1000.

Your task is to shrink the numbers by "linearly mapping" them from `0.0` to `1.0`. This means the smallest number in the array will be mapped to 0.0, the largest to 1.0.

You get the array as a parameter (inside a function) or stdin/program arguments (you can choose). Print out the result in the format `double1;double2;double3;...`. The output **has to have the same order as the input**.

If you want, you can round the output to 2 digits after the decimal point. **There must be atleast 1 digit after the decimal point.**

The **usage of built-in functions** (functions which scale down the numbers for you, such as mathematicas `Rescale`) **is disallowed**.

Examples:

```
Input              Output
[5,-20,30]         0.5;0.0;1.0
[1,2,3,4,5]        0.0;0.25;0.5;0.75;1.0
[0,5,100,400]      0.0;0.01;0.25;1.0

```

(The last output is rounded, otherwise it would be `0.0;0.0125;0.25;1.0`)

# Answer
# CJam, 18 bytes

```
q~_$0=f-_$W=df/';*

```

Note that the online interpreter wrongfully represents `0d` as `0` instead of `0.0`.

### Example run

```
$ cjam shrink.cjam <<< '[5 -20 30]'; echo
0.5;0.0;1.0
$ cjam shrink.cjam <<< '[1 2 3 4 5]'; echo
0.0;0.25;0.5;0.75;1.0
$ cjam shrink.cjam <<< '[0 5 100 400]'; echo
0.0;0.0125;0.25;1.0

```

### How it works

```
q~                    " P := eval(input())         ";
  _$0=                " S := sorted(P)[0]          ";
      f-              " Q := { X - S : X ∊ P }     ";
        _$W=d         " D := double(sorted(Q)[-1]) ";
             f/       " R := { X / D : X ∊ Q }     ";
               ';*    " print(join(R, ';'))        ";

```
> 6 votes

# Answer
## JavaScript, ES6, 81 bytes

Thanks to @edc65 for the `toFixed` trick

```
F=a=>a.map(v=>((v-n)/d).toFixed(2),n=Math.min(...a),d=Math.max(...a)-n).join(';')

```

Run it in latest Firefox Console.

This creates a function `f` which you can invoke like

```
F([5,-20,30])

```
> 5 votes

# Answer
## CJam, ~~24~~ 23 bytes

```
l~_$)\(:M\;-\Mf-\df/';*

```

Input be like:

```
[5 -20 30]

```

Try it online here **Note that online compiler prints `Double 0` as `0` only. Run in the java interpreter which prints correctly.**

How it works:

```
l~                      "Evaluate input and convert each element to double";
  _$                    "Copy the array and sort the copied array";
    )                   "Pop the last element out of the array. This is Max";
     \                  "Swap last two stack elements, bring sorted array on top";
      (:M               "Pop the first element of array and store it in M. This is Min";
         \;             "Bring the remaining of sorted array on top and remove it from stack";
           -\           "Subtract Max and Min and bring the original array to top of stack"
             Mf-        "Push min to stack and subtract it from each array element";
                \df/    "Bring (Double)(Max-Min) to top and divide each array element by it";
                   ';*  "Push the character ; to stack and join the array with it";

```
> 5 votes

# Answer
# Python 2, ~~72 68 63 56~~ 55

Obviously not as concise as other answers, but anyway:

```
x=input()
m=min(x)
print[(i*1.-m)/(max(x)-m)for i in x]

```

Sample run:

```
[1,100,25,8,0]                  #input
[0.01, 1.0, 0.25, 0.08, 0.0]    #output

```

---

Old (68 characters, written in Python 3):

```
x=eval(input())
y=sorted(x)
print([(i-y[0])/(y[-1]-y[0])for i in x])

```
> 5 votes

# Answer
# C# 92

Running inside LinqPad

```
void F(int[]a)
{
   double n=a.Min(),d=a.Max()-n;
   a.Select(x=>((x-n)/d).ToString("0.00")).Dump();
}

```

**Test** in LinqPad

```
void Main()
{
    F(new int[]{5,-20,30});
}
void F(int[]a){double n=a.Min(),d=a.Max()-n;a.Select(x=> ((x-n)/d).ToString("0.00")).Dump();}

```

*Output*

```
IEnumerable<String> (3 items)
0,50
0,00
1,00

```
> 4 votes

# Answer
## APL (15)

```
(2⍕+÷⌈/)(+-⌊/)⎕

```

(or, without trains, also 15 characters:)

```
2⍕V÷⌈/V←V-⌊/V←⎕

```

This reads the argument from the keyboard and prints the result to the screen.

Explanation:

* : read a line from the keyboard and evaluate it
* `+-⌊/`: subtract the lowest item in the array from all items in the array
* `+÷⌈/`: divide each item in the array by the array's highest item
* `2⍕`: format with two decimal places

Test:

```
      (2⍕+÷⌈/)(+-⌊/)⎕
⎕:
     5 ¯20 30
 0.50 0.00 1.00
      (2⍕+÷⌈/)(+-⌊/)⎕
⎕:
      1 2 3 4 5
 0.00 0.25 0.50 0.75 1.00
      (2⍕+÷⌈/)(+-⌊/)⎕
⎕:
      0 5 100 400
 0.00 0.01 0.25 1.00

```
> 4 votes

# Answer
# Pyth, 18

Now with correct formatting!

```
j\;mc-dhSQ-eSQhSQQ

```

**Test:**

```
$ pyth -c 'j\;mc-dhSQ-eSQhSQQ' <<< '[0,5,100,400]'
0.0;0.0125;0.25;1.0

```

**Explanation:**

```
(implicit)              Q = eval(input())
j\;                     ';'.join(
   m                             map(lambda d:
    c                                         float_div(
     -dhSQ                                              d-sorted(Q)[0],
     -eSQhSQ                                            sorted(Q)[-1]-sorted(Q)[0]),
    Q                                         Q))

```
> 4 votes

# Answer
## CJam, ~~30~~ 29 bytes

```
l~:d_{e>}*\_{e<}*:Mf-\M-f/';*

```

Expects the input on STDIN like `[5 -20 30]`.

Test it here. (This will print integer `0` and `1` without decimal point, but the Java interpreter does print `0.0` and `1.0`.)

Due to a bug I can't shorten `{e>}*` to `:e>` although that should be possible as per the spec (which would save 4 bytes when applied to both min and max).

Slightly outdated explanation: (will amend later)

```
l~:d_{e<}*_@_{e>}*@-\@f-\f/';* "Read and eval the input leaving an array of strings on the stack";
l~                             "Read and eval the input leaving an array of strings on the stack";
  :d                           "Convert all elements to double";
    _                          "Duplicate the array";
     {e<}*                     "Wrap the MIN function in a black and fold it onto the array";
          _                    "Duplicate the minimum";
           @                   "Rotate the stack, pulling the array to the top";
            _                  "Duplicate the array";
             {e>}*             "Same as before, now with MAX";
                  @            "Rotate the stack, pulling the minimum to the top";
                   -           "Subtract to give the total range";
                    \          "Swap range and array";
                     @         "Rotate the stack, pulling the other minimum to the top";
                      f-       "Subtract the minimum from each element in the array";
                        \      "Swap range and array";
                         f/    "Divide each element in the array by the range";
                           ';  "Push a semicolon character";
                             * "Riffle the semicolon into the array";

```

At the end of the program, the stack contents are printed by default.

I'm sure there is a way to save half of the stack reshuffling, but I'm not that comfortable with CJam yet.
> 3 votes

# Answer
## APL, 31 characters / 55 bytes

```
{b←⌊/⍵⋄c←(⌈/⍵)-b⋄{2⍕(⍵-b)÷c}¨⍵}

```

Old code without digits after decimal point:

```
{b←⌊/⍵⋄c←(⌈/⍵)-b⋄{(⍵-b)÷c}¨⍵}

```

Take minimum of vector, take difference between maximum and minimum of vector, subtract the minimum from each element and divide by the difference between min and max.

Edited Code to print two digits after the decimal point:
> 3 votes

# Answer
# Octave 25

```
b=min(l);(l-b)/(max(l)-b)

```

Assumes input is in `l` and since it's an interactive shell the result is printed automatically (is this allowed?)
> 3 votes

# Answer
# Xojo, 179 bytes

```
dim x,n as double,k,z as int16,s() as string
n=1e3
x=-n
for each k in a
x=max(x,k)
n=min(n,k)
next
for k=0 to ubound(a)
s.append str((a(k)-n)/(x-n),"0.0#")
next
msgbox join(s,";")

```
> 3 votes

# Answer
## R, 60 bytes

```
m=min(x<-scan());cat(sprintf("%f",(x-m)/(max(x)-m)),sep=";")

```

Formatting eats up a lot of bytes due to `0` and `1` by default are trimmed to display nothing past the integer part.
> 3 votes

# Answer
# Clojure 63

```
(fn[v](let[l(apply min v)](map #(/(- % l)(-(apply max v)l))v)))

```

Doesn't quite follow the rules, since it returns fractions instead of doubles. If that's not acceptable, add 7 bytes

Ungolfed:

```
(fn [values]
    (let [low (apply min values)]
         (map #(/ (- % low)
                  (- (apply max values) low))
              values)))

```

Callable like this:

```
((fn[v](let[l(apply min v)](map #(/(- % l)(-(apply max v)l))v))) [5 -20 30])

```

Output: `(1/2 0 1)`
> 2 votes

# Answer
# Ruby, 49

```
f=->a{$><<a.map{|x|(x-l=a.min).fdiv(a.max-l)}*?;}

```

Explanation:

```
f=->a{}     # Define a lambda that takes one argument a
$><<        # Print the following to STDOUT
a.map{|x|}  # For each element x
(x-l=a.min) # Find the lowest element of a, assign it to l, and subtract it from x
.fdiv       # Float division (/ truncates)
(a.max - l) # Divide by the maximum minus the minimum
*?;         # Convert the resulting array into a string joined by the ';' character

```
> 2 votes

# Answer
# 05AB1E, 13 bytes (Non-competing)

```
ZsWD1.S*+s/Z/

```

Try it online!
> 2 votes

# Answer
## Q (31) IMPROPER OUTPUT FORMAT

```
{(%/)(x;max x)-min x}(.:)(0::)0

```

input

```
1 2 3

```

output

```
0 .5 1

```
> 1 votes

# Answer
# Perl - 60

```
my@a=sort@ARGV;print map{($_-$a[0])/($a[-1]-$a[0])." "}@ARGV

```
> 1 votes

# Answer
# Java 7, 149 bytes

```
float[]c(int[]x){int b=1<<31,a=b-1,j=0,l=x.length;for(int i:x){a=i<a?i:a;b=i>b?i:b;}float[]r=new float[l];for(;j<l;r[j]=x[j++]-a)*1f/(b-a);return r;}

```

**Ungolfed & test code:**

Try it here.

```
import java.util.Arrays;
class M{
  static float[] c(int[] x){
    int b = Integer.MIN_VALUE,
        a = b-1, // In Java, Integer.MIN_VALUE - 1 = Integer.MAX_VALUE (and vice-versa)
        j = 0,
        l = x.length;
    for(int i : x){
      a = i < a ? i : a; // Determine min value of array
      b = i > b ? i : b; // Determine max value of array
    }
    float[] r = new float[l];
    for(; j < l; r[j] = (x[j++] - a) * 1f / (b-a));
    return r;
  }

  public static void main(String[] a){
    System.out.println(Arrays.toString(c(new int[]{ 5, -20, 30 })));
    System.out.println(Arrays.toString(c(new int[]{ 1, 2, 3, 4, 5 })));
    System.out.println(Arrays.toString(c(new int[]{ 0, 5, 100, 400 })));
  }
}

```

**Output:**

```
[0.5, 0.0, 1.0]
[0.0, 0.25, 0.5, 0.75, 1.0]
[0.0, 0.0125, 0.25, 1.0]

```
> 1 votes

# Answer
# Vyxal, 5 bytes

```
g-:G/

```

Try it Online!

Outputs as arbitrary-precision rationals. Look Ma, no Unicode!

```
g-    # Subtract the minimum
  :G  # Make a copy and get the maximum of that
    / # Divide (list - min) by the maximum

```
> 1 votes

# Answer
# Ly, 33 bytes

```
&n&sr>las<l/uy[';ofl/0L[!f!]pu,];

```

Try it online!

This is pretty direct translation of the requirements, but there are two things which add code I wanted to avoid... First, since `0` is a valid number in the list, the code has to explicitly add (and manipulate) a loop iterator on the stack. And second, since the rules imply that negative numbers should produce a `0` output, there's some extra code for that. If `-0.0` is an acceptable output, the code could be a few bytes shorter. :)

```
&n&sr                             (1) read input and prep for processing
&n     - read STDIN onto the stack
  &s   - save a copy of the stack
    r  - reverse the stack

     >las<                        (2) find/stash the largest input number
>       - switch to an empty stack
 l      - restore a copy of the input list
  a     - sort the stack
   s    - save the top of stack (largest number) to backup cell
    <   - switch back to the stack with the original input

          l/uy                    (3) print first entry, prep for loop
 l     - load the largest number from the backup cell
  /    - divide to get the 0-1 scaled number
   u   - print as a number
    y  - push the stack size onto the stack

              [';ofl/0L[!f!]pu,]; (4) process 2-N list entries
 [                ]   - loop through all the list entries
  ';o                 - print the ";" field separator
     f                - flip the iterator and next list entry on stack
      l               - load the largest number on the input
       /              - divide to get the 0-1 ratio
        0L            - compare result against 0, looking for "<0"
          [   ]p      - if/then structure, true if result <0
           !f!        - true: make top two stack entries "0"
                u     - print ratio (or "0" if result was <0)
                 ,    - decrement iterator
                   ;  - exit program to avoid print extraneous "0"

```

If `-0.0` is an acceptable output, this 4 bytes shorter version could be used.

```
 &n&sr>las<l/uy[';ofl/0L!*u,];

```
> 1 votes

---
Tags: code-golf, number
---


title: Determine if a dot(comma) program halts

text:
# Question
Title: Determine if a dot(comma) program halts
Dotcomma is a simple esolang I made a while ago that only uses four operators: `[.,]`. In this challenge, you'll determine if a dotcomma program consisting only of `[.]` halts. Without `,`, there is no input, output, or queue, making this challenge possible.

**Blocks:**

Any code wrapped in `[]` is a block. All blocks and operators (`.`) have a return value. The inputted program will always consist of a single block, and the brackets will always be properly nested.

**Operators:**

The `.` operator's return value depends on what it is preceded by:

* **Any number of blocks:** The sum of the blocks' return values
* **A dot:** The previous `.`'s return value will be kept
* **The beginning of a block (`[`):** `1`

If a `.` is followed by a block, it will be treated as a loop. The loop will run only if the `.`s return value is not `0`, and if the block being looped returns `0` at any point it will terminate.

If a `.` is followed by the end of a block (`]`), the `.`'s return value will be used as the block's. Otherwise, a block's return value is `0`.

**Examples:**

```
[]

```

Returns `true`. There are no loops.

```
[[].[]]

```

Returns `true`. The `.` takes the return value of the first nested block, which is `0`, skipping the second.

```
[.[]]

```

Returns `true`. The `.` returns `1`, but the loop terminates immediately as the block returns `0`.

```
[.[.]]

```

Returns `false`. The `.` returns `1`, and the block being looped returns `1`, creating an infinite loop.

```
[[.][].[.]]

```

Returns `false`. The `[.]` returns `1`, which is added to the `0` returned by the `[]`, resulting in `1` and causing the loop body to be run.

**Other:**

You may return a truthy/falsy value in your language (representing either whether it halts or does not, your choice), or two consistent values for halting and non-halting.

This is . Shortest answer in bytes (per language) wins.

# Answer
> 6 votes
# Python 3, 215 bytes

```
m,v,*d=-1,[],
L,*l=0,
for c in input():
	if c>"[":a=v.pop();l.pop()*a and exit(1);d.pop();d or exit(0);v[m]=v[m]*(d[m]%2)+a;d[m]=1
	elif c>"Z":l+=[L and v[m]];v+=0,;d+=0,
	else:v[m]=v[m]if d[m]else 1;d[m]=2
	L=c<"A"

```

Try it online!

Exit code 0 if it will halt, 1 otherwise.

This is just a naive implementation of the interpreter, but golfed down. Here's a ungolfed version with debug output.

+12 bytes to fix a bug
-8 bytes thanks to Unrelated String

# Answer
> 1 votes
# 05AB1E, 37 bytes

```
„[.Å?·.$Δ„..¤:„[]0:…[.]1:DS„0.ìK}„1]å

```

Outputs `0` if it halts; `1` if it does not halt.

I'm not 100% sure if my approach is correct. It does work for all test cases, including those mentioned in the comments of the challenge and the Python answer. If there is any test case it'll fail for, I'll delete and try to fix it.

Try it online or verify all test cases. (NOTE: Wrap the input of the singular TIO in `"""` quotes, otherwise it'll interpret the input as a list and gives an error.)

**Explanation:**

```
          # If the input starts with "[.", remove it:
„[.Å?     #  Check if the (implicit) input-string starts with "[."
     ·    #  Double this (0 if falsey; 2 if truthy)
      .$  #  Remove that many leading characters from the (implicit) input
Δ         # Keep doing the following until the result no longer changes:
          #  Collapse all multiple adjacent "." to a single ".":
 „..      #   Push string ".."
    ¤     #   Push its last character (without popping): "."
     :    #   Keep replacing all ".." to "." until none are left
 „[]0:    #  Replace all "[]" with a 0
 …[.]1:   #  Replace all "[.]" with a 1
          #  Remove all "0.x" substrings, where `x` can be any character
 D        #   Duplicate the string
  S       #   Convert it to a list of characters
   „0.ì   #   Prepend a "0." in front of each
       K  #   Remove all those substrings from the string
}„1]å     # After the loop: check if the string contains "1]"
          # (after which the result is output implicitly)

```

I could also add an additional remove of all `"1."` within the loop, and then check if the final result contains a `1`, but just checking if it contains a `"1]"` is shorter.

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


title: Count count count

text:
# Question
Title: Count count count
**Description**

You have a list of integers and start counting from the first term to the next and continue from that to the next and so on..
How many times have you counted?

For example given \[ 2, 5, 3, 8 \]
you start at 2 and count to 5 -\> *3 4 5* (3 times)
then from 5.. *4 3* (2 times)
and finally *4 5 6 7 8* (5 times)
You counted 10 times.

With ragged lists, when you have a sublist just count the sublist and use that result.

for example \[ 1, \[ 3, 6 \] \]
1 to ( count\[ 3, 6 \] -\>3 )
1 to 3 -\> 2

For empty lists you count 0 times, the same applies for lists of one element or lists of equal elements.
\[ \] -\> 0
\[ 99 \] -\> 0
\[ 8, 8, 8 \] -\> 0

**Task**
Given a ragged list of non negative integers count it as described above.

**Test cases**

```
[] -> 0
[[2,5]] -> 0
[99] -> 0
[8,8,8] -> 0
[1,1] -> 0
[0,9] -> 9
[2,5,3,8] -> 10
[1,[3,6]] -> 2
[[],4,[[5,3],2]] -> 8
[100,100,[7,[[[6]]]],[[4,8]]] -> 100
[[9,5],0] -> 4
[[],[]] -> 0
[[],3,[]] -> 6
[1,[2,5,10]] -> 7
[2,6,9] -> 7
[[1,2],[1,3],[1,4]] -> 2
[1,99] -> 98
[11,9,6] -> 5
[0,1,2,3,4] -> 4
[2,3,3,3,2] -> 2
[0,1,0,1] -> 3

```

This is , all usual golfing rules apply.

# Answer
# Haskell \+ free, 36 bytes

```
iter$sum.map abs.(zipWith(-)<*>tail)

```

Try it online!

To represent a ragged list we use a free monad. Then this process is just iteration. Our iterative step is `sum.map abs.(zipWith(-)<*>tail)` which calculates the absolute differences and then sums them.
> 6 votes

# Answer
# Vyxal, 9 bytes

```
λIȧ[vx¯ȧ∑

```

Try it Online!

-1 thanks to lyxal.

Or if we can assume no empty lists, 8 bytes:

```
λ-[vx¯ȧ∑

```

Try it Online!

Both are essentially the same, just with different `is_array` checks.

```
λ          # Create a recursive lambda...
  - [      # If the input is a list...
  -        # int - int = 0 (falsy), lst - lst = list of zeros, truthy
 Iȧ        # If n is int, remove_whitespace(" " * n) which is falsy.
           # If n is list, split into two halves and take the absolute value.
     vx    # Call the lambda on each element of the list
       ¯   # Get differences between pairs of elements
        ȧ  # Take the absolute value of those
         ∑ # Sum

```
> 5 votes

# Answer
# Jelly, ~~11~~ 10 bytes

```
ß€IASƲ⁸ŒḊ?

```

Try it online!

## Walkthrough

```
         ?   If
       ŒḊ    Depth (of input) != 0?
 €                Foreach
ß                     call this link
  I               consecutive differences
   A              Absolute of each
    SƲ           sum
      ⁸      If == 0? return the link argument

```
> 5 votes

# Answer
# , ~~87~~ 86 bytes

*Edit: -1 byte thanks to pajonk*

```
f=function(l,`+`=sapply)`if`(length(m<-l+is.list),{l[m]=l[m]+f;sum(abs(diff(l+c)))},0)

```

Try it online!

**Ungolfed**

```
f=function(l){                  # argument = l = ragged list
  m=sapply(l,is.list)           # m = elements of l that themselves are lists
  if(length(l)){                # if l isn't an empty list
    l[m]=sapply(l[m],f)         #   replace its list elements by recursive call
    sum(abs(diff(unlist(l)))    #   and now count from each to the next and so on
  } else 0                      # otherwise ( it's an empty list ) return zero.

```

Note: we use `sapply` twice above, so to save bytes we re-assign the `+` infix operator as `sapply`. Once we've done that, we might as well use it wherever we can: `unlist()` is a bit long, so instead we can `sapply` the identity function `c()` to all elements of a list, to get them unlisted: hence `l+c` instead of `unlist(l)`....
> 5 votes

# Answer
# Python, 68 bytes

```
f=lambda x:sum(abs(f(j)-f(k))for j,k in zip(x,x[1:]))if 0!=x*0else x

```

Try it online!
> 4 votes

# Answer
# Wolfram Language (Mathematica), 33 bytes (@att)

```
Tr@Abs@Differences@{##}&@@#&//@#&

```

Try it online!

---

## Wolfram Language (Mathematica), 35 bytes

```
Map[Tr@*Abs@*Differences,#,{0,-2}]&

```

Try it online!

---

## Wolfram Language (Mathematica), 35 bytes

```
#/.x:List->Tr@*Abs@*Differences@*x&

```

Try it online!
> 4 votes

# Answer
# Retina 0.8.2, 72 bytes

```
\d+
$*
\[
<;
{`(<1*);(1*)(1*),\2(1*)(,|])
$1$3$4;$2$4$5
}`<(1*);1*]
$1
1

```

Try it online! Link includes test cases. Explanation:

```
\d+
$*

```

Convert to unary.

```
\[
<;

```

Place markers at the start of each sublist.

```
{`
}`

```

Repeat until no more replacements can be made.

```
(<1*);(1*)(1*),\2(1*)(,|])
$1$3$4;$2$4$5

```

If a sublist starts with two integers, then remove the first and insert the difference before the marker, which tracks the cumulative absolute total.

```
<(1*);1*]
$1

```

When a sublist runs out of integers then simply replace it with its total.

```
1

```

Convert to decimal.
> 3 votes

# Answer
# JavaScript, ~~60~~ 52 bytes

```
f=(a,t=0)=>p=a.map?.(p=x=>t+=Math.abs(p-f(x)|0))?t:a

```

```
f=(a,t=0)=>p=a.map?.(p=x=>t+=Math.abs(p-f(x)|0))?t:a

console.log(f([]))
console.log(f([[2,5]]))
console.log(f([99]))
console.log(f([8,8,8]))
console.log(f([1,1]))
console.log(f([0,9]))
console.log(f([2,5,3,8]))
console.log(f([1,[3,6]]))
```

*Saved 8 bytes thanks to tsh.*
> 3 votes

# Answer
# Charcoal, 56 bytes

```
⊞υθＦυＦιＦ⁼κ⁺⟦⟧κ⊞υκＷυ«≔⊟υι≔⟦⟧ηＷι⊞ηΣ⁺⟦⁰⟧⊟ι⊞ι↨ＥΦηλ↔⁻κ§ηλ¹»Ｉθ

```

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

```
⊞υθＦυ

```

Start extracting all of the sublists.

```
ＦιＦ⁼κ⁺⟦⟧κ⊞υκ

```

Loop over all the lists and when a sublist is found then push it to the predefined empty list.

```
Ｗυ«

```

Process all of the sublists.

```
≔⊟υι

```

Get the deepest remaining sublist.

```
≔⟦⟧η

```

Start collecting the terms in this sublist.

```
Ｗι⊞ηΣ⁺⟦⁰⟧⊟ι

```

Remove the terms from the list and push their numeric value to the temporary list. Any sublists will have been reduced to their count as a single term `[n]` at this point, so prepending `[0]` results in `[0, n]` and taking the sum returns `n`, while adding `[0]` to an integer `n` results in `[n]` and then taking the sum returns `n` again.

```
⊞ι↨ＥΦηλ↔⁻κ§ηλ¹

```

Compute the absolute pairwise differences and push the total to the list.

```
»Ｉθ

```

Output the final total of the original list.
> 3 votes

# Answer
# SWI-Prolog, ~~123~~ 105 bytes

```
[]+0.
[_]+0.
[H,S|T]+C:-(is_list(H)->H+G;G is H),(is_list(S)->S+Q;Q is S),D is abs(Q-G),[S|T]+R,C is D+R.

```

*-18 bytes thanks to Wheat Wizard!*

Try it online!
> 3 votes

# Answer
# Ruby, 75 bytes

```
f=->a{a*0==0?a:([a[0]]*(a.size%2)+a).map(&f).each_cons(2).sum{(_2-_1).abs}}
```

Attempt This Online!
> 1 votes

# Answer
# 05AB1E, 21 bytes

```
"Ð˜Êi®δ.V}Ð˜Qi¥ÄO"©.V

```

Ugh.. :/

Try it online or verify all test cases.

**Explanation:**

```
"..."        # Define the recursive string below
     ©       # Store it in variable `®` (without popping)
      .V     # Evaluate and execute it as 05AB1E code, using the (implicit)
             # input-list as argument
             # (after which the result is output implicitly)

Ð˜Ê          #  Check if there is an inner list:
Ð            #   Triplicate the current list
 ˜           #   Flatten it
  Ê          #   Check if the top two lists are NOT the same
   i         #  If this is truthy:
     δ       #   Map over each inner item:
    ® .V     #    Do a recursive call
   }         #  After the if-statement, whether we executed its body or not:
    Ð˜Q      #  Check if this is a 1D list:
    Ð        #   Triplicate the current list
     ˜       #   Flatten it
      Q      #   Check if the top two lists are equal
       i     #  If this is truthy:
        ¥    #   Pop the list, and push its deltas/forward-differences
         Ä   #   Convert each to its absolute value
          O  #   And then sum this list

```
> 1 votes

# Answer
# Python NumPy, 69 bytes

```
f=lambda s:sum(abs(s*-1or diff([*map(f,s or[])])))
from numpy import*
```

Attempt This Online!

I suspect it's 66 bytes in Python2 but have no way of checking.
> 1 votes

# Answer
# Perl 5, 88 bytes

```
sub f{$_=pop;1while s!\[[\d,]*\]!@a=$&=~/\d+/g;0+sum map abs$a[$_-1]-$a[$_],1..$#a!e;$_}

```

Try it online!
> 1 votes

---
Tags: code-golf, counting, ragged-list
---


title: Lists of power!

text:
# Question
Title: Lists of power!
Generate the following list of lists consisting of the unique last digits of the powers from 1 to 9 for the numbers \[0..9\]

```
[[0], [1], [2, 4, 8, 6], [3, 9, 7, 1], [4, 6], [5], [6], [7, 9, 3, 1], [8, 4, 2, 6], [9, 1]]

```

e.g. For the number 2 we have: \\$2^1,2^2,2^3,2^4,2^5,... \to 2,4,8,16,32,64,128,... \to 2,4,8,6,4,8,... \to \[2,4,8,6\]\\$

This is , so shortest answer (as measured in bytes) wins and the usual golfing rules apply.

# Answer
> 1 votes
# Lua, 71 bytes

```
for i=0,9 do u=i a=i while a*i%10~=i do a=a*i%10 u=u..a end print(u)end

```

Try it online!

Since you aren't specific about if you need a table/array or only printed results, I present my answer with printed results:

```
0
1
2486
3971
46
5
6
7931
8426
91

```

# Answer
> 1 votes
# JavaScript, ~~71~~ ~~69~~ 67 bytes

Thanks to user81655 and tsh for reducing two bytes each

```
(a=[...'0123456789']).map(v=>[...new Set(a.map(x=>+x?v**x%10:+v))])

```

```
console.log(
(a=[...'0123456789']).map(v=>[...new Set(a.map(x=>+x?v**x%10:+v))])
)
```

# Answer
> 1 votes
# CoffeeScript, 46 bytes

It was not specified whether a set can be considered a list, so this outputs a list of sets:

```
(new Set(v**x%10for x in[1..9])for v in[0..9])

```

Outputting a list of arrays would require **57 bytes**:

```
(Array.from new Set(v**x%10for x in[1..9])for v in[0..9])

```

# Answer
> 1 votes
# 05AB1E, 10 bytes

```
TFN4Lm€θÙ,

```

Try it online!

# Answer
> 1 votes
# JavaScript (Node.js), 61 bytes

```
f=t=>t>9?[]:[(g=x=>[x|0,...x%5>1?g(x*t%10):[]])(t),...f(-~t)]

```

Try it online!

---

# JavaScript (Node.js), 62 bytes

```
_=>[...'0123456789'].map(g=(t,x)=>[x,...x%5>1?g(t,x*t%10):[]])

```

Try it online!

---

# JavaScript (Node.js), 64 bytes

```
_=>Array(10).fill(1).map(g=(x,t)=>[x=x*t%10,...x%5>1?g(x,t):[]])

```

Try it online!

# Answer
> 0 votes
# JavaScript, ~~98~~ 90 bytes

```
_=>{r=[];for(i=-1;++i<=9;){for(c=[],p=1;c[0]!=(a=(p*=i)%10);c.push(a));r.push(c)}return r}

```

Try it online!

# Answer
> 0 votes
# Wolfram Language (Mathematica), 50 bytes

```
DeleteDuplicates/@Array[Mod[(#-1)^#2,a]&,{a=10,a}]

```

Try it online!

# Answer
> 0 votes
# Charcoal, 17 bytes

```
Ｉ﹪ＥχＸιＩ…1§22553ιχ

```

Try it online! Link is to verbose version of code. Outputs each list element on its own line with lists double-spaced. Explanation:

```
   χ                Predefined variable 10
  Ｅ                 Map over implicit range
     ι              Current value
    Ｘ               Vectorised to power
       …            Range from
        1           Literal string `1` to
          22553     Literal string `22553`
         §          Cyclically indexed by
               ι    Current value
      Ｉ             Cast to integer
 ﹪                  Vectorised modulo by
                χ   Predefined variable 10
Ｉ                   Cast to string
                    Implicitly print

```

# Answer
> 0 votes
# Python 3, 55 bytes

```
R=range(10);print([[*{a**-~i%10for i in R}]for a in R])

```

Try it online!

# Answer
> 0 votes
# Haskell, 71 bytes

```
l|d<-[1..9]=[foldl(\a x->a++[x|notElem x a])[][x^p`mod`10|p<-d]|x<-0:d]

```

Try it online!

# Answer
> 0 votes
# Retina, 57 bytes

```

9*¶

$.`
.
$& $.(**) $.(***) $.(****
.\B

(.+?)( \1)+
$1

```

Try it online! Explanation:

```

9*¶

$.`

```

List the digits from `0` to `9`.

```
.
$& $.(**) $.(***) $.(****

```

Calculate the first four powers of each digit.

```
.\B

```

Take the last digit of each power.

```
(.+?)( \1)+
$1

```

Remove duplicates.

# Answer
> 0 votes
# Deadfish~, 549 bytes

```
{{i}d}icc{dddd}dddc{iiii}iiiiic{ddddd}ic{iiiii}dddc{dddd}ddc{iiii}iiiic{ddddd}ic{iiiii}dddc{dddd}dcddddddc{i}ddc{d}iic{i}iic{d}ddc{i}c{iiii}dc{ddddd}ic{iiiii}dddc{dddd}c{d}iiic{i}iiic{d}dddc{i}ic{d}dciiiiic{iiii}iiiic{ddddd}ic{iiiii}dddc{dddd}ic{d}iic{i}c{iiii}dc{ddddd}ic{iiiii}dddc{dddd}iic{iiii}c{ddddd}ic{iiiii}dddc{dddd}iiic{iiii}dc{ddddd}ic{iiiii}dddc{ddd}ddddddc{d}dc{i}iiic{d}dddc{i}dddc{d}iiiciiiiic{iiii}iiiic{ddddd}ic{iiiii}dddc{ddd}dddddc{d}ddc{i}ddc{d}iiciiiiiicddddddc{i}c{iiii}dc{ddddd}ic{iiiii}dddc{ddd}ddddc{d}dddciiiiic{iiii}iiiicc

```

Try it online!

# Answer
> 0 votes
# Vyxal, 10 bytes

```
9ʀƛn9ɾevtU

```

Try it Online!

# Answer
> 0 votes
# Kotlin, ~~134 122~~ 112 bytes

// this codegolf link specifies that lambda names could be ignored in calculating the bytes

```
var listOfPower =

```

```
{n:Int->List(9){n}.mapIndexed{index,_->(1f*n).pow(index).toInt()}.map{"$it".last().digitToInt()}.distinctBy{it}}

```

Try it online!

~~```
{n:Int->List(9){n}.mapIndexed{index,_->(1f*n).pow(index).toInt()}.distinctBy{"$it".last()}.map{"$it".last().digitToInt()}}

```
Try it online!<br>```
{n:Int->List(9){n}.mapIndexed{index,_->(1f*n).pow(index)}.distinctBy{"${it.toInt()}".last()}.map{"${it.toInt()}".last().digitToInt()}}

```~~

~~Try it online!~~

#### Ungolfed:

```
    var listOfPower =
    {n:Int->List(9){n}.
    mapIndexed{index,_->(1f*n).pow(index).toInt()}.
    map{"$it".last().digitToInt()}.
    distinctBy{it}}

```

create an array of size 9, set all of them to n,

set every single one to their power to their index, convert to int

remove duplicates by getting their last digit

create a list that holds in their last digits and return it

# Answer
> -3 votes
# Pyth, 10 bytes

```
m.ue*Ndd)T

```

Try it here!

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


title: Wordsearch Solver

text:
# Question
Title: Wordsearch Solver
Given a list of words and a grid of letters, find all the words in the grid and remove any letters which are not part of any of the words. The words could be forwards, backwards, up, down or diagonal. You may assume that no word in the list will occur in more than one place in the grid.

Input will always be: a list of words, 1 per line, followed by a blank line, followed by the grid of letters.

## Examples

**Input**

```
ADA
ALGOL
ASSEMBLY
BASIC
COBOL
DELPHI
FORTRAN
JAVA
LABVIEW
LOGO
PASCAL
PERL
PHP
PYTHON
SMALLTALK
VISUALC

LLJKCABLFCI
OROLOBOCOIM
GELACSAPRSX
LPSTAHWVTAV
ANRLXLXQRBI
IHPLEDOXAHS
KJYAPHPYNOU
FABMADANZJA
EVISNOHTYPL
AAYLBMESSAC
WEIVBALOGOM

```

**Output**

```
LL K    FC
OR LOBOCOI
GELACSAPRS
LP T    TAV
A  L    RBI
IHPLED  A S
 J APHP N U
 A MADA   A
 V SNOHTYPL
 AYLBMESSAC
WEIVBALOGO

```

**Input**

```
BACKSPACE
BOLD
CLOSE
COMPACTDISC
COPY
CPU
CURSOR
DELETE
DESKTOP
DVD
EDIT
ENTER
EXIT
FLOPPY
FONT
HARDWARE
INTERNET
KEYBOARD
MONITOR
MOUSE
PASSWORD
PASTE
RETURN
SAVE
SOFTWARE
START
TEXT
TOWER
WORDPROCESSING

IAUERAWTFOSICPN
DGZPFLOPPYARFLU
RSNOCURSORVZDBM
AMNIUOMRNHEGUIN
OTBNSRMONITORNT
BEYTTSGPJBOLDRT
YRQEAHEHARDWARE
EOGRRNECECLOSEP
KIONTYKTODTOWER
ELCENSUPERPDKNN
ATRTPRYKELPVIEJ
GIEANPOTKSEDUSL
NXCMPASSWORDRUC
TEDITAGVSWJCTOV
CWOYPGYQKNLVXMW

```

**Output**

```
  UERAWTFOS
DG PFLOPPYA
R NOCURSORV
A NI O    E
OT NS MONITOR
B  TTS P BOLD
Y  EA EHARDWARE
E  RRNECECLOSE
K  NT KTO TOWER
   E SUPER D
 TRTPRY ELPVIE
 IEANPOTKSED S
 XC PASSWORDRUC
TEDITA       O
    P        MW

```

This is code-golf - shortest solution wins.

Example wordsearches from  and .

# Answer
> 3 votes
# 05AB1E, 87 (or 83?) bytes

```
||UεVX8FD»YåiY1:AuSð:1Y:}D€g©ËiεSÐ0:«NFÁ}}øíJ0δKõKë®à©FD®£€нJRsεN®‹i¦}}¦}\)]€Søε{θ}J®ä»

```

With the actual I/O as mentioned in the challenge description.

Try it online. (For some reason, the `Á` is very slow on an inner list of characters instead of a string in this program, so `εSÐ0:«NFÁ}}` has been replaced with `εÐS0:«NFÁ}S}` (rotate first; then convert it to a list of characters) to speed things up substantially - it'll now output on TIO in roughly a second, instead of timing out without any output after 60 seconds.)

With less strict I/O (first words-input as a list, second grid-input as a list of lines; output-grid as a list of lines as well), this would be **83 bytes** instead:

```
εVI8FD»YåiY1:AuSð:1Y:}D€g©ËiεSÐ0:«NFÁ}}øíJ0δKõKë®à©FD®£€нJRsεN®‹i¦}}¦}\)]€Søε{θ}J®ä

```

Try it online (with the same modification as above so it won't time out).

**Explanation:**

In pseudo-code, I do the following steps:

```
Map over the list of words:
 Push the input-grid
 Loop 8 times:
  If the word is present horizontally left-to-right:
   Replace everything else with a space
  Rotate the grid 45 degrees counterclockwise
Reduce/combine all grids of spaces and words

```

As for the actual code, of which most (50 bytes) is used to rotate the grid 45 degrees:

```
|                      # Get all inputs until an empty line is encountered,
                       # resulting in the list of words
 |                     # Do it again, resulting in the grid
  U                    # Pop and store the grid in variable `X`
 ε                     # Map over each of the words:
  V                    #  Pop and store the word in variable `Y`
  X                    #  Push grid `X`
   8F                  #  Loop 8 times:
     D»Yå              #   Check if the word is in the grid:
     D                 #    Duplicate the grid
      »                #    Join the lines with newline delimiter
       Yå              #    Check that this contains the word `Y`
         i             #   If this is truthy:
          Y1:          #    Replace the word temporarily with a 1
          AuSð:        #    Replace all uppercase letters with a space
          1Y:          #    Replace the 1 back to the word
         }             #   Close the if-statement
     D€g©ËiεSÐ0:«NFÁ}}øíJ0δKõKë®à©FD®£€нJRsεN®‹i¦}}¦}\)
                       #   Rotate the grid 45 degrees counterclockwise:
     D€g©Ë             #    Check if the grid is a rectangle:
     D                 #     Duplicate the grid
      €g               #     Get the length of each row
        ©              #     Save this list of lengths in variable `®` (without popping)
         Ë             #     Check whether these lengths are all equal
          i            #    If this is truthy:
           ε           #     Map over each row:
            S          #      Convert it to a list of characters
             Ð0:«      #      Append the row-length amount of 0s to the row
             Ð         #       Triplicate the row
              0:       #       Pop two, and replace all characters to 0s
                «      #       Merge this list of 0s to the row
             NF        #      Loop the 0-based map-index amount of times:
               Á       #       Rotate the row once towards the right
             }         #      Close the loop
           }           #     Close the map
            øí         #     Now rotate 90 degrees clockwise:
            ø          #      Zip/transpose; swapping rows/columns
             í         #      Reverse each row
              J        #     Join the inner list of characters back to a string
                δ      #     Map over each row:
               0 K     #      Remove all 0s from the row
                  õK   #     Remove any empty rows
          ë            #    Else (it's a diamond-shape instead):
           ®           #     Push the list of lengths
            à          #     Pop and push its maximum
             ©         #     Store this maximum as new variable `®` (without popping)
              F        #     Loop this maximum amount of times:
               D       #      Duplicate the list
                ®£     #      Only leave the first max amount of values
                  €н   #      Only leave the first character of each row
                    J  #      Join these characters together to a string
                     R #      Reverse it
               s       #      Swap so the list is at the top again
                ε      #      Map over each row:
                 N®‹i  #       If the map-index is smaller than max `®`:
                     ¦ #        Remove the first character
                    }  #       Close the if-statement
                }      #      Close the map
                 ¦     #      Remove the first (now empty) row
              }        #     Close the loop
               \       #     Discard the now empty list
                )      #     Wrap all rows on the stack into a list
 ]                     # Close the open if-statement; loop; and map
                       # (we now have a list space-grids, except for the found words)
  €S                   # Convert each inner grid to a flattened list of characters
    ø                  # Zip/transpose; swapping rows/columns
     ε                 # Map over each inner list:
      {                #  Sort; spaces at the front, potential letter(s) at the end
       θ               #  Pop and leave the last character
     }                 # Close the map
      J                # Join everything together to one huge string
       ®               # Push the last maximum `®`
        ä              # Split the string into that many equal-sized parts
         »             # Join the list of rows with newline delimiter
                       # (after which it is output implicitly as result)

```

# Answer
> 6 votes
## Perl - 230 chars

Count includes 4 for "-ln " command-line options.

```
if(1../^$/){push@w,$_,''.reverse if$_}else{$a.="$_\n"}END{$_=$a;/.+/;$W=$+[0];y/A-Z/ /;chomp;for$w(@w){for$n(0,$W-1..$W+1){$r=join".{$n}",map"($_)",(@l=split//,$w);if($i=$a=~/$r/s){substr($_,$-[$i++],1,shift@l)while@l}}}print}

```

Ungolfed:

```
# -n: implicitly loop over input lines
# -l: strip the newlines
if ( 1 .. /^$/ ) {              # from first line to empty line
  push @w,                      # record in @w
    $_,                         #   the word
      ''.reverse                #   and its reverse
        if $_                   #   if it's not the empty line
}
else {
  $a .= "$_\n"                  # otherwise, add to the search array
}

END {
  $_ = $a;                      # make a copy for the output
  /.+/; $W = $+[0];             # compute array width
  y/A-Z/ /;                     # blank the output board
  chomp;                        # and remove the trailing newline,
                                #  because -l will add it back for us
  for $w (@w) {                 # for each word
    for $n (0, $W-1 .. $W+1) {  # for each direction in E, SW, S, SE
      $r = join ".{$n}",        # form a regexp with an appropriate
                                #  number of characters skipped between letters
                                #  (0 -> adjacent, so E; $W -> next line, so S;
                                #   off by one from $W for the diagonals),
        map "($_)",             #  capturing the letters of the word (for their offsets),
          (@l=split//,$w);      #  which we split up here
      if ( $i = $a =~ /$r/s ) { # if the word matches in this orientation
        substr( $_,             # set the substring of the output
                $-[$i++],       #  at the offset this letter matched
                1,              #  length 1
                shift @l )      #  to the corresponding letter
          while @l              #  (for each letter)
      }
    }
  }
  print                         # and print the output
}

```

# Answer
> 4 votes
## Ruby 1.9, 214 210 206 182 177 173 172 166

```
s,G=$<.read.split$/*2
O=G.tr'^
',' '
(s+$/+s.reverse).split.map{|w|[0,l=G=~/$/,l+1,l-1].map{|d|(k=G=~/#{[*w.chars].*?.*d}/m)&&w.size.times{|i|O[k+d*i+i]=w[i]}}}
$><<O

```

# Answer
> 3 votes
**JavaScript:** 342 characters

Code-Golfed version:

```
function a(b){c='\n';d=b.split(c+c);e=d[1].split(c);for(f=-1,g=[];h=e[++f];)for(i=-1,g[f]=[];h[++i];)for(j=-2,g[f][i]=' ';2>++j;)for(l=-2;2>++l;)for(k=0;m=d[0].split(c)[k++];)for(n=-1;o=m[++n];)for(p=f-n*j-j,q=i-n*l-l,r=0;(s=m[r++])&&(t=e[p+=j])&&(u=t[q+=l])&&s==u;)if(r==m.length)g[f][i]=o;for(i=0;v=g[i];)g[i++]=v.join('');return g.join(c)}

```

Formatted version:

```
function solveWordsearch(input){
    var lineBreak = '\n';
    var solver = input.split(lineBreak+lineBreak);
    var board = solver[1].split(lineBreak);

    for(row=-1,output=[]; line=board[++row];){
        for(col=-1,output[row]=[]; line[++col];){
            for(rowIncrement=-2,output[row][col]=' ';2>++rowIncrement;){
                for(colIncrement=-2;2>++colIncrement;){
                    for(k=0; word=solver[0].split(lineBreak)[k++];){
                        for(charPosition=-1; wordChar=word[++charPosition];){
                            var startRowIndex=row-charPosition*rowIncrement-rowIncrement;
                            var startColIndex=col-charPosition*colIncrement-colIncrement;
                            for(wordIndex=0;(compareWordChar=word[wordIndex++])&&(compareBoardRow=board[startRowIndex+=rowIncrement])&&(compareBoardChar=compareBoardRow[startColIndex+=colIncrement])&&compareWordChar==compareBoardChar;){
                                if(wordIndex == word.length){
                                    output[row][col]=wordChar;
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    for(i=0;outLine=output[i];){
        output[i++]=outLine.join('');
    }

    return output.join('\n');
}

```

The concept behind this solution is to iterate over all positions on the board, initialize a 2D-array's values to ' ' for each position, and then consider all potential word directions and word offsets. If a matching word is found, the array's value for that position is updated to the correct letter. Finally, the array is converted to a string and returned.

# Answer
> 3 votes
# BQN, ~~126~~ 114 bytesSBCS

```
{S←-++`×¬⋄{wg:g⊑∘↑˜¨¯2+∨´⥊w{H←⊒˜∊·⥊(↕≠)+⌜·/⊸⍷⋄(H˘∨1↓˘⊒˜⌽⁼˘·H˘⌾⍉⊒˜⌽˘' '⊸∾˘)⌾(⌽∘⍉⍟)g}⌜↕4}⟜>´(S⟨⟩⊸≡¨)⊸⊔⊔˜S='
'}

```

Run online!

One third of the code is parsing the input, the more interesting parts are outlined below:

```
{wg:g⊑∘↑˜¨¯2+∨´⥊w{H←⊒˜∊·⥊(↕≠)+⌜·/⊸⍷⋄(H˘∨1↓˘⊒˜⌽⁼˘·H˘⌾⍉⊒˜⌽˘' '⊸∾˘)⌾(⌽∘⍉⍟)g}⌜↕4}

```

Run online!

```
{wg:g⊑∘↑˜¨¯2+∨´⥊w{ ... }⌜↕4}
 wg:                          # A dyadic function taking:
                               #  - left argument w: word list
                               #  - right argument g: grid
                          ↕4   # 0 1 2 3
                  { ... }⌜     # For each of those numbers on the right (specifying rotation) and ...
                 w             # each word on the left, call the inner function.
                               # The inner function returns boolean matrices of the same shape of the input
              ∨´⥊              # Boolean OR of all the matrices
     g⊑∘↑˜¨¯2+                 # For 1's in the matrix take a character from the grid, for 0's take a space.

```

The inner function rotates the grid (as many times as its right argument specifies: `⌽∘⍉⍟`), checks for words from left to right and on diagonals and then rotates the result back.

**How to get get diagonals**:

This method is mostly taken from BQNcrate. First a space is prepended to each row. Then each row is rotated by its index. Now words previously in the diagonals are in the columns, by transposing we get them in the rows. After marking the words, all the steps can be reversed: Try with step-by-step results!

# Answer
> 1 votes
## Scala  697, 666  649

```
val(z,n)=io.Source.fromFile("F").getLines.toList.span(_.length>0)
val m=n.tail
val(w,h)=(m.head.length,m.size)
def g(d:Int,e:Int,k:Int,g:Int,h:Int,i:Int,s:String)={
def f(x:Int,y:Int):Seq[(Int,Int)]={
val q=for(c<-(0 to s.size-1))
yield (y+c*i,x+c*k)
if((q.map(p=>m(p._1)(p._2))).mkString==s)q else Nil}
val t=for(x<-(d to e);
y<-(g to h))yield f(x,y)
t.flatten}
def i(s:String)={val l=s.size
g(0,w-l,1,0,h-1,0,s)++ g(0,w-1,0,0,h-l,1,s)++ g(0,w-l,1,l-1,h-1,-1,s)++ g(0,w-l,1,0,h-l,1,s)}
def j(s: String)=i(s)++ i(s.reverse)
val k=z.map(j).flatten
(0 to h-1).map(r=>{(0 to w-1).map(c=>if(k.contains(r,c))print(""+m(r)(c))else print(" "));println()})

```

### degolfed:

```
object Golf {

def main (args: Array[String]) = {
  val (words, matrix) = io.Source.fromFile ("./wordsearch.data").getLines.toList.span (_.length > 0)
  val m = matrix.tail
  val (w,h) = (m.head.length, m.size)

  // xi: x-increment, yi: y-increment
  def find (x: Int, y: Int, xi: Int, yi: Int, s: String): Seq [(Int, Int)] = {
    val points = for (c <- (0 to s.length-1))
       yield (y + c*yi, x + c * xi)
    if ((points.map (p => m (p._1)(p._2))).mkString == s) points else Nil
  }

  def findInScope (xS: Int, xD: Int, xi: Int, yS: Int, yD: Int, yi: Int, s: String): Seq [(Int, Int)] = {
    val ppoints = for (x <- (xS to xD);
          y <- (yS to yD)) yield find (x, y, xi, yi, s)
    ppoints.flatten
  }

  def findRowColFallingClimbing (s: String) = {
    val l=s.length

    // horizontal:
      findInScope (0,   w-l,  1,   0, h-1,  0, s) ++
    // vertical:
      findInScope (0,   w-1,  0,   0, h-l,  1, s) ++
    // climbing /:
      findInScope (0,   w-l,  1, l-1, h-1, -1, s) ++
    // falling \:
      findInScope (0,   w-l,  1,   0, h-l,  1, s)
  }

  def findBoth (s: String) = findRowColFallingClimbing (s) ++ findRowColFallingClimbing (s.reverse)
  val coords = words.map (findBoth).flatten

  (0 to h-1).map ( r => {
    (0 to w-1).map (c =>
      if (coords.contains (r, c))
       print ("" + m(r)(c))
      else print (" ")
     )
     println ()
   })
  }
}

```

---
Tags: code-golf, word-puzzle, crossword, word-search
---


title: Unreliable data stream

text:
# Question
Title: Unreliable data stream
Your challenge is to golf a program that mimics a data transmission stream. Your program should read input from stdin and output it directly to stdout. To make the problem more interesting, the output stream is 'faulty', and must meet several requirements:

1. There should be a 10% chance that each character is shifted +1 ascii code (ex 'a' becomes 'b', '9' becomes ':'), etc.
2. The input and output should only cover printable ascii values ('!' through '~', decimal 33 through decimal 126, inclusive). If the random +1 occurs on a '~' (decimal 126), a '!' (decimal 33) should be output instead.
3. If three characters are randomly shifted in a row, the program should output "ERROR CODE 4625: UNRECOVERABLE ERROR, PLEASE CONTACT YOUR SYSTEM ADMINISTRATOR" (trailing newline optional) and halt execution.

To simplify the problem, here are a few other criteria:

1. You can assume the input will always be valid; that is, it will only contain values '!' through '~'.
2. The program should continue on until three characters are randomly shifted in a row; it's safe to assume that EOF will never occur.
3. The randomness must differ across runs; if your random number generator needs to be seeded to get an unique result each run, then your code needs to seed it.
4. You must write a program, not a function.
5. You must take input from stdin and write output to stdout.
6. You may not use any external libraries or resources.
7. Your code must have a freely available and working intrepreter or compiler.

Standard code-golf rules apply. Winner is whoever has the shortest program posted two weeks from now (Thursday, Feb 20th, 2014).

# Answer
# Befunge-98, ~~166~~ ~~159~~ ~~156~~ ~~155~~ 148

This one improves on the other excellent Befunge answer with the correct probability (1/10) and is slightly more compact:

```
~>?#v?1+\1>+\:'~1+-4k#x07_$'!>,:3-!#v_
>#?>>>\$\0^>
^<<
A"##  "CT YOUR SYSTEM ADMINISTRATOR"<@,kM'"ERROR CODE 4625: UNRECOVERABLE ERROR, PLEASE CONT

```
> 4 votes

# Answer
## C, 168 characters

```
i;main(c){for(srand(&c);i++<3;putchar(rand()%10?i=0,c:c-126?c+1:33))c=getchar();
puts("ERROR CODE 4625: UNRECOVERABLE ERROR, PLEASE CONTACT YOUR SYSTEM ADMINISTRATOR");}

```

This solution's seeding of the PRNG takes advantage of the fact that modern OSes change the stack's location in memory on each run, as a basic measure against stack-smashing exploits.
> 4 votes

# Answer
## Ruby, 156

```
e=3
putc(($_.ord-33+r=rand(10)/9)%94+33)/e=r>0?e-r :3while gets(1)rescue$><<'ERROR CODE 4625: UNRECOVERABLE ERROR, PLEASE CONTACT YOUR SYSTEM ADMINISTRATOR'

```
> 2 votes

# Answer
# C# - 346 330 313 309 297 288 278 274

Kinda long but does the job.

```
using System;class m{static void Main(){int c=0;var r=new Random();while(c<3){int n=r.Next(10);var j=Console.In.Read();Console.Write((char)(n<1?j>'}'?'!':++j:j));c=n<1?c+1:0;}Console.Write("ERROR CODE 4625: UNRECOVERABLE ERROR, PLEASE CONTACT YOUR SYSTEM ADMINISTRATOR");}}

```
> 1 votes

# Answer
# C, ~~260~~ ~~257~~ ~~237~~ ~~225~~ ~~189~~ 174

My first golf, suggestions appreciated.

```
n;main(){for(srand(&n);n!=3;putchar((getchar()+(rand()%10==7?!!++n:(n=0))-33%94)+33));puts("ERROR CODE 4625: UNRECOVERABLE ERROR, PLEASE CONTACT YOUR SYSTEM ADMINISTRATOR");}

```

7 is very random.

Compiling will give you warnings.

Thanks for help from breadbox and Josh.
> 1 votes

# Answer
## Batch - 359

Open to suggestions to make it completely compliant to the challenge rules.

I will work on making it smaller / better - I wanted to post it while it's working, before I break it.

```
@echo off&setLocal enableDelayedExpansion&for /L %%a in (33,1,126)do cmd/cexit %%a&set %%a=!=exitcodeAscii!
set a=%~1
:l
if defined a (
set c=!a:~0,1!&set a=!a:~1!&set b=0&set/ar=%RANDOM%*10/32768+1
if !r!==1 for /L %%b in (33,1,126)do (
if !b!==1 echo !%%b!>>f
if "!c!"=="!%%b!" set b=1
)
if !b!==1 set/pc=<f&del f
set o=%o%!c!&goto l
)
echo %o%

```

There are definitely quite a few ways to golf it down.

```
h:\uprof>UDS.bat "test ing"
tesu inh

h:\uprof>UDS.bat "test ing"
tfsu ing

```

Un-golfed -

```
@echo off
setLocal enableDelayedExpansion
for /L %%a in (33,1,126) do (
    cmd /c exit %%a
    set %%a=!=exitcodeAscii!
)
set a=%~1
:l
if defined a (
    set c=!a:~0,1!
    set a=!a:~1!
    set b=0
    set /a r=%RANDOM%*10/32768+1
    if !r!==1 for /L %%b in (33,1,126) do (
        if !b!==1  echo !%%b!>>f
        if "!c!"=="!%%b!" set b=1
    )
    if !b!==1 set /p c=<f& del f
    set o=%o%!c!
    goto l
)
echo %o%

```
> 1 votes

# Answer
## ~~sh~~ bash, on OSX, ~~211~~, ~~208~~, ~~203~~, ~~200~~, ~~196~~, 185

```
IFS=
while read -n1 a;do
((RANDOM>3276))&&echo $a&&t=0||{
tr !-}~ \"-~!<<<$a
((t++==2))&&echo ERROR CODE 4625: UNRECOVERABLE ERROR, PLEASE CONTACT YOUR SYSTEM ADMINISTRATOR&&exit
}
done

```

Slightly better than 10% since random will generate numbers between 0 and 32767, so really it's 3,277 in 32,768 odds (10.0006%).

Thanks, @Gilles (but not sure what you mean about the while restructure. had some other ideas in the shower, too.
> 1 votes

# Answer
## PHP 190

that's the further i could golf it, but i think it's pretty good that it is less than 100 chars from the leading

```
<? while($a=fread(STDIN,1)){if(!rand(0,9)){$a=$a=='~'?'!':chr(ord($a)+1);@$i+=1;$i>2&&die("ERROR CODE 4625: UNRECOVERABLE ERROR, PLEASE CONTACT YOUR SYSTEM ADMINISTRATOR");}else$i=0;echo$a;}

```
> 1 votes

# Answer
# Vyxal `s`, 63 bytes

```
ƛ₀℅‹¬;:ĠṠ3<A[?C+₇‹33VC|`»ȯ ¬⋎ 4625: un₆¬×→ »ȯ, ƛṙ λḊ λ¢ ƛβ ↑Ẇ`⇧

```

Try it Online!

```
ƛ    ;                      # Map input to...
 ₀℅‹¬                       # 1 with chance 10%
      :ĠṠ                   # Get sums of groups of identical run lengths
         3<A[               # If all are less than 3 (no error)
             ?C+            # Add randoms to input charcodes
                ₇‹33V       # Replace 127 with 33
                     C      # Get charcodes
                      |`... # Else output the string

```
> 1 votes

# Answer
# 05AB1E, ~~65~~ ~~64~~ 63 bytes

```
v9°Ω})DÅγsÏ3åi.•kUàø¸àŸ´•uŽIZ‘‰ëƒË ÿ: ÿ‰ë,‚µ€Í€ž‚«¢é‘ësÇ+ƵQ33:ç

```

Try it online!
> 0 votes

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

```
for(z=1,r='';z<<=9;z|=y+''==x,r+=y>'~'?'!':y)require('fs').readSync(0,x=Buffer(1),0,1),y=x.map(t=>t+(Math.random()<.1));console.log(r+'ERROR CODE 4625: UNRECOVERABLE ERROR, PLEASE CONTACT YOUR SYSTEM ADMINISTRATOR')

```

Try it online!
> 0 votes

# Answer
# Kotlin, ~~357~~ 355 bytes

2 bytes saved after discovering this

```
import java.util.*import kotlin.random.*import kotlin.random.Random
var c=0
fun main(){var a =Scanner(System.`in`).next().toMutableList()
for(i in a.indices){if(Random.nextUInt()%10u<1u){c++;if(a[i]=='~')a[i]='!' else a[i]=a[i]+1}else if(c<3)c=0}
if(c>2)print("ERROR CODE 4625: UNRECOVERABLE ERROR, PLEASE CONTACT YOUR SYSTEM ADMINISTRATOR")else print(a)}

```

Try it online!

I've noticed that adding newlines causes the same amount of bytes to accumulate compared to adding a semicolon. hence why it isnYt so one liney. this of course does not work with tio.run as it requires input. If you see any places where there could be any kind of improvement please tell.

#### Ungolfed version

```
import java.util.*import kotlin.random.*import kotlin.random.Random
var c =0
fun main()
{
    var a = Scanner(System.`in`).next().toMutableList()
    for(i in a.indices){
        if(Random.nextUInt()%10u<1u)
        {
            c++
            if(a[i]=='~') a[i]='!'
            else a[i]=a[i]+1
        }
        else if(c<3)c=0
    }
    if(c>2) print("ERROR CODE 4625: UNRECOVERABLE ERROR, PLEASE CONTACT YOUR SYSTEM ADMINISTRATOR")
    else print(a)
}

```

~~Try it online!~~

~~```
    import java.util.*;import kotlin.random.Random;import kotlin.random.*
    var c=0
    fun main(){var a =Scanner(System.`in`).next().toMutableList()
    for(i in a.indices){if(Random.nextUInt()%10u<1u){c++;if(a[i]=='~')a[i]='!' else a[i]=a[i]+1}else if(c<3)c=0}
    if(c>2)print("ERROR CODE 4625: UNRECOVERABLE ERROR, PLEASE CONTACT YOUR SYSTEM ADMINISTRATOR")else print(a)}

```~~
> 0 votes

---
Tags: code-golf
---


# Question
Title: How to shorten Python code involving the sum of reciprocals?
I have a coding problem that goes like this:

> Given a positive integer \\$N\\$, return a list of all possible pairs of positive integers \\$(x,y)\\$ such that $$\frac1x+\frac1y=\frac1N$$

I already solved the problem using Python, but I was wondering how I can code golf it. The following is my attempt at golfing (I try to follow some tips on the tips page):

108 bytes

```
exec("f=lambda N:[b for i in range(1,N+1)if N*N%i==0"+"for b in[%s,%s[::-1]]][:-1]"%(("[N+i,N+N*N//i]",)*2))

```

Try it online!

Ungolfed code for better readability

```
def f(N):
 l=[]
 for i in range(1,N+1):
  if N*N%i==0:
   a=[N+i,N+N*N//i]
   l.extend([a,a[::-1]])
 return l[:-1]

```

Try it online!

# Answer
# Python 3.8 (pre-release), 60 bytes

```
f=lambda N:[[N+i,N+N*N//i]for i in range(1,N*N+1)if 1>N*N%i]

```

Try it online!

No need for reversing:

We just generate every fraction for which the first denominator is a divisor of N squared.
> 4 votes

# Answer
As AnttiP has pointed out, this can be shorter with a change of approach and full rewrite. Let's look at some simpler manipulations of your original code though just for the sake of it though:

Here was my first attempt at eliminating the `exec` hack:

### 85 bytes

```
lambda N:[b for i in range(1,N+1)if N*N%i==0for b in[A:=[N+i,N+N*N//i],A[::-1]]][:-1]
```

Attempt This Online!

Unfortunately, as you may notice, it doesn't work, because `:=` is not allowed in `for` comprehension iterable expression.

There's another place we can put it in though: the `if` clause just before it:

### 91 bytes

```
lambda N:[b for i in range(1,N+1)if(A:=[N+i,N+N*N//i])and N*N%i==0for b in[A,A[::-1]]][:-1]
```

Attempt This Online!

This can be shortened a bit by combining the comparison `==0`:

### 89 bytes

```
lambda N:[b for i in range(1,N+1)if 0in(A:=[N+i,N+N*N//i],N*N%i)for b in[A,A[::-1]]][:-1]
```

Attempt This Online!

The `[:-1]` at the end is just to remove the final duplicated result of `(x, x)`, but we can remove this just by switching to a set comprehension (and using a tuple instead of a list, because it's hashable):

### 84 bytes

```
lambda N:{b for i in range(1,N+1)if 0in(A:=(N+i,N+N*N//i),N*N%i)for b in[A,A[::-1]]}
```

Attempt This Online!

The output is no longer in order, so hopefully that doesn't matter here.

I'm working on going further than this... stay tuned
> 3 votes

---
Tags: code-golf, tips, python
---


title: What's the day today (or other dates)?

text:
# Question
Title: What's the day today (or other dates)?
## Task

Write a program or a function that calculates a week-day name of a date which a user inputs.

## Input & Output

Input is a string, `YYYYMMDD`.

Example of input values:

```
20110617 : June 17, 2011
19040229 : February 29, 1904
06661225 : December 25, 666
00000101 : January 1, 0
99991231 : December 31, 9999

```

You may assume that all inputs are valid. Note that year zero is valid.

Output is an integer between `0` and `6`. Each integer represents a week-day name. You can decide freely which integer represents a week-day name, like this one

```
0 : Monday
1 : Tuesday
2 : Wednesday
...
6 : Sunday

```

(in order) or this one

```
0 : Monday
1 : Wednesday
2 : Sunday
...
6 : Saturday

```

(not in order).

## Test Cases

```
Input     Week-day   Output ([0..6 -> Monday..Sunday] is used in this example.)

20110617  Friday     4
19500101  Sunday     6
22220202  Saturday   5
19000228  Wednesday  2
19000301  Thursday   3
19450815  Wednesday  2
19040229  Monday     0
19040301  Tuesday    1
17760704  Thursday   3
20000228  Monday     0
20000229  Tuesday    1
20000301  Wednesday  2
20121223  Sunday     6
00000401  Saturday   5
66660606  Wednesday  2
59161021  Saturday   5

```

## Restriction

You **must not** use **any** kind of function/class/... which are related to timestamp or date, like `Date` class in `Java`/`JavaScript`/`ActionScript`, or `getdate` function in `PHP`.

You should use Gregorian calender, which is used by many people now.

Of course, shortest code wins. If two code have same length, then the code with highest votes wins.

(Due: When there's more than 5 codes which has more than (or equal) `+1` votes.)

# Answer
## Ruby, 95 92 characters

Plain straightforward ruby implementation with 0:Monday, ...

```
p ((y=(d=gets.to_i)/(k=100)/k-((m=d/k%k)<3?1:0))+y/4-y/k+y/400+"squsptrotqro"[-m].ord+d%k)%7

```
> 2 votes

# Answer
# PHP - ~~101~~ ~~97~~ ~~103~~ 125 characters

* Sakamoto Algorithm
* 0 = Sunday

## Code

```
<?php fscanf(STDIN,"%4d%2d%2d",$y,$m,$d);@$a=a032503514624;$y-=$m<3;$z=$y+1;echo($y+$y/4%$z-$y/100%$z+$y/400%$z+$a[$m]+$d)%7;

```

### Note

Unfortunately, due to PHP's dynamic, weak typing, the Sakamoto algorithm doesn't function properly without explicitly flooring each division operation.
> 4 votes

# Answer
## Javascript, 126 123 characters

Using Sakamoto's algorithm with 0 = Sunday:

```
prompt().replace(/(....)(..)(..)/,function(_,y,m,d){y-=m<3;alert((+d+y-~(y/4)+~(y/100)-~(y/400)+ +".621462403513"[+m])%7)})

```

I suspect the divisions can be collapsed, but right now I'm not seeing it.

*Edit:* Improved the divisions (no need to `~~` when you can just `~`).
> 2 votes

# Answer
## C - 129

```
main(y,m,d,s)
{
    scanf("%04d%02d%02d",&y,&m,&d);
    y-=s=86400;
    d+=y+"-addgbegcfadf"[m];
    m>2?y++:0;
    putchar(48+(d+y/4-y/100+y/400+s+s)%7);
}

```

This abuses how division rounds toward zero, at least on my system (Linux x86).

The magic constant, `86400`, serves two purposes:

* Subtract from the year to make it negative, without affecting the day of the week. This makes it so the divisions will round up instead of down.
* Shift the day number so Monday will be 0.

It also happens to be the number of seconds in a day.
> 2 votes

# Answer
# Python 2, ~~83~~ ~~116~~ ~~113~~ 109 bytes

Implements Sakamoto's algorithm. Golfing suggestions welcome. Try it online!

**Edit:** ~~I should have fixed this ages ago.~~ -6 bytes from Jonathan Allan's suggestions +2 bytes to actually fixing the code.

```
def w(s):m=int(s[4:6]);y,d=int(s[:4])-(m<3),int(s[6:]);return(y+y/4-y/100+y/400+int('032503514624'[m-1])+d)%7

```
> 2 votes

# Answer
# C (126 bytes)

```
main(y,m,d){scanf("%4d%2d%2d",&y,&m,&d);y%=400;putchar(((5*y+3)/4-y/100+"-KGGJLHJFIKGI"[m]+(!(y%4)&&m>2&&y%100||!y)+d)%7+48);}

```

Try it online!
> 1 votes

# Answer
## Perl -- 110 bytes

Here is a solution to be run with perl -p source.pl OR perl -pe 'here-is-code'.

```
s/((..)(..))(..)(..)/(1+3*$1+$2-2*($1%4+$2%4)-(2<$4?$4+(1&$4&&4-(8&$4)):(2^$4)+(!($3%4)-!-$3+!($2%4)))+$5)%7/e

```

Simply copy-paste the test cases to stdin.

This seems to be the only code without variables, string constants and divisions.
> 0 votes

---
Tags: code-golf, date
---


# Question
Title: An Scalable Event Scheduler That Can Handle Billions of Events
The event scheduler is a recurrent theme in event-driven architectures: something triggers an event that needs to be checked in the future one or more times. I has particular use in trading where you want to correlate one market event with price movements in the future at several time deltas (1ms, 100ms, 1s, 1 min, etc). During strategy discovery and backtesting the scheduling can reach billions of events.

A parenthesis here: this is a general algorithm challenge that can be implemented in any language. We provide an example implementation in C++ but it does not need to be written in that language necessarily.

The scheduler problem can be summarized in the following interface:

```
using Time = std::uint64_t; ///! nanos since epoch

/** Base class for all events to be handled by the scheduler */
struct Event {
    virtual void fire( Time scheduled, Time now ) = 0;
};

/** A class that functions as a container for events to be fired in the future.
    The same event can be added multiple times into the scheduler.
    Distinct events can be added at the same time.
 */
class Scheduler {
public:
    virtual ~Scheduler()  = default;
    /** Schedules one event */
    virtual void schedule( Event* ev, Time tm ) =0;
    /** Checks events and fires accordingly.
        "t" is guaranteed ascending */
    virtual bool check( Time t ) =0;
};

```

As a note, we decided to use raw points so not to introduce noise around smart pointers, move semantics, etc. These can be added later on.

The scheduler can be trivially coded using the standard containers but it will lead to log(N) algorithms for scheduling. Other trivial solutions will lead to O(1) for scheduling but O(logN) for checking. For example:

```
class StandardScheduler : public Scheduler {
public:
    StandardScheduler();
    virtual void schedule( Event* ev, Time tm ) override;
    virtual bool check( Time t ) override;
private:
    using EventMap = std::multimap<Time,Event*>;
    EventMap events;
    Time current;
};

```

Our goal in this test is to generate a solution that remains fast even for very large number of events, say 1E8. Therefore it helps if the solution is constant time O(1) in both scheduling and checking, in average.

The main requirements are:

1. Both scheduling and checking need to be very fast for extremely large number of events (eg 1E8). It is acceptable if it is slower at times (hiccups) for rebalance for example.
2. Individual events can be submitted multiple times
3. Distinct events can be submitted under the same time (same key in a map)
4. Events need to be fired in strict order by time.

The best solution will display the best execution times to schedule and iterate over a very large number of samples, which we set arbitrarily at 100,000,000 events with 3 random reposts of the same event. If two solutions come in first with 10% between them, I would like to consider the code that is smaller in size.

As per suggestion in the sandbox, I would like to propose winners per language: C++, Java, Python, etc since the commenter highlighted that this task is bread and butter for C/C++. So other languages can also compete.

The times need to be randomized and distributed over a span of time between 0 and 10 times the number of samples. The iteration is done every 5 time units.

A basic implementation for this challenge is provided on Github: https://github.com/HFTrader/scheduler.git.

The sample code is all standard C++ with no platform-specific features and is provided with a CMakeLists.txt which should make it able to compile in all major platforms, although it has only been tested on Linux.

If you choose to do it C++, you might clone, subclass the Scheduler class and replace it in main(). An example StandardScheduler is provided. In other languages, please replace with equivalent constructs.

```
git clone https://github.com/HFTrader/scheduler.git
cd scheduler
mkdir build
cd build
cmake -DCMAKE_BUILD_TYPE=release ..
make
./scheduler 10000000 3

```

The timings in this C++ code provide the number of nanoseconds for scheduling and checking (iteration through time). A sample run can be like:

```
$ ./scheduler
Usage:
        ./scheduler <numsamples> <numreposts>

$ ./scheduler 10000000 3
Timings schedule:1196 check:126
Success!

```

The above code ran in 1196 and 126 nanoseconds per event, which is the key result. The above was ran in an AMD Ryzen Threadripper 3960X with 64Gb RAM under Ubuntu 20.04LTS and compiled with g++ 9.3 under "-O3".

If you are able to submit your solution to that Github repository, I will make sure to run all the solutions and post results.

# Answer
> 8 votes
## Proof that this challenge is impossible without extra assumptions

I'm assuming here that we can't take advantage of the fact that the range of a `Time` is limited, thus technically O(1). (If you do take advantage of that fact, you can solve the challenge in O(1) by using a separate array for every possible `Time` value – `schedule` is easy to implement with this technique, and `check` can work by iterating over every `Time` value less than the value being checked, which is very slow but technically O(1).)

If we can't exploit the limited range of `Time`, then any solution to this problem that obeyed the rules would give an O(*n*) comparison sort routine; simply use your program to schedule a large number of events, then check them all. Because sorting and checking are required to be O(1) on average, the combination of sorting and checking is thus required to be O(*n*) to handle all *n* events – so it can sort data in O(*n*). It's mathematically impossible to use a comparison sort for this, as comparison sorts can't go any faster than O(*n* log *n*); and any attempt to use a non-comparison sort would need to exploit the limited range of a `Time`.

A practically useful answer to this sort of problem would probably work via placing restrictions on the times at which `check` could be called (e.g. by requiring that it's called sufficiently often that performance-per-event that's O(log *t*) in the `Time` since the previous check is acceptable because *t* will be small), or via allowing events found during a single call to `check` to be fired out of order, but both of these techniques are currently disallowed by the question.

---
Tags: sorting, fastest-code, restricted-complexity, data-structures
---