How to find binary representation for n'th Fibonacci number - binary

Its my first post here, so if I commit some mistake please let me know.
I have been given a assignment, and a part of it requires the binary representation of n'th Fibonacci number.
Constraints-
) C++ has to be used as prog. language.
) n'th fib. number has to be calculated in lg(n) time.
I have a function but it works on integers. But the maximum value for which I have to do calculations is about 10^6. So, I am badly stuck here.
Whatever I know, I can't apply in this scenario, because I can generate n'th fib. using strings but that will have linear time complexity.
following is the function,
void multiply(long int F[2][2], long int M[2][2]);
void power(long int F[2][2], long int n);
// Function to Calculate n'th fibonacci in log(n) time
long int fib(long int n)
{
long int F[2][2] = {{1,1},{1,0}};
if(n == 0)
return 0;
power(F, n-1);
return F[0][0];
}
void power(long int F[2][2], long int n)
{
if( n == 0 || n == 1)
return;
long int M[2][2] = {{1,1},{1,0}};
power(F, n/2);
multiply(F, F);
if( n%2 != 0 )
multiply(F, M);
}
void multiply(long int F[2][2], long int M[2][2])
{
long int x = (F[0][0]*M[0][0])%mod + (F[0][1]*M[1][0])%mod;
long int y = (F[0][0]*M[0][1])%mod + (F[0][1]*M[1][1])%mod;
long int z = (F[1][0]*M[0][0])%mod + (F[1][1]*M[1][0])%mod;
long int w = (F[1][0]*M[0][1])%mod + (F[1][1]*M[1][1])%mod;
F[0][0] = x;
F[0][1] = y;
F[1][0] = z;
F[1][1] = w;
}
int main(){
int n; cin >> n; cout << fib(n)<<endl; getchar();
}
As it can be seen, only predefined data types can be used in this function.

Since this is homework, I'll only give you little hints.
The two problems are unrelated, so you need two methods: toBinary and fib. toBinary (fib (n)); would be your solution.
For solving the toBinary part, division and modulo are useful and can be called recursively.
If you calculate fib (n) as fib (n-1) + fib (n-2), there is a trap to step into, that when you calculate fib (n-1) as fib (n-2) + fib (n-3), you end up calculating fib (n-2) twice, fib (n-3) three times and so on.
Instead, you should start from (0 + 1) and step upwards, passing already calculated forward.
After a short test, I see how fast the Fibonacci numbers are growing. Do you have access to Ints of arbitrary size, or are you expected to use preallocated arrays?
Then you would need an add method, which takes the lower and the higher number as array of Integers or Booleans, and creates the sum in the lower array, which then becomes the upper array.
update:
Since you solved the problem, I feel free to post my solution for reference, written in Scala:
import annotation._
/**
add two arrays recursively. carry the position pos and the overrun
overrun=0 = 1 0 1 0 1
Sum low | next | Sum
0 1 | overrun | %2
high 0| 0 1 1 2 | 0 0 0 1 | 0 1 1 0
1| 1 2 2 3 | 0 1 1 1 | 1 0 0 1
*/
#tailrec
def add (low: Array[Int], high: Array[Int], pos: Int = 0, overrun: Int = 0): Array[Int] = {
if (pos == higher.size) {
if (overrun == 0) low else sys.error ("overrun!")
} else {
val sum = low (pos) + high (pos) + overrun
low (pos) = (sum % 2)
add (low, high, pos + 1, if (sum > 1) 1 else 0)
}
}
/** call cnt (example: 5) steps of
fib (5, 0, 1),
fib (4, 1, 1),
fib (3, 1, 2),
fib (2, 2, 3),
fib (1, 3, 5),
fib (0, 5, 8) */
#tailrec
def fib (cnt: Int, low: Array[Int], high: Array[Int]): Array[Int] = {
if (cnt == 0) low else fib (cnt - 1, high, add (low, high)) }
/** generate 2 Arrays, size dependent on n of about 0.7*n + 1, big enough to
hold values and result. Result has to be printed in reverse order, from the highest bit
*/
def fibonacci (n: Int) = {
val lower = Array.fill (n * 7 / 10 + 1)(0) // [...000]
val higher = Array.fill (n * 7 / 10 + 1)(0) // [...000]
higher (0) = 1 // [...001]
val res = fib (n, lower, higher)
res.reverse.foreach (print)
println ()
res
}
fibonacci (n)
For fibonacci (10000) I get a result of nearly 7000 binary digits, and the relation 10/7 is constant, so the millionth Fibonacci digit will have about 1.4 M digits.

