ArrayList string searching - c#

As part of my University course, we've got to use ArrayLists to create a record booking system, and I want to include a way of searching for the surname of the Booking, is there a way to do this in C#?
The ArrayList contains the variable "surname", and at the moment I have this
private void search()
{
string term;
term = searchBox.Text;
foreach (string surname in dataList)
if (surname == term){
and that's where I'm stuck. Any help would be appreciated!

It is easier to use IndexOf and check if the index is not negative:
int pos = dataList.IndexOf(surname);
if (pos >= 0) {
// It's there - do whatever you need to do...
...
}

using System;
using System.Collections;
class Program
{
static void Main(string[] args)
{
ArrayList datalist = new ArrayList
{
"asd",
"surname",
"dfg"
};
Console.WriteLine(datalist.IndexOf("surname") != -1 ? "Found" : "Not found");
Console.ReadKey(true);
}
}

Related

Can't build game because of ObjectNames.GetUniqueName, Unity

I'm building my game and after like 4 seconds there is an error that says:
Assets\PlayerInventory.cs(228,37): error CS0103: The name 'ObjectNames' does not exist in the current context I'm using the function so that the objects don't all have the same name, but I can't build because of it. I'm using it like this:
string uniqueName = ObjectNames.GetUniqueName(names, "");
this is just adding a number on the end so it would be
Object
Object (1)
Object (2)
and so on...
Why is it not letting me build?
EDIT:
Code snippet:
using System.Collections;
using System.IO;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.Linq;
using UnityEditor;
using Photon.Pun;
using UnityEngine.UI;
public class PlayerInventory : MonoBehaviour
{
// Names taken
public string[] names = new string[] { "Object" };
void Start()
{
string uniqueName = ObjectNames.GetUniqueName(names, "");
}
}
Some of the using are not needed for this snippet.
Because ObjectNames is part of the namespace UnityEditor which only exists within the Unity editor itself and is completely stripped of during the build process.
=> You can't use any of it in the actual released application, it is only for doing stuff within the editor itself.
Unfortunately the exact content of GetUniqueName is also not public in the source code but you can implement something similar yourself.
There might be better and more efficient ways but I would go with e.g.
public static class StringExtensions
{
// Regex Matches a trailing indexer
// e.g. "Example (1)"
private const string k_IndexMatch = " \\(([0-9]+)\\)$";
private static bool HasIndexer(string name, out int? index, out string nameWithoutIndex)
{
var matches = Regex.Matches(name, k_IndexMatch);
var nameIndexMatch = matches.LastOrDefault();
// or in case of older Unity/c# version without Linq
//var nameIndexMatch = matches.Count == 0 ? null : matches[matches.Count - 1];
if (nameIndexMatch == null)
{
index = null;
nameWithoutIndex = name;
return false;
}
// First group is always entire match, we want only the numeric value which is the second group
var group = nameIndexMatch.Groups[1];
index = int.Parse(group.Value);
nameWithoutIndex = name.Substring(0, name.Length - nameIndexMatch.Value.Length);
return true;
}
public static string GetUniqueName(this string name, IEnumerable<string> existingNames)
{
HasIndexer(name, out var index, out var nameWithoutIndex);
foreach (var existingName in existingNames)
{
if (existingName == nameWithoutIndex)
{
// Exact match (without index)
// in this case either keep your index or if there is none use 1
if (index == null)
{
index = 1;
}
continue;
}
if (HasIndexer(existingName, out var existingIndex, out var existingNameWithoutIndex))
{
if (existingNameWithoutIndex == nameWithoutIndex)
{
index = index == null ? existingIndex + 1 : Math.Max(index.Value, existingIndex.Value + 1);
}
}
}
return nameWithoutIndex + (index == null ? "" : $" ({index})");
}
}
See also .NetFiddle (older c#)
Example usage
var uniqueName = "Example".GetUniqueName(new []{"Example 0", "Example (1)", "Nope", "Example", "Example (2)"});
=>
Example (3)
since only "Example (1)", "Example", "Example (2)" are overlapping matches and highest free index is 3.

C#: Execute Code from String and Reference Local Variable

I am working on a C# application, and I would like the ability to execute code from a string, where that string contains a variable in scope outside the string. For example:
using Microsoft.CodeAnalysis.CSharp.Scripting;
///...
List<int> myNumbers = new List<int>();
//do something here to populate myNumbers
//userProvidedExpression will be a string that contains curNumber and represents a statement that would evaluate to a bool
string userProvidedExpression = "curNumber == 4";
foreach(int curNumber in myNumbers)
{
if( await CSharpScript.EvaluateAsync<bool>(userProvidedExpression) )
{
Console.WriteLine("curNumber MATCHES user-provided condition");
}
else
{
Console.WriteLine("curNumber DOES NOT MATCH user-provided condition");
}
}
Obviously the key difficulty I am having is getting the "curNumber" from userProvidedExpression to be recognized as the same curNumber from the foreach loop. Is there any straightforward way to accomplish this?
As the documentation says, you need to add a globals, like that:
public class Globals
{
public int curNumber;
}
async static void Main(string[] args)
{
List<int> myNumbers = new List<int>();
myNumbers.Add(4);
//userProvidedExpression will be a string that contains curNumber and represents a statement that would evaluate to a bool
string userProvidedExpression = "curNumber == 4";
foreach (int curNumber in myNumbers)
{
var globals = new Globals
{
curNumber = curNumber
};
if (await CSharpScript.EvaluateAsync<bool>(userProvidedExpression, globals: globals))
{
Console.WriteLine("curNumber MATCHES user-provided condition");
}
else
{
Console.WriteLine("curNumber DOES NOT MATCH user-provided condition");
}
}
Console.ReadLine();
}

How do i acces individual Values in a hash table

I have an assignment where i have to take an string input and apply zipfs law to it. Im having issues accessing the value in a hashtable. Whenever i find a word that already exist i'm supposed to update the wordcounter +1. What ends up happening is the counter applies to all the values in the hash table, and i get ridiculously high numbers. I cant wrap my head around how i'm supposed to give an individual counter for each keyvalue
Here is the code:
using System;
using Spire.Doc;
using System.Collections;
using System.Collections.Generic;
namespace Zipf
{
class Program
{
public static Hashtable wordRegister;
static void Main(string[] args)
{
String[] ArrLoop = TextSplitter();
int[] wordCount = new int[ArrLoop.Length];
int count = 1;
wordRegister = new Hashtable();
for(int i = 0; i < ArrLoop.Length; i++)
{
if (wordRegister.ContainsKey(ArrLoop[i]))
{
// here is where im having trouble
wordRegister[ArrLoop[i]] = count += 1;
}
else
{
wordRegister.Add(ArrLoop[i], count);
}
}
foreach (DictionaryEntry pair in wordRegister)
{
Console.WriteLine($"Key : {pair.Key} ; Forekomster : {pair.Value}");
}
Console.ReadLine();
}
public static String WordString()
{
Document doc = new Document();
doc.LoadFromFile(#"C:\Users\xxx\Desktop\2.g\IDO.docx");
String textString = doc.GetText();
return textString;
}
public static string[] TextSplitter()
{
string s = WordString();
String[] wordArr = s.Split();
return wordArr;
}
}
}
You don't need the count variable. You are incrementing a counter common to all entries.
Try this instead to keep the counts distinct from each other:
wordRegister[ArrLoop[i]] += 1;

Permutation Algorithm OutOfMemory Exception

Please help me to how to fix OutOfMemory exception using below code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Permutation
{
class Program
{
static void Main(string[] args)
{
CreatePartsByFreezingEachElementOnce("abcedfghijk");
PrintPossiblePermutations(false);
Console.WriteLine("---------------");
PrintPossiblePermutations(true);
Console.ReadLine();
}
static void PrintPossiblePermutations(bool unique)
{
var allPermutations = new List<string>();
foreach (var item in _listWithFreezedKey)
if (item.Item2.Count() == 2)
{
allPermutations.Add(Swap(String.Join(",", item.Item1), item.Item2[0], item.Item2[1]));
allPermutations.Add(Swap(String.Join(",", item.Item1), item.Item2[1], item.Item2[0]));
}
if (unique)
{
var uniuePermutations = allPermutations.Distinct();
// PrintPermutations(uniuePermutations.ToList());
Console.WriteLine(uniuePermutations.Count());
}
else
{
// PrintPermutations(allPermutations);
Console.WriteLine(allPermutations.Count());
}
}
static void PrintPermutations(List<string> permutations)
{
int i = 1;
foreach (var item in permutations)
{
Console.WriteLine(string.Format("{0} :{1}", i, item));
i++;
}
}
static List<Tuple<List<char>, List<char>>> _listWithFreezedKey = new List<Tuple<List<char>, List<char>>>();
static void CreatePartsByFreezingEachElementOnce(string str, List<char> indexToFreeze = null)
{
List<Tuple<List<char>, List<char>>> _innerlistWithFreezedKey = new List<Tuple<List<char>, List<char>>>();
var arr = str.ToCharArray().ToList();
var copy = arr;
if (indexToFreeze == null)
{
indexToFreeze = new List<char>();
}
for (int i = 0; i < arr.Count(); i++)
{
copy = str.ToCharArray().ToList();
var nth = arr[i];
copy.RemoveAt(i);
indexToFreeze.Add(nth);
_listWithFreezedKey.Add(new Tuple<List<char>, List<char>>(indexToFreeze.ToList(), copy));
_innerlistWithFreezedKey.Add(new Tuple<List<char>, List<char>>(indexToFreeze.ToList(), copy));
indexToFreeze.RemoveAt(indexToFreeze.Count() - 1);
}
foreach (var item in _innerlistWithFreezedKey)
{
List<char> l = item.Item2;
CreatePartsByFreezingEachElementOnce(String.Join("", l), item.Item1);
}
}
static string Swap(string frezedPart, char swapChar1, char swapChar2)
{
return frezedPart + "," + swapChar1 + "," + swapChar2;
}
}
}
If you run this code using 10 chrs, it throws out of memory exception. But for 9 chars , it returns result.
It was my interview question to write a code such that it should not go out of memory if big data passed.
Thanks,
Your problem is that you want to generate all permutations at once, instead of generating them one-by-one. You are looking for an algorithm which produces the next permutation.
See the first page of Knuth's book on generating permutations.
I would like to answer my question by myself because it may help someone as well.
I will use Iterator Design Pattern to remove unused elements from memory and will convert collection into sequence.
Thanks,

How to sort two arraylist and then compare that they are same

I am trying to sort the two array elements and match them with one another if one any one match it returns lucky otherwise unlucky, any ideas that where i am going to wrong
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Apptest
{
class Program
{
static void Main(string[] args)
{
int[] arr1 = { 5,4,3,8,1};
int[] arr2 = { 8,1,5,4,3};
string str = rollingdice(arr1, arr2);
Console.WriteLine(str);
}
public static string rollingdice(int[] input1, int[] input2)
{
// input1.Sort();
//input2.Sort();
for(int i=0;i<input1.Length && i<input2.Length;i++)
{
if (!Object.Equals(input1[i], input2[i]))
{
return "unlucky";
}
else
{
return "Lucky";
}
}
}
}
}
You can use Enumerable.SequenceEqual:
Array.Sort<int>(input1);
Array.Sort<int>(input2);
bool equal = input1.SequenceEqual(input2);
return equal ? "lucky" : "unlucky"; // lucky in your sample
You have to assign the result of the sorted array
var foo = input1.Sort();
var bar = input2.Sort();
Then compare foo and bar.
The shortest way to check for equality in this case would be:
bool equal = arr1.Length == arr2.Length && !arr1.Except(arr2).Any();

Categories

Resources