We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
functionhanoi(posts){// Write your code hereconstn=posts.length;constrods=[0,0,0,0];for(leti=0;i<n;i++){rods[posts[i]-1]+=2**i;}constbase=2**n;constwin_state=(base-1)*(base**3);conststart_state=rods[0]*(base**3)+rods[1]*(base**2)+rods[2]*base+rods[3];constvisited=newSet();letcurrent=[start_state];letmoves=0;while(current.length>0){constnext=[];for(conststateofcurrent){if(state===win_state){returnmoves;}if(visited.has(state)){continue;}visited.add(state);constrods=[Math.floor((state/(base**3))%base),Math.floor((state/(base**2))%base),Math.floor((state/base)%base),state%base];consttop_discs=rods.map(n=>n===0?Infinity:n^(n&(n-1)));for(leti=0;i<4;i++){for(letj=i+1;j<4;j++){if(top_discs[i]===Infinity&&top_discs[j]===Infinity){continue;}letnew_state;if(top_discs[i]<top_discs[j]){new_state=state-top_discs[i]*(base**(3-i))+top_discs[i]*(base**(3-j));}else{new_state=state+top_discs[j]*(base**(3-i))-top_discs[j]*(base**(3-j));}if(!visited.has(new_state)){next.push(new_state);}}}}moves+=1;current=next;}}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Gena Playing Hanoi
You are viewing a single comment's thread. Return to all comments →
JavaScript based on solution from @chuntao_liu_0118