I've am trying to read a large text file and output the distinct
words in it along with it's count. I've tried a couple of attempts so far, and
this is by far the fastest solution I have come up with.
private static readonly char[]
separators = { ' ' };
public IDictionary<string, int> Parse(string path)
{
var wordCount =
new Dictionary<string, int>();
using (var fileStream
= File.Open(path, FileMode.Open, FileAccess.Read))
using (var
streamReader = new StreamReader(fileStream))
{
string line;
while ((line =
streamReader.ReadLine()) != null)
{
var words =
line.Split(separators,
StringSplitOptions.RemoveEmptyEntries);
foreach (var word in words)
{
if (wordCount.ContainsKey(word))
{
wordCount[word] = wordCount[word]
+ 1;
}
else
{
wordCount.Add(word, 1);
}
}
}
}
return wordCount;
}
string in with and without using reverse function in C#
/// REVERSE
STRIG WITH USING C# FUNCTIONS
public class ReverseStrigs
{
static void Main(string[] a)
{
Console.WriteLine("Enter string for
Reverse");
string str
= Console.ReadLine();
Console.ReadLine();
}
public static string Reverse(string str)
{
return new string(str.Reverse().ToArray());
}
}
/// REVERSE
STRIG WITHOUT USING C# FUNCTIONS
public class ReverseStrigs
{
static void Main(string[] ax)
{
Console.WriteLine("Enter string for
Reverse");
string str
= Console.ReadLine();
Console.WriteLine(Reverse(str));
Console.ReadLine();
}
public static string Reverse(string str)
{
int strLength
= str.Length;
char[] array
= new char[strLength];
for (int i = 0; i <
strLength; i++)
{
array[i] = str[strLength - 1 - i];
}
return new string(array);
}
}
Question 2: Swap neighbor char in string, For Example string “TAPAN” would be:

Answer:
- public static string SwapNeighbourChar(string strToSwap)
- {
- char[] arraStr = strToSwap.ToCharArray();
- StringBuilder strbuild = new StringBuilder();
- for (int i = 0; i <= arraStr.Length - 1; i++)
- {
- if (i != arraStr.Length - 1)
- {
- strbuild.Append(arraStr[i + 1]);
- }
- strbuild.Append(arraStr[i]);
- i = i + 1;
- }
- return strbuild.ToString();
- }
- static void Main(string[] args)
- {
- Console.WriteLine(clsSwapNeighbour.SwapNeighbourChar("TAPAN"));
- Console.ReadLine();
- }
Prime number program using ASP.Net C#
Noted point: The number 0 and 1
are not considered prime numbers.
Prime Numbers : 2, 3, 5, 7, 11, 13, 17, 19, 23,
29, 31, 37, 41, 43, 47, 53, 59, 61..
Answer:
Calling above method,
- public static bool IsPrimeNumbers(int number)
- {
- bool returnMsg = false;
- for (int i = 2; i <= number; i++)
- {
- if ((number % i) == 0 && number != i)
- {
- returnMsg = false;
- return returnMsg;
- }
- else if (number == i)
- {
- returnMsg = true;
- return returnMsg;
- }
- }
- return returnMsg;
- }
- static void Main(string[] args)
- {
- string message = clsIsPrimeNumber.IsPrimeNumbers(17) == true ? "Prime Number" : "Not a prime number";
- Console.WriteLine(message);
- message = clsIsPrimeNumber.IsPrimeNumbers(4) == true ? "Prime Number" : "Not a prime number";
- Console.WriteLine(message);
- message = clsIsPrimeNumber.IsPrimeNumbers(11) == true ? "Prime Number" : "Not a prime number";
- Console.WriteLine(message);
- message = clsIsPrimeNumber.IsPrimeNumbers(21) == true ? "Prime Number" : "Not a prime number";
- Console.WriteLine(message);
- Console.ReadLine(); 5
Factorial Number using Recursion in
ASP.Net C#
Hello everyone, I am going to
share the code sample for factorial number by
using recursion. The factorial number formula. i.e.
L(n)
= n*(n-1)
The example in detail as given below.
public class factorial_Number
{
/// <summary>
/// FACTORIAL
OF A NUMBER USING RECURSION.
/// </summary>
public static int FactorialNumber(int number)
{
if (number
== 0)
{
return 1;
}
return number *
(FactorialNumber(number - 1));
}
static void Main(string[] ax)
{
int number
= Convert.ToInt16(Console.ReadLine());
//CALL
FACTORIAL FUNCTION.
Console.WriteLine(FactorialNumber(number));
Console.ReadLine();
} }
Find the most occurrence of a character in string C#?
public class CountMostOccurrenceCharacters
{
static void Main(string[] ss)
{
int last =
0;
Console.WriteLine("Enter
the charactor string");
foreach (char chr in Console.ReadLine())
{
int count;
dicList.TryGetValue(chr , out count);
count++;
if (count >
last)
{
last = count;
}
dicList[chr ] = count;
}
{
if (charList.Value
== last)
{
Console.WriteLine("{0}:
{1}", charList.Key, charList.Value);
}
}
Console.ReadLine();
}
}
fibonacci series using for loop in c# program
- public static void PrintFibonacciSeries(int limit)
- {
- int digit1, digit2, digit3;
- digit1 = 0;
- digit2 = 1;
- digit3 = digit1 + digit2;
- Console.WriteLine(digit1);
- Console.WriteLine(digit2);
- Console.WriteLine(digit3);
- for (int i = 0; i < limit; i++)
- {
- digit1 = digit2;
- digit2 = digit3;
- digit3 = digit1 + digit2;
- Console.WriteLine(digit3);
- }
- }
- static void Main(string[] args)
- {
- clsFibonacci.PrintFibonacciSeries(10);
- Console.ReadLine();
- }
A simple program that find which of the names in the `names` array occurs the maximum number of times
using System;
using System.Collections.Generic;
namespace Patterns
{
public class FrequentItemFinder
{
/**
* A simple class to hold one data item and the count of
* how many times it has occurred
*/
public class ItemCount
{
private String item;
private int count;
public ItemCount(String item, int count)
{
this.item = item;
this.count = count;
}
public ItemCount(String item)
{
this.item = item;
this.count = 0;
}
public String getItem() { return item; }
public int getCount() { return count; }
public void increment() { count += 1; }
}
/**
* Take an array of items and return an array of unique items
* with counts
*/
public interface ItemCounter
{
/**
* Analyze the list, figure out the number of times
* each unique data item appears in the list, and return
* a list of ItemCount objects corresponding to each
* unique data item and the number of times it occurs
* in the list
*/
List<ItemCount> analyze(List<String> list);
}
public class DictionaryBasedItemCounter : ItemCounter
{
public List<ItemCount> analyze(List<string> list)
{
var wordCount = new Dictionary<string, int>();
foreach (var word in list)
{
if (wordCount.ContainsKey(word))
{
wordCount[word] = wordCount[word] + 1;
}
else
{
wordCount.Add(word, 1);
}
}
List<ItemCount> itemCounts = new List<ItemCount>();
foreach (var word in wordCount)
{
itemCounts.Add(new ItemCount(word.Key, word.Value));
}
return itemCounts;
}
}
/**
* An implementation of ItemCounter interface which
* sorts the input list using Collections.sort and then
* counts the number of occurrences of each item by
* making one pass through the sorted list
*/
public class SortBasedItemCounter : ItemCounter
{
public SortBasedItemCounter() { }
public List<ItemCount> analyze(List<String> list)
{
list.Sort();
List<ItemCount> icList = new List<ItemCount>();
String prev = null;
ItemCount counter = null;
foreach (var s in list)
{
if (s.Equals(prev))
{
// Same item. Just increment the count
counter.increment();
}
else
{
// Item changed. Add previous item count to icList
if (counter != null)
icList.Add(counter);
counter = new ItemCount(s, 1);
prev = s;
}
}
// The last item has not yet been added to the list
if (counter != null)
{
icList.Add(counter);
}
return icList;
}
}
/**
* A class that allows us to choose between different
* implementations of the ItemCounter interface based on the name
* All the different implementations must be registered with this
* class before they can be used.
*/
public class ItemCounterChooser
{
Dictionary<String, Type> registeredCounters =
new Dictionary<String, Type>();
public void register(String name, Type counterType)
{
registeredCounters.Add(name, counterType);
}
/**
* Return an instance of the ItemCounter class that was
* registered using `name`
* Return null if `name` was not registered at all.
*/
public ItemCounter getItemCounterInstance(String name)
{
Type icType = registeredCounters[name];
if (icType == null)
return null;
return (ItemCounter)Activator.CreateInstance(icType);
}
}
private ItemCounterChooser itemCounterChooser;
private ItemCounter itemCounter;
public FrequentItemFinder()
{
itemCounterChooser = new ItemCounterChooser();
itemCounter = null;
itemCounterChooser.register("SortBased",
typeof(SortBasedItemCounter));
itemCounterChooser.register("DictionaryBased",
typeof(DictionaryBasedItemCounter));
}
public void selectItemCounterChooser(String itemCounterName)
{
itemCounter = itemCounterChooser.getItemCounterInstance(
itemCounterName);
}
/**
* Find which string appears the most number of times in list
* Use the ItemCounter to get a list of name,count pairs
* and then find which one appears the maximum number of times.
* In case of a tie, pick any one randomly
*/
public String findFrequentString(List<String> list)
{
if (itemCounter == null)
if (list.Count > 50)
selectItemCounterChooser("DictionaryBased");
else
selectItemCounterChooser("SortBased");
int max = -1;
String frequentItem = null;
foreach (var icount in itemCounter.analyze(list))
{
if (icount.getCount() > max)
{
max = icount.getCount();
frequentItem = icount.getItem();
}
}
return frequentItem;
}
/**
* A simple program that find which of the names in the `names`
* array occurs the maximum number of times
*/
public static void Main(String[] args)
{
FrequentItemFinder frequentItemFinder =
new FrequentItemFinder();
List<String> names = new List<String>{
"Navin Kabra",
"Amit Paranjape",
"Navin Kabra",
"Amit Paranjape1",
"Navin Kotkar",
"Gaurav Kotkar"};
String f = frequentItemFinder.findFrequentString(names);
Console.WriteLine("The most frequent name is: " + f);
}
}
}
How to know the API version is not Latest
in input.text file
Mail App, Authentication API, v6
Video Call App, Authentication API, v7
Mail App, Data Storage API, v10
Chat App, Data Storage API, v11
Mail App, Search API, v6
Chat App, Authentication API, v8
Chat App, Presence API, v2
Video Call App, Data Storage API, v11
Video Call App, Video Compression API, v3
public void CheckOldVersionApp(string path = @"c:\Input.txt")
{
string line;
// Read the file and display it line by line.
List<string> lineStrings = new List<string>();
using (var fileStream = File.Open(path, FileMode.Open, FileAccess.Read))
using (var streamReader = new StreamReader(fileStream))
{
while ((line = streamReader.ReadLine()) != null)
{
lineStrings.Add(line);
}
}
Dictionary<string, int> apiVersionNumbers = new Dictionary<string, int>();
foreach (var lineString in lineStrings)
{
string[] words = lineString.Split(',');
if (!apiVersionNumbers.ContainsKey(words[1]))
{
apiVersionNumbers.Add(words[1], Convert.ToInt32(words[2].Substring(2)));
}
else
{
int versionNumber = apiVersionNumbers[words[1]];
if (versionNumber <= Convert.ToInt32(words[2].Substring(2)))
{
apiVersionNumbers[words[1]] = Convert.ToInt32(words[2].Substring(2));
}
}
}
List<string> appNames = new List<string>();
foreach (var lineString in lineStrings)
{
string[] words = lineString.Split(',');
int versionNumber = apiVersionNumbers[words[1]];
if (versionNumber > Convert.ToInt32(words[2].Substring(2)))
{
if (!appNames.Contains(words[0]))
appNames.Add(words[0]);
}
}
foreach (var appName in appNames)
{
Console.WriteLine(appName);
}
}
-----------------------------------------------------------------------------------------------------------------------------
Group Anagrams
{
var result = find(inputs.ToList());
Group Anagrams
static void Main(string[] args)
{
var inputs =new [] { "abcd", "dcba", "cabd", "xyz", "yxz", "uml" };
var result = find(inputs.ToList());
}
No comments:
Post a Comment