Binary Search a non-existing number in a sorted array, return a larger negative number than -1 - arrays

When the search number is 12, why does it return -6 instead of -1?
int[] list = {2, 4, 7, 10, 11, 45, 50, 59, 60, 66, 69, 70, 79};
System.out.println("1. Index is " + Arrays.binarySearch(list, 11));
System.out.println("2. Index is " + Arrays.binarySearch(list, 12));
Result:
1. Index is 4
2. Index is -6
Update
Now I understand because
Arrays.binarySearch will return
(-(insertion point) - 1)
if the number is not in the array.
i.e
12 is at insertion of 5, so return (-(5) - 1) = -6.
Thanks for the help.

You may refer to the Javadoc : Arrays.binarySearch(int[] a,int key)
It returns :
index of the search key, if it is contained in the array;
otherwise : (-(insertion point) - 1).
Here the insertion point would be :
int[] list = {2, 4, 7, 10, 11, 45, 50, 59, 60, 66, 69, 70, 79};
// 1^ 2^ 3^ 4^ 5^
The position 5 so (-5-1) = -6

Extracted from BinarySearch
Return value:
This method returns index of the search key, if it is contained in the array, else it returns (-(insertion point) - 1). The insertion point is the point at which the key would be inserted into the array: the index of the first element greater than the key, or a.length if all elements in the array are less than the specified key.
From the return value explanation, it returns the negation of the position the element will be in the array (that is -5) minus 1, which would be -6.

