# Question
Title: Words with Easy Letters in a Word Search
## Introduction:

Apparently I keep coming up with word search related challenges lately. :)
When I do the word search in the Dutch news paper, some words are very easy to find because they contain letters that aren't too common in Dutch words, like `x` or `q`. So although I usually look for the first letter or prefix of a word I'm searching, in some cases looking for these letters in the grid is faster to find the words.

#### Brief explanation of what a word search is:

*† Although it's not too relevant for the actual challenge this time.*
In a word search you'll be given a grid of letters and a list of words. The idea is to cross off the words from the list in the grid. The words can be in eight different directions: horizontally from left-to-right or right-to-left; vertically from top-to-bottom or bottom-to-top; diagonally from the topleft-to-bottomright or bottomright-to-topleft; or anti-diagonally from the topright-to-bottomleft or bottomleft-to-topright.

## Challenge:

Given a grid of letters and a list of words, output for each word the lowest count of the letters within this word within the grid.

**For example:**

```
Grid:
REKNA
TAXIJ
RAREN
ATAEI
YCYAN

Words:
AIR
ANKER
EAT
CYAN
NINJA
RARE
TAXI
TRAY
XRAY
YEN

```

For `AIR` we see the following frequency of the letters in the grid: `[A:6, I:2, R:3]`, of which the lowest is `I:2`. Doing something similar for the other words, the result would be `AIR:2, ANKER:1, EAT:2, CYAN:1, NINJA:1, RARE:3, TAXI:1, TRAY:2, XRAY:1, YEN:2`.

## Challenge rules:

* You can take the inputs in any reasonable format. Could be from STDIN input-lines; as a list of lines; a matrix of characters; as codepoint-integers; etc.
* You can optionally take the dimensions of the grid as additional input.
* The output can be in any reasonable format as well. Can be a key-value map of word + integer as above, but can also just be a list of the integers (e.g. `[2,1,2,1,1,3,1,2,1,2]` for the example above.
* You can assume the list of words are always in alphabetical order.
* The list of words is guaranteed to contain at least one word, and all words are guaranteed to be present in the given grid.
* All words are guaranteed to have at least two letters.
* You can assume each word is only once in the grid.

## General rules:

* This is , so the shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* Standard rules apply for your answer with default I/O rules, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
* Default Loopholes are forbidden.
* If possible, please add a link with a test for your code (e.g. TIO).
* Also, adding an explanation for your answer is highly recommended.

## Test cases:

Outputs are displayed as integer-lists.

```
Inputs:
REKNA
TAXIJ
RAREN
ATAEI
YCYAN

AIR
ANKER
EAT
CYAN
NINJA
RARE
TAXI
TRAY
XRAY
YEN

Output:
[2,1,2,1,1,3,1,2,1,2]

```

---

```
Inputs:
ABCD
EFGH
IJKL
MNOP

AFK
BCD
FC
PONM

Output:
[1,1,1,1]

```

---

```
Inputs:
WVERTICALL
ROOAFFLSAB
ACRILIATOA
NDODKONWDC
DRKESOODDK
OEEPZEGLIW
MSIIHOAERA
ALRKRRIRER
KODIDEDRCD
HELWSLEUTH

BACKWARD
DIAGONAL
FIND
HORIZONTAL
RANDOM
SEEK
SLEUTH
VERTICAL
WIKIPEDIA
WORDSEARCH

Output:
[1,1,2,1,1,4,1,1,1,3]

```

---

```
Inputs:
JLIBPNZQOAJD
KBFAMZSBEARO
OAKTMICECTQG
YLLSHOEDAOGU
SLHCOWZBTYAH
MHANDSAOISLA
TOPIFYPYAGJT
EZTBELTEATAZ

BALL
BAT
BEAR
BELT
BOY
CAT
COW
DOG
GAL
HAND
HAT
MICE
SHOE
TOP
TOYS
ZAP

Output:
[5,5,1,5,4,3,1,3,3,2,4,3,4,3,4,3]

```

# Answer
> 8 votes
# , 43 bytes

```
\(w,g,`*`=sapply)w*\(i)min(i*\(j)sum(!g-j))
```

Attempt This Online!

Since we are allowed to input integer codepoints, here it goes. Takes input as a list of codepoint vectors for words, and codepoint matrix for grid.

# Answer
> 5 votes
# Python 3, 42 bytes

```
lambda g,W:[min(map(g.count,w))for w in W]

```

Try it online!

Takes the grid as a string, with any non-letter separator, and an iterable of strings.

# Answer
> 5 votes
# Haskell, 41 bytes

```
g#d=[minimum[sum[1|x<-g,x==c]|c<-w]|w<-d]
```

Attempt This Online!

-3 bytes thanks to @ovs

# Answer
> 4 votes
# Haskell, ~~71 64~~ 51 bytes

```
g#l=[[x|x<-[1..],c<-w,x==sum[1|e<-g,e==c]]!!0|w<-l]

```

Try it online!

Full list comprehension solution

* saved 13 Bytes thanks to @Unrelated String

*Old 71 bytes*

```
g#w=sum.f<$>((\y->[1|l<-g,l==y])<$>)<$>w
f(h:t)|h<f t=h|1>0=f t
f[]=[2]

```

Try it online!

`g#w` takes `g` grid as a string with newlines and `w` words as a list of words.

Each word is transformed into a list of lists of 1's by `g` before using `f` to select the shortest(lexicographically) character.

`f` has an edge case = *\[2\]* for the end of the list which is always greater.
Then sum each selection to obtain the output

# Answer
> 4 votes
# 05AB1E, 3 bytes

```
ε¢W

```

**Try it online!**

### How?

Note: Uses the current interpretation of https://codegolf.meta.stackexchange.com/a/2216/52210 that seems to be being used, that not only may a string be provided as a list of characters but that it may be provided as a list of single-character strings.

```
ε¢W - inputs are: words (list of lists of strings of length one);
                  wordsearch (space separated string)
ε   - for each word:
 ¢  -   count occurrences of each length-one-string in the wordsearch
  W -   minimum

```

---

Original 4 that does not use a list of lists of strings for the words...

```
ε€¢W

```

Try it online!

### How?

```
ε€¢W - inputs are: words (list of strings); wordsearch (space separated string)
ε    - for each word:
 €   -   for each letter:
  ¢  -     count occurrences in the wordsearch
   W -   minimum

```

---

* Taking the words as a list of lists of strings would work, but seems like pre-processing rather than loose IO to me.

# Answer
> 4 votes
# JavaScript (V8), ~~73~~ ~~69~~ 63 bytes

```
g=>l=>l.map(w=>Math.min(...[...w].map(c=>g.split(c).length-1)))

```

Try it online!

*-4 bytes thanks to emanresu A*

*-6 bytes thanks to Matthew Jensen*

# JavaScript (Node.js) \+ Ramda, 56 bytes

```
g=>d=>d.map(w=>R.min(...R.map(c=>R.count(x=>x==c,g),w)))

```

Try it online!

# JavaScript + Sugar, 52 bytes

```
g=>d=>d.map(w=>[...w].map(c=>[...g].count(c)).min())

```

```
Sugar.extend();

f=g=>d=>d.map(w=>[...w].map(c=>[...g].count(c)).min())

console.log(f("REKNA,TAXIJ,RAREN,ATAEI,YCYAN")(["AIR", "ANKER", "EAT", "CYAN", "NINJA", "RARE", "TAXI", "TRAY", "XRAY", "YEN"]).join(', '));
console.log(
  f("JLIBPNZQOAJD,KBFAMZSBEARO,OAKTMICECTQG,YLLSHOEDAOGU,SLHCOWZBTYAH,MHANDSAOISLA,TOPIFYPYAGJT,EZTBELTEATAZ")
  (["BALL","BAT","BEAR","BELT","BOY","CAT","COW","DOG","GAL","HAND","HAT","MICE","SHOE","TOP","TOYS","ZAP"])
  .join(', ')
);
```

```
<script src="https://cdnjs.cloudflare.com/ajax/libs/sugar/2.0.6/sugar.min.js"></script>
```

# Answer
> 3 votes
# Ruby, 46 bytes

```
->g,w{w.map{|x|x.chars.map{|c|g.count c}.min}}

```

Try it online!

# Answer
> 3 votes
# Vyxal `r`, 6 bytes

```
ƛƛ⁰O;g

```

Try it Online!

## Explained

```
ƛƛ⁰O;g
ƛ       # Map the first input
 ƛ  ;   # Map for each letter in the word
  ⁰O    # Count how many times the letter appears in the second input
     g  # Get the minimum

```

# Vyxal `r`, 5 bytes

### taking words as list of list of characters instead of list of strings

```
ƛ⁰vOg

```

Try it Online!

# Answer
> 2 votes
# Jelly, 5 bytes

```
ċⱮⱮṂ€
```

Attempt This Online!

Hmmm.

# Answer
> 2 votes
# Factor, 38 bytes

```
[ [ counts values infimum ] with map ]
```

Attempt This Online!

# Answer
> 2 votes
# Husk, 5 bytes

```
mo▼m#

```

Try it online!

```
m           # map over each word in second arg
 o          # compose 2 functions:
  ▼         #  get minimum of
   m        #  mapping
    #       #  number of occurrences in first arg

```

# Answer
> 2 votes
# Wolfram Language (Mathematica), 22 bytes

```
Min/@Map@Counts@#/@#2&

```

Try it online!

Input `[grid, {words...}]`, where both the grid and words are 1d lists of characters.

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

```
{&/'(#'=,/x)y}

```

Try it online!

Takes the grid of letters as `x` (the first arg), and the list of words as `y` (the second arg).

* `(#'=,/x)`
    + `,/x` flatten the grid of letters into a single string
    + `#'=` build a dictionary mapping the unique letters to the number of times they occur
* `(...)y` index into this with the list of words
* `&/'` get the number of times the least common letter in each word appears in the grid (and implicitly return)

# Answer
> 2 votes
# Thunno, \\$ 6 \log\_{256}(96) \approx \\$ 4.94 bytes

```
ez1scm

```

Attempt This Online!

#### Explanation

```
ez1scm # Implicit input
e      # Map:
   sc  #  Count of each in
 z1    #  Second input
     m #  Minimum
       # Implicit output

```

# Answer
> 1 votes
# Charcoal, 17 bytes

```
ＷＳ≔⁺ωιωＷＳ⟦Ｉ⌊Ｅι№ωκ

```

Try it online! Link is to verbose version of code. Takes input as two newline-separated lists of newline-terminated strings. Explanation:

```
ＷＳ≔⁺ωιω

```

Input and flatten the grid.

```
ＷＳ

```

For each word in the list...

```
⟦Ｉ⌊Ｅι№ωκ

```

... output the minimum count of all of its letters in the flattened string.

Save 6 bytes by using a more awkward input format:

```
ＩＥη⌊Ｅι№⪫θωλ

```

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

```
  η         Word list
 Ｅ          Map over words
     ι      Current word
    Ｅ       Map over letters
      №     Count of
          λ Current letter in
        θ   Grid
       ⪫    Joined with
         ω  Empty string
   ⌊        Take the minimuim
Ｉ           Cast to string
            Implicitly print

```

# Answer
> 1 votes
# Retina 0.8.2, 74 bytes

```
\G(.+)¶
$1
ms`(?<=^(.+)¶.+)$
;$1
1A`
%(`\G(.)(?=(.*?\1)+)
$#2¶
A`;
O#`
1G`

```

Try it online! Explanation:

```
\G(.+)¶
$1

```

Flatten the grid.

```
ms`(?<=^(.+)¶.+)$
;$1

```

Append a copy of the grid to each word in the list.

```
1A`

```

Delete the original grid.

```
%(`

```

Repeat for each pair of word and flattened grid.

```
\G(.)(?=(.*?\1)+)
$#2¶

```

Count the number of times each letter in the word appears in the grid. (Note that when a letter in the word is repeated then the count is only correct for the last letter but this doesn't affect the final result.)

```
A`;

```

Delete the grid.

```
O#`

```

Sort the counts.

```
1G`

```

Keep only the first (i.e. smallest).

# Answer
> 1 votes
# Perl 5 \+ `-MList::Util+(min)`, 44 bytes

```
sub{$g=pop;map{min map$g=~s/$_/$_/g,/./g}@_}
```

Try it online!

## Explanation

Not entirely dissimilar to other solutions, this is a function submission in Perl (unusual I know, but 1 byte shorter than my best "standard" attempt.

Takes the last argument as a string containing the grid, and every other argument as words to find. Iterates over each word (implicitly stored in `$_`, splits (`/./g`) and `map`s over each letter, returning the number of `s///`ubstitutions replacing the letter for itself, taking the `min`imum for each word.

# Answer
> 1 votes
# PARI/GP, 43 bytes

```
f(g,d)=[vecmin([#[1|x<-g,x==c]|c<-w])|w<-d]
```

A port of pxeger's Haskell answer.

Takes the grid as a list of characters, and the word as a list of list of characters.

Attempt This Online!

# Answer
> 1 votes
# Burlesque, 18 bytes

```
f:qsv^mjlnm{)gv<]}

```

Try it online!

```
f:   # Count frequency (as {count val}) in grid
qsv  # Save in global map
^m   # Apply to each frequency
j    # Swap
ln   # Split into lines
m{   # Map over words
 )gv # Map over each letter get value from global map
 <]  # Minimum
}

```

---
Tags: code-golf, string, number, grid, word-search
---


title: Cat goes "Meow"

text:
# Question
Title: Cat goes "Meow"
# `cat` goes "Meow"

We are all familiar with the concept of a `cat` program. The user types something in, it is echoed back to the user. Easy. But all `cat` programs I've seen so far have missed one fact: a `cat` goes "Meow". So your task is to write a program that copies all `STDIN` to `STDOUT` **UNLESS** the input is `cat`, in which case your program should output `cat goes "Meow"`.

## Scoring

This is , so your score is your byte count, with a few modifiers:

* If your program works for any additional animals other than `cat` (e.g. `cow: cow goes "Moo"`), for each additional animal: -10
* If your program doesn't use the word "cat": -15
* If your program responds to `fox` with "What does the fox say": -25

### Animals and sounds that go together:

`cow goes moo` `duck goes quack` `sheep goes baa` `bees go buzz` `frogs go croak`

Anything else on this list is allowed.

## Rules

* Standard loopholes apply
* You must not write anything to `STDERR`
* You can use single quotes/no quotes instead of double quotes.

## Leaderboard

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

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

```
## Language Name, N bytes

```

where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:

```
## Ruby, <s>104</s> <s>101</s> 96 bytes

```

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header:

```
## Perl, 43 + 2 (-p flag) = 45 bytes

```

You can also make the language name a link which will then show up in the leaderboard snippet:

```
## [><>](http://esolangs.org/wiki/Fish), 121 bytes

```

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

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

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

# Answer
## Pyth, 231-255 = -24 bytes

### -24\*10 extra animals, -15 for no "cat" string

```
pzI}zJv.Z"xÚ]ArÃ E¯âñMOÛ|°
Ø¢mÞ½`&ÉR¯'_ãPÍm1;ñÝ|,F ¹×z#½öÂ÷ÜAPúõMh#Ì©UOC *CÑ°k%¹ö´qÌzj,å<&{jàRFÖ(¥s    ñ`GÂ:çkô#ù\M+üqíéaw ÑuW6Lã,¶w/'87ö×_r]¢:jkz»ÚFÙ¦ÈcÅËØíëûÖOa¿Þµ´6 ø¡ãEþþ:"jk(" goes "N@JzN

```

Link to code

Pseudocode

```
Auto assign z to input
print z
J = decompress animal-sound dict
if z in J:
    print " goes ", J[z], '"'

```

Animals it knows:

```
{'hare': 'squeak', 'seal': 'bark', 'lion': 'growl', 'rook': 'hiss', 'sheep': 'baa', 'hamster': 'squeak', 'moose': 'bellow', 'grasshopper': 'chirp', 'rhinoceros': 'bellow', 'cat': 'meow', 'tiger': 'growl', 'stag': 'bellow', 'crow': 'caw', 'okapi': 'bellow', 'snake': 'hiss', 'cicada': 'chirp', 'badger': 'growl', 'dog': 'bark', 'cricket': 'chirp', 'tapir': 'squeak', 'bird': 'chirp', 'sparrow': 'chirp', 'lamb': 'baa', "frog": "croak", "raven": "croak"}

```
> 18 votes

# Answer
# TeaScript, 29 - 15 = 14 bytes

Doesn't use string `cat`.

```
xr(/^c\at$/,'$& goes "Meow"')

```

"What does the fox say" (length = 21) is longer than the bonus is worth.
> 7 votes

# Answer
# PXLCODE, 114 bytes

I SHOULD GET BONUS BECAUSE THIS IS CAT LANGUAGE RIGHT?

ALSO FEED ME BUTTER

```
HAI 1.3
I HAS A V
GIMMEH V
BOTH SAEM V AN "cat",O RLY?
YA RLY,VISIBLE "cat goes meow"
NO WAI,VISIBLE V
OIC
KTHXBYE

```
> 7 votes

# Answer
# APOL, 34 bytes

`p(¿(=(i "cat") "cat goes meow" ⋔))`

BEEP BOOP I AM NOT A ROBOT
> 7 votes

# Answer
# CJam, 12 bytes

```
q_:)"dbu"=" goes \"Meow\""*

```

The program is **27 bytes** bytes long and doesn't use the word `cat` (**-15 bytes**).

Try it inline in the CJam interpreter.

### How it works

```
q_                e# Read all input and push a copy.
:)                e# Increment all code points of the copy.
"dbu"=            e# Push 1/0 if the result is/isn't "dbu".
" goes \"Meow\""* e# Repeat the string that many times.