The better method would be to use Matrix Exponentiation, which would calculate n'th fib. in lg(n) time. ( usefull for various online coding contests) See Method 4 of This post.

Related

Recursive Function that divides two integers and returns result and remainder

I am trying to create a recursive function that divides two integers n and m and then displays the result and the remainder of the division.
Basicly I created two separate functions which do exactly what I want:
let rec div1 (n: int, m: int): int =
if n<m then n else div1(n-m, m)
printfn "Remainder: %i" (div1(5,5))
let rec div2 (n: int, m: int): int =
if n<m then 0 else 1+div2(n-m, m)
printfn "Result: %i" (div2(5,5))
The thing is, I want to do them both at once, I mean in one function like let rec div12 (n: int) (m : int): int * int = , not in two separate.
I am not sure how exactly this would work on F#.
A function may return more than just a number. For example, a function may return a tuple of two numbers:
let f x = (x, x+5)
f 5
> (5, 10)
Further, you can destructure return value of such a function in a similar way:
let (x, y) = f 5
x
> 5
y
> 10
Now we can use this to have our div+mod function return two results - remainder and quotient:
let rec divMod n m =
if n < m
then
(n, 0)
else
let (remainder, quotient) = divMod (n-m) m
(remainder, quotient + 1)
Note how this function simply combines results of your div1 and div2 in a tuple, then destructures them after the recursive call.
divMod 5 5
> (0, 1)
divMod 5 3
> (2, 1)
divMod 7 3
> (1, 2)
Also note that I'm using curried parameters divMod n m instead of tupled parameters as you do div1 (n, m). Ultimately this is a matter of taste, but as a pro tip, I'd like to point out that curried parameters turn out to be much more useful in practice.

Binary divisibility by 10

