最小のファイルを見つける


19

ゴール:

現在のフォルダー内で最小のファイルを見つけるプログラムを作成します。

  • ファイルサイズはバイトまたは文字で測定されます。
  • 複数のファイルのサイズが同じ場合、いずれかを選択するか、すべてを表示できます。
  • フォルダーには少なくとも1つのファイルがあり、サイズが0のファイルはないと想定できます。
  • フォルダー内のすべてのファイルは、使用している言語でロードできると仮定します。

  • 現在のディレクトリにフォルダがないと仮定します。

入力:

次の場合を除き、プログラムはユーザーからの入力を受け付けません。

  • 言語に「現在のフォルダー」がない場合は、ユーザーにフォルダー名/パスを尋ねる場合があります。
  • ご使用の言語がコンピューター上のファイルに直接アクセスできない場合、ユーザーがファイルをアップロードできる場合があります。(たとえば、JavaScript)

出力:

最小のファイルの名前が表示されます。

  • どのファイルが選択されているかが明確である限り、先頭/末尾の記号を使用できます。
  • (すべてのファイルのリストを印刷することは規則に反します)。

ノート:

  • 標準の抜け穴は許可されていません。
  • フォルダー内のファイルを変更/作成/削除して結果を変更することはできません。
  • これはです。最短回答(バイト単位)が勝ちます。

1
私たちは、ファイルをとることができることができます 0の大きさを持っていますか?
— Rɪᴋᴇʀ

また、「フォルダ内のすべてのファイルにアクセスできると仮定する」とはどういう意味ですか?それは隠しファイルを表示する必要がないということですか?
— Rɪᴋᴇʀ

2
現在のフォルダーにフォルダーがないと仮定できますか?ファイルだけでなくファイルとフォルダーの両方を返す言語関数を使用している場合、すべての違いが生じます!
— -sergiol

1
必ずしも。現在のディレクトリ内に明確なディレクトリはなく、回答を無効にしないと想定できます。
— デニス

1
(申し訳ありませんが、すぐに返信しませんでした。私のインターネット接続は数日間ダウンしていました)隠しファイルをスキップできるようにすることに関する問題は、多くの抜け穴を開くように見えることです。「アクセスがやや難しい」ファイルをスキップできると、数バイト節約できるため、最初の9ファイルのみをチェックするなどのことができます。
— 12Me21

回答:


7

Vim 12バイト

