0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

paizaラーニングレベルアップ問題集の連想配列の問題をやってみた。

Posted at

paizaラーニングレベルアップ問題集の連想配列の問題をやってみました。


問題
数値の出現率

英小文字の出現率

文字列の出現率

価格の算出

商品の検索


C
数値の出現率
#include <stdio.h>

int main() {
	int n;
	scanf("%d", &n);
	int A[n];
	for (int i = 0; i < n; i++) scanf("%d", &A[i]);
	int C[10] = {};
	for (int i = 0; i < n; i++) C[A[i]]++;
	for (int i = 0; i < 10; i++) {
		if (i) putchar(' ');
		printf("%d", C[i]);
	}
	puts("");
	return 0;
}
英小文字の出現率
#include <stdio.h>

int main() {
	int n;
	scanf("%d", &n);
	char s[n+1];
	scanf("%s", s);
	int C[26] = {};
	for (int i = 0; i < n; i++) C[s[i] - 'a']++;
	for (int i = 0; i < 26; i++) {
		if (i) putchar(' ');
		printf("%d", &C[i]);
	}
	puts("");
	return 0;
}
文字列の出現率
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int cmp(const void* a, const void* b) {
	return strcmp((const char*) a, (const char*) b);
}

int main() {
	int n;
	scanf("%d", &n);
	int m = 0;
	char S[100][4] = {};
	char C[100] = {};
	for (int i = 0; i < n; i++) {
		char s[4];
		scanf("%s", s);
		for (int j = 0; j <= m; j++) {
			if (j == m) {
				strcpy(S[m++], s);
				C[j]++;
				break;
			} else if (!strcmp(S[j], s)) {
				C[j]++;
				break;
			}
		}
	}
	char T[m][4];
	memcpy(T, S, sizeof(T));
	qsort(T, m, 4, cmp);
	for (int i = 0; i < m; i++) {
		for (int j = 0; j < m; j++) {
			if (!strcmp(S[j], T[i])) {
				printf("%s %d\n", S[j], C[j]);
				break;
			}
		}
	}
	return 0;
}
価格の算出
#include <stdio.h>
#include <string.h>

int main() {
	int n, m;
	scanf("%d %d", &n, &m);
	char A[n][11];
	int B[n];
	for (int i = 0; i < n; i++) {
		scanf("%s %d", A[i], &B[i]);
	}
	while (m--) {
		char s[11];
		scanf("%s", s);
		int t = -1;
		for (int i = 0; i < n; i++) {
			if (!strcmp(A[i], s)) {
				t = B[i];
				break;
			}
		}
		printf("%d\n", t);
	}
	return 0;
}
商品の検索
#include <stdio.h>
#include <string.h>

int main() {
	int n, Q;
	scanf("%d %d", &n, &Q);
	int m = 0;
	char S[100][4] = {};
	int A[100] = {};
	for (int i = 1; i <= n; i++) {
		char s[4];
		scanf("%s", s);
		for (int j = 0; j <= m; j++) {
			if (j == m) {
				strcpy(S[m], s);
				A[m] = i;
				m++;
				break;
			} else if (!strcmp(S[j], s)) {
				break;
			}
		}
	}
	while (Q--) {
		char t[4];
		scanf("%s", t);
		int j = -1;
		for (int i = 0; i < m; i++) {
			if (!strcmp(S[i], t)) {
				j = A[i];
				break;
			}
		}
		printf("%d\n", j);
	}
	return 0;
}

C++
数値の出現率

C++のstd::mapは、キーが存在しない場合デフォルト値(整数型の場合は
0)を返します。

#include <iostream>
#include <map>
using namespace std;

int main() {
	int n;
	cin >> n;
	map<int, int> C;
	for (int i = 0; i < n; i++) {
		int a;
		cin >> a;
		C[a]++;
	}
	for (int i = 0; i < 10; i++) {
		if (i) cout << ' ';
		cout << C[i];
	}
	cout << endl;
	return 0;
}
英小文字の出現率
#include <iostream>
#include <map>
using namespace std;

int main() {
	int n;
	cin >> n;
	string s;
	cin >> s;
	map<char, int> C;
	for (int i = 0; i < n; i++) C[s[i]]++;
	for (char c = 'a'; c <= 'z'; c++) {
		if (c > 'a') cout << ' ';
		cout << C[c];
	}
	cout << endl;
	return 0;
}
文字列の出現率

