Today is month M, day D.
You are given the names and birthdays (month and day) of n friends.
Print the names one per line, starting with the friend whose birthday comes soonest counting from today.
A friend whose birthday is today comes first, because it is 0 days away.
A friend whose birthday date is earlier than today has already had this year's birthday and waits for next year's. These friends come after the friends whose birthdays are today or later, in date order starting from January.
Friends with the same birthday are placed in dictionary order of their names (alphabetical; if one name equals the beginning of another, the shorter one comes first).
Input
The first line has M and D separated by one space. The second line has n. Each of the next n lines has a friend's name, birthday month and birthday day, separated by single spaces. 1 ≤ n ≤ 100. A name is 1 to 10 lowercase English letters and all names are different. Today and every birthday are real calendar dates, and February 29 is never given
Output
n lines. The names, one per line, starting with the friend whose birthday comes soonest
Example 1 · stdin
10 5
6
mina 10 5
joon 3 14
sora 12 25
hana 9 30
dan 10 20
bora 12 25
stdout
mina
dan
bora
sora
joon
hana
main.py
Error List00F8 ↓ · ⇧F8 ↑
Input (stdin)
When you run, these lines are fed to input()/stdin in order (the program doesn't stop to ask).
$ Ready
Open this on a computer to write and run code. On mobile you can read the problem and the solutions.
In other languagesShow solutions by language · 8 languages
Languages differ in how you sort by several criteria. In Python, give sorted(friends, key=key) a tuple key (passed, month, day, name) and it compares from the first slot on. Comparing dates also works in one go with tuples: (m, d) < (M, D). C++ does the same with std::tie(…) < std::tie(…), but the function you pass to std::sort returns a bool: 'does a come before b?'. The function you pass to JS/TS sort, C qsort, C# List.Sort and Craykon list.Sort(function) returns a number instead: negative if the first comes first, 0 if equal, positive if the second comes first. In JS you chain with ||, as in a.passed - b.passed || a.month - b.month || …, so a 0 (equal) falls through to the next criterion. Java chains criteria with Comparator.comparingInt(Friend::passed).thenComparingInt(Friend::month)…. Names are compared with strcmp in C, string.CompareOrdinal in C#, and < in JS and Craykon. Trap one: sorting by month and day alone puts the birthdays that already passed this year at the front. The first line of the example becomes joon (March 14). Trap two: a friend whose birthday is today has not passed. If you test 'passed' with <= instead of <, mina in the example goes to the very end. Trap three: the month and day you read from the input are strings. Compared without converting, "10" comes before "9" and "12" before "3", so the example comes out as mina, bora, sora, joon, hana, dan. Convert with Python int(), JS Number(), Craykon ToNumber(). Trap four: if you pass JS sort a function that returns true/false the C++ way, false is read as 0, meaning 'equal'. A negative number never appears, so in Node the example is not sorted at all and comes out in input order.
Pythonmain.py · 20 lines
import syslines = sys.stdin.read().split("\n")M, D = map(int, lines[0].split())n = int(lines[1])friends = []for line in lines[2:2 + n]: name, m, d = line.split() friends.append((name, int(m), int(d)))# 정렬 열쇠: (올해 생일이 이미 지났나, 월, 일, 이름). 튜플은 앞 칸부터 차례로 견준다.# False가 True보다 앞이라 아직 지나지 않은 생일이 먼저 온다. 오늘이 생일이면 지나지 않은 것이다.def key(friend): name, m, d = friend return ((m, d) < (M, D), m, d, name)for name, m, d in sorted(friends, key=key): print(name)
JavaScriptmain.js · 21 lines
const lines = require("fs").readFileSync(0, "utf8").split("\n");const [M, D] = lines[0].trim().split(" ").map(Number);const n = Number(lines[1]);const friends = [];for (let i = 2; i < 2 + n; i++) { const [name, m, d] = lines[i].trim().split(" "); const month = Number(m); const day = Number(d); // 올해 생일이 이미 지났으면 1, 아니면 0. 오늘이 생일이면 지나지 않은 것이다. const passed = month < M || (month === M && day < D) ? 1 : 0; friends.push({ name, month, day, passed });}// 견주는 함수는 앞이 먼저면 음수, 뒤가 먼저면 양수를 돌려준다. 0이면 || 뒤의 다음 기준으로 넘어간다.friends.sort( (a, b) => a.passed - b.passed || a.month - b.month || a.day - b.day || (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));console.log(friends.map((f) => f.name).join("\n"));
TypeScriptmain.ts · 30 lines
import { readFileSync } from "node:fs";interface Friend { name: string; month: number; day: number; passed: number; // 올해 생일이 이미 지났으면 1, 아니면 0}const lines: string[] = readFileSync(0, "utf8").split("\n");const [M, D]: number[] = lines[0].trim().split(" ").map(Number);const n: number = Number(lines[1]);const friends: Friend[] = [];for (let i = 2; i < 2 + n; i++) { const [name, m, d]: string[] = lines[i].trim().split(" "); const month = Number(m); const day = Number(d); // 오늘이 생일이면 지나지 않은 것이다. const passed = month < M || (month === M && day < D) ? 1 : 0; friends.push({ name, month, day, passed });}// 견주는 함수는 앞이 먼저면 음수, 뒤가 먼저면 양수를 돌려준다. 0이면 || 뒤의 다음 기준으로 넘어간다.friends.sort( (a: Friend, b: Friend): number => a.passed - b.passed || a.month - b.month || a.day - b.day || (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));console.log(friends.map((f: Friend): string => f.name).join("\n"));
JavaMain.java · 38 lines
import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.util.ArrayList;import java.util.Comparator;import java.util.List;public class Main { // passed: 올해 생일이 이미 지났으면 1, 아니면 0 record Friend(String name, int month, int day, int passed) {} public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String[] today = in.readLine().trim().split(" "); int M = Integer.parseInt(today[0]); int D = Integer.parseInt(today[1]); int n = Integer.parseInt(in.readLine().trim()); List<Friend> friends = new ArrayList<>(); for (int i = 0; i < n; i++) { String[] parts = in.readLine().trim().split(" "); int month = Integer.parseInt(parts[1]); int day = Integer.parseInt(parts[2]); // 오늘이 생일이면 지나지 않은 것이다. int passed = (month < M || (month == M && day < D)) ? 1 : 0; friends.add(new Friend(parts[0], month, day, passed)); } // 기준을 차례로 잇는다: 앞 기준이 같을 때만 다음 기준을 본다. friends.sort(Comparator.comparingInt(Friend::passed) .thenComparingInt(Friend::month) .thenComparingInt(Friend::day) .thenComparing(Friend::name)); StringBuilder out = new StringBuilder(); for (Friend f : friends) { out.append(f.name()).append('\n'); } System.out.print(out); }}
C#Main.cs · 39 lines
using System;using System.Collections.Generic;using System.Text;class Program{ static void Main() { string[] today = Console.ReadLine().Trim().Split(' '); int M = int.Parse(today[0]); int D = int.Parse(today[1]); int n = int.Parse(Console.ReadLine().Trim()); // passed: 올해 생일이 이미 지났으면 1, 아니면 0 var friends = new List<(string name, int month, int day, int passed)>(); for (int i = 0; i < n; i++) { string[] parts = Console.ReadLine().Trim().Split(' '); int month = int.Parse(parts[1]); int day = int.Parse(parts[2]); // 오늘이 생일이면 지나지 않은 것이다. int passed = (month < M || (month == M && day < D)) ? 1 : 0; friends.Add((parts[0], month, day, passed)); } // 견주는 함수는 앞이 먼저면 음수, 같으면 0, 뒤가 먼저면 양수를 돌려준다. friends.Sort((a, b) => { if (a.passed != b.passed) return a.passed.CompareTo(b.passed); if (a.month != b.month) return a.month.CompareTo(b.month); if (a.day != b.day) return a.day.CompareTo(b.day); return string.CompareOrdinal(a.name, b.name); // 글자 코드 순서로 견준다 }); var sb = new StringBuilder(); foreach (var f in friends) { sb.Append(f.name).Append('\n'); } Console.Write(sb); }}
C++main.cpp · 32 lines
#include <algorithm>#include <iostream>#include <string>#include <tuple>#include <vector>using namespace std;struct Friend { string name; int month, day; bool passed; // 올해 생일이 이미 지났는가};int main() { int M, D, n; cin >> M >> D >> n; vector<Friend> friends(n); for (Friend &f : friends) { cin >> f.name >> f.month >> f.day; // pair는 앞 칸부터 견준다. 오늘이 생일이면 지나지 않은 것이다. f.passed = make_pair(f.month, f.day) < make_pair(M, D); } // C++의 견주는 함수는 "a가 b보다 앞인가"를 bool로 돌려준다. // tie로 묶으면 앞 칸부터 차례로 견준다(false가 true보다 앞). sort(friends.begin(), friends.end(), [](const Friend &a, const Friend &b) { return tie(a.passed, a.month, a.day, a.name) < tie(b.passed, b.month, b.day, b.name); }); for (const Friend &f : friends) { cout << f.name << '\n'; } return 0;}
Cmain.c · 37 lines
#include <stdio.h>#include <stdlib.h>#include <string.h>typedef struct { char name[11]; int month, day; int passed; /* 올해 생일이 이미 지났으면 1, 아니면 0 */} Friend;/* qsort가 부르는 견주는 함수: 앞이 먼저면 음수, 같으면 0, 뒤가 먼저면 양수 */static int compare_friends(const void *pa, const void *pb) { const Friend *a = pa; const Friend *b = pb; if (a->passed != b->passed) return a->passed - b->passed; if (a->month != b->month) return a->month - b->month; if (a->day != b->day) return a->day - b->day; return strcmp(a->name, b->name);}int main(void) { int M, D, n; static Friend friends[100]; scanf("%d %d", &M, &D); scanf("%d", &n); for (int i = 0; i < n; i++) { Friend *f = &friends[i]; scanf("%10s %d %d", f->name, &f->month, &f->day); /* 오늘이 생일이면 지나지 않은 것이다. */ f->passed = (f->month < M || (f->month == M && f->day < D)) ? 1 : 0; } qsort(friends, n, sizeof(Friend), compare_friends); for (int i = 0; i < n; i++) { printf("%s\n", friends[i].name); } return 0;}
Craykonmain.cray · 60 lines
오늘 = Console.ReadNumbers();M = 오늘[0];D = 오늘[1];n = Console.ReadLine().ToNumber();names = [];months = [];days = [];passed = []; // 올해 생일이 이미 지났으면 1, 아니면 0order = []; // 친구 번호를 담아 두고 이 목록을 정렬한다for (i = 0; i < n; i++){ parts = Console.ReadLine().Trim().Split(" "); m = parts[1].ToNumber(); d = parts[2].ToNumber(); names.Add(parts[0]); months.Add(m); days.Add(d); // 오늘이 생일이면 지나지 않은 것이다 if (m < M || m == M && d < D) { passed.Add(1); } else { passed.Add(0); } order.Add(i);}// 견주는 함수: 앞이 먼저면 음수, 같으면 0, 뒤가 먼저면 양수를 돌려준다먼저오는생일(a, b){ if (passed[a] != passed[b]) { return passed[a] - passed[b]; } if (months[a] != months[b]) { return months[a] - months[b]; } if (days[a] != days[b]) { return days[a] - days[b]; } if (names[a] < names[b]) { return -1; } if (names[a] > names[b]) { return 1; } return 0;}order.Sort(먼저오는생일);foreach (i in order){ Console.WriteLine(names[i]);}