Skip to content

Instantly share code, notes, and snippets.

@boriphuth
Created January 30, 2018 08:59
Show Gist options
  • Save boriphuth/cdbe706af91f41f67a9c45be9eaa5269 to your computer and use it in GitHub Desktop.
Save boriphuth/cdbe706af91f41f67a9c45be9eaa5269 to your computer and use it in GitHub Desktop.
Convert Number and Array pair sum to given
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
//https://codeworldtechnology.wordpress.com/2017/01/07/find-all-pair-of-array-of-integers-whose-sum-is-equal-to-a-given-number-in-c/
class Program
{
static void Main(string[] args)
{
Console.WriteLine(GetString(0));
Console.WriteLine(GetString(5));
Console.WriteLine(GetString(10));
var data = 123456789;
var data1 = data.ToString();
Console.WriteLine(GetString(123456789));
// var result1 = canSum(new[] { 7, 8, 1, 4, 6 }, 15);
var result = canSum(new[] { 1, 4, 6, 7, 8 }, 15);
var result1 = Find(new[] { 1, 4, 6, 7, 8 }, 15);
Console.WriteLine(result == true);
int[] arr = { 2, 4, 3, 5, 6, -2, 4, 7, 8, 9 };
int n = 7;
PrintPairs(arr, n);
Console.ReadKey();
}
static string[] words = "Zero,One,Two,Three,Four,Five,Six,Seven,Eight,Nine,Ten".Split(',');
public static string GetString(int value)
{
// See if the number can easily be represented by an English word.
// ... Otherwise, return the ToString result.
if (value >= 0 && value <= 10)
{
return words[value];
}
return value.ToString();
}
static bool canSum(int[] nums, int target)
{
var set = new HashSet<int>(nums);
//var pair = nums.Where(n => set.Contains(target - n)));
return nums.Any(n => set.Contains(target - n));
//for (int i = 0; i < nums.Length; i++)
//{
// for (int j = i + 1; j < nums.Length; j++)
// {
// if ((nums[i] + nums[j]) == target) return true;
// }
//}
//return false;
}
private static void PrintPairs(int[] arr, int n)
{
List<int> arrayItemList = new List<int>();
foreach (var item in arr)
{
int remainingvalue = n - item;
if (arrayItemList.Contains(remainingvalue))
{
Console.WriteLine($"({ item},{remainingvalue})");
}
else
{
arrayItemList.Add(item);
}
}
}
public class MatchingPairs
{
public int lower;
public int upper;
}
static List<MatchingPairs> Find(int[] array, int sumToFind)
{
var query = from f in array
from g in array
where (f < g) && (f + g == sumToFind)
select new MatchingPairs { lower = f, upper = g };
return query.ToList();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment