Vector folding using Divide et Impera in c# - c#

I'm in trouble on a College project.The project needs to be done using c# as a programming language and made in Windows Form like.
The program executes. I know it has flaws but at least i want to know how to get of this error: http://postimg.org/image/gwuzmyc73/ .
For the problem i need to fold a vector using the Divide et Impera.
I need to insert a number from the keyboard n, the generated vector would be like a=(1,2,3,4,5,6,7) and the final elements are 1,3,5,7.
The problem sounds like:
A vector of n elements.We define its folding by overlaping the 2 halfs,if n is odd.The 2 halfs are folded again until de subvector reaches 1 element.Utilize Divide et Impera.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Plierea_Vectorilor
{
public partial class Form1 : Form
{
public int n;
public int i;
public int[] efinal = new int[50];
public string m = new string(new char[50]);
public int Ls, Ld;
public char[] aux = new char[50];
public Form1()
{
InitializeComponent();
}
public void Pliaza(int p,int q)
{
if (p == q)
{
efinal[p] = 1;
}
else
{
if ((q - p + 1) % 2 != 0)
{
Ls = (p + q) / 2 - 1;
}
else
{
Ls = (p + q) / 2;
}
Ld = (p + q) / 2 + 1;
}
Pliaza(p, Ls);
Pliaza(Ld, q);
/*
string ss = Ls.ToString();
string sd = Ld.ToString();
for (i = p; i <= Ls; i++)
{
aux[0] = 'S';
string.Concat(aux, ss);
string.Concat(aux, " ");
string m = aux.ToString();
string.Concat(aux, m[i]);
}
for ( i = Ld; i <= q; i++)
{
aux[0] = 'D';
string.Concat(aux,Ld);
string.Concat(aux, " ");
string m = aux.ToString();
string.Concat(aux, m[i]);
}
*/
}
private void button1_Click(object sender, EventArgs e)
{
Pliaza(1, n);
for (i = 1; i <= n; i++)
{
if (efinal[i]!=0)
{
label2.Text = Convert.ToString(i);
}
}
}
private void label2_Click(object sender, EventArgs e)
{
}
}
}

You're ALWAYS executing the Pliaza function FROM Pliaza. Aren't you missing a finish condition?
The recursive loop must be finished sometime in someway, else you will get that stack overflow.

A StackOverflowException usually means you have uncontrolled recursion going on. Reviewing your code, I see that Pliaza calls itself twice, using different variables ... but there is no path for Pliaza to exit without calling itself. You need some path to let the recursion bottom out. Very likely this would be to add a return; statement after the efinal[p] = 1; line.

Related

I can't get this simple calculation right

I have a very small windows form application that calculates the storage cost for a warehouse depending on the amount of deliveries per year and presents the result in form of a chart.
It's doing what it's supposed to do, but there is just one little flaw.
There is 13 columns in the first bit and then there is 12 every other time.
I want it to always be 12.
I've been trying to reorder some lines of code, it looks like it's all ok, I'm probably just missing one line of code but can't figure it out
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace StorageCost
{
public partial class Form1 : Form
{
public static int throughPot = 52000;
public static int weekly = 1000;
public static int weeklyPalletCost = 180;
public static int deliveries = 2;
public int storageCost;
public static int x = 0;
public static int currentPot = throughPot / deliveries;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Calculate();
}
private void Calculate()
{
currentPot = throughPot / deliveries;
storageCost = 0;
x = 0;
chart1.Series[0].Points[0].YValues[0] = currentPot + 4000;
for (int i = 1; i < 51; i++)
{
currentPot -= weekly;
if (x>= 51 / deliveries)
{
x = 0;
currentPot = throughPot / deliveries;
}
chart1.Series[0].Points[i].YValues[0] = currentPot + 4000;
storageCost += currentPot * weeklyPalletCost;
x++;
}
cost.Text = "Total storage cost: £" + storageCost / 100;
chart1.ChartAreas[0].RecalculateAxesScale();
chart1.Update();
}
private void deliveriesUpDown_ValueChanged(object sender, EventArgs e)
{
deliveries = (int)deliveriesUpDown.Value;
Calculate();
}
}
}
this is the full code.
all I need basically is to get the same result in the beginning as from 13th column onwards
any help will be much appreciated.
thanks in advance.
It was because the first column was done outside of the for loop!
after commenting this out
//currentPot = throughPot / deliveries;
//storageCost = 0;
//x = 0;
//chart1.Series[0].Points[0].YValues[0] = currentPot + 4000;
and changing the loop to for (int i = 0; i < 51; i++)
I got it to work as expected.
Thanks #Grimm
I didn't know about this F11, F10 thing. This helped me a lot!