C++のstd::mapでは、キーは昇順(辞書順)で管理されます。

#include <iostream>
#include <map>
using namespace std;

int main() {
	int n;
	cin >> n;
	map<string, int> C;
	for (int i = 0; i < n; i++) {
		string s;
		cin >> s;
		C[s]++;
	}
	for (pair<string, int> item : C) {
		cout << item.first << ' ' << item.second << endl;
	}
	return 0;
}
価格の算出
#include <iostream>
#include <map>
using namespace std;

int main() {
	int n, m;
	cin >> n >> m;
	map<string, int> dict;
	while (n--) {
		string a;
		int b;
		cin >> a >> b;
		dict[a] = b;
	}
	while (m--) {
		string s;
		cin >> s;
		if (dict.count(s)) cout << dict[s] << endl;
		else cout << -1 << endl;
	}
	return 0;
}
商品の検索

std::mapの「値」として、添字(1始まり)を格納します。但し、すでにキーが存在する場合は格納しません。

#include <iostream>
#include <map>
using namespace std;

int main() {
	int n, Q;
	cin >> n >> Q;
	map<string, int> dict;
	for (int i = 1; i <= n; i++) {
		string s;
		cin >> s;
		if (!dict.count(s)) dict[s] = i;
	}
	while (Q--) {
		string t;
		cin >> t;
		if (dict.count(t)) cout << dict[t] << endl;
		else cout << -1 << endl;
	}
	return 0;
}

C#
数値の出現率
using System;
using System.Collections.Generic;

class Program
{
	public static void Main()
	{
		int n = int.Parse(Console.ReadLine());
		int[] A = Array.ConvertAll(Console.ReadLine().Split(), int.Parse);
		Dictionary<int, int> C = new Dictionary<int, int>();
		foreach (int a in A) {
			if (!C.ContainsKey(a)) C.Add(a, 0);
			C[a]++;
		}
		for (int i = 0; i < 10; i++) {
			if (i > 0) Console.Write(' ');
			Console.Write(C.ContainsKey(i) ? C[i] : 0);
		}
		Console.WriteLine();
	}
}
英小文字の出現率
using System;
using System.Collections.Generic;

class Program
{
	public static void Main()
	{
		int n = int.Parse(Console.ReadLine());
		string s = Console.ReadLine();
		Dictionary<char, int> C = new Dictionary<char, int>();
		for (int i = 0; i < n; i++) {
			char c = s[i];
			if (!C.ContainsKey(c)) C.Add(c, 0);
			C[c]++;
		}
		for (char c = 'a'; c <= 'z'; c++) {
			Console.Write(C.ContainsKey(c) ? C[c] : 0);
			if (c < 'z') Console.Write(' ');
		}
		Console.WriteLine();
	}
}
文字列の出現率

C#では、キーの辞書順に管理したい場合はSortedDictionaryを使うと便利です。

using System;
using System.Collections.Generic;

class Program
{
	public static void Main()
	{
		int n = int.Parse(Console.ReadLine());
		SortedDictionary<string, int> C = new SortedDictionary<string, int>();
		for (int i = 0; i < n; i++) {
			string s = Console.ReadLine();
			if (!C.ContainsKey(s)) C.Add(s, 0);
			C[s]++;
		}
		foreach (string s in C.Keys) Console.WriteLine(s + ' ' + C[s]);
	}
}
価格の算出
using System;
using System.Collections.Generic;

class Program
{
	public static void Main()
	{
		int[] nm = Array.ConvertAll(Console.ReadLine().Split(), int.Parse);
		int n = nm[0], m = nm[1];
		Dictionary<string, int> dict = new Dictionary<string, int>();
		for (; n > 0; n--) {
			string[] ab = Console.ReadLine().Split();
			string a = ab[0];
			int b = int.Parse(ab[1]);
			dict.Add(a, b);
		}
		for (; m > 0; m--) {
			string s = Console.ReadLine();
			Console.WriteLine(dict.ContainsKey(s) ? dict[s] : -1);
		}
	}
}
商品の検索
using System;
using System.Collections.Generic;

class Program
{
	public static void Main()
	{
		int[] nq = Array.ConvertAll(Console.ReadLine().Split(), int.Parse);
		int n = nq[0], Q = nq[1];
		Dictionary<string, int> dict = new Dictionary<string, int>();
		for (int i = 1; i <= n; i++) {
			string s = Console.ReadLine();
			if (!dict.ContainsKey(s)) dict.Add(s, i);
		}
		for (; Q > 0; Q--) {
			string t = Console.ReadLine();
			Console.WriteLine(dict.ContainsKey(t) ? dict[t] : -1);
		}
	}
}

