# Question
Title: Marcel Proust and Markov decipher security service’s T9 texts
As if this challenge could be any more Pythonesque in spirit... **No prior knowledge of Markov chains or encryption techniques is required.**

You are a spy who needs to obtain some crucial information from the British security service M1S. The agents of M1S are well aware that their Wi-Fi signals can be intercepted, their Android/iOS security vulnerabilities exploited etc., so all of them are using Nokia 3310’s to transmit text information which is typed using the **T9 auto-completion**.

You had previously hacked the phones to be delivered to the intelligence agency and had installed keyloggers under their glorious plastic keyboards, so now you receive sequences of numbers corresponding to the letters they typed, so “the eagle has left the nest alert the agents” becomes

```
84303245304270533808430637802537808430243687

```

But wait! Some T9 sequences are ambiguous (“6263” could be “name”, “mane” or “oboe”; the more obscure, the more suspicious it gets!), so what do you do? You know that the only entrance examination M1S uses is summarising Marcel Proust’s masterpiece “Remembrance of Things Past” in 15 seconds, so you want to pick the word that comes next after the previous one according to its frequency distribution in the entire chef-d’œuvre of Proust!

*Can you crack the code and obtain what could be the original message?*

## The principle of T9

The T9 auto-completion mechanism can be described as follows. It maps alphabetic characters to numbers as shown on the picture above.

```
abc     -> 2
def     -> 3
ghi     -> 4
jkl     -> 5
mno     -> 6
pqrs    -> 7
tuv     -> 8
wxyz    -> 9
<space> -> 0
<other> -> <is deleted>

```

The T9 decryptor receives a sequence of digits and tries to guess the word that could be typed with those keypresses. It might use a standard frequency table, but we are going one step further and predicting the next word using a Markov chain!

## Learning sample

The corpus is this heavily stripped version of Proust’s “Remembrance of Things Past” (`s/-/ /g`, `s/['’]s //g` and `s/[^a-zA-Z ]//g` — begone confusing possessive `'s`!) originally published on the University of Adelaide website (the text of this work is in the Public Domain in Australia).

The whole text **must be analysed as one string, as one long sentence, as one long vector of words** (whichever is more convenient for your language), **stripped of linebreaks**, and **split into words at spaces**. (I do not supply a single-paragraph file because such might be frowned upon by github tools.)

How do I read the whole text as one string / sentence? An example in **R**:

```
p_raw  <- read.table("proust.txt", sep="\t") # Because there are no tabs
p_vec  <- as.character(p_raw$V1)       # Conversion to character vector
p_str  <- paste(p_vec, collapse=" ")   # One long string with spaces
p_spl  <- strsplit(p_str, split=" ")[[1]] # Vector of 1360883 words
proust <- p_spl[p_spl!=""]           # Remove empty entries — 1360797

```

## Task

Given a sequence of digits as a number, return a possible text string that could be typed using the corresponding T9 keys using a probabilty chain to predict the next word *X* based on this training text treated as one long sentence.

If *X* is the first T9-word of the text and there are multiple guesses, pick one at random, otherwise pick the only one possible.

For all subsequent T9-words *X(i)* preceded by a word already deciphered *w(i-1)*:

1. If a T9-word *X* can be converted into a normal word *x* in one unique way, do it.
2. If there are multiple conversion options available for *X*, say *x1, x2, ...*, look up the preceding guessed word *w*.
    * If *w* is never followed by anything that maps to *X* in the original work of Proust, pick any of the possible *x1, x2, ...* at random.
    * If *w X* always corresponds to *w x1* in the original and there are no concurrent *xi*’s that could be mapped into *X*, pick *x1*.
    * If *w X* can be converted to *w x1*, *w x2*, ... that can be found in the corpus, then count all possible *xi*’s that follow *w* and map to *X* in the corpus and pick *xi* with probability *xi/(x1 + x2 + ...)*.

**Example 2a.** If the message is `76630489`, where `489` could be `guy` or `ivy` (they occur in the corpus at least once), `7663` can be deciphered as `some` (a very probable first word). If `some` is never followed by anything that maps to `489` in the corpus, then pick `guy` or `ivy` at random with probability 0.5.

**Example 2b.** If the message is `766302277437`, where `2277437` could be `barrier` or `carrier`, `7663` can be deciphered as `some`. If Proust always used `some carrier` and never `some barrier`, then pick `some carrier`.

**Example 2c.** Suppose that you want to decipher the sequence `536307663`. `5363` was predicted as `lend`. `7663` could be any of these: `pond`, `roof` and `some`. You count the occurrences of the word following `lend` in the sample corpus. Suppose you get something like this (just to illustrate):

```
        T9  Word following lend  Occurrences
      7663  some                           7
      7663  pond                           2
      7663  roof                           1

```

So if `7663` is preceded by `lend`, there is `7/(7+2+1)=70%` probability that `7663` stands for `some`, 20% `pond` and 10% `roof`. Your algorithm should produce `lend some` in 70% cases, `lend pond` in 20% cases etc.

You may safely assume that the agents use **only a-z letters and spaces** (no punctuation marks, no possessive `'s`, and no numbers).

You may also assume that the agents of M1S **never use any words outside the scope of “Remembrance of Things Past”** (which is a whopping vocabulary of 29,237 words!).

The T9 fuctionality was implemented in this challenge, so you might have a look at it.

If you need any help, probabilistic chains were gloriously tamed in this, that and the following challenges, but you do not even need to know the principle of such chains: everything is stated in the task.

## Test cases

```
--Inputs--
20784250276960369
20784250276960369
84303245304270533808430637802537808430243687
94280343084306289072908608430262780482737
94280343084306289072908608430262780482737

--Possible outputs--
c quick brown fox
a stick crown fox
the eagle gas left the nest blest vie agents
what did the navy pay to the coast guards
what did the navy raz un the coast guards

```

## Rules:

* Standard loopholes apply.
* You do not know the original message, all you get is a sequence of digits and the file proust.txt that you just need to load in the memory / workspace / whatever. There is no need to have anything self-contained; assume `proust.txt` is always accessible.
* Your algorithm must be able to produce different outputs with respective probabilities if more than one decryption option is probable according to the corpus (see Example 2c).

You need to stay as discreet as possible, so the shortest code wins!

**P.S.** The obvious benefit of this probabilistic algorithm is the fact that the probability you will get a true original string for an ambiguous deciphered string tends to one — just wait...

**P.P.S.** See also Prediction by Partial Matching.

# Answer
## R solution, non-competing illustration of what can be done

Firstly, we load the sequence of words into the memory:

```
p_raw  <- read.table("proust.txt", sep="\t") # Because there are no tabs
p_vec  <- as.character(p_raw$V1)       # Conversion to character vector
p_str  <- paste(p_vec, collapse=" ")   # One long string with spaces
p_spl  <- strsplit(p_str, split=" ")[[1]] # Vector of 1360883 words
proust <- p_spl[p_spl!=""]           # Remove empty entries — 1360797

```

Secondly, we need a function that T9-ifies any text:

```
t9 <- function (x) {
  x <- chartr(paste(c(letters, " "), collapse=""), "222333444555666777788899990", tolower(x))
  x <- gsub("[^0-9]", "", x, perl = TRUE) # Safety check
  x <- x[x!=""] # Also for safety because... you know...
  x
}

```

Then, we T9-ify Proust:

```
p9 <- t9(proust)

```

Final preparation: we split the input string at zeros using a function that we call `prep`):

```
prep <- function (x) {
  x <- chartr("0", " ", x)
  x <- strsplit(x, " ")[[1]]
  x <- x[x!=""] # Boil the empty strings for safety
  x
}

```

And now I propose a function that takes any input string of numbers, `prep`s it and deciphers the words one by one:

```
decip <- function(x, verbose = FALSE) {
  x <- prep(x)
  l <- length(x)
  decrypted <- rep(NA, l)
  tb <- table(proust[which(p9 == x[1])])
  decrypted[1] <- sample(names(tb), 1, prob=tb/sum(tb))
  if (verbose) print(decrypted[1])
  for (i in 2:l) {
    mtchl <- p9 == x[i]
    mtch <- which(mtchl)  # Positions that matched
    pmtch <- proust[mtch] # Words that matched
    tb <- table(pmtch)    # Count occurrences that matched
    if (length(tb)==1) {  # It is either 1 or >1
      decrypted[i] <- names(tb)[1]
      if (verbose) print(paste0("i = ", i, ", case 1: unique decryption"))
      } else {  # If there are more than one ways to decipher...
      preced <- proust[mtch-1]
      s <- sum(preced==decrypted[i-1])
      if (s==0) {
        decrypted[i] <- sample(names(tb), 1)
        if (verbose) print(paste0("i = ", i, ", case 2a: multiple decryption, collocation never used, picking at random"))
        } else {
        tb2 <- table(pmtch[preced==decrypted[i-1]])
        if (length(tb2)==1) {
          decrypted[i] <-  names(tb2)[1]
          if (verbose) print(paste0("i = ", i, ", case 2b: multiple decryption, only one collocation found, using it"))
        } else {
          decrypted[i] <- sample(names(tb2), 1, prob = tb2/sum(tb2))
          if (verbose) print(paste0("i = ", i, ", case 2c: multiple decryption, ", length(tb2), " choices"))
          }
      }
    }
    if(verbose) print(decrypted[i])
  }
  decrypted
}

```

And now what it is actually doing:

```
decip("20784250276960369", verbose=TRUE)
----
[1] "a"
[1] "i = 2, case 2c: multiple decryption, 2 choices"
[1] "quick"
[1] "i = 3, case 2a: multiple decryption, collocation never used, picking at random"
[1] "brown"
[1] "i = 4, case 1: unique decryption"
[1] "fox"
[1] "a"     "quick" "brown" "fox"

```

Second example:

```
decip("84303245304270533808430637802537808430243687", verbose=TRUE)
----
[1] "what"
[1] "i = 2, case 2b: multiple decryption, only one collocation found, using it"
[1] "did"
[1] "i = 3, case 2b: multiple decryption, only one collocation found, using it"
[1] "the"
[1] "i = 4, case 1: unique decryption"
[1] "navy"
[1] "i = 5, case 2a: multiple decryption, collocation never used, picking at random"
[1] "raz"
[1] "i = 6, case 2a: multiple decryption, collocation never used, picking at random"
[1] "um"
[1] "i = 7, case 2a: multiple decryption, collocation never used, picking at random"
[1] "the"
[1] "i = 8, case 2b: multiple decryption, only one collocation found, using it"
[1] "coast"
[1] "i = 9, case 1: unique decryption"
[1] "guards"
[1] "what"   "did"    "the"    "navy"   "raz"    "um"     "the"    "coast"  "guards"

```

Please do not comment that this can be golfed. Seems that few people are interested in this challenge because of my terrible verbosity, so I posted this answer to show what a possible programme could look like. You need not upvote/downvote this answer.
> 1 votes

# Answer
# Python 3, 316 bytes

```
from random import*
from collections import*
def d(s,f):
 D=defaultdict(Counter);p=q=''
 for w in open(f).read().split():D[w.translate({97+c:(c-(c>17)-(c>24))//3+50for c in range(26)})].update([w]);D[p].update([w]);p=w
 for c in s.split('0'):q=choice([*(len(D[c])>1and D[c]&D[q]or D[c]).elements()]);print(q,end=' ')

```
> 1 votes

---
Tags: code-golf, string, cipher, markov-chain
---


title: Bitflip and negate

text:
# Question
Title: Bitflip and negate
Given an integer, make an expression that produces it from `0` using unary negation `-` and bitwise complement `~` (`~n` = `-n-1`), with the operators applied right to left.

```
...
-3  = ~-~-~0
-2  = ~-~0
-1  = ~0
 0  = 0
 1  = -~0
 2  = -~-~0
 3  = -~-~-~0
...

```

Your expression must be as short as possible, which means no redundant parts of `~~`, `--`, `-0`, or `00`. Output or print the expression as a string or a sequence of characters.

```
var QUESTION_ID=92598,OVERRIDE_USER=20260;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/92598/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```

```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```

# Answer
# Python, 32 bytes

```
lambda x:("-~"*abs(x))[x<0:]+"0"

```

Anonymous lambda function. Given an integer x writes "-~" abs(x) times and removes the first char if x is negative, then a zero is added to the end.
> 17 votes

# Answer
# JavaScript (ES6), ~~33~~ 31 bytes

```
f=x=>x<0?"~"+f(~x):x&&"-"+f(-x)

```

Recursion \< built-ins \< loops (at least in this case). Basically unevaluates the input:

* if it's less than 0, flip it and add a `~` to the string;
* if it's more than 0, negate it and add a `-` to the string;
* if it's exactly 0, return 0.

Takes advantage of this pattern:

