Surrounding Countries

27

3

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:

map

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 , 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

Addison Crump

Posted 2016-02-27T15:06:39.443

Reputation: 10 763

Does the input have the quotation marks or not? – Loovjo – 2016-02-27T16:06:59.240

What should it do on invalid input? (I hope anything, that would open some place for optimizations) – yo' – 2016-02-27T20:57:51.900

@yo' You may assume that all input is valid. – Addison Crump – 2016-02-27T21:45:31.950

2One could make many more claims to the list, e.g. technically, France touches the Netherlands on the Caribbean island of Saint Martin, Melilla and Ceuta are Spanish exclaves on the African mainland making Spain touch Morocco, the quadripoint of Namibia, Botswana, Zambia and Zimbabwe is actually two tripoints some 100 metres apart, San Marino, Monaco, Vatican are missing completely etc. However, I don't think this is relevant for the challenge -- just leave the list as it is, after all our answers are not made to produce geographically correct output but to demonstrate that our algorithms work. – Christallkeks – 2016-02-29T13:40:05.440

1You could add a warning about Mathematica builtins and why they are useful in this challenge – edc65 – 2016-03-01T14:56:43.613

I think it is a pity that this interesting challenge becomes a packing competition. I'd rather see a code-golf of just the algorithm to expand in layers of bordering countries. The program should just get the appropriate data in an appropriate format. – Adám – 2016-03-01T15:48:44.567

@Nᴮᶻ a kolmogorov-complexity challenge is mostly a packing competition in fact – edc65 – 2016-03-01T15:54:22.640

@edc65 (to ping FUI only) VoteToClose: May I post an identical code-golf challenge that does not involve a packing competition? – Adám – 2016-03-01T16:49:08.260

@Nᴮᶻ Sure, but you'd have to specify a source to make output the same for every language. I suggest sandboxing first, because I'm not sure if that's going to be as widely accepted. – Addison Crump – 2016-03-01T19:07:29.330

1@NBZ Normally I'd agree, but in fact the country graph has so much structure that it becomes a very interesting interaction between encoding and the actual code. I learned a lot about graph theory and optimization from this one and I just keep working on it. If it was just a program with plain country input I would have gotten bored long ago. In Perl the expansion is just %r=map%$_,%r. – Ton Hospel – 2016-03-02T19:02:15.977

Answers

15

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]??#${$.+=$&gt$_}{$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: ${$.+=$&gt$_}{$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)

Ton Hospel

Posted 2016-02-27T15:06:39.443

Reputation: 14 114

1Very nice packing, especially the country names. Amazing coincidence that exactly 32 characters suffice. – Christallkeks – 2016-03-03T11:18:11.840

5

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>

edc65

Posted 2016-02-27T15:06:39.443

Reputation: 31 086

At first I was thinking, "why 1/x instead of +x?" Then I realised that's a clever way to get around case 0. +1 – ETHproductions – 2016-02-27T19:11:24.890

@VoteToClose updated – edc65 – 2016-02-27T21:49:08.770

Would it be shorter to remove all the countries with no neighbors and add a fallback for inputs not in the list? It saved me over 500 bytes. – ETHproductions – 2016-02-28T02:35:30.053

@ETHproductions yes surely. I was in doubt about such a big gain just borrowing someone else's idea – edc65 – 2016-02-28T09:22:42.337

5

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]))

ETHproductions

Posted 2016-02-27T15:06:39.443

Reputation: 47 880

List has been updated after finding a fault. Please see revision history for change details. – Addison Crump – 2016-02-27T19:43:50.867

@VoteToClose Thanks, fixed. (It cost me an entire byte!) – ETHproductions – 2016-02-27T19:51:50.470

4

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. The entire program is available here. 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.

Loovjo

Posted 2016-02-27T15:06:39.443

Reputation: 7 357

Might save bytes to use a str:tuple dict. Also, I think {} makes an empty set. – CalculatorFeline – 2016-02-27T16:40:44.587

2@CatsAreFluffy {} makes an dict, unfortunately. – Loovjo – 2016-02-27T16:41:25.957

Try using {x for d in Q[A][1:] if d not in C} and C|=n instead of the for A in C: loop. – CalculatorFeline – 2016-02-27T18:08:00.420

1Nice answer! I was hoping that my list was easily parseable, and it seems that it was. \o/ +1 – Addison Crump – 2016-02-27T18:29:17.067

You should find a more compact way to store the list, that is the most of your byte count – edc65 – 2016-02-27T18:46:50.643

List has been updated after finding a fault. Please see revision history for change details. – Addison Crump – 2016-02-27T19:44:11.290

1Would it be shorter to remove all the countries with no neighbors and add a fallback for inputs not in the list? – ETHproductions – 2016-02-28T02:35:02.487

Your int(i[-1]) fails for layer > 9. Why not get both inputs in the split of the input string? – agtoever – 2016-02-29T07:48:31.993

@agtoever It doesn't fail for inputs > 9: http://ideone.com/17ThJy, the second row, i=raw_input().split(), splits the input at spaces.

– Loovjo – 2016-02-29T09:09:57.300

@Loovjo my mistake. You're right. I misread the code. – agtoever – 2016-02-29T10:10:48.223

4

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: A graph of France's 2-neighborhood

hYPotenuser

Posted 2016-02-27T15:06:39.443

Reputation: 707

That is cool. :D I wish I had this program to test my list! – Addison Crump – 2016-03-02T19:09:54.700

I can change #1 to # to save one byte... doesn't seem to be worth the time to edit :p – hYPotenuser – 2016-03-03T00:55:20.477

3

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 -nias 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, 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.

Christallkeks

Posted 2016-02-27T15:06:39.443

Reputation: 377

Would it be shorter to remove all the countries with no neighbors and add a fallback for inputs not in the list? – ETHproductions – 2016-02-28T02:34:35.000

Yep, that's one of the things I had in mind -- see my freshly edited post for that and a lot more :) – Christallkeks – 2016-02-29T00:33:19.437

3

Dyalog APL, 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¥␀|·bV­MÃ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Åe­fP
ÃÉ^.Ý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⍳⊂⍺]~⊂⍺}

Adám

Posted 2016-02-27T15:06:39.443

Reputation: 37 779