Count the frequency of element of an array in C# [duplicate] - c#

This question already has answers here:
Counting the number of times a value appears in an array
(7 answers)
Closed 3 years ago.
I want to write a code in C#.
In fact, I want to write a program in C# such that the program receives a list of numbers and then receives another number and finally check how many times the received number occurs in the given list.
I searched and obtained the following code in C# from GitHub.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Array9a
{
class Program
{
static void Main(string[] args)
{
int i, j,N,count;
Console.WriteLine("Enter the Maximum Range for the Array");
N = Convert.ToInt32(Console.ReadLine());
string[] a = new string[N];
int[] freq = new int[N];
for (i = 0; i < N; i++)
{
a[i] = Console.ReadLine();
freq[i] = -1;
}
for (i = 0; i < N; i++)
{
count = 1;
for (j = i + 1; j < N; j++)
{
if (a[i] == a[j])
{
count++;
freq[j] = 0;
}
}
if (freq[i] != 0)
{
freq[i] = count;
}
}
for (i = 0; i < N; i++)
{
if (freq[i] != 1)
{
Console.Write("{0}{1}", a[i], freq[i]);
}
}
Console.ReadLine();
}
}
}
The output of the mentioned code is the frequency of all elements. But I want to modify the code such that the program receives a number and just check the frequency of the given number.
Recently I am learning C#. Thanks in advance

That seems pretty straight forward.
var result = freq.Count(x => x == theNumberToCheck);

Very simple you can use linq ,for example
int frequency = 1;
int[] arr = new int[] { 1, 4, 6, 7, 1, 2, 6 ,1};
var res =arr.Count(x => x == frequency);
Console.WriteLine(res);//print 3

To get counts of every number:
var distinctValues = theList.Distinct().ToArray();
for(int i = 0; i < distinctValues.Length; i++)
{
var cnt = theList.Count(e => e == distinctValues[i]);
Console.WriteLine($"Element {distinctValues[i]}, count {cnt}");
}

Related

Trying to find Frequency of elements in array

I am trying to count how many times a number appears in an array 1 (a1) and then trying to print out that number by storing it in array 2 (a2) just once and then try to print array 2. But first using for loop and a function, I will check that if a number already exist in array 2 then move to next index in array 1, unfortunateley this code is not working; can someone please help me in trying to fix it, I don't need some complex solutions like dictionaries or lists athe moment, although it might be helpful too. thanks, I am not an expert in programming and I try to practise it in my free time, so please help me.
I just want this code to be fixed for my understanding and knowledge
class Program
{
static void Main(string[] args)
{
int i, j;
int[] a1 = new int[10];
int[] a2 = new int[10];
int[] a3 = new int[10];
//takes an input
for (i = 0; i < a1.Length; i++)
{
a1[i] = Convert.ToInt32(Console.ReadLine());
}
for (i = 0; i < a1.Length; i++)
{
Cn(a1, a2); //calls in function
i++; //increments is if true
int count = 0;
for (j = 0; j < a1.Length; j++)
{
//if a number matches with a number in second array
if (a1[i] == a1[j])
{
//do count ++
count++;
// store that number into second array
a2[i] = a1[i];
}
}
//store the number of counts in third array
a3[i] = count;
}
for (i = 0; i < a2.Length; i++)
{
if (a2[i] != 0)
{
Console.WriteLine(a2[i]);
}
}
Console.ReadLine();
}
//function to check if element at current index of array 1 exists in array 2 if yes than break
public static void Cn (int[] aa1, int [] aa2)
{
int k, j;
for ( k = 0; k < aa1.Length; k++)
{
for (j = 0; j < aa2.Length; j++)
{
if (aa1[k] == aa2[j])
break;
}
}
}
}
You probably want to do a group by count:
int[] a1 = new int[10];
var rnd = new Random();
//takes an input
for (int i = 0; i < a1.Length; i++)
{
a1[i] = Convert.ToInt32(rnd.Next(0, 11)); // or Console.ReadLine()
}
var grouped = a1
.GroupBy(x => x)
.Select(g => new
{
Item = g.Key,
Count = g.Count()
}).ToList(); // ToList() is optional, materializes the IEnumerable
foreach (var item in grouped)
{
Console.WriteLine($"number: {item.Item}, count: {item.Count}");
}
This uses a Hash algorithm internally.
You can solve this without a Hash or Dictionary but it wouldn't be very efficient because you need to do lots of linear searches through the arrays.
The advantage of a Hash algorithm is that your lookups or groupings are much faster than if you loop over a complete array to find / increment an item.

HeapSort Algorythm from txt file to list of arrays doesn't Sort the numbers

So I have to make HeapSort Algorythm for University using pseudocode I was given (only for heapsort). And I have to use input and output file. But for now I have only made input file which is working fine since it loads the txt file and writes down all the numbers in Console. So the problem is that after adding sorting methods to Main nothing changes. Also I decided to make a test for every method and all of them writes down my numbers once and that is it. I am not really good with sorting so it is hard for me to find the issue. Also because it is from pseudocode I had to use and no the code I could do for myself. So Do You know what cause thats issue that the sorting doesn't occure?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Win32;
using System.IO;
using System.Windows.Forms;
namespace Zad4
{
class Program
{
void Heapify(List<int> array, int i, int n)
{
int largest, temp;
int parent = i;
int left = 2 * i + 1;
int right = 2 * i + 2;
if (left < n && array[left] > array[parent])
{
largest = left;
}
else
{
largest = parent;
}
if (right < n && array[right] > array[largest])
{
largest = right;
}
if (largest != i)
{
temp = array[i];
array[i] = array[largest];
array[largest] = temp;
Heapify(array, largest, n);
}
}
void BuildHeap(List<int> array, int n)
{
int i;
for (i = (n - 1) / 2; i >= 0; i--)
{
Heapify(array, i, n);
}
}
void HeapSort(List<int> array, int n)
{
int i, temp;
for (i = n - 1; i >= 0; i--)
{
temp = array[0];
array[0] = array[n - 1];
array[n - 1] = temp;
n = n - 1;
Heapify(array, 0, n);
Console.WriteLine(string.Join(" ", array));
}
}
static void Main(string[] args)
{
int n = 0;
Program A = new Program();
StreamReader myFile =
new StreamReader("C:\\Users\\dawid\\Desktop\\C#\\Heapsort\\dane.txt");
string myString = myFile.ReadToEnd();
myFile.Close();
char rc = (char)10;
String[] listLines = myString.Split(rc);
List<List<int>> listArrays = new List<List<int>>();
for (int i = 0; i < listLines.Length; i++)
{
List<int> array = new List<int>();
String[] listInts = listLines[i].Split(' ');
for (int j = 0; j < listInts.Length; j++)
{
if (listInts[j] != "\r")
{
array.Add(Convert.ToInt32(listInts[j]));
}
}
listArrays.Add(array);
A.BuildHeap(array, n);
A.HeapSort(array, n);
}
foreach (List<int> array in listArrays)
{
foreach (int i in array)
{
Console.WriteLine(string.Join(" ", array));
}
}
Console.WriteLine();
Console.ReadLine();
}
}
}
So the solution I found is just changing the way I read my txt file and the most important one was bad use of my methods. So that is how it looks now and it sorting well. Maybe I shouldn't ask a question since I got an answer on my own. But well. There You go:
static void Main(string[] args)
{
Program A = new Program();
string[] array = System.IO.File.ReadAllLines(#"C:\Users\dawid\Desktop\C#\Heapsort\dane.txt");
int[] arrayInt = Array.ConvertAll(array, int.Parse);
A.BuildHeap(arrayInt, arrayInt.Length);
A.HeapSort(arrayInt, arrayInt.Length);
Console.WriteLine(string.Join(" ", arrayInt));
Console.ReadLine();
}

Change this nested for loop to recursion [duplicate]

This question already has an answer here:
Creating all possible arrays without nested for loops [closed]
(1 answer)
Closed 6 years ago.
I posted this similar, previous question, but I was not very clear.
I have the following code:
int N=4;
int[] myArray = new int[N];
for (int i1 = 1; i1 < N; i1++)
myArray[0]=i1;
for (int i2 = 1; i2 < N; i2++)
myArray[1]=i2;
for (int i3 = 1; i3 < N; i3++)
myArray[2]=i3;
for (int i4 = 1; i4 < N; i4++)
{
myArray[3]=i4;
foreach (var item in myArray)
Console.Write(item.ToString());
Console.Write(Environment.NewLine);
}
This outputs the following:
1111
1112
1113
1121
1122
1123
1131
....
3332
3333
Is there a simple way to change this nested for loop to recursion? I am not very skilled at programming, so the simpler, the better. I am not worried about how efficient the code is.
I, effectively, would like to be able to change the int N in my code to different numbers, without having to add or remove anything from my code.
EDIT
Here is what I have so far:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sandbox
{
class Program
{
static void Main(string[] args)
{
int class_length = 4;
int[] toric_class = Enumerable.Repeat(1, class_length).ToArray();
Recursion(toric_class, class_length, 1, 3);
Console.Read();
}
static void Recursion(int[] toric_class, int length, int number, int spot)
{
if (number < 4)
{
toric_class[spot] = number;
foreach (var item in toric_class)
{
Console.Write(item.ToString());
}
Console.Write(Environment.NewLine);
Recursion(toric_class, length, number + 1, spot);
}
}
}
}
This only outputs
1111
1112
1113
I am unsure of where to go from here.
public static void Set(int[] array, int index, int N)
{
if (index == N)
{
foreach (var item in array)
Console.Write(item.ToString());
Console.Write(Environment.NewLine);
return;
}
for (int i = 1; i < N; i++)
{
array[index] = i;
Set(array, index + 1, N);
}
}
And call it this way:
int N = 4;
int[] myArray = new int[N];
Set(myArray, 0, N);
If you want just to simplify and generalize the solition, you don't want any recursion:
// N - length of the array
// K - kind of radix; items of the array will be in [1..K] range
private static IEnumerable<int[]> Generator(int N = 4, int K = 3) {
int[] items = Enumerable
.Repeat(1, N)
.ToArray();
do {
yield return items.ToArray(); // .ToArray() : let's return a copy of the array
for (int i = N - 1; i >= 0; --i)
if (items[i] < K) {
items[i] += 1;
break;
}
else
items[i] = 1;
}
while (!items.All(item => item == 1));
}
Test
string test = string.Join(Environment.NewLine, Generator(4)
.Select(items => string.Concat(items)));
Console.Write(test);
Outcome:
1111
1112
1113
1121
1122
...
3321
3322
3323
3331
3332
3333

removing elements from this C# program [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Any chance to get unique records using Linq (C#)?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace WaysOf100
{
class WaysOf100Test
{
static void Main(string[] args)
{
WaysOf100 test= new WaysOf100();
test.Go();
test.EliminateDuplicates();
}
}
class WaysOf100
{
List<string> results = new List<string>();
public void Go()
{
int num = 5, temp=0;//to store the intermediate difference
for (int i = 1; i <num; i++)
{
temp = num - i;
for (int j = 1; j <= temp; j++)
{
if (temp % j == 0)
{
//Console.Write(i + " ");
string text = "";
text = i.ToString();
for (int k = 1; k <= (temp / j); k++)
{
//Console.Write(j + " ");
text += j.ToString();
}
char[] rev = text.ToCharArray();
Array.Reverse(rev);
if(!(results.Contains(rev.ToString())))
results.Add(text);
}
}
}
}
public void EliminateDuplicates()
{
//To eliminate the duplicates
/*for (int i = 0; i < results.Count; i++)
{
for (int j = 0; j < results.Count; j++)
{
if (!(results[i].Equals(results[j])))
{
char [] rev = results[j].ToCharArray();
Array.Reverse(rev);
if (results[i]==rev.ToString())
results.Remove(rev.ToString());
}
}
}*/
foreach (var result in results)
{
Console.WriteLine(result);
}
Console.WriteLine("Total number of elements is :{0}",results.Count);
}
}
}
The result so far is
11111
122
14
2111
23
311
32
41
This is what I want in short : the reverse of 41 is 14 and 14 already exists in the list so i don't want to add 41. Similarly, the reverse of 32 is 23 which also exists and hence 32 should not be added. But this piece of could which I've written to achieve the functionality is not giving the desired results
if(!(results.Contains(rev.ToString())))
results.Add(text);
The problem you are having is that rev.ToString()' returns "System.Char[]" and not the string value you wanted/expected. For your logic, try the following:
public void EliminateDuplicates()
{
//Eliminate the duplicates
for (int i = 0; i < results.Count; i++)
{
for (int j = 0; j < results.Count; j++)
{
if (!(results[i].Equals(results[j])))
{
char[] rev = results[j].ToCharArray();
char[] forward = results[i].ToCharArray();
Array.Reverse(rev);
bool bEqual = true;
for( int n = 0 ; n < results[j].Length && true == bEqual ; n++ )
{
if( rev[n] != forward[n] )
{
bEqual = false;
}
}
if( true == bEqual)
results.Remove(results[j] );
}
}
}
foreach (var result in results)
{
Console.WriteLine(result);
}
Console.WriteLine("Total number of elements is : {0} ", results.Count);
}
Solved by myself finally..
if (!(results.Contains(new string(rev))))
results.Add(text);
changed the rev.ToString() as new string(rev) and works fine now. What I want is achieved. Thanks a lot for the help guys
Is reverse the only case you want to check for? One approach would be to canonicalize your results to e.g. sorted order before comparing. So transform both 132 and 213 to 123 before comparing.

How to divide an array into 3 parts with the sum of each part roughly equal

I have an arranged array and I want to divide it into 3 parts so that their sum are closest to each other.
Ex: I have this array:
10, 8, 8, 7, 6, 6, 6, 5
so it'll be divided into 3 part like:
p1 {10,8} sum = 18
p2 {8,7,6} sum = 21
p3 {6,6,5} sum = 17
The original poster already has a working solution (noted in comments) to split the array into two parts with equal sums; call this split2. The three-part version can be constructed using split2.
Add to the array a new number equal to one-third of the sum of the original numbers.
Split the array into two parts using split2.
One part has the number that was added; remove it.
Split the other part into two using split2.
This is like two-Partition problem which is NP-Hard but not in strong sense, you can have an O(nK) algorithm for it where K is size of your input sum, See pseudo polynomial time algorithm for subset sum, Also See my answer for divide-list-in-two-parts-that-their-sum-closest-to-each-other, but in your case you should just add another dimension to process it.
// calculate total
total = 0;
for(i = 0; i != size; ++i) {
total += array[i];
}
// partition
n_partitions = 3;
current_partition = 1;
subtotal = array[0];
for(i = 1; i != size; ++i) {
if(subtotal + array[i] > total / n_partitions) {
// start new partition;
current_partition++;
subtotal = array[i];
} else {
// push to current partition
subtotal += array[i];
}
}
Try the following code
int total = 0, partSum = 0, partIndex = 0;
int noOfParts = 3; //Initialize the no. of parts
int[] input = { 10, 8, 8, 7, 6, 6, 6, 5 };
int[] result = new int[noOfParts]; //Initialize result array with no. of locations equal to no. of parts, to store partSums
foreach (int i in input) //Calculate the total of input array values
{
total += i;
}
int threshold = (total / noOfParts) - (total / input.Length) / 2; //Calculate a minimum threshold value for partSum
for (int j = input.Length - 1; j > -1; j--)
{
partSum += input[j]; //Add array values to partSum incrementally
if (partSum >= threshold) //If partSum reaches the threshold value, add it to result[] and reset partSum
{
result[partIndex] = partSum;
partIndex += 1;
partSum = 0;
continue;
}
}
if (partIndex < noOfParts) //If no. of parts in result[] is less than the no. of parts required, add the remaining partSum value
{
result[partIndex] = partSum;
}
Array.Reverse(result);
foreach (int k in result)
{
Console.WriteLine(k);
}
Console.Read();
I've tested this with various values in array(arranged in descending order) and also with different value for no. of parts(3,4,5...) and got good results.
Updated with code:
The approach I suggest is as follows (with code below):
Create data structures (Collections etc) to represent the number of output parts that you need (in your example 3)
Sort the input array in descending order.
Iterate through the elements of the input array and for each value:
pick an output part to place the value in (this should be the output part currently with the lowest overall sum..)
add the value to the selected output part
With the above logic, you will always be adding to the output part with the lowest overall value (which will help to keep the parts of similar overall value).
(in the code sample below I have skipped the array sorting step as your example is already sorted)
Code:
// the input array
int[] inputArray = new int[] { 10, 8, 8, 7, 6, 6, 6, 5 };
// the number of parts you want
int numberOfOutputParts = 3;
// create the part structures
List<Part> listOfParts = new List<Part>();
for(int i =0; i < numberOfOutputParts; i++)
{
listOfParts.Add(new Part());
}
// iterate through each input value
foreach (int value in inputArray)
{
// find the part with the lowest sum
int? lowestSumFoundSoFar = null;
Part lowestValuePartSoFar = null;
foreach(Part partToCheck in listOfParts)
{
if (lowestSumFoundSoFar == null || partToCheck.CurrentSum < lowestSumFoundSoFar)
{
lowestSumFoundSoFar = partToCheck.CurrentSum;
lowestValuePartSoFar = partToCheck;
}
}
// add the value to that Part
lowestValuePartSoFar.AddValue(value);
}
The code for the Part class used above (although you could use something better is as follows):
public class Part
{
public List<int> Values
{
get;
set;
}
public int CurrentSum
{
get;
set;
}
/// <summary>
/// Default Constructpr
/// </summary>
public Part()
{
Values = new List<int>();
}
public void AddValue(int value)
{
Values.Add(value);
CurrentSum += value;
}
}
Could you try my sample, this may help you
My Algorithm:
1/ Calculate avg value of the array numbers by the number of output array (exp:value=3 in your post)
2/ Sum the array numbers until the Sum has min gap compare to the avg value (calculated in 1/)
3/ Do step 2 until you go to the end of the array numbers
I using C# 3.5 to test
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;
namespace WindowsFormsApplication2
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
ArrayList inputValue = new ArrayList();
int avgValue = 0;
bool isFinish = false;
private void button1_Click(object sender, EventArgs e)
{
#region Init data
isFinish = false;
avgValue = 0;
inputValue.Clear();
listBox1.Items.Clear();
//assum you input valid number without space and in desc sorting order
string[] arrNumber = textBox1.Text.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
int numberOfBreak = 3;
int record = Convert.ToInt32(arrNumber[0]);//update the record with the maximum value of the array numbers
for (int i = 0; i < arrNumber.Length; i++)
{
inputValue.Add(Convert.ToInt32(arrNumber[i]));
}
foreach (object obj in inputValue)
{
avgValue += (int)obj;
}
avgValue = avgValue / numberOfBreak;
#endregion
int lastIndex = 0;
while (!isFinish)
{
int index = GetIndex(lastIndex);
string sResult = "";
for (int i = lastIndex; i <= index; i++)
{
sResult += inputValue[i].ToString() + "-";
}
listBox1.Items.Add(sResult);
if (index + 1 < inputValue.Count)
{
lastIndex = index + 1;
}
sResult = "";
}
}
private int GetIndex(int startIndex)
{
int index = -1;
int gap1 = Math.Abs(avgValue - (int)inputValue[startIndex]);
int tempSum = (int)inputValue[startIndex];
if (startIndex < inputValue.Count - 1)
{
int gap2 = 0;
while (gap1 > gap2 && !isFinish)
{
for (int i = startIndex + 1; i < inputValue.Count; i++)
{
tempSum += (int)inputValue[i];
gap2 = Math.Abs(avgValue - tempSum);
if (gap2 <= gap1)
{
gap1 = gap2;
gap2 = 0;
index = i;
if (startIndex <= inputValue.Count - 1)
{
startIndex += 1;
}
else
{
isFinish = true;
}
if (startIndex == inputValue.Count - 1)
{
index = startIndex;
isFinish = true;
}
break;
}
else
{
index = i - 1;
break;
}
}
}
}
else if (startIndex == inputValue.Count - 1)
{
index = startIndex;
isFinish = true;
}
else
{
isFinish = true;
}
return index;
}
}
}

Categories

Resources