display Each value Count from an array - c#

I have a string[] with values like
string[] s = { "saravanan", "Karthick", "Jackson", "saravanan" };
I want to see below output
saravanan occures 2 times
Karthick occures 1 times
Jackson occures 1 times
How can I do this without using List or Dictionary
This is what I have tried so far:
int i, j;
String[] s = {"saravanan", "Karthick", "Jackson", "saravanan"}
Console.WriteLine("Number of Times occured Each Values");
for (i = 0; i < s.Length; i++)
{
int count = 0;
for (j = 0; j < s.Length; j++)
{
if (s[i] == (s[j]))
{
count++;
}
}
Console.WriteLine(s[i]+"is count="+count);
}
That code produces this output:
Number of Times occured Each Values
saravananis count=2
Karthickis count=1
Jacksonis count=1
saravananis count=2

Usually, we solve such problems (querying) via Linq
string[] s = new[] {
"saravanan", "Karthick", "Jackson", "saravanan" };
var result = string.Join(Environment.NewLine, s
.GroupBy(item => item)
.Select(chunk => $"{chunk.Key} occures {chunk.Count()} times"));
Console.Write(result);
In case of nested loops (your current code) we should not print out the same name several times. Let's introduce bool appeared if name has been appeared before
string[] s = new[] {
"saravanan", "Karthick", "Jackson", "saravanan" };
for (i = 0; i < s.Length; i++) {
int count = 0;
bool appeared = false;
for (j = 0; j < s.Length; j++) {
if (s[i] == (s[j])) {
// Names are same. Do we have the name before?
if (j < i) {
// If yes we have no need to loop any more
appeared = true;
break;
}
count++;
}
}
// if name has been appeared already we shouldn't print it out
if (!appeared)
Console.WriteLine(s[i] + "is count=" + count);
}

Since you don't want "saravanan" to appear twice in your output. Then you could use an empty string as a sentinel value. When you find matches that increase the count, blank out that element and have checks in place to skip the element when you run across it later.
using System;
public class Program
{
public static void Main()
{
string[] s = { "saravanan","KArthick","Jackson","saravanan" };
for (int i = 0; i < s.Length; i++)
{
// Skip empty element
if (string.IsNullOrEmpty(s[i]))
{
continue;
}
int count = 1;
for (int j = i + 1; j < s.Length; j++)
{
// Skip empty element
if (string.IsNullOrEmpty(s[i]))
{
continue;
}
if (s[i] == s[j])
{
count++;
// Clear the element to indicate the element as already been counted
s[j] = string.Empty;
}
}
Console.WriteLine("{0} occurs {1} times", s[i], count);
}
}
}
Result
saravanan occurs 2 times
KArthick occurs 1 times
Jackson occurs 1 times
Fiddle Demo

you can use linq group option like this:
String[] s = {"saravanan", "Karthick", "Jackson", "saravanan"};
Console.WriteLine("Number of Times occured Each Values");
var groupArray = s.GroupBy(x => x);
foreach (var group in groupArray)
{
Console.WriteLine(group.Key + "is count=" + group.Count());
}

Related

Count Matching Subsequences

