Check if permutations of characters are contained in text file - c#

Quick question.
I am writing a program to find all the permutations of a set of characters I input into the application.
This part works perfectly.
My problem is that I need to check all the permutations of the characters against a text file I use as a dictionary.
Ex. If I input the characters TSTE the outputs givin are tset,ttse,ttes,tets,test,stte,stet,sett...
I only want to print the valid words like tset,sett,stet,test,tets. where ttse,ttes,stte is not printed.
The code I have so far is as follows.
I have been scracthing at the edges of my scull for the past few days and just cant seem to find a way to do it.
Please if there is anything you can see that I have missed?
Thank you
static void Main(string[] args)
{
Console.BufferHeight = Int16.MaxValue - 1;
Console.WindowHeight = 40;
Console.WindowWidth = 120;
Permute p = new Permute();
var d = Read();
string line;
string str = System.IO.File.ReadAllText("Dictionary.txt");
while ((line = Console.ReadLine()) != null)
{
char[] c2 = line.ToArray();
p.setper(c2);
}
}
static Dictionary<string, string> Read()
{
var d = new Dictionary<string, string>();
using (StreamReader sr = new StreamReader("Dictionary.txt"))
{
string line;
while ((line = sr.ReadLine()) != null)
{
string a = Alphabet(line);
string v;
if (d.TryGetValue(a, out v))
{
d[a] = v + "," + line;
}
else
{
d.Add(a, line);
}
}
}
return d;
}
static string Alphabet(string s)
{
char[] a = s.ToCharArray();
Array.Sort(a);
return new string(a);
}
static void Show(Dictionary<string, string> d, string w)
{
string v;
if (d.TryGetValue(Alphabet(w), out v))
{
Console.WriteLine(v);
}
else
{
Console.WriteLine("-----------");
}
}
}
class Permute
{
private void swap(ref char a, ref char b)
{
if (a == b) return;
a ^= b;
b ^= a;
a ^= b;
}
public void setper(char[] list)
{
int x = list.Length - 1;
go(list, 0, x);
}
public void go(char[] list1, int k, int m)
{
if (k == m)
{
Console.WriteLine(list1);
Console.WriteLine(" ");
}
else
{
for (int i = k; i <= m; i++)
{
swap(ref list1[k], ref list1[i]);
go(list1, k + 1, m);
swap(ref list1[k], ref list1[i]);
}
}
}

you just missed Show(d, line); i loop.
change like this.
while ((line = Console.ReadLine()) != null)
{
char[] c2 = line.ToArray();
p.setper(c2);
Console.WriteLine(" combinations which are in Dictionary are:");
Show(d, line);
}
then ..
you didn't required dictionary
use List<string> Dic=new List<string>();// declare it in globally
Dic.add(line); //each line in dictionary
before printing each word
if(Dic.contains(word))
print it;
else{ //no printing }

Not possible with current state.
It's possible because
If the "dictionary.txt" was your input, then you did not define what are the valid words.
You at leaset need another dictionary to define those valid words or an algorithm to decide what those are and what those are not.
If the input is from UI and "dictionary.txt" is the defined valid words, you don't need to the permute the input, just search the input from "dictionary.txt".
However, your Read method is improvable, like
static Dictionary<String, String> Read(String path) {
return (
from line in File.ReadAllLines(path)
where false==String.IsNullOrEmpty(line)
group line by Alphabet(line) into g
select
new {
Value=String.Join(",", g.ToArray()),
Key=g.Key
}
).ToDictionary(x => x.Key, x => x.Value);
}

Although for the valid words are as I mentioned in another answer, not possible with your current state, I've make the code pretty clear for you.
It finally the code, is separated in three parts. They are Permutable<T>, ConsoleHelper and the ConsoleApplication1.Program with an utility Permutation class.
Permutable<T> (Permutable.cs)
using System.Collections.Generic;
using System.Collections;
using System;
public partial class Permutable<T>: IEnumerable {
public static explicit operator Permutable<T>(T[] array) {
return new Permutable<T>(array);
}
static IEnumerable Permute<TElement>(IList<TElement> list, int depth, int count) {
if(count==depth)
yield return list;
else {
for(var i=depth; i<=count; ++i) {
Swap(list, depth, i);
foreach(var sequence in Permutable<T>.Permute(list, 1+depth, count))
yield return sequence;
Swap(list, depth, i);
}
}
}
static void Swap<TElement>(IList<TElement> list, int depth, int index) {
var local=list[depth];
list[depth]=list[index];
list[index]=local;
}
IEnumerator IEnumerable.GetEnumerator() {
return this.GetEnumerator();
}
public IEnumerator<IList<T>> GetEnumerator() {
var list=this.m_List;
if(list.Count>0)
foreach(IList<T> sequence in Permutable<T>.Permute(list, 0, list.Count-1))
yield return sequence;
}
protected Permutable(IList<T> list) {
this.m_List=list;
}
IList<T> m_List;
}
ConsoleHelper (ConsoleHelper.cs)
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Drawing;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public static partial class ConsoleHelper {
[StructLayout(LayoutKind.Sequential)]
public struct RECT {
public static explicit operator Rectangle(RECT rect) {
return new Rectangle {
X=rect.Left,
Y=rect.Top,
Width=rect.Right-rect.Left,
Height=rect.Bottom-rect.Top
};
}
public int Left;
public int Top;
public int Right;
public int Bottom;
}
[DllImport("user32.dll", SetLastError=true)]
static extern bool MoveWindow(IntPtr hWnd, int X, int Y, int Width, int Height, bool repaint);
[DllImport("user32.dll", SetLastError=true)]
static extern bool GetWindowRect(IntPtr hWnd, out RECT rect);
[DllImport("kernel32.dll", SetLastError=true)]
static extern IntPtr GetConsoleWindow();
public static void CenterScreen() {
RECT rect;
var hWnn=ConsoleHelper.GetConsoleWindow();
var workingArea=Screen.GetWorkingArea(Point.Empty);
ConsoleHelper.GetWindowRect(hWnn, out rect);
var rectangle=(Rectangle)rect;
rectangle=
new Rectangle {
X=(workingArea.Width-rectangle.Width)/2,
Y=(workingArea.Height-rectangle.Height)/2,
Width=rectangle.Width,
Height=rectangle.Height
};
ConsoleHelper.MoveWindow(
hWnn,
rectangle.Left, rectangle.Top, rectangle.Width, rectangle.Height,
true
);
}
}
ConsoleApplication1.Program & Permutation (Program.cs)
using System.Collections;
using System.IO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public partial class Permutation {
public static Permutation FromFile(String path) {
return new Permutation(path);
}
public static String GetSortedAlphabet(String text) {
var array=text.ToArray();
Array.Sort(array);
return new String(array);
}
public Dictionary<String, String> Dictionary {
private set;
get;
}
public FileInfo SourceFile {
private set;
get;
}
public Permutation(String path) {
this.Dictionary=(
from line in File.ReadAllLines(path)
where false==String.IsNullOrEmpty(line)
group line by Permutation.GetSortedAlphabet(line) into g
select
new {
Value=String.Join(", ", g.Distinct().ToArray()),
Key=g.Key
}
).ToDictionary(x => x.Key, x => x.Value);
this.SourceFile=new FileInfo(path);
}
}
namespace ConsoleApplication1 {
partial class Program {
static void ProcessLine(IList<char> input) {
Console.WriteLine();
if(input.Count>0) {
var inputArray=input.ToArray();
var key=Permutation.GetSortedAlphabet(new String(inputArray));
var dict=Program.Permutation.Dictionary;
var hasKey=dict.ContainsKey(key);
var source=Permutation.SourceFile;
Console.WriteLine("Possible permutations are: ");
foreach(var sequence in (Permutable<char>)inputArray)
Console.WriteLine("{0}", new String(sequence.ToArray()));
Console.WriteLine("Acceptable in file '{0}' are: ", source.FullName);
Console.WriteLine("{0}", hasKey?dict[key]:"<none>");
Console.WriteLine();
input.Clear();
}
Console.Write(Prompt);
}
static void ProcessChar(IList<char> input, char keyChar) {
Console.Write(keyChar);
input.Add(keyChar);
}
static void ProcessExit(IList<char> input, char keyChar) {
Console.WriteLine();
Console.Write("Are you sure to exit? (Press Esc again to exit)");
input.Add(keyChar);
}
static bool ProcessLast(IList<char> input, char keyChar) {
var last=input.Count-1;
if(0>last||input[last]!=(char)ConsoleKey.Escape)
return false;
input.Clear();
return true;
}
public static Permutation Permutation {
private set;
get;
}
public static String Prompt {
private set;
get;
}
}
partial class Program {
static void Main(String[] args) {
Console.BufferHeight=short.MaxValue-1;
Console.SetWindowSize(120, 40);
ConsoleHelper.CenterScreen();
var input=new List<char>(char.MaxValue);
Program.Permutation=Permutation.FromFile(#"c:\dictionary.txt");
Program.Prompt="User>\x20";
Program.ProcessLine(input);
for(; ; ) {
var keyInfo=Console.ReadKey(true);
var keyChar=keyInfo.KeyChar;
var keyCode=keyInfo.Key;
if(ConsoleKey.Escape==keyCode) {
if(Program.ProcessLast(input, keyChar))
break;
Program.ProcessExit(input, keyChar);
continue;
}
if(ConsoleKey.Enter==keyCode) {
Program.ProcessLine(input);
continue;
}
if(default(ConsoleModifiers)!=keyInfo.Modifiers)
continue;
if(0x1f>keyChar||keyChar>0x7f)
continue;
if(Program.ProcessLast(input, keyChar))
Console.WriteLine();
Program.ProcessChar(input, keyChar);
}
}
}
}
The ConsoleHelper class is only use for ceteral your resized console window, that you can test the program more comfortable. The Permutable class is what I fully re-designed from your original class; it now come with IEnumerable to permute, and also a generic class.
The Permutation class, is like a utility class, itself provide a FromFile method as your original Read, and stores the Dictionary<String, String> as a property. The original method Alphabet is renamed GetSortedAlphabet for more semantical.
The Program class has four main static ProcessXXX methods, they are
ProcessChar: processes for a char of the range from 0x20 to 0x7f
ProcessLine: processes for Enter pressed
ProcessExit: processes for Excape pressed
ProcessLast: additional processing for ProcessLine and ProcessExit
Yes, I meant to make them have the same length of name. For more, Program class have two static properties; Permutation for storing a instance of class Permutation, and Prompt is a string for prompting user.
When your input is not defined in "c:\dictionary.txt", the prompt of "Acceptable in file .." will get you "<none>".
The exit command is twice-Escape key press, you would see
Are you sure to exit? (Press Esc again to exit)
and if you press Enter or other keys, it back to the initial state.
That's all. Now it's time to discover the finally problem you've encountered. After you test with this program, you might describe you questions and issues more clearly.
Good luck!

Thank you for all your feedback.
I have finally figured it out and found a solution to the problem I was having.
static void Main(string[] args)
{
Console.BufferHeight = Int16.MaxValue - 1;
Console.WindowHeight = 40;
Console.WindowWidth = 120;
Console.WriteLine("Enter your caracters for the anagram: ");
//var d = Read();
string line;
//string DictionaryInput = System.IO.File.ReadAllText("Dictionary.txt");
while ((line = Console.ReadLine()) != null)
{
Console.WriteLine("Your results are: ");
char[] charArray = line.ToArray();
//Show(d, line); //Using this to check that words found are the correct words in the dictionary.
setper(charArray);
Console.WriteLine("-----------------------------------------DONE-----------------------------------------");
Console.WriteLine("Enter your caracters for the anagram: ");
File.Delete("Permutations.txt");
}
}
static void swap(ref char a, ref char b)
{
if (a == b) return;
a ^= b;
b ^= a;
a ^= b;
}
static void setper(char[] list)
{
int x = list.Length - 1;
permuteWords(list, 0, x);
}
static void permuteWords(char[] list1, int k, int m)
{
if (k == m)
{
StreamWriter sw = new StreamWriter("Permutations.txt", true);
sw.WriteLine(list1);
sw.Close();
Regex permutationPattern = new Regex(new string(list1));
string[] permutations = File.ReadAllLines("Permutations.txt");
Regex pattern = new Regex(new string(list1));
string[] lines = File.ReadAllLines("Dictionary.txt");
foreach (string line in lines)
{
var matches = pattern.Matches(line);
if (pattern.ToString() == line)
{
Console.WriteLine(line);
}
}
}
else
{
for (int i = k; i <= m; i++)
{
swap(ref list1[k], ref list1[i]);
permuteWords(list1, k + 1, m);
swap(ref list1[k], ref list1[i]);
}
}
}

Related

C# Error: "A namespace cannot directly contain members such as fields or methods"

A method receiving 2 numbers and I need to return the numbers of common digits for them. For example, the numbers 2201 and 3021 returns 3 because these numbers have 3 common digits: 0, 1, and 2.
I get this error and don't understand it: A namespace cannot directly contain members such as fields or methods
Here is the code:
public static int AlphaRomeo(int a, int b)
{
int count = 0;
while (a > 0)
{
int tempa = a % 10;
a = a / 10;
int tempb = b % 10;
b = b / 10;
if (tempa == tempb)
count++;
}
return count;
}
Might be easier to avoid the mathematics:
private static string _digits = "0123456789";
public static int AlphaRomeo(int a, int b)
{
string aStr = a.ToString();
string bStr = b.ToString();
int common = 0;
for (int i = 0; i < _digits.Length; i++)
{
if (aStr.Contains(_digits[i]) && bStr.Contains(_digits[i]))
common++;
}
return common;
}
Consider this example, you don't have a class in your code:
using System; // Imports
namespace LearnClasses // Namespace
{
class Program //class
{
static void Main(string[] args) // Method 1
{
Console.WriteLine( AlphaRomeo(2201, 3021));
}
public static int AlphaRomeo(int a, int b) // Method 2
{
int count = 0;
// Your code
return count;
}
}
}

What does С# SemaphoreSlim guarantee? Is it full memorybarrier? What we can be sure of code between two different semaphore Wait() and Release()?

What does С# SemaphoreSlim guarantee? Is it full memory barrier? What we can be sure of code between two different semaphore Wait() and Release()?
Does sequence of different SemaphoreSlim Wait(), Release() and Interlocked methods and Volatile. Write/Read always keep it order in every threads?
public T Dequeue()
{
canReadCountSemaphoreSlim.Wait();
int i = Interlocked.Decrement(ref end);
T val = Volatile.Read(ref buf[i]);
canWriteCountSemaphoreSlim.Release();
return val;
}
public void Enqueue(T val)
{
canWriteCountSemaphoreSlim.Wait();
int i = Interlocked.Decrement(ref start);
Volatile.Write(ref buf[i], val);
canReadCountSemaphoreSlim.Release();
}
Full code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
namespace Program
{
public class BlockingRingQueue<T> where T: class
{
const int BUFSIZE_LOG2 = 10;
const int BUFSIZE = 1 << BUFSIZE_LOG2;
T[] buf = new T[BUFSIZE];
int start = 0;
int end = 0;
SemaphoreSlim canReadCountSemaphoreSlim = new SemaphoreSlim(0);
SemaphoreSlim canWriteCountSemaphoreSlim = new SemaphoreSlim(BUFSIZE);
public T Dequeue()
{
canReadCountSemaphoreSlim.Wait();
int i = Interlocked.Decrement(ref end);
i = PositiveMod(i, BUFSIZE);
T val = Volatile.Read(ref buf[i]);
canWriteCountSemaphoreSlim.Release();
return val;
}
public void Enqueue(T val)
{
canWriteCountSemaphoreSlim.Wait();
int i = Interlocked.Decrement(ref start);
i = PositiveMod(i, BUFSIZE);
Volatile.Write(ref buf[i], val);
canReadCountSemaphoreSlim.Release();
}
static int PositiveMod(int a, int b) => ((a % b) + b) % b;
}
public class Program
{
const int READ_THREAD_COUNT = 3;
static BlockingRingQueue<string> queue = new BlockingRingQueue<string>();
public static void Main(string[] args)
{
new Thread(() => Pushing("ABCD")) { Name = "0" }.Start();
for(int i = 1; i <= READ_THREAD_COUNT; i++)
new Thread(Poping) { Name = i.ToString() }.Start();
}
public static void Poping()
{
while(true)
{
RandSpinWait();
var val = queue.Dequeue();
if("" == val)
break;
Console.WriteLine(val + Thread.CurrentThread.Name + ' ');
}
//Console.WriteLine('!' + Thread.CurrentThread.Name + ' ');
}
public static void Pushing(string chars)
{
RandSpinWait();
var vals = chars.ToCharArray().Select(c => $"{c}")
.Concat(Enumerable.Repeat("",READ_THREAD_COUNT));
foreach(string v in vals)
queue.Enqueue(v);
}
public static void RandSpinWait() => Thread.SpinWait(new Random().Next(1));
}
}

Print() name doesn't exist in current context

New to c# need help with the following error.
In class Grybai there is an error in Print case 'svoris' does not exist in current context. Print(A, ref n, Svoris); third argument 'Svoris' gives an error.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace C
{
class Grybai
{
public string name;
private int Svoris;
public void Tipas(string nameType, int Weight) { name = nameType; Svoris = Weight; }
public string GetName() { return name; }
public int GetWeight() { return Svoris; }
Tried to do with GetWeight method, still nothing...
}
class Program
{
const string CFd = "..//..//Duom.txt";
const string CFr = "..//..//Rez.txt";
//Duomenu nuskaitymas is failo i masyva
static void Main(string[] args)
{
Grybai[] A = new Grybai[10]; //Sukuriam strukturu masyva
int n = 0;
Read(A, ref n);
Print(A, ref n, Svoris);
The name Svoris does not exist in current context, how to fix it?
}
static void Read(Grybai[] tarp, ref int n)
{
using (StreamReader reader = new StreamReader(CFd))
{
string line;
string[] parts;
if (File.Exists(CFr)) File.Delete(CFr);
while ((line = reader.ReadLine()) != null)
{
parts = line.Split(' ');
tarp[n] = new Grybai();
tarp[n].Tipas(parts[0], int.Parse(parts[1]));
n++;
}
}
}
static void Sort(Grybai[] tarpA, int n)
{
Grybai tarpB;
for (int j = 0; j < n; j++)
{
for (int i = 0; i < n - 1; i++)
{
if (tarpA[i].GetName()[0] > tarpA[i + 1].GetName()[0])
{
tarpB = tarpA[i];
tarpA[i] = tarpA[i + 1];
tarpA[i + 1] = tarpB;
}
}
}
}
static void Print(Grybai[] tarp, int n, int svoris)
{
string top = "|-----------------------------------------------------------|\r\n" +
"| Surusiuoti duomenys |\r\n" +
"|-----------------------------------------------------------|\r\n" +
"|Pavadinimas |Tipas |Svoris |\r\n" +
"|-----------------------------------------------------------|";
In order to resolves argument error on 'Svoris', you can replace a line of code as below.
Old Code : Print(A, ref n, Svoris);
New Code : Print(A, ref n, A.GetWeight());
As per your code, GetWeight() returns value of Svoris. It serves the intended purpose.
private int Svoris;
You "Svoris" is a private class viarable in "Grybai" class. You can't just access it like that in the "Program" class.

Checking letter position and if its the correct letter

Im creating a game that generates a random word and then lets the user guess the word.
After the user enters his word the game will compare them and return what letter were correct and if they had the right position. Right now it return differents results when i input the same word.
This is what i have so far:
class Game
{
public string CorrectPlace;
public string WrongPlace;
public string NoneExist;
public string CorrectWord;
public string InputWord; // the word the uis
public int points;
public string[] Wordarray = new string[] { "radar", "andar", "raggar", "rapar", "raser", "rastar", "rikas" };
public string getRandomWord(string names)
{
Random ran = new Random();
return Wordarray[(ran.Next(0,Wordarray.Length-1))];
}
public void CheckWords(string name)
{
InputWord.ToCharArray();
CorrectWord = getRandomWord(CorrectWord); // store the random word in a string
for (int i = 0; i < CorrectWord.Length; i++)
{
if (InputWord[i] == CorrectWord[i])
MessageBox.Show("Letter #" + (i + 1).ToString() + " was correct!");
else
break;
}
}
}
Im calling the method in my form
private void button1_Click(object sender, EventArgs e)
{
Game nc = new Game();
nc.InputWord = textBox1.Text;
nc.CheckWords(nc.InputWord);
}
Try like this:
class Game
{
public string CorrectPlace;
public string WrongPlace;
public string NoneExist;
public string CorrectWord;
public string InputWord;
public int points;
public string[] Wordarray = null;
public string getRandomWord(string names)
{
Random ran = new Random();
return Wordarray[(ran.Next(0,Wordarray.Length-1))];
}
public void Game()
{
Wordarray = new string[] { "radar", "andar", "raggar", "rapar", "raser", "rastar", "rikas" }
CorrectWord = getRandomWord(); // store the random word in a string
}
public void CheckWords(string name)
{
for (int i = 0; i < CorrectWord.Length; i++)
{
if (InputWord[i] == CorrectWord[i])
MessageBox.Show("Letter #" + (i + 1).ToString() + " was correct!");
else
break;
}
}
}
The idea behind the scene is to get a random word when game starts( an instance of class Game instantiated) and then compare it with the user input in CheckWords method.
I would suggest to do not call MessageBox.show in a loop, it will popup every time a match exists.
occur
Change the Code Like this. Please let me know if you have any issues.
class Game
{
public string CorrectWord = null;
public string InputWord; // the word the uis
public int points;
public string[] Wordarray = new string[] { "radar", "andar", "raggar", "rapar", "raser", "rastar", "rikas" };
public string getRandomWord()
{
Random ran = new Random();
return Wordarray[(ran.Next(0, Wordarray.Length - 1))];
}
public void Newgame()
{
}
public void CheckWords(string name)
{
char[] charInputWord = name.ToCharArray();
CorrectWord = getRandomWord(); // store the random word in a string
Console.WriteLine("Random Word " + CorrectWord);
Console.WriteLine("User Word " + name);
char[] charCorrectWord = CorrectWord.ToCharArray();
for (int i = 0; i < charInputWord.Length; i++)
{
if (charInputWord[i] == charCorrectWord[i])
Console.WriteLine("Letter #" + (i + 1).ToString() + " was correct!");
else
break;
}
}
}
class Program
{
static void Main(string[] args)
{
Game ab = new Game();
ab.CheckWords("raser");
Console.ReadLine();
}
}
Both names and name are never used, and seem unneeded.
It looks like you want something like this (converted to console printing since I don't have your UI source)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace WordGame
{
class Game
{
static void Main(string[] args)
{
Game g = new Game();
bool gameOver = false;
while (!gameOver)
{
Console.WriteLine("Enter a guess (or type 'exit' to exit):");
string answer = Console.ReadLine();
if (answer.ToLower() == "exit")
break;
if (g.CheckWord(answer))
{
Console.WriteLine("You win!");
while (true)
{
Console.WriteLine("Play Again (y/n)?");
answer = Console.ReadLine().ToLower();
if (answer == "n")
{
gameOver = true;
break;
}
else if (answer == "y")
{
g.ChooseRandomWord();
break;
}
}
}
}
}
public string CorrectWord;
public string[] Wordarray = new string[] { "radar", "andar", "raggar", "rapar", "raser", "rastar", "rikas" };
private Random ran = new Random();
public Game()
{
ChooseRandomWord();
}
public void ChooseRandomWord()
{
CorrectWord = Wordarray[(ran.Next(0, Wordarray.Length - 1))];
}
public bool CheckWord(string guess)
{
if (guess.Trim() == CorrectWord)
{
return true;
}
string guessLower = guess.Trim().ToLower();
string correctLower = CorrectWord.ToLower();
for (int i = 0; i < correctLower.Length; i++)
{
if (guessLower[i] == correctLower[i])
Console.Write(guess[i]);
else
Console.Write("#");
}
Console.WriteLine();
return false;
}
}
}

How do you call a method from static main()?

I have a console application with a Main method and a function.
How can I make a function call from the Main method?
I know the code below won't work
static void Main(string[] args)
{
string btchid = GetCommandLine();// GetCommandline is a mthod which returns a string
}
There's also
var p = new Program();
string btchid = p.GetCommandLine();
Make the GetCommandLine static!
namespace Lab
{
public static class Program
{
static string GetCommandLine()
{
return "Hellow World!";
}
static void Main(string[] args)
{
System.Console.WriteLine(GetCommandLine());
System.Console.ReadKey();
}
}
}
You can change the function as a static and call it . Thats all.
static class Program
{
[STAThread]
static void Main()
{
string btchid = Program.GetCommandLine();
}
private static string GetCommandLine()
{
string s = "";
return s;
}
}
A linear search approach to your problem:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace LinearSearch
{
class Program
{
static void Main(string[] args)
{
int var1 = 50;
int[] arr;
arr = new int[10]{10,20,30,40,50,60,70,80,90,100};
int retval = linearsearch(arr,var1);
if (retval >= 1)
{
Console.WriteLine(retval);
Console.Read();
}
else
{ Console.WriteLine("Not found"); Console.Read(); }
}
static int linearsearch(int[] arr, int var1)
{
int pos = 0;
int posfound = 0;
foreach (var item in arr)
{
pos = pos + 1;
if (item == var1)
{
posfound = pos;
if (posfound >= 1)
break;
}
}
return posfound;
}
}
}
GetCommandLine must be a static function
string btchid = classnamehere.GetCommandLine();
Assuming that GetCommandLine is static
Something like this:
[STAThread]
static void Main(string[] args) {
string btchid = GetCommandLine();// GetCommandline is a mthod which returns a string
}
static string GetCommandLine(){
return "Some command line";
}

Categories

Resources