Create a Fraction array - objective-c

I have to Create a dynamic array capable of holding 2*n Fractions.
If the dynamic array cannot be allocated, prints a message and calls exit(1).
It next fills the array with reduced random Fractions whose numerator
is between 1 and 20, inclusive; and whose initial denominator
is between 2 and 20, inclusive.
I ready did the function that is going to create the fraction and reduced it. this is what I got. When I compiled and run this program it crashes I cant find out why. If I put 1 instead of 10 in the test.c It doesn't crash but it gives me a crazy fraction. If I put 7,8,or 11 in the test.c it will crash. I would appreciate if someone can help me.
FractionSumTester.c
Fraction randomFraction(int minNum, int minDenom, int max)
{
Fraction l;
Fraction m;
Fraction f;
l.numerator = randomInt(minNum, max);
l.denominator = randomInt(minDenom, max);
m = reduceFraction(l);
while (m.denominator <= 1)
{
l.numerator = randomInt(minNum, max);
l.denominator = randomInt(minDenom, max);
m = reduceFraction(l);
}
return m;
}
Fraction *createFractionArray(int n)
{
Fraction *p;
int i;
p = malloc(n * sizeof(Fraction));
if (p == NULL)
{
printf("error");
exit(1);
}
for(i=0; i < 2*n ; i++)
{
p[i] = randomFraction(1,2,20);
printf("%d/%d\n", p[i].numerator, p[i].denominator);
}
return p;
}
this is the what I am using to test this two functions.
test.c
#include "Fraction.h"
#include "FractionSumTester.h"
#include <stdio.h>
int main()
{
createFractionArray(10);
return 0;
}

In your createFractionArray() function, you malloc() space for n items. Then, in the for loop, you write 2*n items into that space... which overruns your buffer and causes the crash.

Related

Why is my C program crashing after input?

I am learning to program in C and C++.
My C program keeps crashing after input, here's the code:
\#include\<stdio.h\>
main(){
int n, i,a,sum=0;
printf("How many numbers?\\n");
scanf("%d", &n);
for(i=0;i\<n;i++){
printf("What's the %d number\\n", i+1);
scanf("%d", &a);
sum=sum+a;
}
printf("Sum is %d", sum);
}
And here's the output from my compile log
Compiler: Default compiler
Executing gcc.exe...
gcc.exe "C:\\Dev-Cpp\\Reee.c" -o "C:\\Dev-Cpp\\Reee.exe" -I"C:\\Dev-Cpp\\include" -L"C:\\Dev-Cpp\\lib"
Execution terminated
Compilation successful
There is 0 errors and 0 warnings.
If someone knows how to fix it I would be really thankful.
I tried to make a program that sums up all the numbers in a row. I expected a sum output but the program crashed after input. The program crashes after I input the last number in a row, where it should sum up all of them and output the sum.
I copied this program, added "void" to the main function
and changed the include statement like this ⬇️
everything worked just fine
#include <stdio.h>
void main()
{
int n, i, a, sum = 0;
printf("How many numbers?\\n");
scanf("%d", &n);
for (i = 0; i < n; i++)
{
printf("What's the %d number\\n", i + 1);
scanf("%d", &a);
sum = sum + a;
}
printf("Sum is %d", sum);
}
//output:
How many numbers?\n2
What's the 1 number\n4
What's the 2 number\n5
Sum is 9
you should use only one \ when you print somthing.

2-d Binary Search with Time Complexity

I don't understand how the following program that finds all negative numbers in a 2-d array is using binary search?
I thought binary search worked by taking a sorted list/array, going to middle, and checking if middle value was >, <, or == to the searched for value, and repeating that in the half containing the searched for value. This program checks iteratively for each row in the program (starting at top right of array) if that value is less than 0, and moves down next row if it is.
Also, why does this program what complexity O(row+col)? I thought binary search algorithms have complexity O(log(n)).
#include <bits/stdc++.h>
#include <algorithm>
using namespace std;
class Solution {
public:
int countNegatives(vector<vector<int>>& grid) {
int row = grid.size()-1;
int col = grid[0].size()-1;
int i = 0; int j = col; int count = 0;
while ((i <= row) && (j>=0)){
if (grid[i][j] < 0){
count++;
j--;
if (j < 0){
i++;
j = col;
}
}
else{
i++;
j = col;
}
}
return count;
}
};

Simulating a card game. degenerate suits