C# Random Number Generator Error

I am new to C# and random number generators, but need to code a simulator for a course I am taking. I am having difficulty with my for loop and my user-defined variables. I am coding in Visual Studio and need the user to select a number from a list (or input the number as text), but for the program to read it as an integer, not a string, and then use this integer as the number of times to generate a random number.
I will need to assign a probability distribution to this random number generator later, but right now I just need the thing to run! I am getting an error that it cannot covert int to string (or visa versa depending on how I code it). As well as getting an error that my local variable i is unassigned. I have looked at others codes for similar generators and I cannot see a difference in my for loop. Please help! Below is the form space C# code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace GenerateProfile
{
public partial class Form1 : Form
{
int N;
public Form1()
{
InitializeComponent();
}
private void ChooseN_SelectedIndexChanged(object sender, EventArgs e)
{
N = ChooseN;
}
private void SBtn_Click(object sender, EventArgs e)
{
Random rnd = new Random();
int num = rnd.Next(0, 100);
pi.Text = num.ToString();
for (int i; <= N; i++)
{
num = rnd.Next(0, 100);
pi.Text = pi.Text + num.ToString();
}
}
private void ClBtn_Click(object sender, EventArgs e)
{
Close();
}
}
}
I figured it out myself. I was not reading in ChooseN correctly. This fixed it.
private void Gen_Click(object sender, EventArgs e)
{
MessageBox.Show("N=", this.txtN.Text);
N = Convert.ToInt32(txtN.Text);
Random rnd = new Random();
int num = rnd.Next(-1, 1);
pitxt.Text = num.ToString();
int[] = { num };
for (int i = 1; i <= N; i++)
{
num = rnd.Next(-1, 1);
pitxt.Text = pitxt.Text + "," + num.ToString();
int[] = { int[], num };
}

Async Await Loop/Math problems

I'm making a little program to practice with WPF and Async/Await for multithreading, and what the program does is:
Find all the prime numbers between two numbers "a" and "b", and spit them out to a textbox called "Prime1".
Simultaneously in a different task, find all the prime numbers between "c" and "d", and spit them out to a textbox called "Prime2".
A button in the window will allow the user to click it, and it will keep track of how many times it has been clicked, whilst the other two tasks find prime numbers, to demonstrate asynchronous operations.
The code is as follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WPF_Asynch_Project
{
public partial class MainWindow : Window
{
public int ClickAmount = 0;
public MainWindow()
{
InitializeComponent();
DelegationIsAwesome();
}
private void Test_Click(object sender, RoutedEventArgs e)
{
ClickAmount++;
MessageBox.Show("You clicked me " + ClickAmount.ToString() + " times!");
}
private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
}
private async void DelegationIsAwesome()
{
Task enumtask = new Task(() => FindPrimes(100000, 100000000));
Task[] enumall = new Task[2];
enumall[0] = enumtask;
enumall[1] = new Task(() => FindPrimes2(1000, 10000));
enumall.ToList().ForEach(t => t.Start());
await Task.WhenAll(enumall).ConfigureAwait(false);
}
private void FindPrimes(long lower, long upper)
{
for (long i = lower; i < upper; i++)
{
long primeornot = 1;
for (long q = 2; q < i; q++)
{
if (i % q == 0)
{
primeornot = 0;
}
}
if (primeornot == 1)
{
System.Threading.Thread.Sleep(6);
Prime1.Dispatcher.BeginInvoke(
(Action)(()=>{ Prime1.Text += i.ToString() + ", "; }));
}
}
}
private void FindPrimes2(int lower, long upper)
{
for (int i = lower; i < upper; i++)
{
int primeornot = 1;
for (int q = 2; q < i; q++)
{
if (i % q == 0)
{
primeornot = 0;
}
}
if (primeornot == 1)
{
System.Threading.Thread.Sleep(5);
Prime2.Dispatcher.BeginInvoke(
(Action)(() => { Prime2.Text += i.ToString() + ", "; }));
}
}
}
}
}
However I get odd results. The following is a picture from the program:
Obviously the output from the prime-finding methods is incorrect. But why does it keep repeating those same numbers? It also sometimes spits out a number equal to UpperBound even though "i" should never equal or be greater than UpperBound.
What is happening to my output, and how do I fix it?
This has nothing to do with async/await, really.
You're calling BeginInvoke here:
Prime1.Dispatcher.BeginInvoke(
(Action)(()=>{ Prime1.Text += i.ToString() + ", "; }));
... and your lambda expression uses i, which means it will append the current value of i when the delegate executes. That's not necessarily the value of i when you call BeginInvoke.
If you want to capture the value (rather than the variable) you basically need to instantiate a new variable each time. You might as well do the conversion to a string:
string textToAppend = i + ", ";
// No need for braces here...
Prime1.Dispatcher.BeginInvoke((Action)(() => Prime1.Text += textToAppend));
Because you've declared the variable textToAppend inside the loop, each iteration will create a delegate capturing a separate variable.
You need to do this in both of your methods.

