[過去ログ] プログラミングのお題スレ Part15 (1002レス)
前次1-
抽出解除 レス栞

このスレッドは過去ログ倉庫に格納されています。
次スレ検索 歴削→次スレ 栞削→次スレ 過去ログメニュー
514
(8): 2019/09/21(土)16:12 ID:ZyFDPzPp(1) AAS
お題:正の整数が与えられるので、英語の序数に変換せよ
1 => 1st
23 => 23rd
12 => 12th
515
(1): 2019/09/21(土)16:40 ID:6wFtRpPA(3/5) AAS
>>514 Perl5

%o = qw{1 st 2 nd 3 rd};
$o = $o{$_}//'th', print "$_$o\n" for 1..10,12,23;

実行
~ $ perl 15_514.pl
1st
2nd
3rd
4th
5th
省7
516: 2019/09/21(土)16:54 ID:6wFtRpPA(4/5) AAS
>>514 Perl5、 >>515 はもう少しコンパクトに書けた

%o = qw{1 st 2 nd 3 rd};
printf "$_%s\n", $o{$_}//'th' for 1..10,12,23;
517: 2019/09/21(土)17:38 ID:uZ0K83Mw(2/2) AAS
>>514 ruby
https://ideone.com/3Mupna
520: 2019/09/21(土)19:41 ID:6wFtRpPA(5/5) AAS
>>514 Perl5、>>519 で指摘された誤りの修正 テヘペロ

%h = qw{1 st 2 nd 3 rd};
for (1..4,11,12,13,21,22,23,101,102,103,111,112,113,121,122,123) {
 /(\d?)(\d)$/;
 printf "$_ => $_%s\n", $1 eq 1 ? 'th' : $h{$2}//'th';
}

実行結果
~ $ perl 15_514.pl
1 => 1st
2 => 2nd
省17
533
(1): 2019/09/22(日)08:19 ID:uuB9aO9i(1/2) AAS
>>514 Ruby

suffixes = %w[th st nd rd]
f = -> n {(-(-((n - 10) / 10 % 10) / 9)) * 41 / (n % 10 * 10 + 11) * (n % 10)}

[
  1, 2, 3, 4, 11, 12, 13, 21, 22, 23, 101, 102, 103, 111, 112, 113, 121, 122, 123
].each{|v| puts '%1$d => %1$d%2$s' % [v, suffixes[f[v]]]}

# =>
1 => 1st
2 => 2nd
3 => 3rd
省16
538: 2019/09/22(日)10:14 ID:UtdvR7ZT(1) AAS
>>514 Lua
function f(n)
   local r,x
   x=n%10
   if n%100-x==10 or x<1 or x>3 then
   r="th"
   else
   r=({"st","nd","rd"})[x]
   end
   return n..r
省1
539: 2019/09/22(日)11:43 ID:OEThTvH6(1/2) AAS
>>514 JavaScript
const f=n=>n+=[,'st','nd','rd'][n%100>>3^1&&n%10]||'th'
実行結果略
566: 2019/09/22(日)23:25 ID:35++XhB6(6/6) AAS
>>514 Pharo/Squeak Smalltalk

| suffixes fn |

suffixes := #(st nd rd), (Array new: 7 withAll: #th).
suffixes := (0 to: 9) gather: [:idx | suffixes].
suffixes from: 11 to: 13 put: #th.

fn := [:n | n asString, (suffixes atWrap: n)].

fn value: 1. "=> '1st' "
fn value: 23. "=> '23rd' "
fn value: 12. "=> '12th' "
前次1-
スレ情報 赤レス抽出 画像レス抽出 歴の未読スレ AAサムネイル

ぬこの手 ぬこTOP 1.400s*