Check if the sum of two different numbers in an array equal a variable number?
It looks like you're trying to see if there are any two numbers in the array that add up to the specified value x
. However, your code just picks two numbers at random and checks if those numbers add up.
Ruby has the Array#combination
method, which generates all combinations of a given length:
def contains_pair_for_sum?(arr, n)
!!arr.uniq.combination(2).detect { |a, b| a + b == n }
end
A few things to note:
First, we named it according to Ruby conventions: each word is
separated_by_underscores
. The?
on the end means that the method is a predicate method and returns a true or false value.Inside the method, a few things happen. Let's look at that line, piece by piece.
arr
: We take the array that was passed in.<...>.uniq
: We only look at the unique elements (because the OP wants to pick two different numbers).<...>.combination(2)
: We ask for all combinations from the array of length 2. If the array was[4, 5, 6]
, we'd get[[4, 5], [4, 6], [5, 6]]
.<...>.detect { |a, b| a + b == n }
: We look for the first combination that adds up ton
. If we found one, that's the result of that method. Otherwise, we getnil
.!!<...>
: Finally, we take the result we got fromdetect
and negate it twice. The first negation produces a Boolean value (true
if the value we got wasnil
, orfalse
if it's anything else); the second negation produces a Boolean value that's identical to the truth value of the first negation. This is a Ruby idiom to coerce a result into being eithertrue
orfalse
.
Let's see it in action:
array = [4, 5, 9, 7, 8]
contains_pair_for_sum?(array, 11)
# => true (because [4, 7] sums to 11)
contains_pair_for_sum?(array, 17)
# => true (because [9, 8] sums to 17)
contains_pair_for_sum?(array, 100)
# => false (no pair matched)
Java/ Sum of any two values in an array of numbers
Should I make another array to storage sum of any two elements?
If it is required to provide only the number of the pairs equal to the given number, array is not required, simple if
statement allows to check the condition and increment the counter (and print the pair if needed):
if (a[i] + a[j] == x) {
pairs++;
System.out.println("Found a pair: " + a[i] + " + " + a[j]);
}
What kind of method use to get the sum of any two elements in the array?
Two nested loops:
for (int i = 0; i < a.length - 1; i++) {
for (int j = i + 1; j < a.length; j++) {
//...
}
}
How list the number of combinations?
The total number of possible pairs is calculated by the formula of decreasing progression from n - 1 to 1: S = n * (n - 1) / 2
, so for n = 5 it is 5 * 4 / 2 = 10
.
The number of matching pairs is simply counted in the innermost loop.
Pair of elements from a specified array whose sum equals a specific target number
that map value you're seeing is a lookup table and that twoSum method has implemented what's called Dynamic Programming
In Dynamic Programming, you store values of your computations which you can re-use later on to find the solution.
Lets investigate how it works to better understand it:
twoSum([10,20,40,50,60,70], 50)
//I removed one of the duplicate 10s to make the example simpler
In iteration 0:
value is 10. Our target number is 50. When I see the number 10 in index 0, I make a note that if I ever find a 40 (50 - 10 = 40) in this list, then I can find its pair in index 0.
So in our map, 40 points to 0.
In iteration 2:
value is 40. I look at map my map to see I previously found a pair for 40.
map[nums[x]]
(which is the same as map[40]
) will return 0.
That means I have a pair for 40 at index 0.
0 and 2 make a pair.
Does that make any sense now?
Unlike in your solution where you have 2 nested loops, you can store previously computed values. This will save you processing time, but waste more space in the memory (because the lookup table will be needing the memory)
Also since you're writing this in javascript, your map can be an object instead of an array. It'll also make debugging a lot easier ;)
Find the two numbers that will equal the desired sum
Please have a look at this simple code because I'm pretty sure this is what you need:
function detectPair(sum, array) { for (i=0; i<array.length; i++) { for (j=0; j<array.length; j++) { if (i == j) continue; else if (array[i] + array[j] === sum) return [array[i], array[j]]; } }; return null;}
let sum = 28;let array = [3, 5, 7, 9, 4, 8, 5, 12, 4, 9, 16, 5]
console.log(detectPair(sum, array)); //return would be [12,16]
Array b are equal to the sum the digit of the array element a
There are multiple problems in your code:
you do not test the return value of
scanf()
so any invalid or missing input will cause undefined behavior because the destination variables will not be updated.There is a new variable
n
defined in thewhile
loop, so the original variable in the outer scope is never modified byscanf()
.form
andsum_digit
are both incorrect: you should compute the sum insum_digit()
with a loop and store all sums in a loop inform
.
Here is a modified version:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define MAX 100
void form(int [], int [], int);
int sum_digits(int);
void print (int [], int);
int main() {
int n;
for (;;) {
printf("Enter n:");
if (scanf("%d", &n) != 1)
return 1;
if (n >= 1 && n <= MAX)
break;
printf("Incorrect value: %d\n", n);
}
int a[MAX], b[MAX];
printf("Enter elements of array a:\n");
for (int i = 0; i < n; i++) {
printf("%d. element:", i + 1);
if (scanf("%d", &a[i]) != 1)
return 1;
}
form(a, b, n);
print(b, n);
return 0;
}
void form(int a[MAX], int b[MAX], int n) {
for (int i = 0; i < n; i++) {
b[i] = sum_digits(a[i]);
}
}
int sum_digits(int s) {
int sum = 0;
/* this loop handles positive and negative numbers alike */
while (s != 0) {
sum = sum + s % 10;
s = s / 10;
}
/* return the positive sum of digits */
return abs(sum);
}
void print(int b[MAX], int n) {
for (int i = 0; i < n; i++) {
printf("%d ", b[i]);
}
printf("\n");
}
Compare items from two arrays to see if they sum to 10
If you haven't figured out the solution, here it is:
private static string NumberOfTens(int number1, int number2)
{
//Store 10-pairs in a new variable
int tenPairs = 0;
// Need variables to define the dice - arrays starting at 1?
int[] die1 = Enumerable.Range(1, number1).ToArray();
int[] die2 = Enumerable.Range(1, number2).ToArray();
//Compare each item from die1 to each value from die2 to see if they add up to 10.
for (int i = 0; i < die1.Length; i++)
{
for (int j = 0; j < die2.Length; j++)
{
if (die1[i] + die2[j] == 10)
{
tenPairs++;
}
}
}
//return a string with the message: "There are X total ways to get the sum 10."
string resultMsg = "There are " + tenPairs + " total ways to make 10.";
return resultMsg;
}
here is how to use it :
Console.WriteLine(NumberOfTens(5, 15));
php find sum of two numbers in a dynamic array and see if they equal a given number
Sounds like all you need is to use array_slice before using array_sum.
Something like:
function subarr_sum($array,$offset,$length) {
$newarray = array_slice($array,$offset,$length);
return array_sum($newarray);
}
Related Topics
What Are Some Examples of Using Nokogiri
Text_Field_With_Auto_Complete Inside Form_For
Error Nomethoderror: Undefined Method 'Debug_Rjs=' for Actionview::Base:Class
Add External Style Sheet in Rails Project
Installing Rails with Gem, Error Loading Command: Install Undefined Method 'Invoke_With_Build_Args'
Re-Opened Nested Module Anomaly in Ruby
Activeadmin: Adding Delete for a Nested Resource
Ruby String Strip Defined Characters
How to Declare a Rake Task That Depends on a Parameterized Task
Deadlock Detected with Capybara-Webkit
Carrierwave Cannot Remove Image
Using %I and %I Symbol Array Literal
Why Does Using '-Webkit-Appearance: None' on a Select Option in Osx Make The Text Disappear
How to Create Pretty JSON in Chef (Ruby)
Ruby: How to Load .Rb File in The Local Context
Rails Console Fails with 'Switch to Inspect Mode' in Windows