sum of any four number always one in C# [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
always one is the result of sum four numbers that less than one.
i changed the number to decimal and float
i used math,truncate
i wrote double before each number in calculation
still the result of sum is one
this my code and I added comment in the code in the place of my quistion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
public partial class WebForm3 : System.Web.UI.Page
{
public double[,] array = new double[4, 4];
public double b1vsb1c1=1.0;
public double b1vsb2c2;
public double b1vsb3c3;
public double b1vsb4c4;
// // .....here cotinue declear variable ,I deleteed to shoritng the code;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click1(object sender, EventArgs e)
{
string isChecked2 = RadioButtonList1.SelectedItem.Value.ToString();
if (RadioButtonList1.SelectedItem.ToString() == "1")
{
b1vsb1c1 = 1.0;
b2vsb1c1 = 1.0;
}
else if (RadioButtonList1.SelectedItem.ToString() == "3")
{
b1vsb2c2 =3.0;
b2vsb1c1 =1.0/3.0;
}
// .....here cotinue test radio button value ,I deleteed to shoritng the code;
array[0,0]=b1vsb1c1;
array[0,1]=b1vsb2c2;
//....here cotinue assign value to array ,I deleteed to shoritng the code;
for (int i = 0; i < 4; i++)
{
sum = 0.0;
av = 0.0;
for (int j = 0; j < 4; j++)
{
sum=(double)sum + (double)array[i,j];
}
// here the sum always one why?!!
av = (double)sum/(double)4.0;
Response.Write(av + "| |");
// here is always result 0.25 why?
}
}
}
}
Try to use an Implicit typing : var to declare your varibales
I tried what you said; I have logic result : here is a sample exmaple:
public class Program
{
public static void Main(string[] args)
{
var p1 = 0.120336943441637;
var p5 = 0.01323706377858;
var p9 = 0.120336943441637;
var p13 = 0.120336943441637;
var sum = p1 + p5 + p9 + p13;
Console.WriteLine(sum);
}
}
Result = 0.374247894103491
Code Run

Why can't I find Sum() of this HashSet. says "Arithmetic operation resulted in an overflow."

I was trying to solve this problem projecteuler,problem125
this is my solution in python(just for understanding the logic)
lim = 10**8
total=0
found= set([])
for start in xrange(1,int(lim**0.5)):
s=start**2
for i in xrange(start+1,int(lim**0.5)):
s += i**2
if s>lim:
break
if str(s) == str(s)[::-1]:
found.add(s)
print sum(found)
the same code I wrote in C# is as follows
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
public static bool isPalindrome(string s)
{
string temp = "";
for (int i=s.Length-1;i>=0;i-=1){temp+=s[i];}
return (temp == s);
}
static void Main(string[] args)
{
int lim = Convert.ToInt32(Math.Pow(10,8));
var found = new HashSet<int>();
for (int start = 1; start < Math.Sqrt(lim); start += 1)
{
int s = start *start;
for (int i = start + 1; start < Math.Sqrt(lim); i += 1)
{
s += i * i;
if (s > lim) { break; }
if (isPalindrome(s.ToString()))
{ found.Add(s); }
}
}
Console.WriteLine(found.Sum());
}
}
}
the code debugs fine until it gives an exception at Console.WriteLine(found.Sum()); (line31). Why can't I find Sum() of the set found
The sum is: 2,906,969,179.
That is 759,485,532 greater than int.MaxValue;
Change int to long in var found = new HashSet<long>(); To handle the value.
You can also use uint however instead of long, however I would recommend using long.

Categories

Resources