Arrangement of elements to avoid duplicate on consecutive positions - arrays

I have an array with N elements and I have M numbers. U need to arrange the M(1, 2, 3, ..M) numbers in array, the numbers in M are repeated. Such that constitutive elements in the array are not same.
Ex : N=9 and M=3 [4, 4, 1] means 1 appears 4 times in the array, '2' appears 4 times and 3 appears only one time.
So the possible arrangement will be [1,2,1,2,1,2,3,1,2].
Ex : N=8 and M=2 [3, 5].
There is no possibility to arrange the elements such that two consecutive elements are not same.
I need to find weather the arrangement is possible or not.

Try something like this (Java syntax):
int max = M[0];
int sum = M[0];
for ( i = 1 ; i < M.length ; i++ ) {
if ( M[i] > max ) {
max = M[i];
}
sum = sum + M[i];
}
if ( 2*max <= s+1 ) {
System.out.println("possible");
} else {
System.out.println("NOT possible");
}
Time complexity: O(|M|)
The idea is that if you want to place those numbers into an array, you'll start with the longest sequence, then you choose the first longest sequence in order to avoid repeating.
E.g.:
----------- arr: []
1, 1, 1, 1
2, 2
3
----------- arr: [1]
1, 1, 1
2, 2
3
----------- arr: [1, 2]
1, 1, 1
2
3
----------- arr: [1, 2, 1]
1, 1
2
3
----------- arr: [1, 2, 1, 2]
1, 1
3
----------- arr: [1, 2, 1, 2, 1]
1
3
----------- arr: [1, 2, 1, 2, 1, 3]
1
----------- arr: [1, 2, 1, 2, 1, 3, 1]
So, if the maximum number from M is at most the sum of the others + 1, it's possible to obtain that array without repeats:
max <= sum_of_the_others + 1 | + max
which is equivalent to
max + max <= sum_of_all_numbers + 1
which is equivalent to
2*max <= sum_of_all_numbers + 1

Related

Add all the frequencies of array elements into one array, and its elements to another array

n=8 -> number of elements
1 3 2 4 2 1 9 1 -> Elements of an array
Output:
numbers = [1, 3, 2, 4, 9]
frequency = [3, 1, 2, 1, 1]
var n = 8
var a = arrayOf(1, 3, 2, 4, 2, 1, 9, 1)
var numbers = Array(50){}
var frequency = Array(50){}
var k = 0
for (i in 0 until a.size){
for(j in 1 until a.size){
if (a[j]!=a[j+1]){
k++
println(k)
}
}
}
I don't have any idea of what to do? Pleas help me
Suppose there is an array a.
var a = arrayOf(1, 3, 2, 4, 2, 1, 9, 1)
We will create two MutableList to store the numbers and their frequencies
var numbers = mutableListOf<Int>()
var frequencies = mutableListOf<Int>()
Now we will iterate over our array a and for an element i, if i is not in numbers, we will add i in numbers and add 1 in frequencies. And if i is already in numbers, we will find the index of i in numbers and use this index to update the frequency of i in frequencies, increasing by 1.
for(i in a){
if(i !in numbers){
numbers.add(i)
frequencies.add(1)
}
else{
var indexToChange = numbers.indexOf(i)
frequencies[indexToChange] = frequencies[indexToChange]+1
}
}
Now we will print the value of numbers and frequencies
println("numbers: $numbers\nfrequencies: $frequencies")
Now adding all the pieces...
fun main(){
var a = arrayOf(1, 3, 2, 4, 2, 1, 9, 1)
var numbers = mutableListOf<Int>()
var frequencies = mutableListOf<Int>()
for(i in a){
if(i !in numbers){
numbers.add(i)
frequencies.add(1)
}
else{
var indexToChange = numbers.indexOf(i)
frequencies[indexToChange] = frequencies[indexToChange]+1
}
}
println("numbers: $numbers\nfrequencies: $frequencies")
}
Results:
numbers: [1, 3, 2, 4, 9]
frequencies: [3, 1, 2, 1, 1]

Minimum number of operations to make two arrays equal

