问:
Sort a list of numbers
About Code-Bowling:

In golf, you try to get the lowest score (smallest application, most elegant, etc). In Bowling, you try to get the highest score. So if you follow, the goal of a Code-Bowling challenge is to make the biggest, most bastardized, hardest to maintain piece of code that still meets the requirements of the challenge. However, there's no point in making source longer just for the sake of it. It needs to seem like that added length was from design and not just padding.

The Challenge:

Create a program that sorts a list of numbers in ascending order.

Example:

Input: 1, 4, 7, 2, 5

Output: 1, 2, 4, 5, 7

Code: Obviously this wouldn't be a good answer, since there aren't many WTFs in there

```<code>function doSort(array $input) {
    sort($input);
    return $input;
}
</code>```

Rules:

There are no real rules.  As long as the program functions, have at it!

Remember: This is code-bowling, not golf.  The objective is to make the worst, most bastardized code that you can!  Bonus points for code that looks good, but is actually deceptively evil...

答:
JavaScript (with animation!). 8172 chars. Few hours for 6 numbers.

We like lottery, right? Similar to Bogosort by dan04, but using physics and animation...

```<code>(function(){var e={},v=!1,G=/abc/.test(function(){abc})?/\b_super\b/:/.*/,H=function(c,a,b){return function(){var l=this._super,s;this._super=b[c];try{s=a.apply(this,arguments)}finally{this._super=l}return s}};e.Class=function(){};e.Class.extend=function a(b){var l=this.prototype;v=!0;var s=new this;v=!1;for(var c in b)s[c]="function"===typeof b[c]&&"function"===typeof l[c]&&G.test(b[c])?H(c,b[c],l):b[c];b=function(){!v&&this.init&&this.init.apply(this,arguments)};b.prototype=s;b.prototype.constructor=
b;b.extend=a;return b};e.Events={};var k=e.Events,z,A,w=Object.prototype.toString,I=document.createEvent,r=Date.now;k.EventListener=e.Class.extend({handleEvent:function(){},init:function(a){this.handleEvent=a}},"EventListener");z=k.EventListener;k.Event=e.Class.extend({timeStamp:0,type:"",target:null,cancelable:!1,defaultPrevented:!1,preventDefault:function(){this.cancelable&&(this.defaultPrevented=!0)},initEvent:function(a,b){this.type=a;this.target=b;this.timeStamp=r()}},"Event");A=k.Event;var t=
Object.create(null);e.createEventType=function(a,b){t[a]=A.extend(b,a);return t[a]};e.createEvent=function(a){return null!=t[a]?(a=new t[a],a.timeStamp=r(),a):I(a)};k.EventTarget=e.Class.extend({_listeners:{},addEventListener:function(a,b,l){var c=this._listeners[a];if(!(null!=c&&function(){for(var a="object"===typeof l?l:null,d,e=0,f=c.length;e<f;e++)if(d=this.listeners[e],d.listener.handleEvent===b&&d.scope===a)return!0;return!1}())){var d={listener:"object"===typeof b&&b.handleEvent?b:new z(b),
scope:"object"===typeof l?l:null};"[object Array]"===w.call(c)?c.push(d):this._listeners[a]=[d]}},removeEventListener:function(a,b,c){a=this._listeners[a];if("[object Array]"===w.call(a)){c="object"===typeof c?c:null;for(var d=0,e=a.length;d<e;d++)if(a[d].listener.handleEvent===b&&a[d].scope===c){a.splice(d,1);break}}},dispatchEvent:function(a){a.target||(a.target=this);var b=0,c=this._listeners[a.type],d=c.length,e;if("[object Array]"===w.call(c))for(;b<d;b++)e=c[b].listener.handleEvent,e.call(c[b].scope,
a);return a.defaultPrevented}},"EventTarget");for(var B=0,k=["ms","moz","webkit","o"],h=0;h<k.length&&!window.requestAnimationFrame;++h)window.requestAnimationFrame=window[k[h]+"RequestAnimationFrame"],window.cancelAnimationFrame=window[k[h]+"CancelAnimationFrame"]||window[k[h]+"CancelRequestAnimationFrame"];window.requestAnimationFrame||(window.requestAnimationFrame=function(a){var b=r(),c=Math.max(0,16-(b-B)),d=window.setTimeout(function(){a(b+c)},c);B=b+c;return d});window.cancelAnimationFrame||
(window.cancelAnimationFrame=function(a){clearTimeout(a)});var x=window.clearInterval,C=window.setInterval,D=e.Class.extend({fn:function(){},args:[],thisArg:window,sleepTime:0,init:function(a,b,c){this.method=a||function(){};this.thisArg=b||window;this.args=c||[]}},"FunctionToCall"),r=Date.now,u=Object.create(null);u.animation=0;u.steady=1;u.as_fast_as_possible=2;e.Timer=e.Events.EventTarget.extend({ANIMATION:0,STEADY:1,AS_FAST_AS_POSSIBLE:2,TimerEvent:e.createEventType("TimerEvent",{FPS:0,targetFPS:0,
delta:0,initEvent:function(a,b){if(null==b.getFPS||null==b.targetFPS||null==b.dt)throw notATimerException;this.FPS=b.getFPS();this.targetFPS=b.targetFPS;this.delta=b.dt;this._super(a,b)}}),_clearIntervalFlag:!1,_recursionCounter:0,_tickHandlersFromMethod:Object.create(null),running:!1,paused:!1,mode:0,autoStartStop:!0,setAutoStartStop:function(a){this.autoStartStop=a},prevTime:0,dt:0,maxDelta:0.05,setMaxDelta:function(a){this.maxDelta=a},sysTimerId:-1,targetFPS:50,setFPS:function(a){this.targetFPS=
a;if(this.running&&this.mode===this.STEADY){x(this.sysTimerId);var b=this;this.sysTimerId=C(function(){b.tick()},1E3/a)}},getFPS:function(){return 1/this.dt},queue:[],addToQueue:function(a,b,c){var d=new D(a,b,c),e;this.queue.push(d);var f=function J(f){0<d.sleepTime?d.sleepTime-=f.delta:(e=a.apply(b,[f].concat(c)),"number"===typeof e&&0<e?d.sleepTime=e:!0!==e&&(this.removeEventListener("tick",J,this),this.queue.splice(this.queue.indexOf(d),1)))};null==this._tickHandlersFromMethod[a]?this._tickHandlersFromMethod[a]=
[f]:this._tickHandlersFromMethod[a].push(f);this.addEventListener("tick",f,this);this.autoStartStop&&!this.running&&this.startLoop()},removeFromQueue:function(a){var b=this._tickHandlersFromMethod[a];a=this.queue.indexOf(a);if(-1!==a){for(var c=0,d=b.length;c<d;c++)this.removeEventListener("tick",b[c],this);return this.queue.splice(a,1)}},getQueue:function(){return this.queue.slice(0)},pause:function(){this._clearIntervalFlag=this.paused=!0;this.dt=0},resume:function(){this.paused=!1;this.startLoop()},
startLoop:function(){this.prevTime=r();this.running=!0;if(this.mode===this.steady){var a=this;this.sysTimerId=C(function(){a.tick()},1E3/this.targetFPS)}else this.tick()},tick:function(){if(this._clearIntervalFlag&&-1!==this.sysTimer)x(this.sysTimerId),this.sysTimerId=-1,this._clearIntervalFlag=!1;else if(!this.paused){var a=r();this.dt=(a-this.prevTime)/1E3;this.dt>this.maxDelta&&(this.dt=this.maxDelta);if(0===this.dt&&4>this._recursionCounter)this._recursionCounter++,this.tick();else{0<this._recursionCounter&&
(this._recursionCounter=0);var b=e.createEvent("TimerEvent");b.initEvent("tick",this);this.dispatchEvent(b);this.prevTime=a;a=!(this.autoStartStop&&0>=this.queue.length);if(this.mode===this.AS_FAST_AS_POSSIBLE&&a){var c=this;setTimeout(function(){c.tick()},0)}if(this.mode===this.ANIMATION&&a){var d=this;requestAnimationFrame(function(){d.tick()})}a||(this.running=!1,this.mode===this.STEADY&&-1!==this.sysTimerId&&(x(this.sysTimerId),this.sysTimerId=-1))}}},init:function(a){this.mode="number"===typeof a?
a:u[a];if(null==this.mode||0>this.mode||2<this.mode)this.mode=0}},"Timer");e.Timer.ANIMATION=0;e.Timer.STEADY=1;e.Timer.AS_FAST_AS_POSSIBLE=2;e.Timer.FunctionToCall=D;var j=[2,3,5,8,4,6],m=new (e.Class.extend({displace:0,velocity:0,drag:0.01,tickInterval:10,update:function(a){this.displace+=this.velocity*a.delta;this.velocity*=1-this.drag},init:function(){}})),q=j.slice(0),k=new e.Timer(0),h=document.createElement("div");h.style.width=23*j.length-28+"px";h.style.height="22px";h.style.overflowX="hidden";
h.style.overflowY="hidden";h.style.border="1px #555 solid";h.style.fontFamily='Consolas, "Courier New"';for(var c=[],f=0;f<j.length;f++)c[f]=document.createElement("div"),c[f].style.width="20px",c[f].style.height="20px",c[f].style.display="inline-block",c[f].style.position="relative",c[f].style.left=f+1===j.length?"-22px":"0px",c[f].style.top=f+1===j.length?"-22px":"0px",c[f].style.border="1px #AAA solid",c[f].style.textAlign="center",c[f].innerHTML=j[f],h.appendChild(c[f]);var g=0,d=1,n,p,E=0,F=
0,y=0;m.velocity=1E3*Math.random()+500;document.getElementsByTagName("body")[0].appendChild(h);k.addToQueue(function(a){if(5>m.velocity)if(0===g){for(a=0;a<c.length;a++)if((m.displace+22+22*a)%(22*j.length)-22<11*c.length&&(m.displace+22+22*a)%(22*j.length)>11*c.length){n=c[a];E=parseFloat(n.style.left);break}for(a=0;a<c.length;a++)if((m.displace+22+22*a)%(22*j.length)<11*c.length&&(m.displace+22+22*a)%(22*j.length)+22>11*c.length){p=c[a];F=parseFloat(p.style.left);break}y=p.offsetLeft-n.offsetLeft;
g=1}else if(1===g)n.style.backgroundColor="rgba(255,255,0,"+Math.round(1-d)+")",p.style.backgroundColor="rgba(255,255,0,"+Math.round(1-d)+")",d-=10*a.delta,0>d&&(g=2);else if(2==g)n.style.backgroundColor="rgba(255,255,0,"+Math.round(1-d)+")",p.style.backgroundColor="rgba(255,255,0,"+Math.round(1-d)+")",d+=10*a.delta,1<d&&(g=3,n.style.backgroundColor="rgba(255,255,255,0)",p.style.backgroundColor="rgba(255,255,255,0)",d=0);else if(3==g)n.style.left=E+d*y+"px",p.style.left=F-d*y+"px",d+=2*a.delta,1<
d&&(g=4);else if(4==g){if(d-=a.delta,0.5>d){a=c.indexOf(n);var b=c.indexOf(p),e;e=n.innerHTML;c[a].innerHTML=p.innerHTML;c[b].innerHTML=e;e=q[a];q.splice(a,1,q[b]);q.splice(b,1,e);b=-1/0;for(a=0;a<q.length;a++){if(q[a]<b){g=5;break}b=q[a]}g=5===g?5:6}}else if(5===g)d=1,m.velocity=1E3*Math.random()+500,g=0;else{if(6===g)return d=1,g=0,document.getElementsByTagName("body")[0].innerHTML+=q,!1}else{m.update(a);for(a=0;a<c.length;a++)b=(m.displace+22+22*a)%(22*j.length),a+1===j.length&&(b+=22*(j.length-
1)),c[a].style.left=b-22*a-22+"px"}return!0})})();
</code>```

However, I used a bit of Google Closure Compiler to, er... I don't know. But it looks uglier, right?

It's like one of those lottory wheels, and each time it stops it swaps to numbers in the middle.
You can have a play here: http://jsfiddle.net/VkJUE/5/ (to understand what I mean)

It does work, a bit, except that it may take hours for 6 numbers. However, I tested it on 3 numbers and it works fine!

ContentLicense: CC BY-SA 2.5

Title: Sort a list of numbers

Body:
JavaScript (with animation!). 8172 chars. Few hours for 6 numbers.

We like lottery, right? Similar to Bogosort by dan04, but using physics and animation...