!!ls -Sa
Gd{

オンラインでお試しください!

説明:

!!あるフィルタコマンドは。現在の行の内容を任意のシステムコマンドにパイプし、出力をバッファに送り返します。bashの方がvimより優れている場合、たとえば!!rev現在の行を逆にしたり!Gxxd、バッファーを16進ダンプしたりするために、外部ツールを使用するのに便利です。この場合、バッファは空なので:r!ls、コマンドの出力を現在の行に送るだけのに相当します。

カーソルは1行目にあり、最後の行を除くすべての行を削除します。ナイーブアプローチは

G       " Go to the last line
 k      " Go up one line
  d     " Delete:
   gg   "   Everything up to the first line

しかし、私たちはもっとうまくやることができます。私はで説明のように、この先端、{することができ、通常は(常にではない)に相当しますgg。ここでは、さらに良いです。動きがあるので、文字ベースではなくラインベースのようggで、私達はで私たちを残して、最初の行まで行く必要はありません

Gd{

16

Bash + coreutils、13バイト

ls -Sar|sed q

説明:

ls -Sar|sed q
ls            # list files
   -S         # sorted, biggest first
     a        # show hidden files
      r       # reversed (smallest first)
       |sed q # q is quit at first line that matches given regex, 
              # given regex is empty so guaranteed match.         

これを私自身の回答として投稿しましたが、あなたのものとあまりにも似ていると思います。ls -1Sa|tail -13バイト短くなり、出力がよりきれいになります。
— -orlp

@orlpのおかげ...!
— Rɪᴋᴇʀ

1
「-1」は必要ないと思います。パイプは1行に1つのファイルを自動的に配置します。
— GB

@EasterlyIrk GBは正しいと思います。ls端末への出力を検出した場合、出力を複数の列にフォーマットします。ただし、出力がパイプの場合、1行につき1つだけ実行されます。比較lsvsls|cat
— デジタルトラウマ

2バイト短縮:ls -Sar|sed q
— デジタル外傷

8

Pythonの2 3、94の 76 74 54バイト

@orlpのおかげで-18バイト
@Jonathan Allanのおかげで2バイト
チャレンジ仕様の変更により-20バイト

from os import*
print(min(listdir(),key=path.getsize))

print min(filter(path.isfile,listdir(".")),key=path.getsize)よりきれいで、かなり短い。
— -orlp

"."デフォルトであるため、Python 3に移動して2バイトを保存します。print(min(filter(path.isfile,listdir()),key=path.getsize))
— ジョナサンアラン

また、私は76ない77を数える
— ジョナサン・アラン

@JonathanAllan私が測定したバイト数カウントがwc1バイトより多くの私を与えた
— OVS

無関係なバイトは、Pythonには不要な末尾の改行によるものです。さらに、サブディレクトリが存在しないことを示すためにチャレンジが更新されたため、filterビット全体は不要です。print関数であるため、これもPython 3では機能しません。以下が機能し、大幅に短くなりますprint(min(listdir(),key=path.getsize))
— 。– Mego

8

PowerShell、30 24 21バイト

(ls|sort le*)[0].Name

オンラインでお試しください!

lsはのエイリアスですGet-ChildItem。にパイプされますsort-objectはlength属性でため、ファイルはサイズでソートされます。(...)[0]最初に(つまり、最小の)を取得するためにインデックスを付け、それを取得し.Nameます。暗黙的な出力Write-Outputは、プログラムの完了時に発生します。

ディレクトリにファイルのみが存在することが保証されているため、6バイトを節約しました。ConnorLSWのおかげでさらに3つ節約できました。


2
-fileファイルのみが現在のディレクトリにあるため、削除できませんか?
— ミュータントー

@Mutantoeはい-この回答を投稿した後、チャレンジに編集されました。ありがとう!
— AdmBorkBork

sort le*powershellが受け入れるので、いくつかのバイトを削るのに使用できます。
— colsw

@ConnorLSWはい、もちろんです。ありがとう!
— -AdmBorkBork

7

ルビー、61 40 38 37バイト

GBとValue Inkに感謝

p Dir[?*,".*"].min_by{|x|File.size x}

?を使用できます。Dir.pwdの代わりに、min_by {}を使用して最小のファイルを取得します。Dir.foreach(?.).min_by{|x|File.size x}38バイトで同じ結果を取得します。
— GB

@GBのおかげ!
— dkudriavtsev

ので、それは、「すべて」を見なければなりません言語の缶のアクセスをファイルすることを恥だDir[?*]はるかに短いですが、同様にUnixのファイルを隠さ含まれていません.bash_profile...
— バリューインク

Dir [?*、 "。?*"]が機能する可能性があります。私は試していません。そして、それはより短いです。
— GB

@GB実際にはになりますDir[?*,".*"]。グロブ文字列.?*は、ファイル.aが存在する場合、ファイルと一致しません。
— バリューインク

6

Mathematica、35バイト

FileNames[]~MinimalBy~FileByteCount

FileNames[]現在のディレクトリ内のすべてのファイル(およびディレクトリ)の名前のリストを作成します。~MinimalBy~FileByteCountバイト数が最小のファイルの名前を選択します。FileByteCountディレクトリに適用されると、大量のエラーがスローされますが、エラーによってプログラムが混乱することはありません。


6

Java 7、149 142バイト

String f(){String n="";long s=-1>>>1,p;for(java.io.File f:new java.io.File(".").listFiles())if((p=f.length())<s){n=f.getName();s=p;}return n;}

オンラインでお試しください!

CAD97のおかげで-7バイト


私はあなたがファイル::長さがファイルではない:: getTotalSpaceをしたいと思います
— CAD97

未テストのJava 8:()->java.utils.stream(new java.io.File(".").listFiles()).max((a,b)->a.length()-b.length).get().getName()104バイトのために
— CAD97

@ CAD97その通りです!私は...考えていた
— ポケ

6

SH(Linux / Unix) 15 14 13 14バイト

ls -aS|tail -1

-S サイズでソート(降順)、

-rtail -1リストの最後のファイルを反転して出力します。

@ Dennis 1バイトを保存してくれてありがとう@Dani_l 1バイトを保存してくれてありがとう。


最大のファイルが見つかりますか?
— デニス

気にしない、私は疲れています。tailただし、逆の代わりに使用することができ、これ-1はの省略形です-n1。
— デニス

更新@Dennis
— アベルトム

@EasterlyIrk今では:)なければならない
— アベルトム

@AbelTomかっこいい、修正してくれてありがとう。
— Rɪᴋᴇʀ

4

MATLAB /オクターブ、52 48バイト

d=dir;[~,n]=min([d.bytes]./~[d.isdir]);d(n).name

説明

これは、を使用して現在のディレクトリ内のすべてのファイルとフォルダのディレクトリリストを取得しますdir。の出力dirはstruct、ファイル名、ディレクトリであるかどうか、サイズ(バイト単位)などが含まれます。

我々は、次に、バイト単位で各サイズの配列を取ることができ[d.bytes]、それは、ディレクトリのか否かを示すブールと要素単位の分割を行う~[d.isdir]もたらすれるInfことにより(それ以外の場合は、ディレクトリ(ゼロによる除算)、およびバイト単位のサイズのWHERE分割1)。

の2番目の出力を使用してこの配列の最小のインデックスを見つけ、minそれを使用して初期構造体にインデックスを付け、名前を表示します。d(n).name


disp(...)出力を適切に印刷するには、出力を追加する必要があります。そうでない場合、たとえばans、フォルダー内で最小ではないというファイルが存在する場合、出力は、MATLABに不慣れなユーザーにとってどのファイルが最小であるかが明確になりません。
— トムカーペンター

@TomCarpenterうーん私がいることを意味する「のシンボルがあれば、ファイルが選択されている明らかだとして、許可されている末尾の/リードする」と解釈ans = okです
— Suever

MATLABが暗黙の.(現在のフォルダー)と..(上記のフォルダー)を追加するので、ディレクトリチェックを削除できないようです。ごめんなさい
— トム・カーペンター

4

Scala、52バイト

古いバージョン、79バイト

new java.io.File(".").listFiles.map(a=>a.getName->a.length)sortBy(_._2)apply(0)

jaxad0127のアドバイスに従って調整。現在はわずか52バイトです。

new java.io.File(".").listFiles.sortBy(_.length)head

apply(0)の代わりにheadを使用する方が短くなります。また、FileのtoStringメソッドは問題なく、get nameを呼び出す必要はありません。
— jaxad0127

4

バッチ、43 39 35バイト

@dir/b/os|(set/pf=&call echo %%f%%)

何らかの理由で出力に先行スペースが含まれていますが、幸いなことにそれは許可されています。編集:4バイトを保存するディレクトリがないと仮定します。


ああ、そのように/ pを使用すると、賢いことになります!
— AdmBorkBork

@AdmBorkBorkああ、許可されていることに気づかなかった、ありがとう!
— ニール

サブディレクトリが存在しないことが保証されているため(チャレンジが更新されました)、を削除できます/a-d。
— AdmBorkBork

4

Perl 6の、 33の32 31  16バイト

'.'.IO.dir.grep(*.f).min(*.s).put

それを試してみてください

put '.'.IO.dir.min:{try .s//Inf}

それを試してみてください

put $*CWD.dir.min:{try .s//Inf}

それを試してみてください

put dir.min: *.s

それを試してみてください

拡張:

put        # print with trailing newline
dir        # the list of files in the current directory
.min:      # find the minimum by
  *.s      # calling the `s` method (size) in a Whatever lambda

関数形式のdirデフォルトは$*CWDであり、タスクの説明では、フォルダーが存在しないと想定できるため、これを短縮できると考えていますdir.min(*.s).put。
— -sml

私がこれを書いたとき、プログラムはフォルダを無視しなければならないと言っていました。
— ブラッドギルバートb2gills

4

J、21 20バイト

>{.,(/:2&{"1)1!:0'*'

@ Conorのおかげで1バイト節約できました。

説明

>{.,(/:2&{"1)1!:0'*'
                 '*' Glob all files in current directory
             1!:0    Table of file metadata in that directory
       2&{"1         Get the file size of each
     /:              Sort the files by that
   ,                 Flatten
 {.                  Get the first value
>                    Unbox

@ ConorO'Brienありがとう
— マイル

3

BATCHファイル、77 72 63バイト

@FOR /F "tokens=*" %%G IN ('dir/o-s/b') DO @SET F=%%G
@ECHO %F%

There's no direct equivalent of head or tail in BATCH, at least to my knowledge, so here's a kludgy work-around. (with much assistance from @Neil - thanks!)

The dir command, with /o-s to sort in descending file size, and /b to output only the file names. We loop through those with FOR /F, setting the variable F to the file name each time. Finally, we output just the last one with ECHO %F%.

Saved 9 more bytes thanks to Neil and thanks to guarantees that no directories are present.


1
Your FOR variable needs two %s to work in a script. Otherwise, a few golfing tricks: 1. Don't use @ECHO OFF on short scripts, add a @ to each line and after DO. 2. Delete the space before DO. 3. The spaces and :s aren't needed in the dir command.
— Neil

1
@Neil Ack, thanks. Sorry, pretty rusty since I've been doing PowerShell... Thanks!
— AdmBorkBork

3

PHP, 84 62 bytes

$t=array_map(filesize,$g=glob('*'));asort($t);echo$g[key($t)];

Since the question was updated with the assumption that there will be no folders in the current directory, I was able to remove the file check stuff and golf this down.


Here is my old answer:

$t=array_map(filesize,$g=array_filter(glob('*'),is_file));asort($t);echo$g[key($t)];

This is the best I could do. Maybe there is a better way I'm missing.

$t=array_map(              # visit each array element and...
    filesize,              # map each filename to its filesize...
    $g=array_filter(       # using an array of...
        glob('*'),         # all files and directories...
        is_file            # filtered by files...
    )                      # 
);                         # 
asort($t);                 # sort the array of filesizes, then...
echo$g[key($t)];           # print element from the array of files using the first key of the sorted array as an index

2

Node.js (using walk), 114 bytes

Ignore newline:

require('walk').walk(__dirname).on('file',(r,s,n)=>
(m=s.size>m.size?m:s,n()),m=0).on('end',_=>console.log(m.name))

This invokes a walker that traverses through the current directory (__dirname) and for each file calls a function with its stat s and a function next n() that must be invoked to continue the traversal. Then at the end, it prints a filename with the minimum size in bytes found. s.size>m.size returns false when m.size is undefined, so after the first callback, m is equal to the first file found, and continues from there normally.


2

R, 36 bytes

x=file.info(y<-dir())$s;y[x==min(x)]

Explained

file.info() returns a data.frame of "file information" when given a character or character vector of file/folder names which when used on the list of files/folders in the current directory (dir()), looks something like:

                                                               size isdir mode               mtime               ctime               atime exe
Polyspace_Workspace                                               0  TRUE  777 2014-11-28 17:29:25 2014-11-28 17:29:25 2014-11-28 17:29:25  no
Python Scripts                                                    0  TRUE  777 2016-03-21 23:59:41 2016-03-21 23:59:41 2016-03-21 23:59:41  no
R                                                                 0  TRUE  777 2015-12-23 20:11:02 2015-12-23 20:11:02 2015-12-23 20:11:02  no
Rockstar Games                                                    0  TRUE  777 2015-04-14 12:23:05 2015-04-14 12:23:03 2015-04-14 12:23:05  no
TrackmaniaTurbo                                                   0  TRUE  777 2016-03-24 17:15:05 2016-03-24 13:13:48 2016-03-24 17:15:05  no
ts3_clientui-win64-1394624943-2014-06-11 03_18_47.004772.dmp 314197 FALSE  666 2014-06-11 02:18:47 2014-06-11 02:18:47 2014-06-11 02:18:47  no

Subsequently we just have the find the name of the file for which the size column (abbreviated using $s) is the smallest. Consequently, if there are more than one file with the smallest size, all will be returned.

Bonus: if we also wanted to disregard folders in the current directory we could simply search for size when isdir == FALSE: x=file.info(y<-dir());y[x$s==min(x$s[!x$i])] which turns out to be 44 bytes.


Bit late, but file.size is shorter because you don't have to do $s afterwards.
— JAD


2

SmileBASIC, 110 bytes

DIM F$[0]FILES"TXT:",F$FOR I=0TO LEN(F$)-1F$[I][0]="TXT:
S=LEN(LOAD(F$[I],0))IF!Z||S<Z THEN Z=S:B=I
NEXT?F$[B]

Only looks at TXT: files, since DAT: files cannot be loaded unless you already know their size, making it impossible to load a random one.


How do you load a DAT: file? Could you brute-force every name/file size in the folder?
— Pavel

Trying to load a 3-dimensional DAT: file into a 2-dimensional array (for example) will cause an error, so you can't brute force it. You just have to know the number of dimensions beforehand, which you normally would.
— 12Me21

Could you load a 2-d DAT: file into a 3-d array? Then you could create a maximum size array. And you can't catch errors in any way?
— Pavel

Nope, that will cause a Type mismatch error. And there's no way to catch errors either.
— 12Me21


1

C#, 277 bytes

Not the shortest, but what would you expect from C#?

Golfed

using System.Linq;using static System.IO.Directory;class P{static void Main(){var x=GetFiles(GetCurrentDirectory());var d=new long[]{}.ToList();foreach(var s in x){var b=new System.IO.FileInfo(s).Length;if(!d.Contains(b))d.Add(b);}System.Console.Write(x[d.IndexOf(d.Min())]);}}

Ungolfed

//Linq using for List.Min()
using System.Linq;
//Static using to save bytes on GetCurrentDirectory() and GetFiles()
using static System.IO.Directory;

class P
{
    static void Main()
    {
        //String array containing file paths
        var x = GetFiles(GetCurrentDirectory());
        //Creating a Long array and converting it to a list, less bytes than "new System.Collections.Generic.List<long>()"
        var d = new long[] { }.ToList();
        foreach (var s in x) //Loop through all file paths
        {
            //Getting file size in bytes
            var b = new System.IO.FileInfo(s).Length;
            if (!d.Contains(b))
                //If there isn't already a file with this size in our List, add the file path to list
                d.Add(b);

        }
        //Get index of the smallest Long in our List, which is also the index of the file path to the smallest file, then write that path
        System.Console.Write(x[d.IndexOf(d.Min())]);
    }
}

1

Röda, 32 31 bytes

{ls""|sort key=fileLength|pull}

It's an anonymous function that sorts the files in the current directory by file length and selects then the first file with pull.

Use it like this: main{ {ls""|sort key=fileLength|pull} }


Apparently ls"" works just as well as ls".". I think you can save a byte from that
— Kritixi Lithos

@KritixiLithos It seems to. Thanks!
— fergusq

0

SmileBASIC 3, 105 bytes (competing?)

Beats 12Me21's answer but still suffers from inability to load DAT files (which feels very cruel to be disqualifying considering the circumstances.)

DIM F$[0],T[0]FILES"TXT:",F$FOR I=0TO LEN(F$)-1F$[I][0]="TXT:
PUSH T,LEN(LOAD(F$[I]))NEXT
SORT T,F$?F$[0]

The shorter version above is annoying and prompts you on every file to load, but it does work. For two bytes more you can suppress the prompt; change line 2 to this:

PUSH T,LEN(LOAD(F$[I],0))NEXT

0

Batch File, 33 bytes

Batch files are moderately competitive this time, oddly enough.

@dir/os/b>..\q&set/pa=<..\q&"%a%.

Output

enter image description here


Find a way to stop the creation of q prior to dir/os/b being run and you'll save a maximum of 6 bytes by not needing to put the output file in a separate directory.

@dir/os/b>q&set/pa=<q&"%a%

Will always output q as the smallest file (unless tied for another 0 byte file) as it is created as an empty file before dir/b/os gathers a list of files.


0

C++17 (gcc), 180 bytes

#include<filesystem>
using namespace std::filesystem;auto f(){std::error_code e;path r;size_t m=-1,s;for(auto&p:directory_iterator(".")){s=file_size(p,e);if(s<m)m=s,r=p;}return r;}

Try it online!

Requires a recent standard library that implements std::filesystem.


弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.