하노이의 탑

하노이의 탑

하노이의 탑(Tower of Hanoi)은 퍼즐의 일종이다. 세 개의 기둥과 이 기둥에 꽂을 수 있는 크기가 다양한 원판들이 있고, 퍼즐을 시작하기 전에는 한 기둥에 원판들이 작은 것이 위에 있도록 순서대로 쌓여 있다.

게임의 목적은 다음 세 가지 조건을 만족시키면서, 한 기둥에 꽂힌 원판들을 그 순서 그대로 다른 기둥으로 옮겨서 다시 쌓는 것이다.

  1. 한 번에 한개의 원판만 옮길 수 있다.
  2. 가장 위에 있는 원판만 이동할 수 있다.
  3. 큰 원판이 작은 원판 위에 있어서는 안 된다.
하노이의 탑의 원리(애니메이션)

하노이의 탑 문제는 재귀 호출을 이용하여 풀 수 있는 가장 유명한 예제 중의 하나이다. 그렇기 때문에 프로그래밍 수업에서 알고리즘 예제로 많이 사용한다. 일반적으로 원판이 n개 일 때, 2n -1번의 이동으로 원판을 모두 옮길 수 있다(2n − 1는 메르센 수라고 부른다).

한 번의 실수 없이 64개의 원판을 옮기는 데 264 - 1 = 18,446,744,073,709,551,615번(약 1.84 × 1019)을 움직여야 하고, 1초당 한 번 원판을 움직일 때 584,554,049,253년(1년 = 365.2425일)이 걸린다. 이는 우주의 나이인 138억 년의 42.4배이다.[1]

유래

하노이의 탑은 프랑스의 수학자인 에두아르 뤼카(Édouard Lucas)가 클라우스 교수(professeur N. Claus)라는 필명으로 1883년에 발표하였다.[2] 1년 후 드 파르빌(Henri de Parville)은 Claus가 Lucas의 애너그램임을 밝히면서 다음과 같은 이야기로 하노이의 탑을 소개하였다.

"인도 베나레스에 있는 한 사원에는 세상의 중심을 나타내는 큰 이 있고 그 안에 세 개의 다이아몬드 바늘이 동판 위에 세워져 있습니다. 바늘의 높이는 1 큐빗이고 굵기는 벌의 몸통만 합니다. 바늘 가운데 하나에는 신이 64개의 순금 원판을 끼워 놓았습니다. 가장 큰 원판이 바닥에 놓여 있고, 나머지 원판들이 점점 작아지며 꼭대기까지 쌓아 있습니다. 이것은 신성한 브라흐마의 탑입니다. 브라흐마의 지시에 따라 승려들은 모든 원판을 다른 바늘로 옮기기 위해 밤낮 없이 차례로 제단에 올라 규칙에 따라 원판을 하나씩 옮깁니다. 이 일이 끝날 때, 탑은 무너지고 세상은 종말을 맞이하게 됩니다."[3]

이후 라우즈 볼, 가드너 등이 하노이의 탑을 소개하면서 널리 알려졌다.

소스 코드

이것은 각각의 수를 구하는 컴퓨터 프로그램 등의 실행어에 대한 것이다.

let rec move_tower n a b c = match n with
	| 1 -> [(a,c)]
	| _ -> (move_tower (n-1) a c b) @ (move_tower 1 a b c) @ (move_tower (n-1) b a c);;