(function(){var e={},v=!1,G=/abc/.test(function(){abc})?/\b_super\b/:/.*/,H=function(c,a,b){return function(){var l=this._super,s;this._super=b[c];try{s=a.apply(this,arguments)}finally{this._super=l}return s}};e.Class=function(){};e.Class.extend=function a(b){var l=this.prototype;v=!0;var s=new this;v=!1;for(var c in b)s[c]="function"===typeof b[c]&&"function"===typeof l[c]&&G.test(b[c])?H(c,b[c],l):b[c];b=function(){!v&&this.init&&this.init.apply(this,arguments)};b.prototype=s;b.prototype.constructor=
b;b.extend=a;return b};e.Events={};var k=e.Events,z,A,w=Object.prototype.toString,I=document.createEvent,r=Date.now;k.EventListener=e.Class.extend({handleEvent:function(){},init:function(a){this.handleEvent=a}},"EventListener");z=k.EventListener;k.Event=e.Class.extend({timeStamp:0,type:"",target:null,cancelable:!1,defaultPrevented:!1,preventDefault:function(){this.cancelable&&(this.defaultPrevented=!0)},initEvent:function(a,b){this.type=a;this.target=b;this.timeStamp=r()}},"Event");A=k.Event;var t=
Object.create(null);e.createEventType=function(a,b){t[a]=A.extend(b,a);return t[a]};e.createEvent=function(a){return null!=t[a]?(a=new t[a],a.timeStamp=r(),a):I(a)};k.EventTarget=e.Class.extend({_listeners:{},addEventListener:function(a,b,l){var c=this._listeners[a];if(!(null!=c&&function(){for(var a="object"===typeof l?l:null,d,e=0,f=c.length;e<f;e++)if(d=this.listeners[e],d.listener.handleEvent===b&&d.scope===a)return!0;return!1}())){var d={listener:"object"===typeof b&&b.handleEvent?b:new z(b),
scope:"object"===typeof l?l:null};"[object Array]"===w.call(c)?c.push(d):this._listeners[a]=[d]}},removeEventListener:function(a,b,c){a=this._listeners[a];if("[object Array]"===w.call(a)){c="object"===typeof c?c:null;for(var d=0,e=a.length;d<e;d++)if(a[d].listener.handleEvent===b&&a[d].scope===c){a.splice(d,1);break}}},dispatchEvent:function(a){a.target||(a.target=this);var b=0,c=this._listeners[a.type],d=c.length,e;if("[object Array]"===w.call(c))for(;b<d;b++)e=c[b].listener.handleEvent,e.call(c[b].scope,
a);return a.defaultPrevented}},"EventTarget");for(var B=0,k=["ms","moz","webkit","o"],h=0;h<k.length&&!window.requestAnimationFrame;++h)window.requestAnimationFrame=window[k[h]+"RequestAnimationFrame"],window.cancelAnimationFrame=window[k[h]+"CancelAnimationFrame"]||window[k[h]+"CancelRequestAnimationFrame"];window.requestAnimationFrame||(window.requestAnimationFrame=function(a){var b=r(),c=Math.max(0,16-(b-B)),d=window.setTimeout(function(){a(b+c)},c);B=b+c;return d});window.cancelAnimationFrame||
(window.cancelAnimationFrame=function(a){clearTimeout(a)});var x=window.clearInterval,C=window.setInterval,D=e.Class.extend({fn:function(){},args:[],thisArg:window,sleepTime:0,init:function(a,b,c){this.method=a||function(){};this.thisArg=b||window;this.args=c||[]}},"FunctionToCall"),r=Date.now,u=Object.create(null);u.animation=0;u.steady=1;u.as_fast_as_possible=2;e.Timer=e.Events.EventTarget.extend({ANIMATION:0,STEADY:1,AS_FAST_AS_POSSIBLE:2,TimerEvent:e.createEventType("TimerEvent",{FPS:0,targetFPS:0,
delta:0,initEvent:function(a,b){if(null==b.getFPS||null==b.targetFPS||null==b.dt)throw notATimerException;this.FPS=b.getFPS();this.targetFPS=b.targetFPS;this.delta=b.dt;this._super(a,b)}}),_clearIntervalFlag:!1,_recursionCounter:0,_tickHandlersFromMethod:Object.create(null),running:!1,paused:!1,mode:0,autoStartStop:!0,setAutoStartStop:function(a){this.autoStartStop=a},prevTime:0,dt:0,maxDelta:0.05,setMaxDelta:function(a){this.maxDelta=a},sysTimerId:-1,targetFPS:50,setFPS:function(a){this.targetFPS=
a;if(this.running&&this.mode===this.STEADY){x(this.sysTimerId);var b=this;this.sysTimerId=C(function(){b.tick()},1E3/a)}},getFPS:function(){return 1/this.dt},queue:[],addToQueue:function(a,b,c){var d=new D(a,b,c),e;this.queue.push(d);var f=function J(f){0<d.sleepTime?d.sleepTime-=f.delta:(e=a.apply(b,[f].concat(c)),"number"===typeof e&&0<e?d.sleepTime=e:!0!==e&&(this.removeEventListener("tick",J,this),this.queue.splice(this.queue.indexOf(d),1)))};null==this._tickHandlersFromMethod[a]?this._tickHandlersFromMethod[a]=
[f]:this._tickHandlersFromMethod[a].push(f);this.addEventListener("tick",f,this);this.autoStartStop&&!this.running&&this.startLoop()},removeFromQueue:function(a){var b=this._tickHandlersFromMethod[a];a=this.queue.indexOf(a);if(-1!==a){for(var c=0,d=b.length;c<d;c++)this.removeEventListener("tick",b[c],this);return this.queue.splice(a,1)}},getQueue:function(){return this.queue.slice(0)},pause:function(){this._clearIntervalFlag=this.paused=!0;this.dt=0},resume:function(){this.paused=!1;this.startLoop()},
startLoop:function(){this.prevTime=r();this.running=!0;if(this.mode===this.steady){var a=this;this.sysTimerId=C(function(){a.tick()},1E3/this.targetFPS)}else this.tick()},tick:function(){if(this._clearIntervalFlag&&-1!==this.sysTimer)x(this.sysTimerId),this.sysTimerId=-1,this._clearIntervalFlag=!1;else if(!this.paused){var a=r();this.dt=(a-this.prevTime)/1E3;this.dt>this.maxDelta&&(this.dt=this.maxDelta);if(0===this.dt&&4>this._recursionCounter)this._recursionCounter++,this.tick();else{0<this._recursionCounter&&
(this._recursionCounter=0);var b=e.createEvent("TimerEvent");b.initEvent("tick",this);this.dispatchEvent(b);this.prevTime=a;a=!(this.autoStartStop&&0>=this.queue.length);if(this.mode===this.AS_FAST_AS_POSSIBLE&&a){var c=this;setTimeout(function(){c.tick()},0)}if(this.mode===this.ANIMATION&&a){var d=this;requestAnimationFrame(function(){d.tick()})}a||(this.running=!1,this.mode===this.STEADY&&-1!==this.sysTimerId&&(x(this.sysTimerId),this.sysTimerId=-1))}}},init:function(a){this.mode="number"===typeof a?
a:u[a];if(null==this.mode||0>this.mode||2<this.mode)this.mode=0}},"Timer");e.Timer.ANIMATION=0;e.Timer.STEADY=1;e.Timer.AS_FAST_AS_POSSIBLE=2;e.Timer.FunctionToCall=D;var j=[2,3,5,8,4,6],m=new (e.Class.extend({displace:0,velocity:0,drag:0.01,tickInterval:10,update:function(a){this.displace+=this.velocity*a.delta;this.velocity*=1-this.drag},init:function(){}})),q=j.slice(0),k=new e.Timer(0),h=document.createElement("div");h.style.width=23*j.length-28+"px";h.style.height="22px";h.style.overflowX="hidden";
h.style.overflowY="hidden";h.style.border="1px #555 solid";h.style.fontFamily='Consolas, "Courier New"';for(var c=[],f=0;f<j.length;f++)c[f]=document.createElement("div"),c[f].style.width="20px",c[f].style.height="20px",c[f].style.display="inline-block",c[f].style.position="relative",c[f].style.left=f+1===j.length?"-22px":"0px",c[f].style.top=f+1===j.length?"-22px":"0px",c[f].style.border="1px #AAA solid",c[f].style.textAlign="center",c[f].innerHTML=j[f],h.appendChild(c[f]);var g=0,d=1,n,p,E=0,F=
0,y=0;m.velocity=1E3*Math.random()+500;document.getElementsByTagName("body")[0].appendChild(h);k.addToQueue(function(a){if(5>m.velocity)if(0===g){for(a=0;a<c.length;a++)if((m.displace+22+22*a)%(22*j.length)-22<11*c.length&&(m.displace+22+22*a)%(22*j.length)>11*c.length){n=c[a];E=parseFloat(n.style.left);break}for(a=0;a<c.length;a++)if((m.displace+22+22*a)%(22*j.length)<11*c.length&&(m.displace+22+22*a)%(22*j.length)+22>11*c.length){p=c[a];F=parseFloat(p.style.left);break}y=p.offsetLeft-n.offsetLeft;
g=1}else if(1===g)n.style.backgroundColor="rgba(255,255,0,"+Math.round(1-d)+")",p.style.backgroundColor="rgba(255,255,0,"+Math.round(1-d)+")",d-=10*a.delta,0>d&&(g=2);else if(2==g)n.style.backgroundColor="rgba(255,255,0,"+Math.round(1-d)+")",p.style.backgroundColor="rgba(255,255,0,"+Math.round(1-d)+")",d+=10*a.delta,1<d&&(g=3,n.style.backgroundColor="rgba(255,255,255,0)",p.style.backgroundColor="rgba(255,255,255,0)",d=0);else if(3==g)n.style.left=E+d*y+"px",p.style.left=F-d*y+"px",d+=2*a.delta,1<
d&&(g=4);else if(4==g){if(d-=a.delta,0.5>d){a=c.indexOf(n);var b=c.indexOf(p),e;e=n.innerHTML;c[a].innerHTML=p.innerHTML;c[b].innerHTML=e;e=q[a];q.splice(a,1,q[b]);q.splice(b,1,e);b=-1/0;for(a=0;a<q.length;a++){if(q[a]<b){g=5;break}b=q[a]}g=5===g?5:6}}else if(5===g)d=1,m.velocity=1E3*Math.random()+500,g=0;else{if(6===g)return d=1,g=0,document.getElementsByTagName("body")[0].innerHTML+=q,!1}else{m.update(a);for(a=0;a<c.length;a++)b=(m.displace+22+22*a)%(22*j.length),a+1===j.length&&(b+=22*(j.length-
1)),c[a].style.left=b-22*a-22+"px"}return!0})})();

However, I used a bit of Google Closure Compiler to, er... I don't know. But it looks uglier, right?

It's like one of those lottory wheels, and each time it stops it swaps to numbers in the middle.
You can have a play here: http://jsfiddle.net/VkJUE/5/ (to understand what I mean)

It does work, a bit, except that it may take hours for 6 numbers. However, I tested it on 3 numbers and it works fine!


问:
What's your next move?
This challenge is to write a minimax function in a language of your choice, to output the next best move in an NxN game of tic-tac-toe given the current board state. The board input can be accepted as a Matrix, 2D Collection or anything else that makes sense to you, but adheres to the rules. The output being the next best move for whoever's turn it is currently, where X is considered to have started.

Quick Background on the Minimax Algorithm

The basic idea of the minimax algorithm is to enumerate all possible outcomes as a DAG then weight them by the benefit that the sequence of moves has to the player, keyed by the first move made. All possible outcomes are then 'bucketed' by the first move, and are scored based on the sum of all outcomes (-1 for a loss, 0 for a tie and a 1 for a win). In implementations that require multiple players to play, you enumerate all possible moves by the player, and all possible responses by the opponents as well. For instance, in a game of tic-tac-toe (after the first move) there are 8 possible first moves you can make, and they all may seem equal when only analyzing the next turn. But by iterating through all possible outcomes for each possible set of moves that results in a final outcome and summing them all up, we can get a score for our next move, and have a basis for our choices.

For a better, more in-depth and contextual summary of the mini-max algorithm in terms of tic-tac-toe, read more here: http://neverstopbuilding.com/minimax

XKCD (3x3 Solution Only)

The Rules

Any language can be used, but no external minimax libraries are allowed.

Output can be a coordinate (0-n,0-n) or a number (1-n*n) indicative of the best next move.

In addition to this, you must be able to identify when the best case scenario is a loss or a tie instead of a win.

The way you denote a loss or a tie is, once again, up to you.

Input must use the traditional X and O, and you must assume X moves first; blank spaces can be represented by anything.

