title: What numbers are these?

text:
# Question
Title: What numbers are these?
While I was writing numbers I noticed after a while that my keyboard had the `Shift` key pressed and blocked and all I wrote was `$%&`-like characters. And even worse, I had been switching between the English and Spanish keyboard layouts so I don't know which one I used for each number.

### Challenge

Given a string containing symbol characters, try to guess which number I wrote. My keyboard produces the following characters for the numbers when the `Shift` is pressed:

```
1234567890
----------
!"·$%&/()=  Spanish layout
!@#$%^&*()  English layout

```
* The input will be a non-null, non-empty string composed of the symbols above.
* The output will be a single number if the keyboard layout can be inferred from the string (i.e. if the string contains a `@` an English layout was used, and if the string contains a `"` a Spanish layout was used) or if the number is the same for both layouts (i.e. the input is `!$` which translates as `14` for both layouts); otherwise the output will be the two possible numbers for both layouts if it cannot be inferred and the resulting numbers are different.
* The input string will always be written in a single layout. So you don't need to expect `"@` as input.

### Examples

```
Input  -->  Output
------------------
/()         789        (Spanish layout detected by the use of /)
$%&         456,457    (Layout cannot be inferred)
!@#         123        (English layout detected by the use of @ and #)
()&!        8961,9071  (Layout cannot be inferred)
((·))       88399      (Spanish layout detected by the use of ·)
!$          14         (Layout cannot be inferred but the result is the same for both)
!!$$%%      114455     (Layout cannot be inferred but the result is the same for both)
==$"        0042/42    (Spanish layout, if a number starts with 0 you can choose to
                       omit them in the result or not)

Single character translations:
------------------------------
!   1
"   2
·   3
$   4
%   5
&   6,7
/   7
(   8,9
)   9,0
=   0
@   2
#   3
^   6
*   8

```

This is , so may the shortest code for each language win!

# Answer
> 6 votes
# Jelly, ~~32~~ 31 bytes

```
O“=!"Ṣ$%&/()“)!@#$%^&*(‘iⱮ€PƇ’Q

```

Try it online!

* -1 bytes thanks to Erik the Outgolfer

---

```
O“!"Ṣ$%&/()=“!@#$%^&*()‘iⱮ€PƇ%⁵Q
O                                  ord of each character in the input
 “!"Ṣ$%&/()=“!@#$%^&*()‘           Constant that yields the list:
                                      [[33, 34, 183, 36, 37, 38, 47, 40, 41, 61],
                                       [33, 64, 35, 36, 37, 94, 38, 42, 40, 41]
                          €        For each list of numbers:
                         Ɱ           For each ord of the characters in the input:
                        i              Find the index of the ord of the character
                                       in the list of numbers.
                                       If the number is not found, `i` returns zero
                                       which means it's a character from only one
                                       keyboard.
                                   There are now two lists of numbers 1-10.
                            Ƈ      Keep the list(s) that:
                           P         have nonzero product.
                             %⁵    Modulo 10. This maps 10->0.
                               Q   Unique elements. This removes duplicates if the two numbers are the same.

```

# Answer
> 4 votes
# Python 3, 76 bytes

```
lambda s:{(*map(k.find,s),)for k in['=!"·$%&/()',')!@#$%^&*(']if{*s}<={*k}}

```

Try it online!

# Answer
> 4 votes
# Perl 6, 62 bytes

```
{set grep {!/\D/},TR'=!"·$%&/()'0..9',TR')!@\x23$%^&*('0..9'}

```

Try it online!

Returns a Set. (Could be made two or three bytes shorter if there wasn't a bug in Rakudo's handling of # in search lists.)

# Answer
> 3 votes
# Java (JDK), 173 bytes

**Golfed**

```
c->{String s="",e=s;var m="21#3457#908###6##12#456389###0#7".split("");for(int l:c){e+=m[l=l%16];s+=m[l+16];}return s.equals(e)|s.contains("#")?e:e.contains("#")?s:s+","+e;}

```

Try it online!

---

**Ungolfed**
```
c->{                                                      // Lamdba taking char array as input
    String s="",e=s;                                      // Initialise Spanish and English strings
    var m="21#3457#908###6##12#456389###0#7".split("");   // Create magic hashing lookup array (see below)
    for(int l:c){                                         // Loops through all chars in input
        e+=m[l=l%16];                                     // Get english number from array and append
        s+=m[l+16];                                       // Get Spanish number from array and append
    }
    return s.equals(e)|s.contains("#")?e:                 // If equal or Spanish is invalid return english
        e.contains("#")?s:                                // If English is invalid return Spanish
        s+","+e;                                          // If both are valid but not equal, return both
}

```

---

**The Magic Hashing Lookup Array**

After some experimenting with values I realised that each of the ASCII values of the characters `!"·$%&/()=@#^*` modulo 16 returns a unique number. The *'magic hashing lookup array'* stores the English numbers associated with each character at this unique index, and each of the Spanish numbers at this index offset by 16, making fetching the required number from the array trivial for each language. A hash is stored for values that are invalid for either language.

# Answer
> 3 votes
# Japt, 38 bytes

Outputs an array of strings with the Spanish layout first.

```
"=!\"·$%&/())!@#$%^&*("òA £ËXbD
kø'- â

```

Try it

# Answer
> 2 votes
# Jelly, 38 bytes

```
183Ọ“=!"“$%&/()”j,“)!@#$%^&*(”iⱮ€⁸ẠƇ’Q

```

Try it online!

# Answer
> 2 votes
# Retina 0.8.2, 60 bytes

```
.+
$&¶$&
T`=!"·$%&/()`d`^.+
T`)!@#$%^&*(`d`.+$
D`
Gm`^\d+$

```

Try it online! Link includes test cases. Explanation:

```
.+
$&¶$&

```

Duplicate the input.

```
T`=!"·$%&/()`d`^.+
T`)!@#$%^&*(`d`.+$

```

Try to translate each line according to a different keyboard layout.

```
D`

```

Deduplicate the result.

```
Gm`^\d+$

```

Only keep lines that only contain digits.

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

```
s=>(g=l=>a=s.replace(/./g,c=>l.indexOf(c)))('=!"·$%&/()',b=g(')!@#$%^&*('))>=0?a-b&&b>=0?[a,b]:a:b

```

Try it online!

### How?

The helper function \\$g\\$ attempts to convert the input string using a given layout.

Invalid characters are replaced with \\$-1\\$, which results in either a valid but negative looking numeric string (if only the first character was missing), or an invalid numeric string. Either way, the test `x >= 0` is falsy.

# Answer
> 1 votes
# Clean, 116 bytes

```
import StdEnv,Text
$s=removeDup[foldl(<+)""d\\r<-["=!\"·$%&/()",")!@#$%^&*("],d<-[[indexOf{c}r\\c<-s]]|all((<) -1)d]

```

Try it online!

Takes input and is encoded in CP437. TIO only supports UTF-8, so an escape is used in the demo code to get the literal byte value 250 corresponding to the centre dot (counted as one byte).

# Answer
> 1 votes
# 05AB1E, ~~42~~ 41 bytes

```
•Hhç₁d©u÷^Σ(“ðΣèõĆ
-•184в2äεIÇk}ʒ®å_}>T%Ù

```

Port of *@dylnan*'s Jelly answer.

Try it online or verify all test cases.

**Explanation:**

```
•Hhç₁d©u÷^Σ(“ðΣèõĆ
-•184в           # Compressed list [33,34,183,36,37,38,47,40,41,61,33,64,35,36,37,94,38,42,40,41]
      2ä         # Split into two parts: [[33,34,183,36,37,38,47,40,41,61],[33,64,35,36,37,94,38,42,40,41]]
ε   }            # Map each inner list to:
 IÇ              #  Get the input, and convert each character to its unicode value
   k             #  Then get the index of each unicode value in the current map-list
                 #  (this results in -1 if the item doesn't exist)
     ʒ   }       # Filter the resulting list of indices by:
      ®å_        #  If the inner list does not contain any -1
          >      # Increase each index by 1 to make it from 0-indexed to 1-indexed
           T%    # Take modulo-10 to convert 10 to 0
             Ù   # Uniquify the result-lists (and output implicitly)

```

See this 05AB1E tip of mine (section *How to compress integer lists?*) to understand why `•Hhç₁d©u÷^Σ(“ðΣèõĆ\n-•184в` is `[33,34,183,36,37,38,47,40,41,61,33,64,35,36,37,94,38,42,40,41]`). This (together with the ) is 1 byte shorter than taking the unicode values of the string: `'""!ÿ·$%&/()=""!@#$%^&*()"‚Ç`.

# Answer
> 1 votes
# Ruby, 68 bytes

```
->s{%w[=!"·$%&/() )!@#$%^&*(].map{|a|s.tr a,'0-9'}.grep_v(/\D/)|[]}

```

Try it online!

# Answer
> 1 votes
# APL (Dyalog), 40 bytes

Anonymous tacit prefix function. Though unused, `·` is in the Dyalog single byte character set. Assumes 0-based indexing (`⎕IO←0`) which is default on many systems.

```
{∪⍵/⍨~10∊¨⍵}'=!"·$%&/()' ')!@#$%^&*('⍳¨⊂

```

Try it online!

the entire argument

`'=!"·$%&/()' ')!@#$%^&*('⍳¨` indices of the characters in each of these strings

`{∪⍵/⍨~10∊¨⍵}` apply the following lambda ( is the argument):

`10∊¨⍵` for each list of digits, whether 10 (indicating "not found") is a member thereof

`~` local negation (i.e. only those where all digits are found)

`⍵/⍨` filter the argument by that

find the unique elements of that

# Answer
> 0 votes
# Dart, 125 bytes

```
f(s)=>['=!"·\$%&/()',')!@#\$%^&*('].map((b)=>s.split('').map((e)=>b.indexOf(e)).join()).where((e)=>!e.contains('-')).toSet();

```

Ungolfed :

```
f(s){
  ['=!"·\$%&/()',')!@#\$%^&*(']
    .map(
      (b)=>s.split('').map((e)=>b.indexOf(e))
      .join()
    ).where(
      (e)=>!e.contains('-')
    ).toSet();
}

```
* Creates an array with the two specified key values, from 0 to 9
* For each of them, convert the input string to the corresponding number by using the characters' indexes
* Join the resulting array to create a number
* Remove any number having a '-' (Dart returns -1 when indexOf can't find a char)
* Return as a Set to remove duplicates

Try it on Dartpad!

# Answer
> 0 votes
# T-SQL, 143 bytes

```
SELECT DISTINCT*FROM(SELECT TRY_CAST(TRANSLATE(v,m,'1234567890')as INT)a
FROM i,(VALUES('!"·$%&/()='),('!@#$%^&*()'))t(m))b
WHERE a IS NOT NULL

```

Input is taken via pre-existing table **i** with varchar field **v**, per our IO standards.

Joins the input table with the two different character strings, then uses the new SQL 2017 function `TRANSLATE` to swap out individual characters, and `TRY_CAST` to see if we end up with a number. If not, `TRY_CAST` returns `NULL`.

The final outer `SELECT DISTINCT` combines identical results and filters out the `NULLS`.

---
Tags: code-golf, keyboard
---


title: Blind Random Sort

text:
# Question
Title: Blind Random Sort
Here's a pretty common pattern for sorting algorithms:

```
def sort(l):
    while not is_sorted(l):
         choose indices i, j
         assert i < j
         if l[i] > l[j]:
             l[i], l[j] = l[j], l[i]

```

These algorithms work well because the indices `i` and `j` are chosen carefully, based on the state of the list `l`.

However, what if we couldn't see `l`, and just had to choose blindly? How fast could we sort the list then?

---

Your challenge is to write a function that outputs a random pair of indices, given only the length of `l`. Specifically, you must output two indices, `i, j`, with `0 <= i < j < len(l)`. Your function should work on any length of list, but it will be scored on a list of length 100.

Your score is the mean number of index choices necessary to sort a uniformly randomly shuffled list according to the above pattern, where the indices are chosen according to your function.

I will score submissions, taking the mean number of index choices over 1000 trials on a uniformly randomly shuffled list of length 100 with no repeated entries.

I reserve the right to run less trials if the submission is clearly non-competitive or does not terminate, and I will run more trials to differentiate the top competitors to find a single winner. If multiple top submissions remain within the margin of error at the limit of my computational resources, I will declare the earlier submission the winner, until further computational resources can be brought to bear.

---

Here's an example scoring program, in Python:

```
import random
def is_sorted(l):
    for x in range(len(l)-1):
        if l[x] > l[x+1]:
            return False
    return True

def score(length, index_chooser):
    steps = 0
    l = list(range(length))
    random.shuffle(l)

    while not is_sorted(l):
        i, j = index_chooser(length)
        assert (i < j)
        if l[i] > l[j]:
            l[i], l[j] = l[j], l[i]
        steps += 1
    return steps

```

---

Your function may not maintain any mutable state, interact with global variables, affect the list `l`, etc. Your function's only input must be the length of the list `l`, and it must output a ordered pair of integers in the range `[0, len(l)-1]` (or appropriate for your language's list indexing). Feel free to ask whether something's allowed in the comments.

