Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
please I want to merge strings of these nature by column in C#:
11111111111
01001111101
10111101010
The procedure for output: Once a column have zero(0) that column turns to zero(0). So expected result for above input should be:
00001101000
Note: My own way was to use mathematical solution via array and looping but I think I should ask if there is a simple way of achieving this in c#. My method seems to take more time if the rows are much.
a way to solve this is to turn the stringBin to a number, then apply an AND between them
public static void Main()
{
string x1 = "11111111111";
string x2 = "01001111101";
string x3 = "10111101010";
long result1 = Convert.ToInt64(x1, 2);
long result2 = Convert.ToInt64(x2, 2);
long result3 = Convert.ToInt64(x3, 2);
long res = result1 & result2 & result3;
string binary = Convert.ToString(res, 2);
Console.WriteLine("This is the result: " + binary);
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
As per title; I have tried multiple ways I can't seem to get my head around where I'm going wrong. I feel this is as close as I've got, but something still seems scrambled. Can someone help me out on finalising this? (This current code consistently outputs 0).
To clarify; I want the code to be able to read the number inputted by a user and figure out how many times it can be halved before reaching 1.
Console.WriteLine("Please enter a number to find how many time it can be divided without becoming less than 1");
Int32 DiviNum = Int32.Parse(Console.ReadLine());
Int32 count = 0;
for (int i = 0; i > 1; i = i / 2)
{
count++;
}
Console.WriteLine("Number of times " + DiviNum + " is divisible by 2 is " + count);
Thanks in advance
Solution is
Console.WriteLine("Please enter a number to find how many time it can be divided without becoming less than 1");
Int32 DiviNum = Int32.Parse(Console.ReadLine());
Int32 count = 0;
for (int i = DiviNum/2 ; i > 1; i = i / 2)
{
count++;
}
Console.WriteLine("Number of times " + DiviNum + " is divisible by 2 is " + count);
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I want to use as loop like : Example
i putted in textbox 123 and 300 in my formula.
1/2*(300+123/300) = 150.205 >> answer
i want to loop this Example i got answer 150.205 next formula should be look like this
1/2*(150.205+123/150.205) = 75.512
the answer of this equation i want to put in next formula by loop.
i have written code but i don't know how to use it via loop
My code.
double value = (0.5 * (300 + 123 / 300));
=======================================
For End loop
When condition match like this
1/2*(11.091+123/11.091) = 11.091
Meaning Answer and input where i m putting 300 will be same i want to break loop
**Example** I want to do this without using square root function in c#
like simple if i want a root of 9 it will be 3 so it will be like this .
i choosen 1 Because 9 is one value so i choosen 1
1/2*(1+9/1) = 5.000
1/2*(5+9/5) = 3.400
1/2*(3.4+9/3.4) = 3.024
1/2*(3.024+9/3.024) = 3.000
1/2*(3+9/3) = 3.000
see you will get same value in one point always
The only tricky thing here is a comparison with tolerance, since because of round up errors you can well never meet
answer == value
condition. The implementation could be
double answer = 300.0;
double tolerance = 1e-10;
while (true) {
// based on previous answer we compute next one
double value = 0.5 * (answer + 123.0 / answer);
//TODO: you can print out steps here, if you want something like this
//Console.WriteLine(value);
// check convergence with tolerance
if (Math.Abs(answer - value) <= tolerance) {
answer = value;
break;
}
// next answer (value) becomes the previous one (answer)
answer = value;
}
// 11.0905365064094
Console.Write(answer);
The actual answer (prove it) is just a square root:
// 11.09053650640941716205160010261...
Console.Write(Math.Sqrt(123));
Real life implementation (if my boss wants me to implement it):
public static double NewtonEstimation(Func<double, double> function,
double tolerance = 1e-10,
double guess = 1.0) {
if (null == function)
throw new ArgumentNullException("function");
else if (tolerance < 0)
throw new ArgumentOutOfRangeException("tolerance", "tolerance must not be negative");
while (true) {
double value = function(guess);
if (Math.Abs(value - guess) <= tolerance)
return value;
guess = value;
}
}
...
// 11.0905365064094
Console.Write(NewtonEstimation(x => 0.5 * (x + 123 / x)));
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I have an assignment that requires a lot conversions between different units of measure. I have all of the work done except the math part. My question is, and if anyone has a better solution im all ears, would it be best to do these calculations using a switch or an if statement? Here is a little background info about my program. I have a text file that contains 9 different units of measurement along with their lengths in terms of feet separated by a comma that looks like as follows:
inch,.083333
fathom,6
foot,1
furlong,660
kilometer,3281.5
meter,3.2815
mile,5280
rod,16.5
yard,3
So, i have successfully dumped all of the information into a string array. From there i split the string array twice. The first time i split the string array, i created a new string array that would hold only the names for each unit of measure. The second time i split the string array, i did it so i could create a double array to hold all of the numeric values for each unit of measurement. Now i need to do the math portion. My program is going to display the nine different units of measure, request the unit to convert from, requests the unit to convert to, request the quantity (or total measurement) to convert, and then display the converted quantity. SO far this is what i have:
private void SandC_Load(object sender, EventArgs e)
{
splitContainer1.Panel1Collapsed = false;
splitContainer1.Panel2Collapsed = true;
string[] lengths = File.ReadAllLines("Units.txt");
int count=0;
string[] unitName=new string[count];
while (!(count==10))
{
count++;
lbLengths.Items.Add(count+"."+" "+lengths[count-1].Split(new Char[]{','})[0]);
}
}
private void btnConvert_Click(object sender, EventArgs e)
{
string orginalunits = tborginalUnits.Text;
int orginalunits1;
string desiredunits = tbDesiredunits.Text;
int desiredunits1;
string lenghttoConvert = tbConvert.Text;
double lenghttoConvert1;
string[] lengths = File.ReadAllLines("Units.txt");
int count = lengths.Length;
double[] units = new double[lengths.Length];
for (int i = 0; i < lengths.Length;i++)
{
units[i] = Convert.ToDouble(lengths[i].Split(new Char[] { ',' })[1]);
}
if ((double.TryParse(lenghttoConvert, out lenghttoConvert1)) && (Int32.TryParse(orginalunits, out orginalunits1)) && (Int32.TryParse(desiredunits, out desiredunits1)))
{
if ((desiredunits1==3)&&(orginalunits1==1))
{
double answer;
answer = units[0] * lenghttoConvert1;
Math.Round(answer, 3);
mtbOutput.Text = Convert.ToString(answer);
lblConversion.Text = "Converted to foot length";
}
}
else
MessageBox.Show("In the'Orginal and Desired Units' boxes, please enter only the numbers 1 -9, and in the 'Length to Covert' Box, please enter only numbers");
}
So as you can see in the button click event, i am at the part where the conversions should take place. My question, once again, is what would be the best method i should use to handle all of these calculations? I already have 1 if statement, and if i am going to do if statements, i feel as if it will be very tedious and was wondering if there was a more efficient way of doing this. Thanks for your help guys, i really do appreciate it.
The best approach is to use a little math to avoid conditionals altogether.
No matter what's the original and target units are, you can do the conversion through by converting the original units to feet and then converting feet to the target unit.
Let's say you want to go from X units at index i to units at index j. All you need to do is dividing X by units[i], and multiplying by units[j]. No conditionals or switches are required.
How would the program know which unit to choose?
This depends on the organization of your program. This could be a very simple task if you use drop-down boxes for unit names in your UI, because the index of the selected item will be the same as the index of the conversion rate in the units[] array.
Given this specific example, if statements and switch statements are both redundant.
Another way to solve this would be to create a mapping table (two dimensional array) where you specify the conversion multiplier between both units especially that your code already uses digits to represent units instead of their actual names.
For example
C[1][1] = 1;
C[1][2] = 3.1;
C[1][3] = 5;
C[1][4] = 0.33;
C[2][1] = 1/C[1][2];
....
....
C[4][1] = 1/C[1][4];
After creating that array, you can simply plugin the numbers depending on the source and destination currencies to do the conversion.
You can further improve on the above by creating one or two if statement that check whether the first parameter for the array is less than the second or not. If yes, then take the value as it is, if not take the reciprocal of the value. Therefore, you dont have to fill the entire array with values such as:
C[2][1] = 1/C[1][2];
C[4][1] = 1/C[1][4];
Hope that helped.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I’m no programmer but I’m learning C# to build a foreign exchange trading system and Arrays are being a struggle…
The problem I have is the following…
I have a one dimensional Array with, let’s say, 100 elements in it.
Now I need to build another one dimensional array with a 10 elements rolling average based on the first Array.
Said in another way, I need to take the elements from the first Array starting in i = 0 up to i = 9 and average them and save the average in a new array. Than move one step forward and take i = 1 up to i = 10 from the original Array and average them and save the result in the new Array….and so forth….in Excel this would be extremely easy….
My need to have the data in Arrays is because later I will need to compare the last 10 elements rolling average with historical data….
Please, can anyone build a sample code that I can work with?
Many thanks
Paulo
Maybe something like this could work... Did this on my mac in sublime text so you'll still have to work with. Should get the point though.
public class Foo
{
List<int> main = new List<int>(100);
List<int> rollingAverages = new List<int>(100);
public void Add(int score)
{
main.Add(score);
if(main.Count > 10)
{
int rollingAverage = AverageLast10();
rollingAverages.Add(rollingAverage);
}
}
public int AverageLast10()
{
int sum = 0;
for(int i = main.Count - 10; i < 10; i++)
{
sum += main[i];
}
return sum / 10;
}
}
Somewhere else in the code
Foo foo = new Foo();
foo.Add(94);
foo.Add(94);
...
yadda yadda yadda