fpdf cell positioning from array - arrays

I have an array named Array with its elements: A, B ,C,D,...,Z
I wanna generated a pdf using FPDF which will shows as below:
Elements in Array: A | B | C
D | E | F
.........
X | Y | Z
The code above only shows elements in a single column. I have no idea how to make it to display as i desire. Please help.
$pdf->Cell('50','0','Elements in Array:',0,0,'L');
$pdf->Cell('50','0',' '.$Array[0],0,0,'L');
$pdf->Ln(5);
for($i=1;$i<=count($Array);$i++)
{
$pdf->Cell('50','0','',0,0,'L');
$pdf->Cell('50','0',' '.$Array[$i],0,0,'L');
$pdf->Ln(5);
}

Here's the basic approach; you can work out the details for yourself.
Instead of $i++, use $i += 3, so that each iteration deals with 3 elements of the array. Then, in each iteration, call Cell 3 times, one for each of the three columns. Draw lines, too if you want. (The subscripts you'll use for the 3 elements are $i, $i + 1, and $i + 2.)
Each row of 3 Cells should be positioned at $y. With each iteration, increment $y by whatever spacing seems to work best.
Since the total number of elements isn't necessarily divisible by 3, you'll have to test $i to avoid referencing a nonexistent element, and then break out of the loop.

Related

Perl: How to delete elements from array without spaces

How to delete the elements of array from index 4 to 10. I am doing like this
#!usr/bin/perl
#array=1..10;
#array[0..3]=#array[5..8];
#array[4..10]=();
$str=(join ",",#array);
print "$str\n";
and getting output as
6,7,8,9,,,,,,,
How to remove extra ","?
You're doing a bit more than trying to delete elements of the array in that code...
Anyways, you want splice to remove a contiguous range of array elements:
splice #array, 4, 6;
I'm assuming this is some kind of homework question, because if it's not you're doing some REALLY strange things with this code.
But let's take the problem at hand - the easiest way to filter an array is with grep
my #no_empty = grep { defined } #array;
print join ( ",", #no_empty )
In this we use grep to filter out any undef array elements. The element is returned if the expression in the braces evaluates as true - $_ is set to the current element, and used in any tests that implicitly work on $_. defined does, as does regular expression matches.
However if you genuinely just want to truncate the array to an arbitrary number, you can just do:
#array = #array[0..4]
You start with this array:
my #array = 1..10;
Now you have an array of 10 elements.
1 2 3 4 5 6 7 8 9 10
In your next step, you perform an array slice then assign that to another array slice:
#array[0..3] = #array[5..8];
This leaves alone the elements from 5 to 8, but does a list assignment of their values to the elements from 0 to 3, so you end up with some duplicated elements:
6 7 8 9 5 6 7 8 9 10
Now you want to get rid of everything after index 4. You try that with another list assignment:
#array[4..10] = ();
However, that just assigns the list on the right to the list on the right. As with any list assignment, the left hand elements get their corresponding elements from the right hand list. If the right hand list doesn't have enough elements, Perl uses undef for the rest of the right hand elements. That's why you still have 10 elements in #array:
6 7 8 9 undef undef undef undef undef undef undef
If you want 4 to be the last index, you can assign to the last index of the array. Whatever number you assign becomes the last index, either shortening or extending the array. Since you wanted to get rid of elements 4 and beyond, you can set the last index to 3 (the index right before the one you want to remove):
$#array = 3;
Now you've truncated the array to four elements:
6 7 8 9
You can also do this with splice, which replaces part of an array:
splice #array, $start_index, $length, #replacement;
You might use the starting index to figure out the length since you want to go all the way to the end. Then, replace that portion of the array with the empty list, which effectively makes the array shorter:
my $start = 4;
splice #array, $start, #array - $start, ();
Leaving off the replacement list is the same as the empty list:
splice #array, $start, #array - $start;
This is much more handy when you want to remove parts in the middle. This removes three elements starting at index 4 (so there will be stuff left over at the end):
splice #array, 4, 3;
Now your array has elements that were at the beginning and end of your array:
6,7,8,9,8,9,10
Without shortening the array
There's another sort of problem. You don't want to change the array, but you don't want to deal with empty fields. You can use a grep to select only the defined elements:
say join ',', grep { defined } #array;
If you have undefined elements in the middle of the array, this might be a problem if you expect columns to line up properly. Removing a column in the middle shifts the other columns. You may not care about that though.
Similarly, you might turn the undefined values into something that makes sense for the problem. A map can inspect the value and decide to pass it through or transform it. In this example, undef values turn into 0:
say join ',', map { defined ? $_ : 0 } #array;
6,7,8,9,0,0,0,0,0,0,0
Or "NULL":
say join ',', map { defined ? $_ : 'NULL' } #array;
6,7,8,9,NULL,NULL,NULL,NULL,NULL,NULL,NULL
Or even just undef as a string:
say join ',', map { defined ? $_ : 'undef' } #array;
6,7,8,9,undef,undef,undef,undef,undef,undef,undef
Sometimes those are handy to see what's going on.
And map can act like grep to filter an array. Use the empty list to pass on no elements from the map:
say join ',', map { defined ? $_ : () } #array;

How do I move 1st element in array to the last position in powershell?

I have a powershell array with about 10 items. I'm trying to take the 1st element (0) of the array and move it to the last item. There will still be (only) 10 items in the array at the end.
If you don't mind creating a new array, here's a concise solution:
$a = 1..10 # sample array: 1, 2, ..., 10
$a = $a[1..($a.count-1)] + $a[0]
minmaxavg eventually came up with an even more concise alternative in their answer:
$a[1..($a.count-1) + 0]
Performance-wise the two solutions are virtually identical.
Also, their [array]::Copy() solution is a more efficient, in-place alternative - at the expense of being more complex to write; it could be simplified somewhat to:
$first = $a[0]; [array]::Copy($a, 1, $a, 0, $a.Count - 1); $a[-1] = $first
$a now contains:
2
3
4
5
6
7
8
9
10
1
$a[1..($a.count-1)] returns a new array that contains all elements of $a starting with the element at index 1, i.e., starting with the 2nd element.
1..($a.count-1) is a range expression which itself creates an array - the array of indices to extract from the input array.
As an aside:
PowerShell supports index -1 to refer to an array's last element, -2 to refer to the second-to-last, and so on.
However, using negative indices in a range may not do what you expect; e.g., 1..-1 does not extract all elements from the 2nd to the second-to-last one (GitHub issue #7940 proposes new syntax similar to C#'s ranges to support this use case); instead, it extracts elements with indices 1, 0, and -1 (the last), because these are the elements of the array (of indices) that the range operator (..) generates.
+ $a[0] "appends" the first element to that new array; technically, this creates another array that is the concatenation of the elements of the LHS and the RHS.
In summary, 3 arrays were created in the process: 2 auxiliary, transient ones behind the scenes, plus the result array assigned back to $a.
Therefore, while using the range operator (..) to extract array slices and using + to concatenate arrays is very convenient, it is not efficient, though with small arrays that usually doesn't matter - beware of "appending" to an array in a loop with +=, however, as you'll be recreating the array in every iteration.
If you want to rotate the array in-place, this is more efficient than manually iterating and shifting elements in Powershell (.NET Array.Copy is analogous to Java System.arraycopy):
New-Variable -Name first -Value $arr[0] -Scope Private
[array]::Copy($arr, 1, $arr, 0, $arr.Length - 1)
$arr[$arr.Length - 1] = $Private:first
If copying is desirable (10 elements should be ok):
$arr = $arr[1 .. ($arr.Length - 1) + 0]
Powershell allows combination of two or more ranges through the + operator. Especially if you intend the array to be immutable, this should be the most optimal solution.

Filling a row and columns of a ndarray with a loop

I'm starting with Python and I have a basic question with "for" loop
I have two array which contains a values of a same variables:
A = data_lac[:,0]
In the first array, I have values of area and in the second on, values of mean depth.
I would like to find a way to automatize my calculation with different value of a parameter. The equation is the following one:
g= (np.sqrt(A/pi))/n
Here I can calculte my "g" for each row. Now I want to have a loop with differents values of "n". I did this:
i=0
while i <= len(A)-1:
for n in range(2,6):
g[i] = (np.sqrt(A[i]/pi))/n
i += 1
break
In this case, I just have one column with the calculation for n = 2 but not the following one. I tried to add a second dimension to my array but I have an error message saying that I have too many indices for array.
In other, I would like this array:
g[len(A),5]
g has 5 columns each one calculating with a different "n"
Any tips would be very helpful,
Thanks
Update of the code:
data_lac=np.zeros((106,7))
data_lac[:,0:2]=np.loadtxt("/home...", delimiter=';', skiprows=1, usecols=(0,1))
data_lac[:,1]=data_lac[:,1]*0.001
#Initialisation
A = data_lac[:,0]
#example for A with 4 elements
A=[2.1, 32.0, 4.6, 25]
g = np.zeros((len(A),))
I believe you share the indexes within both loops. You were increasing the i (index for the upper while loop) inside the inner for loop (which index with n).
I guess you have A (1 dim array) and you want to produce G (2 dim array) with size of (Len(A, 5))
I am not sure I'm fully understand your require output but I believe you want something like:
i=0
while i <= len(A)-1:
for n in range(2,6):
g[i][n-2] = (np.sqrt(A[i]/pi))/n # n-2 is to get first index as 0 and last as 4
i += 1 # notice the increace of the i is for the upper while loop
break
Important - remember that in python indentation means a lot -> so make sure the i +=1 is under the while scope and not indent to be inside the for loop
Notice - G definition should be as:
g = np.zeros((len(A),4), dtype=float)
The way you define it (without the 4) cause it to be 1 dim array and not 2-dim

The number of same elements in an array

My aim is to display the number of identical elements in an array.
Here is my code:
a = [5, 2, 4, 1, 2]
b = []
for i in a
unless b.include?(a[i])
b << a[i]
print i," appears ",a.count(i)," times\n"
end
end
I get this output:
5 appears 1 times
2 appears 2 times
4 appears 1 times
The output misses 1.
Here's a different way to do it, assuming I understand what "it" is (counting elements in an array):
a = [5,2,4,1,2]
counts = a.each_with_object(Hash.new(0)) do |element, counter|
counter[element] += 1
end
# => {5=>1, 2=>2, 4=>1, 1=>1}
# i.e. one 5, two 2s, one 4, one 1.
counts.each do |element, count|
puts "#{element} appears #{count} times"
end
# => 5 appears 1 times
# => 2 appears 2 times
# => 4 appears 1 times
# => 1 appears 1 times
Hash.new(0) initialises a hash with a default value 0. We iterate on a (while passing the hash as an additional object), so element will be each element of a in order, and counter will be our hash. We will increment the value of the hash indexed by the element by one; on the first go for each element, there won't be anything there, but our default value saves our bacon (and 0 + 1 is 1). The next time we encounter an element, it will increment whatever value already is present in the hash under that index.
Having obtained a hash of elements and their counts, we can print them, of course, puts is same as print but automatically inserts a newline; and rather than using commas to print several things, it is much nicer to put the values directly into the printed string itself using the string interpolation syntax ("...#{...}...").
The problems in your code are as follows:
[logic] for i in a will give you elements of a, not indices. Thus, a[i] will give you nil for the first element, not 5, since a[5] is outside the list. This is why 1 is missing from your output: a[1] (i.e. 2) is already in b when you try to process it.
[style] for ... in ... is almost never seen in Ruby code, with strong preference to each and other methods of Enumerable module
[performance] a.count(i) inside a loop increases your algorithmic complexity: count itself has to see the whole array, and you need to iterate the array to see i, which will be exponentially slower with huge arrays. The method above only has one loop, as access to hashes is very fast, and thus grows more or less linearly with the size of the array.
The stylistic and performance problems are minor, of course; you won't see performance drop till you need to process really large arrays, and style errors won't make your code not work; however, if you're learning Ruby, you should aim to work with the language from the start, to get used to its idioms as you go along, as it will give you much stronger foundation than transplanting other languages' idioms onto it.
a = [5,2,4,1,2]
b = a.uniq
for i in b
print i," appears ",a.count(i)," times\n"
end
print b
Result:
5 appears 1 times
2 appears 2 times
4 appears 1 times
1 appears 1 times
[5, 2, 4, 1]

Move/remove an element in one array into another

I'm doing a project in C involving arrays. What I have is an array of 7 chars, I need to populate an array with 4 random elements from the 7. Then I compare an array I fill myself to it. I don't want to allow repeats. I know how to compare each individual element to another to prevent it but obviously this isn't optimal. So if I remove the elements from the array as I randomly pick them I remove any chance of them being duplicated, or so I think. My question is how would I do this?
Example:
char name[2+1] = {'a','b'};
char guess[2+1] = {};
so when it randomly picks a or b and puts it in guess[],
but the next time it runs it might pick the same. Removing it will get rid of that chance.
In bigger arrays it would make it faster then doing all the comparing.
Guys it just hit me.
Couldn't I switch the element I took with the last element in the array and shrink it by one?
Then obviously change the rand() % x modulus by 1 each time?
I can give you steps to do what you intend to do. Code it yourself. Before that let's generalize the problem.
You've an array of 'm' elements and you've to fill another 'n' length
array by choosing random elements from first array such that there are
no repetition of number. Let's assume all numbers are unique in first
array.
Steps:
Keep a pointer or count to track the current position in array.
Initialize it to zeroth index initially. Let's call it current.
Generate a valid random number within the range of current and 'm'. Let's say its i. Keep generating until you find something in range.
Fill second_array with first_array[i].
Swap first_array[i] and first_array[current] and increment current but 1.
Repeat through step 2 'n' times.
Let's say your array is 2, 3, 7, 5, 8, 12, 4. Its length is 7. You've to fill a 5 length array out of it.
Initialize current to zero.
Generate random index. Let's say 4. Check if its between current(0) and m(7). It is.
Swap first_array[4] and first_array[0]. array becomes 8, 3, 7, 5, 2, 12, 4
Increment current by 1 and repeat.
Here are two possible ways of "removing" items from an array in C (there are other possible way too):
Replace the item in the array with another items which states that this item is not valid.
For example, if you have the char array
+---+---+---+---+---+---+
| F | o | o | b | a | r |
+---+---+---+---+---+---+
and you want to "remove" the b the it could look like
+---+---+---+------+---+---+
| F | o | o | \xff | a | r |
+---+---+---+------+---+---+
Shift the remaining content of the array one step up.
To use the same example from above, the array after shifting would look like
+---+---+---+---+---+---+
| F | o | o | a | r | |
+---+---+---+---+---+---+
This can be implemented by a simple memmove call.
The important thing to remember for this is that you need to keep track of the size, and decrease it every time you remove a character.
Of course both these methods can be combined: First use number one in a loop, and once done you can permanently remove the unused entries in the array with number two.
To don't forget that an array is just a pointer on the beginning of a set of items of the same type in C. So to remove an element, you simply have to replace the element at the given index with a value that shows that it is not a valid entry i.e. null.
As the entry is a simple number, there is no memory management issue (that I know of) but if it were an object, you would have to delete it if it is the last reference you have on it.
So let's keep it simple:
array2[index2] = array1[index1];
array1[index1] = null;
The other way is to change the size of the original array so that it contains one less element, as Joachim stated in his answer.

Resources