I'm trying to write a program that generates a crossword grid, so I'm using the ncurses library because I just need a simple interface to display the grid, the problem is when I use box() function with ACS_VLINE and ACS_HLINE, it doesn't work; it writes 'q' and 'x' instead of the box lines. It worked at the beginning but suddenly it stopped working; I don't know why.
I'm simply initializing ncurses with initscr() and noecho().
Here's the part of the code where I draw the box:
int crossword(char ***grid, WINDOW **win, WINDOW ****c, int x, int y)
{
int i;
int j;
int ch;
t_word_list *wrdlist;
clear();
(void)x;
(void)y;
if (!(wrdlist = get_words("data/words.list")))
return (-1);
box(*win, ACS_VLINE, ACS_HLINE);
i = -1;
while ((*c)[++i])
{
j = -1;
while ((*c)[i][++j])
mvwaddch((*c)[i][j], 0, 0, (*grid)[i][j]);
}
wrefresh(stdscr);
while ((ch = getch()))
if (ch == 27)
{
nodelay(stdscr, TRUE);
ch = getch();
nodelay(stdscr, FALSE);
if (ch < 0)
break ;
}
return (endwin());
}
Output:
lqqqqqqqqqqqqqqqqqqqqqk
x 0 0 0 0 0 0 0 0 0 0 x
x 0 0 0 0 0 0 0 0 0 0 x
x 0 0 0 0 0 0 0 0 0 0 x
x 0 0 0 0 0 0 0 0 0 0 x
x 0 0 0 0 0 0 0 0 0 0 x
x 0 0 0 0 0 0 0 0 0 0 x
x 0 0 0 0 0 0 0 0 0 0 x
x 0 0 0 0 0 0 0 0 0 0 x
x 0 0 0 0 0 0 0 0 0 0 x
x 0 0 0 0 0 0 0 0 0 0 x
mqqqqqqqqqqqqqqqqqqqqqj
EDIT: I recreated the problem with minimal code:
#include <curses.h>
int main(void)
{
WINDOW *win;
initscr();
win = subwin(stdscr, 10, 10, 1, 1);
box(win, ACS_VLINE, ACS_HLINE);
wrefresh(stdscr);
getch();
return (0);
}
Output:
lqqqqqqqqk
x x
x x
x x
x x
x x
x x
x x
x x
mqqqqqqqqj
The flags I use for compilation: gcc main.c -lcurses
Converting parts of comments into an answer.
What did you change between when it worked and when it stopped working? … Can you recreate the steps you would have used while creating the working version in a new MCVE (Minimal, Complete, Verifiable Example
— or MRE or whatever name SO now uses)
or an
SSCCE (Short, Self-Contained, Correct Example).
This would allow you to find out what breaks the working code with the bare minimum of code?
… I just edited my atoi function that I just use in the main for the sizeX and sizeY; I didn't touch anything else and it suddenly stopped working. I tried to undo what I did after it wasn't working and it still doesn't work.
So you changed something else as well, whether or not you realized it. It's possible that the terminal settings are screwed up — funnier things have been known. Have you tried creating a new terminal window and trying again in the new window?
Oh yes! It was the terminal! It worked after a 'reset', thank you! I don't know why I didn't think about that earlier.
Until curses (ncurses) programs have proved themselves reliable, always consider the possibility that a flawed version of the program under test messed up the terminal settings. Use stty -g to generate a string when the terminal is working properly (when first created, before you run your program). You can then use that string to reset the terminal to the same known state (assuming it is stty settings that are the problem). Sometimes, a new terminal window is necessary even so.
good_stty=$(stty -g)
…testing program under development…
stty "$good_stty"
Sometimes, you may need to type control-J and then stty "$good_stty" (or stty sane) and another control-J because the line ending settings have been modified and not restored correctly.
The problem may be the console encoding for your console. Also if you access from putty you must follow the following steps.
Verif console configuration is UTF
dpkg-reconfigure console-setup
Related
novice programmer here trying to get better at C, so i began doing code problems on a website called codeforces. However i seem to be stuck, i have written code that appears to work in practice but the website does not accept it as right.
the problem :
Theatre Square in the capital city of Berland has a rectangular shape with the size n × m meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size a × a. What is the least number of flagstones needed to pave the Square? It's allowed to cover the surface larger than the Theatre Square, but the Square has to be covered. It's not allowed to break the flagstones. The sides of flagstones should be parallel to the sides of the Square.1
Source :
https://codeforces.com/problemset/problem/1/A
I did have a hard time completely understanding the math behind the problem and used this source's answer from a user named "Joshua Pan" to better understand the problem
Source :
https://www.quora.com/How-do-I-solve-the-problem-Theatre-Square-on-Codeforces
This is my code :
#include<stdio.h>
#include<math.h>
int main(void)
{
double n,m,a;
scanf("%lf %lf %lf", &n,&m,&a);
printf("%1.lf\n", ceil(n/a)*ceil(m/a));
return 0;
}
I compiled it using "gcc TheatreSquare.c -lm"
When given the sample input 6,6,4 my code produces the correct output 4, however the website does not accept this code as correct, i could be wrong but maybe im using format specifiers incorrectly?
Thanks in advance.
Typical double (IEEE754 64-bit floating point) doesn't have enough accuracy for the problem.
For example, for input
999999999 999999999 1
Your program may give output
999999998000000000
While the actual answer is
999999998000000001
To avoid this, you shouldn't use floating point data type.
You can add #include <inttypes.h> and use 64-bit integer type int64_t for this calculation.
"%" SCNd64 is for reading and "%" PRId64 is for writing int64_t.
cell(n/a) on integers can be done by (n + a - 1) / a.
You can solve this using integers.
#include <stdio.h>
int main()
{
unsigned long n, m, a = 1;
unsigned long na, ma, res = 0;
scanf("%lu %lu %lu", &n, &m, &a);
na = n/a;
if (n%a != 0)
na++;
ma = m/a;
if (m%a != 0)
ma++;
res = na * ma;
printf("%lu", res);
return 0;
}
This code will fail in the Codeforce platform, on the test 9 (see below). But if you compile it and run it locally with the same inputs, the result is correct.
> Test: #9, time: 15 ms., memory: 3608 KB, exit code: 0, checker exit code: 1, verdict: WRONG_ANSWER
> Input 1000000000 1000000000 1
> Output 2808348672 Answer 1000000000000000000
> Checker Log wrong answer 1st numbers differ - expected: '1000000000000000000', found: '2808348672'
EDIT:
The problem described above is due to the fact that I'm running a 64-bit machine and the online compiler is probably using 32-bit. The unsigned long variables overflow.
The following code will pass all the tests.
#include <stdio.h>
int main()
{
unsigned long long n, m, a = 1;
unsigned long long na, ma, res = 0;
scanf("%llu %llu %llu", &n, &m, &a);
na = n/a;
if (n%a != 0)
na++;
ma = m/a;
if (m%a != 0)
ma++;
res = na * ma;
printf("%llu", res);
return 0;
}
Use the code below it will pass all the test cases we need to use long long for all variable declaration to get output.
#include <stdio.h>
#include <math.h>
int main(){
long long n,m,a,l,b;
scanf("%lld%lld%lld",&n,&m,&a);
l= n/a;
if(n%a != 0)
l++;
b= m/a;
if(m%a != 0)
b++;
printf("%lld",l*b);
return 0;
}
Theatre Square in the capital city of Berland has a rectangular shape with the size n × m meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size a × a.
import java.util.Scanner;
public class theatre_square {
public static void main(String[] args) {
long a,b,c;
Scanner s = new Scanner(System.in);
a = s.nextLong();
b = s.nextLong();
c = s.nextLong();
long result = 0;
if(a>=c){
if(a%c==0)
result = a/c;
else
result = a/c + 1; // some part is left
}else{ // area of rectangle < area of square then 1 square is required
result = 1;
}
if(b>=c){
if(b%c==0)
result *= b/c;
else
result *= b/c + 1;
}
System.out.println(result);
}
}
case 1 . 2 2 3 => 1
length = 2 so 2 < 3 then only 1 square required <br>
breadth = 2 so 2 < 3 then covered in previous square so output 1
intial view
0 0
0 0
after adding 1 square ( r= remaining or left)
1 1 r
1 1 r
r r r
case 2 . 6 6 4 => 4
length = 2 so 6 > 4 then only 2 square required <br>
breadth = 2 so 6 > 4 then 2 square required
intial view
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
after adding 4 square ( r= remaining or left)
1 1 1 1 2 2 r r
1 1 1 1 2 2 r r
1 1 1 1 2 2 r r
1 1 1 1 2 2 r r
3 3 3 3 4 4 r r
3 3 3 3 4 4 r r
r r r r r r r r
r r r r r r r r
You can try the following:
import math
x,y,z=list(map(float, input().split()))
print(math.ceil(x/z)*math.ceil(y/z))
Here is the code for the above problem in CPP. We need a long long variable to store the value as we may have a very large value.
GUIDANCE ABOUT THE QUESTION:
As we are given the hint of edges so we have to cover them nicely. For a rectangle, we know that we have a length and height which is shown as n * m and the square is of a*a so we will try to cover the length first and decide its squares first
for that, we divide it by k, and then if any remainder exists we will add one more and the same for height.
I hope it will help you
HERE IS THE CODE
#include<iostream>
using namespace std;
int main()
{
long long n,m,k,l=0,o=0;
cin>>n>>m>>k;
l=n/k;
if(n%k!=0)
{
l++;
}
o=m/k;
if(m%k!=0)
{
o++;
}
cout<<l*o;
}
I wrote a function that sets every number of a line in a .txt file to zero and clears the other file.
I originally wrote this logic in main and it worked perfectly fine. But now I need to make a menu for my program, so I need to put this logic into a function.
That's where the things go wrong. Once I move the logic into a function, it doesn't set the numbers to zero, it just clears the file, and I didn't changed anything.
Expected result:
Workers.txt : Adam Washington Monday Friday --(use function)--> {clear}
days.txt: 1 0 0 0 1 0 0 --(use function)--> 0 0 0 0 0 0 0
Actual result:
It's clear in both files.
void ResetOwnData(){
printf("--------------------------------------------------------------------------\n");
FILE* freset = fopen ("workers.txt", "w");
close(freset);
FILE* freset2 = fopen ("days.txt", "w");
for(int i = 0; i < 7; i++){
fprintf(freset2,"%d ",i+1);
}
fprintf(freset2,"\n");
for(int i = 0; i < 7; i++){
fprintf(freset2,"%d ",0);
}
close(freset2);
printf("Everything get reset!\n");
printf("--------------------------------------------------------------------------\n");
}
There are two main things that appear to be incorrect.
You are using close rather than fclose. fclose is used with file streams (like you are using)
Your function is overwriting the one line that you want (e.g., 0 0 0 0 0 0 0) with two lines because you have two for loops
Here is a CodingGround link to the corrections that I believe you are seeking.
You should add some error checking to ensure that you truly have opened the file and that you release any allocated memory
I am doing a socket programming for hospital chanelling.
I am trying to read a text file like this
1 Kavi card 0 0 0
2 Anparasanesan gene 0 0 0
3 Thilak card 0 0 0
4 Akilanesan immu 0 0 0
5 Aravinthanesan derm 0 0 0
6 Akalya derm 0 0 0
7 Vishvapriya derm 0 0 0
8 Kavinga immu 0 0 0
9 Anjalie andr 0 0 0
10 Tom andr 0 0 0
but when i am reading that file it gives me the output as :
1 Kavi cardgenecardimmudermdermdermimmuandrandr
2 Anparasanesan genecardimmudermdermdermimmuandrandr
3 Thilak cardimmudermdermdermimmuandrandr
4 Akilanesan immudermdermdermimmuandrandr
5 Aravinthanesan dermdermdermimmuandrandr
6 Akalya dermdermimmuandrandr
7 Vishvapriya dermimmuandrandr
8 Kavinga immuandrandr
9 Anjalie andrandr
10 Tom andr
Here is my code segment
char line[MAXCHAR];
int x = 0;
while (fgets(line, sizeof(line), fp)){
sscanf(line,"%d\t%s\t%s\t%d\t%d\t%d",&dno,&dname,&dspl,&ti1,&ti2,&ti3);
id[x]=dno;
strncpy(name[x], dname, 50);
strncpy(spl[x], dspl, 4);
times[x][0]=ti1;
times[x][1]=ti2;
times[x][2]=ti3;
x++;
}
int z=0;
for(z=0;z<10;z++)
{
snprintf(line, sizeof(line),"%d\t%s\t%s\n",id[z],name[z],spl[z]);
n = strlen(line);
Writen(sockfd,line,n);
}
Let us look at one of the problems.
evil strncpy
Code is using strncpy with a magic number 4. This does not insure spl[x] is a string as the characters may lack a final null character.
strncpy(spl[x], dspl, 4); // Avoid code like this
Later code tries to print a string with "%s" and spl[z] and gets "cardgene..." rather than the expected "card". When spl[z] is not a string, the result is undefined behavior (UB) - anything may happen.
// Alternative: could limit output with
snprintf(line, sizeof(line),"%.*s\n",(int) (sizeof spl[z]), spl[z]);
How to fix?
Do not use sscanf(line,"%s",&dspl); as it lacks either a width limit, or it is not known that dspl is about the same size of line. I'd expect
char dspl[4+1];
sscanf(line,"%4s", dspl);
Better to insure the source string and destination array are sufficient than use strncpy() without tests.
char spl[X_N][4+1];
char dspl[sizeof spl[0]];
// strncpy(spl[x], dspl, 4);
strcpy(spl[x], dspl);
Others fixes include make certain the sscanf() completed as expected. A simple approach uses " %n" to record the scan offset, if it got that far and then look for extra garbage. Unnecessary "\t" removed.
// Insure dname is at least 50+1, dspl is 4+1 or as big as the line
char dname[sizeof line];
char dspl[sizeof line];
// sscanf(line,"%d\t%s\t%s\t%d\t%d\t%d",&dno,&dname,&dspl,&ti1,&ti2,&ti3);
int n = 0;
sscanf(line,"%d%50s%4s%d%d%d %n",&dno,dname,dspl,&ti1,&ti2,&ti3, &n);
if (n==0 || line[n]) {
puts("Bad Input"); // Handle bad input in some fashion
exit(RETURN_FAILURE);
}
I have an array like this (0,0 is bottom left):
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0 0
0 0 1 0 1 0 1 0 0
0 0 1 1 1 1 1 1 1
1 0 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1
My goal is to get the index of the higher line who is not completely set to 0. For this I made the code below (which works fine):
max=0;
for (i=0 ; i<width ; ++i) {
for (j=max ; j<height ; ++j) {
if (array[i*height+j]!=0) {
max=j;
}
}
}
For the second loop I initialize j to max, because the global maximum cannot be less than a local maximum. And this way I can reduce the number of tests.
The I tried to parallelize it with OpenMp. My code is now:
max=0;
#pragma omp parallel for default(none) \
shared(spec, width, height) \
collapse(2) \
reduction(max:max)
for (i=0 ; i<width ; ++i) {
for (j=max ; j<height ; ++j) {
if (array[i*height+j]!=0) {
max=j;
}
}
}
Which leads to a segmentation fault. In order to make it works, I changed j=max to j=0. So the problem seems to come from the max variable.
I don't understand why, because with the reduction this variable should be private (or lastprivate) between each threads. So why does it make it crash ? And how can I use my "optimization" with OpenMP ?
First of all, the user High Performance Mark is right in his comment. You shouldn't be using collapse if your loop index values depend on the value of a calculation. In your example, "j" depends on "max", which will produce an incorrect result. However, this is not the cause of your segmentation fault.
I would suggest you to debug your example so that you can find the source of the crash; "max" is being initialized with a negative number by default, which causes "j" to also have said value. Thus, when trying to access array[i*height+(-2147483648)], you get a segmentation fault.
This happens because OpenMP specifies an initial value for each reduction operator. In the case of the max operator, you can find the following description in the specification of OpenMP 3.1:
max Least representable value in the reduction list item type
In our case, that means that each thread will have at the start of the parallel region a private copy of the max variable holding the value of the lowest number that can be stored as an int (usually -2147483648).
I've written a very rudimentary workaround for your example. I removed the collapse clause and I'm initializing the max variable manually at the start of the parallel region:
#pragma omp parallel default(none) private(j) shared(array, width, height) reduction(max:max)
{
// Explicit initialization
max = 0;
#pragma omp for
for (i=0 ; i<width ; ++i) {
for (j=max ; j<height ; ++j) {
if (array[i*height+j]!=0) {
max=j;
}
}
}
}
As an extra remark, you shouldn't need to use max=j everytime. You could try to check when the first 0 is found and use the previous position.
Hope it helps
#include <avr/io.h>
#include <util/delay.h>
#define BAUDRATE 115200
#define BAUD_PRESCALLER (((F_CPU / (BAUDRATE * 16UL))) - 1)
//Declaration of our functions
void USART_init(void);
unsigned char USART_receive(void);
void USART_send( unsigned char data);
int main(void){
USART_init(); //Call the USART initialization code
while(1){ //Infinite loop
USART_send('A');
_delay_ms(1000); //Delay for 5 seconds so it will re-send the string every 5 seconds
}
return 0;
}
void USART_init(void){
UBRR1H = (uint8_t)(BAUD_PRESCALLER>>8);
UBRR1L = (uint8_t)(BAUD_PRESCALLER);
UCSR1B = (1<<RXEN1)|(1<<TXEN1);
UCSR1C = (3<<UCSZ10);
}
unsigned char USART_receive(void){
while(!(UCSR1A & (1<<RXC1)));
return UDR1;
}
void USART_send( unsigned char data){
while(!(UCSR1A & (1<<UDRE1)));
UDR1 = data;
}
minicom on Ubuntu set to 115200 8N1
I am using Elegoo ATMEGA2560, TX1 and RX1 and GND pins from communication port. https://github.com/enthusiasticgeek/Elegoo_Mega_2560
I intend to send 'A' from ATMEGA and expect to see it on minicom on PC. But I am receiving ' _ ' on minicom. I changed the minicom setting to 115200 7N1 and still receiving ' _ '. Then I changed to 115200 6N1 then I get a different binary character. I tried changing minicom settings but to no avail. Any idea what I am going wrong?
This is what I am seeing when I send different characters.
Expected (AVR sends) ASCII 0x56 [01010110] (V)
Observed (PC receives) ASCII 0x2A [00101010] (*)
Expected (AVR sends) ASCII 0x41 [01000001] (A)
Observed (PC receives) ASCII 0x5F [01011111] (_)
Expected (AVR sends) ASCII 0x42 [01000010] (B)
Observed (PC receives) ASCII 0x2F [00101111] (/)
Expected (AVR sends) ASCII 0x55 [01010101] (U)
Observed (PC receives) ASCII 0x55 [01010101] (U)
Here are my fuse settings https://github.com/enthusiasticgeek/Elegoo_Mega_2560/blob/master/avrdude.conf
memory "lfuse"
size = 1;
write = "1 0 1 0 1 1 0 0 1 0 1 0 0 0 0 0",
"x x x x x x x x i i i i i i i i";
read = "0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0",
"x x x x x x x x o o o o o o o o";
min_write_delay = 9000;
max_write_delay = 9000;
;
memory "hfuse"
size = 1;
write = "1 0 1 0 1 1 0 0 1 0 1 0 1 0 0 0",
"x x x x x x x x i i i i i i i i";
read = "0 1 0 1 1 0 0 0 0 0 0 0 1 0 0 0",
"x x x x x x x x o o o o o o o o";
min_write_delay = 9000;
max_write_delay = 9000;
;
memory "efuse"
size = 1;
write = "1 0 1 0 1 1 0 0 1 0 1 0 0 1 0 0",
"x x x x x x x x x x x x x i i i";
read = "0 1 0 1 0 0 0 0 0 0 0 0 1 0 0 0",
"x x x x x x x x o o o o o o o o";
min_write_delay = 9000;
max_write_delay = 9000;
;
Here is what happens when I load the fw
avr-gcc -Os -DF_CPU=16000000UL -mmcu=atmega2560 -c -o test.o test.c
avr-gcc -mmcu=atmega2560 test.o -o test
#EEPROM
#avr-objcopy -O ihex -R .eeprom test test.hex
#FLASH
avr-objcopy -O ihex -R .flash test test.hex
sudo avrdude -c wiring -p m2560 -P /dev/ttyACM0 -b 115200 -V -U flash:w:test.hex -D
avrdude: AVR device initialized and ready to accept instructions
Reading | ################################################## | 100% 0.01s
avrdude: Device signature = 0x1e9801 (probably m2560)
avrdude: reading input file "test.hex"
avrdude: input file test.hex auto detected as Intel Hex
avrdude: writing flash (366 bytes):
Writing | ################################################## | 100% 0.08s
avrdude: 366 bytes of flash written
avrdude: safemode: Fuses OK (E:FD, H:D8, L:FF)
avrdude done. Thank you.
Note: I am using CP-US-03 serial adapter which I assume would have FTD232 chip. I also get the same results from the Arduino sketch using the code
void setup() {
// initialize both serial ports:
Serial1.begin(115200);
}
void loop() {
// read from port 1, send to port 0:
//if (Serial1.available()) {
// int inByte = Serial1.read();
// Serial.write(inByte);
//
}
// read from port 0, send to port 1:
//if (Serial1.available()) {
int inByte = 0x41;//Serial.read();
Serial1.write(inByte);
delay(1000);
//}
}
Hence, now I have started to look if this is TTL or logic level conversion issue.
Turns out the problem was nothing related to my code. I ended up ordering the following USB 2.0 to TTL UART 6PIN CP2102 Module Serial Converter and everything was hunky dory.
https://www.amazon.com/gp/product/B01LRVQIFQ/ref=oh_aui_detailpage_o01_s00?ie=UTF8&psc=1
The regular USB to serial CP-US-03 wouldn't work.