Go
数値の出現率
package main
import "fmt"

func main(){
	var n int
	fmt.Scan(&n)
	C := make(map[int]int)
	for i := 0; i < n; i++ {
		var a int
		fmt.Scan(&a)
		C[a] += 1
	}
	for i := 0; i < 10; i++ {
		if i > 0 {
			fmt.Print(" ")
		}
		fmt.Print(C[i])
	}
	fmt.Println()
}
英小文字の出現率
package main
import "fmt"

func main(){
	var n int
	fmt.Scan(&n)
	var s string
	fmt.Scan(&s)
	C := make(map[rune]int)
	for i := 0; i < n; i++ {
		C[rune(s[i])] += 1
	}
	for c := 'a'; c <= 'z'; c++ {
		fmt.Print(C[c])
		if c < 'z' {
			fmt.Print(" ")
		}
	}
	fmt.Println()
}
文字列の出現率
package main
import (
	"fmt"
	"sort"
)

func main() {
	var n int
	fmt.Scan(&n)
	C := make(map[string]int)
	for i := 0; i < n; i++ {
		var s string
		fmt.Scan(&s)
		C[s] += 1		
	}
	S := []string{}
	for s := range(C) {
		S = append(S, s)
	}
	sort.Strings(S)
	for _, s := range(S) {
		fmt.Println(s, C[s])
	}
}
価格の算出
package main
import "fmt"

func main() {
	var n, m int
	fmt.Scan(&n, &m)
	dict := make(map[string]int)
	for i := 0; i < n; i++ {
		var a string
		var b int
		fmt.Scan(&a, &b)
		dict[a] = b
	}
	for i := 0; i < m; i++ {
		var s string
		fmt.Scan(&s)
		v, b := dict[s]
		if b {
			fmt.Println(v)
		} else {
			fmt.Println(-1)
		}
	}
}
商品の検索
package main
import "fmt"

func main() {
	var n, Q int
	fmt.Scan(&n, &Q)
	dict := make(map[string]int)
	for i := 1; i <= n; i++ {
		var s string
		fmt.Scan(&s)
		_, b := dict[s]
		if !b {
			dict[s] = i
		}
	}
	for i := 0; i < Q; i++ {
		var t string
		fmt.Scan(&t)
		j, b := dict[t]
		if b {
			fmt.Println(j)
		} else {
			fmt.Println(-1)
		}
	}
}

Java
数値の出現率

Javaでは、getOrDefaultを用いると便利です。

import java.util.*;

public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		Map<Integer, Integer> C = new HashMap<>();
		for (int i = 0; i < n; i++) {
			int a = sc.nextInt();
			C.put(a, C.getOrDefault(a, 0) + 1);
		}
		sc.close();
		for (int i = 0; i < 10; i++) {
			if (i > 0) System.out.print(' ');
			System.out.print(C.getOrDefault(i, 0));
		}
		System.out.println();
	}
}
英小文字の出現率
import java.util.*;

public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		String s = sc.next();
		sc.close();
		Map<Character, Integer> C = new HashMap<>();
		for (int i = 0; i < n; i++) {
			char c = s.charAt(i);
			C.put(c, C.getOrDefault(c, 0) + 1);
		}
		for (char c = 'a'; c <= 'z'; c++) {
			System.out.print(C.getOrDefault(c, 0));
			if (c < 'z') System.out.print(' ');
		}
		System.out.println();
	}
}
文字列の出現率

Javaでは、キーの辞書順に管理したい場合はTreeMapを使うと便利です。

import java.util.*;

public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		Map<String, Integer> C = new TreeMap<>();
		for (int i = 0; i < n; i++) {
			String s = sc.next();
			C.put(s, C.getOrDefault(s, 0) + 1);
		}
		sc.close();
		for (String s : C.keySet()) {
			System.out.println(s + ' ' + C.get(s));
		}
	}
}
価格の算出
import java.util.*;

public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		int m = sc.nextInt();
		Map<String, Integer> dict = new HashMap<>();
		for (; n > 0; n--) {
			dict.put(sc.next(), sc.nextInt());
		}
		for (; m > 0; m--) {
			String s = sc.next();
			if (dict.containsKey(s)) {
				System.out.println(dict.get(s));
			} else {
				System.out.println(-1);
			}
		}
		sc.close();
	}
}
商品の検索
import java.util.*;

public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		int Q = sc.nextInt();
		Map<String, Integer> dict = new HashMap<>();
		for (int i = 1; i <= n; i++) {
			String s = sc.next();
			if (!dict.containsKey(s)) {
				dict.put(s, i);
			}
		}
		for (; Q > 0; Q--) {
			String t = sc.next();
			if (dict.containsKey(t)) {
				System.out.println(dict.get(t));
			} else {
				System.out.println(-1);
			}
		}
		sc.close();
	}
}

JavaScript
数値の出現率
const [[N], A] = require("fs").readFileSync("/dev/stdin", "utf8").trim().split('\n').map(s => s.split(' ').map(Number));
const C = {};
for (var i = 0; i < N; i++) {
	if (!(A[i] in C)) C[A[i]] = 0;
	C[A[i]]++;
}
for (var i = 0; i < 10; i++) {
	if (i) process.stdout.write(' ');
	if (i in C) process.stdout.write(C[i].toString());
	else process.stdout.write('0');
}
console.log();
英小文字の出現率
const lines = require("fs").readFileSync("/dev/stdin", "utf8").trim().split('\n');
const N = Number(lines[0]);
const S = lines[1];
const C = {};
for (var i = 0; i < N; i++) {
	if (!(S[i] in C)) C[S[i]] = 0;
	C[S[i]]++;
}
for (var c = 'a'.charCodeAt(0); c <= 'z'.charCodeAt(0); c++) {
	if (String.fromCharCode(c) in C) process.stdout.write(C[String.fromCharCode(c)].toString());
	else process.stdout.write('0');
	if (c < 'z'.charCodeAt(0)) process.stdout.write(' ');
}
console.log();
文字列の出現率
const [n, ...S] = require("fs").readFileSync("/dev/stdin", "utf8").trim().split('\n');
const N = Number(n);
const C = {};
for (var i = 0; i < N; i++) {
	if (!(S[i] in C)) C[S[i]] = 0;
	C[S[i]]++;
}
const keys = Object.keys(C);
keys.sort();
keys.forEach(key => console.log(key, C[key]));
価格の算出
const lines = require("fs").readFileSync("/dev/stdin", "utf8").trim().split('\n');
let [n, m] = lines.shift().split(' ').map(Number);
const dict = {};
while (n--) {
	const [a, b] = lines.shift().split(' ');
	dict[a] = Number(b);
}
while (m--) {
	const s = lines.shift();
	if (s in dict) console.log(dict[s]);
	else console.log(-1);
}
商品の検索
const lines = require("fs").readFileSync("/dev/stdin", "utf8").trim().split('\n');
let [n, Q] = lines.shift().split(' ').map(Number);
const dict = {};
for (var i = 1; i <= n; i++) {
	const s = lines.shift();
	if (!(s in dict)) dict[s] = i;
}
while (Q--) {
	const t = lines.shift();
	if (t in dict) console.log(dict[t]);
	else console.log(-1);
}

Kotlin
数値の出現率
fun main() {
	val n = readln().toInt()
	val A = readln().split(' ').map { it.toInt() }
	val C = mutableMapOf<Int, Int>()
	for (i in 0 until n) C.put(A[i], C.getOrDefault(A[i], 0) + 1)
	for (i in 0..9) {
		if (i > 0) print(' ')
		print(C.getOrDefault(i, 0))
	}
	println()
}
英小文字の出現率
fun main() {
	val n = readln().toInt()
	val S = readln()
	val C = mutableMapOf<Char, Int>()
	for (i in 0 until n) C.put(S[i], C.getOrDefault(S[i], 0) + 1)
	for (c in 'a'..'z') {
		print(C.getOrDefault(c, 0))
		if (c < 'z') print(' ')
	}
	println()
}
文字列の出現率
import java.util.TreeMap

