如果内存是我们最大的考虑因素,那么我们根本不需要存储数字,只需要存储 i 和 i + 1之间的 delta。
现在,如果号码范围从2000000-9999999,那么有7,999,999个可能的电话号码。由于我们有100万个数,并且假设它们是均匀分布的,我们在序列数 n _ i 和 n _ i + 1之间有一个 E = n _ i + 1-n _ i ~ 8(3位)的期望距离。所以对于一个32位的 int,我们可以存储多达10个连续的偏移量(大约400kb 的最佳总内存占用量) ,但是在某些情况下,我们可能需要一个大于8的偏移量(也许我们有400个,或者1500个.在这种情况下,我们可以简单地保留整型数的前2位作为头,它告诉我们使用什么帧大小来读取它存储的位。例如,我们可以使用: 00 = 3x10,01 = 5x6,10 = 7x4,11 = 1 * 30。
/********************************************************************************
Filename: Phone_Numbers.c
Author: Paul Romsky
Company: Autoliv AEL
Date: 11 MAR 2013
Problem: What is the most efficient way, memory-wise, to store 1 million
phone numbers?
Caveats: There is no mention if the numbers are contiguous or not, so, to save
space the numbers should be contiguous. The problem (as a specification)
is rather vague and leaves a lot to interpretation, so many different
methods may be desired, but which one(s) desired is not surely known.
Are the phone numbers just the extension (last four digits), or do they
include the exchange (the leading 3 digits), or do they also include
area code and/or international numbers?
There is no mention of the first number, only the range of numbers, so
the first number 000-0000 is used. Although many numbers are not
normally used, they could in fact be used as valid number sequences
within the phone companies and are thus phone numbers nonetheless.
Solution: A simple algorithm. If the numbers are not contiguous a fractal algorithm
could be used.
A standard ANSI C compiler should pack this program into a very small
assembly module of only a few bytes.
Revisions:
Rev Date By Description
--- ----------- -------------------- -------------------------------------------
- 11 MAR 2013 P. Romsky Initial Coding
********************************************************************************/
/* Includes */
#include <stdio.h>
/* Functions */
/********************************************************************************
*
* Main Entry Point
*
********************************************************************************/
int main()
{
unsigned int Number;
/* 1,000,000 Phone Number Storage 000-0000 through 999-9999 */
for(Number = 0000000; Number < 10000000; Number++)
{
/* Retrieve Numbers */
printf("%07u\n", Number);
}
return 0;
}
/* End */