我可以在数组中找到重复的值,但是当我有两组以上的重复值时程序会卡住。
例如,如果我给出输入:
public function index()
{
$this->load->model('sorts');
$data['products'] = $this->sorts->sort_products1();
$this->load->view('cart/products', $data);
}
(注意第一个数字[10]表示数组中有多少个数字,并且假设所有数字都按升序排列)
我得到
的正确分数输出10 1 2 3 4 5 10 10 10 10 10
(runCount(5)* runNumber(10)= 50)
如果我在数组中有两个以上的重复元素,例如 -
Run {10,10,10,10,10} scoring 50.
分数都是混乱的
10 5 5 5 5 5 10 10 10 10 10
由于{5,5,5,5,5}的得分应低于{10,10,10,10,10},理想情况下,该程序会打印得分最高的值。
Run {5,10,10,10,10,5,5,5,5} scoring 45.
如何制作它只使用最高值?我无法让break函数正常工作。
如果您有任何想法,请告诉我?我的代码如下。
我只能使用数组,循环和if / else
Run {10,10,10,10,10} scoring 50.
答案 0 :(得分:1)
像这样:
#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;
}
答案 1 :(得分:0)
或尝试这样:
#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;
}
}
答案 2 :(得分:0)
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
}
了解更多see here