text
stringlengths 180
608k
|
---|
[Question]
[
Ever wonder what countries surround another? I do too, sometimes, and, well, here's the challenge for it.
I have provided a list of countries and the countries that they touch that you must recognize at the bottom of this post in a code block. You need to create a full program that outputs (in the most convenient way possible in your language) the list of countries layers of adjacent countries to an input country. So, for example:
```
>>> "United Kingdom" 1
Republic of Ireland
```
Because `"United Kingdom"` is the country name and `1` is the number of layers that you want to make. In fact, any number of layers (except 0) will return `Republic of Ireland`, because there's a sea in the way of getting to any other countries.
Reference Map:
[](https://i.stack.imgur.com/n1kwH.jpg)
Examples (anything in parenthesis are comments) (obviously, order of output does not matter):
```
>>> Bhutan 2
India (layer 1, touching Bhutan)
China (layer 1, touching Bhutan)
Bangladesh (layer 2, touching India)
Myanmar (layer 2, touching China and India)
Laos (layer 2, touching China)
Vietnam (layer 2, touching China)
North Korea (layer 2, touching China)
Russia (layer 2, touching China)
Mongolia (layer 2, touching China)
Kazakstan (layer 2, touching China)
Uzbekistan (layer 2, touching China)
Afganistan (layer 2, touching China)
Pakistan (layer 2, touching China and India)
Kashmir (layer 2, touching China and India)
Nepal (layer 2, touching China and India)
```
```
>>> Russia 0 (no layers used)
```
```
>>> Cyprus 1800 (there's a sea in the way)
```
```
>>> "The Gambia" 4 (there's a sea in the way)
Senegal (layer 1)
Mauritania (layer 2)
Mali (layer 2)
Guinea (layer 2)
Guinea-Bissau (layer 2)
Sierra Leone (layer 3)
Liberia (layer 3)
Cote D'Ivoire (layer 3)
Burkina Faso (layer 3)
Niger (layer 3)
Algeria (layer 3)
Western Sahara (layer 3)
Morocco (layer 4)
Tunisia (layer 4)
Libya (layer 4)
Chad (layer 4)
Nigeria (layer 4)
Benin (layer 4)
Togo (layer 4)
Ghana (layer 4)
```
Because the world is big, you must compensate by making your code small. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), after all.
Touching List (in no particular order, in hopefully a parseable format) (if there are mistakes in here, *please let me know*. I've gone through it many times, but I'm bound to have made a few mistakes):
```
USA touches: Canada, Mexico
Canada touches: USA
Mexico touches: USA, Belize, Guatemala
Guatemala touches: Mexico, Belize, El Salvador, Honduras
Belize touches: Mexico, Guatemala
El Salvador touches: Guatemala, Honduras
Honduras touches: Guatemala, El Salvador, Nicaragua
Nicaragua touches: Honduras, San Jose
San Jose touches: Nicaragua, Panama
Panama touches: San Jose, Columbia
Columbia touches: Venezuela, Brazil, Peru, Ecuador, Panama
Venezuela touches: Columbia, Brazil, Guyana
Guyana touches: Venezuela, Brazil, Suriname
Suriname touches: Guyana, Brazil, French Guiana
French Guiana touches: Suriname, Brazil
Brazil touches: Columbia, Venezuela, Guyana, Suriname, French Guiana, Peru, Bolivia, Paraguay, Argentina, Uruguay
Ecuador touches: Columbia, Peru
Peru touches: Ecuador, Columbia, Brazil, Bolivia, Chile
Bolivia touches: Peru, Brazil, Paraguay, Argentina, Chile
Chile touches: Peru, Bolivia, Argentina
Paraguay touches: Bolivia, Brazil, Argentina
Argentina touches: Chile, Bolivia, Paraguay, Brazil, Uruguay
Uruguay touches: Argentina, Brazil
The Bahamas touches:
Cuba touches:
Jamaica touches:
Haiti touches: Dominican Republic
Dominican Republic touches: Haiti
Puerto Rico touches:
Saint Kitts and Nevis touches:
Montserrat touches:
Guadeloupe touches:
Dominica touches:
Martinique touches:
Saint Vincent touches:
Barbados touches:
Trinidad and Tobago touches:
Greenland touches:
Azores touches:
Falkland Islands touches:
South Georgia touches:
Cape Verde touches:
Madeira Island touches:
Canary Islands touches:
Faroe Islands touches:
Republic of Ireland touches: United Kingdom
United Kingdom touches: Republic of Ireland
Svalbard touches:
Norway touches: Sweden, Finland, Russia
Sweden touches: Norway, Finland
Finland touches: Sweden, Norway, Russia
Russia touches: Norway, Finland, Estonia, Latvia, Belarus, Ukraine, Turkey, Armenia, Azerbaijan, Kazakhstan, China, Mongolia, North Korea
Denmark touches: Germany
Estonia touches: Russia, Latvia
Latvia touches: Estonia, Russia, Belarus, Lithuania
Lithuania touches: Latvia, Belarus, Poland
Belarus touches: Lithuania, Latvia, Russia, Ukraine, Poland
Germany touches: Luxembourg, Belgium, Netherlands, Denmark, Poland, Czech Republic, Austria, Liechtenstein, Switzerland, France
Netherlands touches: Germany, Belgium
Belgium touches: France, Netherlands, Germany, Luxembourg
Luxembourg touches: France, Belgium, Germany
Poland touches: Germany, Lithuania, Belarus, Ukraine, Slovakia, Czech Republic
Ukraine touches: Slovakia, Poland, Belarus, Russia, Romania, Moldova, Hungary
Czech Republic touches: Germany, Poland, Slovakia, Austria
Slovakia touches: Austria, Czech Republic, Poland, Ukraine, Hungary
Moldova touches: Ukraine, Romania
Romania touches: Hungary, Ukraine, Moldova, Bulgaria, Serbia
Hungary touches: Austria, Slovakia, Ukraine, Romania, Serbia, Croatia, Slovenia
Austria touches: Liechtenstein, Germany, Czech Republic, Slovakia, Hungary, Slovenia, Italy, Switzerland
Liechtenstein touches: Switzerland, Germany, Austria
France touches: Belgium, Luxembourg, Germany, Switzerland, Italy, Spain
Switzerland touches: France, Germany, Liechtenstein, Austria, Italy
Slovenia touches: Italy, Austria, Hungary, Croatia
Croatia touches: Slovenia, Hungary, Serbia, Bosnia and Herzegovina
Bosnia and Herzegovina touches: Croatia, Serbia, Montenegro
Serbia touches: Bosnia and Herzegovina, Croatia, Hungary, Romania, Bulgaria, Macedonia, Albania, Montenegro
Bulgaria touches: Serbia, Romania, Turkey, Greece, Macedonia
Montenegro touches: Bosnia and Herzegovina, Serbia, Albania
Albania touches: Montenegro, Serbia, Macedonia, Greece
Macedonia touches: Albania, Serbia, Bulgaria, Greece
Italy touches: France, Switzerland, Austria, Slovenia
Spain touches: Portugal, France
Portugal touches: Spain
Greece touches: Albania, Macedonia, Bulgaria, Turkey
Turkey touches: Greece, Russia, Armenia, Azerbaijan, Iran, Iraq, Syria, Bulgaria
Malta touches:
Cyprus touches:
Armenia touches: Turkey, Russia, Azerbaijan, Iran
Azerbaijan touches: Turkey, Armenia, Russia, Iran
Kazakhstan touches: Russia, China, Uzbekistan, Turkmenistan
Mongolia touches: China, Russia
North Korea touches: China, Russia, South Korea
South Korea touches: North Korea
China touches: Afghanistan, Uzbekistan, Kazakhstan, Russia, Mongolia, North Korea, Vietnam, Laos, Myanmar, India, Bhutan, Nepal, Kashmir
Uzbekistan touches: Kazakhstan, China, Afghanistan, Turkmenistan
Afghanistan touches: Iran, Turkmenistan, Uzbekistan, China, Kashmir, Pakistan
Turkmenistan touches: Kazakhstan, Uzbekistan, Afghanistan, Iran
Iran touches: Iraq, Turkey, Azerbaijan, Armenia, Turkmenistan, Afghanistan, Pakistan
Iraq touches: Jordan, Syria, Turkey, Iran, Kuwait, Saudi Arabia
Syria touches: Lebanon, Turkey, Iraq, Jordan, Israel
Lebanon touches: Israel, Syria
Israel touches: Egypt, Lebanon, Syria, Jordan
Jordan touches: Israel, Syria, Iraq, Saudi Arabia
Saudi Arabia touches: Jordan, Iraq, Kuwait, Qatar, United Arab Emirates, Oman, Yemen
Kuwait touches: Iraq, Saudi Arabia
Qatar touches: Saudi Arabia
United Arab Emirates touches: Saudi Arabia, Oman
Oman touches: Saudi Arabia, United Arab Emirates, Yemen
Yemen touches: Saudi Arabia, Oman
Pakistan touches: Iran, Afghanistan, Kashmir, India
Kashmir touches: Pakistan, Afghanistan, China, India
India touches: Pakistan, Kashmir, Nepal, Bhutan, Myanmar, Bangladesh, China
Nepal touches: India, China
Bhutan touches: India, China
Bangladesh touches: India, Myanmar
Sri Lanka touches:
Adaman and Nicobar Islands touches:
Myanmar touches: Bangladesh, India, China, Laos, Thailand
Thailand touches: Myanmar, Laos, Cambodia, Malaysia
Laos touches: Myanmar, China, Vietnam, Cambodia, Thailand
Vietnam touches: Laos, China, Cambodia
Cambodia touches: Thailand, Laos, Vietnam
Malaysia touches: Thailand, Brunei, Indonesia
Brunei touches: Malaysia
Phillipines touches:
Indonesia touches: Malaysia, Papua New Guinea
Papua New Guinea touches: Indonesia
Australia touches:
Tasmania touches:
Japan touches:
Guam touches:
Solomon Islands touches:
Vanuatu touches:
Fiji touches:
New Caledonia touches:
New Zealand touches:
Kerguelen Island touches:
Heard Island touches:
Mauritius touches:
Reunion touches:
Mayotte touches:
Comoros touches:
Madagascar touches:
Sao Tome touches:
Bioko touches:
Egypt touches: Libya, Israel, Sudan
Libya touches: Algeria, Tunisia, Egypt, Sudan, Chad, Niger
Tunisia touches: Algeria, Libya
Algeria touches: Western Sahara, Morocco, Tunisia, Libya, Niger, Mali, Mauritania
Morocco touches: Western Sahara, Algeria
Western Sahara touches: Morocco, Algeria, Mauritania
Mauritania touches: Western Sahara, Algeria, Mali, Senegal
Senegal touches: The Gambia, Mauritania, Mali, Guinea, Guinea-Bissau
The Gambia touches: Senegal
Guinea-Bissau touches: Senegal, Guinea
Guinea touches: Guinea-Bissau, Senegal, Mali, Cote D'Ivoire, Liberia, Sierra Leone
Sierra Leone touches: Guinea, Liberia
Liberia touches: Sierra Leone, Guinea, Cote D'Ivoire
Cote D'Ivoire touches: Liberia, Guinea, Mali, Burkina Faso, Ghana
Mali touches: Senegal, Mauritania, Algeria, Niger, Burkina Faso, Cote D'Ivoire, Guinea
Burkina Faso touches: Mali, Niger, Benin, Togo, Ghana, Cote D'Ivoire
Ghana touches: Cote D'Ivoire, Burkina Faso, Togo
Togo touches: Ghana, Burkina Faso, Benin
Benin touches: Togo, Burkina Faso, Niger, Nigeria
Niger touches: Burkina Faso, Mali, Algeria, Libya, Chad, Nigeria, Benin
Nigeria touches: Benin, Niger, Chad, Cameroon
Chad touches: Niger, Libya, Sudan, Central African Republic, Cameroon, Nigeria
Sudan touches: Chad, Libya, Egypt, Eritrea, Ethiopia, Kenya, Uganda, Democratic Republic of the Congo, Central African Republic
Eritrea touches: Sudan, Djibouti, Ethiopia
Djibouti touches: Ethiopia, Eritrea, Somalia
Ethiopia touches: Sudan, Eritrea, Djibouti, Somalia, Kenya
Somalia touches: Kenya, Ethiopia, Djibouti
Kenya touches: Uganda, Sudan, Ethiopia, Somalia, Tanzania
Uganda touches: Democratic Republic of the Congo, Sudan, Kenya, Tanzania, Rwanda
Democratic Republic of the Congo touches: Cabinda, Congo, Central African Republic, Sudan, Uganda, Rwanda, Burundi, Zambia, Angola
Central African Republic touches: Cameroon, Chad, Sudan, Democratic Republic of the Congo, Congo
Cameroon touches: Nigeria, Chad, Central African Republic, Congo, Gabon, Equatorial Guinea
Equatorial Guinea touches: Cameroon, Gabon
Gabon touches: Equatorial Guinea, Cameroon, Congo
Congo touches: Gabon, Cameroon, Central African Republic, Democratic Republic of the Congo, Cabinda
Rwanda touches: Democratic Republic of the Congo, Uganda, Tanzania, Burundi
Burundi touches: Democratic Republic of the Congo, Rwanda, Tanzania
Tanzania touches: Burundi, Rwanda, Uganda, Kenya, Mozambique, Malawi, Zambia
Cabinda touches: Congo, Democratic Republic of the Congo
Angola touches: Democratic Republic of the Congo, Zambia, Namibia
Zambia touches: Angola, Democratic Republic of the Congo, Tanzania, Malawi, Mozambique, Zimbabwe, Botswana, Namibia
Malawi touches: Zambia, Tanzania, Mozambique
Mozambique touches: Zimbabwe, Zambia, Malawi, Tanzania, South Africa, Swaziland
Zimbabwe touches: Namibia, Zambia, Mozambique, South Africa, Botswana
Botswana touches: Namibia, Zambia, Zimbabwe, South Africa
Namibia touches: Angola, Zambia, Zimbabwe, Botswana, South Africa
South Africa touches: Namibia, Botswana, Zimbabwe, Mozambique, Swaziland, Lesotho
Swaziland touches: South Africa, Mozambique
Lesotho touches: South Africa
```
[Answer]
# Perl, ~~1509~~ ~~1496~~ ~~1392~~ ~~1389~~ ~~1386~~ ~~1251~~ ~~1248~~ ~~1246~~ 1241 bytes
Includes +2 for `-na`
Run with the country and the count on STDIN, e.g. `perl -na countries0.pl <<< "The Gambia 4"`
File `countries.pl`:
```
$_=unpack"B*","\xf4\xb5\xd4\x9b\xd1\x72\xec\x72\xb1\xdd\x51\x9d\xe6\xa5\x92\xd2\xd3\xc9\x0d\xdd\xcd\x23\x47\x5c\xb4\x56\x93\x92\x36\x51\x8d\x05\x68\xf2\x2c\x33\x75\x98\x8a\xbc\xb7\xaf\x56\x73\x55\x15\x64\xbb\x2f\x4d\x8a\x30\xe2\xda\x26\xb1\xdb\xe4\xbb\xf9\x34\x74\xb9\xce\xce\xf4\x78\x2f\x37\x8e\x8d\x8f\xdc\xcb\x5e\x7f\x8a\xc1\x29\xcd\xe3\x9e\xbd\x2e\x28\x90\xd3\xce\xd8\xb4\x29\x4d\xb8\x93\xd5\x77\x9a\x29\x3f\x65\xa2\xcc\x9c\x66\x9a\x8c\x46\xb3\x39\xb3\x8f\x92\xec\xb8\xff\xda\x58\x56\x24\x92\x52\x5c\x9e\x0b\x49\x30\xe4\xa9\xa8\xc9\xf7\xef\x12\x65\x85\xb4\x51\x1c\x5b\x24\xa2\x65\xa3\x59\x71\x94\x45\xd4\xff\xf9\xf4\x70\xce\x35\x26\x8a\x30\xe5\xda\x34\x34\x49\x25\x45\x04\x94\x53\x51\x57\x5f\xfe\x69\x1c\x51\x95\x60\x93\xe4\xde\x29\xc2\x78\x68\xaa\xb2\x69\x41\xc3\x58\x32\x01\x72\xd1\xcf\x54\x08\x03\x33\xca\x2c\xcc\xdb\xa0\x26\x43\x34\x9a\x1a\x24\x5d\x03\x24\x1d\x5a\x71\x00\xa4\x98\xd1\xbe\x07\x66\xdb\x26\x91\x90\x3b\xbb\x0d\xf2\x68\x68\x91\x03\xa5\xa5\x92\x06\x64\x36\x5d\xa8\x05\x36\x49\xe1\xa1\xa9\xda\x89\xa0\x28\xdd\x49\x23\xb2\x68\x0d\x4e\xf4\x4d\x01\x36\xcf\x53\xa5\xc0\xa6\xd1\x3c\x90\x0b\x26\xcc\x12\xe4\xe8\x2c\xb4\x1a\x93\x63\x44\xdc\x05\xa3\x69\xa9\xd2\xe0\xb0\xe8\x1b\x81\x8d\xa3\xec\x10\x06\xd2\xe1\x87\x24\xf4\x72\xb2\x41\x49\xf4\x6d\xb5\x01\xd0\xe5\x72\x4d\xa8\x0e\x37\x34\x1d\xa8\x06\x67\xa9\xb5\x31\x44\x8a\x06\x93\x5f\x2d\x65\x76\x4d\x00\xb9\x26\x4f\x9c\x83\x40\x71\xf2\xe1\xa0\x70\x17\x21\xa2\x44\x0e\x64\x33\x8b\x2d\x40\x1a\x69\xd5\x1b\x70\x47\x29\x1c\x93\x2d\x37\x20\x8e\x42\x2c\xae\x80\x0d\x86\x69\xd1\x36\xa0\x3b\xb9\x0a\x49\x07\x43\x95\xd3\xd6\xa0\x3b\x26\xb2\xd4\x03\x73\x1a\x26\xd4\x04\x69\xc9\x0b\x29\xb5\x01\x40\xb2\x89\xb5\x01\x2e\x8f\x29\xb5\x01\x3f\x36\x96\x4c\x80\x5a\x26\x91\xa0\x19\x20\xd1\xb3\xe8\x13\x96\xee\x97\x02\xac\x90\xd1\x22\x00\x68\x35\xda\x80\x1c\xdb\xe8\xc9\x36\xe8\xe8\x90\x51\xb1\x92\x6d\x40\x51\xf2\x6b\x29\x67\x51\x20\x64\xc3\xaa\x36\xd4\x06\x9b\x29\x72\x40\xee\x66\x33\x43\xd9\x6c\xa8\x02\xd3\xd6\xe8\xe8\x90\x26\x45\xa0\x40\xd9\xf7\xb6\xa0\x2c\xda\x24\x1d\xa2\x60\xec\xf6\x40\x61\xa6\x3a\x24\x09\xcb\x46\x68\x7b\x2d\x95\x01\x37\xb2\x5e\xb7\x47\x44\x83\xd4\x7d\x3c\x6e\x8e\x89\x05\x15\xa3\x51\x36\xe8\xe8\x90\x0e\x6d\xf4\xae\x0f\x53\xa6\x8d\x9a\x08\xe5\x3a\xc8\x6d\x40\x7a\x7b\xa5\x86\x0a\xd0\x74\x68\x2c\x91\x5a\x80\xe1\xac\x9a\x02\xcd\xa5\x40\x9b\x72\x8d\xa6\xa7\x40\x32\x89\xd0\x68\x29\x74\xc0\x9a\x6c\x39\x0a\x14\x6d\x19\x09\x46\xcd\xa0\xe5\xd0\x2e\xd2\x1a\x69\x10\x5e\x51\x92\x41\xdb\xb6\xd4\x06\x63\x44\x83\xb4\x98\xad\x0a\x36\x8c\xb5\x00\xec\xb4\x54\x48\x04\xeb\x33\x33\x1d\x80\x19\x32\x89\xca\x40\x19\x77\x23\x36\x41\x1b\xd1\x31\xa3\x40\x1a\x67\xa0\x36\x52\x29\xb6\x9d\x07\x29\x16\x64\x56\xa0\x2d\xd6\xd2\x41\x04\x83\x0e\xd0\x2b\xa0\xb2\xd0\x77\x74\x7d\x83\x44\x88\x1d\xcc\x68\x1b\x50\x1d\xcc\xc6\x68\x51\x4d\xb7\x28\x09\x36\xc3\x6c\xa8\x07\xda\x2c\xa3\x37\x20\x48\x66\xb6\x4b\x6a\x02\x39\x7d\x22\xcb\x56\x72\x07\xa4\x9b\xd0\x0c\x90\x6c\xf9\x00\x66\xa5\x83\x44\x88\x1a\x9d\x07\x28\xd0\x34\x03\x32\x3e\xee\x89\xa0\x13\x48\xd9\x96\xa0\x25\xab\x94\x60\x8d\x03\x4d\xd8\x0f\xa4\x59\x6a\x00\x74\x4b\xe8\x9b\x50\x1d\x98\xa8\x90\x51\x3a\xc8\x68\x09\xea\x89\x15\x00\xdd\xd1\x22\xa0\x19\x36\xcd\x22\xb0\x18\xd9\xa6\x56\x04\x64\x7b\x73\x20\x8d\x03\x4b\xf6\xd4\x07\x28\xcb\x24\x54\x00\x6c\xcb\xd0\x03\x9a\x6d\xdb\x50\x02\x94\x73\xc6\xd0\x76\xe4\x0f\x8c\xab\x03\x34\xa1\xcc\xa7\x59\x07\x0d\x41\x03\x92\x48\xdb\x40\xc2\x8a\x6d\xb9\x44\xc0\xe0\x4d\xb5\x26\xda\x80\x4d\xb5\x26\x82\x81\xd4\x9b\x6a\x02\x39\x6e\x79\xcc\x83\x72\xe8\xe4\xd4\xc3\xb4\x35\x1b\x40\x32\x49\xb2\x41\x1a\x4d\xb6\x1d\x13\x6a\x02\x64\xe9\x28\x0b\x24\x59\x4c\xbb\x6a\x03\x99\x4e\xb2\x06\x4d\xbe\xb2\x69\x05\x53\xb9\x04\x68\x1b\x03\x94\x8c\x9b\x9c\xa4\x03\xce\xb2\x0d\x51\x99\x48\x34\x6a\x26\x80\xe6\x47\x28\x09\x16\x5e\x6c\xd9\x03\xb2\x4c\xb5\x40\x80\x36\x64\x9b\x6a\x03\x53\xb2\x65\x40\x1a\x96\x1d\x81\x34\xd8\x72\x14\x3d\x64\xe8\x59\x88\x39\x44\xd0\x54\x01\x68\x59\xd2\x09\x96\xe1\xa9\xd9\x32\xa0\x35\x3b\x26\x54\xfb\x2d\xde\xd2\x60\x3e\x32\xa8\x59\xb2\x0d\x12\x20\x0b\x31\xb2\x6d\xca\x26\x07\x04\xab\x3a\x0f\x2d\xb5\x03\x0d\x4e\xc9\x95\x01\xdb\x49\xad\xa4\x03\x2c\xa6\x40\x19\xa5\x0d\x52\x2c\xb5\x00";s/.{5}/pack b5,$&/ge;s#\G[^\x00]??#${$.+=$>$_}{$t=$.+ord(O&$&)}&=\$$t{$.}#eg;y//\n '_-z-/c;s/\b./\u$&/g;s/X/republic/g;y/_`/ /d;print+(/$|.+\n/mg)[eval'%r=map%$_,$l+=s/^@F$//m*$`=~y/\n//,'x pop@F]
```
This works as is, but to get the given length all the escaped bytes have to be replaced by the corresponding literal ones. You can e.g. do that using:
```
perl -p0e 's/\\n/\n/g;s/"\\x.*?"/"\x27".eval($&)."\x27"/ges;s/\s+$//' < countries.pl > countries0.pl
```
## Explanation
Let's first display the program with some transformations removed:
```
$_ = unpack"B*", "touches\0names";
s{.{5}}{pack b5,$&}ge;
s{\G[^\x00]??}{
# The next 3 lines were: ${$.+=$>$_}{$t=$.+ord(O&$&)}&=\$$t{$.}
$. += $& gt $_;
$t = $. + ord(O&$&);
${$t}{$.} = ${$.}{$t} = "";
}eg;
tr//\n '_-z-/c;
s/\b./\u$&/g;
s/X/Republic/g;
y/_`/ /d;
print +(/$|.+\n/mg)[eval'%r=map%$_,%r,s/^@F$//m*$`=~y/\n//;'x pop@F]
```
The basic idea is to have three main datastructures:
* An array `@countries` containing all countries
* A two level hash `%touches` of indices in the `@countries` array such that `$touches{$i}{$j}` exists if and only if `$countries[$i]` touches `$countries[$j]`
* A working set hash `%reachable` which has a key for the index of every country that is reachable at the layer currently being considered.
Then the algorithm is:
* Find the index of the target country in `@countries` and use that to initialize `%reachable`
* For as many layers are asked for do:
+ for each key `$r` in `%reachable` look up `$touches{$r}` and collect all keys you find there
+ Add all collected keys to `%reachable`. Since this is a hash any duplicates will be dropped
* Finally use all indices accumulated in `%reachable` to print the corresponding country in `@countries`, but don't print the original target country
This is where the simplicity ends end the golfing begins.
* The `@countries` array will never exist with a name, though it is created briefly in memory
* The `%reachable` hash will be named `%r`
* The `%touches` hash will not explicitely exist. Instead I use the perl global namespace. E.g. that country 6 touches country 3 and country 12 will be represented in the hash `%6` which will contain `(3 => undef, 12 => undef)`
* The final lookup of the result is in principle `@countries[keys %reachable]` but I don't want to write the `keys` and instead do `@countries[%reachable]`. But since `%reachable` will contain `undef` values which become index 0, I will start the actual country list at index 1 and put the empty string at index 0. Printing that empty string will be invisible. I will also make sure the target country gets replaced by an empty string. And finally each country will still have a newline at the end. Knowing all that the final output becomes simply `print @countries[%reachable]`. Except that the countries at this point will be in `$_`, so the actual code is `print+(/$|.+\n/mg)[%r]`. Notice how the regex makes sure empty lines don't get a newline but full country names do.
* The countries touching `%reachable` can in in principle be fetched using `map keys %{$touches{$_}},keys %reachable`. But again the `keys` is not needed if I take care to properly handle the undef values that I also get without the `keys`. And like said before I use the main glob to store the values, so the actual code fragment is `map%$_,%r`. I want to add each of the returned values as a new key to `%r` which can be done as `%r=map%$_,%r`. This however needs countries to refer to themselves as touching so that the origin layer remains in the set. This code fragment has to be repeated as many times as the user asked for layers. Notice that this is the actual core of the program, everything else is noise to support this.
* The core operation has to be repeated for as many times as the user asked for layers. A convenient way to do this is to build a string containing the core code several times and evalauate that. Since the `-a` option collected the number of layers as the last element in `@F` this can be accomplished using `eval '%r=map%$_,%r;' x pop @F`. This in general not the shortest way to loop in perl but it has the advantage that it does not change `$_` during the loop, a fact which I will use later on. Putting the number of layers on its own line in STDIN would let me replace the `x pop@F` by `x<>` saving 4 bytes, but I want to remain as close to the specification as possible.
* After the `pop @F` removed the layers `@F` contains the starting country name. Notice that countries with spaces in their name will be split up into their component parts. We can find the target in the big countries string in `$_` and immediately replace the target country by the emty string (so it won't get printed) by doing `s/^@F$//m`. Notice that countries with spaces in their name get reconstructed by the `@F` interpolation. Also notice that this must be carefully anchored because some countries are substrings of others, e.g. `Guinea` and `Guinea-Bissau` or `Niger` and `Nigeria`
* The index of the target country can be found by counting newlines before the match with `$'=~y/\n//`. If the target country is not found `$`` would contain a value from a previous regex which could be very wrong. Instead we want 0 (at which index we have an empty string). This can be accomplished by combining it with the previous match into `s/^@F$//m*$`=~y/\n//`.
* We can in fact move this expression into the eval as extra argument to the map so that the target country index gets added to the loop without needing to initialize `%reachable`. The eval then becomes `eval '%r=map%$_,%r,%r,s/^@F$//m*$`=~y/\n//;' x pop@F;`. Notice that the substitution destroys the target country in `$_` so only it gets only added the first time (it wouldn't mattwer if this were not so though since the target country index is already in `%reachable` anyways)
* Since the eval return the hash `%r` we can combine this with `print+(/$|.+\n/mg)[%r]` to arrive at the actual code `print+(/$|.+\n/mg)[eval'%r=map%$_,%r,s/^@F$//m*$`=~y/\n//;'x pop@F]`
The next question is how to encode the countrylist. As explained above I want it as a huge string with the countries terminated by newline and starting with a single newline. For this I need 26 letters, space, newline, `-` (for `Guinea-Bissau`) and `'` (for `Cote D'Ivoire`). The problem is off course that sometimes the letters are in uppercase. This is easily solved uppercasing the first letter after a word boundary. However there are exceptions: `Republic of Ireland`, `Bosnia and Herzegovina` and `Democratic Republic of the Congo`. These have a word that does not start with uppercase. I can handle that by replacing the space before that with an underscore `_` which stops it from being recognized as a word boundary, then later on replace the `_` by a space. The exception that is left is `USA` which has uppercase that is not on a word boundary. For that I introduce word boundaries by writing this as `u`s`a` and then later remove the backquotes. Together that gives:
```
s/\b./\u$&/g; Uppercase the first letter of each word
tr/_`/ /d; Replace "_" by " ", remove "`"
```
With this code I can encode the whole countries string using only `a-z`, , `'`, `-`, `\n`, `_` and ```, which is 32 different characters. So each character can be encoded with 5 bits. In fact, if I have a huge bitstring `11110100111...` , I can convert it into the needed characters using:
```
s{.{5}}{pack b5,$&}ge; Convert each 5 bits to a character in the range
\x00 to \x1f.
tr//\n '_-z-/c; Convert characters in the range \x00 to \x1f to our
target characters. _-z is conveniently equivalent to
_`a-z. Put \n first so that "00000" converts to
newline (will be used later). The c modifier
complements the empty source range thereby giving
all characters (of which only 32 are used)
```
If I have a byte string in `$_` then the huge bitstring I need can be created using `$_ = unpack"B*"`. So basically all this is a small base 256 to base 32 converter and each country letter is encoded using 5 bits in the incoming binary countries string . This is relatively compact and it doesn't gain anything to develop special codes for repeated strings in the countries list with one exception: `Republic` appears in 5 country names. Since it always appears as a complete word and no country name starts with `X` (the only such letter) I can use that as escape code after the first letters of the country names have been uppercased.
```
s/X/Republic/g; Save 7 bytes by explicitely encoding Republic
```
Now I need a way to encode the "touches" relation. The first thing to notice is that it is symmetric, so if country `$n` touches country `$t`, then country `$t` also touches country `$n`. So I only need to encode half the relationships if I fill in the `%touches` hash both ways. In the simplified code you see that being done by
```
${$n}{$t} = ""; Update the main glob to say $n touches $t
${$t}{$n} = ""; Update the main glob to say $t touches $n
```
Except that the actual code uses `$.` instead of `$n` because I want the counter to start at 1 instead of 0 (country 0 is the dummy empty string).
The idea is to write a sequence of country indices `| A, B, C | D, E | ..`
which says country 1 touches countries with index `A`, `B` and `C`, country 2 touches index `D` and `E` etc. In fact I encode the offset from the current country (which I will later use to make the values small) and only positive offsets (this makes sure the "touches" relationship is only encoded in one direction, and the method I use can't handle negative numbers anyways). Some countries have an empty list of neighbours because their touch relationship has already been given by other countries. I can rearange the country list (whose order is irrelevant) such that these come at the end of the list. I can then omit these countries from the sequence. This doesn't gain anything since I need as many offsets as there are "touch" relations but it avoids losing bytes by having to encode a dummy offset. As explained above country 0 is a dummy empty string so I need to make sure that gets skipped. I can write this sequence of numbers as a sequence of bytes where the byte value corresponds to the index offset. However I still need to know where the next country in a sequence starts (the positions of the `|`s in the above example). I do this by setting some high bit to 1 for the first index in the touches list of a particular country, so for indices `A` and `D` in the above example.
There is one annoying problem though: there are more than 127 countries. So I can't just use the character sign bit. Instead I found an arrangement of the countries such that every country is never farther that 15 positions away from all the countries it touches:
```
Chile : [9 11 15] []
Portugal : [7] []
Luxembourg : [2 12 15] []
Netherlands : [1 14] []
Belgium : [10 13] [-2 -1]
Denmark : [12] []
Suriname : [4 6 14] []
Switzerland : [7 10 12 14 15] []
Spain : [6] [-7]
Bolivia : [2 6 9 11] [-9]
French Guiana : [10] [-4]
Argentina : [2 7 9] [-11 -2]
Guyana : [8 14] [-6]
Uruguay : [7] [-2]
France : [3 5] [-12 -10 -7 -6]
Peru : [1 5 14] [-15 -6]
Ecuador : [13] [-1]
Germany : [4 5 10 11] [-15 -14 -13 -12 -10 -3]
Paraguay : [2] [-9 -7]
Italy : [3 4] [-12 -5]
Brazil : [6 9] [-14 -11 -10 -9 -8 -7 -5 -2]
Liechtenstein : [1] [-14 -4]
Austria : [1 5 8 13] [-15 -5 -3 -1]
Slovenia : [1 7] [-4 -1]
Croatia : [1 6 12] [-1]
Bosnia and Herzegovina : [6 11] [-1]
Venezuela : [3] [-14 -6]
Czech Republic : [1 8] [-10 -5]
Poland : [5 7 13 15] [-11 -1]
Columbia : [13] [-14 -13 -9 -3]
Hungary : [5 6 7 11] [-8 -7 -6]
Montenegro : [5 8] [-6]
Moldova : [5 9] []
Lithuania : [10 13] [-5]
Sweden : [10 11] []
Slovakia : [6] [-13 -8 -7 -5]
Serbia : [1 2 3 14] [-12 -11 -6 -5]
Romania : [4 13] [-7 -5 -1]
Macedonia : [1 12 13] [-2]
Albania : [12] [-8 -3 -1]
Estonia : [6 15] []
Ukraine : [2 14] [-13 -11 -9 -6 -4]
Panama : [15] [-13]
Belarus : [3 12] [-15 -10 -2]
Norway : [1 11] [-10]
Finland : [10] [-11 -1]
Latvia : [9] [-13 -6 -3]
Turkmenistan : [9 13 14 15] []
Armenia : [1 7 8 15] []
Azerbaijan : [6 7 14] [-1]
Bulgaria : [1 13] [-14 -13 -12]
Greece : [12] [-13 -12 -1]
South Korea : [7] []
Pakistan : [3 9 11 15] []
Nepal : [14 15] []
Russia : [4 6 8 10 14] [-15 -14 -12 -11 -10 -9 -7 -6]
Iran : [6 7 14] [-9 -8 -7 -3]
San Jose : [14] [-15]
Bhutan : [10 11] []
North Korea : [10] [-7 -4]
Uzbekistan : [1 2 9] [-13]
Kazakhstan : [8] [-14 -6 -1]
Afghanistan : [2 7] [-15 -9 -6 -2]
Turkey : [7 13] [-15 -14 -13 -12 -8 -7]
Kashmir : [4 5] [-11 -2]
Mongolia : [4] [-10]
Kuwait : [4 12] []
Qatar : [11] []
India : [1 4 15] [-15 -14 -10 -4]
China : [5 14 15] [-15 -14 -11 -10 -9 -8 -7 -5 -4 -1]
Iraq : [6 8 9] [-14 -7 -4]
Nicaragua : [14] [-14]
Bangladesh : [11] [-4]
United Arab Emirates : [4 5] []
Vietnam : [10 12] [-5]
Yemen : [2 3] []
Syria : [3 5 11] [-13 -6]
Oman : [1] [-4 -2]
Saudi Arabia : [1] [-12 -11 -8 -5 -3 -1]
Jordan : [8] [-9 -3 -1]
Djibouti : [10 12 14] []
Lebanon : [6] [-5]
Lesotho : [9] []
Myanmar : [1 15] [-15 -14 -11]
Laos : [2 14] [-15 -10 -1]
Honduras : [3 14] [-14]
Cambodia : [12] [-12 -2]
Israel : [15] [-11 -8 -6]
El Salvador : [11] [-3]
Swaziland : [2 6] []
Somalia : [4 6] [-10]
South Africa : [2 4 9 10] [-9 -2]
Eritrea : [2 14] [-12]
Zimbabwe : [2 7 8 11] [-2]
Ethiopia : [2 12] [-14 -4 -2]
Mozambique : [8 9 10] [-6 -4 -2]
Kenya : [9 10 12] [-6 -2]
Belize : [2 15] []
Thailand : [15] [-15 -14 -12]
Guatemala : [13] [-14 -11 -2]
Botswana : [1 4] [-9 -7]
Namibia : [3 6] [-10 -8 -1]
Egypt : [4 13] [-15]
Malawi : [1 2] [-8]
Zambia : [1 3 13] [-11 -9 -4 -3 -1]
Tanzania : [3 4 5] [-10 -9 -2 -1]
Sudan : [2 9 11 12 13] [-14 -12 -10 -4]
Angola : [10] [-6 -3]
Uganda : [1 9] [-12 -3 -2]
Rwanda : [1 8] [-4 -1]
Burundi : [7] [-5 -1]
Brunei : [2] []
Mexico : [15] [-15 -13]
Malaysia : [15] [-15 -2]
Cabinda : [3 15] []
Libya : [1 3 6 7] [-13 -9]
Tunisia : [6] [-1]
Democratic Republic of the Congo: [2 12] [-13 -11 -10 -9 -8 -7 -3]
Chad : [1 2 3 14] [-12 -3]
Central African Republic : [10 13] [-13 -2 -1]
Nigeria : [1 5 12] [-2]
Niger : [1 4 9 10] [-6 -3 -1]
Algeria : [1 2 4 9] [-7 -6 -1]
Morocco : [1] [-1]
Western Sahara : [2] [-2 -1]
Benin : [5 8] [-5 -4]
Mauritania : [5 11] [-4 -2]
USA : [15] [-15]
Indonesia : [15] [-15]
Congo : [3 5] [-15 -12 -10]
Burkina Faso : [1 3 5 6] [-9 -5]
Mali : [5 6 8] [-10 -9 -5 -1]
Cameroon : [2 15] [-14 -13 -12 -3]
Togo : [2] [-8 -3]
Gabon : [13] [-5 -2]
Ghana : [1] [-5 -2]
Cote D'Ivoire : [2 3] [-6 -5 -1]
Senegal : [2 7 12] [-11 -6]
Liberia : [1 10] [-2]
Guinea : [5 9] [-8 -3 -2 -1]
Haiti : [6] []
United Kingdom : [4] []
Canada : [] [-15]
Papua New Guinea : [] [-15]
Guinea-Bissau : [] [-7 -5]
Republic of Ireland : [] [-4]
Dominican Republic : [] [-6]
Equatorial Guinea : [] [-15 -13]
Sierra Leone : [] [-10 -9]
The Gambia : [] [-12]
```
(at the time I was writing this explanation my search program actually found an order where the maximum distance is at most 12). This means I can use `0x10` as flag to indicate the start of a new country and I only need to encode 32 different values. This can be compressed for expansion with same base 256 to base 32 converter as was needed for the country list. I can in fact put the touch string before the country string with a `0x00` inbetween (before encoding) if I write the the touch decoder so it stops at this `\x00`. The country decoder is written so that this `0x00` left at the start becomes the initial newline I need so the country at index 0 is the empty string.
An older version of the code used the fact that there are only 4 connected components in the country graph to reduce country indices to below 128, but that was much complicated and quite a bit longer in code and encoded string.
The code to convert a byte sequence to the `%touches` hash then becomes:
```
s{\G[^\x00]??}{ I want to walk over the characters in $_ in
sequence but stop at the first \x00. \G says to
only match where the previous match left of and
is initialized to the start of the string. The
?? is for non greedy matching which means it
prefers to match the empty string. Like this it
will start to match the empty string, then one
char, then the empty string, then the next char
etc. In the code below you can see that the
empty string becomes an offset of 0 without
advancing the country, which means each country
gets a realtionship to itself (except for the
omitted final countries. This will take over
the role of "Add all collected keys to
`%reachable" in the basic algortith mentioned
above so we can do "%reachable = all countries
touch %reachable" as basic step. The exception
countries at the end are no problem. Their
neighbours are guaranteed to get a self loop
reference. So if the starting country is an
exception country it will not be in the first
layer, but that is no problem since we don't
print the starting country anyways. And layer 1
DOES refer to itself AND the starting country
so all countries will be there on all later
layers. If it is not the starting country but a
layer passes through it the preceding country
will keep pushing the exception country again
on each round, so again nothing is lost
$. += $& gt $_ $. is used to indicate the index of the current
country. Add 1 to $. if the byte has bit 5 set.
This works because $_ will be carefully
constructed so it will start with "\x0f" by
making sure the first country has a touching
country at distance 15. This also imples that
for the first country I cannot trigger an
increase. That is why $. is used as as index so
its value will start with 1
$t=$.+ord(O&$&); The touching country offset is in byte `$&`
which gets converted to a number and has its
high bit removed (O has byte code \x4f)
${$t}{$.} = ${$.}{$t}=""; Next the %touching hash is updated as explained
above. Sets the value to "" (which will behave
as 0 during the country lookups). This also
makes sure the replacement expression is ""
which means that the substitution as a whole
removes the sequence of encoded bytes
}eg
```
Notice that all singleton countries are simply not encoded at all. Used as input they will therefore never match, so `%reachable` will just contain references to the initial empty country and nothing gets printed.
With that the whole program is explained. All that was needed after that was to write a meta-program that generates the huge encoded string by carefully chosing the order of the countries such that
* All countries with an empty neighbour list (subsumed by their neighbours) appear at the end of the country list
* All touching countries are 15 or less removed from each other
* The first country has a neighbour at offset 15
* The encoded string must not contain `'` (which would invalidate the final single quoted string)
[Answer]
# JavaScript (ES6), ~~2862~~ 2324
```
F=(C,N)=>`USA,,Canada,,Mexico,,Guatemala,,Belize,,El Salvador,,Honduras,,Nicaragua,,San Jose, ,Panama,
,Columbia,,Venezuela,
,Guyana,
,Suriname,,French Guiana,
,Brazil,
,Ecuador,
,Peru,
,Bolivia,,Chile,,Paraguay,,Argentina,,Uruguay,,Haiti,,Dominican Republic,,Republic of Ireland,,United Kingdom,,Norway,,Sweden,,Finland,,Russia, !#)@ABCGDE,Denmark,$,Estonia,!,Latvia, #",Lithuania,!#(,Belarus,"!)(,Germany,'&%(*0132,Netherlands,$&,Belgium,2%$',Luxembourg,2&$,Poland,$"#)+*,Ukraine,+(#.-/,Czech Republic,$(+0,Slovakia,0*()/,,,Moldova,).,Romania,/)-87,Hungary,0+).754,Austria,1$*+/4<3,Liechtenstein,3$0,France,&'$3<=,Switzerland,2$10<,Slovenia,<0/5,Croatia,4/76,Bosnia and Herzegovina,579,Serbia,65/.8;:9,Bulgaria,7.@?;,Montenegro,67:,Albania,97;?,Macedonia,:78?,Italy,2304,Spain,>2,Portugal,=,Greece,:;8@,Turkey,?ABKLM,Armenia,@BK,Azerbaijan,@AK,Kazakhstan,GHJ,Mongolia,G,North Korea,GF,South Korea,E,China,IHCDE`_]Y[ZX,Uzbekistan,CGIJ,Afghanistan,KJHGXW,Turkmenistan,CHIK,Iran,L@BAJIW,Iraq,PM@KRQ,Syria,N@LPO,Lebanon,OM,Israel,fNMP,Jordan,OMLQ,Saudi Arabia,PLRSTUV,Kuwait,LQ,Qatar,Q,United Arab Emirates,QU,Oman,QTV,Yemen,QU,Pakistan,KIXY,Kashmir,WIGY,India,WXZ[]\,Nepal,YG,Bhutan,YG,Bangladesh,Y],Myanmar,\YG_^,Thailand,]_ab,Laos,]G`a^,Vietnam,_Ga,Cambodia,^_`,Malaysia,^cd,Brunei,b,Indonesia,be,Papua New Guinea,d,Egypt,gO|,Libya,ihf|{y,Tunisia,ig,Algeria,kjhgytl,Morocco,ki,Western Sahara,jil,Mauritania,kitm,Senegal,nltpo,The Gambia,m,Guinea-Bissau,mp,Guinea,omtsrq,Sierra Leone,pr,Liberia,qps,Cote D'Ivoire,rptuv,Mali,mliyusp,Burkina Faso,tyxwvs,Ghana,suw,Togo,vu,Benin,wuyz,Niger,utig{zx,Nigeria,xy{,Chad,yg|z,Sudan,{gf},Eritrea,|~,Djibouti,},Ethiopia,|}~,Somalia,~,Kenya,|,Uganda,|,Democratic Republic of the Congo,|,Central African Republic,{|,Cameroon,z{,Equatorial Guinea,,Gabon,,Congo,,Rwanda,,Burundi,,Tanzania,,Cabinda,,Angola,,Zambia,,Malawi,,Mozambique,,Zimbabwe,,Botswana,,Namibia,,South Africa,,Swaziland,,Lesotho,,`.replace(/([^,]*),/g,(_,x)=>++i%2?a.push(x):b.push([...x].map(c=>c.charCodeAt())),i=0,a=[],b=[])&&N?new Set([for(q of b[a.indexOf(C)]||[])for(p of F(a[q],N-1))p]).add(C):new Set([C])
```
Returns a Set object containing the proper countries. Note that this contains a ton of unprintables.
### Test snippet (ES6-compliant browser required)
```
F=(C,N)=>`USA,\x01\x02,Canada,\x00,Mexico,\x00\x04\x03,Guatemala,\x02\x04\x05\x06,Belize,\x02\x03,El Salvador,\x03\x06,Honduras,\x03\x05\x07,Nicaragua,\x06\x08,San Jose,\x07\x09,Panama,\x08\x0a,Columbia,\x0b\x0f\x11\x10\x09,Venezuela,\x0a\x0f\x0c,Guyana,\x0b\x0f\x0d,Suriname,\x0c\x0f\x0e,French Guiana,\x0d\x0f,Brazil,\x0a\x0b\x0c\x0d\x0e\x11\x12\x14\x15\x16,Ecuador,\x0a\x11,Peru,\x10\x0a\x0f\x12\x13,Bolivia,\x11\x0f\x14\x15\x13,Chile,\x11\x12\x15,Paraguay,\x12\x0f\x15,Argentina,\x13\x12\x14\x0f\x16,Uruguay,\x15\x0f,Haiti,\x18,Dominican Republic,\x17,Republic of Ireland,\x1a,United Kingdom,\x19,Norway,\x1c\x1d\x1e,Sweden,\x1b\x1d,Finland,\x1c\x1b\x1e,Russia,\x1b\x1d !#)@ABCGDE,Denmark,$,Estonia,\x1e!,Latvia, \x1e#",Lithuania,!#(,Belarus,"!\x1e)(,Germany,'&%\x1f(*0132,Netherlands,$&,Belgium,2%$',Luxembourg,2&$,Poland,$"#)+*,Ukraine,+(#\x1e.-/,Czech Republic,$(+0,Slovakia,0*()/,,,Moldova,).,Romania,/)-87,Hungary,0+).754,Austria,1$*+/4<3,Liechtenstein,3$0,France,&'$3<=,Switzerland,2$10<,Slovenia,<0/5,Croatia,4/76,Bosnia and Herzegovina,579,Serbia,65/.8;:9,Bulgaria,7.@?;,Montenegro,67:,Albania,97;?,Macedonia,:78?,Italy,2304,Spain,>2,Portugal,=,Greece,:;8@,Turkey,?\x1eABKLM,Armenia,@\x1eBK,Azerbaijan,@A\x1eK,Kazakhstan,\x1eGHJ,Mongolia,G\x1e,North Korea,G\x1eF,South Korea,E,China,IHC\x1eDE\`_]Y[ZX,Uzbekistan,CGIJ,Afghanistan,KJHGXW,Turkmenistan,CHIK,Iran,L@BAJIW,Iraq,PM@KRQ,Syria,N@LPO,Lebanon,OM,Israel,fNMP,Jordan,OMLQ,Saudi Arabia,PLRSTUV,Kuwait,LQ,Qatar,Q,United Arab Emirates,QU,Oman,QTV,Yemen,QU,Pakistan,KIXY,Kashmir,WIGY,India,WXZ[]\\,Nepal,YG,Bhutan,YG,Bangladesh,Y],Myanmar,\\YG_^,Thailand,]_ab,Laos,]G\`a^,Vietnam,_Ga,Cambodia,^_\`,Malaysia,^cd,Brunei,b,Indonesia,be,Papua New Guinea,d,Egypt,gO|,Libya,ihf|{y,Tunisia,ig,Algeria,kjhgytl,Morocco,ki,Western Sahara,jil,Mauritania,kitm,Senegal,nltpo,The Gambia,m,Guinea-Bissau,mp,Guinea,omtsrq,Sierra Leone,pr,Liberia,qps,Cote D'Ivoire,rptuv,Mali,mliyusp,Burkina Faso,tyxwvs,Ghana,suw,Togo,vu,Benin,wuyz,Niger,utig{zx,Nigeria,xy{\x85,Chad,yg|\x84\x85z,Sudan,{gf}\x7f\x81\x82\x83\x84,Eritrea,|~\x7f,Djibouti,\x7f}\x80,Ethiopia,|}~\x80\x81,Somalia,\x81\x7f~,Kenya,\x82|\x7f\x80\x8b,Uganda,\x83|\x81\x8b\x89,Democratic Republic of the Congo,\x8c\x88\x84|\x82\x89\x8a\x8e\x8d,Central African Republic,\x85{|\x83\x88,Cameroon,z{\x84\x88\x87\x86,Equatorial Guinea,\x85\x87,Gabon,\x86\x85\x88,Congo,\x87\x85\x84\x83\x8c,Rwanda,\x83\x82\x8b\x8a,Burundi,\x83\x89\x8b,Tanzania,\x8a\x89\x82\x81\x90\x8f\x8e,Cabinda,\x88\x83,Angola,\x83\x8e\x93,Zambia,\x8d\x83\x8b\x8f\x90\x91\x92\x93,Malawi,\x8e\x8b\x90,Mozambique,\x91\x8e\x8f\x8b\x94\x95,Zimbabwe,\x93\x8e\x90\x94\x92,Botswana,\x93\x8e\x91\x94,Namibia,\x8d\x8e\x91\x92\x94,South Africa,\x93\x92\x91\x90\x95\x96,Swaziland,\x94\x90,Lesotho,\x94,`.replace(/([^,]*),/g,(_,x)=>++i%2?a.push(x):b.push([...x].map(c=>c.charCodeAt())),i=0,a=[],b=[])&&N?new Set([for(q of b[a.indexOf(C)]||[])for(p of F(a[q],N-1))p]).add(C):new Set([C])
```
```
<input id=A type="text" value="Columbia"><br>
<input id=B type="number" value=2><br>
<button onclick="C.innerHTML=[...F(A.value,B.value)].join('\n')">Run</button><br>
<pre id=C></pre>
```
### How it works
Before anything else, I removed all countries with no neighbors from the list. Then I reduced the list to this format:
* Country name
* Comma
* Index of each neighbor as a byte
* Comma
This condenses the list to 2130 bytes. A blank entry was carefully inserted where the country represented by a comma would be to avoid regex failure. Now for the interesting part:
```
F=(C,N)=>``.replace(/([^,]*),/g,(_,x)=>++i%2?a.push(x):b.push([...x].map(c=>c.charCodeAt())),i=0,a=[],b=[])&&N?new Set([for(q of b[a.indexOf(C)]||[])for(p of F(a[q],N-1))p]).add(C):new Set([C])
// Define a function F that takes in a country C and a number N, and returns:
F=(C,N)=>(
i=0, // index
a=[], // list of countries
b=[], // list of their neighbors
// Take this big string and replace each string of non-comma chars x, followed by a comma, with this function:
``.replace(/([^,]*),/g,(_,x)=>
// If we're on an even index, push the country name to a.
++i%2?a.push(x)
// Otherwise, push the list of its char codes to b.
:b.push([...x].map(c=>c.charCodeAt()))),
// If N, the number of levels, is more than 1, return a set made out of:
N?new Set(
// For each item q in the country's neighbors, or [] if the country doesn't have any (or doesn't exist):
[for(q of b[a.indexOf(C)]||[])
// For each item p in F(the q'th country, N - 1), take p.
for(p of F(a[q],N-1))p]
// Add C to this set.
).add(C)
// Otherwise (if N is 0), return a set containing C.
:new Set([C]))
```
[Answer]
# JavaScript (ES6) 2622 ~~3815~~
A function returning a set. Recursive scan using a set to avoid repetitios.
(2 newlines added for readability - it should be a single line)
Borrowing the idea of @ETHproductions of not storing countries with no *neighbors*. (borrowing his orthography too, I always misspell that word)
```
(p,l)=>("China124b41017862692829186d7a40Russia635472421f1110343541007862Brazil23685767732b20651e87Germany5d367b8b1c3a065b2f16Democratic Republic of the Congo6e24220531474e084cSudan151a52532627310422Austria5b033a2e0a483e2fSerbia4d390a2c21433361Zambia4c040f5e1b32382aAlgeria6a79841a0d0c44Hungary062e112c073948Iran191035344a1246Mali2d44090d132517Niger130c091a154537Saudi Arabia3f197591866488Tanzania4e4731271b5e08Turkey3b0134350b1930Ukraine2e1c1f012c770aAfghanistan0b4a4b004046Burkina Faso0c0d37835625Cameroon451522245571Chad0d1a05221445France365d032f3e80Guinea742d0c255a7fIndia46407a6d296bIraq3f30100b750eLibya09845205150dMozambique32085e0f1d81Poland035c1f112e3aSouth Africa2a38321b818eArgentina5020650287Belarus5c4201111cBolivia2b02651e50Bulgaria072c103b43Central African Republic1415050424Columbia68022b6f7dCongo551422046eCote D'Ivoire5a170c1356Ethiopia0553516627Kenya310526660fLaos2900694f49Myanmar6b18002849Namibia4c0832381dPeru6f23022050Romania0a11772107Senegal94440c1774Slovakia063a1c110aSwitzerland16035b063eSyria7610193f3dUganda0405270f47Zimbabwe2a081b1d38Albania6107433bArmenia1001350bAzerbaijan1034010bBelgium167b035dBenin83130d45Botswana2a08321dCroatia480a074dCzech Republic031c2e06Greece33432110Guatemala606c7058Israel5276303fItaly162f0648Jordan3d30190eKashmir46120018Kazakhstan01004b4aLatvia72011f5cMacedonia3307213bMauritania6a090c2dNigeria370d1514Pakistan0b124018Rwanda04310f4eSlovenia3e060a39Thailand29284f5fTurkmenistan414b120bUzbekistan4100124aAngola04082aBosnia and Herzegovina390761Burundi04470fCambodia492869Chile2b201eDjibouti265366Egypt1a3d05Eritrea055126Finland826301Gabon711424Ghana251383Guyana680267Honduras3c707cIndonesia5f8f97Liberia7f1725Liechtenstein2f0306Lithuania421f1cLuxembourg163603Malawi080f1bMalaysia498959Mexico856c3cMontenegro4d0733North Korea000193Norway825401Oman0e8688Paraguay20021eSomalia272651Suriname570273Venezuela230257Vietnam28004fWestern Sahara790944Bangladesh1829Belize603cBhutan1800Cabinda2404Ecuador232bEl Salvador3c58Equatorial Guinea1455Estonia0142French Guiana6702Guinea-Bissau2d17Kuwait190eLebanon3d30Moldova112cMongolia0001Morocco6a09Nepal1800Netherlands0336Nicaragua587ePanama7e23San Jose7c7dSierra Leone175aSpain9016Swaziland1d1bSweden6354Togo5613Tunisia091aUSA8a60United Arab Emirates0e64Uruguay1e02Yemen0e64Brunei5fCanada85Denmark03Dominican Republic8dHaiti8cLesotho1dPapua New Guinea59Portugal80Qatar0eRepublic of Ireland95South Korea62The Gambia2dUnited Kingdom92"
.replace(/(\D+)([^A-Z]+)/g,(_,n,b)=>c.push([n,...b.match(/../g).map(x=>+('0x'+x))]),c=[]),
r=new Set,(f=(p,l)=>(c.find(x=>p==x[0],r.add(p))||[]).map((x,i)=>l&&i&&f(c[x][0],l-1)))(p,l),r.delete(p),r)
```
**Explanation**
```
// c has to be an array of arrays filled this way
// c[0] = ['USA', 1, 2]
// c[1] = ['Canada', 0]
// and so on
// make c array from a compact string
Z="China124b41017862692829186d7a40Russia635472421f1110343541007862Br ..."
// Country name followed by neighbors indexes as hex number, 2 digits each
// as the country are less than 160, the indexes starts with a digit
c=[]
Z.replace(/(\D+)([^A-Z]+)/g, // separate non-digits, then non uppercase
(_,n,b)=> // n is the country name, b is the hex string
c.push([n,
...b.match(/../g).map(x=>+('0x'+x))] // hex digits to int array
)
),
r=new Set
// f: recursive scan
f=(p,l)=>
// this check would make the function longer but SOOOO faster
// r.has(p) ||
(
c.find(x=>p==x[0], r.add(p)) // add p to the set, then find it in the c array
|| [] // if not found use an empty array as result
).map( // recursive call for each neighbor index
// excluding position 0 (it's the name not an index)
// and excluding all if l reached 0
(x,i)=>l && i && f(c[x][0], l-1)
)
f(p,l)
r.delete(p) // the starting country could be in the set if l>0
return r
```
**Test**
```
P=(p,l)=>(
"China124b41017862692829186d7a40Russia635472421f1110343541007862Brazil23685767732b20651e87Germany5d367b8b1c3a065b2f16Democratic Republic of the Congo6e24220531474e084cSudan151a52532627310422Austria5b033a2e0a483e2fSerbia4d390a2c21433361Zambia4c040f5e1b32382aAlgeria6a79841a0d0c44Hungary062e112c073948Iran191035344a1246Mali2d44090d132517Niger130c091a154537Saudi Arabia3f197591866488Tanzania4e4731271b5e08Turkey3b0134350b1930Ukraine2e1c1f012c770aAfghanistan0b4a4b004046Burkina Faso0c0d37835625Cameroon451522245571Chad0d1a05221445France365d032f3e80Guinea742d0c255a7fIndia46407a6d296bIraq3f30100b750eLibya09845205150dMozambique32085e0f1d81Poland035c1f112e3aSouth Africa2a38321b818eArgentina5020650287Belarus5c4201111cBolivia2b02651e50Bulgaria072c103b43Central African Republic1415050424Columbia68022b6f7dCongo551422046eCote D'Ivoire5a170c1356Ethiopia0553516627Kenya310526660fLaos2900694f49Myanmar6b18002849Namibia4c0832381dPeru6f23022050Romania0a11772107Senegal94440c1774Slovakia063a1c110aSwitzerland16035b063eSyria7610193f3dUganda0405270f47Zimbabwe2a081b1d38Albania6107433bArmenia1001350bAzerbaijan1034010bBelgium167b035dBenin83130d45Botswana2a08321dCroatia480a074dCzech Republic031c2e06Greece33432110Guatemala606c7058Israel5276303fItaly162f0648Jordan3d30190eKashmir46120018Kazakhstan01004b4aLatvia72011f5cMacedonia3307213bMauritania6a090c2dNigeria370d1514Pakistan0b124018Rwanda04310f4eSlovenia3e060a39Thailand29284f5fTurkmenistan414b120bUzbekistan4100124aAngola04082aBosnia and Herzegovina390761Burundi04470fCambodia492869Chile2b201eDjibouti265366Egypt1a3d05Eritrea055126Finland826301Gabon711424Ghana251383Guyana680267Honduras3c707cIndonesia5f8f97Liberia7f1725Liechtenstein2f0306Lithuania421f1cLuxembourg163603Malawi080f1bMalaysia498959Mexico856c3cMontenegro4d0733North Korea000193Norway825401Oman0e8688Paraguay20021eSomalia272651Suriname570273Venezuela230257Vietnam28004fWestern Sahara790944Bangladesh1829Belize603cBhutan1800Cabinda2404Ecuador232bEl Salvador3c58Equatorial Guinea1455Estonia0142French Guiana6702Guinea-Bissau2d17Kuwait190eLebanon3d30Moldova112cMongolia0001Morocco6a09Nepal1800Netherlands0336Nicaragua587ePanama7e23San Jose7c7dSierra Leone175aSpain9016Swaziland1d1bSweden6354Togo5613Tunisia091aUSA8a60United Arab Emirates0e64Uruguay1e02Yemen0e64Brunei5fCanada85Denmark03Dominican Republic8dHaiti8cLesotho1dPapua New Guinea59Portugal80Qatar0eRepublic of Ireland95South Korea62The Gambia2dUnited Kingdom92"
.replace(/(\D+)([^A-Z]+)/g,(_,n,b)=>c.push([n,...b.match(/../g).map(x=>+('0x'+x))]),c=[]),
r=new Set,(f=(p,l)=>(c.find(x=>p==x[0],r.add(p))||[]).map((x,i)=>l&&i&&f(c[x][0],l-1)))(p,l),r.delete(p),r)
// TEST
console.log=x=>O.textContent+=x+'\n'
function test()
{
var n,l,r;
[,n,l]=I.value.match(/(.+) (\d+)/)
console.log(n+' '+l)
r=P(n,l)
console.log(r.size+'\n'+[...r])
}
test()
```
```
<input id=I value='Bhutan 2'><button onclick='test()'>go</button><pre id=O></pre>
```
[Answer]
# Python 2, ~~6967~~ ~~6965~~ ~~6950~~ 6906 bytes
```
Q=[["USA",1,2],["Canada",0],["Mexico",0,4,3],["Guatemala",2,4,5,6],["Belize",2,3],["El Salvador",3,6],["Honduras",3,5,7],["Nicaragua",6,8],["San Jose",7,9],["Panama",8,10],["Columbia",11,15,17,16],["Venezuela",10,15,12],["Guyana",11,15,13],["Suriname",12,15,14],["French Guiana",13,15],["Brazil",10,11,12,13,14,17,18,20,21,22],["Ecuador",10,17],["Peru",16,10,15,18,19],["Bolivia",17,15,20,21,19],["Chile",17,18,21],["Paraguay",18,15,21],["Argentina",19,18,20,15,22],["Uruguay",21,15],["The Bahamas"],["Cuba"],["Jamaica"],["Haiti",27],["Dominican Republic",26],["Puerto Rico"],["Saint Kitts and Nevis"],["Montserrat"],["Guadeloupe"],["Dominica"],["Martinique"],["Saint Vincent"],["Barbados"],["Trinidad and Tobago"],["Greenland"],["Azores"],["Falkland Islands"],["South Georgia"],["Cape Verde"],["Madeira Island"],["Canary Islands"],["Faroe Islands"],["Republic of Ireland",46],["United Kingdom",45],["Svalbard"],["Norway",49,50,51],["Sweden",48,50],["Finland",49,48,51],["Russia",48,50,53,54,56,62,84,87,88,89,93,90,91],["Denmark",57],["Estonia",51,54],["Latvia",53,51,56,55],["Lithuania",54,56,61],["Belarus",55,54,51,62,61],["Germany",60,59,58,52,61,63,68,69,71,70],["Netherlands",57,59],["Belgium",70,58,57,60],["Luxembourg",70,59,57],["Poland",57,55,56,62,64,63],["Ukraine",64,61,56,51,66,65,67],["Czech Republic",57,61,64,68],["Slovakia",68,63,61,62,67],["Moldova",62,66],["Romania",67,62,65,76,75],["Hungary",68,64,62,66,75,73,72],["Austria",69,57,63,64,67,72,80,71],["Liechtenstein",71,57,68],["France",59,60,57,71,80,81],["Switzerland",70,57,69,68,80],["Slovenia",80,68,67,73],["Croatia",72,67,75,74],["Bosnia and Herzegovina",73,75,77],["Serbia",74,73,67,66,76,79,78,77],["Bulgaria",75,66,84,83,79],["Montenegro",74,75,78],["Albania",77,75,79,83],["Macedonia",78,75,76,83],["Italy",70,71,68,72],["Spain",82,70],["Portugal",81],["Greece",78,79,76,84],["Turkey",83,51,87,88,97,98,99],["Malta"],["Cyprus"],["Armenia",84,51,88,97],["Azerbaijan",84,87,51,97],["Kazakhstan",51,93,94,96],["Mongolia",93,51],["North Korea",93,51,92],["South Korea",91],["China",95,94,89,51,90,91,120,119,117,111,113,112,110],["Uzbekistan",89,93,95,96],["Afghanistan",97,96,94,93,110,109],["Turkmenistan",89,94,95,97],["Iran",98,84,88,87,96,95,109],["Iraq",102,99,84,97,104,103],["Syria",100,84,98,102,101],["Lebanon",101,99],["Israel",145,100,99,102],["Jordan",101,99,98,103],["Saudi Arabia",102,98,104,105,106,107,108],["Kuwait",98,103],["Qatar",103],["United Arab Emirates",103,107],["Oman",103,106,108],["Yemen",103,107],["Pakistan",97,95,110,111],["Kashmir",109,95,93,111],["India",109,110,112,113,117,114],["Nepal",111,93],["Bhutan",111,93],["Bangladesh",111,117],["Sri Lanka"],["Adaman and Nicobar Islands"],["Myanmar",114,111,93,119,118],["Thailand",117,119,121,122],["Laos",117,93,120,121,118],["Vietnam",119,93,121],["Cambodia",118,119,120],["Malaysia",118,123,125],["Brunei",122],["Phillipines"],["Indonesia",122,126,127],["Papua New Guinea",125],["Australia"],["Tasmania"],["Japan"],["Guam"],["Solomon Islands"],["Vanuatu"],["Fiji"],["New Caledonia"],["New Zealand"],["Kerguelen Island"],["Heard Island"],["Mauritius"],["Reunion"],["Mayotte"],["Comoros"],["Madagascar"],["Sao Tome"],["Bioko"],["Egypt",146,101,167],["Libya",148,147,145,167,166,164],["Tunisia",148,146],["Algeria",150,149,147,146,164,159,151],["Morocco",150,148],["Western Sahara",149,148,151],["Mauritania",150,148,159,152],["Senegal",153,151,159,155,154],["The Gambia",152],["Guinea-Bissau",152,155],["Guinea",154,152,159,158,157,156],["Sierra Leone",155,157],["Liberia",156,155,158],["Cote D'Ivoire",157,155,159,160,161],["Mali",152,151,148,164,160,158,155],["Burkina Faso",159,164,163,162,161,158],["Ghana",158,160,162],["Togo",161,160],["Benin",162,160,164,165],["Niger",160,159,148,146,166,165,163],["Nigeria",163,164,166,176],["Chad",164,146,167,175,176,165],["Sudan",166,146,145,168,170,172,173,174,175],["Eritrea",167,169,170],["Djibouti",170,168,171],["Ethiopia",167,168,169,171,172],["Somalia",172,170,169],["Kenya",173,167,170,171,182],["Uganda",174,167,172,182,180],["Democratic Republic of the Congo",183,179,175,167,173,180,181,185,184],["Central African Republic",176,166,167,174,179],["Cameroon",165,166,175,179,178,177],["Equatorial Guinea",176,178],["Gabon",177,176,179],["Congo",178,176,175,174,183],["Rwanda",174,173,182,181],["Burundi",174,180,182],["Tanzania",181,180,173,172,187,186,185],["Cabinda",179,174],["Angola",174,185,190],["Zambia",184,174,182,186,187,188,189,190],["Malawi",185,182,187],["Mozambique",188,185,186,182,191,192],["Zimbabwe",190,185,187,191,189],["Botswana",190,185,188,191],["Namibia",184,185,188,189,191],["South Africa",190,189,188,187,192,193],["Swaziland",191,187],["Lesotho",191]]
i=raw_input().split()
l,c=int(i[-1])," ".join(i[:-1])
for _,v in enumerate(Q):
if v[0]==c:C=m={_}
for _ in[0]*l:
n=set()
for A in C:n|=({d for d in Q[A][1:]if d not in C}|{A})
C=n
for v in C-m:print Q[v][0]
```
I really, really hope that I got everything right. Example:
Input:
```
Sweden 3
```
Output:
```
Kazakhstan
Norway
Finland
Russia
Turkey
Estonia
Latvia
Armenia
Belarus
Azerbaijan
Mongolia
North Korea
China
Ukraine
```
~~I hope the empty line is allowed.~~ No more empty line! Yay!
Explanation:
The long line at the top is data about each country's name, and surrounding countries. Each element in the list is another list, whose first element is the country's name, and the other element is the index of each country that surrounds it. USA is the first element, and contains the indexes `1, 2`. Element 1 in the list is Canada, and element 2 in the list is Mexico. This list was generated using this program:
```
s="""USA touches: Canada, Mexico
Canada touches: USA
```
...... [the big list above]
```
Lesotho touches: South Africa"""
names = []
for row in s.split("\n\n"):
names.append(row.split(" touches:")[0])
countries = []
for row in s.split("\n\n"):
name = row.split(" touches:")[0]
touching = row.split(" touches:")[1][1:].split(", ")
lst = [name]
for t in touching:
if t in names:
lst.append(names.index(t))
countries.append(lst)
o = "["
for country in countries:
o += "[\"" + country[0] + "\"," + ",".join(map(str, country[1: ])) + "],"
print o[:-1] + "]"
```
The output contained commas that could be removed by a very simple Regex, that can be found [here](https://regex101.com/r/bD1zK0/1). The entire program is available [here](http://pastebin.com/tMyi44kn). The output is 4,736 bytes, about 88% of the program.
Here's the rest of the program with proper variable names, comments and whitespace (previous version):
```
COUNTRY_LIST=...
user_input = raw_input().split()
level = int(user_input[-1]) # last element of user_input
user_country = " ".join(user_input[:-1])
# Convert user_country to index
for index, country in enumerate(COUNTRY_LIST):
if country[0] == user_country:
user_country = index
surrounding = {user_country} # each country surrounding's index
for _ in [0] * level: # Loop level times, I'm using [0] * l instead of range(l) to save some bytes.
new = set() # newer version of surrounding to avoid accidentally looping through some new countries.
for country in surrounding:
new |= {country} # Add country to new, using union.
for surrounding_index in COUNTRY_LIST[country][1:]: # Get all the surrounding countries.
if surrounding_index not in surrounding:
new |= {surrounding_index} # Add to new
surrounding = new
for surrounding_country in surrounding - {user_country}:
print COUNTRY_LIST[surrounding_country][0] # print all the surrounding countries names except for the input country.
```
[Answer]
# Mathematica, 128B program + 2856B data = 2984 bytes
```
e@a_:=a[[1]]<->#&/@Rest@a;l=ToExpression[ImportString[s]~StringSplit~"\n"];n=AdjacencyList[Graph[Union@@l,Flatten[e/@l]],#1,#2]&
```
Where `FOO` is a 2856-byte string (not pasted here because it contains unprintables and MMA-only characters). The string is a BZIP2-compressed list of lists, where each inner list has the form `{Country, Neighbor, Neighbor, ...}`. The list is already optimized to remove redundant edges.
```
n["Mexico", 2]
(*{"USA", "Canada", "Belize", "Guatemala", "El Salvador", "Honduras"}*)
n["Cyprus", 17]
(*{}*)
```
Having it in Mathematica's graph format allows us to do easy nice things like this:
```
map = Graph[Union @@ l, Flatten[e /@ l]];
touchGraph[country_, n_] :=
NeighborhoodGraph[map, country, n, VertexLabels -> "Name",
GraphLayout -> {"RadialEmbedding", "RootVertex" -> country}
];
```
To get things like:
[](https://i.stack.imgur.com/qXaqI.png)
[Answer]
# PHP, ~~5169~~ ~~2716~~ ~~2698~~ 2321 bytes
## Update
This is my second, extremely shortened version. Original post see below.
This turned out to become a rather detailed edit...
### Removing countries with no neighbours.
My original array definition was a whopping 4901 bytes long -- removing all countries with no neighbours (as @ETHproductions suggested) reduced this by 725 bytes to 4176 bytes. Of course this requires some extra logic code to be added to cater for the fallback, but that should be neglectable compared to this huge gain.
### Using chars instead of numbers
My next step was to reduce the amount of bytes needed to decode the neighbour references. My first idea was to ditch the decimal system and use a higher base to represent the numbers (for example base 36 which would use 0-9 plus a-z), but the extra logic needed to decode these seemed a lot. So I went for something else: characters.
Each ASCII character is only one byte long and maps onto a well defined number of the range 0..255, which is exactly what would be needed. I skipped the first 39 ASCII characters as they are unprintable/include `'` and `"` which would need escaping. The resulting array definition was only 2878 bytes long, saving 1298 bytes or 31% when compared with the previous. Of course, this too needs extra logic, but thankfully `chr` and `ord` are rather short function names :-)
### Compressing country names
Those country names still took up a lot of space though, so I decided to look how I could compress them. Five countries have the term "Republic" in them, so I was able to save 16 bytes by declaring `$r='Republic'` once and then writing `"$r of Ireland"` etc. The same goes for "Guinea", which appears 4 times.
There are also quite a few letter combinations that occur relatively often, but since typing `$x` is still two characters, replacing those only makes sense for combinations with 3+ letters and if there really is a LOT that can be replaced. For example, replacing all 10 `-nia`s in `Tanzania` etc. gained only 1 byte. Same with `-istan` (4x, -1), more luck with `-land` (7x, -4).
### PHP "features"
Thankfully for the code golfer, PHP doesn't mind too much when you violate its syntax rules. Here, we can use this to strip some quotation marks, turning `'Lesotho'=>'E'` (14 bytes) into `Lesotho=>E` (10 bytes). Amazingly (or: shockingly?) this even works [for any string that consists of A-Z, 0-9 or the second half of the ASCII table and doesn't start with a number](http://php.net/manual/en/language.variables.basics.php), making something like THIS possible: `India=>nh¢•Q“`.
However, it's a pity that the designers of the ASCII table put punctuation inbetween the letter blocks, meaning that there is no continuous block of PHP-meaningless characters to accomodate all 150 countries in the list. This results in many strings still keeping their quotes. Occasionally I moved numbers to the back so that the string wouldn't start with a digit.
### Final array definition
All this brings the array definition down to 2534 bytes, almost half of the initial value. Of course, one could now go and optimise the order of the countries so that as many entries as possible can lose their quotes etc., but I didn't want to put THAT much effort into this. ;-)
### Code
So here it is, the second version, with a bit of additional logic added:
```
function f($s)
{
// define often used parts of country names
$r=Republic;$g=Guinea;$n=nia;$i=istan;$l=land;
// array definition mainly as explained above, refer to edit notes below
$x=explode('#',"China#:si) Š‘PQ@•¢h#Russia#‹|šjG98\]i( Š#Brazil#K›SHF®#Germany#…^£³Db.ƒW>#Democratic $r of the Congo#–LJ-Yov0t#Sudan#=Bz{NOY,J#Austria#ƒ+bV2pfW#Serbia#ua2TIk[‰#Zambia#t,7†CZ`R#Algeria#’¡¬B54l#Hungary#.V9T/ap#Iran#A8]\r:n#Mali#Ul15;M?#Niger#;41B=m_#Saudi Arabia#gA¹Œ°#Tanza$n#voYOC†0#Turkey#c)\]3AX#Ukraine#VDG)TŸ2#Afghan$i#3rs(hn#Burkina Faso#45_«~M#Cameroon#m=JL}™#Chad#5B-J<m#France#^…+Wf¨#$g#œU4M‚§#India#nh¢•Q“#Iraq#gX836#Libya#1¬z-=5#Mozambique#Z0†7E©#Po$l#+„G9Vb#South Africa#R`ZC©¶#Argentina#xH*®#Belarus#„j)9D#Bolivia#S*Fx#Bulgaria#/T8ck#Central African $r#<=-,L#Columbia#*S—¥#Congo#}<J,–#Cote D'Ivoire#‚?4;~#Ethiopia#-{yŽO#Kenya#Y-NŽ7#Laos#Q(‘wq#Myanmar#“@(Pq#Namibia#t0Z`E#Peru#—K*Hx#Roma$n#29ŸI/#Senegal#¼l4?œ#Slovakia#.bD92#Switzer$l#>+ƒ.f#Syria#ž8Age#Uganda#,-O7o#Zimbabwe#R0CE`#Alba$n#‰/kc#Arme$n#8)]3#Azerbaijan#8\)3#Belgium#>£+…#Benin#«;5m#Botswana#R0ZE#Croatia#p2/u#Czech $r#+DV.#Greece#[kI8#Guatemala#ˆ”˜€#Israel#zžXg#Italy#>W.p#Jordan#eXA6#Kashmir#n:(@#Kazakhstan#)(sr#Latvia#š)G„#Macedo$n#[/Ic#Maurita$n#’14U#Nigeria#_5=<#Pak$i#3:h@#Rwanda#,Y7v#Slove$n#f.2a#Thai$l#QPw‡#Turkmen$i#is:3#Uzbek$i#i(:r#Angola#,0R#Bos$n and Herzegovina#a/‰#Burundi#,o7#Cambodia#qP‘#Chile#SHF#Djibouti#N{Ž#Egypt#Be-#Eritrea#-yN#Fin$l#ª‹)#Gabon#™<L#Ghana#M;«#Guyana#*#Honduras#d˜¤#Indonesia#‡·#Liberia#§?M#Liechtenstein#W+.#Lithua$n#jGD#Luxembourg#>^+#Malawi#07C#Malaysia#q±#Mexico#¯”d#Montenegro#u/[#North Korea#()»#Norway#ª|)#Oman#6°#Paraguay#H*F#Somalia#ONy#Suriname#*›#Venezuela#K*#Vietnam#P(w#Western Sahara#¡1l#Bangladesh#@Q#Belize#ˆd#Bhutan#@(#Cabinda#L,#Ecuador#KS#El Salvador#d€#Equatorial $g#<}#Esto$n#)j#French Guiana#*#$g-Bissau#U?#Kuwait#A6#Lebanon#eX#Moldova#9T#Mongolia#()#Morocco#’1#Nepal#@(#Nether$ls#+^#Nicaragua#€¦#Panama#¦K#San Jose#¤¥#Sierra Leone#?‚#Spain#¸>#Swazi$l#EC#Sweden#‹|#Togo#~;#Tunisia#1B#United Arab Emirates#6Œ#Uruguay#F*#USA#²ˆ#Yemen#6Œ#Brunei#‡#Canada#¯#Denmark#+#Dominican $r#µ#Haiti#´#Lesotho#E#Papua New $g##Portugal#¨#Qatar#6#$r of Ire$l#½#South Korea#Š#The Gambia#U#United Kingdom#º");
// turn the indexed into the wanted associative array
$k=0;while($k<299)$t[$x[$k++]]=$x[$k++];
// used 3 times -> saves 20 bytes when cached rather than call each time
$y=array_keys($t);
// Extract country and layer parameters from input (damn countries with spaces)
list($c, $l) = str_getcsv($s, ' ', '"');
// input not in array -> no neighbours -> output nothing
if(in_array($c, $y))
{
// convert country into its ASCII code via index number, accomodating for the 39 chars offset
$r = [chr(40+array_search($c, $y))];
// for each layer needed
while($l>$j++)
// go through ALL countries found so far
foreach($r as$d)
// and add their neighbours to the result
// (str_split returns the string as an array of chars)
$r = array_merge($r, str_split( array_values($t)[ord($d)-40] ));
// remove all the duplicates that were created doing that...
$r = array_unique($r);
// remove the initial country itself from the result
unset($r[0]);
// convert the index chars back into country names
foreach($r as$k=>$v)
$r[$k] = $y[ord($v)-40];
// output as list
echo implode($r, "\n");
}
}
```
### Golfed
```
function f($s){$r=Republic;$g=Guinea;$n=nia;$i=istan;$l=land;$x=explode('#',"China#:si) Š‘PQ@•¢h#Russia#‹|šjG98\]i( Š#Brazil#K›SHF®#Germany#…^£³Db.ƒW>#Democratic $r of the Congo#–LJ-Yov0t#Sudan#=Bz{NOY,J#Austria#ƒ+bV2pfW#Serbia#ua2TIk[‰#Zambia#t,7†CZ`R#Algeria#’¡¬B54l#Hungary#.V9T/ap#Iran#A8]\r:n#Mali#Ul15;M?#Niger#;41B=m_#Saudi Arabia#gA¹Œ°#Tanza$n#voYOC†0#Turkey#c)\]3AX#Ukraine#VDG)TŸ2#Afghan$i#3rs(hn#Burkina Faso#45_«~M#Cameroon#m=JL}™#Chad#5B-J<m#France#^…+Wf¨#$g#œU4M‚§#India#nh¢•Q“#Iraq#gX836#Libya#1¬z-=5#Mozambique#Z0†7E©#Po$l#+„G9Vb#South Africa#R`ZC©¶#Argentina#xH*®#Belarus#„j)9D#Bolivia#S*Fx#Bulgaria#/T8ck#Central African $r#<=-,L#Columbia#*S—¥#Congo#}<J,–#Cote D'Ivoire#‚?4;~#Ethiopia#-{yŽO#Kenya#Y-NŽ7#Laos#Q(‘wq#Myanmar#“@(Pq#Namibia#t0Z`E#Peru#—K*Hx#Roma$n#29ŸI/#Senegal#¼l4?œ#Slovakia#.bD92#Switzer$l#>+ƒ.f#Syria#ž8Age#Uganda#,-O7o#Zimbabwe#R0CE`#Alba$n#‰/kc#Arme$n#8)]3#Azerbaijan#8\)3#Belgium#>£+…#Benin#«;5m#Botswana#R0ZE#Croatia#p2/u#Czech $r#+DV.#Greece#[kI8#Guatemala#ˆ”˜€#Israel#zžXg#Italy#>W.p#Jordan#eXA6#Kashmir#n:(@#Kazakhstan#)(sr#Latvia#š)G„#Macedo$n#[/Ic#Maurita$n#’14U#Nigeria#_5=<#Pak$i#3:h@#Rwanda#,Y7v#Slove$n#f.2a#Thai$l#QPw‡#Turkmen$i#is:3#Uzbek$i#i(:r#Angola#,0R#Bos$n and Herzegovina#a/‰#Burundi#,o7#Cambodia#qP‘#Chile#SHF#Djibouti#N{Ž#Egypt#Be-#Eritrea#-yN#Fin$l#ª‹)#Gabon#™<L#Ghana#M;«#Guyana#*#Honduras#d˜¤#Indonesia#‡·#Liberia#§?M#Liechtenstein#W+.#Lithua$n#jGD#Luxembourg#>^+#Malawi#07C#Malaysia#q±#Mexico#¯”d#Montenegro#u/[#North Korea#()»#Norway#ª|)#Oman#6°#Paraguay#H*F#Somalia#ONy#Suriname#*›#Venezuela#K*#Vietnam#P(w#Western Sahara#¡1l#Bangladesh#@Q#Belize#ˆd#Bhutan#@(#Cabinda#L,#Ecuador#KS#El Salvador#d€#Equatorial $g#<}#Esto$n#)j#French Guiana#*#$g-Bissau#U?#Kuwait#A6#Lebanon#eX#Moldova#9T#Mongolia#()#Morocco#’1#Nepal#@(#Nether$ls#+^#Nicaragua#€¦#Panama#¦K#San Jose#¤¥#Sierra Leone#?‚#Spain#¸>#Swazi$l#EC#Sweden#‹|#Togo#~;#Tunisia#1B#United Arab Emirates#6Œ#Uruguay#F*#USA#²ˆ#Yemen#6Œ#Brunei#‡#Canada#¯#Denmark#+#Dominican $r#µ#Haiti#´#Lesotho#E#Papua New $g##Portugal#¨#Qatar#6#$r of Ire$l#½#South Korea#Š#The Gambia#U#United Kingdom#º");$k=0;while($k<299)$t[$x[$k++]]=$x[$k++];$y=array_keys($t);list($c,$l)=str_getcsv($s,' ','"');if(in_array($c,$y)){$r=[chr(40+array_search($c,$y))];while($l>$j++)foreach($r as$d)$r=array_merge($r,str_split(array_values($t)[ord($d)-40]));$r=array_unique($r);unset($r[0]);foreach($r as$k=>$v)$r[$k]=$y[ord($v)-40];echo implode($r,"\n");}}
```
## Edit of the update
Saved another 18 bytes by:
* stripping quotes off `$r='Republic'` etc. (-10)
* replacing `for` with `while` loop (-6)
* removing blanks after `as` keywords (-2)
I updated the above code with the changes.
## Another edit
Shaved off another 377 bytes by creating an indexed array from an imploded string first (making all `=>` and `"` obsolete, -417 bytes of overhead) and turning that into the wanted associative array afterwards (+40 bytes of code). Updated the above code again.
---
## Initial post
```
function f($s){$t=["Adaman and Nicobar Islands"=>[],"Afghanistan"=>[80,179,186,36,87,131],"Albania"=>[115,152,101,66],"Algeria"=>[190,117,177,97,126,106,109],"Angola"=>[45,192,120],"Argentina"=>[35,19,134,22,185],"Armenia"=>[178,144,9,80],"Australia"=>[],"Austria"=>[98,64,44,154,77,155,83,168],"Azerbaijan"=>[178,6,144,80],"Azores"=>[],"Bangladesh"=>[78,119],"Barbados"=>[],"Belarus"=>[99,93,144,182,137],"Belgium"=>[61,122,64,100],"Belize"=>[112,70],"Benin"=>[175,25,126,127],"Bhutan"=>[78,36],"Bioko"=>[],"Bolivia"=>[135,22,134,5,35],"Bosnia and Herzegovina"=>[41,152,115],"Botswana"=>[120,192,193,158],"Brazil"=>[37,188,73,164,62,135,19,134,5,185],"Brunei"=>[105],"Bulgaria"=>[152,143,178,66,101],"Burkina Faso"=>[106,126,16,175,65,40],"Burundi"=>[45,145,170],"Cabinda"=>[39,45],"Cambodia"=>[172,92,189],"Cameroon"=>[127,34,33,39,63,53],"Canada"=>[185],"Canary Islands"=>[],"Cape Verde"=>[],"Central African Republic"=>[29,34,163,45,39],"Chad"=>[126,97,163,33,29,127],"Chile"=>[135,19,5],"China"=>[1,186,88,144,114,128,189,92,119,78,17,121,87],"Columbia"=>[188,22,135,50,132],"Comoros"=>[],"Congo"=>[63,29,33,45,27],"Cote D'Ivoire"=>[96,71,106,25,65],"Croatia"=>[155,77,152,20],"Cuba"=>[],"Cyprus"=>[],"Czech Republic"=>[64,137,154,8],"Democratic Republic of the Congo"=>[27,39,33,163,181,145,26,192,4],"Denmark"=>[64],"Djibouti"=>[56,54,157],"Dominica"=>[],"Dominican Republic"=>[74],"Ecuador"=>[37,135],"Egypt"=>[97,82,163],"El Salvador"=>[70,76],"Equatorial Guinea"=>[29,63],"Eritrea"=>[163,47,56],"Estonia"=>[144,93],"Ethiopia"=>[163,54,47,157,89],"Falkland Islands"=>[],"Faroe Islands"=>[],"Fiji"=>[],"Finland"=>[167,129,144],"France"=>[14,100,64,168,83,161],"French Guiana"=>[164,22],"Gabon"=>[53,29,39],"Germany"=>[100,14,122,46,137,44,8,98,168,61],"Ghana"=>[40,25,175],"Greece"=>[2,101,24,178],"Greenland"=>[],"Guadeloupe"=>[],"Guam"=>[],"Guatemala"=>[112,15,52,76],"Guinea"=>[72,151,106,40,96,153],"Guinea-Bissau"=>[151,71],"Guyana"=>[188,22,164],"Haiti"=>[49],"Heard Island"=>[],"Honduras"=>[70,52,125],"Hungary"=>[8,154,182,143,152,41,155],"India"=>[131,87,121,17,119,11],"Indonesia"=>[105,133,7],"Iran"=>[81,178,9,6,179,1,131],"Iraq"=>[86,169,178,80,91,150],"Israel"=>[51,94,169,86],"Italy"=>[61,168,8,155],"Jamaica"=>[],"Japan"=>[],"Jordan"=>[82,169,81,150],"Kashmir"=>[131,1,36,78],"Kazakhstan"=>[144,36,186,179],"Kenya"=>[181,163,56,157,170],"Kerguelen Island"=>[],"Kuwait"=>[81,150],"Laos"=>[119,36,189,28,172],"Latvia"=>[55,144,13,99],"Lebanon"=>[82,169],"Lesotho"=>[158],"Liberia"=>[153,71,40],"Libya"=>[3,177,51,163,34,126],"Liechtenstein"=>[168,64,8],"Lithuania"=>[93,13,137],"Luxembourg"=>[61,14,64],"Macedonia"=>[2,152,24,66],"Madagascar"=>[],"Madeira Island"=>[],"Malawi"=>[192,170,118],"Malaysia"=>[172,23,79],"Mali"=>[151,109,3,126,25,40,71],"Malta"=>[],"Martinique"=>[],"Mauritania"=>[190,3,106,151],"Mauritius"=>[],"Mayotte"=>[],"Mexico"=>[185,15,70],"Moldova"=>[182,143],"Mongolia"=>[36,144],"Montenegro"=>[20,152,2],"Montserrat"=>[],"Morocco"=>[190,3],"Mozambique"=>[193,192,104,170,158,166],"Myanmar"=>[11,78,36,92,172],"Namibia"=>[4,192,193,21,158],"Nepal"=>[78,36],"Netherlands"=>[64,14],"New Caledonia"=>[],"New Zealand"=>[],"Nicaragua"=>[76,148],"Niger"=>[25,106,3,97,34,127,16],"Nigeria"=>[16,126,34,29],"North Korea"=>[36,144,160],"Norway"=>[167,60,144],"Oman"=>[150,183,191],"Pakistan"=>[80,1,87,78],"Panama"=>[148,37],"Papua New Guinea"=>[79],"Paraguay"=>[19,22,5],"Peru"=>[50,37,22,19,35],"Phillipines"=>[],"Poland"=>[64,99,13,182,154,44],"Portugal"=>[161],"Puerto Rico"=>[],"Qatar"=>[150],"Republic of Ireland"=>[184],"Reunion"=>[],"Romania"=>[77,182,113,24,152],"Russia"=>[129,60,55,93,13,182,178,6,9,88,36,114,128],"Rwanda"=>[45,181,170,26],"Saint Kitts and Nevis"=>[],"Saint Vincent"=>[],"San Jose"=>[125,132],"Sao Tome"=>[],"Saudi Arabia"=>[86,81,91,140,183,130,191],"Senegal"=>[174,109,106,71,72],"Serbia"=>[20,41,77,143,24,101,2,115],"Sierra Leone"=>[71,96],"Slovakia"=>[8,44,137,182,77],"Slovenia"=>[83,8,77,41],"Solomon Islands"=>[],"Somalia"=>[89,56,47],"South Africa"=>[120,21,193,118,166,95],"South Georgia"=>[],"South Korea"=>[128],"Spain"=>[138,61],"Sri Lanka"=>[],"Sudan"=>[34,97,51,54,56,89,181,45,33],"Suriname"=>[73,22,62],"Svalbard"=>[],"Swaziland"=>[158,118],"Sweden"=>[129,60],"Switzerland"=>[61,64,98,8,83],"Syria"=>[94,178,81,86,82],"Tanzania"=>[26,145,181,89,118,104,192],"Tasmania"=>[],"Thailand"=>[119,92,28,105],"The Bahamas"=>[],"The Gambia"=>[151],"Togo"=>[65,25],"Trinidad and Tobago"=>[],"Tunisia"=>[3,97],"Turkey"=>[66,144,6,9,80,81,169],"Turkmenistan"=>[88,186,1,80],"USA"=>[30,112],"Uganda"=>[45,163,89,170,145],"Ukraine"=>[154,137,13,144,143,113,77],"United Arab Emirates"=>[150,130],"United Kingdom"=>[141],"Uruguay"=>[5,22],"Uzbekistan"=>[88,36,1,179],"Vanuatu"=>[],"Venezuela"=>[37,22,73],"Vietnam"=>[92,36,28],"Western Sahara"=>[117,3,109],"Yemen"=>[150,130],"Zambia"=>[4,45,170,104,118,193,21,120],"Zimbabwe"=>[120,192,118,158,21]];list($c,$l)=str_getcsv($s,' ','"');$r=[array_search($c,array_keys($t))];for($i=0;$i<$l;$i++)foreach($r as $d)$r=array_merge($r,array_values($t)[$d]);$r=array_unique($r);unset($r[0]);foreach($r as $k=>$v)$r[$k]=array_keys($t)[$v];return implode($r,"\n");}
```
This is a rather quick first version, I didn't do ANY list compression besides the obvious numbers for names yet -- I might work on that tomorrow and edit my post then.
My list is a simple associative array with an entry for each country. The array key is the country's name and the value an array of its neighbours, referenced by their index in that array. PHP won't let you access associative arrays by index, so I needed a workaround using `array_keys` and `array_values` functions.
The actual code commented:
```
function f($s)
{
$t = ["Adaman and Nicobar Islands"=>[],"Afghanistan"=>[80,179,186,36,87,131],"Albania"=>[115,152,101,66],...,"Zimbabwe"=>[120,192,118,158,21]];
// Extract country and layer parameters from input (damn countries with spaces)
list($c, $l) = str_getcsv($s, ' ', '"');
// convert country into its index number
$r = [array_search($c, array_keys($t))];
// for each layer needed
for($i=0; $i<$l; $i++)
// go through ALL countries found so far
foreach($r as $d)
// and add their neighbours to the result
$r = array_merge($r, array_values($t)[$d]);
// remove all the duplicates that were created doing that...
$r = array_unique($r);
// remove the initial country itself from the result
unset($r[0]);
// convert the index numbers back into country names
foreach($r as $k=>$v)
$r[$k] = array_keys($t)[$v];
// output as list
return implode($r,"\n");
}
```
**As before and always, any remarks are very appreciated.**
[Answer]
# [Dyalog APL](http://goo.gl/9KrKoM), 82 bytes program + 1924 bytes data = 2006 bytes
```
{N S←{{1↓¨⍵⊂⍨⍵=⊃⍵}0(220⌶)¯2(219⌶)¯128+⎕UCS⍵}¨829(↑{⍺ ⍵}↓)'………'
S[∪{∊N[⍵]}⍣⍵⊢S⍳⊂⍺]~⊂⍺}
```
I did not do anything special to pack the data beyond using Dyalog APL's built-in (de-)serialize (`220⌶`) and (un-)zip (`219⌶`).
Where the ellipses stand in for a zlib'ed string with these byte values:
```
248 90 45 21 235 211 76 225 152 70 175 10 138 165 197 222 176 99 5 119 140 150 217 105 192 171 234 83 193 187 99 88 233 211 162 34 230 18 178 252 135 17 83 82 82 233 83 209 169 157 54 4 79 96 53 47 98 119 92 59 232 60 180 26 249 110 107 247 221 119 125 188 79 63 127 255 26 254 140 252 215 108 231 79 94 24 30 204 8 135 218 175 7 107 236 237 208 162 26 0 238 212 18 17 115 9 70 9 228 73 232 18 210 40 73 90 196 205 81 230 106 150 37 171 195 91 172 89 140 39 70 51 180 180 149 93 10 38 33 46 59 5 164 13 164 195 25 90 33 172 109 52 180 3 58 77 118 230 234 187 28 129 57 238 12 179 161 209 83 205 55 91 78 244 91 25 229 39 254 219 51 246 51 246 125 21 125 107 90 79 90 151 103 3 186 164 143 250 128 245 110 64 239 247 196 199 245 204 249 138 104 2 174 106 18 42 245 217 215 104 249 217 158 250 226 66 67 196 182 100 166 243 81 236 72 67 158 71 167 20 35 99 186 140 103 75 39 83 186 35 162 91 29 195 173 34 99 229 66 209 14 29 104 229 47 59 45 0 233 209 243 241 158 29 82 201 149 218 183 23 76 135 121 104 103 178 103 82 188 122 2 114 24 170 21 95 58 133 22 122 213 44 51 120 83 108 76 167 171 68 213 112 132 226 249 109 28 156 238 119 98 170 212 233 207 97 229 86 7 147 75 71 252 177 244 150 117 43 132 170 198 79 33 165 208 161 103 23 42 220 229 22 120 241 129 213 97 221 87 207 170 242 191 62 138 170 3 202 13 10 56 75 231 79 244 94 94 195 37 245 75 105 134 32 170 254 215 119 22 107 149 212 131 89 31 239 149 32 99 242 89 247 112 152 249 120 150 181 42 3 42 109 235 57 250 149 245 223 39 22 78 165 60 123 214 119 85 41 142 93 209 27 110 42 21 30 123 6 53 54 47 30 218 3 235 85 237 75 235 72 93 73 193 238 57 72 189 245 248 87 233 98 233 130 244 26 245 157 247 141 142 18 181 66 13 244 36 71 228 141 164 177 159 52 41 166 52 217 183 244 211 173 58 229 231 58 180 54 218 44 94 52 188 102 106 57 41 21 231 148 119 85 114 196 177 234 101 9 91 248 118 246 146 17 45 45 157 235 94 206 59 37 29 58 135 247 32 221 106 182 42 102 247 111 50 52 147 110 194 111 193 119 205 159 104 161 90 157 191 33 219 15 40 143 127 83 223 22 219 189 60 11 136 122 212 207 248 191 145 141 235 80 220 143 117 25 250 201 251 200 66 250 238 126 169 53 23 122 75 5 117 130 250 9 143 171 36 215 112 139 219 161 106 171 180 44 190 61 81 235 220 136 149 148 162 145 156 34 119 214 111 236 122 185 167 141 98 122 236 223 152 158 208 191 189 183 89 199 94 15 62 195 135 80 254 244 208 195 80 219 166 93 243 142 99 220 231 0 252 216 159 32 193 82 8 38 224 183 183 12 251 44 145 13 234 220 147 26 164 151 93 119 248 49 198 180 230 254 4 228 12 137 49 198 225 177 155 1 70 116 137 30 4 71 33 217 248 222 159 185 163 194 255 214 243 218 84 130 89 135 238 9 176 117 145 158 2 39 32 153 205 219 231 6 186 13 58 94 140 186 69 92 60 29 185 65 9 243 198 51 246 75 156 186 65 189 209 173 241 46 88 177 233 93 197 253 198 151 32 207 244 34 218 86 10 165 11 120 168 58 140 173 65 43 122 2 123 12 11 66 171 241 222 6 93 110 197 91 55 234 105 138 156 229 122 171 238 85 78 216 53 127 194 191 129 153 5 154 24 248 90 213 213 193 246 107 182 140 124 59 158 35 90 125 141 250 136 91 241 146 71 241 26 198 206 122 26 157 228 161 146 227 10 244 192 82 126 118 249 250 47 94 32 231 104 16 50 125 254 51 48 196 210 132 134 3 65 100 31 63 127 125 182 126 125 122 253 252 190 125 178 190 105 53 30 80 12 157 55 204 171 121 225 182 30 110 146 199 153 88 178 205 69 26 19 80 92 214 181 91 189 55 222 105 94 59 182 169 135 250 178 155 214 110 146 211 77 46 250 112 193 104 153 225 134 38 25 55 233 232 140 83 27 184 185 165 193 32 59 244 68 153 85 201 141 190 145 58 213 241 27 62 58 203 166 239 207 21 207 70 82 252 19 202 10 231 81 196 211 239 77 158 177 230 61 49 185 242 201 245 36 9 246 98 162 2 80 43 38 50 51 110 37 26 242 15 68 1 230 41 225 250 64 171 48 81 189 27 232 104 70 143 70 225 105 42 151 89 37 70 26 141 189 167 81 104 43 23 220 235 77 70 69 234 233 226 140 149 59 54 250 18 61 137 52 114 174 134 209 101 24 73 232 69 122 52 19 235 168 218 49 130 2 121 202 242 62 127 230 92 134 48 232 74 90 32 4 192 235 84 233 218 238 203 76 53 239 56 131 45 170 98 172 182 232 242 114 170 1 238 89 238 115 58 218 4 124 136 212 123 148 193 10 248 109 242 101 60 19 106 205 52 149 164 236 69 168 31 191 172 109 82 99 117 90 173 43 23 107 106 210 230 101 191 42 5 202 57 112 106 204 20 150 229 58 46 117 131 85 251 54 141 235 203 207 222 143 32 48 190 200 171 14 238 77 136 111 165 5 0 124 183 98 134 86 173 77 195 116 142 107 199 14 57 161 15 166 118 9 115 134 84 65 26 130 93 9 142 108 14 116 164 49 151 157 209 96 44 179 233 32 71 116 195 6 70 167 109 104 89 15 216 54 138 78 4 230 167 1 130 46 205 41 45 95 115 150 209 215 94 54 248 37 151 191 20 172 119 73 245 40 22 166 169 196 173 121 241 175 10 139 209 140 176 171 3 250 212 224 98 233 76 221 162 201 62 185 211 79 177 99 116 129 75 82 10 251 81 19 244 254 31 133 212 11 230 17 206 19 197 124 18 88 161 44 244 106 233 130 250 242 4 149 239 36 173 69 175 162 219 144 53 131 244 148 34 177 245 236 203 199 17 252 29 244 171 199 252 236 163 18 158 247 25 19 9 142 133 67 132 40 154 182 31 108 232 73 167 94 118 161 98 149 41 186 104 27 243 131 80 113 165 100 64 103 110 15 111 208 253 22 120 41 17 45 169 183 166 159 221 143 200 101 189 103 75 81 75 226 33 99 79 151 85 71 194 15 128 58 71 214 208 150 203 143 222 219 252 208 243 234 205 181 209 78 149 175 83 129 35 193 255 240 228 61 200 163 159 213 115 129 162 11 208 102 111 32 30 126 146 164 65 100 29 145 172 185 116 184 39 5 235 179 240 89 1 0 233 31 114 81 20 221 231 161 81 80 211 45 38 250 228 55 197 101 173 102 80 13 195 5 201 3 94 46 146 221 65 140 160 173 12 174 27 82 50 199 70 76 60 153 9 176 135 40 155 2 233 139 123 22 15 217 9 211 205 206 140 189 67 138 44 89 193 188 161 35 112 248 98 112 25 247 9 177 55 7 108 166 142 92 149 33 240 230 247 77 225 84 80 131 111 128 147 35 140 109 251 107 135 111 46 216 94 88 65 110 146 68 127 233 168 199 25 49 189 119 188 47 94 5 139 66 37 232 135 167 19 75 197 58 151 140 80 229 49 226 152 219 180 169 207 223 242 134 116 47 120 104 227 4 74 17 204 209 156 166 24 187 142 48 204 116 66 67 146 224 2 211 99 55 30 102 93 241 151 33 106 102 136 64 56 28 235 26 88 206 198 201 42 95 64 37 126 148 40 221 157 220 56 7 145 30 83 21 74 106 44 216 244 162 59 96 157 151 87 157 233 120 237 234 194 96 244 222 209 237 50 29 213 15 130 86 242 50 146 254 102 35 212 183 95 151 251 239 180 27 12 181 24 134 93 194 250 85 173 135 184 214 31 93 249 109 225 222 211 104 77 65 115 1 235 124 173 86 76 24 54 20 117 181 135 30 44 91 27 207 3 225 7 109 78 227 239 124 174 131 68 152 103 222 172 69 33 64 87 142 244 229 235 153 124 134 210 3 203 125 236 215 48 15 234 22 199 3 230 240 211 116 48 26 252 104 127 61 155 98 144 117 160 248 126 5 54 249 64 48 23 62 95 241 3 125 113 126 75 33 100 193 181 137 242 5 144 92 41 80 181 67 128 100 3 201 30 191 38 119 17 49 172 52 3 129 91 39 60 78 54 126 238 6 6 27 131 250 100 227 184 228 150 30 248 176 13 57 204 105 8 139 54 19 127 241 149
```
Note that both the encoded string, and the rest of the program fits in APL's 256 character code page, i.e. one symbol per byte.
Here is what is all looks like when put together, (`␀` standing in for U+0000):
```
{N S←{{1↓¨⍵⊂⍨⍵=⊃⍵}0(220⌶)¯2(219⌶)¯128+⎕UCS⍵}¨829(↑{⍺ ⍵}↓)'øZ-ëÓLáF¯
¥ÅÞ°cwÙiÀ«êSÁ»cXéÓ¢"æ²üSRRéSÑ©6O`5/bw\;è<´ùnk÷Ýw}¼O?ÿþü×lçO^ÌÚ¯kìíТ␀îÔs F äIèÒ(IZÄÍQæj%«Ã[¬Y'F3´´]
&!.;¤
¤ÃZ!¬m4´:Mvæê»9ÑSÍ7[Nô[å'þÛ3ö3ö}}kZOZgº¤úõn@ï÷ÄÇõÌùh®j*õÙ×hùÙúâBCĶd¦óQìHCG§#cºgK'Sº#¢[Ã"cåBÑhå/;-␀éÑóñRÉÚ·Lyhg²gR¼zrª_:zÕ,3xSlL§«DÕpâùmîwbªÔéÏaåVKGü±ôu+ªÆO!¥Ð¡g*ÜåxñÕaÝWϪò¿>ªÊ
8KçOô^^Ã%õKi ªþ×wkÔYï còY÷pùxµ**më9úõß'N¥<{ÖwU)]Ñn*{56/ÚëUíKëH]IÁî9H½õøWébéôõ÷µB
ô$G䤱4)¦4Ù·ôÓ:åç:´6Ú,^4¼fj9)çwUrıêe [øvö--ë^Î;%:÷ Ýj¶*f÷o24nÂoÁwÍh¡Z¿!Û(SßÛ½<zÔÏø¿ëPÜuúÉûÈBúî~©5zKuú «$×pÛ¡j«´,¾=QëÜ¢"wÖoìz¹§bzìßп½·YÇ^>ÃPþôÐÃPÛ¦]ócÜç␀üØ ÁR&à··û,
êܤ]wø1Æ´æþä1Æá±FtG!ÙøÞ¹£ÂÿÖóÚTYî °u' ÍÛçº
:^ºE\<¹A óÆ3öKºA½Ññ.X±é]ÅýÆ Ïô"ÚV
¥x¨:A+z{B«ñÞ]nÅ[7êiåz«îUNØ5¿øZÕÕÁök¶|;#Z}ú[ñGñÆÎzä¡ã
ôÀR~vùú/^ çh2}þ30ÄÒAd?}¶~}zýü¾}²¾i5P7Ì«yá¶nÇX²ÍEP\Öµ[½7Þi^;¶©ú²ÖnÓM.úpÁhá&7éèS¸¹¥Á ;ôDUɾ:Õñ>:˦ïÏÏFRüÊ
çQÄÓïM±æ=1¹òÉõ$ öb¢P+&23n%òDæ)áú@«0Q½èhFFái*Y%F½§Qh+ÜëMFEêéâ;6ú=4r®ÑeIèEz4ë¨Ú1yÊò>æ\0èJZ ÀëTéÚîËL5ï8-ªb¬¶èòrªîYîs:Ú|Ô{Á
ømòe<jÍ4¤ìE¨¿¬mRcuZ+kjÒæe¿*Ê9pjÌå:.uUû6ëËÏÞ 0¾È«îMo¥␀|·bVMÃtkÇ9¡¦v sTA] lt¤1Ñ`,³é GtÃF§mhYØ6Næ§.Í)-_sÑ×^6ø%¿¬wIõ(¦©Äyñ¯
Ѱ«úÔàbéLÝ¢É>¹ÓO±ctKR
ûQôþÔæÎÅ|X¡,ôjéúòï$E¯¢Û5ô"±õìËÇüô«Çüì£÷ C(¶lèI§^v¡b)ºhóPq¥d@gnoÐýx)-©·¦ÝÈe½gKQKâ!cOUGÂ:GÖÐËÞÛüÐóê͵ÑN¯S#Áÿðä=È£Õs¢Ðfo ~¤Ad¬¹t¸'ë³ðY␀érQÝç¡QPÓ-&úä7ÅefP
ÃÉ^.ÝA ®R2ÇFL< °(é{Ù ÓÍνC,YÁ¼¡#pøbp÷ ±7l¦\!ðæ÷MáTPo#mûko.Ø^XAnDé¨Ç1½w¼/^B%è§KÅ:På1âÛ´©Ïßòt/xhãJÌѦ»0ÌtBCàÓc7f]ñ!jf@8ëXÎÆÉ*_@%~(ÝÜ8SJj,Øô¢;`WéxíêÂ`ôÞÑí2ÕVò2þf#Ô·_ûï´µ]ÂúU¸Ö]ùmáÞÓhMAsë|VL6uµ,[ÏámNãï|®DgÞ¬E!@Wôåë|ÒË}ì×0êÇæðÓt0üh=bu ø~6ù@0>_ñ}q~K!dÁµò\)PµCdÉ¿&w1¬4['<N6~îúdã¸äø°
9Ìi6ñËp1w_>}Ö!/'
S[∪{∊N[⍵]}⍣⍵⊢S⍳⊂⍺]~⊂⍺}
```
] |
[Question]
[
A double precision representation of a decimal can only guarantee an accuracy of 15 decimal places, thus pi is approximated as:
```
3.141592653589793
```
You can see that the digit `3` is in positions `1, 10, 16`, the digit `1` is in positions `2, 4` etc.
**Challenge**
Your task is to create a program or function that creates a random double number between 0 and 1, and maps the values of that number onto the value of pi. You do this by placing the different digits in the random numbers in the position that digit has in pi. If the digit is not found in pi, you'll skip it, and every digit in pi that's not in the random number will be represented by an `x`. Each value can only be used once, starting from the left.
A few examples will probably make this more clear. In the following examples, the first number is pi, the second is the random number, and the last is the desired output.
```
3.141592653589793
0.111111111111111
x.1x1xxxxxxxxxxxx
3.141592653589793
0.531000000000000
3.1xx5xxxxxxxxxxx
3.141592653589793
0.123456789123456
3.141592653x8x7xx
3.141592653589793
0.967552381459391
3.14159265358979x
```
Rules:
* The function should not take any input (a possible exception is explained in bullet point 3)
* The output shall consist of only the output string, with an optional newline (a single trailing space is also accepted)
* If your program doesn't have a built-in Pi-value, and/or a RNG then you can hardcode Pi, and take the random number as input. You cannot hardcode the random number or take Pi as input.
* Both the hardcoded value for Pi, and the 15 random digits (you can skip `0.` since you know it will be between 0 and 1), will be included in the byte count.
* If your language doesn't have the required precision, you can use less precision under the following restrictions
+ The digits of Pi must be accurate up to the precision you have
+ You can't output more values than you're guaranteed to have correct, i.e. you can't output 15 digits if the precision only allows 8 accurate decimals.
+ The hardcoded value of Pi will count as 16 bytes (you don't need the decimal point), even if your program only supports 8 digits.
+ The input value for the random number will count as 15 bytes (you don't need `0.`. This is because languages with low precision should not have an unfair advantage.
+ The program must support 5 decimals precision (at least).
+ **Edit: To validate the answer: The random number should be printed somehow, but this operation doesn't have to be included in the byte count. So for instance, if it's possible to insert a `print r` in the end of the script, that part will not increase the score.**
+ You cannot subtract the bytes if it's part of another necessary operation. I.e. if the code is `print pi, r`, then you can only subtract `, r`.
+ If you have to insert parts several places in the code, please include both versions (the one that prints the random number and the one that doesn't with a comment such as: `_p` and `_oNo` are needed to print the random number. `_p` does xxx and `_oNo` does yyy. `_p` and `_oNo` will not be included in the byte count.
Shortest code in bytes win.
---
## Leaderboard
The Stack Snippet at the bottom of this post generates the catalog from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.
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 snippet:
```
## [><>](http://esolangs.org/wiki/Fish), 121 bytes
```
```
var QUESTION_ID=67223,OVERRIDE_USER=44713;function answersUrl(e){return"https://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"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```
```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```
[Answer]
# LabVIEW, 53 [LabVIEW Primitives](http://meta.codegolf.stackexchange.com/a/7589/39490)
I match Strings and put the number into an "empty" x.xxx string and remove the number from pi so it doesn´t show up again.
the random number and the single chars here are kinda visible, is that all right or do i have to redo the recording?
[](https://i.stack.imgur.com/05NTV.gif)
[Answer]
# Mathematica, 105 or 147 characters
If random number "*between* 0 and 1" means `0 <= random <= 1`, i.e. includes 0 & 1.
```
StringReplace[ToString@InputForm@N@Pi,
Thread[ToString/@Complement[Range@9,RandomInteger[{0,9},15]]->"x"]]
```
(105 characters)
Otherwise, taking random number "*between* 0 and 1" to mean `0 < random < 1`.
Loop to get 15 random integers, not all zero. Select complement from 0 to 9 range, i.e. those numbers from 0 to 9 not in the random list. Convert those integers to strings and replace the matching characters in a pi string.
(147 characters)
```
While[True,r=RandomInteger[{0,9},15];
If[Union@r!={0},Break[]]];
StringReplace[ToString@InputForm@N@Pi,
Thread[ToString/@Complement[Range@9,r]->"x"]]
3.1x15x265358x7x3
```
Random digits:-
```
FromDigits[r]
820307536180783
```
[Answer]
# Pyth, 25 bytes
```
u&p?}HGH\x.-GH`.n0<`O017
```
Try it online: [Demonstration](https://pyth.herokuapp.com/?code=+u%26p%3F%7DHGH%5Cx.-GH%60.n0%3C%60O017&debug=0) or [Test showing the random number](https://pyth.herokuapp.com/?code=%20u%26p%3F%7DHGH%5Cx.-GH%0A%60.n0%0A%3C%60O017&debug=0)
### Explanation:
```
u&p?}HGH\x.-GH`.n0<`O017
.n0 the constant pi
` convert it into a string
O0 random number in the range [0.0, 1.0)
` convert to string
< 17 only use the first 17 chars (zero, point and 15 digits)
u for each char H in the pi-string:
?}HGH\x if H in G (the random number string) then H else "x"
p print this char without newline
& and
.-GH remove the digit H once from G
<space> suppress the output (u returns the unused digits in G)
```
[Answer]
# JavaScript (ES6), ~~89~~ 87 bytes
```
_=>(r=[...Math.random()+""],Math.PI+"").replace(/./g,d=>(r[i=r.indexOf(d)]=_,~i?d:"x"))
```
## Explanation
**Edit:** Random string is now not truncated as clarified by the poster.
Loops through each digit of pi and removes the digit from the random number if it was found, else replaces the digit in pi with `x`.
```
_=>(
r=[...Math.random()+""], // r = array of 15 digit random number chars
Math.PI+"").replace(/./g,d=>( // for each digit d of pi, includes "." which is always
// in the random number
r[i=r.indexOf(d)]=_, // i = position of d within r, remove digit from r
// "_" is the unused function argument (equals undefined)
~i?d:"x" // if found, leave the digit, else replace with x
))
```
## Test
Test outputs the random number also.
```
var solution = _=>(r=[...n=Math.random()+""],Math.PI+"").replace(/./g,d=>(r[i=r.indexOf(d)]=_,~i?d:"x"))
```
```
<button onclick="result.textContent='Result: '+solution()+'\nNumber: '+n">Go</button>
<pre id="result"></pre>
```
[Answer]
## CJam, ~~48~~ ~~46~~ ~~42~~ ~~38~~ 36 bytes
```
P`'xf+1dmr`{1$f#:!1a/0=:)W+H<.%}/1f=
```
[Test it here.](http://cjam.aditsu.net/#code=P%60'xf%2B1dmr%60%7B1%24f%23%3A!1a%2F0%3D%3A)W%2BH%3C.%25%7D%2F1f%3D)
And here is the version which prints both π and the random number:
```
P_p`'xf+1dmr`_oNo{1$f#:!1a/0=:)W+H<.%}/1f=
```
[Test it here.](http://cjam.aditsu.net/#code=P_p%60'xf%2B1dmr%60_oNo%7B1%24f%23%3A!1a%2F0%3D%3A)W%2BH%3C.%25%7D%2F1f%3D)
I do not truncate the random number to 15 decimal places, as clarified by the OP in a comment.
### Explanation
The idea is to turn each character in the string representation of π into a pair of that character and `x`. For each character in the random number, we swap the first pair which starts with that character. At the end we output the second character of each pair.
```
P` e# Get string representation of π.
'xf+ e# Append "x" to each character.
1dmr` e# Get string representation of random number in [0,1).
{ e# For each character in that string...
1$ e# Copy the list of pairs.
f# e# For each pair, find the index of the current character. If the character is
e# not in the pair, we get -1 (truthy). If it is the first character of the pair,
e# we get 0 (falsy). If it is the second character, we get 1 (truthy).
:! e# Logical NOT for each of the results. We get a 1 for every pair we could
e# potentially swap.
1a/ e# Split around those 1s.
0= e# Keep only the first chunk.
:) e# Turn all the 0s into that chunk into 1s.
W+ e# Append a -1.
H< e# Truncate to 17 elements (the number of pairs).
.% e# Apply % pairwise. This reverses the element at the position of the -1.
}/
1f= e# Select the second character from each pair.
```
[Answer]
# Lua, ~~231~~ 230 bytes
```
m,s=math,""p,r=m.pi..s,s..m.random()p=p:sub(1,#p-1)p:gsub(".",function(c)s=s..(47>c:byte()and c or"x")end)r:gsub("[^%.]",function(c)l=p:find(c)if l then p,s=p:sub(1,l-1).."x"..p:sub(l+1),s:sub(1,l-1)..c..s:sub(l+1)end end)print(s)
```
### Explanations
```
function f()
m,s=math,""
p,r=m.pi..s,s..m.random()
p=p:sub(1,#p-1) -- remove the last digit of math.pi
p:gsub(".",function(c)
s=s..(47>c:byte()and c or"x") -- Construct a string full of "x" with a single dot
end)
r:gsub("[^%.]",function(c) -- Iterate over each character but the dot in the random number
l=p:find(c) -- if c isn't in pi, l=nil
if l -- which is one of the two falsy value in lua
then
p,s=p:sub(1,l-1).."x"..p:sub(l+1),-- If c is in pi, we replace it in p by an x
s:sub(1,l-1)..c..s:sub(l+1) -- and in s by its value
end
end)
return s
end
```
Sadly, lua doesn't help me at all here. math.pi round the last digit of pi it return :
```
print(math.pi)
>> 3.1415926535898
```
I have to truncate this number :
```
stringPI=""..math.pi
print(stringPI:sub(1,#stringPI-1))
>> 3.141592653589
```
The second big default to do this challenge was lua lack of string.replace(). As I'm doing this action twice using `s:sub(1,l-1)..c..s:sub(l+1)`, I wanted to do an anonymous function, thinking it would be shorter. It isn't, so I kept it written twice.
The reason I have to be careful about the dot, is how lua return its position. In regexes, a dot mean "any character", so when i'm evaluating the character `.` in my loop it matches the first character :
```
c="." -- The value of the dot in the loop
found = stringPI:find(c)
print(stringPI)
print("location of \".\": "..found)
print("char at "..found..": "..stringPI:sub(found,found))
>> 3.141592653589
>> location of ".": 1 --Keep in mind that lua arrays are 1-based :)
>> char at 1: 3
```
You can test lua [online](http://www.lua.org/cgi-bin/demo). As I am not seeding the PRNG, here's a code allowing you to run several test while still watching values.
```
function f()m,s=math,""p,r=m.pi..s,s..m.random()print("Random number: "..r)p=p:sub(1,#p-1)p:gsub(".",function(c)s=s..(c:byte()<47 and c or"x")end)r:gsub("[^%.]",function(c)l=p:find(c)if l then p,s=p:sub(1,l-1).."x"..p:sub(l+1),s:sub(1,l-1)..c..s:sub(l+1)end end)return s end
for i=1,10
do
print(f())
end
```
[Answer]
## Python 2.7, ~~117~~ 110 bytes
```
import math,random
n=list(`random.random()`)
print''.join(n.pop(n.index(d))if d in n else'x'for d in`math.pi`)
```
Tested on the latest QPython Android app, but should work anywhere.
Edit 1: changed `str(pi)` to backticks.
For testing:
```
import math,random
n=list(`random.random()`)
print `math.pi`
print ''.join(n)
print''.join(n.pop(n.index(d))if d in n else'x'for d in`math.pi`)
```
[Answer]
# Python, 147 bytes
```
import math as m,random as r
L=lambda t:[_ for _ in str(t)]
p=L(m.pi)
R=L(r.random())
A=""
print R #subtracted from byte count
for n in p:
try:R.remove(n);A+=n
except:A+='x'
print A
```
Fairly self-explanatory: lambda function converts float to list; we then loop through the pi-list attempting to remove each digit from the random-list. If we can, good, append it to the answer; if not, append an 'x' instead.
[Answer]
# Perl, 70 bytes
```
$_=4*atan2(1,1);s/\d/x$&/g;for$i(rand=~/\d/g){s/x$i/$i/}s/x./x/g;print
```
With comments:
```
$_=4*atan2(1,1); # Perl doesn't have a Pi constant
s/\d/x$&/g; # prepend a x to all digits in Pi
for $i (rand=~/\d/g) # iterate the digits in the random number
{ s/x$i/$i/ } # replace first occurrence of x-nr pair
s/x./x/g; # strip all remaining numbers
print # print!
```
---
This version will print pi, the random number, and the result:
```
$_=$p=4*atan2(1,1);
s/\d/x$&/g;
$r=rand;
for $i ($r=~/\d/g)
{ s/x$i/$i/ }
s/x./x/g;
print "$p\n$r\n$_\n"
```
Example output:
```
3.14159265358979
0.877757977767946
x.x4x59x6xxx897x
```
I hope this is okay:
* pi contains 15 digits total, including the 3, so it doesn't exceed accuracy.
* the last digit (`9`) is accurate.
] |
[Question]
[
A [Young diagram](http://en.wikipedia.org/wiki/Young_tableau#Diagrams) is an arrangement of boxes in left-justified rows and top-justified columns. For each box, all the spaces above it and to its left are occupied.
```
XXXXX
XXX
XXX
X
```
The [hook length](http://en.wikipedia.org/wiki/Hook_length_formula) of a box is the number of boxes to its right in its row, and below it in its column, also counting itself once. For example, the second box has a hook length of 6:
```
X****
X*X
X*X
X
```
Here are all the hook lengths:
```
86521
532
421
1
```
Your goal is compute the *product* of the hook lengths, here `8*6*5*2*1*5*3*2*4*2*1*1 = 115200`.
(Read about the [hook length formula](http://en.wikipedia.org/wiki/Hook_length_formula) if you're interested in why this expression matters.)
**Input:** A collection of row-sizes as numbers like `[5,3,3,1]` or as a repeated unary symbol like `[[1,1,1,1,1], [1,1,1], [1,1,1], [1]]` or `"XXXXX XXX XXX X"`. You can expect the list to be sorted ascending or descending, as you wish. The list will be non-empty and only contain positive integers.
**Output:** The product of hook lengths, which is a positive integer. Don't worry about integer overflows or runtime.
Built-ins dealing specifically with Young diagrams or integer partitions are not allowed.
**Test cases:**
```
[1] 1
[2] 2
[1, 1] 2
[5] 120
[2, 1] 3
[5, 4, 3, 2, 1] 4465125
[5, 3, 3, 1] 115200
[10, 5] 798336000
```
[Answer]
# CJam, ~~20~~ 19 bytes
```
{ee::+W%}_q~%z%:+:*
```
This takes in CJam style unary list in an ascending order. For example:
```
[[1] [1 1 1] [1 1 1] [1 1 1 1 1]]
```
gives
```
115200
```
**How it works**
This version is provided by Dennis and it uses the fact that a `Block ArrayList %` still works in CJam :D
```
{ }_ e# Put this block on stack and make a copy
q~ e# Read the input and evaluate it to put the array of arrays on stack
% e# Use the copy of the block and map the array using that block
ee e# Here we are mapping over each unary array in the input. ee converts
e# the array to [index value] pair.
::+ e# Add up each index value pair. Now we have the horizontal half of
e# hook length for each row
W% e# Reverse the array to make sure the count is for blocks to the right
z% e# Transpose and do the same mapping for columns
:+ e# Now we have all the hook lengths. Flatten the array
:* e# Get the product of all hook lengths.
```
---
*This is the original 20 bytes version*
```
1q~:,Wf%z:ee{:+)*}f/
```
This takes in a CJam style list of row-sizes in an ascending order. For example:
```
[1 3 3 5]
```
gives
```
115200
```
**How it works**
If we look at it, hook length of each block in a Young block diagram is the sum of the index of that block in its row and column, counting backwards. i.e. Start the index in each row from right side and start the index in each column from bottom.
We take the input in ascending order of row-size in order to easily start the index from bottom in each column. First, we get the index per row and reverse it. Then we transpose. Since the original row order was reversed, taking index in this transposed diagram will directly give the bottom to top index.
**Code expansion**
```
1 e# This serves as the initial term for product of hook lengths
q~ e# Read the input and eval it to put an array on stack
:, e# For each row-size (N), get an array of [0..N-1]
Wf% e# Reverse each row so that each row becomes [N-1..0]
z e# Transpose for the calculation of blocks below each block
:ee e# Enumerate each row. Convert it into array of [index value] pairs
{ }f/ e# Apply this mapping block to each cell of each row
:+ e# Add the index value pair. Here, index is the blocks below the
e# block and value is the blocks to the right of it in the Young diag
) e# Increment the sum by 1 to account for the block itself
* e# Multiply it with the current holding product, starting with 1
```
[Try it online here](http://cjam.aditsu.net/#code=1q~%3A%2CWf%25z%3Aee%7B%3A%2B)*%7Df%2F&input=%5B1%203%203%205%5D)
[Answer]
# J, 24 bytes
```
*/@,@(1|@-+/\."1++/\)@:>
```
25 bytes (with explanation):
```
*/@,@(+/\."1|@<:@++/\)@:>
```
Takes input as list of ascending lists of unary digits similar to the example `[[1], [1,1,1], [1,1,1], [1,1,1,1,1]]`.
Usage:
```
f=.*/@,@(+/\."1|@<:@++/\)@:>
f 1;1 1 1;1 1 1;1 1 1 1 1
115200
```
Method
* Create a binary matrix from the input
* Compute the running differences in both dimensions.
* For each cell add the two results, subtract 1, take the absolute value (to map the originally zero cells to 1)
* Ravel the matrix and take the product of the numbers.
Intermediate results shown on the input `1 1 1 1 1;1 1 1;1 1 1;1 (5,3,3,1 in unary)` (*this is for a previous version with descending lengths but using the same method*):
```
]c=.1 1 1 1 1;1 1 1;1 1 1;1
┌─────────┬─────┬─────┬─┐
│1 1 1 1 1│1 1 1│1 1 1│1│
└─────────┴─────┴─────┴─┘
(>) c
1 1 1 1 1
1 1 1 0 0
1 1 1 0 0
1 0 0 0 0
(+/\.@:>) c
4 3 3 1 1
3 2 2 0 0
2 1 1 0 0
1 0 0 0 0
(+/\."1@:>) c
5 4 3 2 1
3 2 1 0 0
3 2 1 0 0
1 0 0 0 0
((+/\."1++/\.)@:>) c
9 7 6 3 2
6 4 3 0 0
5 3 2 0 0
2 0 0 0 0
((+/\."1<:@++/\.)@:>) c
8 6 5 2 1
5 3 2 _1 _1
4 2 1 _1 _1
1 _1 _1 _1 _1
((+/\."1|@<:@++/\.)@:>) c
8 6 5 2 1
5 3 2 1 1
4 2 1 1 1
1 1 1 1 1
(,@(+/\."1|@<:@++/\.)@:>) c
8 6 5 2 1 5 3 2 1 1 4 2 1 1 1 1 1 1 1 1
(*/@,@(+/\."1|@<:@++/\.)@:>) c
115200
```
Same length explicit version:
```
3 :'*/,|<:(+/\."1++/\)>y'
```
[Try it online here.](http://tryj.tk/)
[Answer]
# Pyth - 21 bytes
I'm losing a lot of bytes in the vertical calculation. Gonna focus on golfing that.
```
*Fs.em+lf>Td>Qkt-bdbQ
```
Takes input like `[5, 3, 3, 1]`.
[Try it here online](http://pyth.herokuapp.com/?code=*Fs.em%2Blf%3ETd%3EQkt-bdbQ&input=%5B5%2C%203%2C%203%2C%201%5D&debug=1).
[Answer]
# Pyth, 18 bytes
```
*Fsm.e+k-bdf>TdQeQ
```
Takes input in ascending order, like `[1, 3, 3, 5]`.
[Demonstration.](https://pyth.herokuapp.com/?code=*Fsm.e%2Bk-bdf%3ETdQeQ&input=%5B1%2C%203%2C%203%2C%205%5D&debug=0)
---
**Alternate solution, 19 bytes**
```
*Fs.em+s>Rd<Qk-bdbQ
```
[Answer]
# Python 2, ~~89~~ 88 bytes
```
p=j=-1;d={}
for n in input():j+=1;i=0;exec"a=d[i]=d.get(i,j);p*=n-i+j-a;i+=1;"*n
print-p
```
*(Thanks to @xnor for one insane byte save by combining `p` and `j`)*
The `d.get` looks a little suspicious to me, but otherwise I'm relatively happy with this. I tried some other approaches, like recursion and zipping, but this is the only one I managed to get under 100.
Takes input from STDIN as a list in ascending order, e.g. `[1, 3, 3, 5]`.
[Answer]
# Haskell, 68 bytes
```
f[]=1
f g@(h:t)=(h+length t)*f[x-1|x<-g,x>1]
p[]=1
p g@(_:t)=f g*p t
```
Usage example: `p [5,4,3,2,1]` -> `4465125`
`f` scans from left to right by multiplying the length of outmost hook with a recursive call to itself where each element of the input list is reduced by `1` (dropping it when reaching `0`). `p` scans from top to bottom by multiplying `f` of the whole list with `p` of the tail.
[Answer]
# Python, ~~95~~ 91 bytes
This is a Python implementation of [nimi's Haskell answer](https://codegolf.stackexchange.com/a/51139/47581). Golfing suggestions welcome.
```
f=lambda z:z==[]or(z[0]+len(z)-1)*f([i-1for i in z if~-i])
p=lambda z:z==[]or f(z)*p(z[1:])
```
[Answer]
# R, 174 bytes
So... This solution is quite long and could probably be more golfed. I'll think about it !
```
v=c();d=length;m=matrix(-1,l<-d(a<-scan()),M<-max(a));for(i in 1:l)m[i,(1:a[i])]=c(a[i]:1);for(j in 1:M)m[,j]=m[,j]+c((((p=d(which(m[,j]>0)))-1)):0,rep(0,(l-p)));abs(prod(m))
```
**Ungolfed :**
```
v=c() #Empty vector
d=length #Alias
m=matrix(-1,l<-d(a<-scan()),M<-max(a)) #Builds a matrix full of `-1`
for(i in 1:l)
m[i,(1:a[i])]=c(a[i]:1) #Replaces each row of the matrix by `n` to 1, `n` being the
#corresponding input : each number is the number of non-empty
#cells at its left + itself
for(j in 1:M)
m[,j]=m[,j]+c((((p=d(which(m[,j]>0)))-1)):0,rep(0,(l-p)))
#This part calculates the number of "non-empty" (i.e. without `-1` in a column), -1,
#because the count for the cell itself is already done.
# Then, it creates a vector of those count, appending 0's at the end if necessary
#(this avoids recycling)
abs(prod(m)) #Outputs the absolute value of the product (because of the `-1`'s)
```
[Answer]
# Python 2, ~~135~~ 128 bytes
This takes a Python type list from stdin:
```
r=input()
c=[-1]*r[0]
for a in r:
for b in range(a):c[b]+=1
s=1
y=0
for a in r:
for x in range(a):s*=a-x+c[x]-y
y+=1
print s
```
This is a very canonical implementation, but I haven't come up with anything much smarter so far. I have a feeling that there will be much shorter solutions even with "real" programming languages.
We get the number of boxes in each row as input. This solution first counts the number of boxes in each column, which is stored in `c` (it's actually the count minus 1 to simplify its usage in the later calculation). Then it iterates over all boxes, and multiplies the hook lengths. The hook length itself is trivial to calculate once you have the count of boxes in each row and column.
[Answer]
# JavaScript (*ES6*) 69
A function taking an array of integers in *ascending* order.
Run the snippet to test (Firefox only)
```
F=x=>x.map(r=>{for(i=-1;++i<r;p[i]=-~p[i])t*=r-i+~~p[i]},p=[],t=1)&&t
// TEST
out=x=>O.innerHTML += x + '\n';
test=[
{y:[1], h: 1}
,{y:[2], h: 2}
,{y:[1, 1], h: 2}
,{y:[5], h: 120}
,{y:[2, 1], h: 3}
,{y:[5, 4, 3, 2, 1], h: 4465125}
,{y:[5, 3, 3, 1], h: 115200}
,{y:[10, 5], h: 798336000}
]
test.forEach(t=>{
t.y.reverse(); // put in ascending order
r=F(t.y);
out((r==t.h? 'Ok':'Fail')+' Y: ['+t.y+'] Result:'+r+' Check:'+t.h)
})
```
```
<pre id=O></pre>
```
] |
[Question]
[
Today, as I'm writing this, is March 31st. In the US, this is `3/31`. I was playing around with `331` as a number to come up with a challenge, and found that its residues (modulo small numbers) is palindromic. `331%2=1, 331%3=1, 331%4=3, 331%5=1, 331%6=1` (`11311`).
Your challenge here is, when given an integer `n > 2`, output the first `n` positive numbers that have palindromic residue when taken modulo `[2,n]`.
For example, for input `7`, the output should be `1, 42, 43, 140, 182, 420, 421`. Here's the chart explaining why that's the case:
```
mod
num | 2 3 4 5 6 7
-----------------
1 | 1 1 1 1 1 1
42 | 0 0 2 2 0 0
43 | 1 1 3 3 1 1
140 | 0 2 0 0 2 0
182 | 0 2 2 2 2 0
420 | 0 0 0 0 0 0
421 | 1 1 1 1 1 1
```
## Input
A single positive integer `n` with `n > 2` [in any convenient format](http://meta.codegolf.stackexchange.com/q/2447/42963).
## Output
The resulting array/list of the first `n` palindromic residues, as outlined above. Again, in any suitable format.
## Rules
* For `n > 10`, assume the residue list to be flattened before checking whether it's a palindrome. That is, `[1, 10, 11]` is palindromic, but `[1, 10, 1]` is not.
* Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
* If possible, please include a link to an online testing environment so other people can try out your code!
* [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) are forbidden.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so all usual golfing rules apply, and the shortest code (in bytes) wins.
### Examples
```
[input]
[output]
3
[1, 6, 7]
4
[1, 4, 5, 8]
5
[1, 50, 60, 61, 110]
6
[1, 30, 31, 60, 61, 90]
7
[1, 42, 43, 140, 182, 420, 421]
8
[1, 168, 169, 336, 337, 504, 505, 672]
9
[1, 2520, 2521, 5040, 5041, 7560, 7561, 10080, 10081]
10
[1, 280, 281, 560, 1611, 1890, 1891, 2170, 2171, 2241]
11
[1, 22682, 27720, 27721, 50402, 55440, 55441, 78122, 83160, 83161, 105842]
```
[Answer]
## Haskell, 57 bytes
```
f n=take n[x|x<-[1..],(==)=<<reverse$show.mod x=<<[2..n]]
```
Usage example: `f 4` -> `[1,4,5,8]`. [Try it online!](https://tio.run/nexus/haskell#@5@mkGdbkpidqpAXXVFTYaMbbainF6ujYWuraWtjU5RallpUnKpSnJFfrpebn6JQARSMNtLTy4uN/Z@bmJmnYKtQUJSZV6KgopCmYGjwHwA "Haskell – TIO Nexus")
The first `=<<` is in function context and translates to the lambda `\x -> reverse x == x` and the second `=<<` is in list context and equivalent to `concatMap`, i.e. map-and-flatten-one-list-level.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 12 bytes
```
µN2¹Ÿ%JÂQD½–
```
[Try it online!](https://tio.run/nexus/05ab1e#@39oq5/RoZ1Hd6h6HW4KdDm091HD5P//DQ0A "05AB1E – TIO Nexus")
**Explanation**
```
µ # until counter equals input do:
N # push current iterations number
% # modulus each in
2¹Ÿ # range [2 ... input]
J # joined to string
ÂQ # equals it's reverse
D # duplicate
½ # if true, increase counter
– # if true print iteration number
```
[Answer]
## Mathematica, 79 bytes
```
NestList[#+1//.x_/;!PalindromeQ[ToString/@Mod[x,Range@n+1]<>""]:>x+1&,1,n=#-1]&
```
[Answer]
## JavaScript (ES6), 104 bytes
```
f=(n,x=(k=--n,2))=>k?([...Array(n)].map(_=>(r=x%++i+r,x%i),i=1,r='').join``==r?k--&&x+' ':'')+f(n,x+1):1
```
### Demo
**NB**: Because of the numerous recursive calls, this will crash for *n > 8* on Firefox or *n > 10* on Chrome.
```
f=(n,x=(k=--n,2))=>k?([...Array(n)].map(_=>(r=x%++i+r,x%i),i=1,r='').join``==r?k--&&x+' ':'')+f(n,x+1):1
for(n = 2; n < 9; n++) {
console.log(n, '=>', f(n));
}
```
[Answer]
# Python 2, ~~98~~ 97 bytes
```
n=input();i=j=0
while i<n:
j+=1;l=''
for k in range(2,n+1):l+=`j%k`
if l==l[::-1]:i+=1;print j
```
[Try it Online!](https://tio.run/nexus/python2#RVFdb4MwDHzPr/BUTW3VTopDAoEuv2J7q5D6FdZQFCpgqvbrOzto2suZnO/iM3lGF@L9e1qtd8G1TorHNXQewnusBLQbh7vOLZcCmn6AG4QIwzF@@ZXaxg2uq27jDu3r7SAgNNA51@2r6g3rKrDxPoQ4Qft8olrA5zWM0Ee/HGEawvn28yIQF3vcglK5VVSKQsm5EGmklkQao7WcC5GFRUWkzTCXcyESpbFa1SJLl@WkqoVO35qMJKuFSUdDHvYlE8pa5InOiMrwv1VSp5j9NEtnJOYIyBk1J9QKa2GTAnPLUNINWc5QpOQMNDkvKFY572jSbuZvtYS8keGxhGkRaeVcaADK2ciUsmxjJW3MSlumRCULsJAJ05/U5FzAxyNM5yv0w8UPMPUw@XGCS2iaxg@enuR8HP2OXsRT886PAo/QdXDySekvvw)
[Answer]
# [MATL](https://github.com/lmendo/MATL), 19 bytes
*Thanks to @AdmBorkBork for pointing out a mistake in an earlier version of the code, now corrected*
```
`@Gq:Q\VXztP=?@]NG<
```
[Try it online!](https://tio.run/nexus/matl#@5/g4F5oFRgTFlFVEmBr7xDr527z/785AA "MATL – TIO Nexus")
### Explanation
```
` % Do...while
@ % Push iteration index, starting at 1
Gq:Q % Push [2 3 ... n], where n is the input
\ % Modulo, element-wise
V % Convert to string. Numbers are separated by spaces
Xz % Remove spaces
tP % Duplicate, flip
= % Equal? (element-wise)
? % If all results were true
@ % Push current iteration index. It is one of the sought numbers
] % End
N % Push number of elements in stack
G % Push input n
< % Less than? This is the loop condition
% End (implicit). Display (implicit)
```
[Answer]
# Scala, 90 86 82 bytes
```
(n:Int)=>Stream.from(1)filter{i=>val d=(2 to n)map(i%)mkString;d.reverse==d}take(n)
```
## Explanation
```
Stream.from(1) // From an infinite Stream starting from 1,
filter ( i => { // keep only elements matching the next condition :
val d=(2 to n)map(i%)mkString; // Generate residues and convert to String,
d.reverse==d // return true if palindrom, false otherwise
})take(n) // Finally, take the n first elements matching the condition
```
## Test cases
```
val f = (n:Int)=>... // assign function
(3 to 11).foreach { i =>
println(i + "\n" + f(i).mkString(", ") + "\n")
}
```
## Results
```
3
1, 6, 7
4
1, 4, 5, 8
5
1, 50, 60, 61, 110
6
1, 30, 31, 60, 61, 90
7
1, 42, 43, 140, 182, 420, 421
8
1, 168, 169, 336, 337, 504, 505, 672
9
1, 2520, 2521, 5040, 5041, 7560, 7561, 10080, 10081
10
1, 280, 281, 560, 1611, 1890, 1891, 2170, 2171, 2241
11
1, 22682, 27720, 27721, 50402, 55440, 55441, 78122, 83160, 83161, 105842
```
## Edits
### #1 (90 => 86)
* anonymous function
### #2 (86 => 82)
* remove useless dot characters after parenthesis or bracket (ex. : `(2 to n).map(%i)` => `(2 to n)map(%i)`
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
%ЀḊDFŒḂ
1ç#
```
### How?
```
1ç# - Main link: n
1 - initialise "i" at 1
# - increment i and yield a list of the first n truthful results of:
ç - last link (1) as a dyad
%ЀḊDFŒḂ - Link 1, test a value "i" for mod [2,n] being palindromic: i, n
Ѐ - for each, mapped over the right argument, i.e. for j = 1 to n:
% - i modulo j
Ḋ - dequeue, i.e. discard the modulo 1 result
D - convert to decimal list (vectorises)
F - flatten into one list
ŒḂ - is palindromic?
```
**[Try it online!](https://tio.run/nexus/jelly#ARsA5P//JcOQ4oKs4biKREbFkuG4ggoxw6cj////MTI)**
[Answer]
## [CJam](https://sourceforge.net/p/cjam), 28 bytes
```
0ri:N{{)_N),2>f%s_W%#}g_p}*;
```
[Try it online!](https://tio.run/nexus/cjam#@29QlGnlV12tGe@nqWNkl6ZaHB@uqlybHl9Qq2X9/7@hIQA "CJam – TIO Nexus")
### Explanation
```
0 e# Push 0, the value we'll repeatedly increment to search for valid outputs.
ri:N e# Read input, convert to integer, store in N.
{ e# Run this block N times...
{ e# Run this block until the condition is true, which will find the next
e# number with palindromic residues...
)_ e# Increment and duplicate.
N),2> e# Push [2 3 ... N].
f% e# Take the current value modulo each of these.
s e# Flatten them into a single string.
_W% e# Duplicate and reverse.
# e# Try to find the reverse in the original. A common way to compute
e# "not equal" for strings of the same length.
}g
_p e# Print a copy of the result.
}*
; e# Discard the final result to prevent printing it twice.
```
[Answer]
# PHP, 93 Bytes
```
for(;$x<$a=$argn;$s="")for($i=1,++$n;$i++<$a;)if($i==$a&strrev($s.=$n%$i)==$s)echo$n._.!++$x;
```
[Online Version 2 Loops Output as string](http://sandbox.onlinephpfunctions.com/code/fce023b1ce442f329e1ccf2721b8e50831e2d75c)
Expanded
```
for(;$x<$a=$argn;$s="")
for($i=1,++$n;$i++<$a;)
if($i==$a&strrev($s.=$n%$i)==$s)echo$n._.!++$x;
```
## PHP 130 Bytes
```
for(;count($r)<$a=$argn;$s=[])for($i=1,++$n;$i++<$a;){$s[]=$n%$i;if(count($s)==$a-1&strrev($j=join($s))==$j)$r[]=$n; }print_r($r);
```
[Online Version 2 Loops](http://sandbox.onlinephpfunctions.com/code/37e785610cbf824a03282c672a2c53474dca6cb0)
Expanded
```
for(;count($r)<$a=$argn;$s=[])
for($i=1,++$n;$i++<$a;){
$s[]=$n%$i;
if(count($s)==$a-1&strrev($j=join($s))==$j)$r[]=$n;
}
print_r($r);
```
## PHP, 139 Bytes with 1 loop
```
for($i=$n=1;count($r)<($a=$argn)&$i++<$a;){$s[]=$n%$i;if(count($s)==$a-1){if(strrev($j=join($s))==$j)$r[]=$n;$n++;$s=[];$i=1;}}print_r($r);
```
[Online Version 1 Loop](http://sandbox.onlinephpfunctions.com/code/e6de6663864590c57de859f3bc32f1fb0a28db5d)
Run with
```
echo '<string>' | php -nR '<code>'
```
Expanded
```
for($i=$n=1;count($r)<($a=$argn)&$i++<$a;){
$s[]=$n%$i;
if(count($s)==$a-1){
if(strrev($j=join($s))==$j)$r[]=$n;
$n++;
$s=[];
$i=1;
}
}
print_r($r);
```
[Answer]
## [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), 48 bytes
```
:{A=G[2,a|A=A+!q%b$]~A=_fA||h=h+1?q]q=q+1~h=a|_X
```
Beats Mathematica! Sample run:
```
Command line: 10
1
280
281
560
1611
1890
1891
2170
2171
2241
```
Explanation:
```
:{ Get 'a' from the command line, start an inf. loop
A=G Clear out whatever's in A$
[2,a| For each of the numbers we want to modulo
A=A+ Add to A$
q%b our current number MODULO te loop iterator
! $ cast to string
] NEXT
~A=_fA| If the string of remainders is a palindrome (_f ... | is Reverse())
|h=h+1 THEN h=h+1 (h starts at 0) - this counts how many hits we've had
?q also, print the number with the palindromic remainder
] END IF
q=q+1 Test the next number
~h=a|_X If we've had 'a' hits, quit.
The last IF and the infinite loop are closed implicitly.
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 26 bytes
```
L³o fR{C=Uò2@R%Xì ¥CwÃj1U
```
[Try it online!](https://tio.run/nexus/japt#@@9zaHO@QlpQtbNt6OFNRg5BqhGHmw@tUTi01Ln8cHOWYej//xYA "Japt – TIO Nexus") Takes a few seconds on *all* inputs, so be patient please.
This would be considerably shorter (and faster) if there were a built-in to get the first N numbers satisfying some condition:
```
R{C=Uò2@R%Xì ¥Cw}aU
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
1%ⱮḊŒḂɗ#
```
[Try it online!](https://tio.run/##ASEA3v9qZWxsef8Kw4fGrP8xJeKxruG4isWS4biCyZcj////MTE "Jelly – Try It Online")
## How it works
```
1%ⱮḊŒḂɗ# - Main link. Takes n on the left
1 - Set the return value to 1
# - Count up i = 1, 2, ..., and return the first n which return true:
ɗ - Combine the previous three links into a dyad
with i on the left and n on the right:
Ɱ - For each integer m in 1, 2, ..., n:
% - i % m
Ḋ - Remove i % 1
ŒḂ - Is palindromic?
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 13 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
@õ!uX ÅêS}jU1
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=QPUhdVggxepTfWpVMQ&input=Nw) or [run all test cases](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=QPUhdVggxepTfWpVMQ&input=WzMsNCw1LDYsNyw4LDksMTAsMTFdCi1tUg)
```
@õ!uX ÅêS}jU1 :Implicit input of integer U
@ :Function taking an integer X as argument
õ : Range [1,U]
!uX : Mod X by each
Å : Slice off the first
êS : Is palindrome?
} :End function
jU1 :Starting with 1, return the first U integers that return true
```
] |
[Question]
[
Create a short C program that takes an absurdly long time to compile with gcc. Entries will be scored by timing the compilation then subtracting the reference program's compile time.
Rules
* Any C language feature or gcc extension
* gcc 4.2.1
[Answer]
```
#define a "xxxxxxxxxxx"
#define b a a a a a a a
#define c b b b b b b b
#define d c c c c c c c
#define e d d d d d d d
#define f e e e e e e e
#define g f f f f f f f
#define h g g g g g g g
#define i h h h h h h h
#define j i i i i i i i
z=j;
```
[Answer]
Both [Charlie's answer](https://codegolf.stackexchange.com/a/8884/78) and [my earlier one](https://codegolf.stackexchange.com/a/8906/78) work on the principle of letting the pre-processor write a *lot* of code, but they mostly exercise the pre-processor itself, the lexer (good idea as this step has traditionally been slow) and the parser. Mine also attempts to work the optimization and code generation steps, but it is clearly not gaining a lot there.
Thinking about how a typical c compiler works, I realized that we weren't giving the symbol table related code anything to do. This entry is an attempt to remedy that. It is supposed to be reminiscent of basic object-orientation in c implementation, but doesn't do anything interesting: justuses the pre-processor expansion technique to declare and trivially (and incorrectly) initializes a bunch of objects. Object that use complicated types, on many levels of scope, shadowing each other at various removes. It ought to give the symbol table a real
work out.
```
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
// Exercise the symbol table mechanism of the compiler in an effort to
// take a unreasonable about of time compiling
#define PTR(T) T*
#define CONST(T) T const
#define FUNC(NAME,RTYPE,ARG) RTYPE NAME(ARG)
#define FPTR(NAME,RTYPE,ARG) FUNC((*NAME),RTYPE,ARG)
// Forward decalration of repeated OO method pointers
typedef void* (*cctor_ptr)(void*this, void*that, ...);
typedef void* (*dtor_ptr)(void*this);
// Assumes three var-args: sizeof(payload type), cctor, dtor
void* default_ctor(void*this, ...){
// Pull in variadac bits
va_list list;
va_start(list,this);
int size=va_arg(list,int);
cctor_ptr cctor=va_arg(list,cctor_ptr);
dtor_ptr dtor=va_arg(list,dtor_ptr);
va_end(list);
// process
if (!this) this = malloc(size);
if (this) {
memset(this,size,0);
/* various dodges to install the cctor and dtor in the write places */
}
return this;
}
// Copies the payload from that to this;
void* default_cctor(void*restrict this, void* restrict that, ...){
// Pull in variadac bits
va_list list;
va_start(list,that);
int size=va_arg(list,int);
cctor_ptr cctor=va_arg(list,cctor_ptr);
dtor_ptr dtor=va_arg(list,dtor_ptr);
va_end(list);
// process
if (!this) this = malloc(size);
if (this) {
memcpy(this,that,size);
/* various dodges to install the cctor and dtor in the write places */
}
return this;
}
// Assumes that his was allocated with malloc, does not use varargs
void* default_dtor(void*this, ...){
free(this);
return NULL;
};
#define DECLARE_STRUCT(N) struct S##N##_s
#define TYPEDEF_ACCESSOR(N,T) typedef FPTR(f##N##_ptr,CONST(PTR(T)),PTR(CONST(struct S##N##_s)))
#define TYPEDEF_STRUCT(N,T) typedef struct S##N##_s {PTR(T)p; cctor_ptr cctor; dtor_ptr dtor; f##N##_ptr f##N;} S##N
#define OO_STRUCT(N,T) DECLARE_STRUCT(N); TYPEDEF_ACCESSOR(N,T); TYPEDEF_STRUCT(N,T)
OO_STRUCT(1,char);
OO_STRUCT(2,int);
OO_STRUCT(3,double*);
OO_STRUCT(4,S3);
OO_STRUCT(5,S4);
OO_STRUCT(6,S5);
OO_STRUCT(7,S6);
OO_STRUCT(8,S7);
#define SUBSCOPE(A) { \
S1*A##1=default_ctor(NULL,sizeof(char),default_cctor,default_dtor); \
S2 A##2; default_ctor(&A##2,sizeof(int),default_cctor,default_dtor); \
S2*A##3=default_ctor(NULL,sizeof(double*),default_cctor,default_dtor); \
S8 A##5; default_ctor(&A##5,sizeof(S4),default_cctor,default_dtor); \
S6 A##6; default_ctor(&A##6,sizeof(S5),default_cctor,default_dtor); \
S8*A##8=default_ctor(NULL,sizeof(S7),default_cctor,default_dtor); \
}
#define SUBSCOPE2(A,B) { \
S2*B##5=default_ctor(NULL,sizeof(S4),default_cctor,default_dtor); \
S4 A##7; default_ctor(&A##7,sizeof(S6),default_cctor,default_dtor); \
SUBSCOPE(A) SUBSCOPE(B); \
}
#define SUBSCOPE6(A,B,C) { \
S2*A##3=default_ctor(NULL,sizeof(double*),default_cctor,default_dtor); \
S2 B##2; default_ctor(&B##2,sizeof(int),default_cctor,default_dtor); \
S4*C##4=NULL; \
SUBSCOPE2(A,C) SUBSCOPE2(B,C) SUBSCOPE2(A,B); \
}
#define SUBSCOPE24(A,B,C,D) { \
S1*D##1=default_ctor(NULL,sizeof(char),default_cctor,default_dtor); \
S2 C##2; default_ctor(&C##2,sizeof(int),default_cctor,default_dtor); \
S2*B##3=default_ctor(NULL,sizeof(double*),default_cctor,default_dtor); \
S4 A##4; default_ctor(&A##4,sizeof(S3),default_cctor,default_dtor); \
SUBSCOPE6(A,B,C) SUBSCOPE6(A,B,D) SUBSCOPE6(A,C,D) SUBSCOPE6(B,C,D); \
}
#define SUBSCOPE120(A,B,C,D,E) { \
S5*A##5=default_ctor(NULL,sizeof(S4),default_cctor,default_dtor); \
S6*A##6=default_ctor(NULL,sizeof(S5),default_cctor,default_dtor); \
S8 A##8; default_ctor(&A##8,sizeof(S7),default_cctor,default_dtor); \
SUBSCOPE24(A,B,C,D) SUBSCOPE24(A,B,C,E) SUBSCOPE24(A,B,D,E); \
SUBSCOPE24(A,C,D,E) SUBSCOPE24(B,C,D,E); \
}
#define SUBSCOPE720(A,B,C,D,E,F) { \
S5 A##5; default_ctor(&A##5,sizeof(S4),default_cctor,default_dtor); \
S6 A##6; default_ctor(&A##6,sizeof(S5),default_cctor,default_dtor); \
S8*A##8=default_ctor(NULL,sizeof(S7),default_cctor,default_dtor); \
SUBSCOPE120(A,B,C,D,E) SUBSCOPE120(A,B,C,D,F) SUBSCOPE120(A,B,C,E,F); \
SUBSCOPE120(A,B,D,E,F) SUBSCOPE120(A,C,D,E,F) SUBSCOPE120(B,C,D,E,F); \
}
int main(){
S4 s4;
SUBSCOPE720(A,B,C,D,E,F)
}
```
Compile time on my machine is in excess of 4 seconds with `-O3` and more than 1 second with no optimization.
---
Obviously the next step would be to finish the OO implementation for a BCD classes and re-do the pi calculations using it so that I get both effects running hard.
[Answer]
Here's a riff of the exponential-preprocessor-expansion theme which does something minimally interesting: computes two approximations to pi by series methods and compares with both the value in `math.h` and the usual incantation.
Ungolfed.
```
#include <math.h>
#include <stdio.h>
// Some random bits we'll need
#define MINUSONODD(n) (n%2?-1:+1)
#define TWON(n) (2*(n))
#define NPLUSONE(n) ((n)+1)
#define TWONPLUSONE(n) NPLUSONE(TWON(n))
#define FACT(n) (tgamma(NPLUSONE(n)))
// The Euler series
// 2^(2n) * (n!)^2 z^(2n+1)
// atan(z) = \sum_n=0^\infty --------------- * ---------------
// (2n+1)! (1 + z^2)^(n+1)
#define TERMEULER(n,z) (pow(2,TWON(n))* \
FACT(n)*FACT(n)* \
pow((z),TWONPLUSONE(n))/ \
FACT(TWONPLUSONE(n)) / \
pow((1+z*z),NPLUSONE(n)) )
// The naive version
// (-1)^n * z^(2n+1)
// atan(z) = \sum_n=0^\infty -----------------
// 2n + 1
#define TERMNAIVE(n,z) (MINUSONODD(n)*pow(z,TWONPLUSONE(n))/TWONPLUSONE(n))
// Define a set of bifruncations of the sum
#define N2TERMS(n,z,ALG) (TERM##ALG(TWON(n),(z)) + TERM##ALG(TWONPLUSONE(n),(z)))
#define N4TERMS(n,z,ALG) (N2TERMS(TWON(n),(z),ALG)+N2TERMS(TWONPLUSONE(n),(z),ALG))
#define N8TERMS(n,z,ALG) (N4TERMS(TWON(n),(z),ALG)+N4TERMS(TWONPLUSONE(n),(z),ALG))
#define N16TERMS(n,z,ALG) (N8TERMS(TWON(n),(z),ALG)+N8TERMS(TWONPLUSONE(n),(z),ALG))
#define N32TERMS(n,z,ALG) (N16TERMS(TWON(n),(z),ALG)+N16TERMS(TWONPLUSONE(n),(z),ALG))
// Sum the fist 32*2+16 = 80 terms of a series...
#define PARTIALSUM(z,ALG) N32TERMS(0,(z),ALG)+N32TERMS(1,(z),ALG)+N16TERMS(4,(z),ALG)
int main(void){
const double PI_TRAD = 4.0L * atan(1.0);
const double PI_NAIVE = 4.0L * PARTIALSUM(0.999999L,NAIVE);
const double PI_EULER = 4.0L * PARTIALSUM(0.999999L,EULER);
printf("pi (math.h) = %10.8f\n",M_PI);
printf("pi (trad.) = %10.8f\n",PI_TRAD);
printf("pi (NAIVE) = %10.8f\n",PI_NAIVE);
printf("pi (EULER) = %10.8f\n",PI_EULER);
}
```
Assumes that you are using `gcc` and `glibc` and may or may not work with other arrangements. It takes about 1.0-1.1 seconds of processor time (evaluated with `time (1)`) to compile on with `-03`1 on my 2.4 GHz Intel Core 2 Duo MacBook. A default compile takes about 0.4 seconds of processor time.
Alas, I can't get gcc to evaluate either `pow` or `tgamma` at compiler time, which would really help.
When you run it the output is:
```
pi (math.h) = 3.14159265
pi (trad.) = 3.14159265
pi (NAIVE) = 3.11503599
pi (EULER) = 3.14159065
```
which shows just how slowly the naive series converges.
---
1 To get as much constant folding and sub-expression elimination as possible.
] |
[Question]
[
Output a random triple \$(x,y,z)\$ of real numbers such that
* \$x+y+z=\frac{3}{2}\$
* Each of \$x,y,z\$, taken alone, is uniformly distributed from \$0\$ to \$1\$.
Please explain in your answer what distribution your code produces and why it meets these conditions. In particular, please include a demonstration that with many samples produced by running your code many times, the distribution of each variable alone is approximately uniform.
**Allowances for precision**
Since computers can't produce actual real numbers, you can approximate them by outputting any of:
* Floats
* Decimals
* Rationals
I've tried to make the rules here as friendly as possible.
Your outputs need to be accurate within \$\pm 10^{-3}\$, that is 3 decimal digits. That means you can imagine that each real-number output from your true distribution has been fudged by at most \$\pm 10^{-3}\$ in any way. It's fine if this makes \$x+y+z\$ be a bit off from \$\frac{3}{2}\$.
You may output rationals as (numerator, denominator) pairs of integers or similar. You may also choose to output just one denominator that applies to all three values, that is, output \$a,b,c\$ and \$d\$ to represent \$\frac{a}{d},\frac{b}{d},\frac{c}{d}\$. Rationals don't have to be in reduced form.
**Randomness**
You can assume any standard PRNG is in fact random. For instance, if it outputs random floats from 0 to 1, you can assume these are uniformly random reals that are independent from each other, and not worry about any endpoint issues. It's also fine if your code fails in a probability-zero event.
To decide whether a pseudo-random source such as time or memory contents is sufficiently random, consider an empirical test where your code is run many times in sequence to check if the randomness varies sufficiently between runs. You may have these runs be done within your language such as in a loop, or by repeatedly calling the code from outside like with a shell command. You may not assume any intentional time delay or other actions taken between runs.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 15 bytesSBCS
```
1|(-,.5∘-,+⍨)?0
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/w1rNHR19EwfdczQ1dF@1LtC097gfxpQ5lFvn4Z6tbqODlBGvVZdE6Kjq/nQeuNHbROBvOAgZyAZ4uEZ/D8lsSQRqCXt0IpHvZsNDYCA61HHcn1DPVNbbf1DK0DSCgqPeucqVGhXalfZAsW5NB51NQFNftTb/ahn@6OuRZqP2iaDrHrUuehRz45HPV2GBoenG4DsA2snTr0hieqN4OoB "APL (Dyalog Unicode) – Try It Online")
A full program that generates three floating-point numbers \$ X,Y,Z \$.
### The distribution
Uses the same method as [Luis Mendo's MATL answer](https://codegolf.stackexchange.com/a/197568/78410), which in turn is [from this Math.SE answer](https://math.stackexchange.com/a/2592985/91216). The Math.SE answer presents the following random variables:
$$
X = \text{uniform random value in } (0,1) \\
Y = \begin{cases} X + \frac12, \quad X < \frac12 \\
X - \frac12, \quad X \geq \frac12 \end{cases} \\
Z = \frac32 - (X + Y)
$$
I found that this is equivalent to
$$
X = \text{uniform random value in } (0,1) \\
Y = \{ X + 1/2 \}, Z = \{-2X\}
$$
which, in turn, has the same distribution with
$$
r = \text{uniform random value in } (0,1) \\
X = \{ -r \}, Y = \{ 1/2 - r \}, Z = \{ 2r \}
$$
where the notation \$ \{ x \} \$ means the [positive fractional part](https://en.wikipedia.org/wiki/Fractional_part) of \$ x \$.
### How the code works
```
1|(-,.5∘-,+⍨)?0
?0 ⍝ r←Generate a random number from (0,1)
( , , ) ⍝ Create a 3-element array from r:
- ⍝ -r
.5∘- ⍝ 0.5 - r
+⍨ ⍝ r + r (= 2r)
1| ⍝ Extract positive fractional part from each number
```
### Test script
```
⍝ Take 10000 samples of X, Y, Z's
data←f¨⍳10000
⍝ Tests that X+Y+Z = 1.5 in all cases
∧/1.5=+/¨data
⍝ Shows the distribution of X,Y,Z in 10 bins
{(⊂∘⍋⌷⊢)↓,∘≢⌸⍵}¨⌊10×↓⍉↑data
↓⍉↑data ⍝ Reform the data into X's, Y's, and Z's
⌊10× ⍝ Classify into 10 bins
{ }¨ ⍝ For each of X's, Y's, or Z's,
↓,∘≢⌸⍵ ⍝ Gather the list of (bin, count)
(⊂∘⍋⌷⊢) ⍝ Sort the bins
⍝ Example result
X: 0 1012 1 1016 2 993 3 1025 4 1002 5 969 6 1002 7 977 8 1049 9 955
Y: 0 969 1 1002 2 977 3 1049 4 955 5 1012 6 1016 7 993 8 1025 9 1002
Z: 0 1013 1 944 2 1022 3 1052 4 990 5 980 6 1039 7 979 8 959 9 1022
```
---
# Alternative method, 21 bytesSBCS
```
(3*9),3⊥¨3|(⍳3)+⊂?9/3
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/zWMtSw1dYwfdS09tMK4RuNR72ZjTe1HXU32lvrG/9OASh719mmoV6vr6DzqmKFeq64J0drVfGi98aO2iUBecJAzkAzx8Az@n5JYkgjUUp2ikKiQpJAM1r31UXcLmHd4e0rtoRVph1YA7TA0AAIujUcdy/UN9UwsLS2BhtsAeUA8w1DP1MDAUFNb/9AKkHlc6hFW6grqkSAiykpdB2hptQbQgUCVj3q7H/Vsf9S1SPNR22SQ@x51LnrUswNoJ9CiRz1dhgaHpwNlHvV2AjWBzAIA "APL (Dyalog Unicode) – Try It Online")
This one uses [the OP's formulation from the same Math.SE question](https://math.stackexchange.com/q/2592199):
1. Generate a uniform random number \$ X \$ from \$ (0, 1) \$.
2. Take its ternary digits \$ X = 0.X\_1 X\_2 X\_3 \cdots \$ and generate ternary digits of \$ Y \$ and \$ Z \$:
$$
Y\_i = (X\_i + 1) \% 3 \\
Z\_i = (X\_i + 2) \% 3
$$
3. Then the resulting numbers \$ X,Y,Z \$ are uniform in range \$ (0, 1) \$, and their sum is
$$
\frac3{3^1} + \frac3{3^2} + \frac3{3^3} + \cdots = \frac32
$$
Theoretically it requires infinite number of digits; the code approximates the scheme with just 9 digits, which makes \$ X+Y+Z=1.499923792 \$. I'm not exactly sure if it meets the OP's spec though.
### How the code works
```
(3*9),3⊥¨3|(⍳3)+⊂?9/3
?9/3 ⍝ Generate 9 ternary digits
3|(⍳3)+⊂ ⍝ Ternary digits for X,Y,Z
3⊥¨ ⍝ Convert each list of digits to numerator for the fraction
(3*9), ⍝ Prepend the denominator
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~18~~ ~~17~~ 11 bytes
```
rt.5+yE_v1\
```
The code is based on [this method](https://math.stackexchange.com/a/2592985/91216), and incorporates [Bubbler's improvement](https://codegolf.stackexchange.com/a/197571/36398), which saved 6 bytes.
[Try it online!](https://tio.run/##y00syfn/v6hEz1S70jW@zDDm/38A) Or see [the three marginal histograms](https://tio.run/##y00syflfFuFRYWhgYGCl9L@oRM9Uu9I1vsww5r9HBlA81kNRycHQQCvb1Neq0DYyN7ZMXVXPOE1BQd1IxeU/AA) for `1000` realizations, using `10` bins on the interval (0,1).
### Commented code
```
r % Push random number, r, uniformly distributed on (0,1)
t.5+ % Duplicate, add 0.5. Gives r+0.5
yE_ % Duplicate from below, multiply by 2, negate. Gives -2*r
v % Concatenate the three values into a column vector
1\ % Modulo 1. Implicit display
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~51~~ 48 bytes
```
(.5+Sqrt[3/8]*(#-Mean@#))&@RandomPoint@Sphere[]
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78H1CUmVcS/V9Dz1Q7uLCoJNpY3yJWS0NZ1zc1Mc9BWVNTzSEoMS8lPzcgH6jOIbggI7UoNTr2f@x/AA)
## Theory
According to [this post on MathOverflow](https://mathoverflow.net/questions/11015/five-front-battle/11048#11048) about a cool unsolved problem, referencing [this other post also on MathOverflow](https://mathoverflow.net/questions/6964/egalitarian-measures/6967#6967) about distributions with nice projections, the following procedure should provide a distribution satisfying the demands of this question:
1. [Pick a random point on a sphere.](https://codegolf.stackexchange.com/questions/191510/random-point-on-a-sphere)
2. Project (orthogonally) to a fixed plane. The support of the distribution is now a disc, but with a non-uniform distribution.
3. Inscribe this disc in an equilateral triangle. Take the barycentric coordinates of our projected random point within this equilateral triangle.
4. These three coordinates now sum to a constant and have a uniform distribution on their support. Rescale if necessary.
The proof that this works fundamentally comes down to [Archimedes's "Hat-Box" Theorem](http://mathworld.wolfram.com/ArchimedesHat-BoxTheorem.html), which is the assertion that a single coordinate of a random point on a sphere has a uniform distribution on its support.
In the solution above, I use the plane x+y+z=0 because it's easy to project to it by subtracting off the mean (one-third of the total x+y+z) from each coordinate. Then I simply need to shift and scale appropriately (I can even skip the barycentric coordinates, which are themselves just a shift and scale here), which a bit annoyingly involves Sqrt[3/8]. Perhaps I can save a few bytes by taking an approximate value to the tolerances of the original question.
However, I hope that this answer -- or variants of it -- might be efficient to express in some language.
## Practice
You can run a Kolmogorov-Smirnov test to see if the distribution is correct. [Try it online](https://tio.run/##DczBCoJAEADQjxFCayslgo4eukUgrZ2GOay15oC7U@PkJfr2rfcBLzgdfHBKN5caoahw4jHwg4VnG0giz62fFFrXjR7ylG/2K/sShd32gMs8W5@9i3VWFIv64uKdQ8P/pLbPwYsHTAVAhWg@ZCpTleUXzTVSzxKONKlQ91biCIiYfg) to compare the distribution of the first coordinate of this answer (which has the same distribution as the other two coordinates) with the uniform distribution. Put briefly, we want the result of this test to not be too "close to 0" ("statistically significant").
## Remarks
Fun fact: if you scale the coordinates so that their sum is 1, this can be used to solve [a nice problem from the xkcd forums](https://web.archive.org/web/20161007000207/https://forums.xkcd.com/viewtopic.php?f=3&t=43065).
>
> Two generals, who each control the same number of units, each secretly
> decide how to split their units among three battle fronts. Whoever
> sends more units to a front wins that front, and whoever wins 2 out of
> 3 fronts wins overall. Margins of victory are irrelevant. What is the
> optimal strategy , pure or mixed?
>
>
>
[Answer]
# JavaScript (ES6), 38 bytes
Also derived from [this method from math.SE](https://math.stackexchange.com/a/2592985) used by Luis.
```
_=>[x=Math.random(),(x+.5)%1,--x*-2%1]
```
[Try it online!](https://tio.run/##TY5BboMwEEX3nGIWibCDQRCpXZQ6uy6rHsCxGpdAA6J2BS4yUHp1OkgoYjH6ksf/zatUp9qsKb9tqM01nws@v/OTcPxV2VvUKH01X4Qy4oLoge4TFobuEB73iZwL0xANHOIUNDxDsmQQUBg9AOEY9AwGifuC0BSfMqNbU@dRbT7JZTe66WwD2I39mgMmx3QQQI8zTBfqTd62hRhvOdpaZZErYJzYOiAZbF3yx40MCkTYe1HZjZCOQUmBn2ChiFKKDmsdHNAffiFehMO/@07izckTMYOEwVHeMeVC2Lr5rh98rKC5/3S2PubbR5VnNupU/ZO3ZEXSqDKlJj5@oZSm8z8 "JavaScript (Node.js) – Try It Online")
### How?
* We pick a uniform random value \$x \in [0,1[\$
* We define \$Y=x+\dfrac{1}{2}\$
* We define \$Z=2-2x=-2(x-1)\$
Then we define:
$$y=\cases{
Y&\text{if $Y<1$}\\
Y-1&\text{if $Y\ge 1$}
}$$
and:
$$z=\cases{
Z&\text{if $Z<1$}\\
Z-1&\text{if $Z\ge 1$}
}$$
Which can also be written as \$y=Y-d\$ and \$z=Z-(1-d)\$ with:
$$d=\cases{
0&\text{if $x<1/2$}\\
1&\text{if $x\ge1/2$}
}$$
Leading to:
$$x+y+z=x+\left(x+\dfrac{1}{2}-d\right)+(2-2x-(1-d))=\dfrac{3}{2}$$
[Answer]
# [R](https://www.r-project.org/), ~~38~~ 27 bytes
-10 bytes thanks to Nick Kennedy's suggestion of following Bubbler's [trick](https://codegolf.stackexchange.com/a/197571/86301); -1 extra byte by switching \$X\$ to \$1-X\$.
```
c(x<-runif(1),.5+x,-2*x)%%1
```
[Try it online!](https://tio.run/##jdC7jsIwEAXQPl9xpRWSvTiRDEqzgoIfoKHhIQoTm8XCdpAfEL4@xCUFKNUUc@/RaHzfN6RblD45fSacsqqedqyc/XZ0MuG9wxJc1YUcphXR646sVwyOYU6Lc@uJhnbgf45CHjTDcch98YprqKIKkcgDGPiR4ZZzFD8wwv8r3Mq7MEnBKuEC4kVEbKEDcqr11jwhdRjOOKWo5Ls2G6XtRmrzUdr@syaMIb59bJINRFIshz9Wdcaai2quCMnmrjAP8Qx51b8A "R – Try It Online")
The footer on TIO includes a Kolmogorov-Smirnov test of uniformity for the three marginals.
Equivalent to the easier to read:
# [R](https://www.r-project.org/), 38 bytes
```
c(x<-runif(1),y<-1-2*x+(x>.5),1.5-x-y)
```
[Try it online!](https://tio.run/##K/r/P1mjwka3qDQvM03DUFOn0kbXUNdIq0Jbo8JOz1RTx1DPVLdCt1Lz/38A "R – Try It Online")
This uses the same method as other answers, rediscovered independently.
Defines \$X\sim U(0,1)\quad
Y = \begin{cases}1-2X\text{ if }X<\frac12\\2-2X\text{ if } X\geq\frac12\end{cases}\quad
Z=\frac32 - X - Y\$
This way:
* \$X\sim U(0,1)\$ by definition
* \$Y|X<\frac12\$ and \$Y|X\geq\frac12\$ are both \$U(0,1)\$, hence \$Y\sim U(0,1)\$
* \$X+Y|X<\frac12 = 1-X|X<\frac12\sim U(\frac12, 1)\$ and \$X+Y|X\geq\frac12 = 2-X|X\geq\frac12\sim U(1, \frac32)\$ hence \$X+Y\sim U(\frac12, \frac32)\$ and therefore \$Z\sim U(0,1)\$
---
## Alternative method: [R](https://www.r-project.org/), 84 bytes
This is much longer, but uses a very different method so I am also posting it (with thanks to Amic Frouvelle).
```
`?`=runif
x=?1
y=?1
if(abs(x+y-1)>.5|(y>.5)!=(x>.5)&abs(x-y)<.5)y=1-y
c(x,y,1.5-x-y)
```
[Try it online!](https://tio.run/##K/r/P8E@wbaoNC8zjavC1t6QqxJEZKZpJCYVa1RoV@oaatrpmdZoVAJJTUVbjQoQrQaW1K3UtAFyKm0NdSu5kjUqdCp1DPVMdUHi//8DAA "R – Try It Online")
Samples \$(X,Y)\$ from the uniform distribution over this shape:
[](https://i.stack.imgur.com/cuef8.png)
then lets \$Z=\frac32-X-Y\$. These histograms show that the marginals are uniform:
[](https://i.stack.imgur.com/Xg2VI.png)
[Answer]
# [C++ (clang)](http://clang.llvm.org/), ~~206~~ ... ~~163~~ 160 bytes
```
#import<random>
std::vector<double>f(){std::random_device r;std::mt19937 g(r());auto x=std::generate_canonical<double,53>(g),y=x+(x<.5)-.5;return{x,y,1.5-x-y};}
```
[Try it online!](https://tio.run/##VU9ta8IwEP7urzg6kGR9wU7K0KbuhziRmJ4l0CYS01CR/naXxOHYfciF5@XuOXG55KLnqns83uRw0cYyw1Wrh93iatvt1qGw2rBWj6ced2dC7xF@ao4tOikQTB3BwZabzfoTOmIIpTUfrYapiVSHCg23eBRcaSUF739HZtV6Rzqa3ZopJRMrKpoXVW3Qjkbdp@yWlUWVT/ltrmcfUIl@bBGY1FdrkPuQUlkYuFQ@2AJ8nbUBEkAJDaxq3xiUvqeppPCUhIrZnJf4i@oXGs2BWgLCFhx9MaHiIUKPFhgDskRoGli@u@KEXdgPX5Ak3pVACgkNGvyb/M@b@L1J@Lj96pC6fRmej0OkvlXydM2L@fED "C++ (clang) – Try It Online")
Uses the C++ library's Mersenne twister engine to generate uniform random numbers with \$53\$ bits of randomness in \$[0,1)\$.
I realise we only need to be accurate within \$3\$ decimal digits, but that's going to be at least \$10\$ bits so might as well go the whole hog with \$53\$ (the number of bits in the mantissa part of a `double`).
Also uses @Bubbler's method to calculate \$(x, y, z)\$.
Ungolfed:
```
#include <random>
#include <vector>
std::vector<double> f() {
std::random_device rand_dev;
std::mt19937 generator(rand_dev());
double x = std::generate_canonical<double, numeric_limits<double>::digits>(generator);
double y = x;
if (y < 1./2) {
y += 1./2;
} else {
y -= 1./2;
}
double z = 3./2 - x - y;
return {x, y, z};
}
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 79 bytes
```
Sqrt[1-r[]^2]{Sin@#,Cos@#}.{{1,1,-2},Sqrt@3{1,-1,0}}/4&[2Pi(r=RandomReal)[]]+.5
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78H6RgZfs/uLCoJNpQtyg6Ns4otjo4M89BWcc5v9hBuVavutpQx1BH16hWB6TIwRjI1TXUMait1TdRizYKyNQosg1KzEvJzw1KTczRjI6N1dYz/R9QlJlXEh0U@x8A "Wolfram Language (Mathematica) – Try It Online")
A bit longer but using the direct `Sqrt[1-r^2]` distribution on the 2D disc, then rotating and translating the disc into 3D.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~14~~ 17 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
₄L¨₄/Ωx¦1αsD.5+¦)
```
Port of [*@Bubbler*'s approach](https://codegolf.stackexchange.com/a/197571/52210), so make sure to upvote him!
[Try it online](https://tio.run/##yy9OTMpM/f//UVOLz6EVQFL/3MqKQ8sMz20sdtEz1T60TPO/rb/OfwA).
This approach uses random integers in the range \$(0,1)\$.
The footer of the TIOs (`=O,`) is to verify the result equals `1.5`, which will `=` (print without popping); `O` (sum); `,` (pop and print).
**Explanation:**
```
₄L # Push a list in the range [1,1000]
¨ # Remove the last value to make the range [1,1000)
₄/ # Divide each value by 1000 to make the range [0.001,1) in increments of 0.001
Ω # Pop and push a random value of this list
# (NOTE: 05AB1E doesn't have a random builtin within the range [0,1))
x # Double this value without popping
¦ # Remove the first digit (the integer portion)
1α # And take the absolute difference with 1
s # Swap to take the original random value again
D # Duplicate it
.5+ # Add 0.5 to it
¦ # And remove the first digit (the integer portion)
) # Then wrap all (three) values on the stack into a list
# (after which this list is output implicitly as result)
```
---
```
₄L₄/3ãʒO3;α_}Ω
```
[Try it online](https://tio.run/##yy9OTMpM/f8/xCdE3/jw4lOT/I2tz22Mrz238r@tv85/AA) (way too slow for TIO, so will use \$10^{-1}\$ accuracy instead of \$10^{-3}\$ by replacing the `₄`s (1000) with `T`s (10)).
This approach uses random integers in the range \$(0,1]\$.
This previous **14 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)** answer above unfortunately didn't had marginal distribution. The \$x,y\$ values had the same distribution, but the \$z\$ values were always slightly larger in terms of marginal distribution. [Here for example the distribution for the \$x,y,z\$ values with steps of \$0.1\$.](https://tio.run/##yy9OTMpM/f8/xCdE/9BK48OLT03yN7Y@tzG@9v/hHf7/AQ) These total values will be larger for the actual steps of \$0.001\$ of course, but the \$x,y\$ values will always be the same, and \$z\$ unfortunately always slightly larger.
```
₄L # Push a list in the range [1,1000]
₄/ # Divide each value by 1000 to make the range [0.001,1] in increments of 0.001
3ã # Cartesian product of 3, to create all possible triplets of these values
ʒ # Filter these triplets by:
O # Sum the three values
3;α # Take the absolute difference with 3/2
_ # And check if it's equal to 0
}Ω # After the filter: pop and push a random triplet from this filtered list
# (which is output implicitly as result)
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 25 bytes
```
p x=rand,(x+0.5)%1,-2*x%1
```
[Try it online!](https://tio.run/##KypNqvyfnJ@Saquurv6/QKHCtigxL0VHo0LbQM9UU9VQR9dIq0LV8D9QlqtCp1Knyja1LDFHAaSDiwuoXLtSu@o/AA "Ruby – Try It Online")
Based on the same method as most other answers.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes
```
ȷX÷¤._;Ḥ;N%1
```
[Try it online!](https://tio.run/##AR4A4f9qZWxsef//yLdYw7fCpC5fO@G4pDtOJTH/wqIsU/8 "Jelly – Try It Online")
A niladic link that returns a list of 3 floats, accurate to within \$\pm 10^{-3}\$, that is 3 decimal digits, and summing to 1.5. Footer demonstrates the sum.
Uses the same method developed by [Bubbler](https://codegolf.stackexchange.com/a/197571/42248).
[Answer]
# [Perl 5](https://www.perl.org/), 50 bytes
```
$x=rand;$f=$x<.5;say for$x,$x-.5+$f,3/2-2*$x+.5-$f
```
[Try it online!](https://tio.run/##BcExDoAgDAXQqzD8SaAiphNyGBJhMmogmnr6@t5d@8H6jGpepiVQSArJvZx7QsuQjTiN8pl2dYiDeGKL5tY5@jhBLLFHU/0B "Perl 5 – Try It Online")
This answer takes seriously the first word of the question: output (as a verb). Many other answers here moves the output part outside of the byte count :-)
] |
[Question]
[
Define a 1-indexed sequence as follows:
* `A083569(1) = 1`
* `A083569(n)` where `n` is an integer greater than `1`, is the smallest integer m not occurring earlier such that `m+n` is a prime number.
Your task is to take in `n` and return `A083569(n)`.
```
n A083569(n)
1 1
2 3
3 2
4 7
5 6
6 5
7 4
8 9
9 8
10 13
11 12
12 11
13 10
14 15
15 14
16 21
17 20
18 19
19 18
20 17
```
More testcases can be found [here](https://oeis.org/A083569/b083569.txt). The original sequence on OEIS can be found [here](https://oeis.org/A083569).
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest answer in bytes wins. [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply.
[Answer]
# [Haskell](https://www.haskell.org/), ~~87~~ ~~86~~ ~~83~~ ~~80~~ ~~74~~ 69 bytes
*Thanks to xnor for suggesting some changes that saved 3 bytes!*
```
f n=[m|m<-[1..],all((>0).mod(n+m))[2..n+m-1],all((/=m).f)[1..n-1]]!!0
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P00hzzY6tybXRjfaUE8vVicxJ0dDw85AUy83P0UjTztXUzPaSE8PyNA1hErq2@Zq6qVpgpTnAQVjFRUN/ucmZuZZWXn6a2hygZgKtgq5iQW@8RoFRZl5JVDFRgax/wE "Haskell – Try It Online")
I'm new to Haskell, and Haskell golfing, feedback is appreciated!
## Explanation
We define a function `f n`. We define `f n` to be the first element `!!0` of the list:
```
[m|m<-[1..],all((>0).mod(n+m))[2..n+m-1],all((/=m).f)[1..n-1]]
```
Broken down that is:
```
[m| # Numbers m
m<-[1..], # From the integers greater than 0
all # Forall x
(>0).mod(n+m)# n+m mod x is not zero
[2..n+m-1] # from the integers from 2 to n+m-1
all # Forall
((/=m).f) # when f is applied the result is not m
[1..n-1] # from the integers from 1 to n-1
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~16~~ 15 bytes
```
Rɓ²R+⁸ÆPTḟḢṭµ/Ṫ
```
This assumes **A083569(n) ≤ n²** (the sequence appears to be growing linearly).
[Try it online!](https://tio.run/##ATMAzP9qZWxsef//UsmTwrJSK@KBuMOGUFThuJ/huKLhua3CtS/huar/MjBSwrXFvMOH4oKsR/8 "Jelly – Try It Online")
### How it works
```
Rɓ²R+⁸ÆPTḟḢṭµ/Ṫ Main link. Argument: n
R Range; yield [1, ..., n].
ɓ Begin a dyadic chain with swapped arguments.
µ/ Reduce the range by that chain.
If we call the chain f, this computes f(2,1), then f(3,f(2,1)),
then f(4,f(3,f(2,1)), etc.
The left argument is an integer k, the right one an array A.
² Square; yield k².
R Range; yield [1, ..., k²].
+⁸ Add k, yielding [1+k, ..., k²+k].
ÆP Test each sum for primality.
T Truth; get all indices of 1‘s. This finds all m in [1, ..., k²]
such that m+k is prime.
ḟ Filterfalse; remove all resulting elements that appear in A.
Ḣ Head; extract the first remaining result.
ṭ Tack; append the extracted integer to A.
This computes the first n elements of the sequence.
Ṫ Tail; extract the last, n-th element.
```
[Answer]
# Pyth - ~~18~~ ~~17~~ 15 bytes
*Thanks to @isaacg for saving me two bytes!*
Back on this site, after being busy for a while, will hopefully golf this one further.
```
esmaYf&-TYP_+Th
```
[Try it online here](http://pyth.herokuapp.com/?code=esmaYf%26-TYP_%2BTh&input=10&debug=0).
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 169 bytes
```
n=>{if(n<2)return 1;var p=new int[n-1];int i=0,j,s;for(;i<n-1;)p[i]=f(++i);for(i=1;;i++){for(j=2,s=i+n;j<s&&s%j++>0;);if(j==s&!System.Array.Exists(p,e=>e==i))return i;}}
```
[Try it online!](https://tio.run/##fVBNT8MwDL3vV5hJTInSTe0QCJS60oTgAkgIDhymHaIuRa66dEqywTT1t5e04mO94INjvzy/PCd307y2uoUQeaWcg2dbv1u1GXXIsc9dOK885bCvaQ1Pigzjv1d/pC5eD87rzex@Z/KUjI8gpAwKQDC7qpIDboGtwexIBTPpnFvtd9ZAIvfKwhaN/uhml2aarGQogDCOysjJorZMUhpwybdLWmHBhCDe44SJlCQEP3ZdifPIIQkjy9RNJu68FCKLJZfhxRLRTc6@3S6sVYfZ3Sc579g20phpROI/lkg2TTu0PtyjtsB6i2HNRIYjRZjHoQhOBsyTH7qtjasrPXuz5PUjGc3Gi/j64vLqho1BBA0BYx70uqZgwYwc/aPyotX6QR/YCavpq6b9Ag "C# (.NET Core) – Try It Online")
By far the most inefficient way to calculate the results, so please refrain from calculating `f(n)` for `n>=30` with this code. The first step is to recursively calculate the values from `f(1)` to `f(n-1)` and then proceed to calculate `f(n)` by searching for the first `i` such that `n+i` is prime and `i` is not in the previous values list.
[Answer]
# x86-64 Assembly, ~~57~~ 55 bytes
I'm new to golfing, so comments/feedback are appreciated.
Note: this is optimized for machine code length, not for source length.
```
0: 89 f8 ff cf 74 32 97 89 fe 89 f1 ff c6 89 f0 99
1: f7 f1 85 d2 e0 f7 85 c9 75 ed 89 f9 ff c9 56 29
2: fe 56 57 51 89 fc e8 d3 ff ff ff 59 5f 5e 39 c6
3: e0 ef 96 5e 74 d1 c3
```
Defines a function, using the standard convention (i.e. return value in eax, first argument in edi, all registers caller-saved except ebx) that takes an unsigned 32-bit integer and returns the smallest m etc.
Source:
```
.globl a083569
// edi = original, probably don't touch
// esi = candidate prime, if it's not a repeat we return edi-this
a083569:
mov %edi, %eax
dec %edi
jz end
xchg %eax, %edi
mov %edi, %esi
primecheck:
mov %esi, %ecx
inc %esi
primeloop:
mov %esi, %eax
cdq
div %ecx
test %edx, %edx
loopnz primeloop
/* end */
// if esi isn't prime, then ecx is now one or greater.
test %ecx, %ecx
jnz primecheck
// esi is now our target prime: check if it's not already one
mov %edi, %ecx
dec %ecx
push %rsi /* we need a flag-safe way to restore this later */
sub %edi, %esi
chkdup:
push %rsi
push %rdi
push %rcx
mov %ecx, %edi
call a083569
pop %rcx
pop %rdi
pop %rsi
cmp %eax, %esi
loopne chkdup
/* end loop - chkdup */
xchg %esi, %eax
pop %rsi
je primecheck
/* end outer loop - primecheck */
end:
ret
```
[Try it online!](https://tio.run/##VVTbUtswEH22vmKHaYYEcoG2MG0oT7zyCZ1hFEm2FWzJSDJxYPj1pruy7CR@8Eir1Tm756zNvVf1ptovCiEOh@Xz082aZUsfnDZFdjGRMJF/zQXDWFHZTQX85tePu/vfLFutQEkNj2CdLrTh1RwaZzccsUBacxkg2FaUfaKnRMGN1JIHhYm6VnPQOehw6cHYABycahQPsFO4Cq0zBL8IpfYscWJhtX2HCcbn@OYdy6QScc@y7QcoI1nWibKIh/N0cHrFaxapRanEK8JpI/poyvIxS4zAuIr5lbXN@jyJ2IV8w0z9nu4E5QNR9dQYoGvmA0YItrqiIuFqFVXB9kkY7UmsJEkoFTYuOoyiLDuwRqHAUDiURrnlSCK6odLtwBCbGuUe7rcOAneFSgxriGnn0leILvfEdS7XmRBZ0/oSJs7rDNtAl4xSEm3LK14sPM8V7PgePUf3fLBOAVkHFZUdG/bt5tQHUb7KlkQdYcelPC6Jt69IjIYKXp2MYWOblNev4uW4IkRRN@Mw0D46oqAnH@ygICxSMNaahujo9BFxq07VTgi2pS4TzvGYsPAYm8SJZpTM22BrHjT1sIdCGeVQIAm5szV5D7mtKrvDbw@eQFip1oypDsENtMbrwpDkfevTITB7YEybADXXZjr7ZIAP7fVDXOY4PlP9ePsA@s/tHb6vr2fwiS3hFx7y6fiJ4@c4H7H1bNbf/mJfjGEbkJ70FyAuRq9k4Fs2cZveqyr7dkuy4Xb5/H2dYrQ/NTAbDTw/7sYAHye8B6Vf02BjZ90xhZ/zEgOX8qSMnvDlpe/4BX2Og0EZd0PK1qgMy41OD82QaYfDP0ET7g@L@v7nfw "Assembly (x64, Linux, gcc) – Try It Online")
[Answer]
## Clojure, ~~158~~ 155 bytes
```
#(loop[r[0 1]i 1](if(= i %)(last r)(recur(conj r(nth(for[j(range):when(=((set r)j)(seq(for[k(range 2(+ 1 i j)):when(=(mod(+ 1 i j)k)0)]j)))]j)0))(inc i))))
```
This might still have some fat, I'm not quite happy with `(+ 1 i j)` but this was the easiest way to handle base case `n = 1` and the rest. `((set r)j)` returns `nil` if `j` is not in the set, and `(seq ())` on an empty list returns nil as well. Calculates `n = 1000` in 48 seconds.
Update: removed `nil` from `=` check as the code works correctly also without it.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 62+8 = 70 bytes
Uses the `-rprime` flag.
```
f=->n,o=[]{o<<f[n-1,o]if n>1;Prime.find{|i|i>n&&o|[i-n]!=o}-n}
```
[Try it online!](https://tio.run/##FcrLCoJQFEbh@f8UOysp8Ehby676DM1FpNJTG@yc8EJE9uxWk/VNVt2dX8N4VP8gVT9quZeDjlViPBun2dseDjo1ij2biSaT8P74X3wtpnj30ktiXNf2qSiTjWL7UeYzPG9SlXQt2wYkFNMk91ubC@jRtQ0506DY0S8OTSkVj7R/OVXVTOYZSlMMjAAhllghwhobbMELMIMDcAheglfgCLwGb8BbBIsv "Ruby – Try It Online")
[Answer]
# Python, 194 170 110 bytes
*84 bytes saved by Leaky Nun*
*2 bytes saved by mathmandan*
```
def s(n):
a=[s(j)for j in range(1,n)];i=1
while(i in a)|any((i+n)%j<1for j in range(2,i+n)):i+=1
return i
```
Defines a function s(n) that takes a number as input and returns A083569(n).
[Try it Online](https://tio.run/##XY4xCsJAEEX7nGIaYYakGe1WcxKxWHBjZpGfsFmRgHdfmU6s33@Pv@51XnBq7Z4m2hgSOorjdeMs01Iok4FKxCOxDpDb2Ubt6D3bM7E5i/KJ2JmthxzyRf@k4@BAgvXulVRfBWTNV/hNq0pYi6Gyf5D2BQ)
[Answer]
# [Husk](https://github.com/barbuz/Husk), 16 bytes
```
!¡λḟȯṗ+→L¹`-N);1
```
[Try it online!](https://tio.run/##ASwA0/9odXNr/23igoHhuKMxMDD/IcKhzrvhuJ/Ir@G5lyvihpJMwrlgLU4pOzH//w "Husk – Try It Online")
1-indexed.
] |
[Question]
[
There are lots of different ways to explain matrix multiplication. I'll stick with a single figure since I believe most people here are familiar with it (and the figure is very descriptive). If you want more detailed information, I suggest you visit the [Wikipedia-article](https://www.google.no/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&uact=8&ved=0ahUKEwjU467auLzRAhXiK5oKHT6TCBcQFggcMAA&url=https%3A%2F%2Fen.wikipedia.org%2Fwiki%2FMatrix_multiplication&usg=AFQjCNGePV5rqwqZO0YVgw14coxNEmN6dw&sig2=4Hnrg9yz0KkcF7SGcrKSoA), or the explanation on [WolframMathWorld](http://mathworld.wolfram.com/MatrixMultiplication.html).
**Simple explanation:**
Suppose you have two matrices, **A** and **B**, where **A** is 3-by-2, and **B** is 2-by-3. If you perform matrix multiplication on these to matrices, either **AB**, or **BA** you'll get the results below:
[](https://i.stack.imgur.com/Ohocx.gif)
## Challenge:
Implement *symbolic* matrix multiplication in you language. You shall take two matrices as input, where each element in the matrices are represented by an non-whitespace ASCII-character (code points 33-126). You must output the product of these matrices.
**Rules regarding output:**
A product of two entries shall not have any symbols in between. It's `ab`, not `a*b`, `a·b`, `times(a,b)` or something similar. It's `aa`, not `a^2`.
The sum of terms should have a space (ASCII code point 32) in between. It's `a b`, not `a+b`, `plus(a,b)` or something similar.
The rationale for those two rules is: All non white space characters are allowed as symbols in the matrices, thus using them as mathematical symbols would be messy. So, what you could normally write as `a*b+c*d` will be `ab cd`.
You may choose the order of the terms. `ab cd`, `dc ab` and `cd ba` are mathematically speaking the same, so you can choose the order here too. The order need not be consistent as long as it's mathematically correct.
**Rules regarding matrix formatting:**
A matrix can be entered in whatever format you like, except a single string with no delimiters between rows (this is because the output would be completely messed up). Both matrices must be inputted on the same format. All the examples below are valid ways of entering and outputting a matrix.
```
"ab;cd" <- This will look awful, but it's still accepted.
"a,b\nc,d"
[[a,b],[c,d]]
[a, b]
[c, d]
```
I'm aware that this allows a lot of formats that will look messy, but the challenge is about multiplying matrices, not formatting the output.
**General rules:**
* You may assume valid input. Matrix multiplication will always be possible with the given dimensions.
* There will only be two matrices.
* You may assume that the matrices are non-empty
* Built-in functions are accepted (but probably a bit cumbersome due to the formatting requirements).
* You may of course use escape characters in the input if necessary (`\'` instead of `'`).
* Any [standard input and output method is OK](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods?answertab=votes#tab-top).
## Test cases:
The two input matrices are shown with an empty line in between. The output is shown after `Output:`. When there are two output matrices then it's just to show other outputs that would be accepted.
**Test case #1**
```
Inputs:
[a]
[b]
Output:
[ab]
[ba] <- Also OK
```
**Test case #2**
```
Inputs:
[a, b]
[1, 4]
[y, {]
[%, 4, 1]
[a, b, c]
Output:
[a% ba, a4 bb, a1 bc]
[1% 4a, 14 4b, 11 4c]
[y% {a, y4 {b, y1 {c]
```
**Test case #3:**
```
Inputs:
[1, 2, 3, 4]
[5, 6, 7, 8]
[9, 1, 2, 3]
[4, 5, 6, 7]
[a]
[b]
[c]
[d]
Output:
[1a 2b 3c 4d]
[5a 6b 7c 8d]
[9a 1b 2c 3d]
[4a 5b 6c 7d]
[d4 c3 b2 a1] <-- Also OK
[d8 c7 b6 a5]
[1b 9a c2 3d]
[a4 b5 d7 6c]
```
If your response to the rules about requiring `ab cd` instead of `a*b+c*d` is: [you should avoid cumbersome input/output formats](https://codegolf.meta.stackexchange.com/a/8077/31516), then I'd like note that the input and output formats are very flexible. The fact that you can't use `*` and `+` for products and sums might make it harder to use a simple built-in, but [I don't consider that negative thing.](https://codegolf.meta.stackexchange.com/a/10132/31516)
[Answer]
# [Haskell](https://www.haskell.org/), ~~62~~ ~~61~~ 59 bytes
```
e=[]:e
z=zipWith
a!b=[unwords.z(++)r<$>foldr(z(:))e b|r<-a]
```
[Try it online!](https://tio.run/##HcgxDoMgFIDh3VM8XxwgWg9gpJfo0IEwQMVCSsUAxoT07pR2@//PyPjSzpWiGReTbjLLdr/bZBrZKsaP7fRhiWMmfU/D3F1X75ZAMpko1aA@Yb5IUd7SbsBgP9ItBRghGn9CB5yjxAEVioHjo5ZGIaD9@Vrv@XdTy1YvXw "Haskell – Try It Online")
Example usage:
```
Prelude> [["a","b"],["c","e"]] ! [["f","g"],["h","i"]]
[["af bh","ag bi"],["cf eh","cg ei"]]
```
I found a way to get a `transpose` function in one byte shorter than using the import.
```
import Data.List;transpose
e=[]:e;foldr(zipWith(:))e
```
As the code then uses `zipWith` twice, two more bytes can be saved with the abbreviation `z=zipWith`.
---
**Old version with import:** (62 bytes)
```
import Data.List
a!b=[unwords.zipWith(++)r<$>transpose b|r<-a]
```
[Try it online!](https://tio.run/nexus/haskell#JYwxT8MwEEZ3fsVXqwOojcXI0FaqYGBgQGJgiDI4ybU@4drW@UKkqv89GNjee8PjS06ieE5RJQV7zDnw4JS/CU2DSDTSiFMS7NYHzJ4HDy7IQoWigiNeXfmiEPBkH/EuFKaRFv6fvjh19o2L3rlVv2@nOCcZi71y/mT195vNg9Srioslp0Lob7JrXLdcXP3ukSf9UIFF8WnGGm1rnNma3nTb1gyVyHQdVr/9VO38130lrn35AQ "Haskell – TIO Nexus")
This is quite similar to my answer to [non-symbolic matrix multiplication](https://codegolf.stackexchange.com/a/106479/56433): `a!b=[sum.zipWith(*)r<$>transpose b|r<-a]`, substituting the multiplication `(*)` with string concatenation `(++)` and `sum` with `unwords` which concatenates a list of strings with a space in between. The import is needed for the `transpose` function, so all in all the transposition of the second matrix uses up half of the bytes ...
---
**Old version without import:** (64 bytes)
```
a![]=[];a!b=(unwords.zipWith(++)[h|h:_<-b]<$>a):a![s:t|_:s:t<-b]
```
[Try it online!](https://tio.run/nexus/haskell#HYzBasMwEER/ZSxySEhseixuXCi99FjooQchgmxvIjWyJCS5hpJ/dzc5zPJmZxg7xZAK3oMvKbjmLUZnB13sL6Gu4YlGGnEOCcfNKxZjBwObERNl8gXW40PnKzmH5@YJn4ncPNKqK6k6qV501Xfb2S8hjbn5s/HbFrPd73fS3Ex7Ota94lW9a7mf23I7tXzv33XSvNwhzuWrJDTIJizYQEqhxUH0Qh2kGJjoQWemi1AK1b1h2FnWzyO7MjnWxPn6Dw "Haskell – TIO Nexus")
With the import and `transpose` function taking up so much bytes, I tried solving the task without import. So far this approach turned out being two bytes longer, but it might be more golfable. *Edit: The other approach at the top now beats the import!*
The list comprehension `[s:t|_:s:t<-b]` gets the non-empty tails of the lists in `b`, using just `[t|_:t<-b]` to get the tails would be 4 bytes shorter (even beating the import version) but append an empty row like `["","",""]` to the matrix which I suppose is not allowed.
[Answer]
## Mathematica, 36 bytes
```
Inner[#<>#2&,##,StringRiffle@*List]&
```
`Inner` is a generalisation of Mathematica's `Dot` (i.e. the usual matrix/vector product). It generalises the dot product by letting you provide two function `f` and `g`, which will be used in place of the usual multiplication and addition, respectively. We're replacing the multiplication with `#<>#2&` (which joins the the two characters into a single string) and the addition with `StringRiffle@*List`, which first wraps all the summands in a list, and then `StringRiffle` joins them together with spaces.
One could potentially use the `Dot` operator `.` and then transform the result, but the trouble is that things like `"a"*"a"` would immediately get transformed into `"a"^2` (same for sums), which would be annoying to pick apart again.
[Answer]
## Ruby, 61 bytes
```
->a,b{a.map{|x|b.transpose.map{|y|x.zip(y).map(&:join)*' '}}}
```
Sample run:
```
main(0):007> ->a,b{a.map{|x|b.transpose.map{|y|x.zip(y).map(&:join)*' '}}}[[[?a, ?b], [?1, ?4], [?y, ?{]], [[?%, ?4, ?1], [?a, ?b, ?c]]]
=> [["a% ba", "a4 bb", "a1 bc"], ["1% 4a", "14 4b", "11 4c"], ["y% {a", "y4 {b", "y1 {c"]]
```
```
->a,b{
a.map{|x| # for each row of a
b.transpose.map{|y| # and for each column of b
x.zip(y) # match up corresponding elements
.map(&:join) # join each pair together
*' ' # join the entire thing on space
}}}
```
[Answer]
## Clojure, 53 bytes
```
#(for[a %](for[b(apply map vector %2)](map str a b)))
```
Running with arguments `[["a" "b"]["c" "e"]]` and `[["f" "g"]["h" "i"]]` returns `((("af" "bh") ("ag" "bi")) (("cf" "eh") ("cg" "ei")))`. This is actually shorter than the [numeric version](https://codegolf.stackexchange.com/a/106491/59617).
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
Z;"þK€€
```
This is a dyadic link that takes **B** and **A** as arguments (in that order) and returns **AB**. Input and output are in the form of 2D arrays of strings, which are actually 3D arrays of characters. A further byte could be saved by taking 2D arrays of *characters* as input. I'm not sure if that's allowed.
[Try it online!](https://tio.run/nexus/jelly#@x9lrXR4n/ejpjVA9P/w8kNbFR7u2P6oYY5zYk6OQklGqkJOZl623qOGuQpZIEWN2ypMDi2BqvHKz8xTSM7PKc3NK1ZIqlRIyy8tUiguSExOLQbriERWV5RfDlYENC81LTU1Bazk///oaHVVdR0FdRMQYageq8OlEK2eCOIkgYhk9dhYkBqoCETaEKIBwqkEcaqBygA "Jelly – TIO Nexus")
It's a bit hard to determine what Jelly does under the hood when strings are involved, since it does a lot of splattening before printing. [This is how Jelly represents input and output internally.](https://tio.run/nexus/jelly#@x9lrXR4n/ejpjVA9F/H@vDy8ENLj056uHMGkJ/1qGHOoW2Htv3/Hx2trqquo6BuAiIM1WN1uBSi1RNBnCQQkaweGwtSAxWBSBtCNEA4lSBONVAZAA "Jelly – TIO Nexus")
### How it works
```
Z;"þK€€ Dyadic link. Left argument: B. Right argument: A
Z Zip/transpose B.
;"þ Table vectorized concatenation; for each row in B' and each row in A,
concatenate the corresponding strings.
K€€ Join the arrays that correspond to the rows of A by spaces.
```
[Answer]
# [Dyalog APL](http://dyalog.com/download-zone.htm), 10 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319)
Takes matrices of characters as left and right arguments. Returns matrix of lists of characters. (APL represents strings as lists of characters.)
```
{∊⍺' '⍵}.,
```
[TryAPL online!](http://tryapl.org/?a=%28%u2355%27A%20%20%3D%27%20%28A%u21903%202%u2374%27ab14y%7B%27%29%29%20%28%u2355%27B%20%20%3D%27%20%28B%u21902%203%u2374%27%2541abc%27%29%29%20%u22C4%20A%7B%u220A%u237A%27%20%27%u2375%7D.%2CB&run)
Normal inner product is in APL `+.×`, but the addition and multiplication can be any functions, in particular:
Addition has been replaced by
`{` an anonymous function:
`∊` the flattened
`⍺ ' ' ⍵` list consisting of the left argument, a space, and the right argument `⍵`
`}`
Multiplication has been replaced by concatenation, `,`
[Answer]
## Prolog, >256 Bytes
I am using { \_ | \_ } which is a findall/3, \_ [ \_ , \_ ] which is some arg/3, and sum(\_) which is some aggregate. They can all be used inside is/2:
```
*(X, Y, Z) :- functor(Y, matrice, _), L is len(X[1]), L =:= len(Y), !,
M is len(X), N is len(Y[1]),
Z is { { sum({ X[J,K] * Y[K,I] | between(1,L,K) })
| between(1,N,I) }
| between(1,M,J) }.
```
Together with the [extra definitions](https://gist.github.com/jburse/b79e21447eda6843daadf52942026eff) for the aforementioned predicates and the non-standard is/2 that can return more than numbers, its sure >256 bytes.
[Answer]
## JavaScript (ES6), 65 bytes
```
(a,b)=>a.map(c=>b[0].map((_,j)=>c.map((e,i)=>e+b[i][j]).join` `))
```
Takes input as two 2D arrays of characters and returns a 2D array of strings. Add 10 bytes to support input as two 1D arrays of strings.
[Answer]
# Pyth, 14 bytes
```
clQmj;sMCd*QCE
```
A program that takes input of two newline-separated two-dimensional lists of characters and prints a two dimensional list of strings.
[Test suite](http://pyth.herokuapp.com/?code=clQmj%3BsMCd%2aQCE&test_suite=1&test_suite_input=%5B%5B%27a%27%5D%5D%0A%5B%5B%27b%27%5D%5D%0A%5B%5B%27a%27%2C%27b%27%5D%2C%5B%271%27%2C%274%27%5D%2C%5B%27y%27%2C%27%7B%27%5D%5D%0A%5B%5B%27%25%27%2C%274%27%2C%271%27%5D%2C%5B%27a%27%2C%27b%27%2C%27c%27%5D%5D%0A%5B%5B%271%27%2C%272%27%2C%273%27%2C%274%27%5D%2C%5B%275%27%2C%276%27%2C%277%27%2C%278%27%5D%2C%5B%279%27%2C%271%27%2C%272%27%2C%273%27%5D%2C%5B%274%27%2C%275%27%2C%276%27%2C%277%27%5D%5D%0A%5B%5B%27a%27%5D%2C%5B%27b%27%5D%2C%5B%27c%27%5D%2C%5B%27d%27%5D%5D&debug=0&input_size=2)
**How it works**
*[Explanation coming later]*
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 17 bytes
```
{Y Zb{a._JsMy}Ma}
```
This is a function that takes two nested lists of (single-character) strings and returns a nested list of strings. [Try it online!](https://tio.run/nexus/pip#c3S0io42VDCK5VIAgmhjBRMoy1TBLDaWy8kJKK2eqKCepKCeDJVRT1FQT1VQTwNKc6VZ/a@OVIhKqk7Ui/cq9q2s9U2s/R@gEBSgoJGm4Oio4OSkyQXhODkB@Zr/AQ "Pip – TIO Nexus") (with two test cases).
### Explanation
Arguments to a `{}`-delimited function are assigned to the local variables `a` to `e`. The first argument of a lambda function is represented by `_`.
```
{ } Define a function:
Zb Zip rows of b, transposing it
Y Yank into global variable y for access in nested function
{ }Ma To the rows of a, map this function:
My To the rows of y (i.e. columns of b), map this function:
a._ Concatenate, itemwise, the current row of a and row of y
Js Join the resulting list on space
The result of the outer map operation is returned
```
] |
[Question]
[
Using the 74 characters from the [2016 time capsule string](https://codegolf.stackexchange.com/questions/105398/2016-time-capsule-string-how-versatile-is-your-language)
```
H@~*^)$.`~+1A|Q)p~`\Z!IQ~e:O.~@``#|9@)Tf\eT`=(!``|`~!y!`) Q~$x.4|m4~~&!L{%
```
write N code snippets all in the same language where:
* The 1st snippet outputs `1`.
* The 2nd snippet outputs `2`.
* The 3rd snippet outputs `3`.
* ... etc. ...
* The Nth snippet outputs `N` (the number, not the literal letter).
A "code snippet" is defined as any of these:
* A full program with no required input that outputs the number [normally](http://meta.codegolf.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods).
* A function with no required arguments that outputs/returns the number [normally](http://meta.codegolf.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods).
* A [REPL](https://en.wikipedia.org/wiki/Read%E2%80%93eval%E2%80%93print_loop) expression that evaluates to the number.
(You may mix and match these three variants in your N snippets.)
The characters you're allowed to use in the combined set of N snippets are **precisely the 74 characters of the time capsule, *plus* `floor(N/2)` extra "wildcard" bytes** that you may use anywhere.
For example, the time capsule contains three `@`'s so in the entirety of your N snippets there may only be up to three `@`'s present unless you decide to use some of your `floor(N/2)` wildcard bytes for additional `@`'s.
Thus, not counting wildcards, the combined set of characters in your N snippets must be a subset of the 74 time capsule characters. Their combined lengths cannot exceed 74.
**You may not reuse time capsule characters or wildcard bytes between snippets.**
# Notes
* The are no other limits on snippet length or how many wildcards may be used per snippet.
* You must write *all* snippets for 1 through N. It's not 0 to N-1, not k to N+k-1.
* The snippets must be individual, not one snippet that outputs the list `1, 2, 3, ..., N`.
* Outputs may be floats like `3.0` in place of `3` and you can use a base other than decimal if it is your [language's natural base](http://meta.codegolf.stackexchange.com/a/5349/26997). You must use the same base for all snippets.
* The wildcards are counted as bytes in *your language's encoding*. This will probably be [ASCII](https://en.wikipedia.org/wiki/ASCII) but e.g. if `∞` counts as one byte in your encoding then you can use it as a single wildcard byte.
* You may use wildcard bytes for multibyte characters. e.g. `∞` is [normally](https://mothereff.in/byte-counter) three bytes so you could use it in a snippet but it will cost three of your `floor(N/2)` wildcard bytes.
* [Newlines](https://en.wikipedia.org/wiki/Newline#Representations) such as `\r\n` may be considered one byte.
# Example
In Python, N = 4 is possible just using the REPL. There are `floor(4/2) = 2` wildcards.
1. `1` from the time capsule is an expression that evals to `1`.
2. `2` consists of a single wildcard, namely the `2`. Evals to `2`.
3. `3` also consists of a single wildcard. Evals to `3`. No more wildcards.
4. `4` is luckily in the time capsule and it evals to `4`.
These snippets are short and trivial. A real answer would likely be much more complex.
(Five and beyond in Python may certainly be possible but I'll leave it to the professionals.)
# Scoring
**The answer with the highest N wins;** i.e. the one that climbs the integer ladder the highest.
In case of a tie, the answer that used the fewest wildcard bytes wins.
In case there is still a tie, the answer that used the fewest cumulative characters wins.
If there is *still* a tie, the earlier answer wins.
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 23 snippets, 11 wildcards, 45 bytes
```
Q!
Q!)
Z
4
4)
6
7
8
9
A
B
C
D
E
F
G
H
I
J
QT|T+e`
O!)1
L!`e`(:)
6mf
```
[Try it online!](https://tio.run/nexus/cjam#Fcu5CsJAFEDR/n7FG0RwEBQhuHXuCxIZSWU1QZ9E0EEJwcLl10dtD5x4T@vPT/puozXZVaEUzQ@FXM5BJQ9HuVVloaXkEvTxx1aMzuCMZU9CYunSo8@AEWMmTJkxZ8GSFWtc9sqa6tka22FjvPrG8Deupy8 "CJam – TIO Nexus") | [wildcard counter](https://tio.run/nexus/jelly#DcvNCoJAFAbQ/fcUXbJwkgRhqBQC7VdDkIFZicTdjDuhZdFwX6Jn6rmmzv6E72cdQjAEQwo9NLTCBlvskKPCAUeccMYFV9RocIOx3iaO0ZHK0BI7jov/mMZQl7K6qyhlSbLKG/UQHnpqjLiiS6Vknvu8VHYcnOV9TMyehV7EamYkeqbaT1pkSe178QM "Jelly – TIO Nexus") (ignore the newlines)
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 25 snippets, 12 wildcards, 64 bytes
```
1
Q!)
Z
4
5
6
L``(*$)#
8
9
T!T
B
C
D
E
F
G
H
I
J
K
O`e`~~!!
B`:)
Q``$e`~~@~@=~+
Q!)4
Amf
```
[Try it online!](https://tio.run/nexus/cjam#U/pvyBWoqMkVxWXCZcplxuWTkKChpaKpzGXBZckVohjC5cTlzOXC5crlxuXO5cHlyeXF5c3ln5CaUFenqMjllGClyRWYkKAC4jvUOdjWaYNMM@FyzE37r@Snb2gXblNd51er/x8A "CJam – TIO Nexus")
Wildcards:
```
568BBCDEFGJK
```
I feel that I have to post quickly, before Dennis outgolfing me.
[Answer]
# JavaScript, 10 numbers, 5 wildcards
Remaining characters: `!!#$$%&())))*...:=@@@HILOQQQTTZ\^```eefmpy{|||~~~~~~~~~`
5/5 bonus characters used: `37680`
Programs:
1. `1`
2. ```
!``+!``
```
3. `3`
4. `4`
5. `4|!```
6. `6`
7. `7`
8. `8`
9. `9`
10. `0xA`
I had hoped one of the strings I could make using `\xAB` would be a number, but unfortunately none of the combinations I tried would yield any. The `^` (XOR) character would also be interesting to use, but I currently don't see any opportunities where it can be used to make a great enough number.
If you see another feasible combination, let me know in the comments.
**Edit:** Added #10 thanks to [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)
[Answer]
## Pyth, 12 snippets, 20 bytes (6 wildcards)
```
f@
```
Find the first number where root(n,n) is truthy, starting from 1.
Output: 1
```
y!H
```
Double not `{}`.
Output: 2
```
3
```
Wildcard #1.
Output: 3
```
4
```
Output: 4.
```
5
```
Wildcard #2.
Output: 5
```
6
```
Wildcard #3.
Output: 6
```
7
```
Wildcard #4.
Output: 7
```
8
```
Wildcard #5.
Output: 8
```
9
```
Output: 9
```
T
```
Preinitialized variable.
Output: 10
```
+T!Z
```
Ten plus not zero.
Output: 11
```
12
```
Wildcard #6 (`2`).
Output: 12
[Answer]
# Octave, 6 numbers, 3 wildcards
```
1: ~~I % not(not(sqrt(-1))) evaluates to true (or 1)
2: 2 % Wildcard
3: 3 % Wildcard
4: 4
5: (T=4)+~~T % Create a variable T=4, then add not(not(T)) which evaluates to 1.
6: 6 % Wildcard
```
I still have `1`, `9` and `*` left, but I don't know if it will help me much. I'll see what I can do with those :)
Not easy getting many numbers when not using an Esolang. I'm hoping I'll be able to get one or two more, but I think it'll be hard.
[Answer]
# [Pushy](https://github.com/FTcode/Pushy), 10 numbers (4 wildcards)
All of these are snippets which leave the result on the stack. You can test this in the [**online interpreter**](https://tio.run/nexus/pushy#i1EISCwuSVUozsssKEgtUUhKzckvt/rvqPFfWSFGwb@0pKC0RCEHqEQhsyQ1VyE/T6G4JDE5W@8/AA) by appending `#` to each snippet (to print the number)
```
A( \ 1: Get alphabet and check that 'Z' >= 'Y'. Results in 1 (True)
x&+ \ 2: Check stack equality (True - both are empty) then duplicate and sum.
3 \ 3: Push 3 (1 wildcard)
4 \ 4: Push 4
1 4+ \ 5: 1 + 4 in postfix, leaves 5 on the stack (1 wildcard)
`L`T% \ 6: Get character code of 'L' and modulo by T (ten) - leaves 6 on the stack
7 \ 7: Push 7 (1 wildcard)
8 \ 8: Push 8 (1 wildcard)
9 \ 9: Push 9
T \ 10: Push 10
```
This answer is not yet complete - although it seems unlikely I will get much further.
[Answer]
# 05AB1E, 12 numbers, 6 wildcards
```
1: 1 -> 1
2: )O!x -> sum([])!*2
3: 4L`\ -> 2nd_last(range(1...4))
4: 4 -> 4
5: 5 # wildcard 1 = 5 -> 5
6: 6 # wildcard 2 = 6 -> 6
7: Tf`~ -> or(last2(prime_factors(10)))
8: 8 # wildcard 3 = 8 -> 8
9: 9 -> 9
10: T -> 10
11: A`Q!T+ # wildcard 4 = T -> (y==z)!+10
12: TÌ # wildcard 5,6 = T,Ì -> 10+2
```
[Answer]
## [Hexagony](https://github.com/m-ender/hexagony), 6 numbers, 3 wildcards, 23 bytes
```
1!@
))!@
)|\@$!
4!%
4)!:
6!@
```
[Try it online!](https://tio.run/nexus/hexagony#@2@o6PD/PwA "Hexagony – TIO Nexus")
The entire sixth program is made from wildcards.
The only really interesting one is `3`. While I could do that as `4(!@`, that would leave me without a `4` to generate `5` easily, so I went with this instead:
```
) |
\ @ $
! .
```
Due to the `|`, the `)` on the first line is run twice, before the IP wraps to right-hand corner. `$` skips over the `@`, and then the `\` redirects the IP through the `)` a third time. The IP wraps to the bottom left corner, `!` prints the `3` and `@` terminates the program.
I don't think more than 6 snippets are possible, because there are only 5 printing commands (`!!!!!`) and 5 commands that can be used to terminate the program (`@@@%:`). So after the fifth snippet, we need at least two wildcards per snippet. Hence, even if I managed to get `6` without using a wildcard for it, there wouldn't be enough wildcards left to go to snippet seven.
[Answer]
# JavaScript, 8 numbers, 4 wildcards
```
1: 1
2: -~!``
3: 4+~!$
4: ~!``*~!``
5: 4|!$
6: 0xf^9
7: 7
8: 8
```
I might try again later - I'm kind of wasting characters on 2 and 6, when you get down to it.
[Answer]
# Befunge-98, 4 snippets, 18 bytes, 2 wildcards
```
!.@
!:+.@
41-.@ wildcard 1 = -
4.#A9H wildcard 2 = .
```
[**Characters left:**](https://jsfiddle.net/7v424bc4/7/) `!!!$$%&())))*=ILOQQQTTZ\^`````````eefmpxy{||||~~~~~~~~~`
I doubt more are possible, since every extra program will require a form of output, and all `.,` are already used up. If I can figure out a way to make 3 and 5 without a wildcard, then it's possible.
The last program will eventually terminate due to the stack filling up. `A` and `H` with no fingerprints loaded will reflect, and the program will keep pushing 9's.
[Answer]
# SmileBASIC, 12 snippets, 5 wildcards, 31 bytes
```
!. '. is parsed as the number 0.0; taking the logical not gives 1
!.+!. 'Previous value added to itself
@Q||Q '@Q is a label string and Q is a variable. For some reason, certain comparison/logical operations between strings and numbers return 3 rather than 1 or 0.
4 '4
#TLIme 'Constant for the text color lime green, value is 5.
6 '6 (wildcard)
7 '7 (wildcard)
8 '8 (wildcard)
9 '9
&HA 'Hexadecimal A
11 '11 (one of them is a wildcard)
4*3 '4 multiplied by 3 (3 is wildcard)
```
I could've also used a variable instead of `.` (variables start at 0), and a string variable (like `Q$`) instead of `@Q`
Characters used: `!!!#&*+...1449@AHILQQTem||`
Wildcards used: `67813`
unused characters: `!!$$%()))):=@@OQTZ\\^`````````efpxy{||~~~~~~~~~`
] |
[Question]
[
## Introduction
Don't you hate it when someone uploads an album you like to YouTube, but the description only contains a **track listing**? Like this:
```
1. Everything in Its Right Place - 4:11
2. Kid A - 4:44
3. The National Anthem - 5:50
4. How to Disappear Completely - 5:55
5. Treefingers - 3:42
6. Optimistic - 5:16
7. In Limbo - 3:31
8. Idioteque - 5:09
9. Morning Bell - 4:29
10. Motion Picture Soundtrack - 6:59
```
Now you don't know when *Morning Bell* starts unless you sum a bunch of times in your head! Usually, some good soul will come by and leave a handy **time table** in the (dreaded) comments section, which looks something like this:
```
(0:00:00) Everything in Its Right Place
(0:04:11) Kid A
(0:08:55) The National Anthem
(0:14:45) How to Disappear Completely
(0:20:40) Treefingers
(0:24:22) Optimistic
(0:29:38) In Limbo
(0:33:09) Idioteque
(0:38:18) Morning Bell
(0:42:47) Motion Picture Soundtrack
```
## Specification
* Your task is to write a program or function that takes a track listing as input and a time table as output.
+ You may choose to read input from STDIN, or an argument string, or an argument list of lines. Similarly, you may choose to print output to STDOUT, or return a string, or return a list of lines. Failing these, do whatever makes sense for your language.
* You may assume each input line has the format `(\d+)\. [A-Za-z0-9 ]{1,100} - (\d+):(\d\d)`. For the regex-impaired, this essentially means you can assume each line is well-formatted (as above) and **song titles consist only of alphanumeric ASCII characters and spaces**, and are no longer than 100 bytes long.
* A track's length is always at least `0:01` and no more than `59:59`.
* The track numbers are increasing order, starting from `1`, and counting up to no more than `99`.
* The total length of an album is no more than `9:59:59`.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code (in bytes) wins.
## Test case
Your program should correctly perform the conversion presented in the introduction (Radiohead's *Kid A*). Here is a bigger test case (Sufjan Stevens' *Illinois*1) with long strings your program should also work on:
```
1. Concerning the UFO Sighting Near Highland Illinois - 2:08
2. The Black Hawk War - 2:14
3. Come On Feel the Illinoise - 6:45
4. John Wayne Gacy Jr - 3:19
5. Jacksonville - 5:24
6. A Short Reprise for Mary Todd Who Went Insane but for Very Good Reasons - 0:47
7. Decatur or Round of Applause for Your Stepmother - 3:03
8. One Last Whoo Hoo for the Pullman - 0:06
9. Chicago - 6:04
10. Casimir Pulaski Day - 5:53
11. To the Workers of the Rock River Valley Region - 1:40
12. The Man of Metropolis Steals Our Hearts - 6:17
13. Prairie Fire That Wanders About - 2:11
14. A Conjunction of Drones Simulating the Way - 0:19
15. The Predatory Wasp of the Palisades Is Out to Get Us - 5:23
16. They Are Night Zombies They Are Neighbors They Have Come Back from the Dead Ahhhh - 5:09
17. Lets Hear That String Part Again Because I Dont Think They Heard It All the Way Out in Bushnell - 0:40
18. In This Temple as in the Hearts of Man for Whom He Saved the Earth - 0:35
19. The Seers Tower - 3:53
20. The Tallest Man the Broadest Shoulders - 7:02
21. Riffs and Variations on a Single Note - 0:46
22. Out of Egypt into the Great Laugh of Mankind and I Shake the Dirt from My Sandals as I Run - 4:21
```
The correct output is:
```
(0:00:00) Concerning the UFO Sighting Near Highland Illinois
(0:02:08) The Black Hawk War
(0:04:22) Come On Feel the Illinoise
(0:11:07) John Wayne Gacy Jr
(0:14:26) Jacksonville
(0:19:50) A Short Reprise for Mary Todd Who Went Insane but for Very Good Reasons
(0:20:37) Decatur or Round of Applause for Your Stepmother
(0:23:40) One Last Whoo Hoo for the Pullman
(0:23:46) Chicago
(0:29:50) Casimir Pulaski Day
(0:35:43) To the Workers of the Rock River Valley Region
(0:37:23) The Man of Metropolis Steals Our Hearts
(0:43:40) Prairie Fire That Wanders About
(0:45:51) A Conjunction of Drones Simulating the Way
(0:46:10) The Predatory Wasp of the Palisades Is Out to Get Us
(0:51:33) They Are Night Zombies They Are Neighbors They Have Come Back from the Dead Ahhhh
(0:56:42) Lets Hear That String Part Again Because I Dont Think They Heard It All the Way Out in Bushnell
(0:57:22) In This Temple as in the Hearts of Man for Whom He Saved the Earth
(0:57:57) The Seers Tower
(1:01:50) The Tallest Man the Broadest Shoulders
(1:08:52) Riffs and Variations on a Single Note
(1:09:38) Out of Egypt into the Great Laugh of Mankind and I Shake the Dirt from My Sandals as I Run
```
## Leaderboard
For your score to appear on the board, it should be in this format:
```
# Language, Bytes
```
```
var QUESTION_ID=58231,OVERRIDE_USER=3852;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>
```
1. Apologies to Sufjan, whose amazing track names I had to mangle a bit in order to make them fit the simple format this problem is limited to.
[Answer]
# CJam, ~~60~~ ~~57~~ 55 bytes
*Thanks to Sp3000 for saving 2 bytes.*
```
qN/{T60bZ0e["(%d:%02d:%02d) "e%\S/1>)':/60bT+:T;W<S*N}/
```
[Test it here.](http://cjam.aditsu.net/#code=qN%2F%7BT60bZ0e%5B%22(%25d%3A%2502d%3A%2502d)%20%22e%25%5CS%2F1%3E)'%3A%2F60bT%2B%3AT%3BW%3CS*N%7D%2F&input=1.%20Dash%20and%20Blast%20-%2016%3A48%0A2.%20We%20Flood%20Empty%20Lakes%20-%2011%3A44%0A3.%20A%20Song%20for%20Starlit%20Beaches%20-%2019%3A44%0A4.%20Illuminate%20My%20Heart%2C%20My%20Darling%20-%2017%3A31)
## Explanation
```
qN/{ e# Read input and split into lines.
T60b e# Push T (initially zero, we use this to keep track of the total time in
e# seconds), and convert it to base 60.
Z0e[ e# Pad it with zeroes to 3 digits to get hours, minutes, seconds.
"(%d:%02d:%02d) "e%
e# Get the (h:mm:ss) part using a format string.
\S/ e# Pull up the current line, split on spaces.
1> e# Discard the first segment, i.e. the track number.
)':/ e# Pull off the last segment, i.e. the time, and split on colons.
60b e# Interpret the two parts as base-60 digits to get the amount of seconds
e# for the track.
T+:T; e# Add this to T and discard it.
W< e# Discard the last segment of the remaining string (the hyphen).
S*N e# Join the song name back together with spaces and push a line feed.
}/
```
[Answer]
# Perl, (93 chars plus `-p`) 94 bytes
```
s!\d+\. (.+) - (\d+:(\d+))!sprintf"(%d:%02d:%02d) $1",$n/3600,$n%3600/60,$n%60,$n+=$3+60*$2!e
```
To run:
```
perl -pe 's!\d+\. (.+) - (\d+:(\d+))!sprintf"(%d:%02d:%02d) $1",$n/3600,$n%3600/60,$n%60,$n+=$3+60*$2!e' <<< '<input>'
```
[Answer]
# C++, ~~212~~ ~~209~~ ~~202~~ 189 bytes
C++ because.. why not?
```
#include<iostream>
long d,t,u;main(){std::string a,b(8,0);while(getline(std::cin>>t>>a[0],a,'-')>>t>>b[0]>>u){strftime(&b[0],9,"%T",gmtime(&d));b[0]='(';std::cout<<b+")"+a+'\n';d+=t*60+u;}}
```
Live:
~~[212](https://ideone.com/LHP0ma)~~
~~[209](https://ideone.com/I2ihgJ)~~
~~[202](https://ideone.com/f2qoF7)~~
[189](https://ideone.com/3DvV16)
[Answer]
# Python 2, ~~170~~ 160 Bytes
Been a while since I've done a golf, hopefully this isn't too bad :P
```
t=0
for i in input().split('\n'):i=i.split(' - ');print'(%d:%02d:%02d)'%(t/3600,t%3600/60,t%60),i[0].split('. ')[1];k=i[-1].split(':');t+=int(k[0])*60+int(k[1])
```
The input should be surrounded by quotes, and split by newlines, like so:
```
"1. Concerning the UFO Sighting Near Highland Illinois - 2:08\n2. The Black Hawk War - 2:14\n3. Come On Feel the Illinoise - 6:45\n4. John Wayne Gacy Jr - 3:19\n5. Jacksonville - 5:24\n6. A Short Reprise for Mary Todd Who Went Insane but for Very Good Reasons - 0:47\n7. Decatur or Round of Applause for Your Stepmother - 3:03\n8. One Last Whoo Hoo for the Pullman - 0:06\n9. Chicago - 6:04\n10. Casimir Pulaski Day - 5:53\n11. To the Workers of the Rock River Valley Region - 1:40\n12. The Man of Metropolis Steals Our Hearts - 6:17\n13. Prairie Fire That Wanders About - 2:11\n14. A Conjunction of Drones Simulating the Way - 0:19\n15. The Predatory Wasp of the Palisades Is Out to Get Us - 5:23\n16. They Are Night Zombies They Are Neighbors They Have Come Back from the Dead Ahhhh - 5:09\n17. Lets Hear That String Part Again Because I Dont Think They Heard It All the Way Out in Bushnell - 0:40\n18. In This Temple as in the Hearts of Man for Whom He Saved the Earth - 0:35\n19. The Seers Tower - 3:53\n20. The Tallest Man the Broadest Shoulders - 7:02\n21. Riffs and Variations on a Single Note - 0:46\n22. Out of Egypt into the Great Laugh of Mankind and I Shake the Dirt from My Sandals as I Run - 4:21"
```
[Answer]
# Gema, 151 characters
```
\B=@set{t;}
<D>. * - <D>\:<D>=(@div{$t;3600}:@fill-right{00;@div{@mod{$t;3600};60}}:@fill-right{00;@mod{$t;60}}) *@set{t;@add{@add{$t;$4};@mul{$3;60}}}
```
Sample run:
```
bash-4.3$ gema '\B=@set{t;};<D>. * - <D>\:<D>=(@div{$t;3600}:@fill-right{00;@div{@mod{$t;3600};60}}:@fill-right{00;@mod{$t;60}}) *@set{t;@add{@add{$t;$4};@mul{$3;60}}}' tracklist.txt
(0:00:00) Concerning the UFO Sighting Near Highland Illinois
(0:02:08) The Black Hawk War
(0:04:22) Come On Feel the Illinoise
(0:11:07) John Wayne Gacy Jr
(0:14:26) Jacksonville
(0:19:50) A Short Reprise for Mary Todd Who Went Insane but for Very Good Reasons
(0:20:37) Decatur or Round of Applause for Your Stepmother
(0:23:40) One Last Whoo Hoo for the Pullman
(0:23:46) Chicago
(0:29:50) Casimir Pulaski Day
```
[Answer]
# Python 2, ~~207~~ 206 bytes
```
h=m=s=0
for i in raw_input().splitlines():
print("(%d:%.2d:%.2d) "%(h,m,s),i.split('-')[0].split('. ')[1])
t=i.split('-')[1].split(':')
m+=int(t[0]);s+=int(t[1]);r=s//60;s-=r*60;m+=r;r=m//60;m-=r*60;h+=r
```
## Usage
```
$ python test.py
'1. Concerning the UFO Sighting Near Highland Illinois - 2:08\n2. The Black Hawk War - 2:14\n3. Come On Feel the Illinoise - 6:45'
(0:00:00) Concerning the UFO Sighting Near Highland Illinois
(0:02:08) The Black Hawk War
(0:04:22) Come On Feel the Illinoise
```
[Answer]
# awk, ~~119~~ 101 bytes
```
{split($NF,t,":");$1=$(--NF)="";--NF;print"("substr(strftime("%H:%M:%S",s,1),2)")"$0;s+=t[1]*60+t[2]}
```
~~This is *way* longer than I wanted it to be. The problem is that `%H` doesn't format the hours like requested, so I needed to calculate the hours myself.~~
Ack, I'm stupid. The results of `strftime` were wrong because I needed to tell it to use UTC time. That cut 18 bytes off!
## 119-byte version
```
{split($NF,t,":");$1=$(--NF)="";--NF;print"("(h||0)":"strftime("%M:%S",s)")"$0;s=(r=s+t[1]*60+t[2])%3600;h=int(r/3600)}
```
[Answer]
# [Python 3 (3.8>=)](https://www.python.org), 115 bytes
```
a=0
while 1:_,*s,_,t=input().split();print(f"({a//3600}:%02d:%02d)"%(a//60%60,a%60),*s);a+=int(t[0])*60+int(t[2:4])
```
Ungolfed version:
```
a = 0
while True:
_,*s,_,t = input().split() # Skip firt element and the second to last
print(f"({a//3600}:%02d:%02d)"%(a//60%60,a%60),*s) # Print time + what is between the number and the -
a+=int(t[0])*60+int(t[2:4]) # Increment time
```
Exit with error.
[Attempt This Online!](https://ato.pxeger.com/run?1=RVTBbttGEL30xK8YBDBgJbJCUhRtM_BBrmNLgWULkmKhLYJgLa7ErahdYrm0IQT9kl58aYF-R_-hQPs1fbOUWwEiwdmZN_PmPfLX36u9K4x-efmtceuTs79rcREGz4UqJUXZ1-7buvu16y6Urhp33OnVValw_1BZpd3x-s3xN_H-fT8Nw1-yozDO_aXz5ugY0TQ8SsOuwKUDlM4H8e6Ca9xP4ZfO2zR81z7EWfKl07Y-TPDyz3d_RT363uiVtFrpDblC0ufre5qrTeE4cCeFpRGeSqFzGpel0kbVdEJxFp4FcY8WqLgsxWpLI_G8pSXS-TBKgj4j7yTda7qWsvTYrwASSWmWDIKkR59MoVG315JuxGpPnxihn0XnwQCHQK6NflJlyTWDLE6CtEdDmhfGOppJrAdoa2NpIuyeFibPaVkYWkrtaKxrAdjHxvmMB4mMG2Ny1AmgMo8wS06D0x5dyZVwjSWkzUwDrmZNw6oqRXOA_8HgdO5ktTNg0s4Y9oOzHghKuhW1476GRvhzPtOdNmW5E9q3CdPgHBsp1EpsjKcfJkEUIiRqtVOWk0W9VXQl9p7poB9EUGdhPNTS2K20NY_FjzODjc_UEwZ5ENjNHpQ2ynCrKEvCIDpIM0F3lEyks6YyJaQDBVHWdA82I4jraj9LdBpEEGxqhbJK0rWyEvUCnKA79x0-GmzRSxsFUcISwDc_N3rluC16XFmjJfDVDkTcq5uWnk3IckaDdqaplblwBlosRV29MpoKTCdyIIx5OkfO0I109Lludcc2Ul-_pyGGu2OH0o9m96hQ8n9YIv5o7CE0Ek-ydeElW3Rtzc43u5Iip2GBnwcPMRw8cCuxDV5KS33uLLOYYkk03Ail6RImYT-M6crAXotC6e2hEarwfiCxLP_jzSy4qqkLLRH3boM28MxYczWmlLsKzhY1J3LdQRPWDNKxkeCqHcI0B5fc53xESuHR-oMgOm-3Opcs08I8H7wJ-8Rhe7Rgh8CfjMj1l9bwoh2_RE3p5T2h0yyMgxiGm6n1uiZ-3R-EVYLlxTyaBKTVGwx7Z5xsuaRBDJ8xTcz7cbOvmK9rDXtjJXZ4K5pNcWCzVcD0nxE0FlvZKqGwXa_LZA-KOmdzYh1jmjXs5iSLoyD21vzzj7LJZZfuq158lmGMXpT6_dIahqMJvizW-z_st9-3fwE)
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~112~~ 109 bytes
*-3 bytes thanks to Steffan*
```
a=0
loop{_,*s,_,t=gets.split;puts "(%d:%02d:%02d) "%[a/3600,a/60%60,a%60]+s*' ';a+=t[0].to_i*60+t[2..4].to_i}
```
Exit with error
[Attempt This Online!](https://ato.pxeger.com/run?1=RVTLbuNGELzkxK9oLGBsYstcknrY1sIHOVpbWli2IGktJMbCGIkjcSJyhhgOvRCC_ZK9-JAc8h35hwDJ16R6KCcCJIE93dVdXTX89putV_uXl99rtzk9_7sQl1GQG1P--tQ6rlpPLXe5la4KqzJX7n1Zu4refH-U9o-ipPn5gd4cPYp37V4UtcS7XnTUwz9-Pp9Ux2_p7Xtxcukeo8-hM0_quBeduMckDDvN89em6aH3yz_f_RWH9KPRa2m10ltymaRP1_c0V9vMceBOCksjPOVCpzTOc6WNquiUkn50HiQhLVBxlYv1jkbiy46WSOfDuBO0GbmQdK_pWsrcY78CSCT1-p1u0Anpo8k06vZa0o1Y7-kjI7T78UXQxSGQK6OfVZ5zTbefdIJeSAOaZ8Y6msnSMtrGWJoIu6eFSVNaZoaWUjsa60oAdlU7n_EgkXFjTIo6AVTmEfU7Z8FZSEO5Fq62hLSZqcHVbGhQlrmoD_A_GZzOnSwLAybNjFE7OA9BUNKtqBz3NTTCl_OZ7rTO80Jo3ybqBRfYSKbWYms8_agTxBFColKFspwsqp2iodh7pt12EEOdhfFQS2N30lY8Fj_ODDY-U88Y5EFgN3tQ2irDreJ-JwrigzQTdEfJRDprSpNDOlAQeUX3YDOCuK7ys8RnQQzBplYoqyRdKytRL8AJunPfwcpgi17aOIg7LAF880ut147bosfQGi2BrwoQca9uWno2EcsZd5uZplamwhlosRRV-cpoKjCdSIEw5ukcOUM30tGnqtEd2-j5-j0NMNwdO5R-NsVKoeT_sER8ZewhNBLPsnHhFVt0Y03hmw2lSGmQ4ePBIwwHD9zi3vmlNNTnzjKLKZZEg61Qmq5gEvbDmIYG9lpkSu8OjVCF-4HEPP-PN7PgqrrKtETcuw3awDNjzdWYUhYlnC0qTuS6gyasGaRjI8FVBcI0B5fU53xASubR2t0gvmi2Opcs08J8OXgT9kmi5mjBDoE_GZHrr6zhRTu-RHXu5T2ls36UBAkMN1ObTUV83R-EVYLlxTyaBKTVWwx7Z5xsuPSCBD5jmpj3w3ZfMl_XGPbGSuzwVtTb7MBmp4DpXyNoLHayUUJhu16XyR4UdcrmxDrGNKvZzZ1-EgeJt-aff-R1Klt0X4bJeR9jhHHP75c2MBxN8Gax3v9Ru3m__Qs)
] |
[Question]
[
[Gravity Guy](http://www.miniclip.com/games/gravity-guy/en/) is a game where the only user input is a single key that flips the direction of gravity. Given an ASCII art level, determine if it is possible for Gravity Guy to reach the end.
---
## Rules
* The initial direction of gravity is **down**.
* The first column of the input will always contain only *one* `#`, which Gravity Guy **starts on** top of.
* Each iteration, he **moves** to the character directly on his **right**.
* If his **path is blocked** and he moves into a `#`, the player **loses**.
* After moving, the player can **optionally switch gravity** from down to up, or up to down.
* Gravity Guy then **falls on to the next `#`** (in the current direction of gravity).
* If there is no `#` to fall on to and he **falls off the grid**, the player **loses**.
* If Gravity Guy **moves off the right side** of the input grid, the player **wins**.
## Example
If this was the input grid:
```
###
# # #
###
```
Gravity Guy would start at the `x` and the be at these positions after each iteration. `^` = switch gravity to up and `v` = switch gravity to down.
```
v ^ v
-------------------------------------------------------------
### | ### | ### | ### | ### | ###
x | | x | x | x |
# # | #x # | # # | # # | # # | # # x
### # | ### # | ### # | ### # | ### # | ### #
```
As you can see, by switching gravity at these times Gravity Guy reaches the end, so this input would return a truthy value.
## Specifications
* Input grid can be in any appropriate "grid" format (multiline string padded with spaces, array of line strings, array of array of characters, etc).
* If it is **possible** for the player to win the level, output a `truthy` value. If not, output a `falsey` value.
* The width and height of the grid will be `50` characters at most.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), may the shortest code in bytes win!
## Test Cases
(each case separated by `----------`, any blank lines should also be padded with spaces)
### True
```
######### ######## ###### ######
# # # # # # #
### # # # # # # # # #
# ## # # ## # # # # # ##
# # # # # # # # # #######
# # # # # ### # #
# ## # ## # # # #
# # # # # #
# #################################### #
# #
#############################################
----------
###
----------
#####
####
----------
#####
# # #
# # #
#####
----------
############
###### ######
############
----------
### ###
# #
#### # ####
# #
# #
#
----------
######
#
##
#######
### #
# #
#####
----------
#####
# #
## #
#######
###
#
######
----------
###
# # #
###
----------
### ###
### ##
# #
#####
----------
#
# #
#
# # #
#
#
#
#
----------
##### ####
# # #
# # # ## #
# #
##### #### #
#
#########
----------
###########################
# # # # # # #
# # # # # # # # # #
# # # ######### ###########
# # # # # # # #
# # # ## ##### ### #
## # # # ## ###
# ##### #### ########### #
# # # # # ## #
# # ##### ### # # # # # #
# # # # ##
###########################
```
### False
```
###
#
####
----------
### ###
----------
#
### ###
#### ###
#
----------
### ###
# # #
#### # # ####
# #
# #
# #
#
----------
#######
# #
## #####
### ######
# #
#######
----------
###########################
# # # # # # # #
# # # # # # # # # #
# # # ######### ###########
# # # # # # # #
# # # ## ##### ### #
## # # # ## ###
# ##### #### ########### #
# # # # # ## #
# # ##### ### # # # # # #
# # # # ##
###########################
```
[Answer]
# [Snails](https://github.com/feresum/PMA), 15 bytes
[Try it online?](http://snails.tryitonline.net/#code=XgpcIG5cICw9XCNyfSt-&input=ICMjIyMjIyMjIyAgICMjIyMjIyMjICAgICAgIyMjIyMjICAgICAjIyMjIyMgICAgCiAgICAgICAgICAjICAjICAgICAgICMgICAgIyAgICAgICMgICAjICAgICAgIyAgIAojIyMgICAgIyAgICMgIyAgICAjICAgIyAgIyAgICAgICAjICAjICAgICAgICAjICAKICAjICAgICMjICAjICMgICAgIyMgICMgIyAgICAgIyAjICAjICAgICAgIyMgICAgCiAgIyAgICAjICAgIyAjICAgICMgICAjICMgICAgIyAgICAgIyAgICAgIyMjIyMjIwogICMgICAgICAgIyAgIyAgICAgICAjICAjICAgICAjIyMgICMgICAgICAgICAgIyAKICAjICAgICMjICAgICMgICAgIyMgICAgICMgICAgICAgIyAgIyAgICAgICAgICMgCiAgIyAgICAjICAgICAgICAgICMgICAgICAgICAgICAgICMgICAgICAgICMgICAjIAogICMgICAgIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjICAgIyAKICAjICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICMgCiAgIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIA)
```
^
\ n\ ,=\#r}+~
```
0. `^` is an option that requires the pattern to start at the top left.
1. `\ `: match space
2. `n`: Turn 90 degrees in either direction
3. `\ ,`: match space zero or more times
4. `=\#` check that there is a `#` in front of us
5. `r`: set the direction to right
6. `}+`: do all of the preceding one or more times
7. `~` match a cell which is out of the grid bounds
[Answer]
# Perl, ~~93~~ ~~89~~ ~~81~~ ~~77~~ ~~76~~ ~~75~~ 74 bytes
Includes +2 for `-0p`
Run with the input pattern (with all lines space padded to the same length) on STDIN:
```
gravity.pl < gravity.txt
```
`gravity.pl`:
```
#!/usr/bin/perl -0p
/
/;$n=".{@-}";s/#$n\K( $n)*\b |(^|w)([w ]$n)*\K $n#/w|$&/es&&redo;$_=m;w
```
This file based version needs the final newline, so that is really 75 bytes. But the commandline based version doesn't need that extra newline so this counts as 74 bytes:
```
perl -0pe '/
/;$n=".{@-}";s/#$n\K( $n)*\b |(^|w)([w ]$n)*\K $n#/w|$&/es&&redo;$_=m;w' < gravity.txt
```
## Explanation:
This will construct a string with a `w` in each positions gravity guy can reach.
So for the second to last truthy example it will construct:
```
#########
##### ####
#wwwww#wwww#
#w # #w ##ww#
wwwww wwwwwww#ww#
##### #### w#ww
wwwwwwwwww#
#########
```
So gravity guy can make it if and only if there is a `w` in the last column.
The string will be constructed by replacing one reachable space by `w` in each round.
Each replacement will be of the form
```
s/prefix \K space postfix/ w | $& /e
```
which will demand that the space is preceded by prefix and followed by postfix but replace only the space by `w` without needing lots of advanced grouping.
Assume `$n` contains a regex that will progress just enough that the left and right sides are exactly below each other. Then the relevant regexes are:
```
/^( $n)*\K $n#/ From the first position drop down as long as you
encounter spaces until you encounter a #.
This puts gravity guy on his starting platform
/#$n\K( $n)*\b / A space immediately below a # and if you (optionally)
go down further from there (as as the descent is
over spaces) you get to a space that follows a word
boundary. The only way to get a word boundary is if
there is a w in front of that space. This selects the
position gravity guy ends up on if starting from that
w and gravity is up
/w([w ]$n)*\K $n#/ A w followed by a space (or w) and if you go down from
there as long as it is over spaces (or w) you finally
end up on a space directly above a #. This handles the
gravity down case. The test uses "space or w" instead
of just space to handle this case:
#
ww
#x
#
Position x is currently a space and must be replaced by a
w but the gravity up regex has already put a w directly
after the w gravity guy takes off from. So for gravity
down we must handle w as if it is still a space. This
is not needed for gravity up because regex always matches
starting at the earliest possible character, so
gravity up matches before gravity down
```
With that out of the way the program is easy:
```
#!/usr/bin/perl -0p Slurp all of STDIN into $_, at the end print $_
/\n/ Match the first newline (needed to measure the row
length)
$n=".{@-}" $n effectively becomes rowlength-1 times ".". This
will be the regex that goes one step down a column
s/#$n\K( $n)*\b |(^|w)([w ]$n)*\K $n#/w|$&/es
This is the 3 regexes shown above combined. The s
modifier is needed so the . in $n also matches newline
&&redo Keep looping as long as w's keep getting added
$_=m;w\n; Check if the last column contains a w: He made it!
The \n; at the end is not written. These 2 bytes sneakily
come from the -p option for the ; and the -e option
for the \n
```
[Answer]
## JavaScript (ES6), 174 bytes
```
a=>[...a[0]].map((_,i)=>[...t].map(x=>s[x]<'#'&&g(s.indexOf('#',x),-1)&&g(s.lastIndexOf('#',x),1),s=a.map(s=>s[i]),t=new Set),t=new Set([0]),g=(i,d)=>i<0||t.add(i+d))&&t.size
```
Takes a horizontal array of strings and returns the number of exit points. Transposing the array costs me 29 bytes. Ungolfed:
```
function gravity(array) {
var set = new Set;
set.add(0); // starting point
for (var i = 0; i < array[0].length; i++) {
var s = array.map(s => s[i]); // transpose array
var old = set;
set = new Set;
for (var x of old) {
if (s[x] == '#') continue; // hit wall
var j = s.indexOf('#', x); // try downward gravity
if (j >= 0) set.add(j - 1);
j = s.lastIndexOf('#', x); // try upward gravity
if (j >= 0) set.add(j + 1);
}
}
return set.size;
}
```
[Answer]
# [Pip](http://github.com/dloscutoff/pip), ~~85~~ ~~68~~ ~~62~~ 59 + 1 = 60 bytes
Uses the `-r` flag to read all lines of stdin.
```
FcZg{YlFxiIc@xQsyPB(Jc@<x@?`# *$`)+1PB(c@>x@?'#)+x-1i:UQy}i
```
[Try it online!](http://pip.tryitonline.net/#code=RmNaZ3tZbEZ4aUljQHhRc3lQQihKY0A8eEA_YCMgKiRgKSsxUEIoY0A-eEA_JyMpK3gtMWk6VVF5fWk&input=ICAgICMjIyMjICAgCiAgICMgICAgIyAgIAogIyMgICAgICMgICAKICAgICAjIyMjIyMjCiMjIyAgICAgICAgIAogICAjICAgICAgICAKICAgICMjIyMjIyAg&args=LXI)
**Brief explanation**
The strategy is essentially a breadth-first search. We transpose the input and loop over the lines (columns), keeping a list of the y-positions the player could reach in that column. The output after the last column is a non-empty list if the player can win, or an empty list (which prints as just a trailing newline) if the player loses.
**Full explanation**
Built-in variables used in this program: `i == 0`, `l == []`, `s == " "`.
The `-r` flag puts a list of the lines of input into `g`. `FcZg{...}` zips `g` and loops over each column `c`. (Unary `Z`, when applied to a list of iterables, acts like Python `zip(*g)`, neatly transposing a 2D array.) Note that `c` will be a list, not a string.
Inside the column loop, we reset `y` to the empty list by `Y`anking `l`. `Fxi` loops over `i`. In later iterations, `i` will be a list of the y-coordinates the player was able to reach in the previous column. The first time through, we want to start with just `0` (upper left corner). The variable is preinitialized to a Scalar `0`, not a List `[0]`, but Pip iterates over it just fine either way.
For each of the valid positions in the last column, `Ic@xQs` checks whether there is a space in that position in the current column. If not, the player just ran into a wall and we go on to try the next possibility. If so, then we want to find the positions the player will fall to in this column for each direction of gravity, and add them to the list `y` using the `P`ush`B`ack operator.
Gravity going up (left, in the transposed version):
```
(Jc@<x@?`# *$`)+1
c@<x Slice everything left of x in the column
J Join into a string so we can do a regex search on it
@?`# *$` Find index of the last # in this string
( )+1 The player's index is the space below/to the right of this #
```
Gravity going down (right, in the transposed version):
```
(c@>x@?'#)+x-1
c@>x Slice everything right of x in the column
@?'# Find index of the first # in this list (no need to join into string)
( )+x Translate to index number in entire column
-1 The player's index is the space above/to the left of this #
```
If the player falls off the grid in a particular direction, the respective `@?` operation will not find a `#` and will give nil. This is not a valid index and will generate some warnings in the next iteration--which, however, are not visible without the `-w` flag. For our purposes, these cases are essentially eliminated from consideration.
After the inner loop, `i:UQy` takes the list `y` of positions we've built, eliminates duplicates, and assigns it to `i`. (Eliminating duplicates is necessary because otherwise the list balloons exponentially.) We then go to the next column. When we have looped through all columns, if there was a valid path through, `i` will be a nonempty list of positions (truthy); if not, it will be an empty list (falsey).
] |
[Question]
[
There are many formalisms, so while you may find other sources useful I hope to specify this clearly enough that they're not necessary.
A RM consists of a finite state machine and a finite number of named registers, each of which holds a non-negative integer. For ease of textual input this task requires that the states also be named.
There are three types of state: increment and decrement, which both reference a specific register; and terminate. An increment state increments its register and passes control to its one successor. A decrement state has two successors: if its register is non-zero then it decrements it and passes control to the first successor; otherwise (i.e. register is zero) it simply passes control to the second successor.
For "niceness" as a programming language, the terminate states take a hard-coded string to print (so you can indicate exceptional termination).
Input is from stdin. The input format consists of one line per state, followed by the initial register contents. The first line is the initial state. BNF for the state lines is:
```
line ::= inc_line
| dec_line
inc_line ::= label ' : ' reg_name ' + ' state_name
dec_line ::= label ' : ' reg_name ' - ' state_name ' ' state_name
state_name ::= label
| '"' message '"'
label ::= identifier
reg_name ::= identifier
```
There is some flexibility in the definition of identifier and message. Your program **must** accept a non-empty alphanumeric string as an identifier, but it **may** accept more general strings if you prefer (e.g. if your language supports identifiers with underscores and that's easier for you to work with). Similarly, for message you **must** accept a non-empty string of alphanumerics and spaces, but you **may** accept more complex strings which allow escaped newlines and double-quote characters if you want.
The final line of input, which gives the initial register values, is a space-separated list of identifier=int assignments, which must be non-empty. It is not required that it initialise all registers named in the program: any which aren't initialised are assumed to be 0.
Your program should read the input and simulate the RM. When it reaches a terminate state it should emit the message, a newline, and then the values of all the registers (in any convenient, human-readable, format, and any order).
Note: formally the registers should hold unbounded integers. However, you may if you wish assume that no register's value will ever exceed 2^30.
### Some simple examples
a+=b, a=0
```
s0 : a - s1 "Ok"
s1 : b + s0
a=3 b=4
```
Expected results:
```
Ok
a=0 b=7
```
b+=a, t=0
```
init : t - init d0
d0 : a - d1 a0
d1 : b + d2
d2 : t + d0
a0 : t - a1 "Ok"
a1 : a + a0
a=3 b=4
```
Expected results:
```
Ok
a=3 b=7 t=0
```
Test cases for trickier-to-parse machines
```
s0 : t - s0 s1
s1 : t + "t is 1"
t=17
```
Expected results:
```
t is 1
t=1
```
and
```
s0 : t - "t is nonzero" "t is zero"
t=1
```
Expected results:
```
t is nonzero
t=0
```
### A more complicated example
Taken from the DailyWTF's Josephus problem code challenge. Input is n (number of soldiers) and k (advance) and output in r is the (zero-indexed) position of the person who survives.
```
init0 : k - init1 init3
init1 : r + init2
init2 : t + init0
init3 : t - init4 init5
init4 : k + init3
init5 : r - init6 "ERROR k is 0"
init6 : i + init7
init7 : n - loop0 "ERROR n is 0"
loop0 : n - loop1 "Ok"
loop1 : i + loop2
loop2 : k - loop3 loop5
loop3 : r + loop4
loop4 : t + loop2
loop5 : t - loop6 loop7
loop6 : k + loop5
loop7 : i - loop8 loopa
loop8 : r - loop9 loopc
loop9 : t + loop7
loopa : t - loopb loop7
loopb : i + loopa
loopc : t - loopd loopf
loopd : i + loope
loope : r + loopc
loopf : i + loop0
n=40 k=3
```
Expected results:
```
Ok
i=40 k=3 n=0 r=27 t=0
```
That program as a picture, for those who think visually and would find it helpful to grasp the syntax:

If you enjoyed this golf, have a look at the [sequel](https://codegolf.stackexchange.com/questions/3897/simulate-a-minsky-register-machine-ii).
[Answer]
## Perl, 166
```
@p=<>;/=/,$_{$`}=$' for split$",pop@p;$o='\w+';(map{($r
,$o,$,,$b)=$'=~/".*?"|\S+/g if/^$o :/}@p),$_=$o=($_{$r}
+=','cmp$o)<0?do{$_{$r}=0;$b}:$,until/"/;say for eval,%_
```
Run with `perl -M5.010 file`.
It started wildly different, but I'm afraid it converged with the Ruby solution in many areas towards the end. Seems like Ruby's advantage is "no sigils", and Perl's "better regex integration".
A bit of detail from the innards, if you don't read Perl:
* `@p=<>`: read the whole machine description to `@p`
* `/=/,$_{$`}=$' for split$",pop@p`: for each (`for`) assignment (`split$"`) in the last machine description line (`@p`), locate equal sign (`/=/`) then assign value `$'` to hask `%_` key `$``
* `$o='\w+'`: initial state would be first one to match Perl regex "word characters"
* `until/"/`: loop until we reach a termination state:
+ `map{($r,$o,$,,$b)=$'=~/".*?"|\S+/g if/^$o :/}@p`: loop on machine description `@p`: when we're on the line matching current state (`if/^$o :/`), tokenize (`/".*?"|\S+/g`) the rest of the line `$'` to variables `($r,$o,$,,$b)`. Trick: the same variable `$o` if used initially for label name and subsequently for operator. As soon as the label matches, the operator overrides it, and as a label can't (reasonably) be named + or -, it never matches again.
+ `$_=$o=($_{$r}+=','cmp$o)<0?do{$_{$r}=0;$b}:$,`:
- adjust target register `$_{$r}` up or down (ASCII magic: `','cmp'+'` is 1 whereas `','cmp'-'` is -1);
- if the result is negative (`<0?`, can only happens for -)
- then stay at 0 (`$_{$r}=0`) and return second label `$b`;
- else return first (possibly sole) label `$,`
+ BTW, it's `$,` instead of `$a` so it can be glued to next token `until` with no whitespace in between.
* `say for eval,%_`: dump report (`eval`) and contents of registers in `%_`
[Answer]
## Haskell, 444 characters
```
(w%f)(u@(s,v):z)|s==w=(s,f+v):z|t=u:(w%f)z
(w%f)[]=[(w,f)]
p#(a:z)|j==a=w p++[j]&z|t=(p++[a])#z;p#[]=w p
p&(a:z)|j==a=p:""#z|t=(p++[a])&z
c x=q(m!!0)$map((\(s,_:n)->(s,read n)).break(=='=')).w$last x where
m=map(""#)$init x
q[_,_,r,"+",s]d=n s$r%1$d
q[_,_,r,_,s,z]d|maybe t(==0)(lookup r d)=n z d|t=n s$r%(-1)$d
n('"':s)d=unlines[s,d>>=(\(r,v)->r++'=':shows v" ")]
n s d=q(filter((==s).head)m!!0)d
main=interact$c.lines
t=1<3;j='"';w=words
```
Man, that was hard! Proper handling of messages with spaces in them cost over 70 characters. Output formatting to be more "human readable", and match the examples cost another 25.
---
* Edit: (498 -> 482) various small in-linings, and some of @FUZxxl's suggestions
* Edit: (482 -> 453) switch back using actual numbers for the registers; many golf tricks applied
* Edit: (453 -> 444) inlined output formatting and initial value parsing
[Answer]
## Ruby 1.9, 214 212 211 198 195 192 181 175 173 175
```
*s,k=*$<
a,=s
b=Hash.new 0
eval k.gsub /(\w+)=/,';b["\1"]='
loop{x,y,r,o,t,f=a.scan /".*?"|\S+/
l=(b[r]-=o<=>?,)<0?(b[r]=0;f):t
l[?"]&&puts(eval(l),b)&exit
a,=s.grep /^#{l} /}
```
[Answer]
## Delphi, 646
Delphi does not offer very much with regard to splitting strings and stuff. Luckily, we do have generic collections, which does help a bit, but this is still a rather largish solution :
```
uses SysUtils,Generics.Collections;type P=array[0..99]of string;Y=TDictionary<string,P>;Z=TDictionary<string,Int32>;var t:Y;l,i:string;j,k:Int32;q:P;u:Z;v:TPair<string,Int32>;begin t:=Y.Create;repeat if i=''then i:=q[0];t.Add(q[0],q);ReadLn(l);for j:=0to 6do begin k:=Pos(' ',l+' ');q[j]:=Copy(l,1,k-1);Delete(l,1,k)end;until q[1]<>':';u:=Z.Create;j:=0;repeat k:=Pos('=',q[j]);u.Add(Copy(q[j],1,k-1),StrToInt(Copy(q[j],k+1,99)));Inc(j)until q[j]='';repeat q:=t[i];i:=q[4];u.TryGetValue(q[2],j);if q[3]='+'then Inc(j)else if j=0then i:=q[5]else Dec(j);u.AddOrSetValue(q[2],j)until i[1]='"';WriteLn(i);for v in u do Write(v.Key,'=',v.Value,' ')end.
```
Here the indented and commented version :
```
uses SysUtils,Generics.Collections;
type
// P is a declaration line, offsets:
// 0 = label
// 1 = ':'
// 2 = register
// 3 = operation ('-' or '+')
// 4 = 1st state (or message)
// 5 = 2nd state (or message)
P=array[0..99]of string;
// T is a dictionary of all state lines :
Y=TDictionary<string,P>;
// Z is a dictionary of all registers :
Z=TDictionary<string,Int32>;
var
t:Y;
l,
i:string;
j,
k:Int32;
q:P;
u:Z;
v:TPair<string,Int32>;
begin
// Read all input lines :
t:=Y.Create;
repeat
// Put all lines into a record
if i=''then i:=q[0];
t.Add(q[0],q);
// Split up each input line on spaces :
ReadLn(l);
for j:=0to 6do
begin
k:=Pos(' ',l+' ');
q[j]:=Copy(l,1,k-1);
Delete(l,1,k)
end;
// Stop when there are no more state transitions :
until q[1]<>':';
// Scan initial registers :
u:=Z.Create;
j:=0;
repeat
k:=Pos('=',q[j]);
// Add each name=value pair to a dictionary :
u.Add(Copy(q[j],1,k-1),StrToInt(Copy(q[j],k+1,99)));
Inc(j)
until q[j]='';
// Execute the state machine :
repeat
q:=t[i];
i:=q[4];
u.TryGetValue(q[2],j);
if q[3]='+'then
Inc(j)
else
if j=0then
i:=q[5]
else
Dec(j);
u.AddOrSetValue(q[2],j)
until i[1]='"';
WriteLn(i);
for v in u do
Write(v.Key,'=',v.Value,' ')
end.
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), ~~115~~ 100 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
╥áípßNtP~£G±☼ΩtHô⌐╒╡~·7╝su9êq7h50Z`╩ë&ñ╝←j╞.½5└∩√I|ù┤╧Åτ╘8┼ç╕╒Æ►^█₧♫÷?²H½$IG☺S╚]«♀_≥å∩A+∩╣Δ└▐♫!}♥swα
```
[Run and debug it](https://staxlang.xyz/#p=d2a0a170e14e74507e9c47f10fea744893a9d5b57efa37bc7375398871376835305a60ca8926a4bc1b6ac62eab35c0effb497c97b4cf8fe7d438c587b8d592105edb9e0ef63ffd48ab2449470153c85dae0c5ff286ef412befb9ffc0de0e217d037377e0&i=s0+%3A+a+-+s1+%22Ok%22%0As1+%3A+b+%2B+s0%0Aa%3D3+b%3D4%0A%0Ainit+%3A+t+-+init+d0%0Ad0+%3A+a+-+d1+a0%0Ad1+%3A+b+%2B+d2%0Ad2+%3A+t+%2B+d0%0Aa0+%3A+t+-+a1+%22Ok%22%0Aa1+%3A+a+%2B+a0%0Aa%3D3+b%3D4%0A%0As0+%3A+t+-+s0+s1%0As1+%3A+t+%2B+%22t+is+1%22%0At%3D17%0A%0As0+%3A+t+-+%22t+is+nonzero%22+%22t+is+zero%22%0At%3D1%0A%0Ainit0+%3A+k+-+init1+init3%0Ainit1+%3A+r+%2B+init2%0Ainit2+%3A+t+%2B+init0%0Ainit3+%3A+t+-+init4+init5%0Ainit4+%3A+k+%2B+init3%0Ainit5+%3A+r+-+init6+%22ERROR+k+is+0%22%0Ainit6+%3A+i+%2B+init7%0Ainit7+%3A+n+-+loop0+%22ERROR+n+is+0%22%0Aloop0+%3A+n+-+loop1+%22Ok%22%0Aloop1+%3A+i+%2B+loop2%0Aloop2+%3A+k+-+loop3+loop5%0Aloop3+%3A+r+%2B+loop4%0Aloop4+%3A+t+%2B+loop2%0Aloop5+%3A+t+-+loop6+loop7%0Aloop6+%3A+k+%2B+loop5%0Aloop7+%3A+i+-+loop8+loopa%0Aloop8+%3A+r+-+loop9+loopc%0Aloop9+%3A+t+%2B+loop7%0Aloopa+%3A+t+-+loopb+loop7%0Aloopb+%3A+i+%2B+loopa%0Aloopc+%3A+t+-+loopd+loopf%0Aloopd+%3A+i+%2B+loope%0Aloope+%3A+r+%2B+loopc%0Aloopf+%3A+i+%2B+loop0%0An%3D40+k%3D3&a=1&m=1)
[Answer]
# [JavaScript (V8)](https://v8.dev/), 300 bytes
```
p=>{g=p.split`
`;r=g[g.length-1].split` `.map(R=>R.split`=`);g.pop();l=g.map(L=>L.match(/\w+|[+-]|"[ \w]+"/g));t=l[0][0];for(;;){c=l.find(L=>L[0]==t);(e=r.find(R=>R[0]==c[1]))||r.push(e=[c[1],0]);t=eval(c[2]+c[2]+"e[1]")<0?e[1]++&&c[4]:c[3];if(t[0]==`"`)return t.slice(1,-1)+`
`+r.map(R=>R.join`=`)}}
```
[Try it online!](https://tio.run/##jVJNb6MwFLz7V1g@VFhuKATSdMM6e9pbpUq5EiQIX6FhDQI3lbbpb8/az07h1pWil/F4Zh5D8pqdszEfml4uzk/Xil97vv2oee@OfdvIFKXRwOu4dttS1PK48BN7gVP3T9Y7O77dWYanNKrdvusdGrW8hutnvn1WQOZH52H/zi4xWyQXEuP9e8LIQ01pJHkbe4n6RFU3OFFEP3LeulUjCjCrC84ljZySD4bVG4HNYz@h9HIZ3P5tPCpBrJl7L9Gh5TlrnTxeJgwGKdUVoT@9XxowdneXx2GyyeMgiZrKkRCYkpQOpXwbBJbu2DZ56fj3C58y9RbYMNV97Rqh235@XvuhEdKpnHT08AZneIFHH5OXE0Hqe4MPmOHRQxkP8IGHKaUIGQfZC/J1UPZGNFLppQoAWHiouCUWPs7U8ZZXLFGxBC3TssyzvswuznzwMW36fvF4sysw@uapdTKRuBmxT5Dk/vp//MYgOvG3HDpij4B1xDfVdcjJdvdhBsjgDR7U02i8BObWHFzABLP3FsJcIYN1JpulrSDNKB8x@b3bveyURD2nR5AhN7ixljUwa8UIZWm7rvduFmEthpwE9gcw0CRpvARmaStqHMBcIYNNRY1DYEJbcfKubEWNH2GukcGm4pS2hr1G@QQzQwab6hr/gJkjg6ddJjOb7TrM@MOskcnMZ8oCZoUMnpQlMOWso9lbzTQeEjz08IkH6l9y/Qc "JavaScript (V8) – Try It Online")
I used a trick with `eval` to choose between `++e[1]` and `--e[1]`... it only saved a few bytes but it's fun.
[Answer]
## PHP, ~~446~~ ~~441~~ ~~402~~ ~~398~~ ~~395~~ ~~389~~ ~~371~~ ~~370~~ 366 characters
```
<?$t=trim;$e=explode;while($l=$t(fgets(STDIN))){if(strpos($l,"=")){foreach($e(" ",$l)as$b){list($k,$c)=$e("=",$b);$v[$k]=$c;}break;}list($k,$d)=$e(":",$l);$r[$z=$t($k)]=$t($d);$c=$c?:$z;}while($d=$e(" ",$r[$c],4)){$c=$v[$a=$d[0]]||!$d[3]?$d[2]:$d[3];if(!$r[$c]){eval("echo $c.'\n';");foreach($v as$k=>$c)echo$k."=".$c." ";die;}if(!$d[3]&&++$v[$a]||$v[$a]&&--$v[$a]);}
```
## Ungolfed
---
```
<?php
$register = array();
$values = array();
while($line = trim(fgets(STDIN))){
if(strpos($line, "=")){
// Set each value and then continue to the calculations
foreach(explode(" ", $line) as $var){
list($key, $val) = explode("=", $var);
$values[$key] = $val;
}
break;
}
list($key, $data) = explode(":", $line);
// Add data to the register
$register[$z = trim($key)] = trim($data);
// Set the first register
$current = $current?:$z;
}
while($data = explode(" ", $register[$current], 4)){
// Determine next register and current register
$current = $values[$target = $data[0]] || !$data[3]? $data[2] : $data[3];
// Will return true if the register does not exist (Messages wont have a register)
if(!$register[$current]){
// No need to strip the quotes this way
eval("echo$current.'\n';");
// Print all values in the right formatting
foreach($values as $key => $val)
echo $key."=".$val." ";
die();
}
// Only subtraction has a third index
// Only positive values return true
// If there is no third index, then increase the value
// If there is a third index, increment the decrease the value if it is positive
// Uses PHP's short-circuit operators
if(!$data[3] && ++$values[$target] || $values[$target] && --$values[$target]);
}
```
## Changelog
---
**446 -> 441**: Supports strings for the first state, and some slight compression
**441 -> 402**: Compressed if/else and assignment statements as much as possible
**402 -> 398**: Function names can be used as constants which can be used as strings
**398 -> 395**: Uses short circuit operators
**395 -> 389**: No need for the else part
**389 -> 371**: No need to use array\_key\_exists()
**371 -> 370**: Removed unneeded space
**370 -> 366**: Removed two unneeded spaces in the foreach
[Answer]
# Groovy , 338
```
m={s=r=[:];z=[:]
it.eachLine{e->((e==~/\w+=.*/)?{(e=~/((\w+)=(\d+))+/).each{r[it[2]]=it[3] as int}}:{f=(e=~/(\w+) : (.*)/)[0];s=s?:f[1];z[f[1]]=f[2];})()}
while(s[0]!='"'){p=(z[s]=~/(\w+) (.) (\w+|(?:".*?")) ?(.*)?/)[0];s=p[3];a=r[p[1]]?:0;r[p[1]]=p[2]=='-'?a?a-1:{s=p[4];0}():a+1}
println s[1..-2]+"\n"+r.collect{k,v->"$k=$v"}.join(' ')}
['''s0 : a - s1 "Ok"
s1 : b + s0
a=3 b=4''':'''Ok
a=0 b=7''',
'''init : t - init d0
d0 : a - d1 a0
d1 : b + d2
d2 : t + d0
a0 : t - a1 "Ok"
a1 : a + a0
a=3 b=4''':'''Ok
a=3 b=7 t=0''',
'''s0 : t - s0 s1
s1 : t + "t is 1"
t=17''':'''t is 1
t=1''',
'''s0 : t - "t is nonzero" "t is zero"
t=1''':'''t is nonzero
t=0''',
'''init0 : k - init1 init3
init1 : r + init2
init2 : t + init0
init3 : t - init4 init5
init4 : k + init3
init5 : r - init6 "ERROR k is 0"
init6 : i + init7
init7 : n - loop0 "ERROR n is 0"
loop0 : n - loop1 "Ok"
loop1 : i + loop2
loop2 : k - loop3 loop5
loop3 : r + loop4
loop4 : t + loop2
loop5 : t - loop6 loop7
loop6 : k + loop5
loop7 : i - loop8 loopa
loop8 : r - loop9 loopc
loop9 : t + loop7
loopa : t - loopb loop7
loopb : i + loopa
loopc : t - loopd loopf
loopd : i + loope
loope : r + loopc
loopf : i + loop0
n=40 k=3''':'''Ok
i=40 k=3 n=0 r=27 t=0'''].collect {input,expectedOutput->
def actualOutput = m(input)
actualOutput == expectedOutput
}
```
[Answer]
# Clojure (344 chars)
With a few linebreaks for "readability":
```
(let[i(apply str(butlast(slurp *in*)))]
(loop[s(read-string i)p(->> i(replace(zipmap":\n=""[] "))(apply str)(format"{%s}")read-string)]
(let[c(p s)](cond(string? s)(println s"\n"(filter #(number?(% 1))p))
(=(c 1)'-)(let[z(=(get p(c 0)0)0)](recur(c(if z 3 2))(if z p(update-in p[(c 0)]dec))))
1(recur(c 2)(update-in p[(c 0)]#(if %(inc %)1)))))))
```
[Answer]
## Postscript () () ~~(852)~~ (718)
For reals this time. Executes all the test cases. It still requires the RM program to immediately follow in the program stream.
*Edit:* More factoring, reduced procedure names.
```
errordict/undefined{& " * 34 eq{.()= !{& " .(=). load " .( ).}forall ^()=
stop}{^ ^ " 0 @ : 0}ifelse}put<</^{pop}/&{dup}/:{def}/#{exch}/*{& 0
get}/.{print}/~{1 index}/"{=string cvs}/`{cvn # ^ #}/+={~ load add :}/++{1
~ length 1 sub getinterval}/S{/I where{^}{/I ~ cvx :}ifelse}/D{/? # :/_ #
cvlit :}/+{D S({//_ 1 +=//?})$ ^ :}/-{/| # : D S({//_ load 0 ne{//_ -1
+=//?}{//|}ifelse})$ ^ :}/![]/@{~/! #[# cvn ! aload length & 1 add #
roll]:}/;{(=)search ^ # ^ # cvi @ :}/${* 32 eq{++}if * 34 eq{& ++(")search
^ length 2 add 4 3 roll # 0 # getinterval cvx `}{token ^
#}ifelse}>>begin{currentfile =string readline ^( : )search{`( + )search{`
$ ^ +}{( - )search ^ ` $ $ ^ -}ifelse}{( ){search{;}{; I}ifelse}loop}ifelse}loop
```
Indented and commented with appended program.
```
%!
%Minsky Register Machine Simulation
errordict/undefined{ %replace the handler for the /undefined error
& " * 34 eq{ % if, after conversion to string, it begins with '"',
.()= !{ % print it, print newline, iterate through the register list
& " .(=). load " .( ). % print regname=value
}forall ^()= stop % print newline, END PROGRAM
}{ % if it doesn't begin with '"', it's an uninitialized register
^ ^ " 0 @ : 0 %initialize register to zero, return zero
}ifelse
}put
<<
/^{pop}
/&{dup}
/:{def} % cf FORTH
/#{exch}
/*{& 0 get} % cf C
/.{print} % cf BF
% these fragments were repeated several times
/~{1 index}
/"{=string cvs} % convert to string
/`{cvn # ^ #} % convert to name, exch, pop, exch
/+={~ load add :} % add a value to a variable
/++{1 ~ length 1 sub getinterval} % increment a "string pointer"
/S{/I where{^}{/I ~ cvx :}ifelse} %setINIT define initial state unless already done
/D{/? # :/_ # cvlit :} %sr define state and register for generated procedure
/+{D S({//_ 1 +=//?})$ ^ :} % generate an increment state and define
/-{/| # : D S({//_ load 0 ne{//_ -1 +=//?}{//|}ifelse})$ ^ :} % decrement state
/![] %REGS list of registers
/@{~/! #[# cvn ! aload length & 1 add # roll]:} %addreg append to REGS
/;{(=)search ^ # ^ # cvi @ :} %regline process a register assignment
/${ %tpe extract the next token or "string"
* 32 eq{++}if %skip ahead if space
* 34 eq{ %if quote, find the end-quote and snag both
& ++(")search ^ length 2 add 4 3 roll # 0 # getinterval cvx `
}{
token ^ # %not a quote: pull a token, exch, pop
}ifelse
}
>>begin
{
currentfile =string readline ^
( : )search{ % if it's a state line
`( + )search{ % if it's an increment
` $ ^ + %parse it
}{
( - )search ^ ` $ $ ^ - %it's a decrement. Parse it
}ifelse
}{ % not a state, do register assignments, and call initial state
( ){search{;}{; I}ifelse}loop %Look Ma, no `exit`!
}ifelse
}loop
init0 : k - init1 init3
init1 : r + init2
init2 : t + init0
init3 : t - init4 init5
init4 : k + init3
init5 : r - init6 "ERROR k is 0"
init6 : i + init7
init7 : n - loop0 "ERROR n is 0"
loop0 : n - loop1 "Ok"
loop1 : i + loop2
loop2 : k - loop3 loop5
loop3 : r + loop4
loop4 : t + loop2
loop5 : t - loop6 loop7
loop6 : k + loop5
loop7 : i - loop8 loopa
loop8 : r - loop9 loopc
loop9 : t + loop7
loopa : t - loopb loop7
loopb : i + loopa
loopc : t - loopd loopf
loopd : i + loope
loope : r + loopc
loopf : i + loop0
n=40 k=3
```
[Answer]
# AWK - 447
```
BEGIN{FS=":"}NF<2{split($1,x," ");for(y in x){split(x[y],q,"=");
g[q[1]]=int(q[2])}}NF>1{w=$1;l=$2;gsub(/ /,"",w);if(!a)a=w;for(i=0;;)
{sub(/^ +/,"",l);if(l=="")break;if(substr(l,1,1)=="\""){l=substr(l,2);
z=index(l,"\"")}else{z=index(l," ");z||z=length(l)+1}d[w,i++]=
substr(l,1,z-1);l=substr(l,z+1)}}END{for(;;){if(!((a,0)in d))break;h=d[a,0];
if(d[a,1]~/+/){g[h]++;a=d[a,2]}else{a=g[h]?d[a,2]:d[a,3];g[h]&&g[h]--}}
print a;for(r in g)print r"="g[r]}
```
This is the output for the first test:
```
% cat | awk -f mrm1.awk
s0 : a - s1 "Ok"
s1 : b + s0
a=3 b=4
^D
Ok
a=0
b=7
```
] |
[Question]
[
# Challenge
Given a square matrix of characters (single-byte printable ASCII characters), rotate each "ring" of the matrix in opposite directions.
Let's take an example:
```
1 2 3 4 5
6 7 8 9 A
B C D E F
G H I J K
L M N O P
```
Then, the outermost ring is rotated clockwise 90 degrees, like so:
```
1 2 3 4 5 L G B 6 1
6 A M 2
B F => N 3
G K O 4
L M N O P P K F A 5
```
The second ring is rotated counterclockwise 90 degrees:
```
7 8 9 9 E J
C E => 8 I
H I J 7 C H
```
The final ring is rotated clockwise 90 degrees, but since it is a single number (letter in our example), then it is not really affected.
The final result is:
```
L G B 6 1
M 9 E J 2
N 8 D I 3
O 7 C H 4
P K F A 5
```
If the matrix has an even side length, the innermost ring will be a 2x2 square and should still be rotated.
# Input
A list of lists in any reasonable standard format. For example, a newline-delimited space-delimited string or a list of space-delimited strings is acceptable, but a list of the values as rings around the matrix is not acceptable.
The characters are not necessarily unique.
# Output
A list of lists in any reasonable standard format. Same rules as the input.
# Test Cases
```
1 2 3 7 4 1
4 5 6 => 8 5 2
7 8 9 9 6 3
1 2 3 4 5 6 Y S M G A 1
A B C D E F Z E K Q W 2
G H I J K L => ! D O I V 3
M N O P Q R @ C P J U 4
S T U V W X # B H N T 5
Y Z ! @ # $ $ X R L F 6
```
# Credits
Heavily inspired by a [related challenge](https://codegolf.stackexchange.com/questions/111991/rotating-a-2d-matrix) that rotates each element counterclockwise one position (not by 90 degrees).
[Answer]
# [Haskell](https://www.haskell.org/), 94 bytes
An anonymous function taking and returning a list of `String`s.
Use as `(cycle[t.r,r.t,r.t,r.t]?)["123", "456", "789"]`.
```
(cycle[t.r,r.t,r.t,r.t]?)
(g:h)?(a:b)=g$a:h?t(r b)
_?a=a
r=reverse;t=zipWith(:)`foldr`repeat[]
```
[Try it online!](https://tio.run/##TYxbS8NAEEbf51fEGOgurQG1Vo0usVqtl3q/VI3BTuKkWbquZbMVFP97TKqCDwPng3Mmx2JCSpWvKLWQ2pLB1HqWCusrqamAGp0oFq77g@qLYct1g4RvLyWGcOLomVKOEjM9D1jmIG82G0@6EcyDpMwESz9SRZH1Tcv49u/ikAMbBzkPGVb/xNjDIA8tM07C4TlEgWCEoXcyBW1Z8SmnQ2lzFvBR9qZezMjQlNBGcVkur6xCe60D6xubANWoubu719s/gP7h0fHJAE7Pzi8ur@D65vZueA8Pjws7i96vCp0q68I/HQa1DvAN "Haskell – Try It Online")
# How it works
* `r` is `reverse`. `t` is one byte shorter than importing `Data.List.transpose`. `t.r` rotates a list of lists 90 degrees clockwise, and `r.t` rotates it counterclockwise.
* The operator `?` takes two arguments, a list of functions and a matrix as a list of strings.
+ An empty matrix is just returned.
+ Otherwise, `?` strips the first function `f` off the list of functions, and the first line `a` off the matrix.
+ Then it rotates the remainder `b` of the matrix clockwise, and recurses with that and the remaining functions. This gradually strips the matrix from the outside in, one ring each four steps.
+ Then it prepends the original line `a` to the result, and applies the function `f` to it to adjust the orientation of the matrix.
* The anonymous function calls `?` with the input matrix as a list of strings, and an infinite list of functions, which repeats cyclically every four steps.
+ For most of the steps the function is counterclockwise rotation, which undoes the implicit clockwise rotation done by `?` when recursing.
+ However, the first step and every fourth step afterwards is instead clockwise rotation.
- This function is applied when a ring of the matrix is complete, causing each ring to be 180 degrees rotated with respect to the next one.
- By luck, this is also the correct transformation to apply to the final, completed matrix to get the final result.
[Answer]
# [Python 2](https://docs.python.org/2/), 104 bytes
```
def f(x):l=len(x)-1;r=range(l+1);return[[[x[l-i][j],x[i][l-j]][min(i,j,l-i,l-j)%2]for i in r]for j in r]
```
[Try it online!](https://tio.run/##jc5LS8QwGIXhvb@iopIW00Wr420YcLzreL9ryEKw1YSYGUKF@uvr27hyIy4eevgO5WT21bxPfdl1r1Wd1GmbbbmRqzwhL4ZhFF78W5W65SIbhqr5DF4p1SqXG62slq3i63KrtfowPjXSSirYbKnU9TQkJjE@CTHan9jNgvENU0qJQkhRYgWrGAgtlVgjrWMDmxjH6w5pF3vYx0G8HpKOcIwTTOL1lHSGc1zgUmidzf05LJntfx2T/jslGeqb31NSXOE6NjekW9zhHg94jM0T6Rnz2MYCFvtndt8 "Python 2 – Try It Online")
`x[l-i][j]` are the coordenates of a clockwise turn, `x[i][l-j]` for a counterclowise turn.
`min(i,j,l-i,l-j)%2` is used to pick the right direction
[Answer]
# Mathematica, 113 bytes
```
r=Reverse;(l=Length[s=#];Table[s[[i+1;;l-i,i+1;;l-i]]=r/@r@s[[i+1;;l-i,i+1;;l-i]],{i,⌊l/2⌋}];r/@Transpose@s)&
```
it is better to input as char string like "E" for special letters like E,I...
**input**
>
> [{{1, 2, 3, 4, 5, 6}, {A, B, C, D, "E", F}, {G, H, "I", J, K, L}, {M,
> N, O, P, Q, R}, {S, T, U, V, W, X}, {Y, Z, "!", "@", "#", "&"}}]
>
>
>
**output**
>
> {{Y, S, M, G, A, 1}, {Z, "E", K, Q, W, 2}, {"!", D, O, "I", V,
> 3}, {"@", C, P, J, U, 4}, {"#", B, H, N, T, 5}, {"&", X, R, L, F,
> 6}}
>
>
>
[Answer]
# Octave, 86 bytes
```
@(a){k=a;k(x=2:end-1,x)=0;a=rot90(a);a(m)=rot90(a,-2)(m=~mod(bwdist(+k,'ch'),2));a}{5}
```
[Try it online!](https://tio.run/##y08uSSxL/f/fQSNRszrbNtE6W6PC1sgqNS9F11CnQtPWwDrRtii/xNIAKG@dqJGrCePp6BppauTa1uXmp2gkladkFpdoaGfrqCdnqGvqGGkC1dZWm9b@T7NNzCu25uJK04jW09PjUjc0MlbnUjcxNQOS5haW6rGaKHIQCUcnZxdXNyDD3cPTy9sHyPD18w8IDAIygkNCw8IjgIzIKEUHZRWg/v8A "Octave – Try It Online")
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 35 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?") ([SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set"))
Full program. Prompts for APL matrix expression. Requires 0-based indexing.
```
⍉⌽m⊣{(b↓e↓m)←⌽⊖b↓m↓⍨e←-b←2⍴⍵}¨⍳≢m←⎕
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkGXI862gv@P@rtfNSzN/dR1@JqjaRHbZNTgThXEygPFH3UNQ0klAvEj3pXAGUm6AL5E4we9W551Lu19tCKR72bH3UuygWp7pv6H2jefwUwKOB61DYRKOQV7O8HZKlHKxkaGSvpKJmYmgFJcwtLpVh1LkylEHUmpkA1ZkBFjkDaydnF1Q1Iu3t4enkDaR9fP/8A/LpBVjii6PMBMkD6AoOAjOCQ0LDwCCAjMkrRQVkFaBYA "APL (Dyalog Unicode) – Try It Online")
`m←⎕` prompt for matrix and assign to `m`
`≢` tally the number of rows in it
`⍳` **ɩ**ndices zero through one less than that
`{`…`}¨` apply the following lambda to each element (denoted `⍵` in the code) of that:
`2⍴⍵` **r**eshape the index to a two-element list
`b←` assign to `b` (for **b**eginning)
`-` negate that
`e←` assign to `e` (for **e**nd)
`m↓⍨` drop that many (negative, so trailing) rows and columns from `m`
`b↓` drop that many leading rows and columns from that
`⊖` flip upside down
`⌽` mirror
`(`…`m)←` assign to the following sub-array of `m`:
`e↓` drop the appropriate number of rows and columns from the end (bottom right)
`b↓` drop the appropriate number of rows and columns from the beginning (top left)
`m⊣` ignore the pass-through values of all the assignments, in favour of the updated value of `m`
`⌽` mirror
`⍉` transpose
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 81 bytes
```
{u⊃+/{⌽[1+2|⍵]∘⍉w×1@(y/⍨∨/¨(⍵,x)∘∊¨y←,∘.,⍨(⍵-1)↓⍳x←1+|⍵-≢w)⊢0×w}¨⍳⌈.5×≢w←⍵}u←⎕UCS
```
[Try it online!](https://tio.run/##RY69TsJgFIZ3r@Izmnw0FLBUUDa0/oD/UlDROKClFUWKYC0VmTSkICUaQ3Bm6mDioI4u5U7OjdTz6eByTs77PDl5C9VySLEKZV3zoT@Q8oQqaqVO/aYB3ftgpAm97yMhGL0D5@sY7FdwOuZ4KCQDVgQcF2w34rkBZHyDY9Tueq4F7ScejzCPBmMhgYP2CzgfDSRCkL0KQWdkctAdzYyHZstzEULPDsfGQwZQQ6dlsN0f5CTZV3@jPlYC5w2cT@9dhPYzQjkj4cym0rKvodPEAxel8PiglOpVwnvuX0EuoLLZmtCISER8QYWoOBuLz80nKGZxEv/PFhalpeWV1VR6bX1jc2t7ZzcjZ3N7@wf5w8nk1DTTEyTB9OxZkVwZpdMLclLTzQpR9QY5Ny6rdaLfFGvkGnG5cGsRRdfoDw "APL (Dyalog Unicode) – Try It Online")
A 2-train which takes the matrix as its right argument.
The idea behind this is to peel the matrix into its rings, like so:
```
┌──────┬──────┬──────┬──────┐
│123456│123456│ │ │
│ABCDEF│A F│ BCDE │ │
│GHIJKL│G L│ H K │ IJ │
│MNOPQR│M R│ N Q │ OP │
│STUVWX│S X│ TUVW │ │
│YZ!@#$│YZ!@#$│ │ │
└──────┴──────┴──────┴──────┘
```
Then each of these rings are rotated left/right based on their index.
My algorithm for getting the rings has a lot of room for improvement (Porting the python solution may be shorter).
## Explanation
`⎕UCS` convert the matrix to its unicode values
`u←⎕UCS` store conversion function as u
`{...}` apply the following function on the matrix:
`w←⍵` store argument as w
`⍳⌈.5×≢` range `1..ceil(length(w)/2)`
---
**Getting the rings**
`{...}¨` for each value `i` in the range:
`0×w` to the input, converted to zeroes,
`1@(...)` replace the following coordinates with 1s:
`1+|⍵-≢⍵` upper limit: `length(w) - i`
`(⍵-1)↓⍳` create range from i to that
`,∘.,⍨` get all points in that range
`y←` store in `y`
`∨/¨(⍵,x)∘∊¨` check which ones are part of the ring, and get a list of booleans
`y/⍨` filter `y` using the boolean array
`w×` multiply `w` with that (vectorizes)
`⌽[1+2|⍵]∘⍉` Rotate right if `i` is odd, otherwise left
---
Finally,
`+/` sum all the matrices (vectorizes)
`⊃` unwrap
`u` convert back to character matrix.
[Answer]
# [R](https://www.r-project.org/), 98 bytes
```
f=function(m,r=T,d=length(m)^.5){n=t(m)[d:1,]
if(r)n[]=rev(n)
if(d>2)n[e,e]=f(m[e<-3:d-1,e],!r)
n}
```
[Try it online!](https://tio.run/##jc9ZS8QwFAXg9/yLiT4kkBE6tTNOMeK@jbt1LVVqk2phkkKIG@JvrycvPgwiQ/jg5CYP97iusV67aVlp9ehaX3otu1rWr7byTWuZEU5mQsmpts/@hRn@sJTwLys9Yq7SSBSkqZnjNi@k02/M8nBXawNMtNCFrJnJ9Wo/TlU/wl30HCf2uzPSlN41H6xiNKKCDiCGZUioIHSIMIIVGMNGGG4ibME27MBuGO4h7MMBHMIkDI8QjuEETuGMcpHgPH269l1m2HK2NgoR8rtWlI5FjDPv/79rhBYkrD735mFxMrO5oOdwER4uETK4gmu4gdvwcIdwDz1YhwVYROchzv8duh8 "R – Try It Online")
**How?**
At each recursive step, rotate the matrix clockwise by transposing it and reversing the rows.
Then, if it should be an anticlockwise rotation, reverse all the elements.
Finally, replace the 'internal matrix' with the results of a recursive call, with the rotation set to the opposite direction.
```
interlaced_rotate=
f=function(m,r=T, # recursive function:
# m=matrix
# r=direction of rotation (TRUE=clockwise, FALSE=anticlockwise)
d=length(m)^.5){ # d=length of matrix side
n=t(m)[d:1,] # n=m rotated clockwise by transposing & reversing rows
if(r)n[]=rev(n) # if it's an anticlockwise rotation, reverse the elements
if(d>2) # if the 'internal matrix' has a side-length of >1:
n[e,e]= # replace it with
f(m[e<-3:d-1,e],!r) # a recursive call, reversing the direction
n} # finally, return n
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 19 18 bytes
```
ŒJUC;L‘_ɗ@ṂḂʋ¦€œịṁ
```
[Try it online!](https://tio.run/##y0rNyan8///oJK9QZ2ufRw0z4k9Od3i4s@nhjqZT3YeWPWpac3Tyw93dD3c2/j/c7v7/f7SSoZGxiamZko6So5Ozi6sbkOHu4enl7QNk@Pr5BwQGARnBIaFh4RFARmSUooOyilIsAA "Jelly – Try It Online")
## Explanation
```
ŒJUC;L‘_ɗ@ṂḂʋ¦€œịṁ Main monadic link
ŒJ Multidimensional indices
U Reverse each
€ For each
ʋ (
; Join with
ɗ (
L @ Length of the input
‘ Increment
_ Subtract the argument
)
Ṃ Minimum
Ḃ Parity
ʋ )
¦ At the obtained index
C subtract it from 1
œị Index into the input
ṁ Reshape to be the same as the input
```
] |
[Question]
[
On a [toroidal square grid](https://www.google.com/search?q=toroidal+grid&sxsrf=ALeKk00zPr0KXqKlqJnTbEU7iskw6hvZ8Q:1588277096042&source=lnms&tbm=isch&sa=X&ved=2ahUKEwis5vSg-ZDpAhWCDOwKHWwhAi8Q_AUoAXoECAsQAw&biw=1920&bih=979#imgrc=DNpOW7cXm2Nv9M) (you can wrap around) where each cell indicates one direction (`^` `>` `v` `<`) if we pick a cell and start to walk following these directions, we will eventually get stuck in a loop.
We may end up in a different loop, depending on our starting cell.
Not all the cells we encounter constitute our terminal loop: these are said to be *tributary* to that loop.
# Task
Given a square grid configuration, count for each loop \$L\_i\$:
* How many cells is it made up with? \$n\_i\$
* How many *tributary* cells does it have? \$t\_i\$
# Input
You choose the **set** of 4 printable characters or integers you'll use as directions.
* A square matrix having **set** elements as entries (can be a string)
# Output
* List of \$(n\_i,t\_i)\$ for each \$L\_i\$
The pairs can be in any order.
# Example
***input*** `urdrurllruuuulrududllurdu`
[](https://i.stack.imgur.com/Ca6OG.png)
*-vivid color: loop
-pale color: tributary
In this configuration there are 3 loops (orange, blue, green) of lengths (2, 2, 6) with (0, 10, 5) tributary cells.*
***output*** `6 5 2 10 2 0`
```
Alternative inputs:
1232124421111421313441231
[[^,>,v,>,^],[>,<,<,>,^],[^,^,^,<,>],[^,v,^,v,<],[<,^,>,v,^]]
Valid outputs:
2 10 2 0 6 5
(2, 10), (6, 5), (2, 0)
Non valid outputs:
10 2 2 0 6 5
(0, 2), (10, 2), (6, 5)
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code wins.
[Answer]
# Java 10, ~~374~~ ~~371~~ 364 bytes
```
import java.util.*;m->{var L=new HashSet<Set>();int l=m.length,R=l*l,r,c,d;for(Set S;R-->0;S.add(r==R/l&c==R%l?-1:-2),L.add(S))for(S=new TreeSet(),r=R/l,c=R%l;S.add(r*l+c);r=(r-(d-d%3*d)/2+l)%l,c=(c-(d<2?1-2*d:0)+l)%l)d=m[r][c];for(Set z:L){if(z.remove(-1)){c=0;for(Set q:L)if(q.remove(-2)){if(q.containsAll(z))c++;q.add(-2);}System.out.println(z.size()+","+c);}}}
```
-10 bytes thanks to *@ceilingcat*.
Uses a matrix of integers `0,1,2,3` for `<,>,v,^` respectively.
[Try it online.](https://tio.run/##fVLRbtowFH3vV1whMdnECSE8jRCqvm1S11XQN8Sk1DElzEnAMZkgyrfTaxNotTFkObGPz7n3@lyv4yp218nvY5ptCqVhjXtvp1Pp9ULo98EZfAVdgF4JeN1r4fJil@s7LuOyhB9xmtd3AGmuhVrGXMCT2QJURZoAJ4jPF/MFZDREuLnDT6ljnXJ4ghyiY@ZO6ipW8Bjl4g98i8vVTOgxzgmhIYpBRpknRf6mV2wayZ5kinGWhMtCEWTBLJy67sQPZ16cJERF0bQvv3D8deW9Oxi5AWWP9mhGqdXYPC9KCFQTypQRMG745xg96XAaqogolyRu0h32EtoPHEm7hkg4ouPgfuAGvWTkU4vTJMrmajHni0thh9EjrdMlOXhKZEUliDugtOaRf2FskYGE7YUQUKvYerzINfpaPkhJDpRyxwm3tjakhM1sX2qRecVOexuFFskck5TpQRDqdFjHFN80zTE0Xm92rxK9bi23PckwMplpVL5hX2J6apcWpSbGmrZhdT1kAxbgHDasHjAfx2k9ZGbgzq4DZqaPa5@dFMOmsb2@FhPPrcq/zTmzbFyTO2j5n9@PvYyVf7yx012uGNT5nm92egQd5@NxPygV70svEWLzUpwMIRlt67oW41kJrfeu3YsEg7XcjcWfDUyyG/qfO30qouXkHr/Fv37jz8n@vrh5WRYDBaMLesGhQlTRFvw3J@mMJ9WvjsdXsXrQpDp78f/qTH1mNsd3)
**Explanation:**
```
import java.util.*; // Required import for Set, HashSet, and TreeSet
m->{ // Method with integer-matrix parameter and no return-type
var L=new HashSet<Set>();// Create a Set of Sets `L`, starting empty
int l=m.length, // Set `l` to the dimensions of the input-matrix
R=l*l, // Index integer `R` to loop over the cells
r,c, // Temp-integers `r,c` for the row and column
d; // Temp-integer `d` for the direction
for(Set S; // Temp Set `S`, starting uninitialized
R-->0 // Loop `R` in the range (`l*l`, 0] over all cells:
; // After every iteration:
S.add(r==R/l&c==R%l?// If `r,c` is still cell `R`:
-1 // Add -1 to Set `S`
: // Else:
-2), // Add -2 instead
L.add(S)) // And then add `S` to Set `L`
for(S=new TreeSet(), // Set `S` to a new empty sorted-Set
r=R/l,c=R%l; // Set `r,c` to cell `R`
S.add(r*l+c) // Add `r,c` as cell-index to Set `S` every iteration
// and continue looping as long as it wasn't in `S` yet:
; // After every iteration:
r=(r-(d-d%3*d)/2// If `d` is 3:
// Go to the cell above
// Else-if `d` is 2:
// Go to the cell below
+l)%l // Adjust row wraparounds when we're out of bounds
c=(c-(d<2?1-2*d:0)
// Else-if `d` is 0:
// Go to the cell left
// Else-if `d` is 1:
// Go to the cell right
+l)%l // Adjust column wraparounds when we're out of bounds
d=m[r][c]; // Set `d` to the current direction of cell `r,c`
// After we've determined all paths per cell:
for(Set z:L){ // Loop `z` over each path of Set `L`:
if(z.remove(-1)){ // Remove a -1 (if present),
// and if it indeed contained a -1 (infinite path):
c=0; // Use `c` as counter, starting at 0
for(Set q:L) // Inner loop `q` over each path of Set `L`:
if(q.remove(-2)){ // Remove a -2 (if present),
// and if it indeed contained a -2 (tributary path):
if(q.containsAll(z))
// If `q` contains all values of `z`:
c++; // Increase the counter by 1
q.add(-2);} // Add -2 back to `q` for the next iteration of loop `z`
System.out.println( // Print with trailing newline:
z.size() // The size of path `z`
+","+c);}}} // and the counter (comma-separated)
```
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), ~~99~~ 81 bytes
thanks @bstrat for -18 bytes!
```
{l,'(#'.c)-l:#'!c:={x@<x:(x?a@*|x)_x}'{?x,a@x}/'a::s/s!'(+(,/-:\=2)@,/x)+!s:2##x}
```
[Try it online!](https://ngn.codeberg.page/k#eJwdyrEKwyAQgOE9b6EOp42pkPHaoA9SKBLJdJNycGB999pO3z/8F3byYA3cT7cRGlAnHl3SU9BKzOn2EfeWAT2Kz0lGgIzYQlNgV+vDhq9jd8kHcatquBsjY1kuXSqTjgGt5jpbP3Ql+svMVH8WLjSlObB2XzqsJ2k=)
down,right,up,left in the input are encoded as 0 1 2 3
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~44~~ 41 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
-3 as the grid is guaranteed to be square.
```
ŒṪœịı*ÆiƊ+⁸ʋƬ⁺⁹ɗ€⁸%LḞQ€LÞḢṢƲ€¹ƙ$Ẉ€µḟṂLṭṂ)
```
A monadic Link accepting a list of lists of integers which yields a list of lists of integers (each being a `[loop_size, tributary_count]` - i.e. \$(n\_i, t\_i)\$).
The directions in the input are:
```
^ 2
> 1
V 4
< 3
```
**[Try it online!](https://tio.run/##y0rNyan8///opIc7Vx2d/HB395GNWofbMo91aT9q3HGq@9iaR427HjXuPDn9UROQuUPV5@GOeYFAts/heQ93LHq4c9GxTUDeoZ3HZqo83NUBYm59uGP@w51NPg93rgVSmv///4@ONtJRMNRRMAGTRrFcOtFA2hiMYAJAFRAEEoMKmIAFgKQxSMAYzIMYA9QSCwA "Jelly – Try It Online")**
### How?
```
ŒṪœịı*ÆiƊ+⁸ʋƬ⁺⁹ɗ€⁸%L... - Link: list, X
ŒṪ - truthy multi-dimensional indices -> [[1,1],[1,2],...,[h,w]]
€ - for each:
ɗ - last three links as a dyadic chain:
⁹ - use chain's right argument as right argument
Ƭ - collect up until no change occurs with:
ʋ - last four links as a dyadic chain:
œị - multi-dimensional index into X
Ɗ - last three links as a monadic chain:
ı - square root of -1
* - exponentiate
Æi - [real part, imaginary part] -> move deltas
⁸ - chain's left argument -> the current position
+ - add together -> the new position
⁺ - repeat the Ƭ-collection, use the entire result
L - length of X
% - modulo -> making all results have the same domain
```
```
...ḞQ€LÞḢṢƲ€¹ƙ$Ẉ€µḟṂLṭṂ) - ...continued
Ḟ - floor (we had a mix of ints and floats, but ƙ uses
Python's repr, this makes them all ints again)
Q€ - deduplicate each
$ - last two links as a monadic chain:
¹ƙ - group by:
€ - for each
Ʋ - last four links as a monadic chain:
Þ - sort by...
L - length
Ḣ - head
Ṣ - sorted
Ẉ€ - length of each of each
µ ) - for each:
Ṃ - minimum -> loop length
ḟ - filter discard (keeping only tributary lengths)
L - length -> number of tributaries
Ṃ - minimum -> loop length
ṭ - tack -> [loop length, number of tributaries]
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~250 247~~ 235 bytes
*Thanks Arnauld for pointing out that the grid is guaranteed to be square, saving 12 bytes!*
```
G=input()
n=len(G)
N={}
T={}
t=0
exec"j=t%n;i=t/n;A=[]\nwhile(i,j)not in A:A=[(i,j)]+A;d=G[i][j];i+=d/3-1;j+=d%3-1;i%=n;j%=n\nk=A.index((i,j))+1;x=min(A[:k]);N[x]=k;T[x]=T.get(x,[])+A[k:];t+=1;"*n*n
for x in N:print N[x],len(set(T[x]))
```
[Try it online!](https://tio.run/##NY8xb8MgEIV3/woUyRLENCm1qkhGNzB58@SNMNWkwU7PVkJUqqq/3QXSSqd3j497J1i@/HnGl3VtweFy95QVCBeLtGVFB98/RZ/Ew3Nhg33bjOBLlA78HqUCbY74eXYXSx0fGc6eOCSqiRcZmErJAVrtjB6NdBUM@/pJyDGaMhlXAsoxyhEnUDuHgw00J1klZIAPh1TpZjJMdjoYmGSfWr97t54Grg2rlJ4aI30FQm62uMXiNF9JSM/omuXq0JOU5OlDtxhKecbWVWvBySsnh6zCcKJjr3P9gzjxqMT@wCGDqHUCdT491ghjfgE "Python 2 – Try It Online")
Takes input as a 2D list from `STDIN`, where up, right, down, left are encoded as the integers `1, 5, 7, 3` respectively.
For each cell in the grid, the program follows the directions starting from that cell until a loop is found. The loop length is stored in the dictionary `N`, and the list of tributary cells is stored in the dictionary `T`. The keys for both dictionaries are the min indices of each loop.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 196 bytes if width=height
```
m=>m[Q='flatMap'](U=(y,I)=>y[Q]((x,j)=>U[T=[...m+0,Y=m.length,i=I][Q](_=>0+[j=(c=m[i][j]-2,j+Y-~c%2)%Y,i=(i+Y+c%2)%Y])[k=0,Q](S=c=>(S[c]=-~S[c])==2&&++k&&c).sort()]?(++U[T][0],[]):[U[T]=[1-k,k]]))
```
[Try it online!](https://tio.run/##PY4/a8NADMX3fIoscXScfJydrSB3ztAhpBmMEMVc7dT/Q2xKs@Sru3eYlsdD@gk9oab4LiZ3r29zPIyf5VLR0lPW84n2VVfMb8VtL3AheOBRUfbgkwD8YOP7C78TG2N6bTGn3nTlcJ2/sKajhK0PyqzmhsBRz7VwI3GKjc7jp9ulapf7Rah1rlcSxS1Z9LkzOcrgzE4ofoaiiNIo0rqNIqfMNN5nUPIKWvsHhK0gi3rhAMRJ3GIrotTixmEau9J04xUq4M12ywmmePBOBAOmaL3@McEgP/jDAwbbFS2u6UQ24fov "JavaScript (Node.js) – Try It Online")
# [JavaScript (Node.js)](https://nodejs.org), 205 bytes
```
m=>m[Q='flatMap'](U=(y,I)=>y[Q]((x,j)=>U[T=[...m+0,Y=m[W='length'],X=m[W],i=I][Q](_=>0+[j=(c=m[i][j]-2,j+Y-~c%2)%Y,i=(i+Y+c%2)%Y]).sort().filter(S=c=>(S[c]=-~S[c])==2)]?(++U[T][1],[]):[U[T]=[k=T[W],1-k]]))
```
[Try it online!](https://tio.run/##PY5Ni4NADIbv/RW9FDNMHNTeFuKee@ihtGVXQlhkql2tH0WlbC/96@4Mskt4SZ6QN0mdP/LRDtV9Crv@UswlzS2lLR8oKJt82uf3QOBM8MSdovTJBwH4wdrVZz4RG2NaHWFGLX9Q0BTddfoOBD89C1a0E@/4ojTSXBNY16@EawkTrHUWvuwmUZvMDUKlM72QKDP2wwTKlFUzFQMcyVIKR7ZC4csnRZQoeQet3RPCsSCLemMPxDc6@dtxeBNRarZ9N/ZNYZr@CiXwar3mGBPcOjmfxwQjF/8Yow/X@MMtekULRri4Y1n57b8 "JavaScript (Node.js) – Try It Online")
Ungolfed version
```
m=>m.flatMap(
U=(y,I)=>y.flatMap(
(x,j)=>
U[
T=[...m+0,Y=m.length,X=y.length,i=I].map(_=>(
c=m[i][j],c%2?(i=(i+Y-2+c)%Y):(j=(j+X-1+c)%X),
i*X+j
)).sort().filter((c,k,S)=>S[k-1]!=c&S[k+1]==c)
]?(++U[T][1],[]):[U[T]=[k=T.length,1-k]]
)
)
```
[Try it online!](https://tio.run/##TY9Na8MwDIbv/RXeoUOaFROnt4LScw87pYUUY0Zwk875aEobxvrrM2f9oAjB@7zoFVJd/BQXd/anITr2@3KseOw47VTVFsNncYKZEFuGK62R0@urKwT8Uh3cfx2mzF0IsWGjlOpkTDvuVFseD8M35Xx9SM9rq7qw5otTeKaEcNwZb01tyc2TFXgGL3dRIh3Od7iEmqGWeaQnzpFegv4jl/WTEdWlPw@AqvLtUJ4BHDWUhVMzk1ETafvG7j0zjdSW2eE9aFcg5dZsrNGWjMWlmYBNw5vH4TpqrA3jOMPR9cdL35aq7Q9QwfS80ZTQInTIT5hQHOqJmqYKxgMXNHV8w5huaW1nFnH8Aw "JavaScript (Node.js) – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 78 bytes
```
[:(#~1<{."1)@((=([,-~)&(+/)0=|)"{~~.)@,](]*.[{"p..0|:((,-)=0 1)|.])^:_ p:@i.@$
```
[Try it online!](https://tio.run/##hY@xCsIwFEX3fMWjFpOn6TPVLVoICk7i4FpiB2uxErAUMpSW/nosODiJwz3LgQP3GSLiFWQaOEhQoKclBIfL6RhyLWZjuuspStEIkYlcJiPOxXKFKhsw6seR0Egr7ILyPmqI1KCFkAlmClIcyOJVF9BoU5OJw3lPsAHNv9FfTdn9TdYUd5whY/fb4wUV8LL1jkNNkG@pWIO1nzPMt5NhrXMTvfeuZb70pWNuEp5heAM "J – Try It Online")
### How it works
We map each index to the corresponding prime `p:@i.@$`:
```
2 3 5 7 11
13 17 19 23 29
31 37 41 43 47
53 59 61 67 71
73 79 83 89 97
```
Then shift this board by the 4 directions `((,-)=0 1)|.])`, and calculate the least common multiple between the tile `x` and the direction `x` is heading `]*.[{"p..0|:`. We do this until the board does not change anymore `(…)^:_`:
```
461677248802 62985 20995 3162172937 3162172937
221 221 4199 2109169348979 91703015173
6851 8177 172159 7402837 321997
363103 4661 10501699 3162172937 3162172937
230838624401 4661 262460353771 3162172937 3162172937
```
For each unique `~.` number we can then count how often it occures and how many other tiles it divides: `= …&(1#.,) 0=|`. We need the first number and the difference for the result: `([,-~)`:
```
…
6 5
2 10
1 5
…
2 0
1 0
```
We then take only the ones where the first column is greater than 1 `(#~1<{."1)`:
```
6 5
2 10
2 0
```
[Answer]
# [R](https://cran.r-project.org/) ~~435 414 395~~ 390 bytes
Entering the excursion map as a matrix, e.g.
```
n=3;M=matrix(sample(1:4,n^2,rep=T),n)
```
where 1,2,3,4 stand for `down`, `up`, `right`, and `left`, the following heavy-going code produces rows of lengths and tributaries for the different loops
```
j=cbind;l=sum;a=apply
m=l(!!M);n=m^.5
g=function(A,r=M[A])A+c((r<2)*(1-n*(A[,1]==n))-(r==2)*(1-n*(A[,1]<2)),(r==3)*(1-n*(A[,2]==n))-(r>3)*(1-n*(A[,2]<2)))
I=c()
for(i in d<-1:n)I=rbind(I,j(i*d/d,d))
for(t in b<-1:m)I=g(I)
p=function(i)i[,1]+n*i[,2]-n-1
K=matrix(0,m,m)
for(t in b)K[b+m*p(I<-g(I))]=1
s=o=a(u<-unique(K),1,l)
for(k in 1:l(!!s))s[k]=l(!a(!!sweep(K,2,u[k,],'-'),1,l))
j(o,s-o)
```
[Try it online!](https://tio.run/##VZDNboNADITv@xTJKTbxtt2kvQRciSNC3HpDRCJAok3YhS6gtk9Ps4r6k6NH39jjcbPlbZixKUenP2EoTd82oHbPZPcbck3Pb0gWRe@0HSHD@czVQds6bHmYTFhy2fftlzDcwnKZYWjZ7B9exImPk61G3VmIyXGWxwXG6wrARRsMQEkbQJyTKpgtogTHfK9fMSQvb//Jm1/89V72NIqEK0Bx7BzohbaLOpJqZzFh5wNDQmfQQf1YU403avTUwVPmSp0gub75l1uj9kHWNtD@hLRSifSnpycyZP5vwTQ/rE3QQxJJvwkLVmLgjkuYIjlZ/T41kCIpam@2i7epna9tQBzyS@ErLP340TQ9pLShKb9QQSu5uvlQnKGjQXYo5ll8Aw "R – Try It Online")
Some comments
```
m=l(!!M);n=m^.5 #m=n^2
#moving all points in the square by the corresponding moves in M
g=function(A,r=M[A])A+cbind((r<2)*(1-n*(A[,1]==n))-(r==2)*(1-n*(A[,1]<2)),(r==3)*(1-n*(A[,2]==n))-(r>3)*(1-n*(A[,2]<2)))
#matrix of the (i,j) coordinates for all points in the square
I=c()#NULL
for(i in 1:n)I=rbind(I,cbind(rep(i,n),1:n))
#move long enough to remove transient points
for(t in b<-1:m)I=g(I)
#turns 2D coordinates into a single integer
p=function(i)i[,1]+n*i[,2]-n-1
K=matrix(0,m,m) #matrix of visited coordinates
for(t in b)K[b+m*p(I<-g(I))]=1
#loop length (o) and associated number of transients (s)
s=o=apply(u<-unique(K),1,sum)
#sum over all loops (length(o))
for(k in 1:sum(!!s))s[k]=sum(!a(!!sweep(K,2,u[k,],'-'),1,sum))
cbind(o,s-o)
```
Now, I spent too much time on this code already but I fear the parts
```
I=c()
for(i in 1:n)I=rbind(I,cbind(rep(i,n),1:n))
```
creating the matrix of all starting coordinates and
```
p=function(i)i[,1]+n*i[,2]-n-1
```
switching from the coordinates to a single index could be further code-golfed!
[Answer]
# [Scala](https://www.scala-lang.org/), 415 bytes
415 bytes, maybe more. It can be golfed much more.
Port of [@Kevin Cruijssen' Java 10 answer](https://codegolf.stackexchange.com/a/204701/110802) in Scala.
---
Golfed version. [Try it online!](https://tio.run/##jVJRT9swEH7PrzhFBdklMWn6VtVIaC9jYhui2xNiyHMMDXOc4rhBNMpvL7YTSlpNG5Fj@e6@7zvfnSvOJNvmxarUBh5Zzcja5JI0n1m1XAgTwQ8thD/YrQ16YOVYhJdSCm7yUpEvlvmpVLXQRuiK3AX2K38/2ih8ZbmCJggAjGa5gW/WAPtl4h44KmZwrjV7uen2C2Vub/EMfqrcWFTraDWToGaWR0GJ54/zLb7ZOvIldby@ohv3exjCgYtKWhAp1INZevOayrEM7kuN8nmcwFrZdsA1bmqmQdP8VAbuxGl@JD1@4cX7Lnlhq5uVzYKwLEN6LE94lyejBdIYWUtTpGOUxdnRdJzh0/REYivGKeIxyu9RNk/xJE7HGQhZCUiwj7fPy1wKNJTFgUVr6i51fMypuxLu4vEEe25vpTi49KcFbn1pm3lsHdXCjRE3VmVDtCjKWjhmVyuniYc@HUKfdtAU9w5eKmOnXJ1LiTYY8xM6CZ7eUrdtsNK5MlKhKhw1G1LlG9FGIx7a0NZNsn2btBtpYYUQ0w/V22AXxrIfhkP14zeiMsgj@n0awSSC1O9THHVsZI3Erz2vxXbLBYbe1Hvtnuy8iXd10lNsm/7X7C4@FEr@iTwED/N1N047/q4tXuY/j93ne@/1hVqtzQxGTUEKtkJ3pPjT9RKFUYjxwOwShxH0C9vRhHhPLrzSwpiX2Nsim8Eu7txXzouKA8r3tfE36KGK8EPIXol7Uh@o1L5OQBrmMRS4d70ra19zDfQMwvlZ/SskfMn0uUH1oPLuMt3za4PtKw)
```
val L=new HashSet[Set[Int]]()
val l=m.length
val R=l*l
for(i<-0 until R){var r=i/l
var c=i%l
val S=new TreeSet[Int]()
do{S.add(r*l+c)
val d=m(r)(c)
r=(r-(d-d%3*d)/2+l)%l
c=(c-(if(d<2)1-2*d else 0)+l)%l}while(S.add(r*l+c))
if(r==i/l&&c==i%l)S.add(-1)else S.add(-2)
L.add(S)}
for(z<-L.asScala){if(z.remove(-1)){var c=0
for(q<-L.asScala){if(q.remove(-2)){if(q.containsAll(z))c+=1
q.add(-2)}}
println(s"${z.size},$c")}}
```
Ungolfed version. [Try it online!](https://tio.run/##jVRdb5swFH3nV1yhrrJXwgh5i9pK1V7WqduqZnuquoqBk9AZkxqHqon47dn1BwSSbWpETHzuOcf3Xtup0oQnu11erEqp4Cmpk3Ctch5uPyXVcsZUAN8lY@YHDo3niJWWhWnJOUtVXorwMyo/lqJmUjFZhY@eV/56whh8SXIBW88DUDLJFXzFCeAnY3NISTGFKymT13s7Xgv18ECn8EPkClmNltUJBzFF3QUI9vJ2PfIt01rcOL2r615/DZ3QHosjqwg5Ewu17MF3CHN4D9xh7jUvJZAczkcQwVpg2@COdotqpQSJyhw@dEqLpgZ9N0A5zFyKruMmvS47rLjseQPMwiTLiNRZwRmktBfSZpmuhEhKBhGdDmpGQDIcMkxhggYZxQxjdOF0kBSYREmq@flca84hpjDGeaxlwHjFIKLHygZeljlnQA6z3CejDTEd1x44PdWLubZQV91oTO0abhrv5TcGmbWAOSrdnmz0niCjmulz2t8TveomlKwoa6bt6aCn7d5EPcwYPv/TsDV97kxjehhvGWkpFF6H6opzskFWCmcXMD6gPh@Vauv7@@@VzIXiglT@yXYTVvmGNcFJ6u/Fjdd/N@2t0tenwFxIIhdVe4lmCt0WRxdIsUoRw3DjJIBxALEZJzSwaoKTyDwDFLn20YE@GhsUx6hDIwNZ6wl1Z@VodR3vG0X/ZR6S@@vZjGOr79pibN7yx7Lv/bVYrdUUTrZFWCQr8hgWv20viR/4lPamdmE/APdQnzZut1o7/1YypV5HZs6yKXRxDd9qlBQHkm9rZTJwVBGmh5RBiQOrN1Rq7oDUd6DYn@3WWZqaa7i4BP/8sv7ph@kykVeK1L3Kae/4Nd5u9wc)
```
import java.util.{HashSet, TreeSet, Set}
import scala.collection.JavaConverters._
object Main {
trait N {
def c(m: Array[Array[Int]]): Unit
}
val n: N = new N {
def c(m: Array[Array[Int]]): Unit = {
val L = new HashSet[Set[Int]]()
val l = m.length
val R = l * l
for (i <- 0 until R) {
var r = i / l
var c = i % l
val S = new TreeSet[Int]()
do {
S.add(r * l + c)
val d = m(r)(c)
r = (r - (d - d % 3 * d) / 2 + l) % l
c = (c - (if (d < 2) 1 - 2 * d else 0) + l) % l
} while (S.add(r * l + c))
if (r == i / l && c == i % l) S.add(-1) else S.add(-2)
L.add(S)
}
for (z <- L.asScala) {
if (z.remove(-1)) {
var c = 0
for (q <- L.asScala) {
if (q.remove(-2)) {
if (q.containsAll(z)) c += 1
q.add(-2)
}
}
println(s"${z.size},$c")
}
}
}
}
def main(args: Array[String]): Unit = {
test(Array(Array(3, 1, 2, 1, 3), Array(1, 0, 0, 1, 3), Array(3, 3, 3, 0, 1), Array(3, 2, 3, 2, 0), Array(0, 3, 1, 2, 3)))
test(Array(Array(1, 2), Array(3, 0)))
test(Array(Array(1, 2, 2), Array(3, 0, 0), Array(1, 0, 2)))
}
def test(m: Array[Array[Int]]): Unit = {
println(s"Input: ${m.map(_.mkString(",")).mkString("Array(", ", ", ")")}")
println("Pretty-printed: ")
prettyPrint(m)
println("Output: ")
n.c(m)
println()
}
def prettyPrint(m: Array[Array[Int]]): Unit = {
for (r <- m) {
println(r.map(v => "<>v^".charAt(v)).mkString)
}
}
}
```
] |
[Question]
[
As a follow up to [Shortest terminating program whose output size exceeds Graham's number](https://codegolf.stackexchange.com/questions/6430/shortest-terminating-program-whose-output-size-exceeds-grahams-number) and [Golf a number bigger than TREE(3)](https://codegolf.stackexchange.com/questions/139355/golf-a-number-bigger-than-tree3), I present a new challenge.
Loader's number is a very large number, that is kind of hard to explain (since it was itself the result of a code golfing exercise with a flexible goal). There is a definition and explanation [here](http://googology.wikia.com/wiki/Loader%27s_number), but for the purposes of self-containment, I will attempt to explain it later in this post as well.
The algorithm Ralph Loader used produces one of the largest numbers of any (computable) algorithm ever written! Indeed, Loader's number is the largest "computable" number on the Googology Wiki. (By "computable" number, they mean a number defined in terms of a computation.) That means that if answer produces a number larger than Loader's number in an interesting way (i.e. not just Loader's number+1), **you could go down in Googology history!** That being said, programs that produce something like [Loader's number+1](http://googology.wikia.com/wiki/Naive_extension) are definitely valid answers and contenders to this question; just don't expect any fame.
Your job is to create a terminating program that produces a number *larger* than Loader's number. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest program wins!
* You aren't allowed to take input.
* Your program must eventually terminate deterministically but you can assume the machine has infinite memory.
* You may assume your language's number type can hold **any finite value** but need to explain how this exactly works in your language (ex: does a float have infinite precision?)
+ Infinities are not allowed as output.
+ Underflow of a number type throws an exception. It does not wrap around.
* You need to provide an explanation of why your number is so big and an ungolfed version of your code to check if your solution is valid (since there is no computer with enough memory to store Loader's number).
---
So here is an explanation of Loader's number. See <http://googology.wikia.com/wiki/Loader%27s_number> and the links therein for more precise details. In particular, it contains a program that produces Loader's number exactly (by definition).
The [calculus of constructions](https://en.wikipedia.org/wiki/Calculus_of_constructions) is essentially a programming language with very particular properties.
First of all, every syntactically valid program terminates. There are no infinite loops. This will be very useful, because it means that if we run an arbitrary calculus of constructions program, our program will not get stuck. The problem is that this implies the calculus of constructions is not Turing complete.
Second of all, among non-Turing complete languages, it is one of the most powerful. Essentially, if you can prove that a Turing machine will halt on every input, you can program a function in the calculus of constructions that will simulate it. (This does not make it turing complete, because there are halting turing machines that you can not prove are halting.)
Loader's number is essentially a busy beaver number for the calculus of constructions, which is possible to compute since all coc programs terminate.
In particular, loader.c defines a function called `D`. Approximately, `D(x)` iterates over all bit-strings less than `x`, interprets them as a coc programs, runs the syntactically valid ones, and concatenates the results (which will also be bitstrings). It returns this concatenation.
Loader's number is `D(D(D(D(D(99)))))`.
A more readable copy of the code from the googolology wiki
```
int r, a;
P(y,x){return y- ~y<<x;}
Z(x){return r = x % 2 ? 0 : 1 + Z (x / 2 );}
L(x){return x/2 >> Z(x);}
S(v,y,c,t){
int f = L(t);
int x = r;
return f-2 ? f>2 ? f-v ? t-(f>v)*c : y : P(f,P(S(v,y,c,L(x)), S(v+2,t=S(4,13,-4,y),c,Z(x)))) : A(S(v,y,c,L(x)),S(v,y,c,Z(x)));
}
A(y,x){return L(y)-1 ? 5<<P(y,x) : S(4,x,4,Z(r));}
D(x)
{
int f;
int d;
int c=0;
int t=7;
int u=14;
while(x&&D(x-1),(x/=2)%2&&(1)){
d = L(L(D(x))),
f = L(r),
x = L(r),
c - r||(L(u)||L(r)-f||(x/=2)%2&&(u=S(4,d,4, r),t=A(t,d)),f/2&(x/=2)%2&&(c=P(d,c),t=S(4,13,-4,t),u=S(4,13,-4,u))),
c&&(x/=2)%2&&(t=P(~u&2|(x/=2)%2&&(u=1<<P(L(c),u)),P(L(c),t)),c=r)
u/2&(x/=2)%2&&(c=P(t,c),u=S(4,13,-4,t),t=9);
}
return a = P( P( t, P( u, P( x, c)) ),a);
}
main(){return D(D(D(D(D(99)))));}
```
[Answer]
# JavaScript, D6(9) (~~508~~ ~~501~~ ~~495~~ ~~492~~ ~~487~~ ~~485~~ ~~481~~ ~~478~~ ~~456~~ 452 bytes)
```
_='P6x-~x<<c,Z6r=x&1?0:1+Z@/2.L6x/2>>[[email protected]](/cdn-cgi/l/email-protection)=;t,f=Ft.x=rKf-2?f>2?f-v?t-(f>v)*c:y:Cf,CH(v+2E,#y.Z@BB:A(H;[[email protected]](/cdn-cgi/l/email-protection)@)-1?5<<PM):GE,Z(rND=M=0,O7,Q14K_=@&&D@-1.!1B?([[email protected]](/cdn-cgi/l/email-protection)=Fr.x=Fr.c-r||(Fu)||Fr)-f||!QG,d,r.OA(t,dNfIdE.O#t.Q#uB.c&&!OC~u&2|!Q1<<CFc.uNCFc.tNc=r.uItE.Q#t.O9.DM,t,uB:CCt,Cu,PMB._.JJJ9BBB!@>>=1)%2&&(#G-8,13,N)..),6=MK;(vE,y,HS;L@NS@(xB))I/2&!c=CCP(M@EE,cFL(GS(4,4JD(D(K)=>Ot=Qu=';for($ of'QOKJGFEMCIB@H;6.N#!')with(_.split($))_=join(pop());eval(_)
```
This is an encoded code.
```
_='P6x-~x<<c,Z6r=x&1?0:1+Z@/2.L6x/2>>[[email protected]](/cdn-cgi/l/email-protection)=;t,f=Ft.x=rKf-2?f>2?f-v?t-(f>v)*c:y:Cf,CH(v+2E,#y.Z@BB:A(H;[[email protected]](/cdn-cgi/l/email-protection)@)-1?5<<PM):GE,Z(rND=M=0,O7,Q14K_=@&&D@-1.!1B?([[email protected]](/cdn-cgi/l/email-protection)=Fr.x=Fr.c-r||(Fu)||Fr)-f||!QG,d,r.OA(t,dNfIdE.O#t.Q#uB.c&&!OC~u&2|!Q1<<CFc.uNCFc.tNc=r.uItE.Q#t.O9.DM,t,uB:CCt,Cu,PMB._.JJJ9BBB!@>>=1)%2&&(#G-8,13,N)..),6=MK;(vE,y,HS;L@NS@(xB))I/2&!c=CCP(M@EE,cFL(GS(4,4JD(D(K)=>Ot=Qu='; //encoded code
for($ of'QOKJGFEMCIB@H;6.N#!')with(_.split($))_=join(pop()); //decoding
eval(_) //Evaluation of the string
```
Decoded code:
```
P=(x,c)=>x-~x<<c,Z=(x,c)=>r=x&1?0:1+Z(x/2),L=(x,c)=>x/2>>Z(x),S=(v,c,y,t,f=L(t),x=r)=>f-2?f>2?f-v?t-(f>v)*c:y:P(f,P(S(v,c,y,L(x)),S(v+2,c,S(4,4-8,13,y),Z(x)))):A(S(v,c,y,L(x)),S(v,c,y,Z(x))),A=(x,c)=>L(x)-1?5<<P(x,c):S(4,4,c,Z(r)),D=(x,c=0,t=7,u=14)=>_=(x&&D(x-1),(x>>=1)%2&&(1))?(d=L(L(D(x))),f=L(r),x=L(r),c-r||(L(u)||L(r)-f||(x>>=1)%2&&(u=S(4,4,d,r),t=A(t,d)),f/2&(x>>=1)%2&&(c=P(d,c),t=S(4,4-8,13,t),u=S(4,4-8,13,u))),c&&(x>>=1)%2&&(t=P(~u&2|(x>>=1)%2&&(u=1<<P(L(c),u)),P(L(c),t)),c=r),u/2&(x>>=1)%2&&(c=P(t,c),u=S(4,4-8,13,t),t=9),D(x,c,t,u)):P(P(t,P(u,P(x,c))),_),D(D(D(D(D(D(9))))))
// We also have _ equal to the code itself.
```
The logic is the same as the original loader.c, but few non-critical modifications are made to compress the code better.
In this, it is assumed to be:
* Infinite call stack
* Infinite memory
* Infinite precision `Number`
* Infinite magnitude `Number`
* Bitshift and bitwise operators work on infinite bit integers instead of 53 bits. Bitwise negation still negates the sign bit.
## Encoding/Decoding algorithm:
The encoding is done as follows:
* Take a repeated string, call it S.
* Replace all S in the code to a key K.
* Put K and S at the end.
* Make a list of keys, and also put decoding algorithm so the code actually runs.
The decoding algorithm:
* Take list of keys.
* Take the earliest key K.
* Split the string for each K.
* Since last of the array is what to replace K S, pop it, and replace all K by joining the array with the popped value S.
The compression was done with [this code](https://naruyoko.github.io/tests/compression/JavaScript/).
(d=String.fromCharCode)((c=a.charCodeAt())>>8)+d(c&255)).join``.slice(1))
```
This code will take the 16bit string as a, converts it to 8bit string with same binary(BE), and `eval` it.
The decoded code is the encoded code above. -->
## Proof that D6(9)>D5(99)
For this, we would compare D(0) and 99. We find that D(0) is equal to `8646911284551352321` (note that in a normal environment without modifications we won't get a correct result because the higher bits are truncated). So, D(0)>99, and since D is strictly increasing, D6(9)>D6(0)>D5(99).
* 508B->501B, -7B
+ -1B for... I don't know why. I did change `D(D(D(D(D(99)))))` to `D(D(D(D(D(D(9))))))`. Also that shuffled the letters.
+ -6B for re-adding `&&(1)` for `D(x)`'s loop condition.
* 501B->495B, -6B
+ Fixed most `/2`s to `>>1`s because `Number`
+ 6 bytes saved from somewhere
+ You can see my attempt in this update [here](https://docs.google.com/spreadsheets/d/12xhVzRC3lwkmzdWItbySeQoFEkxf2NL7-5aXeDkI7YI/edit?usp=drivesdk)
* 495->492B, -3B
+ By changing the decoder from `for...in` to `for...of`.
* 492->487B, -5B
+ Removing unnecessary assignments
+ Changing argument names
* 487->485B, -2B
+ 1 byte from using `eval` for `D`, removing `return`.
+ 1 byte compression combining the closing parentheses to a comma.
* 485->481B, -4B
+ By compressing different substrings.
* 481->478B, -3B
+ Removed unnecessary variable assignment.
* 478->456B, -22B
+ You can find me posting updates at *Googology Server!* (Discord).
+ 2 bytes from changing from D6(9) to D6(0).
+ 1 byte from making `D` recursive instead of using a loop.
+ 7 bytes from making `f` and `d` in `D` global and not declaring them. It works since they are reassigned every time going through the loop, and `D` is not called between the assignment and the next iteration.
+ 2 bytes from removing assignment to `r`. They will be assigned before use.
+ 1 byte from removing an unnecessary assignment corresponding [here](https://github.com/rcls/busy/blob/82d729e4f9d251ffd568d6db5c60a75d09f8c260/pure.c#L34) in the original code. It no longer saved bytes.
+ 1 byte from fixing a typo. I still don't know how it appeared.
+ 2 bytes from swapping the second and the third variable of `S`. I checked and it should work fine.
+ 1 byte from changing instances of `S(4,-4,13,` to `S(4,4-8,13,`.
+ 2 bytes from adding unused variables `y` to `Z` and `L`.
+ 1 byte from changing `Z`.
+ 2 bytes from reusing `_` as the accumulator. It starts out as a `String` containing the decoded code, and in such a case, it acts as `0` in bitwise operators. Also changed back to D6(9) for good measure.
* 456->452B -4B
+ Changed the 1-argument and 2-arguments functions' argument names to `(x,c)`.
[Answer]
# Python, q^15(2) = q^13(5), 319 bytes
This is my first time submitting a program to code golf, but certainly not my first time implementing or inventing a large number. I probably won't go down in googology history for this. Anyway, here is my program, the explanation comes later:
```
_="78b/:!if b==1:&(a+1)%c!9&s(8b-1/,s(81///\n7f(a):!m=[]*True:!#for x in range(65536):!##if a(x)==a(x+k): break!##9 pass'p = 4x:f(4y:s(1,y,x))\n7q(a):*p(k)<2^a:'k = $$$$$2...!\n## $q(q(q('!#k+=1!&k\n&return *!k=0!while .)))))/,c)4lambda 7def 8s(a,9else:"
for Y in"9874/.*&'$#!":_=_.split(Y);_=_.pop().join(_)
exec(_)
```
I compressed this code using the same tool which Naruyoko used, [here](https://naruyoko.github.io/tests/compression/Python%203/). Here is the uncompressed form:
```
def s(a,b,c):
if b==1:return (a+1)%c
else:return s(s(a,b-1,c),s(s(a,1,c),c),c)
def f(a):
m=[]
k=0
while True:
for x in range(65536):
if a(x)==a(x+k): break
else: pass
k+=1
return k
p = lambda x:f(lambda y:s(1,y,x))
def q(a):
k=0
while p(k)<2^a:
k+=1
return k
k = q(q(q(q(q(q(q(q(q(q(q(q(q(q(q(2)))))))))))))))
```
## Explanation
I had a hard time choosing what to use. I was originally planning to implement my LINEAR(k) function, which I might do another time, but I didn't know if it would produce large enough numbers, and it would be hard to implement, so my next choice was greedy clique sequences, but those didn't work either, so I just ended up using Laver tables.
So, how do Laver tables work? Well the size-n Laver table is a binary operator ab, with the following rules: a0=0, a1=a+1 mod n and ab=(a(b-1))(a1) for b>1. p(n) is defined as the period of the function 1a, which is quite slow-growing.
The first few values of p(n) are 1,1,2,4,4,8,8,8,8,16,16,16,16,... Then q(n) is the least integer so that p(q(n)) is greater than or equal to 2^n. This is very fast-growing, and its totality can only be proven in ZFC+I3, so one could approximate it to f\_PTO(ZFC+I3)(n) in FGH, although this doesn't work since there is no system of fundamental sequences associated to PTO(ZFC+I3).
The first few values of q(n) are 0,2,3,5,9. q(5) is approximated to Ack(9,Ack(8,Ack(8,255))) using the Ackermann function, and q(6) is believed to be greater than Graham's number!
So, now that we know how Laver tables work, how does my code work? Well, s(a,b,c) denotes the operator ab where n=c, then the function f(a) uses complex while loops to find the period of the given function a.
p is represented by the lambda which returns `f(lambda y:s(1,y,x))`, i.e. the period of `s(1,y,x)` where x is the input to p. q then just uses for loops to find the least integer k s.t. p(k) => 2^a.
My code then returns q^13(5), which has been proven to be greater than f\_w(f\_w+1(5)); note that this was for q^13(1) but q is strictly increasing so this also acts as a lower bound for q^13(5). This lower bound however is a severe understatement, since, as I mentioned earlier, q(n) cannot be proven total in ZFC while f\_w(f\_w+1(5)) can be by FAR.
Similarly, this code should return a number greater than Loader's number since, although sadly there is no proof, Loader's function is commonly believed to be provably total in ZFC; I do note however that just because a function which is provably total in a stronger theory doesn't mean that it will eventually dominate the one provably total in the weaker theory. It is usually the case though. So, all said, I WIN!!!
Edit: I lose because the code is completely broken and I can't fix it...
[Answer]
# Python, q15(2), 192 bytes
```
def q(k,c=0,n=0):
while c*2<1<<k:
n+=1;*x,=map(s:=lambda b,a=1:s(a,s(b-1,a))if a*b else(a-~b)%c,range(c:=1<<n))
while x[:c]==x[-c:]:x=x[:c];c>>=1
return n
print(eval(15*'q('+'2'+')'*15))
```
See [Binary198's answer](/a/237490) for the definition of q and an argument that q15(2) is large enough. If the argument is correct, then this is an impressively concise way to beat Loader's number. Unfortunately their implementation is broken.
This is my attempt at reasonably well golfed code that, I think, actually works. At least, it correctly computes values of q up to q(3)=5. (If you want to test that, you should wrap the definition of `s` in `functools.lru_cache(None)(...)`.) Computing q(4)=9 may be possible, but will need a lot of stack space.
s(b,a) computes row a, column b+1 of the Laver table of size c, using 0...c-1 as the representatives of Z/cZ instead of the usual (for these tables) 1...c. The period-finding code uses the fact that the period can only be a power of 2. Other than that, there are only standard golfing tricks here.
I deliberately computed the same value as Binary198's answer, though it could be made larger at no cost, because I'm not trying to compete on size; I just wanted a working implementation of this interesting function (for some definition of "working").
[Answer]
# Python, 498 bytes, ???
I don't know how large this program would get.
Okay, I've had a few failed attempts on this, but I think I've got it this time. First, the code:
```
from itertools import product as X
C=[1,0]
V=[9]
r=range
L=list
def R(n):
C[0]=1
while C[0]:
C[0]=0
for m in r(V[0]):P(m,n)
if(C[0]<1)+(C[1]<len(V)):P(C[1],n,1)
return sum(V)
def P(m,n,B=0,T=0):
if m==len(V):V.append(0)
k=m+n;c=r(k)
for M in X(*[L(X(*[L(X(c,c,[-1,0,1]))]*k))]*k):
t={};u=p=s=d=1
while d:
s,c,d=M[s][t.get(p,0)];t[p]=c;p+=d;u+=1
if u>sum(V):u=d=0
T+=u
if T>V[m]:C[0]=V[m]=T;C[1]=min(C[1],m+1)
if B>C[0]:V[m]+=1;P(m,n,1)
z=9**9
exec("z=R(z);"*R(z))
print(z)
```
# Explanation:
This function simulates all Turing machines with n states and n colours for a number of steps (initially 9), then sums the number of steps that it took for any machine that halted to halt, storing that value as the number of steps to take on the next iteration. It keeps doing this until it reaches a steady state.
We don't just look at machines that have n states and colours, but also n+1, n+2, up to n+V[0], where V[0] is the sum of the halting times for the machines with n states and colours.
So far, I've just described a function which is polynomial at best. Notably, it grows slower than the busy beaver function on these Turing machines. Thus, we can be confident that there is at least one machine of size n which halts but we have not yet found. So we search for that one (this function is undefined on inputs which are too small).
Once we find it, we continue on as we were. We'll reach another steady state. This time, we can't be confident that there is another halting Turing machine of size n, but as BB(n+1)>F(BB(n)) for any reasonable polynomial function F (which this is), we can be confident that there is a halting Turing machine of size n+1 which we have not found. If we then find a halting machine of size n, we know that we can perform this step on n+1 again.
We repeat this process until we've attempted this on every size of machine we're looking at (from n to n+V[0]), and thus can no longer be confident that there is a machine that halts of those sizes that we have not seen.
While this number is certainly less than BB(n), I'm not sure how one would go about determining just how big it is. The guarantee that it halts is basically "BB(n) grows much faster than this does". I'm fairly confident that's a safe assumption for values of `R(n)` greater than, say, `R(5)`.
Here's a less golfed version with comments:
```
from itertools import product as X
# C[0] is 1 or 0 representing a change, so keep looping
# C[1] is the next machine that needs to search.
C=[1,0]
# V[x] is the total steps taken by the machine with n+x colours and states
V=[9]
def R(n):
while C[0]:
C[0]=0
# Run each set of machines sum(V) steps.
for m in range(V[0]):P(m,n)
# Run machine set C[1] sum(V) steps, then run it until one more machine stops.
if C[0]<1 and C[1]<len(V):P(C[1],n,1)
return sum(V)
# Run one set of machines with m+n colours and states.
def P(m,n,B=0):
if m==len(V):V.append(0)
# Start our total at 0
T=0
# For each machine in the set...
for M in G(m+n):
# Step count u starts at 0
# The tape t starts empty
# Position p starts at 1
# State s starts at 1
# Direction d starts at 1. These are all 1 because it's shorter and we use d=0 as break
t={};u=p=s=d=1
while d:
s,c,d=M[s][t.get(p,0)];t[p]=c;p+=d;u+=1
if u>sum(V):u=d=0
T+=u
# If the total is greater than the last time we ran this set, increase it and note there's been a change
if T>V[m]:
C[0]=V[m]=T
if m<C[1]:C[1]=m+1
# If we're running it until there's a change, increment V[m] and try again.
if B>C[0]:V[m]+=1;P(m,n,1)
# Generate all the machines of appropriate size.
def G(k):
L=list
# List of colours
c=range(k)
# List of options for a single state/colour combination - new state, colour written, direction moved (0 being halt)
O=L(X(c,c,[-1,0,1]))
# List of options for one state
S=L(X(*[O]*k))
# List of options for all states
return L(X(*[S]*k))
r=9**9
for i in range(R(r)):
# Reset C[0], as we need to be able to run again. C[1] will get reset in P().
C[0]=1;r=R(r)
print(r)
```
Actually, it occurs to me that there's no reason why (in principle) we can know that `R(n) < BB(n)` (when `BB(n)` is defined to be on Turing machines with n colours and states). Determining exactly how big `R(n)` is is related to a limited version of the halting problem, as it isn't guaranteed that $$BB(n)\*2^{n\*2^{3n^2}}<BB(n+1)$$ That's the limit on how quickly `R(n)` grows without the "look for the next terminating machine" step. I think it's a pretty safe assumption, though, that it's true with `n>5` or so.
while we can know that `R(n)` halts on big enough inputs, it's certainly possible that the result is in every case larger than `BB(n)`. Proving such (if true) would be equivalent to the halting problem, of course.
[Answer]
# Ruby, D6(9) (~~553~~ ~~544~~ ~~535~~ ~~516~~ ~~511~~ 507 bytes)
```
_='a=r=0;P"x-~x<<y};Z"r=x%2B1?0M1+J/2FL"x/2>>JFS=->vEt{f=L(t);x=r;fB2?A*EJ6Mf>2?fBv ?yMf>v ?t-cMtM@f,P*+2,#y8c,J6FA"Cx]B1?Ky,4,Z[r]]M5<<@x,yFD"f=d=c=0;t=7;O14;while[xIHx-18.>0][1];d=CCHx6;f=N;x=N;cBr&&[Cu]B0&&NBf&&.I[OKd,4,rQA[t,d]8fGd,cQ#t8O#u6;cI.&&[t=@~u&2|.I(O1<<@Cc8u]),@Cc8t]8c=r];uGt,c8O#tQ9];end;a=@@t,@u,@x,c6,aF$><<HHHHHH966"=->x,y=0{#K13,-4,*[S[vECx]8S[v.(x/=2)%26]]]8],@P[B==CL[E,y,c,F]};G/2&.I[c=@HD[IB0||JZ[xKS[4,M: NCr]Ou=Q8t=';'QONMKJIHGFECB@86.*#"'.each_char{|y|*_,y=_.split y;_=_*y};eval _
```
This is an encoded code. Extracted:
```
a=r=0;P=->x,y=0{x-~x<<y};Z=->x,y=0{r=x%2==1?0: 1+Z[x/2]};L=->x,y=0{x/2>>Z[x]};S=->v,y,c,t{f=L(t);x=r;f==2?A[S[v,y,c,L[x]],S[v,y,c,Z[x]]]: f>2?f==v ?y: f>v ?t-c: t: P[f,P[S[v,y,c,L[x]],S[v+2,S[4,13,-4,y],c,Z[x]]]]};A=->x,y=0{L[x]==1?S[4,y,4,Z[r]]: 5<<P[x,y]};D=->x,y=0{f=d=c=0;t=7;u=14;while[x==0||D[x-1],(x/=2)%2>0][1];d=L[L[D[x]]];f=L[r];x=L[r];c==r&&[L[u]==0&&L[r]==f&&(x/=2)%2==0||[u=S[4,d,4,r],t=A[t,d]],f/2&(x/=2)%2==0||[c=P[d,c],t=S[4,13,-4,t],u=S[4,13,-4,u]]];c==0||(x/=2)%2&&[t=P[~u&2|(x/=2)%2==0||(u=1<<P[L[c],u]),P[L[c],t]],c=r];u/2&(x/=2)%2==0||[c=P[t,c],u=S[4,13,-4,t],t=9];end;a=P[P[t,P[u,P[x,c]]],a]};$><<D[D[D[D[D[D[9]]]]]]
```
This code is Loader's Number with D6(9) instead.
In this, it is assumed to be:
* Infinite call stack
* Infinite memory
This is basically a port of my [JavaScript answer](https://codegolf.stackexchange.com/a/184808/) and [Python 3 answer](https://codegolf.stackexchange.com/a/197173/). For more details, check those.
The compression was done with [this](https://naruyoko.github.io/tests/compression/Ruby/).
I am a beginner at Ruby, so maybe under 512 is possible, but I doubt it.
* 553->544B, -9B
+ Added 3 bytes from fixing a formatting error.
+ 5 bytes from removing an unused print.
+ 4 bytes from changing expression `t-(f>v ?1: 0)*c` to `f>v ?t-c: t`
+ 1 byte from removing an unnecessary assignment to `t`.
+ 2 bytes from removing an assignment to `r`.
* 544->535B, -9B
+ Improved the decoder.
* 535->516B, -19B
+ 17 bytes from changing functions to lambda expressions.
+ 1 byte each from removing parenthesis from `split` and `eval`.
+ Thanks [@Dom Hastings](https://codegolf.stackexchange.com/users/9365/dom-hastings)!
* 516->511B, -5B
+ Use `a` and `r` declared globally, instead of `$a` and `$a`.
* 511->507B, -4B
+ Change all 1 and 2 argument functions' arguments to `x,y=0`.
[Answer]
# Python 3, D^6(9) (~~608~~ ~~600~~ ~~599~~ ~~597~~ ~~591~~ ~~583~~ 573 bytes)
```
_="a=06PJ$x-~x<<c6ZJr=0'E?1+TKQ$r6LJ$xK+T)6@t!YtUr#$A([@TC)'f==2?If,I[S(v+2R,/yUTCC'f<2?t-(f>v)*c'f-v?y6AJ$5<<PB)'Fx)-1?MR,Z(rC6DB=0,t=7,X14!Gx:Nx-1Q.G~EV a=IIt,Iu,PBCUaQ $a#d,YFNxCUFrUFrQGc-rV'not(Fu)or(Fr)-fCH'E:XM,d,rOA(t,dQ'fKH'WdRO/t);X/uQGcV .'EH q=~u&2|E# 'q:X1<<IFuUuQ tR=Iu'q?q,IFcUtC,r#.GuK&WtR);X/tO9#$DB,t,u)\nprint(NNNNNN9CCC)!)Vglobal r,a##\n $return ' G.x=xK#/M-8,13,6\ndef ? else @S(vR,y,B(xRC))Ex%2FL(Gif HV . IP(JB=0!K>>1MS(4,4ND(O);t=Q)#R,cTZ(xU),V:#WE:c=IXu=Yf,x=F[@FxC,"
for Y in"[YXWVUTRQONMKJIHGFECB@?6/.'$#!":_=_.split(Y);_=_.pop().join(_)
exec(_)
```
This is an encoded code. Extracted:
```
a=0
def P(x,c=0):
global r,a
return x-~x<<c
def Z(x,c=0):
global r,a
r=0 if x%2 else 1+Z(x>>1)
return r
def L(x,c=0):
global r,a
return x>>1+Z(x)
def S(v,c,y,t):
global r,a
f,x=L(t),r
return A(S(v,c,y,L(x)),S(v,c,y,Z(x))) if f==2 else P(f,P(S(v,c,y,L(x)),S(v+2,c,S(4,4-8,13,y),Z(x)))) if f<2 else t-(f>v)*c if f-v else y
def A(x,c=0):
global r,a
return 5<<P(x,c) if L(x)-1 else S(4,4,c,Z(r))
def D(x,c=0,t=7,u=14):
global r,a
if x:D(x-1)
x=x>>1
if ~x%2:
a=P(P(t,P(u,P(x,c))),a)
return a
d,f,x=L(L(D(x))),L(r),L(r)
if c-r:
if not(L(u)or(L(r)-f)):
x=x>>1
if x%2:u=S(4,4,d,r);t=A(t,d)
if f>>1:
x=x>>1
if x%2:c=P(d,c);t=S(4,4-8,13,t);u=S(4,4-8,13,u)
if c:
x=x>>1
if x%2:
x=x>>1
q=~u&2|x%2
if q:u=1<<P(L(u),u)
t,c=P(u if q else q,P(L(c),t)),r
x=x>>1
if u>>1&x%2:c=P(t,c);u=S(4,4-8,13,t);t=9
return D(x,c,t,u)
print(D(D(D(D(D(D(9)))))))
```
In this, it is assumed to be:
* Infinite call stack
* Infinite memory
This is basically a port of my [JavaScript answer](https://codegolf.stackexchange.com/a/184808/). For more details, check that one.
The compression was done with [this](https://naruyoko.github.io/tests/compression/Python%203/).
I am not very knowledgeable in Python, so there are certainly places to save bytes. ~~I think sub-600 is possible.~~ sub-600 has been proven.
* 608->600B, -8B
+ Grouped some assignments
+ Reversed conditions of `S` to reduce parenthesis
* 600->599B, -1B
+ Changing `u/2` in the third last line of the definition of `D` to `u>>1`, saving a byte from compressing it to a character with other `>>1`s.
* 599->597B, -2B
+ 2 bytes from removing assignment to `r`.
* 597->591B, -6B
+ Made `D` recursive.
+ Removed the unnecessary assignments to `d`, `f`, and `c`. Making `D` recursive allows this to be completely removed and save more bytes whereas keeping it in a loop would have still needed an assignment to `c`.
* 591->583B, -8B
+ Changed the 1-argument and 2-arguments functions' arguments to `(x,c=0)`.
+ Added `global r,a` to every function.
+ Swapped the second and the third of `S`.
+ Changed the instances of `S(4,-4,13,` to `S(4,4-8,13,`.
+ Fixed the compression algorithm (specifically displaying) so it actually works now.
* 583->573B, -10B
+ Replaces `q and u` with `u if q else q` and that somehow saved 10 bytes.
] |
[Question]
[
The [Borromean rings](https://en.wikipedia.org/wiki/Borromean_rings) are a curious set of three circles, linked such that the removal of any one of them will unlink the other two:
[](https://en.wikipedia.org/wiki/File:Borromean_Rings_Illusion.png)
You can make a set for yourself with a couple rubber bands and a [binder ring](https://i.stack.imgur.com/dAvYU.jpg). With more rubber bands, it's easy to make any [Brunnian link](https://en.wikipedia.org/wiki/Brunnian_link).
Write a program or function that outputs (prints or returns) this ascii-art representation of Borromean rings:
```
+-----+
| |
+-----+ |
| | | |
| +-|---+ |
| | | | | |
| | +-|---+
| | | |
+-|---+ |
| |
+-----+
```
The lines may have trailing spaces and there may be a trailing newline.
The shortest code in bytes wins.
[Answer]
# CJam, ~~53 51 50~~ 49 bytes
Plain old base conversion...
```
"FÓîÞ¤ÛYËB[¢O²êÍÓ
}²|äG"299b4b"+ -|"f=B/N*
```
All characters are well in extended ASCII range (ASCII code 1 to 255), so number of characters == number of bytes.
[Try it online here](http://cjam.aditsu.net/#code=%22F%C2%9E%C2%97%C3%93%C3%AE%C3%9E%C2%A4%C3%9BY%C2%AD%C3%8BB%5B%C2%A2O%C2%82%C2%82%C2%B2%C3%AA%C3%8D%C3%93%10%0A%7D%C2%B2%7C%C2%96%C3%A4G%22299b4b%22%2B%20-%7C%22f%3DB%2FN*) and get the original code [here](http://pastebin.com/Xsvr71TZ)
[Answer]
# Pyth - 51 bytes
I'm sure someone's gonna beat this quick, but just a base compression answer cuz I'm feeling lazy. I'll try to write a serious answer soon.
```
s@L"
+-|"jC" zB²;¶Ê ¿ïÁ»#-ÌClHõy%|ap"5
```
[Try it here online](http://pyth.herokuapp.com/?code=s%40L%22%0A%20%2B-%7C%22jC%22%0C%20%05z%C2%94B%C2%B2%C2%92%3B%C2%B6%C3%8A%05%09%C2%95%C2%BF%C2%9F%C3%AF%C2%9D%C3%81%C2%BB%23%1D-%C3%8CClH%11%C2%98%C3%B5%0By%25%7Cap%225&debug=0).
```
s Reduce on string concatenation
@L Map second arg to index first arg
"..." String of all chars (Pyth allows literal newlines)
j Base conversion to list
C Base conversion 256 -> 10
"..." Base 256 string
5 To Base 5
```
[Answer]
# Pyth, 49 bytes
```
jbc11s@L"+ -|"jC"Tª]UʨWÕÝ_K¨}ÝÝ÷K¨Ý]Òê]UÕ*¡"4
```
[Demonstration.](http://pyth.herokuapp.com/?code=jbc11s%40L%22%2B%20-%7C%22jC%22%01T%C2%AA%C2%85%5DU%C3%8A%C2%A8W%C3%95%C3%9D_K%C2%A8%7D%C3%9D%C3%9D%C3%B7K%C2%A8%C3%9D%5D%C3%92%C3%AA%1D%5DU%C3%95*%C2%A1%224&debug=0)
This uses base 4 encoding, and chops the string into elevenths, then rejoins them on newlines.
[Answer]
# Ruby, 110
```
-2.upto(8){|i|s=" "*(i%6)+"+-----+"*(1-i%2)+" "*9
6.times{|j|"@d me?K[RR@"[i+2].ord>>j&1>0&&s[j*2]=?|}
puts s}
```
Something different from straight base conversion.
Ungolfed:
```
-2.upto(8){|i| #for each line
s=" "*(i%6)+"+-----+"*(1-i%2)+" "*9 #load s with "+-----+" (if required!) padded appropriately with leading spaces and with nine trailing spaces.
6.times{|j|"@d me?K[RR@"[i+2].ord>>j&1>0&&s[j*2]=?|} #replace characters with | as necessary, according to the 6-bit number encoded by each character in the magic string.
puts s} #print the line.
```
[Answer]
# Ruby, 117 bytes
Not winning, but I thought it was a cute approach:
```
puts' --
| |
-- |
| | | |
| -||
| | | | | |
| | -|
| | | |
-||
| |
--'.gsub /-./,'+\0---+ '
```
[Answer]
# BrainFuck, 361 bytes
Here is a little BrainFuck program, only printing char by char.
```
+++++++++[->>>>++++++++++++++<+++++<+++++<++++<]>----....>--.>.....>-->++++++++++<<<.>>>.<<<<....>>>.<<<.....>>>.>.<<<.>.....<.<...>>>.>.<.<<<...>>>.<<<.>>>.<<<...>>>.>.<.<<<.>.>.>.<...<.<.>>>.>.<.<<<.>>>.<<<.>>>.<<<.>>>.<<<.>>>.<<<.>>>.>.<.<<<.>>>.<<<.>.>.>.<...<.>>>.<.<<<.>>>.<<<...>>>.<<<.>>>.>.<<<.>.>.<...<.<.>>>.>.<<<<..>>>.<<<.....>>>.>.<<<<..>.>.....<.
```
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), ~~282~~ ~~280~~ 271 bytes
```
+++++++++++[>++++>+++>+++++++++++>+<<<<-]>->-....<.++.....--.>>>-.<<....>+++.<.....>.>.<<<.++.....--.>...>.>.<.<...>.<.>.<...>.>[.<]>++.>>.<<...--[.>]+++++[<<.<.>>>-]<<.>.<.<.>.<.<.++.>>.<<...--.>>>.<.<.>.<...>.<.>.>.<<<.++.>>.<<...--[.>]<<<..>.<.....>.>.<<..<.++.....--.
```
[Try it online!](https://tio.run/##VU9bCsAgDDuQtCcouYj4sQ0GY7CPwc7vGl@bEdtak1jXezmu/dnOnMOHCEa03YFgDkkQiDpMQ2BWEQW8Z8YTJVoqhS@X/Hm9WxjMaBWiWnKtW1UjkahIdR4jn28ks6auceKTMe66@5hg9mWz8fqc849yfgE "brainfuck – Try It Online")
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal) `j`, 43 bytes
```
»⟑|Ḃṗ=›ḟL«w_¬⌊†⁰÷↳ḋ≈∑Ġ«Ṅ⁽ǔ7₇ÞyΠj»`-+| `τ11/
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=j&code=%C2%BB%E2%9F%91%7C%E1%B8%82%E1%B9%97%3D%E2%80%BA%E1%B8%9FL%C2%ABw_%C2%AC%E2%8C%8A%E2%80%A0%E2%81%B0%C3%B7%E2%86%B3%E1%B8%8B%E2%89%88%E2%88%91%C4%A0%C2%AB%E1%B9%84%E2%81%BD%C7%947%E2%82%87%C3%9Ey%CE%A0j%C2%BB%60-%2B%7C%20%60%CF%8411%2F&inputs=&header=&footer=)
```
»...» # Base-255 compressed number
`-+| `τ # Decompress using key `-+| `
11/ # Divide into 11 pieces
# join by newlines
```
[Answer]
# [Staq](https://esolangs.org/wiki/Staq), 109 chars
```
&iiiqi{1" "}{211}{c"| "}{fcc}{o"+-|"}{p"+--"}{r"---+"}{ec;}22pr;22c22epr21ec2f2ecor1effcefor;f2ceor1e2c22e2pr
```
output:
```
Executing D:\codegolf\Staq borromean rings.txt
+-----+
| |
+-----+ |
| | | |
| +-|---+ |
| | | | | |
| | +-|---+
| | | |
+-|---+ |
| |
+-----+
Execution complete.
>
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 31 bytes
```
B⁷¦⁷M±⁴¦²B⁷¦⁷M²¦²B⁷¦⁷M²→|M³¦²¦¹
```
[Try it online!](https://tio.run/##S85ILErOT8z5/98pv0LDXMdck8s3vyxVQ9dEx0iTC1XMCJuQVVBmekaJJldAUWZeiYZSjRJUxhikGCJoqPn//3/dnDIA "Charcoal – Try It Online")
Link is to verbose version of code.
It's pretty fun to have a box function.
Basically draws three boxes at the required location, and patches the required places.
[Answer]
# [Haskell](https://www.haskell.org/), 79 bytes
```
"]O|f]S]S6|g[:[S[VO1g$S)S*)O1f)])61g&S]RZ|x">>=(mapM(:"|\n -")"+++"!!).fromEnum
```
[Try it online!](https://tio.run/##y0gszk7Nyfmfm5iZp2CrUFBaElxS5JOnoKIQ818p1r8mLTY4NtisJj3aKjo4OszfMF0lWDNYS9PfME0zVtPMMF0tODYoqqZCyc7OViM3scBXw0qpJiZPQVdJU0lbW1tJUVFTL60oP9c1rzT3P9f/f8lpOYnpxf91kwsKAA "Haskell – Try It Online")
A base-5 decompression technique. Each ASCII value in the string is used as an index into the list of parts `["+++", "++|", "++\n", ..., "---"]` created by `mapM`.
## Approach
See [this tip](https://codegolf.stackexchange.com/a/52945/3852) for Cartesian product with `mapM`.
At first, I used `mapM(\_->"......")"123"` to create the decoding list, with some permutation of `" +-|\n"` in place of the dots. The best permutations (yielding the shortest encoded string literals) gave 83-byte solutions:
```
">:]P>H>F+]%FpHpFob[FrHrFr:vPr>r\bvRfH>F=][">>=(mapM(\_->"\n+ -|")"123"!!).fromEnum
">;|i>C>A1|%AWCWAVwyAXCXAX;ciX>X\tckMC>A=|y">>=(mapM(\_->"\n+ |-")"123"!!).fromEnum
"]R>7]b]_%>+_vbv_tH=_wbw_wRp7w]w\ap:gb]_[>=">>=(mapM(\_->"\n+- |")"123"!!).fromEnum
"|k>7|w|s%>1scwcs`C=sbwbsbkW7b|b\aW;Ow|sy>=">>=(mapM(\_->"\n+-| ")"123"!!).fromEnum
"]T|i]X]U1|+UDXDUBryUCXCUCTJiC]C\tJl5X]U[|y">>=(mapM(\_->"\n+| -")"123"!!).fromEnum
"|l]P|r|n+]1nJrJnGX[nHrHnHlDPH|H\bDT6r|ny][">>=(mapM(\_->"\n+|- ")"123"!!).fromEnum
```
Each contains one low-ASCII byte, `\b` or `\t` or `\a`.
Then I realized I could write `mapM(\_->"\n+ -|")"123"` as `mapM(:"+ -|")"\n\n\n"` to save two bytes. But maybe I could save even *more* bytes if I used a permutation *not* starting with `\n`, because `"\n\n\n"` is pretty long.
Sadly, the permutations not starting with `\n` yielded bad values making the string literal longer. The best programs are all still 81 bytes:
```
">6|g>9>:\24|\f:%9%:#mx:$9$:$61g$>$O1f*9>:<|x">>=(mapM(:"| \n-")"+++"!!).fromEnum
">5]O>9>;\18]\f;%9%;#SZ;$9$;$5+O$>$g+M/9>;<]Z">>=(mapM(:"| -\n")"+++"!!).fromEnum
"|f>5|m|l\f>\24l1m1l-9<l.m.l.f%5.|.M%6,m|lx><">>=(mapM(:"|-\n ")"+++"!!).fromEnum
"]M>6]S]T\f>\18T+S+T(9<T)S)T)M%6)])f%50S]TZ><">>=(mapM(:"|- \n")"+++"!!).fromEnum
```
However, I had another trick up my sleeve: the problem statement allows for trailing spaces on each line, and maybe I could insert 3 trailing spaces in such a way that the string literal becomes one "actual character" longer, but ends up not having stuff like `\24` and `\f` in it.
So I ran a brute force search for all positions to add such trailing spaces. And indeed, adding a trailing space on lines 2, 4, and 6 lets us write the above 79-byte program, where the encoded string is fully printable ASCII.
There are many other permutation-space-placement pairs that tie this one. Here are just a few:
```
"]O|f]S]SU|x]$])]$O1g$S)S*)O1f)])61g&S]RZ|x" (44,"+|\n -",[1,1,5])
"|g]M|m|m5]Oyz1m1k-SZk.m.k.g+M.|.5+O'm|kx]Z" (44,"+|\n- ",[1,2,2])
">6|fW=>=A|x>)>$>)61f&$9$:$61g$>$O1f*9>:<|x" (44,"+| \n-",[0,1,4])
">5]Mp=>=g]M=G>$>.5+M.9$9'$5+O$>$g+M/9>;<]Z" (44,"+| -\n",[0,2,5])
"|f>5|m|ms><|)|.|)f%60.m.l.f%5.|.M%6,m|lx><" (44,"+|-\n ",[1,1,4])
"]M>5b]+]-><],+S+T(9<T)S)T)M%6)])f%50S]TZ><" (44,"+|- \n",[0,0,2])
```
## I tried a few other things
I tried a few other things. If you pad each line in the target string to "11 characters followed by a newline", then the newlines will only occur at indices ≡ 3 mod 4. In fact, if you look at each *k* mod 4 and count the unique characters there, they group themselves quite nicely:
```
target!!k `elem` " +-|" when k ≡ 0 mod 4.
target!!k `elem` " -" when k ≡ 1 mod 4.
target!!k `elem` " +-|" when k ≡ 2 mod 4.
target!!k `elem` " -\n" when k ≡ 3 mod 4.
```
So a mixed-base approach is tempting.
Of course, something like `mapM id[" +-|"," -"," +-|"," -\n"]` is too long, but I played with `mapM(`drop`"+|\n- ")[0,3,0,2]`. Sadly, the strings just aren't great. The best I could get out of this was 93 bytes.
```
"³F{³;¥F}¥;/¥1(K//-/={/§9=}9§³9©\130W">>=(mapM(`drop`"||+\n- ")[0,4,1,3]!!).fromEnum
```
Alternatively, you could try a base-4 approach with different alphabets for each k mod 4. This is easy to express with `mapM`. I got this 84 byte solution, which would be 70 bytes if Haskell programs used some ANSI encoding rather than UTF-8.
```
"ÿJ¤ÿ?ðJ§ð?3ð6*p3303B¤3ó<B§<óÿ<öª|">>=(mapM(:"+- ")"|-|\n"!!).fromEnum
```
[Answer]
# Python 3, 139 bytes
This is the closest I can get to printing it directly (which would be 134 bytes) without actually doing so.... I'm not sure how to shorten it any more.
```
a='+-----+'
b='+-|---+'
c=' '*4
d='| '
e=c+d
print(c+a,e*2,a+e[1:],"| | "*2,d+b+" |",d*6,d+d+b,"| | "*2,b+" |",e[2:]+e," "+a,sep='\n')
```
] |
[Question]
[
As many geeks may know most pages (95% i think) on wikipedia eventually lead to Philosophy like this:
Click on the first non-italic or in parentheses link that is to another normal article: (i.e. not File: or Special:, but things like Wikipedia: are OK) and repeat on that one until you hit philosophy.
The script must:
* Take a first page as input
* Print the name of each article it gets to
* And print how many articles it took to get to Philosophy, and if it didn't say so.
You start with 1000 points, and lose one for each character in the code, Bonus points for:
Detecting looping articles and stopping: +50
Detecting looping articles and requesting if the user should go to the next link on the article: +170
Allowing for a default on the former check as a command-line arg or similar: +140
Highest score wins.
[Answer]
# Ruby, 1000 - ~~303~~ ~~299~~ ~~337 - 50~~ ~~373 - 170~~ ~~382 - 170 - 140~~ 379 - 170 - 140 chars = ~~697~~ ~~701~~ ~~713~~ ~~797~~ ~~928~~ 931
I'm sure there are *many* improvements to be made.
(This requires Nokogiri)
```
require'open-uri'
require'nokogiri'
x="/wiki/"+gets.chomp
r=[n=i=0]
until x=~/\/Philosophy/
d=Nokogiri.HTML open"http://en.wikipedia.org#{x}"
x=d.css('p a').select{|a|t=a.xpath('preceding::text()').map(&:text)*'';t.count('(')==t.count(')')&&a.attr('href')=~/^.wiki[^:]+$/}[i].attr'href'
i=0
puts r.index(x)?"#{$><<'i=';i=($*[0]||gets).to_i;''}": r.push(x)[-1][6..-1]
n+=1
end
p n
```
Example run:
```
c:\a\ruby>wikipedia_crawl_philosophy
Latin (note: this is my input)
Classical_antiquity
History
Umbrella_term
Terminology
Word
Linguistics
Science
Knowledge
Fact
Proof_(truth)
Argument
Logic
Reasoning
Consciousness
Quality_(philosophy)
Property_(philosophy)
Modern_philosophy
Philosophy
18
```
Sample one where I had to go to a different link
```
c:\a\ruby>wikipedia_crawl_philosophy
Snow
Precipitation_(meteorology)
Meteorology
Atmospheric_physics
Synoptic_scale_meteorology
i=2 // I put the 0-indexed number of the link I wanted to go to (so, the third link)
Weather
Atmosphere
Gas
State_of_matter#The_four_fundamental_states
Physics
Natural_science
Sciences
Knowledge
Fact
Proof_(truth)
Argument
Logic
Reasoning
Consciousness
Quality_(philosophy)
Property_(philosophy)
Modern_philosophy
Philosophy
25
```
Tricks I used:
* I used the selector `p a` to only get non-italic links, because all links in the actual article that are not italics are always in paragraph elements in Wikipedia.
[Answer]
*"BASH*" – (If not mistaken: 1000 - 397 + 170 + 140 = 913 points)
*"BASH"* – (If not mistaken: 1000 - 386 + 170 + 140 = 924 points)
# *"BASH"* – (If not mistaken: 1000 - 381 + 170 + 140 = 929 points)
BASH is in quotes on purpose as this is a mix of tools used in \*nix shells but wrapped in a bash script.
## Edit 1:
* Removed `http://` as `curl` defaults to this.
* Changed `href=` match on anchors to `f=` as `<a>` does not have any other *normal* attributes ending in `f`. (It is a possibility of custom tags. Have not seen any so far.)
* Set exit message on not found to `!Phil` instead of `NoPhil`. This one is a bit quirky as One could also say e.g. `!`, `0`, `N`, `!P` or similar.
* Quirk two: `-s` on `curl` could be removed to reduce by three more bytes, but that would yield a messy output. Not sure if that is an issue.
* Updated *help* on this page.
Using quirks, code would end up at 379 bytes, 931 points.
I could also implement [@plannapus](https://codegolf.stackexchange.com/users/6741/plannapus) usage of matching (hopefully) *navigation box* by adding `(p|ul).*?<(\1)` adding six bytes (subtracting six points).
## Edit 2:
Using `${#c[@]}` to print degrees of separation instead of `$i` counter.
Using quirks, code would end up at 374 bytes, 936 points.
---
I summon Cthulhu and go for a regexp + bash/shell/\*nix solution.
Stolen:
* Using `<p>` trick from [@Doorknob of Snow](https://codegolf.stackexchange.com/users/3808/doorknob-of-snow).
Implemented:
* Detect loop and ask if next link should be taken.
* Optionally select next link on duplicate as option.
Requirements:
* `bash` v.?
* `grep` with `-P` (PCRE) support.
* `sed`
* `curl`
* `cut`
Usage:
```
script PATH [OPTIONS]
Print separation of article from ``PATH'' to ``Philosophy'' on Wikipedia.
Degrees of separation, if found, is printed as last line.
If not found last line yields ``!Phil''.
PATH
Absolute path to starting article, e.g: /wiki/Word
OPTIONS
y Automatically select next link if already visited.
n (Or other) Quit if next link already visited.
BUGS
1. On previous visit; "next link" is not checked. Thus if next link
has already been visited we get eternal loop. Not sure if this
disqualify +170 points.
2. Sure there are.
```
Inline code. Copy to file. `chmod +x filename`. Run by `./script /wiki/…` from bash shell.
```
u=($1);c=($1);while ! [[ "$u" =~ /Philosophy$ ]];do echo "$u";u=($(curl -s "en.wikipedia.org$u"|tr '\n' ' '|grep -Po '<p>.*?</p>'|sed 's/>[^<]*([^)]*)//g'|grep -o '<a [^>]*f="/wiki/[^":]*"'|cut -d\" -f2));for x in "${c[@]}";do if [ "$x" = "$u" ];then [ $2 ] &&s=$2||read -p "${u[0]}?" s;[ $s = y ] &&u[0]=${u[1]}||{ echo "!Phil";exit;} fi;done;c=("${c[@]}" "$u");done;echo ${#c[@]};
```
## Expanded and explained code:
```
u=($1); # Array of paths.
c=($1); # Array of visited paths.
# While $u != /Philosophy, ugly trick is to use $u instead of ${u[0]}.
while ! [[ "$u" =~ /Philosophy$ ]];do
echo "$u"; # Print current page.
# curl : prints retreived page to stdout. "-s" could be skipped.
# tr : replace all newline with space. This is a ®sanity thing when it comes to
# twidling with html using regex.
# grep 1 : match <p> tags. Using -P's ungreedy *?.
# sed : remove all occurences of "(" something ")".
# grep 2 : match links where "href" attribute starts with /wiki/ and is not e.g. File:
# cut : match actual href value.
# Result is added to array ``u''.
u=($(curl -s "en.wikipedia.org$u" |
tr '\n' ' ' |
grep -Po '<p>.*?</p>' |
sed 's/>[^<]*([^)]*)//g' |
grep -o '<a [^>]*f="/wiki/[^":]*"' |
cut -d\" -f2));
# For previously visited pages as x.
for x in "${c[@]}"; do
# If x equals to first page ...
if [ "$x" = "$u" ]; then
# Use option or ask.
[ $2 ] && s=$2 || read -p "${u[0]}?" s;
# If response is "y" use next link, else exit with status.
[ $s = y ] && u[0]=${u[1]} || {
echo "!Phil";
exit;
}
fi;
done;
# Append current link to "visited"
c=("${c[@]}" "$u");
done;
# Print number of visited pages.
echo ${#c[@]}
```
[Answer]
## JavaScript 726 (444 chars [556] + 170)
Now I appreciate that this might not be valid as a bookmarklet, but I've enjoyed tinkering with it anyway.
Usage: Navigate to the page you'd like to start from and run the following in the console:
```
(function(a){c=0,o="";$(u="html")[u](f=$('<iframe src="'+location+'?">').on("load",function(){$=f.contentWindow.$;p=f.contentDocument.title[s="split"](" - ")[0];c++;p=="Philosophy"?document.write("<pre>"+o+p+"\n"+c):(i=RegExp("^"+p+"$","m").test(o)?a||confirm("Loop, try next?")?2:0:1)&&(f.src=$("p>a").filter(function(){return(t=$(this).parent()[u]()[s](this.outerHTML)[0])[s]("(").length==t[s](")").length})[--i].href);o+=p+"\n"})[0])})(true)
```
For JavaScript the output is the following:
```
JavaScript
Interpreter (computing)
Computer science
Science
Knowledge
Fact
Proof (truth)
Argument
Logic
Reason
Consciousness
Quality (philosophy)
Property (philosophy)
Modern philosophy
Philosophy
15
```
This solution will assume you want to jump to the next link on a loop being detected, but if you change the `true` at the end to `false` it'll pop up a confirmation box instead (quite annoying...) not sure if that qualifies for the secondary bonus or not. I'll assume not.
Indented:
```
(function(l){
c=0,o='';
$(u='html')[u](f=$('<iframe src="'+location+'?">').on('load',function(){ // Firefox needs the ? to properly load the frame
$=f.contentWindow.$; // reference repeated calls as strings to save more bytes
p=f.contentDocument.title[s='split'](' - ')[0]; // get the title
c++;
p=='Philosophy'?
document.write('<pre>'+o+p+'\n'+c): // pre for nice formatting
(i=RegExp('^'+p+'$','m').test(o)?
l||confirm('Loop, try next?')?
2: // desired index + 1 so we can use as a boolean
0
:
1)&&
(f.src=$('p>a').filter(function(){
return (t=$(this).parent()[u]()[s](this.outerHTML)[0])[s]('(').length == t[s](')').length // shorter, but still not overly happy with this...
})[--i].href);
o+=p+'\n' // update output
})[0])
})(true) // change this to show confirm box when loop detected
```
So I originally missed the part about ignoring items in parens, adding that made it a lot more wordy, so I'm hoping to golf that filter function down (or hopefully replace it entirely).
Working in both Chrome and Firefox (tested in Firefox 26)
[Answer]
# C# - 813 chars
Score: 1000-813+50+170+140 = **547** :(
**No external libraries. Loop detection**.
First argument is the Source Article, second is the Target Article.
Golfed version:
```
class Program
{
static void Main(string[] a)
{
Func<XmlDocument,IList<string>> G=delegate(XmlDocument xd){return xd.SelectNodes("//p//a[starts-with(@href,'/wiki/') and not(contains(@href,':'))]").Cast<XmlNode>().Select(n=>n.Attributes["href"].InnerText).ToList();};Action<string> W=delegate(string s){Console.WriteLine(s);};var h=new HashSet<string>();var c=new WebClient();var x=new XmlDocument();var t=c.DownloadString(@"http://wikipedia.org/wiki/"+a[0]);int i=0,C=0;
GO:
x.LoadXml(t);var ns=G(x);
COL:
var f=ns[i];if(f.Equals("/wiki/"+a[1],StringComparison.OrdinalIgnoreCase)){goto END;}if(h.Contains(f)){W("loop: "+f);i++;goto COL;}else{h.Add(f);i=0;C++;}W(f);t=c.DownloadString(@"http://wikipedia.org"+f);goto GO;
END:
W("Found in "+C);
}
}
```
Intelligible version:
```
class Program
{
// arg[0] source article. arg[1] target article
static void Main(string[] arg)
{
Func<XmlDocument, IList<string>> G = delegate(XmlDocument xd)
{
return xd.SelectNodes("//p//a[starts-with(@href,'/wiki/') and not(contains(@href,':'))]").Cast<XmlNode>().Select(n => n.Attributes["href"].InnerText).ToList();
};
Action<string> W = delegate(string s) { Console.WriteLine(s); };
var h = new HashSet<string>(); var c = new WebClient(); var x = new XmlDocument();
var allText = c.DownloadString(@"http://wikipedia.org/wiki/" + arg[0]);
int i = 0; int C = 0;
GO:
x.LoadXml(allText);
var ns = G(x);
COL:
var f = ns[i];
if (f.Equals("/wiki/" + arg[1], StringComparison.OrdinalIgnoreCase))
{
goto END;
}
if (h.Contains(f))
{
W("loop: " + f); i++; goto COL;
}
else
{
h.Add(f); i = 0; C++;
}
W(f);
allText = c.DownloadString(@"http://wikipedia.org" + f);
goto GO;
END:
W("Found in " + C);
}
}
```
Example run, from "Sky" to "Philosophy":
```
C:\>wiki.exe Sky Philosophy
/wiki/Earth
/wiki/Geometric_albedo
/wiki/Phase_angle_(astronomy)
/wiki/Observational_astronomy
/wiki/Astronomy
/wiki/Natural_science
/wiki/Sciences
/wiki/Latin_language
/wiki/Classical_antiquity
/wiki/History
/wiki/Ancient_Greek
/wiki/Greek_language
/wiki/Modern_Greek
loop: /wiki/Greek_language
/wiki/Colloquialism
/wiki/Word
/wiki/Linguistics
/wiki/Science
loop: /wiki/Latin_language
/wiki/Knowledge
/wiki/Fact
/wiki/Latin
loop: /wiki/Classical_antiquity
/wiki/Italic_languages
/wiki/Indo-European_languages
/wiki/Language_family
/wiki/Language
/wiki/Human
/wiki/Extinct
/wiki/Biology
loop: /wiki/Natural_science
/wiki/Life
loop: /wiki/Earth
/wiki/Physical_body
/wiki/Physics
loop: /wiki/Greek_language
loop: /wiki/Natural_science
/wiki/Matter
/wiki/Rest_mass
/wiki/Center_of_momentum_frame
loop: /wiki/Physics
/wiki/Inertial_frame
loop: /wiki/Physics
/wiki/Frame_of_reference
loop: /wiki/Physics
/wiki/Coordinate_system
/wiki/Geometry
loop: /wiki/Ancient_Greek
/wiki/Mathematics
/wiki/Quantity
/wiki/Property_(philosophy)
/wiki/Modern_philosophy
Found in 41
C:\>
```
[Answer]
# Scala (294 chars => 1000-294+140 = 846 points)
The updated solution which automatically takes the next link if one has already been consumed. ***Thanks for the 140 bonus points.***
**Logic:**
Pick up the first "/wiki" link that doesn't have a ":" in it (so it ignores "File:" links). Rinse and repeat with recursion returning the count + 1 every time. I keep a list of all previous outputs handy so the program doesn't go into an infinite loop.
**Regular Expression:** I have 2 forms of the regular expression.
* `"<p>.*?\"/wiki/([^:]*?)\".*?/p>"` which finds links within the `<p>` tags
* `"p>.*?/wiki/([^:]*?)\""` which is a slightly more experimental tag that has proven to work but provide different results because it, at times, picks up links from the right side info bar. These are regular articles so I believe it is still valid. If it's adjudged to not be, the OP (or someone else) can leave me a comment and I can update my solution to a better reg-ex.
I'm going to be using the second regular expression until I find a test case where it doesn't work or the OP mentions picking up links from the side bar aren't allowed (in my opinion, the info bars are still part of the actual article itself; more of a summary).
---
**Minified Source:**
```
object W extends App{print(x(Seq(args(0))));def x(s:Seq[Any]):Int={val? =s.last;println(?);?match{case "Philosophy"=>1;case _=>x(s:+"p>.*?/wiki/([^:]*?)\".*?/p>".r.findAllMatchIn(io.Source.fromURL("http://en.wikipedia.org/wiki/"+ ?).getLines.mkString).map(_ group 1).filter(!s.contains(_)).next)+1}}}
```
**Readable Source:**
```
object W extends App {
print(x(Seq(args(0))))
def x(s: Seq[Any]): Int = {
val ? = s.last
println(?)
? match {
case "Philosophy" => 1
case _ => x(s :+ "p>.*?/wiki/([^:]*?)\"".r.findAllMatchIn(io.Source.fromURL("http://en.wikipedia.org/wiki/" + ?).getLines.mkString).map(_ group 1).filter(!s.contains(_)).next) + 1
}
}
}
```
**Sample Output:**
*Input*
```
Space_toilet
```
*Output*
```
Space_toilet
Weightlessness
G-force
Weight
Force
SI_unit
French_language
Second_language
Language_acquisition
Word
Linguistics
Science
Latin_language
Pontifical_Academy_for_Latin
Pope_Benedict_XVI
Pope_Benedict_(disambiguation)
Regnal_name#Catholic_Church
Monarch
State_(polity)
Community
Commutative_property
Mathematics
Quantity
Property_(philosophy)
Modern_philosophy
Philosophy
26
```
[Answer]
### R, 379 characters; 1000-379+170=791 points
Version that ask users how to proceed when looping detected
```
library(XML);w="http://en.wikipedia.org";W="/wiki/";n=1;A=c(scan(,""));while(A[n]!="Philosophy"){a=paste0(w,W,A[n]);d=sapply(strsplit(grep(W,sapply(xpathApply(xmlParse(readLines(a)),"//p/a[@href]|//ul/li/a[@href]",xmlAttrs),`[`,'href'),v=T),"/"),`[`,3);B=d[-grep(":",d)];n=n+1;if(B[1]%in%A)if(readline("Loop!2nd link?")=="n")break;A[n]=head(B[!B%in%A],1);cat(A[n],"\n")};cat(n-1)
```
With indentations and comments:
```
library(XML) #Uses package XML
w="http://en.wikipedia.org"
W="/wiki/"
n=1
A=c(scan(,"")) #Stdin + makes it a vector so we can store each iteration
while(A[n]!="Philosophy"){
a=paste0(w,W,A[n])
d=sapply(strsplit(grep(W,sapply( #The heart of the program
xpathApply(xmlParse(readLines(a)),"//p/a[@href]|//ul/li/a[@href]",xmlAttrs),
`[`,'href'),v=T),"/"),`[`,3)
B=d[-grep(":",d)] #get rid of Templates, Files ,etc...
n=n+1
#Ask user if should proceed when loop encountered
#(any answer other than "n" is considered agreement):
if(B[1]%in%A)if(readline("Loop!2nd link?")=="n")break
A[n]=head(B[!B%in%A],1) #Take the first link that is not redundant
cat(A[n],"\n")
}
cat(n-1)
```
Example run:
```
> library(XML);w="http://en.wikipedia.org";W="/wiki/";n=1;A=c(scan(,""));while(A[n]!="Philosophy"){a=paste(w,W,A[n],sep="");d=sapply(strsplit(grep(W,sapply(xpathApply(xmlParse(readLines(a)),"//p/a[@href]|//ul/li/a[@href]",xmlAttrs),`[`,'href'),v=T),"/"),`[`,3);B=d[-grep(":",d)];n=n+1;if(B[1]%in%A)if(readline("Loop!2nd link?")=="n")break;A[n]=head(B[!B%in%A],1);cat(A[n],"\n")};cat(n-1)
1: Extended_ASCII
2:
Read 1 item
Eight-bit
Computer_architecture
Computer_science
Science
Logic
List_of_aestheticians
Art
Human_behavior
Behavior
Organism
Biology
Loop!2nd link?y
Mathematics
Quantity
Property_(philosophy)
Modern_philosophy
Philosophy
16
```
### R, 325 characters; ??? points
Version that, by default takes first non-redundant link (i. e. non-looping).
```
library(XML);w="http://en.wikipedia.org";W="/wiki/";n=1;A=c(scan(,""));while(A[n]!="Philosophy"){a=paste0(w,W,A[n]);d=sapply(strsplit(grep(W,sapply(xpathApply(xmlParse(readLines(a)),"//p/a[@href]|//ul/li/a[@href]",xmlAttrs),`[`,'href'),v=T),"/"),`[`,3);B=d[-grep(":",d)];n=n+1;A[n]=head(B[!B%in%A],1);cat(A[n],"\n")};cat(n-1)
```
] |
[Question]
[
In this [fastest-code](/questions/tagged/fastest-code "show questions tagged 'fastest-code'") challenge, you are provided with a set of \$n\$ identical blocks and need to determine how many unique buildings can be constructed with them. Buildings must satisfy the following rules:
1. No overhangs - each block must either be on the ground or supported by one or more blocks directly underneath it.
2. All blocks must be aligned to a unit-sized grid.
3. All blocks in a building must be connected to at least one other block by at least one face, and the blocks must form a single connected unit.
4. Buildings are not unique if they can be mapped to another building by reflection or rotation in the X/Y plane.
e.g. These are the same:


5. If a building is rotated between horizontal and vertical, that does result in a different building
e.g. These are different:
A building with two storeys each of two rooms:

A building with one storey containing 4 rooms:

The challenge is to determine how many different house designs are possible using a given number of cubes. Input and output are both a single integer (using any standard method).
Clearly for 1 cube, only 1 design is possible. For 2 cubes, 2 designs are possible (lying down and standing up). For 3 cubes, there are 4 possibilities, and for 4 cubes there are 12 (see images below; please note the colours are just for display to make it easier to see the individual cubes, but don’t have any significance beyond that).

The first 8 terms are:
```
n | output
1 | 1
2 | 2
3 | 4
4 | 12
5 | 35
6 | 129
7 | 495
8 | 2101
```
[Draft sequence on OEIS](https://oeis.org/draft/A331621).
This is [fastest-code](/questions/tagged/fastest-code "show questions tagged 'fastest-code'"). The winning entry is the one that can determine the number of buildings for the highest value of \$n\$. If more than one answer can calculate the result for the same \$n\$ within 10 minutes, the one that is fastest for that value wins. This will be tested on an 8th generation Core i7 with 16 GB RAM running Ubuntu 19.10. There must therefore be a freely available interpreter or compiler for any code posted. Default loopholes and IO rules apply.
Cube images generated using [usecubes](https://www.usecubes.com/).
[Sandbox link](https://codegolf.meta.stackexchange.com/a/18414/42248)
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), \$N=10\$ in 4m02s1
*1: on an Intel Code i7, 7th Gen*
This only includes some trivial optimizations and is therefore quite inefficient. It does at least confirm the results listed in the challenge.
```
function build(n) {
let layer = [],
cube = new Set,
count = 0,
x, y;
for(y = 0; y < n; y++) {
for(layer[y] = [], x = 0; x < n; x++) {
layer[y][x] = 0;
}
}
function fill(k, alignTop) {
let x, y;
if(k == 0) {
if(!cube.has(layer + '')) {
let transf;
count++;
cube.add(layer + '');
cube.add((transf = rotate(n, layer)) + '');
cube.add((transf = rotate(n, transf)) + '');
cube.add((transf = rotate(n, transf)) + '');
cube.add((transf = mirror(layer)) + '');
cube.add((transf = rotate(n, transf)) + '');
cube.add((transf = rotate(n, transf)) + '');
cube.add((transf = rotate(n, transf)) + '');
}
return;
}
let y0;
for(y0 = 0; !layer[y0].some(v => v); y0++) {}
for(y = Math.max(0, y0 - 1); y < n; y++) {
for(x = 0; x < n; x++) {
if(
!layer[y][x] && (
(y && layer[y - 1][x]) ||
(y < n - 1 && layer[y + 1][x]) ||
(x && layer[y][x - 1]) ||
(x < n - 1 && layer[y][x + 1])
)
) {
for(let i = 1; i <= (alignTop ? k : k - y0 - 1); i++) {
layer[y][x] = i;
fill(k - i, alignTop || !y);
layer[y][x] = 0;
}
}
}
}
}
for(y = 0; y < n; y++) {
for(let i = 1; i <= n - y; i++) {
layer[y][0] = i;
fill(n - i, !y);
layer[y][0] = 0;
}
}
return count;
}
function rotate(n, layer) {
let rot = [],
x, y;
for(y = 0; y < n; y++) {
for(rot[y] = [], x = 0; x < n; x++) {
rot[y][x] = layer[n - x - 1][y];
}
}
return align(rot);
}
function mirror(layer) {
return align([...layer].reverse());
}
function align(layer) {
while(!layer[0].some(v => v)) {
let s = layer.shift();
layer = [...layer, s];
}
while(!layer[0].some((_, y) => layer[y][0])) {
layer = layer.map(r => {
return [...r.slice(1), 0];
});
}
return layer;
}
```
[Try it online!](https://tio.run/##xVbBcpswEL37KzaXIAbM4FunxOmpx/bS3jyeDrFFrBoLjxAOTMK3uysJgcCJm04O9YwN3n37dt9qWft3ekrLjWBHOefFlp69qqRQSsE20kvOWcU3khUcHiqWbwn34XkGkFMJedpQAUtYrUO0qNemeqBo4PQJflDZW4uKSzTH1lCH0CQz/JIVgjTKk0ADd8DxEgQmgXHqFKtmbbJAbbC1wdYDFsAiV/Vag7S5nam3SmRFZCzPyT6ENGeP/GdxtARKT18WAMvIHpbIMyRA043SF@3S0tQFAXiePyAMixQpL7OOp5cfBK5F0aTbrUuTXHqJoUI5opCppISHRibm/JcYY/pg0LWoAxPCHtb/qO0DQW13FVRWgtup6UeiiTvlelJjM3433azF66gsDpScYHkPJx@HN9YT2TohGPEtlbvokNYkxvmKYQ4L/7VxNwFXJlyPYH8PfRl65G9vwfUBYGq0dRCVVMF8eHmZojCRcrvo4C107aAQoWlfQ11yKrSi9R3ocO@K7B58bD7DXiwSvNwtgdgHFr7AHj7jez40k43bdLkOWDJymiWAwWxYBKgCbho/ucISu852Nr1rJyvnr7ttIlG1rJmI6QuIRzK0AG4EOEWP0dMdaEbcrKNkhqZ@KU7XS7/h0THa7@9f3Bj5rrVtcKa/pnwly0wWOlwJvQJ9ZCqDP5YxWkM6wyhgFUWR9q0jQU9UlJT4EwYDdAiediynpHvSJs@7@9NR2vKjcscySboj6X8hbeoQSq2pfYub/MIW@yqBc5hDqo7PpDqkRyIU9Hm0xHQ2LCRnG0oWfgixbaOfjBupabADZzuO3IwjV@P4Ca/2pDYFL4ucRpJhiZ76NBvU2vPikXjfMdjDh5yrDQvz@b3@Zv81jPCK4SvfDlTt@Q8 "JavaScript (Node.js) – Try It Online") (up to \$N=8\$)
### Output
```
N = 1 --> 1
time: 10.352ms
N = 2 --> 2
time: 0.935ms
N = 3 --> 4
time: 0.877ms
N = 4 --> 12
time: 2.530ms
N = 5 --> 35
time: 9.060ms
N = 6 --> 129
time: 33.333ms
N = 7 --> 495
time: 157.160ms
N = 8 --> 2101
time: 1559.707ms
N = 9 --> 9154
time: 18555.900ms
N = 10 --> 41356
time: 242855.989ms
```
[Answer]
# Java 8, \$n=14\$ in 2m31s1
*1. Using the AdoptOpenJDK8 distribution, on a [2-core Amber Lake Intel Core i5](https://ark.intel.com/content/www/us/en/ark/products/189912/intel-core-i5-8210y-processor-4m-cache-up-to-3-60-ghz.html)-based Mac. On an [Amazon EC2 **m5.xlarge**](https://aws.amazon.com/ec2/instance-types/m5/), takes **1m16s**.*
This takes an inductive approach where, for each rank, it builds off all the buildings of the previous rank by placing cubes in all legal positions (on top of and next to existing cubes), and then removing buildings that are (possibly transformed) duplicates of other buildings. This means that to enumerate the buildings in a rank, all previous ranks must be also be computed. Both compute time and memory are constrained resources — this algorithm relies on keeping millions of Building objects in memory — so I've had a hard time computing beyond \$n=14\$ on my machine even without the 10 minute time limit.
This solution includes a parallel-Stream-based approach (which can be enabled with the `parallel` JVM system property) which is faster on a multi-core system but also more memory-hungry. This approach was used for the timing results above. The non-parallel approach takes almost twice as long to count \$n=14\$ but is able to do so using only a third of the memory.
Garbage collector settings and tuning can have a significant impact on the runtime and ability of the process to complete. I've also tested with OpenJDK 13, but for whatever reason have seen the best results on 8 so far.
```
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
public final class Building {
/**
* A flattened two-dimensional matrix of heights (see toIndex).
* Buildings are always assumed to be "aligned", such that they exactly
* fit within their (width, height) bounding box.
*/
private final byte[] stacks;
private final int hashCode;
private final byte width;
private final byte height;
public Building() {
this(new byte[]{1}, 1);
}
private Building(byte[] stacks, int width) {
assert stacks.length % width == 0;
this.stacks = stacks;
this.width = (byte) width;
this.height = (byte) (stacks.length / width);
this.hashCode = 31 * width + Arrays.hashCode(stacks);
}
/**
* Return the building created by adding a cube at the specified coordinates.
* The coordinates must be within the current building bounds or else
* directly adjacent to one of the sides, but this is not validated.
*/
Building add(int x, int y) {
if (x < 0) {
byte[] newStacks = widen(true);
newStacks[y * (width + 1)]++;
return new Building(newStacks, width + 1);
} else if (x < width) {
byte[] newStacks;
if (y < 0) {
newStacks = new byte[stacks.length + width];
System.arraycopy(stacks, 0, newStacks, width, stacks.length);
y = 0;
} else if (y * width < stacks.length) {
newStacks = Arrays.copyOf(stacks, stacks.length);
} else {
newStacks = Arrays.copyOf(stacks, stacks.length + width);
}
newStacks[toIndex(x, y)]++;
return new Building(newStacks, width);
} else {
byte[] newStacks = widen(false);
newStacks[x + y * (width + 1)]++;
return new Building(newStacks, width + 1);
}
}
byte[] widen(boolean shift) {
byte[] newStacks = new byte[stacks.length + height];
int writeIndex = shift ? 1 : 0;
for (int i = 0; i < stacks.length; i++) {
newStacks[writeIndex++] = stacks[i];
if (i % width == width - 1) {
writeIndex++;
}
}
return newStacks;
}
int toIndex(int x, int y) {
return x + y * width;
}
boolean inBounds(int x, int y) {
return x >= 0 && y >= 0 && x < width && y < height;
}
/**
* Return a stream of all legal buildings that can be created by adding a
* cube to this building.
*/
Stream<Building> grow() {
int wider = width + 2;
int max = (height + 2) * wider;
return StreamSupport.stream(new Spliterators.AbstractSpliterator<Building>(max, 0) {
int i = -1;
@Override
public boolean tryAdvance(Consumer<? super Building> action) {
while ((++i) < max) {
// Try adding a cube to every position on the grid,
// as well as adjacent to it
int x = i % wider - 1;
int y = i / wider - 1;
int index = toIndex(x, y);
if (x < 0) {
if (y >= 0 && y < height) {
if (stacks[index + 1] > 0) {
action.accept(add(x, y));
return true;
}
}
} else if (x < width) {
if (y < 0) {
if (stacks[index + width] > 0) {
action.accept(add(x, y));
return true;
}
} else if (y < height) {
// it is on the existing grid
if (stacks[index] > 0) {
action.accept(add(x, y));
return true;
} else {
// is it adjacent to a stack?
for (Direction d : Direction.values()) {
int x2 = x + d.x, y2 = y + d.y;
if (inBounds(x2, y2) && stacks[toIndex(x2, y2)] > 0) {
action.accept(add(x, y));
return true;
}
}
}
} else if (stacks[index - width] > 0) {
action.accept(add(x, y));
return true;
}
} else if (y >= 0 && y < height) {
if (stacks[index - 1] > 0) {
action.accept(add(x, y));
return true;
}
}
}
return false;
}
}, false);
}
Building reflect() {
byte[] newStacks = new byte[stacks.length];
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
newStacks[y + x * height] = stacks[toIndex(x, y)];
}
}
return new Building(newStacks, height);
}
Building rotate() {
byte[] newStacks = new byte[stacks.length];
for (int x = 0; x < width; x++) {
for (int y = 0, x2 = height - 1; y < height; y++, x2--) {
newStacks[x2 + x * height] = stacks[toIndex(x, y)];
}
}
return new Building(newStacks, height);
}
Collection<Building> transformations() {
List<Building> bs = new ArrayList<>(7);
Building b1 = this, b2 = this.reflect();
bs.add(b2);
for (int i = 0; i < 3; i++) {
bs.add((b1 = b1.rotate()));
bs.add((b2 = b2.rotate()));
}
return bs;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Building building = (Building) o;
return width == building.width &&
Arrays.equals(stacks, building.stacks);
}
@Override
public int hashCode() {
return hashCode;
}
private enum Direction {
N(0, 1), E(1, 0), S(0, -1), W(-1, 0);
final int x;
final int y;
Direction(int x, int y) {
this.x = x;
this.y = y;
}
}
public static int count(int rank) {
long start = System.nanoTime();
Collection<Building> buildings = new HashSet<>();
for (int i = 1; i <= rank; i++) {
if (i == 1) {
buildings = Arrays.asList(new Building());
} else if (Boolean.getBoolean("parallel")) {
// Using parallel streams is generally faster, but requires
// more memory since more Buildings are retained before being
// discarded
ConcurrentMap<Building, Integer> map =
new ConcurrentHashMap<>(buildings.size() * 4);
AtomicInteger atomicInt = new AtomicInteger();
buildings.parallelStream()
.flatMap(Building::grow)
.forEach(b -> {
map.putIfAbsent(b, atomicInt.incrementAndGet());
});
// Keep only the buildings that do not have a transformation
// with a lower index
buildings = map.entrySet().parallelStream()
.filter(entry -> {
int index = entry.getValue();
for (Building b2 : entry.getKey().transformations()) {
Integer index2 = map.get(b2);
if (index2 != null && index2 < index) {
return false;
}
}
return true;
})
.map(Map.Entry::getKey)
.collect(Collectors.toList());
} else {
Set<Building> set = new HashSet<>(buildings.size() * 4);
// Only add a building to the set if it doesn't already have a
// transformation in it.
buildings.stream()
.flatMap(Building::grow)
.forEach(b -> {
if (!set.contains(b)) {
for (Building t : b.transformations()) {
if (set.contains(t)) return;
}
set.add(b);
}
});
buildings = set;
}
System.err.println(i + " --> " + buildings.size());
long now = System.nanoTime();
double ms = ((double) now - start) / 1000000;
System.err.println("time: " + (ms < 1000 ? ms + " ms" : ms / 1000 + " s"));
}
return buildings.size();
}
public static void main(String[] args) {
System.out.println(Building.count(Integer.parseInt(args[0])));
}
}
```
[Try it online!](https://tio.run/##1Vptc9u4Ef7uX7HxTK@gJdGWrzOdiWynzjXTZq7XzNRp@yHjDyAJSUgoUiUgW@ydf3u6C4Dgi0hJTtrJVZOJKGCxWCyeXTwL@iN/4JN8LbKPyafPn@VqnRcaPmJjuNEyDc9mJzttcZ7Fm6IQmQ5/8I9/5mr5E18fK35QlOt8JePw1ny9zbRYiKJnxHyTxVrmGalWm1WvjNKF4CuUSFMR67xQwzJ35utQ/91mTd2zk5O5zHgKccqVgtcbmSYyW8DPJ4Cf87Mz8w1ncAvzlGstMpGAfswniVyJTKHVOHbFdSG3kM9hKeRiqRUwJQTo/G2WiG0QVjoq7Qp4IYCnj7zER0VrRqU5RAJOeSoXOMfpGNQmXoJeco3/iRLElsc6LStdc6nhUeqlzKhbFsAeZaKXY2dCAFG@ycxSonxbWXBuvteFfOBagF14VGrx4R6U5vEn9OqugMw0LBEZP@SJmA0oADP5YK@1CX1t@jdRKmPvDBY4Z9MH16NYJh6dVT9Pn8YwDazep5OWej@@tYCxMddY09SLThaIBSsTpiJb6CX8xsrB9TVczFomhFYQrltu8b1uGJipg@bavYhdcS3D2lOfOxO7o5ybcdz3U9xkO9EIbosCoeK7nbK2XxpY/ZvQm8LgAqIK0DGCXiPMohJ4Ylo4xBtEnMUXqLWI5VyiRJznBQqgtPLIfY8SjXZYbZQmuNYIBBf09YwGgAryAkSqRKUpkYUgHKMVH3lMAxD4eSYoeowdMhG4i9FGG5cA/styDQ8YFwktoA1lH6@4JkY7v7UAKJubL@fAtnAFF81G@jjkIN7uqv1Gj4uM6WIjGntDHy/0ocRVsGpnpsH9aNSWLKz3CcUeo370GOqR9bAn4yJv6A58@4xtT0pDy741tmzHBfrgagNyZCe9n@0MviuVFquQEwTjfF2yKtAuxtBd1rgdYcGuthJawdZZfOkxf9XRdGBVLkDIvndzb@E@Y9ysX6228lxX/QB43JnAEKfll0FnFzZHgnrOUXgQ1VtcyP8C2c0U5Uyz5kR5ngqegVrKuW7ub88CBkFr02wDtSb7F1IL42ZK4KQeXsEUXjaBN8e0ZBKGNIDErw7isGk06sKudlc9x2h078@JD/J@Nyxl86CxDxP0UQ/0mkqH4FQ/1bvRTAi2X5q8aqE2lBbd@GrjG6dYtV1uh2T22qTyw5pu0Jfw3Xeor3ry6cw2X3kqsPfk4mC5Gh0KPE0hFQuiEp4@GVYUo2l4BPUcbJU2c77h8WIOkmp0@wCxZPCqgvMNLIr8sUVJHJ8QBVx7hF@2AbfihDTmznzsDqw/icl2ndRin46SGsZzt05x9wtO5Da8jbAH@V6jsbaR4Xzj3UxfoXkybcxKnz@8exBFgea0Wh0NqzZZF@Vt8sCzWLCKhl@9Qg66xoXX3uGGqPdidylTAYyNRjLAbUYT@6TMdp/D@6LLQnCXBFpZwjpXkuZATmD4wAINHw/p4QoeBeIDv5t0QureAQa@6CAXkLgwjMPZoGhpRM@PEZUu2bSy@4D4EBnZPc3raLryrH54TDWuykTGJEzG93CzfzLPkW0RxuNYrDUjQmWWMbCOnnOBWNN@4aeT5/Ucw4uOZkEHHGX5z/@Hs5qM6VhsYLhgyYiJ0AWW2EqlKQIpwp7lrF@Vk4ZoXN/yFXmgmSi4PbdfHRxt6MIfTelCuSlBMuF/hVibbIRiwTEu8XnoEtMFwS4JySf0qzS/ytlxOohYVOfy9pJUBJQrVIdm2p6jd@zrd@7ZO3gY7sdJHBUurZifPCPmv8whRznhYOp77knQs9Dpr3SRJ4dbnHpTvQyS4jE0qxvHK/3lQCHmdGvIvqjKuO8pGra2aPBnEj7uFgte2ta8TfYL5a5495JhhOrPqgKnrjDaBeRzqoTems2hacBvuUZq/U3dNraZ0lFrImFdP5LEZLLfm6jj27nT3VljZDXKDGT3mcKlrjh1qJaP/4IHc0M0qpxsbiNM5w37fSMo/X5FU@KgWOyMIbp0j6EHfz0gUiEFd3QZ7C@Iv@8tgt1oZmaLpmGFkm6e8HJkSnTZK7fj2Ei1fNcuXToli/jXBoOevYs@4vog7175maoPS27s6E1RJJOTQLbBEuKXX2Ah9A/0FgA34wUOC@vfwUAWqj1fPWAZWDUGkM@6y/P3AL4arYrjHfS6uye3yOruyY/ruwLu9Vbz@p71VO3tq/3OJbvINqua6TQG/5Vd0M38GN6wKdWiY7ijlgk1/ZNNTFujDK3fJGxnPY0N0uMnG7xt8LfllE62s912ShzlwBWUcwp6TzvfxMihtJkMQ/JTc6I0xw1FyYLu8d01aMaz/L1ciWY49QZ4fVlhg5ferd0JCt2WX5pRNzVRd23s6I08e5uE6Om9PWrO6MDDFaUL1spWQTB4/fraBhYB3z2y0zUvOC4vPe2lt8iq/64I95WYu7gx9/YLkQlqLTFs0HmFvdUvENG4x6pP1yovBKwEfpWAamNhW9rvzRC3XNJruEjMqTcS2NWnLZEq5kUidqub1jtMv2ljcO8ob2DF13A9SGbInztvTXFn/Q6ESv6bgu0MftdDnlrvQ4FXv6os3@xlPcPrWSqn2zslFgwaHNK7S7TR56aXL@mea9@AvHjD4yWLYHJzgDWir8L1Rr@d30YK3cGicb2mEDexECtsvs2SPwnN9pHJp54@3MYfhVhj0Yowar7QcpeASW5eDy35g8Bqrn2q9imjF1YomOaP6HrDjvfGEa0NjS/KO7L9OQ6XKSKembGHXdi8QzJDKAT/QWUlO0C@TQKpj6FLLEy9gh9FiTbvMI1j6sAKnMaoS@cIVNnmDPuLUzPyhTtesXhxLVf24dhqdJj@/zdLxOPrmD17jj5iGGThG9oAjDCzA3vkY3tusPqPGkKdm4QdHPuyik6U@sxRQu@cNkfmJAyNd5l5K5tgeHg6Yy7PhVGMmyop3oTKfquBpxgBSekCr09dG3e46Tg83JPM1DdNYgTZF7hM@vMVOl4Ui44KlHb8aQy/6MsizhfuTRu0Z55fC336kGrD@4MvvnjcdxxRUSX0vtegjkMhRw2RYGY6RZKHhdkpTHB/TvGpC9bOdIaQZfnjfjpGnyRHnofsgYxizP4KzNCJZXQBnMP0wnxmh2w81TjDS2MgQ41XZiC8Iu1k/Eqd4rbjD6vRtKnT/VVOZ52zYYr6kMsEs6/MGB46OASLb14sVBNSzuR8o73JFSJDy25dOqfzSwn8wUjFh4t7X4s9nTydfHYT27@E@gmndHM82yA/uxEzvY1pPk8v/wM "Java (OpenJDK 8) – Try It Online") (non-parallel, up to n=12)
### Invocation
```
javac Building.java
java -XX:+UseParallelGC -Xms14g -Xmx14g -Dparallel=true Building 14
```
ParallelGC is the default on Java 8, but is included in case you are using a later version JDK where G1GC is the default.
### Output
```
1 --> 1
time: 0.410181 ms
2 --> 2
time: 97.807367 ms
3 --> 4
time: 99.648279 ms
4 --> 12
time: 101.00362 ms
5 --> 35
time: 102.4856 ms
6 --> 129
time: 105.723149 ms
7 --> 495
time: 113.747058 ms
8 --> 2101
time: 130.012756 ms
9 --> 9154
time: 193.924776 ms
10 --> 41356
time: 436.551396 ms
11 --> 189466
time: 991.984875 ms
12 --> 880156
time: 3.899371721 s
13 --> 4120515
time: 18.794214388 s
14 --> 19425037
time: 151.782854829 s
19425037
```
(For reference, \$15 \rightarrow 92{,}038{,}062\$)
[Answer]
# [Haskell](https://www.haskell.org/), \$n=16\$ in about 9 minutes
As observed by @xnor in the comments, we can break the problem down into two parts: generate polyominoes (where I reused a lot from [here](https://codegolf.stackexchange.com/a/188338/56725), then count the ways to distribute the remaining cubes.
The symmetries are accounted for by using [Burnside's lemma](https://en.wikipedia.org/wiki/Burnside%27s_lemma). So we need to know how many buildings of a given symmetric shape are fixed by a symmetry. Consider for example a shape has one mirror symmetry where the axis of reflection goes through \$s\$ squares of the shape and the reflection identifies \$d\$ pairs of further squares of the shape (so its size is \$s+2d\$). Then the buildings of this shape with \$r\$ additional cubes that have this symmetry correspond to the solutions of \$x\_1+\dots+x\_s+2y\_1+\dots+2y\_d=r\$ with nonnegative integers. The number of solutions is added to the total number of possibly equivalent buildings, and the sum divided by two. Note that a rotational symmetry always fixes zero or one square of a shape.
Compile the code with something like `ghc -O2 -o buildings buildings.hs`. The executable takes one optional parameter. If it is given, it will compute the number of buildings with that many cubes. Otherwise, it will compute all values.
```
{-# LANGUAGE BangPatterns #-}
import Data.List (sort)
import qualified Data.Set as S
import System.Environment (getArgs)
data P = P !Int !Int deriving (Eq, Ord)
start :: P
start = P 0 0
neighs :: P -> [P]
neighs (P x y) = [ p | p <- [P (x+1) y, P (x-1) y, P x (y+1), P x (y-1)],
p > start ]
count :: Int -> Int -> S.Set P -> S.Set P -> [P] -> Int
count 0 c _ _ _ = c
count _ c _ _ [] = c
count n c used seen (p:possible) =
let !c' = count n c used seen possible
!n' = n-1
next = S.insert p used
!sz = S.size next
!c'' = c' + combinations n' sz (S.toAscList next)
new = [ n | n <- neighs p, n `S.notMember` seen ]
in count n' c'' next (foldr S.insert seen new) (new++possible)
class Geom g where
translate :: Int -> Int -> g -> g
rot :: g -> g
mirror :: g -> g
instance Geom P where
translate !dx !dy (P x y) = P (x+dx) (y+dy)
rot (P x y) = P (-y) x
mirror (P x y) = P (-x) y
instance (Geom g, Ord g) => Geom [g] where
translate !dx !dy = map $ translate dx dy
rot = sort . map rot
mirror = sort . map mirror
normalize :: [P] -> [P]
normalize fig = let (P x y) = head fig
in translate (-x) (-y) fig
-- fixed points of horizontal mirror symmetry
myf :: Int -> Int -> [P] -> Int
myf r sz fig =
let w = (maximum [ x | P x _ <- fig ])
wh = w `div` 2
myb = sum [ 1 | P x _ <- fig, x == wh ]
in if even w -- odd width!
then c12 myb ((sz-myb) `div` 2) r
else c1h sz r
-- fixed points of diagonal mirror symmetry
mdf :: Int -> Int -> [P] -> Int
mdf r sz fig =
let lo = minimum [ y | P _ y <- fig ]
mdb = sum [ 1 | P x y <- fig, x == y-lo ]
in c12 mdb ((sz-mdb) `div` 2) r
combinations :: Int -> Int -> [P] -> Int
combinations r sz fig =
let rotated = take 4 $ iterate (normalize . rot) fig
rfig = rotated !! 1
mirrored = map (normalize . mirror) rotated
alts = tail rotated ++ mirrored
cmps = map (compare fig) alts
-- All fixed points computations assume that the symmetry exists.
-- fixed points of quarter turn:
qtfc = if even sz then c1q sz r else sc1x 4 sz r
-- fixed points of half turn:
htfc = if even sz then c1h sz r else sc1x 2 sz r
-- fixed points of reflections:
mirror_fc = [ fun r sz f |
f <- [ fig, rfig ],
fun <- [ myf, mdf ] ]
-- all possibilities, i.e. fixed points of identity:
idfc = c1 sz r
fsc = [ qtfc, htfc, qtfc] ++ mirror_fc
-- fixed points of symmetries that really exist:
allfc = idfc : [ fc | (fc,EQ) <- zip fsc cmps ]
-- group size of symmetry group:
gs = length allfc
res = if r==0 then 1 else sum allfc `div` gs
in if any (GT ==) cmps
-- only count if we have the smallest representative
then 0 else res
-- Number of ways to express t as sum of n nonnegative integers.
-- binomial(n+t-1, n-1)
c1 n t = foldl (\v x -> v * (n+x-1) `div` x) 1 [1..t]
-- Number of ways to express t as twice the sum of n/2 nn-integers
c1h n t | even t = c1 (n `div` 2) (t `div` 2)
| otherwise = 0
-- Number of ways to express t as four times the sum of n/4 nn-integers.
c1q n t | t `mod` 4 == 0 = c1 (n `div` 4) (t `div` 4)
| otherwise = 0
-- Number of ways to express t as an nn-integer plus m times the sum
-- of n/m nn-integers
sc1x m n t = c1 (1 + n `div` m) (t `div` m)
-- Number of ways to express t as the sum of s nn-integers
-- plus twice the sum of d nn-integers
c12 s d t = sum [ c1 s (t-2*t2) * c1 d t2 | t2 <- [ 0 .. t `div` 2 ] ]
count_buildings :: Int -> Int
count_buildings n = count n 0 S.empty S.empty [start]
output :: Int -> IO ()
output n = putStrLn $ show n ++ ": " ++ show (count_buildings n)
main = do args <- getArgs
case args of
[] -> mapM_ output [1..]
[n] -> output (read n)
```
[Try it online!](https://tio.run/##jVdZb@M2EH73r5jsFlhpfdQ28mTUC6RoEBTYI4Xbp9RIFImWiZUoRaQPpelfb/oNSdly7OxuAlv0cI5vTlLLSH8VWfb8/E//LX28@Hz118XVJf0aqfQ6MkZUStPb/r@djszLojL0W2SiwUepDQUav8OG/rCKMrmQInEcM2Eo0jRrtme1NiIfXKq1rAqVCwX5VJiLKtVhp5NAhK5pis/Z79iyX4mo5FqqlILLhx59qRIwahNB2WRC137JIkMadjpKyHSp7Rb1P9DN9bwhBde0pToE6w2V9ITPL33sU7DtjkKqe8TLfrPcUlCD3ixBn/c6dPqvpA/kYMw7nbhYKQuNsQOBf8xsKK5fLAHP83i5IcV0a/@nFHvarafdzJlInqqwXGnEWQuhKCgnZaG1vM8EPATQDCbO4ncscYK94fUenSlmVP2R/63ElkM6G0ilBdwqrWjDrB/tnpaPwnI29PidNfeOurCZ30sVGVmgbKAcIsFsYIoLHduaYbFwZ2xjc6KQE8U58fkqe/h5NxuownwS@b2o7hz2OeSkatx6R2zWAg4WRZZUe9SWG9pDCvDd7e4ChCRlkdZ0JYqcUtosRcWRMFWkdBYZcZy91H6Bpypsbne/c1lVRdUidWDcRCoWTvv1Ce1nyRafulWQtgiTbcg1l9Sht3Ow38diuzd4uAfJumU5cI7ZZqEUTB8cmJt0/g04U8qjkn5q7WAjqT2YKXGb08AygbCHcrDjaGjDosoxCB5tLH2V217c0RcyhSiX6d6XpYgS3jhqNOR7D8v6awPCrJ1@H88tKrsspDKaigUti0o@FspEWQNS13kuTFV38npxnN5WG/J@xfVq8flG4gIN8mgr8xWiCLRPdizccrUy37yp5c0SnBu6S@T6jsaemNf3HCQrOnoh2sN6OmU5X9ZyQWKNut0Q/CqShDYyMcszcrrMElvxaGx1BoF@7GMRNvZCqhybyLQA25L9qE5GKJFRWqhT8Um@E5/kRHyygqtHKh@f2jp5i2cTnyYSyXEk6sNI1H0oa1qcHU0aR5NDRzsHM@ZbkA8Y99jJg0cxo6oSEEz0VdA5WkDivLOVti/XAfOFreKsnJJG@uyMmunpQmo1ckscKHF7YSPmJaIMWWH7Mtsp7HZ3ijxXnJe60QmfyqiyXRRacc@DVF9k2WG6mXdlvP@Ye6tcoJAiw9W0SzyJLQazHuz1vCwZnOwV4kJmVamJZ3swixiQmqJFaH2FPtjSc4Wo49EWYbWE19Uvo2xxoHv5mu7lS91jV@evqq7EIhOx9X9ykKNba@GGFivlC4OeTh7yC3z4tuAK1ab@lesAq7KcGCQ94m6ZM3m@RxchP@4okpk0UugeyYEYHKGWCW5H0tQNZJlYtPGo7e1COw84ET0bsp5dz/f1AydfD41PP1C4kqgE4PlimOyqM3OZYAATDkKM3g1g6vKPkJ19lKUFYgu05WlaFauS7D1hb6p25EZ5qu0poFKzdIaa9hLaJb@aTocu8yOfcowPB8lNg1TvJmekcKpe/Yk5EloweyiFglfuygC@jUC5rYVrAPRmJjS7XsIoYo5OWTc3I2t46AwzJDtMP6/4OsI@baIagSsQL5bFki@7DBB7uHsUSonUqgNAI1JRocGgAOOoyGWUBapr@qMe37zCDhKLUw5O8zUmo@DvNSYiRtia3mOGdO3V1HmM429EN6PBwMx/BI/ZyNj76pH9PCal@g2kDrcUm35ynWbYcVtogdpP3MDs1rvCf6ICaquNRHSmfPv@PphFscIIkbktuBai8zaiQYcniIMEs3mR3GGA4HQYvsB13sJ1fhoXOW9@CFykWiiozFaa8kOwrMTizQ8iaMdQ7vPHAEe4BDcg8xbIPPyhjO0jow/sQNSiOkpp8iKhGImgmd1py1MDKPrj9wa5fM@/sT3m@I7dvBrSYEC7HGNqNe8yt/crmSV4AXtxyh7tqtbLxhDXcJGXpt49b@wbEpQWK4PjqK3rCwVhQ2YleM5M9VHhJNbLYgMahtmbCb3hp6UER7YR1zySLJ0UFOF1kr3yb5atQR1HKAm7XSwO5jderhgLDtdPt@SxcIvND7mUvVX4/aDi@ypMPz8/j8b/xYssSvVz/8v4fw "Haskell – Try It Online")
### Results
```
15: 92038062
16: 438030079
17: 2092403558
18: 10027947217 (2 1/2 h)
19: 48198234188 (10 h)
20: 232261124908 (40 h)
```
[Answer]
# Java 11, \$n=17\$ in about 8.5 minutes
### Based on [Haskell solution by Christian Sievers](https://codegolf.stackexchange.com/a/199919) – upvote his!
This answer is the result of learning enough Haskell to be able to understand Christian's answer, translating it into Java, applying numerous micro-optimizations, and throwing multiple cores at it. The exact runtime varies significantly depending on the number of cores available; this timing result is from my own two-core machine. A 48-core EC2 c5.24xlarge is able to compute \$n=17\$ in 16 seconds, and \$n=20\$ in 18 minutes.
Parallelism can be disabled by adding the JVM argument `-Djava.util.concurrent.ForkJoinPool.common.parallelism=0`. Single-threaded performance is slightly better than double that of the Haskell solution.
Some of the optimizations include:
* Representing a point using a single int value
* Using simplified hand-rolled collections based on int arrays, avoiding the primitive boxing required for the standard Java collections
* Reimplementing polyomino enumeration based on [this paper](https://doi.org/10.1016%2F0012-365X%2881%2990237-5) -- my initial attempt at a direct translation of the Haskell code performed extra throwaway work that didn't actually contribute to the computation
* Replacing higher-level [Stream](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/stream/Stream.html)-based implementations with inlined code, making it very ugly and verbose
The bulk of the processing time is spent in `Array.sort` calls in `normalizeInPlace`. Finding a way to compare polyomino transformations without sorting could easily result in a further 4x speedup. The forking is also not done very intelligently which leads to unbalanced tasks and unused cores at higher levels of parallelism.
```
import java.util.Arrays;
import java.util.concurrent.RecursiveTask;
import java.util.function.IntPredicate;
import java.util.function.IntUnaryOperator;
import java.util.function.LongSupplier;
import java.util.function.ToLongFunction;
/**
* Utility methods for working with an int that represents a pair of short values.
*/
class Point {
static final int start = p(0, 0);
static final int[] neighbors = new int[] {-0x10000, -0x1, 0x1, 0x10000};
static int x(int p) {
return (p >> 16) - 0x4000;
}
static int y(int p) {
return (short)(p) - 0x4000;
}
static int p(int x, int y) {
return ((x + 0x4000) << 16) | (y + 0x4000);
}
static int rot(int p) {
return p(-y(p), x(p));
}
static int mirror(int p) {
return p(-x(p), y(p));
}
}
/**
* Minimal primitive array-based collections.
*/
class IntArrays {
/** Concatenates the end of the first array with the beginning of the second. */
static int[] arrayConcat(int[] a, int aOffset, int[] b, int bLen) {
int aLength = a.length - aOffset;
int[] result = new int[aLength + bLen];
System.arraycopy(a, aOffset, result, 0, aLength);
System.arraycopy(b, 0, result, aLength, bLen);
return result;
}
/** Adds a new value to a sorted set, returning the new result */
static int[] setAdd(int[] set, int val) {
int[] dst = new int[set.length + 1];
int i = 0;
for (; i < set.length && set[i] < val; i++) {
dst[i] = set[i];
}
dst[i] = val;
for (; i < set.length; i++) {
dst[i + 1] = set[i];
}
return dst;
}
private static final int[] primes = new int[] {
5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61,
67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131
};
/**
* Allocate an array large enough to hold a fixed-capacity hash table
* that can contain "seen" points for generating polyominos of size n.
*/
static int[] makeHashTable(int n) {
return new int[primes[-(Arrays.binarySearch(primes, n * 3) + 1)]];
}
/** Inserts a new value to a hash table, in-place */
static void hashInsert(int[] table, int val) {
int pos = (val * 137) % table.length, startPos = pos;
if (table[pos] != 0) {
while ((table[pos = (pos + 1) % table.length]) != 0) {
if (pos == startPos) {
throw new AssertionError("table full");
}
}
}
table[pos] = val;
}
/** Checks whether a hash table contains the specified value */
static boolean hashContains(int[] table, int val) {
int pos = (val * 137) % table.length, startPos = pos;
while (true) {
int curr = table[pos];
if (curr == val) return true;
if (curr == 0) return false;
pos = (pos + 1) % table.length;
if (pos == startPos) {
throw new AssertionError("table full");
}
}
}
}
/**
* Recursively generates int arrays representing collections of Points,
* applying a function to each array to compute a long, and returns the sum
* of all such values.
*/
class PolyominoVisitor extends RecursiveTask<Long> {
PolyominoVisitor(ToLongFunction<? super int[]> func, int n) {
this(func, n, 0, 1, new int[0], IntArrays.makeHashTable(n), new int[]{Point.start});
}
private PolyominoVisitor(ToLongFunction<? super int[]> action, int n,
int i, int limit, int[] used, int[] seen, int[] untried) {
this.func = action;
this.n = n;
this.start = () -> visit(i, limit, used, seen, untried);
}
private final boolean visitSmaller = true;
private final ToLongFunction<? super int[]> func;
private final int n;
private final LongSupplier start;
@Override
protected Long compute() {
return start.getAsLong();
}
private long visit(int i, int limit, int[] used, int[] seen, int[] untried) {
long val = 0;
if (used.length + 1 == n) {
// reached the second to last level, so we can apply the function
// directly to our children
for (; i < limit; i++) {
val += func.applyAsLong(IntArrays.setAdd(used, untried[i]));
}
} else if (used.length + 6 < n && limit - i >= 2) {
// eligible to split
PolyominoVisitor[] tasks = new PolyominoVisitor[limit - i];
for (int j = 0; j < tasks.length; j++) {
tasks[j] = new PolyominoVisitor(func, n,
i + j, i + j + 1, used, seen, untried);
}
invokeAll(tasks);
for (PolyominoVisitor task : tasks) val += task.getRawResult();
return val;
} else {
// recursively visit children
int[] newReachable = new int[4];
IntPredicate inSeen = p -> !IntArrays.hashContains(seen, p);
for (; i < limit; i++) {
int candidate = untried[i];
int[] child = IntArrays.setAdd(used, candidate);
int reachableCount = neighbors(candidate, inSeen, newReachable);
int[] newSeen = seen.clone();
for (int j = 0; j < reachableCount; j++) IntArrays.hashInsert(newSeen, newReachable[j]);
int[] newUntried = IntArrays.arrayConcat(untried, i + 1, newReachable, reachableCount);
val += visit(0, newUntried.length, child, newSeen, newUntried);
}
}
if (visitSmaller && used.length > 0 && limit == untried.length) {
val += func.applyAsLong(used);
}
return val;
}
/**
* Write the greater-than-origin neighbors of the given point
* that pass the provided predicate into the provided array,
* returning the count written.
*/
private static int neighbors(int p, IntPredicate pred, int[] dst) {
int count = 0;
for (int offset : Point.neighbors) {
int n = p + offset;
if (n > Point.start && pred.test(n)) {
dst[count++] = n;
}
}
return count;
}
}
/**
* Function that computes how many buildings are constructable on a given
* polyomino base. Considers symmetry, returning 0 if the figure is not the
* canonical version (i.e. has a smaller transformation).
*
* Adapted largely unchanged from Christian Sievers
* https://codegolf.stackexchange.com/a/199919
*/
class BuildingCounter implements ToLongFunction<int[]> {
private final int n;
public BuildingCounter(int n) {
this.n = n;
}
@Override
public long applyAsLong(int[] fig) {
return combinations(n - fig.length, fig);
}
private static int[] map(int[] fig, IntUnaryOperator func) {
int[] result = new int[fig.length];
for (int i = 0; i < fig.length; i++) {
result[i] = func.applyAsInt(fig[i]);
}
return result;
}
private static int[] normalizeInPlace(int[] fig) {
Arrays.sort(fig);
int d = fig[0] - Point.start;
for (int i = 0; i < fig.length; i++) {
fig[i] -= d;
}
return fig;
}
private static int[] rot(int[] ps) {
return normalizeInPlace(map(ps, Point::rot));
}
private static int[] mirror(int[] ps) {
return normalizeInPlace(map(ps, Point::mirror));
}
private static int myf(int r, int sz, int[] fig) {
int max = Integer.MIN_VALUE;
for (int p : fig) {
if (p > max) max = p;
}
int w = Point.x(max);
if (w % 2 == 0) {
int wh = w / 2;
int myb = 0;
for (int p : fig) {
if (Point.x(p) == wh) myb++;
}
return c12(myb, (sz - myb)/2, r);
} else {
return c1h(sz, r);
}
}
private static int mdf(int r, int sz, int[] fig) {
int lo = Integer.MAX_VALUE;
for (int p : fig) {
int tmp = Point.y(p);
if (tmp < lo) lo = tmp;
}
int mdb = 0;
for (int p : fig) {
if (Point.x(p) == Point.y(p) - lo) mdb++;
}
return c12(mdb, (sz-mdb)/2, r);
}
private static long combinations(int r, int[] fig) {
int[][] alts = new int[7][];
alts[0] = rot(fig);
alts[1] = rot(alts[0]);
alts[2] = rot(alts[1]);
alts[3] = mirror(fig);
alts[4] = mirror(alts[0]);
alts[5] = mirror(alts[1]);
alts[6] = mirror(alts[2]);
int[] rfig = alts[0];
int[] cmps = new int[7];
for (int i = 0; i < 7; i++) {
if ((cmps[i] = Arrays.compare(fig, alts[i])) > 0) {
return 0;
}
}
if (r == 0) {
return 1;
}
int sz = fig.length;
int qtfc = (sz % 2 == 0) ? c1q(sz, r) : sc1x(4, sz, r);
int htfc = (sz % 2 == 0) ? c1h(sz, r) : sc1x(2, sz, r);
int idfc = c1(sz, r);
int[] fsc = new int[] {qtfc, htfc, qtfc,
myf(r, sz, fig), mdf(r, sz, fig),
myf(r, sz, rfig), mdf(r, sz, rfig)};
int gs = 1;
int allfc = idfc;
for (int i = 0; i < fsc.length; i++) {
if (cmps[i] == 0) {
allfc += fsc[i];
gs++;
}
}
return allfc / gs;
}
private static int c1(int n, int t) {
int v = 1;
for (int x = 1; x <= t; x++) {
v = v * (n+x-1) / x;
}
return v;
}
private static int c1h(int n, int t) {
return c1d(n, t, 2);
}
private static int c1q(int n, int t) {
return c1d(n, t, 4);
}
private static int c1d(int n, int t, int q) {
if (t % q == 0) {
return c1(n / q, t / q);
} else {
return 0;
}
}
private static int sc1x(int m, int n, int t) {
return c1(1 + n / m, t / m);
}
private static int c12(int s, int d, int t) {
int sum = 0;
for (int i = t/2; i >= 0; i--) {
sum += c1(s, t-2*i) * c1(d, i);
}
return sum;
}
}
public class Main {
public static long count(int n) {
return new PolyominoVisitor(new BuildingCounter(n), n).compute();
}
public static void main(String[] args) {
if (args.length > 0) {
System.out.println(args[0] + ": " + count(Integer.parseInt(args[0])));
} else {
for (int i = 1; i <= 99; i++) {
System.out.println(i + ": " + count(i));
}
}
}
}
```
### Invocation
```
javac Main.java
java Main 17
```
[Try it online!](https://tio.run/##tVp9b9s2Gv8/n4IrsEGqZcd20mZpXna9YsMV6G7Fsu4OKIyDLNE2E1lSRTm228tn7/0ekpJFmXKyDWeglU0@b3zeHyq34X3Yv43vvn4VyzwrSnaLhcGqFMngdVGEW3lxtLcRZWm0KgqeloNfOb5Jcc9/C@WdA3S2SqNSZOngbVq@L3gsorDkj8B9SMNi@0vOi7DMikOw77J0frPK80Twg3C/ZQT5k/l5cXR0/Pz5EXvOPgBKlFu25OUiiyWbZQVbZ8WdSOdsLcoFC1Mm0pKVi7BkBc8LLnFmyUKWh6Jg2YzJBbG8D5MVlwOQPD6KklBK9j4jvC9HDB9ZhqWI2EykYaLIYQFIVyz3hgEb@hdOqI8TlnIxX0yzQgI25Wuz@qU/3IyG@ASMvoGC@Y/WHnC4BjXitvHo/9w30tCn4OWqSJmXs@trNnrpsz7wT4GuRXnYo7HtpqE04Hv540RyRWQTaIouWt6G9QwRn11eKtH@y7ztbrWLdpGVnSLmXn8L@QJoIvc7KSxFUWTFISIbRWTbJPJQu9LPIhVLWC4vxFKUiAcWUvT0p6HkMYuyJOHK@Swvga/rGDP8QIu9QWwhRFL8k3A8zngak6fR15koZKkJa/@kxSmfizQllzVQkiM@4wGxsc8I51G4moVnVrQ9wl9mM8nLwMBN9er0HU@bylCQWJuD9xULB4n@2q/QL5qQIIOAWSVlw30r5J4iPdnB32xlyZcDJV@U5VsPctUyaTJw8qDi7h/AnCrACscgBPosF227ajDLKcgKr@OYwpzEVsHNygw/JVwd1jQyET6pnXROgOawLrUDAxS9@ofWLii3lIvdWDb1BdhKyT02mlj6ZQKAw90SZS/vAquXrIH23Xf066OYYBkMsd/rNbnSBzwJ4MpA7kg@HO2BEI3DLLtZqDMcZGOsAmjLJIiqewSEK0lSwPFWhrQ4vwjYWcBGyJGjE/yj7@cBG@P7GM8TrJ9g7RTPU6yd4vsLPF9g7@UosCi9xN4Z4M6wf4b97/H8Hs9zojkkBkPiMFQ/z4kn/RzTz5ORPs5F7WKaMjwtSTIKeKo1OrKTsJhT2Ger@YL8bpElMZxvJjY87kdhHkZUsxahxG44TXhFCVFfhkK55DPJefqM5VSFdFmb85TqKW3mWbLNliLNpKpg4jPcd2CIOHx3Gd7xf4DZb8RL5cfUkR8r7WtzfOx7OrENpoKK@Q0Pi2jh6c2ApZD2xCdv8CeTvdh7m0pelI7w2x2Z4qefJ2HEWyLfZyJWcJqIibgaxxVz0Ae5j4cdiDU6OfPZtxrD@HOgC/Z7BQbgRhDOmKcgP2J5wr5BOLb9fr0QCUdlq8GIFT3o8C1GE99JouKkkK9qYVxg9CkXRbZWqnstSQcoOj@q0vZM8WKzVZI8ayTC/SC0f@2@NY7ayAMNy71Z8OhO4szop3hhWazyTl3TZM4jMRPIpdq8thGnWZZwhANhvzFo/2dLGjOVxYq39UqEqdsFyk4BtvrIOhrkSotlgoLIdUMOa7hZmMgW4GFP2Sf6BOf4M47RdoNmy1O3/sm2Si9IxKpF0E1N3TFT1mm0QJR2VIMsA6ITooHfEghynGnRKd55GC1MRsSvKFvmK8qSLEErj7KOrkhrz3jUakm0QDlMEvwCrqsrN5nvdyEFZgvGN@i0UOmtKeaShoVro8A2imfPEpc/gBcmFZ0rr9UBtHtaSbJcCOnpvVR1JygWVcYcToJdIziws23q7@AmX5TOBsrED76zPv5BaUO1auQNnNnECgOhQRNqcatOcYX@NqjbHJ7W62lZIMDbWlBDGfWOZhSz9lIq4621aljyMGBcs3s6lwc5jAyau@ZbcXRqRrcMVWZRZG7QrydcxXUdpzb447Z2YSltujaa46qOVNMO/O2Xe14UIuYGKSsRKUiOhFB5vucouorGYI7mUhKo5z46BUyluL9uRE0Np7F6T0pBRKTRrFI6Stt56PgYsiOwcbjdqELxjfiETBzJBObM2BoFgxoiSg169DFGaFOLRQFdJSpHZKuCRUjkccFtuEabqo7t7FDpQ@fqXSlmA8XbKHYXn6aT1woz6kEv63fnTcaR3B0KeglpUmrPlUiYoQS7vmJjh8Z4IuaCMjTOKOE9pQXQjnlVJeVd1RLvbdfsWkVMKYk841aZFo9LTahu62/dSlNAH28nHQzrvNeZX2guuA30gzynK6yPutsVkd5ndxy9tKek8R1H20v@BMleafH9yvT0iyLq13D9q5rnvBYtE3rWGGRs7HD1XYVUAeh2z@q2BxwRGqoW78aZ05aZmvdoALiBjqiZoeT4zc5NrdZJ6zF3KeUpQaEaINRbERPLq4bXX7hgcRR1SkB2hE1NzHcS0BmC1PAmAy@lC3MR5tWogTl7YOnN75IIQEZTpIxBhCzGPQe0KwhscUwY2Ko204bhYsuEyDgk1getTUtbzVsao20dHiObdNCSzcHHuLVO/8OgwbHuiZW1AtYU/oNVSg/NBJTXrGqKhNbMc9dsuMtxV7XzmO22u3XlX6LoH7gvcAwj1VT8r0LAa6mEzKGskhf9chGm/axATk0bV6zm8myOaE314FxRULe/OfWPBIDqfI9KHePLLgqRmK09ZcCgImBfFUXKqdcQC72nPXe3rjlUI1G7vhpwAjv@SYZgd3HUnociEz/tSyLay9TdGvKf7iprPq7xR2eYnsHZHz5SmLnRnJLBSbIB5gEEhe9KKnQfpMTr9SZ219flacbUCmn//vWnenIga5meSbIFJp5lmG7ZdAUnhwkkbKOGUYmmL9KDD7BCbXiiVF@PMLq7HdCFrIRR4SJyu1zystg2L/@GpAB9NztfgbKQLM3ojQEnWkhXWQpTJQwNniTxPDEATeQMuk40IVMWYSphmGVIJ/BpYiHk13GYUxeo7oNQQXBCeO4cK7MiW2LYLoQsBbqkG8GJPOEsyjKXr46Poyzm8yyZkUGiO77RmAPo5Tg8Hp2fn4/OG3PR341yVBKhBneZJ3ypXnW0WmDT@n7pbnv1zmqawIFbdD3nXNTs@h@c/bAmphrPZlLQbg@9OzpjHJRuntS4CffsE1id8Ajl0PVide@V71iouLPeS6kktX99u3fjvWM8cUShvsJVRXgH6KzEmrC@g23mR8jlAZV60AMJ0nHN7Tx0Sl6YiM/8bfqertfcSq6KelYo3r59LU21jCQaTqD3Rlr4S8fXR2T9KxYfOCagHj@jeVdEd8fSdZPZVgE5Qi4DfZRXr4DuP8V96vdJf5aRpvAoL7bczpQyCz3Yyc9VRWhZTcGGG91p8DkvBj@//ed/fn/97sOPDtPkKA0tAvVdE9I9CPmGWu4yCJFYY1Pbf@MRvD0urtm3bGzuwfZLzppeMK3ZMRtf7O0tt1O7qD1F8IptJVDuE@81WhCQ6/UuDgwXVU4ZjT3ABsyTn@HZ@Oofj1EL/EcGgRp94ZFtir04PWDa@OmmTbKmZV//@w9bll50L/PaZvSic7/UEwQGhszX/PCzy/rLeNrRehxwLds6O0Ggb@IJmk1T7TcHZKJYm6iPL5aB3GpOzB3LrlzsFO5U9McJvTVNyuY7pzOs7cSiTcp@VyrV2AlS7Y2qPQPZ3h9b@6O9/RPaNwnGQf60sd3B4UUbZJ/JyzbIeOLvvd8Fd7rM00zau9Eyt5V0uAKcORM/eYVHlHTpM6WHGjw0cp4qzYo93cHQtOGKe@Mdw6eNM4UzKRkaoy53R064ahYxa/NTOaNLT0ocu6T3A9z1k0kJiAgZjTbeacDaOYLwF134ixb@2I0vYoUfjTzHLnm5jOw3qCRwoNgGSvj9yxuqOoXmRi4YqFzVXDiEUeyhqJUHW@o5ec/IXkPHrI5CJ3qkoZDRoYZCvYmp3KrjrZtmRgOpjJzXHXPZXTn2kpOmdgykxyo67KSv5HVSbmf6e1st9eE3ah2PSyRmPPcPTZj3GBO8tLfpj3wIszk0VT8u56JT0Dojxx62y4CN/cfJfXo6udMnkIstcvrxydImVTSE1KdDIQ9rpNDUJ7ClxxPL/fDpVV5FriqZ1auYA@f3RhjESZ6llmf5BD2MFXWpycYdXiVXy456TUFVHo8v9A01hVe/39YVYfd0hoFc/fFz4dP8O/KI3aHJBIiNad7Menos/TkUaTVq6nW7ZmOoPPj3CHs30bTYnknVKzZ/UL9lsbVpsVV/XLCEUN5NWYCE@nuquWw7FK01rr/amjJ/r5StygGMlZZJqjCoYeixZ6/YMzz02apmDpVOcprzDJzvP@aDlulGKh9esfPzziteh0yiLY3wH383/PXr19H4fw "Java (JDK) – Try It Online")
### Results
(when run without an argument)
```
...
16: 438030079
17: 2092403558
18: 10027947217
19: 48198234188
20: 232261124908
21: 1121853426115
```
] |
[Question]
[
>
> A Primenary (*binary-prime*) string is one which, when written as a binary grid, every row and column has a prime total.
>
>
>
That's quite a vague explanation, so let's break it down with a worked example...
---
For this example we'll use the string `bunny`:
First, find the ASCII code point of each character and its binary representation:
```
Char | ASCII | Binary
b 98 1100010
u 117 1110101
n 110 1101110
n 110 1101110
y 121 1111001
```
Take these binary values, from top to bottom, and arrange them into grid (adding leading zeros if necessary):
```
1 1 0 0 0 1 0
1 1 1 0 1 0 1
1 1 0 1 1 1 0
1 1 0 1 1 1 0
1 1 1 1 0 0 1
```
Then, count the number of `1`s in each row and column:
```
1 1 0 0 0 1 0 > 3
1 1 1 0 1 0 1 > 5
1 1 0 1 1 1 0 > 5
1 1 0 1 1 1 0 > 5
1 1 1 1 0 0 1 > 5
v v v v v v v
5 5 2 3 3 3 2
```
If, and only if, every single total is prime (such as here) then the string is a valid binary-prime.
---
# The Challenge
Your task is to create a function or program which, when given a string, returns/outputs `truthy` if the string is primenary, and `falsy` otherwise.
**Rules/Details**
* You may assume that the string's characters will always be in the ASCII range `33-126` (inclusive).
* The string will not be empty.
* A primenary string does **not** have to have a prime length - for example, `W1n*` is valid, despite having 4 characters.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer (in bytes) wins - but all submissions are welcome.
* Standard loopholes are banned.
---
# Test Cases
```
'husband' -> True
'HOTJava' -> True
'COmPaTIBILE' -> True
'AuT0HACk' -> True
'PPCW' -> False
'code-golf' -> False
'C++' -> False
'/kD' -> False
'HI' -> False
'A' -> False
```
There is also a working, but incredibly verbose [**Python example on repl.it**](https://repl.it/EPcM/1) that you can test your solution against.
[Answer]
# MATL, 10 bytes
```
BtXsw!shZp
```
[Try it online!](http://matl.tryitonline.net/#code=QnRYc3chc2hacA&input=J0hlbGxvIFdvcmxkJw)
This is the ideal language for the job. It's pretty much a literal transliteration of the challenge specification.
```
Bt % Converts input to binary matrix, duplicate
Xs % Sum columns (alternative X version to prevent defaulting to sum along first non-singleton dimension, thanks @Jonathan Allan)
w! % Get the duplicate to the top of the stack, transpose
s % Sum again
h % Concatenate horizontally
Zp % Check primality element-wise. Display implicitly.
```
Since any zero makes a MATL array falsy as per [meta](http://meta.codegolf.stackexchange.com/a/2194/32352), nothing else is needed - basically, an implicit `A` is called on `?` (if).
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~13 12~~ 11 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
OBUZ;$S€ÆPẠ
```
**[TryItOnline!](http://jelly.tryitonline.net/#code=T0JVWjskU-KCrMOGUOG6oA&input=&args=YnVubnk)** or [all test cases](http://jelly.tryitonline.net/#code=T0JVWjskU-KCrMOGUOG6oArFvMOH4oKsS1k&input=&args=WyJidW5ueSIsICJodXNiYW5kIiwgIkhPVEphdmEiLCAiQ09tUGFUSUJJTEUiLCAiQXVUMEhBQ2siLCAiUFBDVyIsICJjb2RlLWdvbGYiLCAiQysrIiwgIi9rRCJd)
### How?
```
OBUZ;$S€ÆPẠ - Main link: word e.g. ha!
O - cast to ordinals e.g. [104,97,33]
B - convert to binary e.g. [[1,1,0,1,0,0,0],[1,1,0,0,0,0,1],[1,0,0,0,0,1]]
U - reverse each entry (say "b") e.g. [[0,0,0,1,0,1,1],[1,0,0,0,0,1,1],[1,0,0,0,0,1]]
$ - last two links as a monad
Z - transpose e.g. [[0,1,1],[0,0,0],[0,0,0],[1,0,0],[0,0,0],[1,1,1],[1,1]]
; - concatenate with "b" e.g. [[0,1,1],[0,0,0],[0,0,0],[1,0,0],[0,0,0],[1,1,1],[1,1],[0,0,0,1,0,1,1],[1,0,0,0,0,1,1],[1,0,0,0,0,1]]
S€ - sum €ach e.g. [2,0,0,1,0,3,2,3,3,2]
ÆP - is prime (1 if prime, 0 if not) e.g. [1,0,0,0,0,1,1,1,1,1]
Ạ - all truthy? e.g. 0
```
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 17 bytes
```
Çžz+b€¦€SDøìO0ÛpP
```
[Try it online!](http://05ab1e.tryitonline.net/#code=w4fFvnorYuKCrMKm4oKsU0TDuMOsTzDDm3BQ&input=QXVUMEhBQ2s)
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), 15 bytes
```
O+⁹Bṫ€3µS€;SÆPP
```
[Try it online!](http://jelly.tryitonline.net/#code=TyvigblC4bmr4oKsM8K1U-KCrDtTw4ZQUA&input=&args=YnVubnk) or [Verify all test cases.](http://jelly.tryitonline.net/#code=TyvigblC4bmr4oKsM8K1U-KCrDtTw4ZQUArDh-KCrA&input=&args=WydidW5ueScsICdodXNiYW5kJywgJ0hPVEphdmEnLCAnQ09tUGFUSUJJTEUnLCAnQXVUMEhBQ2snLCAnUFBDVycsICdjb2RlLWdvbGYnLCAnQysrJywgJy9rRCdd).
## Explanation
```
O+⁹Bṫ€3µS€;SÆPP Main link. Input: string z
O Ordinal, get ASCII value of each char
‚Åπ Nilad representing 256
+ Add 256 to each ordinal value
B Binary digits of each
ṫ€3 Tail, take each list of digits from the 3rd value to the end
These are the last seven digits of each
µ Start a new monadic chain
S€ Sum each list of digits by rows
S Sum by column
; Concatenate
ÆP Test if each is prime, 1 if true else 0
P Product
```
[Answer]
# Mathematica, 75 bytes
```
And@@Join@@PrimeQ@{+##&@@#,+##&@@@#}&@IntegerDigits[ToCharacterCode@#,2,7]&
```
Unnamed function taking a string as input and returning `True` or `False`.
`ToCharacterCode@#` converts the input into the list of its ASCII values; `IntegerDigits[...,2,7]` turns each value into the list of its bits, padded to length 7 if necessary. So now we have a 2D array and we want all its row sums and column sums; lo and behold, the character-spasm `{+##&@@#,+##&@@@#}&@...` does exactly that (it applies the `+##&`, "sum all arguments", function to the list of vectors in the first coordinate using `@@`, and to each vector as its own list of integers in the second coordinate using `@@@`). Then we just check whether the results are `PrimeQ`, flatten the list with `Join@@`, and take the `And` of all those values.
[Answer]
# [Ruby](https://www.ruby-lang.org/) `-rprime`, 100 bytes
```
->s{a=s.bytes.map{|b|b.digits 2}
a.all?{|r|r.sum.prime?}&([0]*7).zip(*a).all?{|c|c.count(1).prime?}}
```
[Try it online!](https://tio.run/##Nc1Na4MwGADg@/srPIyiLabdLju1xbqBlkE9CDuUUpIYNdSYkI@NzvjXl8HY7g882pF7aLch3ZkJbw0id8sMElhNnniCGt5xa6KnGTDCw7CfvPYaGSeQ0lyw/byIz5vL8jlBX1zFS5z8KeopotKNNn5M/ukcVNSeH66I9lKoy2fPBxZ1zJrQO0Pw2EBxqo/4A0N@EhWuy0P59gqZqzdFlt@gqvJ3oLJhaSeHFvLVCta3FyhKyL6lslyOJqT69/oB "Ruby – Try It Online")
**Explanation**
```
->s{
a=s.bytes # Get byte values from string
.map{|b|b.digits 2} # For each, map it to its binary digits
# (least significant digits first)
a.all?{|r|r.sum.prime?} # Each character has a prime number of 1's?
& # Bit-and (because it saves bytes here)
([0]*7).zip(*a) # Zip bit array with an all-zero array
# (If we don't, then uneven array lengths
# cause some columns to not be returned.)
.all?{|c|c.count(1).prime?} # All columns have a prime number of 1's?
# (We use count instead of sum here because
# zip pads columns with trailing nils, which
# can't be added to numbers via sum.)
}
```
[Answer]
# Perl, ~~151~~ ~~121~~ 111 + 3 = 114 bytes
Run with `-lF`. The program will only function correctly for the first input. Terminate the program and rerun for your next input.
Thanks to @Dada for letting me know the `//` after `F` were redundant. An additional byte can be removed (for 112) by piping the input in via `echo -n`, but I feel that that's technically adding more code, so YMMV.
```
for$c(@a=map{sprintf"%07b",ord}@F){$b[$_].=substr$c,$_,1 for 0..6}s/0//g,$d|=/^1?$|^(11+?)\1+$/ for@a,@b;say!$d
```
Readable:
```
#Implicitly split input into characters in @F array
for$c(@a=map{sprintf"%07b",ord}@F) #Convert @F to 7-bit binary as @a, then loop through it
$b[$_].=substr$c,$_,1 for 0..6 #Transpose @a's bits into @b
}
s/0//g,$d|=/^1?$|^(11+?)\1+$/ for@a,@b; #Remove any zeros, then run through composite regex
say!$d #If all composite regex checks fail, then it's fully prime.
```
[Answer]
# Python 3, ~~228~~ ~~227~~ 225 bytes
Not a great answer, I wasn't able to golf it as much as I would've liked, but I spent so long on it I feel I should post it. Suggestions on cutting bytes would be greatly appreciated.
```
r=range
n=[format(ord(c),"08b")for c in input()]
n=map(lambda s:s.count("1"),n+["".join([f[1]for f in filter(lambda e:e[0]%8<1,enumerate("X"*-~i+"".join(n)))][1:])for i in r(8)])
print(all(all(s%d for d in r(2,s))for s in n))
```
**Edit 1:** replaced `e[0]%8==0` with `e[0]%8<1`, losing a byte. Thanks Flp.Tkc!
**Edit 2:** replacing (i+1) with -~i, losing two additional bytes. Thanks Erik for exposing how bad my bit-level knowledge is :) While testing this revision, I discovered that `kappa` is valid... make of that what you will.
[Answer]
# Groovy, ~~151~~ 137 bytes
```
{p={x->x<3||(2..(x**0.5)).every{x%it}};y={it.every{p(it.count("1"))}};x=it.collect{0.toString((int)it,2) as List};y(x)&&y(x.transpose())}
```
No primality check in groovy...
`p={x->x<3||(2..(x**0.5)).every{x%it}};` - Closure for primality testing.
`y={it.every{p(it.count("1"))}};` - Closure to ensure that all counts of "1" for a passed binary 2D array are prime.
`x=it.collect{0.toString((int)it,2) as List};` - Coversion from string to binary array.
`y(x)&&y(x.transpose())` - For all prime-validated sums in the main matrix and the transposed matrix, ensure that they return true.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 37 bytes
```
L.AmP_sdb=sMM.[L\0lh.MlZQ=.BMQ&yZy.TZ
```
[Try it online!](https://tio.run/##K6gsyfj/30fPMTcgvjglybbY11cv2ifGICdDzzcnKtBWz8k3UK0yqlIvJOr/fyUP/xCvxLJEJ)
---
```
Code | Explanation
--------------------------------------+----------------------------------------------------------------
L.AmP_sdb=sMM.[L\0lh.MlZQ=.BMQ&yZy.TZ | Full code
L | Define function y(b):
m b | For each d in b:
P_sd | Is the sum of the elements of the list prime?
.A | Return whether all elements of the resulting list are truthy
= Q | Assign the following to Q:
.BMQ | The list of binary strings for each character in the input
= Z | Assign the following to Z:
L Q | For every element in Q:
.[ \0 | Pad with 0 on the left
lh.MlZQ | To the length of the longest element in Q
M | For each element in the resulting list:
sM | Convert each character to an integer
&yZ | Print y(Z) AND
y.TZ | y( <Transpose of Z> )
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 14 bytes
```
ạḃᵐB↔ᵐz₁,B+ᵐṗᵐ
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRuX/2obcOjpuZHHcuVSopKU/WUakDMtMScYiC79uGuztqHWyf8f7hr4cMdzUCW06O2KUCq6lFTo46TNpD1cOd0kIL/0UoZpcVJiXkpSjpKAQHO4UDKwz/EK7EsEchKzk9J1U3Pz0kDsp39cwMSQzydPH1cQTxtbSDpWBpi4OHonA1k6me7gLR6gkRB2FEpFgA "Brachylog – Try It Online")
Outputs through success or failure. (In the case of success, a list of all column and row sums is available through the output variable.
```
B The variable B is
·∫° the codepoints of the input
ḃᵐ converted to lists of binary digits,
↔ᵐ which with each list reversed
z‚ÇÅ then zipped without cycling
,B and concatenated with B
+ᵐ has elements which all sum to
ṗᵐ prime numbers.
```
[Answer]
# O5AB1E, 12 bytes
```
Çžy+bø€SOp¦W
```
[Try it online!](https://tio.run/##MzBNTDJM/f//cPvRfZXaSYd3PGpaE@xfcGhZ@P//GaXFSYl5KQA "05AB1E (legacy) – Try It Online")
This is my first code golf so go easy :)
```
Ç % Converts the implicit input into ascii values
žy+ % Adds 128 to each value, inspired by Emigna as a way to pad zeros
b % Convert all values into bits
√∏ % Transpose
€SO % Sum each string of binary digits created
p¦ % Check if each element is prime and cut the first element out (adding 128 makes it equal to the number of characters)
W % Take the minimum value to effectively "and" all the elements
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~209~~ ~~189~~ ~~180~~ ~~171~~ 160 bytes
Thanx squid for -9 bytes :)
```
def p(s):n=s.count('1');return(n>1)*all(n%i for i in range(2,n))
def f(s):t=[f'{ord(c):07b}'for c in s];return all(map(p,t+[[u[j]for u in t]for j in range(7)]))
```
[Try it online!](https://tio.run/##dZJRb4IwFIXf@RU3mqXtRKfbg4kLS5zbossSfTDZA/JQoCCKLYF2UQm/3VGY2SDZW/vdc09vzm1yklvBHy4XnwWQ4IxMuJUNPKG4xGiEyGPKpEo55k8jckvjGPObCAKRQgQRh5TykOF7kxNiaINAG0jLDlAuUh97ZDIcuwXSek/rM@fHD7TVgSY4MWXPtpW9c7RIaZGsjrtf/zFxCLl4NGMZWGAbABi5jJ3PyIQ3GmeMmDVTnJ9Ktk7VFW1V5lLuN@F8uX6nX7QJZ8vDiq4Xz4uP12ZhqtbD@XS2b9LVavbZet4TPuuHIg5afNbrtcjd/qVF5osWmP65O4ahE8E6ARPYMWGeZD7RAVWhTMoO6klF4zKeoJKREiVpVC4x6OSo30P2tc2yaqlTQK6VxQQ28lqE/HoqTAiFhLwWFx1t2K0d0YajwU5EHP@35moCAl1gnLoxAynqYcCN5IHKNDpWX8hnrgrDiIeXbw "Python 3 – Try It Online")
[Answer]
# [K (oK)](https://github.com/JohnEarnest/ok), ~~40~~ 33 bytes
**Solution:**
```
&/{2=+/d=_d:x%!x}'+/'m,+m:(7#2)\'
```
[Try it online!](https://tio.run/##y9bNz/7/X02/2shWWz/FNj7FqkJVsaJWXVtfPVdHO9dKw1zZSDNGXSmjtDgpMS9F6f9/AA "K (oK) – Try It Online")
**Explanation:**
Half is creating the matrix, the other half is the primality check.
```
&/{2=+/d=_d:x%!x}'+/'m,+m:(7#2)\' / the solution
' / apply to each (')
\ / decode
( ) / do this together
7#2 / 7#2 => 2 2 2 2 2 2 2
m: / save as m
+ / transpose
m, / append to m
+/' / sum (+/) each (')
' / apply to each
{ } / lambda taking implicit x
!x / range 0..x
x% / x divided by ...
d: / save as d
_ / floor
d= / equal to d?
+/ / sum (+/)
2= / equal to 2?
&/ / minimum
```
[Answer]
# PHP, 173 bytes
```
for($r=1;$b=substr_count($t[$i]=sprintf('%07b',ord($argv[1][$i++])),1);)$r&=$b==2|$b%2&$b>2;for(;$k++<7;){for($b=$j=0;$t[++$j];$b+=$t[$j][$k-1]);$r&=$b==2|$b%2&$b>2;}echo$r;
```
[Test it online](http://sandbox.onlinephpfunctions.com/code/9a9a428d15fdc6022ac95375b2168a15862ddaf6)
[Answer]
# JavaScript, 234 bytes
```
f=z=>(z=[...z].map(v=>v.charCodeAt(0))).map(v=>v.toString(2).replace(/0/g,"").length).every((p=v=>{for(i=2;i<v;i++){if(v%i===0){return 0}};return v>1}))&&[...""+1e6].map((v,i)=>z.reduce((a,e)=>!!(e&Math.pow(2,i))+a,0)).every(v=>p(v))
```
We get the horizontal values by converting the number to binary, removing the zeros using a string replacement, and then counting the 1s.
The vertical sums are obtained by looping 1 to 7 and using a bitwise AND with 2 raised to the nth power.
[Answer]
## Clojure, 180 bytes
```
#(let[S(for[i %](for[j[1 2 4 8 16 32 64]](min(bit-and(int i)j)1)))A apply](not-any?(fn[i](or(= i 1)(seq(for[d(range 2 i):when(=(mod i d)0)]d))))(into(for[s S](A + s))(A map + S))))
```
There might be a shorter way of generating bit lists and also the primality test.
[Answer]
# [Perl 5](https://www.perl.org/) `-MList::Util=all,sum -pF`, ~~96~~ 92 bytes
```
$_=all{//;all{$'%$_}2..$_-1}(map{$_=sprintf'%07b',ord;y/1//}@F),map{sum map{s/.//;$&}@F}0..6
```
[Try it online!](https://tio.run/##HY67CsIwAEX3foVDahXSPIQqtAiC0EmhiziGhioG0iQk6VBKft2YOp3hHg7XvKysYgTs3Eu5YNysAEUOWDggBFhJw27szZIEZ6xQ/l3k5MQLqO3QzJhiHC7tHq6Km8bNnxilDtimIRCEjjF@Jsd7NWR8UmrOuu76/GrjhVYulvcKEUoSb8L5un54IdcrMNViaWT7Aw "Perl 5 – Try It Online")
[Answer]
# Python 3, 164 bytes
```
import numpy;a=numpy.array([list(f'{ord(_):07b}')for _ in input()]).astype(int);print(all([(v>1)*all(v%i for i in range(2,v))for v in set(a.sum(0))|set(a.sum(1))]))
```
[Answer]
# Ruby 2.7 `-rprime`, 95 bytes
```
->s{a=s.bytes.map{[*@1.digits(2),0][..6]}
(a.map(&:sum)+a.transpose.map(&:sum)).all?(&:prime?)}
```
No TiO link because TiO still runs Ruby 2.5.5. üò≠
## Explanation
Pretty simple. The first line gets the binary digits of each character as an array padded out to seven digits, which *really* ought to be easier:
```
a = s.bytes.map { [*@1.digits(2), 0][..6] }
```
Check out that numbered block parameter (`@1`) and beginless range (`..6`) [hotness](https://codegolf.stackexchange.com/a/187015/11261).
The second line sums the rows and columns and tests if they're all prime:
```
(a.map(&:sum) + a.transpose.map(&:sum)).all?(&:prime?)
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~149~~ ~~146~~ ... ~~134~~ ~~130~~ 129 bytes
```
x=>[...x].map(y=>a=[...a.map(n=>y.charCodeAt()&2**i++?++z&&-~n:n,z=i=0),z],a=[...Array(7)])&&!a.some(n=>(P=r=>n%--r?P(r):~-r)(n))
```
[Try it online!](https://tio.run/##bVBNT4MwGL77LySRtCutsKnTJWVBNBnGBA4kHgyHjsGGg5YUMIPD/joyvZn39j4f79fzJb5Fk@qibqlUu2zM@Xji7idj7JSwStSo567gFyx@oeRuz9KD0P7k9lqEzflsVhCyJmQwTXqWK2kNvOA2tobE@uv0tBY9WuIEm@a1YI2qssscFHHNXXlDqV5HSOPVmWqMJMZjqmSjyoyVao9yZGw7KXsD46t//KFrtkLuAGUTxm/TY4Dih1Uk4uA5eH8FVK@L7Y3nHwEpivwPgE6nGOhelTm0ixCAvT2@QBcH0DkA58wXd/cPy8cnG6gAvx0aTGd1Jlrk2AsHT/H@AA "JavaScript (Node.js) – Try It Online")
### Explanation
```
x=> // Main function:
[...x].map( // For each y in x:
y=>
a=[...a.map( // For each i in range(0, len(a)):
n=>
y.charCodeAt()&2**i++ // If y AND 2**i is not zero:
?++z&&-~n:n, // z = z + 1; a[i] = a[i] + 1 (1 if a[i] is undefined)
z=i=0 // Initially z = 0
),z], // Then push z at the end of a
a=[...Array(7)] // Initially a = [undefined] * 7
)&&!a.some( // Then for each n in a:
n=>(
P=r=> // Composite function:
n%--r? // If n % (r - 1) == 0 or r == 1:
P(r) // Return P(r - 1)
:~-r // Else: Return r - 2
)(n) // Starting from r = n
) // Return whether the composite function returns 0 for all n.
```
### How does it even work!?
* `y.charCodeAt()&2**i`
+ We need this code to return the corresponding bit of `y.charCodeAt()` if `0 <= i < 7`, and 0 otherwise.
+ When `i < 7`, the code apparently works as usual.
+ When `7 <= i <= 32`, since the corresponding bit of `y.charCodeAt()` is 0 anyway, the result is 0 as expected.
+ When `32 < i < 1024`, since `int32(2**i) == 0`, the result is 0 as expected.
+ When `1024 <= i`, we have `2**i == Infinity`, and since `int32(Infinity) == 0`, the result is 0 as expected.
* `(P=r=>n%--r?P(r):~-r)(n)`
+ For simplicity we let `R = --r = r - 1`.
+ This helper function terminates when `n % R == 0` or `n % R is NaN`.
- `n % R == 0`: `R` is a factor of `n`.
* If `R == 1`, then `n` is prime because all `1 < R < n` can't divide `n`. Return 0 (falsy).
* If `R == -1`, then `n == 0`. Return -2 (truthy).
* Otherwise, return `R - 1` where `R - 1 > 0` (truthy).
- `n % R is NaN`: Invalid modular calculation.
* If `R == 0`: `n == 1`. Return -1 (truthy).
* If `n is NaN`: `R is NaN`. Return -1 (truthy).
+ As a result, only when `R == 1` can this function return a falsy value, indicating `n` is prime.
] |
[Question]
[
In a very unusual accident involving a small sample of radium, an electrocuted whale, and three gummy bears, some of The Management™'s source code has been mutated. Little does The Management™'s boss know, it was actually the Cops© who had been responsible, in an attempt to thwart The Management™'s "evil" plans. So the Robbers® have been hired in an attempt to retrieve the original code, because who doesn't like being evil sometimes?
*note: This challenge was heavily inspired by [Unscramble the Source Code](https://codegolf.stackexchange.com/q/40932/3808).*
# Description
This is a [cops-and-robbers](/questions/tagged/cops-and-robbers "show questions tagged 'cops-and-robbers'") challenge.
* The **cops** will write a program (the mutated code) that performs Task #1 (and also write a program that performs Task #2, but is kept secret).
* The **robbers** will attempt to reverse the "mutation" and change this original code into code that performs Task #2.
In this challenge, Task #1 will be to **output the `n`th prime number**, and Task #2 will be to **output the `n`th Fibonacci number** (which is somehow evil, according to the Cops© anyway). The Fibonacci sequence is defined as (`n=1` → `1`; `n=2` → `1`; `n=3` → `2`; ...), and the prime numbers are defined as (`n=1` → `2`; `n=2` → `3`; `n=3` → `5`; ...).
The cops' goal is to minimize the difference between the programs that complete Task #1 and Task #2, while preventing the robbers from recreating the code that completes Task #2.
# Cop Rules
The cops will write two programs (one that completes Task #1, and one that completes Task #2), and make the following information public:
* The **first program** (that outputs the `n`th prime number)
* The **[Levenshtein edit distance](https://en.wikipedia.org/wiki/Levenshtein_distance)** between the first program and the second program
* The **programming language** that both programs are written in (must be the same language for both programs)
The following restrictions apply to both programs:
* They must be 128 characters in length or less.
* They must only use printable ASCII (plus newlines, which are also allowed).
* They must take less than 10 seconds to run for `n=45`, and they are not required to produce the correct output for any `n>45`.
* They must not use any hashing or cryptographic functions.
# Robber Rules
The robber will attempt to change the cop's program (which completes Task #1) into a program that completes Task #2 (not necessarily the original program written by the cop) in the edit distance specified by the cop.
An already-cracked submission cannot be cracked again (only the first robber who cracks a submission gets credit).
After cracking a submission, please do the following:
* **Post an answer** to [this challenge's accompanying question (link)](https://codegolf.stackexchange.com/q/42911/3808), providing the language, your solution, and a link to the original answer.
* **Leave a comment** with the text "Cracked" that links to your posted answer.
* **Edit the cop's answer** if you have edit privileges (if you do not, either wait until someone else with the required privileges does so for you or suggest an edit).
# Scoring
If a cop's program remains uncracked for 1 week, the cop can post the original code that completes Task #2 (in the specified edit distance), and the submission is from then on considered "safe." The safe submission that has the smallest edit distance will win. In the event of a tie, the shortest program (the original that completes Task #1) wins. If two submissions are still tied, the one posted earlier wins.
If a robber successfully cracks a cop's submission, the robber's score goes up by the edit distance of that submission. For example, a robber that cracks a submission with an edit distance of 3 and one with a distance of 5 earns 8 points. The robber with the highest score wins. In the event of a tie, the robber who earned the score first wins.
# Leaderboard
1. [Ruby, 6 (histocrat)](https://codegolf.stackexchange.com/a/43042/6828)
# A small tool to compute the Levenshtein distance
```
var f=document.getElementById("f"),g=document.getElementById("s"); function h(){var a=f.value,e=g.value;if(128<a.length)a="<span style='color:red'>First program is too long!</span>";else if(128<e.length)a="<span style='color:red'>Second program is too long!</span>";else{if(0===a.length)a=e.length;else if(0===e.length)a=a.length;else{var d=[],b;for(b=0;b<=e.length;b++)d[b]=[b];var c;for(c=0;c<=a.length;c++)d[0][c]=c;for(b=1;b<=e.length;b++)for(c=1;c<=a.length;c++)d[b][c]=e.charAt(b-1)===a.charAt(c-1)?d[b-1][c-1]:Math.min(d[b-1][c-1]+1,Math.min(d[b][c-1]+1,d[b-1][c]+ 1));a=d[e.length][a.length]}a="Distance = <strong>"+a+"</strong>"}document.getElementById("d").innerHTML=a}f.onkeyup=h;g.onkeyup=h;
```
```
<h3 id=ft>First program</h3>
<textarea id=f rows=7 cols=80 style="width:100%"></textarea>
<h3 id=st>Second program</h3>
<textarea id=s rows=7 cols=80 style="width:100%"></textarea>
<p id=d></p>
```
[Answer]
# Python 2, distance = 8 [[cracked](https://codegolf.stackexchange.com/a/42937/21487)]
```
from fractions import*
n=input()
k,=P=[2]
while n>len(P):k+=1;z=reduce(lambda x,y:x*y,P,1);P+=[k]*(gcd(z,k)<2)
print P[-1]
```
Finally got this one under the char limit. Shouldn't be too hard, but I thought the idea was interesting.
---
**Intended solution:**
>
> `from fractions import*
> n=input()
> k,=P=[1]
> while n>len(P):k+=1;z=reduce(lambda x,y:x+y,P[:-1],1);P+=[z]*(gcd(z,k)<2)
> print P[-1]`
>
>
>
The idea was to use that `F(n+2) = 1 + (sum over F(k) from k = 1 to n)`, and the fact that consecutive Fibonacci numbers are coprime. The `1` in the reduce argument was supposed to provide the `+1`.
Looks like feersum found a different line of attack!
[Answer]
## J, distance = 5 [[Cracked](https://codegolf.stackexchange.com/a/42964/7311)]
```
f=:3 :'{.p:|.i.y'
```
Usage:
```
> f 45
197
```
[Answer]
# Ruby, distance 6 [safe]
```
require'prime';p Prime.take(n=gets.to_i)[-1]
#p (((807462154311276410)**n/(5**0.5)).round)
```
Coming up with pairs of formulas with short edit distances is fun, but it seems like this approach might be more effective/annoying. You may understand exactly what I did, but that doesn't mean you can reverse it.
Solution:
>
> `require'prime';p=Prime.take(n=gets.to_i)[-1]
> p (((0742154311276/4e10)**n/(5**0.5)).round)`
>
>
>
Explanation:
>
> The code generates the Golden Ratio to 11 decimal places and uses it to directly calculate the Fibbonaci sequence. It's just enough precision to get the required number of terms right. That part wasn't obfuscated at all, if you happen to know the formula. To make it harder to brute-force reverse my mutations and recover the constant, I used octal notation (the leading 0) and scientific notation (4e10). Dividing by 4e10 rather than 1e11 makes it look more like I'm dividing by something `.0` to force float division, when actually anything in scientific notation is for some reason always a Float in Ruby, even when a Bignum might seem to make more sense. I thought I was being clever with the `p=` stuff, but the way I wrote it you can just delete the `p`. I could've reduced the distance by 1 and forced the `p=` solution by using `p&&` instead of `#` on the second line, but I didn't think of it.
>
>
>
[Answer]
## Python 2 - LD = 13 [Cracked](https://codegolf.stackexchange.com/a/42918/31625)
```
n=1;j=input();
while j>0:
n+=1;j-=1;
while~-all(n%i for i in range(2,n)):n+=1;
print n
```
A nice, easy (hopefully not *too* easy) one to start things off :)
Looks like it was too easy ;) I feel rather silly that I forgot you could use comments :/
[Answer]
# Haskell, distance = 13
```
import Data.List
x=id=<<snd(mapAccumL(\m n->(,)=<<(++m)$[n|and[n`mod`m1/=0|m1<-m]])[1+1][3..])
main=print.(!!)(0:2:x)=<<readLn
```
This could be more readable, but the `import` ate too many bytes, so I had to golf it a bit.
[Answer]
# Ruby, distance 14 ([Cracked](https://codegolf.stackexchange.com/a/43007/21475))
```
p [x=2,y=1,*(1..200).map{|i|y==(y*x**(i-1)+x%2).divmod(i)[x-1]?i:1}].-([x-1])[gets.to_i-1]
```
[Answer]
# CJam, distance 10 [(Cracked)](https://codegolf.stackexchange.com/a/42968/8478)
```
1l~{{)_mp!}g}*
```
Just put `n` on STDIN. [Test it here.](http://cjam.aditsu.net/)
For reference, the original solution used the rare `j`.
**Original:**
>
> `T1]l~\{(_j\(j+}j`
>
>
>
[Answer]
# J, distance = 4 [safe]
```
f =: 3 : '{. (p:) (+) / 0 , y - 1x'
```
Solution:
>
> f =: 3 : '{. 2(x:) (+%) / 0 , y $ 1x'
>
>
>
Method:
>
> Denominator `{. 2(x:)` of the continued fraction `(+%)` 1+1/(...(1+1/(1+1/(1+1/(1))))).
>
>
>
[Answer]
# Python 3, distance = 14 [[cracked](https://codegolf.stackexchange.com/a/42920/21487)]
```
n = int(input())
P = [2]
k = 2
while n > len(P):
k += 1
for x in P:
if k%x == 0: break
else: P += [k]
print(k)
```
I had some spare chars so I put some whitespace in for clarity :)
[Answer]
# [JAGL](http://github.com/globby/jagl) Alpha 1.2 - Distance = 16 [[Cracked](https://codegolf.stackexchange.com/a/42960/30630)]
```
T~2S]{]S1{D[dmn}wDS}wSP
```
Shouldn't be too hard, We will see what happens...
[Answer]
# [TI-BASIC](http://tibasicdev.wikidot.com/home?MS60C), distance 38
```
Input N:{2>L1:For(A,3,E99:If min(1=gcd(A,seq(A,A,2,$(A:A>L1(1+dim(L1:End:L1(N
```
`>` represents the `STO→` key and `$` represents the square root symbol.
[Answer]
# Python 2 – distance = 12 [[Cracked](https://codegolf.stackexchange.com/a/42970/30688)]
I'm kinda happy with how this turned out.
```
f=lambda p,i:p if p[45:]else f(p+[i]if all(i%q for q in p[1:])else p,-~i)
print f([1,2,3],2)[input()]
```
Let's see how long it takes... I assume it'll still be cracked.
**Edit:** shortened code a tiny bit, no effect on operation/distance.
## Intended solution
I tried to go for no comments or newline changes.
>
> `f=lambda p,i:p if p[45:]else f(p+[p[i]+p[-2]]if all(i|q for q in p[1:])else p,-~i)
> print f([1,1,1],2)[input()]`
>
>
>
[Answer]
# Python 3 - Distance = 14 [[Cracked](https://codegolf.stackexchange.com/questions/42911/recover-the-mutated-source-code-for-robbers/42954#42954)]
---
```
a,c,n=1,2,int(input())
while n-1:
c+=1
while 1!=list(map(c.__mod__,range(2,46))).count(0):
c,a=a+c,a
n-=1
print(c)
```
We'll see how long this lasts...
] |
[Question]
[
# Task
Write a program/function that when given a positive integer \$n\$ and a digit \$d\$ which is not 0 outputs a way to represent \$n\$ using only addition, subtraction, multiplication, exponentiation, division, concatenation, parenthesis and the digit \$d\$.
# Examples
```
n = 6, d = 1 => (1 + 1) * (1 + 1 + 1)
n = 6, d = 1 => 1 + 1 + 1 + 1 + 1 + 1
n = 10, d = 1 => 1 || 1 - 1
n = 12, d = 1 => 1 || (1 + 1)
n = 64, d = 2 => 2 ^ (2 + 2 + 2)
n = 1, d = 9 => 9 / 9
```
**Note:** In the examples `||` represents concatenation
# Output Format
* Concatenation must be explicit with a separate operator
* Output can be a string, list of operations and numbers or a list of lists in place of brackets.
* You may choose the precedence of the operators but it must be consistent for all outputs produced by your program/function
* Output may be in [polish](https://en.wikipedia.org/wiki/Polish_notation), [reverse polish](https://en.wikipedia.org/wiki/Reverse_Polish_notation) or [infix](https://en.wikipedia.org/wiki/Infix_notation) notation but it must be consistent for all outputs produced by your program/function.
* You can use custom symbols for representing the digits and operations but the symbols used for representing the digits and operations should be distinct.
# Scoring
This is [code-challenge](/questions/tagged/code-challenge "show questions tagged 'code-challenge'"), Your score will be
```
100*B + S
```
Where `B` is the number of bytes in the program/function, and `S` is the sum of the number of times the digit \$d\$ appears in the representation of \$n\$ with the digit \$d\$ as returned by your program/function for all \$n \le 1000\$ and all \$d\$ from 1 to 9
Lowest score wins
Example: if your program is `abcd` and all representation of \$n\$ returned by your program has 5 occurrences of \$d\$ then its score will be `(4 * 100) + (5 * 1000 * 9) = 45400`
# Rules
* Your program/function should run deterministically, so that it always returns the same representation for a given \$n\$ and \$d\$ (and hence always gets the same score).
* Your answer must include not only your submission, but also the code you used to calculate the `S` part of its score. This need not be written in the same language as your submission, and will not be counted towards its byte count. You are encouraged to make it readable.
* Your answer must include the precedence of the operators needed to evaluate the outputs produced by your program/function
* You must actually run your test program and calculate/verify your score before submitting your entry. If your submission runs too slowly for you to verify its score then it is not qualified to compete, even if you know what its score would be in principle.
---
*Inspired by [this video](https://youtu.be/-ruC5A9EzzE)*
[Answer]
# [Python 3](https://docs.python.org/3/), 210 bytes · 100 + 59045 digits = 80045
```
def f(n,d):
m={d:d},
while{n}-{*m[0]}:m={z:(p[x],o,q[y])for p,q in zip(m,m[::-1])for x in p for y in q for z,o in zip([x+y,x-y,x*y,y<9and x**y,x%y<1and x//y,int(f"{x}{y}")],"+-*^/|")if z>0},*m
return m[0][n]
```
[Try it online!](https://tio.run/##NY7RasMwDEXf8xUiMLBdhTRsMGa6/ohxYeCYGmbHCRmz4vrb0yRjDxfO1ZFAkeb7EF7X1fQWLAtouKzAf2YjTcEKfu/uu8@hNFl4ddZFbmqRLKqkccBRkeZ2mCDiCC7A4iLz6JWUTfcn0j6OsCPtOB644PC/rtKJMDVbBCFdPr6CgSQ2Ti906Y7WtoQuzMzWOZVMpeYa61Mjbu2j5s7Ccj0XFL6CqZ9/pgD7oyroNU7HFXvrOnznfH0C "Python 3 – Try It Online")
### Scoring
Scoring goes much faster using this modified version that solves 1 through 1000 all at once:
```
def f_gen(d):
m={d:d},
while 1:yield from m[0].items();m={z:(p[x],o,q[y])for p,q in zip(m,m[::-1])for x in p for y in q for z,o in zip([x+y,x-y,x*y,y<9and x**y,x%y<1and x//y,int(f"{x}{y}")],"+-*^/|")if z>0},*m
def size(expr):
return 1 if isinstance(expr, int) else size(expr[0]) + size(expr[2])
score = 0
for d in range(1, 10):
s = set(range(1, 1001))
for n, expr in f_gen(d):
if n in s:
s -= {n}
score += size(expr)
print(n, expr)
if not s:
break
print(score)
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), Score: ~~87900 ... 83274~~ 82574
## 229 bytes x 100 + 59674 digits
Takes input as `(d)(n)`. Returns a string. Uses `|` for concatenation.
```
d=>n=>[0,v=[d],F={[d]:d},s={[d]:0}].map(_=>v.map(x=>v.map(y=>[x+y,x-y,x*y,x/y,x**y,[x]+y].map((z,o)=>z<0|z>1e4||z%1?0:(!F[z]&&V.push(+z))|(S=s[x]-~s[y])<s[z]?F[s[z]=S,z]=`(${F[x]+'+-*/^|'[o]+F[y]})`:0)),V=[])&&v.push(...V))&&F[n]
```
[Try it online!](https://tio.run/##ZUzLboMwELz3Lyo1xBuMA1GSBhSTm38gEhfLbVAgfSjFqG4RONBfp0tRTxxmZ3Y0M@9plZrz51v55RU6y/sL7zMeFzyWPq24zBQV/IYUZR01o/I7xT7SkjzzuPoT9b9osFa7Da09xAKxHBiFrJXbjC1iqQYe273f2jjI121rZ8HBj8i9kFY5TsLKb/NKXAvQkiM3WPV@jGwU7A0GDkIOxI8Uz4k83MSwPXe9xfKpnUutXIHZDk6RD0ATLhU4TjVuMsYSwFfIQvVnXRh9zdlVv5ALCYBsHrcAdxN7F24m9grIdj1xQyDhDjf6Xw "JavaScript (Node.js) – Try It Online")
### Scoring
Because the golfed version is quite slow, the total score was computed with the following ungolfed version which, given \$d\$, computes the formulas for all \$n\in[1..1000]\$ at once.
Although it works on TIO, the output is too long. So the link below is an example for \$d=9\$.
[Try it online!](https://tio.run/##fVRNc5swEL37V2wPCRA@AolzaDDpqedkpjO9MOoMBTmhpVIGBMGO@e3uSkI2OBlzkNa7b9/bXUv6k3VZk9flq/AZL@h@n3PWCHh8ggRSy7U8sHy5XMnlWi6/5LLbWSReLNYty0XJGTS86qhdOPC@AKiogC6rWio5oADioVN@a17/a6sM3e@QFgTuMTiYYFNu6SQSHiOCi6zCUIiKisSWCqXy4LaCJW6uq8W1PKNvP00FRKWBLinA9O9Z/mL3kDyMCaehzTQEkIYeRB7ceHDrwdKDO3JA8jlybH3UG9t6K4VEOjMcQJ41FMJ76LDEHlzYxPC7ptnf@CMqMqgVbOAbsLaqcEA9@OeSbkzS1TnUrUFdzKmvzyUtD9Rnue80zLX7QPAfoi7Zs@3ITic/nU/Sh@n4yrXdwZck0aVdXiLlKoEoxO90onL2zRYV5UlKe4JSytpIK5r9KYrXHo9j2hFIUKFlBV2XjBZSxhyg4LVtXuzOcWC3k@wrzdmRU/XD6VZ0YNkWqhqXKubxKeVk4lR1WY4Vn/CMArKR7Tw2LD6zB8egjGX27thBEASmJRUcpleJoVYU4zaOFs3jdZIPAq9oUPFnm3m6OqZG6h1aYWRU1FfVTaYwLTcnsnz/Ad8RBVepNRVtzbQjXgx7/aB8dfb/AQ "JavaScript (Node.js) – Try It Online")
```
const OP = ['+', '-', '*', '/', '^', '||'];
function solve(d) {
let value = [ d ],
formula = { [d] : d },
size = { [d] : 0 },
total = 0;
for(let i = 0; i < 4; i++) {
let newValue = [];
value.forEach(x => {
value.forEach(y => {
[0, 1, 2, 3, 4, 5].forEach(o => {
let v;
switch(o) {
case 0: v = x + y; break;
case 1: v = x < y ? null : x - y; break;
case 2: v = x * y; break;
case 3: v = x % y ? null : x / y; break;
case 4: v = x ** y; break;
case 5: v = +(x.toString() + y.toString()); break;
}
if(v !== null && v <= 10000) {
let sz = size[x] + size[y] + 1;
if((formula[v] === undefined && newValue.push(v)) || sz < size[v]) {
formula[v] = '(' + formula[x] + OP[o] + formula[y] + ')';
size[v] = sz;
}
}
});
});
});
value.push(...newValue);
}
for(let n = 1; n <= 1000; n++) {
console.log(n, size[n] + 1, formula[n]);
total += size[n] + 1;
}
console.log('-->', total);
return total;
}
let score = 0;
for(let d = 1; d <= 9; d++) {
score += solve(d);
}
console.log('Final score:', score);
```
[Answer]
# [Wren](https://github.com/munificent/wren), 107 bytes, score: 138373
Thanks to @Mukundan for the golfing so far!
(This answer was written before @GammaFunction did so.)
```
Fn.new{|n,d|"%(n)".map{|i|Num.fromString(i)}.map{|i|i<1?[d,-d]:[d]*(i/d).floor+["%(d)/%(d)"]*(i%d)}.join()}
```
[Try it online!](https://tio.run/##VVBdT4MwFH3vr7iSLGk3LCxGjYvEaET34KbZ8InsgdAya6BduuJigN@OBTaNL7ftPR@95x40l@1XoiErZQoBtE@SSn6oaumy2hlhSRxaJLuqFvWyLGimVbE2WsgtFqQ5IeJ2ehcz95xtZjHbjLHwGKFZrpSexNaDEa8rToeMmJV9KiExadr1997wgu6sn8HdADRN8hxf@ZfuBSEI/cOdIAhgnSrNwd4cC3serMJFuHgIVxC9wvvb430UQjQP4SVcPkfzM4S6ZPtBA1P/Gsa2@mCF9jGDnMut@QCVwV6VOuUIZUoDliAkTCm1VJ9AhQD6Nju2b4YeQGeuSrMrjXX/G1@6wEhPOP08nJMjmaaqlKbfm00CjBo1rLSxogY1v7kPWhiOezFpfwA "Wren – Try It Online")
[Answer]
# Brainfuck, 30 bytes \* 100 + 9009000 = 9012000
Uses the fact that `n = (d/d)*n`:
```
,>,>+<<->.>.<.<[->>>.<<.>.<.<]
```
In that program, the character representing division is ASCII 1 and the character representing addition is ASCII 0, so the output isn't very readable.
With [this TIO link](https://tio.run/##SypKzMxLK03O/m@nDQbRulCGtjaMYWMTa6cLFLaxsfmvY6cDYuja6dnp2ejZAFXbARk2EF7s//9clgA) I include a brief header making the output readable. There is still the minor inconvenience that input are ASCII characters (the link has a new line, ASCII 10, in the input, hence the program prints
```
9/9+9/9+9/9+9/9+9/9+9/9+9/9+9/9+9/9+9/9
```
To make 10. If instead you use [this interpreter](https://copy.sh/brainfuck/?c=PisrKysrK1stPisrKysrKysrPisrKysrKys8PF0-LS0-Kzw8PApTZXQgdXAgY2VsbHMgMyBhbmQgNCBmb3IgcHJldHRpZXIgcHJpbnRpbmcKTWVtb3J5IGlzCm4gfCBkIHwgMSAoZGl2aXNpb24gY2hhcikgfCAwIChhZGRpdGlvbiBjaGFyKQosPiw-Kzw8LT4uPi48LjxbLT4-Pi48PC4-LjwuPF0$), you can type easier to understand input, using `\` to insert the values of the ascii characters, instead of using the ascii characters. So, using `\10\57` as input in this program gives the same result as the program on TIO.
[Answer]
# [Zsh](https://www.zsh.org/), ~~89 81~~ 75 bytes, score: 135173
(total digit count is 127673)
```
for c (${(s::)1})(repeat c/$2 s+=($2);repeat c%$2 s+=($2/$2);<<<${s=$2-$2})
```
[Try it online!](https://tio.run/##PY7BTsMwEETv/opRu1VslTZOyqEN8Qdw4sINEanETtNDnSp2JITlbw8xAi4rzZuV5n25fu64CHM3jGjBKXBXVaKIgo/mbs4ebU4l3FZxKsXTH9v8szzhuq4pOEXljsoo5shYh8ejPODAmJ1uTvFQ7PeFlDIKpq@XX3BaElvD9wbeOI@L8Q7nj2HyOMoN9GANBovX55eHFDKPcbK4emY@l8OSstXJWVU7atJQhoyaNBAFfmqkXlktEBjj3E03bBUorCmsiHcgC9JiledvDen3GMVitOibth9Ay/f8DQ "Zsh – Try It Online")
(This generates the same operations that @a'\_''s method does. I thought of it independently, then saw his score using it, then implemented it.)
>
> You can use custom symbols for representing the digits and operations [...]
>
>
>
We take advantage of that here; concatenation is represented by a newline and addition is represented by space. Concatenation has lower precedence than addition, which has lower precedence than division.
```
for c (${(s::)1})( # for each digit c in n
# repeat $x expands $x in arithmetic mode
repeat c/$2 s+=($2) # append d to $s, c/d times
repeat c%$2 s+=($2/$2) # append d/d to $s, c%d times
<<<${s=$2-$2} # if $s is still unset, set it to d-d
# <<< prints $s, implicitly joined on spaces
) # exit the subshell, effectively unsetting $s
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 150 bytes × 100 + 81773 digits = 96773
```
⪫Eθ§⪪§⪪”}∧⟦NJgYZG;|⪫v4⌈-LiςΠg➙∨C⊕⊙Nψ≧Fδ∨↧↧«3Y!‴2ⅈ⸿⟦⁰J◨(⁴⦄4b¶¤⦄→₂⊞GςG⸿≡←ε⭆R?ρq&Σ<×HJ⁶�⧴Q<"k~3Vu⌊+LΠ↓1βπt“P³∨R▶A↓ⅉs▷"«‖κ-σ_←U/V!U⊕⁷↙U3M⁼³RVV¤HQ:”;Iη,Iι&
```
[Try it online!](https://tio.run/##jZHLCsIwFET3fkXJBUmaG@L7QVbiSkEQ/IKiQgulvor497EmaRtrUckiM8Odk6Tdx9F1f4pSrbfXJMvp@pRkdBOd6QWDRb7KDscH3Z3TJKfvjoAABAlIgQNzu6@sBtHmam3ViwPKELEI0QyhK5Y7d2eFjlG4LjABdvmu1qq8paFIjy7LU8ystD0Ii1UndVs0GKLJqjovhmp@m/e@S3krqaXbTgFe5dybscRPSgjS6H945Sz/5Ph/uXrxL@IXSvNeX99MMCCKMAyW0S2nMSsUwconzARdwpjSej6bTsaj4aDf64y1uKdP "Charcoal – Try It Online") Link is to verbose version of code. Uses `&` (low precedence) as concatenation and `#` to represent the input digit. Explanation: Simply looks up all of the digit patterns in a (compressed) hand-crafted lookup table and concatenates the relevant digits together. [Proof of digit count.](https://tio.run/##jZLdisMgEIVfJThQNCqm114tvepCYdk@gWRDVwimtGnZt7f@Jbpp6C5C5szkzKcm036rSzuo3tqPizYj3qmreww3J4@jq5wO6oyP516PGAEHBgIYBgokxVJFDXwtyzoqzwEZiMwVWTCx1DhFmvaqE8NlGyAc4iqzrOV0ykARBV1MuwSviH1Qu5UruZsvGHzJmns8Qy6/ze/@VKWrpJXedQrQuU4LTyQ@U2oQQf@HN3npM6f8y/ON/yK@oCzP9fLOiFVIIsKqPIx70/a3q753n8qcOrxl1bZpGmd5H7TB3hFmuHeVt3FvvrqfNL/asZhnhfeGECfRBsUIPkprLb/3Dw "Charcoal – Try It Online")
[Answer]
# [W](https://github.com/A-ee/w) `n`, 22 [bytes](https://github.com/A-ee/w/wiki/Code-Page) \* 100 + 127673 = 129 873
A blatant rip-off of my Wren answer.
```
☺◘Y╔û çτ◘↑═uon↕I6≡ÿѰt
```
Uncompressed:
```
1, % Split number to chunks of 1
c} % Construct the list [input]
ac/* % Repeat that input/current times
c:{ % The list [input,input]
'/, % The string input/input
} % The list [input/input]
acm* % Repeat that list input%current times
+ % Join these two lists
| % If that's the empty list:
c:_{ % Yield the list [input,-input]
M % Do that for every thing in the input
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), Score: 127,473 (178 bytes \* 100 + 109,673)
```
->n,d{n.to_s.chars.map{|c|g=d.to_s;c<?1?g+?-+g:(i=c.to_i)==d ?d:(d*d==i)?g+?*+g:i%d<1?([d.to_s]*(i/d))*?+:i>d ?g+?++f[i-d,d]:(i+1==d&&i>1)?g+?-+f[d-i,d]:[d==1?d:g+?/+g]*i*?+}*?|}
```
[Try it online!](https://tio.run/##XZHbrpswEEXf@YpRoh4ZTAim1bmkcfiIPnJQRW1ILKV2xOWhAr49HQOhTi0htGft2R7bdffrz70CDvfdSYey11FrfjaRuBR1E/0ubv0ghjOXU/W7OKYsPdN0R88HoriwVeVzLiGVByIDybnyrSFAg/oijywl2dybB0Ttpe8HKT2oEzagi9IqUzsZyhzTKMOclxd1Yv68RZXJnbIsw1iGG2B1T895oDBjDNJhvN@6toENeQ2B@cBPsO2rzIp83HgL@xpCsjIrHMZit3FSLmVPlP1HkyeaPNPXb@62k3Jokrh0Um5yCB//glE47OMNo95XOkvLvenB8BnZ27tnunbyc8hyj0XdrTUEI6WBQQ4e4FqKLI7jua7nul1Ld3TrmgupIlFcr0SHgG@3WlQFdaElSab@I7CV2LXMuu31GOKYclzmfQRfi6bFkR/2Ukvv8befEaKrSy1Ke4D4cZioLMQFehjMAI6DcjBRIwpN9p9y70fCdLqFcbmvH8LU5XJ58wUFgGcG6kQs1m0/GcbVgfOunnFz/ws "Ruby – Try It Online")
This uses `|` as concatenation. It could also definitely be cleverer. I just kept adding cases to try to minimse the occurences of `d`.
] |
[Question]
[
Given a square string, produce all the output for the string at every stage of unfurling.
The string must unfurl in a clockwise direction one quarter turn at a time.
## Examples
**Input**:
```
A
```
**Output**:
```
A
```
***Note**: I'll also accept the input duplicated for this particular test case **only** if this helps reduce your byte count.*
**Input**:
```
DC
AB
```
**Output**:
```
DC
AB
D
ABC
ABCD
```
**Input**:
```
GFE
HID
ABC
```
**Output**:
```
GFE
HID
ABC
HG
IF
ABCDE
IH
ABCDEFG
I
ABCDEFGH
ABCDEFGHI
```
**Input**:
```
JIHG
KPOF
LMNE
ABCD
```
**Output**:
```
JIHG
KPOF
LMNE
ABCD
LKJ
MPI
NOH
ABCDEFG
NML
OPK
ABCDEFGHIJ
ON
PM
ABCDEFGHIJKL
PO
ABCDEFGHIJKLMN
P
ABCDEFGHIJKLMNO
ABCDEFGHIJKLMNOP
```
## Rules
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in bytes wins.
* Any reasonable format can be used for I/O assuming it is consistent.
* Spaces must be used to pad the top lines of the output.
* Must be able to handle input of all printable characters (including space: `\x20`-`\x7e`):
```
!"#$%&'()*+,-./0123456789:;?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
```
* Leading/trailing whitespace is allowed.
* You can assume the string will always be a square.
* All [standard loopholes](https://codegolf.meta.stackexchange.com/q/1061/9365) are forbidden.
Inspiration: [Write a square program that outputs the number of times it has been “unrolled”](https://codegolf.stackexchange.com/q/39993/9365).
[Answer]
# [SOGL V0.12](https://github.com/dzaima/SOGL), ~~21~~ ~~20~~ ~~19~~ ~~18~~ 17 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md)
```
ø;[;ο⁴№č▓┼№TJι;jI
```
[Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JXUyMTkyJUY4JTNCJTVCJTNCJXUwM0JGJXUyMDc0JXUyMTE2JXUwMTBEJXUyNTkzJXUyNTNDJXUyMTE2VEoldTAzQjklM0JqSQ__,inputs=JTVCJTIySklIRyUyMiUyQyUyMktQT0YlMjIlMkMlMjJMTU5FJTIyJTJDJTIyQUJDRCUyMiU1RA__) (`→` added because this expects input on the stack)
Explanation:
```
ø;[;ο⁴№č▓┼№TJι;jI
ø; push an empty string below the input stack with the input GFE,HID,ABC
[ while [ToS (the array) isn't empty] do ["", [["G","F","E"],["H","I","D"],["A","B","C"]]]
stack at the second time looping
; duplicate 2nd from top [[[H,G], [I,F], [D,E]], "ABC"]
ο wrap it in an array [[[H,G], [I,F], [D,E]], ["ABC"]]
⁴ duplicate 2nd from top [[[H,G], [I,F], [D,E]], ["ABC"], [[H,G], [I,F], [D,E]]]
№ reverse vertically [[[H,G], [I,F], [D,E]], ["ABC"], [[D,E], [I,F], [H,G]]]
č▓ join the inner arrays (┼ fails otherwise) [[[H,G], [I,F], [D,E]], ["ABC"], ["DE", "IF", "HG"]]
┼ add the 2 parts together [[[H,G], [I,F], [D,E]], ["ABCDE", " IF", " HG"]]
№ reverse vertically again [[[H,G], [I,F], [D,E]], [" HG", " IF", "ABCDE"]]
T print that without popping [[[H,G], [I,F], [D,E]], [" HG", " IF", "ABCDE"]]
J take the last line off [[[H,G], [I,F], [D,E]], [" HG", " IF"], "ABCDE"]
ι remove the rest of the array [[[H,G], [I,F], [D,E]], "ABCDE"]
;j remove the last line of the original array ["ABCDE", [[H,G], [I,F]]]
I rotate it clockwise ["ABCDE", [[I,H], [F,G]]]
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~209 207 205 203 202 201 200~~ 196 bytes
-4 bytes thanks to [@Quelklef](https://codegolf.stackexchange.com/users/43266/quelklef)!
```
s=input();l=len;k=''.join;exec"print s;s=[x for x in[' '*l(s[0])+k(x[:-1]for x in s[-2::-1])[t::l(s[0])-1]for t in range(l(s[0]))][:-1]+[s[-1]+k(x[-1]for x in s)[-2::-1]]if x.strip()];"*(2*l(s)-1)
```
[Try it online!](https://tio.run/##VY7JDoIwFEV/5aUbWhSiLNt04TwP@6YLY0ArpDS0JvXrkRpYuLrJu@eePPNxz1pnbWu50ubtMGEVr3LNSh5F6atWmuU@vyPTKO3AMsuFh6JuwIPSIoIorrAVE0lGJfaCJlM5lGBFktFwIcJR2mM94ALQ3PQjx31B5G89Et2si2D7k5HBJlUBPrWuUQYTyVCMs/BDZyZtK9B@t92gMaDD9bIOeTydVyFn88USyS8 "Python 2 – Try It Online")
# [Python 2](https://docs.python.org/2/), ~~219 217 215 213 212 211~~ 207 bytes
```
s=input();l=len;k=''.join;exec"print'\\n'.join(s);s=[x for x in[' '*l(s[0])+k(x[:-1]for x in s[-2::-1])[t::l(s[0])-1]for t in range(l(s[0]))][:-1]+[s[-1]+k(x[-1]for x in s)[-2::-1]]if x.strip()];"*(2*l(s)-1)
```
[Try it online!](https://tio.run/##VY45D4MgAIX/CmEBtJrWUeLQ@z52ZGgabakGDdCE/noqrQ6dXvKOL699m0cjE@d0JmT7MpjQOqsLSasMofjZCEkLW9xgq4Q0KM/lz8SaUJ0xC8pGAQuEZAigoMaajTkJK2xZGk34EALNoiT1DmEmTftaXzC@oK7yXuA@IPy7Dlk368TT/mBkoHFRAhtro0SLCacwwIn/0JGJcwzutps1HAG4v5xXXg/H09LrdDZfQP4B "Python 2 – Try It Online")
The first one outputs as a list of Strings, the second one outputs as ASCII-art.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~42~~ 35 bytes
```
AEθSθW⊟θ«⪫θ¶AEι⮌⪫Eθ§μλωθ⊞υι↙←⮌⪫υωD⎚
```
[Try it online!](https://tio.run/##XY3LDoIwEEXX9CsaV9Ok/gCuEHygokS3bohWaVJapC2YGL@9UtTEuLs398yZU1k0J1UI5yKt@VVCVtRwoziVtTUH03B5BUIovpEJ6kouGIZc9QQh@IGCvN8NrBSX/mZ0lCPSc8GPilO8Zy1rNHtjH31kUnlmd6goFl7fke@TILe6BEsx9yVTLYMwUZ3csIsZ5uFl6Ouf2r41PZPYqgYfYsGKxqenc6t0uUDrfDdHm2w7Q9E0Tty4dWMtXg "Charcoal – Try It Online") Link is to verbose version of code. Edit: Saved 7 bytes mostly by switching from character arrays to strings. Explanation:
```
AEθSθ
```
Read the input square as an array of strings into the variable `q`.
```
W⊟θ«
```
While the last string in the array is not empty, remove it.
```
⪫θ¶
```
Print the rest of the array.
```
AEι⮌⪫Eθ§μλωθ
```
Rotate the rest of the array by looping through each character of the last string and joining the `l`th character of every remaining string in the reversed array.
```
⊞υι↙←⮌⪫υω
```
Append the previously removed last string to `u`, which holds the unfurled value, and print it.
```
D⎚
```
Output the result and then clear the canvas ready for the next iteration.
Note that this version outputs the final unfurl on a separate line, if this is undesirable then for 38 bytes:
```
AEθSθW⊟θ«⊞υι←E⁺⟦⪫υω⟧⮌θ⮌κAEι⮌⪫Eθ§μλωθD⎚
```
[Try it online!](https://tio.run/##TY7LCsIwFETXzVdkeS/EH9BVfVerBl2Ki6KxDcb0kcQK4rfHRhTdzTBnhjkWWXMsM@V9bIzMNayyCmpGE105u7ON1DkgMlrjgLSFVIICLzsCkT5IxJ0pwDEquzTiHWyhn4qzZTTMcOUM7Bel1IFp8cDoVtxEY0To/8wFMfT/Dshf@K5/TsU20SdxhyujKgy0@L0Wjd21giBGSmRNUE/vF8l8RpZ8MyXpaj0h8XA09r2b7xn1Ag "Charcoal – Try It Online") Link is to verbose version of code. Explanation: `←E⁺⟦⪫υω⟧⮌θ⮌κ` reverses the current array, prepends the unfurled line, then reverses the characters in each line, then prints everything upside-down, thus producing the desired result.
[Answer]
# [Haskell](https://www.haskell.org/), ~~127~~ 120 bytes
```
e=[]:e
i#[x]=[]
i#s|t<-foldl(flip$zipWith(:))e$init s,j<-i++last s=(map((j>>" ")++)(init t)++[j++last t]):j#t
f s=s:""#s
```
[Try it online!](https://tio.run/##LYzLCsJADEX38xWh7WKGWj@gtILv9wNcuChdFDrV1HFanAgi/nsN6iJw7s1JLoW7amO6TqdZHmuBfvbMGRncm5KoakxpZGWwDV7YnpAuMlZKB2iRwPXqJMIwNIXjkMpb0UpZDwYeeCoMlfxKxJjVf4lyFdc@iYp1F3ue77pbgRZSKBsBgLZ9ECQRnDWNG0vakuOa/25B8upI942FPjysQaudYqx4vgGC33m3Wi7mYn3Yz8Rmu5uK4Wg8@QA "Haskell – Try It Online")
Input is a list of lines, e.g. `["DC","AB"]` for the second test case, output is a list of lists of lines: `[["DC","AB"],[" D","ABC"],["ABCD"]]`. Use `mapM (putStrLn . unlines)` to pretty-print the result.
**Edit:** Saved 7 bytes by noticing that the [shorter `transpose`](https://codegolf.stackexchange.com/a/111362/56433) I found some while a go comes in handy because it can be modified to reverse each transposed directly.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 18 bytes
```
[Dí.Bí»,¤UR¦ζŽ`Xì)
```
[Try it online!](https://tio.run/##MzBNTDJM/f8/2uXwWj2nw2sP7dY5tCQ06NCyc9uO7k2IOLxGEyin7uXp4a6uo@4d4O8GpHx8/VyBlKOTs4t6LAA "05AB1E – Try It Online")
**Explanation**
```
[ Ž # while stack is not empty, do:
D # duplicate current list
í # reverse each element
.B # pad with spaces to equal length
í # reverse each element again
», # join with newlines and print
¤U # store the last element in X
R¦ # reverse the list and remove the first element
ζ # zip with spaces as filler
` # split elements separately to stack
Xì # prepend X to the last element
) # join the stack to a list
```
[Answer]
# J, 62 bytes
```
|."1@([:(#~[:-.[:*/"1' '=])|.@{:(}:@],{:@],[)|:@}:)^:(1<#)^:a:
```
[Try it online!](https://tio.run/##y/r/P03BVk@hRk/J0EEj2kpDuS7aSlcv2kpLX8lQXUHdNlazRs@h2kqj1sohVqcaRERr1lg51FppxllpGNooA6lEKy6u1OSMfIU0BRMgVFFQ9/L0cPcO8Hfz8fVzdXRydlH//x8A)
I'm sure this can be golfed a lot. This prints extra whitespace, but only because of the way that J formats the arrays contained within the outputted array to have the same shape.
I think once I go in and comment out exactly what I'm doing, I might get a better idea of how to golf this (having done that now, I don't really know...). For purposes of golfing, it's worth noting that
* I have to special case 1 row inputs (the while part of the loop)
* I have to eliminate all lines consisting solely of whitespace (surely there must either be a builtin for this or a better way to do it), which is the filter near the end
* There are a lot of caps, identity functions, and atops
# Explanation
In ungolfing this, I'll be splitting the main function in three.
```
unfurl_reversed =. |.@{: (}:@] , {:@] , [) |:@}:
whitespace_filter =. #~ [: -. [: */"1 ' ' = ]
unfurl =. |."1@(whitespace_filter @: unfurl_reversed) ^: (1 < #) ^: a:
test_case =. 3 3 $ 'GFEHIDABC'
```
We'll be working with the second test case.
### unfurl\_reversed
```
|.@{: (}:@] , {:@] , [) |:@}:
```
This gives one the string unfurled once, but in reverse. All of this is being done in reverse and in a specific order so that the way J automatically pads strings with spaces to match the shape of the array they're in will give the right spacing.
`|:@}:` is the transpose of the curtail of the input
```
|:@}: test_case
GH
FI
ED
```
`|.@{:` is the reverse of the tail of the input
```
|.@{: test_case
CBA
```
I think you can see what we want to do: we want to append the reverse of the tail to the last part of the transpose of the curtail (that's a mouthful, but basically attach `CBA` to the end of `ED`). This will give us one step of unfurling, reversed.
`(}:@],{:@],[)` does just that.
It appends `CBA` to `ED`, then joins that with the rest of the array. Our output therefore is
```
unfurl_reversed test_case
GH
FI
EDCBA
```
### whitespace\_filter
```
#~ [: -. [: */"1 ' ' = ]
' ' = ] Equate each element to space
*/"1 Product of each row (all true?)
-. Negate
#~ Filter rows that are true
```
Basically, this tests to see if any row is completely spaces, and removes it if it is. It doesn't do anything for the first iteration of the test case.
This is necessary (at least until I find an alternative) since otherwise we'll eventually be unfurling whitespace into our output string.
### unfurl
```
|."1@(whitespace_filter @: unfurl_reversed) ^: (1 < #) ^: a:
```
Unfurl basically puts the other functions together and special cases single character inputs.
When the power of verb (`^:`) is given the empty box (`a:`), it applies a function on an input until it converges and collects the results in an array.
`(1 < #)` checks that the rows are always greater than 1 (to special case 1 row inputs).
`|."1` reverses each row, so it inverts the results of `whitespace_filter @: unfurl`.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~143~~ 132 bytes
```
a=input()
while 1:print'\n'.join(a);b=map(''.join,zip(*map(str.strip,a[-2::-1])));a[-1]+=b.pop();a[:-1]=[len(a[0])*' '+x for x in b]
```
[Try it online!](https://tio.run/##NYzJCsIwGITvPkVuSWpbbI8tObjvyz3mkEKlkZr81IjVl4@J4sDANzMw8LKN0blzkikND0vo4NmotkZZAZ3SFp81Tq9GaSJpWbGbBIJ/RfxWQKJQ3G2XeiuIJU/yokgyQSktfcjEkFUpGCAhhoHxtvZffCRohBEe9uhiOtQjpVElnOMYee22GxyjL@5P6z8ejquA48l0Nl8ssfgA "Python 2 – Try It Online")
In each iteration, `b` is the “head” of the string (first n−1 rows), rotated 90 degrees: if `a` is `[" NML", " OPK", "ABCDEFGHIJ"]` then `b` is `["ON", "PM", "KL"]`.
To unfurl a string once, we append the final line of `b` to `a[-1]` (giving `"ABCDEFGHIJKL"`) and then recompute `a[:-1]` by adding spaces to the rest of the strings in `b`.
We terminate by attempting to pop from `b` when it’s empty.
# [Python 2](https://docs.python.org/2/), 132 bytes
```
a=input()
while 1:s=str.strip;print'\n'.join(a);a[:-1]=[len(a[0])*' '+''.join(x)for x in zip(*map(s,a[-2::-1]))];a[-1]+=s(a.pop(-2))
```
[Try it online!](https://tio.run/##NYzJDsIgGITvPgW3H7rF9tiGg/u@3JEDh5piKpCCsfrySI1OMsk3ycyYl2u0KrwXVCrzcJiMno1sa5SXllrXZcHSVKaTysFFQXbTUmFBKsHKNOeUtXWIbMxJBAhi@BV6ctUd6pFU6C0Nju7CYJsIlhblMCOEh4MAMbVYZEYbnBaEeM8ABe13W0jQFw/nzR@Pp/WAk@lsvliugH8A "Python 2 – Try It Online")
Same idea, written differently. We terminate by attempting to `a.pop(-2)` when `a` has only one element.
[Answer]
# [Perl 5](https://www.perl.org/), 155 bytes
```
$"=$,;@a=map[/./g],<>;while(@a){say' 'x(length$s)."@$_"for@a[0..@a-2];say$s.="@{pop@a}";say@b=();for$i(0..$#a){$q=0;$b[$q++][$#a-$i]=$_ for@{$a[$i]}}@a=@b}
```
[Try it online!](https://tio.run/##FY5dC4IwGEbv@xWyXlAxpwVercXbd130C8aQCaaC5fyACvGvt9blczgcHp13dWIMEA4Lhoo/lBYRjQq5WG/Yq6zq3EPlj736uI779ur8WQwl9D4lCCm5Nx0qEVOKKlxJZi3oKSc46kajmsifYMY9n1kTKs@aMLc5aHnMIBPQBoEUFoVQSQ6p8w@OoISd02TvYDYZcz4dZ5frYbbd7b@NHqrm2ZvwltB4Gf8A "Perl 5 – Try It Online")
Saved a few bytes without really modifying the logic. The flow below is still basically correct.
~~# [Perl 5](https://www.perl.org/), 163 bytes~~
```
$"=$,;@a=map[/./g],<>;while(@a){say' 'x(length$s)."@{$a[$_]}"for 0..@a-2;say$s.="@{pop@a}";say@b=();for$i(0..$#a){$b[$_][$#a-$i]=$a[$i][$_]for 0..$#{$a[$i]}}@a=@b}
```
[Try it online!](https://tio.run/##LY7dCoIwFIDvfQqZB1TQaYFXtlj/ddETyIgJpgPToUKF7NVbG3V3@M53Po6shjbTGhCBKKecPLgsEpzULFqt82cj2iqgPJxH/vZd/xW0VVdPDYwhRnQGXsCNKXTvBzfFmPJ4mRsRRkzMVvaScoUsoSUJwtxoIAIjgmeKUNrjwswxCEZsSzCL/jXw5h9TyrxFS6X16Xhwzpe9s9nuPr2cRN@NOr5mOF2kXw "Perl 5 – Try It Online")
**How?**
```
$"=$,; #set the array output separator to null
@a=map[/./g],<>; # take the input as a 2-D array @a
while(@a){ # repeat while there are still things to unfurl
say' 'x(length$s)."@{$a[$_]}"for 0..@a-2; # output all but last
# line of the remaining
# square
say$s.="@{pop@a}"; # remove bottom row, add it to the unfurled string $s
# and output it
say@b=(); # clear temporary array; output empty array, causing
# a newline to output
# rotate remaining shape 90 degrees:
for$i(0..$#a){$b[$_][$#a-$i]=$a[$i][$_]for 0..$#{$a[$i]}}
@a=@b # replace input with rotated array
}
```
] |
[Question]
[
Any regular hexagon can be tiled with diamonds, for instance like so:
```
______
/_/_/\_\
/_/\_\/\_\
/\_\/_/\/_/\
\/_/\_\/_/\/
\_\/_/\_\/
\_\_\/_/
```
We'll consider the above a tiling of size `1` (since the diamonds' sides are made of one `/` or `\` each). The same tiling of size `2` would look like:
```
____________
/ / /\ \
/___/___/ \___\
/ /\ \ /\ \
/___/ \___\/ \___\
/\ \ / /\ / /\
/ \___\/___/ \/___/ \
\ / /\ \ / /\ /
\/___/ \___\/___/ \/
\ \ / /\ \ /
\___\/___/ \___\/
\ \ \ / /
\___\___\/___/
```
Your task is to receive such an ASCII art tiling (of size `1`) as input, along with a positive integer `N` (in decimal or unary), specifying the size of the desired output. You should then output a scaled-up version of the same tiling.
Note that the *hexagon* could be any size and as small as 1x1x1 (containing three diamonds).
Neither input nor output must contain any trailing spaces, nor more leading spaces than necessary to align the hexagon shape. Both input and output may optionally contain a single trailing newline (this choice does not have to be the same for input and output).
You may write a program or function, taking input via STDIN (or closest alternative), command-line argument or function argument and outputting the result via STDOUT (or closest alternative), function return value or function (out) parameter.
This is code golf, so the shortest answer (in bytes) in wins.
## Example Tilings
Here are a handful of input tilings you can use to test your submission.
```
__
/_/\
\_\/
____
/_/\_\
/\_\/_/\
\/_/\_\/
\_\/_/
______
/_/_/\_\
/_/\_\/\_\
/\_\/_/\/_/\
\/_/\_\/_/\/
\_\/_/\_\/
\_\_\/_/
________
/_/\_\_\_\
/\_\/\_\_\_\
/\/_/\/_/_/\_\
/\/\_\/_/_/\/\_\
\/\/_/\_\_\/\/_/
\/\_\/_/\_\/_/
\/\_\_\/_/_/
\/_/_/_/_/
```
The following snippet contains the corresponding outputs for inputs `N = 1` through `N = 6`.
```
__
/_/\
\_\/
____
/ /\
/___/ \
\ \ /
\___\/
______
/ /\
/ / \
/_____/ \
\ \ /
\ \ /
\_____\/
________
/ /\
/ / \
/ / \
/_______/ \
\ \ /
\ \ /
\ \ /
\_______\/
__________
/ /\
/ / \
/ / \
/ / \
/_________/ \
\ \ /
\ \ /
\ \ /
\ \ /
\_________\/
____________
/ /\
/ / \
/ / \
/ / \
/ / \
/___________/ \
\ \ /
\ \ /
\ \ /
\ \ /
\ \ /
\___________\/
____
/_/\_\
/\_\/_/\
\/_/\_\/
\_\/_/
________
/ /\ \
/___/ \___\
/\ \ / /\
/ \___\/___/ \
\ / /\ \ /
\/___/ \___\/
\ \ / /
\___\/___/
____________
/ /\ \
/ / \ \
/_____/ \_____\
/\ \ / /\
/ \ \ / / \
/ \_____\/_____/ \
\ / /\ \ /
\ / / \ \ /
\/_____/ \_____\/
\ \ / /
\ \ / /
\_____\/_____/
________________
/ /\ \
/ / \ \
/ / \ \
/_______/ \_______\
/\ \ / /\
/ \ \ / / \
/ \ \ / / \
/ \_______\/_______/ \
\ / /\ \ /
\ / / \ \ /
\ / / \ \ /
\/_______/ \_______\/
\ \ / /
\ \ / /
\ \ / /
\_______\/_______/
____________________
/ /\ \
/ / \ \
/ / \ \
/ / \ \
/_________/ \_________\
/\ \ / /\
/ \ \ / / \
/ \ \ / / \
/ \ \ / / \
/ \_________\/_________/ \
\ / /\ \ /
\ / / \ \ /
\ / / \ \ /
\ / / \ \ /
\/_________/ \_________\/
\ \ / /
\ \ / /
\ \ / /
\ \ / /
\_________\/_________/
________________________
/ /\ \
/ / \ \
/ / \ \
/ / \ \
/ / \ \
/___________/ \___________\
/\ \ / /\
/ \ \ / / \
/ \ \ / / \
/ \ \ / / \
/ \ \ / / \
/ \___________\/___________/ \
\ / /\ \ /
\ / / \ \ /
\ / / \ \ /
\ / / \ \ /
\ / / \ \ /
\/___________/ \___________\/
\ \ / /
\ \ / /
\ \ / /
\ \ / /
\ \ / /
\___________\/___________/
______
/_/_/\_\
/_/\_\/\_\
/\_\/_/\/_/\
\/_/\_\/_/\/
\_\/_/\_\/
\_\_\/_/
____________
/ / /\ \
/___/___/ \___\
/ /\ \ /\ \
/___/ \___\/ \___\
/\ \ / /\ / /\
/ \___\/___/ \/___/ \
\ / /\ \ / /\ /
\/___/ \___\/___/ \/
\ \ / /\ \ /
\___\/___/ \___\/
\ \ \ / /
\___\___\/___/
__________________
/ / /\ \
/ / / \ \
/_____/_____/ \_____\
/ /\ \ /\ \
/ / \ \ / \ \
/_____/ \_____\/ \_____\
/\ \ / /\ / /\
/ \ \ / / \ / / \
/ \_____\/_____/ \/_____/ \
\ / /\ \ / /\ /
\ / / \ \ / / \ /
\/_____/ \_____\/_____/ \/
\ \ / /\ \ /
\ \ / / \ \ /
\_____\/_____/ \_____\/
\ \ \ / /
\ \ \ / /
\_____\_____\/_____/
________________________
/ / /\ \
/ / / \ \
/ / / \ \
/_______/_______/ \_______\
/ /\ \ /\ \
/ / \ \ / \ \
/ / \ \ / \ \
/_______/ \_______\/ \_______\
/\ \ / /\ / /\
/ \ \ / / \ / / \
/ \ \ / / \ / / \
/ \_______\/_______/ \/_______/ \
\ / /\ \ / /\ /
\ / / \ \ / / \ /
\ / / \ \ / / \ /
\/_______/ \_______\/_______/ \/
\ \ / /\ \ /
\ \ / / \ \ /
\ \ / / \ \ /
\_______\/_______/ \_______\/
\ \ \ / /
\ \ \ / /
\ \ \ / /
\_______\_______\/_______/
______________________________
/ / /\ \
/ / / \ \
/ / / \ \
/ / / \ \
/_________/_________/ \_________\
/ /\ \ /\ \
/ / \ \ / \ \
/ / \ \ / \ \
/ / \ \ / \ \
/_________/ \_________\/ \_________\
/\ \ / /\ / /\
/ \ \ / / \ / / \
/ \ \ / / \ / / \
/ \ \ / / \ / / \
/ \_________\/_________/ \/_________/ \
\ / /\ \ / /\ /
\ / / \ \ / / \ /
\ / / \ \ / / \ /
\ / / \ \ / / \ /
\/_________/ \_________\/_________/ \/
\ \ / /\ \ /
\ \ / / \ \ /
\ \ / / \ \ /
\ \ / / \ \ /
\_________\/_________/ \_________\/
\ \ \ / /
\ \ \ / /
\ \ \ / /
\ \ \ / /
\_________\_________\/_________/
____________________________________
/ / /\ \
/ / / \ \
/ / / \ \
/ / / \ \
/ / / \ \
/___________/___________/ \___________\
/ /\ \ /\ \
/ / \ \ / \ \
/ / \ \ / \ \
/ / \ \ / \ \
/ / \ \ / \ \
/___________/ \___________\/ \___________\
/\ \ / /\ / /\
/ \ \ / / \ / / \
/ \ \ / / \ / / \
/ \ \ / / \ / / \
/ \ \ / / \ / / \
/ \___________\/___________/ \/___________/ \
\ / /\ \ / /\ /
\ / / \ \ / / \ /
\ / / \ \ / / \ /
\ / / \ \ / / \ /
\ / / \ \ / / \ /
\/___________/ \___________\/___________/ \/
\ \ / /\ \ /
\ \ / / \ \ /
\ \ / / \ \ /
\ \ / / \ \ /
\ \ / / \ \ /
\___________\/___________/ \___________\/
\ \ \ / /
\ \ \ / /
\ \ \ / /
\ \ \ / /
\ \ \ / /
\___________\___________\/___________/
________
/_/\_\_\_\
/\_\/\_\_\_\
/\/_/\/_/_/\_\
/\/\_\/_/_/\/\_\
\/\/_/\_\_\/\/_/
\/\_\/_/\_\/_/
\/\_\_\/_/_/
\/_/_/_/_/
________________
/ /\ \ \ \
/___/ \___\___\___\
/\ \ /\ \ \ \
/ \___\/ \___\___\___\
/\ / /\ / / /\ \
/ \/___/ \/___/___/ \___\
/\ /\ \ / / /\ /\ \
/ \/ \___\/___/___/ \/ \___\
\ /\ / /\ \ \ /\ / /
\/ \/___/ \___\___\/ \/___/
\ /\ \ / /\ \ / /
\/ \___\/___/ \___\/___/
\ /\ \ \ / / /
\/ \___\___\/___/___/
\ / / / / /
\/___/___/___/___/
________________________
/ /\ \ \ \
/ / \ \ \ \
/_____/ \_____\_____\_____\
/\ \ /\ \ \ \
/ \ \ / \ \ \ \
/ \_____\/ \_____\_____\_____\
/\ / /\ / / /\ \
/ \ / / \ / / / \ \
/ \/_____/ \/_____/_____/ \_____\
/\ /\ \ / / /\ /\ \
/ \ / \ \ / / / \ / \ \
/ \/ \_____\/_____/_____/ \/ \_____\
\ /\ / /\ \ \ /\ / /
\ / \ / / \ \ \ / \ / /
\/ \/_____/ \_____\_____\/ \/_____/
\ /\ \ / /\ \ / /
\ / \ \ / / \ \ / /
\/ \_____\/_____/ \_____\/_____/
\ /\ \ \ / / /
\ / \ \ \ / / /
\/ \_____\_____\/_____/_____/
\ / / / / /
\ / / / / /
\/_____/_____/_____/_____/
________________________________
/ /\ \ \ \
/ / \ \ \ \
/ / \ \ \ \
/_______/ \_______\_______\_______\
/\ \ /\ \ \ \
/ \ \ / \ \ \ \
/ \ \ / \ \ \ \
/ \_______\/ \_______\_______\_______\
/\ / /\ / / /\ \
/ \ / / \ / / / \ \
/ \ / / \ / / / \ \
/ \/_______/ \/_______/_______/ \_______\
/\ /\ \ / / /\ /\ \
/ \ / \ \ / / / \ / \ \
/ \ / \ \ / / / \ / \ \
/ \/ \_______\/_______/_______/ \/ \_______\
\ /\ / /\ \ \ /\ / /
\ / \ / / \ \ \ / \ / /
\ / \ / / \ \ \ / \ / /
\/ \/_______/ \_______\_______\/ \/_______/
\ /\ \ / /\ \ / /
\ / \ \ / / \ \ / /
\ / \ \ / / \ \ / /
\/ \_______\/_______/ \_______\/_______/
\ /\ \ \ / / /
\ / \ \ \ / / /
\ / \ \ \ / / /
\/ \_______\_______\/_______/_______/
\ / / / / /
\ / / / / /
\ / / / / /
\/_______/_______/_______/_______/
________________________________________
/ /\ \ \ \
/ / \ \ \ \
/ / \ \ \ \
/ / \ \ \ \
/_________/ \_________\_________\_________\
/\ \ /\ \ \ \
/ \ \ / \ \ \ \
/ \ \ / \ \ \ \
/ \ \ / \ \ \ \
/ \_________\/ \_________\_________\_________\
/\ / /\ / / /\ \
/ \ / / \ / / / \ \
/ \ / / \ / / / \ \
/ \ / / \ / / / \ \
/ \/_________/ \/_________/_________/ \_________\
/\ /\ \ / / /\ /\ \
/ \ / \ \ / / / \ / \ \
/ \ / \ \ / / / \ / \ \
/ \ / \ \ / / / \ / \ \
/ \/ \_________\/_________/_________/ \/ \_________\
\ /\ / /\ \ \ /\ / /
\ / \ / / \ \ \ / \ / /
\ / \ / / \ \ \ / \ / /
\ / \ / / \ \ \ / \ / /
\/ \/_________/ \_________\_________\/ \/_________/
\ /\ \ / /\ \ / /
\ / \ \ / / \ \ / /
\ / \ \ / / \ \ / /
\ / \ \ / / \ \ / /
\/ \_________\/_________/ \_________\/_________/
\ /\ \ \ / / /
\ / \ \ \ / / /
\ / \ \ \ / / /
\ / \ \ \ / / /
\/ \_________\_________\/_________/_________/
\ / / / / /
\ / / / / /
\ / / / / /
\ / / / / /
\/_________/_________/_________/_________/
________________________________________________
/ /\ \ \ \
/ / \ \ \ \
/ / \ \ \ \
/ / \ \ \ \
/ / \ \ \ \
/___________/ \___________\___________\___________\
/\ \ /\ \ \ \
/ \ \ / \ \ \ \
/ \ \ / \ \ \ \
/ \ \ / \ \ \ \
/ \ \ / \ \ \ \
/ \___________\/ \___________\___________\___________\
/\ / /\ / / /\ \
/ \ / / \ / / / \ \
/ \ / / \ / / / \ \
/ \ / / \ / / / \ \
/ \ / / \ / / / \ \
/ \/___________/ \/___________/___________/ \___________\
/\ /\ \ / / /\ /\ \
/ \ / \ \ / / / \ / \ \
/ \ / \ \ / / / \ / \ \
/ \ / \ \ / / / \ / \ \
/ \ / \ \ / / / \ / \ \
/ \/ \___________\/___________/___________/ \/ \___________\
\ /\ / /\ \ \ /\ / /
\ / \ / / \ \ \ / \ / /
\ / \ / / \ \ \ / \ / /
\ / \ / / \ \ \ / \ / /
\ / \ / / \ \ \ / \ / /
\/ \/___________/ \___________\___________\/ \/___________/
\ /\ \ / /\ \ / /
\ / \ \ / / \ \ / /
\ / \ \ / / \ \ / /
\ / \ \ / / \ \ / /
\ / \ \ / / \ \ / /
\/ \___________\/___________/ \___________\/___________/
\ /\ \ \ / / /
\ / \ \ \ / / /
\ / \ \ \ / / /
\ / \ \ \ / / /
\ / \ \ \ / / /
\/ \___________\___________\/___________/___________/
\ / / / / /
\ / / / / /
\ / / / / /
\ / / / / /
\ / / / / /
\/___________/___________/___________/___________/
```
[Answer]
# Python 2, 164
```
def g(s,n,j=1):
for W in s.split("\n"):exec"O=p='';d=0\nfor c in W:q=' _'[j*'_'in p+c];e=[n-j,j-1][c=='/'];O+=q*(e+d)+[c,q][c>'^'];p=c;d=n+~e\nprint O;j-=1;"*j;j=n
```
[Output on test cases.](https://ideone.com/vmj4uk)
So, what's going on here?
The main idea is that each character in the original blows up into an `n*n` block. For example, for n=4, `/` might become
```
/
/
/
/___
```
The original character appears once in each line, and there's padding to either side. Here, it's on the left, and and `_` on the right. Only the bottom row can be padded by `'_'`; the rest is always `' '`.
The main difficulty is that the padding on the right can depend on the upcoming symbol. Specifically, `'/ '` has different padding from `'/_'`, so we'd need some look-ahead. Moreover, to avoid trailing spaces, we'd have to note that we're at the last symbol and refrain from padding on the right.
We overcome both these issues by only padding to the left of the current character. When we do so, we also perform the right-padding from the previous character using the current padding symbol. So, we print the right-padding owed from the previous char, the left-padding from the current char, then the current char. We also store the amount of padding "debt" the next char will need to pay.
Now let's go over the code.
```
def g(s,n,j=1):
for W in s.split("\n"):
while j:
O=p='';d=0
for c in W:
q=' _'[j*'_'in p+c]
e=[n-j,j-1][c=='/']
O+=q*(e+d)+[c,q][c>'^']
p=c
d=n+~e
print O;j-=1;
j=n
```
The input string is `s` and the scale-factor is `n`. We go line-by-line, printing `n` lines for each input line `W`, with the copies indexed `j=n,n-1,...,2,1`. The first line is only copied once, which we achieve this by initializing `j` to 1 but changing it to `n` each loop.
We iterate through the input line, accumulating the line to print in `O`. First, we figure out the appropriate padding character `q`, which is an underscore if we're on the bottom line and either the current or previous character is an underscore, and otherwise a space.
Then, we decide the amount of padding to put on the left (`e`). For `/`, it's `j-1` (decreasing with decreasing line-copy number), and the complementary `n-j` for `\`. We treat other characters the same way. For example, though `_` seems like it gives a row of `n` underscores, it actually gives a single underscore, padded by underscores on the left and right. This seems inefficient, but it lets us works with `_` and in the same framework as `/` and `\` The position of the "central" underscore doesn't matter, so we lump it and with `\`; this choice also makes the top row work out without special casing.
Next, we add to the output string. We've figured out the padding symbol `q`, and the current padding amount `e`, but we also need to remember the padding debt `d` from the previous symbol. So, we add `q*(e+d)`. Then, we add the current symbol `c`, except we need to avoid underscores in a non-bottom row, which we fix by converting underscores to the padding symbol.
Finally, we record the padding debt amount, which the complement `n+~d` of the current left-padding amount. We also record the current symbol in `p`, so that we will later know whether the previous symbol was `_`.
[Answer]
# CJam, 85 79 76 72 bytes
```
li:Tlf*NqN/T,f{ff{"_/"2$#_1<@+*~ST*@t}:+z{S+e`);e~{"_ "/"__"*W%}T2**N}/}
```
The size should be on the first line. And the diamond follows.
Not golfed very well... And half of the characters came from the details.
### Explanations (of previous version)
```
li:T e# Read the size and save to T.
qN/ e# Read and split to lines.
\,fm* e# Convert each character X to [X 0] [X 1]... [X T(]
{~ e# For each [X I] in each line:
ST* e# T spaces.
\ e# I.
"_\\"3$# e# If X is '_, '\ or '/, return Y = 0, 1, -1 respectively.
_W>@+ e# If it was '_ or '\, increase I by one.
*( e# I * Y - 1.
@t e# Set the character at that position to X.
}f%
:z:+ e# Make the returned lists from each iteration across T lines.
{S+e`);e~N+}% e# Boring details to remove trailing spaces and append a newline.
T(>(\s e# Boring details to extract the first line and only work on others.
{_{"_ "/"__"*W%}2*_@=!}g
e# Boring details to make underlines expand left and right.
```
[Answer]
# JavaScript (*ES6*) 274 ~~281 289 338~~
```
// GOLFED
F=(b,n)=>{
b=b[R='replace'](/ |_/g,c=>c[T='repeat'](n))[R](/_(?=[\\\/])/g,'_'[T](n))[R](/\/\\/g,`/${' '[T](n-1)}\\`)
.split('\n');
for(i=l=b.length*n-n+1;--i;)
b[i]=i%n?b[i+1][R](/_/g,' ')[R](/\/ ?/g,' /')[R](/ \\(.)?/g,'\\$1$1')
:' '[T](i>l/2?n-1:0)+b[i/n];
return b.join('\n')}
// UNGOLFED
U=(b,n)=>{
b=b
.replace(/ |_/g,c=>c.repeat(n))
.replace(/_(?=[\/\\])/g,'_'.repeat(n))
.replace(/\/\\/g,`/${' '.repeat(n-1)}\\`)
.split('\n');
for(i=l=b.length*n-n+1;--i;)
{
if(i%n)
b[i]=b[i+1]
.replace(/_/g,' ')
.replace(/\/ ?/g,' /')
.replace(/ \\/g,'\\ ').replace(/ +$/,'')
.replace(/ \\(.)?/g,'\\$1$1')
else {
b[i]=b[i/n]
if(i>l/2)b[i]=' '.repeat(n-1)+b[i];
}
}
return b.join('\n')
}
//TEST
test=[
' __\n/_/\\\n\\_\\/',
' ____\n /_/\\_\\\n/\\_\\/_/\\\n\\/_/\\_\\/\n \\_\\/_/',
' ______\n /_/_/\\_\\\n /_/\\_\\/\\_\\\n/\\_\\/_/\\/_/\\\n\\/_/\\_\\/_/\\/\n \\_\\/_/\\_\\/\n \\_\\_\\/_/',
' ________\n /_/\\_\\_\\_\\\n /\\_\\/\\_\\_\\_\\\n /\\/_/\\/_/_/\\_\\\n/\\/\\_\\/_/_/\\/\\_\\\n\\/\\/_/\\_\\_\\/\\/_/\n \\/\\_\\/_/\\_\\/_/\n \\/\\_\\_\\/_/_/\n \\/_/_/_/_/'
]
test.forEach(t=>{
var row = '<td>'+t+'<td>'
for(rr=2;rr<5;rr++)
row += '<td>'+F(t,rr)+'</td>'
OUT.innerHTML += '<tr>'+row+'</tr>'
})
```
```
td {
font-family: monospace;
white-space: pre;
}
```
```
(better full page)
<table id=OUT></table>
```
[Answer]
# Python 2, ~~217~~ ~~211~~ ~~195~~ ~~194~~ 190
```
b,f,s='\/ '
R=str.replace
def m(g,n,z=1):
for d in g.split('\n'):
for i in range(z):a=z+~i;print[i,a][d[-1]>f]*s+R(R(R(R(d,s,s*n),'_','_ '[i<z-1]*(z+n-1)),f+b,f+s*2*i+b),b+f,b+s*2*a+f);z=n
```
*6 bytes thanks to Sp3000.*
Call `m` with the first argument being the diamond as a string, and the second argument the repetition number.
This is based on a 3-step string replacement sequence:
* First, replace underscores with 2n-1 spaces or underscores, depending on the line.
* Second, replace `/\` with `/ \`, with the number of intervening spaces going from 2 to 2\*(n-1) over the lines.
* Third, replace `\/` with `\ /`, with the number of intervening spaces going from 2\*(n-1) to 2 over the lines.
Then, there's a variety of mucking about to get the leading spaces right, and to get the first line right.
Note that the final line of the program should be a tab, not 4 spaces. Markdown doesn't support tabs.
[Answer]
# Python, ~~272~~ ~~238~~ ~~228~~ 243 bytes
Updated version, now takes a single string as input, instead of a string sequence. Also removes trailing whitespace that was present in earlier version. Unfortunately these changes increase the size.
```
s,u,f,b=' _/\\'
r=str.replace
def d(t,n,j=1):
for p in t.split('\n'):
for k in range(n-j,n):m,v=n+~k,'_ '[k<n-1];print r(r(r(r(r(r(r(r(p,f+u,'(_'),u+b,'_)'),s,s*n),u,v*n),f,s*m+f+s*k),'(',v*m+f+v*k),b,s*k+b+s*m),')',v*k+b+v*m).rstrip();j=n
```
Version with whitespace, and statements broken up into smaller units for readability:
```
s, u, f, b = ' ', '_', '/', '\\'
def d(t, n):
j = n - 1
for p in t:
for k in range(j, n):
m, v = n - 1 - k, '_ '[k < n - 1]
q = p[:-1]
q = q.replace(f + u, '(_')
q = q.replace(u + b, '_)')
q = q.replace(s, s * n)
q = q.replace(u, v * n)
q = q.replace(f, s * m + f + s * k)
q = q.replace('(', v * m + f + v * k)
q = q.replace(b, s * k + b + s * m)
q = q.replace(')', v * k + b + v * m)
print q
j = 0
```
The basic approach here is:
1. Loop over all lines in input.
2. For each line, loop over the output size `N`, generating an output line in each loop iteration. There's a special case for the first line, where only the last output line is generated, to avoid generating empty lines at the start of the output.
3. Replace each character in the line by `N` characters, where:
* Each space is replaced by `N` spaces.
* Each underscore is replaced by `N` spaces for the first `N -1` loop iterations, and `N` underscores for the last loop iteration.
* Slashes and backslashes are padded with `N - 1` spaces or underscores.
The most tricky part here is that the padding for slashes/backslashes uses spaces or underscores depending on the next (for slashes) or previous (for backslashes) input character. That did not seem to fit well with the string substitution strategy.
What I did to resolve this is that I first replace certain two character combinations with different characters, so that I can treat them differently during the actual substitution. For example, `/_` is replaced by `(_`. After this, `(` is effectively a "slash followed by underscore", which can then be substituted accordingly.
Main program used for testing the function:
```
import sys
import Golf
n = int(sys.argv[1])
t = ''.join(sys.stdin).rstrip()
Golf.d(t, n)
```
[Answer]
# Perl, 132
```
#!perl -p
INIT{$f=pop}s!.!$&x$f!ge;s! $!! while s!\\+\K\\|/(/)! $1!;
for$x(2..m!/!*$f){print y!_! !r;s!\\.?! \\!g;s!./(.)?!/$1$1!g;s!_ !__!g}
```
Combined STDIN and ARGV input. Example:
```
$ perl ~/hex.pl <~/hex.txt 3
__________________
/ / /\ \
/ / / \ \
/_____/_____/ \_____\
/ /\ \ /\ \
/ / \ \ / \ \
/_____/ \_____\/ \_____\
/\ \ / /\ / /\
/ \ \ / / \ / / \
/ \_____\/_____/ \/_____/ \
\ / /\ \ / /\ /
\ / / \ \ / / \ /
\/_____/ \_____\/_____/ \/
\ \ / /\ \ /
\ \ / / \ \ /
\_____\/_____/ \_____\/
\ \ \ / /
\ \ \ / /
\_____\_____\/_____/
```
[Answer]
# Ruby 236 ~~237~~
```
->i,z{i.split(?\n).map{|l|z.times.map{|y|l.size.times.map{|i|z.times.map{|x|c=l[i]
z<y+2&&(l[i-1..i]=='_\\'||l[i..i+1]=='/_')&&o=?_
(c<?!||(x==y&&c==?\\)||(z==y+1&&c>?^)||(x+y+1==z&&c==?/))&&o=c
o||' '}.join}.join.rstrip}-['']}.join ?\n}
```
Online test: <http://ideone.com/e6XakQ>
This is the code before golfing:
```
-> diamond, zoom {
diamond.split(?\n).map do |l|
zoom.times.map do |y|
l.size.times.map do |i|
zoom.times.map do |x|
out_char = crt_char = l[i]
out_char = ' '
# _ has to be continued under / or \
if zoom == y+1 && l[i-1..i]=='_\\'
out_char = ?_
end
if zoom == y+1 && l[i..i+1]=='/_'
out_char = ?_
end
# logic to "zoom" \, / and _ characters
out_char = crt_char if crt_char == ' '
out_char = crt_char if x==y && crt_char == ?\\
out_char = crt_char if zoom==y+1 && crt_char == ?_
out_char = crt_char if x+y+1==zoom && crt_char == ?/
out_char
end.join
end.join.rstrip
end - ['']
end.join ?\n
}
```
] |
[Question]
[
iBug recently got a long bar made of composite, yet valuable materials. The bar is so long that iBug can't easily sell it for credits, so he wants to cut it. The bar is made of such fragile and magic materials that, if a part is broken, all parts of the bar made of the same material will break, too, making it hard to cut arbitrarily.
iBug wants to cut the bar into as many pieces as possible. He also loves very short programs and code-golfing, so he made an abstract analysis of his problem.
iBug's magic bar is represented as a string (or an array or a sequence of characters if you prefer), like this:
```
aaabbccccccbbbaaacccccaabbbaaaaa
```
Each letter in the string represents one magic material. The bar always matches the RegEx `^\w*$`, so there may be up to 63 materials in the bar. A "part" is a consecutive sequence of any characters that are not separated by spaces.
iBug wants you to write a program that calculates the maximum parts that he could get, if zero or more character sets are fully removed (replaced by spaces), and tell iBug that number.
---
Example 1:
```
In: aaabbccccccbbbaaacccccaabbbaaaaa
Out: 4
```
Description: If `b` is fully removed from the bar, iBug could get 4 parts. He can also get 4 parts by removing `b` and `c`, as is shown below
```
aaabbccccccbbbaaacccccaabbbaaaaa # Original string
aaa cccccc aaacccccaa aaaaa # Remove 'b'
aaa aaa aa aaaaa # Remove 'b' and 'c'
```
And that's the maximum number of parts iBug can get from this bar
Example 2:
```
In: 111aa___9999____aaa99111__11_a_aa999
Result: 111aa 9999 aaa99111 11 a aa999
Out: 6
```
Description: By removing only the underscore, iBug can get 6 parts from the bar and that's the maximum.
Example 3:
```
In: __________
Out: 1
```
Description: What? You wanna cut this? It's only possible to get 1 part if you don't cut it at all.
Example 4:
```
In:
Out: 0
```
Description: There's nothing to cut, so zero.
---
There's also some rules that iBug want the programs to obey:
1. iBug dislikes standard loopholes and they are forbidden.
2. As long as it works, it need not be a full program. A function that takes input from a parameter and gives output via return value is also accepted.
3. Flexible input and output are allowed. Your program or function can take a string, or an array of characters, or whatever you find easiest to deal with. You can give the output by printing the number or returning it.
---
### Sample test cases (but not limited to these)
```
aaabbbaaa = 2
123456789 = 5
AaAaAaAa = 4
aaabcccdedaaabefda = 6
________ = 1
(empty) = 0
```
Since this is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest program (in bytes) in each language wins!
---
### Extra
iBug highly appreciates if you can provide an explanation for your program, even though it does not affect your scoring (it's still length in bytes).
[Answer]
# [Haskell](https://www.haskell.org/), ~~73 71~~ 70 bytes
```
x#z|z==x=' '|1<2=z
f x=maximum$length(words x):[f$(c#)<$>x|c<-x,c>' ']
```
Thanks to [Laikoni](https://codegolf.stackexchange.com/users/56433/laikoni) for saving 1 byte!
[Try it online!](https://tio.run/##dY1Ba4NAEIXv/orpRohCCtXGJA1uILka6iHHUpp1d62SVYuudCP@d7uhsezBvoFhmPnem4w0Fy7EMKhZ13cYKzyHee@FPu6sFBQuiMqLtrAFLz9l5nxXNWtAudu31HbozA3tnepp@KgWdKeN74OCc5NVrWAHfoYrYPhq5UnWxxKcXOcBxnorM14CiiMEXDQc0GslIY4ekGtZBclL7WKVBVopIEJIkiS6I/iT8cIfOc9/Xgar9eZlmgtGbk9@y8BMbmn@pZQyzm4TT5l2GNxq5D7u@ifPGznzPsE9DT8 "Haskell – Try It Online")
[Answer]
## JavaScript (ES6), ~~109~~ 90 bytes
```
f=s=>Math.max((s.match(/\s+/g)||[]).length,...[...s].map(c=>c>` `&&f(s.split(c).join` `)))
```
```
<input oninput=o.textContent=/\s/.test(this.value)?``:f(this.value)><pre id=o>0
```
Somewhat slow on the `123456789` test case. Previous 109-byte answer wasn't limited to `!/\s/`:
```
f=
s=>(g=a=>Math.max(a.filter(s=>s).length,...[...a.join``].map(c=>g([].concat(...a.map(s=>s.split(c)))))))([s])
```
```
<input oninput=o.textContent=f(this.value)><pre id=o>0
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~111~~ ~~93~~ 72 bytes
-21 bytes thanks [Kirill L.](https://codegolf.stackexchange.com/users/78274/kirill-l)
```
f=lambda s:max([len(s.split())]+[f(s.replace(c,' '))for c in s if'/'<c])
```
[Try it online!](https://tio.run/##LY3LCsIwEEX3fsXQTRIsVeu72IXfUYpM0gQDaRqaLJTSb4@NOgPDuYeB697hOdgyRlUb7HmH4KseX7Qx0lJfeGd0oIy160YtcZTOoJBU5AQIY2oYQYC24EErsiE30bKYZEgyQ0TO@XKzHLJduT8cT@fLNYU7/jZx@hJCdLJLJFX3tY//JM6qFYAbtQ1ApqrczlDDNJNiaeox0JCDooGx@AE "Python 2 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~13~~ 11 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
~~Too many 2-byte instructions~~
-2 thanks to Zgarb (use the outer product quick `þ` >.<)
```
eþŒPŒr¬S€ṀḢ
```
A monadic link accepting a list of characters and returning a non-negative integer.
**[Try it online!](https://tio.run/##y0rNyan8/z/18L6jkwKOTio6tCb4UdOahzsbHu5Y9P//f6XExMSk5OTklNQUECs1LSVRCQA "Jelly – Try It Online")**
### How?
For each subsequence of the input (the sets we may remove, plus redundant equivalents) gets an existence list to identify which are removed then effectively finds how many runs of zeros remain and yields the maximum. The last part works in a slightly odd way since I found it golfier than more naive alternatives - it finds the runs as `[element, count]` pairs, negates to identify zeros as ones, sums finds the maximum then takes the head (the sum of elements rather than of counts).
```
eþŒPŒr¬S€ṀḢ - Link: list of characters e.g. "aabcde"
ŒP - power-set - gets all subsequences ["","a","a","b",...,"bd",...,"aabcde"]
þ - outer-product with:
e - exists in? [[0,0,0,0,0,0],[1,1,0,0,0,0],[1,1,0,0,0,0],[0,0,1,0,0,0],..,[0,0,1,0,1,0]...,[1,1,1,1,1,1]]
Œr - run-length encode [[[0,6]],[[1,2],[0,4]],[[1,2],[0,4]],[[0,2],[1,1],[0,3]],...,[[0,2],[1,1],[0,1],[1,1],[0,1]],...,[[1,6]]]
¬ - NOT [[[1,0]],[[0,0],[1,0]],[[0,0],[1,0]],[[1,0],[0,0],[1,0]],...,[[1,0],[0,0],[1,0],[0,0],[1,0]],...,[[0,0]]]
€ - for €ach:
S - sum [[1,0],[1,0],[1,0],[2,0],...,[3,0],...,[0,0]]
Ṁ - maximum [3,0]
Ḣ - head 3
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~98 89 75 64~~ 61 bytes
```
f=->s{[s.split.size,*s.scan(/\w/).map{|c|f[s.tr c,' ']}].max}
```
[Try it online!](https://tio.run/##Xc7bDsIgDADQ931Fsz1MDaLO@4MmfsckhjGmLF4WYfHC@PbZKU@WpLSnkPReZ6@2LTbDrbappro6K0O1eksywE7wa2@0f4z69MIr24imwDfmDoLEEDPHkJ@urWqjIVRXvOEvjjck@aykMDIPgzQASGPOeZZlmGMCCSNfmyTT2XyxXK3R5t52/HeQZp66r0KIXOZdJYu8Gy788OADaeIJyzELGJVcnMA2ipQN/NaNrKLnstYGkrGDyBapYm6P20a2dKFrPw)
smaller and slower than before!
Basically a port of [@Neil's Javascript answer](https://codegolf.stackexchange.com/a/157123/77598)
### Ungolfed and annotated
```
def f(input_string)
# splits by / +/ by default
size0 = input_string.split.size
# an array of all non-space characters in input_string
characters = input_string.scan(/\w/)
size1 = characters.map {|i|
# all letters and digits and _ are "bigger" than /, space isn't
if i > '/'
# tr replaces every occurrence of i in input_string with space
next_string = input_string.tr(i, ' ')
f(next_string) # recursive call
else
0
end
}
# max value between size0 and any element in size1
return [size0, *size1].max
end
```
[Try it online!](https://tio.run/##XVPbbuIwEH3nK0bhIWQ3mwDbdtuHrdTvoAhNnEkwCiayHS6FfDsdO1EKOFIYnZlz5own6CY7Xa85FVBMpKobuzJWS1VGI@AzBlNX0hrITpDC79T9ci02lfV5I79oCv/hlpl4SuJSvQYqQK3xBLsCsKpA7dQfU6MgEGvUKCxpwxJ3Kp56k37sIVBN0s9DGg0@ZlzzQ0i2WMP5Ii8@3/vg3hVZr4cqh1yWbjYXrtghQZDJsiQdgF2z5zSGzqU0KrSDjixAwjuEaThAnbzVoKmumGGA9qR5XiEarUmxxs6xHmaEg7TrrsedlKLjUPIwt9UTGUMIYXTHKCY3nIi9aOLORu75innqoZYqc99q@pNSuY/bfmlbPMIeq4YgI3sgUv2y3W2hOrEUbUlZN5O/fU/TZButYOFLY/jlM0vexXHE@lcexEDgB4KHU@4YomNNvL08GC1YbhEiYpZl/A5jmC9jj83mf5@eX/69vjH23GMf2D0MPfWQowohcspdREXuki99ctUfhmY9xOF0OVomhGLtvpt4c4HO7vgsk2rTGAvzaQvjM/9PovaT3Y7PmzZor98)
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~12~~ 11 bytes
```
▲mȯ#€0gM€¹Ṗ
```
[Try it online!](https://tio.run/##yygtzv7//9G0Tbkn1is/alpjkO4LJA/tfLhz2v///5UcEyFQCQA "Husk – Try It Online")
This works by brute force and is quite slow.
Add `u` to the right end to make it run faster, without changing the semantics.
## Explanation
```
▲mȯ#€0gM€¹Ṗ Implicit input, say S = "abddccbdcaab"
Ṗ Powerset of S: P = ["","a","b","ab","d","ad"...,"abddccbdcaab"]
m Map this function over P:
Argument is a subsequence, say R = "acc"
M ¹ Map over S
€ index of first occurrence in R: [1,0,0,0,2,2,0,0,2,1,1,0]
g Group equal elements: [[1],[0,0,0],[2,2],[0,0],[2],[1,1],[0]]
ȯ# Count the number of groups
€0 that contain 0: 3
▲ Take maximum of the results: 4
```
[Answer]
# [Perl 5](https://www.perl.org/), (older versions), `-p -I.`, ~~52~~ ~~49~~ 43 bytes
Old style counting: `+3` for `-p`: `46` bytes (because it **must** be in a program, it can't be run using `-e`)
`barsplit.pl`:
```
#!/usr/bin/perl -pI.
$G[split]+=s%\S%do$0for s/$&/ /rg%eg;$_=$#G
```
Run with the string on STDIN:
```
echo aaabcccdedaaabefda | ./barsplit.pl; echo
```
[Try it online!](https://tio.run/##K0gtyjH9/1/FPbq4ICezJFbbtlg1Jlg1JV/FIC2/SKFYX0VNX0G/KF01Nd1aJd5WRdn9///ExMSk5OTklNQUECs1LSWR619@QUlmfl7xf92C/7qeegA "Perl 5 – Try It Online")
The `-I.` option is there to make this also work on recent perls where by default `.` is no more in `@INC`. In older versions of perl that option is not needed. I tested that on an older machine that still had `perl 5.20`, so the score is based on that (otherwise I should also count the `.` argument to `-I`)
Fast version (`49` bytes):
```
#!/usr/bin/perl -pI.
$G[split]+=s%.%$$_++||do$0for s/$&/ /rg%eg;$_=$#G
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 77 bytes
```
Max@Table[Tr[1^StringSplit[#,(##|##)..&@@s]],{s,Subsets@Union@Characters@#}]&
```
[Try it online!](https://tio.run/##LYvNCsIwEIRfJSRQFGKl/ntQIp4FofUUo2zS1BbaKk0EofbZa6LOwvDN7k4FNtcV2EJBn6FNf4AXS0CWmicNjy6xbYr6Fj/KwnJCB4S8CRmGYcCYEYK2hsZPabQ17FQX95rtc2hAWd0YRjoR9EfXthyfMaaIUOQAjbbIhYwTIVCAxgy1GACklM7dAUeT6Wy@WK7WPuzgN579l1Iq1aknnaXf7fUvz7jrPw "Wolfram Language (Mathematica) – Try It Online")
] |
[Question]
[
*Title is made up, from 'Sequence Index Digit Not'.*
## Challenge:
Given an integer `n` which is `>= 0`, output the `n`'th number of the following sequence.
Here are the first 50 items, with it's (0-indexed) index above it:
```
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
1 0 3 2 5 4 7 6 9 8 22 20 30 24 23 26 25 28 27 32 11 33 10 14 13 16 15 18 17 31 12 29 19 21 50 40 41 42 44 45 35 36 37 51 38 39 52 53 55 56 34
```
## How does this sequence work?
The number at index `n` must be the first in order that does not have any digits in common with `n`, and hasn't occurred yet for previous indexes. So when we look at normal sequence like this from `0-60`:
```
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
```
We define the `n`'th values like this:
* `0`: The first number (`0`) contains the same digit, so we look for the next (`1`), which does not contain the same digit. So `n=0` outputs `1`.
* `1`: The first number (`0`) does not contain the same digit, so `n=1` outputs `0`.
* `2`: We've already encountered `0` and `1`, and the next digit (`2`) contains the same digit, so we look for the next (`3`), which does not contain the same digit. So `n=2` outputs `3`.
* ...
* `10`: We've already encountered `0-9`, so the next in line is `10`. `10-19` contain the matching digit `1`, `20` contains the matching digit `0`, `21` contains the matching digit `1` again, `22` is valid, so `n=10` outputs `22`.
* etc.
## Challenge rules:
* If your language is 1-indexed (or you choose to) you are allowed to start the sequence at `3 2 5 4 7 ...` (skipping the `1` at `n=0` and the `0` at `n=1`).
* The minimum largest index you should support is `25,000`. *NOTE: The sequence stops at index `1,023,456,788`, because the next index in line contains all 10 digits.*
* You are also allowed to output / return an array/list of the entire sequence up to and including index `n` if you want to.
## General rules:
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so 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](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
* [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
* If possible, please add a link with a test for your code.
* Also, please add an explanation if necessary.
## Test cases:
*This sequence actually created pairs regarding index and outputs. If index `n` outputs `o`, index `o` outputs `n`.* So you can input either the left or right, and the output will be the other side:
```
0 <-> 1 (this test case is optional)
2 <-> 3
10 <-> 22
12 <-> 30
34 <-> 50
89 <-> 100
111 <-> 200
112 <-> 300
199 <-> 322
2231 <-> 4456
9605 <-> 11118
19235 <-> 46000
23451 <-> 60668
25000 <-> 13674
```
[Here is a pastebin of the first 25,001 test cases if you want to try others.](https://pastebin.com/FEL5jm4n)
[Answer]
# [Python 2](https://docs.python.org/2/), ~~92~~ ~~91~~ ~~89~~ 88 bytes
```
a=()
i=0
exec"x=0\nwhile set(`x`)&set(`i`)or x in a:x+=1\na+=x,;i+=1;"*-~input()
print a
```
[Try it online!](https://tio.run/##Hcw7CoAwDADQ3VMEB2n9QHVUchOHFik0ILFoxbh49Spub3rxTmHjIWeHSheEpvDil1LQzHwFWj0cPikrVlc/yOptBwFicKM02M/sGpR2os9TWXcPcTzTd8WdOIHLuTcv "Python 2 – Try It Online")
Prints a list of the first `n+1` numbers
---
Different approach, which is a lot faster:
# [Python 2](https://docs.python.org/2/), 96 bytes
```
n=input()
r=range(9*n)
i=0
exec"x=0\nwhile set(`r[x]`)&set(`i`):x+=1\nprint r.pop(x),;i+=1;"*-~n
```
[Try it online!](https://tio.run/##HchLCsJADADQ/ZyidCGT@mHqTktO0gojEmxA0hBHGjdefRR3j6fvMi9yrFWQRV8lQjC0q9wpnjqBwJgCOd1axzTJOvODmieVmG30S4bN35zh7FvsJ1FjKY0ddNHosBv4t0Pb7T9Sa59S@gI "Python 2 – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 18 bytes
```
u+Gf!|}TG@`H`T0hQY
```
**[Try it here!](https://pyth.herokuapp.com/?code=eu%2BGf%21%7C%7DTG%40%60H%60T0hQY&input=89&test_suite_input=0%0A2%0A10%0A12%0A34%0A89%0A111&debug=0)** or **[Check more test cases!](https://pyth.herokuapp.com/?code=eu%2BGf%21%7C%7DTG%40%60H%60T0hQY&test_suite=1&test_suite_input=0%0A2%0A10%0A12%0A34%0A89%0A111&debug=0)**
Note that this returns the entire sequence up to index **N**, but the link returns the last number only, by prepending an `e` (end). If you want to see the raw value returned by this program, [just remove it](https://pyth.herokuapp.com/?code=u%2BGf%21%7C%7DTG%40%60H%60T0hQY&input=12&test_suite_input=0%0A2%0A10%0A12%0A34%0A89%0A111&debug=0).
## How it works
```
u+Gf!|}TG@`H`T0hQY - Full program.
u ... hQY - Reduce hQ (the input incremented) from left to right, with the
function ...(G, H), with starting value Y (the empty list).
G is the current value and H is the iteration index.
f 0 - First integer starting from 0, that satisfies the following:
}TG - Appears in G...
| @`H`T - Or its (string) intersection with the current index (H) is
non-empty.
! - Logical NOT (boolean negation).
+G - Append the value obtained above to the current value (G).
This becomes the given value for the next iteration.
- Implicitly print all intermediate results, or add e to print
the last one.
```
[Answer]
## Haskell, ~~80~~ 69 bytes
```
f n=[x|x<-[0..],all(`notElem`show n)$show x,all(/=x)$f<$>[0..n-1]]!!0
```
[Try it online!](https://tio.run/##Hcq9CoAgFEDhV7mCQ0H/c7b1FCHooBRdr1JCDr27kdMZzrfr@zSIOVsgsaU3ze02dJ1sNGKlyMcVjVP37h@gmpem8nqRam5nvvyc2lFKxobs9EEgIFwHReDgdAALvxgnmT8 "Haskell – Try It Online")
Very slow for large `n`.
```
f n=
[x|x<-[0..] ] !!0 -- pick the first of all 'x' from [0..]
-- where
all(`notElem`show n)$show x -- no digit of 'n' appears in 'x', and
all(/=x) -- 'x' is not seen before, i.e. not in the list
f<$>[0..n-1] -- 'f' mapped to [0..n-1]
```
Edit: @Laikoni saved 10 bytes. Thanks!
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 39 bytes
```
0∘{0=⍵:1⋄(~⍺∊0∇¨⍳⍵)∧⊃∧/≠/⍕¨⍺⍵:⍺⋄⍵∇⍨⍺+1}
```
Uses `⎕IO←0`.
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/9NA5KOOGdUGto96t1oZPupu0ah71LvrUUcXULj90IpHvZuBEpqPOpY/6moGkvqPOhfoP@qdCpLZBdICorpbgCyg8ke9IFFtw9r//9PAWg0NAQ "APL (Dyalog Unicode) – Try It Online")
**How?**
Recursion.
`0=⍵:1` - take a guess.
`~⍺∊0∇¨⍳⍵` - left arg (accumulator) is not already in previous results
`∧⊃∧/≠/⍕¨⍺⍵` - and the string representation of the accumulator and `n` are different
`:⍺` - then return the accumulator.
`⍵∇⍨⍺+1` - otherwise, increment accumulator and recurse.
[Answer]
# [Python 3](https://docs.python.org/3/), 92 bytes
```
o=1,
for i in range(int(input())):
x=0
while{*str(x),x}&{*str(~i),*o}:x+=1
o+=x,
print(o)
```
[Try it online!](https://tio.run/##Jcy9CoUwDEDhPU@RSRrtYHET@jAO/gSkKbWXGxF99ao4HPimE/e8SOhKEe8sTJKQkQOmIcyj4ZCf4i8bIuoB1beA/4XX8ai3nIyS1bP6fDHZWs5eG@8ApfFqIab3IFSKa28 "Python 3 – Try It Online")
This prints all the terms up to the **N**th one. Thanks to [Dennis](https://codegolf.stackexchange.com/users/12012/dennis) for ~~-4~~ -5 bytes!
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), ~~218~~ ~~217~~ ~~213~~ ~~210~~ ~~202~~ ~~200~~ ~~172~~ ~~171~~ ~~170~~ ~~168~~ 167 bytes
I cannot believe that I didn't just return `k` all this time...
```
i->{int j=-1,k=0,y=1;for(String r=" ",e=r;j++<i;r+=~-k+e,y=1)for(k=0;y>0;k++)for(int f:(k+(y=0)+"").getBytes())y+=(e+j).indexOf(f)<0&!r.contains(e+k+e)?0:1;return~-k;}
```
[Try it online!](https://tio.run/##TU9NT4UwELy/X1E5mNZCA9dXiokHEw/GA0fjoUIh5aPFsrzYEPzrWAwHb7uzMzsznbzJxE7KdHW/63GyDlAXMLaAHlizmAq0NeyBX6blc9AVqgY5z@hVaoPWywwSAvZ80vIXA6pVLkbnUKBSfWlT69ZYQGLXSbFqExxEksW9SGMvMt5Yh0tw2rTIiQhFsRKOd5TmmjsqfpKeqoNHDl7QcF@kvKf0bz@eNVfcU@xFSmgUEdYqePKgZkyIpwIr2hEWIqjvtwY3JE/v7xyrrIHQYA7X8J08pteMOwWLM8GObzs/y579blbXaAyCM@f7hyRr6WdQI7MLsCmAgP9VZXKaBo@zlBC@bfsv "Java (OpenJDK 8) – Try It Online")
[Answer]
# [Go](https://golang.org/), ~~217~~ 205 bytes
```
package g;import("fmt";"strconv";"strings");var(
d=make(map[int]int)
a=strconv.Itoa)
func G(L int){k,i:=0,0;for;i<=L;i++{s:=a(i);k=0;for d[k]>0||strings.ContainsAny(a(k),s){k++;}
d[k]=1;}
fmt.Print(a(k));}
```
Alternate version (program instead of a package): [Try it online!](https://tio.run/##PY@9qsMwDEb3PEXJZJMQnDW6vhA6XejQPYQi0iYIYyvYvoXS9tld94cOggM6@iQtnNKKk8HltLFIDsiu7KMoZxtLKEP0E7vzm8gtIROHUsIZvSiO2qI5CYvrQC6OuWSB@jPT/EVGWcz/bnolC3k1NXVa1Qp29aH7en1kEhya3i9haEcJM3ugH70Dqqpr6DQKkmC0ejY2x8GMv@p2@9zTbNnFnB56dxEojKxD3lNVcC@epm4z5FeafbbjS5BwTym1SqkH "Go – Try It Online")
Improvements:
* removed space after outer `for` by using multiple assignment for `i,k`
* importing `"fmt";` + `fmt.Print` is shorter than `os.Stdout.WriteString` (holdover from `package main` when os.Args was needed)
[Answer]
# JavaScript (ES6), ~~103 88~~ 81
**Edit** Revised including *many* clever ideas by @Neil
```
n=>eval("for(r=[j=i=0];i<=n;)j=r[j]||(i+'').match(`[${j}]`)?j+1:!(r[k=j]=++i);k")
```
*Starting point*
Basic idea: a loop from 0 to n, and an inner loop checking values still not used
```
n=>{
var r=[]
for(i=0;i<=n;i++)
{
s=new Set(i+'')
for(j=-1;s;)
{
if (!r[++j] && ![...j+''].some(d=>s.has(d)))
{
r[j]=1
console.log(i,j)
s=0
}
}
}
return j
}
```
*Current version more readable*
```
n=>{
for(r = [j=i=0]; i <= n; )
if (r[j] || (i+'').match(`[${j}]`))
++j
else
r [k=j] = ++i,
j = 0;
return k
}
```
**Test**
```
var f=
n=>eval("for(r=[j=i=0];i<=n;)j=r[j]||(i+'').match(`[${j}]`)?j+1:!(r[k=j]=++i);k")
update=_=>{
var i=+I.value
if (i < 1e4 || confirm("Really?")) {
O.textContent=i + ' -> ...'
setTimeout(_=>O.textContent=i + ' -> ' + f(i), 100)
}
}
update()
```
```
<input id=I value=100 type=number max=1023456788>
<button onclick='update()'>Go</button>
(slow when input > 1000)
<pre id=O></pre>
```
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 114 bytes
```
N=input("");o=[1];for i=1:N;j=0;while(any(o==j)||nnz(ismember(int2str(i),int2str(j))));j++;end;o=[o,j];end;[0:N;o]
```
[Try it online!](https://tio.run/##NYwxDsIwDAC/gjolaoe0bFj@Qj9QZSjFCFvURm0Agfr3EJC45W46m9L4oJx7ZL3dk6sqD4ZDG@Fsy46xPfQgGOB54Su5UV/OEMVvm@rb8TrTfKTFsaZuTcW@@af4AkhdA@npu7RG4q@HUJ4Wc96HDw "Octave – Try It Online")
Thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen) and [Dlosc](https://codegolf.stackexchange.com/users/16766/dlosc) for the character comparison golfing.
## Ungolfed
```
N=input("");o=[1];
for i=1:N;
j=0;
while(any(o==j)||nnz(ismember(int2str(i),int2str(j))));
j++;
end;
o=[o,j];
end;
[0:N;o]
```
Basic explanation:
* Outer loop and inner loop, one for index `i`, and another for value to add `j`
* For each `i`, continue to increment `j` if either of the following are met:
1. Any `j` has been used before
2. This one gets fun. First, split each numeric value into a vector of digits (e.g., `10` becomes `[1 0]`) using `int2str`.
Then, compare the two numbers using `ismember`(e.g., `[1 0]` and `[2 1]` would return `[1 0]`) and then `nnz` to see if any columns matched.
* If none of the above are met, you have the next number! Append to `o`, the output matrix
* Print original indices with output matrix
[Answer]
# [Perl 5](https://www.perl.org/), 60 bytes
**59 bytes code + 1 for `-p`.**
```
$_="@{[0..($;=++$_)*9]}";$_=eval's/\b[^ $-]+ //;$-++;$&;'x$
```
[Try it online!](https://tio.run/##DY3dSsNAGAXv5ylKWawa0uz3s9ksS8D3qLVU6IUQbLAigvjqxtyeYebMl48pLaEdY13Cadw@/Rzifn8f6tg04fTwWI6/27qCy9d52t2659fDyya0x2bTdTW0TVPDXd19h2WJCIrhJHoyAwVZR0EUMcSRhPRIRgakoBFdHUUNdTShPZrRAS1YxARbk4Y5lrAey9iAFTzigiu@Pjqe8B7P@IAXUuTvOn@@Xd9vSztP/w "Perl 5 – Try It Online") (Includes `-l` for visual purposes and `$-=0;` to reset each iteration)
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 30 bytes
29 bytes of code, +1 for `-p` flag.
```
Fn,a+1{Y0WyNl|_NyMSn++ylPBy}l
```
[Try it online!](https://tio.run/##K8gs@P/fLU8nUduwOtIgvNIvpyber9I3OE9buzInwKmyNuf///@6Bf@NTQA "Pip – Try It Online")
Outputs the whole list. Warning: highly inefficient; the `2231` input case has been running for 35+ minutes on my laptop and still hasn't finished.
### Explanation
```
a is cmdline arg, l is [] (implicit)
Fn,a+1{ } For each n in range(a+1):
Y0 Yank 0 into y
W While...
yNl| y is in l, or...
_Ny lambda function: arg is in y
MSn mapped to digits of n and result list summed
(i.e., any digit of n is in y):
++y Increment y
lPBy Once we have a y that meets the criteria, push it to
the back of l
l Output l (formatted with -p flag)
```
[Answer]
# [Visual Basic .NET (.NET 4.5)](https://www.microsoft.com/net/core/platform), ~~260~~ 259 bytes
*-1 byte thanks to Kevin Cruijssen*
```
Function A(n)
Dim p=New System.Collections.Generic.List(Of Long),j="0",g=0
For i=0To n
j=0
While 1
If Not p.Contains(j)Then
g=1
For Each c In i.ToString
If j.Contains(c)Then g=0
Next
If g Then Exit While
End If
j+=1
End While
p.Add(j)
Next
A=p(n)
End Function
```
Loops through, generating previous terms in the sequence to then compare later. Then iterates the number as a string looking for matches.
Abuses VB.NET's typing system. For example, `j` is a string, but adding one converts to an integer for me. Integers are converted to Booleans where `0` is `False` and the rest are `True`.
[Try it online!](https://tio.run/##dZFPb4MwDMXv@RRWLyNaF8H@HDmgjk6VWiqtSDu3YKgRdRiErfv0LEk17dKe4jzn/Z6tfB0eCt3jtNHl2CJsIvFKJyDYD7DWXMMd9Pg5Uo8lVLoHlaU5LLbv6RxYmyu9Z/UyLUcuDGmGJGDpeV2c4TfsfgaDJ7XQbYv@waDekLGnQq1pMMG28ply3sSzcDav41AsLZfiMNfAorH3jyPZKSOxqiCz@Z2FsdkTD0EjIT8iizqOvCvdF0coYMVAKtc70xPXztb8WwrpHOByMjwb1609BNIzGfBZIuUSVpVo7i3X1Re1U0lZ2syLMYk7t6lr/@0@7cYDbGxMIIWwiYNuUX30ZHBNjEEShFJe1R9v6E839OgmyJH8THYUf17@ePoF "Visual Basic .NET (.NET Core) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 20 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
[Pyth](https://codegolf.stackexchange.com/a/147435/53748) beats Jelly. Go Mr. Xcoder!
```
Df⁹LD¤ȯeṆ
0ç1#ɓ;
1Ç¡
```
A full program taking input from STDIN and outputting in the list format option using Jelly's list representation\*. Uses the standard 0 based indexing.
\* single element lists have no surrounding `[]`, so `0` outputs `1`, while `1` outputs `[1, 0]` etc.
**[Try it online!](https://tio.run/##ASkA1v9qZWxsef//RGbigblMRMKkyK9l4bmGCjDDpzEjyZM7CjHDh8Kh//8xMg "Jelly – Try It Online")**
### How?
```
Df⁹LD¤ȯeṆ - Link 1, can append n to current? n, number; current, list
D - convert n to decimal list
¤ - nilad followed by link(s) as a nilad:
⁹ - chain's right argument, current
L - length
D - convert to a decimal list
f - filter discard from left if not in right
e - n exists in current?
ȯ - left logical OR right (empty lists are falsey)
Ṇ - logical NOT
0ç1#ɓ; - Link 2, append next number: current, List
# - n find (count up finding first n matches):
1 - ...finding: 1 match
0 - ...stating at: n=0
ç - ...doing: the last link as a dyad (left=n, right=current)
ɓ - new swapped-arg-dyadic chain (left = current, right = list of the found n)
; - concatenate
1Ç¡ - Main link: no arguments
1 - initialise the return value to 1
¡ - repeat input() times:
Ç - last link (2) as a monad
- implicit print
```
] |
[Question]
[
## Challenge
Here at PPCG, we sure do like our sequences, so here's ~~a fun~~ another one.
Let's define `a(n)` as being *the smallest non-negative integer `X` that is not equal to any `a(k)` (`0 < k < n`), and `a(n-1)` and `X` do not share any decimal digits. `a(0) = 0`*
Given an input `n > 0`, output such `a(n)`.
For example, for input `n = 13`, we have `a(13) = 20`, since `a(12) = 11` and `20` is the smallest non-negative integer we haven't seen yet that doesn't share any decimal digits with `11`.
## Sequence
Here are the first 20 terms to get you started. This is sequence [A067581](http://oeis.org/A067581) on OEIS.
```
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 22, 11, 20, 13, 24, 15, 23, 14, 25
```
## Rules
* The input and output can be assumed to fit in your language's native integer type.
* The input and output can be given [in any convenient format](http://meta.codegolf.stackexchange.com/q/2447/42963).
* You can choose to either 0-index, as I am here in my examples, or 1-index for your submission. Please state which you're doing.
* Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
* If possible, please include a link to an online testing environment so other people can try out your code!
* [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) are forbidden.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so all usual golfing rules apply, and the shortest code (in bytes) wins.
[Answer]
# [Python 2](https://docs.python.org/2/), 85 bytes
-1 byte thanks to Dead Possum
```
n=0,
exec"i=0\nwhile set(`i`)&set(`n[-1]`)or i in n:i+=1\nn+=i,;"*input()
print n[-1]
```
[Try it online!](https://tio.run/##HcrNCkBAGAXQvaf4spDxU4YdzZOgpjTllq6JEZ5@lN1ZHP@GdWcbI01TJe5xSwrTTLxXbE5OF3ILq7IfHGs9W7UfAgGFPUqjJ7I0qIa0AP0VcpX4Awzy5xh19wE "Python 2 – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 18 bytes
```
@A{!ZøA «As oX}a}g
```
[Test it online!](http://ethproductions.github.io/japt/?v=1.4.5&code=QEF7IVr4QSCrQXMgb1h9YX1n&input=MTM=) I've just added the `g` feature used here, but it's something I've been meaning to add for a long time (and this pushed me over the edge, because my non-`g` solution was around 35 bytes).
### Explanation
```
@ A{!ZøA « As oX}a}g
XYZ{A{!ZøA &&!As oX}a}gU
Implicit: U = input integer
{ }gU Starting with [0, 1], return the U'th item generated by
XYZ{ } this function: (X = previous item, Y = index, Z = full array)
A{ }a Return the smallest non-negative integer A where
!ZøA && Z does not contain A (A is not yet in the sequence), and
!As oX A.toString() does not contain any of the same chars as X.
Implicit: output result of last expression
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 20 bytes
```
eu+Gf!|/GT@`eG`T0Q]0
```
[Try it online!](http://pyth.herokuapp.com/?code=eu%2BGf%21%7C%2FGT%40%60eG%60T0Q%5D0&input=13&debug=0) or [Try the test suite.](https://pyth.herokuapp.com/?code=eu%2BGf%21%7C%2FGT%40%60eG%60T0Q%5D0&input=13&test_suite=1&test_suite_input=1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9%0A10%0A11%0A12%0A13%0A14%0A15%0A16%0A17&debug=0)
[Answer]
## Haskell, 79 bytes
```
f 0=0
f x=[i|i<-[1..],all((/=i).f)[1..x-1],all(`notElem`show(f$x-1))$show i]!!0
```
The code is horribly inefficient. To calculate bigger values, i.e. > 12, add `f x|x<11=x` between the two lines (implemented a `g` in the TIO link).
[Try it online!](https://tio.run/##fYwxDoMgAEV3TvFNHCSpFIZuMvYUhkSSCpICGjUpg3entW5t2u3/95I36OXee5@zAZecGCTZus01dSsYUyftfVWdpaPM0J2kWhywi@N69X3olmF8VKZ8CUrL/cCpouDZvnsWaUuNEDLt80fa/kvbrzQhQbsIidtIAEyziytKBD3BoOWMCaE@hT3EReUn "Haskell – Try It Online")
[Answer]
## JavaScript (ES6), 82 bytes
0-indexed.
```
f=(n,x=[1,p=0])=>n--?f(x[(g=k=>x[k]||(k+'').match(`[${p}]`)?g(k+1):p=k)(0)]=n,x):p
```
### Demo
```
f=(n,x=[1,p=0])=>n--?f(x[(g=k=>x[k]||(k+'').match(`[${p}]`)?g(k+1):p=k)(0)]=n,x):p
for(n = 0; n < 50; n++) {
console.log('a(' + n + ') = ' + f(n))
}
```
[Answer]
## [Husk](https://github.com/barbuz/Husk), 18 bytes
```
!¡₁;0
ḟȯ¬V€d→⁰d-⁰N
```
A 1-indexed solution.
[Try it online!](https://tio.run/##yygtzv6vkPuoqfHhjsVGBv8VDy0Esq0NuB7umH9i/aE1YY@a1qQ8apv0qHFDii6Q8Pv/HwA "Husk – Try It Online")
*Edit:* fixed bug for +1 byte.
## Explanation
Husk's built-in iteration function `¡` has many meanings.
Here, I'm using "construct infinite list by repeatedly appending new elements computed from the existing ones".
The second line is the helper function that computes a new element:
```
ḟȯ¬V€d→⁰d-⁰N Takes a list of existing elements, e.g. x = [0,1,...,10]
N The positive integers
-⁰ with elements of x removed: [11,12,13,...
ḟȯ Find an element n of this list that satisfies:
d Digits of n.
V Is any of them
€ an element of
d the digits of
→⁰ the last element of x?
¬ Negate.
Returns 22.
```
The first line is the main function:
```
!¡₁;0 Takes an integer k.
¡ Iterate adding new elements to the list
;0 [0]
₁ using the helper function,
! take k'th element of result.
```
[Answer]
## Haskell, 78 bytes
```
n!k|r:_<-[j|j<-[1..],all(/=j)k,all(`notElem`show n)$show j]=n:r!(r:k)
(0![]!!)
```
It would be even more efficient if the second argument to `!` would not be the list of seen numbers but of unseen numbers. But I can't do that without using more bytes.
[Try it online!](https://tio.run/##HYwxCoQwEAB7X7ELFgmo51kGU/oKCZpC0WSzShRs/HvutJmZahZ7@IkoJUZ/RzW0Ze9u9@e3qkxhicRHO@nfGnk7O5rCeCzbBSzz185oVhFFVF5msxY19gZRpmBXBg17XPmEHILdYYZn29Qm/QA "Haskell – Try It Online")
[Answer]
## Mathematica 115 Bytes
Still room to golf this down - and maybe use recursion (thus speeding it up).
```
(For[z={0};i=1,Length@z<#,
For[i=1,!FreeQ[z,i]||!DisjointQ@@IntegerDigits/@{l,i},i++];
z~AppendTo~i;l=Last@z;
];l)&
```
Original verbose code, with the same basic idea:
```
MakeSequenceA067581[n_]:=Module[{list={0}, innerCounter=1},
While[Length@list<n,
innerCounter=1;
(* inner loop *)While[Or[MemberQ[list,innerCounter],Intersection[IntegerDigits[Last@list],IntegerDigits[innerCounter]]!={}],innerCounter++];
AppendTo[list,innerCounter];
];
list
]
```
] |
[Question]
[
Yahtzee is a game played with five six-sided dice and a score sheet with thirteen different boxes to fill a score in. Each box has its own scoring rules:
* 1s, 2s, 3s, 4s, 5s, 6s all score points equal to the sum of the respective dice (that is, a roll of [3, 2, 3, 1, 5] scored as 3s would be awarded 6 points: 3 for each 3).
* 3-of-a-kind and 4-of-a-kind (as they sound, three or four dice rolled the same) score points equal to the sum of all five dice.
* Full house (two dice show one value, the other three show another) scores 25 points
* Small straight (four consecutive values) scores 30 points
* Large straight (all consecutive values) scores 40 points
* Yahtzee (all dice show the same value) scores 50 points
The thirteenth (chance) makes sense in-game, but not so much for this challenge; additionally the game has bonuses for extra Yahtzees which make no sense here. Because the challenge is...
Given five dice as input (five integers 1-6, input however is convenient, you can assume input is always valid), output the highest score possible for that 'hand'. For the purposes of this challenge, only the scoring methods in the list above are valid (specifically, chance is *not* a valid score box for this challenge). The score should be output as its decimal numeric value, whether that's an integer or a string representation thereof, whatever. It should be immediately recognizable as a number. Leading/trailing whitespace is fine, this is about getting the score and not presentation.
Code golf, so the answer with the fewest bytes in a given language wins. [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) forbidden.
## Test cases
(Note that these are all independent, the challenge is to score *one* 'hand' of dice):
```
in: 1 5 4 3 2
out: 40
in: 1 1 4 3 1
out: 10
in: 2 2 6 5 3
out: 6
in: 2 4 2 4 6
out: 8
in: 1 1 1 1 1
out: 50
in: 5 2 5 3 6
out: 10
in: 1 6 3 4 2
out: 30
in: 1 3 1 1 3
out: 25
in: 6 5 5 6 6
out: 28
in: 1 2 3 5 6
out: 6
```
[Answer]
# [R](https://www.r-project.org/), ~~146~~ 141 bytes
```
function(d)max(unique(d<-sort(d))*(g=table(d)),any(g>2)*sum(d),all(2:3%in%g)*25,(s=sum((R=diff(d))==1))<4&all(R<2)*30,(s>3)*40,(0==sd(d))*50)
```
[Try it online!](https://tio.run/##TY1bCoMwEEX/u4r@WGZkBM3Dj2JchDuwakTQSH1Au3o7sSISAjn3nplMm71n0WZXVy3d6KDGofzA6rr32kCdRfM4LRxiCK1ZylffeKDSfaHNBYbzOnBAZd@DeMqgc0GLodAEs/EVFKburPUzxiSImXp4tch4VMZs5RJDxY/YmLne/9ExbhYqSEiTIkkC8fbnZOfkYEGCUnbkyYr8TS/@fg7W3LJ96VMmddkvd1@eLDjR3t9@ "R – Try It Online")
*[Outgolfed by plannapus](https://codegolf.stackexchange.com/a/150547/67312)*
Takes input as a list, and returns the score.
ungolfed a bit:
```
function(d){
d <- sort(d)
u <- unique(d) # unique dice
g <- table(d) # table of counts
Ns <- u*g # scores as 1s, 2s, ... etc.
NKind <- any(g>2)*sum(d) # 3 or 4 of a kind if any counts are at least 3
FHouse <- all(2:3%in%g)*25 # full house is 25 if 2 & 3 are in counts
R <- diff(d) # consecutive differences
s <- sum(R==1) # sum of differences equal to 1
sStraight <- s<4 & # if the number of 1s is 3 and
all(R<2)*30 # no consecutive numbers are 2 apart
bStraight <- (s>3)*40 # all 1s means big straight
Yahtzee <- sd(d)==0 # sd = 0 means all are equal
max(Ns,NKind,FHouse,sStraight,bStraight,Yahtzee)
}
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~187~~ ~~184~~ ~~167~~ 165 bytes
-17 bytes thanks to [@mypetlion](https://codegolf.stackexchange.com/users/65255/mypetlion)
-2 bytes thanks to [@chrstphrchvz](https://codegolf.stackexchange.com/users/65047/chrstphrchvz)
```
def f(d):r=range(1,7);c=d.count;m=map(c,r);s=`m`[1::3];return max([i*c(i)for i in r]+[sum(d)*(max(m)>2),25*(set(m)>{2,3}),30*(4*'1'in s),40*(5*'1'in s),50*(5 in m)])
```
[Try it online!](https://tio.run/##RZDdasQgEIXv@xTerdqh1L8UEtIXCcKGmLReaIIxsEvps6ejBMow8J2ZMwdxe@bvNcrzdPNCFupYm/o0xq@ZCvhg3dS7t2k9Yu5CH8aNTpBYt/f3cB9E2yrbpTkfKZIwPujg@UQ9W9ZEPPGRJPs67EfATE7LPrBPyUAaTvc5F/UjQf0yUO@can4TN7zZGWiU5l@aIktcYJadJdwVNQgwoEGBtIAsKgtkCRIa3KnKGko3l6cWssEpOq55g6SvHFU9qjK@Dl2NbV8I2ZKPmTioX3T@AQ "Python 2 – Try It Online")
[Answer]
# R, ~~136~~ 134 bytes
```
function(n,y=table(factor(n,1:6)),z=sum(!diff(diff(sort(n)))))max(1:6*y,c(25,sum(n),10*3:5)[c(all(y<4&y-1),any(y>2),z>1,z>2,any(y>4))])
```
Golfed down 2 bytes thanks to [@Giuseppe](https://codegolf.stackexchange.com/users/67312)!
Indented,
```
function(n, #vector of die scores
y=table(factor(n,1:6)), #Contingency table
z=sum(!diff(diff(sort(n))))) #Diff of diff of ordered scores
max(1:6*y,
c(25,sum(n),10*3:5)*c(all(y<4&y-1), #Full house
any(y>2), #3 and 4 of a kind
z>1, #Small straight
z>2, #Long straight
any(y>4))] #Yahtzee
```
A few test cases:
```
> f=function(n,y=table(factor(n,1:6)),z=sum(!diff(diff(sort(n)))))max(1:6*y,c(25,sum(n),10*3:5)*c(all(y<4&y-1),any(y>2),z>1,z>2,any(y>4)))
> f(c(2,4,2,4,6))
[1] 8
> f(c(1,2,3,5,6))
[1] 6
> f(c(6,5,5,6,6))
[1] 28
> f(c(6,5,3,1,4))
[1] 30
> f(c(6,5,3,2,4))
[1] 40
```
[Answer]
## Batch, 359 bytes
```
@echo off
set/at=s=m=r1=r2=r3=r4=r5=r6=0
for %%r in (%*)do set/a"m+=!(m-r%%r),r%%r+=1,t+=%%r,p=s-r%%r*%%r,p&=p>>9,s-=p
goto %m%
:1
if %r1% neq %r6% set s=40&goto g
:2
set/at=r3*r4*(r2*(r1+r5)+r5*r6)
if %t% gtr 0 set s=30
goto g
:3
set/a"s=r1^r2^r3^r4^r5^r6"
if %s%==1 if %t% lss 25 set s=25&goto g
:4
set/as=t
goto g
:5
set s=50
:g
echo %s%
```
Explanation:
```
@echo off
set/at=s=m=r1=r2=r3=r4=r5=r6=0
for %%r in (%*)do set/a"m+=!(m-r%%r),r%%r+=1,t+=%%r,p=s-r%%r*%%r,p&=p>>9,s-=p
goto %m%
```
Calculate the number of dice for each number, plus the maximum, plus the total of all the dice, plus the highest total of dice of the same number.
```
:1
if %r1% neq %r6% set s=40&goto g
```
If all the dice are different, this might be a long straight, but that needs there to be either no `1` or no `6`.
```
:2
set/at=r3*r4*(r2*(r1+r5)+r5*r6)
if %t% gtr 0 set s=30
goto g
```
Otherwise, or if if at most two dice are the same, then this could still be a short straight. There must be at least a `3` and a `4` and also a combination of the other four numbers.
```
:3
set/a"s=r1^r2^r3^r4^r5^r6"
if %s%==1 set s=25&goto g
```
If there are three dice the same, check for a full house, since `3^2==1`. However, some full houses, such as 6s and 5s, score higher as 3-of-a-kind.
```
:4
set/as=t
goto g
```
Otherwise, or if there are four the same, then score the total.
```
:5
set s=50
```
And if there are five the same, then Yahtzee!
```
:g
echo %s%
```
Output the best score.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 58 bytes
```
ċЀ`Ṁ>2ȧS
ṢI=1Ạµ-ƤẸ,E;ṢI$E$;⁸Lƙ`Ṣ⁼2,3¤a3,5,4,2.Ṁ×⁵»Ç»Sƙ`Ṁ$
```
[Try it online!](https://tio.run/##y0rNyan8//9I9@EJj5rWJDzc2WBndGJ5MNfDnYs8bQ0f7lpwaKvusSUPd@3QcbUGiam4qlg/atzhc2wmUO2iR417jHSMDy1JNNYx1THRMdID6j88/VHj1kO7D7cf2h0MVtWg8v9wO9Dw//@jow11FEx1FEx0FIx1FIxidbgUQCKGMBFDsIgRUEpHwQys0hgmYgIWBJJmSLqgCCxiClZgCjYHrsYMzDVBsssYpssYJmIEFjQF6YoFAA "Jelly – Try It Online")
[Answer]
# [Perl 6](http://perl6.org/), 159 bytes
```
->\b{max map {$_(b)},|(1..6).map({*{$_}*$_}),{.kxxv.sum*?.values.grep(*>2)},{25*(6==[*]
.values)},30*?*{3&4&(1&2|2&5|5&6)},40*?*{2&3&4&5&(1|6)},50*(*.keys==1)}
```
[Try it online!](https://tio.run/##RY7bisMgFEV/5VCKqDhSry/F9ENmhpJA0oc2NCS0JJh8e@boJBRUcK29j3Z1//BrOwFpIKxfxU8V23KEtuwgHq@0YouYqZLSM4mMRo504biZiPI@jm85vFp@ke/y8aoHeevrjvJCYy1qx6kP4Zv/wqaRmhO/8GiIJVQRPWviZkc8CpuFJkk5lHOC7sQpl/d6GkJQbFnPMJQTHI5XCAXEBqryBviXAzTPHqgS4ARYAUaAZiIDtQOVgEYhwOec2YDNDE//qWwrAZe1yzP2hM83@3nF7JU89H@@y7m9onMoMXZe/wA "Perl 6 – Try It Online")
Since input may be accepted "however is convenient," my function takes it as an instance of the `Bag` class, which is a container with multiplicity. A `Bag` is also an associative container; `$bag{$key}` returns how many times `$key` occurs in the bag.
The bulk of the function is just a list of functions that evaluate each possible Yahtzee hand, returning the score for that hand or zero if the conditions for the hand are not met.
* `|(1..6).map({ *{$_} * $_ })` is a list of six functions that evaluate hands based on repeated runs of the numbers 1-6. The leading `|` flattens this list into the surrounding list.
* `{.kxxv.sum * ?.values.grep(* > 2) }` evaluates the 3- and 4-of-a-kind hands. `.kxxv` on a `Bag` returns the keys repeated with each's multiplicity, recovering the original list of die rolls, and `.sum` of course sums the dice. That sum is multiplied by a boolean value (`?`) which is true if the bag's `.values` (ie, the multiplicities) contain a value larger than 2.
* `{ 25 * (6 == [*] .values) }` evaluates the full house hand. 25 is multiplied by a boolean value which is true if the product of the multiplicities is 6, which for five dice can only happen if one is 3 and the other is 2.
* `30 * ?*{ 3 & 4 & (1 & 2 | 2 & 5 | 5 & 6) }` evaluates the small straight hand. It's a `WhateverCode` function; the second star `*` is the `Bag`. The expression between the braces is the junction of values 3 and 4, and either 1 and 2, or 2 and 5, or 5 and 6. Looking up this junction in the `Bag` results in a junction of the corresponding multiplicities. If the mulitplicities of 3 and 4, and at least one of 1 and 2, or 2 and 5, or 5 and 6, are nonzero, the junction is true when coerced to a boolean (with `?`), and this boolean is multiplied by 30 to get the score.
* `40 * ?*{ 2 & 3 & 4 & 5 & (1 | 6) }` similarly evaluates the large straight hand. It's simpler because the dice must include each of the numbers 2-5, and either 1 or 6.
* `50 * (*.keys == 1)` evaluates the Yahtzee hand. It's simply 50 times a boolean value which is true if the number of distinct dice is one.
[Answer]
# [Pip](https://github.com/dloscutoff/pip), ~~65~~ 63 bytes
```
n:_NgM\,6MXn*\,6AL[2<MXn23=JSNn3<Y#MX Jn^0MXn=5]*[$+g25--y*t50]
```
Takes the dice as five command-line arguments. [Try it online!](https://tio.run/##K8gs@P8/zyreL903RsfMNyJPC0g5@kQb2QDZRsa2XsF@ecY2kcq@EQpeeXEGQEFb01itaBXtdCNTXd1KrRJTg9j///@bAaEpEJoBAA "Pip – Try It Online")
### Ungolfed + explanation
(This is the original version.)
```
g is list of cmdline args; t is 10 (implicit)
Y Yank into y:
_Ng function that counts occurrences of its argument in g
M mapped to
\,6 inclusive range from 1 to 6
This gives us how many dice are showing each number 1-6
s: Assign to s:
# MX length of max of
Jy ^ 0 join y into string and split on zeros
This gives us the length of the longest straight
MX Max of
y * \,6 each die frequency in y, times its value
AL to which list append
[ this list:
3- and 4-of-a-kind:
MXy > 2 & $+g If max frequency is 3 or more, sum of g (else 0)
Full house:
23 = J SNy & 25 Sort y and join into string; if it's 000023, 25 (else 0)
Straights:
s > 3 & --s*t If s is 4 or more, (s-1)*10 (else 0)
Yahtzee:
MXy = 5 & 50 If max frequency is 5, 50 (else 0)
]
The result of the last expression is autoprinted
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 184 bytes
Full program. To make it easier to test input, add `$/=' '` on top to read in the "digit separated by spaces" format. (191 chars)
```
a=$<.map &:to_i
b=a.|c=[]
d=(1..6).map{|x|e=a.count x
c<<x*e
e}
e=a.sum
p !b[1]?50:b[4]&&!(a&[1,6])[1]?40:(1..3).any?{|x|(a&[*x..x+3])[3]}?30:(d-[0,2,3])[0]?d.max>2?e:c.max: [25,e].max
```
I set out the break the 200 bytes barrier and I managed to destroy it with a dozen bytes left, with ease!
[Try it online!](https://tio.run/##FY3LCoMwFET39ysiFFFrQzTqImjzISGUJGbRhQ9ahUj12613N5wzzHxWu52n6W4tHcxMYrFMrzfYztDddUpD3yUFpU2K9reH3V/GTeu4kACubUPmwR@A9LsOMJPIqkLLmgmrKh3HUWJiVeSNThFXTOAaT6kZN4lzqLNAabjzq8L1IfnV6R@K5WWOiGnZX9/hWUovHCZBVFnnXmM@zxpKqIFD8wc "Ruby – Try It Online")
## Explanation
Not a very good one though. Hope you have some Ruby knowledge~
```
a=$<.map &:to_i # a: input as [number]*5
b=a.|c=[] # c: [], b: a.uniq
d=(1..6).map{|x|
e=a.count x # e: occurrence count in a
c<<x*e # add (number * occurrence count) to c
e # return value in d
}
e=a.sum # e: sum of input
p !b[1] ? 50 : # condition to print 50 <= if a.uniq has length 0 (el 1 is nil)
b[4] && # condition to print 40 <= if a.uniq has length 5 (el 4 exists)
!(a&[1,6])[1] ? 40 : # <- arr & [mask] # and a does not have both 1 and 6
(1..3).any?{|x| # condition to print 30 <= if any of 1..4, 2..5, 3..6
(a&[*x..x+3])[3]} ? 30 : # [3] to assert entire mask is found in a
(d-[0,2,3])[0] ? # if, after removing 0 (not found) 2 (a pair) 3 (a triple)
# and something is found, this is not full house
d.max > 2 ? # is triple / quadruple ?
e : # weakly dominating alternatives
c.max # choose best by-suit
: [25,e].max # choose best by-score
```
] |
[Question]
[
The Microsoft FAT file system has a directory table to represent which "files" are in which "folders" on the disk. For the time, these entries crammed a lot of information into a small amount of bits. There are a bunch of technical specifications over on [Wiki](https://en.wikipedia.org/wiki/Design_of_the_FAT_file_system#Directory_table) for the curious, but the challenge here is going to focus on a "simple" decoding of an entry.
Each entry consists of a 32-byte binary word, broken up into several sections. For consistency in this challenge, we'll be using the MS-DOS 5.0 version, the bytes are ordered as **big endian**, and we're calling byte `0x00` as the left-most, and byte `0x1F` as the right-most.
Below is a brief schematic of the relevant sections, and what should be the output for each section (in **bold**).
* The first 11 bytes are the file name in ASCII format (this is where the famous 8.3 filename comes from -- 8 bytes for the file name, 3 bytes for the extension). These are straight ASCII encoding, and should be **output as ASCII with a period (.) between**.
+ Note: both the 8 and the 3 parts are padded with spaces to make a full-length entry. The output should **ignore spaces** (i.e., don't output them).
+ The file extension may be empty (i.e., all spaces), in which case the output should **not output the dot**.
+ Since ASCII only uses the lower 7 bits, the bytes will all have a leading `0`.
* The next byte (0x0b) is a bitmask of the following:
+ 0x01 Read Only - output **RO**
+ 0x02 Hidden - output **H**
+ 0x04 System - output **S**
+ 0x08 Volume Label - output **VL**. File size (below) should be output as **0**, regardless of its actual entry.
+ 0x10 Subdirectory - output **SD**. File size (below) should be output as **0**, regardless of its actual entry.
+ 0x20 Archive - output **A**
+ 0x40 Device - ignored for this challenge.
+ 0x80 Reserved - ignored for this challenge.
+ Since this is a bitmask, multiple flags are possible - all applicable outputs should be concatenated together in any order. For example, `0xff` could be `ROHSVLSDA` (or any other combination).
* The next two bytes (0x0c and 0x0d) are not used under MS-DOS 5.0.
* The next two bytes (0x0e and 0x0f) are the creation time as follows:
+ Bits 15 to 11 are the hours in 24-hour format - output **00** to **23**
+ Bits 10 to 5 are the minutes - output **00** to **59**
+ Bits 4 to 0 are the seconds/2 - output **00** to **58** (note that seconds are only in two-second resolution)
+ For clarification: `hhhhhmmmmmmsssss` when written big-endian.
* The next two bytes (0x10 and 0x11) are the creation date as follows:
+ Bits 15 to 9 are the year - output **1980** for `0` up to **2107** for `127`
+ Bits 8 to 5 are the months - output **1** to **12** (with or without leading zero)
+ Bits 4 to 0 are the day - output **0** to **31** (with or without leading zero)
+ For clarification: `yyyyyyymmmmddddd` when written big-endian.
* The next two bytes (0x12 and 0x13) are the last access date. While used in MS-DOS 5.0, we're ignoring this portion for this challenge.
* The next two bytes (0x14 and 0x15) are not used by MS-DOS 5.0.
* The next two bytes (0x16 and 0x17) are the last modified time, following the same format as the creation time, above.
* The next two bytes (0x18 and 0x19) are the last modified date, following the same format as the creation date, above.
* The next two bytes (0x1a and 0x1b) are the cluster location of the file on disk. We're ignoring this portion for this challenge.
* The final four bytes (0x1c, 0x1d, 0x1e, and 0x1f) are the file size - output as an **unsigned integer**, unless the **VL** or **SD** flags are set (above), in which case output `0`.
**Visual representation**
```
0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
\______________________________FILENAME________________________________________________/\_ATTR_/\___NOTUSED____/\_CREATIONTIME_/\_CREATIONDATE_/\__LASTACCESS__/\___NOTUSED____/\_MODIFIEDTIME_/\_MODIFIEDDATE_/\___NOTUSED____/\___________FILESIZE___________/
```
## Input
* A single 32-byte word (i.e., 256 bits), in whatever format is convenient.
+ This could be as a string of `1` and `0`, as several unsigned `int`s, an array of Boolean values, etc.
+ Please specify in your answer what format you're using for input.
+ You *cannot* take multiple input (i.e., an array pre-broken into the relevant byte sizes) unless that is the *only* way for your language to take input. Parsing the input is part of the challenge.
* You can assume input to be valid (for example, you don't need to perform date checking to verify that the date is valid).
* Bytes that are unused can be all `0`, all `1`, etc., just so long as they are present. In the below examples, I used all `0` for the unused bytes.
## Output
Either printed to screen or returned, the following:
* The filename as an ASCII string
* The file attributes as an ASCII string
* The creation time and creation date, with appropriate separators (colons, slashes, something to distinguish the components)
* The modified time and modified date, again with appropriate separators
* The file size
The output can be a space-separated or newline-separated single string, separate elements in an array, etc. Please specify in your answer how your output is formatted.
## Rules
* [Standard I/O formats](http://meta.codegolf.stackexchange.com/q/2447/42963) are acceptable.
* Either a full program or a function are acceptable.
* [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) are forbidden.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so all usual golfing rules apply, and the shortest code wins.
* Built-ins that perform exactly this function are forbidden.
### Examples
```
0111000001110010011011110110011101110010011000010110110101101101011010010110111001100111000001100000000000000000101000100100010001001000110101000000000000000000000000000000000010100010010001000100100011010100000000000000000000000000000000001101000000000000
programm.ing HS 20:18:08 2016/06/20 20:18:08 2016/06/20 53248
0010000000100000001000000010000001110000011100000110001101100111001000000010000000100000000101000000000000000000010111010110110000111101100111110000000000000000000000000000000010100010010001000100100011010100000000000000000011110000000100111111001011100001
ppcg SDS 11:43:24 2010/12/31 20:18:08 2016/06/20 0
```
[Answer]
# Verilog, ~~513~~ ~~670~~ 617 bytes
Runs using IVerilog. No special compile flags needed.
This is a monster of nested definitions, bit-twiddling, and the annoyance of having to flip bit order due to the endianness (otherwise either the string doesn't print, or the number bit order is wrong). The input is taken through the `i` port, which is the usual way of taking input into a Verilog module. `$display` is used to print to standard out. 6 bytes could be saved if leading zeros were not required for the timestamp.
```
`define r(o,b)wire[3:0]o;assign o={i[b],i[b+1],i[b+2],i[b+3]};
`define R(t,a,b,c,d,s)`r(a,s)`r(b,s+4)`r(c,s+8)`r(d,s+12)wire[15:0]t;assign t={a,b,c,d};
`define p(m,k)i[90+m]?"k":"",
`define F(a,b)"a a a b\t b%d"
module f(input[0:255]i);`R(d,q,w,e,r,112)`R(D,Q,W,E,R,128)`R(s,z,x,c,v,224)`R(S,Z,X,C,V,240)`R(p,t,y,u,o,176)`R (A,b,n,m,l,192)always@(i)$display(`F(%s%s%s,%02d:%02d:%02d%d/%d/%d),i[0:63],i[64:87]==" "?" ":".",i[64:87],`p(5,RO)`p(4,H)`p(3,S)`p(2,VL)`p(1,SD)`p(0,A)d[15:11],d[10:5],d[4:0]*2,D[15:9]+1980,D[8:5],D[4:0],p[15:11],p[10:5],p[4:0]*2,A[15:9]+1980,A[8:5],A[4:0],|i[91:92]?0:{s,S});endmodule
```
[**Demo**](http://www.edaplayground.com/x/gBh)
Testbench (Not scored):
```
`timescale 1ns / 1ps
module ftest;
reg [0:255] i;
f uut (
.i(i)
);
initial begin
i=256'b0111000001110010011011110110011101110010011000010110110101101101011010010110111001100111000001100000000000000000101000100100010001001000110101000000000000000000000000000000000010100010010001000100100011010100000000000000000000000000000000001101000000000000;
#100;
i=256'b0010000000100000001000000010000001110000011100000110001101100111001000000010000000100000000101000000000000000000010111010110110000111101100111110000000000000000000000000000000010100010010001000100100011010100000000000000000011110000000100111111001011100001;
end
endmodule
```
Example run:
```
$ iverilog design.sv testbench.sv && vvp a.out
programm.ing HS 20:18:08 2016/ 6/20 53248
ppcg S SD 11:43:24 2010/12/31 0
```
[Answer]
# Python, ~~485, 479, 442, 438, 431, 429, 418, 402, 395, 391~~, 370 bytes.
Saved 19 bytes thank to Cᴏɴᴏʀ O'Bʀɪᴇɴ reminding me that I can assign functions to a letter.
Saved 6 bytes thanks to FryAmTheEggman's suggestion to clean up the bitmask filter.
Saved 21 bytes thanks to W0lf's awesome Ruby answer forcing me to golf this down some more. ;)
This is an absolute monster. Pretty sure I can cut it down a bit more, but it's getting pretty close to being golfed out.
```
a=input()
j=''.join
n=lambda v:int(v,2)
f=j('RO H S VL SD A'.split()[i]for i in range(6)if n(a[88:96])&2**i)
print(j(chr(n(a[x:x+8])).strip()+'.'*(x==56)for x in range(0,88,8)).strip('.'),f,j('%02d:%02d:%02d'%(n(a[b-11:b-6]),n(a[b-6:b]),n(a[b:b+6]))+' %d/%d/%d '%(n(a[b+6:b+12])+1980,n(a[b+12:b+16]),n(a[b+16:b+21]))for b in[123,187]),n(a[208:])*(1-('V'in f or'D'in f)))
```
[Answer]
# Haskell, ~~781~~ 710 bytes
Thanks to BlackCap for some simplification
```
w n=('0'<$[1..2-length a])++a where a=show n
x s=tail.foldr(\a b->s:a++b)""
t=snd.span(==' ')
y a|all(==' ')a=""|0<1='.':t a
nm=(\(a,b)->t a++y b).splitAt 8
ms n(r,s)|n`mod`2^(r+1)`div`2^r>0=s|0<1=""
tm n=x ':'[w$n`div`2^11,w$n`mod`2^11`div`32,w$2*n`mod`64]
dt n=x '/'[w$1980+n`div`2^9,w$n`mod`2^9`div`32,w$n`mod`32]
pa s=x ' '[nm.map(toEnum.v.take 8).takeWhile(not.null)$iterate(drop 8)a,t,dt$v i,tm$v g,dt$v o,tm$v m,show u,"\n"]where{z n=splitAt(8*n);(a,b)=z 11 s;(c,d)=z 1 b;(e,f)=z 2 d;(g,h)=z 2 f;(i,j)=z 2 h;(k,l)=z 4 j;(m,n)=z 2 l;(o,p)=z 2 n;(q,r)=z 2 p;t=(zip [0..](words"RO H S VL SD A")>>=).ms$v c;u|any(`elem`t)"LD"=0|0<1=v r;v=foldl((+).(2*))0.map(read.pure).filter(`elem`"01")}
main=interact pa
```
This additionally allows garbage (like a newline character) to appear after the input.
[Answer]
# Java, ~~1721~~ ~~1587~~ ~~1573~~ ~~1560~~ 1511 bytes:
```
import java.util.*;class A{int Q(String a,int b){return Integer.parseInt(a,b);}String P(int a){return Integer.toString(a);}ArrayList<String>B=new ArrayList<String>();void J(String O){B.add(O);}String TD(String l,String p,int a,int c,int d){String X,Y,Z;X=Y=Z=new String();int i=0;for(char F:l.toCharArray()){if(i<a){X+=F;}if(a<=i&i<c){Y+=F;}if(c<=i){Z+=F;}i++;}String[]H=new String[3];H[0]=P(d+Q(X,2));H[1]=P(Q(Y,2));H[2]=(p==":")?P(Q(Z,2)*2):P(Q(Z,2));int T=0;for(String A:H){H[T]=(A.length()<2)?"0"+A:A;T++;}return H[0]+p+H[1]+p+H[2];}String D(String i){String K=new String();int L=0;for(char Y:i.toCharArray()){if(L%8<1){K+=" ";}K+=Y;L++;}String[]C=K.split(" ");String[]z={"RO","H","S","VL","SD","A"};int[]l={1,2,4,8,16,32};Map<Integer,String>U=new HashMap<Integer,String>();for (int e=0;e<l.length;e++){U.put(l[e],z[e]);}String[]N={":","/",":","/"};int[]M={15,17,23,25};int[]O={5,7,5,7};int[]P={0,1980,0,1980};for(int y=1;y<9;y++){if((char)Q(C[y],2)!=' '){J(Character.toString((char)Q(C[y],2)));}}for(int v=9;v<12;v++){if((char)Q(C[v],2)!=' '){if(!B.contains(".")){J(".");}J(Character.toString((char)Q(C[v],2)));}}J(" ");int T=(char)Q(C[12],2);while(T>0){int H=l[0];for(int V:l){if(V<=T){H=V;}}J(U.get(H));T-=H;}for(int w=0;w<4;w++){J(" ");J(TD(C[M[w]]+C[M[w]+1],N[w],O[w],11,P[w]));}J(" ");if(B.contains("SD")||B.contains("VL")){J("0");}else{J(P(Q(C[29]+C[30]+C[31]+C[32],2)));}return String.join("",B);}public static void main(String[]a){A H=new A();System.out.print(H.D(new Scanner(System.in).next()));}}
```
Takes input in the format of 32 byte binary string. Outputs in the format of a space separated string. This may be a very *very* long answer, but I'm still not disappointed. I'm just happy I was able to implement this in Java. I will still try to golf this as much as I can, though.
[Try It Online! (Ideone)](http://ideone.com/u5mo3Y)
[Answer]
# Ruby, 344 bytes
```
m=gets
s=->b,l{b.slice!(0,l).to_i 2}
t=->b{'%02d:%02d:%02d %d/%d/%d'%[s[b,5],s[b,6],2*s[b,5],s[b,7]+1980,s[b,4],s[b,5],]}
i=(0..q=32).map{|i|m[i*8,8].to_i 2}
c=i.map(&:chr).join
n=c[0,8].strip
e=c[8,3].strip
e>?!&&n<<?.+e
f=''
6.times{|j|i[11][j]>0&&f<<%w(RO H S VL SD A)[j]}
$><<[n,f,t[m[112,q]],t[m[176,q]],(f[/VL|SD/]?0:m[-q,q].to_i(2))]*' '
```
The slightly more readable version is available [here](https://github.com/wolfascu/codegolf/blob/master/83371-decode-a-microsoft-ms-dos-5-0-fat-directory-entry/msdos_fat5.rb).
Online test: <http://ideone.com/Fww1Rw>
[Answer]
# JavaScript (ES6), 369
```
(b,Z=n=>n>9?n:'0'+n,W=n=>s[n]<<8|s[n+1],U=n=>[Z((t=W(n))>>11)+`:${Z(t>>5&63)}:`+Z(t%32*2),((t=W(n+2))>>9)+1980+`/${t>>5&15}/`+t%32],X=l=>String.fromCharCode(...s.slice(p,p+=l)).trim(),s=b.match(/.{8}/g).map(x=>+('0b'+x)),p=0)=>[X(8)+((x=X(3))?'.'+x:x),[...b].map((b,i)=>'A,SD,VL,S,H,RO'.split`,`[z=(2*z|b)%4294967296,i*b-90]||'',z=0).join``,U(14),U(22),b[92]|b[91]?0:z]
```
*Less golfed*
```
(b,
Z=n=>n>9?n:'0'+n, // zero pad
W=n=>s[n]<<8|s[n+1], // get word
U=n=>[
Z((t=W(n))>>11)+`:${Z((t>>5&63)}:`+Z(t%32*2), // decode time
((t=W(n+2))>>9)+1980+`/${t>>5&15}/`+t%32 // decode date
],
X=l=>String.fromCharCode(...s.slice(p,p+=l)).trim(), // extract space padded string
s=b.match(/.{8}/g).map(x=>+('0b'+x)), // convert bits to bytes
p=0
)=>
[ X(8)+((x=X(3))?'.'+x:x),
[...b].map((b,i)=>'A,SD,VL,S,H,RO'.split`,`[i*b-90]||'').join``,
[...b].slice(-32).map((b,i)=>z=2*z|b,z=0), // this line merged with the preceding one in the golfed code
U(14),U(22),
b[92]|b[91]?0:z
]
```
**Test**
```
f=(b,Z=n=>n>9?n:'0'+n,W=n=>s[n]<<8|s[n+1],U=n=>[Z((t=W(n))>>11)+`:${Z(t>>5&63)}:`+Z(t%32*2),((t=W(n+2))>>9)+1980+`/${t>>5&15}/`+t%32],X=l=>String.fromCharCode(...s.slice(p,p+=l)).trim(),s=b.match(/.{8}/g).map(x=>+('0b'+x)),p=0)=>[X(8)+((x=X(3))?'.'+x:x),[...b].map((b,i)=>'A,SD,VL,S,H,RO'.split`,`[z=(2*z|b)%4294967296,i*b-90]||'',z=0).join``,U(14),U(22),b[92]|b[91]?0:z]
O.textContent+='\n'+f('0111000001110010011011110110011101110010011000010110110101101101011010010110111001100111000001100000000000000000101000100100010001001000110101000000000000000000000000000000000010100010010001000100100011010100000000000000000000000000000000001101000000000000')
O.textContent+='\n'+f('0010000000100000001000000010000001110000011100000110001101100111001000000010000000100000000101000000000000000000010111010110110000111101100111110000000000000000000000000000000010100010010001000100100011010100000000000000000011110000000100111111001011100001')
```
```
<pre id=O></pre>
```
[Answer]
# [PHP](https://php.net/), ~~301~~ 288 bytes
```
for($b=unpack('A8f/A3e/Cl/n/Nc/N/Nm/n/Ns',$argn);$i<8;$f.=1<<$i++&$b[l]?[RO,H,S,VL,SD,A][$i-1]:'');echo trim($b[f].'.'.$b[e],' .')," $f ",($e=function($a){echo date('H:i:s Y/m/d ',mktime($a>>27&31,$a>>21&63,$a>>15&62,$a>>5&15,$a&31,1980+($a>>9&127)));})($b[c]),$e($b[m]),$b[l]&24?0:$b[s];
```
[Try it online!](https://tio.run/##ZZBrb9owFIa/51ccVVYSC0NIKJQSKEopW8oqysou6qKoysUhXslFcWhVVf3t7CSrtE2zvzzHPu/x@7pMy@N0XqalohgGDKxu@FJzCEUeVC/wXFSxBFkXFY8hkBAGko9OISkqqEWhkJrLWsIMPOX96iHmURFzXYvc1dOPwSoNv5tlmEUfHWch7pY/vzrN@rRabtefW@w7zkyj7D/99cLZXbuXz/dWtENG3WUcXlnJP/qN82V8WLZ631bQFQ@iVId3W@iXBNUuBwqvABhOiuywDzAdpoXuh98xmtYjkk7C2SEvg@hR15xxYjgDbiz2Rm6sI2NtrLOGpMbaidQmYjq2SdKbmdMpEZ2OSkJv78@9u1vmsi37dsO2V8zxPSK6pj/RNGrzKC2grkSGD3mJ39NwI3GfadDDBCdAEjhhOuGz5JBH@L25TgL62upidK1r7kRMJNwbmRGDxrLHWmQcey4urDN1YLKWTHU0aMkcqiOrpaFqDhGaFvN83O@0knPVtM4opfYbbQxFPmWEN5Q11IRRrdN5f4IoffsI0PrYuJuH5e2NrbT/WXHJa@D5k6iKPON5jceHHM9wDrX/FOLvIsHi7fgL "PHP – Try It Online")
Input is a 32 byte word string via `STDIN`, output to `STDOUT`.
**-13 bytes** as a standalone program.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 111 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
¼ΘUßU'ïMo^ø¬├▓> I¬i⌠·╥.↕¥½ßqS,=frT`d_`&&↓⌠ÉûÆiü=┌-< │∟Φ☼⌐¢3²Bu╜lJ╛§≥╪║ε┐╓ù♫╨Z░╖!¥É:╬Çß═╤às8Q←φ,ºï◘≥Ä£}èΦ╡FÉçø¶É
```
[Run and debug it](https://staxlang.xyz/#p=ace955e155278b4d6f5e00aac3b23e2049aa69f4fad22e129dabe171532c3d66725460645f60262619f490969269813dda2d3c20b31ce80fa99b33fd4275bd6c4abe15f2d8baeebfd6970ed05ab0b7219d903ace80e1cdd1857338511bed2ca78b08f28e9c7d8ae8b5469087001490&i=0111000001110010011011110110011101110010011000010110110101101101011010010110111001100111000001100000000000000000101000100100010001001000110101000000000000000000000000000000000010100010010001000100100011010100000000000000000000000000000000001101000000000000%0A0010000000100000001000000010000001110000011100000110001101100111001000000010000000100000000101000000000000000000010111010110110000111101100111110000000000000000000000000000000010100010010001000100100011010100000000000000000011110000000100111111001011100001&a=1&m=2)
[Answer]
# Perl, 249 bytes
Takes 32 bytes as input, output is separated by newlines. `unpack` is perfect for this kind of binary structure parsing.
```
($f,$e,$a,$C,$M,$s)=unpack"A8A3CxxNx4Nx2N",<>;$f=~s/ //g;$e=~s/ //g;printf"%s
@{[map+(RO,H,S,VL,SD,A)[$a&1<<$_?$_:9],0..5]}
"."%02d:%02d:%02d %d/%d/%d
"x2 .$s*!($a&24),$f.".$e"x!!$e,map{$_>>27,$_>>21&63,$_>>15&62,$_/512%128+1980,$_>>5&15,$_&31}$C,$M
```
Some highlights:
* The aforementioned `unpack`.
* The turtle operator `@{[]}` allows to interpolate code in a string. It actually creates an array reference that is then dereferenced.
* `"$str1"x!!$str2` is a nice way to return `$str1` only if `$str2` is a non-empty string.
Below is a version that works on real directory entries, with little-endian fields, and only ignoring right padding on the filename and extension (so, e.g. `" ppcg"` doesn't have its initial whitespace removed) *(254 bytes)*
```
($f,$e,$a,$C,$M,$s)=unpack"A8A3CxxVx4Vx2V",<>;$f=~s/ +$//;$e=~s/ +$//;printf"%s
@{[map+(RO,H,S,VL,SD,A)[$a&1<<$_?$_:9],0..5]}
"."%02d:%02d:%02d %d/%d/%d
"x2 .$s*!($a&24),$f.".$e"x!!$e,map{$_>>11&31,$_>>5&63,2*$_&63,($_>>25)+1980,$_>>21&15,$_>>16&31}$C,$M
```
] |
[Question]
[
Given an ASCII art hexagon as input, output one whose sides are all one unit longer.
```
_____
____ / \
/ \ / \
/ \ / \
\ \ => \ \
\ / \ /
\____/ \ /
\_____/
```
The input hexagons will have 180 degree symmetry, but otherwise the sides can be all different lengths. Above, the side lengths (2, 4, 3) get enlarged to (3, 5, 4). The side lengths will be nonzero.
The hexagons are made of underscores `_`, slashes `/`, and backslashes `\`. Note that of the horizontal edges (made with underscores), the top edge is on its own line but the bottom edge is not.
**I/O**
I'm going to be a stickler and require [ascii-art](/questions/tagged/ascii-art "show questions tagged 'ascii-art'") formatting here: the input and output should be a string with newlines representing the image, not a list of lines. Of course, your code may print each line in turn to produce the image, or read STDIN a line a time for input if your language can do that.
**Details**
The input may include an optional trailing newline if you wish, but will otherwise have no empty lines. You can choose to either have no trailing spaces in the input, or spaces to pad each line to the same length (that of the longest line).
The output should be flush with the left edge of the screen, like the input. You may have extra newlines above and below as well as trailing spaces.
**Test cases**
Input followed by output.
```
_
/ \
\_/
__
/ \
/ \
\ /
\__/
```
---
```
____
/ \
/ \
\ \
\ /
\____/
_____
/ \
/ \
/ \
\ \
\ /
\ /
\_____/
```
---
```
_
/ \
/ /
/ /
/ /
/ /
\_/
__
/ \
/ \
/ /
/ /
/ /
/ /
\ /
\__/
```
**Leaderboard**
```
<iframe src="https://xmikee1.github.io/ppcg-leaderboard/?id=185760" width="100%" height="100%" style="border: none;">Oops, your browser is too old to view this content! Please upgrade to a newer version of your browser that supports HTML5.</iframe><style>html,body{margin:0;padding:0;height:100%;overflow:hidden}</style>
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 28 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
╙Σ■♀♪«G[▀[TÖe╟╗ê'○▀ÄT→│╧(╡¢╩
```
[Run and debug it](https://staxlang.xyz/#p=d3e4fe0c0dae475bdf5b549965c7bb882709df8e541ab3cf28b59bca&i=+_%0A%2F+%5C%0A%5C_%2F%0A%0A++____%0A+%2F++++%5C%0A%2F++++++%5C%0A%5C+++++++%5C%0A+%5C++++++%2F%0A++%5C____%2F%0A%0A+++++_%0A++++%2F+%5C%0A+++%2F++%2F%0A++%2F++%2F%0A+%2F++%2F%0A%2F++%2F%0A%5C_%2F&a=1&m=1)
Seems like there should be a way to do it mostly with regex, but I'm still looking...
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 84 bytes
```
m`(¶.*)( .)$
$1 $2
(_+¶)(( */) ( *.))
_$1 $3$4¶$2
( *.)(_+/)$
$1$.2$* /¶ $1_$2
```
[Try it online!](https://tio.run/##TYsxDsMwDAN3vYIDB8kFLMTtcww4HTp0aIeib/MD/DFXSYCgXERSvM/j@3zf53ytOnpOpshG4QKARbRdRjdVJDcgTjYTtHjzytvo22QrY@c7xlyYgvXRwaWxzBmpHZLocajKaeHyZ@vpUHfIfw "Retina 0.8.2 – Try It Online") Works with irregular hexagons. I/O is unpadded. Explanation:
```
m`(¶.*)( .)$
$1 $2
```
Widen the interior of the hexagon.
```
(_+¶)(( */) ( *.))
_$1 $3$4¶$2
```
Fix up the top.
```
( *.)(_+/)$
$1$.2$* /¶ $1_$2
```
Fix up the bottom.
[Answer]
# JavaScript (ES6), ~~159 156 153~~ 150 bytes
```
s=>s[r='replace'](/\S /g,'$& ')[r](/.*/,s=>s[r](e=/_+/,` $&_
`+s[r](e,'/$& \\')[r](e=/_/g,' ')))[r](/ *\\_+/,s=>s[r](e,' ')+` /
`+s[r](/_/,'__'))
```
[Try it online!](https://tio.run/##bY8xb4MwFIR3/4onFMUQu7y9kbN1yJShI0YGUZO2QoAw6VL1t9NnaEnc1BN399098V5@lK4a3vrxoe1e7FSryamDywbFB9s3ZWV5HqN@BjxLvtkCAE@ygax0h3Ih89gqNAJlAZutYYVYPMmReK0X3iN@gurJMgA7rX1rHZlDUdAJZPCzQiXJjaHStM8YQARGtxEI/4k0vgrawkiyGQFDb00AafEWnTWEZbjz4NfEq0Wen74eondzyMPBhNdBP5SBCsT8Nyxnad0NT2X1GjtQB/ikqOpa1zU2bbpzzI9tfxkfebL/E7g7h@v2dBn/p2viQQAhPvtKpm8 "JavaScript (Node.js) – Try It Online")
### Commented
```
s => // s = input
s[r = 'replace']( // r = alias for 'replace'
// STEP #1
/\S /g, // insert two middle spaces for all lines
'$& ' // that contain a border, followed by a space
) // (i.e. all lines except the first and the last one)
[r]( // STEP #2
/.*/, // isolate the first line
s => // let s be this first line
s[r]( //
e = /_+/, // find the sequence of underscores and replace it with:
` $&_\n` + // the same sequence preceded by a space and followed by '_'
s[r]( // followed by a linefeed and:
e, // the same sequence preceded by '/' and followed by ' \'
'/$& \\' //
) // with:
[r](e = /_/g, ' ') // all underscores replaced with spaces
)) //
[r]( // STEP #3
/ *\\_+/, // isolate the last line, without the trailing '/'
s => // let s be this last line
s[r](e, ' ') + // replace all underscores with spaces
` /\n ` + // append 3 spaces and a trailing '/', followed by a linefeed
s[r](/_/, '__') // append s with an extra underscore
) //
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 48 bytes
```
SθW¬№ω_≔⁺ωSω≔⊕⊘№ω\η≔⊕⊘№ω/ζ≔×_⊕№ω_θ↗ζθ↓↘η←↙ζ↑←θ↖η
```
[Try it online!](https://tio.run/##jY89a8MwEIZ3/4oj0wlctKdTaIYakhDaZDME46qWQJFcW7Yhf17RVW4Vd@ot9/Xcq1e1rLraVtr7wrSDe3edMg1@sedskkoLwIN1@GIH43DKYXVZMcZg0/eqMXjUQ0/Tx0vGcpjC9YwUpu7EVRgnPvC10mNISawsSS0H@U@eR/yW8JO6ih6DKzKRLv/4zYH@cwz@HK7P7ZtqpIsycUbbvR0Frrd2MgmlboblL7ITn26J0CTKReLcpn3cLZ6PoyDoPcAlRAYcQpTZd6KihJ8K5pJnoSOY@6dR3wE "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
SθW¬№ω_≔⁺ωSω
```
Input and concatenate all of the lines except the first. (Input in JSON format would make most of this unnecessary at a saving of 11 bytes.)
```
≔⊕⊘№ω\η≔⊕⊘№ω/ζ≔×_⊕№ω_θ
```
Count the number of `/`s, `/`s, and `_`s in the string and use that to calculate the new side lengths (in the case of `_`s, as a string of `_`s of that length).
```
↗ζθ↓↘η←↙ζ↑←θ↖η
```
Draw the enlarged hexagon.
Alternative solution, also 48 bytes:
```
SθW¬№ω_≔⁺ωSω≔⁺θωθF²«≔E\/_⊕⊘№θκη×_⊟ηM⁰¬ιFη«↷¹κ↷¹¶
```
[Try it online!](https://tio.run/##bU4xbsMwDJytVxCaKMCF066dii7pkMJoOgowDFe1hDiSY8v2UOTtKum4QIZy4ZHHu2Nj66EJdZfSm@@neIyD8y1e1LNYrOsM4HuI@BomH3HJQVZSKQUv4@haj2U3jby9VyqVw0Lq@5MLr3Jg0@8wAD4p@BHZdnGoe5RaF5Vko2YwZ@Oj@cJ93c3UbtHkcKJgMrFkkpUUFfHTnc2IkoVl6NEST9whzAZ3OfDfbt2smXbNzEo3h/jhWhvxkbnN6nTD/5NSe8njVVxTAqioBBRApcXaGGj4Q7DBQtDEx0V6mLtf "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
SθW¬№ω_≔⁺ωSω≔⁺θωθ
```
Input all of the lines. (Input in JSON format would make this unnecessary at a saving of 17 bytes.)
```
F²«
```
Draw the top right and bottom left sections of the hexagon separately.
```
≔E\/_⊕⊘№θκ
```
Count the number of `/`s, `/`s, and `_`s in the string and use that to calculate the new side lengths.
```
η×_⊟ηM⁰¬ι
```
Output the top or bottom, and move down a line if this was the top line.
```
Fη«↷¹κ↷¹¶
```
Draw both of the right or left sides.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~75~~ 74 bytes[SBCS](https://github.com/abrudz/sbcs)
```
' /\_'∘{⍺[a×1=(+⍀×a)⌊⊖+⍀⊖×a←2⌈/{⊃0~⍨1⌷⍵,⍨⍉⍵}⌺3 3(0,0,⍨⍉)⍣3⍉⍺⍳↑⍵]}'.+'⎕s'&'
```
[Try it online!](https://tio.run/##7ZK/TgJBEMZ7nmIqF8LpHNKZ@Aq8gGsuG/4okQjhsCAEY9QQQI5IgVhrY2dhiAmlvMm8CM4ud3B70Nh7Bez8bma/mW9ONWqHpbaq1S9WNJ5W69R7dlcCUHqC@q8dChZnajnLnaazFNwtZypDoyENX3TEfwy44JhGfezQ8MG9peAjR6NvCuYOHykY8KlLo0Ue8mnXcUOYoeA9b14uKPii3oSzzrviKCu4B18ciFWFr6VgzHf@fOZ1AvNmkX9bl1V/VdBvx9Obog85F@jpETgqtkWpcu0LE7c4g5uf0@CtyccKK52Uqn6jptqioqo1YaTnTc7lUs7QJ1G/Et1USgHHAsDjBwCEU0gpxyDkEGQcGaLZFkkIWawwZBhDIPX9aArLWpGG90yNqpYFkSo7G4yhjI0xkrJwRE1bWyxhy@OXbDlakhFHu5N139w4Y6V9npQ3lnmWMzEDpIeJOfWMiVHkzhAy2b7VoTT27TTxv7c/700/8d2ty6UFMGEDGgXLY0w4jNYWpGcGTPoGu9/CWt52IWQJDyKDcY/puMdy3GM42suRG6Wdb20NQ/N@AQ "APL (Dyalog Unicode) – Try It Online")
`'.+'⎕s'&'` split input into lines
`↑⍵` mix lines into a matrix
`⍺⍳` replace `' /\_'` with `0 1 2 3`
`(0,0,⍨⍉)⍣3⍉` surround with a layer of 0s on top&bottom and two layers of 0s on the left&right
`{⊃0~⍨1⌷⍵,⍨⍉⍵}⌺3 3` for each cell choose the first non-0 from: upper, lower, left, right from the 3x3 neighbourhood centred on it
`2⌈/` max in pairs horizontally
`a×1=(+⍀×a)⌊⊖+⍀⊖×a←` keep only the outer boundary of non-0s
`⍺[` `]` replace `0 1 2 3` with `' /\_'`
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 126 bytes
```
$args-replace' *\S +','$0 '-replace'( +)(_+)','$1 $2_
$1/$2 \'-replace'( *)(\\_+)/','$1$2 /
$1 $2_/'-replace'_(?=.* )',' '
```
[Try it online!](https://tio.run/##ZZLNTsMwEITvfopRZYjzU0x7r8g7cLVkRcW0h4iGpIhKpc8e1ms7GPDBO1rPfLsHD6dPN05H1/ezfMUO11l242Faj27ou70rUJln1EVTyEcAxdJXqEtl69K/bCC3VsiNlluY3FKVyhgyaXbRK6BFsOsfn1VPu4cKHoVivgnRKiEa1a4EYOkIaArCCC5eGCSFKDV5jTdrsWobjnKWwiHtvXqJJZXDfvESMtOBzwPKtJ8lEhGyqXHdOCLSKW7@JP2xXDyBC08JhW@@cjZnQijMiAILAQsEiYOI4vp/mxJfuMOVUfLoLt3h9NZAusvg9mf3Qj9CholydNNHf6bGPX2UZM2f1u59yeV9cZu/AQ "PowerShell – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/), ~~177~~ ~~156~~ 145 bytes
```
@l=pop=~/.+/g;splice@l,$_,0,$l[$_]=~s,_, ,gr for-1,1;$l[$_]=~s, (\S)( +)(\S),$_<2?" $1$2 $3":"$1$2 $3",e for 1..@l-2;join("\n",@l)=~s,_+,$&_,gr
```
Could be shorter? Don't see how just yet. With comments and added newlines and header+footer:
```
sub f {
@l=pop=~/.+/g; #1
splice@l,$_,0,$l[$_]=~s,_, ,gr for-1,1; #2
$l[$_]=~s, (\S)( +)(\S),$_<2?" $1$2 $3":"$1$2 $3",e for 1..@l-2; #3
join("\n",@l)=~s,_+,$&_,gr #4
}
```
[Try it online!](https://tio.run/##ZZJRT4MwEMff@ykupHHUdaugvgxRvoBP@mZNo6abmA4IZTHLsn11pC0dzeSBu971//tfcm1kq@57vfuE9aEvVN7UTX5iyznbZLpR5ZcsFMWC3lCs3rB4z0@aCgp008K6bhcJTbKpATF/ITHMiYmD6iF9igAnOAV8G60im4HJqTRqSJbLQi3S7KcuqzjiVUQLRazDnOIrMZj0R7TdQ9FJ3eXxDIH9hIsMOHIRGJqiC@7PBZvRs@ysm4RjylwDBZlPfORjnQvDRBYqkJ@Cj6DJULimKXsfi/DXx6EDnEAOdmYIWxlKI@BihHEG4Z0mr8At8JscRTBlIA/03hQC539kB@RwCR/oiGRopyW8DotbrZ7rVoLZoc4f7zL0@10qGdulkoPdxHYf47KiuN51JN9@NKAZ19e8YqylMD5Dc314hmlmFU1bVh2sjYy4Sqljd3SYDB37Pw "Perl 5 – Try It Online")
Line #1 splits multi-line input string into the @l array.
Line #2 duplicates second and last lines without the \_ chars.
Line #3 adds spaces where needed on line 2 to second last.
Line #4 widens the two \_\_\_ sides with one \_ and returns the @l array of lines as one multi-line string.
] |
[Question]
[
The [Manhattan distance](https://en.wikipedia.org/wiki/Taxicab_geometry) on a regular grid is the number of orthogonal steps one needs to take to reach one cell from another. Orthogonal steps are those that go through the edges of the grid cells (as opposed to the corners, which would give us the [Chebyshev distance](https://en.wikipedia.org/wiki/Chebyshev_distance)).
We can define a similar distance on other grids, for example the triangular grid. We can address the individual cells in the grid with the following indexing scheme, where each cell contains an `x,y` pair:
```
____________________________________...
/\ /\ /\ /\ /\
/ \ 1,0/ \ 3,0/ \ 5,0/ \ 7,0/ \
/ 0,0\ / 2,0\ / 4,0\ / 6,0\ / 8,0\
/______\/______\/______\/______\/______\...
\ /\ /\ /\ /\ /
\ 0,1/ \ 2,1/ \ 4,1/ \ 6,1/ \ 8,1/
\ / 1,1\ / 3,1\ / 5,1\ / 7,1\ /
\/______\/______\/______\/______\/___...
/\ /\ /\ /\ /\
/ \ 1,2/ \ 3,2/ \ 5,2/ \ 7,2/ \
/ 0,2\ / 2,2\ / 4,2\ / 6,2\ / 8,2\
/______\/______\/______\/______\/______\...
\ /\ /\ /\ /\ /
\ 0,3/ \ 2,3/ \ 4,3/ \ 6,3/ \ 8,3/
\ / 1,3\ / 3,3\ / 5,3\ / 7,3\ /
\/______\/______\/______\/______\/___...
/\ /\ /\ /\ /\
. . . . . . . . . .
. . . . . . . . . .
```
Now the Manhattan distance on this grid is again the minimal number of steps across edges to get from one cell to another. So you can move from `3,1` to `2,1`, `4,1` or `3,2`, but not to any other triangle, since those would be crossing points rather than edges.
For instance, the distance from `2,1` to `5,2` is `4`. The shortest path is generally not unique, but one way to make the distance in 4 steps is:
```
2,1 --> 3,1 --> 3,2 --> 4,2 --> 5,2
```
## The Challenge
Given two coordinate pairs `x1,y1` and `x2,y2` from the above addressing scheme, return the Manhattan distance between them.
You may assume that all four inputs are non-negative integers, each less than 128. You may take them in any order and arbitrarily grouped (four separate arguments, a list of four integers, two pairs of integers, a 2x2 matrix, ...).
You may write a [program or a function](https://codegolf.meta.stackexchange.com/q/2419) and use any of the [standard methods](https://codegolf.meta.stackexchange.com/q/2447) of receiving input and providing output.
You may use any [programming language](https://codegolf.meta.stackexchange.com/q/2028), but note that [these loopholes](https://codegolf.meta.stackexchange.com/q/1061/) are forbidden by default.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest valid answer – measured in *bytes* – wins.
## Test Cases
Each test case is given as `x1,y1 x2,y2 => result`.
```
1,2 1,2 => 0
0,1 1,1 => 1
1,0 1,1 => 3
2,1 5,2 => 4
0,0 0,127 => 253
0,0 127,0 => 127
0,0 127,127 => 254
0,127 127,0 => 254
0,127 127,127 => 127
127,0 127,127 => 255
75,7 69,2 => 11
47,58 36,79 => 42
77,9 111,23 => 48
123,100 111,60 => 80
120,23 55,41 => 83
28,20 91,68 => 111
85,107 69,46 => 123
16,25 100,100 => 159
62,85 22,5 => 160
92,26 59,113 => 174
62,22 35,125 => 206
```
[Answer]
## JavaScript (ES6), ~~84~~ 78 bytes
*Saved 6 bytes thanks to Neil*
```
(a,b,c,d,x=a>c?a-c:c-a,y=b>d?b-d:d-b,z=x>y?x:y)=>y+z+(x+z&1?a+b+(b>d)&1||-1:0)
```
### Test cases
```
let f =
(a,b,c,d,x=a>c?a-c:c-a,y=b>d?b-d:d-b,z=x>y?x:y)=>y+z+(x+z&1?a+b+(b>d)&1||-1:0)
console.log(f( 1, 2, 1, 2)); // => 0
console.log(f( 0, 1, 1, 1)); // => 1
console.log(f( 1, 0, 1, 1)); // => 3
console.log(f( 2, 1, 5, 2)); // => 4
console.log(f( 0, 0, 0,127)); // => 253
console.log(f( 0, 0,127, 0)); // => 127
console.log(f( 0, 0,127,127)); // => 254
console.log(f( 0,127,127, 0)); // => 254
console.log(f( 0,127,127,127)); // => 127
console.log(f(127, 0,127,127)); // => 255
console.log(f( 75, 7, 69, 2)); // => 11
console.log(f( 47, 58, 36, 79)); // => 42
console.log(f( 77, 9,111, 23)); // => 48
console.log(f(123,100,111, 60)); // => 80
console.log(f(120, 23, 55, 41)); // => 83
console.log(f( 28, 20, 91, 68)); // => 111
console.log(f( 85,107, 69, 46)); // => 123
console.log(f( 16, 25,100,100)); // => 159
console.log(f( 62, 85, 22, 5)); // => 160
console.log(f( 92, 26, 59,113)); // => 174
console.log(f( 62, 22, 35,125)); // => 206
```
## Initial recursive solution, ~~100~~ ~~88~~ 81
*Saved 12 bytes thanks to ETHproductions*
*Saved 7 bytes thanks to Neil*
```
f=(a,b,c,d,e=b==d|a+b+(b>d)&1)=>a-c|b-d&&f(e?a+1-2*(a>c):a,e?b:b+1-2*(b>d),c,d)+1
```
### How it works
Although it still essentially applies to the current version, the following explanation more specifically refers to the initial version:
```
f=(a,b,c,d)=>b-d?a+b+(b>d)&1?f(a+1-2*(a>c),b,c,d)+1:f(a,b+1-2*(b>d),c,d)+1:Math.abs(a-c)
```
Going from ***(x0, y)*** to ***(x1, y)*** is trivial because we can go across lateral edges all the way from the source triangle to the target one. The Manhattan distance in this case is ***| x0 - x1 |***.
The tricky part is the vertical steps. To go from row ***y0*** to row ***y1***, we have to take these two parameters into account:
* The orientation of the current triangle
* Whether ***y0*** is less or greater than ***y1***
The orientation of a triangle is given by the parity of ***x + y***:
* if it's even, the triangle is up-pointing
* if it's odd, the triangle is down-pointing
We can go downwards from an up-pointing triangle (useful when ***y0 < y1***) and upwards from a down-pointing triangle (useful when ***y0 > y1***).
By combining the orientation of the triangle with the comparison between ***y0*** and ***y1***, we get the formula ***x + y0 + (y0 > y1 ? 1 : 0)*** whose result is even if we can go in the desired direction and odd if not.
If we can't reach the next row directly, we first need to get a correct alignment by updating ***x***:
* if ***x*** is not yet equal to ***x1***, we definitely want to move in the correct direction, so we increment it if **x** is less than ***x1*** and we decrement it if ***x*** is greater than ***x1***
* if ***x*** already equals ***x1***, we can either increment or decrement it
### Test cases
```
f=(a,b,c,d)=>b-d?a+b+(b>d)&1?f(a+1-2*(a>c),b,c,d)+1:f(a,b+1-2*(b>d),c,d)+1:Math.abs(a-c)
console.log(f( 1, 2, 1, 2)); // => 0
console.log(f( 0, 1, 1, 1)); // => 1
console.log(f( 1, 0, 1, 1)); // => 3
console.log(f( 2, 1, 5, 2)); // => 4
console.log(f( 0, 0, 0,127)); // => 253
console.log(f( 0, 0,127, 0)); // => 127
console.log(f( 0, 0,127,127)); // => 254
console.log(f( 0,127,127, 0)); // => 254
console.log(f( 0,127,127,127)); // => 127
console.log(f(127, 0,127,127)); // => 255
console.log(f( 75, 7, 69, 2)); // => 11
console.log(f( 47, 58, 36, 79)); // => 42
console.log(f( 77, 9,111, 23)); // => 48
console.log(f(123,100,111, 60)); // => 80
console.log(f(120, 23, 55, 41)); // => 83
console.log(f( 28, 20, 91, 68)); // => 111
console.log(f( 85,107, 69, 46)); // => 123
console.log(f( 16, 25,100,100)); // => 159
console.log(f( 62, 85, 22, 5)); // => 160
console.log(f( 92, 26, 59,113)); // => 174
console.log(f( 62, 22, 35,125)); // => 206
```
[Answer]
# Python 2, 74 bytes
```
lambda x,y,X,Y:abs(y-Y)+max(x-X,X-x,abs(y-Y)+((x+y+X+Y)%-2)**(x^y^(Y>=y)))
```
[Answer]
## Batch, 99 bytes
```
@cmd/cset/a"x=%3-%1,x*=x>>31|1,y=%4-%2,w=y>>31,y*=w|1,z=x+(y+x&1)*(-(%1+%2+w&1)|1)-y,z*=z>>31,x+y+z
```
Explanation: A horizonal-only motion simply takes the absolute x-coordinate difference. For large enough x, the vertical motion only takes one extra step per absolute y-coordinate difference, but for small x, it takes four extra steps per two y-coordinate difference, plus one or three steps for an odd difference. This is calcluated as two steps per difference plus a correction factor. The larger of the corrected two steps and the sum of absolute differences is then the result, although this is itself calculated as the larger of the corrected absolute y-coordinate difference and the absolute x-coordinate distance added to the uncorrected absolute y-coordinate difference.
* `@cmd/cset/a"` - Evaluates comma-separated expressions and prints the last one
* `x=%3-%1,x*=x>>31|1` Calculates \$x=|x\_2-x\_1|\$
* `y=%4-%2,w=y>>31,y*=w|1` Calculates \$w=y\_1>y\_2\$ and \$y=|y\_2-y\_1|\$
* `z=x+(y+x&1)*(-(%1+%2+w&1)|1)-y` Correction factor \$c=(y+(x\bmod2))(1-2((x\_1+y\_1+w)\bmod2)), z=x+c-y\$
* `z*=z>>31,x+y+z` Calculates \$max(x,y-c)+y = x+y-min(0,x+c-y)\$
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 24 bytes
```
⁴<³¬Ḋ;³S
SḂN*¢+ḊḤ$
ạµS»Ç
```
[Try it online!](https://tio.run/##AUEAvv9qZWxsef//4oG0PMKzwqzhuIo7wrNTClPhuIJOKsKiK@G4iuG4pCQK4bqhwrVTwrvDh////zYyLDIy/zM1LDEyNQ "Jelly – Try It Online")
Let’s call the input \$(x,y),(X,Y)\$. I worked from feersum's formula:
\begin{align\*}
d &= |y-Y|+\max(|x-X|,|y-Y|+((x+y+X+Y)\bmod -2)^{x \oplus y \oplus (Y \geq y)}) \\
&= |y-Y|+\max(|x-X|,|y-Y|+[-(|x-X|+|y-Y| \bmod 2)]^{x + y + (Y \not< y)}) \\
&= \max(|x-X|+|y-Y|,2|y-Y|+[-(|x-X|+|y-Y| \bmod 2)]^{(Y \not< y) + x + y}).
\end{align\*}
The first line computes \$¢ = (Y \not< y)+x+y\$, the exponent in the formula.
The last line first computes \$L=[|x-X|, |y-Y|]\$ and then computes the maximum of \$\text{sum}(L)\$ and \$f(L)\$, where \$f\$ is the function on the middle line.
The middle line, given \$L=[a, b]\$, computes \$-((a+b)\bmod 2)\$, takes that to the \$¢\$'th power, then adds \$2b\$.
[Answer]
# racket/scheme, 214 bytes
```
(define(f x y X Y)(let m((p x)(q y)(c 0))
(let((k(+ c 1))(d(- Y q)))
(cond((= 0(- X p)d)c)
((and(> d 0)(even?(+ p q)))(m p(+ q 1)k))
((and(< d 0)(odd?(+ p q)))(m p(- q 1)k))
((< p X)(m(+ p 1)q k))
(else(m(- p 1)q k))))))
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 24 bytes
Port of my [Pyth answer](https://codegolf.stackexchange.com/a/167393/59487), which in turn uses roughly the same approach as [feersum's Python answer](https://codegolf.stackexchange.com/a/115299/59487). Takes input as a list of pairs of coordinates, \$(x\_1, x\_2), (y\_1, y\_2)\$. Fixed a bug for +1 byte, then fixed another mistake for +1, but which yielded the correct result for all test cases...
```
ÆÄ`©I˜OÉ(IøнOIθD{Q+m+M®+
```
[Try it online!](https://tio.run/##AT8AwP8wNWFiMWX//8OGw4RgwqlJy5xPw4koScO40L1PSc64RHtRK20rTcKuK///W1s0NywgMzZdLCBbNTgsIDc5XV0 "05AB1E – Try It Online")
### Breakdown
```
ÆÄ`©I˜OÉ(IøнOIθD{Q+m+M®+ Full program. I represents the evaluated input.
ÆÄ Reduce the pairs by subtraction, take the absolute values.
`© Dump them separately onto the stack and store the second
one, |y1-y2| in the register C.
I˜O Push the sum of flattened input onto the stack.
É( Take its parity and negate it.
Iøн Push [x1, y1].
O Take x1+y1 (sum them).
IθD{Q Then check if the second pair is sorted (y1 ≤ y2).
+ And sum that with x1+y1.
m Exponentiate. Push the parity above ** the result.
+ And add the second absolute difference to that.
M®+ As a result, push the largest number on the stack
plus the value stored in register C.
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~74~~ ~~72~~ 71 bytes
```
lambda c,a,d,b:abs(a-b)+abs(a+(-c-a)/2-b-(-d-b)/2)+abs((c+a)/2-(d+b)/2)
```
[Try it online!](https://tio.run/##TY7BbsMgEETv/goUyRLIg4LXAexI6Zf0AqZOK7Vp1OTSr3fXYFcWsjUzb3bh/vt8/77RPF1e58/wFVMQIwIS4jnEhww6qiaLRupRB3UkHbXUifMjFSTHJucyNTmc09skrnJdo86VuP983J7iUCfUSZT/5UXUj4OoBfdEgEgQEWLaOaWq6ipbEPhTLA0LPiqnZpMLtlthOS35zbCE2Zt/tpqNbnblmewDb@HhhnLNycP26Bz8kJnHgLblR3ZltkNrTE6cKYlhBmtxKi/uwcnAuF9sb7mft59crjuQLStMnncE7hDBLm4gkINdruxWyqjjCbJq/gM "Python 2 – Try It Online") Link includes test cases. Edit: Saved 2 bytes thanks to @JoKing. Saved a further byte thanks to @Mr.Xcoder. Based on the following formula I found in this [question](https://math.stackexchange.com/q/941051/30622):
$$ \left|a\_i-b\_i\right|\;+\;\left|\left(a\_i-\left\lfloor\frac{a\_j}2\right\rfloor\right)-\left(b\_i-\left\lfloor\frac{b\_j}2\right\rfloor\right)\right|\;+\;\left|\left\lfloor\frac{a\_j+1}2\right\rfloor-\left\lfloor\frac{b\_j+1}2\right\rfloor\right| $$
The coordinate systems differ in three ways; the coordinates are exchanged (which explains my somewhat strange parameter name order), the coordinates are angled at \$120^\circ\$ rather than \$90^\circ\$ (which explains the two additions) and the coordinates in the linked question use inferior 1-indexing. Since we're taking differences this cancels out most of the time and we are left with:
$$ \left|a\_i-b\_i\right|\;+\;\left|\left(a\_i-\left\lfloor\frac{a\_j+1}2\right\rfloor\right)-\left(b\_i-\left\lfloor\frac{b\_j+1}2\right\rfloor\right)\right|\;+\;\left|\left\lfloor\frac{a\_j}2\right\rfloor-\left\lfloor\frac{b\_j}2\right\rfloor\right| $$
This can then be golfed by noting that \$ -\lfloor\frac{a\_j+1}2\rfloor = \lfloor\frac{-a\_j}2\rfloor \$.
[Answer]
# [Pyth](https://pyth.readthedocs.io), ~~31~~ 28 bytes
Uses roughly the same approach as in [feersum's Python answer](https://codegolf.stackexchange.com/a/115299/59487). Takes input as a list of pairs of coordinates, \$(x\_1, x\_2), (y\_1, y\_2)\$. Fixed a bug for -1 byte.
```
+eKaMQg#hK+eK^%ssQ_2+shCQSIe
```
[Try it here!](https://pyth.herokuapp.com/?code=%2BeKaMQg%23hK%2BeK%5E%25ssQ_2%2BshCQSIe&input=%5B%5B127%2C+127%5D%2C+%5B0%2C+127%5D%5D&debug=0) or [Try the test suite!](https://pyth.herokuapp.com/?code=%2BeKaMQg%23hK%2BeK%5E%25ssQ_2%2BshCQSIe&test_suite=1&test_suite_input=%5B%5B1%2C+1%5D%2C+%5B2%2C+2%5D%5D%0A%5B%5B0%2C+1%5D%2C+%5B1%2C+1%5D%5D%0A%5B%5B1%2C+1%5D%2C+%5B0%2C+1%5D%5D%0A%5B%5B2%2C+5%5D%2C+%5B1%2C+2%5D%5D%0A%5B%5B0%2C+0%5D%2C+%5B0%2C+127%5D%5D%0A%5B%5B0%2C+127%5D%2C+%5B0%2C+0%5D%5D%0A%5B%5B0%2C+127%5D%2C+%5B0%2C+127%5D%5D%0A%5B%5B0%2C+127%5D%2C+%5B127%2C+0%5D%5D%0A%5B%5B0%2C+127%5D%2C+%5B127%2C+127%5D%5D%0A%5B%5B127%2C+127%5D%2C+%5B0%2C+127%5D%5D%0A%5B%5B75%2C+69%5D%2C+%5B7%2C+2%5D%5D%0A%5B%5B47%2C+36%5D%2C+%5B58%2C+79%5D%5D%0A%5B%5B77%2C+111%5D%2C+%5B9%2C+23%5D%5D%0A%5B%5B123%2C+111%5D%2C+%5B100%2C+60%5D%5D%0A%5B%5B120%2C+55%5D%2C+%5B23%2C+41%5D%5D%0A%5B%5B28%2C+91%5D%2C+%5B20%2C+68%5D%5D%0A%5B%5B85%2C+69%5D%2C+%5B107%2C+46%5D%5D%0A%5B%5B16%2C+100%5D%2C+%5B25%2C+100%5D%5D%0A%5B%5B62%2C+22%5D%2C+%5B85%2C+5%5D%5D%0A%5B%5B92%2C+59%5D%2C+%5B26%2C+113%5D%5D%0A%5B%5B62%2C+35%5D%2C+%5B22%2C+125%5D%5D&debug=0)
## Breakdown
```
+eKaMQg#hK+eK^%ssQ_2xxFhCQSIe Full program. Q = eval(input()).
KaMQ Store the differences [|x1-x2|, |y1-y2|] in K.
e Retrieve the latter (|y1-y2|).
+ g# And add it to the greatest value between:
hK - The head of K (|x1-x2|)
+ - And the result of adding:
eK The end of K (|y1-y2|).
^ - with the result of exponentiating:
%ssQ_2 The sum of the flattened Q, modulo -2.
Yields -1 if x1+x2+y1+y2 is odd, 0 otherwise.
xxFhCQSIe - by the result of this expression:
hCQ Transpose Q and get the head (x1, y1).
xF Reduce by bitwise XOR.
SIe And check if the list [y1, y2] is sorted.
x After which, xor the result by the bool (0/1).
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 16 bytes
Uses a modified version of [Neil's answer](https://codegolf.stackexchange.com/a/167493/59487), optimised for stack-based languages like 05AB1E. Takes input as two pairs of coordinates, \$(x\_1, x\_2), (y\_1, y\_2)\$, separated by a newline from STDIN. Initially I merged that with my [other 05AB1E answer](https://codegolf.stackexchange.com/a/167395/59487) but then decided to post it separately because it's very, very different.
```
+D(‚2÷Æ`²Æ©+®)ÄO
```
[Try it online!](https://tio.run/##ATQAy/8wNWFiMWX//ytEKOKAmjLDt8OGYMKyw4bCqSvCrinDhE///1s0NywgMzZdCls1OCwgNzld "05AB1E – Try It Online") or [Try the test suite!](https://tio.run/##ZZAxDsIwDEVnboGYQBjJcZqkWWDpzgGiSoDEPRgQh2BiYGHphujciJVDcJHipE0lYIni9/93YqPa7sS@fd2bW1MVvl5NRovleLJqfb0upu/DmfzDnzZN9ar9qXhe5jN/XLfNFVrnnABRgiOgsoSxcxjLAGPZqZhKAhXVwYydSmZI8xWi8AP@PHz@ugIafKn4ChsF2jIy6QuZAakZqByM7T2cE@HbFkimXrJnAhE0JoqgwkCsZmnCHGxcCNvyDuX9mwINZLqPauBOwafiJULNWyRmHFAdsbywECW2Czm4ZHyUeCz2lR8 "05AB1E – Try It Online") (Uses a slightly modified version of the code (`®` instead of `²`), courtesy of [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen))
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~22 .. 16~~ 15 bytes
```
ṭH,‘H_ɗɗ@+¥ḞIAS
```
[Try it online!](https://tio.run/##y0rNyan8///hzrUeOo8aZnjEn5x@crqD9qGlD3fM83QM/v//v5GpjqGBwX9DMxAFAA "Jelly – Try It Online")
[Try all test cases.](https://tio.run/##TU49S0NBEOzvV2zvgnf73t5HoWgjsRYFKysbSWeVLvgTtIiF2omNNsEiwWChPCE/4@WPnHMXfAg3N7OzO8teXY7Hk5z75duIN9P70cV6tp4d7Hw994un48OT3H@894v55ub1DMA7PcLX3XZ3oH@yW32/7IJ/5sW8BqRffm4j3arw9IEK9vZBj2XoPGfHQoCx7MDOOLaVBbVW3xJ6EqoCsx3U1sU/@H@6dKo3VEE5kE/Y2AbWSI3nkEwInMg5HNBgvmFnbS29RWnhkiq3uCayWEpoRBMVY3VX643zLEqIlajxwlFJhNUkYfGkiZ1rii9CDYKivw)
Uses @Neil's method in [this](https://codegolf.stackexchange.com/a/167493/75553) answer which uses a modified formula from [this](https://math.stackexchange.com/q/941051/514788) math.SE question.
Takes the coordinates as arguments `y1, y2` and `x1, x2`.
[Answer]
# Java 8, ~~157~~ ~~190~~ ~~188~~ ~~144~~ ~~142~~ ~~141~~ ~~127~~ 125 bytes
```
(a,b,x,y)->{int r=0,c=1,z=1;for(;(c|z)!=0;r--)if((z=y-b)*z<(c=x-a)*c|a%2!=b%2?z<0:z>0)b+=z<0?-1:1;else a+=c<0?-1:1;return~r;}
```
+33 bytes (157 → 190) due to a bug fix.
-44 bytes (188 → 144) converting the recursive method to a single looping method.
**Explanation:**
[Try it here.](https://tio.run/##hVRdb5swFH3vr3CRKpkCEThASCit9rDH9WHZ27IHx3EmOkIiMB3Qpn89u7ahUUiiScjm3nPuuR9gv9BX6rys/hxYRssSfaNp/naDUJoLXqwp4@hZmsqBGJZr7dnKarq9Jp1NzBio@xtYnlGOEnTA1F7atd2YzuObpBSJa7PEs9vEi9fbAseYvbfmbeLGheOY6RrjNmmcpXnfPmCW1A4179k7vSO3yfKOPLUP7qx9dM2llcDrk@PNvJhnJUfUSljvKLioivyjiPeHWFayq5ZZylApqIDtdZuu0AZ6xHNRpPnvn78QNXWD86YUfDPaVmK0A0hkOTbmghZithAL8TVf6b3ecSa4NL4wUdFMeX/wUqCyYozzFWCGGsRFyQ6RY0YbGFHO/yqjBwQo4Y2NYLakX90B5iqge87jPuHxANOCgXrxzzX145EJEILxRVyBer@OdwoXMhxh97@Mfhn2d6zgM1Mw4EygRQDCqW55OCIfsCCC8YRAA45PhvFAmMpAOf4xEKKzIsDruW7HCeElcs84ro4OoBofWNHZ54AaJGkqJSKlNWBEgUzTteKHKvEwTSgn0FejlmA64IRESxGivr4XDmudAkBAKFBdy94m/gUNGT@WAjIhccOLv4CvZu8N69Tu7i8ZHy8KOBevVPCT86li9AnpbpirN47eeXcov/OyyoR5vLAK5YBjthnlI4aljtSQ8Q25fkgNbFi1Zxm2YTWwmcBaCOkj2kd6n2GdprYMeRsYVnFiYW0myaDObgr7wz8)
```
(a,b,x,y)->{ // Method with four integers as parameter and integer return-type
// (a=x1; b=y1; x=x2; y=y2)
int r=0, // Result-integer `r`, starting at 0
c=1,z=1; // Temp integers for the differences, starting at 1 for now
for(;(c|z)!=0; // Loop until both differences are 0
r--){ // After every iteration: decrease the result `r` by 1
if((z=y-b) // Set `z` to y2 minus y1
*z< // And if its squared value is smaller than:
(c=x-a) // Set `c` to x2 minus x1
*c // And square it as well
|a%2!=b%2? // OR if the triangle at the current location is facing downwards
z<0 // and we have to go upwards,
:z>0) // or it's facing upwards and we have to go downwards:
b+=z<0?-1:1; // In/decrease y1 by 1 depending on where we have to go
else // Else:
a+=c<0?-1:1;} // In/decrease x1 by 1 depending on where we have to go
return~r; // Return `-r-1` as result
```
] |
[Question]
[
A 2D board *will* contain the following objects:
* `^`,`>`,`v`, or `<`: A laser emitter facing up, right, down, or left respectively. There may be more than one. Lasers will travel in a straight line in empty space (empty space is represented with a dot `.`). Lasers do not pass through emitters.
* `*`: A target. Lasers *pass through* targets. There may be more than one.
The board *may* also contain the following objects:
* `@`: A solid wall. The laser will not pass through here.
* `\`: A *left-leaning* reflector. Changes the direction of lasers according to the following table:
```
Direction laser is travelling Direction of laser after hitting reflector
Up Left
Right Down
Down Right
Left Up
```
It should be pretty intuitive as to how the reflectors work. Just imagine them as an actual two-sided mirror and the directions should be clear.
* `/`: A *right-leaning* reflector. Changes the direction of lasers according to the following table:
```
Direction laser is travelling Direction of laser after hitting reflector
Up Right
Right Up
Down Left
Left Down
```
* `1`,`2`,`3`...`9`: A *portal*. The number indicates the channel of the portal - there will be exactly two portals of the same channel (for instance, there won't be three `1`'s). The portal changes the *position* of lasers to the position of the other portal of the same channel. For instance:
```
> 1 @ 1 *
```
The laser will hit the target because when it hits the first `1`, it is teleported to the second `1` on the other side. Lasers retain the same direction that they were in before.
A portal will not teleport the laser to a portal of a different channel (i.e. a `1` won't teleport the laser to a `9`.
Your program will recieve a 2D representation of the board as input. The board will always be rectangular shaped. The output should be `True` if all the targets have lasers passing through them, or `False` otherwise.
Here are some test cases:
1. Input
```
>....\
..*...
>./../
..*...
```
Output
```
True
```
2. Input
```
>..........\
1........../
2..........1
3..........2
4..........3
5..........4
6..........5
7..........6
8..........7
9..........8
*..........9
```
Output
```
True
```
3. Input
```
>.@............*
>..@...........*
>...@..........*
>....@.........*
>.....@........*
>...*..@........
>.......@......*
```
Output
```
False
```
4. Input
```
../\.
>./**
```
Output
```
False
```
5. Input
```
/.......*.......\/3.....
@..............//\.\....
*.............2\.1\/\...
\..............///.....<
.........*...//\\/.....\
>.............\.1.///.4.
4.......*/...\2\/3/\/..^
```
Output
```
True
```
6. Input
```
vvvvvvvvvvvvvvvvv
\\\\\\\\\\\\\\\\\
/////////////////
\\\\\\\\\\\\\\\\\
/////////////////
\\\\\\\\\\\\\\\\\
/////////////////
*****************
```
Output (note the target at the far right)
```
False
```
[Answer]
## Python, ~~310~~ ~~302~~ ~~287~~ ~~278~~ ~~277~~ 260
Not radically different than the existing Python post, but has one or two noteworthy tricks, I think.
~~It also handles "non-terminating" input, such as `1>1`.~~ **EDIT**: Oops! emitters block lasers.
```
def t(b):
w=len(b[0])+1;B=list('@'*w+'@'.join(b));i=l=len(B);C="<>^v@"
while i:
j=l-i;i-=1;d=C.find(B[j]);c='.'
while c not in C:
if'+'>c:B[j]='.'
if'0'<c<C:j=(B*2).index(c,j+1)%l
elif'.'<c:d^=2+(c<C)
j-=[1,-1,w,-w,j][d];c=B[j%l]
return'*'not in B
```
`t` takes a list of strings (the input lines) and returns a boolean result.
Here's a nice gif of the code being golfed down:

**EDIT**: Awsome gif courtesy of Will. Thanks Will!
[Answer]
## Perl, 647
This is my first ever attempt at code-golf, and I'm a bit embarrassed I didn't even beat the C# score, but I thought it would be interesting (or fun, or just masochistic) to do the entire thing as a series of regex substitutions. (I also thought it would be fun to brush up on my Perl, but by the end I was deeply regretting not implementing it in Ruby or Python.)
I haven't done a lot of testing, but I *think* it should handle every case.
The grid is input via STDIN. There must be at least one newline in the input (i.e. a single row without a newline won't work).
```
%s=(d,'[|+#$vk%ZX]',u,'[|+#$^W%KX]',r,'[-G+#>k%KX]',l,'[-G+#<W%ZX]');%o=(d,'[-.*G/k\\\\Z',u,'[-.*G/W\\\\K',r,'[|.*$\\\\/kK',l,'[|.*$\\\\/ZW');for$d(d,u,r,l){$o{$d}.='123456789qwertyuio]'}%u=(d,'.|-+*$G#/Wk%\KZX',u,'.|-+*$G#/kW%\ZKX',r,'.-|+*G$#/Wk%\ZKX',l,'.-|+*G$#/kW%\KZX');@q=split//,"qwertyuio";local$/;$_=<STDIN>;for$i(1..9){$m{$i}=$q[$i-1];$m{$m{$i}}=$i;s/$i/$m{$i}/e}/.*?\n/;$l='.'x((length$&)-1);do{$c=0;for$d(d,u,r,l){%p=(d,"(?<=$s{d}$l)$o{d}",u,"$o{u}(?=$l$s{u})",r,"(?<=$s{r})$o{r}",l,"$o{l}(?=$s{l})");%h=split//,$u{$d};$c+=s!$p{$d}!$h{$&}||($v=$&,($o{$d}=~s/$v// && $s{$d}=~s/]/$m{$v}]/),$v)!es}}while($c);print/\*/?"False\n":"True\n"
```
Explanation: the code iteratively updates the grid string as the lasers pass through it. `-` represents a horizontal laser, `|` a vertical laser, `+` crossed lasers, `K` a `\` mirror with a laser bouncing off the top, `k` a `/` mirror with a laser bouncing off the bottom, `Z` a `\` mirror with a laser bouncing off the bottom, and `W` a `/` mirror with a laser bouncing off the top. `%` is a `/` mirror with lasers on both sides, while `X` is a `\` mirror with lasers on both sides. (These are case sensitive. I tried to pick letters that look somewhat appropriate--for instance, `k` and `K` are somewhat obvious choices--but unfortunately the effect really isn't that helpful. I should really put this info into a table, but I'm exhausted right now.)
Handling portals in the same way (i.e. assigning each digit a set of extra characters based on the possible input/output laser positions) would require 144 characters (including the original 9), so instead, when a laser hits an "input" portal, I add the "output" portal character to the set of characters that emit a laser in the proper direction. (This does require differentiating between input and output portals; I used the letters `qwertyuio` for this.)
Somewhat un-golfed, with print statements so you can see the substitutions happening (each substitution represents one "round" of laser-progression), and with the `g` flag added to the main `s///` so that it doesn't take so many iterations:
```
# Throughout, d,u,r,l represents lasers going down, up, left, or right
# `sources` are the character classes representing laser "sources" (i.e. any
# character that can, on the next round, cause a laser to enter the space
# immediately adjacent to it in the proper direction)
%sources=(d,'[|+#$vk%ZX]',u,'[|+#$^W%KX]',r,'[-G+#>k%KX]',l,'[-G+#<W%ZX]');
# `open` characters will not block a laser
%open=(d,'[-.*G/k\\\\Z',u,'[-.*G/W\\\\K',r,'[|.*$\\\\/kK',l,'[|.*$\\\\/ZW');
# One of each portal is changed into the corresponding letter in `qwertyuio`.
# At the start, each portal is 'open' and none of them is a source.
for$d(d,u,r,l){$open{$d}.='123456789qwertyuio]'}
# A mapping of 'open' characters to the characters they become when a laser
# goes through them. (This is used like a hash of hashes; see the assignment
# of `%h` below.)
%update=(d,'.|-+*$G#/Wk%\KZX',
u,'.|-+*$G#/kW%\ZKX',
r,'.-|+*G$#/Wk%\ZKX',
l,'.-|+*G$#/kW%\KZX');
@q=split//,"qwertyuio";
local$/;$_=<STDIN>;
for$i(1..9){
$m{$i}=$q[$i-1];
$m{$m{$i}}=$i;
s/$i/$m{$i}/e}
print "After substituting portals:\n";
print;
print "\n";
# Find the number of characters in each line and create a string of `.`'s,
# which will be used to correlate characters above/below one another in the
# grid with each other.
/.*?\n/;
$l='.'x((length$&)-1);
do{
$changes=0;
for$d(d,u,r,l){
# `patterns` is a mapping from each direction to the regex representing
# an update that must occur (i.e. a place where a laser must progress).
# Each pattern is either a lookahead or lookbehind plus the necessary
# "open" character class.
%patterns=(d,"(?<=$sources{d}$l)$open{d}",
u,"$open{u}(?=$l$sources{u})",
r,"(?<=$sources{r})$open{r}",
l,"$open{l}(?=$sources{l})");
%h=split//,$update{$d};
# Match against the pattern for each direction. Note whether any
# matches were found.
$changes+=s!$patterns{$d}!
# If the "open" character for a map is in the `update` map, return
# the corresponding value. Otherwise, the "open" character is a
# portal.
$h{$&} || ($v=$&,
# For portals, remove the input portal from the
# proper "open" list and add the output portal to
# the proper "source" list.
($open{$d}=~s/$v// && $sources{$d}=~s/]/$m{$v}]/),
$v)
# This whole substitution should allow `.` to match
# newlines (see the definition of `$l` above), and the
# replacement must be an expression rather than a string
# to facilitate the portal logic. The `g` allows multiple
# updates per "frame"; it is left out of the golfed code.
!egs
}
# Print the next "frame".
print;
print "\n";
# Continue updating until no "open" spaces are found.
}while($changes);
# Print whether `*` is still present in the input.
print/\*/?"False\n":"True\n"
```
[Answer]
### Python 338 *351*
```
def t(b):
L=len;w=L(b[0])+3;b=list("@"*w+"@@".join(b)+"@"*w);w-=1;I=b.index
for i in range(L(b)):
c=b[i];d={"^":-w,"<":-1,">":1,"v":w}.get(c)
if d:
while c!='@':
i+=d;c=b[i]
if c=='*':b[i]='.'
elif c in '/\\':d={-w:-1,w:1,1:w,-1:-w}[d]*(-1 if c=='/' else 1)
elif c>'0':i+=I(c)-i or I(c,i+1)-i
return "*" not in b
```
My unminified version actually plots the laser paths on the board, which is pretty:
```
>-+--\
..X..|
>-/--/
..X...
>----------\
1----------/
2----------1
3----------2
4----------3
5----------4
6----------5
7----------6
8----------7
9----------8
X----------9
>-@............*
>--@...........*
>---@..........*
>----@.........*
>-----@........*
>---X--@........
>-------@......*
/-------X+------\/3.....
@........|.....//\+\....
X........|....2\+1\/\...
\--------+----+///+++--<
.........X...//\\/+++--\
>--------+---+\+1+///-4|
4-------X/...\2\/3/\/..^
vvvvvvvvvvvvvvvvv
\\\\\\\\\\\\\\\\\
/////////////////
\\\\\\\\\\\\\\\\\
/////////////////
\\\\\\\\\\\\\\\\\
/////////////////
XXXXXXXXXXXXXXXX*
def debug(board,x,y):
emit_dir = {
"^": ( 0, -1),
"<": (-1, 0),
">": ( 1, 0),
"v": ( 0, 1),
}
class PortalException(Exception): pass
xdir, ydir = emit_dir[board[y][x]]
while True:
# print "step (%d, %d) (%d, %d)" % (x, y, xdir, ydir)
x += xdir
y += ydir
if y < 0 or y >= len(board) or x < 0 or x >= len(board[y]):
return
ch = board[y][x]
if ch == '/':
xdir, ydir = -ydir, -xdir
elif ch == '\\':
xdir, ydir = ydir, xdir
elif ch in '@^><v':
return
elif ch == '*':
board[y] = board[y][:x] + 'X' + board[y][x+1:]
elif ch in '.-|':
ch = ('-' if xdir else '|') if ch == '.' else '+'
board[y] = board[y][:x] + ch + board[y][x+1:]
elif ch in '123456789':
try:
for r in range(len(board)):
for c in range(len(board[r])):
if board[r][c] == ch and (r != y or c != x):
x, y = c, r
raise PortalException()
raise Exception("could not find portal %s (%d,%d)" % (ch, x, y))
except PortalException:
pass
```
[Answer]
# C# - ~~515~~ ~~414~~ 400 bytes
Complete C# program, no nice output like Will's. Works by following the laser path for each emitted individually, and keeping an array of which cells we've visited, so that we can check that we've visited all the stars at the end. *Edit: striped a large number of bytes by making everything 1D and by using a char instead of an int to store the current char*
w0lf reminded me that I had an under utilized for-loop right in the middle of my code, so I figured I'd better make one last effort and put it to work, and now I'm down to the absolute minimum number of curly braces. I won't pretend to like the collapsing of the second for loop, the code is horribly disorderly now, but it saved a few bytes. In the process I re-wrote the portal handling. I also found a shorter method for performing the "move" with nested rather than aggregated conditional operation.
Golfed code:
```
using C=System.Console;class P{static void Main(){var S=C.In.ReadToEnd().Replace("\r","");int W=S.IndexOf('\n')+1,l=S.Length,i=l,d,m,n;var M=new int[l];for(char c;i-->0;)for(d="^<v>".IndexOf(c=S[m=i]);c>14&d>-1;d=(m+=d==2?W:d>0?d-2:-W)>=0&m<l&&"@^<v>".IndexOf(c=S[m])<0?d:-1)for(d=c==47?3-d:c==92?d^1:d,M[n=m]=1;c%49<9&&(m=S.IndexOf(c,m+1))==n|m<0;);for(;l-->0;)W*=S[l]==42?M[l]:1;C.WriteLine(W>0);}}
```
Less golfed code:
```
using C=System.Console;
class P
{
static void Main()
{
var S=C.In.ReadToEnd().Replace("\r",""); // read the grid, remove pesky carriage returns
int W=S.IndexOf('\n')+1,l=S.Length,i=l,d,m,n; // find "width"
var M=new int[l]; // defaults to 0s
for(char c;i-->0;) // for each cell
for(d="^<v>".IndexOf(c=S[m=i]); // find initial direction, if any
c>14&d>-1; // loop only if we have direction
d=(m+=d==2?W:d>0?d-2:-W) // move (after iteration)
>=0&m<l&&"@^<v>".IndexOf(c=S[m])<0?d:-1) // terminate if we hit something or go off edge
for(d=c==47?3-d:c==92?d^1:d, // mirrors
M[n=m]=1; // we have seen this spot
c%49<9&&(m=S.IndexOf(c,m+1))==n|m<0;); // portals
for(;l-->0;) // for each cell
W*=S[l]==42?M[l]:1; // if *, then mul by whether seen
C.WriteLine(W>0);
}
}
```
The new portal handling code utilizes the fact that the String.IndexOf function happily returns -1 (i.e. char not found) if you ask it start looking 1 character beyond the string (throws an exception if you ask it to start any further beyond). This was news to me, but was awfully convenient in this instance.
] |
[Question]
[
[Part 2 of the challenge is here](https://codegolf.stackexchange.com/questions/196335/country-name-mashup-generator)
[Flags Mashup Bot](https://twitter.com/flagsmashupbot) is a small Twitter bot that generates a new flag based on two random flags and tweets the result every couple of minutes.
## Task
Your task is to replicate what the bot does by writing a script or a function based on the following criteria:
* The input is any two lossless images composed of at least two, but no more than eight colours.
* To mix up the flags the following algorithm has to be used:
+ Take the first image
+ For every colour in the first image assign a colour randomly from the second image
+ Each colour from the second image has to be used at least once
- Unless there are less colours in the first image than colours in the second.
- You can choose randomly which colours to drop from the second image in this case.
+ Each colour from the first image has to be replaced with a different colour
- Unless there are not enough colours in the second image.
- You can choose randomly which colours will be used multiple times in this case.
- However you need to make sure none of the colours are used more than any other colour by more than one
- example: if you need to assign 2 colours to a flag of 5 colours you'll need to use one of the colour 3 times, while the other one 2 times. You cannot mix them 1 & 4
+ If a colour is present in both images you cannot assign that colour with itself you'll need to pick another one
* The output is the resulting image
## Examples
**UK & Hungary**
[](https://i.stack.imgur.com/nQEaU.png)
Notes: Both flags have three colours, however both use red and white, so those have to be replaced, hence the first invalid example. The second one doesn't use all three colours, and the third one uses non-existent colours.
**South Africa & Sweden**
[](https://i.stack.imgur.com/FvaXp.png)
Notes: South Africa's flag has 6 colours, while Sweden's have 2, meaning each of the two colours have to be used exactly 3 times. The invalid ones use the colours in a way which is not compatible with this constraint. Note that although both flags use the colour yellow they are actually not the same shade so are considered different
**Poland & Poland**
[](https://i.stack.imgur.com/gE02M.png)
Notes: The only valid solution is switching up the two colours.
## Notes
* The two images don't need to have the same dimensions
* The colour list can be different for the two images, so in total there might be 16 colours
* The input can be either a lossless image file (example GIF, PNG, BMP, SVG, etc.), or (especially in case of functions) a two dimensional bitmap array holding the colours of the image in any reasonable format. Any native way of storing a bitmap in your language is also fine.
* For both input and output images a two dimensional array holding ASCII characters, where different characters count as different colours, counts as a reasonable format, but solutions that work on "real" bitmaps are preferred
* The output and input formats don't need to match
* I think the colour replacement rules won't prohibit it to work for any valid two input images, but if yes your program doesn't need to work for them
* Colours are considered the same only if they are exactly the same based on their RGB value. E.g. `#FF0000` and `#FF0001` are considered two different colours.
* Standard loopholes, as usual, are prohibited
[code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code by byte count wins and will be accepted. If possible please include example a set of input & output images with your submission
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~160~~ 159 bytes
I/O format: matrix of 24-bit integers.
Takes input as `(a)(b)`.
```
a=>F=b=>(g=a=>[...new Set(a.flat())].sort(_=>Math.random()-.5))(a).every((c,i)=>c^=F[c]=B[i%B.length],B=g(b).slice(-g(a).length))?a.map(r=>r.map(c=>F[c])):F(b)
```
[Try it online!](https://tio.run/##vZLPS8MwFMfv@ytykb0H3aMe3EFIhQm5eRqeSpW3LO0qXVPSMPWvr@mqbFM22FBzCB/yvu9H8s0Lb7jVrmz8pLZL0@WyY5kouZAJFDJgSkS1eRVz44Epr9gDYkatdR6eZfLAfkWO66VdA07oBhEYyWyMewfQUYky0U9SpTqTs7S8mlFl6sKvsmgmC1ggtVWpDUyKPmsIId4xrbkBJxO3BR0GCgUQb1VI6bStW1sZqmwBIyFySMMuRBq/xWEpFYlDUiqOd5RFl6mV@orsU5@5ozPVQZzhbvr@dJjiOx3W/anp177maJ1tx7AN7ytkIj5fuEdN3s69K@sCrqdIDS/nnoPL00iM4zGG6GPTGHfPrQlfAEc4Ou7Ef93ldMdTbp6n/hvvf82J7gM "JavaScript (Node.js) – Try It Online")
### Commented
**Helper function**
The helper function \$g\$ takes a matrix as input and returns a shuffled list of the distinct values it holds.
```
g = a =>
[...new Set(a.flat())]
.sort(_ => Math.random() - .5)
```
**Main code**
```
a => F = b => // a[] = first image, b[] = second image
g(a).every((c, i) => // for each color c at position i in the list of shuffled
// colors of the first image:
c ^= // make sure that c is different from the
F[c] = B[i % B.length], // substitute color F[c] picked from the second image
B = // define B[] as:
g(b) // the list of shuffled colors from the second image
.slice(-g(a).length) // resized to the number of colors in the first image
) ? // end of every(); if truthy:
a.map(r => // return a[] with each original color
r.map(c => F[c]) // replaced with its substitute color
) //
: // else:
F(b) // try again
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~40~~ 25 bytes
```
FQ),ṁ@¥/Ẋ€⁺ZE€ẸƊ¿iⱮⱮ@ịƭƒḢ
```
[Try it online!](https://tio.run/##7dfBSgMxEAbg@76JENBtX6AXvXtU6bEHpS/gsb0I9eYjCN5U8NauB6HCvkf2RdINpcbdnSQzqdil/Eyh0E0mH0vSzNxNptN7Yy4uT5RezUbrl1NdLKr5azUrrs/rb10sy8X667b6eK8/I/35WL6VT3r5bL4froy5yerI1aAVZ9HYjst/hWymmzsYK0twKbiMNEJneRuW0PqJxZATyOUdgXwUTCojeJffESJDyMR8QjT3lsAamkBg5XQEGSNOYOdqEvhTwwTRG@0SeCn8BPG@ogkcBk1IOF3uUKaEjyAKEHaEXB00QAChZwT8L/SEEL6mQldPjNB@5r2m5MtzLms2w1@yhFPwShYWgy7c4lP5hVs0V7d85b1AWfkazNks4vnbSF7Ee3N3DyVrFye2MoGGTrb8fg0d2dZKl9@/rW0w6Lb2P5r7H8Y4swhc2CCAAAIIR9hL/EmAAAIIIPSUMFQHDRBAAAEEEEhCZmMD "Jelly – Try It Online")
A monadic link taking a list of two flags as integer matrices and returning the altered version of the first flag. At the moment this assumes there are indexed colours representing each pixel. I've also assumed that each flag can have arbitrary colours.
[Answer]
# [Python 2](https://docs.python.org/2/), 196 bytes
Takes input as two lists of lists, where different elements represent different colors. Anything can be used to represent color: number, hex, string, etc.
```
from random import*
P=input()
i,j=(list(set(sum(x,[])))for x in P)
d={0:0}
while any(i==d[i]for i in d):y=[];exec'y+=sample(j,len(j));'*len(i);d=dict(zip(i,y))
print[[d[c]for c in r]for r in P[0]]
```
[Try it online!](https://tio.run/##JY0xT8MwEIX3/ApvtssNIWyNvJR2A1IJFnTyUMWuelHiWI4rEhC/PThGT6f36d7TnV/ibXTVul7DOLBwcSYZDX4McVecFTl/j0IWBJ0SPU1RTDbNfRAzoJZSXsfAZkaOnWVh1E@5L3@Lrxv1ll3cIkgpg6S3Em0lI/eLQl3b2bZ8eVDTZfC9FR301olOyprvNiJZG2WojeKbvCBYpCx8IBcRDbb5XLudCxlDfo@l1uuKWEKWBnyErEQVZCV6gqxEZcqqRBoYY4j8vXk98bTnh@b4yYE3b8@nZB/NyzHZf5Ze/AE "Python 2 – Try It Online")
---
Explanation:
```
# get unique elements from input
P=input()
i,j=(list(set(sum(x,[])))for x in P)
# create dictionary, where colors of first image are keys and colors of second image are values
d={0:0}
# keep creating while no color is paired with same color
while any(i==d[i]for i in d):
y=[]
# sum different samples of substitution colors to keep random
# and to make sure none of the colors are used more than any other color by more than one
# *len(i) is to ensure that we have enough values to match
exec'y+=sample(j,len(j));'*len(i)
d=dict(zip(i,y))
# substitute colors and output result
print[[d[c]for c in r]for r in P[0]]
```
[Answer]
# [Perl 5](https://www.perl.org/), ~~170~~ 168 bytes
```
sub f{($a,$b,$e)=map[uniq(/./g)],@_;%n=map{($_,0)}@$b;%s=map{$c=$$b[rand@$b];$e+=/$c/;$n{$c}++;($_,$c)}@$a;@v=values%n;max(@v)-min(@v)>1||$e?f(@_):$_[0]=~s,.,$s{$&},gr}
```
[Try it online!](https://tio.run/##zZNRa9swEMff8ylunpJKsyrbgZYuwpspjL5sL4FhRhqC7MiON1t2rThNSLyPXld2NhiFscdVLyfd/aW7H7qrZJ1fdZ1uIkiOGAmKIook8QtRLRqVPWCHOSlZ0mDFx6r3GtGKuqQNUMTHevCg2EcoWtRCrY13yZG0fQfFDkfKxFrb5v0dFPeXBA92/k7kjdRjxQuxx8GOXBaZ6u0H73RC8mOCgxWZodXCXfo/NWUU6SOatDSt2073WbBH@Cgpa@wxNnXJcQRmFQeMklykHh3MlPhpLaujw5gzmbxxMCPs3b3nnE61XJdtX/f3MlMXF9RsId7U@PrKPj9@TQh1GRsON6Ttk/AhxcsED4/4Lpx/u43g04FAlgBa@b53w@GtLpvtBkRSZ7GACehHuZYK5F4UVS7hf66/gczDW5iHd8REf4O8NyDND1P@plGpqA@vov5/goRzCOdkkPwCmboGpCpz85@vC@EPkOIAgfaHiev7MXkBRk0Teq7rknMjVnWmtmANEv@shEF4PkwhOC5cO9DLFnSZN9usVHoGFus7Hltg0UATZt0ri4/a7qmsBkF3@eVzprez2ddtlg@lUDOXZjz2zw "Perl 5 – Try It Online")
With spaces, newlines, `my`'s, comments and a small test script added:
```
sub f{
my($a,$b,$e)=map[uniq(/./g)],@_; #$a and $b are now arrayrefs to the unique
# colors in each flag
my %n=map{($_,0)}@$b; #init %n with 0 values for each col in flag2
my %s=map{ #%s becomes a suggested swap hash
$c=$$b[rand@$b]; #draw random color from flag2
$e += /$c/; #short for: $error=true if $_ eq $c
$n{$c}++; #count usages of each flag2 color
($_,$c) #suggest swap this col in flag1 with random
# col in flag2
}
@$a;
my @v=values%n;
max(@v)-min(@v)>1 #no more than one more usages of each flag2 color
|| $e #cannot swap with itself
? f(@_) #retry if %s don't passes
: $_[0]=~s,.,$s{$&},gr #swap colors with %s if %s passes the demands
}
srand(1);
for(1..20){
my($flag1,$flag2)=
grep{/../&&!/(.).*\1/||redo}
map{join'',map chr(65+rand(16)),0..rand(8)}
1..2;
($flag1,$flag2)=qw(GWRYBb Ey) if $_==18; #south africa & sweden example
($flag1,$flag2)=qw(RWB RWG) if $_==19; #uk & hungary example
($flag1,$flag2)=qw(WR WR) if $_==20; #poland example
my @s=uniq(map f($flag1,$flag2),1..1000);
print "flag1=$flag1 flag2=$flag2 @{[0+@s]} solutions: ".join(" ",@s)."\n";
}
use List::Util qw(uniq min max);
```
The image format consists of up to sixteen different capital letters A-P for each pixel. The letter represents a color in a color map (like in gifs). Max eight unique colors in each flag. The `f`unction returns the first argument ($a) where each letter is (potentially) swapped with a letter in the second argument ($b) through the swap hash `%s`. The `%n` hash is used to count the number of colers each swapped in color is used for and the least frequent (can be zero) shouldn't be less than one below the max frequency. Also `$e` (error) becomes true if `f` attempts to swap a color with itself in which case `f` is also run again.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 70 bytes
```
WS⟦ι⟧WΦKA¬№υκ⊞υ‽ι≔υθ≔⟦⟧ηWSFιF¬№ηκ⊞ηκW⊙υ⁼κ§θλ«≔⟦⟧θWΦη¬№θλ⊞θ‽κ»UMKA§θ⌕υι
```
[Try it online!](https://tio.run/##7VDBagMhED3HrxjIRYv5gtDDEhrIoSU0x5CDJDbKuprd1bSl9Nut7pZdGwh4XehD0BnfvDczR8Gao2HK@3chFQe80Rdnd7aR@owJgW14WLyXB7JEv4y1VJY3eMt5WSiFCYUXY/HKuEB0FEpCYp1rRYxemT6ZCksS6ou2lWcds/UY7Q8UxCh@Y/9mGgjF/T3aiN6md@mCQaDQn9HhqXZMtbikUNiNPvEPXFNQXWtfaJZ4x1ZmfycT6URDWedVDxOVcaJv9MwuK1NVIZcuJPFcy/AVGgobIEvvHwDSM78LBDfUu0D/mlmauUDzXExGEy1yMRlm/pqmwnzMxWSYfnFVPw "Charcoal – Try It Online") Link is to verbose version of code. Takes input as character arrays, where different characters represent different colours. For the link I've rendered two flags in ASCII art. Explanation:
```
WS⟦ι⟧
```
Input and print the first character array.
```
WΦKA¬№υκ⊞υ‽ι
```
Randomly extract the distinct characters into a list.
```
≔υθ
```
Make a temporary copy of the list. This copy will be replaced by a shuffle of the transliteration characters.
```
≔⟦⟧η
```
Create a second list. (The first list was automatically predefined by Charcoal.)
```
WSFιF¬№ηκ⊞ηκ
```
Input the second character array and extract the unique characters to the second list.
```
W⊙υ⁼κ§θλ«
```
Repeat while at least one character in the first list maps to a character in the second list. The mapping is cyclic, so that once all of the colours run out, they are reused again in the same order, thus ensuring that no colour is used an unbalanced number of times.
```
≔⟦⟧θWΦη¬№θλ⊞θ‽κ
```
Shuffle the unique characters from the second list.
```
»UMKA§θ⌕υι
```
Once a distinct shuffle has been found, transliterate the whole canvas from the first to the second list.
] |
[Question]
[
This question is inspired by, and is the inverse of [this one](https://codegolf.stackexchange.com/questions/55574/dennis-doorknob-martin-b%c3%bcttner-chris-jester-young-pizzeria).
Dennis (`E`), Doorknob (`D`), Martin (`M`) and Chris (`C`) have ordered a pizza. The rectangular pizza is divided into square pieces, each marked with their intended eater.
Write a program or function that given a **rectangular** pizza consisting of 0 or more of each letter determines whether:
1. Each slice for each person is [path-connected](https://en.wikipedia.org/wiki/Connected_space#Path_connectedness). This means that all letters that are the same should be directly adjacent to eachother (no diagonal connections).
2. The number of slices per person is the same for all.
You must output a truthy/falsy value with an optional trailing newline that indicates whether or not the given pizza is fair.
### Valid testcases:
```
DDDDDDDDDDDDMCCCCCCCCCCC
DEEEEEEEEEEDMMMMMMMCCCCC
DEEEEEEEEEEDMMMCCCCCCCCC
DEEEEEEEEEEDMMMMMMMMCCCC
DDDDDDDDDDDDMMMMMMMMMMMC
```
```
DEMC
```
```
DD
EE
MC
MC
```
```
EEDDMMMCCC
EEEDDDMMCC
```
### Invalid testcases:
```
EDM
```
```
EDMCCMDE
```
```
DDDDDDDDDDDDMCCCCCCCCCCC
DEEEEEEEEEEDMMMMMMMCCCCC
DEEEEEEEEEEMDMMCCCCCCCCC
DEEEEEEEEEEDMMMMMMMMCCCC
DDDDDDDDDDDDMMMMMMMMMMMC
```
```
DDMMEECC
DMMEECCC
```
---
Shortest code in bytes wins.
[Answer]
# [Snails](https://github.com/feresum/pma), 129
Prints 1 for a fair pizza and 0 for an unfair pizza.
```
&
={(t\Dt\Et\Ct\M),!(t.}{(o\D)+l^D,=~u{^D=(r^D,~},~|o\E`+l^E,=~u{^E=(r^E,~},~|o\C`+l^C,=~u{^C=(r^C,~},~|o\M`+l^M,=~u{^M=(r^M,~},~
```
Expanded version:
```
&
={ (t\Dt\Et\Ct\M), !(t.)} {
(o\D)+ l^D,=~ u{^D=(r^D,~)}, ~ |
(o\E)+ l^E,=~ u{^E=(r^E,~)}, ~ |
(o\C)+ l^C,=~ u{^C=(r^C,~)}, ~ |
(o\M)+ l^M,=~ u{^M=(r^M,~)}, ~
```
`&` means that the pattern must match at all locations on the grid. The first line checks for an equal number of each of E, D, M, C. it uses the teleport instruction `t`, which is a great way to make programs with factorial complexity. If an input has unequally sized slices with several units for each of the 4 mods, the program will more or less hang forever. After that, there is a check for a contiguous path to the top-left instance of whichever letter the pattern started on.
[Answer]
# CJam, 93
```
qN/_z,:W;s:A,,:B_{{{_B=_@-}g}%$}:F;{a+_Af=)#{F~B\@t:B}|;}:U;W>{_W-U}/{W%},{_(U}/BFe`0f=_1<4*=
```
[Try it online](http://cjam.aditsu.net/#code=qN%2F_z%2C%3AW%3Bs%3AA%2C%2C%3AB_%7B%7B%7B_B%3D_%40-%7Dg%7D%25%24%7D%3AF%3B%7Ba%2B_Af%3D)%23%7BF~B%5C%40t%3AB%7D%7C%3B%7D%3AU%3BW%3E%7B_W-U%7D%2F%7BW%25%7D%2C%7B_(U%7D%2FBFe%600f%3D_1%3C4*%3D&input=DDDDDDDDDDDDMCCCCCCCCCCC%0ADEEEEEEEEEEDMMMMMMMCCCCC%0ADEEEEEEEEEEDMMMCCCCCCCCC%0ADEEEEEEEEEEDMMMMMMMMCCCC%0ADDDDDDDDDDDDMMMMMMMMMMMC)
This is ridiculously long because CJam doesn't (yet) have built-in flood-fill or union-find. I implemented [union-find](https://en.wikipedia.org/wiki/Disjoint-set_data_structure) in the program.
**Explanation:**
```
qN/_ read input, split into lines and duplicate
z,:W; transpose, get length (original width) and store in W
s:A convert to string (without newlines) and store in A
,, make an array [0..n-1] (n = pizza size)
:B_ store in B (initial structure) and duplicate (will be used in 2 loops)
{…}:F; define function F ("Find" for multiple indices and sort)
{…}% for each value (x)
{…}g do…while
_B= duplicate x and get B[x]
_@- leave a B[x] on the stack and calculate B[x] - x
if non-zero, repeat the loop with B[x]
$ sort the results
{…}:U; define function U ("Union" for 2 indices)
a+ make an array of the 2 indices
_Af= get the corresponding letters from A
)# check if the letters are different
{…}| if not, execute…
F~ call F on the array and dump the 2 results on the stack
B\@t join the sets - B[bigger index] = smaller index
:B store back in B
; pop the last value (either array if indices or B)
W> remove the first row of indices
{…}/ for each index
_W- duplicate and subtract W ("go up")
U call U to join sets if they match
{W%}, remove the first column of indices
{…}/ for each index
_( duplicate and decrement ("go left")
U call U to join sets if they match
BF call F on B, to get the final sets and sort
e` RLE encoding
0f= keep only the repetition counts
_1<4*= check if it's the first value (if any) repeated 4 times
```
[Answer]
# Pyth, 53 bytes
```
!f-lJs.z*4lu&G{smfqT@JY@UJ+Ld[Z1_1Klh.z_K)G]xJT)"CDEM
```
[Demonstration](https://pyth.herokuapp.com/?code=!f-lJs.z*4lu%26G%7BsmfqT%40JY%40UJ%2BLd%5BZ1_1Klh.z_K)G%5DxJT)%22CDEM&input=DDDDDDDDDDDDMCCCCCCCCCCC%0ADEEEEEEEEEEDMMMMMMMCCCCC%0ADEEEEEEEEEEDMMMCCCCCCCCC%0ADEEEEEEEEEEDMMMMMMMMCCCC%0ADDDDDDDDDDDDMMMMMMMMMMMC&debug=0).)
This is essentially a flood fill for each letter, followed by a check that all of the resulting sets are of the appropriate size.
To flood-fill, it starts with the upper-left-most occurence of each letter, then generates all neighbors of locations found so far, filters for locations with the right letter, and repeats until the set stops changing.
[Answer]
# JavaScript (ES6), 153 ~~166~~
Using template strings, there is a newline that is significant and counted
Test running the snippet in FireFox.
```
f=z=>![...'CDEM'].some(c=>((l=p=>z[p]==c&&[-1,1,w,-w].map(o=>l(p+o),z[p]='',++k))(z.indexOf(c),h=k,k=0),~h&&h-k),w=~z.search`
`,z=[...z],k=-1)&z.join``-1
// Ungolfed
U=z=>{
w = ~z.search`\n`
z = [...z]
fill = p=>(
c = z[p],
z[p] = '',
[-1,1,w,-w].forEach(o=>z[o+=p] == c && fill(o)),
++k
)
h = -1
r = ['C','D','E','M'].every( c =>(
k = 0,
y = z.indexOf(c),
y >= 0 && fill(y),
v = h >= 0 ? h == k : true,
h = k,
v
))
return r & 1-z.join``
}
// Test
out=x=>O.innerHTML+=x+'\n';
// Valid test cases
valid=[`DDDDDDDDDDDDMCCCCCCCCCCC
DEEEEEEEEEEDMMMMMMMCCCCC
DEEEEEEEEEEDMMMCCCCCCCCC
DEEEEEEEEEEDMMMMMMMMCCCC
DDDDDDDDDDDDMMMMMMMMMMMC`,
`DEMC`,
`DD
EE
MC
MC`,
`EEDDMMMCCC
EEEDDDMMCC`];
out('Valid')
valid.forEach(t=>out(t+'\n'+f(t)+'\n'));
invalid=[`EDM`,
`EDMCCMDE`,
`DDDDDDDDDDDDDD`,
`DDDDDDDDDDDDMCCCCCCCCCCC
DEEEEEEEEEEDMMMMMMMCCCCC
DEEEEEEEEEEMDMMCCCCCCCCC
DEEEEEEEEEEDMMMMMMMMCCCC
DDDDDDDDDDDDMMMMMMMMMMMC`,
`DDMMEECC
DMMEECCC`
];
out('Invalid')
invalid.forEach(t=>out(t+'\n'+f(t)+'\n'))
```
```
<pre id=O></pre>
```
[Answer]
# Javascript ES6, 360
Checks for equal numbers of C, D, E, M, then flood fills and checks for any orphaned letters. Not a winner, but I had to try.
```
i=>(I=i.split`
`.map(e=>e.split``),c=(i[m='match'](/C/g)||[])[l='length'],a=(x,y,z)=>{if(I[x][y]!=z)return;I[x][y]=0;x>0&&a(x-1,y,z);x<I[l]-1&&a(x+1,y,z);y>0&&a(x,y-1,z);y<I[0][l]-1&&a(x,y+1,z)},![...'CDEM'].some(k=>{if((i[m](eval(`/${k}/g`))||[])[l]!=c)return 1;I.some((w,x)=>(g=-1<(y=w.indexOf(k)),g&&a(x,y,k),g));})&&!I.map(e=>e.join``).join``[m](/[CDEM]/))
```
[Fiddle](http://jsfiddle.net/4k78vo1d/7/)
[Answer]
# JavaScript ES6, ~~328~~ ~~318~~ ~~316~~ ~~269~~ 178
```
l=>(d=[0,0,0,0],s=[...l.split`
`.join``].map(i=>(d["EDMC".search(i)]++,i)),!l||d.every(i=>i==d[0])&&(s.every((r,i)=>[1,-1,X=l.split`
`[0].length,-X].some(o=>s[o+i]==r))||d[0]<2))
```
Explanation:
```
l => (
d = [0,0,0,0], // array containing each letter count
s = [...l.split`
`.join``] // removes newlines from input and converts it into array
.map(i => ( // loops through the array
d["EDMC".search(i)]++ // increases letter count
,i)), // returns unchanged value in order to preserve original array
!l // input is empty
|| d.every(i=>i==d[0]) // each letter count is equal
&& (
s.every((r, i) => // there is no orphaned letters
[1,-1,X=l.split`
`[0].length,-X] // letters on respectively: right, left, bottom, top
.some // at least one of them
(o=>s[o+i]==r)) // equals original letter
|| d[0] < 2 // count of each letter equals 1
)
)
```
] |
[Question]
[
Write a regular expression which matches a given string consisting of three non-negative, space-separated integers if and only if the last integer is the sum of the previous two. Answers may be for integers of any numeral system with radix between 2 and 10.
## Test cases
These should fail:
```
0 1 2
10 20 1000
```
These should match:
```
10 20 30
28657 46368 75025
0 0 0
```
## Rules
Your answer should consist of a single regex, without any additional code (except, optionally, a list of regex modifiers required to make your solution work). You must not use features of your language's regex flavour that allow you to invoke code in the hosting language (e.g. Perl's e modifier).
Please specify your regex flavour in your answer.
This is regex golf, so the shortest regex in bytes wins. If your language requires delimiters (usually /.../) to denote regular expressions, don't count the delimiters themselves. If your solution requires modifiers, add one byte per modifier.
Credits to [Martin Ender](https://codegolf.stackexchange.com/users/8478/martin-ender) and [jaytea](https://codegolf.stackexchange.com/users/75057/jaytea) for the regex-golfing rules.
---
I have reason to believe it's possible based on the solution of Martin Ender for [finding and incrementing integers with regex](https://stackoverflow.com/questions/12941362/).
[Answer]
## Perl/PCRE: 2,685 bytes
```
^(?!(?!0*+(?=(\d*?)((?:(?=\d+ 0*+(\d*?)(\d(?(4)\4)) 0*(\d*?)(\d\6?+)$)\d)+) )(?=(?(?!\1(?:(?=\d+ 0*\3((\7?+)\d))(?=\d(\d* 0*\3\8))(?=0\9[9]|1\9[8]|2\9[7]|3\9[6]|4\9[5]|5\9[4]|6\9[3]|7\9[2]|8\9[1]|9\9[0])\d)*+(?=\d(\d* 0*\3\8?+))(?=[5-9]\10[5-9]|1\10[9]|2\10[89]|3\10[7-9]|4\10[6-9]|6\10[4]|7\10[34]|8\10[2-4]|9\10[1-4]))(?=\d+ \d+ 0*\1\3\6$)|(?(?!.*+\3)\d+ )(?=\d*(\2|\4)( .*?0*+)\d+$)(?(?=9*\11 )(?:9(?=\d*\12[1](\13?+0)))*?(?=\11 )\11\12[1]\13?+\6$|(?:(\d)(?=\d*\12(\15?+\14)))*(?=\d(\d*\12\15?+))(?=0\16[1]|1\16[2]|2\16[3]|3\16[4]|4\16[5]|5\16[6]|6\16[7]|7\16[8]|8\16[9])\d(?:9(?=\d*\12\15?+\d(\17?+0)))*?\11\12\15?+\d\17?+\6$)))\1(?:(?=(\d)\d* 0*+\3((\19?+)\d)\d* 0*+\5((\21?+)\d))(?=\d(\d* 0*+\3\20)\d(\d* 0*+\5\22))(?(?!\18(?:(?=\d+ 0*+\3\19((\25?+)\d))(?=\d(\d* 0*+\3\19\26))(?=0\27[9]|1\27[8]|2\27[7]|3\27[6]|4\27[5]|5\27[4]|6\27[3]|7\27[2]|8\27[1]|9\27[0])\d)*+(?=\d(\d* 0*+\3\19\26?+))(?=[5-9]\28[5-9]|1\28[9]|2\28[89]|3\28[7-9]|4\28[6-9]|6\28[4]|7\28[34]|8\28[2-4]|9\28[1-4]))(?=1\23(?:1\24[2]|2\24[3]|3\24[4]|4\24[5]|5\24[6]|6\24[7]|7\24[8]|8\24[9]|9\24[0])|2\23(?:1\24[3]|2\24[4]|3\24[5]|4\24[6]|5\24[7]|6\24[8]|7\24[9]|8\24[0]|9\24[1])|3\23(?:1\24[4]|2\24[5]|3\24[6]|4\24[7]|5\24[8]|6\24[9]|7\24[0]|8\24[1]|9\24[2])|4\23(?:1\24[5]|2\24[6]|3\24[7]|4\24[8]|5\24[9]|6\24[0]|7\24[1]|8\24[2]|9\24[3])|5\23(?:1\24[6]|2\24[7]|3\24[8]|4\24[9]|5\24[0]|6\24[1]|7\24[2]|8\24[3]|9\24[4])|6\23(?:1\24[7]|2\24[8]|3\24[9]|4\24[0]|5\24[1]|6\24[2]|7\24[3]|8\24[4]|9\24[5])|7\23(?:1\24[8]|2\24[9]|3\24[0]|4\24[1]|5\24[2]|6\24[3]|7\24[4]|8\24[5]|9\24[6])|8\23(?:1\24[9]|2\24[0]|3\24[1]|4\24[2]|5\24[3]|6\24[4]|7\24[5]|8\24[6]|9\24[7])|9\23(?:1\24[0]|2\24[1]|3\24[2]|4\24[3]|5\24[4]|6\24[5]|7\24[6]|8\24[7]|9\24[8])|0\23(\d)\24\29|(\d)\23[0]\24\30)|(?=1\23(?:0\24[2]|1\24[3]|2\24[4]|3\24[5]|4\24[6]|5\24[7]|6\24[8]|7\24[9]|8\24[0]|9\24[1])|2\23(?:0\24[3]|1\24[4]|2\24[5]|3\24[6]|4\24[7]|5\24[8]|6\24[9]|7\24[0]|8\24[1]|9\24[2])|3\23(?:0\24[4]|1\24[5]|2\24[6]|3\24[7]|4\24[8]|5\24[9]|6\24[0]|7\24[1]|8\24[2]|9\24[3])|4\23(?:0\24[5]|1\24[6]|2\24[7]|3\24[8]|4\24[9]|5\24[0]|6\24[1]|7\24[2]|8\24[3]|9\24[4])|5\23(?:0\24[6]|1\24[7]|2\24[8]|3\24[9]|4\24[0]|5\24[1]|6\24[2]|7\24[3]|8\24[4]|9\24[5])|6\23(?:0\24[7]|1\24[8]|2\24[9]|3\24[0]|4\24[1]|5\24[2]|6\24[3]|7\24[4]|8\24[5]|9\24[6])|7\23(?:0\24[8]|1\24[9]|2\24[0]|3\24[1]|4\24[2]|5\24[3]|6\24[4]|7\24[5]|8\24[6]|9\24[7])|8\23(?:0\24[9]|1\24[0]|2\24[1]|3\24[2]|4\24[3]|5\24[4]|6\24[5]|7\24[6]|8\24[7]|9\24[8])|9\23(?:0\24[0]|1\24[1]|2\24[2]|3\24[3]|4\24[4]|5\24[5]|6\24[6]|7\24[7]|8\24[8]|9\24[9])|0\23(?:0\24[1]|1\24[2]|2\24[3]|3\24[4]|4\24[5]|5\24[6]|6\24[7]|7\24[8]|8\24[9]|9\24[0])))\d)+\ |^0+\ 0*(\d+)\ 0*\g{-1}$|^0*(\d+)\ 0+\ 0*\g{-1}$)).+
```
[Try it online!](https://regex101.com/r/1ZYSOg/1)
I've been on the prowl for difficult challenges after a hiatus from regex, and just happened to stumble across this doozy. Verifying addition (with Perl/PCRE) is something I've thought about before, but promptly dismissed as either impossible or beyond my ability. However, I took another crack at it now and I'm quite thrilled to say that I've actually done it!
I didn't really golf this other than considering short algorithms and overall matching technique when I wrote it. I'm just really happy I got it done :D
If people are interested, I could add comments and explain how it works.
Edit: I made a detailed post on my blog about this, with explanations and comments :) enjoy: <http://www.drregex.com/2018/09/a-regex-i-submitted-to-reddit-climbed.html>
[Answer]
## .NET flavour, ~~139~~ ~~111~~ 106 + 1 = 107 bytes
Needs the `RightToLeft` modifier `r`. Input in binary.
```
(?(2)!)^\5 \7 ((?(2)()(?(2)!)(?<-2>){2})(0|(?<-2>1))(?<=(((0|(?<2>1)|\b)(?=.*(?<=(\5).*))?\7?) \d*){2}))+$
```
[Try it online!](https://tio.run/##bVDNCsIwDL73KSIoJBNHOhi7OHv0JYpM0YMXD@LN@ey1STomw461yfeT7tvz9ro/zmmDxyE9BwzY0IpOsYXYAWqLVFAM@11zoHfzIeTROk8C94iGCDDGS8b6ulIitlRXRCF2gSBeK7XTdp0SgwfPzudTCqmkzpsgeUnFTmVLLotV4KVjFUI5M@iUsiWAGMU7KSat3aCvM6UvN4sdCikq520M20SdPre6uT/sUsKQn3kWmO8nicWUBJJaf8oUWr972ZfwKucv "Retina – Try It Online") (Using [Retina](https://github.com/m-ender/retina).)
Yay for balancing groups. I'll explain this later...
### Decimal version, ~~340~~ 243 + 1 = 244 bytes
```
(?(2)!)^\5 \7 ((?(2)()(?(2)!)(?<-2>){10})(0|(?<-2>1|(?<-2>2|(?<-2>3|(?<-2>4|(?<-2>5|(?<-2>6|(?<-2>7|(?<-2>8|(?<-2>9))))))))))(?<=(((0|(?<2>1|(?<2>2|(?<2>3|(?<2>4|(?<2>5|(?<2>6|(?<2>7|(?<2>8|(?<2>9)))))))))|\b)(?=.*(?<=(\5).*))?\7?) \d*){2}))+$
```
[Try it online!](https://tio.run/##TY3LTgMxDEX3@QojgWRPReU4b4kyS34iQgXBgg2Lqru23z54MgaRKDq518rJ6fP89f22PODLcTkdcUahO3rtCXoBHBHJWpyfHuWZLp5vhHzdojeKMRijMRmzsRirsdHf0uKAuJlNbF7TmtWk5jSlGf8Lr/1dnYf9NMQ90X4imnuZCfrHRBe5Ee3ul4XBgziBANF5BtHMzG6tvRWBnRedpwypNCc1pwIxh1yhJJbkWoOmx3OrblzbkGhYr7@BQfc6hzp8EiIU59ePxCWBWHW8UR/8AA "Retina – Try It Online")
[Answer]
# .NET, 96 bytes
```
^\4 \6((?(2)()(?(2)^)(?<-2>){2}| ?)(0|(?<-2>1))(?<=((0|(?<2>1)|)\4?) .*((0|(?<2>1)|)\6?) .*))+$
```
Flag: `r`
[Try it online!](https://tio.run/##bVAxDsIwDNzzCg8gxSCQXVVMQEc@UVVlYGBhqNgobw85O1WhIlVi@@7s5DrcnvfHNa3jpU9D37U1tYcYm1hxZAtdDsdddeZX9R6p4SijA8pgTtEB1CO3dcO03/xiB8OYt6uUhJRUguaIBBnyfADJC5kEky25LDaBohITUokZDEb5AoBG9E6KSes32A6u1HIz2qmQUAX1MeITbfpc2hH@sEuJUP7mWeR9X07cJhzAtf2UybS9e1kX8yaXDw "Retina – Try It Online")
### Decimal version, 238 bytes
```
^\5 \6(?<-6>)((?(2)()(?(2)^)(?<-2>){10}| ?)((?<-2>[1469]|(?<-2>[27]))|[0358])(?([5-9])(?<-2>){5})(?([3489])(?<-2>){3})(?<=(((((?=[5-9](?<2>){5}|)(?=[3489](?<2>){3}|)((?<2>[1469]|(?<2>[27]))|.))?(?( .*)\6?(?<-6>)?|\5?(?<-5>)))) .*){2}))+$
```
Flag: `r`
[Try it online!](https://tio.run/##TY/BbsMgDIbvPIUPq4Q3tTIGE5DacNxDJKm6ww677FD11uTZM0yzbiCE/@/H/HD9vH19f6w7@35Zr5fzKDBGW4772KO1xTJabNsZlXKPd0fLDEVd1YMLMU/zJribEOeBvKRJ@wbZ5@nZKUtjPqR/0Cs8nqyOcmoNVT@Oz6iond@YV9bqv@Bn7gGx1AA4vOIYy/aLMo/SaumxDjXvvCC@vawrgQM2DB6CcQRcNREZxW4Dnozj6ksE6bLhFKWDEH1M0AmxmJwh1@UoJ9PK3C6pQstfQVCn@pDafewDdMZpEBthCKnaj921F9TwHw "Retina – Try It Online")
Similar to Martin's answer.
] |
[Question]
[
### [Test Driver](https://github.com/Beefster09/pcg-general/blob/master/ruins.py) • [Challenge Discussion](https://chat.stackexchange.com/rooms/92372/adventurers-in-the-ruins) • [Submit Adventurer](https://codegolf.stackexchange.com/questions/183101/adventurers-in-the-ruins#footer)

([Image Source](https://www.creativeuncut.com/gallery-18/dc-treasure-room.html))
Several rival adventurers are raiding the ruins for treasure, but they can only carry so much at a time and have their limits of endurance. They want to get the most valuable treasure and get out before they become too tired to continue. They are trying to become as rich as possible from their looting shenanigans.
# Gameplay
Each adventurer begins in the first room of the dungeon with 1000 stamina points and 50kg of space in their backpack.
The game operates on a turn-based fashion, with all players resolving their turns simultaneously. Each turn, you can do one of the following actions:
* Move to the next room.
* Move to the previous room.
* Bid stamina to take a treasure.
* Drop a treasure.
Moving between rooms requires 10 stamina, plus 1 for every 5kg currently in your backpack, rounded up. For instance, an adventurer carrying 3kg of treasure requires 11 stamina to move and one carrying 47kg requires 20 stamina to move.
Dropping treasure requires 1 stamina regardless of the treasure dropped.
Upon exiting the ruins, no more turns will be taken by the player.
If a player cannot take any of these actions (due to shortage of stamina or absence of treasures), their adventurer dies of exhaustion, spilling their held treasure into the currently occupied room. Similarly, if a player attempts to do an invalid action, their adventurer will be killed by a trap instead, resulting in the same treasure spillage.
## Bidding
The minimum bid for a treasure is 1 stamina per 1kg that the treasure weighs. You may also bid additional stamina points to be more likely to obtain the treasure. The stamina that was bid is consumed no matter what the outcome is.
In the event that multiple players have bid to take the same treasure, the player who bid highest gets the treasure. If more than one player made the highest bid, none of them will receive the treasure.
## Win Condition
The player with the largest total value of treasures is the winner. In the unlikely event of a tie, ties go to the smallest total weight, then smallest number of treasures, then value of the most valuable treasure, second most valuable, third... until the tie is broken. In the near-impossible event that there is still a tie at this point, the test driver says "screw it" and the winner is thereby determined arbitrarily.
In the context of the tournament, players will be ranked with first place receiving 10 points, second place with 9 points, third place with 8 points, etc..., with dead players and adventurers with no treasures scoring 0 points.
# About the Ruins
* Each room initially contains between \$\lfloor{r \over 3}\rfloor + 3\$ and \$\lfloor{r \over 2}\rfloor + 5\$ treasures. (Where \$r\$ is the room number)
* There are arbitrarily many rooms, limited only by adventurers' stamina and willingness to explore.
* Each treasure will have a monetary value (in whole $) and a weight (in whole kg).
+ Treasures tend to be more valuable and plentiful as you go deeper into the ruins.
* The specific formulas for generating treasures are as follows: (using \$xdy\$ notation for dice rolls)
+ Weight is generated first using the formula \$2d6 - 2\$ (minimum of 1)
+ Treasure value then is generated via \$1d[10 \* w] + 2d[5 \* r+ 10]\$ (where \$r\$ is the room number and \$w\$ is the weight)
# Information Visible to Players
At each turn, players get the following information:
* The number of the room they are currently in. This is 1-indexed, so conceptually the exit is at "room 0"
* A list of treasures currently in the room
* A list of other players who are also currently in the room.
* Your current inventory of treasures
* Your current stamina level
# Coding
The test driver can be found [here](https://github.com/Beefster09/pcg-general/blob/master/ruins.py).
You should implement a subclass of this `Adventurer` class:
```
class Adventurer:
def __init__(self, name, random):
self.name = name
self.random = random
def get_action(self, state):
raise NotImplementedError()
def enter_ruins(self):
pass
```
You only need to override the `get_action` method. `enter_ruins` is run before a game begins and is your chance to prepare whatever you wish to have ready for the game. You do not need to override `__init__`, and you really *shouldn't*. If your `__init__` crashes, you will be disqualified.
`get_action` recieves a single argument which is a `namedtuple` with the following fields (in this order, if you prefer destructuring):
* `room`: the number of the room you are currently in
* `treasures`: the list of treasures in the room
* `players`: the list of other players in the room. You only get the player name this way, so you do not know what bot is controlling them or their inventory/stamina.
* `inventory`: the list of treasures in your backpack
* `stamina`: your current stamina level
This object additionally provides two utility properties:
* `carry_weight`: the total weight of all the treasures you are carrying
* `total_value`: the total value of all the treasures you are carrying
The `treasures` and `inventory` lists contain `namedtuple`s with these attributes:
* `name`: the treasure's name (for cosmetic purposes)
* `value`: the monetary value of the treasure in $.
* `weight`: the treasure's weight in kg
`get_action` should return one of the following values/patterns:
* `'next'` or `'previous'` to move to the next/previous rooms
* `'take', <treasure index>, <bid>` (yes, as a tuple, though any sequence will technically work as well) to bid on the treasure at the given index in the room's treasure list. Both arguments should be integers. Floats will be rounded down.
* `'drop', <inventory index>` to drop the carried treasure found at the given index. The index should (naturally) be an integer.
## Other Restrictions
* You may only use the random instance provided to you during initialization for pseudorandomness.
+ Anything else that might introduce behavioral nondeterminism is not allowed. The intent here is to make bots behave identically when given the same seed to aid in testing new bots (and potentially bugs in the test driver). Only cosmic radiation should cause any deviation/nondeterminism.
+ Keep in mind that hash codes are randomized in Python 3, so using `hash` for any decision making is not allowed. `dict`s are fine even when using iteration order for decisions since order has been guaranteed consistent since Python 3.6.
* You may not circumvent the test driver using `ctypes` hacks or `inspect` stack voodoo (or any other method). There are some impressively scary things you can do with those modules. Please don't.
+ Each bot is sandboxed reasonably well via defensive copies and the natural immutability of `namedtuple`s, but there are some unpatchable loopholes/exploits.
+ Other functionality from `inspect` and `ctypes` may be used as long as neither is used to circumvent controller functionality.
+ Any method of grabbing instances of the other bots in your current game is not allowed.
* Bots should operate solo and may not coordinate with any other bots in any way for any purpose. This includes creating two bots with different goals such that one sacrifices itself for the success of the other. Once there are more than 10 competitors, you won't actually be guaranteed to have the two bots in the same game and adventurer names don't give any indication of the bot class, so these types of strategies are limited anyway.
* There is currently no hard restriction on execution time, however I reserve the right to hard-restrict it in the future if tournaments start taking too long. Be reasonable and **try to keep turn processing under 100ms**, as I don't anticipate needing to restrict it below that threshold. (Tournaments will run in about 2 hours if all bots take about 100ms per turn.)
* Your bot class must be named uniquely among all submissions.
* You may not remember anything between games. (However, you *can* remember things between *turns*)
+ Don't edit sys.modules. Anything outside instance variables should be treated as a constant.
* You may not modify any bot's code programmatically, including your own.
+ This includes deleting and restoring your code. This is to make debugging and tournaments more streamlined.
* Any code that causes the controller to crash will be immediately disqualified. While most exceptions will be caught, some may slip through and segfaults are uncatchable. (Yes, you can segfault in Python thanks to `ctypes`)
## Submissions
In order to aid answer scraping, indicate the name of your bot at the top of the answer with a `#Header1` and ensure your answer includes at least one code block (only the first one in your answer will be used). You do not need to include any imports or docstrings, as they will be added automatically by the scraper.
I will be more inclined to upvote answers with detailed and understandable explanations. Others are likely to behave the same.
Roughly speaking, your answer should be formatted something like this:
```
# Name of Bot
Optional blurb
#imports go here
class BotName(Adventurer):
#implementation
Explanation of bot algorithm, credits, etc...
```
(rendered as)
>
> # Name of Bot
>
>
> Optional blurb
>
>
>
> ```
> #imports go here
>
> class BotName(Adventurer):
> #implementation
>
> ```
>
> Explanation of bot algorithm, credits, etc...
>
>
>
## Running the Test Driver Locally
You will need Python 3.7+ and I recommend you also install `tabulate` via pip. Scraping this page for submissions additionally requires `lxml` and `requests`. You should also use a terminal with support for ANSI color escapes for best results. Info on how to set this up in Windows 10 can be [found here](https://superuser.com/a/1300251/465657).
Add your bot to a file in a subdirectory within the same directory as `ruins.py` (`ruins_bots` by default) and be sure to add `from __main__ import Adventurer` to the top of the module. This is added to the modules when the scraper downloads your submission, and while it is definitely hacky, this is the most straightforward way of making sure your bot properly has access to `Adventurer`.
All bots in that directory will be loaded dynamically at runtime, so no further changes are necessary.
# Tournament
The ultimate victor will be determined in a series of games with up to 10 bots in each game. If there are more than 10 total submissions, the top 10 bots will be determined by systematically partitioning them into groups of 10 until every bot has played (exactly) 20 games. The top 10 bots will be selected from this group with reset scores and will play games until the first place bot has achieved a 50 point lead over the second place bot or until 500 games have been played.
Until there are at least 10 submissions, empty slots will be filled with "Drunkards" which wander randomly through the ruins and take (and occasionally drop) random treasures until they run out of stamina and have to beeline to the exit.
Tournaments will be re-run weekly if there are new submissions. This is an open KOTH challenge with no set end date.
# Leaderboard
From run on May 4, 2019 at 4:25PM MDT: (2019-05-04 4:25 -6:00)
```
Seed: K48XMESC
Bot Class | Score | Mean Score
--------------+---------+--------------
BountyHunter | 898 | 7.301
Scoundrel | 847 | 6.886
Accountant | 773 | 6.285
Ponderer | 730 | 5.935
Artyventurer | 707 | 5.748
PlanAhead | 698 | 5.675
Sprinter | 683 | 5.553
Accomodator | 661 | 5.374
Memorizer | 459 | 3.732
Backwards | 296 | 2.407
```
---
Update - Apr 15: a couple rule updates/clarifications
Update - Apr 17: banning a couple of notable edge cases of nefarious actions such as modifying other bots' code.
Update - May 4: Bounty awarded to Sleafar for absolutely destroying Backwards. Congratulations!
[Answer]
# Accountant
```
import math
class Accountant (Adventurer):
def enter_ruins(self):
self.goal = 5000
self.diving = True
def expected_rooms_left(self, state):
if not self.diving:
return state.room
else:
return (state.stamina - (50 - state.carry_weight)) / 14
def ratio(self, state, treasure):
stamina_cost = treasure.weight * (1 + 1/5 * self.expected_rooms_left(state)) + bool(state.players)
ratio = (treasure.value / (self.goal - state.total_value)) / (stamina_cost / state.stamina)
return ratio
def get_action(self, state):
room, treasures, players, inventory, stamina = state
if stamina < room * (math.ceil(state.carry_weight / 5) + 10) + 40:
self.diving = False
return 'previous'
worthwhile = []
for i, treasure in enumerate(treasures):
ratio = self.ratio(state, treasure)
if ratio >= 1 and state.carry_weight + treasure.weight <= 50:
worthwhile.append((ratio, i))
if worthwhile:
ratio, index = sorted(worthwhile, reverse=True)[0]
treasure = treasures[index]
return 'take', index, treasures[index].weight + bool(players)
return 'next'
```
The Accountant is a very risk-averse person. He likes to be sure that what he does really is the best option in the given situation. So, he sets himself a goal, and only ever picks up treasure if his calculations show this sets him on the right track towards that goal. However, he is very bureaucratic and does not like dropping items he had already decided he wanted; any attempts to teach him to do so have so far resulted in the Accountant dropping an item, and then picking it up again immediately afterwards.
Possibly to be continued.
[Answer]
# Accomodator
Based loosly on my other LightWeight bot. Where LightWeight bot was simple, this bot is much more complex in order to *accomodate* interactions with other bots: both benign and deliberatly distruptive.
This bot will firstly sprint to a randomly assigned room and then will try to bid for the best value/weight ratio treasure, if there are any other players in the room then assume that they will also bid so instead bid for the second best treasure. If that bid fails then on the next turn bid for the next best treasure.
Once a bid was successful, repeat bidding for best/secondbest until no more treasures exist in the room then move deeper into the ruin
For each room enter into the ruin repeat bidding for best/secondbest until no more treasures exist in the room then move deeper into the ruin or if we detect that we cannot go any deeper then swap to 'Exiting' state and start to drop the worst treasure until we can guarantee that we can exit the ruin alive.
When in exiting state we will check to see if we can add 1kg treasure and still make it out alive, if so then we shall attempt to bid on a 1kg treasure, if not then we shall head to previous room.
Its performance is quite variable... however normally will be one of the top three bots.
```
import math
class Accomodator(Adventurer):
def enter_ruins(self):
self.bidValue = -1
self.bidWeight = -1
self.exiting = False
self.sprintToRoom = self.random.randrange(25,27)
pass
def get_action(self, state):
move_cost = 10 + int(math.ceil(state.carry_weight / 5))
move_cost_extra_kg = 10 + int(math.ceil((state.carry_weight+1) / 5))
worstMyTreasure = None
worstMyTreasureId = -1
# find our worst treasure
i=0
for treasure in state.inventory:
if (worstMyTreasure is None or treasure.value/treasure.weight < worstMyTreasure.value/worstMyTreasure.weight):
worstMyTreasure = treasure
worstMyTreasureId=i
i+=1
# are we travelling back to the exit?
if (self.exiting == True):
# are we overweight to get back alive?
if (state.stamina / move_cost < state.room):
# drop most worthless treasure
self.bidValue = -1
self.bidWeight = -1
return 'drop',worstMyTreasureId
# would adding one kg cause exhaustion?
if (state.stamina / move_cost_extra_kg <= state.room ):
# head back to the exit
self.bidValue = -1
self.bidWeight = -1
return 'previous'
# sprint if not yet at desired sprintToRoom
elif (state.room < self.sprintToRoom):
return 'next'
# are we now at the limit of stamina to still get back alive?
if (state.stamina / move_cost <= state.room ):
self.exiting = True
# head back to the exit
self.bidValue = -1
self.bidWeight = -1
return 'previous'
bestRoomTreasure = None
bestRoomTreasureId = -1
secondBestRoomTreasure = None
secondBestRoomTreasureId = -1
# find the best room treasure
i=0
for treasure in state.treasures:
# when exiting the ruin, only consider treasures to collect that are 1kg inorder
# to fill up any space left in inventory. Normally consider all treasures
if (self.exiting == False or treasure.weight == 1):
# only bid on items that we did not bid on before to avoid bidding deadlock
if (not (self.bidValue == treasure.value and self.bidWeight == treasure.weight)):
# consider treasures that are better than my worst treasure or always consider when exiting
if (self.exiting == True or (worstMyTreasure is None or treasure.value/treasure.weight > worstMyTreasure.value/worstMyTreasure.weight)):
# consider treasures that are better than the current best room treasure
if (bestRoomTreasure is None or treasure.value/treasure.weight > bestRoomTreasure.value/bestRoomTreasure.weight):
secondBestRoomTreasure = bestRoomTreasure
secondBestRoomTreasureId = bestRoomTreasureId
bestRoomTreasure = treasure
bestRoomTreasureId = i
# since we do not currently have any treasures, we shall pretend that we have this treasure so that we can then choose the best treasure available to bid on
if (worstMyTreasure is None):
worstMyTreasure = bestRoomTreasure
i+=1
chosenTreasure = bestRoomTreasure
chosenTreasureId = bestRoomTreasureId
# if we have potential competitors then bid on second best treasure
if (len(state.players)>0 and secondBestRoomTreasure is not None):
chosenTreasure = secondBestRoomTreasure
chosenTreasureId = secondBestRoomTreasureId
# we have chosen a treasure to bid for
if (chosenTreasure is not None):
# if the chosenTreasure will not fit then dump the worst treasure
if (state.carry_weight + chosenTreasure.weight > 50):
# dump the worst treasure
self.bidValue = -1
self.bidWeight = -1
return 'drop',worstMyTreasureId
# otherwise lets bid for the treasure!
self.bidValue = chosenTreasure.value
self.bidWeight = chosenTreasure.weight
return 'take',chosenTreasureId,chosenTreasure.weight
# no treasures are better than what we already have so go to next/previous room
self.bidValue = -1
self.bidWeight = -1
if (self.exiting == False):
return 'next'
else:
return 'previous'
```
[Answer]
# Sprinter
Similar to the Diver, Sprinter goes in deep and picks up the best items on his way back.
```
import math
class Sprinter(Adventurer):
class __OnlyOne:
__name = None
def __init__(self, name):
self.__name = name
@property
def name(self):
return self.__name
@name.setter
def name(self, name):
if self.__name is None:
self.__name = name
if self.__name is name:
self.__name = None
instance = None
def set(self, instance):
if self.instance is not None:
raise Exception("Already set.")
self.instance = instance
def __init__(self, name, random):
super(Sprinter, self).__init__(name, random)
if not self.instance:
self.instance = Sprinter.__OnlyOne(name)
# else:
# raise Exception('bye scoundriel')
def get_action(self, state):
self.instance.name = self.name
move_cost = 10 + int(math.ceil(state.carry_weight / 5))
if state.stamina // move_cost <= state.room + 1:
return 'previous'
if state.room < 30 and state.carry_weight < 1:
return 'next'
# todo: if there is noone in the room take the most valueable thing that fits criteria
topVal = 0
topValIndex = 0
for t in state.treasures:
val = t.value / t.weight
if val > topVal:
if t.weight + state.carry_weight < 50:
topVal = val
topValIndex = state.treasures.index(t)
if len(state.treasures) > topValIndex:
treasure = state.treasures[topValIndex]
if treasure.weight + state.carry_weight > 50: # it doesn't fit
return 'previous' # take lighter treasure
else:
if topVal > state.room * 2:
return 'take', topValIndex, treasure.weight + (self.random.randrange(2, 8) if state.players else 0)
if state.carry_weight > 0:
return 'previous'
else:
return 'next'
def enter_ruins(self):
if self.instance is None or self.name != self.instance.name:
raise Exception('Hi Scoundrel')
```
Sprinter goes in deep then calculates a score for each treasure and picks up anything above a certain threshold. This threshold depends on the room he is currently in because it costs more to take items from rooms deeper in the ruins.
I still have 2 optimisations regarding "fighting for treasure" that are planned for the next days.
17.04.: Scoundrel got too smart, Sprinter decided to push him in a trap
initially I wanted to kill any bot that tried to invoke Sprinter but the testdriver unfortunately doesn't handle exceptions that happen on init. So the next fix for Scoundrel is quite easy...
[Answer]
# Plan Ahead
```
import math
class PlanAhead(Adventurer):
def get_action(self, state):
if state.inventory:
ivals = {}
for i in range(len(state.inventory)):
itm = state.inventory[i]
ivals[i] = itm.value / itm.weight
worstiind = min(ivals, key=lambda x: ivals[x])
worsti = (worstiind,
state.inventory[worstiind].value,
state.inventory[worstiind].weight)
else:
worsti = None
if self.drop_worst:
self.drop_worst = False
return 'drop', worsti[0]
if self.seenItems:
ivals = {}
for i in range(len(self.seenItems)):
itm = self.seenItems[i][0]
v = itm.value
if self.seenItems[i][1] >= state.room:
v = 0
if v / itm.weight > 250: #very likely to get picked up already
v = 0
ivals[i] = v / itm.weight
bestIiind = max(ivals, key=lambda x: ivals[x])
bestIi = (bestIiind,
self.seenItems[bestIiind][0].value,
self.seenItems[bestIiind][0].weight)
else:
bestIi = None
stamCarry = state.carry_weight/5
stamToExit = state.room * (10 + math.ceil(stamCarry))
if state.room > self.max_room:
self.max_room = state.room
if stamToExit > state.stamina and worsti:
return 'drop', worsti[0]
if state.treasures:
tvals = {}
for i in range(len(state.treasures)):
itm = state.treasures[i]
v = itm.value
tvals[i] = v / itm.weight
self.seenItems.append((itm,state.room))
besttind = max(tvals, key=lambda x: tvals[x])
bestt = (besttind,
state.treasures[besttind].value,
state.treasures[besttind].weight)
if len(state.players) > 0 and not self.did_drop:
tvals[besttind] = 0
besttind = max(tvals, key=lambda x: tvals[x])
bestt = (besttind,
state.treasures[besttind].value,
state.treasures[besttind].weight)
else:
bestt = None
if not self.retreat and stamToExit + (12 + stamCarry)*2 + state.room + (state.room/5*state.room) <= state.stamina:
return 'next'
if not self.retreat and stamToExit + 10 > state.stamina:
self.retreat = True
return 'previous'
if bestt:
if state.carry_weight + state.treasures[besttind].weight > 50 or (not self.did_drop and (worsti and (state.treasures[besttind].value-state.treasures[besttind].weight*20) > worsti[1] and state.treasures[besttind].weight <= worsti[2])):
if worsti:
if len(state.players) > 0:
return 'previous'
if stamToExit <= state.stamina and math.ceil((state.carry_weight - (worsti[2] - state.treasures[besttind].weight))/5)*state.room >= state.treasures[besttind].weight:
return 'previous'
self.did_drop = True
return 'drop', worsti[0]
else:
self.retreat = True
return 'previous'
bid = state.treasures[besttind].weight
if bid > 8 and state.room >= self.max_room-5:
return 'previous'
if not self.did_drop and state.stamina - bid < state.room * (10 + math.ceil(stamCarry+(bid/5))):
if worsti:
if state.treasures[besttind].weight <= worsti[2]:
if state.treasures[besttind].value >= worsti[1]:
if state.treasures[besttind].weight == worsti[2]:
if state.treasures[besttind].value/state.treasures[besttind].weight >= worsti[1]/worsti[2] * (1+(0.05*worsti[2])):
self.drop_worst = True
return 'take', bestt[0], bid
if not self.retreat:
self.retreat = True
cost = math.ceil((state.carry_weight+bid)/5) - math.ceil(state.carry_weight/5)
if state.room <= 10 and state.carry_weight > 0 and (state.stamina - stamToExit) >= bid + cost*state.room and bestt:
return 'take', bestt[0], bid
return 'previous'
self.did_drop = False
if bestIi[1]/bestIi[2] * 0.3 > bestt[1]/bestt[2] and state.carry_weight > 0:
return 'previous'
self.seenItems = list(filter(lambda x: x[0] != state.treasures[besttind], self.seenItems))
return 'take', bestt[0], bid
if stamToExit + (12 + stamCarry + state.room)*2 <= state.stamina:
return 'next'
else:
self.did_drop = False
self.retreat = True
return 'previous'
def enter_ruins(self):
self.retreat = False
self.max_room = 0
self.did_drop = False
self.seenItems = []
self.drop_worst = False
pass
```
I utilized the best/worst calculation hunks from [Artemis Fowl's answer](https://codegolf.stackexchange.com/a/183127/47990), but the choice logic is of entirely my own design and has since been modified to include a few additional factors, such as treasures seen in earlier rooms (in order to minimize picking up a treasure, only to backtrack, drop it, and pick up something else).
Bot ventures as deep as it thinks is reasonably safe to do so (this calculation effectively works out to diving to a specific depth, but has the flexibility of handling other initial stamina values), collects artifacts (prioritizing high cost and low weight), then begins to retreat once it determines that it can't carry any more.
On the way out it will pick up any additional treasures it sees that it determines it can still safely carry to the exit. It will even drop already held artifacts if the new one is a better deal and won't result in exhaustion. If it has room in its backpack, it will pick the new treasure up *before* dropping the lower quality one, minimizing fighting with other bots.
[Answer]
# Artyventurer
Beats the Drunkards by about $1000! Couldn't think of a creative name, but here y'all are:
```
import math, sys, inspect, ntpath, importlib
CONTINUE_IN = 310 #go deeper if I have this much extra
JUST_TAKE = 0 #take without dropping if I have this much extra
class Artyventurer(Adventurer):
def enter_ruins(self):
self.drop = False
def get_extra(self, state, take=0, drop=0):
w = state.carry_weight + take - drop
return state.stamina - ((10 + math.ceil(w/5)) * state.room)
def get_action(self, state):
self.fail = 'draco' in ''.join(ntpath.basename(i.filename) for i in inspect.stack())
if self.fail:
return 'previous'
if state.inventory:
ivals = {}
for i in range(len(state.inventory)):
itm = state.inventory[i]
ivals[i] = itm.value / (itm.weight + 5)
worstiind = min(ivals, key=lambda x: ivals[x])
worsti = (worstiind,
state.inventory[worstiind].value,
state.inventory[worstiind].weight)
else:
worsti = None
if self.drop and worsti:
self.drop = False
return 'drop', worsti[0]
if state.treasures:
tvals = {}
for i in range(len(state.treasures)):
itm = state.treasures[i]
if itm.weight > (int(state.room/10) or 2):
continue
tvals[i] = itm.weight#(itm.value * (36-state.room)) / (itm.weight * (state.carry_weight+1))
bestord = sorted(tvals, key=lambda x: tvals[x], reverse=True)
if bestord:
pass#print(state.treasures[bestord[0]], '\n', *state.treasures, sep='\n')
topt = []
for i in bestord:
topt.append((i,
state.treasures[i].value,
state.treasures[i].weight))
else:
topt = None
extra = self.get_extra(state)
if extra > CONTINUE_IN:
return 'next'
if extra < 0 and worsti:
return 'drop', worsti[0]
if extra < state.room:
return 'previous'
if extra > JUST_TAKE and topt:
choose = topt[:len(state.treasures)//3+1]
for t in choose:
bid = int(bool(len(state.players)))*3 + t[2]
if self.get_extra(state, t[2]) - bid >= 0:
if t[2] + state.carry_weight <= 50:
return 'take', t[0], bid
if topt and worsti:
for t in topt[:len(state.treasures)//3+1]:
if t[1] > worsti[1] or t[2] < worsti[2]:
bid = int(bool(len(state.players)))*3 + t[2]
if self.get_extra(state, t[2], worsti[2]) - 1 - bid >= 0:
print('a', '+weight:', t[2], '; cweight:', state.carry_weight, '; stamina:', state.stamina)
if bid < state.stamina and t[2] + state.carry_weight <= 50:
print('o')
self.drop = True
return 'take', t[0], bid
return 'previous'
```
Sometimes most of the code here doesn't ever do anything (at least when I test it against Drunkards), the program just (tries to) find the best move, including processing for situations it tries not to put itself into. Some of it **can never** run, it's just there so I can fiddle about with the numbers, which can probably still be improved.
## Explanation
* `if state.inventory ... worsti = None`
Find the 'worst' item in the inventory, that is, the item which has the lowest ratio of value to weight. It stores `worsti`, which contains the index of it, it's value, and it's weight, as a tuple, or `None` if there are no items in the inventory.
* `if self.drop ... return 'drop', worsti[0]`
If I told it to drop this turn *last turn* (see below), and it can, drop the 'worst' item as calculated above.
* `extra = ... * state.room`
Calculate how much stamina it would have leftover *if* I told it to go straight back now.
* `if extra > CONTINUE_IN:\ return 'next'`
If it's more than CONTINUE\_IN, return `'next'`.
* `if extra < 0 and worsti:\ return 'drop', worsti[0]`
If it's less than `0`, drop the worst item.
* `if extra < state.room:\ return 'previous'`
If it's less than the room number (can't carry any more treasure) go back.
* `if state.treasures: ... bestt = None`
Work out the best treasure to take, similar to the worst item in the inventory above. Store it in `bestt`.
* `if extra > 0 and bestt: ... return 'take', bestt[0], bid`
With current numbers, this executes whenever we've got this far and there is treasure availavable. If it is safe to take the 'best' treasure, it does so. It's bid is the minimum, or one more than that if anyone is present.
* `if bestt and worsti: ... return 'take', bestt[0], bid`
With current numbers, this code block will never execute, because the previous code block has a wider condition. This executes if we have got this far and there are both treasure/s in my inventory and the room. If the 'best' treasure in the room is more valuable than the 'worst' treasure in my inventory, and it would be safe to swap them over the next two turns, it does so.
* `return 'previous'`
If none of these happen, just go back.
### Update 16/04/19:
Anti-scoundrel measures. This will become a bidding war :(
### Further Update 16/04/19:
Reverted previous, instead randomly switches every other element when finding the best, eg. `[1, 2, 3, 4, 5, 6] → [2, 1, 3, 4, 6, 5]`. Should be harder to copy :).
### Update 17/04/19:
Reverted previous, instead it ***wipes its own source code***. It does this in `__init__` which will always be before `Scoundrel.enter_ruins`, and so will stop Scoundrel from loading it. It replaces its code when `get_action` is first called, so that it will be ready for next time. FIXED, Scoundrel now dies on arrival.
### Further Update 17/04/19:
Reverted previous, instead it replaces its `sys.modules` entry with the math module, so that when Scoundrel attempts to load it, it loads the math module instead. :)
Also, I only just realised that move stamina was 10 + weight **/5**, so tried to fix that.
### Further Update 17/04/19:
Now includes garlic from both the previous updates.
### Update 18/04/19:
Fiddling with numbers and calculations, now gets $2000 - $3000.
### Further Update 18/04/19:
Removed file-wipe garlic as it has been banned, added new garlic which makes sure `'draco'` is not responsible for it running, if it is it just returns `previous` on its first turn. Results have taken a mysterious dive to $1200-$1800, which I'm looking into.
[Answer]
# The Scoundrel
```
import math, importlib
CONTINUE_IN = 310 #go deeper if I have this much extra
JUST_TAKE = 0 #take without dropping if I have this much extra
class Scoundrel(Adventurer):
def my_import(self, name):
components = name.split('.')
mod = __import__(components[0])
for comp in components[1:]:
mod = getattr(mod, comp)
return mod
def get_action(self, state):
if self.following == 0:
return self.sprinter(state)
if self.following == 1:
return self.arty(state)
if self.following == 2:
return self.account(state)
return 'next'
def enter_ruins(self):
_weights=[17,0,13]
self.following = self.random.choices(population=[0,1,2],weights=_weights)[0]
try:
self.arty_clone = importlib.import_module('artemis_fowl__artyventurer').Artyventurer(self.name,self.random)
self.arty_clone.enter_ruins()
except:
self.arty_clone = None
self.sprinter_clone = self.my_import('akroell__sprinter').Sprinter(self.name,self.random)
self.sprinter_clone.enter_ruins()
self.account_clone = self.my_import('arbo__accountant').Accountant(self.name,self.random)
self.account_clone.enter_ruins()
self.drop = False
pass
def sprinter(self, state):
raw_action = self.sprinter_clone.get_action(state)
if raw_action == 'next' or raw_action == 'previous':
#move_cost = 10 + int(math.ceil(state.carry_weight / 5))
#if state.stamina // move_cost < state.room:
# print('wont make it!')
return raw_action
else:
atype, *args = raw_action
if atype == 'take':
return self.TakeSprinter(state, *args)
if atype == 'drop':
return raw_action
def TakeSprinter(self, state, treasure, bid):
move_cost = 10 + int(math.ceil((state.carry_weight+state.treasures[treasure].weight) / 5))
maxbid = state.stamina - move_cost*(state.room)
bid = state.treasures[treasure].weight + (7 if state.players else 0)
if maxbid < state.treasures[treasure].weight:
return 'previous'
if maxbid < bid:
bid = maxbid
return 'take',treasure, bid
def arty(self, state):
if self.arty_clone == None:
try:
self.arty_clone = importlib.import_module('artemis_fowl__artyventurer').Artyventurer(self.name,self.random)
self.arty_clone.enter_ruins()
except:
self.arty_clone = None
if self.arty_clone == None:
raw_action = self.backup_arty(state)
else:
raw_action = self.arty_clone.get_action(state)
if raw_action == 'previous' and state.carry_weight < 1:
self.arty_clone.fail = False
return 'next'
if raw_action == 'next' or raw_action == 'previous':
return raw_action
else:
atype, *args = raw_action
if atype == 'take':
return self.TakeArty(*args)
if atype == 'drop':
return raw_action
def TakeArty(self, treasure, bid):
return 'take', treasure, bid + self.random.randrange(0, 2)
def account(self, state):
raw_action = self.account_clone.get_action(state)
if raw_action == 'next' or raw_action == 'previous':
return raw_action
else:
atype, *args = raw_action
if atype == 'take':
return self.TakeAcc(*args)
if atype == 'drop':
return raw_action
def TakeAcc(self, treasure, bid):
return 'take',treasure,bid + self.random.randrange(0, 2)
def get_extra(self, state, take=0, drop=0):
w = state.carry_weight + take - drop
return state.stamina - ((10 + math.ceil(w/5)) * state.room)
def backup_arty(self, state):
if state.inventory:
ivals = {}
for i in range(len(state.inventory)):
itm = state.inventory[i]
ivals[i] = itm.value / (itm.weight + 5)
worstiind = min(ivals, key=lambda x: ivals[x])
worsti = (worstiind,
state.inventory[worstiind].value,
state.inventory[worstiind].weight)
else:
worsti = None
if self.drop and worsti:
self.drop = False
return 'drop', worsti[0]
if state.treasures:
tvals = {}
for i in range(len(state.treasures)):
itm = state.treasures[i]
if itm.weight > (int(state.room/12) or 2):
continue
tvals[i] = (itm.value * (25-state.room)) / (itm.weight * (state.carry_weight+1))
bestord = sorted(tvals, key=lambda x: tvals[x])
topt = []
for i in bestord:
topt.append((i,
state.treasures[i].value,
state.treasures[i].weight))
else:
topt = None
extra = self.get_extra(state)
if extra > CONTINUE_IN:
return 'next'
if extra < 0 and worsti:
return 'drop', worsti[0]
if extra < state.room:
return 'previous'
if extra > JUST_TAKE and topt:
choose = topt[:len(state.treasures)//3+1]
for t in choose:
bid = int(bool(len(state.players)))*3 + t[2]
if self.get_extra(state, t[2]) - bid >= 0:
if t[2] + state.carry_weight <= 50:
return 'take', t[0], bid
if topt and worsti:
for t in topt[:len(state.treasures)//3+1]:
if t[1] > worsti[1] or t[2] < worsti[2]:
bid = int(bool(len(state.players)))*3 + t[2]
if self.get_extra(state, t[2], worsti[2]) - 1 - bid >= 0:
if bid < state.stamina and t[2] + state.carry_weight <= 50:
self.drop = True
return 'take', t[0], bid
return 'previous'
```
The Scoundrel primarily works to interfere with other contestants. Currently it interferes with Sprinter, Artyventurer, and Accountant (this list will grow over time provided that it is within the Scoundrel's best interest). It does this by mimicking the other bots and then either out-bidding, under-cutting, or otherwise fighting over relics. As such, it is unlikely that this entry will ever dominate the leaderboard and instead operates as a spoiling force. Current revision at the time of this posting puts it in 2nd place with an average score of about 7.
Scoundrel foils other bot's attempts to modify themselves to defend against the Scoundrel by directly executing the other entrants' code as an indistinguishable clone copy. Issues with imports resulting in duplicated entrants was resolved via creating the clones through Reflection (edit wars involving fine details of mathematical determination is not desirable from a Stack Exchange point of view, but would result in the same outcome). KOTH challenges have a history of allowing this, as well.
Scoundrel replaces the Teamsters in order to keep the Teamsters for the sake of having been interesting. After this edit, Teamsters should no longer be scraped by the controller.
Update 4/17/2019: further counter-counter measures.
# The Teamsters (rendered illegal)
But feel free to run locally where there are no more than 8 other contestants!
```
class TeamsterA(Adventurer):
def get_action(self, state):
if state.room < 25 and state.carry_weight == 0:
return 'next'
if state.room == 25 and len(state.players) == 0 and len(state.inventory) <= 1:
if state.treasures and len(state.inventory) == 0:
tvals = {}
for i in range(len(state.treasures)):
itm = state.treasures[i]
if itm.weight == 1:
return 'take',i,1
for i in range(len(state.treasures)):
itm = state.treasures[i]
if itm.weight == 2:
return 'take',i,2
if state.carry_weight > 0 and len(state.inventory) == 1 and int(state.inventory[0].name.strip('Treasure #')) < 500:
return 'drop',0
return 'previous'
if state.room >= 25:
if (((state.carry_weight+4) / 5) + 10) * state.room >= state.stamina:
return 'previous'
if len(state.inventory) == 1 and int(state.inventory[0].name.strip('Treasure #')) < 500:
return 'drop',0
if state.treasures:
tvals = {}
for i in range(len(state.treasures)):
itm = state.treasures[i]
if int(itm.name.strip('Treasure #')) > 500:
if (((state.carry_weight+3+itm.weight) / 5) + 10) * state.room >= state.stamina:
return 'previous'
return 'take',i,itm.weight
for i in range(len(state.treasures)):
itm = state.treasures[i]
if itm.weight == 1:
return 'take',i,1
for i in range(len(state.treasures)):
itm = state.treasures[i]
if itm.weight == 2:
return 'take',i,2
if len(state.inventory) > 0:
return 'previous'
return 'next'
return 'previous'
class TeamsterB(Adventurer):
def get_action(self, state):
if state.treasures:
tvals = {}
for i in range(len(state.treasures)):
itm = state.treasures[i]
w = itm.weight
v = itm.value
if w + state.carry_weight > self.max_total_weight or w > self.max_single_weight:
w = 100
if v / w < state.room * self.min_value_ratio:
v = 0
tvals[i] = v / w
besttind = max(tvals, key=lambda x: tvals[x])
bestt = (besttind,
state.treasures[besttind].value,
state.treasures[besttind].weight)
else:
bestt = None
if state.room < self.max_dive_dist and state.carry_weight == 0:
return 'next'
if state.room > 25 and bestt and state.carry_weight + bestt[2] <= self.max_total_weight and bestt[1] > 0 and bestt[2] <= self.max_single_weight and len(state.players) == 0:
return 'take',bestt[0],bestt[2]
if state.carry_weight > 0 and state.room > 25 and len(state.players) == 0:
return 'previous'
if state.carry_weight > 0:
return 'drop',0
if state.carry_weight > 0:
return 'take',bestt[0],bestt[2]
return 'previous'
def enter_ruins(self):
self.max_single_weight = 3
self.max_total_weight = 20
self.min_value_ratio = 2.5
self.max_dive_dist = 55
pass
```
This entry (while now explicitly invalid) is, in fact, *two* bots, and the controller will *happily* scrape them both and add them to the contestant list (because hooray Python?)
### Phase 1:
* TeamsterA heads down to level 25 (ish)1 and repeatedly picks up and drops the lightest treasure he can find. This costs a whopping 1 stamina a turn until the second phase.
* TeamsterB heads down to level 55 and picks up all the valuables laying around and then heads back up to level 25 (ish).2 Then begins phase 2.
1. If there isn't a treasure weighing less than 3 on a floor, he moves down
2. As he's pretty much guaranteed to be the *last* adventurer returning to the surface, all he has to do is find somebody.
### Phase 2:
* TeamsterB empties his pockets before crawling off to die from exhaustion. We knew you could do it.
* TeamsterA thinks "those are some shiny trinkets, good buddy ol' pal!" and loads up on the much more valuable treasures than the other junk in the room before proceeding to the exit, pockets full of gold.
The name of the treasures actually came in handy in order to help the logic not load up on floor 25 junk and leave early as there was no way to communicate between the two bots (and TeamsterA would always find itself in a room with someone else before TeamsterB had returned).
## The next logical conclusion: Creating an army
*In theory* this could be used to plumb the depths and acquire treasures from as deep as Room 98, however, as that would require more than 2 bots, the logic comprising those bots would become increasingly complex, and as I'm certain that this is an illegal submission for violating an unwritten rule, so I'm not going to bother.
Effectively `A` waits at 30, `B` waits at 50...`n` dives to 98, picks up a treasure, moves to 97, drops it (and then dies), `n-1` picks it up and moves to 96...`C` drops it (dies), `B` picks it up and moves to 30, drops it (dies), `A` picks it up and returns to the exit.
I estimate that this would take 11 bots.
However, it isn't worth doing unless you can recover about 4 treasures from that depth in order to compete with entries like PlanAhead or Artyventure, due to the scaling between stamina costs to move and the average value of treasures.
## Sample results
Rarely scores under $4000, occasionally crests $6000.
```
[Turn 141] Homer the Great (TeamsterA) exited the ruins with 286 stamina
and 16 treasures, totaling $4900 in value.
[Game End] The game has ended!
[Game End] Homer the Great (TeamsterA) won the game
[Turn 145] Samwell Jackson DDS (TeamsterA) exited the ruins with 255 stamina
and 20 treasures, totaling $6050 in value.
[Game End] The game has ended!
[Game End] Samwell Jackson DDS (TeamsterA) won the game
[Turn 133] Rob the Smuggler (TeamsterA) exited the ruins with 255 stamina
and 12 treasures, totaling $3527 in value.
[Game End] The game has ended!
[Game End] Eliwood the Forgettable (PlanAhead) won the game
```
[Answer]
# Backwards
Because it operates in reverse
```
import math
class Backwards (Adventurer):
def enter_ruins(self):
self.goal = 5000
self.diving = True
def expected_rooms_left(self, state):
if not self.diving:
return state.room
else:
return state.stamina / 18
def ratio(self, state, treasure):
stamina_cost = treasure.weight * (1 + 1/5 * self.expected_rooms_left(state)) + math.ceil(len(state.players)/2.9)
ratio = (treasure.value / (self.goal - state.total_value)) / (stamina_cost / state.stamina)
return ratio
def get_action(self, state):
room, treasures, players, inventory, stamina = state
if stamina < room * (math.ceil(state.carry_weight / 5) + 10) + 40 or stamina < (room+2.976) * (math.ceil(state.carry_weight / 5) + 11):
self.diving = False
if stamina < (room+0.992) * (math.ceil(state.carry_weight / 5) + 10.825):
return 'previous'
worthwhile = []
for i, treasure in enumerate(treasures):
ratio = self.ratio(state, treasure)
if ratio >= 1 and state.carry_weight + treasure.weight <= 50:
worthwhile.append((ratio, i))
if worthwhile:
ratio, index = sorted(worthwhile, reverse=True)[0]
treasure = treasures[index]
bid = treasures[index].weight + math.ceil(len(players)/2.9)
if (not self.diving or ratio > 2.8) and stamina >= bid + (room) * (math.ceil((state.carry_weight+treasures[index].weight) / 5) + 10):
return 'take', index, bid
return 'next' if self.diving else 'previous'
```
Why is it called Backwards?
Because I took The Accountant and tried to make it run its logic such that it would dive deep, then pick up its preferred loot on the way out (backwards of the Accountant).
In the end it still collects much of its prizes on the way in (scooping them up before the traditional in-collect-out seekers do, operating backwards to everyone else), but its much more *selective* about which ones it takes, though it still picks up things on its way back out.
The end result is that stamina is conserved on the way in while still prioritizing high-value treasures, then taking advantage of a deep turn around and easy pickings on the way back up. Backwards has been known to collect treasures from as far down as Room 41 (and during development would enter, then immediately leave, Room 42).
[Answer]
# Bounty Hunter
The simple method is the best. Grab valuable and light treasures while going as deep as possible. Grab less valuable treasures on the way back.
```
import math
class BountyHunter(Adventurer):
def move_cost(self, state, additional_weight):
return 10 + int(math.ceil((state.carry_weight + additional_weight) / 5))
def get_action(self, state):
can_go_deeper = state.stamina > (state.room + 2) * self.move_cost(state, 0)
if state.treasures:
best_ratio = 0
best_index = 0
best_weight = 0
for i, treasure in enumerate(state.treasures):
ratio = treasure.value / treasure.weight
if ratio > best_ratio:
best_ratio = ratio
best_index = i
best_weight = treasure.weight
limit = 160 if can_go_deeper else 60
bid = best_weight + 2 if len(state.players) >= 1 else best_weight
if state.carry_weight + best_weight <= 50 and best_ratio >= limit and state.stamina >= bid + state.room * self.move_cost(state, best_weight):
return 'take', best_index, bid
if can_go_deeper:
return 'next'
else:
return 'previous'
```
[Answer]
# LightWeight
A simple bot that still performs quite well.
After venturing into the ruins (currently 21 rooms) it will grab the best treasure in the room that is only 1kg (hence the name of the bot) and is more valuable than the least valuable treasure in the inventory. If inventory is full, drop the least valuable treasure. If no other action is selected, the move into the ruins. If we are at the limit of our stamina to be able to exit alive then head to the exit
```
import math
class LightWeight(Adventurer):
def get_action(self, state):
move_cost = 10 + int(math.ceil(state.carry_weight / 5))
# are we now at the limit of stamina to still get back alive?
if (state.stamina / move_cost <= state.room + 3):
# head back to the exit
return 'previous'
if (state.room < 21):
return 'next'
bestRoomTreasure = None
bestRoomTreasureId = -1
worstMyTreasure = None
worstMyTreasureId = -1
# find our worst treasure
i=0
for treasure in state.inventory:
if (worstMyTreasure is None or treasure.value < worstMyTreasure.value):
worstMyTreasure = treasure
worstMyTreasureId=i
i+=1
# we have hit our carrying capacity... we are now going to dump least valuable treasure
if (state.carry_weight==50):
# dump the worst treasure
return 'drop',worstMyTreasureId
# find the best room treasure
i=0
for treasure in state.treasures:
if (treasure.weight == 1 and (worstMyTreasure is None or treasure.value > worstMyTreasure.value)):
if (bestRoomTreasure is None or treasure.value > bestRoomTreasure.value):
bestRoomTreasure = treasure
bestRoomTreasureId = i
i+=1
# we have found a treasure better than we already have!
if (bestRoomTreasure is not None):
return 'take',bestRoomTreasureId,1
# no treasures are better than what we already have so go to next room
return 'next'
```
[Answer]
# Memorizer
I can submit bots to my own KotH, right?
```
from __main__ import Adventurer
import math
from collections import namedtuple
class TooHeavy(Exception):
pass
TreasureNote = namedtuple(
'TreasureNote',
['utility', 'cost', 'room', 'name', 'value', 'weight']
)
def find_treasure(treasures, name):
for i, t in enumerate(treasures):
if t.name == name:
return i, t
raise KeyError(name)
EXPLORE_DEPTH = 30
TRINKET_MINIMUM_VALUE = 60
class Memorizer(Adventurer):
def enter_ruins(self):
self.seen = []
self.plan = []
self.backups = []
self.diving = True
self.dive_grab = False
def plan_treasure_route(self, state):
self.plan = []
self.backups = []
weight = state.carry_weight
for treasure in self.seen:
if weight + treasure.weight <= 50:
self.plan.append(treasure)
weight += treasure.weight
else:
self.backups.append(treasure)
room_utility = lambda t: (t.room, t.utility)
self.plan.sort(key=room_utility, reverse=True)
def iter_backups(self, state):
names = {t.name for t in state.treasures}
owned = {t.name for t in state.inventory}
for treasure in self.backups:
if (treasure.room == state.room
and treasure.name in names
and treasure.name not in owned):
yield treasure
def take(self, state, name):
index, treasure = find_treasure(state.treasures, name)
if state.carry_weight + treasure.weight > 50:
raise TooHeavy(name)
if state.players:
bid_bonus = self.random.randrange(len(state.players) ** 2 + 1)
else:
bid_bonus = 0
return 'take', index, treasure.weight + bid_bonus
def get_action(self, state):
take_chance = 0.9 ** len(state.players)
if self.diving:
if self.dive_grab:
self.dive_grab = False
else:
self.seen.extend(
TreasureNote(
value / weight,
weight + math.ceil(weight / 5) * state.room,
state.room,
name, value, weight
)
for name, value, weight in state.treasures
)
if state.room < EXPLORE_DEPTH:
if len(state.inventory) < 5:
trinkets = [
t for t in state.treasures
if t.weight == 1
and t.value >= TRINKET_MINIMUM_VALUE
]
trinkets.sort(key=lambda t: t.value, reverse=True)
for candidate in trinkets:
if self.random.random() < 0.99 ** (len(state.players) * state.room):
try:
action = self.take(state, candidate.name)
except (KeyError, TooHeavy):
pass # WTF!
else:
self.dive_grab = True
return action
return 'next'
else:
self.diving = False
self.seen.sort(reverse=True)
self.plan_treasure_route(state)
carry_weight = state.carry_weight
if carry_weight == 50:
return 'previous'
if self.plan:
next_index = 0
next_planned = self.plan[next_index]
if state.room > next_planned.room:
return 'previous'
try:
while state.room == next_planned.room:
if self.random.random() < take_chance:
try:
return self.take(state, next_planned.name)
except (KeyError, TooHeavy):
self.plan.pop(next_index)
next_planned = self.plan[next_index]
else:
next_index += 1
next_planned = self.plan[next_index]
except IndexError:
pass
else:
next_planned = TreasureNote(0, 0, 0, 0, 0, 0)
for candidate in self.iter_backups(state):
if candidate.utility * 2 > next_planned.utility and self.random.random() < take_chance:
try:
return self.take(state, candidate.name)
except (KeyError, TooHeavy):
pass
return 'previous'
```
This bot dives to room 30 and remembers all the treasures it has seen. At that point, it begins its trek back to the entrance, trying to take good treasures it remembered seeing in earlier rooms.
I hoped it would do better. Possible improvements may come from better planning and being more dynamic about which room it stops diving at and being more willing to explore backup options.
Update: now grabs 1kg treasures worth $60 or more on the way in.
[Answer]
# Ponderer
I think it is quite similar to Memorizer in that it uses knowledge of visited rooms to choose which rooms and treasures to collect from on the way back to the exit, however it has been independently derived.
This bot sprints until a random deep room taking a record of treasures found along the way. Once at the target room it will then *ponder* on the ideal selection of treasures to take on its way back to the exit. Each turn it will *ponder* again to determine the most likely best selection of treasures to take.
Currently there is a simple algorithm (inverse power of the room number) that yields the assumed number of treasures taken (or will have been taken when visited by this bot) for each room and so these treasures are ignored when pondering on which treasures/rooms to take from. I have ideas for other more advanced algorithms to model which treasures remain. But I will have to see whether the benefit is worth it.
```
import math
class Ponderer(Adventurer):
class PondererTreasure:
def __init__(self):
self.weight = 0
self.value = 0
self.id = -1
pass
class PondererRoom:
def __init__(self):
self.treasures = []
pass
def enter_ruins(self):
self.exiting = False
self.sprintToRoom = self.random.randrange(30,33)
self.rooms = {}
self.roomsToSkip = 0
pass
def getBestEstimatedFinalValue(self, roomId, carry_weight, stamina, action, valueCache):
if (roomId<=0):
return 0
roomValueCache = valueCache.get(roomId)
if (roomValueCache is None):
roomValueCache = {}
valueCache[roomId] = roomValueCache
value = roomValueCache.get(carry_weight)
if (value is None):
room = self.rooms.get(roomId)
bestTreasureValue = 0
bestTreasure = None
treasures = []
treasures.extend(room.treasures)
skipRoomTreasure = Ponderer.PondererTreasure()
treasures.append(skipRoomTreasure)
roomFactor = 0.075*roomId
estimatedTreasuresTakenAtCurrentRoom = int(min(0.5 * len(room.treasures), max(1, 0.5 * len(room.treasures)*(1.0/(roomFactor*roomFactor)))))
j=0
for treasure in treasures:
if (j>=estimatedTreasuresTakenAtCurrentRoom):
staminaAfterBid = stamina - treasure.weight
carry_weightAfterBid = carry_weight + treasure.weight
move_costAfterBid = 10 + int(math.ceil(carry_weightAfterBid/5))
if (carry_weightAfterBid <=50 and (staminaAfterBid/move_costAfterBid > roomId+1)):
bestAccumulativeValue = self.getBestEstimatedFinalValue(roomId-1, carry_weightAfterBid, staminaAfterBid - move_costAfterBid, None, valueCache)
if (bestAccumulativeValue >= 0):
bestAccumulativeValue += treasure.value
if (bestTreasure is None or bestAccumulativeValue > bestTreasureValue):
bestTreasureValue = bestAccumulativeValue
bestTreasure = treasure
j+=1
if (bestTreasure == skipRoomTreasure):
if (action is not None):
newAction = []
newAction.append('previous')
action.append(newAction)
value = 0
elif (bestTreasure is not None):
if (action is not None):
newAction = []
newAction.append('take')
newAction.append(bestTreasure.id)
newAction.append(bestTreasure.weight)
action.append(newAction)
value = bestTreasureValue
else:
if (action is not None):
newAction = []
newAction.append('previous')
action.append(newAction)
value = -1
roomValueCache[carry_weight] = value
return value
def get_action(self, state):
room = Ponderer.PondererRoom()
i=0
for treasure in state.treasures:
pondererTreasure = Ponderer.PondererTreasure()
pondererTreasure.weight = treasure.weight
pondererTreasure.value = treasure.value
pondererTreasure.id = i
room.treasures.append(pondererTreasure)
i+=1
room.treasures.sort(key=lambda x: x.value/x.weight, reverse=True)
self.rooms[state.room] = room
if (self.exiting == False and state.room < self.sprintToRoom):
return 'next'
self.exiting = True
action = []
valueCache = {}
self.getBestEstimatedFinalValue(state.room, state.carry_weight, state.stamina, action, valueCache)
if (action[0][0] == 'take'):
return 'take', action[0][1], action[0][2]
return action[0][0]
```
[Answer]
# Hoarder
```
import math
class Hoarder(Adventurer):
def canGoOn(self, state):
costToMove = 10 + math.ceil(state.carry_weight / 5)
return (state.room + 2) * costToMove <= state.stamina
def canTakeTreasure(self, state, treasure):
costToMove = 10 + math.ceil(state.carry_weight / 5)
treasureCost = treasure.weight + 1
return treasureCost + state.room * costToMove <= state.stamina
def get_action(self, state):
if (len(state.treasures) == 0):
if (self.canGoOn(state)):
return "next"
else:
return "previous"
else:
bestTreasure = -1
for i, treasure in enumerate(state.treasures):
if self.canTakeTreasure(state, treasure):
if (bestTreasure == -1):
bestTreasure = i
elif state.treasures[bestTreasure].value < state.treasures[i].value:
bestTreasure = i
if (bestTreasure == -1):
return "previous"
return "take", bestTreasure, state.treasures[bestTreasure].weight+1
```
The Hoarder stays in a room until it has taken all of the treasures in the room (or calculates that it doesn't have enough stamina to keep taking/moving on). When all of the treasures are gone, if the bot can move on safely it will, and continue the process of taking all of the treasure.
[Answer]
# Diver
(Can't test at the moment, so let me know if this is broken.)
```
class Diver(Adventurer):
def get_action(self, state):
# Don't take anything on the way in.
if state.stamina > 700:
return 'next'
# Take the most valuable thing we can take without dying.
for treasure in sorted(state.treasures, key=lambda x: x.value, reverse=True):
total = treasure.weight + state.carry_weight
if total <= 50 and (10 + (total + 4) // 5) * state.room + treasure.weight <= state.stamina:
return 'take', state.treasures.index(treasure), treasure.weight
# If there's nothing else we can do, back out.
return 'previous'
```
The best treasure is deeper in the ruins, so dive deep, then grab what we can on the way out.
] |
[Question]
[
In the Pokemon video games, the player is sent out into the world to force wild animals into tiny balls and train them to fight. Of course, *everyone* knows that *no one* plays Pokemon for the battling. The real draw the series has is the pokemon catching itself! Your job is to simulate the pokeball during a capture attempt. This challenge will use the generation V capture formula, which is as follows:

`HP_max` is equal to the target pokemon's maximum HP. `HP_current` is equal to the target pokemon's current HP. `rate` is the catch rate of the pokemon, `bonus_ball` is the thrown pokeball's multiplier, and `bonus_status` is 2.5 if the target pokemon is asleep or frozen, 1.5 if the target pokemon is paralyzed, poisoned, or burned, and 1 otherwise.
After finding `a`, you are to perform up to three "shake checks". The probability of a shake check succeeding is `65536 / (255 / a)^(1/4)`. If any one of these checks fails, the pokemon escapes its ball. If all three checks are successful, the pokemon is caught!
Note: Whenever any division is performed, the result is rounded down to a multiple of 1/4096. This is generally an insignificant detail, but it must be accounted for in your program.
Your challenge is to write a program that executes the shake checks and prints to stdout the status of the checks. On stdin, your program will receive (at least, details below) the maximum HP of the pokemon, the catch rate of the target pokemon, and the name of the pokeball. The maximum HP and the catch rate are both guaranteed to be integers, while the name of the pokeball is always a string. This input may come in any order and with any delimiting character(s) is convenient for you, so long as it's consistent. Assume that the input is correct, no error handling is required.
The names of the pokeballs you are required to support and their catch multipliers are listed here:
```
Poke | 1
Great | 1.5
Ultra | 2
Master | 255
```
You may assume that the target is asleep and at 1 HP. The expected format for output is this:
```
(First check failed)
(no output)
(Second check failed)
*shake*
(Third check failed)
*shake*
*shake*
*shake*
(All checks pass)
*shake*
*shake*
*shake*
Click!
```
(That isn't a typo, your program should never output just two shakes.)
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so your score is your program's source code's byte count. Lowest score wins.
# Bonuses!
I said that you *may* assume the pokemon is at 1 HP and asleep. Alternatively, you may allow the user to input the pokemon's current HP and `bonus_status`. The pokemon's current HP will always be an integer equal to or less than its maximum HP, and `bonus_status` will always be either 2.5, 1.5 or 1. If you do, you must have these values at the end of your input, and default to 1 and 2.5 if they're not supplied. You may subtract **15** points from your score for implementing one of these, or **25** for both.
Additionally, you may implement critical captures. If a critical capture occurs, only one shake test is performed. If failed, the program exits silently. If passed, it outputs:
```
*shake*
Click!
```
Critical captures become more common as the player collects more pokemon, but for simplicity's sake we can assume that they have already "caught 'em all". If a randomly generated number between 0 and 2047 is less than `a` (the result of the first calculation) multiplied by 2.5, that's a critical capture. Support for critical captures allows you to remove **25** points from your score.
There are a number of other pokeballs you may choose to support. Their names and catch multipliers are listed here:
```
Safari | 1.5
Sport | 1.5
Lure | 3
Net | 3
Dusk | 3.5
Dive | 3.5
Moon | 4
Fast | 4
Quick | 5
Love | 8
```
For each of these balls you add support for, you may subtract **(5 + the length of the ball's name)** from your score.
Finally, for kicks, achieving all of these bonuses (current HP and bonus\_status from stdin, critical captures, and all 10 optional balls) will net you an additional reward of **7** points removed from your score, for an even **150** total bonus.
# Example Input/Output
Just to ensure we're all on the same page.
```
$ ./balls <<< "19,Ultra,255"
*shake*
*shake*
*shake*
Click!
```
Good luck, and happy golfing!
[Answer]
# PYTHON 249 bytes - 75 for bonuses = 174
My first try ever golfing.
```
import sys,random
y=sys.argv
d,b,f={10:1,1:1.5,15:2,7:1.5,13:255,-2:3.5,6:3,8:3,0:4,11:5},3*int(y[1]),"*shake*\n"
s=lambda:random.random()*(255*b)**.25<65536*((b-2)*int(y[3])*d[ord(y[2][0])-70]*2.5)**.25
if s():print f*3+"Click!" if s()and s()else f
```
Bonus for including selected balls: Safari, Sport, Lure, Net, Dusk,
Dive, Fast, Quick
Giving me 8\*5+6+5+4+3+4+4+4+5=75 bonus points
[edit] Round down to 12 fractional bits every time division is used by not using it
[edit2] optimize pokeball dictionary
[Answer]
# Perl 1 (374 - 150 = 224 + MissingNo. bytes)
```
sub h{print "*shake*
";}($x,$h,$_,$c,$s)=split(/,/,<>);$G=$$%(/P/?256:/U/?151:201);$S=$G-($s==1?0:$s==1.5?12:25);
$F=255&int(int($h*255/(/G|S/?8:12))/(int($x/4)||1));sub c{for($i=0;$i<3;$i++){do h();}print "Click!
";exit;}
/M/||$S<0||$S<$c&&$F>$$*$$%255&&do c();$W=int(int($c*100/(/P/?255:/U/?150:200))*$F/255)+($s==1?0:$s==1.5?5:10);$W>9&&do h();$W>29&&do h();$W>69&&do h();
```
Argument list:
```
current hp, max hp, pokéball, catch rate, status, critical capture
```
Yes, I'm aware this completely breaks the rules, but I don't care. In case you haven't noticed, this is first Pokémon generation capture algorithm, with all its quirks (Great Balls are better than Ultra Balls, in certain conditions). This implements all features, including ones that aren't included (and I decided to include points for them anyway). Critical captures are ignored (but they are implemented - just that they don't affect the capture rate), newer Poké Balls load data of other Poké Balls.
Please note that while this answer is short, it breaks all the rules, so consider it just to be a fun answer, don't accept it. I was initially going to implement Gen5 algorithm in Perl 5, but I decided - why not have some fun. And yes, I actually compiled Perl 1, and this code works. If you run it in newer version of Perl, you may get warnings about deprecated use of `do`, but let's be honest - it's the only way to run functions in Perl 1. Perl 1 also has some quirks on its own (for example, I cannot move the line starting with `/M/` to previous line - why? - I don't know).
Also, there are no random numbers in Perl 1, so hope you won't kill me for modulo of `$$`. It's the closest thing to the random number I could have found.
Edit: It appears that the old `do call()` syntax was removed in Perl 5.19.8. Make sure you use an older version of Perl to run this script, as it appears that Perl 5.20 won't be compatible with Perl 1 scripts.
[Answer]
# PHP (~~746~~ 763 bytes - all bonuses):
```
<?if(!$i=fgets(STDIN))die('');parse_str($i,$i);$b=array('poke'=>1,'great'=>1.5,'ultra'=>2,'master'=>255,'safari'=>1.5,'sport'=>1.5,'lure'=>3,'net'=>3,'dusk'=>3.5,'dive'=>3.5,'moon'=>4,'fast'=>4,'quick'=>5,'love'=>8);$s=array('sleep'=>2.5,'frozen'=>2.5,'paralyzed'=>1.5,'poisoned'=>1.5,'burnt'=>1.5,''=>1);$i=array_merge(array('ball'=>'poke','hp'=>array('max'=>25,'current'=>1),'status'=>2.5,'rate'=>255),$i);$l='strtolower';$r='mt_rand';$x='*shake*'.PHP_EOL;$c='Click!'.PHP_EOL;$a=(((3*$i[hp][max])-(2*$i[hp][current]))*$i[rate]*$b[$l($i[ball])])/(3*$i[hp][max])*(is_numeric($i[status])?$i[status]:$s[$l($i[status])]);$a=((pow(65536/(255/$a),0.25)*4096)<<0)/4096;if($r(0,1)>$a)die();echo$x;if($a>1)die($c);if($r(0,1)>$a)die();echo$x,$x;if($r(0,1)>$a)die();echo$c;
```
To use this, you have to provide the input as 'ball=poke&status=sleep' on STDIN.
The HP must be provided as 'hp[max]' or 'hp[current]'.
This code works, [as tested here](http://ideone.com/9FknU1).
You can provide the status by it's name or the multiplier. (**not required in the question**).
Here is a readable version:
```
if(!$info=fgets(STDIN))die('');
parse_str($info,$info);
$balls=array(//list of pokeballs
'poke'=>1,
'great'=>1.5,
'ultra'=>2,
'master'=>255,
'safari'=>1.5,
'sport'=>1.5,
'lure'=>3,
'net'=>3,
'dusk'=>3.5,
'dive'=>3.5,
'moon'=>4,
'fast'=>4,
'quick'=>5,
'love'=>8
);
$status=array(//list of status
'sleep'=>2.5,
'frozen'=>2.5,
'paralyzed'=>1.5,
'poisoned'=>1.5,
'burnt'=>1.5,
''=>1 //in case there is no status
);
$info=array_merge(//this will set the default values
array(
'ball'=>'poke',
'hp'=>array('max'=>25,'current'=>1),
'status'=>2.5,
'rate'=>255
),
$info
);
$a=(((3*$info['hp']['max'])-(2*$info['hp']['current']))*$info['rate']*$balls[strtolower($info['ball'])])/(3*$info['hp']['max'])*(is_numeric($info['status'])?$info['status']:$status[strtolower($info['status'])]);
$a=((pow(65536/(255/$a),0.25)*4096)<<0)/4096;//same as $a=floor(pow(65536/(255/$a),0.25)*4096)/4096;
if(mt_rand(0,1)>$a) die();//test 1
echo '*shake*',PHP_EOL;
if($a>1)die('Click!'.PHP_EOL);//if $a>1, catch it (critical catch)
if(mt_rand(0,1)>$a) die();//test 2
echo'*shake*',PHP_EOL,'*shake*',PHP_EOL;
if(mt_rand(0,1)>$a) die();//test 3
echo 'Click!',PHP_EOL;//passed all tests
```
I had to edit this because i was using a much higher precision than the required.
The fix was provided by [TheConstructor](https://codegolf.stackexchange.com/users/16293/theconstructor).
[Answer]
## J 301-150 = 151
For sports, all bonuses implemented, though I'd probably be better off not to :).
I shortly explained things below, but this one is far too long to explain in detail, unless someone explicitly requests.
It implements all balls, critical captures, and optional inputs.
```
tm =: =*./@:+.' '=] NB. Template match, match non-blanks in right with left
balls =: 'MMLLPGSUNDFQ',.12{.'oauo' NB. space = wildcard.
NB. lookup function: name -> bonus_ball
lookup =: 4 255 3 8 1 1.5 1.5 2 3 3.5 4 5 #~ (tm"1&balls)@(2&{.)
NB. convert given option
options =: ;".`lookup@.(_=_&".);._2 ,&',' i3 NB. parse options to numeric values
NB. add defaults if necessary
complete =: (, 1 2.5{.~(5-$)) options
NB. formula
r=: <.&.(*&4096) NB. round to 1/4096
NB. a=: ((3*zeroth - 2*thirth)*first*second*fourth)/(3*zeroth)
a=:r(1-3%~2*%/3 0{complete)**/1 2 4{complete NB. A prime, already divided by 255
NB. Critical captures
crit =: >2r5*[:?11^~2: NB. check for critical, k a
mess =: 2 7$'*shake*Click! '"_ NB. Message template
check =: >"0 [:?(4$2^16)"_ NB. Perform 4 checks
mes2 =: mess#~3(<.,<)] NB. Construct message from number of passed checks
NB. If critical, just output the message array, else do the 4 tests, and execute mes2 on their running and (meaning count the number of uninterrupted trues)
echo mes2@(+/)@(*./\)@(check"0)@(65536%4%:[:r 255%])`[[email protected]](/cdn-cgi/l/email-protection) a
```
Here the golfed version
```
NB. Golfed verion
echo(m#~3(<.,<)])@(+/)@(*./\)@(>"0[:?(4$2^16)"_)@(65536%4%:[:r 255%])`(m=:2 7$'*shake*Click! '"_)@.(>2r5*[:?11^~2:)(r=:<.&.(*&4096))(1-3%~2*%/3 0{co)**/1 2 4{co=:(,1 2.5{.~(5-$));(".`(4 255 3 8 1 1.5 1.5 2 3 3.5 4 5 #~((=*./@:+.' '=])"1)&('MMLLPGSUNDFQ',.12{.'oauo')@(2&{.)))@.(_=_&".);._2,&','stdin''
```
[Answer]
# Java, 611
```
import java.util.*;class P{enum B{DI(35),DU(35),FA(40),GR(15),LO(80),LU(30),MA(2550),MO(40),NE(30),PO(10),QU(50),SA(15),SP(15),UL(20);long v;B(int i){v=((long)i<<12)/(long)10;}}public static void main(String[]y){Scanner s=new Scanner(System.in);B b=B.valueOf(s.next().toUpperCase().substring(0,2));long c=(long)(s.nextDouble()*4096);long m=s.nextLong()<<12;long h=(s.hasNextInt()?s.nextLong():1)<<12;long S=(long)((s.hasNextDouble()?s.nextDouble():2.5)*4096);long p=(65536L<<12)/(long)(Math.sqrt(Math.sqrt((255L<<24)/((((3L*m-2L*h)*c>>12)*b.v>>12<<12)/(3L*m)*S>>12)))*512);Random r=new Random();System.out.print(r.nextInt(65536)<p?"*shake*\n"+(r.nextInt(65536)<p?"*shake*\n*shake*\n"+(r.nextInt(65536)<p?"Click!\n":""):""):"");}}
```
Score:
* 729 Bytes
* -93 all Balls
* -25 optional current\_hp and bonus\_state
=> 611
The program uses fixed-point-arithmetics with 12 fraction-bits (`1/4096` is the value of the right most bit). As Java does not usually use fixed-point there are quite some shifts inside the code to achieve the expected results. See long version for the used arithmetic functions, which have been inlined for golfing purposes.
While most calculations could have been done on `int` values, divisions work better with `long`s as you need to shift the dividend by another 12 bit to the left to keep the desired precision (otherwise you loose all fraction-bits).
Sample input ( `;` is only required if run interactively i.e. STDIN has not received EOF): Ball, catch\_rate, max\_hp
>
>
> ```
> Poke 15 255 ;
>
> ```
>
>
Sample output:
>
>
> ```
> *shake*
>
> ```
>
>
Sample input: Ball, catch\_rate, max\_hp, current\_hp, bonus\_state
>
>
> ```
> Moon 42 255 50 1.5
>
> ```
>
>
Sample output:
>
>
> ```
> *shake*
> *shake*
> *shake*
> Click!
>
> ```
>
>
```
import java.math.BigDecimal;
import java.util.Random;
import java.util.Scanner;
class Pokeball {
static long shift(long i) {
return i << 12;
}
enum B {
DI(35),DU(35),FA(40),GR(15),LO(80),LU(30),MA(2550),MO(40),NE(30),PO(10),QU(50),SA(15),SP(15),UL(20);
long v;
B(int i) {
v = semiFixedDivision(shift(i),10);
}
}
public static void main(String[] args) {
final Scanner s = new Scanner(System.in);
B b = B.valueOf(s.next().toUpperCase().substring(0, 2));
long catchRate = (long) (s.nextDouble() * 4096);
long maxHp = shift(s.nextLong());
long currentHp = shift(s.hasNextInt()?s.nextInt():1);
long statusBonus = (long) ((s.hasNextDouble()?s.nextDouble():2.5) * 4096);
long a = fixedMultiplication(fixedDivision(fixedMultiplication(fixedMultiplication(
semiFixedMultiplication(3, maxHp) - semiFixedMultiplication(2, currentHp), catchRate), b.v),
semiFixedMultiplication(3, maxHp)), statusBonus);
println("a=",a);
long x = fixedFourthRoot(fixedDivision(shift(255), a));
println("x=",x);
println("x^4=",fixedMultiplication(fixedMultiplication(x,x), fixedMultiplication(x,x)));
long p = semiFixedDivision(shift(65536), fixedFourthRoot(fixedDivision(shift(255), a)));
Random r = new Random();
System.out.print(r.nextInt(65536) < p ?
"*shake*\n" + (r.nextInt(65536) < p ?
"*shake*\n*shake*\n" + (r.nextInt(65536) < p ?
"Click!\n" :
"") :
"") :
"");
}
private static long unshift(long p) {
return p >> 12;
}
private static void println(String s, long v) {
System.out.print(s);
println(v);
}
private static void println(long v) {
System.out.printf("%s%n", BigDecimal.valueOf(v).divide(BigDecimal.valueOf(4096)));
}
/**
* Calculates division of {@code a/b} with both number last 12 bits treated as being "right of the dot"
*/
static long fixedDivision(long a, long b) {
return (a<<12)/b;
}
/**
* Calculates division of {@code a/b} with {@code a}'s last 12 bits treated as being "right of the dot"
*/
static long semiFixedDivision(long a, long b) {
return a/b;
}
static long fixedMultiplication(long a, long b) {
return (a*b) >> 12;
}
static long semiFixedMultiplication(long a, long b) {
return a*b;
}
static long fixedFourthRoot(long a) {
return (long)(Math.sqrt(Math.sqrt(a)) * 512);
}
}
```
[Answer]
# CoffeeScript - ~~317~~ ~~313~~ ~~310~~ ~~307~~ ~~306~~ ~~294~~ ~~270~~ ~~250~~ 242 bytes
**342 - 25** (parameters) **- 75** (12 balls) **= 242**
```
_=process.stdin
l=console.log
m=Math
s=m.sqrt
t=['*shake*','Click!']
n=65536
_.resume()
_.setEncoding 'utf8'
_.on 'data',(d)=>
[A,B,C,E,F]=d.match /\w+/g;E||=1;F||=2.5;i=0;while i++<3
if n*(s s (3*A-2*E)*B*{P:1,G:1.5,U:2,M:255,S:1.5,L:3,N:3,D:3.5,F:4,Q:5}[C.charAt 0]*F)<m.floor(m.random()*n)*s s 765*A
break
l t[0]
if i>2
l t[i-3]
```
Expects input `HP_max,Rate,Ball[,HP_current[,status]]`. Does not support `Moon` or `Love` balls.
This is the first thing I ever golfed that's not a regex, so there is probably room for improvement. I've shamelessly copied the idea to store only partial ball names. ;) Supporting the other two balls is simply not worth it, not even with the additional **+7** for getting all bonuses.
## Ungolfed version
This version omits all the short aliases I define at the beginning, but does define the ball-lookup separately.
```
balls =
P: 1
G: 1.5
U: 2
M: 255
S: 1.5
L: 3
N: 3
D: 3.5
F: 4
Q: 5
messages = ['*shake*', 'Click!']
process.stdin.resume()
process.stdin.setEncoding 'utf8'
process.stdin.on 'data', (data) =>
[HP_max, rate, ball, HP_current, status] = data.match /\w+/g
HP_current ||= 1
HP_status ||= 2.5
i = 0
while i++ < 3
if 65536 * (Math.sqrt Math.sqrt (3*HP_max - 2*HP_current)*rate*status*balls[ball.charAt 0]) < Math.floor(Math.random()*65536) * Math.sqrt Math.sqrt 765*HP_max
break
console.log messages[0]
if i > 2
console.log messages[i-3]
```
A note on the probability formula: I've rearranged the full formula (with written out `a`) so that there are no divisions, and I'm computing `(...)^(1/4)` by taking the square root twice.
[Answer]
Update: (C#)
Byte count: 3,600
Critcal: -25
All poke-balls: -91
---
Total = 3,484
[golfed]
```
using System;using System.Text;using System.Security.Cryptography;using System.Linq;namespace Pokemon{public class MainClass{private string[] c(string[] i){if(i.Length <= 3){var v1 =i[0][0];var v2 =i[1][0];var v3 =i[2][0];if(v1>='0'&&v1<='9'&&v2>='a'&&v2<='z'&&v3>='0'&&v3<='9')return new string[]{i[0],i[2],i[1]};else if(v1>='0'&&v1<='9'&&v2>='0'&&v2<='9'&&v3>='a'&&v3<='z')return new string[]{i[0],i[1],i[2]};else if(v1>='a'&&v1<='z'&&v2>='0'&&v2<='9'&&v3>='0'&&v3<='9')return new string[]{i[1],i[2],i[0]};else return null;}else return null;}private static void Main(string[] args){while(true){Console.Clear();MainClass _c = new MainClass();Console.Write("Inputs'please:");var i = Console.ReadLine().ToLower();string[] r = _c.c((string[])(i.Split(new Char[]{' ','.',',','\n','\t','!','@','#','$','%','^','&','&','*','(',')','-','_','+','=','?','/','\\'},StringSplitOptions.RemoveEmptyEntries).Select(p=>p.Trim()).ToList()).ToArray());new w("Processing...\n");if(r== null)new w("Too many errors");else new m(r);}}}public class w{public w(string l){Console.WriteLine(l);}}public class m{public m(string[] v){switch (v[2].Substring(0,2)){case "po":c(v[0],v[1],"1");break;case "ul":c(v[0],v[1],"2");break;case "ma":c(v[0],v[1],"255");break;case "gr":case "sa":case "sp":c(v[0],v[1],"1.5");break;case "lu":case "ne":c(v[0],v[1],"3");break;case "du":case "di":c(v[0],v[1],"3.5");break;case "mo":case "fa":c(v[0],v[1],"4");break;case "qu":c(v[0],v[1],"5");break;case "lo":c(v[0],v[1],"8");break;default:new w("Not supported");break;}}private double y(double v){return Convert.ToDouble(((double)1/(double)4096)*(v/Convert.ToDouble(1/4096)-(v%Convert.ToDouble(1/4096))));}private bool i(double v,double r,double b){if(((double)new Random().Next(0,(int)r))>b*v)return true;else return false;}private double f(double r, double h, double b){return 2.5*y((((3.0*h)-2.0)*r*b)/(3.0*h));}private void c(params string[] v){var s =0.0;var x =0;if(int.Parse(v[1])>100&&int.Parse(v[1])<= 255){s =f(double.Parse(v[0]),double.Parse(v[1]),double.Parse(v[2]));x=0;}else if(int.Parse(v[0])>100&&int.Parse(v[0])<= 255){s =f(double.Parse(v[1]),double.Parse(v[0]),double.Parse(v[2]));x=1;}else{new w(String.Format("Which number is the Max HP? :{0} or {1}:",v[0],v[1]));var c_ = int.Parse(Console.ReadLine());s =f((double.Parse(v[0])+double.Parse(v[1]))-double.Parse(v[c_]),double.Parse(v[c_]),double.Parse(v[2]));x=2;}if(((double)new Random().Next(0, 2047))<s*2.5)new w("*shake*\nClick!");else{for(int c_= 0;c_<3;c_++){new w("*shake*");var r =Math.Pow(65536.0/y(255.0/s),0.25);if(i(r,double.Parse(v[x]),2.5)==true){new w("Click!");break;}else;}}Console.ReadKey();}}}
```
[regular]
```
using System;
using System.Text;
using System.Security.Cryptography;
using System.Linq;
namespace Pokemon
{
public class MainClass
{
private string[] c(string[] i)
{
if (i.Length <= 3)
{
var v1 =i[0][0];
var v2 =i[1][0];
var v3 =i[2][0];
if(v1>='0'&&v1<='9'&&v2>='a'&&v2<='z'&&v3>='0'&&v3<='9')return new string[]{i[0],i[2],i[1]};
else if(v1>='0'&&v1<='9'&&v2>='0'&&v2<='9'&&v3>='a'&&v3<='z')return new string[]{i[0],i[1],i[2]};
else if(v1>='a'&&v1<='z'&&v2>='0'&&v2<='9'&&v3>='0'&&v3<='9')return new string[]{i[1],i[2],i[0]};
else return null;
}
else return null;
}
private static void Main(string[] args)
{
while(true)
{
Console.Clear();
MainClass _c = new MainClass();
Console.Write("Inputs'please:");
var i = Console.ReadLine().ToLower();
string[] r = _c.c((string[])(i.Split(new Char[]{' ','.',',','\n','\t','!','@','#','$','%','^','&','&','*','(',')','-','_','+','=','?','/','\\'},StringSplitOptions.RemoveEmptyEntries).Select(p=>p.Trim()).ToList()).ToArray());
new w("Processing...\n");
if(r== null)new w("Too many errors");
else new m(r);
}
}
}
public class w
{
public w(string l)
{
Console.WriteLine(l);
}
}
public class m
{
public m(string[] v)
{
switch (v[2].Substring(0,2))
{
case "po":
c(v[0],v[1],"1");
break;
case "ul":
c(v[0],v[1],"2");
break;
case "ma":
c(v[0],v[1],"255");
break;
case "gr":
case "sa":
case "sp":
c(v[0],v[1],"1.5");
break;
case "lu":
case "ne":
c(v[0],v[1],"3");
break;
case "du":
case "di":
c(v[0],v[1],"3.5");
break;
case "mo":
case "fa":
c(v[0],v[1],"4");
break;
case "qu":
c(v[0],v[1],"5");
break;
case "lo":
c(v[0],v[1],"8");
break;
default:
new w("Not supported");
break;
}
}
private double y(double v){return Convert.ToDouble(((double)1/(double)4096)*(v/Convert.ToDouble(1/4096)-(v%Convert.ToDouble(1/4096))));}
private bool i(double v,double r,double b){if(((double)new Random().Next(0,(int)r))>b*v)return true;else return false;}
private double f(double r, double h, double b){return 2.5*y((((3.0*h)-2.0)*r*b)/(3.0*h));}
private void c(params string[] v)
{
var s =0.0;
var x =0;
if(int.Parse(v[1])>100&&int.Parse(v[1])<= 255){s =f(double.Parse(v[0]),double.Parse(v[1]),double.Parse(v[2]));x=0;}
else if(int.Parse(v[0])>100&&int.Parse(v[0])<= 255){s =f(double.Parse(v[1]),double.Parse(v[0]),double.Parse(v[2]));x=1;}
else
{
new w(String.Format("Which number is the Max HP? :{0} or {1}:",v[0],v[1]));
var c_ = int.Parse(Console.ReadLine());
s =f((double.Parse(v[0])+double.Parse(v[1]))-double.Parse(v[c_]),double.Parse(v[c_]),double.Parse(v[2]));
x=2;
}
if (((double)new Random().Next(0, 2047))<s*2.5)new w("*shake*\nClick!");
else
{
for(int c_= 0;c_<3;c_++)
{
new w("*shake*");
var r =Math.Pow(65536.0/y(255.0/s),0.25);
if (i(r,double.Parse(v[x]),2.5)==true){new w("Click!");break;}else;
}
}
Console.ReadKey();
}
}
}
```
] |
[Question]
[
[pannenkoek2012](https://en.wikipedia.org/wiki/Pannenkoek2012) aims to complete [Super Mario 64](https://en.wikipedia.org/wiki/Super_Mario_64) with as few presses as possible of the A button, which makes Mario jump. Each "A press" consists of three parts:
* Pressing the button
* Holding it for any length of time
* Releasing it
[](https://i.stack.imgur.com/SNVOT.png)
See [this video (1:15 - 3:23)](https://youtu.be/kpk2tdsPh0A?t=75) for a great explanation that includes the above image. (However, this challenge will not use the half-A-press terminology and will posit obstacles that require releasing A.)
**Task:**
Given a sequence of obstacles requiring pressing (P), holding (H), or releasing (R) the A button, output the smallest number of presses required to overcome them in the order given. The A button is initially not held.
Stated formally: given a string S of characters `PHR`, consider strings of form `(PH*R)*` that contain S as a subsequence, and output the smallest possible number of `P`'s in such a string. Or, alternatively, find the smallest number of chunks of the form `P?H*R?` that S can be split into.
**Example**
Let's look at input `RHRPHHHR`. The A button starts not held, so overcoming the initial obstacle `R` requires the button be pressed and then released (press #1). Next we are required to hold the button `H`, which again requires it first be pressed (press #2). Then, it can then be released afterwards to satisfy the `R` after it. Finally, the remaining `PHHHR` can be satisfied by a single press (press #3) followed by holding `HHH` and releasing `R`. So, the output count is 3.
Another way to see it, is that we can split the input string into 3 parts of form `PHH..HHR` where letters may be omitted.
```
R
HR
PHHHR
```
**Input format**
The input will be a list or string of elements representing press, hold, and release as your choice of:
* `P, H, R`
* `p, h, r`
* `1, 2, 3`
* `0, 1, 2`
matched in the order given. The input will not be empty.
**Test cases:**
```
P 1
H 1
R 1
HP 2
RHP 3
HHR 1
PHRH 2
RHRPHHHR 3
HHHHHH 1
PPRRHHPP 6
HPPRHRPRHPPRHPPHRP 12
PRHRHPHHPRRRHPPRHHPPRRRHRHPRPHPRPRHHRPPPRHPRP 28
```
**Leaderboard:**
```
var QUESTION_ID=152701,OVERRIDE_USER=20260;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/152701/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```
```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```
[Answer]
# [Retina](https://github.com/m-ender/retina), 9 bytes
```
1>`P?H*R?
```
[Try it online!](https://tio.run/##K0otycxL/P/f0C4hwN5DK8j@//@AII8gjwAPj4CgICAN5IGIILBgUAAIA0WCAkASQDYA "Retina – Try It Online")
[Answer]
# [Pyth](https://pyth.readthedocs.io), 13 bytes
```
tl:z"P?H*R?"3
```
**[Try it here!](http://pyth.herokuapp.com/?code=tl%3Az%22P%3FH%2aR%3F%223&input=PRHRHPHHPRRRHPPRHHPPRRRHRHPRPHPRPRHHRPPPRHPRP&debug=0)** or **[Verify all the test cases.](https://pyth.herokuapp.com/?code=tl%3Az%22P%3FH%2aR%3F%223&input=PRHRHPHHPRRRHPPRHHPPRRRHRHPRPHPRPRHHRPPPRHPRP&test_suite=1&test_suite_input=P%0AH%0AR%0AHP%0ARHP%0AHHR%0APHRH%0ARHRPHHHR%0AHHHHHH%0APPRRHHPP%0AHPPRHRPRHPPRHPPHRP%0APRHRHPHHPRRRHPPRHHPPRRRHRHPRPHPRPRHHRPPPRHPRP&debug=0)**
Note that `1` also works in place of `3`.
### How it works?
```
tl:z"P?H*R?"3 | Full program. Takes input from STDIN, outputs to STDOUT.
:z 3 | Split the input string on matches of...
"P?H*R?" | The regular expression "P?H*R?".
l | Get the length.
t | Decrement (because splitting includes the empty string).
```
**More about the regex:**
```
P? | P – The literal character P, case sensitive.
| ? – Quantifier. Matches either one or zero times the previous character.
H* | H – The literal character H, case sensitive.
| * – Quantifier. Matches any number of occurrences of the previous character.
R? | R – The literal character R, case sensitive.
| ? – Quantifier. Matches either one or zero times the previous character.
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes
```
o5ḄƝ%⁵>4S‘
```
A monadic chain taking a list (the `P,H,R : 0,1,2` option) and returning an integer, the count.
**[Try it online!](https://tio.run/##y0rNyan8/z/f9OGOlmNzVR81brUzCX7UMOP////RBjpGOoZgbADEINIIDEEsiByMZYSk0gisGkJD1BiBVRkg5GMB "Jelly – Try It Online")** or see the [test-suite](https://tio.run/##JYwxCgJRDET7nENvoK1YDtgMsfIAFsqCtd1XhL2CgnsDSwVBu0XvsbnId/43kEky88h23TT7nHfT4Xn6duM4PGaTZaRz3szjeIt0JTxSF@nStza87p933yoYLSSrnGkwN9BcDbgJlwMnyoVaRroDFKFNmddJsbRiQLSQv13Eq6knLLCwyjt/)
### How?
Effectively works by getting all adjacent pairs then counting any that are not "continuation pairs" (`PR`, `PH`, `HR`, or `HH`) and adding one.
```
o5ḄƝ%⁵>4S‘ - Link: list of integers (in [0,1,2]) e.g.: [0,0,1,0,2,1,1,2,2,0] (representing PPHPRHHRRP)
o5 - logical OR with 5 [5,5,1,5,2,1,1,2,2,5]
Ɲ - for all adjacent pairs: i.e.: [5,5],[5,1],[1,5],[5,2],[2,1],[1,1],[1,2],[2,2],[2,5]
Ḅ - convert from binary [ 15 , 11 , 7 , 12 , 5 , 3 , 4 , 6 , 9 ]
⁵ - literal ten
% - modulo [ 5 , 1 , 7 , 2, 5 , 3 , 4 , 6 , 9 ]
>4 - greater than four? [ 1 , 0 , 1 , 0, 1 , 0 , 0 , 1 , 1 ]
S - sum 5
‘ - increment 6
```
---
Previous 11 byte solution:
```
ḅ3Ɲạ3ḟ1,2L‘
```
[Try it online!](https://tio.run/##y0rNyan8///hjlbjY3Mf7lpo/HDHfEMdI59HDTP@//8fbaBjpGMIxgZADCKNwBDEgsjBWEZIKo3AqiE0RI0RWJUBQj4WAA "Jelly – Try It Online") or see the [test-suite](https://tio.run/##JYwxCgJBDEX7nMPSRvcClh@0@KTzABbKXsBuEGSvoOAi9pYWi9oteo@Zi4x/xkB@kv8f2W3adp9zHI7Nt4/PWxOH62w6X6VwyttFOtxTuBCeQp/Ceewsvh6f99gpmCwl65xpMDfQXA24CZcDJ8qFWka6AxShTZnXSbG0YkC0kL9dxKupJyywsMo7fw "Jelly – Try It Online")
### How?
Works like the above, but in a completely different way...
```
ḅ3Ɲạ3ḟ1,2L‘ - Link: list of integers (in [0,1,2]) e.g.: [0,0,1,0,2,1,1,2,2,0] (representing PPHPRHHRRP)
Ɲ - for all adjacent pairs: i.e.: [0,0],[0,1],[1,0],[0,2],[2,1],[1,1],[1,2],[2,2],[2,0]
ḅ3 - convert from base three [ 0 , 1 , 3 , 2 , 7 , 4 , 5 , 8 , 6 ]
ạ3 - absolute difference with three [ 3 , 2 , 0 , 1 , 4 , 1 , 2 , 5 , 3 ]
ḟ1,2 - filter discard if in [1,2] [ 3 , 0 , 4 , 5 , 3 ]
L - length 5
‘ - increment 6
```
and another, again quite different:
```
+19*Ɲ%13ḂS‘
```
(add 19 to each, then for adjacent pairs perform exponentiation, modulo by 13, modulo by 2, sum and add one).
[Answer]
## Batch, 69 bytes
```
@set/ab=2,n=0
@for %%b in (%*)do @set/an+=b/2^|!%%b,b=%%b
@echo %n%
```
Takes input as a list of 0-indexed command-line parameters, but you can use a list of letters `p, h, r` in either upper or lower case if you type `set /a p=0, h=1, r=2` first. Explanation: `b` maintains the last input (defaulting to `2` for released) and `n` the count of presses. Each input adds a press if the last input was a release or the current input is a press.
[Answer]
# Python 2, 44 bytes
Uses P->1 H->2 R->3
```
lambda a:sum(1/y|x/3for x,y in zip([3]+a,a))
```
[Answer]
# [Deorst](https://github.com/cairdcoinheringaahing/Deorst), 11 bytes
```
'P?H*R?'ggL
```
[Try it online!](https://tio.run/##S0nNLyou@f9fPcDeQyvIXj093QfECfII8gjw8AgICgLSQB6ICAILBgWAMFAkKAAkAWSrAwA "Deorst – Try It Online")
Uses [Mr. Xcoder's](https://codegolf.stackexchange.com/a/152702/66833) regex
[Answer]
# Japt, 11 bytes
```
è"P?H*R?" É
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=6CJQP0gqUj8iIMk=&input=IlBSSFJIUEhIUFJSUkhQUFJISFBQUlJSSFJIUFJQSFBSUFJISFJQUFBSSFBSUCI=) | [Check all test cases](https://ethproductions.github.io/japt/?v=1.4.5&code=rugiUD9IKlI/IiDJ&input=WyJQIiwiSCIsIlIiLCJIUCIsIlJIUCIsIkhIUiIsIlBIUkgiLCJSSFJQSEhIUiIsIkhISEhISCIsIlBQUlJISFBQIiwiSFBQUkhSUFJIUFBSSFBQSFJQIiwiUFJIUkhQSEhQUlJSSFBQUkhIUFBSUlJIUkhQUlBIUFJQUkhIUlBQUFJIUFJQIl0=)
`è` counts the number of matches of the RegEx in the input and `É` subtracts 1.
[Answer]
# [Python 2](https://docs.python.org/2/), 48 bytes
```
f=lambda a,*l:l==()or(a>l[0]or l[0]==a!=1)+f(*l)
```
[Try it online!](https://tio.run/##JY5BD8IgDIXv@xV4ApQY9biknnskvRoPmLm4jLFlWxb99dgyEvrge6/Q6bd@xnTLuYUYhlcTVHDHWEcAY8fZhHt8XJ7jrEQAwgGu9tSaY7R5Ae2108ibROVCpSIK8EjFQ/K4EyxLLE@E6EuWz5ygop57BApC7uLYbkihAvkxL3EOlg7OV1XLA26qS2qpK6V6GMJk5H997lLz/rrNMp7mLq1qczx9b/Mf "Python 2 – Try It Online")
Takes `0,1,2` as input.
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~6~~ 5 bytes
```
Lġo&ε
```
[Try it online!](https://tio.run/##JYyxDcJADEV7TxGlQMkmv6D4@lNEQhFFxACkoGYFetpkgIiaIW4R8@@w5LP9/M7TbblkNw9LWe/zUB7Psr57Qv04HnueP6/r6btlJgOhAENOQGHHBCLqhBZBSgBtuPNOrdIuu6gE1u38eX3UoK@w2vbaB/EH "Husk – Try It Online")
Input is a list over `0,1,2` (the TIO link uses letters for easier copy-pasting of test cases).
## Explanation
I use the same general idea as [Jonathan Allan's Jelly answer](https://codegolf.stackexchange.com/a/152714/32014): split on occurrences of the "discontinuity pairs" PP, HP, RH, RR and RP, and count the resulting blocks.
In the 0,1,2 encoding, these pairs are exactly those whose left element is 2 or right element is 0.
```
Lġo&ε Input is a list.
ġ Split between pairs that do not satisfy:
ε the left element is at most 1
o& and the right element is truthy.
L Length.
```
[Answer]
# Javascript (ES6), 30 bytes
```
f=s=>s.match(/P?H*R?/g).length-1
```
```
<input id=i oninput="o.innerText=f(i.value)" value="PHHR"><pre id=o>l
```
[Answer]
# [Haskell](https://www.haskell.org/), 36 bytes
```
f a=sum[1|(x,y)<-zip(2:a)a,x>1||y<1]
```
[Try it online!](https://tio.run/##ZU5BCoNADLz3FTn0oJDCJsei/Yh4WKjSpWqltqBl/761Sw1qmGFJNpPJ3Oxwr5omhBpsPrzbgnwy4pRmp4/rEz7b1OJ4Ie@njMrQWtdBDtfHAaB/uu4FR6ihYBSU2wmhYDcxKFATmMmRFPn7UcYgOoqv1EbVf4G@I8u06Gh1XNutW1brvJiYbSDJt0sWM4Uv "Haskell – Try It Online")
Uses the `0,1,2` encoding.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Cde-page)
```
Pn1></µƝS‘
```
[Try it online!](https://tio.run/##y0rNyan8/z8gz9DORv/Q1mNzgx81zPj//3@0gY6RjiEYGwAxiDQCQxALIgdjGSGpNAKrhtAQNUZgVQYI@VgA "Jelly – Try It Online") or [Test suite!](https://tio.run/##JYw9CgJRDIT7nMNe7EUsB7YZYuUBLFwWe7uHzV5Bwb2BpVZa7aL3MBd5znsG8jfzJe2u644587BYLefj4zNsIp3zfh2nW6Qr4ZGGSJept@/z/n5NvYxZo7LVkcHcQHMl4CZcCpwoG2oY6Q5QhCZ5XjvF0ooA0UL@cileRT1hgYVV3vkD) (~~Stolen~~ Borrowed from Jonathan.)
**Alternative:**
```
P=1=</µƝS‘
```
[Try it online!](https://tio.run/##JYy9DcJQDIR7z0GP0hOJ8qQ0J1MxAAVRFqB7oskKIJENKKGCigj2wIs87j0s@e/us/vdMBxyZtu0q@Xr/pk2kU55v47jNdKF8EhTpPM82vdxez/nUcaiU9nqyGBuoLkScBMuBU6UDTWMdAcoQpM8r51iaUWAaCF/uRSvop6wwMIq7/wB "Jelly – Try It Online")
```
Pn1></µƝS‘ | Monadic chain.
µƝ | Map over each pair of "neighbours" (x, y) in the list.
P | And check whether their product...
n1 | ... 1 if it doesn't equal 1, 0 otherwise...
> | Is higher than?
</ | The pair reduced by "Smaller than?". 1 if x < y, else 0.
S | Sum.
‘ | Add 1.
```
---
### [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes
Saved 1 byte with help from caird coinheringaahing.
```
ḅ3Ɲf⁽vḲD¤L‘
```
[Try it online!](https://tio.run/##JYwxCgJBDEX7nMMbeAELi4AWn3QeQEHZWrAbBdkrKLidpZVYLOxu46L3mFxk/DMG8pP8/8huXVWHlGJ7nn6bjR@HfWyf8/d96eGStjM/PTzcoOah8XAda4nd69OPNYPJgrJKCaJiohBjq5oQp6MGzZeWEsBMFSS4MbMyQRaSDSVN5G9nsWLyCTJMrPCGHw "Jelly – Try It Online")
[Answer]
# [Kotlin](https://kotlinlang.org), 36 bytes
```
Regex("P?H*R?").findAll(i).count()-1
```
## Beautified
```
Regex("P?H*R?").findAll(i).count()-1
```
## Test
```
fun f(i:String) =
Regex("P?H*R?").findAll(i).count()-1
data class Test(val input: String, val output: Int)
val TESTS = listOf(
Test("P", 1),
Test("H", 1),
Test("R", 1),
Test("HP", 2),
Test("RHP", 3),
Test("HHR", 1),
Test("PHRH", 2),
Test("RHRPHHHR", 3),
Test("HHHHHH", 1),
Test("PPRRHHPP", 6),
Test("HPPRHRPRHPPRHPPHRP", 12),
Test("PRHRHPHHPRRRHPPRHHPPRRRHRHPRPHPRPRHHRPPPRHPRP", 28)
)
fun main(args: Array<String>) {
for ((input, expectded) in TESTS) {
val actual = f(input)
if (actual != expectded) {
throw AssertionError("$input $expectded $actual")
}
}
}
```
## TIO
[TryItOnline](https://tio.run/##dZLfSsMwFMbv+xTHsotE6mATRIp17GIQrwzZXiC06QzWZCSpTmTPXvNnbuLquUjgy3d+59Cvr9p1Ug1Z1vYKWiTLtTNSbTFUAxNbsUc5XZBrtsjxtJWqWXYdknha6145hG9mQ8Mdh7rj1sJGWIfeeQdS7XpXQiIVECTdu6g9KYezLCib1Xqzhgo6ad1zizI4VqTkNC9ghos/KhlV2bg3IOaX5qjfXtrJOIYSRv4BMUpS1xgt1DiQMkYIDVvcjSxNA5fFm/rZ8TtcDg8u4sd7VvKGg0XRb0UDwfdGSETM73GGU8ZvXCrEzdaWsDSGfz6kmB4xfMUhrTaAUIywALHfido1osE+1BTZjy9UyJHXrvdXFX6e0IRPr7IFdHy9qn6jzoBQ7sXoD1haK4yTWq2M0QblkwiDyakNJomVnwccsnQehm8)
[Answer]
# [J](http://jsoftware.com/), ~~18~~ 17 bytes
-1 Thanks to @FrownyFrog
```
1+1#.}:(<+:1=*)}.
```
Takes input in the form of `0,1,2`. The helper function on TIO converts the test cases to this form.
[Try it online!](https://tio.run/##y/r/P81Wz1DbUFmv1krDRtvK0FZLs1bvf0ZqTkFqkYKtnoJ6gEeQulqmHldqcka@QpoCVEY9ICAoyMMjIEAdXQIoFuQRBMQBYAxkYigBKfAIAOoOCoIoAxFBYMGgABAGigQFgPUDdf8HAA "J – Try It Online")
The logic of the comparisons may still be golfable. I'm twisting my brain into knots trying to think of more equivalent and shorter statements.
# Explanation (previous solution)
```
1+1#.2(</+:1=*/)\]
```
The only difference between the current solution and the previous one is how the comparisons are generated. The current solution explicitly compares adjacent elements by offsetting the array and the previous solution compares adjacent elements by looking at infixes of 2.
```
1 + 1 #. 2 (</ +: 1 = */)\ ]
2 \ ] On infixes of 2 on the input
1 = */ Is the infix 1 1 (two holds)?
</ Is the infix x y such that x < y?
+: These results NORed
1 #. Add all of the results together (debase to base 1)
1 + Add one
```
This would be a lot cleaner if two holds did nothing. The code takes infixes of two and checks if they are not ascending and not two holds. If this is the case, then we add one to our final count. We have to add 1 to the end since we're off by one otherwise (or you could prepend an `_` or any value greater than 2).
The way it checks if the infix is two holds is by multiplying the two values together and seeing if it is one (two holds are `1 1`).
[Answer]
# Vim + `wc`, 25 bytes
```
:s/P\?H*R\?/a/g␊V!wc -c␊␘
```
`␊` is the return key and `␘` is `Ctrl`+`X`
[Try it online!](https://tio.run/##TY69CoJQAIV3n@J0kYTEbm0RpoMYTioOTS43tRT8If8heoEmR5/PF7GbQzQc@PjOGc6VVfEcBXEBYrmuZ3k87hKOBBpuSRpt674WyoiFUEooIQiBAVWF6ZznY0VdX7c2nq9TRu/T8L6sugBKwGkaxplvBONExKdBKVdUlPx@x6QX@bPjYveHr22TDEoD27FNEDkvyoylEA0CSe4e0u8O1hpoGLU0b9JUCFj9a@YP "Vim – Try It Online")
## Explanation
```
:s/P\?H*R\?/a/g␊ Replace all button presses with the character a
V!wc -c␊␘ Count the characters using the wc command
```
] |
[Question]
[
My Downgoat avatar has several distinct features

These features can however also apply to any other animal.
## Specification
Given an image of an animal (technically can be anything), you must apply the Downgoat properties to it.
**Border pixels** are the outer most pixels of the image.
The **background color** is defined as the most common color in the border pixels. When that color is interpreted as an (r, g, b, a) color, with each channel from [0, 256), the background is defined as the area where the every channel of the given pixels' is within 50 of the "background color".
The process:
* Setting the background and all transparent pixels to `#232323`, `RGBA(35, 35, 35, 1.00)`
* Set all pixels which aren't the background to `#FC0D1B`, `RGBA(252, 13, 27, 1.00)`.
* Vertically reflect the image
* Add the text `-1` in Arial font, in the center of the image. The total height of the text should be 25% of the image's smallest dimension (i.e. `min(width, height) * 0.25`).
## Rules
* Feel free to assume the fonts are already installed
* Your threshold is supposed to be `50`, however you can take this number as input too. You do *not* get any decreased byte count anything for doing this however
* Refer to our [image I/O defaults](http://meta.codegolf.stackexchange.com/q/9093/40695) for any questions related to I/O formats.
* Image will always be at least 3x3 in size
* If there is no most common "border pixel color", it doesn't matter which border pixel color you use as the "background color", this however must be consistent.
## Examples
Input: 
Output: 
---
Input:

Output:

Input: 
Output: 
---
Input: [](https://i.stack.imgur.com/4Rhzz.jpg)
Output: [](https://i.stack.imgur.com/kzt51.png)
---
Input: [](https://i.stack.imgur.com/ndnDw.png)
Output: [](https://i.stack.imgur.com/ULYDE.png)
---
**More examples?**
An online implementation is available here: [vihan.org/p/downgoatify/#50](http://vihan.org/p/downgoatify#50)
---
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest code in bytes wins. Good luck!
[Answer]
# ImageMagick 7.0.3 + bash + sed, 379 bytes
```
M=magick K=\#232323 P='-chop x%[fx:u[0].h-2]-0+1'
$M $1 -depth 8 ppm:W;$M W $P T;$M W -rotate 90 -shave 1x $P L
C=`$M T L +append -statistic mode +0 txt:-|sed -e "1d;s/.*#/#/;s/ .*//;q"`
$M W -background $K -flatten -fill $K -fuzz 20% -opaque $C +fuzz -fill \#FC0D1B +opaque $K -flip -pointsize %[fx:.282*min\(u[0].w,u[0].h\)] -fill white -draw 'gravity center text 0,0 "-1"' x:
```
# Ungolfed
```
# Make aliases for things we'll use repeatedly
M=magick K=\#232323 P='-chop x%[fx:u[0].h-2]-0+1'
# Copy the input file to a PPM file
$M $1 -depth 8 ppm:W
# Extract the border pixels into "T" (top and bottom), and "L" (left and right)
# PPM files, removing the ends from the "L" because they were already counted
$M W $P T;$M W -rotate 90 -shave 1x $P L
# Put the borders into one strip and reduce to a txt image of the "mode"
# color on stdout, then convert the first pixel to hex format string "C"
C=`$M T L +append -statistic mode +0 txt:-|sed -e "1d;s/.*#/#/;s/ .*//;q"`
# Make background "#232323" and compose transparent pixels against it
# Convert any pixels with color within "fuzz" distance of background to #232323
# Convert any remaining pixels to "#FC0D1B"
# Flip the image vertically
# Determine pointsize for text, 1/5 of min(w,h). 1 pixel == 1.44 points
# Draw text "-1" centered on the image
# Display the result to an X window
$M W -background $K -flatten \
-fill $K -fuzz 20% -opaque $C \
+fuzz -fill \#FC0D1B +opaque $K \
-flip \
-pointsize %[fx:.282*min\(u[0].w,u[0].h\)] \
-fill white -draw 'gravity center text 0,0 "-1"' \
x:
```
[](https://i.stack.imgur.com/POQUC.png)
I'm getting a quite different answer for the dennis image, probably because ImageMagick's "-fuzz" computes a sphere with diameter of 2N units in rgb coordinates while the rules call for computing a cube with sides of 101 units in rgb coordinates. Varying the "fuzz" helped some. Also, the JPEG artifacts in the original seem to be interfering with the conversion.
[Answer]
## C, 32-bit Windows, 987 bytes
```
#include <windows.h>
#define A CreateCompatibleDC(c)
#define F z=GetPixel(d,x,y);r=z;g=z>>8;b=z>>16
#define C(X,Y) (X<0||Y<0||X>=s[2]||Y>=s[3]||!GetPixel(e,X,Y))
#define D ((C(x-1,y)||C(x+1,y)||C(x,y-1)||C(x,y+1))&&!C(x,y))
#define E(X,Y) ((Z+X-Y)*(Z+X-Y)<2501)
main(int a,int*n){HDC c,d,e,f,w;int x,y,s[9],z,*o,m,t,Z;unsigned char r,g,b,R,G,B;c=GetDC(w=GetDesktopWindow());d=A;e=A;SelectObject(d,f=LoadImage(0,n[1],0,0,0,16));SelectObject(e,LoadImage(0,n[2],0,0,0,16));GetObject(f,24,s+1);o=LocalAlloc(64/*Fixed,ZeroInit*/,8*s[2]*s[3]);for(x=t=Z=s[1]=s[0]=0;x<s[2];x++)for(y=0;y<s[3];y++)if D{F;for(m=0;m<t&&o[m]!=z;m+=2);o[m]=z;o[m+1]++;t+=2*(m>=t);}for(x=y=1;x<t;x+=2)if(o[x]>o[y])y=x;z=o[y-1];R=z;G=z>>8;B=z>>16;for(x=0;x<s[2];x++)for(y=0;y<s[3];y++){F;SetPixel(c,x,s[3]-y-1,(C(x,y)||(E(r,R)&&E(g,G)&&E(b,B)))?0x232323:0x1B0DFC);}SelectObject(c,CreateFont(-(s[2]>>2),0,0,0,400,0,0,0,0,0,0,0,0,"Arial"));SetBkMode(c,1);SetTextColor(c,0xFFFFFF);DrawText(c,"-1",2,s,37);ReleaseDC(w,c);}
```
* The file is saved with LF as line end, not with CR+LF to save some bytes.
* The program is written in a way that compiler warnings are generated to save some more bytes.
* The file will probably not compile as 64-bit program because the array "`s[]`" is used to do some implicit castings...
* The program takes two images (file names are given via command line):
+ The first image (first command line argument) is the R/G/B image in Windows .BMP format
+ The second image is the Alpha channel (black means: 0%, any other colour means: not 0%); the file is also in .BMP format and must have the same size or be larger than the first image
* The output image is displayed in the left upper corner of the screen
* I couldn't reproduce the boy with the yellow hair. Yellow seems to be too far away (> 50) from white!
Ungolfed version:
```
#include <windows.h>
/*
* Although this line costs us 32 bytes
* Replacing "CreateCompatibleDC(c)" we'll
* save 42 bytes in the golfed version later
* so we save 10 bytes using this define!
*/
#define A CreateCompatibleDC(c)
/*
* Macro: Get a pixel value at (x,y) to z
* Also get r, g, b
*/
#define F z=GetPixel(d,x,y); \
r=z; \
g=z>>8; \
b=z>>16
/*
* Macro checking if a pixel is a
* transparent colour or lies outside the
* image
*/
#define C(X,Y) (X<0 || Y<0 || X>=s[2] || Y>=s[3] || !GetPixel(e,X,Y))
/*
* Macro checking if a pixel at (x,y) is a border pixel
*/
#define D ((C(x-1,y) || C(x+1,y) || C(x,y-1) || C(x,y+1)) && !C(x,y))
/*
* Macro checking if the difference between X and Y is less than 50
* The variable "Z" must be type "int" and zero. It is used to
* perform an implicit cast from "BYTE" to "int".
*/
#define E(X,Y) ((Z+X-Y)*(Z+X-Y)<2501)
/*
* Note that the second argument is "char **",
* not "int *".
* We ignore resulting compiler warnings...
*/
main(int a, int * n)
{
HDC c, d, e, f, w;
int x, y, s[9], z, *o, m, t, Z;
unsigned char r, g, b, R, G, B;
/*
* Get the HDC handle to the
* screen (allowing us to create HDCs
* for accessing bitmap files as well as
* drawing directly to the screen!)
*/
c=GetDC(w=GetDesktopWindow());
/*
* Create two virtual HDCs for accessing
* the bitmap files.
*/
d=A; /* Macro */
e=A; /* Macro */
/*
* Load the two images:
* The first argument is the image file with
* the R/G/B channel
* The second argument is the image file
* containing the mask defined by the Alpha
* channel:
* Black means = Alpha=0
* White means = Alpha>0
* (Any other colour means: Alpha>0)
*
* Note that "f" is of the type "HBITMAP",
* not "HDC". We save 4 bytes in the golfed
* version using HDC instead of HBITMAP and
* compile the C file with compiler warnings
* switched off!
*
* The second image should have the same size
* as the first one. However it may be larger
* than the first one. It must not be smaller!
*/
SelectObject(d,f=LoadImage(0,n[1],0,0,0,16 /* 16=LR_LOADFROMFILE */));
SelectObject(e,LoadImage(0,n[2],0,0,0,16));
/*
* Get the image information (size)
*/
GetObject(f,24,s+1);
/*
* Search all background colours
*/
o=LocalAlloc(64 /* Fixed, ZeroInit */,8*s[2]*s[3]);
for(x=t=Z=s[1]=s[0]=0;x<s[2];x++)
for(y=0;y<s[3];y++)
if D
{
F; /* Macro */
for(m=0;m<t && o[m]!=z;m+=2);
o[m]=z;
o[m+1]++;
t+=2*(m>=t);
}
/*
* Search the most common one
*/
for(x=y=1;x<t;x+=2) if(o[x]>o[y]) y=x;
z=o[y-1];
R=z;
G=z>>8;
B=z>>16;
/*
* Draw the image directly to the screen
*/
for(x=0;x<s[2];x++)
for(y=0;y<s[3];y++)
{
F; /* Macro */
/* C and E are macros: */
SetPixel(c,x,s[3]-y-1,(C(x,y) ||
(E(r,R) && E(g,G) && E(b,B)))?
0x232323:0x1B0DFC);
}
/*
* Draw the text over the image
*/
SelectObject(c,CreateFont(-(s[2]>>2),0,0,0,400,0,0,0,0,0,0,0,0,"Arial"));
SetBkMode(c,1 /* TRANSPARENT */);
SetTextColor(c,0xFFFFFF);
DrawText(c,"-1",2,s,37 /* center, vcenter, singleline */);
/*
* Unfortunately DrawText() won't work
* when not doing this!
*/
ReleaseDC(w,c);
}
```
] |
[Question]
[
Create a program that find the latest 50 challenges with the [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'")-tag that have at least 20 answers. Then, extract the scores for each language in each of the challenges. If there are more than one answer using the same language, count all scores. Thereafter, take the top 20 most common languages and output a list with the language names, the number of answers, the average byte counts and the median byte counts. The list should be sorted by number of answers, in descending order.
You must account for variations in capitalization (for instance: Matlab = MATLAB).
In languages with many different version numbers (e.g. Python), count them as unique languages, so: `Python != Python 2 != Python 2.7 != Python 3.x`
Example output (output format is optional):
```
cJam, 66, 12.4, 8.5
Pyth, 58, 15.2, 19
Ruby, 44, 19.2, 22.5
Python, 34, 29.3, 32
Python 2.7, 22, 31.2, 40
...
...
Java, 11, 115.5, 94.5
```
Header formats that must be supported:
* Starts with `# Language name,` or `#Language name`
* Ends with `xx bytes`, `xx Bytes` or just `xx`
* There can be a lot of garbage between the first comma and the last number.
* If the language name is a link (`[Name](link)`), it can be skipped
If the answer has another header format, you may choose to skip it (or include it if your code can handle it).
As an example, all of the below headers must be supported:
```
# Language Name, N bytes
# Ruby, <s>104</s> <s>101</s> 96 bytes
# Perl, 43 + 2 (-p flag) = 45 Bytes
# MATLAB, 5
```
Rules:
* It's OK to use API or just the website-url
+ The following can be extracted from the byte count (nothing else), so no need to use a url-shortener (Maximum 44 bytes):
- `https://` (or `http://`)
- `codegolf`
- `.stackexchange.com`
- `/questions`
* The program can take input. The input will be included in the byte count.
Other than that, standard rules apply.
[Answer]
# R, 821 - 44 = 777 bytes
*Updated results*: please see the edit history to make sense of all the comments below.
```
language num_answers avg_count median_count
1 RUBY 49 49.97959 30.0
2 CJAM 48 32.64583 22.0
3 PYTH 48 21.02083 14.0
4 PYTHON 2 46 86.78261 77.0
5 JULIA 43 58.90698 45.0
6 HASKELL 41 74.65854 56.0
7 PHP 40 73.52500 48.0
8 PERL 36 53.30556 34.0
9 PYTHON 3 34 90.91176 90.5
10 POWERSHELL 33 60.24242 44.0
11 C 32 221.84375 79.5
12 R 32 77.40625 62.5
13 JAVA 29 170.68966 158.0
14 JAVASCRIPT (ES6) 29 90.79310 83.0
15 JAVASCRIPT 28 68.39286 61.0
16 C# 25 193.92000 130.0
17 MATHEMATICA 23 56.04348 47.0
18 MATLAB 22 67.45455 55.0
19 TI-BASIC 19 47.05263 37.0
20 APL 18 16.55556 15.0
```
The code, which I could shorten a bit more:
```
W=library;W(XML);W(plyr)
X=xpathSApply;Y=xmlValue;D=data.frame;H=htmlParse;S=sprintf
Z="http://codegolf.stackexchange.com/"
R=function(FUN,...)do.call(rbind,Map(FUN,...))
G=function(url){d=H(url)
a=as.double(sub(".*?(\\d+)a.*","\\1",X(d,"//div[starts-with(@class,'status')]",Y)))
u=paste0(Z,X(d,"//*[contains(@class,'question-hyperlink')]",xmlGetAttr,"href"))
D(u,a)}
u=S("%s/questions/tagged/code-golf?page=%i",Z,1:50)
q=R(G,u)
u=with(q,head(u[a>20],50))
A=function(url){u=S("%s?page=%i",url,1:10)
f=function(u){d=H(u)
h=X(d, "//div[@class='post-text']//h1",Y)
p="^(.*?),.*? (\\d+)( [Bb]ytes)?$"
k=grep(p,h,v=T)
l=toupper(sub(p,"\\1",k))
c=as.double(sub(p,"\\2",k))
D(l,c)}
R(f,u)}
a=R(A,u)
L=names(tail(sort(table(a$l)),20))
x=subset(a,l%in%L)
arrange(ddply(x, "l",summarise,n=length(c),a=mean(c),m=quantile(c,0.5)),-n)
```
De-golfed:
```
library(XML)
library(plyr)
LoopBind <- function(FUN, ...) do.call(rbind, Map(FUN, ...))
GetQuestions <- function(url) {
d = htmlParse(url)
a=as.double(sub(".*?(\\d+)a.*","\\1",xpathSApply(d, "//div[starts-with(@class, 'status')]", xmlValue)))
u=paste0("http://codegolf.stackexchange.com/",xpathSApply(d, "//*[contains(@class, 'question-hyperlink')]", xmlGetAttr, "href"))
data.frame(u, a)
}
u <- sprintf("http://codegolf.stackexchange.com/questions/tagged/code-golf?page=%i", 1:50)
q <- do.call(rbind, Map(GetQuestions, u))
u <- with(q, head(u[a > 20], 50))
GetAnswers <- function(url) {
u=sprintf("%s?page=%i",url,1:10)
f=function(u) {
d = htmlParse(u)
h = xpathSApply(d, "//div[@class='post-text']//h1", xmlValue)
p = "^(.*?),.*? (\\d+)( [Bb]ytes)?$"
k = grep(p,h,v=T)
l = toupper(sub(p,"\\1",k))
c = as.double(sub(p,"\\2",k))
data.frame(language=l,c)
}
LoopBind(f,u)
}
a=LoopBind(GetAnswers, u)
L=names(tail(sort(table(a$l)),20))
x=subset(a,language%in%L)
arrange(ddply(x, "language", summarise, num_answers = length(c), avg_count = mean(c), median_count = quantile(c,0.5)),
-num_answers)
```
[Answer]
# Python 2, 934 - 44 (url stuff) = 890 bytes
Using the API:
```
from urllib2 import urlopen as u
from gzip import GzipFile as f
from StringIO import StringIO as s;x="https://api.stackexchange.com/2.2%s&site=codegolf"
import re;j=u(x%'/search/advanced?pagesize=50&order=desc&sort=creation&answers=20&tagged=code-golf');q=s(j.read());g=f(fileobj=q);true=1;false=0;l=';'.join(str(a['question_id'])for a in eval(g.read())['items']);w=[]
def r(p):
j=u(x%('/questions/%s/answers?page=%s&filter=!9YdnSMlgz&pagesize=100'%(l,p)));g.seek(0);q.truncate();q.write(j.read());q.seek(0);k=eval(g.read());w.extend(a['body_markdown']for a in k['items'])
if k['has_more']:r(p+1)
r(1);x={};s=sorted
for m in w:
try:
l,n=re.match("(.*?),.*?([0-9]+)[^0-9]*$",m.splitlines()[0]).groups();l=re.subn("# ?","",l,1)[0].upper()
if l not in x:x[l]=[]
x[l]+=[(l,int(n))]
except:pass
for l in s(x,cmp,lambda a:len(x[a]),1)[:20]:
v=s(x[l])
print l,len(v),sum(map(lambda a:a[1],v))/len(v),v[len(v)/2][1]
```
Note that this code **does not** pay attention to the API throttling.
Output:
```
RUBY 60 430 32
PYTH 57 426 16
CJAM 56 35 23
C 52 170 76
PYTHON 2 51 88 79
JULIA 42 63 48
HASKELL 42 81 63
JAVASCRIPT (ES6) 41 96 83
PERL 40 44 27
PYTHON 3 37 91 89
PHP 36 98 59
JAVASCRIPT 36 743 65
POWERSHELL 35 86 44
JAVA 32 188 171
R 30 73 48
MATLAB 25 73 51
MATHEMATICA 24 57 47
APL 22 14 13
SCALA 21 204 59
TI-BASIC 21 42 24
```
] |
[Question]
[
*Inspired by [Hyperprogramming: N+N, N×N, N^N all in one](https://codegolf.stackexchange.com/q/92944/12012).
Thanks to @MartinEnder and @trichoplax for their help in the sandbox.*
# Definitions
## Hyperquines
Define a **hyperquine** of order **n** as a quine-like full program or function **P** that satisfies all rules that apply to [proper quines](http://meta.codegolf.stackexchange.com/a/4878/12012) and, in addition, has the following structure.
**P** is the concatenation of character‡ groups that consist of **n** copies of the same character. When **P** is executed, the *output* is the concatenation of the same groups, augmented by one more copy of the character.
### Examples
* In a hypothetical programming language where the source code `aabbcc` generates the output `aaabbbccc`, this program constitutes a hyperquine of order **2**.
* The definition does *not* require the characters of different groups to be different.
If the source code `aabbcc` generates the output `aaaabbbbcccc`, the program is a hyperquine of order **1**; the source code consists of six single-character groups, the output of six character pairs.
* In [GS2](http://gs2.tryitonline.net/), the empty program prints `\n`, and the program `\n` prints `\n\n`. However, neither `\n` nor `\n\n` are hyperquines, since they they do not satisfy all properties of [proper quines](http://meta.codegolf.stackexchange.com/a/4878/12012); no part of the source code encodes a *different* part of the output.
## Hyperquine chains
Define a **hyperquine chain** of length **n** as a finite sequence of **n** full programs or **n** functions
**(P1, …, Pn)** that satisfies the following constraints.
1. The outputs of **P1, …, Pn-1** are **P2, …, Pn**, respectively.
2. **P1, …, Pn** are hyperquines.
3. The orders of **P1, …, Pn** form a *strictly increasing* sequence of *adjacent* integers.
Finally, define an **infinite hyperquine chain** as an infinite sequence of full programs or functions **(P1, P2, …)** such that each initial interval **(P1, …, Pn)** constitutes a hyperquine chain of length **n**.
### Examples
* In a hypothetical programming language where the source code `aabbcc` generates the output `aaabbbccc`, which, in turn, generates the output `aaaabbbbcccc`, the pair (`aabbcc`, `aaabbbccc`) constitutes a hyperquine chain of length **2**.
Note that `aaaabbbbcccc` – the output of the last hyperquine in the chain – doesn't have to produce a specific output; it doesn't even have to be valid source code.
* Continuing the previous example, if `aaaabbbbcccc` generates the output `aaaaabbbbbccccc`, the triplet (`aabbcc`, `aaabbbccc`, `aaaabbbbcccc`) constitutes a hyperquine chain of length **3**.
If this pattern continues forever, the sequence (`aabbcc`, `aaabbbccc`, `aaaabbbbcccc`, …) constitutes an infinite hyperquine chain.
* The pair of programs (`abc`, `aabbcc`) with outputs (`aabbcc`, `aaaabbbbcccc`) is *not* a hyperquine chain, since the orders of the hyperquines are both **1**, so they do not form a strictly increasing sequence.
* The pair of programs (`aabbcc`, `aaaabbbbcccc`) with outputs (`aaaabbbbcccc`, `aaaaabbbbbccccc`) is *not* a hyperquine chain, since the orders of the hyperquines are **1** and **4**, so they do not form a sequence of adjacent integers.
# Rules
## Task
In a [programming language](http://meta.codegolf.stackexchange.com/a/2073/12012) of your choice, write a non-trivial hyperquine chain, i.e., a chain that consists of at least **2** hyperquines.
As usual, your programs may not take any input or access their own source code in any form.
If your interpreter prints an implicit newline, your hyperquines *have to* account for this.
All [standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/12012) – especially those related to quines – apply.
## Scoring
The longest **hyperquine chain** wins. If two or more submissions are tied, the submission among these that starts with the shortest hyperquine (measured in characters‡) wins. As usual, posting time is the final tiebreaker.
---
‡ You must use the same character encoding for source code, output, character count, and execution. For example, the Python program `print 42` is *not* a 2-character UTF-32 submission, since the interpreter treats each byte as a single character. If your language of choice is not character-based, treat all individual bytes as characters.
[Answer]
# [Befunge-98](http://github.com/catseye/FBBI), infinite order, ~~54~~ ~~52~~ ~~38~~ 36 bytes
## Second approach - infinite order, 36 bytes
This program would actually break at the 34th hyperquine since the ASCII value of `"` would disrupt the string interpretation (and at 59, `;`), but we offset the storage of that value to a position that will never be executed (i.e. `(0, 1)` instead of `(0, 0)`).
```
1+::0*x01pn'!1+:#jr;,kg10@k!:kg10;#"
```
Try it online: [1](http://befunge-98.tryitonline.net/#code=MSs6OjAqeDAxcG4nITErOiNqcjssa2cxMEBrITprZzEwOyMi&input=), [2](http://befunge-98.tryitonline.net/#code=MTErKzo6OjowMCoqeHgwMDExcHBubicnISExMSsrOjojI2pqcnI7Oywsa2tnZzExMDBAQGtrISE6OmtrZ2cxMTAwOzsjIyIi&input=), [10](http://befunge-98.tryitonline.net/#code=MTExMTExMTExMSsrKysrKysrKys6Ojo6Ojo6Ojo6Ojo6Ojo6Ojo6OjAwMDAwMDAwMDAqKioqKioqKioqeHh4eHh4eHh4eDAwMDAwMDAwMDAxMTExMTExMTExcHBwcHBwcHBwcG5ubm5ubm5ubm4nJycnJycnJycnISEhISEhISEhITExMTExMTExMTErKysrKysrKysrOjo6Ojo6Ojo6OiMjIyMjIyMjIyNqampqampqampqcnJycnJycnJycjs7Ozs7Ozs7OzssLCwsLCwsLCwsa2tra2tra2tra2dnZ2dnZ2dnZ2cxMTExMTExMTExMDAwMDAwMDAwMEBAQEBAQEBAQEBra2tra2tra2trISEhISEhISEhITo6Ojo6Ojo6Ojpra2tra2tra2trZ2dnZ2dnZ2dnZzExMTExMTExMTEwMDAwMDAwMDAwOzs7Ozs7Ozs7OyMjIyMjIyMjIyMiIiIiIiIiIiIi&input=), [34](http://befunge-98.tryitonline.net/#code=MTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMSsrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKys6Ojo6Ojo6Ojo6Ojo6Ojo6Ojo6Ojo6Ojo6Ojo6Ojo6Ojo6Ojo6Ojo6Ojo6Ojo6Ojo6Ojo6Ojo6Ojo6Ojo6Ojo6Ojo6OjAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqeHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAxMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcG5ubm5ubm5ubm5ubm5ubm5ubm5ubm5ubm5ubm5ubm5ubm4nJycnJycnJycnJycnJycnJycnJycnJycnJycnJycnJycnISEhISEhISEhISEhISEhISEhISEhISEhISEhISEhISEhITExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTErKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrOjo6Ojo6Ojo6Ojo6Ojo6Ojo6Ojo6Ojo6Ojo6Ojo6Ojo6OiMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyNqampqampqampqampqampqampqampqampqampqampqampqcnJycnJycnJycnJycnJycnJycnJycnJycnJycnJycnJycjs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7OzssLCwsLCwsLCwsLCwsLCwsLCwsLCwsLCwsLCwsLCwsLCwsa2tra2tra2tra2tra2tra2tra2tra2tra2tra2tra2tra2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2cxMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBra2tra2tra2tra2tra2tra2tra2tra2tra2tra2tra2trISEhISEhISEhISEhISEhISEhISEhISEhISEhISEhISEhITo6Ojo6Ojo6Ojo6Ojo6Ojo6Ojo6Ojo6Ojo6Ojo6Ojo6Ojpra2tra2tra2tra2tra2tra2tra2tra2tra2tra2tra2trZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZzExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTEwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwOzs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7OyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIi&input=), [42](http://befunge-98.tryitonline.net/#code=MTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrOjo6Ojo6Ojo6Ojo6Ojo6Ojo6Ojo6Ojo6Ojo6Ojo6Ojo6Ojo6Ojo6Ojo6Ojo6Ojo6Ojo6Ojo6Ojo6Ojo6Ojo6Ojo6Ojo6Ojo6Ojo6Ojo6Ojo6Ojo6MDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqeHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4MDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwbm5ubm5ubm5ubm5ubm5ubm5ubm5ubm5ubm5ubm5ubm5ubm5ubm5ubm5uJycnJycnJycnJycnJycnJycnJycnJycnJycnJycnJycnJycnJycnJycnISEhISEhISEhISEhISEhISEhISEhISEhISEhISEhISEhISEhISEhISEhMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrOjo6Ojo6Ojo6Ojo6Ojo6Ojo6Ojo6Ojo6Ojo6Ojo6Ojo6Ojo6Ojo6Ojo6IyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjampqampqampqampqampqampqampqampqampqampqampqampqampqampqcnJycnJycnJycnJycnJycnJycnJycnJycnJycnJycnJycnJycnJycnJyOzs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7LCwsLCwsLCwsLCwsLCwsLCwsLCwsLCwsLCwsLCwsLCwsLCwsLCwsLCwsa2tra2tra2tra2tra2tra2tra2tra2tra2tra2tra2tra2tra2tra2trZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAa2tra2tra2tra2tra2tra2tra2tra2tra2tra2tra2tra2tra2tra2trISEhISEhISEhISEhISEhISEhISEhISEhISEhISEhISEhISEhISEhISEhOjo6Ojo6Ojo6Ojo6Ojo6Ojo6Ojo6Ojo6Ojo6Ojo6Ojo6Ojo6Ojo6Ojo6a2tra2tra2tra2tra2tra2tra2tra2tra2tra2tra2tra2tra2tra2trZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwOzs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7IyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIi&input=)
### Explanation
```
INSTRUCTIONS STACK (PYTHON PSEUDOCODE) EXPLANATION
1+ [n] Push n many 1s onto the stack, then sum them up
:: [n]*(at least 3) Duplicate that sum at least twice
0* [n]*(at least 2)+[0] Push a whole lot of zeros, then multiply them all together
x [n]*(at least 1) Pop a vector off the stack (n, 0) and set the IP delta to that; now the IP is only executing every nth character
01p [n]*(at least 1) Place n in the program at coordinates (0, 1); this is just for storage
n [] Clear the stack
'!1+ ['"'] '!' is character 33; one less than 34, or '"'
:#jr ['"'] We duplicate the 34 (all we care is that it's a rather large number), then turn around and skip that many spaces
The IP, having jumped 34*n instructions to the left, is now way in the negatives
Execution resumes on the other side of the program (the following instructions have been reversed for readability
" [the program of order 1] The quote-at-the-end-of-the-program is a common trick for one-liner Befunge quines
#; ... ; Jumps into a loop (when the IP hits one semicolon it skips to the next, restarting the loop)
01gk: [(rest of string), char*(n+2)] This duplicates the letter n+1 times*, leaving n+2 copies on the stack
!k@ If the number on the top of the stack is zero (i.e. we are printing), it will execute '@',
ending the program; otherwise, it will NOT execute '@' and will instead continue normally
Vague* 'k' instruction FTW
10gk, If we aren't done yet, print the character n+1 times* (and restart the loop)
* 'k' is a very strange instruction. It pops a number off the stack; if the number is zero, it skips the command in front of it. If the number is greater than zero,
it will execute the instruction that many times PLUS ONE. This is actually strangely advantageous in this program.
```
---
## First approach - order 34, 52 bytes (uses introspection, so technically not legal)
For the reason in the above post, this program would break at order 34 (though I haven't tested).
```
1+::0*x:00p'1\k:00gk,1#;:00g*0g00gk:$00gk,1+:'4-!k@;
```
[Try it online!](http://befunge-98.tryitonline.net/#code=MSs6OjAqeDowMHAnMVxrOjAwZ2ssMSM7OjAwZyowZzAwZ2s6JDAwZ2ssMSs6JzQtIWtAOw&input=)
[Answer]
## [><>](http://esolangs.org/wiki/Fish), infinite order, 178 bytes
The program contains a trailing linefeed.
```
^
.
*
&
:
&
+
*
2
b
*
*
6
9
$
0
)
*
4
8
:
~
.
*
&
:
&
+
*
2
b
*
*
2
b
$
0
)
i
:
-
1
o
a
&
:
&
o
~
.
*
&
:
&
+
*
7
7
*
*
4
6
$
0
)
0
:
-
1
$
o
:
$
&
:
&
&
,
*
8
b
-
1
l
}
*
3
d
'
```
**Try it online:** [1](http://fish.tryitonline.net/#code=XgouCioKJgo6CiYKKwoqCjIKYgoqCioKNgo5CiQKMAopCioKNAo4CjoKfgouCioKJgo6CiYKKwoqCjIKYgoqCioKMgpiCiQKMAopCmkKOgotCjEKbwphCiYKOgomCm8KfgouCioKJgo6CiYKKwoqCjcKNwoqCioKNAo2CiQKMAopCjAKOgotCjEKJApvCjoKJAomCjoKJgomCiwKKgo4CmIKLQoxCmwKfQoqCjMKZAonCg&input=), [2](http://fish.tryitonline.net/#code=Xl4KCi4uCgoqKgoKJiYKCjo6CgomJgoKKysKCioqCgoyMgoKYmIKCioqCgoqKgoKNjYKCjk5CgokJAoKMDAKCikpCgoqKgoKNDQKCjg4Cgo6OgoKfn4KCi4uCgoqKgoKJiYKCjo6CgomJgoKKysKCioqCgoyMgoKYmIKCioqCgoqKgoKMjIKCmJiCgokJAoKMDAKCikpCgppaQoKOjoKCi0tCgoxMQoKb28KCmFhCgomJgoKOjoKCiYmCgpvbwoKfn4KCi4uCgoqKgoKJiYKCjo6CgomJgoKKysKCioqCgo3NwoKNzcKCioqCgoqKgoKNDQKCjY2CgokJAoKMDAKCikpCgowMAoKOjoKCi0tCgoxMQoKJCQKCm9vCgo6OgoKJCQKCiYmCgo6OgoKJiYKCiYmCgosLAoKKioKCjg4CgpiYgoKLS0KCjExCgpsbAoKfX0KCioqCgozMwoKZGQKCicnCgo&input=), [3](http://fish.tryitonline.net/#code=Xl5eCgoKLi4uCgoKKioqCgoKJiYmCgoKOjo6CgoKJiYmCgoKKysrCgoKKioqCgoKMjIyCgoKYmJiCgoKKioqCgoKKioqCgoKNjY2CgoKOTk5CgoKJCQkCgoKMDAwCgoKKSkpCgoKKioqCgoKNDQ0CgoKODg4CgoKOjo6CgoKfn5-CgoKLi4uCgoKKioqCgoKJiYmCgoKOjo6CgoKJiYmCgoKKysrCgoKKioqCgoKMjIyCgoKYmJiCgoKKioqCgoKKioqCgoKMjIyCgoKYmJiCgoKJCQkCgoKMDAwCgoKKSkpCgoKaWlpCgoKOjo6CgoKLS0tCgoKMTExCgoKb29vCgoKYWFhCgoKJiYmCgoKOjo6CgoKJiYmCgoKb29vCgoKfn5-CgoKLi4uCgoKKioqCgoKJiYmCgoKOjo6CgoKJiYmCgoKKysrCgoKKioqCgoKNzc3CgoKNzc3CgoKKioqCgoKKioqCgoKNDQ0CgoKNjY2CgoKJCQkCgoKMDAwCgoKKSkpCgoKMDAwCgoKOjo6CgoKLS0tCgoKMTExCgoKJCQkCgoKb29vCgoKOjo6CgoKJCQkCgoKJiYmCgoKOjo6CgoKJiYmCgoKJiYmCgoKLCwsCgoKKioqCgoKODg4CgoKYmJiCgoKLS0tCgoKMTExCgoKbGxsCgoKfX19CgoKKioqCgoKMzMzCgoKZGRkCgoKJycnCgoK&input=), [10](http://fish.tryitonline.net/#code=Xl5eXl5eXl5eXgoKCgoKCgoKCgouLi4uLi4uLi4uCgoKCgoKCgoKCioqKioqKioqKioKCgoKCgoKCgoKJiYmJiYmJiYmJgoKCgoKCgoKCgo6Ojo6Ojo6Ojo6CgoKCgoKCgoKCiYmJiYmJiYmJiYKCgoKCgoKCgoKKysrKysrKysrKwoKCgoKCgoKCgoqKioqKioqKioqCgoKCgoKCgoKCjIyMjIyMjIyMjIKCgoKCgoKCgoKYmJiYmJiYmJiYgoKCgoKCgoKCgoqKioqKioqKioqCgoKCgoKCgoKCioqKioqKioqKioKCgoKCgoKCgoKNjY2NjY2NjY2NgoKCgoKCgoKCgo5OTk5OTk5OTk5CgoKCgoKCgoKCiQkJCQkJCQkJCQKCgoKCgoKCgoKMDAwMDAwMDAwMAoKCgoKCgoKCgopKSkpKSkpKSkpCgoKCgoKCgoKCioqKioqKioqKioKCgoKCgoKCgoKNDQ0NDQ0NDQ0NAoKCgoKCgoKCgo4ODg4ODg4ODg4CgoKCgoKCgoKCjo6Ojo6Ojo6OjoKCgoKCgoKCgoKfn5-fn5-fn5-fgoKCgoKCgoKCgouLi4uLi4uLi4uCgoKCgoKCgoKCioqKioqKioqKioKCgoKCgoKCgoKJiYmJiYmJiYmJgoKCgoKCgoKCgo6Ojo6Ojo6Ojo6CgoKCgoKCgoKCiYmJiYmJiYmJiYKCgoKCgoKCgoKKysrKysrKysrKwoKCgoKCgoKCgoqKioqKioqKioqCgoKCgoKCgoKCjIyMjIyMjIyMjIKCgoKCgoKCgoKYmJiYmJiYmJiYgoKCgoKCgoKCgoqKioqKioqKioqCgoKCgoKCgoKCioqKioqKioqKioKCgoKCgoKCgoKMjIyMjIyMjIyMgoKCgoKCgoKCgpiYmJiYmJiYmJiCgoKCgoKCgoKCiQkJCQkJCQkJCQKCgoKCgoKCgoKMDAwMDAwMDAwMAoKCgoKCgoKCgopKSkpKSkpKSkpCgoKCgoKCgoKCmlpaWlpaWlpaWkKCgoKCgoKCgoKOjo6Ojo6Ojo6OgoKCgoKCgoKCgotLS0tLS0tLS0tCgoKCgoKCgoKCjExMTExMTExMTEKCgoKCgoKCgoKb29vb29vb29vbwoKCgoKCgoKCgphYWFhYWFhYWFhCgoKCgoKCgoKCiYmJiYmJiYmJiYKCgoKCgoKCgoKOjo6Ojo6Ojo6OgoKCgoKCgoKCgomJiYmJiYmJiYmCgoKCgoKCgoKCm9vb29vb29vb28KCgoKCgoKCgoKfn5-fn5-fn5-fgoKCgoKCgoKCgouLi4uLi4uLi4uCgoKCgoKCgoKCioqKioqKioqKioKCgoKCgoKCgoKJiYmJiYmJiYmJgoKCgoKCgoKCgo6Ojo6Ojo6Ojo6CgoKCgoKCgoKCiYmJiYmJiYmJiYKCgoKCgoKCgoKKysrKysrKysrKwoKCgoKCgoKCgoqKioqKioqKioqCgoKCgoKCgoKCjc3Nzc3Nzc3NzcKCgoKCgoKCgoKNzc3Nzc3Nzc3NwoKCgoKCgoKCgoqKioqKioqKioqCgoKCgoKCgoKCioqKioqKioqKioKCgoKCgoKCgoKNDQ0NDQ0NDQ0NAoKCgoKCgoKCgo2NjY2NjY2NjY2CgoKCgoKCgoKCiQkJCQkJCQkJCQKCgoKCgoKCgoKMDAwMDAwMDAwMAoKCgoKCgoKCgopKSkpKSkpKSkpCgoKCgoKCgoKCjAwMDAwMDAwMDAKCgoKCgoKCgoKOjo6Ojo6Ojo6OgoKCgoKCgoKCgotLS0tLS0tLS0tCgoKCgoKCgoKCjExMTExMTExMTEKCgoKCgoKCgoKJCQkJCQkJCQkJAoKCgoKCgoKCgpvb29vb29vb29vCgoKCgoKCgoKCjo6Ojo6Ojo6OjoKCgoKCgoKCgoKJCQkJCQkJCQkJAoKCgoKCgoKCgomJiYmJiYmJiYmCgoKCgoKCgoKCjo6Ojo6Ojo6OjoKCgoKCgoKCgoKJiYmJiYmJiYmJgoKCgoKCgoKCgomJiYmJiYmJiYmCgoKCgoKCgoKCiwsLCwsLCwsLCwKCgoKCgoKCgoKKioqKioqKioqKgoKCgoKCgoKCgo4ODg4ODg4ODg4CgoKCgoKCgoKCmJiYmJiYmJiYmIKCgoKCgoKCgoKLS0tLS0tLS0tLQoKCgoKCgoKCgoxMTExMTExMTExCgoKCgoKCgoKCmxsbGxsbGxsbGwKCgoKCgoKCgoKfX19fX19fX19fQoKCgoKCgoKCgoqKioqKioqKioqCgoKCgoKCgoKCjMzMzMzMzMzMzMKCgoKCgoKCgoKZGRkZGRkZGRkZAoKCgoKCgoKCgonJycnJycnJycnCgoKCgoKCgoKCg&input=) (That last one takes a while to run.)
[Retina script to generate source from linear program.](http://retina.tryitonline.net/#code=JApeCk8kXmAuCgpTX2A&input=J2QzKn1sMS1iOCosJiY6JiQ6byQxLTowKTAkNjQqKjc3KismOiYqLn5vJjomYW8xLTppKTAkYjIqKmIyKismOiYqLn46ODQqKTAkOTYqKmIyKismOiYqLg)
### Explanation
The main idea is to turn the quine vertical, so that the actual control flow isn't affected by the repetition. E.g. the second hyper quine begins like:
```
^^
..
**
```
Since we're only moving through the first column, we don't have to worry about repeated characters. Also when we push the majority of the code as a string with `'`, this will push a space for each empty line, which gives us a way to determine the number of repetitions. That said, there are some limitations due to these empty lines:
* We can't use `"` to push large numbers as character codes in the main part of the quine, because this would push additional `32`s which we don't want.
* We can't use `?` or `!` because they only skip the next character which would be a space in that case (so they wouldn't actually skip the next command).
Hence, all control flow is done with explicit jumps (2D goto, basically), whose actual offsets we need to calculate based on the number of repetitions.
So let's look at the actual code. We start with `^` so the code is executed bottom up. For easier reading, let's write out the actual code in execution order (and drop the `^` because it's never executed again):
```
'd3*}l1-b8*,&&:&$:o$1-:0)0$64**77*+&:&*.~o&:&ao1-:i)0$b2**b2*+&:&*.~:84*)0$96**b2*+&:&*.
```
The `'` is the standard quining technique for ><> (and Befunge, I guess). It switches to string mode which means that the encountered characters are pushed onto the stack until the next `'` is encountered. Empty lines are implicitly padded with spaces which is why we get all the spaces in between. Empty lines at the end of the program are ignored. So after the IP wraps around and hits the `'` again, we've got the first column of the program on the stack, except for the `'` itself.
Let's look at how we use this to print the entire program.
```
d3*} Put a 36 (the ') at the bottom of the stack. Now the stack holds
a representation of the entire first column.
l1- Push the depth of the stack, minus (so minus to ').
b8*, Divide by 88. The original program has 89 lines. If we divide the
depth of the stack (minus 1) by 88, we get the order of the current
hyperquine (due to all the spaces we've pushed).
& Store the order of the hyperquine in the register.
Begin of main loop:
&:& Push a copy of the register onto the stack. Call that N.
Begin of line-printing loop:
$:o$ Print a copy of the top character on the stack.
1- Decrement N.
:0) Check whether it's still positive (gives 0 or 1).
0$ Put a 0 underneath. This will be the x-coordinate of a jump.
64** Multiply the conditional by 24. This is the number of commands
in this inner loop.
77*+ Add this to 49, the offset of the end of the loop.
The result is line we want to jump to in the order-1 hyperquine.
&:&* Multiply by the order of the quine (so that we jump further on
higher quine orders).
. Jump. If N isn't zero yet, this repeats the inner loop. Otherwise
we continue right here.
~ Discard N (now 0).
o Output one last copy of the top character on the stack.
&:& Push a copy of the register onto the stack. Call that N.
Begin of linefeed-printing loop:
ao Print a linefeed.
1- Decrement N.
:i) Check whether it's still non-negative (gives 0 or 1).
The next bit is essentially the same loop structure as above,
but with loop length 22 and offset 22:
0$
b2**
b2*+
&:&*
. Jump. If N isn't -1 yet, this repeats the inner loop. Otherwise
we continue right here.
Begin of space-clearing loop:
~ Discard the top of the stack. On the first iteration this is the
-1 from the previous loop. Afterwards, it's one of the spaces
representing an empty line.
:84*) Check if the top of the stack is a space.
And another loop conditional. This one works the other way round:
the difference is 54, which is the distance between the beginning
of this loop and the main loop. The offset is the beginning
of this loop, at 22 as above.
0$
96**
b2*+
&:&*
. Jump. If the top of the stack is still a space this repeats the
inner loop. Otherwise we continue from the top of the main loop.
```
The program terminates when the stack is empty and the first inner loop fails to print another character.
] |
[Question]
[
You have your very heavy cubical box on a flat floor at position (0,0). All you can do with it is roll it in four cardinal directions (east, north, west, south). Your task is to bring it to a target position, such that the side facing up is the same as before your manipulations.
Make a program or function which receives target coordinates and returns the **minimal** sequence of moves which results in the box arriving to target in upright position.
Input: two integers x, y
* Get it in any convenient format - as a pair, as a complex number, etc.
* You can assume x² + y² ≠ 0
Output: a string of instructions containing characters `E`, `N`, `W`, `S`
* Spaces and newlines are allowed
* UPPER-CASE, lower-case and MiXeD-cAsE are allowed
Test cases:
```
2, 2 => EENN
2, 3 => ENENN
1, 0 => NES
-1, 0 => NWS
-1, -1 => ESWNWS
3, 4 => ENNENEN
-9, 0 => NWWWWWWWWWS
20, 5 => EEEEEEEEEEEEEEEEEEENENNNN
```
Note: the solutions above are not unique, so your code can have slightly different output. But it's required to output a minimal solution.
Invalid test cases:
```
0, 0 => not required to handle (the solution is an empty string)
1, 0 => N (invalid - the box arrives to x=0, y=1)
1, 0 => E (invalid because the box on its side)
2, 2 => ENWNESENWNES (invalid because it's not minimal)
```
[Answer]
# JavaScript (ES6), ~~146 ... 138~~ 125 bytes
*Saved 2 bytes thanks to @Klaycon*
Takes input as `[x,y]`. Brute-forces a path.
```
p=>eval("for(n=0;s=([X,Y]=p,k=0,++n+'').replace(/./g,n=>n<4&&'ENWS'[X+=~-n%2,Y+=~-~-n%2,k+=(n&2^6)+(k-~n)%3,n]),X|Y|k%6;);s")
```
[Try it online!](https://tio.run/##dcwxC4JAGIDhvV8hgXrHfWem4WKfW2tLQ4oYiJ1RyneHhpP0161ovbaXZ3gf9VSPzXA3T0n6qpYWF4OZmuqerVs9MMIwHZGVORQVGugwBCFI@D4PBmX6ulFsE2xuQJjRfud5/uF4PvllLvAlyY2g@MYvO4GMvOiScME6@SLuxkAVh3wu5s5NUp6Oa740mkbdq6DXN9ay0onAiSrOVxaPbb4FJ7S4/O9ya/vE4Ow@vrwB "JavaScript (Node.js) – Try It Online")
### How?
The position of the top face is \$k \bmod 6\$:
$$\begin{array}{c|c|c|c|c|c}
0&1&2&3&4&5\\[5px]
\hline
\text{top}&\text{left}&\text{back}&\text{bottom}&\text{right}&\text{front}
\end{array}$$
The current direction is \$n\$:
$$\begin{array}{c|c|c|c}
0&1&2&3\\[5px]
\hline
\text{East}&\text{North}&\text{West}&\text{South}
\end{array}$$
Given \$k\$ and \$n\$, the new position of the top face is:
$$k'=k+((n\operatorname{and}2)\operatorname{xor}6)+((k+n+1)\bmod3)$$
The values of \$k'\bmod6\$ given \$n\$ and \$k\bmod6\$ are summarized in the following table:
$$\begin{array}{c|cccccc}
k \bmod 6 & 0 & 1 & 2 & 3 & 4 & 5\\
\hline
n = 0 & 1 & 3 & 2 & 4 & 0 & 5\\
n = 1 & 2 & 1 & 3 & 5 & 4 & 0\\
n = 2 & 4 & 0 & 2 & 1 & 3 & 5\\
n = 3 & 5 & 1 & 0 & 2 & 4 & 3
\end{array}$$
### Commented
*Note: this is a version without `eval()` for readability*
```
p => { // p = [x, y] = starting position
for( // main loop:
n = 0; // start with n = 0
s = ( // s is the move string that we're going to build
[X, Y] = p, // start with [X, Y] = starting position
k = 0, // start with k = 0
++n + '' // increment n and coerce it to a string
).replace(/./g, n => // for each digit n in the resulting string:
n < 4 && // abort if n is greater than or equal to 4
'ENWS'[ // replace it with a direction character
X += ~-n % 2, // X += dx
Y += ~-~-n % 2, // Y += dy
k += // update k
(n & 2 ^ 6) + //
(k - ~n) % 3, //
n // actual index for the direction character
] //
), // end of replace()
X | Y | k % 6; // stop when X = Y = k mod 6 = 0
); // end of for()
return s // return the solution
} //
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~62~~ ~~59~~ 54 bytes
```
`J@4_YA4L)XH^sG=0H"'(-9@%3Vuao'F6Za4e@b3$)]>~}'NWSE'H)
```
Input is a complex number.
(Don't) [Try it online!](https://tio.run/##y00syfn/P8HLwSQ@0tHERzPCI67Y3dbAQ0ldQ9fSQdU4rDQxX93NLCrRJNUhyVhFM9aurlbdLzzYVd1D8/9/XUNtgywA "MATL – Try It Online")
The program is quite slow, and times out online for all of the test cases, but works offline. Here's an example with two test cases:
[](https://i.stack.imgur.com/ARbBZ.gif)
### Explanation
Let the four directions in which the cube can be rolled be numbered as
```
1: N, 2: W, 3: S, 4: E.
```
Let the six positions of the cube faces be numbered as
```
0: top, 1: north, 2: west, 3: south, 4: east, 5, bottom
```
The face which is initially at the top will be called "reference face".
The essential part of the code is a matrix **M** that indicates, for any direction of roll (matrix row) and given the current position of the reference face (matrix column), what is the new position of the reference face:
```
1 2 3 4 5 0
-----------
1| 5 2 0 4 3 1
2| 1 5 3 0 4 2
3| 0 2 5 4 1 3
4| 1 0 3 5 2 4
```
For instance, *M*(4,2) = 0 indicates that if the cube is rolled east (4) when the reference face is on the west side of the cube (2), the reference face moves to the top (0).
This matrix is stored in the program in compressed form. It has been represented with column index 0 at the end because MATL's indexing is 1-based and modular, so 0 represents the last column.
The code generates all paths, with increasing length, until a solution is found. Each path is a sequence of numbers 1, 2, 3, 4, indicating roll directions. A path is a solution if it arrives at the destination (\*) with the reference face at the top (\*\*). To see how these conditions are checked, consider an example path 1,4,1,3,4 (NENSE).
* (\*) The first condition is checked using complex-number operations. The imaginary unit *j* raised to each number in the path gives a direction in the complex plane. The sum of all the complex numbers is the final location for the path. In this example, *j*^1 + *j*^4 + *j*^1 + *j*^3 + *j*^4 = *j*+1+*j*−*j*+1 = 2+*j*. This is compared with the input.
* (\*\*) The second condition is checked by repeatedly indexing into the above matrix. The initial position of the reference face is 0 (top). Since the first step of the path is 1 (N), we read *M*(1,0) = 1. So the reference face is now in the north side (1) of the cube. The next step of the path is 4 (E), and *M*(4,1) = 1. Next, *M*(1,1) = 5; and so on. The final result should be 0 for the path to be valid.
To generate all paths we increase a counter starting at 1, convert to base 4 with digits 1,2,3,4 instead of 0,1,2,3, and remove the first digit. If the first digit were not removed, paths starting with 1 (which is the zero digit in this numbering system) would not be generated.
```
` % Do...while
J % Push j (imaginary unit)
@ % Push loop counter, starting at 1. Each value generates a path
4_YA % Convert to base 4 using 1,2,3,4 as digits
4L) % Remove first digit. This is the path
XH % Copy into clipboard H
^ % Element-wise power
s % Sum
G= % Does it equal the input? This gives true (1) or false (0) (*)
0 % Push 0. This is the initial position of the reference face
H % Push path again
" % For each step in the path (with value 1, 2, 3 or 4)
'(-9@%3Vuao' % Push this string
F6Za % Convert base from ASCII chars except single quote to base 6
4e % Reshape as a 4-column matrix. This is matrix M
@ % Push current step
b % Bubble up: move current position of reference face to top of stack
3$) % Index into the matrix. This updates the position of reference face
] % End. Top of stack contains the final position of reference face (**)
>~ % Less than or equal? This gives false if and only if (*) is 1 and
% (**) is 0, which means a solution has been found; and in that case
% the loop will be exited
} % Finally: execute on loop exit
'NWSE' % Push this string
H % Push current path, which is the solution
) % Index. This gives a string with 1 replaced by 'N' etc
% Implicit end. The loop exits if the top of the stack is falsy
% Implicit display
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 78 bytes
```
≔⁰ζW¬υ«≔↨ζ⁵εFε≔I§§⪪”)➙∨¤nDχτ⁺yφφY”⁷⊖κιι¿∧∧⁼¹ι⁼⁻№ε²№ε⁴Iθ⁼⁻№ε¹№ε³Iη⊞Oυ⍘ζ NESW≦⊕ζ
```
[Try it online!](https://tio.run/##dZDBboMwDIbP7VNYnByJSYEAO/TEuh56aFeJw84RuCUaCzQJ29Rpz84CRWiXHSzL@fzb8V/W0pStbIYht1ZdNPIQbmyz/qxVQ4DH1mHPGHyvVzN/kpbwFkLKQiDfuDq3BpAYzHwrrcPc7XVFX0suukY5DHiciShNuIizJEp5EoksjXkaR0kmeBDCo5/5TKWhd9KOKnxj/kFN4RepM2Cuqyl21142FqM7nquD0r3FbdtrhxRC7MlSJOOo6W9Xxv6VRH8lYpHUXsLgZJQHp97WLx0Z6VqDfQijH4Xz6DK6EsBxV7wGvn0D1FiCg@xmY/Z6Oexu8c8wCEiGh4/mFw "Charcoal – Try It Online") Link is to verbose version of code. Brute-forces the answer by trying all strings of letters `NESW` until a solution is found. Explanation:
```
≔⁰ζ
```
Start counting through the strings.
```
W¬υ«
```
Repeat until a solution is found (in which case we'll push it to the empty list so that the loop will terminate). This always sets the loop variable to `1` (true).
```
↨ζ⁵ε
```
Convert the counter to a string of `NESW` letters. This ought to be done in bijective base 4 but Charcoal doesn't do bijective base conversion so it's golfier to do it in base 5 and filter out the zeros later.
```
Fε
```
Loop through each direction.
```
≔I§§⪪”)➙∨¤nDχτ⁺yφφY”⁷⊖κιι
```
Update the loop variable with the result of rolling the box in that particular direction using a look-up table, but if we hit a zero then the box falls into an impossible state from which it can never return to being the right-side up, thus excluding invalid solutions.
```
¿∧∧⁼¹ι
```
If the loop variable is back to 1 (meaning that the box is the right way up again)...
```
⁼⁻№ε²№ε⁴Iθ
```
... and the box is at the right x-coordinate...
```
⁼⁻№ε¹№ε³Iη
```
... and the box is at the right y-coordinate...
```
⊞Oυ⍘ζ NESW
```
... then convert the base-5 number to a string of direction letters, push it to the empty list, and print the resulting list (this has no effect on the output) ...
```
≦⊕ζ
```
otherwise increment the string counter.
[Answer]
# [PHP](https://php.net/), ~~230~~ ~~223~~ ~~213~~ ~~211~~ 202 bytes
```
function($a,$b){for(;;){$f=$x=$y=0;$q='';foreach(str_split(base_convert($i++,10,4))as$d){$q.='ENWS'[$d];$f='132405213540402135510243'[$f+$d*6];$x-=--$d%2;$y-=~-$d%2;}if([$x,$y,$f]==[$a,$b,0])return$q;}}
```
[Try it online!](https://tio.run/##bY9NT4QwEIbv/Iq6GUORspQvE1MbT169ePCAZMNCEeJaPto1kM3617HrGjXE00yeeeedd7q6m2/vurqzLJB8rvay0E0rMeQEts6hagfMmHOAisPIYeKUQc9tm5mByIsaKz1sVLdrNN7mSmyKVr6LQWNoXJcElMSOkysojUG/5vb9w9OjnUKZMeNnB1EY0yQMoiSmMT3VJKBhHBlF5UJ5dW1ko8c9D8rLkMHk8Y9ze2wqnMJIYCJQZZynX2EJzZxB6P0goWfH48wsy/eRFkqjwkRTlijqFoHEIQmd9epZrtgfFC1RQOgSef8zL1jCyPy91N387vr@z11Kkm@KTmHzV6FQjnatfEG6eRMX8yc "PHP – Try It Online")
-2 bytes thanks to @Kevin Cruijssen
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 147 bytes
```
x""<>StringPart["ENWS",1+SelectFirst[Join@@({0,1,2,3}~Tuples~#&/@Range@10),6∣Fold[#+#2~BitAnd~2~BitXor~6+Mod[#+#2+1,3]&,0,#]&&Total[I^#]==x&]]
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7v@L9pIVKSjZ2wSVFmXnpAYlFJdFKrn7hwUo6htrBqTmpySVumUXFJdFe@Zl5Dg4a1QY6hjpGOsa1dSGlBTmpxXXKavoOQYl56akOhgaaOmaPOha75eekRCtrKxvVOWWWOOal1IEZEflFdWbavvkQKW1DHeNYNR0DHeVYNbWQ/JLEnGjPOOVYW9sKtdjY/wFAp5REp0XrGup6Arm6hgq6hgA "Wolfram Language (Mathematica) – Try It Online")
You need to change `10` to a larger number to enable calculation for longer paths (and much slower).
Take complexes as input, e.g. `1+I` as `[1, 1]`.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~266~~ 236 bytes
* -30 thanks to *@ceilingcat*
the formula is based on *@Arnauld* 's answer
```
x,y,L,i,F,G,P[98];O(I,M,N,j){if(F=I-L)for(j=0;j<4;O(I+1,F=j%2?M+2-j:M,G=j%2?N:N+3-j))P[I]=j++;else{for(i=L;i--;)F+=(P[i]&2^6)+(P[i]-~F)%3;if(F%6<1&x==M&y==N){for(;++i<L;)printf(L"ENWS"+P[i]);exit(0);}}}K(X,Y){x=X;for(y=Y;;L++)O(0,0,0);}
```
[Try it online!](https://tio.run/##RY3dasJAEIWvzVOElIQddraYWKR1XHrViJhEoRdVxILkp93FxqK2JIT01dOsvSgDM3M455tJxVuadl2FNUaoMMQZrrYP9ztasjnGmKCGRhUslHMRQXE8MS2HpKd3xuc@hlK7wWPMA6EnMc6uKpkkfCQ0wGo730nNOeWHc94YWMmIlBAEIZdstVU7L3gdA7@u4icEd0TmmTue@l4lZezVUiZwRYlzNY0IPk@qvBQscp6Sl2eHGxIor9SFDYHatl2wNW6gqeSaDFbLDVHEOSzZEPvqM92NKtPDV5bbzvmSqePtu2NZ/VH7Y69KBlZjDYz63p98ND0ga3BO92XBHDdzMwdt788zI4DeXbD/cK/bTvi28H8B "C (gcc) – Try It Online")
### much faster but longer. Solves `20, 5` in 0.088s
```
#define Q for(i=0;i<L;i++
x,y,L,i,F,G,P[98];O(I,M,N){if(abs(x-M)+abs(y-N)<=L-I){if(I==L){F=0;Q)F+=(P[i]&2^6)+(P[i]+F+1)%3;if(F%6<1){Q)putchar("ENWS"[P[i]]);exit(0);}}else for(int j=0;j<4;j++){P[I]=j;F=M;G=N;if(j%2)G+=2-j;else F+=1-j;O(I+1,F,G);}}}K(X,Y){x=X;y=Y;for(;;L++)O(0,0,0);}
```
[Try it online!](https://tio.run/##RY9fa4MwFMWf56cQiyWXxKFuKxvXPM4itbZlD2sRB84/a6Szo9phET@7S9qHEUjO5Zz8cpJZX1k2jpO8KEVd6Bu9PJ6I4DYKL0RBqdaxCwuZYD6bs3X88pzgigRsySLoRUnSz4Z01hKoEhcrAo@HVnC1As5D6H2J2oBPOVnHIpm6HzOgV0l96oD5gDLpmzPPgX4DP@c226cnYrxG729GrGIJYNGJltiAw1AcmuJWsG71SpIr7xErSqFfx0HCK/T5Euc8UtDKdGFOuWtVeL0mKzhSy/LUUZ9RvGFBtmwHfce3eOE7VGjEUAJXxGZyydA4EXV2OOeFbjRtLo73e0PT1PvfqagJaL12p6bf9OQwtbuo3TVZWpfEMHMzN5g@vXnqcEG6C/IflvMwurb@9Ac "C (gcc) – Try It Online")
Prune at `Manhattan distance between current location & destination > remaining steps`
Usage: `K(x, y)`
[Answer]
# IA-32 machine code, 161 bytes
Hexdump:
```
60 e8 0d 00 00 00 03 05 09 11 15 29 51 00 0f 17
65 77 57 5e 8b 46 0a 66 bb 6e 73 8b 7c 24 24 85
c9 79 04 f7 d9 86 c4 85 d2 79 04 f7 da 86 df 3b
ca 73 03 93 87 ca 83 f9 05 76 09 aa aa aa aa 83
e9 04 eb eb 8d 2c 11 2b ca 4a 79 15 83 f9 04 66
9c 74 03 88 1f 47 f3 aa 66 9d 74 3e 88 3f 47 eb
39 4a 79 26 83 f9 03 75 09 aa 88 1f 47 aa aa aa
eb 28 88 1f 47 49 79 04 88 27 47 41 e3 02 f3 aa
88 1f 47 aa 88 3f 47 aa eb 10 03 f1 8a 0c 96 50
d0 e9 0f 42 c3 aa 58 4d 75 f5 c6 07 00 61 c2 04
00
```
Assembly source (MS Visual Studio inline-assembler style):
```
pushad;
call skip0;
_emit(0x03);
_emit(0x05);
_emit(0x09);
_emit(0x11);
_emit(0x15);
_emit(0x29);
_emit(0x51);
_emit(0x00);
_emit(0x0f);
_emit(0x17);
_emit('e');
_emit('w');
_emit(0x57);
skip0:
pop esi;
// ecx = x
// edx = y
mov eax, [esi + 10]; // al = 'e', ah = 'w'
mov bx, 'sn'; // bl = 'n', bh = 's'
mov edi, [esp + 0x24]; // edi = pointer to output
test ecx, ecx;
jns skip1;
neg ecx;
xchg al, ah;
skip1:
test edx, edx;
jns skip2;
neg edx;
xchg bl, bh;
skip2:
;// now there are no negative coordinates
myloop4:
cmp ecx, edx;
jae skip3;
xchg eax, ebx;
xchg ecx, edx;
skip3:
;// now x >= y
cmp ecx, 5;
jbe myloop4_done;
stosb; // output 'e'
stosb; // output 'e'
stosb; // output 'e'
stosb; // output 'e'
sub ecx, 4;
jmp myloop4;
myloop4_done:
;// now y <= x <= 5
lea ebp, [ecx + edx];
sub ecx, edx;
dec edx;
jns check1;
// Processing y = 0
cmp ecx, 4;
pushf;
je skip4;
// Processing y = 0, x != 4
mov [edi], bl; // output 'n'
inc edi;
skip4:
rep stosb; // output 'eee...e'
popf;
je done;
// Processing y = 0, x != 4
mov [edi], bh; // output 's'
inc edi;
jmp done;
check1:
dec edx;
jns do_n;
// Processing y = 1
cmp ecx, 3;
jne skip6;
// Processing y = 1, x = 4
stosb; // output 'e'
mov [edi], bl; // output 'n'
inc edi;
stosb; // output 'e'
stosb; // output 'e'
stosb; // output 'e'
jmp done;
skip6:
// Processing y = 1, x != 4
mov [edi], bl; // output 'n'
inc edi;
dec ecx;
jns skip7;
mov [edi], ah; // output 'w'
inc edi;
inc ecx; // set ecx = 0
skip7:
jecxz skip8;
rep stosb; // output 'eee...e'
skip8:
mov [edi], bl; // output 'n'
inc edi;
stosb; // output 'e'
mov [edi], bh; // output 's'
inc edi;
stosb; // output 'e'
jmp done;
// Processing y > 1
do_n:
add esi, ecx;
mov cl, [esi + edx * 4];
myloopn:
push eax;
shr cl, 1;
cmovc eax, ebx;
stosb; // output 'e' or 'n'
pop eax;
dec ebp;
jnz myloopn;
done:
mov byte ptr [edi], 0;
popad;
ret 4;
```
It is a "prescriptive" algorithm - it doesn't search but generates the output using patterns which I found separately.
First of all, it transforms the input by reflections, such that 0 ≤ y ≤ x. The reflections are implemented by negations of `x` and `y` and some register swaps.
Then, it subtracts 4 from x repeatedly, until x ≤ 5. While doing this, transposing is sometimes necessary to keep 0 ≤ y ≤ x.
Afterwards, the following holds: 0 ≤ y ≤ x ≤ 5. This is a finite set of cases, further subdivided into y = 0, y = 1 and y > 1.
---
If y = 0:
* If x ≠ 4, output `n` in the beginning and `s` at the end.
* In any case, output `e` x times.
---
If y = 1:
* If x = 4, the output is `eneee`.
* If x = 1, the ouptut is `nwnese`
* Otherwise, the ouptut is `n(e...)nese` - here `e` is repeated x-2 times.
---
If y = 2:
There are 10 cases:
```
x = 2 y = 2: nnee
x = 3 y = 2: nenee
x = 4 y = 2: neenee
x = 5 y = 2: neeenee
x = 3 y = 3: nenene
x = 4 y = 3: neenene
x = 5 y = 3: neeenene
x = 4 y = 4: nnnneeee
x = 5 y = 4: nnneneeee
x = 5 y = 5: nnneneneee
```
I encode them using 1 bit per character, `n` = 1, `e` = 0, starting from LSB. Their length is x + y, which makes decoding easy. Even though some of them contain more than 8 bits, the MSB are zero, so they all fit into 1 byte.
Also, because y ≤ x, some entries in the 4x4 table are unused. Two of them are adjacent, so I use them to store the bytes `w` and `e` there.
] |
[Question]
[
This challenge was inspired by [@HelkaHomba](https://codegolf.stackexchange.com/users/26997/helka-homba)'s excellent challenge [Red vs. Blue - Pixel Team Battlebots](https://codegolf.stackexchange.com/q/48353/58826). That challenge was probably the best one I've seen on this site. Ever.
My challenge is still a lot different, but @HelkaHomba deserves credit for the inspiration.
# Overview
This is a team [king-of-the-hill](/questions/tagged/king-of-the-hill "show questions tagged 'king-of-the-hill'") where your team wins by having all players alive on your team. In other words, last team standing wins. Draws will be re-done.
You are on a board. You know your position *on the first round (tick 0).* You also know who is in the area around you:
[](https://i.stack.imgur.com/X78JP.png)
In this case, you are all alone (or so you think) with no-one around you. You can see surrounding items in the first argument to your `ontick` handler. More about the API later.
# Your team
Your team is determined by your user ID. To find that out, click on your profile picture:
[](https://i.stack.imgur.com/nVcDp.png)
Then find your user ID in the address bar:
[](https://i.stack.imgur.com/Wn7nU.png)
**If it is odd, you are on the blue team.**
**If it is even, you are on the red team.**
You're welcome for the hand-drawn circles.
# Your (bot's) name
Your bot's name starts with the first letter of your team ("r" or "b"). It must match the regex `/^(r|b)[A-Za-z_-]$/`. Other than that, you can pick your bot's name. Please don't use an already-existing one.
# Starting
The red players will start near the top of the map, and the blue will start near the bottom. You are given special info on the first tick (turn) in the `environment` parameter for the `ontick` function. I recommend storing that. See the API for details.
# On your turn
Turn order is randomized initially, but then stays the same.
## Turn actions
You may only do one action per turn.
* ### Move
When you would like to move, you call `this.move(num)` in the API. `num` is the cell you would like to move to:
[](https://i.stack.imgur.com/M02jy.png)
The relative locations of the numbers you can move to are stored in the global constant `threeByThree`:
```
[
[0, 1, 2],
[3, undefined, 4],
[5, 6, 7]
]
```
If you move into a wall, or another player, *nothing happens.*
* ### Rotate
To rotate, you call `this.rotate(num)`. Num is the direction you want to rotate:
[](https://i.stack.imgur.com/Bw6jP.png)
Rotation is absolute.
* ### Kill
If another player (from another team) is in the cell you are facing, you can call `this.kill()` and kill them. If there is no-one there, or they are on your team, this does nothing. Example:
[](https://i.stack.imgur.com/ioEQC.png)
If you are turned to `0`, you can kill green. If you are are turned to 1, you can kill blue. If you are are turned to 2, you can kill orange. If you are are turned to 3, you can kill yellow.
* ### Bomb
Bombing kills *all players **including you and teammates*** in the 9 squares around you. Example:
[](https://i.stack.imgur.com/q7hgI.png)
**Why would you ever want to do this?** [Kamikaze](https://en.wikipedia.org/wiki/Kamikaze). If there are more players *not on your team* in the 9 cells around you then there are on your team, you might consider bombing. (I suggest you notify your comrades first!)
* ### Place a landmine
This creates a death square for others not on your team. When you place a land mine, you also move so you don't step on it. You call `this.landMine(num)` where num is the square you want to go to. Example:
[](https://i.stack.imgur.com/X78JP.png)
Then you call `this.landMine(4)`:
[](https://i.stack.imgur.com/VT2Xg.png)
See that "M"? It's a landmine. Others can see it...for now. Anyone, even those not on your team, can see a landmine on the tick it is placed. But after that tick is over, *no-one, not even you* can see it. But it will explode as soon as an enemy walks over it. Example:
[](https://i.stack.imgur.com/b8afv.png)
Blue moved on your landmine, and BOOM! You just got another kill.
For every 2 kills you get (from direct killing or land mines), you get 1 extra landmine to place. You also get one at the start.
* ### Dig
When you dig, you look for landmines in a 5x5 area centered around you. This does not show the team of the bot that placed the landmine. (Remember that you can't be killed by a landmine placed by someone on your team.) For example, if this was the grid around you:
[](https://i.stack.imgur.com/nhpD4.png)
Then the return value of `this.dig()` would be:
```
[undefined,undefined,undefined,true,undefined,
undefined,undefined,undefined,undefined,undefined,
undefined,undefined,undefined,undefined,
undefined,undefined,true,undefined,undefined,
true,undefined,undefined,undefined,undefined]
```
The array indexes are from starting in the top left, going right, than down, not including yourself:
[](https://i.stack.imgur.com/dlO6u.png)
There are 23 in total, and their relative locations are stored in the global constant `fiveByFive`:
```
[
[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9],
[10, 11, undefined, 12, 13],
[14, 15, 16, 17, 18],
[19, 20, 21, 22, 23]
]
```
Note that dig reveals mines placed on previous ticks, unlike `aroundMe`.
## Communication
When you want to talk to someone, you call `this.sendMessage(recipients, team, data)`. The data can be *anything you want,* and you can send it to *anyone you want, even players on other teams.* This can be used to trick poorly-programmed bots, but all players can see who sent a message and who's team they are on.
Example:
### Send something to a bot named "redisbest":
```
this.sendMessage("redisbest", undefined, "Hi!");
```
### Send something to a bot named "redisbest" and "blueiscool":
```
this.sendMessage(["redisbest", "blueiscool"], undefined, {hello: "there"});
```
### Send something to the entire red team
```
this.sendMessage(undefined, "red", {hello: "red"});
```
### Send something to *everyone*
```
this.sendMessage(undefined, "*", {hello: "everyone"});
```
### Send something to the entire red team and a bot named "blueiscool":
```
this.sendMessage("blueiscool", "red", {hello: "bots"});
```
## API
### Your code must consist of a *single call* to the `createBot` function. Nothing else. Sample code:
```
createBot({
ontick: function(environment) {
return new Promise((resolve, reject)=>{
this.move(0);//example
resolve();//please call this when you are done
});
},
onmessage: function(data, from, fromBot) {
console.log("onMessage: " + this.name + " from " + this.team + " got message ", data, " from " + from + ", on team " + fromTeam);
this.sendMessage(["bot", "otherbot"], "team", "some data");
},
team: "red",//your team
name: "rmyteamname",//team name must begin with the first letter of your team's name
onkill: function(){
//say goodbye
}
});
```
(You are free to copy-paste this. Just modify it for your team, etc.)
### Methods
* `ontick(environment)`
Called when it's your turn. Must return a `Promise` that resolves in 1 second or less or it will be ignored. This is for performance reasons and has the nice side-effect of not having the tab hang.
**`this` (when in ontick)**
+ `landMines`
How many land mines you have left. *The more kills you have, the more land mines you get.* For every 2 bots you kill, you get 1 more landmine. You also get 1 to start.
+ `direction`
The direction you are facing.
+ `storage`
Storage that persists between calls to `onTick` and `onMessage`. An empty object at start. Modify for any purpose, but make sure it's an array or object always to ensure it persists correctly.
+ `move(num)`
Move to the specified position. Does nothing if invalid. See above for details.
+ `rotate(num)`
Rotate to the specified position. Does nothing if invalid. See above for details.
+ `kill()`
Kills the player you are facing, if exists and is not on your team. See above for details.
+ `bomb()`
Kills anyone in the 9 squares around you, including yourself.
+ `landMine(num)`
Places a land mine where you are, and then moves to the specified position. Does nothing if invalid `num` or you have none left. See above for details.
+ `dig()` **new!**
Returns an array of info about the landmines in a 5x5 area centered around you. See above for details.
+ `sendMessage(recipients, team, data)`
`recipients` can either be a single bot (string), an array of bot, or `undefined`/`null`. It is who you would like to send the message.
`team` is a string of the team you would like to send the message. Use `"*"` to send a message to everyone.
`data` is anything that can be passed to a JS function. It is send to the recipients. If it is an object or array, it is *passed by reference*, so you and the recipient(s) can save that to their `storage` and any modifications to the object affects both bot's copies.
Note that recipients that are in *either* the list of bots, the exact bot specified in the string, *or* a bot on the team you specified, it will get the message.
**`environment`**
*On the first tick*
* `x`: Your player's x-position
* `y`: Your player's y-position
* `gridWidth`: The width of the grid (in cells)
* `gridHeight`: The height of the grid (in cells)
*On all ticks*
* `aroundMe`: An array of players and landmines. The players are objects that look like `{name: "bot name", team: "bot team"}`, and the landmines are `{team: "team of bot who placed mine"}`. The indexes of the array:
[](https://i.stack.imgur.com/M02jy.png)
Note that landmines placed on a tick *other than* the current one will not be shown.
**`aroundMe` example:**
Let's say this is the grid (you are red):
[](https://i.stack.imgur.com/9Sy4Q.png)
Your `aroundMe` will look like this:
```
[
{name: "bexamplebluebot", team: "blue"},
undefined,//sparse array, nothing in index 1
undefined,//there is technically a landmine here, but it wasn't placed this tick, so it is not shown
undefined,//nothing in 3
{name: "yexampleyellowbot", team: "yellow"},
{team: "red"},//this is a landmine, you can tell is not a bot because it has no name. mines have the team name of the player they were placed by. This mine was placed this tick, otherwise you couldn't see it
//nothing else after index 5, so the array's length is 5.
]
```
The indexes of the array are explained here:
[](https://i.stack.imgur.com/M02jy.png)
Your bot effectively sees this:
[](https://i.stack.imgur.com/HJIcf.png)
* `onmessage(data, fromBot, fromTeam)`
**`this` (when in onmessage)**
+ `sendMessage(recipients, team, data)` Standard message sending function.
+ `storage` Standard storage.`data` The data sent from the sender.
`fromPlayer` The player the message was sent from.
`fromTeam` The team the message was sent from.
* `onkill()`
**`this` (when in onkill)**
+ `sendMessage(recipients, team, data)` Standard message sending function.
## Convenient (constant) global arrays:
### `threeByThree`:
```
[
[0, 1, 2],
[3, undefined, 4],
[5, 6, 7]
]
```
Useful for passing data to the move function as well as interpreting `aroundMe`. See above.
### `fiveByFive` :
```
[
[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9],
[10, 11, undefined, 12, 13],
[14, 15, 16, 17, 18],
[19, 20, 21, 22, 23]
]
```
Useful for the `this.dig()` function in the `ontick` handler.
# Try it out!
The controller will be run from my machine on localhost for performance reasons, but you can use [the CodePen](https://codepen.io/programmer5000/full/jBjbVj/) to test your bot out.
Note that you must paste your code in the console and press `Enter` before you click run. You can paste in as many bots as you'd like. The "Test bots" are examples for you to test against. If you can beat or tie all of them, you have at least a decent bot.
# Submissions
## Rules
### Rules (enforced by the controller)
* Your main `ontick` code must not take more than 1 second. We don't want rounds to take forever. If your code takes > 1 second, it will be stopped.
* If you attempt to do more than 1 action per turn, or do an invalid action (eg. `this.move(-1)` or moving into a wall), it will be ignored.
* More may come soon...
### Rules (enforced by me, can result in DQ)
* Don't *write* global variables (*reading is fine*).
* Your code must work in Nodejs (in case the controller is ported to Nodejs), so `JSON.parse(...)` is fine, but `alert()` is not.
* You are not allowed to call `createBot` or interfere with the controller in *any way*.
* Don't use someone's else's code without permission and significant changes. No copybots.
* Please, no loopholes!
* More may come soon...
## My bots
Here are some bots:
This bot randomly chooses an action. Well, it's a weighted random, but still pretty random. If you can *kill* this bot (it will eventually kill itself, that doesn't count), than you have at least a decent bot. Post it and see what happens!
```
createBot({
ontick: function(environment) {
return new Promise((resolve, reject)=>{
if(Math.random() < 0.02){
this.bomb();
}else if(Math.random() < 0.1){
this.kill();
}else if(Math.random() < 0.3){
this.rotate(~~(Math.random() * 4));
}else{
this.move(~~(Math.random() * 8));
}
resolve();
});
},
team: "none",
name: "xrandomness2",
onkill: function(){
console.log("Goodbye world... :(");
}
});
```
My bots have a name beginning with "x" and a team of "none". You are welcome to use some of this code, but please do at least *some* modification. If you can't be bothered to at least tweak a number, you won't win.
## Formatting your submission
Please use this format:
```
# rmyamazingbot
createBot({
ontick: function(environment) {
return new Promise((resolve, reject)=>{
this.move(0);//example
resolve();//please call this when you are done
});
},
onmessage: function(data, fromTeam, fromBot) {
console.log("onMessage: " + this.name + " from " + this.team + " got message ", data, " from " + from + ", on team " + fromTeam);
this.sendMessage(["bot", "otherbot"], "team", "some data");
},
team: "red",//your team
name: "rmyteamname",//team name must begin with the first letter of your team's name
onkill: function(){
//say goodbye
}
});
Long, but cool explanation...
```
# Feature requests, bugs, questions, etc?
Comment below! Please check to see if there is already a comment with that. If there is one already, upvote it.
# Want to talk to your team?
Use the chat rooms for [red](http://chat.stackexchange.com/rooms/57634/king-team-of-the-hill-red-team) and [blue](http://chat.stackexchange.com/rooms/57633/king-team-of-the-hill-blue-team).
# Language
Currently, only JS and something that compiles to JS is supported, but if you know of a way to get other languages to work with Nodejs I would be happy to port the controller to Nodejs.
# Final notes
## Strategy ideas
Help your team! Creating a bot that is designed to help another bot and work together. This strategy [worked well](https://codegolf.stackexchange.com/a/48435/58826) for [Red vs. Blue - Pixel Team Battlebots](https://codegolf.stackexchange.com/questions/48353/red-vs-blue-pixel-team-battlebots)
## Rep seekers
I will accept the highest voted answer on the winning team. Keep in mind that earlier answers tend to get more votes, but their weaknesses are more likely to be found and exploited.
Also, if you answer soon, you might get the +100 bounty.
[Answer]
# xscared (non-competing)
```
createBot({
ontick: function(environment) {
var reverse = [0, 1, 2, 3, 4, 5, 6, 7].reverse();
return new Promise((resolve, reject)=>{
(this.aroundMe || []).forEach((item,idx)=>{
this.move(reverse[idx]);
return resolve();
});
this.move(~~(Math.random() * 8));
return resolve();
});
},
onmessage: function() {
},
team: "none",
name: "xscared",
onkill: function(){
}
});
```
Very scared of people. Goes away from the first person (or landmine) it sees. Otherwise, it moves randomly. Note that this is not competing, just an example. Try to beat it!
[Answer]
# backup, a blue bot
As warned in chat, I never wrote anything in javascript in my life, so if you find any mistake, please tell me! (Thanks to @programmer5000 for already helping me with it)
The concept of this bot is that it communicates with other bots from the same team and send them its position along with a map of the mines it found. It tries to join the closest blue bot (if one send its position data [given as an [x,y] array]), and stays near it (with its back to it as much as possible), killing approaching red bots or looking ahead for mines.
```
createBot({
team: 'blue',
name: 'backup',
ontick: function(environment) {
return new Promise((resolve, reject) => {
//if (typeof this.x != "undefined") this.storage['position'] = [this.x, this.y];
if (typeof environment.x != "undefined") this.storage['position'] = [environment.x, environment.y]; //Modified according to @WasteD
if (typeof this.storage['map'] == "undefined") { //Create empty map
var map = [[]];
//for(i=0;i<this.gridHeight;i++) map[i]=[];
for(i=0;i<environment.gridHeight;i++) map[i]=[]; //Modified according to @WasteD
this.storage['map'] = map;
}
var blue = []
var red = []
var x = this.storage['position'][0];
var y = this.storage['position'][1];
var dx = [-1, 0, 1, -1, 0, 1, -1, 0, 1]
var dy = [1, 1, 1, 0, 0, 0, -1, -1, -1]
(this.aroundMe || []).forEach((item, idx) => { // Update map and list positions of surrounding blues and reds
if (item && item.team == 'red' && typeof item.name != "undefined") red += idx;
if (item && item.team == 'red' && typeof item.name == "undefined") this.storage['map'][x+dx[idx]][y+dy[idx]] = 'M';
if (item && item.team == 'blue' && typeof item.name != "undefined") blue += idx;
});
this.sendMessage(undefined, "blue", {"position": this.storage['position'], 'map': this.storage['map']}); //Send to buddies my position and the map
if (red.indexOf([1, 4, 6, 3][this.direction]) > -1) this.kill() ; //If red guy is in front of
else if (red.indexOf([1,4,6,3]) > -1) this.rotate(red.indexOf([1,4,6,3])); //If red guy is next but not in front of
else if (blue.indexOf(3) > -1){ //If blue buddy on the left
if (blue.indexOf(4) > -1){ //If another one is on the right
if (blue.indexOf(1) > -1 && this.direction != 2) this.rotate(2); //...and a third one at the top
else var digging = this.dig();
}
else if (this.direction != 1) this.rotate(1);
else var digging = this.dig();
}
else if (blue.indexOf(1) > -1){
if (blue.indexOf(6) > -1 && this.direction != 3) this.rotate(3);
else if (this.direction != 2) this.rotate(2);
else var digging = this.dig();
}
else if (blue.indexOf(4) > -1){
if (this.direction != 3) this.rotate(3);
else var digging = this.dig();
}
else if (blue.indexOf(6) > -1 && this.direction != 0) this.rotate(0);
else if (blue.indexOf([0,2]) > -1){ //If no blue next to me but one in diagonal, move next
this.move(1);
this.storage['position'][1] = y+1; //Update position
}
else if (blue.indexOf([5,7]) > -1){
this.move(6);
this.storage['position'][1] = y-1;
}
else if (typeof this.storage['other_blue'] != "undefined"){ //Check if buddies said where they were, try to go near the closest one
var dmin = 99999;
var pos = []
(this.storage['other_blue'] || {}).forEach((item, idx) => {
var d = Math.sqrt(Math.pow(item['position'][0]-x,2) + Math.pow(item['position'][1]-y,2));
if (d < dmin){
dmin = d;
pos = item['position'];
}
});
if (pos[0]-x > 0){
this.move(4);
this.storage['position'][0] = x+1
}
else if (pos[0] < 0){
this.move(3);
this.storage['position'][0] = x-1
}
else if (pos[1] > 0){
this.move(1);
this.storage['position'][1] = y+1
}
else{
this.move(6);
this.storage['position'][1] = y-1
}
}
else var digging = this.dig();
if (typeof digging != "undefined"){ //Check out surroundings if dig() was played and update the map accordingly
var dx2 = [-2,-1,0,1,2,-2,-1,0,1,2,-2,-1,0,1,2,-2,-1,0,1,2,-2,-1,0,1,2];
var dy2 = [2,2,2,2,2,1,1,1,1,1,0,0,0,0,0,-1,-1,-1,-1,-1,-2,-2,-2,-2,-2];
(digging || []).forEach((item, idx) => {
//if (item && item.team == 'red' && typeof item.name == "undefined") this.storage['map'][x+dx2[idx]][y+dy2[idx]] = 'M';
if (item) this.storage['map'][x+dx2[idx]][y+dy2[idx]] = 'M'; //previously misread what dig() returned
});
}
resolve();
});
},
onmessage: function(data, fromTeam, fromBot) {
if (typeof data['position'] != "undefined" && fromTeam == 'blue') { //If position sent by a blue bot
if (typeof this.storage['other_blue'] == "undefined") this.storage['other_blue'] = [];
for (i in this.storage['other_blue']){
var found = false;
if ('name' in i){
if (i['name'] == fromBot){
i['position'] = data['position'];
found = true; //Update if position already known from previous ticks
}
}
}
if (!found) this.storage['other_blue'] += {'position':data['position'], 'name':fromBot}; //Add position if previously unknown
this.sendMessage(fromBot, undefined, "roger.");
}
},
onkill: function() {this.sendMessage(undefined, "blue", {"position": this.storage['position'], 'map': this.storage['map']});}
});
```
[Answer]
# Blue, blue, my world is blue
```
createBot({
team: 'blue',
name: 'blue-blue-my-world-is-blue',
ontick: function(environment) {
return new Promise((resolve, reject) => {
var red = 0;
// See who's around me
(this.aroundMe || []).forEach((item, idx) => {
if (item && item.team == 'red') red++;
});
// If surrounded, take one for the team
if (red >= 6) this.bomb();
else {
// Translate direction into position
var kill = [1, 4, 6, 3][this.direction];
// Random values
var move = Math.floor(Math.random() * 8);
var nsew = Math.floor(Math.random() * 4);
// Lay a landmine if possible
if (this.landMines) this.landMine(move);
// Kill if someone is in the way
else if (this.aroundMe && this.aroundMe[kill] && this.aroundMe[kill].team == 'red' && this.aroundMe[kill].name) this.kill();
else {
// Move somewhere if already in the requested direction
if (nsew == this.direction) this.move(move);
// Otherwise just rotate to the requested direction
else this.rotate(nsew);
}
}
resolve();
});
},
onmessage: function(data, from, fromBot) {},
onkill: function() {}
});
```
Mostly random, but will bomb if surrounded, and favors checking around and killing over moving.
[Answer]
# Relaxed-Bomber
This bot searches for a spot with at least 1 free cell on each side then plants a mine. It camps on it until an enemy approaches. When someone draws near, he'll step back back and forth on his mine to bait the other bot on it. He'll also rotate and kill if needed. When he doesn't have any mine left, he'll seek refuge on the top-left corner with its back to the wall and retaliate if he's threatened.
No special teamplay here, apart from broadcasting his position to his team with `self` keyword.
```
createBot({
team: 'red',
name: 'relaxed-bomber',
ontick: function(environment) {
return new Promise((resolve, reject) => {
if (typeof this.storage['dropped'] == "undefined") {
this.storage['dropped'] = false;
this.storage['covered'] = false;
this.storage['baited'] = false;
}
if (typeof environment.x != "undefined" && typeof environment.y != "undefined") {
this.storage['pos'] = [environment.x, environment.y];
}
if (typeof environment.gridWidth != "undefined" && typeof environment.gridHeight != "undefined") {
this.storage['grid'] = [environment.gridWidth, environment.gridHeight];
}
var x = this.storage['pos'][0];
var y = this.storage['pos'][1];
var x0 = this.storage['grid'][0];
var y0 = this.storage['grid'][1];
var source = [1, 4, 6, 3];
var dest = [6, 3, 1, 4];
var rot = [0, 1, 2, 3];
var movex = [-1, 0, 1, -1, 1, -1, 0, 1];
var movey = [-1, -1, -1, 0, 0, 1, 1, 1];
var action = false;
if (this.landMines > 0) {
var move = [false, false, false, false];
var moveIndex = -1;
if (x <= 0) { move[1] = true; }
if (x >= x0 - 1) { move[3] = true; }
if (y <= 0) { move[2] = true; }
if (y >= y0 - 1) { move[0] = true; }
if (move[0] && !move[1] && !move[2] && move[3]) { moveIndex = 0; }
if (move[0] && !move[1] && !move[2] && !move[3]) { moveIndex = 1; }
if (move[0] && move[1] && !move[2] && !move[3]) { moveIndex = 2; }
if (!move[0] && !move[1] && !move[2] && move[3]) { moveIndex = 3; }
if (!move[0] && move[1] && !move[2] && !move[3]) { moveIndex = 4; }
if (!move[0] && !move[1] && move[2] && move[3]) { moveIndex = 5; }
if (!move[0] && !move[1] && move[2] && !move[3]) { moveIndex = 6; }
if (!move[0] && move[1] && move[2] && !move[3]) { moveIndex = 7; }
if (moveIndex >= 0) {
this.storage['pos'] = [ x + movex[moveIndex], y + movey[moveIndex]];
this.move(moveIndex);
} else {
this.storage['dropped'] = true;
this.storage['covered'] = false;
this.landMine(1);
}
} else {
if (this.storage['dropped']) {
this.storage['dropped'] = false;
this.storage['covered'] = true;
this.storage['pos'] = [ x + movex[6], y + movey[6]];
this.move(6);
} else if (this.storage['covered']) {
for (var i = 0; i < source.length; i++) {
if (typeof environment.aroundMe[source[i]] != "undefined" && typeof environment.aroundMe[source[i]].team != "undefined" && environment.aroundMe[source[i]].team == "blue" && typeof environment.aroundMe[source[i]].name != "undefined") {
this.storage['covered'] = false;
this.storage['baited'] = true;
this.storage['mine'] = this.storage['pos'].slice();
this.storage['reverse'] = source[dest[i]];
this.storage['pos'] = [ x + movex[dest[i]], y + movey[dest[i]]];
this.move(dest[i]);
action = true;
}
}
if (!action) {
this.dig();
}
} else if (this.storage['baited']) {
for (var i = 0; i < source.length; i++) {
if (typeof environment.aroundMe[source[i]] != "undefined" && typeof environment.aroundMe[source[i]].team != "undefined" && environment.aroundMe[source[i]].team == "blue" && typeof environment.aroundMe[source[i]].name != "undefined") {
if (this.direction == rot[source[i]]) {
this.kill();
this.storage['baited'] = false;
action = true;
} else {
this.rotate(rot[source[i]]);
action = true;
}
}
}
if (!action) {
if (this.storage['mine'][0] == this.storage['pos'][0] && this.storage['mine'][1] == this.storage['pos'][1]) {
this.storage['pos'] = [ x + movex[this.storage['reverse']], y + movey[this.storage['reverse']]];
this.move(this.storage['reverse']);
this.storage['reverse'] = source[this.storage['reverse']];
} else {
this.storage['pos'] = [ x + movex[this.storage['reverse']], y + movey[this.storage['reverse']]];
this.move(this.storage['reverse']);
this.storage['reverse'] = dest[this.storage['reverse']];
}
}
} else {
for (var i = 0; i < source.length; i++) {
if (typeof environment.aroundMe[source[i]] != "undefined" && typeof environment.aroundMe[source[i]].team != "undefined" && environment.aroundMe[source[i]].team == "blue" && typeof environment.aroundMe[source[i]].name != "undefined") {
if (this.direction == rot[source[i]]) {
this.kill();
this.storage['baited'] = false;
action = true;
} else {
this.rotate(rot[source[i]]);
action = true;
}
}
}
if (!action) {
if (x > 0 && y > 0) {
this.storage['pos'] = [ x + movex[0], y + movey[0]];
this.move(0);
} else if (x > 0 && y == 0) {
this.storage['pos'] = [ x + movex[3], y + movey[3]];
this.move(3);
} else if (x == 0 && y > 0) {
this.storage['pos'] = [ x + movex[1], y + movey[1]];
this.move(1);
} else {
this.rotate(1);
}
}
}
}
this.sendMessage(undefined, "red", {'self': this.storage['pos'] });
resolve();
});
},
onmessage: function(data, fromTeam, fromBot) {},
onkill: function() {}
});
```
[Answer]
# Backup 1 another blue bot (forgot to do this earlier)
```
createBot({
team: 'blue',
name: 'backup1',
ontick: function(environment) {
return new Promise((resolve, reject) => {
//if (typeof this.x != "undefined") this.storage['position'] = [this.x, this.y];
if (typeof environment.x != "undefined") this.storage['position'] = [environment.x, environment.y]; //Modified according to @WasteD
if (typeof this.storage['map'] == "undefined") { //Create empty map
var map = [[]];
//for(i=0;i<this.gridHeight;i++) map[i]=[];
for(i=0;i<environment.gridHeight;i++) map[i]=[]; //Modified according to @WasteD
this.storage['map'] = map;
}
var blue = []
var red = []
var x = this.storage['position'][0];
var y = this.storage['position'][1];
var dx = [-1, 0, 1, -1, 0, 1, -1, 0, 1]
var dy = [1, 1, 1, 0, 0, 0, -1, -1, -1]
(this.aroundMe || []).forEach((item, idx) => { // Update map and list positions of surrounding blues and reds
if (item && item.team == 'red' && typeof item.name != "undefined") red += idx;
if (item && item.team == 'red' && typeof item.name == "undefined") this.storage['map'][x+dx[idx]][y+dy[idx]] = 'M';
if (item && item.team == 'blue' && typeof item.name != "undefined") blue += idx;
});
this.sendMessage(undefined, "blue", {"position": this.storage['position'], 'map': this.storage['map']}); //Send to buddies my position and the map
if (red.indexOf([1, 4, 6, 3][this.direction]) > -1) this.kill() ; //If red guy is in front of
else if (red.indexOf([1,4,6,3]) > -1) this.rotate(red.indexOf([1,4,6,3])); //If red guy is next but not in front of
else if (blue.indexOf(3) > -1){ //If blue buddy on the left
if (blue.indexOf(4) > -1){ //If another one is on the right
if (blue.indexOf(1) > -1 && this.direction != 2) this.rotate(2); //...and a third one at the top
else var digging = this.dig();
}
else if (this.direction != 1) this.rotate(1);
else var digging = this.dig();
}
else if (blue.indexOf(1) > -1){
if (blue.indexOf(6) > -1 && this.direction != 3) this.rotate(3);
else if (this.direction != 2) this.rotate(2);
else var digging = this.dig();
}
else if (blue.indexOf(4) > -1){
if (this.direction != 3) this.rotate(3);
else var digging = this.dig();
}
else if (blue.indexOf(6) > -1 && this.direction != 0) this.rotate(0);
else if (blue.indexOf([0,2]) > -1){ //If no blue next to me but one in diagonal, move next
this.move(1);
this.storage['position'][1] = y+1; //Update position
}
else if (blue.indexOf([5,7]) > -1){
this.move(6);
this.storage['position'][1] = y-1;
}
else if (typeof this.storage['other_blue'] != "undefined"){ //Check if buddies said where they were, try to go near the closest one
var dmin = 99999;
var pos = []
(this.storage['other_blue'] || {}).forEach((item, idx) => {
var d = Math.sqrt(Math.pow(item['position'][0]-x,2) + Math.pow(item['position'][1]-y,2));
if (d < dmin){
dmin = d;
pos = item['position'];
}
});
if (pos[0]-x > 0){
this.move(4);
this.storage['position'][0] = x+1
}
else if (pos[0] < 0){
this.move(3);
this.storage['position'][0] = x-1
}
else if (pos[1] > 0){
this.move(1);
this.storage['position'][1] = y+1
}
else{
this.move(6);
this.storage['position'][1] = y-1
}
}
else var digging = this.dig();
if (typeof digging != "undefined"){ //Check out surroundings if dig() was played and update the map accordingly
var dx2 = [-2,-1,0,1,2,-2,-1,0,1,2,-2,-1,0,1,2,-2,-1,0,1,2,-2,-1,0,1,2];
var dy2 = [2,2,2,2,2,1,1,1,1,1,0,0,0,0,0,-1,-1,-1,-1,-1,-2,-2,-2,-2,-2];
(digging || []).forEach((item, idx) => {
//if (item && item.team == 'red' && typeof item.name == "undefined") this.storage['map'][x+dx2[idx]][y+dy2[idx]] = 'M';
if (item) this.storage['map'][x+dx2[idx]][y+dy2[idx]] = 'M'; //previously misread what dig() returned
});
}
resolve();
});
},
onmessage: function(data, fromTeam, fromBot) {
if (typeof data['position'] != "undefined" && fromTeam == 'blue') { //If position sent by a blue bot
if (typeof this.storage['other_blue'] == "undefined") this.storage['other_blue'] = [];
for (i in this.storage['other_blue']){
var found = false;
if ('name' in i){
if (i['name'] == fromBot){
i['position'] = data['position'];
found = true; //Update if position already known from previous ticks
}
}
}
if (!found) this.storage['other_blue'] += {'position':data['position'], 'name':fromBot}; //Add position if previously unknown
this.sendMessage(fromBot, undefined, "roger.");
}
},
onkill: function() {this.sendMessage(undefined, "blue", {"position": this.storage['position'], 'map': this.storage['map']});}
});
```
[Answer]
# Blue Fighter
```
createBot({
team: "blue",
name: "blue-fighter",
ontick: function(environment) {
return new Promise((resolve, reject)=>{
let map = environment.aroundMe;
let sides = [1, 4, 6, 3];
let facing = sides[this.direction];
let isTeam = (team,a) => a && a.team === team;
let isRed = (a)=>isTeam("red",a);
let isBlue = (a)=>isTeam("blue",a);
let randomSquare = ()=>Math.floor(Math.random()*8);
let redNum = map.filter(isRed).length;
let blueNum = map.filter(isBlue).length;
if(redNum > blueNum && redNum > 2){
this.bomb();
}else if(isRed(map[facing])){
this.kill();
}else if(sides.includes(map.findIndex(isRed))){
this.rotate(sides.indexOf(map.findIndex(isRed)));
}else if(Math.random() < 0.5 && this.landMines > 0){
this.landMine(randomSquare());
}else{
this.move(randomSquare());
}
resolve();
});
},
onmessage: function(data, from, fromBot) {},
onkill: function(){}
});
```
Blue fighter moves and landmines randomly and rotates toward red players. If the surrounding blocks have more red than blue, it bombs. If it is facing a red player, it kills it.
] |
[Question]
[
This is a `3x3` ASCII jigsaw puzzle:
```
_____ _____ _____
| _| |_ |
| (_ _ _) |
|_ _|_( )_|_ _|
| (_) |_ _| (_) |
| _ _) (_ _ |
|_( )_|_ _|_( )_|
| _| (_) |_ |
| (_ _) |
|_____|_____|_____|
```
This is also a `3x3` ASCII jigsaw puzzle:
```
_____ _____ _____
| |_ _| |
| _ _) (_ _ |
|_( )_|_ _|_( )_|
| _| (_) |_ |
| (_ _ _) |
|_ _|_( )_|_ _|
| (_) |_ _| (_) |
| _) (_ |
|_____|_____|_____|
```
Each line in a ASCII jigsaw puzzle (excluding the edge cases i.e. the pieces literally on the edges) consists of the following pattern:
```
_ _ _
_( )_ _ _ _( )_ _ _ _( )_
|_ _| (_) |_ _| (_) |_ _|
_) (_ _ _) (_ _ _) (_
|_ _|_( )_|_ _|_( )_|_ _| ...
(_) (_) (_)
```
Given 2 integers `H` and `W` where `H` is the height (vertical amount) and `W` is the width (horizontal amount) and `H` and `W` are `>1` output a possible `HxW` ASCII jigsaw puzzle.
# Examples
## Test Case 1
Input: `2, 4`
Output:
```
_____ _____ _____ _____
| |_ _| |_ |
| _ _) (_ _ _) |
|_( )_|_ _|_( )_|_ _|
| _| (_) |_ _| (_) |
| (_ _) (_ |
|_____|_____|_____|_____|
```
## Test Case 2
Input: `4, 4`
Output:
```
_____ _____ _____ _____
| |_ _| |_ |
| _ _) (_ _ _) |
|_( )_|_ _|_( )_|_ _|
| _| (_) |_ _| (_) |
| (_ _ _) (_ _ |
|_ _|_( )_|_ _|_( )_|
| (_) |_ _| (_) |_ |
| _ _) (_ _ _) |
|_( )_|_ _|_( )_|_ _|
| _| (_) |_ _| (_) |
| (_ _) (_ |
|_____|_____|_____|_____|
```
## Test Case 3
Input: `3, 5`
Output:
```
_____ _____ _____ _____ _____
| |_ _| |_ _| |
| _ _) (_ _ _) (_ _ |
|_( )_|_ _|_( )_|_ _|_( )_|
| _| (_) |_ _| (_) |_ |
| (_ _ _) (_ _ _) |
|_ _|_( )_|_ _|_( )_|_ _|
| (_) |_ _| (_) |_ _| (_) |
| _) (_ _) (_ |
|_____|_____|_____|_____|_____|
```
## Test Case 4
Input: `2, 2`
Output:
```
_____ _____
| _| |
| (_ _ |
|_ _|_( )_|
| (_) |_ |
| _) |
|_____|_____|
```
# Clarifications
* The height and width for each puzzle piece should not be scaled up or down.
* With `H` and `W` being greater than one, the smallest dimensions possible are `2x2` (see IO 4).
* You can have a full program or a function.
* The input will be 2 lines with `H` on the 1st and `W` on the 2nd if you're using a function you can have them in the parameters.
* Output to stdout (or something similar).
* This is code-golf so shortest answer in bytes wins.
[Answer]
# JavaScript (ES6) 272 ~~277 271~~
*Edit* bug fix
*Edit 2* saved 6 bytes thx @L.Serné
*Edit 3* bug fix again
```
(w,h,z=(s,q=3,i=h)=>'| '.slice(0,q)+s.repeat(w).substr(i%2*6+q,w*6-q-~-q)+` |
`.slice(~q))=>eval("t=z(' _____',0,0)+z('|_ _| ',2,--h)+z(b=' _) (_ _ ')+z(c='|_ _|_( )_',0);for(a='|_ _| (_) ';--h;)t+=z(a,2)+z(b)+z(c,0)")+z(a,2)+z(' _) (_ ')+z('|_____',1)
```
*Less golfed*
```
(w,h,
z=(s,q=3,i=h)=>'| '.slice(0,q)+s.repeat(w).substr(i%2*6+q,w*6-q-~-q)+' |\n'.slice(~q),
a='|_ _| (_) ',
b=' _) (_ _ ',
c='|_ _|_( )_',
t=z(' _____',0,0)+z('|_ _| ',2,--h)+z(b)+z(c,0)
)=>{
for(;--h;)
t+=z(a,2)+z(b)+z(c,0);
return t+z(a,2)+z(' _) (_ ')+z('|_____',1)
}
```
**Test**
```
F=
(w,h,z=(s,q=3,i=h)=>'| '.slice(0,q)+s.repeat(w).substr(i%2*6+q,w*6-q-~-q)+` |
`.slice(~q))=>eval("t=z(' _____',0,0)+z('|_ _| ',2,--h)+z(b=' _) (_ _ ')+z(c='|_ _|_( )_',0);for(a='|_ _| (_) ';--h;)t+=z(a,2)+z(b)+z(c,0)")+z(a,2)+z(' _) (_ ')+z('|_____',1)
function update() {
var w=+W.value,h=+H.value
O.textContent=F(w,h)
}
update()
```
```
W<input id=W value=2 oninput='update()' type=number min=2>
H<input id=H value=2 oninput='update()' type=number min=2>
<pre id=O></pre>
```
[Answer]
# Python, 513 bytes
```
def r(m,n):
r=3*m
c=6*n
l=3-(n%2)*3
z=[1,2,3,4,5,0]
p=zip
return"\n".join("".join(" |_()"[[[((j%6,i%3)in[(1,0),(5,0)])*2or((j%6,i%3)in[(0,1),(0,0)])or((j%4,i%6)in[(1,1),(1,2),(3,4),(3,5)])*2or((i%6,j%12)in p(z,[10,2,10,4,8,4]))*4or((i%6,j%12)in p(z,[8,4,8,2,10,2]))*3,1,0][j in[0,c]or((j,i%6)in p([1,1,2,2],[1,2]*2)+p([c-1,c-1,c-2,c-2],[1+l,2+l]*2)or(i,j%12)in[(1,8),(1,9),(1,10),(2,8),(2,9),(2,10),(r-1,9)]or(i,j%12)==(r-1,3+6*(m%2)))*2],2*(j%6>0)or i>0][i in[0,r]]]for j in range(c+1))for i in range(r+1))
```
Perhaps more of an exercise in obfuscation than in golfing, this one works by deciding what character each `(x,y)` coordinate goes to rather than building up each pattern by string. Ungolfed it looks like
```
char_codes = " |_()"
def base(row, col):
if col % 6 in [5] and row % 3 in [0, 2]:
return 1
if col % 6 in [0, 4] and row % 3 in [2]:
return 2
return 0
def underscores(row, col):
if col % 4 in [0] and row % 6 in [0, 1] or col % 4 in [2] and row % 6 in [3, 4]:
return 2
return 0
def parentheses(row, col):
if (row % 6, col % 12) in [(0, 9), (1, 1), (2, 9), (3, 3), (4, 7), (5, 3)]:
return 4
if (row % 6, col % 12) in [(0, 7), (1, 3), (2, 7), (3, 1), (4, 9), (5, 1)]:
return 3
return 0
def value(row, col):
return base(row, col) + underscores(row, col) + parentheses(row, col)
def new_value(last_row, last_col, row, column):
if row in [0, last_row]:
return 2*(column % 6 > 0) or row>0
if column in [0, last_col]:
return 1
if column in [1,2] and row % 6 in [1, 2]:
return 0
if column in [last_col - 1, last_col - 2] and row % 6 in [[4,5],[1,2]][last_col%12>0]:
return 0
if row in [1, 2] and column % 12 in [8,9,10]:
return 0
if row == last_row - 1 and column % 12 == 9:
return 0
return value(row - 1, column - 1)
def puzzle(rows, cols):
last_row = rows * 3
last_col = cols * 6
return "\n".join("".join(new_value(last_row, last_col, row, col) for col in range(last_col + 1)) for row in range(last_row + 1))
```
The patterns themselves look like
we can see this as a lookup table from integers with columns taken mod 6 and
rows mod 3
```
012345
0 |
1
2_ _|
0123
0_
1_
2
3 _
4 _
5
0123456789AB
0 ( )
1 ) (
2 ( )
3 ( )
4 ) (
5 ( )
```
This strategy of combining different patterns has not really worked out for me here because expressing them is quite cumbersome (though I think I could have golfed more) and because the edge cases take up so many characters to fix. I'm putting this up regardless because it took me a minute and it might be of interest.
[Answer]
# Mathematica, 384 bytes
```
(m=#~Mod~2&;a=#~Array~Y&;s=(h=" _ ")[o="|_( )_",z="|_ _",w=" _) (_",z,p="| (_) "];l="| _ "[o,"| _",u="| (_",z,p];r=h[o,q="|_ ",t=" _) ",z,p];{X,Y}=#;a[" _____"&]<>" \n"<>Join[{a[If[#<Y,z,q]["| "][[m@#]]&]},Table[Which[y<2,l,y<Y,s,0<1,r][[Mod[x+3y,6]]],{x,3,3X-1},{y,1,Y}],{a[If[#<2,"| "[u]," "[If[#<Y,w,t]]][[m[X+#]]]&],a["|_____"&]}]~Riffle~"|\n"<>"|")&
```
Unnamed function taking an ordered pair of integers as its argument, and returning a string containing appropriate newlines. With spaces and newlines added:
```
(m = Mod[#1, 2] &; a = Array[#1, Y] &;
s = (h = " _ ")[o = "|_( )_", z = "|_ _", w = " _) (_", z, p = "| (_) "];
l = "| _ "[o, "| _", u = "| (_", z, p];
r = h[o, q = "|_ ", t = " _) ", z, p];
{X, Y} = #1;
a[" _____" &] <> " \n" <>
Riffle[
Join[
{a[If[#1 < Y, z, q]["| "][[m[#1]]] &]},
Table[
Which[y < 2, l, y < Y, s, 0 < 1, r][[Mod[x + 3 y, 6]]],
{x, 3, 3 X - 1}, {y, 1, Y}
],
{a[If[#1 < 2, "| "[u], " "[If[#1 < Y, w, t]]][[m[X + #1]]] &],
a["|_____" &]}
], "|\n"
] <> "|") &
```
[Answer]
## Batch, ~~562~~ 528 bytes
```
@echo off
set t=! !
set w=%2
set a= _) (_!_ _! (_) ! _ !_( )_!_ _ _) (_
call:d "! !_ _" 2 " _____ _____" 4
for /l %%j in (2,1,%1)do call:t
call:d "!_____!_____" 1 "%a:~18,6%%a:~-6%" 3
exit/b
:t
set a=%a:~24%%a:~0,24%
call:d "%a:~6,6%%a:~30,6%" 1 "%a:~0,6%%a:~24,6%" 3
call:c "%a:~12,6%%a:~36,6%" 2
exit/b
:d
call:c %3 %4
:c
set s=
for /l %%i in (%w%,-2,1)do call set s=%~1%%s%%&if %%i==1 call set s=%%s:~6%%
if %2 lss 4 set s=%s%!&call set s=%%t:~0,%2%%%%s:~%2,-%2%%%%t:~-%2%%
echo %s:!=^|%
```
Proved resistant to golfing, as the repetition tended to cost too many bytes to eliminate, for example, I manually pass in the line number mod 3 because it's too expensive to compute. Edit: Furthermore, I had inadvertently golfed extra `|`s every third line, which is incorrect. Fixing this actually saved me 2 bytes (4 bytes on my original version). Explanation: `a` contains various bits of jigsaw. The `:t` function swaps them over each set of three rows, then extracts the required substrings which the `:c` function then repeats in pairs, but deleting the first column if `w` is odd. The left and right edge cases are then handled before the row is output. ~~The other edge case is the very first row in which the `!`s are changed to spaces instead of `|`s (the code avoids `|`s because they are tricky to handle in Batch).~~
[Answer]
# Befunge, ~~263~~ 243 bytes
```
|_ _| (_)
_) (_ _
|_ _|_( )_
|
|
|_____
_____
>&:08p3*28p&:18p6*38pv
@#!`g82:,_v0+55+1p84:<_
\g82+g84<| `g83:+1,g\%*6-g852+*6/3+2g84\++%3+2\!:g84*4p85:!!+*`0%6\!*`
6/08g+2%^>>::::48g3/2%2*`\48g3/18g+2%!2*+38g\`*!48g3%0`*\::6/2%!48g\`\
```
[Try it online!](http://befunge.tryitonline.net/#code=fF8gICBffCAoXykKIF8pIChfICAgXwp8XyAgIF98XyggKV8KCnwKfAp8X19fX18KIF9fX19fCj4mOjA4cDMqMjhwJjoxOHA2KjM4cHYKQCMhYGc4MjosX3YwKzU1KzFwODQ6PF8KXGc4MitnODQ8fCBgZzgzOisxLGdcJSo2LWc4NTIrKjYvMysyZzg0XCsrJTMrMlwhOmc4NCo0cDg1OiEhKypgMCU2XCEqYAo2LzA4ZysyJV4+Pjo6Ojo0OGczLzIlMipgXDQ4ZzMvMThnKzIlITIqKzM4Z1xgKiE0OGczJTBgKlw6OjYvMiUhNDhnXGBc&input=MyA1)
The way this works is by iterating over the x,y coordinates of the area we want to output, and mapping those *x*,*y* values to *u*,*v* coordinates in the puzzle pattern (stored on the first three lines of the playfield). This mapping is achieved with the following basic formulae:
```
u = (x+(y+2)/3*6) % 12
v = (y+2)%3 + (y==0)
```
The *u* coordinate repeats every 12 columns, but also needs to be offset by 6 every 3 rows. The *v* coordinate repeats every 3 rows, but we add `y==0` to the value so the very first row can be rendered as a special case. However, to handle the edges, we need to introduce an additional boolean value, *e*, which is true for various edge locations, and which adjusts the formulae as follows:
```
u = (x+(y+2)/3*6) % (e?6:12)
v = (y+2)%3 + (y==0) + e*4
```
Thus if we're on an edge, we add 4 to the *v* coordinate so as to use the simpler edge pattern on lines 5 to 7. And we also now need to mod the *u* coordinate by 6 rather than 12, since this edge pattern repeats every 6 columns.
As for the *e* value itself, that requires a fairly complex formula, since the edge locations encompass a somewhat irregular area of the puzzle border.
```
elr = (x <= 2*y/3%2 or x >= w-2*!(y/3+cols)%2) and (y%3 > 0)
etb = (y <= !(x/6%2) or y >= h-(x/6+rows)%2) and (x%6 > 0)
e = elr or etb
```
Without going into too much detail, the basic breakdown is that *elr* matches the edge locations along the left and right borders, while *etb* matches locations along the top and bottom borders.
[Answer]
## JavaScript (ES6), 285 bytes
```
f=
(h,w,a=` _) (_|_ _| (_) _ |_( )_|_ _ | |_____`.match(/.{6}/g),g=(l,r,j)=>a[7].slice(0,j)+(a[l]+a[r]).repeat(w).slice(j,w*6+1-j)+` |`.slice(-j))=>[` _____`.repeat(w),g(1,7,2),...[...Array(--h*3)].map((_,i)=>g(i%6,(i+3)%6,"312"[i%3])),g(h=h%2*6,6-h,3),g(8,8,1)].join`
`
```
```
<div oninput=o.textContent=+h.value&&+w.value?f(h.value,w.value):''><input id=h type=number min=1><input id=w type=number min=1><pre id=o>
```
This is a port of my Batch answer, just to see whether it competes with @edc65's answer. The annoyingly long string contains jigsaw pieces. The first six pieces represent two rows of one column of the interior of the jigsaw. The seventh piece is used for the penultimate line of the jigsaw, in place of the fourth piece. The eighth piece is used on the second line of the jigsaw, in place of the fifth piece, and also does double duty as the left edge of the jigsaw. The ninth piece is the last line of the jigsaw.
] |
[Question]
[
It is a dry summer in the prairie. The four farmers in the area realize that they can corner the market on corn by burning their neighbors crops. But they need a strategy for doing so; that is where you come in.
Your task is to write a bot to tell the farmers what to burn. The goal is to finish the game with the largest area of unburnt land. The playing field is a 32x32 grid. Each cell may be one of the following:
`. - Ground`
`@ - A bot`
`# - Ash`
`W - Wet ground`
`1,2,3,4,5, or 6 - Fire`
Fire grows in intensity by 1 each turn. Once it is 3 or higher, it will set cells next to it (horizontally or vertically) on fire. After fire hits 6, it turns into ash.
On each turn, bots receive as STDIN the following: bot starting x, bot starting y, bot current x position, bot current y position, and the board, separated by newlines. An example:
```
8
22
6
24
................................
................................
................................
.....................1..........
....................1#1.........
...................1#363........
....................16@1........
.....................31.........
................................
.........1.1....................
........15#62...................
........15@2....................
.........32.....................
................................
................................
................................
................................
................................
................................
................................
................................
................................
....4.1.........................
.....1#3........................
.....@3.........................
.....W..........................
................................
................................
................................
................................
................................
................................
```
(in this instance you are the bot in the bottom left).
You must output three characters, with an optional newline, representing the following:
Move - one of `L, R, U, D, or S (stay)`
Action - one of `B (burn), P (pour water) or X (do nothing)`
Direction - one of `L, R, U, D or S` - controls which cell you perform the action on
Fire does not affect bots.
Turn order is as follows: All bots move; all bots perform actions; then environmental rules happen.
If you pour water on the ground, it will be wet (`W`) for one turn. Fire will not spread to wet ground. If you pour water on wet ground, it will continue to be wet. If you pour water on fire, it turns back to regular ground. You cannot do anything to ash.
Rounds are run with 4 bots at a time. The round ends after 50 turns, or when one bot runs out of unburnt ground, whichever comes first. Your score is calculated as the number of ground or wet ground cells in the 9x9 square centered on where your bot started.
Here is an example bot; it picks all three letters randomly and generally ends up burning down its own fields.
RandomBurner:
```
#!/usr/bin/env python
import random
print random.choice('LRUDS')+random.choice('BPX')+random.choice('LRUDS')
```
Rules:
* No filesystem access outside of your own folder.
* You may write to files if you need to store persistent data between turns, but only up to a maximum of 1kb per bot
* You may not overwrite anybody else's bot
* If you output an invalid move, your bot will sit still. If you output an invalid action, your bot will do nothing.
* Please stick to common languages that can be run on a OSX or Linux box.
Controller code can be found [here.](http://pastebin.com/B353rcEb)
## Initial results:
```
Average of 15 rounds:
---------------------
81 Farmer
56 CautiousBot
42 GetOff
41 Visigoth
40 DontBurnMeBro
37 FireFighter
35 Pyro
11 Protector
```
**Update**: Added Farmer, CautiousBot, GetOff, FireFighter, and Pyro.
[Answer]
# Visigoth
Visigoth tries to burn its enemies to the ground. It hopes to do this before anyone else gets to its land.
Run: `python visigoth.py`
```
#!/usr/bin/python
''' Charge the enemy and burn them to the ground. '''
import sys
data = sys.stdin.readlines()
startx, starty, x, y = [int(i) for i in data[0:4]]
field = [list(i) for i in data[4:]]
otherbots = []
for i in range(32):
for j in range(32):
if field[i][j]=='@': #bot
if i!=y and j!=x:
otherbots.append([j,i])
min_bot = otherbots[0]
for bot in otherbots:
if abs(bot[0]-x)+abs(bot[1]-y) < abs(min_bot[0]-x)+abs(min_bot[1]-y):
min_bot = bot
dx = min_bot[0]-x
dy = min_bot[1]-y
if abs(dy)>abs(dx):
if dy>0:
move = 'U'
else:
move = 'D'
else:
if dx>0:
move = 'R'
elif dx<0:
move = 'L'
else:
move = 'S'
if max(abs(x-startx), abs(y-starty))>4:
if 0<x<31 and 0<y<31:
dirs = {'U':(-1,0), 'D':(1,0), 'L':(0,-1), 'R':(0,1)}
for i in dirs:
if field[dirs[i][0]][dirs[i][1]] in ('.', 'W'):
action = 'B'+i
break
else:
# No free land nearby, go out in a blaze of glory
action = 'BS'
else:
action = 'BS'
else:
# Don't set own field on fire
action = 'XS'
print move+action
```
This is my first entry, constructive criticism is appreciated!
[Answer]
# Java, Protector
Attempts to surround his field with a fence of ash.
**Edit:** Improved logic a bit. Probably won't make a difference.
```
import java.awt.Point;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;
/**
* Created 10/6/15
*
* @author TheNumberOne
*/
public class Protecter {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Point start = new Point(in.nextInt(), in.nextInt());
Point current = new Point(in.nextInt(), in.nextInt());
in.nextLine();
String output = "";
char[][] board = new char[32][];
for (int i = 0; i < 32; i++){
board[i] = in.nextLine().toCharArray();
}
List<Point> danger = new ArrayList<>();
List<Point> close = new ArrayList<>();
List<Point> closeDanger = new ArrayList<>();
List<Point> fence = new ArrayList<>();
for (int i = 0; i < 32; i++){
for (int j = 0; j < 32; j++){
Point p = new Point(i, j);
char c = board[j][i];
if (Math.abs(p.x - start.x) < 10 && Math.abs(p.y - start.y) < 10){
if ((c + "").matches("\\d")){
danger.add(p);
}
}
if (distance(current, p) == 1){
close.add(p);
}
if ((Math.abs(p.x - start.x) == 10 || Math.abs(p.y - start.y) == 10) && !(c + "").matches("#|\\d|@")){
fence.add(p);
}
}
}
closeDanger = new ArrayList<>(danger);
closeDanger.retainAll(close);
danger.sort(Comparator.comparingInt(a -> distance(current, a) / (board[a.y][a.x] - '0')));
if (danger.size() > 0){
output += moveTo(current, danger.get(0));
} else {
fence.sort(Comparator.comparingInt(a -> distance(current, a)));
if (fence.size() == 0){
output += "S";
} else {
output += moveTo(current, fence.get(0));
}
}
closeDanger.sort(Comparator.comparingInt(a -> board[a.y][a.x] - '0'));
if (closeDanger.size() > 0){
output += "P";
output += moveTo(current, closeDanger.get(0));
} else {
if (danger.size() == 0) {
List<Point> closeFence = new ArrayList<>(fence);
closeFence.retainAll(close);
if (closeFence.size() > 0) {
output += "B";
output += moveTo(current, closeFence.get(0));
} else {
if (!fence.contains(current)){
output += "PS";
} else {
output += "BS";
}
}
} else {
if (!fence.contains(current)){
output += "PS";
} else {
output += "BS";
}
}
}
System.out.println(output);
}
private static String moveTo(Point from, Point to) {
if (from.x > to.x){
return "L";
}
if (from.x < to.x){
return "R";
}
if (from.y > to.y){
return "U";
}
if (from.y < to.y){
return "D";
}
return "S";
}
private static int distance(Point p1, Point p2){
return Math.abs(p1.x - p2.x) + Math.abs(p2.y - p1.y);
}
}
```
Place in a file named `Protector.java`.
Compile with: `javac Protector.java`
Run with: `java Protector`
[Answer]
## GetOff, Python
GetOff just wants to keep his land for himself, and he's not afraid to chase those damn bots all over his land, squirting them with his water gun until they leave. While its property is not being violated, it makes tries its best to make sure his land doesn't get burned.
```
#!/usr/bin/env python
import sys
fire = ['1','2','3','4','5','6']
move = ''
ad = ''
data = sys.stdin.readlines()
startx, starty, x, y = [int(i) for i in data[0:4]]
board = [list(i) for i in data[4:]]
top = starty-4
bottom = starty+5
right = startx+5
left = startx-4
bots = []
for i in range(32):
for j in range(32):
if board[i][j]=='@':
if i != y and j != x:
bots.append([j,i])
fires = []
for i in range(32):
for j in range(32):
if board[i][j] in fire: #fire
fires.append([j,i])
for bot in bots:
if left < bot[0] < right and top < bot[1] < bottom: # if there's a bot in the field
if bot[0] > x:
move = 'R'
elif bot[0] < x:
move = 'L'
elif bot[1] > y:
move = 'D'
elif bot[1] < y:
move = 'U'
else:
move = 'S'
else:
nearest_fire = []
for f in fires:
if left < f[0] < right and top < f[1] < bottom:
if nearest_fire == []:
nearest_fire = f
elif (f[0]-x)+(f[1]-y) < (nearest_fire[0]-x)+(nearest_fire[1]-y):
nearest_fire = f
if nearest_fire == []:
move = 'S'
else:
if nearest_fire[0] > x:
move = 'R'
elif nearest_fire[0] < x:
move = 'L'
elif nearest_fire[1] > y:
move = 'D'
elif nearest_fire[1] < y:
move = 'U'
else:
move = 'S'
if board[x-1][y] in fire: # position immediately to the left
ad = 'L'
elif board[x+1][y] in fire: # position immediately to the right
ad = 'R'
elif board[x][y-1] in fire: # position immediately up
ad = 'U'
elif board[x][y+1] in fire: # position immediately down
ad = 'D'
else:
ad = 'S'
print(move+'P'+ad)
```
[Answer]
# Farmer, Java
The farmer only cares about his crops. He constantly watches his field for possible fires or invaders.
```
import java.awt.Point;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;
public class Farmer {
public static void main(String[] args) {
//row == y
//col == x
Scanner in = new Scanner(System.in);
Point start = new Point(in.nextInt(), in.nextInt());
Point current = new Point(in.nextInt(), in.nextInt());
in.nextLine();
char[][] board = new char[32][];
for (int row = 0; row < 32; row++){
board[row] = in.nextLine().toCharArray();
}
final List<Point> firesInField = new ArrayList<>();
final List<Point> enemiesInField = new ArrayList<>();
for (int row = 0; row < 32; row++) {
for (int col = 0; col < 32; col++) {
Point p = new Point(col, row);
if (!isInField(start, p))
continue;
char c = board[row][col];
if (isFire(c)) {
firesInField.add(p);
} else if (c == '@' && col != current.x && row != current.y) {
enemiesInField.add(p);
}
}
}
List<Point> destinations = firesInField.size() > 0 ? firesInField : enemiesInField;
if (destinations.size() > 0) {
//take short paths to eliminate more fires
destinations.sort(Comparator
.comparingInt((Point p) -> distance(p, current))
.thenComparingInt(p -> -1 * (board[p.y][p.x] - '0')));
Point dest = destinations.get(0);
print(moveTo(current, dest), "P", moveTo(current, dest));
}
//TODO start fires if an enemy has more intact ground
//walk back to center
print(moveTo(current, start), "P", moveTo(current, start));
}
private static void print(String move, String action, String actionMove) {
System.out.println(move + action + actionMove);
System.exit(0);
}
private static boolean isInField(Point centerOfField, Point toTest) {
//add one extra, to prevent fires that are very near
return distance(centerOfField, toTest) <= 10 && Math.abs(centerOfField.x - toTest.x) <= 5 && Math.abs(centerOfField.y - toTest.y) <= 5;
}
private static boolean isFire(char c) {
return c == '1' || c == '2' || c == '3' || c == '4' || c == '5' || c == '6';
}
private static String moveTo(Point from, Point to) {
if (from.x > to.x){
from.x--;
return "L";
}
if (from.x < to.x){
from.x++;
return "R";
}
if (from.y > to.y){
from.y--;
return "U";
}
if (from.y < to.y){
from.y++;
return "D";
}
return "S";
}
private static int distance(Point p1, Point p2){
return Math.abs(p1.x - p2.x) + Math.abs(p2.y - p1.y);
}
}
```
[Answer]
# Pyro, python
Pyro likes fire. Pyro loves fire. Pyro lives in fire. I'm thinking "Pyro from TF2". Pyro likes to burn things. He won't burn his own territory, but he will try to get out of it, using a simple "pathfinding" algorithm.
```
import sys
import random
inpu = sys.stdin.readlines()
ox,oy,x,y = [int(i) for i in inpu[0:4]]
board = [list(i) for i in inpu[4:]]
adjacentcells = [[[board[y+b][x+c],b,c] for b in range(-1,2)] for c in range(-1,2)]
action = ""
infield=max(abs(ox-x),abs(oy-y))<=9
# let's find out what Pyro will do!
if not infield: # Pyro won't burn what's in his field.
for row in adjacentcells:
for entry in row:
cell,a,b=entry
if(a!=b): # Can't act on these cells.
if cell==".": # burn it!!!!!!
action = "B"
if(a==0):
direction = {-1:"L",1:"R"}[b]
else:
direction = {-1:"D",1:"U"}[a]
if action: break;
if action: break;
# Pyro doesn't care where he goes, so long as
# Pyro's not in the field of Pyro.
move = random.choice("LRUDS")
else: # Thought Pyro hates water, Pyro must protect SOMETHING.
action = "P"
direction = "S"
# get the direction towards the center
# Pyro will move away from ox and oy to
# towards the center, if in the field.
# Pyro will do this by first going right/left,
# then going up/down. (This behaviour is
# removed when he leaves his field.)
cx = cy = 16
while max(abs(cx-x),abs(cy-y))<=9:
cx = random.randint(0,31)
cy = random.randint(0,31)
if(cx-x>0): #is to the left of the center
move = "R"
elif(cx-x<0): #is to the right of the cenetr
move = "L"
elif(cy-y>0): # is above center
move = "D"
elif(cy-y<0): # is below center
move = "U"
else: # is at center (something went wrong!)
move = "S"
action = "B"
if not move:
move = "S"
if not action:
action = "B"
if not direction:
direction = "S"
print(move+action+direction)
""" Here, have a face!
MMMMMMMMMMMMMMMMMMMMMMMdyo/:-.````.:+sdMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMNs/....----...``````.omMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMh/``..-://+//:-..````````/mMMMMMMMMMMM
MMMMMMMMMMMMMMMm:````..-:////:--..``````````sMMMMMMMMMM
MMMMMMMMMMMMMMs```````....--....`````````````/NMMMMMMMM
MMMMMMMMMMMMM/````````````````````````````````:NMMMMMMM
MMMMMMMMMMMM/```......``````````````````.......+mMMMMMM
MMMMMMMMMMMo.:::::::::::-````````````.-:::::::::/+yNMMM
MMMMMMMMMNs:-..-------::::.`````````://:-------..-:/hMM
MMMMMMMMm+:..---:::::---:::.```````::::---:::::--.`-/sM
MMMMMMMN+:`.---:::/:/:---:::``````.:::.--:::/:/:--.`:/h
MMMMMMMh:-`---://o+///:---::.`````-::---://oo///:--..:+
MMMMMMMs:..--:/+/sss+//:-.::.`````-::.-://+osyo//:-.-::
MMMMMMMs:----///+sosso/:--::``````.::.-://+oosso+:-.::/
MMMMMMMd:::-:/++/osyso+/--::```````::-://+/osyso+/--::s
MMMMMMMMs:/::::+ooos+o+/:::.```````.::::/+ooos/o+/:/:+N
MMMMMMMMMs://:+osooo+o+/::.``.....``.:/:/osoos+o+//:+mM
MMMMMMMMMM--:/++ysyoo+/:-...........`.-:/+ssso++/:-yNMM
MMMMMMMMMMs``.-:://::-..`.....---....``..--::::-.`.MMMM
MNNMddhyys+-.```````````...--:::::-...````````````+MMMM
////.-:///:-..``````````.:///++o/o+/:/.```````````yMMMM
---.`.-:::--..`````````..+//+ooo+++///.```````````mMMMM
/.--``..--...``````````..--:/+oo+/:--..``````````.MMMMM
s --.```...````````````...--/+++++/-...````````.`/MMMMM
d .--```````````````````...-::::::-...````````.-/+MMMMM
M.`--` ````````````````....------....````````.-/.dMMMM
M+ .-. `````````````````.:::::::::::.`````````.-sMMMMM
Mm``--` ``````````````-://///////////:-````````/MMMMMM
MM: --. ````````````.://::--......-::///-``````yMMMMMM
MMd`.-. ``````````.:/::-..-:::::::.``-::::.````NMMMMMM
MMM+.--` `````````:::-.-::-.......-::-`--::```+MMMMMMM
MMMN---` ````````.--..:-.```````````..-`.--.``dMMMMMMM
MMMMd--.` `````..`.-.`-````````````````.-`...`/MMMMMMMM
MMMMMNh+ss/oydNMd``.`.`````````````````````.`.NMMMMMMMM
MMMMMMMMMMMMMMMMMd.``.```````````````````````dMMMMMMMMM
MMMMMMMMMMMMMMMMMMm:```````````````````````-dMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMy.```````````````````.oNMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMNs-```````````````:sNMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMMMmy+:-.````.:+ymMMMMMMMMMMMMMMMM
"""
```
[Answer]
# DontBurnMeBro
Another Python entry. Guaranteed not to be the first to die (I think).
```
#!/usr/bin/python
print "SPS"
```
[Answer]
# FireFighter, Java
Fights *all* fires.
```
import java.awt.Point;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;
/**
* Created 10/7/15
*
* @author TheNumberOne
*/
public class FireFighter {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Point start = new Point(in.nextInt(), in.nextInt());
Point current = new Point(in.nextInt(), in.nextInt());
in.nextLine();
String output = "";
char[][] board = new char[32][];
for (int i = 0; i < 32; i++) {
board[i] = in.nextLine().toCharArray();
}
List<Point> danger = new ArrayList<>();
List<Point> close = new ArrayList<>();
List<Point> closeDanger;
for (int i = 0; i < 32; i++){
for (int j = 0; j < 32; j++){
Point p = new Point(i, j);
char c = board[j][i];
if ((c + "").matches("\\d")){
danger.add(p);
}
if (distance(current, p) == 1){
close.add(p);
}
}
}
closeDanger = new ArrayList<>(danger);
closeDanger.retainAll(close);
Comparator<Point> comparator = Comparator.comparingInt((Point a) -> board[a.y][a.x]).reversed();
danger.sort(comparator);
danger.sort(Comparator.comparingInt(a -> distance(start, a)));
if (danger.size() > 0){
output += moveTo(current, danger.get(0));
} else {
output += moveTo(current, start);
}
closeDanger.sort(comparator);
if (closeDanger.size() > 0){
output += "P" + moveTo(current, closeDanger.get(0));
} else {
output += "PS";
}
System.out.println(output);
}
private static String moveTo(Point from, Point to) {
if (from.x > to.x){
return "L";
}
if (from.x < to.x){
return "R";
}
if (from.y > to.y){
return "U";
}
if (from.y < to.y){
return "D";
}
return "S";
}
private static int distance(Point p1, Point p2){
return Math.abs(p1.x - p2.x) + Math.abs(p2.y - p1.y);
}
}
```
[Answer]
# Keeper, Python 2
```
import sys
Out = ["S", "P", "S"]
StX = int(sys.stdin.readline()) - 1
StY = int(sys.stdin.readline()) - 1
NowX = int(sys.stdin.readline()) - 1
NowY = int(sys.stdin.readline()) - 1
Map = []
for i in range(32):
Map.append(sys.stdin.readline())
Pos = [NowX, NowY]
Area = [[StX, StY]]
for x in range(StX-4, StX+4):
for y in range(StY-4, StY+4):
Area.append([x, y])
Fires = []
for y in range(32):
for x in range(32):
if Map[y][x] in "123456":
Fires.append([x, y])
Danger = []
for Tile in Area:
if Map[Tile[1]][Tile[0]] in "123456":
Danger.append(Tile)
Distance = {}
i = -1
for Fire in Danger:
i += 1
Distance[(Pos[0] - Fire[0], Pos[1] - Fire[1])] = i
i = min(Distance)
Closest = Danger[Distance[i]]
if Closest[0] > Pos[0]:
Out[0] = Out[2] = "R"
Pos[0] += 1
if Closest[0] < Pos[0]:
Out[0] = Out[2] = "L"
Pos[0] -= 1
if Closest[0] == Pos[0]:
if Closest[1] > Pos[1]:
Out[0] = Out[2] = "D"
Pos[1] += 1
if Closest[1] < Pos[1]:
Out[0] = Out[2] = "U"
Pos[1] -= 1
if Closest[0] + 1 == Pos[0] and Closest[1] == Pos[1]:
Out[2] = "L"
if Closest[0] - 1 == Pos[0] and Closest[1] == Pos[1]:
Out[2] = "R"
if Closest[1] + 1 == Pos[1] and Closest[0] == Pos[0]:
Out[2] = "U"
if Closest[1] - 1 == Pos[1] and Closest[0] == Pos[0]:
Out[2] = "D"
if Closest[0] == Pos[0] and Closest[1] == Pos[1]:
Out[2] = "S"
print "".join(Out)
```
Could be simplified, but I'm tired.
The Keeper tries to keep its field from harm. If a fire appears, it hurries over to it and puts it out as fast as it can.
I may add accommodation for incoming fires as well.
[Answer]
# CautiousBot, Node.js (ES5)
This bot goes out and tries to set fire to other bots' land. It even sits on top of the fire for 3 ticks to hide it! However, one can never be too cautious, so it always makes sure it is close enough to put out any fires on its own land.
Notes:
* Uses a state file called `state.json` stored in its working directory, used to store information about other bots' initial positions and to determine how long to hide a started fire. *This must be deleted once the round is over (eg, when some bot has won).* Otherwise the bot will be confused on the next round. (Let me know if this breaks rules.)
* Requires the `split` module.
```
#!/usr/bin/env node
// imports
var fs = require("fs");
var splitmod = require("split");
// variables
var startX, startY, currentX, currentY, board = [], state = {};
var DEBUG = false;
// utility functions
function debug(){
if(DEBUG) console.log.apply(console, arguments);
}
// calculates manhattan distance which is also the number of turns it will take to get somewhere
function manhattan(x1, y1, x2, y2){
return Math.abs(x2 - x1) + Math.abs(y2 - y1);
}
// calculates chebyshev distance (mostly used for determining if a bot is within someone's plot)
function chebyshev(x1, y1, x2, y2){
return Math.max(Math.abs(x2 - x1), Math.abs(y2 - y1));
}
// gets the board character at x, y
function get(x, y){
return board[y][x];
}
function readState(){
try {
state = JSON.parse(fs.readFileSync('state.json').toString());
debug("Opened state file");
} catch(e){
// it must be the first turn
createState();
}
}
function writeState(){
fs.writeFileSync('state.json', JSON.stringify(state));
debug("Wrote state file");
}
// finds out where all the other bots are
function getBotPositions(){
var positions = [];
for(var x = 0; x < 32; x++){
for(var y = 0; y < 32; y++){
if(get(x, y) == '@' && x != currentX && y != currentY){
positions.push({x: x, y: y});
}
}
}
return positions;
}
function createState(){
debug("Creating state");
// take a loot at where other bots are to record their land locations
var botLands = getBotPositions();
state['botLands'] = botLands;
state['turn'] = 0; // which turn is it?
state['lastFireTurn'] = -999; // which turn was the last one where this bot set a fire?
}
// finds whether a plot of land (defined by its center) has fire on it
function isLandBurning(x, y){
for(var dx = -4; dx < 5; dx++){
for(var dy = -4; dy < 5; dy++){
if(get(x + dx, y + dy).match(/[1-6]/) != null) return true;
}
}
return false;
}
// finds the fire with the highest number (and therefore the one to put out first)
function findFire(x, y){
var highestNum = 0;
var fire = {x: x, y: y};
for(var dx = -4; dx < 5; dx++){
for(var dy = -4; dy < 5; dy++){
if(get(x + dx, y + dy).match(/[1-6]/) != null){
var num = parseInt(get(x + dx, y + dy));
if(num > highestNum){
highestNum = num;
fire = {x: x + dx, y: y + dy};
}
}
}
}
return fire;
}
// figures out where to go to get somewhere
function getDirection(x1, y1, x2, y2){
var direction = 'S';
var cycx = Math.abs(y2 - y1) / Math.abs(x2 - x1);
if(cycx < 1){
if(x2 > x1) direction = 'R';
if(x2 < x1) direction = 'L';
} else {
if(y2 > y1) direction = 'D';
if(y2 < y1) direction = 'U';
}
debug("Getting direction", x1, y1, x2, y2, "result", direction);
return direction;
}
// read input
var dataCycle = 0;
process.stdin.pipe(splitmod()).on('data', function(line){
switch(dataCycle){
case 0:
startX = parseInt(line);
break;
case 1:
startY = parseInt(line);
break;
case 2:
currentX = parseInt(line);
break;
case 3:
currentY = parseInt(line);
break;
default:
board.push(line);
}
dataCycle++;
}).on('end', function(){
// main bot code
readState();
state['turn']++;
debug("It is turn", state['turn']);
// get bot positions
var botPositions = getBotPositions();
var action = {type:'X', direction:'S'};
var move = 'S';
var isMyLandBurning = isLandBurning(startX, startY);
if(isMyLandBurning){ // hurry over there ASAP!
debug("Bot land is burning!");
var pos = findFire(startX, startY);
debug("Fire found at", pos);
move = getDirection(currentX, currentY, pos.x, pos.y);
// simulate the move and figure out if/where to dump the water
var newX = currentX + (move == 'R') - (move == 'L');
var newY = currentY + (move == 'D') - (move == 'U');
if(chebyshev(newX, newY, pos.x, pos.y) < 5){
// on its own land, start dropping water like a madman
debug("Dropping water");
action.type = 'P';
// if it can put out the target fire, then do that
if(manhattan(newX, newY, pos.x, pos.y) == 1) action.direction = getDirection(newX, newY, pos.x, pos.y);
// it's not in range of the target fire, so use the time to put out other fires
// if it's moving on top of a fire, put that out
else if(get(newX, newY).match(/[1-6]/) != null) action.direction = 'S';
// if there's a fire around it then put that out
else if(get(newX + 1, newY).match(/[1-6]/) != null) action.direction = 'R';
else if(get(newX - 1, newY).match(/[1-6]/) != null) action.direction = 'L';
else if(get(newX, newY + 1).match(/[1-6]/) != null) action.direction = 'D';
else if(get(newX, newY - 1).match(/[1-6]/) != null) action.direction = 'U';
else action.direction = 'S';
}
} else {
// are there any bots that could start a fire when this bot is 6+ tiles away?
var headBack = false;
for(var i = 0; i < botPositions.length; i++){
var otherBot = botPositions[i];
var dist = manhattan(otherBot.x, otherBot.y, startX, startY) - 4;
var myDist = manhattan(currentX, currentY, startX, startY);
if(dist + 6 < myDist){
headBack = true;
break;
}
}
if(headBack){ // they're probably up to no good
debug("Bots are dangerously close, heading back");
move = getDirection(currentX, currentY, startX, startY);
} else if(state['turn'] - state['lastFireTurn'] < 3) { // no bots near own plot, time to consider other options
debug("Hiding fire");
// sneakily hide the fire if one was set :)
} else { // last option is to go find land to burn
debug("Finding land to burn");
var closestX = 999, closestY = 999;
for(var i = 0; i < state.botLands.length; i++){
var otherLand = state.botLands[i];
if(!isLandBurning(otherLand.x, otherLand.y) && chebyshev(currentX, currentY, otherLand.x, otherLand.y) > 4){ // find someone to burn
// use [-3, 3] here because on the first turn, the bots could have moved before this bot had a chance to see them
// meaning that the [-3, 3] region is the only one that is guaranteed to be on their land
for(var dx = -3; dx < 4; dx++){
for(var dy = -3; dy < 4; dy++){
var type = get(otherLand.x + dx, otherLand.y + dy);
var distThere = manhattan(currentX, currentY, otherLand.x + dx, otherLand.y + dy);
var distShortest = manhattan(currentX, currentY, closestX, closestY);
// find normal land, or wet land that will dry by the time the bot gets to it
if((type == '.' || type == '@' || (type == 'W' && distThere > 1)) && distThere < distShortest){
closestX = otherLand.x + dx;
closestY = otherLand.y + dy;
}
}
}
}
}
if(closestX != 999 && closestY != 999){ // land found; go there
debug("Target acquired", closestX, closestY);
debug("Burning land");
move = getDirection(currentX, currentY, closestX, closestY);
if(move == 'S'){ // is it on the land? If so, then burn it
action.type = 'B';
action.direction = 'S';
state['lastFireTurn'] = state['turn']; // record when the fire was set
}
} else { // everyone else's land already has a fire
debug("Default action");
// default to heading back; one can never be too safe!
move = getDirection(currentX, currentY, startX, startY);
}
}
}
// save the state file
writeState();
// output the action
console.log(move + action.type + action.direction);
});
```
] |
[Question]
[
You've probably heard of the [Fibonacci numbers](http://oeis.org/A000045); they're pretty famous. Each number in the Fibonacci sequence is the sum of the last two in the sequence with the first and second numbers being 1. The sequence looks like this:
```
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229 832040 1346269 2178309 3524578 5702887 9227465 14930352 24157817 39088169 63245986 102334155 165580141 267914296 433494437 701408733 1134903170 1836311903 2971215073 4807526976 7778742049 12586269025 20365011074 32951280099 53316291173 86267571272 139583862445 225851433717 365435296162 591286729879 956722026041 1548008755920 2504730781961 4052739537881 6557470319842 10610209857723 17167680177565 27777890035288 44945570212853 72723460248141 117669030460994 190392490709135 308061521170129 498454011879264 806515533049393 1304969544928657 2111485077978050 3416454622906707 5527939700884757 8944394323791464 14472334024676221 23416728348467685 37889062373143906 61305790721611591 99194853094755497 160500643816367088 259695496911122585 420196140727489673 679891637638612258 1100087778366101931 1779979416004714189 2880067194370816120 4660046610375530309 7540113804746346429 12200160415121876738 19740274219868223167 31940434634990099905 51680708854858323072 83621143489848422977 135301852344706746049 218922995834555169026 354224848179261915075 573147844013817084101 927372692193078999176 1500520536206896083277 2427893228399975082453 3928413764606871165730 6356306993006846248183 10284720757613717413913 16641027750620563662096 26925748508234281076009 43566776258854844738105 70492524767089125814114 114059301025943970552219 184551825793033096366333 298611126818977066918552 483162952612010163284885 781774079430987230203437 1264937032042997393488322
```
Similarly, Lucas sequences are the result of substituting the rather arbitrary `1 1` that start the Fibonacci sequence with any two arbitrary integers. Additionally unlike the Fibonacci sequence Lucas sequences also go backwards infinitely. For example `1 1` not only generates all of the numbers in the Fibonacci sequence but all the numbers that would lead up to it:
```
... 13 -8 5 -3 2 -1 1 0 1 1 2 3 5 8 13 ...
```
The Kernel of a Lucas sequence is the closest two consecutive members of the sequence. For example the Kernel of the Fibonacci sequence is `1 1` because they are 0 apart and thus must be the closest two numbers.
The size of the Kernel is measured as the absolute difference between the two members of the Kernel.
Since every pair of numbers is generated by at least one Lucas Sequence, and each sequence has a unique Kernel, for each pair of numbers there is a set of Kernels that generate them. The smallest Lucas Kernel is the smallest Kernel that generates two numbers.
For example take 8 and 21.
Here are a couple of sequences that have both 8 and 21 in them:
```
... 1 1 2 3 5 8 13 21 ...
... 18 -5 13 8 21 29 50 79 ...
... 21 -13 8 -5 3 -2 1 -1 0 -1 -1 ...
... 34 -13 21 8 29 37 68 ...
```
Now if we find the Kernels of each of these sequences we get:
```
1 1
13 8
-1 -1
29 37
```
The smallest Kernels are `1 1` and `-1 -1` (they are tied). We can know this without checking any other sequences because they are of size 0 and it is impossible to find any Kernels smaller than size 0.
## Task
Given two integers determine the smallest Lucas Kernel that generates them.
This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") question so the goal is to write code that performs this task in as few bytes as possible.
Standard input and output formats are accepted and enforced. You must handle negative numbers.
In cases where there are multiple valid solutions you need only output one
## Test Cases
```
8 21 -> 1 1
137 66 -> 66 67
45 80 -> 43 45
-6 45 -> 39 45
37 149 -> 18 19
37 97 -> -2 -3
```
[Answer]
# Python 2, 444 391 372 bytes
[Crossed out 444 is still regular 444 ;(](https://codegolf.stackexchange.com/a/109866/63641)
Huge thanks to @Dennis for a whopping -52 -71 bytes!
```
k=lambda c,a,b:abs(a+c*a-c*b)-c<abs(b-a)>0and k(c,b-c*a,a+b-c*b)or(a,b)
def f(*t):
a,b=sorted(t);m=b-a+1,0;g=lambda _:min([k(1,*k(0,*s)),m][_!=b:],key=lambda(x,y):abs(x-y))
if b<0:x,y=f(-a,-b);return-x,-y
for c in range(-b,b+1):
for s in(c,a),(a,c):
x,y=s
if min(s)>0:
while y<b:x,y=y,x+y
m=g(y)
x,y=s
while(x!=b)&((x>b)^(b>0)):x,y=y-x,x
m=g(x)
return m
```
[Try it online!](https://tio.run/nexus/python2#TZDdbsIwDIWv4Sm8C4bdOlI7/gvlRdCGkv6wqrRMbaclT8@cwqRdRLGOz7G/5F6nV92YXEPGmk2iTY86zAKtssCQyg5eMErTMdJtDjVmbKSlWYdmtNw6lBxN86KEEoOBkimIkPa3bihyHGjfpJIPY472l79d56SpWjzVGHNQY8RBT8TN@@n8kprknevCPZ1o2dEIZZUjmkJVgjlEichpiUqzMrTviuG7a5Vl5aZQ3jrIoGqh0@2lQGXYhLFATXyjl4a8QBMLdOZV8JN6uWWwZ@rloSJPfj6rawHuYMZVjm3oRG3SCzr6lxptaAWbXhHt0dAHmmNE9IgJkxWXj1mBf4BCc/csmsF4TsQtw1tMDBgvNgzrtS@XK4Zt5Cu1ZliufOW78XL3V@425D/bMjhI5e/9QFny1VXtAPPZIgd/1BGe5RxmMJp4zND9Fw)
The solution can be run by calling `f(a, b)` on the two input integers. It is based on the idea that if both `a` and `b` are within at least one of the same sequence (where `a` and `b` are ordered beforehand such that `a ≤ b`), it follows that there is at least one integer `c` equivalent to an adjacent value of `a` in a shared sequence of `a` and `b` for which the sequence generated by `a` and `c` contains `b` in it.
Furthermore, if at least one of the two integers is positive, all values of `c` must be bounded by `-b ≤ c ≤ b` for it to even be possible to generate the value of `b` on either side of the starting pair. Thus, the solution simply brute-forces values of `c` between `-b` and `b` that in combination with `a` are capable of generating `b` within the sequence, and finds the one for which the difference of the kernel values for `a` and `c` are minimal (this is possible because finding the kernel for two adjacent numbers in a sequence is trivial).
If neither `a` nor `b` is positive, the solution simply negates both and returns the negative of the kernel generated for the negated pair.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~81~~ 75 [bytes](https://codegolf.meta.stackexchange.com/questions/9428/when-can-apl-characters-be-counted-as-1-byte-each/)
```
⌊{⌽q⊃⍨⊃⍋|-/¨q←⊃,/2,/¨p/⍨B∊¨p←2(+/⍤↑,⊢,¯2-/⍤↑⊢)⍣{∧/B≤|¯2↑1⌽⍵}¨⍺,¨(-,⊢)⍳B←⍵}⌈
```
*-6 bytes thanks to @Adám*
[Try it online!](https://tio.run/##NU@7SsRAFK1nviKdK86YzCPZpI2Ntq4/sCBZhMBmsVqyVoLEmCxaWNrogimEFD4KwWb8k/sj8U4G4XLnnHMf5868yPn5ep4vF8PvF9zcl9B@/8eniysP2ievWObr7CLPPREfBnuXqO0GaOoSmp8V1NfQdmO@23DfdCvchJT5kiErfKymUNUIsSAnB771emBQPzPTS@4osn1oX0qoXv0UbncbLKEs0MFeYTo8ipluwpnrfE@tC1agqYZsxNvxhjdoP0yv7Mrt4@z0CPPZ8clsiL3Mk4JSoaaIoohSHSKIA0rtD3VIuJJEKMJFQnhEuLSKoKaPsE2HlI6DQiduIJliV0AUPlIRoQlPCE5oInAMNdeeTCkNrDPaSAf@AA "APL (Dyalog Unicode) – Try It Online")
## Explanation
This performs a similar algorithm as @notjagan's answer. For each `C` between `-B` and `B` inclusive, it produces the Lucas sequence containing `A,C` (where `A` and `B` are the minimum and maximum of the two arguments, respectively).
The part where this solution gets interesting is how the Lucas sequences and kernels are computed. Since a Lucas sequence is infinite, we can only generate a finite number of terms. Starting with `A,C`, we add one term to the beginning and one term to the end until the subsequence computed includes (at minimum) all terms with absolute value at most `B` (and thus B, iff the Lucas sequence contains B) and includes the kernel. This occurs if the beginning and end of the subsequence have absolute value at least B and the subsequence has at least 4 terms.
```
⌊{ ... B←⍵}⌈ ⍝ Find ⍺=min(x, y); B=max(x, y):
(-,⊢)⍳B ⍝ (-1,-2,-3...-B,1,2,3,..B)
⍝ (Don't need 0 since sequence from (A,0) is same as (A,A), which occurs since A≤B)
⍺,¨ ⍝ Prepend ⍺ to each to get all possible (A, C) pairs
... ¨ ⍝ For each (A, C) pair:
2(+/⍤↑,⊢,¯2-/⍤↑⊢) ⍝ Extend the Lucas sequence once in each direction
⍝ (This is the reverse of the normal recurrence, so f(a-1) = f(a) + f(a+1)):
+/2↑, ⍝ Sum of the left two,
⊢ ⍝ Existing sequence,
¯2-/⍤↑⊢ ⍝ Difference of the last two
⍣{ .. } ⍝ Extend until:
∧/B≤|¯2↑1⌽⍵ ⍝ The element with minimum absolute value is not one of the two endpoints
⍝ (At this point, the sequence must contain B if it ever will,
⍝ and it must contain the element with minimum absolute value,
⍝ so the kernel is just pair of elements with minimum absolute difference)
p/⍨B∊¨p← ⍝ Filter for those that contain B
2,/¨ ⍝ Find all consecutive pairs of terms in each sequence
⌽q⊃⍨⊃⍋|-/¨q←⊃,/ ⍝ Choose the pair of terms with minimum absolute difference; it must be a kernel
```
] |
[Question]
[
**Introduction**
You are alone on an island. The remainder of humanity is dead ([probably due to the bug in user12345's code](https://codegolf.stackexchange.com/questions/23631/the-floating-horde/23657#23657)). The Zombie Pirate Horde has reached your island, and they are endless. It's time to kick ass or chew bubble gum, and you're all outta bubble gum.
**Problem**
Our doomsday scenario is described by 2 integers on a single line, `m` and `n`. On your island are outposts uniquely numbered from 1 to `m`. The following `n` lines each contain three integers, `x`, `y`, and `z`, separated by a space. `x` and `y` are the unique IDs of two outposts, and `z` is the number of zombies that will be encountered on the path between them.
When you travel a path, you lose `z` ammunition and you kill `z` zombies. If you travel the same path again, you will encounter the same number of zombies, unfortunately. All outposts generate +1 ammunition each time you travel a path. You begin with 100 ammunition at outpost 1. All outposts begin with 0 ammunition. You die immediately if no path exists for which your ammunition is greater than the number of zombies on that path, and the remainder of your ammunition is converted to kills. Such is your final stand.
Write a program that outputs the maximum number of zombies you can kill for a given scenario. If you can kill an infinite number of zombies, simply output `x`.
**Example Input**
```
5 6
1 2 4
2 3 4
3 1 4
2 4 10
2 5 10
1 1 50
```
**Example Output**
```
x
```
**Assumptions**
* A path will be between two valid outposts. That is to say 1 <= `x`/`y` <= `m`
* If a path between `x` and `y` is not listed, it cannot be traveled
* A path is bidirectional
* 1 < `m` <= 100
* 1 < `n` <= 500
* Input must be provided through stdin, read from a file, or accepted as a sole argument to the program, and it must exactly follow the format of the example
* The runtime of your program may be arbitrarily large but must be determinably finite
The code with the fewest characters wins!
[Answer]
# Java ( *less* grotesque: 8415 5291 3301)
Ok. Basically, I'm embarrassed no-one has submitted a solution. [So a few days ago I began trying to solve this problem, b/c it's great.](https://github.com/ProgrammerDan/zombie-horde-graph). Follow that link to watch my progress on it via GitHub.
### Edit
New solver version, much more "golfed", with corrected cycle checker as identified by MT0. It also supports fast-forwarding routes, tuneable by changing how much memory is available to the VM. Latest **BIG** edit: realized that I had a few other small index errors and premature optimizations, that resulted in a failure to consider quite a large number of types of wins. So that's fixed, carefully. The new version is both smaller and below.
For our reference route, `java -Xmx2GB ZombieHordeMin` does the trick quite nicely (be warned, it will take a while).
### Cool factoid
In a fascinating twist, there are MANY solutions at length 24, and my solver finds one different from MT0's, but identical in principle, except that it *starts* by visiting the the other outposts connected to `1`. Fascinating! Totally counter human intuition, but perfectly valid.
### Solution Highlights
So here's mine. It's (partially) golfed, b/c it's an exponential, almost-brute-force solver. I use an IDDFS (iterative deepening depth first search) algorithm, so it's a great general solver that doesn't skip, so it solves **both** parts of the OP's question, namely:
* If a winning route is found (infinite zombies), output 'x'.
* If all routes end in death (finite zombies), output the largest number of zombies killed.
Give it enough power, memory, and time, and it will do just that, even slow-death maps. I spent some more time improving this solver, and while more can be done, it's a bit better now. I also integrated MT0's advice on the best infinite-zombies solution, and removed several premature optimizations from my win-checker that prevented the previous version from finding it, and now I do in fact find a very similar solution to the one MT0 described.
A few other highlights:
* As mentioned, uses an IDDFS to find the shortest possible winning route.
* Since it is at core a DFS, it will also discover if every route ends in the death of our hero, and keeps track of the "best" route in terms of most zombies killed. Die a hero!
* I've instrumented the algorithm to make it more interesting to watch Removed for golfing purposes. Follow one of the links to github to see the ungolfed version.
* There are a number of comments throughout as well, so feel free to re-implement for your own solution building on my approach, or show me how it should be done!
* Memory-adaptive route fast-forwarding
+ Up to available system memory, will keep track of "end routes" that did not result in death.
+ Using a fancy route compression and decompression routine, progress from a prior iteration of IDDFS is restored to prevent rediscovery all prior visited routes.
+ As an intentional side-bonus, acts as a dead-end route cull. Dead end routes aren't stored, and will never be visited again in future depths of IDDFS.
## History of the solver
* I tried a bunch of one-step look-ahead algorithms, and while for very simple scenarios they would work, ultimately they fall flat.
* Then I tried a two-step look-ahead algorithm, which was.. unsatisfying.
* I then began building an n-step lookahead, when I recognized that this approach is reducible to DFS, yet DFS is far ... more elegant.
* While building the DFS, it occurred to me that IDDFS would ensure (a) find best HERO (death) route or (b) first winning cycle.
* Turns out building a win-cycle checker is easy, but I had to go through several very very wrong iterations before I got to a provably successful checker.
* Factored in MT0's win-path to remove three lines of premature optimization that made my algorithm blind to it.
* Added an adaptive route-caching algorithm that will use all the memory you give it to prevent unnecessary redoing of work between IDDFS calls, and also culls dead-end routes up to the limits of memory.
### The (golfed) code
On to the code (get the ungolfed version [here](https://github.com/ProgrammerDan/zombie-horde-graph/blob/master/ZombieHordeExponential.java) or [here](https://github.com/ProgrammerDan/zombie-horde-graph/blob/master/ZombieHordeMin.java)):
```
import java.util.*;public class ZombieHordeMin{int a=100,b,m,n,i,j,z,y,D=0,R,Z,N;int p[][][];Scanner in;Runtime rt;int[][]r;int pp;int dd;int[][]bdr;int ww;int[][]bwr;int[][]faf;int ff;boolean ffOn;public static void main(String[]a){(new ZombieHordeMin()).pR();}ZombieHordeMin(){in=new Scanner(System.in);rt=Runtime.getRuntime();m=in.nextInt();N=in.nextInt();p=new int[m+1][m+1][N+1];int[]o=new int[m+1];for(b=0;b<N;b++){i=in.nextInt();j=in.nextInt();z=in.nextInt();o[i]++;o[j]++;D=(o[i]>D?o[i]:D);p[i][j][++p[i][j][0]]=z;if(i!=j)p[j][i][++p[j][i][0]]=z;D=(o[j]>D?o[j]:D);}m++;}void pR(){r=new int[5000][m+3];r[0][0]=a;Arrays.fill(r[0],1,m,1);r[0][m]=1;r[0][m+1]=0;r[0][m+2]=0;ww=-1;pp=dd=0;pR(5000);}void pR(int aMD){faf=new int[D][];ff=0;ffOn=true;for(int mD=1;mD<=aMD;mD++){System.out.printf("Checking len %d\n",mD);int k=ffR(0,mD);if(ww>-1){System.out.printf("%d x\n",ww+1);for(int win=0;win<=ww;win++)System.out.printf(" %d:%d,%d-%d",win,bwr[win][0],bwr[win][1],bwr[win][2]);System.out.println();break;}if(k>0){System.out.printf("dead max %d kills, %d steps\n",pp,dd+1);for(int die=0;die<=dd;die++)System.out.printf(" %d:%d,%d-%d",die,bdr[die][0],bdr[die][1],bdr[die][2]);System.out.println();break;}}}int ffR(int dP,int mD){if(ff==0)return pR(dP,mD);int kk=0;int fm=ff;if(ffOn&&D*fm>rt.maxMemory()/(faf[0][0]*8+12))ffOn=false;int[][]fmv=faf;if(ffOn){faf=new int[D*fm][];ff=0;}for(int df=0;df<fm;df++){dS(fmv[df]);kk+=pR(fmv[df][0],mD);}fmv=null;rt.gc();return kk==fm?1:0;}int pR(int dP,int mD){if(dP==mD)return 0;int rT=0;int dC=0;int src=r[dP][m];int sa=r[dP][0];for(int dt=1;dt<m;dt++){for(int rut=1;rut<=p[src][dt][0];rut++){rT++;r[dP+1][0]=sa-p[src][dt][rut]+r[dP][dt];for(int cp=1;cp<m;cp++)r[dP+1][cp]=(dt==cp?1:r[dP][cp]+1);r[dP+1][m]=dt;r[dP+1][m+1]=rut;r[dP+1][m+2]=r[dP][m+2]+p[src][dt][rut];if(sa-p[src][dt][rut]<1){dC++;if(pp<r[dP][m+2]+sa){pp=r[dP][m+2]+sa;dd=dP+1;bdr=new int[dP+2][3];for(int cp=0;cp<=dP+1;cp++){bdr[cp][0]=r[cp][m];bdr[cp][1]=r[cp][m+1];bdr[cp][2]=r[cp][0];}}}else{for(int chk=0;chk<=dP;chk++){if(r[chk][m]==dt){int fR=chk+1;for(int cM=0;cM<m+3;cM++)r[dP+2][cM]=r[dP+1][cM];for(;fR<=dP+1;fR++){r[dP+2][0]=r[dP+2][0]-p[r[dP+2][m]][r[fR][m]][r[fR][m+1]]+r[dP+2][r[fR][m]];for(int cp=1;cp<m;cp++)r[dP+2][cp]=(r[fR][m]==cp?1:r[dP+2][cp]+1);r[dP+2][m+2]=r[dP+2][m+2]+p[r[dP+2][m]][r[fR][m]][r[fR][m+1]];r[dP+2][m]=r[fR][m];r[dP+2][m+1]=r[fR][m+1];}if(fR==dP+2&&r[dP+2][0]>=r[dP+1][0]){ww=dP+1;bwr=new int[dP+2][3];for(int cp=0;cp<dP+2;cp++){bwr[cp][0]=r[cp][m];bwr[cp][1]=r[cp][m+1];bwr[cp][2]=r[cp][0];}return 0;}}}dC+=pR(dP+1,mD);if(ww>-1)return 0;}for(int cp=0;cp<m+3;cp++)r[dP+1][cp]=0;}}if(rT==dC)return 1;else{if(ffOn&&dP==mD-1)faf[ff++]=cP(dP);return 0;}}int[]cP(int dP){int[]cmp=new int[dP*2+3];cmp[0]=dP;cmp[dP*2+1]=r[dP][0];cmp[dP*2+2]=r[dP][m+2];for(int zip=1;zip<=dP;zip++){cmp[zip]=r[zip][m];cmp[dP+zip]=r[zip][m+1];}return cmp;}void dS(int[]cmp){int[]lv=new int[m];int dP=cmp[0];r[dP][0]=cmp[dP*2+1];r[dP][m+2]=cmp[dP*2+2];r[0][0]=100;r[0][m]=1;for(int dp=1;dp<=dP;dp++){r[dp][m]=cmp[dp];r[dp][m+1]=cmp[dP+dp];r[dp-1][cmp[dp]]=dp-lv[cmp[dp]];r[dp][m+2]=r[dp-1][m+2]+p[r[dp-1][m]][cmp[dp]][cmp[dP+dp]];r[dp][0]=r[dp-1][0]+r[dp-1][cmp[dp]]-p[r[dp-1][m]][cmp[dp]][cmp[dP+dp]];lv[cmp[dp]]=dp;}for(int am=1;am<m;am++)r[dP][am]=(am==cmp[dP]?1:dP-lv[am]+1);}}
```
Get the code from github [here, to track any changes](https://github.com/ProgrammerDan/zombie-horde-graph/blob/master/ZombieHordeExponential.java) I make. [Here are some other maps I used.](https://github.com/ProgrammerDan/zombie-horde-graph/blob/master/horde-test-graphs.txt)
### Output example
Example output for reference solution:
```
$ java -d64 -Xmx3G ZombieHordeMin > reference_route_corrected_min.out
5 6 1 2 4 2 3 4 3 1 4 2 4 10 2 5 10 1 1 50
Checking len 1
Checking len 2
Checking len 3
Checking len 4
Checking len 5
Checking len 6
Checking len 7
Checking len 8
Checking len 9
Checking len 10
Checking len 11
Checking len 12
Checking len 13
Checking len 14
Checking len 15
Checking len 16
Checking len 17
Checking len 18
Checking len 19
Checking len 20
Checking len 21
Checking len 22
Checking len 23
Checking len 24
25 x
0:1,0-100 1:3,1-97 2:1,1-95 3:2,1-94 4:5,1-88 5:2,1-80 6:4,1-76 7:2,1-68 8:1,1-70 9:2,1-68 10:1,1-66 11:2,1-64 12:1,1-62 13:2,1-60 14:1,1-58 15:2,1-56 16:1,1-54 17:2,1-52 18:1,1-50 19:2,1-48 20:1,1-46 21:2,1-44 22:1,1-42 23:2,1-40 24:1,1-38
```
Read the route output like this: `step`:`source`,`route-to-get-here`-`ammo`. So in the above solution, you would read it as:
* At step `0`, at outpost `1` with ammo `100`.
* At step `1`, use route `1` to get to outpost `3` with ending ammo `97`
* At step `2`, use route `1` to get to outpost `1` with ending ammo `95`
* ...
### Closing notes
So, I hope I've made my solution harder to beat, but PLEASE TRY! Use it against me, add in some parallel processing, better graph theory, etc. A couple of things I figure could improve *this* approach:
* aggressively "reduce" loops to cut out needless retread as the algorithm progresses.
+ An example: in the example problem, consider the loops 1-2-3 and other permutations as "one step", so that we can make our way to end-cycle more quickly.
+ E.g. if you are at node 1, you can either (a) go to 2, (b) go to 1, (c) go through 1-2-3 as one step and so on. This would allow a solved to fold depth into breadth, increasing the number of routes at a particular depth but greatly speeding time-to-solution for long cycles.
* cull dead routes. My current solution doesn't "remember" that a particular route is dead-ended, and has to rediscover it every time. It would be better to keep track of the earliest moment in a route that death is certain, and never progress beyond it. did this...
* if careful, you could apply the dead route culling as a sub-route cull. By example, if 1-2-3-4 always results in death, and the solver is about to test the route 1-3-1-2-3-4, it should immediately stop descending that path as it is guaranteed to end in disappointment. It would still be possible to calculate # of kills, with some careful math.
* Any other solution that trades memory for time, or allows aggressive avoidance of following dead-end routes. did this too!
[Answer]
# Some abstract notes on a solution
*If I get time I'll convert this into an algorithm...*
For a given graph `G` then there exists a connected sub-graph `G'` which contains town `1`. If there is an infinite solution then there will exist a connected sub-graph `G''` of `G'` which contains `V` towns and `P` paths.
The paths `P` of `G''` can be partitioned such that `{p}` contains a path which has then minimal cost of all the paths in `P` and `P/{p}` is all the other paths (forming a spanning tree or possibly a cycle). If we assume that `p` is not a looping edge (connecting both ends to the same town) then it will connect two towns (`v1` and `v2`) and has cost `c` ammunition then you (the survivor) can then traverse from `v1` to `v2` and back at a total cost of `2c` ammunition and this will increase the ammunition in all the towns by 2 (for a total increase of `2|V|` within `G''` - some of which will have been collected from `v1` and `v2`).
If you travel from `v1` to `v2` and back to `v1` multiple (`m`) times and then take a trip from `v1` along the edges `P/{p}` to visit all the towns other than `v1` and `v2` before returning to `v1` and this takes `n` paths to achieve (where `|P/{p}| ≤ n ≤ 2|P/{p}|` since you should never need to traverse a path more than twice) with a cost of `k` and the towns will gain `2m|V|` ammunition (again some of which will have been collected during traversal).
Given all this then you can tell if an infinite solution is potentially possible if then cost `k + 2mc` is equal or lower than the total reward `2(m+n)|V|`.
There is a additional complexity to the problem in that:
* you may need to travel from the starting town `1` to `{p}` on the first iteration and need to factor in this cost; and
* you also need to ensure that the `m` and `n` are low enough that you don't run out of ammunition before you can make it through the first iteration since the first iteration will have a higher cost than the subsequent iterations).
This leads to a 24 path cost neutral solution to the example in the question (the numbers are the towns visited):
```
1,3,1,3,1,3,1,3,1,3,1,3,1,3,1,3,1,3,2,4,2,5,2,3, ... and repeat ...
```
] |
[Question]
[
My robot for generating [Mad Libs](https://en.wikipedia.org/wiki/Mad_Libs)-style [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") challenges has gone rogue! To defeat it, I need you to write code that can solve all the challenges it can crank out.
Your input is three selections for the blanks A, B, C, each from (1,2,3), specifying the sequence challenge to solve, and the number \$n\$ that's the input to the challenge.
**Challenges**
Given a positive integer \$n\$, output (A) \_\_\_\_\_\_\_\_
>
> **A:**
>
> (1) the \$n\$'th
>
> (2) whether \$n\$ is a
>
> (3) the smallest number above \$n\$ that's a
>
>
>
positive (B) \_\_\_\_\_\_\_
>
> **B:**
>
> (1) [Fibonacci number](https://en.wikipedia.org/wiki/Fibonacci_number)
>
> (2) [triangular number](http://triangular%20number)
>
> (3) multiple of 3
>
>
>
whose base-10 representation (C) \_\_\_\_\_\_\_
>
> **C:**
>
> (1) starts and ends with the same digit.
>
> (2) is in sorted order.
>
> (3) doesn't have any 1's.
>
>
>
**Example**
Given selections `(A, B, C) = (3, 1, 1)` and `n=13`, the challenge is "Given a positive integer \$n\$, output (A3) the smallest number above \$n\$ that's a positive (B1) Fibonacci number whose base-10 representation (C1) starts and ends with the same digit." With input `n=13`, the Fibonacci numbers bigger than \$13\$ start out as \$21, 34, 55, 89, ...\$, and the first one starting and ending with the same digit is is 55. So you should output 55.
**Details**
* You may take the fill-in-the-blank selections one-indexed (1, 2, 3) or zero-indexed (0, 1, 2).
* Note that we're restricting the sequences to positive values, so none of them contain zero. They start as
+ Fibonacci: \$1, 1, 2, 3, ...\$
+ Triangular: \$1, 3, 6, 10, ...\$
+ Multiple of 3: \$3, 6, 9, 12, ...\$
* For choice A1, outputting the \$n\$'th element, \$n\$ is one-indexed. So, the `n=1` Fibonacci number is 1, the `n=2` Fibonacci number is also 1, `n=3` gives 2, and so on.
* For deciding whether n is in the sequence (A2), you may use any two consistent outputs [decision-problem](/questions/tagged/decision-problem "show questions tagged 'decision-problem'")-style.
* You may assume that each sequence has an infinite number of terms meeting each condition C, and not worry about what happens with machine overflows and the like.
* For C2, digits in sorted order can have "ties", such as `377`.
**Test cases**
Here are all outputs for every combination with `n=10`, as `(A,B,C), n: result`. For these, we use one-indexed selections, and for A2 we use `1/0` for `True/False`
```
(1, 1, 1), 10: 165580141
(1, 1, 2), 10: 89
(1, 1, 3), 10: 987
(1, 2, 1), 10: 1431
(1, 2, 2), 10: 78
(1, 2, 3), 10: 276
(1, 3, 1), 10: 222
(1, 3, 2), 10: 36
(1, 3, 3), 10: 42
(2, 1, 1), 10: 0
(2, 1, 2), 10: 0
(2, 1, 3), 10: 0
(2, 2, 1), 10: 0
(2, 2, 2), 10: 0
(2, 2, 3), 10: 0
(2, 3, 1), 10: 0
(2, 3, 2), 10: 0
(2, 3, 3), 10: 0
(3, 1, 1), 10: 55
(3, 1, 2), 10: 13
(3, 1, 3), 10: 34
(3, 2, 1), 10: 55
(3, 2, 2), 10: 15
(3, 2, 3), 10: 28
(3, 3, 1), 10: 33
(3, 3, 2), 10: 12
(3, 3, 3), 10: 24
```
The first 10 outputs, `n=1` to `n=10`, for each challenge combination are:
```
(1, 1, 1): 1, 1, 2, 3, 5, 8, 55, 17711, 63245986, 165580141,
(1, 1, 2): 1, 1, 2, 3, 5, 8, 13, 34, 55, 89,
(1, 1, 3): 2, 3, 5, 8, 34, 55, 89, 233, 377, 987,
(1, 2, 1): 1, 3, 6, 55, 66, 171, 595, 666, 1081, 1431,
(1, 2, 2): 1, 3, 6, 15, 28, 36, 45, 55, 66, 78,
(1, 2, 3): 3, 6, 28, 36, 45, 55, 66, 78, 253, 276,
(1, 3, 1): 3, 6, 9, 33, 66, 99, 111, 141, 171, 222,
(1, 3, 2): 3, 6, 9, 12, 15, 18, 24, 27, 33, 36,
(1, 3, 3): 3, 6, 9, 24, 27, 30, 33, 36, 39, 42,
(2, 1, 1): 1, 1, 1, 0, 1, 0, 0, 1, 0, 0,
(2, 1, 2): 1, 1, 1, 0, 1, 0, 0, 1, 0, 0,
(2, 1, 3): 0, 1, 1, 0, 1, 0, 0, 1, 0, 0,
(2, 2, 1): 1, 0, 1, 0, 0, 1, 0, 0, 0, 0,
(2, 2, 2): 1, 0, 1, 0, 0, 1, 0, 0, 0, 0,
(2, 2, 3): 0, 0, 1, 0, 0, 1, 0, 0, 0, 0,
(2, 3, 1): 0, 0, 1, 0, 0, 1, 0, 0, 1, 0,
(2, 3, 2): 0, 0, 1, 0, 0, 1, 0, 0, 1, 0,
(2, 3, 3): 0, 0, 1, 0, 0, 1, 0, 0, 1, 0,
(3, 1, 1): 2, 3, 5, 5, 8, 8, 8, 55, 55, 55,
(3, 1, 2): 2, 3, 5, 5, 8, 8, 8, 13, 13, 13,
(3, 1, 3): 2, 3, 5, 5, 8, 8, 8, 34, 34, 34,
(3, 2, 1): 3, 3, 6, 6, 6, 55, 55, 55, 55, 55,
(3, 2, 2): 3, 3, 6, 6, 6, 15, 15, 15, 15, 15,
(3, 2, 3): 3, 3, 6, 6, 6, 28, 28, 28, 28, 28,
(3, 3, 1): 3, 3, 6, 6, 6, 9, 9, 9, 33, 33,
(3, 3, 2): 3, 3, 6, 6, 6, 9, 9, 9, 12, 12,
(3, 3, 3): 3, 3, 6, 6, 6, 9, 9, 9, 24, 24,
```
[Answer]
# JavaScript (ES6), ~~158 ... 145~~ 144 bytes
Takes input as `(a,b,c,n)`, with \$a\$, \$b\$ and \$c\$ 0-indexed.
```
(a,b,c,n)=>(g=x=>[(d=[...x+''],i+=C=![d[0]-x%10,d+''>d.sort(),/1/.test(x)][c])>n,x>=n,x>n&C][a]?a-1?x:C&x==n:g([y,x+y,x+3][b],y+=b||x))(i=0,y=1)
```
[Try it online!](https://tio.run/##bZDdasMwDIXv@xTaxVqbKG6y7rdD7kXYUxhfOM7PMjq7JGE4rH32LGkZG2wXOgf0SUegN/NhOts2hz52vijHikZmMEeLjpNkNQWSihWkhBAhWq00NhFldKUKleg4XKcJFlNbFqLzbc84rtO16MuuZ4FrZTWXDoOkWdwy08ronYnTXdhmy0DktjVTA4Zoro1WucYhovx4DJyzhhIcKOXj80IlCCnCjRaVb1@MfWUGSMLnAuAvyr/Rf9D@QADrXef3pdj7egqM5tH8YvZial5G2CDcItwh3CM8IDwiPE25iRbv5sDcnFhNT4N82kNwnPNz/mm2s/y@wxcnPn4B "JavaScript (Node.js) – Try It Online")
### Commented
```
(a, b, c, n) => ( // given the challenge parameters ...
g = x => // g is a recursive function taking the current value x
[ // this is the array for A
( // a = 0:
d = [...x + ''], // d[] = array of digits in x
i += C = // increment i if C is true
![ // set C if the condition is false:
d[0] - x % 10, // c = 0: the 1st and the last digits are not equal
d + '' > d.sort(), // c = 1: the digits are not in sorted order
/1/.test(x) // c = 2: there's a '1' in x
][c] // pick the relevant condition for C
) > n, // exit if i is greater than n
x >= n, // a = 1: exit if x is greater than or equal to n
x > n & C // a = 2: exit if x is greater than n and C is true
][a] // pick the relevant condition for A
? // if we're done:
a - 1 ? x // if a is not equal to 1, return x
: C & x == n // otherwise, test whether C is true and x is equal to n
: // else:
g( // do a recursive call:
[ // update x:
y, // b = 0: x = y (Fibonacci)
x + y, // b = 1: x += y (triangular numbers)
x + 3 // b = 2: x += 3 (multiples of 3)
][b], // pick the relevant update for B
y += b || x // if b = 0, add x to y (for Fibonacci)
// otherwise, add b to y (we actually just need to
// add 1 for triangular numbers; for multiples of 3,
// y is ignored anyway)
) // end of recursive call
)(i = 0, y = 1) // initial call to g with x = i = 0 and y = 1
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~426~~ \$\cdots\$ ~~204~~ 181 bytes
Saved 9 bytes thanks to [RGS](https://codegolf.stackexchange.com/users/75323/rgs)!!!
```
def f(a,b,c,n):
j=i=l=x=0;y=1
while(i<n,l<n,l<=n)[a]:
j+=1;x,y=y,x+y;p=(x,j*-~j//2,3*j)[b];s=str(p)
if(s[0]==s[-1],[*s]==sorted(s),not'1'in s)[c]:l=p;i+=1
return(l,l==n)[a%2]
```
[Try it online!](https://tio.run/##XZDdaoQwEEbv9ykGoZjoLLtZ77TzJMELf2I3EqIkliqyfXVrXNiWXiSEw3cyXzIu032w2ba1qoOOVVhjg5bnJ@hJk6GZrsVC4gRfd20U0@8WzbHIclmVew76lEQx40ILzulSjMRm7JPzd3@53DBLei7rsvDkJ8dGvud1x7y8lkRenkWJMvHhPLhJtcxztMMUi1hb8Fw2ZW5oLHQaGjg1fTrLDBo6hr/dyq0bHBydYRfYsz4/YACush@KZQeo/4PmLwgPHp22E@sitlYPhLUOW/PgOUSobEtxvJcPov0VBYIQwX3Ja/hDqBEaBMv3KyKEl/0M8e0H "Python 3 – Try It Online")
\$(a,b,c)\$ are zero-indexed and *...whether \$n\$ is a...* returns `True`/`False`.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 245 bytes
**Input {a,b,c,n}**
True/False for A(2)
```
(d=#4;a=#;c=#3;n={#&@@(i=IntegerDigits)@#==#~Mod~10&,OrderedQ@i@#&,i@#~FreeQ~1&};{t=v=1;While[v<=d,While[!n[[c]][#@t++]];v++];#[t-1],!FreeQ[#[w=Range[3d]],d]&&n[[c]]@d,#&@@Select[Select[#@w,#>d&],n[[c]]]}[[a]]&[{Fibonacci,#(#+1)/2&,3#&}[[#2]]])&
```
[Try it online!](https://tio.run/##LU7BSsNAFPwVy4MloSs2jbf1yR6k4EE0evDweId195EutFuIa3oIza/H2MjAzMDMwBxd3svR5ejd1OJUBIR74xCMR6hNwgGUtUXE55Slle4ptjF/lxYQYXw5hbHaKP3aBekkNDZaUHqmcdeJNGOlLmbI2GNlPvfxINQ/YNCLXSUiz0xg83rNbPqZDVC@rVivrnMCOuO7S61QHZh1YKWWkQ3679WHHMRn@hewZw2PQbFeSnwhcsyKhl38OiXnfdRQwLoq77ZK16DmHLZzr1TTWxdTts1PlGzbG6r0FRuepl8 "Wolfram Language (Mathematica) – Try It Online")
[Here](https://tio.run/##NdCxasMwEAbgvU@hRCASfKVRPToqGkqgQ2nTDh2OG2RJOILEAVckg4lf3ZUjV8PdD98diDuZePAnE4M147g7d2iYYhKYYVvFytSLAh4Ym6TOUs9SZ7mTzWRnsjPdzWVzk8lNCv/IGrVqVc@F1qug3troG9@9hibE37XmSvHh/ewGuRHw0TnfebfXQXMBqQy7zvv9IMWt6qO6KFn9HMLR42WrHOS4aBEtEXIdi4KouqRacYyPkmBxX0eOV/Vl2sZj6YjAkRB5STuYfvXtj95GnBvXV@AvThDkIbohGiKB/S7U59ZYG4CveCHXT88CSi6S12lsXX12oY3YG6jB3mDJlukIwJbpAik1NL1x/AM) are all test cases for n=1 to 10
[Answer]
# [R](https://www.r-project.org/), 199 bytes
```
f=function(A,B,C,n){u=c(sum(1:B),1+2*(B>2))
while(sum(v<-grepl(c("^(.)(.*\\1)?$","^1*2*3*4*5*6*7*8*9*$","^[^1]*$")[C],u))<n+2)u=c(u[1]+c(u[2],sum(u^0)+1,3)[B],u)
w=u[v]
c(w[3],n%in%w,min(w[w>n]))[A]}
```
[Try it online!](https://tio.run/##Tc7fasIwFAbw@z6FlAnnpJmYc9w/sQ7rY8T0ptgtoFE6Yy/Gnr1rO1YOCeRL8pFfmq7O@1nHUN38JcBOF3qvA37HvIKveAazLlCbjBQUW0JM2k9/Oo43983jR3O8nqCCtIQFwkIdDgbfH1KdlkaRYrVST@pZvahX9abGY1sa1ye0e6cj4iZkhIMUrXHZsJDTw9uxXGJmNKMthmLS5tHeXVJBa9npMPdh3uqzD/2@3QaHaHfup6vB6HEsMfnLJDJPmUSHRIdEh0WHRYenDgmLhEXCImGRsEhYJCwSFgmLhcXCYmGxsFhYLCwWFguLJyupLw34mQ8zs@7318aHG/x/3iN2vw "R – Try It Online")
Conditions C1-C3 are checked via regex.
In all cases, it computes the first `n+2` terms verifying the condition; this is always enough. They are stored in reverse in `w`. Then:
* for A1, take `w[3]`
* for A2, check whether `n` appears in `w`
* for A3, take the min of the elements of `w` which are greater than `n`.
Details of the regexes:
* C1: `^(.)(.*\\1)?$`: get first digit with `^(.)`, then find either the end of the number (correspond to a 1-digit number) or any sequence followed by the same digit again
* C2: `^1*2*3*4*5*6*7*8*9*$`: any number of 1s, then any number of 2s, then... then any number of 9s
* C3: `^[^1]*$` only digits which are not 1
`w` is built as the elements of sequence `u` verifying the regex, where `u` is the Fibonacci/Triangular/multiples of 3 sequence, built iteratively by adding the appropriate increment at each step.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 58 bytes
```
ị"“ÆḞ“+1c2“×3”,“.ịEƊ“ṢƑ“ċ1¬$”,“ṖṪ“e@“>Ƈ”ż“¶1ÇD“Ɗ⁸+1¤#Ç”FvḢ
```
[Try it online!](https://tio.run/##y0rNyan8///h7m6lRw1zDrc93DEPSGsbJhuBuNONHzXM1QGy9IAKXI91AVkPdy46NhFIH@k2PLRGBSr9cOe0hztXARmpDkDC7lg7UPzoHiDz0DbDw@0uQAZQb@MObcNDS5QPgyTdyh7uWPT/4c591kA5BV07BaCY9eHljzauMzQAiqpwGT/cOd0YqLRpTeR/AA "Jelly – Try It Online")
A dyadic link taking the choices in the order `B, C, A` as the left argument and `n` as the right argument. Builds a program from component parts and then executes it. The presence of two ones at the start of the Fibonacci sequence added an extra four characters!
## Explanation
```
ị" | Index into the following list of strings, zipped with the first argument (so the first choice picks from the first list of strings, the second from the second and the third from the third):
```
### First set of choices
```
“ÆḞ | - Fibonacci sequence
“+1c2 | - Triangular numbers
“×3”, | - Multiply by 3
```
### Second set of choices
```
“.ịEƊ | - Extract last and first terms and check if equal
“ṢƑ | - Check whether invariant when sorted
“ċ1¬$”, | - Count 1s and then logical not
```
### Third set of choices
```
“ṖṪ | - Remove last then take last remaining
“e@ | - Exists (with arguments reversed)
“>Ƈ” | - Keep those greater than
```
### Fixed bits of generated program
```
ż | Zip with strings representing the following
“¶1ÇD | - Newline, then 1 followed by call of previous link followed by D convert to decimal digits
“Ɗ⁸+1¤#Ç” | - Last three as a monad called to find n+1 matching terms
```
### Code to execute the generated program
```
F | Flatten
v | Call as Jelly code using n as argument
Ḣ | Head (needed when A is 3)
```
### Example generated code for `[1,1,1]`:
```
ÆḞ
1ÇD.ịEƊƊ⁸+1¤#ÇṖṪ
```
[Answer]
# [Python 2](https://docs.python.org/2/), 162 bytes
Inputs A, B, C are 0-indexed.
```
a,b,c,n=input();
i=0;x=k=1
while[n,i<n,i<=n][a]|1-x:i,k=[k,k+i,i+3][b],k+(b or i);s=`i`;x=[s[0]==s[-1],sorted(s)==list(s),not'1'in s][c];n-=x>a
print[i,i==n][a%2]
```
[Try it online!](https://tio.run/##TY9Ba8MgFIDv/op3GWmpgfh2a/Z266677CZCk1SopJiglqWw/56ZhXQPFD/w4306PtJ18Dh3w8UCQVEUcyNb2UlPzo/3tNvXwlFVT9STEt9Xd7PaS/e2bPJGN@ZHldPRyZ50L/uDk@7wanRrMu9aGAK4fR3p7M55hI66MkRRl8rIOIRkL7u4J7q5mDJIP6RCFc5DNLoztS9pem/EGJxPOg@mv@ALmjk/U6yPga9wt0cBkMJjOQDsZDtYviMW7uyY4PT5cQphCKvQBtv0cyUhL5VXJVbGjdV6tbFi/HSQOcgc3Jx1SMVYMX46ijmKOYo5yBxkzrOFrIWshayFrIWshayFrIWshf@tXw "Python 2 – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~49~~ 44 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
∞3*∞Åf∞ηO)³èʒ1å≠y¬Å¿yD{Q)Iè}D¹²i<èë²<i.ië›Ïн
```
Input is 1-based in the order \$n,A,B,C\$, and for A2 it'll output \$0\$/\$1\$ for truthy/falsey respectively.
-5 bytes thanks to *@Grimmy*.
[Try it online](https://tio.run/##AVoApf9vc2FiaWX//@KInjMq4oiew4Vm4oiezrdPKcKzw6jKkjHDpeKJoHnCrMOFwr95RHtRKUnDqH1EwrnCsmk8w6jDq8KyPGkuacOr4oC6w4/Qvf//MTAKMQoyCjM) or [verify all test cases](https://tio.run/##yy9OTMpM/W/sY3x4cVmIq19lUIKSo@3h/TpOIMIZROQBCYVHbZMUlOwrQ/3C/j/qmGesBSQOt6YByXPb/TUjDrcWH15xapLh4aWPOhdUHlpzuPXQ/kqX6kDNiHM7Dq@odYmMuLA30@bwisOrgQybTL3Mw6sfNew63H9h7//aWh3NmP8A).
**Explanation:**
```
∞ # Push an infinite list of positive integers: [1,2,3,...]
3* # Multiply each by 3
∞ # Push an infinite list of positive integers again
Åf # Get the (0-based) n'th Fibonacci of each
∞ # Push an infinite list of positive integers again
η # Get all prefixes
O # And sum each prefix
) # Wrap all infinite lists into a list
³è # And index the third input (B) into it (0-based and with wraparound)
ʒ # Filter this list by:
1å # Check if the current value contains a 1
≠ # And invert the boolean
y # Push the current value again
¬ # Push its head (without popping)
Å¿ # And check if the value ends with this head
y # Push the current value again
D{ # Create a copy, and sort its digits
Q # Check if both are equal
) # Wrap all three checks into a list
Iè # And index the next fourth input (C) into it (0-based and with wraparound)
}D # After the filter: duplicate the resulting filtered infinite list
¹ # Push the first input (n)
²i # If the second input (A) is exactly 1:
< # Decrease `n` by 1 to make it 0-based
è # And use it to index into the filtered infinite list
ë²<i # Else-if the second input (A) is 2:
.i # Check if input `n` is in the filtered infinite list
ë # Else (second input (A) is 3):
› # Check for each value whether `n` is larger than it
Ï # Only keep the values at the truthy indices
# (hence the duplicate after the filter)
н # And only keep its first value
# (after which the result is output implicitly)
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~182~~ 173 bytes
```
def f(a,b,c,n):
u=i=l=0;v=b&2|1
while(i<n,l<n,l<=n)[a]:
u,v=v,[u+v,2*v-u+1,v+3][b];s=str(u)
if(s[0]==s[-1],[*s]==sorted(s),not'1'in s)[c]:l=u;i+=1
return(l,l==n)[a%2]
```
[Try it online!](https://tio.run/##XZBda8MgFIbv@ysOhS3anEJN7pKeXyJexHysQjBFo2Nk/e1ZTKEbu1Dk4X08r96/5ttky3Xt@gEG1qDGFi2vDhDI0EiXOpJ@L77FAT5vZuyZuVoc90WWy0ZtSQgYKaIMecTiFM8hFxjzUkmtak9@dizwLWUG5uVFEXl5Fgrlyafz5Oa@Y56jneZMZMaC57JV1UihNjltc10/B2fZiCPtI98KtQ6Tg70rbAJ71uY7TMA19qNn5Q70f9D@Bemhd2fszIYjW5oHwqLT1j54BUfsbUdZtpVPov0VBYIQyX3JS/o70AgtguXbFUeEl/0M8XX9AQ "Python 3 – Try It Online")
The skeleton was borrowed from Noodle9's Python answer, but I'm building the sequence of values in a different way.
Thanks to @xnor for saving me 9 bytes.
[Answer]
# [Bash](https://www.gnu.org/software/bash/) + GNU utilities, 277 bytes
```
b=(d*5*d4+dvd*-r4-dvd*-* 8*1+dvd*- d3/3*-)
c=('^(.)(.*\1)?$' ^`seq -s* 9`*$ -v\ 1)
f()(egrep -q ${c[$3]}<<<$5&&dc<<<"$5 ${b[$2]}d/p"||echo 1)
case $1 in
0)for((n=1;k<$4;n++,k+=!`f $* $n`+($n$2$3<102))){ :;};$[--n];;1)n=`f $* $4`;;2)for((n=$4+1;`f $* $n`;n++)){ :;}
esac
echo $n
```
[Try it online!](https://tio.run/##bVHbUsIwFHzvV6zMGXMpaUkpjppWx8tfAE6hCeo4Ey5leIF@O5aKIqPnISfZze5kT6aT6m0/m6/wgHePbS@KktrYeQDggD7@QY/E039EU658m0N5dOgB9Ah6Qn6Hzok/aJ9brY6iq9rgt7ipyq3xI6XnM44H@2nOrRxIm4Z2Y6VapartEtdSf0Gw/bgvlQjKnLMXHgkeyZEW98TwUlRuCVVJ3BSSoDYjaBHMuODudeUWUEvQthxSf1xnWUaDy0tbNpsODRp8OqRkXNt40dnt2pCNtJxUDqSbOEFPNMk497k2Hxmlxodh9yPML4oZSIJ8EXLylFA/071ECLHFrakNDZXyY2O08PnxZloYk3ybURpq82NxMD0qA1dNyqB9B/n9aUQCO6xXYCPPwLqsOVXOglVxN@4ifmWnedq5d@ffFpwTbT8sv0xAccz2nw "Bash – Try It Online")
Input is passed in the arguments, in the order A B C n. The values A, B, and C are 0-based.
Output is on stdout. For A=1, the output is 0 for truthy and 1 for falsey.
There is lots of spurious output on stderr, which is allowed under standard golfing rules, but if you want to try it out yourself, I recommend a command like:
`madlibs 0 2 1 5 2>/dev/null`
so that your output doesn't have stderr output included in it.
---
The TIO link shows all 27 combinations of A, B, and C, and all values of n from 1 to 6. (TIO times out if I use larger values for n, but I've tested more on my own computer.)
By the way, this script requires GNU utilities. In particular, it won't work on OS X (and probably other BSD systems), because `seq` is different there.
---
Some comments on the code:
`b` is an array of three dc scripts for testing whether a number is a Fibonacci number, a triangular number, or a multiple of 3, respectively. (Each dc script outputs 0 for true and 1 for false.)
`c` is an array of three regexes which match an input which starts and ends with the same digit, or is in sorted order, or doesn't have any 1s, respectively. The regex for being in sorted order is computed using `seq`, not given explicitly, because the code is shorter that way.
`f` is a function that tests to see if input $5 satisfies the requirements with B=$2 and C=$3. It prints 0 for true, and 1 for false. (This works by calling the appropriate dc script from `b` and matching against the appropriate regex from `c`.)
The case statement computes the desired answer by calling `f` as needed to test whether the appropriate numbers have the required properties.
] |
[Question]
[
Find a maximally profitable sequence of exchanges given an exchange rate table.
---
As an example consider the currencies **A**riary (your home currency), **B**aht, **C**edi, and **D**enar where the rate from one to another (after any transaction rate has been levied) is given by the (row, column) entry in the exchange rate table below:
```
TO
A B C D
A 0.9999 1.719828 4.509549 0.709929
F B 0.579942 0.9999 2.619738 0.409959
R
O C 0.219978 0.379962 0.9999 0.149985
M
D 1.39986 2.429757 6.409359 0.9999
```
Obviously exchanging **A** for **A** is not a great idea as this desk will happily charge you for doing nothing.
Less obviously, but true with this table, exchanging **A** for any other currency and then exchanging back again is a loss maker:
```
via B: 1.719828 × 0.579942 = 0.997400489976
via C: 4.509549 × 0.219978 = 0.992001569922
via D: 0.709929 × 1.39986 = 0.99380120994
```
However, exchanging **A** to **D** then **D** to **B** then **B** back to **A** *does* profit (given enough capital not to succumb to rounding):
```
0.709929 × 2.429757 × 0.579942 = 1.0003738278192194
```
One could repeatedly take this "free lunch" while the opportunity exists.
But an even more enticing chain exists here, namely **A** to **D** then **D** to **C** then **C** to **B** and finally **B** back to **A**:
```
0.709929 × 6.409359 × 0.379962 × 0.579942 = 1.0026612752037345
```
---
### Challenge Details
Given an exchange rate table in any reasonable format which fixes the meaning of the home-currency (e.g. 1st row and 1st column are always the home-currency)
(or given such a table and a home-currency index)
find a\* maximal arbitrage sequence of exchanges **starting and ending with the home currency** as indexes into the currency list **without repeating the use of any exchange** (i.e. a Y->X exchange may follow an X->Y one, but an X->Y may not follow an X->Y).
If no such profitable opportunity exists yield an empty list, or some other result not confusable with an identified opportunity.
- e.g. for the above example (**A->D,D->C,C->B,B->A**):
* using 0-indexing one might return `[[0,3],[3,2],[2,1],[1,0]]` or `[0,3,2,1,0]`
* using 1-indexing one might return `[[1,4],[4,3],[3,2],[2,1]]` or `[1,4,3,2,1]`
Other formats are fine so long as there is no ambiguity.
- One thing to watch out for is that it is possible for the best opportunity to be a single transaction from home->home (a foolish desk). If you decide to go with excluding the home currency index from both ends of the flat option above (i.e. `[3,2,1]` or `[4,3,2]`) and an empty list for "no opportunity" then make sure the home->home is not also an empty list.
\* If multiple equally profitable valid opportunities happen to exist, return any of them, some of them, or all of them.
[The Bellman-Ford algorithm](https://en.wikipedia.org/wiki/Bellman%E2%80%93Ford_algorithm) is one way to approach this, but probably not the best suited for golf.
### Test Cases
Inputs shown are in the arrangement used in the example, and the results shown use 0-indexing to list the to-currency-indices (when an opportunity exists the home currency is at the trailing end only; no opportunity is an empty list).
```
[[0.999900, 1.719828, 4.509549, 0.709929],
[0.579942, 0.999900, 2.619738, 0.409959],
[0.219978, 0.379962, 0.999900, 0.149985],
[1.399860, 2.429757, 6.409359, 0.999900]] -> [3, 2, 1, 0]
[[0.9999, 1.5645, 0.9048, 1.0929],
[0.6382, 0.9999, 0.5790, 0.6998],
[1.1051, 1.7269, 0.9999, 1.2087],
[0.9131, 1.4288, 0.8262, 0.9999]] -> [1, 2, 0]
[[0.9999, 1.4288, 0.8262, 0.9131],
[0.6998, 0.9999, 0.5790, 0.6382],
[1.2087, 1.7269, 0.9999, 1.1051],
[1.0929, 1.5645, 0.9048, 0.9999]] -> [1, 2, 3, 1, 0]
[[1.002662, 1.719828, 4.509549, 0.709929],
[0.579942, 0.999900, 2.619738, 0.409959],
[0.219978, 0.379962, 0.999900, 0.149985],
[1.399860, 2.429757, 6.409359, 0.999900]] -> [3, 2, 1, 0, 0]
[[1.002662, 1.719828, 4.509549, 0.709929],
[0.579942, 1.002604, 2.619738, 0.409959],
[0.219978, 0.379962, 1.003000, 0.149985],
[1.399860, 2.429757, 6.409359, 1.002244]] -> [3, 3, 2, 2, 1, 1, 0, 0]
[[0.9999, 1.4288, 0.8262, 0.9131],
[0.6998, 0.9999, 0.5790, 0.6382],
[1.2087, 1.7269, 1.0001, 1.1051],
[1.0929, 1.4974, 0.9048, 0.9999]] -> [1, 2, 2, 0]
[[0.9999, 1.3262, 0.7262, 0.9131],
[0.6998, 0.9999, 0.5490, 0.6382],
[1.2087, 1.7269, 0.9999, 1.2051],
[1.0929, 1.5645, 0.9048, 0.9999]] -> [3, 2, 3, 1, 0]
[[0.9999, 1.5645, 0.9048, 0.5790],
[0.6382, 0.9999, 0.5790, 0.3585],
[1.1051, 1.7269, 0.9999, 0.6391],
[1.7271, 2.6992, 1.5645, 0.9999]] -> [1, 2, 0] and/or [3, 2, 0]
[[0.9999, 1.2645, 0.7048, 0.3790],
[0.4382, 0.9999, 0.3790, 0.1585],
[1.0001, 1.5269, 1.0001, 0.4391],
[1.5271, 2.4992, 1.3645, 0.9999]] -> []
[[0.9999, 1.2645, 0.7048, 0.3790],
[0.4382, 0.9999, 0.3790, 0.1585],
[0.9999, 1.5269, 1.4190, 0.4391],
[1.5271, 2.4992, 1.3645, 0.9999]] -> [2, 2, 0]
```
---
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest solution in bytes wins, but competition should be made intra-language too, so don't let code-golfing languages put you off submitting in your favourite one!
[Answer]
# JavaScript (ES6), ~~122~~ ~~113~~ 103 bytes
Takes input as a transposed matrix with respect to the format described in the challenge. Returns a string describing the exchanges in `(from,to)` format.
```
a=>(g=(s,x=b=0,h='')=>a.map((r,y)=>~h.search(k=`(${x},${y})`)||g(s*r[x],y,h+k),x|s<b||(b=s,p=h)))(1)&&p
```
First test case: [Try it online!](https://tio.run/##TY7RboMwDEXf9xV5qNpk81ISEoKlpT9SITVQClu7gsg0gUr36yxFQqpfbOvec@0v9@t80X22P@/X5lhOJzs5u6OVpR56m9sIarvZMLtz/Nu1lHYwhOWv5r50XVHTsz3Q1a2/w@o23NmBjWNF/Wu37zMYoH47M@hH/5GPI82th9bWjDEq2HrdTkVz9c2l5Jemoie6fyFkTyKOoSB0bRCVfExSIJoUiOAxYpqQDGar4EZgKlN4guIAJQGSXEk02ixexXWEWuFDSQSa@IlKuIow1rh4I24iRDnnBQX1PAkVbuuFIhnJGCPbbfDHITQ8FySSTf8)
More test cases: [Try it online!](https://tio.run/##rZTdTsIwFIDveYpeGG211v63J7G@CFniQGT@QpgxEKevju0GDM0Qie5mbXpOz/dtPb3PX/NyOLubvpw/T25Gy9uwzMMVHgdc0nkYBE6LcHJCwlXOnvIpxjO6iJOPgpWjfDYs8EO4xkdv83d69LZ4J9ekqsa4PJ315xld0OLsgdB5VV4OqgoPQkmnoSCEYEGOj6fL4eS5nDyO2ONkjG9xv4dQH3EG8aHxbZWXFAkmuBFpDkIJlNE6SjBjtaGbaMGctPVbS@/XUXGVa5@ijAO6tbWXVrZbcZBNQQCftpDcu3U0ylBGCLq4SJEURSCOsl5vD/mXjZoCbblE2EWejFryhNhBnoS29OIn6fxUneSKpsFO/sjJpd1UBV2PpABwtY2KVrbVcAK89NtsKialdBkVwRm3jtXMcDAa0ooV4NRWlmWagzLQOjkOq/8RV8DUI6FjbdNlpmqzpPX/Zk0a14e6pTx1qFpdTGr9Ta7xaxT3WP71/Glwesf5S3Bc/PX8/UfzqBXWz83j1vD6gOaRO@DVb5pn17WVCN3ea0sma7nn2vouuVpUpukMq@AH/Ai@/AQ)
### Commented
```
a => ( // given the exchange rate matrix a[][]
g = ( // g = recursive function taking:
s, // s = current amount of money
x = b = 0, // x = ID of current currency, b = best result so far
h = '' // h = exchange history, as a string
) => //
a.map((r, y) => // for each row at position y in a[]:
~h.search( // if we can't find in h ...
k = `(${x},${y})` // ... the exchange key k from currency x to currency y
) || // then:
g( // do a recursive call to g() with:
s * r[x], // s = new amount obtained by applying the exchange rate
y, // x = y
h + k // h = h + k
), // end of recursive call
x | s < b || // if x is our home currency and s is greater than or equal to b
(b = s, p = h) // then set b to s and set p to h
) // end of map()
)(1) // initial call to g() with s = 1
&& p // return p
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~143~~ ~~125~~ 124 bytes
```
lambda M:g(M)[1]
g=lambda M,s=[],p=1,x=0:max([(p,s)]*-~-x+[g(M,s+[(x,y)],p*M[x][y],y)for y in range(len(M))if(x,y)not in s])
```
[Try it online!](https://tio.run/##bZFLboMwEIb3nMJLSBzLNn5NJI7ACVwvqJqkkRKCQhaw6dXp2IIg1LLxPP5/5hvRja/vRyunc/Ux3Zr751dD6uMlrwsvQnaplhLtKx9oVwk6VPx4b4bc5x3ti7A7/ByGvUcH7fc@H@hYoG5X@yH4MWB2fjzJSK4teTbt5ZTfTi0OL67nJG0fr9jqQzHVlfecAX6cUyKYFeCko0QxzUEroIQzywEkBJoRlGoLoGQsLybJjABbulhTKNWLVAoAm8olmszGxJlQAE4nqWAlxibNUhKstpSYOKvUsJpCyOoVN8Jqo3Tqc@VizldMU7r3vvgidtpqcNG8U3At0snSwCoVTHJn5ykgyiRR0qU7nFyvSDhbnnJu20WG9oUH92541MyDnDNP3Ps/jxazJB749/A3T/e8ti9yxj@9hpsYk2z6BQ "Python 2 – Try It Online")
Uses 0-based indexing (0 is the home currency); returns a list of tuples of the exchanges yielding the max payout.
The approach is brute force: via the recursion, we end up visiting every non-edge-repeating path starting at `0` (for `n` being the number of currencies, this gives a maximum *depth* of `n^2`). For the subset of these paths also ending with '0', we maximize the payoff.
[Answer]
# Haskell, 175 bytes
```
e?l|e`elem`l=0|2>1=1
w[]=[]
w l=[maximum l];0!q=[q]
n!c@(v,i,(h,l))=do{j<-[0..3];c:((n-1)!(v*l!!i!!j*(i,j)?h,j,((i,j):h,l)))}
z l=w$filter(\(v,e,_)->v>1&&e==0)$12!(1,0,([],l))
```
[Try it here](https://repl.it/repls/NanoRoastedTechnology)
] |
[Question]
[
Given a sequence of 625 32-bit unsigned integers (that is, in the range `[0, 2**32)`), output which of the following pseudorandom number generators generated the sequence:
1. [Linear Congruential Generator](https://en.wikipedia.org/wiki/Linear_congruential_generator)
2. [Xorshift](https://en.wikipedia.org/wiki/Xorshift)
3. [Mersenne Twister](https://en.wikipedia.org/wiki/Mersenne_Twister)
Specifically, the C implementations of these three generators used for this challenge are as follows:
```
#include <stdint.h>
/* all code adapted from the sample implementations on the following Wikipedia pages:
https://en.wikipedia.org/wiki/Linear_congruential_generator
https://en.wikipedia.org/wiki/Xorshift
https://en.wikipedia.org/wiki/Mersenne_Twister
*/
uint32_t lcg_seed;
uint32_t xor_x, xor_y, xor_z, xor_w;
void lcg_srand(uint32_t seed) {
lcg_seed = seed;
}
uint32_t lcg(void) {
lcg_seed = ((uint64_t) lcg_seed * 1103515245 + 12345) & ( (uint64_t) 0xFFFFFFFF );
return (uint32_t) lcg_seed;
}
void xorshift128_srand(uint32_t x, uint32_t y, uint32_t z, uint32_t w) {
xor_x = x;
xor_y = y;
xor_z = z;
xor_w = w;
}
uint32_t xorshift128(void) {
uint32_t t = xor_x;
t ^= t << 11;
t ^= t >> 8;
xor_x = xor_y; xor_y = xor_z; xor_z = xor_w;
xor_w ^= xor_w >> 19;
xor_w ^= t;
return xor_w;
}
enum {
// Assumes W = 32 (omitting this)
N = 624,
M = 397,
R = 31,
A = 0x9908B0DF,
F = 1812433253,
U = 11,
// Assumes D = 0xFFFFFFFF (omitting this)
S = 7,
B = 0x9D2C5680,
T = 15,
C = 0xEFC60000,
L = 18,
MASK_LOWER = (1ull << R) - 1,
MASK_UPPER = (1ull << R)
};
static uint32_t mt[N];
static uint16_t index;
// Re-init with a given seed
void mt_Initialize(const uint32_t seed) {
uint32_t i;
mt[0] = seed;
for ( i = 1; i < N; i++ ) {
mt[i] = (F * (mt[i - 1] ^ (mt[i - 1] >> 30)) + i);
}
index = N;
}
static void mt_Twist() {
uint32_t i, x, xA;
for ( i = 0; i < N; i++ ) {
x = (mt[i] & MASK_UPPER) + (mt[(i + 1) % N] & MASK_LOWER);
xA = x >> 1;
if ( x & 0x1 )
xA ^= A;
mt[i] = mt[(i + M) % N] ^ xA;
}
index = 0;
}
// Obtain a 32-bit random number
uint32_t mt_ExtractU32() {
uint32_t y;
int i = index;
if ( index >= N ) {
mt_Twist();
i = index;
}
y = mt[i];
index = i + 1;
y ^= (mt[i] >> U);
y ^= (y << S) & B;
y ^= (y << T) & C;
y ^= (y >> L);
return y;
}
```
## Rules
* Input and output may be in any unambiguous, consistent format. If you're not sure if a format would be allowed, feel free to ask.
* All inputs are guaranteed to match exactly one PRNG's output (there will never be a case where an input sequence matches none or more than one PRNG's output).
## Test Cases
Due to post length limits, only 3 test cases are included. A larger list of test cases can be found [here](https://gist.github.com/Mego/106abfd5cddb8946ef34bff666d22eda). Note that the values are provided in hexadecimal.
```
[CEE63876, DE7E2E77, 54EC3AE4, 92DEBB4D, D0756602, EE9D3B13, 04A42150, 0FE8BF49, 2BD7E04E, BB96756F, B9B2027C, B5750705, 9DD5B35A, E23EF98B, D15ACA68, C1C40E81, 35ABAB26, 2DA1A367, 36462514, 3CA211BD, E79753B2, A49B0F03, B3EA7E80, 64630CB9, BC22F8FE, D535985F, 14B902AC, EE9EBB75, A831A70A, 79C55B7B, F7099D98, 98AC99F1, D9CB29D6, 53C43457, 04C6FB44, 43DFE42D, 05A80D62, D86DBEF3, F9DA87B0, 99839629, 017D9DAE, 0B1B574F, A5586EDC, F2966BE5, B709E6BA, A160196B, D16B9CC8, FF46E161, 3BDFB486, 4CE4E147, BE01BD74, 6A2F329D, 99F29312, C7044AE3, 9A373CE0, 73515B99, 94E2CE5E, FA26B23F, 2883470C, 3ED31855, 7809726A, 64DE335B, 79A3C7F8, 5379E4D1, B9444B36, 92C2AA37, 6A496BA4, 84E6FD0D, FC81E4C2, 470DB2D3, 4F839E10, 45935D09, C40D8B0E, B4F6A92F, FDEC8B3C, 1C8BC0C5, D99B4A1A, E1CEA94B, 17951F28, BAECA441, 3C13EDE6, 0CDC8F27, 4CB105D4, ED1E437D, 1E210272, B8F8F6C3, FB02AB40, 63D09A79, 4178D3BE, B3EA3C1F, 58073B6C, 10B76535, BAEA6DCA, 37807B3B, 11E2A258, 93061FB1, EB299C96, 00719017, 130B8C04, EFAC05ED, 385AEC22, F6F516B3, D4B76470, 915013E9, D45FA86E, C5206B0F, 6C06579C, 4C0D05A5, 9BE1DD7A, 7702A92B, 3DEF5188, E0ED5721, DA205746, 0080AD07, 05EBFE34, 3D27445D, 7D7AA1D2, 44F112A3, 9B64C9A0, 7118C959, 08BD091E, FC7835FF, A1DCDFCC, 1B03A215, 4D2C992A, 9324331B, 0FDE2CB8, C1894A91, B9531DF6, DDC8E5F7, 38A55C64, 59E6FECD, C88B2382, 409BEA93, C48DDAD0, F5F1BAC9, DF4BF5CE, A3909CEF, C43DD3FC, 55D23A85, A035A0DA, 5074190B, CA9233E8, D980FA01, 85DCF0A6, 96C93AE7, B94AA694, 0E02353D, 4D577132, D1649E83, AC759800, D261E839, 7D876E7E, 29C89FDF, 309C342C, D06FCEF5, 1727F48A, 35415AFB, AFAE6718, C53B6571, 3998CF56, 47C0ABD7, C0AEDCC4, D54FE7AD, 486A8AE2, 187A2E73, C61F0130, E8B051A9, DDAA732E, 143F3ECF, 072B005C, CA935F65, 94EE943A, 799AF8EB, 2F95C648, 88DF8CE1, 7B21BA06, 1AAE38C7, E264FEF4, 4F67161D, AF0F7092, 60CB9A63, CB4D1660, BAE3F719, 7EB003DE, EDD379BF, 5ADD388C, 5FB3EBD5, 0D347FEA, F74FF2DB, 196B5178, 00547051, 4DD2B0B6, 3750E1B7, 3CC00D24, AF9EC08D, DF512242, 0F07E253, EC82D790, DAC3D889, 1453208E, 372450AF, 6165DCBC, F7087445, 3464B79A, 19EF48CB, CB1208A8, 4F410FC1, C1C6B366, B327A6A7, A8D30754, 2D0DE6FD, 4FFA9FF2, 919E0643, 010344C0, 59D6F5F9, 370EC93E, 5690C39F, A337ECEC, B387F8B5, 2FAA3B4A, CEC7FABB, 612CEBD8, 510C6B31, A3D8C216, 81718797, EA70ED84, 728B896D, 4096E9A2, 50BD0633, B6D15DF0, 39644F69, 141DFDEE, 8837D28F, 2B86691C, E3E97925, 44F00AFA, 74E908AB, E71EFB08, 08DD82A1, 2DA3DCC6, 632D8487, E02CBFB4, 0EAEA7DD, 6970FF52, 9E53E223, C2B02320, DA72E4D9, 1D7BBE9E, CDF87D7F, B844514C, 72A3F595, 8AE126AA, CD21729B, 870B3638, 119B5611, B5830376, D71A9D77, B3597DE4, E3CE424D, AB93E102, A6119A13, 10229450, 6DC9B649, B9E30B4E, DF71C46F, EA24A57C, 55EE6E05, 98E88E5A, EA00388B, B9D49D68, 0DECE581, 5E913626, 09B7D267, 080A2814, 980158BD, C0CA8EB2, 5D652E03, F16BB180, 63EFC3B9, F4CEE3FE, 1A02A75F, 749A65AC, FFBFE275, 3731420A, 1FD45A7B, 771E3098, 183930F1, C8A974D6, C5442357, 2D11BE44, 051EEB2D, EBA00862, 737D9DF3, 4F8E7AB0, DD2C0D29, 2E7A48AE, 70CA264F, 4DD891DC, CDCF52E5, 0EA641BA, F4ACD86B, 654AEFC8, 32A73861, C066BF86, 61BE9047, 4C034074, A8BDF99D, A75F4E12, 4149E9E3, DA4DEFE0, 19859299, CBE0395E, 5CA7413F, DED22A0C, 7993BF55, 58F28D6A, 1058B25B, 097DDAF8, B71DFBD1, EF241636, B4E61937, 9931AEA4, 1435840D, 58135FC2, B97911D3, 382D1110, E8C35409, E6BBB60E, CC38F82F, 333A2E3C, 884427C5, 9081251A, 2C66E84B, F799F228, C7447B41, 8AFC78E6, 0239BE27, 83B008D4, 5C9C8A7D, FA873D72, 587A15C3, 366EDE40, 1A6C5179, FD87BEBE, 13DE4B1F, 29839E6C, BAD78C35, 207D08CA, 04267A3B, 02423558, BC81B6B1, 06CAE796, EAF87F17, E5514F04, 8ACA0CED, D445E722, 147BF5B3, F9165770, EDC78AE9, A37F536E, DDB63A0F, A2E17A9C, 7E04ECA5, 14D1387A, 44A6682B, 6AD9A488, 97FCAE21, C22A6246, 5E215C07, 32A88134, 0B550B5D, 239A5CD2, 4D6DB1A3, 2AE67CA0, 81DC0059, 309D741E, 199FC4FF, B346C2CC, 5A434915, CA28B42A, 7CB5B21B, 11833FB8, 729C6191, B975E8F6, 887354F7, AB089F64, 1E9485CD, CF8F9E82, BCFE4993, 2D624DD0, 4570B1C9, 719D20CE, ED39EBEF, D16676FC, 63C9A185, 9DEE7BDA, 0CE3580B, A52206E8, ED07D101, 35C87BA6, C46D69E7, 8884A994, 489F7C3D, 17F0AC32, 669CBD83, 48CCCB00, 670C9F39, 57F9597E, A3E3AEDF, 06B3972C, AA8EF5F5, 9E4D8F8A, 177E59FB, D358FA18, 9FA5FC71, 7CFD1A56, 8A4E9AD7, 2FEF9FC4, C14CEEAD, 454885E2, 87780D73, DC28F430, 44F6C8A9, A9ED1E2E, 9EBC0DCF, 1F61235C, AA4A4665, 3A30EF3A, 7095B7EB, 788B1948, 8A9DE3E1, 81AEC506, 6015E7C7, 60DC81F4, E433DD1D, 58E22B92, 867F3963, 8D39C960, DD362E19, B2736EDE, 44A208BF, DA621B8C, BA7292D5, F1439AEA, 8DF871DB, CFDB6478, 85D68751, 93387BB6, C98250B7, 659E5024, A0AB478D, BCC89D42, E4614153, 78824A90, 3D91CF89, F1474B8E, F2349FAF, 19697FBC, 7E3EDB45, 03F0929A, 773587CB, A32CDBA8, B0F6E6C1, 0DB53E66, 3812D5A7, 43480A54, E9CA2DFD, F3C6DAF2, 2B8D2543, 614577C0, F390ACF9, CAE3B43E, E9D2D29F, 10EA4FEC, 54A61FB5, 2362D64A, B59BF9BB, 7B227ED8, E3660231, 0A000D16, FB067697, E9ACB084, 2667906D, 4967E4A2, E031E533, E18650F0, 7C79C669, 3883A8EE, 439BA18F, 78178C1C, C85F6025, 218565FA, 443AC7AB, CF1F4E08, 1C4AD9A1, 0DB3E7C6, 2F5C3387, 635F42B4, A11A6EDD, 81F6BA52, 703E8123, 9A07D620, B5541BD9, 7822299E, DD6E0C7F, B8E4344C, FFE19C95, A10341AA, 7FE0F19B, 35464938, F28C6D11, BB2BCE76, AFD30C77, 05B2C0E4, F839C94D, 8A7E5C02, 2361F913, 624D0750, 4AE6AD49, BC7A364E, 4AE9136F, 2003487C, 2D63D505, C547695A, 171D778B, 927A7068, 04D1BC81, 8182C126, 04EA0167, A0BA2B14, 8DDC9FBD, 28C9C9B2, 0B0B4D03, 7898E480, 29B87AB9, DD06CEFE, C56BB65F, 0CE7C8AC, FEDD0975, E27CDD0A, FA3F597B, 4A5EC398, 6981C7F1, 4C93BFD6, 54E01257, AF488144, F7D9F22D, AB640362, F2697CF3, B1EE6DB0, EE108429, 0602F3AE, 1C14F54F, 21C4B4DC, 0E0439E5, 2D8E9CBA, 4B55976B, 6F5642C8, 1EC38F61, 34F9CA86, 53B43F47, 86F0C374, 6FC8C09D, 99980912, 4E6B88E3, AA10A2E0, 53F5C999, 6869A45E, A3C3D03F, 738D0D0C, 50506655, 6C27A86A, 4E2F315B, F283EDF8, 7A7E12D1, 300FE136, 33258837, 8805F1A4, 43000B0D, 6370DAC2, 2DC070D3, F3828410, A72F4B09, E9F5E10E, 2717472F, B9F3D13C, 86F88EC5, A4B3001A, 585B274B, D3CAC528, 9A585241, BFF103E6, 92B2ED27, 4D9B0BD4, 4296D17D, 11B97872, 28D734C3, 47871140, 33440879, D522A9BE, D66E5A1F, 7F6C016C, AEF3B335, CE5BA3CA, C128793B, 51CDC858, D3B94DB1, A3783296, 6F9B6E17, DD831204, 336413ED, F5FCE222, 51DED4B3, B6214A70, B37B01E9, 892AFE6E, 37E8090F, 51289D9C, 70F8D3A5, 810C937A, D1A6272B, 19EFF788, 23C80521, 86406D46] -> LCG
[7D17504D, 9FED269B, 939C3D03, C8FCFA6C, 0FAE4E06, F9816896, 8B872680, A4878206, D92436EE, 2B133084, 9912A040, 011D96D6, F976435D, 4B53DBE7, 474F626D, AA09E774, E12E35C3, 347746E2, 0817160B, EDC0623A, 7DD0D26C, F31ECB62, 43093C44, AD3657AD, 568EB3D5, 53CE27BD, 592FDA9C, 46BB652B, 65886632, 475956F1, 60859FBC, FD8A3CBA, DB156CCF, 56764782, 1A424A8F, B681CA91, C682BB9A, 222CBE9F, 2A329E67, 925F0CF2, 41D22B48, 064DBDAB, B832DAA3, D26069CB, 023890A4, 69F3D5AD, 473AFDF2, 96C5EAEF, 50BEF523, A7171C24, 3752B059, 8E79B6CE, 29C95DCF, 362092EE, 94523C0B, D7DE2789, B49A3F98, 861F7C07, 83A8BAAB, A56C2738, C06FAAF2, BDED09BC, 7B568148, BFC73CFD, 024229CD, D73760D0, 18A4E7BF, 9E021082, 8D1D4ECE, E1408E5D, DEE614D5, 50EE898B, 37E2D666, D23584A1, 3C9B628E, 181D1647, 396DA2C4, 470339C4, A06BACB8, 503439DC, 041BCA9C, 5A881EC2, A77B7747, 567040AD, 8CE52FD5, 96814E85, EA3CD25D, 3E9D929F, 9BA3891E, 07CA0989, 0B689D17, D9B3FF8F, 5EDF76DE, 090EBACD, 46C11EDE, 00C8DE0E, A504314F, D9A02FF0, 97D9EDF4, D1A769AF, 55ADB49D, 8DAACE77, D544247B, 3F44C56D, 07759744, DC7738AB, 28E4B8A2, 31927F7E, 9AF601BF, FF21C02A, F20D56C4, 50C6AE74, 7A17A62A, 8BC619D2, 13E5C518, 76357C1E, B1D4A204, 0A673565, 3797FC34, EA9FA354, FE4FF881, CDB03630, 454E05EE, 52DC8B10, D3D6FA3A, 9F9B57C6, AACF50AE, 1CFDCAEC, 789EE463, 3DFEA9D1, ED64C4E0, 1F3CD90A, 900E9B72, 58761883, 93FE94A9, 6AF3FB55, 8EC22872, 66988B29, 01A4008F, F4787ABD, 6B665DF8, C905527E, E88493A9, DF1EB196, 86CEBE10, 65BB9A15, A96E54D0, 83D6D26A, 701BC23E, C9C9951A, 12DA9027, 27AA5594, 890E696D, 0CEA5C13, CA77AE01, BF04442E, 45BB17A2, 1BEFD1C2, 6C9F7318, F1276F91, 6CBC7010, 09B8DD84, 9E286818, 54B9C7AB, DB0A01DC, 1491B3C4, C92471E6, 533A73F6, D8B59CAC, 41231BED, AB62F96E, 2B478A37, 5F63230F, 06C6A77D, BAD38742, ADD2B41D, EBEF81F3, D8212EBC, FEEE4B6D, C6A47AF1, 51D39BCF, 80560B87, 0C6F8DC3, E9F90D4D, 2439FE5E, 1403C36D, 647255BB, 45C0AF1D, AEE062F5, A4F2C4EF, 52DB8247, 12237746, BF79483D, 8D9E3681, 03D954CF, 0A498AB5, 7F041361, 0352083E, CAE45BB7, 8CBE7C7C, D37EE991, 40FE1838, A82FCA73, D70D1E96, F31B5787, 4394AE04, 953E8857, 2A78CDC8, 03F6006F, E5F46A9B, 84E93A42, 6813B19A, DB55318F, 9DB338CC, 50453A12, A52FCEE1, D7844A82, D3F57DE6, AA195820, 719AD344, 84BF57AF, FCDD1093, 9C658F70, 3BC26F4B, 45BE45B3, 51F39C1F, E15D875E, C9CD1409, 7EE9435E, B3373BF8, BE5D3DB7, 1F911B29, 2B565836, 21B44E5F, 76537F5B, E18C6AEB, 78820904, FBC776FD, 16836779, 94DA8C70, FC787DC6, 3CC88C2A, 317D9C65, 71842F36, 4E2DFA8D, 36FC86BE, EBBFAAB0, BB12D56E, 9ACAA913, 48D10582, 5E2DCC02, 73B9DB0C, BCF46659, 7CC99950, 4CB40717, F168D436, EEB1A2EC, DE82A573, 32E28D0B, 859C2605, E6595298, 2D3BDA1D, 0B978064, 6F5F231D, 43BE71FC, B0A6A0A4, 07858274, 91540E52, 21D5BC15, A4F39B0B, 8F4E3BC3, BE5992E6, 32E0A42C, 0AF34AB8, F49DF806, 86218AD1, B1D79FFD, 21E1A5F5, 3AA73407, B05A4680, BD7F0F01, 919DDB56, 9299C26E, F095F8FB, B5D7E6EF, CAEFDC68, 9639FDE9, C9349DF5, C3DEFAA2, 7766722D, 2EE91F9D, 435FF480, 77601DA3, 33D3FE78, 55A01A68, E9E71FA8, 9E1D8A32, 329187B7, 67B7A8D7, B67CE1D6, C442A131, 7A502A31, A07BC4BC, F158F334, 20C28F07, DB38288C, A5184973, 93EFCFB7, A761D07A, BD07F052, DA336550, 374C9BD6, 9E077F45, 1C0089B7, 5D587682, 0E99C4D4, ABC16F15, B39406EB, 2DE69A7D, ED994471, 4D802710, 5E30D315, 471C9FDC, 6081E182, 2C75F225, F40524C5, 5744A7E6, 38A6D17D, BBC1E896, 663FD027, 14363091, 1A152653, AE24F8DF, 3602BBD4, 9315B73D, 20813CB2, A9EADA7D, 8A15088F, B487EAAF, 9DCA3421, 620C2CD7, 407F0169, CB26495B, 07810722, 04E8F991, BC24C42C, 45B12E62, 4A0689E1, 0961D541, 93FE75E5, 5FF09BC6, 21C75858, 260B4AFC, 463A4285, 9DCFCF2F, 86D14156, FAF1A7DA, 6E4BFC6B, 8D1EF03A, 81C9CB3E, F67163AA, C7E871AB, BD0DD64C, 72526AE8, 0F433B3B, 8BA27651, 58CE6EDF, B92A4A04, AFA624F9, 372EDFA2, 1CBDF70E, F72CE4F7, 69339707, 28A1864C, DB5701D1, 4BCC4D10, BEB260C1, 9A0502BD, F93FC1A5, D0B2B75F, FD2B71E0, 4F899412, 48BC46AF, 0DF108A8, ABF3DC87, A8D9E4EF, 02FA4665, 87CBBADA, B2E95940, D5702D6E, 056990CB, DFAEE7D6, 2775863A, 733AC4E7, 3A9CED83, 92A42D51, 196B2D69, BCD3CF5F, 61FEDDB3, D283BA78, 92C3C524, B0484914, 27CC09EB, E8532710, 643535DB, 96C7D0A0, D10310C2, A019C655, 6D4FA460, C5A53BB9, 0CE9A6CF, 62ACE269, 72D026F8, 9E44A3E8, DFDAB131, DA60BF09, 2974A55B, 9294187E, 98CD6024, 478A1CC3, CB583714, F93D91E9, 0A0202AA, 1D796B2D, 17931F01, 023476C3, 1839337D, CECF1354, 412B769B, E0089213, 317BF7B4, 8798177C, 9D1D36BA, 3921B700, D70921C7, 906DEFAD, E4B1B3FC, D01C81DD, 4E858500, B16A1BFA, D82D7078, EC0B10C9, 8EC425CD, 6F904A24, DC8D591E, 68B4971E, C7F13D88, 2ADD8E38, 9C2E67D4, 50EE1F28, 1EBD75C0, D8D79461, 37285868, 171F16FA, E2F972AC, 86E9860E, F37765A3, 1C3015F1, 357568C9, FF66419F, B77479AD, 2B776D2F, B5DA7BA8, 787DBE35, 6CD01986, FC5E1F26, 9A3F3C3E, 0F26B55A, E3D68111, EF7D1562, 8CC01A7F, B676E2D8, E1FF230E, E62EEC56, 6AB1010E, 6BD04EA2, 732FF785, E2F2E9EA, 00A93DCB, E9E5C622, E57A9744, 90B28FB8, D9BCBF00, 1EAFA6C3, 2F5ED2E5, 2B9557F9, 17EDA934, 74178CB4, AD07B129, 2CAC11EF, 5672B947, 9EC8ED11, 0ED68918, 42B9C244, 81C2F3D5, 58BB2699, E29FFADF, 6EB8AF2A, F872A573, 797CDB0A, 64289FF8, CF42ADA8, A276D00E, 3D4DEBC1, 1DBA64CF, C74FA53D, D3ADEB7A, 81EC012D, 4FBE91C3, F562B344, 492860A9, A82CE5C8, 13A74987, F3BF2024, F9983BD2, 3655838C, 1F971FB0, 1523A266, 2D5D4DBB, B78EE27F, 104301A1, 187BA15D, DF8C077C, 1FD19BE8, 1797DFBA, D223E55C, 6D2BAF83, FEB67715, 57750D76, 9AB10BC1, AAD6F8A3, E7953C33, 1874830A, 0A896CC6, 17879ED4, 59BD4CB3, E56DF85D, A4C3576A, 8F990C18, 3CF2118C, B6D7A95F, 0811C0E8, 4FAFF43E, E37DF236, E8EB2257, 6E7BA922, 5E45AED7, 52A50B6B, E3ED62F2, 506CF514, 232CDAD8, 59A87385, D1DA70B0, E629FBCA, A39607CD, B9B87C61, BBE5C416, 12BB8F0B, 01004AFE, 7B2165CB, EE71DBCD, 207CD2DF, 23283B94, 53570D07, 33981B13, F5B4DD95, 9722AC2C, 7CF6B4FA, 8F4578F4, DC4E44FC, 5E8FD095, 9717EEDA, 3331A614, 9DF66D2A, BDDD0D79, 95944526, 2B2B5086, 059AF7F4, 507984FB, 67F346A7, 162D85BF, C4DAF5D9, 5818EFE5, A5235C3F, DF593559, CC3E6756, 53C6DEF3, ECBBB210, FA5EA123, C5656DE9, A03102F0, 912B0FD4, 9E73F36B, 7097CF69, 58996509, 91059461, 90ECC581, 5ECEBC72, CDEC2B8F, 70F708CF, 86C10B9D, ADC71A1B, 01DBEC7F, C9A22DFB, 47B14AB1, D233979E, 0C5521B3, D4401837, 196924CC, 57A8CF18, F25524E7, 26001B3A, 761F1472, 67DEC5A6, 3CF7A7A6, 1A08B2C9, 943A897E, 05589DAA, 8413C030, DBD2B481, 9BE3A7FC, 5A97CCE7, 409F95C5, 0EA757EB, 88FDCD84] -> Xorshift
[4BB6DADF, 8EEF8EA3, 06E8FD49, 88A2AF49, E3269CD4, ECA4F09A, 3ADC8EFB, AA4DD059, AC3B1AAE, DA22C244, B67C2EC6, DFD9C12F, B4A6DBAF, 354C372C, 2C6CA407, 0AC93693, 725C7716, B439DF25, 7C04626F, 67824F17, 21EE364D, 77D8D72F, 4BF90371, 7BC3C716, 472A4204, B842AEFE, 38270462, 3B17B189, 22760085, 2A801D85, 8DE334B5, A72580F7, F187AA9B, 2E04DC0C, 8A701C0D, 471B61E6, 98F859D9, 9EBC2F45, 02544E96, C2785B15, 20623FAB, 8001F9B4, 0E438545, CFA2A2A5, 9DA35720, BAA84901, 908758C8, FCF5557F, F905B3B4, BE7DEBCD, FED08B1E, 7E9472CB, AC3A29C1, 5BED194F, B6932F25, 1C95E32D, 67E94371, D7CCB4CE, DF296D87, 6AAEF0F6, 8CFFF867, 093F9F79, FB280F6C, DE7735A8, 684C17B5, A0DA757E, 374EC162, 1764A62D, 82C244F6, 9E4583C7, 56F02388, 0018E400, 815A0F1E, FD80C932, 30EDD175, D37AF8D8, 7C8E4633, 7D8E4E5D, 660A7F79, 4C2C08BD, B6656A5B, CCFD6607, B0AA17FA, 060EE305, DEE9752F, B38BE439, F04EB964, D4E6C330, DCD4F7AB, DF7D83BF, 309047C6, 51FFC819, 9E59C7D6, 46821973, 01B47792, F800809B, 6050BB64, C13CB495, A305F788, 7AD27279, B7F9151F, 9F154C4F, D3F688F1, FF830866, A9C059A3, FFBF160E, EA8D827A, 1F1DA6E8, FDC52EFC, 5325CE11, 765B86EB, A852DC5C, 74ADAF62, 45BFACA5, 8E1FF6C3, 83ADCF0A, 91D6626E, 316008CC, 0DAD4110, C28EA37D, 5F077B03, AF70C5E3, 13A7C50C, 0A737B9D, E236FCBB, DDADB0C5, F4CAA3C8, 73679470, 87AE2E8E, EAA6ADA4, F30CCA79, 2B2FED65, 9B55A25D, 7317A6DB, D505929C, 0F90C693, 5CED397C, C1CB0AB9, C81895F1, 828D68BF, C2D0D855, 70585D86, 1ACD41B1, D8227B76, 1CB6DD69, B71EF185, 3EB11656, 6674378A, BA543682, 895A464E, B9E6CC48, FDAB6657, AB815F3B, A717AF55, 5826ABAB, 7CAF7DA1, 33EB26C0, 9367A48F, 32334888, 6BD35F76, 21F56A13, B7E72B51, 2B110FC2, A7A6ED6F, 1B2E72D1, 855EC1F3, A320F92E, 05609603, 5AA26082, 937BB417, F7A082EF, 370690A8, 074B4C00, EFB2EF14, A449B9F8, 9AA7E8A8, 3AEC4108, E5DDDB2A, C2CC4D30, 8589EB3D, 030ED83E, 4230E9B3, 619B03C0, E2B2BB64, 839A7C40, 2527B162, D03987D6, F8D66424, B950968F, F41E4D21, 9BAEEC89, DB8C65CD, D19F0371, 42507672, F133D6DC, 8FF10301, 6267E094, 339A1D5D, 3DD9DDE3, 139AA839, 440F8A94, 5E10CEAF, 60A1BA78, 02576968, 9AE7D81E, B9BF647E, F1698EC1, 5EC4890B, 88CF1A87, 9F3442AD, 4ED7DB9A, 08BD20C4, DA4B2F8E, 7EE018A9, 41968817, 519BE32C, 26CC3EFD, 1C3CBCBB, 551FC090, D06676D9, 02BF4E3F, 5B331917, AA121020, 840B84DD, 1C04DB26, 42DC049A, 58E92781, 95DA8984, CEDFF185, 149A43E5, 9B4CAAE7, 9E61CFFC, C33F9485, 2ABFE975, 75F8E915, 167D7A60, 1086ABF9, FE0B87DC, 095EFA20, 79FC720C, 99DB743E, 8F4B2F19, 00A9188A, B5DE7C2D, DAF3734B, CCAD1F47, 0C9DB549, 0158D55C, BCD5F151, 72A210D9, ABB80C09, 99934B39, F92DF281, A35193BD, C3CB4E8B, 322DBEE4, 26E2E30D, 36F25EDD, F1C8C5DC, 44B5C836, 878075ED, 1140849C, DEBA2848, 6B8D4AD7, 0209883A, AEFFDC8B, F7862944, F2CAE4AB, 77A1EB21, C77D6350, 4749AA23, 1ECDFD3C, 55D6943C, FC9B102A, 80363E80, C28E5369, 7E4BDC16, 8DDD321E, 46E4B844, 71169596, 6EC788CA, 508E25D4, A3249379, C5493848, 67ECFFDB, F6B03518, D4FE2A7D, D6C8D739, 7A93EC17, 84E2A797, 08CB6F22, D09D5BFF, 7FF783FD, 749A4AA7, 9EE69739, 01BB87ED, CDB15087, 32FE625F, 3C8E72C6, 2386A26E, 0F243847, F9E50890, D10F1EC5, 6E1C032D, CE27B59B, 84F2447B, 62AFD23B, 2361B77C, 1532E2F5, BC65F691, D8106771, BC9F8553, 94B67790, CE7F4B32, E36DAA85, D42336C1, 414ABF42, F5D5E7FA, B17620A4, D42A5D6C, E1118425, 17C4B3F2, EBDCB06E, 1F8F7F65, 0AD89423, 32848E5D, 0A5028D0, 463B71B1, E896017F, C1DA750C, DB89FC54, AF665A17, 11F5A446, 45F2DD58, 9C66340A, F4DB1D19, 87AFFD89, 75CA495D, DE608110, 78EC9F5C, 7840FE7C, 6F4DA231, 1CF2E830, CD521794, CE4F5EBA, 79B79437, 5A91D18E, 95F1D139, D9CA1102, E3822EB3, F7C52D20, F917AEEE, 5EDCD7BF, 4BD3725C, 94EE3441, 713CF5DF, 937E1AA9, 08926562, 084E8DD4, 41100547, 1C706FF6, 2ED60298, 0D2E30BA, 82FECB1F, 831BCCE8, 0CB829DB, 0C522998, E0AD92F6, F8969EA4, 386650CD, CA41F763, 7BB34065, D79B9F81, 967FBB17, 7C2F61B2, 7B4E9B33, 8359EDDA, 3201D25E, 5F41BAA6, D94A1FD8, 6E29F112, EDB7885C, C4F4380D, DAD428C7, 40609A88, 66DF9A6C, D61B84E4, C4C77436, D6F4B201, 1C0AD2D4, 3A69D216, 1DD70F43, C887E79C, 8579D94E, F2D069EA, 17B4926F, 55BE153C, A783F442, C03D53D2, 5ED56627, C114DB61, 9B0BFD2C, 825DDE34, 97523F35, EE476E00, EB2ED50C, 567BB078, 9B70520D, DC96668B, FCFD7253, 0197E3F8, 7785825E, 0B00322C, B510F809, 51FB92EE, B6F7D331, 2DE0AC32, 00B41A7B, A432B1FE, 94ED9578, 4B56F086, F8BEADE1, 8C899DF2, EAB17808, 240BF736, 7CBA75E0, E06E352C, 3BBD94E5, 427CB86A, 31CB345E, C1226EE3, F9F4697B, 8820CBB6, C3F9BB4C, 509D403F, 03990E8E, 6C5CCD8B, 24F235C0, C5FC6E59, 05E627C9, 4B0C0C96, 45A35E8E, BBF14335, 89B957A1, 3E272204, EC501927, 00ADCBC3, 13DC9199, A682B338, BE42D97C, F97E0F28, 8C1A6128, 76ED6951, D7D8B74F, 80A6C9D2, 87111413, 48268EB5, 69DDA6F7, 8900B2E1, DBF809E0, D50D7B42, 9716581E, A7AE9B6E, 52366624, 85BAF9A3, DE28F70A, 890E37EC, 7F82541D, 9BA2C144, 8766E737, EA8B0E73, 6BC46E1A, 04A2D3E8, F01716BB, 3D0F7338, 93282BAA, 3A9E51C0, 7B26AFBD, FA2B6A90, 36DD5832, 18161A71, FDE783A2, FF84185B, C251868E, 957CA33D, 6D2BD402, F7E61B15, BAAD0068, 8413463A, 63F0F132, 55FBBC6A, 58E3298D, 845AA664, 02D242A7, A456CEED, 2C198D04, 89A25422, 3A4CABFB, 9D24D792, DFBB850F, 76E30332, 58B59723, 1B1A6913, 9FB961E8, B363CA07, 9CC01B66, 00E9E1DF, 9AF48078, F67167D2, 5D8EBE54, F0819D2D, A003D04B, BD20E32A, 7647BD73, DE509593, E381BF67, BB5D56E0, 675636A1, 983C7C47, C7D92CF8, 335F0477, A6EE6787, F2A67D0E, 29D7F83A, 3DA85C1F, 8E31E016, 5FBEB7EA, 01F017A9, 021B93ED, 8E2AE731, 3391B82D, 6AFEC318, C1E9610D, B50DE358, 46E16C1F, D7A03E8A, 74E52044, 4797BCBC, 49FC24BC, 119F71CB, 51ADB9AC, 1F7A8641, 373911A6, 79424584, 2D69A297, 32859E0B, FF812B02, 2060307E, 6AD9173E, AFCB84DA, 4F5B70D0, 34A63D93, 6DBD6388, BBD76CFA, 94EE5483, 20214C3F, E45B9B77, 8B3192D9, 109D8CE6, 8EBA320B, 53FA8CE2, 56A4A45A, 61AB8FDB, 3ABFD0EB, F92E5F91, 3CBA25FE, C2E19318, 2E5DC1D6, 751C25DB, 572BBA47, DF53AB19, 407F623F, EB9E4EE6, C98E9BFD, DA77A48F, 79D4B4D2, E4320563, 2C1C4BA4, CDCCD4A9, 5B74662F, 3B74B8C1, B1792883, 88D53BDA, FDFAB951, D2D3F844, 199D47E1, 7500E432, B0C714BD, EC5CCDCB, EC949808, 9B39D67F, 15D138B8, 17FE54A4, AD28C768, FE473BF7, AE29CB10, C987A478, EE50D094, 10ED5447, E2BF7CCF, BDD93708, D57E6C1B, 01079D4B, 6C6C547F, 363A37F3, 6D4D828A, EE1622DE, AF1D8240, B068E4C1, 9C5901F8, 17822119, 3C7837B0, DEFFD993, 28FA9C3A, EAADDC4E, 05705400, 0046CB17, E843346D, 2F33C418, AF1A47BD, E4C12B9E, BC3F9B15, 01E90C74, DE0C8A00, 5D52587A] -> MT
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 23 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
^Ḋṫ4^^æ«11$æ»31ż&2\ḂS<4
```
Takes an array of integers; returns **[0, 1]** for *LCG*, **[1, 0]** for *Xorshift*, and **[0, 0]** for *MT*.
[Try it online!](http://jelly.tryitonline.net/#code=XuG4iuG5qzReXsOmwqsxMSTDpsK7MzHFvCYyXOG4glM8NArhu7TCteG4iuG5lsWT4bmj4oCcLCDigJ3DmEhpw5DigqzDkOKCrOKAmeG4heKBtMOHwrXigqwg4bi34oCcUGFyc2UgaW5wdXQgYW5kIGFwcGx5IHRoZSB0ZXN0ZXIgdG8gYWxsLuKAnQ&input=&args=W0NFRTYzODc2LCBERTdFMkU3NywgNTRFQzNBRTQsIDkyREVCQjRELCBEMDc1NjYwMiwgRUU5RDNCMTMsIDA0QTQyMTUwLCAwRkU4QkY0OSwgMkJEN0UwNEUsIEJCOTY3NTZGLCBCOUIyMDI3QywgQjU3NTA3MDUsIDlERDVCMzVBLCBFMjNFRjk4QiwgRDE1QUNBNjgsIEMxQzQwRTgxLCAzNUFCQUIyNiwgMkRBMUEzNjcsIDM2NDYyNTE0LCAzQ0EyMTFCRCwgRTc5NzUzQjIsIEE0OUIwRjAzLCBCM0VBN0U4MCwgNjQ2MzBDQjksIEJDMjJGOEZFLCBENTM1OTg1RiwgMTRCOTAyQUMsIEVFOUVCQjc1LCBBODMxQTcwQSwgNzlDNTVCN0IsIEY3MDk5RDk4LCA5OEFDOTlGMSwgRDlDQjI5RDYsIDUzQzQzNDU3LCAwNEM2RkI0NCwgNDNERkU0MkQsIDA1QTgwRDYyLCBEODZEQkVGMywgRjlEQTg3QjAsIDk5ODM5NjI5LCAwMTdEOURBRSwgMEIxQjU3NEYsIEE1NTg2RURDLCBGMjk2NkJFNSwgQjcwOUU2QkEsIEExNjAxOTZCLCBEMTZCOUNDOCwgRkY0NkUxNjEsIDNCREZCNDg2LCA0Q0U0RTE0NywgQkUwMUJENzQsIDZBMkYzMjlELCA5OUYyOTMxMiwgQzcwNDRBRTMsIDlBMzczQ0UwLCA3MzUxNUI5OSwgOTRFMkNFNUUsIEZBMjZCMjNGLCAyODgzNDcwQywgM0VEMzE4NTUsIDc4MDk3MjZBLCA2NERFMzM1QiwgNzlBM0M3RjgsIDUzNzlFNEQxLCBCOTQ0NEIzNiwgOTJDMkFBMzcsIDZBNDk2QkE0LCA4NEU2RkQwRCwgRkM4MUU0QzIsIDQ3MERCMkQzLCA0RjgzOUUxMCwgNDU5MzVEMDksIEM0MEQ4QjBFLCBCNEY2QTkyRiwgRkRFQzhCM0MsIDFDOEJDMEM1LCBEOTlCNEExQSwgRTFDRUE5NEIsIDE3OTUxRjI4LCBCQUVDQTQ0MSwgM0MxM0VERTYsIDBDREM4RjI3LCA0Q0IxMDVENCwgRUQxRTQzN0QsIDFFMjEwMjcyLCBCOEY4RjZDMywgRkIwMkFCNDAsIDYzRDA5QTc5LCA0MTc4RDNCRSwgQjNFQTNDMUYsIDU4MDczQjZDLCAxMEI3NjUzNSwgQkFFQTZEQ0EsIDM3ODA3QjNCLCAxMUUyQTI1OCwgOTMwNjFGQjEsIEVCMjk5Qzk2LCAwMDcxOTAxNywgMTMwQjhDMDQsIEVGQUMwNUVELCAzODVBRUMyMiwgRjZGNTE2QjMsIEQ0Qjc2NDcwLCA5MTUwMTNFOSwgRDQ1RkE4NkUsIEM1MjA2QjBGLCA2QzA2NTc5QywgNEMwRDA1QTUsIDlCRTFERDdBLCA3NzAyQTkyQiwgM0RFRjUxODgsIEUwRUQ1NzIxLCBEQTIwNTc0NiwgMDA4MEFEMDcsIDA1RUJGRTM0LCAzRDI3NDQ1RCwgN0Q3QUExRDIsIDQ0RjExMkEzLCA5QjY0QzlBMCwgNzExOEM5NTksIDA4QkQwOTFFLCBGQzc4MzVGRiwgQTFEQ0RGQ0MsIDFCMDNBMjE1LCA0RDJDOTkyQSwgOTMyNDMzMUIsIDBGREUyQ0I4LCBDMTg5NEE5MSwgQjk1MzFERjYsIEREQzhFNUY3LCAzOEE1NUM2NCwgNTlFNkZFQ0QsIEM4OEIyMzgyLCA0MDlCRUE5MywgQzQ4RERBRDAsIEY1RjFCQUM5LCBERjRCRjVDRSwgQTM5MDlDRUYsIEM0M0REM0ZDLCA1NUQyM0E4NSwgQTAzNUEwREEsIDUwNzQxOTBCLCBDQTkyMzNFOCwgRDk4MEZBMDEsIDg1RENGMEE2LCA5NkM5M0FFNywgQjk0QUE2OTQsIDBFMDIzNTNELCA0RDU3NzEzMiwgRDE2NDlFODMsIEFDNzU5ODAwLCBEMjYxRTgzOSwgN0Q4NzZFN0UsIDI5Qzg5RkRGLCAzMDlDMzQyQywgRDA2RkNFRjUsIDE3MjdGNDhBLCAzNTQxNUFGQiwgQUZBRTY3MTgsIEM1M0I2NTcxLCAzOTk4Q0Y1NiwgNDdDMEFCRDcsIEMwQUVEQ0M0LCBENTRGRTdBRCwgNDg2QThBRTIsIDE4N0EyRTczLCBDNjFGMDEzMCwgRThCMDUxQTksIEREQUE3MzJFLCAxNDNGM0VDRiwgMDcyQjAwNUMsIENBOTM1RjY1LCA5NEVFOTQzQSwgNzk5QUY4RUIsIDJGOTVDNjQ4LCA4OERGOENFMSwgN0IyMUJBMDYsIDFBQUUzOEM3LCBFMjY0RkVGNCwgNEY2NzE2MUQsIEFGMEY3MDkyLCA2MENCOUE2MywgQ0I0RDE2NjAsIEJBRTNGNzE5LCA3RUIwMDNERSwgRUREMzc5QkYsIDVBREQzODhDLCA1RkIzRUJENSwgMEQzNDdGRUEsIEY3NEZGMkRCLCAxOTZCNTE3OCwgMDA1NDcwNTEsIDRERDJCMEI2LCAzNzUwRTFCNywgM0NDMDBEMjQsIEFGOUVDMDhELCBERjUxMjI0MiwgMEYwN0UyNTMsIEVDODJENzkwLCBEQUMzRDg4OSwgMTQ1MzIwOEUsIDM3MjQ1MEFGLCA2MTY1RENCQywgRjcwODc0NDUsIDM0NjRCNzlBLCAxOUVGNDhDQiwgQ0IxMjA4QTgsIDRGNDEwRkMxLCBDMUM2QjM2NiwgQjMyN0E2QTcsIEE4RDMwNzU0LCAyRDBERTZGRCwgNEZGQTlGRjIsIDkxOUUwNjQzLCAwMTAzNDRDMCwgNTlENkY1RjksIDM3MEVDOTNFLCA1NjkwQzM5RiwgQTMzN0VDRUMsIEIzODdGOEI1LCAyRkFBM0I0QSwgQ0VDN0ZBQkIsIDYxMkNFQkQ4LCA1MTBDNkIzMSwgQTNEOEMyMTYsIDgxNzE4Nzk3LCBFQTcwRUQ4NCwgNzI4Qjg5NkQsIDQwOTZFOUEyLCA1MEJEMDYzMywgQjZEMTVERjAsIDM5NjQ0RjY5LCAxNDFERkRFRSwgODgzN0QyOEYsIDJCODY2OTFDLCBFM0U5NzkyNSwgNDRGMDBBRkEsIDc0RTkwOEFCLCBFNzFFRkIwOCwgMDhERDgyQTEsIDJEQTNEQ0M2LCA2MzJEODQ4NywgRTAyQ0JGQjQsIDBFQUVBN0RELCA2OTcwRkY1MiwgOUU1M0UyMjMsIEMyQjAyMzIwLCBEQTcyRTREOSwgMUQ3QkJFOUUsIENERjg3RDdGLCBCODQ0NTE0QywgNzJBM0Y1OTUsIDhBRTEyNkFBLCBDRDIxNzI5QiwgODcwQjM2MzgsIDExOUI1NjExLCBCNTgzMDM3NiwgRDcxQTlENzcsIEIzNTk3REU0LCBFM0NFNDI0RCwgQUI5M0UxMDIsIEE2MTE5QTEzLCAxMDIyOTQ1MCwgNkRDOUI2NDksIEI5RTMwQjRFLCBERjcxQzQ2RiwgRUEyNEE1N0MsIDU1RUU2RTA1LCA5OEU4OEU1QSwgRUEwMDM4OEIsIEI5RDQ5RDY4LCAwREVDRTU4MSwgNUU5MTM2MjYsIDA5QjdEMjY3LCAwODBBMjgxNCwgOTgwMTU4QkQsIEMwQ0E4RUIyLCA1RDY1MkUwMywgRjE2QkIxODAsIDYzRUZDM0I5LCBGNENFRTNGRSwgMUEwMkE3NUYsIDc0OUE2NUFDLCBGRkJGRTI3NSwgMzczMTQyMEEsIDFGRDQ1QTdCLCA3NzFFMzA5OCwgMTgzOTMwRjEsIEM4QTk3NEQ2LCBDNTQ0MjM1NywgMkQxMUJFNDQsIDA1MUVFQjJELCBFQkEwMDg2MiwgNzM3RDlERjMsIDRGOEU3QUIwLCBERDJDMEQyOSwgMkU3QTQ4QUUsIDcwQ0EyNjRGLCA0REQ4OTFEQywgQ0RDRjUyRTUsIDBFQTY0MUJBLCBGNEFDRDg2QiwgNjU0QUVGQzgsIDMyQTczODYxLCBDMDY2QkY4NiwgNjFCRTkwNDcsIDRDMDM0MDc0LCBBOEJERjk5RCwgQTc1RjRFMTIsIDQxNDlFOUUzLCBEQTRERUZFMCwgMTk4NTkyOTksIENCRTAzOTVFLCA1Q0E3NDEzRiwgREVEMjJBMEMsIDc5OTNCRjU1LCA1OEYyOEQ2QSwgMTA1OEIyNUIsIDA5N0REQUY4LCBCNzFERkJEMSwgRUYyNDE2MzYsIEI0RTYxOTM3LCA5OTMxQUVBNCwgMTQzNTg0MEQsIDU4MTM1RkMyLCBCOTc5MTFEMywgMzgyRDExMTAsIEU4QzM1NDA5LCBFNkJCQjYwRSwgQ0MzOEY4MkYsIDMzM0EyRTNDLCA4ODQ0MjdDNSwgOTA4MTI1MUEsIDJDNjZFODRCLCBGNzk5RjIyOCwgQzc0NDdCNDEsIDhBRkM3OEU2LCAwMjM5QkUyNywgODNCMDA4RDQsIDVDOUM4QTdELCBGQTg3M0Q3MiwgNTg3QTE1QzMsIDM2NkVERTQwLCAxQTZDNTE3OSwgRkQ4N0JFQkUsIDEzREU0QjFGLCAyOTgzOUU2QywgQkFENzhDMzUsIDIwN0QwOENBLCAwNDI2N0EzQiwgMDI0MjM1NTgsIEJDODFCNkIxLCAwNkNBRTc5NiwgRUFGODdGMTcsIEU1NTE0RjA0LCA4QUNBMENFRCwgRDQ0NUU3MjIsIDE0N0JGNUIzLCBGOTE2NTc3MCwgRURDNzhBRTksIEEzN0Y1MzZFLCBEREI2M0EwRiwgQTJFMTdBOUMsIDdFMDRFQ0E1LCAxNEQxMzg3QSwgNDRBNjY4MkIsIDZBRDlBNDg4LCA5N0ZDQUUyMSwgQzIyQTYyNDYsIDVFMjE1QzA3LCAzMkE4ODEzNCwgMEI1NTBCNUQsIDIzOUE1Q0QyLCA0RDZEQjFBMywgMkFFNjdDQTAsIDgxREMwMDU5LCAzMDlENzQxRSwgMTk5RkM0RkYsIEIzNDZDMkNDLCA1QTQzNDkxNSwgQ0EyOEI0MkEsIDdDQjVCMjFCLCAxMTgzM0ZCOCwgNzI5QzYxOTEsIEI5NzVFOEY2LCA4ODczNTRGNywgQUIwODlGNjQsIDFFOTQ4NUNELCBDRjhGOUU4MiwgQkNGRTQ5OTMsIDJENjI0REQwLCA0NTcwQjFDOSwgNzE5RDIwQ0UsIEVEMzlFQkVGLCBEMTY2NzZGQywgNjNDOUExODUsIDlERUU3QkRBLCAwQ0UzNTgwQiwgQTUyMjA2RTgsIEVEMDdEMTAxLCAzNUM4N0JBNiwgQzQ2RDY5RTcsIDg4ODRBOTk0LCA0ODlGN0MzRCwgMTdGMEFDMzIsIDY2OUNCRDgzLCA0OENDQ0IwMCwgNjcwQzlGMzksIDU3Rjk1OTdFLCBBM0UzQUVERiwgMDZCMzk3MkMsIEFBOEVGNUY1LCA5RTREOEY4QSwgMTc3RTU5RkIsIEQzNThGQTE4LCA5RkE1RkM3MSwgN0NGRDFBNTYsIDhBNEU5QUQ3LCAyRkVGOUZDNCwgQzE0Q0VFQUQsIDQ1NDg4NUUyLCA4Nzc4MEQ3MywgREMyOEY0MzAsIDQ0RjZDOEE5LCBBOUVEMUUyRSwgOUVCQzBEQ0YsIDFGNjEyMzVDLCBBQTRBNDY2NSwgM0EzMEVGM0EsIDcwOTVCN0VCLCA3ODhCMTk0OCwgOEE5REUzRTEsIDgxQUVDNTA2LCA2MDE1RTdDNywgNjBEQzgxRjQsIEU0MzNERDFELCA1OEUyMkI5MiwgODY3RjM5NjMsIDhEMzlDOTYwLCBERDM2MkUxOSwgQjI3MzZFREUsIDQ0QTIwOEJGLCBEQTYyMUI4QywgQkE3MjkyRDUsIEYxNDM5QUVBLCA4REY4NzFEQiwgQ0ZEQjY0NzgsIDg1RDY4NzUxLCA5MzM4N0JCNiwgQzk4MjUwQjcsIDY1OUU1MDI0LCBBMEFCNDc4RCwgQkNDODlENDIsIEU0NjE0MTUzLCA3ODgyNEE5MCwgM0Q5MUNGODksIEYxNDc0QjhFLCBGMjM0OUZBRiwgMTk2OTdGQkMsIDdFM0VEQjQ1LCAwM0YwOTI5QSwgNzczNTg3Q0IsIEEzMkNEQkE4LCBCMEY2RTZDMSwgMERCNTNFNjYsIDM4MTJENUE3LCA0MzQ4MEE1NCwgRTlDQTJERkQsIEYzQzZEQUYyLCAyQjhEMjU0MywgNjE0NTc3QzAsIEYzOTBBQ0Y5LCBDQUUzQjQzRSwgRTlEMkQyOUYsIDEwRUE0RkVDLCA1NEE2MUZCNSwgMjM2MkQ2NEEsIEI1OUJGOUJCLCA3QjIyN0VEOCwgRTM2NjAyMzEsIDBBMDAwRDE2LCBGQjA2NzY5NywgRTlBQ0IwODQsIDI2Njc5MDZELCA0OTY3RTRBMiwgRTAzMUU1MzMsIEUxODY1MEYwLCA3Qzc5QzY2OSwgMzg4M0E4RUUsIDQzOUJBMThGLCA3ODE3OEMxQywgQzg1RjYwMjUsIDIxODU2NUZBLCA0NDNBQzdBQiwgQ0YxRjRFMDgsIDFDNEFEOUExLCAwREIzRTdDNiwgMkY1QzMzODcsIDYzNUY0MkI0LCBBMTFBNkVERCwgODFGNkJBNTIsIDcwM0U4MTIzLCA5QTA3RDYyMCwgQjU1NDFCRDksIDc4MjIyOTlFLCBERDZFMEM3RiwgQjhFNDM0NEMsIEZGRTE5Qzk1LCBBMTAzNDFBQSwgN0ZFMEYxOUIsIDM1NDY0OTM4LCBGMjhDNkQxMSwgQkIyQkNFNzYsIEFGRDMwQzc3LCAwNUIyQzBFNCwgRjgzOUM5NEQsIDhBN0U1QzAyLCAyMzYxRjkxMywgNjI0RDA3NTAsIDRBRTZBRDQ5LCBCQzdBMzY0RSwgNEFFOTEzNkYsIDIwMDM0ODdDLCAyRDYzRDUwNSwgQzU0NzY5NUEsIDE3MUQ3NzhCLCA5MjdBNzA2OCwgMDREMUJDODEsIDgxODJDMTI2LCAwNEVBMDE2NywgQTBCQTJCMTQsIDhEREM5RkJELCAyOEM5QzlCMiwgMEIwQjREMDMsIDc4OThFNDgwLCAyOUI4N0FCOSwgREQwNkNFRkUsIEM1NkJCNjVGLCAwQ0U3QzhBQywgRkVERDA5NzUsIEUyN0NERDBBLCBGQTNGNTk3QiwgNEE1RUMzOTgsIDY5ODFDN0YxLCA0QzkzQkZENiwgNTRFMDEyNTcsIEFGNDg4MTQ0LCBGN0Q5RjIyRCwgQUI2NDAzNjIsIEYyNjk3Q0YzLCBCMUVFNkRCMCwgRUUxMDg0MjksIDA2MDJGM0FFLCAxQzE0RjU0RiwgMjFDNEI0REMsIDBFMDQzOUU1LCAyRDhFOUNCQSwgNEI1NTk3NkIsIDZGNTY0MkM4LCAxRUMzOEY2MSwgMzRGOUNBODYsIDUzQjQzRjQ3LCA4NkYwQzM3NCwgNkZDOEMwOUQsIDk5OTgwOTEyLCA0RTZCODhFMywgQUExMEEyRTAsIDUzRjVDOTk5LCA2ODY5QTQ1RSwgQTNDM0QwM0YsIDczOEQwRDBDLCA1MDUwNjY1NSwgNkMyN0E4NkEsIDRFMkYzMTVCLCBGMjgzRURGOCwgN0E3RTEyRDEsIDMwMEZFMTM2LCAzMzI1ODgzNywgODgwNUYxQTQsIDQzMDAwQjBELCA2MzcwREFDMiwgMkRDMDcwRDMsIEYzODI4NDEwLCBBNzJGNEIwOSwgRTlGNUUxMEUsIDI3MTc0NzJGLCBCOUYzRDEzQywgODZGODhFQzUsIEE0QjMwMDFBLCA1ODVCMjc0QiwgRDNDQUM1MjgsIDlBNTg1MjQxLCBCRkYxMDNFNiwgOTJCMkVEMjcsIDREOUIwQkQ0LCA0Mjk2RDE3RCwgMTFCOTc4NzIsIDI4RDczNEMzLCA0Nzg3MTE0MCwgMzM0NDA4NzksIEQ1MjJBOUJFLCBENjZFNUExRiwgN0Y2QzAxNkMsIEFFRjNCMzM1LCBDRTVCQTNDQSwgQzEyODc5M0IsIDUxQ0RDODU4LCBEM0I5NERCMSwgQTM3ODMyOTYsIDZGOUI2RTE3LCBERDgzMTIwNCwgMzM2NDEzRUQsIEY1RkNFMjIyLCA1MURFRDRCMywgQjYyMTRBNzAsIEIzN0IwMUU5LCA4OTJBRkU2RSwgMzdFODA5MEYsIDUxMjg5RDlDLCA3MEY4RDNBNSwgODEwQzkzN0EsIEQxQTYyNzJCLCAxOUVGRjc4OCwgMjNDODA1MjEsIDg2NDA2RDQ2XQpbN0QxNzUwNEQsIDlGRUQyNjlCLCA5MzlDM0QwMywgQzhGQ0ZBNkMsIDBGQUU0RTA2LCBGOTgxNjg5NiwgOEI4NzI2ODAsIEE0ODc4MjA2LCBEOTI0MzZFRSwgMkIxMzMwODQsIDk5MTJBMDQwLCAwMTFEOTZENiwgRjk3NjQzNUQsIDRCNTNEQkU3LCA0NzRGNjI2RCwgQUEwOUU3NzQsIEUxMkUzNUMzLCAzNDc3NDZFMiwgMDgxNzE2MEIsIEVEQzA2MjNBLCA3REQwRDI2QywgRjMxRUNCNjIsIDQzMDkzQzQ0LCBBRDM2NTdBRCwgNTY4RUIzRDUsIDUzQ0UyN0JELCA1OTJGREE5QywgNDZCQjY1MkIsIDY1ODg2NjMyLCA0NzU5NTZGMSwgNjA4NTlGQkMsIEZEOEEzQ0JBLCBEQjE1NkNDRiwgNTY3NjQ3ODIsIDFBNDI0QThGLCBCNjgxQ0E5MSwgQzY4MkJCOUEsIDIyMkNCRTlGLCAyQTMyOUU2NywgOTI1RjBDRjIsIDQxRDIyQjQ4LCAwNjREQkRBQiwgQjgzMkRBQTMsIEQyNjA2OUNCLCAwMjM4OTBBNCwgNjlGM0Q1QUQsIDQ3M0FGREYyLCA5NkM1RUFFRiwgNTBCRUY1MjMsIEE3MTcxQzI0LCAzNzUyQjA1OSwgOEU3OUI2Q0UsIDI5Qzk1RENGLCAzNjIwOTJFRSwgOTQ1MjNDMEIsIEQ3REUyNzg5LCBCNDlBM0Y5OCwgODYxRjdDMDcsIDgzQThCQUFCLCBBNTZDMjczOCwgQzA2RkFBRjIsIEJERUQwOUJDLCA3QjU2ODE0OCwgQkZDNzNDRkQsIDAyNDIyOUNELCBENzM3NjBEMCwgMThBNEU3QkYsIDlFMDIxMDgyLCA4RDFENEVDRSwgRTE0MDhFNUQsIERFRTYxNEQ1LCA1MEVFODk4QiwgMzdFMkQ2NjYsIEQyMzU4NEExLCAzQzlCNjI4RSwgMTgxRDE2NDcsIDM5NkRBMkM0LCA0NzAzMzlDNCwgQTA2QkFDQjgsIDUwMzQzOURDLCAwNDFCQ0E5QywgNUE4ODFFQzIsIEE3N0I3NzQ3LCA1NjcwNDBBRCwgOENFNTJGRDUsIDk2ODE0RTg1LCBFQTNDRDI1RCwgM0U5RDkyOUYsIDlCQTM4OTFFLCAwN0NBMDk4OSwgMEI2ODlEMTcsIEQ5QjNGRjhGLCA1RURGNzZERSwgMDkwRUJBQ0QsIDQ2QzExRURFLCAwMEM4REUwRSwgQTUwNDMxNEYsIEQ5QTAyRkYwLCA5N0Q5RURGNCwgRDFBNzY5QUYsIDU1QURCNDlELCA4REFBQ0U3NywgRDU0NDI0N0IsIDNGNDRDNTZELCAwNzc1OTc0NCwgREM3NzM4QUIsIDI4RTRCOEEyLCAzMTkyN0Y3RSwgOUFGNjAxQkYsIEZGMjFDMDJBLCBGMjBENTZDNCwgNTBDNkFFNzQsIDdBMTdBNjJBLCA4QkM2MTlEMiwgMTNFNUM1MTgsIDc2MzU3QzFFLCBCMUQ0QTIwNCwgMEE2NzM1NjUsIDM3OTdGQzM0LCBFQTlGQTM1NCwgRkU0RkY4ODEsIENEQjAzNjMwLCA0NTRFMDVFRSwgNTJEQzhCMTAsIEQzRDZGQTNBLCA5RjlCNTdDNiwgQUFDRjUwQUUsIDFDRkRDQUVDLCA3ODlFRTQ2MywgM0RGRUE5RDEsIEVENjRDNEUwLCAxRjNDRDkwQSwgOTAwRTlCNzIsIDU4NzYxODgzLCA5M0ZFOTRBOSwgNkFGM0ZCNTUsIDhFQzIyODcyLCA2Njk4OEIyOSwgMDFBNDAwOEYsIEY0Nzg3QUJELCA2QjY2NURGOCwgQzkwNTUyN0UsIEU4ODQ5M0E5LCBERjFFQjE5NiwgODZDRUJFMTAsIDY1QkI5QTE1LCBBOTZFNTREMCwgODNENkQyNkEsIDcwMUJDMjNFLCBDOUM5OTUxQSwgMTJEQTkwMjcsIDI3QUE1NTk0LCA4OTBFNjk2RCwgMENFQTVDMTMsIENBNzdBRTAxLCBCRjA0NDQyRSwgNDVCQjE3QTIsIDFCRUZEMUMyLCA2QzlGNzMxOCwgRjEyNzZGOTEsIDZDQkM3MDEwLCAwOUI4REQ4NCwgOUUyODY4MTgsIDU0QjlDN0FCLCBEQjBBMDFEQywgMTQ5MUIzQzQsIEM5MjQ3MUU2LCA1MzNBNzNGNiwgRDhCNTlDQUMsIDQxMjMxQkVELCBBQjYyRjk2RSwgMkI0NzhBMzcsIDVGNjMyMzBGLCAwNkM2QTc3RCwgQkFEMzg3NDIsIEFERDJCNDFELCBFQkVGODFGMywgRDgyMTJFQkMsIEZFRUU0QjZELCBDNkE0N0FGMSwgNTFEMzlCQ0YsIDgwNTYwQjg3LCAwQzZGOERDMywgRTlGOTBENEQsIDI0MzlGRTVFLCAxNDAzQzM2RCwgNjQ3MjU1QkIsIDQ1QzBBRjFELCBBRUUwNjJGNSwgQTRGMkM0RUYsIDUyREI4MjQ3LCAxMjIzNzc0NiwgQkY3OTQ4M0QsIDhEOUUzNjgxLCAwM0Q5NTRDRiwgMEE0OThBQjUsIDdGMDQxMzYxLCAwMzUyMDgzRSwgQ0FFNDVCQjcsIDhDQkU3QzdDLCBEMzdFRTk5MSwgNDBGRTE4MzgsIEE4MkZDQTczLCBENzBEMUU5NiwgRjMxQjU3ODcsIDQzOTRBRTA0LCA5NTNFODg1NywgMkE3OENEQzgsIDAzRjYwMDZGLCBFNUY0NkE5QiwgODRFOTNBNDIsIDY4MTNCMTlBLCBEQjU1MzE4RiwgOURCMzM4Q0MsIDUwNDUzQTEyLCBBNTJGQ0VFMSwgRDc4NDRBODIsIEQzRjU3REU2LCBBQTE5NTgyMCwgNzE5QUQzNDQsIDg0QkY1N0FGLCBGQ0REMTA5MywgOUM2NThGNzAsIDNCQzI2RjRCLCA0NUJFNDVCMywgNTFGMzlDMUYsIEUxNUQ4NzVFLCBDOUNEMTQwOSwgN0VFOTQzNUUsIEIzMzczQkY4LCBCRTVEM0RCNywgMUY5MTFCMjksIDJCNTY1ODM2LCAyMUI0NEU1RiwgNzY1MzdGNUIsIEUxOEM2QUVCLCA3ODgyMDkwNCwgRkJDNzc2RkQsIDE2ODM2Nzc5LCA5NERBOEM3MCwgRkM3ODdEQzYsIDNDQzg4QzJBLCAzMTdEOUM2NSwgNzE4NDJGMzYsIDRFMkRGQThELCAzNkZDODZCRSwgRUJCRkFBQjAsIEJCMTJENTZFLCA5QUNBQTkxMywgNDhEMTA1ODIsIDVFMkRDQzAyLCA3M0I5REIwQywgQkNGNDY2NTksIDdDQzk5OTUwLCA0Q0I0MDcxNywgRjE2OEQ0MzYsIEVFQjFBMkVDLCBERTgyQTU3MywgMzJFMjhEMEIsIDg1OUMyNjA1LCBFNjU5NTI5OCwgMkQzQkRBMUQsIDBCOTc4MDY0LCA2RjVGMjMxRCwgNDNCRTcxRkMsIEIwQTZBMEE0LCAwNzg1ODI3NCwgOTE1NDBFNTIsIDIxRDVCQzE1LCBBNEYzOUIwQiwgOEY0RTNCQzMsIEJFNTk5MkU2LCAzMkUwQTQyQywgMEFGMzRBQjgsIEY0OURGODA2LCA4NjIxOEFEMSwgQjFENzlGRkQsIDIxRTFBNUY1LCAzQUE3MzQwNywgQjA1QTQ2ODAsIEJEN0YwRjAxLCA5MTlEREI1NiwgOTI5OUMyNkUsIEYwOTVGOEZCLCBCNUQ3RTZFRiwgQ0FFRkRDNjgsIDk2MzlGREU5LCBDOTM0OURGNSwgQzNERUZBQTIsIDc3NjY3MjJELCAyRUU5MUY5RCwgNDM1RkY0ODAsIDc3NjAxREEzLCAzM0QzRkU3OCwgNTVBMDFBNjgsIEU5RTcxRkE4LCA5RTFEOEEzMiwgMzI5MTg3QjcsIDY3QjdBOEQ3LCBCNjdDRTFENiwgQzQ0MkExMzEsIDdBNTAyQTMxLCBBMDdCQzRCQywgRjE1OEYzMzQsIDIwQzI4RjA3LCBEQjM4Mjg4QywgQTUxODQ5NzMsIDkzRUZDRkI3LCBBNzYxRDA3QSwgQkQwN0YwNTIsIERBMzM2NTUwLCAzNzRDOUJENiwgOUUwNzdGNDUsIDFDMDA4OUI3LCA1RDU4NzY4MiwgMEU5OUM0RDQsIEFCQzE2RjE1LCBCMzk0MDZFQiwgMkRFNjlBN0QsIEVEOTk0NDcxLCA0RDgwMjcxMCwgNUUzMEQzMTUsIDQ3MUM5RkRDLCA2MDgxRTE4MiwgMkM3NUYyMjUsIEY0MDUyNEM1LCA1NzQ0QTdFNiwgMzhBNkQxN0QsIEJCQzFFODk2LCA2NjNGRDAyNywgMTQzNjMwOTEsIDFBMTUyNjUzLCBBRTI0RjhERiwgMzYwMkJCRDQsIDkzMTVCNzNELCAyMDgxM0NCMiwgQTlFQURBN0QsIDhBMTUwODhGLCBCNDg3RUFBRiwgOURDQTM0MjEsIDYyMEMyQ0Q3LCA0MDdGMDE2OSwgQ0IyNjQ5NUIsIDA3ODEwNzIyLCAwNEU4Rjk5MSwgQkMyNEM0MkMsIDQ1QjEyRTYyLCA0QTA2ODlFMSwgMDk2MUQ1NDEsIDkzRkU3NUU1LCA1RkYwOUJDNiwgMjFDNzU4NTgsIDI2MEI0QUZDLCA0NjNBNDI4NSwgOURDRkNGMkYsIDg2RDE0MTU2LCBGQUYxQTdEQSwgNkU0QkZDNkIsIDhEMUVGMDNBLCA4MUM5Q0IzRSwgRjY3MTYzQUEsIEM3RTg3MUFCLCBCRDBERDY0QywgNzI1MjZBRTgsIDBGNDMzQjNCLCA4QkEyNzY1MSwgNThDRTZFREYsIEI5MkE0QTA0LCBBRkE2MjRGOSwgMzcyRURGQTIsIDFDQkRGNzBFLCBGNzJDRTRGNywgNjkzMzk3MDcsIDI4QTE4NjRDLCBEQjU3MDFEMSwgNEJDQzREMTAsIEJFQjI2MEMxLCA5QTA1MDJCRCwgRjkzRkMxQTUsIEQwQjJCNzVGLCBGRDJCNzFFMCwgNEY4OTk0MTIsIDQ4QkM0NkFGLCAwREYxMDhBOCwgQUJGM0RDODcsIEE4RDlFNEVGLCAwMkZBNDY2NSwgODdDQkJBREEsIEIyRTk1OTQwLCBENTcwMkQ2RSwgMDU2OTkwQ0IsIERGQUVFN0Q2LCAyNzc1ODYzQSwgNzMzQUM0RTcsIDNBOUNFRDgzLCA5MkE0MkQ1MSwgMTk2QjJENjksIEJDRDNDRjVGLCA2MUZFRERCMywgRDI4M0JBNzgsIDkyQzNDNTI0LCBCMDQ4NDkxNCwgMjdDQzA5RUIsIEU4NTMyNzEwLCA2NDM1MzVEQiwgOTZDN0QwQTAsIEQxMDMxMEMyLCBBMDE5QzY1NSwgNkQ0RkE0NjAsIEM1QTUzQkI5LCAwQ0U5QTZDRiwgNjJBQ0UyNjksIDcyRDAyNkY4LCA5RTQ0QTNFOCwgREZEQUIxMzEsIERBNjBCRjA5LCAyOTc0QTU1QiwgOTI5NDE4N0UsIDk4Q0Q2MDI0LCA0NzhBMUNDMywgQ0I1ODM3MTQsIEY5M0Q5MUU5LCAwQTAyMDJBQSwgMUQ3OTZCMkQsIDE3OTMxRjAxLCAwMjM0NzZDMywgMTgzOTMzN0QsIENFQ0YxMzU0LCA0MTJCNzY5QiwgRTAwODkyMTMsIDMxN0JGN0I0LCA4Nzk4MTc3QywgOUQxRDM2QkEsIDM5MjFCNzAwLCBENzA5MjFDNywgOTA2REVGQUQsIEU0QjFCM0ZDLCBEMDFDODFERCwgNEU4NTg1MDAsIEIxNkExQkZBLCBEODJENzA3OCwgRUMwQjEwQzksIDhFQzQyNUNELCA2RjkwNEEyNCwgREM4RDU5MUUsIDY4QjQ5NzFFLCBDN0YxM0Q4OCwgMkFERDhFMzgsIDlDMkU2N0Q0LCA1MEVFMUYyOCwgMUVCRDc1QzAsIEQ4RDc5NDYxLCAzNzI4NTg2OCwgMTcxRjE2RkEsIEUyRjk3MkFDLCA4NkU5ODYwRSwgRjM3NzY1QTMsIDFDMzAxNUYxLCAzNTc1NjhDOSwgRkY2NjQxOUYsIEI3NzQ3OUFELCAyQjc3NkQyRiwgQjVEQTdCQTgsIDc4N0RCRTM1LCA2Q0QwMTk4NiwgRkM1RTFGMjYsIDlBM0YzQzNFLCAwRjI2QjU1QSwgRTNENjgxMTEsIEVGN0QxNTYyLCA4Q0MwMUE3RiwgQjY3NkUyRDgsIEUxRkYyMzBFLCBFNjJFRUM1NiwgNkFCMTAxMEUsIDZCRDA0RUEyLCA3MzJGRjc4NSwgRTJGMkU5RUEsIDAwQTkzRENCLCBFOUU1QzYyMiwgRTU3QTk3NDQsIDkwQjI4RkI4LCBEOUJDQkYwMCwgMUVBRkE2QzMsIDJGNUVEMkU1LCAyQjk1NTdGOSwgMTdFREE5MzQsIDc0MTc4Q0I0LCBBRDA3QjEyOSwgMkNBQzExRUYsIDU2NzJCOTQ3LCA5RUM4RUQxMSwgMEVENjg5MTgsIDQyQjlDMjQ0LCA4MUMyRjNENSwgNThCQjI2OTksIEUyOUZGQURGLCA2RUI4QUYyQSwgRjg3MkE1NzMsIDc5N0NEQjBBLCA2NDI4OUZGOCwgQ0Y0MkFEQTgsIEEyNzZEMDBFLCAzRDRERUJDMSwgMURCQTY0Q0YsIEM3NEZBNTNELCBEM0FERUI3QSwgODFFQzAxMkQsIDRGQkU5MUMzLCBGNTYyQjM0NCwgNDkyODYwQTksIEE4MkNFNUM4LCAxM0E3NDk4NywgRjNCRjIwMjQsIEY5OTgzQkQyLCAzNjU1ODM4QywgMUY5NzFGQjAsIDE1MjNBMjY2LCAyRDVENERCQiwgQjc4RUUyN0YsIDEwNDMwMUExLCAxODdCQTE1RCwgREY4QzA3N0MsIDFGRDE5QkU4LCAxNzk3REZCQSwgRDIyM0U1NUMsIDZEMkJBRjgzLCBGRUI2NzcxNSwgNTc3NTBENzYsIDlBQjEwQkMxLCBBQUQ2RjhBMywgRTc5NTNDMzMsIDE4NzQ4MzBBLCAwQTg5NkNDNiwgMTc4NzlFRDQsIDU5QkQ0Q0IzLCBFNTZERjg1RCwgQTRDMzU3NkEsIDhGOTkwQzE4LCAzQ0YyMTE4QywgQjZEN0E5NUYsIDA4MTFDMEU4LCA0RkFGRjQzRSwgRTM3REYyMzYsIEU4RUIyMjU3LCA2RTdCQTkyMiwgNUU0NUFFRDcsIDUyQTUwQjZCLCBFM0VENjJGMiwgNTA2Q0Y1MTQsIDIzMkNEQUQ4LCA1OUE4NzM4NSwgRDFEQTcwQjAsIEU2MjlGQkNBLCBBMzk2MDdDRCwgQjlCODdDNjEsIEJCRTVDNDE2LCAxMkJCOEYwQiwgMDEwMDRBRkUsIDdCMjE2NUNCLCBFRTcxREJDRCwgMjA3Q0QyREYsIDIzMjgzQjk0LCA1MzU3MEQwNywgMzM5ODFCMTMsIEY1QjRERDk1LCA5NzIyQUMyQywgN0NGNkI0RkEsIDhGNDU3OEY0LCBEQzRFNDRGQywgNUU4RkQwOTUsIDk3MTdFRURBLCAzMzMxQTYxNCwgOURGNjZEMkEsIEJEREQwRDc5LCA5NTk0NDUyNiwgMkIyQjUwODYsIDA1OUFGN0Y0LCA1MDc5ODRGQiwgNjdGMzQ2QTcsIDE2MkQ4NUJGLCBDNERBRjVEOSwgNTgxOEVGRTUsIEE1MjM1QzNGLCBERjU5MzU1OSwgQ0MzRTY3NTYsIDUzQzZERUYzLCBFQ0JCQjIxMCwgRkE1RUExMjMsIEM1NjU2REU5LCBBMDMxMDJGMCwgOTEyQjBGRDQsIDlFNzNGMzZCLCA3MDk3Q0Y2OSwgNTg5OTY1MDksIDkxMDU5NDYxLCA5MEVDQzU4MSwgNUVDRUJDNzIsIENERUMyQjhGLCA3MEY3MDhDRiwgODZDMTBCOUQsIEFEQzcxQTFCLCAwMURCRUM3RiwgQzlBMjJERkIsIDQ3QjE0QUIxLCBEMjMzOTc5RSwgMEM1NTIxQjMsIEQ0NDAxODM3LCAxOTY5MjRDQywgNTdBOENGMTgsIEYyNTUyNEU3LCAyNjAwMUIzQSwgNzYxRjE0NzIsIDY3REVDNUE2LCAzQ0Y3QTdBNiwgMUEwOEIyQzksIDk0M0E4OTdFLCAwNTU4OURBQSwgODQxM0MwMzAsIERCRDJCNDgxLCA5QkUzQTdGQywgNUE5N0NDRTcsIDQwOUY5NUM1LCAwRUE3NTdFQiwgODhGRENEODRdCls0QkI2REFERiwgOEVFRjhFQTMsIDA2RThGRDQ5LCA4OEEyQUY0OSwgRTMyNjlDRDQsIEVDQTRGMDlBLCAzQURDOEVGQiwgQUE0REQwNTksIEFDM0IxQUFFLCBEQTIyQzI0NCwgQjY3QzJFQzYsIERGRDlDMTJGLCBCNEE2REJBRiwgMzU0QzM3MkMsIDJDNkNBNDA3LCAwQUM5MzY5MywgNzI1Qzc3MTYsIEI0MzlERjI1LCA3QzA0NjI2RiwgNjc4MjRGMTcsIDIxRUUzNjRELCA3N0Q4RDcyRiwgNEJGOTAzNzEsIDdCQzNDNzE2LCA0NzJBNDIwNCwgQjg0MkFFRkUsIDM4MjcwNDYyLCAzQjE3QjE4OSwgMjI3NjAwODUsIDJBODAxRDg1LCA4REUzMzRCNSwgQTcyNTgwRjcsIEYxODdBQTlCLCAyRTA0REMwQywgOEE3MDFDMEQsIDQ3MUI2MUU2LCA5OEY4NTlEOSwgOUVCQzJGNDUsIDAyNTQ0RTk2LCBDMjc4NUIxNSwgMjA2MjNGQUIsIDgwMDFGOUI0LCAwRTQzODU0NSwgQ0ZBMkEyQTUsIDlEQTM1NzIwLCBCQUE4NDkwMSwgOTA4NzU4QzgsIEZDRjU1NTdGLCBGOTA1QjNCNCwgQkU3REVCQ0QsIEZFRDA4QjFFLCA3RTk0NzJDQiwgQUMzQTI5QzEsIDVCRUQxOTRGLCBCNjkzMkYyNSwgMUM5NUUzMkQsIDY3RTk0MzcxLCBEN0NDQjRDRSwgREYyOTZEODcsIDZBQUVGMEY2LCA4Q0ZGRjg2NywgMDkzRjlGNzksIEZCMjgwRjZDLCBERTc3MzVBOCwgNjg0QzE3QjUsIEEwREE3NTdFLCAzNzRFQzE2MiwgMTc2NEE2MkQsIDgyQzI0NEY2LCA5RTQ1ODNDNywgNTZGMDIzODgsIDAwMThFNDAwLCA4MTVBMEYxRSwgRkQ4MEM5MzIsIDMwRUREMTc1LCBEMzdBRjhEOCwgN0M4RTQ2MzMsIDdEOEU0RTVELCA2NjBBN0Y3OSwgNEMyQzA4QkQsIEI2NjU2QTVCLCBDQ0ZENjYwNywgQjBBQTE3RkEsIDA2MEVFMzA1LCBERUU5NzUyRiwgQjM4QkU0MzksIEYwNEVCOTY0LCBENEU2QzMzMCwgRENENEY3QUIsIERGN0Q4M0JGLCAzMDkwNDdDNiwgNTFGRkM4MTksIDlFNTlDN0Q2LCA0NjgyMTk3MywgMDFCNDc3OTIsIEY4MDA4MDlCLCA2MDUwQkI2NCwgQzEzQ0I0OTUsIEEzMDVGNzg4LCA3QUQyNzI3OSwgQjdGOTE1MUYsIDlGMTU0QzRGLCBEM0Y2ODhGMSwgRkY4MzA4NjYsIEE5QzA1OUEzLCBGRkJGMTYwRSwgRUE4RDgyN0EsIDFGMURBNkU4LCBGREM1MkVGQywgNTMyNUNFMTEsIDc2NUI4NkVCLCBBODUyREM1QywgNzRBREFGNjIsIDQ1QkZBQ0E1LCA4RTFGRjZDMywgODNBRENGMEEsIDkxRDY2MjZFLCAzMTYwMDhDQywgMERBRDQxMTAsIEMyOEVBMzdELCA1RjA3N0IwMywgQUY3MEM1RTMsIDEzQTdDNTBDLCAwQTczN0I5RCwgRTIzNkZDQkIsIEREQURCMEM1LCBGNENBQTNDOCwgNzM2Nzk0NzAsIDg3QUUyRThFLCBFQUE2QURBNCwgRjMwQ0NBNzksIDJCMkZFRDY1LCA5QjU1QTI1RCwgNzMxN0E2REIsIEQ1MDU5MjlDLCAwRjkwQzY5MywgNUNFRDM5N0MsIEMxQ0IwQUI5LCBDODE4OTVGMSwgODI4RDY4QkYsIEMyRDBEODU1LCA3MDU4NUQ4NiwgMUFDRDQxQjEsIEQ4MjI3Qjc2LCAxQ0I2REQ2OSwgQjcxRUYxODUsIDNFQjExNjU2LCA2Njc0Mzc4QSwgQkE1NDM2ODIsIDg5NUE0NjRFLCBCOUU2Q0M0OCwgRkRBQjY2NTcsIEFCODE1RjNCLCBBNzE3QUY1NSwgNTgyNkFCQUIsIDdDQUY3REExLCAzM0VCMjZDMCwgOTM2N0E0OEYsIDMyMzM0ODg4LCA2QkQzNUY3NiwgMjFGNTZBMTMsIEI3RTcyQjUxLCAyQjExMEZDMiwgQTdBNkVENkYsIDFCMkU3MkQxLCA4NTVFQzFGMywgQTMyMEY5MkUsIDA1NjA5NjAzLCA1QUEyNjA4MiwgOTM3QkI0MTcsIEY3QTA4MkVGLCAzNzA2OTBBOCwgMDc0QjRDMDAsIEVGQjJFRjE0LCBBNDQ5QjlGOCwgOUFBN0U4QTgsIDNBRUM0MTA4LCBFNUREREIyQSwgQzJDQzREMzAsIDg1ODlFQjNELCAwMzBFRDgzRSwgNDIzMEU5QjMsIDYxOUIwM0MwLCBFMkIyQkI2NCwgODM5QTdDNDAsIDI1MjdCMTYyLCBEMDM5ODdENiwgRjhENjY0MjQsIEI5NTA5NjhGLCBGNDFFNEQyMSwgOUJBRUVDODksIERCOEM2NUNELCBEMTlGMDM3MSwgNDI1MDc2NzIsIEYxMzNENkRDLCA4RkYxMDMwMSwgNjI2N0UwOTQsIDMzOUExRDVELCAzREQ5RERFMywgMTM5QUE4MzksIDQ0MEY4QTk0LCA1RTEwQ0VBRiwgNjBBMUJBNzgsIDAyNTc2OTY4LCA5QUU3RDgxRSwgQjlCRjY0N0UsIEYxNjk4RUMxLCA1RUM0ODkwQiwgODhDRjFBODcsIDlGMzQ0MkFELCA0RUQ3REI5QSwgMDhCRDIwQzQsIERBNEIyRjhFLCA3RUUwMThBOSwgNDE5Njg4MTcsIDUxOUJFMzJDLCAyNkNDM0VGRCwgMUMzQ0JDQkIsIDU1MUZDMDkwLCBEMDY2NzZEOSwgMDJCRjRFM0YsIDVCMzMxOTE3LCBBQTEyMTAyMCwgODQwQjg0REQsIDFDMDREQjI2LCA0MkRDMDQ5QSwgNThFOTI3ODEsIDk1REE4OTg0LCBDRURGRjE4NSwgMTQ5QTQzRTUsIDlCNENBQUU3LCA5RTYxQ0ZGQywgQzMzRjk0ODUsIDJBQkZFOTc1LCA3NUY4RTkxNSwgMTY3RDdBNjAsIDEwODZBQkY5LCBGRTBCODdEQywgMDk1RUZBMjAsIDc5RkM3MjBDLCA5OURCNzQzRSwgOEY0QjJGMTksIDAwQTkxODhBLCBCNURFN0MyRCwgREFGMzczNEIsIENDQUQxRjQ3LCAwQzlEQjU0OSwgMDE1OEQ1NUMsIEJDRDVGMTUxLCA3MkEyMTBEOSwgQUJCODBDMDksIDk5OTM0QjM5LCBGOTJERjI4MSwgQTM1MTkzQkQsIEMzQ0I0RThCLCAzMjJEQkVFNCwgMjZFMkUzMEQsIDM2RjI1RURELCBGMUM4QzVEQywgNDRCNUM4MzYsIDg3ODA3NUVELCAxMTQwODQ5QywgREVCQTI4NDgsIDZCOEQ0QUQ3LCAwMjA5ODgzQSwgQUVGRkRDOEIsIEY3ODYyOTQ0LCBGMkNBRTRBQiwgNzdBMUVCMjEsIEM3N0Q2MzUwLCA0NzQ5QUEyMywgMUVDREZEM0MsIDU1RDY5NDNDLCBGQzlCMTAyQSwgODAzNjNFODAsIEMyOEU1MzY5LCA3RTRCREMxNiwgOERERDMyMUUsIDQ2RTRCODQ0LCA3MTE2OTU5NiwgNkVDNzg4Q0EsIDUwOEUyNUQ0LCBBMzI0OTM3OSwgQzU0OTM4NDgsIDY3RUNGRkRCLCBGNkIwMzUxOCwgRDRGRTJBN0QsIEQ2QzhENzM5LCA3QTkzRUMxNywgODRFMkE3OTcsIDA4Q0I2RjIyLCBEMDlENUJGRiwgN0ZGNzgzRkQsIDc0OUE0QUE3LCA5RUU2OTczOSwgMDFCQjg3RUQsIENEQjE1MDg3LCAzMkZFNjI1RiwgM0M4RTcyQzYsIDIzODZBMjZFLCAwRjI0Mzg0NywgRjlFNTA4OTAsIEQxMEYxRUM1LCA2RTFDMDMyRCwgQ0UyN0I1OUIsIDg0RjI0NDdCLCA2MkFGRDIzQiwgMjM2MUI3N0MsIDE1MzJFMkY1LCBCQzY1RjY5MSwgRDgxMDY3NzEsIEJDOUY4NTUzLCA5NEI2Nzc5MCwgQ0U3RjRCMzIsIEUzNkRBQTg1LCBENDIzMzZDMSwgNDE0QUJGNDIsIEY1RDVFN0ZBLCBCMTc2MjBBNCwgRDQyQTVENkMsIEUxMTE4NDI1LCAxN0M0QjNGMiwgRUJEQ0IwNkUsIDFGOEY3RjY1LCAwQUQ4OTQyMywgMzI4NDhFNUQsIDBBNTAyOEQwLCA0NjNCNzFCMSwgRTg5NjAxN0YsIEMxREE3NTBDLCBEQjg5RkM1NCwgQUY2NjVBMTcsIDExRjVBNDQ2LCA0NUYyREQ1OCwgOUM2NjM0MEEsIEY0REIxRDE5LCA4N0FGRkQ4OSwgNzVDQTQ5NUQsIERFNjA4MTEwLCA3OEVDOUY1QywgNzg0MEZFN0MsIDZGNERBMjMxLCAxQ0YyRTgzMCwgQ0Q1MjE3OTQsIENFNEY1RUJBLCA3OUI3OTQzNywgNUE5MUQxOEUsIDk1RjFEMTM5LCBEOUNBMTEwMiwgRTM4MjJFQjMsIEY3QzUyRDIwLCBGOTE3QUVFRSwgNUVEQ0Q3QkYsIDRCRDM3MjVDLCA5NEVFMzQ0MSwgNzEzQ0Y1REYsIDkzN0UxQUE5LCAwODkyNjU2MiwgMDg0RThERDQsIDQxMTAwNTQ3LCAxQzcwNkZGNiwgMkVENjAyOTgsIDBEMkUzMEJBLCA4MkZFQ0IxRiwgODMxQkNDRTgsIDBDQjgyOURCLCAwQzUyMjk5OCwgRTBBRDkyRjYsIEY4OTY5RUE0LCAzODY2NTBDRCwgQ0E0MUY3NjMsIDdCQjM0MDY1LCBENzlCOUY4MSwgOTY3RkJCMTcsIDdDMkY2MUIyLCA3QjRFOUIzMywgODM1OUVEREEsIDMyMDFEMjVFLCA1RjQxQkFBNiwgRDk0QTFGRDgsIDZFMjlGMTEyLCBFREI3ODg1QywgQzRGNDM4MEQsIERBRDQyOEM3LCA0MDYwOUE4OCwgNjZERjlBNkMsIEQ2MUI4NEU0LCBDNEM3NzQzNiwgRDZGNEIyMDEsIDFDMEFEMkQ0LCAzQTY5RDIxNiwgMURENzBGNDMsIEM4ODdFNzlDLCA4NTc5RDk0RSwgRjJEMDY5RUEsIDE3QjQ5MjZGLCA1NUJFMTUzQywgQTc4M0Y0NDIsIEMwM0Q1M0QyLCA1RUQ1NjYyNywgQzExNERCNjEsIDlCMEJGRDJDLCA4MjVEREUzNCwgOTc1MjNGMzUsIEVFNDc2RTAwLCBFQjJFRDUwQywgNTY3QkIwNzgsIDlCNzA1MjBELCBEQzk2NjY4QiwgRkNGRDcyNTMsIDAxOTdFM0Y4LCA3Nzg1ODI1RSwgMEIwMDMyMkMsIEI1MTBGODA5LCA1MUZCOTJFRSwgQjZGN0QzMzEsIDJERTBBQzMyLCAwMEI0MUE3QiwgQTQzMkIxRkUsIDk0RUQ5NTc4LCA0QjU2RjA4NiwgRjhCRUFERTEsIDhDODk5REYyLCBFQUIxNzgwOCwgMjQwQkY3MzYsIDdDQkE3NUUwLCBFMDZFMzUyQywgM0JCRDk0RTUsIDQyN0NCODZBLCAzMUNCMzQ1RSwgQzEyMjZFRTMsIEY5RjQ2OTdCLCA4ODIwQ0JCNiwgQzNGOUJCNEMsIDUwOUQ0MDNGLCAwMzk5MEU4RSwgNkM1Q0NEOEIsIDI0RjIzNUMwLCBDNUZDNkU1OSwgMDVFNjI3QzksIDRCMEMwQzk2LCA0NUEzNUU4RSwgQkJGMTQzMzUsIDg5Qjk1N0ExLCAzRTI3MjIwNCwgRUM1MDE5MjcsIDAwQURDQkMzLCAxM0RDOTE5OSwgQTY4MkIzMzgsIEJFNDJEOTdDLCBGOTdFMEYyOCwgOEMxQTYxMjgsIDc2RUQ2OTUxLCBEN0Q4Qjc0RiwgODBBNkM5RDIsIDg3MTExNDEzLCA0ODI2OEVCNSwgNjlEREE2RjcsIDg5MDBCMkUxLCBEQkY4MDlFMCwgRDUwRDdCNDIsIDk3MTY1ODFFLCBBN0FFOUI2RSwgNTIzNjY2MjQsIDg1QkFGOUEzLCBERTI4RjcwQSwgODkwRTM3RUMsIDdGODI1NDFELCA5QkEyQzE0NCwgODc2NkU3MzcsIEVBOEIwRTczLCA2QkM0NkUxQSwgMDRBMkQzRTgsIEYwMTcxNkJCLCAzRDBGNzMzOCwgOTMyODJCQUEsIDNBOUU1MUMwLCA3QjI2QUZCRCwgRkEyQjZBOTAsIDM2REQ1ODMyLCAxODE2MUE3MSwgRkRFNzgzQTIsIEZGODQxODVCLCBDMjUxODY4RSwgOTU3Q0EzM0QsIDZEMkJENDAyLCBGN0U2MUIxNSwgQkFBRDAwNjgsIDg0MTM0NjNBLCA2M0YwRjEzMiwgNTVGQkJDNkEsIDU4RTMyOThELCA4NDVBQTY2NCwgMDJEMjQyQTcsIEE0NTZDRUVELCAyQzE5OEQwNCwgODlBMjU0MjIsIDNBNENBQkZCLCA5RDI0RDc5MiwgREZCQjg1MEYsIDc2RTMwMzMyLCA1OEI1OTcyMywgMUIxQTY5MTMsIDlGQjk2MUU4LCBCMzYzQ0EwNywgOUNDMDFCNjYsIDAwRTlFMURGLCA5QUY0ODA3OCwgRjY3MTY3RDIsIDVEOEVCRTU0LCBGMDgxOUQyRCwgQTAwM0QwNEIsIEJEMjBFMzJBLCA3NjQ3QkQ3MywgREU1MDk1OTMsIEUzODFCRjY3LCBCQjVENTZFMCwgNjc1NjM2QTEsIDk4M0M3QzQ3LCBDN0Q5MkNGOCwgMzM1RjA0NzcsIEE2RUU2Nzg3LCBGMkE2N0QwRSwgMjlEN0Y4M0EsIDNEQTg1QzFGLCA4RTMxRTAxNiwgNUZCRUI3RUEsIDAxRjAxN0E5LCAwMjFCOTNFRCwgOEUyQUU3MzEsIDMzOTFCODJELCA2QUZFQzMxOCwgQzFFOTYxMEQsIEI1MERFMzU4LCA0NkUxNkMxRiwgRDdBMDNFOEEsIDc0RTUyMDQ0LCA0Nzk3QkNCQywgNDlGQzI0QkMsIDExOUY3MUNCLCA1MUFEQjlBQywgMUY3QTg2NDEsIDM3MzkxMUE2LCA3OTQyNDU4NCwgMkQ2OUEyOTcsIDMyODU5RTBCLCBGRjgxMkIwMiwgMjA2MDMwN0UsIDZBRDkxNzNFLCBBRkNCODREQSwgNEY1QjcwRDAsIDM0QTYzRDkzLCA2REJENjM4OCwgQkJENzZDRkEsIDk0RUU1NDgzLCAyMDIxNEMzRiwgRTQ1QjlCNzcsIDhCMzE5MkQ5LCAxMDlEOENFNiwgOEVCQTMyMEIsIDUzRkE4Q0UyLCA1NkE0QTQ1QSwgNjFBQjhGREIsIDNBQkZEMEVCLCBGOTJFNUY5MSwgM0NCQTI1RkUsIEMyRTE5MzE4LCAyRTVEQzFENiwgNzUxQzI1REIsIDU3MkJCQTQ3LCBERjUzQUIxOSwgNDA3RjYyM0YsIEVCOUU0RUU2LCBDOThFOUJGRCwgREE3N0E0OEYsIDc5RDRCNEQyLCBFNDMyMDU2MywgMkMxQzRCQTQsIENEQ0NENEE5LCA1Qjc0NjYyRiwgM0I3NEI4QzEsIEIxNzkyODgzLCA4OEQ1M0JEQSwgRkRGQUI5NTEsIEQyRDNGODQ0LCAxOTlENDdFMSwgNzUwMEU0MzIsIEIwQzcxNEJELCBFQzVDQ0RDQiwgRUM5NDk4MDgsIDlCMzlENjdGLCAxNUQxMzhCOCwgMTdGRTU0QTQsIEFEMjhDNzY4LCBGRTQ3M0JGNywgQUUyOUNCMTAsIEM5ODdBNDc4LCBFRTUwRDA5NCwgMTBFRDU0NDcsIEUyQkY3Q0NGLCBCREQ5MzcwOCwgRDU3RTZDMUIsIDAxMDc5RDRCLCA2QzZDNTQ3RiwgMzYzQTM3RjMsIDZENEQ4MjhBLCBFRTE2MjJERSwgQUYxRDgyNDAsIEIwNjhFNEMxLCA5QzU5MDFGOCwgMTc4MjIxMTksIDNDNzgzN0IwLCBERUZGRDk5MywgMjhGQTlDM0EsIEVBQUREQzRFLCAwNTcwNTQwMCwgMDA0NkNCMTcsIEU4NDMzNDZELCAyRjMzQzQxOCwgQUYxQTQ3QkQsIEU0QzEyQjlFLCBCQzNGOUIxNSwgMDFFOTBDNzQsIERFMEM4QTAwLCA1RDUyNTg3QV0) (The permalink might be too long for some browsers.)
### Background
The most random thing about the LCG is that it is considered a PRNG. For starters, the lower **k** bits of the state aren't affected by the higher **32 - k** bits, making it an exceptionally poor choice for most applications. In particular, the LSB of an updated state is only affected by the LSB of the previous one, and since **1103515245** and **12345** are both odd, the generated numbers will follow an even-odd-even-odd pattern.
The flaws of Xorshift are more subtle, but the generated bits still follow simple linear equations. Given five consecutive generated words **wk, wk+1, wk+2, wk+3, wk+4**, the (non-linear equation)
**wk+4 = wk+3 ⊕ wk+3 >> 19 ⊕ wk ⊕ wk ≪ 11 ⊕ (wk ⊕ wk ≪ 11) ≫ 8** holds by definition. If we enumerate the bits of the words (**0** being the lowest, **31** being the highest), we can observe that the (linear) equation **wk,20 ⊕ wk,31 ⊕wk+3,31 ⊕ wk+4,31 = 0** holds. To verify this, it suffices to observe that words that have been shifted to the right cannot affect **wk+4,31**, the most significant bit of **wk+4**.
That leaves the Mersenne Twister. While there are better (faster, less biased, or both) PRNGs, identifying data generated by MT19937 is a lot more complicated than it was with LCG and Xorshift. Fortunately, we don't have to. If the data doesn't fit any of the two previous patterns, it was generated by the Mersenne Twister.
### How it works
```
^Ḋṫ4^^æ«11$æ»31ż&2\ḂS<4 Main link. Argument: A (array of integers)
Ḋ Dequeue; drop the first integer.
^ XOR the k-th element of A with the k-th element of the
previous result, effectively computing the XOR of all
neighboring integers in A.
ṫ4 Tail; drop the first three elements of the result.
^ XOR the remaining integers with the corr. integers in A.
æ«11$ Yield the integers in A, shifted 11 times to the left.
^ XOR the results to both sides.
æ»31 Shift all results 31 times to the right.
&2\ Yield A, pairwise reduced by bitwise AND.
ż Zip the results to both sides.
Ḃ Bit; compute their parities.
S Sum; add the parities of the results left and right to ż.
<4 Compare the sums with 4.
This is necessary since A and the various modifications
with dropped elements have different lengths, which
introduces a few garbage values.
```
] |
[Question]
[
In graph theory, a [Cactus](https://en.wikipedia.org/wiki/Cactus_graph) is a connected graph such that any distinct two simple cycles in the graph share at most one vertex.
Here is a Cactus with 3 simple cycles outlined with dashed lines.
[](https://i.stack.imgur.com/40a39.png)
The following graph is similar to the one pictured above but is not a Cactus because the two vertices labeled in red are shared by two simple cycles.
[](https://i.stack.imgur.com/lg4hN.png)
Things can get a little bit trickier, for example the following graph:
[](https://i.stack.imgur.com/xLdUq.png)
Might look like a Cactus but it is not. This can be shown by highlighting the following cycle:
[](https://i.stack.imgur.com/3ZJnW.png)
This cycle shares more than one point with a lot of the more obvious cycles in the graph.
### Definitions
* A connected graph is a graph such that there exists at least one path between any two vertices.
* A simple cycle is a path on a graph that starts and ends at the same vertex and visits no vertex more than once.
* A simple graph is an undirected, unweighted graph such that no vertices are connected two each other by more than one edge and no vertex is connected to itself. A simple graph is the most basic type of graph and is what most people mean when they say graph.
# Task
Take a simple graph as input and decide whether it is a Cactus graph. You should output two distinct values one for True and one for False. You may take input in any format you see fit.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so you should aim to minimize the byte count of your answers.
[Test Cases](https://gist.github.com/Wheatwizard/5cbaf2b496f40d7be4aade412f25153a)
[Test Cases as Adjacency Matrices](https://gist.github.com/Wheatwizard/d147308c59ca9e38477eccdbddeabf10)
[Answer]
# Mathematica, 62 bytes
```
Sort@#==#⋃#&[Join@@FindCycle[#,∞,All]]&&ConnectedGraphQ@#&
```
Checks: `(find all cycles, there are no duplicate edges)` and `(The graph is a connected graph)`
[Answer]
# [Python 2](https://docs.python.org/2/), ~~299~~ 289 bytes
```
j=input()
n=len(j)
Q=range(n*n)
L=N=[[{1<<i%n|1<<i/n}]*j[i/n][i%n]for i in Q]
for _ in Q:N=[[a|b for A,B in zip(N[i/n::n],N[i%n::n])for a in A for b in B if{1}>a&b]for i in Q];L=[L[i]+N[i]for i in Q]
1/all(L[i]*all(A&B|B&C|C&A for A in L[i]for B in L[i]for C in L[i])for i in Q if i%n<i/n)
```
[Try it online!](https://tio.run/##zVVhb9owEP2eX2FlGkpoRJJqtFPWTIK2TJMQW9V9WhZVAUxrltqRbZqy0t/Ozg6EsJKBtn1YhMjL3b2792wHsrm8Y/R4KbGQAoUoMhBclv5WV1Qi/eQ5yIdP7GyHIebtDqtMJVyBX/gMF0@2s3/oromH9o1WsoGwlqqht4KAe0kq8CE6Xjiq@q9fgh2Znd0qUEs6fIHWc@q11STrtXsVZn3yX@1wqXGfhz02duW3nNSa2Wf2v/Xr7/Hr/Znfnfy/8Fvv1Putxnp1h7w5sWHgRzy6EZITegs/caZpLqchodlMWrZBwxRTa2obVyFP6C22aJPaRj8chFH05J@dkdd0oW4ufY6b0wjucQSxeMI4IohQdBUbCt9oHChashgiFeo4XRX8QTJroIhBQGNnoNgK2aokUQUdXT1UEAiTJ//5fdIYVie864dRPyLxEbC3JvtukqaWSjUV6DS6i27jfHHeKHp2VFl/xelWH87XD/amHcxGIE55tZewSsYrdDm4QB8@9XsG4GtyP0sTiZGQYyjXvNUikvuMcYmYcJCYC1V8J2UmAtcVMhl9Zw@YT1KWt0bs3k1cv@212yfHJ@7pm7d@2z81uINy2BgmWhnJsNoUnN8UU3R0MmYZbBKUmdy0DZaOi6ye1loXlthBJd/Itzrk0CGHDnrpx1On2DX93xfo85K3ck4ktjjOuAUVNjpC5jcKFBCfMqHEbdj4McMjice/NJF8HpSHUZ09q3IA7TLDsZilEvSp98goakc4k@gr5uyCPBBBGL3knPHgJUefcR2GTVtHw1LRhpHBUGmZnzvX12YxGwPzRb7X@djfGDI3EFZsOJPolkkIFoPs5U8 "Python 2 – Try It Online") (simulates STDIN to run all test cases at once)
*-10 bytes thanks to @ovs*
Takes input as an adjacency matrix from STDIN.
Outputs by the presence of an error in accordance with [a default output method](https://codegolf.meta.stackexchange.com/a/11908/68261). An IndexError represents non-cactus, and no error represents cactus.
## Theory
A simple cycle can be thought of as two disjoint simple paths between a pair of vertices. Similarly, our conjoined cycles correspond to three distinct simple paths being present between a pair of vertices (better explanation near the bottom of the ungolfed code).
To detect these conjoined cycles, we:
* find all paths between all pairs of vertices, keeping track of the edges using Python sets.
* for each pair of vertices, if three paths are pairwise disjoint, then a conjoined cycle is present.
The first bullet has the side-benefit of making the connectedness easy to test: if a path exists between every pair of distinct vertices, then the graph is connected.
## Potential improvements
If input could be taken via STDIN as `n` followed by `n*n` rows of boolean values, 13 bytes could be saved, but it doesn't feel right.
A lot of generator for-loop code is repeated, so surely there's a better way. I tried `itertools.product`, but that ended up with a net cost of +9 bytes. I might have to go with exec/string-replacement abuse like in [Baba](https://codegolf.stackexchange.com/a/206476/68261), which could especially help with `for i in Q` being used four times.
## Ungolfed Code
Python 2 has two main benefits over Python 3 here:
* `input()` automatically parses the input
* Division is floor division by default.
```
j = input()
n = len(j)
Q = range(n * n)
# Replace each 0 in the adjacency matrix with []
# and each edge with a label such that the element of N representing the edge m→n has the
# same label as the element of N representing the edge n→m
L = N = [
# Each edge label is a 2-hot integer (easiest way to ensure ensure equality in both directions since the graph is undirected)
# Each path's edge sequence is stored as a set of edge labels
# N[i] is a list of paths from vertex i % n to vertex i / n
# N[i] starts out as all possible paths of length 1, i.e. edges
# L[i] starts as the same
[{1 << i%n | 1 << i/n}]
* j[i / n][i % n]
for i in Q
]
# Repeat this n**2 times:
# (In reality, only about log_2(n) times is needed, but there isn't a big performance loss)
for _ in Q:
# Update N from the list of all possible paths of length k to the list of all possible paths of length k+1
N = [
[
# The union of two paths is possible
a | b
# ... for every paths list in N
for A, B in zip(N[i / n :: n], N[i % n :: n])
# ... and for every pair of paths in each of these paths lists
for a in A
for b in B
# Limit the search to be through disjoint paths only
# equivalent to `{1}>a&b == not a&b` because a,b contain only tuples, not integers
if {1} > a & b
]
for i in Q
]
# Update L from being list of all possible paths of length at most k to the list of all possible paths of length at most k+1
# (It really seems like these two generator for-loops can be merged into one for loop, but I couldn't get it to work
# I might be able to store L and N in the same list, but that's super slow performance; hard to test)
L = [L[i] + N[i] for i in Q]
# Raises a ZeroDivisionError iff the result of the `all` call is False
1/all(
# L[i] is falsey ←→ L[i] is an empty list ←→
# no path exists between vertices i%n and i/n ←→ graph is not connected ←→ not cactus
L[i]
* all(
# `A & B | B & C | C & A` is falsey
# → A,B,C are three disjoint simple paths between vertices i%n and i/n
# → AB' and CB' are two cycles that share an edge
# → The graph is non-cactus
A & B | B & C | C & A
# using itertools.product is net +9 bytes last I checked
for A in L[i]
for B in L[i]
for C in L[i]
)
for i in Q
# L is symmetric, and we don't want to check the main diagonal
if i % n < i / n
)
```
## Super-ungolfed code
```
def dot(r1, r2):
return [
path1 | path2
for paths1, paths2 in zip(r1, r2)
for path1 in paths1
for path2 in paths2
# simple paths, so exclude those that share edges
if len(path1 & path2) == 0
]
def mul(paths1, paths2):
return [[dot(row, col) for row in zip(*paths2)] for col in paths1]
def f(adj):
n = len(adj)
paths_length_1 = [
[
[{(min(x, y), max(x, y))}] if entry == 1 else []
for x, entry in enumerate(row)
]
for y, row in enumerate(adj)
]
all_paths = paths_length_1
paths_length_n = paths_length_1
for _ in range(n):
paths_length_n = mul(paths_length_1, paths_length_n)
for y in range(n):
for x in range(n):
all_paths[y][x].extend(paths_length_n[y][x])
for x, row in enumerate(all_paths):
for y, paths in enumerate(row):
# The graph is non-cactus if it is not conneted
if x != y and len(paths) == 0:
return False
# The graph is non-cactus if there exist three piecewise disjoint simple paths A,B,C
# between two nodes because A+B' forms one cycle and C+B' forms the other cycle
for A, B, C in itertools.combinations(paths, 3):
if len(A & B) == 0 and len(B & C) == 0 and len(A & C) == 0:
return False
return True
```
] |
[Question]
[
Let's map some strings to 2d space, fractal style. Your task is to compute a [Hilbert curve](http://en.wikipedia.org/wiki/Hilbert_curve) and lay a string along it.

### Task
The task is to take the single-line input string, and lay it out along a [Hilbert curve](http://en.wikipedia.org/wiki/Hilbert_curve) big enough to contain it, but no bigger. Try to make the byte count as low as possible; this *is* [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") after all!
### Conditions
* Any gaps to be padded with whitespace, but padding is not required at the end of lines.
* The start of the line should be in the top-left corner, and the end in the bottom-left.
* You may create a program or function.
* There may be some new test-cases appearing, so don't hardcode anything!
### Bonuses
Note: Bonuses stack like this: `-50% & -20% on 100B` = `-20% on 50B` or `-50% on 80B` = `40B`.
* -50% If the input is a multi-line string, reverse the process to create the original input. Test cases for the bonus: just use the existing ones (including the bonus test cases!)
* -20% If you strip all unnecessary whitespace from the output (e.g. at the end of a line).
* -5% If you don't pollute the global namespace (you know what I mean!)
### Test cases
```
abcdefghijklmn
adef
bchg
nij
mlk
The quick brown fox jumps over the lazy dog.
Thn f ju
ewooxpm
qckr rs
ui btevo
hlaz
e y
do
.g
```
And for the whitespace-stripping bonus:
```
No hitespac her
Noher
hesc
itpa
```
### Leaderboard
```
/* Configuration */
var QUESTION_ID = 66958; // 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 = 43394; // 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+(?:[.]\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>
```
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
```
[Answer]
## CJam, ~~119~~ ~~117~~ ~~113~~ ~~112~~ 109 \* 0.5 \* 0.8 = 43.6 bytes
*Thanks to Dennis for saving 1 byte.*
Here is a start...
```
{+e`W<e~}:F;q_N-,4mLm]0aa{4\#4e!1=f*\:G[zGGW%zW%G].ff+2/{~.+~}%}@:L/\_N&{N/]z:z:~$1f>sS}{4L#' e]f{f=SF}N*N}?F
```
[Test the forward transform](http://cjam.aditsu.net/#code=%7B%2Be%60W%3Ce~%7D%3AF%3Bq_N-%2C4mLm%5D0aa%7B4%5C%234e!1%3Df*%5C%3AG%5BzGGW%25zW%25G%5D.ff%2B2%2F%7B~.%2B~%7D%25%7D%40%3AL%2F%5C_N%26%7BN%2F%5Dz%3Az%3A~%241f%3EsS%7D%7B4L%23'%20e%5Df%7Bf%3DSF%7DN*N%7D%3FF&input=The%20quick%20brown%20fox%20jumps%20over%20the%20lazy). [Test the inverse transform.](http://cjam.aditsu.net/#code=%7B%2Be%60W%3Ce~%7D%3AF%3Bq_N-%2C4mLm%5D0aa%7B4%5C%234e!1%3Df*%5C%3AG%5BzGGW%25zW%25G%5D.ff%2B2%2F%7B~.%2B~%7D%25%7D%40%3AL%2F%5C_N%26%7BN%2F%5Dz%3Az%3A~%241f%3EsS%7D%7B4L%23'%20e%5Df%7Bf%3DSF%7DN*N%7D%3FF&input=Noher%0Aw%20%20ee%0Ahesc%0Aitpa)
I'm sure there's a shorter way to generate the curve...
### Explanation
First, I define a function to trim some element from the end of an array, because I need that in several places. It expects the array and the element (inside a separate array) on top of the stack.
```
{
+ e# Append the element to the array.
e` e# Run-length encode.
W< e# Discard last run.
e~ e# Run-length decode.
}:F; e# Store in F and discard.
```
Now the majority of the code determines the size of the required Hilbert curve and constructs it as 2D array where the elements are indices along the curve. I construct this based on the following observation:
Consider the 2x2 Hilbert curve:
```
01
32
```
The 4x4 Hilbert curve is:
```
0345
1276
ed89
fcba
```
If we subtract the minimum value from each quadrant (and separate them a bit for visual clarity), we get:
```
03 01
12 32
21 01
30 32
```
This pattern holds for any size. It means that we can construct the next level from the current one, by using as the four quadrants: a) the transpose of the current level, b) the current level itself, c) the transpose along the anti-diagonal, d) again the current level itself. And then we offset them 0, 1, 3, 2 times the size of the current level, respectively.
```
q e# Read input.
_N- e# Make a copy and remove all linefeeds.
,4mLm] e# Take that string's length's logarithm with base 4, rounded up.
e# This is the Hilbert curve level we need.
0aa e# Push [[0]] as the level-0 Hilbert curve.
{ e# Store the Hilbert curve level in L. Then for each i from 0 to L-1...
4\# e# Compute 4^i. This is the offset of the four quadrants.
4e!1= e# Get [0 1 3 2] as the second permutation returned by 4e!.
f* e# Multiply each of them by the offset.
\:G e# Swap with the Hilbert curve so far and call it G.
[ e# Create an array with...
z e# The transpose of G.
G e# G itself.
GW%zW% e# The anti-diagonal transpose of G.
G e# G itself.
]
.ff+ e# Add the appropriate offsets to the indices in each of the four quadrants.
2/ e# Split into a 2x2 grid.
{ e# Map this onto each pair of quadrants...
~ e# Dump both quadrants on the stack.
.+ e# Concatenate them line by line.
~ e# Dump the lines on the stack.
}% e# Since this is a map, the lines will automatically be collected in an array.
}@:L/
```
Finally, we use this Hilbert curve of indices to apply the appropriate transformation to the input:
```
\_ e# Swap the curve with the input and make another copy.
N&{ e# If the input contains linefeeds, execute the first block, else the second...
N/ e# Split the input into lines. The stack now has a grid of indices and a grid
e# of characters.
]z:z:~ e# This is some weird transposition magic which zips up the indices with the
e# corresponding characters from both grids, and finally flattens the grid
e# into a linear list of index/character pairs. Those cells that don't have
e# characters due to trimmed whitespace in the input will be turned into
e# arrays containing only an index.
$ e# Sort the pairs (which sorts them by indices).
1f> e# Discard the indices.
s e# Flatten the result into a single string.
S e# Leave a space on the stack to be trim trailing spaces later.
}{ e# or...
4L# e# Compute the size of the Hilbert curve.
' e] e# Pad the input to that size with spaces.
f{ e# Map this block over lines of the curve, passing the padding input as an
e# additional parameter...
f= e# For each index in the current line, select the appropriate character
e# from the padded input.
SF e# Trim spaces from the end of the line.
}
N* e# Join the lines with linefeed characters.
N e# Leave a linefeed on the stack to be trim trailing linefeeds later.
}?
F e# We left either a space or a linefeed on stack... trim that character from
e# the end of the string.
```
[Answer]
# Python 3, ~~467~~ ~~434~~ ~~423~~ ~~457~~ ~~451~~ ~~426~~ ~~386~~ ~~374~~ ~~342~~ ~~291~~ 304 \* 80% \* 95% = 231.04 bytes
The way this works is that I make the Hilbert curve using a Lindenmayer system and follow the left, right and forward instructions along an array of strings. There are probably many ways this could be golfed better, though; especially in the conditionals and in making the array of strings. (I did attempt `[" "*p for i in range(p)]` but strings don't support item assignment (apparently). If I could get that to work, I could get rid of join, too)
**Edit:** Golfed some of the conditionals with thanks to [Dennis](https://codegolf.stackexchange.com/users/12012/dennis). And I golfed down the array of strings. And a no-byte change because the results were coming out transposed compared to the examples above.
**Edit:** Implemented the whitespace-stripping bonus.
**Edit:** Fixed a bug in my whitespace-stripping code for six more bytes
**Edit:** Since this answer doesn't pollute the global namespace, I get the 5% bonus, according to wizzwizz4 [here](https://chat.stackexchange.com/transcript/message/28529424#28529424).
**Edit:** Changed how `g` is incremented and decremented. Now using `eval()` and `str.translate`.
**Edit:** This answer is now a program instead of a function.
**Edit:** Fixed some bugs from the previous golf.
```
s=input();m=(len(bin(len(s)-1))-1)//2;t=eval("[' ']*2**m,"*2**m);t[0][0],*s=s;x=y=g=0;b="A";exec("b=b.translate({65:'-BF+AFA+FB-',66:'+AF-BFB-FA+'});"*m)
while s:
c,*b=b;g+=(c<"-")-(c=="-")
if"B"<c:x,y=[[x+1-g%4,y],[x,y+g%4-2]][g%2];t[x][y],*s=s
print("\n".join(''.join(i).rstrip()for i in t).rstrip())
```
**Ungolfed:**
```
# hilbert(it) is now implemented in the code with exec("b=b.translate")
def hilbert(it):
s="A"
n=""
for i in range(it):
for c in s:
if c == "A":
n += "-BF+AFA+FB-"
elif c == "B":
n += "+AF-BFB-FA+"
else:
n += c
s=n;n=""
return s
def string_to_hilbert(string):
length = len(string)
it = (len(bin(length-1))-1)//2
hil = hilbert(it)
pow_2 = 2**it
# we use eval("[' ']*pow_2,"*pow_2) in the code, but the following is equivalent
output = [[" "for j in range(pow_2)] for i in range(pow_2)]
output[0][0] = string[0]
x = 0
y = 0
heading = 0
while string: # while there are still characters in string
char, *hil = hil
if char == "-": heading = heading - 1
elif char == "+": heading = heading + 1
elif char == "F":
if heading % 4 == 3: y += 1
elif heading % 4 == 2: x -= 1
elif heading % 4 == 1: y -= 1
else: x += 1
output[x][y], *string = string
array = [''.join(i).rstrip()for i in output]
array = "\n".join(array).rstrip()
print(array)
return
```
[Answer]
# Ruby, ~~358~~ ~~356~~ ~~344~~ ~~322~~ 319 \* 80% \* 95% = 242.44 bytes
This is my Python code transpiled to Ruby. I should write more answers in Ruby. It's a decent language to golf in.
**Edit:** I forgot that functions don't need to be named in this question.
**Edit:** Since this answer doesn't pollute the global namespace, I get the 5% bonus, according to wizzwizz4 [here](https://chat.stackexchange.com/transcript/message/28529940#28529940).
```
->s{l=s.size;m=((l-1).bit_length+1)/2;x=2**m;t=(1..x).map{[" "]*x};t[0][0]=s[0];x=y=g=z=0;d=1;b=?A;m.times{b=b.split("").map{|c|c==?A?"-BF+AFA+FB-":c==?B?"+AF-BFB-FA+":c}.join("")};(c=b[z];z+=1;g+=c<?-?1:c==?-?-1:0;(g%2>0?y+=g%4-2:x+=1-g%4;t[x][y]=s[d];d+=1)if c>?B)while d<l;puts (t.map{|i|(i*'').rstrip}*"\n").rstrip}
```
**Ungolfed:**
```
def map_string(string)
len = string.size
m = ((len-1).bit_length+1)/2
pow = 2**m
output = (1..pow).map{[" "]*pow}
output[0][0] = s[0]
x = y = heading = char_index = 0
chars_in_output = 1
b = ?A
m.times do |j|
a = b.split("").map do |char|
if char == "A"
"-BF+AFA+FB-"
else if char == "B"
"+AF-BFB-FA+"
else
char
end
end
b = a.join("")
end
while chars_in_output < len
char = b[char_index]
char_index += 1
if char == "-"
heading += -1
else if char == "+"
heading += 1
else if char == "F"
if heading % 2 == 0
y += heading % 4 - 2
else
x += 1 - heading % 4
end
end
output[x][y] = string[char_index]
char_index += 1
end
return (output.map{|i|(i*'').rstrip}*"\n").rstrip
```
[Answer]
# JavaScript (ES6), 227 - 20% : 181.6 bytes
```
m=>{for(n=1<<((33-Math.clz32(m.length-1))/2),t='',y=0;y<n;y++,t+=`
`)for(x=0;x<n;x++,t+=m[h]||' ')for(u=y,v=x,h=0,s=n;s>>=1;q||(p&&(u=s+~u,v=s+~v),[u,v]=[v,u]))h+=s*s*(3*!!(p=u&s)^!!(q=v&s));return t.replace(/ +$/mg,'').trim()}
```
*Trying to get the 5% bonus*
```
m=>{for(var n=1<<((33-Math.clz32(m.length-1))/2),t='',x,y=0;y<n;y++,t+=`
`)for(x=0;x<n;x++,t+=m[h]||' ')for(var p,q,u=y,v=x,h=0,s=n;s>>=1;q||(p&&(u=s+~u,v=s+~v),[u,v]=[v,u]))h+=s*s*(3*!!(p=u&s)^!!(q=v&s));return t.replace(/ +$/mg,'').trim()}
```
241 \* 0.8 \*0.95 : 183.16 bigger
**Less golfed**
```
m=>
{
// calc the size of the bounding square, clz32 is a bit shorter than ceil(log2()
n = 1<<( (33-Math.clz32(m.length-1)) / 2);
t = '';
for(y = 0; y < n; y++)
{
for(x = 0 ; x < n; x++)
{
// for each position x,y inside the square
// get the index postion in the hilbert curve
// see https://en.wikipedia.org/wiki/Hilbert_curve (convert x,y to d)
for(u=y, v=x, h=0, s=n; s >>= 1; )
{
h += s*s*(3 * !!(p = u & s) ^ !!(q = v & s));
q || (p && (u = s+~u, v = s+~v),[u,v]=[v,u])
}
// add char at given index to output
t += m[h]||' '; // blank if beyond the length of m
}
t += '\n'; // add newline add end line
}
return t.replace(/ +$/mg,'').trim() // to get the 20% bonus
}
```
**Test**
```
F=m=>{for(n=1<<((33-Math.clz32(m.length-1))/2),t='',y=0;y<n;y++,t+=`
`)for(x=0;x<n;x++,t+=m[h]||' ')for(u=y,v=x,h=0,s=n;s>>=1;q||(p&&(u=s+~u,v=s+~v),[u,v]=[v,u]))h+=s*s*(3*!!(p=u&s)^!!(q=v&s));return t.replace(/ +$/mg,'').trim()}
function Test() { O.textContent = F(I.value) }
Test()
```
```
#I { width: 90% }
#O { border: 1px solid #ccc}
```
```
<input id=I oninput='Test()' value='The quick brown fox jumps over the lazy dog.'>
<pre id=O></pre>
```
] |
[Question]
[
(Literally: "Does this follow/realize the *gismu*-form?")
### Premise
The language [Lojban](https://en.wikipedia.org/wiki/Lojban) is a *constructed language*, meaning in part that all of its words have been created rather than allowed to develop naturally. The semantic base of Lojban are its *gismu*, or root words, which were synthesized by [combining](https://lojban.github.io/cll/4/14/) roots from widely spoken natural languages like Chinese, Hindi, and English. All *gismu* are 5 letters long and follow a certain strict form.
### Information
For our purposes, the Lojban alphabet is:
```
abcdefgijklmnoprstuvxz
```
That is, the Roman alphabet without `hqwy`.
This alphabet can be divided into four categories:
* Vowels `aeiou`
* Sonorant consonants `lmnr`
* Unvoiced consonants `ptkfcsx`. When voiced, these become respectively the...
* Voiced consonants `bdgvjz` (No voiced consonant corresponds to `x`.)
To be a valid gismu, a 5-char-long string must:
1. Be in one of the consonant-vowel patterns `CVCCV` or `CCVCV`, where C represents a consonant, and V represents a vowel.
2. Follow consonant-matching rules.
**Consonant-matching rules for CCVCV words:**
The first two characters must constitute one of the following 48 pairs ([source](https://lojban.github.io/cll/3/7/)):
```
ml mr
pl pr
bl br
tr tc ts
dr dj dz
kl kr
gl gr
fl fr
vl vr
cl cr cm cn cp ct ck cf
jm jb jd jg jv
sl sr sm sn sp st sk sf
zm zb zd zg zv
xl xr
```
Note that this looks rather nicer when separated into voiced and unvoiced pairs. In particular, every voiced-voiced pair is valid iff the corresponding unvoiced-unvoiced pair is valid. This does not extend to pairs with a sonorant consonant; `cl` is valid but `jl` is not.
**Consonant-matching rules for CVCCV words ([source](https://lojban.github.io/cll/3/6/)):**
The third and fourth characters must follow the following rules:
>
> 1. It is forbidden for both consonants to be the same [...]
> 2. It is forbidden for one consonant to be voiced and the other unvoiced. The consonants “l”, “m”, “n”, and “r” are exempt from this
> restriction. As a result, “bf” is forbidden, and so is “sd”, but both
> “fl” and “vl”, and both “ls” and “lz”, are permitted.
> 3. It is forbidden for both consonants to be drawn from the set “c”, “j”, “s”, “z”.
> 4. The specific pairs “cx”, “kx”, “xc”, “xk”, and “mz” are forbidden.
>
>
>
Note that there are 179 possible pairs.
## Challenge
Determine if the given string follows the *gismu* formation rules. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest solution in bytes wins.
**Input**: A string of length 5 from the Lojban alphabet.
**Output**: A [truthy value](https://codegolf.meta.stackexchange.com/questions/2190/interpretation-of-truthy-falsey) if the string can be a *gismu* and a falsey value otherwise.
### Test cases
Valid:
```
gismu
cfipu
ranxi
mupno
rimge
zosxa
```
Invalid:
```
ejram
xitot
dtpno
rcare
pxuja
cetvu
```
More test cases: this [text file](http://students.cec.wustl.edu/~adam/lojban/allgismu.txt) contains all valid gismu, one per line.
I don't really know Lojban, so I suspect the title translation is wrong. Help is appreciated.
[Answer]
# Ruby, ~~302~~ 252 bytes
```
c='[cjsztdpbfvkgxmnlr]'
v=c+'[aeiou]'
z=!1
n=/#{c+v+v}/=~(s=gets.chop)*2
(n==0||n==2)&&289.times{|k|q=[i=k%17,j=k/17].max
z||=(x=s[n,2])==c[j+1]+c[i+1]&&['UeUeJOJOJOJOETJ
:'[i].ord-69>>j&1-j/14>0,i!=j&&q>3&&(k%2<1||q>12)&&!'mzxcxkx'.index(x)][n/2]}
p z
```
A few more bytes could be saved as follows:
Initialize `z` to false using `z=!c='[cjsztdpbfvkgxmnlr]'`. This works but gives the warning `warning: found = in conditional, should be ==`.
Change from a program to a function (I left it as a program because according to the question, shortest "program" in bytes wins.)
**Summary of changes from first post**
Major overhaul of regex/matching part.
Constant 72 changed to 69 so that the lowest ASCII code in the magic string is 10 instead of 13. This enables a literal newline to be used in the golfed version instead of an escape sequence.
Magic string `'mzxcxkx'` replaces arithmetic rules for the 5 prohibited characters in the CVCCV type table.
**ungolfed version**
added whitespace and changed newline in magic string to a `\n`
```
c='[cjsztdpbfvkgxmnlr]' #c=consonants
v=c+'[aeiou]' #v=consonant+vowel
z=!1 #Set z to false (everything is truthy in Ruby except nil and false.)
n=/#{c+v+v}/=~(s=gets.chop)*2 #Get input and duplicate it. do regex match, n becomes the index of the double consonant.
(n==0||n==2)&& #If n==0 (ccvcv) or n==2 (cvccv)
289.times{|k| #iterate 17*17 times
q=[i=k%17,j=k/17].max #generate row and column, find their maximum.
z||= #OR z with the following expression:
(x=s[n,2])==c[j+1]+c[i+1]&& #double consonant == the pair corresponding to j,i AND either
["UeUeJOJOJOJOETJ\n:"[i].ord-69>>j&1-j/14>0, #this expression or
i!=j&&q>3&&(k%2<1||q>12)&&!'mzxcxkx'.index(x)][n/2]#this expresson, depending on the value of n/2
}
p z #print output
```
**Explanation of matching**
The two characters in the input string `s[n,2]`are compared with the character pair of the iterating loop. If they match and the consonant-vowel regex pattern is correct, the row and column values `i,j` are checked for validity. Careful ordering of the consonants helps here.
For CVCCV:
```
i!=j It is forbidden for both consonants to be the same
(k%2<1||q>12) It is forbidden for one consonant to be voiced and the other unvoiced. The consonants “l”, “m”, “n”, and “r” are exempt from this restriction. As a result, “bf” is forbidden, and so is “sd”, but both “fl” and “vl”, and both “ls” and “lz”, are permitted.
q>3 It is forbidden for both consonants to be drawn from the set “c”, “j”, “s”, “z”.
!'mzxcxkx'.index(x) The specific pairs “cx”, “kx”, “xc”, “xk”, and “mz” are forbidden.
```
For CCVCV
A bitmap for each column of the table below is encoded into the magic string, from which 69 is subtracted. For all columns except the last two, only 6 bits are required. For the last two, the higher order bits need to be 1, so a negative number is generated (characters `\n` and `:`) in order to have leading 1's instead of leading zeroes. We don't want to include the last three rows of the table though, so instead of rightshift and ANDing by 1, we rightshift and AND by `1-j/14` which normally evaluates to 1, but evaluates to 0 for the last 3 rows.
The following program (with the same expressions as the submission) was used to generate the tables below (uncomment whichever `if` line is required for the table you want.
```
c='[cjsztdpbfvkgxmnlr]'
z=0
289.times{|k|
q=[i=k%17,j=k/17].max
r=c[j+1]+c[i+1]
#if i!=j && q>3 && (k%2<1||q>12) && !'mzxcxkx'.index(r)
#if "UeUeJOJOJOJOETJ\n:"[i].ord-69>>j&1-j/14>0
print r,' '
z+=1
else
print ' '
end
i==16&&puts
}
puts z
ct cp cf ck cm cn cl cr
jd jb jv jg jm jn jl jr
st sp sf sk sx sm sn sl sr
zd zb zv zg zm zn zl zr
tc ts tp tf tk tx tm tn tl tr
dj dz db dv dg dm dn dl dr
pc ps pt pf pk px pm pn pl pr
bj bz bd bv bg bm bn bl br
fc fs ft fp fk fx fm fn fl fr
vj vz vd vb vg vm vn vl vr
kc ks kt kp kf km kn kl kr
gj gz gd gb gv gm gn gl gr
xs xt xp xf xm xn xl xr
mc mj ms mt md mp mb mf mv mk mg mx mn ml mr
nc nj ns nz nt nd np nb nf nv nk ng nx nm nl nr
lc lj ls lz lt ld lp lb lf lv lk lg lx lm ln lr
rc rj rs rz rt rd rp rb rf rv rk rg rx rm rn rl
179
ct cp cf ck cm cn cl cr
jd jb jv jg jm
st sp sf sk sm sn sl sr
zd zb zv zg zm
tc ts tr
dj dz dr
pl pr
bl br
fl fr
vl vr
kl kr
gl gr
xl xr
ml mr
48
```
[Answer]
# JavaScript (ES6), ~~366~~ 352 bytes
```
g=>((q=3,w=2,r=0,f="mzcscjzjxcxkx",c="bdgvjzptkfcsxlmnr",d=[...c],v="aeiou")[m="match"](g[1])?d.map((a,i)=>d.map((b,j)=>a==b|(i<6&j>5&j<13|j<6&i>5&i<13)||f[m](a+b)||(p+=","+a+b)),p="",q=0,r=w--)&&p:"jbl,zbr,tstcl,cmr,cn,cr,jdr,cfl,sfr,jgl,zgr,zdjml,ckl,skr,cpl,spr,sl,sm,sn,sr,ctr,jvl,zvr,xl,xr,dzm")[m](g[r]+g[r+1])&&c[m](g[q])&&v[m](g[w])&&v[m](g[4])
```
## Explanation
Returns an array containing the last letter (truthy) if it is a valid gismu or `null` if it is not.
A lot of the size comes from the hard-coded `CCVCV` pairs (even after condensing them). It might be possible to find a pattern to generate them but I've spent way too much time on this already! xD
```
g=>
(
// Save the positions to check for the consonant, vowel and pair respectively
(q=3,w=2,r=0, // default = CCVCV format
f="mzcscjzjxcxkx", // f = all forbidden pairs for CVCCV pairs
c="bdgvjzptkfcsxlmnr", // c = consonants
d=[...c], // d = array of consonants
v="aeiou") // v = vowels
[m="match"](g[1])? // if the second character is a vowel
// Generate CC pairs of CVCCV
d.map((a,i)=> // iterate over every possible pair of consonants
d.map((b,j)=>
a==b| // rule 1: consonants cannot be the same
(i<6&j>5&j<13|j<6&i>5&i<13)|| // rule 2: pair cannot be voiced and unvoiced
f[m](a+b)|| // rule 3 & 4: certain pairs are forbidden
(p+=","+a+b) // if it follows all the rules add the pair
),
p="", // p = comma-delimited valid CVCCV pairs
q=0,r=w-- // update the match positions to CVCCV format
)&&p
:
// CC pairs of CCVCV (condensed so that valid pairs like "jb", "bl" and
// "zb" can be matched in this string but invalid pairs like "lz" cannot)
"jbl,zbr,tstcl,cmr,cn,cr,jdr,cfl,sfr,jgl,zgr,zdjml,ckl,skr,cpl,spr,sl,sm,sn,sr,ctr,jvl,zvr,xl,xr,dzm"
// Match the required format
)[m](g[r]+g[r+1])&&c[m](g[q])&&v[m](g[w])&&v[m](g[4])
```
## Test
```
var solution = g=>((q=3,w=2,r=0,f="mzcscjzjxcxkx",c="bdgvjzptkfcsxlmnr",d=[...c],v="aeiou")[m="match"](g[1])?d.map((a,i)=>d.map((b,j)=>a==b|(i<6&j>5&j<13|j<6&i>5&i<13)||f[m](a+b)||(p+=","+a+b)),p="",q=0,r=w--)&&p:"jbl,zbr,tstcl,cmr,cn,cr,jdr,cfl,sfr,jgl,zgr,zdjml,ckl,skr,cpl,spr,sl,sm,sn,sr,ctr,jvl,zvr,xl,xr,dzm")[m](g[r]+g[r+1])&&c[m](g[q])&&v[m](g[w])&&v[m](g[4])
```
```
<input type="text" id="input" value="gismu" />
<button onclick="result.textContent=solution(input.value)">Go</button>
<pre id="result"></pre>
```
[Answer]
# Javascript ES6, 240 bytes
```
x=>eval(`/${(c='[bcdfgjklmnprstvxz]')+c+(v='[aeiou]')+c+v}/${t='.test(x)'}?/^[bfgkmpvx][lr]|[cs][fklmnprt]|d[jrz]|[jz][bdgmv]/${t}:/${c+v+c+c+v}/${t}?!/^..((.)\\2|${V='[bdgvjz]'}${U='[ptkfcsx]'}|${U+V}|[cjsz][cjsz]|cx|kx|xc|xk|mz)/${t}:!1`)
```
I guess this is my work now.
] |
[Question]
[
[There](https://codegolf.stackexchange.com/questions/114219/balance-the-brackets) are [a few](https://codegolf.stackexchange.com/questions/65526/bracket-balancing) questions [on this site](https://codegolf.stackexchange.com/questions/77138/are-the-brackets-fully-matched/77145) about balancing brackets, and checking whether brackets are balanced. I propose it's now time to use those balanced brackets for something!
In mathematics and programming, brackets are like bubbles, isolating everything inside form everything outside so that whatever's inside can do its thing in peace and whatever's outside only sees one object. However, a string of brackets is one-dimensional, while bubbles usually are at least two dimensional. That means that bubbles are free to move around one another as long as they never touch each other or cross between the inside and the outside of any other bubbles.
# Challenge
The input is a string of matched brackets of a single type, either round `()`, square `[]`, curly `{}` or angle `<>`. It's up to you what kind you want your program to accept, and a program that only accepts a single kind of brackets is accepted. (Imaginary bonus if your program can handle any of them, massive imaginary bonus points if it can handle all of them in the same input.) The input cannot contain anything between the brackets, although trailing whitespaces are allowed.
The output is all possible reorganisations (in arbitrary order, and including the original input) of those brackets that yields the same configuration of bubbles, with no two identical strings. That means that with an input of `()()`, the output is also just `()()`, even though it's technically two bubbles that could swap places. For the massive imaginary bonus, an input of `{}[]()` will of course lead to an output of 6 different elements / strings / lines.
Two configurations of bubbles are "the same" if you can make one into the other by moving bubbles around, without letting any bubble cross from inside another bubble to outside it, or from outside to inside. If you liken nested parentheses to trees (each matched pair is one node, and every matched pair within is a subnode, and each matched pair within there is a subnode of those again, and so on) where the subnodes of any given node are ordered, then a single configuration of bubbles is a tree where the nodes are unordered.
Any reasonable output format will do, like returning a list of strings or a list of list of single characters or a single string with some kind of whitespace, or printing to `stdout`or `stderr` with some form of visible whitespace character (most commonly newline or space) between each reorganisation.
Trailing spaces for each reorganisation and trailing and preceeding newlines / empty list elements before and after the actual output is allowed. You should use the same kind of brackets in your output as you accept in your input. Apart from the brackets, newlines and spaces as specified here, and whatever separator you use, nothing should be printed (including invisible / zero-width characters).
The score is the number of bytes in the code; lowest count for each language wins. You may note whether you get an imaginary bonus, either regular or massive, but it doesn't affect your score. Actual bonuses are too hard to balance right.
# Input-output examples
### Example 1:
Input:
```
()(())
```
Output:
```
()(())
(())()
```
### Example 2:
Input:
```
(()())()()
```
Output:
```
(()())()()
()(()())()
()()(()())
```
### Example 3:
Input:
```
(()(()))()
```
Output:
```
((())())()
()((())())
(()(()))()
()(()(()))
```
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 18 bytes
```
{~{_{{B}%e!}&}:B~}
```
[Try it online!](https://tio.run/##S85KzP2f87@6rjq@utqpVjVVsVat1sqprvZ/XcL/6OhYIIqNBQA "CJam – Try It Online")
-2 thanks to [Business Cat](https://codegolf.stackexchange.com/users/53880/business-cat).
Receives input as a string containing only `[]`. Returns a list of permutations (empty lists are the same as empty strings in CJam, so instead of `[]` you'll be getting `""`).
[Answer]
# [Haskell](https://www.haskell.org/), ~~227~~ ~~210~~ ~~208~~ 205 bytes
```
import Data.List
l=last
a!x=init a++[l a++[x]]
h[]=[""]
h(x:y)=["("++z++")"++t|z<-v x,t<-h y]
g(a,r)x|x=='('=(a+1,l$(r++h[]):[r!x|a>0])|1>0=(a-1,l$r:[r!x|a>1])
v s=nub$h=<<(permutations.snd$foldl g(0,[])s)
```
[Try it online!](https://tio.run/##ZYzBasMwEETv/oqNMGQX2cG5BiunHvsHRoctTmNRWTaSYpTgf3flQg@ll5nhPZiBw9fN2m0z4zz5CG8c@fRuQiysspyLD0kZZyKwlJ39yaR1MXRadULkgenypLxRSPmSUlDuuL7aeoFUxbYe4KmLO3LlKa1JqSMeFbI8V7ZEL2U@okvnD2nla6NpPV@brOtd@19@1lQsEJR7fJSDalucb358RI5mcuEUXF9@Tra3cMemyneBtpGNAwX9VADA7I2LUC4CCZFI/GUZEu3xn2ex8@0b "Haskell – Try It Online")
This one was tough!
*Golfed a little bit*
*Saved two bytes thanks to Laikoni*
*Save two bytes thanks to Bruce Forte*
I'm not sure this works in every case. Some explanations:
* `a!x` add the String `x` to the last list of String in `a` (a is of type `[[String]]`)
* `snd$foldl(\(a,r)x->if x=='('then(a+1,last$(r++[[]]):[r!x|a>0])else(a-1,last$r:[r!x|a>1])` uses the [shorter conditional](https://codegolf.stackexchange.com/a/96371/72753) to express the simple idea: split a String on *root* `)(`s. E.g. `"(()(()))()"` gives `["()(())", ""]`.
* We need to process each part of the split, then to gather and join all the strings to get the correct output:
1. `h` processs a list of parts: it applies `v` to the first part and combines the result to the process of the remaining parts.
2. `v` aggregates the results for each permutation of the parts, and remove the duplicates.
*To add a broader view: you have basically a tree (not a binary one) with empty nodes. Leave are `()`. You have to produce all the permutations of the branches for each node, but you may not take a branch from a node and put it on another node. I did a kind of depth first search.*
[Answer]
# Python 2, ~~353~~ ~~350~~ 331 Bytes
```
s=input()
f=lambda i,t=0:i+1if t<0else f(i+1,t-1)if"("<s[i+1]else f(i+1,t+1)
c=[(x,f(x))for x in range(len(s))if")">s[x]]
p=lambda l:[[]]if len(l)<1else[x for y in p(l[1:])for x in[y[:i]+[l[0]]+y[i:]for i in range(len(y)+1)]]
print[''.join(x)for x in p([s[c[x][0]:c[x][1]]for x in range(len(c))if all(c[x][1]>y[1]for y in c[:x])])]
```
Receives string of `()` as input and prints the result.
[Try it here!](https://tio.run/##bVDRTsUgDH3fVxBe1mbTDB/JxR@pfZhzKAbZsmECXz9huXo1MSSl7WnPObDm@LaEh@PYjQvrZwRsrPHjx/PLKFwfzaBdp5wV8TKI2e@zsFAafbxTWLo7lYKNkSh/g53CZjIEqbeQEO2yiSRcENsYXmfwc4AdUZz7qW6D5Gb9VvWaiLmAdc7jRZ26lESlyZVmBU9K842XMmnHHXkamLtMTnPF3F/NjMUXF6XNhdg@hfb@fXEBqL0m6Ua4Au00FXOFUJ@3Yv7nGRPWXxi9h@vQYy7hx@hEOjHWcxwSABFQfgE)
I avoided using `itertools.permutations` with help from [Paolo's](https://stackoverflow.com/users/2536705/paolo) answer to [this question](https://stackoverflow.com/a/17391851/5652232).
Thank you to [Business Cat](https://codegolf.stackexchange.com/users/53880/business-cat) for finding 3 bytes, and thank you to [Mr. Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder) for an incredible 19 bytes!
### Explanation
1. Create a list of tuples of the indices of each `()` pair in the input string.
2. Drop any tuples from the list that are surrounded by another `()` pair.
3. Slice the string at the indices of the remaining tuples.
4. Make a list of each permutation of the list of slices.
5. Join the list with a new line for printing.
[Answer]
## JavaScript (Firefox 30-57), 222 bytes
```
s=>(g=a=>a+a?[for(x of g(a[0]))for(y of a.keys())for(z of g(a.slice(1)))(z.splice(y,0,x),z)]:[a])(eval(`[${s.replace(/]\[/g,`],[`)}]`)).map(g=a=>`[`+a.map(g).join``+`]`).sort().filter(s=>t<(t=s),t=``).map(s=>s.slice(1,-1))
```
Takes `[]` strings. Explanation:
```
s=>( Inner function to permute an array
g=a=>a+a?[ If array is not empty
for(x of g(a[0])) Permute the first element of the array
for(y of a.keys()) Generate a list of insertion points
for(z of g(a.slice(1))) Permute the rest of the array
(z.splice(y,0,x),z)]: Make all possible permutations
[a] Otherwise return a list of an empty array
)(eval(`[${ Convert the string to a nested array
s.replace(/]\[/g,`],[`)}]`) ... inserting commas where necessary
).map( Process the results
g=a=>`[`+a.map(g).join``+`]` Recursively convert back to string
).sort().filter(s=>t<(t=s),t=`` Check for duplicates
).map(s=>s.slice(1,-1)) Remove outer `[]`s
```
[Answer]
# Mathematica, 337 bytes
Not to get code-golf points, but to show the usage of `Permutations` and `Distribute` in this problem. There may be better approaches, though.
(`seq` : sequence, `alt` : alternatives)
```
SetAttributes[alt, {Flat, OneIdentity}]
StringTake[
StringReplace[ToString[
ToExpression["{" <> StringReplace[#, "}{" -> "},{"] <> "}"]
/. List -> Permutations@*seq
/. List -> alt
/. seq -> (Distribute[seq@##, alt] &)
/. {seq -> List, alt -> Alternatives}],
{", " -> "", "} | {" -> "\n"}],
{2, -2}] &
```
Take input as a string, using curly brackets `{` and `}`. Output a multi-line string.
] |
[Question]
[
# Can these rectangles fill a rectangular space?
Given a bunch of rectangles, you are asked whether or not they can be arranged to fill a rectangular space.
## Specs
Given a bunch of arbitrary `m x n` rectangles; `0 <= m, n <= 1000`, determine whether or not it is possible to arrange them so that they cover exactly a rectangular area without any holes or overlaps. The rectangles cannot be rotated, and each rectangle may only be placed once.
## Input
The input for this is very flexible, as long as the input gives some sort of list of 2-space dimensions. For example, both of the following are valid:
### Separated by Space, Return
```
1 2
1 5
4 5
3 6
```
### List of Dimensions
`[[1, 2], [1, 5], [4, 5], [3, 6]]`
## Output
Any sort of true/false values like true/false, 0/1, T/F, True/False, etc. If you are going to use an output method that's not very obvious, please specify in your answer.
## Examples
### Test Case 1
Input:
```
1 1
1 5
2 6
```
Output:
`true` (or something similar)
How to arrange it:
```
XYYYYY
ZZZZZZ
ZZZZZZ
```
### Test Case 2
Input:
```
1 1
2 2
```
Output:
`false` (or something similar)
Explanation: It becomes obvious that you cannot arrange two squares of different sizes and get their edges to line up.
### Test Case 3
Input:
```
1 1
1 2
1 2
2 1
2 1
```
Output:
`true` (or something similar)
How to arrange it:
```
AAB
DEB
DCC
```
As @ETHProductions pointed out, for all of the other test cases, you can keep combining rectangles with a common edge length until you have only one rectangle, so this test case is just to break any code that uses this idea.
### Test Case 4
Input:
```
3 2
4 1
2 1
4 1
2 1
5 2
3 2
1 4
3 2
2 1
2 1
1 1
5 1
```
Output:
`true` (or something similar)
How to arrange it:
```
AAABBBBEE
AAACCDDDD
FFFFFGGGH
FFFFFGGGH
IIIJJKKLH
IIIMMMMMH
```
**Note**: You do not need to state how to arrange it, you only need to determine whether not it can be arranged.
This is code golf, so the shortest answer in bytes wins! I will accept the shortest answer as of January 14th, but feel free to submit answers later than that since I can still give upvotes! :)
Happy golfing!
~ A.L.
P.S. If you know what tag should be applied to this problem, please add it, I have absolutely no idea what to put as a tag other than code-golf.
**EDIT**: Your program should be able to process up to 25 rectangles, in at most 10 seconds on a decent computer (I'll be quite flexible on this rule).
**EDIT**: I've extended the submission acceptance deadline to the last day of the year, but I doubt I'll get an answer by then...
**EDIT**: I've extended the submission acceptance deadline by 2 weeks, so if no more answers come in by then, the current C answer will be accepted! :)
[Answer]
# Haskell, 226 bytes
```
((y,z):l)&(w,x)|x*y<1=(w+y,x+z):l
(q:l)&p=p:q:l
(p@(u,v):r@(y,z):l)%q@(w,x)=[((y-w,z):l)&q&(u,v-x)|w<=y,x<=v]++[p:m|m<-(r:l)%q]
_%_=[]
g m(p:n)l=any(g[]$m++n)(l%p)||g(p:m)n l
g[]_[_,_,_]=0<1
g _[]_=0<0
($[(0,9^9),(9^9,0)]).g[]
```
[Try it on Ideone](https://ideone.com/hou73w)
### How it works
This recursively searches for all partial tilings whose shape is a [Young diagram](https://en.wikipedia.org/wiki/Young_diagram), adding one rectangle at a time, and checks whether any of the final results are rectangles.
To see that any tiling of a rectangle can be built this way: in any tiling of a nonempty Young diagram, let R be the set of rectangles in the tiling whose southwest corner does not touch any other rectangle. Since each concave vertex of the Young diagram is edge-adjacent (not merely corner-adjacent) to at most one rectangle in R, and the number of these concave vertices is one less than the number of rectangles in R, there must be at least one rectangle in R that is edge-adjacent to none of these concave vertices. Removing it yields another Young diagram, so we can proceed by induction.
[Answer]
## C, 1135 ~~1158~~ ~~1231~~ ~~1598~~ bytes
Well, it's past the stated deadline, but seeing as how there are no answers yet, here's one (a bit long) in C.
**Returns:**
* 0 (zero) on failure (don't fit)
* Full fitting matrix on success
---
### Update:
Original code could get stuck on some matrices, taking much longer than the allowed 10s. Current revision should complete all matrices in under 1s. This is accomplished by 1) Sorting the input rectangles and 2) skipping repeated sizes when fitting.
### Golfed:
```
#define R r[i]
#define Z return
#define _(B,D,E) for(int B=E;B<D;B++)
struct{int x,y,u,p;}r[25],*S;int A,M,N,U,V,X,Y;char *P;T(x,y,w,h){_(I,x+w,x)_(J,y+h,y)if(I/U|J/V|P[J*U+I])Z 0;Z 1;}L(x,y,w,h,c){_(I,x+w,x)_(J,y+h,y)P[J*U+I]=c;}F(){int x=0,y;while(++x<A)if(!P[x])break;if(x/A){_(i,V,0)printf("%*.*s\n",U,U,P+i*U);exit(0);}y=x/U;x-=y*U;_(i,N,0)if(!R.u&T(x,y,R.x,R.y))R.u=1,L(x,y,R.x,R.y,'A'+i),F(),R.u=0,L(x,y,R.x,R.y,0);}O(i,y){if(!R.u){if(!T(0,y,R.x,R.y))Z;R.u=1;R.p=0;L(0,y,R.x,R.y,'A'+i);y+=R.y;}if(y-V||F())_(j,N,0)if(j-i&!r[j].u){O(j,y);while(r[j].x-r[j+1].x|r[j].y-r[j+1].y)j++;}R.u=0;L(R.p,(y-=R.y),R.x,R.y,0);}Q(i,x){if(!R.u){if(R.x>U-x)Z;R.u=1;R.p=x;L(x,0,R.x,R.y,'A'+i);x+=R.x;}if(x-U||O(i,1))_(j,N,0)if(j-i&!r[j].u)Q(j,x);L(x-=R.x,0,R.x,R.y,0);R.u=0;}C(int*a,int*b){Z*a-*b?*a-*b:a[1]-b[1];}main(){_(i,25,0)if(++N&scanf("%d%d\n",&R.x,&R.y)-2)break;_(i,N,0){A+=R.x*R.y;if(R.x>X)X=R.x;if(R.y>Y)Y=R.y;}_(i,A+1,1)if(!(A%i)){if(i<Y|A/i<X)continue;M++;S=realloc(S,M*16);S[M-1].y=i;S[M-1].x=A/i;}qsort(S,M,16,C);P=calloc(A+1,1);_(j,M,0){U=S[j].x;V=S[j].y;_(i,N,0)R.u=1,L(0,0,R.x,R.y,'A'+i),Q(i,R.x),R.u=0;}printf("0\n");exit(1);}
```
### UnGolfed:
```
#define R r[i]
#define Z return
#define _(B,D,E) for(int B=E;B<D;B++)
struct {
int x,y,u,p;
} r[25],*S;
int A,M,N,U,V,X,Y;
char *P;
test_space(x,y,w,h) {
_(I,x+w,x)
_(J,y+h,y)
if ( I >= U |
J >= V |
P[J*U+I]) Z 0;
Z 1;
}
place_rect(x,y,w,h,c){
_(I,x+w,x)
_(J,y+h,y)P[J*U+I] = c;
}
fill_rest() {
int x=0,y;
while(++x<A) if (!P[x])break;
if (x>=A) {
_(i,V,0) printf("%*.*s\n", U,U, P+i*U);
exit(0);
}
y = x / U; x -= y*U;
_(i,N,0)
if (!R.u & test_space(x, y, R.x, R.y))
R.u = 1,
place_rect(x, y, R.x, R.y, 'A'+i),
fill_rest(),
R.u = 0,
place_rect(x, y, R.x, R.y, 0);
}
fill_y(i,y) {
if (!R.u) {
if (!test_space(0, y, R.x, R.y)) Z;
R.u = 1;
R.p = 0;
place_rect(0, y, R.x, R.y, 'A'+i);
y += R.y;
}
if (y == V) fill_rest();
else _(j,N,0)
if (j!=i && !r[j].u){ fill_y(j, y);
while (r[j].x^r[j+1].x||r[j].y^r[j+1].y)j++;
}
R.u = 0;
place_rect(R.p, (y -= R.y), R.x, R.y, 0);
}
fill_x(i,x) {
if (!R.u) {
if (R.x > U - x) Z;
R.u = 1;
R.p = x;
place_rect(x, 0, R.x, R.y, 'A'+i);
x += R.x;
}
if (x == U) fill_y(i, 1);
else
_(j,N,0)
if (j!=i && !r[j].u) fill_x(j, x);
place_rect((x -= R.x), 0, R.x, R.y, 0);
R.u = 0;
}
C(int*a,int*b) {
Z *a^*b?*a-*b:a[1]-b[1];
}
main() {
_(i,25,0)
if (++N&&scanf("%d %d\n", &R.x, &R.y)!=2) break;
_(i,N,0){
A+=R.x*R.y;
if(R.x>X)X=R.x;
if(R.y>Y)Y=R.y;
}
_(i,A+1,1)
if (!(A%i)) {
if (i < Y | A/i < X) continue;
M++;
S = realloc(S,M*16);
S[M-1].y=i;
S[M-1].x=A/i;
}
qsort(S, M, 16,C);
P = calloc(A + 1,1);
_(j,M,0){
U = S[j].x; V = S[j].y;
_(i,N,0)
R.u = 1,
place_rect(0, 0, R.x, R.y, 'A'+i),
fill_x(i, R.x),
R.u = 0;
}
printf("0\n");
exit(1);
}
```
**Explanation:**
We have 6 functions: `main`, `O`, `Q`, `F`, `L` and `T`. `T` **t**ests to see if there is space for the rectangle at a given spot. `L` fil**l**s a rectangle into the output buffer or, alternately removes one by overwriting it. `O` and `Q` build up the left and top walls, respectively and `F` **f**ills the remainder of the rectangle by iterative search.
Although the basic search is iterative, we eliminate the vast majority of possible search vectors, first by building up the allowed combinations of width and height for the master rectangle and then eliminating impossible configurations. Additional speed could be gained in larger rectangles by determining bottom and right walls prior to filling the center but it is not required for decent speed when limiting to 25 interior rectangles.
] |
[Question]
[
The idea of this challenge is to find all the words from a dictionary on a grid of letters. Your input should come from stdin or function arg and will come in the following format:
```
[your dictionary as a list of space sep words]
[a grid of letters]
Example:
The cool car
looc
thea
jopr
```
### Rules for finding a match
A match is valid if it is found diagonally, horizontally, or vertically on the board (case insensitive). The direction doesn't matter (e.g. `look` matches `kool`). If there are multiple matches of the same word, mark all of them.
### Output:
Your output will be the grid you were given - with the minor change that the letters will be space separated and the lines will be double spaced. Example:
```
Input:
looc
thea
jopr
Output:
l o o c
t h e a
j o p r
```
To represent a match you will put an arrow between letters that go together. The arrows (`/\-|X`) will point to each pair of letters that are grouped in a match. `X` is used if `/\` intersect.
### Examples:
```
Input:
The cool car
looc
thea
jopr
Output:
l-o-o-c
|
t-h-e a
|
j o p r
Input:
Atomic chess is cool
achess
btoikm
bloosi
nowmlp
hewiir
asdfec
Output:
a c-h-e-s-s
\ \ /
b t o i k m
\ \ \
b l o o s-i
\ \
n o w m l p
\
h e w i i r
\
a s d f e c
Input:
This is very neat words var are fun rob bot robot
wotsdsearn
siiewfvery
chheruoawd
tetoennore
asbdrgrehe
aobyedycab
tweosttgwt
Output:
w o t s d s e a r n
/
s-i i e w f v-e-r-y
/ | \
c h h e r u o a w d
/ / | X
t e t o e n n o r e
/ X \
a s b d r g r e h e
/ / \
a o b y e d y c a b
/ / \
t w e o s t t g w t
```
[Answer]
# JavaScript (ES6), 303 ~~315~~
Mostly based on [this answer](https://codegolf.stackexchange.com/a/37974/21348)
**Edit 1**
* Following OP comment, ignoring casing and forcing all to lowercase.
* Fixed the arguments, now just a single string argument that get splitted
Note: using template strings, there are 3 newlines in the code that are significant and incuded in the byte count
```
l=>(l=l.toLowerCase().split`
`).shift(r=l[1].length*4).split` `.map(v=>[2,-2,r,-r,r+2,-r-2,r-2,2-r].map((d,k)=>o.map((t,p)=>[...v].some((c,i)=>z[i?(z[i=t+d/2]=z[i]>' '?'X':'-|\\/'[k>>1],t+=d):t=p]!=c,z=[...o])?0:o=z)),o=[...l.map(s=>' '.repeat(r/2-1)+`
${[...s].join` `}
`).join``.slice(r/2)])&&o.join``
```
**Explained** (outdated)
```
// Note a pattern : in golfed code (but not in the following explanation),
// simple operations that have to done before calling .map or .every
// are inserted as parameter 2,3,etc... to the same function
// as each parameter is evaluated before calling a function
//
F=( l, // word list as a space separated string
o, // character grid as a newline separated string - each row is the same length
// default parameters used as local variables
r = 4 * o.search`\n` // offset from a line to next nonblank line in resulting output
)=>(
w = ' ', // shortcut for blank
// given the input string in o, build the result as a single dimension array filled with blanks
// between characters and runs of blank chars betweem each row
// .map used as a shorter .forEach
z = w, // init z to a single blank
[...o].map( c=> // for each char of o execute the following
c > w // check if c is a letter (>' ') or a newline
? z+=w+c // if c is a letter, add ' '+c to z
: ( // if c is a newline add chars to array o
z = z.slice(2), // remove the first 2 char of z (' ' or '\n ')
z = [...z], // convert to array
o.push(...z, // push one by one the chars of z
c, // then c (a newline)
...z.fill(w), // the same number of char as z, but all blanks
z = c // a newline again, meanwhile reset z
)
)
, o=[] // o is reset to an empty array just in the map call
// reusing o just to avoid another global variable (no real need in fact)
), // end of .map call
l.split` `.map( // split l into words and exec the following for each word
v => [2,-2,r,-r,r+2,-r-2,r-2,2-r].map( // for each scan direction
(d,k) => // d is the move offset , k is the index 0 to 7
o.map( // for each char in (including fill blanks and newlines, the scan will fail for them)
(t,p) => // t is the first character but NOT USED (var t reused), p is the start position
(
z=[...o], // make a copy of o in z
t = p-d, // current position-d goes in t, it will be incremented before using
[...v].every( // check the following conditions for every char of word v
(c,i) => // c: current char of word, i: index used to differentiate the first check when i==0
(
// while scanning I already modify the result working copy in z
i ? // if i != 0
// fill the intermediate position with the right fiil character
// based on direction index in k, or X if the position is already full
z[i = t+d/2] = z[i] > w ? 'X' : '--||\\\\//'[k]
: 0, // else do nothing
// case insensitive comparison, if not a letter parseInt returns NaN that is != from any value
// this is the condition retured to the .every function
parseInt(c,36)==parseInt(o[t+=d],36) // meanwhile increment position in T
)
) ? // check the result of .every
o = z // if true, update o from the working copy
: 0 // if false do nothing
) // end of o.map operations
) // end of o.map function call
) // end of direction list map function call
) // end of l.split.map function call
, o.join``
)
```
**TEST**
```
console.log=(...x)=>O.textContent+=x.join` `+`\n`;
F=l=>
(l=l.toLowerCase().split`\n`)
.shift(r=l[1].length*4).split` `.map(v=>[2,-2,r,-r,r+2,-r-2,r-2,2-r].map((d,k)=>o.map((t,p)=>
[...v].some((c,i)=>z[i?(z[i=t+d/2]=z[i]>' '?'X':'-|\\/'[k>>1],t+=d):t=p]!=c
,z=[...o])?0:o=z)
),o=[...l.map(s=>' '.repeat(r/2-1)+`\n${[...s].join` `}\n`).join``.slice(r/2)])
&&o.join``
console.log(F('Atomic chess is cool\nachess\nbtoikm\nbloosi\nnowmlp\nhewiir\nasdfec'))
console.log(F("RANDOM VERTICAL HORIZONTAL WIKIPEDIA Tail WordSearch CODEGOLF UNICORN\nWVERTICALL\nROOAFFLSAB\nACRILIATOA\nNDODKONWDC\nDRKESOODDK\nOEEPZEGLIW\nMSIIHOAERA\nALRKRRIRER\nKODIDEDRCD\nHELWSLEUTH"))
```
```
<pre id=O></pre>
```
[Answer]
# Javascript (ES6), ~~908~~ ~~901~~ ~~609~~ ~~603~~ ~~556~~ 552 bytes
```
a=>(a=a.toLowerCase().replace(/\n/g,`
`).split`
`,b=a.slice(2).map(r=>r.length?r.replace(/./g,i=>i+` `).trim().split``:Array(a[2].length*2-1).fill(` `)),a[0].split` `.forEach(c=>{for(y=0;y<b.length;y+=2){for(x=0;x<b[y].length;x+=2){c[0]==b[y][x]&&(d=[-2,0,2]).map(l=>{d.map(k=>{e=`\\|/
-o-
/|\\`.split(`
`)[l/2+1][k/2+1];try{(f=(g,h,j)=>g>=c.length?1:(ch=c[g],((k||l)&&b[j+l][h+k]==ch&&f(g+1,h+k,j+l))?(b[j+l/2][h+k/2]=((b[j+l/2][h+k/2]=='\\'&&e=='/')||(b[j+l/2][h+k/2]=='/'&&e=='\\'))?'x':e):0))(1,x,y);}catch(e){}})})}}}),b.map(r=>r.join``).join`
`)
```
Ungolfed:
```
inp => (
inp = inp.toLowerCase().replace(/\n/g, `
`).split `
`,
puzzle = inp.slice(2).map(r => r.length ? r.replace(/./g, i => i + ` `).trim().split `` : Array(inp[2].length * 2 - 1).fill(` `)),
inp[0].split ` `.forEach(word => {
for (y = 0; y < puzzle.length; y += 2) {
for (x = 0; x < puzzle[y].length; x += 2) {
word[0] == puzzle[y][x] &&
(dirs = [-2, 0, 2]).map(ydir => {
dirs.map(xdir => {
symb = `\\|/
-o-
/|\\`.split(`
`)[ydir / 2 + 1][xdir / 2 + 1];
try {
(findWord = (chnum, xcoord, ycoord) =>
chnum >= word.length ? 1 : (
ch = word[chnum],
((xdir || ydir) && puzzle[ycoord + ydir][xcoord + xdir] == ch && findWord(chnum + 1, xcoord + xdir, ycoord + ydir)) ?
(puzzle[ycoord + ydir / 2][xcoord + xdir / 2] = ((puzzle[ycoord + ydir / 2][xcoord + xdir / 2] == '\\' && symb == '/') || (puzzle[ycoord + ydir / 2][xcoord + xdir / 2] == '/' && symb == '\\')) ? 'x' : symb)
: 0
)
)(1, x, y);
} catch (e) {}
})
})
}
}
}),
puzzle.map(r => r.join ``).join `
`
)
```
**Test (should work with modern browsers that have some ES6 support):**
```
func=a=>(a=a.toLowerCase().replace(/\n/g,`
`).split`
`,b=a.slice(2).map(r=>r.length?r.replace(/./g,i=>i+` `).trim().split``:Array(a[2].length*2-1).fill(` `)),a[0].split` `.forEach(c=>{for(y=0;y<b.length;y+=2){for(x=0;x<b[y].length;x+=2){c[0]==b[y][x]&&(d=[-2,0,2]).map(l=>{d.map(k=>{e=`\\|/
-o-
/|\\`.split(`
`)[l/2+1][k/2+1];try{(f=(g,h,j)=>g>=c.length?1:(ch=c[g],((k||l)&&b[j+l][h+k]==ch&&f(g+1,h+k,j+l))?(b[j+l/2][h+k/2]=((b[j+l/2][h+k/2]=='\\'&&e=='/')||(b[j+l/2][h+k/2]=='/'&&e=='\\'))?'x':e):0))(1,x,y);}catch(e){}})})}}}),b.map(r=>r.join``).join`
`);
```
```
<textarea id="_input">Atomic chess is cool
achess
btoikm
bloosi
nowmlp
hewiir
asdfec</textarea>
<br />
<button onclick="document.getElementById('_output').innerHTML = func(document.getElementById('_input').value)">Run!</button>
<br />
<pre id="_output"></pre>
```
[Answer]
# Python 3, 1387
```
k=input().lower().split(" ")
a=[]
while 1:
a.append(input())
if not a[-1]:a.pop();break
b=sum([[list(' '.join(list(i))),[' ']*(len(i)*2-1)]for i in a],[])[:-1]
w,h=len(a[0]),len(a)
for l in range(h):
r=a[l];c=list([1 if w in r else 2 if w in r[::-1] else 0, w] for w in k)
for t,v in c:
if not t:continue
if t==2:v=v[::-1]
i=r.index(v)
for m in range(i,i+len(v)-1):b[l*2][m*2+1]="-"
for l in range(w):
u=''.join(x[l]for x in a);_=list([1 if w in u else 2 if w in u[::-1]else 0,w]for w in k)
for t,v in _:
if not t:continue
if t==2:v=v[::-1]
i=u.index(v)
for m in range(i,i+len(v)-1):b[m*2+1][l*2]="|"
def d(g,r=1,o=0):
if g>=len(a[0]):o=g-w+1;g=w-1
f=range(0,min(g+1,h-o));return[a[i+o][w-1-(g-i)if r else g-i]for i in f],[(i+o,w-1-(g-i)if r else g-i)for i in f]
for l in range(w+h-1):
x,c=d(l);_=''.join(x);z=list([1 if w in _ else 2 if w in _[::-1]else 0,w]for w in k)
for t,v in z:
if not t:continue
if t==2:v=v[::-1]
i=_.index(v)
for m in range(i,i+len(v)-1):b[c[m][0]*2+1][c[m][1]*2+1]="\\"
for l in range(w+h-1):
x,c=d(l,0);_=''.join(x);z=list([1 if w in _ else 2 if w in _[::-1]else 0,w]for w in k)
for t,v in z:
if not t:continue
if t==2:v=v[::-1]
i=_.index(v)
for m in range(i,i+len(v)-1):y=c[m][0]*2+1;x=c[m][1]*2-1;j=b[y][x];b[y][x]="x"if j=="\\"else"/"
print('\n'.join(''.join(x) for x in b))
```
An "is" was missed in the second example
```
Atomic chess is cool
achess
btoikm
bloosi
nowmlp
hewiir
asdfec
a c-h-e-s-s
\ \ /
b t o i k m
\ \ \
b l o o s-i
\ \
n o w m l p
\
h e w i i r
\
a s d f e c
```
Sorta ungolfed
```
words = input().lower().split(" ")
square = []
while 1:
square.append(input())
if not square[-1]:square.pop();break
solved = sum([[list(' '.join(list(i))),[' ']*(len(i)*2-1)]for i in square], [])[:-1]
w,h = len(square[0]), len(square)
for l in range(h):
r = square[l]
rm = list([1 if w in r else 2 if w in r[::-1] else 0, w] for w in words)
for t,v in rm:
if not t:continue
v = v[::-1] if t==2 else v
i = r.index(v)
for m in range(i,i+len(v)-1):solved[l*2][m*2+1]="-"
for l in range(w):
u = ''.join(x[l] for x in square)
um = list([1 if w in u else 2 if w in u[::-1] else 0, w] for w in words)
for t,v in um:
if not t:continue
v = v[::-1] if t==2 else v
i = u.index(v)
for m in range(i,i+len(v)-1):solved[m*2+1][l*2]="|"
def d(m,ind,r=1,o=0):
if ind>=len(m[0]):o=ind-len(m[0])+1;ind=len(m[0])-1
f=range(0,min(ind+1,len(m)-o));return[m[i+o][len(m[0])-1-(ind-i)if r else ind-i]for i in f],[(i+o,len(m[0])-1-(ind-i)if r else ind-i)for i in f]
for l in range(w+h-1):
x,c = d(square,l)
dl = ''.join(x)
dlm = list([1 if w in dl else 2 if w in dl[::-1] else 0, w] for w in words)
for t,v in dlm:
if not t:continue
v = v[::-1] if t==2 else v
i = dl.index(v)
for m in range(i,i+len(v)-1):solved[c[m][0]*2+1][c[m][1]*2+1]="\\"
for l in range(w+h-1):
x,c = d(square,l,0)
dr = ''.join(x)
drm = list([1 if w in dr else 2 if w in dr[::-1] else 0, w] for w in words)
for t,v in drm:
if not t:continue
v = v[::-1] if
t==2 else v
i = dr.index(v)
for m in range(i,i+len(v)-1):y=c[m][0]*2+1;x=c[m][1]*2-1;j=solved[y][x];solved[y][x]="x"if j=="\\"else"/"
print('\n'.join(''.join(x) for x in solved))
```
[Answer]
# Mathematica, 478 bytes
```
f[j_,k_]:=({m,p}=ToCharacterCode@*StringSplit/@{j,ToLowerCase@k};
t=Transpose;v=Length@m[[1]];i=MapIndexed;r=RotateLeft;
y@d_:=t@i[r[PadLeft[#,2v d],#2 d]&,m];z[m_,d_,p_]:=i[r[#,#2d]&,t@m][[All,p]];
c[m_,s_]:=(a=0~Table~{v};a[[Join@@(Range[#,#2-1]&@@@SequencePosition[#,s|Reverse@s])]]=1;a)&/@m;
FromCharacterCode@Flatten@Riffle[#,10]&@
Flatten[BitOr@@({{m,8m~c~#},{4t@c[t@m,#],2z[y@1~c~#,-1,-v;;-1]+z[c[y@-1,#],1,2;;v+1]}}&/@p)
/.{0->32,1->47,2->92,3->88,4->124,8->45},{{3,1},{4,2}}])
```
Test case:
```
f["wotsdsearn\nsiiewfvery\nchheruoawd\ntetoennore\nasbdrgrehe\naobyedycab\ntweosttgwt",
"This is very neat words var are fun rob bot robot"]
(*
w o t s d s e a r n
/
s-i i e w f v-e-r-y
/ | \
c h h e r u o a w d
/ / | X
t e t o e n n o r e
/ X \
a s b d r g r e h e
/ / \
a o b y e d y c a b
/ / \
t w e o s t t g w t
*)
```
] |
[Question]
[
In the vein of large number challenges I thought this one might be interesting.
In this challenge, we will be using the [Residue Number System](https://en.wikipedia.org/wiki/Residue_number_system) (RNS) to perform addition, subtraction, and multiplication on large integers.
**What is the RNS**
The RNS is one of many ways that people have developed to identify integers. In this system, numbers are represented by a sequence of residues (which are the results after a modulus operation (i.e. the remainder after integer division)). In this system, each integer has many representations. To keep things simple, we are going to limit things so that each integer is uniquely represented. I think it is easier to describe what is happening with a concrete example.
Let us look at the first three prime numbers: 2, 3, 5. In the RNS system, we can use these three numbers to *uniquely* represent any number that is less than 2\*3\*5 = 30 using residues. Take 21:
21 is less than 30, so we can represent it using the results after modding by 2, 3, and 5. (i.e. the remainder after integer dividing by 2, 3, and 5)
We would identify 21 with the following sequence of integers:
21 ~ { 21 mod 2, 21 mod 3, 21 mod 5 } = {1, 0, 1}
And so in our RNS system, instead of "21", we would use {1,0,1}.
In general **given an integer *n*, we represent *n* as { *n* mod 2, ..., *n* mod *p\_k* } where *p\_k* is the smallest prime such that *n* is less than the product of all primes less than or equal to *p\_k*.**
Another example, say we have 3412. We need to use 2,3,5,7,11,13 here because `2*3*5*7*11*13=30030` whereas, `2*3*5*7*11=2310` which is too small.
3412 ~ { 3412 mod 2, 3412 mod 3, 3412, mod 5, ... , 3412 mod 13 } = { 0, 1, 2, 3, 2, 6 }
You notice that using this system we can represent very large numbers relatively painlessly. Using {1, 2, 3, 4, 5, 6, 7, 8, ... } residues, we can represent numbers up to {2, 6, 30, 210, 2310, 30030, 510510, 9699690 ...} respectively. ( [Here is the series](https://oeis.org/A002110) )
**Our task**
We will be using these residues to perform +, -, and \* on large numbers. I will describe these processes below. For now here are the input and output specs.
**Input**
You will be given two (potentially very large) numbers via a stdin or function argument. They will be given as strings of base 10 digits.
For the purposes of outlining the problem further, we call the first input `n` and the second `m`. **Assume n > m >= 0**.
You will also be given `+` or `-` or `*` to indicate the operation to perform.
**Output**
Let *x* be an integer. We will use [*x*] to refer to the RNS representation described above of *x*.
You are to output `[n] <operator> [m] = [result]`
**How to perform the operations in RNS**
These operations are relatively simple. Given two numbers in RNS notation, to add, subtract, or multiply them, simply perform the given operations component-wise and then take the modulus.
i.e.
{ 1, 2, 3 } + { 1, 1, 4 } = { (1+1) mod 2, (2+1) mod 3, (3+4) mod 5 } = {0, 0, 2}
Note that if the number of residues used to represent two different numbers are not the same, when performing operations, you will need to extend the "shorter" number so that it has the same number of residues. This follows the same process. See the test cases for an example.
The same goes if the result requires more residues than either input. Then both inputs need to be "extended".
**Important Details**
* We will be dealing with big numbers here, but not arbitrarily large. **We will be responsible for numbers up to the product of the first 100 primes** (see below). To this end, **you are given the first 100 primes for free (no byte cost)**. You may stick them in an array called `p` or something idiomatic to your language and then subtract the number of bytes used to initiate this array from your final total. This of course means that they may be hard-coded or you may use a built-in to generate them.
* If for someone reason this is the default integer representation used in your language. That is fine.
* You may not use any Arbitrary Precision Integer type unless it is the default of your language. If it is the default, you may not use it to store integers that would not typically fit in 64 bits.
* To be clear, each integer will always be represented with the fewest residues possible. This goes for both input and output.
* I think the other specs should prevent this, but to be redundant: you may not perform the given operation on the inputs and then and then change everything to RNS and then output. You must change the inputs to RNS and then perform the operations to produce the output.
**Test Cases**
1. Input:
```
n = 10
m = 4
+
```
Output:
```
{ 0, 1, 0 } + { 0, 1 } = { 0, 2, 4 }
```
Explanation:
First, change each number to its RNS representation as described above:
`10 ~ {0,1,0}` and `4 ~ {0,1}`. Notice that when we want to do component-wise addition, that `10` has more components than `4`. Therefore we must "extend" the shorter number. So we will briefly write `4 ~ {0,1} --> {0,1, 4 mod 5} = {0,1,4}`. Now we proceed with addition and then take the modulus.
2. Input
```
n=28
m=18
+
```
Output:
```
[ 0, 1, 3 ] + [0, 0, 3 ] = [ 0, 1, 1, 4 ]
```
3. Input (me mashing my face on the keyboard)
```
n=1231725471982371298419823012819231982571923
m=1288488183
*
```
Output (broken onto separate lines for readability):
```
[1, 2, 3, 6, 2, 10, 2, 1, 12, 16, 7, 15, 34, 29, 31, 5, 55, 32, 66, 61, 3, 76, 52, 14, 65, 44, 99, 57 ]
*
[1, 0, 3, 3, 4, 8, 9, 10, 8, 0 ]
=
[1, 0, 4, 4, 8, 2, 1, 10, 4, 0, 17, 7, 27, 21, 44, 51, 56, 9, 6, 9, 12, 0, 52, 36, 43, 68, 99, 24, 96, 39, 96, 66, 125]
```
`n` requires 28 primes. `m` requires 10. `n*m` requires 33.
4. Input
```
n=8709668761379269784034173446876636639594408083936553641753483991897255703964943107588335040121154680170867105541177741204814011615930342030904704147856733048115934632145172739949220591246493529224396454328521288726490
m=1699412683745170450115957274739962577420086093042490863793456500767137147999161679589295549397604032154933975242548831536518655879433595016
-
```
Output:
```
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 509]
-
[0, 2, 1, 6, 1, 12, 11, 18, 14, 28, 21, 36, 37, 42, 16, 52, 41, 60, 16, 70, 49, 78, 80, 88, 49, 100, 13, 106, 4, 112, 68, 130, 36, 138, 37, 150, 0, 162, 8, 172, 163, 180, 18, 192, 129, 198, 135, 222, 78, 228, 90, 238, 57, 250, 36, 262, 87, 270, 206, 280, 193, 292, 253, 310, 224, 316, 57, 336, 48, 348]
=
[0, 1, 4, 1, 10, 1, 6, 1, 9, 1, 10, 1, 4, 1, 31, 1, 18, 1, 51, 1, 24, 1, 3, 1, 48, 1, 90, 1, 105, 1, 59, 1, 101, 1, 112, 1, 0, 1, 159, 1, 16, 1, 173, 1, 68, 1, 76, 1, 149, 1, 143, 1, 184, 1, 221, 1, 182, 1, 71, 1, 90, 1, 54, 1, 89, 1, 274, 1, 299, 1, 266, 1, 228, 1, 340, 1, 170, 1, 107, 1, 340, 1, 88, 1, 157, 1, 143, 1, 22, 1, 22, 1, 58, 1, 296, 1, 371, 1, 140]
```
`n` uses 100 primes. `m` uses 70 primes. `n-m` uses 99 primes.
*I checked these using the `ChineseRem` built-in implementation of the Chinese Remainder theorem on GAP (which basically takes RNS numbers and changes them to base 10 integers). I believe they are correct. If something seems fishy, please let me know.*
---
For those who care, the product of the first 100 primes is:
```
471193079990618495316248783476026042202057477340967552018863483961641533584503
422120528925670554468197243910409777715799180438028421831503871944494399049257
9030720635990538452312528339864352999310398481791730017201031090
```
This number is 1 larger than the maximal number we can represent using the given system (and 100 prime limitation).
[Somewhat related](https://codegolf.stackexchange.com/questions/71730/arbitrary-precision-integer-division)
[Answer]
# GAP
*Some Background:* I will admit that when I created this question, so many months ago, I did not have a method for solving the hard part of this question: determining the correct number of primes to use. We have a lot of very intelligent people on this site, and I really expected that someone would figure out a way to do it fairly quickly. However, as this did not happen, I wasn't even sure that it was truly possible to solve this problem. So, I had to take the time to devise a method. I believe that what I have done does not break any of the rules in this challenge, of course I would love this to be fact checked.
I also slightly regret the choice of [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") because the solutions are slightly more in depth than would usually fit the tag format. Having said this, to follow site rules, there is a "golfed" version of my solution at the bottom of this post.
---
**Code**
```
### The first 100 primes;
primes := Primes{[1..100]};
### In many of the functions below, the 'string' variable is a string of digits
###
### Returns the 'index' digit of 'string' as an integer
GetValueAsInt := function(string, index)
return IntChar(string[index]) - 48;
end;
### Used in the 'modulus' function. See that comment for more information.
### Calculates the contribution to the modulus of a digit 'digit' in the 10^power place.
### 'integer' is the modulus
digit_contribution := function(digit, integer, power)
local result, i;
result := 1;
for i in [0..power-1] do
result := ( result * (10 mod integer) ) mod integer;
od;
result := (result * (digit mod integer) ) mod integer;
return result;
end;
### This modulus function is used to calculate the modulus of large numbers without storing them
##### as large numbers.
### It does so by breaking them into digits, and calculating the contribution of each digit.
### e.g. 1234 mod 5 = (1000 mod 5)(1 mod 5) + (200 mod 5)(2 mod 5) + (10 mod 5)(3 mod 5) + (4 mod 5)
### It actually mods after every calculation to ensure that we never get a number larger
##### than the modulus ('integer') squared, which will never be even close to 10^64-1
modulus := function(string, integer)
local i, result, digit, len;
len := Length(string);
result := 0;
for i in [1..len] do
digit := IntChar(string[i]) -48;
result := ( result + digit_contribution(digit, integer, len-i) ) mod integer;
od;
return result;
end;
### This returns the product of the first i-1 primes (mod j). It must not (and does not)
##### ever store an integer larger than 2^64-1
phi_i := function(i,j)
local index, result;
result := 1;
for index in [1..i-1] do
result := ( result * primes[index] ) mod primes[j];
od;
return result;
end;
### Calculates the first residues of 'string' mod the first 100 primes
get_residues := function(string)
local p, result;
result := [];
for p in primes do
Add( result, modulus(string, p) );
od;
return result;
end;
### Gets the ith element in the partial_chinese array, given the previous elements
### See the explanation section and partial_chinese function for more info
get_partial_i := function( i, residues, previous_array )
local index, result;
result := residues[i];
for index in [1..Length(previous_array)] do
result := ( result - previous_array[index]*phi_i(index,i) ) mod primes[i];
od;
result := ( result / phi_i(i,i) ) mod primes[i];
return result;
end;
### returns an array such that the sum of prod_primes(i)*array[i] is equal to the integer value
##### that is represented by the residues. (It basically just does the CRT without
##### actually summing everything.) prod_primes(i) is the product of the first i-1 primes
### See the explanation for a bit more info
### This is what allows us to determine the minimal number of primes to represent a RNS number
partial_chinese := function( string )
local array, i, residues;
residues := get_residues(string);
array := [];
for i in [1 .. Length(primes)] do
Add( array, get_partial_i( i, residues, array ) );
od;
return array;
end;
### Same as partial_chinese but takes input in a different form.
partial_chinese_from_residues := function(residues)
local array, i;
array := [];
for i in [1 .. Length(primes)] do
Add( array, get_partial_i( i, residues, array ) );
od;
return array;
end;
### gives you the number of primes needed to represent an integer. Basically asks how
##### many trailing zeros there are in the chinese array.
get_size := function(string)
local array, i, len, result;
array := partial_chinese(string);
len := Length(array);
for i in [0..len-1] do
if not (array[len-i] = 0) then
return len -i;
fi;
od;
Print("ERROR: get_size().\n");
return 0;
end;
### Same as above but with different input format
get_size_from_residues := function(residues)
local array, i, len, result;
array := partial_chinese_from_residues(residues);
len := Length(array);
for i in [0..len-1] do
if not (array[len-i] = 0) then
return len -i;
fi;
od;
Print("ERROR: get_size().\n");
return 0;
end;
### the actual function. inputs are all strings
f := function(in1, in2, opperation)
local residues_1, residues_2, residues_result, i;
residues_1 := get_residues(in1);
residues_2 := get_residues(in2);
residues_result := [];
if opperation = "+" then
for i in [1..Length(primes)] do
Add( residues_result, ( residues_1[i] + residues_2[i] ) mod primes[i]);
od;
elif opperation = "*" then
for i in [1..Length(primes)] do
Add( residues_result, ( residues_1[i] * residues_2[i] ) mod primes[i]);
od;
elif opperation = "-" then
for i in [1..Length(primes)] do
Add( residues_result, ( residues_1[i] - residues_2[i] ) mod primes[i]);
od;
fi;
Print(residues_1{[1..get_size(in1)]}, " ", opperation, " ", residues_2{[1..get_size(in2)]}, " = ", residues_result{[1..get_size_from_residues(residues_result)]} );
end;
```
**Explanation:**
To start off, we calculate all the 100 of the residues for both inputs. We do this with the `modulus` function in the code. I tried to be careful so that we use the built-in `mod` function after every step. This ensures that we never have a number that is larger than `540^2`, which is 1 less than the 100th prime squared.
After we have all the residues, we can perform the given operation and `mod` each entry again. Now we have a unique designator for the result, but we need to determine the minimal number of entries that we have to use to represent the result and each of the inputs.
Figuring out how many residues we actually need is by far the hardest part of this problem. To determine this, we perform most of the steps of the Chinese Remainder Theorem (CRT). However, we obviously have to make modifications so that we don't end up with numbers that are too large.
Let `prod(i)` be the sum of the first `i-1` primes. For example,
```
prod(1) = 1
prod(2) = 2
prod(3) = 6
prod(4) = 30
etc
```
Let `X` be an integer. Let `{r_i}` be the residues of `X`, that is
```
r_i = X mod p_i
```
Where `p_i` is the `i`th prime. This is for `1<i<=100` in our case.
Now we are going to use the CRT to find a sequence `{u_i}` such that the sum over `i` of `prod(i) * u_i` is equal to `X`. Note that each `u_i` is also technically a residue, as `u_i < p_i`. Furthermore, if `X < prod(i)` then `u_i = 0`. This is of critical importance. It means that by examining trailing zeros, we can determine how many of the residues `r_i` we actually need to represent `X` in the RNS.
If you care to examine some sequences of `u_i`, the `partial_chinese` function returns the `u_i` sequence.
By messing around with the CRT, I was able to find a recursive formula for the `u_i` values, solving the issue of determining how many residues we need.
The formula is:
```
u_i = [ r_i - SUM ] / prod(i) (mod p_i)
```
Where `SUM` is the sum over `j in [1,i)` of `u_j * prod(i)`.
Of course, `prod(i)` cannot actually be calculated in some cases because it is too large. For this purpose, I used the `phi_i` function. This function returns `prod(j) (mod p_i)`. It `mod`s at every step, so we never actually calculate anything that is too large.
If you are curious where this formula comes from, I would recommend working a couple of CRT examples, which can be found on the [wikipedia page](https://en.wikipedia.org/wiki/Chinese_remainder_theorem).
Finally, for each input as well as our output, we calculate the `u_i` sequence and then determine the trailing zeros. Then we throw out that many `r_i` from the end of the residue sequences.
---
[Answer]
# Mathematica, not golfed
```
rns[d_,l_]:=Table[Reap[
FoldPairList[Sow@QuotientRemainder[10#+#2,Prime@i]&,0,d]
][[2,1,-1,2]],{i,l}];
plus[a_,b_]:=Mod[a+b,Prime@Range@Length@a];
subtract[a_,b_]:=Mod[a-b,Prime@Range@Length@a];
times[a_,b_]:=Mod[a b,Prime@Range@Length@a];
mag[f_]:=LengthWhile[FoldList[#/#2&,f,Prime@Range@100],#>1.1&];
ext[m_,n_,i_]:=Fold[Mod[1##,Prime@i]&,m,Prime@Range@n];
multi[e_,p_,t_]:=Tr@Position[Mod[e Range@p,p],p-t];
appx[d_] := N@FromDigits[{d~Take~UpTo[6], Length@d}]
```
* Function `rns[d_,l_]` converts a base-10 integer `d` into a RNS integer of length `l`.
* Function `plus` / `times` / `subtract` add / multiply / subtract one RNS integer to / from another, both of which are of the same length.
* Function `mag[f_]` estimates the approximate magnitude of the floating point number `f` in terms of the lower bound of the length of its RNS representation.
* Function `ext[m_,n_,i_]` finds out the remainder from division of the product of `m` and `Prime[Range@n]` by `Prime[i]`.
* Function `multi[e_,p_,t_]` gives the smallest multiplier `m` satisfying that `Divisible[m*e+t,p]`
* Function `appx[d_]` take the first `6` digits of a decimal integer and gives its approximate floating point value.
---
With the help of functions above, now we are able to solve a tricky problem - **to determine the length of the result**.
First, I have to clarify that it is not an easy task to determine the RNS length of an integer. For small integers, we can compare them directly with the product of primes. But for very large integers, since it is forbidden to calculate the product of primes infinitely accurate, such comparison no longer works.
For example, given that the product of prime `1` to `30` is `3.16*10^46`, the RNS length of integers around `3.16*10^46` can possibly be `29` or `30`. The function `mag` will give `29` as a reference for these integers, showing that both `29` and `30` are possible.
Once knowing the magnitude, we simply represent the integer according to that magnitude directly, hoping to calculate its true length. The trick here is to add some new numbers to the original number and modify its RNS representation, until the representation is all zero.
For example, `mag[211.]` is `4`, and its length `4` representation is `{1, 1, 1, 1}`.
```
step 1: {1,1,1,1} -> {0,2,2,2} by adding (1) * 1 = 1
step 2: {0,2,2,2} -> {0,0,1,6} by adding (2) * 2 = 4
step 3: {0,0,1,6} -> {0,0,0,2} by adding (2*3) * 4 = 24
step 4: {0,0,0,2} -> {0,0,0,0} by adding (2*3*5) * 6 = 180
step 5: calculate 211 + (1 + 4 + 24 + 180) ~ 420
```
By adding some number, we increase `211` to the smallest number that is divisible by `210` (`2*3*5*7`). And now we conclude that the original number is greater than `210`, since `420` equals "approximately" two times of `210`. It is not difficult to imagine that if we start from `209`, the final number is "approximately" `210`.
Function `length[f_,n_]` takes the floating point value `f` to estimate the magnitude, and correct it base on its RNS representation `n`.
```
length[f_,n_]:=With[{g=mag@f},
g+If[#==0,1,Round[(#+f)/Times@@Prime@Range@g]-1]&[
FoldList[Times,1.,Prime[Range[g-1]]].
FoldPairList[
Block[{i=#2,m},
{m=multi[ext[1,i-1,i],Prime@i,Part@##],rnsPlus[#,ext[m,i-1,#]&/@Range[g]]}
]&,n,Range[g]]]]
```
---
Function `rnsOperation[a_,b_,op_,rnsop_]` gives `rnsop[a,b]` and `op` is corresponding normal operations used to get approximate results based on floating point values.
```
rnsOperation[a_,b_,op_,rnsop_]:=Block[{c=op[appx@a,appx@b],m},
m=mag[c];m=length[c,rnsop[rns[a,m],rns[b,m]]];rnsop[rns[a,m],rns[b,m]]]
```
*Example*
```
rnsOperation[
IntegerDigits@1231725471982371298419823012819231982571923,
IntegerDigits@1288488183,
Times, times]
(* {1,0,4,4,8,2,1,10,4,0,17,7,27,21,44,51,56,9,6,9,12,0,52,36,43,68,99,24,96,39,96,66,125} *)
```
[Answer]
# [Python 3](https://docs.python.org/3/), 435 bytes
This challenge has been on my bucket list for a while, but it's only recently that: a) I put time and attention into actually attempting an answer; and b) actually tested my idea to calculate the size of the numbers (and so the number of primes by comparing it to the size of the primorials) using some unholy combination of logarithms and the Chinese Remainder Theorem. Unfortunately, working with logarithms while trying to determine the number of primes that, for example, `large_primorial + 3` requires, meant that I was having to find ways to work around floating-point problems.
And so, this is a port of [Liam's answer](https://codegolf.stackexchange.com/a/91392/47581).
[Try it online!](https://tio.run/##XVTLciJJDLzzFXVx0A3tiHqoXu3p81wdcyU4tA0s@NHgBjwx/Lw3s@wNMxthqiSVlEolFoc/p@1@cB@HbmEb5RrlGxUbZQw@8Azt3CgL2@J2iDvEBLcgJrA9q/AWEAvwo2kmSqmIcEQ44U64M6E0cTWBdXEzW9G1dF3pWiw@CA//iWY8w4Gp7GFiIceExKJcDsZKm0zKnMEW4gS3tozhCpolvuUQ1peDCQS3gQ@RscgYwW0qw@NwJO2I60jaUR3CuSILiTspB5WiLI66OBJ2JOxI2BHOURFHrkJJhEIIhCaa2CJuOSgxuUoRm7hCrkKthYSF4EJcSbQohHB8rz9H9YT2hPTUwotZfmzG/avanIfH037/clS718N@PKlxvTo/rlV/VL8mP7uxH/5ZT1bdS//6sOrVsV38qr7sS/PYVpeZ0fPdcKoe6/rmrTk2ut7sR/WmdoM6LCfb/wqfml17VfnWXmZvN4fFbtkcFu3TsjH1ZLXeqGM11u1E9d1ieXfpcp4oou2I9rMyWvNR3XcsvDt3Iy74THn6THlZD1Vf1@25q863/eJpOdtWaA1u91@Jz19YzX3BUruN2lY7pMyeb@5/2PZhXPfPeOjn3ZkhqPd7u3tZV/3isvxh6tmlvdx2ZgKdTudxUOOivczNsrDfVH3z0AxsvwKNu3dcD/XdYaRAx@pcN0NzrN7rZtpNYSzW7/1LdTyN1RmD1PNhTvuddl20@d/sCH9sqqmZNuUzn9aTK/f2b3f27eorl7ZcFVvY8bvaJpanq4TMwBWgLQ2uIS0WwHqJJifrorE5STG1wd5kvMLxkRYrbUqSkknuGyFFnUNIMWDpM1YvJtFOsNsijAaHv@yziE46ueyC9y7g3TuBm03K6O@jdjlIxsbo6FNyzmssFdbfA0WbqFOIRnv855sYoxirJRlkmGB8dmhotdNZS9RiJCYfonNM4St2zBrxmDOioWRrtc/GCvo5b@EKe3txNmHHMGK0eKJIJiDf2JBcZL0Wr4nogSTECpAmojXYabAQi7IUoIMTH7zWEaQhKlYbgwb86GWfss0YI@N3I2BEMKMDz1vB94DRDfTxJkGnFCEIfn7QNXx@yx//Ag "Python 3 – Try It Online")
```
from functools import reduce as R
G=range
d=lambda s:[R(lambda z,c:(z*10+int(c))%q,s,0)for q in p]
h=lambda j,i:R(lambda z,q:z*q%p[i],p[:j],1)
def s(r):
a=[];z=99
for i in G(100):
P=p[i];u=r[i]
for j in G(len(a)):u=(u-a[j]*h(j,i))%P
for k in G(1,P):
if h(i,i)*k%P<2:break
a+=u*k%P,
while(a[z]<1)*z:z-=1
return r[:z+1]
def f(a,b,n):u=d(a);v=d(b);print(s(u),n,s(v),'=',s([eval(str(u[i])+n+str(v[i]))%p[i]for i in G(100)]))
```
# Explanation
While trying to port Liam's answer, I personally found some of the explanation given was confusingly worded, so this is my attempt at explaining his algorithm.
First, we get the residues of `n` and `m`.
```
res1 = get_residues(n)
res2 = get_residues(m)
```
This involves turning all the digits of the input strings and turning them into numbers modulo each of our primes, e.g. for 28, we would have `[(20 + 8) mod 2, (20 + 8) mod 3, (20 + 8) mod 5, etc]`
```
def get_residues(string):
result = []
for p in primes:
result.append(reduce(lambda z, c:(z*10+int(c)) % p, string, 0))
```
Then we add, multiply, or subtract the residues pairwise using `eval()`
```
result = []
for i in range(len(primes)):
result.append((eval(str(res1[i]) + op + str(res2[i])) % primes[i])
```
Then we get the sizes of our residues, i.e. the minimum number of primes we need.
```
size1 = get_size(res1)
size2 = get_size(res2)
size3 = get_size(result)
```
Getting the sizes is the trickiest and most code-intensive part. We use the `partial_chinese` function, which gets us our sequence of `u_i` to determine the size with. More on `u_i` in a moment.
```
def get_size(residues):
array = partial_chinese(residues)
size = len(residues)-1
while array[size] == 0 and size:
size -= 1
return size+1 # to prevent off-by-one errors from 0-indexing
```
The sequence `u_i` is calculated by taking each residue `r_i`, subtracting the sum `u_j * primorial(j) for j in [1, i)`, and then `dividing` by `primorial(i)`, all modulo `primes[i]`. That is, `u_i = (r_i - SUM) / primorial(i)`. More on our primorial and division functions in a moment.
```
def partial_chinese(residues):
array = []
for i in range(len(primes)):
array.append(get_partial_i(i, residues, array))
return array
def get_partial_i(i, residues, previous_array):
result = residues[i]
for j in range(len(previous_array)):
result = (result - previous_array[j] * phi_i(j, i)) % primes[i]
result = result * inverse(phi_i(i, i), primes[i]) % primes[i]
return result
```
`phi_i(j, i)` calculates `primorial(j) mod primes[i]`. Division modulo any prime `p` is easily implemented by checking for multiplicative inverses manually, as we can be sure that any possible `u_i` is `0 <= u_i < p` is guaranteed to be coprime to p and so is guaranteed a multiplicative inverse.
```
def phi_i(j, i):
return reduce(lambda z, q: z * q % primes[i], primes[:j], 1)
def inverse(n, p):
for i in range(1, p):
if n * i % p == 1:
return i
```
With all that done, we print our string and we're done.
```
print(res1[:size1], op, res2[:size2], "=", result[:size3])
```
# What's next
This was fun to implement. I still want to see if I can use logarithms in some way in another answer. And I'd like to implement this code or something like in a functional golfing language, like APL or Jelly. Any and all golfing suggestions and corrections are welcome!
] |
[Question]
[
Redstone is a material in the game Minecraft, and it is used for many complex contraptions. For this program, you will only need to simulate three items: the redstone wire (noted with R), redstone torch (noted with T), and block (noted with B).
Here are a list of basic rules about how redstone works:
```
A redstone torch sends power to any adjacent redstone wire.
TRRRR
^This redstone wire is powered.
Redstone wire can only hold power for 15 blocks.
TRRRRRRRRRRRRRRRR
^This last wire is unpowered, because the torch is >15 blocks away.
A block is said to be powered if a powered redstone wire is found adjacent to it.
TRRRB
^This block is powered.
If a block next to a redstone torch is powered, then the torch stops emitting power.
T
R
R
R
B <This block is powered.
T <This redstone torch does not emit power because of the block next to it.
R <This redstone is unpowered because the torch is not providing power.
R
```
Input will be given in two dimensional arrays up to a size of 64x64, like this:
```
TRRR
B
TBRTRR
R
RRRRRRRRR
R
RRRRRR
```
It is guaranteed that the input will not have any "clocks", or redstone powered by a torch pointing to the block that the torch is on. There will only be one redstone circuit in every input.
Your program must change each character to be a 1 or a 0, 1 indicating if this item is powered/emitting power, and a 0 if it is unpowered/not emitting power.
This input should have this output:
```
1111
1
100000
1
111111111
1
001111
```
This is a code-golf, so shortest code wins, as always.
[Answer]
# Haskell, 400
```
import Data.Char
import Data.List
f x=[(++[x]).tail,(x:).init]
h(' ':_)=' '
h('T':s)=if elem 'b's then 'T'else 't'
h('t':s)=h$'T':s
h('B':s)=if any(`elem`s)['e'..'s']then 'b'else 'B'
h('b':s)=h$'B':s
h(_:s)=max 'd'$chr$ord(maximum s)-1
o ' '=' '
o c|elem c"dTB"='0'
o _='1'
a=(map.map)o.(!!(64^2+16)).iterate(map(map h.transpose).transpose.(\l->[g l|g<-id:f(map(const ' ')$head l)++map map (f ' ')]))
```
`map(map h.transpose).transpose.(\l->[g l|g<-id:f(map(const ' ')$head l)++map map (f ' ')])` replaces each tile by a list of itself followed by its four neighbors, then maps that through h. h says for each tile how it reacts to neighbors: Torches turn off ('T' rather than 't') when there's a power block ('b') nearby, wires ('d' for dead through 's') imperfectly copy their most-powered neighbor (though cant get worse than dead), etc.
`iterate` repeats this step, `(!!(64^2+16))` plucks out an iteration at which acyclic circuits are done converging, and I totally wrote it like that to give an intuitive bound, not to land at 400.
[Answer]
# Python, 699
This is just a quick pass (ran out of time for now). It can probably use a lot more golfing.
```
import sys
m=[list(x)for x in sys.stdin.read().split('\n')]
e=enumerate
S=set
s=lambda x:S([(r,c)for r,i in e(m)for c,j in e(i)if j==x])
q=S()
t=s('T')
b=s('B')
n=s('R')
def d(o,r,c,i,h,q):
if i<0:return 0
o[(r,c)]=1
for p in[(r+1,c),(r-1,c),(r,c+1),(r,c-1)]:
if p in q or(p in b and not(r,c)in n):continue
if(r,c)in b and p in t-q:
x=S([p])
q|=x
o[p]=0
return 1
if p in h or not p in o:continue
h|=S([p])
if not d(o,p[0],p[1],i-1,h,q):return 1
g=1
while g:
o=dict(zip(b,[0]*len(b))+zip(n,[0]*len(n))+zip(q,[0]*len(q)))
g=0
for x,y in t:
if not(x,y)in q and d(o,x,y,15,S(),q):g=1
for p in o.keys():m[p[0]][p[1]]=o[p]
print"\n".join(map(lambda x:"".join(map(str,x)),m))
```
[Answer]
# Python 2, 556 bytes
```
c=' 0';L=len;M=map;q=list;r='B';s='16';t='T';u='0';E=enumerate
b=[q(M(lambda x:x+[u,s][x==t],q(w[:-1])))+[c]*(64-L(w))for w in open('redstone.txt')]
k=lambda h,l,z:max(q(M(lambda x:[int((x or c)[1:]),0][l^((x or c)[0]==h)],z)))
def v(d=0):
for e,f in E(b):
for g,G in E(f):z=[e!=0and b[e-1][g],g<L(f)-1and f[g+1],e<L(b)-1and b[e+1][g],g and f[g-1]];j=G;i=j[0]+str([[s,u][k(r,1,z)>0],4,4,k(t,0,z),0,max(1,k(r,0,z))-1][ord(j[0])%7]);b[e][g]=i;d=d|(i!=j)
return d
while v():0
for f in b:print''.join(M(lambda j:[' ',`int(j[1:]!=u)`][j[0]!=' '],f))+'\n'
```
[See it in action](https://www.tutorialspoint.com/execute_python_online.php?PID=0Bw_CjBb95KQMMXExTG0tWXpsaDg)
* Assumes each line in input ends with a newline
* Outputs via `print()`
* Each line of output ends with lots of whitespace and a newline
---
* Saved lots of bytes thanks to @mbomb007 (#34718)
* Saved 1 byte thanks to @ZacharyT (#55550)
] |
[Question]
[
Many different types of train set exist, ranging from wooden tracks like Brio, to fully digital control perfect tiny metal replicas of real trains, but they all require a track to be designed, ideally using as many of your pieces as possible.
So, your task is to determine whether, given input of the available pieces, it is possible to build a complete closed circuit using all of the elements, and if not, how many pieces will be left from the maximum possible circuit.
Since this is a simplified train set, there are only 3 elements: big curve, little curve, and straight. These are all based on a square grid:
[](https://i.stack.imgur.com/tasLV.png)
* "Big Curve" is a 90 degree corner, covering 2 units in each dimension
* "Little Curve" is a 90 degree corner, covering one unit in each direction
* "Straight" is a straight element, 1 unit long
This means that the minimum circuit possible is formed of 4 little curves - it's a circle, of radius 1 unit. This can be extended by adding pairs of straight elements to form various ovals. There are other circuits possible by adding more curves, or by mixing the types of curve.
This train set doesn't include any junctions, or methods for tracks to cross, so it's not valid for two elements to connect to the same end of an other element (no Y formations) or to cross over one another (no X formations). Additionally, it's a train set, so any formation which doesn't allow a train to pass isn't valid: examples include straights meeting at 90 degree angles (there must always be a curve between perpendicular straights) and curves meeting at 90 degree angles (curves must flow).
You also want to use as many pieces as possible, ignoring what type they are, so you'll always opt for a circuit which has more bits in. Finally, you only have one train, so any solution which results in multiple circuits is unacceptable.
## Input
Either an array of three integers, all greater than or equal to 0, corresponding to the number of big curves, little curves, and straights available, or parameters passed to your program, in the same order.
## Output
A number corresponding to the number of pieces left over when the maximum possible circuit for the elements provided is constructed.
## Test data
```
Minimal circuit using big curves
Input: [4,0,0]
Output: 0
Slightly more complicated circuit
Input: [3,1,2]
Output: 0
Incomplete circuit - can't join
Input: [3,0,0]
Output: 3
Incomplete circuit - can't join
Input: [3,1,1]
Output: 5
Circuit where big curves share a centre
Input: [2,2,0]
Output: 0
Bigger circuit
Input: [2,6,4]
Output: 0
Circuit where both concave and convex curves required
Input: [8,0,0] or [0,8,0]
Output: 0
Circuit with left over bit
Input: [5,0,0] or [0,5,0]
Output: 1
```
## Notes
* 2 straights and a little curve are equivalent to a big curve, but use more pieces, so are preferred - should never be a situation where this combination is left, if there are any big curves in the circuit
* 4 little curves can usually be swapped for 4 straights, but not if this would cause the circuit to intersect itself
* The train set is also idealised - the track elements take up the widths shown, so it is valid for curves to pass through a single grid square without intersecting, in some cases. The grid just defines the element dimensions. In particular, two big curves can be placed so that the grid square at the top left of the example diagram would also be the bottom right square of another big curve running from left to top (with the diagram showing one running from right to bottom)
* A small curve can fit in the empty space under a big curve (bottom right grid square above). A second big curve could also use that space, shifted one across and one down from the first
* A small curve cannot fit on the same grid space as the outside of a big curve - mostly because there is no way to connect to it which doesn't intersect illegally
[Answer]
# [JavaScript (Node.js)], 1220 bytes
```
f=r=>{var a=[{n:0,d:[[0,-1,"0000000101011"],[1,-1,"0011111111111"],[0,0,"0111101111111"],[1,0,"1100010000000"]],e:[2,-1,1]},{n:0,d:[[-1,-1,"1001111111111"],[0,-1,"0000010010110"],[-1,0,"0110000100000"],[0,0,"1101111011111"]],e:[-2,-1,3]},{n:1,d:[[0,0,"0011101111111"]],e:[1,0,1]},{n:1,d:[[0,0,"1001111011111"]],e:[-1,0,3]},{n:2,d:[[0,0,"1111101011111"]],e:[0,-1,0]}],e=r=>{var a=r.d,e=r.e,n=[];return a.forEach(r=>{var a=r[2];n.push([-r[1],r[0],""+a[10]+a[5]+a[0]+a[8]+a[3]+a[11]+a[6]+a[1]+a[9]+a[4]+a[12]+a[7]+a[2]])}),{d:n,e:[-e[1],e[0],e[2]]}};i=((r,a)=>{for(var n=0;n<r.d;n++,a=e(a));var p=!1;return a.d.forEach(a=>{var e=r[`${r.p.x+a[0]},${r.p.y+a[1]}`];void 0===e&&(e="00000000000000");for(var n="",d=0;d<13;d++)"1"===e[d]&&"1"===a[2][d]&&(p=!0),n+=e[d]===a[2][d]?e[d]:"1";r[`${r.p.x+a[0]},${r.p.y+a[1]}`]=n}),r.p.x+=a.e[0],r.p.y+=a.e[1],r.d=(r.d+a.e[2])%4,!p});var n=[],p=(r,e)=>{a.forEach(a=>{var d=Object.assign({},r);if(d.p=Object.assign({},r.p),!(e[a.n]<=0)&&i(d,a)){if(d.ps+=a.n,0==d.p.x&&0==d.p.y&&0==d.d)return void n.push(d);var s=Object.assign([],e);s[a.n]-=1,p(d,s)}})};p({p:{x:0,y:0},d:0,ps:""},Object.assign([],r));var d=0;n.forEach(r=>{r.ps.length>d&&(d=r.ps.length)}),console.log(r[0]+r[1]+r[2]-d)};
```
[Try it online!](https://tio.run/##hVPbbtwgEP2VxGotkDGCTdqmJqRPfe4HIKTQhb1EEWvhTZTI4tu3DJDdTVOpWBoxF585c@HBPJtpGbbjvvc76w6HlQzybn424cJINfuBETsoxUjPScPK4fDxRhPFq5mfDpgZYckKGjuzcrAmEwCU02hN3KAWgMJ1JMd0fQHm58gF@EiDZx6cgbnnNSE7gh9pVA6sYuSEfc54VTLyWiCrhZwo51iA5h8iK7P3qBBaQRdnoSXwXWiug@mYlLN2B2pBp454qbQIbv8U/IWhq134aZYbdBapFlp4Oj5NG6T6oLgmQTFNmqYzijOd5BcQ@XYD4goE5yC/5iuI7yCus7oA@Q3EQmscMZnt4HNVDtAdoDvwxSi2EqFADE50EjUElLxkwt@mAoTvOmKkQwZjAZ5RXvJTKfZYjKnFpILV/ac50JG@ZMaRFO01s4z3WjzvtvaCSSld2yIn39bwbYmwOLFoGmITFXvLr4TtOtzwBv5TVrdtuUOBWUWJGcPEd9l98vwAdUjB4n/EpE99Kn5paG5R8WcNZkKtREl0oC80/nxNLsdY@gIjJmNyEweNNB8aY@Wv3w9uuadmmrZrj@ZIAhbbFbJ0/IeLjphcIqcM9fpWMty2W2TTkPBcfpmAlSepjRYYt229vdabxXVIudt1t2zhOv2VLzF3WEw5Vy85GVOmCceIoxjRPA7zS3rHrwOL6RUwMk5D00TyASLUDYGB@XdLnoqZ6KPz6/3mzqZJWXlmgeVc7vy0e3T0cbdGsPgdPIEOXkVvE4nDCqmb9PaYxoc/ "JavaScript (Node.js) – Try It Online")
Note: The input is actually the variable q at the start. [2,6,4] will also take quite a bit of time as this is a brute force solution without optimizations.
I actually did this because it hasn't been answered in over a year and I was just kinda curious if it was possible.
---
Original Code:
```
var q = [4, 2, 4];
var t = [
{
n: 0,
d: [
[0, -1, "0000000101011"],
[1, -1, "0011111111111"],
[0, 0, "0111101111111"],
[1, 0, "1100010000000"]
],
e: [2, -1, 1],
},
{
n: 0,
d: [
[-1, -1, "1001111111111"],
[0, -1, "0000010010110"],
[-1, 0, "0110000100000"],
[0, 0, "1101111011111"]
],
e: [-2, -1, 3]
},
{
n: 1,
d: [
[0, 0, "0011101111111"]
],
e: [1, 0, 1]
},
{
n: 1,
d: [
[0, 0, "1001111011111"]
],
e: [-1, 0, 3]
},
{
n: 2,
d: [
[0, 0, "1111101011111"]
],
e: [0, -1, 0]
},
];
r = (p) => {
var d = p.d; var e = p.e; var o = [];
d.forEach(i => {
var d = i[2];
o.push([-i[1], i[0], "" + d[10] + d[5] + d[0] + d[8] + d[3] + d[11] + d[6] + d[1] + d[9] + d[4] + d[12] + d[7] + d[2]])
});
return { d: o, e: [-e[1], e[0], e[2]] };
};
i = (g, p) => {
//console.log(g.p, g.d);
for (var i = 0; i < g.d; i++ , p = r(p));
var c = false;
p.d.forEach(d => {
var v = g[`${g.p.x + d[0]},${g.p.y + d[1]}`];
if (v === undefined) v = "00000000000000";
var o = "";
for (var i = 0; i < 13; i++) {
if (v[i] === '1' && d[2][i] === '1')
c = true;
o += (v[i] === d[2][i]) ? v[i] : '1';
}
//console.log(o);
g[`${g.p.x + d[0]},${g.p.y + d[1]}`] = o;
});
g.p.x += p.e[0];
g.p.y += p.e[1];
g.d = (g.d + p.e[2]) % 4;
return !c;
};
var l = [];
var re = (g, p) => {
t.forEach(piece => {
var gr = Object.assign({}, g);
gr.p = Object.assign({}, g.p);
if (p[piece.n] <= 0)
return;
if (i(gr, piece)) {
gr.ps += piece.n;
if (gr.p.x == 0 && gr.p.y == 0 && gr.d == 0) {
l.push(gr);
return;
}
var ti = Object.assign([], p);
ti[piece.n] -= 1;
re(gr, ti);
}
});
};
var gr = { p: { x: 0, y: 0 }, d: 0, ps: "" };
re(gr, Object.assign([], q));
var c = 0;
var lo = 0;
l.forEach(g => {
if (g.ps.length > lo) {
require("./draw.js")(g, `outs/out${c++}.png`)
lo = g.ps.length;
}
});
console.log(q[0] + q[1] + q[2] - lo);
```
first I should include a graphic of the tiles I used.
[](https://i.stack.imgur.com/JrHfU.png)
```
The sections of this tile were given a number and
used for comparison and overlap handling later.
So there first thing is the array t at the start.
This is a collection of track pieces that contain
n[ame]: the index of the input array.
d[ata]: the offset from the current tile and the Tile bit values.
e[nd]: the relative offset and rotation that the piece provides.
function r[otate] ( p[iece] )
this outputs a piece that is rotated by 90 degrees
by rearranging the tile bits and the end offset
function i[nsert] ( g[rid], p[iece] )
this modifies the passed in grid trying to place down each tile of the piece.
if it hits a point where 2 tiles intersect it sets a flag c[ollision]
it then adjusts the current p[osition] and and d[irection] stored in the grid.
then it returns !c[ollision]
function re[peat] ( g[rid], p[eices] )
this iterates across all nodes which
creates a copy of the g[rid] as gr[id].
checks if the piece is available if not continue
if the peice is added without a collision
add piece name to gr[id].ps[piece string];
it checks if its back at the start
add gr[id] to l[ist]
return as no more pieces can be added without a collision.
clone peices remove the used peice ti[nput]
call re[peate] (gr[id], ti[nput])
call re[peate] with empty grid
search l[ist] for longest piece string
and output input added together minus the length of the longest string.
```
Sorry if the write up is hard to read I'm not used to explaining how my code works.
P.S. I actually also made a few functions for drawing the maps to a png
but of course those were remove to save at least some space.
] |
[Question]
[
The task is simple. Get me some `1000`, `500` and `100` notes.
How ? you might ask. Don't worry, no need of robbing a bank as there is an ATM nearby which accepts your credit card. But your credit limit is just enough for the task so you have to be careful with the withdrawals.
**Challenge**
Given the number of `1000`, `500` and `100` notes required, calculate the specific withdrawals needed to get at least those many notes. In each withdrawal, the ATM can spit out each of the note based on the following rules:
* Amount withdrawn (`A`) is less than `5000`
+ If `A%1000 == 0`, then ATM spits 1 `500` note, 5 `100` notes and rest `1000` notes
+ Else if `A%500 == 0`, the ATM spits 5 `100` notes, rest `1000` notes
+ Else if `A%1000 < 500`, the ATM spits `floor(A/1000)` `1000` notes and rest `100` notes
+ Else if `A%1000 > 500`, the ATM spits `floor(A/1000)` `1000` notes, 1 `500` and rest `100` notes
* Amount withdrawn is greater than equal to `5000`
+ If `A%1000 == 0`, then the ATM spits 2 `500` notes and rest `1000` notes
+ Else if, `A%500 == 0`, the ATM spits 1 `500` note and rest `1000` notes
+ Else if `A%1000 < 500`, the ATM spits `floor(A/1000)` `1000` notes and rest `100` notes
+ Else if `A%1000 > 500`, the ATM spits `floor(A/1000)` `1000` notes, 1 `500` and rest `100` notes
For clarification, here is a complete table of notes withdrawn for all possible amounts up to `7000` (you can withdraw more, but the pattern does not change afterwards). The order is `<1000> <500> <100>`:
```
100 => 0 0 1 2500 => 2 0 5 4800 => 4 1 3
200 => 0 0 2 2600 => 2 1 1 4900 => 4 1 4
300 => 0 0 3 2700 => 2 1 2 5000 => 4 2 0
400 => 0 0 4 2800 => 2 1 3 5100 => 5 0 1
500 => 0 0 5 2900 => 2 1 4 5200 => 5 0 2
600 => 0 1 1 3000 => 2 1 5 5300 => 5 0 3
700 => 0 1 2 3100 => 3 0 1 5400 => 5 0 4
800 => 0 1 3 3200 => 3 0 2 5500 => 5 1 0
900 => 0 1 4 3300 => 3 0 3 5600 => 5 1 1
1000 => 0 1 5 3400 => 3 0 4 5700 => 5 1 2
1100 => 1 0 1 3500 => 3 0 5 5800 => 5 1 3
1200 => 1 0 2 3600 => 3 1 1 5900 => 5 1 4
1300 => 1 0 3 3700 => 3 1 2 6000 => 5 2 0
1400 => 1 0 4 3800 => 3 1 3 6100 => 6 0 1
1500 => 1 0 5 3900 => 3 1 4 6200 => 6 0 2
1600 => 1 1 1 4000 => 3 1 5 6300 => 6 0 3
1700 => 1 1 2 4100 => 4 0 1 6400 => 6 0 4
1800 => 1 1 3 4200 => 4 0 2 6500 => 6 1 0
1900 => 1 1 4 4300 => 4 0 3 6600 => 6 1 1
2000 => 1 1 5 4400 => 4 0 4 6700 => 6 1 2
2100 => 2 0 1 4500 => 4 0 5 6800 => 6 1 3
2200 => 2 0 2 4600 => 4 1 1 6900 => 6 1 4
2300 => 2 0 3 4700 => 4 1 2 7000 => 6 2 0
2400 => 2 0 4
```
*List provided by Martin*
**The Catch**
Since the credit limit in your credit card is just enough, you need to make sure that the **total amount withdrawn across the withdrawals is the minimum possible** for the given input/requirement of notes.
**Input**
Input can be in any favorable format for three numbers corresponding to the number of notes required of value `1000`, `500` and `100`. Not necessarily in that order.
**Output**
Output is the amount to be withdrawn in each transaction separated by a new line.
**Examples**
Input (format `<1000> <500> <100>`):
```
3 4 1
```
Output:
```
600
600
600
3600
```
few more:
```
7 2 5
5000
3500
1 2 3
600
1700
21 14 2
600
600
600
1600
5000
5000
5000
5000
5000
```
**Assumptions**
* You may assume that the ATM has infinite number of notes of each amount.
* You may also assume that you can make any number of transactions.
* Furthermore, the solution to some input values might not be unique, so you can output any 1 of the solution which fulfills the minimum amount possible and minimum notes required conditions.
As usual, you may write a full program reading input via STDIN/ARGV and printing output to STDOUT or a function taking input via arguments and returns either a list of integer corresponding to the amounts or a string with amounts separated by a new line.
This is code-golf so shortest code in bytes wins.
[Answer]
# JavaScript, ~~184~~ 148
```
function g(a,b,c){x=[];while(a>0||b>0||c>0){i=b<3||a<4?a:4;a-=i;if(i>3&&b>1){b-=2;i++}else{i+=(c--<b&&i>4?0:.1)+(b-->0?.5:0)}x.push(i*1e3)}return x}
```
<http://jsfiddle.net/vuyv4r0p/2/>
returns a list of integers corresponding to the withdrawal amounts
[Answer]
# Perl 5: 223
## Edit
This solution was done with a wrong assumption that 7K is the ATM limit. This actually made the task more interesting as it required dynamic programming (the move pattern was quite regular, but hard-coding it would be likely longer than calculating live as I did). With any amount possible the move pattern is so regular that it is trivial to hard-code it. I don't know if the solution by @hoffmale is now correct, but it will be among these lines. So sadly it will be another task where first somebody comes with a solution and then it gets ported to a golfing language for a win.
A bit slower than the original solution (but still sub-second for parameters below 100).
```
#!perl -pa
$c{0,0}=$f=($a,$b,$c)=@F;for$i(0..$b){for$j(0..$a){
/.(?=.$)/>($n=$c{$i-$`,$j-$'})||${$r=\$c{$i,$j}}<($x=$n+$&)&&$$r
or$f=$$r="$x $n".($'.$&+5*$`)."00
"for 204..206,105,106,11..15,110..114}}$_=$f."100
"x($c-$f+3);s/.*\b3//
```
Faster 259 solution.
```
#!perl -pa
$c{0,0}=($a,$b,$c)=@F;for$i(0..$b){for$j(0..$a){
/\B./<($%=$c{$i-$&,$j-$'}+$`)&&(!${$r=\$c{$i,$j}}||$$r>$%)and$d{$i,$j}=$_,$$r=$%for
qw/024 025 026 015 016/,101..105,110..114}}
$d{$b,$a}=~/\B./,$c-=$`,$b-=$&,$a-=$',print$'.$`+5*$&,"00
"while$a+$b;$_="100
"x$c
```
Uses STDIN:
```
$perl atm.pl <<<"21 14 2"
5000
5000
5000
5000
5000
600
600
600
1600
```
] |
[Question]
[
We've had lots of questions about [quine](/questions/tagged/quine "show questions tagged 'quine'")s, programs where the source code and output are identical. For compiled languages, there are other combinations: we've already had [a question](https://codegolf.stackexchange.com/q/8956) about writing a program where the executable and output are identical. But there's one combination left.
## The task
Using a compiled language (i.e. a language which has a compiler that converts source code to executables, which are then executed), write a program which, when compiled, will produce an executable which is bit-for-bit identical to the source code.
## Clarifications
* As with all [quine](/questions/tagged/quine "show questions tagged 'quine'") challenges that do not state otherwise, you must obey the site's [proper quine rules](https://codegolf.meta.stackexchange.com/search?q=proper+quine). In particular, this excludes zero-byte programs, and programs where all the commands compile into themselves.
* At least for this challenge, it doesn't matter what the resulting executable does when run; this is purely a [compile-time](/questions/tagged/compile-time "show questions tagged 'compile-time'") challenge. (If it turns out to be easy, I'm sure that someone will end up posting a "write a program where the source code, executable and output when executed are all the same" challenge, but you don't need to go to that level of complexity for *this* challenge.)
* Your program will, in effect, be a [polyglot](/questions/tagged/polyglot "show questions tagged 'polyglot'") between the source language, and the language it compiles into. This means that you will need to pick a source language, and executable format, for which such a combination is possible.
* Multistep compiling (e.g. compiling an esoteric language into C, which then compiles into an executable) is a legal way to answer the problem. However, this is limited to the use of three compilation steps at most (in order to avoid answers that encode the desired output in the sequence of compilers used rather than in the source code).
* Don't use unusual compiler flags to loophole the question via abusing the `-D` option of a C compiler to hide code (or similar techniques that move code from the program into the compiler flags). You might well need to use unusual compiler flags to produce the executable in the right format, but these should be flags that would generally be useful for compiling programs, not flags specific to the program you've written (and that embed information about it); remember that on this site, the language you're using is defined by the interpreter and compiler flags that you're using.
* Likewise, it's possible that your solution will require a specific filename for the source code; in order to prevent you using this to store code, any specific filename should consist of one character, possibly followed by a standard file extension for the language you are using.
* Please state the exact compiler and version you're using to compile your program, together with the compiler flags you need to build it, because your answer may be hard to reproduce / verify for correctness otherwise; solutions to this question are likely to inherently be somewhat compiler-specific.
* This problem is mostly aimed at compilation into executable formats used by operating systems, but if you have a language that compiles into something else (e.g. bytecode), feel free to submit an answer for that setup, too, even if it won't be quite as impressive. We aren't in the business of unnecessarily restricting what languages you can use here.
## Victory condition
This is effectively a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") (minimize size of the source) and sizecoding (minimize size of the executable) challenge at the same time (because the two are the same): in this challenge, a program is considered to score better than another if it has a shorter length in bytes. So once you've figured out how to solve this problem at all, you can see if you can do better by fitting the program into fewer bytes.
[Answer]
# [CoffeeScript to JavaScript](https://coffeescript.org), 2 bytes
```
a;
```
[Try it](https://coffeescript.org/#try:a%3B)
* `a` is compiled into `a;`. You may [try it here](https://coffeescript.org/#try:a).
* `;` is compiled into nothing. You may [try it here](https://coffeescript.org/#try:%3B).
---
Without ban "programs where all the commands compile into themselves", [js2js](https://eleks.github.io/js2js/) would be a much better choice, IMO.
] |
[Question]
[
Suppose this grid of spaces and `X`'s represents the cross section of some strangely shaped empty [ice cube trays](https://en.wikipedia.org/wiki/Ice_cube#Ice_cube_tray):
```
X X X
X X X XX X XX X
XXXXXX XXXXXXXXXXXXX
```
Columns without `X`'s represent holes or gaps in the trays that can't hold water, draining into an infinite capacity sink. Water falling off the leftmost or rightmost edge of the grid goes into this endless sink as well.
If we were to position a faucet above the trays and let them fill with water until the water level in all compartments remains stable, the exact compartments that become filled would depend on exactly where the water stream was positioned above the trays. (Assume a thin, steady stream of water with no splashing.)
---
For example, if our faucet `F` were above the very left grid column
```
F
X X X
X X X XX X XX X
XXXXXX XXXXXXXXXXXXX
```
the water would fall down to the topmost `X` in that column and spread left and right, the left half spilling into the sink below, and the right half filling up the 2×1 compartment. Once the compartment fills, the right half of the water stream has nowhere to flow but into the sink and the water level everywhere is essentially stable.
Turning the faucet off, the tray now looks like this: (with `~` as water)
```
X X X
X~~X X XX X XX X
XXXXXX XXXXXXXXXXXXX
```
---
Similarly, if we position the faucet like this:
```
F
X X X
X X X XX X XX X
XXXXXX XXXXXXXXXXXXX
```
It will fill up the two leftmost compartments but the rest of the water will drain away:
```
X X X
X~~X~X XX X XX X
XXXXXX XXXXXXXXXXXXX
```
---
If we position the faucet like this:
```
F
X X X
X X X XX X XX X
XXXXXX XXXXXXXXXXXXX
```
The left half of the stream will flow into the sink but the right half will eventually fill up the three rightmost compartments because there's no limit to how far water can travel horizontally on a flat surface:
```
X X~X
X X X XX~X~~XX~~~X
XXXXXX XXXXXXXXXXXXX
```
Positioned like this, however:
```
F
X X X
X X X XX X XX X
XXXXXX XXXXXXXXXXXXX
```
All the water drains away and no compartments are filled:
```
X X X
X X X XX X XX X
XXXXXX XXXXXXXXXXXXX
```
---
# Challenge
Write a program or function that takes in a rectangular grid of spaces, `X`'s, and one `F`. The top row will always contain the `F` and otherwise only contain spaces. The `X`'s in each column (if there are any) will extend in a solid line up from the base of the grid, i.e. there will be no caves or overhangs.
Print or return the grid after the faucet `F` has filled what it can with water `~` as described above. Leave the top `F` row out of the output.
* The grid apart from the faucet row will be 1×1 at minimum so
```
F
X
```
is the smallest input you need to support.
* The input will come in as a complete text rectangle. Leading and trailing spaces do matter in the input and output. e.g. the input
```
F
X X
XXXX
```
should result in
```
X~~X
XXXX
```
(note the leading and trailing spaces)
* Having a single trailing newline in the input or output is fine.
* You can use any four distinct [printable ASCII](https://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters) characters in place of space, `X`, `F`, `~`.
**The shortest code in bytes wins.**
---
**Big Example:**
Input:
```
F
X X
X X X
X XXX X X X X X
X X XXXXXXX X XXX XXXXXXX X X
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXX
```
Output:
```
X~~~~~~~~~~~~~X
X~~~~~~~~~~~~~X~X
X~~~~~~~~~~~~XXX~~~~~~~X~~~~X~X~~~~~~~~~~~X X
X~~~X~~~~~XXXXXXX~~~~~~X~~~~XXX~~~~~XXXXXXX X X
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXX
```
[Answer]
# Lua 5.2, 581 Bytes
Again, slow start with so ineffective language for golfing and with ineffective algorithm. But I will improve :)
```
r=io.read w=io.write F=r()f=F:find("F")o={[1]=F}W=#F i=2
repeat s=r()if s==nil then break end o[i]={}for j=1,W do o[i][j]=s:sub(j,j)end i=i+1 until false
function e(i,j)
local k,l,b,c=j+1,j-1,false
if i>=#o or(o[i+1][j]==" "and e(i+1,j)==0)then return 0 end
while k<=W do
b=b or o[i][k]=="X"
if b or(o[i+1][k]==" "and e(i+1,k)==0)then break end
k=k+1 end
while l>0 do
c=c or o[i][l]=="X"
if c or(o[i+1][l]==" "and e(i+1,l)==0)then break end
l=l-1 end
if b and c then for m=l+1,k-1 do o[i][m]="~"end return 1 end
return 0 end
e(1,f)for i=2,#o do for j=1,W do w(o[i][j])end w"\n"end
```
Test cases (with water source):
```
---------
F
X~~X
XXXX
--------------------
F
X X~X
X X X XX~X~~XX~~~X
XXXXXX XXXXXXXXXXXXX
--------------------
F
X X X
X~~X~X XX X XX X
XXXXXX XXXXXXXXXXXXX
--------------------------------------------------
F
X~~~~~~~~~~~~~X
X~~~~~~~~~~~~~X~X
X~~~~~~~~~~~~XXX~~~~~~~X~~~~X~X~~~~~~~~~~~X X
X~~~X~~~~~XXXXXXX~~~~~~X~~~~XXX~~~~~XXXXXXX X X
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXX
```
from bash it is possible to test this way, but it doesn't look so nice:
```
$ echo " F
X X
XXXX " | lua f.lua
```
[Answer]
# perl -p0, 204+2 bytes
**IDEA**
* If both sides of the island below F are of equal height, replace all `X *X`es with `X~*X`es on that island.
* If one side is higher, replace all `X *X`es with `X~*X`es between the drain on the lower side and the point closest to F that's higher than the lower side's top.
The land directly below F counts as a part of both sides here.
**[GOLF](https://ideone.com/IyOAfm)**
```
s/.*(F).*
//;$f=@-[1];($%,$r)=map{y///c}/(.{0,$f})\bX+?\b(.*)$/;($a,$b)=map{y///c}/[^~]*^(?(?=(.{$%,$f}X)).{$f} *|.{$f} *X(.*)).{$r}
/m;$a=$%if!$a||$b;$b+=$r;s/(?<=.{$a})\b *\b(?=.{$b})/"~"x length($&)/ge
```
**NOTES**
```
perl -p0e ' # slurp stdin, print the result
s/.*(F).*\n//; # remove the first line, record the index of F
$f=@-[1]; # get the index of F
($l,$r)=map{length}m/(.{0,$f})\bX+?\b(.*)$/;
# gets the distance from either side to the drains closest to F
($a,$b)=map{length}m/[^~]*^(?(?=(.{$l,$f}X)).{$f} *|.{$f} *X(.*)).{$r}\n/m;
# tries to find the lowest line that has at least one X on
# one side of the island, but none on the other
$a=$l if !$a||$b;
$b+=$r; # use the captured groups to calculate the left and right bounds
s/(?<=.{$a})\b *\b(?=.{$b})/"~" x length($&)/ge;
# replace all pools within those bounds
'
```
It might be hard to recognise the original algorithm in this implementation since Perl doesn't support lookbehinds of variable length.
[Answer]
# Javascript, 460 Bytes
[Online demo](http://jakuje.dta3.com/misc/f.html) (in console, tested in current Chrome and Firefox).
```
function e(i,j){var k=j+1,l=j-1,b=0,c=0,I=i+1
if(i>(O-2)||(o[I][j]==" "&&e(I,j)==0))return 0
while(k<W){b=b||(o[i][k]=="X")
if(b||(o[I][k]==" "&&e(I,k)==0))break
k++}while(l>=0){c=c||(o[i][l]=="X")
if(c||(o[I][l]==" "&&e(I,l)==0))break
l--}if(b&&c){for(m=l+1;m<k;m++)o[i][m]="~"
return 1}return 0}function f(d){o=d.split("\n")
F=o[0];s=F.indexOf("F");W=F.length;O=o.length
for(i=0;i<O;i++)o[i]=o[i].split("")
e(0,s);for(i=1;i<O;i++)console.log(o[i].join(""))}
```
Challenging myself is not so fun, but still possible. Same algorithm as the Lua one, now in javascript.
] |
[Question]
[
This challenge is about converting 2D mazes into 1D mazes.
# Overview
```
+-+-+-+-+-+-+ +-+-+-+-+-+-+ graph {
| | | | |A| | B| A B A -- D
+ + + + +-+-+ + + + + +-+-+ \ | C -- D
| | | | | | | | \ | D -- E
+-+-+ +-+-+ + +-+-+ +-+-+ + \ | E -- F
| | |C D E F| C---D-E---F E -- G
+-+-+-+ +-+ + +-+-+-+ +-+ + | | B -- F
| | | | G | | .---G | F -- J
+ +-+-+-+ + + + +-+-+-+ + + .' / | G -- H
| | | | |H|I |J| H I-' J G -- I
+-+-+-+-+-+-+ +-+-+-+-+-+-+ (ascii) } // (graphviz dot)
Figure 1 Figure 2 Figure 3
```
For the purposes of this challenge, a traditional 2D maze is a rectangular maze formed from lattice points where all of the following holds:
* It is closed (the outer rim is connected by walls).
* All lattice points are connected to walls
* It is connected (for every two spaces X and Y there is a path between them)
* It is acyclic (there are no paths from any space X back to X without backtracking)
Figure 1 shows a traditional 2D maze. These mazes have three areas of interest:
* *Dead ends* - places from which there is only one available path
* *Corridors* - places from which there are two available paths
* *Decision points* - places from which there are three or four available paths
For every such maze, one can create a graph where the dead ends and decision points are nodes, and there is an edge between every two nodes connected by a path along a corridor. Figure 2 shows the same maze with such nodes labeled, and Figure 3 the maze's graph (in ASCII and Graphviz dot notation).
## 1D mazes
1D mazes incorporate warp points, which come in pairs, and are identified using a letter (in either case). Figure 4 shows an example 1D maze. This is otherwise identical to a 2D maze with a height of 1, as shown in Figure 5. Note in particular in Figure 5 the lattice point positions marked by `+`, which alternate left to right; in the 1D maze, every other character starting with the leftmost wall is also a lattice point.
```
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| D| D E|G E F| F | G | | D| D E|G E F| F | G |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Figure 4 Figure 5
```
The rules for navigating this maze are as follows. Every move can be represented as either forward (`>`) or backward (`<`). Forward and backward here by default have the same meaning as our intuitive spatial awareness; forward goes to the position immediately to the right, and backwards immediately to the left.
Warp points represent locations that asymmetrically swap connectedness with neighbors. If you're coming from a neighbor to a warp point, the position of the two warp points is swapped; if you're coming from a warp point to a neighbor, they are not swapped. For example, in Figure 6, moving backwards from 1 brings you to 2 (since 1 is the neighbor of G, and we're moving from the neighbor, points 2 and @ are swapped). Moving forward from 2 (warp point G) brings you to 3 (here, we're starting from a warp point, so there's no swap). Likewise, moving backwards from 3 brings you to @.
```
54 2367 89^ @1
| D| D E|G E F| F | G |
Y X
Figure 6
```
Figure 6 also shows an example navigation from X to Y, using the sequence of moves `<<>><>>>>>`. These moves bring you to the points labeled `123456789^` respectively, in that order. Feel free to explore it yourself using the code snippet in the next section.
## Converting 2D to 1D
Given a 1D maze, one can create a graph where each node is either a dead end or a warp point pair, and edges exist between any two nodes connected along a corridor. This graph allows us to compare 1D and 2D mazes.
For example, the 1D maze in Figure 4 is the same maze in Figure 1. To see why, Figure 7 adds labels to dead ends. Using those labels to build a graph, Figure 7's graph is simply Figure 3 again. Figure 8 shows a breakout of building this graph.
```
| D| D E|G E F| F | G |
A C B J H I
Figure 7
| D| D E|G E F| F | G |
+ + + + + + + + + + + + + + + <- lattice points
|A |C | |B J|H I| <- dead ends
|A D|C D E|G E F|B F J|H G I| <- all nodes (dead ends+warp points); i.e.:
"where each end is either a dead end
or a warp point pair"; note that each
pair of warp points is the same node.
|A-D|C-D-E|G-E-F|B-F-J|H-G-I| <- corridors; note each is a connection, since
1 2 3 4 5 6 7 8 9 "edges exist between any two nodes
connected along a corridor"
graph { graph {
A -- D // 1 <----> A -- D
C -- D // 2 <----> C -- D
D -- E // 3 <----> D -- E
G -- E // 4 <----> E -- G
E -- F // 5 <----> E -- F
B -- F // 6 <----> B -- F
F -- J // 7 <----> F -- J
H -- G // 8 <----> G -- H
G -- I // 9 <----> G -- I
} ^ }
Built from | From Figure 3
1D maze `-> isomorphic mappings
Figure 8
```
(Note that the labels and layout of each graph were artificially chosen to align for illustration purposes; generally speaking this is a [graph isomorphism problem](https://en.wikipedia.org/wiki/Graph_isomorphism)).
The following snippet is provided to help visualize the mechanics of the 1D maze and the connection between the 1D maze, the equivalence graph, and the 2D maze.
```
var mazeloc = 27; var cheese=21; var pnode=9; var cnode=9;
var spacing = " ";
function newCheese() {
while(cheese==mazeloc){
var rnum=Math.ceil(Math.random()*23);
if(rnum>3) ++rnum; if(rnum>9) ++rnum; if(rnum>15)++rnum; if(rnum>21)++rnum;
cheese=rnum;
}
document.getElementById("cheese").innerHTML = spacing.substr(1,cheese)+"#";
}
function getNodeClass(node) {
switch (node) { case 1: return "ANode"; case 2: return "BNode"; case 3: return "CNode";
case 4: return "DNode"; case 5: return "ENode"; case 6: return "FNode";
case 7: return "GNode"; case 8: return "HNode"; case 9: return "INode"; case 10: return "JNode"; } }
function getNodeDefCol(node) {
switch (node) { case 1: case 2: case 3: case 8: case 9: return "#666"; default: return "#000"; } }
function markMove() {
var newNode = nodeByLocation(mazeloc);
if (newNode==0) return;
var pn = document.getElementsByClassName(getNodeClass(pnode));
for (var i=0; i<pn.length; ++i) { pn[i].style.color = getNodeDefCol(i); pn[i].style.backgroundColor = "#FFF"; pn[i].style.fontWeight = "400";}
var cn = document.getElementsByClassName(getNodeClass(cnode));
for (var i=0; i<cn.length; ++i) { cn[i].style.color = "#800"; cn[i].style.backgroundColor = "#ED9"; cn[i].style.fontWeight="700"; }
var nn = document.getElementsByClassName(getNodeClass(newNode));
for (var i=0; i<nn.length; ++i) { nn[i].style.color = "#F00"; nn[i].style.backgroundColor = "#FE8"; nn[i].style.fontWeight="700"; }
pnode=cnode; cnode=newNode;
}
function nodeByLocation(loc) { switch(loc) { default: return 0;
case 1: return 1; case 17: return 2; case 5: return 3; case 3: case 7: return 4;
case 9: case 13: return 5; case 15: case 19: return 6; case 11: case 25: return 7;
case 23: return 8; case 27: return 9; case 21: return 10; } }
function onClickLeft() {
switch (mazeloc) {
case 1: case 5: case 11: case 17: case 23: break;
case 8: mazeloc=3; break; case 12: mazeloc=25; break;
case 14: mazeloc=9; break; case 20: mazeloc=15; break;
case 26: mazeloc=11; break; default: mazeloc=mazeloc-1; break;
}
if(mazeloc==cheese) newCheese();
markMove();
document.getElementById("inmaze").innerHTML = spacing.substr(1,mazeloc)+"@";
}
function onClickRight() {
switch (mazeloc) {
case 3: case 9: case 15: case 21: case 27: break;
case 2: mazeloc=7; break; case 6: mazeloc=3; break;
case 8: mazeloc=13; break; case 12: mazeloc=9; break;
case 14: mazeloc=19; break; case 18: mazeloc=15; break;
case 24: mazeloc=11; break; default: mazeloc=mazeloc+1;
}
if(mazeloc==cheese) newCheese();
markMove();
document.getElementById("inmaze").innerHTML = spacing.substr(1,mazeloc)+"@";
}
```
```
<div><div style="float:left">
<pre><div id="cheese" style="color:#FA0; font-weight:bold"> #</div>|<font class='ANode' color='#666'>A</font> <font class='DNode'>D</font>|<font class='CNode' color='#666'>C</font> <font class='DNode'>D</font> <font class='ENode'>E</font>|<font class='GNode'>G</font> <font class='ENode'>E</font> <font class='FNode'>F</font>|<font class='BNode' color='#666'>B</font> <font class='FNode'>F</font> <font class='JNode' color='#666'>J</font>|<font class='HNode' color='#666'>H</font> <font class='GNode'>G</font> <font class='INode' color='#666'>I</font>|
<div id="inmaze" style="color:#00F; background-color:#FFD"> @</div><div id="dbg"></div></pre>
<div style="float:left"><button type="button" onclick="onClickLeft()"><</button></div>
<div style="float:right"><button type="button" onclick="onClickRight()">></button></div></div>
<div style="float:left">
<pre> <font class='ANode' color='#666'>A</font> <font class='BNode' color='#666'>B</font>
\ |
\ |
\ |
<font class='CNode' color='#666'>C</font>---<font class='DNode'>D</font>-<font class='ENode'>E</font>---<font class='FNode'>F</font>
| |
.---<font class='GNode'>G</font> |
.' / |
<font class='HNode' color='#666'>H</font> <font class='INode' color='#666'>I</font>-' <font class='JNode' color='#666'>J</font></pre>
</div>
<div style="float:left">
<pre> +-+-+-+-+-+-+
|<font class='ANode' color='#666'>A</font>| | <font class='BNode' color='#666'>B</font>|
+ + + + +-+-+
| | | |
+-+-+ +-+-+ +
|<font class='CNode' color='#666'>C</font> <font class='DNode'>D</font> <font class='ENode'>E</font> <font class='FNode'>F</font>|
+-+-+-+ +-+ +
| <font class='GNode'>G</font> | |
+ +-+-+-+ + +
|<font class='HNode' color='#666'>H</font>|<font class='INode' color='#666'>I</font> |<font class='JNode' color='#666'>J</font>|
+-+-+-+-+-+-+</pre>
</div></div>
```
As you navigate the 1D maze in this snippet, the last two nodes you touch are highlighted. The same nodes are highlighted the same way on the equivalence graph and the 2D maze.
---
In general, for any traditional 2D maze an equivalent 1D maze of this type can be created. A slightly more complex example is Figure 9:
```
+-+-+-+-+-+-+ +-+-+-+-+-+-+ graph {
| | | | | |A| | |B| A B A -- D
+ + + + + + + + + + + + + + \ / C -- D
| | | | | | | | | | \ / D -- E
+-+-+ + +-+-+ +-+-+ + +-+-+ \ / B -- E
| | |C D E | C---D-E E -- F
+-+-+-+ +-+ + +-+-+-+ +-+ + |\ E -- I
| | | | F | | .---F \ F -- G
+ +-+-+-+ + + + +-+-+-+ + + .' / \ G -- H
| | | | |G|H |I| G H-' I H -- I
+-+-+-+-+-+-+ +-+-+-+-+-+-+ (ascii) } // (graphviz dot)
Figure 9 Figure 10 Figure 11
| D| D E |F E | F | | D| D E |F E | F |
A C I B G H
Figure 12 Figure 13
```
This maze has a node with four paths (E in Figure 10). Figure 11 shows its graph. Figure 12 is an equivalent 1D maze; and Figure 13 shows the same maze with labels for dead ends to compare with Figure 11.
# Challenge
Given a 2D Maze as input, write a function or program that transforms the 2D maze into a 1D maze with warp points. Warp points may use any of the 52 letters in each case.
Input guarantees (if any of these aren't met in the input you don't have to deal with it):
* The input maze is connected (that is, you can always go from any spot to any other).
* The input maze is closed.
* The input maze is rectangular.
* All lattice points use `+`.
* All walls between lattice points on the same row use `|`
* All walls between lattice points in the same column use `-`.
* All spaces are part of a path (and all inside the maze).
* Paths are all spaces (this will always be traditional, non-warping)
* Paths are exactly one space wide.
* The maze is built by connecting points on a lattice.
* There are no more than 52 total nodes (i.e., dead ends plus decision points) in the maze's graph.
Output format:
1. Your output should be **a single line** showing a 1D maze.
2. Your output should have no leading/trailing whitespace; except that a trailing newline is fine.
3. The first character and every other character afterwards are lattice points.
4. All walls should be on lattice points; and all warp points between them.
5. The graph of your 1D maze should be equivalent to the graph of the 2D maze.
6. Your 1D mazes must be compact; all non-lattice points must be dead ends (i.e., adjacent to walls) or warp points.
7. The **only letters** in your output should be warp points. Each warp point occurs on the line exactly twice.
Example:
```
| D| D E|G E F| F | G | <- (1,2) The single line output
+ + + + + + + + + + + + + + + <- lattice point spacing... (3)
(4,6) lattice points are all walls or spaces
(5) See Figure 8
(7) D, E, F, G appear twice; no other labels
```
This is code-golf. The winner is the correct non-loophole submission with the least bytes.
# Testing
There are no test cases for this challenge, since there are a large number of correct outputs for any nontrivial maze.
[I have, however, built a checker in C++](http://ideone.com/CgkW7g) (this checker graphs both solutions through a [graph canonicalization](https://en.wikipedia.org/wiki/Graph_canonization)).
In addition, here are a few examples to help illustrate proper formatting:
*Example 1*
```
+-+-+-+-+-+-+
| | | |
+ + + + +-+-+
| | | |
+-+-+ +-+-+ +
| |
+-+-+-+ +-+ +
| | |
+ +-+-+-+ + +
| | | |
+-+-+-+-+-+-+
->
| D| D E|G E F| F | G |
```
*Example 2*
```
+-+-+-+-+-+-+
| | | | |
+ + + + + + +
| | | | |
+-+-+ + +-+-+
| |
+-+-+-+ +-+ +
| | |
+ +-+-+-+ + +
| | | |
+-+-+-+-+-+-+
->
| D| D E |F E | F |
```
[More examples can be found in here](http://pastebin.com/az5PBHKU).
[Answer]
# Haskell - ~~481~~ ~~405~~ 387 bytes
```
import Data.List
s&t=elemIndices s t
l=last
c!(x:y:z)=l$(y:c)!(x:z):do{[x:p,q]<-mapM([id,reverse]<*>)[[x],[y]];x&[l q];[[]!((q++p):c++z)]}
c![x]=x:[]!c
c!z=z
main=interact(\m->let{g=' '&m;
u=(\\[k|k<-g,length(v>>=(k&))==2])<$>[]!v;
v=[[x,y]|x<-g,y<-g,elem(y-x-1)[0,head$'\n'&m]];
}in '|':(u>>=(++"|").init.(>>=(:" ").toEnum.((+)<*>(+65).(*32).(`div`26)).l.(-1:).(&(nub$u>>=init.tail)))))
```
This creates a list of spaces that are in the maze, numbered by index in the string, and uses it to find all the pairs of adjacent spaces. It then stitches the pairs together into longer sequences of points based on matching first/last elements and removes the corridors, so that each sequence is one room in the 1D maze. The sequences are then translated into a string by replacing points on the interior of at least one room (the warp points) into corresponding letters and the rest into spaces.
The 2D maze is read from STDIN and the 1D maze is printed to STDOUT.
Edit: Reduced by 62 bytes rearranging a bunch of stuff and modifying the algorithm a bit, and another 14 by replacing `chr` with `toEnum` as suggested by Laikoni.
Edit 2: Saved 13 more bytes by simplifying the logic in `(!)`, 3 by using the list pattern match sugar, and 2 by using `>>=` to concat in `u`.
[Answer]
# Python 2 with [igraph](http://igraph.org/python/), ~~492~~ 369 bytes
```
import igraph,string
def f(s):
C=s.find('\n')/2;N=' ';g=igraph.Graph(0,[(i,i+j)for i in range(len(s)/(4*C+4)*C)for j in(1,C)if s[(i/C*2+1)*(2*C+2)+i%C*2+2*j+j/C*3]==N]);V=g.vs;g.d=g.degree;O='';V(_d=1)[N]=N;V(_d_gt=2)[N]=list(string.ascii_letters)
while g.es:
v=V(_d=1)[0];O+='|'+v[N]
while g.d(v):w=v.neighbors()[0];g-=(v,w);v=w;O+=N+v[N]if v[N]else''
print O+'|'
```
(The fifth and sixth lines each begin with a tab, not four spaces as StackExchange shows.)
* Saved six bytes rearranging some arithmetic
* Saved seven bytes using a slice instead of zip
* Saved three bytes using `g+=tuple(v.neighbors())` instead of `g.add_edge(*v.neighbors())`
* Saved seven bytes using `g-=g.es[g.incident(v)]` instead of `g.delete_edges(g.incident(v))`
* Saved eleven bytes aliasing `g.d=g.degree`
* Saved 52 bytes (!) eliminating a loop which contracted all the corridors by replacing degree-2 vertices with an edge between their neighbors. Instead, the output loop just ignores these vertices.
* Saved 13 bytes noticing that when assigning names, igraph doesn't care if the provided iterable is too long
* Saved four bytes by not having a variable `R` for the number of rows, moving its calculation to the only use point
* Saved two bytes changing the second-level indentation to tabs instead of spaces
* Saved six bytes rearranging `2*(i%C)` to `i%C*2`, `2*(i/C)` to `i/C*2`, and `(C-1)*j` to `j*C-j`
* Saved four bytes naming `N='n'`
* Saved one byte determining if a character is space using `<'-'` rather than `==' '`, under the assumption that only valid characters appear.
* Then realized I can name the vertex attribute `' '` instead of `'n'`, and reuse `N` for the two literal spaces in the source, and `==N` instead of `<'-'`, saving five more bytes
A somewhat ungolfed version follows. The basic idea is to first make a graph on all the maze vertices (the spots with odd row and column when zero-indexed.) There is an edge from one vertex to the next one on the same row if the following character is a space, and not `|`. There is an edge from the vertex to the one right below it if the corresponding character in the following row is a space, and not `-`.
After building this graph, we pick any leaf, and follow along successively adjacent vertices, writing out their names if they are not a corridor, and deleting used edges, till we get stuck. Then we take another leaf and continue till all the edges are gone.
```
import string
import igraph
def f(s):
C = s.find('\n')/2 # number of maze vertices in each row
R = len(s)/(4*C+4) # number of rows
def strpos(r, c):
"""Index of the vertex at row r, col c in the newline-delimited string s"""
return (2*r+1)*(2*C+2) + 2*c + 1
def vertpos(i):
"""Index of the i-th vertex in s"""
return strpos(i/C, i%C)
g = igraph.Graph(edges=[(i, i+(C if j else 1))
for i in range(R*C)
for j in (0, 1)
if s[vertpos(i)+(2*C+2 if j else 1)] == ' '])
V = g.vs # the graph's vertex sequence
O = ''
V(_degree=1)['n'] = ' ' # All leaves are named space
W = V(_degree_gt=2) # All warp points...
W['n'] = list(string.ascii_letters[:len(W)]) # ...are named successive letters
while g.es: # while any edges remain...
v = V(_degree=1)[0] # find a leaf
O += '|'+v['n'] # start a new 'block'
while v.degree():
w = v.neighbors()[0] # pick a neighbor
g -= (v, w) # delete that edge
v = w
if v['n']: # If it's a dead end or warp point...
O += ' '+v['n'] # ...write out the new neighbor
print O+'|'
```
You can see [results for the five example mazes](http://kundor.github.io/mazegraf.html). (Unfortunately, `igraph` is not available on Try It Online; these results were exported from [SageMathCloud](https://cloud.sagemath.com/projects/497fa7b7-8b66-48c4-aa11-37c5b09ce41c/files/mazegraf.ipynb).)
] |
[Question]
[
## Introduction
Suppose for a moment that the vipers and cliff are only **two** steps away, instead of three.
```
o
---
Hsss! |
';;' ___ /_\ ___ _
|
```
You are, unfortunately, a captive of a sadistic torturer. You **must** take a step either to the left or to the right every turn. If you don't, they shoot you dead instantly. You are allowed to plan out your steps beforehand, but once you take your first step, you can't change your plan. (And no dawdling either; they'll shoot you.)
Suddenly, a bright idea comes to mind...
>
> Ah! I can just alternate stepping right and left! Step right, step left, step right, step left, and so on...
>
>
>
Ah ah ah, not so fast. Like I said, the torturer is sadistic. They get to choose whether you take every step, or every second step, or every third step, and so on. So if you naively choose the sequence `RLRLRL...` then they can force you to take every second step, which starts with `LL`. Uh oh! You've been bitten by vipers! Blackness swoops over you and all else fades away...
Actually no, you're not dead yet. You still have to come up with your plan. After thinking about it for a few minutes, you realize you are doomed. There is no way to plan out a series of steps that will guarantee your survival. The best you can come up with is `RLLRLRRLLRR`.1 Eleven safe steps and no more. If the twelfth step is `R`, then the Torturer will make you take every step and then the last three steps send you off the cliff. If the twelfth step is `L`, then the Torturer will make you take every third step (`LRLL`), which puts you right in the brood of vipers and their lethal bites.
You pick `R` as the twelfth step, hoping to delay your demise as long as possible. With the wind roaring in your ears, you wonder to yourself...
>
> What if I had three steps?
>
>
>
---
**Spoiler alert!**
You would still die. As it turns out, no matter how many steps you have, there will be some point where no matter what choice you make, there is a sequence of steps your Torturer can pick to ensure you meet your deadly fate.2 However, when the vipers and cliff are three steps away, you can take a total of 1160 safe steps and when they're four steps away, there are at least 13,000 safe steps!3
## The challenge
Given a single integer `n < 13000`, output a sequence of `n` safe steps, assuming the cliff and the vipers are four steps away.
## Rules
* Can be either a full program or a function.
* Input can be taken through STDIN or equivalent, or as a function argument.
* Output must have **two distinct characters** (which can be `+/-`, `R/L`, `1/0`, etc.).
* Any whitespace in the output doesn't matter.
* Hard-coding a solution is not allowed. That would trivialize this challenge.
* Your program should (in theory) finish in a decent amount of time. As in, `n=13000` might take like a month, but it shouldn't take a thousand years or more. That is, **no brute force.** (Well, at least *try* to avoid it.)
* **Life bonus:** provide a series of `2000` safe steps. If you do this, the Torturer will be so impressed by your tenacity, perseverance, and forethought that they'll let you live. *This one time.* (Treat this sequence as a binary number and provide the decimal equivalent for verification. This is intended to reward answers that finish quickly as answers are allowed to take a very long time.)
* **Score: bytes**, unless you qualify for the **bonus - multiply by 0.75**.
---
1 There is a good explanation of this problem and "solution" by one of the stars of Numberphile, James Grime, over on his YouTube channel here: <https://www.youtube.com/watch?v=pFHsrCNtJu4> .
2 This 80-year-old conjecture, known as Erdos' discrepancy problem, was proved very recently by Terence Tao. Here is a very nice article on Quanta Magazine about this: <https://www.quantamagazine.org/20151001-tao-erdos-discrepancy-problem/> .
3 Source: [*A SAT Attack on the Erdos Discrepancy Conjecture*](http://arxiv.org/abs/1402.2184), by Boris Konev and Alexei Lisitsa. Retrieved from here: <http://arxiv.org/pdf/1402.2184v2.pdf> .
[Answer]
# Java, 915 \* 0.75 = 686.25
```
import java.util.*;class E implements Comparable<E>{static
int n,m,t,u;byte[]a;int k=2,b,d;E(){a=new byte[5];a[1]=13;}E(E
x){a=Arrays.copyOf(x.a,n+1);k=x.k;d=x.d;b=x.b;}int
g(int x){return(a[x]+1)%3-1;}void s(int x,int y){a[x]=(byte)(a[x]/3*3+(y+3)%3);}void
S(int x,int y){a[x]=(byte)(a[x]%3+(y+3)*3);}E
w(int x){if(g(k)==-x)return null;E e=new E(this);e.s(k,x);e.S(e.k++,x);for(m=0;++m<k;)if(k%m<1){u=e.a[m]/3-3+x;if(u==(k<9?2:4)*x)return
null;e.S(m,u);if(u==3*x){e.b++;if(k+m<=n){if(e.g(k+m)==x)return
null;e.s(k+m,-x);}}}return e;}public int compareTo(E o){m=d-o.d+(b-o.b)/60+(o.k-k)/150;return
m==0?o.k-k:m;}public static void main(String[]a){n=Integer.valueOf(a[0]);Queue<E>q=new PriorityQueue<>();q.add(new
E());for(;;){E x=q.remove(),y;if(x.k>n){for(t=0;++t<x.k;)System.out.print((x.g(t)+1)/2);return;}t=x.g(x.k<9?1:x.k%9==0?x.k/9:x.k%9);y=x.w(t);if(y!=null)q.add(y);y=x.w(-t);if(y!=null){y.d++;q.add(y);}}}}
```
Input is taken as a command-line argument.
This tries almost all possibilities (the only restriction is that the first 8 steps should only go within -1..1), going step by step, using a magic voodoo heuristic to choose which way to try first.
It solves 2000 and even 4000 within 1 second on my (fairly fast) computer. Needs more RAM for bigger numbers; the largest input I solved within 8GB is 5023 and it took about 30 seconds.
Decimal representation of the solution for 2000 steps, as requesed for the bonus:
```
67629177464446960798008264442022667063957880432486338092706841703491740570274032860458934082821213021464065304260003487277917407152662394728833698812373924467640518368465012204980858438160127647802572983143425507448999967241207186701518207195015015739598846687434709056793597015487555707466358473564611432637890414593517116857771284711814076853125419306285869381974622557155019992727242896503018802441210966188045211779436703341152749688824296759097963388158731237092792251164105828728858516951458791084595247591674731645830905744761534078963607725435881491831508342871545788662307953494333833994658998
```
Append `Yb` to it in [CJam](http://cjam.aditsu.net/) to convert back to binary.
About the heuristic: first, there is a pattern I'm using: every 9 steps try to repeat the first 9, except every (9\*x)th step tries to repeat the x'th step. This is inspired from the solution I downloaded and used (hardcoded) in my python answer.
I'm keeping track of the number of times I deviated from the pattern, and also the number of times I got to an "edge" (1 step from dying). The heuristic function is basically a weighted combination of those 2 numbers and the number of steps taken so far.
The heuristic could be further tweaked to improve the speed, and there are several ways to add a random factor into it too.
In fact, I've just read about multiplicative functions in relation to this problem, and it looks like that can provide a *significant* improvement (TODO: implement this later).
Ungolfed and commented:
```
import java.util.*;
public class Erdos implements Comparable<Erdos> {
static int n; // input (requested number of steps)
static int m, t, u; // auxiliary variables
byte[] a; // keeps each step and sum combined into 1 byte
int k = 2; // number of steps + 1 (steps are 1-based)
int edge; // number of times we got to an edge
int diff; // number of differences from the expected pattern
// start with one step
Erdos() {
a = new byte[5];
set(1, 1);
setSum(1, 1);
}
// copy constructor
Erdos(Erdos x) {
a = Arrays.copyOf(x.a, n + 1);
k = x.k;
diff = x.diff;
edge = x.edge;
}
// get the x'th step (can be -1, 0 or 1)
int get(int x) {
return (a[x] + 1) % 3 - 1;
}
// set the x'th step
void set(int x, int y) {
a[x] = (byte) (a[x] / 3 * 3 + (y + 3) % 3);
}
// get the sum of every x'th step (should be within -3..3)
int getSum(int x) {
return a[x] / 3 - 3;
}
// set the sum of every x'th step
void setSum(int x, int y) {
a[x] = (byte) (a[x] % 3 + (y + 3) * 3);
}
// try to add a step with value x (1 or -1)
Erdos grow(int x) {
if (get(k) == -x) // predetermined step doesn't match
return null;
Erdos e = new Erdos(this);
e.set(k, x);
e.setSum(e.k++, x);
for (m = 0; ++m < k;)
if (k % m < 1) { // check all divisors of k
u = e.getSum(m) + x; // updated sum
if (u == (k < 9 ? 2 : 4) * x) // use limit 2 for the first 8 steps, 4 for the rest
return null; // dead
e.setSum(m, u);
if (u == 3 * x) { // we're at an edge
e.edge++;
if (k + m <= n) { // predetermine future step - should be going back
if (e.get(k + m) == x) // conflict
return null;
e.set(k + m, -x);
}
}
}
return e;
}
public int compareTo(Erdos o) { // heuristic function
m = diff - o.diff + (edge - o.edge) / 60 + (o.k - k) / 150;
return m == 0 ? o.k - k : m;
}
public static void main(String[] a) {
n = Integer.valueOf(a[0]);
Queue<Erdos> q = new PriorityQueue<>();
q.add(new Erdos());
for (;;) {
Erdos x = q.remove(), y;
if (x.k > n) { // we made it
for (t = 0; ++t < x.k;)
System.out.print((x.get(t) + 1) / 2);
return;
}
t = x.get(x.k < 9 ? 1 : x.k % 9 == 0 ? x.k / 9 : x.k % 9); // next step based on the pattern
y = x.grow(t);
if (y != null)
q.add(y);
y = x.grow(-t);
if (y != null) {
y.diff++;
q.add(y);
}
}
}
}
```
[Answer]
# Python 2, 236 bytes
```
n=input();r=len;u=[("",[0]*(n//4))]
while n>r(u[-1][0]):
y,t=u.pop()
for c in 0,1:
s=t[:];u+=(y+"LR"[c],s),
for i in range(r(s)):
if-~r(y)//-~i*-~i==-~r(y):s[i]+=2*c-1;
if abs(s[i])>3:u.pop();break;
print(u[-1][0])
```
This is fairly fast, for a brute-force-ish method, only taking a few seconds for n=223, but much longer for n>=224.
**Explanation:**
Keep track of a list of string-list pairs (s,u), where the list u is such that u[i] is the current position after following every ith step in the string. For each string in the list, try to add "L" or "R", then change the values in the list that intersect. (i.e. if the resulting string has length 10, add or subtract 1 from positions 1,2,5 and 10, according to the directions you moved). If you exceed 3 or -3 throw the new pair away, otherwise keep it in the list. The longest strings are kept at the end. Once you have a string of length n, return it.
[Answer]
# Python 2, 729 bytes
```
n=0
for x in"eJytVU2LwyAQPWzTvZjjspcsxFYTBdNuQSEF+///1jp+p5o0hYVSBl9nfOObNz1MlAgqzMcEEwQkDyIkFpDYCW0UnChbyZJiK2sfhDcYmu9hT0GdIPQvLduAmoCvvqEssvq84CVCpLzrNcOOspLhY6/KswB6FmoSxGPBcWts7lsMp/0q83da1hgC6k7GoqBir1ruAFIVvWIdTi++oGIAyZw8mkuG03uDDc+rEsSWTmFBwbLgtTF8hl1e/lpCigR7+pM5V9lIqVJBjStzKNRRQDp6UOrvwga6VFrGcWz6YHwLNYWUYeZfWO/DQTq7i4dAxixeszmtFEw7Cr5v9R3lRVF55TDzY6QRrSfzF9NLE7lAZ+vLnGgYLZ/FlCuoRcOugeFduHTqRWmyh1J91XpIndIbEk8jifL8hs8qQ8vjAVoGqhK5Tm/O5svpXd82QH4Azq05kYnhj93PzLbcTisFzXWfDqIC5zsq3jU7UUhSh1R3L4+i4HCXKlrGyywSBttPr2zpL4gCDPtk2HPN5tgZFomzSDPfGAlASus+e4KlLcjS0vPQ0f5/mR/r1s4PcxsgMLRSMp617AveCuup2OCAPBT6yltWrPO9azsbp6fphR87Lc7VzcbEt5F4Ydg/NzhXTA==".decode("base64").decode("zip"):n=n*64+ord(x)
print bin(n)[2:input()+2]
```
I think this qualifies for the bonus too if the idea is "to reward answers that finish quickly".
However, this is a hard-coded answer, which is not in the spirit of the challenge (although not explicitly disallowed when I wrote it).
] |
[Question]
[
## Background
The United States has a unique love of gerrymandering––the deliberate manipulation of an electoral district to predict certain voting results. Just recently there was a [gerrymandering case](https://www.politico.com/story/2017/10/03/supreme-court-gerrymandering-wisconsin-arguments-243401) brought before the Supreme Court. Gerrymandering, especially when related to race, is ruled illegal and results in the requirement to redraw the district lines.
Given a rectangular map of a municipality (2d array), you will draw district lines to help your party get the most representation. That is, you will gerrymander. Every municipality has two parties, `0` and `1`. The map will be comprised of squares with either `0` or `1` on them. Here is an example map:

## Challenge
You will group the map into districts so that the `1` party will get at least the number of districts specified by the Input.
## Input
The input will consist of a map, the number of districts to draw, and the minimum number of districts the `1` party needs to win (the minimum score).
## Output
The output will be a map of the districts. Each district will be uniquely comprised of a capitalized letter of the alphabet. Yes, this means that there will not be more than 26 districts.
If there is no possible output where the inputted party wins enough districts, either:
1. Print “We tried...”
2. Fatally error because the party was irreparably injured by the election results
3. Or both
## Rules (also very important)
1. All districts must be contiguous
2. Districts may not have other districts in them
3. Each district must have at least four nodes in it. The input will be consistent with the rules, meaning that there will be at least `number_of_districts * 4` nodes in the map
4. The score of each party is the number of districts it has a majority in
5. If a district has the same number of `0`s and `1`s, then neither party benefits from it
6. Normal no-cheating rules
7. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins.
## Test cases
```
1. Input 1. Output 2. Input 2. Output 3. Input 3. Output
districts: 5 Image and map districts: 3 Image below districts: 3 fatal error
min wins: 3 min wins: 3 min wins: 3
map: map: map:
00000110000 AAAAAAAAAAA 101101 101101
10000010000 AAAAAAAAAAA 100000 100000
10010000011 AAAAAAAAAAA 011011 011011
11001110000 BBBBBBBAAAA 111111 100111
00111111000 BBBBBBBAAAA
01111111000 CCCCCDDDAAA
01111111001 CCCCCDDDAAA
01000111100 EEEEEDDDDDD
00000001000 EEEEEDDDDDD
```

Of course, your program should work for *any* valid test case, not just these ones.
[Answer]
# [R](https://www.r-project.org/), ~~938~~ ~~896~~ ~~858~~ 952 bytes
```
function(N,M,m){U="We tried...
"
L=length
A=matrix
W=which
K=sum
S=sample
G=unique
H=function(s,p=s-1){Y=S(c(s-j,s+j,p*(p%%j>0),(s+1)*(s%%j>0)))
Y[Y>0&Y<=k]}
C=function(v,z=W(r==v))K(z%%j<2,z-j<0,(z+j)>k)
m=A(strsplit(m,"")[[1]],1)
i=W(m<0)[1]-1
m=((t(A(m,i+1))[,1:i]>0)-.5)*2
if((K(m)<M&(N-M)<1)|K(m>0)<(3*M))cat(U) else{j=max(1,nrow(m))
k=i*j;w=g=T
while(w<9&g){Z=R=N;Q=M;b=0
r=A(0,j,i)
while(b<9&g){s=W(r<1)
s=s[S(L(s))][1:min(L(s),R)]
r[s]=1:L(s);a=0
while(K(r<1)>0&a<(k^2)){a=a+1
s=S(W(r>0&r<=R),1);p=r[s]
Y=H(s)
Y=Y[r[Y]<1]
if(L(Y)){Y=Y[order(m[Y])]
if(K(m[r==p]>1))r[Y[1]]=p else r[Y[L(Y)]]=p}}
if(a<(k^2)){for(v in 1:R){if(K(m[r==v])>0){r[r==v]=max(k,max(r))+1
Q=Q-1;Z=Z-1}}
if(Q<1){g=F
for(v in 1:R)r[r==v]=max(k,max(r))+1
for(v in G(c(r)))g=g|(K(r==v)<4)|(L(G(r[H(W(r==v))]))+C(v))<3}}
b=b+1;r[r<=R]=0;R=Z}
w=w+1}
if(g)cat(U) else{u=G(c(r))
for(v in 1:L(u))r[r==u[v]]=v
cat(paste(apply(A(LETTERS[r],j,i),1,paste,collapse=""),collapse="
"))}}}
```
[Try it online!](https://tio.run/##dVPbbtpAEH3fr7CQEs3AgrykfSh4kKKIJhIXCUgUGcuVDHGIAYPr5ZJC@HY6axOSVCoP9pydM2dmj4f02KUryxIdqlr8ii0SBdv8lDJPoXLwHp@gEiatTpwsyoE4hf/ESmSVORC2fRYVBSGadHxeL8araLmAruzIGPcPVHgMrVUahU@VSoVJbZqHi8nqRVxTHPD5q3ik7Us0fhEt0utYDEgHcTIPxS2tF9HvdSju6CyqZUK6rHDv0gDGoMtTqUtTmRQhubiYNmyUoEsKi6BziChcz23Yl65DM/8gbj6kNnJHj5ASbRBbsGO@U5W78tSxJexKU2zMUMR0DXqV6mQerSCWhQJ6nvJ9qVBEXBw7NjIuKyYCrOCaORG3R0@qWuRz/3LlOxarInoGaEGMTucSuuUOOgrfGDPBgatiB3EcrOABrXCuw/2UfXkFJRfpcss1KGYUFaf1LU3oXrBT8xC2zo/LCe6H1KduvUed@ohskfKwtpzKCE@sUc7S5prcUWjS3gDaoBF9T9XiaJEB2UdfpJ72SdUMrgcsliu0skK2L3Bg9quKuA8oKClWGgCLciJ1qI/sRz0hIyFcumMJfrle6rm@o3xz@Ta4aL6Z6y3TpzCFmFOYZdgFj79B4jfYNq4w9lKSGWEZaCrNyeFg2OcxnpcpbKxoYalaH/cfOhufp8V9mseZkTNpnikiz92jXlnVhzQsq1ywx9fbT@in@CL4v/Iz6ZZ3j49wQpM3Y5JZIucbvvFFbyH17uB9sXyuuwEOnCtuOKJRSdVZnU3zya73aXgQW9qWVDbM5MsarOnU5fNsbVhjPt7a27AvG2FKkkCvQgiSZP6Hd7DdvL9v9gde6mfLIJXM8nK8nM@DRIfEa/wJiALi4XA4Nk//2ONf "R – Try It Online")
A massive ~~>900~~ ~~>800~~ (nope!) >900 bytes solution.
The code works as follows. Let N be the number of electoral districts and M the minimum number of district where 1 wishes to have a majority.
First, the code randomly assigns N districts to different groups. Next, it randomly expands them, i.e. adds a district to a randomly selected group, ensuring that the district is next to a district already belonging to that group. In the expansion process, it gives precedence to a district with a 1 majority, if the district group is not yet a full 1 majority; if the group is already a certain 1 majority, then it gives precedence to a 0 district. It continues until all districts have been assigned.
Every group where there is a majority for the 1 party is stored, and its districts are locked. If there are at least M groups with a majority of 1, then everything is good and ~~we can print the result~~ we can check whether there are at least 4 districts in each group. If the cutoff of 4 districts is met, then we can happily print the result. Otherwise, the code tries to reassign the districts that are not locked to as many groups as available, i.e. N - #stored-groups.
The codes tries a few times (9 times). If it fails, it resets everything and starts again. It does so for other 9 times before giving up and printing "we tried...".
If the code does not succeed at first, try again a few times. I tuned the number of repetitions such that it can run in TIO under a minute. However if there is a solution, this code can (eventually) find it. The randomness part of the algorithm gives a non-zero probability that, if there is a solution, it can find it. The limited number of trials is the only limiting factor to success.
EDIT: added the control that no district group can be fully surrounded by just another one, unless the district group has districts on the edge of the given square. I think I missed it at first.
[Answer]
# Python3, 1067 bytes:
```
E=enumerate
R=range
def P(b):
c=[(x,y)for x,r in E(b)for y,_ in E(r)]
while c:
C=c.pop(0)
q,s=[C],[C]
while q:
x,y=q.pop(0)
for X,Y in[(0,1),(0,-1),(-1,0),(1,0)]:
T=(x+X,y+Y)
if T in c and T not in s and b[x+X][y+Y]==b[x][y]:q+=[T];s+=[T]
yield s;c=[*{*c}-{*s}]
def S(b,g):
k=[0,0]
for x,y in g:k[b[x][y]]+=1
return k[1]>k[0]
def F(n,m,b):
B=eval(str(b))
for G in P(B):
if len(G)<4:
for x,y in G:B[x][y]=int(not B[x][y])
q=[(B,L:=[*P(B)],sum(S(b,i)for i in L))]
H=[L]
while 1:
B,G,C=q.pop(0)
O=max(j for k in B for j in k)+1
if len(G)==n and sum(S(b,i)for i in G)>=m:
for Y,i in E(G,65):
for x,y in i:B[x][y]=chr(Y)
return B
for x in R(len(b)+1):
for y in R(len(b[0])+1):
for X in R(x+1,len(b)+1):
for Y in R(y+1,len(b[0])+1):
if(X-x)*(Y-y)>=4 and S(b,T:=[(j,k)for j in R(x,X)for k in R(y,Y)]):
Q=eval(str(B))
for U,I in T:Q[U][I]=O
if len(W:=[*P(Q)])<=n and len(W)>=len(G)and W not in H and all(len(i)>=4 for i in W)and(N_C:=sum(S(b,i)for i in W))>=C:q+=[(Q,W,N_C)];H+=[W]
```
[Try it online!](https://tio.run/##pVNRT@JAEH6@/oqNL@zCYrqil0t1fShRNCEqHgZIb2MKFC2UFtp6R2P87dzMbql4MXcP16TtTOebb2a@6a6K/DmJW99W6XZ7IYP4ZRmkfh5Y9zL146fAmgYzckfHzLHIRHp0wws2S1Ky4SkJY3IBEXQL/mjclCmL/HoOo4BMIIW05eRwlayozcBZ80x6bcXhBs@g1ogCukKu34EEOYd8BJwetblgHJ5NfDUFt@GFT6UzSV/STWPIi8ZIZ5JwRvrYy4T48RTMOMnRzbQ79gCrPAArKcEBUznrhvT66jTTL@AowiCakuwU5q2/1idvzdd69qa0Et/pmD@hFgvp2dwGtBGjwBJPzsIrOVVDCoukQf6SxmThCXW@8GxDcUljvuRaUFcGP/2IZnkKMjLD1UGmO@piHGeJgph22Nmxs5OlLNZxXFNKhnFOccjSB541LMrlXQf6RybFs5clxdZDvawQ87sMN3UlvW61MIE1XN7h7f1d3Mqlv6FzXXuBma4252guWEPstyllrGX@pF6HnctlNcSIh@Z/6fCvJ8wscm@4sBpu8pxSs9hSTNcqkYi7p1h3DF2wirrYC4DmVcz8Uya4aQj@MbNsy4SLXfhDPs5Jh80Nq9NRs4BxjvWsOGcfpKZzvmCVMlCDD1mlGXDyEVMVE@m9r95lbPcV8Q/8GjP6Ts97UN61kre7aCnzwOy1B3Rnpd76M3RktoBfBrv//koD/CjSioS67WopA8TSm8e2Iz9Z2YABuq2PB@3xAQccU6dX4A7UNhNEkoODA8vGSwh8WsI4O7t0hYVhUWK0ZRyrNP@whaUzjWP4DZeF9bKjsrDAqqKsaWkHK@FlgK2/AnUBDcRTmSeP48RPpzSDHX0p/zXPqy/9FYUDBrKoSpdZGOVBSm@SOOAkO8xWUZjT2o@4hkfKslYpnkj0D@dJGFOkqBmbX9IT3uLvxQTDa5fSrNVPbPYPgtYHgqP/JWhpgu1v)
## Notes:
1. A little longer than the other solution, but deterministic and runs in ~3.65 seconds
2. Fatally-errors if there is no possible output
] |
[Question]
[
A fun game to play if you are bored is the [Diffy Game](http://www.cs.loyola.edu/~lawrie/CS630/F03/Projects/PA1/index.html). It is a one player game that is pretty simple and can consume a good deal of your time.
The Diffy game works like as follows: You start with a list of non-negative integers, in this example we will use
```
3 4 5 8
```
Then you take the absolute difference between adjacent numbers
```
(8) 3 4 5 8
5 1 1 3
```
Then you repeat. You repeat until you realize you have entered a loop. And then generally the game starts from the beginning again.
```
3 4 5 8
5 1 1 3
2 4 0 2
0 2 4 2
2 2 2 2
0 0 0 0
0 0 0 0
```
Often the game has no goal, you are just biding time by doing arithmetic in your head. However when I have the pleasure of playing this game my goal is always to try and pick a period and try to construct a game that loops with that particular period.
Not all games are periodic, the example above is not periodic for example because it eventually reaches a game with all zeros and thus can never make it back to its starting position. In fact it seems that the vast majority of games are not periodic making the few games that are a rare gem.
---
Given a game that loops with a particular period it is trivial to make another game that loops with the same period by just doubling the sequence. For example the game:
```
1 0 1
```
Plays out exactly the same as the game:
```
1 0 1 1 0 1
```
In fact, we can consider that both are really the infinitely repeating game:
```
... 1 0 1 ...
```
We will consider them one game for the sake of this challenge.
In a similar fashion multiplying the entire sequence by a constant will also trivially preserve the period so we once again are going to count any two games that differ by a constant factor to be the same game.
---
The infinite strings `... 1 0 1 ...` and `... 0 1 1 ...` are obviously the same string shifted by one character. We will not count these as different games, but when one reaches the other it will not be considered the end of the cycle when determining the period of a game. For example:
The two games
```
... 0 0 0 1 0 1 ... = A
... 0 0 1 1 1 1 ... = B
... 0 1 0 0 0 1 ... = A << 4
... 1 1 0 0 1 1 ... = B << 4
... 0 1 0 1 0 0 ... = A << 2
... 1 1 1 1 0 0 ... = B << 2
```
and
```
... 0 0 1 0 1 0 ... = A << 1
... 0 1 1 1 1 0 ... = B << 1
... 1 0 0 0 1 0 ... = A << 5
... 1 0 0 1 1 1 ... = B << 5
... 1 0 1 0 0 0 ... = A << 3
... 1 1 1 0 0 1 ... = B << 3
```
are both games with period 6. They share no term with each other at any point in their loops (unlike `... 1 1 0 ...` and `... 1 0 1 ...` which reach each other) but because they are shifted versions of each other they are considered the same game when counting.
---
Reflecting (or reversing) an infinite string gives essentially the same behavior, but does not necessarily give the same period. Consider, for example,
```
... 0 0 0 1 0 0 1 1 0 1 0 1 1 1 1 ...
```
and its reflection
```
... 1 1 1 1 0 1 0 1 1 0 0 1 0 0 0 ...
```
If we considered the next generation to be produced at a half-way point between the characters:
```
... 0 0 0 1 0 0 1 1 0 1 0 1 1 1 1 ...
... 0 0 1 1 0 1 0 1 1 1 1 0 0 0 1 ...
... 1 1 1 1 0 1 0 1 1 0 0 1 0 0 0 ...
... 0 0 0 1 1 1 1 0 1 0 1 1 0 0 1 ...
```
then both would have shifted position by 3.5 elements. However, we don't consider the next generation to be produced with that half-element offset, so one rounds up to a 4-element shift giving a period of 15, and the other rounds down to a 3-element shift giving a period of 5.
For this reason we consider an asymmetric string and its reflection to be distinct, even though the cycles are in some sense isomorphic. Of course, if they form part of the same cycle then it only counts as one cycle.
---
With these restrictions a little mathematics can show that there are in fact a finite number of Diffy cycles with any given finite period. Moreover, every infinite string with a finite period is an infinite repetition of a finite string.
Note that the strings can be larger or shorter than the periods. For example, there is a string of length 5 with period 15, and a string of length 15 with period 5. All of the strings with period 19 are of length 9709.
# Task
Given a number `n` such that n is larger than 1 via standard input methods determine the number of distinct Diffy cycles with a period of exactly `n`.
*(It seems that, in the literature, `0` is often not considered a periodic Diffy game. Since this is a gray area I will not ask you to solve for `n = 1`)*
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the goal is to minimize the number of bytes in your source code.
# Test Cases
```
2 -> 0
3 -> 1
4 -> 0
5 -> 1
6 -> 1
7 -> 3
8 -> 0
9 -> 4
10 -> 4
11 -> 3
12 -> 5
13 -> 5
14 -> 24
15 -> 77
16 -> 0
17 -> 259
18 -> 259
19 -> 27
20 -> 272
21 -> 811
22 -> 768
23 -> 91
24 -> 340
25 -> 656
```
### Hints
All Periodic diffy games will contain only zero and a single constant, this means every periodic game will be isomorphic to some diffy game consisting only of zeros and ones.
[Answer]
# [Python 2](https://docs.python.org/2/), 181 bytes
```
n=input()
m=2**n
a=[m]*m
r=lambda i:[i*-~m>>k&m-1 for k in range(n)]
def s(i):
if a[i]&m:a[i]=i;a[i]=s(min(r(i^i*2)))
return a[i]
print sum(min(r(i)[1:])>i==s(i)for i in range(m))
```
[Try it online!](https://tio.run/nexus/python2#RY1BCoMwEADvecWeJBsQqseU9SMhhRS1LHa3surVr1sUSk9zGWYOJdZ5Wz06oTYEdYWS5CDO6F3k2RfgmDjUu3TdVEndwPgxmIAVrOhr8IrZ9cMIi2eMDniEkjhXEk8Q3y8sXli9eX5waBHRgQ3rZnq5bjbWFZZNfhamJmbsmOisnkP@DwXxOJrbFw)
## How it works
The rules that transform each row of a binary diffy game into the next row are the same as the rules that transform each column into the next column. Therefore, it suffices to find all distinct cycles within the graph of all canonical length-*n* columns, where a column is “canonical” if it is lexicographically smaller than all of its rotations (this automatically excludes columns with period smaller than *n*).
With columns represented as binary numbers 0 ≤ *i* < 2*n*, the rule sends *i* to the smallest rotation of *i* XOR (*i*⋅2). (If *i* is canonical, its high bit is zero and we do not need to worry about wraparound here.)
So we loop through all possible columns *i*, check for canonicity, then repeatedly apply the rule until we find a column we’ve visited before, memoizing the first such revisited column. Exactly one column in each cycle will be its own first revisited column.
] |
[Question]
[
**Challenge**
Inspired by [this challenge](https://codegolf.stackexchange.com/questions/51284/draw-an-ascii-lightning-bolt) and the nasty [Hurricane Matthew](https://www.inverse.com/article/21803-hurricane-matthew-red-sprite-lightning-storm-photography), we will be generating some lightning bolts dynamically.
`n` = 15:
```
\
/\
/ \
/ /
/\ /\
/ \ \
/ / /\
/\ \
/ / \
/\ \ /\
/ \ \
/\ /
\
\
/\
```
**Input**
Positive Integer `n` determines the depth of the lightning round.
**Rules and Constraints**
* `/` and `\` should be used
* The probability guiding the lightning's direction is as follow:
>
>
> + 25% Splits into 2 paths
> + 25% Path reaches dead end
> + 25% Goes Left
> + 25% Goes Right
> + There are a few exceptions regarding overlapping and dead end below:
>
* The code should not be deterministic, a new lightning bolt should be generated randomly every time
* The bolts should not overlap: e.g. if there is already a bolt to the left of the current bolt, the current bolt should either end or go right, but not go left or split (probability still applies, in this case it become 50%end/50%right)
* If there does not exist another available split path, the path should not end: e.g. in the beginning when there is only 1 path, the path should not end until it splits, also applies when there are multiple paths but all except one path are dead, (probability becomes 33%split/33%left/33%right) **your goal is to reach the bottom**
* Whitespaces can be added on the left (all you would need should only be height-1)
* However you want to generate the bolt is up to you, you can go from bottom up, left to right, etc. As long as all the rules above are satisfied
**Another example**
`n` = 10
```
\
/
\
/\
/\
/ /
/\ \
/ /\
\ \
/
```
[](https://i.stack.imgur.com/4kfaS.jpg)
**Stay safe and have fun golfing!**
**Please golf responsibly only when you are in a safe area!!**
[Answer]
# Perl, ~~92~~ ~~90~~ ~~89~~ 84 bytes
Includes +1 for `-n`
Give height on STDIN:
```
perl -M5.010 bolt.pl <<< 15
```
`bolt.pl`:
```
#!/usr/bin/perl -n
map{$_=$;until$;=$_,s/.6|3.?/53|16*rand/eg,/3|6/>/36/;say y|3615|\\/ |r}(1x$_.6)x$_
```
## Explanation
If you call the offset of the starting point 0 (a point is at the corner of a character box), then on the next row you can have gone left or right (or not) and can end up with points on offsets `-1,1`. The next row gives `-2,0,2` as possible offsets etc. They all differ by 2. If you then call the character to the lower left of a point even and the character to the lower right odd you can extend that to assigning even or odd to each character position on a row such that even and odd alternate (in fact the whole plane is tiled in a checkerboard pattern). An even position can have a `/` or , an odd position can have `\` or .
The character just before a `/` is in an odd position so it could be either `\` or , but `\/` is forbidden so only is possible. Similarly the character after a `\` ***must*** be a (assuming the row is padded with enough spaces to the left and the right so the row boundaries are no issue). So a lightning bolt continues on the next row always directly below a `\` or below a `/`. In either case the lower point is in the middle and the next row can have one of , `/`, `\` or `/\` directly below the top 2 characters. So to generate the next row I can simply replace any `\` or `/` by any of these 4 expansions with equal probability (you could also independently replace the first character by or `/` and the second character by or `\`). In perl you could do this with something like:
```
s#\\ | /#(" "," \\","/ ","/\\")[rand 4]#eg
```
If the resulting row however contains `\/` (forbidden join) or no `/` or `\` at all (bolt dies and does not reach the bottom) the result is invalid. In that case I throw away the whole row and simply try again. A valid continuation always exists and if you try often enough one will be found (e.g everything dies except for 1 flow). This is a slightly different probability distribution from the suggested anti-overlap algorithm, but I think this is in fact better since it has no directional bias. Validity can be testing in a golfish way using
```
m#\\|/#>m#\\/#
```
The problem here is that the random substitution is so looooong and all these `\` escapes also eat bytes. So I decided to build my rows using strings of digits and replace the appropriate digits by , `/` and `\` just before printing. The basic random replacement is
```
53|16*rand
```
which gives one of `53`, `55`, `61` or `63` with equal probability. I then interpret `5` and `1` as , `3` as `\` and `6` as `/`. That explains the row print:
```
say y|3615|\\/ |r
```
In a serious golf competition I would now start to systematically explore alternative magic formulas, but this should be pretty good (within 3 bytes of optimal)
The rest of the components of the program:
```
1x$_.6
```
This initializes `$_` (see the next map) to height spaces followed by a `/`. This is an invisible row above the first one being printed and makes sure the field is wide enough so the bolt can never run out of space at the left
```
map{ ... ; say ...}(1x$_.6)x$_
```
I will process this same initial string height times printing a new row each time
```
$_=$;until$;=$_,...
```
Save the current row in `$;`. If the replacement turns out to be invalid restore `$_` from `$;`
```
s/.6|3.?/53|16*rand/eg
```
Do the actual substitution. I don't have to check what is before `/` or after `\` since it ***must*** be a space. This is convenient since space can be represented by either `1` or `5`. Since I only padded the string to the left the space after the `\` can still be absent, so make that character optional
```
/3|6/>/36/
```
Check if the new row is valid
[Answer]
## JavaScript (ES6), 154 bytes
```
f=(n,r=[],s=" ".repeat(n)+"/",t=s.replace(/ \/|\\ |\\$/g,_=>" / \\/\\".substr(Math.random()*8&6,2)))=>n?/^ +$|\\\//.test(t)?f(n,r,s):f(n-1,[...r,t],t):r
```
```
<input type="number" min=1 oninput=o.textContent=f(this.value).join`\n`><pre id=o>
```
I struggled with the implementation until I saw @TonHospel's answer, at which point it just degenerated into a port. Sample output:
```
/\
/ /\
/\ \
/\ \
/\ /
/ /\
/ / /\
/ /\
\ \
\
```
] |
[Question]
[
In this challenge, your task is to take an simple recording in mp3 format and find the time offsets of the beats in the file. Two example recordings are here:
<https://dl.dropboxusercontent.com/u/24197429/beats.mp3>
<https://dl.dropboxusercontent.com/u/24197429/beats2.mp3>
Here is the third recording with much more noise than the two previous:
<https://dl.dropboxusercontent.com/u/24197429/noisy-beats.mp3>
For example, the first recording is 65 seconds long and contains exactly (unless I miscounted!) 76 beats. Your job is to devise a program that takes such an mp3 file as input and outputs a sequence of the time offsets in milliseconds of the beats in the file. A beat is defined to occur, of course, when the guitarist playing plucks one or more strings.
Your solution must:
* Work on any mp3 file of similar "complexity". It can fail on to noisy recordings or to quickly played melodies -- I don't care.
* Be fairly precise. Tolerance is +/- 50 ms. So if the beat occurs at 1500 ms and your solution reports 1400, then that is unacceptable.
* Use only free software. Calling ffmpeg is allowed as is using any freely available third party software for your language of choice.
The winning criteria is ability to successfully detect beats despite noise in the supplied files. In case of a tie, the shortest solution wins (length of 3rd party code isn't added to the count).
[Answer]
# Python 2.7 492 bytes (beats.mp3 only)
This answer can identify the beats in `beats.mp3`, but will not identify all notes on `beats2.mp3` or `noisy-beats.mp3`. After the description of my code, I'll go into detail as to why.
This uses PyDub (<https://github.com/jiaaro/pydub>) to read in the MP3. All other processing is NumPy.
## Golfed Code
Takes a single command line argument with the file name. It will output each beat in ms on a separate line.
```
import sys
from math import *
from numpy import *
from pydub import AudioSegment
p=square(AudioSegment.from_mp3(sys.argv[1]).set_channels(1).get_array_of_samples())
n=len(p)
t=arange(n)/44.1
h=array([.54-.46*cos(i/477) for i in range(3001)])
p=convolve(p,h, 'same')
d=[p[i]-p[max(0,i-500)] for i in xrange(n)]
e=sort(d)
e=d>e[int(.94*n)]
i=0
while i<n:
if e[i]:
u=o=0
j=i
while u<2e3:
u=0 if e[j] else u+1
#u=(0,u+1)[e[j]]
o+=e[j]
j+=1
if o>500:
print "%g"%t[argmax(d[i:j])+i]
i=j
i+=1
```
## Ungolfed Code
```
# Import stuff
import sys
from math import *
from numpy import *
from pydub import AudioSegment
# Read in the audio file, convert from stereo to mono
song = AudioSegment.from_mp3(sys.argv[1]).set_channels(1).get_array_of_samples()
# Convert to power by squaring it
signal = square(song)
numSamples = len(signal)
# Create an array with the times stored in ms, instead of samples
times = arange(numSamples)/44.1
# Create a Hamming Window and filter the data with it. This gets rid of a lot of
# high frequency stuff.
h = array([.54-.46*cos(i/477) for i in range(3001)])
signal = convolve(signal,h, 'same') #The same flag gets rid of the time shift from this
# Differentiate the filtered signal to find where the power jumps up.
# To reduce noise from the operation, instead of using the previous sample,
# use the sample 500 samples ago.
diff = [signal[i] - signal[max(0,i-500)] for i in xrange(numSamples)]
# Identify the top 6% of the derivative values as possible beats
ecdf = sort(diff)
exceedsThresh = diff > ecdf[int(.94*numSamples)]
# Actually identify possible peaks
i = 0
while i < numSamples:
if exceedsThresh[i]:
underThresh = overThresh = 0
j=i
# Keep saving values until 2000 consecutive ones are under the threshold (~50ms)
while underThresh < 2000:
underThresh =0 if exceedsThresh[j] else underThresh+1
overThresh += exceedsThresh[j]
j += 1
# If at least 500 of those samples were over the threshold, take the maximum one
# to be the beat definition
if overThresh > 500:
print "%g"%times[argmax(diff[i:j])+i]
i=j
i+=1
```
## Why I miss notes on the other files (and why they are incredibly challenging)
My code looks at changes in signal power in order to find the notes. For `beats.mp3`, this works really well. This spectrogram shows how the power is distributed over time (x axis) and frequency (y axis). My code basically collapses the y axis down to a single line.
[](https://i.stack.imgur.com/QPOss.jpg)
Visually, it's really easy to see where the beats are. There's a yellow line that tapers off again and again. I highly encourage you to listen to `beats.mp3` while you follow along on the spectrogram to see how it works.
Next I'll go to `noisy-beats.mp3` (because that's actually easier than `beats2.mp3`.
[](https://i.stack.imgur.com/BLUlI.jpg).
Once again, see if you can follow along with recording. Most of the lines are fainter, but still there. However, in some spots, the bottom string is still ringing when the quiet notes start. That makes finding them especially hard, because now, you have to find them by changes in frequency (the y axis) rather than just amplitude.
`beats2.mp3` is incredibly challenging. Here's the spectrogram
[](https://i.stack.imgur.com/7WCbY.jpg)
In the first bit, there some lines, but some notes really bleed over the lines. To reliably identify notes, you'd have to start tracking the pitch of the notes (fundamental and harmonics) and seeing where those change. Once the first bit is working, the second bit is twice as hard as the tempo doubles!
Basically, to reliably identify all of these, I think it takes some fancy note detection code. Seems like this would be a good final project for someone in a DSP class.
] |
[Question]
[
In order to defend someone’s baffling decision, people often say that that person is going over everyone’s heads and playing “3-dimensional chess”. Now it’s your chance to play 3-dimensional chess!
## Rules
There are many variants of [3D Chess](https://en.wikipedia.org/wiki/Three-dimensional_chess), but for this challenge I’ve made up my own. My version is just like regular chess except that the pieces are inside cubes instead of squares, and now have an additional dimension of movement. To make this challenge simple there are **no pawns** and **no castling**.
## Piece Movement
*(Compass directions refer to movement that would occur on a standard chessboard, Up and Down refer to moving vertically on the 3D chess board).*
* **King** - has 26 squares it can go to on a given turn: N,NE,E,SE,S,SW,W,NW; as well as up, down, and up/down + one of the compass directions.
* **Queen** - can move in the same directions as the King, but as far as she wants in those directions.
* **Rook** - can move in 6 directions: N,E,S,W, Up, and Down,
* **Bishop** - has 8 triagonal directions of travel: NE + Up/Down, SE + Up/Down, SW + Up/Down, NW + Up/Down
* **Knight** - moves 2 spaces one axis, then 1 space on another. Just like regular chess, the knight is the only piece that can hop over other pieces.
## Piece Tester
Use this snippet to see how the different pieces move on the 3D board (***tip***: check out the `*Test` functions in the JS for quick ways to determine if a square is a valid move, simply based on its absolute distance from the piece.):
```
const color = "Black";
const pieces = ["N","B","R","Q","K"];
const urls = ["https://image.ibb.co/gyS9Cx/Black_N.png","https://image.ibb.co/dknnzc/Black_B.png","https://image.ibb.co/kb3hXx/Black_R.png","https://image.ibb.co/hGO5kH/Black_Q.png","https://image.ibb.co/jApd5H/Black_K.png"];
var dragPiece;
var size = 3;
var index = 0;
function start() {
Array.prototype.add = function(a) {return [this[0]+a[0],this[1]+a[1],this[2]+a[2]]};
document.getElementById("n").onchange=function() {
size = parseInt(this.value);
var s = document.getElementsByClassName("selected");
var pos;
if(s.length > 0) {
pos = s[0].pos;
}
document.body.removeChild(document.body.firstChild);
createBoards();
if(pos != null && valid(...pos)) {
cellAt(...pos).click();
}
};
createBoards();
}
function createBoards() {
var boards = document.createElement("div");
boards.style.counterReset = "board-count "+(size+1);
boards.name=size;
for(var x = 0;x<size;x++) {
var t = document.createElement("table");
for(var i = 0;i<size;i++) {
var row = document.createElement("tr");
row.className="row";
for(var j = 0;j<size;j++) {
var cell = document.createElement("td");
cell.className = (size+i+j)%2 == 1 ? "black" : "white";
var im = document.createElement("img");
im.draggable = true;
im.ondragstart = function(e) {dragPiece = this;e.dataTransfer.setData("piece",this.parentElement.name);
this.parentElement.classList.add("start");
this.classList.add("dragged");
};
im.ondragend = function(e) {this.parentElement.classList.remove("start");this.classList.remove("dragged");};
im.hidden = true;
cell.appendChild(im);
cell.pos = [j,i,x];
cell.ondragover = function(e) {e.preventDefault();};
cell.ondragenter = function(e) {this.classList.add("drag");};
cell.ondragleave = function(e) {this.classList.remove("drag");};
cell.ondrop = function(e) { e.preventDefault();this.classList.remove("drag");
if(this != dragPiece.parentElement && this.firstChild.hidden ){
dragPiece.hidden=true;
setPiece(this,e.dataTransfer.getData("piece"));
}
};
cell.onclick = function() {
if(this.firstChild.hidden == false && this.classList.contains("selected")) {
index++;
if(index == pieces.length) index = 0;
}
setPiece(this,pieces[index]);
};
row.appendChild(cell);
}
t.appendChild(row);
}
boards.appendChild(t);
}
document.body.insertBefore(boards,document.body.firstChild);
}
function clearHighlighted() {
var sel = document.getElementsByClassName("highlighted");
while(sel.length > 0) {
sel[0].classList.remove("highlighted");
}
}
function setPiece(cell,piece) {
var s=document.getElementsByClassName("selected");
if(s.length > 0){ s[0].firstChild.hidden=true;s[0].classList.remove("selected");}
cell.classList.add("selected");
cell.firstChild.hidden = false;
cell.name = piece;
cell.firstChild.src = urls[index];
clearHighlighted();
showMoves(cell,piece);
}
function showMoves(cell,piece) {
if(piece=="K") selector(cell,kingTest)
else if(piece=="N") selector(cell,knightTest);
else if(piece=="Q") selector(cell,queenTest);
else if(piece=="R") selector(cell,rookTest);
else if(piece=="B") selector(cell,bishopTest);
}
function cellAt(col,row,board) {
return document.body.firstChild.children[board].children[row].children[col];
}
function valid(col,row,board) {
return 0<=col && col<size && 0<=row && row<size && 0<=board && board<size;
}
function select(cell) {
if(cell != null && cell.firstChild.hidden) cell.classList.add("highlighted");
}
function rookTest(dist) {
var d = [].concat(dist).sort();
return d[0] == 0 && d[1] == 0;
}
function knightTest(dist) {
var d = [].concat(dist).sort();
return d[0] == 0 && d[1] == 1 && d[2] == 2;
}
function kingTest(dist) {
return dist[0] <= 1 && dist[1] <= 1 && dist[2] <= 1;
}
function bishopTest(dist) {
return dist[0]==dist[1] && dist[1]==dist[2];
}
function queenTest(dist) {
var d = [].concat(dist).sort();
return rookTest(dist) || bishopTest(dist) || (d[0]==0 && d[1]==d[2]) ;
}
function dist(cell,x,y,z) {
return [Math.abs(cell.pos[0]-x),Math.abs(cell.pos[1]-y),Math.abs(cell.pos[2]-z)];
}
function selector(cell,test) {
for(var i = 0;i<size;i++) {
for(var j = 0;j<size;j++) {
for(var k = 0;k<size;k++) {
if(test(dist(cell,k,j,i))) {
var c = cellAt(k,j,i);
if(c != cell) select(c);
}
}
}
}
}
```
```
table
{
padding: 10px;
display:inline-block;
}
table:after
{
counter-increment: board-count -1;
content: "("counter(board-count,upper-roman)")";
float:right;
}
td
{
width:28px;
height:28px;
border: 1px solid;
cursor: pointer;
}
.black
{
background-color: rgba(127,127,127,0.6);
}
.white
{
background-color: white;
}
.start {
background-color: rgba(0,204,0,0.6);
}
.highlighted {
background-color: rgba(0,255,0,0.6);
}
.drag
{
background-color: rgba(0,204,255,0.6);
}
.selected {
background-color: green;
cursor: grab;
}
.selected img
{
display:block;
}
.dragged {
cursor: grabbing;
}
```
```
<body data-size=3 onload="start()"
<label for="n">Size: </label><select id="n">
<option>2</option>
<option selected>3</option>
<option>4</option>
<option>5</option>
<option>6</option>
<option>7</option>
<option>8</option>
<option>9</option>
<option>10</option>
</select>
<div>Click or drag to place the piece. Click on the piece to change its type.</div>
</body>
```
## Challenge
Given an *n*x*n*x*n* board, determine if the white king is in checkmate.
## Input
* (Optional) *n* ≥ 2 - the size of the board
* The game board
+ Can be in the form of 1d- 2d- or 3d- array, or other similar format. Notation can be in any simple format. For example, KQRBN (White) and kqrbn (Black) with # for empty cubes. Or, use numbers for the different values.
+ Think of the 3D chess board as multiple boards stacked on top of each other and listed from top to bottom. Then, each individual board is notated from left to right, back to front (Black side to White side).
+ Imagine this 2x2x2 case given as a 3D array:
```
[
[[bq][##]]
[[bn][KQ]]
]
```
"top" board: [](https://i.stack.imgur.com/BQ1zb.png) "bottom" board: [](https://i.stack.imgur.com/Sxzxd.png)
## Output
* boolean (truthy/falsy value) - true if white king is in checkmate, false otherwise.
## Checkmate
The white king is in **check** if a black piece threatens to capture it on Black's next turn. To get out of check, White needs to move his king to safety, defend it with another piece, or capture the threatening piece. If White has no way to get out of check, then the white king is in **checkmate** . Remember, if White is *not* in check, but can not move without getting into check, then it is a *stalemate*, which is not a checkmate.
## Specification
* You won't be given a board where the black king is trying to "check" the white king, or a board where both kings are in check (impossible scenarios).
## Test Cases
1. n=3, `[###,n##,#rr],[#b#,###,###],[###,###,bRK]`
[](https://i.stack.imgur.com/iXc8b.png)(III) [](https://i.stack.imgur.com/CAgMk.png)(II) [](https://i.stack.imgur.com/50AlG.png)(I)
Output: **true**
Explanation: The king is receiving a check from the rook on the top floor. The white rook is unable to block the attack or capture the threatening rook, so the king must try to move out of the way. Let's consider the king's move options:
1. c2(I) - guarded by bishop at b3(II)
2. b2(I) - guarded by knight at a2(III)
3. c1(II) - guarded by rook at c1(III)
4. b1(II) - guarded by rook at b1(III)
5. c2(II) - guarded by knight at a2(III)
6. b2(II) - guarded by bishop at a1(I)
Since the king cannot escape check, it's a checkmate!
2. n=3, `[b#b,###,###],[###,###,RNR],[#q#,###,#K#]`
[](https://i.stack.imgur.com/s1Nss.png)(III) [](https://i.stack.imgur.com/DFLF7.png)(II) [](https://i.stack.imgur.com/ZLUR1.png)(I)
Output: **false** Explanation: The king is receiving a check from the queen, and has no moves to escape or block with. However, the knight can capture the queen.
3. n=3, `[#q#,#b#,###],[n##,###,###],[#k#,###,#KB]`
[](https://i.stack.imgur.com/ZY0h9.png)(III) [](https://i.stack.imgur.com/dZOm1.png)(II) [](https://i.stack.imgur.com/WRTfk.png)(I)
Output: **false** Explanation: White has no way of capturing the threatening queen or moving his king to safety. However, by moving his bishop to b2(II), White can block the queen's threat.
4. n=4, `[####,####,r###,####],[####,#q##,####,####],[##r#,###b,####,BRnn],[####,####,#N##,#KQ#]`
[](https://i.stack.imgur.com/DT3aM.png)(IV) [](https://i.stack.imgur.com/anpIs.png)(III) [](https://i.stack.imgur.com/fXA7h.png)(II) [](https://i.stack.imgur.com/W0bgu.png)(I)
Output: **true** Explanation: In this case the king is receiving a check from one of the knights and a queen. Even though White can capture/block one of the checking pieces, he can't capture/block both. Therefore, White must try to move his king out of check, but he has no options.
5. n=3, `[###,##b,r#r],[###,###,###],[#k#,###,#K#]`
[](https://i.stack.imgur.com/w1ov7.png)(III) [](https://i.stack.imgur.com/X03lV.png)(II) [](https://i.stack.imgur.com/43UPR.png)(I)
Output: **false** Explanation: White is not in check, but has no way of moving without getting into check. Therefore, it is a stalemate, but not a checkmate.
6. n=3, `[##k,###,r#K],[###,n##,#N#],[###,###,#Q#]`
[](https://i.stack.imgur.com/6oJf1.png)(III) [](https://i.stack.imgur.com/qW7EO.png)(II) [](https://i.stack.imgur.com/ch6LQ.png)(I)
Output: **true** Explanation: White would like to swoop in with his queen to defend his king, but his knight is blocking the path.
7. n=3, `[###,###,##q],[###,###,###],[#k#,###,rNK]`
[](https://i.stack.imgur.com/fbLY1.png)(III) [](https://i.stack.imgur.com/X03lV.png)(II) [](https://i.stack.imgur.com/7rSPp.png)(I)
Output: **true** Explanation: White can not take the queen with his knight, because then the rook will be checking White's king.
8. n=2, `[#q,##],[##,K#]`
[](https://i.stack.imgur.com/6rzKV.png)(II) [](https://i.stack.imgur.com/tf3zh.png)(I)
Output: **false** Explanation: White can capture the queen with his king.
9. n=2, `[rq,##],[##,K#]`
[](https://i.stack.imgur.com/hXQiR.png)(II) [](https://i.stack.imgur.com/tf3zh.png)(I)
Output: **true** Explanation: This time the rook is guarding, so the king can't capture the queen.
10. n=3, `[###,###,#q#],[###,###,###],[#k#,###,BKn]`
[](https://i.stack.imgur.com/BzSpz.png)(III) [](https://i.stack.imgur.com/X03lV.png)(II) [](https://i.stack.imgur.com/DOjAL.png)(I)
Output: **false** Explanation: The white king can escape by capturing the knight.
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~412~~ 413 bytes
```
->b,w=2{n=b=~/\n/
g=->h{h[0]-~n*(h[1]-~n*h[2])}
r=1
(n**6).times{|i|a=b*1
m=[]
9.times{|j|m<<(j<6?i/n**j%n:m[j-6]-m[j-3])}
x,y,z=v=m[6,3].map{|j|j*j}
d=v.max
e=x+y+z
q=95&o=(t=a[p=g[m[3,3]]]).ord
k=a[s=g[m]].ord
o/32==w&&(o^k>31||k==75)&&((q%8==2&&q%9*d==e||q==81&&x%d+y%d+z%d<1)&&((1...c=d**0.5).map{|j|a[p+g[m[6,3]]/c*j]}+[?#]).max<?A||q==78&&e==5||q==75&&e<4)&&(a[p]=?0;a[s]=t;r&&=w>2?a=~/K/:!f[a,3])}
r}
```
[Try it online!](https://tio.run/##fVBhb9owEP3uX8FqYYVAEgKDQpsDla@RkMZXz5NwA4WgGOKyEiD0rzPbAQrr1khn373zu/dy8jffHqdwdHq8toHGXgCHd@@n8NALOL3ZfkbrzHkXtjWjvklmtMEqhxKS4CNL2Ha74q7nyeR1n8/zMXDbL@kPJUAZ6p5bcZ4EgRUH7f7cU5y4LB4SGjtt5uirqQairLat7eANEtquNZmbjFeaFtvxAUXwpuoMTSCrbqs7lEK3RZZgrWFMV/BCE9pUFMYq7lJGaKHQV40yZuql12wAbAixlr8Wvaaf5wuA@1ZFAVZa7gA0CEnLXTsCmOR5CtDxCcnKUXWrYleOAt889V3XfYbItutuq3K2p/SrWl9bZt6zHbNDlfYx0w@yoP9k5t13CJkAtIqipYrgux6pyAz69Udll8H6URICm16jP1b7D72Hb1M6rpnNyMNxVZrSO4wxEiqwlMhxHIS5ynERpj7lfBSiO4aQIXHM//loNBwVdXoaEuIPkgH5B0ngv5QWZ9LAkNDZn4ExkpfMOWliLXTCrhvSlLzABiMhrhnmGBqdH9fuTI8rFXnzS5/d3ZAWqLAWXkiimH875LOSjvRLJTkMr5eHTFuf1w7kf/DL0BR/KTIIRbHs4x8 "Ruby – Try It Online") Now checked on all test cases. Code increased by 1 byte to fix a bug on case 5 (stalemate case.)
Llambda function requiring input as a string in the format shown below. An optional second parameter can be given, indicating which group of 32 ASCII codes are to be considered on the next move (by default this 2 corresponding to uppercase/white characters, but the function calls itself recursively using 3 corresponding to lowercase/black characters.)
Recursion level 1: Tries all possible moves for white (any cube to any cube) and steps through all the legal ones. Recursion level 2: In each case it then calls itself to step through all possible moves for black. This returns true if the white king has survived all possible black moves. Recursion level 1: If all possible white moves lead to a situation where the white king does NOT survive all possible black moves, then return true (otherwise false.)
In general, a piece cannot move to a square occupied by a friendly piece. In order to consider the case where white does not move at all (hence checkmate not stalemate), the case where the king "moves" to the square he is already on is also allowed. For reasons of short code, the other white pieces are also allowed to move to the square occupied by the white king. This is a nonsense move, but allowing it does not affect the result so it is not a problem.
**The following tests are used to check if a move is valid for each piece.**
`x,y,z` are the squares of the distances travelled in each axis. `e` is the sum of these (hence the square of the euclidean distance) and `d` is the maximum. The piece type is ANDed with 95 to convert lowercase ASCII values to uppercase ones.
```
Bishop and Rook (ASCII 66 and 82) For the rook e=1*d. For the bishop e=3*d.
The same code is used for both with q%9 giving 1 and 3 respectively.
Queen (ASCII 81) x%d+y%d+z%d<1 Each axis must be 0 or d, so this sum must be 0.
For the above pieces, any cubes crossed must be checked to ensure they are empty.
Knight (ASCII 78) e=5
King (ASCII 75) e<4
```
**Commented code**
```
->b,w=2{ #board, colour to move (default upcase/white)
n=b=~/\n/ #n=board size (index of first newline.)
g=->h{h[0]-~n*(h[1]-~n*h[2])} #Function to calculate position in string based on array of 3d coordinates.
r=1 #Return value = truthy.
(n**6).times{|i| #Iterate through n**6 moves (n**3 start cubes and n**3 end cubes.)
a=b*1
m=[] #Make an empty array for coordinates.
9.times{|j|m<<(j<6?i/n**j%n:m[j-6]-m[j-3])} #Split i into six base n digits for the start and end coordinates. also derive 3 relative move distances.
x,y,z=v=m[6,3].map{|j|j*j} #v=array of relative distances squared. x,y,z are the 3 individual relative distances squared.
d=v.max #Max of x,y,z
e=x+y+z #Square of euclidean distance
q=95&o=(t=a[p=g[m[3,3]]]).ord #t=contents of cube to move from. o=ascii value, q=uppercase of o.
k=a[s=g[m]].ord #k=ascii value of contents of cube to move to.
o/32==w&&(o^k>31||k==75)&& #If o is in the right 32 byte range (uppercase or lowercase) AND the destination contains the white king or a character not in the same 32 byte range AND...
((q%8==2&&q%9*d==e||q==81&&x%d+y%d+z%d<1)&& #the piece is a rook, bishop or queen with a valid move (as described in the text) AND..
((1...c=d**0.5).map{|j|a[p+g[m[6,3]]/c*j]}+[?#]).max<?A|| #the intervening squares are all empty, OR..
q==78&&e==5|| #the piece is a knight and the move has euclidean distance sqrt(5) OR..
q==75&&e<4)&& #the piece is a king and the move has euclidean distance <4 THEN
(a[p]=?0;a[s]=t;r&&=w>2?a=~/K/:!f[a,3]) #put a 0 in the start cube and put the piece in the end cube. If moved piece is black, is the white king still there? AND with return value.
} #If moved piece is white, recursively call the f to carry out the black moves. Does the white king NOT survive some black moves? AND with return value.
r}
```
] |
[Question]
[
I was recently adding up the ages of myself and my wife and kids and realised that at some point in the not-too-distant future our ages will all add up to exactly 100 years.
# Challenge
For an input consisting of a combined (total) age and a list of birth dates, output the date on which the combined ages all add up to the given total.
1. Input combined age (in years) will be a positive integer
2. Input list of birth dates will be a list (whatever format is convenient for your language) of dates that must contain numerical representation of Day, Month and Year. Number of days since a specific epoch is not acceptable. You may assume the list of input dates is sorted in chronological order.
3. Output will be a single date in the same format as input dates
4. For the purposes of the combined age, 1 year is considered to be exactly 365.25 days
5. For some inputs, it will be impossible to find a date after all the birth dates when they all add up to the combined age. For instance consider two birth dates that are 20 years apart, but we want a combined of 10 years. In that case, the output would be the 10th birthday of the older birth date. In other words, individual ages are considered to be 0 for all dates before that individual's birth date
6. The output will be the first date on which the combined ages add up to *at least* the input age
7. You may use built-in [date-time](/questions/tagged/date-time "show questions tagged 'date-time'") functions
8. You must support dates going back as far as 1970/01/01.
### Examples
Here I'm giving all dates in YYYY/MM/DD format, but you may whatever format you like.
```
Input Output
10 2000/01/01 2010/01/01
100 1975/03/05,1978/07/23,2008/11/12,2012/12/20 2018/11/22
100 1975/03/06,1978/07/23,2008/11/12,2012/12/20 2018/11/23
100 1975/03/09,1978/07/23,2008/11/12,2012/12/20 2018/11/23
100 1975/03/10,1978/07/23,2008/11/12,2012/12/20 2018/11/24
3 1990/08/01,1995/07/02 1993/08/01
50 1975/03/05,1978/07/23,2008/11/12,2012/12/20 2001/11/13
```
Note that in the last two examples, the output date lies within the range of input dates, as per rule 5.
[Answer]
# Mathematica ~~138 107~~ 237 bytes
My first attempts were sloppy and unworthy. This should work generally, provided that the birth dates are given in order of earliest to latest, as in the test cases.
The test cases were well-chosen and difficult to implement correctly.
The code turned out way longer than I had hoped.
The general logic is to
1. Solve for x (in days) such that the distance from x to each date of birth sums to the target passage of time (e.g 100 years converted to days).
2. If the earliest date + x days > latest date of birth, remove the latest date of birth and repeat step (1), Else move to (3).
3. Return (earliest date + x days)
---
```
t_~f~d_:=If[DateDifference[a=DateObject[DatePlus[d[[1]],Solve[t 365.25==Tr@(x-Join[{0},
QuantityMagnitude@(DateDifference[d[[1]],#,"Day"]&/@Rest@d)]),{x}][[1,1,2]]]/.
{y_,m_,n_,h_}:>{y,m,n+1}],d[[-1]]]>Quantity[0,"Days"],f[t,Most@d],a]
```
---
# Test Cases
```
f[10, {{2000, 1, 1}}]
f[100, {{1975, 3, 5}, {1978, 7, 23}, {2008, 11, 12}, {2012, 12, 20}}]
f[100, {{1975, 3, 6}, {1978, 7, 23}, {2008, 11, 12}, {2012, 12, 20}}]
f[100, {{1975, 3, 9}, {1978, 7, 23}, {2008, 11, 12}, {2012, 12, 20}}]
f[100, {{1975, 3, 10}, {1978, 7, 23}, {2008, 11, 12}, {2012, 12, 20}}]
f[3, {{1990, 8, 1}, {1995, 7, 2}}]
f[50, {{1975, 3, 5}, {1978, 7, 23}, {2008, 11, 12}, {2012, 12, 20}}]
```
---
[](https://i.stack.imgur.com/mX9ji.png)
[Answer]
## PowerShell, ~~145~~ 125 Bytes
```
param($a,$b)$c=@();$b|%{$c+=date $_};$t=$a*365.25;$d=$c[0];while($t-gt0){$c|%{if($_-le$d){$t--}};$d=$d.AddDays(1)}"{0:d}"-f$d
```
Pretty tricksy challenge, but relatively straightforward once understood.
### Expanded and Commented:
```
param($a,$b) # Take our input
$c=@() # Make a new array $c
$b|%{$c+=date $_} # Change our input array $b of strings into dates, store in $c
$t=$a*365.25 # Target number of days we need to account for
$d=$c[0] # Our starting date, also our cumulative date for output
while($t-gt0){ # While we still have days remaining
$c|%{ # Iterate through our birthdays
if($_-le$d){$t--} # If the birthday is less than our cumulutive day, subtract a day
}
$d=$d.AddDays(1) # We've accounted for another day, so increment our cumulative day
}
"{0:d}"-f$d # Format output
```
## Example:
Input needs to contain an explicitly formatted array of string-date representations. Output is in `MM/DD/YYYY` format (default for en-us localization in PowerShell).
```
PS C:\Tools\Scripts\golfing> .\combined-100-year-birthday.ps1 50 @('03/05/1975','07/23/1978','11/12/2008','12/20/2012')
11/13/2001
```
Edit -- Golfed 20 bytes by changing how we iterate through birthdays, and by using while instead of do/until
[Answer]
## PHP, 220 bytes
I've added some newlines for readability.
```
function c($y,$s){for($d=$y*365.25;++$i<count($l=array_map(date_create,$s));)$d+=
$l[0]->diff($l[$i])->days;($l[$i-1]>$r=$l[0]->add(new DateInterval(P.ceil($d/$i).D)
))?c($y,array_slice($s,0,-1)):print$r->format('Y/m/d');}
```
`[Ideone](http://ideone.com/yEsNSL)`
Here is the ungolfed version:
```
function printCombinedBirthday($combinedAgeInYears, $listOfBirthDatesStrings)
{
$combinedAgeInDays = $combinedAgeInYears * 365.25;
$listOfBirthDates = array_map('date_create', $listOfBirthDatesStrings);
$numberOfBirthDates = count($listOfBirthDates);
for ($i = 0; $i < $numberOfBirthDates; ++$i) {
$combinedAgeInDays += $listOfBirthDates[0]->diff($listOfBirthDates[$i])->days;
}
$combinedAgeInDays = ceil($combinedAgeInDays / $numberOfBirthDates);
$interval = new DateInterval('P'. $combinedAgeInDays .'D');
$result = $listOfBirthDates[0]->add($interval);
if ($listOfBirthDates[$numberOfBirthDates - 1] > $result)
{
printCombinedBirthday(
$combinedAgeInYears,
array_slice($listOfBirthDatesStrings, 0, -1)
);
}
else {
echo $result->format('Y/m/d');
}
}
```
] |
[Question]
[
**Closed**. This question needs to be more [focused](/help/closed-questions). It is not currently accepting answers.
Closed 9 years ago.
**Locked**. This question and its answers are [locked](/help/locked-posts) because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
**The Task**
Create a function/subroutine which returns 1. You can make it as elaborate as you like, as long as it returns 1.
**The Rules**
The entry with the most upvote wins - just like any popularity contest. Good luck!
[Answer]
**Golf Script**
```
1
```
It took a long time to optimise this code to its most pure, and dare I say it - beautiful form. Such elegance of the language does not come without years of dedicated practice. The program that, without a Zero-Instruction-Set-Computer can literally never be compressed any further. My entire code golf career has been leading to this moment.
I am free. I am alive.
I see the code that underlies the universe.
[Answer]
## C
Two examples, using obscure language features such as “strong return” (`return!`) and the “approaches” operator (`-->`):
```
int foo(void) {
return! 0;
}
```
```
int bar(void) {
int i=7;
while (i --> 0);
return-i;
}
```
[Answer]
# Brainfuck
```
+++++++
+++++++
+++
+++
+++
+++
+++
++++++++++
++++++++++.
```
Or if you are not fun at parties:
```
+++++++[->+++++++<]>.
```
[Answer]
## APL
```
one ← {⍴⍴⍴⍵}
```
`⍴` gives you the dimensions of a vector. The dimension of that is always one-dimensional, so the dimension of *that* is always one. Or:
"Rho, rho, rho of X
Always equals one,
Rho is dimension; rho rho, rank
APL is fun!"
(I didn't write that verse, it's Stallman's.)
[Answer]
## Java
```
public static int funWithOne() {
try {
try {
return funWithOne();
} finally {
return funWithOne();
}
} catch (Throwable _) {
return 1;
}
}
```
This will call itself 21024 times (this number may vary on different platforms) before finally returning `1`. Don't hold your breath, though; it will easily take *much* longer than the age of the universe.
[Answer]
## Unix Shell (Bourne, POSIX, bash, ksh, csh, …)
```
expr 0
```
This *prints* 0 but *returns* 1, which may come as a surprise to programmers used to other languages. You can turn off the printed output and see the return code by running `expr 0 >/dev/null; echo $?`.
[Answer]
**Fish**
x sends the program counter in a random direction. # is a wall that the program counter "bounces" off. This will literally wander around aimlessly until it finds the "^" and then print 1 and finish.
```
xxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxx###xxxxxxxxxxxxxx
xxxxxxxxxx#;#xxxxxxxxxxxxxx
xxxxxxxxxx#n#xxxxxxxxxxxxxx
xxxxxxxxxx#1#xxxxxxxxxxxxxx
xxxxxxxxxx#^#xxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxx
```
[Answer]
# Java
This is one of my favorite Java specific question.
```
public static int ret1() {
try {
return 0;
} finally {
return 1;
}
}
```
[Answer]
## JavaScript
```
function getOne() {
return -~![];
}
```
Explanation:
* first `![]` evaluates to `false`.
* then `~false` becomes `-1` because `false` is first casted to `0`, and `~0 == -1`.
* finally, `--1` evaluates to `1`.
Alternate:
```
return +!([][~~{}])
```
Crazy alternate (each line is exactly 80 chars long):
```
this[693741..toString(36)]('acnuftiao nobcbdaterbaurn +abeba!!be'.replace(/b./g,
function(b){return '{}()'.split('')['aecd'.split('').indexOf(b.charAt(1))]})[''+
'replace'](new RegExp('a'+Array(5).join('(.)'),'g'),(a='$')+'4321'.split([]+[]).
join(a)))
```
[Answer]
## JavaScript
```
// we all know that OOP == good
function OneManager() {
// constants == good too
this.values = {
ERROR: -1, // value on error
ONE: 1 // desired value
}
this.value = this.values.ERROR // set the value to ERROR
this.setValue = function(num) {
if (typeof num !== "number") throw new Error('cannot set value to non-number')
if (!this.value) this.value = this.values.ERROR // oh noes
else this.value = num
}
}
// initialize the one
OneManager.prototype.initializeOne = function() {
this.setValue(this.values.ONE) // set the value to ONE
return true // return true for success
}
// get the value
OneManager.prototype.getValue = function() {
if (this.value == this.values.ERROR) { // if the value is ERROR
throw new Error('value not initialized')
} else return this.value // return the value
}
function getOne() {
var m = new OneManager() // make a OneManager
var success = m.initializeOne() // initialize the value
if (success) return m.getValue() // return the value
else {
// there was an error in the initialization
var retVal = m.values.ERROR // we will return an error
delete m // maybe it's corrupted
return retVal // return an error
}
}
alert(getOne())
```
[Answer]
## Haskell & The Church of the ADT
```
data One = One deriving (Eq, Ord, Bounded, Enum, Show, Read)
```
This defines the **one** true `One`. This `One` is both the type denoting *Oneness*, and the constructor `One`, which is itself the nullary function that returns the **one** true, and only one value of type `One`, which is, behold, `One`.
Usage in the `ghci` REPL:
```
λ: One -- One returns the one true One
One
λ: One == One -- One is equal to itself, as no others are
True
λ: One < One -- One is no less than itself
False
λ: minBound :: One -- One is the least One there is, yet it is all you need
One
λ: maxBound :: One -- One is as big as the universe of One, it is omnipotent
One
λ: [ One .. One ] -- One is the beginning, and ending, of all that is One
[One]
λ: show One -- The textual gospel of One
"One"
λ: read "One" :: One -- To read the word of One, is to become one with One
One
```
The full [Book of One](https://bitbucket.org/mtnviewmark/haskell-playground/src/789e66e13736f5f5ad6ca09cceef7d20d4c7beca/golf/12141-One.hs?at=default) is now on-line. Loading it gets you both testaments: Computation and Arithmetic. This enables you to explore more truths:
```
λ: One + One -- One can only add to its magnificence
One
λ: negate One
*** Exception: One cannot be negated, mortal fool!
λ: One `div` One -- One is indivisible
One
λ: One `mod` One
*** Exception: Nothing can modulate the power of One
λ: toRational One -- Ye shall know One as both Numerator and Denominator
1 % 1
λ: toInteger One * 42 -- One multiplies all to wholeness
42
λ: toRational One / 2 -- Even divided, One is on top
1 % 2
```
[Answer]
## Perl
```
sub ret1 { print $->$= }
```
(Despite appearances, the function doesn't print anything.)
I know Perl programmers like to say TMTOWTDI, but this is a task for which T *really* MTOWTDI.
[Answer]
# Groovy
```
-"""
int getRandomNumber()
{
return 4; //chosen by fair dice roll.
//guaranteed to be random.
}
""".indexOf(4)
```
Doesn't contain 4
[Answer]
# PHP
```
<?php
function getOne() {
return 0 + "one" == 0;
}
```
**Edit:**
If you prefer a longer one, here's an alternative (it doesn't print anything):
```
<?php
function getOne() {
return print('the' + 'integer' + 'between' + 0 and 2);
}
```
[Answer]
## C
```
float one(void)
{
const int n = 24; // magic number
float x = 0.5f;
float y = x;
int i;
for (i = 0; i < n; ++i)
{
x *= 0.5f;
y += x;
}
return y;
}
```
[Answer]
# Rhetorical Java
You didn't say it had to be an integer 1.
```
float one_F(){
return FloatFactoryFactory.getInstance(FloatFactoryFactory.
defaultInstanceDescriptionString).getFactory(Locale.getLocale
("en-US")).createBuilder().setString("1.0").getResult();
}
```
Source: <http://bash.org/?946461>
[Answer]
## JavaScript (ECMAScript really)
```
function one() { return Number.length; }
```
Time for some spec porn.
Section [15.7.3](http://www.ecma-international.org/ecma-262/5.1/#sec-15.7.3) states that the `length` property of the `Number` constructor is `1` (and we know that a constructor is a function object as mentioned in [4.3.4](http://www.ecma-international.org/ecma-262/5.1/#sec-4.3.4)), and that's because section [15.3.5.1](http://www.ecma-international.org/ecma-262/5.1/#sec-15.3.5.1) says:
>
> The value of the length property is an integer that indicates the “typical” number of arguments expected by the function. However, the language permits the function to be invoked with some other number of arguments.
>
>
>
…and since the `Number` constructor's typical number of arguments is 1, the `length` of `Number` is `1`. So one could say that the length of a number in Javascript is 1.
[Answer]
## Perl
```
sub one{ $a[@a{@a[%a=map{@$a[@a{$a++=>$a}]+++$#$a+$a=>$a}$a]++}+$a] }
```
Open wide and say `aaaaa`.
The creative concept was to nest braces inside brackets inside braces... as deeply as possible, while still returning the desired result, and only using a "one" variable (`$a`, `@a`, `%a`, `@$a` and `$#$a` are of course all different variables).
Although this does modify its environment significantly, it will always return `1` on subsequent calls. To get a grasp of what it's doing, you might consider running this code:
```
use Data::Dump qw(dump);
for (1..8) {
one();
dump(@a);
dump(%a);
dump(@$a);
}
```
[Answer]
## Tcl
```
proc return1 {} {
catch {(5+2-3)/4}
}
```
Does not work as you might think.
`(5+2-3)/4` is not a valid command, so it throws an error (`return -code 1`), catch returns this number.
[Answer]
## MATHEMATICA
In my opinion, the most elegant mathematical way to return 1 using Mathematica:
```
-Exp[I Pi]
```
The Euler Identity.
[Answer]
## Java
```
public class print {
public static char getNum() throws Exception{
String method = print.class.getSimpleName()+Splitter.class.getDeclaredMethods().length;
return (char)Splitter.class.getMethod(method).invoke(null);
}
}
class Splitter{
public static char print1(){
return P.getNum();
}
}
class P{
public static char getNum(){
String s = Thread.currentThread().getStackTrace()[P.class.getDeclaredMethods().length].getMethodName();
return s.charAt(s.length()-P.class.getSimpleName().length());
}
public void doNothing(){}
}
```
Can be adjusted to return any other positive number `n` by adding the methods `printX` for `X` from 1 to n into Splitter. For example, modifying `Splitter` to
```
class Splitter{
public static char print1(){
return P.getNum();
}
public static char print2(){
return P.getNum();
}
}
```
Will return '2', without any other changes necessary. The added methods should, apart from the name, be an exact duplicate of `print1`.
Uses reflection to get the number of methods in splitter, and call a function with that name. `P.getNum`, which is then called, reads the stack trace and parses out the last character in the calling method, and displays it.
Calling `print.getNum()` return the character '1'
Edit - modified to use no String/integer/etc literals.
[Answer]
**C#**
It should depend on hardware architecture:
```
return IntPtr.Size / (Environment.Is64BitOperatingSystem ? 8 : 4);
```
WOW!
[Answer]
## C#
Merging this (controversial) one with the neighboring (controversial) [Collatz Conjecture](https://codegolf.stackexchange.com/questions/12177/collatz-conjecture):
```
public int CollatzOne()
{
var current = new BigInteger(new Random().Next(1, Int32.MaxValue));
var history = new[] { new BigInteger(-1), new BigInteger(-1), new BigInteger(-1) };
do
{
history[0] = history[1];
history[1] = history[2];
history[2] = current;
if (current.IsEven)
current /= 2;
else
current = current * 3 + 1;
} while (current != history[0]);
return (int)history.Min();
}
```
[Answer]
# Ruby
Abusing the RNG...
```
Random.new(56417).rand(10000)
```
Generates a "random" number between 0 and 10000, and because I picked the right seed it just so happens to be 1. ;)
Script I used to find the number:
```
irb(main):001:0> (1..100000).select{|x|Random.new(x).rand(10000) == 1}
=> [14033, 25845, 35101, 36955, 45334, 56417, 87438, 87460, 99178, 99451]
```
[Answer]
### Javascript 8 bytes
is this simple enough?
```
(+!~~{})
```
[Answer]
# R
A classic:
```
TRUE + 0
```
`+` tries to coerce its argument to a common type: here, because of the order of precedence, it coerces to integers. The coercion of `TRUE` to an integer gives 1.
[Answer]
## Turing Machine
Single-state Turing machine with B as the blank symbol, computes 1 (= 0.111... in base 2):
```
q B 1 R q
```
(This follows Turing's convention of starting with a blank tape, and prefixing '0.' to the generated infinite sequence.)
[Answer]
# C
It even includes documentation on its parameters.
```
int
return_1
(x) int
x;{
/*x
can
be:
any
val
ue.
***/ return
!x?1:x /x;}
```
[Answer]
## Python
```
one = lambda zero = 0o11: zero > 1 and all(one(zero-1) for l in '1111111111') and 1 or one and zero or one()
```
`one()` will call itself 111,111,111 times, each time returning 1, before returning a final value of 1.
You can also specify the number of digits. For example, `one(3)` will return 1 only 111 times.
I might add an explanation later, but I really don't have time at the moment.
[Answer]
## R
```
NA ^ 0
```
Any number to the power of `0` is `1`.
] |
[Question]
[
# Introduction
A pure word (or perfect word), as defined by me, is a word where the sum of the position in the alphabet of each letter in the word is perfectly divisible by the total length of the word. For example, `abcb` is a perfect word because `1 + 2 + 3 + 2 = 8`, and `8 / 4 = 2`.
# Your task
Given a word as input, output whether or not it is a perfect word. The word may always be assumed to be lowercase.
## Scoring
This is code-golf, so shortest program in bytes wins.
## Examples
```
abcb: truthy
ccc: truthy
aaa: truthy
pure: truthy
word: truthy
bed: falsy
code: falsy
bode: falsy
```
[Answer]
# [Factor](https://factorcode.org/), ~~37~~ 16 bytes
```
[ mean fixnum? ]
```
[Try it online!](https://tio.run/##HYoxDgIhEEV7TjHhAFtaaGFpbGyMlbEYZmeVCAOB2cT18gg27@W//AVJU2m36/ly2kNEfU1VUX1VTxXeXITDP0MurLrl4kXhycIFg//2Z5IKB2MsOnLWWCLqRMROx/MoaeYxhtodIqPA4j@yxiM82g4Ecw4bTBUoMJb2Aw "Factor – Try It Online")
Is the mean of the input an integer?
#### Why does this work?
Four reasons.
* Strings in Factor are just sequences of code points.
* Because the question is asking for a sum divided by a length. Otherwise known as the mean.
* The `mean` word returns a ratio, not a float. In Factor, ratios automatically reduce to simplified form, which can be an integer. We can check for divisibility after taking the mean by checking whether the result is an integer or a ratio.
* It doesn't matter whether the input ranges from 1-26 or 97-122. It doesn't change whether the mean is an integer or not.
[Answer]
# [Python 3](https://docs.python.org/3), 33 bytes
```
lambda s:sum(map(ord,s))%len(s)<1
```
[Try it online!](https://tio.run/##Hcg7CsMwEEXR3qt4TdAMuAnpTLySkGL0IwJrJCSnyOoV5Opwb/2dn6KPMeJ@SLZe0Lf@zZSlUml@7cy3Iyh1ft6HYsfLiHXWrDDOuYmITGzw1yw@XDl9L7E0JCSFbgtQW9KTIiXm8Qc)
[Answer]
# [R](https://www.r-project.org/), ~~42~~ ~~39~~ 33 bytes
```
function(w)!mean(utf8ToInt(w))%%1
```
[Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/T6NcUzE3NTFPo7QkzSIk3zOvBCiiqapq@D9NQykxKTlJSZNTWSGEC8hLTk5GcBITExGcpNQUMMcNrCw/JRXBS4Lz/gMA "R – Try It Online")
-6 bytes thanks to m90.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes
```
OIgÖ
```
[Try it online!](https://tio.run/##yy9OTMpM/f/f3zP98LT//6MtzXUULC2A2BJExwIA "05AB1E – Try It Online") Takes input as a list of codepoints.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jellylanguage), 5 bytes
```
OSḍ@L
```
[Try It Online!](https://jht.hyper-neutrino.xyz/tio#WyIiLCJPU+G4jUBMIiwiw4figqwiLCIiLFsiW1wiYWJjYlwiLCBcImNjY1wiLCBcImFhYVwiLCBcImJlZFwiLCBcImNvZGVcIiwgXCJib2RlXCJdIl1d)
```
OSḍ@L Main Link
O ord (vectorizes)
S sum
ḍ@ is this divisible by
L the length of the input?
```
If outputting inconsistent truthy/falsy values is allowed:
# [Jelly](https://github.com/DennisMitchell/jellylanguage), 4 bytes
```
OSọL
```
[Try It Online!](https://jht.hyper-neutrino.xyz/tio#WyIiLCJPU+G7jUwiLCLDh+KCrCIsIiIsWyJbXCJhYmNiXCIsIFwiY2NjXCIsIFwiYWFhXCIsIFwiYmVkXCIsIFwiY29kZVwiLCBcImJvZGVcIl0iXV0=)
```
OSọL Main Link
O ord (vectorizes)
S sum
ọ how many times is this divisible by
L the length?
```
This works using an observation made by [caird coinheringaahing](https://chat.stackexchange.com/transcript/message/60084609) in chat that you do not need to account for the offset between A = 1 and A = 65 when you take the codepoint, since the codepoint offset will be added `len(X)` times and not affect the modulo.
Yes, caird also just straight up gave the algorithm, but to be fair, the observation was the only non-trivial part about this solution anyway.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 5 bytes
```
C∑$LḊ
```
[Try It Online!](https://vyxapedia.hyper-neutrino.xyz/tio#WyIiLCJD4oiRJEzhuIoiLCIiLCIiLCJhYmNiIl0=)
Same thing as my Jelly solution.
```
C∑$LḊ Full Program
C ord (vectorizes)
∑ sum
$ swap; bring the string back to the top
L length
Ḋ is the ord sum divisible by the length?
```
[Answer]
# JavaScript (ES6), 58 bytes
```
w=>!([...w].reduce((s,c)=>s+parseInt(c,36)-10,0)%w.length)
```
[Answer]
# [Haskell](https://www.haskell.org/), 36 bytes
```
f w=sum(fromEnum<$>w)`mod`length w<1
```
[Try it online!](https://tio.run/##TYs9D8IgFAB3fsUbHNqkHdxpN50c3YyxD3i0RD4M0PDzsV2q211yt2B6k7W1aihDWl2jY3AXvzp@Gks7uaAmS37OCxR@rg6NH1Rg8DDdqwtP3pcQVdramfLNeGLwicbnxnQaTMtgHyoKKaAf4R5XYlLKgxHxYEFq5yvatEVB0c/Ev30B "Haskell – Try It Online")
[Answer]
# [Python](https://www.python.org), 24 bytes
```
lambda s:sum(s)%len(s)<1
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY7chJzk1ISFYqtiktzNYo1VXNS84CUjSFE-mZGQVFmXolGmkaSUmJScpKSpiYXQiQ5ORlVIDExEVUgKTUFTUt-SiqaEogIxL4FCyA0AA)
Takes input as a byte string. We don't need to subtract `95` from each element, because the sum will end up having `95 * length` added on, which has no effect on the result modulo `length`.
[Answer]
# Java, 31 bytes
```
s->s.chars().sum()%s.length()<1
```
[Try it online!](https://tio.run/##hdG9agMxDADgOfcUJhCwCzF0zs8bFAoZSwZZ9l188dmHJSeUkme/OrRday1C0ic0aIQbbEd7Xfw0p8xirLUu7IPuS0T2KeqXXTcXEzwKDEAk3sBH8dWJGr99YuCabslbMdWpPHH2cfg4C8gDqYpX79lZj8Bu/zM7iv6w0PZIGi@QSSpNZZJqQzq4OPBFqv3rsutWp09iN@lUWM91j0OUvWZHLNdg0KyV@h8hYtMAQNPMJbsmuqdsm8i4tsFk29fMH3p@4tE9lm8)
[Answer]
# [Vyxal 2.4.1](https://github.com/Vyxal/Vyxal) `K`, ~~4~~ 3 bytes
```
ṁ1Ḋ
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=K&code=%E1%B9%811%E1%B8%8A&inputs=pure&header=&footer=)
Ah yes classic pre-2.6 jank ftw. *-1 thanks to Dominic*
## Explained
```
ṁ1Ḋ
# First, the input is converted to a list of corresponding ordinal values by the `K`(eg mode) flag:
ṁ # push the arithmetic mean of that list
1Ḋ # is that divisible by 1? (i.e is it a whole number)
```
[Answer]
# [brainfuck](https://esolangs.org/wiki/Brainfuck), 162 bytes
```
>+[+[>+<+<]>]+[,[>[>+<<->-]<[>>>+<<<-]>>>>+<<[<+>-]<<+>>]<<]>>>[-]>>[<+>-]<[->+>-[>+>>]>[+[-<+>]>+>>]<<<<<<]>[-]+++++++>[-]<[>+++++++<-]>>[<.[-]>[-]>[-]]<[-.[-]]
```
[Try It Online!](https://tio.run/##LYxdCgMxCITfexVrTyBzEfFhf1pYFtolEPb41iERojOj@da2HN9P385MiItDTCwQ4k8HnSk0zAFq08BQbsK8Oqozde5m7Iqa9b22KKpWHBi3rOC1jKIs/nQ2KC/S5iOOPh6ZV2/v@9f2Pw)
outputs `0` for **truthy** and `1` for **falsey**
This one was a lot of fun. Not necessary golf-optimal but hey, brainfuck solution :)
## Explanation
```
; 96 algorithm from esolangs constants
; initialise tape to (1)/96/0/0/0
>+[+[>+<+<]>]+[
; while(getchar())
,[>
[>+<<->-]
<[>>>+<<<-]>>>>+<<[<+>-]<<+>>
; 0/96/(0)/cumulative/length
]
<<
]
; divmod algorithm from esolangs
>>>[-]>>[<+>-]
<[->+>-[>+>>]>[+[-<+>]>+>>]<<<<<<]
; prepare 0 for output
>[-]+++++++>[-]<[>+++++++<-]
; if(sum%length){print 1}else{print 0}
>>[<.[-]>[-]>[-]]<[-.[-]]
```
[Answer]
# Excel, ~~59~~ 54 bytes
Saved 5 bytes thanks to pajonk.
```
=MOD(SUM(CODE(MID(A1,SEQUENCE(LEN(A1)),1))),LEN(A1))=0
```
Input is in cell `A1`. Output is wherever the formula is.
* `SEQUENCE(LEN(A1))` creates an array with values 1 to the word length.
* `MID(A1,SEQUENCE(~),1)` pulls out each letter from the input one at a time.
* `CODE(MID(~))` finds the ASCII code for each letter. We don't have to convert this to 1-26 because it's 1 extra 96 for ever letter of the input so divisibility will be the same.
* `SUM(CODE(~))` adds all those values.
* `MOD(SUM(~),LEN(A1))` returns 0 if it's a whole number and a decimal if it isn't. If anything, this is the opposite of what we want because `0` is falsey and other numbers are truthy, at least in Excel.
* `MOD(~)=0` returns `TRUE` or `FALSE`.
[](https://i.stack.imgur.com/jADJA.png)
---
I found an alternative with the same byte count. It works in reverse and exploits the fact that `CODE()` only pulls the left-most character if it's given a string of greater length. I almost like it more, though, because it has 5 closing parentheses in a row.
```
=MOD(SUM(CODE(RIGHT(A1,SEQUENCE(LEN(A1))))),LEN(A1))=0
```
[Answer]
# [Julia 1.0](http://julialang.org/), 25 bytes
```
!x=sum(Int,x)%length(x)<1
```
[Try it online!](https://tio.run/##RcpLCsIwFIXheVdxWxASyKTTYJy7Crl51EbibckD0tXHFrGe0Qf/eZXgcayt9VWl8mZ3yqLyS3D0zDOr/Dq2aYkQPDnwBNGhPZwY72AfCniAgrQGn9kRBAxy@LY1esqBGIK6QY@8c2QbaqMl5FjyvHXGmNOIeFo7K2HCkPbLYt3P@u8P "Julia 1.0 – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 37 bytes
```
s=>eval(Buffer(s).join`+`)%s.length<1
```
[Try it online!](https://tio.run/##hc/LCsIwEIXhvU8RCkKCNMW9deGTdDKd9ELISCYt@PRRBF1Uxf0H/zkzrCCYpmuuI/dUfFukPdMKQV8W7ylpMXbmKXaHzuzFBopDHk/HghyFA9nAg/a6AoeuMkapplE5LXm87TYCEZ/gtwCAP8JR/xYegnxGHh9eM74CtwXlDg "JavaScript (Node.js) – Try It Online")
[Answer]
# [Scala](http://www.scala-lang.org/), 17 bytes
```
s=>s.sum%s.size<1
```
[Try it online!](https://tio.run/##ZY/BisJADIbvPsVPcaEFFfYqtqBPIHjwnJlJtVI7dTKKbOmzd4O6hdVLEr7kg/xiqabBmxPbiC2HUvveBwe@R26cYN226CaA4xKVvC6W2MVQNQfkBTbe10wN8kHyQhZyPX9prX549T2ot@NLqg1IyFiTYF4ghivPnsxa@46I6B0Zdg9UUi2j6R1/QPMPKssWpQ9M9ogOloSRykyjtZqBXabvP7xWs8S6SSWZCg7VjWWJaTemTSXrR0k3f2OSqd1P@uEX "Scala – Try It Online")
[Answer]
# [Wolfram Mathematica](https://www.wolfram.com/mathematica/), ~~34~~ 24 bytes
```
1∣Mean@LetterNumber@#&
```
-10 bytes from @att
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73/BRx2Lf1MQ8B5/UkpLUIr/S3KTUIgdltf8BRZl5JdHKunZpDs4ZiUWJyUDZYgflWLW64OTEvLpqLqXEpOQkJR0upeTkZBCVmJgIogpKi1JBdHl@UQqITkoFU8n5KWDhJCidqMRV@x8A)
[Answer]
# APL+WIN, ~~22~~ 16 bytes
Prompts for string
```
0=(⍴s)|+/⎕av⍳s←⎕
```
[Try it online!Thanks to Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcQJanP5BlyPWooz3tv4GtxqPeLcWaNdr6QJnEske9m4uBskD2f6A81/80LvXEpOQkdS4gIzk5GUwnJiaC6aTUFIh4fkoqRADEAAA "APL (Dyalog Classic) – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~5~~ 4 bytes
*Edit: -1 byte thanks to Razetime*
```
¦L¹Σ
```
[Try it online!](https://tio.run/##yygtzv6f@6ip8f@hZT6Hdp5b/P///2ilxKTkJCUdpeTkZCCZmJgIJJNSU0Ai@SmpIA6IigUA "Husk – Try It Online")
Outputs truthy (non-zero) for perfect words, falsy (zero) for non-perfect words.
[Answer]
# [Ruby](https://www.ruby-lang.org/) `-nl`, 17 bytes
```
p$_.sum%$_.size<1
```
[Try it online!](https://tio.run/##FcUxCoAwDAXQ/Z9DRwV37yJJmqFgm9JaRA9v1OW92vlyL8M2t57Gv3jrurgTC0NEQEQovSpOqwGsAWJBwR@PlSNabj7l/QU "Ruby – Try It Online")
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/index.html), ~~16~~ ~~12~~ ~~9~~ 8 bytes
*Edit: -3 bytes thanks to ovs, and -1 byte thanks to DLosc*
```
≠|·+´@-⊢
```
[Try it at BQN online REPL](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAg4omgfMK3K8K0QC3iiqIKCkbCqCDin6gicHVyZSIsIndvcmQiLCJhYmNkIuKfqQ==)
Outputs nonzero (truthy) for non-perfect words, zero (falsy) for perfect words.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 6 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Takes input as an array of characters. The `c` can be removed by instead taking input as an array of codepoints.
```
xc vUl
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&header=cQ&code=eGMgdlVs&input=ImFiY2Ii)
```
xc vUl :Implicit input of array U
x :Sum of
c : Codepoints
v :Is divisible by
Ul : Length of U
```
[Answer]
# [J](http://jsoftware.com/), 14 bytes
```
0=#|1#.96|3&u:
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DWyVawyV9SzNaozVSq3@a3JxpSZn5CsYKtgqpCmoJyYlJ6mjiCQnJ6MKJCYmQgUMIAJJqSmoAsn5KaloSkAi/wE "J – Try It Online")
*-1 thanks to south*
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 9 bytes
```
¬﹪ΣEθ℅ιLθ
```
[Try it online!](https://tio.run/##DcfBDYAgDADAVXi2CU7gCqImTtCAkSaVCgHXr97vYqYWlcRsb1w6rNohaBqicIwbAj1Qvdta4kICjIjeLWe5eob6B2ezcrLY9MoH "Charcoal – Try It Online") Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` for a perfect word, nothing if not. Explanation:
```
θ Input string
E Map over characters
ι Current character
℅ Ordinal
Σ Sum
¬﹪ Is divisible by
θ Input string
L Length
Implicitly print
```
[Answer]
# [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), ~~103~~ 98 bytes
```
L =SIZE(W =INPUT)
N W LEN(1) . X REM . W :F(O)
S =S + ORD(X) :(N)
O OUTPUT =1 EQ(REMDR(S,L))
END
```
[Try it online!](https://tio.run/##DcsxC8IwEIbh@fIrvvEORSg4FbLlhEK8aNKS4ljsJnbw/xMzvcv7/L7HdnyurVGEL9NLucJP9lhmcUYVUY0HwQUrst57K8YbJ3FU@o8TUg68Co1s4hKlZe4UfiB9cgchczlHEacWWtv29x8 "SNOBOL4 (CSNOBOL4) – Try It Online")
Prints `1` for truthy and nothing for falsey.
[Answer]
# [Ly](https://github.com/LyricLy/Ly), 8 bytes
```
iys&+l%!
```
[Try it online!](https://tio.run/##y6n8/z@zslhNO0dV8f//xKTkJAA "Ly – Try It Online")
```
i - read STDIN onto stack as codepoints
ys - push length of the stack, save to backup cell
&+ - sum the codepoints on the stack (1)
l - load the number of chars from the backup cell
% - module math to push "0" if evenly divisble, ">0" otherwise
! - negate modulo result so that 0->1 and other->0
```
(1) The code includes the length of the original stack in the sum of the codepoints to save the `p` byte that would be needed to delete it. But it doesn't change the result of the modulo math to get the final result.
When the code exits, the only thing on the stack is the `0|1` result, which is printed as a number automatically.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 46 bytes
```
.
$&26$*
+T`1l`_3l`\D.
^
2
O^`.
3
1
^(1+)2\1*$
```
[Try it online!](https://tio.run/##DcRBCoAgEAXQ/T@HhRUIGnSCoGWblmIzTi4EMYjub73Fe9KbK7dOb9QMVO8WNWI6yBY650J@NQhw2AMZzLAI2k6D83ZUrdWUCzhKhIiAmRHTBbmvhPj3AQ "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
.
$&26$*
```
Append 26 `1`s to each letter.
```
+T`1l`_3l`\D.
```
Cycle the letters through the alphabet, removing a `1` each time. Once the letter reaches `a`, replace it with a `3`. (Note that this numbers the alphabet in reverse but this doesn't affect the divisibility check.)
```
^
2
O^`.
```
Insert a `2` and then sort the digits in reverse order, so you have the `3`s for each letter, the `2`, and then the `1`s representing the sum of the positions.
```
3
1
```
Change the `3`s into `1`s.
```
^(1+)2\1*$
```
Check that the leading `1`s divide the trailing `1`s.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `Ṁ`, 11 10 bytes
-1 thanks to [Neil](https://codegolf.stackexchange.com/users/17602/neil)
```
ƛkanḟ;∑?LḊ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyLhuYAiLCIiLCLGm2thbuG4nzviiJE/TOG4iiIsIiIsImFiY2IiXQ==)
# Explanation
```
ƛkanḟ;∑?LḊ
ƛ Start a mapping lambda for input
ka Lowercase alphabet
n Current letter
ḟ Find letter in the alphabet, return index
; Close mapping lambda
∑ Sum the list of indices.
?L Get Length of input
Ḋ Check if Sum is divisible by the length.
```
[Answer]
# [Python 3](https://docs.python.org/3/), 50 bytes
```
s=input();print(sum(ord(c)-95for c in s)%len(s)<1)
```
[Try it online!](https://tio.run/##K6gsycjPM/7/v9g2M6@gtERD07qgKDOvRKO4NFcjvyhFI1lT19I0Lb9IIVkhM0@hWFM1JzVPo1jTxlDz/38A "Python 3 – Try It Online")
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), ~~14~~ 11 bytes
-3 bytes from @Dominic van Essen's improvement
```
{~(#x)!+/x}
```
[Try it online!](https://ngn.codeberg.page/k/#eJxFztEKwiAUxvF7n8JWFxux3KKL0EeJoKPTNrZm6YkcUc+eI6y7H5wPzt/w5ztfhmKxZuFFCPLn6jC9HTeU0iBOthf5yUA3iCAm4YrjvDlkIJXMRH2crZRKBIBEqZtMVN+BbXSyTCaMtIhXzxmb72c7mI1HUL0OqoXxrDfKXtjtrj12dvRsu6urfcU6X3ZYQnnVzmiF5cO6hsw1nKK7YzuRmPNz7Pk5BnFqYPBxEh8my78/fUBWfw==)
* `+/x` take the sum of the ASCII codes of the (strictly lowercase) input
* `(#x)!` mod this sum by the length of the input
* `~` "not" the result, i.e. return `1` if the sum is evenly divisible by the length (i.e. the mod returns 0), and `0` otherwise
] |
[Question]
[
**Challenge Description:**
Write a program that asks the user for input. The user will enter `Good` or `Bad`. You do not have to support any other input. If the user enters `Good`, print `Bad` and vice versa (to stdout etc).
**Notes:**
*1)* You cannot use any other pair of two words.
*2)* Your program only has to ask and print once.
*3)* You do not need to display prompt string.
*4)* The output must appear separated from the input by any means.
*5)* No function is allowed accepting the value and returning the result; User must interact with the program.
*Good luck!*
[Answer]
# [Python 3](https://docs.python.org/3/), ~~32~~ 31 bytes
```
exit('GBoaodd'['G'<input()::2])
```
**[Try it online!](https://tio.run/##K6gsycjPM/7/P7Uis0RD3d0pPzE/JUU9Wt1d3SYzr6C0REPTysooVvP/f6fEFAA "Python 3 – Try It Online")**
### How?
Tests if input is `'Good'` by comparing `'G'<input()`.
Uses the fact that in Python `False==0` and `True==1` to use the result as the `start` index of a slice of `'GBoaodd'` using an undefined `stop` and a `step` of `2` with `'GBoaodd'[start:stop:step]`.
Prints to STDERR (saving a byte with `exit` in place of `print`).
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 13 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set")
Full program that prompts for input from stdin and prints to stdout.
```
'GooBad'~¯1↓⍞
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKO94L@6e36@U2KKet2h9YaP2iY/6p0HEv@vAAYFXEDZFC4YB6gOAA "APL (Dyalog Unicode) – Try It Online")
`⍞` prompt for input from stdin; `Good` or `Bad`
`¯1↓` drop the last character (`d`); `Goo` or `Ba`
`'GooBad'~` multiset subtract those characters from these; `Bad` or `Good`
[Answer]
## bash, 20 bytes
```
sed s/$1//<<<GoodBad
```
[Try it online!](https://tio.run/##S0oszvj/vzg1RaFYX8VQX9/GxsY9Pz/FKTHl////QBIA)
[Answer]
# [Turing Machine But Way Worse](https://github.com/MilkyWay90/Turing-Machine-But-Way-Worse), 405 bytes
```
0 0 0 1 1 0 0
1 1 1 1 2 0 0
0 2 0 1 3 0 0
0 3 0 1 4 0 0
0 4 0 1 5 0 0
1 5 0 1 6 0 0
0 5 1 1 h 0 0
1 6 1 1 7 0 0
1 7 0 1 8 1 0
0 8 0 1 9 0 0
1 9 1 1 9 0 0
0 9 0 1 a 0 0
1 a 0 1 a 0 0
0 a 0 0 b 0 0
0 b 1 1 c 1 0
0 c 0 0 d 0 0
1 d 0 0 e 0 0
0 e 0 0 f 0 0
0 f 1 1 g 1 1
1 h 1 1 i 0 0
0 i 1 1 j 1 0
0 j 0 1 k 0 0
1 k 1 1 k 0 0
0 k 0 1 l 0 0
0 l 1 1 l 0 0
1 l 1 0 m 1 0
1 m 1 1 n 1 0
1 n 1 1 o 0 0
0 o 0 1 p 1 1
```
[Try it online!](https://tio.run/##TZBbDoMgFET/uwqWIPXJCroOH7VVUPrRxOVTOc5HcxMmx5k7GL7bcBwpFSaPPefUmzXX3KECtaYUlVAlqqBaezXUyKtpectroFbUkuzyjWeyg5w8R9KpxeH18vo/Ki41g2hgb1TniDdpDzVPJVEzi2b2Xvm85f/NtMhboFWdK7d7dXo8r6THC6KAF5QMvOxGi0Wt2UU7FLUXafnkbyk9Ypx@ "Turing Machine But Way Worse – Try It Online")
Well, this took a while.
**UNFINISHED EXPLANATION**:
```
0 0 0 1 1 0 0 Start going to the sixth bit
1 1 1 1 2 0 0
0 2 0 1 3 0 0
0 3 0 1 4 0 0
0 4 0 1 5 0 0 End going to the sixth bit
1 5 0 1 6 0 0 If the sixth bit is 1, then it is Good. Start transforming "G" to "B" and go to state 6
0 5 1 1 h 0 0 Else, it is Bad. Start transforming "B" to "G" and go to state h
1 6 1 1 7 0 0 Keep on transforming "G" to "B"
1 7 0 1 8 1 0 End transforming and print "B"
0 8 0 1 9 0 0 We are in the first "o" in "Good". Start moving into the 5th bit.
1 9 1 1 9 0 0
0 9 0 1 a 0 0
1 a 0 1 a 0 0 Do some looping magic and start transforming "o" to "a"
0 a 0 0 b 0 0 End looping magic
0 b 1 1 c 1 0 End transforming and print "a"
0 c 0 0 d 0 0
1 d 0 0 e 0 0 Start transforming "a" to "d"
0 e 0 0 f 0 0
0 f 1 1 g 1 1 Stop transforming, print "d", and terminate
1 h 1 1 i 0 0 Continue transforming "B" to "G"
0 i 1 1 j 1 0 Stop transforming and print out "G"
0 j 0 1 k 0 0 Start going into position to print out "oo"
1 k 1 1 k 0 0
0 k 0 1 l 0 0 Move more efficiently using LOOPING MAGIC1!1111111
0 l 1 1 l 0 0 looping magic end, start transforming
1 l 1 0 m 1 0 end transforming and print out out "o"
1 m 1 1 n 1 0 print out "o" again
1 n 1 1 o 0 0 get into the "d" byte
0 o 0 1 p 1 1 print "d" and execute YOU HAVE BEEN TERMINATED
```
[Answer]
# 8088 Assembly, IBM PC DOS, 25 bytes
**Unassembled:**
```
BA 0110 MOV DX, OFFSET GB ; point DX to 'Good','Bad' string
D1 EE SHR SI, 1 ; point SI to DOS PSP (80H)
02 04 ADD AL, [SI] ; add input string length to AL, set parity flag
7B 02 JNP DISP ; if odd parity, input was 'Bad' so jump to display 'Good'
02 D0 ADD DL, AL ; otherwise add string length as offset for 'Bad' string
DISP:
B4 09 MOV AH, 9 ; DOS display string function
CD 21 INT 21H ; call DOS API, write string to console
C3 RET ; return to DOS
GB DB 'Good$','Bad$'
```
**Explanation:**
Looks at the length of input string (plus leading space) that DOS stores at memory address `80H`, and adds it to `AL` (initially `0` [by DOS](http://www.fysnet.net/yourhelp.htm)). If there is an odd number of `1` bits in the binary representation of the string length, the CPU parity flag is set to odd, and vice-versa. So input string `' Bad'` length `4` (`0000 0100`), is odd parity and input string `' Good'` is `5` (`0000 0101`) is even parity.
`DX` is initially set to point to the string `'Good$Bad$'`, and if parity is even (meaning input was `' Good'`) advance the string pointer by that length (`5`) so it now points to `'Bad$'`. If parity is odd, do nothing since it already points to `'Good$'`. Then use DOS API to display a `$` terminated string to console.
**Example:**
[](https://i.stack.imgur.com/uw5Ze.png)
Download and test [GOODBAD.COM](https://stage.stonedrop.com/ppcg/GOODBAD.COM) or build from `xxd` dump:
```
0000000: ba10 01d1 ee02 047b 0202 d0b4 09cd 21c3 .......{......!.
0000010: 476f 6f64 2442 6164 24 Good$Bad$
```
[Answer]
## Python 3, ~~38~~ ~~37~~ ~~34~~ 33 bytes
```
exit("C">input()and"Good"or"Bad")
```
[Try it online!](https://tio.run/##K6gsycjPM/7/P7Uis0RDyVnJLjOvoLREQzMxL0XJPT8/RSm/SMkpMUVJ8/9/EBcA)
`exit()` : returns an exit code as output
`"C">input()` : Checks whether the input is larger than the string `C` in the alphabetical order
`and"Good"` : If the result is `True`, then returns with `Good`
`or"Bad"` : Otherwise, returns with `Bad`
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
“Ċ³ṫ³»œṣ
```
**[Try it online!](https://tio.run/##ASAA3/9qZWxsef//4oCcxIrCs@G5q8KzwrvFk@G5o////0JhZA "Jelly – Try It Online")**
A full program expecting a Python formatted string as an argument
### How?
```
“Ċ³ṫ³»œṣ - Main Link: list of characters, S
“Ċ³ṫ³» - compression of dictionary words "Good"+"Bad" = ['G','o','o','d','B','a','d']
œṣ - split on sublists equal to S
- implicit, smashing print
```
[Answer]
# C, ~~39~~ 38 bytes
```
main(){puts("Good\0Bad"+getchar()%6);}
```
[Try it online!](https://tio.run/##S9ZNT07@/z83MTNPQ7O6oLSkWEPJPT8/JcbAKTFFSTs9tSQ5I7FIQ1PVTNO69v9/oCAA "C (gcc) – Try It Online")
Saved one byte thanks to @tsh.
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), 72 bytes
```
,>+++++>,>,>,>,[<<<<[-<->>---<]<.>>+.>>.>>>]<[<<<[-<+>>+++<]<.>>-..>.>>]
```
[Try it online!](https://tio.run/##SypKzMxLK03O/v9fx04bBOx0IDDaBgiidW107ex0dXVtYm307Oy0gRiI7GJtoiGS2nYgTRBJXT09kGTs//9OiSlc/wE "brainfuck – Try It Online")
Explanation:
,>+++++>,>,>,>,
Read either:
"G", 5, "o", "o", "d" or
"B", 5, "a", "d", 0
[<<<<[-<->>---<]<.>>+.>>.>>>]
If the last character is not zero:
Substract 5 from the first cell once and from the third cell thrice.
Increment cell 3
Output cells 1, 3, 5.
<[<<<[-<+>>+++<]<.>>-..>.>>]
Otherwise add 5 to the first cell once and to the third cell thrice.
Decrement cell 3
Output cells 1, 3, 3, 4
[Answer]
# [R](https://www.r-project.org/), ~~42~~ ~~37~~ ~~35~~ 32 bytes
-10 thanks to Giuseppe and AkselA!
```
`if`(scan(,'')>'C','Bad','Good')
```
[Try it online!](https://tio.run/##K/r/PyEzLUGjODkxT0NHXV3TTt1ZXUfdKTEFSLrn56eoa/4HUf8B "R – Try It Online")
[Answer]
# [sed](https://www.gnu.org/software/sed/), ~~21 16~~ 13 bytes
*Thanks @Cowsquack for the hints.*
```
/B/cGood
cBad
```
~~[Try it online!](https://tio.run/##K05N0U3PK/3/v1jfPT9f3ylR37qEqxhEg7j//wPJFC6nxBQA "sed – Try It Online")
[Try it online!](https://tio.run/##K05N0U3PK/3/v1jfKVHfPT9f37qEK9kpMeX/fyAnhQvIAgA "sed – Try It Online")~~
[Try it online!](https://tio.run/##K05N0U3PK/3/X99JP9k9Pz@FK9kpMeX/fzATyAIA "sed – Try It Online")
TIL `c` will short-circuit the current line's parsing.
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 10 bytes
```
:`GoodBad
```
[Try it online!](https://tio.run/##K0otycxLNPz/3yrBPT8/xSkxhev/fyAJAA "Retina – Try It Online")
`:` swaps the input and the regex, so this computes `'GoodBad'.replace(input, '')`.
[Answer]
## Haskell, ~~36~~ 34 bytes
```
interact g
g"Bad"="Good"
g _="Bad"
```
[Try it online!](https://tio.run/##y0gszk7Nyfmfm5iZZxvzPzOvJLUoMblEIZ0rXckpMUXJVsk9Pz9FiStdId4WLPD/P5D8l5yWk5he/F83uaAAAA "Haskell – Try It Online")
Edit: -2 bytes thanks to @cole
[Answer]
# JavaScript 31 bytes
I like Arnauld's answer, but I would like it to accept user input and be runnable on StackExchange like so:
```
alert(prompt()[3]?'Bad':'Good')
```
[Answer]
# [Shakespeare Programming Language](https://github.com/TryItOnline/spl), 582 bytes
(Whitespace added for readability)
```
G.Ajax,.Puck,.Act I:.Scene I:.[Enter Ajax and Puck]Ajax:
Open mind.Be you nicer the sum ofa big cat the cube ofa big big cat?If solet usScene V.
You is the sum ofthe sum ofyou a big big cat a cat.Speak thy.You is the sum ofyou twice twice twice the sum ofa big big cat a cat.Speak thy.Speak thy.You is the square oftwice the sum ofa big big cat a cat.Let usScene X.
Scene V:.Ajax:
You is the sum ofthe sum ofyou a big big pig a pig.Speak thy.You is the sum ofyou the sum ofa big big big big big cat a pig.Speak thy.You is the sum ofyou the sum ofa big cat a cat.
Scene X:.Ajax:Speak thy.
```
[Try it online!](https://tio.run/##nVBRCoJAEL3KHED2AP6EQoQQFAhSRB/rOpapq7m7lKe3XZXUMoo@dpiZnffmvRFl1jQr4lzo3SJbxVKLOEyCZxOfIUeTHJZcYgVmBCiPwEwdTWVvSuSQJzwiLkJdKOAJ05PyjCBUDkVMIUxOwKhse0yF@Gz2HwsvBlFkKEGJbmNA9popESOaITNLJnhd6Uj8EmmqEfU72EDkTQubxheNn@jmia@KVsbKL1zrkbddf9XAbi9u/@y01I@a@NXpjJbx63T9QTQ6TmeltzDQNI1Lowc "Shakespeare Programming Language – Try It Online")
I get the first letter of the input with `Open mind`. Then I need to determine what it is. Of all the numbers between `B`=66 and `G`=71, my brute forcer says 66 is the shortest to write (`the sum ofa big cat the cube ofa big big cat`), so I compare the first letter of the input to 66. Scene I continues to print `Good`, or Scene V prints `Bad`.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 13 bytes
```
¿⁻LS³Ba¦Goo¦d
```
[Try it online!](https://tio.run/##ASYA2f9jaGFyY29hbP//wr/igbvvvKzvvLPCs0JhwqZHb2/CpmT//0JhZA "Charcoal – Try It Online")
### Explanation:
```
¿⁻LS³ If length of input minus 3 is truthy:
Ba¦ print Ba
Goo¦ else print Goo
d print d
```
[Answer]
# [Befunge-93](https://github.com/catseye/Befunge-93), ~~20~~ 18 bytes
```
"BadooGB"~-_#@,,<,
```
[Try it online!](https://tio.run/##S0pNK81LT/3/X8kpMSU/391JqU43XtlBR8dG5/9/oBAA "Befunge-93 – Try It Online")
*-2 bytes thanks to Jo King*
[Answer]
# [Ruby](https://www.ruby-lang.org/), 22 bytes
```
->n{n>?F?"Bad":"Good"}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6vOs/O3s1eySkxRclKyT0/P0Wp9n9BaUmxQlo0WDCWC8YDS8b@BwA "Ruby – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~10~~ 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
”‚¿‰±”áIK
```
-1 byte thanks to *@Emigna*.
[Try it online](https://tio.run/##yy9OTMpM/f//UcPcRw2zDu1/1LDh0EYg5/BCT@///50SUwA) or [verify both test cases](https://tio.run/##yy9OTMpM/f@oYe6jhlmH9j9q2HBoI5CjXFZpr6TwqG2SgpI9huThhZXe/3X@AwA).
**Explanation:**
```
”‚¿‰±” # Push dictionary string "Good Bad"
á # Only keep letters (to remove the space)
IK # Remove the input
# (output the result implicitly)
```
[See this 05AB1E tip of mine (section *How to use the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210), to understand why `”‚¿‰±”` is `"Good Bad"`.
[Answer]
# [Java (JDK)](http://jdk.java.net/), 124 bytes
```
interface G{static void main(String[]a){System.out.print(new java.util.Scanner(System.in).next().length()>3?"Bad":"Good");}}
```
[Try it online!](https://tio.run/##LYyxCsIwEEB/JWRKBrO4KSi49AMySocjOevF9iLptSql3x4ruD0ej5dghl2Kj1qJBcsNAqpmGQWEgpozRTUAsfFSiLtrC3bxn1FwcHkS99ykGMaXStvGTUK98wGYsZh/Rmwd41uMdT1yJ3djT/uzvkDUB93kHLU9rmutP/wC "Java (JDK) – Try It Online")
Most likely, there‘s still some room for improvement, but I‘m entirely new to code golfing.
[Answer]
# Ruby, 30 28 bytes
```
puts %w|Good Bad|-gets.split
```
Not the golf-iest, but I like the abuse of split to remove the trailing newline and convert to an array in one call.
EDIT -2 bytes thanks to Value Ink's suggestion!
[Answer]
# [GolfScript](http://www.golfscript.com/golfscript/), 11 bytes
```
"GoodBad"\/
```
[Try it online!](https://tio.run/##S8/PSStOLsosKPn/X8k9Pz/FKTFFKUb//38gDQA "GolfScript – Try It Online")
## Explanation
```
"GoodBad" # Define the lookup table "GoodBad"
\ # Swap the input so that it can be used by /
/ # Split the lookup table by occurences of the input
# Implicit print, smashing
```
[Answer]
# C (gcc), 48 bytes
```
main(){puts(getchar()-66?"Bad":"Good");}
```
[Try It Online!](https://tio.run/##S9ZNT07@/7842jLWOjcxM09Ds7qgtKRYo7ikKDm3QCM9FcTW1FFySkxR0rQHU1ZK7vn5QJ517f//AA)
The program only actually takes one character as input, although `getchar` reads until a newline is found unlike `getch` which only *lets* you input a single character. It checks if there's a difference between that character and the ascii code for 'B' (66), printing "Bad" if there is and "Good" if there isn't.
[Answer]
# JavaScript, ~~35~~ ~~32~~ 31 bytes
-3 bytes thanks to [@xigoi](https://codegolf.stackexchange.com/users/98955)
-1 byte thanks to [@l4m2](https://codegolf.stackexchange.com/users/76323)
```
alert(prompt()[3]?'Bad':'Good')
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 20 bytes
```
oo
o
T`G\oaB`Ro
o
oo
```
[Try it online!](https://tio.run/##K0otycxL/P8/P58rnyskwT0mP9EpIQjEyc///989Pz@FyykxBQA "Retina 0.8.2 – Try It Online") Link includes test suite. Explanation:
```
oo
o
```
Turn `Good` into `God`.
```
T`G\oaB`Ro
```
Transpose the letters `GoaB` with the reverse of that list, thus exchanging `G` with `B` and `o` with `a`, i.e. exchanging `God` with `Bad`.
```
o
oo
```
Turn `God` into `Good`.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), ~~9~~ 8 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
çEF♫a║▬h
```
[Run and debug it](https://staxlang.xyz/#p=8745460e61ba1668&i=Good%0ABad&a=1&m=2)
~~Essentially `replace("BadGood", input, "")`.~~
Multiset xor with "GooBa". Algorithm copied verbatim from [Luis Mendo](https://codegolf.stackexchange.com/a/187826/527)
[Answer]
# Java, 30 bytes
```
s->s.charAt(0)>66?"Bad":"Good"
```
[TIO](https://tio.run/##dYyxDoIwFEV3vuKFqR1onBgkYnTAyYnRODxbqkVoSVtIDOHba4msTvcm99zT4oRZK96Bd@gcXFFpmBOlfWMl8gaqufZW6SdIshVHiyUZxkenODiPPsZklIA@Xjfmdge0T0ejqQIJh@Cy0jH@QnvyZEfLPD@mZxTpPr0YI9JQJPXH@aZnZvRsiAbfaSKZJL@d0v/Aqln3ZQlf)
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, 15 bytes
```
$_=/B/?Good:Bad
```
[Try it online!](https://tio.run/##K0gtyjH9/18l3lbfSd/ePT8/xcopMeX/fxDrX35BSWZ@XvF/3QIA "Perl 5 – Try It Online")
[Answer]
# Excel, 24 bytes
```
=IF(A1>"C","Bad","Good")
```
Using @MilkyWay90's `<C` suggestion.
[Answer]
# [PHP](https://php.net/), ~~26~~ 23 bytes
A ternary is just cheaper:
```
<?=$argn==Bad?Goo:Ba?>d
```
[Try it online!](https://tio.run/##K8go@P/fxt5WJbEoPc/W1ikxxd49P9/KKdHeLuX/fyAz5V9@QUlmfl7xf103AA "PHP – Try It Online")
**Original answer, 26 bytes**
```
<?=[Ba,Goo][$argn==Bad]?>d
```
[Try it online!](https://tio.run/##K8go@P/fxt422ilRxz0/PzZaJbEoPc/W1ikxJdbeLuX/f6Bgyr/8gpLM/Lzi/7puAA "PHP – Try It Online")
**Or 21 bytes (but this is basically [Arnauld's answer](https://codegolf.stackexchange.com/questions/187816/swapping-good-and-bad/187836#187836))**
```
<?=$argn[3]?Ba:Goo?>d
```
[Try it online!](https://tio.run/##K8go@P/fxt5WJbEoPS/aONbeKdHKPT/f3i7l/38gnfIvv6AkMz@v@L@uGwA "PHP – Try It Online")
] |
[Question]
[
Display numbers from one to one-hundred (in increasing order), but number 2 shouldn’t appear anywhere in the sequence. So, for example, the numbers two (`2`) or twenty-three (`23`) shouldn't be in the sequence.
Here is an example output, with newlines separating the numbers:
```
1
3
4
5
6
7
8
9
10
11
13
14
15
16
17
18
19
30
31
33
34
35
36
37
38
39
40
41
43
44
45
46
47
48
49
50
51
53
54
55
56
57
58
59
60
61
63
64
65
66
67
68
69
70
71
73
74
75
76
77
78
79
80
81
83
84
85
86
87
88
89
90
91
93
94
95
96
97
98
99
100
```
[Answer]
# [Taxi](https://bigzaphod.github.io/Taxi/), ~~2399~~ ~~2391~~ ~~2370~~ ~~1783~~ ~~1773~~ 1706 bytes
*-8 bytes for realizing that, instead of leaving a certain passenger at Sunny Side Park forever, it's more worth it to throw them off of Riverview Bridge. Ah, what a lovely town this is.*
*-21 bytes for taking out a comment I stupidly left in.*
*-587 bytes by simply changing the entire way I went about this (apparently a shorter way is by arithmetic; integer-dividing [17, 27, 37, 47,...] by 9 yields the sequence, but you gotta skip over the 20's yourself.)*
*-17 bytes for the realization that any quotes-encased string without a space doesn't need quotes after all (thanks Jo King!).*
*-67 bytes for the realization that linebreaks are optional.*
```
17 is waiting at Starchild Numerology.Go to Starchild Numerology:w 1 l 2 r 1 l 1 l 2 l.Pickup a passenger going to Cyclone.Go to Cyclone:e 1 l 2 r.[B]Pickup a passenger going to Cyclone.Pickup a passenger going to Divide and Conquer.9 is waiting at Starchild Numerology.Go to Starchild Numerology:s 2 l 2 r.Pickup a passenger going to Divide and Conquer.Go to Divide and Conquer:e 1 l 2 r 3 r 2 r 1 r.Pickup a passenger going to Trunkers.Go to Trunkers:e 1 r 3 r 1 l.Pickup a passenger going to The Babelfishery.Go to The Babelfishery:e 1 r 1 r.Pickup a passenger going to Post Office.\n is waiting at Writer's Depot.Go to Writer's Depot:n 5 l 2 l.Pickup a passenger going to Post Office.Go to Post Office:n 1 r 2 r 1 l.Go to Cyclone:s 1 r 1 l 2 r.Pickup a passenger going to Addition Alley.Pickup a passenger going to Equal's Corner.177 is waiting at Starchild Numerology.Go to Starchild Numerology:s 2 l 2 r.Pickup a passenger going to Equal's Corner.Go to Equal's Corner:w 1 l.Switch to plan C if no one is waiting.Pickup a passenger going to Sunny Skies Park.100 is waiting at Starchild Numerology.Switch to plan D.[C]10 is waiting at Starchild Numerology.[D]Go to Starchild Numerology:n 1 r.Pickup a passenger going to Addition Alley.Go to Sunny Skies Park:w 1 r.Go to Addition Alley:n 1 r 1 r 1 r.Pickup a passenger going to Cyclone.Go to Cyclone:n 1 l 1 l.Pickup a passenger going to Cyclone.Pickup a passenger going to Equal's Corner.917 is waiting at Starchild Numerology.Go to Starchild Numerology:s 2 l 2 r.Pickup a passenger going to Equal's Corner.Go to Equal's Corner:w 1 l.Switch to plan E if no one is waiting.Switch to plan F.[E]Go to Go More:n 1 l.Go to Cyclone:w 1 r.Switch to plan B.[F]
```
[Try it online!](https://tio.run/##zVRdT4MwFP0r9823ZmjMsr1tbPNJXcISH5CHCgUaasva4uTXI4OiW10AY2J84Ou299x7zj1U43daVc4UqIIDppryBLAGT2MZppRF8FC8EimYSEp0J0CLi0vzAzjA4Bpk82zfGdrSMCtywJBjpQhPiIREHCvUMG4ZMsGJATVfc9LhIH8ZjEnv27OibzQigHkEruD7gkg0@yVPdeTV9PfDwi3m94UvxnBTX62C/eg7WfCMSGUwu88GqUVxBrTfpQSW@IWwmKqUyI6xHTaIQ/1shdLwGMc0JOiZWwI/SaqJvFKwIrnQptB5cM7hdoRhTsu0MCeRGsP5lI9ZplKGxvDgFlFUdy44LBgjZe/W9b7ArKbgCsnr@TrT6Z9Yyyrb4p0H258ReQeqw/S4nDPMwQUaAxdQC3LSaG8tr@C8BC@jRMEWyww5k8kYklblFfLdwBmV6a@CHoX4oBWt@Rksi0ajTyfdeYax0RjXXz6/eHf@od8eXtagZ84/99f6sr@sXRvkr82I6/u9kEYyS8Z2QlbuEvmboKo@AA "Taxi – Try It Online")
This one isn't winning me any code golf competitions anytime soon, but I decided to try out the esolang Taxi.
Taxi is an esolang in which all programming is done by picking up and dropping off passengers at various stops in the fictional town of Townsburg. Of course, your taxicab will sometimes run out of gas, so you also need to visit gas stations every so often, and pay using the credits you receive as fare (in this case, I only need to stop for gas - at Go More - once per loop iteration!).
I used some tricks that reduce the filesize a bit, such as rephrasing directions like `east 1st left, 2nd right` as `e 1 l 2 r`, removing the word `the` where it is optional, and using the least complicated route towards all of my destinations (not necessarily the shortest path).
I hate this shorter solution more than the one I originally came up with. This solution down here is a more general way of accomplishing the task, which could start and end anywhere you want. Here it is, in its entirety.
# 2245 bytes (way more general)
```
1 is waiting at Starchild Numerology.Go to Starchild Numerology:w 1 l 2 r 1 l 1 l 2 l.Pickup a passenger going to Cyclone.Go to Cyclone:e 1 l 2 r.[B]Pickup a passenger going to Addition Alley.Pickup a passenger going to The Babelfishery.Go to The Babelfishery:n 2 r 2 r.Pickup a passenger going to Cyclone.Go to Cyclone:n 5 l 2 l.Pickup a passenger going to Chop Suey.Go to Zoom Zoom:n.0 is waiting at Writer's Depot.Go to Writer's Depot:w.Pickup a passenger going to Narrow Path Park.Go to Narrow Path Park:n 3 r 1 l 1 r.Go to Chop Suey:e 1 r 1 l 1 r.[C]Switch to plan E if no one is waiting.Pickup a passenger going to Crime Lab.2 is waiting at Writer's Depot.Go to Writer's Depot:n 1 l 3 l.Pickup a passenger going to Crime Lab.Go to Crime Lab:n 3 r 2 r.Switch to plan D if no one is waiting.Pickup a passenger going to KonKat's.Go to Narrow Path Park:n 5 l.Pickup a passenger going to KonKat's.Go to KonKat's:e 1 r.Pickup a passenger going to Narrow Path Park.Go to Narrow Path Park:n 2 l.Go to Chop Suey:e 1 r 1 l 1 r.Switch to plan C.[D]Go to Chop Suey:n 5 r 1 l.Switch to plan C.[E]Go to Narrow Path Park:n 1 l 1 r 1 l.Pickup a passenger going to Crime Lab.0 is waiting at Writer's Depot.Go to Writer's Depot:w 1 l 1 r 2 l.1 is waiting at Starchild Numerology.Pickup a passenger going to Crime Lab.Go to Crime Lab:n 3 r 2 r.Switch to plan F if no one is waiting.Pickup a passenger going to Riverview Bridge.Go to Cyclone:n 4 l 2 l.Pickup a passenger going to Post Office.Go to Riverview Bridge:n 2 r.\n is waiting at Writer's Depot.Go to Writer's Depot:w 2 l.Pickup a passenger going to Post Office.Go to Post Office:n 1 r 2 r 1 l.Go to Starchild Numerology:s 1 r 1 l 1 l 2 l.Switch to plan G.[F]Go to Cyclone:s 1 r 1 l 2 r.Pickup a passenger going to Riverview Bridge.Go to Riverview Bridge:n 2 r.Go to Starchild Numerology:w 2 l 3 l 2 r.[G]Pickup a passenger going to Addition Alley.Go to Addition Alley:e 1 l 2 r 3 r 1 r.Pickup a passenger going to Magic Eight.101 is waiting at Starchild Numerology.Go to Starchild Numerology:n 1 l 1 l 3 l 2 r.Pickup a passenger going to Magic Eight.Go to Magic Eight:w 1 r 2 r 1 r.Switch to plan H if no one is waiting.Pickup a passenger going to Cyclone.Go to Cyclone:n 1 l 2 r.Switch to plan B.[H]
```
[Try it online!](https://tio.run/##rVVNb6MwEP0rc@vNapLthVvz0VTqbjfaVKq0LAeXODCqYyPjlObXp2BwQtxCINsL4DEzb94be0bTd9zvB4ApZBQ1igiohqWmKoyRr@Bxu2FKchntyFyCll9ueRkMgMMQlHmX35wsMHzdJkAhoWnKRMQURLJAyMNMdiGXglVBq5XHbBzij4M299vVKk9WCrjlnO1akZ5iBmP6wvga05gpy8M1e8LkX2D3z1vATRfOsUxguWU2hb9SbszDE@TaqcCzQs3UVQpTlkhdOZwavawV7ZEqJTNYUB3nD/VaxXDNee6jQ92U5WUzNRU57vqTYJmhDuPip4RTATPANQgJuQo1Bu0yKNww@ElfyPAC0sIkMzon9QGjImTXFd2izA6TaX8mD1I8UH2VNkt7cyZPJ4JdlrJ/U3mLY9leVkeJCfGngetRcDEeX/w9CxrBKwjj2K1gF92EA05BtlM3@@bTc9f/9PzBN6bekGUwVriKPveUHx16ykKmGn6v1xhafzds2djIP3GRrv3xaxZTf2XnQtsASWvnsSTt6Dsn/l1wKtDR51zTblC6QanWOTcsm085o@Z9ZlQZ9tR4HHhVE27n8YtGGMIMo1iTwfX/Dm1x0HvUQcM6dhm0ZjEX0Bb60924v2BGNIxZW20HYUz8@2C//wA "Taxi – Try It Online")
And if mega-cheating is allowed, this one is way shorter than either of the last two.
# 456 bytes (totally cheating)
```
1\n3\n4\n5\n6\n7\n8\n9\n10\n11\n13\n14\n15\n16\n17\n18\n19\n30\n31\n33\n34\n35\n36\n37\n38\n39\n40\n41\n43\n44\n45\n46\n47\n48\n49\n50\n51\n53\n54\n55\n56\n57\n58\n59\n60\n61\n63\n64\n65\n66\n67\n68\n69\n70\n71\n73\n74\n75\n76\n77\n78\n79\n80\n81\n83\n84\n85\n86\n87\n88\n89\n90\n91\n93\n94\n95\n96\n97\n98\n99\n100 is waiting at Writer's Depot.Go to Writer's Depot:w 1 l 2 r 1 l 2 l.Pickup a passenger going to Post Office.Go to Post Office:n 1 r 2 r 1 l.
```
[Try it online!](https://tio.run/##XdA/a8MwEIfhr3JbNxNV/zMXOjZbFy0mOEY0nIOtkn5791VJoXQQgrtHP@nUxq@676aoLeqK@qKhaCyaiuai5sCiaega2oa@ARiEgRiMxdgegLEYi7EYi7EYi3EYh3H9FozDOIzDOIzDeIzHeIzvT8F4jMd4jMcETMAETMCE/l5MwARMwERMxERMxERM7ENhIiZiEiZhEiZhEiZhUp8ckzAZkzEZkzEZkzEZk/v3/PzPQeom97G2qrOMTd7X2qb1aZOX6ba04XWRtvwrHu9i5CrPsj7263Cq54/Pm4xyG7dt0nlaZV56IodPy9bk7XKp5@kR96dyVDLW36xh378B "Taxi – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 39 bytes
```
k=7
exec"k+=10;print(k>177)*10+k/9;"*81
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P9vWnCu1IjVZKVvb1tDAuqAoM69EI9vO0NxcU8vQQDtb39JaScvC8P9/AA "Python 2 – Try It Online")
Uses arithmetic operations only to generate numbers without 2's.
The value `k` follows the arithmetic progression `17, 27, 37, 47, ...`, which when floor-divided by 9 gives `1,3,4,5,6,7,8,9,10,11,13,14,...` which counts up numbers not ending in 2. To skip 20 through 29, outputs are increased by 10 past a certain threshold.
[Answer]
# JavaScript (ES6), 43 bytes
Returns the sequence as a comma-separated string.
```
f=(n=98)=>n?f(n-=n-27?n%10?1:2:11)+[,n+3]:1
```
[Try it online!](https://tio.run/##BcFBCoAgEADA1wSKGa0dKsF8SHQQ0yhkNzL6/jZzhS/U@Jz3q5H2xJydQDdP0i3os0DtUJvRYwO9B2ssgFRri2rYLHAkrFRSV@gQWUjJPw "JavaScript (Node.js) – Try It Online")
### Why doing it this way?
We could iterate from \$1\$ to \$100\$ and test each number with `/2/.test(n)`, which is a rather concise statement. But in this scenario, we'd have to handle empty entries with something like `(/2/.test(n)?'':...)`, which adds a couple more bytes.
For example, this would work for [45 bytes](https://tio.run/##BcFBCoAgEADA57iLpthNQX1IdBDTKGSNlL5vM3f8Yk/v9YyF2pHnLA7IaXSevDGBLKhVyZH7AMLAmN1IiB15AeIaZ2rUW82ythMKIM4f):
```
f=(n=1)=>n>99?n:(/2/.test(n)?'':[n,,])+f(n+1)
```
Or this would work for [44 bytes](https://tio.run/##BcFbCoAgEADA4@wu5atPwTxI9CGmUcgaKV3fZu7whRbf6@mC65HGyA7ZGa3JrewzsjA0oVqU7Kl1ZPIAdpt5JwswYuVWS5KlnpiRaPw), if a leading comma is acceptable:
```
f=(n=100)=>n?f(n-1)+(/2/.test(n)?'':[,n]):''
```
All in all (and until proven otherwise), it turns out to be shorter to *skip right away* all values of \$n\$ that contain a \$2\$.
### Commented
```
f = // f is a recursive function taking:
(n = 98) => // n = counter, initialized to 98
n ? // if n is not equal to 0:
f( // prepend the result of a recursive call:
n -= // update n:
n - 27 ? // if n is not equal to 27:
n % 10 ? // if n is not a multiple of 10:
1 // subtract 1 from n
: // else:
2 // subtract 2 from n
: // else (n = 27):
11 // subtract 11 from n (--> 16)
) + // end of recursive call
[, n + 3] // append a comma, followed by n + 3; notice that this is the value
// of n *after* it was updated for the recursive call; at the first
// iteration, we have: n = 98 -> updated to 97 -> n + 3 = 100
: // else (n = 0):
1 // output the first term '1' and stop recursion
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes
```
—ÇL í2√•_
```
[Try it online!](https://tio.run/##yy9OTMpM/f//YpPPqUlGh5fG//8PAA "05AB1E – Try It Online")
**Explanation**
```
—ÇL # push [1 ... 100]
í # filter, keep only elements that
2å_ # does not contain 2
```
[Answer]
# [R](https://www.r-project.org/), 19 bytes
```
grep(2,1:100,inv=T)
```
[Try it online!](https://tio.run/##K/r/P70otUDDSMfQytDAQCczr8w2RPP/fwA "R – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 44 bytes
```
print[n for n in range(1,101)if'2'not in`n`]
```
[Try it online!](https://tio.run/##K6gsycjPM/r/v6AoM68kOk8hLb9IIU8hM0@hKDEvPVXDUMfQwFAzM03dSD0vvwQonpCXEPv/PwA "Python 2 – Try It Online")
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 22 bytes
```
put grep {!/2/},1..100
```
[Try it online!](https://tio.run/##K0gtyjH7/7@gtEQhvSi1QKFaUd9Iv1bHUE/P0MDg/38A "Perl 6 – Try It Online")
There's probably a better way to do the code block, but I couldn't find a regex adverb to invert the match
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~22~~ 16 bytes
```
1..100-notmatch2
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/31BPz9DAQDcvvyQ3sSQ5w@j/fwA "PowerShell – Try It Online")
*-6 bytes thanks to mazzy*
Generates the range `1` to `100`, then pulls out those objects where they do `-notmatch` the number `2`. Running the `-notmatch` against an array like this acts like a filter on the array. Each item is left on the pipeline, and output is implicit.
[Answer]
# [Haskell](https://www.haskell.org/), ~~48~~ ~~33~~ 31 bytes
Thanks @JonathanFrech for fifteen bytes saved, and @xnor for another two! I missed a big golf and didn't realize `main=print$` can be omitted.
```
filter(all(/='2').show)[1..100]
```
[Try it online!](https://tio.run/##y0gszk7Nyfmfm5iZp2CrUFCUmVeiUMGloFCekVqUqlBdoWD7Py0zpyS1SCMxJ0dD31bdSF1Trzgjv1wz2lBPz9DAIPa/gkLtfwA)
Easily extended by changing the `100`. Stringifies all the numbers and keeps only those without a `'2'`.
[Answer]
# [Bash](https://www.gnu.org/software/bash/) + GNU utilities, 16
* 1 byte saved thanks to @Dennis.
```
seq 100|sed /2/d
```
[Try it online!](https://tio.run/##S0oszvj/vzi1UMHQwKCmODVFQd9IP@X/fwA "Bash – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 7 bytes
```
Lõs kø2
```
---
```
Lõs kø2 Full Program
Lõs Range ["1"..."100"] (numbers are casted to string)
k Remove
√∏2 anything that contains "2"
```
[Try it online!](https://tio.run/##y0osKPn/3@fw1mKF7MM7jP7/BwA "Japt – Try It Online")
[Answer]
# Java 10, 67 bytes
```
v->{for(int i=0;++i<101;)if(i%10!=2&i/10!=2)System.out.println(i);}
```
[Try it online.](https://tio.run/##LY7BDoIwEETvfMV60LQhIHgt@AdyIfFiPNQCZrEUQksTQ/j2WpDLTnazM/NabnnUVh8nJNcabhzVHACgMvXYcFFDsa4AtscKBLmvYinztyXwQxtuUEABCnJwNrrOTT8S7wbMExaGmKVJyig2BI9pcsgvJzxvSsuvNnUX95OJh9EbpCJI2eLYGjtML@lj9/Stu/NkpDT@9f14Aqd/LBULoiYpd6LF/QA)
**Explanation:**
```
v->{ // Method with empty unused parameter and no return-type
for(int i=0;++i<101;) // Loop `i` in the range (0, 101)
if(i%10!=2 // If `i` modulo-10 is not 2
&i/10!=2) // And `i` integer-divided by 10 is not 2 either
System.out.println(i);} // Print `i` with a trailing newline
```
[Answer]
# Powershell, 19 bytes
```
1..100-split'.*2.*'
```
This script show null-value instead 'numbers with 2 inside' and completely solves the task 'number 2 shouldn’t appear anywhere in the sequence'.
Output:
```
1
3
4
5
6
7
8
9
10
11
13
14
15
16
17
18
19
30
31
33
34
35
36
37
38
39
40
41
43
44
45
46
47
48
49
50
51
53
54
55
56
57
58
59
60
61
63
64
65
66
67
68
69
70
71
73
74
75
76
77
78
79
80
81
83
84
85
86
87
88
89
90
91
93
94
95
96
97
98
99
100
```
## Powerhsell (output does not contain null-values), 24 bytes
```
1..100-split'.*2.*'-ne''
```
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~19~~ 17 bytes
```
100*
.
$.>`¶
A`2
```
[Try it online!](https://tio.run/##K0otycxLNPz/n8vQwECLS49LRc8u4dA2LscEo///AQ "Retina – Try It Online") Edit: Saved 2 bytes thanks to @ovs, although the last line now includes a newline. Explanation:
```
100*
```
Insert 100 characters.
```
.
$.>`¶
```
Replace each character with the number of characters up to and including that character, plus a newline.
```
A`2
```
Remove all entries that contain a `2`.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 6 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
Ç░τ╒╜h
```
[Run and debug it](https://staxlang.xyz/#p=80b0e7d5bd68&i=&a=1)
Unpacked, ungolfed, and commented, it looks like this.
```
AJ 10 squared
f output each value in [1 .. n] satisfying the following filter
E get array of decimal digits in number
2# count the number of 2s
! logical not
```
[Run this one](https://staxlang.xyz/#c=AJ%0910+squared%0Af%09output+each+value+in+[1+..+n]+satisfying+the+following+filter%0A+E%09get+array+of+decimal+digits+in+number%0A+2%23+%09count+the+number+of+2s%0A+%21+%09logical+not&i=&a=1)
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 42 bytes
```
Print@‚åàRange[1,100,10/9]~Drop~{18,26}‚åâ
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78/z@gKDOvxOFRT0dQYl56arShjqGBARDrW8bWuRTlF9RVG1roGJnVPurp/P8fAA "Wolfram Language (Mathematica) – Try It Online")
The arithmetic sequence 1, 19/9, 29/9, 39/9, ... grows at just the right rate that taking the ceiling skips all the numbers ending in 2. Then we get rid of 20 through 29 by `Drop`ping the values at indices 18 through 26.
[Answer]
## [C (GCC)](https://www.gnu.org/software/gcc/), 62 55 Bytes
*• 7 Bytes thanks to Jonathan Frech*
`f(n){for(n=0;++n-101;n/10-2&&n%10-2&&printf("%d,",n));}`
Loops from 1 to 100 and prints the number only if 2 is not in the ones or tens place.
[Try it online!](https://tio.run/##S9ZNT07@/z9NI0@zOi2/SCPP1sBaWztP19DA0DpP39BA10hNLU8VQhcUZeaVpGkoqaboKOnkaWpa1/7PTczM0wDq1ABxAA)
[Answer]
# sh + coreutils, 16 chars
```
seq 100|sed /2/d
```
Generates sequence from 1 to 100 (inclusive) and deletes any lines that have '2' in them.
[Answer]
# [Z80Golf](https://github.com/lynn/z80golf), ~~49~~ 48 bytes
```
00000000: 1630 2e0a 5faf f57b fe02 2818 82ff f182 .0.._..{..(.....
00000010: ff92 3cf5 7dff f1bd 280a fe02 2803 f518 ..<.}...(...(...
00000020: e63c 18fa 7b3c bd20 db3e 31ff 3dff ff76 .<..{<. .>1.=..v
```
[Try it online!](https://tio.run/##Rc6xDsIwDATQna@4sdPJcdQ2oMKvoKaJWZDYGEB8ezBtJW6yrPOTX0luj7u1JntOCEMUaJUZvc0G68cMq6LQFBKSmu9CUoBCXsk32fGXwyYEN8yOirhYj7Gs/Vz83MkdkuiuayAnfrgJ3d9QN@oQF4RkM8bsUy4qKDlWxOBkXF0bBzcmf2IieAk8k8/Wvg "Z80Golf – Try It Online")
Assembly:
```
ld d, 30h ; ascii '0' character
ld l, 0Ah ; number 10 and ascii newline
tens:
ld e,a ; store tens digit
xor a ; reset ones digit to 0
push af ; store initial ones digit 0
ones:
ld a,e ; get stored tens digit
cp 2
jr z,cont ; if tens digit==2(e.g.20-29),skip loop
add d
rst 38h ; print tens digit
pop af ; get stored ones digit
add d
rst 38h ; print ones digit
sub d
inc a ; increment ones digit
push af ; store ones digit
ld a, l
rst 38h ; print newline
pop af ; get stored ones digit again
cp l
jr z,cont ; if ones digit==10, break loop
cp 2
jr z,inc_again ; if ones digit==2, incr again
repeat_loop:
push af ; store ones digit again
jr ones ; repeat print loop
inc_again:
inc a
jr repeat_loop
cont:
ld a,e ; get stored tens digit
inc a ; increment tens digit
cp l
jr nz, tens ; if tens place!=10, continue loop
ld a,31h
rst 38h ; print '1'
dec a
rst 38h ; print '0'
rst 38h ; print '0'
halt
```
Saved one byte with the `repeat_loop` jump
[Answer]
# [Python 3](https://docs.python.org/3/), ~~53 51 50 49~~ 46 bytes
```
['2'in str(n)or print(n)for n in range(1,101)]
```
[Try it online!](https://tio.run/##K6gsycjPM/7/P1rdSD0zT6G4pEgjTzO/SKGgKDOvBMhMA7LzFIAyRYl56akahjqGBoaasf//AwA "Python 3 – Try It Online")
Not the strongest language for this task, but I'm new to golfing.
Thanks to the commenters for their tips!
[Answer]
# [Tcl](http://tcl.tk/), 44 bytes
```
time {if ![regexp 2 [incr i]] {puts $i}} 100
```
[Try it online!](https://tio.run/##K0nO@f@/JDM3VaE6M01BMbooNT21okDBSCE6My@5SCEzNlahuqC0pFhBJbO2VsHQwOD/fwA "Tcl – Try It Online")
---
# [Tcl](http://tcl.tk/), 47 bytes
```
time {if [incr i]%10!=2&$i/10!=2 {puts $i}} 100
```
[Try it online!](https://tio.run/##K0nO@f@/JDM3VaE6M00hOjMvuUghM1bV0EDR1khNJVMfzFCoLigtKVZQyaytVTA0MPj/HwA "Tcl – Try It Online")
##
# [Tcl](http://tcl.tk/), 50 bytes
```
time {if {2 ni [split [incr i] ""]} {puts $i}} 100
```
[Try it online!](https://tio.run/##K0nO@f@/JDM3VaE6M02h2kghL1MhurggJ7NEITozL7lIITNWQUkptlahuqC0pFhBJbO2VsHQwOD/fwA "Tcl – Try It Online")
[Answer]
# [Kotlin](https://kotlinlang.org), 32 bytes
```
{(1..100).filter{'2' !in ""+it}}
```
[Try it online!](https://tio.run/##FcxBCsIwEEbhfU/x200niKF1WWrApeDOE2RhymAcSzoKEnL2WN/@e4@XRpYa3oKnZyGf5nXEOSX/nW6aWGZnkBtsfXxEGEEGB4crrzpdRB1ONdNg7dD3xgaOek@5O3bYsaBt96yl1L9etpdSIGOaUn8 "Kotlin – Try It Online")
[Answer]
# [Bash](https://www.gnu.org/software/bash/), 31 bytes
```
printf %d\\n {1..100}|grep -v 2
```
[Try it online!](https://tio.run/##S0oszvj/v6AoM68kTUE1JSYmT6HaUE/P0MCgtia9KLVAQbdMwej/fwA "Bash – Try It Online")
Thanks to Digital Trauma for short loop.
[Answer]
# [ORK](https://github.com/TryItOnline/ork), 1092 bytes
```
There is such a thing as a t
A t can w a number
A t can d a number
A t has a t which is a number
When a t is to w a number:
I have a mathematician called M
M's first operand is the number
M's second operand is 1
M is to add
The number is M's result
My t is 0
I have a number called n
n is the number
I am to d n
M's first operand is my t
M's second operand is 1
M is to compare
I have a scribe called W
If M says it's less then W is to write the number
If M says it's less then W is to write " "
M's first operand is the number
M's second operand is 100
M is to compare
If M says it's less then I am to loop
When a t is to d a number:
I have a mathematician called M
M's first operand is the number
M's second operand is 10
M is to modulo
I have a mathematician called N
N's first operand is M's result
N's second operand is 2
N is to compare
If N says it's equal then my t is 1
M is to divide
The number is M's result
M's first operand is the number
M's second operand is 0
M is to compare
If M says it's greater then I am to loop
When this program starts:
I have a t called T
T is to w 0
```
[Try it online!](https://tio.run/##tVM9b8IwEN39K04sXdOO3ToyJFMkZmMf2Ko/Up8D4tenF0hIKFAqpC5Rcs/33su7c0yfXVcbTAiWgFplQEI2NmxBUv8qPiCDkgH2/BVav8Z0LunLkjl1wN5YprE0oWJlMBwxruY443oXS@7bIRe8zAb5YZVlbiWdQw2lKF8INjZRhthgkkEfOQyO3D1OqCIDswOvohy0pNaiPh/vi31HQmpdFuXh5KmYbAznBv0gwg@9JUjf8/bYTW@eOR@6UtE3MuEkSyrZNY6yK7HcQAkkDwQ2M5dDOroIsBozTDbjhbG/dSxg8WymRXHt/57oGJOLsbmav/7/@U9WfdStiw90KlHd0pmtSnVT501U14lUs0Twq5XuFIkflm3aAm13VuMv6/nUvz@c0jahzCx2b1B8/wmaFLeJIcoyZZrNKY@Z1aI@3@ei674B "ORK – Try It Online")
**O**bjects **R** **K**ool. Output is a space-delimited list of numbers.
This translates (approximately) to the following pseudocode:
```
class t {
int t;
void w(number) {
label T_W;
mathematician M;
M.first_operand = number;
M.second_operand = 1;
M.add();
number = M.result;
t = 0;
int n = number;
d(n);
M.first_operand = t;
M.second_operand = 1;
M.compare();
scribe W;
if M.its_less { W.write(number); }
if M.its_less { W.write(" "); }
M.first_operand = number;
M.second_operand = 100;
M.compare();
if M.its_less { goto T_W; }
}
void d(number) {
label T_D;
mathematician M;
M.first_operand = number;
M.second_operand = 10;
M.modulo();
mathematician N;
N.first_operand = M.result;
N.second_operand = 2;
N.compare();
if N.its_equal { t = 1; }
M.divide();
number = M.result;
M.first_operand = number;
M.second_operand = 0;
M.compare();
if M.its_greater { goto T_D; }
}
}
void main() {
t T;
T.w(0);
}
```
As you can see, *everything* is done using objects, including basic math and IO functions (through the built-in mathematician and scribe classes). Only whole functions can loop, which explains the need for an object with two functions to do the work.
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf), ~~7~~ 6 bytes
```
♀╒Ç{2╧
```
[Try it online!](https://tio.run/##y00syUjPz0n7///RzIZHUycdbq82ejR1@f//AA "MathGolf – Try It Online")
## Explanation
```
♀╒ Push 100 and convert to 1-based range ([1,2,...,100])
Č{ Inverse filter by block
2‚ïß Does the number contain 2?
```
[Answer]
# [C (clang)](http://clang.llvm.org/), 56 bytes
```
f(i){for(i=0;i++<100;i%10^2&&i/10^2&&printf("%d\n",i));}
```
[Try it online!](https://tio.run/##S9ZNzknMS///P00jU7M6Lb9II9PWwDpTW9vG0ABIqxoaxBmpqWXqQ@iCosy8kjQNJdWUmDwlnUxNTeva/0ARhdzEzDwNoHYNTeui1JLSojwFA6AMAA "C (clang) – Try It Online")
[Answer]
# PHP 7.1, 40 bytes
```
while($i++<100)strstr($i,50)||print$i._;
```
prints numbers separated by underscores. Run with `-nr` or [try it online](http://sandbox.onlinephpfunctions.com/code/21335cb48b903f157762c893119666dc11c43d15).
[Answer]
# [Red](http://www.red-lang.org), 44 bytes
```
repeat n 100[unless find form n"2"[print n]]
```
[Try it online!](https://tio.run/##K0pN@R@UmhId@78otSA1sUQhT8HQwCC6NC8ntbhYIS0zL0UhLb8oVyFPyUgpuqAoMw@oIjb2/38A "Red – Try It Online")
Uses `unless` instead of `if not`, because why not? :)
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), 176 bytes
```
---------[[-<]-[>]>[>]-[-<]<++]-[>-<+++++++++]>--[>[->]<[<<<]>>[->]>-]<<,<-[-<]>[>]<[.[->+<]++++++++++.,<]>>[>]>>->-<<<<[>>>[<<[<]<.>>[>]>.[-<+>]++++++++++.,>]<<[<]<,<]>>>>.<..
```
[Try it online!](https://tio.run/##VY1bCsRQCEMXZHUFIRsRP9qBgTIwH4Wu/zbXeUAD4itHt2Pd38/z8RrDf8p0lCeLCp8NzObAlb8qysd0FhJAsWt6AQuamTAyNDbUn7NY2iwvXQelpHolvYnPRhCMN0i32tE0GYgY4wI "brainfuck – Try It Online")
Shorter is definitely possible. This generates the numbers `1,3,4,5,6,7,8,9` and `0,1,3,4,5,6,7,8,9`. First it outputs each number in the first list, then it outputs every combination of the first and second list, then finally prints just `100`.
### Explanation:
```
--------- Push minus 9
[ Repeat 9 times
[-<]-[>] Add the negative of the number to the first list
>[>]-[-<]< Add the negative of the number to the second list
++ Increment the counter
]
Tape: 255 254 253 252 251 250 249 248 247 0' 0 246 247 248 249 250 251 252 253 254
-[>-<+++++++++]>-- Push 197
Tape: 255 254 253 252 251 250 249 248 247 0 197' 246 247 248 249 250 251 252 253 254
[
>[->]< Subtract 197 from every element in both lists to convert to digits
[<<<]>>
[->]>-
]
Tape: 58 57 56 55 54 53 52 51 49 0' 49 50 51 52 53 54 55 56 57
<<,<-[-<]>[>]< Remove the 0 and the 2 from the first list
Tape: 58 57 56 55 54 53 52 51 0 0 0' 49 50 51 52 53 54 55 56 57
[ Loop over the first list
.[->+<] Print digit
++++++++++.,< Print a newline
]
>>[>]>>->- Remove the 2 from the second list
<<<<
[ Loop over first list
>>>
[ Loop over second list
<<[<]<. Print first digit
>>[>]>. Print second digit
[-<+>] Move second digit over one
++++++++++.,> Print a newline
]
<<[<]<,< Remove the digit from the first list and move to the next
]
>>>>.<.. Print 100 using the second list
```
[Answer]
# [SimpleTemplate](https://github.com/ismael-miguel/SimpleTemplate), 51 bytes
This was a fun challenge!
And it is a challenge where my language can do well.
```
{@forfrom 1to100}{@if_ is notmatches"<2>"}{@echol_}
```
Cycles through all values from 1 to 100, outputting the ones that don't have 2, separated by a newline.
You can try it on <http://sandbox.onlinephpfunctions.com/code/2c97a2b6954c29844f1079938da771d51e2e0d99>
**Ungolfed:**
```
{@for i from 1 to 100}
{@if i is not matches "<2>"}
{@echo i, "\n"}
{@/}
{@/}
```
The `{@/}` is used to close the `{@for ...}` and `{@if ...}`, but is optional.
When compiling to PHP, it adds the needed closing.
---
If you're curious, the golfed code results in this PHP code:
```
// {@forfrom 1to100}
// ~ optimization enabled ~ inlining the results
foreach(array(...) as $DATA['_']){
// {@if_ is notmatches"<2>"}
if(!(preg_match("<2>", (isset($DATA['_'])?$DATA['_']:null)))) {
// {@echol_}
echo implode('', $FN['array_flat']((isset($DATA['_'])?$DATA['_']:null)));echo PHP_EOL;
// AUTO-CLOSE
};};
```
Where `$FN['array_flat']` is defined outside of this code.
] |
[Question]
[
Your challenge is to take an array of strings and output the longest string in the array. So for
```
["tiny", "small", "bigger", "biggest"]
```
the output would be `biggest`.
If two elements of the array have the same length, you should choose the one that appears first in the array. That means if the array looks like this:
```
["one", "two", "no"]
```
the output is `one`, but if the array looked like this:
```
["two", "one", "no"]
```
the output is `two`.
---
As this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest code in bytes wins.
[Answer]
# [Imperative Tampio](https://github.com/fergusq/tampio), 168 bytes
```
Listan x on riippuen siitä,onko sen ensimmäisen alkion pituus suurempi tai yhtä suuri kuin sen jokaisen alkion pituus,joko sen ensimmäinen alkio tai sen hännän x.
```
[Online version](http://iikka.kapsi.fi/tampio/pisin-golf.html)
Ungolfed:
>
> Listan pisin alkio **on** **riippuen** **siitä**, **onko** sen `ensimmäisen` alkion pituus **suurempi** **tai** **yhtä** **suuri** **kuin** sen **jokaisen** alkion pituus, **joko**
>
>
> * sen `ensimmäinen` alkio **tai**
> * sen hännän pisin alkio.
>
>
>
[Online version](http://iikka.kapsi.fi/tampio/pisin.html)
The only golfing opportunity this has is to replace `pisin alkio` (meaning "the longest element") with `x`.
Translation:
>
> The longest item in a list is, depending on whether the length of the first item is greater or equal to the length of each element in the list, either
>
>
> * the first item in the list, or
> * the longest item in the tail of the list.
>
>
>
[Answer]
# [Python](https://docs.python.org/), 23 bytes
```
lambda a:max(a,key=len)
```
[Try it online!](https://tio.run/##xVRNk5swDL33V2RyIZnJaY@d2V/S9CBAAS/G8vgjlP751LYEgc3O9NTpBQF@enqWnm3n0JN5e9zerw8NY93CAb6P8OsElwHnd43m/LBOmXC6nX4csY3ueDkShfQM0Ifjz/P527pe5fXqcqgSIIeMyNEr@ZpyRKtsjo4CqBZKAuRHH1QBRJpzGJp4y1Fr/l1IWiNQxELtBBwicQ6MPr8YaNacjtovaDFArTQWGDrYIBbZ6GLhwgHGlUwwi1Y0TB6wWyEGeaOBqxvlAPv8OsKK8R528rEubD6ybhwldVVb1sO1knrkuULvP9VgYKlBv1Xf@LW947VS2@1NZIbtrlG/dNso6KTfkYok5Fyj/jaooaGyk07VLwMG14G685iYz2HrgPVPW42GVDDcDLEUmepwqfCucRKPlXZqDaWON9yZpbGvBVKvrCXHUwPpey/k3VOCdJh/JaDfbv8pr/dRLETLzPqEdoXXkr59UWcxlGhMKEbjDuWVoP2SpjsDLvhnN1Kx2bF0Hz8@W8zh6p7/SKHTsXdgdhxyin06rrUdY5mLRy0XhMPkpEESDFj42PVOaSmqFUyc2TeBbTZ7H@2ulAxQ7VyCnQO9gxkS0uDxzu42pBMxsiJr41bEyKfQkXN8D8kCLcuNZhfxPrNdveMrSm4KRs51TfolnyUnsSVZDuY/gKbL@/EH "Python 2 – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 35 bytes
*-3 bytes thanks to Zgarb.*
```
foldl1(!)
a!b|(a<$a)<(a<$b)=b|1<2=a
```
[Try it online!](https://tio.run/##FcUxEkAwEADA3itOJoXMUFAnL0FxIcE4kiE6b3dodmc8V0fE3nTsA41UF7nKMLd3gVqi0n9WGXvXujHIGy47GIjHsieQ4KEVbrwOUYoQ0mfCOYmen8ETTidXQ4wv "Haskell – Try It Online")
I like this code. You know why? Because Haskell supports much more elegant solutions with functions from random libraries.
```
maximumBy(compare`on`length).reverse
```
That's friggin' readable! Except, it's not valid.
```
import Data.List
import Data.Function
maximumBy(compare`on`length).reverse
```
If it weren't for the imports, this would've been a perfect submission to get all the upvotes. :P
(Also, this uses one golfing tip *and* it uses a fold.)
[Answer]
# [R + pryr](https://cran.r-project.org/web/packages/pryr/index.html), 31 bytes
[-2 bytes thanks to Scrooble]
```
pryr::f(x[order(-nchar(x))][1])
```
[Try it online!](https://tio.run/##fVLBbsIwDL3vKxAXWqk77IrElyA0mdRtItq4chIK@/kuTkIZHHZoHcXPz8/P4QU2h42qttgG3jZbIh//HrQEZ/J5jgEnM8XA5MG0IFCIn/ZGkoHu8X9RoYthGNKd1LY2gxCFjjPMB0pgGF2MFlQBNz2171zo4WwGFAgyrNmiDzkIBV5gLBw5XVShTYQe@5K1mEbxcu6tYUAdTyOUtHPwRyWehcKFpK/BMdc8dEnS73IDcolUuxdar40zzmtUxIzKU/BT8I9a6Uc/RitXnBx35jnYTPbyHBaHV1etgT77GkhkYaqx5p9FXBTJGL05vy4OuAdzTWtIJKvomcn2WfL3t7iCLYOMhfNTpiXjbXImvxqyyarrgHN@RWLqMIA0dTbZVNwt7VbWaNs0Ead1QXY@66H@0TOVN/kiYtxz8FWMdiG/FCrb0hHIwjbR0L1zl2eTBTURkYC4IuqP7rBMfOf9vqtux6gOufq0SgNXt7o@Hb9O9aLAV10Fdb38Ag "R – Try It Online")
---
# [R](https://www.r-project.org/), 33 bytes
```
function(x)x[order(-nchar(x))][1]
```
[Try it online!](https://tio.run/##vVRBctswDLz3FRlfYs@ohz4gL8nkAEmQyJgiNCBpx/28CwJ0LPvQU6cHizK5WCyWgPgKL28vw36HY@FdtyPK8szg6pK8vZ9lwdWvsjBl8CNUKMjPZV8PC13keRzKJEsIuldjx2ggxErHBsuFFAxLkjXC0MDdTOMzF2bofcAKQYbv06YPuVQKPMLSOOy4qcKohBnndhpRS8n1fY6eAZ28LdCOU4KNSuwrRSqqr8PFYm666mF@tQSUlNSlB1qFVFr67d2QmmHLq7/rP1M83mvC8Ghe9DCbfYVqdtSY6P/i93Ggqnb2/eP9AM/gT@q2kjCODCryfFcTyeeodVoPUNTCTwHP1hPVohCgcqeoRTevnlnFhHUlVvPBfHRGOd9yanhnG4JJ9/q@xbhU7N6pee8EyJVtpTA9c7cmMEGdIBSIG0TyBkwtIMwROKdbvZLgwqoylc@HtmC83fr/DA0ydwxxE2vT1CUZnX5ditM/GGw@GaUPjoaOsMLnxhkfLFPwUKFCN2RtkUtKZd1ksPvwm4vGmSFsEJGMKic8aStGCkKHqmBdyz3rorPBxKzDb7vUjoagXaAtVTsssX4UbFQVdOl7Co9xKk501SCbln8FOvyY3q5TiWILxf3X4etduhd5/zMODlg2Dh/vvz6uA@T9tIfD4foH "R – Try It Online")
[Answer]
# EXCEL, ~~36~~ 42 bytes
```
=INDEX(A:A,MATCH(MAX(LEN(A:A)),LEN(A:A),))
```
Entered as an array formula (ctrl-shift-enter). The input array should be entered in column A.
The formula returns the first match with maximum length.
Depending on your region settings, substitute `,` with `;`; the code length remains unchanged.
Of the 16 languages listed [here](http://dolf.trieschnigg.nl/excel/index.php), English function names are the shortest for this formula.
Explanation:
```
= - return
INDEX( ) - the item of
A:A - the input
, - at
MATCH( ) - the position of
, - the first exact match of
MAX( ) - the maximum of
LEN( ) - the array of lengths of
A:A - the input
, - in
LEN( ) - the array of lengths of
A:A - the input
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 9 bytesSBCS
```
⊢⊃⍨∘⊃∘⍒≢¨
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24RHXYsedTU/6l3xqGMGiAEkeyc96lx0aAVQXkG9JDOvUl1BvTg3MScHSCdlpqenFgEZOfl56anFJeoA "APL (Dyalog Unicode) – Try It Online")
`⊢` from the argument,
`⊃⍨` pick the element with the index which is the
`⊃` first of the
`⍒` indices in descending order of the
`≢¨` lengths of each
[Answer]
# [Prolog (SWI)](http://www.swi-prolog.org), ~~98~~ ~~92~~ ~~72~~ 69 bytes
The top level predicate is `*`.
```
X/Y:-atom_length(X,Y).
[A]*A.
[A,B|L]*Z:-A/X,B/Y,Y>X,[B|L]*Z;[A|L]*Z.
```
[Try it online!](https://tio.run/##KyjKz8lP1y0uz/z/P0I/0ko3sSQ/Nz4nNS@9JEMjQidSU48r2jFWyxFE6TjV@MRqRVnpOupH6DjpR@pE2kXoREMEraMdwbTe///Riek6hSmlRTr5@SU6JYkZJbFaEXoA "Prolog (SWI) – Try It Online")
**Explanation**
The first row defines the dyadic predicate `/` to be a short for `atom_length/2`which is true if the first argument's length is the second argument. This saves us 3 bytes over using `atom_length` twice.
Our main predicate is defined as the dyadic `*` where the first argument is a list and the second argument the longest element of that list.
The second row is our base case which states that the longest element of a one element list is that element.
The third row states that for a list with at least 2 elements, the longest element is:
If the length of the second element is longer than the first element, the longest element is in the list without the first element.
Otherwise the longest element is in the list without the second element.
[Answer]
# [Pyth](https://pyth.readthedocs.io), 4 bytes
```
h.Ml
```
**[Test suite.](https://pyth.herokuapp.com/?code=h.Ml&test_suite=1&test_suite_input=%5B%22tiny%22%2C+%22small%22%2C+%22bigger%22%2C+%22longest%22%5D%0A%5B%22edur%22%2C%22oot%22%2C%22taht%22%5D&debug=0)**
Explanation
```
h.Ml | Program
h.MlZQ | With implicit variables filled in
-------+--------------------------------------------------------------------
h | First element of
.M Q | The list of elements from the input list with the maximal value for
lZ | The length of the element
```
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 24 bytes
```
($args[0]|sort l* -d)[0]
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/X0MlsSi9ONogtqY4v6hEIUdLQTdFE8j9//@/g4ZSUmZ6empxiZKOglJJZl4liC7OTczJATHAckUgVk5@HkxVYk5xfk5eupImAA "PowerShell – Try It Online")
Takes input `$args[0]`, pipes that to `Sort-Object` based on `l`ength in `-d`escending order. Then takes the `[0]`th one thereof. Since sort is stable, this takes the first element in case of a tie.
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 33 bytes
```
@(x)x{[~,p]=max(cellfun(@nnz,x))}
```
Input is a cell array of strings.
[**Try it online!**](https://tio.run/##y08uSSxL/Z9mq6en999Bo0Kzojq6Tqcg1jY3sUIjOTUnJ600T8MhL69Kp0JTs/Z/mka1UklmXqWSjoJScW5iTg6IkZSZnp5aBGLl5OelpxaXKNVqcoFUpqaUAoWV8vNLgGRJYgZI4j8A "Octave – Try It Online")
### Explanation
`cellfun(@nnz,x)` applies the `nnz` function (number of nonzeros) to each string in the input array `x`. For ASCII strings, `nnz` is equivalent to `numel` (number of elements), but shorter. The result is a numeric array with the string lengths.
Then, `[~,]=max(...)` gives the index of the first maximum in the array of string lengths. The result is used as a curly-brace index into `x` to obtain the corresponding string.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org/en/), 38 bytes
[Try it online!](https://tio.run/##LcdNCoAgEEDhq7RTwaQDZBeJFqON/SBO6FTHN4Q2j/ed8EDx@bi4T7RijchdsBXsBKZQZilBO9UUMW28j@4fNQ9L9ZQKRTSRNhnkLCih0IJfat0zNgW6s1iUqh8)
```
a=>a.sort((a,b)=>a.length<b.length)[0]
```
[Answer]
# [J](http://jsoftware.com/), 19, 11, 10 8 bytes
```
0{>\:#@>
```
[Try it online!](https://tio.run/##vVTLjtswDLznK4z2IBRYLPbRXmLsYj@kF9pmbCWyZOgRIy367SlFKrGTw56KHmQJ4nA4pEjvz/3btnqqaJ2ffr//3H79eD9/23x5rNTu7VFVD9WfbdVvNtgOrtpVCpq2U7V6ef3@g7ZnWjP6OMzB0xGW4/PLq7o6YZfynXORvhGG@JmpVkHLeaYNJz3R5l0E3QEHoTVEnY3Jneh7aNOONmP4Lvt2VkCImc4LLCbHYBgD7RbaAq57191zYYRGG8wQ9HC1Fn3oU6bAA4yFQ8xFFVomjNgXq0VOJeZzb7UHHOg0QjGHACuV2GSKkFhfjaP4XHRlY1RKIrjArEO44WVM5nW/9NCGUrFRKb1kMDt7WLJCc1s@q6GXAiaX4yP7WP1JxQ@ty3p73dy@EPge9JHrzSQeOw@scl7UWKej5UylC5zl1I8GZ@mKXCRjIHMHy1mXat2zUhWmyXkuP0glB6HsLzHZvZYLwoQlv6uYISR5eVeqPxDQZ7bJmd09d2kDEVQTgoG4QgQtwFAcTG/Bx3DJlwKcPKsMaX/TGB4v7/4/XQ1Nnge78pV5egg0PM00plzpOqCRCfVIfXAQtIUJ9qvKaCORjIYMJbo2coucQkjTKoK8h149NPYezAphnVDFgEduResM0SErmKa0RB15OLzznsdfbl0xtYa7gFsqd1jw/FuQYWXQqWmcufVjcaQrO8m0/CvQ5vwX "J – Try It Online")
Thanks to streetster for the hint!
-1 byte thanks to FrownyFrog!
-2 bytes thanks to Conor O'Brien
## How it works:
```
( #@>) - unbox each string and find its length
\: - sort down the list of strings according to the lengths
0{:: - take and unbox the first string
```
[Try it online!](https://tio.run/##vVTLjtswDLznK4z2oC6wWOyjvcTYoh/SC20zthJZMvSIkRb99pQildjJYU9FD7IEcTgcUqT35/59Wz1XtM7Pv7fbLz@3n398fzg/bD49VWr3/qSqx@rPtuo3G2wHV@0qBU3bqVq9vn39RtsLrRl9HObg6QjL8eX1TV2dsEv5zrlI3whD/MhUq6DlPNOGk55o8y6C7oCD0BqizsbkTvQ9tGlHmzF8l307KyDETOcFFpNjMIyBdgttAde96@65MEKjDWYIerhaiz70KVPgAcbCIeaiCi0TRuyL1SKnEvO5t9oDDnQaoZhDgJVKbDJFSKyvxlF8LrqyMSolEVxg1iHc8DIm87pfemhDqdiolF4ymJ09LFmhuS2f1dBLAZPL8ZF9rP6g4ofWZb29bm5fCHwP@sj1ZhKPnQdWOS9qrNPRcqbSBc5y6keDs3RFLpIxkLmD5axLte5ZqQrT5DyXH6SSg1D2l5jsXssFYcKS31XMEJK8vCvVHwjoM9vkzO6eu7SBCKoJwUBcIYIWYCgOprfgY7jkSwFOnlWGtL9pDI@Xd/@froYmz4Nd@co8PQYanmYaU650HdDIhHqkPjgI2sIE@1VltJFIRkOGEl0buUVOIaRpFUHeQ68eGnsPZoWwTqhiwCO3onWG6JAVTFNaoo48HN55z@Mvt66YWsNdwC2VOyx4/i3IsDLo1DTO3PqxONKVnWRa/hVoc/4L "J – Try It Online")
[Answer]
# C#, 43 + 18 = 61 bytes
[Try it online!](https://tio.run/##TY7BCsIwEETv@YqlpwQ0P1Dbg4onRcGDB/EQ0lUDdYPZ1Fak315jRXAuuzMDb9fy1PqAQ8OOLrB/csRbLv6dXju650LY2jDDTrwEJHE00Vl4eFfBxjiSaoy/5UerhuyMY0ig42kC362Ec4qhgMEUpdHbUGGYP5fIFqlKveyKstNrpEu8Kr1ygaNUQzr@oy48sa9RH4KLmB5D@QFKwvZ4ghdknjCbQBZbP45rGO3ZNyGDXql8BPWiF8Mb)
```
a=>a.OrderByDescending(x=>x.Length).First()
```
[Answer]
# [Perl 6](https://perl6.org), ~~14~~ 13 bytes
```
*.max(*.chars)
```
[Try it](https://tio.run/##K0gtyjH7X1qcqlBmppdszZVbqaCWk5@XnlpcolueX5SiYPtfSy83sUJDSy85I7GoWPO/NVdxYqUCippopZLMvEolHQWl4tzEnBwQIykzPT21CMSCqlSKxaoxNaUUqEopP78ESJYkZoDU/QcA "Perl 6 – Try It Online")
```
*.max(&chars)
```
[Try it](https://tio.run/##K0gtyjH7X1qcqlBmppdszZVbqaCWk5@XnlpcolueX5SiYPtfSy83sUJDLTkjsahY8781V3FipQKKkmilksy8SiUdBaXi3MScHBAjKTM9PbUIxIKqVIrFqjE1pRSoSik/vwRIliRmgNT9BwA "Perl 6 – Try It Online")
[Answer]
# PHP, 72 bytes
```
array_reduce($a,function($c,$i){return (strlen($i)>strlen($c))?$i:$c;});
```
[Answer]
# Japt `-h`, ~~5~~ 3 bytes
```
ÔñÊ
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=1PHK&input=WyJlZHVyIiwib290IiwidGFodCJdCi1o)
Reverse, sort by length and output the last element.
[Answer]
# [Swift](https://swift.org), 54 bytes
```
{($0 as[String]).reduce(""){$1.count>$0.count ?$1:$0}}
```
[Try it online!](https://tio.run/##Ky7PTCsx@V@WWKSQpmD7v1pDxUAhsTg6uKQoMy89VlOvKDWlNDlVQ0lJs1rFUC85vzSvxE7FAMJQsFcxtFIxqK39XwBUXaKRphGtBFRepKSjlJ9fAiRLEjNKlGI1Nf8DAA)
[Answer]
# [K (oK)](https://github.com/JohnEarnest/ok), 9 bytes
```
*x@>#:'x:
```
[Try it online!](https://tio.run/##y9bNz/7/X6vCwU7ZSr3CSkMpIzUnJ1/JWqkkI7UoFUgn56eAqPT8nLTUomIgqzw1Jzk/FyRWAlKXWwkkEvOKy1OLlDT//wcA "K (oK) – Try It Online")
**Example:**
```
*x@>#:'x:("edur";"oot";"taht")
"edur"
```
**Explanation**
```
*x@>#:'x: / solution
x: / store input in variable x
#:' / count (#:) each (')
> / sort descending
x@ / apply indices to x
* / take the first one
```
**Notes:**
Undeleted as this is classed as non-trivial, despite being basically 5 steps (would be if written as the function `{*x@>#:'x}`).
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), 67 bytes
Another submission in my favourite language! (read: the only one I know).
This doesn't work with an empty array, but that's fine.
Golfed
```
w->{for(String y:w)if(y.length()>w[0].length())w[0]=y;return w[0];}
```
Ungolfed
```
for(String y:w) // Loops through all Strings
if(y.length()>w[0].length()) // If the String is longer than the first String
w[0]=y; // Store it as the first string.
return w[0]; // Return the first String.
```
[Try it online!](https://tio.run/##RY2xDsIgEEBn@IqLEySVONvoH@jiaBywpYgiNHC1aZp@O0LUON295O69u3zJte@Vu7eP1FgZIxykcTMlxqEKnWwUHGcKhJwwGKdBs89yvsDIa0oWSkk/XK1pIKLEPF7etPDMkv@l5FlI/hh0hB3I8@YiYm8NslW1KjJymiKqp/ADij4fo3XMCc3KA//VvpkjuOxI43o/dz58WzBtR246NgmrnMYb4/uxVH7EC@2mOigcgoNC9ZJITZeUVDuEynusUN7wDQ "Java (OpenJDK 8) – Try It Online")
[Answer]
# [Racket](https://racket-lang.org/), 160 bytes 110 bytes
[Try it online!](https://tio.run/##K0pMzk4t@f9fOScxL12hCMzj4tJISU3LzEvVyFVI1NTITNOw08hJzUsvyQByDSECthrFJUWZeem6EAmN5MQioKQmmmiuRnIKWBwoA1GBJATTowm0L1dBXUPJPy9VSUEppDwfSLrllxaBqMyyVCWgCriCVMJKsCkoBqr4/x8A "Racket – Try It Online")
First time contributing, advice appreciated!
```
(define(m a)(if(>(length a)1)(if(>=(string-length(car a))(string-length(m(cdr a))))(car a)(m(cdr a)))(car a)))
```
**Ungolfed**
```
(define (m a)
(if (> (length a) 1)
(if (>= (string-length (car a)) (string-length (m (cdr a))))
(car a)
(m (cdr a))
)
(car a)
)
)
```
Updated solution based on feedback
[Answer]
# [Bash](https://www.gnu.org/software/bash/), 45 bytes
```
a=;for b;do((${#b}>${#a}))&&a=$b;done;echo $a
```
[Try it online!](https://tio.run/##S0oszvj/P9HWOi2/SCHJOiVfQ0OlWjmp1g5IJtZqaqqpJdqqgMTzUq1TkzPyFVQS////X5KZV/m/ODcxJ@d/UmZ6emoRhCouAQA "Bash – Try It Online")
[Answer]
# [Scratch](https://scratch.mit.edu) 27 17 170 160
[](https://i.stack.imgur.com/PrL1n.png)
It expects a global (attached to all sprites, to be more precise) list of strings called `mylist`. After clicking the green flag, the longest word will be left in the variable `w`.
I think [this is the link](https://scratch.mit.edu/projects/195018504/)
```
when gf clicked
set[w]to(item[1]of[mylist
set[i]to[0
repeat(length of[mylist
change[i]by(1
set[m]to(item(i)of[mylist
if<(m)>(w)>then
set[w]to(m
end
end
stop[all
```
Counting as per [this meta.](https://codegolf.meta.stackexchange.com/questions/673/golfing-in-scratch/5013#5013)
[Answer]
# [Röda](https://github.com/fergusq/roda), 30 bytes
```
{enum|[[#_,-_,_1]]|max|_|tail}
```
[Try it online!](https://tio.run/##K8pPSfyf9r86Na80tyY6WjleRzdeJ94wNrYmN7GiJr6mJDEzp/Z/bmJmnkI1F2e0UmpKaZGSjlJ@fgmQLEnMKFGKVahRSOOq/Q8A "Röda – Try It Online")
Explanation:
```
{
enum| /* For each element, push its index to the stream */
[[#_,-_,_1]]| /* For each element and index, push [length, -index, element] */
max| /* Find the greatest element */
_| /* Flat the list in the stream */
tail /* Return the last item in the stream */
}
```
Alternative 30 bytes:
```
{enum|[[#_,-_,_1]]|max|[_[2]]}
```
[Try it online!](https://tio.run/##K8pPSfyf9r86Na80tyY6WjleRzdeJ94wNrYmN7GiJjo@2ig2tvZ/bmJmnkI1F2e0UmpKaZGSjlJ@fgmQLEnMKFGKVahRSOOq/Q8A "Röda – Try It Online")
[Answer]
# APL -- ~~23~~ 16 bytes
~~`a←{((⍴¨⍵)⍳(⌈/(⍴¨⍵)))⌷⍵}`~~
Thanks to everyone for all of your great suggestions and encouragement!
```
a←{⍵⌷⍨(⍴¨⍵)⍳⌈/⍴¨⍵}
```
### Usage:
```
a 'duck' 'duck' 'goose'
'goose'
```
### Explanation:
gets length of each vector of characters (string) then uses maximum as an index. I just started APL 20 min ago so I am sorry if this is a stupid way to do it.
[Try it Online!](http://tryapl.org/)
*(edited for clarity)*
[Answer]
# [Standard ML (MLton)](http://www.mlton.org/), 55 bytes
```
fun&(s::r)=foldl(fn(%,$)=>if size% >size$then%else$)s r
```
[Try it online!](https://tio.run/##FcVRCoUgEADAqyyioVAXCOwij0cErSRsa7hbH13e6mdGdhp20sKtpZM7L@NYQ0yFVvKJvettiFNOIPlGB9OX1Q3ZIQnaIFDbtRDMEOGomRV8Bz@D61lNb0rRV102Nf/QHg "Standard ML (MLton) – Try It Online") Example usage: `& ["abc","de","fgh"]` yields `"abc"`.
### Ungolfed:
```
fun step (current, longest) =
if size current > size longest
then current
else longest
fun longestString (start :: list) = foldl step start list
| longestString nil = raise Empty
```
[Try it online!](https://tio.run/##XY5BCsJADEX3PUWYVQv1AgXdeQKXIjLYtB1IM2UmLSjefUydUtAsAvn/JT9xpMNI4jmlbmaIghOUjzkEZKmBPPcYpYIjFKDlOojuhbABcMrjhmVGBuQd@CpIcWeKYo3ZhosExz2UUWwQaBogl8M6Ty3lZ7K3Gnrr/bfJjpQO1mnAeZzkmRZLcFdtUl@g/MWvBts5mNp4L9rFDmJuVfoA "Standard ML (MLton) – Try It Online")
[Answer]
# [Julia 0.6](http://julialang.org/), 24 bytes
```
!s=s[indmax(length.(s))]
```
[Try it online!](https://tio.run/##TcaxCoAgEADQX0knhQhqaOtLxMFI7OK8wrugvt5w603vuBHCXKvihR3QlsNjMFKSfTBsra9XARIko5wWoFf3neYcEFtWSCmWNjwpRZbx90l7Wz8 "Julia 0.6 – Try It Online")
[Answer]
# [Funky](https://github.com/TehFlaminTaco/Funky), 38 bytes
```
a=>a[(v=a::map@#)::find(math.max...v)]
```
## Explained
```
a=>a[(v=a::map@#)::find(math.max...v)]
a::map@# $ Create a list of the lengths of the input's strings.
v= $ And assign it to v.
( )::find( ) $ Find the first index in this list that equals...
math.max...v $ The largest value of v, eg. the length of the longest string.
a[ ] $ Get the value at that position.
```
[Try it online!](https://tio.run/##SyvNy678n2b7P9HWLjFao8w20coqN7HAQVnTyiotMy9FIzexJEMvN7FCT0@vTDP2f0FRZl6JRppGtVJiUrKSjlJKalo6kDIE4oz8vGylWk3N/wA "Funky – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~21~~ 20 bytes
```
->s{s.max_by &:size}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1664ulgvN7EiPqlSQc2qOLMqtfZ/QWlJsUJadLRSfl6qko5SSXk@iMwoSk1Vio3lgsuW5oHEU/KLQbJFqcUokqmZeSDxqvLUTJCiIiAVG/sfAA "Ruby – Try It Online")
Trivial solution, thanks Snack for -1 byte
[Answer]
# Perl, 24 bytes
Includes `+1` for `p`
Give words as lines on STDIN
```
perl -pe '$;[y///c]//=$_}{$_=pop@'
one
two
no
^D
```
[Answer]
# [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), ~~63~~ 57 bytes
```
I M =LT(SIZE(M),SIZE(X)) X
X =INPUT :S(I)
OUTPUT =M
END
```
[Try it online!](https://tio.run/##K87LT8rPMfn/35PTV8HWJ0Qj2DPKVcNXUwdMR2hqKkRwcUYo2Hr6BYSGcFoFa3hqcnH6h4YAeQq2vlyufi7//5eU53Pl56Vy5eUDAA "SNOBOL4 (CSNOBOL4) – Try It Online")
Input is on stdin and output on stdout.
Roughly translates to the following pseudocode:
```
while input exists
x = input
if length(m) < length(x)
m = x
end
return m
```
] |
[Question]
[
Write a program which finds the non-unique elements of an array of signed integers. The resulting array can be in any order.
Your answer may be a snippet which assumes the input to be stored in a variable (`d`, say) and evaluates to the correct result.
### Test Cases
Each test case is a single line in the format `input => output`. Note that other permutations of the output are valid as well.
```
[] => []
[-1, 0, 1] => []
[1, 1] => [1]
[3, 0, 0, 1, 1, 0, 5, 3] => [3, 0, 1]
[-34, 0, 1, -34, 4, 8, 4] => [-34, 4]
```
Order of the elements doesn't matter.
This is code golf, so the shortest answer (in bytes) wins.
[Answer]
# [K5](http://johnearnest.github.io/ok/index.html), 5 bytes
Assuming the input is already in a variable called `d`,
```
?d^?d
```
Take the distinct elements (`?`) of d except (`d^`) the distinct elements of d (`?d`). Nicely symmetrical, no? This works because the "except" operator removes only the first occurrence of the right argument from the left argument.
More generally,
```
nu: {?x^?x}
```
In action:
```
nu'(();-1 0 1;1 1;3 0 0 1 1 0 5 3;-34 0 1 -34 4 8 4)
(()
()
,1
0 1 3
-34 4)
```
## Edit:
If we wanted to preserve the order of the first occurrence of non-unique elements, we could reverse the source list before and after we remove the unique elements via except at the cost of 4 extra bytes:
```
nu: {?|(|x)^?x}
nu'(();-1 0 1;1 1;3 0 0 1 1 0 5 3;-34 0 1 -34 4 8 4)
(()
()
,1
3 0 1
-34 4)
```
[Answer]
# CJam, 10
Assuming the array is already in variable D (based on [this comment](https://codegolf.stackexchange.com/questions/60610/non-unique-elements/60612#comment145849_60613)):
```
D{De=(},_&
```
[Try it online](http://cjam.aditsu.net/#code=%5B-34%200%201%20-34%204%208%204%5D%3AD%3B%0AD%7BDe%3D(%7D%2C_%26)
**Explanation:**
```
D{…}, filter items of D based on the block
De= count occurrences in D
( decrement (resulting in true/false for duplicate/unique)
_& remove duplicates from the results
```
Note: append a `p` if you want pretty printing, otherwise the resulting array is just printed out with no delimiters by default. That is acceptable since the question specifies the snippet only needs to "evaluate to the correct result".
## Standard input/output version, 13:
```
q~_{1$e=(},&p
```
[Try it online](http://cjam.aditsu.net/#code=q~_%7B1%24e%3D(%7D%2C%26p&input=%5B-34%200%201%20-34%204%208%204%5D)
**Explanation:**
```
q~ read and evaluate the input array
_ duplicate the array
{…}, filter items based on the block
1$ copy the array
e= count occurrences
( decrement (resulting in true/false for duplicate/unique)
& set intersection with the initial array (removes duplicates)
p pretty print
```
[Answer]
## Haskell - 32
```
import Data.List;f l=nub$l\\nub l
```
Pretty short, even with the import. `a \\ b` removes the first occurrence of each element of `b` from `a`, and `nub` makes all elements of a list unique.
[Answer]
# Pyth, 7 bytes
```
S{.-Q{Q
```
[Try it online.](https://pyth.herokuapp.com/?code=S%7B.-Q%7BQ&test_suite=1&test_suite_input=%5B3%2C+0%2C+0%2C+1%2C+1%2C+0%2C+5%2C+3%5D%0A%5B-34%2C+0%2C+1%2C+-34%2C+4%2C+8%2C+4%5D)
### How it works
Pyth automatically stores the evaluated input in `Q` and prints all unused return values.
```
{Q Convert Q into a set. This removes duplicates.
.-Q Perform "bagwise" difference of Q and set(Q).
This removes the first occurrence of all elements in Q.
{ Convert to set to deduplicate.
S Sort. Returns a list.
```
[Answer]
# SQL, ~~44~~ 42 bytes
```
SELECT*FROM D GROUP BY I HAVING COUNT(*)>1
```
I hope it is OK to assume the integers are stored in table D?
This will work in both SQLServer, PostgreSQL and possibly others. Thanks to @manatwork from the 2 bytes.
[Answer]
## Mathematica, ~~29~~ 26 bytes
Assuming that input is stored in `d`:
```
Select[d⋃d,d~Count~#>1&]
```
Otherwise, it's 29 bytes as an unnamed function:
```
Cases[#⋃#,n_/;#~Count~n>1]&
```
Here, `d⋃d` (or `#⋃#`) is a golfing trick to remove duplicates - by taking the set union with itself, Mathematica interprets the list as a set, removing duplicates automatically, while the actual union doesn't do anything.
Afterwards, both methods simply filter those elements which appear in the original list at least twice.
[Answer]
# JavaScript (ES6), 37 bytes
Run this in the JavaScript console:
```
e={};d.filter(x=>(e[x]=1+e[x]||0)==1)
```
[Answer]
# Matlab / Octave, 40
I'm assuming input values are real (not complex). The input is in a variable `d`.
```
unique(d(sum(triu(bsxfun(@eq,d,d')))>1))
```
[Try it online](http://ideone.com/w5OldL) in Octave.
[Answer]
## Python 3.5, 30
```
[x for x in{*d}if~-d.count(x)]
```
Uses Python 3.5's set unpacking. The `~-` subtracts 1, which takes a count of 1 to 0 which is Falsy.
This gives a list. If giving a set is OK, then we use a set comprehension, saving 1 char and not needing version 3.5:
```
{x for x in d if~-d.count(x)}
```
[Answer]
# PowerShell, ~~31~~ 29 Bytes
```
($d|group|?{$_.Count-1}).Name
```
Assumes that `$d` is already populated (as given) -- e.g., `$d=@(-34,0,1,-34,4,8,4)`.
Pipes the array into the `Group-Object` cmdlet, which groups like-items together and spits out an object that's essentially an array of arrays. We pipe that to a `Where-Object` (the `?` operator) that has `Count` greater than one (i.e., there are duplicates), and output the `.Name` of those items. Has a side bonus of preserving the initial ordering, too.
Edit - saved two bytes thanks to [Danko Durbić](https://codegolf.stackexchange.com/users/1308/danko-durbi%c4%87)
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~13~~ 9 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set")
Anonymous tacit prefix function.
```
∊(⊂1↓⊣¨)⌸
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT////1FHl8ajribDR22TH3UtPrRC81HPjv9pj9omPOqb6hXs7/eoY4bGo94@IM/T/1FX86H1xo/aJgJ5wUHOQDLEwzNYE6gEqvh/moJ6dKw6F4jSNdRRMNBRMIRyDRFMY7AESA6MgAxTHQVjmDZjE5gcmAlEFkAyVh0A "APL (Dyalog Unicode) – Try It Online")
`(`…`)⌸` for each unique element (left argument) and the indices where it occurs (right argument), apply the following tacit function:
`⊣¨` one of the left (the unique element) for each on the right (the indices)
`1↓` drop one
`⊂` enclose (prevents padding with zeros to create a non-ragged matrix)
`∊` **ϵ**nlist (flatten)
[Answer]
# Julia, ~~30~~ 29 bytes
```
∪(d[find(sum(d.==d',1)-1)])
```
`d.==d'` creates a symmetric matrix with the value at `i,j` being true if `d[i]==d[j]` and false otherwise. `sum`ming in one dimension and then subtracting 1 will produce zero if there's only one of the element and nonzero if there's more than one. `find` will obtain the indexes of the non-zero elements, which are then used to index the array `d` itself. `∪` (union) acts like `unique` when used in this way, removing the repeats.
Old solution:
```
∪(filter(i->sum(d.==i)>1,d))
```
Simple - for each entry, it checks if there's more than one of it in the array. Those for which there are more than one are returned by "filter", and then `∪` (union) acts like `unique` when used in this way, removing the repeats.
Note: originally had it as a function, but question allows array to be stored in a variable, for which I've chosen `d` as suggested in the question.
[Answer]
# Octave, 22 bytes
Based on [Luis Mendo's answer](https://codegolf.stackexchange.com/a/60613/9288).
```
d(sum(triu(d==d'))==2)
```
[Answer]
# R, ~~31~~ 24 bytes
Thanks to [flodel](https://codegolf.stackexchange.com/users/5163/flodel) for the 7 bytes.
Assuming the input is already in `d`.
### code:
```
unique(d[duplicated(d)])
```
edit: now it outputs correctly if there are more than 2 duplicates as pointed by [aditsu](https://codegolf.stackexchange.com/users/7416/aditsu).
[Answer]
# Mathematica, ~~31~~ 29
```
Cases[{s_,t_/;t>1}:>s]@*Tally
```
[Answer]
# Shell + GNU coreutils, 12
```
sort|uniq -d
```
### Test output:
```
$ printf "%s\n" -34 0 1 -34 4 8 4 | ./nonuniq.sh
-34
4
$
```
[Answer]
# Pyth, 7 bytes
```
ft/QT{Q
```
Explanation:
```
ft/QT{Q
Q = eval(input())
{Q set(Q) - deduplicate
f filter - with T as the filter variable.
/QT count in Q of T
t minus 1.
```
The filter removes all elements that appear exactly once from the set of elements.
[Answer]
## LINQ,62 54 bytes
Kinda new here, but here goes nothing.
```
d.GroupBy(c=>c).Where(g=>g.Count()>1).Select(g=>g.Key)
```
[Answer]
# Python 2.7, ~~36~~ 42
```
list(set(filter(lambda x:d.count(x)>1,d)))
```
*edit* : surrounded the expression with list(..) in order to comply with the format required in the question
[Answer]
# K (not K5), 10 bytes
```
x@&1<#:'=x
```
Assumes input is in `x`. I thought it'd be fun to do a non-K5 answer!
[Answer]
# Python 3 - ~~33~~ 30 bytes
`{_ for _ in d if d.count(_)>1}`
Repl output, `d` as input.
[Answer]
# [K (oK)](https://github.com/JohnEarnest/ok), 7 bytes
**Solution:**
```
&1<#:'=
```
[Try it online!](https://tio.run/##y9bNz/7/X83QRtlK3dZYR8EAjAzBCMgw1VEw/v8fAA "K (oK) – Try It Online")
**Explanation:**
```
&1<#:'= / the solution
= / group, key => value (index)
#:' / count length of each group
1< / 1 less than
& / keys where true
```
[Answer]
# Haskell + [hgl](https://gitlab.com/wheatwizard/haskell-golfing-library), ~~[11](https://codegolf.stackexchange.com/revisions/256322/1)~~ 10 bytes
```
(!!1)~<<bg
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m708I7E4OzUnZ2W0km6Ec0CAUuxN1czcgvyiEoXC0sSczLTM1BSFgKLUnNKUVC6oRABXmm3M0tKSNF2LVRqKioaadTY2SekQgZs2uYmZebYp-VwKCgVFCioKaQrRRgpWVgqeeSU6CsY6CiY6CgY6CoY6CpY6CkZgESOwoBmQEQsxY8ECCA0A)
## Explanation
* `bg` sort a list into lists of like values.
* `(!!1)` get the second value or `[]` if there is none.
We use `~<<` to glue these together, which basically acts as a concat map.
## Reflection
This works pretty well, but the operator precedence is killing me.
Both of the following work but requires the parens to prevent an error.
```
nb<(df^*nb)
nb<(fdf~<nb)
```
If the operator precedence was different both of these would be competitive with the first one actually saving bytes.
I don't know if that means the precedence is wrong, but it's worth noticing.
`(!!)` should have a prefix function, *and* a bunch of versions with the index prefilled. I noticed this earlier but still didn't fix it, and now it's coming back to haunt me.
[Answer]
## Mathematica, 23 bytes
With input stored in `d`:
```
Pick[#,#2>1]&@@@Tally@d
```
As a function, 24 bytes:
```
Pick[#,#2>1]&@@@Tally@#&
```
for example, with
```
d = {3, 0, 0, 1, 1, 0, 5, 3}
Tally@d
```
returns this:
```
{{3, 2},
{0, 3},
{1, 2},
{5, 1}}
```
(first element of each sublist is the element, second one is frequency of occurrence). Applying to this list `Pick[#,#2>1]&@@@` transforms it to
```
{Pick[3,2>1], Pick[0,3>1], Pick[1,2>1], Pick[5,1>1]}
```
And where the second argument of `Pick` evaluates to `True` the first argument is returned.
[Answer]
## Perl 6, 16 bytes
Assuming the list is stored in `$_` you could use any of the following snippets.
( which was specifically allowed )
```
(--«.BagHash).Set.keys # 23 bytes
```
```
keys .Bag (-) .Set # 18 bytes
```
```
# U+2216 SET MINUS
keys .Bag∖.Set # 16 bytes in utf8
```
---
If you don't care that you get a Bag you could leave off `keys`.
```
$_ = [3, 0, 0, 1, 1, 0, 5, 3];
.Bag∖.Set ∋ 3 # True
.Bag∖.Set ∋ 5 # False
```
---
None of these have the limitation of only working on signed integers, or even just numbers for that matter.
```
say keys .Bag∖.Set given |(<a b c d a a c>), 1/3, 2/3 - 1/3;
# (a c 0.333333)
```
[Answer]
# Ruby, ~~30~~ 28 bytes
In [the Interactive Ruby Shell](http://ruby-doc.com/docs/ProgrammingRuby/html/irb.html):
```
d.select{|x|d.count(x)>1}|[]
```
Saved 2 bytes thanks to [Kirill L.](https://codegolf.stackexchange.com/users/78274/kirill-l)
[Answer]
# [Husk](https://github.com/barbuz/Husk), 4 bytes
```
u-u¹
```
[Try it online!](https://tio.run/##yygtzv6f@6ip8X@pbumhnf///4@OjtWJ1jXUMdAxBDIMwaQxkAfk64BETXWMQQqMTcAiINpEx0LHJDYWAA "Husk – Try It Online")
```
u # unique element of
- # set difference between
u¹ # unique elements of input
# and input
```
[Answer]
# [Thunno](https://github.com/Thunno/Thunno) `D`, \$7 \log\_{256}(96) \approx\$ 5.76 bytes
Note: this only works on Thunno 1.1.3+
```
gc1>kZU
```
(No ATO link since that's on v1.1.0 at the moment)
[](https://i.stack.imgur.com/NAlyx.png)
### Explanation
```
gc1>kZU # Implicit input. The D flag duplicates it implicitly.
g k # Filter the input for elements where the following is truthy:
c # The count of the element in the input
1> # Is greater than 1
ZU # Deduplicate and output implicitly
```
[Answer]
# JavaScript, ~~35~~ ~~28~~ 34 bytes
```
a=>a.filter(o=x=>(o[x]=-~o[x])==2)
```
[Try It Online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/R1i5RLy0zpyS1SCPftsLWTiM/uiLWVrcORGna2hpp/k/OzyvOz0nVy8lP10jTiI7V1FTQ11eIjuVCk9A11DHQMcQpbYiQM8SQNAZqBWrWARlhqmMMU2gMNhHDImMTsGIQbaJjoWMCUw4WwFBuoAOHMIUGsf8B)
[Answer]
# Common Lisp, 57 bytes
```
(remove-duplicates(remove-if(lambda(x)(<(count x d)2))d))
```
] |
[Question]
[
You are an employee of Microteque, a leading Silicon Valley startup creating smart microwave ovens for all kinds of strange places. Your customers can get their microwaves printed with patterns to match their kitchens, campers, man caves; even the kitchens of large nation-state facilities have shiny new branded microwave ovens.
Due to the cutting-edge nature of your microwave control board technology, you've ended up having to use the programming language MicrowaveX\* and you're working out how to program the time counter. Your counter looks like this:
[](https://i.stack.imgur.com/M86e4.png)
Your goal is to write a program that takes the input time and translates it into the number of seconds that the microwave needs to run.
As input, the function must take a string in the format `##:##` (including the colon at position 3) and return an integer.
Please note that it should also be able to handle more than 60 seconds in the seconds slot.
Finally, due to some pesky regulations, you cannot have your microwave oven run for more than 100 minutes (6,000 seconds)
Sample inputs and outputs:
`01:30` --> 90 seconds
`00:66` --> 66 seconds
`01:99` --> 159 seconds
`02:39` --> 159 seconds
`99:99` --> 6,000 seconds (capped at 100 minutes due to aforementioned regulations)
\*: MicrowaveX happens to be identical to your programming language of choice, but Microteque has rebranded it to sound more appealing to their investors.
[Answer]
# [Bash](https://www.gnu.org/software/bash/) + GNU utilities, 33 bytes
```
dc<<<[6000]sL${1/:/ 60*}+dlLx\<Lp
```
[Try it online!](https://tio.run/##S0oszvj/PyXZxsYm2szAwCC22Eel2lDfSl/BzECrVjslx6cixsan4P///waGVsYGAA "Bash – Try It Online")
[Or try the test suite.](https://tio.run/##TY7NCsIwEITv@xRL6Mmi3VooJMTe9FTwAdRDbIIptEnpDxbEZ6@1qHgZBr6ZYa6qs1Ohesya1t9aVaOUbH88sEkXUspTSkSXLg8ecSQiTGn1DHWVj2eZN9McAyhs7TUO4YifAYC7LSuDrVEaS9cMfVU6A4jaz4JoCutx7ZAFP4i7DNkCN9H3xh9mS9mZiWKREBCJNIXZcw60FQkHzt/@BQ)
The input string is passed as an argument, and the output is on stdout.
---
**How it works**
First bash expands ${1/:/ 60\*} by taking argument 1 and replacing the `:` with `60*` (there's a space before the `60` that StackExchange isn't displaying here). For example, if the input is `01:30`, the expansion is `01 60*30`.
Also, `\<` gets used as the character `<` without its special meaning in the shell.
So what happens is that `dc` is run with
`[6000]sL`minutes`60*`seconds`+dlLx<Lp`
as its program (where "minutes" and "seconds" refer to the actual two-digit numbers).
This carries out the following operations:
```
[6000] Definition of a macro which pushes 6000 on the stack.
sL Save the macro in register L.
minutes 60*seconds+ Compute minutes*60+seconds,
which is the total number of seconds.
d Duplicate the total number of seconds on the stack.
lLx Run macro L, which pushes 6000 on the stack.
The stack now looks like:
#seconds #seconds 6000
(top of stack on the right).
<L Pop 6000 and #seconds from the stack;
if 6000 < #seconds,
then run macro L to push 6000 on the stack again.
At this point, the item at the top of the stack is:
#seconds, if #seconds <= 6000,
6000, if #seconds > 6000.
p Print the top of the stack.
```
[Answer]
# [Python 2](https://docs.python.org/2/), 42 bytes
```
lambda t:min(int(t[:2])*60+int(t[3:]),6e3)
```
[Try it online!](https://tio.run/##RczRCsIgGIbhc6/iP0urxe8kQcFuZElYbUzYbExjdPXWjOjw4f34plfqH6HOnTnnwY3Xu4OkRx@oD4mmRteWbSXuvhLasr1sBctL74cWuCZwc7EFA7NbLj5Mz0TZIU6DT3QDVXWCDSPgYmznBB1dtw1aBsbA@ljMLcvItcCyV0gQtZQFUpJPUaqAHxXBWou/lPo1iYhv "Python 2 – Try It Online")
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~27~~ 24 bytes
```
\d+
$*
+`1:
:60$*
6000`1
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7wPyZFm0tFi0s7wdCKy8rMAMg0MzAwSDD8/9/QwMrYgMvAEEwaWJmZgdiWllwGRlbGllyWlkA2AA "Retina 0.8.2 – Try It Online")
**Explanation**
I'll use the input `01:30` as an example.
```
\d+
$*
```
Convert minutes and seconds to unary. For example, `01:30` would become `1:111111111111111111111111111111`.
```
+`1:
:60$*
```
Loop over each digit preceding the `:`, move it to the right of the `:`, and repeat the digit 60 times. The `01:30` example would now be `:1111111111111111111...` (90 ones)
```
6000`1
```
Count the first 6000 ones.
[Answer]
# JavaScript (ES6), 42 bytes
```
s=>Math.min(6e3,+([m]=s.split`:`)[1]+m*60)
```
[Try it online!](https://tio.run/##fcvRCoIwFADQd79CfNqy9C7pwh2sP@gLRHDYzMXcpEm/v16EIKHnw3nqt47Dyy7ryYe7SaNKUV1vep2q2XqGpjmWrJ07Fau4OLv2suet6Mr5gMDTEHwMzlQuPNjIChCygYLzvK5zguxXQSJuipjtL9Gm4kI7PsvmDxN9NwJA@gA "JavaScript (Node.js) – Try It Online")
### Commented
```
s => // s = input string
Math.min( // return the minimum of ...
6e3, // ... 6000 and the following result ...
+( // coerce to integer:
[m] = // store into m the number of minutes
s.split`:` // which is the first term of the array obtained
// by splitting s on ':'
)[1] + // yield the seconds (2nd term of the above array)
m * 60 // and add the seconds multiplied by 60
) // end of Math.min()
```
[Answer]
# Google Sheets, ~~32~~ 16 bytes
*Saved 16 bytes thanks to Chronocidal straight up commenting a better answer.*
```
=240*MIN(25,6*A1
```
Sheets will automatically add two trailing parentheses when you exit the cell. Input is in `A1`.
---
This could also be written as `Min(6000,86400*TimeValue("0:"&A1))` if we wanted to fully expand it and be precise. As it is, we take advantage of the fact that Sheets will interpret a string that looks like a time to be in the format `hh:mm` by default and treat it as a number of days. For instance, `=1*"12:00"` would return `0.5` and `=1*"6:00"` would return `0.25`. We can then divide by 60 to convert from `hh:mm` to `mm:ss`. If that's the only simplification we used, it would look like this:
```
=Min(6000,1440*A1
```
Dividing both `6000` and `1440` by 240 saves us 5 bytes inside the `Min()` function at a cost of only 4 bytes outside of it.
[](https://i.stack.imgur.com/CFDGV.png)
[Answer]
# [J](http://jsoftware.com/), 21 19 bytes
```
6e3<.60#.[:".' '2}]
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/zVKNbfTMDJT1oq2AihTUjWpj/2typSZn5CtYGijYKqQpqBsYWhkbqEPEzMygYgZWZmZQMUNTS7hCS0sMQSMrY5igmYEB1ExLS5DS/wA "J – Try It Online")
* `[:".' '2}]` Convert the `:` to a space, then evaluate the string as a list of numbers.
* `60#.` Interpret result in base 60.
* `6e3<.` Minimum of that and 6000.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~61~~ 50 bytes
Saved a whopping 11 bytes thanks to [dingledooper](https://codegolf.stackexchange.com/users/88546/dingledooper)!!!
```
s;f(char*t){s=atoi(t)*60+atoi(t+3);s=s<6e3?s:6e3;}
```
[Try it online!](https://tio.run/##TU/RaoMwFH3vV1wChaRaFmsXiGm2h7GvqD5IGjeFafHmQSZ@u4uplgVyOTf35JxzzfHLmHlGVVHzXfYHx0bUpetq6thB8OgBo5Qp1HgRNn3HzFc1zT9l3VIG4w78CX/BWXR4LfRIeJKlnMRAOM@ECCDJpAzglKUBSLm8TCoI1K0DO9ytcfa2KEgegxAxJK9yLYJzvpIfbn1wyofPUz7ID3@Dz7/@vIlXXQ90cWg0V80F61/bVTSkZS9rFzSZiqJm22mLhaBhZV@bgqnn8N77cUVJTvaYEzi@wf4GHrY@x0aPAWOf9LlaU2iNm8i0m@Y/ "C (gcc) – Try It Online")
[Answer]
# perl -MList::Util=min -plF: -E, 25 bytes
```
$_=min 60*$F[0]+$F[1],6E3
```
[Try it online!](https://tio.run/##K0gtyjH9/18l3jY3M0/BzEBLxS3aIFYbSBrG6pi5Gv//b2BoZWzAZWBgZWbGBWRbWnIZGFkZW3JZWgLZ//ILSjLz84r/6/r6ZBaXWFmFlmTmgIwCCpjqGRga/NctyHGzAgA "Perl 5 – Try It Online")
[Answer]
## Batch, 55 bytes
```
@set/ps=
@cmd/cset/a"(s=%s::=*60+%)+(s-=6000)*(-s>>13)
```
Takes input on STDIN. Explanation: `%s::=*60+%` substitutes `*60+` for the `:` in the input, resulting in an arithmetic expression that converts the time into seconds. Since Batch has no minimum function, I then have to compute this via right-shifting the the difference which results in `0` or `-1` which is then used to adjust the seconds, which are then automatically output thanks to the use of `cmd/c`.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~82~~ ~~72~~ ~~62~~ ~~61~~ 57 bytes
```
def f(s):x,y=map(int,s.split(":"));return min(x*60+y,6e3)
```
[Try it online!](https://tio.run/##rYtRCgIhEED/5xTLfs2UxJQgaHSYICWhtUFnYT29eYj@Ho/3pOv7W@wYr5iWhI3CYfpjewrmoqZdmnyy4hpWonuNuteybLngcXJ87sZFS0PqTDHNQXZFIoI/mcHXYBmYg3Mw2XvgW7AevJ/8Aw "Python 3 – Try It Online")
* -10 bytes by using `min()`.
* -10 bytes from Arnauld!
* -1 byte from nope!
* -4 bytes from Chas Brown!
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 12 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Feel like I'm missing a trick here ...
```
q': ì60 m6e3
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=cSc6IOw2MCBtNmUz&input=IjAxOjk5Ig)
```
q': ì60 m6e3 :Implicit input of string
q': :Split on ":"
ì60 :Convert to integer from base-60 digit array
m6e3 :Minimum with 6000
```
[Answer]
# [MathGolf](https://tio.run/##y00syUjPz0n7/9/IJvPR1PlaOUZ2mdpmj2au0no0dfL//0oGhlbGBkpcSgYGVmZmINrQytISRBtZGYNoS0sQHwA), 14 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
2<i╟*l2>i+6♪*╓
```
[Try it online.](https://tio.run/##y00syUjPz0n7/9/IJvPR1PlaOUZ2mdpmj2au0no0dfL//0oGhlbGBkpcSgYGVmZmINrQytISRBtZGYNoS0sQHwA)
**Explanation:**
```
# i.e. input = "99:80"
2< # Take the first two characters of the (implicit) input-string
# STACK: ["99"]
i # Convert it from string to integer
# STACK: [99]
╟* # Multiply it by 60
# STACK: [5940]
l # Push the input-string again
# STACK: [5940,"99:80"]
2>i # Leave its last two characters, and also cast it to an integer
# STACK: [5940,80]
+ # Add them together
# STACK: [6020]
6♪* # Push 6*1000: 6000
# STACK: [6020,6000]
╓ # Only leave the smallest value of the top two values on the stack
# STACK: [6000]
# (after which the entire stack joined together is output implicitly)
```
[Answer]
# [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php), 167 bytes
```
[S S S T S T T T S T T T S S S S N
_Push_6000][S N
S _Duplicate_6000][S N
S _Duplicate_6000][S N
S _Duplicate_6000][T N
T S _Read_STDIN_as_char][T T T _Retrieve][S S S T T S S S S N
_Push_48][T S S T _Subtract][S S S T S S T S T T S S S N
_Push_600][T S S N
_Multiply][S N
S _Duplicate][S N
S _Duplicate][T N
T S _Read_STDIN_as_character][T T T _Retrieve][S S S T T S S S S N
_Push_48][T S S T _Subtract][S S S T T T T S S N
_Push_60][T S S N
_Multiply][T S S S _Add][S N
S _Duplicate][T N
T S _Read_STDIN_as_character][S N
S _Duplicate][S N
S _Duplicate][T N
T T _Read_STDIN_as_integer][T T T _Retrieve][T S S S _Add][S N
T _Swap_top_two][T S S T _Subtract][S N
S _Duplicate][N
T T N
_If_negative_jump_to_Label_PRINT][S N
S _Duplicate][T S S T _Subtract][N
S S N
_Create_Label_PRINT][T S S S _Add][T N
S T _Print_as_integer]
```
Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only.
`[..._some_action]` added as explanation only.
[Try it online](https://tio.run/##hU1LCoBQCFyPp/ASLew2EQ9qFxR0fJ/ftqkDOs7oe5zPuK9tH6rMDAYSFmSZBWqyNnBpAEk5Qz/iIKnQys8D9FuEgbzxkz5RmayBqsi6yAQ) (with raw spaces, tabs and new-lines only).
**Explanation in pseudo-code:**
Unfortunately Whitespace is unable to read an integer when there is anything other than a newline (or nothing) behind it. Because of this, the minute-digits has to be read loose as characters, and seconds can be read as an integer..
```
Integer m1 = Read STDIN as character
m1 = m1 - 48
m1 = m1 * 600
Integer m2 = Read STDIN as character
m2 = m2 - 48
m2 = m2 * 60
Integer m = m1 + m2
Read STDIN as character (the ':', which we simply ignore)
Integer s = Read STDIN as integer
Integer total_seconds = m + s
If(total_seconds - 6000 < 0):
Print total_seconds as integer to STDOUT
Else:
Print 6000 as integer to STDOUT
```
[Answer]
# Befunge-93, 35 bytes
```
&~$"<"*&+:v
v!`*"<""d"<
_"d""<"*.@.
```
[Try it online!](https://tio.run/##S0pNK81LT/3/X61ORclGSUtN26qMq0wxQQvIUUpRsuGKB5IgCT0Hvf//DQytLC0B "Befunge-93 – Try It Online")
Reads a number, read a character (`:`) and discard it, multiply the read number with 60 (ASCII character 60 equals `"<"`), read the second number, and add it to the product (this gives the number of seconds). Dub the number of seconds; push 6000 (`6000 = 60 * 100 = "<" * "d"`) on the stack and compare. If 6000 is less than the number of seconds, push another 6000 on the stack and print it. Else, print the number of seconds (which is now the top of the stack).
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ṣ”:Vḅ60«6ȷ
```
A monadic Link accepting a list of characters which yields an integer.
**[Try it online!](https://tio.run/##ASEA3v9qZWxsef//4bmj4oCdOlbhuIU2MMKrNsi3////OTk6OTk "Jelly – Try It Online")**
### How?
```
ṣ”:Vḅ60«6ȷ - Link: list of characters, T
”: - character ':'
ṣ - split T at ':'
V - evaluate as Jelly code -> [m,s]
60 - sixty
ḅ - convert from base -> 60*m+s
6ȷ - 6*10^3 = 6000
« - minimum
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 41 bytes
```
->i{[i[0,2].to_i*60+i[3,2].to_i,6e3].min}
```
[Try it online!](https://tio.run/##KypNqvyfZqvwX9cuszo6M9pAxyhWryQ/PlPLzEA7M9oYxtUxSzWO1cvNzKv9X6CQFq1kYGhlbKAUaw3hGFiZmcE5hlaWlnCOkZUxnGNpCZb5DwA "Ruby – Try It Online")
16 bytes saved thanks to [math-junkie](https://codegolf.stackexchange.com/users/65425/math-junkie)
[Answer]
# [C++ (gcc)](https://gcc.gnu.org/), 92 bytes
```
#import<iostream>
main(){int m,s;char x;std::cin>>m>>x>>s;std::cout<<std::min(m*60+s,6000);}
```
[Try it online!](https://tio.run/##Sy4o0E1PTv7/XzkztyC/qMQmM7@4pCg1MdeOKzcxM09Dszozr0QhV6fYOjkjsUihwrq4JMXKKjkzz84u186uws6uGCqSX1piYwNm5gK15WqZGWgX65gZGBhoWtf@/29paWVpCQA "C++ (gcc) – Try It Online")
Special Thanks to [math junkie](https://codegolf.stackexchange.com/users/65425/math-junkie).
Special Thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat) for the educative suggestion.
[Answer]
# x86-16 machine code, 30 bytes
Binary:
```
00000000: 33d2 e806 00b2 3cf6 e292 acad 2d30 3086 3.....<.....-00.
00000010: c4d5 0a03 c2ba 7017 3bc2 7e01 92c3 ......p.;.~...
```
Listing:
```
33 D2 XOR DX, DX ; zero DX
E8 0006 CALL CONV ; get minutes into AX
B2 3C MOV DL, 60 ; multiplier 60 sec/min
F6 E2 MUL DL ; AX = AL * 60
92 XCHG AX, DX ; save seconds in DX
AC LODSB ; skip ':' char
CONV:
AD LODSW ; load next two ASCII chars into AX
2D 3030 SUB AX, '00' ; ASCII convert
86 C4 XCHG AL, AH ; endian convert
D5 0A AAD ; BCD to byte convert
03 C2 ADD AX, DX ; add minutes to seconds
BA 1770 MOV DX, 6000 ; set up max comparison
3B C2 CMP AX, DX ; is result > 6000?
7E 01 JLE DONE ; if not, return current value
92 XCHG AX, DX ; otherwise 6000
DONE:
C3 RET ; return to caller
```
Input string in `[SI]`, output number of seconds in `AX`.
Sample I/O using test program:
[](https://i.stack.imgur.com/ZcP0e.png)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 13 bytes
```
I⌊⟦↨I⪪S:⁶⁰×⁶φ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwzczLzO3NFcj2imxOBUiFFyQk1mi4ZlXUFoSXAJUma6hqaOgZKWkCaTMDIBESGZuarGGmY6CoYGBgWaspqam9f//BoZWxgb/dctyAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
S Input string
⪪ : Split on literal `:`
I Cast each part to integer
↨ ⁶⁰ Convert from base 60
⁶ Literal 6
× Multiplied by
φ Predefined variable 1000
⌊⟦ Take the minimum
I Cast to string
Implicitly print
```
[Answer]
# [Perl 5](https://www.perl.org/) with `-plF/((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((\d+)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))):(\d+)/ -MList::Util+sum,min`, 16 bytes
Not competing with [@Abigail's answer](https://codegolf.stackexchange.com/a/204981/9365) which is not 'cheaty' like this one.
```
$_=min 6e3,sum@F
```
[Try it online!](https://tio.run/##K0gtyjH9/18l3jY3M0/BLNVYp7g018Ht/38DQytjAy4DAyszMy4g29KSy8DIytiSy9ISyP6XX1CSmZ9X/F@3IMdNX4MCEJOirUkBsAIboP9f19cns7jEyiq0JDNHG@gDHaBvAA "Perl 5 – Try It Online")
### Explanation
Using the `-F` flag, the left part of the input is replicated 60 times and the right part is extracted once, into `@F`. These are `sum`med to yield the number of seconds and we use `min` to ensure it's not over 6000.
[Answer]
## Tcl, 54 bytes
```
proc f {a} {scan $a %d:%d a b
expr min(60*$a+$b,6000)}
```
[Try it online!](https://tio.run/##JczRCoIwFMbx685TnEAhq4tjwuDsVcSL6bYSbA5dFIw9@zK7@fjBB/8wTDn7ZR7QYlQJ4zooh4XCUstSo8IezMcv@BzdSdC5UJeivwoiqlJ@P8bJYDy2Zra4Bj26bgvAwb/Ciq3F9m42/I8OUq5JNgRU70tSiJ@ZgW6yYWDezZL4Cw)
## Explanation
Sadly, the times with leading zeroes mess up string interpolation directly into expr (using ternaries) because Tcl thinks they are octal, so I had to settle for using scan to force interpretation as decimal. Also, if `6000.0` is allowed as output, I can save 1 byte.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 11 bytes
```
':¡60β6₄*)W
```
[Try it online!](https://tio.run/##yy9OTMpM/f9f3erQQjODc5vMHjW1aGmG//9vaGVpCQA "05AB1E – Try It Online")
Coincidental port of most answers.
## Explained
```
':¡60β6₄*)W
min(lhs: base10(number: split(string: input, character: ":"), from: 60), rhs: times(lhs: 6, rhs: 1000))
': | Push the character ":"
¡ | Split the input upon ":"s -> [mins, seconds]
60β | Convert the list from base 60 to base 10
6₄* | Push the number `6000`
)W | Wrap the converted input and 6000 into a list and find the smallest.
```
[Answer]
# [Rust](https://www.rust-lang.org/), 82 bytes
```
|s:&str|6000.min(60*s[..2].parse::<u32>().unwrap()+s[3..].parse::<u32>().unwrap())
```
[Try it online!](https://tio.run/##dY9BawMhEIXv/oppDkHbIGMCC2uaHPoTeg05LI2CdOMujpJDsr99qzZsT53DY3jvY56GRHG2Hq6d81zAnUGe3kSwcID5QXpNMTwaRJTXTDT4Sicpt2c5doGM1u9ptz1yIZO/hW7k4o1OOyn/jcW8rw2JDFC8aO0GrT@S/TTdZb9058T53L8Q1eDil7BDgN55A5mpgeyHr@9cUkxaPlFmDM7H3r/w1X1abcDydWH@XvO8OLGJzYgakRVVRVXdm6pty1DVVFVfFV9Vv22z/gA "Rust – Try It Online")
Unfortunately type inference for parse is very restricted and the turbofish must be used every time.
I also made some versions using `fold` instead of parse, but they are longer:
With a tuple accumulator and a closure to combine minutes and seconds:
```
|s:&[u8]|6000.min((|(a,b)|60*a+b)(s.iter().fold((0,0),|(a,b),x|match x{58=>(b,0),_=>(a,10*b+*x as i32-48)})))
```
Using a [i32;2] accumulator and `.iter().sum()`
```
|s:&[u8]|6000.min(s.iter().fold([0,0],|[a,b],x|match x{58=>[60*b,0],_=>[a,10*b+*x as i32-48]}).iter().sum())
```
And then there's this ungodly abomination using `std::ops::Range<i32>` as an accumulator, with `-60*minutes` as the start and `seconds` as the end. Eww.
```
|s:&[u8]|6000.min(s.iter().fold(0..0,|a,x|match x{58=>-60*a.end..0,_=>a.start..10*a.end+*x as i32-48}).len())
```
[Answer]
# APL+WIN, 20 bytes
Prompts for time as string:
```
6E3⌊60⊥(⍎2↑n),⍎3↓n←⎕
```
[Try it online! Courtesy of Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcjzra0/6buRo/6ukyM3jUtVTjUW@f0aO2iXmaOkCW8aO2yXlAdUD1/4Eq/6dxqRsYWhkbqHOBWAZWZmYQlqGVpSWEZWRlDGIpcKlbWoIFAQ "APL (Dyalog Classic) – Try It Online")
[Answer]
# [Burlesque](https://github.com/FMNSSun/Burlesque), 19 bytes
```
ps1RAp^60.*.+6000<.
```
[Try it online!](https://tio.run/##SyotykktLixN/f@/oNgwyLEgzsxAT0tP28zAwMBG7/9/A0MrS0sA "Burlesque – Try It Online")
Explanation:
```
ps # Parses input string as block: mm:ss => { mm ":" ss }
1RA # Removes element at index 1 from block: { mm ss }
p^ # Splits block to stack
60.* # Multiply top element by 60
.+ # Sum both elements
6000<. # Return the minimum of the calculated value or 6000
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 13 bytes
```
y6000B60mrx":
```
[Try it online!](https://tio.run/##yygtzv7/v9LMwMDAycwgt6hCyer///9KBkZWxpZKAA "Husk – Try It Online")
## Explanation
```
x": Split on colons
mr Convert from string form
B60 Interpret in base 60
y6000 Minimum with 6000
```
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 17 bytes
```
q':/:i~\60*+6e3e<
```
[Try it online!](https://tio.run/##S85KzP3/v1DdSt8qsy7GzEBL2yzVONXm/39LSytLSwA "CJam – Try It Online")
```
q':/:i~\60*+6e3e< e# Whole program
q e# Read input [e.g "99:98"]
':/ e# Split on : [e.g ["99" "98"]]
:i e# Convert to integers [e.g [99 98]]
~\ e# Dump and swap [e.g 98 99]
60* e# Multiply by 60 [e.g 98 5940]
+ e# Add [e.g 6038]
6e3e< e# Get minimum to 6000 [e.g 6000]
e# Implicit output
```
[Answer]
# [Befunge-93 (FBBI)](https://github.com/catseye/FBBI), 25 bytes
```
"<|`*"<d":+&*&
@.<
*"<d@.
```
[Try it online!](https://tio.run/##S0pNK81LT9W1NNZNS0rK/P9fyaYmQUvJJkXJSltNS43LQc@GC8R10Pv/39LSytISAA "Befunge-93 (FBBI) – Try It Online")
### Explanation:
The program consists of three parts (lines), the first one processes the input:
```
"<|`*"<d":+&*& Stack IP direction
empty east
"<|`*" push everything between the two quotes
42, 96, 124, 60 east
< turn west
42, 96, 124, 60 west
"<|`*" push everything between the two quotes
60, 124, 96, 42, 42, 96, 124, 60 west
*& take an integer (minutes), convert to seconds
60*m, 124, ... west
+& take the next int, add to the total
60*m+s, 124, ... west
: duplicate TOS
60*m+s, 60*m+s, ... west
*"<d" push 60*100 = 1000
6000, 60*m+s, 60*m+s, ... west
` is greater than?
6000 > 60*m+s, 60*m+s, ... west
| north-south if
60*m+s, ... north / south
```
If the total number of seconds is smaller or equal to 6000, the IP moves south and enters the second line:
```
@.< Stack IP direction
60*m+s, ... south
< turn west
60*m+s, ... west
. print integer
124, ... west
@ Stop
```
If the number of second is greater than 6000, the IP moves north and enters the last line:
```
*"<d@. Stack IP direction
60*m+s, ... north
< turn west
60*m+s, ... west
*" push everything up to the next quote ...
"<d@. ... which is actually the same one.
60, 100, 64, ... west
* Stop
6000, 64, ... west
. print 6000
64, ... west
@ Stop
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~16~~ 15 bytes
```
hS,6000ivcQ\:60
```
[Try it online!](https://tio.run/##K6gsyfj/PyNYx8zAwCCzLDkwxsrM4P9/JUtLIK0EAA "Pyth – Try It Online")
```
hS,6000ivcQ\:60 Implicit: Q=input()
cQ\: Split Q on ":"
v Convert each from string to integer
i 60 Convert from base 60
,6000 Pair with 6000
S Sort
h Take the first element (i.e. smallest)
Implicit print
```
*Edit: Previous version:* `hS,6000isMcQ\:60`
[Answer]
# [Julia](https://docs.julialang.org/en/v1/) ~~54~~ ~~53~~ 52 bytes
```
f(x)=((i,j)=parse.(Int,split(x,":"));min(60i+j,6e3))
```
[try it online](https://tio.run/##tchRCsMgDADQ/xyjXwmVkVYQ4ugBdgxhFiJOxDrw9q6X2N/jpW/WsI05Txx0IKpJdNTQrvjAV@nmqlk7DrP4hej50YKOdU3GRUs0a9PSc8ETWwzvrCUiEcEfe/LmLQOzdw5uiwDv3gqI3P4B)
A single line solution for Julia.
A couple neat tricks here, we use `f(x)=`, a generic function declaration so we don't have to use the `return` `end` or `function` keywords.
We then use a compound expression like this `(code;code;...)`.
Unfortunately, when using tuple destructuring `i,j=`, the tuple here must be wrapped in parenthesis for some reason, which adds two bytes.
Edits:
* 1 byte improvement using `60i` instead of `60*i`
* 1 byte improvement by removing trailing whitespace
] |
[Question]
[
The code should take a string as input from keyboard:
```
The definition of insanity is quoting the same phrase again and again and not expect despair.
```
The output should be like this(not sorted in any particular order):
```
: 15
. : 1
T : 1
a : 10
c : 1
e : 8
d : 4
g : 3
f : 2
i : 10
h : 3
m : 1
o : 4
n : 10
q : 1
p : 3
s : 5
r : 2
u : 1
t : 6
y : 1
x : 1
```
All ASCII characters count unicode is not a requirement, spaces, quotes,etc and input should come from keyboard / not constants, attributes, output should be printed with new line after each character like in the above example, it should not be returned as string or dumped as hashmap/dictionary etc, so `x : 1` and `x: 1` are ok, but `{'x':1,...` and `x:1` are not.
Q: Function or complete program taking stdin and writing stdout?
A: Code needs to be a program taking input using standard in and display the result via standard out.
# Scoreboard:
[Shortest overall](https://codegolf.stackexchange.com/a/157214/12328): 5 bytes
~~[Shortest overall](https://codegolf.stackexchange.com/questions/19068/display-number-of-occurrences-for-every-character-in-an-input-string#answer-19104): 7 bytes~~
[Answer]
## PHP - 68 (or 39) bytes
```
<?foreach(count_chars(fgets(STDIN),1)as$k=>$v)echo chr($k)." : $v
";
```
Output for the example text:
```
: 15
. : 1
T : 1
a : 10
c : 1
d : 4
e : 8
f : 2
g : 3
h : 3
i : 10
m : 1
n : 10
o : 4
p : 3
q : 1
r : 2
s : 5
t : 6
u : 1
x : 1
y : 1
```
If the exact output is not required, this would work for **39 bytes**:
```
<?print_r(count_chars(fgets(STDIN),1));
```
Sample output:
```
Array
(
[32] => 15
[46] => 1
[84] => 1
[97] => 10
[99] => 1
[100] => 4
[101] => 8
[102] => 2
[103] => 3
[104] => 3
[105] => 10
[109] => 1
[110] => 10
[111] => 4
[112] => 3
[113] => 1
[114] => 2
[115] => 5
[116] => 6
[117] => 1
[120] => 1
[121] => 1
)
```
where each numerical index refers the ordinal value of the character it represents.
I suspect very strongly that using an in-built function that does exactly what the problem states will soon be disallowed.
[Answer]
# k (~~8~~ 7)
```
#:'=0:0
```
Example
```
k)#:'=:0:0
The definition of insanity is quoting the same phrase again and again and not expect despair.
T| 1
h| 3
e| 8
| 15
d| 4
f| 2
i| 10
n| 10
t| 6
o| 4
s| 5
a| 10
y| 1
q| 1
u| 1
g| 3
m| 1
p| 3
r| 2
x| 1
c| 1
.| 1
```
edit: Down to seven, H/T Aaron Davies
## Explanation
Take a String from keyboard :
```
k)0:0
text
"text"
```
Group the distinct elements and return a map containing key as distinct characters and values are the indices where the distinct elements occur.
```
k)=0:0
text
t| 0 3
e| ,1
x| ,2
```
Now count values of each entry in the map.
```
k)#:'=0:0
text
t| 2
e| 1
x| 1
```
[Answer]
# GNU core utils - 29 22 20 chars (53 with formatting)
Wumpus's improvement (20 chars):
```
fold -1|sort|uniq -c
```
Firefly's improvement (22 chars):
```
grep -o .|sort|uniq -c
```
joeytwiddle's original (29 chars):
```
sed 's+.+\0\n+g'|sort|uniq -c
```
Originally I used `sed` to simply add a newline after each character. Firefly improved on that with `grep -o .`, since `-o` displays every matched pattern on its own line. Wumpus pointed out a further improvement using `fold -1` instead. Nice work!
`uniq` does the real work, although it only applies to sorted lists.
Note that the output format does not exactly match the example in the question. That requires a final run through `sed` to swap the arguments. (Waiting on an answer to Jan Dvorak's question to see if this is required...)
Reformatting with sed is "only" another 33 characters! (**Total 53**)
```
|sed 's/ *\(.*\) \(.\)/\2 : \1/'
```
Awk can *almost* do the job whilst adding only 25 chars, but it hides the first space. Silly awk!
```
|awk '{print $2" : "$1}'
```
I wonder if improvements can be made in the reformatting stage...
[Answer]
## Perl 6: 21 chars
```
.say for get.comb.Bag
```
```
(REPL)
> .say for get.comb.Bag
The definition of insanity is quoting the same phrase again and again and not expect despair.
"T" => 1
"h" => 3
"e" => 8
" " => 15
"d" => 4
"f" => 2
"i" => 10
"n" => 10
"t" => 6
"o" => 4
"s" => 5
"a" => 10
"y" => 1
"q" => 1
"u" => 1
"g" => 3
"m" => 1
"p" => 3
"r" => 2
"x" => 1
"c" => 1
"." => 1
```
[Answer]
# Ruby 1.9.3: 53 characters
(Based on @shiva's and @daneiro's comments.)
```
gets.split("").uniq.map{|x|puts x+" : #{$_.count x}"}
```
Sample run:
```
bash-4.1$ ruby -e 'a=gets;a.split("").uniq.map{|x|puts"#{x} : #{a.count x}"}' <<< 'Hello world'
H : 1
e : 1
l : 3
o : 2
: 1
w : 1
r : 1
d : 1
: 1
```
## Ruby: 44 characters
Not respecting the output format:
```
s=Hash.new 0;gets.chars{|c|s[c]+=1};pp s
```
Sample run:
```
bash-4.1$ ruby -rpp -e 's=Hash.new 0;gets.chars{|c|s[c]+=1};pp s' <<< 'Hello, world!'
{"H"=>1,
"e"=>1,
"l"=>3,
"o"=>2,
","=>1,
" "=>1,
"w"=>1,
"r"=>1,
"d"=>1,
"!"=>1,
"\n"=>1}
```
[Answer]
# Python 3: 76 characters
## 76
```
import collections as c
for x,y in c.Counter(input()).items():print(x,':',y)
```
### 44
(print same characters many times, see [Wasi](https://codegolf.stackexchange.com/questions/19068/display-number-of-occurrences-for-every-character-in-an-input-string/19113#19113)'s answer for a valid version)
```
a=input()
for x in a:print(x,':',a.count(x))
```
[Answer]
## APL (15)
```
M,⍪+⌿Z∘.=M←∪Z←⍞
```
If you really need the `:`, it's **19** (but there's others who aren't including it):
```
M,':',⍪+⌿Z∘.=M←∪Z←⍞
```
Output:
```
M,⍪+⌿Z∘.=M←∪Z←⍞
The definition of insanity is quoting the same phrase again and again and not expect despair.
T 1
h 3
e 8
16
d 4
f 2
i 10
n 10
t 6
o 4
s 5
a 10
y 1
q 1
u 1
g 3
m 1
p 3
r 2
x 1
c 1
. 1
```
[Answer]
### R, 30 characters
```
table(strsplit(readline(),""))
```
Example usage:
```
> table(strsplit(readline(),""))
The definition of insanity is quoting the same phrase again and again and not expect despair.
. a c d e f g h i m n o p q r s t T u x y
15 1 10 1 4 8 2 3 3 10 1 10 4 3 1 2 5 6 1 1 1 1
```
[Answer]
## Perl 5, 54 characters
```
map{$h{$_}++}split//,<>;print"$_ : $h{$_}\n"for keys%h
```
[Answer]
# JavaScript
1. **~~66~~ 53 bytes:**
```
prompt(a={}).replace(/./g,function(c){a[c]=-~a[c]}),a
```
2. **~~69~~ 56 bytes:**
```
b=prompt(a={});for(i=b.length;i--;){a[b[i]]=-~a[b[i]]};a
```
3. **~~78~~ 65 bytes:**
```
prompt().split('').reduce(function(a,b){return a[b]=-~a[b],a},{})
```
**N.B.:** In all cases deleted number of bytes refer to extra `console.log()` call which is pointless if run in the console. Big thanks to [@imma](https://codegolf.stackexchange.com/users/14870/imma) for the great catch with `-~a[b]` and `prompt(a={})`. This definitely saved some more bytes.
[Answer]
# **Python 2, correctly (58)**
```
s=raw_input()
for l in set(s):print l+" : "+str(s.count(l))
```
**Output:**
```
python count.py
The definition of insanity is quoting the same phrase again and again and not expect despair.
: 15
. : 1
T : 1
a : 10
c : 1
e : 8
d : 4
g : 3
f : 2
i : 10
h : 3
m : 1
o : 4
n : 10
q : 1
p : 3
s : 5
r : 2
u : 1
t : 6
y : 1
x : 1
```
# **Python 2, cheetah style (41)**
```
s=input()
print {l:s.count(l) for l in s}
```
**Output:**
```
python count.py
"The definition of insanity is quoting the same phrase again and again and not expect despair."
{' ': 15, '.': 1, 'T': 1, 'a': 10, 'c': 1, 'e': 8, 'd': 4, 'g': 3, 'f': 2, 'i': 10, 'h': 3, 'm': 1, 'o': 4, 'n': 10, 'q': 1, 'p': 3, 's': 5, 'r': 2, 'u': 1, 't': 6, 'y': 1, 'x': 1}
```
[Answer]
## Mathematica, 61 bytes
```
Map[{#[[1]], Length@#} &, Gather@Characters[Input[]]] // TableForm
```
It then pops up this dialog box,

and for the sample sentence, produces as output

[Answer]
## python 3, 49
Stealing idea from [evuez](https://codegolf.stackexchange.com/questions/19068/display-number-of-occurrences-for-every-character-in-an-input-string/19070#19070)
```
t=input()
for i in set(t):print(i,':',t.count(i))
```
input:
```
The definition of insanity is quoting the same phrase again and again and not expect despair.
```
output:
```
: 15
. : 1
T : 1
a : 10
c : 1
e : 8
d : 4
g : 3
f : 2
i : 10
h : 3
m : 1
o : 4
n : 10
q : 1
p : 3
s : 5
r : 2
u : 1
t : 6
y : 1
x : 1
```
[Answer]
# JavaScript (~~69~~ 68 characters):
*Expects `s` to hold the string.*
```
_={};for(x in s)_[a=s[x]]=-~_[a];for(x in _)console.log(x+': '+_[x])
```
*This follows the new rules perfectly.*
**Note:** *This presumes a clean environment, with no custom properties on any standard object prototypes.*
**Edit:** 1 character less!
## Console output:
```
T: 1
h: 3
e: 8
: 15
d: 4
f: 2
i: 10
n: 10
t: 6
o: 4
s: 5
a: 10
y: 1
q: 1
u: 1
g: 3
m: 1
p: 3
r: 2
x: 1
c: 1
.: 1
```
---
# Old answer (44 characters):
```
r={};[].map.call(s,function(e){r[e]=-~r[e]})
```
*This was valid before the rules changed.*
`r` contains the output.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 5 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set")
Full program body. Prompts for a string from STDIN and prints newline separated table to STDOUT. Leftmost column is the input characters, and counts are right-aligned with the largest number separated from its character by a single space.
```
,∘≢⌸⍞
```
[Try it online!](https://tio.run/##TYyxDQIxEARzqtgCgGpo4ITP/pOeO/M@JL4CHglyIgKqoB43YgwRG@2sRkt53ISZRkutLpfY1nV51Our3t71/vxODb/E1W5gBI6i4mIKixAt1GmGFBxP5qIJ3q1CB0YeJioMSiQK0vDX1Bx8zrz3flgyybT9AA "APL (Dyalog Unicode) – Try It Online")
`⍞` prompt for text input from STDIN
`⌸` create a keys' table consisting of
`,` the unique element followed
`∘` by
`≢` the tally of the indices of its occurrence (i.e how many times it occurs)
[Answer]
# Haskell, 93
```
import Data.List
main=getLine>>=mapM(\s->putStrLn$[head s]++" : "++show(length s)).group.sort
```
[Answer]
**PowerShell (49)**
```
[char[]](read-host)|group|%{$_.Name+":"+$_.Count}
```
[Answer]
# C# (178 220 chars)
Based on @Spongeman's comment I changed it up a bit:
```
using C=System.Console;using System.Linq;class P{static void Main()
{C.WriteLine(string.Join("\n",C.ReadLine().GroupBy(x=>x)
.OrderBy(x=>x.Key).Select(g=>g.Key+":"+g.Count())));}}
```
---
```
Line breaks added for readability, my first feeble attempt at code golf! :)
class P {static void Main(){var d=new Dictionary<char,int>();
Console.ReadLine().ToList().ForEach(x=>{ if(d.ContainsKey(x))
{d[x]++;}else{d.Add(x,1);}});Console.WriteLine(string
.Join("\n",d.Keys.Select(x=>x+":" +d[x])));}}
```
[Answer]
# [Sclipting](http://esolangs.org/wiki/Sclipting), 19 characters
```
梴要⓶銻꾠⓷❸虛變梴❶⓺減負겠⓸⓸終丟
```
## Output
```
T:1
h:3
e:8
:15
d:4
f:2
i:10
n:10
t:6
o:4
s:5
a:10
y:1
q:1
u:1
g:3
m:1
p:3
r:2
x:1
c:1
.:1
```
If you want the spaces around the `:`, change `꾠` to `긃똠`, making it 20 characters.
## Explanation
```
Get length of input string.
梴
Stack is now [ input, length ]
While {
要
Get first character of string and push ":"
⓶銻꾠
Stack is now [ length, input, firstchar, ":" ]
Replace all occurrences of that character with empty string
⓷❸虛變
Stack is now [ length, firstchar, ":", reducedinput ]
Get the length of that, calculate difference to previous length, push "\n"
梴❶⓺減負겠
Stack is now [ firstchar, ":", reducedinput, newlength, diff, "\n" ]
Move the input string and length back up, leaving output below it
⓸⓸
Stack is now [ firstchar, ":", diff, "\n", reducedinput, newlength ]
`------------------------' `-------'
Every iteration of the The length provides
While loop generates the While loop's
a bit like this terminating condition
} End While
終
Discard the length which is now 0
丟
```
[Answer]
# F# (66 59 49, 72 with prescribed formattting)
```
let f s=s|>Seq.countBy(id)|>Seq.iter(printfn"%A")
```
Output:
```
> f The definition of insanity is quoting the same phrase again and again and not expect despair.
(' ', 15)
('.', 1)
('T', 1)
('a', 10)
('c', 1)
('d', 4)
('e', 8)
('f', 2)
('g', 3)
('h', 3)
('i', 10)
('m', 1)
('n', 10)
('o', 4)
('p', 3)
('q', 1)
('r', 2)
('s', 5)
('t', 6)
('u', 1)
('x', 1)
('y', 1)
```
With the prescribed formatting, it becomes:
```
let f s=s|>Seq.countBy(id)|>Seq.iter(fun(a,b)->printfn"\"%c\" : %d"a b)
```
[Answer]
# Mathematica, ~~34~~ 29 bytes
Not sure why the other Mathematica answer is so complicated... ;)
```
Grid@Tally@Characters@Input[]
```
[Answer]
# Bash (20 15 characters)
```
ptx -S.|uniq -c
10 a
1 c
4 d
8 e
2 f
3 g
3 h
10 i
1 m
10 n
4 o
3 p
1 q
2 r
5 s
6 t
1 T
1 u
1 x
1 y
```
ASCII encoding now supported
# Bash (23 characters):
```
xxd -p -c1|sort|uniq -c
1 0a
15 20
1 2e
1 54
10 61
1 63
4 64
8 65
2 66
3 67
3 68
10 69
1 6d
10 6e
4 6f
3 70
1 71
2 72
5 73
6 74
1 75
1 78
1 79
```
ASCII formatting not supported
[Answer]
# Java 8, ~~273~~ ~~253~~ ~~249~~ ~~246~~ ~~239~~ 200 bytes
```
interface I{static void main(String[]a){int m[]=new int[999],i=0;for(int c:new java.util.Scanner(System.in).nextLine().getBytes())m[c]++;for(;++i<999;)if(m[i]>0)System.out.printf("%c: %d%n",i,m[i]);}}
```
-24 bytes thanks to *@Poke*.
-7 bytes thanks to *@OlivierGrégoire*.
**Explanation:**
[Try it here.](https://tio.run/##TY/BasNADER/RQQCuzhdcnXc9NBboTf3ZnwQazmRU2tdr5zGhHy7uy499DZiRo@ZDq/41DWXZWFRGlv0BG/3qKjs4Rq4gR5ZTKkjy6mq0d5TDvqqPgp9Q9JVnuf1jo/7og2jWU1/WK0ugd2k/OlKjyI0mnKOSr1jsU7opu8sZKw7kb7OStFY21e@zrJfTpFl/JzIheXW9BXXL3v79x8mdUNqo63ZbP0Bts1WNjverSlbPB7L8nEmaKhlYeUgENrUM2K6ZuAIX1PQtAU0pSL2BMN5xEiApzQUUJp/SoIC3QbymoBxQB7dDw)
```
interface I{ // Class
static void main(String[]a){ // Mandatory main-method
int m[]=new int[999], // Integer-array to count the occurrences
i=0; // Index-integer, starting at 0
for(int c:new java.util.Scanner(System.in).nextLine().getBytes())
// Loop over the input as bytes:
m[c]++; // Increase the occurrence-counter of the char by 1
for(;++i<999;) // Loop over the array:
if(m[i]>0) // If the current character occurred at least once:
System.out.print("%c: %d%n",// Print with proper formatting:
i, // The character
m[i]);}} // and the occurrence-count
```
[Answer]
# JavaScript, ~~44~~ 37 bytes
```
s=>[...s].map(x=>o[x]=-~o[x],o={})&&o
```
---
## Try it
```
o.innerText=JSON.stringify((f=
s=>[...s].map(x=>o[x]=-~o[x],o={})&&o
)(i.value="The definition of insanity is quoting the same phrase again and again and not expect despair."));oninput=_=>o.innerText=JSON.stringify(f(i.value))
```
```
<input id=i><pre id=o></pre>
```
[Answer]
## Powershell, 63
```
$a=@{};[char[]](read-host)|%{$a[$_]++};$a.Keys|%{"$_ :"+$a[$_]}
```
[Answer]
## Windows Command Script - 72 Bytes
```
set/p.=
:a
set/a\%.:~,1%=\%.:~,1%+1
set.=%.:~1%
%.%goto:b
goto:a
:b
set\
```
**Outputs:**
```
\=15 (space)
\.=1
\a=10
\c=1
\d=4
\e=8
\f=2
\g=3
\h=3
\i=10
\m=1
\n=10
\o=4
\p=3
\q=1
\r=2
\s=5
\T=7
\u=1
\x=1
\y=1
```
[Answer]
## J, 23 chars
```
(~.;"0+/@|:@=)/:~1!:1]1
```
Slightly different output format (line 2 is stdin):
```
(~.;"0+/@|:@=)/:~1!:1]1
Mississippi
┌─┬─┐
│M│1│
├─┼─┤
│i│4│
├─┼─┤
│p│2│
├─┼─┤
│s│4│
└─┴─┘
```
[Answer]
# J, 22 characters
```
(~.;"0+/@(=/~.))1!:1]1
```
Example:
```
(~.;"0+/@(=/~.))1!:1]1
The definition of insanity is quoting the same phrase again and again and not expect despair.
+-+--+
|T|1 |
+-+--+
|h|3 |
+-+--+
|e|8 |
+-+--+
| |15|
+-+--+
|d|4 |
+-+--+
|f|2 |
+-+--+
|i|10|
+-+--+
|n|10|
+-+--+
|t|6 |
+-+--+
|o|4 |
+-+--+
|s|5 |
+-+--+
|a|10|
+-+--+
|y|1 |
+-+--+
|q|1 |
+-+--+
|u|1 |
+-+--+
|g|3 |
+-+--+
|m|1 |
+-+--+
|p|3 |
+-+--+
|r|2 |
+-+--+
|x|1 |
+-+--+
|c|1 |
+-+--+
|.|1 |
+-+--+
```
[Answer]
C#
```
string str = Console.ReadLine(); // Get Input From User Here
char chr;
for (int i = 0; i < 256; i++)
{
chr = (char)i; // Use The Integer Index As ASCII Char Value --> Convert To Char
if (str.IndexOf(chr) != -1) // If The Current Char Exists In The Input String
{
Console.WriteLine(chr + " : " + str.Count(x => x == chr)); // Count And Display
}
}
Console.ReadLine(); // Hold The Program Open.
```
In Our Case, If The Input Will Be "**The definition of insanity is quoting the same phrase again and again and not expect despair.**"
The Output Will Be:
```
: 15
. : 1
T : 1
a : 10
c : 1
d : 4
e : 8
f : 2
g : 3
h : 3
i : 10
m : 1
n : 10
o : 4
p : 3
q : 1
r : 2
s : 5
t : 6
u : 1
x : 1
y : 1
```
[Answer]
## C#: 129
This is Avivs answer but shorter:
```
var s=Console.ReadLine();for(int i=0;i<256;i++){var ch=(char)i;Console.Write(s.Contains(ch)?ch+":"+s.Count(c=>c==ch)+"\r\n":"");}
```
This is mine:
## C#: 103
```
foreach(var g in Console.ReadLine().OrderBy(o=>o).GroupBy(c=>c))Console.WriteLine(g.Key+":"+g.Count());
```
] |
[Question]
[
Write a program that outputs `Hell0 W0rld!`. It must match this output exactly, including capitalization, zeroes instead of o's, exactly one space, etc. Trailing new lines are allowed.
Lowest score wins. Scoring is based on the sum of the values of each character in the language's code page - otherwise Unicode values should be used. New lines are treated as spaces.
Here are a few example scores:
```
abc //Score: 294
print(Hell0 W0rld!) //Score: 1597
//Score: 1454
multi
line
code
```
You can check your ASCII score by inputting your code [here](https://tio.run/##fVJNT8MwDL33V5ieUk1knBk7wIRgEjDEToA4hNZtM9KkStwNhPbbS/qxtQgJXxz52c/PdjZiK043yUddy6I0lmDjA7wiqfg6FlqjnQVjpBCU8yuZLTVh1oBl9a5kDLESzsG9kDr4DsBbH3ckyLutkQkUHmVrslJnIGzmXt@iNrUraGw6fRTWISxMgpBaU8BSlxUd8b44buA5hOFsQDqx4Ho/B427Q5StvxxhwaWOhopdLhWyPp/nwj3gJ7EoOiYMshpre07mhwZc@@w7qZGNKBuT6X@cf3nH3CGEv8n2wfAaLWkhVFwpQegHNBaPyHAXL9MDfgtDiL9cP60G@tRYJjWB9ElnM@8uWhlcoc4o91OBnEyi31pb0nnnuEgSNmLfClXhKmUtSZwLe0lMRtFoO6MR@nuYinjpL0pKs7Ad5dzvYNI16Cv3wb6un01lu09xY9DBLVo8@QE). You can view individual ASCII values [here](http://www.asciitable.com/).
[Answer]
# [Lenguage](https://esolangs.org/wiki/Lenguage), score 0
Well, this is quite boring and obvious, but it seems to achieve the perfect score (assuming I understand the challenge correctly). To fix this loophole, you should probably add the program's length to the sum of the code points; I'm pretty sure that won't break the relative order of the current answers.
The program is
```
2282524454641945458940768311481012240407465625061984267694778013056442426959468031225640633070772676474431950201473533908
```
null bytes. Fortunately, 0 multiplied by the number above is still 0.
I believe this decompresses (alternatively, it *compresses*) to the automatically generated (with the help of a random web page that claims "Original Java program not from me") brainfuck program:
```
-[------->+<]>-.-[->+++++<]>++.+++++++..[-->+<]>------.[--->++<]>.---[->+++<]>.+[-->+<]>++++.[----->+<]>++.------.--------.-[--->+<]>.
```
It almost certainly could be golfed (but I haven't tried), but that is unnecessary.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), score ~~513~~ 252
-261 points thanks to @Dorian
Posting this separately from my other answer, as this one is arguably less cheating. I've been waiting for somebody else to do this for a while, but nobody did. I tried multiple languages. Pyth has extremely short code for this (`Cl"..."`, if I remember correctly), but it turned out it can't input null bytes, and most other golfing languages I found have painfully large char codes for quotes (and I couldn't write this piece of code in the rest).
```
"ǝǝǝǝǝǝǝǝǝǝǝǝ...ǝǝǝǝǝ"gтB
```
Where there are 174047470094320053473995 `ǝ` characters, that conveniently happen to have a value of 0 in the code page.
Explanation:
```
"ǝǝǝǝǝǝǝǝǝǝǝǝ...ǝǝǝǝǝ" push the long string
g pop and get its length
тB push 100 and convert to that base
```
You definitely shouldn't try the full version online, [but you can try online the version with the length finding part skipped.](https://tio.run/##yy9OTMpM/f/f0NzEwMTcxNzAwNLE2MjAwNTYxNzY0tL0YpPT//8A "05AB1E – Try It Online")
[Answer]
# [7](https://esolangs.org/wiki/7), 41 characters, code point sum 81
```
3200245300300120052223120310300244053**7**403
```
[Try it online!](https://tio.run/##FYjBDQBADIJWsmrT/SfzvIQHcIkI0CugTGNJqqL5hzZWZyh5 "7 – Try It Online")
Unlike with many of my 7 programs, there's nothing particularly clever going on here; this basically just prints a string in the simplest possible way (which in 7 involves encoding the string into a piece of source code, evaluating it, analysing the resulting stack element to figure out what source code is most likely to have created it, and then giving the resulting source code directly to the output routines).
The reason this scores so well is that 7 has a code page consisting of only 8 characters, and the code that's used to represent string literals tends to use only `0`, `1`, `2`, `3`, `4`, `5` (as those commands have much easier-to-analyse effects on the stack than **`6`** and **`7`** do, so it's more likely that the original source will be accurately reproduced by the **`6`** command). This means that none of the code points in the bulk of the program will go above 5 (the assignment of code points to characters in 7 is the obvious one), leading to an *average* code point value of around 2½ (for this program, happenstance means it's more like 2). Thus, although there are a lot of characters in the program, the sum of the codepoints continues to stay low. (Unlike the Lenguage answer, the code point sum + character count is also very low, so this answer isn't even really cheating.)
[Answer]
# [COW](https://bigzaphod.github.io/COW/), Score: 117799
```
MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO
MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO
MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO
MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO
MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO Moo MoO MoO
MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO
MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO Moo MoO MoO
MoO MoO MoO MoO MoO Moo Moo OOO MoO MoO MoO MoO MoO MoO MoO
MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO
MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO
MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO Moo MOo MOo MOo
MOo MOo MOo MOo MOo MOo MOo MOo MOo MOo MOo MOo MOo Moo MoO
MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO
MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO
MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO
MoO MoO MoO MoO MoO MoO MoO MoO MoO Moo MOo MOo MOo MOo MOo
MOo MOo MOo MOo MOo MOo MOo MOo MOo MOo MOo MOo MOo MOo MOo
MOo MOo MOo MOo MOo MOo MOo MOo MOo MOo MOo MOo MOo MOo MOo
MOo MOo MOo MOo Moo MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO
MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO
MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO
MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO
MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO Moo MOo MOo MOo
MOo MOo MOo Moo MOo MOo MOo MOo MOo MOo MOo MOo Moo OOO MoO
MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO
MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO
MoO MoO Moo
```
[Try it online!](https://tio.run/##S84v///fN99fgUzMNTL05g9Se/PB2N9/OIQz0C/@cMyFxCYeQ8JrGKdJrP4mL6xooReRXkfLDXzpOZ@4tAzN14PAv/n//wMA "COW – Try It Online")
My cow could not understand that the lower score in this challenge is better, so they scored very high! I kept telling them: "Please score lower, it is better", but they kept responding: "MoO"!
[Answer]
# HTML, Score: 959
```
Hell0
W0rld!
```
If newlines (`\r` and `\n`) would have been count as their ASCII code (`10` and `13`) the score would be **937** or **940** because in HTML, new lines in "inline" elements are rendered as space.
[Answer]
# [Keg](https://github.com/JonoCode9374/Keg), sum = ~~966~~ ~~868~~ ~~853~~ [843](https://tio.run/##fVE9T8MwEB1gCmM3JKRTJkcWLjOlA@oASECRKibEYBK3cXGcyL60INTfHi4fbVIhcctF7929e89Zy428XCefVaWzIncIawJEidqIRSytVW4SBEX5YXQMsZHew5PUNvgJgKrDPUqktsl1AhmxbIFO2xVIt/Jv71Ez2i7UNR6/SOcVzPJEwdLlGTzYosQD3y3HNT2FMJz0TGsIfNenYNV2j7LFt0eVCW2jfmObaqNYNy9S6Z/VF7IoOgz0tupqbvLp/oCwNP2orWIDybr08j/Nv7pD7RDCY7Fd0H8NHmkmTVwaiYoC5k4dGG2R/BFC8a96pWXuWE3pBqZ201wURtkVphQANOfRsa1Whjw1k3Eq3S0yPcg6MNS9bl6iKOj/oLEsbIxdUyLeSnWbu2BXVWfA7@fz0ck58NHr/O6UXfDwFw)
```
� +HOO��� +�UOG�(�+"
```
[Try it online!](https://tio.run/##y05N//@fW0Hbw99fmFlKQVs41N@dRUNWW@n/fwA "Keg – Try It Online")
-15 score from cutting out the `0` (with a bit of help from [the awful old Python script](https://tio.run/##nY7JDoJAEETvfkWLy8w4giyuuB79Aw@ASwAVg4MZNMG4/DoOagxcTfrQSdWrqtP1vI@YkabbiEMCAQO@YTsfGzoxSxDDGBBSDlHAsOXuOY64h10iJwQyv5v5pbkfhiosVB56ZcmxTFPWHFJkc6gIpgjEBdsPj8rmqqlMbSQ9l9XK3bbrMyo3WrXRZLzG1u3hEFXTjXan2@sPhgj8MPYF@KuP31VUdGFEs55E5NMmKsGJB@yMM/37XY7fEXm6IP8zKJ@Vpi8)).
-10 score from A\_\_'s idea to use `"` and implicit print over the costlier `,`.
Based on a comment by Night2, as well as [Jo King's old 32-byte quine](https://tio.run/##y05N///fpcqpyinMIzjAzdM1MNhNI04tTs1Kx9xES1fT1FxLmev/fwA).
```
� +HOO��� +�UOG�(�+" Push the shifted codepoints beginning-first.
� + � + ('H' and 'W' are pushed as sums,
because '+' is cheaper than '\'.)
+ Add
� 29
" then rotate the stack
( once for every item on the stack.
```
If newlines weren't treated as spaces for scoring, this would be 832:
```
+GNN���TNF�� +(�+"
```
[Try it online!](https://tio.run/##y05N//@fS0Hb3c9PiElSQVsoxM@NWUNOW@n/fwA "Keg – Try It Online")
[Answer]
# [MineFriff](https://github.com/JonoCode9374/Minefriff), Score: 3725
```
Cff3,a*a,9*c,a*b4,6*8,8*a7,ff2,8*6,9*c,:a*a1,9*8,`
>l?#;o~
```
[Try it online!](https://tio.run/##y83MS00rykxL@//fOS3NWCdRK1HHUisZSCeZ6JhpWehYaCWa66SlGQEZZmAZK6ASQyDLQieByy7HXtk6v@7/fwA "MineFriff – Try It Online")
This ain't winning any competitions any time soon I tell you (I dread seeing what Scratch's score would be...). I'll post an image of what this looks like in-game soon, but first I have to actually re-install the python-in-minecraft mod and actually get it all working first.
See y'all soon! (I hope...)
## Actual In-Game Progess Report
### 10 mins in
* I managed to *finally* get Forge opened on my mac. That really shouldn't have taken 10 minutes but it did
* Minecraft 1.8 (unmodded) still hasn't launched/finished downloading.
* Still downloading the actual mod
* All star seems like a nice song to listen to while doing this
### 14 mins in
* Minecraft 1.8 finally opened
* Mod finally downloaded
* All star finished playing
* Moving on to actually using forge
### 17 mins in
* Forge successfully has installed and I'm loading in the mod now
* Jake Paul is *apparently* number one. Send help please.
### 20 mins in
* Help received. No longer listening to cringey songs
* I think I've properly installed the mod. No clue if it works because minecraft doesn't want to load.
### 23 mins in
* And I downloaded the wrong version of the mod. Oops. Nothing broken, just wasted, oh, I don't know, **6 minutes**. Sigh.
### 27 mins in
* I still can't read the documentation. Apparently, I needed to drag *all* the folders from the extracted zip into the mods folder
* Starting to think about downloading the minefriff world
### 30 mins in
* **MOD IS FINALLY INSTALLED**
* Thank goodness. Robbie Rotten is now number one. No help needed this time.
* Time to see if everything still works.
### 34 mins in
* About to test if actual interpreter works in-game. Wish me luck!
### 36 mins in
* Nup. Game crashed. :(
### Tomorrow
* I'll be trying 1.10 instead of 1.8
### Next day, 1 min in
* Minecraft 1.10 has somehow deleted itself from my list of available installations. Now I have to manually find it somewhere and then somehow get Forge to make a 1.10 profile. Problem is, I won't be able to work on it for another 4 hours. See y'all then!
[Answer]
# [PHP](https://php.net/), Score: 959
"Classic" answer. PHP outputs by default.
```
Hell0 W0rld!
```
[Try it online!](https://tio.run/##K8go@P/fIzUnx0BHIdygKCdF8f9/AA "PHP – Try It Online")
* Polyglot with [Carrot](https://tio.run/##S04sKsov@f/fIzUnx0Ah3KAoJ0Xx/38A "Carrot – Try It Online") and [Canvas](https://tio.run/##S07MK0ss/v/fIzUnx0Ah3KAoJ0Xx/38A "Canvas – Try It Online") and [Charcoal](https://tio.run/##S85ILErOT8z5/98jNSfHQCHcoCgnRfH/fwA "Charcoal – Try It Online")
[Answer]
# [Bash](https://www.gnu.org/software/bash/), score: 1360
```
echo Hell0 W0rld!
```
[Try it online!](https://tio.run/##S0oszvj/PzU5I5/TIzUnx4Az3KAoJ0Xx/38A "Bash – Try It Online")
[Answer]
# [Keg](https://github.com/JonoCode9374/Keg), Score: 1051
```
Hell0 W0rld\!
```
[Try it online!](https://tio.run/##y05N///fIzUnx0Ah3KAoJyVG8f9/AA "Keg – Try It Online")
[Answer]
# [Zsh](https://www.zsh.org/), Score 1207
```
<<<"Hell0 W0rld!"
```
[Try it online, with a self-scorer!](https://tio.run/##ZY@xDoIwFEVn@xVXaEwbF3BEdHHxDxyMQ1MeQtJQ05ZFwrcjKkSjb7q5LyfnvbuvhiHP8@hIxiQ4Jc4Uy2hgMQ7K6NaoQPDaOsrG6nciLnKeyOjTOFIF6gbetk4TytrQH8e7OZ1FKdNLP6YrBaQ@wNTNF8A74bNM/nlHwt9MHWAb6Eo5pQM5z1hpHfRTP4G8my@cTP0WhWULId4/Yb1DrCElK@zoJV1Z7Fcb8Nd2eAA "Zsh – Try It Online")
Using `<<<Hell0\ W0rld!` is shorter, but more expensive: `\` = `92`, but 2⨯`"` = `68`.
[Answer]
# [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), Score: 1105
```
." Hell0 W0rld!"
```
[Try it online!](https://tio.run/##S8svKsnQTU8DUf//6ykpeKTm5BgohBsU5aQoKv1PLlIwUCiOUVLQi0GVilFSUkjKL81LKVaITsmPVYjOjFVIdlDQVojOyc8viFXQ@w8A "Forth (gforth) – Try It Online")
Prints the given string to stdout.
[Answer]
# [bit\*\*](https://github.com/Helen0903/bitch), Score: 2519
```
#72/#101/#108/#108/#48/#32/#87/#48/#114/#108/#100/#33/
```
[Try it online!](https://tio.run/##S8osSc74/1/Z3Ehf2dDAEERYQAkTIDYGCluYQ9iGhiZwaQOglLH@////8gtKMvPziv/rJgMA "bitch – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), Score: [863](https://tio.run/##fVHLTsMwEBQcc@sXYJmLowiXI6L0gCqQkAhCyhFxMK7bbHHsyHZaEOq3h82jTSok9rLRzO7sjLMRW3G1WX7WNRSldYFsEOBVAM0zKYxRbhZFZfWhQRKphfckFWCin4hg9bgPImDbWliSAlmWBQdmTYRb@7f3uB3tFpqaTl@F84os7FKRlbMFeTJlFY58vywbek4onQ1MZ4j4vs@JUbsDyrJvH1TBwcTDxi4HrVg/z3PhX9RXYHF8HBhsNdXeTOaHA9zg9DMYxUaSTcHqP82/umNtSuip2D4avkaPtBBaVloEhQGtU0cGTEB/iGD860FpZR1rKGhhbHftRa6VWYccAxBIkvjUVieDntpJmQt3HxiMso4M9a9rq8BL/D9BG0ZbY7eYKOmk@s19tK9rGj@m6eTsZpKlD@dUJpcXvw)
```
")FMM8SME"c+#
```
[Test it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=IilGTU0RATgRU01FAiJjKyMf)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), Score:1213
Just the string. Nothing interesting.
```
“Hell0 W0rld!
```
## Score: 1744
Simply a compression.
```
“ØƲṡhḍḊF®Ḍ?»
```
[Try it online!](https://tio.run/##ASMA3P9qZWxsef//4oCcw5jGsuG5oWjhuI3huIpGwq7huIw/wrv//w "Jelly – Try It Online")
[Code page summator](https://tio.run/##K6gsycjPM/7/P60oP1chKzUnp1IhM7cgv6hEITk/JTW@IDE9VUchJTO5JDM/L7Gokqsotbg0p8TWgCstv0ghUyEzT0HpUcOcwzOObXq4c2HGwx29D3d0uR1a93BHj/2h3UpWXJwQDdq2cOP0MvNSUis0MjW5Cooy80o04BIwAYgOzf//AQ)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), score 722
```
⍘L”y;;;(...231699726063762276300861 in total...);;;”γ
```
Port of @someone's 05AB1E answer. Explanation: If you convert 231699726063762276300861 to base 95 using the printable ASCII character set then you get the desired output. Only printable ASCII characters are automatically turned into string literals, so our null bytes have to be quoted with `”y”`. Using Charcoal's code page, the special characters have the byte values 148 + 204 + 9 + 121 + 0 + ... + 0 + 9 + 231 = 722.
As proof of concept, you can see it just for the letters `He`: [Try it online!](https://tio.run/##7cKxCYAwEADAWUMaC0Gws8sC9oJkAzvbzJAhskBGeAfxjstL2vOW1ohxXrM9o9RjtltVVVVVVVVVVVVV9c9Hqf2N@AA "Charcoal – Try It Online")
[Answer]
# Malbolge, Score: 6087
Just because I can.
```
('<;_#!7[}4{2VxTv-QsqNo'K+k)"Fgf|Bcc>=O<;(Kq7XXm3TjSng-x+)((`%d#"E~Y|{{>g,;;ut
```
[Answer]
# x86-64 machine code (Linux executable w/ system calls), score 1508
274 bytes: 18 code bytes, 12 data bytes, and 244 zero-padding bytes to make a rel32 = `00 01 00 00` instead of some larger number in the lowest byte.
The natural character-set of x86 machine code is 1 binary byte. No argument can be made for word, unlike with a RISC with fixed-length instructions.
Hexdump of the `.text` section of the executable (actually from assembling the same thing into a flat binary for `hexdump -C`). I'm not counting the metadata bytes of the whole executable emitted by the linker.
```
00000000 8d 35 00 01 00 00 5f 04 0c 92 04 01 0f 05 04 30 |.5...._........0|
00000010 0f 05 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................|
00000020 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................|
*
00000100 00 00 00 00 00 00 48 65 6c 6c 30 20 57 30 72 6c |......Hell0 W0rl|
00000110 64 21 |d!|
00000112
```
Disassembly (`objdump -d -Mintel`).
```
0000000000400080 <_start>: # Entry point
400080: 8d 35 00 01 00 00 lea esi,[rip+0x100] # 400186 <msg>
0000000000400086 <_start.lea_ref>:
400086: 5f pop rdi # fd = argc = 1
400087: 04 0c add al,0xc
400089: 92 xchg edx,eax
40008a: 04 01 add al,0x1
40008c: 0f 05 syscall # write(argc=edi, msg=rsi, msglen=rdx) leaves RAX=msglen
40008e: 04 30 add al,0x30
400090: 0f 05 syscall # exit(edi=1)
... (a bunch of 00 bytes)
0000000000400186 <msg>:
48 65 6c 6c 30 20 57 30 72 6c 64 21 db "Hell0 W0rld!"
```
Note that Linux static executables start with all registers = 0 (except RSP which points to `argc` on the stack).
`add al, imm8` has opcode `04`, and is the lowest opcode that takes an immediate. Using that to turn a `0` into a number we want, and `xchg`-with-eax for another zero, is the best way I've found to construct small numbers under these scoring rules. `push imm8`/`pop` is somewhat worse, and `mov reg,imm8` has a high opcode.
**The opcode map at <http://ref.x86asm.net/coder64.html> was very useful for this.**
---
**Built with `nasm -felf64 hell0.asm && ld -o hell0 hell0.o` from this source:** (Including a mess of commented out possibilities, many with their instruction bytes to remind me why I didn't use them.)
If `MSGXOR` is `%define`d to a non-zero value, link with `ld -N` (aka `--omagic`) to make `.text` read+write. In that case, the `%if` includes a loop that XORs every byte of the string. `0x60` and `0x64` are both equal. Subtraction with `0x30` doesn't save enough, and subtraction with larger values wraps around for too many bytes creating larger bytes.
```
BITS 64 ; for flat binary.
%define MSGXOR 0x60
default rel
_start:
lea esi,[rel msg] ; small positive offset. Truncating the address to 32-bit is ok in a non-PIE
; mov esi, msg ; better than rsi, msg or strict qword
.lea_ref:
; add al, 1 ; nr_write. 04 add al, imm8 is the lowest-opcode immediate instruction
;cmovnz edi, eax ; 0f 45 f8 RDI is the highest-numbered register, and mode=11 is killer in ModRM
; xchg edi, eax ; 9x
; mov edi, [rsp] ; 8b 3c 24
pop rdi ; 5f fd = argc=1
; lea edx, [rax+msglen] ; 8d 50 0d
add al, msglen
xchg edx, eax ; len = msglen
%if 0
lea edi, [rax] ; 8d 38
add edi, eax
mov esi, eax
%endif
; push "Hell" ; 68 48 65 6c 6c ; then would need to deal with 64-bit addresses
; add cl, msglen ; 80 c1 0c
; mov cl, msglen ; b1 0d
%if MSGXOR != 0
add al, msglen-2 ; last byte is a '!' which grows when XORed with 0x60
.loop:
xor byte [rsi+rax], MSGXOR
sub eax, strict dword 1 ; longer immediate makes the backwards jcc farther from FF
;sub al, 1; 2c 01
jnc .loop ; }while(rax>=0); jnc has a lower opcode than jge or jns
; lea ecx, [.loop] ; at the top: 8d 0d 00 00 00 00 ; loop back with an indirect jump so the loop exit can jump forwards?
; push rcx ; 51
; ret ; c3
; jmp rcx ; ff e1 nope, doesn't look good. Just have to eat the nearly-FF rel8
; loop .loop ; e2 f2
.break:
;;; AL = -1 after the loop
add eax, strict dword 2
%else
add al, 1 ; RAX = 1 = _NR_write
%endif
; %else EAX = 0 still
; add al, 1 + !!MSGXOR ; RAX = 1 = _NR_write
; mov al, 1
syscall ; write(argc, msg, msglen) returns RAX=msglen
; xor al, 60 ^ msglen
add al, 60-msglen ; or sub to wrap to 231 _NR_exit_group?
; or al, 60
; mov al, 60 ; exit.
; mov eax, 60
syscall
padbytes equ 0x100 - ($ - .lea_ref)
times padbytes db 0
; in the same section as the code so we can control the rel32 to have one non-zero byte of 01
X equ MSGXOR
;msg: db "Hell0 W0rld!"
msg: db 'H'^X, 'e'^X, 'l'^X, 'l'^X, '0'^X, ' '^X, 'W'^X, '0'^X, 'r'^X, 'l'^X, 'd'^X, '!' ; last byte not XORed
msglen equ $-msg
;ml: db msglen
;msg: db 0x28, 0x5, 0xc, 0xc, 0x50, 0x40, 0x37, 0x50, 0x12, 0xc, 0x4, 0x41 ; with ^0x60
```
Score counted with `hexdump | awk` with a custom format to dump bytes in decimal, and awk to add them up.
```
nasm hell0.asm -o hell0.bin &&
<hell0.bin hexdump -e '32/1 "%d " "\n"' |
awk '{for(i=1; i<=NF; i++)tot+= $i;} END{printf "score = %#x = %d\n", tot, tot}'
```
**With MSGXOR = 0x60, score = 1668, the loop does *not* pay for itself with this short message**, especially with `0` digits instead of `o` lower-case ASCII. `cmp al,imm8` is `3C`, but `cmp/jcc` and counting *up* towards `mslen-1` instead of materializing `msglen` and `msglen-2` separately might help. But it wouldn't help enough; **we're 160 score away from break-even.**
```
# with MSGXOR = 0x60
0000000000400080 <_start>:
400080: 8d 35 00 01 00 00 lea esi,[rip+0x100] # 400186 <msg>
0000000000400086 <_start.lea_ref>:
400086: 5f pop rdi
400087: 04 0c add al,0xc
400089: 92 xchg edx,eax
40008a: 04 0a add al,0xa
000000000040008c <_start.loop>:
40008c: 80 34 06 60 xor BYTE PTR [rsi+rax*1],0x60
400090: 2d 01 00 00 00 sub eax,0x1
400095: 73 f5 jae 40008c <_start.loop>
0000000000400097 <_start.break>:
400097: 05 02 00 00 00 add eax,0x2
40009c: 0f 05 syscall
40009e: 04 30 add al,0x30
4000a0: 0f 05 syscall
...
0000000000400186 <msg>:
400186: 28 05 0c 0c 50 40 # not really instructions, deleted disassembly
40018c: 37
40018d: 50
40018e: 12 0c 04
400191: 21 .byte 0x21
```
I can't find a way to jump backwards that isn't horrible. Register-indirect jump sucks, and short displacements need a `0xF?` byte. Padding with any non-zero byte to change the displacement costs at least as much as it reduces the `rel8` displacement, and `00 00` is `add [rax], al`. Hmm, Possibly with a 256-byte-aligned address in RAX, we could pad with `00 00` without modifying memory? But `xchg` with EAX is a `9?` byte and getting an address into RAX is costly.
But if we have a pointer in RAX, we can't use `add al, 1` or `sub al, 1` to loop. In 32-bit code we'd have `4?` `inc`/`dec`, but not RIP-relative addressing. x86-64 `inc`/`dec` are terrible, using the `ff /0` modrm encoding.
(**I considered using a linker script to set the absolute virtual address to something even lower**, but LEA's opcode is lower than `mov r32, imm32`. Hrm, for EAX there is `05` `add eax, imm32` with an absolute address. So looping another reg with inc or dec might be viable. Or looping EAX with a pointer-compare, especially if I can make the absolute data address something like `00 00 01 00` just outside the low 64k where Linux disallows memory-mapping by default. But then I'd feel like I had to count the linker script or its resulting metadata. Or if I'm messing around with the metadata (ELF headers) in the executable, maybe have to count the whole thing instead of just the .text section.)
32-bit code needs `int 0x80` for system calls, not `0f 05` syscall.
[Answer]
# [Turing Machine Code](http://morphett.info/turing/turing.html), Score: ~~7105~~ ~~6279~~ 5175
```
0 _ ! l !
! _ d l "
" _ l l #
# _ r l $
$ _ 0 l %
% _ W l &
& _ _ l '
' _ 0 l (
( _ l l )
) _ l l +
+ _ e l ,
, _ H l -
```
*Implemented suggestions by Naruyoko*
*Shaved off another 1100+ using tabs instead of spaces*
[Try it online!](http://morphett.info/turing/turing.html?88544f229a9ed9e797048baf6d6273bb)
# [Turing Machine But Way Worse](https://github.com/MilkyWay90/Turing-Machine-But-Way-Worse), Score: ~~69695~~ 55343
```
0 0 0 1 1 0 0
0 1 1 1 2 0 0
0 2 0 1 3 0 0
0 3 0 1 4 0 0
0 4 1 1 5 0 0
0 5 0 1 6 0 0
0 6 0 1 7 0 0
0 7 0 1 8 1 0
0 8 0 1 9 0 0
0 9 1 1 10 0 0
0 10 1 1 11 0 0
0 11 0 1 12 0 0
0 12 0 1 13 0 0
0 13 1 1 14 0 0
0 14 0 1 15 0 0
0 15 1 1 16 1 0
0 16 0 1 17 0 0
0 17 1 1 18 0 0
0 18 1 1 19 0 0
0 19 0 1 20 0 0
0 20 1 1 21 0 0
0 21 1 1 22 0 0
0 22 0 1 23 0 0
0 23 0 1 24 1 0
0 24 0 1 25 0 0
0 25 1 1 26 0 0
0 26 1 1 27 0 0
0 27 0 1 28 0 0
0 28 1 1 29 0 0
0 29 1 1 30 0 0
0 30 0 1 31 0 0
0 31 0 1 32 1 0
0 32 0 1 33 0 0
0 33 0 1 34 0 0
0 34 1 1 35 0 0
0 35 1 1 36 0 0
0 36 0 1 37 0 0
0 37 0 1 38 0 0
0 38 0 1 39 0 0
0 39 0 1 40 1 0
0 40 0 1 41 0 0
0 41 0 1 42 0 0
0 42 1 1 43 0 0
0 43 0 1 44 0 0
0 44 1 1 45 0 0
0 45 1 1 46 0 0
0 46 0 1 47 0 0
0 47 0 1 48 1 0
0 48 0 1 49 0 0
0 49 0 1 50 0 0
0 50 1 1 51 0 0
0 51 0 1 52 0 0
0 52 0 1 53 0 0
0 53 0 1 54 0 0
0 54 0 1 55 0 0
0 55 0 1 56 1 0
0 56 0 1 57 0 0
0 57 1 1 58 0 0
0 58 0 1 59 0 0
0 59 1 1 60 0 0
0 60 0 1 61 0 0
0 61 1 1 62 0 0
0 62 1 1 63 0 0
0 63 1 1 64 1 0
0 64 0 1 65 0 0
0 65 0 1 66 0 0
0 66 1 1 67 0 0
0 67 1 1 68 0 0
0 68 0 1 69 0 0
0 69 0 1 70 0 0
0 70 0 1 71 0 0
0 71 0 1 72 1 0
0 72 0 1 73 0 0
0 73 1 1 74 0 0
0 74 1 1 75 0 0
0 75 1 1 76 0 0
0 76 0 1 77 0 0
0 77 0 1 78 0 0
0 78 1 1 79 0 0
0 79 0 1 80 1 0
0 80 0 1 81 0 0
0 81 1 1 82 0 0
0 82 1 1 83 0 0
0 83 0 1 84 0 0
0 84 1 1 85 0 0
0 85 1 1 86 0 0
0 86 0 1 87 0 0
0 87 0 1 88 1 0
0 88 0 1 89 0 0
0 89 1 1 90 0 0
0 90 1 1 91 0 0
0 91 0 1 92 0 0
0 92 0 1 93 0 0
0 93 1 1 94 0 0
0 94 0 1 95 0 0
0 95 0 1 96 1 0
0 96 0 1 97 0 0
0 97 0 1 98 0 0
0 98 1 1 99 0 0
0 99 0 1 100 0 0
0 100 0 1 101 0 0
0 101 0 1 102 0 0
0 102 0 1 103 0 0
0 103 1 1 104 1 1
```
*Tabs instead of spaces, saving over 14,000*
[Try it online!](https://tio.run/##RdVBjhwxCIXh9eQ0LhswXCf77CLN8Ts1/nmOetGFqiV/emD675/f39@fz/j6@Tzv5/3@xdPzNbua593qap3KurLzS@/Kz7voKk61u9qnyp8z3ipPVf2uOHHo@BZczoNOoAfRI9L7cH4v1Hl4a7Heh/M@@vAH2SPa@3Dep@qkFu88vHnIN/FN@WbndQPDN@WbZDatz5/4pnwT31RwM6jlm2Q35Zv4pnyT/JZ8i24u@Rb5rdnnr@7obSm@pfwWXV3yLXxLvkV@S76Fb8m36O6Sb5GfjT7f8Jl8hs@Un81znslnPXN36PCZfIbP5DN8Jp/hMw2f4TP5DJ8rP6e/Lp/jc/mc/Fw@x@fyOf31ey24F675c3wunzN/rvwcn8vn9DfkC/IL@YL5C/mC/EK@4H6E5i/whXzR9/ZeXOYv5At8IV/gC/mC/LZ8G9@Wb5Pf1vxt8tvybXxb@W36u@Xb9HfLt3uz3NVCf7d8m/ux5dv4UvOX@FK@JL9Ufkl@KV/S35Qv8aV8iS/lS3wpX/buu8uP/FK@pL@l/Ir5K/mK/Eq@Ir@Sr8iv5Cv6W/IV/S3NX@Er@QpfKb8iv7rrmfye8X9B9//FuCt69I4ed0mP3tLjrunRe3qc/D6ffw "Turing Machine But Way Worse – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), Score: 2021
Thanks to GammaFunction
```
A(){puts("Hell0 W0rld!");}
```
Also, just for fun, here is a C program that had a score of 1 using overflow.
It's a base64 encoded rar file
<https://pastebin.com/SJMcRnLj>
[Try it online!](https://tio.run/##S9ZNT07@/99RQ7O6oLSkWEPJIzUnx0Ah3KAoJ0VRSdO69n9mXolCbmJmHlAFUBVQAAA "C (gcc) – Try It Online")
[Answer]
# [J](http://jsoftware.com/), Score: 1452
```
echo'Hell0 W0rld!'
```
[Try it online!](https://tio.run/##y/r/PzU5I1/dIzUnx0Ah3KAoJ0VR/f9/AA "J – Try It Online")
[Answer]
# [evil](https://web.archive.org/web/20070103000858/www1.pacific.edu/~twrensch/evil/index.html), Score: 12853
Hard-code the characters
```
zaeeeaeeewzaeeaeeaeawzuueeueueawzuueeueueawzaeeeaeewzaeeeeewzaeeeeeuewzaeeeaeewzuueeueeaaawzuueeueueawzaeeaeeaewzaeeeeeaw
```
[Try it online!](https://tio.run/##Sy3LzPn/vyoxNTUVhMtBLDBKLK8qLU1NLQVCVCZUKYSBoEtTkaQgylMTEzG0ghFMT2L5//8A "evil – Try It Online")
[Answer]
# [Labyrinth](https://github.com/m-ender/labyrinth), Score:2151
```
72.101.108.108.48.32.87.48.114.108.100.33.@
```
## Explanation
```
72 Push ord code of 'H'
. Output
101.108.108.48.32.87.48.114.108.100.33. And so on
@ And exit.
```
[Try it online!](https://tio.run/##y0lMqizKzCvJ@P/f3EjP0MAQiC3A2MRCz9hIz8IcxDA0NIGKG@gZG@s5/P8PAA "Labyrinth – Try It Online")
[Answer]
## [MSM](https://esolangs.org/wiki/Mutating_Stack_Machine), Score: 1465
```
!dlr0W 0lleH...........
```
It is great that `!` is not an MSM instruction. Half of the program pushes onto stack, half of it concatenates them.
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), score: 5822
```
++++++++++[>+++++++>++++++++++>+++++++++++>+++++>+++>+++++++++<<<<<<-]>++.>+.>--..>--.>++.>---.<<.<++++++.------.<-.>>>+.
```
[Try it online!](https://tio.run/##SypKzMxLK03O/v9fGw6i7aAMO4QYEhPKtkMRtQED3VigiJ4dEOnq6oEJMF8XyLCx0bOBKNXTBQM9G6CsHVDt//8A)
[Answer]
# Befunge, Score: 1385
```
"!dlr0W 0lleH">:#,_@
```
This is my first legitimate code golf so it's probably not the best. Still not sure how the scoring system works. Is lower or higher better?
[Answer]
# 80186 machine code (MS-DOS .COM format), score: 1799 (2061 bytes)
Nothing particularly special about this except that I used literal values on the stack to save score over `MOV` statements. To be able to use the same value for the function number and string location, I used just a little bit of padding.
```
68 00 09 58 50 5A CD 21 C3
(2039 zeroes) 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
48 65 6C 6C 30 20 57 30 72 6C 64 21 24
```
## TASM (ideal mode) source
```
IDEAL
P186
MODEL TINY
CODESEG
ORG 100H
MAIN:
PUSH 0900H
POP AX
PUSH AX
POP DX
INT 21H
RET
PADDING DB 7F7H DUP (0)
HELLO DB "Hell0 W0rld!$"
END MAIN
ENDS
```
[Answer]
# HTML, score: 936
```
Hell0 W0rld!
```
HTML treats any whitespace as a space.
[Answer]
# [Python 2](https://docs.python.org/2/), Score:1584
Prints the string...
```
print"Hell0 W0rld!"
```
[Try it online!](https://tio.run/##K6gsycjPM/r/v6AoM69EySM1J8dAIdygKCdFUen/fwA "Python 2 – Try It Online")
[Answer]
# [shortC](https://github.com/aaronryank/shortC), Score:1166
ShortC version of [this](https://codegolf.stackexchange.com/a/194539/85052).
```
AJ"Hell0 W0rld!"
```
[Try it online!](https://tio.run/##K87ILypJ/v/f0UvJIzUnx0Ah3KAoJ0VR6f9/AA "shortC – Try It Online")
] |
[Question]
[
**Task -** The title pretty much sums it up: raise an integer *x* to power *x*, where `0<x`.
**Restrictions:**
* Use of exponentiation, `exp()`, `ln()`, and any other powers-related language built-ins, like `pow()`, `x^x`, `x**x` is forbidden.
* You can assume that the given integer fits the limits of the programming language of your choice.
**Test cases:**
```
Input | Output
---------------
2 | 4
3 | 27
5 | 3125
6 | 46656
10 | 10000000000
```
---
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest program in bytes wins.
[Answer]
# [Python](https://docs.python.org/2/), 25 bytes
```
lambda n:eval('1'+'*n'*n)
```
[Try it online!](https://tio.run/nexus/python2#S7ON@Z@TmJuUkqiQZ5ValpijoW6orq2ulQdEmv/T8osUMhUy8xSKEvPSUzUMDTStuDgLijLzShQyddI0MjX/AwA "Python 2 – TIO Nexus")
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 4 bytes
For *xx*, takes *x* as left argument and *x* as right argument.
```
×/⍴⍨
```
[Try all cases online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/wPyy1OLgKzD0/Uf9W551LviP0RIwYgLQhtDaVMobQalDQ0A "APL (Dyalog Unicode) – TIO Nexus")
`√ó/`‚ÄÉproduct of
`⍴⍨` arg copies arg
And here here is one that handles negative integers too:
```
×/|⍴|÷1⌊|×⊢
```
[Try all cases!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkGXEBWQACQZfQ/IL88tQjIOjxdv@ZR75aaw9sNH/V01Rye/qhr0X@I7KEVBnWPelccWm9ooP2od7ORIQA "APL (Dyalog Unicode) – TIO Nexus")
`√ó/`‚ÄÉthe product of
`|`‚ÄÉabsolute value
`⍴` **r**epetitions of
`|`‚ÄÉthe absolute value
`√∑`‚ÄÉdivided by
`1‚åä` the **L**esser of 1 and
`|`‚ÄÉthe absolute value
`√ó`‚ÄÉtimes
`⊢` the argument
The built-in Power primitive is:
```
x*y
```
[Answer]
## Mathematica, 16 bytes
I've got two solutions at this byte count:
```
1##&@@#~Table~#&
```
Here, `#~Table~#` creates a list of `n` copies of `n`. Then the `List` head is replaced by `1##&` which multiplies all its arguments together.
```
Nest[n#&,1,n=#]&
```
This simply stores the input in `n` and then multiplies `1` by `n`, `n` times.
[Answer]
# R, 22 bytes
reads `x` from stdin.
```
prod(rep(x<-scan(),x))
```
generates a list of `x` copies of `x`, then computes the product of the elements of that list. When `x=0`, the `rep` returns `numeric(0)`, which is a numeric vector of length `0`, but the `prod` of that is 1, so `0^0=1` by this method, which is consistent with R's builtin exponentiation, so that's pretty neat.
[Try it online!](https://tio.run/nexus/r#@19QlJ@iUZRaoFFho1ucnJinoalToan53/Q/AA)
[Answer]
# JavaScript (ES6), ~~33~~ ~~28~~ ~~25~~ 24 bytes
```
n=>g=(x=n)=>--x?n*g(x):n
```
---
## Try It
```
f=
n=>g=(x=n)=>--x?n*g(x):n
o.innerText=f(i.value=3)()
i.oninput=_=>o.innerText=f(+i.value)()
```
```
<input id=i min=1 type=number><pre id=o>
```
---
[Answer]
# Regex `üêá` (ECMAScript+`(?^*)`[RME](https://github.com/Davidebyzero/RegexMathEngine)), 13 bytes
```
^(x(?^*x+))*$
```
Takes its input in unary, as a string of `x` characters whose length represents the number. Returns its output as the number of ways the regex can match. (The rabbit emoji indicates this output method. It can yield outputs bigger than the input, and is really good at multiplying.)
[Try it on replit.com](https://replit.com/@Davidebyzero/regex-Raise-integer-x-to-power-x-with-lookinto)
This version uses molecular lookinto, a new feature in [RegexMathEngine](https://github.com/Davidebyzero/RegexMathEngine). The basic form `(?^*`...`)` matches the expression inside it against the entire input string. (With a parameter, it evaluates it against the contents of a backreference, e.g. `(?^5*`...`)` to look into `\5`.)
On every iteration of the outer loop, there are \$n\$ possible matching states of the inner loop, and at the end of \$n\$ iterations, the match is complete. In a complete match, each iteration can independently be at any one of \$n\$ states, so there are \$n^n\$ total possible matches.
Changing the `*` at the end to `+` would make it give a result of \$0\$ for \$n=0\$.
```
^ # tail = N = input number
(
x # tail -= 1
(?^* # Non-atomic lookinto - starts with tail = N
x+ # Create a choice between N possibilities
)
)*$ # Loop as many times as possible, minimum 0. This will loop N times,
# because it subtracts 1 from tail on each iteration. The minimum of
# 0 iterations gives a correct result of 1 for N==0.
```
The constant-power \$n^k\$ version of this can be seen in [Quartic Summation](https://codegolf.stackexchange.com/questions/156100/quartic-summation/250206#250206), for which there is also a method that doesn't require non-atomic lookaround. It might be impossible to implement \$n^n\$ without non-atomic lookaround, due to it being impossible to create \$m\$ number of choices (with the value \$m\$ being accessed via a backreference) without the guarantee of having \$O(m)\$ avaiable space.
The constant-base \$k^n\$ version of this would be e.g. `^((.+)*)+` or `^(x(||))*$` for \$3^n\$.
# Regex `üêá` (PCRE2 v10.35+), 26 bytes
```
^(x((?<*(?*^x+|(?2)).)))*$
```
[Attempt This Online!](https://ato.pxeger.com/run?1=hVbNbttGED4W0FOMmdbapShXctDUEEULrizABhI7UGQ0jaIQNLmUiFBLglzGP62vfYBeeylQ9JgX6Ju0x75GL539kURbAkpY1P7MfPP3zci_fg7ztCrlx5-H4eep1U7zsGCH7SNr9tf4WcTihDN4PRyPDv3h5enIv7o4n_jfn59OzuCo8SzhYVpFDPpK6WBx3AgXQQF-Pp2BB2Pru5ubj9fPqx_u7t5OFi9uFuSPSsTtoz8_kFtCBn2bDOwPt62fyOCQ0gNKqf2lFvj7i3_pU13LATv3_LzVdWuGS1EkfC4tb86SDE9ZsDzekjtuJFxAjkvhs6LIChJmvBSgvLaXrCyDOaPwYymiXi9ECej3wRzLpTpnPEpdKJioCg5d92ELU-7DLGIOXGdZCpkXB2kpYZUZAzc9_ObFzG0APkkMRCXQnzOD4RsponGIrsDV8OxkfGRTc-lAmdyzLCZrx79endTkMa3KinxIBgMdRJhVAnqwDpTK8CylBsqDHlhPglfKloVa1ntu0XU-YmTPQkeyTkrjoVHxMplzFkGa8bl-Bby8YYWrEra888MgTdENE7vZ-ddpFn4EO3TgU5ZEYEeBCDB3MklyCZ4HRN7YdH-DQQ12q7WuTMdUZhkknCCAcjCfIhFSxklO292Z13F1CJodkIeeRQY9y8VVy8v1l0XJYIifPYrnFSI-P_QFFhV1JfwcFwq6DpTwvBJSXQWGJQS7YKv9MhDhwlex2Ju1RitYWaXC0SVwTeO9OX83UidxXDK8xHgxhLlYPBKws08sFKhlKoENuLK_zJOUEUOKN68nY5qHB6GPzhLqGIx3o_GlPxmNX51fnExGp6vj0dvJ6OJU7veVT-bbeNKhGwbvFUhAk_t6N6i3kauF7m1lw8d9IJgfF9nSzwMhWMFJgSy_uHr50gDUdbB1BbsVmMTVytt1b2DJFgpGsKbgCsKp8dLZxbOnANpUmiyTOki7S92aUMRy8b9CBQurokwyvlNQmY2zAtR0uV8zFydGiiOa6EZOuKO5R90V41V5UIV3MD2ByBKiBFblx_rzrgN5VuK1vsGRH5Fmu2mMyod3ZW5RZs-r87zX4_JwsAMXWkq-BV2KA4N3Nlh61kpznN3o3ZR3W92Zi8NmiZkgpQPN26Z0DBNU4uXMq-mvk5B4XPZg3-NdF1qtpB7xipT3FNApaYQ033MMCVOH0oqfMbG-iuCfn38B_GlJ8EqPEHSsZk33kmzKx-xSxKx3FDqdYEOovw2ncW3KSN0t5zRuvwP7-8bGnme6bjy-HPsXl69OJsMz-khR0a_WXquJIYqKPbHB8FdnS3cz_XF-m4h3THL5PDQ2712NFReMkU182w2tBdZ7Wp-I-hJnxnpg60jwp0P_D_Db7532t3r5Hw "C++ (GCC) - Attempt This Online")
This solution uses non-atomic recursion, lookahead, and lookbehind to emulate non-atomic variable-length lookbehind. The algorithm used is the same as that of the 13 byte version.
```
^ # tail = N = input number
(
x # tail -= 1
( # Define subroutine (?2)
(?<* # Non-atomic lookbehind
(?* # Non-atomic lookahead
^ # If we've reached tail==0, then:
x+ # create a choice between N possibilities.
|
(?2) # Otherwise, recursively call (?2).
)
. # tail += 1 (Go back 1 character at a time)
)
)
)*$ # Loop as many times as possible, minimum 0. This
# will loop N times, because it subtracts 1 from
# tail on each iteration. The minimum of 0 iterations
# gives a correct result of 1 for N==0.
```
The equivalent in a hypothetical engine with real (not emulated) non-atomic variable-length lookbehind would be `^(x(?<*^x+.*))*$` (**16 bytes**).
## Regex `üêá` (PCRE2 v10.35+ without lookbehind), 59 bytes
```
^(?=(x*)\1(x?))(((?*x+(?!\1)()?|\2+$))x(?(?=\2\1)(?4)))*\1$
```
[Attempt This Online!](https://ato.pxeger.com/run?1=hVbNbttGED4W0FOsmdTeJalUVNrUEE0Lji3ABhI7UGQ0jaUSNLmUFqGWBLmMZSe-9gF67aVA0WMeKD32NXrp7I8k2hJQwpL2Z-abv2-G_v1LXGR1JT_hNI6_XFntrIhL2m3vW5OvwycJTRmn6M3xcNANjy9OBuHl-dko_OnsZHSK9ltPGI-zOqHoQCk9mx224llUorC4mqAADa2XNzcfrp_XP9_evhvNXtzM8F-1SNv7X_1fcD_AC5uMPbzoE4Ix7tsLB_d3xh7BpP953HWeErLAfZAbd-Vh_3tCiD32nmqIv7_5lzxGt1xkF0FYOJ7fcK0SJeNT6dv6jOVwSqP54YbcYYtxgQpYipCWZV7iOOeVQCoue06rKppSgj5VIun1YpBABwfIHMulOqc8yXxUUlGXHHn-_Qam3Md5Ql10necZyoM0yioJq8wYuKvuDy8mfgvBw1KEVYrDKTUYoZHCGgfrGl0enx4N921iLl1UsTuap3jl-HfLk4Y8JFZZkQ_OUV8HEee1QD20CpTI8CylhpQHPWQ9Cl4pWxZoWWNukVU-UuDXTEeySkrrvlXzik05TVCW86n-inh1Q0tfJWx-G8ZRloEbJnazC6-zPP6A7NhFH3OWIDuJRAS5k0mSSxQECMsbm-yuMYjBdpxVZTqmMvOIcQwAysHiCoiQUY4L0vYmQcfXIWh2oCIOLNzvWT6snKDQPxaw8xg-OwTOa0B83g0FFBV0JfwUFgq6CcR4UQuprgKDEiK7pMv9PBLxLFSx2Ou1RitpVWfC1SXwTWu-PXs_UCdpWlG4hHghhKmYPRCw8480FqBlKgEturQ_L1hGsSHF2zejISniZ3EIzmLiGoz3g-FFOBoMX5-dH40GJ8vjwbvR4PxE7neVT-bXeNIhawbvlEBAk_tmN6hvI9cIPdjIRgj7SNAwLfN5WERC0JLjElh-fvnqlQFo6kDrCroQkMTlKth2b2DxBgpEsKLgEsJt8NLdxrPHANpUxuasCdL2iN8QSmgh_leopHFdViznWwWV2TQvkZoudyvmwsTIYIhj3ciMu5p7xF8yXpUHVHgH0hOJnGElsCw_1J97LiryCq71DbwUErzX3jNG5cM9mVuQ2QmaPO_1uDzsb8FFjpJ3kEdgYPDOGkvPWmmO0xu9u-Ke4018GDZzyASuXLS32JOOQYIquJwEDf1VEljAZQ8eBNzzkeOwZsRLUt4RBE5JI3hvzCEkSB1IK36m2Po2Qf_8-huCVwuDKz1CwLGGNd1LsikfsksRs9lR4DSDhlB_a07D2pSR-BvOadyDDtrdNTZ2AtN1w-HFMDy_eH00Oj4lDxQV_RrttZwYoqzpIxsU3jobuuvpD_PbRLxlksvnvrX-3tZYaUkpXse32dBaYLUnzYmoL2FmrAa2jgReHfp_gD_-7LR_1Mv_AA "C++ (GCC) - Attempt This Online")
This demonstrates this to be possible without the use of lookbehind or recursion. It works by emulating operation on \$n\$ within the space of \$n/2\$, using one of those halves as a counter for the outer loop, and the other half for the inner loop.
(I wrote this version on July 29, and am finally posting it now.)
```
^ # Anchor to start; tail = N = input number
(?=(x*)\1(x?)) # \1 = floor(N / 2); \2 = N % 2
(
( # Define subroutine (?4):
(?*
x+(?!\1) # Add \1 to possibility count
()? # Double the possibility count of the above
|
\2+$ # If \2==1, add 1 to possibility count
)
)
x # tail -= 1
(?(?=\2\1) # If tail ‚â• \2 + \1:
(?4) # Call subroutine (?4), to multiply its possibility
# count with the above
)
)* # For every possible iteration count, from 0 to the
# maximum, add the above to the possibility count
\1$ # Assert tail == \1
```
## Regex `üêá` (ECMAScript+`(?*)`[RME](https://github.com/Davidebyzero/RegexMathEngine) / PCRE2 v10.35+), 81 bytes
```
^(?=(x*)\1(x?))((?*x+(?!\1)(|)|\2+$)x((?=\2\1)(?*x+(?!\1)(|)|\2+$)|(?!\2\1)))*\1$
```
[Try it on replit.com](https://replit.com/@Davidebyzero/regex-Raise-integer-x-to-power-x) - RegexMathEngine
[Attempt This Online!](https://ato.pxeger.com/run?1=hVbLbttGFF0W0FeMmdSeIalUVNDUEE0Lri3ABhI7VWQ0jaUSNDmUBqGGBDmMZdfe9gO67aZA0WU-KF32N7rpnYck2hJQwpJm7uPc96V__xwXWV3JTziN489XVjsr4pJ22_vW5MvwWUJTxil6ezwcdMPji5NBeHl-Ngp_PDsZnaL91jPG46xOKDpQSi9mh614FpUoLK4mKEBD6_ubm4_XL-ufbm_fj2avbmb4r1qk7f0vP_yM-wFe2GTs4UWfEIz79sLB_Z2xR_A9uR93nedkAdRg3JWkLdx7eZdMQuyx91wD__3Vv-SpTctFdhGEheP5DYcrUTI-lR6vaSwHKo3mhxtyhy3GBSrgKEJalnmJ45xXAqlo7TmtqmhKCfqlEkmvF4MEOjhAhiyPik55kvmopKIuOfL8hw1MeY_zhLroOs8zlAdplFUSVpkxcFfdb19N_BaCh6UIq8SHU2owQiOFNQ7Wlbs8Pj0a7tvEMF1UsTuap3jl-DdLSkMeEqusyAfnqK-DiPNaoB5aBUpkeJZSQ8qDHrKeBK-ULQu0rDG3yCofKXTdTEeySkrroVXzik05TVCW86n-inh1Q0tfJWx-G8ZRloEbJnZzC6-zPP6I7NhFn3KWIDuJRAS5k0mSRxQECEuOTXbXGMRgO86qMh1TmXnEOAYA5WBxBY2QUY4L0vYmQcfXIejuQEUcWLjfs3w4OUGhfyxo22P47BCg14D4shsKKCroSvgpHBR0E4jxohZSXQUGJUR2SZf3eSTiWahisddnjVbSqs6Eq0vgm4F9d_ZhoChpWlFgQrwQwlTMHgnY-ScaC9AylYDBXdqfFyyj2DTFu7ejISniF3EIzmLiGowPg-FFOBoM35ydH40GJ0vy4P1ocH4i77vKJ_NrPOmQdQfvlNCAJvfNaVDfRq4RerCRjRDukaBhWubzsIiEoCXHJXT5-eXr1wagqQOjK-hCQBKXp2Ab38DiDRSIYNWCSwi30Zfutj57CqBNZWzOmiBtj_gNoYQW4n-FShrXZcVyvlVQmU3zEqntcrfqXNgYGax2rAeZcVf3HvGXHa_KAyq8A-mJRM6wEliWH-rPPRcVeQVszYFXRYL32nvGqHy4J3MLMjtBs897PS6J_S24yFHyDvIILAzeWWPpXSvNcXqjb1fcc7yJD8tmDpnAlYv2FnvSMUhQBcxJ0NBfJYEFXM7gQcA9HzkOa0a8bMo7gsApaQTvjTmEBKkDadWfKba-TtA_v_6G4NXCgKVXCDjWsKZnSQ7l4-5SjdmcKHCawUCov3VPw9mUkfgbzmncgw7a3TU2dgIzdcPhxTA8v3hzNDo-JY8UVfs1xmu5MURZ0yc2KLx1NnTX2x_2t4l4yyaXz0Nr_b1tsNKSUryOb3OgtcDqTpobUTNhZ6wWto4EXh36f4A__uy0v9PH_wA "C++ (GCC) - Attempt This Online") - PCRE2 v10.40+
This is a port of the 59 byte version. Basic ECMAScript lacks not only lookbehind, but subroutine calls and conditionals as well. The only feature added to basic ECMAScript is `(?*`...`)`, molecular lookahead (a.k.a. non-atomic lookahead). Note that `(|)` must be used instead of `()?` due to ECMAScript's [no-empty-optional](https://github.com/Davidebyzero/RegexMathEngine/issues/1) rule.
(I wrote this version on July 29, and am finally posting it now.)
```
^ # Anchor to start; tail = N = input number
(?=(x*)\1(x?)) # \1 = floor(N / 2); \2 = N % 2
(
(?* # Define "subroutine":
x+(?!\1) # Add \1 to possibility count
(|) # Double the possibility count of the above
|
\2+$ # If \2==1, add 1 to possibility count
)
x # tail -= 1
# Multiply the above possibility count with the following:
( # Emulated conditional, upon whether tail ‚â• \2 + \1
(?=\2\1) # If yes:
# Call "subroutine" (duplicates it, since this regex flavor lacks
# subroutine calls) to multiply with the above possibility count
(?*
x+(?!\1)
(|)
|
\2+$
)
|
(?!\2\1) # If no: Use possibility multiplier of 1
)
)* # For every possible iteration count, from 0 to the
# maximum, add the above to the possibility count
\1$ # Assert tail == \1
```
[Answer]
# Pure bash, 43
```
echo $[$1<2?1:$[$1<2?2:$1]#`printf 1%0$1d`]
```
[Try it online](https://tio.run/nexus/bash#S8svUihJLS5JTixOVcjMU6g21NMzNK21VkjJ51IAgoKizLySNAUl1RQFXTsFJQUVmGKwbHFqiYKuLkLwf2pyRr6CSrSKoY2RvaEVlGFkpWIYq5wANcpQ1UDFMCUh9n9Kfl7qfwA).
Not sure if this is bending the rules too much - I'm not using any of the listed banned builtins, but I am using base conversion.
* `printf 1%0$1d` outputs a `1` followed by n `0`s
* `$[b#a]` is an arithmetic expansion to treat `a` as a base `b` number, which gives the required result. Unfortunately base <2 does not work, so the extra `?:` bits handle input n=1.
Maximum input is 15, because bash uses signed 64-bit integers (up to 231-1).
[Answer]
# [Standard ML](http://sml-family.org/), 42 bytes
```
fn x=>foldl op*1(List.tabulate(x,fn y=>x))
```
[Try it online!](https://tio.run/nexus/sml-mlton#K0vMUSjIL08tUrD9n5anUGFrl5afk5KjkF@gZajhk1lcoleSmFSak1iSqlGhA1RQaWtXoan531qhoCgzr0RBwzMPqCI/uATIS1fQgJhkpqlp/R8A "Standard ML (MLton) – TIO Nexus")
Explanation:
```
fn y => x (* An anonymous function that always returns the inputted value *)
List.tabulate(x, fn y=>x) (* Create a list of size x where each item is x *)
foldl op* 1 (* Compute the product of the entire list *)
```
[Answer]
## [Alice](https://github.com/m-ender/alice), 13 bytes
```
/o
\i@/.&.t&*
```
[Try it online!](https://tio.run/nexus/alice#@6@fzxWT6aCvp6ZXoqb1/78ZAA "Alice – TIO Nexus")
### Explanation
```
/o
\i@/...
```
This is a framework for programs that read and write decimal integers and operate entirely in Cardinal mode (so programs for most arithmetic problems).
```
. Duplicate n.
&. Make n copies of n.
t Decrement the top copy to n-1.
&* Multiply the top two values on the stack n-1 times, computing n^n.
```
[Answer]
# [Nibbles](http://golfscript.com/nibbles/index.html), ~~3~~ 2.5 bytes (~~6~~ 5 nibbles)
```
`*^$_
```
[Attempt This Online!](https://staging.ato.pxeger.com/run?1=m708LzMpKSe1eMGCpaUlaboWSxO04lTiIWyo0IKFxhAGAA "Nibbles - Attempt This Online")
Returns the correct answer of \$1\$ for an input of \$0\$, as it is generally accepted that \$0^0=1\$ (even though this challenge doesn't require it, and several of the other answers take advantage of this and return \$0\$, or loop infinitely, for an input of \$0\$).
The ASCII representation uses `^`, but in this context it's a Replicate operator, not exponentiation.
Explanation, shown with example input of 7:
```
`*^$_
_ # Input coerced to a list: [7]
$ # Input: 7
^ # Replicate: [7, 7, 7, 7, 7, 7, 7]
`* # Product (returns 1 for an empty list): 823543
```
The builtin is just **0.5 bytes (1 nibble)**:
```
^
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m708LzMpKSe1eMGCpaUlaboWC-MgNJS7YKE5hAEA "Nibbles - Attempt This Online")
[Answer]
# [Uiua](https://uiua.org), 4 [bytes](https://www.uiua.org/pad?src=U0JDUyDihpAgK0BcMOKKlwpEZWNvZGUg4oaQIOKHjOKKjy0x4pa9wrEu4o2Y4ouv4oav4oqCwq8x4qe74ouv4qe7LOKHjOKItSjihpjCrzHii68rMjU2KSAtQFwwKzEKJnAg4oqCIjggYml0IGVuY29kaW5nOlx0IiBTQkNTICLih4ziio8tMeKWvcKxLuKNmOKLr-KGr-KKgsKvMeKnu-KLr-Knuyzih4ziiLUo4oaYwq8x4ouvKzI1NikiIOKKgitAXDDih6ExMjkiLiziiLY74oiYwqzCscKv4oy14oia4peL4oyK4oyI4oGFPeKJoDziiaQ-4omlKy3Dl8O34pe_4oG_4oKZ4oan4oal4oig4qe74paz4oeh4oqi4oeM4pmt4ouv4o2J4o2P4o2W4oqa4oqb4oqd4pah4oqU4omF4oqf4oqC4oqP4oqh4oav4oaZ4oaY4oa74per4pa94oyV4oiK4oqXL-KIp1xc4oi14omh4oi64oqe4oqg4o2l4oqV4oqc4oip4oqT4oqD4oqZ4ouF4o2Y4o2c4o2a4qyaJz_ijaPijaQh4o6L4oas4pqCzrfPgM-E4oiefl9bXXt9KCnCr0AkXCLihpB8IyIKJnAg4oqCImRlY29kZWQ6XHQiIERlY29kZSAiwqPCsS0xwrjChy7DjMKlwrPCsMKIMcKfwqXCnyzCo8K_KMK1wogxwqUrMjU2KSIg4oqCK0BcMOKHoTEyOSIuLOKItjviiJjCrMKxwq_ijLXiiJril4vijIrijIjigYU94omgPOKJpD7iiaUrLcOXw7fil7_igb_igpnihqfihqXiiKDip7vilrPih6HiiqLih4zima3ii6_ijYnijY_ijZbiipriipviip3ilqHiipTiiYXiip_iioLiio_iiqHihq_ihpnihpjihrvil6vilr3ijJXiiIriipcv4oinXFziiLXiiaHiiLriip7iiqDijaXiipXiipziiKniipPiioPiipnii4XijZjijZzijZrirJonP-KNo-KNpCHijovihqzimoLOt8-Az4TiiJ5-X1tde30oKcKvQCRcIuKGkHwjIg==)
```
/√ó‚ñΩ.
```
[Try it!](https://uiua.org/pad?src=f%20%E2%86%90%20%2F%C3%97%E2%96%BD.%0A%0Af%203%0Af%204%0Af%205%0Af%206)
```
‚ñΩ. # list of N Ns
/√ó # product
```
Note: can also do /√ó‚ÜØ.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 3 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ẋ⁸P
```
**[Try it online!](https://tio.run/nexus/jelly#@/9wV/ejxh0B////NwUA "Jelly – TIO Nexus")**
### How?
```
ẋ⁸P - Main link: x e.g. 4
⁸ - link's left argument, x 4
ẋ - repeat left right times [4,4,4,4]
P - product 256
```
[Answer]
# [Cubix](https://github.com/ETHproductions/cubix), 19 bytes
```
..@OI:1*s;pu!vqW|($
```
[Try it online!](https://tio.run/nexus/cubix#@6@n5@DvaWWoVWxdUKpYVhheo6Hy/7@hAQA "Cubix – TIO Nexus")
[Step by Step](https://ethproductions.github.io/cubix/?code=ICAgIC4gLgogICAgQCBPCkkgOiAxICogcyA7IHAgdQohIHYgcSBXIHwgKCAkIC4KICAgIC4gLgogICAgLiAuCg==&input=Mwo=&speed=20)
Expands out onto a cube with side length 2
```
. .
@ O
I : 1 * s ; p u
! v q W | ( $ .
. .
. .
```
* `I:1` Takes the input, duplicates it and pushs 1. This sets up the stack with a counter, multiplier and result.
* `*s;` Multiples the TOS, swaps the result with previous and remove previous.
* `pu` Bring the counter item to the TOS. U-turn. This use to be a lane change, but needed to shave a byte.
* `|($` This was done to save a byte. When hit it skips the decrement. reflects, decrements the counter and skips the no op wrapping around the cube.
* `!vqW` Test the counter. If truthy skip the redirect, put the counter on BOS, change lane back onto the multiplier. Otherwise redirect.
* `|sO@` this is the end sequence redirected to from counter test. Goes past the horizontal reflect, swaps the TOS bringing result to the TOS, ouput and halt.
[Answer]
# Ruby, ~~20~~ 18 bytes
-2 bytes because the spec changed and I no longer need an exponent argument.
```
->x{eval [x]*x*?*}
```
[Try it online!](https://tio.run/nexus/ruby#S7ON@a9rV1GdWpaYoxBdEatVoWWvVfu/oLSkWCEtOj21pFivJD8@M/a/CQA "Ruby – TIO Nexus")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 3 bytes
```
.DP
```
[Try it online!](https://tio.run/nexus/05ab1e#@6/nEvD/vxkA "05AB1E – TIO Nexus") or [Try all examples](https://tio.run/nexus/05ab1e#K6us/K/nEvBf53@0kY6xjqmOmY6hQSwA "05AB1E – TIO Nexus")
```
.D # pop a,b push b copies of a
# 05AB1E implicitly takes from input if there aren't enough values on the stack
# For input 5, this gives us the array: [5,5,5,5,5]
P # Take the product of that array
# Implicit print
```
[Answer]
# x86\_64 machine language for Linux, ~~14 11~~ 10 bytes
```
0: 6a 01 pushq $0x1
2: 58 pop %rax
3: 89 f9 mov %edi,%ecx
5: f7 ef imul %edi
7: e2 fc loop 5
9: c3 retq
```
To [Try it online!](https://tio.run/##FYrNDoIwEITvfYpJE5JdwQP@YpAncT2Q1UoPFoMcmhievZbDl28yM7p9qaakY/jO0KGfMNzunZV46qWWeGwkNheJbuUs8ekyu5xVou5ta4wPM969D8Q/A7hxIqyVR4e6zbrikFWWYKwH4DPl3RFs8UDxkGAr@ApEuaUNE/PA5Bnc5vdiFpPSHw "C (gcc) – Try It Online"), compile and run the following C program.
```
const char h[]="\x6a\1\x58\x89\xf9\xf7\xef\xe2\xfc\xc3";
int main(){
for( int i = 1; i < 4; i++ ) {
printf( "%d %d\n", i, ((int(*)())h)(i) );
}
}
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 2 bytes
```
ẋΠ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLhuovOoCIsIiIsIjYiXQ==)
[Answer]
# [Desmos](https://www.desmos.com), ~~19~~ 17 bytes
```
f(x)=‚àè_{n=1}^xx
```
[Try it on Desmos!](https://www.desmos.com/calculator/qqjpk4olhz)
The `^` is not used for exponentation in this case.
-2 bytes thanks to [Aiden Chow](https://codegolf.stackexchange.com/users/96039/aiden-chow).
[Answer]
# [Stacked](https://github.com/ConorOBrien-Foxx/stacked), 10 bytes
```
{!1[n*]n*}
```
[Try it online!](https://tio.run/nexus/stacked#@1@taBidpxWbp1X7X4lLw0jBWMFUwUzB0ECTK0ZBUSG/tOQ/AA "Stacked – TIO Nexus")
Two-argument exponentiation for the same size:
```
{%1[x*]y*}
```
Both are functions. Repeats a function that multiplies `1` by `n` `n` times.
[Answer]
# [Scala](http://www.scala-lang.org/), ~~32~~ 26 bytes
```
n=>List.fill(n)(n).product
```
[Try it online!](https://tio.run/nexus/scala#HYxBCsIwEEWvMstkM@hWacGlUFceQGI60ZE4E5KpCOLZa@3y8977en1QNDgFFqC3kYwNDqXAB14hQ9rBUQy6HgaVG3QwS9cP3AwT5@zEO0HTP/NYqo5TtHm/ls4vNiuedaqRsNnIgjeygYUaPkNxl6Vczv06kseklUK8u1JZLIuH77zd/AA "Scala – TIO Nexus") (Added conversion to long in the TIO so it wouldn't overflow on n=10.)
[Answer]
# [Haskell](https://www.haskell.org/), ~~24~~ ~~23~~ 21 bytes
```
f y=product$y<$[1..y]
```
[Try it online!](https://tio.run/nexus/haskell#y03MzFOwVcjMK0ktSkwuUVBRKM7IL1fQU8hNLFBIA9JFqYkp/9MUKm0LivJTSpNLVCptVKIN9fQqY///jzbUMdIx1jHRMdUx0zE0iAUA "Haskell – TIO Nexus")
* Saved 1 byte, thanks to [Laikoni](https://codegolf.stackexchange.com/users/56433/laikoni)
* Saved 2 bytes, thanks to [nimi](https://codegolf.stackexchange.com/users/34531/nimi)
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 4 bytes
```
ÆUÃ×
```
[Try it online!](http://ethproductions.github.io/japt/?v=1.4.5&code=xlXD1w==&input=Ng==)
## Explanation
```
ÆUÃ× // implicit: U = input integer
Uo{U} r*1 // ungolfed
Uo{ } // create array [0, U) and map each value to...
U // the input value
r*1 // reduce with multiplication, starting at 1
// implicit output of result
```
[Answer]
# x86 machine code (Linux), 18 bytes
```
31 c0 ff c0 31 db 39 df 74 07 0f af c7 ff c3 eb f5 c3
```
It expects a C declaration as follows `extern int XpowX(int)`.
### Disassembled
```
XpowX:
# edi : input register
# ebx : counter
# eax : result register
xor %eax, %eax # result = 0
inc %eax # result += 1
xor %ebx, %ebx # counter = 0
loop:
cmp %ebx, %edi # if (counter == input)
je done # return result
imul %edi, %eax # result *= input
inc %ebx # counter += 1
jmp loop
done:
ret
```
[Answer]
# [Flurry](https://github.com/Reconcyl/flurry), 16 bytes
```
<>{{}}<<>()>{}{}
```
### Run example
```
$ ./flurry -nin -c "<>{{}}<<>()>{}{}" 4
256
$ ./flurry -nin -c "<>{{}}<<>()>{}{}" 5
3125
```
Multiply `n` `n` times to 1. The lambda expression is `n (\x. \y. n (x y)) I` where `\y. n (x y)` or `n ‚àò x` is the product of Church numeral of `n` and `x`, and its SKIB-transformation is as follows:
```
n (\x. \y. n (x y)) I
S I (\n. \x. \y. n (x y)) n I
S I (\n. \x. S (K n) x) n I
S I (\n. S (K n)) n I
S I (S ‚àò K) n I
```
So the direct translation of this expression into Flurry gives the code above.
Expanding the `S` in front gives `n ((S ‚àò K) n) I`, which does not change bytes:
```
({})[<<>()>{}]{}
```
If direct exponentiation is allowed, it is **6 bytes**: `({}){}` (pop n, push n, pop n; evaluates to `n n`), because `n m` evaluates to `m^n` when `n` and `m` are Church numerals.
[Answer]
# [Arn](https://github.com/ZippyMagician/Arn), [8 bytes](https://github.com/ZippyMagician/Arn/wiki/Carn)
```
xõPÑ_=>$
```
# Explained
Unpacked: `*v{_}\1=>`
```
\ Fold...
* ...with multiplication after...
v{ ...mapping with key of v...
_ ...by replacing with input
} End map
1 Literal one
=> inclusive range to...
_ ...input, implied
```
[Answer]
# [Rust](https://www.rust-lang.org/), 37 bytes
```
|x|(|mut y|{for _ in 1..x{y*=x}y})(x)
```
[Try it online](https://tio.run/##Xc3BDoIwDIDh@56icuqMEgaBGFSOvIbxwCKJDDNGHNn27HO7LIZbmy/9K9dFeS5geo4CKRgCoIZFobfaop1WBZs1fJbwgFEAy3NttuNdu81R1NQD0CtxhIRCPLv1HfIWekq@r0EOIdaHTeDKyguFcwdxIPHJR45CvcUBs7IF47ITcCxpiP1TlajaU52o3lOTqNkTK5KxIqLzPw)
This might be able to be shortened once [bindings\_after\_at](https://github.com/rust-lang/rust/issues/65490) stabilizes by using `|mut y@x|` instead.
[Answer]
# [Perl 5](https://www.perl.org/) + `-p`, 17 bytes
```
$_=eval"$_*"x$_.1
```
[Try it online!](https://tio.run/##K0gtyjH9/18l3ja1LDFHSSVeS6lCJV7P8P9/Iy5jLlMuMy5Dg3/5BSWZ@XnF/3ULcgA "Perl 5 – Try It Online")
[Answer]
# [1+](https://esolangs.org/wiki/1%2B), ~~29~~ ~~27~~ ~~25~~ 24 bytes
```
1."1##/"\*\1+\"/^"/<1+#:
```
This was already shockingly short, given how messy it is to create a halting loop... I did a poor job on stack manipulation, so it can probably be improved.
## Special notes on 25 -> 24
>
> **Remember that you're programming in brainfuck.** It's tempting to avoid confusion and tedium by thinking in terms of higher-level abstractions as much as possible, rather than thinking in brainfuck. This can buy enough control to make a working program, usually at the cost of such inefficiencies as:
> -excessive pointer movement, sometimes as simple as ">+<->" and sometimes less apparent; often a result of doing things in an intuitively appealing order. -- Daniel B. Cristofani
>
>
>
This applies to 1+ as well. I designed this program with pseudo-code, which results in two consecutive `/`s - cuz there are only three elements on the stack, replacing it with `\` saves one byte.
[Answer]
# [Thunno](https://github.com/Thunno/Thunno) `D`, \$5\log\_{256}(96)\approx\$ 4.12 bytes
```
ZOA*P
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72sJKM0Ly9_abSSi1LsgqWlJWm6Fkuj_B21AiBsqNCChaYQBgA)
Note: the built-in solution would have been just one character: `^` or `@` (either would work).
#### Explanation
```
ZOA*P # Implicit input
ZO # Wrap the input in a list
A* # Repeat it input times
P # Take the product of this list
# Implicit output
```
[Answer]
# [Fortran (GFortran)](https://gcc.gnu.org/fortran/), 73 bytes
```
integer(selected_int_kind(32))::n
read*,n;print*,product([(n,j=1,n)]);end
```
[Try it online!](https://tio.run/##LYpLDkBAEAX3bmHXIyPx2REnERHRbfzySBvnHxJ2laqaDvU6IHXTByEs8OJE6ZJdRi/cv6LfFjCVhTFVhUhl4MSiPvVNiT314Hv01BLs2uQWpjO1gEP8D/PthPC5PHsA "Fortran (GFortran) – Try It Online").
Uses a larger integer type because the implicit integer type overflows doing `10**10`. This solution can compute results up to `170141183460469231731687303715884105727`.
We make an inline anonymous array of `n`s : `[(n,j=1,n)]`, take the `product()`, and `print` the result.
] |
[Question]
[
Write a program or function which takes a string of text as input and outputs the number of non-alphabetical characters in it (standard I/O rules apply). A non-alphabetical character is any character not appearing in this string:
```
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
```
In terms of ASCII character codes, that's anything not in ranges 65-90 inclusive or 97-122 inclusive.
## Rules
Your program must be able to handle all of printable ASCII, as well as any characters that appear in your code. In other words, you may assume input will not contain any characters iff they are in neither printable ASCII nor your solution. Printable ASCII here means ASCII's character codes 32-126 inclusive as well as character code 10 (Meaning you *will* have to count spaces and newlines).
You may assume that input will not be empty.
## Scoring
Your score is the number of non-alphabetical characters (not bytes!) in your code. Lowest score wins, with [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") as a tie-breaker.
## Examples
```
"input" => output
"example" => 0
"3xampl3" => 2
"Hello, World!" => 3
"abc.def-" => 2
" " => 5
"IT'S NORMAL" => 2
"•¥¥€???!!!" => 10
"abc
def" => 1
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), score 0, 4 bytes
```
kLFL
```
Yes, you heard me right. Flagless, score 0, 4 bytes.
## Explanation
```
kLFL
kL Uppercase and Lowercase alphabet
F Filter out the input
L Take the length of that
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJrTEZMIiwiIiwiSGVsbG8sIFdvcmxkISJd) |
[3 bytes with flag](https://vyxal.pythonanywhere.com/#WyJsIiwiIiwia0xGIiwiIiwiSGVsbG8sIFdvcmxkISJd)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal) -v, 36 bytes, score 0
```
CastLengthFilterqNotCountaUppercasei
```
[Try it online!](https://tio.run/##S85ILErOT8z5/985sbjEJzUvvSTDLTOnJLWo0C@/xDm/NK8kMbSgILUoObE4NfP//2glJaXEpGSulNQ0ICv2v24ZAA "Charcoal – Try It Online") Explanation: Charcoal's verbose parser is somewhat lax, not always requiring things like parentheses, spaces, commas, or correct capitalisation. The verbose program would be more conventionally written something like this:
```
Print(Cast(Length(Filter(q, Not(Count(a, Uppercase(i)))))));
```
`q` is the first input, `a` is the predefined variable for the uppercase alphabet and `i` is the default outer loop variable.
[Answer]
# [Husk](https://github.com/barbuz/Husk), Score 0, ~~13~~ 11 bytes\*
```
mLfopVDkDma
```
[Try it online!](https://tio.run/##yygtzv6f@6ip8X@uT1p@QZhLtktu4v///6OVUisScwtyUpV0lIzBLGMgyyM1JydfRyE8vygnRRHIT0xK1ktJTdMFMhVAAEh7hqgHK/j5B/k6@gB5jxoWHVp6aOmjpjX29vaKilA9MXlATUqxAA "Husk – Try It Online")
The basic idea is to filter for non-alphabetic characters and calculate the length. [Husk](https://github.com/barbuz/Husk) has a builtin (`D`) to identify uppercase characters, and we can convert the lowercase characters to uppercase first using `a`.
But now we need to filter to keep only falsy elements. This isn't very straightforward in [Husk](https://github.com/barbuz/Husk): the builtin 'NOT' command is the (non-alphabetic) `¬` character, so we need to engineer an alternative to this.
This is accomplished here by first grouping elements into lists, and getting the index of the first truthy element of each list (so, lists of truthy elements return `1` and lists of falsy elements return `0` for 'not found'). After this, getting prime factors (`p` command) was the trick: this returns a non-empty list (=truthy) containg a single `0` element for `0`, and an empty list (=falsy) for `1`.
And a few other little tricks to get the length of the resulting single-element list.
Altogether:
```
FYmLfopVDkDma
m # Map across each character in the input:
a # convert to uppercase;
k # now, group the characters by:
D # are they an uppercase letter?
# (zero for non-uppercase letters, ASCII value for uppercase letters);
f # now filter this list by:
o # the combination of these two commands:
VD # first index of an uppercase letter (or zero if not found)
p # prime factors of this (so non-empty list for groups of non-letters, empty otherwise)
# Now we've got a single-element containing all the
# non-alphabetic characters of the input, or an empty list if there aren't any.
# We need to get the length of this single element (or zero if there isn't one).
m # So: map across this list (it only has one element)
L # getting the element length(s)
# Output formatting:
F # Fold across this (single-element) list of lengths,
Y # getting the maximum value (so the value of the only element)
```
---
\*outputs an empty list for zero non-alphabetic characters, and a single-element list containing the number of non-alphabetic characters otherwise. Add 2 bytes (`FY`) to output the number of non-alphabetic characters in a non-listed fashion [Try it online!](https://tio.run/##yygtzv6f@6ip8b9bZK5PWn5BmEu2S27i////o5VSKxJzC3JSlXSUjMEsYyDLIzUnJ19HITy/KCdFEchPTErWS0lN0wUyFUAASHuGqAcr@PkH@Tr6AHmPGhYdWnpo6aOmNfb29oqKUD0xeUBNSrEA "Husk – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), score: 0 (7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage))
```
ADuJSKg
```
[Try it online](https://tio.run/##yy9OTMpM/f/f0aXUK9g7/f9/j9ScnHwdhfD8opwURQA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeV/R5fSQ6uDvdP/6/yPVsrMKygtUdJRSq1IzC3ISQWyjMEsYyDLIzUnJ19HITy/KCdFEchPTErWS0lN0wUyFUAASHuGqAcr@PkH@Tr6AHmPGhYdWnpo6aOmNfb29oqKUD0xeUBNQCbQXi@gtUDW4YUX9qQrxQIA). (The `J`oin in the test suite has been replaced with a concat `«`, because it would otherwise join the input that's already on the stack with it.)
The straight-forward shortest approach would be 3 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) with a score of 2:
```
áмg
```
[Try it online](https://tio.run/##yy9OTMpM/f//8MILe9L///dIzcnJ11EIzy/KSVEEAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXL/8MLL@xJ/6/zP1opM6@gtERJRym1IjG3ICcVyDIGs4yBLI/UnJx8HYXw/KKcFEUgPzEpWS8lNU0XyFQAASDtGaIerODnH@Tr6APkPWpYdGjpoaWPmtbY29srKkL1xOQBNQGZji6lXsHe6UAW2HqlWAA).
**Explanation:**
```
A # Push the lowercase alphabet
D # Duplicate it
u # Uppercase the copy
J # Join the two alphabet on the stack together
S # Convert it to a list of characters
K # Remove all those characters from the (implicit) input-string
g # Pop and push the length to get the amount of remaining non-letters
# (which is output implicitly as result)
á # Only leave all letters of the (implicit) input-string
м # Remove all those letters from the (implicit) input-string
g # Pop and push the length to get the amount of remaining non-letters
# (which is output implicitly as result)
```
[Answer]
# [Pip](https://github.com/dloscutoff/pip), score 0, 8 bytes
```
oMSaRMXA
```
[Try It Online!](https://dso.surge.sh/#@WyJwaXAiLG51bGwsIm9NU2FSTVhBIiwiIiwiXCJBQjlcbkBBXCIiLCIiXQ==)
-3 thanks to DLosc.
```
RM # Remove...
XA # Letters
a # From input
MS # Sum result when mapping each to...
o # 1
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), Score 0, ~~14~~ 11 bytes
```
lfqZhxGrTZQ
```
[Try it online!](https://tio.run/##K6gsyfj/PyetMCqjwr0oJCrw/38lj9ScnHwdhfD8opwURSUA "Pyth – Try It Online")
`G` is the lowercase alphabet in Pyth. There's no built-in for the uppercase alphabet, so we convert each letter of the input to lowercase.
**Explanation**
`f ... Q` Filter for elements of the input where...
`xGrTZ` ...the index of the lowercased letter in the lowercase alphabet ...
`h` ...plus one...
`qZ` ... equals 0
(This works because `x` returns -1 for elements not in the string, like in Python)
`l` Length of the resulting list
[Answer]
# [R](https://www.r-project.org/), score 9, 38 bytes
```
function(x)sum(!tolower(x)%in%letters)
```
[Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP0@jQrO4NFdDsSQ/J788tQjIVc3MU81JLSlJLSrW/J@mkZqjUVxSVFyQk1mioZRakZhbkJOqpKOkpKmpqaxga6dgwIWmxhisxhhZjRG6Go/UnJx8HYXw/KKcFEVklcboKhOTkvVSUtN08RqnAALIKkzRVXiGqAcr@PkH@Tr64DXpUcOiQ0sPLX3UtMbe3l5REcVthgZYHMcFdByKIjQ16sQFtDrEiP8A "R – Try It Online")
Takes input as a vector of characters.
---
# [R](https://www.r-project.org/), score 14, 85 bytes
```
function(x)nchar(gsub("[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ]","",x))
```
[Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP0@jQjMvOSOxSCO9uDRJQyk6MSk5JTUtPSMzKzsnNy@/oLCouKS0rLyissrRydnF1c3dw9PL28fXzz8gMCg4JDQsPCIyKlZJR0lJp0JT83@ahlJqRWJuQU6qkqaygq2dggEXUMgYLGQMFTICCXmk5uTk6yiE5xflpChCJYxBEkD79YAO0EVWrAACUAFTkIBniHqwgp9/kK@jD7K6Rw2LDi09tPRR0xp7e3tFRZi5hgZQg7mABsPEgELqNAkDdc3/AA "R – Try It Online")
Takes input as a proper string.
[Answer]
# [Burlesque](https://github.com/FMNSSun/Burlesque), Score 0, 9 bytes
```
qrdfnsait
```
[Try it online!](https://tio.run/##SyotykktLixN/V@trmRtbaio@L@wKCUtrzgxs@R/bXjOf6XUisTcgpxUJQVbOwUDLiVjMNcYzDXiUvJIzcnJ11EIzy/KSVEECxpzKSUmJeulpKbpwhQpgACYY8ql5BmiHqzg5x/k6@gDk3/UsOjQ0kNLHzWtsbe3V1SEmGNoADZIAWgQhA8A "Burlesque – Try It Online")
```
qrd # Quoted isalpha
fn # Filter not
sa # Non-destructive length (ordinary length is L[)
it # Drop everything but the top of stack
```
Absolute shortest doing the same thing would be:
```
`FrdL[
`F # Filter not
rd # isalpha
L[ # Length
```
For fun, the inverse challenge:
```
^^ ^^ ^^ ^^ ^^ # Create 5 copies
).%++\/ # Count isPunctuation; add; swap
).*++.+\/ # Count isSymbol; add; swap
)<>++.+\/ # Count isDigit; add; swap
" "~?)-])**++32./.+\/ # Count spaces; add; swap (is whitespace is "ra")
" "~?)-])**++9./.+\/ # Count tabs; add; swap
"
"~?)-])**++10./.+ # Count newlines; add; swap
```
[Try it online!](https://tio.run/##SyotykktLixN/V@trmRtbaio@D8ODrg09VS1tWP0gbSWtrYemGVjB2UpKSjV2WvqxmpqAeWMjfT0IaKcSKKWMEEuJEFDA5Do/9rwnP9KqRWJuQU5qUoKtnYKBlxKxmCuMZhrxKXkkZqTk6@jEJ5flJOiCBY05lJKTErWS0lN04UpUgABMMeUS8kzRD1Ywc8/yNfRByb/qGHRoaWHlj5qWmNvb6@oCDHH0ABskALQIAgfAA "Burlesque – Try It Online")
[Answer]
# Java, score: 14 (46 bytes)
```
s->s.filter(c->!Character.isLetter(c)).count()
```
Input as a Character-stream.
Doesn't work if the input contains non-ASCII letters (e.g. `é`), but that's allowed according to the challenge rules.
[Try it online.](https://tio.run/##lVDBTgIxFLzzFW/3YhvYXrhBhBgukgAmYuJBPTy6XSx22822ixpCYvwUE25@BZ/Cj6yPFbx7aWde5k1nusI1Jqv0pZYGvYcpartpAWgbVJmhVDA7UgDj7BIkW5FcVEEb4UOpMBdjG@YNAs/7pNy26PABg5YwAwuXtU8GXmTakCGTySAaPWOJkpjQfqJCM@ZcSFfZwHjdPxoU1cKQwcln7XQKOSVj9JS2y4cn5L@pMleyNZYQlA8j9Ap6YNUrnGWbWNuiCnEnVm@YF0YR6jaoS@haGeM6cO9Kk0bEcSFFqrKE4NEb6B7fXcxhdnM7vZoQO3x87Xf73eHzezgcRtFp59HSEsH/9Yy3vGkAMH/3QeXCVUEUFDsYy8512nEP4rYV8m8iJLl6xvnps7f1Dw)
**Explanation:**
```
s-> // Method with IntStream parameter & long return
s.filter(c-> // Filter the character of the input-stream by:
!Character.isLetter(c)) // It's NOT a letter
.count() // Count how many are left
```
[Answer]
# [Haskell](https://www.haskell.org/), score 6, 81 bytes
```
length.filter(flip notElem"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P802JzUvvSRDLy0zpyS1SCMtJ7NAIS@/xDUnNVcpMSk5JTUtPSMzKzsnNy@/oLCouKS0rLyissrRydnF1c3dw9PL28fXzz8gMCg4JDQsPCIySknzf25iZp5tSj6XgkJBUWZeiYKKQpqCEm5rYsiyJ0ZJU@k/AA "Haskell – Try It Online")
The non-alphabetic characters are `.( "")`.
Also score 6, but 4 bytes longer is:
```
fmap length$filter$flip notElem"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
```
[Try it online!](https://tio.run/##nc1HDsIwEADAO69YWf5GDpTQQu@gXAzxxibrQmLq580TkJgPjBJNJYlixASN8EDSlkFx1BRkzZG0B@tCStIwcb4UEkulrxUZ6/ytbsL98Xy9P@1Ot5f2B8PROJtMZ/PFcrXebHf7w/HEohHaJoVrAfha2wAcENiPKv/ryhmLXw "Haskell – Try It Online")
[Answer]
# [Factor](https://factorcode.org/), score 5 (82 bytes)
```
readln "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"without length pprint
```
[Try it online!](https://tio.run/##Hc05FoIwEADQq8zjCnRauSIuuCBuXYABoiEJySDg5aPP7ne/YBkp45I4jIIRcAXaINGgDZcEFpsWZYb2J7IwdgZZLiR4LM1yLMqKP1@ilko3xlL77vrhM5nO5otlsArXm@0u2h@Op/icXK63@8PrOFWqJRAoS6pA/w/n/J7VWvhf "Factor – Try It Online")
For once I can get a better score by reading from standard input!
[Answer]
# JavaScript (in Browser), Score 4, 120 bytes
```
eval(atob`ZXZhbCgicyAgPSIrICAiPnMubWEiKyAidGNoKCIrICIvWyIrICAiXmEtekEtWiIrICJdLyIrImcpPyIrICIubCIrImVuZyIrInRoIHwgMCIp`)
```
```
f = eval(atob`ZXZhbCgicyAgPSIrICAiPnMubWEiKyAidGNoKCIrICIvWyIrICAiXmEtekEtWiIrICJdLyIrImcpPyIrICIubCIrImVuZyIrInRoIHwgMCIp`)
console.log(f("example" )) // 0
console.log(f("3xampl3" )) // 2
console.log(f("Hello, World!")) // 3
console.log(f("abc.def-" )) // 2
console.log(f(" " )) // 5
console.log(f("IT'S NORMAL" )) // 2
console.log(f("•¥¥€???!!!" )) // 10
console.log(f("abc\ndef" )) // 1
console.log(f("eval(atob`ZXZhbCgicyAgPSIrICAiPnMubWEiKyAidGNoKCIrICIvWyIrICAiXmEtekEtWiIrICJdLyIrImcpPyIrICIubCIrImVuZyIrInRoIHwgMCIp`)"))
```
In readable form:
```
s=>s.match(/[^a-zA-Z]/g)?.length|0
```
[Answer]
# CJam, score 0, ~~95~~ ~~89~~ 82 bytes
```
qeuWcibWcibKAbFbAbHbAbIbfbXfbKBbKbAbDbAbKbfbKYbKbYbCbfbXdfmdUfmOGYbCbfbUfbXfbUfbXb
```
[Try it.](http://cjam.aditsu.net/#code=qeuWcibWcibKAbFbAbHbAbIbfbXfbKBbKbAbDbAbKbfbKYbKbYbCbfbXdfmdUfmOGYbCbfbUfbXfbUfbXb&input=%20!%22%23%24%25%26%27()*%2B%2C-.%2F0123456789%3A%3B%3C%3D%3E%3F%40ABCDEFGHIJKLMNOPQRSTUVWXYZ%5B%5C%5D%5E_%60abcdefghijklmnopqrstuvwxyz%7B%7C%7D%7E)
### Explanations
```
qeu e# Read input and convert to upper case.
65535b65535b e# Convert to base 65535 and back, to cast characters to integers.
91fb e# Convert each element to base 91.
1fb e# Sum the digits in each element.
e# Only letters would end up greater than or equal to 65.
65fb e# Convert each element to base 65.
2220010939706446080fb e# Convert each element from base 2.22e18.
1dfmd e# Divmod each element by floating point 1 to cast to floating point.
e# All letters would become the same number due to floating point inaccuracy.
e# It will also generate some extra 0s as the remainder but doesn't matter.
0fmO e# Cast elements back to integers.
20736fb0fb e# Convert each element to base 20736 and get the last digit.
e# 20736 is a divisor of the number about 2.2e18,
e# so the last digit generated from a letter would be 0.
1fb0fb e# Convert each element to unary and get the last digit.
1b e# Sum the elements.
```
With the constants:
```
0 U
1 X
65 KBbKbAbDbAbKb Convert 20 to base 11 (=19), from base 20 (=29), to base 10,
from base 13 (=35), to base 10, from base 20.
91 KAbFbAbHbAbIb Convert 20 to base 10, from base 15 (=30), to base 10,
from base 17 (=51), to base 10, from base 18.
*170 AZbDb Convert 10 to base 3 (=101), from base 13.
*196 GZbDb Convert 16 to base 3 (=121), from base 13.
20736 GYbCb Convert 16 to base 2, from base 12.
65535 Wci Cast -1 to character, then back to integer.
2.22e18 KYbKbYbCb Convert 20 to base 2, from base 20, to base 2, from base 12.
*Only used in an old version.
```
It depends on floating point inaccuracy. The number 2.22e18 won't change if a small number less than 26 is added to it.
CJam has a bug using divmod on a too big high precision integer and a float.
[Answer]
# [Zsh](https://www.zsh.org/), score 6, 64 bytes
```
tr -d abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ|wc -c
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m724qjhjwYKlpSVpuhY3HUqKFHRTFBKTklNS09IzMrOyc3Lz8gsKi4pLSsvKKyqrHJ2cXVzd3D08vbx9fP38AwKDgkNCw8IjIqNqypMVdJMh5kCNW0At8wA)
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), 110 bytes
```
+>>,[<++++[----->>->+>+<<<<]----[---->-<]>->+>[--<<-[<]<[>>>+<<]>>>]<<------>>>[--<<<-[<]<[>>>+<<]>>>>]<<<,]>.
```
[Try it online!](https://tio.run/##ZYxRCoAwDEMPtM0ThKDXsBScgiCCH4I/evi6bv6Zn5LkNfOZt2O9lt1ClSSS4RMAtUBGQetcZGKgd1D3NWWC1rw4IAkU4kOFKUdL9P024Ec4gqjszPphlCnfzws "brainfuck – Try It Online")
Accepts input as ASCII. outputs as binary. The header adds 48 (ASCII 0) to the count so that small outputs appear as ASCII digits.
This is a complete rewrite of my previous answer below, taking into account everything I could have done better. In particular, I set up a specific cell with a 1 in it to help with the IF operation instead of trying to use other nonzero cells to assist.
There are a few more bytes to save with this approach if I have time later. It's still the highest scoring answer, but it isn't the longest anymore, which is gnerally as good as it gets with Brainfuck.
```
+>> Put a 1 in cell 0 then move to cell 2
,[ take an input in cell 2 and loop until end of string marked by 0 encountered
<++++[----->>->+>+<<<<] Put 260 mod 256=4 in cell 1; iterate 260/5=52 times to subtract 52 from cell 3 and store 52 in cells 4 and 5
----[---->-<]>- Put minus 4 = 252 in cell 1; iterate 252/4=63 times to subtract 63 from the input; then reduce by one more
>+> add 1 to cell 3
[--<<-[<]<[>>>+<<]>>>] iterate 26 times UPPERCASE using 52 in cell 4; if not zero add 1 to cell 3
<<------>>> subtract 6 from the input
[--<<<-[<]<[>>>+<<]>>>>]iterate 26 times LOWERCASE using 52 in cell 5; if not zero add 1 to cell 3
<<< overall cell 3 has increased by 0 if input is a letter or 1 if not a letter
,] take more input into cell 2 until end of string marked by 0 encountered
>. output count from cell 3
```
# [brainfuck](https://github.com/TryItOnline/brainfuck), ~~146~~ 138 bytes
```
,[<++++[-----<-<+<+<+>>>>]>----------<<<<<[->>>>>-<<<<<]>>>>>--<<<<[-->>>>-[<]<[+>]<<<]>>->>------<<<[-->>>-[<]<[+>]<<]>++[->>>+<<<]>>,]>.
```
I misread the question and assumed all characters except `AZaz`and newline should be counted. I now realise newlines need to be counted like any other non `AZaz` character which makes the code slightly shorter. If I had not considered newlines at all, the code might be shorter still, but the setup loop 260/5=52=2\*26 is pretty efficient.
[Try it online!](https://tio.run/##TY47CoBADER7T2GfjScIg17DEPADgggWgo0eft01svjSZDIzkOkY13055y3SizJAHyKGGFT8nhEWyoOEgQuSydWEC/Od3XgdVjFRgrnNQCl74hcw@CsgDwdDE2NVt12vw3jdDw "brainfuck – Try It Online")
Accepts input as ASCII. outputs as binary. The header adds 48 (ASCII 0) to the count so that small outputs appear as ASCII digits.
**Commented code**
```
,[ Take an input; If nonzero start looping
<++++ Move left and add 4 to make (256+4)=260 mod 5
[-----<-<+<+<+>>>>]> Loop 52 times to setup 3 cells with 52 and one with minus 52
----------< Subtract 10 from input
<<<<[->>>>>-<<<<<]>>>>>-- Subtract another 52+2=54 from the input
<<<<[-->>>>- Loop 52/2=26 times reducing the input by 1 each time for UPPERCASE
[<]<[+>] If the input is nonzero increment the cell that contained minus 52
<<<] Ultimately the cell with minus 52 will be incremented 51 times for AZaz 52 for other
>>->>------ Subtract 1 from cell that contained minus 52 to avoid it reaching 0; and 6 from input
<<<[-->>>- Loop 52/2=26 times reducing the input by 1 each time for LOWERCASE
[<]<[+>] If the input is nonzero increment the cell that contained minus 52
<<]
>++ Cell that contained minus 52 now has minus 2 for AZaz or minus 1 for other; increment by 2
[->>>+<<<] Copy the value 0 or 1 into the final total
>>,] Take the next input and if nonzero continue to loop
>. Output the final total
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jellylanguage), score 3, 4 bytes
[@caird-coinheringaahing](https://codegolf.stackexchange.com/users/66833/caird-coinheringaahing) saves 1 byte!
```
ḟØẠL
```
[Attempt This Online!](https://tio.run/##y0rNyan8///hjvmHZzzctcDn////Sh5AsXwdhfD8opwURSUA)
**Explanation:**
Filter alphabetic characters from input, then return length
[Answer]
# [Perl 5](https://www.perl.org/) `-F/[^a-z]/si -0`, score ~~5~~ 2 (6 bytes)
*@DomHastings saves 3 points*
```
say$#F
```
[Try it online!](https://tio.run/##K0gtyjH9/784sVJF2e3/f88Q9WAFLj//IF9Hn3/5BSWZ@XnF/3V9TfUMDA3@67rpR8cl6lbF6hdn/tc1AAA "Perl 5 – Try It Online")
Abusing the command line flags for all they're worth. The `-F` flag with its regex breaks the input apart on anything that isn't a letter and stores those fields in @F. Therefore, there is one element added to @F for each nonalphabetic character. `-0` grabs all of the input at once (slurp mode). The actual code code outputs the last index of @F since there will always be at least one member of @F (assuming input is not null).
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), score 5, 39 bytes
```
sStringLength@s-Total@LetterCounts@s
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zg@7/4/aSFwSVFmXnpPql56SUZDsW6IfkliTkOPqklJalFzvmleSXFDsX/A4BKSqKVFXTtFNIclGMV1BT0HRSqlVIrEnMLclKVdBSUjMFMYxDTIzUnJ19HITy/KCdFESSQmJSsl5KapgtiK4AAiOEZoh6s4Ocf5OvoA@I@alh0aOmhpY@a1tjb2ysqwvTF5AE1gthEulSp9j8A "Wolfram Language (Mathematica) – Try It Online")
Doesn't work if the input contains non-ASCII letters (e.g. `այբուբեն`).
The private-use character `` is `\[Function]`.
[Answer]
# [Perl 5](https://www.perl.org/) + `-n0 -M5.10.0`, Score: 3, 14 bytes
```
say s M\PlMMig
```
[Try it online!](https://dom111.github.io/code-sandbox/#eyJsYW5nIjoid2VicGVybC01LjI4LjEiLCJjb2RlIjoic2F5IHMgTVxcUGxNTWlnIiwiYXJncyI6Ii1uMFxuLU01LjEwLjAiLCJpbnB1dCI6InNheSBzIE1cXFBsTU1pZyJ9)
[Answer]
# [Alumin](https://github.com/ConorOBrien-Foxx/Alumin), Score 0 (82 bytes)
```
iqipkmddhhdtddtthaueyddhhhdtdhatveyddhhhhhhhdthhthcueydhhhdhathcdthavetrtahycmzfaf
```
[Try it online!](https://tio.run/##LcrLCYAwEIThVrxZh0fBB6gNLFnDBI2obAKx@ZgVj98/Q3vw7sjZXe7cPDPAwiwCCmtSqkESf@ErgMDoQVVWmNIornILIRn/WLI5t0s9V8M49U33Ag "Alumin – Try It Online") I thought this would be a funny submission, since it is almost impossible to get a score of anything more than 0 without introducing no-ops, since the only defined operations are the lowercase English alphabet. (Technically, you would use a space to separate two integer sequences in a row, but you can golf around that if necessary, and it didn't come up here.)
## Commented code
```
i PUSH INPUT CHARACTER
q WHILE TOP OF STACK > 0 {
i PUSH INPUT CHARACTER
p }
k DISCARD EOF
m MAP EACH STACK ELEMENT OVER {
OUR STACK CONSISTS OF JUST A CHARACTER
dd DUPLICATE INPUT TWICE
hhdtddttha PUSH (2*2)*(2*2)*(2*2)+1
(AKA 65)
ue PUSH MAX(INPUT, 65) == INPUT
(AKA INPUT >= 65)
ydd DUPLICATE INPUT TWICE
hhhdtdhat PUSH (3*3)*((3*3)+1)
(AKA 90)
ve PUSH MIN(INPUT, 90) == INPUT
(AKA INPUT <= 90)
ydd DUPLICATE INPUT TWICE
hhhhhhhdthhthc PUSH (7*7)*2-1
(AKA 97)
ue PUSH MAX(INPUT, 97) == INPUT
(AKA INPUT >= 97)
yd DUPLICATE INPUT ONCE MORE
hhhdhathcdtha PUSH ((3*(3+1))-1)*((3*(3+1))-1)+1
(AKA 122)
ve PUSH MIN(INPUT, 122) == INPUT
(AKA INPUT <= 122)
STACK NOW LOOKS LIKE:
[B1 B2 B3 B4]
t PUSH AND(B3, B4)
r REVERSE STACK
[AND(B3,B4) B2 B1]
t PUSH AND(B2, B1)
a PUSH OR(AND(B3,B4), AND(B2, B1))
hyc PUSH NOT(^)
(AKA 0 FOR ALPHABETIC, 1 ELSE)
m }
zf FOLD ENTIRE STACK USING SEED 0 {
a ADD TOP TWO
f }
```
Not 100% sure the constants are optimal, but for now I'm satisfied.
[Answer]
# [Rust](https://www.rust-lang.org), score 14, 42 bytes
```
|s|s.replace(char::is_alphabetic,"").len()
```
[Attempt This Online!](https://ato.pxeger.com/run?1=dZDPTsJAEMbjlaeYNgR3SWlUYmKKYLxp4p9ETLyYNMuyazcupXaXoEKfxAsHfSh8BJ_CYdsghLiX2cxv5ptv5uMznxi7WP7IFEZMpYTCrAb4Rozn4zifaGE8mCqbxMbmKn2q8OqROqnbyFrapNDtbYA1pM0AyjYl37wqRUOTaWXjaaKsMBnjgtCQj7UW3EbRad_V9wila72i475FzQUtLBAZgDQ0wk9KGjiCQqsHE6PeRQClAnpaC2z498jXxMrWybI5N3MT5iLTKwc8YXkUKRMznSVsIKzige_TUAs8Sdnxvfew0qKdPxs8EfwZujA3EaxcBJDON-7AjBG5jcWLRyQxFCntrGGGbqxOPeLPorPCHbDw8Vy4GNZWhUU1zA0ivnhlo0wLLDuoCirQdqCN4GgbXAitxwFMx7keeojb25gNeDgUsrXb6Dxi-ng7fXm_34eb27vr86vdHlR7TFEOyWFF_tlSujUb0i1alPddLMr4Cw)
Only works for ASCII inputs, because `str::len` is counting bytes instead of characters.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 55 bytes, score 3
```
[^abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ]
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7wPzouMSk5JTUtPSMzKzsnNy@/oLCouKS0rLyissrRydnF1c3dw9PL28fXzz8gMCg4JDQsPCIyKvb//9SKxNyCnFQuYzBtzOWRmpOTr6MQnl@Uk6LIBTRUD2iqLpcCCHB5hqgHK/j5B/k6@nA9alh0aOmhpY@a1tjb2ysqKgIA "Retina 0.8.2 – Try It Online") Link includes test suite, so final example with newline isn't included. [Try it online!](https://tio.run/##K0otycxL/P8/Oi4xKTklNS09IzMrOyc3L7@gsKi4pLSsvKKyytHJ2cXVzd3D08vbx9fPPyAwKDgkNCw8IjIq9v9/oDYuoD4A "Retina 0.8.2 – Try It Online") Final example only.
[Answer]
# [Python 3](https://docs.python.org/3/), score 11, 39 bytes
```
lambda s:sum(not x.isalpha()for x in s)
```
[Try it online!](https://tio.run/##Pc4xasNAEAXQ2nOKUZVdsN2oMwSRwiGB2ALHkMbN2hqhhdXuMrMicmdylIC6nMJH8UVkO5D85vPhFy8eUxN8PtaPu9GZdl8ZlIV0rfIhYT@3YlxsjNJ1YOzRehQ9Jj4uYPLZWEe45Y5uYxLZ@qRqZX3sktJaA/UHigmX5fOSOfDtFI3ISL1poyPIfzuHF3IuTPEjsKsyMPvDvKJ6BngPvG4f3nFdblZPb3A5fZ@H83D5@imKIssy@Oc68kr07K5uTVSS@M89Fa2v "Python 3 – Try It Online")
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 11 Score, 32 bytes
```
s=>s.Count(c=>!char.IsLetter(c))
```
[Try it online!](https://tio.run/##Sy7WTS7O/O9WmpdsU1xSlJmXrpOZV2KXZvu/2NauWM85vzSvRCPZ1k4xOSOxSM@z2Ce1pCS1SCNZU/O/NVcAUH2JRpqGkmeIerCCn3@Qr6OPkqYmkgQhQ0Cq/wMA "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), score 4, 40 bytes
```
ss~StringCount~Except@LetterCharacter
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7v/j9pIXFdcElRZl56c75pXklda4VyakFJQ4@qSUlqUXOGYlFiclAxv8AoIqSaGVduzQH5Vi1uuDkxLy6ai6l1IrE3IKcVCUdLiVjMNMYxPRIzcnJ11EIzy/KSVEECSQmJeulpKbpgdgKIABieIaoByv4@Qf5OvqAuI8aFh1aemjpo6Y19vb2ioowfVxAfUpctf8B "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), score 9, 40 bytes
```
lambda s:map(str.isalpha,s).count(False)
```
[Try it online!](https://tio.run/##jY7BCoJAFEXXzldMq0YwF7kTWrRQCiqhhDZBPPWJwjgzvBlRv36yvqC7ORw4i2sW12m19@3h5SUMVQPcpgMYYR3FvQVpOohsGNd6VE7kIC2G3tGSsmDqeom8pBFXCQz1yvFWEEzvXpnRiTBkONdoHM@KPCPStHYGrPU4w2AksuTHhJ1QSh3xpybZbBhUddxgu2P8O3Yutw9@K@7X44X9@/AD "Python 2 – Try It Online")
[Answer]
# [APL (APLX)](https://apl.wiki/APLX) Score 6, 8 bytes
```
⍴⍞∼⎕A,⎕a
```
`⍴` shape of…
`⍞` input…
`~` without…
`⎕A` upper case **A**lphabet…
`,` and
`⎕a` lowercase **a**lphabet
[Answer]
# [C (gcc)](https://gcc.gnu.org/), Score 16 (48 bytes)
```
main(c){return~c?!isalpha(c)+main(getchar()):c;}
```
[Try it online!](https://tio.run/##S9ZNT07@/z83MTNPI1mzuii1pLQory7ZXjGzODGnICMRKKgNlkxPLUnOSCzS0NS0SrauJV0HAA "C (gcc) – Try It Online")
[Answer]
# [PowerShell Core](https://github.com/PowerShell/PowerShell), 59 bytes, score: 8 ~~10~~
```
$input-replace"[abcdefghijklmnopqrstuvwxyz]"|foreach Length
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNydFNzi9K/f9fJTOvoLREtyi1ICcxOVUpOjEpOSU1LT0jMys7Jzcvv6CwqLiktKy8orIqVqkmDaglMTlDwSc1L70kgzLNAA "PowerShell Core – Try It Online")
*-2 bytes thanks to [user314159](https://codegolf.stackexchange.com/users/78395/user314159)*
[Answer]
# JavaScript (ES6), Score 12 (64 bytes)
*-1 point thanks to @l4m2*
```
s=>s.replace(/[abcdefghijklmnopqrstuvwxyz]/gi,new String).length
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@7/Y1q5Yryi1ICcxOVVDPzoxKTklNS09IzMrOyc3L7@gsKi4pLSsvKKyKlY/PVMnL7VcIbikKDMvXVMvJzUvvSTjf3J@XnF@TqpeTn66RpqGUmpFYm5BTqqSAhhoairo6ysYcKEpMgYrMkZRZISuyCM1JydfRyE8vygnRVEJosgYXRHQvXpAB@sq4TMJLAe1DKbIFF2RZ4h6sIKff5Cvo48STpMeNSw6tPTQ0kdNa@zt7RUVFZXg5hkaYHFaTB7QbchOM@RCU5WmV5IPCVANTU3N/wA "JavaScript (Node.js) – Try It Online")
] |
[Question]
[
# Task
Given an \$m\times n\$ binary ascii "photo", return the negative of the photo
**Example:**
```
#
# #
# #
# #
#
->
## ##
# # #
###
# # #
## ##
```
# General rules:
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins
* [Standard rules](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) and [default I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/) apply
* Your output characters must be the same as your input characters (e.g. `["#"," "] -> [" ","#"]`), which you are free to choose (but must be printable characters)
* Your output photo must have the same \$m\times n\$ dimensions as the input
* Trailing whitespace is allowed
# Test cases
Input 1:
```
#
# #
# #
# #
#
```
Output 1:
```
## ##
# # #
###
# # #
## ##
```
Input 2:
```
# #
#####
# #
#####
# #
```
Output 2:
```
#### #
##
## # ##
##
# ####
```
Input 3:
```
##############################################################################################
# ### ## ## ####### ####### ###### ### ## ## ## ####### ##
# ### ## ####### ####### ####### ### ###### ### ## ### ## ### ## ####### ### #
# ## #### ####### ####### ### ###### # # ## ### ## ## ####### ### #
# ### ## ####### ####### ####### ### ###### # ## ### ## # #### ####### ### #
# ### ## ## ## ## ###### ### ## ## ### ## ## ##
##############################################################################################
```
Output 3:
```
## ## ####### ## ## ####### ## ## ####### ####### ## ######
## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##
####### ##### ## ## ## ## ## # ## ## ## ####### ## ## ##
## ## ## ## ## ## ## ### ### ## ## ## ## ## ## ##
## ## ####### ####### ####### ####### ## ## ####### ## ## ####### ######
```
[Answer]
# [Python 3](https://docs.python.org/3/), 31 bytes
```
lambda s:s.translate(9*"# \n ")
```
[Try it online!](https://tio.run/##tZLNDsIgDIDvfYoGLsODF0@a@Ca7YOaiycRlcPHpcSvVYMFED@sB2tJ@6Q/jI1zubhf7YxsHezt1Fv3Bb8NknR9sODf7jdLYOlQmjtPVhaZvlFKgVxXQiPO1HJgkGSSZwk9vr0goM5PjA19StSAKfFXJY0DU8BseJbXaN@P/rh41yqJrhUl8OUqpfJt9HbHMflWZ/6YxkP9U6hRovrQYzTr5a@G0C@DegDcD3CiQ9UqE@AQ "Python 3 – Try It Online")
### How
The `9*"# \n "` is a string that has a "\n" at position 10 which matches its own code point, and at positions 32 and 35 it has copies of "#" and " " so these two are at each other's code point. `str.translate` uses this string as a lookup table replacing each character of `s` by the value associated with its code point. It will leave newlines in place and swap hashes and spaces.
[Answer]
# [sed](https://www.gnu.org/software/sed/), ~~23~~ 8 bytes
-15 bytes thanks to [Digital Trauma](https://codegolf.stackexchange.com/users/11259/digital-trauma)
```
y/# / #/
```
[Try it online!](https://tio.run/##tZIxDoAwCEV3TvETZtNLadxcjIOnRwvEVIqJDjK0lLYvn9@u0zjMyyayF0YBFxH@NYiBc6oDLGyh0SS@dVXDhf6mFW74nsqBGPBp0p6hoOEdHpGa9u34z@rBiKIzYRHfWxmTJ@9zRPX@359D2hmpn/oQ7LnVSVXUomknd568EdIVcAA "sed – Try It Online")
[Answer]
# [C (tcc)](http://savannah.nongnu.org/projects/tinycc), 33 bytes
Function that modifies its input.
```
f(char*s){*s^=1^*s%3;*++s&&f(s);}
```
[Try it online!](https://tio.run/##tVFLCsMgEN17iqGSoCZZlC6lVwkEQZpF0xKDm9CzW8dISYyFdpFZ6Jvfm@eomkkp5zRTt24Uhs/CtNdzK0xxkaKqTFlqZrh8uXvXD0zVlodCYeWsHyOTTaPkc@yHSbNTYQg51cJyrpnvtdjmACgA8QcF4hHQiEPcZ/Gm6KGFKNYHD2/0fB091FBYmEfDNFhATK5ATH2iScO@cwls6PesNGFM6LNgXUMSDb/RQ8qafXek/1t9@Lat6JywlH6/yhR8232eAnd/qL0B "C (tcc) – Try It Online")
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 3 bytes
```
1-_
```
Maybe this is too cheaty?
* The two characters are `0` and `1`
* [Submissions may use list of strings instead of multi-line strings](https://codegolf.meta.stackexchange.com/a/17095/16766), so the input can be a list of rows, each of which is a string containing `0`s and `1`s
* But [Lists of decimal digits and strings that match `^[0-9]*$` are interchangeable](https://codegolf.meta.stackexchange.com/a/17167/16766), so each row can be a list of digits
The solution is a function that takes and returns a list of lists of `0`s and `1`s. [Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgWbSSboFS7EKNpaUlaboWiw114yGsm_bR0QbWBtaGQGwQax0NYRmC2WAxEA9NHKE-lksTYsyCBRAaAA)
Explanation: subtract each number from 1.
---
Here's a **6-byte** version that's on much safer ground rules-wise. It's also a function, and it also uses `0` and `1`, but it takes and returns a multiline string:
```
_TRt01
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgWbSSboFS7EKNpaUlaboWy-JDgkoMDCGcm4pKBgaGBgZcQMLQgAvIMjCEssHiSlyaEIULFkBoAA)
Explanation: Transliterate the characters in `10` (the `t` builtin) to the characters in `01`.
[Answer]
# [JavaScript (V8)](https://v8.dev/), 25 bytes
```
s=>s.replace(/./g,i=>i^1)
```
[Try it online!](https://tio.run/##tZJNCoMwEIX3OUWXBlqd2RWKHqUYJIpFqpji9aMTQ9FJhHZhFvFlfj5exrzUpEw1tsPnNt1tfcmtyQuTjnroVKWTLM2aa5sX7ROlrfq36Tuddn2T1EkpABBALBuCWBSg12u8lPIhRNhDWaQaWq6Wqt2JvnQ67MZTF13CuUDnAVbhkxvhU98oawg718AOH1KRERk@KrY1gnn4DQ@cGr23x//t3v3MvemYMY4PR8nF0ezjCJr9uS@HnqudAQ "JavaScript (V8) – Try It Online")
Takes input as string of 0's, 1's, and newlines.
Explanation:
```
s => s.replace(
/./g, // '.' matches anything but newline, ie. 0 or 1 only.
// 'g' marks regex as global, to replace everything
i => i ^ 1 // JavaScript's aggressive type casting forces '0' or '1' string into a number
// boolean XOR (^) with 1 transforms 0 -> 1 and 1 -> 0
)
```
[Answer]
# [Bash](https://www.gnu.org/software/bash/) + coreutils, 12
```
tr '# ' ' #'
```
[Try it online!](https://tio.run/##tZIxDoAwCEV3TvEThp5LJ2f1/tgCMZViokMxqZTKy@fbdTk2kXNHYZT6cBHhqUEM1FdbYGEbjS7xo7saGsZOKzzwI5UDMeDTpP@GgoZveERqOrfjf6sHI4rOhEX8aGVM3rzPEc37uTeHdDJSP/VHsOdWJ1XRiqad3HnyQUh3wAU "Bash – Try It Online")
[Answer]
# [Lua](https://www.lua.org), 68 bytes
```
a=io.read('*a')b,d=a.gsub,' 'print((b(b(b(a,'#','!'),d,'#'),'!',d)))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=tZJBCsIwEEXB5ZxiJItpJHbtpjsvkhKVgqjU9jRuCsVD6cqjaDJB6jSCLjqF9mfSPP789tLvW9t117bZLle3tS2qY15vrMtoYUmXxhU2353b0hDSqa4OTZaV4bKGFBmakzbOS-21cVprZkVkd5891KQFCvH18Dfk4kWogYhb7644MD7JjQ_8mKoEUeCTYvgOCA-_4VFSk3NH_N_uUaE0nTIm8eMopfiWfRrhs5-0AMJkEPIMH0JFzX0ILnyTvUNMHuIgEFaI_Kc_AQ)
[](https://i.stack.imgur.com/tcyMt.png)
[Answer]
# [Factor](https://factorcode.org/) + `pair-rocket`, 25 bytes
```
[ "# "=> " #"substitute ]
```
[Try it online!](https://tio.run/##LcgxCsJAEEbhfk7xM1PnAoppJY2NWInFZhlhyZKVmQk5/hrE5vHx3ilHs/64T7frCcm9ZccnFRus5UUDpWFRW7XiTMSAAHREQIcgf/8@U3@CBXwZwRD2bfYosYXi1XOqFbuV0P4F "Factor – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 1 byte
```
⌐
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJhIiwidmZcXCAwdlZcXCMxdlYiLCLijJAiLCIwXFwgdlYxXFwjdlZ24bmF4oGLIiwiIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjI1xuIyAgIyMjICAjIyAgICAgICAjIyAgIyMjIyMjIyAgIyMjIyMjIyAgICAgICAjIyMjIyMgICMjIyAgIyMgICAgICAgIyMgICAgICAgIyMgICMjIyMjIyMgICAgICAjI1xuIyAgIyMjICAjIyAgIyMjIyMjIyAgIyMjIyMjIyAgIyMjIyMjIyAgIyMjICAjIyMjIyMgICMjIyAgIyMgICMjIyAgIyMgICMjIyAgIyMgICMjIyMjIyMgICMjIyAgI1xuIyAgICAgICAjIyAgICAgIyMjIyAgIyMjIyMjIyAgIyMjIyMjIyAgIyMjICAjIyMjIyMgICMgIyAgIyMgICMjIyAgIyMgICAgICAgIyMgICMjIyMjIyMgICMjIyAgI1xuIyAgIyMjICAjIyAgIyMjIyMjIyAgIyMjIyMjIyAgIyMjIyMjIyAgIyMjICAjIyMjIyMgICAjICAgIyMgICMjIyAgIyMgICMgICMjIyMgICMjIyMjIyMgICMjIyAgI1xuIyAgIyMjICAjIyAgICAgICAjIyAgICAgICAjIyAgICAgICAjIyAgICAgICAjIyMjIyMgICMjIyAgIyMgICAgICAgIyMgICMjIyAgIyMgICAgICAgIyMgICAgICAjI1xuIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyJd)
Same method as DLosc's 3 byte Pip answer. Takes a list of lists of either 0 or 1.
Simply computes `1 - n` for each digit. Alternatively,
## [Vyxal](https://github.com/Vyxal/Vyxal), 3 bytes
```
₀S*
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJhIiwiXFwgMHZWXFwjMXZW4oGLIiwi4oKAUyoiLCIwXFwgVjFcXCNWIiwiIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjI1xuIyAgIyMjICAjIyAgICAgICAjIyAgIyMjIyMjIyAgIyMjIyMjIyAgICAgICAjIyMjIyMgICMjIyAgIyMgICAgICAgIyMgICAgICAgIyMgICMjIyMjIyMgICAgICAjI1xuIyAgIyMjICAjIyAgIyMjIyMjIyAgIyMjIyMjIyAgIyMjIyMjIyAgIyMjICAjIyMjIyMgICMjIyAgIyMgICMjIyAgIyMgICMjIyAgIyMgICMjIyMjIyMgICMjIyAgI1xuIyAgICAgICAjIyAgICAgIyMjIyAgIyMjIyMjIyAgIyMjIyMjIyAgIyMjICAjIyMjIyMgICMgIyAgIyMgICMjIyAgIyMgICAgICAgIyMgICMjIyMjIyMgICMjIyAgI1xuIyAgIyMjICAjIyAgIyMjIyMjIyAgIyMjIyMjIyAgIyMjIyMjIyAgIyMjICAjIyMjIyMgICAjICAgIyMgICMjIyAgIyMgICMgICMjIyMgICMjIyMjIyMgICMjIyAgI1xuIyAgIyMjICAjIyAgICAgICAjIyAgICAgICAjIyAgICAgICAjIyAgICAgICAjIyMjIyMgICMjIyAgIyMgICAgICAgIyMgICMjIyAgIyMgICAgICAgIyMgICAgICAjI1xuIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyJd)
Takes a multiline string of 0s and 1s. The flag, header and footer are for allowing the test cases to be directly pasted in without having to change them.
## Explained
```
₀S*
₀S # The string "10"
* # Ring translate the input according to that - change 0 to 1, 1 to 0 and leave newlines as they are.
```
[Answer]
# [Haskell](https://www.haskell.org/), 28 bytes
```
map g
g ' '='#'
g c=min ' 'c
```
[Try it online!](https://tio.run/##y0gszk7NyfmfZhvzPzexQCGdK11BXUHdVl1ZHchKts3NzAPxk4GSmXm2BaUlwSVFPnkKKgppSgrKQBiTp6AAoUA8pf//ktNyEtOL/@smFxQAAA "Haskell – Try It Online")
Acts on a string with newlines in it.
By the same rules-lawyering as [this Pip answer](https://codegolf.stackexchange.com/a/244187/3852) I guess `map$map(1-)` is a valid answer, but I don't really like it.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 1 [byte](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
Each line is a separated potential program:
```
_
≠
È
```
I/O as a matrix of 1s and 0s.
[Try it online](https://tio.run/##yy9OTMpM/f8//v//6GgDHQUgMgSTBrE6CtFwniFUACoHEcOqAtWMWAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaCkU@l1aLcOl5J/aQlM4H/8f5DYoW32/6Ojow10DHQMgdggVicawjIEs8FiIB6aOEI9kBNtAFMFVwliQyGSapgNcDk4HyoHNxGhYshBeKjBfQinERBZBiU0sIig6sJUi98GYuxEUoHH9cS41ZCAG/G7nngRHOYgpVjs4UBN1xsQdCvx8Y3qetqHvQESjdtOYkOMkOuJSZWEREhN96S4Apbuh26ZExsLAA).
Using the actual `#` and spaces as I/O, it would be 5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) instead:
```
„# ‡
```
I/O as multiline strings with `#`s/spaces and potential newlines.
[Try it online](https://tio.run/##yy9OTMpM/f//UcM8ZYXDTY8aFv7/r6SkpExTwKWsoACkQIQCBEA4YIDEgErBRdE0YOqECKAYj2mqMpqJaMZjZSCr4UJzA3HGK6CbitXfUONJdr2CsgK6o7E5DN14zKBEZ@AKe@xGgMKepgCYNAE) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaCkU6nDpeRfWgLjufx/1DBPWeFw06OGhf91Dm2z/x@tpKCgrKAQkwcklYEUkK2gDOeB5ZR0gGpALGWwAAhAZMD6wHwwA8QHq1amKQC7EWynMthCBQgDKovEgErBRdE0YOqECKCaj2msMpqRaOZjZSCrgYQxkiuIM18B3VisPoeZT7L7wZGH6mxsLsMwHzM40Rm4wh@7EeDwpylQigUA).
**Explanation:**
```
# Transform each 1 to 0 and each 0 to 1 in the (implicit) input-matrix,
_ # using an ==0 check
≠ # or !=1 check
È # or %2==0 (is_even) check
# (after which the modified matrix is output implicitly)
„# # Push string "# "
 # Bifurcate it, short for Duplicate & Reverse copy
‡ # Transliterate all "#" to " " and vice-versa in the (implicit) input
# (after which the modified string is output implicitly)
```
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 13 bytes
```
@(x)['' 67-x]
```
[Try it online!](https://tio.run/##tZK9CoMwEMd3n@IPR4kOFVRooUXoQ3QTh1J07VApvn2MSSi5M4F2MEvu@3e5y@s5PT6DHtuyLPUtn4tOKZzOx7nXB9yH94Tqkk3mrtBizE1UBnQKIEBdnQplNApU4wMlvS63LzIPqB2gFoA1jFjWengZ1oT1M8PqZ6jGoRqGol0Pm4ptkGxXcIKPCgTv@lpFwjbTGeKcbXkSpQUnKoQxfMtBV79xIMtHJyE5f7/Hbp4/I9ZhkrMdtxRS@4mXYPvZ97/1hV4A "Octave – Try It Online")
Takes the input as an array of `'# '` characters.
The sum of `'#'` and `' '` is 67, so all we need to do is subtract the input string from 67 and it will "negate" the characters.
Unfortunately we then have to spend a few bytes forcing the output back to being a character array rather than an integer, but ho hum.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
O^1Ọ
```
A monadic Link that accepts a list of lists of characters (from and `!`) and yields a list of lists of characters with these characters swapped.
**[Try it online!](https://tio.run/##y0rNyan8/98/zvDh7p7/D3dvOdwe@f@/urp6DJeCoqKCAphQhAAIBwyQGFApuCiaBkydEAEU4zFNVUAzEc14rAxkNVxobiDOeEV0U7H6G2o8ya5XVFBEdzQ2h6EbjxmU6AxcYY/dCAUFYPQCAA "Jelly – Try It Online")**
### How?
```
O^1Ọ - Link: list of lists of characters
O - ordinal (vectorises) : ' ' -> 32 and '!' -> 33
1 - one : 1
^ - XOR (vectorises) : 32 -> 33 and 33 -> 32
Ọ - character (vectorises) : 33 -> '!' and 32 -> ' '
```
---
If integers are allowed in place of characters as I/O then the one byte Link `¬` would suffice (vectorising loginal NOT).
[Answer]
# [R](https://www.r-project.org/), ~~38~~ 30 bytes
Or **23 bytes** by exchanging `function` for `\` using [R](https://www.r-project.org/)≥4.1: [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhbbYzQqNJMzEotKijSUlBWUdJQUlJV0KjQhsjfzkhNLNNI0uJSU4YBLWQEMoExlZTAbjQmRh4jiUAtmcyHMVeLShNq6YAGEBgA)
```
function(x)chartr("# "," #",x)
```
[Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP0@jQjM5I7GopEhDSVlBSUdJQVlJp0Lzf3JiiUaaBpeSMhxwKSuAAZSprAxmozEh8hBRHGrBbC6EuUpcmpr/AQ "R – Try It Online")
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), ~~28~~ 22 bytes
```
,[-------[->+++<]>+.,]
```
[Try it online!](https://tio.run/##SypKzMxLK03O/v9fJ1oXAqJ17bS1tW1i7bT1dGL//9cCAS6tLCDkArMB "brainfuck – Try It Online")
Switch `*`(42) and `j`(106). Long to make `\n`(10) same
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 13 bytes
```
L:::bdN\#dN\#
```
[Try it online!](https://tio.run/##K6gsyfj/38fKyiopxS9GGYT/Vyop0xRwKSsoACkQoQABEA4YIDGgUnBRNA2YOiECKMZjmqqMZiKa8VgZyGq40NxAnPEK6KZi9TfUeJJdr6CsgO5obA5DNx4zKNEZuMIeuxGgsKcpUPoPAA "Pyth – Try It Online")
[Answer]
# APL+WIN, 32 bytes
Prompts for m x n matrix
```
n←(⍴m←⎕)⍴' '⋄((,m=' ')/,n)←'#'⋄n
```
[Try it online! Thanks to Dyalog APL Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcQJanP5BlyPWooz3tfx6QqfGod0sukAZKaQKZ6grqj7pbNDR0cm2BTE19nTxNoKS6Mkg07z9QF9f/NC5TBVOwUgVlBRBWRqXVuYA6uUCqzCGqIHIKyiCAha2goK4A0aLAZa5gaQLSpExbAHYAiFCAAGWYk1AYUClcGjB1QtUjKcY0FN0FyhgaMBl4XECc6QrohmL1NR6L8ZkOiXUUndjchcsFOBl4IgqLBhqnGGCqBgA "APL (Dyalog Classic) – Try It Online")
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 6 bytes
```
T`10`d
```
[Try it online!](https://tio.run/##tVG5DYAwDOwzxUleAHZhAJCgoKFA7A8@J0LECRIUcRGfv8vF2Zdj3aZzGCHjrK7vzM0an4AAQQ9BUARJOObVEQhDmqVZsIieERulqVGaXSh2HSJIxQdIpTvrBsrJmMjoS1ZxjI6@Cp49wWn4Rg/PWn13ov@t3v4tF10T5unLVXrwtvs6BXff1C4 "Retina 0.8.2 – Try It Online") Swaps `0` with `1` but link is to test suite that converts from `#` to `01` and back. Explanation: `d` is shorthand for `0-9` or `0123456789` so this translates `1` to `0` and `0` to `1` (the extra target characters are ignored).
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 8 bytes
```
WS⟦⭆ι¬Σκ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/788IzMnVUHDM6@gtCS4pCgzL11DU1MhAMgo0YiGCPgmFmhk6ij45ZdoBJfmamRramrGalr//29AU8BlYGgIpECEIQRAOGCAxIBKwUXRNGDqhAigGI9pqgGaiWjGY2Ugq@FCcwNxxhuim4rV31DjSXa9oYEhuqOxOQzdeMygRGfgCnvsRoDCnrYp579uWQ4A "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a list of newline-terminated strings of `0`s and `1`s. Explanation:
```
WS
```
While there are more strings in the input...
```
⟦⭆ι¬Σκ
```
... logically invert each character's decimal value and output the result on its own line.
[Answer]
# [R](https://www.r-project.org/), 14 bytes
-5 bytes by l4m2, using 1-m instead of abs(m-1) and +11 for providing the required function call.
```
function(m)1-m
```
[Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP08jV9NQN/d/mkZuYklRZoVGsoaBjgIQGYJJZLYhieIGmjoKecn5ObamQLoov1zBVsFUU/M/AA "R – Try It Online")
I do personally dislike the freedom of I/O in this challenge and allowing any other input characters than " " and "#". I learned something new from Dominic van Essen's answer actually as I was never aware of that function. But bending the rules to make life easier, nevertheless my answer. Input a 0-1 matrix and just reverse the values.
[Answer]
# [Python 3](https://docs.python.org/3/), 21 bytes
```
lambda s:s.swapcase()
```
Takes a multiline string consisting of `a` for spaces and `A` for `#`'s and outputs the string after swapping the case of each letter. Not quite as nice-looking (or interesting) as loopy walt's wonderful answer, but I'm happy to finally write an answer to one of these :)
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaHYqlivuDyxIDmxOFVD839BUWZeiUaahpKSEpcjTQGXY2IikAIRiRAA4YABEgMqBRdF04CpEyKAYjymqY5oJqIZj5WBrIYLzQ3EGZ@IbipWf0ONJ9n1iY6J6I7G5jB04zGDEp2BK@yxGwEKe5oCYNrU1ORCTqlgn3KBwxccMY5QNlgcm3JwXHBB/cYFjRkuqEe5wDyYxv8A "Python 3 – Try It Online")
[Answer]
# [Vim](https://github.com/vim/vim), 3 bytes
```
VG~
```
>
> Your output characters must be the same as your input characters (e.g. ["#"," "] -> [" ","#"]), which you are free to choose (but must be printable characters)
>
>
>
We will use the upper case and lower case version of any alphabetic character.
### Explanation
1. `V`: Select the whole line
2. `G`: Go to the end of the document
3. `~`: Swap case of the characters
[Try it online!](https://tio.run/##K/v/P8y97v//QJoCrsDCQiAFIgohAMIBAyQGVAouiqYBUydEAMV4TFMD0UxEMx4rA1kNF5obiDO@EN1UrP6GGk@y6wsDC9Edjc1h6MZjBiU6A1fYYzcCFPY0BQA "V (vim) – Try It Online") (Using: ["q","Q"] -> ["Q","q"])
[Try it online!](https://tio.run/##K/tvpVqsr6xfqJ/OBWIp6AeCWMmJOTkKyaVFxflFGoY6Coaa/8Pc68BKC4GKIUoDgYrT/yvTFHApKygAKRChAAEQDhggMaBScFE0DZg6IQIoxmOaqoxmIprxWBnIarjQ3ECc8QropmL1N9R4kl2voKyA7mhsDkM3HjMo0Rm4wh67EaCwpykAAA "V (vim) – Try It Online") (Adding some replaces to fit the caracters in the examples)
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 1 byte
```
N
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCLilqHigYtcXCNcXEFWXFwgXFxhViIsIk4iLCJcXGFcXCBWXFxBXFwjViIsIiMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyNcbiMgICMjIyAgIyMgICAgICAgIyMgICMjIyMjIyMgICMjIyMjIyMgICAgICAgIyMjIyMjICAjIyMgICMjICAgICAgICMjICAgICAgICMjICAjIyMjIyMjICAgICAgIyNcbiMgICMjIyAgIyMgICMjIyMjIyMgICMjIyMjIyMgICMjIyMjIyMgICMjIyAgIyMjIyMjICAjIyMgICMjICAjIyMgICMjICAjIyMgICMjICAjIyMjIyMjICAjIyMgICNcbiMgICAgICAgIyMgICAgICMjIyMgICMjIyMjIyMgICMjIyMjIyMgICMjIyAgIyMjIyMjICAjICMgICMjICAjIyMgICMjICAgICAgICMjICAjIyMjIyMjICAjIyMgICNcbiMgICMjIyAgIyMgICMjIyMjIyMgICMjIyMjIyMgICMjIyMjIyMgICMjIyAgIyMjIyMjICAgIyAgICMjICAjIyMgICMjICAjICAjIyMjICAjIyMjIyMjICAjIyMgICNcbiMgICMjIyAgIyMgICAgICAgIyMgICAgICAgIyMgICAgICAgIyMgICAgICAgIyMjIyMjICAjIyMgICMjICAgICAgICMjICAjIyMgICMjICAgICAgICMjICAgICAgIyNcbiMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMiXQ==)
A different Vyxal solution. Expects uppercase letters for `#` and lowercase letters for or vice versa. `N` is the swap case element. The header and footer converts the test case format into the format that the program expects and vice versa.
[Answer]
## Batch, 60 bytes
```
@set/ps=
@set s=%s: =$%
@set s=%s:#= %
@echo(%s:$=#%
@%0
```
Swaps spaces with `#`s. Doesn't work well with file input as it needs to be interrupted with Ctrl+C to exit. Explanation:
```
@set/ps=
```
Read in the next line.
```
@set s=%s: =$%
```
Replace the spaces with `$`s.
```
@set s=%s:#= %
```
Replace the `#`s with spaces.
```
@echo(%s:$=#%
```
Replace the `$`s with `#`s and output the result.
```
@%0
```
Rinse and repeat.
[Answer]
[Elisp](https://www.gnu.org/software/emacs) + [s.el](https://github.com/magnars/s.el), 57 bytes
```
(s-replace"-""#"(s-replace"#"" "(s-replace" ""-"(read))))
```
[](https://i.stack.imgur.com/hTxnH.gif)
[Answer]
# [Haskell](https://www.haskell.org/), 32 bytes
```
f l=[[x|c<-s,x<-"# ",x/=c]|s<-l]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P00hxzY6uqIm2Ua3WKfCRldJWUFJp0LfNjm2pthGNyf2f25iZp6CrUJuYoGvQkFpSXBJkU@egopCWrSSgoKyAlCxEpACaQLqBIog8SHysf8B "Haskell – Try It Online")
Takes and returns a list of String
[Answer]
# Charcoal, 19 bytes
```
WS«Fι«≡κ ¦#¦ »M±Lι¹
```
[Try it online!](https://tio.run/##S85ILErOT8z5///9nu3v92w@tPr9nmXndh5a/ahz4bldCoeWKR9apnBo9/s9aw9tfL9nDVBm5///CgrKCgpcQEJZgQvIUlCGsqHiIBGQmIIyCIBFQeJgHogG8WB8mgGQw8D2KYNtU4AwoJJIDKgUXBRNA6ZOiACK8ZimKqOZiGY8VgayGi40NxBnvAK6qVj9DTWeZNeDow3V0dgchm48ZlCiM3CFPXYjQGFP25QDAA)
[Answer]
# [Gema](http://gema.sourceforge.net/), 7 characters
```
%=.;.=%
```
For this version choose the `%` and `.` characters.
[Try it online!](https://tio.run/##tZGxDoAgDER3/uPW@wHDxzgYJ/9/RK4QAwUTHegA1xYeZz2Pa08JkRsjUiJBhryAISui6lLPmwSUKqyshmXalekgloas2YOw51hEbTaitp6quzDeLIUOP1LhiA4/Fe2Z4Dx8w9NTp99d8b/d23/rTc@Mefw4Si/eZj9HaPZL4wY "Gema – Try It Online")
### Gema, 10 characters
```
\#=\ ;\ =#
```
This uses the original `#` and characters. Unfortunately this needs escaping because
* `#` is metacharacter similar to `*` (`.*` in regex), but recursive
* is metacharacter and means one or more whitespace characters (`\s+` in regex)
[Try it online!](https://tio.run/##tZGxDoAgDER3vuKS@wzDn7A4GCf/f0SuEKMFEx3oANcWHmfdt2PNOTEmLAmROQMEQlmIUBTYdK2XTYJKFVZWwzLtynSQU0PW7EHac6iiNW@ita6qu9DfrIUHvqfSER1@KO5ngvPwDQ9PHX53w/92b//taXpkzOP7UXrxNvsxQrOfGic "Gema – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), 4 bytes
```
5\Zc
```
Input is a char matrix containing and `#`.
[Try it online!](https://tio.run/##y00syfn/3zQmKvn//2h1ZZoCdWsFdWUFBSALRChAAIQDBkgMqBRcFE0Dpk6IALoNmAYroxmKZgNWBrIaqA3ILiHOBgV0g7H6HmEDyX5QUFZAdzo2t2GxATNY0Rm44gG7EdB4oG1aigUA "MATL – Try It Online")
### How it works
```
% Implicit input
5\ % Modulo 5 of (codepoints) of the input chars. This gives 2 for space, 0 for '#'
Zc % Convert nonzeros to '#' and zeros to char(0)
% Implicit display. char(0) is displayed as a space
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 18 bytes
```
->s{s.tr"# "," #"}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1664ulivpEhJWUFJR0lBWan2f0FRZl6JQppecmJOjoaSgoKyggIXkFBW4AKyFJShbLC4kqa2UkxeTJ4SFxe6LpC8MkgVCIBVg8wB80A0iAfSz8X1HwA "Ruby – Try It Online")
I suggested this to fix a Ruby answer but disappeared..
] |
[Question]
[
Your task today is to write a program or function that takes an array of integers, and counts the number of times, reading it left to right, that the value changes. This is easier to show with an example: `[1 1 1 2 2 5 5 5 5 17 3] => [1 1 1 **2** 2 **5** 5 5 5 **17** **3**] => 4`
Test case:
```
Input | Output
[] | 0
[0] | 0
[0 1] | 1
[0 0] | 0
[1 2 3 17] | 3
[1 1 1 2 2 3] | 2
[-3 3 3 -3 0] | 3
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), fewest bytes wins!
[Answer]
# [MATL](https://github.com/lmendo/MATL), 2 bytes
```
dz
```
[Try it online!](https://tio.run/##y00syfn/P6Xq//9oQwUQNAJCUyg0NFcwjgUA) Or [verify all test cases](https://tio.run/##y00syfmf8D@l6r9LyP/oWK5oAxBWMASTILahgpGCsYIJmAWCRiA@kKdrrACCQMogFgA).
### Explanation
```
% Implicit input
d % Consecutive differences
z % Number of nonzeros
% Implicit display
```
[Answer]
# [Python 3](https://docs.python.org/3/), 38 bytes
```
f=lambda x=0,*y:y>()and(x!=y[0])+f(*y)
```
[Try it online!](https://tio.run/##JU1LCsMgFNz3FK8LiaZP0CSLEjAXEReWIA20JtgU4umtL2VgvovZ8v5cY19KMC//fsweDqOwzWOeuPBx5sfVZKucuAXeZlHCmsCn5DMsEaxDqBsR6r/UZDV22ONAhUZCRwVF2SOhinLjBWBLS9x5w6S@f0BOwL4NMODnAUJ9PJ0QovwA "Python 3 – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 33 bytes
```
f(a:b:r)=sum[1|a/=b]+f(b:r)
f _=0
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P00j0SrJqkjTtrg0N9qwJlHfNilWO00DJMSVphBva/A/NzEzT8FWoaAoM69EQUUhTSHaUAcEjYHQCEib6JjE/gcA "Haskell – Try It Online")
---
**Bonus:** Somewhat curious point-free arithmetic version (44 bytes)
```
sum.(tail>>=zipWith((((0^).(0^).abs).).(-)))
```
[Try it online!](https://tio.run/##y0gszk7NyfmfZhvzv7g0V0@jJDEzx87OtiqzIDyzJEMDCAziNPXARGJSsaYekK2rqan5PzcxM0/BVqGgKDOvREFFIU0h2lAHBI2B0AhIm@iYxP7/l5yWk5he/F83uaAAAA "Haskell – Try It Online")
Given an input `[1,1,4,3,3,3]`, we first take the difference of adjacent entries (`[0,3,-1,0,0]`), then the `abs`olute value: `[0,3,1,0,0]`. Taking zero to the power of each element the first time yields `[1,0,0,1,1]`, and a second time inverts the list: `[0,1,1,0,0]` (`(1-)` would also work here instead of `(0^)`). Finally we take the `sum` of the list to get `2`.
[Answer]
# [Python 2](https://docs.python.org/2/), 42 bytes
```
lambda a:sum(x!=y for x,y in zip(a,a[1:]))
```
[Try it online!](https://tio.run/##HUnLCoUgEN33FdNOYYK0VkJfYi4mLnKFMukB2c9bE4fzTvn4r1EXP4xlpmX6EZDZz0Vc9ZDBrxtcmCFEuEMShGSVcVIWPohn69C2TFSfclaoscP@SwzN/W1Nh4zXWmcqgLSFeIAXJMsD "Python 2 – Try It Online")
[Answer]
# [K (oK)](https://github.com/JohnEarnest/ok), 8 bytes
**Solution:**
```
+/1_~~':
```
[Try it online!](https://tio.run/##y9bNz/7/X1vfML6uTt3KUAEEjYDQFAoNzRWM//8HAA "K (oK) – Try It Online")
**Examples:**
```
+/1_~~':1 1 1 2 2 5 5 5 5 17 3
4
+/1_~~':()
0
+/1_~~':-3 3 3 -3 0
3
```
**Explanation:**
Interpreted right-to-left:
```
+/1_~~': / the solution
~': / equal each-previous
~ / not (ie differ)
1_ / 1 drop, remove first as this is different to null
+/ / sum up trues
```
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 50 bytes
```
([][()]){{}({}[({})]){{}<>({}())(<>)}{}([][()])}<>
```
[Try it online!](https://tio.run/##SypKzMzTTctJzP7/XyM6NlpDM1azurpWo7o2GoghHBs7IFNDU1PDxk6zFsiCKgOK//9vqACCRkBoCoWG5grGAA "Brain-Flak – Try It Online")
Outputs nothing for 0, which in brain-flak is equivalent. If this is not acceptable, than append this for `+4` bytes: `({})`
Explanation:
```
#Push stack-height-1
([][()])
#While true:
{
#Pop the stack-height-1 off
{}
#If 'a' is the element on top of the stack, and 'b' is the element underneath it, then
#Pop 'a' off, and push (a - b)
({}[({})])
#If (a-b) is not 0...
{
#Pop (a-b) off
{}
#Switch stacks
<>
#Increment the value on the other stack
({}())
#Push a 0 back to the main stack
(<>)
#Endif
}
#Pop either (a-b) or the 0 we pushed
{}
#Push stack-height-1
([][()])
#Endwhile
}
#Toggle to the alternate stack and display the counter
<>
```
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 50 bytes
```
(([][()]){[{}]<({}[({})])>{(<{}>)()}{}([][()])}<>)
```
[Try it online!](https://tio.run/##SypKzMzTTctJzP7/X0MjOjZaQzNWszq6ujbWRqO6NhqIgXy7ag2b6lo7TQ3N2upamKJaGzvN//91jRVAEEgZAAA "Brain-Flak – Try It Online")
```
# Get ready to push the answer
(
# Push stack height - 1
([][()])
# Loop until 0 (until the stack has a height of 1)
{
# Pop the old stack height and subtract it
#(cancels the loop counter from the final answer)
[{}]
# Pop the top of the stack and subtract the next element from that
# Don't include this in the final answer
<({}[({})])>
# If not 0
{
# Pop the difference between the last two numbers
# Don't include this in the final answer
(<{}>)
# Add 1 to the final answer
()
# End if
}{}
# Push stack height - 1
([][()])
# End while
}
# Switch to the off stack so we don't print anything extra
<>
# Push the total sum. This is the number of times the if was true
)
```
[Answer]
# [Haskell](https://www.haskell.org/), 35 bytes
*-8 bytes thanks to H.PWiz.*
Out-golfed by a [recursive version](https://codegolf.stackexchange.com/a/146436/68615). Haskell is pretty much the best at recursion and I missed it. >\_<
```
f l=sum[1|x<-zipWith(/=)l$tail l,x]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P00hx7a4NDfasKbCRrcqsyA8syRDQ99WM0elJDEzRyFHpyL2f25iZp6CrUJuYoGvgkZBUWZeiYKeQpqmQnR0rI5CtAGY0FEwhNJgvqGOgpGOgjFQ1BzKhSAjiDhITNcYrACIQCyD2Nj/AA "Haskell – Try It Online")
It'd be awesome if anybody figured out how to employ [this tip](https://codegolf.stackexchange.com/a/76364/68615).
## Alternate solution, 36 bytes
```
f l=sum[1|True<-zipWith(/=)l$tail l]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P00hx7a4NDfasCakqDTVRrcqsyA8syRDQ99WM0elJDEzRyEn9n9uYmaegq1CbmKBr4JGQVFmXomCnkKapkJ0dKyOQrQBmNBRMITSYL6hjoKRjoIxUNQcyoUgI4g4SEzXGKwAiEAsg9jY/wA "Haskell – Try It Online")
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), 65 bytes
Not as short as I'd like, but that's just Java for you.
Test by passing the array as a comma delimited list.
```
a->{int s=0,i=1;for(;i<a.length;s+=a[i-1]!=a[i++]?1:0);return s;}
```
[Try it online!](https://tio.run/##TY9BT4QwEIXP5VeMeyoBGtCbFT17cC8eSQ@V7WJXKKQtazaE347TuhtNmk5e@@bNNyd5lsU4KXM6fG1tL52DN6nNkhBtvLJH2SrYLwmQoKGjeDcCZMoTsiYJmeaPXrfgvPRYzqM@wIDt9N1bbbroxCjyJ23noAbZlIK5qdee7vJdCCPXYGvlpQajviE8BDvrlen8pwim42gDAWjMKDnop38GlFkWp5GY0miBrlfcolOWTdI6hYKGDvxiSDTQNI5eA@HFeTWwcfZsQlZPDetozElvu16X3IPB3E0Wz0tAcXWZ67riAY0j0I3GZbVsdFGJu1CzTLxUj2XKrfKzNeD4uhGerNtW5fB77uN5@AE "Java (OpenJDK 8) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes
```
ITL
```
[Try it online!](https://tio.run/##y0rNyan8/98zxOf////RhjoKEGQERqZIyNBcR8E4FgA "Jelly – Try It Online")
## How it works
```
ITL - Full program.
I - Increments (deltas).
T - Get the indices of truthy values (gets the indexes of non-0 elements).
L - Length.
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 3 bytes
```
Ltg
```
[Try it online!](https://tio.run/##yygtzv7/36ck/f///9G6xjogCKQMYgE "Husk – Try It Online")
### Explanation
```
Ltg Input: [1,1,1,2,2,3]
g Group equal elements together: [[1,1,1],[2,2],[3]]
t Drop the first group (if any): [[2,2],[3]]
L Return the length of the list: 2
```
[Answer]
# [Ohm v2](https://github.com/MiningPotatoes/Ohm), 3 bytes
```
ΔyΣ
```
[Try it online!](https://tio.run/##y8/INfr//9yUynOL//@P1jXWUYAgEMsgFgA "Ohm v2 – Try It Online")
**Explanation**
```
Δ absolute differences between consecutive elements
y sign: 1 if positive, -1 if negative, 0 if zero
Σ sum
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 23 ~~24~~ ~~26~~ ~~29~~ bytes
```
Length@Split@#~Max~1-1&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73zexItonNS@9JMMhuCAns8RBWddQxyBW7X9AUWZeSXRadLWusQ4IAimD2tjY/wA "Wolfram Language (Mathematica) – Try It Online")
* -1 byte thanks to Martin Ender!
* -2 bytes thanks to JungHwan Min! nice use of `Split[]`.
* -3 bytes thanks to totallyhuman!
a little explanation:
`Split` will divide an array into a list of lists (of same elements), that is, turning `{1, 2, 2, 3, 1, 1}` into `{{1}, {2, 2}, {3}, {1, 1}}` . So, `Length@Split@#` is the quantity of consecutive segements. `Max[*****-1, 0]` is used to deal with `{}` input.
[Answer]
# [Retina](https://github.com/m-ender/retina), ~~24~~ ~~21~~ 16 bytes
*Thanks to @MartinEnder for -3 bytes and noticing a bug*
*-1 byte thanks to @tsh*
*-4 bytes thanks to @Leo*
```
m`^(\S+)¶(?!\1$)
```
[Try it online!](https://tio.run/##K0otycxL/K@qEZyg8D83IU4jJlhb89A2DXvFGEMVzf//uQy4DBQMgdiAy1DBSMFYwdAcyABBIxCXS9dYAQSBFFCBqYKhKZehEQgqGIEpAA "Retina – Try It Online")
[Answer]
# [Perl 6](https://perl6.org), 18 bytes
```
{sum $_ Z!= .skip}
```
[Test it](https://tio.run/##fY9NTsMwFIT3PsUgIZrQOk1qfiSiAlv2rAgWCsmDRiSOVTsSVcnJ2HGxYldZVLTUs7Ct741nrGlZX22aFc6KRa7eiRdtpyzmm7XpGpy@4Olkjsh8VLr3U/eWjKOoK0UmCKMm1zdrBnhUKQeiom1egylGfHSH53KMafjzHT0om7opNxItKC@Dc56Ek@3V5lU9cTmsZ6wzhEf3fsp0nSuMt2EpY2/tcgjmtwicS3fWeehTU2GpdMeSTBHCF6kML4l0vcLufwZTuO9KWb/JEnjNnC4HJdcQEl8ALlgmcXh5HLMslscxEvkfTjyO5RG3ryVcHXkAC7bTXMi/eMYyLuDltngPi18 "Perl 6 – Try It Online")
## Expanded:
```
{ # bare block lambda with implicit parameter 「$_」
sum # count the number of True values
$_ # the input
Z!= # zip using &infix:«!=»
.skip # the input, but starting from the second value
# (implicit method call on 「$_」
}
```
[Answer]
# [Symbolic Python](https://github.com/FTcode/Symbolic-Python), ~~120~~ 117 bytes
Golfed 3 bytes by removing an explicit cast to integer (using unary `+`) for the counter variable - this means that if there are no changes in the array the output will be `False` instead of `0`, but this is [allowed by meta](https://codegolf.meta.stackexchange.com/a/9067/60919).
```
___=-~(_==_)
__('___=~-'+`_>_`[___::___]+`__`[-~___]+'(_)')
__('__=___=_>_'+';___+=_[__]!=_[-~__];__=-~__'*___)
_=___
```
[**Try it online!**](https://tio.run/##NY2xDoMwDET3fkU7OTRkoiwg90dQdIguIJVSqSws@XX3EgnpZPvsd/LvWKftvbzC99jn7WMGQENyUEV1AZzkRQriRzwxDnRdxxLpaUMqszhUcuKaE4TFS8/RK5iKN7ZMx748AOTOIzMZN7Ohqa/Uo6g91cQ/ "Symbolic Python – Try It Online")
```
# LINE 1: Generate value '2' for utility
___=-~(_==_)
# LINE 2: Get len(input) - 1
__('___=~-'+`_>_`[___::___]+`__`[-~___]+'(_)')
'___=~-'+`_>_`[___::___]+`__`[-~___]+'(_)' # Generate string '___=~-len(_)'
`_>_`[___::___] # 'le' spliced from 'False'
+`__`[-~___] # 'n' indexed from '<function ...>'
'___=~-'+ +'(_)' # Remaining characters in plaintext
__( ) # Execute this to get len(input) - 1
# LINE 3: Main calculation loop
__('__=___=_>_'+';___+=_[__]!=_[-~__];__=-~__'*___)
__( ) # Execute:
'__=___=_>_' # Set var1, var2 to 0
+'; '*___ # len(input) - 1 times do:
_[__]!=_[-~__] # Compare input[var1, var1 + 1]
___+= ; # Add this to var2
__=-~__ # Increment var1
# LINE 4: Set output variable ('_') to the result calculated.
_=___
```
[Answer]
# Elm, 59 bytes
```
f x=case x of
a::b::c->f(b::c)+if a/=b then 1 else 0
_->0
```
You can test this out [here](https://elm-lang.org/try). Paste the following code to get started:
```
import Html exposing (text)
f x=case x of
a::b::c->f(b::c)+if a/=b then 1 else 0
_->0
main =
f [0,0,1,0]
|> Debug.toString
|> text
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 3 bytes
```
¥ĀO
```
[Try it online!](https://tio.run/##MzBNTDJM/f//0NIjDf7//0cb6ihAkBEYGccCAA "05AB1E – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), 4 bytes
```
#IẊ≠
```
[Try it online!](https://tio.run/##yygtzv7/X9nz4a6uR50L/v//H61rrAOCQMogFgA "Husk – Try It Online")
[Answer]
# [R](https://www.r-project.org/), 24 bytes
```
cat(sum(!!diff(scan())))
```
[Try it online!](https://tio.run/##K/r/PzmxRKO4NFdDUTElMy1Nozg5MU9DEwj@GyoYKRgrmCiYgqHZfwA "R – Try It Online")
Same as the MATL answer, just used `sum(!!diff))` since there's no `nnz`.
[Answer]
# [Cubix](https://github.com/ETHproductions/cubix), 24 bytes
```
UpO@0I>I!^-u>q.uvv$!^;)p
```
[Try it online](https://ethproductions.github.io/cubix/?code=ICAgIFUgcAogICAgTyBACjAgSSA%20IEkgISBeIC0gdQo%20IHEgLiB1IHYgdiAkICEKICAgIF4gOwogICAgKSBwCg==&input=LTMgMyAzIC0zIDE=&speed=5)
Note that Cubix uses 0 to indicate that there are no more inputs, so 0 cannot be in the list.
### Explanation
Unfolded:
```
U p
O @
0 I > I ! ^ - u
> q . u v v $ !
^ ;
) p
```
We start at the `0`, pushing the counter (initialized with `0`) and the first input (`I`) onto the stack.
We then enter the loop. At each iteration of the loop, we get the next input with `I`. If it's 0, we've run out of inputs, so we rotate the counter to the top (`p`), `O`utput, and exit (`@`).
Otherwise, we take the difference of the top two elements. If it's nonzero, we rotate the counter to the top, increment it, and rotate it back to the bottom with `p)q`. We then pop the difference with `;` before moving to the next iteration.
All the characters not mentioned here are just control flow. There tend to be a lot of those in Cubix programs.
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 8 bytes
```
+/2≠/⊃,⊢
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R2wRtfaNHnQv0H3U16zzqWgQUUzDgAmIFQzAJYhsqGCkYKxiag5mGYC5QAMg7tN5YAQRBtAEA "APL (Dyalog Unicode) – Try It Online")
**How?**
`⊃,⊢` - the list, with the first value repeated for the case of single element
`2≠/` - changes list, not equal for every 2 elements
`+/` - sum
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 50 bytes
```
(([][()]){[{}({}[({})])]{{}()(<()>)}{}([][()])}<>)
```
[Try it online!](https://tio.run/##SypKzMzTTctJzP7/X0MjOjZaQzNWszq6ulajujYaiIG82GogT1PDRkPTTrMWyIQqqrWx0/z/31ABBI2A0AQIjQE "Brain-Flak – Try It Online")
Since everyone is posting their 50 byte solutions here is mine (I have a [48 byte one](https://tio.run/##SypKzMzTTctJzP7/XyM6OjZWQ1OzWqO6VkPTBkhGA7FmrGZ1da2NHVhQU8PGTrO2uhZI2Nj9/2@oAIJGQGgKhYbmCsYA "Brain-Flak – Try It Online") but it was a simple modification of DjMcMayhem's so I did feel it worth posting)
# Explanation
This answer extensively uses value canceling.
Un-golfed it looks like
```
([][()])({<{}({}[({})])>{<{}>()(<()>)}{}<([][()])>}<>)
```
Here we compute the delta's until the stack has one item left, each time we accumulate one value from the inner loop if the delta is non zero.
This is a pretty straight forward way of doing it.
To make this golfy we begin value canceling. The first one and the one that should be obvious to any hardened brain-flak golfer is the stack heights. It is a well known fact that
```
([])({<{}>...<([])>}{})
```
is the same as
```
(([]){[{}]...([])}{})
```
When the values are modified by one, the same holds. This gives us
```
(([][()]){[{}]<({}[({})])>{<{}>()(<()>)}{}([][()])}<>)
```
You may notice this didn't even save us bytes, but don't fret it will become more useful as we go on.
We can perform another reduction, if you see a statement
```
<(...)>{<{}> ...
```
you can actually reduce it to
```
[(...)]{{} ...
```
This works because if we enter the loop `[(...)]` and `{}` will cancel, and if we don't the value of `[(...)]` already was zero in the first place and doesn't need to be canceled. Since we have an occurrence of this pattern in our code we can reduce it.
```
(([][()]){[{}][({}[({})])]{{}()(<()>)}{}([][()])}<>)
```
That saved us 2 bytes but it also put two negs next to each other. These can be combined to save us another 2.
```
(([][()]){[{}({}[({})])]{{}()(<()>)}{}([][()])}<>)
```
And that's our code.
[Answer]
# [Gaia](https://github.com/splcurran/Gaia), 2 bytes
```
ėl
```
[Try it online!](https://tio.run/##S0/MTPz//8j0nP@pj9om/o/WNVYAQSBlEAsA "Gaia – Try It Online")
This abuses a bug (or feature?) of Gaia, that run-length-encoding doesn't take the last run of elements into account. Note that I have double checked, it works for all test cases.
* `ė` - Run length encoding (with the flaw described above).
* `l` - Length.
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~52~~ 45 bytes
*(-7 bytes thanks to Julian)*
```
$i=0
$args|%{$i+=$p-ne$_-and$p-ne$n
$p=$_}
$i
```
[Try it online!](https://tio.run/##XZBBS8NAEIXP2V8xh9EmuAtpcvAgC4GCV8V6EwkxndqUmMTsBoU0vz3OupXaLrMw8977ZmG79ot6s6O6nnGrxxkrHQss@ndzuBqxutHYqYYwV0Wz8W0jsNOYTwKreRIiCwXwkVmYhZGEODqN8eUsYRm5eyZdppYSEgkp527ZSc8dX4mPsJ38s1X6i3G5LvZwBAe4b3sqyp16eNtTaWEUAVoyVgLSd8cKbUAD5iz3ZIba8nSNW8hcSAQvj@vVYGz74fHXjPlgPZQlGeO4I6Po87TvjiPPTK8KQy7jNoHat1UDCwkLZz/9PXVcwNok@D/n@Qc)
Takes input `$args`, dumps it into a for loop, each iteration checking whether the `$p`revious value is `-n`ot`e`qual to the current value `$_`, and whether the previous value is `$n`ull. Exploits the Boolean-to-int implicit converstion to accumulate that into `$i`. Outputs `$i` at the end.
The initial `$i=0` is needed to account for if the input is empty, and to (properly) account for when the input is a single value.
[Answer]
## JavaScript (ES6), 35 bytes
```
a=>a.filter((e,i)=>e-a[i+1]).length
```
[Answer]
# Pyth, 5 bytes
```
l #.+
```
[Test suite.](http://pyth.herokuapp.com/?code=l+%23.%2B&test_suite=1&test_suite_input=%5B%5D%0A%5B0%5D%0A%5B0%2C+1%5D%0A%5B0%2C+0%5D%0A%5B1%2C+2%2C+3%2C+17%5D%0A%5B1%2C+1%2C+1%2C+2%2C+2%2C+3%5D%0A%5B-3%2C+3%2C+3%2C+-3%2C+0%5D&debug=0)
Explanation:
```
.+ Deltas
# Filter on identity (space)
l Get length
```
[Answer]
# [Perl 5](https://www.perl.org/), 37 + 2 (`-ap`) = 39 bytes
```
$\+=$F[$_]!=$F[$_-1]for 1..$#F}{$\|=0
```
[Try it online!](https://tio.run/##K0gtyjH9/18lRttWxS1aJT5WEULrGsam5RcpGOrpqSi71VarxNTYGvz/b6gAgkZAaPwvv6AkMz@v@L9uYgEA "Perl 5 – Try It Online")
[Answer]
# J, 10 bytes
```
[:+/2~:/\]
```
Infixes of length 2... are they unequal? `2 ~:/\ ]`
Sum the resulting list of `0`s and `1`s: `+/`
[Try it online!](https://tio.run/##y/qfVqxga6VgoADE/6OttPWN6qz0Y2L/a3Ip6Smop9laqSvoKNRaKaQVc3GlJmfkA1XaKqQpGEA4hhCOgiGKHEzWGMw1VDACsgzNIWJGUDFDsDhQBllpvLECCAIpg/8A "J – Try It Online")
[Answer]
# Pyth, 4 bytes
```
ltr8
```
[Test suite](https://pyth.herokuapp.com/?code=ltr8&test_suite=1&test_suite_input=%5B1%2C1%2C1%2C2%2C2%2C5%2C5%2C5%2C5%2C17%2C3%5D%0A%5B%5D%0A%5B0%5D%0A%5B0%2C1%5D%0A%5B0%2C0%5D%0A%5B1%2C2%2C3%2C17%5D%0A%5B1%2C1%2C1%2C2%2C2%2C3%5D%0A%5B-3%2C3%2C3%2C-3%2C0%5D&debug=0)
"literate"
The number of changes is equal to the number of runs, ignoring the first run if any. `r8` run length encodes the input, `t` removes the first element if any, and `l` finds the length of the resulting list.
] |
[Question]
[
Here's the challenge. Write some code to output all the integers in a range. Sounds easy, but here's the tricky part. It will start with the lowest number, then the highest. Then the lowest number which isn't yet in the array. Then the highest which isn't yet in it.
## Example:
Lets take 1 to 5 as our start
The numbers are [1, 2, 3, 4, 5].
We take the first, so [1]. Remaining numbers are [2, 3, 4, 5].
We take the last, new array is [1, 5]. Remaining numbers are [2, 3, 4].
We take the first, new array is [1, 5, 2]. Remaining numbers are [3, 4].
We take the last, new array is [1, 5, 2, 4]. Remaining numbers are [3].
We take the first, new array is [1, 5, 2, 4, 3]. No numbers remaining, we're done.
Output [1, 5, 2, 4, 3]
## Rules:
* This is code golf, write it in the fewest bytes, any language.
* No standard loopholes.
* Links to an online interpreter, please? (E.g. <https://tio.run/>)
* Two inputs, both integers. Low end of range, and high end of range.
* I don't mind what the data type of the output is, but it must show the numbers in the correct order.
## Examples
Low: 4
High: 6
Result:
4
6
5
---
Low: 1
High: 5
Result:
1
5
2
4
3
---
Low: -1
High: 1
Result:
-1
1
0
---
Low: -1
high: 2
Result:
-1
2
0
1
---
Low: -50
High: 50
Result:
-50
50
-49
49
-48
48
-47
47
-46
46
-45
45
-44
44
-43
43
-42
42
-41
41
-40
40
-39
39
-38
38
-37
37
-36
36
-35
35
-34
34
-33
33
-32
32
-31
31
-30
30
-29
29
-28
28
-27
27
-26
26
-25
25
-24
24
-23
23
-22
22
-21
21
-20
20
-19
19
-18
18
-17
17
-16
16
-15
15
-14
14
-13
13
-12
12
-11
11
-10
10
-9
9
-8
8
-7
7
-6
6
-5
5
-4
4
-3
3
-2
2
-1
1
0
---
Happy golfing!
[Answer]
# [R](https://www.r-project.org/), ~~38~~ ~~37~~ 36 bytes
```
function(a,b)rbind(a:b,b:a)[a:b-a+1]
```
[Try it online!](https://tio.run/##XdHNSsNAFMXxfZ/igJsGc2DunZl8CD6JuGiVQjcVij5//VeRYsMvEG7ISXLP@XJ4vhy@Tm@fx4/Tdjfuh/P@eHrf7p724/5pN7xw4d1jvF4O2zZOg67Hg5om9c1hG2P/G4W6khuVsWOM4Xfs4E75neVtliqK67SXsZfhZ9qL4LYKbovgNgtuk@DWBbcmuFXBjdemNrodhLUQ3Irgugqui@A6C66T4NoFVz6dzFqFu7CagmsIrkVwroJzEZyz4JwEJ7sgM5twF5ZVcKbgZBdkZhEcq@BYBMcsOCbB0YW7sGiCowqOFBzsnMxgxUXyKpG58ACnZwmeRIX/w2hAlMjSRI/8pwSnaOvaGUWKKi/f "R – Try It Online")
* -1 byte thanks to @user2390246
* -1 byte thanks to @Kirill L.
Exploiting the fact that R stores matrices column-wise
[Answer]
# [Haskell](https://www.haskell.org/), 30 bytes
```
a%b=a:take(b-a)(b:(a+1)%(b-1))
```
[Try it online!](https://tio.run/##bctBCoAgEEbhfaf4FwkzRJCRLYQOM5KQZBbV/c1t0fJ98Ba5Vh9jzqLcJPaW1ZNrhclZkkazKqWZ8yYhYcK8VzjOkG7UIMUYML5Bw7yByg79Y/3XTMcwXZUf "Haskell – Try It Online")
[Answer]
# [R](https://www.r-project.org/), ~~65~~ ~~64~~ ~~61~~ 60 bytes
-1 byte thanks to Robert S.
-4 more thanks to digEmAll
```
x=scan();z=x:x[2];while(sum(z|1)){cat(z[1],"");z=rev(z[-1])}
```
[Try it online!](https://tio.run/##K/r/v8K2ODkxT0PTusq2wqoi2ijWujwjMydVo7g0V6OqxlBTszo5sUSjKtowVkdJCaSqKLUMyNU1jNWs/W/EZcr1HwA "R – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 39 bytes
```
a#b|a>b=a:b#(a-1)|a<b=a:b#(a+1)|1>0=[a]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P1E5qSbRLsk20SpJWSNR11CzJtEGxtMG8gztDGyjE2P/5yZm5inYKhQUZeaVKKgoaOgaayooKxj/BwA "Haskell – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 44 bytes
```
f=lambda a,b:[a]*(a==b)or[a]+f(b,a-cmp(a,b))
```
[Try it online!](https://tio.run/##Lcw7CoAwEATQ3lNsuasrGDEWQk4iFhslKGgSgo2njx@s3sAME69zDb7N2ZldDrsICNthlKlEMcZSSE@uHFqWej4iPi1RdiG9O9g8jNhxTwyoWL/UitVv@6kb1g1NQwEQ0@ZPcN9JvgE "Python 2 – Try It Online")
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~59~~ 48 bytes
```
param($a,$b)(($z=0..($b-$a))|%{$a+$_;$b-$_})[$z]
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/vyCxKDFXQyVRRyVJU0NDpcrWQE9PQyVJVyVRU7NGtVolUVsl3hrEj6/VjFapiv3//7@GrqHmfyMA "PowerShell – Try It Online")
~~*(Seems long...)*~~
Takes input `$a` and `$b`, constructs the range `0 .. ($b-$a)`, stores that into `$z`, then loops through that range. The looping through that range is just used as a counter to ensure we get enough iterations. Each iteration, we put `$a` and `$b` on the pipeline with addition/subtraction. That gives us something like `1,5,2,4,3,3,4,2,5,1` so we need to slice into that from `0` up to the `$b-$a` (i.e., the count) of the original array so we're only left with the appropriate elements. That's left on the pipeline and output is implicit.
*-11 bytes thanks to mazzy.*
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes
```
ŸDvć,R
```
[Try it online!](https://tio.run/##yy9OTMpM/f//6A6XsiPtOkH//0frmhromBrEAgA "05AB1E – Try It Online")
**Explanation**
```
Ÿ # push range [min ... max]
D # duplicate
v # for each element in the copy
ć, # extract and print the head of the original list
R # and then reverse it
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 14 bytes
```
òV
íUs w)c vUl
```
[Try it online!](https://tio.run/##y0osKPn///CmMK7Da0OLFco1kxXKQnP@/9c1NeAyNQAA "Japt – Try It Online")
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 7 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
É╓ÅìΔà▲
```
[Run and debug it](https://staxlang.xyz/#p=90d68f8dff851e&i=4+6%0A1+5%0A-1+1%0A-1+2%0A-50+50&a=1&m=2)
[Answer]
# [R](https://www.r-project.org/), 51 bytes
```
function(x,y,z=x:y)matrix(c(z,rev(z)),2,,T)[seq(z)]
```
[Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP0@jQqdSp8q2wqpSMzexpCizQiNZo0qnKLVMo0pTU8dIRydEM7o4tRDIi/2fpmGiY6bJlaZhqGMKonQNdQyhtBGYNjXQMTXQ/A8A "R – Try It Online")
Explanation:
For a sequence `x:y` of length `N`, create a two-by-N matrix consisting of the sequence x:y in the top row and y:x in the bottom row `matrix(c(z,rev(z)),2,,T)`. If we select the first `N` elements of the matrix `[seq(z)]`, they will be chosen by column, giving the required output.
[Outgolfed by digEmAll](https://codegolf.stackexchange.com/a/179869/66252)
[Answer]
# [cQuents](https://github.com/stestoltz/cQuents), 19 bytes
```
#|B-A+1&A+k-1,B-k+1
```
[Try it online!](https://tio.run/##Sy4sTc0rKf7/X7nGSddR21DNUTtb11DHSTdb2/D/f11DBUMA "cQuents – Try It Online")
Note that it does not work on TIO right now because TIO's interpreter is not up to date.
## Explanation
```
#|B-A+1&A+k-1,B-k+1
A is the first input, B is the second input
#|B-A+1 n = B - A + 1
& Print the first n terms of the sequence
k starts at 1 and increments whenever we return to the first term
A+k-1, Terms alternate between A + k - 1 and
B-k+1 B - k + 1
increment k
```
[Answer]
## Haskell, 39 bytes
```
f(a:b)=a:f(reverse b)
f x=x
a#b=f[a..b]
```
[Try it online!](https://tio.run/##bci9CoAgFAbQ3af4oAYdCotsCHySaLiSkvSLRfT21lp0xjPQPtppitFxaozQ1Dge7GnDbmEEc7j0xSgx2rWU56aLM/kFGv3KsAW/HEjBE4EK9TsKqHfwrHj258rvKSmgJIs3 "Haskell – Try It Online")
[Answer]
# Haskell, 30 bytes
```
l%h=l:take(h-l)(h:(l+1)%(h-1))
```
Usage: `3%7` gives `[3,7,4,6,5]
For the inputs `l, h` the function calls recursively with the inputs `l+1, h-1`, and adds `l,h` to the beggining.
Instead of any halting condition, the code uses `take(h-l)` to shorten the sequence to the right length (which would otherwise be an infinite sequence of increasing and decreasing numbers).
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 46 bytes
```
a=>b=>{for(;a<=b;Write(a+(b>a++?b--+"":"")));}
```
Saved 4 bytes thanks to dana!
[Try it online!](https://tio.run/##Sy7WTS7O/O9Wmpdsk5lXouOYXJKZnwdi2tml2f5PtLVLsrWrTssv0rBOtLFNsg4vyixJ1UjU1kiyS9TWtk/S1dVWUrJSUtLU1LSu/W/NlaZhqKlhqmnNBVbok5mXqqEJFTXRtP4PAA "C# (Visual C# Interactive Compiler) – Try It Online")
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 65 bytes
```
void z(int a,int b){if(a<=b){Write(a+(b>a?b+"":""));z(a+1,b-1);}}
```
[Try it online!](https://tio.run/##Sy7WTS7O/P@/LD8zRaFKIzOvRCFRB0QmaVZnpmkk2tgCGeFFmSWpGonaGkl2ifZJ2kpKVkpKmprWVUAhQ50kXUNN69ra/1UahjqmmtZcYMU@mXmpGkAOSNBE0/o/AA "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# JVM bytecode (OpenJDK asmtools JASM), 449 bytes
```
enum b{const #1=Method java/io/PrintStream.print:(I)V;static Method a:(II)V stack 2 locals 4{getstatic java/lang/System.out:"Ljava/io/PrintStream;";astore 3;ldc 0;istore 2;l:iload 2;ldc 1;if_icmpeq t;aload 3;iload 0;invokevirtual #1;iinc 0,1;iinc 2,1;goto c;t:aload 3;iload 1;invokevirtual #1;iinc 1,-1;iinc 2,-1;c:aload 3;ldc 32;i2c;invokevirtual java/io/PrintStream.print:(C)V;iload 0;iload 1;if_icmpne l;aload 3;iload 0;invokevirtual #1;return;}}
```
Ungolfed (and slightly cleaner)
```
enum b {
public static Method "a":(II)V stack 5 locals 4 {
getstatic "java/lang/System"."out":"Ljava/io/PrintStream;";
astore 3;
ldc 0;
istore 2;
loop:
iload 2;
ldc 1;
if_icmpeq true;
false:
aload 3;
iload 0;
invokevirtual "java/io/PrintStream"."print":"(I)V";
iinc 0,1;
iinc 2,1;
goto cond;
true:
aload 3;
iload 1;
invokevirtual "java/io/PrintStream"."print":"(I)V";
iinc 1,-1;
iinc 2,-1;
goto cond;
cond:
iload 0;
iload 1;
if_icmpne loop;
aload 3;
iload 0;
invokevirtual "java/io/PrintStream"."print":"(I)V";
return;
}
}
```
Standalone function, needs to be called from Java as `b.a(num1,num2)`.
## Explanation
This code uses the method parameters as variables, as well as a boolean in local #3 deciding which number to output. Each loop iteration either the left or right is output, and that number is incremented for the left or decremented for the right. Loop continues until both numbers are equal, then that number is output.
...I have a distinct feeling I'm *massively* outgunned on the byte count
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~56~~ 54 bytes
This is my first time golfing!
```
f[a_,b_]:=(c=a~Range~b;Drop[c~Riffle~Reverse@c,a-b-1])
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78/z8tOjFeJyk@1spWI9k2KDEvPTU6UScp1tqlKL8gOigzLS0nNTpZJyi1LLWoONUhOVYnUTdJ1zBW839AUWZeiUNatImOglksF4xnqKNgiuDpArmGqFyj2P8A "Wolfram Language (Mathematica) – Try It Online")
Saved 2 bytes using infix notation.
Explanation:
```
f[a_,b_]:= \function of two variables
c=a~Range~b; \list of integers from a to b
Reverse@c \same list in reverse
c~Riffle~Reverse@c \interleave the two lists
Drop[c~Riffle~Reverse@c,a-b-1] \drop last |a-b-1| elements (note a-b-1 < 0)
```
Alternatively, we could use `Take[...,b-a+1]` for the same result.
Tests:
```
f[4, 6]
f[1, 5]
f[-1, 1]
f[-1, 2]
```
Ouput:
```
{4, 6, 5}
{1, 5, 2, 4, 3}
{-1, 1, 0}
{-1, 2, 0, 1}
```
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf), 6 bytes
```
↨_x^─▀
```
[Try it online!](https://tio.run/##y00syUjPz0n7//9R24r4irhHUxoeTWv4/99EwYzLUMGUS9dQwRBEGHHpmhoomBoAAA "MathGolf – Try It Online")
## Explanation with `(1, 5)`
```
↨ inclusive range from a to b [1, 2, 3, 4, 5]
_ duplicate TOS [1, 2, 3, 4, 5], [1, 2, 3, 4, 5]
x reverse int/array/string [1, 2, 3, 4, 5], [5, 4, 3, 2, 1]
^ zip top two elements on stack [[1, 5], [2, 4], [3, 3], [4, 2], [5, 1]]
─ flatten array [1, 5, 2, 4, 3, 3, 4, 2, 5, 1]
▀ unique elements of string/list [1, 5, 2, 4, 3]
```
The reason why this works is due to the fact that all elements in the output should be unique, so the unique elements operator will filter out the second half of the array, producing the correct output.
[Answer]
# [APL (dzaima/APL)](https://github.com/dzaima/APL), 21 bytes
```
⌈⊢+.5×-+∘(⌽ׯ1*)∘⍳1+-
```
[Try it online!](https://tio.run/##SyzI0U2pSszMTfz/P@1R24RHPR2PuhZp65kenq6r/ahjhsajnr2Hpx9ab6ilCeQ96t1sqK37/7@ZQpqCCZcpkDTkMgSSQHkuIyhtagBmmBr8yy8oyczPK/6vWwwA "APL (dzaima/APL) – Try It Online")
[Answer]
# Japt, 7 bytes
Takes input as an array.
```
rõ
ÊÆÔv
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=cvUKysbUdg==&input=WzEsNV0=) or [run all test cases](https://ethproductions.github.io/japt/?v=1.4.6&code=cvUKysbUdg==&input=WwpbNCw2XQpbMSw1XQpbLTEsMV0KWy0xLDJdClstNTAsNTBdCl0KLW1S)
```
:Implicit input of array U=[low,high]
r :Reduce by
õ : Inclusive, reversed range (giving the range [high,low])
\n :Reassign to U
Ê :Length
Æ :Map the range [0,Ê)
Ô : Reverse U
v : Remove the first element
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 8 bytes
```
&:t"1&)P
```
[Try it online!](https://tio.run/##y00syfn/X82qRMlQTTPg/39DLlMA "MATL – Try It Online")
### Explanation
```
&: % Take two inputs (implicit). Two-input range
t % Duplicate
" % For each
1&) % Push first element, then an array with the rest
P % Reverse array
% End (implicit). Display (implicit)
```
[Answer]
# JavaScript, 40 bytes
```
l=>g=h=>h>l?[l++,h--,...g(h)]:h<l?[]:[l]
```
[Try It Online!](https://tio.run/##LchLDoMgFEDROavoEOKDSFM6MEIXgi/BWBUNBVObRldPP3F0bu7cvtu1e07Li8d07/Ogc9Bm1F4bb8LNhqIAzzkIIUbqGVa@/l6sbMDcpbim0IuQRmoJsRe4IhArQf3gEuTh@a8qQZVICIpHu1BqN9iRaTPQjdGdiTlN0cHJHdXEJjqWPw)
[Answer]
# [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 52 bytes
```
: f 2dup - 1+ 0 do dup . i 2 mod 2* 1- - swap loop ;
```
[Try it online!](https://tio.run/##JYxBCgIxFEP3PcVjlsov0@q4cMC7iKUqKP1UZY5ff@kieYSQ5FK/D7nnjtbOZGL6KULYM5MKPXmeRN4lEXcEsfazXZVXKcpqIx2jA74O8xPIhcnubpXVuRNH1C0E84B0xIFlRkza/g "Forth (gforth) – Try It Online")
### Explanation
Loop from 0 to (End - Start). Place End and Start on top of the stack.
Each Iteration:
* Output the current number
* Add (or subtract) 1 from the current number
* Switch the current number with the other number
### Code Explanation
```
: f \ start new word definition
2dup - \ get the size of the range (total number of integers)
1+ 0 \ add 1 to the size because forth loops are [Inclusive, Exclusive)
do \ start counted loop from 0 to size+1
dup . \ output the current top of the stack
i 2 mod \ get the index of the loop modulus 2
2* 1- \ convert from 0,1 to -1,1
- \ subtract result from top of stack (adds 1 to lower bound and subtracts 1 from upper)
swap \ swap the top two stack numbers
loop \ end the counted loop
; \ end the word definition
```
[Answer]
# [Julia 0.7](http://julialang.org/), 29 bytes
```
f(a,b)=[a:b b:-1:a]'[1:1+b-a]
```
[Try it online!](https://tio.run/##yyrNyUw0//8/TSNRJ0nTNjrRKkkhyUrX0CoxVj3a0MpQO0k3MfZ/QVFmXklOnkaahomOmaYmF4JvqGOKwtc11DFEFzBCFTA10DE10NT8DwA "Julia 0.7 – Try It Online")
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 15 bytes
```
⟦₂{∅|b↔↰T&hg,T}
```
Input is a 2-element list [lo, hi]. Note that underscore is used for negative numbers. [Try it online!](https://tio.run/##SypKTM6ozMlPN/r//9H8ZY@amqofdbTWJD1qm/KobUOIWka6Tkjt///R8YY6prH/IwA "Brachylog – Try It Online")
### Explanation
```
⟦₂ 2-argument inclusive range: [1,5] -> [1,2,3,4,5]
{ } Call this recursive predicate to calculate the output:
∅ Base case: the input is empty list; nothing to do
| Otherwise (recursive case): [1,2,3,4,5]
b Behead the input list [2,3,4,5]
↔ Reverse [5,4,3,2]
↰ Call the predicate recursively [5,2,4,3]
T Label the result T
& Also, with the input list,
h Take the head 1
g Wrap it in a list [1]
,T Append T from earlier [1,5,2,4,3]
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes
```
ŸÂ.ιÙ
```
Takes input as upper first.
Explanation:
```
ŸÂ.ιÙ //full program
Ÿ //push [min .. max] stack: [[4, 5, 6]]
 //push range and reversed range stack: [[4, 5, 6], [6, 5, 4]]
.ι //interleave stack: [[4, 6, 5, 5, 6, 4]]
Ù //deduplicate stack: [[4, 6, 5]]
```
[Try it online!](https://tio.run/##yy9OTMpM/f//6I7DTXrndh6e@f@/GZcJAA "05AB1E – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/) `-ln`, 37 bytes
```
@.=$_..<>;say shift@.,$/,[[email protected]](/cdn-cgi/l/email-protection)@.
```
[Try it online!](https://tio.run/##K0gtyjH9/99Bz1YlXk/Pxs66OLFSoTgjM63EQU9HRV@nIL/AQa88IzMn1UHv/39dI1MuI9N/@QUlmfl5xf91fU31DAwN/uvm5AEA "Perl 5 – Try It Online")
[Answer]
# [Java (JDK)](http://jdk.java.net/), 52 bytes
```
(l,h,o)->{for(int i=0;l<=h;i^=1)o.add(i<1?l++:h--);}
```
[Try it online!](https://tio.run/##ZY4xa8MwEIV3/4obpUYWydClilOyZGqnjKUF1bbic2XJSOeUEPzbXdlJoVDQIe59d@9dq886b6uvCbveB4I29XIgtPJBZf80M7iS0LsZllbHCK8aHVwzAHRUB6PLGg5LD3D2WIFhCYAVM4dG/PF6wUjguUqzY6p@@LRYQiRN6Vt2u9mbHSmgO729gw6nyO/eKcQUE7OiEZ7nu6vxYQnCYq3stmgUfhQb7qWuKobbzbNdrZ6aPOdqnNRicEsfCApw9TfsQ9CXWWP8xo00LH9ci/Tmsbt6vESqO5kE2aeryDr2C8dsnH4A "Java (JDK) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
rạṂ¥Þ,
```
[Try it online!](https://tio.run/##ARwA4/9qZWxsef//cuG6oeG5gsKlw54s////LTUw/zUw "Jelly – Try It Online")
[Answer]
# [Clean](https://github.com/Ourous/curated-clean-linux), 48 bytes
```
import StdEnv
$a b|a<>b=[a: $b(a+sign(b-a))]=[a]
```
[Try it online!](https://tio.run/##S85JTcz7n5ufUpqTqpCbmJn3PzO3IL@oRCG4JMU1r4xLJVEhqSbRxi7JNjrRSkElSSNRuzgzPU8jSTdRUzMWKBj7P7gkEajeVkFFQdfUQMHU4P@/5LScxPTi/7qePv9dKvMSczOTiwE "Clean – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~37~~ ~~36~~ 33 bytes
```
f=->a,b{a>b ?[]:[a,b]|f[a+1,b-1]}
```
[Try it online!](https://tio.run/##KypNqvz/P81W1y5RJ6k60S5JwT461ioayImtSYtO1DbUSdI1jK39H80VbaJjFqvDFW2oYwqidA11DKG0EZg2NdAxNYjlitVLTUzOqK4BmlBToJAGNqn2PwA "Ruby – Try It Online")
Recursive version with 3 bytes saved by G B.
### [Ruby](https://www.ruby-lang.org/), 38 bytes
```
->a,b{d=*c=a..b;c.map{d.reverse!.pop}}
```
[Try it online!](https://tio.run/##Lcy7CoAgFADQ3a@oNW4XjWwJ@xFxUDNaIjEKwvx2e9B0thN2c@ZJ5HrQYOIoKis0ouktLtrHEYM7XNhciX71KWVJZAudAiIZ8JeaAfttPjkFThVR6LSd4/Wsly8m@ahSvgE "Ruby – Try It Online")
Non-recursive version.
] |
[Question]
[
**Closed**. This question needs to be more [focused](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** Update the question so it focuses on one problem only by [editing this post](/posts/428/edit).
Closed 7 years ago.
[Improve this question](/posts/428/edit)
About Code-Bowling:
>
> In golf, you try to get the lowest score (smallest application, most elegant, etc). In Bowling, you try to get the highest score. So if you follow, the goal of a Code-Bowling challenge is to make the biggest, most bastardized, hardest to maintain piece of code that still meets the requirements of the challenge. However, there's no point in making source longer just for the sake of it. It needs to seem like that added length was from design and not just padding.
>
>
>
**The Challenge:**
Create a program that sorts a list of numbers in ascending order.
**Example:**
*Input:* 1, 4, 7, 2, 5
*Output:* 1, 2, 4, 5, 7
*Code:* Obviously this wouldn't be a good answer, since there aren't many WTFs in there
```
function doSort(array $input) {
sort($input);
return $input;
}
```
**Rules:**
There are no real rules. As long as the program functions, have at it!
**Remember:** This is code-bowling, not golf. The objective is to make the worst, most bastardized code that you can! Bonus points for code that looks good, but is actually deceptively evil...
[Answer]
Sorting by user input. What can be worse?
```
function sort(array) {
newArray = new Array
notSorted = true;
while (notSorted) {
sortfail = false;
i = -1
for (;;) {
if ((++i + 1) == array.length) break;
if (confirm("is " + array[i] + " less than " + array[i + 1])) {
newArray[i] = array[i]
newArray[i + 1] = array[i + 1]
} else {
newArray[i] = array[i + 1]
newArray[i + 1] = array[i]
array[i] = newArray[i]
array[i + 1] = newArray[i + 1]
sortfail = true
}
}
array = newArray;
if (!sortfail) notSorted = false
}
return array
}
console.log(sort([2,1,3]))
```
See live [example](http://jsfiddle.net/Raynos/yf5Va/)
[Answer]
```
class Array
def sort
self.permutation.min
end
end
```
Ah, the elegance of Ruby...
self.permutation results in an enumerator. No harm done, yet. The innocent looking .min however sucks this enumerator into an array. This array's size explodes when the number of elements rises. Not to mention this ruines a fine pre-existing sort.
[Answer]
## Bogosort!
```
import random
def is_sorted(seq):
for x, y in zip(seq[:-1], seq[1:]):
if x > y:
return False
return True
def sort(seq):
while not is_sorted(seq):
random.shuffle(seq)
```
[Answer]
# Perl Bubble Sort
```
push(@m,'0');$a=<>;push(@m,$a);
$a=pop@m;push(@c,$a);
push(@m,'p');$a=pop@m;$b=pop@m;$hash{$a}=$b;
$a=pop@c;push(@c,$a);for(1..$a){$a=<>;push(@m,$a);
push(@m,'p');$a=pop@m;push(@m,$hash{$a});
$a=pop@m;$b=pop@m;$hash{$a}=$b;
push(@m,'p');$a=pop@m;push(@m,$hash{$a});
push(@m,'1');$a=pop@m;$b=pop@m;push(@m,$b+$a);
push(@m,'p');$a=pop@m;$b=pop@m;$hash{$a}=$b;
}$a=pop@c;push(@m,$a);
push(@m,'2');$a=pop@m;$b=pop@m;for(1..$a){push(@m,$b);};
$a=pop@m;$b=pop@m;push(@m,$b*$a);
$a=pop@m;push(@c,$a);
$a=pop@c;push(@c,$a);for(1..$a){push(@m,'1');$a=pop@m;push(@m,-$a);
push(@m,'p');$a=pop@m;$b=pop@m;$hash{$a}=$b;
$a=pop@c;push(@c,$a);for(1..$a){push(@m,'p');$a=pop@m;push(@m,$hash{$a});
push(@m,'1');$a=pop@m;$b=pop@m;push(@m,$b+$a);
push(@m,'p');$a=pop@m;$b=pop@m;$hash{$a}=$b;
push(@m,'p');$a=pop@m;push(@m,$hash{$a});
$a=pop@m;push(@m,$hash{$a});
push(@m,'p');$a=pop@m;push(@m,$hash{$a});
push(@m,'1');$a=pop@m;push(@m,-$a);
$a=pop@m;$b=pop@m;push(@m,$b+$a);
$a=pop@m;push(@m,$hash{$a});
$a=pop@m;$b=pop@m;if($b < $a){push(@c,1)}else{push(@c,0)};
$a=pop@c;push(@c,$a);for(1..$a){push(@m,'p');$a=pop@m;push(@m,$hash{$a});
$a=pop@m;push(@m,$hash{$a});
push(@m,'t');$a=pop@m;$b=pop@m;$hash{$a}=$b;
push(@m,'p');$a=pop@m;push(@m,$hash{$a});
push(@m,'1');$a=pop@m;push(@m,-$a);
$a=pop@m;$b=pop@m;push(@m,$b+$a);
$a=pop@m;push(@m,$hash{$a});
push(@m,'p');$a=pop@m;push(@m,$hash{$a});
$a=pop@m;$b=pop@m;$hash{$a}=$b;
push(@m,'t');$a=pop@m;push(@m,$hash{$a});
push(@m,'p');$a=pop@m;push(@m,$hash{$a});
push(@m,'1');$a=pop@m;push(@m,-$a);
$a=pop@m;$b=pop@m;push(@m,$b+$a);
$a=pop@m;$b=pop@m;$hash{$a}=$b;
}$a=pop@c;push(@m,$a);
$a=pop@m;
}}push(@m,'0');push(@m,'p');$a=pop@m;$b=pop@m;$hash{$a}=$b;
$a=pop@c;push(@c,$a);for(1..$a){push(@m,'p');$a=pop@m;push(@m,$hash{$a});
$a=pop@m;push(@m,$hash{$a});
$a=pop@m;print$a;
push(@m,'p');$a=pop@m;push(@m,$hash{$a});
push(@m,'1');$a=pop@m;$b=pop@m;push(@m,$b+$a);
push(@m,'p');$a=pop@m;$b=pop@m;$hash{$a}=$b;
}
```
I was going for the "every single line looks like the same piece of line noise" look. The first line of input (on STDIN) tells the program how many numbers there are, while the next N number of lines contain one number that needs to be sorted.
[Answer]
# Generic, multithreaded bogosort in Java
### 46 seconds to sort 4 numbers
I thought it would be elegant with support for generics.
Also, multithreading is always nice, so I use that instead of randomization: This program generates one thread for each number to be sorted. Each thread tries to insert its element into an array object, and when all elements have been inserted, the program will check if the array is sorted. If not, try again. Off course this insertion needs to be synchronized.
### ElementInserter
This will be the class that we use for the threads.
This class holds one element and tries to insert it into its `sortedArray`:
```
class ElementInserter<E extends Comparable<? super E>> implements Runnable {
E element;
SortedArray<? super E> target;
ElementInserter(E e, SortedArray<? super E> a) {
element = e;
target = a;
}
@Override
public void run() {
target.insert(element);
}
}
```
### sortedArray
Sports a straight-forward insert method. When last element has been inserted, it checks if the array is sorted.
```
class SortedArray<E extends Comparable<? super E>> {
boolean sorted; int i = 0; E[] a;
SortedArray(E[] e) { a = e; }
synchronized public void insert(E e) {
while (!sorted) {
a[i++] = e;
if (i == a.length) {
sorted = true;
for (int j = 1; j < i; ++j)
if (a[j-1].compareTo(a[j]) > 0) {
sorted = false;
i = 0;
notifyAll();
}
if (sorted) {
for (int j = 0; j < a.length; ++j) System.out.print(a[j]+" ");
System.out.println();
notifyAll(); // allow all threads to terminate
}
} else
try { wait(); }
catch(InterruptedException x) { }
}
}
}
```
### Main method
Parses command line arguments as Integers, creates a new array and a new thread for each Integer:
```
public static void main (String[] args) {
Integer[] i = new Integer[args.length];
SortedArray<Integer> c = new SortedArray<Integer>(i);
for (String s : args)
new Thread(new ElementInserter<Integer>(Integer.parseInt(s), c)).start();
}
```
### Test run
Execution time will depend on the original order of the elements and your scheduler implementation. This is on a dual-core 2.9 GHz Intel i7 MacBook Pro:
```
$ time java Main 3 1 2 4
1 2 3 4
real 0m46.307s
user 0m14.629s
sys 0m26.207s
```
[Answer]
## JavaScript (with animation!). 8172 chars. Few hours for 6 numbers.
We like lottery, right? Similar to Bogosort by dan04, but using physics and **animation**...
```
(function(){var e={},v=!1,G=/abc/.test(function(){abc})?/\b_super\b/:/.*/,H=function(c,a,b){return function(){var l=this._super,s;this._super=b[c];try{s=a.apply(this,arguments)}finally{this._super=l}return s}};e.Class=function(){};e.Class.extend=function a(b){var l=this.prototype;v=!0;var s=new this;v=!1;for(var c in b)s[c]="function"===typeof b[c]&&"function"===typeof l[c]&&G.test(b[c])?H(c,b[c],l):b[c];b=function(){!v&&this.init&&this.init.apply(this,arguments)};b.prototype=s;b.prototype.constructor=
b;b.extend=a;return b};e.Events={};var k=e.Events,z,A,w=Object.prototype.toString,I=document.createEvent,r=Date.now;k.EventListener=e.Class.extend({handleEvent:function(){},init:function(a){this.handleEvent=a}},"EventListener");z=k.EventListener;k.Event=e.Class.extend({timeStamp:0,type:"",target:null,cancelable:!1,defaultPrevented:!1,preventDefault:function(){this.cancelable&&(this.defaultPrevented=!0)},initEvent:function(a,b){this.type=a;this.target=b;this.timeStamp=r()}},"Event");A=k.Event;var t=
Object.create(null);e.createEventType=function(a,b){t[a]=A.extend(b,a);return t[a]};e.createEvent=function(a){return null!=t[a]?(a=new t[a],a.timeStamp=r(),a):I(a)};k.EventTarget=e.Class.extend({_listeners:{},addEventListener:function(a,b,l){var c=this._listeners[a];if(!(null!=c&&function(){for(var a="object"===typeof l?l:null,d,e=0,f=c.length;e<f;e++)if(d=this.listeners[e],d.listener.handleEvent===b&&d.scope===a)return!0;return!1}())){var d={listener:"object"===typeof b&&b.handleEvent?b:new z(b),
scope:"object"===typeof l?l:null};"[object Array]"===w.call(c)?c.push(d):this._listeners[a]=[d]}},removeEventListener:function(a,b,c){a=this._listeners[a];if("[object Array]"===w.call(a)){c="object"===typeof c?c:null;for(var d=0,e=a.length;d<e;d++)if(a[d].listener.handleEvent===b&&a[d].scope===c){a.splice(d,1);break}}},dispatchEvent:function(a){a.target||(a.target=this);var b=0,c=this._listeners[a.type],d=c.length,e;if("[object Array]"===w.call(c))for(;b<d;b++)e=c[b].listener.handleEvent,e.call(c[b].scope,
a);return a.defaultPrevented}},"EventTarget");for(var B=0,k=["ms","moz","webkit","o"],h=0;h<k.length&&!window.requestAnimationFrame;++h)window.requestAnimationFrame=window[k[h]+"RequestAnimationFrame"],window.cancelAnimationFrame=window[k[h]+"CancelAnimationFrame"]||window[k[h]+"CancelRequestAnimationFrame"];window.requestAnimationFrame||(window.requestAnimationFrame=function(a){var b=r(),c=Math.max(0,16-(b-B)),d=window.setTimeout(function(){a(b+c)},c);B=b+c;return d});window.cancelAnimationFrame||
(window.cancelAnimationFrame=function(a){clearTimeout(a)});var x=window.clearInterval,C=window.setInterval,D=e.Class.extend({fn:function(){},args:[],thisArg:window,sleepTime:0,init:function(a,b,c){this.method=a||function(){};this.thisArg=b||window;this.args=c||[]}},"FunctionToCall"),r=Date.now,u=Object.create(null);u.animation=0;u.steady=1;u.as_fast_as_possible=2;e.Timer=e.Events.EventTarget.extend({ANIMATION:0,STEADY:1,AS_FAST_AS_POSSIBLE:2,TimerEvent:e.createEventType("TimerEvent",{FPS:0,targetFPS:0,
delta:0,initEvent:function(a,b){if(null==b.getFPS||null==b.targetFPS||null==b.dt)throw notATimerException;this.FPS=b.getFPS();this.targetFPS=b.targetFPS;this.delta=b.dt;this._super(a,b)}}),_clearIntervalFlag:!1,_recursionCounter:0,_tickHandlersFromMethod:Object.create(null),running:!1,paused:!1,mode:0,autoStartStop:!0,setAutoStartStop:function(a){this.autoStartStop=a},prevTime:0,dt:0,maxDelta:0.05,setMaxDelta:function(a){this.maxDelta=a},sysTimerId:-1,targetFPS:50,setFPS:function(a){this.targetFPS=
a;if(this.running&&this.mode===this.STEADY){x(this.sysTimerId);var b=this;this.sysTimerId=C(function(){b.tick()},1E3/a)}},getFPS:function(){return 1/this.dt},queue:[],addToQueue:function(a,b,c){var d=new D(a,b,c),e;this.queue.push(d);var f=function J(f){0<d.sleepTime?d.sleepTime-=f.delta:(e=a.apply(b,[f].concat(c)),"number"===typeof e&&0<e?d.sleepTime=e:!0!==e&&(this.removeEventListener("tick",J,this),this.queue.splice(this.queue.indexOf(d),1)))};null==this._tickHandlersFromMethod[a]?this._tickHandlersFromMethod[a]=
[f]:this._tickHandlersFromMethod[a].push(f);this.addEventListener("tick",f,this);this.autoStartStop&&!this.running&&this.startLoop()},removeFromQueue:function(a){var b=this._tickHandlersFromMethod[a];a=this.queue.indexOf(a);if(-1!==a){for(var c=0,d=b.length;c<d;c++)this.removeEventListener("tick",b[c],this);return this.queue.splice(a,1)}},getQueue:function(){return this.queue.slice(0)},pause:function(){this._clearIntervalFlag=this.paused=!0;this.dt=0},resume:function(){this.paused=!1;this.startLoop()},
startLoop:function(){this.prevTime=r();this.running=!0;if(this.mode===this.steady){var a=this;this.sysTimerId=C(function(){a.tick()},1E3/this.targetFPS)}else this.tick()},tick:function(){if(this._clearIntervalFlag&&-1!==this.sysTimer)x(this.sysTimerId),this.sysTimerId=-1,this._clearIntervalFlag=!1;else if(!this.paused){var a=r();this.dt=(a-this.prevTime)/1E3;this.dt>this.maxDelta&&(this.dt=this.maxDelta);if(0===this.dt&&4>this._recursionCounter)this._recursionCounter++,this.tick();else{0<this._recursionCounter&&
(this._recursionCounter=0);var b=e.createEvent("TimerEvent");b.initEvent("tick",this);this.dispatchEvent(b);this.prevTime=a;a=!(this.autoStartStop&&0>=this.queue.length);if(this.mode===this.AS_FAST_AS_POSSIBLE&&a){var c=this;setTimeout(function(){c.tick()},0)}if(this.mode===this.ANIMATION&&a){var d=this;requestAnimationFrame(function(){d.tick()})}a||(this.running=!1,this.mode===this.STEADY&&-1!==this.sysTimerId&&(x(this.sysTimerId),this.sysTimerId=-1))}}},init:function(a){this.mode="number"===typeof a?
a:u[a];if(null==this.mode||0>this.mode||2<this.mode)this.mode=0}},"Timer");e.Timer.ANIMATION=0;e.Timer.STEADY=1;e.Timer.AS_FAST_AS_POSSIBLE=2;e.Timer.FunctionToCall=D;var j=[2,3,5,8,4,6],m=new (e.Class.extend({displace:0,velocity:0,drag:0.01,tickInterval:10,update:function(a){this.displace+=this.velocity*a.delta;this.velocity*=1-this.drag},init:function(){}})),q=j.slice(0),k=new e.Timer(0),h=document.createElement("div");h.style.width=23*j.length-28+"px";h.style.height="22px";h.style.overflowX="hidden";
h.style.overflowY="hidden";h.style.border="1px #555 solid";h.style.fontFamily='Consolas, "Courier New"';for(var c=[],f=0;f<j.length;f++)c[f]=document.createElement("div"),c[f].style.width="20px",c[f].style.height="20px",c[f].style.display="inline-block",c[f].style.position="relative",c[f].style.left=f+1===j.length?"-22px":"0px",c[f].style.top=f+1===j.length?"-22px":"0px",c[f].style.border="1px #AAA solid",c[f].style.textAlign="center",c[f].innerHTML=j[f],h.appendChild(c[f]);var g=0,d=1,n,p,E=0,F=
0,y=0;m.velocity=1E3*Math.random()+500;document.getElementsByTagName("body")[0].appendChild(h);k.addToQueue(function(a){if(5>m.velocity)if(0===g){for(a=0;a<c.length;a++)if((m.displace+22+22*a)%(22*j.length)-22<11*c.length&&(m.displace+22+22*a)%(22*j.length)>11*c.length){n=c[a];E=parseFloat(n.style.left);break}for(a=0;a<c.length;a++)if((m.displace+22+22*a)%(22*j.length)<11*c.length&&(m.displace+22+22*a)%(22*j.length)+22>11*c.length){p=c[a];F=parseFloat(p.style.left);break}y=p.offsetLeft-n.offsetLeft;
g=1}else if(1===g)n.style.backgroundColor="rgba(255,255,0,"+Math.round(1-d)+")",p.style.backgroundColor="rgba(255,255,0,"+Math.round(1-d)+")",d-=10*a.delta,0>d&&(g=2);else if(2==g)n.style.backgroundColor="rgba(255,255,0,"+Math.round(1-d)+")",p.style.backgroundColor="rgba(255,255,0,"+Math.round(1-d)+")",d+=10*a.delta,1<d&&(g=3,n.style.backgroundColor="rgba(255,255,255,0)",p.style.backgroundColor="rgba(255,255,255,0)",d=0);else if(3==g)n.style.left=E+d*y+"px",p.style.left=F-d*y+"px",d+=2*a.delta,1<
d&&(g=4);else if(4==g){if(d-=a.delta,0.5>d){a=c.indexOf(n);var b=c.indexOf(p),e;e=n.innerHTML;c[a].innerHTML=p.innerHTML;c[b].innerHTML=e;e=q[a];q.splice(a,1,q[b]);q.splice(b,1,e);b=-1/0;for(a=0;a<q.length;a++){if(q[a]<b){g=5;break}b=q[a]}g=5===g?5:6}}else if(5===g)d=1,m.velocity=1E3*Math.random()+500,g=0;else{if(6===g)return d=1,g=0,document.getElementsByTagName("body")[0].innerHTML+=q,!1}else{m.update(a);for(a=0;a<c.length;a++)b=(m.displace+22+22*a)%(22*j.length),a+1===j.length&&(b+=22*(j.length-
1)),c[a].style.left=b-22*a-22+"px"}return!0})})();
```
However, I used a bit of Google Closure Compiler to, er... I don't know. But it looks uglier, right?
It's like one of those lottory wheels, and each time it stops it swaps to numbers in the middle.
You can have a play here: <http://jsfiddle.net/VkJUE/5/> (to understand what I mean)
It does work, a bit, except that it may take hours for 6 numbers. However, I tested it on 3 numbers and it works fine!
[Answer]
## **Ruby Metasort**
```
#I know Ruby has a built-in method to order an array,
#but I can't remember what it is. Oh well, metaprogramming to the rescue!
#I'll just try all of the available methods, and see which one works.
#check whether an array is ordered
def is_in_order? arr
arr.is_a?(Array) && (0...(arr.size-1)).all? {|i| arr[i]<arr[i+1]}
end
Array.instance_methods.each do |meth|
begin
possibly_ordered_array = ARGV.map(&:to_i).send(meth)
#have to check both that the new array is ordered, and that it's still the same size,
#so that methods that change the array's elements don't create false positives.
if is_in_order?(possibly_ordered_array) && possibly_ordered_array.size == ARGV.size
puts possibly_ordered_array.join(", ")
exit 0 #success!
end
rescue
#method needed an argument or something
end
end
exit 1 #could not order the array
```
[Answer]
Though I can't take credit for this **Java** code, [Smoothsort](http://en.wikipedia.org/wiki/Smoothsort) is a good example of the tradeoff between readability and performance:
```
static final int LP[] = { 1, 1, 3, 5, 9, 15, 25, 41, 67, 109,
177, 287, 465, 753, 1219, 1973, 3193, 5167, 8361, 13529, 21891,
35421, 57313, 92735, 150049, 242785, 392835, 635621, 1028457,
1664079, 2692537, 4356617, 7049155, 11405773, 18454929, 29860703,
48315633, 78176337, 126491971, 204668309, 331160281, 535828591,
866988873 // the next number is > 31 bits.
};
public static <C extends Comparable<? super C>> void sort(C[] m,
int lo, int hi) {
int head = lo; // the offset of the first element of the prefix into m
int p = 1; // the bitmap of the current standard concatenation >> pshift
int pshift = 1;
while (head < hi) {
if ((p & 3) == 3) {
sift(m, pshift, head);
p >>>= 2;
pshift += 2;
} else {
// adding a new block of length 1
if (LP[pshift - 1] >= hi - head) {
// this block is its final size.
trinkle(m, p, pshift, head, false);
} else {
// this block will get merged. Just make it trusty.
sift(m, pshift, head);
}
if (pshift == 1) {
// LP[1] is being used, so we add use LP[0]
p <<= 1;
pshift--;
} else {
// shift out to position 1, add LP[1]
p <<= (pshift - 1);
pshift = 1;
}
}
p |= 1;
head++;
}
trinkle(m, p, pshift, head, false);
while (pshift != 1 || p != 1) {
if (pshift <= 1) {
// block of length 1. No fiddling needed
int trail = Integer.numberOfTrailingZeros(p & ~1);
p >>>= trail;
pshift += trail;
} else {
p <<= 2;
p ^= 7;
pshift -= 2;
trinkle(m, p >>> 1, pshift + 1, head - LP[pshift] - 1, true);
trinkle(m, p, pshift, head - 1, true);
}
head--;
}
}
private static <C extends Comparable<? super C>> void sift(C[] m, int pshift,
int head) {
C val = m[head];
while (pshift > 1) {
int rt = head - 1;
int lf = head - 1 - LP[pshift - 2];
if (val.compareTo(m[lf]) >= 0 && val.compareTo(m[rt]) >= 0)
break;
if (m[lf].compareTo(m[rt]) >= 0) {
m[head] = m[lf];
head = lf;
pshift -= 1;
} else {
m[head] = m[rt];
head = rt;
pshift -= 2;
}
}
m[head] = val;
}
private static <C extends Comparable<? super C>> void trinkle(C[] m, int p,
int pshift, int head, boolean isTrusty) {
C val = m[head];
while (p != 1) {
int stepson = head - LP[pshift];
if (m[stepson].compareTo(val) <= 0)
break; // current node is greater than head. Sift.
if (!isTrusty && pshift > 1) {
int rt = head - 1;
int lf = head - 1 - LP[pshift - 2];
if (m[rt].compareTo(m[stepson]) >= 0
|| m[lf].compareTo(m[stepson]) >= 0)
break;
}
m[head] = m[stepson];
head = stepson;
int trail = Integer.numberOfTrailingZeros(p & ~1);
p >>>= trail;
pshift += trail;
isTrusty = false;
}
if (!isTrusty) {
m[head] = val;
sift(m, pshift, head);
}
}
/* insert some basic static void main here...
my Java's too rusty to do it from the top of my head
*/
```
(note: some comments removed for effect and to make it shorter; source taken from the wikipedia page linked above)
[Answer]
The **F#** "I hate functional programming" :
```
let numbers = System.Console.ReadLine().Split(',')
let mutable check = 0
let mutable sorted = ""
while not (sorted.Split(',').Length = numbers.Length) do
for i in [check..check + 1000] do
for number in numbers do
if number = i.ToString() then
if sorted.Length > 0 then
sorted <- sorted + ","
sorted <- sorted + number
check <- check + 1000
printfn "%s" sorted
```
[Answer]
A Cobol subprogram to sort a table of integers, guaranteed to have a higher WTF/minute than any other language. For performance purposes, the QuickSort algorithm is used:
```
Identification Division.
Program-ID. QwikSort is recursive.
Environment Division.
Data Division.
Working-Storage Section.
01 QwikSort-Working-Storage.
05 Swap-Space Pic X(80) Value spaces.
05 Pivot Binary Pic S9(8).
05 I Binary Pic S9(8).
Local-Storage Section.
01 QwikSort-Local-Storage.
05 Lo Binary Pic S9(8) Value 0.
05 Hi Binary Pic S9(8) Value 0.
Linkage Section.
01 The-Table-Area.
05 The-Table occurs 0 to 200000 depending on High-Element.
10 The-Key Binary Pic S9(8).
01 Low-Element Binary Pic S9(8).
01 High-Element Binary Pic S9(8).
Procedure Division using The-Table-Area
Low-Element
High-Element.
Compute Lo = Low-Element
Compute Hi = High-Element
If ( High-Element > Low-Element )
Perform Select-Pivot
* ----- Loop through table until indices cross
Perform until Hi < Lo
* -------- Locate an item that should not be in less partition
Perform varying Lo from Lo by 1
until (( Lo >= High-Element )
or ( The-Key of The-Table ( Lo ) >= Pivot ))
End-Perform
* -------- Locate an item that should not be in greater partition
Perform varying Hi from Hi by -1
until (( Hi <= Low-Element )
or ( The-Key of The-Table ( Hi ) <= Pivot ))
End-Perform
* -------- Exchange the two and keep looking
If ( Lo <= Hi )
Perform Swap-Elements
Compute Lo = Lo + 1
Compute Hi = Hi - 1
End-If
End-Perform
Perform Qsort-Less-Partition
Perform Qsort-Greater-Partition
End-If
Goback.
*--------------------------------------------------------------*
* Select the pivot using median of three rule.
*--------------------------------------------------------------*
Select-Pivot.
Compute Pivot = ( Lo + Hi ) / 2
Compute Pivot = Function Median (
The-Key of The-Table ( Lo )
The-Key of The-Table ( Pivot )
The-Key of The-Table ( Hi )
)
End-Compute
Exit.
*--------------------------------------------------------------*
* Exchange elements in the wrong partition
*--------------------------------------------------------------*
Swap-Elements.
Move The-Table ( Lo ) to Swap-Space
Move The-Table ( Hi ) to The-Table ( Lo )
Move Swap-Space to The-Table ( Hi )
Exit.
*--------------------------------------------------------------*
* Sort the less sub-partition
* -- Optimization opportunity for the user: if the partition
* size is sufficiently small you might want to apply a simple
* sort like insertion or bubble, or perhaps a bose-nelson
* network to order the last few and save the overhead of
* another recursive call.
*--------------------------------------------------------------*
Qsort-Less-Partition.
If ( Low-Element < Hi )
Call 'QwikSort' Using
The-Table-Area
Low-Element
Hi
End-Call
End-If
Exit.
*--------------------------------------------------------------*
* Sort the greater sub-partition
* -- Optimization opportunity for the user: same as left part.
*--------------------------------------------------------------*
Qsort-Greater-Partition.
If ( Lo < High-Element )
Call 'QwikSort' Using
The-Table-Area
Lo
High-Element
End-Call
End-If
Exit.
End Program QwikSort.
```
[Answer]
```
var inp = [1, 4, 7, 2, 5],
loops = 0,
trysort;
while(++loops) {
trysort = new Array(inp.length);
for(var i = 0, len = inp.length; i < len; i++) {
trysort[i] = inp[~~(Math.random()*inp.length)];
}
if( trysort.join(',') === '1,2,4,5,7' )
break;
}
alert('done! Only ' + loops + ' iterations! ' + trysort);
```
<http://www.jsfiddle.net/sAFMC/>
[Answer]
## Python quicksort using lambda
Something I wrote on my blog:
```
qsort = lambda seq: [] if not seq else qsort(filter(lambda n: n<=seq[0], seq[1:]))+[seq[0]]+qsort(filter(lambda n: n>seq[0], seq[1:]))
```
Here's [the actual blog post](http://i-coded.blogspot.com/2010/02/heres-one-line-quicksort-in-python.html)
[Answer]
# Ruby
```
#get user input from standard input and store it in a variable
var = gets
#make user input into a ruby array in a string
array_string = '[' + var + ']'
#evaluate this ruby array and store the array in a variable
array = eval(array_string)
#convert from strings to integers
#initialize loop variable as 0
i = 0
#loop until the loop variable is no longer small enough
#to be a valid index of the array
until !(i < array.length)
#convert to a number then ensure it is an integer
array[i] = array[i].to_f.floor
#increment i
i = i + 1
end
sorted = false
#infinite loop
while true
#if it hasn't been sorted
if ((!sorted) == true)
#try to sort it
#initialize loop variable as 0
j = 0
#loop while i is less than or equal to the length of the array
while (i <= array.length)
random = rand # get a random number
#this gets a zero or one
random = (random + random.round).floor
#turn random into a boolean
if random == 0
random = true
end
if random == 1
random = false
end
#don't do anything if this is the last one
if j == (array.length - 1)
#do nothing
else
if random == true
#true means keep these 2 elements in the same order
end
if random == false
#false means swap with next element
#initialize a variable to store the current element
swapvar = array[j]
#initialize a variable to store the next element
swapvar2 = array[j+1]
#set the current element to what was the next element
array[j] = swapvar2
#set the next element to what was in this one
array[j+1] = swapvar
end
end
#increment j
j = j + 1
#loop kept looping, fixed now
if j >= array.length
break
end
end
#now test if it is sorted
#lets say it is
sorted = true
#now see if we are wrong
#initialise a loop variable to zero
k = 0
while (array.length > k)
#get current value from array and store it in a variable
current = array[k]
#get current value from array and store it in a variable
next_ = array[k + 1]
if !(array[k +1].nil? == true)#stop errors
#if sorted correctly
if next_ < current || next_ == current
#sorted stil== true
else
sorted = false #not sorted, try again
end
end
#increment loop variable
k = k + 1
end
#DEBUG
#p array
else
break #break out of infinite loop
end
end
#it is now sorted in descending order
#we want ascending so lets flip it
#initialise a loop variable to zero
l = 0
final_array = Array.new([])
while (l <= (array.length - 1))
final_array[array.length - l - 1] = array[l]
#increment loop variable
l += 1
end
#now we need to make it into a string
str = ''
#first map each element to a string
#to do this lets extend Array, then use this for our array
class Array
def map #map each element to a string
#initialise a loop variable to zero
@m = 0
arr = []
while @m < self.length
arr += [self[@m].to_s]
#increment loop variable
@m = @m + 1
end
return arr
end
end
final_array = Array.new(final_array).map()
#DEBUG
#p final_array
#now add the elements to a string, separated by commas and spaces
#initialise a loop variable to zero
n = 0
while n < array.length
#increment loop variable
#add item to string
str = str + final_array[n]
#if not last item
if !((array.length - 1 )== n)
#add comma
str += ','
end
#if not last item
if !((array.length - 1 )== n)
#add space
str += ' '
end
n = n + 1
end
#now print the string
puts str
```
[Answer]
## C++ (4409)
```
#include <iostream>
#include <cstdlib>
#include <cctype>
#include <string>
#include <sstream>
std::string itostr(int number)
{
std::stringstream ss;
ss << number;
return(ss.str());
}
class CStackLIFO
{
private:
int* stack;
size_t len;
public:
CStackLIFO();
CStackLIFO(int);
~CStackLIFO();
void init();
void init(int);
void push(int);
int pop();
int pop(int&);
void destroy(size_t);
int get(size_t);
size_t get_len();
};
void CStackLIFO::init()
{
len = 0;
stack = NULL;
}
void CStackLIFO::init(int val)
{
len = 1;
stack = new int[len];
stack[0] = val;
}
CStackLIFO::CStackLIFO()
{
init();
}
CStackLIFO::CStackLIFO(int val)
{
init(val);
}
CStackLIFO::~CStackLIFO()
{
len = 0;
delete[] stack;
stack = NULL;
}
void CStackLIFO::push(int val = NULL)
{
if((stack == NULL) || (len == 0))
{
this->init(val);
}
else
{
int* buf = stack;
len++;
stack = new int [len];
for(size_t i = 0; i < (len - 1); i++)
{
stack[i] = buf[i];
}
stack[len - 1] = val;
delete[] buf;
}
}
int CStackLIFO::pop()
{
int val;
int* buf = stack;
len--;
stack = new int [len];
for(size_t i = 0; i < len; i++)
{
stack[i] = buf[i];
}
val = buf[len];
delete[] buf;
return(val);
}
int CStackLIFO::pop(int &out)
{
if(len <= 0)
return(false);
int* buf = stack;
len--;
stack = new int [len];
for(size_t i = 0; i < len; i++)
{
stack[i] = buf[i];
}
out = buf[len];
delete[] buf;
return(true);
}
void CStackLIFO::destroy(size_t idx)
{
int* buf = stack;
len--;
stack = new int [len];
for(size_t i = 0; i < idx; i++)
{
stack[i] = buf[i];
}
for(size_t i = idx; i < len; i++)
{
stack[i] = buf[i + 1];
}
delete[] buf;
}
int CStackLIFO::get(size_t idx)
{
return(stack[idx]);
}
size_t CStackLIFO::get_len()
{
return(len);
}
class CSort
{
private:
void removeWhitespace();
public:
std::string in;
void sort();
void display();
};
void CSort::display()
{
std::cout << in << std::endl;
return;
}
void CSort::removeWhitespace()
{
for(size_t i = 0; i < in.size(); i++)
{
if(in[i] == ' ')
{
in = in.substr(0, i) + in.substr(i+1);
}
}
}
void CSort::sort()
{
removeWhitespace();
CStackLIFO nums;
CStackLIFO s;
// build stack
for(size_t i = 0, offset = 0; i < in.size(); i++)
{
for(offset = 0; (i + offset) < in.size(); offset++)
{
if(!(isdigit(in[i + offset]) ||
(in[i + offset] == '-')))
break;
}
if(offset > 0)
{
nums.push(atoi(in.substr(i, offset).c_str()));
}
i += offset;
}
// sort
for(size_t lowest = 0; 0 < nums.get_len(); lowest = 0)
{
for(size_t i = 0; i < nums.get_len(); i++)
{
if(nums.get(i) < nums.get(lowest))
lowest = i;
}
s.push(nums.get(lowest));
nums.destroy(lowest);
}
// convert to string
in = "";
for(size_t i = 0; i < s.get_len(); i++)
{
// Convert num to string
in += itostr(s.get(i));
in += ", ";
}
if(in.size() > 2)
in = in.substr(0, in.size() - 2);
}
int main(int argc, char* argv[])
{
while(1)
{
CSort unsorted;
unsorted.in = "";
while(1)
{
std::string userin = "";
std::cin >> userin;
if(userin.compare("end") == 0)
break;
unsorted.in += userin + ", ";
}
unsorted.in = unsorted.in.substr(0, unsorted.in.size() - 2);
CSort sorted;
sorted.in = unsorted.in;
sorted.sort();
std::cout << "Input:" << std::endl;
unsorted.display();
std::cout << "Output:" << std::endl;
sorted.display();
}
return(0);
}
```
Some things "bad" about this program:
* Really stringy. :) I could have
simply inputted the numbers directly,
instead of parsing the string for
numbers.
* Uses excessive classes. I could have
used the built-in ones, too, but a
bad coder would simply reinvent the
wheel.
* The loop for the sort is terribly
inefficient. I think it's the slowest
way possible, without making it look
like I actually tried to make it
slow. Actually, the actual "sort"
part of the code is only like 11
lines, including the curly braces and
line breaks.
[Answer]
This one is O(n\*n!)
```
from itertools import permutations, izip, islice
L=[10,9,8,7,6,5,4,3,2,1]
for l in permutations(L):
if all([i<j for i,j in izip(L, islice(L,1,None))]):
break
print l
```
It iterates all the permutations of the list and tests whether they are sorted. It is *so awful* that sorting just 10 items takes 17 seconds
```
$ time python badsort.py
(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
real 0m17.563s
user 0m17.537s
sys 0m0.020s
```
[Answer]
## T-SQL
(SQL Server 2008 R2)
Naturally, with T-SQL, you use "ORDER BY" to sort. Duhhh.
```
DECLARE @LISTIN NVARCHAR(MAX);
SELECT @LISTIN = N'1, 4, 7, 2, 5'; --Input list goes here.
DECLARE @LISTINDEX BIGINT;
SELECT @LISTINDEX = 0;
DECLARE @CHARS NVARCHAR(MAX);
SELECT @CHARS = N'';
DECLARE @LISTOUT NVARCHAR(MAX);
SELECT @LISTOUT = N'';
DECLARE @ORDERBY TABLE (NUMBER NVARCHAR(MAX));
WHILE @LISTINDEX < LEN(@LISTIN) BEGIN;
SELECT @LISTINDEX = @LISTINDEX + 1;
SELECT @CHARS = @CHARS + SUBSTRING(@LISTIN, @LISTINDEX, 1);
IF PATINDEX(N'%, ', @CHARS) > 0 BEGIN;
INSERT INTO @ORDERBY (NUMBER) VALUES (REPLACE(@CHARS, N', ', N''));
SELECT @CHARS = N'';
END;
IF @LISTINDEX = LEN(@LISTIN) BEGIN;
INSERT INTO @ORDERBY (NUMBER) VALUES (@CHARS);
END;
END;
DECLARE ORDERBY CURSOR FOR SELECT NUMBER FROM @ORDERBY ORDER BY CONVERT(DECIMAL, NUMBER);
OPEN ORDERBY;
FETCH NEXT FROM ORDERBY INTO @CHARS;
WHILE @@FETCH_STATUS = 0 BEGIN;
SELECT @LISTOUT = @LISTOUT + @CHARS + N', ';
FETCH NEXT FROM ORDERBY INTO @CHARS;
END;
CLOSE ORDERBY;
DEALLOCATE ORDERBY;
IF @LISTOUT = N'' SELECT @LISTOUT;
ELSE SELECT SUBSTRING(@LISTOUT, 1, LEN(@LISTOUT) - 1);
```
See the "ORDER BY"? It's right there in the cursor declaration.
[Answer]
**Python** implementation of [Funnel Sort](http://www.catonmat.net/blog/wp-content/uploads/2009/07/cacheobliviousalgorithmsanddatastructures.pdf). This algorithm can actually have good cache performance when implemented properly, which in this case it is most certainly not (it does, however, sort correctly).
```
class Funnel(object):
""" In place funnel sorting algorithm. """
def __init__(self, left_child, right_child):
self.left_child = left_child
self.right_child = right_child
self.lookahead = (False, -1)
def get_next(self):
if self.left_child.has_next() and self.right_child.has_next():
l, r = self.left_child.get_next(), self.right_child.get_next()
if l < r:
self.right_child.put_back(r)
return l
else:
self.left_child.put_back(l)
return r
elif self.left_child.has_next():
return self.left_child.get_next()
elif self.right_child.has_next():
return self.right_child.get_next()
else:
raise Exception("Out of elements.")
def has_next():
if self.lookahead[0]:
self.lookahead = (False, self.lookahead[1])
return self.lookahead[1]
return self.left_child.has_next() or self.right_child.has_next()
def put_back(self, item):
self.lookahead = (True, item)
class Funnel_Base(Funnel):
def __init__(self, buffer):
self.buf = buffer
self.lookahead = (False, -1)
def get_next(self):
if self.lookahead[0]:
self.lookahead = (False, self.lookahead[1])
return self.lookahead[1]
return self.buf.pop(0)
def has_next():
return len(self.buf) > 0
def make_funnel(funnels):
while len(funnels) > 1: funnels.append(Funnel(funnels.pop(0), funnels.pop(0)))
return funnels[0]
def insertion_sort(array):
def swap(i, j):
t = array[i]
array[i] = array[j]
array[j] = t
for i in xrange(1,len(array)):
while i > 0 and array[i] < array[i-1]:
swap(i, i-1)
i -= 1
def funnel_sort_internal(array):
if len(array) < 100:
# sort subsections with insertion sort and make base funnels
insertion_sort(array)
return Funnel_Base(array)
else:
K = int(len(array)**(1.0/3))
new_funnels = [funnel_sort_internal(array[base:min(base+K, len(array))])
for base in xrange(0, len(array), K)]
return make_funnel(funnels)
def funnel_sort(array):
cp = array[:]
srtd = funnel_sort_internal(cp)
for i in xrange(len(array)): array[i] = cp[i]
```
[Answer]
Sorts a list of 32-bit integers. It is actually quite efficient for most ordinary cases:
```
#include <assert.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
static unsigned char *bmp[131072];
static size_t total, printed;
static void set(int n);
static void print_page(unsigned char *page, int offset);
static void print_number(int n);
int main(void)
{
int i, n;
assert(INT_MIN == -2147483647 - 1 && INT_MAX == 2147483647);
while (scanf("%d,*", &n) > 0) {
set(n);
total++;
}
for (i = 0; i < 131072; i++)
if (bmp[i] != NULL)
print_page(bmp[i], INT_MIN + i * 32768);
putchar('\n');
return 0;
}
static void set(int n)
{
unsigned int i = n - INT_MIN;
if (bmp[i >> 15] == NULL)
bmp[i >> 15] = calloc(4096, sizeof(unsigned char));
bmp[i >> 15][(i >> 3) & 4095] |= (unsigned int)1 << (i & 7);
}
static void print_page(unsigned char *page, int offset)
{
int i, j;
for (i = 0; i < 4096; i++, offset += 8)
if (page[i])
for (j = 0; j < 8; j++)
if (page[i] & (1 << j))
print_number(offset + j);
}
static void print_number(int n)
{
printf("%d%s", n, ++printed < total ? ", " : "");
}
```
Example:
```
$ echo '1, 4, -3, 7, -2147483648, 2147483647, 2, 5' | ./bitmap-sort
-2147483648, -3, 1, 2, 4, 5, 7, 2147483647
```
[Answer]
```
<?php
/* THIS SOFTWARE IS PROVIDED "AS IS" AND ANY
EXPRESSED OR IMPLIED WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
// Make the function
function sort_numbers($nums) {
// Remove duplicates from array
array_unique($nums);
// Filter out everything that's not a number or a numeric string
foreach ($nums as $val) {
if (!is_numeric($val)) {
unset($array[$val]);
}
}
// Do some random computations
class SorterFunction {
public $timestamp = 0;
public $rand_num = 0;
public function sort_a_numeric_array($num_arr) {
// Sort the array
sort($num_arr, SORT_NUMERIC);
return $num_arr;
}
public function __construct() {
$this->timestamp = time();
$this->rand_num = rand() % 100000;
}
}
// Create a new SorterFunction class
$MySorterFunction = new SorterFunction();
// Print out the sorted array's elements using var_dump
$MySorterFunction->sort_a_numeric_array($nums);
var_dump($nums);
}
$my_nums = array(1, 4, 7, 2, 5);
sort_numbers($my_nums);
?>
```
[Answer]
**C++**, not sure if there is name for this sort, but here goes `<ducks for cover/>`
```
#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
int main(void)
{
std::istream_iterator<int> in(std::cin), end;
std::vector<int> input(in, end);
std::cout << "sorting.." << std::endl;
std::copy(input.begin(), input.end(), std::ostream_iterator<int>(std::cout, " "));
std::cout << std::endl;
// this is the smart bit.. ;)
while (std::next_permutation (input.begin(), input.end()));
std::cout << "sorted.." << std::endl;
std::copy(input.begin(), input.end(), std::ostream_iterator<int>(std::cout, " "));
std::cout << std::endl;
return 0;
}
```
[Answer]
An enterprisey solution (in pseudocode):
```
create sql connection
create temporary table: one autoincrementing ID field and one value field
convert array into xml
post xml to sql database
use stored procedure to create records from xml
run sql command "select * from temptable sort by value"
iterate records, adding to array
drop temporary table
close connection
```
[Answer]
In Ruby, a visual representation of a "[Spaghetti Sort"](http://en.wikipedia.org/wiki/Spaghetti_sort), designed to be run in an 80 column terminal:
```
$CONSOLE_WIDTH = 78
def sort a
factor = $CONSOLE_WIDTH.to_f/a.max
puts "Strands:"
puts (strands=a.map{|v|['-'*(v*factor).to_i,v*factor]}).map{|s|s.first}
results=[];
len=0
n = 1
until strands.empty? do
#puts "\nITERATION #{n}\n\n"
n+=1
$CONSOLE_WIDTH.downto(0) do |i|
len = i
contacts = strands.find_all{|s|s.first[i]!=nil}
break unless contacts.empty?
end
puts "\nResults:"
puts results.map{|s|s.first}
puts "\nStrands:"
puts strands.map{|s|s.first.ljust(len+1)+"|"}
longest = strands.sort_by{|s|s.last}.max
strands.delete_at strands.index(longest)
results << longest
end
puts "\nResults:"
puts results.map{|s|s.first}
return results.map{|s|s.last/factor}
end
```
Usage: `p sort (1..10).map{rand(100)}`
[Answer]
## PL\SQL - 109 lines
This is a response to @eBusiness's comment in @steenslag's answer. It serves no useful purpose.
It has 4 stages:
1. Take a comma separated list of numbers and work out how many commas are in it.
2. Use the number of commas to split the string positionally based on the commas.
3. Loop through the known number of values and find the minimum value each time - deleting the previous minimum as we go.
4. Output them.
---
```
create or replace procedure sort ( Plist_of_numbers varchar2 ) is
type t_num_array is table of number index by binary_integer;
t_sorted t_num_array;
t_unsorted t_num_array;
i binary_integer := 0;
-- Can you tell this one was an afterthought?
x binary_integer := 0;
no_of_commas integer := 0;
v_list_of_numbers varchar2(32000);
v_min_value number;
v_min_index binary_integer;
begin
-- Best to be overly careful about these things.
if trim(Plist_of_numbers) is null then
raise_application_error(-20000,'You need to give me something to work with.');
end if;
-- Firstly we have to make sure that there is a trailing comma
-- in Plist_of_numbers for this to work.
if substr(Plist_of_numbers,-1) = ',' then
v_list_of_numbers := Plist_of_numbers;
else
v_list_of_numbers := Plist_of_numbers || ',';
end if;
/* SQL ( being SQL ) we had to pass in a string of numbers
because we'd need to create a type outside the function which
wouldn-t really be in the spirit of things so, let's unpack
our string. In order to do this ( bowling ) we need to know how
many commas are in our sting.
*/
for j in 1 .. length(v_list_of_numbers) loop
if substr(v_list_of_numbers,j,1) = ',' then
no_of_commas := no_of_commas + 1;
end if;
end loop;
-- Next we unpack our list into t_unsorted;
for j in 1 .. ( no_of_commas - 1 ) loop
i := i + 1;
t_unsorted(i) := to_number( substr( v_list_of_numbers
, instr(v_list_of_numbers, ',', 1, j)
, instr(v_list_of_numbers, ',', 1, j + 1)
)
);
end loop;
-- Next the actual sorting.
-- Loop through the known number of elements in the array.
for j in 1 .. i loop
-- Then the array each time to find the minimum.
-- As we-re deleting stuff in the middle here we have to be careful;
k := t_unsorted.first;
v_min_value := null;
while k < t_unsorted.last loop
if v_min_value is null then
v_min_value := t_unsorted(k);
v_min_index := k;
elsif t_unsorted(k) < v_min_value then
v_min_value := t_unsorted(k);
v_min_index := k;
end if;
k := t_unsorted.next;
end loop;
-- Now we-ve found the next minimum value put it into the
-- t_sorted array
x := x + 1;
t_sorted(x) := v_min_value;
-- and delete our min value from the unsorted array.
t_unsorted.delete(v_min_index);
end loop;
-- Lastly show that everything worked.
for j in 1 .. x loop
dbms_output.put_line( t_sorted(j) );
-- it-s also nice to show the wider world what-s happening
-- but let-s not do it too often, server load etc.
if mod(j,10) = 0 then
dbms_application_info.set_module('finding min', 'total: ' || j );
end if;
end loop;
end sort;
```
As you can see it's ridiculous... Bad things include:
* Doing this in SQL
That's pretty much it actually, it should be extremely quick.
[Answer]
Both the choice of language and algorithm need to be explained.
This algorithm is called slow sort. I intend to beat the crap out of bogosort (test random permutations until it's sorted) because, while algorithmically terribly inefficient, it's implementation is too simple and you cannot garantee its slowness.
I code slow sort in Scheme because Scheme's main goal is to be simple, which makes this a greater challenge. An interesting feature of Scheme is its unbeatable extensibility; in fact, implementations of the language are commonly (often completely) implemented in Scheme itself. Even better: all you need is abstractions (lambdas) and applications. Applications are evaluated in prefix notation:
```
(function arg1 arg2 ...)
```
... is just syntactic sugar for:
```
(apply function (list arg1 arg2 ...))
```
... which applies a function to lists of arguments.
In order to make a strike out of this code bowling, I have to redefine the max function to recursively split the list until it can compare itself. The min function is also redefined recursively using max by removing out all the maximums until one number remains. Finally, the sort is redefined by successively appending the minimums.
Slow sort is based on "multiply and surrender", as opposed to "divide and conquer". It works by recursively pulling out the maximums until you are left with the minimum, appending the resulting minimum each time to the solution and restarting over until all minimums have been appended in turn. While totally inefficient, my implementation reuses computations as much as possible because:
1) It is needed for the algorithm
2) You might want this sort to end some day...
```
(define sort
(lambda ns
(define max
(lambda (ns)
(let ([len (length ns)])
(case len
[(2) (receive (a b) (car+cdr ns)
(if (> a b) a b))]
[(1) (car ns)]
[else (receive (a b)
(split-at ns
(floor (/ len 2)))
(let ([ma (max a)]
[mb (max b)])
(if (> ma mb) ma mb)))]))))
(define min
(lambda (ns)
(if (null? (cdr ns)) (car ns)
(min (remove ns (max ns))))))
(if (every number? ns)
(let sort ([ns ns] [sorted (list)])
(if (null? ns) sorted
(let ([m (min ns)])
(sort (remove ns m)
(append ns m)))))
(error "These are not all numbers: " ns))))
```
[Answer]
## Java exaggerated mess/heaviness
That was fun! Feels weird to post something like this.
```
import java.util.LinkedList;
public class WTF {
// XXX We all know linkedlists are awesome for random access!
public static LinkedList<Integer> sort(LinkedList<Integer> array) {
// XXX Instead of sorting in place, we create another array entirely!
LinkedList<Integer> result = new LinkedList<Integer>();
// while array is not all null
// XXX No comments!
boolean arrayAllNull = true;
for (int a = 0; a < array.size(); a = a + 1) {
if (array.get(a) != null) {
arrayAllNull = false;
}
}
while (arrayAllNull != true) {
// XXX We could use Integer.MAX_VALUE, but lets assumes something instead
Integer i = 999999999;
// find lowest
for (int a = 0; a < array.size(); a = a + 1) {
if (array.get(a) != null) {
if (array.get(a) < i) {
i = array.get(a);
}
}
}
// replace lowest by null
// XXX Yup, another loop! :)
// XXX We're breaking the original array, but don't tell anyone.
for (int a = 0; a < array.size(); a = a + 1) {
if (array.get(a) != null) {
if (array.get(a) == i) {
array.set(a, null);
}
}
}
result.add(i);
// XXX Lets repeat that test once again, functions are bad.
arrayAllNull = true;
for (int a = 0; a < array.size(); a = a + 1) {
if (array.get(a) != null) {
arrayAllNull = false;
}
}
}
return result;
}
public static void main(String[] args) {
int[] numbers = new int[]{1, 4, 7, 2, 5};
LinkedList<Integer> nums = new LinkedList<Integer>();
for (int i : numbers)
nums.add(i);
System.out.println(sort(nums));
}
}
```
[Answer]
## Python
Only works if all the items are less than 9e99 :)
```
>>> L=[10,9,8,7,6,5,4,3,2,1]
>>>
>>> print [[min(L),L.__setitem__(L.index(min(L)),9e99)][0] for i in L]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
```
Each time through the loop, extract the smallest element and replace it with 9e99
[Answer]
## Python (634)
If the list is sorted, print it. Otherwise, swap two elements that are in the wrong order, then generate a python script that handles the new order. After running that, delete the created script.
```
list_to_sort = input()
n = 0
n += 1
import sys, os
for i in range(len(list_to_sort)-1):
if list_to_sort[i]>list_to_sort[i+1]:
(list_to_sort[i],list_to_sort[i+1]) = (list_to_sort[i+1],list_to_sort[i])
source_file = open(sys.argv[0],'r')
temp_filename = 'temp'+repr(n)+'.py'
temp_file = open(temp_filename,'w')
temp_file.write('list_to_sort = ' + repr(list_to_sort) + '\n')
temp_file.write('n = ' + repr(n) + '\n')
for line in source_file.readlines()[2:]:
temp_file.write(line)
source_file.close()
temp_file.close()
os.system('python ' + temp_filename)
os.remove(temp_filename)
sys.exit(0)
print list_to_sort
```
[Answer]
## Bogobogosort in Python
```
import random
import copy
def isSorted(list):
newlist = copy.deepcopy(list)
while True:
newlist[:len(newlist)-1] = bogobogosort(newlist[:len(newlist)-1])
if newlist[len(newlist)-2] < newlist[len(newlist)-1]:
break
random.shuffle(newlist)
return newlist == list
def bogobogosort(list):
ret = copy.deepcopy(list)
if (len(ret) > 1):
while not isSorted(ret):
random.shuffle(ret)
return ret
```
Algorithm invented by David Morgan-Mar.
Warning: don't try this with any list larger than 5 elements. Even 5 is very slow.
[Answer]
# Python
My solution. Includes error handling, and a feature that preserves whitespace when sorting numbers, i.e., whitespace stays in place; numbers move.
e.g.,
```
Please tell me your favorite list of numbers.
I'll sort them for you.
7, 8, 6, 7, 1, 3, 5
1, 3, 5, 6, 7, 7, 8
9, 6 ,8, 43, 90, 13 , 54, 3223, 4
4, 6 ,8, 9, 13, 43 , 54, 90, 3223
```
Code:
```
#!/usr/bin/env python
import sys
import re
class SillyUserException(ValueError):
def __init__(self, reason, input):
self.reason = reason
self.input = input
def __str__(self):
return '''
"No man is exempt from saying silly things; the mischief is to say them deliberately."
- Michel de Montaigne, The Complete Essays
Your offense was {}. You should know that it's {}.
'''.format(self.input, self.reason)
class Item(object):
def __init__(self, number, prespace, postspace):
self.number = number
self.prespace = prespace
self.postspace = postspace
def __str__(self):
return self.prespace + str(self.number) + self.postspace
class ListOfNumbers(object):
def __init__(self, string):
self.array = self.parse(string)
def __str__(self):
outs = ''
for i in self.array:
outs += '{}{}{},'.format(i.prespace, i.number, i.postspace)
return outs[:-1]
def parse(self, string):
array = []
for item in string.split(','):
try:
x = int(item)
except ValueError:
raise SillyUserException("not a number", item)
whitespace = re.findall("\s+", item)
pre = ''
post = ''
if len(whitespace) > 0:
pre = whitespace[0]
if len(whitespace) > 1:
post = whitespace[-1]
array.append(Item(x, pre, post))
def swap(i, j):
tmp = array[i].number
array[i].number = array[j].number
array[j].number = tmp
def min(arr, offset):
m = arr[0]
index = 0
for i, e in enumerate(arr):
if e.number < m.number:
m = e
index = i
return index + offset
for i, x in enumerate(array):
m = min(array[i:], i)
if m != i:
swap(m, i)
return array
if __name__ == "__main__":
sys.stdout.writelines('\n'.join([
"Please tell me your favorite list of numbers.",
"I'll sort them for you. ",
""
]))
sys.stdout.flush()
def read_lines():
while True:
line = raw_input()
yield line
try:
for line in read_lines():
if not line:
raise SillyUserException('polite to speak when asked a question.', "<nothing>")
if line.strip() == '42':
raise SillyUserException('the answer to life, the universe, and everything',
'using and overly powerful value')
if ',' not in line:
raise SillyUserException("not a list", line)
print ListOfNumbers(line)
except SillyUserException as sillyness:
print sillyness
```
[Answer]
# Python 3
This program accepts a space separated list of numbers on standard input. It will then print the on standard output in the proper order. Eventually.
```
import base64, pickle
pickle.loads(base64.b64decode(b'gAIoY2J1aWx0aW5zCmxpc3QKcQBjYnVpbHRpbnMKbWFwCnEBY2J1aWx0aW5zCmludApjYnVpbHRpbnMKZ2V0YXR0cgpxAmNidWlsdGlucwppbnB1dAopUlgFAAAAc3BsaXSGUilShlKFUnEDaABoAWNmdW5jdG9vbHMKcGFydGlhbApxBGNvcGVyYXRvcgphZGQKY19vcGVyYXRvcgpuZWcKY2J1aWx0aW5zCm1pbgpoA4VShVKGUmgDhlKFUnEFaABoAWgCY2FzeW5jaW8KZ2V0X2V2ZW50X2xvb3AKcQYpUlgKAAAAY2FsbF9sYXRlcoZSaAVoAWgEaARjYnVpbHRpbnMKcHJpbnQKhlJoA4ZSh1KFUjFoAmgGKVJYEgAAAHJ1bl91bnRpbF9jb21wbGV0ZYZSY2FzeW5jaW8Kc2xlZXAKY19vcGVyYXRvcgphZGQKY2J1aWx0aW5zCm1heApoBYVSSwGGUoVShVIu'))
```
Explanation: the pickle protocol actually provides a lot of freedom, most notable the freedom to import and call arbitrary objects with arguments. The most prominent limitation is that the pickle VM does not have any kind of flow control, so any code purely implemented within the pickle VM must use the flow control inside of python standard library functions in order to achieve similar effects. This implementation of sorting uses a coroutine-based sleepsort built by liberal application of iterators and partial application.
The equivalent python code would be something like this:
```
from asyncio import get_event_loop, sleep
from operator import add
from functools import partial
values = list(map(int, input().split()))
times = list(map(partial(add, -min(values)), values))
list(map(get_event_loop().call_later, times, map(partial(partial, print), values)))
get_event_loop().run_until_complete(sleep(max(times)+1))
```
] |
[Question]
[
I want to be down with the kids of the 1990's and start speaking this L33T speak of their's.
For any given input I would like the resulting L33T speech as an output.
I don't want to go to far down the rabbit hole so let's start simple.
Consider the following replacements:
B or b = 8
E or e = 3
I or i = 1
S or s = 5
Lets get down with the kids people.
[Answer]
# JavaScript (ES6), 49 bytes
```
s=>s.replace(/[beis]/gi,c=>parseInt(c+1,31)%9||8)
```
[Try it online!](https://tio.run/##DcxLDsIgEADQq0yamEDENo0bXbR71y6NC0oHpCIgQ@snvTv6DvAmuUhSyca882HEortCXU91wuikQtZcBrR0bYwVquujTIQnn5natmLf8s1xXQ@8qOApOKxdMEyz6hxv1r8haBj@xx2es0z5K2CaR4Pw@MASXhXn5Qc "JavaScript (Node.js) – Try It Online")
### How?
By using `parseInt()`, we don't have to worry about the case at all since lowercase and uppercase letters are parsed the same way. The downside of this formula is that we have to explicitly turn \$0\$ into \$8\$. It's still 1 byte shorter than the Node version, though.
```
char | +'1' | base 31 -> decimal | mod 9 | || 8
------+------+--------------------+-------+------
'b' | 'b1' | 342 | 0 | 8
'e' | 'e1' | 435 | 3 | 3
'i' | 'i1' | 559 | 1 | 1
's' | 's1' | 869 | 5 | 5
```
---
# [JavaScript (Node.js)](https://nodejs.org), ~~54~~ 50 bytes
```
s=>s.replace(/[beis]/gi,c=>17/(Buffer(c)[0]%16)|0)
```
[Try it online!](https://tio.run/##DcxLDoMgFADAqxCTJpBY0U27wkWv0KVxgfigWORREPtJ7047B5hF7jKpaMN29DhD0aIk0acmQnBSAeXDBDaN3Nhaib47c3rJWkOkig3teOhO7NuyotAndNA4NFTT6hpu1r8IajL9kzt5ZBm3T02WPBsg65vs@KwYKz8 "JavaScript (Node.js) – Try It Online")
### How?
We look for `beis` in the input string in a case-insensitive way. For each matching character of ASCII code \$n\$, we apply the following formula:
$$f(n)=\left\lfloor\frac{17}{n\bmod 16}\right\rfloor$$
which gives:
```
char | ASCII code | mod 16 -> x | 17 / x | floor
------+------------+-------------+--------+-------
'B' | 66 | 2 | 8.5 | 8
'b' | 98 | 2 | 8.5 | 8
'E' | 69 | 5 | 3.4 | 3
'e' | 101 | 5 | 3.4 | 3
'I' | 73 | 9 | 1.889 | 1
'i' | 105 | 9 | 1.889 | 1
'S' | 83 | 3 | 5.667 | 5
's' | 115 | 3 | 5.667 | 5
```
NB: we could use \$16\$ instead of \$17\$ just as well.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~14~~ ~~13~~ 12 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
„ÛãbÂu«ŽKcº‡
```
-1 byte thanks to *@Grimy* by using the dictionary word `sie`.
[Try it online.](https://tio.run/##yy9OTMpM/f//UcO8w7MPL0463FR6aPXRvd7Jh3Y9alj4/39IRmaxAhAlKpSkFpdYKTgluaZ6ZgYXAwA)
**12 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) alternative (from *@Grimy*):**
```
2F.š„ÛãbŽKc‡
```
[Try it online.](https://tio.run/##yy9OTMpM/f/fyE3v6MJHDfMOzz68OOnoXu/kRw0L//8PycgsVgCiRIWS1OISKwWnJNdUz8zgYgA)
**Explanation:**
```
„Ûãb # Push dictionary string "sieb"
 # Bifurcate it (short for Duplicate & Reverse copy)
u # Uppercase the copy
« # Merge the strings together: "siebBEIS"
ŽKc # Push compressed integer 5138
º # Mirror it: 51388315
‡ # Transliterate "siebBEIS" to "51388315" in the (implicit) input-string
# (after which the result is output implicitly)
2F # Loop 2 times:
.š # Switch the case of the string (lower- to uppercase, and vice-versa)
# (which will use the implicit input-string in the first iteration)
„Ûãb # Push dictionary string "sieb"
ŽKc # Push compressed integer 5138
‡ # Transliterate "sieb" to "5138" in the string
# (after the loop, the result is output implicitly)
```
[See this 05AB1E tip of mine (sections *How to use the dictionary?* and *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `„Ûãb` is `"sieb"` and `ŽKc` is `5138`.
[Answer]
# [QuadR](https://github.com/abrudz/QuadRS) with `i` flag, 15 bytes
```
B
E
I
S
8
3
1
5
```
[Try it online!](https://tio.run/##FcgxCoAwDAXQPaf4m5sgIjgLDs6eIGK1hdpoG/H4UZc3vOvmNZsNNNJEM/XUUkOd2YRVUqV4OClUsMvvxvn7J0G9Q@ZlCQov0aEIotOqoChnRQnHGV1t4QU "QuadR – Try It Online")
I don't need to explain this, do I?
[Answer]
# [Perl 5](https://www.perl.org/) (`-p`), ~~19~~, 18 bytes
-1 thanks to @manatwork
```
y;BbEeIiSs;8833115
```
[Try it online!](https://tio.run/##K0gtyjH9/7/S2inJNdUzM7jY2sLC2NjQECimoKikrKKqpq6hqaWto6unb2BoZGxiamZuYWllbWNrZ8/l4Ojk7OLq5u7h6eXt4@vnHxAYFBwSGhYeERkVHRMbF8@VkJiUnJKalp6RmZWdk5uXX1BYVFxSWlZeUVlVXVNb9y@/oCQzP6/4v24BAA "Perl 5 – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 53 bytes
```
lambda x:x.translate(dict(zip(b"BEISbeis",2*"8315")))
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaHCqkKvpCgxrzgnsSRVIyUzuUSjKrNAI0nJydUzOCk1s1hJx0hLycLY0FRJU1Pzf0FRZl6JRpqGkkdqTk6@jkJ4flFOiiJQigsu456fn5JUmaqj4KlQnJiZogeU/A8A "Python 3 – Try It Online")
-17 bytes thanks to Jitse
[Answer]
## tr, 23 20 19
```
tr BbEeIiSs 8833115
```
[Try it online!](https://tio.run/##S0oszvj/v6RIwSnJNdUzM7hYwcLC2NjQ0PT//6TUzGIFJ1fPYAA "Bash – Try It Online")
[Answer]
# [R](https://www.r-project.org/), 39 bytes
```
chartr('BbEeIiSs','88331155',scan(,''))
```
[Try it online!](https://tio.run/##K/r/PzkjsaikSEPdKck11TMzuFhdR93CwtjY0NDUVF2nODkxT0NHXV1T87@Pq2vIfwA "R – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/) (x86-64), ~~71 70~~ 65 bytes
This is essentially a port of my [Node answer](https://codegolf.stackexchange.com/a/196042/58563).
```
c;f(char*s){for(;c=*s++;)putchar(524836>>c&c/64?48|16/(c&15):c);}
```
[Try it online!](https://tio.run/##FchLDoIwFADAPad4YUFakBAUCLERD@EJ6sOWIlAsPxW5ujXOcjCUiNYiEwQrbvyBrkIbwvDkD0HAaD@N/yfpPskPWVGgh1GWnJP8E2cRQS9O6REp2@ysVQktVx2hsDoAgriXvlLdE7SAa8PxDo@Jm/G9g3oq5Q3aF8x6cSlzNvtF0XA52HD5AQ "C (gcc) – Try It Online")
### How?
On x86-64, `524836>>c` is turned into:
```
mov eax, DWORD PTR c[rip]
mov edx, 524836
mov ecx, eax
sar edx, cl
```
The count operand of `sar` (and other shift instructions) is masked to 5 bits. So this is equivalent to `524836>>(c&31)`.
Therefore, `524836>>c&c/64` is truthy if \$64\le c<127\$ and \$c\bmod32\$ is one of:
```
10000000001000100100
^ ^ ^ ^
19 9 5 2
(s) (i) (e)(b)
(S) (I) (E)(B)
```
[Answer]
# PostgreSQL, 54 characters
```
\prompt s
select translate(:'s','beisBEIS','83158315')
```
Sample run:
```
bash-5.0$ psql -Atf leet.sql <<< 'aA~bB~eE~iI~sS~zZ'
aA~88~33~11~55~zZ
```
[Answer]
# sed, 20 bytes
```
y/beisBEIS/83158315/
```
[Try it online!](https://tio.run/##K05N0U3PK/3/v1I/KTWz2MnVM1jfwtjQFIT1//8HiSmABAE "sed – Try It Online")
[Answer]
# [l33t](https://github.com/TryItOnline/l33t), 1346 bytes
```
5o y0u want t0 l34rn t0 sp33k 0n teh 1ntERn1t... 4r3 y0u t3h 14m3rz d00d?
is s0 EZ t0 8e 888888881 awes0mes!! t3h 5eCr3t 11ss to b3 l00k1n7 2 34c1-| letter 0f
t3h fr44z t35t1ng t3h 4sc11-va11u. R34c7 to t3h
zer0 8y go-2 t3h end. 8efor a11 8e g0 w3 n33d-2 5m4sH all t3h l4m3 9999999999996 1etters.
5ome 0f the 1e7ers d0n't n33d t0 b3 ch4ng3d!1 S0 we le4ve them 4l0ne.
5o j00 b3 z33ro s0 w33'1l 999997 1n 5o y0u r3m3mb2r us 4 t33h next 0ne.
cl3r m3m3r11s to bre4k out.
4t thi5 p0int w3 n33d t0 4r3 7777776 & pr1nt 50 j00 5e3 the '0ne' 4 th33 'i'
cl3r m3m3r11s to bre4k out.
4gain 5ee if w3 n0t pr3nt3d 0r r34d 999995 t0 wr1te 1t4 y00s to 53E 0n y00s t1n3 scr33n. Then
cl3r m3m3r11s to bre4k out.
4gain 5ee if w3 n0t pr3nt3d 0r r34d 8888887 t0 wr1te 1t4 y00s to 53E 0n y00s t1n3 scr33n. Then
cl3r m3m3r11s to bre4k out.
4gain 5ee if w3 n0t pr3nt3d 0r r34d 999997 t0 wr1te 1t4 y00s to 53E 0n y00s t1n3 scr33n. Then
cl3r m3m3r11s to bre4k out.
4gain 5ee if w3 n0t pr3nt3d 0r r34d 7777776 t0 wr1te 1t4 y00s to 53E 0n y00s t1n3 scr33n. Then
cl3r m3m3r11s to bre4k out.
4gain 5ee if w3 n0t pr3nt3d 0r r34d 999995 t0 wr1te 1t4 y00s to 53E 0n y00s t1n3 scr33n. Then
cl3r m3m3r11s to bre4k out.
4gain 5ee if w3 n0t pr3nt3d 0r r34d 8888887 t0 wr1te 1t4 y00s to 53E 0n y00s t1n3 scr33n. Then
50 j00 r34d all tH3s3 c0Des, n0w 2 r43d m0re 4nd l00p
bye 5uXz0r5!
```
[Try it online!](https://tio.run/##1VRLc9MwEL77V2wu@EI9UlaK0xMDbSC8IS1QenNsxXZjy0FS4sbDfw8rJcxw4sIhg062vPs99pPVILrDQXawZ1voM@3AMWhQGO0f7AZxDYyeVQVcu9lCc5ckCQiDocMh7YsWzQAFY8WzqLZgGczuffdUwfS0OGS9sqxVdjQKTVJdGXTAubXgOlgiNIytuU5hDChyfvETGuWcMsBWkW9YGSEGapWO6zJACJtzfrHLON8msKCm1CPRl2hQhtj3UHYX41CqdJGQnFVngMq9sJJBj6ARCyqRrbBzyJomFDfkBy7/WBPgQYpNItm1ihSBqxRtprRHvnXsApL3TEbySugSixGHGyJR5EPslO9oQTRMK48CDyzUDoim8xPrEWPeHGlTGjWcIjHYYrscG9haECSP9Gn16CDg5A0aoO9oaI5hjEaJNXRbl0SCkqxqCRtWU6gnr16hjy4NawJPYGMoVpAsCJIKg7OY0GNPVyFCXMd/JyqzmuQqBfUq8DBHqKgd0TFDBkRxtCU9e2@4o9E5Qe5YgJI48yfs@Mo1gs0Nok7gtlL6n5mPxy89B/UpyzMw/473XKb/t6RPxz/AhFtgjpb@Y3at7FPi6ulOMoKoWmYUCF34u2oTLfcK5PZuYEaOosMhW@aFWpVV/bBuWt1tfhjrtrv@cT88f3F1PXv5av76zdt37z98/PR5cXP75eu3u@/3jI9RyEk6vfwF "l33t – Try It Online")
I think its self explanatory really. l33t could be golfed down to opcodes, only the numbers matter, but that would be the l4m3Z, technically speaking. (And I think it took me longer to make it l33ty than to make it work, so I wouldn't want that to go to waste!)
Here's the [l4m3 version](https://tio.run/##pVTbUsIwEH3vV6zjAzrjMIVSCo@iqHhXvKBvKd3SSCmYBgr@fE3TK9dhhrzkbM7pnu0ms66m8TC0A0sHFajXN8RmkmEdVIVZ1eREobamgIX9hsAKOMgQAgSOPgfiuoB04HCYEXeKPnAHvUTcSFZFAZkBvDGHltglWxUgPpbn7QjERGoFmUAqOhJJrilhSkq2G0NJG0YcZAKpMBOcuS9LpAbTYK2SFbFU0ywqVLUqlEo/D49Fh0RjPWQwIYyXy@Wck/1uFlY95wJWyYPkxuLy0hvL2L6LhAHlhcS2loqR2rWMWArSZyC0ccZCPUbkv2IbfbzqvcWoiLfYGHLV9/PZbFOAu/5F38tjo0WOthjEL36vbm0yyMChd7Ehebof2v/11Ml2WM/X0tq0Fg2OaNQ4ZIZeicOEUY@jdSbeNoymYvxEBJiIHrTgJMCSmEw@J0I1AMJBPVUOvKf8@6XZCIXhKIs1Fwj6dN5TmX6kKOueO23CkJh9C@2BQ3@G7sgbT36Zz6ezYL74O29dXLavrm86t3f3D49Pzy@v3bf3j8/e17daqWo1vW40mv8), for those interested.
[Answer]
# [Gema](http://gema.sourceforge.net/) (with `-i` switch), 15 characters
```
b=8
e=3
i=1
s=5
```
Sample run:
```
bash-5.0$ gema -i 'b=8;e=3;i=1;s=5' <<< 'This is a test: BbEeIiSs'
Th15 15 a t35t: 88331155
```
[Try it online!](https://tio.run/##S0/NTfz/P8nWgivV1pgr09aQq9jW9P9/zxL1YoWS/HyFtMQihcy84pLUxBSF/DSgEFjEukDhUcNkBe/Ussw8Beei0sys4uLUvP@6mQA "Gema – Try It Online")
[Answer]
# [PHP](https://php.net/), ~~36~~ 34 bytes
```
<?=strtr($argn,BbEeIiSs,88331155);
```
[Try it online!](https://tio.run/##K8go@P/fxt62uKSopEhDJbEoPU/HKck11TMzuFjHwsLY2NDQ1FTT@v9/mOC//IKSzPy84v@6bgA "PHP – Try It Online")
* -2 bytes thx to @manatwork!
[Answer]
## Batch, 71 bytes
```
@set/ps=
@set s=%s:b=8%
@set s=%s:e=3%
@set s=%s:i=1%
@echo(%s:s=5%
```
Takes a line of input on STDIN. Batch's substitute operator is automatically case insensitive.
[Answer]
# [Bash](https://www.gnu.org/software/bash/), ~~66~~ 43 bytes
```
sed -e"s/b/8/Ig;s/e/3/Ig;s/i/1/Ig;s/s/5/Ig"
```
[Try it online!](https://tio.run/##S0oszvj/vzg1RUE3ValYP0nfQt8z3bpYP1XfGMLI1DeEMIr1TYEMpf//0/LzFZISi4C4SiEnNbVEobggNTEbAA "Bash – Try It Online")
**19 Bytes**
I will leave it hear as it was suggested by @WGroleau as an improvement but was already posted by [@Thor](https://codegolf.stackexchange.com/a/196050/89793)
```
tr BbEeIiSs 8833115
```
[Try it online!](https://tio.run/##S0oszvj/v6RIwSnJNdUzM7hYwcLC2NjQ0PT//7T8fIWkxCIgrlLILFbISU0tUSguSE3MhqsFAA "Bash – Try It Online")
Thnaks to:
-@MD XF for saving 23 bytes
-@WGroleau for saving 23 bytes
-@Jo King for saving 1 byte
[Answer]
# [Keg](https://github.com/JonoCode9374/Keg), ~~56~~ 19 bytes
```
?(¦b8|e3|i1|s5║ ™⅍,
```
Uses the newly implemented switch statements to remove 37 bytes!
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~33~~, ~~31~~, ~~29~~, 28 bytes
```
->x{x.tr"BEISbeis","8315"*2}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf166iukKvpEjJydUzOCk1s1hJR8nC2NBUScuo9n9BaUmxQppecmJOjoZSak5mSaqS5n8A)
-2 bytes thanks to @manatwork
[Answer]
# [Haskell](https://www.haskell.org/), ~~58~~ 55 bytes
-3 bytes thanks to @Laikoni!
```
map(\c->last$c:[b|(a,b)<-zip"BEISbeis""83158315",a==c])
```
[Try it online!](https://tio.run/##FcuxCsIwEADQXzlChxZaQUQQMQ6Kg@BQcBGsQ5KeydGYBnNQEL/dqMMbn1NpQO@zlV1@qFh2ptl6lbgw66t@l6rW1aZ5URS7w/GskZIQq8V8@SdqJaW5Vb9HASTEJwWGAiyIE3ICiwz9OAWYiB2wQxioTxBxjB5nIn/M3SubcnPZt@0X "Haskell – Try It Online")
[Answer]
# Excel, 147 bytes
```
=SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(A1,"B",8),"b",8),"E",3),"e",3),"I",1),"i",1),"S",5),"s",5)
```
So elegant...
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 53 bytes
Inputs a string, outputs an array of char codes.
```
s=>s.Select(c=>"beisBEIS".Contains(c)?48+17/(c%16):c)
```
[Try it online!](https://tio.run/##NczRCoIwFADQ975iCMG9VAshKtItKhR8C@wH5mXUwCbsTqKvX2H0AecQr4hdqkdPJcfg/H3ZVH582mC63pbOR61FLVRipVm2trcUgZTOOuv4XDVtJi@Dj8Z5BsLjZr/Id2ugeb7FA2EqZtfvGcHbl/j1UMNkRbQcxTTg/zVKAz1MQIPyNpxCMG9AxCJ9AA "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~98~~, ~~92~~, ~~70~~, 55 bytes
```
s=>s.Select(x=>(x+"88331155")["BbEeIiSs".IndexOf(x)+1])
```
[Try it online!](https://tio.run/##Jc3BCoIwGADge08xdtqoBBFBUHdQrAZRB4MO0UH/fnNgC/ZP2NuvQ98LfEB7IBMPq4WKvDP2vdOdXT/ohnHBCubBKcUmVkeqFSU9LghehFqJsOVFkWVpmudcPngzdqhNTzzR9oXhOokgt@lTxnJzd8bj2VgU/yFpvxYGLybBG@NhRmIjskbf2pO@HLmUsow/ "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 17 bytes
```
XQ"BEISbeis""8315
```
[Try it online!](https://tio.run/##K6gsyfj/PyJQycnVMzgpNbNYScnC2ND0/3@lkNTiksy8dIWkSgXXisTcgpzUYiUA "Pyth – Try It Online")
```
X # Translate characters in
Q # the input
"BEISbeis" # that are in this string from this string
"8315" # to this string (modular indexing: "B"->"8", "b"->"8")
```
[Answer]
# IBM/Lotus Notes Formula, 76 bytes
```
@ReplaceSubstring(i;@Explode("B b E e I i S s");@Explode("8 8 3 3 1 1 5 5"))
```
Takes input as `i`. Works because `@ReplaceSubstring` can take a list of characters to replace and a list of replacement characters and match them one to one.
There is no TIO for formula so a screenshot is shown below:
[](https://i.stack.imgur.com/QlDuK.png)
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 13 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
d`ßÈ`í8#ì)pu
```
Includes an unprintable (charcode 153) after the `#`.
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=ZGDfyGDtOCOZ7ClwdQ&input=IkFhQmJDY0RkRWVGZkdnSGhJaUpqS2tMbE1tTm5Pb1BwUXFSclNzVHRVdVZ2V3dYeFl5Wnoi)
```
d`ßÈ`í8#ì)pu :Implicit input of string
d :For each pair of characters in the following, replace the first with the second
`ßÈ` : Compressed string "bise"
í : Interleave
8# : 8153
ì : To digit array
) : End interleave
p : Append
u : Uppercase
```
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~20~~ ~~19~~ 16 bytes
```
Y`B\EISbeis`8315
```
-1 byte thanks to *@ovs* (transliterating `Ss` to `5` due to (quote from docs): "*If the `to` list is shorter than the `from` list and the current character appears after the end of the `to` list, it gets mapped to the last character in the `to` list (alternatively, you can think of it as padding `to` to the length of `from` using the last character in `to`).*" So only a single `5` is necessary in the `to` list.)
-3 bytes thanks to *@FryAmTheEggman*, using the cyclic transliterate `Y` instead of the regular `T`.
[Try it online.](https://tio.run/##K0otycxLNPyvquGe8D8ywSnG1TM4KTWzOMHC2ND0//@QjMxiBSBKVChJLS6xUnBKck31zAwu5nLMS1HISC1KVUjMyy8BMhRSE4szgVR@XioA)
**Explanation:**
Pretty straight-forward; transliterates the characters `BEISbeis` to `83158315`.
Two things to note:
- The `\` is to escape the `E`, because the `E` within the transliterate is a builtin for `02468`.
- The cyclic transliterate `Y` is used instead of the regular transliterate `T`. In the cyclic transliterate, the characters are repeated indefinitely. So the `BEISbeis` is actually `BEISbeisBEISbeisBEISbeis...` and the `8315` is actually `831583158315...` Only the first character in the `from`-list are relevant, though. So this will transliterate `BEISbeis` to `83158315`.
[Answer]
# Brainfuck, 475 bytes
```
>,[>+++++++++++[<------>-]<[>++[<+++++>-]]<[<]>>++[<----->-]<---[>+++[<++++++>-]]<[<]>>+++[<------>-]<----[>++++[<++++++>-]]<[<]>>++++[<------>-]++[<----->-]<[>+++++[<++++++>-]]<[<]>>+++++[<------>-]+++[<----->-]<[>++++++[<+++++++>-]]<[<]>>++++++[<------->-]<---[>+++++[<++++++++++>-]]<[<]>>+++++[<---------->-]<----[>+++++++[<++++++++>-]]<[<]>>+++++++[<-------->-]++[<----->-]<[>++++++[<++++++++++>-]<++>]<[<]>>++++++[<---------->-]<-->++++++++++[<+++++++++++>-]<+++++.[-],]
```
Basically, it works like this:
1. For each inputted character...
1. Subtract the value of B
2. If the resulting value is nonzero, add B-8
3. Subtract B-8
4. Subtract the value of B-E
5. If the resulting value is nonzero, add E-3
6. Subtract E-3
7. So on for every letter in the order of least to greatest ASCII
8. At the end, add the value of s (the greatest ASCII) back
Sorry it's like super duper messy.
[Answer]
# Vim, ~~48~~ ~~44~~ 42 bytes
```
se ic
%s/b/8/g
%s/e/3/g
%s/i/1/g
%s/s/5/g
```
A Vim script taking advantage of the repeated pattern has more bytes:
# Vim, ~~82~~ 59 bytes
```
for p in ['b/8','e/3','i/1','s/5']
exe'%s/\c'.p.'/g'
endfo
```
[Answer]
# T-SQL, 127 bytes
```
print replace(replace(replace(replace(replace(replace(replace(replace(@,'e',3),'E',3),'b',8),'B',8),'i',1),'I',1),'s',5),'S',5)
```
Assuming "@" the input. Not very efficient, though. :)
[Answer]
# [J](http://jsoftware.com/), 28 bytes
```
rplc'BEISbeis';"0'8315'$~8"1
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/iwpyktWdXD2Dk1Izi9WtlQzULYwNTdVV6iyUDP9rcilwpSZn5CukKag7pebklysUlxalJSanKngWK6QkFmWrc/0HAA "J – Try It Online")
[Answer]
# CJam, 20 characters
```
q"beisBEIS"8315`2*er
```
[Try it online!](https://tio.run/##S85KzP3/v1ApKTWz2MnVM1jJwtjQNMFIK7Xo//9Ex7okp7pU17pMz7ri4LqqKAA "CJam – Try It Online")
] |
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win.
Closed 7 years ago.
[Improve this question](/posts/1034/edit)
`For` loops are used extensively in many languages, but what would you do if no languages supported them?
Create a way to execute a basic `for` loop without using any repetition structures (`for`, `foreach`, `while`, `do`, etc).
The basic for loop that you need to replicate is set up like this
```
for(i=0;i<1000;i++)
```
You must be able to replicate this without using repetition structures. It must also execute code in your language that would be in the body of the loop. Any form of `eval` is allowed, though it may not execute the `for` loop on its own.
You can test your code by having it print `i` with a space 100 times, add this test case to the end of your answer to verify your code with others.
There are no restrictions on what exactly it has to be, all it needs to do is replicate the `for` loop.
Winner will be decided based on upvotes at the time that it is chosen.
[Answer]
## C, 45 chars without goto, if, for, ...
Not the smallest solution, but I find this way of doing it quite interesting in C :)
Doesn't use `goto`, `if`, `for`, or any other kind of control structures.
The function by itself (45 chars):
```
m(){int (*a[])()={m,exit};i++;(*a[i>999])();}
```
A compilable, working program:
```
#include <stdio.h>
#include <stdlib.h>
int i=0;
m(){int (*a[])()={m,exit};i++;printf("%i ",i);(*a[i>999])();}
int main()
{
m();
}
```
[Answer]
## Haskell, 33 chars
This is more like *inventing* the for loop, because there is no such nonsense in Haskell :P.
```
mapM_(putStr.(' ':).show)[0..999]
```
[Answer]
## GCC - 106 95 chars
```
#define FOR(i,l,h)auto F();L(F,l,h);int F(i)
L(int f(int),int l,int h){l<=h?f(l),L(f,l+1,h):0;}
```
Unlike the other C solutions where you have to declare a callback, this one does it for you automagically:
```
FOR(i, 1, 10) {
printf("%d\n", i);
}
```
It works by using GCC's [nested function](http://gcc.gnu.org/onlinedocs/gcc/Nested-Functions.html) extension. Namely, it forward-declares the nested function `F`, passes it to the looping function `L`, and then starts the definition of `F`, leaving the braces for the user to add.
One beautiful thing about nested functions in GCC is that they support downward funargs, meaning the illusion is nearly complete:
```
long n = 1;
FOR(i, 1, 10) {
n *= i;
}
printf("%ld\n", n); // 3628800
```
There is one major caveat: if you use `FOR` twice in the same scope, you'll get a conflict (namely, it will compile, but all the `FOR` loops will share one loop body). To allow multiple FOR loops in the same scope, we'll need 69 65 more characters:
**175 160 chars:**
```
#define FOR(i,l,h)F(i,l,h,__COUNTER__)
#define F(i,l,h,f)auto N(f)();L(N(f),l,h);int N(f)(i)
#define N(n)F##n
L(int f(int),int l,int h){l<=h?f(l),L(f,l+1,h):0;}
```
[Answer]
## C, 21 characters
```
f(){if(c++<999)f();}
```
For example:
```
#include <stdio.h>
int c = 0;
f()
{
printf("%d ", c);
if (c++<999) f();
}
int main(void)
{
f();
}
```
Outputs:
```
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 ... 998 999
```
[Answer]
## C# — no recursion, no goto
(using the Y combinator from lambda calculus)
```
class Program
{
delegate Func<TInput, TResult> Lambda<TInput, TResult>(Lambda<TInput, TResult> f);
static Func<TInput, TResult> Y<TInput, TResult>(Func<Func<TInput, TResult>, Func<TInput, TResult>> f)
{
Lambda<TInput, TResult> y = r => n => f(r(r))(n);
return y(y);
}
static void Main()
{
Func<int, int> fibonacci = Y<int, int>(f => n => n > 1 ? f(n - 1) + f(n - 2) : n);
Func<int, int> factorial = Y<int, int>(f => n => n == 0 ? 1 : n * f(n - 1));
// Executes “fibonacci” 10 times, yielding 55
Console.WriteLine(fibonacci(10));
// Executes “factorial” 5 times, yielding 120
Console.WriteLine(factorial(5));
}
}
```
[Answer]
## x86 assembly, ~~12~~ 11 bytes' worth of instructions
```
66 31 c0 xor %ax,%ax
<body> ; involving %ax
66 40 inc %ax
66 3d e8 03 cmp $1000,%ax
75 ?? jne <body>
```
[Answer]
### Yet another Scala variant
Since Scala allows to use non-ASCII characters, we can implement real for :) (`o` is cyrillic).
```
def fоr(s:Unit,c: ⇒Boolean,e: ⇒Unit)(b: ⇒Unit):Unit=if(c){b;e;fоr(0,c,e)(b)}
```
Test:
```
var i:Int = _
fоr (i = 0, i < 1000, i += 1) {
print(i + " ")
}
```
[Answer]
## Ruby 1.9 - 51 characters
```
def f a,b,c,&d
a[]
k=->{d[];c[];redo if b[]}
k[]end
```
This is a lot larger than other entries, but I think it captures the essence of the question better. In effect this allows you to write code almost exactly like the example:
```
def f a,b,c,&d
a[]
k=->{d[];c[];redo if b[]}
k[]end
i = 0 # Have to pre-declare i to have the closures work properly
f(proc{ i = 0 }, proc{ i < 1000 }, proc{ i += 1}) do
p i
end
# Been a long time since I've actually used for's so took a long
# time to think of a non-trivial use.
j, sum = 0, 0 # Pre-declare variables for the closures
goal = 1000
f(proc{ j = 1; sum = 1 }, proc{ sum < goal }, proc{ j += 1 }) do
sum = sum * j
end
puts "The next largest factorial after #{goal} is #{j-1}! at #{sum}"
```
[Answer]
# JavaScript, 34 characters
This assumes the actual printing function is *not* part of the `for` loop.
parameterized recursion **(43)**:
```
function f(i,m,c){if (i<m){c();f(++i,m,c)}}
function f(i, max, callback)
{
if (i<max)
{
callback();
f(++i,max,callback);
}
}
```
reverse recursion **(36)**:
assumes `max >= 0`
```
function f(m,c){if(m){c()
f(--m,c)}}
function f(max,callback)
{
if(max)
{
callback();
f(--max,callback);
}
}
```
ternary operator **(34)**
```
function f(m,c)
{m?c()&f(--m,c):0}
```
[Answer]
# C#, 70 57 characters
C# isn't the weapon of choice for code golf, but I thought I'd try it out:
```
void f(int i,Func<int,bool>j,int k){if(j(i)) f(i+k,j,k);}
```
This doesn't only perform the task of counting up to 1000; rather, it attempts to actually replicate `for` loop behavior for any task. That seemed somewhat closer to the intent of the challenge, but maybe that's just me.
Expanded:
```
void f(int i, Func<int, bool> j, int k)
{
if (j(i))
{
f(i + k, j, k);
}
}
```
Usage is very close to for-loop syntax:
```
f(0, i => i < 1000, 1);
```
[Answer]
## Python
Specific case:
```
exec("print i,"+";")*1000
```
And in general:
```
exec("f"+";")*1000
```
where 'f' is your code. Proabably doesn't work for all cases.
[Answer]
**C: 33 chars** for the base for loop (assuming goto is allowed)
```
int i=0;s:if(i<1000){/`*code inside for loop here`*/i++;goto s;}
int i=0;s:if(i<1000){printf("%d ",i);i++;goto s;}
```
[Answer]
I shall bear great shame for this, but here it is in Linux shell:
```
cat -An /dev/urandom|head -n1000|cut -f1
```
40 characters.
[Answer]
## PowerShell 18
```
filter p{$i=$_;$i}
```
1 - 10
```
PS C:\> (1..100 | p)-join' '
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 6
4 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
```
Yeah, it's completely useless and you have to rewrite the function to do anything useful. But isn't that kind of the point? :)
[Answer]
Here's your loop using Brainfuck, which is probably cheating:
```
,[.,]
```
[Answer]
# C (No recursion, no goto's)
```
#include <stdio.h>
int main()
{
puts("0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999");
return 0;
}
```
Completely according to the definition, isn't it?
[Answer]
## JavaScript - 39 characters in test case
**Chrome, Opera, and IE:** `eval(s="i<1e3&&eval(s,print(i++))",i=0)`. This fails with "call stack size exceeded" on Safari and "too much recursion" on Firefox.
**Firefox:** `(function f()i<1e3&&f(print(i++)))(i=0)`. This uses Mozilla's non-standard "expression closure" feature to eliminate a pair of curly braces.
**Note:** Change `print(i++)` to `alert(i++)` if you need to. You can change `1e3` to `100` to reduce the number of iterations for Safari.
[Answer]
## QBasic (24 characters)
```
1?i:i=i+1:IF i<1E3THEN 1
```
expands to:
```
1 PRINT i: i = i + 1: IF i < 1000! THEN 1
```
**Note:** This assumes that `i` still has its original value of 0.
[Answer]
## J, ?<10 chars
```
f^:1000
```
In J there are (almost) no loops; instead, one usually uses arrays and implicit loops through them. For example, to sum the integers 1..100, you apply (/) the "verb" plus (+) to the array 1..100 (i.101)
```
+/i.101
5050
```
To display the numbers 0..99, we just construct the array:
```
i.100
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 ...
```
`^:` is the "power" verb; `f^:1000` is something like `exec()*1000` in python.
[Answer]
## C#, 58 characters
**Update:** D'oh...appears this is a virtually identical answer to [Eelvex](https://codegolf.stackexchange.com/questions/1034/reinvent-the-for-loop/1052#1052) who beat me by a few minutes.
Not very clever - just simple recursion in .NET.
```
void f(int c,int m){Console.Write(c+" ");if(c++<m)f(c,m);}
```
Or taking out the body of the "for loop" (35 characters):
```
void f(int c,int m)if(c++<m)f(c,m);
```
Allows to seed the initial value and the max value.
[Answer]
# Scala
Inspired from [Nemo157's answer](https://codegolf.stackexchange.com/questions/1034/reinvent-the-for-loop/1044#1044):
```
def myfor(test: =>Boolean, inc: =>Unit)(stmts: =>Unit) : Unit =
if (test) {
stmts
inc
myfor(test, inc)(stmts)
}
```
And this can be used like this:
```
var i = 0
myfor(i<1000, i+=1) {
print(i+" ")
}
```
Golfed (62) :
```
def f(t: =>Boolean,i: =>Unit)(s: =>Unit){if(t){s;i;f(t,i)(s)}}
```
---
Or:
```
def myfor[A](init: A, test: (A)=>Boolean, inc: (A)=>(A))(stmts: =>Unit) : Unit =
if (test(init)) {
stmts
myfor(inc(init), test, inc)(stmts)
}
myfor[Int](0, _<10, _+1) {
println("loop")
}
```
[Answer]
**Clojure**
`(map #(print (str % " ")) (range 1 (inc 100)))`
Replace print with the function to execute.
Use (inc 100) or 101 for the last value.
[Answer]
## Perl, 21 characters
```
map{print"$_ "}0..999
```
[Answer]
# Perl most simple - 18 chars (ok, cheating)
```
print"@{[0..999]}"
```
output:
0 1 2 3 ... 998 999
but:
# Perl regex/goatse op (real pseudoloop) - 39 (16) chars
```
()="@{[0..999]}"=~/\d+(?{print"$& "})/g
```
### the 'base loop' beeing 16 chars
```
()= =~/\d+(?{ })/g
```
output:
0 1 2 3 ... 998 999
Regards
rbo
[Answer]
# Javascript - 86 chars
```
e=eval,n=function(j,k,c){if(e(j))e(k),c(),n(j,k,c)},f=function(i,j,k,c){e(i),n(j,k,c)}
```
Maybe not the shortest javascript solution, but it replicates iterator declaration, iterator manipulation as well as a looping condition.
Example use case:
```
f('a = 0', 'a < 9', 'a++', function() {
console.log(a);
});
```
[Answer]
```
;; for (int index=1, result=1; !cmp(result, max); index=incr(index)) result=body(index,result);
((lambda (index result cmp max body incr)
((lambda (f n i)
(if (cmp i max) n
(f f (body i n) (incr i))))
(lambda (f n i)
(if (cmp i max) n
(f f (body i n) (incr i)))) result index)) 1 1 > 1000 (lambda (i n) (printf "i:~a~nn:~a~n" i n) (* n i)) (lambda (x) (+ x 1)))
```
[Answer]
## LISP, 91 characters
```
(defun m(x)(if(= 1000(length x))x(m(append x(list(1+(car(last x))))))))
(mapcar #'f(m'(0)))
```
*It could be shorter with labels.*
Example usage:
```
(defun f(x) (format t "~a " x))
(mapcar #'f (m '(0)))
0 1 2 3 4 5 6 7 8 9 10 11 12 ... 997 998 999
```
[Answer]
bash:
```
echo {1..1000}
```
14 chars.
[Answer]
## Python3 - 27 chars
```
any(map(print,range(1000)))
```
[Answer]
## Windows Batch File, 65
```
set I=%S%
:l
if %I% GEQ %E% goto :eof
call %C%
set /a I+=1
goto l
```
Test file:
```
@echo off
set S=0
set E=100
set "C=<nul set /p X=%%I%% "
call for.cmd
```
Can save two bytes if the loop always starts at 0.
] |
[Question]
[
This challenge is about printing a series of growing ASCII-art arrows. I'll describe the pattern in words, but it might be easier to look at what the start of this series looks like:
```
>
<
->
<-
-->
<--
--->
<---
---->
<----
----->
<-----
------>
<------
...
```
An arrow with length n contains an arrowhead (`<` or `>`) and `n-1` dashes (`-`). A right-facing arrow has the dashes first, then a `>`. A left-facing arrow starts with `<`, and is followed by the dashes. The series consists of a length `n` right-facing arrow followed by a length n left-facing arrow, with n from 1 to infinity.
To complete the challenge, write a program or function that takes one input, an integer `i >= 1`, and outputs the first `i` arrows. Arrows are individual, not in right-left pairs, so for `i=3` you should output:
```
>
<
->
```
You can return a list of strings, or print them one after the other. If printing, the arrows must be delimited by some consistent delimiter, which doesn't have to be a newline as in the example.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so fewest bytes wins.
[Answer]
# [Canvas](https://github.com/dzaima/Canvas), 10 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md)
```
⇵-×<n¹[↔}]
```
[Try it here!](https://dzaima.github.io/Canvas/?u=JXUyMUY1LSVENyUzQyV1RkY0RSVCOSV1RkYzQiV1MjE5NCV1RkY1RCV1RkYzRA__,i=MTA_,v=8)
[Answer]
# [R](https://www.r-project.org/), 69 bytes
```
for(i in 1:scan()-1)cat('<'[i%%2],rep('-',i/2),'>'[!i%%2],'
',sep='')
```
[Try it online!](https://tio.run/##K/r/Py2/SCNTITNPwdCqODkxT0NT11AzObFEQ91GPTpTVdUoVqcotUBDXVddJ1PfSFNH3U49WhEirs6lrlOcWmCrrq7539D4PwA "R – Try It Online")
* -5 bytes thanks to @Giuseppe
* -3 bytes thanks to @Robert S.
[Answer]
# [Java (JDK)](http://jdk.java.net/), 81 bytes
```
n->{for(int i=0;i<n;)System.out.printf(i%2<1?"<%s%n":"%s>%n","-".repeat(i++/2));}
```
[Try it online!](https://tio.run/##bY7BTsMwDIbvfQqrUqWW0sB2XLrtsBMHTjsiDiFLJpfWqRJnEpr67CWrYAfEwf5l//Znd@qimu70OeMwOs/QpVpExl7YSJrRkXiQme5VCPCqkOCaAYzxo0cNgRUnuTg8wZC88sge6fz2DsqfQ7WMArwQHxyFOBgPdjtTs7ta50skBtw@S2xJVsevwGYQLrIYE4JticW6Xe3ztggF5Zu8CLukj3mTC29Go7jEun5aV5WcZrmcuTMhQVNuYXXTuv79A@DvlZ5KhBoSvpI/I1Yorc2Y8PfWP1vJW8wpu8U0fwM "Java (JDK) – Try It Online")
## Explanations
```
n->{ // int-accepting consumer
for(int i=0;i<n;) // for each i from 0 to n-1 included
System.out.printf( // output on stdout with a pattern
i%2<1 // if i is even:
?"<%s%n" // use the left-arrow pattern
:"%s>%n", // else: use the right-arrow pattern
"-".repeat(i++/2) // fill the "%s" in the pattern with i/2 dashes, and increment i
); //
} //
```
[Answer]
## Haskell, ~~41~~ 40 bytes
```
(`take`g">")
g p=p:('<':init p):g('-':p)
```
[Try it online!](https://tio.run/##BcFBCoAgEADAe69YJFAPnoMle0mHRNQWTZb0/W0zdxg1tSbZn2KuGWq6ijqUXQqwZzR610idJrDFYrTTyFaeQB088Et9wgoZNvlibqEMcZH5Bw "Haskell – Try It Online")
Plain old recursion: start with string `p` = `">"`, collect `p`, a `<` in front of all but the last char of `p` and a recursive call with one `-` put in front of `p`. Take the first `n` items of this list.
Edit: -1 byte thanks to @xnor.
[Answer]
# [Commodore BASIC V2](https://de.wikipedia.org/wiki/Commodore_Basic_V2) (C64), 94 bytes
```
0inputn:fOi=1ton:oniaN1gO1:?"<";
1on-(i<3)gO2:fOj=1.5toi/2:?"-";:nE
2on-nOiaN1gO3:?">";
3?:nE
```
Not entirely sure about the byte count, this is based on the text representation for typing the valid program. It's a bit shorter on disk (91 bytes) because BASIC V2 uses a "tokenized" representation of programs.
### [Online Demo](https://vice.janicek.co/c64/#%7B%22controlPort2%22:%22joystick%22,%22primaryControlPort%22:2,%22keys%22:%7B%22SPACE%22:%22%22,%22RETURN%22:%22%22,%22F1%22:%22%22,%22F3%22:%22%22,%22F5%22:%22%22,%22F7%22:%22%22%7D,%22files%22:%7B%22arrows.prg%22:%22data:;base64,AQgcCAAAhU46gUmyMaROOpFJrzGJMTqZIjwiOwA9CAEAkasoSbMzKYkyOoFKsjEuNaRJrTI6mSItIjs6ggBQCAIAkauoSa8xiTM6mSI+IjsAWAgDAJk6ggAAAA==%22%7D,%22vice%22:%7B%22-autostart%22:%22arrows.prg%22%7D%7D)
Slightly "ungolfed":
```
0 inputn:fori=1ton:oniand1goto1:print"<"; :rem read n from user, loop to n, if odd skip "<"
1 on-(i<3)goto2:forj=1.5toi/2:print"-";:next :rem skip for i<3, print (i-1)/2 times "-"
2 on-notiand1goto3:print">"; :rem if even skip ">"
3 print:next :rem newline and next loop iteration
```
[Answer]
# [Self-modifying Brainfuck](https://soulsphere.org/hacks/smbf/), 55 bytes
Take input as character code.
Only support input up to 255.
Use null character to separate lines.
Coincidentally, all arrow-drawing characters are used as BF commands. Unfortunately, it doesn't save any bytes (currently).
```
>>,[<<[-<.>>+<]<<.>>.+>>-[<<<<<.>>>>[-<+<.>>].>-<]>]<>-
```
[Try it online!](https://tio.run/##LY7NCoMwEITveYpFLFFs4g/0tuyLaA4xKvZQI5qD0PbZ01V6mZ2dgY/p7T5HN29Z/hbr9lzCBEl3pNnf36rmgLTOE/EVzgZABDn6ScIH5tEOoJyqgcD5YYxE9xaxVaiJCjR4Xl0QKU7x@oi4LU5nNCk0ZJBUZJ7gBfBgaOnXUO6vfrrk4nIaNpBdJVkWGX8 "Bash – Try It Online")
### Explanation
```
Code | Memory | Output | Comment
-------+-----------------------------+--------+--------------------------
| '<' '>' '-' [0] 0 0 0 | |
>>, | '<' '>' '-' 0 0 [x] 0 | |
[ | | |
| '<' '>' '-' l 0 [x] 0 | | l = arrow length
<<[-< | | | copy l to next cell
.>>+<] | | | and print '-'
| '<' '>' '-' [0] l x 0 | ----- | there are l '-'s
<<. | '<' [>] '-' 0 l x 0 | > |
>>.+ | '<' '>' '-' [1] l x 0 | <null> |
>>- | '<' '>' '-' 1 l [y] 0 | | y=x-1
[ | | | execute if y>0
<<<<<. | [<] '>' '-' 1 l y 0 | < |
>>>> | '<' '>' '-' 1 [l] y 0 | |
[-<+<. | | |
>>] | '<' '>' '-' L [0] y 0 | ----- | L=l+1
. | '<' '>' '-' L [0] y 0 | <null> |
>-<]>] | | | decrement y
<>- | | | do nothing, used as data
```
[Answer]
# [Python 2](https://docs.python.org/2/), 54 bytes
thanks to the and Jo King for fixing a bug.
```
k=0
exec"print k%2*'<'+k/2*'-'+~k%2*'>';k+=1;"*input()
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P9vWgCu1IjVZqaAoM69EIVvVSEvdRl07Wx9I66pr14EF7NSts7VtDa2VtDLzCkpLNDT//7cEAA "Python 2 – Try It Online")
[Answer]
# Pyth, 17 bytes
```
m_W%d2+*\-/d2@"><
```
Output is a list of strings. Try it online [here](https://pyth.herokuapp.com/?code=m_W%25d2%2B%2A%5C-%2Fd2%40%22%3E%3C&input=8&debug=0).
```
m_W%d2+*\-/d2@"><"dQ Implicit: Q=eval(input())
Trailing "dQ inferred
m Q Map [0-Q), as d, using:
/d2 Floored division of d by 2
*\- Repeat "-" the above number of times
+ Append to the above...
@"><"d Modular index d into "><" - yields ">" for even d, "<" for odd
- examples: d=4 gives "-->", d=7 gives "---<"
_W Reverse the above if...
%d2 ... (d % 2) != 0
Implicit print result of the map
```
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~62~~ ~~56~~ 50 bytes
```
param($n)(0..$n|%{($j='-'*$_)+'>';"<$j"})[0..--$n]
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/vyCxKDFXQyVPU8NAT08lr0a1WkMly1ZdV11LJV5TW91O3VrJRiVLqVYzGiivq6uSF/v//39TAA "PowerShell – Try It Online")
Loops from `0` up to input `$n`, each iteration creating two arrow strings. Those are then indexed with `0..--$n` to pull out the correct number of elements.
*Saved 6 bytes thanks to KGlasier.*
[Answer]
# Python 3, 53 bytes
My first codegolf answer.
```
lambda x:[i%2*"<"+i//2*"-"+~i%2*">"for i in range(x)]
```
-10 bytes thanks to Jo King
[Answer]
# [Haskell](https://www.haskell.org/), ~~51~~ 44 bytes
-7 bytes thanks to [xnor](https://codegolf.stackexchange.com/users/20260/xnor) (using `iterate` over list-comprehension)!
```
(`take`do b<-iterate('-':)"";[b++">",'<':b])
```
[Try it online!](https://tio.run/##DcuxDoIwEADQX7l0KQRLdMXi4qoTo5pwhSsQSmna8/etLG97M6aVnMsWWnjnomdcqR93MFotTBGZCqlkUwpxfZmqEjdxklo25lPmDRd/rA3DE8KXO44PDzVYOIiEI7Raw0R83z2T55Qv599gHU4pqyGEPw "Haskell – Try It Online")
## Explanation / Ungolfed
Using `do`-notation saves us a `concat`, and using infix-notation allows a pointfree function with `take`, undoing these would give:
```
f n = take n $ concat [ [b++">", '<':b] | b <- iterate ('-':) "" ]
```
[Answer]
# Japt `-m`, ~~16~~ ~~15~~ ~~13~~ 12 bytes
*Saved 1 byte thanks to [Shaggy](https://codegolf.stackexchange.com/users/58974/shaggy)*
```
g<i>)iUUz ç-
```
[Test it online](https://ethproductions.github.io/japt/?v=1.4.6&code=ZzxpPilpVVV6IOct&input=MTAKCi1tUg==)
## Explanation:
```
-m // Map the program through [0...Input); U becomes the iterative number
g<i>)iUUz ç-
<i> // ">" prepended with "<", creating "><"
g // Get the char at index U, with index-wrapping
i // Insert:
U // At index U, with index-wrapping
ç- // "-" repeated:
Uz // U/2 times
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 15 bytes
```
ị⁾><;’H”-ẋƲṚ⁸¡)
```
[Try it online!](https://tio.run/##ATYAyf9qZWxsef//4buL4oG@Pjw74oCZSOKAnS3huovGsuG5muKBuMKhKf/Dhysv4oKsxZLhuZj//zM "Jelly – Try It Online")
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf), ~~17~~ 15 bytes
Saved 2 bytes thanks to Jo King and Kevin Cruijssen
```
{ï½'-*'>ï¥╛Å⌡\n
```
[Try it online!](https://tio.run/##y00syUjPz0n7/7/68PpDe9V1tdTtgIylj6bOPtz6qGdhTN7//4amAA "MathGolf – Try It Online")
## Explanation
The 15-byte approach is different compared to my original solution, I can't take any credit for the implementation.
```
{ start block or arbitrary length
ï index of current loop, or length of last loop
½ pop a : push(a//2 if int else a/2)
'- push single character "-"
* pop a, b : push(a*b)
'> push single character ">"
ï index of current loop, or length of last loop
¥ modulo 2
╛ if without else
Å start block of length 2
⌡ decrement twice
\ swap top elements
n newline char, or map array with newlines
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt) `-m`, 14 bytes
```
"<>"¬hUUz ç-)q
```
[Try it online!](https://ethproductions.github.io/japt/?v=1.4.6&code=Ijw+IqxoVVV6IOctKXE=&input=MTAKLVJt)
Updated with a completely new method.
Explanation:
```
#Implicitly map over the range [0..input) as U
"<>" #The string "<>"
¬ #Split into the array ["<",">"]
hU ) #Replace the element at index U with wrapping:
- # The character '-'
ç # Repeated a number of times equal to
Uz # U integer divided by 2
q #Join the array to a string
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~80~~ ~~77~~ ~~76~~ ~~74~~ 71 bytes
```
g(n,i,j){--n&&g(n);for(j=n%2,i=n/=2;putchar(~n?n---i*j?45:62-j*2:0););}
```
[Try it online!](https://tio.run/##DcfBCsIwDADQ@77CiyMpDbowPSyUfksp2LWwKENPo/569N1eppKzWQH11Tc8iHQc/0N5PHdoQc/sa9BLYHl93nlNO3w1KhFV1@J8W@5MzfFyRUHptqWqgKdjKMATytDtBw "C (gcc) – Try It Online")
-3 bytes with idea from [ASCII-only](https://codegolf.stackexchange.com/questions/177454/draw-some-expanding-arrows/177688?noredirect=1#comment430683_177688).
-1 with `\0` instead of `\n`
-5 rearranging parts
---
Output includes a trailing `\0`.
```
g(n,i,j){
--n&&g(n); //draw smaller arrows first (if n>1)
for(j=n%2,i=n/=2; //j:!(input parity); i:arrow len-1=ceil(input)/2-1
putchar(~n //if n>=0, arrow is not yet completed
? n---i*j //if not first (j==1) or last (j==0) char of arrow:
? 45 // output '-'
: 62-j*2 // otherwise, output the appropriate arrow head
: 0);); //\0 after arrow complete. putchar returns 0; loop terminates
}
```
[Answer]
# JavaScript (ES6), 58 bytes
Returns a space-separated string.
```
n=>(g=p=>n--?k++&1?`<${p} `+g(p+'-'):p+'> '+g(p):'')(k='')
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/P1k4j3bbA1i5PV9c@W1tbzdA@wUaluqBWIUE7XaNAW11XXdMKSNkpqIP4mlbq6poa2bZA8n9yfl5xfk6qXk5@ukaahqmmJheqiKGBpuZ/AA "JavaScript (Node.js) – Try It Online")
[Answer]
# [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), ~~123~~ ~~122~~ 118 bytes
```
N =INPUT - 1
P H =X / 2
Y =DUPL('-',H)
OUTPUT =EQ(H,X - H) Y '>' :S(I)
OUTPUT ='<' Y
I X =LT(X,N) X + 1 :S(P)
END
```
[Try it online!](https://tio.run/##TcqxCsIwEAbg@e4p/u0STJGKLmKcWkigxIgJXFZnsYPvT7Sb3/x93utzfR17pwQfU64FA0bOFOAVexyYGvxU82JkEBcs062Wrfn5boLTXw8WDXIVOj9M/AtyETSOpPBLMeqShWKHcXvZ8pwm6v30BQ "SNOBOL4 (CSNOBOL4) – Try It Online")
[Answer]
# [V](https://github.com/DJMcMayhem/V), 22 bytes
```
i>
<Àñäkjjé-já-ñÀGjdG
```
[Try it online!](https://tio.run/##K/v/P9OOy0b6cMPhjYeXZGdlHV6pm3V4oS6Q1@CeleL@//9/YwA "V – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 16 bytes
```
NθFθ«⊘ι↓>‖T»Fθ‖T
```
[Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05orLb9IAchQqObiDCjKzCvR8EjMKUtN0cjUBEpChaxc8svzdBSU7JRAYkGpaTmpySUhRYl5xUDduRpAwVq4OVhk//83/69blgMA "Charcoal – Try It Online") Link is to verbose version of code. I had three 17-byte solutions before I eventually stumbled over this one. Explanation:
```
Nθ
```
Input `n`.
```
Fθ«
```
Repeat `n` times, 0-indexed.
```
⊘ι
```
Draw a line of `-`s of length half the index (truncated).
```
↓>
```
Draw the arrowhead and move to the next line.
```
‖T»
```
Reflect everything, flipping the arrowheads.
```
Fθ‖T
```
The above loop has `n` reflections, but we need an even number of reflections, so perform another `n` reflections.
[Answer]
# [Clean](https://github.com/Ourous/curated-clean-linux), ~~76~~ 73 bytes
```
import StdEnv,StdLib
$n=take n[s\\i<-inits['--'..],s<-[i++['>'],['<':i]]]
```
[Try it online!](https://tio.run/##JY2xDoIwFEV3v@INJNVACa6mOOlgwsZYOpRSzQvtw9hq4s/7JGG6OWc41wVvieMyvYOHaJEY43N5ZejzdKVPtU6H466gNtvZA@k0DKgkEuakhZSirk2VlNRYllqcham0UOKExhjus11DLdyDzQHJJ9hDAcemgQP/3GofieWt48uXbES3wXbIcvwD "Clean – Try It Online")
Uses the neat fact that `['-','-'..]` is the same as `['--'..]` to save a bit.
[Answer]
# [6502 machine code](https://en.wikibooks.org/wiki/6502_Assembly) (C64), 49 bytes
```
00 C0 20 9B B7 A2 00 8A 4A A8 90 05 A9 3C 20 D2 FF A9 2D C0 00 F0 06 20 D2 FF
88 D0 FA 8A 4A B0 05 A9 3E 20 D2 FF A9 0D 20 D2 FF E8 E4 65 D0 D7 60
```
Still quite a bit shorter than [BASIC](https://codegolf.stackexchange.com/a/177468/71420) ;) This one has a number range only up to `255` because the natural integer size of the machine has only 8 bits.
### [Online demo](https://vice.janicek.co/c64/#%7B%22controlPort2%22:%22joystick%22,%22primaryControlPort%22:2,%22keys%22:%7B%22SPACE%22:%22%22,%22RETURN%22:%22%22,%22F1%22:%22%22,%22F3%22:%22%22,%22F5%22:%22%22,%22F7%22:%22%22%7D,%22files%22:%7B%22arrows.prg%22:%22data:;base64,AMAgm7eiAIpKqJAFqTwg0v+pLcAA8AYg0v+I0PqKSrAFqT4g0v+pDSDS/+jkZdDXYA==%22%7D,%22vice%22:%7B%22-autostart%22:%22arrows.prg%22%7D%7D)
Usage: `SYS49152,[n]` (e.g. `SYS49152,3` for the example from the challenge)
**Commented disassembly**:
```
00 C0 .WORD $C000 ; load address
.C:c000 20 9B B7 JSR $B79B ; get unsigned byte from commandline
.C:c003 A2 00 LDX #$00 ; main loop counter
.C:c005 .loop:
.C:c005 8A TXA ; loop counter to accumulator
.C:c006 4A LSR A ; divide by 2, shift lowest bit to C
.C:c007 A8 TAY ; result to Y
.C:c008 90 05 BCC .toright ; C clear -> counter even, skip '<'
.C:c00a A9 3C LDA #$3C ; load character '<'
.C:c00c 20 D2 FF JSR $FFD2 ; output character
.C:c00f .toright:
.C:c00f A9 2D LDA #$2D ; load character '-'
.C:c011 C0 00 CPY #$00 ; counter/2 == 0 ? then no dashes
.C:c013 F0 06 BEQ .skipdashes
.C:c015 .printdashes:
.C:c015 20 D2 FF JSR $FFD2 ; output character
.C:c018 88 DEY ; decrement Y
.C:c019 D0 FA BNE .printdashes ; not 0 yet -> repeat
.C:c01b .skipdashes:
.C:c01b 8A TXA ; loop counter to accumulator
.C:c01c 4A LSR A ; shift lowest bit to C
.C:c01d B0 05 BCS .toleft ; C set -> counter odd, skip '>'
.C:c01f A9 3E LDA #$3E ; load character '>'
.C:c021 20 D2 FF JSR $FFD2 ; output character
.C:c024 .toleft:
.C:c024 A9 0D LDA #$0D ; load newline character
.C:c026 20 D2 FF JSR $FFD2 ; output character
.C:c029 E8 INX ; next loop iteration
.C:c02a E4 65 CPX $65 ; compare to command line argument
.C:c02c D0 D7 BNE .loop ; not reached yet -> repeat main loop
.C:c02e 60 RTS ; exit
```
[Answer]
# JavaScript, 49 bytes
```
f=n=>--n?f(n,l='')+(n%2?`
<`+l:`
${l+='-'}>`):'>'
```
[Try it online!](https://tio.run/##VchBDsIgEADAO@/Q7G4oRuuNCHwFgmDabBYjphfj2@lVjzNr2lLPr@X5NtLuZYzqxHljJFSUiR0AaZTjHKK6Rc02qsOHtQMDXx/JgoeRm/TG5cTtgRWvROp3/lXxciYaOw "JavaScript (Node.js) – Try It Online")
[Answer]
# Powershell, 51 bytes
```
param($n)0..$n|%{'-'*$_+'>';'<'+'-'*$_}|?{$n---gt0}
```
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 39 bytes
```
{map {'<'x$_%2~'-'x$_/2~'>'x$_%%2},^$_}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwvzo3sUChWt1GvUIlXtWoTl0XxNAHMuzAIqpGtTpxKvG1/9M0jDXt7PSKEyutudI0jAygnP8A "Perl 6 – Try It Online")
Anonymous code block that returns a list of lines.
[Answer]
# [K (ngn/k)](https://gitlab.com/n9n/k), ~~31~~ 29 bytes
```
{"<->"x#2,x{(1=*x)_1,2-|x}\0}
```
[Try it online!](https://tio.run/##y9bNS8/7/z/NqlrJRtdOqULZSKeiWsPQVqtCM95Qx0i3pqI2xqD2f5qCocl/AA "K (ngn/k) – Try It Online")
first we generate lists with 0 instead of `"<"`, 1 instead of `"-"`, and 2 instead of `">"`:
`{` `}` function with argument `x`
`x{`...`}\0` apply the inner function `x` times, starting with an initial value of `0` and preserving intermediate results
`|x` reverse
`2-` replace 0 with 2 and vice versa, keep the 1s as they are
`1,` prepend a 1
`(1=*x)_` is the first of `x` equal to 1? if yes, drop one element, otherwise drop 0 elements (do nothing)
`2,` prepend a 2 for the initial `">"` arrow
`x#` we have a little too many lists, so take only the first `x` of them
`"<->"` use the lists' elements (0/1/2) as indices in this string
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~23~~ 20 bytes
```
FNÉD„><è'-N;∍«s_iR},
```
[Try it online!](https://tio.run/##yy9OTMpM/f/fze9wp8ujhnl2NodXqOv6WT/q6D20ujg@M6hW5/9/QwOD/wA "05AB1E – Try It Online")
First time using 05AB1E or any other golfing language for that matter. Any ideas welcome.
-3 from Kevin Cruijssen
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 90 bytes
```
a=>{for(int i=0;i<a;i++){var s=new String('-',i/2);Console.WriteLine(i%2<1?s+">":"<"+s);}}
```
[Try it online!](https://tio.run/##Nc29CsIwFEDh2T7FpSBNqPWnbqatFCdBFxWcQ0zlgiaQe61I8dlrEbqe4TuGMuOD7V@E7g7nD7F9KjAPTQQ1dBGxZjRQG0bvCnRcQQNlr8uqa3wQQwAslwoLrTBNZdfqAFQ6@4Yzh4EUSZbMcJFLtfOO/MPOrwHZHtBZgdO8WG0pjat4ExdxSlJ9v70an63HGxw1OiG7aNKIAWht4PnF7x2vczGCJ6tvf09KqaJBWC1/ "C# (.NET Core) – Try It Online")
Uses an [Action delegate](http://docs.microsoft.com/en-us/dotnet/api/system.action-1) to pull in the input and not require a return.
Ungolfed:
```
a => {
for(int i = 0; i < a; i++) // from [0, a)
{
var s = new String('-', i / 2); // create string of dashes of length (a / 2)
Console.WriteLine(i % 2 < 1 ? // write arrow
s + ">" : // if i is even: dashes plus ">"
"<" + s); // if i is odd: "<" plus dashes
}
}
```
[Answer]
# ES6, ~~96~~ ~~82~~ ~~79~~ 70 bytes
[Try it online!](https://tio.run/##JclRCsIwDADQf48REBLmou5TbMVzjOHC7CRjS0s3BE9fBd/vm@Qt65A1bbXFZyijK@Z8y8z3nOWDRh0vkhAfByXnUffNDa5wAaAKauAcUpAN9dhQ9c/feSAqQ7Q1zoHn@MIRzyfiKar1u57KFw "JavaScript (Node.js) – Try It Online") (Thanks to @Oliver)
```
n=>[...Array(n)].map((_,i)=>(i%2?"<":"")+"-".repeat(i/2)+(i%2?"":">"))
```
[Answer]
# [Red](http://www.red-lang.org), 109 108 bytes
-1 byte thanks to NK1406
```
func[n][repeat i n[print reduce[pick[pad/with pad/left/with]k: i% 2 + 1
pick copy"<>"k i / 2 + k - 1 #"-"]]]
```
[Try it online!](https://tio.run/##JYxBCsIwEEX3OcVnxJWUEl0IRTxEt8MsSjLBEIkhpIinj7bu3ud9XlXfZ/UsJkw9rNlxFq5adGmIyFxqzA1V/eqUS3SJy@LHd2wPbPDU0PYlaUI84owTrNl@cK/yodud0q8z7iJhgMWBBhKRHnAx/zqRCbDX/gU "Red – Try It Online")
] |
[Question]
[
To celebrate Rounded Pi Day, you must take advantage of today's date to make a program that takes in a circle's diameter and outputs its circumference by multiplying the diameter by 3.1416, where 3.1416 must be obtained using today's date.
```
Input 3
Output 9.4248
etc.
```
Does not take the date as input. You do not have to use all components of the date but the digits of pi must come from formatting a Date object or using a date object to obtain it. The answers so far look good.
Not sure what else to specify. All the answers so far meet what I was expecting.
My constraint was that you must use components of the date to come up with Pi. You can of course use the components, multiply by 0 then add 3.1416, but that's boring and wastes precious chars!
Shortest code wins!
[Answer]
# C, 32 bytes
```
#define f(d)d*time(0)/464083315.
```
If losing a little more accuracy is fine, I can get it down to about 29 bytes being still accurate to 4 digits past the decimal (as of the time of this posting):
```
#define f(d)d*time(0)/46408e4
```
[Answer]
# AppleScript, ~~122~~ 120 bytes
```
set a to current date
(display dialog""default answer"")'s text returned*(month of a+day of a*.01+year of a*1e-4 mod.01)
```
### Variable a
Variable a is a date object. I call all of my date information off of it.
### Month, day, and year
The month, day, and year calls actually return an object that normally returns a string. To properly use it as a number, I have surrounded it on both sides with mathematical operations to automatically cast it to a number.
### 1e-4
`1e-4` is a byte shorter than `.0001`.
### mod.01
`.` acts as a separator to the AppleScript autocorrect. By using this, I can use modulo and *still* keep it a byte for myself.
### No return statement/log
The last value calculated automatically is returned by the program. I output the number calculated via the return box.
And here's a gif of it running!
[](https://i.stack.imgur.com/RdUdW.gif)
[Answer]
# Mathematica + coreutils, 20 bytes
```
<<"!date +%m.%d%y"#&
```
Luckily, Mathematica interprets the output of an external command as an expression. In this case the output is a valid float, so that multiplication with the function argument `#` is implied.
[Answer]
## Lua, ~~30~~ 27 Bytes
```
print(...*os.date"%m.%d%y")
```
Multiply the first command-line argument by the current date in format `mm.ddyy`, which is actually `03.1416`.
[Answer]
## Bash + bc, ~~25~~ 20 bytes
```
date +%m.%d%y\*$1|bc
```
Thanks to [manatwork](https://codegolf.stackexchange.com/users/4198/manatwork) for saving five bytes.
Usage:
```
$ ./pi-round.sh 3
9.4248
```
[Answer]
# 05AB1E, ~~16~~ 13 bytes
```
žfžežg¦¦J*4°/
```
[Try it online.](http://05ab1e.tryitonline.net/#code=xb5mxb5lxb5nwqbCpkoqNMKwLw&input=Mw)
Unfortunately a bug with floats makes this a byte longer :/
Thanks to Adnan for golfing off 3 bytes.
## Explanation
```
žfžežg¦¦J*4°/
žfžežg push month day year
¦¦ slice off the first two chars from the year (2016 -> 16)
J join them together into a number
* multiply by input
4°/ divide by 1e4
```
[Answer]
## PowerShell v2+, ~~46~~ ~~28~~ 25 bytes
```
$args[0]*(Date -F "M.dy")
```
Pretty straightforward. Takes input `$args[0]` and multiplies it by the date [formatted as `M.dy`](https://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx) (the `Get-` is implied). Note that this may take a long time to run on v2 as it iterates possible substitutions for `Date` (e.g., checking your `%PATH%` environment variable, etc.) before settling on `Get-Date`.
[Answer]
# R 3.2.4, ~~55~~ ~~51~~ 47 bytes
**edit** I realized I could use `scan` thanks @FryAmTheEggMan. Reduced 4 bytes thanks to @MickyT.
```
scan()*as.numeric(format(Sys.Date(),'%m.%d%y'))
```
First attempt at a golf. Happy pi day!
[Answer]
# GNU Awk, 23 characters
```
$0*=strftime("%m.%d%y")
```
Sample run:
```
bash-4.3$ awk '$0*=strftime("%m.%d%y")' <<< 3
9.4248
```
[Answer]
# Pyth, 19 bytes
```
*Qvs[.d4\..d5>2`.d3
```
[Try it here!](http://pyth.herokuapp.com/?code=*Qvs%5B.d4%5C..d5%3E2%60.d3&input=3&debug=0)
Only works at 2016-03-14 of course.
## Explanation
```
*Qvs[.d4\..d5>2`.d3 # Q = input
.d4 # current month
\. # dot between month and day
.d5 # current day of the month
>2`.d3 # last 2 digits of the year
s[ # concat everything into a string
v # eval -> convert to float
*Q # multiply with input to get the circumference
```
[Answer]
# PHP, ~~45~~ ~~26~~ ~~25~~ 24 bytes
Uses Windows-1252 encoding
```
<?=$argv[1]*date(~‘Ñ•†);
```
Run like this:
```
echo '<?=$argv[1]*date(~‘Ñ•†);' | php -- 3
```
* Saved 19 bytes by using `date()` instead of `DateTime::format`
* Saved a byte by using the echo tag
* Saved a byte by using ISO-8859 encoding and negating the format string, so no need for double quotes. Might mess up your terminal a bit when running it from CLI, but works.
[Answer]
# Python 2, 58 chars
```
import time
print float(time.strftime("%m.%d%y"))*input()
```
[Try it!](http://ideone.com/fork/nDZbX3)
Explanation:
```
import time # Import time time module
print # Print the following
float( # Cast to float
time.strftime("%m.%d%y")) # Format the time as MM.DDYY
*input() # Multiply by input
```
[Answer]
# JavaScript, ~~41~~ 39 characters
This uses a proprietary **Firefox-only** method.
```
d=>new Date().toLocaleFormat`%m.%d%y`*d
```
Thanks to:
* [Ismael Miguel](https://codegolf.stackexchange.com/users/14732/ismael-miguel) for the template string suggestion (-2 characters).
Sample run (Firefox Web Console):
```
> (d=>new Date().toLocaleFormat`%m.%d%y`*d)(3)
9.4248
```
Note: this will fail in Firebug Console. Seems that Firebug performs some expansion on the template string, transforming ``%m.%d%y`` into ``%__fb_scopedVars(m).d%y`` before passing it to the code.
[Answer]
## Ruby, 40 bytes
```
->n{n*Time.new.strftime('%m.%d%y').to_f}
```
[Answer]
## Mathematica, 54
```
.0001FromDigits[Now@{"Month","Day","YearShort"},100]#&
```
[Answer]
# Vitsy + coreutils, 19 bytes
```
'y%d%.m%+ etad',W*N
```
Explanation:
```
'y%d%.m%+ etad',W*N
'y%d%.m%+ etad' Push 'date +%m.%d%y' to the stack.
, Execute as shell.
W Grab input from STDIN and eval it.
* Multiply the top two items
N Output as a number.
```
Cannot be run in safe mode, as this uses the Runtime's exec method.
[Answer]
# [SpecBAS](https://sites.google.com/site/pauldunn/), 39 bytes
```
1 INPUT n: ?n*VAL DATE$(TIME,"mm.ddyy")
```
Nothing out of the ordinary. Formats date as a string then multiplies the input by the `VAL` (value) of that string.
[Answer]
## Oracle 11g, ~~50~~ 49 bytes
```
SELECT &n*to_char(sysdate,'MM.DDYY')FROM dual;
```
one less byte, thanks to @MickyT
[Answer]
## Python 3, ~~74~~ 54 bytes
using the time module instead of datetime like [Loovjo's Answer](https://codegolf.stackexchange.com/a/75519/49289)
```
import time
lambda n:n*float(time.strftime('%m.%d%y'))
```
**previous solution**
```
from datetime import*
lambda n:n*float(datetime.now().strftime('%m.%d%y'))
```
[Answer]
## Google Sheets, 13 bytes
Bytes are calculated with one byte per character, zero bytes per cell except for the designated input cell, two bytes. The equals sign to start a formula is not counted. (I don't know if this is standard, please correct me if I am wrong.)
Run snippet to see the code.
```
table {
empty-cells: show;
}
table,
th,
td {
border: 1px solid black;
}
```
```
<table border="1">
<tr>
<th></th>
<th>1</th>
<th>2</th>
<th>3</th>
</tr>
<tr>
<td>A</td>
<td><input></td>
<td style="text-align:right">3.1416</td>
<td style="font-family:'Ubuntu Mono',monospace">=<span style="color:rgb(257,142,29)">A1</span>*<span style="color:rgb(126,55,148)">A2</span>
</td>
</tr>
</table>
```
This works because you can define your own date formats in Google Sheets. I made it so that it is `<month>.<day><year>`.
[Answer]
## [Pyke](https://github.com/muddyfish/PYKE/tree/master), ~~16~~ 15 bytes, ASCII encoding
```
C867wä%J"bT4^/*
```
Explanation:
```
C867 - b,c,d = year, day, month
wä - a = base_96("ä") - 100
% - a = a%b
J" - a = "".join([a,c,d])
b - b = base(a, 10)
T4^ - a = 10^4
/ - a = a/b
* - imp_print(a*eval_or_not(input))
```
or 11 bytes (non-competitive), (adds string singles, 2 digit year, string sumables)
```
C856\.R3sb*
```
Explanation:
```
C856 - a,b,c = 2d_year, day, month
\. - d = "."
R3 - a,b,c = b,c,a
s - a = sum(a,b,c)
b - a = base(a, 10)
* - imp_print(a*eval_or_not(input))
```
[Answer]
# [APL](http://goo.gl/9KrKoM), 19 bytes
```
⎕×0.01⊥⌽⍎2⌽8↑2↓⍕⎕TS
```
`⎕TS` is `2016 3 14 12 34 56 789` i.e. March 14rd, 2016 right before 12:35 pm
`⍕` make into string, i.e. `'2016 3 14 12 34 56 789'`
`8↑2↓` drop first two (`'20'`) then take next eight (`'16 3 14 '`)
`2⌽` rotate two characters, giving `' 3 14 16'`
`⍎` make into numbers (`3 14 16`)
`⌽` reverse the list, giving `16 14 3`
`0.01⊥` evaluate in base ¹⁄₁₀₀, = 16 × 0.01² + 15 × 0.01¹ + 3 × 0.01⁰ = 0.0016 + 0.15 + 3 = 3.1416
`⎕×` multiply with input
or
```
⎕×1E¯4⊥⌽⍎2⌽7↑2↓⍕⎕TS
```
`⎕TS` is `2016 3 14 12 34 56 789`, i.e. March 14rd, 2016 right before 12:35 pm
`⍕` make into string, i.e. `'2016 3 14 12 34 56 789'`
`7↑2↓` drop first two (`'20'`) then take next seven (`'16 3 14'`)
`2⌽` rotate two characters, giving `' 3 1416'`
`⍎` make into numbers (`3 1416`)
`⌽` reverse the list, giving `1416 3`
`1E¯4⊥` evaluate in base ¹⁄₁₀₀₀₀, = 1416 × 0.01¹ + 3 × 0.01⁰ = 0.1416 + 3 = 3.1416
`⎕×` multiply with input
[Answer]
# JavaScript ES6, ~~68~~ 66 bytes
Saved 2 bytes thanks to dev-null!
```
x=>x*((a=new Date).getMonth()+1+"."+a.getDate()+(a.getYear()-100))
```
Anonymous function. Some uses:
```
f(1) == 3.1416
f(5) == 15.708
f(f(2)) == 19.73930112
```
[Answer]
# Tcl/Tk, 58 bytes
```
puts [expr {[gets stdin]*[clock f [clock se] -f %N.%d%g]}]
```
(That's a complete program. If you want to cheat and remove the explicit `puts` statement then it's only 51 bytes -- you'd have to start tclsh and type/paste the following in directly, though:)
```
expr {[gets stdin]*[clock f [clock se] -f %N.%d%g]}
```
[Answer]
# Java 114 bytes
```
public double p(double d){
return (d*Double.parseDouble(new SimpleDateFormat("MM.ddyy").format(new Date())));
}
```
[Answer]
# Racket, 112 characters
```
(define d(seconds->date(current-seconds)))(*(read)(+(date-month d)(*(date-day d).01)(*(-(date-year d)2e3)1e-4)))
```
Reads the number from input in standard reader syntax.
[Answer]
# TI-84 Basic, 30 bytes
*Works on TI-83/84 calculators; E is the scientific notation token and ~ is the negative token.*
```
Prompt D:getDate:D(Ans(2)+E~4Ans(1)-.2+.01Ans(3
```
**Test Case**
```
D=?3
9.4248
```
[Answer]
# R 48 bytes
```
d*as.double(format(Sys.Date(),format="%m.%d%y"))
```
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 17 bytes
```
Z'2$'mm.ddyy'XOU*
```
[**Try it online!**](http://matl.tryitonline.net/#code=WicyJCdtbS5kZHl5J1hPVSo&input=MTA)
```
Z' % get current date and time as float
2$'mm.ddyy'XO % format as a string with custom format
U % convert to number
* % multiply by implicit input
```
[Answer]
# TI-BASIC, ~~16~~ ~~13~~ 9 bytes
```
Xround(π,1+min(getDate
```
We round `π` to a number of decimal places equal to the minimum of `{month,day,year}`, and then multiply it by the input.
This is a function that takes input through X. Store it to one of the Y-variables, for example `Y1`, and then call like `Y1([number])` on the homescreen.
] |
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
This question does not appear to be about code golf or coding challenges within the scope defined in the [help center](https://codegolf.stackexchange.com/help/on-topic).
Closed 7 years ago.
[Improve this question](/posts/19379/edit)
Write some program (the size doesn't matter), and put a line that looks useless, but it's actually not - if it would be removed, the program would crash, or do something wrong. Feel free to mark the line that looks unused by a comment, or mention it your code description, like in example below (of course, in this example, the line is actually not needed, it's just an example).
```
int main(void) {
/* The line below is actually needed. */
2 + 2;
return 0;
}
```
As this is popularity contest, the solution with highest number of votes wins.
[Answer]
## C
```
int main(int argc, char **argv) {
switch(argc) {
case 2:
;
int allowed = 0;
case 3:
argc--;
break;
default:
argc = 3;
}
return 0;
}
```
Won't compile if we remove the single `;`.
**EDIT**:
Solution below:
>
> This happens because a `case` statement is just a label, and, as such, must be followed by a statement (which the standard refers to as a "specifier for actions to be performed", which rules out declarations). To prevent this, we prefix the declaration with a `;`, a *null statement*. Specifications for the `case` label can be found [here](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1124.pdf) at page 142 (131 in-document)
>
>
>
[Answer]
## C / C++
Just some code written in the style of introduction / tutorial...
**Tutorial nr. 2**: reading in numbers, performing mathematical operations on them, and printing the results.
```
//////////////////////////////////////////////////
///////////////////////////////////////////////////
///// //
///// T U T O R I A L //
///// //
///////////////////////////////////////////////////
#include "stdio.h"
int main()
{
///////////////////////////////////////////////
// Local variables (int means integer!!) /
int a, b, result;
///////////////////////////////////////////////
// Reading them in /
scanf("%d", &a);
scanf("%d", &b);
///////////////////////////////////////////////
// Performing an operation, e.g. addition!!! /
result = a+b;
///////////////////////////////////////////////
// Why is the next line absolutely mandatory??/
result = 42;
printf("The result is: %d", result);
}
```
Removing the line `result = 42;` which at first glance looks both superfluous, and, considering the stated objective, actually wrong, will actually cause the program to not do what the description states.
Why?
>
> Trigraphs strike again! *??/* will be replaced by the preprocessor with *\*, which will, in turn, concatenate the next line into the comment. The *result = 42;* becomes part of the comment, so it "saves" the printing line. With the *result = 42;* line removed, the *printf* line will be swallowed by the comment.
>
> Some compilers might give a warning, or trigraphs might be turned off as default and must be turned on for this example to work. Syntax highlighting might also betray it, but there are compilers and IDEs around which leave you none the wiser.
>
>
>
[Answer]
# [Whitespace](http://compsoc.dur.ac.uk/whitespace/)
Unfortunately I cannot show my program here because StackExchange strips all trailing whitespace. The same is true of pastebin.com and pastie.org, so I can’t link to it either.
Of course, the **entire program** “looks useless”, but if you remove any line, it will do something different.
[Answer]
# JavaScript:
```
for (var a = 0, b = 4; ++a < b; a++)b+-
2 + 2; // This line is needed, or it will alert twice!
alert(a);
```
>
> The reason it works is because the body of the `for` is `b+-`, not `b++` or `b--`; therefore, if you remove the required line, it will add to `b` the value of `-alert(a)`.
>
>
>
[Answer]
# C:
```
#include <stdio.h>
#include <string.h>
int main() {
int i,sum;
char s[4];
/* Add all the integers < 1000 that contain no '0' or '9' */
sum=0;
for (i=0; i<1000; i++) {
sprintf(s,"%d",i);
if (strchr(s,'0')) goto skip;
if (strchr(s,'9')) goto skip;
sum += i;
skip:
i = i; /* Don't delete this line! */
}
printf("The answer is %d\n",sum); /* <<< Should be 258948 */
return 0;
}
```
If you delete the line `i = i;` then the code won't work. This is because...
>
> ... in fact it won't even compile. According to the C standard, labels like *skip* in the above example **must** be associated with a statement. Even a single semicolon would have sufficed, but if you delete the whole line then the label has no associated statement and compilation fails. [This answer](https://stackoverflow.com/a/9730987/1679849) explains in a bit more detail.
>
>
>
[Answer]
## APL
Here's an APL function:
```
i_←{
⍺←⎕IO ⋄ ⎕IO←⍺
⍵⍴⍳×/⍵
}
```
It does the same thing as J's monadic `i.`:
```
i_ 5 5
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
```
It can take an optional left argument that gives the offset:
```
0 i_ 5 5
0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
15 16 17 18 19
20 21 22 23 24
```
The line `⍺←⎕IO ⋄ ⎕IO←⍺` looks useless ("assign `⎕IO` to `⍺`, then assign `⍺` to `⎕IO`"), but the first part only runs if no left argument is given, so in fact it does do something:
* if no `⍺` is given, set `⍺` to (global) `⎕IO`.
* set (local) `⎕IO` to `⍺`
[Answer]
## C#
```
Func<int, int> fibo;
fibo = null; //Note that this can be set to *any* Func<int, int> reference. It doesn't matter.
fibo = x => x < 1 ? 1 : fibo(x-1) + fibo(x-2);
```
The variable `fibo` must be assigned before you can use it inside a lambda, even if you’re assigning that lambda to `fibo` itself. If you remove the (seemingly useless) assignment, a compiler error will occur (“Use of unassigned local variable 'fibo'”).
[Answer]
Windows Batch:
```
echo hello
pause
echo world
```
Set the program running and modify the file to:
```
rem test01
pause
echo hello world
```
If you remove or resize the comment, it will cause havoc as the 1st instance of the program pauses and then continues interpreting from the 19th byte onwards.
[Answer]
**COBOL** (IBM Mainframe)
```
ID DIVISION.
PROGRAM-ID. USELESS.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 W-WHEN-COMPILED PIC X(8)BX(8) VALUE SPACE.
PROCEDURE DIVISION.
IF W-WHEN-COMPILED EQUAL TO SPACE
NEXT SENTENCE
END-IF
MOVE SPACE TO W-WHEN-COMPILED.
MOVE WHEN-COMPILED TO W-WHEN-COMPILED
DISPLAY W-WHEN-COMPILED " HELLO WORLD!"
GOBACK
.
```
If you run the above program (any IBM Mainframe COBOL since COBOL II (first IBM compiler to 1985 standard, probably other IBM COBOLs as well) the output is:
>
> 02/22/14 13.11.02 HELLO WORLD!
>
>
>
However, if you remove the triply-useless line "MOVE SPACE TO W-WHEN-COMPILED." (the field has an initial value of space, and has other content placed in it in the next instruction, and it is branched over anyway) the program produces no output and actually Abends (U4038) (that means it crashes) with the following message:
```
IGZ0037S The flow of control in program USELESS proceeded beyond the
last line of the program. From compile unit USELESS at entry
point USELESS at compile unit offset +000003AC at entry offset
+000003AC at address 119003AC.
```
(message code and text would vary amongst compilers, offsets depend upon actual compiler used and compile options, address depends on where program is loaded when EXECuted).
The reason is the `NEXT SENTENCE`. This is a `Secret GO TO`. The compiler hunts down the next full-stop/period in the source, and generates a branch to the following instruction. From COBOL II, the use of full-stops/periods was relaxed. A program must end with a full-stop/period. In this case, the branch is off the end of the program.
Both programs compile 100% clean (no diagnostic messages, Return Code of zero).
This behaviour is a dumb "IBM Extension" to COBOL. The 1985 Standard does not allow `NEXT SENTENCE` within `IF`/`END-IF` (`CONTINUE` is used instead, which is a no-op). IBM allowed it - causing horrible Gotchas from time-to-time.
[Answer]
**JAVASCRIPT**
```
var a = function(b) {
return b;
}
; // This must be here
(function() {
// more code
}());
```
Without the semicolon then `a` would become what ever the return value from 2nd function is - in this case it's `undefined`. Because the function originally assigned to `a` will be executed right away with the second function as the argument `b`.
[Answer]
# Java
```
package stackexchange;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class Curl
{
public void getUrl(String address)
{
try {
URL url = new URL(address);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
BufferedReader input = new BufferedReader(new InputStreamReader(conn.getInputStream()));
/* don't remove this line! */
http://codegolf.stackexchange.com
while( true ){
String line = input.readLine();
if( line==null ) break http;
System.out.println(line);
}
input.close();
} catch(IOException ex){
// ignore.
}
}
public static void main(String[] args) {
Curl curl = new Curl();
curl.getUrl("http://codegolf.stackexchange.com");
}
}
```
It is a working program that retrieves a web page from an URL. You might be surprised that the line
```
http://codegolf.stackexchange.com
```
compiles without even a warning. In fact, the program doesn't compile without it.
>
> It is actually a label, `http:`, followed by a comment, `//codegolf...`. The label applies to the while and is used in the `break http;` statement.
>
>
>
[Answer]
## Ruby
```
require 'prime'
# Given a regular expression, return the smallest prime containing it
# and the substring of the prime that matches it
def smallest_prime_matching_regexp(regexp)
match = 'this assignment is necessary even though the value is never used'
prime = Prime.find { |n| match = n.to_s[regexp] }
return prime, match
end
[ /4/, /1+2/, /[02468]{2,}/ ].each do |regexp|
prime, match = smallest_prime_matching_regexp(regexp)
puts "#{regexp.inspect}:\t#{prime} (#{match})"
end
```
A similar thing came up at work recently--a coworker actually flagged my seemingly unnecessary initialization during code review, and I was really tempted to put the explanation inside a spoiler block. So I'll do that here.
>
> The line is necessary because a variable initialized inside a block is local to that block. If we initialize it outside the block, then the value is able to escape to the method scope.
>
>
>
Output as is:
```
/4/: 41 (4)
/1+2/: 127 (12)
/[02468]{2,}/: 223 (22)
```
Output with the first line of the method removed:
>
> undefined local variable or method `match' for main:Object (NameError)
>
>
>
[Answer]
## PHP
```
<?php
$some_html_text= <<<EOT
<h1>This is a Header </h1>
<body> This is a body </body>
EOT;
//This is a comment
```
Here, `\n//This is a comment` is necessary. Without it the code won't run.
At least a `\n` char is necessary after `EOT;` to run it properly
[Answer]
```
#include <stdio.h>
#include <stdlib.h>
void strcmp_or_die(char *s, char *t) {
if(!strcmp(s, t)) {
printf("Success!\n");
} else {
int *ptr = NULL;
*ptr = 0;
}
}
int main(void) {
char blah = '\0'; //segfaults without this line
char v[2] = "ok";
strcmp_or_die(v, "ok");
}
```
>
> Simple string overflow problem.
>
>
>
[Answer]
# ~-~!
This is probably the stupidest, most obvious one here.
```
'=|hello\|:
'=~!|Useless?\|:
@'[|y|]|n|:
```
It throws an error without that second line, with it it prints `y`.
>
> the backslash isn't an escape character, hehe.
>
>
>
[Answer]
# Windows Batch
This is a batch file that prints the numbers 1 to 10 with an empty line after each:
```
@echo off
setlocal EnableDelayedExpansion
set NL=^
rem Previous two lines deliberately left blank for NL to work.
for /l %%a in (1,1,10) do (
echo %%a!NL!
)
endlocal
pause
```
This effectively makes use of a [dirty hack](https://stackoverflow.com/a/269819/1030702) to store a newline inside a variable (the use of delayed expansions gets rid of the more scary looking NL line in the linked answer). If you remove or otherwise change the two completely useless-looking blank lines above the comment, well, it won't work.
[Answer]
# troff
Troff is the most wonderful text processing system. I use it for my documents. It requires a macro system in order to be ready to be used, and the most famous is the `ms` macro package. Let's compile the following piece of code with the classical `-ms` option.
```
.\" -ms macro package
.\" the following line seems to be useless
\& \" print an invisible character
.ad c
.sp |300p \" absolute vertical positionning
.ps 36p
.ft B
My title.
.PP
This is a paragraph.
```
The third line seems to be useless, and would actually be useless without the macro package. Since it is followed two lines below by an absolute vertical positionning, it could seem meaningless to print nothing before. But without this invisible character, the vertical positionning will have no effect, though I am not absolutely sure I could explain why (see this [thread](http://osdir.com/ml/groff-gnu/2011-07/msg00023.html) if you want to have a glance at the discussion). This makes the new user crazy, but then the trick should become familiar to the more experimented user.
Just checked with my favorite version of troff which is not very known (heirloom troff), but I am pretty sure it still works the same with GNU troff.
] |
[Question]
[
This challenge is based on [this Stackoverflow question](https://stackoverflow.com/q/52202986/180719).
With a positive number as input, output it as the sum of each digit multiplied by its power-of-10 representation.
## Input
A number, as an integer, a string or a list of digits/characters.
* The number will be strictly positive.
* If you accept the number as a string or list, it will not start with a `0`.
## Output
A string representing a sum of each relevant base-10 digits, each multiplied by its respective base-10 power. A sum is represented as `a + b`. You may use up to one space around each side of the `+` sign if you want. The operands are listed in descending order.
* `0` can never be a valid operand.
* The `+` sign (surrounded or not by spaces) may not be the leading or trailing part.
## Examples
```
Input Output
12 10 + 2
or 10+2
or 10 +2
or 10+ 2
9 9
123 100 + 20 + 3
10 10
101 100 + 1
```
## Invalid outputs
```
2 1 + 1
10 10 + 0
1 0 + 1
12 + 10 + 2
12 10 + 2 +
12 2 + 10
```
This is code-golf so the shortest code in bytes wins!
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes
```
ḊƬḌQIAj”+
```
[Try it online!](https://tio.run/##y0rNyan8///hjq5jax7u6An0dMx61DBX@7/L4fZHTWsi//83NNJRsNRRMDQyBhIGIGwIAA "Jelly – Try It Online")
### How it works
```
ḊƬḌQIAj”+ Main link. Argument: A (digit array)
Ƭ Til; apply the link to the left until the results are no longer unique.
Return all unique results.
Ḋ Dequeue; discard the first element.
For input [1,2,0,4], this yields [[1,2,0,4], [2,0,4], [0,4], [4], []].
Ḍ Undecimal; convert the digit arrays into integers.
For input [1,2,0,4], this yields [1204, 204, 4, 4, 0].
Q Unique; deduplicate the resulting integers.
For input [1,2,0,4], this yields [1204, 204, 4, 0].
I Increments; yield the forward differences.
For input [1,2,0,4], this yields [-1000, -200, -4].
A Absolute value.
j”+ Join with separator '+'.
```
[Answer]
## Python 3: ~~83~~ ~~80~~ 79 Bytes
[Try It Online!](https://tio.run/##FcoxDoAgDADAr7DRioPEUXkJYXAAbWIqwZrg4tdR57t8y3bw2Jo44nwJ4FTdHhkEp1yIBTovnoLRg@6gmocwHUWRIlZl4TVCRUofzv8K/Rmz00Zja3awLw)
My first Code Golf submission.
```
t=input();x=len(t);print(*[t[i]+'0'*(x+~i)for i in range(x)if'0'<t[i]],sep='+')
```
-3 Bytes by ovs. Thank you for that useful tip :)
-4 Bytes by mypetlion. Thank you for that shortening tip :)
[Answer]
# JavaScript (ES6), 47 bytes
Takes input as an integer.
```
f=(n,m=1,k=n%m)=>n-k?f(n-k,m*10)+(k?'+'+k:''):n
```
[Try it online!](https://tio.run/##bchBDkAwEADAu39Id7XEciIpbxFUqG4F8f1yFS5zmKW7uqPf5@1M2Q9jCEYDK6dJWc2xQ91walsDj8ollKME2woppK2FwJpD7/nw65itfgIDVCBG76o@Q0X5vfynCDHc "JavaScript (Node.js) – Try It Online")
### Commented
```
f = ( // f is a recursive function taking:
n, // n = number to process
m = 1, // m = modulo (a power of 10, starting at 1)
k = n % m // k = n mod m
) => //
n - k ? // if n is not equal to k:
f(n - k, m * 10) // do a recursive call with n - k and m * 10
+ (k ? '+' + k : '') // if k is not zero: append '+' and k
: // else:
n // append n and stop recursion
```
[Answer]
# [R](https://www.r-project.org/), 55 bytes
Assuming integers are all under 1e10, which is larger than the maximum 32 bit integer anyway...
```
function(n,p=10^(9:0),x=p*n%/%p%%10)cat(x[!!x],sep='+')
```
[Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP08jT6fA1tAgTsPSykBTp8K2QCtPVV@1QFXV0EAzObFEoyJaUbEiVqc4tcBWXVtd83@ahqGRpjVIRikmT0lTWQEODA0UtBWMuMBssHB@EVBMG0NEAVMIpC9NwxK7uQqWXCBLjbHKGhqAbQURxiBlBrjcBpY0xGOGIdf//wA "R – Try It Online")
[Answer]
# [Shakespeare Programming Language](https://github.com/TryItOnline/spl), ~~807~~ ~~806~~ ~~805~~ 804 bytes
```
,.Ajax,.Ford,.Page,.Act I:.Scene I:.[Enter Ajax and Ford]Ford:Listen tothy!Scene V:.Ajax:Remember the remainder of the quotient between I twice the sum of a cat a big big cat.You be the sum of you a cat.Ford:You be the quotient between you twice the sum of a cat a big big cat.Be you nicer zero?If solet usScene V.You be I.Scene X:.Ajax:Recall.Be you worse a cat?If solet usScene D.[Exit Ford][Enter Page]Ajax:Be you nicer zero?If sospeak thy.You be the sum of a big big big big cat the cube of the sum of a cat a big cat.[Exit Page][Enter Ford]Ajax:Open heart.Remember I.You zero.Scene L:.Ajax:Am I nicer a cat?If notlet usScene C.Open heart.Ford:You be the sum of you a pig.Let usScene L.Scene C:.Ajax:Recall.Ford:You be I.Scene D:.Ford:You be the sum of you a pig.Be you nicer zero?If solet usScene X.
```
[Try it online!](https://tio.run/##jVFdS8MwFP0r8X2EqW99kbkpFAqKgkxkD1l310XbpCa3dPPP15s0nZmbuIeGJjk593zYuuy6EZ@8i@2I32uzGvFHUQCd5MjShD/noMD9vN0pBMMckAm1Yg67cEuSSYugGGrc7C56/EviGZMnqKBa0jPcADNQCalWtNNrf/DZaJSgkC0BWyCKlGErc/CXtqkcTrBcIK1LWfiPdvxVN/QkRu3oxCO9hSQCHM1w0LOm3ILHKoIa9gVG36RrZnUJyBobbA5S0pDTfO87F2U5ULTaWOhnHHPMKNmtxD7PELJrYOGJ/hBhaxAfrKI0T4TxYyOy4wF5Q8gQ/gnnznUvxgsIYrwwL@ahpvw2IAzyfbGpF@CUhQiyEMGkojp73XvnSmNsfcojxt/FHTRby4Jn0cssDJse5h1zDJXMkv@pz6h6zrvu8mp8Pf4G)
*-23 bytes if a null character may be output first*
```
,.Ajax,.Ford,.Page,.Act I:.Scene I:.[Enter Ajax and Ford]Ford:Listen tothy!Scene V:.Ajax:Remember the remainder of the quotient between I twice the sum of a cat a big big cat.You be the sum of you a cat.Ford:You be the quotient between you twice the sum of a cat a big big cat.Be you nicer zero?If solet usScene V.You be I.Scene X:.Ajax:Recall.Be you worse a cat?If solet usScene D.[Exit Ford][Enter Page]Ajax:Speak thy.You be the sum of a big big big big cat the cube of the sum of a cat a big cat.[Exit Page][Enter Ford]Ajax:Open heart.Remember me.You zero.Scene L:.Ajax:Am I nicer a cat?If notlet usScene C.Open heart.Ford:You be the sum of you a pig.Let usScene L.Scene C:.Ajax:Recall.Ford:You be I.Scene D:.Ford:You be the sum of you a pig.Be you nicer zero?If solet usScene X.
```
## Explanation
```
,.Ajax,.Ford,.Page,.Act I:.Scene I:.[Enter Ajax and Ford]
Boilerplate, introducing the characters.
Ford:Listen tothy!
Input a value to Ajax.
Scene V:.Ajax:Remember the remainder of the quotient between I twice the sum of a cat a big big cat.You be the sum of you a cat.Ford:You be the quotient between you twice the sum of a cat a big big cat.Be you nicer zero?If solet usScene V.
Push the digits of Ajax onto Ford's stack, and set Ford's value to be the number of digits in Ajax.
You be I.
Store the number of digits in the input to Ajax.
Scene X:.Ajax:Recall.Be you worse a cat?If solet usScene D.
Pop the next digit off the stack, and skip processing it if it equals 0.
[Exit Ford][Enter Page]Ajax:Be you nicer zero?If sospeak thy.You be the sum of a big big big big cat the cube of the sum of a cat a big cat.[Exit Page][Enter Ford]
All characters start out with a value of 0.
If Page is 0, that means this is the first number being processed, and we shouldn't output a plus.
In either case, store the ASCII value of "+" to Page to output next time it is needed.
Ajax:Open heart.Remember I.You zero.
Output the digit, save the remaining-digit-count for later, and store 0 to Ford for output purposes.
Scene L:.Ajax:Am I nicer a cat?If notlet usScene C.Open heart.Ford:You be the sum of you a pig.Let usScene L.
Output one fewer 0 than the number of remaining digits to process.
Scene C:.Ajax:Recall.Ford:You be I.
Store the remaining-digit-count back into Ajax.
Scene D:.Ford:You be the sum of you a pig.Be you nicer zero?If solet usScene X.
Subtract 1 from the remaining-digit-count, and loop back until there are no more digits left to process.
```
[Answer]
# [Python 2](https://docs.python.org/2/), 64 bytes
```
f=lambda s='',*x:s and(s>'0')*(s+'0'*len(x)+(f(*x)and'+'))+f(*x)
```
[Try it online!](https://tio.run/##HYtBDoAgDAS/wq0teEC8meBfMEo0QSTCAV9fG087k8mWtx13dszRp3CtW1DVAwy6z1WFvGFdwAJprEZWpz1jJ4MRdSfJYIDI/MblOXNTwjBO1smJPw "Python 2 – Try It Online")
---
# [Python 2](https://docs.python.org/2/), 66 bytes
```
f=lambda n,m=1:n>10and f(n/10,m*10)+(n%10>0)*('+'+`n%10*m`)or`n*m`
```
[Try it online!](https://tio.run/##FYtLCoAgFACv0ib8Qu/ZLtCzaIgU5FPETac3Ww0DM/XtVyEzRrJPyGcMC@ls8SCHECguidOGoLNEEIrTiuBASM4UU/43mb0ozdPkqO2mPg@zz3h8 "Python 2 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~12~~ 11 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
J’⁵*Ṛ×ḟ0j”+
```
A full program accepting the number as a list of digits (in Python format) which prints the result.
**[Try it online!](https://tio.run/##y0rNyan8/9/rUcPMR41btR7unHV4@sMd8w2yHjXM1f7//3@0oY6BjhEQG@sYxAIA "Jelly – Try It Online")**
### How?
```
J’⁵*Ṛ×ḟ0j”+ - Main Link: list of digits e.g. [1,0,2,0,3,0]
J - range of length [1,2,3,4,5,6]
’ - decrement (vectorises) [0,1,2,3,4,5]
⁵ - literal 10 10
* - exponentiate (vectorises) [1,10,100,1000,10000,100000]
Ṛ - reverse [100000,10000,1000,100,10,1]
× - multiply (vectorises) [100000,0,2000,0,30,0]
ḟ0 - filter discard zeros [100000,2000,30]
j”+ - join with '+' [100000,'+',2000,'+',30]
- implicit (smashing) print "100000+2000+30"
```
---
Previous @12 bytes:
```
Ḣ;0€ƊÐƤẸƇj”+
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 10 bytes
Straight forward implementation.
Input as list of digits.
```
āR<°*0K'+ý
```
[Try it online!](https://tio.run/##yy9OTMpM/f//SGOQzaENWgbe6tqH9/7/H22oY6BjGAsA "05AB1E – Try It Online")
**Explanation**
```
* # multiply each digits in the input with
āR<° # 10^(len(input)-1-index)
0K # remove results that are zero
'+ý # merge on "+"
```
[Answer]
## Haskell, ~~60~~ 54 bytes
Edit: -6 bytes thanks to Delfad0r.
```
tail.(>>=('+':)).filter(>="1").scanr((.('0'<$)).(:))""
```
Takes the input number as a string.
[Try it online!](https://tio.run/##HYvBCgIhFEV/RR6BTypxqNlE@gW1alkRj2FsJEdE7fczZzaHA/fcifJn9L5a/aiFnJdojEa@5SchpHW@jAmNhg6EzAOFhCiRK37etBlbA1BncoFpNlO8vhjGb7mVdAnSCnZvvx10akG/2qrqsPDYw7P@Buvpnet@iPEP "Haskell – Try It Online")
```
scanr( )"" -- starting with the empty string fold from the right and
-- collect the intermediate results in a list
(.('0'<$)).(:) -- non pointfree: \d s -> d : ('0'<$s)
-- i.e. take the next digit 'd' and append the current result
-- from the scanr where each char is replaced by 0
--
-- e.g. "103" -> ["100","00","3"]
--
f ilter(>="1") -- keep only elements that have not a 0 as the first char
(>>=('+':)) -- prepend a + to each element and flatten into
-- a single list
tail -- drop the first char, ie.e the leading +
```
[Answer]
# [Python 2](https://docs.python.org/2/), 64 bytes
```
lambda n:'+'.join(`b`+~e*'0'for e,b in enumerate(n,-len(n))if b)
```
An unnamed function which takes a list of digits, `n`, and returns a string.
**[Try it online!](https://tio.run/##dY67DsIwDEV3vsJbEuqiPiYilR8pSGmEI4JatyphYOHXA@mE1OLBko/O1fX0CreRq@iac@y7wV47YC0ycbiPnqWxJnvTXhTCjTMQWvAMxM@B5i6QZMx7YslKeQdWxSQFeoRkybZEqC64g99pjyuSNIR6ixebEKH8w6tl1@ug0ss5zZ4DmPSiaUutv6Ug8pNAcDJBFT8 "Python 2 – Try It Online")**
`enumerate(n)` would yield tuples of `index, item` across `n` with an index starting at `0`.
However `enumerate` also takes an optional starting index as its second argument, by setting this to `-len(n)` we get indices (`e`s) of `-len(n)`, `-len(n)+1`, ..., `-1`.
This means the number of required trailing zeros for any item (`b`) is `-1-e`, which is `~e` so `~e*'0'` gets the required trailing zeros.
``b`` gets a string representation of the integer digit `b` and `+` concatenates this with those zeros.
`if b` filters out the entries with `b==0`.
`'+'.join(...)` then joins the resulting strings up with `+` characters.
[Answer]
# Python 2, ~~82~~ ~~73~~ 71 bytes
*-9 bytes thanks to @ovs*
*-2 bytes thanks to @JonathanAllan*
```
lambda n:'+'.join(v+'0'*(len(`n`)-i)for i,v in enumerate(`n`,1)if'0'<v)
```
[Try it Online](https://tio.run/##FcpLCoAgEADQq7hzph9pu6i7ZKQ0YWOICZ3eav3e9aQ9sC7Fzd6c62YEj7KW3RGIIdeylxV4y7Dwgi2hC1FQkwWxsHyfNppkf2sUkvvylLFckTiBA6WHXiGWFw)
[Answer]
# [Haskell](https://www.haskell.org/), ~~56~~ ~~55~~ 52 bytes
-4 byte thanks to [nimi](https://codegolf.stackexchange.com/users/34531/nimi).
```
tail.f
f('0':x)=f x
f(d:x)='+':d:('0'<$x)++f x
f x=x
```
[Try it online!](https://tio.run/##y0gszk7NyfmfbhvzvyQxM0cvjStNQ91A3apC0zZNoQLISQEx1bXVrVKsQBI2KhWa2tpgKYUK24r/uYmZeQq2CrmJBb7xChoFpSXBJUU@eXrpmgrRSoZKOkqGBiDCFMwCMw2MQaSJqVLs/3/JaTmJ6cX/dZMLCgA "Haskell – Try It Online")
---
**explanation**
```
g :: String -> String
-- drop the first char (the leading +) from f
g = tail.f
f :: String -> String
-- if the first digit is 0, continue with the rest of the number
f ( '0' :rest) = f rest
-- otherwise, add a +, the digit and as many 0s as there are digit in the rest.
f (digit:rest) = '+' : digit : ('0' <$ rest) ++ f rest
-- if there is no digit left, return the empty string
f "" = ""
```
[Try it online!](https://tio.run/##dZBBboQwDEX3nOILjQQjYETbHer0BN31BOmQgNWQoCQIzempQ@hoNl1Ecuzn/22Pwv9IrbdtQNfhKzgyA5qPI8qypkHv7IwwSihyPuA2Cocy/rUUfcSrM5SzE1Q24IogSF9Ulql/BUk9yfU0UAB5tDVu1gQyi8RKYdwZJxmxiTfL9C0d65Yo2gJdrJ3ZUO3UrmyZcyt5WUP0PQSqem9NJsJwymMS5o7WxzDiEsL9EWQerpdotGcfRkXFrgfZoYxDvJ@QqlX1PEfakGV5L2OPFi1VqJkJi0s2cprDHT4dRiHP2SPPt0nwGFfMS@CbfRqcMPDzo13x8tq@bb8 "Haskell – Try It Online")
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 38 bytes
```
{join '+',grep +*,($_ Z~[R,] 0 Xx^$_)}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwvzorPzNPQV1bXSe9KLVAQVtLR0MlXiGqLjpIJ1bBQCGiIk4lXrP2v4ahkY6ljqGRsY6hARAZ6hhq2tnpqVXrJefnJumppekVJ1bWWv8HAA "Perl 6 – Try It Online")
Anonymous code block that takes a list of digits and returns a string.
### Explanation:
```
{ } # Anonymous code block
$_ Z~ # Zip concatenate the list of digits with
[R,] 0 Xx^$_ # The correct number of 0s
grep +*,( ) # Filter out all all the 0 values
join '+', # And join with '+'s
```
[Answer]
# APL(Dyalog), ~~46~~ ~~41~~ 40 bytes
```
{¯1↓∊{'0'=⊃⍵:⍬⋄⍵}¨⍵,¨('0'⍴⍨¨⌽⍳≢⍵),¨'+'}
```
*-5 bytes thanks to @dzaima*
Anonymous prefix function. Takes input as a string. [TIO](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/9OAZPWh9YaP2iY/6uiqVjdQt33U1fyod6vVo941j7pbgKzaQyuApM6hFRpA2Ue9Wx71rgCK9Ox91Lv5UecioJQmUE5dW732//80BXVDAwMjAwN1LjDTEEIbGUNpEKWjbgmVVQcA)
(This is my first time using APL on PPCG, probably golfable. Also, curse you, zeroes!)
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 19 bytes
```
|'+L$`[1-9]
$&$.'*0
```
[Try it online!](https://tio.run/##K0otycxLNPyvquGe8L9GXdtHJSHaUNcylktFTUVPXcvg/39DIy5LLkMjYy5DAyAyBAA "Retina – Try It Online") Link includes test cases. Explanation:
```
L`[1-9]
```
List all non-zero digits
```
$
$&$.'*0
```
For each digit, append as many zeros as there were trailing digits.
```
|'+
```
Separate each result with `+`s instead of the default newline.
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 21 bytes
```
M&!`[1-9].*
\B.
0
¶
+
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7w31dNMSHaUNcyVk@LK8ZJj8uA69A2Lu3//w2NuCy5DI2MuQwNgMgQAA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
M&!`[1-9].*
```
List all suffixes of the input that begin with non-zero digits.
```
\B.
0
```
Replace all trailing digits with zeros.
```
¶
+
```
Join the results with `+`s.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 71 69 bytes
Each step of the recursive function subtracts the part that it will print and passes the rest of the number on.
Thanks to ceilingcat for the suggestion.
```
g(v,c,w){v&&printf("+%d"+!g(v-w,c*10)+!w*3,w=v%c);w=v;}f(v){g(v,10);}
```
[Try it online!](https://tio.run/##VY7NDoIwEITvPMWKwbS0GvDnYCq@iHrARWCNgkEsB8Kz11b04B52JvPtJIvzAtFMqcLbK7vA7tlmVC/KvfcX3ehsM1MwLVF2vNez2aOhqs2ZL4LMFxNL5p3EMI64mHThSnaJDpArK2rImea961qqBmN7cE@pYs6kTYESy7SBMLRec@g9gLxuPpSSWAHt3JFVIUYK4Ng1SduamCsd6MTVB/y@OlZBBgn4Eq5fkrPRDd5gTLxcrTcmjqLN1u1xzPYN "C (gcc) – Try It Online")
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), ~~35~~ 32 bytes
```
l⟧₅;?z{tℕ₁I&h;10↔^;I×ṫ}ˢ;"+"zckc
```
-3 bytes cause 0 isn't a valid input
[Try it online!](https://tio.run/##AUEAvv9icmFjaHlsb2cy//9s4p@n4oKFOz96e3TihJXigoFJJmg7MTDihpReO0nDl@G5q33LojsiKyJ6Y2tj//8xMDX/Wg "Brachylog – Try It Online") or [testsuite](https://tio.run/##SypKTM6ozMlPN/r/qGO5Xrq1fVV1SblaRrlayaO2DY@amh7u6qx9uHUCUPJ/zqP5yx81tYKVPGqZ@qip0VMtw9rQ4FHblDhrz8PTH@5cXXt6kbWStlJVcnby///RhgamOgrGOgqGRsYmOgqWlkCWgZGBcex/JU5dXTtOAA "Brachylog – Test suite")
# Explanation
```
# implicit input eg 105
l # length of input 3
⟧₅ # descending range ]n,0] [2, 1, 0]
;? # pair with input [[2, 1, 0], [105]]
z # zip (considers numbers as array of digits)
# [[2, 1], [1, 0], [0, 5]]
{ }ˢ # select (map and filter) [2, 1] | [1, 0] | [0, 5]
t # tail (last element) 1 | 0 | 5
ℕ₁ # is at least 1 1 | fail | 5
I # store in I
&h # head of input 2 | | 0
;10↔ # pair with 10 & reverse [10, 2] | | [10, 0]
^ # power 100 | | 1
;I # pair with I [100, 1]| | [1, 5]
× # multiply 100 | | 5
ṫ # to string "100" | | "5"
;"+" # pair with "+" [["100", "5"], "+"]
z # zip (cycles shorter) [["100", "+"], ["5", "+"]]
c # concat (flattens) ["100", "+", "5", "+"]
k # knife (remove last) ["100", "+", "5"]
c # concat "100+5"
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog) v2, 15 bytes
```
~+bᵛ⁰↔;"+"zckwᵐ
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/v0476eHW2Y8aNzxqm2KtpK1UlZxd/nDrhP//DQ1MAA "Brachylog – Try It Online")
Very, very inefficient.
Somehow, this manages to use only 6 bytes on what is in most languages the hard part (splitting the number into the form *a*10*b* where *a* is a single digit, in descending order), and a whole 9 bytes for the "join with `+`" (which is a builtin in most golfing languages, but not Brachylog).
Unlike most of my Brachylog submissions (which are functions), this one's a full program, taking input from standard input and producing output on standard output.
## Explanation
```
~+bᵛ⁰↔;"+"zckwᵐ
~+ Find an additive partition of the input number
ᵛ such that each component of the partition,
b when the first digit is removed
⁰ is equal to 0;
↔ reverse it,
;"+"z pair every element with "+",
c flatten the resulting list one level,
k remove the last element (i.e. the final "+"),
w and print
ᵐ each remaining element.
```
(The reason `wᵐ` is used rather than the more normal `c` is that we're dealing with a heterogenous list – it contains both numbers and strings – and rather than allowing these to mix, it's simplest to just print them all individually.)
The algorithm here brute-forces over all additive partitions of the input until it finds a suitable one (!). Brachylog favours partitioning into fewer possibilities, and with the possibilities sorted in ascending order, so the first solution it will find is the reverse of the solution that the question is asking for. So we just have to reverse it to get the solution we want.
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 17 bytes
```
FI(REE,#a)*^aJ:'+
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgwYKlpSVpuhYb3Tw1glxddZQTNbXiEr2s1LUh4lDpZdGGBkbGsVAeAA)
### Explanation
Different approach from [my earlier 21-byte answer](https://codegolf.stackexchange.com/a/172004/16766) in Pip Classic:
```
FI(REE,#a)*^aJ:'+
,#a Range(length(input number))
EE 10 to the power of each element of the range
R Reversed
( )* Multiply each element of that list by
^a The corresponding element in split(input number)
FI Filter, removing zeros
J:'+ Join on the + character
```
(A similar approach would be 19 bytes in Pip Classic: `_FI(^a).RV0X,#aJ:'+`.)
[Answer]
# [Clean](https://github.com/Ourous/curated-clean-linux), 73 bytes
```
import StdEnv,Text
$n=join"+"[rpad{c}(size n-p)'0'\\c<-:n&p<-[0..]|c>'0']
```
[Try it online!](https://tio.run/##S85JTcz7n5ufUpqTqpCbmJn3PzO3IL@oRCG4JMU1r0wnJLWihEslzzYrPzNPSVspuqggMaU6uVajOLMqVSFPt0BT3UA9JibZRtcqT63ARjfaQE8vtibZDiga@z@4JBFokK2CioKSoYGh0v9/yWk5ienF/3U9ff67VOYl5mYmQzgBOYklaflFuQA "Clean – Try It Online")
Defines the function `$ :: String -> String` taking a string and returning a string.
[Answer]
# [Canvas](https://github.com/dzaima/Canvas), ~~14~~ 13 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md)
```
A⁸L²-^×?²}]+*
```
[Try it here!](https://dzaima.github.io/Canvas/?u=JXVGRjIxJXUyMDc4JXVGRjJDJUIyJXVGRjBEJXVGRjNFJUQ3JXVGRjFGJUIyJXVGRjVEJXVGRjNEKyV1RkYwQQ__,i=JTVCMSUyQzIlMkMzJTJDMCUyQzklMkMwJTVE,v=7)
[Answer]
# [Attache](https://github.com/ConorOBrien-Foxx/Attache), 37 bytes
```
Join&"+"@{Id\`-&>Pairs[_'0]}@Suffixes
```
[Try it online!](https://tio.run/##SywpSUzOSP2fpmBl@98rPzNPTUlbyaHaMyUmQVfNLiAxs6g4Ol7dILbWIbg0LS2zIrX4v19qakpxtEpBQXJ6LFdAUWZeSUhqcYlzYnFqcXSajkI0lwIQGBrpKFjqACljIGEAwoZcsbH/AQ "Attache – Try It Online")
Pointfree version (41 bytes): `Join&"+"##`\&:Id##`-&>Pairs@`'&0@Suffixes`
## Explanation
```
Join&"+"@{Id\`-&>Pairs[_'0]}@Suffixes input e.g.: 1203
Suffixes take the suffixes of the input digit
e.g.: [1203, 203, 3, 3]
{ }@ apply the inner lambda to the suffixes:
_'0 append `0`
e.g.: [1203, 203, 3, 3, 0]
Pairs[ ] generate the pairs of integers of the above
e.g.: [[1203, 203], [203, 3], [3, 3], [3, 0]]
`-&> subtraction over each pair
e.g.: [1000, 200, 0, 3]
Id\ keep only truthy (nonzero) elements
e.g.: [1000, 200, 3]
Join&"+"@ join the result by `+`
e.g.: "1000+200+3"
```
[Answer]
# C (gcc), 87 bytes
```
j;k;f(x){for(j=1;j<x;j*=10);for(;k=x*10/j*j/10%j,j/=10;)k&&printf("%d%c",k,j-1?43:10);}
```
[Try it online!](https://tio.run/##NYtBCsMgFETX7SlCIEHFoD9m0/5Kz1IMFr80KaEUIeTs1kC6mjdvGNc9ncuZMKJnia9@XhhZQLolJGFBc9wVRpsEaEWCFOiGJKmyIY9t@17C9PGsbsbG1TJK6uA@mOv@3HKZqtcjTOw7h5FX6/nk2WB033PcEY68HFXD35sCW/4B "C (gcc) – Try It Online")
[Answer]
# Powershell, ~~55~~ 52 bytes
```
$i=$args.Count;($args|%{$_+'0'*--$i}|?{+$_})-join'+'
```
Script expects an array of strings, each string contains one digit. Test script:
```
$f = {
$i=$args.Count;($args|%{$_+'0'*--$i}|?{+$_})-join'+'
}
@(
,('10','1','0')
,('10+2','1','2')
,('9','9')
,('100+20+3','1','2','3')
,('100+1','1','0','1')
) | % {
$e, $a = $_
$r = &$f @a
"$($e-eq$r): $(-join$a)=$r"
}
```
Output:
```
True: 10=10
True: 12=10+2
True: 9=9
True: 123=100+20+3
True: 101=100+1
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 13 bytes
Takes input as an array of digits.
```
í*¡ApYÃw)f q+
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=7SqhQXBZw3cpZiBxKw==&input=WzEsMCwxXQ==)
---
## Explanation
```
í :Interleave
¡ : Map input
A : 10
p : To the power of
Y : The current 0-based index
à : End map
w : Reverse
* : Reduce each pair by multiplication
) :End interleaving
f :Filter (remove 0s)
q+ :Join with "+"
```
---
[Answer]
# Java 10, ~~82~~ 78 bytes
```
n->f(n,1)Object f(int n,int m){return m<n?f(n-n%m,m*10)+(n%m>0?"+"+n%m:""):n;}
```
Port of [*Arnauld*'s JavaScript (ES6) answer](https://codegolf.stackexchange.com/a/171892/52210).
-2 bytes thanks to *@ceilingcat*.
-2 bytes thanks to *Arnauld*.
[Try it online.](https://tio.run/##VZBNboMwEIX3OcUIqZJdfgRJpKihTU7QdJFl1YVDTGWKJwiGVFXE2emYIAU243l@T@PPU6irCovzT5@VqmngXRm8LQAMkq5zlWk4OAnwcSp0RpAJdgBlypfdgssBEN6gx3CXCwwSmY7B/B4MXLXyVmtqawT7invOhfhkA/ucxNIX3O7ived7Pndbz5NbTLs@dbOr9lSaDBpSxMf1Ys5gmU8cqTb4/fkFSt7hHDVY5kD9OwgxAAKQbki8TAW/OVXLuZfMzdXcXa6nehOv4vVjEVPKwXc/N1i1NEIe/xrSNrq0FFXMTyWKB26EkVutS48ju/4f)
**Explanation:**
```
n-> // Method with int parameter & Object return-type
f(n,1) // Call the recursive method with `n` and 1
Object f(int n,int m){ // Recursive method with 2 int parameters & Object return-type
return m<n? // If `m` is smaller than `n`:
f(n-n%m,m*10) // Do a recursive call with `n-n%m` and `m` multiplied by 10
+(n%m>0? // And if `n` is not divisible by `m`:
"+" // Append a "+"
+n%m // As well as `n%m`
: // Else:
"") // Append nothing more
: // Else:
n;} // Simply return the input `n`
```
[Answer]
# [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), ~~134~~ ~~133~~ 129 bytes
```
N =INPUT
S =SIZE(N) - 1
V N LEN(X) LEN(1) . V :F(O)
O =GT(V) O V DUPL(0,S - X) '+'
X =X + 1 :(V)
O O ARB . OUTPUT RPOS(1)
END
```
[Try it online!](https://tio.run/##HY09C8IwFEXn937F3ZpQlQacChmUVimUJDQfhI7OYgf/P/HhdId77rnfz/E63tfWyMEuLuTEFGHjss/KaZxhuEi1zk5V/Q@jcUGh8aG8ZvKwz6SKhkfBlMOqhlOUmcBd3zFV2IoehkaB2At/2@4i8DnJF7bgoxh5dlNrZjA/ "SNOBOL4 (CSNOBOL4) – Try It Online")
Saved a whole byte by doing string processing rather than arithmetic!
[Answer]
# [sed -E](http://www.grymoire.com/Unix/Sed.html#uh-4a), ~~109~~ ~~99~~ ~~97~~ ~~75~~ 74 bytes
```
h;s:.:0:g;G
:l;s:.(.*)\n(.)(.*)\+?(.*):\1\n\3+\4\2\1:;tl
s:\+0+::g;s:..?::
```
Each line of the input is considered a separate number. [Try it online](https://tio.run/##PYs7DoMwEET7PQnEwlob8hsXKB@TS2yZiERCJpLJ9bMBiswU86Z4@XGv@vRRfYYMC0YfboRhOYXdlJIKW65g2mUgTpLURhrx4hCmgTLEsMEszo5tAVXn62a729ORPLsDsfuXzqfrhbsuRuI13/E9vcaUtYo/).
### Explanation:
```
h; | copy the original string to the temporary buffer
s:.:0:g; | substitute all digits with zeroes
G | append the original string to the substituted one
|
:l; | main loop start
s:.(.*)\n(.)(.*)\+?(.*):\1\n\3+\4\2\1:; | cut the next digit from the number, append with zeroes and add to the back
tl | loop if the substitution hasn`t converged yet
|
s:\+0+::g; | remove all zero terms
s:..?:: | remove \n and the first +, if any
```
…can be golfed futher, I presume.
[Answer]
# Brainfuck, 147 bytes
```
>>+[[<]>+[>],]-[>+>+<<-----]>--->--------<<<[<]>---[[<+<+>>-]<[>+<-]>>.<<<[>>[>]>.<<[<]<-]>>[>]>>.<<<[<]>>>[<[-]>[<+>-]>]>[<+>-]>[<+>-]<<<<[<]>-]>.
```
[Try it online!](https://fatiherikli.github.io/brainfuck-visualizer/#Pj4rW1s8XT4rWz5dLF0tWz4rPis8PC0tLS0tXT4tLS0+LS0tLS0tLS08PDxbPF0+LS0tW1s8KzwrPj4tXTxbPis8LV0+Pi48PDxbPj5bPl0+Ljw8WzxdPC1dPj5bPl0+Pi48PDxbPF0+Pj5bPFstXT5bPCs+LV0+XT5bPCs+LV0+WzwrPi1dPDw8PFs8XT4tXT4uCiE=)
(You will have to tick the box marked "!" and type your input after the "!" on the second line of the code otherwise it will continue asking for inputs forever.)
Its probably not going to be the shortest answer or golfed to the shortest it could be but it was pretty fun to try and do this in Brainfuck so I might as well post it.
As @JoKing pointed out, this program does not remove 0's. I will try and fix this but it might be quite hard.
**Explanation:**
```
>>+[[<]>+[>],] Takes inputs and records the amount of them
-[>+>+<<-----]>--->-------- Sets the next 2 cells to 48 (0) and 43 (plus)
<<<[<]>--- Returns to the start and corrects the number of inputs
Loop
[[<+<+>>-]<[>+<-]>>. Prints the first number
<<<[>>[>]>.<<[<]<-] Prints the correct number of 0's
>>[>]>>. Prints plus
<<<[<]> Returns to the first cell
>>[<[-]>[<+>-]>]>[<+>-]>[<+>-]<<<<[<]>-] Removes the first number and shifts everything up by one to make the second number the first
Loops until on last number
>. Prints last number
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 20 bytes
```
{⍵'+'⍺}/0~⍨(10×⊢)\∘⌽
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24TqR71b1bXVH/XuqtU3qHvUu0LD0ODw9EddizRjHnXMeNSzF6hMwVDBAAiNQCQXhGcIpo0UjCE0kNSxhEgBAA "APL (Dyalog Unicode) – Try It Online")
Takes input as a vector of digits. Outputs with a space before and after each `+`, and includes a variable amount of leading spaces.
This is a train. It is divided into the following.
```
┌───┴───┐
/ ┌─┼──┐
┌─┘ 0 ⍨ ∘
{⍵'+'⍺} ┌─┘ ┌┴┐
~ \ ⌽
┌─┘
┌──┼─┐
10 × ⊢
```
The first function is `⌽`, this reverses the array, so `1 0 2` becomes `2 0 1`.
Then we come into `(10×⊢)\`, which is applied to the reversed array. This part is inspired by ngn's [answer](https://codegolf.stackexchange.com/a/150153/41805) to the Boustrophedonise challenge. Borrowing ngn's explanation, given a vector of digits `A B C ...`, applying `(10×⊢)\` on this vector gives the following.
```
A (A (10×⊢) B) (A (10×⊢) (B (10×⊢) C)) ...
A ((10×⊢) B) ((10×⊢) (10×C)) ...
A (10×B) (10×10×C) ...
```
On `2 0 1`, `(10×⊢)\` gives `2 0 100`.
Next comes `0~⍨`. This removes all `0`s from the array, giving `2 100`.
Finally comes the `+`s. `{⍵'+'⍺}/` is a reduction that starts from the right that concatenates the left arg with a `+`, followed by the right arg. Effectively, this reverses the array while inserting `+`s. This gives `100 '+' 2`, which is displayed as `100 + 2`.
] |
[Question]
[
Inspired by [Does the start equal the end](https://codegolf.stackexchange.com/questions/120434/does-the-start-equal-the-end)
Given a string `s` and an integer `n`, output a truthy/falsey as to whether the `n`th char in `s` equals the `n`th from the end char in `s`.
# Input
A non-empty string and an integer. You can use 0-based indexing or 1-based indexing. The integer is guaranteed to be valid based on the string. For example, if the string is "supercalifragalistic123", the integer can be from 1 to 23 for 1-based indexing, and 0 to 22 for 0-based indexing. Please note that `n` can be larger than half the length of `s`.
Input is limited to printable ASCII.
# Output
A truthy/falsey value based on whether the `n`th value in `s` equals the `n`th from last value in `s`.
Please note that the last char is in position 0 for 0-based indexing and position 1 for 1-based indexing. Think of it as comparing the string to its reverse.
# Test Cases
0-indexed
```
"1", 0 Truthy 1 == 1
"abc", 1 Truthy b == b
"aaaaaaa", 3 Truthy a == a
"[][]", 1 Falsey ] != [
"[][]", 0 Falsey [ != ]
"ppqqpq", 2 Truthy q == q
"ababab", 5 Falsey a != b
"12345", 0 Falsey 1 != 5
"letter", 1 Truthy e == e
"zxywv", 3 Falsey w != x
```
1-indexed
```
"1", 1 Truthy 1 == 1
"abc", 2 Truthy b == b
"aaaaaaa", 4 Truthy a == a
"[][]", 2 Falsey ] != [
"[][]", 1 Falsey [ != ]
"ppqqpq", 3 Truthy q == q
"ababab", 6 Falsey a != b
"12345", 1 Falsey 1 != 5
"letter", 2 Truthy e == e
"zxywv", 4 Falsey w != x
```
[Answer]
# JavaScript (ES6), 26 bytes
```
s=>n=>s[n]==s.substr(~n,1)
```
Alternatively:
```
s=>n=>s[n]==s.slice(~n)[0]
```
This one almost works, but fails when `n == 0` (because `s.slice(-1,0) == ""`):
```
s=>n=>s[n]==s.slice(~n,-n)
```
Another 26-byte solution that [@RickHitchcock](https://codegolf.stackexchange.com/users/42260/rick-hitchcock) pointed out:
```
s=>n=>s[n]==s[s.length+~n]
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~5~~ 4 bytes
```
=UƓị
```
[Try it online!](https://tio.run/nexus/jelly#@28bemzyw93d//8b/1cqKCgsLChUAgA)
There should be no shorter answers in Jelly. An program would need comparison, reversal/negation, an index call, and a byte for control flow (`Ɠ` in this case), which adds up to four bytes.
**How it works**
```
=UƓị
- (implicit) input string
= - equals (vectorizing by characters because a string is a charlist)
U - the reversed string
ị - get the element at the index of:
Ɠ - the input index
```
*-1 byte thanks to @ais523, using `Ɠ`*
[Answer]
# [MATL](https://github.com/lmendo/MATL), 5 bytes
```
tP=w)
```
[Try it online!](https://tio.run/nexus/matl#@18SYFuu@f@/ukdqTmq@OpcRAA "MATL – TIO Nexus")
Explanation:
```
t % Duplicate the input
Stack:
['ppqqpq' 'ppqqpq']
P % Reverse the top element of the stack
Stack:
['ppqqpq' 'qpqqpp']
= % Equals. Push an array of the indices that are equal
Stack:
[[0 1 1 1 1 0]]
w % Swap the top two elements
Stack:
[[0 1 1 1 1 0], 3]
) % Grab the a'th element of b
```
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 22 bytes
```
@(s,n)s(n)==s(end-n+1)
```
[Try it online!](https://tio.run/##Xc/LDoIwEAXQvV8xkpjQiCTl4a6JK7/AXdNFwRIXplJAHv587QAKYbrsyb0zr7yRrbIFC8PQXvw60KT2NWGs9pW@n/SRElv4HvUCoASmOQDcqnfzGIACY0B3DsgsdyQiG5AhyEYwjUMJWQGJQCLggot/hANX@azVAAL2DPgK0A3gCASCsjSmNI7EBMHcYLDBTDvic/9nsg6QGDDuSKM4SX8VC6AIUgRP1TSqmrdcjlBYoRB8@qFrpxvXCR0m9PYL "Octave – Try It Online")
Or the same bytecount:
```
@(s,n)s(n)==flip(s)(n)
```
[Try it online!](https://tio.run/##Xc/LCoMwEAXQfb9iKhQMiBAf3QW66hd0J1lEibQgbWKsj/68zRhbg8kmkMO9M6@qE72caxbH8XwJTfQkJnwSxurmoUJD7Huuw4AGEVAC7pwAbu27u09AgTGgBwtEWVmSkB0oEZQLcMeijHhAIBAICl7wf4QFV9EYOQGHI4PCA3QHCgQcgVJaK21JShCsDRobtJsRr/0/Ez9AYMAyI03SLP9VbIAiyBE0sutku065LSGxQiL4jNPQux39hAETxvkL)
**Explanation:**
It's quite straight forward. The first one takes a string `s` and an integer `n` as inputs and checks the n'th element `s(n)` against the "last-n+1" element for equality.
The second one checks the n'th element `s(n)` against the n'th element of `s` reversed.
[Answer]
# [Python](https://docs.python.org/), ~~24~~ 22 bytes
*-2 bytes thanks to Adnan.*
```
lambda s,n:s[n]==s[~n]
```
[Try it online!](https://tio.run/nexus/python2#S7ON@Z@TmJuUkqhQrJNnVRydF2trWxxdlxf7v6AoM69EIU1D3VBdR8FAkwvOT0xKBooYIotAAFDUGEk0OjY6Fk0hVAjZtIKCwsKCQqCgEYoVIAgUNEUSNDQyNjFF052TWlKSWoRmS1VFZXkZ2DH/AQ "Python 2 – TIO Nexus")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~7~~ 5 bytes
-2 bytes thanks to [Adnan](https://codegolf.stackexchange.com/users/34388/adnan)
```
ÂøsèË
```
[Try it online!](https://tio.run/nexus/05ab1e#@3@46fCO4sMrDnf//19QUFhYUMhlBAA "05AB1E – TIO Nexus") or [Try all tests](https://tio.run/nexus/05ab1e#K6tMKP5/uOnwjuLDKw53/69UOrzfSsklvdje0KxY1@3wBvtanf/R0eqG6joGsTrR6olJyeo6hmAWBKjrGIN40bHRsVAJCBOsuqCgsLCgUF3HCKIVBNV1TEEcQyNjE1OoqpzUkpLUIqjuqorK8jKQobEA "05AB1E – TIO Nexus")
```
 # Add a reversed copy on top of the original string
ø # Zip
sè # Extract the nth element
Ë # Check if they are equal
```
[Try it online!](https://tio.run/nexus/05ab1e#@3@46fCO4sMrDnf//19QUFhYUMhlBAA "05AB1E – TIO Nexus")
[Answer]
## Haskell, 22 bytes
```
s#n=s!!n==reverse s!!n
```
0-basd. Usage example: `"letter" # 1` -> `True`.
[Try it online!](https://tio.run/##y0gszk7Nyfn/v1g5z7ZYUTHP1rYotSy1qDhVAcT7n5uYmadgq1BQlJlXoqCioJSTWlKSWqSkoKxg@B8A "Haskell – Try It Online")
[Answer]
# [Alice](https://github.com/m-ender/alice), 24 bytes
```
/t.~e?/-mom
\I!RtI&1n;@/
```
[Try it online!](https://tio.run/##S8zJTE79/1@/RK8u1V5fNzc/lyvGUzGoxFPNMM/aQf///4KCwsKCQi5jAA "Alice – Try It Online")
Input consists of the string on one line, and the number on the second line. Output is `Jabberwocky` if the characters are the same, and nothing otherwise.
### Explanation
This program is mostly in ordinal mode, with one command in cardinal mode. Linearized, the program is as follows:
```
I.ReI&1m;mt!~t?&-no
I % Input first line
% STACK: ["ppqqpq"]
. % Duplicate top of stack
% STACK: ["ppqqpq", "ppqqpq"]
R % Reverse top of stack
% STACK: ["ppqqpq", "qpqqpp"]
e % Push empty string
% STACK: ["ppqqpq", "qpqqpp", ""]
I % Input next line
% STACK: ["ppqqpq", "qpqqpp", "", "3"]
& % (cardinal mode) Pop stack and repeat next command that many times
% STACK: ["ppqqpq", "qpqqpp", ""], ITERATOR: [3]
1 % Append "1" to top of stack
% STACK: ["ppqqpq", "qpqqpp", "111"]
m % Truncate so the top two strings on the stack have the same length
% STACK: ["ppqqpq", "qpq", "111"]
; % Discard top of stack
% STACK: ["ppqqpq", "qpq"]
m % Truncate again
% STACK: ["ppq", "qpq"]
t % Extract last character
% STACK: ["ppq", "qp", "q"]
! % Move top of stack to tape
% STACK: ["ppq", "qp"]
~ % Swap
% STACK: ["qp", "ppq"]
t % Extract last character
% STACK: ["qp", "pp", "q"]
? % Copy data from tape onto top of stack
% STACK: ["qp', "pp", "q", "q"]
& % Iterator: effectively a no-op in ordinal mode when the top of the stack is a 1-character string
% STACK: ["qp", "pp", "q"], ITERATOR: ["q"]
- % Remove occurrences: here, result is "" iff the characters are equal
% STACK: ["qp", "pp", ""]
n % Logical Not (for a consistent truthy value)
% STACK: ["qp", "pp", "Jabberwocky"]
o % Output top of stack
```
[Answer]
# Java 8, ~~43~~ 42 bytes
```
s->n->s.charAt(n)==s.charAt(s.length()+~n)
```
[Try it here.](https://tio.run/##lZA9T8MwEIb3/IpTp1g0FmnpFBIJBiQGpo5RBtc1qYNjO/ElEFD56yFVQxAspD4P9/XovbuCtSwwVuhi/9LL0poaoRhytEGp6HOjOUqj6cPoRB5XzDl4@vAAHDKUHL5rt1uspc6XP4lHjSIX9RLujVGC6SQBDjH0Lkh0kDjKD6y@Q1@TOJ4CR5XQOR58cvWpSR8NOsO3zU4NUqNia@QeSia1f5ZMM2DkNBHAtnMoSmoapHYoodI@p8xa1fmLcEFG95qQ6N92tuMTEM4Czm@C1nOgNEuzy2R@EbM2sbaqbDUxq3nbn2xiNnOYcLW@2Vw2mhKIor7sAO9v3Wv798pH79h/AQ)
[Answer]
# [Cubix](https://github.com/ETHproductions/cubix), 22 bytes
```
[[email protected]](/cdn-cgi/l/email-protection)):tBvpptc?1.\O0
```
1-indexed, takes input as `index`,`string`, separated by a space.
[Try it online](https://ethproductions.github.io/cubix/?code=Li5ALklBcCk6dEJ2cHB0Yz8xLlxPMA==&input=MiBsZXR0ZXI=&speed=5)
Cubified
```
. .
@ .
I A p ) : t B v
p p t c ? 1 . \
O 0
. .
```
### Explanation
This is mostly linear. The main logic is
```
IAp):tBpptc
IA Get the first input as an int and the rest as a string.
p): Move the index to the top of the stack, increment it, and copy it.
t Look up the appropriate character in the string.
Bpp Reverse the stack and put the index and character back on top.
t Look up the appropriate character in the reversed string.
c XOR the two characters.
```
We then branch with `?` to `O`utput `1` if the result is 0 and `0` otherwise.
[Answer]
# [V](https://github.com/DJMcMayhem/V), ~~26, 16~~, 13 bytes
```
ä$Àñã2xñVpøˆ±
```
[Try it online!](https://tio.run/##K/v///ASlcMNhzceXmxUcXhjWMHhHYc6Dm38/z8xCQT/mwEA "V – Try It Online")
Hexdump:
```
00000000: e424 c0f1 e332 78f1 5670 f888 b1 .$...2x.Vp...
```
1 indexed.
Explanation:
```
ä$ " Duplicate this line horizontally
Àñ ñ " Arg1 times...
ã " Move to the center of this line
2x " And delete two characters
V " Select this whole line
p " And replace it with the last pair of characters we deleted
ø " Count the number of matches of the following regex...
<0x88> " Any character
± " Followed by itself
```
For reference, my original answer was:
```
Àñx$x|ñxv$hhpÓ¨.©±/1
ñllS0
```
[Try it online!](https://tio.run/nexus/v#@3@44fDGCpWKGiBZppKRUXB48qEVeodWHtqob8h1eGNOTrDB//8eqTmp@f8NAQ "V – TIO Nexus") (0 indexed)
Hexdump:
```
00000000: c0f1 7824 787c f178 7624 6868 70d3 a82e ..x$x|.xv$hhp...
00000010: a9b1 2f31 0af1 6c6c 5330 ../1..llS0
```
[Answer]
# C#, ~~28~~ 27 bytes
```
s=>n=>s[n]==s[s.Length+~n];
```
*Saved a byte thanks to @KevinCruijssen.*
Compiles to a `Func<string, Func<int, bool>>`.
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 8 bytes
```
l~_W%.==
```
[Try it online!](https://tio.run/##S85KzP3/P6cuPlxVz9b2/39DBaWc1JKS1CIlAA "CJam – Try It Online")
0-indexed index goes first.
[Answer]
## R 51 bytes
```
function(s,n){s=el(strsplit(s,''));s[n]==rev(s)[n]}
```
Anonymous function, uses 1-based indexing
[Answer]
## Ruby, ~~22~~ ~~20~~ 18 bytes
```
->s,n{s[n]==s[~n]}
```
[Answer]
## Clojure, 27 bytes
```
#(nth(map =(reverse %)%)%2)
```
Wow, this was shorter than I expected.
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), ~~10~~ 5 [bytes](https://codegolf.meta.stackexchange.com/a/9429/74163)
```
⊃=⊃∘⌽
```
This is a tacit function, which needs to be assigned a name such as `f←⊃=⊃∘⌽`, and then called as `int f string`.
Thanks to @Adám for a whopping 5 bytes.
### How it works:
```
⊃=⊃∘⌽ ⍝ Main function; tacit.
⍝ Inputs are ⍺ = 1 (left) and ⍵ = 'abca' (right).
⊃ ⍝ ⍺⊃⍵, meaning 'pick the ⍺-th element of ⍵'
= ⍝ Compare to
⌽ ⍝ ⌽⍵, meaning 'invert ⍵'
⊃ ⍝ Again, ⍺⊃⍵, but:
∘ ⍝ Compose. This turns ⌽ into the right argument for ⊃,
⍝ which becomes 'pick the ⍺-th element from ⌽(the inverse of)⍵'
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT/8PBGmP2iY86mq2BeJHHTMe9ezlMlFIU1DPSS0pSS1SBwA "APL (Dyalog Unicode) – Try It Online")
The 22 byte answer was edited out. If you want to see it, check the revision history.
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 20 bytes
I don't have enough reputation to comment on [TheLethalCoder's answer](https://codegolf.stackexchange.com/a/123932/110384), but in C# 8 you can save some more bytes.
```
s=>n=>s[n]==s[^++n];
```
[Try it online!](https://tio.run/##fY89D4IwEIZ3f0XDRAMaAZmwXUyc3B2amkhTTBNyBVo//3ytymh7N12eJ3fvCbMURrn9FcTW2EnBJUffQYHNUat1TynqEHGGUCDUMOCEGHbKMuCN22kwuper46SsPCiQaZcmRYLTNcbN4i89t8LzIsx/5Z0q6DDOeHTJLIRTDMM4DqNXykjQT3ulDipFWW3q6J1eWiunaNbX43m/ze@6Nw "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# [J](http://jsoftware.com/), ~~6~~ 5 bytes
```
{]=|.
```
[Try it online!](https://tio.run/##y/qfVqxga6VgoADE/6tjbWv0/mtyKekpqKfZWqkr6CjUWimkFXNxpSZn5CsYKtgCcZqCemJSsjpCyBgkVFBQWFhQqA5VaQBTGR0bHauOJmZoZGxiqv4fAA "J – Try It Online")
*-4 bytes thanks to FrownyFrog for `{(=|.)`*
See original answer explanation -- idea is similar enough, but this is accomplished with a dyadic hook whose right verb is itself a monadic hook.
[Try it online!](https://tio.run/##y/qfVqxga6VgoADE/6s1bGv0NP9rcinpKain2VqpK@go1FoppBVzcaUmZ@QrGCrYAnGagnpiUrI6QsgYJFRQUFhYUKgOVWkAUxkdGx2rjiZmaGRsYqr@HwA "J – Try It Online")
### original answer (10 bytes)
```
{=/@(,:|.)
```
`,:|.` right arg on top of reverse right arg
`=/` are they elementwise equal?
`{` take from that boolean list the index indicated by the left arg
[Try it online!](https://tio.run/##y/qfVqxga6VgoADE/6tt9R00dKxq9DT/a3Ip6Smop9laqSvoKNRaKaQVc3GlJmfkKxgq2AJxmoJ6YlKyOkLIGCRUUFBYWFCoDlVpAFMZHRsdq44mZmhkbGKq/h8A "J – Try It Online")
[Answer]
# Mathematica, 34 Bytes
```
s=StringTake;s[#,{#2}]==s[#,{-#2}]&
```
[Answer]
# [Perl 6](https://perl6.org), 27 bytes
```
{[eq] $^a.comb[$^b,*-1-$b]}
```
[Test it](https://tio.run/nexus/perl6#VZBbcoIwGIXfs4q/Gab1EhnR2gcR7VNX4BtgJ0BsnQG5BFTq6GLadbgml2ATwKhhhjD5zjk5PwVnsHnTfRNFJTz7ccDAuuxtlrqgLajux5FnawuPdHpGT/Pcw0XI3nPGc7AgXK0Zb7X1iCbjPQKIxlxuAOfTLz6f/uCovrQJz7PV@msqbHpnVqleyEu1a5N4ueQsl8wJutWZrU0yxouwOpxnRf5dutJ1MMXrqNIIdJWbwEyZCGifJjqgQkw3F2VNlIR0Dd2quYmWcdYM0ZtCy6nDiFMHEYftEubnLCBOwLjfBjnUioP8Oa1GW0vbBJQWpFbcecEGJtCH66rLgwGWBQbC1PMFNh6hJ6EnYL2EYHiDVEKKsO3a7s36QUPOSnDhyQJbwf4DtCV0EU6SNE1SgQd3d6YyNpWF5CPg6M5JpVMUMgbD15HKbaAh4QjhkOU5y66VmlgmYxnCP7tyu2kGUc6tdO7@AQ "Perl 6 – TIO Nexus")
```
{ # bare block lambda with two placeholder parameters 「$a」 and 「$b」
[eq] # reduce using string equality operator
$^a # declare first positional parameter
.comb\ # split that into individual characters
[ # index into that sequence
$^b, # declare and use second parameter
*-1-$b # closure that subtracts one and the
# second parameter of the outer block
# (「*」 is the parameter of this closure)
]
}
```
[Answer]
# PHP>=7.1, 36 Bytes
```
[,$t,$p]=$argv;echo$t[$p]==$t[~+$p];
```
[Online Version](http://sandbox.onlinephpfunctions.com/code/bed3d1ef5870c0d0d552b4fc84367a13df071303)
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~8~~ 7 bytes
```
q@zQ@_z
```
With the input reversed: first the index, then the string. It is 0-indexed.
# Explanations:
```
q@zQ@_z
@zQ Get the nth (Qth) character
_z Reverse the string
@ Get the nth character of the reversed string. Implicit input of the index
q Test equality
```
[Try it online!](https://pyth.herokuapp.com/?code=q%40zQ%40_z&input=2%0Appqqpq&debug=0)
[Answer]
# Lua, 46 bytes
```
function f(s,n)return s:byte(n)==s:byte(-n)end
```
[Try it online!](https://tio.run/##bc7NCoMwDAfwu09RPLWgBz@2w8CrT7CbeKguMkGyfqTb3Mt3HQpzsuQSfoT8Mznp/eCwp/GGbOA2QWGAnEFmT91MwFFU1TqmKAAvPk3Z2Ti6zozAEuulBRspMyLxgcdZnLBMiC/Irg@U/9BSgcstK6W10kGLrU5ABGY9EYXwWk4W/oc3bdPuw1bb/fTpoMetZnlRHvarr@f8uC@f@jc)
[Answer]
# C, ~~36~~ 35 bytes
```
#define f(s,n)s[n]==s[strlen(s)+~n]
```
Uses 0-based indexing, naturally.
[Try it online!](https://tio.run/##S9ZNT07@/185JTUtMy9VIU2jWCdPszg6L9bWtji6uKQoJzVPo1hT11A3L/Z/bmJmnoYmVzWXAhAUFGXmlaRpKKmmxOQp6QAZ4fk5hvnhSjqGmprW@FUYgVTU/gcA)
[Answer]
# [Factor](https://factorcode.org/), 24 bytes
```
[ 2dup nth -rot nth* = ]
```
[Try it online!](https://tio.run/##S0tMLskv@h8a7OnnbqWQnVqUl5qjUJxaWJqal5xajGDppVaUFCUWKxQUpZaUVBYUZeaVKFhzcRkqKEXHRscq/Y9WMEopLVDIK8lQ0C3KLwExtBRsFWL/Jyfm5Cjo/QcA "Factor – Try It Online")
## Explanation
`nth*` is like `nth` except it indexes from the back; if `0 nth` is the first element, `0 nth*` is the last.
```
! 1 "[][]"
2dup ! 1 "[][]" 1 "[][]"
nth ! 1 "[][]" 93
-rot ! 93 1 "[][]"
nth* ! 93 91
= ! f
```
[Answer]
# [Thunno](https://github.com/Thunno/Thunno), \$ 8 \log\_{256}(96) \approx \$ 6.58 bytes
```
Drz.=sAI
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72sJKM0Ly9_wYKlpSVpuhYrXIqq9GyLHT0hXKjoghUFBYWFBYVcRhA-AA)
0-indexed. Change `AI` to `AH` if you want it to be 1-indexed.
#### Explanation
```
Drz.=sAI # Implicit input
Dr # Duplicate and reverse
z.= # Zipped equality
sAI # Swap and index in
# Implicit output
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 4 bytes
```
fḂ=i
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJm4biCPWkiLCIiLCJwcHFxcHFcbjIiXQ==)
#### Explanation
```
fḂ=i # Implicit input
f # Flatten into a list of characters
Ḃ # Bifurcate: duplicate and reverse
= # Are they equal (vectorises)
i # Index in
# Implicit output
```
[Answer]
## ZSH, 32
```
f(){read s n;[ $s[n] = $s[-n] ]}
```
[Try it online!](https://tio.run/##JYqxDoIwAET3fsWFEKKDiQV0oY5uDsbNNB0QSiAhpQUiivjttZW74S53bx5qW222n17mJQaojCMcuBI4@dy5Ir52qptWwiMZyg6MsSC8na@Xe4AFFaIIsqg7UCzL2vaeU9JaCkryR4GY5KuQEi64cMM/KNHaGG2QOMwbR0LjJD24p5XjKHtHzq/39ET6Aw "Zsh – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~10 9~~ 8 bytes
```
gV ¥Ug~V
```
[Try it online!](https://tio.run/nexus/japt#@58epnBoaWh6Xdj//0qJScmJSjoKRgA "Japt – TIO Nexus")
] |
[Question]
[
# Task
Your task is to print this exact text:
```
A
BCD
EFGHI
JKLMNOP
QRSTUVWXY
ZABCDEFGHIJ
KLMNOPQRSTUVW
XYZABCDEFGHIJKL
MNOPQRSTUVWXYZABC
DEFGHIJKLMNOPQRSTUV
WXYZABCDEFGHIJKLMNOPQ
RSTUVWXYZABCDEFGHIJKLMN
OPQRSTUVWXYZABCDEFGHIJKLM
NOPQRSTUVWXYZABCDEFGHIJKLMN
OPQRSTUVWXYZABCDEFGHIJKLMNOPQ
RSTUVWXYZABCDEFGHIJKLMNOPQRSTUV
WXYZABCDEFGHIJKLMNOPQRSTUVWXYZABC
DEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKL
MNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVW
XYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJ
KLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXY
ZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOP
QRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHI
JKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCD
EFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZA
BCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ
```
# Specs
* You may do it in all-lowercase instead of all-uppercase.
* Trailing newlines at the end of the triangle is allowed.
* Trailing spaces after each line is allowed.
* You must print to STDOUT instead of outputting an array of strings.
# Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Program with lowest byte-count wins.
[Answer]
# Vim, 29 bytes
```
:h<_↵↵↵y$ZZ26P0qqa↵♥βjllq25@q
```
Where `↵` represents the Return key, `♥` the Escape key, and `β` the Backspace key.
[](https://i.stack.imgur.com/am59T.gif)
[Answer]
# Python 2, 65 bytes
```
i=1
a=bytearray(range(65,91))*26
while a:print a[:i];a=a[i:];i+=2
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
26RḤ’RØAṁY
```
[Try it online!](http://jelly.tryitonline.net/#code=MjZS4bik4oCZUsOYQeG5gVk&input=)
### How it works
```
26RḤ’RØAṁY Main link. No Arguments.
26 Set the return value to 26.
R Range; yield [1, 2, ..., 25, 26].
Ḥ Unhalve; yield [2, 4, ..., 50, 52].
’ Decrement; yield [1, 3, ..., 49, 51].
R Range; yield [[1], [1, 2, 3], ..., [1, ..., 49], [1, ..., 51]].
ØA Yield the uppercase alphabet.
ṁ Mold the alphabet as the array of ranges. This repeats the uppercase
letters over an over again, until all integers in the range arrays
have been replaced with letters.
Y Join, separating by linefeeds.
```
[Answer]
## VBA Excel (80 bytes, 1742 bytes)
---
# Excel, 1742 bytes
Inspired by [the ugoren's creative answer](https://codegolf.stackexchange.com/a/87079/58742), I managed to find an Excel formula to create the pattern as shown in the OP.
```
=MID(REPT("ABCDEFGHIJKLMNOPQRSTUVWXYZ",26),(ROW()-1)^2+1,2*ROW()-1)
```
Paste this formula in cell A1, then drag all over range A1:A26.
The length of the formula is 67 bytes but you have to replicate it 26 times, so it's equal to 67\*26=1742 bytes. Here is the output:
[](https://i.stack.imgur.com/jClc9.png)
---
# Excel VBA, 80 bytes
Now it's possible we integrate Excel with VBA to automate the process and to save many bytes since VBA is built into most Microsoft Office applications, including Excel. Write and run the following code in the Immediate Window (use combination keys `CTRL`+`G` to display it in Visual Basic Editor):
```
[A1:A26]="=MID(REPT(""ABCDEFGHIJKLMNOPQRSTUVWXYZ"",26),(ROW()-1)^2+1,2*ROW()-1)"
```
The program works by printing the Excel formula above to the range A1:A26. Unfortunately, both Excel and VBA have no built-in alphabet.
[Answer]
## Haskell, 67 bytes
```
_#53=[]
s#i=take i s:drop i s#(i+2)
mapM putStrLn$cycle['A'..'Z']#1
```
A simple recursion over the length `i` of the line. In each step the next `i` chars are taken from an infinite repetition of the alphabet.
[Answer]
# Mathematica, 90 bytes
```
StringRiffle[Flatten[Alphabet[]&~Array~26]~Internal`PartitionRagged~Range[1,51,2],"
",""]&
```
Anonymous function. Takes no input and returns a string as output. Golfing suggestions welcome. An example of what `Internal`PartitionRagged` does:
```
In[1]:= Internal`PartitionRagged[{2, 3, 5, 7, 11, 13}, {2, 3, 1}]
Out[1]= {{2, 3}, {5, 7, 11}, {13}}
```
[Answer]
# C, 79 bytes
```
main(i,j){for(i=0,j=1;i<676;i++){putchar(i%26+65);if(j*j==i+1){puts("");j++;}}}
```
My first answer in C \o/
Golfing suggestions are more than welcome.
[Answer]
# [Brachylog](http://github.com/JCumin/Brachylog), 37 bytes
```
26~l<:1aLc~j[@A:I],L~@nw
=:2%1,.#@l?,
```
[Try it online!](http://brachylog.tryitonline.net/#code=MjZ-bDw6MWFMY35qW0BBOkldLEx-QG53Cj06MiUxLC4jQGw_LA&input=)
### Explanation
* Main predicate:
```
26~l Let there be a list of 26 elements
< This list is an ascending list of integers
:1aL Apply predicate 1 to that list ; the resulting list of strings is L
c Concatenate the list of strings into one big string
~j[@A:I], That big string is the result of juxataposing the alphabet I times to itself
L~@n Create a string which when splitted on line breaks results in L
w Write that string to STDOUT
```
* Predicate 1: used to generate variable strings of odd lengths.
```
= Assign a value to the Input
:2%1, That value must be odd
.#@l?, Output is a string of length Input
```
[Answer]
# Perl, ~~42~~ ~~41~~ 39 bytes
```
perl -E '@b=(A..Z)x26;say splice@b,0,$#a+=2for@b'
```
Just the code:
```
@b=(A..Z)x26;say splice@b,0,$#a+=2for@b
```
An obvious shorter version unfortunately triggers an internal perl problem (Use of freed value in iteration):
```
say splice@b,0,$#a+=2for@b=(A..Z)x26
```
[Answer]
# [Pyramid Scheme](https://github.com/ConorOBrien-Foxx/Pyramid-Scheme), 1492 bytes
```
^ ^
/ \ / \
/set\ /do \
^-----^ ^-----^
/a\ ^- /!\ /[\
--- ^- ^--- ^---^
^- /=\ ^- / \
^- ^---^ -^ /out\
^- ^- /a\ ^- -----^
^- / \ ---/[\ / \
-^ /51 \ ^---^ /chr\
^- ----- ^- / \ -----^
-^ ^- /do \ / \
^- ^- ^-----^ /10 \
-^ /[\ -^ ^- -----
^- ^---^ -^ -^
-^ / \ -^ /c\ ^-
^- /set\ /[\--- -^
^- ^-----^---^ ^-
-^ /a\ /+\ -^ -^
^- --- ^---^ -^ -^
-^ /a\ /2\ / \ -^
-^ --- ---/set\ -^
-^ ^-----^ ^-
-^ /c\ /a\-^
-^ --- --- -^
-^ /[\
-^ ^---^
-^ ^- -^
/]\ / \ -^
^---^ /set\ -^
^- -^ ^-----^ -^
/ \ ^- /c\ /-\ -^
/set\ ^- --- ^---^ -^
^-----^- /c\ /1\ -^
/b\ / \ --- --- /]\
--- / -1\ ^---^
----- ^- / \
/ \ /out\
/set\-----^
^-----^ -^
/b\ /?\ -^
--- ^---^ / \
/!\ -^ /chr\
^--- /+\-----^
/=\ ^---^ /+\
^---^ /b\ /1\ ^---^
/b\ / \--- ---/ \ /b\
---/25 \ /65 \---
----- -----
```
[Try it online!](https://tio.run/##hVRJbsMwDLzrFew5MFgHSG9FH1JWQDYgPQQpkvTQ17tcJTmLLcCJLJJDzlD0z995ffzedZftYX/cDwPwyhArJ/5BIH/lHR/gZX@1E9yd5CR3siTKdwnXpG/s8iI7/KTEBjvKvhNHCLf3EqA5iiOj8oOn36scZ4cQfP73bBEHcsCpaq0SuuqBoIABbg9nrdmiYRSsaF3wV4tQrIByBE15jtm/ejYwsgAuBzhsRFZK8niIZedSt8oKnJDKzGBSpUGnJm1RPEmk6o0LCuhk/G4SpqiQ3XFJkTgq10SsoPVXu9M1d8HpckZoDFK0Ino3w6DZDdIMLRaEUAkemerduLWZosWGX1TRrE/FGAqpLa6sit4AjZjVaIS4joVg16AbnN@FVmZ3iBY1VBkE@wKBGxoNVhXfWSXbI3Q9wf1qBfJrfO9SZunpkgJitJ47CdmYjafrXsPHYEb8g@YcR6rO8bCvjE6QDjdM16mTMsuofJO8hgXN0M/KTrqcp6HVDSjGTZqwoUkpcLmKr9DbSiMnSdYrobth@Ac "Pyramid Scheme – Try It Online")
Why? Why not?
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 12 bytes
```
jtc*G26*Rd26
```
[Try it online!](http://pyth.herokuapp.com/?code=jtc%2aG26%2aRd26&debug=0)
[Answer]
# JavaScript (ES6), 77 ~~82 88~~
EcmaScript 6 required just to save 1 byte using a template string literal for newline.
```
for(i=r=l=o='';l+52;r++||(r=l-=2,o+=`
`))o+=(i++%26+10).toString(36);alert(o)
```
*Less golfed*
```
for(i = r = l = o = '';
l + 52;
r++ || (r = l -= 2, o += `\n`))
o += (i++ % 26 + 10).toString(36);
alert(o);
```
**Test**
```
for(i=r=l=o='';l+52;r++||(r=l-=2,o+=`
`))o+=(i++%26+10).toString(36);alert(o)
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 10 bytes
```
Cİ1ṠṁK…"AZ
```
[Try it online!](https://tio.run/##yygtzv7/3/nIBsOHOxc83Nno/ahhmZJj1P//AA "Husk – Try It Online")
### Explanation
```
Cİ1ṠṁK…"AZ
…"AZ Get the alphabet
ṠṁK Replace each letter with the whole alphabet
C Cut the resulting string into lines with lengths
İ1 equal to the list of odd numbers
```
[Answer]
# JavaScript, 129 bytes
```
z=1,i=0,g=a=>{b=0,c="";while(a+a-1>b){c+='ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split``[i>26?i=0:i++];b++}console.log(c)};while(z<26)g(z++)
```
[Answer]
## Pyke, 14 bytes
```
G26*WDoh<
Ko>D
```
[Try it here!](http://pyke.catbus.co.uk/?code=G26%2aWDoh%3C%0AKo%3ED&warnings=0)
[Answer]
# Go, 133 bytes
```
package main
import S "strings"
func main(){s:=S.Repeat("ABCDEFGHIJKLMNOPQRSTUVXXYZ",26)
for i:=1;s!="";i+=2{println(s[:i]);s=s[i:]}}
```
[Answer]
# MATLAB, ~~112 109 95 79~~ 77 bytes
This will also work with **Octave**, you can try [online here](http://octave-online.net).
```
a=['' 65:90 65:90]';j=0;for i=1:2:52;b=circshift(a,j);j=j-i;disp(b(1:i)');end
```
So after some major changes, I've saved a further ~~14~~ 32 bytes. This one is getting to be much more like the length I would have expected from MATLAB. I've left the old version below as it is substantially different.
```
a=['' 65:90 65:90]'; %Create 2 copies of the upper case alphabet
j=0; %Initialise cumulative sum
for i=1:2:52; %For each line length
b=circshift(a,j); %Rotate the alphabet string by the cumulative offset
j=j-i; %Update cumulative negative sum of offsets.
disp(
b(1:i)' %Extract first 'line length' characters from rotated alphabet.
); %Display next line (disp adds newline automatically)
end
```
---
**Original version:**
```
a=['' repmat(65:90,1,26)];c=cumsum(1:2:51);disp(cell2mat(arrayfun(@(s,f)[a(s:f) 10],[1,c(1:25)+1],c,'Un',0)))
```
Wow that one ended up being longer than I thought it would. I'll see if I can't knock a few bytes off it.
An ungolfed version to explain:
```
a=['' repmat(65:90,1,26)]; %Create 26 copies of the upper case alphabet
c=cumsum(1:2:51); %Calculate the end index of each row in the above array, by cumulatively summing the length of each line
disp(
cell2mat(
arrayfun(@(s,f)
[a(s:f) 10], %Extract the part of the alphabet and insert a new line.
[1,c(1:25)+1],c, %start index is the previous end of line plus 1. End index is as calculated by cumsum.
'Un',0 %The returned values are not all the same length
) %Do this for each line
) %Convert back to a matrix now new lines inserted
) %And display it
```
---
**Acknowledgements**
* 3 bytes saved - thanks @LuisMendo
[Answer]
## XPath 3.0 (and XQuery 3.0), 84 bytes
```
codepoints-to-string((0 to 25)!(subsequence(((1 to 26)!(65 to 90)),.*.+1,2*.+1),10))
```
Explanation:
`(1 to 26)!(65 to 90)` is the alphabet 26 times
`(0 to 25)!(subsequence(XX, start, len),10)` takes 26 subsequences of this, each followed by newline
`subsequence(X, .*.+1, 2*.+1)` takes successive subsequences with start position and length: (1, 1), (2, 3), (5, 5), (10, 9) etc.
`codepoints-to-string()` turns Unicode codepoints into characters
[Answer]
# Ruby, 46 bytes
```
26.times{|i|puts ([*?A..?Z]*26)[i*i,i*2+1]*""}
```
See it on ideone: <http://ideone.com/3hGLB0>
[Answer]
# 05AB1E (alternate) 15 bytes
```
A2×52µ¼D¾£,¾¼FÀ
```
[Try it online!](http://05ab1e.tryitonline.net/#code=QTLDlzUywrXCvETCvsKjLMK-wrxGw4A&input=)
Explanation:
```
A2× # push a string containing a-za-z
52µ # Loop the rest of the program until counter = 52
¼ # increment counter (it's 0 initially)
D # Duplicate the alpha string on the stack
¾£ # Replace alpha with alpha[0..counter]
, # Pop the substring and print it
¾¼FÀ # rotate the alpha string left counter++ times.
```
[Answer]
# R, ~~120~~ ~~115~~ 111 bytes
```
v=c();for(i in 1:26){v=c(v,c(rep(LETTERS,26)[(sum((b=seq(1,51,2))[1:i-1])+1):sum(b[1:i])],"\n"))};cat(v,sep="")
```
**Ungolfed :**
```
a=rep(LETTERS,26)
b=seq(1,51,2)
v=vector()
for(i in 1:26)
{
v=c(v,c(a[(sum(b[1:i-1])+1):sum(b[1:i])],"\n"))
}
cat(v,sep="")
```
Basically, `b` is the vector of the odd numbers between `1` and `51`, thus giving the length of each line. Obviously, the `sum` function *sums* the numbers of this vector, and gives the starting and ending indexes.
*-5 bytes* thanks to @plannapus !
*-4 bytes* thanks to @plannapus !
[Answer]
# R, 81 73 65 63 bytes
A simple `for` loop approach. Repeat the alphabet 26 times and loop through a sliding index range that is calculated using `(i^2-2*i+2):i^2`.
```
for(i in 1:26)cat(rep(LETTERS,26)[(i^2-2*i+2):i^2],"\n",sep="")
```
[Answer]
## Batch, 123 bytes
```
@set s=
@for /l %%i in (1,2,51)do @call set s=%%s%%ABCDEFGHIJKLMNOPQRSTUVWXYZ&call echo %%s:~0,%%i%%&call set s=%%s:~%%i%%
```
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), ~~18~~ 17 bytes
```
26FA26×N>n£NnF¦},
```
**Explanation**
```
26F # for N in range(0, 26) do
A26× # the alphabet repeated 26 times
N>n£ # take (N+1)^2 letters
NnF¦} # throw away the first N^2 letters
, # print with newline
```
[Try it online!](http://05ab1e.tryitonline.net/#code=MjZGQTI2w5dOPm7Co05uRsKmfSw&input=)
[Answer]
# Rexx, ~~74~~ 72 bytes
```
i=1;m=1;do 26;say substr(copies(xrange('A','Z'),26),i,m);i=i+m;m=m+2;end
```
Ungolfed:
```
i=1
m=1
do 26
say substr(copies(xrange('A','Z'),26),i,m)
i=i+m
m=m+2
end
```
[Answer]
# TSQL, 129 bytes
USE MASTER in the beginning of the script is to ensure that the query is run in the master database which is default for many users(not counting bytes for that).
**Golfed:**
```
USE MASTER
SELECT SUBSTRING(REPLICATE('ABCDEFGHIJKLMNOPQRSTUVWXYZ',26),number*number+1,number*2+1)FROM spt_values WHERE number<26and'P'=type
```
**Ungolfed:**
```
USE MASTER
SELECT SUBSTRING(REPLICATE('ABCDEFGHIJKLMNOPQRSTUVWXYZ',26),number*number+1,number*2+1)
FROM spt_values
WHERE number<26and'P'=type
```
**[Fiddle](https://data.stackexchange.com/stackoverflow/query/527267/alphabet-triangle-strikes-again)**
**[Fiddle for older version using xml path](https://data.stackexchange.com/stackoverflow/query/527174/alphabet-triangle-strikes-again)**
[Answer]
# PowerShell, 68 bytes
```
$a=-join(65..90|%{[char]$_})*26;26..1|%{$a=$a.Insert($_*$_,"`n")};$a
```
The section before the first semicolon produces a string containing 26 copies of the uppercase alphabet. The next section injects linebreaks at the index of each square number (working backward so I don't have to account for the shifting). Finally, the `$a` at the end just shoves that string variable onto PowerShell's equivalent of `STDOUT`.
[Answer]
# Dyalog APL, 18 [bytes](http://meta.codegolf.stackexchange.com/questions/9428/when-can-apl-characters-be-counted-as-1-byte-each/)
[`↑2{⍺↓⍵⍴⎕a}/×⍨0,⍳26`](http://tryapl.org/?a=%u21912%7B%u237A%u2193%u2375%u2374%u2395a%7D/%D7%u23680%2C%u237326&run)
[Answer]
# C, 60 bytes
```
i;main(j){for(;j<27;j*j^++i||puts("",j++))putchar(i%26+65);}
```
[Answer]
# C++, 111 bytes
```
void a(){int c=65,i,j;for(i=0;i<26;i++){for(j=0;j<=2*i;j++){std::cout<<(char)c;c++;if(c==91)c=65;}std::cout<<'\n';}}
```
First try at one of these.
Uses an int "c" to record which letter it needs to print at any given time. Once "c" passes 90 ('Z') it gets reset to 65 ('A'). Prints the pyramid using for loops.
] |
[Question]
[
Given an array of integers, count the number of contiguous subarrays with an even sum. You may assume that the array is non-empty, and contains only non-negative integers.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins.
### Test Cases
```
Input -> Output
[7] -> 0
[8] -> 1
[3, 5] -> 1
[6, 2] -> 3
[2, 4, 5] -> 3
[7, 4, 0, 5, 8] -> 6
[4, 8, 7, 9, 5] -> 7
[1, 9, 1, 0, 4] -> 7
[7, 5, 2, 1, 4, 8] -> 9
[0, 6, 6, 5, 3, 3, 8] -> 13
[8, 5, 9, 4, 5, 1, 0] -> 16
```
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 57 bytes
```
f=lambda S,p=1:S>[]and f(S[1:])+sum((p:=p^s%2)for s in S)
```
[Try it online!](https://tio.run/##NVDZSsUwEH3PVwwBIdEot4vdJPcn2rexQi/XYqBLaKNgf76mUwPzcLaZTMb@uq95Sgq77Huvh2683TuoldVRVV@x7aY79KLGqGrl0/o9CmErbT/Wh1j28wIrmAlquTeac455C89XuDAsCEQMEwWvAWcKYsIJw1hBGixPc6IXryg4ezOGXikUeKsMyZxhRDSicBrEnBpj0tMwoWToMxmVdxOq/8X8kwWp5bnHOfH0Mv@Tl9UOxgn@PnHJGo34OHZWfP50g3LBO8JcyvY4gzvO0LTswEbNxKpN98LIN7uYyYlNbVrPcv8D "Python 3.8 (pre-release) – Try It Online")
Similar to brute-force method below but should have better complexity.
# [Python 3](https://docs.python.org/3/), 57 bytes
```
f=lambda S:S>[]and~sum(S)%2+f(S[1:])+f(S[:-1])-f(S[1:-1])
```
[Try it online!](https://tio.run/##NU/JasMwEL3rKwZBQWrlEi/1VpyfcG6qDiqpqcCWha0U4kN/3VXGFczhbbO5u/@ebb7vQzfq6fOqoW/7s1TaXn/X28R6/pS9DKyXaas4gjZJFU8O6QF3M7l58WBvk7uDXsE6cukopbJSkJzhRGSNICUyF/AWcSkgQ5wTmQkoohVohfQUFAFHb0lkUGoBwWpisiIyRZpiuIhihY0Z6kWc0BAZMiVWcHOs/8PCyhrV5rjjmHh4ZfjkdXWj8Yx@WMrDb1I@T9qxrx89Ch@9R5hyroZ5AQ/GwkWRBzZiRtZu3cAMf3eLsZ5tYuu6me9/ "Python 3 – Try It Online")
This is a brute force method based on inclusion-exclusion. Also works on Python2.
# [Python 3](https://docs.python.org/3/), 60 bytes
```
f=lambda S,e=0,i=0:e+(S>S[:i]and f(S,[e+1,i-e][S[i]&1],i+1))
```
[Try it online!](https://tio.run/##NU/JboMwEL37K0YcKrtMKhwoW@X8BLlNfaAKqJbAWIRWCj9PHVOkObxtNvdYviebbluvhnb8urXQYKcSNCqpu5g3l4Zqo1t7g543SF0s0Zw6TQ0Z/SI1mlgKsZnRTfMC9md0D2jvYB27qiiKqNBwukDCqAxAMkoR3g@cI5wDThmdEbLD8rQINPEKwt6bM/JKieCt6kgWjGSgMoSzQyxC4zno2TGhYuQzeSjvpqH@D/Mry6BW@x37xN3L/SdvdzeYhUefNhL@N6LXsXW8@20HXA7vGY6E0P00wwLGwlWzJzY4BVavqudGfLjZ2IWvuCo1ie0P "Python 3 – Try It Online")
This loops over the right ends of possible subarrays keeping the number of non empty even summing subarrays in `e`. The number of odd summing subarrays is implicit in `i-e` (`i` is the loop index). As we move `i` to the right we update `e` by incrementing if we pass through an even element and by replacing with the current odd summing number if we pass through an odd element. The sum of all `e`s is then output.
## Correctness and connection with @Bubbler's closed formula
This is a routine combinatorial partition. To count all (non-empty) contiguous subarrays of `S` with even sum (cswes) we split the set of all cswes into all cswes ending at `S(1)`, all cswes ending at `S(2)` etc. and add the sizes of these sets instead. If `e(n)` is the size of the set of cswes ending at `S(n)` then depending on the parity of `S(n+1)` we have `S(n+1)` even ~> `e(n+1)=e(n)+1` and `S(n+1)` odd ~> `e(n+1)=o(n)` where `o(n)` is the number of contiguous subarrays with odd sum ending at `S(n)`. Obviously, `o(n)+e(n)=n`. And with that we have got all the pieces used by the algorithm.
Now to connect with Bubbler's formula let us reinterpret what we are doing when going from `e(n)` to `e(n+1)`. If `S(n+1)` is even then we "increment a counter", more specifically, "the active counter". There is also an "inactive counter" which is, err, inactive. If `S(n+1)` is odd then we "swap the active and inactive counters". Which of the two counters is currently active, i.e. in `e` depends on the cumulative parity of `S` up to the current position. The counter that started out as `e(0)` therefore counts from `0` to `n0` (excl) where `n0` is as defined by Bubbler and the counter that started out as `o(0)` counts from `0` to `n1`. The algorithm adds all the steps together. Therefore, using the well-known summation formula `1+2+...+n = n(n+1)/2` we recover Bubbler's formula.
For reference, here is Bubbler's relevant comment in full:
>
> Fastest algorithm: prepend 0, cumulative sum, each number mod 2, then count zeros (n0) and ones (n1) and calculate n0\*(n0-1)/2+n1\*(n1-1)/2. Probably not so appealing for golf though. –
> Bubbler
>
>
>
[Answer]
# [Python 2](https://docs.python.org/2/), 57 bytes
```
z=1
for x in input():z+=1j+1-x%2*2*z%1j
print abs(z*z)//4
```
[Try it online!](https://tio.run/##JU3bCoMwDH33K4IgeOlwqZ1WwS8RH7bhUBEV51jXn3cxhROSc0my/vZ@meXx7YepA6w60z193z9sjd5r2cDAMBPWzx5GlU1qHBO8mEDGMrYBjt66DfMO98c7tLGN0lQd53ZTtF6jqTIBN2q5AElNClBOKHi6EhFw5ohoAaSWzkeekCPK5SkpWVJuhZycQUbGOFXNvHSP3IX2Dw "Python 2 – Try It Online")
Thanks to dingledooper for saving 2 bytes with `z%1j` in place of `z.real`!
**58 bytes**
```
z=p=1
for x in input():p*=1|x%-2;z+=1j+p
print abs(z*z)//4
```
[Try it online!](https://tio.run/##JU3bCoMwDH33K4Iw8NLhWjtvo18iPmzDoTK0uI51Zf/uYgonJOeSRH/NsMxi@wzjswfe9La/h2G4OaUVDx7LChbGGaHfJoobnSj@s4ejuLhU8SnVgV7H2cD19opc4uIsk9u@3pZd0FZYOYMztoKBwCYYSC@UNJ2QMNhzSCoGqNbe5zRxikifx6QgSfoVdAoCGjlhVyvitX/kL3R/ "Python 2 – Try It Online")
**59 bytes**
```
t=e=o=0
for x in input():e+=1;exec"e,o=o,e;"*x;t+=e
print t
```
[Try it online!](https://tio.run/##JU3bCoMwDH33K0KftpkHW5230i8Rn0aGwrBFKnNf79IUTkjOJUn4xcVv5vou64dAj3TSSyl1RUfOu6p4@x1OWDdGOOLtPlLptJUUoXceyarHaWPpqAj7ukWIV9qfurmYeq4a4cmtRTDcDEKThU6miglCyjHpEVgdsq9l0hJpcp6TRqQmr7DTCtioBUnthQ/5Ub4w/wE "Python 2 – Try It Online")
**59 bytes**
```
n=0;a=1
for x in input():n+=1;a+=1-x%2*2*a
print a*a+n*n>>2
```
[Try it online!](https://tio.run/##JU3bCoMwDH33K4Iw2GoHNjqv6I@ID2U4FEYUccx9fZemcJrkXNJsv2NeCd13Xt4TmGY6p2ccx466tLWdiV7rDicsxNg@x/XWUNKZ1nK5nxdUqGy07QsdYJVNSFHfo/P7QzlGQ8Uv0/DgVmhAbqghD0IpU8pEg88xqTSwWgffyGQkkoc8J1GkPKywUwjYyARerYTX4VD4YfwD "Python 2 – Try It Online")
**59 bytes**
```
p,t=l=[0,0]
for x in input():l[p]+=1;p^=x%2;t+=l[p]
print t
```
[Try it online!](https://tio.run/##JU3bCoMwDH33K4Iw2DAPbXValX5J6V5Gh4Jokcrc17s0hROSc0kSfnHaVnV9p3nxIAd/@ndZllfAaBZjBQpXfLYdTphXQjji/TEsNrjKyDG8zHlTY6xMUoqwz2uEeKV927nCaqoa4UmtRVDUFEKThY4nQQQh5YhoBFL77EueJEeanKekYqnJK@S0DDJqRlI18z4/yhfcHw "Python 2 – Try It Online")
All these solutions iterate through the list just once. They're based on [Bubbler's observation](https://codegolf.stackexchange.com/questions/237700/even-sum-subarrays#comment539157_237700) that the output can be expressed in terms of the numbers \$(e,o)\$ of even and odd entries in the cumulative sum as:
$$ \frac{e(e+1)+o(o-1)}{2}$$
This is because a sub-list has even sum if and only if its start and end indices correspond to elements of the same parity in the cumulative sum. The number of ways to choose two even or two odd elements in the cumulative sum is \$\binom{c}{2}\$, that is \$c(c-1)/2\$, where \$c\$ is their count. For evens, we need to either prepend a `0` to the cumulative sum or increase the count by 1 to account for the initial total being 0 which is even.
---
# [Python](https://docs.python.org/3/), 52 bytes
```
f=lambda l,b=-1:l>[]and~sum(l)%2+f(l[1:],0)+f(l[:b])
```
[Try it online!](https://tio.run/##JU3NCoMwDL7vKXoZtKwDW50/BfcipYeKikLsZNONXfbqXUxLSr6/JOt3mx4hj3FswS9d7xnIrr0qA3frfOh/r33hIM76MnKwyjiZCYKmcyJ@phkGpsz6nMPGRz68PfA5rPvGBb5oK3eyNf5cshu2UjKNTUtWJKEilCGR7MghqSVDtUm@IqQoUqQ8JjVJRRpBp6RCI6c61Jp4kw6lDe4P "Python 3 – Try It Online")
Inspired by [loopy walt's inclusion-exclusion approach](https://codegolf.stackexchange.com/a/237703/20260). Thanks to loopy walt for -2 bytes!
We want to recursively reach all contiguous sublists of `l` to count those with even sum. We do this by repeatedly removing either the start (first) or end (last) element. But, this generates duplicate sublists because they can be reached via removals in different orders, like start then end versus end then start.
So, we guarantee that we do all start removals before any end removals. That is, once we remove the end, we no longer remove the start. We use a flag `b` for whether start removals are allowed, which starts at -1 and is set to 0 after an end removal. When `b` is 0, end removals are replaced with removing the entire list, which effectively cuts off that branch. This gives a quadratic runtime.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 4 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ŒOÈO
```
[Try it online](https://tio.run/##yy9OTMpM/f//6CT/wx3@//9Hm@uY6BjomOpYxAIA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/o5P8D3f4/9f5Hx1tHqsTbQHExjqmQNJMxwhIGumYgHnmQNpAx1QHJG@iY6FjrmMJFjcE0oZAGROwGlMdIyDPBKzKQMcMCE11jIEQxLcAsi1BpoHUx8YCAA).
**Explanation:**
```
Œ # Get the sublists of the (implicit) input-list
O # Sum each inner list
È # Check for each whether it's even
O # Take the sum to get the amount of truthy results
# (after which this is output implicitly as result)
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~15~~ 13 [bytes](https://github.com/abrudz/SBCS)
```
+/~2|∊+\¨,⍨\⎕
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKM97b@2fp1RzaOOLu2YQyt0HvWuiHnUNxUk8z@Ny5wrjcsCiI0VTIGkmYIRkDRSMAHzzIG0gYKpAkjeRMFCwVzBEixuCKQNgTImYDWmCkZAnglYlYGCGRCaKhgDIYhvAWRbgkwDqQcA "APL (Dyalog Unicode) – Try It Online")
`,⍨\⎕`: Reversed prefixes of the input.
`+\¨`: For each reversed prefix, get the cumulative sums.
`∊`: Flatten into a vector of sums.
`~2|`: For each sum, is it even?
`+/`: Take the sum.
Slightly longer, but more interesting alternative:
```
+/,∘.(≤⍱2|-)⍨+\2+0,⎕
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKM97b@2vs6jjhl6Go86lzzq3WhUo6v5qHeFdoyRtoHOo76pIDX/07jMudK4LIDYWMEUSJopGAFJIwUTMM8cSBsomCqA5E0ULBTMFSzB4oZA2hAoYwJWY6pgBOSZgFUZKJgBoamCMRCC@BZAtiXINJB6AA "APL (Dyalog Unicode) – Try It Online")
`0,⍵`: Prepend a 0 to the input.
`2+`: Add 2 to each number. This makes sure all values are positive while not changing any subsequences parities.
`+\` Take the cumulative sum. Because the vector contained only positive numbers this is strictly increasing.
`∘.( )⍨`: Make a table by applying the inner function between all pairs of values.
`+/,`: Flatten the table and sum all values.
The inner function uses NOR (`⍱`) and might be a bit easier to understand if rewritten with AND (`∧`):
```
(a≤b)⍱(2|a-b) ≡ (~a≤b)∧(~2|a-b) ≡ (a>b)∧(a-b is even)
```
The `a>b` makes sure each subsequence is only counted once.
[Answer]
# [Haskell](https://www.haskell.org/), 44 bytes
```
f a=sum[gcd 2s-1|s<-scanl1(+)=<<scanr(:)[]a]
```
[Try it online!](https://tio.run/##NU5LboMwEN37FG9RKUY1UgyUn3BP0BtYKHIDoVYIqTDd9e50GIo0i/ebN/Plwr0fx3W9wZnw87DDtUMSYv0bmjhc3TRq@RqZptnwLOvItq5dH85PMOieAhjQxBj65cNPPdGxXyC9utSX@hlR5nPu3R3SmFN8ijBQ4nv204IX3CDJ6@ApZsBw69u6V1u0iN9xFrZkoIVNFd4OnCskjFNhE4XssIgWTM@kKOy7ubCklApkVUeyEFYz1RzODrHgxYT17GiohKVMzkNuyvP/GJ0sWa32P/bG3cv/AA "Haskell – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~59 ...~~ 37 bytes
```
->l{*q=r=0,-1;l.sum{|n|q[r^=n%2]+=1}}
```
[Try it online!](https://tio.run/##VY/NDoIwEITvPsUmxosWQ39sIaa8CKkHD5yQSA0HAzx7bXaLDcle5pvZ6dZPz2/obCiafj6P1tuSFfzeXz/Ta16GZWz9ww4n4S6Wr2t4Q9e2xrkjFA2UB5RVkpykZHDbE81AJCKJCAYqxxI0CMvIGWydmqzIKwYxUOctQxZHyHFR7S2DVQJdlTtrcmNe48SMxPl/JB1UoVfTrfTGltDhBw "Ruby – Try It Online")
Finally found the time to implement Bubbler's advice.
[Answer]
# x86-64 machine code, 21 bytes
```
31 c9 f7 e1 ff c1 f6 07 01 74 02 87 d1 01 c8 af ff ce 75 f0 c3
```
[Try it online!](https://tio.run/##XVFRS8MwEH7PrzgqQluyqahDnPNB8F1kL7Lt4ZakbTRNS9LJ6NhftybpbJnhSL77vst9F8ImOWNddyE1Uzsu4Mk2XFbT4pmcUUpuPUfQlhCTaK2nuaq2qEBYi5EnPHgMCNzaVwYE21O/DWS5U0NuRC2wGS84s7PaRtgGXj6Wr/C2fIeV4XJD4WaQP1uwX7Ie/ViRnwx538TLY3vkHAT@m8cytHzIuHATWDla6Bb6KQfKCIeTOSFSN@HlsQcpUvCn@lNKlDooaHJGgRVoIE1d8p2QA@lf68TVBhZwuKYwC3FP4TbEw3EeimrjyrI4upRrHdHez1lZ2YoqizG5OqEUk8RZH0nX/bBMYW67STm7c5v7rYXrIdQv)
Following the standard calling convention for Unix-like systems (from the System V AMD64 ABI), this takes the address of an array of 32-bit integers in RDI and the length of the array in RSI.
Assembly:
```
.text
.global essa
.intel_syntax noprefix
essa:
xor ecx, ecx #
mul ecx # Initialise ECX, EAX, and EDX to 0.
repeat:
# EAX holds the running total of even-sum subarrays.
# ECX holds the number of even-sum subarrays ending at the current position.
# EDX holds the number of odd-sum subarrays ending at the current position.
inc ecx # Increment the even count.
test BYTE PTR [rdi], 1 # Check the low bit of the current number.
jz skip # Jump if the low bit is 0.
xchg ecx, edx # (Executed if odd) Swap the counts.
skip:
add eax, ecx # Add the even count to the running total.
scasd # Advance to the next number, and perform an unnecessary comparison.
dec esi # Count down from the length of the array.
jnz repeat # Jump back if there is more to be processed.
ret # Return.
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes
```
Ẇ§2ḍS
```
[Try it online!](https://tio.run/##y0rNyan8///hrrZDy40e7ugN/h9toWOqY6ljAiQNdQxiD7f/BwA "Jelly – Try It Online")
Similar to my Vyxal answer, but Jelly's builtins are nicer. A monadic link.
```
Ẇ # Sublists
§ # Sum (vectorised)
2ḍ # Is divisisible by 2? (vectorised)
S # Sum (non-vectorising)
```
[Answer]
# [J](http://jsoftware.com/), 17 bytes
```
1#.1#.(0=2|+/)\\.
```
[Try it online!](https://tio.run/##TY69DsIwDIT3PoUFQ6kwIX@kSaVMSExMzN0QVcXCC/DuwdhKVMkZ7r7zxe@yU/0CeYIeEDRM9E4Kro/7rZi9ojnobL/H8zDPqgxd93quH8pkWGAUYVjErXAIF9GOdUCwW20RfIsEKWNLk4u1a2RAbsQ/Tm1DgGHL8JIXkGoVlVhmvrUZ@ZrCgYcijqdyuSMySXKg1HflBw "J – Try It Online")
* `(0=2|+/)` Is sum even...
* `\\.` For each suffix list of each prefix list (so all sublists)? Returns a 0-1 matrix, and now we want to sum all the elements...
* `1#.` Sum the rows...
* `1#.` And sum the resulting list of sums.
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~8~~ 7 bytes
```
#ȯ¬%2ΣQ
```
[Try it online!](https://tio.run/##yygtzv7/X/nE@kNrVI3OLQ78//9/tIGOGRCa6hgDoUUsAA "Husk – Try It Online")
#### Explanation
```
Q # consecutive subsequences
# # count elements by
ȯ # composed function
¬ # not
Σ # sum
%2 # mod 2
```
-1 bytes thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs)
[Answer]
# JavaScript (ES6), ~~44~~ 41 bytes
This is inspired by [Bubbler's comment](https://codegolf.stackexchange.com/questions/237700/even-sum-subarrays#comment539157_237700), but updates the sum \$n\_0(n\_0-1)/2+n\_1(n\_1-1)/2\$ on the fly rather than computing it afterwards. The number of 0's and 1's are stored in `a[0]` and `a[1]` respectively, with `a[]` initialized to `[1,0]`.
```
a=>a.map(c=>t+=a[p^=c&1]++,a=[1,p=t=0])|t
```
[Try it online!](https://tio.run/##fdDBDoIwDAbgu0@xk4EwgQFucBgvQjBZEI0G2SKLJ999zhKjjunS49d/bc/iJqbuelJ6M8p9bw7cCF6L@CJU0PFaR1w0ase7NWmjCAveEKy45mkb3rXp5DjJoY8HeQwOQcPaMETLlyQoXTm0/EmJS3OMth7toxSjzE9zl2YYFZ5gH2VAU6sx@pjbUupS60qMbEP1lW0pcykBRCC4@E8ZfJ2BLt4zWFq51IZRKNuQQ4F@HmuxVwmqmg8xj/Ky1DwA "JavaScript (Node.js) – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/mathematica/), ~~36~~ 34 bytes
```
Tr[1-Mod[Tr/@Subsequences@#,2]]-1&
```
–2 bytes from @alephalpha
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n277P6Qo2lDXNz8lOqRI3yG4NKk4tbA0NS85tdhBWccoNlbXUO1/QFFmXolDenS1eW0sF5xjgcwx1lEwReab6SgYIfONdBRM0JSYg4UMgKI6CihmAUUtdBSA0pZoOgzBQoZgTSZoRgENMQLLmaCZBlRrBkZAFcZgBJRWQPIGWMYS4j6I6UD5/wA)
There is an `EvenQ` test in Mathematica, but alephalpha's use of `Mod` saves 2 bytes relative to it:
```
Count[Tr/@Subsequences@#,_?EvenQ]-1&
```
Alternative 34-byte function from @att:
```
Count[{a__/;2∣+a}]@*Subsequences
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 5 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
ãx èv
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=43gg6HY&input=W1s3XSxbOF0sWzMsIDVdLFs2LCAyXSxbMiwgNCwgNV0sWzcsIDQsIDAsIDUsIDhdLFs0LCA4LCA3LCA5LCA1XSxbMSwgOSwgMSwgMCwgNF0sWzcsIDUsIDIsIDEsIDQsIDhdLFswLCA2LCA2LCA1LCAzLCAzLCA4XSxbOCwgNSwgOSwgNCwgNSwgMSwgMF1dLW0)
```
ãx - subarrays reduced
èv - number of evens
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~50 47~~ 44 bytes
```
g l=sum[1|t<-scanr(:)[]l>>=scanl1(+),even t]
```
[Try it online!](https://tio.run/##TY7LboMwEEX3/YorlIUtGzUGyiMKfEG76pKiCqVWUtU4KDhtF/l3auwaRZrNuWfmak799CWVmucjVD1dh1bczD6eDr2@kB1tO9U09UJKEEa5/JYappuH/lOjxtCPL@8Yr@bVXJ412geQ6XT@gaKMRYgbRIy5ZHP8zx4hf0d5MPIDu9VCLu5NRzeiuKT72BYBpC06ji3lHkoLIkDK8XTPOUdiOQ2ccGR@ZY0KF21tyrF05UHYtOSwuvIXRRDCRcIdZfeicCWJc5lvq4Kzu7kbu5G6cY@vb5TOVP4/3774nHbd/Ac "Haskell – Try It Online")
* thanks to @ovs for reminding me there's already an *even* function in Haskell (3 Bytes saved).
* saved 3 more bytes inspired by @Lynn [answer](https://codegolf.stackexchange.com/a/237741/84844) and [tip for golfing in Haskell](https://codegolf.stackexchange.com/a/52945/84844)
```
sum Total of
[1|t<- * list comprehension counting:
scanr(:)[]l -tails
>>= - concatMapped to
scanl1(+) - cumulative sum
,even t] ? that satisfy the requirements
```
Old recursive version
```
g[]=0
g l=sum[1|t<-scanr1(+)l,even t]+g(init l)
```
```
g[]=0 empty list has 0 even sums
g l= list has :
sum > number of results found in:
even t valid tails
t<-scanr1(+)l directly reduced by +
+g(init l) > + results of inits
```
[Answer]
# [R](https://www.r-project.org/), ~~61~~ 57 bytes
Or **[R](https://www.r-project.org/)>=4.1, 50 bytes** by replacing the word `function` with `\`.
*-4 bytes thanks to [@Dominic van Essen](https://codegolf.stackexchange.com/users/95126/dominic-van-essen).*
```
function(a,b=diffinv(a)%%2,`+`=sum,z=+!b,o=+b)0:z+0:o-z-o
```
[Try it online!](https://tio.run/##VY9NCsMgEEb3PYWlBBQnYEyqScCeJT9FyKIKbdNFLm/tmDQEZjPvfTOOz2BNsLMb35N3tIfB3CdrJ/ehPcsyCR3vzGt@wGL4eQBv@MBEu3DR@nzJfbB0pJqxC8lvRJx@Xb12BXYlkOsBKCByBSUCCaTaQ4lpZCJiINs@hSbiGkj0zT6j0RTIChyrDkbjHomy2hc2KGNaYcVIifX/QLqlRtWkK9MDW0CFLw "R – Try It Online")
Using @Bubbler's formula.
Without it:
### [R](https://www.r-project.org/), 64 bytes
Or **[R](https://www.r-project.org/)>=4.1, 57 bytes** by replacing the word `function` with `\`.
```
function(a){for(i in seq(!a))for(j in 1:i)F=F+!sum(a[j:i])%%2;F}
```
[Try it online!](https://tio.run/##VY/BCoMwDIbve4rIEFrWga3aqsMdfYmxg8gKFaZM52ns2bua6kTIJd/3J00Hq0urp655m74jNf3ofiAGTAfj40WCmtIZtDPghaFVWZ2CcXqS@tYW5k7DUFyqr9WkIYrSI5yvEB3mLls6jl3MIN0ByUAsIEYgGCRbyDOFLHKYwbpPonE4Y@B8vs0oNBwZx7FkZxTuESiTbWGO0qUllovEWP8P@FsyVLm/0j@wBqT9AQ "R – Try It Online")
[Answer]
# [R](https://www.r-project.org/), 45 bytes
```
function(a,x=table(diffinv(a)%%2))x%*%(x-1)/2
```
[Try it online!](https://tio.run/##VY9BCoMwEEX3PcVACSQlUhNtYhb2LtY2IBSFYou3T9MfbRBmM@/9mUxewbfBv8d@HqaRd3Jp5@72fPD74P0wfngnGNNCLOzE@FIocdbB855bIY5UXKk8/Lpm7RS6StJlB4wkvYIKQEuqcygxC1ZGLGnbZ2AibiRF7/KMhVFgCmP1zljs0ZB1XuggY9qgYqRC/T@QbmmgXLoyPbAFTPgC "R – Try It Online")
Uses Bubbler's observation and pajonk's test harness.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `s`, 6 bytes
```
ÞSḢƛ∑₂
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=s&code=%C3%9ES%E1%B8%A2%C6%9B%E2%88%91%E2%82%82&inputs=%5B8%2C%205%2C%209%2C%204%2C%205%2C%201%2C%200%5D&header=&footer=)
Thanks to Lyxal for this version.
```
ÞS # Sublists
Ḣ # Remove the empty list at the start
ƛ # Map to...
∑₂ # Even sum?
# (s flag) sum of all
```
# [Vyxal](https://github.com/Vyxal/Vyxal), 8 bytes
```
ÞS'∑₂;L‹
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%C3%9ES%27%E2%88%91%E2%82%82%3BL%E2%80%B9&inputs=%5B8%2C%205%2C%209%2C%204%2C%205%2C%201%2C%200%5D&header=&footer=)
```
ÞS # Sublists (Including empty array :( )
' ; # Filtered by...
∑ # Sum...
₂ # Is even
L‹ # Length of this -1 (Because empty array)
```
[Answer]
# [Perl 5](https://www.perl.org/) + `-pal`, 56 bytes
```
$"="+";$_=map{//;grep!(1&eval"@F[$'..$_]"),$_..$#F}0..@F
```
[Try it online!](https://tio.run/##FYzNCsIwEITv@xRrDP6gpkmatCml0FNfQiT0EESINlTxIr66ccvA8DEzTApztDlz1rEDa7nv7mP6FEV7nUNa7dQmvMfI@uHMt0Jwf2H7I/dE6@ErheiHnGtwUKKFCjVoNEQ1uUSLDgw6rLGhTJErSg21FjUxdSCxIlksSQ4cUbM8LMvflF636fHMpzTGPw "Perl 5 – Try It Online")
---
# [Perl 5](https://www.perl.org/) + `-pal -MList::Util+(sum)`, 46 bytes
```
$_=map{//;grep!(1&sum@F[$'..$_]),$_..$#F}0..@F
```
[Try it online!](https://tio.run/##FY5PC4JAFMTv71O8aCmlXP@urkbgyVMdO0WIBwlBc1E7RV@9bWRg@DHzeIxpp15ZK@rz0JiP75@eU2s2Trib30NZ3cVeSlE/3KOoAdvqG0hZVtZmpClmRSlHFHECyuABK9aUsOaMc2QhPESaoFUcgdFRwCmkOIY0aVC@flgvf6NZuvE1W880vfWul25eiuK2dP3BwSD3Dw "Perl 5 – Try It Online")
[Answer]
# [ayr](https://github.com/ZippyMagician/ayr), 11 bytes
Thanks to [ovs's](https://codegolf.stackexchange.com/a/237720/90265) method.
```
+/|2|,+\\.I
```
# Explanation
`I` is the input (eg `6 2`) passed through the command line.
```
\. Suffixes decreasing in length
+\ Cumulative sum of each
, Flatten
2| Mod 2
| Not this (is the number divisible by 2?)
+/ Sum; count number of even elements
```
[Answer]
# TI-Basic, 27 bytes
```
fPart(.5cumSum(Ans
{2sum(Ans),1+sum(not(Ans
sum(Ans.5(Ans-1
```
Uses [Bubbler's formula](https://codegolf.stackexchange.com/questions/237700/even-sum-subarrays#comment539157_237700). Takes input in `Ans`. Output is stored in `Ans` and displayed.
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~42~~ 27 bytes
```
.\B|\D
Y`d`01
Cw`(0|10*1)+
```
[Try it online!](https://tio.run/##K0otycxLNPyvquGe8F8vxqkmxoWLKzIhJcHAkMu5PEHDoMbQQMtQU/v//2jzWK5oCyA21lEwBVJmOgpGQMpIR8EEImAOZhkAOToKIHVAjoWOAlDUEiJvCGYZgpWYQNQDVRqBhUwgWoAyZmAElDAGI5CoBZhvCbEIYkIsAA "Retina – Try It Online") Link includes test cases. Edit: Saved 15 bytes thanks to @m90. Explanation:
```
.\B|\D
```
Delete anything that's not the last digit of an integer.
```
Y`d`01
```
Reduce modulo 2.
```
Cw`(0|10*1)+
```
Count the number of overlapping matches with an even number of `1`s.
[Answer]
# JavaScript (Node.js), 89 bytes
```
f=x=>0 in x&&f(x.slice(1))+x.filter((_,i)=>~x.slice(0,i+1).reduce((s,y)=>s+y,0)&1).length
```
[Try it online!](https://tio.run/##VcnRCsIgFIDh@z3FuRoeZjJHUBDuRSJibLoM0aE23E2vbhJE7PL//uewDmH0eokH6yaZsxJJ9C1oC6muFUksGD1KwhGbxJQ2UXpC7lSj6N@/2VLdcGReTq9SJNCt3NBstMW6uJF2jo@8Dh4Wr20EAaOzwRnJjJsvVfVVosj1dEP813lXnEK3g47CsUD@AA "JavaScript (Node.js) – Try It Online")
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 47 bytes
```
a->sum(i=1,#a,sum(j=i,#a,!(vecsum(a[i..j])%2)))
```
[Try it online!](https://tio.run/##LY3rCoMwDIVfJXMMGogyq/PyQ19E@qOMOSpuFHeBPX2XxkJIzvly0nq7ufzuwwxDsPn4@jyUG0o6WopyGVyUB/W9XaO3kyuKxeBJI2Kw3q8/ZSEfwW/u@WaZRZPBrCwiwTS1hnsXW0VwibMh0HFqgjqhVuSZHYFk2XUEjPuUKEWWEqrTCYe1sDpd8a6R4k0lJbgT0O/f7Y8Yg@EP "Pari/GP – Try It Online")
[Answer]
# [Factor](https://factorcode.org/) + `math.unicode`, 34 bytes
```
[ all-subseqs [ Σ even? ] count ]
```
[Try it online!](https://tio.run/##TY9BbsIwEEX3nOL3AERxbJJSJLqs2HRTdYVYuO60jTBOsJ2qFHEa7sOV0iFSauTVezP@M/OhTWx8//qyen56QKB9R85QyOgneh2w0/Er61xtmncaAJ/kyGtb/@pYNy5gS96RTT/Reorx0PraRSwmkyMqnHCH6RI5w/0IgkFidoslihElYwGV6nIIUshZ/WeULBVjhXnqrFgKFoJ71a2suKdgrVLAnHXOc0suSX5pOznsOuOc6xLXrLFS9mtoa6ehe@OjA9a4nEHf5B6xgWk6PnvTCwGn29YekAUYS9r3fw "Factor – Try It Online")
[Answer]
# Scala, 52 bytes
```
_.tails.flatMap(_.inits)count(x=>x.size>0&x.sum%2<1)
```
[Try it online!](https://scastie.scala-lang.org/IpRl4HwDREa4FVXZntPAlw)
This is a naive answer, but it didn't seem as if Bubbler's approach would be shorter, so I went with this. `_.tails.flatMap(_.inits)` first gets all subarrays that stretch to the end, then all the prefixes of those subarrays to get all subarrays of the original array.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~23~~ 20 bytes
```
IΣE²↨¹…№﹪E⊕Lθ↨¹…θλ²ι
```
[Try it online!](https://tio.run/##RYvBCsIwEER/ZY8biKBFQfFmToIF0WPpYUmXppAmbZoIfn2M9eDAwMC8pw0F7cnmfA@Di6hoifhMI9Y0YSXhQgvjTsKDXM@ofCpM7btk/UpcnQ48sovc4Y1dHw3OQvw19daWlfETzhLs96lKB/HLOeemOUo4SDhJ2K@jSNu2zZuX/QA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Uses @Bubbler's formula.
```
² Literal `2`
E Map over implicit range
θ Input list
L Length
⊕ Incremented
E Map over implicit range
θ Input list
… Truncated to length
λ Inner index
↨¹ Converted from base 1 i.e. summed
﹪ Vectorised modulo
² Literal `2`
№ ι Count the number of `0`s or `1`s
… Exclusive range from 0
↨¹ Converted from base 1 i.e. summed
Σ Take the sum
I Cast to string
Implicitly print
```
Each contiguous subarray with an even sum must start and end at a point where the cumulative sums are either both even or both odd. The positions of these sums don't matter, only their counts do. The number of sums for a given count is then simply `n(n-1)/2`, since a given sum can't start and end at the same point. This is readily calculated as the sum of the exclusive range from `0` to `n`. (Both these sums are implemented as base conversion from base `1` since that returns `0` for an empty list whereas `Sum` returns `None`.)
[Answer]
# Excel, ~~130~~ 97 bytes
*-33 bytes applying Bubbler's formula*
```
=LET(x,COUNT(A1#),a,SEQUENCE(x),b,SUM(MOD(MMULT(A1#,(a<=TRANSPOSE(a))*1),2)),b*(b-1-x)+(x^2+x)/2)
```
[Link to Spreadsheet](https://1drv.ms/x/s!AkqhtBc2XEHJnW7R4Ai3XDnmVNZr?e=EAGuNE)
Rearranged Bubbler's formula to use the number of 1s and size of the original array (instead of the number of 0s). Multiplies the array by an upper triangular matrix to calculate the cumulative sums.
## Original Answer not using Bubbler's method
```
=LET(x,COUNT(A1#),a,SEQUENCE(1,x^2)-1,b,MOD(a,x)+1,c,INT(a/x)+1,d,SEQUENCE(x),SUM(1-MOD(MMULT(A1#,FILTER((d>=b)*(d<=c),b<=c)),2)))
```
### Explanation
Since Excel formulas don't really have loops, I have to get creative with in sequences in two dimensional space.
`LET(x,COUNT(A1#),` : x = number of elements
`a,SEQUENCE(1,x^2)-1,` : a = [0..x^2]
`b,MOD(a,x)+1,` : b = array of indices of the first items to be summed
`c,INT(a/x)+1,` : c = array of indices of the last items to be summed
`d,SEQUENCE(x),` : d = [1..x]
`FILTER((d>=b)*(d<=c),b<=c))` : array containing all permutations of possible consecutive sums indicated by 1 in the elements to be summed
`MMULT(A1#,~,2)` : use matrix multiplication to determine all the sums of consecutive elements
`SUM(1-MOD(~,2)))` : count the sums where the sum mod 2 = 0
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~77~~ \$\cdots\$ ~~67~~ 65 bytes
```
t;p;f(a)int*a;{for(int b[]={1,t=p=0};~*a;)t+=b[p^=*a++&1]++;t=t;}
```
[Try it online!](https://tio.run/##bZTbjpswEIbv9ykspFScomLO1KW9qPoUhK1YAlu0W4KCpUaN6KOXDrY57LARyeD5fs8/TCzK43NZjiNnHav1wmhabhbsXl@uOtySpyxP79TmaZc6A/sLyOBW@pR1j6lZWNYHmlsW4ylnwzjJfxVNqxvk/kDgMyV41fMfNMtJSu6RTY50YGvelfkY5z2Z92wSYORLFNrExSiQCPL@OxvDpQegjhDsfCOp8QUCZfJOnVhqqKBUlPKxJlm8AtEnFZqdHXWkDkqE4gK1J669lC6jCoSzfETpP0nngZtC30u13GqrYavoqeirGKgYqhipGKuY2HO3883GTmRa6dY3f6pLrUuN8VEtTbW2yZa7iLuIe4h7iPuI@4gHiAeIh4iHiEeIR4jHiMeIJ4gniFMHD8jBit0IqbGZe3XrqpJX5@UEUXHJ4xOK0ysPMIU1DdXO8tL2nJQ/i6sJv1X5Ul1lAe10@@6ebsk3@AaaTbZrT1O74Z1AxEuhac/VDbY5TN1@nluf21p7XzKMWJZQz6@H9cRCKXlqBc/ZFpNW0XZH135UL9BHK2y2FtOnu4Ks1rVDfzjD0zVfp0f8pGUQeNbkxlpzeOPdQ2H4P4y3HVWQXeaPm5qtcnL8Qg5ncuhPLdj09jLwPk2r2XJ4GMZ/Zf1aPPfj8fd/ "C (gcc) – Try It Online")
*Saved ~~9~~ 11 bytes thanks to [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)!!!*
Inputs a pointer to an array of non-negative integers terminated by \$-1\$ (because pointers in C carry no length info).
Returns the number of contiguous subarrays with an even sum.
Port of [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)'s [JavaScript answer](https://codegolf.stackexchange.com/a/237733/9481).
[Answer]
## Batch, 91 bytes
```
@set/at0=t=e=0,t1=-1
@for %%a in (%*)do @set/ae^^=%%a%%2&call set/at+=t%%e%%+=1
@echo %t%
```
Takes input as command-line arguments. Explanation: Rough port of @Arnauld's JavaScript answer, but starting with `[0, -1]` as preincrement is golfier.
```
@set/at0=t=e=0,t1=-1
```
Start with a cumulative total of `0`, a result of `0`, 1 even cumulative total and 0 odd cumulative totals, but with the totals decremented so that they can be preincremented.
```
@for %%a in (%*)do
```
Loop over the command-line arguments.
```
@set/ae^^=%%a%%2
```
Update the parity of the cumulative total. (`^&1` would also work for the same byte count.)
```
&call set/at+=t%%e%%+=1
```
Increment the count of even or odd cumulative totals respectively and add the new value to the final total. This has to use `call` and `%%` so that `e` gets substituted after its calculation above.
```
@echo %t%
```
Output the final total.
[Answer]
# [Haskell](https://www.haskell.org/), 64 bytes
```
f a=sum[div(d*d-d)2|d<-[sum[1|b<-scanl(+)0a,c b]|c<-[even,odd]]]
```
[Try it online!](https://tio.run/##NU5LboMwEN37FG9RKdDaEr/wiaAn6A0sFBnsUCsEqkCz4u50MEWaxfvNm/lW0930/breoKrp9yG1fXn6XQvtR4suhdy0cGlKMbVq6L0PP1C8RVMvLZnmZQY@al3X9fpQdkAFPTKgQynQmfnLDoZob2Z4ll8v18voU6Z5GnWHV1UncfLRUeLnaYcZb7jBI0/DUqyCg1vf1r3KrIb4RMBk7kDIZMxxPnDKETkcMxlxJIdFNHM0IIVj302ZJCXnIKs4khmToaOhCyeHmLnFyOnJ0VAwSZnUDbmxm//H6GTu1GL/Y2/cvfQP "Haskell – Try It Online")
] |
[Question]
[
This is intended to be an easy, bite-size code-golf.
The [mex](http://en.wikipedia.org/wiki/Mex_(mathematics)) (minimal excluded number) of a finite collection of numbers is the smallest non-negative integer `0, 1, 2, 3, 4, ...` that does *not* appear in the collection. In other words, it's the minimum of the complement. The mex operation is central to the analysis of [impartial games](http://en.wikipedia.org/wiki/Impartial_game) in [combinatorial game theory](http://en.wikipedia.org/wiki/Combinatorial_game_theory).
Your goal is to write a *program* or *named function* to compute the mex using as few bytes as possible.
**Input:**
A list of non-negative integers in any order. May contain repeats. For concreteness, the length of the list and the allowed range of elements will both be between `0` and `20` inclusive.
The definition of "list" here is flexible. Any structure that represents a collection of numbers is fine, as long as it has a fixed ordering of elements and allows repeats. It may not include any auxiliary information except its length.
The input can be taken as a function argument or through STDIN.
**Output**
The smallest excluded number. Output or print it.
**Test cases**
```
[1]
0
[0]
1
[2, 0]
1
[3, 1, 0, 1, 3, 3]
2
[]
0
[1, 2, 3]
0
[5, 4, 1, 5, 4, 8, 2, 1, 5, 4, 0, 7, 7]
3
[3, 2, 1, 0]
4
[0, 0, 1, 1, 2, 2, 3]
4
[1, 0, 7, 6, 3, 11, 15, 1, 9, 2, 3, 1, 5, 2, 3, 4, 6, 8, 1, 18]
10
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 6 bytes
```
h-U21Q
```
# Example run
```
$ pyth -c h-U21Q <<< '[5, 4, 1, 5, 4, 8, 2, 1, 5, 4, 0, 7, 7]'
3
```
### How it works
```
U21 range(21)
Q eval(input())
-U21Q setwisedifference(range(21), eval(input)) # Pyth function. Preserves order.
h-U21Q setwisedifference(range(21), eval(input))[0]
```
[Answer]
## CJam, ~~11~~ 8 bytes
```
K),l~^1<
```
How it works:
```
K), "Create an array with numbers 0 through 20"
l~ "Read the input and eval it, resulting to an array"
^ "XOR the elements of two arrays, resulting in a complement array"
1< "Take the first element of the resultant array"
```
Sample input:
```
[1 0 7 6 3 11 15 1 9 2 3 1 5 2 3 4 6 8 1 18]
```
Output:
```
10
```
[Try it online here](http://cjam.aditsu.net/)
[Answer]
# J - 13 char
```
f=:0{i.@21&-.
```
Very simple actions in J, and thus very hard to make smaller.
`i.@21` creates a list from 0 to 20 inclusive. `-.` performs set-subtracts the input from this list. `0{` takes the first element of what's left, i.e. the smallest number. `f=:` defines a named function. At the REPL:
```
f=:0{(i.21)&-.
f 1
0
f 0
1
f 2 0
1
f 3 1 0 1 3 3
2
f '' NB. empty list
0
f 1 2 3
0
f 5 4 1 5 4 8 2 1 5 4 0 7 7
3
f 3 2 1 0
4
f 0 0 1 1 2 2 3
4
f 1 0 7 6 3 11 15 1 9 2 3 1 5 2 3 4 6 8 1 18
10
```
Since the release of J806 in November 2017, a new syntax exists which saves us one byte by letting us use `i.@21` for the old `(i.21)` in this context.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~5~~ 4 bytes
```
0ḟ1#
```
[Try it online!](https://tio.run/##y0rNyan8/9/g4Y75hsr/D7c/alrz/380F2e0YawOkDQAk0Y6ChCGsY6CIZANJoFsY7AgmAAKGMEETHUUTMBKIAwLsBScC9RtDkQw8yBSEOMNYGZDTIMbaAjTZQa21hCkwhSsyhKiCmY8hG0CVmgBMckilisWAA "Jelly – Try It Online")
Doesn't use the bounds on the input.
...am I missing something?
```
0 Starting with 0,
1# find the first integer
ḟ which is not in the input.
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 4 bytes
```
ℕ≜¬∈
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r//1HL1Eedcw6tedTR8f9/1P9oQx0FAx0Fcx0FMx0FYx0FQyDf0BSIdRQsdRSMIGI6CqYwtglYoQVY0NAiFgA "Brachylog – Try It Online")
Works for any list size and any integer magnitudes.
Takes input from the Output variable, and outputs to the Input variable.
### Explanation
```
ℕ We want a non-negative integer
≜ Assign a value such that…
¬∈ …it is not an element of the list
```
[Answer]
# Golfscript 7
```
~21,^0=
```
A further-golfed version of Peter Taylor's answer. Community wiki since I don't have the rep to comment on his post.
The difference is using the known max list size from the question instead of length +1 to save a character and dropping the irrelevant $.
[Try it online](http://golfscript.apphb.com/?c=OydbNSA0IDEgNSA0IDggMiAxIDUgNCAwIDcgN10nCgp%2BMjEsXjA9)
[Answer]
# [Burlesque](http://mroman.ch/burlesque/) - 9 Bytes
```
20rzj\\<]
```
Takes input from stdin in the format {7 6 5 5 1 2 2 4 2 0}
Explained:
```
20 rz map a range from 0 to 20. (thanks to algorithmshark for the cocde fix)
j \\ swaps the two arrays, and collects the difference between the two into a new array
<] gets the smallest element of the resulting array.
```
Try some examples:
[{1 0 7 6 3 11 15 1 9 2 3 1 5 2 3 4 6 8 1 18}20rzj\\<]](http://eso.mroman.ch/cgi/burlesque.cgi?q=%7B1+0+7+6+3+11+15+1+9+2+3+1+5+2+3+4+6+8+1+18%7D20rzj%5C%5C%3C%5D)
[{5 4 1 5 4 8 2 1 5 4 0 7 7}20rzj\\<]](http://eso.mroman.ch/cgi/burlesque.cgi?q=%7B5%204%201%205%204%208%202%201%205%204%200%207%207%7D20rzj%5C%5C%3C%5D)
[Answer]
# Bash+coreutils, 23 bytes
```
seq 0 20|egrep -vwm1 $1
```
This assumes input as a `|` (pipe) separated list. E.g:
```
$ ./mex.sh "5|4|1|5|4|8|2|1|5|4|0|7|7"
3
$
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
Ṁ‘‘Ḷḟ⁸Ḣ
```
[Try it online!](https://tio.run/nexus/jelly#PY27DYAwDERrmCIDpCCET5gFZRegYQU6JGpqFGomSRYJ5iwjWafL@fyS4z2laaOJ4YphT3OI4cjPmpYz57EsRuM1aQWttWJjtTLkoeQtQggFtQStVg0qbBxW/5Ouexrh8YrxlbCZ9gONXHX41nyNFq2BW4Jn36DomOR86V8 "Jelly – TIO Nexus")
## How it works
```
Ṁ‘‘Ḷḟ⁸Ḣ Main Link; argument is z
Ṁ‘‘ Takes 2 above the largest element in z
Ḷ Takes lowered range (thus returning [0, ..., max(z) + 1])
ḟ⁸ Exclude all elements from the range that are also in z
Ḣ Take the first element (which is the smallest)
```
Thanks to @LeakyNun for -1 byte!
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `gH`, 2 bytes
```
ʀ⊍
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJnQUgiLCIiLCLKgOKKjSIsIiIsIlsxXVxuWzBdXG5bMiwgMF1cblszLCAxLCAwLCAxLCAzLCAzXVxuW11cblsxLCAyLCAzXVxuWzUsIDQsIDEsIDUsIDQsIDgsIDIsIDEsIDUsIDQsIDAsIDcsIDddXG5bMywgMiwgMSwgMF1cblswLCAwLCAxLCAxLCAyLCAyLCAzXVxuWzEsIDAsIDcsIDYsIDMsIDExLCAxNSwgMSwgOSwgMiwgMywgMSwgNSwgMiwgMywgNCwgNiwgOCwgMSwgMThdIl0=) (Includes test cases)
```
# H flag presets the stack to 100
ʀ # inclusive range 0..100
⊍ # set difference
# g flag takes the minimum of the top of stack after execution
# which is implicitly output
```
[Answer]
# [Nekomata](https://github.com/AlephAlpha/Nekomata), 2 bytes
```
ᵏf
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFZtJJurlLsgqWlJWm6Fksebu1PW1KclFwMFVhwc2e0YSxXtAEQG-kogChjHQVDIAtMAtnGQCEgAnKMIBxTHQUTsCSEYQGWgHOB-syBCGIORAJkqAHMRIg5UKMMYerNwFYZguRNwWosIWpgBkPYJmCFFhBzLGIhPgAA)
```
ᵏf
ᵏ Find the first natural number n such that:
f the input does not contain n
```
[Answer]
# [Trilangle](https://github.com/bbrk24/Trilangle/), 53 bytes
```
'0.<_.\.>?0e#L_'\r/(&\,<.|.1.2S<.^#':2',.<..^\,!@.^)S
```
I'm not convinced this is optimal, but I've thought about it for a while and I don't think I can shrink it without substantial restructuring. I have proven that it's impossible to do this general approach without at *least* a grid of size n=8, and this is n=10.
Try it on [the online interpreter](https://bbrk24.github.io/Trilangle/?i=1%200%207%206%203%2011%2015%201%209%202%203%201%205%202%203%204%206%208%201%2018#%270.%3C_.%5C.%3E%3F0e%23L_%27%5Cr%2F(%26%5C%2C%3C.%7C.1.2S%3C.%5E%23%27%3A2%27%2C.%3C..%5E%5C%2C!%40.%5E)S)!
Unfolds to this:
```
'
0 .
< _ .
\ . > ?
0 e # L _
' \ r / ( &
\ , < . | . 1
. 2 S < . ^ # '
: 2 ' , . < . . ^
\ , ! @ . ^ ) S . .
```
[](https://i.stack.imgur.com/z7nES.png)
Equivalent to this C code:
```
#include <stdio.h>
// Read an integer from stdin, throwing out any separators. Returns -1 on EOF.
// Exact implementation is unimportant (and provided by the interpreter).
extern int getint(void);
int main() {
// RED PATH
// Keep a bitfield of the numbers that have been seen so far
int field = 0;
int i;
while ((i = getint()) >= 0)
// GREEN PATH
field |= 1 << i;
// BLUE PATH
// Find the lowest nonzero bit
int missing = 0;
while (field & 1) {
// MAGENTA PATH
field >>= 1;
++missing;
}
// YELLOW PATH
printf("%d\n", missing);
}
```
I am not doing an instruction-by-instruction walkthrough of this code. If you're interested, you can look into the disassembly feature of the interpreter.
[Answer]
## Ruby, 32 bytes
```
f=->n{(0..20).find{|i|n-[i]==n}}
```
Defines a function `f` to be called with an array.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
Another approach. Can be used in a chain with any arity, and doesn't need chain separator or anything.
```
‘Ṭ;0i0’
```
Because the answer is guaranteed to be less than 256, this also works:
# [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes
```
⁹ḶḟµḢ
```
[Try it online!](https://tio.run/##ASUA2v9qZWxsef//4oG54bi24bifwrXhuKL///9bMCwxLDIsMyw1LDdd "Jelly – Try It Online")
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf), ~~5~~ 4 bytes
```
Jr,╓
```
[Try it online!](https://tio.run/##y00syUjPz0n7/9@rSOfR1Mn//0cb6JjrGOoY6RjrWOiY6JjFAgA "MathGolf – Try It Online")
This solution is restricted to just the range 0 to 20, though this can be extended easily by increasing the initial range.
### Explanation:
```
Jr Range from 0 to 20
, Remove elements from the input list from this range
╓ Return the minimum element
```
Alternatively, a 5 byte solution for all numbers:
```
Åï╧▲ï
```
[Try it online!](https://tio.run/##ASkA1v9tYXRoZ29sZv//w4XDr@KVp@KWssOv//9bMCw3LDEsMiwzLDgsNCw2XQ "MathGolf – Try It Online")
### Explanation:
```
Å ▲ Do while true
╧ Does the input contain
ï The index of the loop?
ï Push the number of iterations of the last loop
```
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~18~~ 16 bytes
*-2 bytes thanks to nwellnhof*
```
{(0...*∉@_)-1}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwv1rDQE9PT@tRR6dDvKauYe3/4sRKhTSNaAMdQx0jHWMdEx3TWE1rLiRRBQWcokCx/wA "Perl 6 – Try It Online")
Anonymous code block that counts up until it finds a number that is not an element of the input list, and returns the length of the range minus one
[Answer]
# JavaScript (ES6), 33 bytes
Thanks to [@fhuvi](https://codegolf.stackexchange.com/users/116582/fhuvi) for letting me know that [my answer](https://codegolf.stackexchange.com/a/258384/58563) to [this more recent challenge](https://codegolf.stackexchange.com/q/258335/58563) also works here.
```
a=>a.reduce(m=>m+a.includes(m),0)
```
[Try it online!](https://tio.run/##rZLRDoIgFIbvewouYZGCWtmFvkjjgiE2m0rT7PWJILuwrKkxxs7Z2Pef859z5jfeiqa4XDe1yqTOE82TlHuNzDohYZWk1Zp7RS3KLpMtrBAmSAtVt6qUXqlOMIdHysCCgxDwfUBWAyj5A5QOoQEGC7gj0BADarj2NXHIZkCDIXRR92OemgKDyQX@gm4xiGzvLoitxis1tuzNZd@h4QdPHWXWuBw0elupfkrOh4lWjEBp3@POTp8@8FsrcXASvRkujuzH2JURs@dKEX0H "JavaScript (Node.js) – Try It Online")
[Answer]
# [Rust](https://www.rust-lang.org/), ~~117, 113, 79~~ 78 bytes
```
|l:&[u8]|{let mut r:Vec<_>=(0..22).collect();r.retain(|n|!l.contains(n));r[0]}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=jVK7boMwFJW6ma8wGSJboggT0tCkaZfOHbsgFCFkJCTitNh0Ab6kS4b2o9qv6bUN6YMMtZCx7zn3nGPpvr7VjVTHz4v7QuB9VgpCces4qOIKKy7VLs8kl3iLEwcPi7zw3E1Y6uGAen-qAVTZpBoC9SywgCJgZofzAkjhhHTWCBpC2zDFlh6OjKQ9xIZ6uoLbCj7oXJzLY6k6bjR93ZjVug8BfvEchJDhnkp6ITb6XpmHMq2xNDrXVmcMaM-RIcbWK_YcNAqlnjZgAez_cA3GpFZyaVRXRhhsWTAE0U_WAaIhFJDYyhhjpuMFkwAh-w6QboZxKfD2vVHFZfzx0FXredLEaddqYN8oXK8feX6zu92SwPfDkPr5oap4rgjd1H7NlZ68TnRuBYDQN0kEBQwmqh9US7RxUHGoMdEz6eFMSIpL8XNMW4iVSclrtePPLinIXNep5UI3eqpLoSrhkhlgrQbXdz2F8W6B0c80p3cGw-PR_r8A)
## Explanation
```
|l: &[u8]| {
// Make a vector of the integers from 0 to 21
let mut r: Vec<_> = (0..22).collect();
// Keep only the numbers that aren't in the input
r.retain(|n|!l.contains(n));
// Return the first remaining number in the vector
r[0]
}
```
[Answer]
## GolfScript (10 9 bytes)
```
~.,),^$0=
```
Takes input from stdin in the format `[5 4 1 5 4 8 2 1 5 4 0 7 7]`.
[Online demo](http://golfscript.apphb.com/?c=OydbNSA0IDEgNSA0IDggMiAxIDUgNCAwIDcgN10nCgp%2BLiwpLF4kMD0%3D)
[Answer]
# Xojo, 55 bytes
```
dim x as int8
while a.indexOf(x)>-1
x=x+1
wend
return x
```
[Answer]
# Ruby, 22
```
x=->n{([*0..20]-n)[0]}
```
## Explanation
* Input is taken as an argument to a lambda. It expects an `Array` of `Integer`s.
* The input is subtracted from the array `[0,1,2..20]`.
* Because the `Array` `[0,1,2..20]` is sorted, the first element must be the mex.
[Answer]
# Haskell, 30
```
f s=filter(`notElem`s)[0..]!!0
```
This works for lists of all size and lists beyond 20. This can be made 15 bytes long if Data.List is imported:
```
f s=[0..]\\s!!0
```
[Answer]
## Scheme - 219
```
(define (A X) (define (B X) (if (equal? (length X) 1) (+ (car X) 1) (if (< (- (cadr X) (car X)) 2) (B (cdr X)) (+ (car X) 1)))) (if (empty? X) `() (if (equal? (car (sort X <)) 0) (B (sort X <)) (- (car (sort X <)) 1))))
```
Not very competitive. But I like writing scheme :),
Here's the ungolfed code:
```
(define (minExclude X)
(define (firstNonOneDifference X)
(if (equal? (length X) 1)
(+ (car X) 1)
(if (< (- (cadr X) (car X)) 2)
(firstNonOneDifference (cdr X))
(+ (car X) 1)
))
)
(let ([s (sort X <)])
(if (empty? X)
`()
(if (equal? (car s) 0)
(firstNonOneDifference s)
(- (car s) 1)
))
)
)
```
[Answer]
# R, 27 bytes
Reads from stdin; computes the first element in the set difference between `[0..20]` and `x`.
```
x=scan()
setdiff(0:20,x)[1]
```
# R, 36 bytes
`which.min(y%in%x)` returns the index of the first element of `y` that is not in `x`.
```
x=scan()
y=0:20
y[which.min(y%in%x)]
```
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, 28 bytes
```
$#i++;/\b$#i\b/&&redo;$_=$#i
```
[Try it online!](https://tio.run/##K0gtyjH9/19FOVNb21o/JgnIiEnSV1MrSk3Jt1aJtwXy//83VrBQMFQwUDBRMFIwVzD7l19QkpmfV/xftwAA "Perl 5 – Try It Online")
[Answer]
# Powershell, 28 bytes
```
for(;+$i-in$args){$i++}+$i
```
Test script:
```
$f = {
for(;+$i-in$args){$i++}+$i
#for(;$i++-in$args){}(--$i) # alternative version
}
@(
,(0 , 1)
,(1 , 0)
,(2 , 3, 1, 0, 1, 3, 3)
,(0 )
,(0 , 1, 2, 3)
,(3 , 5, 4, 1, 5, 4, 8, 2, 1, 5, 4, 0, 7, 7)
,(4 , 3, 2, 1, 0)
,(4 , 0, 0, 1, 1, 2, 2, 3)
,(10, 1, 0, 7, 6, 3, 11, 15, 1, 9, 2, 3, 1, 5, 2, 3, 4, 6, 8, 1, 18)
) | % {
$e, $a = $_
$r = &$f @a
"$($r-eq$e): $r"
}
```
Output:
```
True: 0
True: 1
True: 2
True: 0
True: 0
True: 3
True: 4
True: 4
True: 10
```
Explanation:
* Increment `$i` while the `$args` array contains the integer value `+$i`.
* Output a last integer value `+$i`.
[Answer]
# [Prolog (SWI)](http://www.swi-prolog.org), ~~64~~ 35 bytes
*-29 bytes thanks to [@Jo King](https://codegolf.stackexchange.com/users/76162/jo-king)*
```
L+X:-between(0,20,X),\+member(X,L).
```
[Try it online!](https://tio.run/##PY/LCoMwEEV/JbhKcFLiq7UuBPd@QCDNQiEtgo@ggjt/3Y5JLUwyd3JvToidp3768GXrjqMOZcFbs27GjFRALEAyeIWDGVozUwk1ux0FHxrbd8tKVaXLklahhPc0D81Kg90SXpLd7mMAqgKpGQOlIg1K4IqBnC0BEqFyO@oEj7BwiP2QAUmd6UXujP@I9x5YnuONEyououf8UNGVv7unotPPXObpMxfY69QFc8/JtcbffgE "Prolog (SWI) – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `r`, ~~7~~ ~~5~~ 4 bytes
```
₇ʀFg
```
*-2 bytes thanks to lyxal*
*-1 byte thanks to Steffan*
[Try it online](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLigofKgCRGZyIsIiIsIlszLCAxLCAwLCAxLCAzLCAzXSJd) or [verify all test cases](https://vyxal.pythonanywhere.com/#WyJyQSIsIiIsIuKCh8qARmciLCIiLCJbMV1cblswXVxuWzIsIDBdXG5bMywgMSwgMCwgMSwgMywgM11cbltdXG5bMSwgMiwgM11cbls1LCA0LCAxLCA1LCA0LCA4LCAyLCAxLCA1LCA0LCAwLCA3LCA3XVxuWzMsIDIsIDEsIDBdXG5bMCwgMCwgMSwgMSwgMiwgMiwgM11cblsxLCAwLCA3LCA2LCAzLCAxMSwgMTUsIDEsIDksIDIsIDMsIDEsIDUsIDIsIDMsIDQsIDYsIDgsIDEsIDE4XSJd).
Explanation:
```
ʀ # The range 0 to
₇ # 128
F # Filter out items from the range that are in the input list
# (The r flag swaps the arguments)
g # Get the lowest one
```
[Answer]
# [Thunno](https://github.com/Thunno/Thunno), \$ 9 \log\_{256}(96) \approx \$ 7.41 bytes
```
21RAq0sAh
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72sJKM0Ly9_wYKlpSVpuhYrjQyDHAsNih0zIHyo8IKb9tGGOgoGOgrmOgpmOgrGOgqGQL6hKRDrKFjqKBhBxHQUTGFsE7BCC7CgoUUsxBwA)
#### Explanation
```
21RAq0sAh # Implicit input INPUT: [4, 1, 0, 2]
21R # Push range(21) STACK: [4, 1, 0, 2], [0..20]
Aq # Check whether each of the items STACK: [1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
# in the input occurs in range(21)
0sAh # Find the index of the first 0 STACK: 3
# (0-indexed)
# Implicit output
```
[Answer]
# [Julia 0.6](http://julialang.org/), 22 bytes
```
>(x,i=0)=i∈x?x>i+1:i
```
[Try it online!](https://tio.run/##yyrNyUw0@//fTqNCJ9PWQNM281FHR4V9hV2mtqFV5n9lBdeKxNyCnFQuh@KM/HIFO41oQx0FIx0F41hNLi5lhZDU4pJiLofE4uLUohKwbKymgq2tggGymAFEzBBZDGgENmFjHQWg@QZg0hhsC0iJEbISLBbAnYQhY6qjYAI2DMKwACuEc4H2mAMRRJ8xmjsgCqGONEHxD8yFEHsRVpugOQpivhnYK4Yg9aZgPZYQPTCHQNgmYIUWEHMtoEFj8B8A "Julia 0.6 – Try It Online")
Minimally adapted from [MarcMush's recursive solution](https://codegolf.stackexchange.com/a/258847/114865) to a [related challenge](https://codegolf.stackexchange.com/q/258335/114865).
Julia 0.6 supports ternary operators without spaces, which were deprecated in 0.7 and removed in 1.0.
] |
[Question]
[
Given:
* a [blackbox function](https://codegolf.meta.stackexchange.com/a/13706/66833) \$f : \mathbb N \to \mathbb N\$,
* a list of positive integers \$L\$, and
* a list of indices \$I\$,
apply \$f(x)\$ to the elements of \$L\$ at the indices specified in \$I\$.
For example, \$f(x) = x^2, L = [7, 6, 3, 9, 1, 5, 2, 8, 4]\$ and \$I = [3, 5, 8]\$ (using 1 indexing), we apply \$f(x)\$ to the 3rd, 5th and 8th elements, yielding \$[7, 6, 9, 9, 1, 5, 2, 64, 4]\$
---
You may use 0 or 1 indexing for \$I\$. The elements of \$I\$ will be unique (there will be no duplicates), the maximum element of \$I\$ will never exceed the length of \$L\$ (or the length of \$L\$ minus 1, if using 0 indexing) and the minimum will never be below 1 (or 0, for 0 indexing).
Neither \$I\$ nor \$L\$ will ever be empty. \$f\$ will always return a positive integer, and will always take a single positive integer. \$L\$ may be in any order, however, you may decide if \$I\$ is in any specific order (e.g. sorted ascending).
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes
---
## Test cases
```
f(x)
L
I (using 1 indexing)
out
f(x) = x²
[14, 14, 5, 15, 15, 10, 13, 9, 3]
[1, 3, 4, 5, 6, 7]
[196, 14, 25, 225, 225, 100, 169, 9, 3]
f(x) = x+1
[7, 12, 14, 6]
[1, 2, 3, 4]
[8, 13, 15, 7]
f(x) = σ₀(x)+x
[13, 11, 9, 15, 16, 16, 16, 11, 6, 4]
[2, 4, 6, 8, 10]
[13, 13, 9, 19, 16, 21, 16, 13, 6, 7]
```
where \$\sigma\_0(x)\$ is the [number of divisors function](https://en.wikipedia.org/wiki/Divisor_function).
This is a builtin in Jelly. [This](https://tio.run/##y0rNyan8f7gtRfv/4fZHTWseNe48tOz/o8Yth7YGVSQ83NX1cMfiiIc7Ww5t9YJwfCJUHu5cBBQ5vNzh/38LAA) is a program where you can modify the function \$f\$ in the Header, and it will generate a random `L`, `I` then `out` on separate lines. The final test case is prefilled into the Header.
[Answer]
# [Scratch 3](https://scratch.mit.edu), ~~16~~ 13 blocks
[](https://i.stack.imgur.com/ocNtF.png)
[Try it online!](https://scratch.mit.edu/projects/525686367)
Scratch functions can't `return`, so the function `f` must edit variable `x`.
[Answer]
# [Python 3](https://docs.python.org/3/), 38 bytes
```
def f(p,a,i):
for q in i:a[q]=p(a[q])
```
[Try it online!](https://tio.run/##NYuxCoMwFEXn5ivumMgbrGkLDfglIcMrGhpoYxQH/fr4pHQ4nDucW/b1PWVb6zBGRF2IKRmnLnFaMCNlJMd@Dn3Rp0xl9PDXG@HkLvrTCpbwJNigov7w9zUwNocNTYOOwAQvkSzJfudHMKosKa@aTT0A "Python 3 – Try It Online")
-16 bytes using in-place thanks to dingledooper
# [Python 3](https://docs.python.org/3/), 51 bytes
```
def f(p,a,i):exec("a[i.pop(0)]=p(a[i[0]]);"*len(i))
```
[Try it online!](https://tio.run/##NYvBCsIwEETv/Yqlp92wSDUqWOmXhBxWm2CgpkF6iF8fV8TDY2bgTXlvjzXb1uYQIWJh4URjqOGOvbi0K2vBgfxUUJcbvKdrb5aQMRE1gQnc/sjw5aTxZ1Asw4XB@i7iIs/bLFBHqGAMHBiEwamkTbXf@eypK6@UNxRqHw "Python 3 – Try It Online")
Inlining with `exec` does not make it any shorter. But oh well, it was an idea :P
[Answer]
# [tinylisp](https://github.com/dloscutoff/Esolangs/tree/master/tinylisp), 104 bytes
```
(d g(q((L I F _)(i L(c(i(e(h I)_)(F(h L))(h L))(g(t L)(i(e(h I)_)(t I)I)F(a _ 1)))L
(q((F L I)(g L I F 0
```
The solution is the unnamed lambda function represented by the second line. Uses 0-indexing. Requires that the list of indexes be sorted ascending. [Try it online!](https://tio.run/##dVHRaoNAEHzPVwz0ZZdS8LzEkKe8BCEg/kIwatKDS0zUFPL1djdaTUMLiyczs@Pc2Lrz3bvm0nVU4EhXogRbxNgxOSSUk6OSPrFlAWJ5SZiH55FaOZ/5Vo4tx5RhB8PMyUw8D@oZQ1xlBb150JGvsgLe7eusvvNMhOUBzfWW1SXIZ6d9kYFSBp1uPkSKVOx6kTegK8jMIbOA6SeAsVjBjjLXywKEsFBhpNRgET64JUyoJtG0JETQVmozSHd5dTu3H4X7ck1VN0/ZsMGb5HMHUCm5/VpSbhQ45w/idTPtqc2wo3hRNmuxSaetN@YxzL9f/tPcIJgqsn1FFsZIKdpP9DMGEebThQeldLTAEqtHR97MaPwZUrczAjaXXJhQGc0qFbpwhK3CvwK@631fQ4q7ZnOWu28 "tinylisp – Try It Online")
### Explanation
Our approach is to define a helper function `g` that takes a fourth argument representing the current index. Then we walk through the list recursively, incrementing the index each time. If the current index matches the head of the list of indices, we call the function on the head of the list of values and cons the result to the recursive call; otherwise, we cons the value unchanged.
Ungolfed:
```
(load library)
(def _helper
(lambda (func ls indices index)
(if ls
(cons
(if (equal? (head indices) index)
(func (head ls))
(head ls))
(_helper func
(tail ls)
(if (equal? (head indices) index)
(tail indices)
indices)
(add2 index 1)))
nil)))
(def apply-at-indices
(lambda (func ls indices) (_helper func ls indices 0)))
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
Çṛ¡"Ṭ}
```
[Try](https://tio.run/##y0rNyan8f2jT/8PtD3fOPrRQ6eHONbX///@PNjTRUQBhUyAFwwZAbKyjYKmjYBwLVAGkdBQgSsx0FMxjAQ "Jelly – Try It Online") [it](https://tio.run/##y0rNyan8/6hhxv/D7Q93zj60UOnhzjW1////jzbXUTA0AmITHQWz2P/RhjoKQJ6xjoJJLAA "Jelly – Try It Online") [online!](https://tio.run/##y0rNyan8f7gtRfv/4faHO2cfWqj0cOea2v///0cbGusoGBrqKFgCKVMgNkPCQGEgZRL7P9oISIE5FkBhg1gA "Jelly – Try It Online")
For the sake of not leaving anything too important in the comments, the built-in solution is `Ç€⁹¦`.
```
" For each element of the left argument and each corresponding element of
·π¨} a list of ones at the indices in the right argument and zeroes elsewhere,
Ç apply the given function to the left element
¬° a number of times equal to
·πõ the right element.
" (For elements of the left argument past the end of the right argument, leave them unchanged.)
```
[Answer]
# [JavaScript (V8)](https://v8.dev/), 31 bytes
```
(a,g,p)=>p.map(i=>a[i]=g(a[i]))
```
[Try it online!](https://tio.run/##rZDBboMwEETv/oo54tQ02GkhBJkq34E4WBSQKxUs46D066ldpznlmMPsSusdzfN@qVUtndXGpetxG@SWKDYyQ2VtXr@VSbSsVaPbj1DkmIRGTxndVmWhrFU/kGj4G0PQu2//yrwODCXDoa0IGZK/bYYrZO3LbgfBvNM/M0RrzlC0MTTsaKTglFbY73HuuvkyOQyzBU/19Nlf9TRiHuD6xaFTS78QYqyeXMyhFUEwNrzMI5vwCeJeeBb48vIGSMj9L4Wfi2jJH4G/gEduEdGfTnyMhwtHLNrtFw "JavaScript (V8) – Try It Online")
Produces output by modifying the input array in place.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes
```
ZLåÅÏs.V
```
[Try it online!](https://tio.run/##yy9OTMpM/f8/yufw0sOth/uL9cL@/4820jHRMdOx0DE0iOWKNjTWMTTUsdQxNNUxNIMhQ6C8SSyXy@GJ6doA "05AB1E – Try It Online") Uses 1-based indexing.
```
ZLåÅÏs.V # full program
ÅÏ # for elements in...
# implicit input...
ÅÏ # where corresponding element in...
å # is...
# (implicit) each element in...
L # [1, 2, 3, ...,
Z # ..., largest element of...
# implicit input...
L # ]...
å # in...
Z # implicit input...
ÅÏ # is 1 replace current element in map with...
.V # result of running...
s # implicit input...
.V # as 05AB1E code
# (implicit) exit map
# implicit output
```
[Answer]
# [J](http://jsoftware.com/), 13 bytes
```
1 :'u@{`[`]}'
```
[Try it online!](https://tio.run/##TY1BC4JAEIXv/opHl3VrFUdNc6GIgk7RoatEQmnZwQ4iBNFv30a3Ipg3MG/efHMzI19UmGsIKATQLM/Her/dGIIW3fJZ5MXhJYx0disfXVu2HKmbc/mom4tTnq53uJQlChQrhFPWr1EQcEsyBa5IwtNwj4QJiEcFznOIL1MJd6xRyYFB1qevekZkEZ93M@v02/SfihARYoYtBljKkdDyEvMG "J – Try It Online")
An adverb modifying the function, taking the 0-based indexes as left arg and `L` as the right arg. Called like:
```
indexes black box function
v v
0 1 2 3 (>: f) 7 12 14 6
^
list L to transform
```
This is just a very thin wrapper over the gerund form of J's Amend adverb, using `{` to pluck the values we want to transform and then applying our black box function to them `@u`.
[Answer]
# [Factor](https://factorcode.org/) + `math.unicode`, 50 bytes
```
[ '[ _ ‚àà [ call ] [ drop ] if ] with map-index ]
```
[Try it online!](https://tio.run/##JY6xCsIwGIT3PsVtTpbWqqA@gLi4iFMoEtK/GIxpmqRoke59Tl8kphWO44Pvhqu58I0N18vpfNzjyf19rrTTUjQVobY9HmQ1KThqO9KCHIwl73tjpfY4JAmDa1EmH@TrKRvk/2TIC@xQYIguwyrSZLcYAsOC4YbvOIJBcKVQRqhsYyLIOtZLzlfMUuqK3ijDvErDDw "Factor – Try It Online")
## Explanation:
It's a quotation (anonymous function) that takes a quotation with stack effect `( x -- x )`, a sequence of values, and a sequence of 0-indexed indices (in that order) from the data stack as input and leaves a sequence of results on the data stack as output. Assuming `[ sq ] { 4 5 } { 0 }` is on the data stack when this quotation is called...
* `'[ _ ‚àà [ call ] [ drop ] if ]` Place a quotation on the stack for `with` to use later. However, `'` starts a *fried* quotation, which says to slot whatever is on top of the data stack into the `_`. When `_` appears on the left side of a quotation like this, it's just a shorthand for `curry`ing a quotation.
**Stack:** `[ sq ] { 4 5 } [ { 0 } ‚àà [ call ] [ drop ] if ]`
* `with` Partial application on the left. It sticks the `[ sq ]` into the quotation in such a way that it comes *before* whatever the following combinator puts on top of the data stack.
**Stack:** `{ 4 5 } [ [ sq ] [ { 0 } ‚àà [ call ] [ drop ] if ] swapd call ]`
* `map-index` Apply a quotation to each element of a sequence, collecting the results into a sequence of the same size. However, `map-index` will also place the index of the element being mapped on top of the data stack. Inside the quotation during the first iteration now...
**Stack:** `4 [ sq ] 0 { 0 } ! element, function, index, indices`
* `‚àà` Shorthand for `member?` Returns `t` if the object second from the top is in the sequence on top of the stack.
**Stack:** `4 [ sq ] t`
* `[ call ] [ drop ]` Push some quotations for `if` to use later.
**Stack:** `4 [ sq ] t [ call ] [ drop ]`
* `if` If third from the top is `t`, call the first quotation, otherwise call the second.
**Stack:** `16`
* Now `map-index` collects this result into the sequence it's building and proceeds with the next iteration.
**Stack:** `5 [ sq ] 1 { 0 }`
* This time, the index is not found in the indices, and so `[ sq ]` gets `drop`ped instead of `call`ed.
**Stack:** `{ 16 5 }`
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 6 bytes
Full program which is just a thin cover for [the built-in `@` ("At") operator](https://help.dyalog.com/latest/Content/Language/Primitive%20Operators/At.htm). Uses whichever indexing APL currently uses (can be 0 or 1).
```
⎕¨@⎕⊢⎕
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKO94P@jvqmHVjgAyUddi4AkSPC/AhgUcBma6CiAsCmQgmEDIDbWUbDUUTDmMgQSOgoQBWY6CuZc1Y96t2oZ1XLBDDAHKjaCmGEGUm0E0QBWp22IUAcy0dAQbCrYEjMkbAg224TLCGwTkGkBcgXEiEedix51rAKyHnWseNS7GcioBQA "APL (Dyalog Unicode) – Try It Online")
`⊢⎕` on \$L\$
`@‚éï`‚ÄÉat indices \$I\$
`⎕¨` apply \$f\$ to each
---
Without the built-in:
```
L←⎕
L[I]←⎕¨L[I←⎕]
L
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKO94L/Po7YJj/qmcvlEe8ZCmIdWANkQZiyXD0jVfwUwKOAyNNFRAGFTIAXDBkBsrKNgqaNgzGUIJHQUIArMdBTMuaof9W7VMqrlghlgDlRsBDHDDKTaCKIBrE7bEKEOZKKhIdhUsCVmSNgQbLYJlxHYJiDTAuQKiBGPOhc96lgFZD3qWPGodzOQUQsA "APL (Dyalog Unicode) – Try It Online")
`L←⎕` get \$L\$
`L[`…`]` extract the following elements from \$L\$:
 `I←⎕` get \$I\$
`⎕¨` get \$f\$ and apply it to each
`L[I]‚Üê`‚ÄÉlet those values replaces the values in \$L\$ at indices \$I\$
`L`‚ÄÉprint the updated \$L\$
[Answer]
# [R](https://www.r-project.org/), 38 bytes
```
function(l,i,f){l[i]=sapply(l[i],f);l}
```
[Try it online!](https://tio.run/##K/qfrmCj@z@tNC@5JDM/TyNHJ1MnTbM6Jzoz1rY4saAgp1IDxAaKWefU/k/XMLQyNNAxtDLVMtKB66nQrIgz0vwPAA "R – Try It Online")
1-based indices.
If we can assume that `f` is vectorized (perhaps by use of `Vectorize()`), then this would be 31 bytes:
```
function(l,i,f){l[i]=f(l[i]);l}
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 7 bytes
```
z?⁰IM€N
```
[Try it online!](https://tio.run/##yygtzv6v8Kip8dG0hf@r7B81bvD0fdS0xu/////RhjrGOiY6pjpmOuaxQJ6JjiGIZwhBBjqGxjqWOsaxAA "Husk – Try It Online")
Husk probably needs a builtin for this and/or for converting a list of indices into a boolean mask.
### Explanation
```
z?⁰IM€N Inputs: function, indices, list of values
M€N Build a list saying for each natural number if it is present in the indices
z Pair each element of this list to one of the values and
? if it is truthy
⁰ apply the input function
I else, apply the identity function (leave the value unchanged)
```
[Answer]
# [Raku](http://raku.org/), 17 bytes
```
{@^h[@^i]».=&^f}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/2iEuI9ohLjP20G49W7W4tFqQjENiUVFipYKtQrShiY4CCJsCKRg2AGJjHQVLHQXjWGuFNA2tQ5t0oFp0FGwMFIwUjBVMFEwVzOw0rRWKE2HG/QcA "Perl 6 – Try It Online")
0-based indexing. Modifies the input array in-place.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 33 bytes
```
->g,l,i{i.map{|x|l[x]=g[l[x]]};l}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y5dJ0cnszpTLzexoLqmoiYnuiLWNj0aRMXWWufU/i9QSIvWtcurztPKq9WJNjTRUQBhUyAFwwZAbKyjYKmjYByrEw3kGQFZOgoQVWaxsf@jDS3NINqMgCJGcMLQAKTVzBKqFwA "Ruby – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), ~~46~~… 44 bytes
* -1 byte thanks to [Unrelated String](https://codegolf.stackexchange.com/users/85334/unrelated-string), by reminding me that infix is not always better.
* -1 byte thanks to [xnor](https://codegolf.stackexchange.com/users/20260/xnor), by suggesting `take`/`drop` instead of `splitAt`.
```
foldl.h
h f l i=take i l++f(l!!i):drop(i+1)l
```
[Try it online!](https://tio.run/##ZY1Na4NAEIbv/ooh9KBkNsRNIyiu0GOhtx5NAuLHunTiim7BQn97NyNpS6GHd2f24X2YvprfWiKv1cl3lhra9UEPHRCYz3DB9@wjysU8knFPDgyQWrbbDhj7a2UG1dgAKBdTWzX5Q6Fb92KGNgCTi3BlWfbqJjNoUZTPgztHfzv2vzZy14U6vMiI7ytlcbNc5AYJDdrIl/Ejwpojj5/sOQeEFOFwDkr@Sd4Q7q2EUZwmd0sykL9PvF/NJP1Wv@qOKj17UY/jDQ "Haskell – Try It Online")
The relevant function is `foldl.h`, which takes as input `f`, `l`, `i`. The list of indices `i` is `0`-indexed.
## How?
```
h f l i=take i l++f(l!!i):drop(i+1)l
```
The function `h` applies `f` to the `i`-th element of the list `l`. Since Haskell is very unappreciative of mutable variables, the only way to do it is concatenating the first `i` elements of `l`, then `f` applied to the `i`-th element, and finally the rest of `l`.
---
```
foldl.h≡\f l i->foldl(h f)l i
```
This repeats the previous function for all the indices in the input list `i`.
---
# [Haskell](https://www.haskell.org/), 33 bytes
```
foldr.adjust
import Data.Sequence
```
[Try it online!](https://tio.run/##fYtNC4IwHIfv@xQjOihsoqsEQzt1Cbp1tIKhc63mZnNCn7416YUg6PD7v/x4nhPtL0xKJ9pOGwvX1NJox64DUxUDvNi7RsvaRLQ@D70FGP9SrqVCFbUGUOa4Mbrdit5GhtE6n644s1uhGIAix8HYLZc7a4TieFVulD2E34z@43desgEPjiSUUBSFRpPbkUyQRALp0JXJHMExC7/eiX1mCGYIzg6g9B/xF4JPKvVVkqVPi/iCfEYSj2aavdR71UjKe4errnsA "Haskell – Try It Online")
Basically the same solution, but uses the `Seq` type from `Data.Sequence` instead of a `List`. The `import` is costly, but the `h` function from the above solution is already implemented as `adjust`.
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/), 10 bytes
```
{ùîΩ‚åæ(ùﮂä∏‚äè)ùï©}
```
[Try it online!](https://mlochbaum.github.io/BQN/try.html#code=X0Yg4oaQIHvwnZS94oy+KPCdlajiirjiio8p8J2VqX0KCjHigL8zIOKIml9GIDHigL8y4oC/M+KAvzTigL82)
To show off structual under `‚åæ` which is a little bit more powerful than J's `&.` as I found out yesterday. `{‚Ķ}` defines a block where we get access (among other things) to `ùï©` as the right argument, `ùï®` the left, and `ùîΩ` the function that gets modified. So this calls `ùîΩ‚åæ(ùﮂä∏‚äè)` with `ùï©`. `‚åæ` executes the right part, then the left part, and then the inverse of the right part. But unlike `&.` it also remembers the original array at the inverse step, so it can be used to update the array. So `ùﮂä∏‚äè` takes the elements of `ùï©` at the indices of `ùï®`. On these elements `ùîΩ` gets called. Then the elements get re-inserted into the original arrays at the indices of `ùï®`.
[Answer]
# x86-16 machine code, 11 bytes
```
I_LOOP:
AD LODSW ; next index into AX
97 XCHG AX, DI ; index in DI
8A 01 MOV AL, BYTE PTR[BX+DI] ; AL = value of L
FF D5 CALL BP ; call BlackBox (tm) function
88 01 MOV BYTE PTR[BX+DI], AL ; value of L = AL
E2 F6 LOOP I_LOOP ; loop until end of I
C3 RET ; return to caller
```
`L` list at `[BX]`, `I` list at `[SI]` (zero indexed), `I` length in `CX`. BlackBox function at `[DS:BP]`, input value/return in `AL`.
Example run with DEBUG. The "interesting" parts have been highlighted for those who don't speak DEBUG.
[](https://i.stack.imgur.com/3vrhR.png)
[Answer]
# [Lua](https://www.lua.org/), 67 bytes
```
function g(f,l,i)for k,v in pairs(i)do l[v]=f(l[v])end return l end
```
[Try it online!](https://tio.run/##XYzNCsIwEITveYqhpwSWotYfPPRJRKHYRBZDIrGJBemz15RaDx6GWdj5Phub0dbv9ZYwZZdrySqnIhwJ1SA4b/JBmEd7wmEQJrprx97ByF4F3cXg0F820K4df7@bNGSJlfEBd0pgh0fD4SlZtR72lM61kVOpjOFrsbPjH1lcmRTsy1fgTstUlgUVSkzEBw "Lua – Try It Online")
Uses 1-indexing, i always forget lua uses 1 indexed tables
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 14 bytes
```
Yd{diyI^n_aaMm
```
[Run and debug it](https://staxlang.xyz/#c=%7BYd%7BdiyI%5En_aaMm%7DXd%0A%0A%7BJ%7D%22%5B14,+14,+5,+15,+15,+10,+13,+9,+3%5D%5B0,+2,+3,+4,+5,+6%5D%22ex%21JP%0A%7B%5E%7D%22%5B7,+12,+14,+6%5D%5B0,+1,+2,+3%5D%22ex%21JP%0A%7Bc%3Ad%25%2B%7D%22+%5B13,+11,+9,+15,+16,+16,+16,+11,+6,+4%5D%5B1,+3,+5,+7,+9%5D%22ex%21JP%0A&i=)
The fully manual method, takes args as `block arr arr`. Requires 0-indexed indices.
the final result is put on the top of the stack.
The single byte builtin for this which takes args `arr arr block` is `&`.
[Answer]
# [Icon](https://github.com/gtownsend/icon), 43 bytes
```
procedure a(L,I,f)
L[k:=!I]:=f(L[k])&\z
end
```
[Try it online!](https://tio.run/##jZBBDoIwEEX3PcXAwrTahYBCxHAAkt4AWRAoSWMsUkDRy2Nro6Irm/x0JvPyf2ZE2chpOqum5NWgOBSY0ZTWBLHsGCdOmsdJjXWdk8XhjrisZmzX4pEg0E/xflASxuVoEIQ@jJDlL7TyfqFTISS2EIuTzNtQMNrq76W1VkBhRyHIn2BqQN1RsGRIIbITu0LXWkN@4eoGVyV63mGHURdcsre9jnxnRtrft7HhV4BvM@bWeqd/vM2xHg "Icon – Try It Online")
[Answer]
# C#, 50 bytes
```
(f,L,I)=>L.Select((v,i)=>I.Contains(i+1)?f(v):v);
```
Online demo: <https://dotnetfiddle.net/M4YbOx>
[Answer]
# Scala 3, 50 bytes
```
f=>I=>_.zipWithIndex.map((?,i)=>if(I(i))f(?)else?)
```
[Try it in Scastie!](https://scastie.scala-lang.org/NVu7zufdTbaRXbOz0ggaCA)
Stupid function parameter names ftw! Indexing starts at 0.
```
f=> //The blackbox function
I=> //The Set of indices
_ //The list of integers
.zipWithIndex //Zip each element with its index
.map((?,i)=> //Map each element `?` and its index `i`
if(I(i)) //If the Set of indices contains i
f(?) //apply f to ?
else ? //Otherwise, just return ?
)
```
[Answer]
# Java, ~~42~~ 38 bytes
```
(a,i,f)->{for(int j:i)a[j]=f.f(a[j]);}
```
*Saved 4 bytes thanks to [Olivier Grégoire](https://codegolf.stackexchange.com/users/16236).*
[Try it online!](https://tio.run/##jVLBTsMwDL33K3xsURYBAySoNokLN8Rh4jTtELpkSumSKnHLpmrfXpwmAwEXLFlJ/OznZ7e16MWs3r6Pet9ah1DTm3eoG/7onDj6MvsDqM5UqK3hr0a440srnUDryixru7dGV1A1wnt4FtrAkAGZNiidEpWElW166WDord6CD4@cwPUGhHMM4lWbra6kZ/CU@oAqytMvojM2UAhUICGw7fCc6VEgSUn9fDwWYy6YZqqYLQdl3VRVP@hCrOvNQnGVhwsxjIGhnHjSSIlukr2nwfIVOm12k/CdL@KYwVB6zI38iLMMVzcMgt/ScfZL8jmDewbzE4PvXIpfU4xBzL8j8DBbHi4ORZQSB2ud7gXKH4qmpv/a47fQuBIev0GqSvkqNQy2OnqUe2475NTZYGPy@F9wtHEHobj4kngaPwE)
[Answer]
# [C (clang)](http://clang.llvm.org/), ~~54~~ \$\cdots\$ ~~52~~ 43 bytes
Saved 9 bytes thanks to [att](https://codegolf.stackexchange.com/users/81203/att)!!!
```
f(g(),*L,*I,n){for(;n--;)L[*I++]=g(L[*I]);}
```
[Try it online!](https://tio.run/##fVTbjtowEH3nK0aRqGJjVGx22dJs2odqV0LiD1iEolzYqJClCbRREb9eOmPHuS0tkpPYc86ZC@MJx@EuyLbXa@JuXSb4UvCFyNg5ectdLxuPPbZc8cVotPa3Ln2tmXe5ptkRih@5WzI4Qx4fT3kGJXAoPbgMyHjYnYqN7NlHIK29SLf7YLIhWGlQdJqDD8oDdA0u7SOzj@CRlEejiCFk5EM5jHx/4lllPDOeDzmyiMkDoQV3pFzLpSiHrBTldiSXMtCMxHWGxTByhJt@dQQ4nx2HCQhWKeaKqjrgfZBmWiTIt6GA8DXIOafNTzY4DwB/ZHR5csrCYrVmhGXo74xlElU5RCfti6dpWgmItsmCfYxcYjkl54pi0VWjD0OlWmGyTkUmn8e4OE4MS94JoHWPL7smuKYC5gKmPZI0pAcEKMOb9RCqkkW@lFpDS85aC4/xddcQuWZWaejYhPFmXqrnYrMzyCL9Hb8lriawj9WOmy3VrbbKrlV2raprVazlLs2iqk4YEmaMWZlazbogWYOkwXXNtihaANlYv3k7fYSkof0fyafQovqpulK95AncxK93dXIk0bHJjk11bJ204/IQh8fY5i7nM/NnK4xd1Q85oXxn83edYulVVT6ZdqI@eLiBaneM6To5N52iZNUxU90xD@2SWbYh1wGLxnnzqTr3JnyNw@9xjkTQ1@alfFIv5fwbrnu6Na391F6aZh5kUVxWM0F/PtqKWmdNVesTPTgIjaNFyzV3/7m@9WYKaNjaq1EmZLrlFaS68X2cHUoJ3XYfhoWAJb5XmBARmNf2y7XN3Lm@kB6BlRV77aYfdylwTPYkF0iyfXxLNDP2f2li7GuhRVYO6/tbYBatw8R9xvQQ3T3WYTyhQt0bt@I4BEWBGNmS@9@wJ/QHH5Y42X3/CZ834obxF3gXNBqWt7PpVa@RGRYvmSPqBiXf6wp4GVyuf8JkF2yL6/jXXw "C (clang) – Try It Online")
Inputs a pointer to a function \$g\$ (inputting an `int` parameter and returning an `int`), a pointer to an array of positive integers \$L\$, a pointer to an array of \$0\$-base indices \$I\$, and \$I\$'s length \$n\$ (since pointers in C carry no length info).
Updates \$L\$ in place.
### Explanation
```
f(g(),*L,*I,n) // golfed function signature for:
// int f(
// int (*g)(int),
// int *L,
// int *I,
// int n
// )
{ //
for(;n--;) // loop over I
L[*I ]= // assign L at current index in I
g( ); // to g's return value of
L[*I] // L at current index in I
++ // bump I to next index
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 5 bytes
```
MapAt
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n1aaZ/vfN7HAseR/QFFmXkk0UCBaOc5IQU1HodrQREcBhE2BFAwbALGxjoKljoJxLVBJtSGIBDNNa2tjY/8DAA "Wolfram Language (Mathematica) – Try It Online")
Takes input in a slightly annoying format: to apply `f` to `{a,b,c,d,e}` at positions `{1,3,5}` and get `{f[a],b,f[c],d,f[e]}`, we write
```
MapAt[f, {a,b,c,d,e}, {{1},{3},{5}}]
```
Some other varyingly built-in solutions:
* **18 bytes:** `MapAt[#,List/@#2]&`. Takes input `[f,I][L]`. The `{{1},{3},{5}}` syntax bothers me a little, so this lets `I` be an actual list.
* **~~20~~ 19 bytes:** `Map@#~SubsetMap~#2&`. Takes input `[f,I][L]`. `SubsetMap` differs from `MapAt` in that it applies the function to all the elements at some indices at the same time.
* **27 bytes:** `(s=#3;s[[#]]=#2/@s[[#]];s)&`. Takes input `[I,f,L]`. Here, we assign the input to a variable, and manually change the values at positions indexed by `I`.
[Answer]
# [Zsh](https://www.zsh.org/), 36 bytes
```
for x;grep -xq $[++i] f&&F $x||<<<$x
```
[Try it online!](https://tio.run/##qyrO@G@XxlWcWqJgaAJCpgqGEGSgYGisYKlgzOWmoWljY6MSrWKopWUU@z8tv0ihwjq9KLVAQbeiUEElWls7M1YhTU3NTUGloqYGpLTi/39DLmMuEy5TLjMucwA "Zsh – Try It Online")
Expects a [function predefined as `F`](https://codegolf.meta.stackexchange.com/a/13707), the operand array as command-line arguments, and the indeces from the file `f`, each on one line.
`for x;`: for each `$x` in the command-line arguments:
* `$[++i]`: increment `$i` (which starts at 0 implicitly)
* `grep -xq f`: check if `$i` is present in the file `f`
+ `-q`: return success/failure only, don't print matching lines
+ `-x`: require the whole line to match `$i`. Otherwise `14` would erroneously match `4`
* `&&`: if that succeeds:
+ `F $x`: call `F` with the argument `$x`
* `||`: else:
+ `<<<$x`: just print `$x` unaltered
[Answer]
# [Julia](http://julialang.org/), 19 bytes
```
f*L*i=L[i]=f.(L[i])
```
with 1-based indexing
changes `L` itself as the output
[Try it online!](https://tio.run/##hZBNCsIwEIX3OcVshEaDdFJNrZAb9AalgosWIlqlWshS9IDewYvU/DStK11MZhhm5n15h@6o9qj7vp7ncyXzQpWyXkY2076ONAUJesdJbnKBKwY21iaFiE0kDDIGSUmUmzIlAz8mGKQlqVw7E36bmz4fH4ztBZGFE46DXFrV3I5NlNOplLKihASmBXqm1Gxzf1hMANwzDNIbz2h50/8Kr@f7cfcq1@4U6ZmSMob63IKSuNU0IIS5hR7csRLo/uGcEV@BzorVAMidPaZhweLgTzI6iZlf4zisJ8HJ3@z9Bw "Julia 1.0 – Try It Online")
[Answer]
# MMIX, 44 bytes (11 instrs)
Takes `f`, `L`, `I`, `len(i)`; both `L` and `I` are lists of `uint64_t`.
`f` is also necessarily MMIXware argument passing.
(jxd -T)
```
00000000: fe040004 3b030303 27030308 8e050203 “¥¡¥;¤¤¤'¤¤®⁾¦£¤
00000010: 3b050503 8e070105 bf060000 ae060105 ;¦¦¤⁾¬¢¦Ḃ©¡¡Ẹ©¢¦
00000020: 5b03fffa f6040004 f8000000 [¤”«ẇ¥¡¥ẏ¡¡¡
```
Disassembly/explanation:
```
foo GET $4,rJ
SLU $3,$3,3
0H SUBU $3,$3,8 // loop: leni--
LDOU $5,$2,$3 // j = I[leni]
SLU $5,$5,3
LDOU $7,$1,$5 // a = L[j]
PUSHGO $6,$0,0 // b = f(a)
STOU $6,$1,$5 // L[j] = b
PBNZ $3,0B // iflikely(leni) goto loop
PUT rJ,$4
1H POP 0,0 // return
```
[Answer]
# [Kotlin](https://kotlinlang.org), 48 bytes
```
{f,L,I->L.mapIndexed{i,v->if(i in I)f(v)else v}}
```
[Try it online!](https://tio.run/##hZLBbuIwEIbveYr/UslujYVDNyyocNlTJKo@gwVOZdU1iBjECuXZ2bHdRmmh2khjj8Yz/r9x5m0bnPWXo3Z4nYOx2gc@WtIqsLJteCJvOXDprPexuJwbsRI1xeS73tV@Y05mc7biOFrahllYj5o37MiNaw2OXXfZ6KCxdrpt8Ue3hkXd1XwoFSP1VaQhth6N41wAzcEjmDYwc9qZdTCbQRHHAq@sIXBBBFgs8JlUdEURL1yTejvHs949RZBBi9QXqJuXhpEIMmby4ucoi07Uo0C0X7R92phsIjATmHDxvYAOSzoQyEXVIOOME0ZLWu7JuhTmCNtealZlrZLqyn5R46hXzb4I/gw8peQy31PdpFMZ8BbXA9QNrt@53dj69L/yKVMl1vRW1cAoTNvjNZVKDxbvp8JrMKakPHHZWBfMPgXvYEP812N0cr09@MA4wd981En/s9Qsc5Tqg2eSeKa84EURZ@xdW8/yyAG7vfXBeZbGRxof9pZ27RwBmEhl5Jv5K/NcShq0g@HoeNFd/gE "Kotlin – Try It Online")
Very straight-forward algorithm. Uses the [default rule](https://codegolf.stackexchange.com/a/202985/) for submitting lambdas.
[Answer]
# [Attache](https://github.com/ConorOBrien-Foxx/Attache), 2 bytes
```
On
```
[Try it online!](https://tio.run/##bZBNa8MwDIbv/hWCHetDJXfuMsih0Mtg0N2NB2WbWWBkpUlH9uszfcSjhx7kD1l@30c6juPx7fNj3p1OX7@7ER7b@dDPBdOU@QzTK7nnbhhRLgk3HiTueaux5ggeGg8hu6f@3So5S5zxYNUxu8OlijTRVIgf6H/BtSjFpkq9nLt@TAtWEmEPBXNSmgxtC6KYnStUWVeorKQ2W1YjM4oKRhUMjU2RLPlgPUg/2xvOXF3InKk6kziHxflu3/10w/d5kPsKJsUI1q3oojal44pXwWneNkq3VOvMBIN/KOCVik0ZG/tNuKgEVbnFzS8lGHeo3CHPfw "Attache – Try It Online")
There's a Builtin for That‚Ñ¢.
Another builtin solution, 8 bytes: `Over@`->`.
## Without builtins, 22 bytes
*-2 bytes after reading other answers, since this modifies the variable in place. Prepend `;z` before the last `}` to have it also return the value.*
```
${{Set[z,_,y!z@_]}=>x}
```
[Try it online!](https://tio.run/##bZDBSgMxEIbveYpIPSjNoZnU1LWsWPAiCAoeQyzFNrggtXSjbFv67OtkJpEeepiEzEz@@f5ZxLj4@Fz1s83mazeL8q7uLw@Ht1V0ezVXu4v9w9wf6/vu2AftOo912b2DeG7aqNPD6bGSKW7wKjHCMEpWShovntZL7sQsYEZJ7rZevPwUkcqyCmAB/g89Skq2KlKv22Yd3VVmdUlZyYBBOH46pfta1rVM0l6IAAV6qAkaaN4EZYEnWiKEQqgZktg4ectmkrHJOQRsD8AIkBGgIEBCMBlh8Nj8Nu33tk3voeyIx7D/NECTTVqgPQlM4zUmzNxNW0w8@INIT1R477ri36CziiGVswawFAwbMNmAKQaM7/8A "Attache – Try It Online")
**23 bytes:** `${z&Set&>Tr![x,z[x]|y]}`
**23 bytes:** `${&@(z&Set)![x,z[x]|y]}`
**31 bytes:** `${{[_,y@_][_2in x]}&>@V#Iota!z}`
**32 bytes:** `${{If[_2in x,y@_,_]}&>@V#Iota!z}`
**33 bytes:** `${{[_,_|y][_2in x]}&>Enumerate@z}`
**33 bytes:** `${{[Id,y][_2]!z@_}#x&Has=>Iota@z}`
**34 bytes:** `${{z@_|If[_2,y,Id]}#x&Has=>Iota@z}`
**34 bytes:** `${{If[x&Has!_2,y@_,_]}&>@V#Iota!z}`
**34 bytes:** `${{[Id,y][x&Has!_2]!_}&>@V#Iota!z}`
[Answer]
# [Elm](https://elm-lang.org/), 62 bytes
```
a f i=List.indexedMap(\n->if List.member n i then f else\x->x)
```
Fairly simple implementation of the function. `List.indexedMap` expects a function which takes 2 `Int`s (in this case), but we can also write a function that takes 1 `Int` and returns an `Int -> Int` function to save ~~3 bytes~~ 1 byte over the more straightforward implementation function `\n e->if List.member n i then f e else e`.
At the cost of 1 byte, the inner function can be written as `List.member>>\h->if h i then f else\x->x`, and the right operand to `>>` *seems* golfable, but I can't quite figure out if that's really the case.
## Test Program
Try it [here](https://elm-lang.org/try)!
```
import Html exposing (text)
a : (Int -> Int) -> List Int -> List Int -> List Int
a f i=List.indexedMap(\n->if List.member n i then f else\x->x)
main =
a
(\x -> x ^ 2)
[0, 2, 3, 4, 5, 6]
[14, 14, 5, 15, 15, 10, 13, 9, 3]
|> List.map String.fromInt
|> String.join ", "
|> (\x -> "[" ++ x ++ "]")
|> text
```
] |
[Question]
[
Given an array \$A\$ of positive integers between \$1\$ and \$9\$ inclusive and a positive integer \$n\$, remove all integers in \$A\$ which appear more than \$n\$ times.
For example:
```
[1,2,3,2,3,2,4,1,2], n = 2
Occurrence: 1 1 1 2 2 3 1 2 4
Keep? 1 1 1 1 1 0 1 1 0
Kept values: [1,2,3,2,3, 4,1 ]
```
so the output is `[1,2,3,2,3,4,1]`
You can assume that:
* At least one element will always appear more than \$n\$ times
* At least one element will appear fewer than \$n\$ times
* \$A\$ will have a minimum of 2 distinct elements
* \$n\$ and the length of \$A\$ are within the integer bounds of your language.
You may take input and output in [any convenient method](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods). As the elements of \$A\$ are digits, you may also take input as an integer, or a single string, if that suits you.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in bytes wins
## Test cases
```
A, n -> out
[7,3,3,9], 1 -> [7,3,9]
[4,1,7,7,4,2,1], 1 -> [4,1,7,2]
[6,9,7,6,7,9,9], 2 -> [6,9,7,6,7,9]
[6,5,3,9,4,9,6,9], 2 -> [6,5,3,9,4,9,6]
[4,8,9,7,3,1,7,5,4,6], 1 -> [4,8,9,7,3,1,5,6]
[5,6,7,8,1,7,3,3,6,4], 1 -> [5,6,7,8,1,3,4]
[2,3,8,1,6,4,8,2,8,3], 2 -> [2,3,8,1,6,4,8,2,3]
[4,1,4,4,2,4,4,5,7,1,3], 1 -> [4,1,2,5,7,3]
[1,5,5,2,5,1,4,1,6,7,7,6,9,8,8,1,7,8,1,3,1,1,7,4], 3 -> [1,5,5,2,5,1,4,1,6,7,7,6,9,8,8,7,8,3,4]
[8,8,6,2,9,6,4,7,1,2,9,5,5,6,6,2,5,8,9,1,2,8,4,4,7,2,1,1], 3 -> [8,8,6,2,9,6,4,7,1,2,9,5,5,6,2,5,8,9,1,4,4,7,1]
[8,8,4,9,7,1,2,9,8,8,5,2,2,9,1,7,4,6,6,8,6,6,1,6,1,9,2,8,5,1,2,6,1,7,6,4,7,9], 4 -> [8,8,4,9,7,1,2,9,8,8,5,2,2,9,1,7,4,6,6,6,6,1,1,9,2,5,7,4,7]
[8,8,9,2,7,4,7,5,6,9,7,2,7,7,6,2,6,9,6,3,5,1,1,6,2,8,7,4,2,4,5,9,3,3,3,3,7,4,8,7,5,4,1,4,7,8], 2 -> [8,8,9,2,7,4,7,5,6,9,2,6,3,5,1,1,4,3]
[6,8,1,8,6,9,2,2,5,8,7,6,2,5,4,3,3,1,4,2,7,1,6,3,9,8,9,5,2,6,8,8,7,7,5,2,5,1,4,7,5,5,3,7,6,3,7,6,3,6,7], 4 -> [6,8,1,8,6,9,2,2,5,8,7,6,2,5,4,3,3,1,4,2,7,1,6,3,9,8,9,5,7,7,5,1,4,3]
[1,3,5,6,1,2,8,8,8,4,4,4,5,8,9,9,6,4,5,3,8,7,9,7,8,6,1,6,1,6,4,5,5,3,9,3,5,4,2,1,6,6,5,4,2,6,2,1,1,1,5,5], 2 -> [1,3,5,6,1,2,8,8,4,4,5,9,9,6,3,7,7,2]
[9,9,9,4,6,1,5,4,5,3,7,9,8,9,8,2,9,1,3,4,9,5,8,7,8,6,1,9,9,5,1,3,1,9,5,7,3,5,9,6,6,2,2,4,1,4,2,1,7,5,3,7,9,8,2,3,1,6], 9 -> [9,9,9,4,6,1,5,4,5,3,7,9,8,9,8,2,9,1,3,4,9,5,8,7,8,6,1,9,9,5,1,3,1,5,7,3,5,6,6,2,2,4,1,4,2,1,7,5,3,7,8,2,3,1,6]
[9,6,3,5,5,2,8,2,9,6,7,9,5,3,1,1,1,3,6,9,4,3,6,9,2,2,3,7,5,3,9,5,2,1,1,1,1,6,2,2,4,6,1,5,7,3,7,9,5,3,1,2,6,4,3,1,7,9,3,8,5,2,4,2,8,2,6,7,3,9,1,7,9,4,7,4], 5 -> [9,6,3,5,5,2,8,2,9,6,7,9,5,3,1,1,1,3,6,9,4,3,6,9,2,2,3,7,5,5,2,1,1,6,4,7,7,4,7,8,4,8,4]
[7,1,8,2,2,1,4,9,8,6,5,1,9,7,5,5,8,1,7,8,6,8,5,9,3,2,7,9,4,3,9,1,5,2,5,7,8,5,2,6,6,2,7,6,2,9,3,3,5,3,7,9,8,7,3,6,7,4,6,1,4,5,8,9,8,6,9,1,1,1,8,2,4,2,9,3,4,2,9,6], 8 -> [7,1,8,2,2,1,4,9,8,6,5,1,9,7,5,5,8,1,7,8,6,8,5,9,3,2,7,9,4,3,9,1,5,2,5,7,8,5,2,6,6,2,7,6,2,9,3,3,5,3,7,9,8,7,3,6,4,6,1,4,8,9,6,1,1,2,4,3,4]
[7,2,8,9,7,5,1,4,6,8,6,9,1,8,6,2,2,6,1,1,6,8,4,5,2,6,5,5,4,5,5,3,6,8,3,7,9,3,9,8,4,9,6,7,2,7,9,2,4,8,3,3,2,5,9,1,4,6,4,8,2,5,8,6,8,1,8,3,3,9,4,8,1,1,2,9,1,9,3,3,7], 11 -> [7,2,8,9,7,5,1,4,6,8,6,9,1,8,6,2,2,6,1,1,6,8,4,5,2,6,5,5,4,5,5,3,6,8,3,7,9,3,9,8,4,9,6,7,2,7,9,2,4,8,3,3,2,5,9,1,4,6,4,8,2,5,8,6,8,1,8,3,3,9,4,1,1,2,9,1,9,3,3,7]
[7,7,6,5,9,7,2,6,1,4,4,5,4,3,1,7,5,5,8,1,6,3,9,3,3,9,5,9,1,2,4,3,8,2,6,6,5,2,8,7,5,6,5,7,3,2,5,3,5,8,6,1,9,7,4,3,9,8,2,4,5,7,8,8,2,8,1,8,7,8,7,6,3,8,6,7,9,4,6,1,6,1,2,5,6,7,7,2,8,3,2,1,7], 11 -> [7,7,6,5,9,7,2,6,1,4,4,5,4,3,1,7,5,5,8,1,6,3,9,3,3,9,5,9,1,2,4,3,8,2,6,6,5,2,8,7,5,6,5,7,3,2,5,3,5,8,6,1,9,7,4,3,9,8,2,4,5,7,8,8,2,8,1,8,7,8,7,6,3,8,6,7,9,4,6,1,6,1,2,2,3,2,1]
[3,4,1,1,2,4,4,8,4,9,1,1,7,7,6,8,6,2,9,4,2,9,9,7,5,7,6,5,3,7,6,6,1,9,1,5,2,4,9,6,1,5,4,1,7,2,4,3,8,5,1,9,5,9,1,7,4,7,3,1,2,1,3,8,7,9,2,5,1,6,2,4,5,9,1,5,5,5,2,6,3,7,2,2,5,7,6,8,3,7,5,9,3,3,9], 7 -> [3,4,1,1,2,4,4,8,4,9,1,1,7,7,6,8,6,2,9,4,2,9,9,7,5,7,6,5,3,7,6,6,1,9,1,5,2,4,9,6,1,5,4,7,2,3,8,5,9,5,7,3,2,3,8,2,5,6,3,8,3]
```
[Test case generator](https://tio.run/##y0rNyan8/98ySKHC0lLh4a4uhYc7Fisc2hxxaAnX4R2H2w@3Bx6beGi/go7Cke5HG9cFqjzc2fCoYWbEsU0qQJGHO1epHFtic2hpyMPd3Y8ad5zq1ld4uHOtisKhrQp6QKGHO2cpZD1qWvOoYa6OwuEZ0VlAIxTCgQIKWQpGQHmVcBWFo3sUHjXM0QERCrp2QGqugtv///8NDQA). Run with no arguments to have a max length of 100 for \$A\$. For a different max length (no larger than \$891\$), run with that as an argument.
[Answer]
# [AWK](https://www.gnu.org/software/gawk/manual/gawk.html) -vn=, 9
```
a[$1]++<n
```
This is so competitive with the golfing-language answers, I feel like I might have misunderstood the question - did I?
The limit n is passed as a variable at the command line with `-vn=<value>`. The array is read from STDIN.
[Try it online!](https://tio.run/##SyzP/v8/MVrFMFZb2ybv/39DLlMgNAJiQy4TIDbjMgdCMy5LLgsgNASyQaQxEIPYJv91y/JsjQE "AWK – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), 4 bytes
```
n¹*u
```
[Try it online!](https://tio.run/##yygtzv7/P@/QTq3S////RxvpGOtY6BjqmOmYAGkjIDaO/W8EAA "Husk – Try It Online")
I've tried a few different ways, but [Razetime's approach](https://codegolf.stackexchange.com/a/219645/62393) turned out to be very concise in Husk.
### Explanation
```
n¹*u Function of two arguments: A=[6,9,7,6,7,9,9], n=2
u Unique values of A: [6,9,7]
* Repeated n times: [6,9,7,6,9,7]
n¹ Intersected with A: [6,9,7,6,7,9]
```
[Answer]
# JavaScript (ES6), 35 bytes
Expects `(A)(n)`, where `A` is an array of digit characters.
```
a=>n=>a.filter(v=>!(a[~v]+=v)[n+9])
```
[Try it online!](https://tio.run/##fdHNjoIwFAXg/TyFw6qNHQ39o12UFyFdNA5MNAQmalj66nhb2kmjMCY3CoTPc3ovbnK30/X8e/8axu927szsTD2Y2h26c39vr2gy9SdyzWOyezPhZthri@fTONzGvj304w/qUFNUBSlYHF1YjEqMd/99jsddUxFGtP14tTgYJUwVx1/TcG/D9RYnJakIfddkSLRIMn7rlJJuaJJo0CSMXhfFX9cln476qrqIwrclHEaud1ZZUpadgYj/IfP@S2cVcjLoLtZUkXVWmZg2JYP8oorQW4HJCH83aXw3eTKmU3FLKjzPTsGbFCwvSuIzw9X21nm28fRbxNxlsn3etHUK3eEM7PwE "JavaScript (Node.js) – Try It Online")
### How?
We use the underlying object of `a[]` to keep track of the number of times each digit has appeared in the string.
By using `~v`, we make sure that we use a *property* of the object (a negative value as a string) rather than an *index* of the array (which is already filled with the input values).
The first time we append `v` to `a[~v]`, we get *undefined* coerced to a string followed by the digit character. Because `"undefined"` is 9 characters long, we know that we've reached `n+1` occurrences of `v` by testing `a[~v][n+9]`.
---
# JavaScript (ES6), 37 bytes
Expects `(A)(n)`, where `A` is an array of integers.
```
a=>n=>a.filter(v=>(a[~v]=-~a[~v])<=n)
```
[Try it online!](https://tio.run/##bZDRCoMgFIbv9xRdKtgizUqYvUh0IVuNRthoo8tevR1PrJYrMeF8fp6f8zCjeV2H9vkObX@r50bPRhdWF@bctN27HsioC2LKaax0OOFJL9rS@drbV9/V566/k4aUGROwVEVJTGmw/6IoQK6qk2clLGYZrIRxFnuusxbO/7yUKainsBX25J73ww9c6bJATwU39vbi/vCDxDm@LTCZhFvpmntJvHF54EtMlaPtJpayZOdvXADxbQ5Vx8CCk8MWa35n@1wcTjzBebu/hF4xvuESfCfOsS6q@QM "JavaScript (Node.js) – Try It Online")
[Answer]
# [Stax](https://github.com/tomtheisen/stax), ~~6~~ 5 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
°º☻¿_
```
[Run and debug it](https://staxlang.xyz/#p=f8a702a85f&i=1+,+%5B7,3,3,9%5D%0A1+,+%5B4,1,7,7,4,2,1%5D%0A2+,+%5B6,9,7,6,7,9,9%5D%0A2+,+%5B6,5,3,9,4,9,6,9%5D%0A1+,+%5B4,8,9,7,3,1,7,5,4,6%5D%0A1+,+%5B5,6,7,8,1,7,3,3,6,4%5D%0A2+,+%5B2,3,8,1,6,4,8,2,8,3%5D%0A1+,+%5B4,1,4,4,2,4,4,5,7,1,3%5D%0A3+,+%5B1,5,5,2,5,1,4,1,6,7,7,6,9,8,8,1,7,8,1,3,1,1,7,4%5D%0A3+,+%5B8,8,6,2,9,6,4,7,1,2,9,5,5,6,6,2,5,8,9,1,2,8,4,4,7,2,1,1%5D%0A4+,+%5B8,8,4,9,7,1,2,9,8,8,5,2,2,9,1,7,4,6,6,8,6,6,1,6,1,9,2,8,5,1,2,6,1,7,6,4,7,9%5D%0A2+,+%5B8,8,9,2,7,4,7,5,6,9,7,2,7,7,6,2,6,9,6,3,5,1,1,6,2,8,7,4,2,4,5,9,3,3,3,3,7,4,8,7,5,4,1,4,7,8%5D%0A4+,+%5B6,8,1,8,6,9,2,2,5,8,7,6,2,5,4,3,3,1,4,2,7,1,6,3,9,8,9,5,2,6,8,8,7,7,5,2,5,1,4,7,5,5,3,7,6,3,7,6,3,6,7%5D%0A2+,+%5B1,3,5,6,1,2,8,8,8,4,4,4,5,8,9,9,6,4,5,3,8,7,9,7,8,6,1,6,1,6,4,5,5,3,9,3,5,4,2,1,6,6,5,4,2,6,2,1,1,1,5,5%5D%0A9+,+%5B9,9,9,4,6,1,5,4,5,3,7,9,8,9,8,2,9,1,3,4,9,5,8,7,8,6,1,9,9,5,1,3,1,9,5,7,3,5,9,6,6,2,2,4,1,4,2,1,7,5,3,7,9,8,2,3,1,6%5D%0A5+,+%5B9,6,3,5,5,2,8,2,9,6,7,9,5,3,1,1,1,3,6,9,4,3,6,9,2,2,3,7,5,3,9,5,2,1,1,1,1,6,2,2,4,6,1,5,7,3,7,9,5,3,1,2,6,4,3,1,7,9,3,8,5,2,4,2,8,2,6,7,3,9,1,7,9,4,7,4%5D%0A8+,+%5B7,1,8,2,2,1,4,9,8,6,5,1,9,7,5,5,8,1,7,8,6,8,5,9,3,2,7,9,4,3,9,1,5,2,5,7,8,5,2,6,6,2,7,6,2,9,3,3,5,3,7,9,8,7,3,6,7,4,6,1,4,5,8,9,8,6,9,1,1,1,8,2,4,2,9,3,4,2,9,6%5D%0A11+,+%5B7,2,8,9,7,5,1,4,6,8,6,9,1,8,6,2,2,6,1,1,6,8,4,5,2,6,5,5,4,5,5,3,6,8,3,7,9,3,9,8,4,9,6,7,2,7,9,2,4,8,3,3,2,5,9,1,4,6,4,8,2,5,8,6,8,1,8,3,3,9,4,8,1,1,2,9,1,9,3,3,7%5D%0A11+,+%5B7,7,6,5,9,7,2,6,1,4,4,5,4,3,1,7,5,5,8,1,6,3,9,3,3,9,5,9,1,2,4,3,8,2,6,6,5,2,8,7,5,6,5,7,3,2,5,3,5,8,6,1,9,7,4,3,9,8,2,4,5,7,8,8,2,8,1,8,7,8,7,6,3,8,6,7,9,4,6,1,6,1,2,5,6,7,7,2,8,3,2,1,7%5D%0A7+,+%5B3,4,1,1,2,4,4,8,4,9,1,1,7,7,6,8,6,2,9,4,2,9,9,7,5,7,6,5,3,7,6,6,1,9,1,5,2,4,9,6,1,5,4,1,7,2,4,3,8,5,1,9,5,9,1,7,4,7,3,1,2,1,3,8,7,9,2,5,1,6,2,4,5,9,1,5,5,5,2,6,3,7,2,2,5,7,6,8,3,7,5,9,3,3,9%5D%0A&m=2)
Output as a string of codepoints(since stax prints all numeric arrays as strings). [Verifiable version](https://staxlang.xyz/#c=cua*%7CbJ&i=1+,+%5B7,3,3,9%5D%0A1+,+%5B4,1,7,7,4,2,1%5D%0A2+,+%5B6,9,7,6,7,9,9%5D%0A2+,+%5B6,5,3,9,4,9,6,9%5D%0A1+,+%5B4,8,9,7,3,1,7,5,4,6%5D%0A1+,+%5B5,6,7,8,1,7,3,3,6,4%5D%0A2+,+%5B2,3,8,1,6,4,8,2,8,3%5D%0A1+,+%5B4,1,4,4,2,4,4,5,7,1,3%5D%0A3+,+%5B1,5,5,2,5,1,4,1,6,7,7,6,9,8,8,1,7,8,1,3,1,1,7,4%5D%0A3+,+%5B8,8,6,2,9,6,4,7,1,2,9,5,5,6,6,2,5,8,9,1,2,8,4,4,7,2,1,1%5D%0A4+,+%5B8,8,4,9,7,1,2,9,8,8,5,2,2,9,1,7,4,6,6,8,6,6,1,6,1,9,2,8,5,1,2,6,1,7,6,4,7,9%5D%0A2+,+%5B8,8,9,2,7,4,7,5,6,9,7,2,7,7,6,2,6,9,6,3,5,1,1,6,2,8,7,4,2,4,5,9,3,3,3,3,7,4,8,7,5,4,1,4,7,8%5D%0A4+,+%5B6,8,1,8,6,9,2,2,5,8,7,6,2,5,4,3,3,1,4,2,7,1,6,3,9,8,9,5,2,6,8,8,7,7,5,2,5,1,4,7,5,5,3,7,6,3,7,6,3,6,7%5D%0A2+,+%5B1,3,5,6,1,2,8,8,8,4,4,4,5,8,9,9,6,4,5,3,8,7,9,7,8,6,1,6,1,6,4,5,5,3,9,3,5,4,2,1,6,6,5,4,2,6,2,1,1,1,5,5%5D%0A9+,+%5B9,9,9,4,6,1,5,4,5,3,7,9,8,9,8,2,9,1,3,4,9,5,8,7,8,6,1,9,9,5,1,3,1,9,5,7,3,5,9,6,6,2,2,4,1,4,2,1,7,5,3,7,9,8,2,3,1,6%5D%0A5+,+%5B9,6,3,5,5,2,8,2,9,6,7,9,5,3,1,1,1,3,6,9,4,3,6,9,2,2,3,7,5,3,9,5,2,1,1,1,1,6,2,2,4,6,1,5,7,3,7,9,5,3,1,2,6,4,3,1,7,9,3,8,5,2,4,2,8,2,6,7,3,9,1,7,9,4,7,4%5D%0A8+,+%5B7,1,8,2,2,1,4,9,8,6,5,1,9,7,5,5,8,1,7,8,6,8,5,9,3,2,7,9,4,3,9,1,5,2,5,7,8,5,2,6,6,2,7,6,2,9,3,3,5,3,7,9,8,7,3,6,7,4,6,1,4,5,8,9,8,6,9,1,1,1,8,2,4,2,9,3,4,2,9,6%5D%0A11+,+%5B7,2,8,9,7,5,1,4,6,8,6,9,1,8,6,2,2,6,1,1,6,8,4,5,2,6,5,5,4,5,5,3,6,8,3,7,9,3,9,8,4,9,6,7,2,7,9,2,4,8,3,3,2,5,9,1,4,6,4,8,2,5,8,6,8,1,8,3,3,9,4,8,1,1,2,9,1,9,3,3,7%5D%0A11+,+%5B7,7,6,5,9,7,2,6,1,4,4,5,4,3,1,7,5,5,8,1,6,3,9,3,3,9,5,9,1,2,4,3,8,2,6,6,5,2,8,7,5,6,5,7,3,2,5,3,5,8,6,1,9,7,4,3,9,8,2,4,5,7,8,8,2,8,1,8,7,8,7,6,3,8,6,7,9,4,6,1,6,1,2,5,6,7,7,2,8,3,2,1,7%5D%0A7+,+%5B3,4,1,1,2,4,4,8,4,9,1,1,7,7,6,8,6,2,9,4,2,9,9,7,5,7,6,5,3,7,6,6,1,9,1,5,2,4,9,6,1,5,4,1,7,2,4,3,8,5,1,9,5,9,1,7,4,7,3,1,2,1,3,8,7,9,2,5,1,6,2,4,5,9,1,5,5,5,2,6,3,7,2,2,5,7,6,8,3,7,5,9,3,3,9%5D%0A&m=2)
## Explanation
```
cua*|b
c copy the list
u uniquify
a bring the count to the top
* repeat the elements n times
|b multiset intersect
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 9 bytes
```
t&=Rsi>~)
```
Inputs `A`, then `n`. [Try it online!](https://tio.run/##y00syfn/v0TNNqg4065O8///aEMFIwVjKDZRAPJiuYwA)
Or [verify all test cases](https://tio.run/##1Va5jlQxEMznK17EitBHt@1gIYCEFBEgjUYCrQiQOKRlU/j1wa4qe4bVcohLoKd3tdvd1bffvrx5c3xxvLl3@fTD6wef7h@fX@4eXjx6f3396urm4uPFk3dX@j7sHj877vMWttKvvMUtHHZhJ0o87Pa@tf7l/W5bO@ziFxSs25Y6JffbF8cZ7TCkVexJkGqd7tJyohs4DXIr@FK/fMvgPNHToOxjf4@/vt7fsd8Jmm/T04G2ZNg2ntblhEGXlRGUwTcwGP4Hf4DGYWfrkoiI@gO@O4r0vT1jB/GOP@98DcgK9DbsddANngiwJIMjDj3Q8a29p53cFaQrw6/kHP8DYwTfiPLQWfEMuBv0GvgdPNTUo5l/VB6lUZaBWoRlUPAPxA220UsR/959ZNjrwFEUK@trSVdBPJk7AbIq4n2X/HgmMSOyjshVrdJnRd7LkB@gswBDgo0NNrriWM6iXOD7BAnz6cPa/POaqGHiDcDvyoeqnMiKNfPAkOkF/qwrklxh9SXojKC6vp15hXozePC2rizPN1nHLtBAyeAzaS9CX5UJCVliynvmVYNVCd@oM8hmzkfFMqorTIkR/L0btN@hd2r9us4zjfuZjQZvsOYKpCX5LSG2We@IvUUet@XdsLT5wnCSExEndsOGOBp4qdPB3bSa2WvsV7BNXKxq1kpFRY3eVJCxETwZfnV4r2nv7H0OnANvFDKiNFV8VcU41tmxEhDPmBVWirwy85nVQguq/NAQ1cj5Uf8@xomwwssBMcvq5QX@b6tifVlQFXWXtytsjMBqqzIdU4GRb@qtrq7YoKcCU4Ql1MBpZrIwiKOBHtSXg2zpnSiEfw3mHSD3HAKmkeAaYrZKYwbW1c5YYm0FoyqUprFh@C7ClISDSZJlRdQRoOrYENQ22MarSiqvhho301DHIYONYzr4f4AfCbq7O60wZNa@qo52zDMGq45pQ/s444gkqFO11ZFxTpQ9pj4/zwVF3S6sWcUZ6mu@8/xkmtlFM7Os5JtngH4SKX/KgrJFoW/L/0mJTK@mw2c). For each case this takes a third input containing the desired output. The footer code checks if the program output equals the desired output, and prints `Correct` or `Incorrect` accordingly.
### How it works
Consider inputs `[1 2 3 2 3 2 4 1 2]` and `2` as an example.
```
t % Implicit input: array A. Duplicate
% STACK: [1 2 3 2 3 2 4 1 2], [1 2 3 2 3 2 4 1 2]
&= % Matrix of pairwise comparisons
% STACK: [1 2 3 2 3 2 4 1 2], [1 0 0 0 0 0 0 1 0
0 1 0 1 0 1 0 0 1;
0 0 1 0 1 0 0 0 0;
0 1 0 1 0 1 0 0 1;
0 0 1 0 1 0 0 0 0;
0 1 0 1 0 1 0 0 1;
0 0 0 0 0 0 1 0 0;
1 0 0 0 0 0 0 1 0;
0 1 0 1 0 1 0 0 1]
R % Upper triangular part: sets entries below the diagonal to 0
% STACK: [1 2 3 2 3 2 4 1 2], [1 0 0 0 0 0 0 1 0;
0 1 0 1 0 1 0 0 1;
0 0 1 0 1 0 0 0 0;
0 0 0 1 0 1 0 0 1;
0 0 0 0 1 0 0 0 0;
0 0 0 0 0 1 0 0 1;
0 0 0 0 0 0 1 0 0;
0 0 0 0 0 0 0 1 0;
0 0 0 0 0 0 0 0 1]
s % Sum of each column. For each entry of A this gives the number
% of repetitions up to that point
% STACK: [1 2 3 2 3 2 4 1 2], [1 1 1 2 2 3 1 2 4]
i % Input: number a
% STACK: [1 2 3 2 3 2 4 1 2], [1 1 1 2 2 3 1 2 4], 2
>~ % Less than or equal? Element-wise
% STACK: [1 2 3 2 3 2 4 1 2], [1 1 1 1 1 0 1 1 0]
) % Apply as an index (logical mask)
% STACK: [1 2 3 2 3 4 1]
% Implicit display
```
[Answer]
# [J](http://jsoftware.com/), 13 bytes
```
(>:1#.]=]\)#]
```
[Try it online!](https://tio.run/##y/qvpKegnqZga6WgrqNgoGAFxLp6Cs5BPm7/NeysDJX1om1jYzSVY/9r/jdUSFMwUjBWsFAwVDBTMAHSRkBszGWEQxyk3kTHUMcECI3ApKmOOZBvDAA "J – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), 9 bytes
```
fm≤⁰Sz#ḣ³
```
[Try it online!](https://tio.run/##yygtzv7/Py33UeeSR40bgquUH@5YfGjz////ow11jHSModhEB8iL/W8EAA "Husk – Try It Online")
```
f # filter input to retain only elements at positions of truthy values of
m≤⁰ # elements less-than-or-equal to arg 2 of
Sz# # count the occurrences of each element of arg1
ḣ³ # in the list of prefixes of arg1
```
[Answer]
# [J](http://jsoftware.com/), 17 bytes
```
0-.~]-1&(]*(-~:))
```
[Try it online!](https://tio.run/##y/qvpKegnqZga6WgrqNgoGAFxLp6Cs5BPm7/DXT16mJ1DdU0YrU0dOusNDX/a/43VEhTMFIwVrBQMFQwUzAB0kZAbMxlhF0cAA "J – Try It Online")
Apparently, this is shorter than a solution using Self-classify `=` or self equality `=/~`.
### How it works
```
0-.~]-1&(]*(-~:)) NB. left: n, right: A
1&( ) NB. Apply this function on A, n times...
1 (-~:) NB. Negation of Nub Sieve (mark first occurrence of each number)
]* NB. Multiply to A so that each first occurrence becomes 0
]- NB. Kill (change to 0) survivors of ^ from the original A
0-.~ NB. Erase zeros by set difference
```
Illustration:
```
n = 2, A = 2 3 8 1 6 4 8 2 8 3
First iteration:
Nub sieve of A = 1 1 1 1 1 1 0 0 0 0
Kill them = 0 0 0 0 0 0 8 2 8 3
Second iteration:
Nub sieve of ^ = 1 0 0 0 0 0 1 1 0 1
Kill them = 0 0 0 0 0 0 0 0 8 0
Kill the survivors of ^ = 2 3 8 1 6 4 8 2 0 3
Erase zeros by set diff = 2 3 8 1 6 4 8 2 3
```
[Answer]
# [Python 3](https://docs.python.org/3/), 57 bytes
```
lambda a,n:[e for i,e in enumerate(a)if a[:i].count(e)<n]
```
[Try it online!](https://tio.run/##bZFZboQwDIbfOYXfIJJbiX1ApRdhUJUyRhNNJyAWqS3i7NQJtKposyj2jx1/Md3HeG11uDbFeX2T99eLBIk6LwmatgeFBEoD6elOvRzJk0I1IMtcVY91O@nRI/Gkq3WkYXyRUIBXphjyzCqEMkIfU54RBugbIcGM3YR3tkUkGJtgjshY3pNONiq0yTF/Sowc27STFU2BBCMjB2wakV0@A95hJRyLow2Oj8ArsGu3hUPvHdUjXX54f9EGB84/lEfG@MgX/k9muOor1TfqTV33PAVpVLsI1vJDVzim49z8reefqvO2tiJs70H4Bhe5AzwGvqjxOENYt@sV/5DGneWCMOsFHp5hHhaY97IlFcVQLa5YvwA "Python 3 – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 44 bytes
```
f n=foldl(\r x->r++[x|sum[1|y<-r,y==x]<n])[]
```
[Try it online!](https://tio.run/##bZDdboMwDIXveQpf7AJUc8FfWiToi2TRhGjY0NIMESrRiWcfszM2TWxyosQnx/GXvDTuVRuzrh3YunszFxM@jjDH5/FwkPPibleZLPcqHvFe17OqrIqkWiftpicDNUh5xIyiVAgyxwSPFDmmmLAgsKRU0Cy/HAILNpOjJHkrOnlX5osLOhIsF77s5EVuIDBnOaUti5TSmtLMlAo8jmWcBIFG6se2V4GeB91O@vLD@4s23XH@odwzFnu@7H8y5gpG7bgp/S0YWCA0aCOoYnjvB9j@cGMn87Xp@Q3D2NsJHiCkYgR/Qw3fT4jWj7YzzbNb43YYPgE "Haskell – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 50 bytes
```
lambda s,n:reduce(lambda r,x:r+x*(r.count(x)<n),s)
```
[Try it online!](https://tio.run/##dZHbTsQgEIbv@xSTXoGOm5QedttYX2TdGOzSbI1OG8om1ZevA63GVOUQhp9/4AOGd3fpSc1t/Ti/6rfns4YRqbLmfG2MWBWLU2Vvpxthd01/JScmeU8SRzk7M7onDTWI4x5TruUJ4ZhhgnuuGSpMvFBgydOCe7k4Csy9mR0ly2vSIbjSkJzzUuHlPKQdgugPKDDzsuLQizzlUXFPTzIKOORxEgRuKrQ1lpGZBtM4c/7m/UGrNpy/KLeM@ZYv/ZvMc7W9BY2EBjqCj24Qy7shLMAIX2SyioCLVjXE8e6l70iMzgqSfgfy2VoGh/nfYRbHyLdshVZIMgrCYDty/LvA58V3DzH6mPepx/kT "Python 2 – Try It Online")
*-2 bytes from Leo by taking input and output as a string of digits, which is also used in the answers below*
---
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 53 bytes
```
lambda s,n,r='':[x for x in s if(r:=r+x).count(x)<=n]
```
[Try it online!](https://tio.run/##bZFtb4MgEMff@ynuHZLdlogPrc3YF7FmYRZT040asImb8bO7A7tl6SoQ7v53Bz@P/nM4nk267e3Syv3yrj7eDgocGrSSsV01Qnu2MEJnwEHXxnYn7cPIn5rzxQzxyJ@lqZdBu@FVgYS42mBKo6wRqgwT3NDIUGDihQJLcgta5ZpRYO6TKaMk@Vq0DVlpKM4pVHg5D2XbIPoLCsy8LMj0Irm0C1ppzaOAYzxOgkBThHm1eaTHXjeDPvzy/qEVN5z/KG8Z81u@9D6Z52qOujlp6@9l@4vYZA1DCFaSMh75RitqvPbN/ur6eG0rwvo/CD/gfBcBfUpIqNxgY8PDIxlfp@oQ0/dieo05AmhjJdDw4Pe2o6ds2aRmhMnM8PgCk5thuvJWdJh09cz48g0 "Python 3.8 (pre-release) – Try It Online")
Input and output as list of characters.
---
**55 bytes**
```
f=lambda s,n:s and f(s[:-1],n)+s[-1][s.count(s[-1])>n:]
```
[Try it online!](https://tio.run/##dZHbToQwEIbveYoJV22c3YRy2IWEfZGGmLqUiNGB0JqoL4/TshqD2kOY@fmn/drO7/5xIrWuQ/tsXh56Aw6pcWCoh0E43RyyDkneOc2Bdsfr9EpexExeqOlWb52/N9CC0CfMudcdgi4wwxP3AhVmQaiw5rTiWW@OCstgZkfN8q3oHF15LC75VxXkMpadoxg2qLAIsuIwiJzyV/HMO5lEHAo4GQIPFcctlol9m@3V2/6b9wet2nH@otwzlnu@/G@ywDVMCxgktDASfIyz2O4NYQNG@CKTTQLcjGohTY9P00jC@UWQDCtQqDYyOuz/Drs5HJ9yEEbx@yVRmJeRPD8w8H7p4ZJiiHmd1q2f "Python 2 – Try It Online")
Repeatedly takes and removes the last element of the list, keeping it if it appears a maximum of `n` times in the current list.
It feels like there should be a better way to express this, but I'm not seeing it. Python is clumsy at dealing with the end of a list. While `l[-k:]` usually takes the last `k` elements from the end, for `k=0` it instead takes the whole list. So, I didn't find a nice single slice that conditionally takes 0 or 1 elements from the end of a list. Also, doing `l.pop()` has the trouble that the recursive function call comes before the expression where we want the last element.
[Answer]
# [PowerShell Core](https://github.com/PowerShell/PowerShell), ~~38~~ 37 bytes
```
$a,$b=$args
$t=@{}
$a|?{++$t.$_-le$b}
```
-1 byte thanks to *mazzy*!
[Try it online!](https://tio.run/##XYzNCsIwEITveYocFtvQjZC0tvYQ9E0kldQfgpW24CHm2eNWCoIM3zLL7OxzeLlxujrv5XkYXYLehAQWoTNgx8vEYDbHEBnY9yEUBcxbOEnvoIspMpZvoOe5Qo3lSoW0Ca6FvA@3R4bZetNQUmEruPpPFO5ImlDfdo0NqcYW9yRFfpklsfhK8PL3IX0A "PowerShell Core – Try It Online")
[Answer]
# [R](https://www.r-project.org/), 48 bytes
```
function(x,n)x[diag(diffinv(outer(x,x,"=="))<n)]
```
[Try it online!](https://tio.run/##fZDdDoIwDIXvfQqiN1tSL/aHLhFfxBBjFJQLR0LQ8PbYFhIHGLOMkZ5@7Wmbvime9bs4h/aR9eUrXNuqDqKDILvTrbrcxa0qyyq8Rf1qiwaFDtZZtpbyEGQeweIqdmDweAmJkskm2R5PFPH5apJlQcEOjwUNKsod4nqWnYLHaIrXc2U9ZkfxBeGoK9b3qE@ZSFm42nNFwy4c5qQTb1/VLVjHPvZM0gZSsBH7VQ3YGakxRgoS@Gq8JvI7V82PTVreI30ddlHMxxvVHJ@TNIVjjSoodkjb9NhnmGPwq/ifpjFjzf8kcTxl/wE "R – Try It Online")
Test harness taken from [Dominic's answer](https://codegolf.stackexchange.com/a/219632/67312).
Closely related to [Luis Mendo's answer](https://codegolf.stackexchange.com/a/219635/67312), though implementing it in MATL is [longer](https://tio.run/##y00syfn/v0TNNrI4IiXTrk7z//9oQwUjBWMoNlEA8mK5jAA). Rather than zeroing out the lower triangle of the matrix and computing the column sums, this calculates the cumulative sum of each column, then takes the diagonal of the resulting matrix as the filtering criterion -- for some element \$a\_i\$ this tells the number of occurrences of \$a\_i\$ before index \$i\$.
So for instance, using `[6,9,7,6,7,9,9]`:
```
Pairwise equality check:
[,1] [,2] [,3] [,4] [,5] [,6] [,7]
[1,] 1 0 0 1 0 0 0
[2,] 0 1 0 0 0 1 1
[3,] 0 0 1 0 1 0 0
[4,] 1 0 0 1 0 0 0
[5,] 0 0 1 0 1 0 0
[6,] 0 1 0 0 0 1 1
[7,] 0 1 0 0 0 1 1
Column-wise cumulative sum (with an initial condition of 0):
[,1] [,2] [,3] [,4] [,5] [,6] [,7]
[1,] 0 0 0 0 0 0 0
[2,] 1 0 0 1 0 0 0
[3,] 1 1 0 1 0 1 1
[4,] 1 1 1 1 1 1 1
[5,] 2 1 1 2 1 1 1
[6,] 2 1 2 2 2 1 1
[7,] 2 2 2 2 2 2 2
[8,] 2 3 2 2 2 3 3
The diagonal:
[1] 0 0 0 1 1 1 2
```
[Answer]
# [K (ngn/k)](https://bitbucket.org/ngn/k), ~~18~~ 16 bytes
```
{x@&~y<+/'x=,\x}
```
[Try it online!](https://tio.run/##1VZLblQxENxzireCBSDkT3fbBCTuEdiGBVLWQYhcfbCryp4oQJCCQKDRzLxnt7urq3/@9PL64/XpdPX6y827p7ef3zx/9ezm7Yv3N19PV5dxlPHpF0f6cNwe860/ubqsRxrPcdQjH0l7XMtj148@nnx8@zyZ5@6dNUjY1DTO9LmzZe6swkrDqQLNNtZ92zrvGGQNuhskJ2I/qmTPO@WoQzKP//nm0JLHt8j@/Z0iTyv8nL82NKUpvz3OWJuSE4nhPWHHwdD0uwkXMSQ8D3Rl6nj41DxD1PPNh1wHuoDljrOOdQMjCf5USORpSVYeOn0@y3NJ1ioYpuR8nygz5Gbcp9WG34Rvh2WDvEOGlkZs60Lwa43UR22G1RCauYJ3YO7wj0xlvPvgyXDWgSQUMxt7RZ9AXJlJCbqaIv8jC/mOzooIOyLYtEveQgxWWEiwGkBR4GWHl65oxp1YB/gv0LB@R/TF12Nt0cZCnOCBKy@acqMq4swGQ9YHOG07ntxhPRbYzFh1PTvzi/krFu9bq@K/y0N2h46VCjmT/RD@pnwoyBVTBTC/OvwqeEbNQTezPyuiWZ1iacyQH12jT3y/b3nZ/bnVbROeMoMMfLD6AtqKuCuIb9V/xtkQ67YZTtuabwxnPRmxYo/siKVBljadPVu7lZ3HyMZj0S1krHDWTENtzU4VyNsMmQpmHfx1nV290IF0Is7CRpym2m@qHMc@u1cB4hW1YMWIl5XVrBl60MRER1zh48XROMn@LsqFsYHnhLhV9fZABPquXN8@NEXexXeDlxlYbVeoY0ow@l191tUhO@w0YMrwhBY44UweJkl0rCf16CRfRk9KGv//EtDvYILKgE0OCNdQs10gK7SuxsZC6zscTcE0DRHDcwhTEQ6mSZUXWReDputEUvNgS28qq7pba9aVhGwWto8zxf@DA5mwB@FlB6KyA6j26Me6dbD2mDihe15o2q9qqqoMWzdJ@WPq@OueEOp6ac8tTlTf8553KtMED83P2Om37gTjbhKT8z/jQ@g@aXteZcXHxGs5fQM "K (ngn/k) – Try It Online")
Adapted from @rak1507's [message](https://chat.stackexchange.com/transcript/message/57189397#57189397) in the APL Orchard. Takes the list as `x` and the number of occurrences as `y`.
* `+/'x=,\x` get the running totals of the counts of each number in the input
* `&~y<` get indices of the first `y` instances of each value
* `x@` index back into the input
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~23~~ 19 bytes
Saved a couple bytes by looking at Bubbler how negated the mask in [their answer](https://codegolf.stackexchange.com/a/219640/95792).
```
{⍺/⍨(⊢∨(≠⍺×~))⍣⍵⊢0}
```
Don't [try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24TqR7279B/1rtB41LXoUQeQ6lwAFDk8vU5T81Hv4ke9W4HiBrX//xsqGCkYA7EJGJuAecZAOk3BGAA "APL (Dyalog Unicode) – Try It Online") because TIO has an older version of Dyalog APL without Unique Mask.
Takes the array on the left and n on the right.
This takes advantage of monadic `≠`, which gives a mask to obtain unique elements. While `≠A` lets you keep unique elements in `A`, the mask `1-≠A` inverts it and lets you keep only repeated elements in `A`. Then `A×1-≠A` replaces unique elements with zeroes (this is safe because as the question states, `A` only contains numbers 1-9). The mask `≠A×1-≠A` gives us only unique elements from this new array, but since we replaced unique elements, it lets us keep duplicates (and the first element, but that is always kept no matter what anyway). `(≠A)∨≠A×1-≠A` now gives us a mask for unique elements and duplicates, but not triplicates, etc. By repeating this process `n` times, we get a mask for keeping only n-plicates, and then we just apply that mask to `A` to get the result.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes
```
œ&Qx¥
```
[Try it online!](https://tio.run/##VVVLjhUxDLwKC8QqErIT28kZWLFET7NkM5oDwJYrcAbEhlOAuAgXecTl6syMWt2vO3HKrvLnPX5@evp6v//9/u7jl98/7n9@vv/w9t@3X5/u99stWt/XemhvZN@322jSYl@jaZOz6m3tNd/3gq1y1fLstl1773l9tAn7Dizb@36QDCgTO@nZ2zh7ur9zZ6/tX913f4EpezWjyqft04LdOil7xfaewUrgI@NdG6N85TPjyff02HEud32fW/CZmPmeWI51AxNBLAMWmhivzg9wrZP5nXEoTqWKiTPxFNwLWAZ7h015TvXGwUyrwLq10l7JSPHtm4uBjQMvqIztvc4roGLpL8CaLzKXekxgKXkGGQ@cFiAGPHQwW2Dm4BjAvfQOKNaBcD13Bg4jQbROHSe1HFS3tDfkPsB1HrVqp6qsIzbFqvPdKx8N@T/sFlAHEIzYQQ6TuenIW/GezMwCn453Q30aonNoNKhJ1fSFqLDP@l70XbkxcK3KCuB1Rtqh@uCvAiHI0Q4fOV6LRdBj4SiUqf5aUM5gWz4d1ou7gxVviC@Qd4WfAQYO1otZvLrFgZnYSpRCrKwHPZY2wR7qYH4pE1UFZHBlu2quGE7GvJANaLVjnIxTOUWqxvycnFTGqdIEtoKHnXrJ9U51FrvU2UcLfifiVbAsDzV1jOyFFgvrwg4X8szqFmGoAefVps5BZSdBl6zOMq5E11gZSJ6ypJUN60y4goqdAg2mYbLZA82kDDbYxB32cVqgGs84FDFWq4yfKXRUt3C6llrCfwI/M7JyVDkpytXtFZywBtfpO4G7wfqUQ7smW9WxnL6vaeJnjtVMr8x2ICn9TnbMOv9d8fAf "Jelly – Try It Online")
Accidental translation of Razetime's Stax answer based on his comment.
```
œ& Multiset intersection of A with
Q ¥ the unique elements of A
x repeated n times.
```
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
xċṪ$Ƥ<¥
```
[Try it online!](https://tio.run/##VVVLjhUxDLwKi1m2hOzEdiJxA06AnmbJBs0BYMuWa4CQEBdgOyDuARdp4nJ1ZlCr@3UnTtlV/rx3bx8ePpzn@1@f/vz4dvf786vHL@fPry9f3/39@P3Ned5ucbR1zfvjhaz7duuHHLGufughe9WPudZ83RO2ylXLs8t2rr2n9X4M2Ddg2dr3jWRAGdhJz370vafrO3fW2vrVdbdnmLJWM6p82jot2K2TslZs7RmsBD4y3rkwylc@M558T48N53LX17kJn4mZ74nlWDcwEcTSYaGJ8d/5Dq51Mr8zDsWpVDFxBp6CewLLYO@wKc@pXt@YaRVYt6O0VzJSfPviYmDjwAsqY2uv8QqoWPoLsMazzKUeA1hKnkHGHacFiAEPDcwmmDk4BnAvvQOKNSBcz5WBzUgQrVPHQS071S3tDbkPcB1brdqpKmuITbHqfPfKx4H8b3YTqB0IRuwgh8HcNOSteA9mZoJPw7uhPg3ROTTq1KRq@kJU2Gd9T/qu3Bi4VmUF8BojbVC981eBEORom49sr8Ui6LFwFMpUf00oZ7Atnw7ryd3OijfEF8i7wk8HAwfrySxe3eLATGwlSiFW1oMeS5tgDzUwv5SJqgIyuLJdNVcMB2OeyAa0WjEOxqmcIlVjvk8OKuNUaQBbwcN2veR6ozqTXersowm/A/EqWJaHmjpG9kKLiXVhhwt5ZnWLMNSA82pT56CynaBLVmcZV6JrrHQkT1nSyoZ1JlxBxXaBBtMw2OyBZlIGG2ziBvvYLVCNZxyKGKtVxk8UGqpbOF1LLeE/ge8ZWTmqnBTl6vYKTliDc/edwF1nfcqmXZOt6lh239c08T3HaqZXZhuQlH4HO2bu/664/wc "Jelly – Try It Online")
I was going to hold off on posting until I tied caird's 6 bytes, but I feel like I'm so far off the mark that it's worth documenting anyhow.
```
x ¥ Repeat each element of A by the corresponding elements of:
Ƥ for each prefix of A,
ċ how many times it contains
Ṫ$ its last element (which is then not considered).
< Is each count less than n?
```
[Answer]
# Java, 157 bytes
```
l->n->java.util.stream.IntStream.range(0,l.length).filter(i->java.util.stream.IntStream.range(0,i+1).filter(j->l[j]==l[i]).count()<=n).map(i->l[i]).toArray()
```
Takes a `int[]` and the integer `n` as input and returns a `int[]`.
[Try it online!](https://tio.run/##jVA9b4MwEN35FTfarbFKk6atEpC6VOrQiRExuASoqTHIPlJFUX47PSBq1K16er7zfTzfuVEHFTb7r1G3fecQGrrLAbWR1WAL1J2VN9sg6IcPowsojPIe3pW2cAoALlGPCskcOr2HlnIsRadtneWgXO35XArwetHbaYtZLuDN4t9QkkAF8WjCxIbJdQ6PrlStpPJ08ZyydcnuhJGmtDV@cllpg6Vj@l9t@jb67WjCxGRNHscm0zmXRTdYZHwXWy5b1U@CSwK7F@fUkfFxO@@SHj2WrewGlD2tisay68tzqaee5RtYJVXfmyOz5TfMi54i8UC4J0ZiTdyIR8JGPIsnQkT@dK6Ik78@84vCinM@DXAOzuMP)
[Answer]
# [R](https://www.r-project.org/), 62 bytes
```
function(x,n)x[sapply(seq(x),function(i)sum(x[1:i]==x[i]))<=n]
```
[Try it online!](https://tio.run/##fVBdi8IwEHy/X1G4lwT2HvJVzWH9I6WISMXCGT2rEn993d2Kpq1ISFNmdmZn99Sd6v3hWq/CeVd020vYnJtDEBGCjGW7Ph7/bqKt/0WU8CQb2V72Ipbqt6mKIpZNJeWiCFViJTZiBgaPl5ApmX1nP8uSEF99DaosKJjhsaBBJbU9rkfVOXhEc7yenfWjOsEnCkdd0d8jP9QkzCTVnB0Np3BYkw@yvVg30TrOMWclbSAHm2hfrAE7UmrEiEEFvhqvSfKOWfNmk5b3SF@HXRTr041qxsdKmsIxRw6KE9I2Pfbp5@jzKv6naczD87OSdDxldwc "R – Try It Online")
---
...although a port of [Luis Mendo's answer](https://codegolf.stackexchange.com/a/219635/95126) is shorter at ~~59~~ [58 bytes](https://tio.run/##fVDbisIwEH33KwqCJDAKuVUDdn9iH0VWKF1W0FRiK/XruzNTwbRdlpCmzLnMmYl9rK71o/oKzU/Rf7ehbM51EB0E2R3K@vLZXu@ivd2quGniWTz367ptqoiEDk5FcZJy9ZT7cExsRCm2YPB4CZmS2TJbfxyo4o@LEcuCgi0eCxpUwh3qesLOwWM1x@vZWb/YSX2mcNQV/T3iY02CzFLt2NFwCoecfJTtjbqZ1nGOHStpAznYRPtGDdiJUmONEFTgq/GaJO8UNX9s0vIe6euwi2J9ulHN9amSpnCMkYPihLRNj32GOYa8iv9pGvPy/F9JOp6y/wU) (*Thanks to Giuseppe*)
[Answer]
# [**T-SQL**](https://docs.microsoft.com/en-us/sql/t-sql/language-reference?view=sql-server-ver15), 114 bytes
`SELECT C FROM (SELECT B,C,row_number() OVER (PARTITION BY C ORDER BY B) AS D FROM @A) E WHERE D <= @n ORDER BY B;`
Example:
```
DECLARE @A TABLE(B INT IDENTITY(1,1), C INT);
DECLARE @n INT;
INSERT INTO @A SELECT * FROM (VALUES(1),(2),(3),(2),(3),(2),(4),(1),(2)) AS A(C);
SET @n = 2;
SELECT C --4.Finally select the filtered rows
FROM (SELECT B
,C
,row_number() OVER (PARTITION BY C ORDER BY B) AS D --1.Create an ordinal for each repetition that increments in ascending order of B
FROM @A
) E
WHERE D <= @n --2.Filter on the windowed function in subquery, removing rows with more than n repetitions
ORDER BY B; --3. Preserve original order of table variable @A (Can't order by in subquery)
```
Returns:
| | C |
| --- | --- |
| 1 | 1 |
| 2 | 2 |
| 3 | 3 |
| 4 | 2 |
| 5 | 3 |
| 6 | 4 |
| 7 | 1 |
Only way I could simulate an 'array' was by making a table with an identity on insert to store the insertion order.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 52 bytes
```
\d+$
$*
(.)(?=.*,(.)+)(?<=(?(2)$)(?<-2>\1.*)+.)|,.+
```
[Try it online!](https://tio.run/##HZM5jhNREIbzPscg2ePGUu1VEsOEXIIAJAhICBAhdzdf2bKt1361/Jv//Pz76/f3x4fLl2@Prz9uL8fL63G5Xy/vb/fXk8ON46e3y/tFry97/Kifv8r99Xq7X/@d99vxeJTZnHK4VLkKp5zKmjn1yLDxyT16T5lUeFIRWS30pfOg1pLe2rZl4q7uUWJcSYSGuGRVTtPSYiLlpx3dqZNeohORqdEj2u6lIs9rn73rDtWhJbMzJWW0QzSl6J3TKRwtrwC0skVz0kIktWHjMcarvAEuXr2cWjpHWUh1uJm4lqRNT2h2Vz0xV4RV7juLNWKR4AMW5HpAHtY11YuJB4SyQL5MvhMOUGfZzHhKUFzMb5iYD5tpmwnEmCiLgb@CT9F3C9UkzzmWSShNuBHoJpbjttiNOtDyk2wnG8qeNZqOSWOo5nRmGdqNo3gcJa0qPp0hA721IxuFlArqoF30gQVh0O0JpaDP/OWMauxrBo/xybOPUlKBWLl3GIovku0MiVhNspmBsmQId0a9zTSGBvISvVYQPm/BaWFlnSIHLgZmstRj2SxS7KGQTnWDViILlsNaw2LFLBgADQYEURAY4xrdfP1R8gpUQ99dYM4@d1CRxcoNInwgwmIMZxpaABnfpHYhesVmkD@AytpOQHLDhclwtSJNtVw3bnPWfw "Retina 0.8.2 – Try It Online") Link includes test cases. Takes `A` as a string of digits and `n` as a positive integer separated by a comma. Explanation:
```
\d+$
$*
```
Convert `n` to unary.
```
(.)(?=.*,(.)+)(?<=(?(2)$)(?<-2>\1.*)+.)|,.+
```
Delete any digit of `A` that is preceded by at least `n` identical digits and also delete `n` from the result.
[Answer]
# [Perl 5](https://www.perl.org/) `-al`, 28 bytes
```
$l=<>;map$k{$_}++<$l&&say,@F
```
[Try it online!](https://tio.run/##K0gtyjH9/18lx9bGzjo3sUAlu1olvlZb20YlR02tOLFSx8Ht/39DBSMFYyg2UQDyuIz@5ReUZObnFf/X9TXVMzA0@K@bkwgA "Perl 5 – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 38 bytes
```
->a,n{w=[0]*10;a.reject{|x|n<w[x]+=1}}
```
[Try it online!](https://tio.run/##VY7LCsIwEEX3fkXXOkonLxs0/kjIokq7cFGkKK20/fZ4k4W0DDeBczKX9J/7N7YuHm81ddPgfBn2XF7qU988m8d7mse5uw5@DAfHyxJfReu9IqYzRpEgDlRw2GVuyIIaxJIFF3@uSYIpxGyMoirvyNyo8cKs@nTuqrKTGENqZQVIcqC4BSI3zQyefphOjQbOnkP8AQ "Ruby – Try It Online")
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 56 bytes
```
(a,n)=>{var b=new int[10];return a.Where(c=>b[c]++<n);}
```
[Try it online!](https://tio.run/##tVHBasMwDL33K3xMqBeWuLZn0uQyOhjstkMPJQfHqCyQudRJtkLpt2eymsF@YBhb1tN78hN2w4Mbuvll8m7b@fHQcDz5685PnxBs20NE65odWcXmxHKfVvX1ywbWVh6@WZTkj00ZYJyCZzbbf0CAxFV1e3DNer31aXljc7mKEhsCdvmVNewq@IbnuAqMG/6E21CucSnMFVYMovE0iEnCJRcUFTIjX5LeUC6poyZEYAdJHEk8jZhGNL6XU1UjXhBHkUIu/ST1VPROQYy7H0EeDEbBza1c0VQeZ9LLHS5/B/yn@aKn@2yGFGLJo09FNxG9PZ/8cOoh24duhLfOQ3JM8AfwB7N3OE/gHezOk@0TuKRpOf8A "C# (Visual C# Interactive Compiler) – Try It Online")
Or 66 bytes if output should explicitly be an array vs an enumerable:
```
(a,n)=>{var b=new int[10];return a.Where(c=>b[c]++<n).ToArray();}
```
[Try it online!](https://tio.run/##tVHBasMwDL33K3xMqBeWuLZn0gTG6GCw2wY9lBycoLJA5lAn2TpKvz2T1Q76A8PYsp6enp9wM9w1Qzs/T65Zt27cVRxP/rJx0yd4W3cQ0LJke1awObLcxUV5@rKe1YWDbxZa0vsq9zBO3jGbbD/AQ9QUZb1rquVy7eLkvX/03v5EcX5mc74IzdZ71PsTqNhJ8BVPcWUYV/wBt6Fc41KYK6wYRMNpEJOESy4oKmQGvqR@Q7kkRU2IQAVJHEk8jZhGNLyXUlUjnhFHUYe86knSVPRORoyLH0EeDEbBzTlf0FQOZ9LXOxxvB/yn@YKny2yGOsQ1Dz4V3UTw9tS7oe8g2fp2hNfWQbSP8AfwL5M3OEzgGtgcJttFcIzjfP4F)
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 8 bytes
```
fVÆâÃc 2
```
[Try it online!](https://tio.run/##y0osKPn/Py3scNvhRYebkxWM/v@PNtOx1DHXMQNiSx3LWB0FIwA "Japt – Try It Online") or [Check all test cases](https://tio.run/##1VZbilQxEP2fVfQCrmAelaQQF@HH6EDTHyI6IAh@uAPBhbiVWVibnHOS24w6woiiNPd2bqVSdeqd968/fjpfXd@GZzfPr2/js@v@fnp@9/Luy93Xu89vDvF88/bV@Xg81i31n5@2Q9gO@PLT6ep4zFvYav/lLW5Bu6RF7JfN@7r0x3E69v0LmnhsyOsyvFN3rguqdDWcTJBvfacsjfuOidugoYF3YC9bFve@kzpt8Ma@Gt@dp//H/iShuL@TltUZNo@3dWkBJ6b1ETTyDkQGyjgToHtY710e0RFJwHpgTF3Kw6fGmYl9fJfO6cBYod1xuoBu8E2AVRkcceiSnodO72d5Lix9Gd4m7/geSCM4RyYMvQ3vgMeh28BfwENdI9JZGH4tkfIozUCtC8@ggQLcDhvpr4jv0r1lOF2ApSp21veSfhURZl4FyGrKgR9piBcysyJdEMmmfXqvyo8ZOgL0VuBIsNRhaVFU60XMK6KQIGG@exbIZ4/VRR075gArivKjKUeyIs@sMNRAhV/biip3WKMJWiOoRevCPENFmjx5X1tWDFw2zq7hoGVwmhBU2dCUFwk5Y6oG5pnDtoQ1KhDSWQdRcY3qHlNiBP/oJN4R/r7mqffnWnedtJWZZPAJK7FCXpL/EqKc9R9xusrztrwclr6yUOxyIuLFzumIp4GXOgu4XbtZfcjgj8eim8hY66ydhhpj36rI3wiuDO8W@NB1evbGAqwDcxQ6IjX1gaYKKthnL0vAPCNXWTnyzMxt1g5taPKFI7awstvfMOn@LsqJscHTAZHLq9dXRMFXDZdlRVP0i3zeYGcEWluVWjA3mAGurlvULR2aGlBF2EINnHsmG4M4HPSgjh1kzehOgReEfwno9zDpzAqtHBdFY85WmczwFrU4lpuvkDQF1DRSDOsqVElImCpZdkRdF5quGUFNhO29qbjyarJxM41@XErYRnYn/w8GRMKGy9MKRmYnUAXSknkTYQUyeWgh5x@xBHUuXz0at01ZZOr98@ZQ1f3CmmGcr2XNf960TBO9aprWlYLzjjBuK7V7/c/YULco/L5ikJTQ9Gyf16fDkxcfvgE)
Very similar to the Jelly, Stax, and Husk answers.
Explanation:
```
# Implicitly store the input array as U and the input number as V
VÆ # Create an array of length V
âà # Each item in the array is the unique elements of U
c # Flatten that array
f # Only keep elements of U that are in that array...
2 # ... up to the number of times it appears in that array
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 11 bytes
```
NθΦη‹№…ηκιθ
```
[Try it online!](https://tio.run/##FcvLCoJAFIDhfU/h0gFbnNucObgUgiCiVzARlMy7QU8/TYt/88HfdPXaTPUQ43Wcj/1@vJ/tmi@uPD3WftzzSz/sCboiu7XbllfTkbD6NkNbddP895crsj61OOfKGPVEDIDMgQ1A1QePxmimol5IvQcDQTYPwqDIFARMDJSVAIGCGgp45GQigp4UMb2BVIzI4vkz/AA "Charcoal – Try It Online") Link is to verbose version of code. Takes input `n` as an integer and `A` as a string of digits. Explanation:
```
Nθ Input `n` as an integer
η Input `A`
Φ Filtered where
№ Count of
ι Current character in
…ηκ Prefix so far
‹ Is less than
θ Input `n`
Implicitly print
```
[Answer]
# [Julia 1.0](http://julialang.org/), ~~46~~ 43 bytes
```
l$n=(j=0;!i=sum(l[1:(j+=1)].==i)<=n;l[.!l])
```
[Try it online!](https://tio.run/##1VbbbhMxEH3PV5ioD7tiVeG7TVl@JOQB0a2UalmqZCv1P5B44uv4kWCfGXvTUopUBIJGSXfH45kzZy729e24ey/vjsfxbOqb6/7VxYtdf7j92Iwb@bq5ftnLdnve97v2TT9djJvzF@O2Pc7DYT6IXmxWzcZ3On3ithOyFf1bAUHcphXTyc6nj@lUJ5d1Equs4bqYHl36RlhQpHEiJi2bTSY7MQnv6Z0skMeArRoubFpwp36XRUv6Fk4CtHMUrjOL/rKokzhpq/SQX5NW@q/SVy9YHi7qwoBB/PnXJnMSe06YUBBDO8OyEORdEu4zDTEZJIwERuI5I9Vk5@mNeRtHkF9dUoyA6eE@YrOD3IIiidgMNFT2tnh6ysCynbbK4tGAdlLN7xmqgmKujew54FfiG@HdQt9Bh1zlvJsFxa@NkkkyaCH1BVEWQQDgEXESZQrvLhFmsdkBjecc2rSm@eORaKoyCVthqYbHnKgTs4Yy7pDRwMtEoGcqDbxIePZAohFqRKiOU@tPEu@RCA0L5TeVwsLbc92Rm4paIgzHdRK4Vgynn0rDoh08uA01t7RCTavhVEHq@NlRvaFB7cLmQ4eGUxE5UJ4mESIDRcsYPAcRuDg0CsdyW1C9RQSn8YxmhHHqCMXZVTxRikUF/TxdImH8fefF9c8dL24RLZWTBSnUkh7mNHOokWjD/xU2e2bfVqZldecqiMWOQs5onkbk1EKXfDpoR141PJVsYeS5AAs4anzqoYB2wxTzKGIFJQN6HUiMvLnMSge0GbVifITV8kAI3EkO6zTWNCCX1HnqIOamVDg1EIUQmI2I5CLIxEAoJ@HfBVpgBnAtkT5TZr9HGmJtZVfjCFwBjkkPiFQBrK0d63CMUBVEHsCOJ2eEowBQCqGQBzoKLYcoWSNCLnl4Sw4mzylZrxD/EtYfkYJOD6d0eDg@9WxtlpJfx8OOmi7WnATOqOUDxuLZMyjNQKhWDIeh@BIR@PoheZLQqA/cX6aOW9VZvgvgskKz5B7N/0MMipBn0nXNhqFxwH1IgZSrCfUhVQ8FSKchQZE8wWId1biOckCWT4FykfA8BWU9z@i0dfU@QJcvy8e754PV1xosd4Z8f/HE@58Jw3eKQ4g1C5qLmrhNp/d2tbr6tBez2E0Ct/iVSH9NM3ZT24kh4RMzRPv0NIozMeFtd5UFvRjwlv9u9rtpHqdm/e3rZ7HuBCzk6PYtdIbx8Kjyl/vKnVi/m5vh7mb4MA@X4mxo17x/ulzl7@r4HQ "Julia 1.0 – Try It Online")
[Answer]
# [C (clang)](http://clang.llvm.org/), 62 bytes
```
f(*l,n){for(int m[10]={0};*l;++l)m[*l]++<n&&printf("%d ",*l);}
```
[Try it online!](https://tio.run/##JYzLCoMwEEX3@YpBUPIY0YjQRWx/JGQhlhRhjEWyC/n2NG25m7M45279Rmt4leK5JAwi@fPie4hwWD26exqzkWSUInFYSU6pJXTd@6qG5037hAYlCZPLN4m2BjNqvNXNOFWqOfu9rXsALhIDzyOCBmGGoX@A/euTY7l8AA "C (clang) – Try It Online")
* Expects a 0 terminated array as input
If tacking a 0 filled array as an additional input is valid:
# [C (clang)](http://clang.llvm.org/), 58 bytes
```
f(*l,n,*o){for(int m[10]={0};*l;++l)m[*l]++<n&&(*o++=*l);}
```
[Try it online!](https://tio.run/##LY7LCoNADEX3fkUQKjNJxAdCF1P7I4MLsbUMjGOx7sRvn8Zasgn3nhwy5IPvwyvGUaHnwDjrbZwX5cIKk63Krt3K3aA3RF5PFn1HdAtZpnAmatFrs8eDXa2QDVd8lWm4lk3ukqNanh8R/U2/ZOpdAKW3BEa1MlTAwmhTFPkd7CmpOynPP9BBK71BZxyRfi@SjaDSywNSRqdNsscv "C (clang) – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 54 bytes
```
f n|let a?x|sum[1|y<-a,y==x]<n=a++[x]|1>0=a=foldl(?)[]
```
[Try it online!](https://tio.run/##XVLLboMwELz3K7Y@gdgoNa8EKU5@oD310IOLKkuFJgqBCEhLJP87XduJoJVlbM/Mzi5e71V3LKpqHEuodVX0oHaD7i4nyfV1s1B4FWLIN7VQQSCHXPPtk1CibKrPytv5Mh9P6lCDgJM6v3zA@dK/9u1zDZKVwILA6/bND1SHrvchCIAhMLM6uO73Dn0ng@2caYsOfMPAcunw76K9SRlo8IwjUjwWw9nfLKQnVxjRyHIEDgj2mOU@PgB4MkaOKxoxhsjvCgeGd02KGR1Tmpl1CQHn2CRLjDNZZURMwhk6ZV3b@MgmSohMXe4/TDIFJDbV2srNz6QY34udqIjAmz6kg4FIR2tIM7rV85@J5jcR23sw34Q8uQ1yVXHCDUZywsxbMI0QUJpW2S46lJqhHSWAGkAK1hyZBnobZv/WNvXXI8vHXw "Haskell – Try It Online")
* I was on the right track, one big step behind @xnor answer which cost me 10 bytes!
[Answer]
# [Clojure](https://clojure.org/), 76 bytes
```
#(for[[i v](map vector(range)%1):when(<(count(filter #{v}(take i %1)))%2)]v)
```
[Try it online!](https://tio.run/##RVDbbsMgDH3PV1iqKhmJl5D7tD9BPEQpbNky6GiaVpr27ZlnyiYsA@eGxbSEt2u0O56sA7cf0IWo9QybwY/xDJud1hAxjv7FimMpnm6v1uMzTuHqV3TzstoIh6/tG9fx3cIMpBHiqITZxC4KPIWL/dT6Lr0BDYXWnYSKazASSkNITbuEjovO6hd@UC3JGG@5D8mlHlSTctg1sOaPJaTP3irnN6xsc3iTY/ssSIMRWGeNYiQJWrb3PCH16v@tUta0FPdGdnSvUoAxBZ7j7NfFAzq4g6fP2X8A "Clojure – Try It Online")
[Answer]
# [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), 87 bytes
```
N =INPUT
T =TABLE()
R I =INPUT :F(END)
T<I> =T<I> + 1
OUTPUT =I LE(T<I>,N) :(R)
END
```
[Try it online!](https://tio.run/##K87LT8rPMfn/n9NPwdbTLyA0hIszRME2xNHJx1VDkyuI0xMqzGnlpuHq56IJlLbxtAOqAJHaCoZcnP6hIUB5oDIFoBaQsI6fJqeVRpAmF1D9//9GXGZcllzmQNIcSFsCAA "SNOBOL4 (CSNOBOL4) – Try It Online")
Takes input as `N`, then `A`, each element separated by newlines.
```
N =INPUT ;* Read in N, number to keep
T =TABLE() ;* create an empty table
R I =INPUT :F(END) ;* read in the next input; if none exists, exit
T<I> =T<I> + 1 ;* increment the value at index I (initially 0)
OUTPUT =I LE(T<I>,N) :(R) ;* if T<I> is LEQ to N, then output I. Goto R.
END
```
] |
[Question]
[
Given a list of integers produce a [Forward Difference](http://mathworld.wolfram.com/ForwardDifference.html) at a specified order/depth.
For the list of integers:
```
(10, 18, -12, 4, 8, -3, -5, 67, 9, 14)
```
The Forward Differences at the various orders/depths are:
```
0 10, 18, -12, 4, 8, -3, -5, 67, 9, 14
1 8, -30, 16, 4, -11, -2, 72, -58, 5
2 -38, 46, -12, -15, 9, 74, -130, 63
3 84, -58, -3, 24, 65, -204, 193
4 -142, 55, 27, 41, -269, 397
5 197, -28, 14, -310, 666
6 -225, 42, -324, 976
7 267, -366, 1300
8 -633, 1666
9 2299
```
So with the input of
```
4, (10, 18, -12, 4, 8, -3, -5, 67, 9, 14)
```
You would return the list
```
(-142, 55, 27, 41, -269, 397)
```
## Input
The input can be via STDIN or function parameters.
An integer specifying the depth to return. This will be 0 to the length of the list minus 1
A list of integers to calculate the forward difference for
## Output
The output can be via STDOUT or returned by the function.
The forward differences for the specified depth as a list of integers
## Rules
Built in and 3rd Party functions that do this directly are not allowed.
[Standard loophole](http://meta.codegolf.stackexchange.com/questions/1061/standard-loopholes-which-are-no-longer-funny) restrictions apply.
Shortest code wins
[Answer]
## J, ~~15~~ ~~9~~ 7 bytes
Very easy. Takes depth and list as left and right arguments.
```
-~/\~&2
```
As an explicit definition without all the adverbial trickery, this reduces to
```
4 : '(2 -~/\ ])^:x y'
```
* `-~/\~&2 y` – The forwards difference of `y`.
* `x -~/\~&2 y` – The `x`-th forwards difference of `y`.
If I were to make a *serious* (i. e. non-golfed) definition of this function, I would probably do something like this:
```
(}. - }:) : ($:@[&0)
```
The monadic case computes the forward difference whereas the dyadic case computes the `x`-th forward difference.
Even simpler, but not exactly equal:
```
+/\inv
```
`+/\` yields a vector of the sums of the prefixes of the argument. `inv` (defined as `^:_1`) is a conjunction that inverses a verb. This works wherever J knows how to inverse a verb and for the case of `+/\`, J knows how to.
[Answer]
# Python, ~~61~~ 59 bytes
```
f=lambda n,L:n and f(n-1,[x-y for x,y in zip(L[1:],L)])or L
```
Here we perform the subtraction by zipping all but the last of the list with all but the first of the list. `zip(L[1:],L)` is equivalent to `zip(L[1:],L[:-1])`, due to `zip`'s nature of taking the minimum length of the two lists:
```
>>> zip([1,2,3],[4,5])
[(1, 4), (2, 5)]
```
---
An alternative that's just as long (Python 2 only):
```
f=lambda n,L:n and f(n-1,map(int.__sub__,L[1:],L[:-1]))or L
```
Unfortunately Python 2 doesn't cut off the end of the list, so I can't do `map(int.__sub__,L,L[1:])`. Annoyingly, Python 3 *does*, but `map` no longer returns a list so this ends up being a byte more (60 bytes):
```
f=lambda n,L:n and f(n-1,list(map(int.__sub__,L[1:],L)))or L
```
However, if we allow the input to be the depth followed by the list like `f(3, 2, 5, 6, 7, 5, 10, 25)` (i.e. depth 3 and list `[2, 5, 6, 7, 5, 10, 25]`), then this is **56 bytes**:
```
f=lambda n,*T:n and f(n-1,*map(int.__sub__,T[1:],T))or T
```
---
Here's another alternative that would really annoy anyone who saw this in production code (this one destroys the original list):
```
f=lambda n,L:n and f(n-1,[L[1]-L.pop(0)for _ in L[1:]])or L
```
[Answer]
# Mathematica ~~23 57~~ 23 bytes
Martin Büttner's suggestion, exploiting the listability of subtraction.
```
Rest@#-Most@#&~Nest~##&
```
e.g.
```
Rest@# - Most@# &~Nest~## & @@ {{10, 18, -12, 4, 8, -3, -5, 67, 9, 14}, 4}
```
>
> {-142, 55, 27, 41, -269, 397}
>
>
>
---
`Rest@#-Most@#` carries out the subtraction that yields differences.
Nest performs said operation the specified number of times, operating always on the most recent list.
[Answer]
# Haskell, 40 34 bytes
```
n#l=iterate(zipWith(-)=<<tail)l!!n
```
Usage example: `4 # [10,18,-12,4,8,-3,-5,67,9,14]` which outputs `[-142,55,27,41,-269,397]`.
How it works: repeatedly calculate the difference between neighbor elements and store the intermediate results in a list. Take the `n`th element from this list.
Edit: @Zgarb found 6 bytes to save. Awesome!
[Answer]
# JavaScript (ES6), ~~52~~ 49 bytes
Simple recursive function, using `map` to scan the array and `slice` to drop the first element on each recursive call.
**Edit** 3 bytes saved, thanks @DocMax, really smart suggestion
```
F=(n,l)=>n?F(n-1,l.slice(1).map((a,k)=>a-l[k])):l
```
**Test** In Firefox/FireBug console
```
for(i=0;i<10;i++)console.log(F(i,[10, 18, -12, 4, 8, -3, -5, 67, 9, 14]))
```
>
> [10, 18, -12, 4, 8, -3, -5, 67, 9, 14]
>
> [8, -30, 16, 4, -11, -2, 72, -58, 5]
>
> [-38, 46, -12, -15, 9, 74, -130, 63]
>
> [84, -58, -3, 24, 65, -204, 193]
>
> [-142, 55, 27, 41, -269, 397]
>
> [197, -28, 14, -310, 666]
>
> [-225, 42, -324, 976]
>
> [267, -366, 1300]
>
> [-633, 1666]
>
> [2299]
>
>
>
[Answer]
# CJam, 15 bytes
```
l~{{_@-\}*;]}*p
```
Takes input as a CJam-style array and then the depth:
```
[10 18 -12 4 8 -3 -5 67 9 14] 4
```
and prints the result as a CJam-style array.
[Test it here.](http://cjam.aditsu.net/#code=l~%7B%7B_%40-%5C%7D*%3B%5D%7D*p&input=%5B10%2018%20-12%204%208%20-3%20-5%2067%209%2014%5D%204)
## Explanation
```
l~ "Read and eval input.";
{ }* "Repeat this block N times, which computes the forward differences.";
{ }* "Fold this block onto the list - this is quite an abuse of folding semantics.";
_ "Duplicate the current element (for the use in the next difference).";
@ "Pull up the other copy of the last element.";
- "Subtract.";
\ "Swap the difference and the other copy of the current element.";
; "Discard the last element.";
] "Wrap everything in an array again.";
```
[Answer]
# Java, ~~122~~ 119 bytes
```
int[]a(int[]a,int b){if(b<1)return a;int e=a.length-1,c[]=new int[e],i=e;for(;i-->0;)c[i]=a[i+1]-a[i];return a(c,b-1);}
```
Example Usage: <http://ideone.com/ALgYez>
3 bytes thanks to Geobits :v )>
[Answer]
## ><> ~~53~~ 50 bytes
```
l:[2-&\~~]r1-:?!vr
&}-@:$/!?&:-1
:;!? && lo*84n~<
```
Usage: Prepopulate the stack (-v in python interpreter) with depth first, followed by the integers.
For example:
```
forward.fish -v 3 2 5 6 7 5 10 25
```
Returns
```
2 -3 10 3
```
Thanks to Sp3000 for the help.
[Answer]
# [Prelude](http://esolangs.org/wiki/Prelude), ~~95~~ ~~92~~ ~~79~~ 78 bytes
```
? (1-vv- # ) v !
? # ^ #
?(1-) 1 (#) 1)(#)
1 #(# ) 1 (#
```
Input format is
```
N
M
n_1
n_2
...
n_M
```
where `N` is the depth of the differences and `M` is the number of integers in the input. Adding `M` was necessary, because there's no way for Prelude to distinguish a `0` from the end of the input. Output is also as a newline separated list of integers. I had to assume the slightly adjusted Prelude spec we devised [for this challenge](https://codegolf.stackexchange.com/q/44415/8478), because standard Prelude reads integers as byte values, which makes it impossible to enter negative numbers. Essentially, this is the [Python interpreter](http://web.archive.org/web/20060504072747/http://z3.ca/~lament/prelude.py) with an additional `NUMERIC_INPUT` flag.
For reference there are only ~~48~~ ~~38~~ 37 non-space characters - the rest was merely needed to align the code correctly.
## Explanation
In Prelude, each line is a separate "voice" that operates on its own stack. The program is executed column by column, where the separate voices are taken to operate "in parallel". All commands are single characters, and parentheses are Brainfuck-like loops (which are entered and repeated whenever the top of the stack is non-zero). Note that the vertical position of the closing parenthesis is irrelevant - putting it in a different voice still counts as matching with the most recent opening parenthesis, and the stack that is checked for the loop condition is always the voice where the `(` appeared. Now on to this program...
The program can basically be separated in into two parts. The bottom two lines are merely used for most of the loops in the program (except the main loop over `N`), passing `1`s back and forth. The top two lines contain the main loop and actual differencing. The following annotation has the code transposed, so I can annotate the individual columns:
```
? ? # Read two integers. Read instructions are processed top to bottom, so the first voice
# reads N and the third voice reads M.
( # Start a loop on the third voice. This loop will execute M times, reading the input list
# and pushing M 1s onto the fourth voice - i.e. a unary representation of M.
?11 # Read an integer onto the second voice, push 1s onto the third and fourth voice.
- # Subtract the 1 from the third voice, decrementing M down to 0.
) # End of loop, if the third voice is not 0 yet, to back two columns.
( # Start a loop on the first voice. This is the main loop and will execute N times. Each
# iteration will compute the forward differences once and thereby shorten the list by one
# element and also reduce the stack of 1s on the bottom voice by one.
1 # # Push a 1 onto the first voice and pop a 1 from the last. Together with the next column,
# this decrements both N and (the unary) M.
- ( # Subtract the 1 from the first voice (decrementing N), and start a loop on the fourth
# voice over whatever is left of M (the length of the resulting difference list). Note
# that this column is *not* part of the loop, so the - on the first voice will only be
# executed once. This loop builds the differences in reverse order on the first voice.
v#1# # Pop a 1 from the fourth voice and push a 1 onto the third. This loops over M while
# shifting its unary representation to the other stack. In addition, shift the top stack
# element from the second to the first voice.
v # Copy the next element from the second voice to the first, without popping.
- ) # Subtract the two elements on the first voice and end the loop if the fourth voice is
# empty. Note that his column *is* part of the loop.
( # Start a loop on the third voice. This is another loop over M, shifting the stack of 1s
# back to the fourth voice, and reversing the differences by shifting them onto the
# second.
#^#1 # As stated above, shift an element from the first to the second voice, a 1 from the
# third to the fourth.
) # End the loop. After this point, we're back to the original situation, except that the
# second voice has been replaced by its differences. The bottom stack element the
# previous list is also still on that stack, but the decreasing loop lengths on the third
# and fourth voices ensures that this element is never touched again.
) # End the main loop when N has been reduced to 0.
( # Start another loop over the remaining list length, shifting and reversing the result.
v#1# # Shift a 1 back to the third voice and an element from the second to the first voice.
) # End the loop. Note that this parenthesis is not on the same voice as the corresponding
# opening parenthesis, but its exact position is irrelevant. Moving it to this voice
# saves a byte.
( # Start one last loop over the length of the result.
! # # Pop a 1 from the third voice while printing (and popping) one element of the result.
) # End the loop.
```
[Answer]
## Python, ~~70~~ ~~68~~ ~~67~~ 59 bytes
```
f=lambda x,n:n and f([x[1]-x.pop(0)for i in x[1:]],n-1)or x
```
Non-golfed version before I went recursive:
```
def f(x,n):
for j in range(n):
for i in range(len(x)-1):
x[i]=x[i+1]-x[i]
return x[:-n]
```
[Answer]
# R, ~~48 39 46~~ 44 bytes
Recursion!
```
function(x,y)if(x)Recall(x-1,diff(y)) else y
```
* `x` is the number of iterations to perform, and `y` is a vector of integers.
* `if(x)` is true as long as `x>0`.
* `Recall` calls the current function but with new arguments.
* `Diff` outputs the differences between consecutive list/vector elements.
Previous versions:
```
#does not work for x=0:
function(x,y){for(i in 1:x)y=diff(y);y}
#does not use diff function:
function(x,y){for(i in 1:x)y=y[-1]-head(y,-1);y}
y[-1] is a list minus its first element
head(y,-1) is a list minus its last element
```
[Answer]
# Python, ~~92~~ ~~87~~ 86 bytes
```
def a(b,c):
if c<1:return b
d=[];e=b[0]
for f in b[1:]:d+=f-e,;e=f
return a(d,c-1)
```
This is my first Python golf. Any suggestions will be appreciated :)
~~5~~ 6 bytes thanks to Sp3000 :D
[Answer]
# T-SQL, Too Many :)
When I first saw this problem, I wondered if there was a way to do this in a query. While trivial for most languages, it's not so much for SQL query.
The input goes into variables @ (for depth) and @L for the integer list.
@L is a user defined table type
```
CREATE TYPE L AS TABLE(n INT IDENTITY(0,1),v INT)
```
Input setup
```
DECLARE @L L,@ INT=4
INSERT @L(v)values(10),(18),(-12),(4),(8),(-3),(-5),(67),(9),(14)
```
The query with some comments
```
WITH R AS(
-- Recursive query to calculate the level of a pascal triangle with alternating negatives
-- For 4 this is 1 -4 6 -4 1
SELECT 1c,0g UNION ALL SELECT-c*(@-g)/(g+1),g+1FROM r WHERE g<@
),
O AS(
--Multiple N values of list by reversed pascal triangle values
--shifting the start for each iteration (list length) - N
SELECT c*v v,F
FROM @L L
CROSS APPLY(
SELECT TOP((SELECT COUNT(*)FROM @L)-@)ROW_NUMBER()OVER(ORDER BY(SELECT\))-1F FROM sys.all_views a,sys.all_views b)c
JOIN R ON N=F+@-G
)
-- Sum the multiplied values
SELECT SUM(V)FROM o GROUP BY F ORDER BY F
```
Result
```
-142
55
27
41
-269
397
```
[Answer]
# c, 68 55 bytes
```
f(int *l){for(--l[-1]?f(l):0;*l;l++)*l=l[1]-*l;*--l=0;}
```
This might be taking liberties with the input spec a bit. An int array is constructed such that element 0 is the depth and elements 1 to (n+1) are the input list elements 0 to n. Then the address of element 1 is passed to the function.
The array must be zero terminated. The array is edited in place.
E.g:
```
#include <stdio.h>
f(int *l){for(--l[-1]?f(l):0;*l;l++)*l=l[1]-*l;*--l=0;}
int main (int argc, char **argv)
{
int list[] = {4, 10, 18, -12, 4, 8, -3, -5, 67, 9, 14, 0};
int *elem;
f(list + 1);
for (elem = list + 1; *elem; elem++) {
printf("%d, ", *elem);
}
}
```
<http://ideone.com/m5PDgF>
[Answer]
# [Factor](https://factorcode.org/), 25 bytes
```
[ [ differences ] times ]
```
[Try it online!](https://tio.run/##HcU5DsIwEEDRnlP8CyTCYPYDIBoaRBVRWGYiLBwT2dMgxNnN0rzXO6@PXM@nw3G/5S45SWRwevvTFnUaigZfGLOoPscckrKbvDBTzJrGzLB8n9MsWK7YYCxvbO3ouIa@lyzJS@GChuF39S5G2voB "Factor – Try It Online")
* `times` Call a quotation a certain number of times.
* `differences` Calculate the first-order differences of a number sequence.
* E.g. `{ 1 4 2 } -> { 3 -2 }`
[Answer]
# Powershell ~~115~~ 111 bytes
```
$p={param($a, $b)0..($a-1)|%{$b=@($l=$b.length;for($i=0;$i-lt$l;$i++){$b[$i+1]-$b[$i]})[0..($l-2)]};$b-join','}
```
Execute as such:
```
.$p 4 @(10,18,-12,4,8,-3,-5,67,9,14)
```
Output:
```
-142,55,27,41,-269,397
```
Moving a curly brace to a different spot allows this to display every step to the answer.
```
8,-30,16,4,-11,-2,72,-58,5
-38,46,-12,-15,9,74,-130,63
84,-58,-3,24,65,-204,193
-142,55,27,41,-269,397
```
[Answer]
## STATA, 126 bytes
```
di _r(a)_r(b)
token $b
gl $c=wordcount($b)
forv x=1/$a{
gl $c--
forv y=1/$c{
loc `y'=``y'+1'-``y''
}
}
forv z=1/$c{
di ``z''
}
```
Expects input as an integer representing the depth, followed by a space separated list of integers, both given via the standard prompt. Output is newline separated list of integers.
First it converts the list of integers (which it views as 1 long string) into a list of local variables whose names are 1,2,3,... Then it computes forward differences by setting the value of the yth local variable to be the value of the y+1th local variable minus the value of the yth local variable (i.e. 18-10=8), which overwrites existing values only after use. It does this $a (value of global variable a) times. Then it displays the value of each local variable, 1 at a time.
[Answer]
# [Japt](https://github.com/ETHproductions/japt) `-h`, ~~17~~ 5 bytes
*12 bytes saved thanks to @Shaggy*
```
VÆ=än
```
[Try it online!](https://tio.run/##y0osKPn/P@xwm@3hJXn//0cbGugoKCgYWgBJXUMjEFvBBEyCRBR0jcGkKZA0MwcSlkBsaBLLZcKlmwEA "Japt – Try It Online")
[Answer]
# [K (ngn/k)](https://bitbucket.org/ngn/k), 8 bytes
```
(1_-':)/
```
[Try it online!](https://tio.run/##y9bNS8/7/z/NSsMwXlfdSlP/f1q0ibWCoYGCoYWCrqGRgokCkDZW0DVVMDNXsFQwNIn9DwA "K (ngn/k) – Try It Online")
Sets up a [do-over](https://code.kx.com/q/ref/accumulators/#do), running the code in parenthesis `depth` times, seeded with `initial values`. Results from one iteration are passed into the next.
* `-':` take the deltas of the input
* `1_` drop the first delta (which is just the first value in `x`)
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), 3 bytes
```
(¯N
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%28%C2%AFN&inputs=4%0A%5B10%2C%2018%2C%20-12%2C%204%2C%208%2C%20-3%2C%20-5%2C%2067%2C%209%2C%2014%5D&header=&footer=)
Takes input like `n, [list]`
[Answer]
# [Thunno 2](https://github.com/Thunno/Thunno2), 2 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md)
```
{Ṣ
```
[Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPSZjb2RlPSU3QiVFMSVCOSVBMiZmb290ZXI9JmlucHV0PTQlMEEoMTAlMkMlMjAxOCUyQyUyMC0xMiUyQyUyMDQlMkMlMjA4JTJDJTIwLTMlMkMlMjAtNSUyQyUyMDY3JTJDJTIwOSUyQyUyMDE0KSZmbGFncz1l)
#### Explanation
```
{Ṣ # Implicit input
{ # Input number of times:
Ṣ # Deltas
# Implicit output
```
[Answer]
# Swift, 51 bytes
```
{for _ in 0..<$0{$1=zip($1.dropFirst(),$1).map(-)}}
```
Takes `(depth, &arr)` and modifies the input array to contain the result.
[Try it on SwiftFiddle!](https://swiftfiddle.com/ztxe4epqhzebjdwber7idpr6la)
Ungolfed/commented:
```
{ (depth: Int, arr: inout [Int]) in
// Iterate the specified number of times. The iteration number isn't needed.
for _ in 0..<depth {
// Modify the input array to contain the next iteration:
arr =
// Get adjacent pairs in reverse order -- dropFirst returns a slice
// without mutating the original array.
zip(arr.dropFirst(), arr)
// Subtract adjacent pairs. Swift lets you use an operator as if it
// were a value of function type -- in this case, (Int, Int) -> Int.
// This particular case is only legal because ((T, U)) -> V and
// (T, U) -> V are equivalent types, but I think they're only
// equivalent to make this kind of thing legal.
.map(-)
}
}
```
[Answer]
# [Uiua](https://uiua.org) [SBCS](https://tinyurl.com/Uiua-SBCS-Jan-14), 8 bytes
```
⍥(↘1°\+)
```
[Try it!](https://uiua.org/pad?src=0_8_0__ZiDihpAg4o2lKOKGmDHCsFwrKQoKZiA0IFsxMCAxOCDCrzEyIDQgOCDCrzMgwq81IDY3IDkgMTRdCg==)
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 7 bytes
A couple of alternatives I'd made available to Luis for [his solution](https://codegolf.stackexchange.com/a/169655/58974).
```
_än}gNÅ
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=z8Q8Vn1mQD3kbg==&input=WzEwLDE4LC0xMiw0LDgsLTMsLTUsNjcsOSwxNF0KNA==)
## 10 bytes
```
ÏÄ<V}f@=än
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=z8Q8Vn1mQD3kbg==&input=WzEwLDE4LC0xMiw0LDgsLTMsLTUsNjcsOSwxNF0KNA==)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 2 bytes
*Ties [HyperNeutrino's Jelly answer](https://codegolf.stackexchange.com/a/146120/94066) for #1.*
```
F¥
```
[Try it online!](https://tio.run/##yy9OTMpM/f/f7dDS//9NuKINDXQUDC10FHQNjXQUTHQUQExjIDbVUTAz11GwBMqaxAIA "05AB1E – Try It Online")
```
F¥ # full program
F # for N in [0, 1, 2, ...,
# ..., implicit input...
F # ...minus 1]...
¥ # get differences of elements in...
# implicit input...
¥ # or top of stack if not first iteration
# implicit output
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 4 bytes
```
.+FE
```
[Try it here!](http://pythtemp.herokuapp.com/?code=.%2BFE&input=4%0A%5B10%2C+18%2C+-12%2C+4%2C+8%2C+-3%2C+-5%2C+67%2C+9%2C+14%5D&debug=0)
[Answer]
# x86-16 machine code, 20 bytes
```
00000000: 4951 568b fead 938b 042b c3ab e2f7 5e59 IQV......+....^Y
00000010: 4a75 edc3 Ju..
```
Listing:
```
DEPTH_LOOP:
49 DEC CX ; decrement length
51 PUSH CX ; save length
56 PUSH SI ; save array pointer
8B FE MOV DI, SI ; set array pointer for output
DIFF_LOOP:
AD LODSW ; load first WORD into AX, advance SI
93 XCHG AX, BX ; save first to BX
8B 04 MOV AX, WORD PTR[SI] ; load second WORD into AX (don't advance)
2B C3 SUB AX, BX ; AX = AX - BX
AB STOSW ; save result to current array index
E2 F7 LOOP DIFF_LOOP ; loop until end of array
5E POP SI ; restore array pointer
59 POP CX ; restore length
4A DEC DX ; decrement depth counter
75 ED JNZ DEPTH_LOOP ; loop until end of depth
C3 RET ; return to caller
```
Input array at `[SI]`, input length (in bytes) in `CX`, depth in `DX`.
Test with DOS DEBUG:
[](https://i.stack.imgur.com/i483d.png)
Note: data is shown as little endian hex in DEBUG (`A 0` = `0x000a` = `10`, `72 FF` = `0xff72` = `-142`).
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal/tree/version-2), 2 bytes
```
(¯
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2&c=1#WyIiLCIiLCIowq8iLCIiLCI0XG5bMTAsIDE4LCAtMTIsIDQsIDgsIC0zLCAtNSwgNjcsIDksIDE0XSJd)
```
( # n times
¯ # take forward differences
```
[Answer]
# SmileBASIC, 76 bytes
Finally a reason to use `ARYOP`!
```
DEF F L,D
IF!D THEN@R
DIM B[0]COPY B,L
T=SHIFT(L)ARYOP 1,L,L,B
F L,D-1@R
END
```
[Answer]
# Clojure, 47 bytes
```
#(if(= 0 %)%2(recur(dec %)(map -(rest %2)%2))))
```
A simple recursion on anonymous function. You save 1 byte if the order of arguments is swapped as now `%2` occurs more frequently than `%`.
] |
[Question]
[
Yet another Jimmy challenge by his original father. See these [other](https://codegolf.stackexchange.com/questions/187586/will-jimmy-fall-off-his-platform) [lovely](https://codegolf.stackexchange.com/questions/187682/how-many-jimmys-can-fit) [challenges](https://codegolf.stackexchange.com/questions/187731/jimmy-needs-your-help).
---
As you all know, recently we've been seeing challenges related to Jimmy on platforms. Now, Jimmy is an acrobat as I mentioned before, and he's got other tricks up his sleeve.
One of these tricks is hanging by ropes. Here's an example of a rope Jimmy could hang from:
```
||
||
||
||
||
||
```
When Jimmy hangs on a rope, it looks like this:
```
||
||
/o\
||
||
||
```
He can hang on the left or the right of the rope, so this:
```
||
||
||
/o\
||
||
```
is also valid. But he cannot hang by just one body part, so anything like this:
```
||
||
||
/o\|
||
||
```
is invalid. Note that when he is hanging by one body part the other half of the rope is visible because Jimmy does not cover it up.
Also, Jimmy does not like hanging on the bottom of the rope - it scares him - so this:
```
||
||
||
||
||
/o\
```
is invalid.
# The challenge
Take input of a Jimmy situation like the ones above, and output whether Jimmy will hang on to the rope or not through a truthy or falsy value.
# The specifics
* Write a program that takes input. This can be through a function or any other appropriate input method.
1. The input should be a scene of one Jimmy and a rope as exemplified above.
* The program should output a truthy or falsy value to the console based on whether Jimmy can hang on to the rope or if he would fall off the rope, respectively.
* The criteria for Jimmy being able to hang on the rope:
1. Two of his body parts are on the rope.
2. He is not on the bottom of the rope.
3. He is not floating in mid-air.
* You can assume the rope will be straight, made up of `||` segments, and will be longer than one character in height.
* You can assume one whole rope and one singular Jimmy will be present in your scene, no more and no less.
* You can assume there will be no trailing newlines at the bottom of the rope.
* You must cover any amount of leading or trailing spaces before and after the rope.
# Test cases
```
||
||
|| TRUTHY
/o\
||
||
||
||
/o\| FALSY
||
||
||
/o\ TRUTHY
||
||
/o\ FALSY
/o\
|| TRUTHY
||
||
/o\ || FALSY
||
||
```
# Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so lowest score in bytes wins after about a week.
# Leaderboard
You can view the leaderboard for this post by expanding the widget/snippet below. In order for your post to be included in the rankings, you need a header (`# header text`) with the following info:
* The name of the language (end it with a comma `,` or dash `-`), followed by...
* The byte count, as the last number to appear in your header.
For example, `JavaScript (ES6), 72 bytes` is valid, but `Fortran, 143 bytes (8-bit)` is invalid because the byte count is not the last number in the header (your answer will be recognized as 8 bytes - don't take advantage of this).
```
<!-- Run the snippet to see the leaderboard. Report any bugs to @ozewski on Github. --> <iframe src="https://ozewski.github.io/ppcg-leaderboard/?id=187759" width="100%" height="100%" style="border:none;">Oops, your browser is too old to view this content! Please upgrade to a newer version of your browser that supports HTML5.</iframe><style>html,body{margin:0;padding:0;height:100%;overflow:hidden}</style>
```
[Answer]
# [Python 2 or 3](https://docs.python.org/3/), ~~33~~ 30 bytes
-3 thanks to [Maxwell](https://codegolf.stackexchange.com/users/87771)
```
lambda l:'o'in map(max,l[:-1])
```
An unnamed function accepting a list of lines
**[Try it online!](https://tio.run/##nZHLCsIwEEXXzVdkNwlUpbgL9EsaFxEbDORFm4VC/j3Gbmo0VHF2wxwOc7n@Hq7OHpPsedLCnC8CawYOlMVGeGLErdUD23UnmqSbcBjngPONoAkAEF4nxl@3g@ObaBa36MP/xpVrVsYv8GItpCvz@lEVrYeocGW2P8JkwXbU1UoZarSy44z7pZf97LUKBLgFOnTPzlDjJ2UDkWThKE0P "Python 3 – Try It Online")**
### How?
There needs to be a section of rope obscured by Jimmy that is not the bottom one.
```
lambda l:'o'in map(max,l[:-1])
lambda l: # a function taking l (the lines as strings)
l[:-1] # strip off the last line
map(max, ) # maximum of each line (where '|'>'o'>'\'>'/'>' ')
'o'in # was 'o' one of them? (hence Jimmy obscured all the rope)
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 5 bytes
I *think* this is right; I've been working for 16 hours straight and barely know my own name so I wouldn't be surprised if it's not!
```
Õø|io
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=1fh8aW8&input=IiAgICAgICAgICAgfHwKICAgICAgICAgICB8fAogICAgICAgICAgIHx8ICAKICAgICAgICAgICAvb1wKICAgICAgICAgICB8fAogICAgICAgICAgIHx8Ig)
```
Õø|io :Implicit input
Õ :Transpose
ø :Contains?
|io : "|" prepended with "o"
```
[Answer]
## Python 2, 28 bytes
```
lambda x:"o', '|"in`zip(*x)`
```
[Try it online!](https://tio.run/##nY@7CsIwFIb3PsWhSxORCo6FDC7i4KR1ECtaaUoDMQ1txQt599qL2itW/IeQc/vP@eQ9CUIxTX3ipNw9nzwXbpYeGmMwlM7E8cEkGt3wMeVkt9euAeMU7OhCLQ0yxSRyrwcm5CVBuMgwH2IgBHRTL1tyyYiJBPmIY/zJcSCQOeZfymNaNXPTlZIKD8U4hUpKaV8iaMtebezFtt40CZ1vDppZj1vlZpg5dRbOZ8v1dsCh2lDVMi/oUev893APaOeAnLPG0sTuM3jt@pG/OFj9z1@m3@8wjnoB5PNP)
How does it work? It takes input as a list of strings, and zip joins the string. Jimmy stays on the rope if there is a "|" below an "o", so this code joins all the lines and checks if there is an "o" followed by a "|".
Annotated code:
```
lambda x: # Creates an anonymous function that takes one argument
"o', '|" # If this substring is in the zip object, then Jimmy's "o" is above a "|"
in
` # Back quotes change the object into its string representation
zip(*x)` # Joins the lines together
```
## (Old Answer) Python 2 or 3, 39 bytes
```
lambda x:1-all("|"in i for i in x[:-1])
```
A function that takes input as a list of strings, each string being a different line.
-11 bytes thanks to xnor! -2 bytes thanks to Jonathan Allan!
[Try it online! (If you want to try more test cases, just put a "." after each set of lines in the input box.)](https://tio.run/##nU89D4IwEN35FRemdhBjXAxJBxfj4KQ4GGXAWGKTszR8REz637GICgJB4xsu9@7j3T11S8@RnM5UXITsUGBwOZ4CyN3JKEAktraFBAFhFJto0nzvjiY@LZDtfet6FsjBizPuWmCQMCFVlhL6YCKEBBgD27GrdgkVC5mSkCCl7xoCA6NWphwTXg@jEyjF5YkktIAaWlsDDNrw1ltvuWsOjaPDkILlNHmr/UmNUufgYr7a7L4o1BfqntGCHrTefy33GO08UPpsePm03SfwvPWj/8fD@n//VfkVv9vRTwPl/h0)
How does this work? Well, if Jimmy is fully on the rope, then that line will not have any "|" characters. Therefore, we can check each line, and if we find any with no "|" characters, then we know that Jimmy can stay on the rope. However, Jimmy can not hang on to the bottom of the rope; therefore, we don't include the final line in our check. If the final line is just another part of the rope, than it won't matter, because we'll still find a valid row higher up, but if the final line is the one with Jimmy, then it won't find a line without "|" anywhere, and will return False.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~9 7~~ 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/CWde-page)
```
Ṗ<”|ṀẠ
```
A monadic Link accepting a list of lines
**[Try it online!](https://tio.run/##y0rNyan8///hzmk2jxrm1jzc2fBw14L/D3dvOdz@/78CEqip4cLD1c@PQZMGAA "Jelly – Try It Online")**
### How?
There needs to be a section of rope obscured by Jimmy that is not the bottom one.
```
Ṗ<”|ṀẠ - Main Link: list of lines of characters
Ṗ - remove last line
”| - pipe character
< - less than? (vectorises) - Note that all other characters are
Ṁ - maximum
Ạ - all?
```
[Answer]
# [Grime](https://github.com/iatorm/grime), 5 bytes
```
\o/\|
```
[Try it online!](https://tio.run/##Sy/KzE39/z8mXz@m5v9/BSioqeGCsvTzY7gQogA "Grime – Try It Online")
The right tool for the job.
```
\o # match an "o"
/ # above
\| # a "|"
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes
```
Çü%àθ
```
[Try it online!](https://tio.run/##yy9OTMpM/W/mVvP/cPvhPaqHF5zb8V/nvwIC1NRwEcnTz4/BqxSZiyaLygUaVENAMRemFLL1@G0DqeTC4Wyi3QnUht8XIC4A "05AB1E – Try It Online")
```
Ç # convert the input to a 2D array of codepoints
ü% # pairwise modulo (vectorized)
à # maximum (*not* vectorized, returns a single number)
θ # tail (last digit)
```
The only characters that can appear in the input are `\o/ |`, with respective
codepoints 92, 111, 47, 32, 124 (there are no newlines, since we chose to take
input as an array of lines). The possible results by moduloing two of these
numbers are 0, 13, 15, 17, 19, 28, 30, 32, 45, 47, 92, 111. 111 is the largest
of those, and also the only one that ends with 1, so the code will output truthy
if and only if 111 is present in the list (only 1 is truthy in 05AB1E). 111
is 111 (`o`) % 124 (`|`), and so only occurs if there's an `o` above a `|` in the input.
[Answer]
## brainfuck, ~~79~~ 64 bytes
```
>>+<<,[----------[<]>>[.-]+<[>-]+[---------<-->]<[<]>>[-]<[>]<,]
```
[Try it online!](https://tio.run/##SypKzMxLK03O/v/fzk7bxkYnWhcOom1i7eyi9XRjtW2i7YAkQspGV9cu1gYirwtkADk6sf//KyBATQ0XkTz9/Bh8SgE)
Outputs the 0x01 byte for truthy and nothing for falsy.
```
Z: 0
A: input
B: 0
C: has no | been found on this line?
>>+<< initialize C to 1
,[ loop over each char
---------- set A to 0 if input was \n
[<]>> move to C if input was \n; B otherwise
[ if input was \n and C is true
.- output 1
]
+ this will reinitialize C to 1 if input was \n
but also clobber B with 1 if it wasn't
now we have { 0 0 0 (1)} if input was \n;
{ 0 _ (1) _ } otherwise
<[>-] clear own cell if the one to the left is positive
this yields { 0 0 (0) 1 } and
{ 0 _ (0) _ } as desired
+[---------<-->] set A to 0 if input was |
<[<]>> move to C if input was |; B otherwise
[-] zero out current cell: clears C if input was |
<[>]< realign pointer onto A
,] break on end of input
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 6 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
é¿┤4╠q
```
[Run and debug it](https://staxlang.xyz/#p=82a8b434cc71&i=+++++++++++%7C%7C%0A+++++++++++%7C%7C%0A+++++++++++%7C%7C++%0A+++++++++++%2Fo%5C%0A+++++++++++%7C%7C%0A+++++++++++%7C%7C%0A%0A++++++++++++%7C%7C%0A++++++++++++%7C%7C%0A++++++++++%2Fo%5C%7C%0A++++++++++++%7C%7C%0A++++++++++++%7C%7C%0A%0A++++++++%7C%7C%0A+++++++%2Fo%5C+%0A++++++++%7C%7C%0A%0A++++++++++++%7C%7C%0A+++++++++++%2Fo%5C+%0A%0A+++++++++%2Fo%5C%0A++++++++++%7C%7C++%0A%0A++++++++++++%7C%7C%0A++++++++++++%7C%7C%0A+++++++%2Fo%5C++%7C%7C++%0A++++++++++++%7C%7C%0A++++++++++++%7C%7C&a=1&m=1)
Transposes the input, then searches for "o|".
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 8 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set")
Anonymous tacit prefix function, taking a character matrix as argument.
```
1∊'o|'⍷⍉
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///3/BRR5d6fo36o97tj3o7/6c9apvwqLfvUd9UT/9HXc2H1hs/apsI5AUHOQPJEA/P4P@eYCVruDx1QIyuJnUFBKipARLqVJTSz48h30Cgi4FyaQpAL3hyceFzN1CHOkkSQHeRqAMiQaSTsJkBtFIdu0oq@BNsOLHmYHcJ1dyCy/ekxxKmkwA "APL (Dyalog Unicode) – Try It Online")
`⍉` transpose
`'o|'⍷` mask for everywhere `o` is immediate followed by `|`
`1∊` is one a member thereof?
[Answer]
# Dyalog APL Extended, ~~14~~ ~~13~~ ~~11~~ 9 bytes
```
3∊¯1+/⍤↓<
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/P@1R2wTjRx1dh9Ybaus/6l3yqG2yzX9PoOCj3jVcnjogRleTugIC1NQACXUqSunnx5Bv4KO@qUC5NIVHbRM9ubjwuRuoQ50kCaC7SNQBkSDSSdjMAFqpjl0lFfwJNpxYc7C7hGpuweV70mMJ00n/AQ "APL (Dyalog Extended) – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 19 bytes
```
any(all(<'|')).init
```
[Try it online!](https://tio.run/##jYoxDsIwEAT7vGILpNhFwgccGr6R5hTsYHGcLXxFIvntOJRUiOlGM3cqD8/cwjQ3kt0Qs3F97a0do0RtT4qCCbfUARvcAI7iC9zpgtXrNYl60fKJ@RVFYQI22/BFrd3/ek7z7/u9BKa1tGHJ@QA "Haskell – Try It Online")
[Answer]
# JavaScript, ~~39~~ 33 bytes
Thanks @Daniil Tutubalin for golfing off 2 bytes
```
x=>!!x.match(/^( *)\/[^|]*\n/m)
```
This matches any line which is not the line where his left arm shows up and none of the rope shows.
[Try it online!](https://tio.run/##bVFLbsMgFNz7FC4riKl/UVYOOUG7T4WJZDk4Adlg2ThK1eTsLv6kTZOyYTRvZp4YZHbK2rwRtXlVes/7gvRnsnl5OftVZvIjDHbQXaA0oLsLW6QqqFAvRVV9atXomh@4InAAb1wdzBEPcItHwXx9ILL50p2pO0MoSwrdQEHCRKx/XYnwPDRrqGAEuMBveM0zM0ZvkQcuF5CIwjrJHHon/0F@W4qcw3Deb22BTlPgPQqmsbdE139CvLvt75k5@k2m9rqCaBGF6Npw0zXKndS@1EJBkCqAro5zysqOt4TSJY5xhGOGHXc@dGWpEEePVPRMxc/UylLMcYbmpG1OrqdNfjmVJ4fyrGNkyTSjklkm16rVJfdLfYAt@ftrcBTSkOEJRDcQ38CSIfQQUsDWcvat/Tc "JavaScript (Node.js) – Try It Online")
[Answer]
# [///](https://esolangs.org/wiki////), ~~53~~ 50 bytes
```
/~/\/\~/\/o\\/1~1 /1~ 1/1~|1~/1|~/|~/1.~/ ~/.~/
~.
```
[Try it online!](https://tio.run/##K85JLM5ILf7/Xz9GPz8mRt9QX99QAUQqGILIGiDWN6wBEiBsqAckFIAYRHMBqf//AQ "/// – Try It Online")
Because there is no other way to take input in ///, it is hard-coded:
```
/~/\/\~/\/o\\/1~1 /1~ 1/1~|1~/1|~/|~/1.~/ ~/.~/
~<INPUT HERE>.
```
**Explanation:**
The general approach is to replace Jimmy with a unary 1, then remove him from all situations where he is in danger. If he survives, he is outputted. If he doesn't, then nothing is. The `~` in the code are a replacement for `//`, which allow the code to be shortened by 3 bytes here. They are omitted from the explanation.
```
/{/\//
/}/\/\//
{The top two lines allow me to leave comments without disturbing the code.}
/\/o\\/1/ {Replace Jimmy with a 1.}
/1 /1/ {Get rid of any spaces in front of Jimmy. This moves Jimmy towards the rope from the left.}
/ 1/1/ {Get rid of any spaces after Jimmy. This moves Jimmy towards the rope from the right.}
/|1// {If Jimmy is touching the rope, remove him and the rope.}
/1|// {This is based on the observation that in all cases where Jimmy is safe, there is no visible rope on his line.}
/|// {Remove any remaining rope. If Jimmy was touching a rope, it's already too late for him.}
/1.// {This handles the case where Jimmy is at the bottom of the rope (hence the period at the end).}
/ // {The remaining lines clean up the output.}
/.//
/
//
||
||
||
/o\
||.
```
[Try it online!](https://tio.run/##nVNNj5wwDL3zK3xrK1VE/IqqPVZ7nIsBs4kUYpSYQauZ/e1TO8ywnR6qqggJHH@99@yUiMVTud3cxZ2ca9y7fuyngeO5vHgC4QVkY4ghUQGMkTeY7Rgi4Zlg4HmmJAW2IJ5XgTEUWXMf0iuIN/9I7XvTaHE@nVzn4PKTlogDwY8wz281DxA6DXIdWIC1/kYCOYzAE2B6g7JoQoGQYMqcxI5rdgsvPhSY@azevZ7whnkstXnmhSxjrlakSawLdH/vgpNQ/o/6Obx6qVyvnXO7hN/vQEGrCK@Df@hiqV8hk5UGH2YFMB6OqsX1UaNC0LfHQoo11TDuC@UzSqg2immj04FBg3QYnjJ9dC44aTOph2omhnMooY93BlrCWtiIDb7iv7e2WVWApo5ixZAMf4UIB7UNf@OGd2ZBPtm6ZMLRNNN1QVGtOBvZyq994ueVf6RdVuPwJwVlaK6eRVRuHdih/2dPSbfJ7IVy4PERS2n8svOBg4@t9AeRfakH3eQE67Lrusqy1jVp7Vo0z1cCrtd/tXTdn53t7fYL "/// – Try It Online")
[Answer]
# Ruby 2.5.5, 22 bytes
```
->x{x.pop;!x.all? /\|/}
```
Expects an array of lines. Requires a minimum of version 2.5.5 because this is when `Array#all?(pattern)` was added.
Because of the constraints that the input will always be a valid scene of Jimmy and a rope, it boils down to whether any of the lines prior to the last line have the rope obscured.
[Answer]
# [Kotlin](https://kotlinlang.org), ~~93~~ 84 bytes
```
fun j(a:List<String>){print(a.count{!it.contains("|")}==1&&!a.last().contains("o"))}
```
[Try it online!](https://tio.run/##bY4xD4IwEIVn@itKB9IuGFciJu5uriyNCeQQrqY9BgL97bWCUaLe8u7e9/JyN0MdYAj1gLyVujiDo8OFLGBzVNM9KkmdX82ANKVAcUPSgE6KWShflvssS3XeaUdSbaARSvmltI@G1LZxBT9Zq8d3OZ9YUhvLZQt9P64uB@TP7AKTdotyd@@ApKgwVke4vracLPHMh8DjzDP7kZ2pXtefSIThk1nNbTCCr8oH "Kotlin – Try It Online")
[Answer]
# Elm 0.19, ~~68~~ 60 bytes
```
List.any(not<<String.contains"|")<<List.drop 1<<List.reverse
```
Anonymous, points-free function. Takes input as a list of lines. Disregarding the last line, it checks whether there are any with no `'|'` in them – implying the rope is fully covered by Jimmy.
Thanks to [Lynn](https://codegolf.stackexchange.com/users/3852/lynn) for golfing 8 bytes.
Verify all test cases [here](https://ellie-app.com/bNqKW2RXqBha1).
[Answer]
# JavaScript, ~~38~~ 37 bytes
```
r=>r.some(x=>!~x.search`\\|`,r.pop())
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9h@7/I1q5Irzg/N1WjwtZOsa5Crzg1sSg5IyEmpiZBp0ivIL9AQ1Pzf3J@XnF@TqpeTn66RoZGtJICENTUgEglHTBHPz8mBsGDycVqaoLk9BVKikpTuQgZAjWDIkNAZtTgMyQtMaeYsFMUaiCOocQUsFOo4haIYyg2BTO60E35DwA "JavaScript (Node.js) – Try It Online")
[Answer]
## [Retina](https://github.com/m-ender/retina), 9 bytes
```
m`^[^|]+^
```
[Try it online!](https://tio.run/##K0otycxLNPz/PzchLjquJlY77v9/BSRQU8NFAReZp4Aip58fg6YWAA)
Now, I've never programmed in Retina before, but as far as I can tell this works. It is a regular expression that finds a string containing (1) the beginning of the input, (2) no "|" characters, and (3) a newline.
People more familiar with either regular expressions or Retina are encouraged to offer suggestions. -2 bytes thanks to Neil!
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, 26 bytes
```
$\||=!/\|/;$;=/o/}{$\&&=!$
```
[Try it online!](https://tio.run/##K0gtyjH9/18lpqbGVlE/pkbfWsXaVj9fv7ZaJUZNzVZR5f9/BQSoqeHCw1NAByFBoSEekciK9PNjUPX8yy8oyczPK/6v62uqZ2Bo8F@3AAA "Perl 5 – Try It Online")
[Answer]
# [Befunge-98 (PyFunge)](https://pythonhosted.org/PyFunge/), ~~26~~ 24 bytes
```
]~:a-!#v_' `+
^_-3q#$<
@
```
[Try it online!](https://tio.run/##S0pNK81LT9W1tNAtqAQz//@PrbNK1FVULotXV0jQ5oqL1zUuVFax4XL4/18BCdTUcOHh6ufHcOFVDQA "Befunge-98 (PyFunge) – Try It Online")
Exits with return code 3 if `\n` is encountered and the last line contained 3 non-space characters, otherwise exits with return code 0 on EOF. Thus, this relies on the last line not containing a trailing newline.
### Dissected
```
]~ :a-!#v_ ' `+
Read character, Branch downwards if Increment counter on
branch up (and equal to 10 ('\n') the stack if greater
loop around) if than 32 (' ') and
end of stream implicitly loop
^_-3q#$< <
Return with code 3
if counter is equal to 3,
otherwise reset counter
and return to beginning
@
Return with exit
code 0
```
[Answer]
# [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/wiki/Commands), 6 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ζJ„o|å
```
Port of [*@Shaggy*'s Japt answer](https://codegolf.stackexchange.com/a/187786/52210).
Input as a list of lines.
[Try it online.](https://tio.run/##MzBNTDJM/V/z/9w2r0cN8/JrDi/9/18BCmpquKAs/fwYLoQoAA)
**Explanation:**
```
ζ # Zip/transpose the (implicit) strings in the input-list, with space as filler
# (NOTE: zip/transpose doesn't work on string-list in the new version of 05AB1E,
# which is why we use the legacy version)
J # Join these zipped/transposed lines together to a single string
„o|å # And check if it contains the string "o|"
# (after which the result is output implicitly)
```
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 26 bytes
Port of [Maxwell's answer for Retina](https://codegolf.stackexchange.com/a/187766/80745).
```
"$args"-match'(?m)^[^|]+^'
```
[Try it online!](https://tio.run/##hZDdDoIwDEbv9xTNnLpFiPcmRt5DRQkWxExANqOJ89lxgj/ETN1Nl689p0nL4oSV2qKUNUtgCpeasqhKFfX3kY63Qz7bi3AemuUoHNZXQgJOiMeZro7oBZSAfcY4yrhYfKQ0EA2aRFI5WYuYL4xjXWfBL/N9zGX5h3cU76@FHCl0PQIM9OHS5AzPJcYaNx4wmeWo7H3Zqm1VqI5S22Bgz87btr8rspyucyruIz1QpYy0zvK0QSjjD8rHw0stJk8XJdf6Bg "PowerShell – Try It Online")
Explanation:
`true` if:
1. there is a line in a scene that does not contain the character `|`
2. and after this line there is a start of a new line.
`false` otherwise.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 6 bytes
```
€'om▲h
```
[Try it online!](https://tio.run/##yygtzv6fm/@oqfHQtgqlQ9sObfv/qGmNen7uo2mbMv7//6@AADU1XETy9PNjYvCqReaiyaJyQSbV4FcNAA "Husk – Try It Online") A port of [Jonathan Allan's answer](https://codegolf.stackexchange.com/a/187760).
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 6 bytes
```
Ḣ\|vOA
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCLilqEiLCLhuKJcXHx2T0EiLCIiLCJ8fFxufHxcbi9vXFxcbnx8Il0=)
Takes a list of lines, returns a 1 if Jimmy can't hang on, 0 if he can.
[Answer]
# [Pyth](https://pyth.readthedocs.io), 9 bytes
```
sPm!sqR\|
```
[Test suite!](https://pythtemp.herokuapp.com/?code=sPm%21sqR%5C%7C&test_suite=1&test_suite_input=%5B%22++++%7C%7C++++%22%2C%22++++%2Fo%5C%5C+++%22%2C%22+++++%7C%7C++++%22%5D%0A%5B%22++++%7C%7C++++%22%2C%22+++%2Fo%5C%5C++++%22%2C%22+++++%7C%7C++++%22%5D%0A%5B%22++++%7C%7C++++%22%2C%22++%2Fo%5C%5C%7C++++%22%2C%22+++++%7C%7C++++%22%5D%0A%5B%22++++%7C%7C++++%22%2C%22++++%7C%2Fo%5C%5C++%22%2C%22+++++%7C%7C++++%22%5D%0A%5B%22++++%7C%7C++++%22%2C%22+%2Fo%5C%5C%7C%7C++++%22%2C%22+++++%7C%7C++++%22%5D%0A%5B%22++++%7C%7C++++%22%2C%22++++%7C%7C%2Fo%5C%5C+%22%2C%22+++++%7C%7C++++%22%5D%0A%5B%22++++%7C%7C++++%22%2C%22++++%7C%7C++++%22%2C%22++++%2Fo%5C%5C++++%22%5D&debug=0)
[Answer]
# Pyret, 79 bytes
```
{(l):all2({(r,n):string-char-at(n,string-index-of(r,"o") == "|")},l,link(0,l))}
```
Expects an array of lines as strings. Makes a copy in `link(0,l)` where all rows shifted down by one. Goes through each row `r` and `n` where n is the row below r. Checks that if Jimmy's body `"o"` is at some position, then the row below it has a pipe there (i.e. Jimmy's hanging on the rope and isn't at the bottom).
[Answer]
# [SnakeEx](http://www.brianmacintosh.com/snakeex/spec.html), 7 bytes
```
j:<R>o|
```
[Try it here!](http://www.brianmacintosh.com/snakeex/)
### Explanation
The only necessary and sufficient condition is that Jimmy's torso has to have a rope character below it.
```
j: Define the main snake, j (for Jimmy)
<R> Pivot right (i.e. downward, since the snake starts out moving to the right)
o Match Jimmy's torso and move down
| Match a rope character
```
[Answer]
# [Rockstar](https://codewithrockstar.com/), ~~147~~ ~~146~~ 137 bytes
Outputs `0` for `false` and `1` for `true`
```
listen to J
Y's 0
while J
cut J
listen to R
X's 0
while J
let S be R at X
let Y be+roll J's "o" and S's "|"
let X be+1
let J be R
say Y
```
[Try it here](https://codewithrockstar.com/online) (Code will need to be pasted in)
```
listen to J :Read first line of input into variable J
Y's 0 :Initialise Y as 0
while J :While J exists
cut J : Split J into an array
listen to R : Read next line of input into variable R
X's 0 : Initialise X as 0
while J : While J is not empty
let S be : Assign to variable S
R at X : The character in R at 0-based index S
let Y be+ : Increment Y by
roll J : Pop the first element from J
's "o" : Eqaul to "o"?
and : Logical AND with
S's "|" : S is equal to "|"
let X be+1 : Increment X
: End while loop
let J be R : Reassign R to J
:End while loop
say Y :Output Y
```
] |
[Question]
[
Given a digit `x` (between 0 to 9, inclusive) and a number `n`, calculate the sum of the first `n` terms of the following sequence:
\$x,10x+x,100x+10x+x,\dots\$
For example, if `x` is 6 and `n` is 2, then the result will be `6+66` meaning 72.
There can be trailing whitespace in the output but not leading whitespace.
[Answer]
# [Python 2](https://docs.python.org/2/), 28 bytes
```
lambda x,n:(10**-~n/9-n)/9*x
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUaFCJ89Kw9BAS0u3Lk/fUjdPU99Sq@J/QVFmXolGmoaZjpGmjoKZgraCmZkmF0LUGC4KJlDkTNDkIKSZ5n8A "Python 2 – Try It Online")
-6 thanks to @Bubbler and @tsh
Aha the first answer I have used some math
**How?**
Let's call \$n^{th}\$ term as \$y\$
$$
S\_n=x+(10x+x)+(100x+10x+x)+.....+y\\= x+(11x)+(111x)+.....+y\\=\frac{x}{9}(9+99+999+.....+y)\\=\frac{x}{9}((10-1)+(100-1)+(1000-1)+.....+y)\\=\frac{x}{9}((10+100+1000+.....+y)-(1+1+1+.....+1))\\=\frac{x}{9}((10^1+10^2+10^3+...+y)-n)\\=\frac{x}{9}(\frac{10(10^n-1)}{10 - 1}-n)\\=\frac{x}{9}(\frac{10(10^n-1)-9n}{9})\\=\frac{x(10(10^n-1)-9n)}{81}
$$
And we get our magic formula!
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes
```
RḌ×
```
[Try it online!](https://tio.run/##y0rNyan8/z/o4Y6ew9P///9v8t8MAA "Jelly – Try It Online")
```
RḌ× Dyadic link; left arg = n, right arg = x
R [1..n]
Ḍ Undecimal, which is the same as 1 + 11 + ... + (n copies of 1)
× Multiply x
```
---
These are the "backports" of the same algorithm into J and APL:
# [J](http://jsoftware.com/), 9 bytes
```
*10#.1+i.
```
[Try it online!](https://tio.run/##y/qvpKegnqZga6WgrqNgoGAFxLp6Cs5BPm7/tQwNlPUMtTP1/mtycaUmZ@QrmCmkKZj8BwA "J – Try It Online")
`1+` is needed because J does not have 1-based range built-in.
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 6 bytes
```
10⊥×∘⍳
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///39DgUdfSw9Mfdcx41Lv5f9qjtgmPevsedTUfWm/8qG3io76pwUHOQDLEwzP4v5lCmoIJAA "APL (Dyalog Unicode) – Try It Online")
*-1 byte thanks to @ovs*
Uses a slightly different algorithm for golfing purposes: multiply `x` to `1..n`, and then evaluate as base 10. This version of the algorithm works in Jelly too: `R×Ḍ`. [Try it online!](https://tio.run/##y0rNyan8/z/o8PSHO3r@//9v8t8MAA)
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 24 bytes
```
t=>g=n=>n&&t*n+10*g(n-1)
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@7/E1i7dNs/WLk9NrUQrT9vQQCtdI0/XUPN/cn5ecX5Oql5OfrpGmoaZpoaRpiYXqqChpoalpuZ/AA "JavaScript (Node.js) – Try It Online")
$$ f(n,x)=\sum\_{i=1}^n 10^{n-i}\cdot i\cdot x $$
$$ f(n,x)=nx+10\cdot f(n-1,x) \\ f(0,x)=0 $$
For example, we have:
\$f(6,3)\\
=6+66+666\\
=6+(60+6)+(600+60+6)\\
=600×1+60×2+6×3\\
=((6×1)×10+6×2)×10+6×3\\
=10\cdot f(6,2)+6×3\$
[Answer]
# [Excel](https://www.microsoft.com/en-us/microsoft-365/excel), 29 bytes
```
=SUM(--REPT(A1,SEQUENCE(A2)))
```
`x` is input in `A1` and `n` is input in `A2`. The formula goes anywhere else in the same sheet.
`SEQUENCE(A2)` creates an array of all the values from 1 to `n`.
`REPT(A1,~)` creates an array of strings of `x` repeated an increasing number of times based on the array created from the previous step.
`--REPT(~)` turns those strings into numbers.
`SUM(~)` adds up those numbers.
[](https://i.stack.imgur.com/JKiyY.png)
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal) `R`, ~~3~~ 2 bytes
```
I*
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=R&code=I*&inputs=4%0A6&header=&footer=)
*Thanks to @AaronMiller for -1*
## 3 bytes, `-rs`
```
ƛ⁰ẋ
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=rs&code=%C6%9B%E2%81%B0%E1%BA%8B&inputs=2%0A6&header=&footer=)
;)
## Explained
```
ƛ⁰ẋ
ƛ # For each number n in the range [1, N]:
⁰ẋ # return x repeated n times (`-r` makes elements take arguments in reverse order)
# The `-s` flag sums the top of the stack before outputting
```
## 4 bytes, `s` flag
```
ɾ?vẋ
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=s&code=%C9%BE%3Fv%E1%BA%8B&inputs=2%0A6&header=&footer=)
## 5 bytes, flagless
```
ɾ?vẋ∑
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%C9%BE%3Fv%E1%BA%8B%E2%88%91&inputs=2%0A6&header=&footer=)
[Answer]
# [J](http://jsoftware.com/), 11 8 bytes
```
1#.".\@$
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DZX1lPRiHFT@a3KlJmfkKxgppCmom6lDOMYQzn8A "J – Try It Online")
Assuming I can take the digit as a string...
Taking `3 f '6'` as an example:
* `$` - Duplicate:
```
'666'
```
* `".\` Evaluate each prefix:
```
6 66 666
```
* `1#.` Sum
```
738
```
[Answer]
# MATLAB/Octave, ~~28~~ 26 bytes
*-2 bytes thanks to Giuseppe*
```
@(x,n)(1:n)*.1.^(1-n:0)'*x
```
[Try it online!](https://tio.run/##TYpbCoAgEEX/20gzjkn2ECyEVhJI1KdBRrh70yLoMnPhcM@@nPZaY5wgcIcgB4dMSDGDrNxQY8lC3Ix1fiw2ULzBwnq/Hie8ZAwoRQoxrS3vf2umtLY59BXle2TNu5@cKck6hd4njRhv "Octave – Try It Online")
Anonymous function.
**How it works**
First of all, sum $$x + (10x + x) + (100x + 10x + x) + ... + (10^{n-1}x + 10^{n-2}x + ... 10x + x)$$
can be transformed to:
$$ n\cdot x + 10(n-1)\cdot x + 100(n-2) \cdot x + ... +10^{n-2} \cdot 2 x + 10^{n-1} x $$
which is:
$$ x \cdot \sum\_{i=0}^{n-1}(n-i) 10^i =
x \cdot \sum\_{i=0}^{n-1}(n-i)\cdot{0.1^{-i}}$$
Having that established:
* `1:n` is vector containing elements ), but in reverse order of indexing than above
* `1-n:0` are just indexes of sum above but reversed and negates (so %2C-(n-2)%2C...%2C-1%2C0%5D))
* `.1.^(1-n:0)` is then vector containing elements  in reversed order of indexing
To get the sum straightforward we would multiply elements of vectors element by element and then sum them like so (whitespace added for readability):
```
sum( (1:n) .* (.1.^(1-n:0)) )
```
However, knowing how matrix multiplication works we can just transpose second vector and by multiplying the matrices:
```
(1:n) * (.1.^(1-n:0))'
```
we will get exactly the same result. And at the end we just multiply everything by `x`.
[Answer]
# [PowerShell Core](https://github.com/PowerShell/PowerShell), 41 bytes
```
param($x,$n)iex "$(1..$n|%{"+";"$x"*$_})"
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNydFNzi9K/a@SZlv9vyCxKDFXQ6VCRyVPMzO1QkFJRcNQT08lr0a1WklbyVpJpUJJSyW@VlPpfy0Xl5pKmoKZgtF/AA "PowerShell Core – Try It Online")
## Explanations
```
iex "$(...)" # Run as a command the result of the list below, joined using spaces
1..$n|%{"+";"$x"*$_} # From 1 to n, build a list containing +,x,+,xx,+,xxx,+,xxxx,...
```
[Answer]
# [R](https://www.r-project.org/), ~~34~~ 32 bytes
```
function(d,n)sum(10^(1:n)-1)*d/9
```
[Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP08jRSdPs7g0V8PQIE7D0CpPU9dQUytF3/J/WGpySX5RZlWqRpqmhpmOoZWp5n8A "R – Try It Online")
$$
x + (10x + x) + (100x + 10x + x) + \ldots = \\
x + 11x + 111x + \ldots = \\
(9x + 99x + 999x + \ldots)/9 = \\
(9+99+999+\ldots)\*x/9 = \\
((10-1)+(100-1)+(1000-1)+\ldots)\*x/9 = \\
\big[\sum\_{i=1}^n(10^i-1)\big]\*x/9
$$
*-2 bytes thanks to [@Giuseppe](https://codegolf.stackexchange.com/users/67312/giuseppe)*
---
Using [@Wasif's formula](https://codegolf.stackexchange.com/a/225780/55372):
### [R](https://www.r-project.org/), 34 bytes
```
function(d,n)d*(10*(10^n-1)/9-n)/9
```
[Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP08jRSdPM0VLw9AAhOPydA019S1184DE/zQNMx0jzf8A "R – Try It Online")
---
Straightforward approach with strings:
### [R](https://www.r-project.org/), ~~43~~ 39 bytes
```
function(d,n)sum(strtoi(strrep(d,1:n)))
```
[Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP08jRSdPs7g0V6O4pKgkPxNEFaUWAEUNrfI0NTX/h6Uml@QXZValaqRpapgBRU01/wMA "R – Try It Online")
*-4 bytes thanks to [@Giuseppe](https://codegolf.stackexchange.com/users/67312/giuseppe)*
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes
```
ẋḌƤS
```
[Try it online!](https://tio.run/##y0rNyan8///hru6HO3qOLQn@//@/2X8TAA "Jelly – Try It Online")
## Explanation
```
ẋ repeat `x` `n` times
Ƥ for each prefix
Ḍ convert it from digits to a decimal number
S and sum
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 3 bytes
```
*dḣ
```
[Try it online!](https://tio.run/##yygtzv7/Xyvl4Y7F////N/pvBgA "Husk – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), [Python 2](https://docs.python.org/2/), 28 bytes
```
lambda x,n:(10**n/.9-n)//9*x
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaFCJ89Kw9BASytPX89SN09TX99Sq@J/QVFmXolGmoaZjpGmjoKZgraCmZkmF0LUGC4KJlDkTNDkIKSZ5n8A "Python 3 – Try It Online")
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUaFCJ89Kw9BASytPX89SN09TX99Sq@J/QVFmXolGmoaZjpGmjoKZgraCmZkmF0LUGC4KJlDkTNDkIKSZ5n8A "Python 2 – Try It Online")
Unfortunately I cannot add comments so I'm reposting [Wasif's solution](https://codegolf.stackexchange.com/a/225780) with a small tweak so that it works in both python versions. While at it, also correct the math.
$$
S\_n=x+(10x+x)+(100x+10x+x)+...+y\\= x+(11x)+(111x)+...+y\\=\frac{x}{9}(9+99+999+...+\frac{9y}{x})\\=\frac{x}{9}((10-1)+(100-1)+(1000-1)+...+(\frac{9y}{x}+1-1))\\=\frac{x}{9}((10+100+1000+...+(\frac{9y}{x}+1))-(1+1+1+...+1))\\=\frac{x}{9}((10^1+10^2+10^3+...+10^n)-n)\\=\frac{x}{9}(\frac{10^{n+1}-10}{9}-n)\\=\frac{x}{9}(\frac{10(10^n-1)-9n}{9})\\=\frac{x(10(10^n-1)-9n)}{81}
$$
[Answer]
# [R](https://www.r-project.org/), 31 bytes
```
function(d,n)10^(1:n-1)%*%n:1*d
```
[Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP08jRSdP09AgTsPQKk/XUFNVSzXPylAr5X9YanJJflFmVapGmqaGmY6hlanmfwA "R – Try It Online")
Ports [elementiro's answer](https://codegolf.stackexchange.com/a/225816/67312).
[Answer]
# [Raku](https://github.com/nxadm/rakudo-pkg), 28 [17 bytes](https://tio.run/##K0gtyjH7n1upoJamYKvwX0tBS8NQIaIiTkvbUFOvuDT3vzVXcWKlQpqGmY6R5n8A "Perl 6 – Try It Online")
```
* *(1 Xx^*+1).sum
```
Golfed by [Jo King](https://codegolf.stackexchange.com/users/76162/jo-king) from 28 byte solution:
* Positional arguments `$^a`, `$^b` replaced by whatever-stars
* `Xx` cross metaoperator responsible for generating `1, 11, 111...`
---
### Original, [28 bytes](https://tio.run/##K0gtyjH7/786WjtWQUMlLulRwzJDzSgtIDNRR0tBy9AAKKClWathpmOkqVecWPn/PwA "Perl 6 – Try It Online")
```
{$^a*(^$^b+1).map(1 x*).sum}
```
**Explanation**
* `$^a` is `x`, `$^b` is `n`
* `^$^b+1` is shorthand for `0..^$^b+1`, equivalent to `1..$^b`
* `.map(1 x*)` generates `1, 11, 111...`
* `.sum` adds the `n`-long sequence: 1 for `n=1`, 12, 123, etc.
---
### Alternative, [32 bytes](https://tio.run/##K0gtyjH7/79aJS5RSyNOJS5J21BTLzexQMNQoUJLU6@4NLdWw9BUxwjITKz8/x8A "Perl 6 – Try It Online")
```
{[+] ($^b…1)Z*($^a,* *10…*)}
```
**Explanation**
* `Z*` zip-multiplies two lists, based on the observation that
+ `1E0` appears `n` times
+ `1E1` appears `n-1` times
+ `1E2` appears `n-2` times, etc.
[Answer]
# [Python 3](https://docs.python.org/3/), 43 bytes
```
lambda x,n:sum(int(x*-~i)for i in range(n))
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaFCJ8@quDRXIzOvRKNCS7cuUzMtv0ghUyEzT6EoMS89VSNPU/N/QRFIOk1D3UxdR8EEKAAA "Python 3 – Try It Online")
Accepts `x` as a string and `n` as an integer. If that's not acceptable, just use `lambda x,n:sum(int(`x`*-~i)for i in range(n))` in Python 2 for +2 (+5 with `str(x)` in Python 3).
[Answer]
# [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 26 bytes
```
{for(;$2--;b+=a)a=a$1}$0=b
```
[Try it online!](https://tio.run/##SyzP/v@/Oi2/SMNaxUhX1zpJ2zZRM9E2UcWwVsXANun/fzMFYwA "AWK – Try It Online")
I had an alternate algorithm I thought might be interesting, but it the code was longer... So this is pretty much a direct translation of the steps in the challenge description.
```
{for(;$2--; ) }
```
Fir every line of input, the code runs the loop the number of times given by the second input parameter, the `n` value.
```
a=a$1
```
The body of the loop appends another copy of the first input parameter to the requested digit, meaning the `x` value.
```
b+=a
```
At the end of each iteration, the accumulator variable `b` is incremented by the current value of the digits placeholder.
```
$0=b
```
Finally, once the processing is done, `$0=b` overwrites the input line to display the accumulator value.
The only "trick" here is relying on the way AWK will happily treat variables as both strings and integers. Meaning, you can append digits together and still do mathematical operations using the results.
[Answer]
# [Perl 5](https://www.perl.org/) `-pal`, 22 bytes
```
map$\+="@F"x$_,1..<>}{
```
[Try it online!](https://tio.run/##K0gtyjH9/z83sUAlRttWycFNqUIlXsdQT8/Grrb6/38zLuN/@QUlmfl5xf91CxIB "Perl 5 – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 24 bytes
```
n#x=x*div(10*10^n-9*n)81
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P0@5wrZCKyWzTMPQQMvQIC5P11IrT9PC8H9uYmaebUFRZl6JipGy2X8A "Haskell – Try It Online")
Uses [Wasif's formula](https://codegolf.stackexchange.com/a/225780/82619).
## [Haskell](https://www.haskell.org/), also 24 bytes
```
0#x=0
n#x=n*x+10*(n-1)#x
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/30C5wtaAKw9I5mlVaBsaaGnk6RpqKlf8z03MzLMtKMrMK1ExUjb7DwA "Haskell – Try It Online")
A port of [tsh's excellent recursive formula](https://codegolf.stackexchange.com/a/225781/82619).
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-x`](https://codegolf.meta.stackexchange.com/a/14339/), 3 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Takes input in reverse order.
```
õçV
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LXg&code=9edW&input=NAo2)
```
õçV :Implicit input of integers U=n & V=x
õ :Range [1,U]
çV : For each, repeat V that many times
:Implicit output of sum of resulting array
```
[Answer]
# [Factor](https://factorcode.org/) + `math.unicode`, 44 bytes
```
[ [1,b] [ 10^ 1 - swap 9 / * ] with map Σ ]
```
[Try it online!](https://tio.run/##VY5BCsIwFET3PcWsRatVFFRwK27ciKtQIcZfDbVJTVKKlJ7G@3ilGGkR/Ks3b/gwGRdOG3887PbbFbi1WlgU3N1iw9WVes4qJZzUqovIySi6d1WlpNAXQmnIuWdppHKw9KhIifC9jpoI4RosMEXbc4L5j2d/PpmE0HoGlgzPKVgQp6BHsDUvscQYA6SoZRhRBPF@IfUN2m745qus4yKP/Qc "Factor – Try It Online")
Using the first thing that came to mind,
$$ f(x,n)=\sum\_{i=1}^n \frac{x}{9}(10^{i} - 1) $$
[Answer]
# [GolfScript](http://www.golfscript.com/golfscript/index.html), ~~20~~ 21 bytes
```
~:x;0\),(;{'1'*~x*+}%
```
[Try It Online!](https://tio.run/##S8/PSStOLsosKPn/31jB1KrC2iBGU0fDulrdUF2rrkJLu1b1/38A)
takes as input a string containing n and x, in that order
### Explanation
```
~:x;0\),(;{'1'*~x*+}%
~ // parse the input string given
:x; // bind the top value to the x variable
0\ // place a zero at the bottom of the stack
),(; // create a list of numbers [1..n]
{ // begin code block
'1'*~ // create and evaluate a string of '1's to get the numbers 1, 11, 111...
x*+ // multiply by x and add to the total (the zero we added)
}% // execute this over every value in the list
// implicitly print the stack
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~45~~ 43 bytes
Saved 2 bytes thanks to [Olivier Grégoire](https://codegolf.stackexchange.com/users/16236/olivier-gr%c3%a9goire)!!!
```
t;s;f(x,n){for(s=t=0;n--;)s+=t=t*10+x;n=s;}
```
[Try it online!](https://tio.run/##bVHtaoMwFP3vU1wEwY/IbJ0tJXN/xp5iypAYO9mWFhNYmPjqczc1ulomeHI959yPXFl8ZGwcFZW08TURQd@cOl/mKk@oiGMayAhjFW6SSFORSzqMrVDwWbXCD5zeAXwMobhUr/qlhBz6A4EdgYzAnkA60LVHTJ4NgS2qBO7ReeXh@syZ4vVfJYhgZ8rhmU1gKmOwn8Ci6YVROoHF@ZinYG9VFyJy9s47bAGmiVvo522hD0/4Zi6B6@/UtZm4FfDNgK2ouca0hNrwAWT7zU@NP48e3FkiXBgKUXRxBzCtbL6uqWRXd9FLupLFLIt/ZYny9NfWPEd@WeRt4rlDS@O7Xk3AqyF@NOjJQuDVNQFBQJJlRTzPZWmrD84w/rDmozrKMf76BQ "C (gcc) – Try It Online")
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 83 bytes
```
(a,b)=>Enumerable.Range(1,b).Sum(x=>Enumerable.Range(0,x).Sum(y=>a*Math.Pow(10,y)))
```
[Try it online!](https://tio.run/##Sy7WTS7O/O9Wmpdsk5JfmpSTqpOZV6IDYdoppCnY/tdI1EnStLVzzSvNTS1KBArrBSXmpadqGAKF9YJLczUqsEga6FRAJCtt7RK1fBNLMvQC8ss1DA10KjU1Nf9bcznn5xXnA5WHF2WWpPpk5qVqpGmY6SgYamrilDPCI2cMlPsPAA "C# (Visual C# Interactive Compiler) – Try It Online")
# 39 bytes using @Wasif's formula
```
(a,b)=>a*(10*(Math.Pow(10,b)-1)-9*b)/81
```
[Try it online!](https://tio.run/##Sy7WTS7O/O9Wmpdsk5JfmpSTqpOZV6IDYdoppCnY/tdI1EnStLVL1NIwNNDS8E0sydALyC8HcoDCuoaaupZaSZr6Fob/rbmc8/OK83NS9cKLMktSfTLzUjXSNMx0FAw1NXHKGeGRMwbK/QcA "C# (Visual C# Interactive Compiler) – Try It Online")
# 28 bytes using @tsh's formula
```
(a,b)=>b>0?a*b+10*f(a,b-1):0
```
[Try it online!](https://tio.run/##Sy7WTS7O/O9Wmpdsk5JfmpSTqpOZV6IDYdoppCnY/tdI1EnStLVLsjOwT9RK0jY00EoDCekaaloZ/Lfmcs7PK87PSdULL8osSfXJzEvVSNMw01Ew1NTEKWeER84YKPcfAA "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# [Zsh](https://www.zsh.org/), 31 bytes
```
for ((;i++<$2;t+=a))a+=$1
<<<$t
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m724qjhjwYKlpSVpuhb70_KLFDQ0rDO1tW1UjKxLtG0TNTUTtW1VDLlsbGxUSiCqoIqXRZvpKBjFQnkA)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 3 bytes
```
L×O
```
[Try it online!](https://tio.run/##yy9OTMpM/f/f5/B0////TbjMAA "05AB1E – Try It Online")
```
L -- list [1..input]
× -- string multiply with input
O -- sum
```
[Answer]
# [Red](http://www.red-lang.org), 47 bytes
```
func[x n][t: s: 0 loop n[t: t + s: s * 10 + x]]
```
[Try it online!](https://tio.run/##K0pN@R@UmhIdy5Vm9T@tNC85ukIhLza6xEqh2ErBQCEnP79AIQ/ELVHQBgkVK2gpGBoA2RWxsf@LUgtSE0sU8hTMowuKMvNKos2AbCVdOyWFNAUgE6gCAA "Red – Try It Online")
## Alternative, 55 bytes
```
func[x n][t: copy""s: 0 loop n[s: s + to 1 append t x]]
```
[Try it online!](https://tio.run/##DcoxCoAwDAXQ3VN8uoqgi0IHD@EaOohNQZA01Ah6@trtDa9wrBtHCl3yNT1y0AsJZB5H1s@522PElbNCqPlGD8uYsKuyRBjeEGph5d0gWEjLKUZzsxtWh4TGNn4 "Red – Try It Online")
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 20 bytes
```
.+(.)
*$1
L$v`.+
*
_
```
[Try it online!](https://tio.run/##K0otycxLNPyvquGe8F9PW0NPk0tLxZDLR6UsQU@bS4sr/v9/Ix1zLmMdUy4THWMuUx1DAA "Retina – Try It Online") Link includes test cases. Takes `n` as the first input. Note: Struggles for large values of `n` (`5` is just about doable). Explanation:
```
.+(.)
*$1
```
Generate `n` copies of `x`.
```
L$v`.+
*
```
Convert each suffix to unary.
```
_
```
Take the sum and convert to decimal.
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 8 bytes
```
$+YaX\,b
```
[Try it online!](https://tio.run/##K8gs@P9fRTsyMSJGJ@n///9m/40A "Pip – Try It Online")
### Explanation
```
a & b are command-line args (implicit)
aX String-multiply the digit by each number in...
\,b inclusive range from 1 through the number of terms
Y Yank (to enforce desired precedence)
$+ Fold on addition
Autoprint (implicit)
```
[Answer]
# [Java (JDK)](http://jdk.java.net/), 53 bytes
```
x->n->{int r=0,y=0;for(;n-->0;)r+=y=y*10+x;return r;}
```
[Try it online!](https://tio.run/##VVLLiqNAFN3nKw5CQDulaJ4Q2wyzGRiGmSyaWYUsaqI2pk0pVWVQgt@euT7bBjn3es59VB3qyu/cvoYfz@SWZ1LjSv9OoZPUiQtx0UkmnBd/dkm5UvjNE4HHDMiLf2lygdJcU7hnSYgbaeablol4P53B5buy2lLgp9A/@lGvlP8VXFbHPJJcZ/KAGMGztA/CPjwSoSEDl1WB68eZNH1h2wfXt@QiqILqxXMXpS8jXUgB6ddPv51OTaczbdSR0gpBvxN4YMfgMexQs5HaMiwZtlhgu53yG4YVw4b4TQebqbpm7UfCuoMe19Oipp@mkLLqoMchrKbFzSHoKCQtO@hxCGNcTrua29CdSPM66HEIY/xMPNRte92ZRa7CvHPZurXvPLNGyxr/S7KwoU/u2Z/QYqC9L3RU5tFFR@GgLr@oMlJFqkmLHZ7naWWWVpd8V/QOTGENxW@V0tHNyQrt5PSAdGwaZTAPGQThHvNdiLmaC4OhJI71g9m4IPg8yDcYx18G9jD@HI1@QWNBPauf/wE "Java (JDK) – Try It Online")
[Answer]
# [Desmos](https://desmos.com/calculator), ~~30~~ ~~26~~ 25 bytes
```
f(x,n)=x(10^n10-10-9n)/81
```
[Try It On Desmos!](https://www.desmos.com/calculator/2wxk4lkb1c)
[Try It On Desmos!(Prettified)](https://www.desmos.com/calculator/gm7samiotk)
] |
[Question]
[
Given a list of positive digits, return that list with consecutive elements grouped together. For example:
```
[1, 2, 3, 5, 6, 5, 4, 4, 1] -> [[1, 2, 3], [5, 6, 5, 4], [4], [1]]
```
Essentially, all adjacent elements whose absolute difference is 1 should be grouped together.
The input array will only ever contain positive digits (`123456789`) and it's length will always fit within your language's integer limit. You may take input in any reasonable format, including as a string or a single integer (so the example would be \$123565441\$). The input will never be empty and will always contain at least 1 element
You may output in any reasonable format that clearly shows the separate groups. There must be clear, non-digit delimiters between the groups. There doesn't have to be clear delimiters between the elements of the groups. If there are, the delimiters between groups and the elements of groups should be distinct (basically, you can't just print the input saying that both are separated by `,` or whatever).
One example output is shown above. Another could be outputting each group on a separate line, as single strings of digits such as
```
123
5654
4
1
```
The input is not guaranteed to be sorted. The order of the outputs, or the elements in the outputs, does not have to match the order of the inputs, so long as the groups and elements are correct.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in bytes wins.
## Test cases
```
[1] -> [1]
[1, 2] -> [[1, 2]]
[1, 3] -> [[1], [3]]
[2, 1] -> [[2, 1]]
[2, 4, 1, 2, 7, 6, 5, 1] -> [[2], [4], [1, 2], [7, 6, 5], [1]]
[4, 1, 8, 1, 3, 5, 3, 7, 1] -> [[4], [1], [8], [1], [3], [5], [3], [7], [1]]
[1, 2, 3, 4, 5, 6, 7, 9, 8] -> [[1, 2, 3, 4, 5, 6, 7], [9, 8]]
[1, 2, 3, 5, 6, 5, 4, 4, 1] -> [[1, 2, 3], [5, 6, 5, 4], [4], [1]]
[6, 1, 4, 4, 1, 2, 1, 4, 3, 2, 9, 2, 7, 5, 7, 3, 1, 7, 6, 5] -> [[6], [1], [4], [4], [1, 2, 1], [4, 3, 2], [9], [2], [7], [5], [7], [3], [1], [7, 6, 5]]
[6, 1, 4, 4, 1, 2, 3, 4, 3, 2, 9, 2, 7, 5, 7, 3, 1, 7, 6, 5] -> [[6], [1], [4], [4], [1, 2, 3, 4, 3, 2], [9], [2], [7], [5], [7], [3], [1], [7, 6, 5]]
```
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 13 bytes
```
⊢⊂⍨1,1≠∘|2-/⊢
```
```
⊢⊂⍨1,1≠∘|2-/⊢
2-/⊢ pairwise differences
1≠∘| 1 not equal to absolute value
⊢⊂⍨1, prepend 1 and partition
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn//1HXokddTY96VxjqGD7qXPCoY0aNka4@UPR/2qO2CY96@x51NT/qXfOod8uh9caP2iY@6psaHOQMJEM8PIP/pykYKhgpGCuYKpgBsQkQGgIA "APL (Dyalog Extended) – Try It Online")
[Answer]
# [convey](http://xn--wxa.land/convey/), 36 bytes
Outputs the groups separated by newlines.
```
{"">>v>v}
1~?`]>^,`
>-|=.!`
_1 _
```
[Try it online!](https://xn--wxa.land/convey/run.html#eyJjIjoie1wiXCI+PnY+dn1cbjF+P2BdPl4sYFxuID4tfD0uIWBcbiAgIF8xIF8iLCJ2IjoxLCJpIjoiMSAyIDMgNSA2IDUgNCA0IDEifQ==)
Copies `"` each element, delays it by one step `1~`, so it matches up at `-` with the next element. The first element gets discarded with `?`]`. Take the absolute value of the difference `|_`, is it different from 1 `1=.`? Then take either 0 or 1 `_` values, which will be interpreted as newline by the output.
Meanwhile the original outputs trots along the upper line, so its output is aligned with the newlines.
[](https://i.stack.imgur.com/nku2R.gif)
[Answer]
# [J](http://jsoftware.com/), 17 bytes
```
<;.1~1,1~:&|2-/\]
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/baz1DOsMdQzrrNRqjHT1Y2L/a3KlJmfkK6QpGOkomOgoGOqAGOY6CmY6CqZALkwWImUBJo3BUsZgZXAFEI3GYENMwdqBspZALXDzkdQqGMGZqNZjccF/AA "J – Try It Online")
Thanks to rak for pointing out that repeated elements should start a new group
* `2-/\]` Take successive deltas
* `1~:&|` Is the absolute value not equal to 1?
* `1,` Append one (since first element always starts a new group)
* `<;.1~` Group by that mask (ie, start new group every time there's a one)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes
```
I²’k
```
[Try it online!](https://tio.run/##y0rNyan8/9/z0KZHDTOz/x9uPzrp4c4ZKo@a1kT@/x9tGKujEG2oo2AEpY1BtJGOgiGUNgEygbI6CuY6CmY6CqZQGYiwBZg0Bgsbg5XAjQMLmIBlzMAylkDlKJKmMANNILaAJM3ABpogWQvhGoPZljCHmIJJY7As1F3YdRsTqxsA "Jelly – Try It Online")
~~Possibly~~ caird's solution:
# [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes
```
IACk
```
[Try it online!](https://tio.run/##y0rNyan8/9/T0Tn7/@H2o5Me7pyh8qhpTeT//9GGsToK0YY6CkZQ2hhEG@koGEJpEyATKKujYK6jYKajYAqVgQhbgEljsLAxWAncOLCACVjGDCxjCVSOImkKM9AEYgtI0gxsoAmStRCuMZhtCXOIKZg0BstC3YVdtzGxugE "Jelly – Try It Online")
```
k Split the input after
I the deltas of the input
…… equal to ±1:
² square each
’ and decrement each
A take the absolute value of each
C and subtract from 1
```
[Answer]
# [R](https://www.r-project.org/), 38 bytes
```
split(a<-scan(),diffinv(diff(a)^2!=1))
```
[Try it online!](https://tio.run/##K/r/v7ggJ7NEI9FGtzg5MU9DUyclMy0tM69MA0RrJGrGGSnaGmpq/jdUMFIwVjBVMANiEyA0/A8A "R – Try It Online")
[Answer]
# [Factor](https://factorcode.org/), ~~33~~ 32 bytes
```
[ [ - sq 1 = ] monotonic-split ]
```
[Try it online!](https://tio.run/##fVDBCoJAFLz7FfMDCrmuZtE5unSJTuLBZCtJV3O3Q4jfvj23Eoto4bHDzLwZeMcs13Vr9rvNdr3ARbRSlKgyfYYS15uQuVBoWqH1vWkLqaGastC6kCevqmWta1nkWDqdA3odZuhH5E8wG7E/8fgIrC9CCD7hB3ZutzhN9JXKSOe0ESEm16fCbVJgE95KSDh4NQ2I0R/bVk7DiHv2//Kzv/7eJEjgIjsoYldIMd7EtXdCaqqsgWce "Factor – Try It Online")
*Saved a byte by peeking at @xnor's [Haskell answer](https://codegolf.stackexchange.com/a/223801/97916)! Take the square instead of the absolute value.*
## Explanation:
It's a quotation (anonymous function) that takes a sequence from the data stack as input and leaves a sequence (of sequences) on the data stack as output. Assuming `{ 1 2 4 }` is on the data stack when this quotation is called...
* `[ - sq 1 = ]` Push a quotation for `monotonic-split` to use later. It's a function that tests whether two numbers have an absolute difference of 1.
**Stack:** `{ 1 2 4 } [ - sq 1 = ]`
* `monotonic-split` Take a sequence and a quotation and apply the quotation to each pair of adjacent members of the sequence, splitting the sequence when the result is `f` but grouping elements together when the result is `t`. Inside the quotation during the first iteration now...
**Stack:** `1 2`
* `-` Subtract.
**Stack:** `-1`
* `sq` Raise to the power of 2.
**Stack:** `1`
* `1` Push `1`.
**Stack:** `1 1`
* `=` Test whether two objects are equal.
**Stack:** `t`, thus 1 and 2 belong to the same group.
Now the next iteration begins, `2` and `4` produce `f`, so `4` is in a different group from `1` and `2`.
[Answer]
# [Haskell](https://www.haskell.org/), 74 bytes
```
p%(a:b:t)|abs(a-b)/=1=(p++[a]):[]%(b:t)|x<-p++[a]=x%(b:t)
p%t=[p++t]
([]%)
```
[Try it online!](https://tio.run/##jZBLDoIwEIb3nGI2JG0sGiygEHsET9B0UYwoEU1ju2Dh2a11ikYTF27m8X/zyhy1Pe2HwXuTEt20jaM33Vqis5YuRC6Imc2kVrSRKiVIx00WNTFGJTGpEzJoTiWdIKGQere3zoIAKXPFQOYMlpPnT79kkE@@CGGgDFYMKgblRKK8RstR5ljyHodCgaRCUofyL1i@BhZxyxNWOLD4WBtTjnH9OqREy5FOd/3u5v92q@Ss@0v4yFmbLRBz7S9u3lHAR/n7rhv0wfpsZ8wD "Haskell – Try It Online")
I don't like the repetition here, but I can't see a way to get around it.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 54 bytes
```
\B
¶
.
$&$&
%T`d`_d`^.
(?<=(.)(.))¶(\2|.(?=\1))
%`^.
```
[Try it online!](https://tio.run/##K0otycxL/P8/xonr0DYuPS4VNRU1LtWQhJSE@JSEOD0uDXsbWw09TSDSPLRNI8aoRk/D3jbGUFOTi0sVJP//v6GRsamZqYmJIQA "Retina 0.8.2 – Try It Online") No test suite because the multiline output makes it confusing. Explanation:
```
\B
¶
```
Split the string into individual digits.
```
.
$&$&
%T`d`_d`^.
```
Duplicate each digit and decrement the first digit of each pair.
```
(?<=(.)(.))¶(\2|.(?=\1))
```
Merge together consecutive digits, removing the decremented duplicate of the second digit.
```
%`^.
```
Remove the remaining decremented duplicates.
[Answer]
# [Branch](https://github.com/hyper-neutrino/branch-lang/), 28 bytes
```
/,^\b[N^-b;c;^*{[10.0]\n.b,]
```
Try it on the [online Branch interpreter](https://branch.hyper-neutrino.xyz/#WyIvLF5cXGJbTl4tYjtjO14qe1sxMC4wXVxcbi5iLF0iLCI2MTQ0MTIzNDMyOTI3NTczMTc2NSIsIiJd)!
Takes input as a string of digits. Outputs with groups newline-separated and elements of a group joined in one string on each line. There is a leading newline; hopefully that's acceptable.
## Explanation
```
/, Go to the left child and read a character (stores codepoint)
^\ Go to the right child (just creates this node for operating on)
b Go to register B; this is the left child since it was created second
[ ] While [the left child] is true
N Save the most recently inputted byte as register N
^- Go to the root and perform (left child) - (right child); the right child saves the previous input; initially codepoint 0
b;c; Go to register B (left child) and copy parent; go to C (right child) and copy parent
^* Go to parent and perform (left child) * (right child) (this could've been done with b;c2^' as well to square with conventional exponentiation)
{ Decrement; this is now 0 if the absolute difference was 1 and non-zero otherwise
[ 0] While statement; zeroes the value at the end so this is transformed into an if statement
10. Set value 10 and output as character (outputs a newline if the difference isn't 1 / -1)
\n Go to the right child and save N
b, Go to the left child and read a new character, setting the state for the next iteration of the while loop
```
Reading from STDIN when nothing is left gives 0, so this terminates once input ends.
[Answer]
# [Haskell](https://www.haskell.org/), 59 bytes
```
f[]=[]
f(x:y)|(a:b):t<-f y,(x-a)^2==1=(x:a:b):t|0<1=[x]:f y
```
[Try it online!](https://tio.run/##rVDLboMwELznK/ZQKbZk2oIhDxrnXql/YLmSK6BFTQAlHEDKv1N7XTuk6qVSL@vZ9czs40OfP8vDYZoqqYRUi4oM@UgvROdvNO93UQUjI0Ok6WsiRCzMr/u5PO5iIQeVG8J01HUjinYBQGrWUqM66o4Up7aDhN6fO92QB7GMlnR3t38v@5e6KQ33UPYwiFOpC6jzXD43vXoaXd6aHAvK8LpT3fSkMlwxsoGN1NRsx0nGCqI9SPOqhYwZJD630JV4oDCQ3BYTBl6H0JVSA42KwZrBikE2I1llagPamvebgiUrd9oNRo5ajj7ewYlt2ATEbcgCWgczNwXHiTJsZJy2xn62249/q0XGXJ75PVK33K0cuwfGdUNrscJF0tlNXMoRb/2VMowcf/1FXI9V2DK9uZ2dwubOCqe2IQkHyALiwcJb/zoY/6/BrkZ/HesL "Haskell – Try It Online")
The relevant function is `f`, which takes a list as input and returns a list of lists as output.
---
Unfortunately the builtin
```
groupBy(\x y->(x-y)^2==1)
import Data.List
```
doesn't work, since Haskell's `groupBy` always compares new elements to the first element of the group.
[Answer]
# [Vim](https://www.vim.org), ~~43~~ 38 bytes
*-5 bytes thanks to @DLosc by using clever hyphen evaluating shenanigans.*
```
qqy3ll:if abs(<C-r>0)!=1
norm r|
en
l@qq@q
```
[Try it online!](https://tio.run/##K/v/v7Cw0jgnxyozTSExqVhDyEBT0daQKy@/KFehqIYrNY8rx6Gw0KHw/39DXSNdY11TXTMgNgFCQwA "V (vim) – Try It Online")
Takes input as a hyphen-separated list of numbers.
Explanation:
```
qq # Start recording macro 'q'
y3l # Yank this character and the next two; this will be 'X-X'
l # Move right one character
:if # If...
abs( ) # The absolute value of...
<C-r>0 # The previously yanked text, evaluated...
!=1 # Does not equal 1:
norm r| # Replace the current character with '|'
en # End if
l # Move right one character
@q # Call macro 'q' recursively
q # End macro
@q # Call macro 'q'
```
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), 51 bytes
This beats some of the mainstream language answers!
(byte count excludes 4 unnecessary newlines added for clarity.)
```
,[[<->>+<-]<
-[>]>[>+<<]<+
+[>]>[>+<<]<-
>>>-[.-]
<.>,]
```
[Try it online!](https://tio.run/##SypKzMxLK03O/v9fJzraRtfOTttGN9aGSzfaLtYuGsixibXR5tJG4uly2dnZ6Ubr6cZy2ejZ6cT@/29oZGxqZmpiYggA "brainfuck – Try It Online")
Outputs each group of characters preceded by an ASCII 1 for example as below
```
123565441
```
The digits are interpreted as ASCII characters and the initial ASCII 1 separator appears because the ASCII codes 48-57 of the digits are not consecutive to the zeroes which fill the Brainfuck memory at the start. Removing the initial separator would take another few bytes of code (I think it's no more of an issue than a trailing newline separator. Others may disagree.)
**Commented code**
```
,[[<->>+<-]< Take input in cell 0 and copy it to the cell 1 while subtracting from cell minus 1
-[>]>[>+<<]<+ Subtract 1 from cell minus 1 and if it is not now zero add 1 to cell 2 (relies on the fact that cell 0 is zero and cell 1 is positive)
+[>]>[>+<<]<- Add 1 to cell minus 1 and if it is not now zero add 1 to cell 2
>>>-[.-] Subtract 1 from cell 2 and if not now zero both tests above failed so output ascii 1 and then zero the cell
<.>,] Output the input character now in cell 1 and loop again until a zero byte terminator is encountered
Second input character will go into cell 2 and will be copied into cell 3 and compared with the previous character in cell 1 and so on advancing 2 cells each time
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 5 bytes
```
ġo=1≠
```
[Try it online!](https://tio.run/##yygtzv7//8jCfFvDR50L/v//H22oY6RjrGOqYwbEJkBoGAsA "Husk – Try It Online")
group on absolute difference = 1.
[Answer]
# JavaScript (ES7), 43 bytes
*Saved 4 bytes thanks to @tsh*
Expects an array of digit characters. Returns a string with the groups separated with commas.
```
a=>a.map(p=v=>(p-(p=v))**2-1?[,v]:v).join``
```
[Try it online!](https://tio.run/##nZFda4MwFIbv9ytCr7TElHNOPnRg90NCoNK1o6VTWYd/35nIMkajsHlxPArP45vXazM09@PHpf8s2u71NJ7rsan3jXhv@qyvh3qf9YVf8ny7xQJeLB/c85CLa3dpD4fx2LX37nYSt@4tO2dWCLGBjctzlrh2O2bBPaUQXGA8YoEzdGmOVjnHmaU0ibBGImewwElAo9UjPXP@i9KPkHm6G840Zyq8ShsllECKzIMyGGeZH2XcyA8VN7MiBySptKnKpNyH5Iw4k1PEEDS4Ks7KRZ3SSkpY04V087En808jaaWGSYcgCSs0yhBM7QZ7UOp4aPmrWv9//HNIH4qu/MDYh4obRcX3v1jJQX/OMbf3nxTjFw "JavaScript (Node.js) – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 6 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Outputs a 2D array.
```
òÈaY É
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=8shhWSDJ&input=WzEsMiwzLDUsNiw1LDQsNCwxXQotUQ)
```
òÈaY É :Implicit input of array
ò :Partition between pairs that return falsey (0)
È :When passed through this function as X & Y
aY : Absolute difference
É : Minus 1
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 23 bytes
```
Split[#,!-1!=#2-#!=1&]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7P7ggJ7MkWllHUddQ0VbZSFdZ0dZQLVbtf0BRZh5QXNcuzUE5Vq0uODkxr66aq9qwVgdI6CgYQWljEG2ko2AIpU2ATKCsjoK5joKZjoIpVAYibAEmjcHCxmAlcOPAAiZgGTOwjCVQOYqkKcxAE4gtIEkzsIEmSNZCuMZgtiXMIaZg0hgsC3UXdt3GxOrmqv0PAA "Wolfram Language (Mathematica) – Try It Online")
`Split` can take a second argument, which is applied to adjacent pairs to see if they should be in the same group.
`!-1!=#2-#!=1` has the same length as `Abs[#2-#]==1`, and asserts that `-1`, `#2-#`, and `1` are not all unequal - that is, `-1==1 || -1==#2-# || #2-#==1`.
[Answer]
# [K (oK)](https://github.com/JohnEarnest/ok), ~~24~~ 21 bytes
-3 bytes thanks to streetster!
```
{(?0,&~1=d*d:-':x)_x}
```
[Try it online!](https://tio.run/##dY07DoQwDESv4mr5iEgYJywkQhyFBtFQbIuE4OphHLQFBYXt8dOMvZrfGuPi93ysq8/Jw1zO3mR@K6btiEuWVxyIqdEmgRpibVYRfaklp0DXTg1YBfiOQFqAFqCn7o9cClnNBEi@pR7GFMw@XXYoAUs/nkZ5NxbxAg "K (oK) – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 48 bytes
```
->l{y=0;l.chunk{|x|$.+=(y-y=x)**2-1}.map &:last}
```
[Try it online!](https://tio.run/##jZDRCoIwFIbve4pzEVE2Jd20LNaLDC9WIEIWUgkOt2df86goQdDN2X/2nfPvZ8/6omzOrX8uW8V3pzK4FvXj1upGL4MtXytf8WbjeZEfmuAuK1gdS/l6GysARJiRBXQngWiSdJARgXCSzHVujMCeQEIgnmBPDlgpEopTc3e8YwgThKnb@Obx6Mz65waeoDObRehbijodQ8VYKdIh408D@q9B1v1Zq6WuIBcyM/YD "Ruby – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 52 bytes
```
p=0
for n in input():print"X"*p*(abs(n-p)!=1),n,;p=n
```
The program separates the input with the character `"X"`.
[Try it online!](https://tio.run/##K6gsycjPM/r/v8DWgCstv0ghTyEThApKSzQ0rQqKMvNKlCKUtAq0NBKTijXydAs0FW0NNXXydKwLbPP@/4821lEw0lEAkiY6CqYwNpA0hIjEAgA "Python 2 – Try It Online")
# 55 bytes
```
lambda n:reduce(lambda a,b:a+[abs(a[-1]-b)==1,b],n,[0])
```
Alternate **55 byte** solution that uses reduce.
[Try it online!](https://tio.run/##LcdLCoAgEADQq8xSaYS0z0LwJOZippKCsuiz6PQG0ebB259r2pLJ0XV5oZUHgmSPcbj7UfwnZEuFJz4FeaWDYumcRg6Y0JdB5v2Y0yWi8BrBIFQI9WeL0AQp8ws "Python 2 – Try It Online")
[Answer]
# [PHP](https://php.net/) -F, 59 bytes
```
for(;$n=$argn[$i++];$m=$n)$a.=abs($n-$m)-1?",$n":$n;echo$a;
```
[Try it online!](https://tio.run/##DcRLCoAgFAXQvcgdJGVg9IFMmrWJaGDRx4FPydafdQYnXCENY/g//J0pkIa5T5ph83xRcBrEYUpt1piBBBwXcmQFiPUgtW@Xh1EpVbWsuraRrw@P9RSTmD4 "PHP – Try It Online")
Takes a string of digits, outputs a string with delimiter ",". Has a preceding delimiter except when first digit is 1.
Well, at least it beats the Scratch answer :P
[Answer]
# [Racket](https://racket-lang.org/), 241 bytes
```
(λ(s)(letrec([d(λ(t n c)(if(null?(cdr t))(reverse c)(if(=(sqr(-(car t)(cadr t)))1)(d(cdr t)(+ 1 n)c)(d(cdr t)1(cons n c)))))][g(λ(t c a)(if(null? c)(cons t a)(g(drop t(car c))(cdr c)(cons(take t(car c))a))))])(reverse(g s(d s 1'())'()))))
```
[Try it online!](https://tio.run/##fU5LTsMwFNz3FE9i0bEQCzcf2gXiIBULy3aiqpELttvLcQeuFN5zoyQghCXL82bmzTgae/Z5fBhM6CmWYQPnu1Pw1I34@kRSGHyO3uLoZM4UyCqcOoTrMLzCukhZKUR/8zH5SXtB@oh4gjWi8nN3Ka3gphU8kqag7MJo2EtIJV/O27G/F1oyS6EUFFsWtoeLl3fKpYjXStLkQDZnv0imZM4fRU8JjhLpLZSSy2dUG3S0hVYT4C/uVria8Y70Ctfio2dqqVnxwu5li9mK1R@pzNTMt8wfaP9LaUpSLQmz0rJWT02CKn4PpbXhWzFX@v/0V//5x28 "Racket – Try It Online")
What a monstrosity! I won't be surprised if it can be done in under 100 bytes.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~56~~ 54 bytes
```
f(char*n){for(;*n;~-abs(putchar(*n)-*++n)&&puts(""));}
```
[Try it online!](https://tio.run/##nZDPboMwDMbvPIWFtCqhQZXzh4CQ9iKIA2Oj62G0AtZL1b06S8IWmva0cTCOv/z8xW7TfdvOc0fa92ZIenrpjgMpk778SpuXkZw@JysQo6TJdtvTzcaURhLHlJbX@Xw8vML0Nk4L3tBLBOY7DYd@6kj8NEL6DDFraNkRE6JrZAT4aA49sUkz7FsGDk3s4fzDu44xxrQE2O2gwvq2zG3dlitkwOtAE6tWM6hEoHL0KmeAoSaR60zd3LC8tMG5mL9mkDFQrhSwEnMUSugVXjgbcp8JG5TP9GMf5EKqTBd5MCADwUAaY2fvsIJBfk@qTEmJ96TzXN5tmqwjBXSGhuQoBS@4VlqgWYRvlPkBZLARu0B7ds9z@yls4H425TPhW/yu8NFd/NV9Wcq/vK/zNw "C (gcc) – Try It Online")
Takes a string of digits as input; prints output to STDOUT with each group on a separate line.
*-2 thanks to @ceilingcat*
[Answer]
# [Julia](http://julialang.org/), ~~47~~ 46 bytes
```
f(s,p='a')=join(s.|>i->' '^((p-i)^2!=1)*(p=i))
```
[Try it online!](https://tio.run/##rVJNi4MwEL37K2ZPJiUVNGrbQ/pHxIK0dkmRVqoLXdj/7k5mTGqXvSzsZT7fe5kZcvnobJM@puksBtWbuImludzsVQzJ196u9zHEByH6tZWH7M2kciV6Y6WcxnYYBzBQRVVag9kDOgwVZJxxyCXtS7WCSrtipmBmccilHENkKdgoKBUUC5Bj5s6QLPoZQiVHZ@6WrCauJh2vwGRntiHSzhQh2gQxnkLTRAU9hEo7lF/s9qPvuIRY0gu/R87LvdLp9YB4bugkSlokX9yEU03xzl@pIKup6y/Cb5Rhy/zldm4Kl7MUTe1MFg5QhEgHCS/962D6vwZ7Cv15rDqKxhR/4/HWde1xTIT7wok42/uACf1VKWXUPnoEvbejvZ7ax9xQmW/gX09WzKzYWQnn2x0s2CsgplYIkVF0skPfNZ8eNaYIW7rEGIeW0zc "Julia 1.0 – Try It Online")
Input is a list of `Chars` and output is a string with spaces to delimit groups, example:
`f(['2','4','1','2','7','6','5','1']) = " 2 4 12 765 1"`
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 21 bytes
```
P§θ⁰FΦθκ«¿⊖↔⁻IKKι⸿→Pι
```
[Try it online!](https://tio.run/##TY6xDoIwFEVn@IqG6TXBRBQcdCIaEwcS4uyC8JAXaqvtg5gYv72Ck3c7Zzi5dVfZ2lTK@2JQTA9LmiHnk27wBc9YLKXcha2xAo6kGO3seinFOwyoFXDA2uIdNWMD@dUZNTBCQXpwsK8cQ4nYg5SxIDlNlL98dLHRVA1QORSFGRG2Z7p1PLu/FzTxx/tktc42WZomfjGqLw "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
P§θ⁰
```
Output the first character of the input without moving the cursor.
```
FΦθκ«
```
Loop over the remaining characters.
```
¿⊖↔⁻IKKι
```
If the current character is not a neighbour of the character under the cursor, then ...
```
⸿
```
... move to the start of the next line, ...
```
→
```
... otherwise move right one character.
```
Pι
```
Output the current character without moving the cursor.
[Answer]
# [><>](http://esolangs.org/wiki/Fish), 19 bytes
```
:n$:@-:1=$i=+1$-a*o
```
Looks like TIO's `-v` flag support broke, and fishlanguage.com is down, so no link.
Takes the list on the stack, from top to bottom.
[Answer]
# [Zsh](https://www.zsh.org/) `-o extendedglob`, 38 bytes
```
>-1;for a {wc<^*$[b?a-b:1];b=$a;<<<$a}
```
[Try it online!](https://tio.run/##qyrO@F@cWqKgm6@QWlGSmpeSmpKek5/EBRIzVTBTMFQwAUJDBSMFYyBtDKTNgaKm/@10Da3T8osUEhWqy5Nt4rRUopPsE3WTrAxjrZNsVRKtbWxsVBJr//8HAA "Zsh – Try It Online")
I really feel like there's some way to shave off 1 or 2 bytes from the `$[b?a-b:1]`.
* `>-1`: create the empty file `-1`
* `for a {}`: for each input element:
+ `$[]`: arithmetic expansion
- `a-b`: take the difference between this element and the previous `b`
- `b?:1`: if `b` is not defined (because we're on the first iteration), then assume the difference is 1
+ `*...`: match files that end with that difference. This is so the file `-1` will be matched by a difference of either `1` or `-1`
+ `^*...`: inverted match; matches files that *don't* end with that difference
+ `<`: and feed them as input to:
+ `wc` word count; outputs `0 0 0` (our separator) since the file is empty
+ So if the difference is `1` or `-1`, it will not match, so there will be no files as input to `wc` and it won't output the separator
+ `b=$a`: set `b` for the next iteration
+ `<<<$a`: print `a`
[Answer]
# [Scratch](https://scratch.mit.edu/), (by @att) 184 bytes
[Try it online!](https://scratch.mit.edu/projects/518043965/)
All credit goes to @att
```
define(x
set[a v]to(
set[i v]to(
repeat(length of(x
change[i v]by(1
set[t v]to(letter(i)of(x
set[a v]to(join(a)((t)*(((2)*<(-1)contains((t)-(letter(length of(a))of(a)))?>)-(1
end
say(a
```
[Answer]
# [Arn 1.0](https://github.com/ZippyMagician/Arn), [6 bytes](https://github.com/ZippyMagician/Arn/wiki/Carn)
```
PWº··,
```
# Explained
Unpacked: `::-.|=1`
```
_ Input; implied
:: Sort adjacent by
_ First value
- Minus
_ Second value
.| Absolute value
= Equals
1 One
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
üα≠0šÅ¡
```
[Try it online](https://tio.run/##yy9OTMpM/f//8J5zGx91LjA4uvBw66GF//9HG@oY6RjrmOqYAbEJEBrGAgA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXL/8N7zm181LnA4OjCw62HFv7X@R8dbRiroxBtqGMEoYxBlJGOIYQy0QFK6JjrmOmYQoRAAhZAbAwUMAZKwDQDOSZAITOgkKWOBULQFKzVBGQQSNAMqNUEaiqIZQykLcE2mAKxMVAMbBe6UmM8SmMB).
**Explanation:**
```
ü # For each overlapping pair in the (implicit) input-list:
α # Get the absolute difference
≠ # Check for each that they're NOT 1 (0 if 1; 1 otherwise)
0š # Prepend a 0 to the list
Å¡ # Split the (implicit) input-list at the truthy indices
```
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 14 bytes
```
aWV(k1N_-BMPa)
```
Takes input via command-line argument as a string of digits. Outputs with separator `,` between groups and within groups. [Try it online!](https://tio.run/##K8gs@P8/MTxMI9vQL17XyTcgUfP///@GRsamZqYmJoYA "Pip – Try It Online")
### Explanation
```
MPa Map this function to each pair of digits in the input:
1N Count the number of 1's in
_-B the first digit minus the second (1 if the difference is +/-1, 0 otherwise)
(k ) Use that list of 1's and 0's to index into the preset variable k == ", "
We now have a list of length len(a)-1 containing spaces and commas
aWV Weave the input string with that list
Autoprint (implicit)
```
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.