How to check if a binary number can be divided by 10 (decimal), without converting it to other system.
For example, we have a number:
1010 1011 0100 0001 0000 0100
How we can check that this number is divisible by 10?
First split the number into odd and even bits (I'm calling "even" the
bits corresponding to even powers of 2):
100100110010110000000101101110
0 1 0 1 0 0 1 0 0 0 1 1 0 1 0 even 1 0 0 1 0 1 1 0 0 0 0 0 1 1 1 odd
Now in each of these, add and subtract the digits alternately, as in
the standard test for divisibility by 11 in decimal (starting with
addition at the right):
100100110010110000000101101110 +0-1+0-1+0-0+1-0+0-0+1-1+0-1+0 =
-2 +1-0+0-1+0-1+1-0+0-0+0-0+1-1+1 = 1
Now double the sum of the odd digits and add it to the sum of the even
digits:
2*1 + -2 = 0
If the result is divisible by 5, as in this case, the number itself is
divisible by 5.
Since this number is also divisible by 2 (the rightmost digit being
0), it is divisible by 10.
Link
If you are talking about computational methods, you can do a divisiblity-by-5 test and a divisibility-by-2 test.
The numbers below assume unsigned 32-bit arithmetic, but can easily be extended to larger numbers.
I'll provide some code first, followed by a more textual explanation:
unsigned int div5exact(unsigned int n)
{
// returns n/5 as long as n actually divides 5
// (because 'n * (INV5 * 5)' == 'n * 1' mod 2^32
#define INV5 0xcccccccd
return n * INV5;
}
unsigned int divides5(unsigned int n)
{
unsigned int q = div5exact(n);
if (q <= 0x33333333) /* q*5 < 2^32? */
{
/* q*5 doesn't overflow, so n == q*5 */
return 1;
}
else
{
/* q*5 overflows, so n != q*5 */
return 0;
}
}
int divides2(unsigned int n)
{
/* easy divisibility by 2 test */
return (n & 1) == 0;
}
int divides10(unsigned int n)
{
return divides2(n) && divides5(n);
}
/* fast one-liner: */
#define DIVIDES10(n) ( ((n) & 1) == 0 && ((n) * 0xcccccccd) <= 0x33333333 )
Divisibility by 2 is easy: (n&1) == 0 means that n is even.
Divisibility by 5 involves multiplying by the inverse of 5, which is 0xcccccccd (because 0xcccccccd * 5 == 0x400000001, which is just 0x1 if you truncate to 32 bits).
When you multiply n*5 by the inverse of 5, you get n * 5*(inverse of 5), which in 32-bit math simplifies to n*1 .
Now let's say n and q are 32-bit numbers, and q = n*(inverse of 5) mod 232.
Because n is no greater than 0xffffffff, we know that n/5 is no greater than (232-1)/5 (which is 0x33333333). Therefore, we know if q is less than or equal to (232-1)/5, then we know n divides exactly by 5, because q * 5 doesn't get truncated in 32 bits, and is therefore equal to n, so n divides q and 5.
If q is greater than (232-1)/5, then we know it doesn't divide 5, because there is a one-one mapping between the 32-bit numbers divisible by 5 and the numbers between 0 and (232-1)/5, and so any number out of this range doesn't map to a number that's divisible by 5.
Here is the code in python to check the divisibilty by 10 using bitwise technique
#taking input in string which is a binary number eg: 1010,1110
s = input()
#taking initial value of x as o
x = 0
for i in s:
if i == '1':
x = (x*2 + 1) % 10
else:
x = x*2 % 10
#if x is turn to be 0 then it is divisible by 10
if x:
print("Not divisible by 10")
else:
print("Divisible by 10")

Zig Zag Decoding

In the google protocol buffers encoding overview, they introduce something called "Zig Zag Encoding", this takes signed numbers, which have a small magnitude, and creates a series of unsigned numbers which have a small magnitude.
For example
Encoded => Plain
0 => 0
1 => -1
2 => 1
3 => -2
4 => 2
5 => -3
6 => 3
And so on. The encoding function they give for this is rather clever, it's:
(n << 1) ^ (n >> 31) //for a 32 bit integer
I understand how this works, however, I cannot for the life of me figure out how to reverse this and decode it back into signed 32 bit integers
Try this one:
(n >> 1) ^ (-(n & 1))
Edit:
I'm posting some sample code for verification:
#include <stdio.h>
int main()
{
unsigned int n;
int r;
for(n = 0; n < 10; n++) {
r = (n >> 1) ^ (-(n & 1));
printf("%u => %d\n", n, r);
}
return 0;
}
I get following results:
0 => 0
1 => -1
2 => 1
3 => -2
4 => 2
5 => -3
6 => 3
7 => -4
8 => 4
9 => -5
Here's yet another way of doing the same, just for explanation purposes (you should obviously use 3lectrologos' one-liner).
You just have to notice that you xor with a number that is either all 1's (equivalent to bitwise not) or all 0's (equivalent to doing nothing). That's what (-(n & 1)) yields, or what is explained by google's "arithmetic shift" remark.
int zigzag_to_signed(unsigned int zigzag)
{
int abs = (int) (zigzag >> 1);
if (zigzag % 2)
return ~abs;
else
return abs;
}
unsigned int signed_to_zigzag(int signed)
{
unsigned int abs = (unsigned int) signed << 1;
if (signed < 0)
return ~abs;
else
return abs;
}
So in order to have lots of 0's on the most significant positions, zigzag encoding uses the LSB as sign bit, and the other bits as the absolute value (only for positive integers actually, and absolute value -1 for negative numbers due to 2's complement representation).
How about
(n>>1) - (n&1)*n
After fiddling with the accepted answer proposed by 3lectrologos, I couldn't get it to work when starting with unsigned longs (in C# -- compiler error). I came up with something similar instead:
( value >> 1 ) ^ ( ~( value & 1 ) + 1 )
This works great for any language that represents negative numbers in 2's compliment (e.g. .NET).
I have found a solution, unfortunately it's not the one line beauty I was hoping for:
uint signMask = u << 31;
int iSign = *((Int32*)&signMask);
iSign >>= 31;
signMask = *((UInt32*)&iSign);
UInt32 a = (u >> 1) ^ signMask;
return *((Int32*)&a);
I'm sure there's some super-efficient bitwise operations that do this faster, but the function is straightforward. Here's a python implementation:
def decode(n):
if (n < 0):
return (2 * abs(n)) - 1
else:
return 2 * n
>>> [decode(n) for n in [0,-1,1,-2,2,-3,3,-4,4]]
[0, 1, 2, 3, 4, 5, 6, 7, 8]

