How to draw desired matrix using c++? - c++

Draw below matrix using c++. Problem require a function, which could be called into the main().
x!x!x
~~~~~
x!x!x
~~~~~
x!x!x
I tried comparing the location 0,2,4. and tried to print but is there any other way to do this problem ?

If the matrix are characters, you could do something like this:
char board[] =
"x|x|x\n"
"-+-+-\n"
"x|x|x\n"
"-+-+-\n"
"x|x|x\n"
;
The columns containing the character 'x' are located at indices 0, 2, 4, 14, 16, 18, 26, 28, 30. Row indices are 0, 14, and 28.
Hint: there are 6 characters per row.
Hint: columns indices are (row * (characters per row)) + ((column - 1) * (2 characters per row))
This has the nice benefit of only requirement one statement to print:
std::cout.write(&board[0], sizeof(board) - 1U);
The - 1U is so that the terminating nul is not sent to cout.

Related

Julia - replace

I have tried the following method and it worked.
a=[1,2,3]
b=[5,6,7]
for i=1:3
a=replace(a,a[i]=>b[i]*a[i])
end
The result showed: a=[5,12,21], which is the product I wanted,elementwise product.
However, I tried to use the same method for getting the product I want but it didn't work.
a=[]
for i=1:10
a=push!(a,2^i)
end
for i=1:10
a=replace(a,a[i]=>a[i]*a[i])
end
But the result is
a=[65536,65536,4096,65536,1048576,4096,16384,65536,262144,1048576]
And I want to yield
a=[4,16,64,256,1024,4096,16384,65536,262144,1048576]
The problem here is, that replace might not do what you want. The command
replace(A, old => new)
takes a collection A and creates a new collection where every occurrence of old is replaced by new.
So if we look at your example, in the first iteration we replace every occurrence of a[1] == 2 by 4. This yields
a == [4, 4, 8, 16, 32, 64, 128, 256, 512, 1024]
In the second iteration, we replace every occurrence of a[2] == 4 by 16. This yields
a == [16, 16, 8, 16, 32, 64, 128, 256, 512, 1024]
and so on. This should explain why you get that weird result.
Apart from the broadcasts a .= a .* a or a .= a .^ 2 that Oscar Smith mentioned in his comment, you could also use the functions map
a = map(x -> x^2, a)
or map!:
map!(x -> x^2, a, a)
The difference between map and map! is, that map creates a new version and map! writes to an already existing collection. In this example, the input collection is the same as the output collection.

MATLAB to C++: Coder: not consistent array dimension concatenation