This might be a bit cryptic title but I have a very specific problem. First my current setup
Namely in my card simulator I deal 32 cards to 4 players in sets of 8. So 8 cards per player.
With the 4 standard suits (spades, harts , etc)
My current implementation cycles threw all combinations of 8 out of 32
witch gives me a large number of possibilities.
Namely the first player can have 10518300 different hands be dealt.
The second can then be dealt 735471 different hands.
The third player then 12870 different hands.
and finally the fourth can have only 1
giving me a grand total of 9.9561092e+16 different unique ways to deal a deck of 32 cards to 4 players. if the order of cards doesn’t matter.
On a 4 Ghz processor even with 1 tick per possibility it would take me half a year.
However I would like to simplify this dealing of cards by making the exchange of diamonds, harts and spades. Meaning that dealing of 8 harts to player 1 is equivalent to dealing 8 spades. (note that this doesn’t apply to clubs)
I am looking for a way to generate this. Because this will cut down the possibilities of the first hand by at least a factor of 6. My current implementation is in c++.
But feel free to answer in a different Languages
/** http://stackoverflow.com/a/9331125 */
unsigned cjasMain::nChoosek( unsigned n, unsigned k )
{
//assert(k < n);
if (k > n) return 0;
if (k * 2 > n) k = n-k;
if (k == 0) return 1;
int result = n;
for( int i = 2; i <= k; ++i ) {
result *= (n-i+1);
result /= i;
}
return result;
}
/** [combination c n p x]
* get the [x]th lexicographically ordered set of [r] elements in [n]
* output is in [c], and should be sizeof(int)*[r]
* http://stackoverflow.com/a/794 */
void cjasMain::Combination(int8_t* c,unsigned n,unsigned r, unsigned x){
++x;
assert(x>0);
int i,p,k = 0;
for(i=0;i<r-1;i++){
c[i] = (i != 0) ? c[i-1] : 0;
do {
c[i]++;
p = nChoosek(n-c[i],r-(i+1));
k = k + p;
} while(k < x);
k = k - p;
}
c[r-1] = c[r-2] + x - k;
}
/**http://stackoverflow.com/a/9430993 */
template <unsigned n,std::size_t r>
void cjasMain::Combinations()
{
static_assert(n>=r,"error n needs to be larger then r");
std::vector<bool> v(n);
std::fill(v.begin() + r, v.end(), true);
do
{
for (int i = 0; i < n; ++i)
{
if (!v[i])
{
COUT << (i+1) << " ";
}
}
static int j=0;
COUT <<'\t'<< j++<< "\n";
}
while (std::next_permutation(v.begin(), v.end()));
return;
}
A requirement is that from lexicographical number I can get back the original array.
Even the slightest optimization can help my monto carol simulation I hope.

Blas DGEMV input error

I'm having trouble figuring out why a piece of blas call is throwing n error. The problem call is the last blas call. The code compiles without issue and runs fine up until this call then fails with the following message.
** ACML error: on entry to DGEMV parameter number 6 had an illegal value
As far as I can tell everything the input types are correct and array a has
I would really appreciate an insight into the problem.
Thanks
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "cblas.h"
#include "array_alloc.h"
int main( void )
{
double **a, **A;
double *b, *B, *C;
int *ipiv;
int n, nrhs;
int info;
int i, j;
printf( "How big a matrix?\n" );
fscanf( stdin, "%i", &n );
/* Allocate the matrix and set it to random values but
with a big value on the diagonal. This makes sure we don't
accidentally get a singular matrix */
a = alloc_2d_double( n, n );
A= alloc_2d_double( n, n );
for( i = 0; i < n; i++ ){
for( j = 0; j < n; j++ ){
a[ i ][ j ] = ( ( double ) rand() ) / RAND_MAX;
}
a[ i ][ i ] = a[ i ][ i ] + n;
}
memcpy(A[0],a[0],n*n*sizeof(double)+1);
/* Allocate and initalise b */
b = alloc_1d_double( n );
B = alloc_1d_double( n );
C = alloc_1d_double( n );
for( i = 0; i < n; i++ ){
b[ i ] = 1;
}
cblas_dcopy(n,b,1,B,1);
/* the pivot array */
ipiv = alloc_1d_int( n );
/* Note we MUST pass pointers, so have to use a temporary var */
nrhs = 1;
/* Call the Fortran. We need one underscore on our system*/
dgesv_( &n, &nrhs, a[ 0 ], &n, ipiv, b, &n, &info );
/* Tell the world the results */
printf( "info = %i\n", info );
for( i = 0; i < n; i++ ){
printf( "%4i ", i );
printf( "%12.8f", b[ i ] );
printf( "\n" );
}
/* Want to check my lapack result with blas */
cblas_dgemv(CblasRowMajor,CblasTrans,n,n,1.0,A[0],1,B,1,0.0,C,1);
return 0;
}
The leading dimension (LDA) needs to be at least as large as the number of columns (n) for a RowMajor matrix. You’re passing a LDA of 1.
Separately, I’m slightly suspicious of your matrix types; without seeing how alloc_2d_double is implemented there’s no way to be sure if you’re laying out the matrix correctly or not. Generally speaking, intermixing pointer-to-pointer-style “matrices” with BLAS-style matrices (contiguous arrays with row or column stride) is something of a code smell. (However, it is possible to do correctly, and you may well be handling it properly; it’s just not possible to tell if this is the case from the code you posted).

Objective c, Scanf() string taking in the same value twice