You may assume any inputs coming into your program have n O's and n+1 X's, in other words you may assume you're getting a well-formed board.

The current state of the board must be the only input to your program, if you are using recursion, helper methods must be made to facilitate the input requirements. See https://codegolf.stackexchange.com/a/92851/59376 for clarification.

Any value of 10 >= n >= 1 must be supported; if your program "times out" for n > 10, I find this acceptable as well, as some languages have significantly lower processing power (Especially using web-facing consoles).

Judging

This is code-golf, so the lowest byte-count of the program wins and standard loopholes are universally disallowed.

In the case of a tie, the program that supports the largest 'n' will win.

Example Inputs

2x2

```<code>[[X,O]
 [-,-]]
</code>```

Output: 2 or [0,1]  (3 or [1,1] would also be arguably correct)
(Some form of indication of the location, arbitrary as long as you can easily explain the format you used)

3x3

```<code>[[X,O,X]
 [O,X,-]
 [-,-,-]]
</code>```

Output: -1 (Loss)

Once again any input format you want is allowed, but X's and O's must be used, the examples provided were not meant to constrain to that format, just to inspire.

答:
Javascript (ES6), <s>320</s> 294 bytes

```<code>(b,p,d,M,S=-2)=>(T=(p,q,r,s)=>b[p][q]==(n=b[r][s|0])&&n!='-',w=0,b.map((r,y)=>(l=r.length-1,m=15,r.map((c,x)=>(m&=8*T(l-x,x,l)+4*T(x,x,0)+2*T(x,y,0,y)+T(y,x,y))),w|=m)),w?-1:(b.map((r,y)=>r.map((c,x)=>S<1&&c=='-'&&(r[x]='O.X'[p+1],(s=-f(b,-p,1))>S&&(S=s,M=[x,y]),r[x]=c))),S=S+2?S:0,d?S:[M,S]))
</code>```

Input

1) An array of array of characters describing the current board, such as:

```<code>[['X', '-'], ['-', 'O']]
</code>```

2) An integer describing the current turn: 1 = X, -1 = O

Output

An array made of:

an array describing the best move in [x, y] format

the outcome of the game as an integer: 1 = win, -1 = loss, 0 = tie

Example

In the following example, X is guaranteed to win by playing [1, 2].

let f =
(b,p,d,M,S=-2)=>(T=(p,q,r,s)=>b[p][q]==(n=b[r][s|0])&&n!='-',w=0,b.map((r,y)=>(l=r.length-1,m=15,r.map((c,x)=>(m&=8*T(l-x,x,l)+4*T(x,x,0)+2*T(x,y,0,y)+T(y,x,y))),w|=m)),w?-1:(b.map((r,y)=>r.map((c,x)=>S<1&&c=='-'&&(r[x]='O.X'[p+1],(s=-f(b,-p,1))>S&&(S=s,M=[x,y]),r[x]=c))),S=S+2?S:0,d?S:[M,S]))

console.log(JSON.stringify(f(
  [['O','X','O'],
   ['-','-','-'],
   ['-','-','X']],
  1
)));```

A STRANGE GAME. THE ONLY WINNING MOVE IS NOT PLAY.

HOW ABOUT A NICE GAME OF CHESS?

ContentLicense: CC BY-SA 3.0

Title: What's your next move?

Body:
Javascript (ES6), <s>320</s> 294 bytes

(b,p,d,M,S=-2)=>(T=(p,q,r,s)=>b[p][q]==(n=b[r][s|0])&&n!='-',w=0,b.map((r,y)=>(l=r.length-1,m=15,r.map((c,x)=>(m&=8*T(l-x,x,l)+4*T(x,x,0)+2*T(x,y,0,y)+T(y,x,y))),w|=m)),w?-1:(b.map((r,y)=>r.map((c,x)=>S<1&&c=='-'&&(r[x]='O.X'[p+1],(s=-f(b,-p,1))>S&&(S=s,M=[x,y]),r[x]=c))),S=S+2?S:0,d?S:[M,S]))

Input

1) An array of array of characters describing the current board, such as:

[['X', '-'], ['-', 'O']]

2) An integer describing the current turn: 1 = X, -1 = O

Output

An array made of:

an array describing the best move in [x, y] format

the outcome of the game as an integer: 1 = win, -1 = loss, 0 = tie

Example

In the following example, X is guaranteed to win by playing [1, 2].

let f =
(b,p,d,M,S=-2)=>(T=(p,q,r,s)=>b[p][q]==(n=b[r][s|0])&&n!='-',w=0,b.map((r,y)=>(l=r.length-1,m=15,r.map((c,x)=>(m&=8*T(l-x,x,l)+4*T(x,x,0)+2*T(x,y,0,y)+T(y,x,y))),w|=m)),w?-1:(b.map((r,y)=>r.map((c,x)=>S<1&&c=='-'&&(r[x]='O.X'[p+1],(s=-f(b,-p,1))>S&&(S=s,M=[x,y]),r[x]=c))),S=S+2?S:0,d?S:[M,S]))

console.log(JSON.stringify(f(
  [['O','X','O'],
   ['-','-','-'],
   ['-','-','X']],
  1
)));

A STRANGE GAME. THE ONLY WINNING MOVE IS NOT PLAY.

HOW ABOUT A NICE GAME OF CHESS?


问:
Marcel Proust and Markov decipher security service’s T9 texts
As if this challenge could be any more Pythonesque in spirit... No prior knowledge of Markov chains or encryption techniques is required.

You are a spy who needs to obtain some crucial information from the British security service M1S. The agents of M1S are well aware that their Wi-Fi signals can be intercepted, their Android/iOS security vulnerabilities exploited etc., so all of them are using Nokia 3310’s to transmit text information which is typed using the T9 auto-completion.

You had previously hacked the phones to be delivered to the intelligence agency and had installed keyloggers under their glorious plastic keyboards, so now you receive sequences of numbers corresponding to the letters they typed, so “the eagle has left the nest alert the agents” becomes

```<code>84303245304270533808430637802537808430243687
</code>```

But wait! Some T9 sequences are ambiguous (“6263” could be “name”, “mane” or “oboe”; the more obscure, the more suspicious it gets!), so what do you do? You know that the only entrance examination M1S uses is summarising Marcel Proust’s masterpiece “Remembrance of Things Past” in 15 seconds, so you want to pick the word that comes next after the previous one according to its frequency distribution in the entire chef-d’œuvre of Proust!

Can you crack the code and obtain what could be the original message?

The principle of T9

The T9 auto-completion mechanism can be described as follows. It maps alphabetic characters to numbers as shown on the picture above.

```<code>abc     -> 2
def     -> 3
ghi     -> 4
jkl     -> 5
mno     -> 6
pqrs    -> 7
tuv     -> 8
wxyz    -> 9
<space> -> 0
<other> -> <is deleted>
</code>```

The T9 decryptor receives a sequence of digits and tries to guess the word that could be typed with those keypresses. It might use a standard frequency table, but we are going one step further and predicting the next word using a Markov chain!

Learning sample

The corpus is this heavily stripped version of Proust’s “Remembrance of Things Past” (s/-/ /g, s/['’]s //g and s/[^a-zA-Z ]//g — begone confusing possessive 's!) originally published on the University of Adelaide website (the text of this work is in the Public Domain in Australia).

The whole text must be analysed as one string, as one long sentence, as one long vector of words (whichever is more convenient for your language), stripped of linebreaks, and split into words at spaces. (I do not supply a single-paragraph file because such might be frowned upon by github tools.)

How do I read the whole text as one string / sentence? An example in R:

```<code>p_raw  <- read.table("proust.txt", sep="\t") # Because there are no tabs
p_vec  <- as.character(p_raw$V1)       # Conversion to character vector
p_str  <- paste(p_vec, collapse=" ")   # One long string with spaces
p_spl  <- strsplit(p_str, split=" ")[[1]] # Vector of 1360883 words
proust <- p_spl[p_spl!=""]           # Remove empty entries — 1360797
</code>```

Task

Given a sequence of digits as a number, return a possible text string that could be typed using the corresponding T9 keys using a probabilty chain to predict the next word X based on this training text treated as one long sentence.

If X is the first T9-word of the text and there are multiple guesses, pick one at random, otherwise pick the only one possible.

For all subsequent T9-words X(i) preceded by a word already deciphered w(i-1):

If a T9-word X can be converted into a normal word x in one unique way, do it.

If there are multiple conversion options available for X, say x1, x2, ..., look up the preceding guessed word w.

If w is never followed by anything that maps to X in the original work of Proust, pick any of the possible x1, x2, ... at random.

If w X always corresponds to w x1 in the original and there are no concurrent xi’s that could be mapped into X, pick x1.

If w X can be converted to w x1, w x2, ... that can be found in the corpus, then count all possible xi’s that follow w and map to X in the corpus and pick xi with probability xi/(x1 + x2 + ...).

Example 2a. If the message is 76630489, where 489 could be guy or ivy (they occur in the corpus at least once), 7663 can be deciphered as some (a very probable first word). If some is never followed by anything that maps to 489 in the corpus, then pick guy or ivy at random with probability 0.5.

Example 2b. If the message is 766302277437, where 2277437 could be barrier or carrier, 7663 can be deciphered as some. If Proust always used some carrier and never some barrier, then pick some carrier.

Example 2c. Suppose that you want to decipher the sequence 536307663. 5363 was predicted as lend. 7663 could be any of these: pond, roof and some. You count the occurrences of the word following lend in the sample corpus. Suppose you get something like this (just to illustrate):

```<code>        T9  Word following lend  Occurrences
      7663  some                           7
      7663  pond                           2
      7663  roof                           1
</code>```

So if 7663 is preceded by lend, there is 7/(7+2+1)=70% probability that 7663 stands for some, 20% pond and 10% roof. Your algorithm should produce lend some in 70% cases, lend pond in 20% cases etc.

You may safely assume that the agents use only a-z letters and spaces (no punctuation marks, no possessive 's, and no numbers).

You may also assume that the agents of M1S never use any words outside the scope of “Remembrance of Things Past” (which is a whopping vocabulary of 29,237 words!).

The T9 fuctionality was implemented in this challenge, so you might have a look at it.

If you need any help, probabilistic chains were gloriously tamed in this, that and the following challenges, but you do not even need to know the principle of such chains: everything is stated in the task.

Test cases

```<code>--Inputs--
20784250276960369
20784250276960369
84303245304270533808430637802537808430243687
94280343084306289072908608430262780482737
94280343084306289072908608430262780482737