adapting the code from this coder-compatible solution to read csv data i ran into the following issue during the runtime issue check of Matlab Coder:
Error using cat>>check_non_axis_size (line 283)
Dimensions of arrays being concatenated are not consistent.
Error in cat>>cat_impl (line 102)
check_non_axis_size(isempty, i, sizes{i}, varargin{:});
Error in cat (line 22)
result = cat_impl(#always_isempty_matrix, axis, varargin{:});
Error in readCsv (line 28)
coder.ceval('sscanf', [token, NULL], ['%lf', NULL], coder.wref(result(k)));
my adaptation:
function result = readCsv(filepath, rows, columns)
NULL = char(0);
fid = fopen(filepath, 'r');
% read entire file into char array
remainder = fread(fid, '*char');
% preallocation for speedup
result = coder.nullcopy(zeros(columns,rows));
k = 1;
while ~isempty(remainder)
% comma, newline
delimiters = [',', char(10)];
% strtok ignores leading delimiter,
% returns chars upto, but not including,
% the next delimiter
[token,remainder] = strtok(remainder, delimiters);
% string to double conversion
% no need to worry about return type / order
% since we only look at one token at a time
if coder.target('MATLAB')
result(k) = sscanf(token, '%f');
else
coder.ceval('sscanf', [token, NULL], ['%lf', NULL], coder.wref(result(k)));
end
k = k + 1;
end
% workaround for filling column-major but breaks on single-line csv
result = reshape(result,rows, [])';
disp(k)
fclose(fid);
the .csv in case is a 200x51 matrix
testing in matlab: works as expected - the .csv is read 1:1 as with csvread()
the error pops up during code generation, and as far as I understand, an issue with writing the result of sscanf into the preallocated result array - but only for the c code.
Addendum: a line with only integer values (1,1,1,...,0) works fine, a line with actual floats (6.7308,38.7101,...,40.5999,0) breaks with the aforementioned error.
remainder = fread(f, [1, Inf], '*char');
turns out sizeA argument is not optional in this case

How do I form characters design with do loop

I am trying to make characters with an output as such in Fortran but I don't know how to. I made one with columns of asterisks but now I need it to change to the image linked.
I am a novice at Fortran.
Here's my code for the columns:
program chardesign
integer complete
do complete = 1, 5
write (*, 10, advance='no')
10 format (' * ')
enddo
!Newline to complete
write (*, 10)
stop
end program chardesign
How can I go about this?
Since we can no longer restrain ourselves from offering solutions...
Suppose we had a file called diamond.txt that had the picture already drawn:
*
***
*****
*******
*********
*******
*****
***
*
I know it's not visible here, but each line in diamond.txt has sufficient trailing spaces to make it 9 characters long. Now we just need a program that copies diamond.txt to its output:
program diamond
implicit none
character(9) line
open(10,file='diamond.txt',status='old')
do
read(10,'(a)',end=20) line
write(*,'(a)') line
end do
20 continue
end program diamond
The program has a couple of new features: first off it has implicit none which forces the programmer to declare all variables, thus avoiding a common source of hard-to-trace programming errors. Then it declares a character variable character(9) line which creates a variable which always contains 9 characters. There are rules that govern what happens if you try to assign it to a string of lesser or greater length, but we won't do that here.
Then it opens the file diamond.txt. The unit number, 10, will be used to reference the file in subsequent I/O statements. The status='old' part will cause the program to abort if it can't find diamond.txt.
Then we have a do statement which means do forever. Of course we don't really want to 'do forever', so there should be some way to exit the loop from its body.
Now we have a read statement that reads from unit 10, which, due to our previous open statement, is our file diamond.txt. The end=20 part means that when the read statement tries to read past end-of-file execution jumps to statement number 20, which gets us out of the loop. The format (a) does character I/O. It is the same as (a9) because the program knows that the length of the character variable to be read, line, is 9, so it will try to read the next 9 characters from diamond.txt and put them in variable line. After the read statement is complete, the file pointer advances to the next line of diamond.txt.
Then the write statement just writes variable line to standard output, thus copying the current line of diamond.txt to the screen.
When it's done, the end=20 branch is taken getting us to the 20 continue statement after which the end line is encountered and execution terminates.
So how could we do this without an external file? We could just convert the picture into a format statement and then print according to the format:
1 format(' * '/ &
' *** '/ &
' ***** '/ &
' ******* '/ &
'*********'/ &
' ******* '/ &
' ***** '/ &
' *** '/ &
' * ')
print 1
end
So we have encountered a new format specifier, /, the 'slash', which advances I/O to the next record (or line). Also the free-format continuation character &, the 'ampersand', which means that the current line continues to the next noncomment line. Also the print statement where here print 1 has the same effect as write(*,1).
OK, but what if we wanted to carry out some kind of calculation to produce the picture? If we considered the picture to lie on a raster array where row i ran from 1 at the top to 9 at the bottom and column j ran from column 1 at the left to column 9 at the right, we might observe that the image is symmetric about i=5 and about j=5. If we considered i and j to run from -4 to 4 instead we might be able to see some patterns that enable us to take advantage of the symmetry now about the y-axis and x-axis. Accordingly we write a program that will print out the coordinates...
print"(9(1x:'(',i2,',',i2,')'))",[((i,j,j=-4,4),i=-4,4)];end
Now we have a couple of new program elements: there is an array constructor [stuff] which will create an array of the elements listed within the square brackets.
[(more_stuff,i=-4,4)] is an ac-implied-do which effectively creates a list by evaluating more_stuff sequentially for each value of i from -4 to 4, thus a list of 9 things.
[((still_more_stuff,j=-4,4),i=-4,4)] is a nested ac-impied-do which for each value of i makes a list by evaluating still_more_stuff sequentially for each value of j from -4 to 4, thus there is a list of 9*9=81 things.
Since still_more_stuff is i,j, i.e. 2 things, the array constructor creates an array of 162 things, each (i,j) pair with j varying faster than I.
The print statement has a format string surrounded by " double quotes rather than ' apostrophes so that we can use apostrophe-delimited strings in the format.
The 9(stuff) part is a repeat count that means to do the formats specified in stuff 9 times over.
The 1x format says just skip one space and the following colon just separates it from the next format item. We can use , (comma), : (colon), or / (slash) to separate format items. As the reader will recall, slash skips to the next record; for the purposes or the current discussion let's ignore the distinction between comma and colon.
The i2 format prints out an integer in a field of width 2. If it takes more than 2 characters to print out the integer it will print out two asterisks ** instead.
So the format with the repeat count will print out 2*9=18 integers. When the format is exhausted there are rules called format reversion that in this case will result in output advancing to the next line and the format being reused.
Finally, in free format code one can write the next line of code on the current one if the current statement is followed by a semicolon ;. Thus ;end puts the required end statement at the end of the program. Note that the introductory program statement, although good style, is optional.
The output of the program is as follows:
(-4,-4) (-4,-3) (-4,-2) (-4,-1) (-4, 0) (-4, 1) (-4, 2) (-4, 3) (-4, 4)
(-3,-4) (-3,-3) (-3,-2) (-3,-1) (-3, 0) (-3, 1) (-3, 2) (-3, 3) (-3, 4)
(-2,-4) (-2,-3) (-2,-2) (-2,-1) (-2, 0) (-2, 1) (-2, 2) (-2, 3) (-2, 4)
(-1,-4) (-1,-3) (-1,-2) (-1,-1) (-1, 0) (-1, 1) (-1, 2) (-1, 3) (-1, 4)
( 0,-4) ( 0,-3) ( 0,-2) ( 0,-1) ( 0, 0) ( 0, 1) ( 0, 2) ( 0, 3) ( 0, 4)
( 1,-4) ( 1,-3) ( 1,-2) ( 1,-1) ( 1, 0) ( 1, 1) ( 1, 2) ( 1, 3) ( 1, 4)
( 2,-4) ( 2,-3) ( 2,-2) ( 2,-1) ( 2, 0) ( 2, 1) ( 2, 2) ( 2, 3) ( 2, 4)
( 3,-4) ( 3,-3) ( 3,-2) ( 3,-1) ( 3, 0) ( 3, 1) ( 3, 2) ( 3, 3) ( 3, 4)
( 4,-4) ( 4,-3) ( 4,-2) ( 4,-1) ( 4, 0) ( 4, 1) ( 4, 2) ( 4, 3) ( 4, 4)
Looking at these results we might observe that within the diamond, |i|+|j|<=4 while outside, |i|+|j|>=5. Let's create a program to check this:
print'(9(L1))',[((abs(j)+abs(i)<5,j=-4,4),i=-4,4)];end
Similar to the last program, but now the still_more_stuff in the inner ac-implied-do, abs(j)+abs(i)<5 is a logical expression which asks 'is |j|+|i| less than 5?' The value of the expression will be .TRUE. or .FALSE., depending on the outcome of this test.
The L1 format is a logical I/O specifier that outputs T for .TRUE. or F for .FALSE..
Output of the program is as follows:
FFFFTFFFF
FFFTTTFFF
FFTTTTTFF
FTTTTTTTF
TTTTTTTTT
FTTTTTTTF
FFTTTTTFF
FFFTTTFFF
FFFFTFFFF
We can see the diamond but we need to convert to (spaces) and * (asterisks):
print'(9a)',merge('*',' ',[((abs(j)+abs(i)<5,j=-4,4),i=-4,4)]);end
And this does it! The merge function processes our logical array (the third argument) and everywhere a .TRUE. element is encountered, replaces it with an asterisk * (the first argument) while every .FALSE. element is replaced by a space (the second argument).
The resulting 81-element character array is printed out 9 elements at a time by the (9a) format string, resulting in the desired output. The whole program, although complex to write, was only 66 characters long :)
I propose this approach on implementation, because it gives you flexibility on the character string length to be printed.
program chardesign
implicit none
call print_diamond('*', 5, 1)
call print_diamond('()', 3, 3)
call print_diamond('.', 1, 4)
call print_diamond('0', 0, 3)
contains
subroutine print_diamond(str, depth, start)
character(*), intent(in) :: str
integer, intent(in) :: depth, start
character(len(str)) :: spc
integer :: i, span
spc = ''
span = start + (depth - 1) * 2
print '(a)', (repeat(spc, (span - i) / 2) // repeat(str, i), i = start, span, 2)
print '(a)', (repeat(spc, (span - i) / 2) // repeat(str, i), i = span - 2, start, -2)
end
end
This yields the following output:
*
***
*****
*******
*********
*******
*****
***
*
()()()
()()()()()
()()()()()()()
()()()()()
()()()
....

Mod of two large numbers in C++

I have a class named LargeNum, which stores large numbers by array such as digit[]. Because int is not large enough to store it.
The base is 10000, so number '9876 8764 7263' is stored like:
digit[4] = {9876, 8764, 7263};
(the base can be changed into 10 or 100, like digit[12] = {9,8,7,6,8,7,6,4,7,2,6,3})
The problem is that I want to overload operator %, so than I can get the remainder of two large numbers. Overloading operator *, - between large numbers is finished by dealing with every digit of the large number. But I really don't how to do so with %. Like:
{1234,7890,1234} % {4567,0023}
Can anyone help me?
The pseudocode should be:
while digits_source > digits_base {
while first_digit_source > first_digit_base {
source -= base << (digits_source - digits_base)
}
second_digit_source += first_digit_source * LargeNum.base
first_digit_source = 0
digits_source--
}
while (source >= base) {
source -= base
}
return source
This should take advantage of your "digits" of the large number.
Edit: For simplicity, I am assuming that a single digit of you array can contain (numerically speaking) two digits. If it cannot, then the code would become quite tricky because you cannot do second_digit_source += first_digit_source * LargeNum.base
Edit:
Regarding an example operation (base = 10000)
{65,0000,0099} % {32,0001}
As 65 is > 32, then proceed to do:
65 - 32 = 33
0 - 1 = -1
Then we have {33, -1, 99} % {32, 1}. Proceed again
33 - 32 = 1
-1 - 1 = -2
We have {1, -2, 99} % {32, 1}. Because 32 > 1, the we join the two first digits of the source and we have {1*1000 - 2, 99} % {32, 1}. Now we can go into the simple while, simply by doing the minus operation. The while does a full comparison of source >= base because we cannot afford to have negative digits. However, during the first part of the algorithm we can because we are guaranteeing that the combination of the two first digits will be positive.

Skipping empty lines in Fortran

I'm working with a fortran code, where my input file looks something like this:
...
Binning n: 4, "Si2-Events", Event #: 12, Primary(s) weight 1.0000E+00
Number of hit cells: 3
488534 4.23038400E-05 489533 1.50734719E-04 489534 5.79968946E-05
Binning n: 4, "Si2-Events", Event #: 13, Primary(s) weight 1.0000E+00
Number of hit cells: 2
477500 3.04398331E-04 478500 1.13192732E-06
Binning n: 4, "Si2-Events", Event #: 14, Primary(s) weight 1.0000E+00
Number of hit cells: 2
512496 1.32522946E-05 513496 2.86743394E-04
Binning n: 4, "Si2-Events", Event #: 15, Primary(s) weight 1.0000E+00
Number of hit cells: 2
476539 1.95245666E-04 476540 2.37216373E-05
Binning n: 4, "Si2-Events", Event #: 16, Primary(s) weight 1.0000E+00
Number of hit cells: 9
502533 1.26090490E-05 502534 1.00212252E-04 503527 3.07000097E-04 503528 9.53662311E-06 503529 9.42530642E-06 503530 1.07992764E-05 503531 1.26466557E-05 503532 1.68176994E-05 503533 1.18242851E-05
...
In other words, I have a file with many many lines, each displaying a cell number and energy in the third row, e.g.
488534 4.23038400E-05 489533 1.50734719E-04 489534 5.79968946E-05
I want to write a fortran code that reads only this line, and writes to an output file the cell number and energy in two colums, something like
Line 1
Cells 488534
489533
489534
Energy
4.23038400E-05
1.50734719E-04
5.79968946E-05
Line 2
Cells 477500
478500
Energy 3.04398331E-04
1.13192732E-06
etc...
The problem is that the number of cells varies from line to line.
How can I make it skip to the next line when it has read all the values?
Here is a little bit of the code I tested out:
open (unit=7, file="Si1.txt", action="read", access="sequential")
open (unit=8, file="output.txt", action="write")
do i = 1, 900
read (7,*) line1
read (7,*) line2
read (7,*) cell1, energy1, cell2, energy2
write(8,*) "Run = ", i, "and cells = ", cell1, cell2, "and energy = ", energy1, energy2
end do
Problem is that this only worked as long as there was two or more values in that row, and not if it was less than two.
I'm a bit lost (and possibly a noob here), but any suggestions on how to make this work?
You're currently ignoring the useful information on the 2nd line of each block, ie the number of cell number/energy pairs to be found on the 3rd line of the block. So get that information.
Replace your
read(7,*) line2
by a statement such as
read(7,'(a32,i)') words, num_cells
I write 'such as' because I haven't counted how many characters to read into the words variable (which you will have declared as character(len=32) :: words or similar), you'll have to do that for yourself. Following execution of this statement the integer variable num_cells will have the number of cell pairs to read from the next line. Replace your
read (7,*) cell1, energy1, cell2, energy2
with
do ix = 1, num_cells
read (7,fmt=*, advance='no') cell(ix), energy(ix)
end do
read (7, '()', advance = ’yes’)
The advance=no argument tells the processor not to move to the next line in the input file after reading the cell/energy pair. The line at the end of the loop, on the other hand, tells the processor to move to the next line.
Obviously (?) I haven't written you a complete solution but you should be able to take it the rest of the way. And I haven't tested this for you, so there may well be minor errors with the syntax.