简体   繁体   中英

Draw rectangle using capital letters

I want to make rectangle using capital letters. For example, when we input the is "A" , then show

A 

if "B" , then

BBB
BAB
BBB

if "C" , then

CCCCC 
CBBBC
CBABC
CBBBC
CCCCC

the pattern will be like that until Z. I've managed to make the rectangle but it is always the same letter like this:

BBB
BBB
BBB

Here my code:

 $('#click').click(function () { $('#output').html(''); var input = $('#input').val(); var validpattern = new RegExp('^[AZ\\d&Ñ]+$'); if (input.length > 1) { $('#output').append('invalid output'); } else if (!input.match(validpattern)) { $('#output').append('invalid output'); } else { var string = String.fromCharCode(input.charCodeAt(0)); var stringa = 65; var inputascii = string.charCodeAt(); var inputasciiawal = inputascii; var jarak = inputascii - stringa; jarak = jarak * 2; var kiri = 0; console.log(jarak); for (kiri; kiri <= jarak; kiri++) { $('#output').append('<br>'); for (var isi = 0; isi <= jarak; isi++) { $('#output').append(String.fromCharCode(inputascii)); } } } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" id="input"> <button id="click">click</button> <br><br> <span id="output"></span> 

You can calculate the distance between the code of letter "A" and the input first letter. Then, you can build a square with a side equal to

var side = (2*distance)+1;

This is because you reserve a cell for the central letter, plus distance cells for surrounding letters on each side.

Then you can make a double cycle (one for rows, one for columns), calculate the distance from the center and then output the proper letter. This is the core of the application (you can obviously add your input checks before it, to validate input data)

var input = "D"; // the first letter of input
var value = input.charCodeAt(0);
var stringa = 65;
var distance = value-stringa;
var side = (2*distance)+1;
console.log(distance);

for(i=0;i<side;i++)
{
    for(j=0;j<side;j++)
    {
        var absi = Math.abs(i-distance);
        var absj = Math.abs(j-distance);
        var max = Math.max(absi,absj);
        var letter = String.fromCharCode(stringa + max)
        $('#output').append(letter + '&nbsp;&nbsp;&nbsp;');      
    }

    $('#output').append('<br/>');  
}

Fiddle

Maybe this is not the most efficient solution, but it does the job (actually, I don't think that efficiency could represent a problem in this situation).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM