Given a function fun, what is the mathematical equation for Rec?
public class Fun {
public static int Rec(int n) {
if ((n==1) || (n==2))
return 1;
else {
int result = 0;
for(int i=2; i<=(n-1); i++)
result = result+Rec(n-1)+ Rec(n-2);
return result;
}
}
}
f(0) = 0
f(1) = 1
f(2) = 1
f(3) = 2
f(4) = 6
f(5) = 24
f(6) = 120
f(7) = 720
f(8) = 5040
f(9) = 40320
f(10) = 362880
f(11) = 3628800
looks like (n-1)!
Related
I have to calculate how many anagrams are in a given word.
I have tried using factorial, permutations and using the posibilities for each letter in the word.
This is what I have done.
static int DoAnagrams(string a, int x)
{
int anagrams = 1;
int result = 0;
x = a.Length;
for (int i = 0; i < x; i++)
{ anagrams *= (x - 1); result += anagrams; anagrams = 1; }
return result;
}
Example: for aabv I have to get 12; for aaab I have to get 4
As already stated in a comment there is a formula for calculating the number of different anagrams
#anagrams = n! / (c_1! * c_2! * ... * c_k!)
where n is the length of the word, k is the number of distinct characters and c_i is the count of how often a specific character occurs.
So first of all, you will need to calculate the faculty
int fac(int n) {
int f = 1;
for (int i = 2; i <=n; i++) f*=i;
return f;
}
and you will also need to count the characters in the word
Dictionary<char, int> countChars(string word){
var r = new Dictionary<char, int>();
foreach (char c in word) {
if (!r.ContainsKey(c)) r[c] = 0;
r[c]++;
}
return r;
}
Then the anagram count can be calculated as follows
int anagrams(string word) {
int ac = fac(word.Length);
var cc = countChars(word);
foreach (int ct in cc.Values)
ac /= fac(ct);
return ac;
}
Answer with Code
This is written in c#, so it may not apply to the language you desire, but you didn't specify a language.
This works by getting every possible permutation of the string, adding every copy found in the list to another list, then removing those copies from the original list. After that, the count of the original list is the amount of unique anagrams a string contains.
private static List<string> anagrams = new List<string>();
static void Main(string[] args)
{
string str = "AAAB";
char[] charArry = str.ToCharArray();
Permute(charArry, 0, str.Count() - 1);
List<string> copyList = new List<string>();
for(int i = 0; i < anagrams.Count - 1; i++)
{
List<string> anagramSublist = anagrams.GetRange(i + 1, anagrams.Count - 1 - i);
var perm = anagrams.ElementAt(i);
if (anagramSublist.Contains(perm))
{
copyList.Add(perm);
}
}
foreach(var copy in copyList)
{
anagrams.Remove(copy);
}
Console.WriteLine(anagrams.Count);
Console.ReadKey();
}
static void Permute(char[] arry, int i, int n)
{
int j;
if (i == n)
{
var temp = string.Empty;
foreach(var character in arry)
{
temp += character;
}
anagrams.Add(temp);
}
else
{
for (j = i; j <= n; j++)
{
Swap(ref arry[i], ref arry[j]);
Permute(arry, i + 1, n);
Swap(ref arry[i], ref arry[j]); //backtrack
}
}
}
static void Swap(ref char a, ref char b)
{
char tmp;
tmp = a;
a = b;
b = tmp;
}
Final Notes
I know this isn't the cleanest, nor best solution. This is simply one that carries the best across the 3 object oriented languages I know, that's also not too complex of a solution. Simple to understand, simple to change languages, so it's the answer I've decided to give.
EDIT
Here's the a new answer based on the comments of this answer.
static void Main(string[] args)
{
var str = "abaa";
var strAsArray = new string(str.ToCharArray());
var duplicateCount = 0;
List<char> dupedCharacters = new List<char>();
foreach(var character in strAsArray)
{
if(str.Count(f => (f == character)) > 1 && !dupedCharacters.Contains(character))
{
duplicateCount += str.Count(f => (f == character));
dupedCharacters.Add(character);
}
}
Console.WriteLine("The number of possible anagrams is: " + (factorial(str.Count()) / factorial(duplicateCount)));
Console.ReadLine();
int factorial(int num)
{
if(num <= 1)
return 1;
return num * factorial(num - 1);
}
}
I have this code that draws hexagons randomly in a grid and coloring them randomly from an array.
What I want to do is press a CP5 button to initialize the drawing function. If I press this button again, it will fill all drawn hexagons with black and re-initialize the drawing function.
Currently this initialize the drawing:
void mousePressed() {
if (active_counter == 0) {
hexagons[int(wide/2)][int(tall/2)].active = true;
active_counter++;
}
}
So I tried this approach:
public void startDrawing(int theValue) {
println("a button event from startDrawing: "+theValue);
c1 = c2;
c2 = color(0,0,0);
if (active_counter == 40) {
fill(color(0));
}
}
This is not working, because “fill” is not connected to “hexagons”, but I have difficulty appending it the right way.
This is the full code:
import controlP5.*;
ControlP5 cp5;
int myColor = color(255);
int c1,c2;
float n,n1;
// ------------- Hexagon grid -------------
Hexagon[] [] hexagons;
float rx = 51;
float ry = 56;
int wide;
int tall;
int hexagon;
int active_counter = 0;
boolean active;
int max_hexagons;
float Xoffset, Yoffset;
int randX;
int randY;
int randD;
int x;
int y;
int[] stepX = { -1, -1, 1, 0, 1, 1 };
int[][] stepY = {{ 0, 1, -1, 1, 0, 1 }, { 0, -1, -1, 1, 0, -1 } };
class Hexagon {
float x;
float y;
int rand;
color[] colors;
boolean active;
Hexagon (float ix, float iy) {
x = ix;
y = iy;
active = false;
// Array of colors
colors = new color[10];
colors[0] = color(#62563D); // Infantry green
colors[1] = color(#2C2B2D); // Parisian night blue
colors[2] = color(#3E2224); // Purple heart
colors[3] = color(#A49F9B); // Wild dove grey
colors[4] = color(#684F40); // Brown
colors[5] = color(#5C573D); // Moss green
colors[6] = color(#B9897F); // Pink
colors[7] = color(#24283B); // Dark blue
colors[8] = color(#1F1D20); // Black
colors[9] = color(#C5A9A2); // Brazilian clay
// Takes the colors array and output random colors
rand = (int)random(colors.length);
}
// ------------- Nested draw -------------
void draw() {
if (active) {
// Call the colors array in random order
fill(colors[rand]);
} else {
noFill();
}
stroke(80);
pushMatrix();
translate(x, y);
beginShape();
vertex(-17, -28);
vertex(17, -28);
vertex(34, 0);
vertex(17, 28);
vertex(-17, 28);
vertex(-34, 0);
endShape(CLOSE);
popMatrix();
}
}
// ------------- setup -------------
void setup() {
size(1000, 700);
// ------------- CP5 control buttons -------------
cp5 = new ControlP5(this);
cp5.addButton("start drawing")
.setValue(0)
.setPosition(20,80)
.setSize(200, 19)
;
// ------------- Create hexagon grid -------------
wide = int(width/rx) + 2;
tall = int (height/ry) + 2;
max_hexagons = 40;
hexagons = new Hexagon [wide] [tall];
for (int y = 0; y < tall; y++) {
for (int x = 0; x < wide; x++) {
if ( x % 2 == 0) {
hexagons[x] [y] = new Hexagon(x*rx, y*ry);
} else {
hexagons[x] [y] = new Hexagon(x*rx, (y-.5)*ry);
}
}
}
float targetX = width/2;
float targetY = height/2;
Xoffset = hexagons [int(wide/2)] [int(tall/2)] .x - targetX;
Yoffset = hexagons [int(wide/2)] [int(tall/2)] .y - targetY;
}
// ------------- draw -------------
void draw () {
background(0);
pushMatrix();
translate(-Xoffset, -Yoffset);
for (int y = 0; y < tall; y++) {
for (int x = 0; x < wide; x++) {
hexagons[x] [y] .draw();
}
}
if (active_counter > 0 && active_counter < max_hexagons) {
nextHex();
}
popMatrix();
myColor = lerpColor(c1,c2,n);
n += (1-n)* 0.1;
}
public void controlEvent(ControlEvent theEvent) {
println(theEvent.getController().getName());
n = 0;
}
public void startDrawing(int theValue) {
println("a button event from startDrawing: "+theValue);
c1 = c2;
c2 = color(0,0,0);
if (active_counter == 40) {
fill(color(0));
}
}
// ------------- Mouse interaction -------------
void mousePressed() {
if (active_counter == 0) {
hexagons[int(wide/2)][int(tall/2)].active = true;
active_counter++;
}
}
// ------------- Drawing next hexagon -------------
void nextHex() {
int randX = int(random(wide));
int randY = int(random(tall));
while (!hexagons[randX][randY] .active) {
randX = int(random(wide));
randY = int(random(tall));
}
int randD = int(random(6));
if (
randX + stepX[randD] >= 0 &&
randX + stepX[randD] < wide &&
randY + stepY[randX % 2][randD] >= 0 &&
randY + stepY[randX % 2][randD] < tall
) {
if (!hexagons[randX + stepX[randD]][randY + stepY[randX % 2][randD]] .active) {
active_counter++;
}
hexagons[randX + stepX[randD]][randY + stepY[randX % 2][randD]] .active = true;
}
}
I need to write the divide function in the Jack language.
my code is:
function int divide(int x, int y) {
var int result;
var boolean neg;
let neg = false;
if(((x>0) & (y<0)) | ((x<0) & (y>0))){
let neg = true;
let x = Math.abs(x);
let y = Math.abs(y);
}
if (y>x){
return 0;
}
let result = Math.divide(x, y+y);
if ((x-(2*result*y)) < y) {
if (neg){
return -(result + result);
} else {
return (result + result);
}
} else {
if (neg){
return -(result + result + 1);
} else {
return (result + result + 1);
}
}
}
this algorithm is sub-optimal since each multiplication operation also requires O(n) addition and subtraction operations.
Can I compute the product 2*result*y without any multiplication?
Thanks
Here's an implementation of (unsigned) restoring division (x/y), I don't actually know Jack though so I'm not 100% sure about this
var int r;
let r = 0;
var int i;
let i = 0;
while (i < 16)
{
let r = r + r;
if ((x & 0x8000) = 0x8000) {
let r = r + 1;
}
if ((y ^ 0x8000) > (r ^ 0x8000)) { // this is an unsigned comparison
let x = x + x;
}
else {
let r = r - y;
let x = x + x + 1;
}
let i = i + 1;
}
return x;
You should be able to turn that into signed division.
Does Microsoft have a good FFT that I can use ?
so I made my owe FFT and it work from some case but now all...
like if I get it
f(t) =10*sin(2*pi *3000*t) + 20*sin(1000* 2* PI* t)
it will work but if I add
+ 5*sin(2*pi*100*T) is start acting fun?
now in Matlab it works good but not in my close, also my fft only seem to return the right numbers in the Image not so much in the real...
here is my code:
enter code here
public struct polar1
{
public double real;
public double img;
};
private float Fs;
private int N;
private polar1 [] F;
private int R;
public DSPclass(float[] DSP1,int f1)
{
N = DSP1.Length;
R = DSP1.Length;
F = new polar1[N];
Fs = (float)f1;
}
public void FFT1(float[] DSP1)
{
polar1[] x = new polar1[DSP1.Length];
for (int v = 0; v < N; v++)
{
x[v].real = DSP1[v];
x[v].img = 0;
}
F = FFT(x);
int temp;
}
public polar1[] FFT(polar1[] x)
{
int N2 = x.Length;
polar1[] X = new polar1[N2];
if (N2 == 1)
{
return x;
}
polar1[] odd = new polar1[N2 / 2];
polar1[] even = new polar1[N2 / 2];
polar1[] Y_Odd = new polar1[N2 / 2];
polar1[] Y_Even = new polar1[N2 / 2];
for (int t = 0; t < N2 / 2; t++)
{
even[t].img = x[t * 2].img;
even[t].real = x[t * 2].real;
odd[t].img = x[(t * 2) + 1].img;
odd[t].real = x[(t * 2) + 1].real;
}
Y_Even = FFT(even);
Y_Odd = FFT(odd);
polar1 temp4;
for (int k = 0; k < (N2 / 2); k++)
{
temp4 = Complex1(k, N2);
X[k].real = Y_Even[k].real + (Y_Odd[k].real * temp4.real);
X[k + (N2 / 2)].real = Y_Even[k].real - (Y_Odd[k].real * temp4.real);
X[k].img = Y_Even[k].img + (Y_Odd[k].real * temp4.img);
X[k + (N2 / 2)].img = Y_Even[k].img - (Y_Odd[k].real * temp4.img);
}
return X;
}
public double magnitude( polar1 temp)
{
double tempD;
tempD = Math.Sqrt ( (temp.img * temp.img) + (temp.real * temp.real));
return tempD;
}
public polar1 Complex2(int K, int N, int F3)
{
polar1 temp;
double temp1;
temp1 = (2D * K *F3) / N;
if (temp1 % 2 == 0 || temp1 == 0)
{
temp.real = 1D;
temp.img = 0D;
}
else if ((temp1 - 1) % 2 == 0)
{
temp.real = -1D;
temp.img = 0D;
}
else if ((temp1 / .5D) - 1 % 2 == 0)
{
if ((temp1 - .5D) % 2 == 0)
{
temp.real = 0D;
temp.img = -1D;
}
else
{
temp.real = 0D;
temp.img = 1D;
}
}
else
{
temp.real = Math.Cos(temp1 * Math.PI);
temp.img = -1D * Math.Sin(temp1 * Math.PI);
}
return temp;
}
public polar1 Complex1(int K, int N3)
{
polar1 temp;
double temp1;
temp1 = (2D * Math.PI *K) / N3;
temp.real = Math.Cos(temp1);
temp.img = Math.Sin(temp1);
return temp;
}
public int Apm(double[] img, double[] real)
{
for (int i = 0; i < R; i++)
{
img[i] = F[i].img;
real[i] = F[i].real;
}
return R;
}
public int frequencies(float [] freq, float [] Ctemp)
{
bool flag = false;
bool flagD = false;
float tempOld = 0;
float tempNew =0;
int tempc = 0;
int counter = 0;
for (int i = 0; i < R; i++)
{
if (((i / N) * Fs) >= (Fs / 2))
{
return counter;
}
if ((int)F[i].img != 0 )
{
flag = true;
tempOld = (float)(Math.Abs(F[i].img));
}
else
{
if (flagD == true)
{
freq[counter] = ((float)tempc / (float)N) * Fs;
Ctemp[counter] = tempNew; //magnitude(F[tempc]);
counter++;
flagD = false;
}
flag = false;
tempOld = 0;
tempNew = 0;
}
if(flag == true)
{
if (tempOld > tempNew)
{
tempNew = tempOld;
tempc = i;
flagD = true;
}
}
}
return counter;
}
}
I am able to do this query just fine with the test repository which is In Memory
when I move to the sqlRepository I get this error
Unsupported overload used for query operator 'Intersect'.
I assume it is because sending the query to sql is too complicated for Linq to Sql to do when it is not dealing with the Model.Model.Talent Type. Is there some way around doing a search like this with Intersect?
thanks
public class TalentService : ITalentService
{
ITalentRepository _repository = null;
private IQueryable<Talent> BasicSearch(string searchExpression)
{
IQueryable<Talent> t;
string[] sa = searchExpression.Trim().ToLower().Replace(" ", " ").Split(' ');
t = _repository.GetTalents();
foreach (string s in sa)
{
t = t.Intersect(AddBasicSearch(s), new TalentComparer());
}
return t;
}
private IQueryable<Talent> AddBasicSearch(string s)
{
IQueryable<Talent> t2 = _repository.GetTalents()
.Where(tal => tal.EyeColor.ToString().ToLower().Contains(s)
|| tal.FirstName.ToLower().Contains(s)
|| tal.LastName.ToLower().Contains(s)
|| tal.LanguagesString.ToLower().Contains(s)
);
return t2;
}
}
public class SqlTalentRepository:ITalentRepository
{
public IQueryable<Model.Model.Talent> GetTalents()
{
var tal = from t in _db.Talents
let tLanguage = GetTalentLanguages(t.TalentID)
where t.Active == true
select new Model.Model.Talent
{
Id = t.TalentID,
FirstName = t.FirstName,
LastName = t.LastName,
TalentLanguages = new LazyList<Model.Model.TalentLanguage>(tLanguage),
LanguagesString = t.TalentLanguages.ToLanguageNameString(_LanguageRepository.GetLanguages())
};
return tal ;
}
public IQueryable<Model.Model.TalentLanguage> GetTalentLanguages(int iTalentId)
{
var q = from y in this.talentLanguageList
let Languages = _LanguageRepository.GetLanguages()
where y.TalentId == iTalentId
select new Model.Model.TalentLanguage
{
TalentLanguageId = y.TalentLanguageId,
TalentId = y.TalentId,
LanguageId = y.LanguageId,
Language = Languages.Where(x => x.LanguageId == y.LanguageId).SingleOrDefault()
};
return q.AsQueryable<Model.Model.TalentLanguage>();
}
}
public static class TalentExtensions
{
public static string ToLanguageNameString(this IEnumerable<TalentLanguage> source
, IEnumerable<Model.Model.Language> allLanguages)
{
StringBuilder sb = new StringBuilder();
const string del = ", ";
foreach (TalentLanguage te in source)
{
sb.AppendFormat("{0}{1}", allLanguages
.Where(x => x.LanguageId == te.LanguageID).SingleOrDefault().LanguageName, del);
}
string sReturn = sb.ToString();
if (sReturn.EndsWith(del))
sReturn = sReturn.Substring(0, sReturn.Length - del.Length);
return sReturn;
}
}
public class TestTalentRepository : ITalentRepository
{
IList<Talent> talentList;
public TestTalentRepository(ILanguageRepository _LanguageRepo )
{
this._LanguageRepository = _LanguageRepo;
talentList = new List<Talent>();
talentLanguageList = new List<TalentLanguage>();
for (int i = 0; i < 55; i++)
{
var t = new Talent();
t.Id = i;
t.FirstName = (i % 3 == 0) ? "Ryan" : "Joe";
t.LastName = (i % 2 == 0) ? "Simpson" : "Zimmerman";
AddLanguagesToTestTalent(i, t);
talentList.Add(t);
}
}
private void AddLanguagesToTestTalent(int i, Talent t)
{
IList<Language> Languages = _LanguageRepository.GetLanguages().ToList<Language>();
Random rLanguages = new Random();
int numLanguages = rLanguages.Next(Languages.Count - 1) + 1;
t.TalentLanguages = new LazyList<TalentLanguage>();
for (int j = 0; j < numLanguages; j++)
{
var x = new TalentLanguage();
x.TalentLanguageId = j;
x.TalentId = i;
Random random2 = new Random();
int rand = random2.Next(Languages.Count);
var y = Languages.ElementAtOrDefault(rand);
Languages.RemoveAt(rand);
x.Language = y;
x.LanguageId = y.LanguageId;
t.TalentLanguages.Add(x);
}
}
public IQueryable<Talent> GetTalents()
{
var ts = from t in this.talentList
let tLanguage = GetTalentLanguages(t.Id)
where t.Active == true
select new Model.Model.Talent
{
Id = t.Id,
FirstName = t.FirstName,
LastName = t.LastName,
TalentLanguages = new LazyList<Model.Model.TalentLanguage>(tLanguage),
LanguagesString = t.TalentLanguages.ToLanguageNameString(_LanguageRepository.GetLanguages()),
City = t.City,
};
return ts.AsQueryable<Model.Model.Talent>();
}
public IQueryable<Model.Model.TalentLanguage> GetTalentLanguages(int iTalentId)
{
var q = from y in this.talentLanguageList
let Languages = _LanguageRepository.GetLanguages()
where y.TalentId == iTalentId
select new Model.Model.TalentLanguage
{
TalentLanguageId = y.TalentLanguageId,
TalentId = y.TalentId,
LanguageId = y.LanguageId,
Language = Languages.Where(x => x.LanguageId == y.LanguageId).SingleOrDefault()
};
return q.AsQueryable<Model.Model.TalentLanguage>();
}
}
If you're trying to find entries which match all of those criteria, you just need multiple where clauses:
private static readonly char[] SplitDelimiters = " ".ToCharArray();
private IQueryable<Talent> BasicSearch(string search)
{
// Just replacing " " with " " wouldn't help with "a b"
string[] terms = search.Trim()
.ToLower()
.Split(SplitDelimiters,
StringSplitOptions.RemoveEmptyEntries);
IQueryable<Talent> query = _repository.GetTalents();
foreach (string searchTerm in terms)
{
query = AddBasicSearch(query, searchTerm);
}
return query;
}
private IQueryable<Talent> AddBasicSearch(IQueryable<Talent> query, string s)
{
return query.Where(tal =>
tal.EyeColor.ToString().ToLower().Contains(s)
|| tal.FirstName.ToLower().Contains(s)
|| tal.LastName.ToLower().Contains(s)
|| tal.LanguagesString.ToLower().Contains(s)
);
}