Returning Fibonacci series c# - c#

I need to make a method that returns the nth integer in the fibonacci series, the code that I wrote (edited) did not work, could anyone guide me in my for loop section. I need to use a webform and return the fibonacci series to a specific point.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
{
public partial class Default : System.Web.UI.Page
{
int i, temp;
public void Page_Load(object sender, EventArgs e)
{
}
public int Fibonacci(int x)
{
if (x == 0)
{
return 1;
}
if (x == 1)
{
return 1;
}
else
{
return (Fibonacci(x - 2) + Fibonacci(x - 1));
}
}
public void btSubmit_Click(object sender, EventArgs e)
{
// getting input from user
int num = Convert.ToInt32(txtInput.Text);
// logic for fibonacci series
for (i = 0; i < num; i++)
{
lblResult.Text = Fibonacci(i).ToString();
}
}
}
}

First of all, we, usually, assume
F(0) = 0,
F(1) = 1,
...
F(N) = F(N - 1) + F(N - 2)
See https://oeis.org/A000045
If you want a serie, let's implement a serie (with a help of IEnumerable<T> and yield return):
using System.Linq;
...
//TODO: do you really want int as a return type? BigInteger seems to be a better choice
public static IEnumerable<int> Fibonacci() {
int n_2 = 1; // your rules; or start Fibonacci from 1st, not 0th item
int n_1 = 1;
yield return n_2;
yield return n_1;
while (true) {
int n = n_2 + n_1;
yield return n;
n_2 = n_1;
n_1 = n;
}
}
Having a generator we can easily take num first Fiboncacci numbers (Linq Take):
lblResult.Text = string.Join(", ", Fibonacci().Take(num));
In case num == 7 we'll get
1, 1, 2, 3, 5, 8, 13
If you want an individual item - ElementAt (index is zero based):
// 8
lblResult.Text = Fibonacci().ElementAt(5).ToString();

You can use an integer array to keep the Fibonacci numbers until n and returning the nth Fibonacci number:
public int GetNthFibonacci_Ite(int n)
{
int number = n - 1; //Need to decrement by 1 since we are starting from 0
int[] Fib = new int[number + 1];
Fib[0]= 0;
Fib[1]= 1;
for (int i = 2; i <= number;i++)
{
Fib[i] = Fib[i - 2] + Fib[i - 1];
}
return Fib[number];
}
and then you can call it like this:
GetNthFibonacci_Ite(7);
and it retuns 7th fibonacci number

Your mistake is that you overwrite the Text, rather then add to it. Change it to lblResult.Text += Fibonacci(i).ToString() to append.
Do however note that appending a lot of text from a Loop to a GUI Element is a problematic opreation. You incur a massive overhead reading and writing GUI Elemetns. It does not mater if you only do it once per user Triggered event, but from a loop you will notice it quickly.
It might be better to build the sequence in the code behind, then dispaly it in one go. I even wrote a example code to showcase that issues:
using System;
using System.Windows.Forms;
namespace UIWriteOverhead
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
int[] getNumbers(int upperLimit)
{
int[] ReturnValue = new int[upperLimit];
for (int i = 0; i < ReturnValue.Length; i++)
ReturnValue[i] = i;
return ReturnValue;
}
void printWithBuffer(int[] Values)
{
textBox1.Text = "";
string buffer = "";
foreach (int Number in Values)
buffer += Number.ToString() + Environment.NewLine;
textBox1.Text = buffer;
}
void printDirectly(int[] Values){
textBox1.Text = "";
foreach (int Number in Values)
textBox1.Text += Number.ToString() + Environment.NewLine;
}
private void btnPrintBuffer_Click(object sender, EventArgs e)
{
MessageBox.Show("Generating Numbers");
int[] temp = getNumbers(10000);
MessageBox.Show("Printing with buffer");
printWithBuffer(temp);
MessageBox.Show("Printing done");
}
private void btnPrintDirect_Click(object sender, EventArgs e)
{
MessageBox.Show("Generating Numbers");
int[] temp = getNumbers(1000);
MessageBox.Show("Printing directly");
printDirectly(temp);
MessageBox.Show("Printing done");
}
}
}
As another commenter mentioned, you may want to go to some form of Multitasking too. Indeed my first Multitasking learnign experience was a Fibbonacci/Prime Number checker. They are good learning examples for that.

Use the method for Fibonacci:
public int Fibonacci(int n)
{
int a = 0;
int b = 1;
for (int i = 0; i < n; i++)
{
int temp = a;
a = b;
b = temp + b;
}
return a;
}
And replace:
lblResult.Text = Fibonacci(i).ToString();
To:
lblResult.Text += Fibonacci(i).ToString();

Related

HeapSort Algorythm from txt file to list of arrays doesn't Sort the numbers

So I have to make HeapSort Algorythm for University using pseudocode I was given (only for heapsort). And I have to use input and output file. But for now I have only made input file which is working fine since it loads the txt file and writes down all the numbers in Console. So the problem is that after adding sorting methods to Main nothing changes. Also I decided to make a test for every method and all of them writes down my numbers once and that is it. I am not really good with sorting so it is hard for me to find the issue. Also because it is from pseudocode I had to use and no the code I could do for myself. So Do You know what cause thats issue that the sorting doesn't occure?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Win32;
using System.IO;
using System.Windows.Forms;
namespace Zad4
{
class Program
{
void Heapify(List<int> array, int i, int n)
{
int largest, temp;
int parent = i;
int left = 2 * i + 1;
int right = 2 * i + 2;
if (left < n && array[left] > array[parent])
{
largest = left;
}
else
{
largest = parent;
}
if (right < n && array[right] > array[largest])
{
largest = right;
}
if (largest != i)
{
temp = array[i];
array[i] = array[largest];
array[largest] = temp;
Heapify(array, largest, n);
}
}
void BuildHeap(List<int> array, int n)
{
int i;
for (i = (n - 1) / 2; i >= 0; i--)
{
Heapify(array, i, n);
}
}
void HeapSort(List<int> array, int n)
{
int i, temp;
for (i = n - 1; i >= 0; i--)
{
temp = array[0];
array[0] = array[n - 1];
array[n - 1] = temp;
n = n - 1;
Heapify(array, 0, n);
Console.WriteLine(string.Join(" ", array));
}
}
static void Main(string[] args)
{
int n = 0;
Program A = new Program();
StreamReader myFile =
new StreamReader("C:\\Users\\dawid\\Desktop\\C#\\Heapsort\\dane.txt");
string myString = myFile.ReadToEnd();
myFile.Close();
char rc = (char)10;
String[] listLines = myString.Split(rc);
List<List<int>> listArrays = new List<List<int>>();
for (int i = 0; i < listLines.Length; i++)
{
List<int> array = new List<int>();
String[] listInts = listLines[i].Split(' ');
for (int j = 0; j < listInts.Length; j++)
{
if (listInts[j] != "\r")
{
array.Add(Convert.ToInt32(listInts[j]));
}
}
listArrays.Add(array);
A.BuildHeap(array, n);
A.HeapSort(array, n);
}
foreach (List<int> array in listArrays)
{
foreach (int i in array)
{
Console.WriteLine(string.Join(" ", array));
}
}
Console.WriteLine();
Console.ReadLine();
}
}
}
So the solution I found is just changing the way I read my txt file and the most important one was bad use of my methods. So that is how it looks now and it sorting well. Maybe I shouldn't ask a question since I got an answer on my own. But well. There You go:
static void Main(string[] args)
{
Program A = new Program();
string[] array = System.IO.File.ReadAllLines(#"C:\Users\dawid\Desktop\C#\Heapsort\dane.txt");
int[] arrayInt = Array.ConvertAll(array, int.Parse);
A.BuildHeap(arrayInt, arrayInt.Length);
A.HeapSort(arrayInt, arrayInt.Length);
Console.WriteLine(string.Join(" ", arrayInt));
Console.ReadLine();
}

Why is my sorting algorithm producing an infinite loop? C#

ok, decided I would mess around and create a very basic Bubble sorting algorithm, I have only spent a couple hours, and this is only my second iteration of the program, and I'm kind of burnt out right now, and I seem to have hit a bit of a wall. I have it designed so that it will produce and display an Integer based on the number of transpositions it made on each round of sorting ( so I can keep an eye on it and make sure it is trending downward) and it is stuck in an infinite loop, returning the value '36' constantly.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
bool sorted = false;
int[] data = new int[100];
data = GenerateData(data);
while (sorted == false)
{
int count = Sort(data);
if (count == 0)
{
sorted = true;
}
else
{
Console.WriteLine("{0}", count);
}
}
}
public static int[] GenerateData(int[] data)
{
Random num = new Random();
for (int x = 0; x < 100; x++)
{
data[x] = num.Next(0, 99);
}
return data;
}
public static int Sort (int[] data)
{
int TempA = 0;
int TempB = 101;
int count = 0;
for (int x =0; x<100; x++)
{
TempA = data[x];
if ((x + 1) < 100)
{
TempB = data[(x + 1)];
}
else
{
TempB = 101;
}
if ( TempA > TempB)
{
data[x++] = TempA;
data[x] = TempB;
count++;
}
}
return count;
}
}
}
I think there is something wrong with these two lines
data[x++] = TempA;
data[x] = TempB;
It should either be
data[x++] = TempA;
data[x--] = TempB;
Or
data[x+1] = TempA;
data[x] = TempB;
Otherwise your for loop will end up skipping elements.

matching characters in strings in visual C#

I'm working on visual C#
to calculate the word error rate
I have one textbox for the refrence which is the correct sentance
and one for the hypothesis which is wrong one.
in order to calculate WER I need to calculate :
substitution : the word that has been changed which was my first question
Insert : the words that had been inserted in the sentence
Deleted: the words that had been deleted from the original sentence
For EX:
refrence: This is a NPL program.
hypothesis: it is an NPL cool.
it: substitution
is: correct
an :substitution
NPL:correct
program: deleted
cool: inserted
I tried the algorithm that dasblinkenlight proposed ( thank you so much by the way )
I worked but there is a runtime error I couldn't figure it out, in line
int x= Compute(buffer[j], buffer_ref[i]);
Index was outside the bounds of the array.
and here is my code :
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
string [] hyp = new string[20];
string [] refrence = new string[20];
string [] Anser= new string[20];
string[] buffer = new string[20];
string[] buffer_ref = new string[20];
int count = 0; // number of words
string ref2=" " ;
string hyp2 = " ";
string Anser2 = " ";
string buffer2 = " ";
int corecct_c=0;
int corecct_d = 0;
int corecct_i = 0;
//====================================================================
public Form1()
{
InitializeComponent();
for (int i = 0; i <= 19; ++i)
{
hyp[i] = null;
buffer[i] = null;
}
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
refrence = this.textBox2.Text.Split(' ');
buffer_ref = this.textBox2.Text.Split(' ');
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
hyp = this.textBox1.Text.Split(' ');
buffer = this.textBox1.Text.Split(' ');
//hyp = this.textBox1.Text;
// fname1.Add(this.textBox1.Text);
}
public void correct(string[] R)
{
for (int i = 0; (i <= 19) && (R[i] != "."); ++i)
{
if (buffer[i] == refrence[i])
{ buffer[i] = "0";
buffer_ref[i] = "0";
corecct_c = corecct_c + 1;
Anser[i] = "C";
}
}
}
// function that compute 2 strings
public static int Compute(string s, string t)
{
int n = s.Length;
int m = t.Length;
int[,] d = new int[n + 1, m + 1];
// Step 1
if (n == 0)
{
return m;
}
if (m == 0)
{
return n;
}
// Step 2
for (int i = 0; i <= n; d[i, 0] = i++)
{
}
for (int j = 0; j <= m; d[0, j] = j++)
{
}
// Step 3
for (int i = 1; i <= n; i++)
{
//Step 4
for (int j = 1; j <= m; j++)
{
// Step 5
int cost = (t[j - 1] == s[i - 1]) ? 0 : 1;
// Step 6
d[i, j] = Math.Min(
Math.Min(d[i - 1, j] + 1, d[i, j - 1] + 1),
d[i - 1, j - 1] + cost);
}
}
// Step 7
return d[n, m];
}
public void sub(){
for (int j = 0;j<=19;j++)
{
if (buffer[j].IndexOf("0") != -1)
{
for (int i = 0; i <= 19; i++)
{
if (buffer_ref[j].IndexOf("0") != -1)
{
int x= Compute(buffer[j], buffer_ref[i]);
if (x > 3)
{
buffer[j] = "0";
Anser[j] = "S";
}
}//end if
}
}//end if
}//end for
}// end fun
private void button1_Click(object sender, EventArgs e)
{
correct(refrence);
sub();
for (int i = 0; (i <= 19) && (refrence[i] != "."); ++i)
{
//loop intialize
ref2 = ref2 + " " + refrence[i];
hyp2 = hyp2 + " " + hyp[i];
Anser2 = Anser2 + " " + Anser[i];
buffer2 = buffer2 + " " + buffer[i];
count++;
}
listBox1.Items.Add(" Refrence :" + ref2);
listBox1.Items.Add(" HYp :" + hyp2);
listBox1.Items.Add(" Anser:" + Anser2);
listBox1.Items.Add(" buffer:" + buffer2);
listBox1.Items.Add(count);
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void label1_Click(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
}
private void label2_Click(object sender, EventArgs e)
{
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}
can you help me please ?
There is a built-in way to test if two lines are identical, but there is no built-in way to tell if two lines are similar. You need to implement an algorithm that measures string similarity, such as the Levenshtein Distance - a very common Edit Distance algorithm. Lines with small edit distance can be declared similar depending on some threshold specific to your requirements.
You'll need to use an algorithm that compares the "distance" between two strings:
The closeness of a match is measured in terms of the number of
primitive operations necessary to convert the string into an exact
match. This number is called the edit distance between the string and
the pattern. The usual primitive operations are:
insertion: cot → coat
deletion: coat → cot
substitution: coat → cost

Creating a reverse ordered array

I am currently trying to create an array and display it reverse or descending order. It currently displays a list of numbers but sometimes it does not follow the correct descending order. I believe the issues is in the if statement in between the two for loops, each time I am comparing a random number between 1-101 with the first number in your array. Instead of doing it that way, How can I compare the numbers in the array with each other? Or any suggestion in proving my reverse order array generator?
CODE
namespace reverseArray
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
long operations = 0;
int size;
int max;
int[] createArray;
int[] sortArray;
int[] copyArray;
public void ReverseOrder()
{
size = Convert.ToInt32(textBoxSize.Text);
max = Convert.ToInt32(textBoxMax.Text);
createArray = new int[size];
copyArray = new int[size];
sortArray = new int[size];
createArray[size - 1] = 1;
for (int i = size - 1; i > 0; i--)
{
createArray[i - 1] = createArray[i] + r.Next(1, max);
}
for (int i = size - 1; i > 0; i--)
{
if (r.Next(1, 101) < createArray[0])
{
for (int x = size - 1; x > 0; x--)
{
createArray[x] = r.Next(1, createArray[0]);
}
}
}
}
private void buttonCreateArray_Click(object sender, EventArgs e)
{
ReverseOrder();
}
}
}
No need to implement your own algorithm to sort or reverse an array.
Use Array.Sort and/or Array.Reverse.
To sort in descending order, first sort then reverse the array.
Use LINQ
using System.Linq;
namespace reverseArray
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
long operations = 0;
int size;
int max;
int[] createArray;
int[] orderedArray;
int[] orderedByDescendingArray;
public int[] CreateArray(int size, int max)
{
var result = new int[size];
Random r = new Random();
for(int i; i<size; i++)
{
result[i] = r.Next(max);
}
return result;
}
private void buttonCreateArray_Click(object sender, EventArgs e)
{
size = Convert.ToInt32(textBoxSize.Text);
max = Convert.ToInt32(textBoxMax.Text);
createArray = CreateArray(size, max);
orderedArray = array.OrderBy(a => a);
orderedByDescendingArray = array.OrderByDescending(a => a);
}
}
}
//P.S. Code may contain errors coz I typed it directly here.
Consder using built methods for sorting like Array.Sort and Enumerable.OrderBy. They have variants that take comaprer to customize sorting.
no need to use logic to create reverse order array. In C# has default method to reverse it. so used that and you can get output ..
string fullOrder= Console.ReadLine();
char[] charArray= fullOrder.ToCharArray();
Array.Reverse(charArray);
Console.WriteLine(charArray);
Console.ReadLine();

