Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Numbers {
- public static final int DEFAULT_CAPACITY = 10;
- private int[] numbers;
- private int currentPos = 0;
- public Numbers(){
- this(DEFAULT_CAPACITY);
- }
- public Numbers(int capacity){
- numbers = new int[capacity];
- }
- //if is full we leave otherwise insert number
- public void add(int num){
- if(isFull()) return;
- insertNumInPos(num, currentPos);
- incrementPos();
- }
- public String toString(){
- StringBuilder s = new StringBuilder("[");
- for(int i =0; i < size(); ++i){
- s.append(getNumber(i));
- if(i < size() - 1)
- s.append(",");
- }
- s.append("]");
- return s.toString();
- }
- public int getNumber(int pos){
- return numbers[pos];
- }
- public int size(){
- return currentPos;
- }
- public int capacity(){
- return numbers.length;
- }
- private void insertNumInPos(int num, int pos){
- numbers[pos] = num;
- }
- private void incrementPos(){
- currentPos++;
- }
- public boolean isFull(){
- return currentPos == numbers.length;
- }
- public boolean isEmpty(){
- return currentPos == 0;
- }
- }
- //testclass with main method
- import java.util.Random;
- public class ArrayMergeDemo{
- public static void main(String[] args){
- //nums1 intialized with twice the capacity of nums2
- Numbers nums1 = new Numbers(20),nums2 = new Numbers();
- //lets fill them with random numbers just from 0 to nums2 capacity
- Random randomNumsGenerator = new Random();
- for(int i = 0; i < nums2.capacity(); ++i){
- nums1.add(randomNumsGenerator.nextInt(10));
- nums2.add(randomNumsGenerator.nextInt(10));
- }
- System.out.println("contents of nums1 : " + nums1);
- System.out.println("contents of nums2 : " + nums2);
- if(arraysCanBeMerged(nums1,nums2)){
- merge(nums1,nums2);
- System.out.println("contents of nums1 after merge : " + nums1);
- }
- }
- public static boolean arraysCanBeMerged(Numbers to, Numbers from){
- return to.capacity() >= (to.size() + from.size());
- }
- public static Numbers merge(Numbers to, Numbers from){
- for(int num = 0; num < from.size(); ++num)
- to.add(from.getNumber(num));
- return to;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement