Using foreach and hashtable to find common element in three arrays - c#

I am trying to find common element in three arrays. I am using Hashtable for this purpose as many people suggested here that it gives O(n) and its better.
Here is the code I have tried..
using System;
using System.Collections;
using System.Linq;
using System.Text;
namespace ConsoleApplication2
{
class newAttempt
{
static void Main()
{
Hashtable hm = new Hashtable();
int[] a = new int[] { 1, 2, 3, 4, 5 };
int[] b = new int[] { 2, 4, 6, 7, 8 };
int[] c = new int[] { 3, 4, 5, 6, 9 };
for (int i = 0; i <= a.Length - 1; i++)
{
hm.Add(i, a[i]);
}
foreach(int k in b)
if (hm.Contains(k))
{
foreach (int j in c)
if (hm.Contains(j))
Console.WriteLine(j);
}
Console.ReadKey();
}
}
}
I am getting ouput as
3
4
3
4
I want my program to stop looking when it finds out that 4 is the only element which is common in this case. Please help.

Use list.Intersect function , this is example .
var list1 = new string[] {"4", "5", "6", "7", "8"};
var list2 = new string[] {"4", "5"};
var commonElement = list1.Intersect(list2);
foreach (string s in commonElement ) Console.WriteLine(s);
Output:
4
5
For more information ,
This is the example of Intersection or array !

int[] a = new int[] { 1, 2, 3, 4, 5 };
int[] b = new int[] { 2, 4, 6, 7, 8 };
int[] c = new int[] { 3, 4, 5, 6, 9 };
var result = a.Intersect(b).Intersect(c).ToArray(); // 4

You can use the Extension Method Intersect from linq.
var hm1 = new HashSet<int>(new[] {1, 2, 3, 4, 5});
var hm2 = new HashSet<int>(new[] { 2, 4, 6, 7, 8 });
var hm3 = new HashSet<int>(new[] { 3, 4, 5, 6, 9 });
var intersection = hm1.Intersect(hm2).Intersect(hm3);
foreach (var i in intersection)
{
Console.WriteLine(i);
}

You're not checking if the inner number is the same as the outer loop's number, so essentially you're printing all numbers in b and c that are in hm. Replace your inner loop by:
foreach (int j in c)
if (j==k) // hm.Contains(j) is covered by the previous hm.Contains(k)
Console.WriteLine(j);
Edit: The other answer's intersect method is preferable for C#. Alternately, you can convert the arrays to a Set before performing this operation to improve performance for longer sequences.

Try changing the code to something like
foreach (int k in b)
if (hm.Contains(k))
{
foreach (int j in c)
if (j == k && hm.Contains(j)) //changes here
Console.WriteLine(j);
}
If you wish to exit the for loops once a match has been found you can try something like
bool found = false;
for (int bIndex = 0; !found && bIndex < b.Length; bIndex++)
{
int k = b[bIndex];
if (hm.Contains(k))
{
for (int cIndex = 0; !found && cIndex < c.Length; cIndex++)
{
int j = c[cIndex];
if (j == k && hm.Contains(j))
{
Console.WriteLine(j);
found = true;
}
}
}
}

in your code you are checking the first array with second array.if match then the first array with third array.
but what we need is,if the first to array have a match hen we want to check if that value is present in third array.only that particular value.
but your checking the whole values of first array with the third array
public static void main(String args[])
{
Hashtable hm = new Hashtable();
int[] a = new int[] { 1, 2, 3, 4, 5 };
Integer[] b = new Integer[]{ 2, 4, 6, 7, 8 };
int[] c = new int[] { 3, 4, 5, 6, 9 };
for (int i = 0; i <= a.length - 1; i++)
{
hm.put(i,a[i]);
}
for(int k:b)
{
if (hm.contains(k))
{
for(int j:c)
{
if (k==j) //here is the change
{
System.out.print(j);
}
}
}
}
}
}

