6
\$\begingroup\$

Given N items (0 < N <= 50) with prices (which are always integers) P0 ... PN-1 and given amounts of each item A0 ... AN-1, determine how much the total cost will be.

Examples

N: 2
P0: 2
P1: 3
A0: 1
A1: 4
Result: 14

N: 5
P0: 2
P1: 7
P2: 5
P3: 1
P4: 9
A0: 1
A1: 2
A2: 3
A3: 2
A4: 3
Result: 60

Remember, this is , so the code with the smallest number of bytes wins.

Leaderboards

Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

# Language Name, N bytes

where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:

# Ruby, <s>104</s> <s>101</s> 96 bytes

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:

# Perl, 43 + 2 (-p flag) = 45 bytes

You can also make the language name a link which will then show up in the leaderboard snippet:

# [><>](http://esolangs.org/wiki/Fish), 121 bytes

var QUESTION_ID=95128,OVERRIDE_USER=12537;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>

\$\endgroup\$
5
  • 7
    \$\begingroup\$ In other words, "find the dot product of two vectors"? \$\endgroup\$ – xnor Oct 2 '16 at 0:22
  • \$\begingroup\$ Will the costs always be integers? \$\endgroup\$ – Dennis Oct 2 '16 at 0:26
  • \$\begingroup\$ @Dennis Yes. They will. \$\endgroup\$ – Oliver Ni Oct 2 '16 at 0:45
  • \$\begingroup\$ In case it matters, positive integers? \$\endgroup\$ – xnor Oct 2 '16 at 0:46
  • \$\begingroup\$ @xnor No, it can be negative \$\endgroup\$ – Oliver Ni Oct 2 '16 at 0:47

28 Answers 28

7
\$\begingroup\$

Actually, 1 byte

*

Try it online!

Okay, this is the shortest dot product built-in I could find. >_>

\$\endgroup\$
5
\$\begingroup\$

Jelly, 2 bytes

æ.

Try it online!

A built-in computing the dot product between two input vectors: if, for each 1 ≤ i ≤ n, we buy ai items worth pi each, the formula for the total cost is a1p1 + a2p2 + … +anpn, which is precisely the definition of the dot product.

\$\endgroup\$
4
\$\begingroup\$

Mathematica, 1 byte

.

Usage:

{1, 2, 3}.{4, 5, 6}

(* 32 *)
\$\endgroup\$
3
\$\begingroup\$

Haskell, 17 bytes

(sum.).zipWith(*)

Multiply the lists entrywise, then sum. Shorter than importing (23 bytes)

import Data.Vector
vdot
\$\endgroup\$
3
\$\begingroup\$

Python, 36 33 bytes

lambda*x:sum(map(int.__mul__,*x))

Thanks to @xnor for golfing off 3 bytes!

Test it on Ideone.

\$\endgroup\$
3
  • \$\begingroup\$ If you can take input as a list of lists, you can do lambda*M:sum(x*y for x,y in zip(*M)) and lambda*M:sum(map(int.__mul__,*M)). \$\endgroup\$ – xnor Oct 2 '16 at 0:31
  • \$\begingroup\$ How about float.__mul__? Should still be one byte shorter. \$\endgroup\$ – Lynn Oct 2 '16 at 0:32
  • \$\begingroup\$ @Lynn Thanks, but we didn't need to handle non-integers after all. \$\endgroup\$ – Dennis Oct 2 '16 at 0:48
3
\$\begingroup\$

TI-Basic, 12 bytes

