title: How much is my dice matrix worth?

text:
# Question
Title: How much is my dice matrix worth?
## Input

A non-empty binary matrix consisting of 3x3 sub-matrices put side by side.

## Task

Your task is to identify valid dice patterns (as described below) among the 3x3 sub-matrices. Each valid pattern is worth the value of the corresponding dice. Invalid patterns are worth 0.

## Output

The sum of the valid dice values.

## Dice patterns

$$\begin{align} &1:\pmatrix{\color{gray}0,\color{gray}0,\color{gray}0\\\color{gray}0,1,\color{gray}0\\\color{gray}0,\color{gray}0,\color{gray}0} &&2:\pmatrix{1,\color{gray}0,\color{gray}0\\\color{gray}0,\color{gray}0,\color{gray}0\\\color{gray}0,\color{gray}0,1}\text{or}\pmatrix{\color{gray}0,\color{gray}0,1\\\color{gray}0,\color{gray}0,\color{gray}0\\1,\color{gray}0,\color{gray}0}\\ &3:\pmatrix{1,\color{gray}0,\color{gray}0\\\color{gray}0,1,\color{gray}0\\\color{gray}0,\color{gray}0,1}\text{or}\pmatrix{\color{gray}0,\color{gray}0,1\\\color{gray}0,1,\color{gray}0\\1,\color{gray}0,\color{gray}0} &&4:\pmatrix{1,\color{gray}0,1\\\color{gray}0,\color{gray}0,\color{gray}0\\1,\color{gray}0,1}\\ &5:\pmatrix{1,\color{gray}0,1\\\color{gray}0,1,\color{gray}0\\1,\color{gray}0,1} &&6:\pmatrix{1,\color{gray}0,1\\1,\color{gray}0,1\\1,\color{gray}0,1}\text{or}\pmatrix{1,1,1\\\color{gray}0,\color{gray}0,\color{gray}0\\1,1,1} \end{align}$$

## Example

The expected output for the following matrix is **14** because it contains the dice **5**, **6** and **3**, followed by an invalid pattern (from left to right and from top to bottom).

$$\pmatrix{1,0,1,1,1,1\\ 0,1,0,0,0,0\\ 1,0,1,1,1,1\\ 1,0,0,0,0,0\\ 0,1,0,0,1,0\\ 0,0,1,0,1,0}$$

## Rules

* Both the width and the height of the matrix are guaranteed to be multiples of 3.
* You must ignore sub-matrices that are not properly aligned on the grid (see the 3rd test case). More formally and assuming 0-indexing: the coordinates of the top-left cell of each sub-matrix to be considered are of the form \\$(3x, 3y)\\$.
* This is .

## Test cases

```
// 0
[ [ 1,0,0 ],
  [ 0,0,1 ],
  [ 1,0,0 ] ]

// 2
[ [ 0,0,1 ],
  [ 0,0,0 ],
  [ 1,0,0 ] ]

// 0 (0 + 0)
[ [ 0,0,1,0,1,0 ],
  [ 0,0,0,1,0,0 ],
  [ 0,0,1,0,1,0 ] ]

// 9 (3 + 3 + 3)
[ [ 1,0,0,0,0,1,1,0,0 ],
  [ 0,1,0,0,1,0,0,1,0 ],
  [ 0,0,1,1,0,0,0,0,1 ] ]

// 6 (6 + 0)
[ [ 1,0,1 ],
  [ 1,0,1 ],
  [ 1,0,1 ],
  [ 1,0,1 ],
  [ 1,0,0 ],
  [ 1,0,1 ] ]

// 14 (5 + 6 + 3 + 0)
[ [ 1,0,1,1,1,1 ],
  [ 0,1,0,0,0,0 ],
  [ 1,0,1,1,1,1 ],
  [ 1,0,0,0,0,0 ],
  [ 0,1,0,0,1,0 ],
  [ 0,0,1,0,1,0 ] ]

// 16 (1 + 2 + 3 + 4 + 0 + 6)
[ [ 0,0,0,1,0,0,1,0,0 ],
  [ 0,1,0,0,0,0,0,1,0 ],
  [ 0,0,0,0,0,1,0,0,1 ],
  [ 1,0,1,1,1,1,1,0,1 ],
  [ 0,0,0,1,0,1,1,0,1 ],
  [ 1,0,1,1,1,1,1,0,1 ] ]

```

# Answer
> 5 votes
# Python 3, ~~195~~ 189 bytes

*-6 bytes thanks to @Jo King*

```
lambda m:sum({16:1,257:2,68:2,273:3,84:3,325:4,341:5,455:6,365:6}.get(int(''.join(str(e)for c in m[3*i:][:3]for e in c[3*j:][:3]),2),0)for i in range(len(m)//3)for j in range(len(m[0])//3))

```

Try it online! (189) ~~Try it online! (195)~~

### Human readable version:

```
# 3x3 part matrix to dice, beginning at coordinates 3*i, 3*j
def single_matrix_to_dice(matrix, i, j):
    # Example: matrix = [[0, 0, 0], [0, 1, 0], [0, 0, 0]], i=0, j=0 (result is 1)

    matrix_string = ''.join(
        str(e) for column in matrix[3*i:3*i+3]
        for entry in column[3*j:3*j+3]
    ) # Slicing the matrix so that only the valid entries remain, here '000010000'

    # Interpreting the matrix string as binary number, here 16
    binary_number = int(matrix_string,2)

    # binary representations of all valid dice rolls
    dct = {16:1,257:2,68:2,273:3,84:3,325:4,341:5,455:6,365:6}

    return dct.get(binary_number, 0)

def f(matrix):
    return sum(
        single_matrix_to_dice(matrix, i, j) for i in range(len(m)//3)
        for j in range(len(m[0])//3))
    ) # len(m)/3 would generate a float, so len(m)//3 is used

```

# Answer
> 5 votes
# , 134 bytes

```
function(m,d=dim(m)/3-1){for(a in 0:d)for(b in 0:d[2])F=F+sum(y<-m[1:3+a*3,1:3+b*3])*sum(y*2^(8:0))%in%utf8ToInt("āDđTŅŕǇŭ");F}

```

Try it online!

I noticed I had the same idea of @Heteira

History :

* ~~171~~ : -10 bytes thanks to @JayCe !
* ~~161~~ : -3 bytes thanks to @Giuseppe !
* ~~158~~ : -13 bytes saved !
* ~~145~~ : -2 bytes thanks to @Giuseppe!
* ~~143~~ : -6 bytes saved !
* ~~137~~ : -3 bytes thanks to @JayCe!

# Answer
> 4 votes
# Perl 6, ~~113 105 97~~ 94 bytes

```
{sum (|@_[*;^3+3*$_]for ^@_[0]).rotor(9).map:{"@āđŅŕǇ@@DT@@ŭ".ords.first(:2[$_],:k)%7}}

```

Try it online!

Splits up the matrix into sub matrices of 3x3, converts the nine 1s and 0s to base 2 and then indexes it into a list of integers for the value.

### Explanation:

```
{  #Start anonymous code block
  sum   # Sum of all
     (|@_[*;^3+3*$_]   # Get the n*3 to n*3+3th elements in every sub-list
           for ^@_[0]) # For n in the range 0 to width (divide by 3 to avoid warnings)
     .rotor(9)  # Split this list into groups of 9 (split the dice up)
     .map:{     # And map each die to
        "@āđŅŕǇ@@DT@@ŭ".ords  # In the list of integers
           .first(      # The first appearance of
               :2[$_],  # The dice converted from a list of 0s and 1s to base 2
                 :k     # Returning the index
             )%7        # And modulo by 7 to get the alternate versions of 2, 3 and 6
          }
}

```

# Answer
> 4 votes
# Jelly,  ~~29~~ 28 bytes

-1 thanks to Mr. Xcoder (use  to replace `ṢṪ`)

```
s€3ZẎs3µZU,ƊṀṙ1FḄ“°€⁼-Ḍ?‘i)S

```

A monadic link.

**Try it online!** Or run the tests.

### How?

```
s€3ZẎs3µZU,ƊṀṙ1FḄ“°€⁼-Ḍ?‘i)S - Link: list of lists of 1s and 0s
s€3                          - split each into threes
   Z                         - transpose
    Ẏ                        - tighten
     s3                      - split into threes -> the sub-matrices in column-major order
       µ                  )  - for each sub-matrix, say D:
           Ɗ                 -   last three links as a monad:
        Z                    -     transpose D
         U                   -     reverse each -> D rotated a quarter turn clockwise
          ,                  -     pair with D
            Ṁ                -   get the maximum of the two orientations
             ṙ1              -   rotate left by one (to ensure FḄ will yield integers <256 for all non-zero valued D)
               F             -   flatten
                Ḅ            -   convert from binary
                         i   -   first 1-based index in (0 if not found):
                 “°€⁼-Ḍ?‘    -     code-page indices list = [128,12,140,45,173,63]
                           S - sum

```

For example when a sub-matrix is:

```
[[1,0,1],
 [1,0,1],
 [1,0,1]]

```

Then `ZU,Ɗ` yields:

```
[[[1, 1, 1],
  [0, 0, 0],
  [1, 1, 1]],   ...which has maximum (Ṁ):    ...and after ṙ1:
 [[1, 0, 1],                   [[1, 1, 1],         [[0, 0, 0],
  [1, 0, 1],                    [0, 0, 0],          [1, 1, 1],
  [1, 0, 1]]]                   [1, 1, 1]]          [1, 1, 1]]

```