```
> 6 votes

# Answer
# JavaScript, 45 - 15 = 30 / 264 - 235 = 29

```
alert((s=(d='MeowBuzzSongMooMooCawBarkQuackCroakHissOinkBaaSingRoarLowCooCawBarkBaaHissCryRoarSingC\x61tBeeBirdCattleCowCrowDogDuckFrogHorseHogLambLarkLionOxPigeonRookSealSheepSnakeSwanTigerWhale'.split(/(?=[A-Z])/))[d.indexOf(i=prompt())-23])?i+' goes "'+s+'"':i)

```

**Downside: you have to write the name of the animal with the first letter in uppercase and the rest in lowercase. Look below for another version which fixes this.** This version escapes the `a` in cat with `\x61` and includes code for the 22 extra animals from this list (all the allowed animals which had short enough words to be worth it):

> bee buzz 7
> bird song 8
> cattle moo 9
> cow moo 6
> crow caw 7
> dog bark 7
> duck quack 9
> frog croak 9
> horse hiss 9
> hog oink 7
> lamb baa 7
> lark sing 8
> lion roar 8
> ox low 5
> pigeon coo 9
> rook caw 7
> seal bark 8
> sheep baa 8
> snake hiss 9
> swan cry 7
> tiger roar 9
> whale sing 9

(thanks to my friend for helping me with the tedious task of making this list)

Ungolfed code:

```
data = 'MeowBuzzSongMooMooCawBarkQuackCroakHissOinkBaaSingRoarLowCooCawBarkBaaHissCryRoarSingC\x61tBeeBirdCattleCowCrowDogDuckFrogHorseHogLambLarkLionOxPigeonRookSealSheepSnakeSwanTigerWhale'.split(/(?=[A-Z])/);

input = prompt();
index = data.indexOf(input);
sound = data[index-23];
result = sound ? input + ' goes "' + sound + '"' : input;
alert(result);

```

---

## First version, 45 bytes - 15 bonus = 30

```
alert((i=prompt())=='\x63at'?i+' goes "Meow"':i)

```

Yes, I know. I went from 30 to 29 with ALL that extra work. It was fun!

## Version that allows full lowercase input, 294 bytes - 235 bonus = 59

```
alert((s=(d='MeowBuzzSongMooMooCawBarkQuackCroakHissOinkBaaSingRoarLowCooCawBarkBaaHissCryRoarSingC\x61tBeeBirdCattleCowCrowDogDuckFrogHorseHogLambLarkLionOxPigeonRookSealSheepSnakeSwanTigerWhale'.split(/(?=[A-Z])/))[d.indexOf((i=prompt())[0].toUpperCase()+i.slice(1))-23])?i+' goes "'+s+'"':i)

```

I also tried removing casing from the data array with `.join().toLowerCase().split(',')` but it ended up taking 297 characters instead.
> 5 votes

# Answer
# APL (Dyalog), 28 - 15 = 13 bytes

```
{⍵,' goes "Meow"'/⍨⍵≡⌽'tac'}

```

Input followed by  `goes "Meow"` if input is equivalent to `tac` reversed.

Try it online!

`{``}` anonymous function

`⌽'tac'` reverse the string (to get the -15 bonus by avoiding the characters `cat`)

`⍵≡` Boolean for whether the argument is identical to that

`' goes "Meow"'/⍨` use that to filter the string (i.e. returns empty string if false)

`⍵,` append to the argument
> 4 votes

# Answer
# Python 3, ~~81~~ ~~70~~ ~~55~~ 46 - 15 = 31 bytes

Thanks to Stewie Griffin for saving 15 bytes

Thanks to grc for saving 8 bytes.

Not using the string `cat` gives -15 bytes.

```
y=input()
print(y+' goes "Meow"'*(y=="ca""t"))

```
> 3 votes

# Answer
## JavaScript, ~~81 - 20 - 15 = 46 bytes~~ 50 - 15 = 35 bytes

```
(o=prompt()=="ca"+"t")&&o+=' goes "Meow"';alert(o)

```
> 3 votes

# Answer
# Stack, 51 bytes

```
'' input dup 'cat' = { 'cat goes "meow"' } if print

```
> 3 votes

# Answer
## Pyke, 391 -595 = -204 bytes

-58\*10 extra animals, -15 for no "cat" string

```
"goes"Q.dt偮晪ꅢὐὥ墵셞᳙ᄷ쟿䁔漲ᬰ䵙ꄨ塋튖თ᠞鮔૪爟㍅爟⼱]꣟勒〥鴞᫠⬻䋥ュ⣹邦㺓堚퀦잓號漲ქ䦙ᔯ漲ᠥ쏔っ鮔牔鶇Ƒ䂝雥⬻⯎偮燩巺䯥봽鮔튖➒゗ᨼ䄇嚕㮷鮏ᘽ挳ᖘ漲睴윿꒲⬻鼤㨂ᘽdc2cY@]3J

```

Try it here!

Uses dictionary-based compression to store the words. Pyke is older than the question.

Animals it knows:

```
{'seals': 'bark', 'turkeys': 'gobble', 'mosquitos': 'whine', 'curlews': 'pipe', 'dogs': 'howl', 'sheep': 'bleat', 'elephants': 'trumpet', 'eagles': 'scream', 'raccoons': 'trill', 'goats': 'bleat', 'donkeys': 'bray', 'monkey': 'whoop', 'snakes': 'hiss', 'wolves': 'howl', 'grasshoppers': 'chirp', 'ferrets': 'dook', 'geese': 'honk', 'ducks': 'quack', 'chinchillas': 'squeak', 'oxen': 'low', 'pigs': 'snort', 'lions': 'snarl', 'antelopes': 'snort', 'crows': 'caw', 'hamsters': 'squeak', 'ravens': 'croak', 'leopards': 'snarl', 'tapirs': 'squeak', 'lambs': 'bleat', 'horses': 'neigh', 'jaguars': 'snarl', 'crickets': 'chirp', 'moose': 'bellow', 'cattle': 'moo', 'deer': 'bellow', 'rooks': 'caw', 'dolphins': 'click', 'whales': 'sing', 'owls': 'hoot', 'walruses': 'groan', 'cicadas': 'chirp', 'tigers': 'snarl', 'chickens': 'cluck', 'giraffes': 'bleat', 'mice': 'squeak', 'peacocks': 'scream', 'songbirds': 'sing', 'geckos': 'croak', 'frogs': 'croak', 'pigeons': 'coo', 'swans': 'cry', 'bitterns': 'boom', 'rhinoceros': 'bellow', 'cats': 'purr', 'badgers': 'growl', 'magpies': 'chatter', 'vultures': 'scream', 'elk': 'bleat'}

```
> 3 votes

# Answer
## LOLCODE, 100 109 Bytes

```
HAI 1
I HAS A I
GIMMEH I
BOTH SAEM I "cat",O RLY?
YA RLY,VISIBLE "cat goes Meow"
NO WAI,VISIBLE I
OIC
KTHXBYE

```

Try it out online

My first post on this platform, as well as my first code-golf challenge and my first code in LOLCODE, so there's probably lots to improve. I tried avoiding the "cat" with casting the equivalent hex-code `":(63):(61):(74)"` instead, but it didn't work out for me. If you know a solution to this, please let me know!

\*+9 Bytes because I didn't read the instructions clear enough
> 3 votes

# Answer
# MATLAB, 58 - 15 = 43 bytes

Pretty straight forward, with bonus for not using `cat` in the code:

```
x=input('');if isequal(x,'dbu'-1);x=[x ' goes "Meow"'];end;x

```

Input must be given inside single quotes: `' '`.
> 2 votes

# Answer
# C++11, 316 - 11\*10 - 15 = 191 bytes

```
#include <map>
#define t(a,b){#a,#b},
using s=std::string;int main(){std::map<s,s>m{t(cow,moo)t(crow,caw)t(dog,bark)t(hog,oink)t(lark,sing)t(lion,roar)t(oxen,low)t(rook,caw)t(seal,bark)t(sheep,baa)t(swan,cry){"c""at","meow"}};s l;while(int i=~getchar())l+=~i;printf("%s",(m[l]==""?l:l+" goes \""+m[l]+'"').c_str());}

```

Compiles well with VisualStudio. GCC wants me to `#include <string>` and `#include <cstdio>`. It would be shorter if I wouldn't go for bonuses, but I still hope author revises bonuses. I can't think of language where defining `cow -> moo` or so is way way shorter than 10bytes. Mine cost `3+key+value` bytes for additional animal and flat `22+17` bytes for defining structure and so.

Ungolfed

