Pointer notation to declare a two dimensional array in C programming - arrays

Given the following
0 1 2 3
4 5 6 7
8 9 10 11
How do I use pointer notation to declare the above data as a two dimensional array x.
Does it work to simply write
int (*x)[4] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};

int x[4][4] = {
{ 0, 1, 2, 3 },
{ 4, 5, 6, 7 },
{ 8, 9, 10, 11 },
{ 12, 13, 14, 15 } };
printf("x[2][2] = %d\n", x[2][2]);

Related

on restoring the original order of row elements

Consider numpy array p shown below. Unique values 0 to 9 are used in each row. The distinguishing characteristic is that every row is composed of 5 (in this case) values PAIRED with 5 other values. Pairs are formed when p[k] = p[p[k]] for k = 0 to 9.
p = np.array([[1, 0, 3, 2, 5, 4, 7, 6, 9, 8],
...
[6, 5, 3, 2, 9, 1, 0, 8, 7, 4],
...
[9, 8, 5, 7, 6, 2, 4, 3, 1, 0]])
Examine, for example, the row:
[6, 5, 3, 2, 9, 1, 0, 8, 7, 4]
This row pairs values 6 and 0 because p[6] = 0 and p[0] = 6. Other pairs are values (5, 1), (3, 2), (9, 4), (8, 7). Different rows may have different arrangements of pairs.
Now, we are interested here in the 1st value of each pair (ie: 6, 5, 3, 9, 8) and the 2nd value of each pair (ie: 0, 1, 2, 4, 7)
I'm not sure this is the best way to proceed, but I've separated the 1st pair values from the 2nd pair values this way:
import numpy as np
p = np.array([6, 5, 3, 2, 9, 1, 0, 8, 7, 4])
p1 = np.where(p[p] < p) # indices of 1st member of pairs
p2 = (p[p1]) # indices of 2nd member of pairs
qi = np.hstack((p1, p2.reshape(1,5)))
qv = p[qi]
#output: qi = [0, 1, 2, 4, 7, 6, 5, 3, 9, 8] #indices of 1st of pair values, followed by 2nd of pair values
# qv = [6, 5, 3, 9, 8, 0, 1, 2, 4, 7] #corresponding values
Finally consider another 1D array: c = [1, 1, 1, 1, 1, -1, -1, -1, -1, -1].
I find c*qv, giving:
out1 = [6, 5, 3, 9, 8, 0, -1, -2, -4, -7]
QUESTION: out1 holds the correct values, but I need them to be in the original order (as found in p). How can this be achieved?
I need to get:
out2 = [6, 5, 3, -2, 9, -1, 0, 8, -7, -4]
You can reuse p1 and p2, which hold the original position information.
out2 = np.zeros_like(out1)
out2[p1] = out1[:5]
out2[p2] = out1[5:]
print(out2)
# [ 6 5 3 -2 9 -1 0 8 -7 -4]
Can also use qi to similar effect, but even neater.
out2 = np.zeros_like(out1)
out2[qi] = out1
Or using np.put in case you don't want to create out2:
np.put(out1, qi, out1)
print(out1)
# [ 6 5 3 -2 9 -1 0 8 -7 -4]
2D Case
For 2D version of the problem, we will use a similar idea, but some tricks while indexing.
p = np.array([[1, 0, 3, 2, 5, 4, 7, 6, 9, 8],
[6, 5, 3, 2, 9, 1, 0, 8, 7, 4],
[9, 8, 5, 7, 6, 2, 4, 3, 1, 0]])
c = np.array([1, 1, 1, 1, 1, -1, -1, -1, -1, -1])
p0 = np.arange(10) # this is equivalent to p[p] in 1D
p1_r, p1_c = np.where(p0 < p) # save both row and column indices
p2 = p[p1_r, p1_c]
# We will maintain row and column indices, not just qi
qi_r = np.hstack([p1_r.reshape(-1, 5), p1_r.reshape(-1, 5)]).ravel()
qi_c = np.hstack([p1_c.reshape(-1, 5), p2.reshape(-1, 5)]).ravel()
qv = p[qi_r, qi_c].reshape(-1, 10)
out1 = qv * c
# Use qi_r and qi_c to restore the position
out2 = np.zeros_like(out1)
out2[qi_r, qi_c] = out1.ravel()
print(out2)
# [[ 1 0 3 -2 5 -4 7 -6 9 -8]
# [ 6 5 3 -2 9 -1 0 8 -7 -4]
# [ 9 8 5 7 6 -2 -4 -3 -1 0]]
Feel free to print out each intermediate variable, will help you understand what's going on.

