gpt4 book ai didi

algorithm - F# - Facebook 黑客杯 - 双方 block

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:51:08 26 4
gpt4 key购买 nike

我正在努力加强我的 F#-fu,并决定解决 Facebook Hacker Cup Double Squares 问题。我在运行时遇到了一些问题,想知道是否有人可以帮助我弄清楚为什么它比我的 C# 等效程序慢得多。

另一个帖子有很好的描述;

Source: Facebook Hacker Cup Qualification Round 2011

A double-square number is an integer X which can be expressed as the sum of two perfect squares. For example, 10 is a double-square because 10 = 3^2 + 1^2. Given X, how can we determine the number of ways in which it can be written as the sum of two squares? For example, 10 can only be written as 3^2 + 1^2 (we don't count 1^2 + 3^2 as being different). On the other hand, 25 can be written as 5^2 + 0^2 or as 4^2 + 3^2.

You need to solve this problem for 0 ≤ X ≤ 2,147,483,647.

Examples:

10 => 1

25 => 2

3 => 0

0 => 1

1 => 1

Numbers From Competition

1740798996
1257431873
2147483643
602519112
858320077
1048039120
415485223
874566596
1022907856
65
421330820
1041493518
5
1328649093
1941554117
4225
2082925
0
1
3

我的基本策略(我愿意接受批评)是:

  1. 为初始化为 0 的输入数字创建一个字典(用于内存)
  2. 获取最大的数(LN),传给count/memo函数
  3. 获取整数形式的 LN 平方根
  4. 计算所有数字 0 到 LN 的平方并存储在字典中
  5. 从 0 到 LN 的非重复数字组合的平方和
    • 如果 sum 在 memo dict 中,则将 1 添加到 memo
  6. 最后输出原始数的个数。

这是我编写的 F# 代码(请参阅底部的代码更改),我认为它符合此策略(运行时间:~8:10);

open System
open System.Collections.Generic
open System.IO

/// Get a sequence of values
let rec range min max =
seq { for num in [min .. max] do yield num }

/// Get a sequence starting from 0 and going to max
let rec zeroRange max = range 0 max

/// Find the maximum number in a list with a starting accumulator (acc)
let rec maxNum acc = function
| [] -> acc
| p::tail when p > acc -> maxNum p tail
| p::tail -> maxNum acc tail

/// A helper for finding max that sets the accumulator to 0
let rec findMax nums = maxNum 0 nums

/// Build a collection of combinations; ie [1,2,3] = (1,1), (1,2), (1,3), (2,2), (2,3), (3,3)
let rec combos range =
seq {
let count = ref 0
for inner in range do
for outer in Seq.skip !count range do
yield (inner, outer)
count := !count + 1
}

let rec squares nums =
let dict = new Dictionary<int, int>()
for s in nums do
dict.[s] <- (s * s)
dict

/// Counts the number of possible double squares for a given number and keeps track of other counts that are provided in the memo dict.
let rec countDoubleSquares (num: int) (memo: Dictionary<int, int>) =
// The highest relevent square is the square root because it squared plus 0 squared is the top most possibility
let maxSquare = System.Math.Sqrt((float)num)

// Our relevant squares are 0 to the highest possible square; note the cast to int which shouldn't hurt.
let relSquares = range 0 ((int)maxSquare)

// calculate the squares up front;
let calcSquares = squares relSquares

// Build up our square combinations; ie [1,2,3] = (1,1), (1,2), (1,3), (2,2), (2,3), (3,3)
for (sq1, sq2) in combos relSquares do
let v = calcSquares.[sq1] + calcSquares.[sq2]
// Memoize our relevant results
if memo.ContainsKey(v) then
memo.[v] <- memo.[v] + 1

// return our count for the num passed in
memo.[num]


// Read our numbers from file.
//let lines = File.ReadAllLines("test2.txt")
//let nums = [ for line in Seq.skip 1 lines -> Int32.Parse(line) ]

// Optionally, read them from straight array
let nums = [1740798996; 1257431873; 2147483643; 602519112; 858320077; 1048039120; 415485223; 874566596; 1022907856; 65; 421330820; 1041493518; 5; 1328649093; 1941554117; 4225; 2082925; 0; 1; 3]

// Initialize our memoize dictionary
let memo = new Dictionary<int, int>()
for num in nums do
memo.[num] <- 0

// Get the largest number in our set, all other numbers will be memoized along the way
let maxN = findMax nums

// Do the memoize
let maxCount = countDoubleSquares maxN memo

// Output our results.
for num in nums do
printfn "%i" memo.[num]

// Have a little pause for when we debug
let line = Console.Read()

这是我在 C# 中的版本(运行时:~1:40:

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;

namespace FBHack_DoubleSquares
{
public class TestInput
{
public int NumCases { get; set; }
public List<int> Nums { get; set; }

public TestInput()
{
Nums = new List<int>();
}

public int MaxNum()
{
return Nums.Max();
}
}

class Program
{
static void Main(string[] args)
{
// Read input from file.
//TestInput input = ReadTestInput("live.txt");

// As example, load straight.
TestInput input = new TestInput
{
NumCases = 20,
Nums = new List<int>
{
1740798996,
1257431873,
2147483643,
602519112,
858320077,
1048039120,
415485223,
874566596,
1022907856,
65,
421330820,
1041493518,
5,
1328649093,
1941554117,
4225,
2082925,
0,
1,
3,
}
};

var maxNum = input.MaxNum();

Dictionary<int, int> memo = new Dictionary<int, int>();
foreach (var num in input.Nums)
{
if (!memo.ContainsKey(num))
memo.Add(num, 0);
}

DoMemoize(maxNum, memo);

StringBuilder sb = new StringBuilder();
foreach (var num in input.Nums)
{
//Console.WriteLine(memo[num]);
sb.AppendLine(memo[num].ToString());
}

Console.Write(sb.ToString());

var blah = Console.Read();
//File.WriteAllText("out.txt", sb.ToString());
}

private static int DoMemoize(int num, Dictionary<int, int> memo)
{
var highSquare = (int)Math.Floor(Math.Sqrt(num));

var squares = CreateSquareLookup(highSquare);
var relSquares = squares.Keys.ToList();

Debug.WriteLine("Starting - " + num.ToString());
Debug.WriteLine("RelSquares.Count = {0}", relSquares.Count);

int sum = 0;
var index = 0;
foreach (var square in relSquares)
{
foreach (var inner in relSquares.Skip(index))
{
sum = squares[square] + squares[inner];
if (memo.ContainsKey(sum))
memo[sum]++;
}
index++;
}

if (memo.ContainsKey(num))
return memo[num];

return 0;
}

private static TestInput ReadTestInput(string fileName)
{
var lines = File.ReadAllLines(fileName);
var input = new TestInput();
input.NumCases = int.Parse(lines[0]);
foreach (var lin in lines.Skip(1))
{
input.Nums.Add(int.Parse(lin));
}

return input;
}

public static Dictionary<int, int> CreateSquareLookup(int maxNum)
{
var dict = new Dictionary<int, int>();
int square;
foreach (var num in Enumerable.Range(0, maxNum))
{
square = num * num;
dict[num] = square;
}

return dict;
}
}
}

感谢您的关注。

更新

稍微改变连击函数将导致相当大的性能提升(从 8 分钟到 3:45):

/// Old and Busted...
let rec combosOld range =
seq {
let rangeCache = Seq.cache range
let count = ref 0
for inner in rangeCache do
for outer in Seq.skip !count rangeCache do
yield (inner, outer)
count := !count + 1
}

/// The New Hotness...
let rec combos maxNum =
seq {
for i in 0..maxNum do
for j in i..maxNum do
yield i,j }

最佳答案

同样,x^2 + y^2 = k 的整数解的个数是

  • 零,如果有一个质因数等于 3 mod 4
  • 等于 1 mod 4 的 k 的素数约数的四倍。

请注意,在第二种选择中,您将 a^2 + b^2 算作 (-a)^2 + b^2(和其他符号)和 b^2 + a^2 的不同解。因此,如果您想要解决方案作为集合而不是有序对,您可能想要除以 4,然后再除以 2(请发言,正如@Wei Hu 所指出的)。

知道了这一点,编写一个给出解数的程序就很容易了:一劳永逸地计算最多 46341 个素数。

给定 k,使用上面的列表计算 k 的质因数(测试到 sqrt(k))。计算等于 1 mod 4 的那些,然后求和。如果需要,将答案乘以 4。

所有这些都是任何惰性函数式语言中的一两行代码(我对 f# 了解不够,在 Haskell 中它有两行那么长),一旦你有了一个 primes 无限序列:计算除数 = 1 mod 4(filterby |> count 或类似的东西)是很自然的事情。

我怀疑它比强制分解更快。

关于algorithm - F# - Facebook 黑客杯 - 双方 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4681434/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com