check50 not working properly - greedy

check50 gives weird output please help
#include <cs50.h>
#include <stdio.h>
#include <math.h>
int main(void)
{
int amount,n25,n10,n5,n1,total;
int rem;
float gamount;
printf("O hai!");
do{
printf("How much change is owed?\n");
gamount = GetFloat();
}while(gamount<0);
amount = (int) round(gamount *100.00);
rem = round(amount);
n25 =(int) rem /25;
rem = rem %25;
n10 = rem /10;
rem = rem%10;
n5 = rem /5;
rem = rem%5;
n1 = rem /1;
rem = rem%1;
total = n25+n10+n5+n1;
printf("%d",total);
return 0;
}
check50 output:
*~/workspace/pset1/ $ check50 2015.fall.pset1.greedy greedy.c
:) greedy.c exists
:) greedy.c compiles
:( input of 0.41 yields output of 4
\ expected output, but not "4"
:( input of 0.01 yields output of 1
\ expected output, but not "1"
:( input of 0.15 yields output of 2
\ expected output, but not "2"
:( input of 1.6 yields output of 7
\ expected output, but not "7"
:( input of 23 yields output of 92
\ expected output, but not "92"
:( input of 4.2 yields output of 18
\ expected output, but not "18"
:) rejects a negative input like -.1
:) rejects a non-numeric input of "foo"
:) rejects a non-numeric input of ""
https://sandbox.cs50.net/checks/f9c8501c99a848df82d8bd0df231a6ea
i tried changing the printf("%d",total) statement to printf(total) but it results in compile error
compiling using
clang -ggdb3 -O0 -std=c11 -Wall -Werror -Wshadow greedy.c -lcs50 -lm -o greedy

Instead of this:
printf("%d",total);
try using this:
printf("%d\n",total);

Related

Why is GraalVM + native-image slower than GraalVM alone on a while loop?

Just for fun, I'm trying to compare gcc (9.4.0), OpenJDK (11.0.12), GraalVM (22.3.r19) and GraalVM + native-image (22.3.r19) performances on a "while loop n++" use case (see programs below).
Bottom line on Linux is (see results below): native-image is slower than all other options.
So I'm wondering: am I missing something (magic command-line option)? Or is it just life that native-image is slower on this particular program (and that's fine)?
Count.java
public class Count {
public static void main(String[] args) {
int n = 0;
int inc = Math.random() >= 0 ? 1 : 0; // to prevent the optimizer from removing the loop
while (n < 1000000000) {
n += inc;
}
System.out.println(n);
}
}
count.c
#include <time.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
int n = 0;
srand(time(NULL));
int inc = rand() >= 0 ? 1 : 0; // to prevent the optimizer from removing the loop
while (n < 1000000000) {
n += inc;
}
}
gcc:
me#laptop:~/dev/java-count-graalvm$ gcc -O2 -s -DNDEBUG count.c -o count
me#laptop:~/dev/java-count-graalvm$ time ./count
real 0m0,261s
user 0m0,261s
sys 0m0,000s
OpenJDK 11:
me#laptop:~/dev/java-count-graalvm$ time java -classpath target/classes Count
1000000000
real 0m0,632s
user 0m0,612s
sys 0m0,030s
GraalVM:
me#laptop:~/dev/java-count-graalvm$ time java -classpath target/classes Count
1000000000
real 0m0,326s
user 0m0,362s
sys 0m0,013s
GraalVM native-image:
me#laptop:~/dev/java-count-graalvm$ native-image -cp target/classes Count
me#laptop:~/dev/java-count-graalvm$ time ./count
1000000000
real 0m1,283s
user 0m1,271s
sys 0m0,013s
For the sake of sanity, I commented-out the while loop and native image is returning in 3 milliseconds:
bruno#hearne:~/dev/java-count-graalvm$ time ./count
0
real 0m0,003s
user 0m0,000s
sys 0m0,003s
So I would say that the penalty is coming from the while loop and nothing else.

merge branch coverage of two or more runs with lcov

How can I merge branch coverage of two or more runs?
Is any tool or lcov command exist?
Let's say that I have two test runs and would like to see summary branch coverage
gcc -O0 --coverage main.c -o test-coverage
test-coverage param1
lcov --capture --rc lcov_branch_coverage=1 --directory . --config-file ./lcovrc --output coverage1.info
test-coverage param2
lcov --capture --rc lcov_branch_coverage=1 --directory . --config-file ./lcovrc --output coverage2.info
Looks like it is needed to parse and merge files coverage1.info and coverage2.info
Is any solution exist already or I have to develop my own?
Developed the python script, which merges a list of files (line coverage is not accurate here)
def merge(files):
if (len(files) == 0):
return 0
covs = [open(f, "r").readlines() for f in files]
result = []
branch_number = 0
for i, line in enumerate(covs[0]):
if ('end_of_record' in line):
result.append(line)
else:
tmp = line.split(':')
tag = tmp[0]
data = tmp[1]
if (tag == 'BRDA'):
c = data.split(',')[-1]
if (c == '1\n'):
branch_number += 1
result.append(line)
else:
flag = 0
for j in covs[1:]:
if j[i].split(',')[-1] == '1\n':
branch_number += 1
result.append(j[i])
flag = 1
break
if flag == 0:
result.append(line)
elif (tag == 'BRH'):
result.append(tag + ":" + str(branch_number)+'\n')
else:
result.append(line)
return result

the performance of erlang numeric calculation

C version:
#include <stdio.h>
#include <stdlib.h>
unsigned int test(unsigned int n_count) {
unsigned int c = 1;
unsigned int i;
for (i=0; i< n_count;i++) {
c += 2 * 34 + 1;
c /= 2;
c *= 39;
}
return c;
}
int main(int argc, char* argv[])
{
printf("%u\n", test(atoi(argv[1])));
}
Result:
$ gcc p2.c
$ time ./a.out 100000000
563970997
real 0m0.865s
user 0m0.864s
sys 0m0.004s
erlang version:
-module(test2).
-export([main/1]).
-mode(compile).
calc(Cnt, Total) when Cnt > 0 ->
if Total >= 4294967296 -> Total2 = Total rem 4294967296;
true -> Total2 = Total end,
calc(Cnt - 1, trunc((Total2 + 2 * 34 + 1) / 2) * 39);
calc(0, Total)->
if Total >= 4294967296 -> Total2 = Total rem 4294967296;
true -> Total2 = Total end,
io:format("~p ~n", [Total2]),
ok.
main([A])->
Cnt = list_to_integer(A),
calc(Cnt, 1).
Result:
$ erlc +native +"{hipe, [to_llvm]}" test2.erl
$ time escript test2.beam 100000000
563970997
real 0m4.940s
user 0m4.892s
sys 0m0.056s
$ erlc +native test2.erl
$ time escript test2.beam 100000000
563970997
real 0m5.381s
user 0m5.320s
sys 0m0.064s
$ erlc test2.erl
$ time escript test2.beam 100000000
563970997
real 0m9.868s
user 0m9.808s
sys 0m0.056s
How to improve the performance of erlang version?
In erlang, I have to simulate the integer overflow case, is there better way?
And even with hipe, the performance is far from C.
Edit:
Python version:
def test(n_count):
c = 1
for i in xrange(n_count):
c += 2 * 34 + 1
c /= 2
c *= 39
if c >= 4294967296:
c = c % 4294967296
return c
print test(100000000)
Result:
$ time python p2.py
563970997
real 0m17.813s
user 0m17.808s
sys 0m0.008s
$ time pypy p2.py
563970997
real 0m1.852s
user 0m0.508s
sys 0m0.128s
I think the following link may be especially helpful, you'll be able to 'bake' your C code into your Erlang application:
http://www.erlang.org/doc/tutorial/c_port.html
Erlang really has not good in digit-rolling tasks. It good, if you want take bytes and send them.
Usual serious Erlang development cycle is including final optimization, when you rewriting some bottleneck modules to native.
Yes, Erlang looks like good calc (and projects like Wings3D showing that), but maybe you must choose another tool?

How to solve a Zlib adler32 rolling checksum problem?

I am using adler32 function from zlib to calculate the weak checksum of a chunk of memory x (4096 in length). Everything is fine, but now I would like to perform the rolling checksum if the chunks from different file do not match. However, I am not sure how to write a function to perform that on the value returned by adler32 in zlib. So if the checksum does not match, how do I calculate rolling checksum by using original checksum, x + 1 byte and x + 4096 + 1? Basically trying to build rsync implementation.
Pysync has implemented rolling on top of zlib's Adler32 like this:
_BASE=65521 # largest prime smaller than 65536
_NMAX=5552 # largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1
_OFFS=1 # default initial s1 offset
import zlib
class adler32:
def __init__(self,data=''):
value = zlib.adler32(data,_OFFS)
self.s2, self.s1 = (value >> 16) & 0xffff, value & 0xffff
self.count=len(data)
def update(self,data):
value = zlib.adler32(data, (self.s2<<16) | self.s1)
self.s2, self.s1 = (value >> 16) & 0xffff, value & 0xffff
self.count = self.count+len(data)
def rotate(self,x1,xn):
x1,xn=ord(x1),ord(xn)
self.s1=(self.s1 - x1 + xn) % _BASE
self.s2=(self.s2 - self.count*x1 + self.s1 - _OFFS) % _BASE
def digest(self):
return (self.s2<<16) | self.s1
def copy(self):
n=adler32()
n.count,n.s1,n.s2=self.count,self.s1,self.s2
return n
But as Peter stated, rsync does not use Adler32 directly, but a faster variant of it.
Code of the rsync tool is bit hard to read, but checkout librsync. It's a completely separate project and it's much more readable. Take a look at rollsum.c and rollsum.h. There is an efficient implementation of the variant in C macros:
/* the Rollsum struct type*/
typedef struct _Rollsum {
unsigned long count; /* count of bytes included in sum */
unsigned long s1; /* s1 part of sum */
unsigned long s2; /* s2 part of sum */
} Rollsum;
#define ROLLSUM_CHAR_OFFSET 31
#define RollsumInit(sum) { \
(sum)->count=(sum)->s1=(sum)->s2=0; \
}
#define RollsumRotate(sum,out,in) { \
(sum)->s1 += (unsigned char)(in) - (unsigned char)(out); \
(sum)->s2 += (sum)->s1 - (sum)->count*((unsigned char)(out)+ROLLSUM_CHAR_OFFSET); \
}
#define RollsumRollin(sum,c) { \
(sum)->s1 += ((unsigned char)(c)+ROLLSUM_CHAR_OFFSET); \
(sum)->s2 += (sum)->s1; \
(sum)->count++; \
}
#define RollsumRollout(sum,c) { \
(sum)->s1 -= ((unsigned char)(c)+ROLLSUM_CHAR_OFFSET); \
(sum)->s2 -= (sum)->count*((unsigned char)(c)+ROLLSUM_CHAR_OFFSET); \
(sum)->count--; \
}
#define RollsumDigest(sum) (((sum)->s2 << 16) | ((sum)->s1 & 0xffff))