```
#include <map>

#define t(a, b) { #a, #b },
using s = std::string;
int main()
{
    std::map<s, s> m{
        t(cow,moo)
        t(crow,caw)
        t(dog,bark)
        t(hog,oink)
        t(lark,sing)
        t(lion,roar)
        t(oxen,low)
        t(rook,caw)
        t(seal,bark)
        t(sheep,baa)
        t(swan,cry)
        { "c""at", "meow" }
    };
    s l;
    while (int i = ~getchar())
        l += ~i;
    printf("%s", (m[l] == "" ? l : l + " goes " + m[l]).c_str());
}

```
> 2 votes

# Answer
# GNU sed, 37 - 15 = 22 bytes

```
sed -r 's/^(\x63at)$/\1 goes "Meow"/'

```
> 2 votes

# Answer
## Javascript, 117 bytes

```
for(c=0,s="bee.Buzz.bird.Song.c\at.Meow.cow.Moo.crow.Caw.dog.Bark.oxen.Low.owl.Who.rook.Caw.sheep.Baa.swan.Cry".split('.'),p=prompt(),a=![];c<s.length;c+=2){if(p==s[c])a=c}if(!a)alert(p=='fox'?'What does the fox say':p);else alert(s[a]+' goes "'+s[a+1]+'"')

```

I definitely haven't won here, but I've covered a lot of extra animals.

## Javascript, 31 bytes

```
p=prompt();alert(p=='c\at'?p+' goes "Meow"':p)

```
> 2 votes

# Answer
# HALT, 71 - 15 = 56 bytes

```
1 IF "cat" 2 ELSE 3
2 TYPE "MEOW";HALT
3 SET 0;NEXT
4 INCREMENT;STORE 0

```

HALT is a language I (@Downgoat) made designed for string processing, the only problem is that it's a bit long

## Formatted

```
1              IF "cat" 2 ELSE 3
2 TYPE "MEOW"; HALT
3 SET 0      ; GOTO 6
4 INCREMENT  ; STORE 0

```
> 2 votes

# Answer
# Python, ~~62~~ ~~58~~ 48 - 15 = ~~48~~ ~~44~~ 33 bytes

Thanks to Unrelated String for -10 bytes!

```
x=input()
print(x,*['goes "Meow"'][:"c""at"==x])

```

0x61 = a.

## Try it online!

Revision 3: with cat without cat

Revision 2: with cat without cat

Revision 1: with cat without cat
> 2 votes

# Answer
# Ruby, ~~49~~ ~~46~~ 50 - 15 = 35 bytes

Pretty straight-forward I guess. Not using cat.

```
$<.map{|l|puts l==?c+'at
'??c+'at goes "Meow"':l}

```

Edit: Thanks for @w0lf for saving 3 bytes!
> 1 votes

# Answer
# JavaScript, 48 - 15 = 33 bytes

Uses `\x61` as a substitute for the `a` in `cat`.

```
i=prompt();alert(i=="c\x61t"?i+' goes "Meow"':i)

```
> 1 votes

# Answer
## Perl, 46 - 15 = 31

```
$_=join'',<>;s/(?<=^ca)t$/t goes "Meow"/;print

```
> 1 votes

# Answer
# Beam, ~~208~~ 206 - 15 = 191 bytes

Not a competitive entry, but a bit of fun to do. It checks the first for letters of the input against `cat`. If it gets a mismatch it will shortcut to the standard cat program. If it matches it will append `goes "Meow"`

```
'''''''''>`\/n@>`)'''>`++\
/++++++++++/r /SP''+(++++/
\+)'PSrn@--S/ \rn@`>`)rn'''''>`++++++)++@P'p++++@'p-----@`p++@'p-@``p@++@'''''>`+++++++++)--@'p++@'p-----@++++++++@``p++@H
/@<  (`<     < `<    ''<
>ruH

```
> 1 votes

# Answer
# , 23 - 15 = 8 chars / 58 - 15 = 43 bytes

```
ïċɘ㴃탵ˠⓀ㐀攁退胦ްおр夁䰰ᷗȿ 쨀#

```

`Try it here (Firefox only).`

The byte to char ratio is real.
> 1 votes

# Answer
# PHP, 1204 - (10 * 64) - 15 - 20 = 529 bytes

```
<?php $i = $argv[1];$s = json_decode(gzuncompress(hex2bin("78da555351b2db200cbc8a27dfee057a1b192bc018104f40dcbccebb7b25d9499d8fcc588b10abddcddf1b64e4e8a04c3bd1eac86db7df3774e136dfa0744c5451805688bb400bac1e5900cfb42703ba1e3bc6e3ce82dabe8cef6f2d22af52b910b95ad93b72d173a22c8083f4d0f63bc75c131aa2e332d2ae45886e43ed7769082f438afc52027df46b20182af457b83c24537ad2c199484b99f6fe669dd9afcd6cc70ef67972a03bb8c10915abb12aa995bc7206deac48555818a9e80ea46cf8142020fe0aa0ccd761327e0db00e046f745426d0c531610d22af609d47aea8dade91d998ad447aebcef6aef0b32d7d64b8df4ddd84a0173c436b816a35475efbf8110bc254a3bf6a1420b76e7d1788f1a346ceb14f8e61b98c0bc44ddb0a46afe284582b55ea9087e1af2004236b3999278a452726c8cb8bef3c2d0086b14ad362f1f3b4032fe67b8aa59cae88742744aab26ccff3f47a2583af11ad0f344c0a1119910553b2d864929562270577b14a87d10635ea351a3e0895572ffd11f0f8ac0867fadf36898668249c65a732448e387de481c1c96931272598863c8ed09ec6b17020874c5792ac1e5bea8ee234c7c238df1a42faff449360552b55c05660d3d5426c4dcb0a7c26f874ac75f0d7a7da0e079da7145d74f848418fc71f5a75d652947a4e1edd469715fae023e29e96c3b0c748027e847a87c4ef4cc893820438722f666bc9a6cb69facf3f28e87499")));echo array_key_exists($i,$s)?"$i goes {$s->$i}":($i=="fox"?"What does the $i say":$i);

```

I use a json encoded gz compressed array of animal sounds. This means it works with all 65 allowed animals, but my script is huge. Also works with fox and doesn't have the word cat in it.
> 1 votes

# Answer
## MATLAB, 46 bytes

```
regexprep(input(''),'^cat$','cat goes "Meow"')

```

Admittedly trivial. The input must be given in single quotes.
> 1 votes

# Answer
## Java = 222 bytes (compressed)

```
public class A {public static void main(String[] args) {Scanner a=new Scanner(System.in);for(;;){String b=a.nextLine();if(!b.equalsIgnoreCase("cat"))System.out.println(b);else {System.out.println("meow");System.exit(0);}}}

```

Or I could decompress it.

## Batch = 52 bytes

```
set /p k=
if "k"=="cat" (echo cat) ELSE (echo %k%)

```
> 1 votes

# Answer
# Javascript: 48 Characters, 48 Bytes

```
function(s){return (s=="cat")?"cat goes meow":s}

```

### Test

`=>`"Dog"

`<=`"Dog"

`=>`"cat"

`<=`"cat goes meow"
> 1 votes

# Answer
# Haskell, 52-15 = 37 bytes

```
c"\99at"="\99at goes \"Meow\""
c s=s
main=interact c

```

Using `\99` as a substitute for c in “cat” so as to get the 15 bytes bonus.
> 1 votes

# Answer
# Prolog, 48 bytes

```
p:-read(X),write(X),X=cat,write(' goes "Meow"').

```

Attempts to bring more animals to the party made the program longer even with bonuses.
> 1 votes

# Answer
# Pyth, 26-15 (no "cat") = 11 bytes

My first ever Pyth program!

```
Iqz_"tac"+z" goes meow";Ez

```

## Try it here

### Explaination

```
   _"tac"                   # Reverse the string "tac"
Iqz                         # If the input equals "tac" reversed
         +z" goes meow";    # Append " goes meow"
                        Ez  # Else, use the input.
                            # Implicit: print the input, if it's used.

```
> 1 votes

# Answer
## Pyth, 82-95 = -13 bytes

```
+z*}zKc."atÜiÃ'4ãl¾Eªîiû<-È&e"\jjk[d"goes"dNr@c."bw««[áÅ3ÏB"\c%x`Kz3 3N

```

I finally got around to converting my new functional Python 2 entry to Pyth. It doesn't beat the top contender. Turns out zipping together more animals into a larger dictionary reduces score faster than cleverly associating animals with sounds. This supports 8 animals in addition to cat: rhino, okapi, moose, lion, tiger, badger, hippo, and stag.

Try it online
> 1 votes

# Answer
# , ~~22~~ ~~16~~ 14 bytes

**29 bytes - 15**

```
Q"tac"`J=J" goes \"Meow\""+Q?
```

It's long and can be golfed more
> 1 votes

# Answer
## Japt, ~~25-15=10~~ 24-15 = 9 bytes

First time trying Japt:

```
N¦`¯t`?N:`¯t goƒ \"´ow\"

```

`ƒ` should be replaced with unprintable character `U+0083` Compiles to:

```
N!="cat"?N:"cat goes \"meow\""

```

Old solution:

```
N¥`¯t`?`¯t goƒ \"´ow\"`:N

```

Try it here
> 1 votes

# Answer
# 05AB1E, score: -136 (214 bytes \- 31\*10 - 15 - 25)

```
'¨›Qi“What‚à€€ ÿ…è“ë“ÓÕŸâÍÝ¹ÐÀ¼ÛË—Ä¬…Ð§ÀÛÆÓ‹·»ÑÐœ²èàæÑåî€žÚÆÚØåÊÓ³âÌ–ÔÄ¤•ã‚í„ÄŠêÂÝ¢“#sk©di.•QÃ€}£≠‰ŒΛ(Ïûвrüéä[ñøuF½3¡üÃïßåιQÊçdï€]Üвβ`šŠû©ª«ĀLΩÝβ\à¨TĆηÎ.₄₆öª$γâôΘ:Æ™{¹и5|Âć®λ¬¡¸αâË::´óýÏƶ5~¦m.škα†#Ð6λ•#®è™s“ÿ—± "ÿ"

```

Bonuses:

* -15 for not using `cat`
* -25 for outputting `What does the fox say` when the input is `fox`
* 31 times -10 for the animals and sounds: `["bat screech","bear roar","bee buzz","tiger roar","lion roar","jaguar snarl","cat meow","chicken cluck","cow moo","cricket chirp","deer bellow","dog bark","wolf howl","duck quack","eagle screech","elephant trumpet","frog croak","horse neigh","mouse squeak","monkey scream","pig oink","rabbit squeak","seal bark","sheep baa","snake hiss","turkey gobble","whale sing","ass heehaw","rat squeak","goat bleat","lamb baa"]`

Try it online or verify all used animals.

**Explanation:**

```
'¨›                  '# Push dictionary word "fox"
   Qi                 # If the (implicit) input-string equal "fox":
     “What‚à€€ ÿ…è“   #  Push dictionary string "What does the ÿ say"
                      #  (where the `ÿ` is automatically filled with the implicit input)
   ë                  # Else:
    “ÓÕŸâÍÝ...ÄŠêÂÝ¢“ #  Push dictionary string "bar bear bee ... rat goat lamb"
    #                 #  Split it on spaces
    sk                #  Get the index of the input-string in this list (-1 if not found)
    ©                 #  Store this index in variable `®` (without popping)
    di                #  If this index is non-negative (>= 0):
      .•QÃ€...Ð6λ•    #   Push compressed string "screech roar ... bleat baa"
      #               #   Split it on spaces
      ®è              #   Index variable `®` into this list
      ™               #   Titlecase this sound
      s               #   Swap to get the (implicit) input-string at the top of the stack
      “ÿ—± "ÿ"        #   Push dictionary string 'ÿ goes "ÿ"'
                      #   (where the first `ÿ` is the input at the top of the stack,
                      #    and the second `ÿ` is the titlecased sound below it)
                      # (after which the top of the stack is output implicitly as result,
                      #  which will be the (implicit) input itself for any other input)

```

See this 05AB1E tip of mine (sections *How to use the dictionary?* and *How to compress strings not part of the dictionary?*) to understand why:

* `'¨›` is `"fox"`
* `“What‚à€€ ÿ…è“` is `"What does the ÿ say"`
* `“ÓÕŸâÍÝ¹ÐÀ¼ÛË—Ä¬…Ð§ÀÛÆÓ‹·»ÑÐœ²èàæÑåî€žÚÆÚØåÊÓ³âÌ–ÔÄ¤•ã‚í„ÄŠêÂÝ¢“` is `"bat bear bee tiger lion jaguar cat chicken cow cricket deer dog wolf duck eagle elephant frog horse mouse monkey pig rabbit seal sheep snake turkey whale ass rat goat lamb"`
* `.•QÃ€}£≠‰ŒΛ(Ïûвrüéä[ñøuF½3¡üÃïßåιQÊçdï€]Üвβ`šŠû©ª«ĀLΩÝβ\à¨TĆηÎ.₄₆öª$γâôΘ:Æ™{¹и5|Âć®λ¬¡¸αâË::´óýÏƶ5~¦m.škα†#Ð6λ•` is `"screech roar buzz roar roar snarl meow cluck moo chirp bellow bark howl quack screech trumpet croak neigh squeak scream oink squeak bark baa hiss gobble sing heehaw squeak bleat baa"`
* and `“ÿ—± "ÿ"` is `'ÿ goes "ÿ"'`
> 1 votes

# Answer
# Pyth, 132 - 150 (animals) - 15 (no `cat`) = -33 bytes

```
pJjb.zp.x++" goes \""r@.dmcd\ic."ay-ÝÏåâšB²ÅuŠ°µ²¦DÄ²Öì |t`2“‚Êôë¨}èÔèw:ÿÊ_OƒÄ<Ú›ø‚î½ùÛ&L°„6a<9-¾¹™,Uø0é6Œû²Ù²ËyÊ·%C"\lJ4\"k

