I have come up with this code, it works for what the teacher wants. Counts spaces, counts words, does a substring search and individually counts letters and shows you what letters are used.
But I need to convert it into an array method rather than a 600 line do while loop. I really have no clue how to do this. Could anyone give me input?
using System;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int a = 0;
int b = 0;
int c = 0;
int d = 0;
int e = 0;
int f = 0;
int g = 0;
int h = 0;
int i = 0;
int j = 0;
int k = 0;
int l = 0;
int m = 0;
int n = 0;
int o = 0;
int p = 0;
int q = 0;
int r = 0;
int s = 0;
int t = 0;
int u = 0;
int v = 0;
int w = 0;
int x = 0;
int y = 0;
int z = 0;
int A = 0;
int B = 0;
int C = 0;
int D = 0;
int E = 0;
int F = 0;
int G = 0;
int H = 0;
int I = 0;
int J = 0;
int K = 0;
int L = 0;
int M = 0;
int N = 0;
int O = 0;
int P = 0;
int Q = 0;
int R = 0;
int S = 0;
int T = 0;
int U = 0;
int V = 0;
int W = 0;
int X = 0;
int Y = 0;
int Z = 0;
int readChar = 0;
int word = 0;
int lower = 0;
int upper = 0;
string inputString ="";
char ch = ' ';
string findString = "";
int space = 0;
int startingPoint = 0;
int findStringCount = 0;
Console.Write("Please enter a string: ");
do{
readChar = Console.Read();
ch = Convert.ToChar(readChar);
if (ch.Equals(' '))
{
space++;
}
else if (Char.IsLower(ch))
{
lower++;
if (ch.Equals('a'))
{
a++;
}
else if (ch.Equals('b'))
{
b++;
}
else if (ch.Equals('c'))
{
c++;
}
else if (ch.Equals('d'))
{
d++;
}
else if (ch.Equals('e'))
{
e++;
}
else if (ch.Equals('f'))
{
f++;
}
else if (ch.Equals('g'))
{
g++;
}
else if (ch.Equals('h'))
{
h++;
}
else if (ch.Equals('i'))
{
i++;
}
else if (ch.Equals('j'))
{
j++;
}
else if (ch.Equals('k'))
{
k++;
}
else if (ch.Equals('l'))
{
l++;
}
else if (ch.Equals('m'))
{
m++;
}
else if (ch.Equals('n'))
{
n++;
}
else if (ch.Equals('o'))
{
o++;
}
else if (ch.Equals('p'))
{
p++;
}
else if (ch.Equals('q'))
{
q++;
}
else if (ch.Equals('r'))
{
r++;
}
else if (ch.Equals('s'))
{
s++;
}
else if (ch.Equals('t'))
{
t++;
}
else if (ch.Equals('u'))
{
u++;
}
else if (ch.Equals('v'))
{
v++;
}
else if (ch.Equals('w'))
{
w++;
}
else if (ch.Equals('x'))
{
x++;
}
else if (ch.Equals('y'))
{
y++;
}
else if (ch.Equals('z'))
{
z++;
}
}
else if (Char.IsUpper(ch))
{
upper++;
if (ch.Equals('A'))
{
A++;
}
else if (ch.Equals('B'))
{
B++;
}
else if (ch.Equals('C'))
{
C++;
}
else if (ch.Equals('D'))
{
D++;
}
else if (ch.Equals('E'))
{
E++;
}
else if (ch.Equals('F'))
{
F++;
}
else if (ch.Equals('G'))
{
G++;
}
else if (ch.Equals('H'))
{
H++;
}
else if (ch.Equals('I'))
{
I++;
}
else if (ch.Equals('J'))
{
J++;
}
else if (ch.Equals('K'))
{
K++;
}
else if (ch.Equals('L'))
{
L++;
}
else if (ch.Equals('M'))
{
M++;
}
else if (ch.Equals('N'))
{
N++;
}
else if (ch.Equals('O'))
{
O++;
}
else if (ch.Equals('P'))
{
P++;
}
else if (ch.Equals('Q'))
{
Q++;
}
else if (ch.Equals('R'))
{
R++;
}
else if (ch.Equals('S'))
{
S++;
}
else if (ch.Equals('T'))
{
T++;
}
else if (ch.Equals('U'))
{
U++;
}
else if (ch.Equals('V'))
{
V++;
}
else if (ch.Equals('W'))
{
W++;
}
else if (ch.Equals('X'))
{
X++;
}
else if (ch.Equals('Y'))
{
Y++;
}
else if (ch.Equals('Z'))
{
Z++;
}
}
if (((ch.Equals(' ') && (!inputString.EndsWith(" ")))||(ch.Equals('\r') && (!inputString.EndsWith(" "))))&&(inputString!=""))
{
word++;
}
inputString = inputString + ch;
} while (ch != '\r');
Console.ReadLine();
Console.WriteLine("Report on {0}",inputString);
Console.WriteLine("# of spaces {0}",space);
Console.WriteLine("# of lower {0}", lower);
Console.WriteLine("# of upper {0}", upper);
Console.WriteLine("# of word {0}", word);
Console.WriteLine("UPPERCASE");
if (A >= 1)
{
Console.WriteLine("A = {0}",A);
}
if (B >= 1)
{
Console.WriteLine("B = {0}",B);
}
if (C >= 1)
{
Console.WriteLine("C = {0}", C);
}
if (D >= 1)
{
Console.WriteLine("D = {0}", D);
}
if (E >= 1)
{
Console.WriteLine("E = {0}", E);
}
if (F >= 1)
{
Console.WriteLine("F = {0}", F);
} if (G >= 1)
{
Console.WriteLine("G = {0}", G);
}
if (H >= 1)
{
Console.WriteLine("H = {0}", H);
}
if (I >= 1)
{
Console.WriteLine("I = {0}", I);
}
if (J >= 1)
{
Console.WriteLine("J = {0}", J);
}
if (K >= 1)
{
Console.WriteLine("K = {0}", K);
}
if (L >= 1)
{
Console.WriteLine("L = {0}", L);
}
if (M >= 1)
{
Console.WriteLine("M = {0}", M);
}
if (N >= 1)
{
Console.WriteLine("N = {0}",N);
}
if (O >= 1)
{
Console.WriteLine("O = {0}",O);
}
if (P >= 1)
{
Console.WriteLine("P = {0}",P);
}
if (Q >= 1)
{
Console.WriteLine("Q = {0}",Q);
}
if (R >= 1)
{
Console.WriteLine("R = {0}",R);
}
if (S >= 1)
{
Console.WriteLine("S = {0}",S);
}
if (T >= 1)
{
Console.WriteLine("T = {0}",T);
}
if (U >= 1)
{
Console.WriteLine("U = {0}",U);
}
if (V >= 1)
{
Console.WriteLine("V = {0}",V);
}
if (W >= 1)
{
Console.WriteLine("W = {0}",W);
}
if (X >= 1)
{
Console.WriteLine("X = {0}",X);
}
if (Y >= 1)
{
Console.WriteLine("Y = {0}",Y);
}
if (Z >= 1)
{
Console.WriteLine("Z = {0}",Z);
}
Console.WriteLine("LOWERCASE");
if (a >= 1)
{
Console.WriteLine("a = {0}", a);
}
if (b >= 1)
{
Console.WriteLine("b = {0}", b);
}
if (c >= 1)
{
Console.WriteLine("c = {0}", c);
}
if (d >= 1)
{
Console.WriteLine("d = {0}", d);
}
if (e >= 1)
{
Console.WriteLine("e = {0}", e);
}
if (f >= 1)
{
Console.WriteLine("f = {0}", f);
} if (g >= 1)
{
Console.WriteLine("g = {0}", g);
}
if (h >= 1)
{
Console.WriteLine("h = {0}", h);
}
if (i >= 1)
{
Console.WriteLine("i = {0}", i);
}
if (j >= 1)
{
Console.WriteLine("j = {0}", j);
}
if (k >= 1)
{
Console.WriteLine("k = {0}", k);
}
if (l >= 1)
{
Console.WriteLine("l = {0}", l);
}
if (m >= 1)
{
Console.WriteLine("m = {0}", m);
}
if (n >= 1)
{
Console.WriteLine("n = {0}", n);
}
if (o >= 1)
{
Console.WriteLine("o = {0}", o);
}
if (p >= 1)
{
Console.WriteLine("p = {0}", p);
}
if (q >= 1)
{
Console.WriteLine("q = {0}", q);
}
if (r >= 1)
{
Console.WriteLine("r = {0}", r);
}
if (s >= 1)
{
Console.WriteLine("s = {0}", s);
}
if (t >= 1)
{
Console.WriteLine("t = {0}", t);
}
if (u >= 1)
{
Console.WriteLine("u = {0}", u);
}
if (v >= 1)
{
Console.WriteLine("v = {0}", v);
}
if (w >= 1)
{
Console.WriteLine("w = {0}", w);
}
if (x >= 1)
{
Console.WriteLine("x = {0}", x);
}
if (y >= 1)
{
Console.WriteLine("y = {0}", y);
}
if (z >= 1)
{
Console.WriteLine("z = {0}", z);
}
Console.WriteLine();
Console.Write("Please enter a substring ");
findString = Console.ReadLine();
if (findString.Length <= inputString.Length)
{
do
{
if (inputString.IndexOf(findString, startingPoint) != -1)
{
findStringCount++;
startingPoint = inputString.IndexOf(findString, startingPoint) + findString.Length;
}
} while (inputString.IndexOf(findString, startingPoint) != -1);
}
else
{
Console.WriteLine("Substring is too long!");
}
Console.WriteLine("The number of times that {0} is found in the text is {1}", findString, findStringCount);
Console.ReadLine();
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int[] counterArray = new int[123];
string myString;
int wordCounted = 0;
int result = 0;
//Prompt user and get value
Console.Write("Please enter a string: ");
myString =
Console.ReadLine();
//Word count
for (int i = 1; i < myString.Length; i++)
{
if (char.IsWhiteSpace(myString[i - 1]))
{
if (char.IsLetterOrDigit(myString[i]) ||
char.IsPunctuation(myString[i]))
{
wordCounted++;
}
}
}
if (myString.Length > 2)
{
wordCounted++;
}
//White space count
foreach (char countSpace in myString)
{
if (char.IsWhiteSpace(countSpace))
{
result++;
}
}
//Display words and space count,
Console.WriteLine("\nWORDS:\t\t{0}", wordCounted);
Console.WriteLine("SPACES: \t{0}", result);
for (int x = 0; x < myString.Length; x++)
{
int myValue = Convert.ToInt32(myString[x]);
counterArray[myValue]++;
}
//Display uppercase letter count
Console.WriteLine("\nUPPERCASE LETTERS: ");
//Counting uppercase letter
for (int y = 65; y < 91; y++)
{
if (counterArray[y] > 0)
{
Console.WriteLine("\t\t{0}: \t{1}", Convert.ToChar(y), counterArray[y]);
}
}
//Display lowercase letter count
Console.WriteLine("LOWERCASE LETTERS: ");
//Counting lowercase letter
for (int z = 97; z < 123; z++)
{
if (counterArray[z] > 0)
{
Console.WriteLine("\t\t{0}: \t{1}", Convert.ToChar(z), counterArray[z]);
}
}
int startingPoint = 0;
int findStringCount = 0;
Console.Write("Please enter a substring ");
findString = Console.ReadLine();
Console.WriteLine("Press ENTER to exit...");
Console.ReadLine();
}
}
}
Here is a way to use the dictionary and Linq. (Edit added the uppercase linq operation to fill in the A-Z to compliment the a-z):
Dictionary<char, int> myLetters = new Dictionary<char, int>();
Enumerable.Range(0,26)
.Select( indx => (char)+('a' + indx))
.Union( Enumerable.Range(0,26)
.Select( indx => (char)+('A' + indx)))
.ToList()
.ForEach( chr => myLetters.Add( chr, 0));
myLetters['a'] = 2;
myLetters['Z'] = 3;
myLetters.ToList()
.ForEach( ml => Console.WriteLine("{0} : {1}", ml.Key, ml.Value));
/* Prints out
a : 2
b : 0
c : 0
...
Z : 3
*/
Note the above is for learning purposes, I would actually do the myLetters assignment with the enumerable in one fell swoop such as:
Dictionary<char, int> myLetters =
Enumerable.Range(0,26)
.Select( indx => (char)+('a' + indx))
.Union( Enumerable.Range(0,26)
.Select( indx => (char)+('A' + indx)))
.ToDictionary (letter => letter, letter => 0);
The ideal solution would be to use a Dictionary<char,int>, but if the homework specifically requires an array, you can use the fact that the ASCII representation of alphabetic characters are serial. That is, A=65, B=66,...,Z=90 and a=97, b=98,...,z=122. For example:
var uppercase = new int[26];
var lowercase = new int[26];
if( ch >= 'A' && ch <= 'Z' )
uppercase[ch-'A']++;
if( ch >= 'a' && ch <= 'z' )
lowercase[ch-'a']++;
Then when you go print it out, you can just cast the indeces to type char:
for( var i='A'; i<='Z'; i++ ) {
Console.WriteLine( (char)i + " = " + uppercase[i-'A'] );
}
I'll leave the rest of the implementation up to you.
Well IMHO the easiest way to get an array of characters would be this:
char[] alphaLower = "abcdefghijklmnopqrstuvwxyz".ToCharArray();
char[] alphaUpper = //same thing as above with uppercase letters;
at this point you can do your calculations inside of a loop. Something like this:
foreach(char c in alphaLower)
{
//possibly a nested foreach here to process each character of input against each char in the alphabet?
//write your calculation to console
}
I wouldn't be surprised to see what you have above rewritten in as little as 20 lines of code. Post what you come up with in your next iteration and we will continue to point you in the right direction.
Try using a hashtable...where they key is the letter, and the value is the number of times it occurs
if (ht.Contains({yourletter}))
//increment the value by 1
if (ht.ContainsKey(letter))
ht[letter] = Convert.ToInt32(ht[letter]) + 1;
else
ht.Add(letter, 1);
ASCII space is continuous for capital letters, and for small caps, capital A starts from decimal 65.
see http://www.asciitable.com/ for details
you should allocate an array for all characters in lower part of ascii table (127)
var countingchars = new int[128];
then you loop over chars in string and do sth like in this loop:
countingchars[(byte)currentchar]++;
whenever you encounter (byte)currentchar == 32, you should increment word count
when you have gone through entire string,
get spaces from countingchars[32]
get caps from 65 - 90
get small letters from 97-122
hope this is enough.
I am leaving it up to you for putting it nicely into c#
Hope this will help in learning
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace HomeWork
{
class Alphabets
{
static void Main(string[] args)
{
string sentence = null;
string findString = null;
int numericCount;
int upperCount;
int lowerCount;
int specialCount;
int countBlankSpace;
int countWord;
Console.Write("Please enter a string: ");
sentence = Console.ReadLine();
numericCount = Regex.Matches(sentence, #"\d").Count;
upperCount = Regex.Matches(sentence, #"[A-Z]").Count;
lowerCount = Regex.Matches(sentence, #"[a-z]").Count;
specialCount = Regex.Matches(sentence, #"[!""£$%^&*())]").Count;
countBlankSpace = new Regex(" ").Matches(sentence).Count;
countWord = Regex.Matches(sentence, #"[\S]+").Count;
Console.WriteLine("Report on {0}",sentence);
Console.WriteLine("# of spaces {0}", countBlankSpace);
Console.WriteLine("# of lower {0}", lowerCount);
Console.WriteLine("# of upper {0}", upperCount);
Console.WriteLine("# of word {0}", countWord);
Console.WriteLine("# of Special Characters {0}", specialCount);
Console.Write("Please enter a substring:");
findString = Console.ReadLine();
Alphabets.findSubString(findString, sentence);
Console.WriteLine("\nLowercase Letters \n");
Alphabets.lowerLetters(sentence);
Console.WriteLine("\nUppercase Letters \n");
Alphabets.upperLetters(sentence);
Console.ReadLine();
}
public static void lowerLetters(string sentence)
{
int[] upper = new int[(int)char.MaxValue];
// 1.
// Iterate over each character.
foreach (char t in sentence)
{
// Increment table.
upper[(int)t]++;
}
// 2.
// Write all letters found.
for (int i = 0; i < (int)char.MaxValue; i++)
{
if (upper[i] > 0 &&
char.IsLower((char)i))
{
Console.WriteLine("Letter: {0} = {1}",
(char)i,
upper[i]);
}
}
}
public static void upperLetters(string sentence)
{
int[] upper = new int[(int)char.MaxValue];
// 1.
// Iterate over each character.
foreach (char t in sentence)
{
// Increment table.
upper[(int)t]++;
}
// 2.
// Write all letters found.
for (int i = 0; i < (int)char.MaxValue; i++)
{
if (upper[i] > 0 &&
char.IsUpper((char)i))
{
Console.WriteLine("Letter: {0} = {1}",
(char)i,
upper[i]);
}
}
}
public static void findSubString(string findString, string sentence)
{
int findStringCount = 0;
int startingPoint = 0;
if (findString.Length <= sentence.Length)
{
do
{
if (sentence.IndexOf(findString, startingPoint) != -1)
{
findStringCount++;
startingPoint = sentence.IndexOf(findString, startingPoint) + findString.Length;
}
} while (sentence.IndexOf(findString, startingPoint) != -1);
}
else
{
Console.WriteLine("Substring is too long!");
}
Console.WriteLine("The number of times that {0} is found in the text is {1}", findString, findStringCount);
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int[] counterArray = new int[123];
string myString;
int wordCounted = 0;
int result = 0;
//Prompt user and get value
myString = getStringMethod();
//Word count
wordCounted = countWordsMethod(myString, wordCounted);
//White space count
result = spaceCounterMethod(myString, result);
//Display words and space count,
displayCountMethod(counterArray, myString, wordCounted, result);
//Display uppercase letter count
displayUpperMethod();
//Counting uppercase letter
uppserCaseMethod(counterArray);
//Display lowercase letter count
displayLowerMethod();
//Counting lowercase letter
lowerCaseMethod(counterArray);
Console.WriteLine("Press ENTER to exit...");
Console.ReadLine();
}
private static void displayLowerMethod()
{
Console.WriteLine("LOWERCASE LETTERS: ");
}
private static void displayUpperMethod()
{
Console.WriteLine("\nUPPERCASE LETTERS: ");
}
private static void lowerCaseMethod(int[] counterArray)
{
for (int z = 97; z < 123; z++)
{
if (counterArray[z] > 0)
{
Console.WriteLine("\t\t{0}: \t{1}", Convert.ToChar(z), counterArray[z]);
}
}
}
private static void upp
Related
I keep on receiving this CS0136 error and I'm unsure why?
using System;
namespace Lab2_1
{
class Program
{
static void Main(string[] args)
{
Action<string> cw = Console.WriteLine;
int[] numbers = new int[10];
int currentIndex = 0;
bool repeat = true;
do
{
cw("Please enter an interger: ");
string line = Console.ReadLine();
if (line == "exit")
{
repeat = false;
}
else
{
try
{
int number = int.Parse(line);
cw("The number you entered was: " + number);
numbers[currentIndex] = number;
currentIndex++;
}
catch (FormatException)
{
cw("That wasn't a number!");
}
}
} while (repeat);
Console.WriteLine("Press any key to exit.");
{
while (repeat) ;
for (int i = 0; i < currentIndex; i++)
{
Console.WriteLine(numbers[i]);
}
currentIndex++;
if (currentIndex == numbers.Length)
{
int expandedNumberOfCells = currentIndex + 10;
}
int expandedNumberOfCells = currentIndex + 10;
int[] expandedNumbers = new int[expandedNumberOfCells];
for (int i = 0; i < currentIndex; i++)
{
expandedNumbers[i] = numbers[i];
}
numbers = expandedNumbers;
}
}
}
}
From this page you can see what error CS0136 is.
You could not declare expandedNumberOfCells repeatedly, you can slightly modify your code:
int expandedNumberOfCells = currentIndex + 10;
int[] expandedNumbers = new int[expandedNumberOfCells];
if (currentIndex == numbers.Length)
{
expandedNumberOfCells = currentIndex + 10;
}
for (int i = 0; i < currentIndex; i++)
{
expandedNumbers[i] = numbers[i];
}
numbers = expandedNumbers;
Give two strings of equal size. Determine whether each character in the first string can be uniquely replaced by a character in the second string so that the two strings are equal. Display also the corresponding character pairs between the two strings. The code works well now.
Example 1:
For input data:
aab
ttd
The console will display:
True
a => t
b => d
Example 2:
For input data:
tab
ttd
The console will display:
False
In the second example the answer is false because there is no unique correspondence for the character 'a': both 't' and 'd' correspond to it.
This is my code:
using System;
namespace problemeJM
{
class Program
{
static void Main(string[] args)
{
string firstPhrase = Convert.ToString(Console.ReadLine());
string secondPhrase = Convert.ToString(Console.ReadLine());
string aux1 = string.Empty, aux2 = string.Empty;
bool x = true;
for (int i = 0; i < firstPhrase.Length; i++)
{
if (!aux1.Contains(firstPhrase[i]))
{
aux1 += firstPhrase[i];
}
}
for (int i = 0; i < secondPhrase.Length; i++)
{
if (!aux2.Contains(secondPhrase[i]))
{
aux2 += secondPhrase[i];
}
}
if (aux1.Length != aux2.Length)
{
Console.WriteLine("False");
}
else
{
for (int i = 0; i < firstPhrase.Length - 2; i++)
{
for (int j = 1; j < secondPhrase.Length - 1; j++)
{
if (firstPhrase[i] == firstPhrase[j] && secondPhrase[i] == secondPhrase[j])
{
x = true;
}
else if (firstPhrase[i] != firstPhrase[j] && secondPhrase[i] != secondPhrase[j])
{
x = true;
}
else if (firstPhrase[i] == firstPhrase[j] && secondPhrase[i] != secondPhrase[j])
{
x = false;
break;
}
else if (firstPhrase[i] != firstPhrase[j] && secondPhrase[i] == secondPhrase[j])
{
x = false;
break;
}
}
}
Console.WriteLine(x);
aux1 = string.Empty;
aux2 = string.Empty;
if (x == true)
{
for (int i = 0; i < firstPhrase.Length; i++)
{
if (!aux1.Contains(firstPhrase[i]))
{
aux1 += firstPhrase[i];
}
}
for (int i = 0; i < secondPhrase.Length; i++)
{
if (!aux2.Contains(secondPhrase[i]))
{
aux2 += secondPhrase[i];
}
}
for (int i = 0; i <= aux1.Length - 1; i++)
{
for (int j = 1; j <= aux2.Length; j++)
{
if (aux1[i] == aux1[j] && aux2[i] == aux2[j])
{
Console.WriteLine(aux1[i] + " => " + aux2[i]);
break;
}
else if (aux1[i] != aux1[j] && aux2[i] != aux2[j])
{
Console.WriteLine(aux1[i] + " => " + aux2[i]);
break;
}
}
}
}
}
}
}
}
I think you should use a Dictionary<char, char> as commented. But you need to check if there's a unique mapping in both string, so from s1 to s2 and from s2 to s1:
static bool UniqueMapping(string s1, string s2)
{
int length = Math.Min(s1.Length, s2.Length);
var dict = new Dictionary<char, char>(length);
for (int i = 0; i < length; i++)
{
char c1 = s1[i];
char c2 = s2[i];
bool contained = dict.TryGetValue(c1, out char c);
if (contained && c2 != c)
{
return false;
}
dict[c1] = c2;
}
return true;
}
Here are your samples. Note that i use UniqueMapping twice(if true after 1st):
static void Main(string[] args)
{
var items = new List<string[]> { new[]{ "aab", "ttd" }, new[] { "tab", "ttd" }, new[] { "ala bala portocala", "cuc dcuc efghficuc" }, new[] { "ala bala portocala", "cuc dcuc efghijcuc" } };
foreach (string[] item in items)
{
bool result = UniqueMapping(item[0], item[1]);
if(result) result = UniqueMapping(item[1], item[0]);
Console.WriteLine($"Word 1 <{item[0]}> Word 2 <{item[1]}> UniqueMapping? {result}");
}
}
.NET Fiddle: https://dotnetfiddle.net/4DtIyH
I'm writing a code which counts the most frequent word in an array of string , I'm also trying to count the number of vowels in each line of the word , in other words the total number of vowels in all the words which are in the array , I've written the code but it's not working and I can't figure out what's the problem with it , is it because I'm comparing string with char ?
using System;
using System.Collections.Generic;
namespace lab1._2
{
class Program
{
static String findWord(String[] arr)
{
Dictionary<String, int> hs =
new Dictionary<String, int>();
for (int i = 0; i < arr.Length; i++)
{
if (hs.ContainsKey(arr[i]))
{
hs[arr[i]] = hs[arr[i]] + 1;
}
else
{
hs.Add(arr[i], 1);
}
}
String key = "";
int value = 0;
foreach (KeyValuePair<String, int> me in hs)
{
if (me.Value > value)
{
value = me.Value;
key = me.Key;
}
}
return key;
}
static void Main(string[] args)
{
int s;
//char[] v = new char[10] {'a','A','e','E','i','I','o','O','u','U'};
Console.WriteLine("Enter size of array : ");
s = Convert.ToInt32(Console.ReadLine());
string[] arr = new string[s];
Console.WriteLine("Enter string elements : ");
for (int i = 0; i < s; i++)
{
arr[i] = Console.ReadLine();
}
Console.WriteLine("\nArray elements : ");
for (int i = 0; i < s; i++)
{
Console.WriteLine(arr[i]);
}
Console.WriteLine("\nThe most frequent word : ");
Console.WriteLine(findWord(arr));
int vowel = 0, cons = 0;
for (int i = 0; i < arr.Length; i++)
{
if (arr[i] == "a" || arr[i] == "e" || arr[i] == "i" || arr[i] == "o" || arr[i]
== "u")
{
vowel++;
}
else
cons++;
}
Console.WriteLine("Vowels : ");
Console.WriteLine(vowel);
Console.WriteLine("Consants : ");
Console.WriteLine(cons);
}
}
}
I think the problem is that arr is an array of string and you are iterating through it as if it was a single string.
A simple way of doing this would be to have a nested loop.
foreach (var s in arr) // s is a string
{
for (int i = 0; i < s.Length; i++)
{
if (s[i] == 'a' || s[i] == 'e' || s[i] == 'i' || s[i] == 'o' || s[i] == 'u')
{
vowel++;
}
else
cons++;
}
}
https://dotnetfiddle.net/tI3oTc
using System;
public class Program
{
public static void Main()
{
int vowel = 0;
int cons = 0;
string[] arr = new string[]{"test"};
foreach (var s in arr) // s is a string
{
for (int i = 0; i < s.Length; i++)
{
if (s[i] == 'a' || s[i] == 'e' || s[i] == 'i' || s[i] == 'o' || s[i] == 'u')
{
vowel++;
}
else
cons++;
}
}
Console.WriteLine(vowel);
}
}
I'm a math student with little to no experience programming, but I wrote this to act like a brute force algorithm. It seems to run fine except that it runs all the password combinations out to 3 characters for passwords as short as 2. Also I'm sure there's a way to refactor the for and if statements as well. Any help would be appreciated, thanks.
I've already been testing to see if some of the if statements aren't executing, and it looks like the statements with "console.writeln(Is this executing)" aren't executing but I'm not really sure.
public Form1()
{
InitializeComponent();
}
static char[] Match ={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f','g','h','i','j' ,'k','l','m','n','o','p',
'q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','C','L','M','N','O','P',
'Q','R','S','T','U','V','X','Y','Z','!','?',' ','*','-','+'};
private string[] tempPass;
private void button1_Click(object sender, EventArgs e)
{
string tempPass1 = "lm";
string result = String.Empty;
int passLength = 1;
int maxLength = 17;
tempPass = new string[passLength];
for (int i = 0; i < Match.Length; i++)
{
if (tempPass1 != result)
{
tempPass[0] = Match[i].ToString();
result = String.Concat(tempPass);
if (passLength > 1)
{
for (int j = 0; j < Match.Length; j++)
{
if (tempPass1 != result)
{
tempPass[1] = Match[j].ToString();
result = String.Concat(tempPass);
if (passLength > 2)
{
for (int k = 0; k < Match.Length; k++)
{
if (tempPass1 != result)
{
tempPass[2] = Match[k].ToString();
result = String.Concat(tempPass);
if (tempPass[0] == "+" && tempPass[1] == "+" && tempPass[2] == "+" && tempPass1 != result)
{
Console.WriteLine("This will execute?");
passLength++;
tempPass = new string[passLength];
k = 0;
j = 0;
i = 0;
}
else if (result == tempPass1)
{
Console.WriteLine("Broken");
Console.WriteLine("This is big gay: " + result);
break;
}
}
}
}
if (tempPass[0] == "+" && tempPass[1] == "+" && tempPass1 != result)
{
Console.WriteLine("Did this execute?");
passLength++;
tempPass = new string[passLength];
j = 0;
i = 0;
}
else if (result == tempPass1)
{
Console.WriteLine("Broken");
Console.WriteLine("This is bigger gay: " + result);
break;
}
}
}
}
//tempPass[1] = "World!";
//Console.WriteLine(result);
if (tempPass[tempPass.Length - 1] == "+" && tempPass1 != result)
{
passLength++;
tempPass = new string[passLength];
Console.WriteLine(tempPass.Length + " " + result + " " + "Success");
Console.WriteLine(i);
i = 0; /**update
j = 0;
k = 0;
l = 0;
m = 0;*/
}
else if (result == tempPass1)
{
Console.WriteLine("Broken");
Console.WriteLine("This is biggest gay: " + result);
}
}
}
}
Play with this; modified from my answer here. It'll show you all the 2 and 3 length combinations. Clicking the button will start/stop the generation process. You need a button, label, and a timer:
public partial class Form1 : Form
{
private Revision rev;
public Form1()
{
InitializeComponent();
rev = new Revision("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!? *-+", "00");
label1.Text = rev.CurrentRevision;
}
private void button1_Click(object sender, EventArgs e)
{
timer1.Enabled = !timer1.Enabled;
}
private void timer1_Tick(object sender, EventArgs e)
{
rev.NextRevision();
if (rev.CurrentRevision.Length == 4)
{
timer1.Stop();
MessageBox.Show("Sequence Complete");
// make it start back at the beginning?
rev = new Revision("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!? *-+", "00");
label1.Text = rev.CurrentRevision;
}
else
{
label1.Text = rev.CurrentRevision;
}
}
}
public class Revision
{
private string chars;
private char[] values;
private System.Text.StringBuilder curRevision;
public Revision()
{
this.DefaultRevision();
}
public Revision(string validChars)
{
if (validChars.Length > 0)
{
chars = validChars;
values = validChars.ToCharArray();
curRevision = new System.Text.StringBuilder(values[0]);
}
else
{
this.DefaultRevision();
}
}
public Revision(string validChars, string startingRevision)
: this(validChars)
{
curRevision = new System.Text.StringBuilder(startingRevision.ToUpper());
int i = 0;
for (i = 0; i <= curRevision.Length - 1; i++)
{
if (Array.IndexOf(values, curRevision[i]) == -1)
{
curRevision = new System.Text.StringBuilder(values[0]);
break;
}
}
}
private void DefaultRevision()
{
chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
values = chars.ToCharArray();
curRevision = new System.Text.StringBuilder(values[0]);
}
public string ValidChars
{
get { return chars; }
}
public string CurrentRevision
{
get { return curRevision.ToString(); }
}
public string NextRevision(int numRevisions = 1)
{
bool forward = (numRevisions > 0);
numRevisions = Math.Abs(numRevisions);
int i = 0;
for (i = 1; i <= numRevisions; i++)
{
if (forward)
{
this.Increment();
}
else
{
this.Decrement();
}
}
return this.CurrentRevision;
}
private void Increment()
{
char curChar = curRevision[curRevision.Length - 1];
int index = Array.IndexOf(values, curChar);
if (index < (chars.Length - 1))
{
index = index + 1;
curRevision[curRevision.Length - 1] = values[index];
}
else
{
curRevision[curRevision.Length - 1] = values[0];
int i = 0;
int startPosition = curRevision.Length - 2;
for (i = startPosition; i >= 0; i += -1)
{
curChar = curRevision[i];
index = Array.IndexOf(values, curChar);
if (index < (values.Length - 1))
{
index = index + 1;
curRevision[i] = values[index];
return;
}
else
{
curRevision[i] = values[0];
}
}
curRevision.Insert(0, values[0]);
}
}
private void Decrement()
{
char curChar = curRevision[curRevision.Length - 1];
int index = Array.IndexOf(values, curChar);
if (index > 0)
{
index = index - 1;
curRevision[curRevision.Length - 1] = values[index];
}
else
{
curRevision[curRevision.Length - 1] = values[values.Length - 1];
int i = 0;
int startPosition = curRevision.Length - 2;
for (i = startPosition; i >= 0; i += -1)
{
curChar = curRevision[i];
index = Array.IndexOf(values, curChar);
if (index > 0)
{
index = index - 1;
curRevision[i] = values[index];
return;
}
else
{
curRevision[i] = values[values.Length - 1];
}
}
curRevision.Remove(0, 1);
if (curRevision.Length == 0)
{
curRevision.Insert(0, values[0]);
}
}
}
}
Can that be done with no while loops?
static void Main(string[] args)
{
Console.WriteLine("Please enter a number");
int number = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(" #" + Fibonacci(number));
}
public static int Fibonacci(int number)
{
if (number <= 1)
{
return 1;
}
else
{
return Fibonacci(number - 2) + Fibonacci(number - 1);
}
}
I can't even add a Console.WriteLine in the body of base case since it gets executed [number] number of times; Not sure how to do this without loops...
static void Main(string[] args)
{
Console.WriteLine("Please enter a number");
int number = Convert.ToInt32(Console.ReadLine());
Fibonacci(0, 1, 1, number);
}
public static void Fibonacci(int a, int b, int counter, int number)
{
Console.WriteLine(a);
if (counter < number) Fibonacci(b, a+b, counter+1, number);
}
public static int Fibonatchi(int position) {
if(position == 0) {
return 1;
}
if(position == 1) {
return 1;
} else {
return Fibonatchi(position - 2) + Fibonatchi(position - 1);
}
}
I didn't find a way to do it closest way is it to combine both loops + recursion
static void Main(string[] args)
{
Console.WriteLine("Please enter a number");
int number = Convert.ToInt32(Console.ReadLine());
for(int counter=0;counter<number;counter++)
Console.WriteLine(" \n" + Fibonacci(counter) );
}
public static int Fibonacci(int number)
{
if (number == 0)
return 0;
else if(number ==1)
return 1;
else
{
return Fibonacci(number - 2) + Fibonacci(number - 1);
}
}
namespace Algorithms
{
class Program
{
static void Main(string[] args)
{
string fibResult = "";
fibResult = FibCal(10);
Console.WriteLine(fibResult);
Console.ReadLine();
}
public static string FibCal(int n)
{
string series = "";
int k, f1, f2 , f = 0;
f1 = f2 = 1;
if (n < 2)
return n.ToString();
else
for (k = 0; k < n; k++)
{
f = f1 + f2;
f2 = f1;
f1 = f;
series += f.ToString() + ",";
}
return series;
}
}
}
Hope this helps
Using recursion in this fashion is a very bad idea. It will cause memory problems very quickly. I know you want to avoid using while/for loops, but an array is really the best way to go.
Using LINQ
public static void fibSeriesEx3()
{
List<int> lst = new List<int> { 0, 1 };
for (int i = 0; i <= 10; i++)
{
int num = lst.Skip(i).Sum();
lst.Add(num);
foreach (int number in lst)
Console.Write(number + " ");
Console.WriteLine();
}
}
That's a way to do it by returning a value into the main.
public static void Main() {
Console.WriteLine("Introduce the number");
int num = Convert.ToInt32(Console.ReadLine());
int num1 = 1, num2 = 1, counter = num-2;
//Take 2 out to match the list as first 2 numbers doesn't count in the function.
Console.WriteLine(Fibo(num1, num2, counter));
}
public static int Fibo(int num1, int num2, int counter) {
int temp = num1;
if (counter <= 0)
return num2;
else
return Fibo(num1 = num2, num2 += temp, counter-1);
}
public static class Golden
{
public static IEnumerable<long> Fibonacci()
{
var a = 0L;
var b = 1L;
var s = 0L;
yield return a;
while (a < long.MaxValue - b)
{
yield return b;
s = a + b;
a = b;
b = s;
}
}
public static IEnumerable<long> FibonacciR()
{
IEnumerable<long> Fibo(long a, long b)
{
yield return a;
if (a < long.MaxValue - b)
{
foreach (var v in Fibo(b, a + b))
{
yield return v;
}
}
}
return Fibo(0, 1);
}
}
I realize this may be an old thread, but oh well I think this kinda question is good in its nature.
Using while loop/or recursive way of doing is not the optimal way of doing as it takes a O(2^n) times. A better way to do this is using what is already in memory like below. This should take at most O(n) time.
Cheers!
static double fibDynamic(int n)
{
double[] array = new double[n];
array[0] = array[1] = 1;
for(int i = 2; i < n; i++)
{
array[i] = array[i - 1] + array[i - 2];
}
return array[n-1];
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static int Main(string[] args)
{
int n, i = 0, c;
Console.WriteLine("Enter the number of terms:");
n = Convert.ToInt16(Console.ReadLine());
Console.WriteLine("Fibonacci series\n");
for (c = 1; c <= n; c++)
{
int result = FibonacciFunction(i);
Console.Write(result + " " );
i++;
}
Console.WriteLine();
return 0;
}
public static int FibonacciFunction(int n)
{
if (n == 0)
{
return 0;
}
else if (n == 1)
{
return 1;
}
else
{
return (FibonacciFunction(n - 1) + FibonacciFunction(n - 2));
}
}
}
}
Simple and easy solution :
static void Main(string[] args)
{
int number;
Console.WriteLine("enter number");
number = int.Parse(Console.ReadLine());
Console.WriteLine(Recursive(number));
Console.ReadLine();
}
public static int Recursive(int number)
{
if (number <= 2)
{
return 1;
}
else
{
return Recursive(number - 1) + Recursive(number - 2);
}
}
Using one line code:
public static int Fibonacci(int i)
{
return i <= 2 ? 1 : Fibonacci(i - 1) + Fibonacci(i - 2);
}