For each element in an array, if the element is less than its previous element, increase it till the previous element with one

Suppose I have an array: list1 = [8, 5, 3, 1, 1, 10, 15, 9]
Now if the element is less than its previous element, increase it till the previous element with one.
Here:
5 < 8 so 5 should become: 5 + 3 + 1 = 9 i.e (8+1)
3 < 5 so 3 should become: 3 + 2 + 1 = 6 i.e (5+1)
1 < 3 so 1 should become: 1 + 2 + 1 = 4 i.e (3+1)
Now I am able to get the difference between elements if its less than its previous element.
But, how to use it in a final list to get an output like this:
finallist = [8, 9, 6, 4, 1, 10, 15, 16]
Also how can I get a final list value of 'k' list in my code? Right now it shows:
[2]
[2, 4]
[2, 4, 3]
[2, 4, 3, 3]
[2, 4, 3, 3, 7]
Source code:
list1 = [8, 5, 3, 1, 1, 10, 15, 9]
k = []
def comput(x):
if i[x] < i[x-1]:
num = (i[x-1] - i[x]) + 1
k.append(num)
print(k)
return
for i in [list1]:
for j in range(len(list1)):
comput(j)
You can use a list comprehension for this. Basically, the following code will check if one is larger than the next. If it is, then it will convert it to the previous+1.
list1 = [8, 5, 3, 1, 1, 10, 15, 9]
k = [list1[0]] + [i if j<=i else j+1 for i,j in zip(list1[1:],list1[:-1])]
cost = [j-i for i,j in zip(list1,k)]
print(k)
print(cost)
Output:
[8, 9, 6, 4, 1, 10, 15, 16]
[0, 4, 3, 3, 0, 0, 0, 7]
The following code will create a new list with the required output
l1 = [8, 5, 3, 1, 1, 10, 15, 9]
l = [l1[0]]
c=[0] # cost / difference list
for i in range(len(l1)-1):
if l1[i+1] < l1[i]:
l.append(l1[i]+1)
c.append(l1[i]+1-l1[i+1])
else:
l.append(l1[i+1])
c.append(0)
print(l)
Output
[8, 9, 6, 4, 1, 10, 15, 16]
[0, 4, 3, 3, 0, 0, 0, 7]

Confusion with loops in C