You can use Linq. Intersect method will be good for such purpose.
But, do you want to find out intersections just using loops and Hashtable?
this code should work:
Hashtable hm = new Hashtable();
int[] a = new int[] { 1, 2, 3, 4, 5 };
int[] b = new int[] { 2, 4, 6, 7, 8 };
int[] c = new int[] { 3, 4, 5, 6, 9 };
foreach (var iA in a)
{
foreach (var iB in b)
{
if (iA == iB && !hm.ContainsKey(iA))
{
hm.Add(iA, iA);
}
}
}
foreach (var iC in c)
{
if (hm.ContainsKey(iC))
{
Console.WriteLine(iC);
hm.Remove(iC);
}
}

Related

Using foreach to get the even numbers out of array c#

I have this homework assignment where I have array called myArr with values 4, 9, 2, 5, 1, 4, 8, 3, 3 and I have to extract even numbers out of there and place them in myOtherArray and then printing them with foreach. I tried doing the code but I kinda got stuck since I know it won't work.
Here is my attempt:
int[] myArr = { 4, 9, 2, 5, 1, 4, 8, 3, 3 };
int num = 0;
int[] myOtherArr = new int[num];
for (int i = 0; i < myArr.Length; i++)
{
if (myArr[i] % 2 == 0)
{
num++;
}
}
Num is the counter to count how many even numbers are there, but right now I don't know how to save them into myOtherArray because I get the error that Index was outside the bounds of the array.
for (int i = 0; i < myArr.Length; i++)
{
if (myArr[i] % 2 == 0)
{
myArr[i] = myOtherArr[i];
}
}
Right now I don't know how to do this. Please help I want to be ready for my exam comming soon.
Thank you all in forward for your answers.
you can also try using Array.FindAll() built-in method to achieve this , instead of looping construct. Please try below code.
var myArr = new int[] { 4, 9, 2, 5, 1, 4, 8, 3, 3 };
var myOtherArr = Array.FindAll(myArr, v => v%2 == 0);
Thank you.
I would try something like this
int[] myArr = { 4, 9, 2, 5, 1, 4, 8, 3, 3 };
var i=0;
foreach (var item in myArr)
if (item % 2 == 0) i++;
var myOtherArr= new int[i];
i=0;
foreach (var item in myArr)
if (item % 2 == 0) { myOtherArr[i] = item; i++; }
I did it this way because you don't have to figure out the length of the array.
int[] myArr = { 4, 9, 2, 5, 1, 4, 8, 3, 3 };
int[] myOtherArr;
List<int> cache = new List<int>();
//goes through each number in this array and stores the ones for that round in "num".
//If the number is "% 2 == 0" then it will be added to a list.
foreach (int num in myArr)
{
if (num % 2 == 0)
{
cache.Add(num);
}
}
//the list is converted and stored in your array
myOtherArr = cache.ToArray();
//all numbers are displayed
foreach (int num in myOtherArr)
{
Console.WriteLine(num);
}
but you can also write it like this (I like to do this, for example).
int[] myArr = { 4, 9, 2, 5, 1, 4, 8, 3, 3 };
int[] myOtherArr;
List<int> cache = new List<int>();
//goes through each number in this array and stores the ones for that round in "num".
//If the number is "% 2 == 0" then it will be added to a list.
foreach (int num in myArr)
if (num % 2 == 0)
cache.Add(num);
//the list is converted and stored in your array
myOtherArr = cache.ToArray();
//all numbers are displayed
foreach (int num in myOtherArr)
Console.WriteLine(num);
The problem is here:
int[] myOtherArr = new int[num]; // you initialize the array to 0 length.
Try this:
int[] myArr = { 4, 9, 2, 5, 1, 4, 8, 3, 3 };
int num = 0;
for (int i = 0; i < myArr.Length; i++)
{
if (myArr[i] % 2 == 0)
{
num++;
}
}
int[] myOtherArr = new int[num];
int j = 0;
for (int i = 0; i < myArr.Length; i++)
{
if (myArr[i] % 2 == 0)
{
myOtherArr[j] = myArr[I];
j++;
}
}

Check for pair in an array with a given sum