Given 2 arrays of integers, A and B, an operation on array B is defined as follows:
B[i] = B[i]+2 and B[j] = B[j]-2, where i != j
i and j can be any indices and the above operation can be performed
any number of times such that i and j are not equal
a valid operation consists of both the addition and subtraction steps, both parts are mandatory
The array is considered equal if the frequency of all the elements is same, the array need not be ordered, find the minimum operations required
Input:
A = [ 2, 10, 14 ]
B = [ 6, 2, 18 ]
Output: 2
Explanation :
1st operation: select i=0; j=2;
B[i] += 2 i.e B[0]=8;
B[j] -= 2 i.e B[2] = 16;
B after 1st operation [8,2,16]
2nd operation: select i=0; j=2;
B[i] += 2 i.e B[0]=10;
B[j] -= 2 i.e B[2] = 14;
B after 2nd operation [10,2,14]
Order doesnt matter, so we have made the arrays equal return 2;
I am unable get an approach to solve this and couldn't find any similar questions, so posting this here, thanks in advance.
Assuming the arrays are solvable, then sort the arrays (by parity, and then by value), add up the absolute value of the deltas and divide by 4.
E.g.
A = [ 2, 10, 14 ], already sorted
B = [ 6, 2, 18 ], sorted becomes [2, 6, 18]
Sum of absolute value of deltas = 0 + 4 + 4 = 8. 8/4 = 2 so 2 moves.
A = [2, 10, 14]( % 2 == 0)
B = [2, 6, 18]( % 2 == 0)
another example
A = [1, 2, 5] -> [1, 5]( % 2 == 1) & [2]( % 2 == 0)
B = [1, 3, 4] -> [1, 3]( % 2 == 1) & [4]( % 2 == 0)
Notice that (a + k) mod k == a.
Assuming we already have a sorted array.
We divide the array into k parts, according to the mod k value of the element, then we sum all absolute differences, it's four times the answer.
k = 2
A.sort(key=lambda x: x % k)
B.sort(key=lambda x: x % k)
result = 0
n = len(A)
for i in range(n):
result += abs(A[i] - B[i])
print(result >> 2)
# A = [1, 2, 5]
# B = [1, 3, 4]
# result = 1
# A = [2, 10, 14]
# B = [6, 2, 18]
# result = 2
O(N log N) because of sorting.

how to shrink an array if two consecutive numbers in an array are equal then remove one and increment other

How to shrink an array if two consecutive numbers in an array are equal then remove one and increment other
Example 1:
int a[6]={2,2,3,4,4,4};
// Output: 6
Example 2:
int b[7]={1,2,2,2,4,2,4};
// Output: {1,3,2,4,2,4}
lst = [2,2,3,4,4,4]
def shrink(lst):
idx = 0
while len(lst) > idx+1:
a, b = lst.pop(idx), lst.pop(idx)
if a == b:
lst.insert(idx, a+1)
idx = 0
else:
lst.insert(idx, b)
lst.insert(idx, a)
idx += 1
shrink(lst)
print(lst)
Prints:
[6]
For [5, 5, 5, 1] prints [6, 5, 1]
This can be done in near-linear time like so:
a = [2, 2, 3, 4, 4, 4]
b = [1, 2, 2, 2, 4, 2, 4]
c = [5, 5, 5, 1]
def shrink_array(a):
res = []
for i in range(1, len(a)+1):
if i < len(a) and a[i] == a[i-1]: # if equal to previous
a[i] += 1 # increment and move on
else:
if len(res) > 0 and res[-1] == a[i-1]: # if equal to last in res
res[-1] += 1 # increment last in res
else:
res.append(a[i-1]) # add to res
while len(res) > 1 and res[-1] == res[-2]: # shrink possible duplicates
res[-2] += 1
del res[-1]
return(res)
for arr in [a, b, c]:
print(shrink_array(arr))
Output:
[6]
[1, 3, 2, 4, 2, 4]
[6, 5, 1]

Algorithm for array permutation

