java - How to sort characters in a string diagonally -
im splitting string square number of length..
string alphabet = "abcdefghijklmnopqrstuvwxyz"; int = alphabet.length(); int b = (int)math.round(math.sqrt(a)); system.out.println(java.util.arrays.tostring(splitter(key, b))); // prints: [abcde, fghij, klmno, pqrst, uvwxy, z]
the splitter function:
public static string[] splitter(string s, int len) { return s.split(string.format("(?<=\\g.{%1$d})", len)); }
what want sort diagonal this:
[0] = {a,b,d,g,k} [1] = {c,e,h,l,p} [2] = {f,i,m,q,u} [3] = {j,n,r,v,y} [4] = {o,s,w,z,0} [5] = {t,x,0,0,0}
i trying solve loops checking if (i-1) >= i... confused , kinda lost in here..
the solution created below
- calculates dimensions of result matrix;
- uses dimensions initialize two-dimensional
result
arraynul
character values; - sets values in array based on idea elements on same diagonal, sum of coordinates constant.
string alphabet = "abcdefghijklmnopqrstuvwxyz"; double root = math.sqrt(alphabet.length()); int width = (int) math.round(root); int height = width < root ? width + 1 : width; char[][] result = intstream.range(0, height) .maptoobj(i -> new char[width]) .toarray(i -> new char[height][]); int x = 0, y = 0, sum = 0; (char c : alphabet.tochararray()) { result[x][y] = c; y = x == math.min(sum, height - 1) ? math.min(++sum, width - 1) : y - 1; x = sum - y; } system.out.println(arrays.deeptostring(result));
this yields following output:
[[a, b, d, g, k], [c, e, h, l, p], [f, i, m, q, u], [j, n, r, v, y], [o, s, w, z, ], [t, x, , , ]]
Comments
Post a Comment