--Possible outputs--
c quick brown fox
a stick crown fox
the eagle gas left the nest blest vie agents
what did the navy pay to the coast guards
what did the navy raz un the coast guards
</code>```

Rules:

Standard loopholes apply.

You do not know the original message, all you get is a sequence of digits and the file proust.txt that you just need to load in the memory / workspace / whatever. There is no need to have anything self-contained; assume proust.txt is always accessible.

Your algorithm must be able to produce different outputs with respective probabilities if more than one decryption option is probable according to the corpus (see Example 2c).

You need to stay as discreet as possible, so the shortest code wins!

P.S. The obvious benefit of this probabilistic algorithm is the fact that the probability you will get a true original string for an ambiguous deciphered string tends to one — just wait...

P.P.S.  See also Prediction by Partial Matching.

答:
R solution, non-competing illustration of what can be done

Firstly, we load the sequence of words into the memory:

```<code>p_raw  <- read.table("proust.txt", sep="\t") # Because there are no tabs
p_vec  <- as.character(p_raw$V1)       # Conversion to character vector
p_str  <- paste(p_vec, collapse=" ")   # One long string with spaces
p_spl  <- strsplit(p_str, split=" ")[[1]] # Vector of 1360883 words
proust <- p_spl[p_spl!=""]           # Remove empty entries — 1360797
</code>```

Secondly, we need a function that T9-ifies any text:

```<code>t9 <- function (x) {
  x <- chartr(paste(c(letters, " "), collapse=""), "222333444555666777788899990", tolower(x))
  x <- gsub("[^0-9]", "", x, perl = TRUE) # Safety check
  x <- x[x!=""] # Also for safety because... you know...
  x
}
</code>```

Then, we T9-ify Proust:

```<code>p9 <- t9(proust)
</code>```

Final preparation: we split the input string at zeros using a function that we call prep):

```<code>prep <- function (x) {
  x <- chartr("0", " ", x)
  x <- strsplit(x, " ")[[1]]
  x <- x[x!=""] # Boil the empty strings for safety
  x
}
</code>```

And now I propose a function that takes any input string of numbers, preps it and deciphers the words one by one:

```<code>decip <- function(x, verbose = FALSE) {
  x <- prep(x)
  l <- length(x)
  decrypted <- rep(NA, l)
  tb <- table(proust[which(p9 == x[1])])
  decrypted[1] <- sample(names(tb), 1, prob=tb/sum(tb))
  if (verbose) print(decrypted[1])
  for (i in 2:l) {
    mtchl <- p9 == x[i]
    mtch <- which(mtchl)  # Positions that matched
    pmtch <- proust[mtch] # Words that matched
    tb <- table(pmtch)    # Count occurrences that matched
    if (length(tb)==1) {  # It is either 1 or >1
      decrypted[i] <- names(tb)[1]
      if (verbose) print(paste0("i = ", i, ", case 1: unique decryption"))
      } else {  # If there are more than one ways to decipher...
      preced <- proust[mtch-1]
      s <- sum(preced==decrypted[i-1])
      if (s==0) {
        decrypted[i] <- sample(names(tb), 1)
        if (verbose) print(paste0("i = ", i, ", case 2a: multiple decryption, collocation never used, picking at random"))
        } else {
        tb2 <- table(pmtch[preced==decrypted[i-1]])
        if (length(tb2)==1) {
          decrypted[i] <-  names(tb2)[1]
          if (verbose) print(paste0("i = ", i, ", case 2b: multiple decryption, only one collocation found, using it"))
        } else {
          decrypted[i] <- sample(names(tb2), 1, prob = tb2/sum(tb2))
          if (verbose) print(paste0("i = ", i, ", case 2c: multiple decryption, ", length(tb2), " choices"))
          }
      }
    }
    if(verbose) print(decrypted[i])
  }
  decrypted
}
</code>```

And now what it is actually doing:

```<code>decip("20784250276960369", verbose=TRUE)
----
[1] "a"
[1] "i = 2, case 2c: multiple decryption, 2 choices"
[1] "quick"
[1] "i = 3, case 2a: multiple decryption, collocation never used, picking at random"
[1] "brown"
[1] "i = 4, case 1: unique decryption"
[1] "fox"
[1] "a"     "quick" "brown" "fox"
</code>```

Second example:

```<code>decip("84303245304270533808430637802537808430243687", verbose=TRUE)
----
[1] "what"
[1] "i = 2, case 2b: multiple decryption, only one collocation found, using it"
[1] "did"
[1] "i = 3, case 2b: multiple decryption, only one collocation found, using it"
[1] "the"
[1] "i = 4, case 1: unique decryption"
[1] "navy"
[1] "i = 5, case 2a: multiple decryption, collocation never used, picking at random"
[1] "raz"
[1] "i = 6, case 2a: multiple decryption, collocation never used, picking at random"
[1] "um"
[1] "i = 7, case 2a: multiple decryption, collocation never used, picking at random"
[1] "the"
[1] "i = 8, case 2b: multiple decryption, only one collocation found, using it"
[1] "coast"
[1] "i = 9, case 1: unique decryption"
[1] "guards"
[1] "what"   "did"    "the"    "navy"   "raz"    "um"     "the"    "coast"  "guards"
</code>```

Please do not comment that this can be golfed. Seems that few people are interested in this challenge because of my terrible verbosity, so I posted this answer to show what a possible programme could look like. You need not upvote/downvote this answer.

Body:
R solution, non-competing illustration of what can be done

Firstly, we load the sequence of words into the memory:

p_raw  <- read.table("proust.txt", sep="\t") # Because there are no tabs
p_vec  <- as.character(p_raw$V1)       # Conversion to character vector
p_str  <- paste(p_vec, collapse=" ")   # One long string with spaces
p_spl  <- strsplit(p_str, split=" ")[[1]] # Vector of 1360883 words
proust <- p_spl[p_spl!=""]           # Remove empty entries — 1360797

Secondly, we need a function that T9-ifies any text:

t9 <- function (x) {
  x <- chartr(paste(c(letters, " "), collapse=""), "222333444555666777788899990", tolower(x))
  x <- gsub("[^0-9]", "", x, perl = TRUE) # Safety check
  x <- x[x!=""] # Also for safety because... you know...
  x
}

Then, we T9-ify Proust:

p9 <- t9(proust)

Final preparation: we split the input string at zeros using a function that we call prep):

prep <- function (x) {
  x <- chartr("0", " ", x)
  x <- strsplit(x, " ")[[1]]
  x <- x[x!=""] # Boil the empty strings for safety
  x
}

And now I propose a function that takes any input string of numbers, preps it and deciphers the words one by one:

decip <- function(x, verbose = FALSE) {
  x <- prep(x)
  l <- length(x)
  decrypted <- rep(NA, l)
  tb <- table(proust[which(p9 == x[1])])
  decrypted[1] <- sample(names(tb), 1, prob=tb/sum(tb))
  if (verbose) print(decrypted[1])
  for (i in 2:l) {
    mtchl <- p9 == x[i]
    mtch <- which(mtchl)  # Positions that matched
    pmtch <- proust[mtch] # Words that matched
    tb <- table(pmtch)    # Count occurrences that matched
    if (length(tb)==1) {  # It is either 1 or >1
      decrypted[i] <- names(tb)[1]
      if (verbose) print(paste0("i = ", i, ", case 1: unique decryption"))
      } else {  # If there are more than one ways to decipher...
      preced <- proust[mtch-1]
      s <- sum(preced==decrypted[i-1])
      if (s==0) {
        decrypted[i] <- sample(names(tb), 1)
        if (verbose) print(paste0("i = ", i, ", case 2a: multiple decryption, collocation never used, picking at random"))
        } else {
        tb2 <- table(pmtch[preced==decrypted[i-1]])
        if (length(tb2)==1) {
          decrypted[i] <-  names(tb2)[1]
          if (verbose) print(paste0("i = ", i, ", case 2b: multiple decryption, only one collocation found, using it"))
        } else {
          decrypted[i] <- sample(names(tb2), 1, prob = tb2/sum(tb2))
          if (verbose) print(paste0("i = ", i, ", case 2c: multiple decryption, ", length(tb2), " choices"))
          }
      }
    }
    if(verbose) print(decrypted[i])
  }
  decrypted
}

And now what it is actually doing:

decip("20784250276960369", verbose=TRUE)
----
[1] "a"
[1] "i = 2, case 2c: multiple decryption, 2 choices"
[1] "quick"
[1] "i = 3, case 2a: multiple decryption, collocation never used, picking at random"
[1] "brown"
[1] "i = 4, case 1: unique decryption"
[1] "fox"
[1] "a"     "quick" "brown" "fox"

Second example:

decip("84303245304270533808430637802537808430243687", verbose=TRUE)
----
[1] "what"
[1] "i = 2, case 2b: multiple decryption, only one collocation found, using it"
[1] "did"
[1] "i = 3, case 2b: multiple decryption, only one collocation found, using it"
[1] "the"
[1] "i = 4, case 1: unique decryption"
[1] "navy"
[1] "i = 5, case 2a: multiple decryption, collocation never used, picking at random"
[1] "raz"
[1] "i = 6, case 2a: multiple decryption, collocation never used, picking at random"
[1] "um"
[1] "i = 7, case 2a: multiple decryption, collocation never used, picking at random"
[1] "the"
[1] "i = 8, case 2b: multiple decryption, only one collocation found, using it"
[1] "coast"
[1] "i = 9, case 1: unique decryption"
[1] "guards"
[1] "what"   "did"    "the"    "navy"   "raz"    "um"     "the"    "coast"  "guards"

Please do not comment that this can be golfed. Seems that few people are interested in this challenge because of my terrible verbosity, so I posted this answer to show what a possible programme could look like. You need not upvote/downvote this answer.


问:
Counting Goats to Sleep
Some people count sheep to get to sleep. Others count goats.

Write a program or function that takes in a positive integer N and outputs N-1 awake goats followed by one sleeping goat, as if someone was counting N goats and at the very last one they fell asleep.

Awake goats look like this:

```<code>      \
  ___/o>
-(___)"
 '' ''
</code>```

Sleeping goats look like this:

```<code>      \
  ___/->
,(___)"
 `` ``
</code>```

They are chained together with a single space between beard and tail of adjacent goats:

```<code>      \       \       \
  ___/o>  ___/o>  ___/->
-(___)" -(___)" ,(___)"
 '' ''   '' ''   `` ``
</code>```

The output is allowed to have trailing spaces and a single trailing newline.

The shortest code in bytes wins.

Examples

N = 1:

```<code>      \
  ___/->
,(___)"
 `` ``
</code>```

N = 2:

```<code>      \       \
  ___/o>  ___/->
-(___)" ,(___)"
 '' ''   `` ``
</code>```

N = 3:

```<code>      \       \       \
  ___/o>  ___/o>  ___/->
-(___)" -(___)" ,(___)"
 '' ''   '' ''   `` ``
</code>```

N = 4:

```<code>      \       \       \       \
  ___/o>  ___/o>  ___/o>  ___/->
-(___)" -(___)" -(___)" ,(___)"
 '' ''   '' ''   '' ''   `` ``
</code>```

Larger N should work just as well.

答:
Pyke, <s>56</s> 54 bytes

```<code>Fhqd6*"\
  ___/o>
-(___)
 '' ''"+23\":RI"-o'"",-`".:(P
</code>```

Try it here!

4 bytes too many because Pyke doesn't allow double quotes in strings :(

Title: Counting Goats to Sleep

Body:
Pyke, <s>56</s> 54 bytes

Fhqd6*"\
  ___/o>
-(___)
 '' ''"+23\":RI"-o'"",-`".:(P

Try it here!

4 bytes too many because Pyke doesn't allow double quotes in strings :(


问:
Sum or difference of two powers of two
Your challenge, should you choose to accept it, is, given an integer K >= 1, find non-negative integers A and B  such that at least one of the two conditions following hold:

K = 2^A + 2^B

K = 2^A - 2^B

If there does not exist such A and B, your program may behave in any fashion. (To clarify, A and B can be equal.)

Test cases

There are often multiple solutions to a number, but here are a few:

```<code>K => A, B
1 => 1, 0
15 => 4, 0                      ; 16 - 1 = 15
16 => 5, 4                      ; 32 - 16 = 16; also 3, 3: 8 + 8 = 16
40 => 5, 3                      ; 2^5 + 2^3 = 40
264 => 8, 3
17179867136 => 34, 11           ; 17179869184 - 2048 = 17179867136
</code>```

The last test case, 17179867136, must run in under 10 seconds on any relatively modern machine. This is a code golf, so the shortest program in bytes wins. You may use a full program or a function.

答:
JavaScript (ES6), 73 bytes

```<code>(n,[s,f,z]=/^1+(.*1)?(0*)$/.exec(n.toString(2)))=>[s.length-!!f,z.length]
</code>```

For the subtraction case, the first number is the number of digits in the binary representation and the second number is the number of trailing zeroes. For the addition case, we subtract 1 from the first number. If the binary representation is all 1s followed by some 0s then the addition case is assumed otherwise the subtraction case is assumed. 36-byte port of @xnor's version that only works for B≤30 in JavaScript:

```<code>n=>[(l=Math.log2)(n+(n&=-n))|0,l(n)]
</code>```

Title: Sum or difference of two powers of two

Body:
JavaScript (ES6), 73 bytes

(n,[s,f,z]=/^1+(.*1)?(0*)$/.exec(n.toString(2)))=>[s.length-!!f,z.length]

For the subtraction case, the first number is the number of digits in the binary representation and the second number is the number of trailing zeroes. For the addition case, we subtract 1 from the first number. If the binary representation is all 1s followed by some 0s then the addition case is assumed otherwise the subtraction case is assumed. 36-byte port of @xnor's version that only works for B≤30 in JavaScript:

n=>[(l=Math.log2)(n+(n&=-n))|0,l(n)]


问:
Esolang-Comment-Template-Generator
Lots of people on this site use esoteric languages, and since these languages are unusual and hard to understand, they will frequently write an explanation in a certain format. For example, if the code was

```<code>abcdefghijklmnop
</code>```

And this languages uses # for comments, they would write an explanation like this:

```<code>a                #Explanation of what 'a' does
 bc              #Bc
   d             #d
    e            #Explanation of e
     fgh         #foobar
        ij       #hello world
          k      #etc.
           l     #so on
            mn   #and
              op #so forth
</code>```

I frequently do this too, but every time I do this, I feel like creating the layout of text is really obnoxious and time-consuming. So I want you to create a "Esolang-Comment-Template-Generator" for me. For example, if we ignore the comments, the previous code has this template:

