title: Play Best Card in Euchre

text:
# Question
Title: Play Best Card in Euchre
Input:

Firstly
An array of three cards representing the cards played by each player formatted like

```
[JD][TH][9S]

```

Representing

```
Jack of Diamonds, 10 of Hearts, and Nine of Spades.

```

As you always sit across from your team-mate in Euchre, the second element represents your team mate's play. Here, the `TH`.

Secondly
A Single Char, String, etc representing the trump suit formatted like

```
S, D, C, H

```

representing

```
Spades, Diamonds, Clubs, Hearts

```

Thirdly an array of four cards representing your hand formatted like

```
[KD][JC][QH][AS]

```

representing

```
King of Diamonds, Jack of Clubs, Queen of Hearts, Ace of Spades

```

### Objective:

Given the three inputs, output the best possible card to add to the cards that have been played such that it meets the following criteria:

1. It takes the hand if it can, if not output the least valuable card
2. It takes the hand if it can, however it will not trump your team mate unless it is unavoidable
3. If it can take the hand, it does so by using the least valuable card. (If you have an ace and a queen that can win the hand, you play the queen).
4. Any plays must follow suit as required by the rules at the bottom.

Output format like `[JD]`

### Formatting

```
A - Ace
K - King
Q - Queen
J - Jack
T - Ten
9 - Nine

H - Hearts
D - Diamonds
S - Spades
C - Clubs

TH, 9D, JD, QH, AD, 9C, TC

```

### Examples

In: `[QD][KD][9C]`, `"C"`, `[AH][JH][QH][9H]`

Out: `9H`

Reason: As clubs are trump, the 9C is winning the hand, we are unable to take the hand so we should discard our lowest card, here the `9H`

In: `[QD][KD][AD]`, `"H"`, `[AH][JH][QH][9H]`

Out: `9H`

Reason: As Hearts are trump, the Ace of Diamonds is currently winning the hand, we are able to trump the hand so we should use our lowest card, here the `9H`

In: `[QD][KD][TD]`, `"D"`, `[AD][JH][QH][9D]`

Out: `9D`

Reason: As diamonds are trump and we are currently winning the hand, we should play the 9D because our partner currently is winning the hand, so we want to play the `9D` over the `AD`

In: `[QH][KH][JH]`, `"D"`, `[AD][JD][QH][9D]`

Out: `QH`

Reason: As Diamonds are trump our opponents are winning with the left Bower `JH` We have the right bower but cannot trump him because QH was led and we must follow suit, the `QH`

In: `[QH][KH][JH]`, `"D"`, `[AD][JD][QC][9D]`

Out: `JD`

Reason: As Diamonds are trump our opponents are winning with the left Bower `JH` We have the right bower and since we have no `Diamonds` we can trump over him with the `JD`

### Euchre Card Strengths

If Hearts is trump:

```
JH
JD
AH
KH
QH
TH
9H

```

See the Euchre Rules if you are unfamiliar with the strength of different cards in Euchre

Since this is Code-Golf the shortest code wins!

Good Luck and have fun!

# Answer
# Perl - ~~557 532 511 490 482 384~~ 363

```
($p,$t,$h)=@ARGV;%L=(H=>D,D=>H,C=>S,S=>C);$B=%L{$t};$_="\]$p$h\[";s/(.$t)/0$1/g;s/J$B/01$B/;s/0J/00/;s/J/R/g;s/9/Z/g;($T,@C)=split/\]\[/,$_;$s=$C[0];$s=~s/.+(.)/$1/;$s=~s/$t/0/;$X=(sort@C[0..2])[0];@M=@C[3..6];@F=(grep{/$s/}@M);@M=@F if@F;$w=(sort@M)[@M-1];push@M,$X;foreach$g(sort@M){$g ne$X?$b=$g:last}$_=$C[1]eq$X||!$b?$w:$b;s/.(..)/$1/;s/Z/9/;s/0|1|R/J/;print

```

### How it works

Try it online!

First it reads args and finds the left-bauer's suit (jack of the same color as trump) with a hash lookup:

```
($p,$t,$h)=@ARGV;
%L=(H=>D,D=>H,C=>S,S=>C);
$B=%L{$t};

```

Then it combines all cards into one string and does some replacements, making the cards naturally sort in the correct order for euchre:

```
$_="\]$p$h\[";
s/(.$t)/0$1/g; # trump cards start with '0'
s/J$B/01$B/;   # left-bauer's 'J' changes to '01', making it trump
s/0J/00/;      # right-bauer's 'J' changes to '0'
s/J/R/g;       # all other jacks have 'J' changed to 'R'
s/9/Z/g;       # all 9s change to Z
($T,@C)=split/\]\[/,$_;

```

At the end of this block, the card string is then split on the brackets, which builds an array of all cards where:

* index 0 = opponent's lead card
* index 1 = teammate's card
* index 2 = other opponent's card
* indices 3-6 represent the hand

The lead suit is parsed from the first card, but the suit changes to '0' to represent trump if trump was led:

```
$s=$C[0];
$s=~s/.+(.)/$1/;
$s=~s/$t/0/;

```

The best card in-play is found by sorting the first three cards and retrieving the first card:

```
$X=(sort@C[0..2])[0];

```

The playable cards are found. If any cards in-hand match the lead suit, then only those cards remain. Otherwise all cards are considered playable:

```
@M=@C[3..6];
@F=(grep{/$s/}@M);
@M=@F if@F;

```

The 'throwaway' card is found by returning the last card in the sorted array of playable cards:

```
$w=(sort@M)[@M-1];

```

The lowest 'winning' card that can win the trick is found by adding the highest card in-play to the array of playable cards, sorting the array, and iterating over it until the highest card in-play is found. The 'winning' card is the card from the previous iteration:

```
push@M,$X;
foreach$g(sort@M){$g ne$X?$b=$g:last}

```

The correct play is then evaluated. The 'throwaway' card is chosen if any of the following are true:

1. The best card on the table has an index of 1 in the unsorted array of all cards, meaning it belongs to our teammate
2. The search for the lowest 'winning' card came up null, meaning our opponent's best card is higher than all cards in the hand

Otherwise the 'winning' card is returned:

```
$_=$C[1]eq$X||!$b?$w:$b;
s/.(..)/$1/; # remove the '0' that indicated trump
s/Z/9/;      # get those 9s back
s/0|1|R/J/;  # fix the jacks
print

```
> 2 votes

---
Tags: code-golf, card-games
---


title: N Doors, K Monkeys

text:
# Question
Title: N Doors, K Monkeys
There are N doors and K monkeys. Initially, all the doors are closed.

**Round 1:** The 1st monkey visits every door and toggles the door (if the door is closed, it gets opened it; if it is open, it gets closed).

**Round 2**: The 1st monkey visits every door and toggles the door. Then The 2nd monkey visits every 2nd door and toggles the door.

. . .

. . .

**Round k:** The 1st monkey visits every door and toggles the door . . . . . . . . . . The kth monkey visits every kth door and toggles the door.

**Input :** N K (separated by a single space)

**Output:** Door numbers which are open, each separated by a single space.

**Example**:

Input: 3 3

Output: 1 2

**Constraints**:

0\< N\<101

0\<= K\<= N

**Note**:

* Assume N doors are numbered from 1 to N and K monkeys are numbered from 1 to K
* The one with the shortest code wins. Also, display output for N=23, K=21

# Answer
## APL, ~~32~~ ~~28~~ 26

```
{(2|+/(⍳⍺)∘.{+/0=⍺|⍨⍳⍵}⍳⍵)/⍳⍺}/⎕

```

---

```
⎕:
      23 21
 1 2 4 8 9 16 18 23

```

---

**Explaination**

* `{+/0=⍺|⍨⍳⍵}` is a function that returns the number of times door (left argument) is toggled on round (right argument), which equal the number of factors of  that is ≤:

+ `⍳⍵` Generate numerical array from 1 to
    + `⍺|⍨` Calculate  modulus each every item of that array
    + `0=` Change to a 1 where there was a 0, and a 0 for every thing else
    + `+/` Sum the resulting array
* The outer function:

+ `(⍳⍺)` , `⍳⍵` Generate arrays from 1 to N and 1 to K
    + `∘.{...}` For every pair of elements of the two arrays, apply the function. This gives a matrix of number of times toggled, each row represents a door and each column represents a round.
    + `+/` Sum the columns. This gives an array of the number of times each door is toggled over all rounds.
    + `2|` Modulus 2, so if a door is open, it's a 1; if it's closed, it's a 0.
    + `(...)/⍳⍺` Finally, generate an array from 1 to N and select only the ones where there is a 1 in the array on the previous step.
* `/⎕` Finally, insert the function between the numbers from input.

---

## EDIT

```
{(2|+⌿0=(,↑⍳¨⍳⍵)∘.|⍳⍺)/⍳⍺}/⎕

```
* `,↑⍳¨⍳⍵` Generate all "monkeys" (If K=4, then this is `1 0 0 0 1 2 0 0 1 2 3 0 1 2 3 4`)

+ `⍳⍵` Array from 1 to  (K)
    + `⍳¨` For each of those, generate array from 1 to that number
    + `,↑` Convert the nested array into a matrix () and then unravel to a simple array (`,`)
* `(,↑⍳¨⍳⍵)∘.|⍳⍺` For each number from 1 to  (N), mod it with each monkey.
* `0=` Change to a 1 where there was a 0, and a 0 for every thing else. This gives a matrix of toggles: Rows are each monkey on each round, columns are doors; 1 means a toggle, 0 means no toggle.
* `+⌿` Sum the rows to get an array of number of times each door is toggled

Other parts are not changed

---

## EDIT

```
{(≠⌿0=(,↑⍳¨⍳⍵)∘.|⍳⍺)/⍳⍺}/⎕

```

Use XOR reduce (`≠⌿`) instead of sum and mod 2 (`2|+⌿`)
> 14 votes

# Answer
### GolfScript, 33 characters

```
~:k;),1>{0\{1$)%!k@-&^}+k,/}," "*

```

If doors were numbered starting with zero it would save 3 characters.

Examples (online):

```
> 3 3
1 2

> 23 21
1 2 4 8 9 16 18 23

```
> 4 votes

# Answer
# Mathematica, 104 chars

```
{n,k}=FromDigits/@StringSplit@InputString[];Select[Range@n,OddQ@DivisorSum[#,If[#>k,0,k+1-#]&]&]~Row~" "

```

---

Example:

