Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,877 questions

51,801 answers

573 users

How to print all distinct 4 elements from an array that have the same given sum in C#

1 Answer

0 votes
using System;

public class MyClass
{
	public static void getDistinct4Elements(int[] arr, int sum) {
		Array.Sort(arr);

		int size = arr.Length;

		for (int i = 0; i <= size - 4; i++) {
			for (int j = i + 1; j <= size - 3; j++) {
				int k = sum - (arr[i] + arr[j]);

				int fromstart = j + 1;
				int fromend = size - 1;

				while (fromstart < fromend) {
					if (arr[fromstart] + arr[fromend] < k) {
						fromstart++;
					}

					else if (arr[fromstart] + arr[fromend] > k) {
						fromend--;
					}

					else {
						Console.Write(arr[i] + ", " + arr[j] + ", ");
						Console.WriteLine(arr[fromstart] + ", " + arr[fromend]);
						fromstart++;
						fromend--;
					}
				}
			}
		}
	}
	public static void Main(string[] args)
	{
		int[] arr = new int[] {4, 8, 1, 5, 9, 0, 3, 7};

		int sum = 18;

		getDistinct4Elements(arr, sum);
	}
}





/*
run:
   
0, 1, 8, 9
0, 3, 7, 8
0, 4, 5, 9
1, 3, 5, 9
1, 4, 5, 8
   
*/

 



answered Aug 20, 2022 by avibootz
...