```

Try it online!

Uses a packed string to fit in animals for less than 10 bytes each

Full list:

```
parrot goes "Squack"
cat goes "Meow"
rook goes "Caw"
ass goes "Bray"
goose goes "Honk"
dog goes "Woof"
duck goes "Quack"
sheep goes "Baa"
ox goes "Moo"
raven goes "Caw"
goat goes "Baa"
swan goes "Cry"
frog goes "Croak"
toad goes "Croak"
monkey goes "Chatter"

```

Edit 1: Almost forgot the no cat bonus :P
> 1 votes

# Answer
# GolfScript, 25 - 15 = 10 bytes

```
."c""at"+=" goes 'Meow'"*

```

Try it online!

### Example

```
."c""at"+=" goes 'Meow'"*   # Input: cat
."c""at"                    # Duplicate input, push c and at. Stack: cat cat c at
        +                   # Concatenate, Stack: cat cat cat
         =                  # Check if equal, Stack: cat 1
          " goes 'Meow'"*   # " goes 'Meow'" pushed onto stack n times, Stack: "cat" " goes 'Meow'"
                            # Implicitly print

```

### Alternate Example

```
."c""at"+=" goes 'Meow'"*   # Input: asdf
."c""at"                    # Duplicate input, push c and at. Stack: asdf asdf c at
        +                   # Concatenate, Stack: asdf asdf cat
         =                  # Check if equal, Stack: asdf 0
          " goes 'Meow'"*   # " goes 'Meow'" pushed onto stack n times, Stack: "asdf" ""
                            # Implicitly print

```
> 1 votes

# Answer
# Nim, 65 - 15 = ~~56~~ 50 bytes

Does not use the word cat. Supports only cat and then "Meow", no other animals.

```
while 1>0:
 var i=readLine stdin;echo if i=="ca"&"t":"Meow"else:i

