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ラーニングレベルアップ問題集の配列のサイズの変更をやってみました。


問題


Visual Basic系では

ReDim Preserve A(m-1)

というものがあります。
それ相応の関数やメソッドのない言語の場合、$n>N$の場合には全要素0・長さ$n-N$の配列を結合する方法もあります。


C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {
	int N, n;
	scanf("%d %d", &N, &n);
	int *A = malloc(sizeof(int) * N);
	for (int i = 0; i < N; i++) scanf("%d", &A[i]);
	A = realloc(A, sizeof(int) * n);
	if (n > N) memset(A + N, 0, sizeof(int) * (n - N));
	for (int i = 0; i < n; i++) printf("%d\n", A[i]);
	return 0;
}

C++
#include <iostream>
#include <vector>
using namespace std;

int main() {
	int N, n;
	cin >> N >> n;
	vector<int> A(N);
	for (int i = 0; i < N; i++) cin >> A[i];
	A.resize(n);
	for (int i = 0; i < n; i++) cout << A[i] << endl;
	return 0;
}

C#
using System;
using System.Linq;

class Program
{
	public static void Main()
	{
		int[] Nn = Array.ConvertAll(Console.ReadLine().Split(), int.Parse);
		int N = Nn[0], n = Nn[1];
		int[] A = Enumerable.Range(0, N).Select(_ => int.Parse(Console.ReadLine())).ToArray();
		Array.Resize(ref A, n);
		for (int i = 0; i < n; i++) Console.WriteLine(A[i]);
	}
}

Go
package main
import "fmt"

func main() {
	var N, n int
	fmt.Scan(&N, &n)
	A := make([]int, N)
	for i := 0; i < N; i++ {
		fmt.Scan(&A[i])
	}
	if n < N {
		A = A[:n]
	} else if n > N {
		A = append(A, make([]int, n - N)...)
	}
	for i := 0; i < n; i++ {
		fmt.Println(A[i])
	}
}

Java
import java.util.*;
import java.util.stream.*;

public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int N = sc.nextInt();
		int n = sc.nextInt();
		int[] A = IntStream.range(0, N).map(__ -> sc.nextInt()).toArray();
		sc.close();
		A = Arrays.copyOf(A, n);
		for (int i = 0; i < n; i++) System.out.println(A[i]);
	}
}

JavaScript
let [[N, n], ...A] = require("fs").readFileSync("/dev/stdin", "utf8").trim().split('\n').map((s, i) => i ? Number(s) : s.split(' ').map(Number));
A.length = n;
for (var i = N; i < n; i++) A[i] = 0;
for (var i = 0; i < n; i++) console.log(A[i]);

Kotlin
fun main() {
	val (N, n) = readLine()!!.split(" ").map { it.toInt() }
	var A = Array(N) { readLine()!!.toInt() }
	if (n < N) A = A.toList().take(n).toTypedArray()
	else if (n > N) A = A.plus(Array(n - N) { 0 })
	for (i in 0 until n) println(A[i])
}

PHP
<?php
	[$N, $n] = array_map("intval", explode(' ', fgets(STDIN)));
	$A = [];
	for ($i = 0; $i < $N; $i++) $A[] = intval(fgets(STDIN));
	if ($n < $N) array_splice($A, $n);
	else if ($n > $N) array_splice($A, $N, 0, array_fill(0, $n - $N, 0));
	for ($i = 0; $i < $n; $i++)	echo $A[$i], PHP_EOL;
?>

Perl
my ($N, $n) = map { int($_) } split ' ', <STDIN>;
my @A;
for (1..$N) {
	push @A, int(<STDIN>);
}
if ($n < $N) {
	splice @A, $n;
} elsif ($n > $N) {
	splice @A, $N, 0, (0) x ($n - $N);
}
for (my $i = 0; $i < $n; $i++) {
	print $A[$i], $/;
}

Python3
N, n = map(int, input().split())
A = [int(input()) for _ in range(N)]
A = A[:n] + [0] * max(0, n - N)
for i in range(n):
	print(A[i])

Ruby
N, M = gets.split.map(&:to_i)
a = N.times.map { gets.to_i }
a = a[...M] + [0] * [0, M - N].max
M.times do |i|
	p a[i]
end

Scala
import scala.io.StdIn._

object Main extends App{
	val Array(n, m) = readLine().split(' ').map { _.toInt }
	var A = (0 until n).map { _ => readInt() }
	if (m < n) A = A.take(m)
	else if (m > n) A = A ++ Array.fill(m - n)(0)
	for (i <- 0 until m) println(A(i))
}

Swift
let Nn = readLine()!.split(separator: " ").compactMap { Int($0) }
let (N, n) = (Nn[0], Nn[1])
var A = (0..<N).map { _ in Int(readLine()!)! }
if n < N {
	A = Array(A.prefix(n))
} else if n > N {
	A += Array<Int>(repeating: 0, count: n - N)
}
for i in 0..<n {
	print(A[i])
}

VB.NET
Imports System

Module Main
	Sub Main()
		Dim nm() As String = Console.ReadLine.Split
		Dim n As Integer = Integer.Parse(nm(0))
		Dim m As Integer = Integer.Parse(nm(1))
		Dim A(n-1) As Integer
		For i As Integer = 0 to n - 1
			A(i) = Integer.Parse(Console.ReadLine)
		Next
		ReDim Preserve A(m-1)
		For i As Integer = 0 To m - 1
			Console.WriteLine(A(i))
		Next
	End Sub
End Module
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?