Submissions may be in any free-to-use language. Please include a scoring harness if one has not already been posted for your language. You may post a provisional score, but I will leave a comment with the official score.

Scoring is the mean number of steps to a sorted list on a uniformly randomly shuffled list of length 100. Good luck.

# Answer
> 10 votes
# Python, score = 4508

```
def half_life_3(length):
    h = int(random.uniform(1, (length / 2) ** -3 ** -0.5) ** -3 ** 0.5)
    i = random.randrange(length - h)
    return i, i + h

```

Half-Life 3 confirmed.

# Python, score = 11009

```
def bubble(length):
    i = random.randrange(length - 1)
    return i, i + 1

```

Apparently a randomized bubble sort doesn’t do all that much worse than a normal bubble sort.

# Optimal distributions for small length

There’s no way this could be extended to length 100, but it’s interesting to look at anyway. I computed optimal distributions for small cases (length ≤ 7) using gradient descent and lots of matrix algebra. The *k*th column shows the probability of each swap at distance *k*.

```
length=1
score=0.0000

length=2
1.0000
score=0.5000

length=3
0.5000 0.0000
0.5000
score=2.8333

length=4
0.2957 0.0368 0.0000
0.3351 0.0368
0.2957
score=7.5106

length=5
0.2019 0.0396 0.0000 0.0000
0.2279 0.0613 0.0000
0.2279 0.0396
0.2019
score=14.4544

length=6
0.1499 0.0362 0.0000 0.0000 0.0000
0.1679 0.0558 0.0082 0.0000
0.1721 0.0558 0.0000
0.1679 0.0362
0.1499
score=23.4838

length=7
0.1168 0.0300 0.0041 0.0000 0.0000 0.0000
0.1313 0.0443 0.0156 0.0000 0.0000
0.1355 0.0450 0.0155 0.0000
0.1355 0.0443 0.0041
0.1313 0.0300
0.1168
score=34.4257

```

# Answer
> 7 votes
# Score: 4627

```
def rand_step(n):
	step_size = random.choice([1, 1, 4, 16])

	if step_size > n - 1:
		step_size = 1

	start = random.randint(0, n - step_size - 1)
	return (start, start + step_size)

```

Try it online!

Outputs random indices whose distance apart is chosen uniformly from `[1,1,4,16]`. The idea is to have a mix of 1-step swaps with swaps at larger scales.

I hand-tweaked these values for lists of length 100, and they are likely far from optimal. Some machine search could probably optimize the distribution over distances for the random-pair-with-chosen-distance strategy.

# Answer
> 3 votes
# Score: 28493

```
def x_and_y(l):
    x = random.choice(range(l))
    y = random.choice(range(l))
    while y == x and l != 1: y = random.choice(range(l))
    return sorted([x,y])

```

Try it online!

This solution just selects distinct values for `x` and `y` randomly from the range and returns them in sorted order. As far as I can tell, this performs better than choosing `x` then choosing `y` from the remaining values.

# Answer
> 3 votes
# Python, score: 39525

```
def get_indices(l):
    x = random.choice(range(l-1))
    y = random.choice(range(x+1,l))
    return [x,y]

```

First it chooses a random value in the range \\$\[0, l-1)\\$ for the \\$x\\$-index.
After that it will choose another random value larger than \\$x\\$ in the range \\$\[x+1, l)\\$ for the \\$y\\$-index.

Try it online.

# Answer
> 2 votes
# Python, score ≈ 5000

```
def exponentialDistance(n):
    epsilon = 0.25
    for dist in range(1, n):
        if random.random() < epsilon:
            break
    else:
        dist = 1
    low = random.randrange(0, n - dist)
    high = low + dist
    return low, high

```

Tried with a bunch of epsilon values, 0.25 seems to be the best.

### Score ≈ 8881

```
def segmentedShuffle(n):
    segments = 20
    segmentLength = (n - 1) // segments + 1

    if random.random() < 0.75:
        a = b = 0
        while a == b or a >= n or b >= n:
            segment = random.randrange(segments)
            a = random.randrange(segmentLength) + segment * segmentLength
            b = random.randrange(segmentLength) + segment * segmentLength
        return sorted([a, b])

    highSegment = random.randrange(1, segments)
    return highSegment * segmentLength - 1, highSegment * segmentLength

```

A different approach. Not as good, and it dies horribly with length not divisible by the number of segments, but still fun to build.

# Answer
> 1 votes
# Score: 4583

```
def rand_shell(l):
    steps = [1, 3, 5, 9, 17, 33, 65, 129]
    candidates = [(left, left + step)
            for (step, nstep) in zip(steps, steps[1:])
            for left in range(0, l - step)
            for i in range(nstep // step)
    ]
    return random.choice(candidates)

```

Try it online!

I've no idea why. I just tried sequences listed on wikipedia artical for shellsort. And this one seem works best. It get similar score with the one xnor posted.

# Answer
> 1 votes
# Python 2, 4871

```
import random
def index_chooser(length):
    e= random.choice([int(length/i) for i in range(4,length*3/4)])
    s =random.choice(range(length-e))
    return [s,s+e]
def score(length, index_chooser):
    steps = 0
    l = list(range(length))
    random.shuffle(l)
    while True:
        for x in range(length-1):
            if l[x] > l[x+1]:
                break
        else:
            return steps
        i, j = index_chooser(length)
        assert(i < j)
        if l[i] > l[j]:
            l[i], l[j] = l[j], l[i]
        steps += 1

print sum([score(100, index_chooser) for t in range(100)])

```

Try it online!

---
Tags: code-challenge, random, sorting
---


# Question
Title: Recreate the ASCII-table as an ASCII-table
Frequently while I'm code-golfing, I'll want to know what the ASCII value of a certain character is. One of my favorite resources for quickly looking up all of the printable ASCII characters is ASCIItable.com. This has a really nice image that not only shows the printable ASCII characters and their values, but also the unprintable and extended characters, and the values in hexadecimal, octal, and HTML:

Today's challenge is to recreate that ASCII table as an ASCII table instead of an image. To keep things simpler, we will not use control-characters (characters below 32) and we'll only show the decimal value and the character. In other words, your challenge is to write either a full-program or a function that prints or returns the following text:

```
Dec  Chr   | Dec  Chr   | Dec  Chr
----------------------------------
32   Space | 64   @     | 96   `
33   !     | 65   A     | 97   a
34   "     | 66   B     | 98   b
35   #     | 67   C     | 99   c
36   $     | 68   D     | 100  d
37   %     | 69   E     | 101  e
38   &     | 70   F     | 102  f
39   '     | 71   G     | 103  g
40   (     | 72   H     | 104  h
41   )     | 73   I     | 105  i
42   *     | 74   J     | 106  j
43   +     | 75   K     | 107  k
44   ,     | 76   L     | 108  l
45   -     | 77   M     | 109  m
46   .     | 78   N     | 110  n
47   /     | 79   O     | 111  o
48   0     | 80   P     | 112  p
49   1     | 81   Q     | 113  q
50   2     | 82   R     | 114  r
51   3     | 83   S     | 115  s
52   4     | 84   T     | 116  t
53   5     | 85   U     | 117  u
54   6     | 86   V     | 118  v
55   7     | 87   W     | 119  w
56   8     | 88   X     | 120  x
57   9     | 89   Y     | 121  y
58   :     | 90   Z     | 122  z
59   ;     | 91   [     | 123  {
60   <     | 92   \     | 124  |
61   =     | 93   ]     | 125  }
62   >     | 94   ^     | 126  ~
63   ?     | 95   _     | 127  DEL

```

Trailing spaces on each line, and a trailing newline are permitted. Since this is a challenge, your submission may not take any input, or access any external resources (such as a file or the web), and your goal is to compress the code to output this text as much as possible.

Standard loopholes apply, and the shortest answer in bytes wins. Happy golfing!

# Answer
> 11 votes
## Python ~~2~~ 3.6, ~~185~~ ~~183~~ ~~175~~ ~~159~~ 156 bytes

Saved 8 bytes thanks to FlipTack!

Still quite new to golfing in Python.

```
for a in["Dec  Chr   | "*3,"-"*39]+["".join(f"{l:<5}{('Space',chr(l),'DEL')[(l>32)+(l>126)]:<6}| "for l in(i,32+i,64+i))for i in range(32,64)]:print(a[:-5])

```

Uses a nested list comprehension to generate the table body.

Ungolfed:

```
lines =   \
  ["Dec  Chr   | "*3, "-"*39] +                      # first two lines
    ["".join(                                        # join 3 parts of each line
      f"{l:<5}{('Space',chr(l),'DEL')[(l>32)+(l>126)]:<6}| "
        for l in (i,32+i,64+i)                       # generate 3 parts of a line
      )
      for i in range(32,64)]

for line in lines: print line[:-5]

```

Update: apparently using f-string here is shorter than the `%` operator.

---

### Old attempt, ~~185~~ ~~183~~ 175 bytes

```
print("Dec  Chr   | "*3)[:-5]+"\n"+"-"*34
a=lambda x:('Space',chr(x),'DEL')[(x>32)+(x>126)]
for l in range(32,64):print("%-5d%-6s| "*3%(l,a(l),l+32,a(l+32),l+64,a(l+64)))[:-5]

```

Ungolfed:

```
print ("Dec  Chr   | "*3)[:-5] + "\n" + "-"*34
def a(x):
    return "Space" if x==32 else "DEL" if x==127 else chr(x)
for line in range(32,64):
    print ("%-5d%-6s| "*3 % (line, a(line), line+32, a(line+32),
      line+64, a(line+64))) [:-5]

```

# Answer
> 6 votes
# Befunge, ~~176~~ 172 bytes

```
<v"Dec  Chr   "0
^>:#,_$1+:2`#v_" |",,
\:#->#1_55+,v>55+,"!-":>,#:
+2*,:"_"`#@_v>1+:8-#v_$1+:3%!:7g,!29+*5
*84+1%3\/3::<^,gg00:<`"c"p00+5+`"~"\`*84::p62:.:+*
  Space

| DEL

```

Try it online!

# Answer
> 6 votes
# Pyth, ~~89~~ ~~85~~ ~~79~~ 77 bytes