How to divide an array into 3 parts with the sum of each part roughly equal

I have an arranged array and I want to divide it into 3 parts so that their sum are closest to each other.
Ex: I have this array:
10, 8, 8, 7, 6, 6, 6, 5
so it'll be divided into 3 part like:
p1 {10,8} sum = 18
p2 {8,7,6} sum = 21
p3 {6,6,5} sum = 17
The original poster already has a working solution (noted in comments) to split the array into two parts with equal sums; call this split2. The three-part version can be constructed using split2.
Add to the array a new number equal to one-third of the sum of the original numbers.
Split the array into two parts using split2.
One part has the number that was added; remove it.
Split the other part into two using split2.
This is like two-Partition problem which is NP-Hard but not in strong sense, you can have an O(nK) algorithm for it where K is size of your input sum, See pseudo polynomial time algorithm for subset sum, Also See my answer for divide-list-in-two-parts-that-their-sum-closest-to-each-other, but in your case you should just add another dimension to process it.
// calculate total
total = 0;
for(i = 0; i != size; ++i) {
total += array[i];
}
// partition
n_partitions = 3;
current_partition = 1;
subtotal = array[0];
for(i = 1; i != size; ++i) {
if(subtotal + array[i] > total / n_partitions) {
// start new partition;
current_partition++;
subtotal = array[i];
} else {
// push to current partition
subtotal += array[i];
}
}
Try the following code
int total = 0, partSum = 0, partIndex = 0;
int noOfParts = 3; //Initialize the no. of parts
int[] input = { 10, 8, 8, 7, 6, 6, 6, 5 };
int[] result = new int[noOfParts]; //Initialize result array with no. of locations equal to no. of parts, to store partSums
foreach (int i in input) //Calculate the total of input array values
{
total += i;
}
int threshold = (total / noOfParts) - (total / input.Length) / 2; //Calculate a minimum threshold value for partSum
for (int j = input.Length - 1; j > -1; j--)
{
partSum += input[j]; //Add array values to partSum incrementally
if (partSum >= threshold) //If partSum reaches the threshold value, add it to result[] and reset partSum
{
result[partIndex] = partSum;
partIndex += 1;
partSum = 0;
continue;
}
}
if (partIndex < noOfParts) //If no. of parts in result[] is less than the no. of parts required, add the remaining partSum value
{
result[partIndex] = partSum;
}
Array.Reverse(result);
foreach (int k in result)
{
Console.WriteLine(k);
}
Console.Read();
I've tested this with various values in array(arranged in descending order) and also with different value for no. of parts(3,4,5...) and got good results.
Updated with code:
The approach I suggest is as follows (with code below):
Create data structures (Collections etc) to represent the number of output parts that you need (in your example 3)
Sort the input array in descending order.
Iterate through the elements of the input array and for each value:
pick an output part to place the value in (this should be the output part currently with the lowest overall sum..)
add the value to the selected output part
With the above logic, you will always be adding to the output part with the lowest overall value (which will help to keep the parts of similar overall value).
(in the code sample below I have skipped the array sorting step as your example is already sorted)
Code:
// the input array
int[] inputArray = new int[] { 10, 8, 8, 7, 6, 6, 6, 5 };
// the number of parts you want
int numberOfOutputParts = 3;
// create the part structures
List<Part> listOfParts = new List<Part>();
for(int i =0; i < numberOfOutputParts; i++)
{
listOfParts.Add(new Part());
}
// iterate through each input value
foreach (int value in inputArray)
{
// find the part with the lowest sum
int? lowestSumFoundSoFar = null;
Part lowestValuePartSoFar = null;
foreach(Part partToCheck in listOfParts)
{
if (lowestSumFoundSoFar == null || partToCheck.CurrentSum < lowestSumFoundSoFar)
{
lowestSumFoundSoFar = partToCheck.CurrentSum;
lowestValuePartSoFar = partToCheck;
}
}
// add the value to that Part
lowestValuePartSoFar.AddValue(value);
}
The code for the Part class used above (although you could use something better is as follows):
public class Part
{
public List<int> Values
{
get;
set;
}
public int CurrentSum
{
get;
set;
}
/// <summary>
/// Default Constructpr
/// </summary>
public Part()
{
Values = new List<int>();
}
public void AddValue(int value)
{
Values.Add(value);
CurrentSum += value;
}
}
Could you try my sample, this may help you
My Algorithm:
1/ Calculate avg value of the array numbers by the number of output array (exp:value=3 in your post)
2/ Sum the array numbers until the Sum has min gap compare to the avg value (calculated in 1/)
3/ Do step 2 until you go to the end of the array numbers
I using C# 3.5 to test
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;
namespace WindowsFormsApplication2
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
ArrayList inputValue = new ArrayList();
int avgValue = 0;
bool isFinish = false;
private void button1_Click(object sender, EventArgs e)
{
#region Init data
isFinish = false;
avgValue = 0;
inputValue.Clear();
listBox1.Items.Clear();
//assum you input valid number without space and in desc sorting order
string[] arrNumber = textBox1.Text.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
int numberOfBreak = 3;
int record = Convert.ToInt32(arrNumber[0]);//update the record with the maximum value of the array numbers
for (int i = 0; i < arrNumber.Length; i++)
{
inputValue.Add(Convert.ToInt32(arrNumber[i]));
}
foreach (object obj in inputValue)
{
avgValue += (int)obj;
}
avgValue = avgValue / numberOfBreak;
#endregion
int lastIndex = 0;
while (!isFinish)
{
int index = GetIndex(lastIndex);
string sResult = "";
for (int i = lastIndex; i <= index; i++)
{
sResult += inputValue[i].ToString() + "-";
}
listBox1.Items.Add(sResult);
if (index + 1 < inputValue.Count)
{
lastIndex = index + 1;
}
sResult = "";
}
}
private int GetIndex(int startIndex)
{
int index = -1;
int gap1 = Math.Abs(avgValue - (int)inputValue[startIndex]);
int tempSum = (int)inputValue[startIndex];
if (startIndex < inputValue.Count - 1)
{
int gap2 = 0;
while (gap1 > gap2 && !isFinish)
{
for (int i = startIndex + 1; i < inputValue.Count; i++)
{
tempSum += (int)inputValue[i];
gap2 = Math.Abs(avgValue - tempSum);
if (gap2 <= gap1)
{
gap1 = gap2;
gap2 = 0;
index = i;
if (startIndex <= inputValue.Count - 1)
{
startIndex += 1;
}
else
{
isFinish = true;
}
if (startIndex == inputValue.Count - 1)
{
index = startIndex;
isFinish = true;
}
break;
}
else
{
index = i - 1;
break;
}
}
}
}
else if (startIndex == inputValue.Count - 1)
{
index = startIndex;
isFinish = true;
}
else
{
isFinish = true;
}
return index;
}
}
}

Categories

Resources