Tuesday, October 21, 2025

TWC344

Challenge Link

My Perl somehow got broken, and I didn't yet have the time to fix the issue, so this post will contain Java solutions.

Task1

We add the digit x to the array which contains the digits of a number:
import java.util.List;
import java.util.LinkedList;

public class Ch1 {
  public static void main(String[] args) {
    System.out.println(array_form_compute(new int[]{1,2,3,4},12));
    System.out.println(array_form_compute(new int[]{2,7,4},181));
    System.out.println(array_form_compute(new int[]{9,9,9},1));
    System.out.println(array_form_compute(new int[]{1,0,0,0,0},9999));
    System.out.println(array_form_compute(new int[]{0},1000));
  }

  private static List array_form_compute(int[] arr,int k) {
    int i = arr.length-1,carry = 0;
    List res = new LinkedList<>();
    while(i >= 0 || k > 0 || carry > 0) {
      carry += (i < 0 ? 0 : arr[i--]) + k % 10;
      res.addFirst(carry % 10);
      carry /= 10;
      k /= 10;
    }
    return res;
  }
}

Task2

We check if the array can be formed by combining the source elements:
public class Ch2 {
  public static void main(String[] args) {
    System.out.println(array_formation(new int[][]{{2,3},{1},{4}},
				       new int[]{1,2,3,4}));
    System.out.println(array_formation(new int[][]{{1,3},{2,4}},
				       new int[]{1,2,3,4}));
    System.out.println(array_formation(new int[][]{{9,1},{5,8},{2}},
				       new int[]{5,8,2,9,1}));
    System.out.println(array_formation(new int[][]{{1},{3}},
				       new int[]{1,2,3}));
    System.out.println(array_formation(new int[][]{{7,4,6}},
				       new int[]{7,4,6}));
  }

  private static boolean array_formation(int[][]source,
					 int[] target) {
    for(int i = 0; i < target.length;) {
      int k = 0;
      while(k < source.length && source[k][0] != target[i]) ++k;
      if(k == source.length) return false;
      int j = 0;
      while(j < source[k].length && target[i] == source[k][j]) {
	++i;
	++j;
      }
    }
    return true;
  }
}

No comments:

Post a Comment