Use. Net core to realize the function of unpacking red packets

Time:2020-6-22

Requirement description

I used to hate to order takeout. Recently, I often order takeout at noon, because it’s really convenient. Order a good meal in advance, calculate the time, and then I can have a meal at the end of the day, and then I can have more rest at noon.

After ordering, there will be a friend sharing the red bag function. Although the red bag can’t be withdrawn, it can deduct the cost of ordering. For people who often order, it’s really a big temptation to directly use it to deduct cash. The red bag obtained after ordering must be shared before it can be disassembled.

So if you want to realize the following red packet grabbing function, it should be noted that the red packet function described in this paper pays more attention to the generation of random red packets. As for high concurrency, data consistency and other issues, this paper does not cover, the following are the two technical points discussed in this paper:

The total amount of red packets obtained by different consumption amounts is different. The larger the consumption amount is, the larger the total amount of red packets will be, and the more the total amount of red packets will be. Suppose one day, there is a need to ensure that the amount of red packets obtained by the people participating in the red packet snatching fluctuates near the average, that is to say, the maximum amount is subject to normal distribution;

Function realization

In the scenario described in this paper, the amount involved is divided into two parts for better handling of random numbers. The overall schematic diagram is as follows:

Initialization of red packets after consumption

Demand focus: the total amount of red packets shared by users is directly proportional to the total consumption, and the number of sub red packets that can be split is also directly proportional to the total consumption.

For example:

The consumption amount of 10-20 yuan is 10 yuan for a single red packet that can be shared, 20-40 yuan for 5 people, 20 yuan for a single red packet that can be shared, 40-60 yuan for 8 people, 30 yuan for a single red packet that can be shared, 60-100 yuan for 10 people, 40 yuan for a single red packet that can be shared, and 1 yuan for 1 The consumption amount of 0 person is more than 100 yuan, and the single red packet amount that can be shared is 50 yuan, which can be robbed by 10 people

Then we design an entity to represent the red packet information to facilitate the configuration and adjustment of red packet rules

public class RedPacketsInfo
{
/// <summary>
///Maximum consumption amount
/// </summary>
public int MaxAmount { get; set; }
/// <summary>
 ///Minimum consumption amount
  /// </summary>
  public int MinAmount { get; set; }
  /// <summary>
  ///Red packet amount
  /// </summary>
  public int TotalAmount { get; set; }
  /// <summary>
  ///Number of red packets that can be divided
  /// </summary>
  public int RedPacketQuantity { get; set; }
}

Red packet initialization information


private static List<RedPacketsInfo> GetRedPackets()
{
  return new List<RedPacketsInfo>()
  {
    new RedPacketsInfo
    {
      MinAmount = 1000,
      MaxAmount = 2000,
      RedPacketQuantity = 5,
      TotalAmount=1000
    },
    new RedPacketsInfo
    {
      MinAmount = 2000,
      MaxAmount = 3000,
      RedPacketQuantity = 5,
      TotalAmount=1000
    },
    new RedPacketsInfo
    {
      MinAmount = 4000,
      MaxAmount = 6000,
      RedPacketQuantity = 5,
      TotalAmount=1000
    },
    new RedPacketsInfo
    {
      MinAmount = 6000,
      MaxAmount = 8000,
      RedPacketQuantity = 5,
      TotalAmount=1000
    },
    new RedPacketsInfo
    {
      MinAmount = 10000,
      MaxAmount = int.MaxValue,
      RedPacketQuantity = 5,
      TotalAmount=1000
    }
  };
}

Next, we can get the corresponding red packet information through the consumption amount.

Generation time and treatment of random red packets

The generation of random red packets can be generated before or during the process of robbery. Generally speaking, red packets will be allocated dynamically in the process of robbery in many cases. However, in this paper, red packets will be generated in advance after users share successfully. The main reason is to better process the data so that the data can obey the normal distribution.

The following is the flow chart. One part of the logic is the callback function. You may be asked by a circle of friends how to ensure the success of the callback. There are many kinds of processing in this place, such as MQ, task scheduling, etc., which will not be discussed here

Then we need to design a new entity to represent the shared red packets and the generated random red packets:

public class SharedRedPacket
{
  /// <summary>
  ///Shared by userid
  /// </summary>
  public int SenderUserId { get; set; }
  /// <summary>
  ///Sharing time
  /// </summary>
  public DateTime SendTime { get; set; }
  public List<RobbedRedPacket> RobbedRedPackets { get; set; }
}
public class RobbedRedPacket
{
  /// <summary>
  ///Userid of the person who grabbed the red packet
  /// </summary>
  public int UserId { get; set; }
  /// <summary>
  ///Amount of red packets captured
  /// </summary>
  public int Amount { get; set; }
  /// <summary>
  ///Seize the time
  /// </summary>
  public DateTime RobbedTime { get; set; }
}

In the process of implementation, the corresponding red packet is obtained according to the user’s consumption amount, and then n-1 original random data is generated through the random number. The last data is obtained by subtracting the sum of n-1 data from the sum of the last data

//Red packet random split
Random ran = new Random();
List<double> randoms = new List<double>(redPacketsList.Count);
for (int i = 0; i < redPacketsInfo.RedPacketQuantity - 1; i++)
{
  int max = (totalAmount - (redPacketsInfo.RedPacketQuantity - i)) * 1;
  int result = ran.Next(1, max);
  randoms.Add(result);
  totalAmount -= result;
}
randoms.Add(totalAmount);

Then, by setting the coefficients, the data can be processed to conform to the normal distribution

//Positive and negative distribution processing
for (int i = 0; i < redPacketsInfo.RedPacketQuantity; i++)
{
  double a = Math.Sqrt(Math.Abs(2 * Math.Log(randoms[i], Math.E)));
  double b = Math.Cos(2 * Math.PI * randoms[i]);
  randoms[i] = a * b * 0.3 + 1;
}

After the second processing, there is a deviation between the obtained data and the original data. Then we process it again in an equal proportion way to ensure that the total amount of red packets after splitting is equal to the original total amount of red packets:

//Generate final red packet data
double d = originalTotal / randoms.Sum();
SharedRedPacket sharedRedPacket = new SharedRedPacket();
sharedRedPacket.RobbedRedPackets = new List<RobbedRedPacket>(redPacketsList.Count);
for (int i = 0; i < redPacketsInfo.RedPacketQuantity - 1; i++)
{
  sharedRedPacket.RobbedRedPackets.Add(new RobbedRedPacket
  {
    Amount = (int)Math.Round(randoms[i] * d, 0)
  });
}
sharedRedPacket.RobbedRedPackets.Add(new RobbedRedPacket
{
  Amount = originalTotal - sharedRedPacket.RobbedRedPackets.Sum(p => p.Amount)
});

test

The test effect diagram is as follows:

Some of the codes are as follows,

Console.WriteLine ("share input y successfully, input n to exit");
 string result = Console.ReadLine();
 if (result == "Y")
 {
   var leftRedPacket = sharedRedPacket.RobbedRedPackets.Where(p => p.UserId <= 0).ToList();
   var robbedRedPacket = leftRedPacket[new Random().Next(1, leftRedPacket.Count + 1)];
   Console.WriteLine (the amount of the red packet received is:+ robbedRedPacket.Amount );
   Console.WriteLine("-------------------------------------------------------");
 }

summary

The above-mentioned is the use of. Net core introduced by Xiaobian to realize the function of unpacking red packets. I hope it can help you. If you have any questions, please leave me a message, and Xiaobian will reply to you in time!