简体   繁体   English

使用大写字母绘制矩形

[英]Draw rectangle using capital letters

I want to make rectangle using capital letters. 我想使用大写字母制作矩形。 For example, when we input the is "A" , then show 例如,当我们输入is为"A" ,则显示

A 

if "B" , then 如果为"B" ,则

BBB
BAB
BBB

if "C" , then 如果为"C" ,则

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: 直到Z为止,模式都是这样。我设法制作了矩形,但它始终是相同的字母,如下所示:

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. 您可以计算字母“ A”的代码与输入的第一个字母之间的距离。 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. 这是因为您为中心字母保留了一个单元格,并且在每一侧都为周围的字母保留了distance单元格。

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). 也许这不是最有效的解决方案,但确实可以完成工作(实际上,在这种情况下,我认为效率不代表问题)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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