...which flattens to `[0, 0, 0, 1, 1, 1, 1, 1, 1]`, which, converting from binary, is `63` which is the sixth entry in the code-page index list `“°€⁼-Ḍ?‘` (`?` being byte `3F` in Jelly's code-page)

# Answer
> 3 votes
# Japt `-x`, 36 bytes

*Now it's getting interesting. I'm sure can be golfed down even more*

```
ò3 ®®ò3Ãy f@"0ıtŵġdťƍǧ"øºXm¬¬Í+H)d
c

```

Try it online!

# Answer
> 2 votes
# Retina 0.8.2, 90 bytes

```
+`(...)(.+¶)(...)(.+¶)(...)
$1¶$3¶$5¶$2$4
¶

M!`.{9}
G`111000111|(101){3}|(.)0(.0).0\3\2
1

```

Try it online! Explanation:

```
+`(...)(.+¶)(...)(.+¶)(...)
$1¶$3¶$5¶$2$4

```

Repeatedly remove \\$3\times 3\\$ blocks from each \\$3\times n\\$ row until all rows have 3 columns.

```
¶

M!`.{9}

```

Join all the blocks together and then split back up into rows of 9 columns.

```
G`111000111|(101){3}|(.)0(.0).0\3\2

```

Only keep valid dice patterns (two patterns for `6`, then one matches any number from `0` to `5`, although `0` of course will not contribute to the count below.)

```
1

```

Count the pips on the valid dice.

# Answer
> 2 votes
# Vyxal `d`, 34 bytes

```
3ẇƛƛ3ẇ;ÞTvf;f9ẇ'†B»@uS∨∪ċ#»b9ẇvB$c

```

Try it Online!

A mess.

# Answer
> 1 votes
# Ruby, 151 bytes

```
->m{m.each_slice(3).flat_map{|r|r.transpose.each_slice(3).map{|d|" \x10āđŅŕǇ  DT  ŭ".chars.map(&:ord).index(d.flatten.join.to_i 2)&.%7}-[p]}.sum}

```

Try it online!

A lambda accepting a 2d array of ints (or strings, I guess). Takes inspiration from Jo King's answer. I feel like slicing the dice out of the input matrix took a lot of space, so I may well be outgolfed. Fortunately, dealing with nils only cost me a handful of bytes.

Ungolfed:

```
->m{
  m.each_slice(3).flat_map{|r|             # Split into groups of 3 rows
    r.transpose.each_slice(3).map{|d|      # Split into groups of 3 columns
      " \x10āđŅŕǇ  DT  ŭ".chars.map(&:ord) # [0,16,257,273,325,341,455,0,0,68,84,0,0,365]
        .index(                            # Find in that array
          d.flatten.join.to_i 2            #   the die flattened into a bitstring (nil if not found)
        )&.%7                              # Safe-modulo 7 (leaves nils as nil)
    }-[p]                                  # Remove nils
  }.sum                                    # Add 'em up
}

```

# Answer
> 1 votes
## Clojure, 197 bytes

```
#(apply +(for[R[range]i(R 0(count %)3)j(R 0(count(% 0))3)](case(apply +(map *(iterate(partial * 2)1)(for[x(R 3)y(R 3)]((%(+ i x))(+ j y)))))16 1 257 2 68 2 273 3 84 3 325 4 3 4 1 5 455 6 365 6 0)))

```

I should have come up with something smarter.

# Answer
> 1 votes
# Python 2, 159 bytes

```
f=lambda a:a>[]and sum(u'ȀāDđTŅȀŕȀǇŭ'.find(unichr(int(J(J(map(str,r[i:i+3]))for r in a[:3]),2)))/2+1for i in range(0,len(a[0]),3))+f(a[3:])
J=''.join

```

Try it online!

Hat tip to Jonathan Frech for the unicode encoding approach.

---
Tags: code-golf, array, binary-matrix
---


title: Try to make a cube!

text:
# Question
Title: Try to make a cube!
Based on this: Make me a square!

You need to output this:

```
  ####
 # # #
###  #
# # #
####

```

Where "#" is replaced with the input.

If you input "A", you should get

```
  AAAA
 A A A
AAA  A
A A A
AAAA

```

If you input "&", you should get

```
  &&&&
 & & &
&&&  &
& & &
&&&&

```

## Leaderboard

Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.

```
/* Configuration */

var QUESTION_ID = 121651; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 48934; // This should be the user ID of the challenge author.

/* App */

var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;

function answersUrl(index) {
  return "https://api.stackexchange.com/2.2/questions/" +  QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}

function commentUrl(index, answers) {
  return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}

function getAnswers() {
  jQuery.ajax({
    url: answersUrl(answer_page++),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      answers.push.apply(answers, data.items);
      answers_hash = [];
      answer_ids = [];
      data.items.forEach(function(a) {
        a.comments = [];
        var id = +a.share_link.match(/\d+/);
        answer_ids.push(id);
        answers_hash[id] = a;
      });
      if (!data.has_more) more_answers = false;
      comment_page = 1;
      getComments();
    }
  });
}

function getComments() {
  jQuery.ajax({
    url: commentUrl(comment_page++, answer_ids),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      data.items.forEach(function(c) {
        if (c.owner.user_id === OVERRIDE_USER)
          answers_hash[c.post_id].comments.push(c);
      });
      if (data.has_more) getComments();
      else if (more_answers) getAnswers();
      else process();
    }
  });
}

getAnswers();

var SCORE_REG = /<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;

var OVERRIDE_REG = /^Override\s*header:\s*/i;

function getAuthorName(a) {
  return a.owner.display_name;
}

function process() {
  var valid = [];

  answers.forEach(function(a) {
    var body = a.body;
    a.comments.forEach(function(c) {
      if(OVERRIDE_REG.test(c.body))
        body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>';
    });

    var match = body.match(SCORE_REG);
    if (match)
      valid.push({
        user: getAuthorName(a),
        size: +match[2],
        language: match[1],
        link: a.share_link,
      });

  });

  valid.sort(function (a, b) {
    var aB = a.size,
        bB = b.size;
    return aB - bB
  });

  var languages = {};
  var place = 1;
  var lastSize = null;
  var lastPlace = 1;
  valid.forEach(function (a) {
    if (a.size != lastSize)
      lastPlace = place;
    lastSize = a.size;
    ++place;

    var answer = jQuery("#answer-template").html();
    answer = answer.replace("{{PLACE}}", lastPlace + ".")
                   .replace("{{NAME}}", a.user)
                   .replace("{{LANGUAGE}}", a.language)
                   .replace("{{SIZE}}", a.size)
                   .replace("{{LINK}}", a.link);
    answer = jQuery(answer);
    jQuery("#answers").append(answer);

    var lang = a.language;
    if (/<a/.test(lang)) lang = jQuery(lang).text();

    languages[lang] = languages[lang] || {lang: a.language, user: a.user, size: a.size, link: a.link};
  });

  var langs = [];
  for (var lang in languages)
    if (languages.hasOwnProperty(lang))
      langs.push(languages[lang]);

  langs.sort(function (a, b) {
    if (a.lang > b.lang) return 1;
    if (a.lang < b.lang) return -1;
    return 0;
  });

  for (var i = 0; i < langs.length; ++i)
  {
    var language = jQuery("#language-template").html();
    var lang = langs[i];
    language = language.replace("{{LANGUAGE}}", lang.lang)
                       .replace("{{NAME}}", lang.user)
                       .replace("{{SIZE}}", lang.size)
                       .replace("{{LINK}}", lang.link);
    language = jQuery(language);
    jQuery("#languages").append(language);
  }

}
```

```
body { text-align: left !important}

#answer-list {
  padding: 10px;
  width: 290px;
  float: left;
}

#language-list {
  padding: 10px;
  width: 290px;
  float: left;
}

table thead {
  font-weight: bold;
}

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
# Carrot, 31 bytes

```
  ####
 # # #
###  #
# # #
####

```

`#`s are replaced by the input.

Basically a port of this answer, to this problem.
> 19 votes

# Answer
# 05AB1E, ~~16~~ 15 bytes

```
ð‚•nxвΛ•2вèJ6ô»

```

Try it online!

**Explanation**

```
ð‚                # push the list [<input>,<space>]
  •nxвΛ•          # push the number 816342339
        2в        # convert to list of base 2 digits
          è       # index into the the 2-char string with this list
           J      # join to string
            6ô    # split into pieces of length 6
              »   # join on newlines

```
> 13 votes

# Answer
# Cubix, 62 bytes

```
./v<.o;.@?/;w.w;i:::::NrSs::SrSuUS::sN::rS:r:srNr:SrSsNs:::SSv

```

Try it online! and Watch the interpreter!

This fits onto a 4-cube:

```
        . / v <
        . o ; .
        @ ? / ;
        . . w ;
i : : : : : N r S s : : S r S u
U S : : s N : : r S : r : s r N
r : S r S s N s : : : S S v . .
. . . . . . . . . . . . . . . .
        . . . .
        . . . .
        . . . .
        . . . .

```

I'm not very good at manipulating the direction of the instruction pointer, so I will continue to try and golf this. Both this and my answer here are based on the "Hello, World!' example program using `./v.o;@?/` (on a 3-cube) to recursively print and pop the characters on the stack, so the rest of the code is just pushing the characters onto the stack in the right order.

I have now made a cube on a cube, so I can rest easy (and do my actual work).
> 12 votes

# Answer
# SOGL, ~~13~~ 10 bytes

```
Βū&⁵'r⁹‘6n

```

Explanation:

```
Βū&⁵'r⁹‘    push "  ŗŗŗŗ ŗ ŗ ŗŗŗŗ  ŗŗ ŗ ŗ ŗŗŗŗ", where "ŗ" is replaced with input
        6n  split into lines of length 6

```
> 9 votes

# Answer
# MATL, ~~13~~ 10 bytes

*Thanks to Conor O'Brien for removing 3 bytes, and for showing me that unprintables can be used in Octave.*

The code contains unprintable characters. Try it online!

### Explanation

```
'....'   % Push 5-char string (contains unprintables). Each char encodes a row
         % of the desired pattern
B        % Convert to binary. Gives a 5×6 binary matrix with the pattern
*        % Implicit input. Multiply element-wise (converts input to ASCII code)
c        % Convert to char. Implicitly display. Char 0 is shown as space

```
> 9 votes

# Answer
# PHP, 52 Bytes

```
<?=strtr("  0000
 0 0 0
000  0
0 0 0
0000",0,$argn);

```

Try it online!
> 6 votes

# Answer
## Japt, 20 bytes

```
"OUyj|"®c ¤Åd0S1U +R

```

Test it online!

Not too bad for a language with no built-in compression (well, except compressing strings of lowercase letters)...

### Explanation

In binary, the five characters in the string are:

```
O 1001111
U 1010101
y 1111001
j 1101010
| 1111100

```

Slice off the initial `1` from each, and you get the pattern for the cube.

```
"OUyj|"®   c ¤  Å  d0S1U +R
"OUyj|"mZ{Zc s2 s1 d0S1U +R}  // Expanded
                              // Implicit: U = input string
"OUyj|"mZ{                 }  // Replace each character Z in this string with this function:
          Zc                  //   Take the char-code of Z.
             s2               //   Convert to a binary string.
                s1            //   Slice off the first character (always a "1").
                   d0S1U      //   Replace "0"s with spaces and "1"s with the input.
                         +R   //   Append a newline.
                              // Implicit: output result of last expression

```
> 6 votes

# Answer
# LOLCODE, ~~202~~ 170 bytes

```
I HAS A c
GIMMEH c
VISIBLE"  "AN c AN c AN c AN c AN":) "AN c AN" "AN c AN" "AN c AN":)"AN c AN c AN c AN"  "AN c AN":)"AN c AN" "AN c AN" "AN c AN":)"AN c AN c AN c AN c

```

In LOLCODE, not much to golf...

This sets the variable `c` into the input, and creates a giant concatenated string including `:)` newlines. That's about it.
> 6 votes

# Answer
# Sed, 40 characters

```
s/./  &&&&\
 & & &\
&&&  &\
& & &\
&&&&/

```

Almost cheating as the challenge description contained it almost literally.

Sample run:

```
bash-4.4$ sed 's/./  &&&&\
 & & &\
&&&  &\
& & &\
&&&&/' <<< 'C'
  CCCC
 C C C
CCC  C
C C C
CCCC

```

Try it online!
> 5 votes

# Answer
# Python 2, 61 bytes

```
lambda c:"""  ####
 # # #
###  #
# # #
####""".replace('#',c)

```

Try it online!
> 5 votes

# Answer
# Z80 Assembly, 37 bytes machine code

Assume a memory mapped I/O device:

```
; DO NOT INPUT A SPACE or it will go into infinite loop printing spaces & newlines!

3A xx xx    ld  a, (input)  ; get input character
11 0A 20    ld  de, 200ah   ; space & newline
21 yy yy    ld  hl, output  ; get output address
4F          ld  c, a        ; put character in c
loop:
72          ld  (hl), d     ; output space * 2       | output character * 2
72          ld  (hl), d
77          ld  (hl), a     ; output character       | output character
71          ld  (hl), c     ; output character * 2   | output space * 2
71          ld  (hl), c
77          ld  (hl), a     ; output character       | output character
73          ld  (hl), e     ; output newline         | output newline
72          ld  (hl), d     ; output space           | output character
71          ld  (hl), c     ; output character       | output space
72          ld  (hl), d     ; output space           | output character
71          ld  (hl), c     ; output character       | output space
72          ld  (hl), d     ; output space           | output character
B9          cp  c           ; set zero flag 1st time | clear 2nd time
20 06       jr  nz, end     ; skip to end
77          ld  (hl), a     ; output character
73          ld  (hl), e     ; output newline
4A          ld  c, d        ; put space in c
57          ld  d, a        ; put character in d
28 FB       jr  z, loop     ; loop to 2nd time
end:
73          ld  (hl), e     ; output newline
77          ld  (hl), a     ; output character * 4
77          ld  (hl), a
77          ld  (hl), a
77          ld  (hl), a
76          halt            ; or C9 ret

```
> 5 votes

# Answer
# , 27 bytes

```
4äl2>>Äyvho3pÄÙ3älWx<<3Îd^

```

Try it online!

Hexdump:

```
00000000: 34e4 6c32 3e3e c479 7668 6f1b 3370 c4d9  4.l2>>.yvho.3p..
00000010: 33e4 6c57 783c 3c33 ce64 5e              3.lWx<<3.d^

```
> 4 votes

# Answer
# Charcoal, ~~17~~ 16 bytes

```
ＳβＧＨ7+↗→³β→Ｇ↓↙³β

```

Try it online! Link is to verbose version of code. Longer than I wanted it to be, because the "cube" is slightly wider than it is tall or deep. Fortunately some of the multidirectional characters work with PolygonHollow, which saves me 3 bytes. Edit: Saved a further byte by using + instead of T↑. Explanation:

```
Ｓβ          Input the character
ＧＨ7+↗→³β    Draw the left half. 7 becomes ←↙ and + becomes →↓←↑.
→           Move right one character.
Ｇ↓↙³β       Draw the right half.

```

At the time of the challenge, the `q` variable didn't work in verbose mode, otherwise I could have created this 14-byte version:

```
ＧＨ7+↗→³θ→Ｇ↓↙³θ

```

Try it online!
> 4 votes

# Answer
# PHP, 72 bytes

I made this one just for the fun of it, since there's already a better PHP answer.

```
for($i=0;$i<27;)echo('00'.decbin(64349871))[$i]?$argn:' ',++$i%6?'':'
';

```

---

The cube is drawn by getting the binary value of `64349871`, concatenated by `'00'`.
This returns the following:

```
0011110101011110011010101111

```

Every 6th character, I'm outputting a newline, resulting in this:

```
001111
010101
111001
101010
1111

```

And, instead of displaying `0`, it displays a space, which will look like:

```
  1111
 1 1 1
111  1
1 1 1
1111

```
> 4 votes

# Answer
# Stacked, 31 bytes

```
' '\+$'9*<'#.2 tb[6 dpad]map#

```

Try it online!

Here's a hexdump:

```
λ xxd try-to-make-a-cube.stk
00000000: 2720 275c 2b24 270f 1539 2a3c 2723 2e32  ' '\+$'..9*<'#.2
00000010: 2074 625b 3620 6470 6164 5d6d 6170 23     tb[6 dpad]map#

```

This converts a character array to binary, pads each row to length `6`, and indexes it according to the string `' ' input +`
> 3 votes

# Answer
# Pyth, ~~25~~ ~~22~~ ~~21~~ 20 bytes

```
jcsm?d\ zjC"0¨eC"2 6

```

Try it!

21 bytes

```
t::." \"o½MËñ"\!bNw

```

Try this!

Also 21 bytes:

```
:jbct." \" ±¢î
"6Nw

```

Try that!
> 3 votes

# Answer
# JS (ES6), ~~64~~ ~~60~~ 52 bytes

```
i=>`  ####
 # # #
###  #
# # #
####`.replace(/#/g,i)

```

Can this be improved:

```
i=>`  ${y=i+i+i+i}
 # # #
###  #
# # #
${y}`.replace(/#/g,i)

```
> 2 votes

# Answer
# C (gcc), ~~90~~ 84 bytes

```
i;v;f(g){for(i=32;i--;)putchar((v="####*@#@#@#*#@@###*#@#@#@*####@@"[i])&1?g:v-32);}

```

Try it online! Defines a function `f` that takes a character `g`. Too bad encoding the table directly is shorter...

## Old version, 90 bytes

(Still trying to golf this one)

Trying to have only a single `putchar`, but idk. There are unprintables, so here is the hexdump:

```
λ xxd try-to-make-a-cube.c
00000000: 693b 6a3b 6628 6729 7b63 6861 722a 6b3d  i;j;f(g){char*k=
00000010: 220f 1539 2a3c 223b 666f 7228 693d 303b  "..9*<";for(i=0;
00000020: 693c 353b 7075 7463 6861 7228 3130 292c  i<5;putchar(10),
00000030: 692b 2b29 666f 7228 6a3d 3332 3b6a 3b6a  i++)for(j=32;j;j
00000040: 2f3d 3229 7075 7463 6861 7228 6b5b 695d  /=2)putchar(k[i]
00000050: 266a 3f67 3a33 3229 3b7d                 &j?g:32);}

```

This encodes the cube into a binary lookup table, where a `1` bit represents the input and a `0` bit represents a space. Try it online!
> 1 votes

# Answer
# Brain-Flak, 217 bytes

```
(((((((((((((((((({}))))<([][]()())>)<(([][])[]{}())>)<(([][]){})>)<([])>)<(((()
())[][]{}()()))>)))<((()()()()()){})>)<(((()()()){}){}()[])>)<(((()()())()){}{}[
])>)<(((()()())){}{}[])((()()()()()){})>))))(([]()()()))

```

Try it online!

Waaaaay too long.
> 1 votes

# Answer
# Swift - 82 bytes + Foundation (18 bytes)?

```
var f={"  ####\n # # #\n###  #\n# # #\n####".replacingOccurrences(of:"#",with:$0)}

```

By default, Xcode-Swift projects have `Whole-Module Optimization`, so that `import Foundation` is not required for this simple lambda-like function. However, running it in online environments requires it, which may add 18 bytes.

**Check it out!**
> 1 votes

# Answer
# Java 8, 55 bytes

```
c->"  ####\n # # #\n###  #\n# # #\n####".replace('#',c)

```

Try it here.

# Java 7, 77 bytes

```
String c(char c){return"  ####\n # # #\n###  #\n# # #\n####".replace('#',c);}

```

Try it here.
> 1 votes

# Answer
# Vyxal `jr`, 12 bytes

```
ðp»2<I∵»τ5$/

```

Try it Online!

```
  »2<I∵»τ    # Decompress the pattern using...
ðp           # Space + input
         5$/ # Split into 5
             # (j flag) Join by newlines

```
> 1 votes

# Answer
# brainfuck, 79 bytes

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

```

Try it online!

Not sure why this doesn't exist
> 1 votes

# Answer
## CJam, 23 bytes

```
"pjFUC"{i2b(;}%rS+ff=N*

```

I feel like I can still golf this.

```
"pjFUC" e# String literal:          │ "pjFUC"
{       e# For each:                │ 'p
  i     e#   Get code point:        │ 112
  2b    e#   To binary:             │ [1 1 1 0 0 0 0]
  (;    e#   Delete first:          │ [1 1 0 0 0 0]
}%      e# End                      │ [[1 1 0 0 0 0] [1 0 1 0 1 0] [0 0 0 1 1 0] [0 1 0 1 0 1] [0 0 0 0 1 1]]
r       e# Read token:              │ [[1 1 0 0 0 0] [1 0 1 0 1 0] [0 0 0 1 1 0] [0 1 0 1 0 1] [0 0 0 0 1 1]] "&"
S       e# Push space:              │ [[1 1 0 0 0 0] [1 0 1 0 1 0] [0 0 0 1 1 0] [0 1 0 1 0 1] [0 0 0 0 1 1]] "&" " "
+       e# Concatenate:             │ [[1 1 0 0 0 0] [1 0 1 0 1 0] [0 0 0 1 1 0] [0 1 0 1 0 1] [0 0 0 0 1 1]] "& "
ff=     e# Vectorized array lookup: │ ["  &&&&" " & & &" "&&&  &" "& & & " "&&&&  "]
N*      e# Join with newlines       │ "  &&&&
        e#                          │   & & &
        e#                          │  &&&  &
        e#                          │  & & &
        e#                          │  &&&&  "
e# Implicit output

```
> 0 votes

# Answer
# dc, 70 bytes

Encodes the sequence rather directly, with minor optimization:

```
8224PdPdPdPdP10Pd8192+ddPPP10PdPdPdP8224PdP10Pd256*32+ddPPP10PdPdPdPdP

```

Try it online!

---

Taken to a (not very golfy) extreme, 145 bytes:

```
27065671941896667324298575455432398417474802390765222440949482848513*56759961956005660143530475805610581704254588701249011343446231795984498688+P

```

Try it online!

This computes `A*x+B`, where `A` encodes the positions of the input character and `B` encodes all the rest:

> A = 2560 \+ 2561 \+ 2562 \+ 2563 \+ 2565 \+ 2567 \+ 2569 \+ 25611 \+ 25614 \+ 25615 \+ 25616 \+ 25618 \+ 25620 \+ 25622 \+ 25625 \+ 25626 \+ 25627 \+ 25628
>
> B = 10×2564 \+ 32×2566 \+ 32×2568 \+ 10×25610 \+ 32×25612 \+ 32×25613 \+ 10×25617 \+ 32×25619 \+ 32×25621 \+ 32×25623 \+ 10×25624 \+ 32×25629 \+ 32×25630

`P` command prints the resulting number as a byte stream.
> 0 votes

# Answer
# Windows batch, 79 bytes

```
@echo   %1%1%1%1
@echo  %1 %1 %1
@echo %1%1%1  %1
@echo %1 %1 %1
@echo %1%1%1%1

```

Special char. safe, 97 bytes:

```
@echo   ^%1^%1^%1^%1
@echo  ^%1 ^%1 ^%1
@echo ^%1^%1^%1  ^%1
@echo ^%1 ^%1 ^%1
@echo ^%1^%1^%1^%1

```
> 0 votes

# Answer
## C#, 53 bytes

```
c=>@"  ####
 # # #
###  #
# # #
####".Replace('#',c);

```
> 0 votes

# Answer
# Tcl, 60 bytes

```
proc c x {regsub . $x "  &&&&\n & & &\n&&&  &\n& & &\n&&&&"}

```
> 0 votes

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


title: pleTriwapt Sgpin (Triplet Swapping)

text:
# Question
Title: pleTriwapt Sgpin (Triplet Swapping)
## Intro/Background

I was looking at a Flybuys card at Coles recently and noticed that if I took something like this:

Source, randomly found on the Internet

And swapped some words around, I'd get this:

After I finished laughing (don't judge my sense of humour please), I said to myself: "I need a program that can generate text like that". So I devised a set of rules for substring swapping and wrote yet another CGCC challenge!

## The Challenge

Given a single string as input, output a string with its substrings swapped. This can be done by:

* Splitting the string into chunks of three. The last triplet can possibly be shorter. (`abcdefgh => [abc, def, gh]`)
* Swap every triplet with every other triplet, leaving the last triplet in place if there is an odd amount of triplets.

The above bullet point more succinctly:

> \[D\]ivide the list into adjacent pairs and swap each pair ~ @FlipTack

## Test Cases

```
Input->Output
flybuys->buyflys
Once->eOnc
Triplet->pleTrit
Code Golf->e GCodolf
TopAnswers!->AnsTops!wer
Never gonna let you down->er Nevna gon yoletownu d
I'm Sorry, I Haven't a Clue-> SoI'm, Irryven Haa C't lue
Can I please have my vegetables back?-> I Canasepleve  havegmy bleetaacks b?
You are filled with determination-> arYouille fwited eteh dnatrmiion
->

```

Reference Program

## Some Test Cases Explained

```
flybuys
[fly, buy, s] (split)
[buy, fly, s] (swapped)
buyflys

Once
[Onc, e] (split)
[e, Onc] (swapped)
eOnc

Triplet
[Tri, ple, t] (split)
[ple, Tri, t](swapped)
pleTrit

Code Golf
[Cod, e G, olf] (split)
[e G, Cod, olf] (swapped)
e GCodolf

TopAnswers!
[Top, Ans, wer, s!] (split)
[Ans, Top, s!, wer] (swapped)
AnsTops!wer

```

## Rules

* Input/output can be taken/given in any reasonable and convenient format
* The input will not contain newlines
* Strings can be of any length, and can be empty
* Input will only contain printable ASCII characters
* All standard loopholes are forbidden

## Scoring

This is , so the answer with the lowest bytes wins

# Answer
> 8 votes
# , 13 bytes

```
[:;_2|.\_3<\]

```

Try it online!

Example input: 'flybuys'

* `_3<\]` Box every group of 3

```
┌───┬───┬─┐
│fly│buy│s│
└───┴───┴─┘

```
* `_2|.` Split *that* into groups of 2, and reverse each one:

```
┌───┬───┐
│buy│fly│
├───┼───┤
│s  │   │
└───┴───┘

```
* `[:;` Raze the result:

```
buyflys

```

# Answer
> 7 votes
# Perl 6, 24 bytes

```
{S:g/(...)(..?.?)/$1$0/}

```

Try it online!

Simple regex substitution that swaps every pair of three and up to three.

# Answer
> 6 votes
# Jelly, 5 bytes

```
s3ṭ2/

```

A full program accepting a string which prints the result.

**Try it online!**

### How?

```
s3ṭ2/ - Main Link: list of characters
s3    - split into threes
   2/ - 2-wise reduce with:
  ṭ   -   tack
      - implicit, smashing print

```

# Answer
> 5 votes
# Gema, 13 characters

```
<u3><u3>=$2$1

```

Sample run:

```
bash-5.0$ echo -n 'flybuys' | gema '<u3><u3>=$2$1'
buyflys

```

Try it online! / Try all test cases online!

# Answer
> 5 votes
# Brainfuck, ~~37~~ 33 bytes

```
,[>,>,>>,>,>,<<[.>]<[<]<<<[.>]>,]

```

-4 bytes thanks to @JoKing

You can try it online

Cell layout is `|a|b|c|0|d|e|f|`, I read unconditionally and then print what is there to be printed.

Probably still golfable...

# Answer
> 5 votes
# APL (Dyalog Unicode), 17 bytesSBCS

```
⍬∘(⍋⍋-6×3≤6|⍋)⊃¨⊂

```

Try it online!

Uses `⎕IO←0`, i.e. 0-based indexing.

### How it works

Uses `⍬⍋` generating index trick, though simply using `⍳≢` gives the same byte count here (thanks @ngn for pointing this out).

```
⍬∘(⍋⍋-6×3≤6|⍋)⊃¨⊂
⍬∘( ⍋-6×3≤6|⍋)     ⍝ Generate some numbers to apply "sortBy" on the input
⍬∘          ⍋        ⍝ Generate 0-based indexes
          6|         ⍝ Modulo 6
        3≤           ⍝ 1 if 3≤x is true, 0 otherwise
      6×             ⍝ 6 times
⍬∘  ⍋-               ⍝ Subtract from the original 0-based indexes;
                     ⍝ the result looks like 0 1 2 ¯3 ¯2 ¯1 6 7 8 3 4 5 12 13 ..
   ⍋          ⊃¨⊂  ⍝ "sortBy"; sort the input in the increasing order of above

```

# Answer
> 4 votes
# PHP, ~~60~~ 57 bytes

```
for($a=str_split($argn,3);$b=$a[$i++|0];)echo$a[$i++],$b;

```

Try it online!

# Answer
> 3 votes
# , 5 bytes

```
"jC?┐

```

Uncompressed

```
3,2,_r

```

# Explained

```
3,%Split the input into chunks of three
2,%Group the inputs into chunks of two
_r%Reverse every two-chunk of the input

```

# Answer
> 3 votes
# Jelly, 6 bytes

```
s3s2Ṛ€

```

Try it online!

A full program taking a string and implicitly printing the rearranged string. This could be turned into a monadic link that returns a Jelly string by adding `F` (flatten) to the end.

## Explanation

```
s3     | Split into sublists length 2
  s2   | Split into sublists length 2
    Ṛ€ | Reverse each

```

# Answer
> 3 votes
# JavaScript (Node.js), 36 bytes

```
x=>x.replace(/(...)(..?.?)/g,"$2$1")

```

Try it online!

Simple regex substitution.

# Answer
> 3 votes
# 05AB1E, 6 bytes

```
3ô2ôíS

```

Outputs as a list of characters.

Try it online or verify all test cases.

**Explanation:**

```
3ô      # Split the (implicit) input-string into parts of size 3
  2ô    # Split this list into parts of size 2
    í   # Reverse each inner pair of triplets
     S  # Convert it to a flattened list of characters
        # (after which this is output implicitly)

```

# Answer
> 3 votes
# Factor, 62 bytes

```
: f ( s -- s ) 3 group 2 group [ reverse concat ] map concat ;

```

Try it online!

Factor defies golfing :)

# Answer
> 2 votes
# GolfScript, 10 bytes

```
3/2/{-1%}%

```

Try it online!

# Explanation

```
3/         # Split the input into chunks of three
  2/       # Group the inputs into chunks of two
    {-1%}% # Reverse every two-chunk of the input
           # This deals with the last two-chunk, in which
           # no reversing is done

```

# Answer
> 2 votes
# Charcoal, 10 bytes

```
⭆⪪Ｓ⁶⪫⮌⪪ι³ω

```

Try it online! Link is to verbose version of code. Splitting into groups of 6 and splitting those works out shorter because it keeps the two numbers separate. Explanation:

```
  Ｓ         Input string
 ⪪ ⁶        Split into substrings of 6 characters
⭆           Map over substrings and join
       ι    Current substring
      ⪪ ³   Split into substrings of 3 characters
     ⮌      Reverse the substrings
    ⪫    ω  Join together
            Implicitly print

```

# Answer
> 2 votes
# Haskell, ~~50~~ 42 bytes

```
s(a:b:c:d)=take 3d++a:b:c:s(drop 3d)
s x=x

```

-8 bytes thanks to Post Rock Garf Hunter.

Try it online!

# Answer
> 2 votes
# K (ngn/k), 15 bytes

```
,//|'0N 2#0N 3#

```

Try it online!

`0N 3#` chunks of 3; last may be shorter

`0N 2#` pairs of chunks; last may be a singleton list

`|'` reverse each

`,//` flatten

# Answer
> 2 votes
# Burlesque, 13 bytes

```
3co2co)<-FL\[

```

Try it online!

```
3co # Chunks of 3
2co # Chunks of 2
)<- # Map - Reverse
FL  # Flatten
\[  # Concatenate

```

# Answer
> 1 votes
# Japt `-P`, 7 bytes

```
ò3 ò cw

```

Try it

# Answer
> 1 votes
# PHP, 153 bytes

```
$c=($h='array_chunk')($h(str_split($argn),3),2);foreach($c as&$i)count($i)-1&&[$i[0],$i[1]]=[$i[1],$i[0]];echo implode(($m='array_merge')(...$m(...$c)));

```

Try it online!

# Answer
> 1 votes
# Lua, 43 bytes

```
print(((...):gsub('(...)(.?.?.?)','%2%1')))

```

Try it online!

Take input as argument, print result to stdout. TIO link include program that check all testcases given in question. Uses Lua patterns to capture three and up to three characters, then swap those groups.

# Answer
> 1 votes
# naz, ~~210~~ 190 bytes

```
2a2x1v1x1f1r3x1v2e2x2v1r3x1v3e2x3v1r3x1v4e2x4v1r3x1v5e2x5v1r3x1v6e2x6v1r3x1v7e2x7v5v1o6v1o7v1o2v1o3v1o4v1o1f0x1x2f0a0x1x3f2v1o0x1x4f2v1o3v1o0x1x5f2v1o3v1o4v1o0x1x6f5v1o5f0x1x7f5v1o6v1o5f0x1f

```

I finally fixed the bug in the linked implementation that made solving challenges like this one impossible!

The main part of this program uses a *ton* of conditional instructions to properly split strings of any length, so I've split it onto multiple lines in the below explanation to aid readability.

Works for any input string terminated with the control character STX (U+0002).

Edit: Saved 20 bytes by calling function 5 directly from functions 6 and 7 instead of repeating its logic verbatim.

**Explanation** (with `0x` commands removed)

```
2a2x1v                       # Set variable 1 equal to 2
1x1f1r3x1v2e2x2v             # Function 1
                             # Read a byte of input
                             # Jump to function 2 if it equals variable 1
                             # Otherwise, store it in variable 2
  1r3x1v3e2x3v               # This pattern continues for the next 5 bytes of input
  1r3x1v4e2x4v               # ...
  1r3x1v5e2x5v               # ...
  1r3x1v6e2x6v               # ...
  1r3x1v7e2x7v               # ...
  5v1o6v1o7v1o2v1o3v1o4v1o   # Output variables 5, 6, and 7, then variables 2, 3, and 4
                          1f # Then, jump back to the start of the function
1x2f0a                       # Function 2
                             # Add 0 to the register
1x3f2v1o                     # Function 3
                             # Output variable 2
1x4f2v1o3v1o                 # Function 4
                             # Output variables 2 and 3
1x5f2v1o3v1o4v1o             # Function 5
                             # Output variables 2, 3, and 4
1x6f5v1o5f                   # Function 6
                             # Output variable 5, then variables 2, 3, and 4
1x7f5v1o6v1o5f               # Function 7
                             # Output variables 5 and 6, then variables 2, 3, and 4
1f                           # Call function 1

```

# Answer
> 1 votes
# Perl 5 `-p`, 21 bytes

```
s/(...)(..?.?)/$2$1/g

```

Try it online!

# Answer
> 1 votes
# Python 3, ~~67 77 75~~ 63 bytes

~~`s` is the variable holding the string to manipulate.~~

```
''.join(sum([(s[k+3:k+6],s[k:k+3]) for k in range(0,len(s),6)],()))

```

Try it online!

**Edit**: 77 bytes to respect the rules of Code Golf

```
f=lambda s:''.join(sum([(s[k+3:k+6],s[k:k+3])for k in range(0,len(s),6)],()))

```

Try it online!

**Edit 2**: Dropped the `f=`

```
lambda s:''.join(sum([(s[k+3:k+6],s[k:k+3])for k in range(0,len(s),6)],()))

```

Try it online!

**Edit 3**: Post Rock Garf Hunter made this version which gets rid of the `sum(...,())` call, bringing the byte count down to 63!

```
lambda s:''.join(s[k+3:k+6]+s[k:k+3]for k in range(0,len(s),6))

```

Try it online!

# Answer
> 1 votes
# Red, 59 bytes

```
func[s][until[move/part skip s 3 s 3""= s: skip s 6]head s]

```

Try it online!

# Answer
> 1 votes
# Ruby, 33 bytes

```
->s{s.gsub /(...)(.{,3})/,'\2\1'}

```

Try it online!

# Answer
> 1 votes
# Kotlin, 64 bytes

```
{chunked(3).chunked(2).fold(""){a,v->a+v.getOrElse(1){""}+v[0]}}

{chunked(3)                                                       // split string into triplets
           .chunked(2)                                            // group triplets by two
                      .fold(""){a,v->a+                           // join to string
                                       v.getOrElse(1){""}+v[0]}}  // putting second before first (if exists)

```

Try it online!

# Answer
> 1 votes
# Husk, 7 bytes

```
Σṁ↔C2C3

```

Try it online!

# Answer
> 1 votes
# Vyxal `s`, 5 bytes

```
3ẇy$Y

```

Try it Online!

```
3ẇ    # Divide into chunks of three
  y$Y # Swap each pair

```

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


title: Duplicate & switch case

text:
# Question
Title: Duplicate & switch case
The goal is, having taken a string as input, duplicate each latin letter and "toggle" its case (i.e. uppercase becomes lowercase and vice-versa).

Example inputs & outputs:

```
Input      Output
bad        bBaAdD
Nice       NniIcCeE
T e S t    Tt eE Ss tT
s E t      sS Ee tT
1!1!1st!   1!1!1sStT!
n00b       nN00bB
(e.g.)     (eE.gG.)
H3l|@!     Hh3lL|@!

```

The input consists of printable ASCII symbols.

*You shouldn't duplicate non-latin letters, numbers, special chars.*

# Answer
> 12 votes
# Jelly, 5 bytes

```
żŒsQ€

```

Try it online!

### How it works

```
żŒsQ€  Main link. Argument: s (string)

 Œs    Yield s with swapped case.
ż      Zip s with the result.
   Q€  Unique each; deduplicate each pair of characters.

```

# Answer
> 17 votes
# Python, ~~56~~ 54 bytes

```
lambda s:''.join(c+c.swapcase()*c.isalpha()for c in s)

```

Test it on Ideone.

# Answer
> 16 votes
# JavaScript ES6, ~~70~~ ~~68~~ ~~66~~ 64 bytes

*Saved 2 bytes thanks to @Kevin Lau - not Kenny*

*Saved 2 bytes thanks to @Cᴏɴᴏʀ O'Bʀɪᴇɴ*

```
s=>s.replace(/[A-Z]/gi,l=>l+l[`to${l<"a"?"Low":"Upp"}erCase`]())

```

## Explanation

This uses a really hacky:

```
l[`to${l<"a"?"Low":"Upp"}erCase`]()

```

which ungolfed is:

```
l[`to${
   l < "a" ?
   "Low" :
   "Upp"
}erCase`]()

```

Basically `l < "a"` checks if the code point of the letter is less then the code point of `a` (therefore being an uppercase letter). If it is it'll do `to + Low + erCase` which becomed `l['toLowerCase']()` and makes the character lowercase. ``` quotes allow string formatting so essentially you can think of:

```
`to${l < "a" ?"Low" : "Upp"}erCase`

```

as: `"to" + (l<"a" ? "Low" : "Upp") + "erCase"` which generates the function to call (make the string upper or lower case). We put this in square brackets `[ ... ]` which lets us access a property given its name as a string. This returns the appropriate function and then we just call it.

# Answer
> 10 votes
# Ruby, ~~37~~ 33 (30 +  `-p` flag) bytes

`swapcase` to the rescue! Sort of. -4 bytes from @Lynn.

```
gsub(/[a-z]/i){$&+$&.swapcase}

```

# Answer
> 8 votes
# C, ~~63~~ 60 bytes

```
f(char*s){for(;*s;s++)isalpha(putchar(*s))&&putchar(32^*s);}

```

Uses the fact that `'a' XOR 32 == 'A'`, etc.

Three bytes saved thanks to FryAmTheEggman.

# Answer
> 6 votes
## CJam, 11 bytes

```
l_el_eu.+.|

```

Test it here.

### Explanation

```
l      e# Read input.
_el    e# Duplicate, convert to lower case.
_eu    e# Duplicate, convert to upper case.
.+     e# Concatenate the two characters in matching positions from those two
       e# strings. E.g. "ab!" "AB!" would give ["aA" "bB" "!!"].
       e# For each character from the original string and the corresponding
.|     e# string from this list, take the set union (which eliminates duplicates
       e# and keeps the order the values appear in from left to right, so that
       e# the original case of each letter comes first).

```

# Answer
> 5 votes
# Pyth, 7 bytes

```
sm{+dr2

```

Test suite.

```
sm{+dr2    input: Q
sm{+dr2dQ  implicit arguments

        Q  input
 m         for each character as d:
     r2d       swapcase
   +d          prepend d
  {            deduplicate
s          join as string

```

# Answer
> 5 votes
# Python 3.5, ~~60~~ 56 bytes:

```
for i in input():print(end=i+i.swapcase()[:i.isalpha()])

```

A full program. Will try to golf more.

Try It Online! (Ideone)

# Answer
> 5 votes
# Haskell, 73 bytes

```
l=['a'..'z']
u=['A'..]
(>>= \c->c:maybe""pure(lookup c$zip l u++zip u l))

```

# Answer
> 5 votes
# Cheddar, ~~118~~ 104 bytes

```
(s)->s.chars.map((i)->{if String.letters has i.lower{if i<"a"{i+i.lower}else{i+i.upper}}else{i}}).join()

```

First real Cheddar answer!!! This is a lot less climactic than I thought it would be... ;\_;

Works with release 1.0.0-beta.9, non-competing.

---

As you can tell I didn't design cheddar to be golfy :/

Ungolfed:

```
(str) -> str.chars.map(
    (i) -> {
        if String.letters has i {
            if i < "a" { // Check char code, meaning it's upper case if true
                i+i.lower
            }
            else {
                i+i.upper
            }
        } else {
            i
        }
    }
).join()

```

Usage:

```
var doThing = <code here>;
doThing("input...");

```

---

**Update:** 7/14/16 I've finished ternaries making this come down to 84 bytes

## Cheddar, 84 bytes

```
(s)->s.chars.map((i)->String.letters has i.lower?i<"a"?i+i.lower:i+i.upper:i).join()

```

works as of version v1.0.0-beta.14

# Answer
> 4 votes
# Retina, ~~28~~ ~~27~~ 21 bytes

Those are tabs, not spaces.

```
.
$&  $&
T`lL    p`Ll_`  .
```

**Try it online**

Thanks for the suggestions everyone.

# Answer
> 4 votes
# C, ~~87~~ 80

Pass a string as input to `f()` and the output is written to STDOUT. The string is not modified.

```
f(char*v){for(;*v;++v)putchar(*v),isalpha(*v)?putchar(*v-32+64*!islower(*v)):0;}

```

# Answer
> 4 votes
# sed, 30 bytes

29 bytes code + 1 byte parameter `-r`

```
s/([a-z])|([A-Z])/&\u\1\l\2/g

```

Usage:

```
echo -e 'bad\nNice\nT e S t\ns E t\n1!1!1st!\nn00b\n(e.g.)\nH3l|@!' |\
sed -r 's/([a-z])|([A-Z])/&\u\1\l\2/g'

```

# Answer
> 4 votes
# Ruby, ~~31+1=32~~ 30+1=31 bytes

With the `-p` flag, run

```
gsub(/(?<=(.))/){$1.swapcase!}

```

Takes advantage of the fact that `swapcase!` will return `nil` on anything but an ASCII letter, which translates to an empty string when returned out of the `gsub` block. @Jordan saved a byte by capturing the previous character in a look-behind.

# Answer
> 4 votes
# J, ~~31~~ 29 bytes

```
[:;]<@~."1@,.tolower,.toupper

```

## Explanation

```
[:;]<@~."1@,.tolower,.toupper  Input: s
                      toupper  Convert s to all uppercase
             tolower           Convert s to all lowercase
                    ,.         Join them as columns in a 2d array
   ]                           Identity function, get s
           ,.                  Prepend s as a column to the 2d array
      ~."1@                    Take the unique chars on each row
    <@                         Box them
[:;                            Unbox the list of boxes and join their contents and return

```

# Answer
> 4 votes
# Haskell, ~~121, 101, 85,~~ 82

```
import Data.Char
g n|isLower n=toUpper n|1<2=toLower n
(>>= \x->x:[g x|isAlpha x])

```

# Answer
> 4 votes
## Perl, 36 bytes (35 + `-n` flag)

```
s/[a-z]/$&.(ord$&<97?lc$&:uc$&)/ige

```

(`-p` tag needed)

(-2 bytes thanks to @Dom Hasting)

Short explanation:
`ord` returns the numeric value of a char. `ord(any lower case) >= 97`, and `ord(any upper case) <= 90)`.

Run with :

```
perl -pe 's/[a-z]/$&.(ord$&<97?lc$&:uc$&)/ige'

```

# Answer
> 4 votes
# R, 191 187 ~~168~~ ~~156~~ ~~98~~ 99 bytes

99 bytes due to improvements fro Giuseppe and MickyT.

```
paste0(x<-unlist(strsplit(readline(),"")),gsub("[^A-Za-z]","",chartr("a-zA-Z","A-Za-z",x)),collapse="")

```

# Answer
> 3 votes
# 05AB1E, 7 bytes

Code:

```
vyyš«Ù?

```

Explanation:

```
v       # For each in input.
 yyš    # Push y and y swapcased.
    «Ù  # Concatentate and uniquify.
      ? # Print without a newline.

```

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

# Answer
> 3 votes
## Pyke, ~~8~~ 6 bytes

```
FDl4+}

