// Assume you got some data from a customer and your task is to design a routine that will calculate the average Product price per Group.
//
// The Price of each Product is calculated as:
// Cost * (1 + Margin)
//
// Assume there can be a large number of products.
//
// Plus points:
// - use Groovy closures (wherever it makes sense)
// - make the category look-up performance effective
 
// contains information about [Product, Group, Cost]
def products = [
["A", "G1", 20.1],
["B", "G2", 98.4],
["C", "G1", 49.7],
["D", "G3", 35.8],
["E", "G3", 105.5],
["F", "G1", 55.2],
["G", "G1", 12.7],
["H", "G3", 88.6],
["I", "G1", 5.2],
["J", "G2", 72.4]]
 
// contains information about Category classification based on product Cost
// [Category, Cost range from (inclusive), Cost range to (exclusive)]
// i.e. if a Product has Cost between 0 and 25, it belongs to category C1
// ranges are mutually exclusive and the last range has a null as upper limit.
def category = [
["C3", 50, 75],
["C4", 75, 100],
["C2", 25, 50],
["C5", 100, null],
["C1", 0, 25]]
 
// contains information about margins for each product Category
// [Category, Margin (either percentage or absolute value)]
def margins = [
"C1" : "20%",
"C2" : "30%",
"C3" : "0.4",
"C4" : "50%",
"C5" : "0.6"]
 
// ---------------------------
//
// YOUR CODE GOES BELOW THIS LINE
//
// Assign the 'result' variable so the assertion at the end validates
//
// ---------------------------
 
 
def grouped = getGroupedPrices(products, category, margins)
def result = getResult(grouped)
 
// ---------------------------
//
// IF YOUR CODE WORKS, YOU SHOULD GET "It works!" WRITTEN IN THE CONSOLE
//
// ---------------------------
assert result == [
"G1" : 37.5,
"G2" : 124.5,
"G3" : 116.1
] : "It doesn't work"
 
println "It works!"
 
// Returns the prices of products grouped by product group. The price fo the product is already applied with margins.
def getGroupedPrices(List products, List categories, Map margins) {
def grouped = [:]
products.each { prod ->
def cost = new BigDecimal(prod[2])
def group = prod[1]
def cat =  findCategory(categories, cost)  
def value = findMarginValue(margins, cat)
def finalCost = cost * new BigDecimal(1 + value)
def list = getGroupList(grouped, group)
list.add(finalCost)
grouped.put(prod[1], list)
}
return grouped;
}

// Returns the list of prices from especific group
private getGroupList(Map grouped, String group) {
def list = grouped.getAt(group)
if (list == null) {
list = new ArrayList()       
}
return list;
}
 
// Returns the product category where the product price is within the range
private findCategory(List category, BigDecimal cost) {
return category.find { cat -> (cost > cat[1] && cost <= Optional.ofNullable(cat[2]).orElse(Integer.MAX_VALUE))}
}
 
// Returns the margin of the product category
private findMarginValue(Map margins, Object cat) {
def margin = margins.find {margin -> margin.key == cat[0]}
def value = margin.value
 
if (value.endsWith("%")) {
value = new BigDecimal(value.replace("%", "")).divide(100);
} else {
value = new BigDecimal(value)
}
return value
}
 
//Return the average price per product group
def getResult(Map groupedPrices) {
def result = [:]
groupedPrices.each {
def average= new BigDecimal(it.value.sum()).divide(it.value.size(), 1, java.math.RoundingMode.HALF_UP)
result.put(it.key, average )
}
return result
} 

Groovy online compiler

Write, Run & Share Groovy code online using OneCompiler's Groovy online compiler for free. It's one of the robust, feature-rich online compilers for Groovy language, running the latest Groovy version 2.6. Getting started with the OneCompiler's Groovy editor is easy and fast. The editor shows sample boilerplate code when you choose language as Groovy and start coding.

Read inputs from stdin

OneCompiler's Groovy online editor supports stdin and users can give inputs to programs using the STDIN textbox under the I/O tab. Following is a sample Groovy program which takes name as input and prints hello message with your name.

def name = System.in.newReader().readLine()
println "Hello " + name

About Groovy

Groovy is an object-oriented programming language based on java. Apache Groovy is a dynamic and agile language which is similar to Python, Ruby, Smalltalk etc.

Key Features

  • It's not a replacement for java but it's an enhancer to Java with extra features like DSL support, dynamic typing, closures etc.
  • Accepts Java code as it extends JDK
  • Greater flexibility
  • Concise and much simpler compared to Java
  • Can be used as both programming language and scripting language.

Syntax help

Data Types

Data typeDescriptionRange
StringTo represent text literalsNA
charTo represent single character literalNA
intTo represent whole numbers-2,147,483,648 to 2,147,483,647
shortTo represent short numbers-32,768 to 32,767
longTo represent long numbers-9,223,372,036,854,775,808 to +9,223,372,036,854,775,807
doubleTo represent 64 bit floating point numbers4.94065645841246544e-324d to 1.79769313486231570e+308d
floatTo represent 32 bit floating point numbers1.40129846432481707e-45 to 3.40282346638528860e+38
byteTo represent byte value-128 to 127
booleanTo represent boolean values either true or falseTrue or False

Variables

You can define variables in two ways

Syntax:

data-type variable-name;

[or]

def variable-name;

Loops

0.upto(n) {println "$it"}

or

n.times{println "$it"}

where n is the number of loops and 0 specifies the starting index

Decision-Making

1. If / Nested-If / If-Else:

When ever you want to perform a set of operations based on a condition or set of conditions, then If / Nested-If / If-Else is used.

if(conditional-expression) {
  // code
} else {
  // code
}

2. Switch:

Switch is an alternative to If-Else-If ladder and to select one among many blocks of code.

switch(conditional-expression) {    
case value1:    
 // code    
 break;  // optional  
case value2:    
 // code    
 break;  // optional  
...    
    
default:     
 //code to be executed when all the above cases are not matched;    
} 

List

List allows you to store ordered collection of data values.

Example:

def mylist = [1,2,3,4,5];
List MethodsDescription
size()To find size of elements
sort()To sort the elements
add()To append new value at the end
contains()Returns true if this List contains requested value.
get()Returns the element of the list at the definite position
pop()To remove the last item from the List
isEmpty()Returns true if List contains no elements
minus()This allows you to exclude few specified elements from the elements of the original
plus()This allows you to add few specified elements to the elements of the original
remove()To remove the element present at the specific position
reverse()To reverse the elements of the original List and creates new list