```
 0         = 0
-1 = ~( 0) = ~0
+1 = -(-1) = -~0
-2 = ~(+1) = ~-~0
+2 = -(-2) = -~-~0
-3 = ~(+2) = ~-~-~0
+3 = -(-3) = -~-~-~0
etc.

```
> 16 votes

# Answer
# Pyth, ~~14~~ ~~13~~ 12 Bytes

```
_<>0Q+0sm"~-

```

*-2 Bytes thanks to @StevenH.*

**test suite**

Decided to try out Pyth, so i translated my python answer to it. Any help welcome!

### Explanation:

```
_<>0Q+0sm"~-
        m"~-     # Map "~-" onto the input (= a list of n times "~-").
       s         # Join the list to a string.
     +0          # Add "0" in front.
 <>0Q            # Slice off the last char if the input is negative.
_                # Reverse the whole thing.

```
> 11 votes

# Answer
# C, 46 bytes

```
m(x){putchar(x?x<0?126:45:48);x&&m(-x-(x<0));}

```

Unlike most (all?) other answers, this one outputs the operators `~` and `-` one by one.
> 8 votes

# Answer
# 05AB1E, ~~14~~ 13 bytes

```
Ä„-~×¹0‹i¦}0J

```

**Explanation**

```
 „-~           # the string "-~"
Ä   ×          # repeated abs(input) times
     ¹0‹i¦}    # if input is negative, remove the first char
           0J  # join with 0

```

Try it online!
> 7 votes

# Answer
# Retina, ~~19~~ 17 bytes

Replace the number with unary, with a zero on the end. Replace each `1` with `-~`. Remove double negative if there is one.

```
\d+
$*10
1
-~
--

```

**Try it online**

**All test cases at once** (slightly modified program to support multiple test cases)
> 7 votes

# Answer
# Perl 38 35 33 (23 + 1 for -p) 24

```
s/\d+/"-~"x$&.0/e;s;--;

```

-13 thanks to Dada
> 7 votes

# Answer
# Haskell, 41 bytes

~~`f n=['-'|n>0]++(tail$[1..abs n]>>"-~")++"0"`~~

```
f n|n<0=tail$f(-n)|x<-[1..n]>>"-~"=x++"0"

```

Thanks to nimi for 3 bytes
> 6 votes

# Answer
# Dyalog APL, 18 bytes

```
'0',⍨0∘>↓'-~'⍴⍨2×|

```

`'0',⍨` character zero appended to

`0∘>` negativeness (i.e. 1 for numbers under 0; 0 for zero and up)

dropped from

`'-~'⍴⍨` the string "~-" cyclically reshaped to length

two times

`|` the absolute value

`+` plus

`0∘<` positiveness (i.e 1 for numbers over 0)

TryAPL online!
> 6 votes

# Answer
# , 21 bytes

```
/ä
é
D@"ña-~ñá0kgJó--

```

Try it online!

V has *very* limited number support, and it actually has no concept of negative numbers. This means in order to support negatives (or even 0), we have to use some hacky workarounds.

Explanation:

```
/ä                  "Move forward to the first digit
é                   "And enter a newline
D                   "Delete this number, into register '"'
 @"                 "That number times:
   ñ   ñ            "Repeat the following:
    a               "  Append the string:
     -~             "  '-~'
        á0          "Append a 0
          k         "Move up a line
           gJ       "And join these two lines together
             ó--    "Remove the text '--', if it exists

```
> 5 votes

# Answer
# JavaScript (ES6), ~~39~~ 37 bytes

```
x=>"-~".repeat(x<0?-x:x).slice(x<0)+0

```

Saved 2 bytes thanks to @Neil
> 5 votes

# Answer
## Ruby, 34 bytes

```
->x{("-~"*x.abs+?0)[2[0<=>x]..-1]}

```
> 5 votes

# Answer
# Jelly, 10 bytes

```
A⁾-~ẋḊẋ¡N0

```

This is a full program. Try it online!

### How it works

```
A⁾-~ẋḊẋ¡N0  Main link. Argument: n

A           Take the absolute value of n.
 ⁾-~ẋ       Repeat the string "-~" that many times. Result: s
       ¡    Conditional application:
     Ḋ        Dequeue; remove the first element of s...
      ẋ N     if s, repeated -n times, is non-empty.
         0  Print the previous return value. Set the return value to 0.
            (implicit) Print the final return value.

```
> 5 votes

# Answer
# Java 7, ~~95~~ 79 bytes

**79 bytes:**

```
String s(int x){String t=x<0?"~":"";while((x<0?++x:x--)!=0)t+="-~";return t+0;}

```

**Ungolfed:**

```
String s(int x) {
    String t = x<0 ? "~" : "";
    while((x<0 ? ++x : x--) != 0)
        t += "-~";
    return t+0;
}

```

~~Old version (95 bytes):~~

```
String s(int x){return new String(new char[x<0?-x:x]).replace("\0","-~").substring(x<0?1:0)+0;}

```

**Usage:**

```
class A {
    public static void main(String[]a) {
        System.out.println(s(-3));
        System.out.println(s(-2));
        System.out.println(s(-1));
        System.out.println(s(0));
        System.out.println(s(1));
        System.out.println(s(2));
        System.out.println(s(3));
    }
    static String s(int x){String t=x<0?"~":"";while((x<0?++x:x--)!=0)t+="-~";return t+0;}
}

```

Try it here!

Output:

```
~-~-~0
~-~0
~0
0
-~0
-~-~0
-~-~-~0

```
> 5 votes

# Answer
# EXCEL: ~~55~~ 33 bytes

```
=REPT("-~",IF(A1>0,A1,ABS(A1)-1))&"0"

```

Input is in the form of putting a number in the A1 cell. Formula can go anywhere except A1.
> 3 votes

# Answer
## CJam, ~~18~~ 14 bytes

*Took some inspiration from Emigna's answer to save 4 bytes.*

```
li_z"-~"*\0<>0

```

Try it online! (As a linefeed-separated test suite.)

### Explanation

```
li      e# Read input and convert to integer N.
_z      e# Duplicate and get |N|.
"-~"*   e# Repeat this string |N| times.
\0<     e# Use the other copy of N to check if it's negative.
>       e# If so, discard the first '-'.
0       e# Put a 0 at the end.

```
> 3 votes

# Answer
## T-SQL, 87 bytes

```
select substring(replicate('-~',abs(x)),case when x<0then 2 else 1 end,x*x+1)+'0'from #

```

The `x*x+1` condition in substring is sufficient, since `x^2+1>=2*abs(x)` for all `x`.

As usually in SQL, the input is stored in a table:

```
create table # (x int)

insert into # values (0)
insert into # values (1)
insert into # values (-1)
insert into # values (2)
insert into # values (-2)

```
> 3 votes

# Answer
# Vim - 31 keystrokes

First vim golf, prolly missed a ton of stuff.

```
`i-~<esc>:s/-\~-/\~-/dwp<left>ii<esc><left>d$@"<esc>a0`

```
> 3 votes

# Answer
## Matlab, 61 bytes

```
x=input('');A=repmat('-~',1,abs(x));disp([A((x<0)+1:end) 48])

```
> 2 votes

# Answer
## Pyke, ~~14~~ 13 bytes

```
X,"-~"*Q0<>0+

```

Try it here!
> 2 votes

# Answer
# Perl 6, 25 bytes

```
{substr '-~'x.abs~0,0>$_}

```

# Explanation:

```
{
  substr
    # string repeat ｢-~｣ by the absolute value of the input
    '-~' x .abs

    # concatenate 0 to that
    ~ 0

    ,

    # ignore the first character of the string if it is negative
    0 > $_
}

```
> 2 votes

# Answer
# Jelly, ~~14~~ 12 bytes

-2 bytes thanks to @Dennis (return 0 rather than concatenate "0", making this a full program only.)

```
0>‘
A⁾-~ẋṫÇ0

```

Test it at **TryItOnline**

How?

```
0>‘      - link 1 takes an argument, the input
0>       - greater than 0? 1 if true 0 if false
  ‘      - increment

A⁾-~ẋṫÇ0 - main link takes an argument, the input
      Ç  - y = result of previous link as a monad
A        - x = absolute value of input
 ⁾-~     - the string "-~"
    ẋ    - repeat the sting x times
     ṫ   - tail repeatedString[y:] (y will be 1 or 2, Jelly lists are 1-based)
       0 - implicit print then return 0

```
> 2 votes

# Answer
## \>\<\>, 18 + 3 = 22 bytes

```
:?!n0$-:0):1go-
-~

```

Try it online! +3 bytes for the ` -v` flag to initialise the stack with the input. If assuming that STDIN is empty is okay, then the following is a byte shorter:

```
:?!ni*:0):1go-
-~

```

The program keeps flipping the input `n` as necessary until it reaches 0, after which it errors out.

```
[Loop]
:?!n      If n is 0, output it as a num. If this happens then the stack is now
          empty, and the next subtraction fails
0$-       Subtract n from 0
:0)       Push (n > 0)
:1go      Output the char at (n>0, 1) which is a char from the second line
-         Subtract, overall updating n -> -n-(n>0)

```
> 2 votes

# Answer
# PseudoD, ~~688~~ ~~579~~ 521 bytes

```
utilizar mate.pseudo
utilizar entsal.pseudo
adquirir n
adquirir a
adquirir r
adquirir i
fijar n a llamar LeerPalabra finargs
si son iguales n y CERO
escribir {0}
salir
fin
fijar a a llamar ValorAbsoluto n finargs
fijar i a CERO
si comparar Importar.Ent.Comparar n < CERO
fijar r a {~}
sino
fijar r a {-}
fin
mientras comparar Importar.Ent.Comparar i < a
escribir r finargs
si son iguales r y {~}
fijar r a {-}
Importar.Ent.Sumar i UNO i
sino
fijar r a {~}
fin
finbucle
si son iguales r y {~}
escribir {~}
fin
escribir {0}

```

Explain:

```
Read a number from STDIN;
If the number is zero (0); Then:
    Writes 0 to STDOUT and exits;
End If;
If the number is less than zero (0); Then:
    Set the fill character to "~";
Else:
    Set the fill character to "-";
End If;
For i = 0; While i is less than abs(number); do:
    Write the fill character to STDOUT;
    If the fill character is "~":
        Set the fill character to "-"
        Increment i by one
    Else:
        Set the fill character to "~"
    End if;
End for;
If the fill character is "~"; Then:
    Write "~" to STDOUT;
End If;
Write "0" to STDOUT

