I want to sort a 2*n matrix, n is given in the input. Make a program to output a matrix. Here is the requirement:
the first column MUST be sorted in ASC, and
the second column in DESC if possible.
For example, let n = 5, and the matrix is
3 4
1 2
3 5
1 6
7 3
The result should be
1 6
1 2
3 5
3 4
7 3
So I write down the code like this. First line input the value n, and the following lines like above.
#include <stdio.h>
#define TWO_16 65536
#define TWO_15 32768
int v[100000][2];
int z[100000];
int vec[100000];
int n;
int main()
{
int i, j;
scanf ("%d", &n); // give the value of n;
for (i = 1; i <= n; i++) // filling the matrix;
{
scanf ("%d%d", &v[i][0], &v[i][1]);
z[i] = TWO_16 * v[i][0] + TWO_15 - v[i][1];
vec[i] = i;
}
for (i = 1; i <= n; i++)
for (j = 1; j <= i; j++)
{
if (z[j] > z[i])
{
int t = vec[i];
vec[i] = vec[j];
vec[j] = t;
}
}
for (i = 1; i <= n; i++) // output the matrix
printf("%d %d\n",v[vec[i]][0],v[vec[i]][1]);
return 0;
}
But in gcc, the output is
1 6
3 5
3 4
1 2
7 3
What's more, when the first line is changed to "1 2" and the second is changed to "3 4" in input, the result also changed.
What's the problem of my code?
Additional information:
I use z[] because I use a function that satisfy the requirement of this problem, so I can simply sort them. And vec[] stores the original index, because moving arrays may cost lots of time. So v[vec[i]][0] means the 'new' array's item i.
Note that v[0] is NOT used. n is less than 100000, not equal.
You are comparing values stored in z[], but swapping elements of vec.
So when in the begginig you have:
i vec z
------------------
1 1 z[1]
2 2 z[2]
3 3 z[3]
...
After for e.g. swapping 2 with 3
i vec z
------------------
1 1 z[1]
2 3 z[2]
3 2 z[3]
...
you will have improper mapping between vec and z.
So in another iteration you will again compare z[2] with z[3] and again you will have to swap elements of vec. That's why you should at least also swap elements of z or index elements of z using elements of vec
i vec z
------------------
1 1 z[vec[1]] = z[1]
2 3 z[vec[2]] = z[3]
3 2 z[vec[3]] = z[2]
...
Adding this should do the trick
...
int t = vec[i];
vec[i] = vec[j];
vec[j] = t;
//Add this also when swapping vec
t = z[i];
z[i] = z[j];
z[j] = t;
...
Array index start with 0, so your for cicles must start from 0
if (z[j] > z[i]): you want to sort v but you are comparing z and sorting vec. By sorting vec and comparing z bubble sort cannot work. You must use the same array.
Related
I'm having the following problem:
A park that have the form of a m x n board. There are k kinds of trees (1 <= k <= 100). The park is divided into m x n cells and each cell, they'll plant a tree. Now, on the map, each cell of the park have an integer i inside if the i-th kind of tree is planted in it, or a 0 if no tree is planted in it. A line of cells is considered "good" if it has at least t trees of same types, (and they must be on the same either line or column). Count the number of trees that is not in a "good" line.
Input: Integers m, n, t and an m x n array of integers represent the map.
Output: Number of trees that is not in a "good" line.
Example:
Input:
5 6 3
1 3 3 3 3 4
1 2 3 2 0 4
3 2 2 2 4 4
1 0 0 2 4 0
1 2 3 0 4 4
Output: 10
Explanation: The bold numbers are the trees that is not in a good line.
1 3 3 3 3 4
1 2 3 2 0 4
3 2 2 2 4 4
1 0 0 2 4 0
1 2 3 0 4 4
My idea is to check for each element in the array. If it is satisfied then I'll move to the nearest element outside the "good" line. Else, it will just move to the next element on the same line, or if the line is ended then the next element on the column.
Here is my code
#include <stdio.h>
#define maxn 120
int a[maxn][maxn], m, n, t;
int check(int *i, int *j){
int k, cnt_r, cnt_c;
cnt_r = 0;
//jump to the nearest cell that is not in good line
for(k = *i + 1; k < m; k++){
if(a[*i][*j] == a[k][*j]) cnt_r++;
if(cnt_r >= t){
*i = k;
return 1;
}
}
cnt_c = 0;
for(k = *j + 1; k < n; k++){
if(a[*i][*j] == a[*i][k]) cnt_c++;
if(cnt_c >= t){
*j = k;
return 1;
}
}
return 0;
}
//check if this is the last square or not
int lastSq(int r, int c){
return (r == n - 1 && c == n);
}
int main(){
int res = 0, i, j, pos_r = 0, pos_c = 0;
scanf("%d%d%d", &m, &n, &t);
for(i = 0; i < m; i++)
for(j = 0; j < n; j++)
scanf("%d", &a[i][j]);
while(!lastSq(pos_r, pos_c)){
if(a[pos_r][pos_c] == 0){
if(pos_c < n - 1) pos_c++;
else if(pos_r < n - 1){
pos_c = 0;
pos_r++;
}
}
if(!check(&pos_r, &pos_c)){
res++;
if(pos_c < n - 1) pos_c++;
else{
pos_c = 0;
pos_r++;
}
}
}
printf("%d", res);
}
But it doesn't print any output. The only thing I have is 0xC0000005. Can someone please check where did I make a mistake and provide me a direction? Thanks.
I want to generate all possible increasing subsequences of numbers (repetition allowed) from 1 to n, but of length k.
Ex. n=3, k=2
Output:
1 1
1 2
1 3
2 2
2 3
3 3
This is my code:
#include <stdio.h>
int s[100];
int n=6;
int k=4;
void subk(int prev,int index)
{
int i;
if (index==k)
{
for(int i=0; i<k; i++)
printf("%d ",s[i]);
printf("\n");
return;
}
s[index]=prev;
for (i=prev; i<=n; ++i)
{
subk(i,index+1);//,s,n,k);
}
}
int main()
{
int j;
for (j = 1; j<=n ; ++j)
{
subk(j,0);
}
return 0;
}
But this generates some unwanted repetitions. How do I eliminate those?
I have tested your code with n = 3 and k = 2 and got the following result:
1 1
1 1
1 1
1 2
1 2
1 3
2 2
2 2
2 3
3 3
This is obviously incorrect, as there are several identical numbers like 1 1 or 1 2.
But what exactly went wrong?
Let's write down the right results if n = 3 and k = 3. Now compare those to the result we got from the program when n = 3 and k = 2.
correct program (incorrect)
k = 3 k = 2
1 1 1 1 1
1 1 2 1 1
1 1 3 1 1
1 2 2 1 2
1 2 3 1 2
1 3 3 1 3
2 2 2 2 2
2 2 3 2 2
2 3 3 2 3
3 3 3 3 3
Now we can see that the incorrect output of the program is the same as the first two columns of the correct answer when we set k = 3. This means that the program solves the problem for 3 columns if we set k = 2, but only displays the first two columns.
You need to stop the program from writing the same number several times.
Solution 1
One way to do this is to execute the for-loop in the subk-function only once when it writes the last number (index == (k - 1)) into the buffer s.
In order to achieve this, you need to add the following two lines to the end of your for-loop.
if (index == (k - 1))
break;
(Instead of the break you could also use return)
After you added these two lines the function should look like this:
void subk(int prev, int index)
{
int i;
if (index == k)
{
for (int i = 0; i<k; i++)
printf("%d ", s[i]);
printf("\n");
return;
}
s[index] = prev;
for (i = prev; i <= n; ++i)
{
subk(i, index + 1);//,s,n,k);
if (index + 1 == k)
break;
}
}
Solution 2
Another way to solve the problem is to move the line s[index] = prev; to the beginning of the function and change the k in the if-statement to k - 1.
Now the function should look like this:
void subk(int prev, int index)
{
int i;
s[index] = prev;
if (index == k - 1)
{
for (int i = 0; i<k; i++)
printf("%d ", s[i]);
printf("\n");
return;
}
for (i = prev; i <= n; ++i)
{
subk(i, index + 1);//,s,n,k);
}
}
With this solution, the for-loop is never executed when the index shows that the program is at the last 'sub-number'. It just displays the number and exits the function because of the return.
You get the right result with both solutions, but I personally like the second solution better, because there is no additional if-statement that is executed every iteration of the for-loop and the program is (slightly) faster.
I'm trying to make a program that shifts all the elements of an array to the right by one and move the last element into the first position. My problem is when I run my code it's giving me the number 5 twice. Can someone help me, maybe my logic or my for loop is not right?
#include <stdio.h>
int main ()
{
int array[6];
int x;
int temp;
printf("Enter six numbers.\n\n");
for (x = 0; x < 6; x++) {
printf("Enter a number : ", x + 1);
scanf("%d", &array[x]);
temp = array[x - 1];
}
for (x = 6 - 1; x > 0; x--) {
array[x] = array[x - 1];
}
array[0] = temp;
for (x = 0; x < 6; x++) {
printf("%d\n", array[x]);
}
return 0;
}
You could make a for loop like
for(i=0; i<SIZE; ++i)
{
scanf("%d", &arr[(i+1)%SIZE]);
}
The (i+1)%SIZE would evaluate to i+1 if i+1 is less than SIZE. Otherwise, it would wrap around.
Or you can
int t=arr[SIZE-1];
for(i=SIZE-1; i>0; --i)
{
arr[i]=arr[i-1];
}
arr[0]=t;
save the last element into a temporary variable, shift other elements towards right and finally assign the first element the value in the temporary variable.
As Gourav pointed out, in the first iteration of your first for loop, arr[x-1] would become arr[-1] as x is 0. You are trying to access memory which is not part of that array. This invokes undefined behavior.
I will try to explain it with the very easiest algorithm and yes easy means not efficient as from performance perspective.
For example, let's say you have an array of six elements:
1 2 3 4 5 6
From the question, all I understood is that you want to reverse this array to have a final array to be:
6 5 4 3 2 1
A naive way of doing is to store the first element in a temporary variable, assign the second element to the first element and after that assign the temporary variable to the second element and repeat this until all elements are swapped as shown below:
temp = arr[0]
arr[0] = arr[1]
arr[1] = temp
You will need two loops to do this, one decrementing and one incrementing
1 2 3 4 5 6 i=0; j=5
2 1 3 4 5 6 i=1; j=5
2 3 1 4 5 6 i=2; j=5
2 3 4 1 5 6 i=3; j=5
2 3 4 5 1 6 i=4; j=5
2 3 4 5 6 1 i=5; j=5
Next, you have to execute the above loop with one less iteration:
2 3 4 5 6 1 i=0; j=4
3 2 4 5 6 1 i=1; j=4
3 4 2 5 6 1 i=2; j=4
3 4 5 2 6 1 i=3; j=4
3 4 5 6 2 1 i=4; j=4
So, the loops would be:
for(i=5; i>0; i--)
{
for(j=0; j<i; j++)
{
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
You can make things a bit more generic by adding a direction to your shift routine and putting the shift code in a function that takes the array, the number of members and the direction to shift as arguments. Then its just a matter of iterating in the proper direction and shifting the elements in the correct direction and putting the final value in the proper place. For example, you could write a simple function as follows:
/** shift array index in in circular manner by 1 in the
* 0 - left or 1 - right direction.
*/
void arrayshift (int *a, size_t nmemb, int dir)
{
if (dir) { /* shift to RIGHT */
int tmp = a[nmemb - 1];
for (size_t i = nmemb - 1; i > 0; i--)
a[i] = a[i - 1];
a[0] = tmp;
}
else { /* shift to LEFT */
int tmp = a[0];
for (size_t i = 1; i < nmemb; i++)
a[i - 1] = a[i];
a[nmemb - 1] = tmp;
}
}
A simple test routine could be:
#include <stdio.h>
enum { LEFT, RIGHT };
void arrayshift (int *a, size_t nmemb, int dir);
int main (int argc, char **argv) {
int a[] = { 1, 2, 3, 4, 5, 6 },
dir = argc > 1 ? LEFT : RIGHT;
size_t n = sizeof a / sizeof *a;
printf ("original:");
for (size_t i = 0; i < n; i++)
printf (" %d", a[i]);
putchar ('\n');
arrayshift (a, n, dir);
printf ("shifted :");
for (size_t i = 0; i < n; i++)
printf (" %d", a[i]);
putchar ('\n');
return 0;
}
/** shift array index in in circular manner by 1 in the
* 0 - left or 1 - right direction.
*/
void arrayshift (int *a, size_t nmemb, int dir)
{
if (dir) { /* shift to RIGHT */
int tmp = a[nmemb - 1];
for (size_t i = nmemb - 1; i > 0; i--)
a[i] = a[i - 1];
a[0] = tmp;
}
else { /* shift to LEFT */
int tmp = a[0];
for (size_t i = 1; i < nmemb; i++)
a[i - 1] = a[i];
a[nmemb - 1] = tmp;
}
}
Example Use/Output
$ ./bin/array_cir_shift_by_1
original: 1 2 3 4 5 6
shifted : 6 1 2 3 4 5
$ ./bin/array_cir_shift_by_1 0
original: 1 2 3 4 5 6
shifted : 2 3 4 5 6 1
You can also pass the number of element to shift the array by and use the modulo operator to help with the indexing. (that is left for another day)
In the hottest part of my program (90% of time according to gprof), I need to sum one array A into another B. Both arrays are 2^n (n is 18..24) sized and holds an integer (for simplicity, actually the element stored is mpz_t or small int array). The rule of summing: for each i in 0..2^n-1, set B[i] = sum (A[j]), where j is bit vector, and j & ~ i == 0 (in other words, k-th bit of any j can't be set to 1 if k-th bit of i is not 1).
My current code (this is a body of innermost loop) does this in the time of 2^(1.5 * n) sums, because I will iterate for each i on (in average) 2^(n/2) elements of A.
int A[1<<n]; // have some data
int B[1<<n]; // empty
for (int i = 0; i < (1<<n); i++ ) {
/* Iterate over subsets */
for (int j = i; ; j=(j-1) & i ) {
B[i] += A[j]; /* it is an `sum`, actually it can be a mpz_add here */
if(j==0) break;
}
}
My I mentioned, that almost any sum is recomputed from the values, summed earlier. I suggest, there can be code, doing the same task in the time of n* 2^n sums.
My first idea is that B[i] = B[i_without_the_most_significant_bit] + A[j_new]; where j_new is only j's having the most_significant bit from i in '1' state. This halves my time, but this is not enough (still hours and days on real problem size):
int A[1<<n];
int B[1<<n];
B[0] = A[0]; // the i==0 will not work with my idea and clz()
for (int i = 1; i < (1<<n); i++ ) {
int msb_of_i = 1<< ((sizeof(int)*8)-__builtin_clz(i)-1);
int i_wo_msb = i & ~ msb;
B[i] = B[i_wo_msb];
/* Iterate over subsets */
for (int j_new = i; ; j_new=(j_new-1) & i ) {
B[i] += A[j_new];
if(j_new==msb) break; // stop, when we will try to unset msb
}
}
Can you suggest better algorithm?
Additional image, list of i and j summed for each i for n=4:
i j`s summed
0 0
1 0 1
2 0 2
3 0 1 2 3
4 0 4
5 0 1 4 5
6 0 2 4 6
7 0 1 2 3 4 5 6 7
8 0 8
9 0 1 8 9
a 0 2 8 a
b 0 1 2 3 8 9 a b
c 0 4 8 c
d 0 1 4 5 8 9 c d
e 0 2 4 6 8 a c e
f 0 1 2 3 4 5 6 7 8 9 a b c d e f
Note the similarity of figures
PS the msb magic is from here: Unset the most significant bit in a word (int32) [C]
Divide and conquer anyone? Now not in-place.
void sums(int *a, int n, int *b) {
if (n <= 0) {
*b = *a;
return;
}
int m = 1 << (n - 1);
sums(a, n - 1, b);
sums(a + m, n - 1, b + m);
for (int i = 0; i < m; i++) {
b[m + i] += b[i];
}
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Algorithm to rotate an image 90 degrees in place? (No extra memory)
By saying 90 degrees i mean to say if:
A = {1,2,3,
4,5,6,
7,8,9}
then after 90 degree rotation A becomes:
A = {7,4,1,
8,5,2,
9,6,3}
Transpose and interchange rows or columns (depends whether you want to rotate left or right).
e. g.
1) original matrix
1 2 3
4 5 6
7 8 9
2) transpose
1 4 7
2 5 8
3 6 9
3-a) change rows to rotate left
3 6 9
2 5 8
1 4 7
3-b) or change columns to rotate right
7 4 1
8 5 2
9 6 3
All these operations can be done without allocating memory.
let a be an nxn array 0 based indexing
f = floor(n/2)
c = ceil(n/2)
for x = 0 to f - 1
for y = 0 to c - 1
temp = a[x,y]
a[x,y] = a[y,n-1-x]
a[y,n-1-x] = a[n-1-x,n-1-y]
a[n-1-x,n-1-y] = a[n-1-y,x]
a[n-1-y,x] = temp
Edit If you want to avoid using temp, this works (it also rotates in the correct direction) this time in python.
def rot2(a):
n = len(a)
c = (n+1) / 2
f = n / 2
for x in range(c):
for y in range(f):
a[x][y] = a[x][y] ^ a[n-1-y][x]
a[n-1-y][x] = a[x][y] ^ a[n-1-y][x]
a[x][y] = a[x][y] ^ a[n-1-y][x]
a[n-1-y][x] = a[n-1-y][x] ^ a[n-1-x][n-1-y]
a[n-1-x][n-1-y] = a[n-1-y][x] ^ a[n-1-x][n-1-y]
a[n-1-y][x] = a[n-1-y][x] ^ a[n-1-x][n-1-y]
a[n-1-x][n-1-y] = a[n-1-x][n-1-y]^a[y][n-1-x]
a[y][n-1-x] = a[n-1-x][n-1-y]^a[y][n-1-x]
a[n-1-x][n-1-y] = a[n-1-x][n-1-y]^a[y][n-1-x]
Note: This only works for matrices of integers.
The algorithm is to rotate each "ring", working from the outermost to the innermost.
AAAAA
ABBBA
ABCBA
ABBBA
AAAAA
The algorithm would rotate all the A's first, then B's then C's. Rotating a ring requires moving 4 values at once.
The index i ranges from 0..ring-width-1, e.g. for A the width is 5.
(i,0) -> temp
(0, N-i-1) -> (i, 0)
(N-i-1, N-1) -> (0, N-i-1)
(N-1, i) -> (N-i-1, N-1)
temp -> (N-1, i)
This is then repeated for each successive inner ring, offsetting the co-ordinates reducing the ring width by 2.
[Another answer has appeared with the code, so I'll not repeat that.]
Complete implementation in C using the method described by #Narek above
#include <stdio.h>
int n;
unsigned int arr[100][100];
void rotate() {
int i,j,temp;
for(i=0; i<n; i++) {
for(j=i; j<n; j++) {
if(i!=j) {
arr[i][j]^=arr[j][i];
arr[j][i]^=arr[i][j];
arr[i][j]^=arr[j][i];
}
}
}
for(i=0; i<n/2; i++) {
for(j=0; j<n; j++) {
arr[j][i]^=arr[j][n-1-i];
arr[j][n-1-i]^=arr[j][i];
arr[j][i]^=arr[j][n-1-i];
}
}
}
void display(){
int i,j;
for(i=0;i<n;i++) {
for(j=0;j<n;j++) {
printf("%d",arr[i][j]);}
printf("%s","\n");
}
}
int main(int argc, char *argv[]){
int i,j;
printf("%s","Enter size of matrix:");
scanf("%d",&n);
printf("%s","Enter matrix elements\n");
for(i=0;i<n;i++) {
for(j=0;j<n;j++) {
scanf("%d",&arr[i][j]);
}
}
rotate();
display();
return 0;
}
See this article for in-place matrix transposition; also google for "in-place matrix transposition". It can be easily adapted to perform rotation by 90 degrees. To transpose square matrices, you just interchange b[i][j] with b[j][i] where b[k][l] is a[n*k+l]. On nonsquare matrices, it's considerably more difficult. "Without any extra space" is a rather strong requirement, maybe you meant O(1) space? (assuming integers are fixed size) Implementation in C++: here.
You need one temp variable, then it is just to jump elements around.
temp = A[0];
A[0] = A[6];
A[6] = A[8];
A[8] = A[2];
A[2] = temp;
temp = A[1];
A[1] = A[3];
A[3] = A[7];
A[7] = A[5];
A[5] = temp;
I came across the following implementation:
For square matrices:
for n = 0 to N - 2
for m = n + 1 to N - 1
swap A(n,m) with A(m,n)
For rectangular matrices:
for each length>1 cycle C of the permutation
pick a starting address s in C
let D = data at s
let x = predecessor of s in the cycle
while x ≠ s
move data from x to successor of x
let x = predecessor of x
move data from D to successor of s
For more info, one can refer here: http://en.wikipedia.org/wiki/In-place_matrix_transposition