How to use some text processing(awk etc..) to put some character in a text file at certain lines

I have a text file which has hex values, one value on one separate line. A file has many such values one below another. I need to do some analysis of the values for which i need to but some kind of delimiter/marker say a '#' in this file before line numbers 32,47,62,77... difference between two line numbers in this patterin is 15 always.
I am trying to do it using awk. I tried few things but didnt work.
What is the command in awk to do it?
Any other solution involving some other language/script/tool is also welcome.
Thank you.
-AD
This is how you can use AWK for it,
awk 'BEGIN{ i=0; } \
{if (FNR<31) {print $0} \
else {i++; if (i%15) {print $0} else {printf "#%s\n",$0}}\
}' inputfile.txt > outputfile.txt
How it works,
BEGIN sets an iterator for counting from your starting line 32
FNR<31 starts counting from the 31st record (the next record needs a #)
input lines are called records and FNR is an AWK variable that counts them
Once we start counting, the i%15 prefixes a # on every 15th line
$0 prints the record (the line) as is
You can type all the text with white spaces skipping the trailing '\' on a single command line.
Or, you can use it as an AWK file,
# File: comment.awk
BEGIN{ i=0; }
$0 ~ {\
if (FNR<31) {print $0} \
else {\
i++; \
if (i%15) {\
print $0
}\
else {\
printf "#%s\n",$0
}\
}\
}
And run it as,
awk -f comment.awk inputfile.txt > outputfile.txt
Hope this will help you to use more AWK.
Python:
f_in = open("file.txt")
f_out = open("file_out.txt","w")
offset = 4 # 0 <= offset < 15 ; first marker after fourth line in this example
for num,line in enumerate(f_in):
if not (num-offset) % 15:
f_out.write("#\n")
f_out.write(line)
Haskell:
offset = 31;
chunk_size = 15;
main = do
{
(h, t) <- fmap (splitAt offset . lines) getContents;
mapM_ putStrLn h;
mapM_ ((putStrLn "#" >>) . mapM_ putStrLn) $
map (take chunk_size) $
takeWhile (not . null) $
iterate (drop chunk_size) t;
}

Resources