Getting multiple strings of the same lenght from array [closed] - c#

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
i need to take the longest line, or multiple if there is, out of string array of lines and write it out in console together with its posision in the array, i managed to find the longest one but im unable to find multiple strings. Can anyone help? (sorry if this is hard to understand).

One way you could do this is store the longest lines and their indexes in a dictionary. Start with a temporary variable to hold the longest line, and then walk through the array. As we find lines that are equal length, add them to our dictionary. If we find a longer line, set the dictionary to a new one, with just that line added to it, and continue.
For example:
public static void PrintLongestLinesAndIndexes(string[] input)
{
if (input == null)
{
Console.WriteLine("No data");
return;
}
var longestLine = string.Empty;
var longestLines = new Dictionary<int, string>();
for (int i = 0; i < input.Length; i++)
{
// If this line is longer, reset our variables
if (input[i].Length > longestLine.Length)
{
longestLine = input[i];
longestLines = new Dictionary<int, string> {{i, input[i]}};
}
// If it's the same length, add it to our dictionary
else if (input[i].Length == longestLine.Length)
{
longestLines.Add(i, input[i]);
}
}
foreach (var line in longestLines)
{
Console.WriteLine($"'{line.Value}' was found at index: {line.Key}");
}
}
Then we can use it like:
public static void Main(string[] args)
{
PrintLongestLinesAndIndexes(new[]
{
"one", "two", "three", "four", "five",
"six", "seven", "eight", "nine", "ten"
});
GetKeyFromUser("\nDone! Press any key to exit...");
}
Output
Another way to do this would be to use Linq to select the items and their indexes, group them by the item's length, then order them by the length and select the first group:
public static void PrintLongestLinesAndIndexes(string[] input)
{
Console.WriteLine(string.Join(Environment.NewLine,
input.Select((item, index) => new {item, index})
.GroupBy(i => i.item.Length)
.OrderByDescending(i => i.Key)
.First()
.Select(line => $"'{line.item}' was found at index: {line.index}")));
}

Related

How to import Dictionary text file and check for word matches?

