#8
by かずま » 5年前
かずま さんが書きました: ↑5年前
例えば、
int a[8] = { 30, 10, 40, 20, 50, 40, 30, 30 };
という配列があった時、
....
・重複要素の値と元の要素番号の両方の場合
30: 0 6 7
40: 2 4
すみません。
30: 0 6 7
40: 2 5
の間違いでした。
このように出力するための C++プログラム
コード:
#include <iostream>
#include <map>
#include <vector>
using namespace std;
int main()
{
int a[] = { 30, 10, 40, 20, 50, 40, 30, 30 };
const int n = sizeof a / sizeof *a;
map<int, vector<int>> m;
for (int i = 0; i < n; i++) m[a[i]].push_back(i);
for (auto& p : m)
if (p.second.size() > 1) {
cout << p.first << ':';
for (int i : p.second) cout << ' ' << i;
cout << endl;
}
}
Cプログラムだと
コード:
#include <stdio.h>
#include <stdlib.h> // malloc, free
int main(void)
{
int a[] = { 30, 10, 40, 20, 50, 40, 30, 30 };
const int n = sizeof a / sizeof *a;
int *c = malloc(sizeof a);
int i, j, k;
for (i = 0; i < n; i++) c[i] = i;
for (i = 0; i < n; i++)
for (j = i + 1; j < n; j++)
if (a[c[i]] > a[c[j]]) k = c[i], c[i] = c[j], c[j] = k;
k = 0; // 重複検出フラグ
for (i = 0; i < n-1; i++)
if (a[c[i]] == a[c[i+1]]) {
if (!k) printf("%d:", a[c[i]]);
printf(" %d", c[i]), k = 1;
}
else if (k) printf(" %d\n", c[i]), k = 0;
if (k) printf(" %d\n", c[i]);
free(c);
}
[quote=かずま post_id=153344 time=1557205652]
例えば、
int a[8] = { 30, 10, 40, 20, 50, 40, 30, 30 };
という配列があった時、
....
・重複要素の値と元の要素番号の両方の場合
30: 0 6 7
40: 2 4
[/quote]
すみません。
30: 0 6 7
40: 2 5
の間違いでした。
このように出力するための C++プログラム
[code]
#include <iostream>
#include <map>
#include <vector>
using namespace std;
int main()
{
int a[] = { 30, 10, 40, 20, 50, 40, 30, 30 };
const int n = sizeof a / sizeof *a;
map<int, vector<int>> m;
for (int i = 0; i < n; i++) m[a[i]].push_back(i);
for (auto& p : m)
if (p.second.size() > 1) {
cout << p.first << ':';
for (int i : p.second) cout << ' ' << i;
cout << endl;
}
}
[/code]
Cプログラムだと
[code]
#include <stdio.h>
#include <stdlib.h> // malloc, free
int main(void)
{
int a[] = { 30, 10, 40, 20, 50, 40, 30, 30 };
const int n = sizeof a / sizeof *a;
int *c = malloc(sizeof a);
int i, j, k;
for (i = 0; i < n; i++) c[i] = i;
for (i = 0; i < n; i++)
for (j = i + 1; j < n; j++)
if (a[c[i]] > a[c[j]]) k = c[i], c[i] = c[j], c[j] = k;
k = 0; // 重複検出フラグ
for (i = 0; i < n-1; i++)
if (a[c[i]] == a[c[i+1]]) {
if (!k) printf("%d:", a[c[i]]);
printf(" %d", c[i]), k = 1;
}
else if (k) printf(" %d\n", c[i]), k = 0;
if (k) printf(" %d\n", c[i]);
free(c);
}
[/code]