Search code snippets, questions, articles...

java code snippets

Recursive Sum of Digits
static int digitsSum(int n) {
        if (n < 0) {
            return -1;
        }
        if (n < 10) {
            return n;
        } else {
            return n % 10 + digitsSum(n / 10);
        }
    }
Java program to split a String using a seperator
String str = "Java~programming~is~cool";
String[] result = str.split("~");
String p1 = result[0];
String p2 = result[1];
String p3 = result[2];
String p4 = result[3];

System.out.println(p1);
System.out.println(p2);
System.out.println(p3);
System.out.println(p4);
String to int conversion using Java
String mystr = "100";
int intVal = Integer.parseInt(mystr);
      
System.out.println(intVal);
helloj
azdd
Java 8 Stream
List<String> myList =
    Arrays.asList("a1", "a2", "b1", "c2", "c1");

myList
    .stream()
    .filter(s -> s.startsWith("c"))
    .map(String::toUpperCase)
    .sorted()
    .forEach(System.out::println);
Pascal Matrix
public List<List<Integer>> generate(int numRows) {
        List<List<Integer>> pascalMatris = new ArrayList<>();
        for (int numRow=0; numRow<numRows; numRow++){
            pascalMatris.add(generatePascalRow(getTheLastMatrisRow(pascalMatris)));
        }
        return  pascalMatris;
    }

    private List<Integer> getTheLastMatrisRow(List<List<Integer>> pascalMatris) {
        return pascalMatris.isEmpty()? new ArrayList<>(): pascalMatris.get(pascalMatris.size()-1);
    }

    private List<Integer> generatePascalRow(List<Integer> theLastPascalRow) {
        List<Integer> pascalRow= new ArrayList<>();
        // adds the lead element '1' in the row
        pascalRow.add(1);
        pascalRow.addAll(calculateTheLastPacalRow(theLastPascalRow));
        if (theLastPascalRow.size()>0) {
            // adds the last element '1' in the row
            pascalRow.add(1);
        }
        return pascalRow;
    }

    private List<Integer> calculateTheLastPacalRow(List<Integer> theLastPascalRow) {
        List<Integer> pascalRowCalculated = new ArrayList<>();
        for (int i=0; i<theLastPascalRow.size()-1; i++){
            pascalRowCalculated.add(theLastPascalRow.get(i)+ theLastPascalRow.get(i+1));
        }
        return pascalRowCalculated;
    }
spiralOrder
/**
     * Input:
     [
     [ 1, 2, 3 ],
     [ 4, 5, 6 ],
     [ 7, 8, 9 ]
     ]

     Output: [1,2,3,6,9,8,7,4,5]


     * @param matrix
     * @return
     */
    public List<Integer> spiralOrder(int[][] matrix) {
        String spiralDirection="RIGHT";
        int startRow=0;
        int startColumn=0;
        int k=0;
        if (matrix==null || matrix.length==0)
            return new ArrayList<>();
        int row = matrix.length;
        int lastRow= row-1;
        int column = matrix[0].length;
        int lastColumn = column-1;
        List<Integer> spiralOrder= new ArrayList<>();

        while (k<row*column) {
            switch (spiralDirection){
                case "RIGHT":
                    for (int i = startRow, j = startColumn; j <= lastColumn; j++) {
                        spiralOrder.add(matrix[i][j]);
                        k++;
                    }
                    startRow++;
                    spiralDirection = "DOWN";
                    break;

                case "DOWN":
                    for (int i = startRow, j = lastColumn; i <= lastRow; i++) {
                        spiralOrder.add(matrix[i][j]);
                        k++;
                    }
                    lastColumn--;
                    spiralDirection = "LEFT";
                    break;

                case "LEFT":
                    for (int i = lastRow, j = lastColumn; j >= startColumn; j--) {
                        spiralOrder.add(matrix[i][j]);
                        k++;
                    }
                    lastRow--;
                    spiralDirection = "UP";
                    break;

                case "UP":
                    for (int i = lastRow, j = startColumn; i >= startRow; i--) {
                        spiralOrder.add(matrix[i][j]);
                        k++;
                    }
                    startColumn++;
                    spiralDirection = "RIGHT";
                    break;

                    default:
                        break;
            }
        }
        return spiralOrder;
    }
Index of maximum in an array
class Solution {
    public int dominantIndex(int[] nums) {
        int maxIndex = 0;
        for (int i = 0; i < nums.length; ++i) {
            if (nums[i] > nums[maxIndex])
                maxIndex = i;
        }
        return maxIndex;
    }
}
Pivot index
class Solution {
    public int pivotIndex(int[] nums) {
        int sum = 0, leftsum = 0;
        for (int x: nums) sum += x;
        for (int i = 0; i < nums.length; ++i) {
            if (leftsum == sum - leftsum - nums[i]) return i;
            leftsum += nums[i];
        }
        return -1;
    }
}