DEV Community

dev.to staff
dev.to staff

Posted on

Daily Challenge #187 - Most Sales

You work in the best consumer electronics company around. Your boss asked you to find out which products generate the most revenue.

You'll be given lists of products, amounts, and prices. Given these three lists of same length, return the product name(s) with the highest revenue (amount * price). If multiple products have the same revenue, order them according to their original positions.

Example

products: ["Computer", "Cell Phones", "Vacuum Cleaner"]
amounts: [3, 24, 8]
prices: [199, 299, 399]

return: Cell Phones

Test

products: ["Cell Phones", "Vacuum Cleaner", "Computer", "Autos", "Gold", "Fishing Rods", "Lego", " Speakers"]
amounts: [0, 12, 24, 17, 19, 23, 120, 8]
prices: [9, 24, 29, 31, 51, 8, 120, 14]


This challenge comes from JakobPri on CodeWars. Thank you to CodeWars, who has licensed redistribution of this challenge under the 2-Clause BSD License!

Want to propose a challenge idea for a future post? Email yo+challenge@dev.to with your suggestions!

Top comments (10)

Collapse
 
avalander profile image
Avalander

Haskell

module MostSales where

import Data.List (groupBy, head, zip3, sortBy)


findHighest :: [String] -> [Int] -> [Int] -> [String]
findHighest a b c =
    ((map fst) . head . (groupBy value) . (sortBy compare') . (map total)) $ (zip3 a b c)
    where
        total (n, a, b)        = (n, a * b)
        value (_, x)           = ((==) x . snd)
        compare' (_, a) (_, b) = compare b a
Collapse
 
avalander profile image
Avalander • Edited

Scala

object MostSales {
  private implicit val order = Ordering.Int.reverse

  private val total = (x: ((Int, Int), String)) => x match {
    case ((a, p), n) => (n, a * p)
  }

  def findHighest (names: Seq[String], amounts: Seq[Int], prices: Seq[Int]): Seq[String] = {
    val sorted = amounts zip prices zip names map total sortBy (_._2)
    val result = sorted takeWhile (_._2 == sorted.head._2)
    result map (_._1)
  }
}

And some tests

import org.scalatest._

class MostSalesTest extends FunSuite {
  import MostSales._

  test("Case 1") {
    val products = List("Computer", "Cell Phones", "Vacuum Cleaner")
    val amounts = List(3, 24, 8)
    val prices = List(199, 299, 399)

    val result = findHighest(products, amounts, prices)
    assert(result == List("Cell Phones"))
  }

  test("Case 2") {
    val products = List("Cell Phones", "Vacuum Cleaner", "Computer", "Autos", "Gold", "Fishing Rods", "Lego", " Speakers")
    val amounts = List(0, 12, 24, 17, 19, 23, 120, 8)
    val prices = List(9, 24, 29, 31, 51, 8, 120, 14)

    val result = findHighest(products, amounts, prices)
    assert(result == List("Lego"))
  }

  test("Returns multiple results") {
    val products = List("Computer", "Cell Phones", "Vacuum Cleaner")
    val amounts = List(3, 2, 6)
    val prices = List(200, 299, 100)

    val result = findHighest(products, amounts, prices)
    assert(result == List("Computer", "Vacuum Cleaner"))
  }
}
Collapse
 
savagepixie profile image
SavagePixie

Elixir

def get_max_revenue(products, amounts, prices) do
  list = Enum.zip([ products, amounts, prices ])
    |> Enum.map(fn { product, amount, price } -> { product, amount * price } end)
    |> Enum.sort(fn { _, r1 }, { _, r2 } -> r1 >= r2 end)
  first = list
    |> List.first
    |> (fn { _, revenue } -> revenue end).()
  Enum.take_while(list, fn { _, revenue } -> revenue == first end)
    |> Enum.map(fn { product, _ } -> product end)
end
Collapse
 
sabbin profile image
Sabin Pandelovitch

Javascript - Reduce method

const products = [
  "Cell Phones",
  "Vacuum Cleaner",
  "Computer",
  "Autos",
  "Gold",
  "Fishing Rods",
  "Lego",
  " Speakers"
];
const amounts = [0, 12, 24, 17, 19, 23, 120, 8];
const prices = [9, 24, 29, 31, 51, 8, 120, 14];

const { productName } = products.reduce(
  (acc, val, i) =>
    amounts[i] * prices[i] > acc.value
      ? {
          productName: val,
          value: amounts[i] * prices[i]
        }
      : acc,
  { productName: "", value: 0 }
);

console.log(productName);
Collapse
 
amcmillan01 profile image
Andrei McMillan

python

def most_sales(product_list, amount_list, price_list):
    if len(product_list) == len(amount_list) == len(price_list):

        revenue_list = []
        top_revenue = []

        for i, n in enumerate(product_list):
            revenue_list.append(amount_list[i] * price_list[i])

        max_val = max(revenue_list)

        for index, value in enumerate(revenue_list):
            if value == max_val:
                top_revenue.append(str(product_list[index]) + ' - ' + '${:,.2f}'.format(value))

        print '\n'.join(top_revenue)
        print '\n' + ('-' * 20) + '\n'
    else:
        print('invalid entries')


most_sales(
    ["Computer", "Cell Phones", "Vacuum Cleaner"],
    [3, 24, 8],
    [199, 299, 399]
)
# Cell Phones - $7,176.00

most_sales(
    ["Cell Phones", "Vacuum Cleaner", "Computer", "Autos", "Gold", "Fishing Rods", "Lego", " Speakers"],
    [0, 12, 24, 17, 19, 23, 120, 8],
    [9, 24, 29, 31, 51, 8, 120, 14]
)
# Lego - $14,400.00

most_sales(
    ["Cell Phones", "Vacuum Cleaner", "Computer", "Autos", "Gold", "Fishing Rods", "Lego", " Speakers"],
    [120, 12, 24, 17, 19, 23, 120, 8],
    [120, 24, 29, 31, 51, 8, 120, 14]
)
# Cell Phones - $14,400.00
# Lego - $14,400.00

Collapse
 
vidit1999 profile image
Vidit Sarkar

Here is C++ solution

vector<string> highestRevenue(vector<string> products, vector<int> amounts, vector<int> prices){
    vector<int> revenue; // holds the revenue of all products
    for(int i=0; i<amounts.size();i++){
        revenue.push_back(amounts[i]*prices[i]);
    }

    int max_revenue = *max_element(revenue.begin(),revenue.end()); // maximum revenue
    if(max_revenue == 0)
        return vector<string>(); // if maximum revenue is zero then there is no need to return any product

    vector<string> highestRevProducts; // vector storing the products with maximum revenue
    for(int i=0;i<revenue.size();i++)
        if(revenue[i] == max_revenue)
            highestRevProducts.push_back(products[i]);

    return highestRevProducts;
}
Collapse
 
maskedman99 profile image
Rohit Prasad

Python

for i in range(len(prices)):
        prices[i] = int(amounts[i])*int(prices[i])

j = max(prices)

for i in range(len(prices)):
        if prices[i] == j:
                print(products[i])
Collapse
 
craigmc08 profile image
Craig McIlwrath • Edited

Haskell:

maximumsBy :: Ord b => (a -> b) -> [a] -> [a]
maximumsBy f = foldr g [] 
  where g x [] = [x]
        g x ys = case f x `compare` f (head ys) of
                   LT -> ys
                   EQ -> x : ys
                   GT -> [x]

bestSeller :: (Ord b, Num b) => [a] -> [b] -> [b] -> [a] 
bestSeller ns qs ps = map fst $ maximumsBy snd $
                      zip ns $ zipWith (*) qs ps
Collapse
 
divyanshpratap profile image
divyansh-pratap • Edited

include

int main()
{
int i , a , j , revenue;
char A[15][30];
int B[30];
int C[30];
printf("enter the number of inputs you want to enter :");
scanf("%d" , &a);
printf("enter the name of the items :-\n");
for(i=-1;i<a;i++)
{

    gets(A[i]);

}

for(i=0;i<a;i++)
{
    printf("enter the price of %dth element :\n",i+1);
    scanf("%d" , &B[i]);
}
for(i=0;i<a;i++)
{
    printf("\nenter the quantity of %dth element :\n" , i+1);
    scanf("%d" , &C[i]);
}
 revenue=C[0]*B[0];
 j=0;

for(i=0;i<a;i++)

{
if(i>0)
{
if(C[i]*B[i]>C[i-1]*B[i-1])
{
revenue=C[i]*B[i];
j=i;
}
}

}

printf("%s" , A[j]);

}