Confusion with loops in C - 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

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.

Need help filtering an array?

I am trying to remove odd numbers from an array.
arr = [1, 2, 3, 4, 5, 6, 7, 8, 10]
def remove_odd_nums(arr)
for x in arr
if x % 2 == 0
arr.delete(x)
end
end
end
print remove_odd_nums(arr)
# [1, 3, 5, 7, 10]
I can't seem to make this program work. The method works on the numbers except for the last one. What am I doing wrong?
You want to delete odd numbers but your program is deleting even numbers (x % 2 == 0 checks if x is an even number)
METHOD 1:
arr = [1, 2, 3, 4, 5, 6, 7, 8, 10]
arr.delete_if &:odd?
print arr
delete_if iterates by incrementing the index for arr, and deletes an element immediately after evaluating the block &:odd? with respect to the element. In other words, it is going through each element in array, and deleting the element if &:odd? is true.
&:odd?: a lambda function passing in an object to the odd? method, which returns true if the object is an odd number. Further explanations can be found what is the functionality of "&: " operator in ruby?
Note that method 1 actually MODIFIES the original array. For a way to create a new array of non-odd numbers, there is...
METHOD 2:
non_odds = arr.select{|i| not i.odd?}
TL;DR: don't modify an array while iterating it.
Let's see what's happening by printing the current value of x and arr inside the loop:
def remove_odd_nums(arr)
for x in arr
p x: x, arr: arr # <- debug output
if x % 2 == 0
arr.delete(x)
end
end
end
remove_odd_nums([1, 2, 3, 4, 5, 6, 7, 8, 10])
Output:
{:x=>1, :arr=>[1, 2, 3, 4, 5, 6, 7, 8, 10]}
{:x=>2, :arr=>[1, 2, 3, 4, 5, 6, 7, 8, 10]}
{:x=>4, :arr=>[1, 3, 4, 5, 6, 7, 8, 10]}
{:x=>6, :arr=>[1, 3, 5, 6, 7, 8, 10]}
{:x=>8, :arr=>[1, 3, 5, 7, 8, 10]}
The first two x values are as expected: 1 and 2. But then it moves on to 4, skipping 3. It also skips 5, 7, and 10. But why?
It's because you are modifying the array while iterating it. Think of the for loop as someone pointing to an element at a specific position. Initially it looks like this:
1 2 3 4 5 6 7 8 10 <- array
^ <- element
for then moves on to the next element:
1 2 3 4 5 6 7 8 10
^
at this point x % 2 == 0 becomes true and 2 is deleted from the array:
1 3 4 5 6 7 8 10
^
for isn't aware of this change and simply moves on to the next element:
1 3 4 5 6 7 8 10
^
which is why we have unintentionally skipped 3. The same happens for 5 and 7.
When for finally reaches 8:
1 3 5 7 8 10
^
it is being deleted:
1 3 5 7 10
^
and for stops looping because it seems to have reached the array's end.
Hello Practical1 just to clarify why do you want to destroy objects and array?
In case you on want to filter array and only select even numbers , you can try a combination of Array#select and Integer#even? method helpers
arr = arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# select all even numbers in an array
arr.select(&:even?) # shorthand for arr.select {|number| number.even? }
will return even numbers
[0] 2,
[1] 4,
[2] 6,
[3] 8,
[4] 10
source:
Array#select https://apidock.com/ruby/Array/select
Integer#even? https://ruby-doc.org/core-1.8.7/Integer.html
Ruby has fabulous methods to modify arrays in place based on the logic in a block.
To arrive at an array with only odd numbers, you can either remove the elements that don't meet a test or keep the number that do meet a test. You can either return a new array or use one of the in place modification methods.
To remove undesired values, use either .reject for a new array or .reject! to modify an existing array in place.
Since we are removing, we would use {|e| e%2!=0} inside the block for odd numbers:
> [1,2,3,4,5,6,7,8,9,10].reject {|e| e%2!=0}
=> [2, 4, 6, 8, 10] # new array
> arr = [1, 2, 3, 4, 5, 6, 7, 8, 10]
> arr.reject! {|e| e%2!=0}
=> [2, 4, 6, 8, 10] # arr modified in place
Rather than a block, you can also use the odd? logical test for the same result:
> [1,2,3,4,5,6,7,8,9,10].reject &:odd?
=> [2, 4, 6, 8, 10]
Or, you can keep the values desired and other values will not be kept. You would use {|e| e%2==0} inside the block for even values. Or you can use &:even? instead of the block.
You can use .keep_if to return a new array:
> arr
=> [1, 2, 3, 4, 5, 6, 7, 8, 10]
> [1,2,3,4,5,6,7,8,9,10].keep_if {|e| e%2==0}
=> [2, 4, 6, 8, 10] # new array.
Or use .select! to modify in place:
> arr = [1, 2, 3, 4, 5, 6, 7, 8, 10]
=> [1, 2, 3, 4, 5, 6, 7, 8, 10]
> arr.select! {|e| e%2==0}
=> [2, 4, 6, 8, 10]
> arr
=> [2, 4, 6, 8, 10] # arr modified in place

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]

Pointer notation to declare a two dimensional array in C programming

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]);

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