i have to make a program with the following condition: A delivery guy deliver stacks(packs) of beer to different shops
1st shop, 1 stack
2nd shop, 2 stacks
3rd shop, 3 stacks
...
until 10th shop.
The program must print it like this :
int i1,shop[10]={1,2,3,4,5,6,7,8,9,10},stacks[10]={1,2,3,4,5,6,7,8,9,10},counter;
for (i1 = 9; i1 >= 0; i1--){
for(counter=0;counter<=i1;counter++){
printf("Shop[%i] %i \t",shop[i1], stacks[i1]);
}
It's running but the output is not what I want :
Shop[10] 10 Shop[10] 10 Shop[10] 10 Shop[10] 10
Shop[10] 10 Shop[10] 10 Shop[10] 10 Shop[10] 10
Shop[10] 10 Shop[10] 10 Shop[9] 9 Shop[9] 9
Shop[9] 9 Shop[9] 9 Shop[9] 9 Shop[9] 9
Shop[9] 9 Shop[9] 9 Shop[9] etc.
It must look like this:
Shop 1 - 1
Shop 2 - 2, 2
Shop 3 - 3, 3, 3
Shop 4 - 4, 4, 4, 4.
You've got your loops scrambled. Here is a piece of code that will print what you want. Modify the code so it access the right arrays and print their contents:
for(i = 1; i <= 10; i++) {
printf("Shop %d - ", i);
for(j = 1; j <= i; j++)
printf("%d, ", i);
putchar('\n');
}
The first loop (with i), will print the "Shop - " string, 10 times. The second loop will run for every iteration of the first loop, thus, giving you the correct numbers of prints. Minor code changes will take core of the comma printing...
Outputs:
Shop 1 - 1,
Shop 2 - 2, 2,
Shop 3 - 3, 3, 3,
Shop 4 - 4, 4, 4, 4,
Shop 5 - 5, 5, 5, 5, 5,
Shop 6 - 6, 6, 6, 6, 6, 6,
Shop 7 - 7, 7, 7, 7, 7, 7, 7,
Shop 8 - 8, 8, 8, 8, 8, 8, 8, 8,
Shop 9 - 9, 9, 9, 9, 9, 9, 9, 9, 9,
Shop 10 - 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
You'll need to use multiple printf statements to produce each line of output. Put
printf( "Shop %d", i1 );
in your outer loop (no newline).
Within your inner loop, you'll just print out the value of stacks[i1] (again, with no newlines):
printf( " %d", stacks[i1] );
You'll have to write a newline in a separate statement after the inner loop has finished:
putchar( '\n' );
Don't worry about commas or other separators for now.
Make those changes, and that'll get you most of the way there.
Edit
Your inner loop should check against stacks[i1], rather than i1.
If you want your output to appear on separate lines you need to put in a \n new line character at the end of the string like this rather than the tab character you've got currently.
printf("Shop[%i] %i \n",shop[i1], stacks[i1]);
Fist of all, please get used to write clean code so its more readeable, and your question more organized. Is this what you want?
int i1;
int shop[10]={1,2,3,4,5,6,7,8,9,10};
int stacks[10]={1,2,3,4,5,6,7,8,9,10};
int counter;
//To go through the shops
for (i1 = 0; i1 < 10; i1++){
printf("Shop[%i] - ",i1);
//to go through the packs
for(counter=0;counter<=i1;counter++){
printf("%i", stacks[counter]);
}
printf("\n");
}
To output the pattern there is no need to use arrays. You can output it using loops.
For example
#include <stdio.h>
int main(void)
{
const unsigned int N = 10;
const char *Title = "Shop %u - %u";
for ( unsigned int i = 0; i < N; i++ )
{
unsigned int item = i + 1;
printf( Title, item, item );
for ( unsigned int j = 0; j < i; j++ )
{
printf( ", %u", item );
}
putchar( '\n' );
}
return 0;
}
The program output is
Shop 1 - 1
Shop 2 - 2, 2
Shop 3 - 3, 3, 3
Shop 4 - 4, 4, 4, 4
Shop 5 - 5, 5, 5, 5, 5
Shop 6 - 6, 6, 6, 6, 6, 6
Shop 7 - 7, 7, 7, 7, 7, 7, 7
Shop 8 - 8, 8, 8, 8, 8, 8, 8, 8
Shop 9 - 9, 9, 9, 9, 9, 9, 9, 9, 9
Shop 10 - 10, 10, 10, 10, 10, 10, 10, 10, 10, 10
Pay attention to that there is no redundant last comma in the output.
If to define the variable Title the following way
const char *Title = "Shop %2u - %u";
^^^
then the output will be more aligned.
Shop 1 - 1
Shop 2 - 2, 2
Shop 3 - 3, 3, 3
Shop 4 - 4, 4, 4, 4
Shop 5 - 5, 5, 5, 5, 5
Shop 6 - 6, 6, 6, 6, 6, 6
Shop 7 - 7, 7, 7, 7, 7, 7, 7
Shop 8 - 8, 8, 8, 8, 8, 8, 8, 8
Shop 9 - 9, 9, 9, 9, 9, 9, 9, 9, 9
Shop 10 - 10, 10, 10, 10, 10, 10, 10, 10, 10, 10
Also you could define the variable like
const char *Title = "Shop %2u - %2u";
^^^ ^^^
For example
#include <stdio.h>
int main(void)
{
const unsigned int N = 10;
const char *Title = "Shop %2u - %2u";
for ( unsigned int i = 0; i < N; i++ )
{
unsigned int item = i + 1;
printf( Title, item, item );
for ( unsigned int j = 0; j < i; j++ )
{
printf( ", %2u", item );
}
putchar( '\n' );
}
return 0;
}
The output is
Shop 1 - 1
Shop 2 - 2, 2
Shop 3 - 3, 3, 3
Shop 4 - 4, 4, 4, 4
Shop 5 - 5, 5, 5, 5, 5
Shop 6 - 6, 6, 6, 6, 6, 6
Shop 7 - 7, 7, 7, 7, 7, 7, 7
Shop 8 - 8, 8, 8, 8, 8, 8, 8, 8
Shop 9 - 9, 9, 9, 9, 9, 9, 9, 9, 9
Shop 10 - 10, 10, 10, 10, 10, 10, 10, 10, 10, 10

Sum of ruby arrays in a loop

I want to find sum of arrays from 1 to 100.Each number is converted to array containing its own digits eg 97 will be [9,7].Here is what i have tried
(1..100).to_a.each do |i|
i.to_s.split("").map(&:to_i).inject(0) { |sum, number| sum + number }
end
But the sum of arrays are not displayed correctly!
For example;We first create an array of the digits and then return sum
[1]=1
[5]=5
[1, 0]=1
[1, 1]=2
[1, 2]=3
[1, 3]=4
[1, 4]=5
So sum of individual arrays is to be returned.
each will iterate the array, but not create a new array with the result of the block. If you want the results at the end, you need to use map:
result = (1..100).to_a.map do |i|
i.to_s.split("").map(&:to_i).inject(0) { |sum, number| sum + number }
end
result
#=> [1, 2, 3, 4, ...]
For summing an array you can also simply write
array.inject(:+)
# instead of
array.inject(0) { |sum, number| sum + number }
Also, the to_a is not necessary, you can directly call each and/or map on a range. So the simplified code would be
result = (1..100).map do |i|
i.to_s.split("").map(&:to_i).inject(:+)
end
result
#=> [1, 2, 3, 4, ...]
For your codes, you just need to change each method to map.
(1..100).to_a.map do |i|
i.to_s.split("").map(&:to_i).inject(0) { |sum, number| sum + number }
end
more simplicity way:
result = (1..100).to_a.map{ |e| e.to_s.split('').map(&:to_i).reduce(:+) }
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 1]
if you want to get the sum of result, just do like this:
result.reduce(:+)
If I understand your question correctly you want the sum of these new arrays, right? This should solve your problem:
(1..100).map { |i| i.to_s.split("").map(&:to_i).inject(:+) }.inject(:+)
digits and sum are newer methods, simplifying this to
(1..100).sum{|i| i.digits.sum}
Another alternative for modern newer versions of Ruby:
(1..100).flat_map(&:digits).sum

