52
3
Usually, it is said that "Doing X without Y" can be a trap to beginners writing challenges (source). However, I am cocky and think that I can definitely make an X without any Ys. Randomly. Oh yes, this will be good.
Challenge: Given an odd integer n
greater than or equal to 1, output an ex of side length n
made of random printable ascii characters sans "y" and "Y", and the space. All allowed characters must have a nonzero chance of occurring, but not necessarily uniform. This is a code-golf so the shortest code in bytes wins. You should, however, randomize each char--that is, the struts of the ex shouldn't be equal, unless if by chance.
The chars to appear
!#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXZ[\]^_`abcdefghijklmnopqrstuvwxz{|}~"
Constructing the ex
Side length 1:
x
Side length 3:
x x
x
x x
Side length 5:
x x
x x
x
x x
x x
etc.
Example outputs
input
output
empty line
3
h 2
^
9 5
1
:
5
D 1
W z
W
q j
W 1
Example implementation
You do not need to handle invalid inputs.
function generate(sideLength){
var result = "";
var INNER = "@"
for(var i = 0; i < sideLength; i++){
var p = i < sideLength / 2 ? i : sideLength - i - 1;
result += " ".repeat(p) + ((sideLength / 2 | 0) == p ? "" : INNER) + " ".repeat(Math.max(sideLength - p * 2 - 2, 0)) + INNER + "\n";
}
return result.replace(RegExp(INNER, "g"), function(e){
let c = "y";
while(c === "y" || c === "Y"){
c = String.fromCharCode((Math.random() * 94) + 33 | 0);
}
return c;
});
}
function print(v){
output.innerHTML = "";
output.appendChild(document.createTextNode(v));
}
function update(){
var n = Number(input.value);
if(n !== Math.floor(n)) print("error: " + n + " is not an integer.");
else if(n % 2 === 0) print("error: " + n + " is not odd.");
else if(n < 1) print("error: " + n + "is less than one.");
else print(generate(n));
}
input.onchange = update;
update();
* {
font-family: Consolas, monospace;
}
#output {
white-space: pre;
}
<input id="input" min=1 value=1 type=Number>
<div id="output"></div>
Which characters exactly must be eligible for appearing? – xnor – 2016-07-27T01:01:33.833
@xnor Characters from
!
to~
sansy
andY
– Conor O'Brien – 2016-07-27T01:02:21.603@LegionMammal978 No, because non-Y characters include
y
and然
. – Leaky Nun – 2016-07-27T01:05:40.127@CᴏɴᴏʀO'Bʀɪᴇɴ I take it then that other characters not in the list may not appear? – xnor – 2016-07-27T01:08:37.463
@xnor Yes, you are right. – Conor O'Brien – 2016-07-27T01:09:09.417
It is OK if our program tries generating the X repeatedly until it gets one without a y, and then prints it? It is OK if the number of tries is some function of n such that the probability of not getting it is exponentially small? – xnor – 2016-07-27T01:11:38.387
@xnor Both are acceptable. – Conor O'Brien – 2016-07-27T01:12:29.523
7
Hmm.. random...
– NonlinearFruit – 2016-07-27T02:26:14.64314Wait!? We're allowed to use "Y" and "y" in the our code? – Adám – 2016-07-27T05:35:21.843