We have an integer array A[] of size N (1 ≤ N ≤ 10^4), which originally is a sorted array with entries 1...N. For any permutation P of size N, the array is shuffled so that i-th entry from the left before the shuffle is at the Ai-th position after the shuffle. You would keep repeating this shuffle until the array is sorted again.
For example, for A[] = {1, 2, 3, 4}, if P = {1, 2, 3, 4}, it would only take one move for the array to be sorted (the entries would move to their original positions). If P = {4, 3, 1, 2}, then it would take 4 moves for the array to be sorted again:
Move 0 | [1, 2, 3, 4]
Move 1 | [3, 4, 2, 1]
Move 2 | [2, 1, 4, 3]
Move 3 | [4, 3, 1, 2]
Move 4 | [1, 2, 3, 4]
The problem is to find the sum of all positive integers J for which you can generate a permutation that requires J moves to get the array sorted again.
Example:
For A[] = {1, 2, 3, 4}, you can generate permutations that require 1, 2, 3, and 4 steps:
Requires 1 move: P = {1, 2, 3, 4}
Requires 2 moves: P = {1, 3, 2, 4}
Requires 3 moves: P = {1, 4, 2, 3}
Requires 4 moves: P = {4, 3, 1, 2}
So you would output 1 + 2 + 3 + 4 = 10.
Some observations I have made is that you can always generate a permutation that requires J moves for (1 ≤ J < N). This is because in the permutation, you would simply shift by 1 all the entries in the range of size J. However, for permutations that requires J moves where J ≥ N, you would need another algorithm.
The brute-force solution would be checking every permutation, or N! permutations which definitely wouldn't fit in run time. I'm looking for an algorithm with run time at most O(N^2).
EDIT 1: A permutation that requires N moves will always be guaranteed as well, as you can create a permutation where every entry is misplaced, and not just swapped with another entry. The question becomes how to find permutations where J > N.
EDIT 2: #ljeabmreosn made the observation that there exists a permutation that takes J steps if and only if there are natural numbers a_1 + ... + a_k = N and LCM(a_1, ..., a_k) = J. So using that observation, the problem comes down to finding all partitions of the array, or partitions of the integer N. However, this won't be a quadratic algorithm - how can I find them efficiently?
Sum of distinct orders of degree-n permutations.
https://oeis.org/A060179
This is the number you are looking for, with a formula, and some maple code.
As often when trying to compute an integer sequence, compute the first few values (here 1, 1, 3, 6, 10, 21) and look for it in the great "On-line Encyclopedia of Integer Sequences".
Here is some python code inspired by it, I think it fits your complexity goals.
def primes_upto(limit):
is_prime = [False] * 2 + [True] * (limit - 1)
for n in range(int(limit**0.5 + 1.5)):
if is_prime[n]:
for i in range(n*n, limit+1, n):
is_prime[i] = False
return [i for i, prime in enumerate(is_prime) if prime]
def sum_of_distinct_order_of_Sn(N):
primes = primes_upto(N)
res = [1]*(N+1)
for p in primes:
for n in range(N,p-1,-1):
pj = p
while pj <= n:
res[n] += res[n-pj] * pj
pj *= p
return res[N]
on my machine:
>%time sum_of_distinct_order_of_Sn(10000)
CPU times: user 2.2 s, sys: 7.54 ms, total: 2.21 s
Wall time: 2.21 s
51341741532026057701809813988399192987996798390239678614311608467285998981748581403905219380703280665170264840434783302693471342230109536512960230

Arranging array into all possible pairs

I am working on a problem (in C) that requires me to list all possible connections between an even number of points, so that every point is connected to only one other point. For example, say I have points 1, 2, 3, and 4:
1 - 2, 3 - 4
1 - 3, 2 - 4
1 - 4, 2 - 3
The order of the points doesn't matter (1 - 2 is same as 2 - 1), and the order of connections doesn't too (1 - 2, 3 - 4 same as 3 - 4, 1 - 2).
I am currently trying to simply order the array such as {1, 2, 3, 4} into all possible orderings and check to see if it is already generated. However this can be very expensive and also the ordering of the points and pairs needs to be disregarded.
What would be a better way to arrange an array into all possible pairs? A basic outline of an algorithm would be appreciated!
Edit: in the example above with {1, 2, 3, 4}, if pairings are represented as two adjacent elements in the array, all possible outcomes would be:
{1, 2, 3, 4}: 1 - 2, 3 - 4
{1, 3, 2, 4}: 1 - 3, 2 - 4
{1, 4, 2, 3}: 1 - 4, 2 - 3
I would need the entire arranged array to perform calculations based on all the connections.
This can be accomplished by nondeterministically pairing the rightmost unpaired element and recursing. In C:
void enum_matchings(int n, int a[static n]) {
if (n < 2) {
// do something with the matching
return;
}
for (int i = 0; i < n-1; i++) {
int t = a[i];
a[i] = a[n-2];
a[n-2] = t;
enum_matchings(n-2, a);
a[n-2] = a[i];
a[i] = t;
}
}

Resources