> In\[1\]:= {n,k}=FromDigits/@StringSplit@InputString\[\];Select\[Range@n,OddQ@DivisorSum\[#,If\[#\>k,0,k+1-#\]&\]&\]~Row~" "
>
> ? 23 21
>
> Out\[1\]= 1 2 4 8 9 16 18 23
> 3 votes

# Answer
## Ruby, 88

Based on @manatwork's answer.

```
gets;~/ /
$><<(1..$`.to_i).select{|d|(1..k=$'.to_i).count{|m|d%m<1&&(k-m+1)%2>0}%2>0}*$&

```

Those dodgy globals always break syntax highlighting!
> 3 votes

# Answer
## Python 3, ~~97~~ 84

If a monkey appears in an even number of rounds, that's no change at all. If a monkey appears in an even number of times, that's the same as in exactly one round.

Thus some monkeys can be left out, and the others just have to switch doors once.

```
N,K=map(int,input().split())
r=set()
while K>0:r^=set(range(K,N+1,K));K-=2
print(*r)

```

Output for `23 21`:

```
1 2 4 8 9 16 18 23

```
> 3 votes

# Answer
## javascript ~~148~~ 127

```
function e(n,k){b=array(n);d=[];function a(c){for(i=0;i<n;i+=c)b[i]=!b[i];c<k&&a(c+1)}a(1);for(i in b)b[i]&&d.push(i);return d}

```

here is a (tiny bit) readable version:

```
function e(n, k) {     //define N and K
     b = array(n); //declare all doors as closed
     d = [];     //create array later used to print results

     function a(c) {   //(recursive) function that does all the work
         for (i = 0; i < n; i += c)  //increment by c until you reach N and...
              b[i] = !b[i];  //toggle said doors
         c < k && a(c + 1)  //until you reach k, repeat with a new C (next monkey)
     }
     a(1); //start up A

     for (i in b) b[i] && d.push(i); //convert doors to a list of numbers
     return d //NO, i refuse to explain this....
}   //closes function to avoid annoying errors

```

DEMO fiddle

i should note that it starts counting from 0 (technically a off-by-one error)
> 2 votes

# Answer
## R - 74

```
x=scan(n=2);cat(which(colSums((!sapply(1:x[1],`%%`,1:x[2]))*x[2]:1)%%2>0))

```

Simulation:

```
> x=scan(n=2);cat(which(colSums((!sapply(1:x[1],`%%`,1:x[2]))*x[2]:1)%%2>0))
1: 23 21
Read 2 items
1 2 4 8 9 16 18 23

```
> 2 votes

# Answer
### JavaScript, 153

```
(function(g){o=[],f=g[0];for(;i<g[1];i++)for(n=0;n<=i;n++)for(_=n;_<f;_+=n+1)o[_]=!o[_];for(;f--;)o[f]&&(l=f+1+s+l);alert(l)})(prompt().split(i=l=s=' '))

```

Output for N=23, K=21:

```
1 2 4 8 9 16 18 23

```

Tested in Chrome, but doesn't use any fancy new ECMAScript features so should work in any browser!

I know I'll never win against the other entries and that @tryingToGetProgrammingStrainght already submitted an entry in JavaScript, but I wasn't getting the same results for N=23, K=21 as everyone else was getting with that so I thought I'd have a go at my own version.

**Edit**: annotated source (in looking over this again, I spotted places to save another 3 characters, so it can probably be improved still...)

```
(function(g) {
    // initialise variables, set f to N
    o = [], f = g[0];

    // round counter
    // since ++' ' == 1 we can use the same variable set in args
    for (; i < g[1]; i++)
        // monkey counter, needs to be reset each round
        for (n = 0 ; n <= i; n++)
            // iterate to N and flip each Kth door
            for (_ = n; _ < f; _ += n + 1)
                // flip the bits (as undef is falsy, we don't need to initialise)
                // o[_] = !~~o[_]|0; // flips undef to 1
                o[_] = !o[_]; // but booleans are fine
    // decrement f to 0, so we don't need an additional counter
    for (;f--;)
        // build string in reverse order
        o[f] && (l = f + 1 + s + l); // l = (f + 1) + ' ' + l
    alert(l)
    // return l // use with test
// get input from user and store ' ' in variable for use later
})(prompt().split(i = l = s = ' '))
// })('23 21'.split(i = l = s = ' ')) // lazy...

// == '1 2 4 8 9 16 18 23  '; // test

```
> 2 votes

# Answer
Ruby - 65 characters

```
(1..n).each{|d|
t=0
(1..k).each{|m|t+=n-m+1 if d%m==0}
p d if t%2>0}

n = 23, k = 21 # => 1 2 4 8 9 16 18 23

```

Here is the calculation, in pseudo-code:

* Let s(d) be the number of times door d is touched after k rounds.
* s(d) = sum(m=1..m=k)(d%m==0 ? (n-m+1): 0)
* door d is open after k rounds if s(d) % 2 = 1 (or \> 0)

If you are not convinced that the expression for s(d) is correct, look at it this way:

* Let s(d,r) be the number of times door d is touched after r rounds.
* s(d,k) - s(d,k-1) = sum(m=1,..,m=k)(d%m==0 ? 1 : 0)
* s(d,k-1) - s(d,k-2) = sum(m=1,..,m=(k-1))(d%m==0 ? 1 : 0)
* ...
* s(d,2) - s(d,1) = d%2==0 ? 1 : 0
* s(d,1) = 1
* sum both sides to obtain the above expression for s(d), which equals s(d,k)
> 1 votes

# Answer
## PowerShell: 132

**Golfed Code:**

```
$n,$k=(read-host)-split' ';0|sv($d=1..$n);1..$k|%{1..$_|%{$m=$_;$d|?{!($_%$m)}|%{sv $_ (!(gv $_ -Va))}}};($d|?{(gv $_ -Va)})-join' '

```

**Un-Golfed, Commented Code:**

```
# Get number of doors and monkeys from user as space-delimited string.
# Store number of doors as $n, number of monkeys as $k.
$n,$k=(read-host)-split' ';

# Store a list of doors in $d.
# Create each door as a variable set to zero.
0|sv($d=1..$n);

# Begin a loop for each round.
1..$k|%{

    # Begin a loop for each monkey in the current round.
    1..$_|%{

        # Store the current monkey's ID in $m.
        $m=$_;

        # Select only the doors which are evenly divisible by $m.
        # Pass the doors to a loop.
        $d|?{!($_%$m)}|%{

            # Toggle the selected doors.
            sv $_ (!(gv $_ -Va))
        }
    }
};

# Select the currently open doors.
# Output them as a space-delimited string.
($d|?{(gv $_ -Va)})-join' '

# Variables cleanup - don't include in golfed code.
$d|%{rv $_};rv n;rv d;rv k;rv m;

# NOTE TO SELF - Output for N=23 K=21 should be:
# 1 2 4 8 9 16 18 23

```
> 1 votes

# Answer
# Powershell, 66 bytes

> Based on Cary Swoveland's answer.

```
param($n,$k)1..$n|?{$d=$_
(1..$k|?{($n-$_+1)*!($d%$_)%2}).Count%2}

```

Test script:

```
$f = {

param($n,$k)1..$n|?{$d=$_
(1..$k|?{($n-$_+1)*!($d%$_)%2}).Count%2}

}

@(
    ,(3, 3   , 1,2)
    ,(23, 21 , 1, 2, 4, 8, 9, 16, 18, 23)
) | % {
    $n,$k,$expected = $_
    $result = &$f $n $k
    "$("$result"-eq"$expected"): $result"
}

```

Output:

```
True: 1 2
True: 1 2 4 8 9 16 18 23

```
> 0 votes

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


title: Garbled Phone Numbers

text:
# Question
Title: Garbled Phone Numbers
You know how you get a voicemail message and the person's connection wasn't great, and you're trying to figure out how to call them back, but you're not sure if that was a "5" or an "8" they said?

That's this challenge.

The good news is that the caller read off their number twice, but it's garbled in both places.

Your program should take input like this:

```
5551231234 / 5551231234

```

Where the first ten digits are the first time the phone number is said in the voice mail and the second set are the second time it's said. Only...it'll look more like this:

```
555?ABC1_36? / 55?522_1?234

```
* A digit followed by a question mark means that that's the best-guess for that digit (e.g. "5?" means "probably a 5, compare with repeat").
* An underscore indicates a known missing digit, something too fuzzed by static to be deciphered at all.
* Letters are just that: letters. Treat them as their respective digits
    + ABC -\> 2, DEF -\> 3, GHI -\> 4, JKL -\> 5, MNO -\> 6, PQRS -\> 7, TUV -\> 8, WXYZ -\>9
    + All sample inputs use uppercase (you can safely omit a ToUpper() call)
    + If your language works better in lower case, you can freely use lowercase for the input and omit a ToLower() call. Just note that in your answer.

You can additionally assume the following judgement calls:

```
5? / _     -> 5  //5 is the best guess we have, use it
5? / 5?    -> 5  //uncertain, but matching
5? / 4?    -> ?  //conflict
 5 / 4     -> ?  //conflict
5? / 4     -> 4  //solid information overrides possible value
 5 / 4?    -> 5  //solid information overrides possible value
 _ / _     -> ?  //no information available

```

Additionally you can assume that all inputs will contain ten-digit phone numbers, not including the question marks. Inputs that aren't ten digits (e.g. `1234567 / 1234567`) can either be treated as unsolvable (falsey output) or throw an error.

### Input

One line of characters `0-9A-Z _?/`, as described above.

### Output

If it can be parsed to a single valid ten-digit phone number, output the phone number. Otherwise output some form of error indication (e.g. -1, false, or an empty line).

Shortest wins, as per usual.

Sample inputs:

```
1234567890 / 1234567890
1234567890? / 1234567890
123456789_ / 1234567890
1234567890? / 123456789_
1234567890 / 1234567890?
1234567890 / 123456789_
123456789_ / 1234567890?
1234567890? / 1234567890?
1234567890? / 1234567891?
123456789_ / 123456789_
555CALLUS1 / 5552255871
404_12?6039 / 4041?1560_9
_GETREVENGE / 16?36?_2838_
1?691460_50 / 16_14609?50
61?08977211 / 612?897725?1
40?0INSTA__ / 8?00_NSTI?LL
3985_534?10 / 39?8?5053_10
7__7294?737 / 7797299?_37
28?897_384?1 / _8?89763861
271168090_ / 27116800?09
6802?148343 / 67?01148343
94_11628?2?6? / 9491162_47?
17?4285_689 / 1__26?52689
6_311?95_38 / 6731194?7?38
380?7DRAGON / 3807378?5?66
4?647_93236 / 5646?6?9__36
365?268898_ / 366267?7?984
GRATEDBATE / IRATEDBATE
5307_079?93 / ____8_____
535_3_0255 / 52?5_3_024?5
55_____088 / 54?2397207?7?
6_48398_95 / _946?398?6_5?
_0_312_3_1 / 81?53123?1?71
____1_____ / 64?255?508?61
8427820607 / 6?424?8?__6?07
50_3707__6 / 52?8375?74?56
615___8255 / 62?526?983?2?1?
__652618__ / 8365261__0
149___933_ / 1_9677?92?31
___7?281562 / 3438?28154?2
5?7?7?___8?3?7?4 / 57_855837_
605_272481 / 605427__81
86?569__731 / 88560?0?7721
1__91654?15 / 17?9?9165715
800NWABODE / 80069ABI?DE
8___9017_0 / 8_2494?12?9_
_024?5?91?470 / 304?17908?7_
42510704_2 / 4_51070492
9338737_89 / 93_873PLUS
327762_401 / 327_MASH01
33093_2058 / 3309_12058
4061_33578 / 40619_3578
559_383197 / 559938_197
94_9746084 / 9459746_84
1_37655238 / 163POLKA_T
_672FRIZZY / 767237499_
8_76318872 / TIP63188_2
51_8404321 / 5178404_21
358_030314 / 358603_314
2597_85802 / 25979_5802
77141_1408 / 7714_91408
330858_457 / 330_586457
4686079_39 / 46_6079239
86457508_6 / 8_45750826
523226626_ / _23BANNANA
_ISSY_ISSY / 44__9548?79?
6?00B_YJILT / 800289KILL?
2?52803___0 / 1526?0390?61?
FI?ND___T?HE / EAS?T?EREGGS?
0_231?95_38 / 0723194?7?38
0?647_39236 / 0646?6?3__36
025?267798_ / 06?6265?9?984
0061_33578 / _0619_3578

```

I've only insured that every possible edge-case is covered (the first 11 entries), but other than that, it's pretty much random.

**Update**

Four entries at the bottom added with leading zeros (at Jonathan Allan's suggestion).

Correct output for the sample inputs:

> https://pastebin.com/gbCnRdLV

Based on the output from Jonathan Allan's entry (the formatted output was ideal).

# Answer
> 3 votes
# Jelly, 84 bytes

+4 bytes - I think it should probably behave the same in all cases, so I've converted the keypad lookup integers back to digit-characters using `+49Ọ`.

```
”?e‘ḣ@µ”_eḤ‘ẋ@
;Ṃµ68DṬ+3RØAṁẇ@€FT+49Ọȯµ€Fṡ2i”?Ḃ$ÐḟÇ€
ḟ⁶ṣ”/Ç€ZLÐṂ€Q€LỊ$ÐfF€Ḣ€ḟ”_µL⁼⁵ȧ

```

A function which takes the string in the specified format and returns the phone number as a list of character or zero if invalid. As a program this is printed as if it were a string.

The way it works they could repeat the number more times
(e.g. `"123456789_ / 123456789_ / 1234567890"`)
...or even only say it once, and the logic defined will apply.

**Try it online!**, or see all the sample inputs.

### How?

```
”?e‘ḣ@µ”_eḤ‘ẋ@ - Link 1, helper to vary the length of a 2-slice: list s
”?             - literal '?'
  e            - exists in s                   (1 or 0)
   ‘           - increment                     (2 or 1)
    ḣ@         - head with reversed @rguments  (s or s[:1] - removes 2nd value if not '?')
      µ        - monadic chain separation, call that t
       ”_      - literal '_'
         e     - exists in t                   (1 or 0)
          Ḥ    - double                        (2 or 0)
           ‘   - increment                     (3 or 1)
            ẋ@ - repeat t that many times      (t*3 or t - [`_`]->['_','_','_'])

;Ṃµ68DṬ+3RØAṁẇ@€FT+49Ọȯµ€Fṡ2i”?Ḃ$ÐḟÇ€ - Link 2, reformat a phone number: char list of [0-9][A-Z], p
;                                     - concatenate p with
 Ṃ                                    - minimum of p - (?<_<0<1<...<9<A<...<Z - never "?" however, since it only follows a digit.)
                                      -   - this is simply to make a 2-slice with the last character on the left, as used at the very end of this link.
  µ                                   - monadic chain separation call that q
                       µ€             - monadic chain separation, for €ach v in q do:
   68                                 -   literal 68
     D                                -   cast to a decimal list -  [6,8]
      Ṭ                               -   untruth                -  [0,0,0,0,0,1,0,1]
       +3                             -   add 3                  -  [3,3,3,3,3,4,3,4]
         R                            -   range                  -  [[1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3,4],[1,2,3],[1,2,34]]
          ØA                          -   uppercase alphabet     -  ABCDEFGHIJKLMNOPQRSTUVWXYZ
            ṁ                         -   mould like the range ^ -  [ABC,DEF,GHI,JKL,MNO,PQRS,TUV,WXYZ]
             ẇ@€                      -   sublist v exists in that? for €ach, with reversed @rguments
                F                     -   flatten        (e.g. 'E' -> [0,1,0,0,0,0,0,0]; '4' -> [0,0,0,0,0,0,0,0]
                 T                    -   truthy indexes (e.g. 'E' -> [2]; '4' -> [])
                  +49                 - add 49
                     Ọ                - cast to character
                      ȯ               -   or             (e.g. 'E' -> [3]; '4' -> '4')
                         F           - flatten
                          ṡ2          - all slices of length 2
                                 Ðḟ   - filter discard if:
                                $     -   last two links as a monad:
                            i         -     first index of
                             ”?       -     literal '?'   (first index returns 0 if none exists)
                               Ḃ      -   mod 2 (so this filter discards pairs starting with '?')
                                   Ç€ - call the last link (1) as a monad for €ach slice

ḟ⁶ṣ”/Ç€ZLÐṂ€Q€LỊ$ÐfF€Ḣ€ḟ”_µL⁼⁵ȧ - Main link: string (or char list) s
ḟ                               - filter discard any:
 ⁶                              - literal ' '
  ṣ                             - split on:
   ”/                           - literal '/'
     Ç€                         - call the last link (2) as a monad for €ach
       Z                        - transpose
         ÐṂ€                    - filter, for €ach, keep items with minimal:
        L                       -   length
            Q€                  - de-duplicate €ach
                 Ðf             - filter keep items with:
                $               - last two links as a monad:
              L                 -   length
               Ị                -   insignificant? (=1 effectively here)
                   F€           - flatten €ach
                     Ḣ€         - head €ach
                       ḟ        - filter discard any of:
                        ”_      -   literal '_'
                          µ     - monadic chain separation, call that r
                           L    - length(r)
                             ⁵  - literal 10
                            ⁼   - equal?
                              ȧ - and r (0 if r did not result in a 10-digit list, else r)

```

# Answer
> 7 votes
# Python 2, ~~314~~ ~~307~~ 274 bytes

```
lambda s:g(*''.join(q<n<"["and`(int(n,36)-4-(n>"R")-(n>"Y"))//3`or n for n in s).split(" / "))
def g(a,b,s=str.startswith):
 if b:c,d,e,f=a[0],a[1:],b[0],b[1:];b=(c==e and[c,q][c=="_"]or"_"in c+e and min(c,e)or[q,c,e][s(f,q)-s(d,q)])+g(d[s(d,q):],f[s(f,q):])
 return b
q="?"

```

Try it online!

# Answer
> 5 votes
# Python 3, ~~549~~ ~~530~~ ~~509~~ ~~453~~ ~~449~~ ~~410~~ ~~406~~ ~~394~~ ~~393~~ 391 bytes

I'm sure this can be improved, but it's a start:

```
def f(e,z,q="?",u=str.isnumeric):
 if e+z in(e,z):return""
 o,O,t,T,*x=e[0],e[1:2],z[0],z[1:2],e[1:],z[1:]
 if"?"in o+t:return f([e,x[0]][o==q],z)
 if u(o):
  if u(t):return t+f(*x)if O==q!=T else o+f(*x)if o==t or T==q!=O else 1
  return o+f(*x)
 if u(t):return t+f(*x)
def g(s):
 for a,b in zip(map(chr,range(65,91)),"2223334445556667777888999"):s=s.replace(a,b)
 return f(*s.split(" / "))

```

I'm using `str.translate` for the letters, and a wrapper function `g` to make the inputs in the format in which I want them. The actual function `f` is recursive, and will fail for ambiguous inputs. I still have lots of repititions in there though, so I'm sure there's lots of room for improvement.

Improvements:

* saved 19 bytes by combining conditions
* saved 21 bytes with ternaries
* saved 56 bytes using a dictionary comprehension instead of the manual dictionary, thanks to @TuukkaX
* saved 4 bytes by switching to the method suggested by @ovs, with @TuukkaX's improvement
* saved 38 bytes with improvements from @ovs (and the last removable whitespace removed)
* saved 4 bytes by putting defining `str.isnumeric` in a keyword argument
* saved 12 bytes with combined comparison operators (e.g. `T==q!=O`)
* saved 1 byte by turning `not(e or z)` into `e+z in(e,z)`.
* saved 2 bytes by saving the frequently used `(E,Z)`

# Answer
> 3 votes
## JavaScript (ES6), ~~180~~ ~~190~~ 188 bytes

*Edit: ~~+10~~ +9 bytes to comply with the falsy output rule*

---

Takes the two input strings in currying syntax `(a)(b)`. Returns either `false` or a string representing the guessed phone number.

```
a=>b=>!(s=(F=a=>a.match(/(.\??)|_/g).map(([x,y])=>(x<=9?++x:parseInt(x,36)*.32-(x>'Y'))|(x!='_'&!y)*16))(a).map((x,i)=>(x=(d=x^(y=F(b)[i]),x>y)?x:y)&&(d&16|!(d%x))?--x&15:a).join``)[10]&&s

```

### How it works

**Step #1 - Parsing the input strings**

We first define the `F()` function which translates a string into an array of integers by applying the following rules:

* the underscore is converted to ***0***
* a digit ***N*** or an equivalent letter is converted to ***(N+1) OR 16*** (e.g. "2" → 19, "R" → 24)
* a digit ***N*** or an equivalent letter followed by an interrogation mark is converted to ***N+1*** (e.g. "2?" → 3, "R?" → 8)

Which can be interpreted the other way around as follows:

* ***0****unknown*
* **\[ *1 .. 10* \]***unreliable*
* **\[ *17 .. 26* \]***reliable*

We apply `F()` to both `a` and `b`. This gives us a pair of integers ***(x, y)*** for each digit in the phone number, corresponding to the two possible interpretations.

**Step #2 - Guessing the digits**

For each pair ***(x, y)***, we compute:

* ***d = x XOR y***
* ***x = MAX(x, y)****reliable values are always preferred to unreliable ones*

If ***x == 0***, it means that both inputs are underscore characters. So, the digit is unknown in this case.

If ***x != 0***, we can safely deduce the digit if one of the following conditions is true:

```
condition       | interpretation
----------------+------------------------------------------------------
(d AND 16) != 0 | one input is unreliable and the other one is reliable
d == 0          | both inputs are identical
d == x          | one input is an underscore

```

The last two conditions can be merged with `!(d % x)`. Hence the final formula:

```
x && (d & 16 || !(d % x))

```

If true, we convert ***x*** back to the guessed digit by computing ***(x - 1) AND 15***.

### Test cases

(Only the 50 first ones because the console snippet can't support more output history.)

```
let f =

a=>b=>!(s=(F=a=>a.match(/(.\??)|_/g).map(([x,y])=>(x<=9?++x:parseInt(x,36)*.32-(x>'Y'))|(x!='_'&!y)*16))(a).map((x,i)=>(x=(d=x^(y=F(b)[i]),x>y)?x:y)&&(d&16|!(d%x))?--x&15:a).join``)[10]&&s

console.log(f('1234567890')('1234567890'))
console.log(f('1234567890?')('1234567890'))
console.log(f('123456789_')('1234567890'))
console.log(f('1234567890?')('123456789_'))
console.log(f('1234567890')('1234567890?'))
console.log(f('1234567890')('123456789_'))
console.log(f('123456789_')('1234567890?'))
console.log(f('1234567890?')('1234567890?'))
console.log(f('1234567890?')('1234567891?'))
console.log(f('123456789_')('123456789_'))
console.log(f('555CALLUS1')('5552255871'))
console.log(f('404_12?6039')('4041?1560_9'))
console.log(f('_GETREVENGE')('16?36?_2838_'))
console.log(f('1?691460_50')('16_14609?50'))
console.log(f('61?08977211')('612?897725?1'))
console.log(f('40?0INSTA__')('8?00_NSTI?LL'))
console.log(f('3985_534?10')('39?8?5053_10'))
console.log(f('7__7294?737')('7797299?_37'))
console.log(f('28?897_384?1')('_8?89763861'))
console.log(f('271168090_')('27116800?09'))
console.log(f('6802?148343')('67?01148343'))
console.log(f('94_11628?2?6?')('9491162_47?'))
console.log(f('17?4285_689')('1__26?52689'))
console.log(f('6_311?95_38')('6731194?7?38'))
console.log(f('380?7DRAGON')('3807378?5?66'))
console.log(f('4?647_93236')('5646?6?9__36'))
console.log(f('365?268898_')('366267?7?984'))
console.log(f('GRATEDBATE')('IRATEDBATE'))
console.log(f('5307_079?93')('____8_____'))
console.log(f('535_3_0255')('52?5_3_024?5'))
console.log(f('55_____088')('54?2397207?7?'))
console.log(f('6_48398_95')('_946?398?6_5?'))
console.log(f('_0_312_3_1')('81?53123?1?71'))
console.log(f('____1_____')('64?255?508?61'))
console.log(f('8427820607')('6?424?8?__6?07'))
console.log(f('50_3707__6')('52?8375?74?56'))
console.log(f('615___8255')('62?526?983?2?1?'))
console.log(f('__652618__')('8365261__0'))
console.log(f('149___933_')('1_9677?92?31'))
console.log(f('___7?281562')('3438?28154?2'))
console.log(f('5?7?7?___8?3?7?4')('57_855837_'))
console.log(f('605_272481')('605427__81'))
console.log(f('86?569__731')('88560?0?7721'))
console.log(f('1__91654?15')('17?9?9165715'))
console.log(f('800NWABODE')('80069ABI?DE'))
console.log(f('8___9017_0')('8_2494?12?9_'))
console.log(f('_024?5?91?470')('304?17908?7_'))
console.log(f('42510704_2')('4_51070492'))
console.log(f('9338737_89')('93_873PLUS'))
console.log(f('327762_401')('327_MASH01'))
```

# Answer
> 2 votes
# Perl 5, 211 bytes

...without indentation and \n newlines

```
@i=map{y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/22233344455566677778889999/;$_}split' / ',shift;
print map{
  $_=join'',map{s,(\d\??|_),,;$1}@i;
  /((\d)\??\2\??|(\d)\??_|_(\d)\??|(\d)\d\?|\d\?(\d))$/;$2//$3//$4//$5//$6//'?'
}1..10

```

Try it online!

# Answer
> 2 votes
# Retina, ~~150~~ ~~140~~ 136 bytes

*Saved a few bytes thanks to Kritixi Lithos*

```
T`?L`#22233344455566677778889
./.

(?<=(\d)(\w#?){9}).#|.#(?=(\w#?){9}(\d)(?!#))
$1$4
#

_(?=.{9}(.))|(?<=(.).{9})_
$1$2
^(\d*)\1$|.*
$1

```

Try it Online!

**Explanation:**

The first line transforms all `?` in the input into `#` and all letters into their numeric equivalents. We then remove the spaces and `/` from the input. The next two lines take care of "guess vs. certainty" cases (eg. `5? \ 4` would be replaced by `4 \ 4`). After removing all `#`s, lines 8 and 9 deal with "number vs. `_`" cases (`_ \ 3` becomes `3 \ 3`). Then, if both halves of the string match, we keep the first 10 digits. Otherwise, the phone number is invalid so we remove everything.

Alternative 160-byte solution that works for phone numbers of arbitrary length (and equal size): TIO

# Answer
> 1 votes
# PHP, ~~251~~ 236 bytes

```
for(;a&$c=preg_replace(["#[^_?](?!\?)#","#_#"],["$0k","?<"],join("-",$argv))[++$i];)${$k+="-"==$c}.=$c<_&$c>=A?0|(ord($c)-($c>W)-($c>P)-59)/3:$c;for(;$c=${1}[$k+1];)echo($n=${1}[$k])==($m=${2}[$k++])|($b=${2}[$k++])!=$c?$c>$b?$n:$m:"?";

```

takes input from command line; run with `-nr` or try it online.

**breakdown**

```
# A: transform input
                                    # 2. replace single chars with two-character chunk and make sortable:
                                    #   replace "_" with "?<", append "k" to everything else not followed by "?"
for(;a&$c=preg_replace(["#[^_?](?!\?)#","#_#"],["$0k","?<"],join("-",$argv))[++$i];)    # (unknown "<" < unsure "?" < certain "k")
${$k+="-"==$c}.=                # if "-", next argument
        $c<_&$c>=A              # if letter
            ?0|(ord($c)-($c>W)-($c>P)-59)/3 # then translate to digit
            :$c                             # else don´t
    ;
# B: evaluate
for(;$c=${1}[$k+1];)            # loop through arguments: $c=command 2
    echo
        ($n=${1}[$k])                   # $n=digit 2
        ==                          # if digits are equal
        ($m=${2}[$k++])                 # $m=digit 3
        |
        ($b=${2}[$k++])             # $b=command 3
        !=$c                        # or "commands" are not
            ?$c>$b?$n:$m            # then get the one with the more definitive "command"
            :"?"                    # else conflict/unknown
    ;

```

**golfings**

* `preg_replace` first: -8 bytes
* `join`: -2
* `$$k` instead of `$t[$k]`: -5

# Answer
> 1 votes
# PHP, 200+8 bytes

inspired by Arnaulds solution.

```
for($s=join($argv);$c=ord($s[$i++]);$i+=$x)$t[]=$c>90?63:15&($c<65?$c:($c-($c>80)-($c>87)-59)/3)|16*$x="?"==$s[$i];for(;$p++<10;)echo chr(($e=$t[$p]^$d=$t[$p+10])&48|!(15&$e)?min($t[$p],$d)&15|48:63);

```

takes input from command line arguments; run with `-nr` or try it online.

*modifications to comply with the error output restriction:* (print `X` for an incomplete number):

* remove `|48` (-3 bytes)
* replace `echo chr(...);` with `$r.=...;echo$r>1e10?X:$r;` (+11 bytes)

**breakdown**

```
for($s=join($argv);$c=ord($s[$i++]);    # loop through characters of arguments
    $i+=$x)                             # skip "?"
$t[]=
    $c>90                               # if "_"
        ?63                             # then 32+16+15
        :                               # else
            15&(                            # lower 4 bits of
            $c<65                               # if digit
            ?$c                                 # then digit
            :($c-($c>80)-($c>87)-59)/3          # else letter mapped to digit
        )
        |16*$x="?"==$s[$i]                  # if next char is "?", add 16
;
for(;$p++<10;)echo chr( # loop through translated arguments
    (
        $e=$t[$p]^      # 2. $e=difference
        $d=$t[$p+10]    # 1. $d=char from 2nd argument
    )&48                # if certainties differ
    |!(15&$e)           #    or digits do not
    ?min($t[$p],$d)&15|48   # then pick the more definite digit (15|48 -> "?")
    :63             # else "?"
);

```

**golfings**

* work around `preg_replace_callback` (-10 bytes)
* rely on 10 digit input (-9)
* and additional golfing (-8)
* removed `join` delimiter (-7)
* moved `$x` assignment to the end (-2)

# Answer
> 1 votes
# Perl 5 `-pl`, 173 bytes

```
sub t{$_=pop;y/A-Z/22233344455566677778889999/;/_|\d\??/g}@e=m|\S+|g;@a=t$e[0];$_=join"",map{$_.=shift@a;s/^(.+)\1$/$1/||s/_//||s/..../_/||s/.\?//;$_}t$e[2];s/\?//;$_ x=!/_/

```

Try it online!

---
Tags: code-golf, cipher
---


title: Regex only base64 decoder

text:
# Question
Title: Regex only base64 decoder
Write a regular expression substitution string which can base64 decode a string using only a regular expression engine built into the language. Eg:

```
# Example in python
import re

print(re.sub(..., ..., "SGVsbG8gd29ybGQK"))  # "Hello world\n"
#            ^^^  ^^^
#            These count towards your byte count, the rest doesn't

```

Rules:

* No libraries
* No tools like `base64` in bash
* Must be a regular expression
* Must decode RFC 4648 based base64
* Any programming language (eg: Python, JavaScript, PHP, Ruby, Awk, Sed)
* Length of your find string + Length of your replace string = Byte count
* Shortest byte count wins

# Answer
> 2 votes
# Perl 6, 4 + 87 = 91 bytes

```
S/(.)*/{:64[first(.ord,:k,flat 65..90,97..122,48..57,43,47)for $0].polymod(256 xx*).chrs.flip}/

```

Try it online!

Assumes that the input is padded with ending `=`s and uses `+` and `/` as 62 and 63. Really, the first half selects everything while the second half is just a code block to translate base64...

---
Tags: code-golf, regular-expression
---


# Question
Title: Calculate hamming weight with low hamming weight
Create a program that computes the hamming weight of a string. Winner is the program with the lowest hamming weight.

Rules:

* Hamming weight for an ASCII character is defined as the total number of bits set to `1` in its binary representation.
* Assume input encoding is 7-bit ASCII, passed through whatever input mechanism is normal for your language (e.g. stdin, args, etc.)
* Output the result, as a number, to stdout or whatever default/normal output mechanism your language uses.
* It should go without saying, but you have to be able to *actually run the program, in real life,* for it to be a valid solution.
* Winner is the solution whose code has the lowest hamming weight.
* Sorry, no solutions in whitespace for this one! Ok, you can code in whitespace now I've sorted out the rules :)

Per-character examples:

```
char |  binary  | weight
-----+----------+-------
a    | 01100001 | 3
x    | 01111000 | 4
?    | 00111111 | 6
\x00 | 00000000 | 0
\x7F | 01111111 | 7

```

# Answer
> 6 votes
# J (33)

One lower than 34!

```
+/,#:3 u:

```

Heavily *inspired* by this answer, but a hamming weight of one lower.

```
   +/,#:3 u:'+/,#:3 u:'
33

```

# Answer
> 8 votes
## J, weight 34

```
+/,#:a.i.

```

Usage - place the string to be measured in quotes at the end:

```
   +/,#:a.i.'+/,#:a.i.'
34

```

Alternatively, taking input from the keyboard (weight 54):

```
   +/,#:a.i.1!:1[1
hello
21

```

# Answer
> 5 votes
## , 39

```
+/,#:a.i:]

```

This is a function taking one argument. (Or replace `]` with the string directly; as Gareth notes, that brings the cost down to 34.)

```
   +/,#:a.i:] 'hello world'
45
   +/,#:a.i:] '+/,#:a.i:]'
39

```

# Answer
> 5 votes
## Python, 189

```
print sum(bin(ord(A)).count("1")for A in raw_input())

```

# Answer
> 5 votes
## QBasic, ~~322~~ ~~311~~ ~~286~~ 264

```
H$=COMMAND$
FOR A=1 TO LEN(H$)
B=ASC(MID$(H$,A,1))
WHILE B>0
D=D+B MOD 2
B=B\2
WEND
NEXT
?D

```

*Kind of* the right tool for the job, still sucks of course.

# Answer
> 5 votes
## Unary 0

You all knew it was coming. First the BrainFuck program:

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

```

I added newlines to make it "readable" but it has a Hamming weight of 4066. It works by repeatedly getting the quotient/remainders of an input string and adding up all the remainders. Of course should you run it on itself you get: 226 (4066 % 256) (technically \xe2) so clearly it rules itself the winner.

Now we convert it to Unary and get

```
000 ... 9*google^5.9 0's ... 000

```

We use a unary implementation with NULL characters \x00 for '0' and boom, hamming weight of 0.

**Bonus question**: For what ASCII characters `c` can you run this program on a string consisting on `N` repitions and have it output that character. (E.G. a string of 32 spaces gives a space). What values of `N` work (either an infinite number of them will work, or none will).

# Answer
> 4 votes
### Golfscript ~~84~~ ~~72~~ 58

```
{2base~}%{+}*

```

*(thanks to Howard and Peter Taylor for their help)*

*Input:* the input string has to be on the stack (passed as command line argument, or simply placed on the stack).

In case you run it from the command line, make sure you use `echo -n`, otherwise the trailing newline will also be counted.

*Output:* prints the hamming weight value to the console

The program can be tested here.

# Answer
> 4 votes
## C, weight 322 263 256

Does the hamming weight of the hamming weight count?

```
main(D,H,A)char*A,**H;{for(A=*++H;*A;A+=!(*A/=2))D+=*A%2;printf("%d",D-2);}

```

Used mostly standard golfing techniques.
A single loop calculates weight (shifting right and adding until zero) and scans the string (advances pointer when zero reached).
Assuming `D` is initialized to 2 (single parameter).

Hamming weight specific optimizations:
1. `ABDH`, with weight 2 each, used for names.
2. `*++H` preferred over `H[1]`.

# Answer
> 2 votes
## Perl, 80 (22 chars)

Done and done:

```
perl -0777nE 'say unpack"%32B*"'

```

Or here's an alternate version with a weight of 77 (21 chars):

```
perl -0777pE '$_=unpack"%32B*"'

```

I don't like that version as much, though, because its output omits the final newline.

To calculate the weight, I'm assuming that I'm counting characters in the usual way (excluding the `perl -e`/`-E`, but including other option characters). If for some reason people complain about this, then the best I can do without options is 90 (26 chars):

```
$/=$,,say unpack"%32B*",<>

```

Sample usage:

```
$ perl -0777nE 'say unpack"%32b*"' rickroll.txt
7071

```

Boom.

# Answer
> 2 votes
# Pyth - 15

**Disclaimer: This answer isn't eligible to win since Pyth is younger than this challenge.**

Uses `.B` for binary representation and counts the number of `"1"`'s.

```
/.BQ\1

```

Takes input in a string to save on `z` versus `Q`.

Try it online here.

# Answer
> 1 votes
### Scala 231

```
readLine().map(_.toInt.toBinaryString).flatten.map(_.toInt-48)sum

```

Selftesting code:

```
"""readLine().map(_.toInt.toBinaryString).flatten.map(_.toInt-48)sum""".map(_.toInt.toBinaryString).flatten.map(_.toInt-48)sum

```

with selftesting modification.

# Answer
> 1 votes
# Java, weight ~~931~~ ~~774~~ ~~499~~ 454

I think this is the only answer at the moment with a weight over about 300.

```
class H{public static void main(String[]A){System.out.print(new java.math.BigInteger(A[0].getBytes()).bitCount());}}

```

Expects input as a command line argument.

# Answer
> 1 votes
# GNU `sed -r`, 467 + 1

(+1 for use of `-r` \- or should that be +4?)

Outputs as a unary value per source line; to convert to a decimal total, redirect output into `| tr -d "\n" | wc -c`. Counts all printable ASCII characters (32-126), plus linefeed (10).

```
s@[a-z]@\U& @g
s@[?{}~]@      @g
s@[][/7;=>OW|^]@     @g
s@[-'+.3569:<GKMNSUVYZ\\]@    @g
s@[#%&)*,CEFIJL1248ORTX]@   @g
s@$|[!"$(ABDH0P`]@  @g
y! @!11!

```

It's hard to avoid listing all characters, but we can reduce this observing that lowercase letters have a Hamming weight of one more than the corresponding uppercase letters. We prefer newline (score 2) over semicolon (score 5) as a statement separator; we prefer `@` (score 1) or `!` (score 2) over `/` (score 5) as pattern delimiter.

Note - to get the right sets of characters, I created this table from the one in `man ascii`, sorted by weight. Just add the scores right and below to get the overall weight of each character:

```
   2 4   3 5 6   7
   ---  ------   -
0:   @   0 P `   p |0

1: ! A   1 Q a   q |
2: " B   2 R b   r |1
4: $ D   4 T d   t |
8: ( H   8 X h   x |

3: # C   3 S c   s |
5: % E   5 U e   u |
6: & F   6 V f   v |2
9: ) I   9 Y i   y |
A: * J   : Z j   z |
C: , L   < \ l   | |

7: ´ G   7 W g   w |
B: + K   ; [ k   { |3
D: - M   = ] m   } |
E: . N   > ^ n   ~ |

F: / O   ? _ o     |4
   ---  ------   -
    1      2     3

```

This might prove useful to others.

# Answer
> 0 votes
# Julia 262 268

Modified version uses handy 'count\_ones' function for a saving of 6 (262)

```
show(mapreduce(x->count_ones(x),+,map(x->int(x),collect(ARGS[1]))))

```

Old version using no built in one-counting function (268)

```
show(mapreduce(x->int(x)-48,+,mapreduce(x->bits(x),*,collect(ARGS[1]))))

```

Uses command line argument for input.

# Answer
> 0 votes
# CJam 52 or 48

If input is not already on the stack (52)

```
q:i2fbs:s:i:+

```

If input is on stack (48)

```
:i2fbs:s:i:+

```

For example

```
"Hello World":i2fbs:s:i:+

```

# Answer
> 0 votes
# Julia, HW 199

```
H=mapreduce;H(B->B=='1',+,H(P->bits(P),*,collect(A[:])))

```

With

```
A="H=mapreduce;H(B->B=='1',+,H(P->bits(P),*,collect(A[:])))"

```

or by directly inserting the string:

```
julia> H=mapreduce;H(B->B=='1',+,H(P->bits(P),*,collect("H=mapreduce;H(B->B=='1',+,H(P->bits(P),*,collect(A[:])))")))
199

```

The ungolfed version (HW 411) looks like this:

```
bitstring=mapreduce(x->bits(x),*,collect(teststring[:]))
mapreduce(checkbit->checkbit=='1',+,bitstring)

```

And for the fun of it, here is an optimized version (Hamming Weight **231**) of bakerg’s take on the problem:

```
A=mapreduce;show(A(B->int(B)-48,+,A(B->bits(B),*,collect(H[:]))))

```

with

```
H="A=mapreduce;show(A(B->int(B)-48,+,A(B->bits(B),*,collect(H[:]))))"

```

# Answer
> 0 votes
# HPPPL (HP Prime Programming Language), 74

```
sum(hamdist(ASC(a),0))

```

The HP Prime graphing calculator has a built-in hamdist() function. The hamming weight of each character is the same as the hamming distance from 0.

ASC(string) creates an array of the ASCII values of each character in a string.

hamdist(value,0) computes the hamming distance from 0 for each ASCII value

sum() sums up all values.

Calculating the hamming weight of its own source code:

# Answer
> 0 votes
# 05AB1E, weight 17 (4 bytes)

```
ÇbSO

```

Try it online or verify some more test cases.

**Explanation:**

```
Ç       # Convert the characters in the (implicit) input to their ASCII decimal values
        #  i.e. "Test" → [84,101,115,116]
 b      # Convert those values to binary
        #  i.e. [84,101,115,116] → ["1010100","1100101","1110011","1110100"]
  S     # Split it into a list of 0s and 1s (implicitly flattens)
        #  i.e. ["1010100","1100101","1110011","1110100"]
        #   → [1,0,1,0,1,0,0,1,1,0,0,1,0,1,1,1,1,0,0,1,1,1,1,1,0,1,0,0]
   O    # Sum those (and output implicitly)
        #  i.e. [1,0,1,0,1,0,0,1,1,0,0,1,0,1,1,1,1,0,0,1,1,1,1,1,0,1,0,0] → 16

```

# Answer
> 0 votes
# Perl 6, 102

```
+*.ords>>.base(2).comb(~1)

```

Try it online!

While this isn't code golf, the shortest solution also seems to have the smallest hamming weight...

---
Tags: code-golf, binary, number-theory
---


title: Happy Birthday to Me!

text:
# Question
Title: Happy Birthday to Me!
## Happy birthday to Me!

Write a program that prints `Happy birthday to me!` on its birthday.

1. The program's birthday is the creation, last modification or compilation time of the program (you choose), and must not be hard-coded.
2. The date you use as the birthday must not be affected by the program's invocation or execution in any way. You can't modify your birthday.
3. For extra credit (-15% byte count), print `Happy birthday to you!` on your birthday (hard coded), if it doesn't coincide with the program's. Or use some celebrity's birthday and get -14%.
4. It must print only this, and not print anything on any other day.
5. Count bytes, in UTF-8.
6. Use the Gregorian calendar.

Good luck and happy birthday (to the newborn programs).

P.S.
Following Izkata's comment, if you print `Happy birthday to Mel` on Mel Kaye's birthday, you get 20% off. But you have to provide a credible source that it's this date.

# Answer
## PHP ~~77~~ ~~75~~ ~~74~~ ~~65~~ 60

Many thanks to the superb suggestions from Tim Seguine:

```
<?date(dm,getlastmod())-date(dm)&&die?>Happy birthday to me!

```

## Sneaky PHP: ~~46~~ ~~42~~ ~~41~~ 40

Using Phil H's idea and again Tim Seguine's suggestion:

```
<?touch(__FILE__)?>Happy birthday to me!

```
> 10 votes

# Answer
# bash - 65

```
[ `date +%d%m -r $0` = `date +%d%m` ]&&echo Happy birthday to me!

```

Thanks to *ugoren*, *ace* and *nyuszika7h* for help.
> 13 votes

# Answer
# C# 198.05 (233 - 15%)

```
using s=System;class P{static void Main(){string t=s.DateTime.Now.ToString("Mdd"),b="1202";if(s.IO.File.GetCreationTime(typeof(P).Assembly.Location).ToString("Mdd")==t|b==t)s.Console.Write("Happy birthday to "+(b==t?"you!":"me!"));}}

```

Formatted:

```
using s = System;
class P
{
    static void Main()
    {
        string t = s.DateTime.Now.ToString("Mdd"), b = "1202";
        if (s.IO.File.GetCreationTime(typeof(P).Assembly.Location).ToString("Mdd") == t | b == t)
            s.Console.Write("Happy birthday to " + (b == t ? "you!" : "me!"));
    }
}

```

# 191 (No bonus)

```
using s=System;class P{static void Main(){if(s.IO.File.GetCreationTime(typeof(P).Assembly.Location).ToString("Mdd")==s.DateTime.Now.ToString("Mdd"))s.Console.Write("Happy birthday to me!");}}

```

# 181,05 (213 - 15%)

With some additional instructions (you need to compile this to `b.exe` and run it from the directory the executable is in) I can get it down to this:

```
using s=System;class P{static void Main(){string t=s.DateTime.Now.ToString("Mdd"),b="1202";if(s.IO.File.GetCreationTime("b.exe").ToString("Mdd")==t|b==t)s.Console.Write("Happy birthday to "+(b==t?"you!":"me!"));}}

```

# 171 (No bonus)

Same instructions as above, this time only printing a message on it's own birthday (so no -15% bonus).

```
using s=System;class P{static void Main(){if(s.IO.File.GetCreationTime("b.exe").ToString("Mdd")==s.DateTime.Now.ToString("Mdd"))s.Console.Write("Happy birthday to me!");}}

```
> 6 votes

# Answer
# Java - 275 - 15% = 233.75 with bonus / 237 without bonus

With bonus:

```
import java.util.*;class L{public static void main(String[]y){int s=f(new Date());String j="Happy birthday to ";System.out.print(s==f(new Date(new java.io.File("L.class").lastModified()))?j+"me!":s==183?j+"you!":"");}static int f(Date d){return d.getMonth()*40+d.getDate();}}

```

Without the bonus:

```
import java.util.*;class L{public static void main(String[]y){if(f(new Date())==f(new Date(new java.io.File("L.class").lastModified())))System.out.print("Happy birthday to me!");}static int f(Date d){return d.getMonth()*40+d.getDate();}}

```

I was born in April, 23rd.
> 5 votes

# Answer
## Matlab: 66

```
t=dir('f.m');if strncmp(t.date,date,5),'Happy birthday to me!',end

```

File name has to be 'f.m'
> 2 votes

# Answer
I'm pretty proud of this little trick to save a few bytes on the message. I hope it will be included in other answers. I was the first to think of this!

# Python

105 characters, no extra credit. Save the file as "happy birthday to me" and run. Runs in GMT only, and "birthday" is defined as the date of your birth, not it's anniversary (also often call "birthday").

```
import sys,os,time
if (int(os.stat(*sys.argv).st_atime/86400)==int(time.time()/86400)):print sys.argv[0]

```

For it to work, save this as "happy birthday to me" and run `python "happy birthday to me"`

Note: of course, the all but a small bootstrap could be in the filename, making any arbitrarily large code reduce down to the bootstrap. Normally I would consider this "cheating". However, "happy birthday to me" is not an unreasonable filename - it describes what the program does, much better than some programs (e.g. "python"), so in this case I'm going to allow it :)
> 2 votes

# Answer
## Batch - 37 Bytes

Stealing the method used by one of the Bash answers..

```
@echo.>>%0&echo Happy birthday to me!

```

**Other method - 145 Bytes**

```
@for /f "tokens=2,3 delims=/ " %%a in ("%date%")do @for /f "tokens=1,2 delims=/" %%c in ("%~t0")do @if %%a%%b==%%c%%d @echo Happy Birthday to me!

```
> 2 votes

# Answer
**GNU COBOL** with -free, **204**

```
PROGRAM-ID.B.DATA DIVISION.WORKING-STORAGE SECTION.
1 A PIC XXXX/XX.
1 B PIC X(5).
1 C PIC X(21).
PROCEDURE DIVISION.ACCEPT A FROM DATE
ACCEPT C
MOVE WHEN-COMPILED TO B
IF A(3:5) = B OR "12/09" DISPLAY C.

```

I break the rules about the celebrity, so no bonus there...

The text produced is user-input (requested when run). If that is not good-to-go, then the line defining `C` needs to be deleted, as does `ACCEPT C`, and `DISPLAY C` must become `DISPLAY "HAPPY BIRTHDAY TO ME!"`, for an extra seven characters.

`WHEN-COMPILED` is a special-register containing compile date/time which is available to the program (always handy, you can know you have the correct version). It is truncated in the `MOVE` because the rest isn't needed. `DATE` is the current date - this one is yymmdd.

The `/` in the definition of A is an insertion editing symbol, since the compile-date contains slashes. An extra character, but eases the compare.

Celebrity = Grace Hopper
> 2 votes

# Answer
### Powershell - 127

```
if ((gci $MyInvocation.MyCommand.Path).lastwritetime.ToString("MMdd") -eq (get-date).ToString("MMdd")){"happy birthday to me!"}

```

### For the 15% bonus - 151 bytes, less 15% = 128.4

```
$r=@{"0308"="you";(gci $MyInvocation.MyCommand.Path).lastwritetime.ToString("MMdd")="me"}[(get-date).tostring("MMdd")]
if($r){"Happy birthday to $r!"}

```
> 1 votes

# Answer
# JavaScript

## Node.js, 156 bytes

```
b=new Date(require("fs").statSync(__filename).mtime);d=new Date();b.getDate()==d.getDate()&&b.getMonth()==d.getMonth()&&console.log("Happy birthday to me!")

```

Uses the file's modification time.
> 1 votes

# Answer
# Ruby, 69 characters/bytes

```
puts'Happy birthday to me!'if(Time.new-File.atime($0))%31536000<86400

```

`31536000` is the number of seconds in a year, and `86400` is the number of seconds in a day.
> 1 votes

# Answer
## Ruby - ~~80~~ ~~103~~ 87 bytes

```
m=File.mtime $0
t=Time.now
puts"Happy birthday to me!"if t.month==m.month&&t.day==m.day

```

---

## Ruby - ~~123~~ ~~115~~ ~~135~~ 121 - 15% = ~~104.55~~ ~~97.75~~ ~~114.75~~ 102.85 points

```
t=Time.now
{me:File.mtime($0),you:Time.at(36e5)}.map{|n,d|puts"Happy birthday to #{n}!"if t.month==d.month&&t.day==d.day}

```

Might be a little longer or shorter depending on where your birthday falls in the year, and the shortest way to represent that. For mine, that's `36e5` (seconds since epoch; time zone dependent).

---

Does Mel **Gibson** count? Here's a 138 byte - 35% bonus = **89.7-point** program that celebrates itself, me, and Mel!

```
t=Time.now
{me:File.mtime($0),you:Time.at(36e5),Mel:Time.at(2e5)}.map{|n,d|puts"Happy birthday to #{n}!"if t.month==d.month&&t.day==d.day}

```
> 1 votes

# Answer
# Powershell - 105 bytes

```
if('{0:M}'-f(gi $MyInvocation.MyCommand.Definition).creationtime-eq(date -f M)){'Happy birthday to me!'}

```

Ungolfed:

```
if('{0:M}' -f (gi $MyInvocation.MyCommand.Definition).creationtime -eq (date -f M)){
  'Happy birthday to me!'
}

```

The bonus isn't worth it, I can only get 117.5.
> 1 votes

# Answer
## TI-BASIC, 68 bytes

```
If Ans=0:getDate→G:0:G=G:If getDate=G:Disp "HAPPY BIRTHDAY TO ME!"

```

Remember, these tokens are one byte: `If , Ans, →, Disp`. `getDate` is two bytes. All other one-character symbols are one byte.
> 0 votes

# Answer
# PureBasic

## Without Bonus - 142

```
If Bool(FormatDate("%dd%mm",Date())=FormatDate("%dd%mm",GetFileDate(ProgramFilename(),0)))
MessageRequester("","Happy birthday To me!")
EndIf

```

## With Bonus - 218 - 15% = 185.3

```
Dim s$(2)
s$(1)="me"
s$(2)="you"
m$="%dd%mm"
d$=FormatDate(m$,Date())
i=Bool(d$=FormatDate(m$,GetFileDate(ProgramFilename(),0)))|(Bool(d$="2301")<<1)
If i=0:End:EndIf
MessageRequester("","Happy birthday To "+s$(i)+"!")

```
> 0 votes

# Answer
## C# 191 no bonus

```
using s=System;class P{static void Main(){if(s.IO.File.GetCreationTime(typeof(P).Assembly.Location).ToString("Mdd")==s.DateTime.Now.ToString("Mdd"))s.Console.Write("Happy birthday to me!");}}

```

formatted:

```
using s = System;
class P
{
    static void Main()
    {
        if (s.IO.File.GetCreationTime(typeof(P).Assembly.Location).ToString("Mdd") == s.DateTime.Now.ToString("Mdd"))
            s.Console.Write("Happy birthday to me!");
    }
}

```
> 0 votes

# Answer
# J 79

```
 echo((6!:0'')(('',:'Happy birthday to me!'){~])@:-:&(1 2&{)&:>])1{,1!:0{:4!:3''

```

### Bonus version120 - 15% = 102

Do I get extra credit for also printing both when both are having their birthday?

```
echo((2 6$(6!:0 '') , 0 2 7)(' ','Happy birthday to ',"2 1]3 5$'you! me!  both!'){~#.@:(-:&(1 2&{)"1)&:>])1{,1!:0{:4!:3''

```

Explanation (right to left):

```
last =: {:4!:3''     NB. Take the last script run (i.e. the file itself)
time =: 1{,1!:0 last NB. the modification time is the second element in that file's listing

```

The central verb of the train

```
unbox_both =: &:>      NB. unboxes left and right argument
match  =: -:&(1 2&{)"1 NB. for each date given, left and right, compare them
to_int =: #.           NB. convert boolean to int
from   =: {~           NB. from the left array, take element right.

NB. H contains messages an empty row, appended to all combinations of messages.
H =: (' ','Happy birthday to ',"2 1]3 5$'you! me!  both!')

V =: (H from to_int)@:match unbox_both NB. after unboxing and comparing,
                                       NB. select the according message

```

The left tine for the central train:

```
dates=: (2 6$(6!:0 '') , 0 2 7) NB. the current date, and the relevant fields of my birthday.

NB. Combining the bricks:
echo (dates V ]) time           NB. output the monads result on time.

```
> 0 votes

# Answer
# Java - 196

This differs from the other Java submission by using Strings, shaving 41 characters off in the process. It uses String.format("%tj") to format a java.util.Date or a long as a day-of-year String, and then compares these two Strings.

```
class Z{public static void main(String[]y){if("".format("%tj",new java.util.Date()).equals("".format("%tj",new java.io.File("Z.class").lastModified())))System.out.print("Happy birthday to me!");}}

```

Formatted:

```
class Z
{
    public static void main(String[] y)
    {
        if ("".format("%tj", new java.util.Date()).equals("".format("%tj", new java.io.File("Z.class").lastModified())))
            System.out.print("Happy birthday to me!");
    }
}

```
> 0 votes

# Answer
**JavaScript (node.js) - 100 bytes**

```
(require('fs').fstatSync(4).mtime+1).match(Date().substr(4,6))&&console.log('Happy birthday to me!')

```
> 0 votes

# Answer
**vb.net ~161c**

This will print the celebration message to all whose birthday it is.

```
Module M
Sub Main
For Each b In{({"1705","Alan"}),({"2012","You"}),({FileDateTime(Process.GetCurrentProcess.MainModule.FileName).ToString("ddMM"),"Me"})}
If b(0)=Now.ToString("ddMM") Then Console.WriteLine("Happy Birthday To {0}!",b(1))
Next
End Sub
End Module

```

Alan =\> Alan Kaye

Score: 253c (-33c vb.net min) = 220 - 15% (my birthday bonus) = 187c - 14% (Celeb Birthday) = 160.82 ~161c or 220c - 29% = 156.2 ~157c
> 0 votes

# Answer
# Powershell, 82 bytes

> see also answers from Chris J and SpellingD

```
"Happy birthday to me!"|?{(gv My* -v|% M*|% p*h|gci|% l*w*e|% D*r)-eq(date|% D*r)}

```

where

```
gv My* -v|% M*|% p*h|gci|% l*w*e|% D*r

```

is the combinations of shortcuts and aliases for the expression:

```
Get-Valiable MyInvocation -value|% MyCommand|% Path|Get-ChildItem|% LastWritetime|% DayOfYear

```

that equivalent a canonical form:

```
(Get-ChildItem $MyInvocation.MyCommand.Path).LastWritetime.DayOfYear

```

---

# Powershell, 119 bytes - 14% = 102.34 Points

```
filter e{$_-eq(date|% D*r)}$('me'|?{gv My* -v|% M*|% p*h|gci|% l*w*e|% D*r|e}
'Prof'|?{3|e})|%{"Happy birthday to $_!"}

```

At January 3, the script display `Happy birthday to Prof!`. If this script is saved on January 3, two greetings will be displayed.
> 0 votes

---
Tags: code-golf
---


title: Alphanumeric balance

text:
# Question
Title: Alphanumeric balance
Write a program which gets a string as its input, and counts the number of alphanumeric and non-alphanumeric characters in it. It has to display its result like this:

input: `http://stackexchange.com`
output: `20 + 4 = 24`

The catch is, your source code has to have the same number of alphanumeric characters as non-alphanumeric ones. Comments are not allowed, whitespace is ignored. (The language called *Whitespace* might compete for votes, but will not be selected as winner, obviously)

Characters in the code must have at least **some** minor justification, they should not be **completely** superfluous. For example, longer variable names are allowed, `i = (j*3)+4;` instead of `i = j*3+4;` is also allowed. However, `i = i + 1;;;;;;` is not.

Besides this, standard code-golf rules apply.

# Answer
# Perl, 32 + 32 = 64

The string is expected in STDIN. The output is written to STDOUT. White space is ignored. My interpretation of the task is that the program should be able to run on itself to get the score.

```
$/ = $,;
$_ = <>;
s x\sxxg;
$\ = length;
print s x[0-9a-z]xxgi,
      ' + ',
      s x.xxg,
      ' = '

```

## Ungolfed with comments

```
$/ = $,; # The input separator becomes undefined, because the default for $, is "undef"
$_ = <>; # now $_ takes the whole file (STDIN) instead of the first line
s x\sxxg; # $_ =~ s/\s//g;
          # white space is removed from $_
$\ = length; # The number of the other characters are put into $\,
             # which is automatically printed the end of "print".
print s x[0-9a-z]xxgi, # s/[0-9a-z]//gi
                       # Remove alphanumeric characters and return their count
      ' + ',
      s x.xxg, # s/.//g
               # Remove the remaining special characters and return their count.
               # "." does not catch new lines, but we have already
               # removed white spaces including new lines.
      ' = '

```

I found several variations with the same byte counts, e.g.:

```
$/ = $x;
$_ = <>, s x\sxxg;
$\ = split $x;
print s x[\da-z]xxgi,
      " + ",
      s x.xxg,
      ' = '

```

## Examples

* Example from the question:

```
echo 'http://stackexchange.com' | perl a.pl
20 + 4 = 24

```
* Running on itself (`a.pl`):

```
cat a.pl | perl a.pl
32 + 32 = 64

```

The file size is 104 bytes, thus 40 bytes are ignored as white space.

# Perl, 29 + 29 = 58

```
$_=<>;s x\sxxg;$\=length;print s x[0-9a-z]xxgi,' + ',s/.//g,' = '

```

The string is expected at STDIN and it is limited to the first line. The result is printed to STDOUT. White space is ignored.

## Ungolfed

```
$_ = <>;
s x\sxxg; # same as s/\s//gx; removes white space;
$\ = length($_); # sum is automatically appended at the end of print
print sx[0-9a-z]xxgi, # same as s/[0-9a-z]//gi;
                      # the number of alphanumeric characters
      ' + ',
      s/.//g, # the number of the remaining special characters
      ' = '

```

## Examples

File `a.pl` contains the Perl script.

* Example from the question:

```
echo 'http://stackexchange.com' | perl a.pl
20 + 4 = 24

```
* Running on itself:

```
cat a.pl | perl a.pl
29 + 29 = 58

```

The file size of `a.pl` is 65 bytes, thus 7 bytes are ignored as white space.
> 8 votes

# Answer
# C - 96 (48+48) characters

It's somewhat readable. There's room for improvement, though.

```
i,j;main(_){while((_=getchar())>=0)isspace(_)||(isalnum(_)?i++:j++);printf("%i + %i = %i",i,j
,i+j);}

```
> 7 votes

# Answer
# Bash + coreutils, 72 (36 + 36) non-whitespace chars

```
a=`tr -dc [:alnum:]<<<$1|wc -c`
n=`tr -dt [:space:]<<<$1|wc -c`
echo $a + $[n-a] = $n

```

Output:

```
$ ./alnumbalance.sh http://stackexchange.com
20 + 4 = 24
$ ./alnumbalance.sh "$(cat alnumbalance.sh)"
36 + 36 = 72
$

```

---

*Previous answer:*

### Pure Bash, 92 (46 + 46) non-whitespace chars

```
nosp=${1//[[:space:]]}
noaln=${nosp//[[:alnum:]]}
echo $[${#nosp}-${#noaln}] + ${#noaln} = ${#nosp}

```

Output:

```
$ ./alnumbalance.sh http://stackexchange.com
20 + 4 = 24
$ ./alnumbalance.sh "$(cat alnumbalance.sh)"
46 + 46 = 92
$

```
> 5 votes

# Answer
# PowerShell (43+43=86)

**Golfed**

```
function alf($i){$a=0;$n=0;[char[]]$i|%{if($_-match"[a-zA-Z0-9]"){$a++}else{$n++}}; write-host "$a+$n=$($a+$n)"}

```

**Un-golfed**

```
function alf($i){
    $a=0;$n=0;
    [char[]] $i | %{ if ($_ -match "[a-zA-Z0-9]") { $a++ } else { $n++ } };
    write-host "$a+$n=$($a + $n)"
}

```

**Test**

```
PS > alf "http://stackexchange.com"
20+4=24

```

**Testing with the code itself to pass the criteria**

```
PS > alf "function alf($i){$a=0;$n=0;[char[]]$i|%{if($_-match`"[a-zA-Z0-9]`"){$a++}else{$n++}}; write-host `"$a+$n=$($a+$n)`"}"
43+43=86

```

`"` has been escaped with \` which is not part of string.
> 3 votes

# Answer
### GolfScript, 74 characters (=37+37)

```
{+}:PLUS;.,.@10,''*26,{65PLUS.32|}%PLUS$-,\1$-' + 'PLUS\PLUS' = 'PLUS\PLUS

```

Online test for the code with the code as input.
> 2 votes

# Answer
# Ruby 38+38=76

This program counts trailing newline in the input.

```
puts"#{a=gets.scan(/[a-z0-9]/i).length}+#{b=$_.scan(/\W|_/).length}=#{a+b}"

```

The character count is done by the program itself: `$ ruby alphabalance.rb alphabalance.rb` :)
> 2 votes

# Answer
# Python 2 (60+60 = 120)

Tough one, there is probably room for improvement. Like the fact the function itself can be used to evalulate its own alphnumeric balance.

```
def f(s):
 i=j=0
 for c in s:
  t=ord(c)
  if (t!=2**5):
   i+=1
  if (48<=t<=57 or 65<=t<=90 or 97<=t<=122):
   j+=1
 print `j`,'+',`i-j`,'=',i

```

Test:

```
>>> f("http://stackexchange.com")
20 + 4 = 24

```
> 2 votes

# Answer
# Powershell, 70 bytes (=35+35)

```
param($s)"$(($l=$s.Length)-($n=($s|sls '\W' -a).Matches.Count))+$n=$l"

```

Test script:

```
$f = {
param($s)"$(($l=$s.Length)-($n=($s|sls '\W' -a).Matches.Count))+$n=$l"
}

&$f "http://stackexchange.com"
&$f $f.toString().Trim()

```

Output:

```
20+4=24
35+35=70

```

---

# Powershell, 70 bytes (=35+35), alternative

```
"$(($l="$args"|% Length)-($n=($args|sls '\W'-a).Matches.Count))+$n=$l"

```
> 2 votes

# Answer
# C++, 146 (73+73) ~~178 (89+89)~~ non-whitespace characters#

Original included `<algorithm>` for no good reason. Oops.

```
//create a test string
#include<string>
std::string a = "\?\?=include <cstdio>\
int x,y;\
int main()\?\?<\
    for(char c : a)\
            !isspace(c) ? (isalnum(c) ? y++ : x++) : 0;\
    printf(\"%d\?\?/t%c\?\?/t%d\?\?/t%c\?\?/t%d\?\?/n\",y,'+',x,'=',(x+y));\
\?\?>";

//Code itself starts here
??=include <cstdio>
int x,y;
int main()??<
    for(char c : a)
        !isspace(c) ? (isalnum(c) ? y++ : x++) : 0;
    printf("%d??/t%c??/t%d??/t%c??/t%d??/n",y,'+',x,'=',(x+y));
??>

```

I am only counting characters in the lines after `//Code itself starts here`. In particular, this means not counting `#include <string>`. I am also counting trigraphs as three characters each, which is perhaps debatable. Note that in testing the program on its own source code some care is required to prevent trigraph replacement within the string literal.

There are some peculiar design decisions here -- in most production code you will not encounter trigraphs and range-based-for loops in the same function -- but I think all within the bounds of 'justifiable'.
> 1 votes

# Answer
# python 52 +52 = 104

Interesting challnge because python avoids non-alphanumeric characters.

```
def f(_):
    _=_.replace(" ","");l=len(_);a=sum([c.isalnum() for c in _][:l]);print("{0} + {1} = {2}".format(a,l-a,l))

```

Minor justification for using slice: it speeds it up (maybe?)
> 1 votes

# Answer
# Julia, 64

```
f(s)=(b=endof(s);a=sum([isalnum(c) for c in s]);"$(a) + $(b-a) = $(b)";)

```

All the only unnecessary non alphanumeric characters are the last `;` and some of the `()` in the string formatting., it came out almost perfectly balanced, and as a power of 2 without much fiddling.

```
julia> f("http://stackexchange.com")
"20 + 4 = 24"
julia> nowhite(s)=join(split("s"," "))
julia> f(nowhite("f(s)=(b=endof(s);a=sum([isalnum(c) for c in s]);\"\$(a)+\$(b-a)=\$(b)\";)"))
"32 + 32 = 64"

```
> 1 votes

# Answer
# perl, 64 non-whitespace chars:

```
$/=$,;
$_=<>;
s 0\s00g;
$\=length;
print s 1[a-z0-9]11ig .
      " + " .
      s 2.22g .
      " = "

```

Clarified slightly via perl -MO=Deparse and some comments:

```
$/ = $,;               # input record separator = a variable defaulting to undef
$_ = <ARGV>;           # slurp stdin
s/\s//g;               # strip whitespace
$\ = length $_;        # output record separator = total length of string sans whitespace
print s/[a-z0-9]//gi . ' + ' . s/.//g . ' = '; # count alphanumerics, then everything else

```

The ORS, $\ is appended automatically in every call to print, putting the total count at the end.
> 1 votes

# Answer
## Python 2, 50 + 50 = 100

```
import re
def f(i):
    w = re.sub('\s', '', i)
    s = re.subn('[\W_]', '', w)
    a = len(s[0])
    print '%d + %d = %d' % (a, s[1], a+s[1])

```

**Try it Online!**
> 1 votes

# Answer
# Rebol (64 + 64 = 128)

```
f: func [x] [
    c: :charset
    a: c [#"a" - #"z"]
    s: c [#" " #"^/" #"^-"]
    n: complement union a s
    a+: n+: 0
    parse x [
        some [
            a (++ a+) |
            n (++ n+) |
            s
        ]
    ]
    print [a+ "+" n+ "=" a+ + n+]
]

```

### Usage example (in Rebol console):

```
>> f "http://stackexchange.com"
20 + 4 = 24

```

NB. Program ignores spaces, tabs & newlines from counts.
> 0 votes

# Answer
# J - 46 + 46 = 92

Counts whitespace, so you can't self-test without a modification. Takes input on stdin. Has a bad mouth, should go wash it out with soap.

```
;":&.>(+/;' + ';(#-+/);' = ';#)(e.~1!:1@1:)(,toupper)'golfscriptSUCKSabdehjkmnquvwxyz',,":"0 i.10

```

Usage:

```
   ;":&.>(+/;' + ';(#-+/);' = ';#)(e.~1!:1@1:)(,toupper)'golfscriptSUCKSabdehjkmnquvwxyz',,":"0 i.10
http://stackexchange.com
20 + 4 = 24

   NB. modification for self-test:    vvvvvv - remove spaces, the only whitespace
   ;":&.>(+/;' + ';(#-+/);' = ';#)(e.~' '-.~1!:1@1:)(,toupper)'golfscriptSUCKSabdehjkmnquvwxyz',,":"0 i.10
;":&.>(+/;' + ';(#-+/);' = ';#)(e.~1!:1@1:)(,toupper)'golfscriptSUCKSabdehjkmnquvwxyz',,":"0 i.10
46 + 46 = 92

```
> 0 votes

# Answer
# Javascript - 76 (38 + 38)

```
_ = prompt()
o = _.match(/[a-z0-9]/gi).length
$ = _.length - o
alert(o + " + " + $ + " = " + (o + $))

```

Sample Input: `http://stackexchange.com`
Output: `20 + 4 = 24`

Running on self:

```
var a  = '_ = prompt()o = _.match(/[a-z0-9]/gi).length$ = _.length - oalert(o + " + " + $ + " = " + (o + $))'

var letters = a.match(/[a-z0-9]/g).length;
var nons = a.match(/[^a-z0-9 ]/g).length; // excludes whitespace from count

console.log(nons + " = " + letters); // 38 = 38 :)

```

P.S. For those concerned with `(o + $)` being done to maintain alphanumeric balance, it is not so. Because after seeing `o + " + "` JS would decide all `+` to be string concatenaters rather than number adders. Thus the parentheses are necessary, or `20 + 4` would become `204` rather than `24` :D

Happy Coding!
> 0 votes

# Answer
# Clojure: (31 + 31 = 62) non-whitespace chars

```
(def ff #(let [c count y (c %) x (c (re-seq #"\w" %))] (str x " + " (- y x) " = " y)))

```

Output:

```
alphabalance.core=> (ff "http://stackexchange.com")
"20 + 4 = 24"

```
> 0 votes

# Answer
# CJam, 27 + 27 = 54

CJam is a couple of months newer than this challenge, so this answer is not eligible for the green checkmark. It was a fun exercise anyway, though!

```
ea0=eu{A,s'[,65>+#)g}%_:+1@f-:+ea0=,]"DODDaD"36f-3/]zo

```

It takes the input string as a command-line argument, so it won't work in the online interpreter, but you can test it with the Java interpreter.

## Explanation

```
"Distinguish alphanumeric characters:";
ea0=eu{A,s'[,65>+#)g}%
ea0=                   "Get the first command-line argument.";
    eu                 "Convert it to upper case.";
      {             }% "Map this block onto each character.";
       A,s             "Get the string '0123456789'.";
          '[,          "Get a string with all characters from the null byte to Z.";
             65>       "Remove the first 65 characters, to leave A to Z.";
                +      "Add to digit.";
                 #     "Find character in that string. Returns -1 if not alphanumeric.":
                  )g   "Increment and get signum. Yields 1 for alphanumeric characters,
                        0 otherwise.";

"Now we've got an array of 0s and 1s. Let's do the counting:";
_:+1@f-:+ea0=,]
_               "Duplicate array.";
 :+             "Get the sum. This is the number of alphanumeric characters.";
   1@           "Push a 1 and pull up the other copy of the array.";
     f-         "Subtract each element from 1, this swaps 0s and 1s.";
       :+       "Get the sum. This is the number of symbol characters.";
         ea0=   "Get the first command-line argument again.";
             ,  "Get its length. This is the total number of characters.";
              ] "Collect everything in an array.";

"And now the formatting:";
"DODDaD"36f-3/]zo
"DODDaD"          "Push this string.";
        36f-      "Subtract 36 from each character. This yields ' +  = '.";
            3/    "Split into two halves of 3 characters each.";
              ]   "Wrap this and the previous array in another array.";
               z  "Zip. Transposes the array to interleave strings with numbers.";
                o "Output the resulting array without delimiters.";

```
> 0 votes

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


# Question
Title: Algorithm to print the Minimum number of adjacent character swaps necessary to remove all instances of "VK" in a given string?
For example, how many adjacent swaps are at least needed to convert some string such as `BVVKCV` to one without any instances of `VK`?

Input-length of the string will be within the range `1 <= length <= 200`.
`VK` will be hardcoded across all test cases.

Input string examples:

```
Input:  VKVKVVVKVOVKVQKKKVVK
Output: 8

Input:  VVKEVKK
Output: 3

Input:  JUSTIN
Output: 0

```

# Answer
# Japt, 44 bytes

```
m£Z¯Y cZtY2 Ô cZsY+2Ãrc
®¬ø"VK"
W+VÌ
Ve ?ß:W

```

Try it online!

It times out on the first test case because it's super inefficient (something like O(n^n)?) but it should be a viable algorithm. Input is weird; it is a singleton list containing the input, but the input itself is formatted as a list of upper-case characters. I think that would typically be valid, but if not let me know.

Explanation:

```
#Step 1: try all the swaps
m                          #For each string Z reachable with n swaps (n starts at 0)
 £                  Ã      # For each letter Y in Z:
  Z¯Y                      #  Get the letters before it in Z
      c                    #  Concat
       ZtY2 Ô              #  Y swapped with the following character
              c            #  Concat
               ZsY+2       #  The rest of Z
                     rc    #Flatten by one level
                           #Result: A list of all strings reachable with n+1 swaps

#Step 2: Check for "VK"
®¬         #For each string from Step 1:
  ø"VK"    # Check whether it contains "VK"
           #Result: A list where 1 indicates there was "VK" and 0 otherwise

#Step 3: Increment the counter appropriately
W+      #Increase the counter by
  VÌ    #The value for the original string when run through step 2
        #Result: 0 if 0 swaps were required, the current number of swaps otherwise

#Step 4: Iterate or end
Ve ?       #If all the reachable strings contain "VK"
    ß      # Repeat the program with the current values
     :W    #Otherwise return the counter
           #Result: Outputs the counter when a non-"VK" string is found.

```
> 1 votes

# Answer
# Python 3, 125 bytes

```
s={input()}
a=0
while all("VK"in q for q in s):a+=1;s={a[:i]+a[i+1]+a[i]+a[i+2:]for a in s for i in range(len(a)-1)}
print(a)

```

Try it online!

Basic BFS.
> 0 votes

---
Tags: code-golf, string, programming-puzzle, recursion
---