I generate a random string of 500 characters and want to check for words.
bliduuwfhbgphwhsyzjnlfyizbjfeeepsbpgplpbhaegyepqcjhhotovnzdtlracxrwggbcmjiglasjvmscvxwazmutqiwppzcjhijjbguxfnduuphhsoffaqwtmhmensqmyicnciaoczumjzyaaowbtwjqlpxuuqknxqvmnueknqcbvkkmildyvosczlbnlgumohosemnfkmndtiubfkminlriytmbtrzhwqmovrivxxojbpirqahatmydqgulammsnfgcvgfncqkpxhgikulsjynjrjypxwvlkvwvigvjvuydbjfizmbfbtjprxkmiqpfuyebllzezbxozkiidpplvqkqlgdlvjbfeticedwomxgawuphocisaejeonqehoipzsjgbfdatbzykkurrwwtajeajeornrhyoqadljfjyizzfluetynlrpoqojxxqmmbuaktjqghqmusjfvxkkyoewgyckpbmismwyfebaucsfueuwgio
I import a Dictionary Words txt file and check the string to see if it contains each word. If a match is found, it's added to a list.
I read using Dictionary<> is faster than Array for a words list.
When I use that method, I can see the cpu working the foreach loop in the debugger, and my loop counter goes up, about 10,000+ times in 10 seconds, but the loop continues on forever and does not return any results.
When I use Array for Dictionary, the program works, but slower at around 500 times in 10 seconds.
Not Working
Using Dictionary<>
// Random Message
public string message = Random(500);
// Dictionary Words Reference
public Dictionary<string, string> dictionary = new Dictionary<string, string>();
// Matches Found
public static List<string> matches = new List<string>();
public MainWindow()
{
InitializeComponent();
// Import Dictionary File
dictionary = File
.ReadLines(#"C:\dictionary.txt")
.Select((v, i) => new { Index = i, Value = v })
.GroupBy(p => p.Index / 2)
.ToDictionary(g => g.First().Value, g => g.Last().Value);
// If Message Contains word, add to Matches List
foreach (KeyValuePair<string, string> entry in dictionary)
{
if (message.Contains(entry.Value))
{
matches.Add(entry.Value);
}
}
}
Working
Using Array
// Random Message
public string message = Random(500);
// Dictionary Words Reference
public string[] dictionary = File.ReadAllLines(#"C:\dictionary.txt");
// Matches Found
public List<string> matches = new List<string>();
public MainWindow()
{
InitializeComponent();
// If Message Contains word, add to Matches List
foreach (var entry in dictionary)
{
if (message.Contains(entry))
{
matches.Add(entry);
}
}
}
I doubt if you want Dictionary<string, string> as a dictionary ;) HashSet<string> will be enough:
using System.Linq;
...
string source = "bliduuwfhbgphwhsyzjnlfyizbj";
HashSet<string> allWords = new HashSet<string>(File
.ReadLines(#"C:\dictionary.txt")
.Select(line => line.Trim())
.Where(line => !string.IsNullOrEmpty(line)), StringComparer.OrdinalIgnoreCase);
int shortestWord = allWords.Min(word => word.Length);
int longestWord = allWords.Max(word => word.Length);
// If you want duplicates, change HashSet<string> to List<string>
HashSet<string> wordsFound = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
for (int length = shortestWord; length <= longestWord; ++length) {
for (int position = 0; position <= source.Length - length; ++position) {
string extract = source.Substring(position, length);
if (allWords.Contains(extract))
wordsFound.Add(extract);
}
}
Test: for
https://raw.githubusercontent.com/dolph/dictionary/master/popular.txt
dictionary donwloaded as C:\dictionary.txt file
Console.WriteLine(string.Join(", ", wordsFound.OrderBy(x => x)));
we have output
id, li, lid
Using a Dictionary in this scenario doesn't make much sense. A Dictionary is, essentially, a list of variables that stores both the variable name and the variable value.
I could have the following:
int age = 21;
int money = 21343;
int distance = 10;
int year = 2017;
And convert it to a Dictionary instead, using the following:
Dictionary<string, int> numbers = new Dictionary<string, int>()
{
{ "age", 21 },
{ "money", 21343},
{ "distance", 10 },
{ "year", 2017 }
};
And then I can access a value in the dictionary using its key (the first value). So, for example, if I want to know what "age" is, I would use:
Console.Log(numbers["age"]);
This is only a single example of the power of dictionaries - there is a LOT more that they can do, and they can make your life a lot easier. In this scenario, however, they aren't going to do what you're expecting them to do. I would suggest just using the Array, or a List.
You are misusing the dictionary,
you are basically using the dictionary as a list, so it only added some overhead to the program. not helping in any way.
It would have been useful if you had something you want to query against the dictionary not the other way around.
Also, in any case, what you want is a HashSet, not a dictionary since your key in the dictionary is not the word you are querying against but an irrelevant int.
you can read more about dictionary and HashSet here:
dictionary: https://www.dotnetperls.com/dictionary
hashset: https://www.dotnetperls.com/hashset

Get an array of string from a jagged array [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have a jagged array that contains other 1d string arrays:
string[] first = {"one","two"};
string[] second = {"three","four"};
string[][] jagged = {first,second};
When I try to get the sub-arrays, they give a null value (I might be doing something wrong):
foreach (string[] arr in jagged[][]) {
// My stuff here
}
Did I do something wrong in the array initialization progress or do I have to convert the sub-arrays somehow?
Just the foreach part is wrong.
I have tested it like as follows:
string[] first = { "one", "two" };
string[] second = {"three","four"};
string[][] jagged = {first,second};
foreach (string[] arr in jagged)
{
Console.WriteLine(string.Join(",", arr));
}
Output:
one, two
three, four
It should be:
foreach (string[] arr in jagged)
{
// My stuff here
}
I pasted your code on my local environment and could iterate just fine.
If you use jagged[][] in your loop, then possibly you get a type conversion failed message:
Cannot convert type 'char' to 'string'.
Instead use jagged in your loop.
public class Program
{
public static void Main()
{
string[] first = {"one","two"};
string[] second = {"three","four"};
string[][] jagged = {first,second};
foreach (string[] arr in jagged)
{
//Your code
}
}
}

How to access Dictionary in for loop in C# [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have declare a dictionary in C#. But I can't access it by foreach.
Dictionary<int,string>dic=new Dictionary<int,string>()
{
{78,"A"},
{81,"B"},
{90, "C"}
}
Now I want to compare its integer value with an other variable(count). If matches then it will give corresponding string value. How can I access the dictionary by for loop??
I have tried like this.
foreach(int p in dic.Value)
{
if(dic.ContainsKey(p)==count)
{
Console.WriteLine(dic.Values(p));
}
}
It's not working. Not finding anything in any site. Help in advance.
I'm unsure what you are actually trying to ask here. However, below is how to loop over the key value pairs of a dictionary using a foreach.
var dic = new Dictionary<int, string>
{
{78, "A"},
{81, "B"},
{90, "C"}
};
//To loop over the key value pairs of a dictionary
foreach (var keyValue in dic)
{
Console.WriteLine("This is the key: {0}",keyValue.Key);
Console.WriteLine("This is the value: {0}", keyValue.Value);
}
However, i think this is what you are looking to do which requires no loop to find if the key is contained in the dictionary.
const int count = 78;
if (dic.ContainsKey(count))
{
Console.WriteLine(dic[count]);
}
else
{
Console.WriteLine("The dictionary does not contain the key: {0}", count);
}
As #john has mentioned in the comments, you can also use Dictionary.TryGetValue to get the value with a specified key as well
string value;
var success = dic.TryGetValue(count, out value);
if (success)
Console.WriteLine("The dictionary value is: {0}", value);
You can iterate using foreach this way:
foreach(KeyValuePair<int, string> pair in dic)
{
if(pair.Key==count)
Console.WriteLine(pair.Value);
}
Try the example.
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
Dictionary<string, int> dictionary =
new Dictionary<string, int>();
dictionary.Add("apple", 1);
dictionary.Add("windows", 5);
// See whether Dictionary contains this string.
if (dictionary.ContainsKey("apple"))
{
int value = dictionary["apple"];
Console.WriteLine(value);
}
// See whether it contains this string.
if (!dictionary.ContainsKey("acorn"))
{
Console.WriteLine(false);
}
}
}

Show C# Array on user request [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
I need a way to get the response from a user.
For example they type "hat" and it displays the price in the array table in a console writeline. It also needs to be done in a 2d array instead of dictionary
class Table
{
string[,] names = {
{"rice", "50"},
{"chip", "20"},
{"hat", "50"},
{"ball", "34"},
};
}
class Program
{
static void Main(string[] args)
{
string Res;
Console.WriteLine("What product would you like?");
Res = Console.ReadLine();
Console.ReadKey();
}
}
Use a Dictionary<string, string> rather that way you can look up the Value based on the Key
Dictionary<string, string> example = new Dictionary<string, string>();
example.Add("hat", "50");
//Add the rest in this manner
The you can do the lookup like this
if (example.ContainsKey(Res))
string price = example[Res];
Straightforward solution with 2-d array:
class Program
{
static void Main(string[] args)
{
var products = new[,] { {"rice", "50"}, {"chip", "20"}, {"hat", "50"}, {"ball", "34"} };
Console.WriteLine("What product would you like?");
var request = Console.ReadLine();
string value = null;
if (request != null)
{
for (int i = 0; i < products.GetUpperBound(0); i++)
{
if (products[i, 0] == request)
{
value = products[i, 1];
break;
}
}
}
if (!string.IsNullOrEmpty(value))
{
Console.WriteLine("You've selected: " + request + ". Value is: " + value);
}
else
{
Console.WriteLine("You've selected: " + request + ". No value found.");
}
Console.ReadKey();
}
}
you should be using a Dictionary instead of your jagged array. It is better and you get more flexibility.
var items = new Dictionary<string, string>(5);
items.Add("rice", "50");
items.Add("chip", "20");
// and so on
then you get the item by checking to see if the key exists first:
if (items.ContainsKey("rice"))
{
// it exists! read it:
Console.WriteLine(items["rice"]);
}

Any utility to print out array directly? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have an array, I am wondering any utility to print out array directly?
You can use string's Join() method, like this:
Console.WriteLine("My array: {0}",
string.Join(", ", myArray.Select(v => v.ToString()))
);
This will print array elements converted to string, separated by ", ".
You can use the following one liner to print an array
int[] array = new int[] { 1 , 2 , 3 , 4 };
Array.ForEach( array , x => Console.WriteLine(x) );
I like #dasblinkenlight solution, but I'd like to note that the select statement is not nessasary.
This code produces the same result for an array of strings:
string[] myArray = {"String 1", "String 2", "More strings"};
Console.WriteLine("My array: {0}", string.Join(", ", myArray));
I find it a little easier on the eyes having less code to read.
(linqpad is a fantastic app to test snippets of code like this.)
You can write an extension method something like this
namespace ConsoleApplication12
{
class Program
{
static void Main(string[] args)
{
var items = new []{ 1, 2, 3, 4, 5 };
items.PrintArray();
}
}
static class ArrayExtensions
{
public static void PrintArray<T>(this IEnumerable<T> elements)
{
foreach (var element in elements)
{
Console.WriteLine(element);
}
}
}
}

Categories

Resources