Hi all I am having a strange issue, when i use scanf to input data it repeats strings and saves them as one i am not sure why.
Please Help
/* Assment Label loop - Loops through the assment labels and inputs the percentage and the name for it. */
i = 0;
j = 0;
while (i < totalGradedItems)
{
scanf("%s%d", assLabel[i], &assPercent[i]);
i++;
}
/* Print Statement */
i = 0;
while (i < totalGradedItems)
{
printf("%s", assLabel[i]);
i++;
}
Input Data
Prog1 20
Quiz 20
Prog2 20
Mdtm 15
Final 25
Output Via Console
Prog1QuizQuizProg2MdtmMdtmFinal
Final diagnosis
You don't show your declarations...but you must be allocating just 5 characters for the strings:
When I adjust the enum MAX_ASSESSMENTLEN from 10 to 5 (see the code below) I get the output:
Prog1Quiz 20
Quiz 20
Prog2Mdtm 20
Mdtm 15
Final 25
You did not allow for the terminal null. And you didn't show us what was causing the bug! And the fact that you omitted newlines from the printout obscured the problem.
What's happening is that 'Prog1' is occupying all 5 bytes of the string you read in, and is writing a null at the 6th byte; then Quiz is being read in, starting at the sixth byte.
When printf() goes to read the string for 'Prog1', it stops at the first null, which is the one after the 'z' of 'Quiz', producing the output shown. Repeat for 'Prog2' and 'Mtdm'. If there was an entry after 'Final', it too would suffer. You are lucky that there are enough zero bytes around to prevent any monstrous overruns.
This is a basic buffer overflow (indeed, since the array is on the stack, it is a basic Stack Overflow); you are trying to squeeze 6 characters (Prog1 plus '\0') into a 5 byte space, and it simply does not work well.
Preliminary diagnosis
First, print newlines after your data.
Second, check that scanf() is not returning errors - it probably isn't, but neither you nor we can tell for sure.
Third, are you sure that the data file contains what you say? Plausibly, it contains a pair of 'Quiz' and a pair of 'Mtdm' lines.
Your variable j is unused, incidentally.
You would probably be better off having the input loop run until you are either out of space in the receiving arrays or you get a read failure. However, the code worked for me when dressed up slightly:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char assLabel[10][10];
int assPercent[10];
int i = 0;
int totalGradedItems = 5;
while (i < totalGradedItems)
{
if (scanf("%9s%d", assLabel[i], &assPercent[i]) != 2)
{
fprintf(stderr, "Error reading\n");
exit(1);
}
i++;
}
/* Print Statement */
i = 0;
while (i < totalGradedItems)
{
printf("%-9s %3d\n", assLabel[i], assPercent[i]);
i++;
}
return 0;
}
For the quoted input data, the output results are:
Prog1 20
Quiz 20
Prog2 20
Mdtm 15
Final 25
I prefer this version, though:
#include <stdio.h>
enum { MAX_GRADES = 10 };
enum { MAX_ASSESSMENTLEN = 10 };
int main(void)
{
char assLabel[MAX_GRADES][MAX_ASSESSMENTLEN];
int assPercent[MAX_GRADES];
int i = 0;
int totalGradedItems;
for (i = 0; i < MAX_GRADES; i++)
{
if (scanf("%9s%d", assLabel[i], &assPercent[i]) != 2)
break;
}
totalGradedItems = i;
for (i = 0; i < totalGradedItems; i++)
printf("%-9s %3d\n", assLabel[i], assPercent[i]);
return 0;
}
Of course, if I'd set up the scanf() format string 'properly' (meaning safely) so as to limit the length of the assessment names to fit into the space allocated, then the loop would stop reading on the second attempt:
...
char format[10];
...
snprintf(format, sizeof(format), "%%%ds%%d", MAX_ASSESSMENTLEN-1);
...
if (scanf(format, assLabel[i], &assPercent[i]) != 2)
With MAX_ASSESSMENTLEN at 5, the snprintf() generates the format string "%4s%d". The code compiled reads:
Prog 1
and stops. The '1' comes from the 5th character of 'Prog1'; the next assessment name is '20', and then the conversion of 'Quiz' into a number fails, causing the input loop to stop (because only one of two expected items was converted).
Despite the nuisance value, if you want to make your scanf() strings adjust to the size of the data variables it is reading into, you have to do something akin to what I did here - format the string using the correct size values.
i guess, you need to put a
scanf("%s%d", assLabel[i], &assPercent[i]);
space between %s and %d here.
And it is not saving as one. You need to put newline or atlease a space after %s on print to see difference.
add:
when i tried
#include <stdio.h>
int main (int argc, const char * argv[])
{
char a[1][2];
for(int i =0;i<3;i++)
scanf("%s",a[i]);
for(int i =0;i<3;i++)
printf("%s",a[i]);
return 0;
}
with inputs
123456
qwerty
sdfgh
output is:
12qwsdfghqwsdfghsdfgh
that proves that, the size of string array need to be bigger then decleared there.