```
> 2 votes

# Answer
# Octave, 51 bytes

```
x=input('');[("-~"'*[1:abs(x)>0])((x<0)+1:end),'0']

```

At first blatantly copying the Matlab approach by @pajonk and then modifying some details, rewriting as an "outer product" between a vector of ones and the characters "-~" and abusing **on-the-fly-indexing** (or what it could be called) lets us save some bytes. It still pains me slightly that I can't get the index expression to take fewer bytes.

Octave allows a(i1)(i2) or even (...)(i1)(i2) for indexing where Matlab would want us to store variables in between the indexings.

```
((x<0)+1:end)

```

is far too long to describe "skip first if". There must be a better way.
> 2 votes

# Answer
# PHP, 61 bytes

```
if(0>$n=$argv[1]){echo"~";$n=~$n;}echo str_repeat("-~",$n),0;

```
> 1 votes

# Answer
# PHP, 58 bytes

```
<?=((0<$a=$argv[1])?'-':'').str_pad('0',2*abs($a),'~-',0);

```
> 1 votes

# Answer
## Labyrinth, 25 bytes

```
`?+#~.
.  ; 6
54_"#2
  @!

```

Try it online!

### Explanation

I really like the control flow in this one. The IP runs in a figure 8 (or actually a ∞, I guess) through the code to reduce the input slowly to `0` while printing the corresponding characters.

The code starts in the upper left corner going right. The ``` doesn't do anything right now. `?` reads the input and `+` adds it to the implicit zero below. Of course that doesn't do anything either, but when we run over this code again, `?` will push a zero (because we're at EOF), and `+` will then get rid of that zero.

Next the `#` pushes the stack depth, simply to ensure that there's a positive value on the stack to make the IP turn south, and `;` discards it again.

The `"` is a no-op and acts as the main branch of the code. There are three cases to distinguish:

* If the current value is positive, the IP turns right (west) and completes one round of the left loop:

```
_45.`?+
_45      Push 45.
   .     Print as character '-'.
    `    Negate the current value (thereby applying the unary minus).
     ?+  Does nothing.

```
* If the current value is negative, the IP turns left (east) and the following code is run:

```
#26.~
#        Push stack depth, 1.
 26      Turn it into a 126.
   .     Print as character '~'.
    ~    Bitwise NOT of the current value (applying the ~).

```

Note that these two will alternate (since both change the sign of the input) until the input value is reduced to zero. At that point...
* When the current value is zero, the IP simply keeps moving south, and executes the `!` and then turns west onto the `@`. `!` prints the `0` and `@` terminates the program.
> 1 votes

# Answer
# GolfScript, ~~30~~ ~~24~~ 20 bytes

* Saved 6 bytes thanks to xnor.
* Saved 4 bytes thanks to Dennis.

`~."-~"\abs*\0<{(;}*0`

Input: `-5`

Output: `-5 = ~-~-~-~-~0`

### Explanation

```
~.     # Input to integer and duplicate
"-~"   # We shall output a repetition of this string
\abs   # Move the input onto the stack and computes abs
*      # Multiply "-~" for abs(input) times
\      # Copy onto the stack the input
0<     # Is it less than 0?
{(;}*  # Yes: remove first '-' from the output
0      # Push 0

```

Try it online!
> 1 votes

---
Tags: code-golf, string, math, bitwise
---


title: RGB Gradients Generation

text:
# Question
Title: RGB Gradients Generation
**The Challenge**

Given the two uppercase hexadecimal strings (both 6 characters long, XXXXXX and YYYYYY) representing RGB values (ranging from `000000` to `FFFFFF` inclusive), and a positive non-zero integer N, display a linear transition of the N+2 colors generated from XXXXXX to YYYYYY that would result in a color gradient.

## **Example**

Input

```
FF3762
F08800
9

```

Output

*Please note in our example, I've requested 9 interim steps between the two colors, therefore 11 lines will be displayed from initial color to the final color*

```
FF3762
FD3F58
FC474E
FA4F44
F9573A
F75F31
F66727
F46F1D
F37713
F17F09
F08800

```

## **Caveats**

While I've gone with a simple linear process of deriving the integer values for the interim colors before converting them back into hexadecimal, your methods may vary. Please consider the various ways one could round up/down your numbers accordingly.

## **Testing**

To make this interesting, I've provided a snippet to allow testing of your code, inclusive of a button to provide you with two random colors to test your code against. Displaying your results is optional, but it's encouraged!

```
c1=()=>('00000'+(Math.random()*(1<<24)|0).toString(16)).slice(-6);

$("#col").click(function(){
  alert("Your two colors are: "+c1()+" and "+c1()+".");
});

$("#colors").blur(function(){
  $("#test").empty();
 var colArr = $("#colors").val().split("\n");
 for(c in colArr){
   $("#test").append('<div class="tester" style="background-color:#'+colArr[c]+';">'+colArr[c]+'</div>')
  }

});
```

```
.tester{height: 20px;
width: 60px;padding: 4px;border: 1px solid black;}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="col">Your two colors</button><br />
<textarea id="colors"></textarea>
<div id="test">

</div>
```

1) You can access two random colors for your test by clicking on the "Your two colors" button. 2) The number of interim steps will be the same as the number of characters in your PPCG username inclusive of spaces, in the case of "WallyWest" it would be 9 (as per my example above). 3) Run your code with the two colors and the number and once you have your generated list, you have the option of pasting your output into the textarea and tabbing away from it to get your generated color gradient.

My example is shown here:

I must admit, that looks pretty awesome!

Please note: As I mentioned, showing your testing of your output using the snippet is optional, but it's encouraged! :)

## **Output**

The list output must be in the form of N+2 sets of 6 digit hex numbers separated by line feeds (\n) as shown in my example above. Output can be in the form of separate lines, space/comma separated list, an array or whatever is best suited for your language... *(Thanks @nimi for the heads up)* Please remember, that if you plan on testing your code with the snippet, however you separate each "color" is up to you.

## **Rules**

