+ 6
Add n Addends (a challenge)
Here's a little challenge: Define a function called add() which adds an indeterminate number of addends and outputs the result as a mathematical expression. e.g. if the function is called like this: add(2, 3, 4, 5, 6, 8) you get this: 2 + 3 + 4 + 5 + 6 + 8 = 28 If you're using Python, the function code block can't be more than 3 lines. No user input is required, but the function should be flexible enough to take any number of addends.
16 Réponses
+ 2
Python one line code.
https://code.sololearn.com/c8JbI5F1lE5M/?ref=app
+ 11
https://code.sololearn.com/cin4XhifxrZc/?ref=app
+ 4
C++ first number is the count of numbers after:
#include <iostream>
#include <cstdarg>
using namespace std;
void add(int count, ...) {
va_list numbers;
va_start(numbers, count);
int total = 0;
for(int i = 0; i < count; ++i) {
int num = va_arg(numbers, int);
total += num;
cout << num << " ";
if(i < count-1)
cout << "+ ";
}
va_end(numbers);
cout << "= " << total;
}
int main() {
add(7,2,3,4,5,6,7,8);
return 0;
}
+ 4
javascript:
let add = (...args) =>
args.join(' + ') + ' = ' + args.reduce((a, b) => a + b);
+ 3
ahh ok. I'll modify. Thought the function/method was supposed to return the sum.
+ 2
Java:
public class Program
{
public static void main(String[] args) {
add(2,3,4,5,6,7,8);
}
static void add(int... numbers) {
int total = 0;
String output = "";
for(int num: numbers) {
total += num;
output += num + " + ";
}
System.out.println(output.substring(0, output.length() - 2) + "= " + total);
}
}
+ 2
@Chaotic and @P R So far so good, but the output needs to be '2 + 3 + 4 + 5 + 6 + 8 = 28', not just '28' 🙂
+ 2
Already saw and changed it :P
+ 2
Hats off to Pythonistas @vari93 and @Sivan Tal for 2 lines and 1 line of code, respectively. (I thought I was clever reducing 8 lines to 3 🙃)
+ 2
@Baptiste that's impressive. Not sure I understand the '=n=n' configuration at the end of the outputs?
+ 1
@Schilndlabua Nice one-liner, but same comment as for the other codes so far:
The output needs to be, e.g., '2 + 3 + 4 + 5 + 6 + 8 = 28', not just '28'.
+ 1
Here in C++, I had done this one a long time ago :)
https://code.sololearn.com/cx9tgwF9sRd4/?ref=app
+ 1
It is a debug purpose, the result that should be and the real result ^^
0
@ChaoticDog your C++ solution is not real C+p, rather C ^^