I was working on this problem in c#,
Write a program that finds in given array of integers a sequence of given sum S (if present).
here is how it should work
Input: {4, 3, 1, 4, 2, 5, 4}, S = 11
Output: "First Sequence: {4, 2, 5}, 4 + 2 + 5 = 11", "Second Sequence: {2, 5, 4}, 2 + 5 + 4 = 11"
But what I get as output is the correct sum, I tried for other numbers as well
Output from console directly:
11
11
My code:
using System.Collections.Generic;
using System.Linq;
class EntryPoint
{
static void Main(string[] args)
{
int[] arr = { 4, 3, 1, 4, 2, 5, 4 };
int S = 11;
int p = 0;
int[] sumSeq = { };
for (int i = 0; i < arr.Length; i++)
{
p = 0;
for (int j = 0; j < arr.Length; j++)
{
if (arr[j]!=arr[i])
{
p += arr[j] + arr[i];
if (p == S)
{
Console.WriteLine(p);
break;
}
}
}
}
}
}

System.ArgumentOutOfRangeException: 'Index was out of range. copy from one list to another

I built following programm, but I get the out of range error. Basically I would like to copy values from one list to another (from a to b):
List<int> a = new List<int> { 99, 2, 3, 4, 5, 6 };
List<int> b = new List<int>(6);
for ( int i = 0; i < a.ToArray().Length; i++ )
{
a[i].ToString().Insert(0, b[i].ToString());
}
for ( int i = 0; i < a.ToArray().Length; i++ )
{
Console.WriteLine(b[i]);
}
Console.ReadKey();
Just copy the values from the first list to the second list by calling ToList() on the first list:
List<int> uzytkownik = new List<int>() { 99, 2, 3, 4, 5, 6 };
List<int> uzytkownik1 = uzytkownik.ToList();//only values are copied, not the reference to the first list
for (int i = 0; i < uzytkownik1.Count; i++)
{
Console.WriteLine(uzytkownik1[i]);
}
Console.ReadKey();
If you have to use a for loop then:
List<int> uzytkownik = new List<int>() { 99, 2, 3, 4, 5, 6 };
List<int> uzytkownik1 = new List<int>();
for (int i = 0; i < uzytkownik.Count; i++)
{
uzytkownik1.Add(uzytkownik[i]);
}
for (int i = 0; i < uzytkownik1.Count; i++)
{
Console.WriteLine(uzytkownik1[i]);
}
Console.ReadKey();
Have a look at the Array.CopyTo method.
https://learn.microsoft.com/en-us/dotnet/api/system.array.copyto?view=netframework-4.8
The List<T> already has a method for that kind of work. List<T>.AddRange(IEnumerable<T>)
List<int> a = new List<int> { 99, 2, 3, 4, 5, 6 };
List<int> b = new List<int>(6);
b.AddRange( a );
.net fiddle example

C# Multiply Each row of array by set of factors