```<code>a                #
 bc              #
   d             #
    e            #
     fgh         #
        ij       #
          k      #
           l     #
            mn   #
              op #
</code>```

The Challenge:

You must write a program or function that takes two strings as input, and outputs this "Esolang-Comment-Template". The first input will be the code, but with bars (|) inserted where the newlines go. The second input is what we will use for comments. So our last example would have this for input:

```<code>"a|bc|d|e|fgh|ij|k|l|mn|op", "#"
</code>```

Unfortunately this excludes bars from being part of the code input, but that's OK. You can assume that the comment input will be a single character. For simplicity's sake, the comment char will not be a bar. The code input will only contain printable ASCII, and it will not contain any newlines.

Hopefully you can infer what to do from the testcases, but I'll try to clarify some things.

You must split the code input up into "code-sections" on every bar. Then, each section of code is output on its own line and left-padded with the length of all the previous code (not including the bars). Then, each line is right-padded with enough spaces so that the last two characters on every line are "One additional space" + "The comment character".

One trailing newline is allowed.

Here is another example. For the input

```<code>"Hello|World", "/"
</code>```

The first section of code is "Hello" and the second is "World". So it should give the output:

```<code>Hello      /
     World /
</code>```

Here are some more samples:

```<code>Input:
"a|b|c|d|e|f|g", ","

Output:
a       ,
 b      ,
  c     ,
   d    ,
    e   ,
     f  ,
      g ,

Input:
"abcdefg", ":"

Output:
abcdefg :

Input:
"4|8|15|16|23|42", "%"

Output:
4          %
 8         %
  15       %
    16     %
      23   %
        42 %

Input:
"E|ac|h s|ecti|on is| one c|haracte|r longer| than the| last!", "!"

Output:
E                                                   !
 ac                                                 !
   h s                                              !
      ecti                                          !
          on is                                     !
                one c                               !
                     haracte                        !
                            r longer                !
                                     than the       !
                                              last! !

Input:
"This|Code|has||empty||sections", "@"

Output:
This                     @
    Code                 @
        has              @
                         @
           empty         @
                         @
                sections @
</code>```

Rules:

You may take these inputs and outputs in any reasonable format. For example, reading/writing a file, STDIN/STOUT, function arguments/return value, etc. As usual, this is code-golf, so try to make your code as short as possible and you win if you can get the shortest solution in your language! I will also select the shortest solution as the overall winner. Standard loopholes are banned.

答:
Pyth - <s>28</s> <s>27</s> <s>24</s> 23 bytes

<s>Might be able to golf a little off.</s> A lot off, apparently!

```<code>jt+R+;zC.t.u+*lNdYcQ\|k
</code>```

Try it online here.

ContentLicense: CC BY-SA 4.0

Title: Esolang-Comment-Template-Generator

Body:
Pyth - <s>28</s> <s>27</s> <s>24</s> 23 bytes

<s>Might be able to golf a little off.</s> A lot off, apparently!

jt+R+;zC.t.u+*lNdYcQ\|k

Try it online here.


答:
Python 3, 316 bytes

```<code>from random import*
from collections import*
def d(s,f):
 D=defaultdict(Counter);p=q=''
 for w in open(f).read().split():D[w.translate({97+c:(c-(c>17)-(c>24))//3+50for c in range(26)})].update([w]);D[p].update([w]);p=w
 for c in s.split('0'):q=choice([*(len(D[c])>1and D[c]&D[q]or D[c]).elements()]);print(q,end=' ')
</code>```

Title: Marcel Proust and Markov decipher security service’s T9 texts

Body:
As if this challenge could be any more Pythonesque in spirit... No prior knowledge of Markov chains or encryption techniques is required.

You are a spy who needs to obtain some crucial information from the British security service M1S. The agents of M1S are well aware that their Wi-Fi signals can be intercepted, their Android/iOS security vulnerabilities exploited etc., so all of them are using Nokia 3310’s to transmit text information which is typed using the T9 auto-completion.

You had previously hacked the phones to be delivered to the intelligence agency and had installed keyloggers under their glorious plastic keyboards, so now you receive sequences of numbers corresponding to the letters they typed, so “the eagle has left the nest alert the agents” becomes

```<code>84303245304270533808430637802537808430243687
</code>```

But wait! Some T9 sequences are ambiguous (“6263” could be “name”, “mane” or “oboe”; the more obscure, the more suspicious it gets!), so what do you do? You know that the only entrance examination M1S uses is summarising Marcel Proust’s masterpiece “Remembrance of Things Past” in 15 seconds, so you want to pick the word that comes next after the previous one according to its frequency distribution in the entire chef-d’œuvre of Proust!

Can you crack the code and obtain what could be the original message?

The principle of T9

The T9 auto-completion mechanism can be described as follows. It maps alphabetic characters to numbers as shown on the picture above.

```<code>abc     -> 2
def     -> 3
ghi     -> 4
jkl     -> 5
mno     -> 6
pqrs    -> 7
tuv     -> 8
wxyz    -> 9
<space> -> 0
<other> -> <is deleted>
</code>```

The T9 decryptor receives a sequence of digits and tries to guess the word that could be typed with those keypresses. It might use a standard frequency table, but we are going one step further and predicting the next word using a Markov chain!

Learning sample

