Saturday, February 13, 2016

Get 4 "different" numbers

It is easy to just get 4 numbers. But it is difficult to get 4 numbers which are different from each other. This is the code to get 4 different numbers.

public static void main(String[] args){
    int[] answer = new int[4];
    for(int i = 0; i < answer.length; i++){
        Loop: while(true){
            answer[i] = (int)(Math.random() * 10);  //Random numbers between 0 and 9
            for(int j = 0; j < i; j++){
                //If one is same as one of the previous numbers, the loop is repeated
                if(answer[j] == answer[i]) continue Loop;
            }
            break;
        }
    }
}

Saturday, February 6, 2016

reverse3 --- Answer to a codingbat's practice problem

This is an answer code for a problem of codingbat; http://codingbat.com/prob/p112409

public int[] reverse3(int[] nums) {
  int[] numsRev = new int[nums.length];
  int j = nums.length-1;

  for(int i = 0; i <= nums.length-1; i++){
    numsRev[i] = nums[j];
    j--;
  }

  return numsRev;
}

maxSpan --- Answer to the practice problem of coding bat.

The code below is my answer toward the practice problem of coding bat; http://codingbat.com/prob/p189576 .
I know my code is ugly... But it works anyway.

public int maxSpan(int[] nums) {
  if(nums.length == 0){
    return 0;
  }

  int[] counter = new int[nums.length];

  for(int i = 0; i <= nums.length-1; i++){
    for(int j = 0; j <= nums.length-1; j++){
      if(nums[i] == nums[j]){
        counter[i]++;
      }
    }
  }

  int biggest = 0;
  int arrayNumMin = 0;
  int arrayNumMax = 0;

  for(int k = 0; k <= counter.length-1; k++){
    if(biggest < counter[k]){
      biggest = counter[k];
      arrayNumMin = k;
    }
  }

  for(int l = 0; l <= counter.length-1; l++){
    if(nums[l] == nums[arrayNumMin]){
      arrayNumMax = l;
    }
  }

  return arrayNumMax - arrayNumMin + 1;
}