This is code-golf, so the shortest solution in bytes will be crowned the winner. No loopholes, naturally. Input must accept the two strings and a number (which as I said will be equivalent to the number of letters in your username on PPCG, thus your resulting output will always be a minimum of three lines long.

# Answer
# MATL, 31 bytes

```
2+1yhjjh2e!1ZA3e!b:1&Ynk8W5Y2Za

```

This uses linear interpolation with rounding down. Input format is

```
9
FF3762
F08800

```

**Try it online!**

### Graphical output, 31 bytes

```
2+1yhjjh2e!1ZA3e!b:t2YG1&Ynk2ZG

```

This is the result for inputs

```
5
FF3762
F08800

```

Try it in **MATL Online**! The interpreter is currently experimental. If you don't get any output refresh the page and press "Run" again.
> 1 votes

# Answer
## JavaScript (ES6), 130 bytes

```
g=
(f,t,n)=>[...Array(++n+1)].map((_,i)=>f.replace(/../g,(e,j)=>((`0x${e}`*(n-i)+`0x${t[j]+t[j+1]}`*i)/n|256).toString(16).slice(1)))
;
p=_=>g(f.value,t.value,+n.value).map(e=>o.insertRow().insertCell().appendChild(document.createTextNode(e)).parentNode.bgColor=e);
```

```
<input id=f value=e14f09><input id=t value=9a04f6><input id=n value=4 type=number><input type=button onclick=p() value=Go!><table id=o bgcolor=black cellpadding=4>
```
> 4 votes

# Answer
# Dyalog APL, 44 bytes

Prompts for **N**, then **B**eginning-color, then **E**nding-color. Needs `⎕IO←0` which is default on many systems.

```
h[↑⌊B∘+¨(⍳2+N)×(-/E B←(h←⎕D,⎕A)∘⍳¨⍞⍞)÷1+N←⎕]

```

`h[`...`]` index into **h** (which has a value when we finish evaluating the the bracket's content)

`N←⎕` prompt for numeric **N** (4)

`1+` add one to **N** (5)

`(`... use that to divide the result of...

`⍞⍞` prompt for two character strings \["7E0E7E","FF3762"\]

`(`...`)∘⍳¨` find the indices of the each string's characters in...

`⎕D,⎕A` **D**igits followed by **A**lphabet

`h←` assigned to **h**

now we have "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"

`E B←` assign the indices to **E** and **B** \[\[7,14,0,14,7,14\],\[15,15,3,7,6,2\]\]

`-/` subtract and enclose **B** from **E** \[\[-8,-1,-3,7,1,12\]\]

the result so far is \[\[-1.6,-0.2,-0.6,1.4,0.2,2.4\]\]

`(`... multiply this by...

`2+N` two plus **N** (6)

first integers \[0,1,2,3,4,5\]

this gives us \[\[0,0,0,0,0,0\],\[-1.6,-0.2,-0.6,1.4,0.2,2.4\],\[-3.2,-0.4,-1.2,2.8,0.4,4.8\],...\]

`B∘+¨` add **B** to each \[\[15,15,3,7,6,2\],\[13.4,14.8,2.4,8.4,6.2,4.4\],\[11.8,14.6,1.8,9.8,6.4,6.8\],...\]

round down \[\[15,15,3,7,6,2\],\[13,14,2,8,6,4\],\[11,14,1,9,6,6\],...\]

make list of lists into table

```
[[15,15, 3, 7, 6, 2]
 [13,14, 2, 8, 6, 4]
 [11,14, 1, 9, 6, 6]
 [10,14, 1,11, 6, 9]
 [ 8,14, 0,12, 6,11]
 [ 7,14, 0,14, 7,14]]

```

here we index into **h**, giving

```
[["F","F","3","7","6","2]
 ["D","E","2","8","6","4]
 ["B","E","1","9","6","6]
 ["A","E","1","B","6","9]
 ["8","E","0","C","6","B]
 ["7","E","0","E","7","E]]

```

which is the same as

```
[["FF3762"]
 ["DE2864"]
 ["BE1966"]
 ["AE1B69"]
 ["8E0C6B"]
 ["7E0E7E"]]

```

and prints as

```
FF3762
DE2864
BE1966
AE1B69
8E0C6B
7E0E7E

```

TryAPL online!
> 3 votes

# Answer
# Pyth - 35 bytes

Horribly golfed, just gave up.

```
j++hQsMCm.HMsM:F+dc-FdvzCmiR16cd2Qe

```

Try it online here.

Example:
> 2 votes

# Answer
## PowerShell v2+, ~~176~~ ~~159~~ 150 bytes

```
param($a,$b,$n)$x=$a-split'(..)'-ne'';$a;++$n..1|%{$j=$_;-join($x=$x|%{"{0:x2}"-f(+"0x$_"-[int]((+"0x$_"-"0x$(($b-split'(..)'-ne'')[$i++%3])")/$j))})}

```

Takes the input as two strings and a number, then converts the start string into an array of strings split on every two characters, stores that into `$x`. We then output `$a` as our starting section, and loop from `++$n` to `1` (to ensure proper fenceposting).

Each iteration, sets helper `$j` to the current number (used later for ensuring we've got the right number of steps between where we're currently at to our destination) and calculates the next step based on a loop through `$x`.

Each inner loop is just an assignment. We're setting `$x` at the appropriate place equal to a new string `"{0:x2}"` using the `-f`ormat operator. The `x2` here specifies a two-digit hexadecimal output, and the input is the right-hand side of the `-f` operator. PowerShell has a native hexadecimal-to-decimal operator `0x`, so this lengthy parens-nested expression is using that operator to convert the current hex to numbers, subtracting to find the difference yet to go (done by dynamically splitting `$b` here just like we did to `$a`, and using modulo to select the right element), dividing by `$j` steps remaining, casting to an `[int]` (PowerShell does banker's rounding by default), and subtracting that step-count from the current hex to get what our next hex needs to be.

The result of that calculation is stored back into `$x` as three hex elements. That's encapsulated in parens to create a copy on the pipeline, and `-join`ed together into a single string. All those resultant strings are left on the pipeline, and output via implicit `Write-Output` happens at program execution.

---

### Example

I was given **0ba7c5** and **6c0e50** for my two colors, and **TimmyD** has 6 characters in it.

```
PS C:\Tools\Scripts\golfing> .\rgb-gradients-generation.ps1 '0ba7c5' '6c0e50' 6
0ba7c5
1991b4
277ba3
356592
434f82
513971
5f2361
6c0e50

```
> 2 votes

# Answer
# \[Groovy\] Final Update (199 Bytes) - As per request

## Non-golf

```
def g(a,b,n){
  (0..(1.0/n)).collect{
    c->
    x={s->s.split("(?<=\\G.{2})").collect{Integer.parseInt(it,16)}};
    (0..2).collect {
      (int)(x(a).get(it)*n*c+x(b).get(it)*(1-n*c))
    }.collect {
      String.format("%X", it)
    }.join()
  }
}
g('FFFFFF','000000',1/10)

```

## Golf

```
g(a,b,n){(0..(1.0/n)).collect{c->x={s->s.split("(?<=\\G.{2})").collect{Integer.parseInt(it,16)}};(0..2).collect {(int)(x(a).get(it)*n*c+x(b).get(it)*(1-n*c))}.collect{String.format("%X",it)}.join()}}

```

Try the final here: https://groovyconsole.appspot.com/script/5130696796405760

---

# OLD VERSIONS BELOW, DECLINED BY OP

---

# Groovy (123 Bytes)

## Golf

```
def g(r,g,b,r2,g2,b2,s){(1..(1.0/s)).collect{c->[(int)(r*s*c+r2*(1-s*c)),(int)(g*s*c+g2*(1-s*c)),(int)(b*s*c+b2*(1-s*c))]}}

```

## Non-golf

```
def g(r,g,b,r2,g2,b2,s){
  (1..(1.0/s)).collect {
    c ->
    [(int)(r*s*c+r2*(1-s*c)),(int)(g*s*c+g2*(1-s*c)),(int)(b*s*c+b2*(1-s*c))]
  }
}

```

## Inputs

```
r,g,b -> Starting RGB Color
r2,g2,b2 -> Ending RGB Color
s -> Gradient step

```

## Output Example

```
(00,00,00,255,255,255,.5)

```

results in

```
[
  [255, 255, 255]
  [127, 127, 127]
  [0, 0, 0]
]

```

Try it yourself: https://groovyconsole.appspot.com/script/5184465357766656

# With Hex Conversions Included

Guess I'm kind of cheating as well... Here's the script with using hex:

## New code with hex conversions:

```
    def g(r,g,b,r2,g2,b2,s){
      (0..(1.0/s)).collect {
        c ->
        String.format("%X", ((int)(r*s*c+r2*(1-s*c)))) +  String.format("%X", ((int)(g*s*c+g2*(1-s*c)))) + "" +  String.format("%X", ((int)(b*s*c+b2*(1-s*c))))
      }
    }

    g(126,34,166,218,26,33,0.0625)

```

## 188 characters when golfed:

```
def g(r,g,b,r2,g2,b2,s){(0..(1.0/s)).collect {c->String.format("%X",((int)(r*s*c+r2*(1-s*c))))+String.format("%X",((int)(g*s*c+g2*(1-s*c))))+String.format("%X",((int)(b*s*c+b2*(1-s*c))))}}

```

## Output for 000000 to FFFFFF and 16 (Username Length)

```
g(00,00,00,255,255,255,0.0625).each{println it}

```
> 1 votes

# Answer
# Python 2, 189 bytes

```
w='[int(%s[i:i+2],16)for i in range(0,6,2)]'
def f(a,b,n):
 l=lambda x,y:'%02x'%int((x*(n-i)+y*i)/n);c,d,e=eval(w%'a');f,g,h=eval(w%'b');n+=1
 for i in range(n+1):print l(c,f)+l(d,g)+l(e,h)

```
> 1 votes

# Answer
## R, 68 bytes

There is a built-in function that interpolates two colours:

```
a=scan(,'')
colorRampPalette(paste0("#",a[1:2]))(as.numeric(a[3])+2)

```

Input:

```
d9e7a5
3ef951
15

```

Output: a vector with values

```
"#D9E7A5" "#CFE89F" "#C5E99A" "#BBEA95" "#B2EB90" "#A8EC8A" "#9EED85" "#95EE80"
"#8BF07B" "#81F175" "#78F270" "#6EF36B" "#64F466" "#5BF560" "#51F65B" "#47F756"
"#3EF951"

```

Colour specification in R requires a hash symbol.

Let’s plot something, like a function:

```
filled.contour(outer(1:20, 1:20, function(x,y) sin(sqrt(x*y)/3)),
    col = colorRampPalette(paste0("#",a[1:2]))(as.numeric(a[3])+2))

```
> 1 votes

# Answer
# C, 175 169 168 bytes

```
i;j;x[6];f(a,b,n)char*a,*b;{char*f="%2x%2x%02x";for(n++;i<=n;i++,puts(""))for(j=sscanf(a,f,x,x+1,x+2)-sscanf(b,f,x+3,x+4,x+5);j++<printf(f+6,x[j]+(x[j+3]-x[j])*i/n););}

```

Ungolfed:

```
int i, j;
int x[3], y[3];

f(char *a, char *b, int n) {
  sscanf(a, "%2x%2x%2x", &x[0], &x[1], &x[2]);
  sscanf(b, "%2x%2x%2x", &y[0], &y[1], &y[2]);

  for(i = 0, n++; i <= n; i++) {
    for(j = 0; j < 3; j++)
      printf("%02x", x[j] + (y[j] - x[j]) * i / n);
    puts("");
  }
}

```

Thanks to @h-walters for shaving off 5 bytes!
> 1 votes

# Answer
# sh + ImageMagick, 81 bytes

```
convert -size 1x$((2+$3)) gradient:#$1-#$2 -depth 8 txt:-|grep -o "[A-F0-9]\{6\}"

```

usage:

```
> ./grad.sh FF3762 F08800 9
FF3762
FE3F58
FC474E
FB4F45
F9573B
F86031
F66827
F5701D
F37814
F2800A
F08800

```

("-depth 8" is not necessary if your IM is compiled with 8bpp as the default)
> 1 votes

---
Tags: code-golf, color
---


title: What's your next move?

text:
# Question
Title: What's your next move?
This challenge is to write a **minimax function** in a language of your choice, to output the next best move in an **NxN** game of **tic-tac-toe** given the **current board state**. The board input can be accepted as a **Matrix, 2D Collection** or **anything else that makes sense to you, but adheres to the rules**. The output being **the next best move** for **whoever's turn it is currently**, where **X is considered to have started**.

# Quick Background on the Minimax Algorithm

The basic idea of the minimax algorithm is to enumerate all possible outcomes as a DAG then weight them by the benefit that the sequence of moves has to the player, keyed by the first move made. All possible outcomes are then 'bucketed' by the first move, and are scored based on the sum of all outcomes (-1 for a loss, 0 for a tie and a 1 for a win). In implementations that require multiple players to play, you enumerate all possible moves by the player, and all possible responses by the opponents as well. For instance, in a game of tic-tac-toe (after the first move) there are 8 possible first moves you can make, and they all may seem equal when only analyzing the next turn. But by iterating through all possible outcomes for each possible set of moves that results in a final outcome and summing them all up, we can get a score for our next move, and have a basis for our choices.

For a better, more in-depth and contextual summary of the mini-max algorithm in terms of tic-tac-toe, read more here: http://neverstopbuilding.com/minimax

# XKCD (3x3 Solution Only)

# The Rules

* Any language can be used, but no external minimax libraries are allowed.
* Output can be a coordinate (0-n,0-n) or a number (1-n\*n) indicative of the best next move.
    + In addition to this, you must be able to identify when the best case scenario is a loss or a tie instead of a win.
    + The way you denote a loss or a tie is, once again, up to you.
* Input must use the traditional X and O, and you must assume X moves first; blank spaces can be represented by anything.
* You may assume any inputs coming into your program have n O's and n+1 X's, in other words you may assume you're getting a well-formed board.
* The current state of the board must be the only input to your program, if you are using recursion, helper methods must be made to facilitate the input requirements. See https://codegolf.stackexchange.com/a/92851/59376 for clarification.
* Any value of 10 \>= n \>= 1 must be supported; if your program "times out" for n \> 10, I find this acceptable as well, as some languages have significantly lower processing power (Especially using web-facing consoles).

# Judging

* This is code-golf, so the lowest byte-count of the program wins and standard loopholes are universally disallowed.
* In the case of a tie, the program that supports the largest 'n' will win.

# Example Inputs

## 2x2

```
[[X,O]
 [-,-]]

```

**Output:** 2 or \[0,1\] (3 or \[1,1\] would also be arguably correct) (Some form of indication of the location, arbitrary as long as you can easily explain the format you used)

---

## 3x3

```
[[X,O,X]
 [O,X,-]
 [-,-,-]]

```

**Output:** -1 (Loss)

---

Once again any input format you want is allowed, but X's and O's must be used, the examples provided were not meant to constrain to that format, just to inspire.

# Answer
> 8 votes
# Perl, ~~101~~ 98 bytes

Includes `+4` for `-0p`

Run with the input on STDIN

```
tictactoe.pl
OXO
---
--X
^D

```

Output is the same diagram, but with each move updated with its status, `1` represents a win, `2` represents a draw and `3` represents a loss. For this case that would be

```
OXO
223
21X

```

so 3 moves draw, 1 wins and 1 loses (I'll update the solution if this output format is unacceptable, but the basic code will remain the same)

`tictactoe.pl`:

```
#!/usr/bin/perl -0p
m%@{[map"O.{$_}"x"@-"."O|",1-/.(
)(.)/,@-]}Z%sx||s%-%$_="$`X$'";y/XO/OX/;do$0%eg?/1/?3:1+/2/:2

```

This is already painfully slow and uses lots of memory for the empty 3\*3 board (why actually, the recursion doesn't go that deep. Must be some memory leak). Adding memoizing costs 6 bytes but is a lot saner:

```
#!/usr/bin/perl -0p
$$_||=m%@{[map"O.{$_}"x"@-"."O|",1-/.(\n)(.)/,@-]}Z%sx||s%-%$_="$`X$'";y/XO/OX/;do$0%eg?/1/?3:1+/2/:2

```

# Answer
> 2 votes
## Javascript (ES6), ~~320~~ 294 bytes

```
(b,p,d,M,S=-2)=>(T=(p,q,r,s)=>b[p][q]==(n=b[r][s|0])&&n!='-',w=0,b.map((r,y)=>(l=r.length-1,m=15,r.map((c,x)=>(m&=8*T(l-x,x,l)+4*T(x,x,0)+2*T(x,y,0,y)+T(y,x,y))),w|=m)),w?-1:(b.map((r,y)=>r.map((c,x)=>S<1&&c=='-'&&(r[x]='O.X'[p+1],(s=-f(b,-p,1))>S&&(S=s,M=[x,y]),r[x]=c))),S=S+2?S:0,d?S:[M,S]))

```

### Input

1) An array of array of characters describing the current board, such as:

```
[['X', '-'], ['-', 'O']]

```

2) An integer describing the current turn: 1 = `X`, -1 = `O`

### Output

An array made of:

* an array describing the best move in `[x, y]` format
* the outcome of the game as an integer: 1 = win, -1 = loss, 0 = tie

### Example

In the following example, `X` is guaranteed to win by playing `[1, 2]`.

```
let f =
(b,p,d,M,S=-2)=>(T=(p,q,r,s)=>b[p][q]==(n=b[r][s|0])&&n!='-',w=0,b.map((r,y)=>(l=r.length-1,m=15,r.map((c,x)=>(m&=8*T(l-x,x,l)+4*T(x,x,0)+2*T(x,y,0,y)+T(y,x,y))),w|=m)),w?-1:(b.map((r,y)=>r.map((c,x)=>S<1&&c=='-'&&(r[x]='O.X'[p+1],(s=-f(b,-p,1))>S&&(S=s,M=[x,y]),r[x]=c))),S=S+2?S:0,d?S:[M,S]))

console.log(JSON.stringify(f(
  [['O','X','O'],
   ['-','-','-'],
   ['-','-','X']],
  1
)));
```

*A STRANGE GAME. THE ONLY WINNING MOVE IS NOT PLAY.
HOW ABOUT A NICE GAME OF CHESS?*

---
Tags: code-golf, game, board-game, tic-tac-toe
---


title: Sum or difference of two powers of two

text:
# Question
Title: Sum or difference of two powers of two
Your challenge, should you choose to accept it, is, given an integer `K >= 1`, find non-negative integers `A` and `B` such that at least one of the two conditions following hold:

1. `K = 2^A + 2^B`
2. `K = 2^A - 2^B`

If there does not exist such `A` and `B`, your program may behave in any fashion. (To clarify, `A` and `B` can be equal.)

## Test cases

There are often multiple solutions to a number, but here are a few:

```
K => A, B
1 => 1, 0
15 => 4, 0                      ; 16 - 1 = 15
16 => 5, 4                      ; 32 - 16 = 16; also 3, 3: 8 + 8 = 16
40 => 5, 3                      ; 2^5 + 2^3 = 40
264 => 8, 3
17179867136 => 34, 11           ; 17179869184 - 2048 = 17179867136

```

The last test case, `17179867136`, **must run in under 10 seconds** on any relatively modern machine. This is a code golf, so the shortest program in bytes wins. You may use a full program or a function.

# Answer
> 3 votes
# Jelly, ~~11~~ 10 bytes

```
;0+N&$BL€’

```

Applying the bit twiddling trick from the Python answer by @xnor

Test it at **TryItOnline**
All test cases are also at **TryItOnline**

How?

```
;0+N&$BL€’ - main link takes an argument, k, e.g 15
;0         - concatenate k with 0, e.g. [15, 0]
     $     - last two links as a monad
   N       - negate, e.g. -15
    &      - bitwise and, e.g. -15&15=1 since these two are called as a monad (one input)
  +        - add, vectorises, e.g. [16,1]
      B    - convert to binary, vectorises, e.g. [[1,0,0,0,0],[1]]
       L€  - length for each, e.g. [5,1]
         ’ - decrement, vectorises, e.g. [4,0]

```

# Answer
> 15 votes
## Python 2, 43 bytes

```
lambda n:[len(bin((n&-n)+k))-3for k in n,0]

```

Say that `n==2^a ± 2^b` with `a>b`. Then, the greatest power-of-2 factor of `n` is `2^b`, and we can find it using the bit-trick `2^b = n&-n`. That lets us compute `2^b + n`, which equals either `2^a + 2 * 2^b` or just `2^a`. Either one has the same-length bit-length as `a`\*. So, we output the bit-lengths of `n&-n` and `(n&-n)+n`, computed from the lengths of their binary representations. Python 3 is one byte longer for parens in `for k in(n,0)]`.

\*Except that `2^a + 2^b` with `a==b+1` has one longer bit-length, but that's fine because we can interpret that as `2^(a+1)-2^b`.

# Answer
> 8 votes
## JavaScript (ES6), 73 bytes

```
(n,[s,f,z]=/^1+(.*1)?(0*)$/.exec(n.toString(2)))=>[s.length-!!f,z.length]

```

For the subtraction case, the first number is the number of digits in the binary representation and the second number is the number of trailing zeroes. For the addition case, we subtract 1 from the first number. If the binary representation is all 1s followed by some 0s then the addition case is assumed otherwise the subtraction case is assumed. 36-byte port of @xnor's version that only works for B≤30 in JavaScript:

```
n=>[(l=Math.log2)(n+(n&=-n))|0,l(n)]

```

# Answer
> 6 votes
# Perl, ~~52~~ ~~49~~ 32 bytes

Old solution (49 bytes)

Includes +1 for `-p`

Give input on STDIN:

```
pow2.pl <<< 17179867136

```

`pow2.pl`

```
#!/usr/bin/perl -p
$_=reverse sprintf"%b",$_;/()1(?:1+|0*)/;$_="@+"

```

However, using xnor's algorithm and adding a twist gives 32 bytes:

```
perl -nE 'say 13/9*log|0for$;=$_&-$_,$_+$'

```

Just the code:

```
say 13/9*log|0for$;=$_&-$_,$_+$

```

This suffers from severe rounding error because `13/9 = 1.444...` is quite a bit above `1/log 2 = 1.44269...` (`log` itself also has a rounding error but that is so much smaller that we can wrap it up in the analysis of 13/9). But since any `2**big - 2** small` gets corrected to `2** big` before the log this doesn't mater and the calculation for `2**big + 2 * 2**small` gets truncated down so is also safe.. And at the other side of the range `2**n+2**(n-1)` doesn't get increased enough in the range `[0,64]` (I can't properly support more than the integer range anyways due to the use of `&`) to lead to a wrong result (multiplicator `1.5` however would be too far off for large numbers).

# Answer
> 5 votes
# Brachylog, 23 bytes

```
,A:B#+.:2rz:^a{+|-}?,.=

```

Try it online!

This is much faster than required, e.g. this is still under 10 seconds on TIO.

### Explanation

This is basically a direct transcription of the formula with no optimization:

```
,A:B     The list [A, B]
#+       Both A and B are greater than or equal to 0
.        Output = [A, B]
:2rz     The list [[2, A], [2, B]]
:^a      The list [2^A, 2^B]
{+|-}?   2^A + 2^B = Input OR 2^A - 2^B = Input
,.=      Assign a value to A and B which satisfy those constraints

```

# Answer
> 4 votes
# Mathematica, ~~57~~ 54 bytes

*Saved 3 bytes thanks to LegionMammal978!*

```
Do[Abs[2^a-#]==2^b&&Print@{a,b},{a,2Log@#+1},{b,0,a}]&

```

Actually prints out all1 appropriate pairs {a,b}. `2Log@#+1` is an upper bound for the largest `a` that can possibly appear when representing the input `#` (the tight upper bound is Log\[2#\]/Log\[2\] = 1.44... Log\[#\] + 1). Runs almost instantaneously on the test input, and in less than a quarter second (on my new but off-the-shelf computer) on 100-digit inputs.

1 Letting `a` start at the default value of 1 instead of 0 saves two bytes; it causes the output {0,0} to be missed when the input is 2, but finds the output {2,1} in that case, which is good enough.

# Answer
> 4 votes
# Python, 69 bytes

```
def f(k):b=bin(k)[::-1];return len(b)-2-(b.count('1')==2),b.find('1')

```

Tests are on **ideone**

Since non-valid input can do anything, we know that if the input has exactly 2 bits set it is the sum of those 2 powers of 2, and otherwise (if valid) it will be be a run of some number of bits (including the possibility of just 1 bit) and will be the difference between the next highest power of 2 than the MSB and the LSB set.

# Answer
> 4 votes
## JAVA 7 ,~~142~~ ,~~140~~, 134 BYTES

This is my first post on PPCG!I would really appreciate for feedback on golfing tips
*Thanks to **frozen** for saving 2 bytes*

```
void f(long n){for(int i=-1,j;i++<31;)for(j=0;j++<34;){long a=1,x=a<<i,y=a<<j;if(x+y==n|y-x==n){System.out.println(j+" "+i);return;}}}

```

## UNGOLF

```
void f(long n){
    for(int i=-1,j;i++<31;)
         for(j=0;j++<34;){
          long a=1,x=a<<i,y=a<<j;
            if(x+y==n|y-x==n){
            System.out.println(j+" "+i);
        return;
        }
            }
    }

```

ideone

# Answer
> 3 votes
# MATL, ~~23~~ 22 bytes

```
BnQ:qWtG-|ym)1)tG-|hZl

```

Try it online! Or verify all test cases.

### Explanation

```
B      % Implicit input. Convert to binary. Gives n digits
nQ:q   % Range [1 ... n+1]
W      % 2 raised to that, element-wise: gives [1 2 4 ... 2^(n+1)] (*)
tG-|   % Duplicate. Absolute difference with input, element-wise (**)
y      % Push a copy of (*)
m      % True for elements of (**) that are members of (*)
)      % Use as logical index to select elements from (*)
1)     % Take the first element. Gives power of the first result
tG-|   % Duplicate. Absolute difference with input. Gives power of the second result
hZl    % Concatenate. Take binary logarithm. Implicit display

```

# Answer
> 3 votes
# Perl 6, 41 bytes

```
{.base(2).flip~~/1[1+|0*]/;$/.to,$/.from}

```

( Algorithm shamelessly copied from the Perl 5 answer )

## Explanation:

```
# bare block lambda with implicit parameter ｢$_｣
{
  # turn into binary
  # ( implicit method call on ｢$_｣ )
  .base(2)

  # flip the binary representation
  .flip

  ~~ # smartmatch that against:

  /
    1      # a ｢1｣
    [
      | 1+ # at least one ｢1｣
      | 0* # or any number of ｢0｣
    ]
  /;

  # returns a list comprised of

  # the position of the end of the match (larger of the two)
  $/.to,
  # the position of the beginning of the match
  $/.from
}

```

## Usage:

```
# give it a lexical name for clarity
my &bin-sum-diff = {.base(2).flip~~/1[1+|0*]/;$/.to,$/.from}

say bin-sum-diff 15; # (4 0)
say bin-sum-diff 16; # (5 4)

say bin-sum-diff 20; # (4 2)
# 2**4==16, 2**2==4; 16+4 == 20

say bin-sum-diff 40; # (5 3)
say bin-sum-diff 264; # (8 3)
say bin-sum-diff 17179867136; # (34 11)

```

# Answer
> 1 votes
# PHP, 73 bytes

I could have copied Jonathan´s Pyhton 2 solution for 54 bytes (+13 overhead),
but wanted to come up with something different.

save to file, then execute with `php` or `php-cgi`.

```
<?=strlen($n=decbin($argv[1]))-!!strpos($n,'01')._.strpos(strrev($n),49);

```

prints `a` and `b` separated by an underscore, anything for no solution.

**distinctive solution, 96 bytes**

```
<?=preg_match('#^(10*1|(1+))(0*)$#',decbin($argv[1]),$m)?strlen($m[0])-!$m[2]._.strlen($m[3]):_;

```

prints `a` and `b` separated by an underscore; a sole underscore for no solution.

It even tells you the operation for 11 more bytes:
Just replace the first underscore in the code with `'-+'[!$m[2]]`.

# Answer
> 0 votes
# PHP ,117 Bytes

```
if(preg_match("#^(1+|(10*1))0*$#",$b=decbin($k=$argv[1]),$t))echo($l=strlen($b))-($t[2]?1:0).",",$l+~strrpos($b,"1");

```

Extended version 4 Cases

```
$l=strlen($b=decbin($k=$argv[1]));
// Case 1: n=2(n-1)=n+n or n=n*(2-1)=2n-n
if(preg_match('#^100*$#',$b))echo($l-2).'a+'.($l-2).':'.$l.'a-'.($l-1);
// Case 2: n-m
elseif(preg_match('#^1+0*$#',$b)){echo $l.'b-',strpos($b,"0")?$l-strpos($b,"0"):0;}
// Case 3: n+m
elseif(preg_match('#^10*10*$#',$b))echo ($l-1).'c+',$l-strrpos($b,"1")-1;
else echo "Nothing";

```

the short version union Case 1 and 3 and makes a Difference to Case 3 and in both versions Case 4 gives no output.

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


# Question
Title: Produce the word 'codegolf' without using any of its characters in code
You need to produce the word **codegolf**

---

### **Rules:**

1. ***None*** of the characters of the word `codegolf` (i.e. 'c', 'o', 'd', 'e', 'g', 'o', 'l' and 'f') in either case can exist anywhere in the code.
2. Case of the word must be one of three:

* All Upcase (`CODEGOLF`)
    * All Downcase (`codegolf`)
    * Capitalized (`Codegolf`)
3. You only need to produce it somehow so there can be other characters in the output as well. For example, `21§HCodegolf092` is an acceptable result.
4. The shortest code (counting in bytes) to do so in any language wins.

---

I guess it will be less trickier in some languages than others (Brainfuck, Javascript, etc.)

# Answer
> 12 votes
## Bash(works if there are no other files matching `/bin/?at`), 14

```
/bin/?at /*/u*

```

This expands to `cat <files>`, where the files include /dev/urandom. Because of the infinite monkey theorem, this will eventually output "codegolf".

# Answer
> 9 votes
# PHP, 8 bytes

```
CODEGOLF

```

Does not contain 'c', 'o', 'd', 'e', etc.

(You *might* want to ban their uppercase versions as well.)

# Answer
> 9 votes
# C - lots of characters

Without `include`, `define`, `char`, `printf`, `return` and lots of other useful things, it's a real challenge to try to do this in C.

I thought of outputting upside down letters, i.e. ɟloƃǝpoɔ, but the l and o are the same.

So here's the best I can do, which many people might remember as being very much like their first C assignment.

```
int main()
{
    puts("                   @                       @     @@ ");
    puts("                   @                       @    @   ");
    puts("                   @                       @    @   ");
    puts("  @@@    @@@    @@@@   @@@    @@@@   @@@   @  @@@@@ ");
    puts(" @   @  @   @  @   @  @   @  @   @  @   @  @    @   ");
    puts(" @      @   @  @   @  @@@@@  @   @  @   @  @    @   ");
    puts(" @   @  @   @  @   @  @      @   @  @   @  @    @   ");
    puts("  @@@    @@@    @@@@   @@@    @@@@   @@@   @    @   ");
    puts("                                 @                  ");
    puts("                                 @                  ");
    puts("                              @@@                   ");
}

```

To compile: `gcc -o codegolf codegolf.c`, surprisingly `gcc`, at least my installation, doesn't complain about missing includes or returns.

Running:

```
 $ ./codegolf
                   @                       @     @@
                   @                       @    @
                   @                       @    @
  @@@    @@@    @@@@   @@@    @@@@   @@@   @  @@@@@
 @   @  @   @  @   @  @   @  @   @  @   @  @    @
 @      @   @  @   @  @@@@@  @   @  @   @  @    @
 @   @  @   @  @   @  @      @   @  @   @  @    @
  @@@    @@@    @@@@   @@@    @@@@   @@@   @    @
                                 @
                                 @
                              @@@

```

If you squint your eyes and/or zoom out, it kind of looks okay!

# Answer
> 6 votes
# Pyth, 9 bytes with updated rules

```
^v"\107"8

```

`v"\107"` evals a string containing `G`, octal escaped, which is the pyth variable for the alphabet.

`^G8`, is the result, which prints all 8 letter strings in the lowercase alphabet, including `codegolf`. Runs out of memory on my machine, unfortunately.

# Answer
> 5 votes
# Javascript (2,786 Bytes)

I'm not competing with this answer, just pointing out that it can be done.

```
([]+{})[!+[]+!![]+!![]+!![]+!![]]+([]+{})[+!![]]+([][[]]+[])[!+[]+!![]]+([][[]]+[])[!+[]+!![]+!![]]+[][(![]+[])[!+[]+!![]+!![]]+([]+{})[+!![]]+(!![]+[])[+!![]]+(!![]+[])[+[]]][([]+{})[!+[]+!![]+!![]+!![]+!![]]+([]+{})[+!![]]+([][[]]+[])[+!![]]+(![]+[])[!+[]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+[]]+([]+{})[!+[]+!![]+!![]+!![]+!![]]+(!![]+[])[+[]]+([]+{})[+!![]]+(!![]+[])[+!![]]]((!![]+[])[+!![]]+([][[]]+[])[!+[]+!![]+!![]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+!![]]+([]+{})[!+[]+!![]+!![]+!![]+!![]+!![]+!![]]+([][[]]+[])[+[]]+([][[]]+[])[+!![]]+([][[]]+[])[!+[]+!![]+!![]]+(![]+[])[!+[]+!![]+!![]]+([]+{})[!+[]+!![]+!![]+!![]+!![]]+(+{}+[])[+!![]]+([]+[][(![]+[])[!+[]+!![]+!![]]+([]+{})[+!![]]+(!![]+[])[+!![]]+(!![]+[])[+[]]][([]+{})[!+[]+!![]+!![]+!![]+!![]]+([]+{})[+!![]]+([][[]]+[])[+!![]]+(![]+[])[!+[]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+[]]+([]+{})[!+[]+!![]+!![]+!![]+!![]]+(!![]+[])[+[]]+([]+{})[+!![]]+(!![]+[])[+!![]]]((!![]+[])[+!![]]+([][[]]+[])[!+[]+!![]+!![]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+!![]]+([]+{})[!+[]+!![]+!![]+!![]+!![]+!![]+!![]]+(![]+[])[!+[]+!![]]+([]+{})[+!![]]+([]+{})[!+[]+!![]+!![]+!![]+!![]]+(+{}+[])[+!![]]+(!![]+[])[+[]]+([][[]]+[])[!+[]+!![]+!![]+!![]+!![]]+([]+{})[+!![]]+([][[]]+[])[+!![]])())[!+[]+!![]+!![]]+([][[]]+[])[!+[]+!![]+!![]])()([][(![]+[])[!+[]+!![]+!![]]+([]+{})[+!![]]+(!![]+[])[+!![]]+(!![]+[])[+[]]][([]+{})[!+[]+!![]+!![]+!![]+!![]]+([]+{})[+!![]]+([][[]]+[])[+!![]]+(![]+[])[!+[]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+[]]+([]+{})[!+[]+!![]+!![]+!![]+!![]]+(!![]+[])[+[]]+([]+{})[+!![]]+(!![]+[])[+!![]]]((!![]+[])[+!![]]+([][[]]+[])[!+[]+!![]+!![]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+!![]]+([]+{})[!+[]+!![]+!![]+!![]+!![]+!![]+!![]]+([][[]]+[])[!+[]+!![]+!![]]+(![]+[])[!+[]+!![]+!![]]+([]+{})[!+[]+!![]+!![]+!![]+!![]]+(+{}+[])[+!![]]+([]+[][(![]+[])[!+[]+!![]+!![]]+([]+{})[+!![]]+(!![]+[])[+!![]]+(!![]+[])[+[]]][([]+{})[!+[]+!![]+!![]+!![]+!![]]+([]+{})[+!![]]+([][[]]+[])[+!![]]+(![]+[])[!+[]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+[]]+([]+{})[!+[]+!![]+!![]+!![]+!![]]+(!![]+[])[+[]]+([]+{})[+!![]]+(!![]+[])[+!![]]]((!![]+[])[+!![]]+([][[]]+[])[!+[]+!![]+!![]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+!![]]+([]+{})[!+[]+!![]+!![]+!![]+!![]+!![]+!![]]+(![]+[])[!+[]+!![]]+([]+{})[+!![]]+([]+{})[!+[]+!![]+!![]+!![]+!![]]+(+{}+[])[+!![]]+(!![]+[])[+[]]+([][[]]+[])[!+[]+!![]+!![]+!![]+!![]]+([]+{})[+!![]]+([][[]]+[])[+!![]])())[!+[]+!![]+!![]]+([][[]]+[])[!+[]+!![]+!![]])()(([]+{})[+[]])[+[]]+(!+[]+!![]+!![]+!![]+!![]+!![]+[])+(!+[]+!![]+!![]+!![]+!![]+!![]+!![]+[]))+([]+{})[+!![]]+(![]+[])[!+[]+!![]]+([][[]]+[])[!+[]+!![]+!![]+!![]]

```

---

**Output:**

```
codegolf

```

# Answer
> 5 votes
# CJam, 15 bytes

```
"r~utv~}w"{H^}%

```

I guess it should be shorter than Marbelous.

# Answer
> 5 votes
## PHP, 13 bytes

```
<?=~œ›š˜“™;

```

StackExchange may swallow some of the control characters. Here's a hexdump of the program:

```
3c 3f 3d 7e 9c 90 9b 9a 98 90 93 99 3b

```

It bitwise inverts the string, and prints it using the PHP short tag syntax.

# Answer
> 5 votes
## Perl - 12

```
say a.."z"x8

```

This also takes advantage of rule 3. It prints every word from `a` to `zzzzzzzz`.

Run with:

```
perl -E'say a.."z"x8'

```

# Answer
> 5 votes
# Java, 118 Bytes

This is probably the lamest answer. Java programs have many key words. In order to print anything you have to use `System.out`. Despite all of these restrictions I can remove all of the letters in `codegolf` from my program except two letters.

With `c` and `o` allowed, 118 bytes:

```
c\u006cass a{pub\u006cic static voi\u0064 main(String[]a){Syst\u0065m.out.print("\143\157\144\145\143\157\154\146");}}

```

With `l` and `o` allowed, 123 bytes:

```
\u0063lass a{publi\u0063 stati\u0063 voi\u0064 main(String[]a){Syst\u0065m.out.print("\143\157\144\145\143\157\154\146");}}

```

With `c` and `f` allowed, 128 bytes:

```
c\u006cass a{pub\u006cic static v\u006fi\u0064 main(String[]a){Syst\u0065m.\u006fut.print("\143\157\144\145\143\157\154\146");}}

```

With `l` and `f` allowed, 133 bytes:

```
\u0063lass a{publi\u0063 stati\u0063 v\u006fi\u0064 main(String[]a){Syst\u0065m.\u006fut.print("\143\157\144\145\143\157\154\146");}}

```

With no restrictions on boilerplate code, 98 bytes:

```
class a{public static void main(String[]a){System.out.print("\143\157\144\145\143\157\154\146");}}

```

Expanded:

```
class a{

    public static void main(String[]a){
        System.out.print("\143\157\144\145\143\157\154\146");
    }

}

```

# Answer
> 4 votes
# CJam, 10 bytes

```
'P,{_m*}3*

```

It runs very slowly, and it should run out of memory on most computers. But if it exited successfully finally, it will print a lot of things including `CODEGOLF`.

# Answer
> 4 votes
# Marbelous \- 9 bytes

```
7A
/\/\??

```

This will with a probability approaching 1 print a string containing all three acceptable outputs, since it prints an endless string of random ascii characters (up to and including the lowercase 'z' with ascii value 7A). Nothing was specified about whether this program should terminate. And just to make it clear, the characters get printed as they get generated, not after the program terminates (which is never).

# Answer
> 3 votes
## Brainfuck (66 Bytes)

Can you do it in Brainfuck? Yes? Than I do it in Brainfuck!

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

```

**Output:**

```
CODEGOLF

```

# Answer
> 3 votes
# Python 2.7, ~~52~~ 48 bytes

```
print('%'+`map`[13])*8%(67,79,68,69,71,79,76,70)

```

**Output:**

```
CODEGOLF

```

This answer creates a format string using a 'c' found in the representation string of the built-in `map` function. The program then uses the format string to convert each integer into a character that creates the 'CODEGOLF' string.

# Answer
> 3 votes
# dc, 20

```
4850170388041124934P

```

Prints the ASCII byte stream 0x434F4445474F4C46.

# Answer
> 3 votes
# Javascript (29 bytes / 25 characters)

```
this['bt\x6fa']("àÄâÅ")

```

SE strips out the control characters, so here's a hex dump:

```
74 68 69 73 5B 27 62 74 5C 78 36 66 61 27 5D 28 22 08 C3 A0 C3 84 18 C3 A2 C3 85 22 29

```

## With escape characters (34 / 29)

```
this['bt\x6fa']("\bàÄ\x18âÅ")

```

# Answer
> 3 votes
# J, 6 (12?) char

A sentence returning `CODEGOLF` at the REPL, along with every other combination of 8 ASCII characters and a whole bunch of spaces, newlines, and box-drawing characters.

```
{8#<a.

```

If you want to toss this into STDOUT, prepend `1!:2&4` to double the charcount.

# Answer
> 3 votes
# C, ~~49~~ 48 bytes

-1 byte thanks to ceilingcat.

```
main(){int a[]={1701080931,1718382439};puts(a);}

```

# C11, ~~46~~ 45 bytes

```
main(){puts((int[]){1701080931,1718382439});}

```

It's obviously possible in C.

Works in 32bit little-endian systems.

# Answer
> 2 votes
# Brainfuck (145 Bytes)

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

```

---

**Output:**

```
CODEGOLF

```

# Answer
> 2 votes
# CJam, 18 bytes

```
"1n¯]"245bHb{'B+}%

```

This answer prints the result instantaneously without consuming infinite system memory :)

It is just base conversion of the string `CODEGOLF` to both save bytes and to avoid using any of the restricted characters.

Just try it out here

# Answer
> 2 votes
Alright, here we go again.

# **The Hexadecimal Stacking Pseudo-Assembly Language** (156):

(Technically not a valid entry, or so I'm told)

```
200066
400000
200063
400000
200009
400000
210000
200066
400000
200009
400000
210000
200067
400000
200065
400000
200064
400000
200066
400000
200009
400000
210000
200063
400000
140000

```

Output:

```
codegolf
```

# Answer
> 1 votes
# Shell, 21

```
tr 2-@ A-P<<<4@568@=7

```

# Answer
> 1 votes
# ROT13, 8 bytes

```
pbqrtbys

```

`rot13` is part of `bsdgames`.

# Answer
> 1 votes
# Unnamed Two-Dimensional Programming Language, 26 bytes

```
67&79&68&69&71&79&76&70&s;

```

**Output:**

```
CODEGOLF

```

You can try it out here (Replace the code in the `code()` function with this code).

If it is acceptable, the final semicolon can be removed and the program will loop infinitely (in theory, not in the interpreter, as the interpreter gives up after 2048 instructions to avoid a browser-crashing infinite loop) for a score of **25 bytes**.

This works by pushing the values for the characters `CODEGOLF` to the stack, printing them, and terminating.

# Answer
> 1 votes
# Jelly, 7 bytes

```
“£ṙɲI⁵»

```

Try it online!

# Answer
> 1 votes
# Vitsy, 6 bytes

```
<ZR^72

```

This has a 1 in 36028797018963968 chance of printing the right order of characters per character output with ~10000 characters output a second. This means that, by 3.17 million years from now, you'll almost certainly have seen it.

:)

Using a method found here.

Try it online!

# Answer
> 0 votes
**Lua, 33 bytes**

CODEGOLF (33 bytes)

```
print("\67\79\68\69\71\79\76\70")

```

Codegolf (40 bytes)

```
print("\67\111\100\101\103\111\108\102")

```

codegolf (40 bytes)

```
print("\99\111\100\101\103\111\108\102")

```

# Answer
> 0 votes
## Pyke, 5 bytes

```
~aHpr

```

Try it here!

# Answer
> 0 votes
# 05AB1E, 5 bytes

```
’ƒËŠˆ

```

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

---
Tags: code-golf, restricted-source
---


title: Distance to four

text:
# Question
Title: Distance to four
This challenge is based on this video. I recommend that you watch it before trying this challenge.

First we define a function. This function (OEIS) takes a integer n as input and outputs the number of letters in the English representation of n (without spaces or hyphens). For example "three" has 5 letters so 3 maps to 5.

As demonstrated in the video starting with any number repeating this process will eventually result in a four, which will map to itself forever.

Here is a crude directed graph showing the orbits of the numbers less than 16:

```
  12 11
    \|
15 2 6 1 10 14 13
  \ \|/ /  /  /
   7 3-/  8--/
    \|   /
 9 0 5--/
  \ \|
   \-4

```

Your challenge is to determine the number of steps that a number will take (or the number of times this function must be applied to a number) before reaching four (i.e. the level on the directed graph pictured).

## Forming english numbers

Here is a brief explanation of how one should form english words for this challenge:

The numbers one through nineteen are:

one, two, three, four, five, six, seven, eight, nine, ten, eleven, twelve, thirteen, fourteen, fifteen, sixteen, seventeen, eighteen, nineteen

For numbers greater than nineteen the process is as follows:

If the number has a hundreds place begin with the name of digit in the hundreds place and "hundred".

e.g.

```
100 -> "onehundred"

```

If the remainder is less than twenty append the remainder's English representation.

e.g.

```
714 -> "sevenhundredfourteen"

```

Otherwise if the tens digit is not zero append the proper representation:

```
2-> twenty
3-> thirty
4-> forty
5-> fifty
6-> sixty
7-> seventy
8-> eighty
9-> ninety

```

e.g.

```
470 -> "fourhundredseventy"

```

Finally if there is a one's digit append its representation

e.g.

```
681 -> "sixhundredeightyone"

```

## Further Stipulations

* For numbers greater than one hundred you should leave out the "and" when counting the number of letters. For instance 577 is "fivehundredseventyseven" which has 23 letters.
* Your program must accept all integers greater than 0 and less than 1,000 as input via standard methods.
* Your program must output the number of steps required to standard output methods.
* This is codegolf so the solution with the fewest bytes wins.

## Test cases

```
1 -> 3
4 -> 0
7 -> 2
23 -> 5
577 -> 6
600 -> 4

```

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

```
f=(n,a="03354435543668877998")=>n-4&&1+f(7*(n>99)-(-a[n/100|0]-(a[n%=100]||a[n%10])-"0066555766"[n/10|0]))

```

Strings seem to be the best way to encode the length, despite the numeric conversion overhead.

# Answer
> 2 votes
# Python, with num2words, ~~97 113 115 94 93~~ 92 bytes

+16 bytes (forgot the hyphenation that num2words applies which does not actually change the results of any of the test cases, even though `23` and `577` each have a hyphen)
+2 bytes (forgot to include `f=` although recursive)
-20 bytes (use `re`)
-8 bytes thanks to @Wheat Wizard (use `~`, replace `n!=4` with `n-4`, and ...one line import \>\_\<)
-1 byte thanks to @Cyoce (space from `4 and`)

```
import re,num2words as w
f=lambda n:n-4and-~f(len(re.sub('\W|and','',w.num2words(n))))

```

Just counts up the number of steps; works for huge and negative integers too (`\W` finds the spaces, commas and hyphens in the num2words result):

```
>>> for test in (1,4,7,23,577,600,-1*2**96,3**96):
...     print('test: {0}  ->  {1}'.format(test, f(test)))
...
test: 1  ->  3
test: 4  ->  0
test: 7  ->  2
test: 23  ->  5
test: 577  ->  6
test: 600  ->  4
test: -79228162514264337593543950336  ->  4
test: 6362685441135942358474828762538534230890216321  ->  5

```

Here is that last case, step by step:

```
sixquattuordecillionthreehundredsixtytwotredecillionsixhundredeightyfiveduodecillionfourhundredfortyoneundecilliononehundredthirtyfivedecillionninehundredfortytwononillionthreehundredfiftyeightoctillionfourhundredseventyfourseptillioneighthundredtwentyeightsextillionsevenhundredsixtytwoquintillionfivehundredthirtyeightquadrillionfivehundredthirtyfourtrilliontwohundredthirtybillioneighthundredninetymilliontwohundredsixteenthousthreehundredtwentyone
fourhundredfiftyone
nineteen
eight
five

```

# Answer
> 1 votes
# Pyth - 54 bytes

Will try to refactor.

```
KjC"Y©åláóê¤"Ttl.u?<NyT@KNs+V@LKJ_jNT[Z@jC"Ckg"ThtJ7

```

Test Suite.

# Answer
> 1 votes
# Java, ~~556~~ 295 bytes

Thanks to @KevinCruijssen for saving *261 bytes*

```
  void int(n) {int s[]={0,3,3,5,4,4,3,5,5,4,3,6,6,8,8,7,7,9,9,8,6,9,9,11,10,6,6,5,5,7,7,6};int c=0,t=(int)Math.pow(10,(int)Math.log10(n)),v=1;while(n>0){if(n/100>0)c+=(s[n/100]+7);else {if(n>0&n<25){c+=s[n];break;}else{c+=s[(n/10)+22];}}n=n%t;t=t/10;}while(c!=4){v++;c=s[c];}System.out.print(v);}

```

# Ungolfed:

```
  void int(n) {

    int s[]={0,3,3,5,4,4,3,5,5,4,3,6,6,8,8,7,7,9,9,8,6,9,9,11,10,6,6,5,5,7,7,6};
     int c=0,t=(int)Math.pow(10,(int)Math.log10(n)),v=1;
         while(n>0){
            if(n/100>0)
                c+=(s[n/100]+7);
            else {if(n>0&n<25){
                c+=s[n];
            break;
            }
            else{
                c+=s[(n/10)+22];

            }
            }
            n=n%t;
            t=t/10;
        }

        while(c!=4)
        {
            v++;
        c=s[c];
        }
System.out.print(v);
}

```

# Answer
> 1 votes
# Mathematica, 89 bytes

```
Length@FixedPointList[StringLength@StringReplace[IntegerName@#,{" "->"","-"->""}]&,#]-2&

```

Typical Mathematica: built-in functions good, long function names bad. `FixedPointList` applies its first argument (a function) to the second argument repeatedly until the answer doesn't change, listing all results; the results include the original input and two copies of the repeated output, hence the `-2` at the end. Mathematica's built-in `IntegerName` contains spaces and hyphens, so we need to get rid of those by hand.

Annoyingly, `IntegerName`'s output contains the character "‐" (Unicode #8208) rather than normal hyphens; that's why this submission is 89 bytes rather than 88. (And I couldn't precede the code above with four spaces *and* have it accept the Unicode character—any help?—so the above code won't work exactly right if cut and pasted.)

# Answer
> 1 votes
# Python 2.7, ~~344~~ ~~216~~ 208 bytes:

```
x=`input()`;c=0;y=lambda v:dict(zip(range(0,10),[0]+v));l=[3,3,5,4,4,3,5,5,4];d=y(l);e=y([3,6,6,6,5,5,7,7,6]);f=y([i+7for i in l])
while x!='4':x=`sum([q[int(r)]for q,r in zip([d,e,f],x[::-1])])`;c+=1
print c

```

Does not use any external libraries unlike other Python answer. Takes input through `stdin` and outputs to `stdout`.

Repl.it with All Test Cases!

## Explanation

First creates 3 dictionaries with each one pairing the length of the English word representations of each number to the number it represents in the closed interval `[1,9]` in the ones, tens, and hundreds place, respectively. For example, the first entry in dictionary `d` is `1:3` as `1` is spelled `one` in English and has `3` letters.

Then, each digits place in some string input `x` is assigned to its corresponding dictionary, after which each number in each place is matched up with its value in the corresponding dictionary. For instance, suppose the input number was `23`. The `20` in the tens place would be paired with dictionary `e`, in which it is matched with `6`, and the `3` in the ones place would be paired with dictionary `d`, in which it is matched with `5`. These matched digits are then added together to represent the length of the English representation of the number, which is assigned to `x` as a string and, as long as `x!='4'`, the while loop goes on, incrementing `c` by `1` each time to represent the number of steps taken thus far. Therefore, `23` would correspond to `11`, which would in turn correspond to `6` which would turn to `3` and then to `5` and finally to `4`, resulting in `5` total steps.

Finally, once the loop finishes, `c` is output to `stdout` to represent the "Distance to Four", which in this case would be `5`.

---
Tags: code-golf, number, natural-language
---


title: 4-way intersection generator

text:
# Question
Title: 4-way intersection generator
Here is an ASCII-art of a 4-way intersection:

```
     |  |  |
     |     |
     |  |  |
     |     |
     |  |  |
-----+-----+-----
     |     |
- - -|     |- - -
     |     |
-----+-----+-----
     |  |  |
     |     |
     |  |  |
     |     |
     |  |  |

```

(Note how the horizontal roads are 3 rows tall, while the vertical roads are 5 columns wide. This is for aesthetic reasons, because of the rectangular font.)

Your challenge is to produce this ASCII art. However, as I'm sure you all know, not every intersection has a road travelling off in every single direction. This particular intersection goes `NESW`, but some intersections might go, for example, `NW`:

```
     |  |  |
     |     |
     |  |  |
     |     |
     |  |  |
-----+-----+
     |     |
- - -|     |
     |     |
-----+-----+

```

Or it might go `SWE`:

```
-----+-----+-----
     |     |
- - -|     |- - -
     |     |
-----+-----+-----
     |  |  |
     |     |
     |  |  |
     |     |
     |  |  |

```

Or it may even go `E`, just a single direction (although you can hardly call this an *intersection*, but try to avoid being overly pedantic):

```
     +-----+-----
     |     |
     |     |- - -
     |     |
     +-----+-----

```

You need to write a program or function that can easily generate *any* of these combinations. More specifically, your challenge is to write a program or function that takes a string of directions, consisting of `NESW`, as input, and outputs or returns this ASCII art of an intersection with roads pointing in those directions. These directions may appear in any order, but the input *will not* contain any characters except for `N`, `E`, `S`, or `W`. If you like, you may request inputs to be lowercase instead, but you must specify this in your answer. You may also assume that all inputs will contain at least one direction.

The last example had leading spaces on each line, because there is no road going west. If you do not have a road going west, these leading spaces are optional. This:

```
+-----+-----
|     |
|     |- - -
|     |
+-----+-----

```

Would also be an acceptable output. Similarly, if `N` or `S` is gone, empty lines in there place are optional. One trailing newline is allowed, and trailing spaces are allowed as long as the output is *visually* the same.

You may take input and output in any reasonable format, such as STDIN/STDOUT, command line args, files, function arguments/return values, etc.

As usual, this is , so try to get the shortest possible answer in whatever language you happen to use!

# Sample IO:

```
NESW:

     |  |  |
     |     |
     |  |  |
     |     |
     |  |  |
-----+-----+-----
     |     |
- - -|     |- - -
     |     |
-----+-----+-----
     |  |  |
     |     |
     |  |  |
     |     |
     |  |  |

NS:

|  |  |
|     |
|  |  |
|     |
|  |  |
+-----+
|     |
|     |
|     |
+-----+
|  |  |
|     |
|  |  |
|     |
|  |  |

S:

+-----+
|     |
|     |
|     |
+-----+
|  |  |
|     |
|  |  |
|     |
|  |  |

EW:

-----+-----+-----
     |     |
- - -|     |- - -
     |     |
-----+-----+-----

SE:
+-----+-----
|     |
|     |- - -
|     |
+-----+-----
|  |  |
|     |
|  |  |
|     |
|  |  |

```

# Answer
> 10 votes
## Javascript (ES6), ~~190~~ ~~187~~ 185 bytes

This is an attempt to build this ASCII art character per character by iterating on a 17x15 matrix. Therefore, the output is always made of 15 rows of 17 columns with the intersection of the roads centered in the middle.

```
p=>eval("for(y=15,s='';y--;s+=`\n`)for(x=17;x--;)s+=' |-+'[+[a=y>4,b=y<10,c=x>4,d=x<12].every((c,i)=>c|p.search('SNEW'[i])+1)&&!((z=x-8||y&1|a&b)&&z*z-9)+2*!((z=y-7||x&1|c&d)&&z*z-4)]")

```

### Ungolfed and commented

```
for(y = 15, s = ''; y--; s += `\n`)   // iterate on y, from 14 to 0 / append line feeds
  for(x = 17; x--;)                   // iterate on x, from 16 to 0
    s += ' |-+' [                     // append next character to string
      +[ a = y > 4,                   // a = outside South area?
         b = y < 10,                  // b = outside North area?
         c = x > 4,                   // c = outside East area?
         d = x < 12 ]                 // d = outside West area?
      .every((c, i) =>                // for each area, see if either:
        c |                           //   - we're currently outside it
        p.search('SNEW' [i]) + 1      //   - or it's an allowed area (p = function param.)
      )                               // if all tests pass, add a:
      &&                              //   - vertical bar (encoded as 1) if:
      !((z = x - 8 || y & 1 | a & b)  //     - x=8, y is even and we're not in the middle
      && z * z - 9)                   //     - OR x=5 OR x=11 (<=> (x-8)*(x-8) = 9)
      + 2 *                           //   - horizontal bar (encoded as 2) if:
      !((z = y - 7 || x & 1 | c & d)  //     - y=7, x is even and we're not in the middle
      && z * z - 4)                   //     - OR y=5 OR y=9 (<=> (y-7)*(y-7) = 4)
    ]                                 // (vertical + horizontal = 3, which leads to '+')

```

### Matrix

Below is the matrix with the coordinates used in the code.

### Demo

The following snippet allows to try any road configuration.

```
let f =
p=>eval("for(y=15,s='';y--;s+=`\n`)for(x=17;x--;)s+=' |-+'[+[a=y>4,b=y<10,c=x>4,d=x<12].every((c,i)=>c|p.search('SNEW'[i])+1)&&!((z=x-8||y&1|a&b)&&z*z-9)+2*!((z=y-7||x&1|c&d)&&z*z-4)]")

function update() {
  document.getElementById("o").innerHTML = f(document.getElementById("s").value);
}
update();
```

```
<input id="s" size=4 value="NSEW" oninput="update()">
<pre id="o" style="font-size:9px"></pre>
```

# Answer
> 8 votes
## PowerShell v3+, ~~226~~ ~~204~~ ~~192~~ 191 bytes

```
param([char[]]$a)($n=0..4|%{($x=' '*5*($b=87-in$a))+('|  |  |',($w='|     |'))[$_%2]})*(78-in$a)
($z=($y='-'*5)*$b+"+$y+"+$y*($c=69-in$a))
$x+$w
'- - -'*$b+$w+'- - -'*$c
$x+$w
$z
$n*(83-in$a)

```

Takes input as a string of capital letters, explicitly casts it as a `char` array. Constructs the "North" segment via looping from `0` to `4`. Each loop, constructs a string of 5 spaces (if `W`/`87` is present in the input), stores that in `$x`, then either `| |` (stored in `$w`) or `| | |`, depending upon whether we're currently even or odd. That array of strings is stored into `$n`, and multiplied by whether `N`/`78` is `-in` the input. That will determine if `$n` is placed on the pipeline or not.

Then, we construct the middle portion. The first line, `$z` is the "top" of the east-west route, using the same logic for `W` and `E`/`69`, and surrounded in parens to also place a copy on the pipeline. We use helper variable `$y` to save a byte on the `-----` sections.

The next line is just the appropriate number of spaces (i.e., `$x`) string-concatenated with the correct-width pipes (i.e., `$w`). Then, the middle striped line, again with `W` and `E` logic and `$w` filling in the middle. Then `$x+$w` and `$z` again.

Finally, since the South road is the same as the north, put `$n` on the pipeline if `S`/`83` is `-in` `$a`.

All of those resultant strings are gathered from the pipeline and output is implicit at the end of program execution. Abuses the default `Write-Output` delimiter to insert a newline between elements.

---

### Examples

```
PS C:\Tools\Scripts\golfing> .\4-way-intersection.ps1 'EN'
|  |  |
|     |
|  |  |
|     |
|  |  |
+-----+-----
|     |
|     |- - -
|     |
+-----+-----

PS C:\Tools\Scripts\golfing> .\4-way-intersection.ps1 'SNW'
     |  |  |
     |     |
     |  |  |
     |     |
     |  |  |
-----+-----+
     |     |
- - -|     |
     |     |
-----+-----+
     |  |  |
     |     |
     |  |  |
     |     |
     |  |  |

PS C:\Tools\Scripts\golfing> .\4-way-intersection.ps1 'WE'
-----+-----+-----
     |     |
- - -|     |- - -
     |     |
-----+-----+-----

```

# Answer
> 4 votes
# C++ ~~317~~ ~~280~~ 276 bytes

```
int i(char*j){for(int y=0;y<15;++y)for(int x=0;x<18;++x)putchar(x-17?y<5&!strchr(j,'N')|y>9&!strchr(j,'S')|x<5&!strchr(j,'W')|x>11&!strchr(j,'E')?' ' :x==5|x==11?y==5|y==9?'+':'|':y==5|y==9?x==5|x==11?'+':'-':x==8&y%2|y==7&x%2?' ':x==8&(y/5-1)?'|':y==7&(x/6-1)?'-':' ':'\n');}

```

Ungolfed:

```
int i (char* j)
{
  for (int y=0; y<15; ++y)
    for (int x=0; x<18; ++x)
      putchar(
        x-17 ?
        y<5 & !strchr(j,'N') |
        y>9 & !strchr(j,'S') |
        x<5 & !strchr(j,'W') |
        x>11 & !strchr(j,'E') ? ' ' :
        x==5 | x==11 ? y==5 | y==9 ? '+' : '|' :
        y==5 | y==9 ? x==5 | x==11 ? '+' : '-' :
        x==8 & y%2 | y==7 & x%2 ? ' ' :
        x==8 & (y / 5 - 1) ? '|' :
        y==7 & (x / 6 - 1) ? '-' :
        ' ' : '\n');
}

```

# Answer
> 2 votes
## Batch, ~~351~~ ~~344~~ 341 bytes

```
@echo off
set/pi=
set t=
if not "%i:n=%"=="%i%" call:l
set l=-----
set r=%l%
if "%i:w=%"=="%i%" set l=%t%
if "%i:e=%"=="%i%" set r=
for %%s in (%l%+-----+%r% "%t%|%t%|" "%l:--=- %|%t%|%r:--=- %" "%t%|%t%|" %l%+-----+%r%) do echo %%~s
if "%i:s=%"=="%i%" exit/b
:l
call :m
call :n
:n
echo %t%^|%t%^|
:m
echo %t%^|  ^|  ^|

```

Note: The line `set t=` ends in five spaces, and the line `if "%i:e=%"=="%i%" set r=` ends in a space. Takes case-insensitive input from STDIN. Edit: Saved 7 bytes by eliminating the `d` variable. Saved 3 bytes by using a `for` loop to print the middle section. If I'm allowed separate command-line parameters instead, then for ~~326~~ ~~319~~ 316 bytes:

```
@echo off
set t=%*
set/an=s=e=w=5,%t: ==%=0
set t=
call:%n%
set r=-----%t%
call set l=%%r:~%w%,5%%
call set r=%%r:~%e%%%
for %%s in (%l%+-----+%r% "%t%|%t%|" "%l:--=- %|%t%|%r:--=- %" "%t%|%t%|" %l%+-----+%r%) do echo %%~s
goto %s%
:0
call :1
call :2
:2
echo %t%^|%t%^|
:1
echo %t%^|  ^|  ^|
:5

```

# Answer
> 2 votes
# Python 3, 186 bytes

```
S=' -- -  -- -  --'
lambda d:'\n'.join(S[r//4:15*('W'in d):3]+'||+  -  -| -  -  -||+'[r%4::3]+S[r//4:15*('E'in d):3]for r in[0,1,0,1,0,6,1,9,1,6,0,1,0,1,0][5-5*('N'in d):10+5*('S'in d)])

```

An anonymous lambda called with a string of directions, e.g. 'NWS'

### Explanation to follow

# Answer
> 2 votes
# sed 234

```
s,$,@+-----+@|     |@!     !@|     |@+-----+@,
:l;tl
/N/s,^,#,;t
:r
/S/s,@$,#,;t
/E/{s,!@,|- - -@,;s,+@,+-----@,g}
/W/{s,@!,@- - -|,;s,@+,@-----+,g;s,@|,@     |,g}
y,@!NSEW,\n|    ,
q
:
s,#,@|  |  |@|     |@|  |  |@|     |@|  |  |,
tr

```

It just builds the different parts if the proper character is on the line.
Uses `@` instead of `\n` and subs `\n` back in at the end.
The north and south parts are identical, so I use what's basically a function to insert them.

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

```
t,s,r,i=[],[],range(5),raw_input()
for n in r:t+=[" "*5*("W"in i)+"|  "+("|"," ")[n%2]+"  |"]
exec"s+=['-'*5];s[:1]+=' '*5,;"*2;s[:2]+="- - -",
if"N"in i:print'\n'.join(t)
print'\n'.join([s[n]*("W"in i)+("|     |","+-----+")[`n`in"04"]+s[n]*("E"in i)for n in r])
if"S"in i:print'\n'.join(t)

```

# Answer
> 1 votes
# GolfScript, 154 bytes

```
{a?1+}:x;'-'5*:e;' '5*:b;"+"e+"+"+:f;{b'|'b'|'b n}:k;{'W'x{e}{b}if\'E'x{e}{}if n}:y;{x{b"|  |  |
"+:c k c k c}{}if}:z;1/:a;'N'z f y k'|'b+'|'+ y k f y'S'z

```

Try it online!

# Answer
> 1 votes
# Pyth (385 380 373 353 bytes)

Golfed:

```
K"     |  |  |\n     |     |\n"?}\Nz++KKPKk?}\Wz?}\Ez+++*5\-*2+\+*5\-"\n     |     |\n- - -|     |- - -\n     |     |\n"+*5\-*2+\+*5\-++*2+*5\-\+"\n     |     |\n- - -|     |\n     |     |\n"*2+*5\-\+?}\Ez+"     "+*2+\+*5\-"\n     |     |\n     |     |- - -\n     |     |\n     +-----+-----"++"     +-----+\n"*3"     |     |\n""     +-----+"?}\Sz++KKPKk

```

Ungolfed:

```
K"     |  |  |\n     |     |\n"  //sets K to first two lines of north
?}\Nz                            //if north in the input
  ++KKPK                         //then: return K + K + K[:-1]
  k                              //else: return ""
?}\Wz                            //if West in input
  ?}\Ez                          //if East in input
    +++*5\-*2+\+*5\-"\n     |     |\n- - -|     |- - -\n     |     |\n"+*5\-*2+\+*5\-    //then: Return E+W string
    ++*2+*5\-\+"\n     |     |\n- - -|     |\n     |     |\n"*2+*5\-\+         //else: Return W string
  ?}\Ez                          //else: if east in input (and not W)
    +"     "+*2+\+*5\-"\n     |     |\n     |     |- - -\n     |     |\n     +-----+-----" //return East without West String
    ++"     +-----+\n"*3"     |     |\n""     +-----+" \\Return empty left and right intersection
?}\Sz                            //if south in input
  ++KKPK                         //return north string
  k                              //return ""

```

Of course, if there are any improvements please tell me.

Saved 5 bytes thanks to Maltysen

You can try it here

# Answer
> 0 votes
# Groovy (274 Bytes)

## Ungolfed

```
r{
    l->
    t='+-----+'
    s='     ';
    m='|     |'
    x='-----'
    v=(1..5).collect{s}
    nsR=(1..5).collect{[s,((it%2)?'|  |  |':m),s]}
    ewR=[x,s,'- - -',s,x]
    c=[l[3]?ewR:v,[t,m,m,m,t],l[1]?ewR:v]
    (l[0]?nsR.collect{it}:[])+((0..4).collect{x->((0..2).collect{y->c[y][x]})})+(l[2]?nsR.collect{it}:[])
}

```

## Golfed

```
def i(l) {t='+-----+';s='     ';m='|     |';x='-----';v=(1..5).collect{s};n=(1..5).collect{[s,((it%2)?'|  |  |':m),s]};e=[x,s,'- - -',s,x];c=[l[3]?e:v,[t,m,m,m,t],l[1]?e:v];(l[0]?n.collect{it}:[])+((0..4).collect{x->((0..2).collect{y->c[y][x]})})+(l[2]?n.collect{it}:[])}

```

Try it: https://groovyconsole.appspot.com/script/5082600544665600

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


title: Corrcey my Soellign

text:
# Question
Title: Corrcey my Soellign
## Introduciton

Some of you might have realised that I am a sloppy typer when using my phone. That's why I want you to write a program which corrects my typos.

## Chalkrnge

Given a misspelled word, output all of the possible words which I meant to write.

## Typso

The main cause of my typos is down to the fact that I hit the wrong keys and often hit the key next door. The following is my keyboard layout:

```
q w e r t y u i o p
 a s d f g h j k l
   z x c v b n m
   , [ space ] .

```

*Note that the bottom row, `, [ space ] .` will never be used in this challenge*

For some reason, I only make mistakes horizontally: I would never hit the *n* instead of the *j*, but I might hit an *f* instead of a *d*.

For example, I could end up spelling the word *sloppy* as:

```
akioot

```

Where I've gone left of each key.

However, don't forget that I may not necessarily make a mistake on *every* letter in the word.

## Ezsmple

Let's say the input is:

```
vid

```

The possibilities that the word could have been are:

```
vid cid bid
vis cis bis
vif cif bif
vod cod bod
vos cos bos
vof cof bof
vud cud bud
vus cus bus
vuf cuf buf

```

Out of those, the following are in the dictionary:

```
cod
cud
bid
bud
bus

```

So that should be your output.

## Rulws

You should only use the text file found here as your dictionary: http://mieliestronk.com/corncob\_lowercase.txt. You do not have to count this file as part of your byte count.

All input will be a single word. You may display your output in any way you wish (as long as there is some kind of separator).

Assume that with all input, you will find a variant which is in the dictionary.

## Wibninf

The shortest code in bytes wins.

# Answer
# Japt, ~~50~~ 47 bytes

```
;D=R+Dv;W=3pUl¹óW ®s3 s1 £DgDbUgY)-X+1}Ãf@~V·bX

```

Input is the word to fix, and the dictionary as a string. Test it online! (Note: you'll have to manually paste the dictionary into the string.)

### How it works

```
;D=R+Dv;W=3pUl¹óW ®s3 s1 £DgDbUgY)-X+1}Ãf@~V·bX  // Implicit: U = input, V = dictionary, R = newline
;                                                // Re-assign preset variables. D = "QWERTYUIOP\nASDFGHJKL\nZXCVBNM";
 D=R+Dv;                                         // Convert D to lowercase and prepend a newline.
        W=3pUl¹                                  // Set W to 3 to the power of U.length.
               óW                                // Create the range [W, W+W).
                  ®                       Ã      // Map each item Z in the range by this function:
                   s3                            //  Take Z.toString(3).
                      s1                         //  Remove the first character.
                                                 //  If the input is two chars long, e.g. "id", the array is now
                                                 //  ["00", "01", "02", "10", "11", "12", "20", "21", "22"].
                         £            }          //  Map each char X and index Y in the string by this function:
                              UgY                //   Get the char at position Y in U.
                            Db   )               //   Take the index of the char in D.
                                  -X+1           //   Subtract X and add 1.
                          Dg                     //   Get the char at that position in D.
                                                 // This maps our array for "id" to:
                                                 // ["of", "od", "os", "if", "id", "is", "uf", "ud", "us"].
                                        f@       // Filter to only the items X where
                                             bX  //  the index of X in
                                           V·    //  the dictionary, split at newlines,
                                          ~      //  is not -1.
                                                 // This filters our array for "id" to:
                                                 // ["of", "if", "id", "is", "us"].
                                                 // Implicit: output last expression

```
> 1 votes

# Answer
## Python 2.7, ~~161~~ 159 bytes

```
from itertools import*
lambda a,k=' qwertyuiop asdfghjkl zxcvbnm ':set(map(''.join,product(*[k[k.index(l)-1:k.index(l)+2].strip()for l in a])))&set("<dictionary>".split())

```

readable version

```
from itertools import *
dictionary=set("<dictionary>".split())
keyboard=' qwertyuiop asdfghjkl zxcvbnm '
x=[]
for letter in input():
 index=keyboard.index(letter)
 x.append(keyboard[index-1:index+2].strip())

words=set(map(''.join,product(*x)))
print words&dictionary

```
* *Saved 1 byte thanks to @TuukkaX*
> 2 votes

---
Tags: code-golf
---