logo
down
shadow

Find a sum of two distinct numbers from the set, closest to the query number


Find a sum of two distinct numbers from the set, closest to the query number

Content Index :

Find a sum of two distinct numbers from the set, closest to the query number
Tag : c , By : ChristianM
Date : November 28 2020, 09:01 AM

Hope that helps First, input the n number of integers into an array. Sort them in O(n.log(n)) time.
Now, for each query of m, do as follows:
/*     arr => array holds sorted values    */

int low  = 0;               // Lower Index of an array
int high = length;          // Upper Index of an array

int query_value;            // Input from the user
int near_value;             // Near Value to be calculated
int difference = INT_MAX;   // difference between near_value and query_value
int temp;

while(low < high) {
    temp = arr[low] + arr[high];

    if(temp == query_value) {
        near_value = query_value;
        break;
    } else if(temp < query_value) {
        if(abs(temp - query_value) < difference) {
            difference = abs(temp - query_value);
            near_value = temp;
        }

        low++;
    } else {
        if(abs(temp - query_value) < difference) {
            difference = abs(temp - query_value);
            near_value = temp;
        }

        high--;
    }
}

print near_value;          // Print the near_value calculated

Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

Find the closest number in a list of numbers


Tag : chash , By : littlefuzz
Date : March 29 2020, 07:55 AM
wish of those help Well, you cannot do this faster than O(N) because you have to check all numbers to be sure you have the closest one. That said, why not use a simple variation on finding the minimum, looking for the one with the minimum absolute difference with x?
If you can say the list is ordered from the beginning (and it allows random-access, like an array), then a better approach is to use a binary search. When you end the search at index i (without finding x), just pick the best out of that element and its neighbors.

How do I find the closest n numbers to a given number at x distance from it?


Tag : python , By : Milander
Date : March 29 2020, 07:55 AM
I think the issue was by ths following , You can use a list comprehension for that. See this post for more on list comprehensions.
>>> lst = [1, 2, 3, 3, 4, 4, 5, 6, 7, 8, 9]
>>> given_numer = 5
>>> distance = 3
>>> [i for i in lst if abs(i-given_numer)==distance]
[2, 8]
>>> distance = 2
>>> [i for i in lst if abs(i-given_numer)==distance]
[3, 3, 7]
def checkdistance(given_number,distance):
    def innerfunc(value):
        return abs(value-given_number)==distance
    return innerfunc


lst = [1, 2, 3, 3, 4, 4, 5, 6, 7, 8, 9]
given_number = 5
distance = 3
checkdistance3from5 = checkdistance(5,3)
list(filter(checkdistance3from5,lst))

Find The Closest Number To Numbers Given In A List ~ Python


Tag : python , By : Umang
Date : March 29 2020, 07:55 AM
should help you out How would you find the closest number in comparison to numbers given in a list? This is what I have tried but I have come of unsuccessfull: , If you are too new to understand lambda functions yet,
   minimum = float("inf")
   setted_list = [2,9,6,20,15]
   value_chosen = 17
   for val in setted_list:
       if abs(val - value_chosen) < minimum:
           final_value = val
           minimum = abs(val - value_chosen)


   print final_value

Find three Numbers with Sum closest to a given number


Tag : python , By : lili
Date : March 29 2020, 07:55 AM
like below fixes the issue As we worked out in the comments the last return statment was erroneously inside the for loop cutting it short after the first iteration. Also, closest should be updated in both branches where we overshoot or undershoot the target.
I think an obvious improvement of your algorithm would be to sort first. Removing individual elements doesn't destroy order, so you'd need to sort only once. That would get you from O(n^2 log n) to O(n^2).

Find combination of numbers such that their addition is closest to a number?


Tag : r , By : kakashi_
Date : March 29 2020, 07:55 AM
I hope this helps . Results
Below are functions that tackle the problem, firstly though here are the results
find_grouping(orders, 300L)
#      orders group
# [1,]    100     1
# [2,]    198     1
# [3,]     50     2
# [4,]     40     2
# [5,]    215     2
# [6,]    296     3

allocate_groups(orders, 300L, 3L)    # third argument <-> max. num. of groups
#      orders group
# [1,]    100     3
# [2,]    198     3
# [3,]     50     2
# [4,]     40     2
# [5,]    215     2
# [6,]    296     1 

# bigger vector
set.seed(123)
orders <- sample(1:300, 15)
find_grouping(orders, 300L)
#       orders group
#  [1,]     87     2
#  [2,]    236     2
#  [3,]    122     3
#  [4,]    263     4
#  [5,]    279     5
#  [6,]     14     9
#  [7,]    156     6
#  [8,]    262     7
#  [9,]    162     8
# [10,]    133     8
# [11,]    278     9
# [12,]    132    10
# [13,]    196     1
# [14,]    165    10
# [15,]     30     7
allocate_groups(orders, 300L, 3L)
#       orders group
#  [1,]     87     1
#  [2,]    236     2
#  [3,]    122     3
#  [4,]    263     3
#  [5,]    279     1
#  [6,]     14     2
#  [7,]    156     3
#  [8,]    262     3
#  [9,]    162     2
# [10,]    133     1
# [11,]    278     2
# [12,]    132     2
# [13,]    196     1
# [14,]    165     1
# [15,]     30     3
create_groups <- function (orders, num, group_num) {
  orders
  groups <- rep(list(NA_integer_), group_num)
  for (k in sort(orders, decreasing = TRUE)) {
    sums <- vapply(1:group_num, function (s) as.integer(sum(groups[[s]], na.rm = TRUE)), integer(1))
    index <- ifelse(any(sums + k <= num), which(sums + k <= num)[which.min(abs(sums[which(sums + k <= num)]+k - num))], NA_integer_)
    index <- ifelse(is.na(index), which.min(sums), index)
    groups[[index]] <- append(groups[[index]],k)
    groups[[index]] <- groups[[index]][!is.na(groups[[index]])]
  }
  groups
}
allocate_groups <- function (orders, num, group_num) {
  groups <- create_groups(orders, num, group_num)
  g <- rep(seq_along(groups), sapply(groups, length))
  out <- cbind(orders, group = g[match(orders, unlist(groups))])
  out
}
# results above
find_grouping <- function (orders, num) {
    combs2 <- RcppAlgos::comboGeneral(orders, 2L, constraintFun = 'sum')
    combs2 <- cbind.data.frame(combs2,close=abs(num - combs2[,3]))
    out <- integer(length(orders))
    skip <- NA_integer_
    group <- 1L
    for (k in seq_along(out)) {
      val1 <- orders[k]
      if (val1 %in% skip) next
      ind1 <- (.subset2(combs2,1L) == val1) | (.subset2(combs2,2L) == val1)  
      ind2 <- (which.min(.subset2(combs2, 4L)[ind1]))
      ind3 <- which(ind1)[ind2]
      val2 <- .subset2(combs2, 3L)[ind3]
      if (abs(num-val1) <= abs(num-val2)) {
        out[k] <- group
        group  <- group + 1L
        next
      }
      intList <- as.integer(combs2[ind3,1:2])
      ordersRemain <- setdiff(orders, intList)
      if (abs(num-val2) <= abs(num-val2-min(ordersRemain))) {
        skip <- c(skip, intList)
        out[orders %in% intList] <- group
        group <- group + 1
        next
      }
      val3 <- val2
      cond <- FALSE
      while (!cond) {
        toAdd <- which.min(abs(num - (val2 + ordersRemain)))
        val3 <- val3 + ordersRemain[toAdd]
        intList <- c(intList, ordersRemain[toAdd])
        ordersRemain <- ordersRemain[-toAdd]
        cond <- abs(num-val3) <= abs(num-val2-min(ordersRemain))
      }
      skip <- c(skip, intList)
      out[orders %in% intList] <- group
      group <- group + 1
    }
    cbind(orders,group=out)
}
# num
combs <- RcppAlgos::comboGeneral(orders, 2L, constraintFun = 'sum')
combs <- cbind.data.frame(combs,close=abs(num - combs[,3])) # check how far from num are the combinations
#      1   2   3 close
# 1  100 198 298     2
# 2  100  50 150   150
# 3  100  40 140   160
# 4  100 215 315    15
# ...
Related Posts Related QUESTIONS :
  • Is there any difference usage in external interrupt between GPIO (AHB bus)and those (APB bus)?
  • Trouble programming AVR to interpret input from Arduino rotary encoder module
  • Is it correct to use a do-while loop inside a for loop? Why and why not?
  • Why we can't use dot for new created pointers to structs
  • Atomicity of fprintf from MPI processes
  • Printing of negative value in c via printf
  • What's the difference between global or local variables regarding the main function?
  • movsd from memory to xmm0 in c x86-64 jit
  • Problem with a function that insert the content of a csv into an array of struct
  • Segmentation Fault running time on sem_post(flag)
  • Extracting values from an incoming bluetooth serial on an arduino
  • "How much memory space does an array takes if the maximum size that is declared is not used?"
  • C GTK2 frustrated with gnome documentation
  • What really happens when a dynamic memory allocation is explicitly converted to struct type?
  • Re-Indexing Bits Within a Char
  • pointer de-referencing balagurusamy
  • Is it safe to memcpy regex_t?
  • Find a tight upper bound on complexity of the below program:
  • FFTW results differ from FFT in MATLAB
  • How to fix Misra 2012 violation , " Assignment operation in expression "
  • What is the difference between "int *p =0;" and "int *p; *p=0;"
  • Strncpy gives unwanted characters at end of string
  • What is really happening behind when a constant is assigned to a pointer variable?
  • Having trouble tracking logic of program includes Fork()
  • Are leftshift operators dependent on register size?
  • How to pass and receive back pointer to array of structures?
  • How to convert 2 bytes into a signed short in C
  • Using while loop to print Ascii Table with 10 characters per line
  • Is it possible to compress binary files with Huffman-encoding?
  • Why I am getting missing terminating " character?
  • Function call problem in data structure learning
  • Getting a segmentation fault trying to pass a node
  • Copying chars from file into an array
  • How to measure the time in seconds between two characters while user inserting them as an input
  • How to print two strings on the same line in c
  • Passing ("text"+1) argument to Strlen function in C. Why is Output 3?
  • to find the total no of letter in a string. please checkout my code too
  • Why do hiredis functions use void* instead of redisReply*?
  • Is there any case where the C static keyword should or could be used in header files for variables?
  • Sort an array in the relative order of elements of another array in c
  • Why functional programming over c
  • Re-assign value to variable if rand() repeats a number
  • does decrementing a NULL pointer lead to undefined behavior?
  • Access global variable value in different .c files present in different paths
  • Voltage Measurement on STM32
  • Printf behaviour with $ notation when sequence of arguments incomplete
  • Using "extern" to declare functions with no parameters
  • Stop mex function (C) without closing MATLAB
  • Cross-platform synchronization primitives which allow determining which PID is using them
  • Memory Leak : Possible memory while scan through valgrind
  • Store doubles in an array in C
  • How do I count correctly processes created by fork?
  • How to call system call from kernel?
  • Why is this C code section flagged as bad?
  • How to send MPU6050 device data to IoT Hub
  • How to send and receive a binary tree using MPI?
  • CreateRemoteThread fails on Windows7 64bit for 32bit applications
  • Is there anything wrong with how I pass pointer arguments?
  • How to fix "Segmentation fault" while printing string of struct?
  • Linked list add new root element
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com