The corpus is this heavily stripped version of Proust’s “Remembrance of Things Past” (s/-/ /g, s/['’]s //g and s/[^a-zA-Z ]//g — begone confusing possessive 's!) originally published on the University of Adelaide website (the text of this work is in the Public Domain in Australia).

The whole text must be analysed as one string, as one long sentence, as one long vector of words (whichever is more convenient for your language), stripped of linebreaks, and split into words at spaces. (I do not supply a single-paragraph file because such might be frowned upon by github tools.)

How do I read the whole text as one string / sentence? An example in R:

```<code>p_raw  <- read.table("proust.txt", sep="\t") # Because there are no tabs
p_vec  <- as.character(p_raw$V1)       # Conversion to character vector
p_str  <- paste(p_vec, collapse=" ")   # One long string with spaces
p_spl  <- strsplit(p_str, split=" ")[[1]] # Vector of 1360883 words
proust <- p_spl[p_spl!=""]           # Remove empty entries — 1360797
</code>```

Task

Given a sequence of digits as a number, return a possible text string that could be typed using the corresponding T9 keys using a probabilty chain to predict the next word X based on this training text treated as one long sentence.

If X is the first T9-word of the text and there are multiple guesses, pick one at random, otherwise pick the only one possible.

For all subsequent T9-words X(i) preceded by a word already deciphered w(i-1):

If a T9-word X can be converted into a normal word x in one unique way, do it.

If there are multiple conversion options available for X, say x1, x2, ..., look up the preceding guessed word w.

If w is never followed by anything that maps to X in the original work of Proust, pick any of the possible x1, x2, ... at random.

If w X always corresponds to w x1 in the original and there are no concurrent xi’s that could be mapped into X, pick x1.

If w X can be converted to w x1, w x2, ... that can be found in the corpus, then count all possible xi’s that follow w and map to X in the corpus and pick xi with probability xi/(x1 + x2 + ...).

Example 2a. If the message is 76630489, where 489 could be guy or ivy (they occur in the corpus at least once), 7663 can be deciphered as some (a very probable first word). If some is never followed by anything that maps to 489 in the corpus, then pick guy or ivy at random with probability 0.5.

Example 2b. If the message is 766302277437, where 2277437 could be barrier or carrier, 7663 can be deciphered as some. If Proust always used some carrier and never some barrier, then pick some carrier.

Example 2c. Suppose that you want to decipher the sequence 536307663. 5363 was predicted as lend. 7663 could be any of these: pond, roof and some. You count the occurrences of the word following lend in the sample corpus. Suppose you get something like this (just to illustrate):

```<code>        T9  Word following lend  Occurrences
      7663  some                           7
      7663  pond                           2
      7663  roof                           1
</code>```

So if 7663 is preceded by lend, there is 7/(7+2+1)=70% probability that 7663 stands for some, 20% pond and 10% roof. Your algorithm should produce lend some in 70% cases, lend pond in 20% cases etc.

You may safely assume that the agents use only a-z letters and spaces (no punctuation marks, no possessive 's, and no numbers).

You may also assume that the agents of M1S never use any words outside the scope of “Remembrance of Things Past” (which is a whopping vocabulary of 29,237 words!).

The T9 fuctionality was implemented in this challenge, so you might have a look at it.

If you need any help, probabilistic chains were gloriously tamed in this, that and the following challenges, but you do not even need to know the principle of such chains: everything is stated in the task.

Test cases

```<code>--Inputs--
20784250276960369
20784250276960369
84303245304270533808430637802537808430243687
94280343084306289072908608430262780482737
94280343084306289072908608430262780482737

--Possible outputs--
c quick brown fox
a stick crown fox
the eagle gas left the nest blest vie agents
what did the navy pay to the coast guards
what did the navy raz un the coast guards
</code>```

Rules:

Standard loopholes apply.

You do not know the original message, all you get is a sequence of digits and the file proust.txt that you just need to load in the memory / workspace / whatever. There is no need to have anything self-contained; assume proust.txt is always accessible.

Your algorithm must be able to produce different outputs with respective probabilities if more than one decryption option is probable according to the corpus (see Example 2c).

You need to stay as discreet as possible, so the shortest code wins!

P.S. The obvious benefit of this probabilistic algorithm is the fact that the probability you will get a true original string for an ambiguous deciphered string tends to one — just wait...

P.P.S.  See also Prediction by Partial Matching.

Body:
Python 3, 316 bytes

from random import*
from collections import*
def d(s,f):
 D=defaultdict(Counter);p=q=''
 for w in open(f).read().split():D[w.translate({97+c:(c-(c>17)-(c>24))//3+50for c in range(26)})].update([w]);D[p].update([w]);p=w
 for c in s.split('0'):q=choice([*(len(D[c])>1and D[c]&D[q]or D[c]).elements()]);print(q,end=' ')


答:
Mathematica, <s>57</s> 54 bytes

Saved 3 bytes thanks to LegionMammal978!

```<code>Do[Abs[2^a-#]==2^b&&Print@{a,b},{a,2Log@#+1},{b,0,a}]&
</code>```

Actually prints out all1 appropriate pairs {a,b}. 2Log@#+1 is an upper bound for the largest a that can possibly appear when representing the input # (the tight upper bound is Log[2#]/Log[2] = 1.44... Log[#] + 1). Runs almost instantaneously on the test input, and in less than a quarter second (on my new but off-the-shelf computer) on 100-digit inputs.

1 Letting a start at the default value of 1 instead of 0 saves two bytes; it causes the output {0,0} to be missed when the input is 2, but finds the output {2,1} in that case, which is good enough.

Title: Sum or difference of two powers of two

Body:
Your challenge, should you choose to accept it, is, given an integer K >= 1, find non-negative integers A and B  such that at least one of the two conditions following hold:

K = 2^A + 2^B

K = 2^A - 2^B

If there does not exist such A and B, your program may behave in any fashion. (To clarify, A and B can be equal.)

Test cases

There are often multiple solutions to a number, but here are a few:

```<code>K => A, B
1 => 1, 0
15 => 4, 0                      ; 16 - 1 = 15
16 => 5, 4                      ; 32 - 16 = 16; also 3, 3: 8 + 8 = 16
40 => 5, 3                      ; 2^5 + 2^3 = 40
264 => 8, 3
17179867136 => 34, 11           ; 17179869184 - 2048 = 17179867136
</code>```

The last test case, 17179867136, must run in under 10 seconds on any relatively modern machine. This is a code golf, so the shortest program in bytes wins. You may use a full program or a function.

Body:
Mathematica, <s>57</s> 54 bytes

Saved 3 bytes thanks to LegionMammal978!

Do[Abs[2^a-#]==2^b&&Print@{a,b},{a,2Log@#+1},{b,0,a}]&

Actually prints out all1 appropriate pairs {a,b}. 2Log@#+1 is an upper bound for the largest a that can possibly appear when representing the input # (the tight upper bound is Log[2#]/Log[2] = 1.44... Log[#] + 1). Runs almost instantaneously on the test input, and in less than a quarter second (on my new but off-the-shelf computer) on 100-digit inputs.

1 Letting a start at the default value of 1 instead of 0 saves two bytes; it causes the output {0,0} to be missed when the input is 2, but finds the output {2,1} in that case, which is good enough.


答:
Perl, <s>52</s> <s>49</s> 32 bytes

Old solution (49 bytes)

Includes +1 for -p

Give input on STDIN:

```<code>pow2.pl <<< 17179867136
</code>```

pow2.pl

```<code>#!/usr/bin/perl -p
$_=reverse sprintf"%b",$_;/()1(?:1+|0*)/;$_="@+"
</code>```

However, using xnor's algorithm and adding a twist gives 32 bytes:

```<code>perl -nE 'say 13/9*log|0for$;=$_&-$_,$_+$'
</code>```

Just the code:

```<code>say 13/9*log|0for$;=$_&-$_,$_+$
</code>```

This suffers from severe rounding error because 13/9 = 1.444... is quite a bit above 1/log 2 = 1.44269... (log itself also has a rounding error but that is so much smaller that we can wrap it up in the analysis of 13/9). But since any 2**big - 2** small gets corrected to 2** big before the log this doesn't mater and the calculation for 2**big + 2 * 2**small gets truncated  down so is also safe..
And at the other side of the range 2**n+2**(n-1) doesn't get increased enough in the range [0,64] (I can't properly support more than the integer range anyways due to the use of &) to lead to a wrong result (multiplicator 1.5 however would be too far off for large numbers).

Title: Sum or difference of two powers of two

Body:
Perl, <s>52</s> <s>49</s> 32 bytes

Old solution (49 bytes)

Includes +1 for -p

Give input on STDIN:

pow2.pl <<< 17179867136

pow2.pl

#!/usr/bin/perl -p
$_=reverse sprintf"%b",$_;/()1(?:1+|0*)/;$_="@+"

However, using xnor's algorithm and adding a twist gives 32 bytes:

perl -nE 'say 13/9*log|0for$;=$_&-$_,$_+$'

Just the code:

say 13/9*log|0for$;=$_&-$_,$_+$

This suffers from severe rounding error because 13/9 = 1.444... is quite a bit above 1/log 2 = 1.44269... (log itself also has a rounding error but that is so much smaller that we can wrap it up in the analysis of 13/9). But since any 2**big - 2** small gets corrected to 2** big before the log this doesn't mater and the calculation for 2**big + 2 * 2**small gets truncated  down so is also safe..
And at the other side of the range 2**n+2**(n-1) doesn't get increased enough in the range [0,64] (I can't properly support more than the integer range anyways due to the use of &) to lead to a wrong result (multiplicator 1.5 however would be too far off for large numbers).


答:
Brachylog, 23 bytes

```<code>,A:B#+.:2rz:^a{+|-}?,.=
</code>```

Try it online!

This is much faster than required, e.g. this is still under 10 seconds on TIO.

Explanation

This is basically a direct transcription of the formula with no optimization:

```<code>,A:B     The list [A, B]
#+       Both A and B are greater than or equal to 0
.        Output = [A, B]
:2rz     The list [[2, A], [2, B]]
:^a      The list [2^A, 2^B]
{+|-}?   2^A + 2^B = Input OR 2^A - 2^B = Input
,.=      Assign a value to A and B which satisfy those constraints
</code>```

Title: Sum or difference of two powers of two

Body:
Brachylog, 23 bytes

,A:B#+.:2rz:^a{+|-}?,.=

Try it online!

This is much faster than required, e.g. <a href="http://brachylog.tryitonline.net/#code=LEE6QiMrLjoycno6XmF7K3wtfT8sLj0&input=NDQ4NDg4NTUyODQxNTA1NjczNTI4NDUwNDY5MjEwMDMyMDI1MDA4NzE3ODUyMzc4Mzk2NTYyNjg2NTc5MTk0MDcyNTY0OTQ1ODU2Mzk0NjUzODUwMjU3NjExODQyMzg1MjYxNjg2ODkyOTU0OTM3MTA0NDc3NjQ1ODc3NzgwODQ0MDg3MTMwOTg4ODM4MjU0NDM2MDAyNTk4OTAwNTQzNDc2NTIwMDk4ODc2MDkzNzUyNjkwNTQzNTQ3ODEyNjc1Mjc5MDE5MjQ2MDU0OTM1NDkzMTQzNjc4MTg1NDA0ODY4NzA0NTQ2NjY5MjA3MTMyOTcwNTcxNjk1MTk4ODQ3NjQyODA1MzIxODcwMzQ3NDM5OTU5Mzk2OTY2MDYxMTMxMDAwNjQxNDkyMDcxNjEyMDM2NTAwNjU5ODAwNzIwNTQxMDM3NTA5Mjk0ODYyNTMwOTE0MjkyNTgxNzc2NDcwNzA0ODAwNzkxODYyMTM1MjU3MTUwNDc2NTk0MjY2NTQ3OTczNzk1OTQyNDUyNjY5MjA3ODM4Mjc3MzI1NzY3MjU4MzA4Njc4ODI3NTcxODkwNzg5Njg2OTI2NDk3MDc2MzMxNTk5MzUxMTgwMDQ2NTY0NjY3ODAzODQyMTQ3MTU2NDAyOTY5MDcwMTQ1Mzc3NDYzMjEzODg4MjA0Nzg3NDM2NDI5NzQ4MTU3MzgwODYyNzcyNDMxODMwNTM0NjAzMTU0MDYwNzc0MTI4Nzc1ODM4NDk0NDA4ODgyOTQ4NDQ1NDI4NzYyMzg1NzQyNzA4MzE1NTIxMDI0&args=Wg&debug=on" rel="noreferrer">this is still under 10 seconds on TIO.

Explanation

This is basically a direct transcription of the formula with no optimization:

,A:B     The list [A, B]
#+       Both A and B are greater than or equal to 0
.        Output = [A, B]
:2rz     The list [[2, A], [2, B]]
:^a      The list [2^A, 2^B]
{+|-}?   2^A + 2^B = Input OR 2^A - 2^B = Input
,.=      Assign a value to A and B which satisfy those constraints


问:
The Letter A without A
Your task is to display the letter "A" alone, without anything else, except any form of trailing newlines if you cannot avoid them, doing so in a program and/or snippet. Code that returns (instead of printing) is allowed.

Both the lowercase and uppercase versions of the letter "A" are acceptable (that is, unicode U+0061 or unicode U+0041. Other character encodings that aren't Unicode are allowed, but either way, the resulting output of your code must be the latin letter "A", and not any lookalikes or homoglyphs)

You must not use any of the below characters in your code, regardless of the character encoding that you pick:

"A", whether uppercase or lowercase.

"U", whether lowercase or uppercase.

X, whether uppercase or lowercase.

+

&

#

0

1

4

5

6

7

9

Cheating, loopholes, etc, are not allowed.

Since this is code-golf, the shortest solution, in bytes, that follows all the rules, is the winner.

Validity Checker

This Stack Snippet checks to make sure your code doesn't use the restricted characters. It might not work properly for some character encodings.

var t = prompt("Input your code.");

if (/[AaUuXx+&#0145679]/.test(t)) {
  alert("Contains a disallowed character!");
} else {
  alert("No disallowed characters");
}```
</div>
</div>
</p>

<p><em>This Stack Snippet that makes sure you don't have a disallowed character is also available on JSFiddle.</em></p>

<h3>Leaderboard</h3>

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

body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td>Link</td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td>Link</td></tr></tbody> </table></code>```

Title: The Letter A without A

Body:
Woefully, 400 bytes

| || |
|| |
||| |
|||| |
||||| |
|||||| |
||||||| |
|||||| |
||||| |
|||| |
||| |
|| |
| |
| |
| |
| |
| |
| |
|| |
|| |
|| |
|| |
|| |
|| |
||| |
||| |
||| |
||| |
||| |
|||| |
|||| |
|||| |
|||| |
|||| |
||| |
|| |
| |
|| |
|| |
|| |
||| |
|| |
| |
| |
| |
| |
|| |
|| |
|| |
||| |
||| |
||| |
||| |
|||| |
|||| |
||||| |
|||| |
||| |
|| |
| |
|| |
||| |
|| |
||| |
|||| |
||||| |
|||||| |
||||||| |

Can probably be golfed more


答:
Python, 69 bytes

def f(k):b=bin(k)[::-1];return len(b)-2-(b.count('1')==2),b.find('1')
```

Tests are on ideone

Since non-valid input can do anything, we know that if the input has exactly 2 bits set it is the sum of those 2 powers of 2, and otherwise (if valid) it will be be a run of some number of bits (including the possibility of just 1 bit) and will be the difference between the next highest power of 2 than the MSB and the LSB set.

Title: Sum or difference of two powers of two

Body:
Python, 69 bytes

def f(k):b=bin(k)[::-1];return len(b)-2-(b.count('1')==2),b.find('1')

Tests are on ideone

Since non-valid input can do anything, we know that if the input has exactly 2 bits set it is the sum of those 2 powers of 2, and otherwise (if valid) it will be be a run of some number of bits (including the possibility of just 1 bit) and will be the difference between the next highest power of 2 than the MSB and the LSB set.


问:
Golf you a quine for great good!
Using your language of choice, golf a quine.

A quine is a non-empty computer program which takes no input and produces a copy of its own source code as its only output.

No cheating -- that means that you can't just read the source file and print it. Also, in many languages, an empty file is also a quine: that isn't considered a legit quine either.

No error quines -- there is already a separate challenge for error quines.

Points for:

Smallest code (in bytes)

Most obfuscated/obscure solution

Using esoteric/obscure languages

Successfully using languages that are difficult to golf in

The following Stack Snippet can be used to get a quick view of the current score in each language, and thus to know which languages have existing answers and what sort of target you have to beat:

var QUESTION_ID=69;
var OVERRIDE_USER=98;

var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";var COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk";var answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;function answersUrl(index){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+index+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}
function commentUrl(index,answers){return"https://api.stackexchange.com/2.2/answers/"+answers.join(';')+"/comments?page="+index+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}
function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(data){answers.push.apply(answers,data.items);answers_hash=[];answer_ids=[];data.items.forEach(function(a){a.comments=[];var id=+a.share_link.match(/\d+/);answer_ids.push(id);answers_hash[id]=a});if(!data.has_more)more_answers=!1;comment_page=1;getComments()}})}
function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(data){data.items.forEach(function(c){if(c.owner.user_id===OVERRIDE_USER)
answers_hash[c.post_id].comments.push(c)});if(data.has_more)getComments();else if(more_answers)getAnswers();else process()}})}
getAnswers();var SCORE_REG=(function(){var headerTag=String.raw `h\d`
var score=String.raw `\-?\d+\.?\d*`
var normalText=String.raw `[^\n<>]*`
var strikethrough=String.raw `<s>${normalText}</s>|<strike>${normalText}</strike>|<del>${normalText}</del>`
var noDigitText=String.raw `[^\n\d<>]*`
var htmlTag=String.raw `<[^\n<>]+>`
return new RegExp(String.raw `<${headerTag}>`+String.raw `\s*([^\n,]*[^\s,]),.*?`+String.raw `(${score})`+String.raw `(?=`+String.raw `${noDigitText}`+String.raw `(?:(?:${strikethrough}|${htmlTag})${noDigitText})*`+String.raw `</${headerTag}>`+String.raw `)`)})();var OVERRIDE_REG=/^Override\s*header:\s*/i;function getAuthorName(a){return a.owner.display_name}
function process(){var valid=[];answers.forEach(function(a){var body=a.body;a.comments.forEach(function(c){if(OVERRIDE_REG.test(c.body))
body='
'+c.body.replace(OVERRIDE_REG,'')+'
'});var match=body.match(SCORE_REG);if(match)
valid.push({user:getAuthorName(a),size:+match[2],language:match[1],link:a.share_link,})});valid.sort(function(a,b){var aB=a.size,bB=b.size;return aB-bB});var languages={};var place=1;var lastSize=null;var lastPlace=1;valid.forEach(function(a){if(a.size!=lastSize)
lastPlace=place;lastSize=a.size;++place;var answer=jQuery("#answer-template").html();answer=answer.replace("{{PLACE}}",lastPlace+".").replace("{{NAME}}",a.user).replace("{{LANGUAGE}}",a.language).replace("{{SIZE}}",a.size).replace("{{LINK}}",a.link);answer=jQuery(answer);jQuery("#answers").append(answer);var lang=a.language;lang=jQuery(''+a.language+'').text().toLowerCase();languages[lang]=languages[lang]||{lang:a.language,user:a.user,size:a.size,link:a.link,uniq:lang}});var langs=[];for(var lang in languages)
if(languages.hasOwnProperty(lang))
langs.push(languages[lang]);langs.sort(function(a,b){if(a.uniq>b.uniq)return 1;if(a.uniq<b.uniq)return-1;return 0});for(var i=0;i<langs.length;++i)
{var language=jQuery("#language-template").html();var lang=langs[i];language=language.replace("{{LANGUAGE}}",lang.lang).replace("{{NAME}}",lang.user).replace("{{SIZE}}",lang.size).replace("{{LINK}}",lang.link);language=jQuery(language);jQuery("#languages").append(language)}}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{text-align:left!important}#answer-list{padding:10px;float:left}#language-list{padding:10px;float:left}table thead{font-weight:700}table td{padding:5px}</code>```

  <link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Sites/codegolf/primary.css?v=f52df912b654">

Winners by Language

Language	User	Score

Leaderboard

	Author	Language	Size

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}

{{LANGUAGE}}	{{NAME}}	{{SIZE}}

 ```

答:
Straw, 10 bytes (non-competing)

```<code>(:%>>):%>>
</code>```

Title: Golf you a quine for great good!

Body:
Straw, 10 bytes (non-competing)

(:%>>):%>>


问:
My Squiggly Lamp
While moving, I broke my lamp. Now, I need a new one. It's your job to make me a lamp! I'm not sure what size I want, though I know I want a squiggly one.

Your program/function must take in a number input, and print out a lamp with that many squiggles/bumps.

Examples:

Input:2

Output:

```
/--\
 ()
 ()
/__\
```

Input:3

Output:

```
/--\
 ()
 ()
 ()
/__\
```

Input:5

Output:

```
/--\
 ()
 ()
 ()
 ()
 ()
/__\
```

Rules:

0 & negative numbers don't matter

To give the lamps (an this challenge) more of a variety, you must change the lamp shade.

They must be 4 characters wide and 1 character high.

They can be in any shape, including non-lamp-shade shapes.

They must not contain whitespace.

The base must stay the same.

You must show an example input & output with your lamp shade.

Shortest code wins!

Title: My Squiggly Lamp

Body:
Ruby, 42 bytes

i=gets.to_i
puts "|--|\n#{" ()\n"*i}/__\\"


答:
Python 2, 43 bytes

lambda n:[len(bin((n&-n)+k))-3for k in n,0]
```

Say that n==2^a ± 2^b with a>b. Then, the greatest power-of-2 factor of n is 2^b, and we can find it using the bit-trick 2^b = n&-n. That lets us compute 2^b + n, which equals either 2^a + 2 * 2^b or just 2^a. Either one has the same-length bit-length as a*. So, we output the bit-lengths of n&-n and (n&-n)+n, computed from the lengths of their binary representations. Python 3 is one byte longer for parens in for k in(n,0)].

*Except that 2^a + 2^b with a==b+1 has one longer bit-length, but that's fine because we can interpret that as 2^(a+1)-2^b.

Title: Sum or difference of two powers of two

Body:
Python 2, 43 bytes

lambda n:[len(bin((n&-n)+k))-3for k in n,0]

Say that n==2^a ± 2^b with a>b. Then, the greatest power-of-2 factor of n is 2^b, and we can find it using the bit-trick 2^b = n&-n. That lets us compute 2^b + n, which equals either 2^a + 2 * 2^b or just 2^a. Either one has the same-length bit-length as a*. So, we output the bit-lengths of n&-n and (n&-n)+n, computed from the lengths of their binary representations. Python 3 is one byte longer for parens in for k in(n,0)].

*Except that 2^a + 2^b with a==b+1 has one longer bit-length, but that's fine because we can interpret that as 2^(a+1)-2^b.


答:
JAVA 7 ,142 ,140, 134 BYTES

This is my first post on PPCG!I would really appreciate for feedback on golfing tips

Thanks to frozen for saving 2 bytes

```<code>void f(long n){for(int i=-1,j;i++<31;)for(j=0;j++<34;){long a=1,x=a<<i,y=a<<j;if(x+y==n|y-x==n){System.out.println(j+" "+i);return;}}}
</code>```

UNGOLF

```<code>void f(long n){
    for(int i=-1,j;i++<31;)
         for(j=0;j++<34;){
          long a=1,x=a<<i,y=a<<j;
            if(x+y==n|y-x==n){
            System.out.println(j+" "+i);
        return;
        }
            }
    }
</code>```

ideone

Title: Sum or difference of two powers of two

Body:
JAVA 7 ,142 ,140, 134 BYTES

This is my first post on PPCG!I would really appreciate for feedback on golfing tips

Thanks to frozen for saving 2 bytes

void f(long n){for(int i=-1,j;i++<31;)for(j=0;j++<34;){long a=1,x=a<<i,y=a<<j;if(x+y==n|y-x==n){System.out.println(j+" "+i);return;}}}

UNGOLF

void f(long n){
    for(int i=-1,j;i++<31;)
         for(j=0;j++<34;){
          long a=1,x=a<<i,y=a<<j;
            if(x+y==n|y-x==n){
            System.out.println(j+" "+i);
        return;
        }
            }
    }

ideone


答:
MATL, <s>23</s> 22 bytes

```<code>BnQ:qWtG-|ym)1)tG-|hZl
</code>```

Try it online! Or verify all test cases.

Explanation

```<code>B      % Implicit input. Convert to binary. Gives n digits
nQ:q   % Range [1 ... n+1]
W      % 2 raised to that, element-wise: gives [1 2 4 ... 2^(n+1)] (*)
tG-|   % Duplicate. Absolute difference with input, element-wise (**)
y      % Push a copy of (*)
m      % True for elements of (**) that are members of (*)
)      % Use as logical index to select elements from (*)
1)     % Take the first element. Gives power of the first result
tG-|   % Duplicate. Absolute difference with input. Gives power of the second result
hZl    % Concatenate. Take binary logarithm. Implicit display
</code>```

Title: Sum or difference of two powers of two

Body:
MATL, <s>23</s> 22 bytes

BnQ:qWtG-|ym)1)tG-|hZl

Try it online! Or verify all test cases.

Explanation

B      % Implicit input. Convert to binary. Gives n digits
nQ:q   % Range [1 ... n+1]
W      % 2 raised to that, element-wise: gives [1 2 4 ... 2^(n+1)] (*)
tG-|   % Duplicate. Absolute difference with input, element-wise (**)
y      % Push a copy of (*)
m      % True for elements of (**) that are members of (*)
)      % Use as logical index to select elements from (*)
1)     % Take the first element. Gives power of the first result
tG-|   % Duplicate. Absolute difference with input. Gives power of the second result
hZl    % Concatenate. Take binary logarithm. Implicit display