I have a multidimensional array and I want to multiply each row of it by a single dimensional array containing factors to create a new multidimensional array. However, the number of rows in the multidimensional array will vary from one run to the next, so I'll need a way to loop the multiplication through each row of the multidimensional array until the last row is reached.
Here is a simple example, I have multidimensional array:
{ { 1, 2, 3, 4}, { 5, 6, 7, 8}, { 9, 10, 11, 12} }
and I want to multiply each row by:
{0.5, 0.4, 0, 0.8}
to get:
{ { 1*0.5, 2*0.4, 3*0, 4*0.8}, { 5*0.5, 6*0.4, 7*0, 8*0.8}, { 9*0.5, 10*0.4, 11*0, 12*0.8} }
I've tried to use .Length within a for loop using the example code.
double [] factors = {0.5, 0.4, 0, 0.8};
int [,] myarray = new int [3,4] {
{ 1, 2, 3, 4},
{ 5, 6, 7, 8},
{ 9, 10, 11, 12}
};
double [] output = new double[myarray.Length];
for(int i = 0; i < myarray.Length; ++i)
output[i] = myarray[i] * factors;
I'm getting syntax errors that extension method 'Length' cannot be applied to type int, and also indexing with [] cannot be applied to type int.
I'd suggest a ragged array. Multidimensional arrays exist, but are poorly supported and almost nobody uses them. If you use a jagged array, you can be more concise. More importantly, you can be more intentional about it:
double[][] myArray = getMeSomeData();
double[] factors = getMeSomeRowFactors();
foreach (var row in myArray)
{
MultiplyRow(row, factors)
}
. . .
void MultiplyRow( double[] row, double[] factors )
{
for ( int col = 0 ; col < row.length ; ++col )
{
row[col] = row[col] * factors[col];
}
}
Or even better: use Linq:
double[][] myArray = getMeSomeData();
double[] factors = getMeSomeRowFactors();
myArray = myArray
.Select( row => row.Select( (cell, i) => cell * factors[i] ).ToArray() )
.ToArray()
;
Or even [arguably] better;
double[][] myArray = getMeSomeData();
double[] factors = getMeSomeRowFactors();
myArray = myArray
.Select( Multiply(factors) )
.ToArray()
;
. . .
Func<double,int,double[]> Multiply( double[] factors )
{
return (cell, i) => cell * factors[i];
}
I am not sure if you find it useful, but you can achieve it by using MathNet.Numerics:
PM> Install-Package MathNet.Numerics
using MathNet.Numerics.LinearAlgebra.Double;
using System.Linq;
...
var myarray = new double[3, 4]
{
{ 1, 2, 3, 4},
{ 5, 6, 7, 8},
{ 9, 10, 11, 12}
};
var factors = new double[4] { 0.5, 0.4, 0, 0.8 };
var matrix1 = Matrix.Build
.DenseOfArray(myarray);
var matrix2 = Matrix.Build
.DenseOfRows(Enumerable.Repeat(factors, matrix1.RowCount));
var res = matrix1.PointwiseMultiply(matrix2).ToArray();
You can get the length of each dimension by using the method GetLength:
double[,] output = new double[myarray.GetLength(0), myarray.GetLength(1)];
for (int i = 0; i < myarray.GetLength(0); i++)
{
for (int j = 0; j < myarray.GetLength(1); j++)
{
output[i, j] = myarray[i, j] * factors[j];
}
}
In case your array is huge, you can speed up the calculation by using all processors/cores of your PC:
Parallel.For(0, myarray.GetLength(0), i =>
{
for (int j = 0; j < myarray.GetLength(1); j++)
{
output[i, j] = myarray[i, j] * factors[j];
}
});

Find Largest subarray( descending order)in a list of array c#

I need to find the largest subarray. For example: array list { 1, 4, 7, 3, -3, -4, -1, 4, 2, 1 } need to find the largest subarray where the numbers are decreasing.
As from the list { 7, 3, -3, -4 } is one subarray and { 4, 2, 1 }, as the earlier one is biggest need to print that.
Simply
var results = new List<int>();
for (var i = 0; i < input.Length; i++)
{
// how we check
var current = new List<int>();
// just to know if we are are going down
var lastValue = input[i];
// second loop make sure we stop if the numbers aren't going down
for (var j = i; j < input.Length && input[j] <= lastValue; j++)
{
current.Add(input[j]);
lastValue = input[j];
}
// Update the result depending on the criteria
if (current.Count >= results.Count)
{
results = current;
}
}
// print your awesome numbers
foreach (var value in results)
{
Console.Write($"{value}, ");
}
You can test it here
You could try this LINQ approach:
var array = new[] { 1, 4, 7, 3, -3, -4, -1, 4, 2, 1 };
var descending_subarrays =
array
.Skip(1)
.Aggregate(new [] { array.Take(1).ToList() }.ToList(), (a, x) =>
{
if (a.Last().Last() > x)
{
a.Last().Add(x);
}
else
{
a.Add(new [] { x }.ToList());
}
return a;
})
.OrderByDescending(x => x.Count)
.ToList();
That gives:
You can then just pick the find answer with a descending_subarrays.First().

Categories