```

Attempt This Online!

(-6 bytes thanks to Steffan)
> 1 votes

# Answer
# Vyxal, 285 - 310 - 15 - 25 = -65 bytes

```
`∷¾`=[`λ⟩ ƛ∪ λλ ∷¾ ∨¶`|`Ḃṙ ∞¨ εċ ṗµ √₇ Ṁ⋎ ¢₌ β¡ ¦‹ √⊍ ₃⇩ •ƈ ṡƒ ¦ø ḟ₇ Ẇ⟑ µɽ ½ż Þ‡ ₃⅛ Ḣ⟨ ₈Ḋ ġṄ ⁋ė Ċṁ ∴† Ẏ₇ ass ₀⌈ ⌊ṫ Ȯ⁰`⌈?ḟ:£0≥[`s⇩⋏↳⋎ r⋎« Ȧ¨ r⋎« r⋎« sn₴£ m□ŀ cḟĿ moo ch↲Ṗ Ǎ⟩⟑ṙ •øk h⋎₄ qꜝ½k s⇩⋏↳⋎ t≥⁋⌐¨ crβ⁰ ne⋏ṫ sȧ‛ak s›‹ o›₌ sȧ‛ak •øk baa λµs £⁋ǎʁ ⟩ɽ hee¥↓ sȧ‛ak bl↓⟑ baa`⌈¥i`% ¢₃ `?%$+

```

Try it Online!

Port of Kevin Cruijssen's 05AB1E answer.

# Vyxal, 42 - 15 - 25 = 2 bytes

```
`¢₌`=[`¢₌ ¢₃ "M□ŀ"`|`∷¾`=[`λ⟩ ƛ∪ λλ ∷¾ ∨¶`

```

Try it Online!

Bonuses:

* -15 for not using `cat`
* -25 for responding to `fox` with `What does the fox say`

## Vyxal, 19 - 15 = 4 bytes

```
`¢₌`=[`¢₌ ¢₃ "M□ŀ"`

```

Try it Online!

Bonuses:

* -15 for not using `cat`

### Explanation

Most of it is just string compression:

* ``¢₌`` is `cat`
* ``¢₌ ¢₃ "M□ŀ"`` is `cat goes "meow"`
* ``∷¾`` is `fox`
* ``λ⟩ ƛ∪ λλ ∷¾ ∨¶`` is `What does the fox say`
> 1 votes

# Answer
# TI-Basic, 48 bytes

```
Input Str1
Str1="cat
If Ans
Disp Str1+" goes Meow
If not(Ans
Disp Str1

```

All those lowercase letters are increasing the bytecount by a lot.
> 1 votes

# Answer
# Pyth, 31 - 15 = 16 bytes

You can try it out here

```
In+C99"at"zz;E+z" goes \"Meow\"

```

Explaination:

```
I                                # If-statement
 n                               # not equal
  +C99"at"                       # Adds the char 99 with the string "at" = "cat"
          z                      # z, the user input
           z                     # Print the user input
            ;                    # Ends all open parentheses
             E                   # Else-statement
              +z" goes \"Meow\"  # Adds ' goes "Meow"' to z and prints the result

```
> 0 votes

# Answer
# C, 76 bytes

```
main(){char a[99];gets(a);printf("%s%s",a,strcmp(a,"cat")?"":" goes meow");}

```
> 0 votes

# Answer
# PHP, 70-15 = 55 bytes

```
<?=$l=rtrim(stream_get_contents(STDIN),~òõ),$l==~œž‹?~ß˜šŒßÝ²šˆÝ:'';

```

(saved as ISO-8859-1)

Uses inverted undefined constants as string literals:

* `~òõ` == `"\r\n"`
* `~œž‹` == `'cat'`
* `~ß˜šŒßÝ²šˆÝ` == `' goes "Meow"'`

Everything is combined in a single echo statement, shorthanded with `<?=`
> 0 votes

# Answer
## Ruby, 35 + 2 (-p flag) - 15 = 22 bytes

```
$_==?c'at
'&&$_[-2]+=' goes "Meow"'

```

Inspired by trying to improve Peter Lenkefi's solution.
> 0 votes

# Answer
## Ruby, 110 + 2 (-p flag) -60 (cow, ox, dog, bee, pig and crow) -15 (no cat) = 37 bytes

```
(h=Hash[*%W(cow Moo ox Low c\141t Meow dog Woof bee Buzz pig Oink crow Caw)][$_.chop])&&$_[-2]+=' goes "'+h+?"

```

Multiple animal Ruby solution... As long as the animal+sound is \<8 characters, it shrinks for each one added. Gross abuse of Ruby. :)
> 0 votes

# Answer
# Ruby, 26 + 1 = 27

With command-line flag `-p`, run

```
sub /^cat$/,'\& goes Meow'

```

Getting the no-cat bonus costs 2 bytes, which isn't actually worth it:

```
sub /^c at$/x,'\& goes Meow'

```
> 0 votes

# Answer
# Hassium, 67 Bytes

```
func main()if((x=input())=="cat")print(x+" goes meow")else print(x)

```

See expanded here
> 0 votes

# Answer
# JacobFck, 31 Bytes

I really like the golfed version of this.

```
"cat"<|=_e>!:e"cat goes Meow">

```

See commented and expanded here
> 0 votes

# Answer
## Python 2, 149-95 = 54 bytes

### -8\*10 extra animals, -15 for no "cat"

```
u=raw_input()
l="ca""t badger rhino okapi moose stag tiger hippo lion".split()
print u+' goes "%s"'%["Growl","Bellow","Meow"][`l`.find(u)%3]*(u in l)

```

Supported animals:

* moose, stag, okapi, rhino (all Bellow)
* tiger, badger, lion, hippo (all Growl)

This is not the shortest Python answer, but at least it does bother to try at some other animals! I add it here because the answer i had previously did not work, and I'm confident this will become the shortest Pyth answer once I translate it and golf it there.

### How it works:

1. Take input
2. Create a list of animals in a very precise order.
3. Print the input, and if the input is in the list, use the location of the input in the string representation of the list to index an array of sounds, and append the appropriate "goes" string.
> 0 votes

# Answer
## JavaScript, 35 - 15 (-p no cat) = 20 Bytes

```
c=i=>(i=='c\at')?i+' says "Meow"':i

```

Can someone check to see that I did the header right?
> 0 votes

# Answer
# Arcyóu, 38 bytes (non-competitive)

*Since this version of the language was made after the challenge was posted, it is not eligible.*

```
(: s(q))(?(= s "cat")"cat goes Meow" s

```

Arcyóu is a LISP-like golfing language.

Explanation:

```
(: s(q))           ; Set the variable s to the contents of STDIN
(? (= s "cat")     ; If-statement. Condition is s == "cat"
  "cat goes Meow"  ; If true: return the string "cat goes Meow"
  s                ; Otherwise, return what was entered

```

Arcyóu automatically prints the result of the last expression evaluated. In this case, it is the `?` statement. It also allows you to leave off trailing close-parens.
> 0 votes

# Answer
# Emacs Lisp (67 Bytes)

```
(set'a(read-string""))(message(pcase a("cat""cat goes meow")(_ a)))

```

It uses pattern matching to distinguish cats from other input. This could be extended to fit other animals in as well, but as most of them take up more than 10 characters, there is not much to be gained from that.
> 0 votes

# Answer
# Milky Way 1.5.16, 29 bytes - 15 = 14

```
"c""at"+'?{b_" goes Meow"+_}!

```

Doesn't use a `"cat"` string.

---

### Explanation

```
"c""at"      " goes Meow"      # push string to the stack
       +                 +     # add the TOS and the STOS
        '                      # read input from the command line
         ?{ _             _}   # if statement
           b                   # equality of the TOS and the STOS
                            !  # output the TOS

```

---

### Usage

```
python3 milkyway.py <path-to-code> -i <input>

```
> 0 votes

# Answer
## Perl, 13 bytes

The string "cat" does not appear in my code (Special thanks to Dennis for shaving 15 bytes off of the code, and teaching me some new Perl tricks):

```
s/^(c)at$/$& goes Meow/

```
> 0 votes

# Answer
# Swift 2.0, ~~71~~ 68-15 (no "cat") = 53 bytes

```
func a(s:String)->String{return s=="c\u{61}t" ?s+" goes \"Meow\"":s}

```

For some reason, a compilation error is thrown if there isn't a space before the ternary operator `?`

### Ungolfed

```
func a(s: String) -> String{
    return s == "c\u{61}t" ? s + " goes \"Meow\"" : s
}

```

This doesn't use "cat" in it by replacing the a with the unicode literal `\u{61}`. You can test this code here
> 0 votes

# Answer
## DIG, 163 - 15 = 148 bytes

Disclaimer: Due to the fact that DIG was created after the challenge, this answer is non-competing.

Zoomed in (Note: This file will NOT compile, due to the nature of the language)

While I have no idea if this is considered a valid language for PPCG, it *does* complete the challenge. Documentation for the language can be found here and the interpreter can be found here.
> 0 votes

# Answer
# C#6, 302 - 110 - 15 = 177 bytes

This works for 12 different animals, including cat. It does not include the word "cat" verbatim.

```
using static System.Console;class P{static void Main(){var a=ReadLine();var d="bee,Buzz,c\x61t,Meow,cow,Moo,crow,Caw,dog,Bark,hog,Oink,lamb,Baa,lion,Roar,ox,Low,owl,Hoo,pig,Oink,rook,Caw,seal,Bark,sheep,Baa,swan,Cry".Split(',');int i=22;while(--i>0&&d[--i]!=a);Write(i<0?a:d[i]+" goes '"+d[i+1]+"'");}}

```

Indentation and new lines for clarity.

```
using static System.Console;
class P{
    static void Main(){
        var a=ReadLine();
        var d="bee,Buzz,c\x61t,Meow,cow,Moo,crow,Caw,dog,Bark,hog,Oink,lamb,Baa,lion,Roar,ox,Low,owl,Hoo,pig,Oink,rook,Caw,seal,Bark,sheep,Baa,swan,Cry".Split(',');
        int i=22;
        while(--i>0&&d[--i]!=a);
        Write(i<0?a:d[i]+" goes '"+d[i+1]+"'");
    }
}

```
> 0 votes

# Answer
# Retina, 23 - 15 = 8 bytes

```
^ca\0*t$
$& goes "Meow"

```
> 0 votes

# Answer
# Pylongolf2, 33-15=18 bytes

```
"tac"╨1cd_@0=b?" goes Meow"¿~

```

Explanations:

```
"tac"╨1cd_@0=b?" goes Meow"¿~
"tac"                         push "tac" to stack
     ╨1                       reverse it
       cd                     read input and then select latest item in stack
         _                    duplicate input
          @0                  select first item in stack
            =b                compare then swap places
              ?               if true,
               " goes Meow"¿  push " goes Meow" to stack and end if statement
                            ~ print it.

```
> 0 votes

# Answer
## Lua 5.3.2, 229 - 25 - 15 - 80 (extra animals) = 109 bytes

```
r={...}a={['\99\97\116']='Meow',duck='Quack',sheep='Baa',bee='Buzz',frog='Croak',bat='Screech',elk='Bugle',swan='Cry',pig='Oink'}print(r[1]=='fox' and 'What does the fox say' or(a[r[1]] and r[1]..' goes "'..a[r[1]]..'"' or r[1]))

```

### Ungolfed

```
local Args = {...}
local Sounds = {
    ['\99\97\116'] = 'Meow',
    duck = 'Quack',
    sheep = 'Baa',
    bee = 'Buzz',
    frog = 'Croak',
    bat = 'Screech',
    elk = 'Bugle',
    swan = 'Cry',
    pig = 'Oink'
}
print(
    Args[1] == 'fox' and 'What does the fox say' or (
        Sounds[Args[1]] and Args[1] .. ' goes "' .. Sounds[Args[1]] .. '"' or Args[1]
    )
)

```

I tried to make the logic a little clearer by putting it on multiple lines.
It's essentially a ternary operator `?:`
> 0 votes

# Answer
## AWK, 32 - 15 = 17

```
/^[c]at$/{$0=$0" goes 'Meow'"}1

```

I think this counts as not using "cat". Could have saved a couple bytes if "cat" were allowed to be anywhere in the line.

For giggles I also put together one with more animals, but it's not competitive, especially with trying to capture the correct verb to use, but here's what I came up with :)

```
{for(;I<split("ca""t,Meow,bees,Buzz,bird,Song,cow,Moo,crow,Caw,dog,Woof,duck,Quack,frogs,Croak,hog,Oink,ox,Low,pig,Oink,sheep,Baa,swan,Cry",a,",");)
m[a[I-1]="'"a[I+=2]"'"}
m[$0]{$0=$0($0~/s$/?" go ":" goes ")m[$0]}
/^fox$/{$0="What does the fox say"}
1

```
> 0 votes

# Answer
# Java, 174 - 15 = 159 bytes

```
interface a{static void main(String[]A){for(String s="";;s=new java.util.Scanner(System.in).nextLine())System.out.println(s+(s.equalsIgnoreCase("ca"+"t")?" goes meow":""));}}

```

Ungolfed:

```
interface a {
    static void main(String[] A){
        for (String s = "";;s = new java.util.Scanner(System.in).nextLine())
            System.out.println(s + (s.equalsIgnoreCase("ca"+"t") ? " goes meow" : ""));
    }
}

```
> 0 votes

# Answer
# Python 3, 44 - 15 = 29

```
i=input();print(i+' goes Meow'*(i=='ca''t'))

```
> 0 votes

# Answer
# 0815, 132 - 15 = 117

```
}:(:!~>^:(:}:):{~$>^:):{=<:63:-^:
:{=<:61:-^:
:{=<:74:-^:
:{=<:0:-^:
:<:20:~>$<:67:~$<:6F:~>$<:65:~>$<:73:~${~$<:4D:~$&{~${~$<:77:~$

```
> 0 votes

# Answer
# PHP, 47-15=32 bytes

```
<?=($s=fgets(STDIN)).[" goes Meow"][c.a.t!=$s];

```

4 bytes longer than on `$argv[1]`, and: it works only on the first line of input (including the linebreak).

**69-15=54 bytes** to take all lines:

```
while(false!==$n=fgets(STDIN))$s.=$n;echo$s,[" goes Meow"][c.a.t!=$s];

```
> 0 votes

# Answer
# Pepe, 244 - 15 = 229 bytes

*Bonus -15 for not containing the word "cat"*

```
rEeEEeeeEErrEEREEeererEeEEeeeeErrEEREEeererEeEEEeEeerrEEREEeererErrEEreeEEeeeEEreeEEeeeeEreeEEEeEeereeeEeeeeereeEEeeEEEreeEEeEEEEreeEEeeEeEreeEEEeeEEreeeEeeeeereeeEeeeEereeEeeEEeEreeEEeeEeEreeEEeEEEEreeEEEeEEEreeeEeeeEeREEEEeEEErEeREEeREReEReee

```

Try it online!

Commented version

```
re  # fix syntax highlighting, doesn't affect the program
rEeEEeeeEE  # push "c"
rrEE  # func

REEee re  # pop "c"
rEeEEeeeeE  # push "a"
rrEE  # func

REEee re  # pop "a"
rEeEEEeEee  # push "t"
rrEE  # func

REEee re  # pop "t"
rE
rrEE  # func

# Output the text
reeEEeeeEE reeEEeeeeE reeEEEeEee reeeEeeeee reeEEeeEEE reeEEeEEEE reeEEeeEeE reeEEEeeEE reeeEeeeee reeeEeeeEe reeEeeEEeE reeEEeeEeE reeEEeEEEE reeEEEeEEE reeeEeeeEe

# Clear the stack
REEEEeEEE

rEe  # end-pop

# Loop
REEe RE  # Take input, add a trailing null
ReE

Reee

```
> 0 votes

# Answer
# Runic Enchantments, 50 - 15 = 35

```
D q?=1l" "\>
Rlril1-{=?/:1´759E" "=?@"goes Meow"@

```

Try it online!

In general, for a zero-length animal name and zero-length sound, the overhead for another animal is 10 bytes (roughly, `:0""=2*?""`). The fifteen bytes we get for cat makes it worth spending a net 1 byte encoding "cat" as the numerical value `1759` and extracting "cat" from the dictionary.
> 0 votes

# Answer
# C (gcc), 81 - 15 = 66 bytes

## Text input version

Does not contain the word "cat", so gets that bonus. All attempts at further bonuses made the program larger.

Assumes a little-endian machine where `sizeof(int) >= 4` and where signed integers are of the two's complement variety.

```
q;main(c){for(;c=~getchar();)q=q<<8|putchar(~c);q^6513012||printf(" goes meow");}

```

Try it online!

```
q;main(c){
for(;c=~getchar();)         Read bit-flipped character from STDIN into c. getchar()
                            returns -1 on EOF, and with two's complement, ~c == -c - 1,
                            so we stop on EOF.
q=q<<8|putchar(~c);         Insert character at LSB of q, moving the current values along one
                            byte, while also sending it to STDOUT.
q^6513012||                 Is q non-equal to "cat"?
printf(" goes meow");}      If no (it IS equal), print addendum, otherwise ignore.

```

The above is fine for text-only input, and most binary input. The only (known by me) corner case is if the file happens to end with a NUL character followed by "cat" (`\0cat`), which will give a false positive. I am not 100% sure if we were meant to deal with anything but text, so here is the safer version too:

## Binary-friendly version, 90 - 15 = 75 bytes

```
q,x;main(c){for(;c=~getchar();x++)q=q<<8|putchar(~c);x^3|q^6513012||printf(" goes meow");}

```

Try it online!
> 0 votes

# Answer
# Python 3, 516 - \[10 x 53\] - 15 = -29 bytes

```
lambda i:([i+f' goes "{a.split(",")[0]}"'for a in("bark,dog,wolf,seal,zebra bellow,alligator,moose,okapi bleat,deer,elk,giraffe,sheep,goat,lamb bray,donkey,ass buzz,bee,mosquito caw,crow,raven,rook chirp,cicada,cricket,songbird chuckle,linnet croak,frog,toad cry,swan hiss,goose,snake,tarantula meow,c"+"at moo,calf,cow,ox oink,pig,hog roar,badger,bear,lion,tiger,jaguar,leopard scream,monkey,peacock,vulture screech,bat,eagle,owl squeak,hamster,mouse,rat,rabbit,hare,tapir").split()if i in a.split(",")[0:]]+[i])[0]

```

Try it online!

Started with all the animals on the list, sorted into optimal groupings by sounds they make, then culled down animals whose bytes use more than 10. The final list contains 54 animals, for a bonus of -540 bytes.

It doesn't contain `cat` for another -15 bytes.

It's an anonymous function that works like a table with the animal sounds as headers, and finds the corresponding header for the animal in the table, otherwise returns the input.

If I'm allowed to respond to `cat` with `cat goes "hiss"` as in the list of animal sounds, I can pull off another 5 bytes.

-3 bytes thanks to Reinstate Monica.
> 0 votes

# Answer
# Japt, 18 bytes

```
r`^¯t$`È+` go ´ow

```

Try it
> 0 votes

# Answer
# Gema, 24 characters - 15 = 9

```
\Ac\Lat\Z=$0 goes "Meow"

```

`gema` works like a filter, so an empty `gema ''` is the same as `cat`.

To avoid using the word “cat” literally, inserted a pointless `\L` (turns on line mode, like an inline `-line` switch, meaning following arguments can't cross line boundary).

Sample run:

```
bash-5.0$ echo -n cat | gema '\Ac\Lat\Z=$0 goes "Meow"'
cat goes "Meow"

bash-5.0$ echo -n cats | gema '\Ac\Lat\Z=$0 goes "Meow"'
cats

```

Try it online!
> 0 votes

---
Tags: code-golf
---


title: The Unaverageables

text:
# Question
Title: The Unaverageables
Related.

Given a list of 3 or more positive integers, remove every number X for which there is another number Y in the list and the average of X and Y is also in the list. In other words, if X, Y, and the average of X and Y are all in the input, neither X nor Y should appear in the output.

Note: Pairs of numbers are not successively removed from the list, rather all at once. This avoids ambiguity. A pair of numbers whose average is in the list will be removed even if one or both of the numbers are already part of another such pair.

The average of two numbers is their sum divided by two.

Examples:

```
input => output
explanation

[1, 2, 3] => [2]
1 and 3 are removed because their average (2) is in the list.

[1, 2, 3, 4] => []
1 and 3 are removed because their average (2) is in the list,
2 and 4 are removed because their average (3) is in the list.

[1, 3, 4, 5] => [4]
1 and 5 are removed because their average (3) is in the list,
3 and 5 are removed because their average (4) is in the list.

[1, 5, 10, 20, 40] => [1, 5, 10, 20, 40]
No numbers are removed; No pair of numbers also has their average in the list.

[1, 5, 6, 10] => [1, 5, 6, 10]

[1, 2, 3, 4, 10, 52, 100, 200] => [10, 52, 200]

[1, 2, 3, 5, 8, 13, 21, 34] => []

```

You may assume numbers are given in ascending order with no duplicates.

Shortest code wins.

# Answer
# Jelly, ~~9~~ 7 bytes

```
+HfḊʋÐḟ

```

Try it online!

```
     Ðḟ    Remove elements for which
+          that element plus each element of the list
 H         halved
   Ḋ       has more than one element
  f ʋ      after being filtered to only elements of the original list.

```
> 8 votes

# Answer
# , 27 22 15 14 bytes

```
-.&,~:/~*+:-/]

```

Try it online!

Consider `1 3 4 5`.

* `+:-/]` We note that if `c = (a + b)/2`, then `2c - a = b`. So we can double the input, and create a subtraction table between that doubled input and the original input:

```
1 _1 _2 _3
5  3  2  1
7  5  4  3
9  7  6  5

```

Now any element in that table not on the diagonal is the `a` or `b` giving rise to a `c` in the original list, and thus invalid.
* `~:/~*` So zero out the diagonal:

```
0 _1 _2 _3
5  0  2  1
7  5  0  3
9  7  6  0

```
* `-.&,` Flatten, and then remove all the table elements from the original list:

```
4

```
> 6 votes

# Answer
# , ~~48~~ 46 bytes

```
\(v)v[!v%in%combn(v,2)[,combn(v,2,mean)%in%v]]
```

Attempt This Online!
> 6 votes

# Answer
# K (ngn/k), 17 bytes

```
{x^/x+(x-\:x)^'0}

```

Try it online!

Dang, Jonah's solution translates very well to K.

```
{x^/x+(x-\:x)^'0}
      (x-\:x)      self difference table
             ^'0   remove zeros from each row
    x+             add i-th item of x to i-th row of matrix above
 x^/               seeded reduce: remove all numbers that appear
                   in the matrix from x

```

---

# K (ngn/k), 22 bytes

```
{((*>^/^\+\2#,x-)')_x}

```

Try it online!

I think this idea is not touched well yet (or at least not explained well in other answers).

The idea here is: given an element E of list X, E is to be removed from the result if:

* there exists two other elements E2 and E3 of X such that E2 = (E + E3)/2
* ⇔ E, E2, E3 forms an arithmetic progression
* ⇔ E2 = E + k, E3 = E + 2k for some nonzero k
* ⇔ X-E (elementwise) contains k and 2k for some nonzero k

```
{((*>^/^\+\2#,x-)')_x}
{((             )')_x}  apply to each element E and keep those that gives 0
              x-    L = X-E
         +\2#,      (L, 2L)
     ^/^\           set intersection of L and 2L
   *>      first of grade down (index of max)
           all k's (including zero) are found in increasing order;
           index of max is nonzero iff there exist some nonzero k's

```
> 6 votes

# Answer
# 05AB1E, ~~10~~ 5 bytes

```
ʒ+;Ãg

```

Byte-count halved thanks to *@Steffan* by porting *@UnrelatedString*'s Jelly answer.

Try it online or verify all test cases.

**Explanation:**

```
ʒ      # Filter the (implicit) input-list by:
 +     #  Add the current value to each in the (implicit) input-list
  ;    #  Halve each
   Ã   #  Only keep those values from the (implicit) input-list
    g  #  Pop and push the length to get the amount of remaining values
       #  (only 1 is truthy in 05AB1E)
       # (after which the filtered result is output implicitly)

```
> 5 votes

# Answer
# Haskell, 39 bytes

```
f a=[x|x<-a,[1]==[1|z<-a,elem(2*z-x)a]]
```

Attempt This Online!

ovs and Wheat Wizard each saved a byte. Thanks!
> 5 votes

# Answer
# JavaScript (ES6), 50 bytes

```
a=>a.filter(x=>!a.some(y=>x-y&&a.includes(y*2-x)))

```

Try it online!

### Commented

```
a =>            // a[] = input
a.filter(x =>   // for each value x in a[]:
  !a.some(y =>  //   test whether there is a value y in a[]:
    x - y &&    //     which is not equal to x
    a.includes( //     and is the average of x and
      y * 2 - x //     another value 2y - x that exists in a[]
    )           //
  )             //   end of some()
)               // end of filter()

```
> 4 votes

# Answer
# K (ngn/k), 20 bytes

```
{x^/a*~=#a:-x-\:2*x}

```

Try it online!

Switched to @Jonah's approach.

-1 byte thanks to @ovs!

## Explanation

Input is *x*.

* `a:-x-\:2*x` subtraction table of 2*x* \- *x* stored as `a`
* `a*~=#` multiply *a* by inverse of eye of *a* (i.e. zero out *a*'s diagonals)
* `x^/` remove table elements from *x*
> 4 votes

# Answer
# Vyxal, ~~9~~ 7 bytes

```
'?+½?↔₃

```

Try it Online or verify all test cases.

*-2 bytes by porting Unrelated String's Jelly answer*

## How?

```
'?+½?↔₃
'       # Filter for:
 ?+     #  Add the input (vectorizes)
   ½    #  Halve each
    ?↔  #  Remove elements that are not in the input
      ₃ #  Is the length equal to 1?

```
> 3 votes

# Answer
# Scala, 52 bytes

```
s=>s.filter(i=>s.forall(j=>i==j|s.forall(_*2!=i+j)))

```

Try it online!
> 3 votes

# Answer
# Husk, ~~12~~ 10 bytes

```
f(εn¹Mo½+¹

```

Try it online!

```
f(          )  # filter the input to keep only elements that satisfy:
         ½+    # half the sum
       Mo  ¹   # with each other element of the input
    ε          # has only 1 element
     n¹        # shared with any elements of the input

```
> 3 votes

# Answer
# Python 3

## 58 bytes with unordered sets

*Thanx to Jitse!*

```
lambda l:{*l}-{a for a in l for b in{*l}-{a}if(a+b)/2in l}

```

Try it online!

## ~~62~~ 61 bytes with ordered lists

```
lambda l:[a for a in l if{(a+b)/2in l for b in{*l}-{a}}=={0}]

```

Try it online!
> 3 votes

# Answer
# Ruby, 39 bytes

```
->l{l-l.permutation(2).map{|a,b|a*2-b}}

```

Try it online!
> 3 votes

# Answer
# Nibbles, 7 bytes (14 nibbles)

```
|$~<<`&*2@+@_

```

```
|$~<<`&*2@+@_
|               # filter
 $              # input list
  ~             # keeping only elements that are falsy for
   <<           #   discard first element of
     `&         #   common elements of
       *2@      #     twice the input list
                #     and
          +@_   #   sum of this element and the input list

```

---

Works on the basis that if the average of X and Y is Z, then X+Y=2\*Z. So we just remove all Xs whenever there's a Y that when added to it gives twice one of the other elements of the input.

Step-by-step for input of `[1, 2, 3, 4, 10, 52, 100, 200]`:

```
|$              # for each element x in input=[1, 2, 3, 4, 10, 52, 100, 200]
  ~             # keep it if the following function returns an empty list (falsy):
     `&         #   find elements in common between:
       *2@      #      double the input: [2, 4, 6, 8, 20, 104, 200, 400]
                #   and:
          +@_   #      input + x:
                #         so, when x=1 => [2, 3, 4, 5, 11, 53, 101, 201]
                #               common elements = [2, 4]
                #             when x=10 => [11, 12, 13, 14, 20, 62, 110, 210]
                #               common elements = [20]
   <<           #   and remove the first element:
                #         so, when x=1 => [4] => so won't keep it
                #             when x=10 => [] => so we'll keep it

```
> 3 votes

# Answer
# Jelly, 10 bytes

```
ŒcSe¥ƇḤFḟ@

```

A monadic Link that accepts a list of positive integers and yields the filtered list.

**Try it online!**

### How?

```
ŒcSe¥ƇḤFḟ@ - Link: list L
Œc         - ordered pairs (L)
      Ḥ    - double (L) (vectorises)
     Ƈ     - filter the pairs keeping those for which:
    ¥      -   last two links as a dyad - f(pair, doubled L)
  S        -     sum (pair)
   e       -     exists in (doubled L)?
       F   - flatten (this list of pairs whose sum is in the doubled L)
         @ - with swapped arguments:
        ḟ  -   filter discard (take L and remove the pair elements)

```
> 2 votes

# Answer
# Factor \+ `math.unicode`, ~~57~~ ~~51~~ 50 bytes

```
[| s | s [ s n+v 2 v/n s ∩ length 1 > ] reject ]

```

Attempt This Online!
> 2 votes

# Answer
# Pyth, ~~12~~ 10 bytes

```
-Qs-L-LydQ

```

Try it online! or Verify all test cases

```
-Qs-L-LydQ
    L     (Q) # Left map over the implicit input with variable `d`:
      L  Q    #   Left map over the input with variable `k`:
     - yd     #     d*2 - k
   -          #   Remove d from the resulting list
  s           # Flatten
-Q            # Remove elements of the resulting list from the input

```

### 12-byte solutions

```
fqFf}-yYTQQQ

```

```
-Qsf}.OT-QT*

```
> 2 votes

# Answer
# Desmos, ~~80~~ 76 bytes

```
f(l)=l[[[(.5k-l)^2.minfork=l[m]+l[(L-m)^2>0]].minform=L]>0]
L=[1...l.length]

```

This is probably a terrible way of doing it, but whatever. Also, the "words" `minfork` and `minform` that appear in the code are very much intentional, though you will quickly see what they actually parse as in the graph links :P.

Try It On Desmos!

Try It On Desmos! - Prettified
> 2 votes

# Answer
# \[T-SQL\] 111 bytes

```
DELETE FROM T WHERE EXISTS(Select*From T Y Join T Z ON T.ID NOT IN(Y.ID,Z.ID)And Y.ID<>Z.ID And T.N+Y.N=2*Z.ID)

```

Formatted:

```
DELETE FROM T
WHERE EXISTS(
    Select *
    From T as Y
    Join T as Z
        ON T.ID NOT IN(Y.ID, Z.ID)
        And Y.ID <> Z.ID
        And T.N+Y.N = 2*Z.ID)

```

I *could* save one more byte by using the excremental SQL-89 joins, but my soul is worth more than one byte.
> 2 votes

# Answer
# Arturo, 41 bytes

```
$[a][a--map permutate.by:2a'p[-p\0*2p\1]]

```

Try it

Port of G B's Ruby answer.
> 2 votes

# Answer
# Thunno, \\$ 14\log\_{256}(96)\approx \\$ 11.52 bytes

```
gz0+2/z0sAqS2<

```

Attempt This Online!

#### Explanation

```
g   # Filter:
z0+ # Add input
2/  # Halve each
z0  # Push input again
sAq # Each is in the input?
S2< # Sum is less than 2?

```
> 2 votes

# Answer
# Pyt, 16 bytes

```
ĐĐ2*⇹ɐ-ĐŁřĐɐ≠*Ƒ\

```

Try it online!

Port of Jonah's J answer
> 2 votes

# Answer
# Julia 1.0, 32 bytes

```
!l=l[l.|>i->sum(i.+l.∈[2l])<2]

```

Try it online!
> 2 votes

# Answer
# PowerShell Core, 68 bytes

```
($a=$args)|?{$_-notin($a|%{$a-ne($c=$_)|%{$_,$c*(($_+$c)/2-in$a)}})}

```

Try it online!
> 2 votes

# Answer
# Charcoal, 16 bytes

```
ＩΦθ¬⊙θ∧⁻κμ№⊗θ⁺ιλ

```

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

```
  θ                 Input list
 Φ                  Filtered where
     θ              Input list
   ¬⊙               No elements satisfy
       ⁻κμ          Indices differ
      ∧             Logical And
            θ       Input list
           ⊗        Doubled
          №         Does not contain
             ⁺ιλ    Sum of current elements
Ｉ                   Cast to string
                    Implicitly print

```
> 1 votes

# Answer
# Burlesque, 26 bytes

```
Js12CB:U_f{avg1j~[}g1jFL\\

```

Try it online!

Takes input as block of doubles

```
J          # Duplicate
s1         # Store as 1
2CB        # Combinations of length 2
:U_        # Filter for unique (guaranteed safe by no dups)
f{avg1j~[} # Filter for average contained in original list (1)
g1         # Get 1
j          # Reorder stack
FL         # Flatten
\\         # Remove elements contained in (1) also in averages

```
> 1 votes

# Answer
# Haskell, 67 bytes

```
f a=[z|z<-a,not$elem z[x|x<-a,y<-a,x/=y,even$x+y,div(x+y)2`elem`a]]
```

Attempt This Online!
> 1 votes

# Answer
# Zsh, 75 bytes

```
for x;for y;((s=x+y,s%2||x==y))||a+=(${=${(M)@:#$[s/2]}:+$x $y})
<<<${@:|a}

```

Try it online!

Not as compact as I was expecting...

```
for x;for y   # for $x, $y in the Cartesian product of the list with itself
    ((s=x+y,s%2||x==y)) ||          # test if the sum is odd or x == y. If not,
    a+=(${=${(M)@:#$[s/2]}:+$x $y})
#          ${(M)@:#$[s/2]}          # substitute the average if found in $@
#       ${                :+$x $y}  # if non-empty, substitute "$x $y"
#   a+=(${=                      }) # split on spaces and add it to $a

<<<${@:|a}                          # set difference

```
> 1 votes

# Answer
# Python \+ NumPy, 50 bytes

```
lambda a:a[((a+[[a]]).T==a+a[:,1>0]).sum((0,1))<2]
```

Attempt This Online!

Straightforward masking with a few tricks to shorten the required indexing operations without having to explicitly import numpy.

#### How?

Construct 3d table of *z,y,x* each running through the input list *a*. Each cell is True if *2z=y+x* and False otherwise. Fixing *x=a* count solutions *z,y*. If *a* is not part of an averaging pair there is only solution *z=a,y=a*, otherwise there are more. Use boolean indexing to filter *a* accordingly.

`(a+[[a]]).T` is a shorter surrogate for `2*a[:,None,None]` and `a[:,1>0]` is shorter than the more natural `a[:,None]`.
> 1 votes

---
Tags: code-golf
---


title: Ragged list pattern matching, Part 2

text:
# Question
Title: Ragged list pattern matching, Part 2
*This is a sequel to Ragged list pattern matching. In this challenge, the wildcard may match a sequence of items of any length instead of just a single item.*

Given a pattern and a ragged list of integers, your task is to decide whether the pattern matches the ragged list.

The pattern is also represented by a ragged list. But in addition to positive integers, it may contain a wildcard value.

Here is the rule for matching:

* A positive integer matches the same positive integer.
* The wildcard value matches a sequence of items (integer or list) of any length, including the empty sequence.
* A ragged list matches a ragged list if each item in the pattern matches the corresponding item in the list.

For example, if we write the wildcard as `0`, then the pattern `[0, [4, [5], 0]]` matches the ragged list `[[1, 2], [3], [4, [5]]]`: here the first `0` matches the sequence `[1, 2], [3]`, and the second `0` matches the empty sequence.

You may choose any fixed value as the wildcard, as long as it is consistent.

This is , so the shortest code in bytes wins.

This is . You may use your language's convention for truthy/falsy, or use two distinct, fixed values to represent true or false.

## Testcases

Here I use `0` to represent the wildcard. The input here are given in the order `pattern, ragged list`.

### Truthy

```
[], []
[0], []
[0], [1, 2]
[0], [[[]]]
[0, 0], [1, 2, 3]
[1, 0], [1, [[2, 3]]]
[1, 0, 2], [1, 2, 2, 2]
[1, 0, [2, 3]], [1, [2, 3]]
[1, [2, 0], 4], [1, [2, 3], 4]
[0, [4, [5], 0]], [[1, 2], [3], [4, [5]]]

```

### Falsy

```
[1], []
[[]], []
[[0]], [3]
[[4]], [4]
[1, 0], [2, 1]
[[0]], [[1], [2]]
[1, 0, 2], [1, 2, 3]
[1, 0, 2, 0], [1, [3, 2, 3]]
[1, [0, 2], 4], [1, [2, 3], 4]
[[0], [4, [5], 0]], [[1, 2], [3], [4, [5]]]

```

# Answer
# Retina, 71 bytes

```
>
,>
<,
<
~(L$`^.+
\n$&$
_,
(\d+,|<((?<_><)|(?<-_>>)|\d|,)+(?(_)^)>,)$*

```

Try it online! Takes two newline-separated \<\>-wrapped lists but link is to test suite that deletes spaces, splits on semicolons and converts other types of brackets for convenience. Uses _ to represent the wild card. Explanation: Based on my Retina answer to Ragged list pattern matching.

```
>
,>
<,
<

```

Ensure that non-empty lists end in a comma.

```
~(

```

Evaluate the result of the transformations below on the comma-safe input. Since they result in a single line, this makes Retina attempt to match the comma-safe input against the result.

```
L$`^.+
\n$&$

```

Take only the first line of the input and wrap it in `\n` and `$` so that it will match against the second line of the input.

```
_,
(\d+,|<((?<_><)|(?<-_>>)|\d|,)+(?(_)^)>,)$*

```

Replace each `_,` with a match against any number (`$*` represents a literal `*` which would otherwise be the string repetition operator) of comma-safe non-negative integers or lists, using a .NET balancing group to ensure that the lists are properly balanced. A named capturing group `?<_>` is used here because .NET allows capturing groups to be reused in this way and it's golfier than calculating the capturing group number.
> 1 votes

# Answer
# Haskell, 89 bytes

**Assumption**: ragged lists are defined in the following way:

```
data RL a = L [RL a] | N a | W
  deriving Eq

```

**Solution**:

```
L(W:p)#L x|L p#L x=1>0
L(W:p)#L(_:x)=L(W:p)#L x
L(q:p)#L(y:x)=q#y&&L p#L x
a#b=a==W||a==b

```

Attempt This Online!
> 1 votes

---
Tags: code-golf, decision-problem, ragged-list, pattern-matching
---


title: Produce a m*n table in HTML

text:
# Question
Title: Produce a m*n table in HTML
# Input :

Two decimal integers `m` and `n` that respectively give the number of rows and columns of the table. `m` and `n` are greater than or equal to 1.

# Output :

A table in HTML that has m rows and n columns.

The table should be displayable by a modern browser of your choice. Most browsers will display everything properly even if tags are not closed. Proper indentation and spacing is optional.

There should be at least one (non-whitespace) printable character in each cell.

**Cells on the first line should use `<th>` tags while the ones on the following lines should use `<td>`tags.**

# Win condition :

This is so the shortest source-code for each language wins.

### Input example :

```
2 3

```

### Output example :

```
<table>
 <tr>
   <th>A</th>
   <th>A</th>
   <th>A</th>
 </tr>
 <tr>
   <td>A</td>
   <td>A</td>
   <td>A</td>
 </tr>
</table>

```

or : `<table><tr><th>A<th>A<th>A<tr><td>A<td>A<td>A`

# Answer
# APL (Dyalog Unicode) with MiServer 3.0, ~~31~~ 30 bytesSBCS

Full program. Prompts stdin for the two-element list `[m,n]` and prints strict XHTML to stdout.

```
(⎕NEW _.Table((⎕⍴0)⍬1)).Render

```

Example session:

```
      )xload C:\Users\Adam.DYALOG\Documents\MiServer\miserver.dws
C:\Users\Adam.DYALOG\Documents\MiServer\miserver.dws saved Wed Mar  7 17:19:40 2018
      Load ''
Development environment loaded
MiSite "C:/Users/Adam.DYALOG/Documents/MiServer/MS3/" loaded
      (⎕NEW _.Table((⎕⍴0)⍬1)).Render
⎕:
      2 3
<table id="id691498143"><thead><tr><th>0</th><th>0</th><th>0</th></tr></thead><tbody><tr><td>0</td><td>0</td><td>0</td></tr></tbody></table>

```

Try it online!

Explanation:

`(``).Render` Render the following HTML element:

`⎕NEW _.Table (``)` a new Table with the following parameters:

`(``) ⍬ 1` the following content, no special styling, 1 header row:

`⎕⍴0` evaluated input reshapes zero (i.e. an m-row, n-column matrix of zeros)
> 7 votes

# Answer
# JavaScript (ES6), 70 bytes

*Saved 2 bytes thanks to @RickHitchcock*

Takes input in currying syntax `(m)(n)`.

```
m=>n=>'<table>'+(g=c=>'<tr>'+`<t${c}>A`.repeat(n))`h`+g`d`.repeat(m-1)

```

Try it online!

### Demo

```
f=

m=>n=>'<table>'+(g=c=>'<tr>'+`<t${c}>A`.repeat(n))`h`+g`d`.repeat(m-1)

O.innerHTML = f(2)(3)
```

```
<div id=O></div>
```
> 7 votes

# Answer
# Canvas, 31 bytes

```
<ŗ>
table⁸ｏ╶［tr⁸⁶｛¹１≡╵dh＠t×⁸；｝］

```

Try it here! or Try it visualized!

After fixing 2 bugs (ಠ\_ಠ) in the interpreter, 30 bytes works too
> 5 votes

# Answer
# Python 2, 57 bytes

```
lambda m,n:'<table><tr>'+'<th>A'*n+('<tr>'+'<td>A'*n)*~-m

```

Try it online! Assumes `m` isn't zero.
> 5 votes

# Answer
# 05AB1E, 30 bytes

```
’<…È>’sF"<tr>"„hdNĀè"<tÿ>A"I×J

```

Try it online!

**Explanation**

```
’<…È>’                           # push "<table>"
      sF                         # no-of-rows times do:
        "<tr>"                   # push "<tr>"
              „hd                # push "hd"
                 NĀ              # push the iteration counter truthified
                   è             # index into the 2-char string with this
                    "<tÿ>A"      # insert the result into the string "<tÿ>A" instead of ÿ
                           I×    # repeat this string no-of-columns times
                             J   # join the stack to a single string

```
> 3 votes

# Answer
# JavaScript, 65 bytes

```
f=(m,n)=>m?f(--m,n)+'<tr>'+`<t${m?'d':'h'}>x`.repeat(n):'<table>'

document.write(f(4,3));
```
> 3 votes

# Answer
# Java 10, ~~139~~ ~~133~~ 102 bytes

```
m->n->{var r="<table>";for(int j=0,i;j++<m;)for(r+="<tr>",i=n;i-->0;r+=j<2?"<th>A":"<td>B");return r;}

```

Try it online.

**Explanation:**

```
n->m->{                  // Method with two integer parameters and String return-type
  var r="<table>";       //  Result-String, starting at "<table>"
  for(int j=0,i;j++<m;)  //  Loop `j` over the rows in the range [0, `m`)
    for(r+="<tr>",       //   Append "<tr>" to the result
        i=n;i-->0;       //   Inner loop `i` over the columns in the range [`n`, 0)
      r+=j<2?            //    If `j` is 1 (first iteration):
          "<th>A"        //     Append "<th>A" to the result
         :               //    Else:
          "<td>B");      //     Append "<td>B" to the result
  return r;}             //  Return the result

```
> 2 votes

# Answer
# C (gcc), ~~107~~ ~~99~~ ~~98~~ 97 bytes

```
i;f(x,y){char s[]="<th>A";for(puts("<table><tr>");x--;s[2]=96+puts("<tr>"))for(i=y;i--;)puts(s);}

```

Try it online!

-8 bytes thanks to potato

-2 bytes thanks to ceilingcat

The `s` array has to be declared as an array not a pointer otherwise it won't be editable (we set the first h to a d). Most browsers don't even care if your closing tag is correct, so we just close all tags with `</t>`.
> 2 votes

# Answer
# APL (Dyalog Unicode), ~~42~~ 38 bytesSBCS

-4 thanks to ngn.

Full program. Prompts stdin for the two-element list \[m,n\] and prints unclosed tags to stdout.

```
'<table>',∊'<tr>',⍤1{'d'}@3⍀⎕⍴⊂'<th>A'

```

Try it online!

`⊂'<th>A'` enclose this string to treat it as a whole

`⎕⍴` prompt for dimensions and cyclically **r**eshape the single cell to a matrix of that size

`…⍀` cumulatively insert the following function between each vertical pair of cells:

`{'d'}@3` ignore upper cell; place `d` at 3rd position in bottom cell

`'<tr>',⍤1` prepend this string each row

**ϵ**nlist (flatten)

`'<table>',` prepend this string
> 2 votes

# Answer
# , 73 bytes

```
function(n,m)cat("<table><tr>","<th>A"<m,c("<tr>","<td>A"<m)<n-1)
"<"=rep

```

Try it online!

Saved 7 bytes with a dirty hack - replace "rep" by "\<".
> 2 votes

# Answer
# Stax, 28 bytes

```
üÉ$♠═?S┼╪├8°‼←sí☼←T≡┴╜ô‼\↑0ⁿ

```

Run and debug it

Unpacked, ungolfed, and commented, it looks like this.

```
"<table>"P  print "table"
"<th>A"*    "<th>A" repeated specified number of times
,D          repeat the rest of the program specified number of times
  "<tr>"p   print "<tr>" with no newline
  Q         print top of stack without popping
  .hd|t     replace "h" with "d"

```

Run this one
> 2 votes

# Answer
# PowerShell Core, ~~72~~ 68 bytes

```
Function F($m,$n){'<table><tr>'+'<th>A'*$n+('<tr>'+'<td>A'*$n)*--$m}

```

Try it online!

Here are my test cases and expected outputs (C.f., TIO)

* m=2; n=3 `<table><tr><th>A<th>A<th>A<tr><td>A<td>A<td>A`
* m=1; n=3 `<table><tr><th>A<th>A<th>A`
* m=4; n=2 `<table><tr><th>A<th>A<tr><td>A<td>A<tr><td>A<td>A<tr><td>A<td>A`
* m=2; n=8 `<table><tr><th>A<th>A<th>A<th>A<th>A<th>A<th>A<th>A<tr><td>A<td>A<td>A<td>A<td>A<td>A<td>A<td>A`

Thanks, @mazzy, for the -4 bytes!
> 2 votes

# Answer
# Nibbles, ~~24 23.5 22~~ 21.5 bytes

```
;~"able"::"<t"$">".`,_:@"r"^_:@?$"d" "h"

```

Attempt This Online!

Takes arguments in the order `cols rows`. Outputs something like this (for `8 5`):

```
<table><tr><th>0<th>0<th>0<th>0<th>0<th>0<th>0<th>0
<tr><td>1<td>1<td>1<td>1<td>1<td>1<td>1<td>1
<tr><td>2<td>2<td>2<td>2<td>2<td>2<td>2<td>2
<tr><td>3<td>3<td>3<td>3<td>3<td>3<td>3<td>3
<tr><td>4<td>4<td>4<td>4<td>4<td>4<td>4<td>4

```

## Explanation

```
;~     Define function f(str)
"able"  and call it with str = "able":
:       join
:        join
"<t"      "<t"
$         str
">"      ">"
.      Map
`,      0...
_        number of rows
:       join
@        f
"r"       "r"
^        repeat
_         number of columns
:         join
@          f
?           if
$            row index is positive
"d"          then "d"
"h"          else "h"
           row index

```
> 2 votes

# Answer
# APL+WIN, ~~68 63~~ 56 bytes

12 bytes in total saved thanks to Adám

Prompts for number of rows followed by number of columns and outputs non-closure option:

```
t←⊂'<tr>'⋄'<table>'t(n⍴⊂'<th>A'),,t,((⎕-1),n←⎕)⍴⊂'<td>A'

```
> 1 votes

# Answer
# Retina, ~~56~~ 54 bytes

```
(.+) (.+)
<table>$1*$(<tr>$2*$(<td>@
T`\d`\h`^.*?r.*?r

```

Try it online! Edit: Saved 2 bytes thanks to @CowsQuack. Explanation: The first stage uses Retina 1's string multiplication first to generate the appropriate number of cells, then to generate the appropriate number of rows. The second stage then changes the first row of `td`s into `th`s.
> 1 votes

# Answer
# Haskell, ~~109~~ ~~107~~ 103 bytes

```
n!i="<t"++n++'>':i++"</t"++n++">"
r#c="able"!("r"!([1..c]*>"h"!"H")++([2..r]*>("r"!([1..c]*>"d"!"A"))))

```

So many parentheses… Thanks to @nimi for two bytes (and a loss of genericity)!

Try it online!

Without end tags the straight implementation wins at 87 bytes (Try it online):

```
r?c="<table><tr>"++([1..c]*>"<th>H")++([2..r]*>("<tr>"++([1..c]*>"<td>A")))++"</table>"

```
> 1 votes

# Answer
# Perl 5 `-p`, ~~65~~ 54 bytes

*-11 bytes thanks to @msh2108's reminder*

```
/ /;$_="<table><tr>"."<th>A"x$'.('<tr>'.'<td>B'x$')x$`

```

Try it online!
> 1 votes

# Answer
# Carrot, ~~77~~ 51 bytes

```
<th>A^*$v<tr>vl+(^h)*($^F- 1)A"h"S"d"h+(^l)v<table>

```

(While working on this, I discovered a bug with `h` not working and fixed it)

Golfed some bytes by shortening the html as well as using "split, join" instead of "replace"

Try it online!, use the command-line option `-d` to see the AST (Note: this uses the new node interpreter, so the older version on the website cannot run this.)

This program takes the input 0-indexed and in reversed order, because of Carrot's weird nature, thus `3 2` printing a 3×4 table.

Run the program like so, `./carrot -f prog.carrot input.txt`

Basically creates the header row, then the data rows on another cell of the garden (2D tape), and concatenates them together.

---

Carrot works on a 2D tape, called a garden. Each cell on the garden is made up of three stack modes, string, float, array. There is a value for each mode, called a "stack" (note: misnomer). These stacks begin empty. When a cell is at a particular mode, the following commands will affect the stack that corresponds to this mode, for example in float mode, the operations will affect the stack float. And of course, there are commands for switching between modes. The modes are important because each operator can be overloaded for each mode and each argument type.

In addition, there are two additional modes (these only affect the commands, not the stack directly), normal mode and caret mode. Normal mode works normally, where there are operators taking in arguments and affecting the stack directly. In caret mode, (almost) every character is interpreted literally as a string, and is later prepended/appended accordingly to the stack. Caret mode is started/ended with carets (append) or down-carets (prepend).

Carrot begins in a cell on the garden, in stack-string mode, and in caret mode.

---

Beginning in caret-mode, the string `<th>A` is added to the initially empty stack-string. Then follows the `*` command that duplicates it `$`, the input, times. Then `<tr>` is prepended to the stack-string by the usage of the down-caret `v`. This creates the header row of the table.

To create the data rows, we duplicate the header to another cell. `l` moves the IP to the right empty cell, and `+` appends `(^h)` the string in the cell to the left (essentially copying it to the cell on the right). `()` starts a subshell, a new Carrot program with almost the same tape, and `^` exits out of caret-mode so that we can `h` get the string in the left cell. This is then `*` duplicated by `($^F- 1)`, the next input minus 1, times.

Still in the right cell, `A` sets the array of this cell to its stack- tring split by `"h"`. `S` joins the stack array by `"d"` and sets the stack string to this value. `A"h"S"d"` really just replaces `h`s with `d`s to form the data rows. Now `h` we move to the left starting cell.

Now we append the stack string of the cell to the right to this cell using `+(^l)`. All that's remaining is to add the `<table>` tag, so we do this by `v` prepending it.
> 1 votes

# Answer
# Charcoal, 33 bytes

```
<table><tr>×<th>AηＦ⊖θ«<tr>×<td>Aη

```

Try it online!

### Explanation

```
<table><tr>                         Print "<table><tr>"
           ×<th>Aη                  Print "<th>A" * second input
                  Ｆ⊖θ«            For i in (implicit) range over first input
                        <tr>        Print("<tr>")
                            ×<td>Aη Print("<td>A") * second input

```
> 1 votes

# Answer
# K, 58 bytes

K version is whatever is included in `KDB+ 3.5 2017.11.30`.

Port of the Python answer above. Ends up being 1 byte longer due to having to enlist and flatten multiple times.

```
{,/"<table><tr>",(y#,"<th>A"),(x-1)#,("<tr>",/y#,"<td>A")}

```
> 1 votes

# Answer
# C# (.NET Core), 130 bytes

```
m=>n=>{var r="<table>";for(int i=0;i++<m;)r+="<tr>"+string.Concat(System.Linq.Enumerable.Repeat(i<2?"<th>H":"<td>D",n));return r;}

```

Try it online!
> 1 votes

# Answer
# Powershell, 63 bytes

```
$m,$n=$args;$t='h';'<table>';1..$m|%{'<tr>'+"<t$t>A"*$n;$t='d'}

```

save it as `new-mntable.ps1`. Test script:

```
.\new-mntable.ps1 2 3
.\new-mntable.ps1 1 3
.\new-mntable.ps1 4 2
.\new-mntable.ps1 2 8

```

output (extra spaces are optional):

```
<table>
<tr><th>A<th>A<th>A
<tr><td>A<td>A<td>A
<table>
<tr><th>A<th>A<th>A
<table>
<tr><th>A<th>A
<tr><td>A<td>A
<tr><td>A<td>A
<tr><td>A<td>A
<table>
<tr><th>A<th>A<th>A<th>A<th>A<th>A<th>A<th>A
<tr><td>A<td>A<td>A<td>A<td>A<td>A<td>A<td>A

```

---

# Powershell, 65 bytes, `-replace`

```
'<table>h'+'d'*--$args[0]-replace'h|d',('<tr>'+'<t$0>A'*$args[1])

```

save it as `new-mntable.ps1`. Test script:

```
.\new-mntable.ps1 2 3
.\new-mntable.ps1 1 3
.\new-mntable.ps1 4 2
.\new-mntable.ps1 2 8

```

output:

```
<table><tr><th>A<th>A<th>A<tr><td>A<td>A<td>A
<table><tr><th>A<th>A<th>A
<table><tr><th>A<th>A<tr><td>A<td>A<tr><td>A<td>A<tr><td>A<td>A
<table><tr><th>A<th>A<th>A<th>A<th>A<th>A<th>A<th>A<tr><td>A<td>A<td>A<td>A<td>A<td>A<td>A<td>A

```

How it work:

1. `'<table>h'+'d'*--$args[0]` \- create a string like `<table>hddd...`
2. `'h|d'`\- search `h` or `d` chars in the string for replacing
3. `'<tr>'+'<t$0>A'*$args[1]` \- replace each char with string like `<tr><t$0>A<t$0>A...`
4. where `$0` is a captured `group[0]` \- the char in the `-replace`.

---

# Powershell, 65 bytes, `scriptblock`

```
$m,$n=$args;'<table>';&($r={'<tr>'+"<t$args>A"*$n})h;(&$r d)*--$m

```

save it as `new-mntable.ps1`. Test script:

```
.\new-mntable.ps1 2 3
.\new-mntable.ps1 1 3
.\new-mntable.ps1 4 2
.\new-mntable.ps1 2 8

```

output:

```
<table>
<tr><th>A<th>A<th>A
<tr><td>A<td>A<td>A
<table>
<tr><th>A<th>A<th>A

<table>
<tr><th>A<th>A
<tr><td>A<td>A<tr><td>A<td>A<tr><td>A<td>A
<table>
<tr><th>A<th>A<th>A<th>A<th>A<th>A<th>A<th>A
<tr><td>A<td>A<td>A<td>A<td>A<td>A<td>A<td>A

```
> 1 votes

# Answer
# Vyxal, 34 bytes

```
`<∨ø>`?(`<tr>`‛hdn1>i`<t%>A`$%⁰*Wṅ

```

Try it Online!

Port of Emigna's 05AB1E answer.

#### Explanation

```
`<∨ø>`         # Push "<table>"
      ?(       # Input number of times:
        `<tr>` #  Push "<tr>
‛hd            #  Push "hd"
   n1>         #  Is the loop variable
               #  greater than 1?
      i        #  Index into "hd"
       `<t%>A` #  Push "<t%>A"
$%             #  Replace "%" with
               #  either "h" or "d"
   ⁰*          #  Multiply this string
               #  by the second input
     Wṅ        #  Join the stack into a string
               #  Implicit output

```
> 1 votes

# Answer
# Go, ~~130~~ 123 bytes

```
func f(r,c int)(s string){for d,i:="<th>A",0;i<r;i++{if i>0{d="<td>A"}
s+="<tr>"
for j:=0;j<c;j++{s+=d}}
return"<table>"+s}

```

Attempt This Online!

* -7 bytes from removing unused variable, condensing string literals (@xigoi)
> 1 votes

# Answer
# Jelly,  ~~33~~  32 bytes

```
“<td>A”ẋ”h3¦s5ẋ€ṭ€“<tr>”ṭ“¢ssɱU»

```

A full program taking `rows`, `columns` which prints the result.

**Try it online!**

---

hmm, also 32 using a table:

```
Ịị⁾hdṭ”t⁾<>j;ðþZṭ€“<tr>”ṭ“¢ssɱU»

```
> 0 votes

# Answer
# Dart, 45 63 bytes

### Working solution:

```
(m,n){print('<table><tr>'+'<th>A'*n+('<tr>'+'<td>A'*n)*(m-1));}

```

Try it online here!

Lambda/anonymous function taking `m` and `n` as parameters, displays output to `STDOUT`.

Since tables with unclosed `<table>`, `<tr>`, `<th>`, and `<td>` tags still render in modern browsers (ex., Chrome), the output is valid.

### Old (broken) solution:

My first attempt forgot to switch to `<td>` after the first row:

```
(m,n){print('<table><tr>'+'<th>A'*n+('<tr>'+'<th>A'*n)*(m-1));}

```

Thanks to @Lynn for pointing that out.
> 0 votes

# Answer
# Pyth, 40 bytes

```
J"<tr>"AQ"<table>"J*H"<th>A"*tGJ*H"<td>A

```

Try it online!
> 0 votes

# Answer
# Google Sheets, 66 bytes

```
="<table><tr>"&Rept("<th>A",B1)&Rept("<tr>"&Rept("<td>A",B1),A1-1)

```

Input is in cell `A1` and `B1`.
There's nothing fancy, really; it's just nested `Rept` functions.
It *does* assume `m > n > 0` and that they're both integers.
> 0 votes

# Answer
# J, 64 bytes

Another port of the Python answer:

```
4 :0
'<table><tr>',(;y#<'<th>A'),;(<:x)#<('<tr>',(;y#<'<td>A'))
)

```
> 0 votes

# Answer
## PHP, 161 Bytes

Try it online

**Code**

```
function f($m,$n){$t=["table>","th>","td>","tr>","</"];echo strtr("
<0<3".str_repeat("<1A41",$n)."43".str_repeat("<3".str_repeat("
<2A42",$n)."43",$m-1)."40",$t);}

```

**Explanation**

```
function f($m,$n){
  $t=["table>","th>","td>","tr>","</"];           //array representing the tags its created
  echo strtr("<0<3".str_repeat("<1A41",$n)."43"   //strtr it's called and uses
                                                  //the array to replace values
           .str_repeat("<3".                      //repeat the tags
                         str_repeat("<2A42",$n)   //repeat the tags again
                            ."43",$m-1)."40",$t);
   //its repeated m-1 times because head is counted as one row
  }

```

## PHP, 193 Bytes

Full table structure forgot `<tfooter>` `<thead>, <tbody>..etc..`

Try example of the function

```
function f($m,$n)   {$t=["table>","thead>","tbody>","th>","td>","tbody>","tr>"];
echo strtr(
      "<0<1".str_repeat("<3A</3",$n).
      "</1<2".str_repeat(
                  "<6".str_repeat("<4A</4",$n)
                       ."</6",$m-1)."</2</0",
  $t);
  }

```

**Explanation**

`$t=["table>","thead>","tbody>","th>","td>","tbody>","tr>"];`

An array with all the tags for the table it's builded and then with `str_repeat` a number refering to an index in the array is written, **then** to `strtr` the string plus the array is passed
> 0 votes

# Answer
# Yabasic, 124 bytes

An anonymous function that takes input from as space delimited integers and outputs to the console.

```
?"<table>"
input""i,j
For c=1To i
?"<tr>"
For r=1To j
If c=1?"<th>H</th>"
If c>1?"<td>D</td>"
Next
?"</tr>"
Next
?"</table>"

```

Try it online!
> 0 votes

# Answer
# Forth (gforth), 86 bytes

```
: f ." <table>" 0 do ." <tr>" dup 0 do j if ." <td>A" else ." <th>A" then loop loop ;

```

Try it online!

### Explanation

```
." <table>"         \ output <table>
0 do                \ start loop from 0 to m-1
   ." <tr>"         \ output <tr>
   dup 0 do         \ duplicate n and loop from 0 to n-1
      j if          \ if the outer loop index is true (not 0)
         ." <td>A"  \ output <td>A
      else          \ if outer loop index is false (0)
         ." <th>A"  \ output <th>A
      then          \ end if-else
   loop             \ end inner loop
loop                \ end outer loop

```
> 0 votes

# Answer
# K (ngn/k), 51 bytes

```
{"<table>",/"<tr>",//:y#'(,,"<th>A"),1_x#,,"<td>A"}

```

Try it online!
> 0 votes

# Answer
# Japt `-P`, ~~34~~ 33 bytes

```
Æ"<tr>"+"<t{XÎgdih}>A"pVÃu`<ta½e>

```

Try it

-1 thanks to a clever trick by Shaggy

```
Æ             # the range [0, #cols) with each X mapped to:
  "<tr>"+     #   "<tr>" prepended to
  "<t{        #     "<t" prepended to
    XÎgdih    #       index into "dh" with the sign of X
  }>A"        #     append ">A"
  pV          #     repeated #rows times
Ã             # end map over range
u`<ta½e>      # prepend the compressed string "<table>

```
> 0 votes

---
Tags: code-golf, code-generation
---