```
PP*"Dec  Chr   | "3*\-34V32PPsm++.[`=+N32;5.[?qN32"Space"?qN127"DEL"CN;6"| "3

```

Try it online!

# Answer
> 5 votes
## JavaScript (ES6), ~~179~~ 173 bytes

```
f=n=>n?(n>>6?' | ':`
`)+n+(99<n?'  ':'   ')+(126<n?'DEL':String.fromCharCode(n)+'    '+f(n>95?n-63:n+32)):`${x='Dec  Chr   '}| ${x}| ${x}
${'-'.repeat(34)}
32   Space`+f(64)

console.log(f())
```

# Answer
> 5 votes
## F#, 222 bytes

```
let c,p=String.concat" | ",printfn"%s"
Seq.replicate 3"Dec  Chr  "|>c|>p
p(String.replicate 34"-")
for i=32 to 63 do[for j in[i;i+32;i+64]->sprintf"%-5d%-5s"j (match j with 32->"Space"|127->"DEL"|_->string(char j))]|>c|>p

```

Try it online!

# Answer
> 5 votes
# , ~~98, 96~~, 94 bytes

```
i32 | 64 | 9631ñÙl.l.ñÍä«/&   &
ÎéiD@"
bsDELF 27kdH5lRSpaceÄÒ-Ä3RDec  Chr³ | Î35|D

```

Try it online!

Just *barely* squeaking in under a hundred. I'm gonna see if I can beat Pyth, but I won't make any promises.

Here is a hexdump:

```
00000000: 6933 3220 7c20 3634 207c 2039 361b 3331  i32 | 64 | 96.31
00000010: f1d9 016c 2e6c 2ef1 cde4 ab2f 2620 2020  ...l.l...../&
00000020: 1616 2620 2020 200a cee9 6944 4022 0a62  ..&    ...iD@".b
00000030: 7344 454c 1b46 2016 3237 6b64 4835 6c52  sDEL.F .27kdH5lR
00000040: 5370 6163 651b c4d2 2dc4 3352 4465 6320  Space...-.3RDec
00000050: 2043 6872 b320 7c20 1bce 3335 7c44        Chr. | ..35|D

```

And here's how it works:

```
i32 | 64 | 96<esc>      " Insert some starting text
31ñ          ñ          " 31 times:
   Ù                    "   Duplicate this line
    <C-a>               "   Increment the first number on this line
         l.             "   Increment the next number
           l.           "   Increment the next number

```

Here is where it get's interesting. First, let me explain a vim-trick. While in insert mode, certain characters are inserted (all printable ASCII-characters, most unmapped characters above `0x7f`, and a few others), but other characters have a side-effect. For example, `0x1b` (`<esc>`) will escape to normal mode. `0x01` (`<C-a>`) will re-insert the last inserted text, etc. Sometimes, we want to insert these characters literally. So to insert a literal escape character, you must type `<C-v><esc>`. This works for all characters that have a side effect. So essentially, `<C-v>` is the equivalent of a backslash in languages with string literals that allow you to escape certain characters in a string.

The other useful trick with `<C-v>` in insert mode, is that it can be used to insert characters by code-point, in either Decimal, Hexadecimal, Octal, or Hexadecimal Unicode. Since we already have the numbers that correspond to certain ASCII values, we just need to put a `<C-v>` before those characters, and run the corresponding text as vim-keystrokes. This can be achieved with a regex command, and a "Do 'x' on every line" command. So we:

```
Í                       " Substitute globally:
 ä«                     "   One or more digits
   /                    " With:
    &                   "   The matched number + some spaces
        <C-v><C-v>&     "   A ctrl-v character, then the matched number again
                        "   Since ctrl-v is like a backslash, we need two to enter a literal ctrl-v character
Î                       " On every line:
 éi                     "   Insert an 'i'
   D                    "   Delete this line
    @"                  "   Run it as vim keystrokes

```

At this point, the buffer looks like this

```
32         | 64   @     | 96   `
33   !     | 65   A     | 97   a
34   "     | 66   B     | 98   b
35   #     | 67   C     | 99   c
36   $     | 68   D     | 100   d
37   %     | 69   E     | 101   e
38   &     | 70   F     | 102   f
39   '     | 71   G     | 103   g
40   (     | 72   H     | 104   h
41   )     | 73   I     | 105   i
42   *     | 74   J     | 106   j
43   +     | 75   K     | 107   k
44   ,     | 76   L     | 108   l
45   -     | 77   M     | 109   m
46   .     | 78   N     | 110   n
47   /     | 79   O     | 111   o
48   0     | 80   P     | 112   p
49   1     | 81   Q     | 113   q
50   2     | 82   R     | 114   r
51   3     | 83   S     | 115   s
52   4     | 84   T     | 116   t
53   5     | 85   U     | 117   u
54   6     | 86   V     | 118   v
55   7     | 87   W     | 119   w
56   8     | 88   X     | 120   x
57   9     | 89   Y     | 121   y
58   :     | 90   Z     | 122   z
59   ;     | 91   [     | 123   {
60   <     | 92   \     | 124   |
61   =     | 93   ]     | 125   }
62   >     | 94   ^     | 126   ~
63   ?     | 95   _     | 127

```

Now we just need some general clean up, which accounts for most of the bytes in this answer

```
bsDEL<esc>              " Change the literal 0x7f character to "DEL"
          F <C-v>27kd   " Remove a space from the lines that have too many
H5l                     " Move to the first space character
   RSpace<esc>          " And replace it with "Space"
Ä                       " Duplicate this line
 Ò-                     " And replace it with '-'s
   Ä                    " Duplicate this line
    3R                  " And replace it with three copies of the following string:
      Dec  Chr³ | <esc> " 'Dec  Chr   | '

Î35|D                   " Remove all but the first 35 characters of each line

```

# Answer
> 4 votes
# dc, 167 bytes

```
[[Space]nq]sp[[DEL]nq]sq[[ ]n]sc[Dec  Chr]dsen[   | ]dsfnlenlfnlen10P34[[-]n1-d0<a]dsax10P0[[32+dndZ2=c[  ]ndd32=pd127=qP[    ]n]dswx[ | ]nlwx[ | ]nlwx10P95-d32>b]dsbx

```

Try it online!

How it works:

```
[[Space]nq]sp     # p is a macro that prints "Space" and then quits from the call one level up
[[DEL]nq]sq       # q is a macro that prints "DEL" and then quits from the call one level up
[[ ]n]sc          # c is a macro that prints a space
[Dec  Chr]dsen    # Save the string "Dec  Chr" in register e, and print it.
[   | ]dsfn       # Save the string "   | " in register f, and print it.
len               # Print "Dec  Chr" again.
lfn               # Print "   | " again.
len               # Print "Dec  Chr" again.
10P               # Print a newline.
34                # Push 34 on the stack.

[[-]n1-d0<a]dsa   # a is a macro that repeatedly prints "-" and decrements the top of the stack, while the top of the stack is positive.

x10P              # Execute macro a, followed by a newline. (This prints the line of hyphens.)

0                 # Push 0 on the stack.

[                 # Starting a large macro (which will be stored in register b) for printing the table row by row.

[32+dndZ2=c[  ]ndd32=pd127=qP[    ]n]dsw

                  # w is a macro which:
                        (1) adds 32 to the top of the stack;
                        (2) prints it as a number;
                        (3) uses Z to compute the number of characters the number required to print that number;
                        (4) if it required 2 characters to print the number, calls the macro c to print an extra space
                        (5) prints the string "Space" (for ASCII code 32) or the string "DEL" (for ASCII code 127) or the appropriate character, followed by the right number of spaces

x                 # Execute macro w to print an entry in column 1.
[ | ]n            # Print a column divider.
lwx               # Execute macro w to print an entry in column 2 (ASCII code 32 higher than the previous entry).
[ | ]n            # Print a column divider.
lwx               # Execute macro w to print an entry in column 3 (ASCII code 32 higher than the previous entry).

10P               # Print a newline.
95-               # Subtract 95 to adjust to go to the beginning of the next line.

d32>b             # If the top of stack is <= 32, execute macro b again, effectively looping to print all the rows of the table.

]dsb              # End the definition of the large macro, and store it in register b.

x                 # Execute the macro that's in b (with 0 at the top of the stack initially).

```

# Answer
> 4 votes
## Perl, 120 bytes

```
$,="| ";say+("Dec  Chr   ")x3;say"-"x32;say map{sprintf"%-5s%-6s",$_,$_-32?$_-127?chr:DEL:Space}$_,$_+32,$_+64for 32..63

```

Run with `-E` flag:

```
perl -E '$,="| ";say+("Dec  Chr   ")x3;say"-"x32;say map{sprintf"%-5s%-6s",$_,$_-32?$_-127?chr:DEL:Space}$_,$_+32,$_+64for 32..63'

```

*-2 bytes thanks to @G B.*

# Answer
> 3 votes
# C, 179 bytes

```
i;f(){for(;i++<37;)printf(i<4?"Dec  Chr%s":"-",i<3?"   | ":"\n");printf("\n32   Space | ");for(i=64;i<127;i+=i>95?-63:32)printf("%-5d%-6c%s",i,i,i>95?"\n":"| ");puts("127  DEL");}

```

Try it online!

Semi-ungolfed:

```
i;
f() {
  for(;i++<37;) printf(i<4?"Dec  Chr%s":"-",i<3?"   | ":"\n");

  printf("\n32   Space | ");
  for(i=64;i<127;i+=i>95?-63:32) printf("%-5d%-6c%s",i,i,i>95?"\n":"| ");
  puts("127  DEL");
}

```

# Answer
> 3 votes
# , ~~151~~ ~~150~~ ~~148~~ ~~136~~ ~~135~~ ~~130~~ ~~129~~ 125 bytes

*12 bytes saved thanks to @nmjcman101 for using `<C-v>g<C-a>` for the numbers instead of `line('.')`*

*2 byte saved thanks to @DJMcMayhem for removing lines with leading spaces using `ÇÓ/d` and by using  to remove extra spaces and rearranging stuff*

This answer is in competition with @nmjcman101's V answer (which uses `:set ve=all`). ~~But now, I found a way to remove those `A ^[`s and saved some bytes and we are at an even bytecount~~

```
iSpace
¬!~Ó./&ò
iDELí^/31
HlgGo| 63ÙkGld/Sp
$p/`
G$d/@
$p/64
G$d/S
$pÇÓ/d
/d
hdê/32
O34é-O!| !| !Ó!/Dec  Chr
```

Try it online!

Hexdump:

```
00000000: 6953 7061 6365 200a 1bac 217e d32e 2f26  iSpace ...!~../&
00000010: f20a 6944 454c 1bed 5e2f 3331 2020 200a  ..iDEL..^/31   .
00000020: 1648 6c67 0147 6f7c 201b 3633 d96b 1647  .Hlg.Go| .63.k.G
00000030: 6c64 2f53 700a 2470 2f60 0a16 4724 642f  ld/Sp.$p/`..G$d/
00000040: 400a 2470 2f36 340a 1647 2464 2f53 0a24  @.$p/64..G$d/S.$
00000050: 70c7 d32f 640a 2f64 0a68 64ea 2f33 320a  p../d./d.hd./32.
00000060: 4f1b 3334 e92d 4f21 7c20 217c 2021 1bd3  O.34.-O!| !| !..
00000070: 212f 4465 6320 2043 6872 2020 20         !/Dec  Chr

```

### Explanation (uncomplete and outdated)

The strategy here is that I'm using the line numbers to generate the ASCII code points.

Note: `^[` is `0x1b`, `^V` is `C-v`

First we generate all the characters.

```
iSpace             " insert Space
^[¬!~              " insert every character between ! and ~

```

The current buffer looks like

```
Space
!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~

```

Now we insert a newline between these characters

```
     Ó./&ò         " insert a newline before every character (:s/./&\r/g)

```

# Answer
> 3 votes
## Ruby, 124 bytes

```
 puts [["Dec  Chr   "]*3*"| ",?-*34,(0..31).map{|d|(1..3).map{|x|"%-5s%-6s"%[y=x*32+d,y<33?"Space":y>126?"DEL":y.chr]}*"| "}]

```

# Answer
> 3 votes
# , ~~130~~ ~~120~~ 99 bytes

Sub 100 club. I'm no longer convinced that `:se ve=all` is the best way of doing this. It's an extra... 11 bytes just for writing the `|`'s! But that's what I have.

I'm posting this almost in competition with @KritixiLuthos answer using `:se ve=all` to avoid some `A <esc>`'s. I'm not convinced that either method is better yet, so hopefully this can inspire some golfing on both parties and see which method takes the cake.

I'm also half expecting @DJMcMayhem to kick both our pants

```
iSpace
¬!~Ó./&ò
iDELí^/31
Hlg:se ve=all
12|êr|2ñ031j$x)PñHd)ÄÒ-Ä3RDec  Chr³ | /d
hdêÎ35|D

```

Try it online!

Hexdump for the curious (if there's interest I'll just change this to a vim-style hidden character block)

```
00000000: 6953 7061 6365 0a1b ac21 7ed3 2e2f 26f2  iSpace...!~../&.
00000010: 0a69 4445 4c1b ed5e 2f33 3120 2020 0a16  .iDEL..^/31   ..
00000020: 486c 6701 3a73 6520 7665 3d61 6c6c 0a31  Hlg.:se ve=all.1
00000030: 327c 16ea 727c 32f1 3016 3331 6a24 7829  2|..r|2.0.31j$x)
00000040: 50f1 4864 29c4 d22d c433 5244 6563 2020  P.Hd)..-.3RDec
00000050: 4368 72b3 207c 201b 2f64 0a68 64ea ce33  Chr. | ./d.hd..3
00000060: 357c 44                                  5|D

```

# Answer
> 3 votes
# AWK, 200 bytes

```
BEGIN{b="-----------";a="Dec  Chr   ";print a"|",a"|",a"\n-"b b b;for(a=31;a++<63;){printf"%-5d%-6s| %-5d%-6c| %-5d%-5s\n",a,a<33?"Space":sprintf("%c",a),a+32,a+32,a+64,a<63?sprintf("%c",a+64):"DEL"}}

```

Formatted:

```
BEGIN {
  b="-----------"
  a="Dec  Chr   "
  print a"|",a"|",a"\n-"b b b
  for(a=31;a++<63;) {
    printf "%-5d%-6s| %-5d%-6c| %-5d%-5s\n",
      a,    a<33 ? "Space" : sprintf("%c", a),
      a+32, a+32,
      a+64, a<63 ? sprintf("%c", a+64) : "DEL"
  }
}

```

Try it online!

# Answer
> 2 votes
# Tcl, 233 bytes

```
lassign {"Dec  Chr" "   | " 31} h S i
set H $h$S$h$S$h\n[string repe - 34]
proc p x {format %-5d%c $x $x}
time {set H "$H
[p [incr i]]  $S[p [expr $i+32]]  $S[p [expr $i+64]]"} 32
puts [regsub {\ {8}} [regsub \177 $H DEL] "   Space"]

```

Try it online!

# Answer
> 2 votes
## C 188 Bytes

```
f(){i=31;printf("Dec Chr | Dec Chr | Dec Chr");printf("\n--------------------------");for(;i<63;i++)printf("\n%d%4c  | %d%4c  | %d%4c",(i+1),(i+1),(i+33),(i+33),(i+65),(i+65));puts("DEL");

```

Normally looks like this:

```
f()
{
    int  i=31;
    printf("Dec Chr | Dec Chr | Dec Chr");
    printf("\n--------------------------");
    for(;i<63;i++)
      printf("\n%d%4c  | %d%4c  | %d%4c", (i+1),(i+1),(i+33),(i+33),  (i+65),(i+65));
    puts("DEL");
}

```

# Answer
> 2 votes
## C (249 bytes)

Newlines added for clarity.

```
#define L(s,e)for(i=s;i<e;++i)
#define P printf
main(i){L(0,3)P("Dec  Chr  %s",i<2?" | ":"\n");
L(0,34)P("-");P("\n");L(32,64){P("%-5d", i);
i==32?P("Space"):P("%-5c",i);
P(" | %-5d%-5c | %-5d ",i+32,i+32,i+64);
i==63?P("DEL"):P("%-5c",i+64);P("\n");}}

```

# Answer
> 2 votes
# Java, 434 422 321 bytes

```
class A{public static void main(String[]a){
    int k=1,r,s=32;
    for(;k<4;k++)
        o("Dec   Chr  ",k);
    for(;k<37;k++)
        o("-",k==36?3:4);
    for(k=r=s;!(k==64&&r==-63);r=k>95?-63:s,k+=r)
        o(k+"   "+((k>99)?"":" ")+(k==s?"Space":k==127?"DEL  ":((char)k+"    ")),k/s);
    }
    static void o(String s,int j){
        System.out.print(s+(j==4?"":j==3?"\n":"|"));
    }
}

```

Java is probably not the best language for this as there is the overhead of classes and main method...

You can eliminate main method using a static declaration, reducing the byte count down further:

```
class A{
    static{...}

```

but this results in an error (after otherwise successfully running):

```
Exception in thread "main" java.lang.NoSuchMethodException: A.main([Ljava.lang.String;)
    at java.lang.Class.getMethod(Class.java:1786)
    ...

```

The byte count does int include newlines or indentation.

# Answer
> 2 votes
# PHP, ~~163 149~~ 147 bytes

```
<?=($p=str_pad)(D,31,"ec Chr   | D"),$p("
",32,"-");whhile($i<96)printf("%s%-4d%-6s",$i%3?"| ":"
",$o=$i%3*32+32+$i/3,$i++?$i<96?chr($o):DEL:Space);

```

**breakdown**

```
                        # print header
<?=($p=str_pad)(D,31,"ec Chr   | D"),$p("\n",32,"-");
while($i<96)            # loop $i from 0 to 96
    printf("%s%-4d%-6s",    # print formatted:
                            # string, 4 space decimal leftbound, 6 space string leftbound
        $i%3?"| ":"\n",                 # linebreak for 1st column, pipe+space else
        $o=$i%3*32+32+$i/3,             # ($i mapped to) ASCII value
        $i++?$i<96?chr($o):DEL:Space    # character
    );

```

Using `%-N` is worth the byte that rightbound numbers and character would save.

# Answer
> 2 votes
# , ~~235 228 221~~ 212 bytes

```
y=apply(rbind(rep("Dec  Chr  ",3),1,matrix(sapply(1:96,function(i)paste(i+31,rep(" ",i<69),"if"(i<2,"Space","if"(i>95,"DEL",intToUtf8(c(i+31,rep(32,4))))))),nrow=32)),1,paste,collapse=" | ")
y[2]=strrep("-",34)
y

```

Try it online!

I tried really hard to get under 200 bytes but these `paste` and `collapse` are killing me. Returns a list of lines.

# Answer
> 2 votes
# Stax, 53 bytes

```
éV ►Γ┐º╬¼1N_◄╒0└♀α→┴♂┐Y♣╟n»┤3°k⌡{═╥I⌂╜<─W}íè7Y♠Σ▲ÿb#√

```

Run and debug it

# Answer
> 1 votes
# Python 2, ~~1564~~ 218 bytes

My first golf, sorry for obvious mistakes

```
print("Dec  Chr   | "*3)[:-2]+"\n"+"-"*34+"\n32   Space | 64   @     | 96   `"
for n in range(33,63):print"| ".join([str(n+x).ljust(5)+chr(n+x).ljust(6)for x in [0,32,64]])
print"63   ?     | 95   _     | 127  DEL"

```

Try it online!

Incase you're wondering, the first version was a base64 encoded string.

# Answer
> 1 votes
# Perl, ~~165~~ 155 bytes

```
$s='Dec  Chr   ';$_=join"\n",("$s| $s| $s","-"x34,map{join"| ",map{sprintf'%1$-5d%1$-6c',$_}($_,$_+32,$_+64)}32..63);s/ {8}/   Space/;s/\x7f.*/DEL\n/;print

```

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

```
a="Dec  Chr   | ".repeat(2)+"Dec  Chr\n"+"-".repeat(34);for(b=32;64>b;b++)a+="\n"+b+"   "+(32==b?"Space  ":String.fromCharCode(b)+"      ")+"| "+(b+32)+"   "+String.fromCharCode(b+32)+"     | "+(b+64)+(35<b?"  ":"   ")+(63==b?"DEL":String.fromCharCode(b+64))

console.log(a)

```

# Answer
> 1 votes
# PowerShell, 159 bytes

```
,'Dec  Chr'*3-join'   | '
'-'*34
32..63|%{($_,($_+32),($_+64)|%{"$_".PadRight(5)+"$(([char]$_,('Space','DEL')[$_-ne32])[$_-in32,127])".padRight(5)})-join' | '}

```

Try it online!

The first two lines are just creating literal strings and leaving them on the pipeline. The first uses the comma operator `,` to create an array, and then `-join`s that array together to create the headers. The second is just a straight string multiplication.

The third line loops over `32..63` and each iteration sends three values `$_`, `($_+32)`, and `($_+64)` into an inner loop. The inner loop does a `PadRight` on the value (adds the appropriate spaces to pad to `5` characters). That is then string concatenated `+` with the result of a nested pseudo-ternary `( )[ ]`. The pseudo-ternary selects either the `char` representation of that number, or else `Space` or `DEL` if it's the appropriate value. Again, we `PadRight` the appropriate characters.

Those three strings (for example, `32 Space`, `64 @`, `96 ``) are encapsulated in parens and `-join`ed with the column markers into a single string. Each of those 32 strings are then left on the pipeline. At the end of execution, an implicit `Write-Output` inserts a newline between elements on the pipeline, so we get that for free.