答:
Jelly, <s>11</s> 10 bytes

```<code>;0+N&$BL€’
</code>```

Applying the bit twiddling trick from the Python answer by @xnor

Test it at TryItOnline

All test cases are also at TryItOnline

How?

```<code>;0+N&$BL€’ - main link takes an argument, k, e.g 15
;0         - concatenate k with 0, e.g. [15, 0]
     $     - last two links as a monad
   N       - negate, e.g. -15
    &      - bitwise and, e.g. -15&15=1 since these two are called as a monad (one input)
  +        - add, vectorises, e.g. [16,1]
      B    - convert to binary, vectorises, e.g. [[1,0,0,0,0],[1]]
       L€  - length for each, e.g. [5,1]
         ’ - decrement, vectorises, e.g. [4,0]
</code>```

Title: Sum or difference of two powers of two

Body:
Jelly, <s>11</s> 10 bytes

;0+N&$BL€’

Applying the bit twiddling trick from the Python answer by @xnor

Test it at TryItOnline

All test cases are also at TryItOnline

How?

;0+N&$BL€’ - main link takes an argument, k, e.g 15
;0         - concatenate k with 0, e.g. [15, 0]
     $     - last two links as a monad
   N       - negate, e.g. -15
    &      - bitwise and, e.g. -15&15=1 since these two are called as a monad (one input)
  +        - add, vectorises, e.g. [16,1]
      B    - convert to binary, vectorises, e.g. [[1,0,0,0,0],[1]]
       L€  - length for each, e.g. [5,1]
         ’ - decrement, vectorises, e.g. [4,0]


答:
Bash + GNU Coreutils, <s>165</s> 155 bytes

```<code>a=" \
>o/___
 \")___(-
  '' '' "
eval paste -d \'\' $(seq $1|while read;do
printf '<(echo "$a") '
done) | sed "s/-/,/;s/o/-/;s/'' ''/"'`` ``/'|rev
</code>```

Run with:

```<code>bash my_pgm.bash N
</code>```

Basically the program prints N times of the same goat (reversed), and substitutes the first -, for ,, the first o for - and the first '' '' for the backticks. Then reverses the lines.

Title: Counting Goats to Sleep

Body:
Some people count sheep to get to sleep. Others count goats.

Write a program or function that takes in a positive integer N and outputs N-1 awake goats followed by one sleeping goat, as if someone was counting N goats and at the very last one they fell asleep.

Awake goats look like this:

```<code>      \
  ___/o>
-(___)"
 '' ''
</code>```

Sleeping goats look like this:

```<code>      \
  ___/->
,(___)"
 `` ``
</code>```

They are chained together with a single space between beard and tail of adjacent goats:

```<code>      \       \       \
  ___/o>  ___/o>  ___/->
-(___)" -(___)" ,(___)"
 '' ''   '' ''   `` ``
</code>```

The output is allowed to have trailing spaces and a single trailing newline.

The shortest code in bytes wins.

Examples

N = 1:

```<code>      \
  ___/->
,(___)"
 `` ``
</code>```

N = 2:

```<code>      \       \
  ___/o>  ___/->
-(___)" ,(___)"
 '' ''   `` ``
</code>```

N = 3:

```<code>      \       \       \
  ___/o>  ___/o>  ___/->
-(___)" -(___)" ,(___)"
 '' ''   '' ''   `` ``
</code>```

N = 4:

```<code>      \       \       \       \
  ___/o>  ___/o>  ___/o>  ___/->
-(___)" -(___)" -(___)" ,(___)"
 '' ''   '' ''   '' ''   `` ``
</code>```

Larger N should work just as well.

Body:
Bash + GNU Coreutils, <s>165</s> 155 bytes

a=" \
>o/___
 \")___(-
  '' '' "
eval paste -d \'\' $(seq $1|while read;do
printf '<(echo "$a") '
done) | sed "s/-/,/;s/o/-/;s/'' ''/"'`` ``/'|rev

Run with:

bash my_pgm.bash N

Basically the program prints N times of the same goat (reversed), and substitutes the first -, for ,, the first o for - and the first '' '' for the backticks. Then reverses the lines.


问:
Print 1 to 1000 in C++ without semi-colons
Following this popular question, present your solution which prints the numbers 1 to 1000 (all of them, not the string "1 to 1000" verbatim or something funny) in C++ without using any semi-colons. Unlike the original question, you may use conditionals and loops.

Solutions not requiring any compiler flags are preferred. Please mention any you use if you go against this. Undefined behaviour is allowed, so please specify the compiler and version you're using. Preference will be given to clever solutions. This is not a shortest code contest.

(I have a solution, which I'll post in 24 hours if a similar solution isn't posted before then.)

答:
This works great on my Linux machine:

```<code>#include <cstdlib>

int main()
{
    if (system("seq 1 1000")){}
}
</code>```

I know, I know, ...it's not portable.

Body:
This works great on my Linux machine:

#include <cstdlib>

int main()
{
    if (system("seq 1 1000")){}
}

I know, I know, ...it's not portable.


问:
Simulate a Rubik's cube
A Rubik's cube has 6 colors: red, orange, yellow, white, blue, and green. Red and orange, yellow and white, and blue and green faces are on opposite sides.

Net of a solved Rubik's cube looks like this:

```<code> Y
BRGO
 W
</code>```

And the tiles look like this:

```<code>      Y Y Y
      Y Y Y
      Y Y Y
B B B R R R G G G O O O
B B B R R R G G G O O O
B B B R R R G G G O O O
      W W W
      W W W
      W W W
</code>```

Challenge