fun main() {
	val C = TreeMap<String, Int>()
	repeat(readln().toInt()) {
		val s = readln()
		C.put(s, C.getOrDefault(s, 0) + 1)
	}
	for (s in C.keys) println(s + ' ' + C[s])
}
価格の算出
fun main() {
	val (n, m) = readln().split(' ').map { it.toInt() }
	val dict = mutableMapOf<String, Int>()
	repeat (n) {
		val (a, b) = readln().split(' ')
		dict.put(a, b.toInt())
	}
	repeat (m) {
		val s = readln()
		println(if (dict.containsKey(s)) dict.get(s) else -1)
	}
}
商品の検索
fun main() {
	val (n, Q) = readln().split(' ').map { it.toInt() }
	val dict = mutableMapOf<String, Int>()
	for (i in 1..n) {
		val s = readln()
		if (!dict.containsKey(s)) dict.put(s, i)
	}
	repeat (Q) {
		val t = readln()
		println(if (dict.containsKey(t)) dict.get(t) else -1)
	}
}

PHP
数値の出現率
<?php
	$N = intval(fgets(STDIN));
	$A = array_map("intval", explode(' ', fgets(STDIN)));
	$C = [];
	foreach ($A as $a) {
		if (!array_key_exists($a, $C)) $C[$a] = 0;
		$C[$a]++;
	}
	for ($i = 0; $i < 10; $i++) {
		if ($i) echo ' ';
		if (array_key_exists($i, $C)) echo $C[$i];
		else echo 0;
	}
	echo PHP_EOL;
?>
英小文字の出現率
<?php
	$N = intval(fgets(STDIN));
	$S = trim(fgets(STDIN));
	$C = [];
	for ($i = 0; $i < $N; $i++) {
		if (!array_key_exists($S[$i], $C)) $C[$S[$i]] = 0;
		$C[$S[$i]]++;
	}
	for ($c = ord('a'); $c <= ord('z'); $c++) {
		if (array_key_exists(chr($c), $C)) echo $C[chr($c)];
		else echo 0;
		if ($c < ord('z')) echo ' ';
	}
	echo PHP_EOL;
?>
文字列の出現率
<?php
	$N = intval(fgets(STDIN));
	$C = [];
	for ($i = 0; $i < $N; $i++) {
		$s = trim(fgets(STDIN));
		if (!array_key_exists($s, $C)) $C[$s] = 0;
		$C[$s]++;
	}
	ksort($C);
	foreach (array_keys($C) as $s) echo $s, ' ', $C[$s], PHP_EOL;
?>
価格の算出
<?php
	[$n, $m] = array_map("intval", explode(' ', fgets(STDIN)));
	$dict = [];
	while ($n--) {
		[$a, $b] = explode(' ', fgets(STDIN));
		$dict[$a] = intval($b);
	}
	while ($m--) {
		$s = trim(fgets(STDIN));
		if (array_key_exists($s, $dict)) echo $dict[$s];
		else echo -1;
		echo PHP_EOL;
	}
?>
商品の検索
<?php
	[$n, $m] = array_map("intval", explode(' ', fgets(STDIN)));
	$dict = [];
	for ($i = 1; $i <= $n; $i++) {
		$s = trim(fgets(STDIN));
		if (!array_key_exists($s, $dict)) $dict[$s] = $i;
	}
	while ($m--) {
		$t = trim(fgets(STDIN));
		if (array_key_exists($t, $dict)) echo $dict[$t];
		else echo -1;
		echo PHP_EOL;
	}
?>

Perl
数値の出現率
my $n = int(<STDIN>);
my @A = map { int($_) } split ' ', <STDIN>;
my %C;
foreach my $a (@A) {
	$C{$a}++;
}
for my $i (0..9) {
	if ($i) {
		print ' ';
	}
	if (exists($C{$i})) {
		print $C{$i};
	} else {
		print 0;
	}
}
print $/;
英小文字の出現率
my $n = int(<STDIN>);
chomp(my $s = <STDIN>);
my %C;
foreach my $c (split '', $s) {
	$C{$c}++;
}
foreach my $c ('a'..'z') {
	if (exists($C{$c})) {
		print $C{$c};
	} else {
		print 0;
	}
	if ($c lt 'z') {
		print ' ';
	}
}
print $/;
文字列の出現率
my %C;
foreach (1..int(<STDIN>)) {
	chomp(my $s = <STDIN>);
	$C{$s}++;
}
foreach $s (sort keys %C) {
	print "$s $C{$s}$/";
}
価格の算出
my ($n, $m) = map { int($_) } split ' ', <STDIN>;
my %dict;
for (1..$n) {
	my ($a, $b) = split ' ', <STDIN>;
	$dict{$a} = int($b);
}
for (1..$m) {
	chomp(my $s = <STDIN>);
	if (exists($dict{$s})) {
		print $dict{$s}, $/;
	} else {
		print -1, $/;
	}
}
商品の検索
my ($n, $Q) = map { int($_) } split ' ', <STDIN>;
my %dict;
for $i (1..$n) {
	chomp(my $s = <STDIN>);
	if (!exists($dict{$s})) {
		$dict{$s} = $i;
	}
}
for (1..$Q) {
	chomp(my $t = <STDIN>);
	if (exists($dict{$t})) {
		print $dict{$t}, $/;
	} else {
		print -1, $/;
	}
}