# Answer
> 1 votes
# 05AB1E, ~~82~~ 76 bytes

```
žQSDÇƵQ¸«.Bsð”‡²”:"DEL"¸«.B)øvyð2×ý})3äøvy… | ©ý}®”†…  Chr  ÿ”3×¨¨'-34×.Á.Á»

```

Try it online!

Still golfing, this can be improved a lot.

---

`žQSDÇƵQ¸«.Bsð”‡²”:"DEL"¸«.B)ø` pushes padded numbers with text equivalent:

```
[['32 ', 'Space'], ['33 ', '!    '], ['34 ', '"    '], ['35 ', '#    '], ['36 ', '$    '], ['37 ', '%    '], ['38 ', '&    '], ['39 ', "'    "], ['40 ', '(    '], ['41 ', ')    '], ['42 ', '*    '], ['43 ', '+    '], ['44 ', ',    '], ['45 ', '-    '], ['46 ', '.    '], ['47 ', '/    '], ['48 ', '0    '], ['49 ', '1    '], ['50 ', '2    '], ['51 ', '3    '], ['52 ', '4    '], ['53 ', '5    '], ['54 ', '6    '], ['55 ', '7    '], ['56 ', '8    '], ['57 ', '9    '], ['58 ', ':    '], ['59 ', ';    '], ['60 ', '<    '], ['61 ', '=    '], ['62 ', '>    '], ['63 ', '?    '], ['64 ', '@    '], ['65 ', 'A    '], ['66 ', 'B    '], ['67 ', 'C    '], ['68 ', 'D    '], ['69 ', 'E    '], ['70 ', 'F    '], ['71 ', 'G    '], ['72 ', 'H    '], ['73 ', 'I    '], ['74 ', 'J    '], ['75 ', 'K    '], ['76 ', 'L    '], ['77 ', 'M    '], ['78 ', 'N    '], ['79 ', 'O    '], ['80 ', 'P    '], ['81 ', 'Q    '], ['82 ', 'R    '], ['83 ', 'S    '], ['84 ', 'T    '], ['85 ', 'U    '], ['86 ', 'V    '], ['87 ', 'W    '], ['88 ', 'X    '], ['89 ', 'Y    '], ['90 ', 'Z    '], ['91 ', '[    '], ['92 ', '\\    '], ['93 ', ']    '], ['94 ', '^    '], ['95 ', '_    '], ['96 ', '`    '], ['97 ', 'a    '], ['98 ', 'b    '], ['99 ', 'c    '], ['100', 'd    '], ['101', 'e    '], ['102', 'f    '], ['103', 'g    '], ['104', 'h    '], ['105', 'i    '], ['106', 'j    '], ['107', 'k    '], ['108', 'l    '], ['109', 'm    '], ['110', 'n    '], ['111', 'o    '], ['112', 'p    '], ['113', 'q    '], ['114', 'r    '], ['115', 's    '], ['116', 't    '], ['117', 'u    '], ['118', 'v    '], ['119', 'w    '], ['120', 'x    '], ['121', 'y    '], ['122', 'z    '], ['123', '{    '], ['124', '|    '], ['125', '}    '], ['126', '~    '], ['127', 'DEL  ']]

```

---

`vyð2×ý})3äøvy… | ©ý}` joins 'em together into the table:

```
['32   Space | 64   @     | 96   `    ', '33   !     | 65   A     | 97   a    ', '34   "     | 66   B     | 98   b    ', '35   #     | 67   C     | 99   c    ', '36   $     | 68   D     | 100  d    ', '37   %     | 69   E     | 101  e    ', '38   &     | 70   F     | 102  f    ', "39   '     | 71   G     | 103  g    ", '40   (     | 72   H     | 104  h    ', '41   )     | 73   I     | 105  i    ', '42   *     | 74   J     | 106  j    ', '43   +     | 75   K     | 107  k    ', '44   ,     | 76   L     | 108  l    ', '45   -     | 77   M     | 109  m    ', '46   .     | 78   N     | 110  n    ', '47   /     | 79   O     | 111  o    ', '48   0     | 80   P     | 112  p    ', '49   1     | 81   Q     | 113  q    ', '50   2     | 82   R     | 114  r    ', '51   3     | 83   S     | 115  s    ', '52   4     | 84   T     | 116  t    ', '53   5     | 85   U     | 117  u    ', '54   6     | 86   V     | 118  v    ', '55   7     | 87   W     | 119  w    ', '56   8     | 88   X     | 120  x    ', '57   9     | 89   Y     | 121  y    ', '58   :     | 90   Z     | 122  z    ', '59   ;     | 91   [     | 123  {    ', '60   <     | 92   \\     | 124  |    ', '61   =     | 93   ]     | 125  }    ', '62   >     | 94   ^     | 126  ~    ', '63   ?     | 95   _     | 127  DEL  ']

```

---

`®”†… Chr ÿ”3×¨¨'-34×.Á.Á»` takes care of the header portion of the table:

```
Dec  Chr   | Dec  Chr   | Dec  Chr
----------------------------------
32   Space | 64   @     | 96   `
33   !     | 65   A     | 97   a
34   "     | 66   B     | 98   b
35   #     | 67   C     | 99   c
36   $     | 68   D     | 100  d
37   %     | 69   E     | 101  e
38   &     | 70   F     | 102  f
39   '     | 71   G     | 103  g
40   (     | 72   H     | 104  h
41   )     | 73   I     | 105  i
42   *     | 74   J     | 106  j
43   +     | 75   K     | 107  k
44   ,     | 76   L     | 108  l
45   -     | 77   M     | 109  m
46   .     | 78   N     | 110  n
47   /     | 79   O     | 111  o
48   0     | 80   P     | 112  p
49   1     | 81   Q     | 113  q
50   2     | 82   R     | 114  r
51   3     | 83   S     | 115  s
52   4     | 84   T     | 116  t
53   5     | 85   U     | 117  u
54   6     | 86   V     | 118  v
55   7     | 87   W     | 119  w
56   8     | 88   X     | 120  x
57   9     | 89   Y     | 121  y
58   :     | 90   Z     | 122  z
59   ;     | 91   [     | 123  {
60   <     | 92   \     | 124  |
61   =     | 93   ]     | 125  }
62   >     | 94   ^     | 126  ~
63   ?     | 95   _     | 127  DEL

```

# Answer
> 0 votes
# T-SQL, 242 bytes

```
DECLARE @ INT=32PRINT'Dec  Chr   | Dec  Chr   | Dec  Chr
'+REPLICATE('-',34)L:PRINT CONCAT(@,'   ',IIF(@=32,'Space | ',CHAR(@)+'     | '),@+32,'   ',CHAR(@+32),'     | ',@+64,SPACE(5-LEN(@+64)),IIF(@=63,'DEL',CHAR(@+64)))SET @+=1IF @<64GOTO L

```

Formatted:

```
DECLARE @ INT=32
PRINT'Dec  Chr   | Dec  Chr   | Dec  Chr
' + REPLICATE('-',34)
L:
    PRINT CONCAT(@,'   ',IIF(@=32,'Space | ',CHAR(@)+'     | ')
                ,@+32,'   ',CHAR(@+32),'     | ',
                 @+64,SPACE(5-LEN(@+64)),IIF(@=63,'DEL',CHAR(@+64)))
    SET @+=1
