SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Stuart Reges, Marty Stepp
Chapter:
Arraylists
Exercise:
Exercises
Question:5 | ISBN:9780136091813 | Edition: 2

Question

Write a method called scaleByK that takes an ArrayList of integers as a parameter and replaces every integer of value K with K copies of itself. For example, if the list stores the values (4, 1, 2, 0, 3) before the method is called, it should store the values (4, 4, 4, 4, 1, 2, 2, 3, 3, 3) after the method finishes executing. Zeroes and negative numbers should be removed from the list by this method.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

Implementation of scaleByK method:

	public static void scaleByK(ArrayList intList)
	{
		int i = 0;
		
		while(i < intList.size())
		{
			int value = intList.get(i);
			
			if(value > 0)
			{
				for(int j = 1; j < value; j++)
				{
					intList.add(i + j, value);
				}
				
				i += value;
			}
			else
			{
				intList.remove(i);
			}
		}
	}
0 0

Discussions

Post the discussion to improve the above solution.