Python3
数値の出現率

標準のdictを使う方法と、collections.defaultdictを用いる方法を記載します。

n = int(input())
A = list(map(int, input().split()))
C = dict()
for a in A:
	if a not in C:
		C[a] = 0
	C[a] += 1
for i in range(10):
	if i:
		print(end=' ')
	print(C[i] if i in C else 0, end='')
print()
from collections import defaultdict
n = int(input())
A = list(map(int, input().split()))
C = defaultdict(int)
for a in A:
	C[a] += 1
for i in range(10):
	if i:
		print(end=' ')
	print(C[i], end='')
print()
英小文字の出現率
n = int(input())
S = input()
C = {}
for i in range(n):
	c = S[i]
	if c not in C:
		C[c] = 0
	C[c] += 1
for i in range(ord('a'), ord('z')):
	c = chr(i)
	print(C[c] if c in C else 0, end=' ')
print(C['z'] if 'z' in C else 0)	
from collections import defaultdict
n = int(input())
S = input()
C = defaultdict(int)
for c in S:
	C[c] += 1
for c in "".join(chr(i) for i in range(ord('a'), ord('z'))):
	print(C[c], end=' ')
print(C['z'])
文字列の出現率
n = int(input())
C = {}
for _ in range(n):
	s = input()
	if s not in C:
		C[s] = 0
	C[s] += 1
for s in sorted(C):
	print(s, C[s])
from collections import defaultdict
S = [input() for _ in range(int(input()))]
C = defaultdict(int)
for s in S:
	C[s] += 1
for s in sorted(C):
	print(s, C[s])
価格の算出
n, m = map(int, input().split())
D = {a: int(b) for a, b in [input().split() for _ in range(n)]}
for _ in range(m):
	s = input()
	print(D[s] if s in D else -1)
商品の検索
n, Q = map(int, input().split())
D = {}
for i in range(n):
	s = input()
	if s not in D:
		D[s] = i + 1
for _ in range(Q):
	t = input()
	print(D[t] if t in D else -1)

Ruby
数値の出現率
N = gets.to_i
A = gets.split.map(&:to_i)
C = {}
A.each do |a|
	if !C.key?(a)
		C[a] = 0
	end
	C[a] += 1
end
10.times do |i|
	if i > 0
		print ' '
	end
	print C.key?(i) ? C[i] : 0
end
puts
英小文字の出現率
N = gets.to_i
S = gets.chomp
C = {}
N.times do |i|
	c = S[i]
	if !C.key?(c)
		C[c] = 0
	end
	C[c] += 1
end
('a'..'z').each do |c|
	print C.key?(c) ? C[c] : 0
	if c < 'z'
		print ' '
	end
end
puts
文字列の出現率
N = gets.to_i
C = {}
N.times do
	s = gets.chomp
	if !C.key?(s)
		C[s] = 0
	end
	C[s] += 1
end
C.sort.each do |k, v|
	print k, ' ', v, "\n"
end
価格の算出
N, M = gets.split.map(&:to_i)
dict = {}
N.times do
	a, b = gets.split
	dict[a] = b.to_i
end
M.times do
	s = gets.chomp
	p dict.key?(s) ? dict[s] : -1
end
商品の検索
N, Q = gets.split.map(&:to_i)
dict = {}
(1..N).each do |i|
	s = gets.chomp
	if !dict.key?(s)
		dict[s] = i
	end
end
Q.times do
	t = gets.chomp
	p dict.key?(t) ? dict[t] : -1
end

Scala
数値の出現率
import scala.io.StdIn._
import scala.collection.mutable