IF @<64 GOTO L

```

Tried a few variations, including replacing various common strings with other variables, but this was the shortest version I found.

# Answer
> 0 votes
# Python 3, 154 bytes

```
for l in[['Dec  Chr  ']*3,['-'*35]]+[[f"{x:<5}{['Space',chr(x),'DEL'][(x>32)+(x>126)]:5}"for x in(c,c+32,c+64)]for c in range(32,64)]:print(' | '.join(l))

```

Try it online!

# Answer
> 0 votes
# Attache, 144 bytes

```
(p:=PadRight)["",37,"Dec  Chr   | "]'(34*"-")'(Join&"| "=>Tr@ChopInto&3<|{p&11<|p&5@Repr@_+(<~32->$Space,127->$DEL~>@_or Char!_)}=>32:127)|Print

```

Try it online!

---
Tags: code-golf, string, ascii-art, kolmogorov-complexity
---


title: Cracking in progress

text:
# Question
Title: Cracking in progress
Remember those brute-force programs to crack password that show every combination they are trying? More precisely, at one point, the *n* first characters are fixed (they have been guessed successfully), and every possible character for the remaining ones is being tested. You've probably seen some in movies, or in some software written by people that like fancy interfaces.
Sorry to disappoint, but we won't write a program to crack password, only one to reproduce the nice output.

### Challenge

Given a string containing printable ascii characters but no newlines (ascii code 32 to 126 or matching the regex `^[ -~]{2,}$`), print an output following this rules:

* At time `t=n seconds`, the `n` first characters printed are the `n` first characters of the input string.
* After the `n` fixed characters, you should append a string formed random character (chosen uniformly pseudo-randomly from the unicode range  to `~` (code 32 to 126)) to form a string of the length of the initial one.
* You should output *at least* (more on that later) 20 lines every second: every one of them will have the same `n` first characters, but a different random end.

It's probably not very clear yet what you are supposed to do, so lets go through an example:

### Example

*I'll print only 5 different lines for every seconds instead of the 20 minimum just to make it more readable.*

Consider the input `abcde`.
During the first second, a valid output can be something like (completely random):

```
dGuT4
S!jkN
"gQ>[
TU3!
*fAjV

```

Then, `t=1`, the first character of every following string will be `a` (the first character of the input):

```
a);jD
aHv^p
aqw5*
a|.?:
a{gbK

```

Now, `t=2`, the first two characters will be `ab`:

```
abTJ"
ab\ e
ab3T#
abYWS
ab"#<

```

Now, `t=3`, the first three characters will be `abc` :

```
abcvW
abc3G
abc(g
abc{@
abc@4

```

Now, `t=4`, the first four characters will be `abcd` :

```
abcdD
abcdv
abcdj
abcd$
abcd6

```

Finally, `t=5`, we print the input (only once):

```
abcde

```

### A few precisions

* You shouldn't bother too much with your language precision toward the seconds (ie. If your algorithm is correct but your system/language lacks precision then it's fine).
* The first second can be shorter than one second (That is, if you launch you program during a second, the first second can be just the remaining time until the end of the current second). Or put differently, you don't have to wait for the start of a new second to start printing the outputs.
* *At least 20 lines per second*: The more natural way would be an infinite loop with a special behaviour one every second (or a timeout, or whatever), so that will result in probably a few thousand lines per second (and that's perfectly fine!). But if you have another idea, feel free to use it as long as you print at least 20 lines per second.
* The input will always be more than 2 characters long.
* You can consider that the input won't be more that 30 characters long if it helps. (But if it works for longer ones, it's for the best)
* The input format should be the most natural representation of a string in your language.
* You are allowed to print a trailing newline.

### Code example

If you still don't understand exactly what you have to do, you can run the following code in a linux terminal to see:

```
perl -F -aplE 'map{$t=time;print$s,map{chr 32+rand 94}@F until$t-time;$s.=shift@F}@F' <<< "Cracking in progress\!"

```

### Winning criterion

This is , so shortest code in byte wins!

---

*Thanks to Laikoni and Flp.Tkc for their suggestions and improvement in the sandbox.*

# Answer
# Pyth - ~~27~~ 24 bytes

This actually looks pretty cool :D

```
WJ-lQKs.d1+<QKsmOr;\~J;Q

```

Try it online here (obviously not in real time, but if you scroll it down with a steady hand).
> 3 votes

# Answer
## HTML/JavaScript, ~~170~~ ~~168~~ 167 bytes

```
setInterval('o.textContent=i.value.replace(/./g,(c,i)=>new Date-d>++i*1e3?c:String.fromCharCode(Math.random()*95+32))',d=50)
```

```
<input id=i oninput=d=Date.now()><pre id=o>
```

Edit: Saved 2 bytes thanks to @ETHproductions. Saved 1 byte thanks to @jrich.
> 28 votes

# Answer
# Node, ~~145~~ 142 bytes

```
for(s=process.argv[2],d=new Date;s[a=(new Date-d)/1e3|0]+console.log(s.replace(/./g,(c,i)=>i<a?c:String.fromCharCode(32+Math.random()*95))););

```

This seems a little long, and there's probably a little room for golfing. Note that the semicolon at the end is required; without it the program throws a syntax error because the `for` statement has no body.

Outputs way more than 20 lines per second; a little birdie told me that it's roughly 12 thousand. Here's how it looks in the ConEmu terminal emulator on my computer (recorded at 30 fps):
> 20 votes

# Answer
# 05AB1E, 26 bytes

I post this as a different answer with respect to the other 05AB1E answer since the approach is different

```
.põ¸ì¨vT·FyžQ.r¹gyg-£«}}¹»

.p                         Generate ordered prefix of input (e.g., ["a", "ab", "abc", "abcd", "abcde"] for "abcde")
  õ¸ì                      Prepend an empty string (e.g., result is ["", "a", "ab", ...])
     ¨                     Strip the last element (the same string as the input)
      v                    For each string in the array
       T·F                 For N in range(20)
          y                Push the current string
           žQ.r            Push all printable characters, shuffled
               ¹gyg-       Take the difference between the length of the input and the length of the current string -> x
                    £      Take the x first characters from the shuffled printable characters
                     «     Yield currentString + shuffledCharacters
                      }    End inner for
                       }   End outer for
                        ¹  Push input (last iteration)
                         » Join everything with newlines and implicitly display