```

Try it here!

# Answer
> 3 votes
# , 21 bytes

Try it online!

Too many bytes...

```
Ó./°ò
Íá/°°
Îlg~lÎHògJ

```

# Answer
> 3 votes
## Actually, 8 bytes

```
`;Öo╔`MΣ

```

Try it online!

Explanation:

```
`;Öo╔`MΣ
`;Öo╔`M   for each character in input:
 ;          duplicate the character
  Ö         swap case
   o        append to original character
    ╔       remove duplicated characters
       Σ  concatenate

```

# Answer
> 3 votes
# MATL, ~~11~~ 9 bytes

```
tYov"@uv!

```

**Try it Online**

**Explanation**

```
        % Implicitly grab input as string
t       % Duplicate the input
Yo      % Swap case of all characters
v       % Vertically concatenate the original and swap-cased versions
"       % For each column (letter in the original)
  @u    % Compute the unique values (without sorting)
  v!    % Vertically concatenate with the existing output and transpose
        % Implicit end of for loop and implicit display

```

# Answer
> 3 votes
## Common Lisp (Lispworks), 262 bytes

```
(defun f(s)(let((b""))(dotimes(i(length s))(if(lower-case-p(elt s i))(progn #1=(setf b(concatenate 'string b(string #2=(elt s i))))(setf b(concatenate 'string b(string(char-upcase #2#)))))(progn #1#(setf b(concatenate 'string b(string(char-downcase #2#)))))))b))

```

ungolfed:

```
(defun f (s)
  (let ((b ""))
    (dotimes (i (length s))
      (if (lower-case-p (elt s i))
          (progn
           #1=(setf b (concatenate 'string b (string #2=(elt s i))))
           (setf b (concatenate 'string b (string (char-upcase #2#)))))
        (progn
          #1#
          (setf b (concatenate 'string b (string (char-downcase #2#)))))))
    b))

```

Usage:

```
CL-USER 1 > (f "abc")
"aAbBcC"

CL-USER 2 > (f "bad")
"bBaAdD"

```

# Answer
> 3 votes
## Perl, ~~28~~ ~~22~~ 21 bytes (20 + `-p` flag)

```
s/[a-z]/$&.$&^$"/ige

```

# Answer
> 3 votes
# Stax, ~~7~~ 6 bytes

Thanks to @recursive for a byte saved!

```
┤§ÆP♦■

```

Run and debug it at staxlang.xyz! (link is to unpacked version)

### Unpacked (7 bytes):

```
c:~\{um

```

### Explanation:

```
c:~\{um
c          Copy the top element of the stack (the input, in this case).
 :~        Switch case of each letter in the copy.
   \       Zip. This produces an array of two-character strings.
    { m    Map a block over this array of two-character strings.
     u       Get all unique elements.
           Implicit concatenate and print.

```

# Answer
> 2 votes
## Python, 59 bytes

```
lambda s:''.join((x,x+x.swapcase())[x.isalpha()]for x in s)

```

Edited to fix repeating non-alphabetic characters

# Answer
> 2 votes
# Julia, 40 bytes

```
!s=[print(c,isalpha(c)?c$' ':"")for c=s]

```

Try it online!

# Answer
> 2 votes
# C#, ~~82~~ 71 bytes

```
s=>string.Concat(s.Select(c=>c+(char.IsLetter(c)?(char)(c^32)+"":"")));

```

C# lambda where the input and the output are `string`. Try it online.

11 bytes thanks to @Lynn trick.

# Answer
> 2 votes
# PHP 4.1, 57 bytes

This code assumes access through a web server (Apache, for example), using the default configuration.

You can pass the string by sending the key `S` by any means (`POST`, `GET`, `COOKIE`, `SESSION`...).

```
<?for($i=0;$c=$S[$i++];)echo$c,ctype_alpha($c)?$c^' ':'';

```

# Answer
> 2 votes
# Java 8, ~~105~~ ~~104~~ 80 bytes

```
a->{for(char c:a)System.out.print(c+(c>64&c<91|c>96&c<123?(char)(c^32)+"":""));}

```

**Explanation:**

Try it here.

```
a->{                          // Method with character-array parameter and no return-type
  for(char c:a)               //  For each character in the input:
    System.out.print(c        //   Print the current character
     +(c>64&c<91|c>96&c<123?  //   And if it's a letter:
       (char)(c^32)+""        //    Print the letter again with reversed case
      :                       //   Else:
       ""));}                 //    Print nothing more

```

# Answer
> 2 votes
## T-SQL, 244

The byte total includes a one-byte string. Replace the example input string "Q" with the string you want to try.

```
DECLARE @I VARCHAR(MAX)='Q',@O VARCHAR(MAX)='',@ CHAR #:SELECT @=LEFT(@I,1),@O+=@+CASE WHEN @ LIKE'[A-Za-z]'COLLATE Thai_BIN THEN CASE WHEN ASCII(@)/13IN(5,6)THEN LOWER(@)ELSE UPPER(@)END ELSE''END,@I=STUFF(@I,1,1,'')IF LEN(@I)>0GOTO # PRINT @O

```

This script works in SQL Server 2008 R2, although you can try it in SQL Server 2016 here. This SQL works by iterating through the characters in the input string @I, checking each character using a short-named collation and ASCII codes. When one character is processed, the result is added to the output string @O and removed from @I.

# Answer
> 2 votes
# Japt v2.0a0, 8 bytes

```
r\lÈ+c^H

```

Try it

---

## Explanation

```
r            :Replace
 \l          :Regex /[a-z]/gi
   È         :Pass each match X through a function
    +        :  Append
    c        :  The charcode of X
     ^       :  Bitwise XORed
       H     :  With 32

```

# Answer
> 2 votes
# str, 6 bytes

```
d#S:#q

```

Try it online!

## Explanation

```
d#S:#q
          over each character:
d         duplicate
 #S       swapcase
   :      concatenate
    #q    uniq-ify string

```

# Answer
> 1 votes
## C, 62 bytes

Function that reads from `stdin` and writes to `stdout`:

```
f(c){while(c=getchar())printf(isalpha(c)?"%c%c":"%c",c,c^32);}

```

# Answer
> 1 votes
## Erlang, 106 bytes

```
f(S)->G=string,lists:flatten([case G:to_upper(C)==G:to_lower(C)of true->C;false->[C,C bxor 32]end||C<-S]).

```

Uses Lynn's XOR trick to toggle the case.

# Answer
> 1 votes
# Gema, 37 characters

```
<J>=$1@upcase{$1}
<K>=$1@downcase{$1}

```

Sample run:

```
bash-4.3$ gema '<J>=$1@upcase{$1};<K>=$1@downcase{$1}' <<< 'H3l|@!'
Hh3lL|@!

```

# Answer
> 1 votes
# PowerShell, 102 Bytes

```
-join([char[]]$args[0]|%{$_;if($_-cmatch'[A-Z]'){"$_".ToLower()}if($_-cmatch'[a-z]'){"$_".ToUpper()}})

```

Run the script with an argument like so:

```
PS C:\PretendDirectory> .\DupeCase.ps1 "Hello World ?!!1"
HheElLlLoO WwoOrRlLdD ?!!1

```

Ungolfed:

```
-join([char[]]$args[0] | % {
    $_
    if($_-cmatch'[A-Z]'){
        "$_".ToLower()
    }
    if($_-cmatch'[a-z]'){
        "$_".ToUpper()
    }
})

```

Explanation:

This script splits the argument from a string into a character array, and loops through the array. It returns a given character then, if it's an upper case letter between A and Z returns a lowercase version using the built in function, does the same for lowercase letters. To wrap up it joins the array into a single string.

# Answer
> 1 votes
# Rust, 250 bytes

```
fn main(){let(mut i,mut o)=(String::new(),String::new());std::io::stdin().read_line(&mut i);let b:&[u8]=i.trim().as_bytes();for x in b{o.push(*x as char);if*x>64&&*x<91{o.push((x+32)as char)}else if*x>96&&*x<123{o.push((x-32)as char)}}print!("{}",o)}

```

Ungolfed

```
fn main() {
    let (mut input_string, mut output_string) = (String::new(), String::new());
    std::io::stdin().read_line(&mut input_string);
    let bytes: &[u8] = input_string.trim().as_bytes();

    for x in bytes {
        output_string.push(*x as char);
        if *x > 64 && *x < 91 {
            //is_uppercase
            output_string.push((x + 32) as char);
        } else if *x > 96 && *x < 123 {
            //is_lowercase
            output_string.push((x - 32) as char);
        }
    }
    print!("{}", output_string);
}

```

This answer assumes the input only consists of ASCII characters. It uses comparisons and addition/subtraction instead of library functions as it is shorter.

# Answer
> 1 votes
# Add++, 100 bytes

```
D,g,@,O91 65r$e
D,l,@,O123 97r$eBn
D,w,@~,S
D,f,@~,€gB]VAbU€lB]GBcB+32€*B]VAbU€OB]GBcB+€CJABc€wB@B+J

```

Try it online!

This is annoyingly long. Let's compare this answer to the current shortest, Dennis' Jelly answer:

```
**ż***Œs****Q€***
```

Here, I've split it into three parts: **`ż`**, *`Œs`* and ***`Q€`***, highlighted to show the corresponding parts in the Add++ code, as so:

```
*D,g,@,O91 65r$e
D,l,@,O123 97r$eBn*
***D,w,@~,S***
D,f,@~,*€gB]VAbU€lB]GBcB+32€*B]VAbU€OB]GBcB+€CJ***ABc*€wB@B+J***

```

## How it works

```
		; A note on functions:
		; Each function returns the value on the top of the stack
		; A function has 'flags' that change its behaviour:
		;
		;	@	-	Specifies an argument to be taken
		;	~	-	Splats the arguments to the stack

D,u,@,		; Declare a monadic function 'u'
		; Example argument:	['I']
	O	; Ordinal;	STACK = [73]
	91 65r	; [65 ... 90];	STACK = [73 [65 66 ... 89 90]]
	$e	; Contains?	STACK = [1]

D,l,@,		; Declare a monadic function 'l'
		; Example argument:	['i']
	O	; Ordinal;	STACK = [105]
	123 97r	; [97 ... 122];	STACK = [105 [97 98 ... 121 122]]
	$e	; Contains?	STACK = [1]
	Bn	; Negate;	STACK = [-1]

D,w,@~,		; Declare a monadic function 'w'
		; Example argument:	[['N' 'n']]
	S	; Deduplicate;	STACK = [['N' 'n']]

D,f,@~,		; Declare a monadic function 'f'
		; Example argument:		['N' 'i' 'c' 'e' '!']
	€u	; Map 'u' over €ach;	STACK = [1 0 0 0 0]
	B]	; Wrap the stack;	STACK = [[1 0 0 0 0]]
	V	; Save;			STACK = []
	AbU	; Push argument;	STACK = ['N' 'i' 'c' 'e' '!']
	€l	; Map 'l' over €ach;	STACK = [0 -1 -1 -1 0]
	B]	; Wrap;			STACK = [[0 -1 -1 -1 0]]
	G	; Retrieve;		STACK = [[0 -1 -1 -1 0] [1 0 0 0 0]]
	BcB+	; Column sums;		STACK = [1 -1 -1 -1 0]
	32€*	; Multiply €ach by 32;	STACK = [32 -32 -32 -32 0]
	B]	; Wrap;			STACK = [[32 -32 -32 -32 0]]
	V	; Save;			STACK = []
	AbU€OB]	; Codepoints of input;	STACK = [[78 105 99 101 33]]
	G	; Retrieve;		STACK = [[78 105 99 101 33] [32 -32 -32 -32 0]]
	BcB+	; Column sums;		STACK = [110 73 67 69 33]
	€C	; Convert to chars;	STACK = ['n' 'I' 'C' 'E' '!']
	JABc	; Zip with argument;	STACK = [['n' 'N'] ['I' 'i'] ['C' 'c'] ['E' 'e'] ['!' '!']]
	€w	; Map 'w' over €ach;	STACK = [['n' 'N'] ['I' 'i'] ['C' 'c'] ['E' 'e'] ['!']]
	B@	; Reverse each;		STACK = [['N' 'n'] ['i' 'I'] ['c' 'C'] ['e' 'E'] ['!']]
	B+	; Sum each;		STACK = ['Nn' 'iI' 'cC' 'eE' '!']
	J	; Join;			STACK = ['NniIcCeE!']

```

# Answer
> 1 votes
# Kotlin, ~~87~~ 86 bytes

```
x->x.map{c->if(c.isLetter())"$c${(c.toInt()xor 32).toChar()}" else c}.joinToString("")

```

Try it online!

I wish Kotlin had a ternary operator, but it doesn't so I'm stuck with the more verbose if/else.

I feel like I can get this shorter if I can find a way to consolidate map{} and joinToString() in one call.

# Answer
> 1 votes
# SNOBOL4 (CSNOBOL4), 139 bytes

```
	U =&UCASE
	L =&LCASE
	I =INPUT
S	I LEN(1) . X REM . I	:F(O)
	X ANY(L U)	:S(D)F(A)
D	X =X REPLACE(X,L U,U L)
A	O =O X	:(S)
O	OUTPUT =O
END

```

Try it online!

The line `X ANY(L U) :S(D)F(A)` checks if any of `X` are `U`pper or `L`owercase, going to `D` if so or to `A` if not. Then `D` duplicates and swaps case, and `A` concatenates the results together, finally outputting once `I` has no characters.

# Answer
> 1 votes
# Vyxal `d`, 5 bytes

```
ƛǍ[N"

```

Try it Online!

```
ƛ     # Map to...
 Ǎ[   # If alphabetical
   N" # Pair with swap_case
      # (Otherwise leave it)
      # (d flag) Print deep sum of stack

```

# Answer
> 0 votes
# Java, 259 bytes

```
for (i=0;i<in.length();i++)
{
if(Character.isLowerCase(in.charAt(i))){
o=o+in.charAt(i)+Character.toUpperCase(in.charAt(i));}
else if(Character.isUpperCase(in.charAt(i))){o=o+in.charAt(i)+Character.toLowerCase(in.charAt(i));}
else {o=o+in.charAt(i);}}

```

# Answer
> 0 votes
# Yabasic, 133 bytes

A answer that takes input as a raw string and outputs to the STDOUT.

```
Line Input""S$
For i=1To Len(S$)
c$=Mid$(S$,i,1)
u$=Upper$(c$)
?c$;
If"@"<u$And u$<"["Then
If c$=u$Then?Lower$(c$);Else?u$;Fi
Fi
Next

```

Try it online!

# Answer
> 0 votes
# x86-16 machine code, IBM PC DOS, 26 bytes

**Binary:**

```
00000000: b401 cd21 3c61 7c08 3c7a 7ff4 24df eb06  ...!<a|.<z..$...
00000010: 3c41 7cec 0c20 cd29 ebe6                 <A|.. .)..

```

**Unassembled listing:**

```
        START:
B4 01       MOV  AH, 1                  ; DOS read char from STDIN
CD 21       INT  21H                    ; read char into AL
3C 61       CMP  AL, 'a'                ; is letter < ASCII 'a'?
7C 08       JL   UPPER                  ; if so, check if uppercase
3C 7A       CMP  AL, 'z'                ; is letter > ASCII 'z'?
7F F4       JG   START                  ; if so, don't repeat
24 DF       AND  AL, NOT ('A' XOR 'a')  ; uppercase it
EB 06       JMP  WRITE                  ; continue to display
        UPPER:
3C 41       CMP  AL, 'A'                ; is letter < ASCII 'Z'?
7C EC       JL   START                  ; if so, don't repeat either
0C 20       OR   AL, 'A' XOR 'a'        ; lowercase it
        WRITE:
CD 29       INT  29H                    ; write AL to screen
EB E6       JMP  START                  ; keep looping

```

Standalone IBM PC DOS executable. Input via `STDIN`, output to console.

**I/O:**

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


title: Fix Facebook exported JSON

text:
# Question
Title: Fix Facebook exported JSON
When you export data in JSON from Facebook, the multi-byte Unicode characters are broken. Example Unicode characters and their representation inside JSON:

```
'\u00c2\u00b0' : '°',
'\u00c3\u0081' : 'Á',
'\u00c3\u00a1' : 'á',
'\u00c3\u0089' : 'É',
'\u00c3\u00a9' : 'é',
'\u00c3\u00ad' : 'í',
'\u00c3\u00ba' : 'ú',
'\u00c3\u00bd' : 'ý',
'\u00c4\u008c' : 'Č',
'\u00c4\u008d' : 'č',
'\u00c4\u008f' : 'ď',
'\u00c4\u009b' : 'ě',
'\u00c5\u0098' : 'Ř',
'\u00c5\u0099' : 'ř',
'\u00c5\u00a0' : 'Š',
'\u00c5\u00a1' : 'š',
'\u00c5\u00af' : 'ů',
'\u00c5\u00be' : 'ž',

```

In the last example the bytes `0xC5` and `0xBE` are the UTF-8 encoding for `U+017E`. If those individual bytes are treated as unicode codepoints, they are `Å` and `¾`. So Facebook wrote each byte as an Unicode codepoint instead of handling multi-byte UTF-8 sequences appropriately.

This incorrect representation is used for every multi-byte UTF character. In short, to fix it, one needs to convert any string sequences like `\u00c5\u00be\u00c5\u0099` into byte data where first byte is `\xc5` and second byte is `\xbe`, third is `\xc5` and fourth is `\x99`, then read these bytes as a UTF-8 string. This can happen by direct manipulation of raw JSON text or by first parsing JSON, then do some magic with the *incorrectly* parsed strings or whatever comes to your mind.

Note that while `"\u00c5\u00be\u00c5\u0099"` is valid JSON, `"\xc5\xbe\xc5\x99"` is not. Also

A working Ruby and Python (not verified) solution can be seen in the referenced StackOverflow question at the bottom.

The task is to fix JSON generated by Facebook **with the shortest code**.

Winning criteria: code-golf - **the shortest code**.

As input you can take a file name, STDIN or the file text as a variable. The output should be on STDOUT, a file name or a string in a variable.

You don't have precise JSON input format (except that it is valid JSON), because exported data can be different. Also result should be valid JSON.

Solutions

* should accept as input both - pretty and non-pretty formatted JSON
* should handle properly 1,2,3 and 4 octets UTF character. With the assurance (if that matters) that any multi-byte UTF characters in the input will always be split into multiple `\u00##` sequences (i.e. you will never get `\u017E` or another sequence where first byte is non-zero).
* can output any - pretty formatted or non-pretty JSON
* doesn't matter whether characters in the output are represented by plain Unicode characters or escaped Unicode `\u017E`
* you are allowed to use any JSON parsing libraries

Example input:

```
{
   "name": "\u00e0\u00a4\u0085\u00e0\u00a4\u0082\u00e0\u00a4\u0095\u00e0\u00a4\u00bf\u00e0\u00a4\u00a4 G \u00e0\u00a4\u00b6\u00e0\u00a5\u0081\u00e0\u00a4\u0095\u00e0\u00a5\u008d\u00e0\u00a4\u00b2\u00e0\u00a4\u00be",
   "timestamp": 1599213799,
   "whatever": "someth\u0022\u00d0\u0092\u00d0\u00b8\u00d0\u00ba\u00d0\u00b8",
   "test": "\\u0041"
}

```

Example acceptable output:

```
{
  "name": "अंकित G शुक्ला",
  "timestamp": 1599213799,
  "whatever": "someth\"Вики",
  "test": "\\u0041"
}

```

Credit goes to original question https://stackoverflow.com/q/52747566/520567

# Answer
# Bash, 15 bytes

```
jq .|iconv -tl1

```

TIO version of `jq` requires the identity filter `.` but later versions can get away with `jq|iconv -tl1` for 13 bytes

Try it online!
> 1 votes

# Answer
# APL (Dyalog Unicode), 51 bytes

Anonymous prefix lambda taking a string as argument.

```
'(\\u00..)+'⎕R{'UTF-8'⎕UCS⎕UCS⎕JSON'"',⍵.Match,'"'}

```

Try it!

`'(\\u00..)+'⎕R{``}`**R**eplace any sequence of `\u00` followed by two other characters with:

`'"',⍵.Match,'"'` the match, surrounded by double quotes

`⎕JSON` interpret as JSON

`⎕UCS` convert to code points

`'UTF-8'⎕UCS` interpret as UTF-8 bytes
> 2 votes

# Answer
# Javascript, 79 bytes

```
f =

s=>s.replace(/(\\u00[8-f].)+|\\./g,c=>c[2]?decodeURI(c.replace(/.u00/g,'%')):c)

; function ch() { try { console.log(f(val.value)) } catch (e) { console.log(e); } } ch();
```

```
<textarea id="val" onchange="ch()">
{
   "name": "\u00e0\u00a4\u0085\u00e0\u00a4\u0082\u00e0\u00a4\u0095\u00e0\u00a4\u00bf\u00e0\u00a4\u00a4 G \u00e0\u00a4\u00b6\u00e0\u00a5\u0081\u00e0\u00a4\u0095\u00e0\u00a5\u008d\u00e0\u00a4\u00b2\u00e0\u00a4\u00be",
   "timestamp": 1599213799,
   "whatever": "someth\u0022\u00d0\u0092\u00d0\u00b8\u00d0\u00ba\u00d0\u00b8",
   "test": "\\u0041"
}
</textarea>
```

Still use `[8-f]` rather than `[^2]` in case `\u000a` exist
> 2 votes

# Answer
# JavaScript, 85 bytes

```
let d=s=>new TextDecoder().decode(new Uint8Array(s.split('').map(r=>r.charCodeAt())))

```

Test:

```
let s = "nejni\u00c5\u00be\u00c5\u00a1\u00c3\u00ad bod: 0 mnm Ben\u00c3\u00a1tky\n";
s = d(s);
console.log(s);

```

As I said in the other page \[1\], the Facebook data is valid UTF-8. However JavaScript doesnt use UTF-8, it uses UTF-16. So you have to convert from UTF-8 to UTF-16, to get the text to play nice with JavaScript.

1. https://stackoverflow.com/a/68237082
> 2 votes

# Answer
# Perl 5 (`-p`), 34 bytes

```
s/(?<!\\)\\u00([^2].)/chr hex$1/ge

```

Try it online!
> 1 votes

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

```
s=>JSON.stringify(eval('s='+s),(k,v)=>v===v+''?decodeURIComponent(escape(v)):v)

```

Try it online!

It only fix non printable ascii strings in JSON value, but not JSON keys. But as we accept JSON exported from Facebook which doesn't handle non ASCII correctly, we may safely assume keys won't contain such strings by design.
> 1 votes

# Answer
# Retina, ~~239~~ 213 bytes

```
/\\\\|\\u00[cde].(\\u00[89ab].)+/_(/\w/_(`[89a-f]
g$&
T`89l`d0
.
*
)4+`^(_*)\1(_)?
$1$#2
\\(0{7}(0{5})110(.{5})|0{12}1110(.{4})\\0{12}10(.{6}))\\0{12}10(.{6})
\u$2$3$4$5$6
/\d{4}/_(`1
01
+`10
011
C`1
T`d`l`..
b\B

```

Try it online! Retina isn't really designed for bit-twiddling. Outputs in escaped Unicode. Explanation:

```
/\\\\|\\u00[cde].(\\u00[89ab].)+/_(`

```

Run the rest of the script on pairs of backslashes and Unicode escapes of UTF-8 byte sequences. (The rest of the script leaves pairs of backslashes unchanged so this simply avoids treating them as the start of a Unicode escape.)

```
/\w/_(`[89a-f]
g$&
T`89l`d0
.
*
)4+`^(_*)\1(_)?
$1$#2

```

Change each letter into its binary equivalent. (This also changes `u` to `0000` but that doesn't matter a lot.)

```
\\(0{7}(0{5})110(.{5})|0{12}1110(.{4})\\0{12}10(.{6}))\\0{12}10(.{6})
\u$2$3$4$5$6

```

Shuffle the bits from the UTF-8 bytes into a single Unicode character.

```
/\d{4}/_(`

```

Run the rest of the script on each set of four bits.

```
1
01
+`10
011
C`1

```

Convert to decimal.

```
T`d`l`..

```

Change `10-15` to `ba-bf`.

```
b\B

```

Remove any leading `b`.

The previous version converted from hexadecimal to binary in a single substitution, but I was able to shave off 26 bytes by using a per-digit script:

```
/\w/_(`
)`

```

Run the script on each letter i.e. hexadecimal digit or `u`.

```
[89a-f]
g$&

```

Prepend `g` to the digits `a-f`.

```
T`89l`d0

```

Subtract 8 from the digits `8-f`, but turn `g` into 8 as compensation; also turn `u` into `0`.

```
.
*

```

Convert each digit to unary.

```
4+`^(_*)\1(_)?
$1$#2

```

Convert the unary to four bits of binary.
> 0 votes

---
Tags: code-golf, string, unicode
---


title: When will DST start / end

text:
# Question
Title: When will DST start / end
Daylight saving time (DST), is the practice of advancing clocks (typically by one hour) during warmer months so that darkness falls at a later clock time. The typical implementation of DST is to set clocks forward by one hour in the spring ("spring forward") and set clocks back by one hour in autumn ("fall back") to return to standard time. <sup>\[from Wikipedia\]</sup>

Write a program (full or function), takes no input from user, tells user when next Daylight Saving Time clock shift will happen in the following year for users' timezone (as configured on users' system / environment). Output should be the time when DST starts / ends in second precision, or output some other non-ambiguous text / value to tell user there will be no DST start / end happened in the following year.

## Rules

* This is , shortest codes in bytes win as usual;
* Your program should running on a platform which support at least 12 different timezone, and at least 2 of them have different DST shifts in the following year. So a program simply tells user "there is no DST" on a platform only support UTC would be disqualified.
* You may output in any reasonable format including (but not limited to) any one of following formats. Please also specify your output format in your post.
    + A Unix timestamp in second / millisecond;
    + Any human readable string in UTC or users timezone;
    + A built-in date time type value as return value of function;
* If your program output time in users' timezone, you should clarify whether the time outputted had DST counted. This can be done by including UTC offset / timezone name in your output, or specify it in your post (only when all outputs both use / not use DST.
* For timezone uses DST whole year, you program should tell user no DST start / end will happen;
* If your program running in some sandbox / emulator / virtual machine / docker environment which provides its own timezone config, you may use the timezone info configured in the runtime environment instead of user's operating system. But again, the environment should support multiple timezone with different DST to make your answer valid.

To keep this challenge simple, you may assume:

* The timezone will not change its offset to UTC due to other reasons;
* The offset to UTC of the timezone is an integer in seconds (both before / after DST);
* The timezone will start / end its DST when Unix timestamp (as in second) is an integer;
* The timezone will either start / end its DST in the following year or it will never start / end its DST (No DST applied or use DST whole year);

## Example Outputs

Following example outputs assume user is running your program in 2021-06-01T00:00:00Z. Your program may need to have different behavior as time past.

```
America/Anchorage
* 1636279200
* 2021-11-07T10:00:00.000Z
* Sun Nov 07 2021 01:00:00 GMT-0900 (Alaska Standard Time)
* Sun Nov 07 2021 02:00:00 GMT-0800 (Alaska Daylight Time)

Australia/Adelaide
* 1633192200
* 2021-10-02T16:30:00.000Z
* Sun Oct 03 2021 03:00:00 GMT+1030 (Australian Central Daylight Time)
* Sun Oct 03 2021 02:00:00 GMT+0930 (Australian Central Standard Time)

Asia/Singapore
* No DST

```

# Answer
# APL (Dyalog Unicode), ~~105~~ 103 bytes (SBCS)

-2 by throwing an error if the current location has no upcoming DST

Full program. Prints DateTime in local format (includes seconds), with the special value of midnight on the new-year of year 1 (in the past, so cannot be the real upcoming change time) indicating that there is no upcoming DST change.

```
⎕USING←'System'
DateTime.Now(⊃+.>↓⊢)∊(TimeZone.CurrentTimeZone.GetDaylightChanges¨0 1+⊃⎕TS).(Start End)

```

`⎕USING←'System'` use .NET's standard core library

`(``).(Start End)` get the Start and End times for each DST period in:

`⎕TS` the current **T**ime**S**tamp as a 7-element list: `(Y,M,D,h,m,s,ms)`

pick the first element (the year); 2021

`0 1` add zero and one; `(2021,2022)`

`TimeZone.CurrentTimeZone.GetDaylightChanges¨` for each year, get its DST period

**e**nlist (flatten from pair of pairs, to 4-element list)

`DateTime.Now(``)` with the current time as left argument, apply the following tacit infix function:

drop the following number of elements from that:

`+.>` the sum of the 4-element Boolean list indicating the change times that the current time is greater than

pick the first remaining change time

If there are no upcoming DST changes, then all Start and End times are midnight on the new-year of year 1. The current time is greater than all of these values, so we end up with no elements. Trying to pick the first one errors with a NONCE ERROR.

Trial run from the UK currently gives:

```
31/10/2021 02:00:00

```
> 5 votes

# Answer
# PHP, ~~72~~ 70 bytes

```
for($d=date(I,$r=$t=time());$d==date(I,++$t);)$t-$r<4e7?:die();echo$t;

```

Try it online! for `'America/Anchorage'`, replace the timezone in the header to test another one

This time I'm proud of good ol' PHP! Will output the timestamp of the shift if there is one, or terminates with an empty string if there is no shift.

* `date('I',timestamp)` will return `1` if DST is on or `0` if off
* bruteforces for each second until the value changes
* if the checked timestamp minus initial timestamp reaches 40000000 (a regular year is 31536000 seconds) it terminates

**EDIT:** saved 2 bytes by pre-incrementing `$t`
> 4 votes

# Answer
# Python 3, 183 bytes

```
from datetime import*
import pytz,time
y=k=datetime.now().replace(microsecond=0)
f=timedelta(seconds=1)
while pytz.timezone(time.tzname[0]).localize(y+f).dst():y+=f
if y!=k:print(y+f)

```

Try it online!

-63 thanks to @ovs

Test for America Anchorage!

Horrendously slow, but works.

It repeatdly adds 1 second to current date, until it is DST or not.

If the current date is not DST, it exists with empty output.

I tested this by changing timezone (third line, function parameter) and dates (sixth and fifth line). It worked like a charm! The test timezone was Anchorage, and test date was Nov 1, 2021 (Changed date only for faster speed)
> 1 votes

# Answer
# Go, 168 bytes

```
package main
import."time"
func main(){a:=Now()
_,b:=a.Zone()
for c:=a;c.Unix()<a.AddDate(1,0,0).Unix();c=c.Add(Minute){_,d:=c.Zone()
if d!=b{print(c.String())
break}}}

```
> 1 votes

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

```
for(d=()=>new Date,l=console.log,t=1000,a=d(),b=d(),c=0,i=x=>x.setSeconds(x.getSeconds()+1);(a-d()<32*t**3||l("no DST"))&&(c===t||!c||l(r));i(a),c=a-b,r=~~((+b+t)/t),i(b));

```

Try it online!

This increments a `Date` by 1 *wall clock time* second until it detects that the incremented value is not 1 *Unix time* second apart from the original one. In such case it prints the Unix timestamp (seconds, integer) of the change. If no gap are found, prints `no DST`.
> 0 votes

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


# Question
Title: Odds that a string of N digits contains two or more of the same
I have to fill in 2fa codes all day. They're 6-digit strings. One day I noticed that not once did any of these codes contain 6 unique digits, like 198532 There was always at least one double, like 198539 (here it's 9).

For any given uniformly random string of \\$N\\$ digits in the set \\$\\{0,1,2,3,4,5,6,7,8,9\\}\\$, what is the odds for this happening?

Your input is a single positive integer, \\$N\\$, with \\$N \le 10\\$

Your output is a number between 0 and 1, which is the probability that a string with \\$N\\$ digits has at least one repetition.

The shortest code wins

# Answer
# Haskell, 30 bytes

```
f n=1-product[1,0.9..1.1-n/10]

```

Try it online!

If we pick, for example, 4 digits sequentially, then the odds of each one being "fresh" is

* \\$10/10\\$ for the first digit
* \\$9/10\\$ for the second digit (it must ≠ the first digit)
* \\$8/10\\$ for the third digit (it must ≠ the first and second digits)
* \\$7/10\\$ for the fourth digit (it must ≠ the first, second and third digits)

so the probability of getting 4 unique digits is \\$\frac{10}{10}\cdot\frac{9}{10}\cdot\frac{8}{10}\cdot\frac{7}{10}\\$, and the probability of *not* getting 4 unique digits (i.e. some repetition) is one minus that.

In general the answer is $$1 - \prod\_{k=0}^{n-1} \frac{10-k}{10}.$$

(Though not required, this formula is also valid for \\$N \geq 11\\$, where the answer is \\$1\\$. In that case, this product contains a factor 0, representing the fact that we can't possibly pick an eleventh digit that is different from all ten digits that exist.)
> 8 votes

# Answer
# Jelly, ~~7~~ 6 bytes

Uses the same formula as Lynn's Haskell answer.

-1 byte thanks to Dominic van Essen!

```
Ḷ÷⁵CPC

```

Try it online!

```
Ḷ         lowered range:                    [0, 1, ..., n-1]
 ÷⁵       divide each value by 10           [0/10, 1/10, ..., (n-1)/10]
   C      complement, subtract each from 1  [10/10, 9/10, ..., (11-n)/10]
    P     take the product of all values    (10/10)*(9/10)* ... *(11-n)/10
     C    complement                        1 - (10/10)*(9/10)* ... *(11-n)/10

```
> 5 votes

# Answer
# Vyxal, 9 bytes

```
₀~εrΠ?↵/⌐

```

Try it Online!

Me and the boys on our way to port Lynn's Haskell answer be like.

## Explained

```
₀~εrΠ?↵/⌐
₀~εr       # the range (10 - input, 10]
    Π      # the product of that
       /   # divided by
     ?↵    # 10 ** input
        ⌐  # 1 - that

```
> 4 votes

# Answer
# Japt, 10 bytes

```
ÇnA /AÃ×n1

```

Try it

```
ÇnA /AÃ×n1     :Implicit input of integer U
Ç              :Map the range [0,U]
 n             :  Subtract from
  A            :  10
    /A         :  Divide by 10
      Ã        :End map
       ×       :Reduce by multiplication
        n1     :Subtract from 1

```
> 1 votes

# Answer
# Wolfram Language (Mathematica), 19 bytes

```
1-10!/10^#/(10-#)!&

```

Try it online!
> 1 votes

# Answer
# , 13 bytes

```
1-!*(!%^~)&10

```

Try it online!

* 1 minus `1-` the factorial of the input `!` times `*`...
* `(!%^~)&10` the input choose 10 divided by 10 raised to the input.

Or, equivalenly:

```
1-!*!&10%10&^

```
> 1 votes

# Answer
# Python 3, ~~39~~ 38 bytes

```
f=lambda x:x and(x-1-f(x-1)*(x-11))/10

```

Try it online!

* Thanks to @ovs for -1
> 1 votes

# Answer
# 05AB1E, 8 bytes

```
Tses°/1α

```

Try it online!

Uses a different formula from the Wikipedia page:

$$ 1-{\_{365}P\_{n} \over 10^n} $$

```
Ts        # push 10 and swap implicit input n to the front
  e       # number of permutations
   s°     # 10 ** n
     /    # divide: nPr(10, n) / 10 ** n
      1α  # absolute difference from 1

```
> 1 votes

# Answer
# APL(Dyalog Unicode), ~~13~~ 12 bytes SBCS

Implements the same formula as Lynn's Haskell answer.

```
1-(×/1-.1×⍳)

```

Try it on APLgolf!

And 15 bytes with \\$1-{1\over 10^n} {10!\over (10-n)!}\\$:

```
10∘(1-*÷⍨⊣÷⍥!-)

```

Try it on APLgolf!
> 1 votes

# Answer
# Charcoal, 11 bytes

```
Ｉ⁻¹ΠＥＮ∕⁻χιχ

```

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

```
     Ｎ      Input integer
    Ｅ       Map over implicit range
        χ   Predefined variable `10`
       ⁻    Subtract
         ι  Current index
      ∕     Divided by
          χ Predefined variable `10`
   Π        Take the product
 ⁻¹         Subtract from 1
Ｉ           Cast to string
            Implicitly print

```

Alternative approach, also 11 bytes:

```
Ｉ⁻¹Π∕⁻χ…⁰Ｎχ

```

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

```
       …⁰Ｎ  Range from 0 to input integer
     ⁻χ     Vectorised subtract from 10
    ∕     χ Vectorised divide by 10
Ｉ⁻¹Π        Cast product subtracted from 1 to string

```
> 0 votes

---
Tags: code-golf, math, arithmetic, probability-theory
---


title: Nearest possible expressed number

text:
# Question
Title: Nearest possible expressed number
A screen consists of some LED segments like such:

The screen can be split into several(maybe one) component. Each component is a segment like above, with varying lengths. These components can be used to display any amount, including 0, of digits, as long as the component is large enough.

Every digit except 1 needs two columns of the grid to be displayed. These columns are not allowed to overlap (even a number like 67 still needs 4 columns and does not fit into a n=2 component). The digit 1 is slim, so it only needs one column.

Therefore, a number fits into a component, iff `2 * Length - (Amount of 1's) <= n+1`.

For example, the number 14617 can be displayed in a screen with the component lengths `[0, 1, 1, 2, 0]`:

Given the n's of each component and a positive integer, find the nearest positive integer that can be expressed in the screen. If multiple number are nearest, you can output either.

Shortest code wins.

# Examples

```
[1],3 => 3
[1],16 => 11
[0,0],3 => 1
[0,0],6 => 1 or 11
[2],14 => 14
[2],24 => 21
[3],999999999 => 1111
[1,0,0,0,0,0,1],23 => 23
[0,3],100 => 100

```

# Answer
> 3 votes
# Ruby, ~~163~~ 143 bytes

```
->r,i{g=->s,r{*t,c=s;d,*q=r;n=c==1?1:2;!c||d&&(n<d+2?g[t,[d-n,*q]]:g[s,q])}
h=->n,r{g[n.digits,r]&&p(n)}
a=0;until h[i+a,r]||h[i-a,r];a+=1;end}

```

Try it online!

*-20 bytes thanks to @Kirill L.*

My first golf in Ruby. I'm sure that it can be even shorter, but I didn't find anything.

### Explanation

`g` (takes an array of chars, representing the number, and the displays) checks if a given number fits into the given display. `f` then checks all numbers, starting with the given integer, then i+1, i-1, i+2, ..., and outputs the first number that fits.

# Answer
> 2 votes
# Jelly, 29 bytes

```
n1‘S>
⁵*ḶD“”ṭçÐḟ
‘Ç€ŒpF€ḌạÐṂḢ

```

Try it online!

# Answer
> 1 votes
# Jelly, 34 bytes

```
‘Ø½ṗⱮẎS=¥ƇƲ€ŒpF€ị⁵Ḷṭ1¤Œp€ŒP€€ḌFạÞḢ

```

Try it online!

-2 bytes thanks to caird coinheringaahing

This is absolutely horrible. I won't be surprised if someone can halve my bytecount. I spent a decent bit of time on it; not too much - I'll keep golfing this but I think it's at least close to worth posting.

# Answer
> 1 votes
# Python 3, 190 181 215 175 bytes

```
def f(n,i,m=["0"]):
 for g in n:m=[u+x[1:]for u in m for x in[str(d)for d in range(0,12*i)if sum(-~(b!="1")for b in str(d))<g+3]]
 return min(map(int,m),key=lambda v:abs(v-i))

```

Generates a roughly bounded list of possible ints for each segment, zero pads, tests each to see if they fit, permutates all the sequences for each segment, then finds closest int match to the input.

Thanks mypetlion and l4m2 for improving my swing!

Try it online!

# Answer
> 0 votes
# Common Lisp, 337 bytes

```
(defun C(a b &aux r)(dolist(x a)(dolist(y b)(push(concatenate'string x y)r)))r)(defun P(n &aux r)(case n(0'("""1"))(1'("0""1""2""3""4""5""6""7""8""9""11"""))(t(dotimes(i n r)(setf r`(,@r,@(C(P i)(P(- n i 1)))))))))(defun F (i x)(- x(reduce'min(mapcar(lambda(p)(-(or(parse-integer p :junk-allowed t)0)x))(reduce'C(mapcar'P i))):key'abs)))

```

Try it online!

Gets all possible numbers that can be represented by the given component list `i`, finds the smallest distance from the numbers to input `x` and returns `x - distance`.

`F` is the main function, `C` concatenates combinations, and `P` recursively gets the possible digits for a component of size `n`.

Testing included in TIO. This can ~~probably~~ maybe be reduced by 50-75 or so bytes as is, mainly the double `dotimes` in `C`, the disgusting string hell in `P`, and the `:junk-allowed t` in `parse-integer` used by `F`. The `junk-allowed t` was needed for the case where the string is empty. I at some point tried to replace all instances of `dolist`, `reduce`, `defun`, and `mapcar` with `l`, `d`, `e`, `m` respectively but the resulting code ended up being larger at 404 bytes but someone might be able to make use of it so I'm still putting it here:

```
(let((f(copy-tree'(progn(d C(a b &aux r)(l(x a)(l(y b)(push(concatenate'string x y)r)))r)(d P(n &aux r)(case n(0'("""1"))(1'("0""1""2""3""4""5""6""7""8""9""11"""))(t(dotimes(i n r)(setf r`(,@r,@(C(P i)(P(- n i 1)))))))))(d F (i x)(- x(e'min(m(lambda(p)(-(or(parse-integer p :junk-allowed t)0)x))(e'C(m'P i))):key'abs)))))))(mapc(lambda(x y)(nsubst x y f))'(dolist defun reduce mapcar)'(l d e m))(eval f))

```

Try it online!

The code is essentially wrapped in

```
(let ((f (copy-tree '(progn CODE))))
  (mapc (lambda (x y) (nsubst x y f))
        '(THINGS TO BE REPLACED)
        '(THINGS TO REPLACE THEM WITH))
  (eval f))

```

# Answer
> 0 votes
# , ~~148~~ 147 bytes

```
function(n,m,g=function(n,s=nchar(n),d=2-!n%/%10^(0:s)%%10-1){for(i in m)while(s&&(i=i-d[s])>-2)s=s-1;n*!s}){while(!(r=max(g(n-F),g(n+F))))F=F+1;r}

```

Try it online!

---
Tags: code-golf
---


title: Approx how many search results

text:
# Question
Title: Approx how many search results
When one performs a search query using Google, one of the first things you see is an approximation of how many results were found. Today, you'll be simulating this in as few bytes as possible.

## Input

A short string of length at most 10 with characters from a-z.

## Output

The approx count that Google reports for the number of hits.

## Test Cases

```
query string -> approximate number of results
fish -> 2340000000
quantock -> 1390000
codegolf -> 891000
google -> 9340000000
e -> 22500000000
bzoea -> 34700
zoea -> 529000

```

## Extra Clarifications

You may use any regional Google you like.

You can either scrape the page resulting from the search query, or interface with Google APIs.

Search queries are usually in the format `https://www.google.com/query?q=<query>`

This is , so the shortest code in bytes wins

# Answer
> 6 votes
# Python 3, ~~158~~ ~~137~~ 131 bytes

Using `requests` module and a doctored User-Agent header. Still looking for a shorter functioning UA header.

```
lambda q:get(f'http://goo.gl/search/{q}',headers={'User-Agent':'Firefox/8'}).text.split('out ')[1].split()[0]
from requests import*

```

Try it online!

# Answer
> 4 votes
# Bash + curl + grep, 61

```
curl -LA Firefox/8 goo.gl/search?$1|grep -Po "bout \K[0-9,]*"

```

This will output `curl`'s progress indicator to stderr. If you want to suppress that, change the `-LA` to `-sLA`.

# Answer
> 3 votes
# Applescript, 389

This is perhaps the most inefficient golfing language, but it is still fun to golf in:

```
open location"http://goo.gl/search?"&(display dialog""default answer"")'s text returned
repeat with l in{"a","c"}
delay 2
tell application"System Events"to keystroke l using command down
end
delay 1
set d to the clipboard
set Applescript's«class txdl»to" "
set c to d's text items
set p to""
repeat with w in c
considering case
if p contains"About"then display alert w
end
set p to w
end

```

# Answer
> 2 votes
# PowerShell, ~~64~~ ~~61~~ ~~56~~ 75 bytes

```
iwr goo.gl/search?$args -User Firefox/8|sls '(?<=">About )[\d,]*'|% M*|% V*

```

Try it online!

The correct solution is `parseHtml` method and `xPath` query `div[@id="result-stats"]` of course. But we are in CodeGolf! So let's look for a shorter code :)

The CodeGolf solution is based on the following:

* the search string contains chars `"` and `>`
* this chars are regular for `regex` and special for `Html`
* any Html document should to escape this chars in `value` attributes and in the inner text - `"` and `<`
* so we can found the string `">About`  only in a Raw content of a Html page.

---

Less golfed:

```
Invoke-WebRequest goo.gl/search?$args -UserAgent Firefox/8|
    Select-String '(?<=">About )[\d,]*'|% Matches|% Value

```

The script assumes the English locale is default.

The script returns a string same format as Google itself, So comma as thousand separators is fine. See comment from author `Anush`.

`iwr` is the alias for Invoke-WebRequest. `M*` is shortcut for the `Matches` method and `V*` is shortcut for the `Value` method.

---

* Thanks @MarcMush for the brilliant question!
* Thanks to mhawke for `Mock for TIO` idea.

# Answer
> 1 votes
# Go, 260 bytes

Most answers on this page are now wrong, as Google no longer accepts `Firefox/8` as a valid User-Agent:

```
package main
import(."io"
."net/http"
."regexp")
func main(){e,_:=NewRequest("GET","http://goo.gl/search?codegolf",nil)
e.Header.Set("User-Agent","Firefox/51")
s,_:=new(Client).Do(e)
b,_:=ReadAll(s.Body)
print(string(MustCompile(`About \S+ results`).Find(b)))}

```

# Answer
> 0 votes
# 05AB1E, ~~25~~ ~~26~~ 29 bytes

```
’Š¹.ŒŒ/€±?q=ÿ’žZì.w”€«”¡1è#1è

```

+1 byte as bug-fix if the input is `about`.
+3 bytes, because it apparently doesn't work without the `www.`

Outputs the result in the same format as on the Google page itself (so with dots for thousand separators). If it should be returned as an integer, an additional trailing `þ` can be added to the program.

Builtin `.w` (read data from an URL) is disabled on TIO, so the TIO's are split into two parts:

Creating the Google search URL based on the input:

```
’Š¹.ŒŒ/€±?q=ÿ’žZì

```

Try it online.

Get the amount of results from the Google page:

```
”€«”¡1è#1è

```

Try it online.
The input is only a small portion of the entire google page, since the TIO-link would become over 30,000 characters long with the entire page.. :/ To test any google search page with this part of the program, follow these steps:

1. Ctrl+U (Show page source)
2. Copy-paste everything into the second TIO's input-field
3. Surround it with leading and trailing `"""` (for multi-line string inputs)

**Explanation:**

```
’Š¹.ŒŒ/€±?q=ÿ’    # Push dictionary string "google.com/search?q=ÿ"
                  # where the `ÿ` is automatically filled with the (implicit) input
  žZ              # Push builtin string "http://www."
    ì             # Prepend it in front of the string
     .w           # Go to this URL, and get its page as string
       ”€«”       # Push titlecased dictionary string "About"
           ¡      # Split the google page on that titlecased word
            1è    # Only leave the second part (0-based 1st)
              #   # Split that on spaces
               1è # And index into the second part (0-based 1st) to get the amount
                  # (after which the result is output implicitly)

```

See this 05AB1E tips (section *How to use the dictionary?*) to understand why `’Š¹.ŒŒ/€±?q=ÿ’` is `"google.com/search?q=ÿ"` and `”€«”` is `"About"`.

---
Tags: code-golf, parsing, internet
---