addBorder [CodeSignal]

Given a rectangular matrix of characters, add a border of asterisks(*) to it.

Example

For

picture = ["abc",
           "ded"]

the output should be

addBorder(picture) = ["*****",
                      "*abc*",
                      "*ded*",
                      "*****"]

Input/Output

  • [execution time limit] 3 seconds (java)
  • [input] array.string picture

    A non-empty array of non-empty equal-length strings.

    Guaranteed constraints:
    1 ≤ picture.length ≤ 100,
    1 ≤ picture[i].length ≤ 100.

  • [output] array.string
    • The same matrix of characters, framed with a border of asterisks of width 1

 

String[] addBorder(String[] picture) {
String startEnd = "";
for(int i = 0; i<picture[0].length()+2;i++){
startEnd +="*";
}

ArrayList<String> list = new ArrayList<>();
list.add(startEnd);
for(int i = 0; i<picture.length; i++){
list.add("*"+picture[i]+"*");
}
list.add(startEnd);
return list.toArray(new String[list.size()]);
}

stringsConstruction [CodeSignal]

<!– HTML generated using hilite.me –>

int stringsConstruction(String a, String b) {
int[] chars = new int[255];
int[] charsB = new int[255];
for(char c: b.toCharArray()){
chars[c]++;
}
for(char c: a.toCharArray()){
charsB[c]++;
}
int max = Integer.MAX_VALUE;
for(char c: a.toCharArray()){
if(chars[c] < max){
max = Math.min(chars[c]/charsB[c],max);
}
}


return max;
}

reverseOnDiagonals [CodeSignal]

The longest diagonals of a square matrix are defined as follows:

  • the first longest diagonal goes from the top left corner to the bottom right one;
  • the second longest diagonal goes from the top right corner to the bottom left one.

Given a square matrix, your task is to reverse the order of elements on both of its longest diagonals.

Example

For

matrix = [[1, 2, 3],
          [4, 5, 6],
          [7, 8, 9]]

the output should be

reverseOnDiagonals(matrix) = [[9, 2, 7],
                              [4, 5, 6],
                              [3, 8, 1]]

Input/Output

  • [execution time limit] 3 seconds (java)
  • [input] array.array.integer matrix

    Guaranteed constraints:
    1 ≤ matrix.length ≤ 10,
    matrix.length = matrix[i].length,
    1 ≤ matrix[i][j] ≤ 1000.

  • [output] array.array.integer
    • Matrix with the order of elements on its longest diagonals reversed.

 

int[][] reverseOnDiagonals(int[][] matrix) {

for(int i = 0, j = matrix.length-1; i<j; i++,j--){
int temp = matrix[i][i];
matrix[i][i] = matrix[j][j];
matrix[j][j] = temp;
}

for(int i = 0,j = matrix.length-1; i<j; i++, j-- ){
System.out.println(i + " "+ j);
int temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
return matrix;

}