object Main extends App{
	val N = readInt()
	val A = readLine().split(' ').map { _.toInt }
	val C = mutable.Map[Int, Int]()
	for (a <- A) {
		if (!C.contains(a)) C(a) = 0
		C(a) += 1
	}
	for (i <- 0 until 10) {
		if (i > 0) print(' ')
		print(if (C.contains(i)) C(i) else 0)
	}
	println()
}
英小文字の出現率
import scala.io.StdIn._
import scala.collection.mutable

object Main extends App{
	val N = readInt()
	val S = readLine()
	val C = mutable.Map[Char, Int]()
	for (i <- 0 until N) {
		val c = S(i)
		if (!C.contains(c)) C(c) = 0
		C(c) += 1
	}
	for (c <- 'a' to 'z') {
		print(if (C.contains(c)) C(c) else 0)
		if (c < 'z') print(' ')
	}
	println()
}
文字列の出現率
import scala.io.StdIn._
import scala.collection.mutable

object Main extends App{
	val n = readInt()
	val C = mutable.TreeMap[String, Int]()
	for (_ <- 0 until n) {
		val s = readLine()
		if (!C.contains(s)) C(s) = 0
		C(s) += 1
	}
	for ((k, v) <- C) println(k + ' ' + v)
}
価格の算出
import scala.io.StdIn._
import scala.collection.mutable

object Main extends App{
	val Array(n, m) = readLine().split(' ').map { _.toInt }
	val dict = mutable.Map[String, Int]()
	for (_ <- 0 until n) {
		val Array(a, b) = readLine().split(' ')
		dict(a) = b.toInt
	}
	for (_ <- 0 until m) {
		val s = readLine()
		println(if (dict.contains(s)) dict(s) else -1)
	}
}
商品の検索
import scala.io.StdIn._
import scala.collection.mutable

object Main extends App{
	val Array(n, q) = readLine().split(' ').map { _.toInt }
	val dict = mutable.Map[String, Int]()
	for (i <- 1 to n) {
		val s = readLine()
		if (!dict.contains(s)) dict(s) = i
	}
	for (_ <- 0 until q) {
		val t = readLine()
		println(if (dict.contains(t)) dict(t) else -1)
	}
}

Swift
数値の出現率
let n = Int(readLine()!)!
let A = readLine()!.split(separator: " ").compactMap { Int($0) }
var C: [Int:Int] = [:]
for i in 0..<n {
	let a = A[i]
	if C[a] == nil {
		C[a] = 0
	}
	C[a] = C[a]! + 1
}
for i in 0..<10 {
	if i > 0 {
		print(terminator: " ")
	}
	print(C[i] == nil ? 0 : C[i]!, terminator:"")
}
print()
英小文字の出現率
let n = Int(readLine()!)!
let S = Array(readLine()!)
var C: [Character:Int] = [:]
for i in 0..<n {
	let c = S[i]
	if C[c] == nil {
		C[c] = 0
	}
	C[c] = C[c]! + 1
}
for u in Unicode.Scalar("a").value...Unicode.Scalar("z").value {
	let c = Character(Unicode.Scalar(u)!)
	print(C[c] == nil ? 0 : C[c]!, terminator:"")
	if u < Unicode.Scalar("z").value {
		print(terminator: " ")
	}
}
print()
文字列の出現率
let n = Int(readLine()!)!
var C: [String:Int] = [:]
for _ in 0..<n {
	let s = readLine()!
	if C[s] == nil {
		C[s] = 0
	}
	C[s] = C[s]! + 1
}
for item in C.sorted(by: { $0.key < $1.key }) {
	print(item.key, item.value)
}
価格の算出
let nm = readLine()!.split(separator: " ").compactMap { Int($0) }
let (n, m) = (nm[0], nm[1])
var dict: [String:Int] = [:]
for _ in 0..<n {
	let ab = readLine()!.split(separator: " ")
	let (a, b) = (ab[0], Int(ab[1])!)
	dict[String(a)] = b 
}
for _ in 0..<m {
	let s = readLine()!
	if let c = dict[s] {
		print(c)
	} else {
		print(-1)
	}
}
商品の検索
let nq = readLine()!.split(separator: " ").compactMap { Int($0) }
let (n, q) = (nq[0], nq[1])
var dict: [String:Int] = [:]
for i in 1...n {
	let s = readLine()!
	if dict[s] == nil {
		dict[s] = i
	}
}
for _ in 0..<q {
	let t = readLine()!
	if let c = dict[t] {
		print(c)
	} else {
		print(-1)
	}
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?