Compact data Download

Dave Wittry

ints, arrays, methods Student approved


Introduction

A common task with array processing might be to traverse a list and eliminate an undesired value. A text file of integers is provided (compact.txt) which contains both non-zero and zeroes in random fashion. The number of integers is not given, though it will be less than or equal to 100.


Task

  1. Write a program that reads a text file (compact.txt) and stores the integers in an array.
  2. Write a function compact that eliminates all 0's (zeroes) from its array parameter, leaving the relative order of the other elements unchanged. All local variables within this function must be scalar; in other words, you may not use a second array to solve the problem. You must use the function header public static int compact (int list[], int N)
  3. Your method's precondition is: list contains integers; N is the number of integers in the array (N <= list.length)
  4. Your method's postcondition is: all non-zero elements in the array are at the front of the array
  5. Your method should return: the number of non-zero elements – all of which are at the beginning of the array, N has been updated
  6. Do not solve the problem by printing out only the non-zero values in the array. Instead, compact must move all non-zero elements to the front of the array.


Starter code

class Compact{
	public static int compact(int list[], int N){
		// Your work here
	}
}

Expected output

Before: 0, 9, 7, 0, 0, 23, 4, 0
After: 9, 7, 23, 4

Useful tools to solve the problem