开发者

C# for those who are good in Math

开发者 https://www.devze.com 2023-02-01 00:31 出处:网络
I\'ve a number Between 10 and 30, I need to present this number in 4 operation addition or subtraction but both should be present at least one time so always we need to use addition and subtraction at

I've a number Between 10 and 30, I need to present this number in 4 operation addition or subtraction but both should be present at least one time so always we need to use addition and subtraction at least one time.

Here is an example:

The number is 21 I need to generate: 5+6 , 8-5, 9-4, 1+1 (11+3+5+2)=21 (or any other combination equals to 21)

I need generate 4 operations for any number between 10 and 开发者_开发知识库30

anyone could help me out?

If you have a sample in Java, C# or VB it works for me.


Maybe something like this, customize it to meet your needs:

Random rn = new Random();
        int a, b, c, d;

        int min = 3, max = 10;
        int desired = 30;
        while
            (
            (
            (a = rn.Next(min, max))
            + (b = rn.Next(min, max))
            + (c = rn.Next(min, max))
            + (d = rn.Next(min, max))
            )
            != desired
            ) { }

        int x = rn.Next(-1* (a - 1 ), a - 1);
        int y = rn.Next(-1 * (b - 1), b - 1);
        int z = rn.Next(-1 * (c - 1), c - 1);
        int v = rn.Next(-1 * (d - 1), d - 1);

        string result =
            (x >= 0 ? (a - x) + "+" + x : (a + -1 * x) + "-" + -1 * x) + " + " +
            (y >= 0 ? (b - y) + "+" + y : (b + -1 * y) + "-" + -1 * y) + " + " +
            (z >= 0 ? (c - z) + "+" + z : (c + -1 * z) + "-" + -1 * z) + " + " +
            (v >= 0 ? (d - v) + "+" + v : (d + -1 * v) + "-" + -1 * v);


Homework?

You could try to split this into two operations:

  • write the target number as a sum of 4 numbers
  • write those numbers as addition or subtraction.

You do know about System.Random? You could use that to generate some numbers, then try if you can make them "fit".


i once found decent solution about this. but sadly forgot. but what i found is the guy implement by using LINQ mixed with random operator to get all possibility as IEnumerable and .First() to do the magic.

0

精彩评论

暂无评论...
验证码 换一张
取 消