How to declare a 2d Array without knowing the dimensions? [closed] - c

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I have a C programming assignment which i have to read from a text file and store the input in a 2d array. But text file only contains the matrix, stores no information about rows and columns. My program will be tested with several inputs so the 2d array shouldn't have a fixed size. But this matrix guaranteed to be a square one. I've been searching the net for several hours but couldn't come up with a solution. So how can i store this matrix in a 2d array which has dynamic dimensions when tested with several input files?

NOTE: From the phrasing, this seems like a homework question. For that reason, I won't post any direct code.
Your matrix is guaranteed to be square, so that means you will have the same number of rows as columns. That means you only have to scan the first line in order to know how many rows and how many columns are needed.
Let us assume that your matrix will be stored in a .csv (comma-separated variable) file. Your data is
n1, n2
n3, n4
Simply read the file as plain text, counting how many delimiters you find before the end of the line. In this case, you found 1 comma in the first row which obviously means you have 2 entries and therefore 2 columns by 2 rows; if you had 3 commas, you would have 4 entries and therefore 4 columns by 4 rows.
n1, n2, n3, n4
n5, n6, n7, n8
n9, n10, n11, n12
n13, n14, n15, n16
From there, you just have to malloc an n by n array of the size you just computed.

Related

Solution to make all array elements equal [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 days ago.
Improve this question
Can you advise the solution for this..
ARRAY EQUALITY
Problem Statement
Amy has an array A, of N integers. She wants to make all the elements of the array equal.
On each day she can select a subarray of A, with length exactly M and perform following operation: ·
Pick any element of the selected subarray and increase or decrease it by 1. She can perform this operation any number of times she wants (possibly 0), on that day.
Find the minimum number of days required to make all the elements of the array A equal. NOTE: A subarray is the sequence of consecutive elements of the array. You are given T independent test cases.
Constraints
`
All input values are integers.
Input Format First-line contains T.
First line of each test case consists of two space separated integers N and M.
Second line of each test case consists of N space separated integers denoting the array A. Output Format Print in a newline for each test case single integer denoting the minimum number of days required to make all the elements of the array A equal.
Sample Input 1
1
5 3
1 2 2 3 1
Sample Output 1
1
I want to know the aproach to solve this problem?

Shuffle an array of unequally repeating entries, so they do not repeat [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I am writing an experiment in Matlab Psychtoolbox and my conditions are stored in an array like this
Cond = ["VM" "VM" "VN" "VS" "AM" "AM" "AN" "AS" "CM" "CM" "CN" "CS"...
"VM" "VM" "VN" "VS" "AM" "AM" "AN" "AS" "CM" "CM" "CN" "CS"];
I now want to shuffle the array in a way that I don't have repeating conditions.
There are a lot of treats regarding this problem e.g.this one, but they always have every condition equally often.
Some suggested a brute force method, shuffling so often until this criteria is reached. But since I have tree of this condition arrays and I have to shuffle them several times per experimental run I don't think that is a good solution.
Hope someone can help
I devised an algorithm that should do what you're asking for. Given a sequence, it will randomly reorder it such that no value repeats. However, it does appear to have a tendency to create repeated sub-sequences (e.g. ..."A" "B" "C" "A" "B" "C"...). I wrapped it in a function reorder_no_reps:
function seq = reorder_no_reps(seq)
% Find unique values and counts:
N = numel(seq);
[vals, ~, index] = unique(seq(:), 'stable');
counts = accumarray(index, 1);
[maxCount, maxIndex] = max(counts);
% Check the maximum number of occurrences:
if (2*maxCount-1 > N)
error('Can''t produce sequence without repeats!');
end
% Fill cell array column-wise with permuted and replicated set of values:
C = cell(maxCount, ceil(N/maxCount));
if (3*maxCount-1 > N)
permIndex = [maxIndex(1) ...
setdiff(randperm(numel(vals)), maxIndex(1), 'stable')];
else
permIndex = randperm(numel(vals));
end
C(1:N) = num2cell(repelem(vals(permIndex), counts(permIndex)));
% Transpose cell array and extract non-empty entries:
C = C.';
seq = reshape([C{~cellfun('isempty', C)}], size(seq));
end
A description of the steps for the algorithm:
Find the unique values in the input sequence (vals) and how many times they each appear (counts).
Find the maximum occurrence of a single value (maxCounts) and check if it is too large to make a sequence without repreats.
A random permutation order is applied to both the unique values and their counts. If the maximum occurrence exceeds a given threshold, the corresponding value index is moved to the beginning of the randomized order (the reason why is addressed in the next bullet).
Each unique value is then replicated in place by its number of occurrences in the sequence. A cell array is filled in column-wise order with these replicated values, possibly leaving some cells at the end empty. Since the cell array has a number of rows equal to the maximum occurrence of a value, no single row of the resulting cell array will have a value appearing more than once in it. In addition, the last value in each row should be different than the first value in the subsequent row (ensured by filling first with the most frequently occurring value in certain cases).
Transpose the cell array, then pull all the non-empty cell values in column-wise order and reshape them into the same size as the input sequence. This is the same as pulling values row-wise from the non-transposed cell array, which should give you a sequence without repeated values.

find the number of distinct prime divisors of G using python programming? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
i have just wasted my 2 hours only for solving this programming question.if any one knows the trick of doing then please share it.question is given below.
You have given an array A having N integers. Let say G is the product of all elements of A.You have to find the number of distinct prime divisors of G.
Input Format
The first argument given is an Array A, having N integers.
Output Format
Return an Integer, i.e number of distinct prime divisors of
G.
Constraints
1 <= N <= 1e5
1 <= A[i] <= 1e5
For Example
Input:
A = [1, 2, 3, 4]
Output:
2
Explanation:
here G = 1 * 2 * 3 * 4 = 24
and distinct prime divisors of G are [2, 3]
Since this seems to be a homework question, I'll give some pushes in the right direction.
Theoretically, this is a very simple thing to do. Anyone can write code that loops through an array and multiplies its elements. It is also very easy to find pseudocode (or even real code) for factorizing a number into its prime factors.
However, this approach will not work here, since we will be dealing with HUGE numbers. The maximum value of G, given your constraints, is (10⁵)^(10⁵) = 10⁵⁰⁰⁰⁰⁰. This by far exceeds the number of electrons in the observable universe. We cannot factorize such huge numbers.
But luckily we don't need to know the value of G. We are only required to calculate it's prime factors, but we don't need to know the value of G to do so. So instead you will have to factorize the individual numbers in the array. I would recommend something like this code:
factors = set()
for num in A:
f = factorize(num) # Function that returns the set of prime factors in num
factors |= f # Add all elements in f to factors
You were only interested in the distinct prime factors, so using a set will take care of that. Just add everything, and it will automatically throw away any duplicates. factorize(x) is a function you will need to write that takes a number as argument and return the set of prime factors.
Good luck!

Extract one dimension from a multidimensional array [duplicate]

This question already has answers here:
On shape-agnostic slicing of ndarrays
(2 answers)
Closed 6 years ago.
Suppose A is multi-dimensional array (MDA) of size 3,4,5 and B is another MDA of size 3,4,5,6.
I know A(1,:,:) or B(1,:,:,:) can both extract their elements along the first dimension.
I now need to write a general program to extract the k-th dimension from a MDA without knowing its size.
For example, the MDA C has 6 dimension: 4,5,6,7,8,9 and I want an extraction C(:,:,k,:,:,:).
Sometimes, the MDA 'D' has 4 dimension: 3,4,5,6 and I want another extraction D(k,:,:,:).
That is, my problem is the numbers of colon is varying because of the dimension.
Thanks in advance
You can use string arrays to index the array dynamically:
function out = extract(arr,dim,k)
subses = repmat({':'}, [1 ndims(arr)]);
subses(dim) = num2cell(k);
out = arr(subses{:});
where dim is the dimension in which you want to select and k is an index within that dimension.
I have used a code from this answer:
https://stackoverflow.com/a/27975910/3399825

Find number of k-permutation with ordering but no repetition [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 10 years ago.
Improve this question
Im truggling to find a closed form for the number of k-permutations of a set S of cardinality n.
The combinations should regard ordering, but no repitions.
Example:
|S| = n = 3
S = {a,b,c}
k = 2
{a,b}
{b,a}
{b,c}
{c,b}
{a,c}
{c,a}
Anyone could help me out how to compute the number of viable permutations (and not the permutations itself)?
What I've tried:
I've read through different material and found out, that including repitititions it is
O(n) = n^k
My initial though was, that I need to eliminiate the permutations like
{a,a}
{b,b}
{c,c}
But I struggle finding a closed form for the number of perceivable repititions.
You are looking for the number of k-permutations of a set S of cardinality n.
The formulae is well known : n!/(n-k)!
Pseudo-proof :
for the 1st element, you are able to choose among the n elements of S ;
for the 2nd, only among : n-1, because you don't want doublons ;
...
for the ith, only among : n-(i-1) ;
...
for the kth, only among : n-(k-1) ;
So, finally :
n * (n-1) * ... * (n-i) * ... * (n-k+1)
= n! / (n-k)!

Resources