C# program to find no of words that can be generated from a word by adding ' . ' in between characters?
I asked this question in the chat room. but no answer so i am posting the question here.开发者_运维百科
The question is, for example take the word abcd
it has 4 charcters. by adding the ' . ' in between the characters you can write it as a.b.c.d
rules
can use only 1 dot between characters can use multiple dots in the word Edit: there can be characters without ' . ' in between them. eg (ab or abcd) cannot use dot at the beginning or end of the word ie .abcd or abcd. are falsesome of the answers
a.b.c.d a.bcd ab.cd abc.d a.b.cd a.bc.d ab.c.d abc.dhow many word are possible to make. how to write a program to find it in c# ?
Edit how to display each possible word ?
You don't really need to write a program for this.
For a word of n characters, there are n-1 positions where there can be a dot (i.e. between each pair of characters). Each position either has a dot or doesn't.
There are therefore 2n-1 possible words.
If you really want to write a C# program to display this:
using System;
class Test
{
static void Main(string[] args)
{
// Argument validation left as an exercise for the reader
string word = args[0];
Console.WriteLine("Word {0} has {1} possibilities",
word, Math.Pow(2, word.Length - 1));
}
}
EDIT: Note that this assumes that the original word (with no dots) still counts. If you don't want it to count, subtract one from the result.
EDIT: I've changed the computation to use Math.Pow
so that:
- It copes with words with more than 33 letters (up to another limit, of course)
- It's clearer
You can do it recursively.
All possible combinations of (abcd) are:
a + . + all combinations of (bcd)
ab + . + all combinations of (cd)
abc + . + all combinations of (d)
abcd
Code:
public static IEnumerable<string> GetCombinations(string str) {
for (int i = 1; i < str.Length; i++) {
foreach (string s in GetCombinations(str.Substring(i))) {
yield return str.Substring(0, i) + "." + s;
}
}
yield return str;
}
Usage:
foreach (string s in GetCombinations("abcd")) Console.WriteLine(s);
Number of combinations:
string s = "abcd";
int len = s.Length;
int combinations = 1 << (len - 1);
EDIT: as Paul notes in the comments,
int combinations = 1 << (len - 1) - 1;
to remove the word that contains no dots if that's not a valid combination.
Why do you need a program?
if the string is length n, then there are n-1 places you can put a .
In any place, there can either be a . or not, that is, two options.
SO the answer is 2**(n-1) - 1 (the -1 being for the answer that has no dots, i.e the original word)
精彩评论