Hello I have written the code needed for a dice rolling generator base on rand() and time.h.
It basically asks the user to input the number of times he wants the dice to be rolled and then rolls those X times. It saves the times each one of 1-6 number was rolled in an array and the percentage of each number in another array.
Now what I want to do is create a histogram the has the numbers 1-6 and - on the X-axis, the percentages and | on the Y-axis and stars(*) for columns.
Something like this:
10% | *
8% |* * *
6% |* * * * *
4% |* * * * * *
2% |* * * * * *
+------------
1 2 3 4 5 6
I have search throught google to find something to begin with but I have really found anything similar to my case thats gonna help me begin with.
My code thus for is:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int random_number();
float calc_percentage(int totals, int nums);
float calc_maxper(float perc[6]);
float calc_minper(float perc[6]);
float permin;
float permax;
int main(void)
{
int nums;
int i;
int totals[6] = {0};
float percentages[6] = {0};
srand(time(NULL));
printf("How many numbers to generate?");
scanf("%d", &nums);
for (i = 1; i <= nums; i++)
{
int x = random_number();
totals[x-1]++;
}
for (i = 0; i<6; i++)
{
percentages[i] = calc_percentage(totals[i],nums);
printf("The percentage of each number is: %.2f%\n", percentages[i]);
}
permin = calc_minper(percentages);
permax = calc_maxper(percentages);
if (((permax) - (permin)) > 5)
printf("The generator is not good.\n");
printf("The percentage difference is:%.1f\n", permax-permin);
system("pause");
return 0;
}
int random_number()
{
int randnum;
randnum = 1 + (rand() % 6);
return randnum;
}
float calc_percentage(int totals, int numbers)
{
float a;
a = (totals * 100)/numbers;
return a;
}
float calc_minper(float perc[6])
{
int i;
float min;
min = perc[0];
for (i=1; i<6; i++)
{
if (perc[i] < min)
min = perc[i];
}
return min;
}
float calc_maxper(float perc[6])
{
int i;
float max;
max = perc[0];
for (i=1; i<6; i++)
{
if (perc[i] > max)
max = perc[i];
}
return max;
}
Ok I finally got this done.
Kinda long and messy but it definitely gets the job done!!
printf("20%|");
for (i=0; i<6; i++)
{
if (percentages[i] >= 20)
printf("* ");
}
printf("\n");
printf("16%|");
for (i=0; i<6; i++)
{
if (percentages[i] >= 16)
printf("* ");
}
printf("\n");
printf("12%|");
for (i=0; i<6; i++)
{
if (percentages[i] >= 12)
printf("* ");
}
printf("\n");
printf(" 8%|");
for (i=0; i<6; i++)
{
if (percentages[i] >= 8)
printf("* ");
}
printf("\n");
printf(" 4%|");
for (i=0; i<6; i++)
{
if (percentages[i] >= 4)
printf("* ");
}
printf("\n");
printf(" +------------\n");
printf(" 1 2 3 4 5 6\n");
Thanks dude for your ideas!!
If u have any quick ideas to make it shorter am all ears!
For each range (10%, 8%, etc), check if the current dice number (1-6) percentage exceeds it, then print a * (or a space if it doesn't meet the range minimum). At the end, print the graph base.
You could use a for to handle the ranges:
float range;
float interval = (permax-permin)/(NUM_INTERVALS-1);
for (range = permax; range >= permin - EPSILON; range -= interval){
int i;
printf("%2.2f%% | ", range);
for(i=0; i<6; i++){
char *out = percentages[i] >= range ? "*" : " ";
printf("%s ", out);
}
printf("\n");
}
printf(" | 1 2 3 4 5 6\n");
Related
I need to input a matrix, where the first element of a row is the student ID number, and the other 12 elements are student points and GPA. Each row represents one student. What the program needs to do is calculate the total point amount, and then sort the matrix so it goes in descending order by the amount of points.
This is my code:
#include <stdio.h>
int main() {
int number_of_students,i,j;
double matrix[50][50],GPA,grades,total,GPA_before;
printf("Number of students: ");
scanf("%d", &number_of_students);
printf("Input students: ");
for(i=0; i<number_of_students; i++){
for(j=0; j<12; j++){
scanf("%lf", &matrix[i][j]);
}
}
printf("Final list: \n");
for(i=0; i<number_of_students; i++){
GPA_before=(matrix[i][2]+matrix[i][3]+matrix[i][4]+matrix[i][5])*2.5;
if(GPA_before==50){
GPA=GPA_before+3;
}
else{
GPA=GPA_before;
}
grades=(matrix[i][6]+matrix[i][7]+matrix[i][8]+matrix[i][9]+matrix[i][10]+matrix[i][11])*0.67;
total=GPA+grades+matrix[i][12];
printf("%d. %g | %g\n",i,matrix[i][1],total);
}
return 0;
}
And this is what I get:
Number of students: 4
Input students: 123456 4.00 4.50 5.00 5.00 5 5 5 4 4 5 15
456789 4.50 5.00 4.00 3.50 3 5 4 5 5 2 10
789321 5.00 5.00 4.50 3.00 5 4 5 3 5 3 15
456987 4.50 4.50 4.50 5.00 4 4 4 5 5 5 25
Final list:
1. 123456 | 80.01
2. 456789 | 68.58
3. 789321 | 75.5
4. 456987 | 89.34
The matrix should be sorted from highest number of points to the lowest, not by ID. It is specified not to sort the list while printing it out, the matrix itself must be sorted.
I would really appreciate the help.
Firstly, I saw a few things in your code that I would like to point out and change, if possible.
You are allocating an 2-D Array of 50 rows and 50 columns. However, you're only utilizing 12 of those columns. So, first thing that I would like you to fix is the use of those extra unnecessary array indexes. So, I wrote the following code:
const int MAX = 50;
const int NUM_INPUTS = 12;
int number_of_students, i, j;
double matrix[MAX][NUM_INPUTS + 1], GPA, grades, total;
Note: I added NUM_INPUTS + 1, that we will use to store the total of that you were calculating in the loop and also printing it too.
Now, another thing I would like to point out, is your use of loops. You're iteration is beginning from the index 1. You're not using the 0th index. So, you'll have to fix each loop from this:
for(i=1; i<=number_of_students; i++){
for(j=1; j<=12; j++){
scanf("%lf", &matrix[i][j]);
}
}
to this:
for (i = 0; i < number_of_students; i++) {
for (j = 0; j < NUM_INPUTS; j++) {
scanf("%lf", &matrix[i][j]);
}
}
Now, this indexing from 0 will cause the code that you wrote for the calculations, to not work properly, so, you will have to fix that too:
for(i=1; i<=number_of_students; i++){
GPA_before=(matrix[i][2]+matrix[i][3]+matrix[i][4]+matrix[i][5])*2.5;
if(GPA_before==50){
GPA=GPA_before+3;
}
else{
GPA=GPA_before;
}
grades=(matrix[i][6]+matrix[i][7]+matrix[i][8]+matrix[i][9]+matrix[i][10]+matrix[i][11])*0.67;
total=GPA+grades+matrix[i][12];
You were using this code in-junction with printf. I used this code to calculate the total and then store it in the index matrix[i][NUM_INPUTS].
Now, I slightly changed your code and loop for storing the total in the matrix itself becomes:
for (i = 0; i < number_of_students; i++) {
GPA = (matrix[i][1] + matrix[i][2] + matrix[i][3] + matrix[i][4]) * 2.5;
if (GPA == 50) {
GPA += 3;
}
grades = (matrix[i][5] + matrix[i][6] + matrix[i][7] + matrix[i][8] + matrix[i][9] + matrix[i][10]) * 0.67;
total = GPA + grades + matrix[i][11];
matrix[i][NUM_INPUTS] = total;
}
Now, this made it easy for me to implement a basic Bubble Sort algorithm to sort your matrix:
int k;
for (i = 0; i < number_of_students; i++) {
for (j = 0; j < number_of_students - 1; j++) {
if (matrix[j][NUM_INPUTS] > matrix[j + 1][NUM_INPUTS]) {
double temp;
for (k = 0; k < NUM_INPUTS + 1; k++) {
temp = matrix[j][k];
matrix[j][k] = matrix[j + 1][k];
matrix[j + 1][k] = temp;
}
}
}
}
Now, since the matrix itself has been sorted, we will simply print the final matrix:
for (i = 0; i < number_of_students; i++) {
printf("%d. %g | %g\n", i + 1, matrix[i][0], matrix[i][NUM_INPUTS]);
}
Note: One more thing you can do (totally for input validation) is write an if statement, that would check if the user input for number of students is in the range of 1 <= number_of_students <= MAX (50), if it is greater than that, it would cause an out-of-bounds exception or a Buffer Overflow.
if(number_of_students > MAX || number_of_students <= 0) {
printf("Invalid number of students");
return 1;
}
I hope you understood what I wrote and would love if you'd upvote as this is my first answer here.
Here's the full source code:
#include <stdio.h>
int main() {
const int MAX = 50;
const int NUM_INPUTS = 12;
int number_of_students, i, j;
double matrix[MAX][NUM_INPUTS + 1], GPA, grades, total;
printf("Number of students: ");
scanf("%d", &number_of_students);
if(number_of_students > MAX || number_of_students <= 0) {
printf("Invalid number of students");
return 1;
}
printf("Input students: ");
for (i = 0; i < number_of_students; i++) {
for (j = 0; j < NUM_INPUTS; j++) {
scanf("%lf", &matrix[i][j]);
}
}
// Firstly calculating the total and storing it in the final index of the matrix:
for (i = 0; i < number_of_students; i++) {
GPA = (matrix[i][1] + matrix[i][2] + matrix[i][3] + matrix[i][4]) * 2.5;
if (GPA == 50) {
GPA += 3;
}
grades = (matrix[i][5] + matrix[i][6] + matrix[i][7] + matrix[i][8] + matrix[i][9] + matrix[i][10]) * 0.67;
total = GPA + grades + matrix[i][11];
matrix[i][NUM_INPUTS] = total;
}
// Sorting this based on total:
for (i = 0; i < number_of_students; i++) {
for (j = 0; j < number_of_students - 1; j++) {
if (matrix[j][NUM_INPUTS] > matrix[j + 1][NUM_INPUTS]) {
double temp;
for (int k = 0; k < NUM_INPUTS + 1; k++) {
temp = matrix[j][k];
matrix[j][k] = matrix[j + 1][k];
matrix[j + 1][k] = temp;
}
}
}
}
printf("Final list:\n");
for (i = 0; i < number_of_students; i++) {
printf("%d. %g | %g\n", i + 1, matrix[i][0], matrix[i][NUM_INPUTS]);
}
return 0;
}
Let's say I have an array like this:
int array[]={1, 2, 2, 1, 2, 4, 4, 5};
I want to display all duplicate elements only once, display their corresponding frequency and count total duplicate elements. I searched about it a lot but every solution is for an array that has only 2 duplicate elements.
void non_unique_numbers(int arr[], int size){
int i,j;
int frequency[Frequency_size]={0};
for(i=0; i<size; i++){
for(j=0; j<size; j++){
if(arr[i]==arr[j] && i!=j){
++frequency[arr[j]];
printf("Number: %d , Frequency: %d\n", arr[j], frequency[j]);
}
}
}
}
When I run this my output is:
Number: 1 , Frequency: 3
Number: 2 , Frequency: 1
Number: 2 , Frequency: 1
Number: 2 , Frequency: 1
Number: 2 , Frequency: 2
Number: 1 , Frequency: 0
Number: 2 , Frequency: 2
Number: 2 , Frequency: 6
Number: 4 , Frequency: 0
which is meaningless. How can I display every duplicate element once and find out their corresponding frequency?
Rather than nested loops, you need two loops.
One to calculate the frequency. And, another that displays the frequencies and calculates the total number of duplicate numbers.
Here is the refactored code:
Edit: I've removed my broken original code during the second update.
UPDATE:
Yes but it still displays the same element more than once –
goku
Oops, my bad ... Here is one that indexes into the frequency table on the second loop:
#include <stdio.h>
#define Frequency_size 10000
void
non_unique_numbers(int arr[], int size)
{
int i;
int freq;
int totdup = 0;
int frequency[Frequency_size] = { 0 };
// calculate freqency
for (i = 0; i < size; i++)
++frequency[arr[i]];
for (i = 0; i < Frequency_size; i++) {
freq = frequency[i];
if (freq <= 0)
continue;
printf("Number: %d , Frequency: %d\n", i, freq);
if (freq >= 2)
++totdup;
}
printf("The number of duplicated numbers is: %d\n",totdup);
}
UPDATE #2:
Can we make it work for also negative elements? for (i = 0; i < Frequency_size; i++) { freq = frequency[i]; if (freq <= 0) continue; printf("Number: %d , Frequency: %d\n", i, freq); Because of this part it is not working for negative integers –
goku
Yes, we just need to use a second array for the negative number frequencies and index it by the negative of the negative number. (i.e.) we use a corresponding positive index.
Also, some have commented about doing range checks, so I've added that along with some statistics on the out of range values [if any]. I've also updated the if test so that only duplicate numbers are printed.
Once again, I've compiled this but not tested it, but it should be okay:
#include <stdio.h>
#include <string.h>
#define Frequency_size 10000
void
non_unique_numbers(const int *arr, int size)
{
int i;
int freq;
int val;
int totdup = 0;
int pos_badcnt = 0;
int pos_badmax = 0;
int neg_badcnt = 0;
int neg_badmax = 0;
static int freq_pos[Frequency_size];
static int freq_neg[Frequency_size];
// set frequency counts to zero
memset(freq_pos,0,sizeof(freq_pos));
memset(freq_neg,0,sizeof(freq_neg));
// calculate freqency
for (i = 0; i < size; i++) {
val = arr[i];
// handle positive number(s)
if (val >= 0) {
if (val >= Frequency_size) {
++pos_badcnt;
if (val > pos_badmax)
pos_badmax = val;
}
else
++freq_pos[val];
}
// handle negative number(s)
else {
// index frequency array with positive index -- that's the trick
val = -val;
if (val >= Frequency_size) {
++neg_badcnt;
if (val > neg_badmax)
neg_badmax = val;
}
else
++freq_neg[val];
}
}
// for negative numbers, skip 0 and show lowest (most negative) first
for (i = Frequency_size - 1; i >= 1; --i) {
freq = freq_neg[i];
if (freq <= 1)
continue;
printf("Number: %d , Frequency: %d\n", -i, freq);
++totdup;
}
// show positive number frequencies
for (i = 0; i < Frequency_size; i++) {
freq = freq_pos[i];
if (freq <= 1)
continue;
printf("Number: %d , Frequency: %d\n", i, freq);
++totdup;
}
printf("The number of duplicated numbers is: %d\n",totdup);
// show out of range negative number stats
if (neg_badcnt > 0) {
printf("There were %d out of range negative numbers\n",neg_badcnt);
printf("Smallest out of range negative number was %d\n",-neg_badmax);
}
// show out of range positive number stats
if (pos_badcnt > 0) {
printf("There were %d out of range positive numbers\n",pos_badcnt);
printf("Largest out of range positive number was %d\n",pos_badmax);
}
}
You can try this.
void non_unique_numbers(int arr[], int size){
int i,j;
for(i=0; i<size; i++)
{
int frequency=0;
bool wasFoundEarlier=false;
for(j=i; j<size; j++)
{
if(arr[i]==arr[j])
{
frequency++;
}
}
for(int x=0;x<i;x++)
{
if(arr[x]==arr[i])
{
wasFoundEarlier=true;
}
}
if(!wasFoundEarlier)
{
printf("Number: %d , Frequency: %d\n", arr[i], frequency);
}
}
}
This will print the frequency of all the elements.
If you want to print the frequency of only duplicate ones, just change the inner loop
for(j=i+1; j<size; j++)
I'm trying to finish my homework, while there is something trapped me.
Here the question:
In the range of N, output those numbers whose factors sum is equal to themselves according to the following format.
Input:
1000
output:
6 its factors are 1 2 3
28 its factors are 1 2 4 7 14
496 its factors are 1 2 4 8 16 31 62 124 248
Here my code, please tell me why can't i get the right output. Appreciate it if
you can improve it for me.
Thanks in advance.
#include<stdio.h>
#define NUM 100
int main()
{
int goal[NUM];//array for factors.
int N;
scanf("%d",&N);
getchar();
for(int p=2;p<N;p++)//1 and N are not included.
{
int j=0,sum=0;
for(int i=1;i<p; )
{
//get factors and put them into array.
while(p%i==0)
{
goal[j]=i;
sum+=goal[j];
j++;
i++;
}
}
//judge the sum of factors and p the two values are equal.
if(sum==p)
{
printf("%d its factors are ",p);
for(int i=0;i<j;i++)
{
while(i==j-1)
printf("%d \n",goal[i]);
}
}
}
return 0;
}
Making the same a little clean,
int main()
{
int N, factors_sum, factors_cnt, num, j;
scanf("%d", &N);
int *factors = malloc(sizeof(int) * N/2);
if (factors == NULL)
{
perror("malloc(2)");
return 1;
}
for (num = 2 ; num < N ; ++num)
{
factors_cnt = 0;
factors_sum = 0;
for (j = 1 ; j <= num/2 ; ++j)
if (num % j == 0)
factors_sum += (factors[factors_cnt++] = j);
if (factors_sum == num)
{
printf("%d its factors are", num);
for (j = 0 ; j < factors_cnt ; ++j)
printf(" %d", factors[j]);
printf("\n");
}
}
free(factors);
return 0;
}
Modifications retaining your code:
#include<stdio.h>
#define NUM 100
int main()
{
int goal[NUM];//array for factors.
int sum=0;
int N;
scanf("%d",&N);
//getchar(); // I donno why you need this, better to remove it
for(int p=2;p<N;p++)//1 and N are not included.
{
// sum is different for every number
// need to be set to 0 individually for every number
sum = 0;
int j=0;
for(int i=1;i<p; i++) // i++ everytime
{
//get factors and put them into array.
if (p%i==0)
// changed while to if
// while would keep executing forever
{
goal[j]=i;
sum+=goal[j];
j++;
}
}
//judge the sum of factors and p the two values are equal.
if (sum==p)
{
printf("%d its factors are ",p);
for(int i=0;i<j;i++)
{
// no need for while here
printf("%d \n",goal[i]);
}
}
}
return 0;
}
I have made modifications in your code and corrected/commented where you have made mistakes.
The problem is I can't get the proper GPA. I am suspecting the divisions and type conversions. Below is the exact question I'm trying to do but I would like to learn what am I missing with my code.
https://imgur.com/a/HFrIO - They don't mention about credits so I simply ask it from the user in the program.
Edit: As seen from the question above, it should calculate the GPA but when I try with marks 50, 60, 70 respectively and 3 credits for each course, I get no sense outputs like 0.
(Original assignment wants 30 students and 5 courses but I defined them and changed them to 2 courses 1 student in order to test it in runtime.)
#include <stdio.h>
#define NUMBER_OF_COURSES 2 // Homework asks for 5, change at the end
#define NUMBER_OF_STUDENTS 1 // Homework asks for 30, change at the end
void calculateCourse(int *letterGradePoints, int *credit); // Func. prototype
float calculateStudentGpa(); // Func. prototype
int main()
{
// Store gpa s of students in an array
float studentGpas[NUMBER_OF_STUDENTS];
int i;
for(i = 0; i < NUMBER_OF_STUDENTS; ++i)
{
/*DEBUG*/printf("----\nPROGRAM IS IN MAIN FOR LOOP\n----\n");
studentGpas[i] = calculateStudentGpa();
}
// Print all gpas
for(i = 0; i < NUMBER_OF_STUDENTS; ++i)
{
printf("\nGPA of student %d is : %d ", i + 1, studentGpas[i]);
}
// Find min gpa
int min = studentGpas[0];
for(i = 1; i < NUMBER_OF_STUDENTS; ++i)
if(min > studentGpas[i])
min = studentGpas[i];
// Find max gpa
int max = studentGpas[0];
for(i = 1; i < NUMBER_OF_STUDENTS; ++i)
if(max < studentGpas[i])
max = studentGpas[i];
// Print min and max
printf("Min gpa is : %d Max gpa is : %d", min, max);
return 0;
}
float calculateStudentGpa()
{
/*DEBUG*/printf("\nPROGRAM IS IN calculateStudentGpa FUNCTION");
/* Dealing with a single students gpa */
int credit[NUMBER_OF_COURSES];
int letterGradePoints[NUMBER_OF_COURSES];
int i; int debug = 0;
for(i = 0; i < NUMBER_OF_COURSES; ++i)
{
/*DEBUG*/ if(debug == 0) { /*DEBUG*/printf("\nPROGRAM IS IN calculateStudentGpa FUNCTION for LOOP\n"); debug++; } // Print this one once
calculateCourse(&letterGradePoints[i], &credit[i]);
/*DEBUG*/printf("\nPROGRAM IS IN calculateStudentGpa FUNCTION for LOOP\n");
/*DEBUG*/printf("\n[DEBUG] i in calculateStudentGpa : %d", i);
/*DEBUG*/printf("\n[DEBUG] letterGradePoints[i] in calculateStudentGpa : %d", letterGradePoints[i]);
/*DEBUG*/printf("\n[DEBUG] credit[i] in calculateStudentGpa : %d\n", credit[i]);
}
/*DEBUG*/printf("\nPROGRAM HAS ..PASSED.. calculateStudentGpa FOR LOOP");
float gpa; float up = 0; float down = 0;
/* Either we need to have
* (i = 0; i < NUMBER_OF_COURSES; ++i) AND indexes of arrays as i
* or
* (i = 1; i <= NUMBER_OF_COURSES; ++i) AND indexes of arrays as i - 1
* below in 2 for loops!!!!
*/
for(i = 0; i < NUMBER_OF_COURSES; ++i)
{
up += (letterGradePoints[i] * credit[i]); // Might need (float)
}
for(i = 1; i <= NUMBER_OF_COURSES; ++i)
{
down += credit[i - 1];
}
gpa = up / down;
/* We are done with a single student, we need all 30 students */
return gpa;
}
void calculateCourse(int *letterGradePoints, int *credit)
{
/*DEBUG*/printf("\n--------------------------------------");
/*DEBUG*/printf("\nVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV");
/*DEBUG*/printf("\nPROGRAM IS IN calculateCourse FUNCTION\n");
/* Dealing with a single course */
int labMark, midtermMark, finalMark;
printf("\nEnter lab mark : ");
scanf("%d", &labMark);
printf("Enter midterm mark : ");
scanf("%d", &midtermMark);
printf("Enter final mark : ");
scanf("%d", &finalMark);
float average =
(
(float) (0.5 * finalMark)
+
(float) (0.4 * midtermMark)
+
(float) (0.1 * labMark)
); // Might need (float)
/*DEBUG*/printf("\n[DEBUG] average : %f", average);
// int letterGradePoints; // I decided to use pass by reference in order to return 2 values
if(average >= 0) *letterGradePoints = 0;
if(average >= 50) *letterGradePoints = 1;
if(average >= 60) *letterGradePoints = 2;
if(average >= 70) *letterGradePoints = 3;
if(average >= 80) *letterGradePoints = 4;
/*DEBUG*/printf("\n[DEBUG] letterGradePoints in calculateCourse : %d\n", *letterGradePoints);
// int credit; // I decided to use pass by reference in order to return 2 values
printf("Enter the credit for the course : ");
scanf("%d", credit);
/*DEBUG*/printf("\n[DEBUG] *credit in calculateCourse : %d\n", *credit);
/*DEBUG*/printf("/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\\n");
/*DEBUG*/printf("--------------------------------------\n");
/* We are done with a single course, we need all 5 courses for the gpa */
}
You're printing the GPA as an integer instead of as a floating point number. Change
printf("\nGPA of student %d is : %d", i + 1, studentGpas[i]);
to
printf("\nGPA of student %d is : %f", i + 1, studentGpas[i]);
Look here for a list of format specifiers used by printf.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I can find duplicate values in an array, however the program gets stuck when I have more than 2 sets of duplicating values.
So for example, if I give the input:
10 1 2 3 4 5 10 10 10 10 10
(note the first digit [10] indicates how many numbers are in the array, and it is assumed all number will be in ascending order)
I get the correct score output of
Run {10,10,10,10,10} scoring 50.
(runCount (5) * runNumber (10) = 50)
If I have more than 2 repeating elements in the array, for example -
10 5 5 5 5 5 10 10 10 10 10
the scores are all muddled
Run {5,10,10,10,10,5,5,5,5} scoring 45.
As the scores for {5,5,5,5,5} should be lower than {10,10,10,10,10}, ideally, the program would print the values with the highest score.
Run {10,10,10,10,10} scoring 50.
How do I make it so it only uses the highest values? I couldn't quite get the break function to work correctly.
Please let me know if you have any ideas? My code is below.
I can only use arrays, loops, and if/else
//Game that calculates the highest score based on array inputs
#include <stdio.h>
#define MAX_PLAYERS 13
#define TRIPLE 3
int main(void) {
int nPlayers, i, j, k;
int gameNumbers[MAX_PLAYERS];
int runCount, runCounter, runNumber, runScore;
int runScores[MAX_PLAYERS] = {0};
//read in numbers
scanf("%d", &nPlayers);
i = 0;
while (i < nPlayers) {
scanf("%d", &gameNumbers[i]);
i = i + 1;
}
//Calculates Run Scores
//A run is when there are duplicates of the same number in a row
runCounter=0;
runNumber=0;
runScore=0;
j=0;
for (i=(nPlayers-1); i>=1; i--) {
if(gameNumbers[i] - gameNumbers[i-1] == 0) { //compares highest number to previous number to find equality
runScores[j]=gameNumbers[i];
j++;
runCounter++;
runCount=(runCounter+1);
runNumber=(gameNumbers[i]);
runScore=(runCount*runNumber);
}
}
//Run Score
printf("runCounter:%d, runCount=%d, runNumber=%d, runScore=%d\n", runCounter, runCount, runNumber, runScore);
printf("runScores[]=");
i=0;
while (i<runCount) {
printf("%d ", runScores[i]);
i++;
}
printf("\n");
//Print run scores
printf("Run {%d", runNumber);
j=0;
while (j < runCounter) {
printf(",%d", runScores[j]); //loop prints remainder of the stored run scores array
j++;
}
printf("} scoring %d.\n", runScore);
return 0;
}
Like this:
#include <stdio.h>
#include <limits.h>
int main(void){
int n;
scanf("%d", &n);
int numbers[n];
for(int i = 0; i < n; ++i) {
scanf("%d", &numbers[i]);
}
int hi_score = INT_MIN, dupCount = 0 , theNumber;
for(int i = 0; i < n; ++i){
int counter = 0, score;
for(int j = i + 1; j < n && numbers[i] == numbers[j]; ++j){
++counter;
}
if(counter > 0){
score = (counter + 1) * numbers[i];
if(hi_score <= score){//= : when 4 4 4 4 4 5 5 5 5, 4 < 5
theNumber = numbers[i];
dupCount = counter + 1;
hi_score = score;
}
i += counter;
}
}
if(dupCount > 0){
int new_array[dupCount];
printf("Run {");
for(int i = 0; i < dupCount; ++i){
if(i)
putchar(',');
printf("%d", new_array[i] = theNumber);
}
printf("} scoring %d.\n", hi_score);
}
return 0;
}
Or try sth like this:
#include<stdio.h>
#include<stdlib.h>
void generateScore(int*, int , int* , int* );
int main(){
int number = 0;
int times = 0;
int array[10] = {10, 10, 10, 10, 10, 4, 4, 10, 10, 10};
generateScore(array, 10, &number, ×);
printf("number: %d \t times:%d", number, times);
return (0);
}
void generateScore(int* array, int size, int* number, int* times) {
*number = array[0];
*times = 1;
int i;
for(i = 1 ; i < size && array[i] == *number; i++) {
*times = *times + 1 ;
}
if(size <= i) {
return;
}
int number2 = array[i];
int times2 = 1;
i++;
for(; i < size; i++){
if(array[i] == number2){
times2 = times2 + 1;
} else {
if((*times * (*number)) < (number2 * times2)) {
*times = times2;
*number = number2;
}
number2 = array[i];
times2 = 1;
}
}
if((*times * (*number)) < (number2 * times2)) {
*times = times2;
*number = number2;
}
}
int array[10] = {5 5 5 5 5 10 10 10 10 10};
generateScore(array, 10, &number, ×);
void generateScore(....){
int sum=0;
int preSum=0;
int index=-1;
int k;
for(i=0;i<size;i++)
{
k=i;
sum=0;
while(((k+1)<size)&&(array[k]==array[k+1]))
{
sum=sum+array[k];
k=k+1;
}
if(sum>presum){
index=k-1;
presum=sum;
}
i=k;
}
var num = presum/array[index];
//now your sum in presum which is present num times in your array whose last index in array is index
}
for more see here