Prompt L1,L2
sum(L1L2
\$\endgroup\$
0
2
\$\begingroup\$

Ruby, 34 23 + 9 = 32 bytes

+9 bytes for -rmatrix flag.

->p,a{Vector[*p].dot a}

See it on eval.in: https://eval.in/653676

\$\endgroup\$
2
  • \$\begingroup\$ indirectly you use N as count of arrays \$\endgroup\$ – Jörg Hülsermann Oct 2 '16 at 0:05
  • \$\begingroup\$ That's sort of an existential question. If N was never defined, would the arrays still exist? If the arrays didn't exist, would N? \$\endgroup\$ – Jordan Oct 2 '16 at 0:12
2
\$\begingroup\$

Pyth, 3 bytes

s*V

(s)ums the (V)ectorized (*)product of the two input arrays.

\$\endgroup\$
2
\$\begingroup\$

MATLAB / Octave, 4 bytes

@dot

This defines an anonymous function.

Try it at Ideone.

\$\endgroup\$
2
\$\begingroup\$

C#, 25 bytes

p.Zip(a,(x,y)=>x*y).Sum()

Sample program:

using System.Linq;
using Xunit;
public class Tests {
    [Fact]
    public void Cost() {
        int[] p = new [] { 2, 7, 5, 1, 9 };
        int[] a = new [] { 1, 2, 3, 2, 3 };
        int r = p.Zip(a, (x, y) => x * y).Sum();
        Assert.Equal(60, r);
    }
}
\$\endgroup\$
2
\$\begingroup\$

R, 8 18 bytes

sum(scan()*scan())

Now takes input from stdin.

\$\endgroup\$
1
  • \$\begingroup\$ Submissions must either be full programs or functions. \$\endgroup\$ – TuxCrafting Oct 4 '16 at 19:42
2
\$\begingroup\$

Julia 1.0, 13 bytes

Building up on Donat's solution. Thanks to Chartz Belatedly for pointing out the issue with inputs

x/y=sum(x.*y)

Try it online!

\$\endgroup\$
1
1
\$\begingroup\$

MATL, 2 bytes

*s

Try it online!

*     % Element-wise product of two implicit inputs
s     % Sum of array, implicitly displayed
\$\endgroup\$
1
\$\begingroup\$

Java, 67 bytes

a->{int p=0;for(int i=-1;++i<a[0];)p+=a[i+1]*a[i+a[0]+1];return p;}

Slightly ungolfed:

public static int pay(int...a){
  int p=0;
  for(int i=-1;++i<a[0];){
    p+=a[i+1]*a[i+a[0]+1];
  }
  return p;
}
\$\endgroup\$
1
\$\begingroup\$

Perl 6, 13 bytes

{[+] [Z*] $_}

Input is a list of two lists

Example:

say {[+] [Z*] $_}(  ((2,7,5,1,9),(1,2,3,2,3))  );
# 60

Explanation:

{          # bare block lambda with implicit parameter 「$_」

  [+]      # reduce using addition operator

    [Z*]   # reduce using zip meta-operator combined with multiplication operator

      $_   # the argument ( list of lists )
}
\$\endgroup\$
1
\$\begingroup\$

TI-BASIC, 3 tokens

sum(L₁L₂

Input in L₁ and L₂, output in Ans.

Usage:

{1,2,3→L1
{4,5,6→L2
prgmCOST

Output: 32

\$\endgroup\$
1
\$\begingroup\$

05AB1E, 3 bytes

øPO

Try it online!

øPO  # full program
  O  # sum of...
 P   # products of...
     # (implicit) each element in...
     # implicit input...
ø    # with each element from the first sublist paired with the corresponding element from the second sublist
     # implicit output
\$\endgroup\$
1
\$\begingroup\$

R, 5 bytes

`%*%`

Try it online!

That's the dot-product built-in in R...

\$\endgroup\$
1
\$\begingroup\$

JavaScript, 33 bytes

a=>b=>a.reduce((c,d,e)=>c+d*b[e])

Takes input as ([p[0],...,p[n-1])([a[0],...,a[n-1]]).

\$\endgroup\$
1
\$\begingroup\$

C, 58 56 bytes

f(n,p,a,s)int*p,*a;{for(s=0;n;s+=p[--n]*a[n]);return s;}

Input is n: number of elements, p:array 1, a:array 2.

Somewhat un-golfed:

f(n,p,a,s)
    int*p,*a;
{
    for(s=0;n;s+=p[--n]*a[n]);
    return s;
}
\$\endgroup\$
1
1
\$\begingroup\$

APL (Dyalog Classic), 3 bytes

+.×  ⍝ My code is self-documenting

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Vyxal s, 1 byte

*

Try it Online!

Magic.

\$\endgroup\$
0
\$\begingroup\$

PHP, 46 Bytes

<?foreach($_GET[a]as$n)$s+=$n[0]*$n[1];echo$s;

48 Bytes

<?=array_sum(array_map(array_product,$_GET[a]));
\$\endgroup\$
0
\$\begingroup\$

Zsh, 31 bytes

This is the core function. The challenge didn't say anything about setting up variables or output so that's all external. If there's a better way to take array product in Zsh, please comment! Try it online.

for i ({1..$n})((S+=p[i]*a[i]))
\$\endgroup\$
0
\$\begingroup\$

Julia 1.0, 14 bytes

sum((*).(x,y))

Try it online!

\$\endgroup\$
0
\$\begingroup\$

PowerShell, 43 bytes

function d($a,$b){$a|%{$r+=$_*$b[$i++]};$r}

Try it online!

Basically, just calculate the dot product.

\$\endgroup\$
0
\$\begingroup\$

PowerShell, 36 bytes

param($p,$q)$p|%{$r+=$_*$q[$i++]}
$r

Try it online!

\$\endgroup\$
0
\$\begingroup\$

BQN, 3 bytes

+´×

Try it!

dot product

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.