[英]2D Char Array For Loop (Java)
我目前正在解决此问题https://www.hackerrank.com/challenges/encryption 。
这就是我到目前为止
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String input = in.nextLine();
double length = input.length();
int width = (int) Math.ceil(Math.sqrt(length));
int height = (int) Math.floor(Math.sqrt(length));
char[] letters = input.toCharArray();
char[][] matrix = new char[height][width];
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
if ((j + i * width) < letters.length) {matrix[i][j] = letters[j + i * width];}
}
}
StringBuffer encrypted = new StringBuffer();
for (int cols = 0; cols < width; cols++) {
for (int rows = 0; rows < height; rows++) {
encrypted.append(matrix[rows][cols]);
}
encrypted.append(' ');
}
System.out.println(encrypted.toString());
}
}
在“ feedthedog”的情况下失败-我打印“ fto ehg ee”,而不是答案“ fto ehg ee dd”。 此外,似乎我永远无法获得第二个for循环的最后一次迭代,而且我似乎也找不到原因。 任何帮助将不胜感激,谢谢。
“确保,高度*宽度> = len(word)”
您这样做是为了在循环中进行检查,因为它的高度和宽度是已知的,所以循环检查本质上是不好的。 但是您应该使用它来检查宽度和高度,并在宽度和高度不符合约束的情况下对其进行调整。 练习有缺陷,因为它没有说明是否应该首先扩展宽度或高度。
您假设高度始终为地板,宽度始终为ciel,在这种情况下,高度比应该的高度小1,这就是为什么高度不完整的原因。
编辑:尽管floor(sqrt(len(word)))<=宽度,高度<= ceil(sqrt(len(word)))可能意味着width = ... floor,height = ... ciel,该语句已编写好像它是一种向量,但如果不是这种情况,他们应该使用分号。 但是,如果是这样,您只需将宽度和高度向后移动。
而且您使用的是cols <宽度,行<高度。
同样,由于它不可逆,因此它并不是真正的密码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.