Given rotations, reversed rotations, or double rotations output what a solved cube will transform to, as ASCII art or as an image (whitespaces aren't necessary, may or may not exist, trailing whitespaces are allowed.).

Input will be rotation (and optional modifier). Rotation notation goes like: U(p), L(eft), F(ront), R(ight), B(ack), D(own); 2 (double), ' or i (inverse).

All normal rotations will be 90° clockwise, inverse ones will be counterclockwise.

Explanation about clockwiseness: Imagine the cube as you're looking at the red face, and the yellow face is at the top. Then rotate the cube so that the face that the program will rotate will face you. This is the way clockwiseness will work. (Except back face, you will rotate the cube horizontally in that case.)

Input

Input will be a list of moves.

Output

An ASCII art that represents the cube or an image of the net of the cube.

Examples

Input:  (empty)

Output:

```<code>      Y Y Y
      Y Y Y
      Y Y Y
B B B R R R G G G O O O
B B B R R R G G G O O O
B B B R R R G G G O O O
      W W W
      W W W
      W W W
</code>```

Input: U (up)

Output:

```<code>      Y Y Y
      Y Y Y
      Y Y Y
R R R G G G O O O B B B
B B B R R R G G G O O O
B B B R R R G G G O O O
      W W W
      W W W
      W W W
</code>```

Input: U' or Ui (inverse up)

Output:

```<code>      Y Y Y
      Y Y Y
      Y Y Y
O O O B B B R R R G G G
B B B R R R G G G O O O
B B B R R R G G G O O O
      W W W
      W W W
      W W W
</code>```

Input: U2 (double up)

Output:

```<code>      Y Y Y
      Y Y Y
      Y Y Y
G G G O O O B B B R R R
B B B R R R G G G O O O
B B B R R R G G G O O O
      W W W
      W W W
      W W W
</code>```

Input: L' (inversed left)

Output:

```<code>      R Y Y
      R Y Y
      R Y Y
B B B W R R G G G O O Y
B B B W R R G G G O O Y
B B B W R R G G G O O Y
      O W W
      O W W
      O W W
</code>```

Input: R (right)

Output:

```<code>      Y Y R
      Y Y R
      Y Y R
B B B R R W G G G Y O O
B B B R R W G G G Y O O
B B B R R W G G G Y O O
      W W O
      W W O
      W W O
</code>```

Input: U2 L' D (double up, inverse left, down)

Output:

```<code>      O Y Y
      R Y Y
      R Y Y
G B B W O O B B B R R Y
G B B W R R G G G O O Y
O O Y G B B W R R G G G
      R O O
      W W W
      W W W
</code>```

Rules

No loopholes allowed.

This is code-golf, so shortest code in bytes solving the problem wins.

答:
Ruby, <s>370 339</s> 305 bytes

Latest edit: a few bytes saved by rearrangement of the plotting formulas and removal of unnecessary brackets. A massive saving by rewriting the generation of the cube - I never knew Ruby had a builtin for Cartesian Products!

```<code>->s{q=[-66,0,71].product [-87,0,89],[-79,0,82]
s.map{|c|m="LDBRUF".index c[0];e=m/3*2-1
c.sub(/[i']/,"33").chars{q.map{|j|j[m%=3]*e>0&&(j[m-2],j[m-1]=j[m-1]*e,-j[m-2]*e)}}}
t=[" "*12]*9*$/
q.map{|r|a,b,c=r.map{|i|i<=>0}
3.times{|i|r[i]!=0&&t[56+[a*3-a*c-d=b*13,a-d*3+d*c,3-d-c*3+c*a][i]]=r[i].abs.chr}}
t}
</code>```

Anonymous function.

Accepts an array of strings, each representing one face turn (a single string with spaces between each face turn is an additional 6 bytes.)

Returns a 9x12 rectangular string.

Brief explanation

This is closely based on a concept from my answer to this question, which in turn was based on a similar concept by Jan Dvorak.

The first line generates a 27 element array, representing the 27 cubies. Each cubie is represented by a 3 dimensional vector in which the sign represents its current position and the magnitude of each coordinate represents the ascii code for the colour of the sticker.

Example move: for R, for each cubie check if the x coordinate is >0 and if so rotate 90 degrees by swapping the y and z coordinates and swapping the sign of one of them.

Take a 9x12 array of spaces and plot the cube into it. For each cubie and axis we check if the sticker exists (coordinate in that axis nonzero), and work out where it is to go. Then we take the coordinate and perform .abs.chr to change the number into the required character and plot it.

Ungolfed in test program (per 339 byte edit)

```<code>f=->s{

  q=(0..26).map{|i|                         #Build an array of 27 cubies
    [[-66,0,71][i%3],                       #x coordinate B.G
     [-87,0,89][i/3%3],                     #y coordinate Y.W
     [-79,0,82][i/9]]                       #z coordinate O.R
  }

  s.map{|c|                                 #For each move in the input array
    m="LDBRUF".index(c[0]);e=m/3*2-1        #m=face to move. e=-1 for LDB, +1 for RUF.
    c.sub(/[i']/,"33").chars{               #Substitute "i" and "'" for "33" so chars in string = clockwise 1/4 turns required. For each char...
      q.map{|j|j[m%=3]*e>0&&                #...and each cubie, m%3 tells the relevant axis. if coordinate*e>1 rotate the cubie 1/4 turn.
        (j[m-2],j[m-1]=j[m-1]*e,-j[m-2]*e)} #Swap other two axes and change sign of one. e performs sign change if necessary for LDB.
    }
  }

  t=[" "*12]*9*$/                           #Make an array of 9 strings of 12 spaces, then make a single string by joining them with newlines
  q.map{|r|                                 #For each cubie
    a,b,c=r.map{|i|i<=>0}                   #make a normalised (-1,0,1) copy of each coordinate.
    d=b*13                                  #13 chars per line, d will be useful for plotting to the correct line of the output.
    3.times{|i|                             #For each of the 3 coordinates of the cubie
      r[i]!=0&&                             #if zero, sticker doesn't exist (edges and centres have <3 stickers.) If not zero plot the sticker.
      t[[56-d+a*3-a*c,                      #Calculate position on plot for x (L/R faces),
         56-d*3+d*c+a,                      #Calculate position on plot for y (D/U faces),
         59-d-c*3+c*a][i]]=                 #Calculate position on plot for z (B/F faces). Select the correct axis.
      r[i].abs.chr                          #Convert the coordinate to a character and assign to the correct space on the output plot.
    }
  }
t}                                          #Return the output string.

puts f[gets.chomp.split]
</code>```

Output

```<code>Checkerboard
U2 D2 F2 B2 L2 R2
   YWY
   WYW
   YWY
BGBRORGBGORO
GBGOROBGBROR
BGBRORGBGORO
   WYW
   YWY
   WYW

6-spot
U D' R L' F B' U D'
   RRR
   RYR
   RRR
WWWGGGYYYBBB
WBWGRGYGYBOB
WWWGGGYYYBBB
   OOO
   OWO
   OOO

Testcase
U2 L' D
   OYY
   RYY
   RYY
GBBWOOBBBRRY
GBBWRRGGGOOY
OOYGBBWRRGGG
   ROO
   WWW
   WWW
</code>```

Title: Simulate a Rubik's cube

Body:
Ruby, <s>370 339</s> 305 bytes

Latest edit: a few bytes saved by rearrangement of the plotting formulas and removal of unnecessary brackets. A massive saving by rewriting the generation of the cube - I never knew Ruby had a builtin for Cartesian Products!

->s{q=[-66,0,71].product [-87,0,89],[-79,0,82]
s.map{|c|m="LDBRUF".index c[0];e=m/3*2-1
c.sub(/[i']/,"33").chars{q.map{|j|j[m%=3]*e>0&&(j[m-2],j[m-1]=j[m-1]*e,-j[m-2]*e)}}}
t=[" "*12]*9*$/
q.map{|r|a,b,c=r.map{|i|i<=>0}
3.times{|i|r[i]!=0&&t[56+[a*3-a*c-d=b*13,a-d*3+d*c,3-d-c*3+c*a][i]]=r[i].abs.chr}}
t}

Anonymous function.

Accepts an array of strings, each representing one face turn (a single string with spaces between each face turn is an additional 6 bytes.)

Returns a 9x12 rectangular string.

Brief explanation

This is closely based on a concept from my answer to this question, which in turn was based on a similar concept by Jan Dvorak.

The first line generates a 27 element array, representing the 27 cubies. Each cubie is represented by a 3 dimensional vector in which the sign represents its current position and the magnitude of each coordinate represents the ascii code for the colour of the sticker.

Example move: for R, for each cubie check if the x coordinate is >0 and if so rotate 90 degrees by swapping the y and z coordinates and swapping the sign of one of them.

Take a 9x12 array of spaces and plot the cube into it. For each cubie and axis we check if the sticker exists (coordinate in that axis nonzero), and work out where it is to go. Then we take the coordinate and perform .abs.chr to change the number into the required character and plot it.

Ungolfed in test program (per 339 byte edit)

f=->s{

  q=(0..26).map{|i|                         #Build an array of 27 cubies
    [[-66,0,71][i%3],                       #x coordinate B.G
     [-87,0,89][i/3%3],                     #y coordinate Y.W
     [-79,0,82][i/9]]                       #z coordinate O.R
  }

  s.map{|c|                                 #For each move in the input array
    m="LDBRUF".index(c[0]);e=m/3*2-1        #m=face to move. e=-1 for LDB, +1 for RUF.
    c.sub(/[i']/,"33").chars{               #Substitute "i" and "'" for "33" so chars in string = clockwise 1/4 turns required. For each char...
      q.map{|j|j[m%=3]*e>0&&                #...and each cubie, m%3 tells the relevant axis. if coordinate*e>1 rotate the cubie 1/4 turn.
        (j[m-2],j[m-1]=j[m-1]*e,-j[m-2]*e)} #Swap other two axes and change sign of one. e performs sign change if necessary for LDB.
    }
  }

  t=[" "*12]*9*$/                           #Make an array of 9 strings of 12 spaces, then make a single string by joining them with newlines
  q.map{|r|                                 #For each cubie
    a,b,c=r.map{|i|i<=>0}                   #make a normalised (-1,0,1) copy of each coordinate.
    d=b*13                                  #13 chars per line, d will be useful for plotting to the correct line of the output.
    3.times{|i|                             #For each of the 3 coordinates of the cubie
      r[i]!=0&&                             #if zero, sticker doesn't exist (edges and centres have <3 stickers.) If not zero plot the sticker.
      t[[56-d+a*3-a*c,                      #Calculate position on plot for x (L/R faces),
         56-d*3+d*c+a,                      #Calculate position on plot for y (D/U faces),
         59-d-c*3+c*a][i]]=                 #Calculate position on plot for z (B/F faces). Select the correct axis.
      r[i].abs.chr                          #Convert the coordinate to a character and assign to the correct space on the output plot.
    }
  }
t}                                          #Return the output string.

puts f[gets.chomp.split]

Output

Checkerboard
U2 D2 F2 B2 L2 R2
   YWY
   WYW
   YWY
BGBRORGBGORO
GBGOROBGBROR
BGBRORGBGORO
   WYW
   YWY
   WYW

6-spot
U D' R L' F B' U D'
   RRR
   RYR
   RRR
WWWGGGYYYBBB
WBWGRGYGYBOB
WWWGGGYYYBBB
   OOO
   OWO
   OOO

Testcase
U2 L' D
   OYY
   RYY
   RYY
GBBWOOBBBRRY
GBBWRRGGGOOY
OOYGBBWRRGGG
   ROO
   WWW
   WWW


问:
Bitflip and negate
Given an integer, make an expression that produces it from 0 using unary negation - and bitwise complement ~ (~n = -n-1), with the operators applied right to left.

```<code>...
-3  = ~-~-~0
-2  = ~-~0
-1  = ~0
 0  = 0
 1  = -~0
 2  = -~-~0
 3  = -~-~-~0
...
</code>```

Your expression must be as short as possible, which means no redundant parts of ~~, --, -0, or 00. Output or print the expression as a string or a sequence of characters.

var QUESTION_ID=92598,OVERRIDE_USER=20260;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/92598/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="
"+e.body.replace(OVERRIDE_REG,"")+"
")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}</code>```

 <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

```

答:
Octave, 51 bytes

```<code>x=input('');[("-~"'*[1:abs(x)>0])((x<0)+1:end),'0']
</code>```

At first blatantly copying the Matlab approach by @pajonk and then modifying some details, rewriting as an "outer product" between a vector of ones and the characters "-~" and abusing on-the-fly-indexing (or what it could be called) lets us save some bytes. It still pains me slightly that I can't get the index expression to take fewer bytes.

Octave allows a(i1)(i2) or even (...)(i1)(i2) for indexing where Matlab would want us to store variables in between the indexings.

```<code>((x<0)+1:end)
</code>```

is far too long to describe "skip first if". There must be a better way.

Title: Bitflip and negate

Body:
Octave, 51 bytes

x=input('');[("-~"'*[1:abs(x)>0])((x<0)+1:end),'0']

At first blatantly copying the Matlab approach by @pajonk and then modifying some details, rewriting as an "outer product" between a vector of ones and the characters "-~" and abusing on-the-fly-indexing (or what it could be called) lets us save some bytes. It still pains me slightly that I can't get the index expression to take fewer bytes.

Octave allows a(i1)(i2) or even (...)(i1)(i2) for indexing where Matlab would want us to store variables in between the indexings.

((x<0)+1:end)

is far too long to describe "skip first if". There must be a better way.