Given an integer, how do I find the next largest power of two using bit-twiddling?

If I have a integer number n, how can I find the next number k > n such that k = 2^i, with some i element of N by bitwise shifting or logic.
Example: If I have n = 123, how can I find k = 128, which is a power of two, and not 124 which is only divisible by two. This should be simple, but it eludes me.
For 32-bit integers, this is a simple and straightforward route:
unsigned int n;
n--;
n |= n >> 1; // Divide by 2^k for consecutive doublings of k up to 32,
n |= n >> 2; // and then or the results.
n |= n >> 4;
n |= n >> 8;
n |= n >> 16;
n++; // The result is a number of 1 bits equal to the number
// of bits in the original number, plus 1. That's the
// next highest power of 2.
Here's a more concrete example. Let's take the number 221, which is 11011101 in binary:
n--; // 1101 1101 --> 1101 1100
n |= n >> 1; // 1101 1100 | 0110 1110 = 1111 1110
n |= n >> 2; // 1111 1110 | 0011 1111 = 1111 1111
n |= n >> 4; // ...
n |= n >> 8;
n |= n >> 16; // 1111 1111 | 1111 1111 = 1111 1111
n++; // 1111 1111 --> 1 0000 0000
There's one bit in the ninth position, which represents 2^8, or 256, which is indeed the next largest power of 2. Each of the shifts overlaps all of the existing 1 bits in the number with some of the previously untouched zeroes, eventually producing a number of 1 bits equal to the number of bits in the original number. Adding one to that value produces a new power of 2.
Another example; we'll use 131, which is 10000011 in binary:
n--; // 1000 0011 --> 1000 0010
n |= n >> 1; // 1000 0010 | 0100 0001 = 1100 0011
n |= n >> 2; // 1100 0011 | 0011 0000 = 1111 0011
n |= n >> 4; // 1111 0011 | 0000 1111 = 1111 1111
n |= n >> 8; // ... (At this point all bits are 1, so further bitwise-or
n |= n >> 16; // operations produce no effect.)
n++; // 1111 1111 --> 1 0000 0000
And indeed, 256 is the next highest power of 2 from 131.
If the number of bits used to represent the integer is itself a power of 2, you can continue to extend this technique efficiently and indefinitely (for example, add a n >> 32 line for 64-bit integers).
There is actually a assembly solution for this (since the 80386 instruction set).
You can use the BSR (Bit Scan Reverse) instruction to scan for the most significant bit in your integer.
bsr scans the bits, starting at the
most significant bit, in the
doubleword operand or the second word.
If the bits are all zero, ZF is
cleared. Otherwise, ZF is set and the
bit index of the first set bit found,
while scanning in the reverse
direction, is loaded into the
destination register
(Extracted from: http://dlc.sun.com/pdf/802-1948/802-1948.pdf)
And than inc the result with 1.
so:
bsr ecx, eax //eax = number
jz #zero
mov eax, 2 // result set the second bit (instead of a inc ecx)
shl eax, ecx // and move it ecx times to the left
ret // result is in eax
#zero:
xor eax, eax
ret
In newer CPU's you can use the much faster lzcnt instruction (aka rep bsr). lzcnt does its job in a single cycle.
A more mathematical way, without loops:
public static int ByLogs(int n)
{
double y = Math.Floor(Math.Log(n, 2));
return (int)Math.Pow(2, y + 1);
}
Here's a logic answer:
function getK(int n)
{
int k = 1;
while (k < n)
k *= 2;
return k;
}
Here's John Feminella's answer implemented as a loop so it can handle Python's long integers:
def next_power_of_2(n):
"""
Return next power of 2 greater than or equal to n
"""
n -= 1 # greater than OR EQUAL TO n
shift = 1
while (n+1) & n: # n+1 is not a power of 2 yet
n |= n >> shift
shift <<= 1
return n + 1
It also returns faster if n is already a power of 2.
For Python >2.7, this is simpler and faster for most N:
def next_power_of_2(n):
"""
Return next power of 2 greater than or equal to n
"""
return 2**(n-1).bit_length()
This answer is based on constexpr to prevent any computing at runtime when the function parameter is passed as const
Greater than / Greater than or equal to
The following snippets are for the next number k > n such that k = 2^i
(n=123 => k=128, n=128 => k=256) as specified by OP.
If you want the smallest power of 2 greater than OR equal to n then just replace __builtin_clzll(n) by __builtin_clzll(n-1) in the following snippets.
C++11 using GCC or Clang (64 bits)
#include <cstdint> // uint64_t
constexpr uint64_t nextPowerOfTwo64 (uint64_t n)
{
return 1ULL << (sizeof(uint64_t) * 8 - __builtin_clzll(n));
}
Enhancement using CHAR_BIT as proposed by martinec
#include <cstdint>
constexpr uint64_t nextPowerOfTwo64 (uint64_t n)
{
return 1ULL << (sizeof(uint64_t) * CHAR_BIT - __builtin_clzll(n));
}
C++17 using GCC or Clang (from 8 to 128 bits)
#include <cstdint>
template <typename T>
constexpr T nextPowerOfTwo64 (T n)
{
T clz = 0;
if constexpr (sizeof(T) <= 32)
clz = __builtin_clzl(n); // unsigned long
else if (sizeof(T) <= 64)
clz = __builtin_clzll(n); // unsigned long long
else { // See https://stackoverflow.com/a/40528716
uint64_t hi = n >> 64;
uint64_t lo = (hi == 0) ? n : -1ULL;
clz = _lzcnt_u64(hi) + _lzcnt_u64(lo);
}
return T{1} << (CHAR_BIT * sizeof(T) - clz);
}
Other compilers
If you use a compiler other than GCC or Clang, please visit the Wikipedia page listing the Count Leading Zeroes bitwise functions:
Visual C++ 2005 => Replace __builtin_clzl() by _BitScanForward()
Visual C++ 2008 => Replace __builtin_clzl() by __lzcnt()
icc => Replace __builtin_clzl() by _bit_scan_forward
GHC (Haskell) => Replace __builtin_clzl() by countLeadingZeros()
Contribution welcome
Please propose improvements within the comments. Also propose alternative for the compiler you use, or your programming language...
See also similar answers
nulleight's answer
ydroneaud's answer
Here's a wild one that has no loops, but uses an intermediate float.
// compute k = nextpowerof2(n)
if (n > 1)
{
float f = (float) n;
unsigned int const t = 1U << ((*(unsigned int *)&f >> 23) - 0x7f);
k = t << (t < n);
}
else k = 1;
This, and many other bit-twiddling hacks, including the on submitted by John Feminella, can be found here.
assume x is not negative.
int pot = Integer.highestOneBit(x);
if (pot != x) {
pot *= 2;
}
If you use GCC, MinGW or Clang:
template <typename T>
T nextPow2(T in)
{
return (in & (T)(in - 1)) ? (1U << (sizeof(T) * 8 - __builtin_clz(in))) : in;
}
If you use Microsoft Visual C++, use function _BitScanForward() to replace __builtin_clz().
function Pow2Thing(int n)
{
x = 1;
while (n>0)
{
n/=2;
x*=2;
}
return x;
}
Bit-twiddling, you say?
long int pow_2_ceil(long int t) {
if (t == 0) return 1;
if (t != (t & -t)) {
do {
t -= t & -t;
} while (t != (t & -t));
t <<= 1;
}
return t;
}
Each loop strips the least-significant 1-bit directly. N.B. This only works where signed numbers are encoded in two's complement.
What about something like this:
int pot = 1;
for (int i = 0; i < 31; i++, pot <<= 1)
if (pot >= x)
break;
You just need to find the most significant bit and shift it left once. Here's a Python implementation. I think x86 has an instruction to get the MSB, but here I'm implementing it all in straight Python. Once you have the MSB it's easy.
>>> def msb(n):
... result = -1
... index = 0
... while n:
... bit = 1 << index
... if bit & n:
... result = index
... n &= ~bit
... index += 1
... return result
...
>>> def next_pow(n):
... return 1 << (msb(n) + 1)
...
>>> next_pow(1)
2
>>> next_pow(2)
4
>>> next_pow(3)
4
>>> next_pow(4)
8
>>> next_pow(123)
128
>>> next_pow(222)
256
>>>
Forget this! It uses loop !
unsigned int nextPowerOf2 ( unsigned int u)
{
unsigned int v = 0x80000000; // supposed 32-bit unsigned int
if (u < v) {
while (v > u) v = v >> 1;
}
return (v << 1); // return 0 if number is too big
}
private static int nextHighestPower(int number){
if((number & number-1)==0){
return number;
}
else{
int count=0;
while(number!=0){
number=number>>1;
count++;
}
return 1<<count;
}
}
// n is the number
int min = (n&-n);
int nextPowerOfTwo = n+min;
#define nextPowerOf2(x, n) (x + (n-1)) & ~(n-1)
or even
#define nextPowerOf2(x, n) x + (x & (n-1))

Finding closest match in collection of numbers [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Closed 8 years ago.
Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
So I got asked today what was the best way to find the closes match within a collection.
For example, you've got an array like this:
1, 3, 8, 10, 13, ...
What number is closest to 4?
Collection is numerical, unordered and can be anything. Same with the number to match.
Lets see what we can come up with, from the various languages of choice.
11 bytes in J:
C=:0{]/:|#-
Examples:
>> a =: 1 3 8 10 13
>> 4 C a
3
>> 11 C a
10
>> 12 C a
13
my breakdown for the layman:
0{ First element of
] the right argument
/: sorted by
| absolute value
# of
- subtraction
Shorter Python: 41 chars
f=lambda a,l:min(l,key=lambda x:abs(x-a))
My attempt in python:
def closest(target, collection) :
return min((abs(target - i), i) for i in collection)[1]
Groovy 28B
f={a,n->a.min{(it-n).abs()}}
Some C# Linq ones... too many ways to do this!
decimal[] nums = { 1, 3, 8, 12 };
decimal target = 4;
var close1 = (from n in nums orderby Math.Abs(n-target) select n).First();
var close2 = nums.OrderBy(n => Math.Abs(n - target)).First();
Console.WriteLine("{0} and {1}", close1, close2);
Even more ways if you use a list instead, since plain ol arrays have no .Sort()
Assuming that the values start in a table called T with a column called N, and we are looking for the value 4 then in Oracle SQL it takes 59 characters:
select*from(select*from t order by abs(n-4))where rownum=1
I've used select * to reduce the whitespace requirements.
Because I actually needed to do this, here is my PHP
$match = 33;
$set = array(1,2,3,5,8,13,21,34,55,89,144,233,377,610);
foreach ($set as $fib)
{
$diff[$fib] = (int) abs($match - $fib);
}
$fibs = array_flip($diff);
$closest = $fibs[min($diff)];
echo $closest;
PostgreSQL:
select n from tbl order by abs(4 - n) limit 1
In the case where two records share the same value for "abs(4 - id)" the output would be in-determinant and perhaps not a constant. To fix that I suggest something like the untested guess:
select n from tbl order by abs(4 - n) + 0.5 * 4 > n limit 1;
This solution provides performance on the order of O(N log N), where O(log N) is possible for example: https://stackoverflow.com/a/8900318/1153319
Ruby like Python has a min method for Enumerable so you don't need to do a sort.
def c(value, t_array)
t_array.min{|a,b| (value-a).abs <=> (value-b).abs }
end
ar = [1, 3, 8, 10, 13]
t = 4
c(t, ar) = 3
Language: C, Char count: 79
c(int v,int*a,int A){int n=*a;for(;--A;++a)n=abs(v-*a)<abs(v-n)?*a:n;return n;}
Signature:
int closest(int value, int *array, int array_size);
Usage:
main()
{
int a[5] = {1, 3, 8, 10, 13};
printf("%d\n", c(4, a, 5));
}
Scala (62 chars), based on the idea of the J and Ruby solutions:
def c(l:List[Int],n:Int)=l.sort((a,b)=>(a-n).abs<(b-n).abs)(0)
Usage:
println(c(List(1,3,8,10,13),4))
PostgreSQL:
This was pointed out by RhodiumToad on FreeNode and has performance on the order of O(log N)., much better then the other PostgreSQL answer here.
select * from ((select * from tbl where id <= 4
order by id desc limit 1) union
(select * from tbl where id >= 4
order by id limit 1)) s order by abs(4 - id) limit 1;
Both of the conditionals should be "or equal to" for much better handling of the id exists case. This also has handling in the case where two records share the same value for "abs(4 - id)" then that other PostgreSQL answer here.
The above code doesn't works for floating numbers.
So here's my revised php code for that.
function find_closest($match, $set=array()) {
foreach ($set as $fib) {
$diff[$fib] = abs($match - $fib);
}
return array_search(min($diff), $diff);
}
$set = array('2.3', '3.4', '3.56', '4.05', '5.5', '5.67');
echo find_closest(3.85, $set); //return 4.05
Python by me and https://stackoverflow.com/users/29253/igorgue based on some of the other answers here. Only 34 characters:
min([(abs(t-x), x) for x in a])[1]
Haskell entry (tested):
import Data.List
near4 = head . sortBy (\n1 n2 -> abs (n1-4) `compare` abs (n2-4))
Sorts the list by putting numbers closer to 4 near the the front. head takes the first element (closest to 4).
Ruby
def c(r,t)
r.sort{|a,b|(a-t).abs<=>(b-t).abs}[0]
end
Not the most efficient method, but pretty short.
returns only one number:
var arr = new int[] { 1, 3, 8, 10, 13 };
int numToMatch = 4;
Console.WriteLine("{0}",
arr.OrderBy(n => Math.Abs(numToMatch - n)).ElementAt(0));
returns only one number:
var arr = new int[] { 1, 3, 8, 10, 13 };
int numToMatch = 4;
Console.WriteLine("{0}",
arr.Select(n => new{n, diff = Math.Abs(numToMatch - n) }).OrderBy(x => x.diff).ElementAt(0).n);
Perl -- 66 chars:
perl -e 'for(qw/1 3 8 10 13/){$d=($_-4)**2; $c=$_ if not $x or $d<$x;$x=$d;}print $c;'
EDITED = in the for loop
int Closest(int val, int[] arr)
{
int index = 0;
for (int i = 0; i < arr.Length; i++)
if (Math.Abs(arr[i] - val) < Math.Abs(arr[index] - val))
index = i;
return arr[index];
}
Here's another Haskell answer:
import Control.Arrow
near4 = snd . minimum . map (abs . subtract 4 &&& id)
Haskell, 60 characters -
f a=head.Data.List.sortBy(compare`Data.Function.on`abs.(a-))
Kdb+, 23B:
C:{x first iasc abs x-}
Usage:
q)a:10?20
q)a
12 8 10 1 9 11 5 6 1 5
q)C[a]4
5
Python, not sure how to format code, and not sure if code will run as is, but it's logic should work, and there maybe builtins that do it anyways...
list = [1,4,10,20]
num = 7
for lower in list:
if lower <= num:
lowest = lower #closest lowest number
for higher in list:
if higher >= num:
highest = higher #closest highest number
if highest - num > num - lowest: # compares the differences
closer_num = highest
else:
closer_num = lowest
In Java Use a Navigable Map
NavigableMap <Integer, Integer>navMap = new ConcurrentSkipListMap<Integer, Integer>();
navMap.put(15000, 3);
navMap.put(8000, 1);
navMap.put(12000, 2);
System.out.println("Entry <= 12500:"+navMap.floorEntry(12500).getKey());
System.out.println("Entry <= 12000:"+navMap.floorEntry(12000).getKey());
System.out.println("Entry > 12000:"+navMap.higherEntry(12000).getKey());
int numberToMatch = 4;
var closestMatches = new List<int>();
closestMatches.Add(arr[0]); // closest tentatively
int closestDifference = Math.Abs(numberToMatch - arr[0]);
for(int i = 1; i < arr.Length; i++)
{
int difference = Math.Abs(numberToMatch - arr[i]);
if (difference < closestDifference)
{
closestMatches.Clear();
closestMatches.Add(arr[i]);
closestDifference = difference;
}
else if (difference == closestDifference)
{
closestMatches.Add(arr[i]);
}
}
Console.WriteLine("Closest Matches");
foreach(int x in closestMatches) Console.WriteLine("{0}", x);
Some of you don't seem to be reading that the list is unordered (although with the example as it is I can understand your confusion). In Java:
public int closest(int needle, int haystack[]) { // yes i've been doing PHP lately
assert haystack != null;
assert haystack.length; > 0;
int ret = haystack[0];
int diff = Math.abs(ret - needle);
for (int i=1; i<haystack.length; i++) {
if (ret != haystack[i]) {
int newdiff = Math.abs(haystack[i] - needle);
if (newdiff < diff) {
ret = haystack[i];
diff = newdiff;
}
}
}
return ret;
}
Not exactly terse but hey its Java.
Common Lisp using iterate library.
(defun closest-match (list n)
(iter (for i in list)
(finding i minimizing (abs (- i n)))
41 characters in F#:
let C x = Seq.min_by (fun n -> abs(n-x))
as in
#light
let l = [1;3;8;10;13]
let C x = Seq.min_by (fun n -> abs(n-x))
printfn "%d" (C 4 l) // 3
printfn "%d" (C 11 l) // 10
printfn "%d" (C 12 l) // 13
Ruby. One pass-through. Handles negative numbers nicely. Perhaps not very short, but certainly pretty.
class Array
def closest int
diff = int-self[0]; best = self[0]
each {|i|
if (int-i).abs < diff.abs
best = i; diff = int-i
end
}
best
end
end
puts [1,3,8,10,13].closest 4