Sort BST in O(n) using constant memory

This is not a homework. Just an interesting task :)
Given a complete binary search three represensted by array. Sort the array in O(n) using constant memory.
Example:
Tree:
8
/ \
4 12
/\ / \
2 6 10 14
/\ /\ /\ /\
1 3 5 7 9 11 13 15
Array: 8, 4, 12, 2, 6, 10, 14, 1, 3, 5, 7, 9, 11, 13, 15
Output: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
It is possible, people calling it homework probably haven't tried solving it yet.
We use the following as a sub-routine:
Given an array a1 a2 ... an b1 b2 .. bn, convert in O(n) time and O(1) space to
b1 a1 b2 a2 ... bn an
A solution for that can be found here: http://arxiv.org/abs/0805.1598
We use that as follows.
Do the above interleaving for the first 2^(k+1) - 2 elements, starting at k=1 repeating for k=2, 3 etc, till you go past the end of array.
For example in your array we get (interleaving sets identified by brackets)
8, 4, 12, 2, 6, 10, 14, 1, 3, 5, 7, 9, 11, 13, 15
[ ][ ]
4, 8, 12, 2, 6, 10, 14, 1, 3, 5, 7, 9, 11, 13, 15 (k = 1, interleave 2)
[ ][ ]
2, 4, 6, 8, 10, 12, 14, 1, 3, 5, 7, 9, 11, 13, 15 (k = 2, interleave 6)
[ ][ ]
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 (k = 3, interleave 14)
So the total time is n + n/2 + n/4 + ... = O(n).
Space used is O(1).
That this works can be proved by induction.
Thinking about the O(1) in-place variant, but for now here's the O(N) solution
An O(N) space solution
If you can use an O(N) output array, then you can simply perform an inorder traversal. Every time you visit a node, add it to the output array.
Here's an implementation in Java:
import java.util.*;
public class Main {
static void inorder(int[] bst, List<Integer> sorted, int node) {
if (node < bst.length) {
inorder(bst, sorted, node * 2 + 1);
sorted.add(bst[node]);
inorder(bst, sorted, node * 2 + 2);
}
}
public static void main(String[] args) {
int[] bst = { 8, 4, 12, 2, 6, 10, 14, 1, 3, 5, 7, 9, 11, 13, 15 };
final int N = bst.length;
List<Integer> sorted = new ArrayList<Integer>();
inorder(bst, sorted, 0);
System.out.println(sorted);
// prints "[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]"
}
}
Attachment
Source and output on ideone.com

Resources