This is what I need to do:
Create a function that receives a text string, and a search string, and returns how many times the search string appears in the string, as a subsequence of its letters in order.
For example, if you receive the word "Hhoola" and the substring "hola", the answer would be 4, because you could take the first H with the first O (and with the L and with the A), the first H with the second O, the second H with the first O, or the second H with the second O. If you receive "hobla", the answer would be 1. If you receive "ohla", the answer would be 0, because after the H there is no O to complete the sequence in order.
This is what i got so far:
int count = 0;
void Function(string text, string subText)
{
for (int i = 0; i < text.Length; i++)
{
if (text[i] == subText[0])
{
for (int j = 0; j < subText.Length; j++)
{
if (text[i + j] != subText[j])
{
break;
}
if (j == subText.Length - 1)
{
count++;
}
}
}
}
}
string text = Console.ReadLine().ToLower();
string subText = Console.ReadLine().ToLower();
ReceibeText(text, subText);
The code should look like this. Code doesn't work but is close.
public class SubSequences
{
string input = "";
string word = "";
int count = 0;
public void FindMatches(string input, string word)
{
this.input = input;
this.word = word;
FindMatchesRecursive(0, 0);
}
public void FindMatchesRecursive(int inputIndex, int wordIndex)
{
for (int i = inputIndex; i < input.Length - word.Length; i++ )
{
for (int j = wordIndex; j < input.Length - word.Length; j++)
{
if (word.Substring(i) == input.Substring(j))
{
if (j == word.Length)
{
FindMatchesRecursive(i + 1, j + 1);
}
else
{
Console.WriteLine("Word Matches");
}
}
}
}
}

Unable to find long string in array string - C#

I'm trying to find a long string in another string. For this I've been using G[i].Contains(P[arr]) but for some reason the code just skips that condition. In my case : G[I] is 1000 character long and P[arr] is 475. When I debug I can see strings are not trimmed and also I have verified that P[ARR] is part of G[I] in Notepad++ so it should definitely satisfy a condition.
for (int arr = 0; arr < P.Length; arr++)
{
for (int i = a; i < G.Length; i++)
{
if (G[i].Contains(P[arr]))
{
if (!(b == 0))
{
a = i + 1;
continue;
}
primary_1 = (a == 0) ? G[i].IndexOf(P[arr]) : primary;
++count;
a = i + 1;
Console.WriteLine("Counter: " + i);
break;
}
}
}

How do we count the number of occurrence from left to right and continue until we have consecutive numbers?

So the code that I wrote, is for the number of occurrence. Suppose in the sample part which is mentioned, if I give an input Array of {2,1,1,1,3}, it will give me the count of Number 2 occurrence as 1. Now, I'm struggling to write the code in a manner so that it gives me the count only if it's continuous from left to right. Suppose, if my array is {1,1,1,2,0}, only then it will give me the total occurrence of 1 as 3, but not if it's {1,0,1,2,1} or {0,0,1,1,1} or {1,1,2,2,1}
static void Evaluate_V5B(int[] window, int[] PayCombos,)
{
int[] Counters1 = new int[3];
for (int index0 = 0; index0 < 5; index0++)
{
Console.Write("{0} ", window[index0]);
int symbol = window[index0];
Counters1[symbol]++;
}
Console.WriteLine();
for (int indexJ = 0; indexJ < Counters1.Length; indexJ++)
{
Console.WriteLine("{0}", Counters1[indexJ]);
}
}
This will take the 1st element in the array and return continuous occurrences from left to right. If that element found anywhere else it will return 0 as count:
static void Evaluate(int[] array)
{
var count = 1;
var first = array[0];
for (int i = 1; i < array.Length; i++)
{
if(array[i] == first)
{
count++;
}
else{
for (int j = i + 1; j < array.Length; j++)
{
if(first == array[j]) {
count = 0;
break;
}
}
break;
}
}
Console.WriteLine($"Count of Number {first} occurrence is {count}");
}
This function will find the number of continuous occurrences of a specific number num in the array nums, if it is the first number.
static int ContinuousOccurrences(int[] nums, int num)
{
if (nums[0] == num)
{
int continuousOccurrences =
nums.TakeWhile(x => x == num).Count();
int totalOccurrences =
nums.Where(x => x == num).Count();
if(continuousOccurrences == totalOccurrences)
{
return continuousOccurrences;
}
else
{
return 0;
}
}
return 0;
}
If you want to know the number of continuous occurrences of the first number, call the function this way:
ContinuousOccurrences(nums, nums[0])

Function not returning array

I have this function to initiate a two dimensional array:
static Array Matrix(int Rows, int Columns)
{
int[,] LotteryArray = new int[Rows,Columns];
for (int i = 0; i < LotteryArray.GetLength(0); i++)
{
for (int j = 0; j < LotteryArray.GetLength(1); j++)
{
LotteryArray[i, j] = RandomNum(1, 46);
Console.Write("{0,3},", LotteryArray[i, j]);
}
Console.WriteLine();
}
return LotteryArray;
}
Then I have this which is supposed to give me a one dimensional array and see how many numbers in the winning array are in the matrix:
int RowNum = 1;
int Prediction = 0;
Console.WriteLine("Your winning numbers are!");
Console.WriteLine("------------------------");
int[] Winner = new int[6];
for (int i = 0; i < Winner.Length; i++) //this loop is to initiate and print the winning numbers
{
Winner[i] = RandomNum(1, 46); //the numbers are supposed to be between 1 and 45, so i tell it to do it until 46 because the upper limit is exclusive
Console.Write("{0,3},", Winner[i]);
}
Console.WriteLine();
Console.WriteLine("------------------------"); //these two lines are for aesthetics
Matrix(Rows, Columns);
foreach (int i in Winner)
{
for (int j = 0; j<LotteryArray; j++)
{
if (Winner[i] == j)
{
Prediction++;
if (j % 6 == 0) { RowNum++; }
}
Console.WriteLine("you got {0} correct prediction in row number {1}",Prediction,RowNum);
RowNum = 1;
}
}
It's telling me LotteryArray doesn't exist in the current context.
LotteryArray is a variable within another method. You cannot access it in the scope you are showing.
You can do get the return from your method into a variable and then use it.
var LotteryArray = Matrix(Rows, Columns);
foreach (int i in Winner)
{
for (int j = 0; j<LotteryArray; j++)
{
if (Winner[i] == j)
{
Prediction++;
if (j % 6 == 0) { RowNum++; }
}
Console.WriteLine("you got {0} correct prediction in row number {1}",Prediction,RowNum);
RowNum = 1;
}
}
LotteryArray is a variable declared in Matrix method, and is not visible outside.

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.

Categories

Resources