(defun hanoitowers (disc src aux dst)
  (cond ((> disc 0)
	 (hanoitowers (- disc 1) src dst aux)
	 (princ (list "Move" disc "from" src "to" dst))
procedure Hanoi(n: integer; from, dest, by: char);
Begin
    if (n=1) then
        writeln('Move the plate from ', from, ' to ', dest)
    else begin
        Hanoi(n-1, from, by, dest);
        Hanoi(1, from, dest, by);
        Hanoi(n-1, by, dest, from);
    end;
End;
#include <iostream>
using namespace std;

void move(int from, int to)
{
    cout << from << " -> " << to << '\n';
}

void hanoi(int n, int from, int by, int to)
{
    if(n == 0) return;
    hanoi(n - 1, from, to, by);
    move(from, to);
    hanoi(n - 1, by, from, to);
}
def hanoi(number_of_disks_to_move, from_, to_, via_):
    if number_of_disks_to_move == 1:
        print(from_, "->", to_)
    else:
        hanoi(number_of_disks_to_move-1, from_, via_, to_)
        print(from_, "->", to_)
        hanoi(number_of_disks_to_move-1, via_, to_, from_)
class hanoi
   predicates
       hanoi : (unsigned N).
end class hanoi

implement hanoi
   domains
       pole = string.

   clauses
       hanoi(N) :- move(N, "left", "centre", "right").

   class predicates
       move : (unsigned N, pole A, pole B, pole C).
   clauses
       move(0, _, _, _) :- !.
       move(N, A, B, C) :- 
           move(N-1, A, C, B),
           stdio::writef("move a disc from % pole to the % pole\n", A, C),
           move(N-1, B, A, C).
end implement hanoi

goal
   console::init(),
   hanoi::hanoi(4).
import Foundation

func hanoi(_ n: Int, from a: Int, to b: Int, by c: Int) {
    if n==1 {
        print("Move 1 from \(a) to \(b)")
    }
    else {
        hanoi(n-1, from: a, to: b, by: c)
        print("Move \(n) from\(a) to\(b)")
        hanoi(n-1, from: c, to: b, by: a)
    }
}

같이 보기

각주

  1. Moscovich, Ivan (2001). 《1000 playthinks: puzzles, paradoxes, illusions & games》. Workman. ISBN 978-0-7611-1826-8. 
  2. Hinz, Andreas M.; Klavžar, Sandi; Milutinović, Uroš; Petr, Ciril (2013년 1월 31일). 《The Tower of Hanoi – Myths and Maths》. ISBN 978-3034802369. 
  3. Spitznagel, Edward L. (1971). 《Selected topics in mathematics》. Holt, Rinehart and Winston. 137쪽. ISBN 978-0-03-084693-9. 

외부 링크

Read other articles:

Ginástica nosJogos Olímpicos de Verão da Juventude de 2010ArtísticaQualificatóriamascfemIndividual geralmascfemSaltomascfemSolomascfemCavalo com alçasmascArgolasmascBarras paralelasmascBarra fixamascBarras assimétricasfemTravefemRítmicaGroup geralfemIndividual geralfemTrampolimIndividualmascfemvde A qualificatória masculina da ginástica artística nos Jogos Olímpicos de Verão da Juventude de 2010 foi disputada no dia 16 de agosto no Bishan Sports Hall, em Singapura.[1] Os resultad...

 

This article relies largely or entirely on a single source. Relevant discussion may be found on the talk page. Please help improve this article by introducing citations to additional sources.Find sources: Nothing Less Than Brilliant – news · newspapers · books · scholar · JSTOR (December 2009) 1994 compilation album by Sandie ShawNothing Less Than BrilliantCompilation album by Sandie ShawReleased1994GenrePopLabelVirginSandie Shaw chronology Hel...

 

Finlandia en los Juegos Olímpicos Bandera de FinlandiaCódigo COI FINCON Comité Olímpico Finlandés(pág. web)Juegos Olímpicos de Nagano 1998Deportistas 85 en 10 deportesAbanderado Janne AhonenMedallasPuesto: 11 2 4 6 12 Historia olímpicaJuegos de verano 1908 • 1912 • 1920 • 1924 • 1928 • 1932 • 1936 • 1948 • 1952 • 1956 • 1960 • 1964 • 1968 •...

جامعة عبد المالك السعديⵜⴰⵙⴷⴰⵡⵉⵜ ⵏ ⵄⴰⴱⴷⵍⵎⴰⵍⴽ ⵙⵙⴰⵄⴷⵉ معلومات التأسيس 1989 النوع جامعة عمومية الموقع الجغرافي إحداثيات 35°33′40″N 5°21′52″W / 35.56100619121°N 5.3645465438349°W / 35.56100619121; -5.3645465438349  المكان تطوان البلد المغرب[1]  سميت باسم عبد الملك الأول السعدي&#...

 

Chiesa di San Francesco e convento dei CappucciniVeduta della chiesa e del conventoStato Italia RegioneToscana LocalitàSan Lorenzo (Arcidosso) Coordinate42°52′55.1″N 11°32′09.71″E / 42.881972°N 11.536031°E42.881972; 11.536031Coordinate: 42°52′55.1″N 11°32′09.71″E / 42.881972°N 11.536031°E42.881972; 11.536031 Religionecattolica TitolareSan Francesco Arcidiocesi Siena-Colle di Val d'Elsa-Montalcino Modifica dati su Wikidata · M...

 

Gebäude der Außenstelle des Franz-Mehring-Instituts und des Wilhelm-Griesinger-Krankenhauses in Berlin-Biesdorf (2008) Die Außenstelle des Franz-Mehring-Instituts in Berlin-Biesdorf war eine Bildungsinstitution der Deutschen Demokratischen Republik (DDR) in Ost-Berlin. Sie wurde 1970 vom Ministerrat der DDR eingerichtet und diente dazu, Funktionäre der westdeutschen Deutschen Kommunistischen Partei (DKP) in Marxismus-Leninismus zu schulen. Organisatorisch gehörte die Außenstelle zum Fra...

Part of MSN's web services MSN MusicMSN Music logo, circa 2008Type of siteMusic websiteAvailable inEnglishOwnerMicrosoftLaunchedFebruary 18, 2004; 19 years ago (2004-02-18) MSN Music was a part of MSN's web services. It delivered music news, music videos, spotlights on new music, artist information, and live performances of artists. The website also served as a digital music store from 2004 to 2008. History In 2004, Microsoft created an MSN Music download store to compe...

 

American magazine for teenagers For the Japanese magazine, see Seventeen (Japanese magazine). For the former British magazine, see Just Seventeen. Seventeen MagazineDemi Lovato on the cover of the August 2014 issueExecutive DirectorKristin KochCategoriesTeen magazineFrequencyBimonthlyPublisherHearst Magazines (from 2003)Total circulation(2017)2,020,492[1]First issueSeptember 1944CountryUnited StatesBased inNew York CityLanguageEnglishWebsitewww.seventeen.comISSN0037-301X Seventeen is ...

 

Запрос «Одер» перенаправляется сюда; см. также другие значения. У этого топонима есть и другие значения, см. Одра (значения).Одрачеш. Odra, польск. Odra, нем. Oder Одра у Киница Характеристика Длина 840 км Бассейн 125 000 км² Расход воды 480 м³/с Водоток Исток   (Т) (B...

Bridge in Niagara Falls, Ontario and New York Whirlpool Rapids BridgeWhirlpool Rapids Bridge (left) with out-of-service Michigan Central Railway Bridge (far right). A since-removed viaduct of the Niagara Scenic Parkway is also visible in the distance.Coordinates43°06′33″N 79°03′30″W / 43.109208°N 79.058336°W / 43.109208; -79.058336Carries2 auto lanes (lower)1 rail line (upper)CrossesNiagara RiverLocaleNiagara Falls, Ontario, and Niagara Falls, New YorkNamed...

 

American college football season 2020 Central Michigan Chippewas footballConferenceMid-American ConferenceDivisionWest DivisionRecord3–3 (3–3 MAC)Head coachJim McElwain (2nd season)Offensive coordinatorCharlie Frye (2nd season)Defensive coordinatorRobb Akey (2nd season)Home stadiumKelly/Shorts Stadium(capacity: 32,885)UniformSeasons← 20192021 → 2020 Mid-American Conference football standings vte Conf Overall Team   W   L     W ...

 

Subgenre of hip hop This article needs additional citations for verification. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sources: Industrial hip hop – news · newspapers · books · scholar · JSTOR (July 2008) (Learn how and when to remove this template message) This article needs to be updated. Please help update this article to reflect recent events or newly available i...

This article uses bare URLs, which are uninformative and vulnerable to link rot. Please consider converting them to full citations to ensure the article remains verifiable and maintains a consistent citation style. Several templates and tools are available to assist in formatting, such as reFill (documentation) and Citation bot (documentation). (September 2022) (Learn how and when to remove this template message) Illumination of a Christmas tree in the city of Nazareth Christmas celebrations ...

 

Indian stand-up comedy and talk show This article has multiple issues. Please help improve it or discuss these issues on the talk page. (Learn how and when to remove these template messages) This article may be written from a fan's point of view, rather than a neutral point of view. Please clean it up to conform to a higher standard of quality, and to make it neutral in tone. (September 2022) (Learn how and when to remove this template message) This article needs additional citations for veri...

 

Тропарь шестого гласа, поемый на Воздвижение Креста Господня: «Кресту́ Твоему́ покланя́емся Влады́ко, и свято́е Воскресе́ние Твое́ сла́вим.» «Кондакарь крюковый», исход ХІІ века Тропа́рь (греч. τροπάριον) в православной церкви — одно из кратких молитвенных песнопени...

American philosopher (1863–1931) Sidney Edward Mezes5th President of the University of Texas at AustinIn office1908–1914Preceded byDavid Franklin HoustonSucceeded byWilliam James Battle4th President of City College of New YorkIn office1914–1927Preceded byJohn Huston FinleySucceeded byFrederick Bertrand Robinson Personal detailsBorn(1863-10-19)October 19, 1863Belmont, CaliforniaDiedSeptember 10, 1931(1931-09-10) (aged 67)Pasadena, CaliforniaEducationUniversity of California,...

 

1981 song by Elvis Costello Watch Your StepSingle by Elvis Costello and the Attractionsfrom the album Trust B-sideLuxembourgReleasedApril 1981RecordedOctober–November 1980GenreNew waveLabelColumbia (US)Songwriter(s)Elvis CostelloProducer(s) Nick Lowe Roger Béchirian Elvis Costello and the Attractions singles chronology From a Whisper to a Scream (1981) Watch Your Step (1981) A Good Year for the Roses (1981) Watch Your Step is a song written by new wave musician Elvis Costello and performed...

 

This article needs additional citations for verification. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sources: The Dangling Man – news · newspapers · books · scholar · JSTOR (May 2016) (Learn how and when to remove this template message) 1985 EP by Crime & the City SolutionThe Dangling ManEP by Crime & the City SolutionReleased1985RecordedFebruary 1985St...

1931 in music By location United Kingdom Norway By genre country jazz By topic 1931 in jazzDecade1930s in jazzMusic1931 in musicStandardsList of 1930s jazz standardsSee also1930 in jazz – 1932 in jazz Overview of the events of 1931 in jazz List of years in jazz … 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 … Art Archaeology Architecture Literature Music Philosophy Science +... This is a dynamic list and may never be able t...

 

VaspurakanՎասպուրական Estado desaparecido 908-1021 Vaspurakan en 908-1021Coordenadas 38°48′N 44°00′E / 38.8, 44Capital VanEntidad Estado desaparecidoIdioma oficial ArmenioSuperficie   • Total 40 870 km² Población ()   • Total 1 000 000 hab. • Densidad 24,47 hab/km²Religión CristianaHistoria   • 908 Conversión en reino • 1021 Cesión al Imperio bizantinoForma de gobierno Princi...

 

Strategi Solo vs Squad di Free Fire: Cara Menang Mudah!