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 3 years ago.
Improve this question
I have a function that generates a double number between 0 and 2.2:
Random random = new Random();
double value= random.NextDouble() * (2.2 - 0) + 0;
This works great but what I need is to generate the next number with a delta not exceeding 0.2 (positive or negative), i.e. the next random value is within 0.2 of the previously generated one.
For example: If the first random number is: 1.3434434, the next random number should be in the range between 1.5434434 and 1.1434434. The numbers can have a trend going up and then could go down but the difference between the previously generated and the new one cant be greater than 0.2.
Any easy way to achieve this?
I wrote a couple of extension methods to aid with this task. GenerateTrend will generate an infinite enumerable of numbers, and the difference between two consecutive numbers is never going to be larger than delta.
public static class RandomExtensions
{
public static IEnumerable<double> GenerateTrend(this Random random, double start, double delta)
{
var last = start;
while (true)
{
yield return last;
last = random.NextDouble(last - delta, last + delta);
}
}
public static double NextDouble(this Random random, double from, double to)
=> random.NextDouble() * (to - from) + from;
}
Use like this:
var random = new Random();
var start = random.NextDouble(0, 2.2);
var numbers = random.GenerateTrend(start, 0.2).Take(20).ToArray();
As you can see, this being an infinite generator, the calling code is responsible for limiting the amount of random numbers it's taking. In this example, I limit the generation to 20 items by using Take(20).
Related
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 3 years ago.
Improve this question
I'm doing a counting program and i need to multiple all digits of x number by it self.
for example: number 123456789;
1*2*3*4*5*6*7*8*9=362,880
A good solution is provided in the comments, but it isn't very easy to follow if you are trying to figure out what you are actually doing. The following code is a bit more verbose, but shows you what is actually happening each step of the way:
using System;
class MainClass {
public static void Main () {
int myNumber = 123456789; //store original number
int newNumber = (int)Math.Abs(myNumber); //changes the number to positive if it is negative to prevent string formatting errors.
int product = 1; //store product start point
string myString = newNumber.ToString(); //convert number to string
foreach(char number in myString){ //loop through string
string numberString = number.ToString(); //convert chars to strings to ensure proper output
int oneDigit = Convert.ToInt32(numberString); //convert strings to integers
product = product*oneDigit; //multiply each integer by the product and set that as the new product
}
if(myNumber < 0){product = -product;}
//if the number is negative, the result will be negative, since it is a negative followed by a bunch of positives.
//If you want your result to reflect that, add the above line to account for negative numbers.
Console.WriteLine(product); //display product
}
}
Output>>> 362880 //The output that was printed.
So we start by converting our number into a string so we can iterate through it. Then we have a foreach loop that goes through each character in the string, converts it into an integer, and multiplies it by the product of the previous numbers. Each time a new multiplication is performed, the product is updated, until, when you reach the end of the number, you have the product of all digits. This is a good project to become familiar with looping. I would recommend playing around with variations of it such as multiplying each number by the original number, multiplying together only multiples of 3, only multiplying numbers less than 5, or only multiplying the first 5 numbers to get a better handle on what's happening in a loop.
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 5 years ago.
Improve this question
how to generate 6 number as => 2 numbers is Const + and 4 numbers is random for Example => 228796 or 225564
First what you intend to be a GUID isn´t a GUID, which is a reversed thing for something like this: "353e1ff6-0493-48f6-953e-15ec5e383034". As of MSDN:
A GUID is a 128-bit integer (16 bytes) that can be used across all computers and networks wherever a unique identifier is required.
Apart from this you can easily create a randomizer that creates numbers between zero and 9999 and use those numbers as your second part:
string constPart = "22";
Random r = new Random();
string myNumber = constPart + r.Next(0, 10000);
You can - even simpler - also use a randomizer for ranges between 220000 and 229999 as follows:
Random r = new Random();
string myNumber = r.Next(220000, 230000).ToString();
Be aware that those numbers aren´t neccessarily unique. That means the more numbers you create, the more does the probability of duplicates increase.
You can simply just use the Random Class.
Make a new Instance of it and use the Next method which has parameters for minimum, maximum.
class Program
{
static void Main(string[] args)
{
int const1 = 1;
int const2 = 2;
Random rng = new Random();
string id = $"{const1}{const2}";
for(int i = 0; i <= 4; i++)
{
id += $"{rng.Next(0, 10)}";
}
Console.WriteLine(id);
Console.ReadKey(true);
}
}
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 5 years ago.
Improve this question
A concrete example.
If i have a range of 1-300, how can a generate 5 unique numbers within that range using GUID "EDAAE218-FBF0-4B66-AEAF-FB036FBF69F4". Applying the same algorithm to the GUID should result in the same 5 numbers being chosen every time.
The input doesn't have to be a GUID, it's just acting as some sort of key.
Some context for the problem i am trying to solve. I have a hard coded List of values that contains roughly 300 or so elements. I am trying to find a way to select 20 elements from this list that always produces the same elements.
My idea was to generate a GUID which could be handed out to multiple users. When those users input the GUID into the app, the same 20 elements would be returned for everyone.
A guid is effectively a 128-bit number. So you can easily do this provided that the number of bits required to represent your numbers are fewer than the number of bits in the guid (128). You don't need to hash the guid or anything like that.
EDIT:
Now that I know what you need (i.e. a unique seed to be derived from a guid, you could do it this way) - but you could equally hand out a 32-bit number and avoid the guid-to-int conversion.
EDIT2: Using GetHashCode as per suggestion from comments above.
EDIT 3: Producing unique numbers.
static void Main(string[] args)
{
var guid = new Guid("bdc39e63-5947-4704-9e12-ec66c8773742");
Console.WriteLine(guid);
var numbers = FindNumbersFromGuid(guid, 16, 8);
Console.WriteLine("Numbers: ");
foreach (var elem in numbers)
{
Console.WriteLine(elem);
}
Console.ReadKey();
}
private static int[] FindNumbersFromGuid(Guid input,
int maxNumber, int numberCount)
{
if (numberCount > maxNumber / 2) throw new ArgumentException("Choosing too many numbers.");
var seed = input.GetHashCode();
var random = new Random(seed);
var chosenSoFar = new HashSet<int>();
return Enumerable.Range(0, numberCount)
.Select(e =>
{
var ret = random.Next(0, maxNumber);
while (chosenSoFar.Contains(ret))
{
ret = random.Next(0, maxNumber);
}
chosenSoFar.Add(ret);
return ret;
}).ToArray();
}
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 9 years ago.
Improve this question
So I have this problem where I have to calculate the Fibonacci number of any given number from the user. I don't know how to do the actual calculations part, but everything else works. Here's my code. Can someone help me with the calculation part?
using System;
namespace Assignment
{
class MainClass
{
public static void Main (string[] args)
{
int sum = 0;
Console.WriteLine("Fibonacci Number: ");
String fib = Console.ReadLine ();
double result = Convert.ToDouble (fib);
for(int i = 0; i <= result; i++)
{
sum = i * i - 1;
}
Console.WriteLine ("!" + result + " = " + sum);
}
}
}
Extension on recursion approach - use anonymous recursion (which uses Fibonacci as example of recursive call):
Define recursive function: f(n+1) = f(n) + f(n-1);.
Grab definition of Y-Combinator from the article:
delegate Func<A,R> Recursive<A,R>(Recursive<A,R> r);
static Func<A, R> Y<A, R>(Func<Func<A, R>, Func<A, R>> f)
{
Recursive<A, R> rec = r => a => f(r(r))(a);
return rec(rec);
}
Now use Y-combinator to construct recursive function:
Func<int,int> fib = Y<int,int>(f => n => n > 1 ? f(n - 1) + f(n - 2) : n);
Ready to call:
var fibOfSmallNumber = fib(4);
Now for large values you'd need BigInteger
Func<BigInteger,BigInteger> fibForBigNumbers =
Y<BigInteger,BigInteger>(f => n => n > 1 ? f(n - 1) + f(n - 2) : n);
var fibOfBigNumber = fib(4);
Don't expect it to return value in short amount of time - default recursive implementation is very slow. Instead you should apply Memoization to remember previous values of the function (which also covered in the article).
Do you know the definition of the Fibonacci numbers? Please look them up; they have nothing to do with the polynomial x² - 1. The point of the problem is for you to translate the algorithm into C♯.
There are three general approaches you'll find:
Iteration by a for loop.
Recursion.
Direct formulas using exponentiation.
Try it all three ways. I suggest you look at the textbook by Graham, Knuth, and Patashnik, Concrete Mathematics. You'll learn some of the history too.
If what you want is the nth fibonacci number something like this should work:
const double goldenratio = 1.6180339887;
int n = 16;
int nthfib = Math.Round(Math.Pow(goldenratio, n - 1) / Math.Sqrt(5));
nthfib will equal the 16th fibonacci number, 610.
Since the fibonacci sequence gets very large rather quickly, you might need a limit set on n so that nthfib doesn't max out.
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