Write each of the following functions in Java or C++. You must use the API of a
ID: 3583157 • Letter: W
Question
Write each of the following functions in Java or C++. You must use the API of a list class in the library. take(1 st, n) This function returns the n-element prefix of 1st if n is less than the size of 1st; otherwise, it returns let itself. For example, if 1st is ['a', 'b', 'c', 'd'] and n is 3, then the return list is ['a', 'b', 'c']. sublists(1st, n). This function returns all n-element sublists of 1st. For example, if let is ['a', 'b', 'c'] and n is 2, then the returned list is: [['a', 'b'], ['b', 'c'], ['c', 'd']].Explanation / Answer
package org.jay.sample;
import java.util.ArrayList;
import java.util.List;
public class Tester {
public static void main(String[] args) {
List<String>list=new ArrayList<>();
list.add("a");
list.add("b");
list.add("c");
list.add("d");
System.out.println(list);
list=take(list,2);
System.out.println(list);
List<String>list2=new ArrayList<>();
list2.add("a");
list2.add("b");
list2.add("c");
list2.add("d");
List<List<String>>sublist=sublists(list2,2);
System.out.println(sublist);
}
/**
*
* @param list
* @param n
* @return list
*/
public static List<String> take(List<String>list,int n){
if(n>=list.size() || n<=0) //if n=size of list or n<=0 will return the same list
return list;
List<String>tempList=new ArrayList<>();
for (int i = 0; i < n; i++) {
tempList.add(list.get(i));//adding the required element
}
list=tempList;
return list;
}
/**
*
* @param list
* @param n
* @return list
*/
public static List<List<String>>sublists(List<String>list,int n){
List<List<String>>finalList=new ArrayList<>();
if(n>=list.size() || n<=0){ //if n=size of list or n<=0 will return the same list
finalList.add(list);
return finalList;
}
int fromIndex=0;
while(fromIndex<list.size()-1){ // loop till the fromindex < list size
List<String>subList=new ArrayList<>();
if(fromIndex+n<list.size()){
subList=list.subList(fromIndex, fromIndex+n); // getting sublist from list
}else{
subList=list.subList(fromIndex, list.size()); //// getting sublist from list
}
finalList.add(subList); // adding to the final list
fromIndex+=n-1;
}
return finalList;
}
}
output
[a, b, c, d]
[a, b]
[[a, b], [b, c], [c, d]]
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.