```

Try it online!
> 10 votes

# Answer
## BASH, 99 93 92 91 88 bytes

with `tr` \+ `head` \+ `urandom`

```
while ((${#1}-n));do
echo "${1::n=SECONDS}`tr -dc \ -~</dev/ur*|head -c$[${#1}-n]`"
done

```

(thx. to @manatwork )
> 8 votes

# Answer
# 05AB1E, 30 bytes

```
gFžcUNV[¹Y£žQ.r¹gY-£J,XžcÊ#}¹,

```

Uses the **CP-1252** encoding. Try it online!

Please help me golf this down.
> 7 votes

# Answer
# C, ~~182~~ ~~176~~ ~~128~~ ~~126~~ 125 bytes

Golfed:

```
i;s;n;x;g(char*c){time(&s);while(c[++x]);do{n=time(0)-s;for(i=0;i<x;i++)putchar(i<n?c[i]:32+rand()%95);puts("");}while(n<x);}

```

Ungolfed:

```
#include "stdio.h"
#include "stdlib.h"
#include "time.h"
int i,s,n,x;
void g(char* c) {
  time(&s); //Get the initial time
  while(c[++x]); // x = strlen(c) (happy about this one)
  do {
    n = time(0) - s; //seconds since beginning
    for(i = 0; i < x; i++)
      //after each second, print another char of the password
      putchar(i < n ? c[i] : 32 + rand() % 95);
    puts("");
  } while(n < x); //while we haven't printed the whole word
}

```

~~I've heard that it's possible to drop some standard `#include`s, but I couldn't get it to work on the MingW GCC compiler I just downloaded. Also couldn't figure out how to `#define b #include` without using more space than it was worth.~~ I'm just an idiot, it works fine without them.
> 6 votes

# Answer
# Java 7, ~~271~~ ~~265~~ 207 bytes

```
void c(String s)throws Exception{for(int i=0,j,l=s.length();i<=l*20;i++){String r=s.substring(0,i/20);Thread.sleep(45);for(;j++<l;r+=(char)(32+Math.random()*95);System.out.println(r);if(s.equals(r))return;}}

```

-58 bytes saved thanks to *@OliverGrégoire*. (Don't forget to upvote his even shorter Java 8 answer.)

**Ungolfed:**

```
void c(String s) throws Exception{
  for(int i = 0, j, l = s.length(); i <= l*20; i++){
    String r = s.substring(0, i/20);
    Thread.sleep(45);
    for( ; j++ < l; r += (char)(32+Math.random()*95));
    System.out.println(r);
    if(s.equals(r)){
      return;
    }
  }
}

```

**Input:** `abcde`
**Output:**
> 5 votes

# Answer
# MATL, 26 bytes

```
`GZ`:)' ~'olGn4Mk-I$YrhD7M

```

Try it online!

Below is the real-time output from the offline compiler. Note that the animated GIF was recorded at 20 fps to keep its size small, but the actual speed is much greater.

# How it works

```
           % Implicitly start timer
`          % Do...while
  G        %   Push input
  Z`       %   Push timer's current value, say t
  :)       %   Select the first t elements of the input, with t
           %   implicitly rounded down
  ' ~'     %   Push this string
  o        %   Convert to numbers, i.e. [32 126]
  l        %   Push 1
  Gn       %   Push input size, say n
  4Mk      %   Push floor(t), where t is the same value used above
  k        %   Subtract. Gives n-floor(t)
  I$Yr     %   Generate a row vector of n-floor(t) integers randomly
           %   chosen from 32 to 126
  h        %   Concatenate with the first characters of the input
  D        %   Display
  7M       %   Push the value n-floor(t) used above. This is used
           %   as loop condition: iz zero the loop is exited
           % Implicit end

```
> 4 votes

# Answer
# Bash, ~~247~~ ~~245~~ ~~212~~ 207 bytes

```
R()(echo $SECONDS);w=`R`;until [ "$a" = "$1" ];do for i in `seq 1 $[${#1}-${#a}]`;{ a+=`printf "\x$(printf %x $[$RANDOM%127+32])"`;};echo -e "$a\r";a=${1:0:q};((`R`-w>0))&&{ w=`R`;((q++));}||:;done;echo "$a"

```

*Thanks a lot Bash for being so whitespace sensitive...*

Anyways, output is given in real time on separate lines. Save as a `.sh` script and invoke with:

`bash <File Name>.sh <Input>`

For example, `bash Cracking_In_Progress.sh okayerty` results in the following output, recorded at 30 frames per second:
> 4 votes

# Answer
# WinDbg, ~~400~~ 391 bytes

```
.for(r$t1=@$t0;by(@$t1);r$t1=@$t1+1){};m@$t0 L@$t1-@$t0+1 @$t1+1;r$t4=2*@$t1+2-@$t0;r$t8=@$t4+f;r$t3=0;.for(r$t2=0;@$t2<@$t1-@$t0;da@$t0){.for(r$t7=@$t0+@$t2;by(@$t7);r$t7=@$t7+1;r$t8=@$t8+1){eb@$t7 by(@$t8)%5e+20};r$t9=0;.foreach(p {.echotime}){.if7==@$t9{ea@$t4"p";.if1>@$t3{r$t3=by(@$t4+7)}};r$t9=@$t9+1};j@$t3!=by(@$t4+7)'m@$t0+@$t4-@$t1+@$t2-1 L1 @$t0+@$t2;r$t2=@$t2+1;r$t3=by(@$t4+7)'}

```

*-9 bytes by simplifying some math*

This definitely does not seem to be the kind of thing WinDbg is intended to do. ;)

Input is taken by entering an ascii string at a memory location and setting that address to the pseudo-register `$t0`. Eg:

```
r$t0 = 2000000
eza @$t0 "abcde"

```

The prng I'm using is whatever the contents in memory, some bytes past the input string. Chrome.exe appears to fill the memory space after `0x2000000` with random-looking-enough bytes so I used a dump of chrome.exe. Unknown if this is uniform, but looks random-enough to me.

How it works:

```
.for(r$t1=@$t0; by(@$t1); r$t1=@$t1+1){};         * From $t0, increment $t1 until the byte
                                                  * at $t1 is 0 to find length of input
m@$t0 L@$t1-@$t0+1 @$t1+1;                        * Duplicate input (memory
                                                  * becomes: "input\0input\0")

r$t4=2*@$t1+2-@$t0;                               * Set $4 to the byte after \0 of the
                                                  * duplicated input
r$t8=@$t4+f;                                      * Set $t8 to $t4+15, this is the prng
r$t3=0;                                           * Init $t3=0, this will hold the time

.for(r$t2=0; @$t2<@$t1-@$t0; da@$t0){             * For $t2=0, loop until it's input length,
                                                  * printing the string at $t0 after each
                                                  * loop. $t0 is where the password crack
                                                  * progress is written.
    .for(r$t7=@$t0+@$t2; by(@$t7); r$t7=@$t7+1;   * Loop over each uncracked char
                                   r$t8=@$t8+1){  * also incrementing prng ($t8)
        eb@$t7 by(@$t8)%5e+20                     * Write a visible ascii char onto the
                                                  * uncracked char position based on the
                                                  * current byte of prng%0x5e+0x20 (prng%126+32)
    };

    r$t9=0;                                       * Set $t9=0 for updating current time
    .foreach(p {.echotime}){                      * For each (string) word in a statement
                                                  * like "Debugger (not debuggee) time: Mon
                                                  * Nov 21 18:23:08.433 2016 (UTC - 8:00)"
        .if7==@$t9{                               * If the 7th word, ie- the current time
            ea@$t4"p";                            * Write the time at $t4
            .if1>@$t3{                            * If $t3 has not been set yet
                r$t3=by(@$t4+7)                   * ...save the current second in $t3
            }
        };
        r$t9=@$t9+1                               * Increment $t9 until it's 7
    };

    j@$t3!=by(@$t4+7)'                            * If the current second has changed
        m@$t0+@$t4-@$t1+@$t2-1 L1 @$t0+@$t2;      * Copy the cracked char from dupe input
        r$t2=@$t2+1;                              * Increment $t2 (loop ends when this is input length)
        r$t3=by(@$t4+7)                           * Save the new current second
    '
}                                                 * Final crack is printed by for loop

```

Note: Some bytes could be golfed by using `j` instead of the `.if`'s, but that causes it to run too slowly on my machine so it doesn't output at least 20 lines per second, so not saving those bytes.

Sample Output: http://pastebin.com/H4H74sAx
> 4 votes

# Answer
## R, 138 bytes

```
z=Sys.time;n=nchar(x<-scan(,""));s=z();t=0;while(t<=n){t=t+z()-s;cat(substr(x,1,f<-floor(t)),intToUtf8(sample(32:126,n-f,T)),"\n",sep="")}

```

Reads input from stdin.

Counted approximately 61 lines on my machine between each additional letter in the "password".
> 4 votes

# Answer
# Haskell (GHC), 202 bytes

```
import System.Random
import Control.Concurrent
f s|l<-length s=mapM_(\n->putStr('\r':take n s)>>mapM(\_->toEnum<$>randomRIO(32,126))[1..l-n]>>=putStr>>threadDelay 50000)$[n|n<-[0..l-1],f<-[1..20]]++[l]

```

-5 bytes without fancy carriage return action
> 4 votes

# Answer
## Python 3, 167 166 bytes

```
import time,random
t=time.time
p,s=input(),t()
while t()-s<len(p):print(p[:int(t()-s)]+''.join(chr(random.randint(32,126))for _ in range(len(p)-int(t()-s))))
print(p)

```

Reads input from stdin. A 171-byte version runs under Python 2 (replaced `input` with `raw_input`):

```
import time,random
t=time.time
p,s=raw_input(),t()
while t()-s<len(p):print(p[:int(t()-s)]+''.join(chr(random.randint(32,126))for _ in range(len(p)-int(t()-s))))
print(p)

```

Ungolfed:

```
import random
import time

p = input()
start = time.time()
while time.time() - start < len(p):
    print(
        p[:int(time.time() - start)] +
        ''.join(chr(random.randint(32, 126)) for _ in range(len(p) - int(time.time()-start)))
    )
print(p)

```
> 3 votes

# Answer
# Python3, ~~149~~ ~~141~~ 139 bytes

```
import time,random
i,x=input(),0;l=len(i)
while x<l:x=int(time.clock());print(i[:x]+"".join(chr(random.randint(32,126))for _ in"a"*(l-x)))

```

Input from stdin.

Eyes version (157 bytes):

```
import time,random
p,i,x=print,input(),0;l=len(i)
while x<l:x=int(time.clock());p(i[:x]+"".join(chr(random.randint(32,126))for _ in"a"*(l-x)),end="\r")
p(i)

```
> 3 votes

# Answer
# Node.js, 134 bytes

```
for(s=[...process.argv[2]],n=new(d=Date);s[m=(new d-n)/1e3|0]+console.log(s.map((a,i)=>i<m?a:Buffer([Math.random()*95+32])).join``););

```

Similar to @ETHproductions (borrowed some of his optimizations), but otherwise takes a different approach. Uses Node's `Buffer` to handle character generation instead of the lengthy `String.fromCharCode`, which has the side benefit of letting us use `map` without much string-\>array-\>string conversion overhead.
> 3 votes

# Answer
# Dyalog APL, ~~59~~ 58 bytes

### Solution

Requires `⎕IO←0` which is default on many systems.

```
⊢⊣≢{⍵{≢⎕←⍵↑⍺,⎕UCS 32+?⍵⍴95}⍣{t≤2⊃⎕AI}⍺⊣t←1E3+2⊃⎕AI}¨⍳∘≢↑¨⊂

```

### Display

By adjusting the window to two lines, we get the illusion of an in-place transformation:

### Explanation

This is an anonymous function train which takes the password as right argument.

`⊢⊣` return the password and dismiss the result of

`≢{`... the below function, with the length of the password as left argument, applied to each of

`2⊃⎕AI` current up-time (lit. third element of **A**ccount **I**nformation)

`1E3+` add a second

`t←` assign that to *t*

dismiss that

`⍵{`...`}⍣{t≤2⊃⎕AI}⍺` apply the following function (with sub-string as  and password length as ) repeatedly until the up-time reaches *t*

`⍵⍴95` 95 repeated as many times as there are characters in the password

`?` random integer 0...94

`32+` add 32 (thus yielding  random integers in the range 32...126)

`⎕UCS` convert to Unicode character

`⍺,` prepend the currently processed sub-string

`⍵↑` take only as many character as there are in the password

`⎕←` output that on a separate line

return the length of the outputted string (= the length of the password)

`⍳∘≢` 0 ... length-1

`↑¨`each taking characters from

the password
> 3 votes

# Answer
# Java, 159 bytes

```
s->{for(int i=0,j,l=s.length();i<=l*99;i++){String r=s.substring(0,j=i/20);Thread.sleep(9);for(;j++<l;r+=(char)(32+Math.random()*95));System.out.println(r);}}

```

Same algorithm as Kevin Cruijssen's answer, only totally optimized for Java 8.

## Ungolfed:

```
public class Tmp {

  interface X {

    void f(String s) throws Exception;
  }
  static X f = s -> {
    for (int i = 0, j, l = s.length(); i <= l * 20; i++) {
      String r = s.substring(0, j = i / 20);
      Thread.sleep(48);
      for (; j++ < l; r += (char) (32 + Math.random() * 94));
      System.out.println(r);
    }
  };

  public static void main(String[] args) throws Exception {
    f.f("abcde");
  }
}

```
> 2 votes

# Answer
## C#, ~~203~~ ~~197~~ ~~195~~ 190 bytes

Golfed:

```
void F(string s){int l=s.Length,t=0;var w=Stopwatch.StartNew();do{if(w.Elapsed.Seconds>t)t++;Console.WriteLine($"{s.Substring(0,t)}{Path.GetRandomFileName().Substring(0,l-t)}");}while(t<l);}

```

Ungolfed:

```
    void F(string s)
    {
        int l = s.Length, t = 0;
        var w = Stopwatch.StartNew();

        do
        {
            if (w.Elapsed.Seconds > t)
                t++;

            Console.WriteLine($"{s.Substring(0, t)}{Path.GetRandomFileName().Substring(0, l - t)}");
        } while (t < l);
    }

```

`l` stores input length.

`StopWatch` and `Path.GetRandomFileName()` are parts of .NET framework.

EDIT1: Implicit `Stopwatch` declaration.

EDIT2: `l` initialization merged with declaration.

EDIT3: Thanks, @Chris.
> 1 votes

# Answer
# ForceLang, ~~322~~ 309 bytes

```
def s set
s g goto
s W io.writeln
s k io.readln()
s T timer.new()
def a T.poll()
label 1
s P math.floor a.mult 1e-6
if P=k.len
 W k
 exit()
s j 0
s t ""
if P=0
g 4
label 3
s v k.charAt j
s t t+v
s j 1+j
if j-P
g 3
label 4
if j=k.len
 W t
 g 1
s r 94.mult random.rand()
s v string.char 32+r
s t t+v
s j 1+j
g 4

```
> 1 votes

# Answer
# Scala, 259 254 248 233 232 231 227 225 bytes

```
import scala.concurrent.duration._;(b:String)=>{val d=b.length.seconds.fromNow;while(d.hasTimeLeft)println(b.zipWithIndex.map{case(f,g)=>if(g<b.length-d.timeLeft.toSeconds-1)f else(32+math.random*94)toChar}mkString);print(b)}

```

Ungolfed:

```
import scala.concurrent.duration._;

(b:String) => {
    val d = b.length.seconds.fromNow;
    while(d.hasTimeLeft)
        println(
            b.zipWithIndex.map{
                case(f,g) =>
                    if(g<b.length-d.timeLeft.toSeconds-1)
                        f
                    else
                        (32+math.random*94)toChar}
            mkString
        );

    print(b)
}

```
> 1 votes

# Answer
# C++ (gcc), ~~280~~ 278 bytes

```
#include<iostream>
#include<chrono>
#include<cstdlib>
#include<thread>
int i,n,t,q;void f(std::string s){for(t=s.size(),n=0;n<=t;n++)for(q=n<t?20:1;q--;std::this_thread::sleep_for(std::chrono::milliseconds(50)))for(std::cout<<"\n"<<s.substr(0,i=n);i++<t;)putchar(32+rand()%84);}

```

Try it online!

It just prints 20 random strings waiting for 50 `std::chrono::milliseconds` between each other (thus outputting exactly 20 lines per second) and then proceeds to the next "cracking" step.
> 1 votes

# Answer
# Go, 244 bytes

```
import(."fmt"
."math/rand"
."time")
func a(s string){Seed(Now().Unix())
for i:=0;i<len(s);i++{t:=Now().Truncate(Second).Add(Second)
for Now().Before(t){q:=[]rune(s)
for p:=len(q)-1;p>=i;p--{q[p]=rune(32+Intn(95))}
Println(string(q))}}
Print(s)}

```

Try it online! (truncates the result so it doesn't show every instance)

This is my first Golang answer \o/

(Filmed @ 30fps)

### How:

```
func a(s string) {                      //function a
Seed(Now().Unix())                      //Create a seed for the pRNG
for i := 0; i < len(s); i++ {           //set helper var i (this is the number of characters we'll keep)
t := Now().Truncate(Second).Add(Second) //set helper var t = 1 second from now
for Now().Before(t) {                   //while inside that 1 second window
q := []rune(s)                          //put each character in a rune slice and assign that to q
for p := len(q) - 1; p >= i; p-- {      //loops through the rune slice
q[p] = rune(32 + Intn(95))              //replace the character in position p with a random code point in [32,126]
}
Println(string(q))                      //print the rune slice as a string
}
}
Print(s)                                //finally, print the original string
}

```
> 1 votes

# Answer
# PHP, 222 bytes

```
$a=$argv[1];$c=range(32,126);$t=time();$s=$t;$e=$t+strlen($a);while(time()<=$e){$l=time();$p=$l-$s;$x=substr($a,0,$p);$k=$e-$l;$r='';for($i=$k;$i>0;$i--)$r.=chr($c[rand(0,94)]);$o=$x.$r;echo"$o\n";if($o==$a&&$l==$e)break;}

```

Ungolfed

```
<?php
$input = $argv[1];
$chars = range(32, 126); // count() is 95

$startTime = time();
$endTime = time() + strlen($input);

while (time() <= $endTime) {
    $plaintextAmountToPrint = time() - $startTime;

    $plain = substr($input, 0, $plaintextAmountToPrint);

    $cryptAmountToPrint = $endTime - time();

    $crypt = '';

    for ($i = $cryptAmountToPrint; $i > 0; $i--)
        $crypt .= chr($chars[rand(0, 94)]);

    $output = $plain . $crypt;

    echo $output . "\n";

    if ($output == $input && time() == $endTime)
        break;
}

```

(i know the video is crap)
> 0 votes

# Answer
# Tcl, 295 bytes

First golf for me in Tcl. Not a very golfable language, since everything is treated as strings here so whitespace is usually a must...

```
set l [string length $argv];set s [clock seconds];set r -1;while {$r<$l-1} {puts -nonewline [string range $argv 0 $r];set k $l;while {[set k [expr $k-1]]>$r} {puts -nonewline [format %c [expr int(rand()*95+32)]]};puts "";if {[expr [clock seconds]-$s]>[expr $r+1]} {set r [expr $r+1]}};puts $argv

```

Ungolfed:

```
set l [string length $argv]
set s [clock seconds]
set r -1
while {$r < $l-1} {                                      # loop on time
  puts -nonewline [string range $argv 0 $r]
  set k $l
  while {[set k [expr $k-1]] > $r} {                     # loop on "unfound" chars
    puts -nonewline [format %c [expr int(rand()*95+32)]]
  }
  puts ""
  if {[expr [clock seconds]-$s] > [expr $r+1]} {         # advance time
    set r [expr $r+1]
  }
}
puts $argv

```
> 0 votes

# Answer
## QBIC, ~~92~~  88 bytes

I've cracked it!

```
t=20;_LA|[a*t-t|B=$left$|(A,b/t)[a|B=B+$CHR$|(_r94|+32)]?$left$|(B,a)~b%t=0|$sleep 1|}?A

```

This relies on QBasic's SLEEP function using the code literal `$sleep 1|`, and on QBasic's `LEFT$` function because I haven't implemented that function in QBIC yet...

Managed to scrape a few bytes by substituting all the `20`'s for `t` and setting that to 20. Also, streamlined a call to random and a FOR loop.

Explanation:

```
' Get cmd line param with 'password' and the length of that string, set t to 20
t=20;_LA|

' loop from 1 (implicitly) to (#chars-1) * 20 cracks per char
[a*-t|

'have our crack-display start with the first N chars of
'the password, where N is the number of seconds passed
B=$left$|(A,b/t)

' loop to add the 'crack-visual'
' It's too long, but we'll trim it down to the original length
[a|B=B+$CHR$|(_r92|+34)]?$left$|(B,a)

' if we've done 20 cracks, sleep for 1 second
~b%20=0|$sleep 1|}

' We've cracked it!
?A

```

Output (a piece of the middle section on 'helloworld')

```
hewnoluZfs
heb!mrc2g@
hee+yh"5ut
he0?V+O)Uu
heqf(#M/BM
hez|DGX%a8
he<_n[6-.+
helkxQ#g%,
hel&^A9$I8
hel43{b5]t
helszK50%F
hel`kdy ;b
hel Vr6Z}s
helLIR7*7o

```
> 0 votes

# Answer
## Kotlin, 188 bytes

**Golfed**

```
val x=readLine()!!;val n=System::currentTimeMillis;val t=n();do{val s=(n()-t)/1000;x.mapIndexed{i,c->print(if(i<s)c else((Math.random()*(126-32))+32).toChar())};println()}while(s<x.length)

```

**Ungolfed**

```
val input = readLine()!!
val time = System::currentTimeMillis
val startTime = time()
do {
    val crackIndex = (time() - startTime) / 1000
    input.mapIndexed{ i, letter ->
        print(
            if (i < crackIndex) letter else ((Math.random()*(126-32))+32).toChar()
        )
    }
    println()
} while(crackIndex < input.length)

```

Renaming `System.currentTimeMillis` saved quite a few bytes!
> 0 votes

---
Tags: code-golf, string, random
---


title: Send the pairs in smallest output

text:
# Question
Title: Send the pairs in smallest output
Write two programs A and B.

* Program A (the encoder) takes 1024 pairs of integers \\$(k,v)\\$, where \\$0≤k\<2^{32}\\$ and \\$0≤v\<1024\\$, and all \\$k\\$ will be different. It will output a single positive integer (likely a few thousand digits long).
* Program B (the decoder) takes two inputs: the output-integer of program A, and one \\$k\\$ from the input pairs we've used as input for program A. It will output the \\$v\\$ corresponding with the given \\$k\\$.

In other words, Program A compresses 1024 key-value pairs to the smallest size possible, and Program B must use the data provided by A to recover each value given its corresponding key.

Your score is the average value of the output of program A for the test data. Hardcoding for a given test case is forbidden, so this should be essentially the same as the score on the pretest data. Pretest data and test data are drawn from the same (uniform) distribution.

Random pretest data is available here.

```
Random.txt
MD5: 6FA62A283282F5CFBC6E089B2369C9B9
SHA1: 0BF7FB62A8566575D4A948DD34A559BAAAC422FC
CRC32: 2675DAB3

Testdata.txt
MD5: 6C8F90F126C8F3C55A9FC9F22733CE55
SHA1: F7D11AAB54393DE8CC4E75565950D8C6D9CFE42A
CRC32: B3DB1479

```

Actual test cases:

https://www.mediafire.com/folder/i6hmn9zzk73ig/174035

A stupid program A that work but totally didn't optimize is here. Its program B is easily written.

# Answer
# Python 3, pretest ≈ 3.198 · 103085

```
from hashlib import sha512
import sys

def encode(pairs):  # program A
    elim = [[] for i in range(10)]
    done = set()
    code = 0
    i = 0
    while len(done) < 10 * len(pairs):
        e = 1 << i
        for a, e1 in elim[i % 10]:
            if decode(e, a) & 1 << i % 10:
                e ^= e1
        for a, b in pairs:
            if (a, i % 10) not in done and decode(e, a) & 1 << i % 10:
                elim[i % 10].append((a, e))
                done.add((a, i % 10))
                if (decode(code, a) ^ b) & 1 << i % 10:
                    code ^= e
                print("progress:", len(done), "of", 10 * len(pairs))
                break
        i += 1
    return code

def decode(code, a):  # program B
    k = -(-code.bit_length() // 8)
    a_bytes = a.to_bytes(4, "little")
    s = b"".join(
        sha512(a_bytes + i.to_bytes(4, "little")).digest() for i in range(-(-k // 64))
    )
    b = 0
    for i, (x, y) in enumerate(zip(code.to_bytes(k, "little"), s)):
        b ^= (x & y) << i * 8 % 10
    return b & 1023 ^ b >> 10

def read_pairs():
    return [tuple(map(int, line.split())) for line in sys.stdin]

def test(pairs):
    code = encode(pairs)
    for a, b in pairs:
        assert decode(code, a) == b
    print(code)

test(read_pairs())

```

### Pretest output

The encoder (program A) takes about 6 minutes to run in PyPy. Its output for the pretest is:

```
31983609135966228809777741024866634396367955850954563312910243722966419655757435319862170247982609333805811315728884450895580799383047152743378820273077053884539894357668608677003723034054150072472679319590110643492810118920515801395958239291576592748237372467748241886558720871264342908155191777359585845696600370935487361341785211913110481040589139281898484188938846817560295768498881287225642023856190028544427590648046456036574330957328066402924125404073006144179946215625958643494081212962075340324684130280414625483652805036566339457267551141894682726365505972133784971174734160698976154775811488656096461968463830423074194023690503590590775033695214423998615444187716064686144001451215863398975347419967640878071667106313050954800893007781291647431510389526738768573353015452189679155051541561231146940706328809607485776138460159591319080343284358448724370020894125934538601889550086934233091980254236012141359542061770911092807766526451019824031548581065916355093797436687555279312288875998494044065641530299531661256941700326425163573657004343895103496724901715610405315696830871086538183435694121760474073023458471744226820280782007502797691083190318324487197753443963571848733746071847847503077912802000091614327968964141450181973360651625471354587026290724846906554164924720066533282988840115094797514460217879380690461261835733295861803705394151420199059533051945944829244868440580371672125590557347324783817602474773801825029895884776404639198926793779867410515553784121435319134307253638568331529787781235084628432871984360992875472633958491882569077293145250495277979952525973740358428525766027507530317692602517027217679810063987302625422496799748842451355136627998296037177558122844929449377522984595368107136303866235523533278732324181522202203636626264487517560120680389621562028772569157498411869721766672498939022664474767985892820170334179252554511620260319259569593256276255895000364202791049913505972232782566530566341223654980901733905002516092163056581626593518077383131036496001950185439305868415290006860241666136700655660075381115903744293277973930796274779653647714016073922883203769217980038066409200998466193202329090278491648479911508276027286548829602558975386937067679077276971208214625876007703346632539055994199462748282900998214486645162277623073498410220953186861172886747394992230973314265902007187446129816157393697305312624793190210450979525381906198852578619071224265649145441460469662250448218764499047348362548750003370944772956154662554023857705149861774126960045122299555516709305181620013892453158471100545618056605123335183465355868672237737792628988379889459029444873409805140995088383991356246685699313569301017907549835057806089472106637383136584875471496123974387658318450782138871582131161643221907721116143710024435066884630344739171885220542678102635637192667329306874983507141585026570891055701250722003923329858567937864129882737742073320064153568198296932909448928951903564049064190959836027425436414766746048788435990514173396582362591284614310722316033029018983309186148295917238363165751109139219360789557442877663768774219

```

which you can use to verify the much faster decoder (program B) if you don’t want to wait for the encoder.

### How it works

The decoder expands \\$a\\$ into a deterministic pseudorandom stream using SHA-512, bitwise ANDs the stream with the code (output of program A), and bitwise XORs all the base 1024 digits of the result.

It has the important property that the decoder is a linear function of the code: `decode(code1 ^ code2, a) == decode(code1, a) ^ decode(code2, a)`. Therefore, the encoder can compute the needed code using Gaussian elimination.

### Scoring note

For official scoring, please make the thoroughly negligible “output formatting” adjustment of adding 1 to the code value, since otherwise a theoretically possible output is 0, which is not a positive integer. As of this writing, the other answer has the same property.
> 6 votes

# Answer
# Wolfram Language (Mathematica), \\$n \approx 2.088\times 10^{5033}\\$ for pretest

```
a=Block[{aValues,bValues,p,poly,i},
  {aValues,bValues}=Thread@#;
  p=NextPrime[nPair-1];i=0;
  While[!DuplicateFreeQ[aValues~Mod~p],
    p=NextPrime@p;++i;
  ];
  coef=CoefficientList[PolynomialMod[
    InterpolatingPolynomial[Thread@{aValues,bValues},x,
      Modulus->p],p],x];
  coefval=FromDigits[Reverse@coef,p];
  FromDigits[
    Join[{coefval},8191~Table~Floor[i/8191],{i~Mod~8191}]
    ,8192]+1
]&;
b=Block[{i,p,coef,n,aValue},
  n=#-1;i=0;
  While[
    {n,p}=QuotientRemainder[n,8192];
    i+=p;
    p==8191];
  p=NextPrime[nPair-1,i+1];
  coefReversed=IntegerDigits[n,p];
  aValueQuery=#2;
  Fold[
    Mod[#*aValueQuery+#2,p]&,
    Table[0,Length@aValueQuery],
    coefReversed
  ]
]&;

```

Try it online! (generate random test case based on random seed)

Try it online! (pretest)

Use `InterpolatingPolynomial`.

Due to the Birthday's paradox, this is not as efficient as I expected.
> 2 votes

# Answer
# Python 3, 1.873x104405

```
import sys
inputs = sys.stdin.read()

numbers = [list(map(int, l.split(' '))) for l in inputs.strip().split('\n')]
def encode(numbers):
  output = ''
  def allNumbers(numbers, a, b):
    nonlocal output
    if len(numbers) == 0: output += '00'
    elif len(numbers) == 1:
      output += '0'
      output += bin(1024 + numbers[0][1])[2:]
    else:
      output += '1'
      l, r = [], []
      m = (a + b) // 2
      for item in numbers:
        if item[0] < m: l.append(item)
        else: r.append(item)
      allNumbers(l, a, m)
      allNumbers(r, m, b)
  allNumbers(numbers, 0, 2 ** 32)
  return int(output, 2)

def decode(output, key):
  output = bin(output)[2:]
  index = 0
  def peak(n):
    return output[index:index + n]
  def skip(n):
    nonlocal index
    index += n
  result = 0
  def findRange(a, b):
    nonlocal result
    if peak(1) == '0':
      if peak(2) == '00':
        skip(2)
        return
      else:
        skip(2)
        n = int(peak(10), 2)
        if a < key < b: result = n
        skip(10)
        return
    skip(1)
    m = (a + b) // 2
    findRange(a, m)
    findRange(m, b)
  findRange(0, 2 ** 32)
  return result

output = encode(numbers)
print("%s.%sE+%d" % (str(output)[0], str(output)[1:10], len(str(output)) - 1))
for (key, value) in numbers:
  assert(decode(output, key) == value)

```

Try it online!
> 1 votes

# Answer
# Sample answer: Python 3, pretest ≈ 3.612 · 1012946

This is just the sample program A given in the problem, along with a corresponding program B, to help those having trouble understanding the problem.

Program A simply concatenates the (32 + 10)-bit binary representations of all the input pairs. Program B iterates through these (32 + 10)-bit chunks until it finds the chunk whose first 32 bits match the given \\$a\\$, and outputs the corresponding \\$b\\$ from its last 10 bits.

### Program A

```
x = 0
for i in range(1024):
  [a,b] = input().split()
  x = x * 4398046511104 + int(a) * 1024 + int(b)
print (x)

```

Try it online!

### Program B

```
x, a = map(int, input().split())
while (x % 4398046511104) // 1024 != a:
  x //= 4398046511104
print(x % 1024)

```

Try it online!
> 1 votes

---
Tags: code-challenge, compression
---


title: Longest Seven Segment Word

text:
# Question
Title: Longest Seven Segment Word
This question was inspired by Tom Scott's video here.

The English language has plenty of words, but what's the longest one that can be displayed on a seven segment display? Your challenge is given a list of letters that may **not** be displayed, display the longest English word in a 7 segment display format?

# Input

* Input will contain a series of unacceptable characters. (letters that you are **not** permitted to use in your word.)
* Input can be taken from one of the following:
    + `stdin`
    + command-line arguments
    + function arguments

# Output

* Output the longest word using the provided alphabet from the input. (In the case of 2 words of the same length, the one that comes first is the "longest". When a hyphen is in the word, it counts towards its length, but is not displayed.)
* Output must be formatted like a 7 segment display, see the rules below for more about the format.
* Output must be in stdout or closest equivalent.
* Output may contain a trailing newline character.

# Letters

This image shows my source of the alphabet

Here is my simple ascii display so you can visually see the letters (my apologies, the wrap function I used broke with spaces so I had to settle on asterisks). And here is a table to show the alphabet as well:

```
  ____  A
 | F  | B
 |    |
  ____  G
 |    |
 | E  | C
  ____  D

ABCDEFG Letter
1110111 a
0011111 b
1001110 c
0111101 d
1001111 e
1000111 f
1011110 g
0010111 h
0000110 i
0111100 j
1010111 k
0001110 l
1010100 m
1110110 n
1111110 o
1100111 p
1110011 q
1100110 r
1011011 s
0001111 t
0111110 u
0111010 v
0101010 w
0110111 x
0111011 y
1101001 z

```

# Rules

* Standard loopholes are disallowed HOWEVER words.txt (the dictionary) is the only outside file you may reference (renaming it is not allowed, it **must** be called `words.txt` as it is in the repository).
* The seven segment display must:
    + Be an actual seven segment display. (I'm not going to be picky on how it looks, if it was accepted over there then it's accepted over here.)
    + Have any filler/whitespace character of choice.

# Test Cases

Wrapping is an unnecessary challenge and is not needed; I did it out of ease of looking at it in my terminal. Remember: Your *whitespace* does not need the same character.

```
input:
gkmqvwxz

output:
******************____********************____****____****____********
******|**|*******|*******|*******|*******|****|**|****|**|****|*******
******|**|*******|*******|*******|*******|****|**|****|**|****|*******
**____********************____************************************____
*|****|**|*******|*******|****|**|*******|****|**|*******|****|**|****
*|****|**|*******|*******|****|**|*******|****|**|*******|****|**|****
**____************____************____****____************____****____
************____************____****____****************************__
|**|*******|****|**|*******|*******|****|**|****|**|*******|*******|**
|**|*******|****|**|*******|*******|****|**|****|**|*******|*******|**
************____****____****____************____************____******
|**|*******|*******|****|**|*******|****|*******|**|*******|*******|**
|**|*******|*******|****|**|*******|****|*******|**|*******|*******|**
****************************____************____****____****____******
__************____********************____****____****____****____****
**|**|*******|*******|*******|*******|****|**|****|**|****|**|*******|
**|**|*******|*******|*******|*******|****|**|****|**|****|**|*******|
**********************____************************************____****
*****|*******|*******|****|**|*******|****|**|*******|****|**|*******|
*****|*******|*******|****|**|*******|****|**|*******|****|**|*******|
**************____************____****____************____****____****
****************____****____****____**
*******|*******|****|**|****|**|******
*******|*******|****|**|****|**|******
____****____****____************____**
*******|****|**|****|**|****|**|******
*******|****|**|****|**|****|**|******
____****************************____**

```

The word should be "dichlorodiphenyltrichloroethane" for debugging purposes.

```
input:
gkmqvwxzio

output:
**____************____****____****____************____****____****____
*|*******|****|**|****|**|*******|****|**|*******|****|**|****|**|****
*|*******|****|**|****|**|*******|****|**|*******|****|**|****|**|****
**____************____****____************____************____********
******|**|****|**|*******|*******|*******|*******|*******|****|**|****
******|**|****|**|*******|*******|*******|*******|*******|****|**|****
**____****____************____************____************************
****____****____****____****____************____****____************__
|**|*******|*******|*******|****|*******|**|*******|****|**|*******|**
|**|*******|*******|*******|****|*******|**|*******|****|**|*******|**
****____************____************____****____************____******
|*******|**|*******|*******|****|**|****|**|*******|****|**|*******|**
|*******|**|*******|*******|****|**|****|**|*******|****|**|*******|**
****____****____****____************____****____************____******
__****____****____****____**
**|**|*******|*******|******
**|**|*******|*******|******
******____****____****____**
**|**|************|*******|*
**|**|************|*******|*
******____****____****____**

```

The word should be "supertranscendentness" for debugging purposes.

```
input:
abcdefghijklm

output:
**********____****____************____********************____****____
*|*******|****|**|****|**|*******|*******|****|**|****|**|****|**|****
*|*******|****|**|****|**|*******|*******|****|**|****|**|****|**|****
**____********************____****____****____************************
*|*******|****|**|****|**|************|*******|**********|****|**|****
*|*******|****|**|****|**|************|*******|**********|****|**|****
**____****____****____****____****____****____****____****____****____
************____**********
|**|*******|*******|****|*
|**|*******|*******|****|*
****____****____****____**
|**|************|*******|*
|**|************|*******|*
****____****____****____**

```

The word should be "tootsy-wootsy" for debugging purposes. (We do not output the hyphen but it does count towards the length of the word.)

```
input:
ikmopqsvwz

output:
**____****____****____****____************____****____****____****____
*|*******|****|**|*******|****|**|*******|*******|****|**|****|**|****
*|*******|****|**|*******|****|**|*******|*******|****|**|****|**|****
******************____****____****____********************____********
*|****|**|*******|*******|****|**|*******|****|**|*******|****|**|****
*|****|**|*******|*******|****|**|*******|****|**|*******|****|**|****
**____************____************____****____************************
********************____************____********************____****__
|*******|*******|**|****|**|****|**|*******|*******|*******|*******|**
|*******|*******|**|****|**|****|**|*******|*******|*******|*******|**
****____****____****____********************____****____****____******
|**|****|**|****|**|****|**|****|**|****|**|****|**|*******|*******|**
|**|****|**|****|**|****|**|****|**|****|**|****|**|*******|*******|**
****____****____************____****____************____****____******
__**
**|*
**|*
****
****
****
****

```

The word should be "great-granddaughter" for debugging purposes. (We do not output the hyphen but it does count towards the length of the word.)

# Scoring

This is , so the shortest submission (in bytes) wins.

(This is also my first question so tell me if I skipped over something or something is unclear or not. Thanks and good luck!)

# Answer
# JavaScript, 830 characters, oooooof

**Edit: I fixed the issue and ignore my previous edits where I started I found an error, I was sanitizing the dictionary incorrectly. Funny enough, this didn't change the code length**

Anyways, someone had to do this challenge. If winning only requires the shortest, it's always possible to win by default, right? :P

```
var q=new XMLHttpRequest();q.open("get","words.txt");q.onreadystatechange=()=>{if(q.readyState!=4)return;(z=>q.responseText.toLowerCase().split("\n").filter(w=>w.split("").reduce((j,l)=>j&&z.indexOf(l)<0,true)).map((o,p)=>[o,p]).sort((a,b)=>{if(a[0].length == b[0].length){return a[1]-b[1]}return b[0].length-a[0].length;})[0][0].split("").forEach(e=>e=e.replace(/[^a-z]/,"")&&console.log(("ABCEFGCDEFGADEFBCDEGADEFGAEFGACDEFCEFGEFBCDEACEFGDEFACEABCEFABCDEFABEFGABCFGABEFACDFGDEFGBCDEFBCDFBDFBCEFGBCDFGABDG".split("").reduce((f,v,i)=>{if(i==114){f[0].unshift(v);f[1].push(f[0])}else if(v<f[0][0]){f[1].push(f[0]);f[0]=[v]}else{f[0].unshift(v)}return f},[[0],[]])[1][e.charCodeAt()-97]).reduce((f,v)=>f.replace(RegExp(`${v}`,"g"),"#"),"-AAA-\nF---B\nF---B\n-GGG-\nE---C\nE---C\n-DDD-").replace(/[^#\n]/g,"-"))))(prompt())};q.send()

```

Basically, how it works is, there's an output string that encodes segments for letters, and a format string, that the output string is applied onto.

Here's a version that labels these variables and is a bit less... Harsh.

It skips functions entirely and recalculates variables for any place they are iterated, so it's very inefficient, but it should never take more than a few seconds at worst case to run. Input is given through an html prompt. The script assumes it is part of a window with relative file access and outputs to the console.

```
const outputString = "ABCEFGCDEFGADEFBCDEGADEFGAEFGACDEFCEFGEFBCDEACEFGDEFACEABCEFABCDEFABEFGABCFGABEFACDFGDEFGBCDEFBCDFBDFBCEFGBCDFGABDG";
const formatString = "-AAA-\nF---B\nF---B\n-GGG-\nE---C\nE---C\n-DDD-";

var q=new XMLHttpRequest();
q.open("get","words.txt");
q.onreadystatechange=()=>{
    if(q.readyState!=4)return;
    (z=>q.responseText.toLowerCase().split("\n").filter(
        w=>w.split("").reduce((j,l)=>j&&z.indexOf(l)<0,true)
    ).map(
        (o,p)=>[o,p]
    ).sort(
        (a,b)=>{
            if(a[0].length == b[0].length){
                return a[1]-b[1]
            }
            return b[0].length-a[0].length;
        }
    )[0][0].split("").forEach(
        e=>e=e.replace(/[^a-z]/,"")&&console.log(
            (outputString.split("").reduce(
                (f,v,i)=>{
                    if(i==114){
                        f[0].unshift(v);f[1].push(f[0])
                    }else if(v<f[0][0]){
                        f[1].push(f[0]);f[0]=[v]
                    }else{
                        f[0].unshift(v)
                    }return f
                },[[0],[]]
            )[1][e.charCodeAt()-97]).reduce(
                (f,v)=>f.replace(RegExp(`${v}`,"g"),"#"),formatString
            ).replace(/[^#\n]/g,"-"))
    ))(prompt())
};
q.send()

```

These particular seven segment display codes for the alphabet (for example, 0101100) can't overlap when you remove their zeroes. What I mean by that is for each index of the string if you were to encapsulate that spot, chaining all the strings together never results in a case that the last index of a display code is lower than the first index of the following code. This isn't particularly true of all display code permutations and orderings, but in this case it was so we use that.

I haven't double checked because I got so, um, involved in this code, but I think that it might be smaller to store these modified display codes in a flat array than to break them into an array based on one string. But that wasn't as fun.

I don't expect to win, but I am curious if anyone else can beat this in web-oriented JavaScript using an `XMLHttpRequest` and `prompt()` for input.
> 1 votes

# Answer
# PHP, 292 bytes

```
foreach(file("words.txt")as$w)preg_match("%[$argn]%i",$w)||$e<($n=strlen($w=trim($w)))&&$s=strtoupper($w.$e=$n;for($r=["
","
","
"];$i<$e;$b&&$k+=4)for($b=ord("}7f\37vtg5$\17u&Emo|yls6/+*=;Z"[ord($s[$i++])-65]),$p=7;$p--;)$b>>$p&1&&$r[(8-$p)/3][$k+$x="3213212"[$p]]="_|"[$x&1];echo join($r);

```

Run as pipe with `-nr` or try it online (with a much smaller dictionary).

In case you run out of memory, replace `foreach(file("words.txt")as$w)` with `for($f=fopen("words.txt",r);$w=fgets($f);)`. This will also improve performance a lot.

**breakdown**

```
foreach(file("words.txt")as$w)      # 1. loop $w through words
    preg_match("%[$argn]%i",$w)||       # if there are forbidden characters, skip
        ($e<$n=strlen($w=trim($w)))     # if length $n exceeds current max length $e
            &&$s=strtoupper($w)             # then update longest word $s
            .$e=$n;                         # and max length
for($r=["\n","\n","\n"];            # 2. init my ouput buffer
    $i<$e;                          # 3. loop through word characters
    $b&&$k+=4)                          # 3. if previous char was legal, increment output offset
    for(                                # 1. get bit mapping for character: (none for non-letters)
        $b=ord("}7f\37vtg5$\17u&Emo|yls6/+*=;Z"[ord($s[$i++])-65]),
        $p=7;$p--;)                     # 2. loop through bits
        $b>>$p&1&&                          # if bit $p is set,
            $r[(8-$p)/3][$k+$x="3213212"[$p]]   # then map bit no. to segment coordinates
                =$x&1?d|t:_;                    # and draw the according character
echo join($r);                      # 4. print my output buffer

```

**notes**

* I could lose 11 bytes if the dictionary contained only letters, space and linebreaks
OR 12 if only all letters were uppercase. Dang!
* I could paint every "longest" word; the last will remain in the buffer for printing; that would mean I wouldn´t have to copy `$w` to `$s` and I could copy `$n` to `$e` in the character loop, but I would need `if(!preg_match(...)&&$e<$n=strlen(...))` and I had to reset `$i=$k=0`; that would eat up all the savings.
I could do `!$i=$k=preg_match(...)` but that would require extra parentheses - no savings either.
Makes me almost wish that we also had to paint the digits.
* Painting the whole thing into a single string instead of an array would save five bytes in the painting, but cost nine in the output.
> 1 votes

---
Tags: code-golf
---