This is a common return type for BinarySearch() methods.
If you would like to print the index of an integer a :
int[] list = {2, 4, 7, 10, 11, 45, 50, 59, 60, 66, 69, 70, 79};
int a =12; //Value can be updated or read through Scanner
int temp = Arrays.binarySearch(list,a);
if(temp>=0){
System.out.println("Index of a is : " + temp)
}else{
System.out.println("Insertion point for a is : " + (-1)*(temp+1);
}

Related

how can i multiply each index of a list by the next?

So, I have this array:
numbers = [5, 9, 3, 19, 70, 8, 100, 2, 35, 27]
What I want to do is to create another array from this one, but now each value of this new array must be equal to the corresponding value
in the numbers array multiplied by the following.
For example: the first value of the new array should be 45, as it is the multiplication
of 5 (first value) and 9 (next value). The second value of the new array should be 27, as it is the multiplication of 9 (second
value) and 3 (next value), and so on. If there is no next value, the multiplication must be done by 2.
So, this array numbers should result in this other array: [45, 27, 57 ,1330, 560, 800, 200, 70, 945, 54]
I only managed to get to this code, but I'm having problems with index:
numbers = [5,9,3,19,70,8,100,2,35,27]
new_array = []
x = 0
while x <= 8: # Only got it to work until 8 and not the entire index of the array
new_array.append(numbers[x] * numbers[x + 1])
x += 1
print(new_array)
How can I make it work no matter what is index of the array and then if there's no next number, multiply it by 2? I've tried everything but this was the closest I could get.
Try:
numbers = [5, 9, 3, 19, 70, 8, 100, 2, 35, 27]
out = [a * b for a, b in zip(numbers, numbers[1:] + [2])]
print(out)
Prints:
[45, 27, 57, 1330, 560, 800, 200, 70, 945, 54]
Andrej Kesely's approach is totally fine and would be the way to go for an experienced python developer.
But I assume you are kind of new to python, so here is a more simple approach if you are a bit familiar with other programming languages:
#function called multiply, taking an int[], returns int[]
def multiply(values):
newData = []
valuesLength = len(values) - 1
for i in range(valuesLength):
newData.append(values[i] * values[i+1])
newData.append(values[valuesLength] * 2)
return newData
#init int[], calling multiply-function and printing the data
numbers = [5,9,3,19,70,8,100,2,35,27]
newData = multiply(numbers)
print(newData)
The multiply-Function basically initiates an empty array, then loops over the passed values, multiplying them with the following value, leaves the loop one value too early and finally adds the last value by multiplying it with 2.
With the same approach as you did, making use of len(numbers):
numbers = [5,9,3,19,70,8,100,2,35,27]
new_array = []
x = 0
while x < len(numbers):
nxt = 2 if x+1 >= len(numbers) else numbers[x+1]
new_array.append(numbers[x] * nxt)
x += 1
print(new_array)
NOTE: The shorthand for nxt = 2.... is explained in the first comment of this answer: https://stackoverflow.com/a/14461963/724039

Increase minumum value distance between Integers in Array

I would like the increase the minimum 'distance' between values in an array. For example, if I have the array
44,45,47,51,65,66
I would like the minimum 'distance' to be 2. So, the desired output would be
44,46,48,51,65,67
I've tried doing something like
prevValue = array[0]
array.pop(0)
for a in array:
if(prevValue + 1 >= a):
a += 1
this wasn't the entire code as I had create temp arrays to not mess up the original one. But, this logic does not work.
Has anybody done anything similar? I was looking at np.arrange() but that wasn't the desired use case.
Thank you!
The line a += 1 only modifies your local variable named a; it would not modify any elements in a list. Here is one way to do what you want:
list1 = [44, 45, 47, 51, 65, 66]
list2 = []
prev = None
for a in list1:
if prev and prev + 1 >= a:
a = prev + 2
list2.append(a)
prev = a
print(list2)
They are actually called "lists", not "arrays", in Python. Using the correct search terms might help you find answers better on your own.
Try (assuming the lst is sorted):
lst = [44, 45, 47, 51, 65, 66]
distance = 2
for i in range(1, len(lst)):
diff = lst[i] - lst[i - 1]
if diff < distance:
lst[i] += distance - diff
print(lst)
Prints:
[44, 46, 48, 51, 65, 67]
For distance = 5:
[44, 49, 54, 59, 65, 70]

Matching two list of numbers by the index of closest value

I know there are already similar questions (1, 2, 3) but they are all in Python and they do not fit what I need.
Given two sorted list, say 1, 6, 13, 21, 28 and 2, 15, 20. The indices, without repeating (unlike link 1 above), of the closest number in the first array are returned, in this case 0, 2, 3.
The tricky point is, in the case 1, 4, 66, 67, 68, 71 and 68, 68, 68, 82, 82, returning 2, 3, 4, 5, 1 is more preferable than 1, 2, 3, 4, 5.
It is possible that the length of the first list < the length of the second list. 1, 7, 11 and 6, 24, 28, 32, 34 should return 0, 1, 2, X, X, where X can be any integer other than 0, 1 and 2. (Both 0, 1, 2, -1, -1 and 0, 1, 2, 3, 4 are acceptable.)
Edit: Just swap the two lists and return 0, 1, 2.
Codes given in C-like languages or pseudocode is preferable.
Any idea better than a brute-force search?
Edit
The given examples may not be the best solutions, e.g. the final (struckthrough) example could return 1, 0, 2 (1, 0, 2, X, X) instead.
Let the first array be a and the second be b.
Let the cost of assigning index i to b[j] be abs(a[i] - b[j]). Then we can find a solution by modelling our problem as an unbalanced assignment problem in O(nr2) time where r is the size of the smallest array and n the biggest.

How can I generate a random number from a group of numbers (not a range)

I would like to be able to generate a random number from a group of numbers, like for example: 1, 2, 3, 12, 11, 23, 45, 54, 10, 10, 12, 23, 35, 24. Using the rand and the srand i can generate random numbers different each time but i would like to able to condition the outcomes by generating random numbers from a group.
Example code
Take an Array
int a[]={ 1, 2, 3, 12, 11, 23, 45, 54, 10, 10, 12, 23, 35, 24};
int i = rand()%14; // here 14 is number of element in array.
i will receive a value between 0 to 13
At last
printf("%d",a[i]); //print that array index

Calculate number of elements to be evaluated

This is a logical Question which is not bound to any specific language.
Does someone know a way on how to achieve the following?
I do have an array of which I can always evaluate a max of 10 elements.
So if the size of the array grows higher than 10, I need to determine which element I can evaluate - equally distributed.
Example:
[87, 34, 65, 23, 98, 45, 21, 54, 65, 235, 4, 32, 98, 42, 17]
The bold ones could be the ones considered.
And I do want to always evaluate the highest amount of possibles:
If the length of the array is smaller than 10 THEN evaluate every item.
If the length is higher THEN evaluate 10 out of the array.
If length is 20 -> every 2nd item should be evaluated
If length is 100 -> every 10th item should be evaluated
But what if length is 13 or 27?
You can use a function which remaps your index 0..9 to an evenly distributed index form 0..n-1, e.g.
int map_index(int i, // index: 0..9
int n) // no of elements in array
{
return i * (n - 1) / (10 - 1);
}
How about using the ones with the indices floor(k*length/10), where k=1, 2, ... 10?
For length 15 this will result indices 1, 3, 4, 6, 7, 9, 10, 12, 13, 15 - almost matching your example.

Resources