Podaj mi rozdzielczość ekranu!


33

Przesyłaj rozdzielczość ekranu urządzenia w określonym formacie [width]x[height](bez nawiasów). Na przykład wyjście może być 1440x900.

Oto tester online, którego można użyć do sprawdzenia własnej rozdzielczości ekranu.


17
Określony format wyjściowy nie jest zabawny, ale prawdopodobnie jest już za późno na zmianę
Luis Mendo

3
Jakie powinno być zachowanie, jeśli podłączonych jest wiele monitorów?
Jonathan Allan

4
Przypuszczam, że nie wolno nam najpierw zmienić rozdzielczości, a następnie powiedzieć ci tych wartości, prawda?
Inżynier Toast

3
APL \ 360 (można uruchomić tylko w środowisku maszyn do pisania IBM / 360), 5 bajtów:'0x0'
Adám

4
Podoba mi się, że ten dyskwalifikuje większość języków golfowych i zachęca ludzi do odkrywania granic praktycznych.
robbie

Odpowiedzi:


38

JavaScript (ES6), 32 bajty

(_=screen)=>_.width+"x"+_.height

Wyjścia jako funkcja return. Dodaj f=na początku i wywołaj jak f(). Używa inicjalizacji parametru do inicjalizacji parametru _do screenobiektu. Reszta jest oczywista.

f=(_=screen)=>_.width+"x"+_.height
console.log(f())

Uwaga: przekazanie argumentu do tej funkcji spowoduje jej niepowodzenie.


JavaScript (poprzednie rozwiązanie), 35 bajtów

with(screen)alert(width+"x"+height)

Nigdy nie myślałem, że pewnego dnia skorzystam with! Nie sądzę, że można to dalej pograć w golfa.


Jeśli dozwolone są REPL, s=screen,s.width+"x"+s.height(29 znaków) również działa.
Kobi

Oooch Dobre wykorzystanie domyślnej wartości argumentu.
Matthew Roh

Rozwiązanie 35-bajtowe może zaoszczędzić pięć bajtów, nie zawracając sobie głowy alert: with(screen)(width+'x'+height)po prostu zwraca odpowiedni ciąg.
KRyan

2
Ta odpowiedź jest zasadniczo błędna. Mogę oszukiwać, powiększając i pomniejszając przeglądarkę!
Wielka Kaczka

1
Chodźcie, czy nawet próbujecie: _=screen,_.width+"x"+_.height29 bajtów
M28

33

TI-BASIC, 30 32 29 bajtów (niekonkuruje?)

* westchnienie * TI-BASIC zajmuje dodatkowy bajt na każdą małą literę.

+2 dzięki @Timtech

-3 dzięki @Timtech

:If ΔX>.1
:Then
:Disp "96x64
:Else
:Disp "320x240

Działa to tylko dlatego, że TI-BASIC można uruchomić tylko na kalkulatorach o dwóch różnych rozdzielczościach ekranu: 96 na 64 i 320 na 240. Po prostu testuję, aby zobaczyć, który ekran mam, ustawiając Zoom na coś, co jest różne w zależności od rozdzielczości ekranu, a następnie wyświetlanie prawidłowej rozdzielczości.

Na razie zaznaczam to jako niekonkurujące, ponieważ jest mocno zakodowane.


6
To sprytne nadużycie;)
Matthew Roh

1
Możesz zapisać, nie używając, ZDecimala następnie używając innego Xmaxporównania, przynajmniej jednego bajtu. Myślę też, że musisz użyć małych liter, xktóre są dwoma bajtami (x2) zamiast jednobajtowego odpowiednika wielkich liter.
Timtech

@ Timtech Muszę użyć dwubajtowego powiększenia (podobnego ZDecimal), ponieważ domyślny zoom ( ZStandard) jest taki sam na obu kalkulatorach. Naprawię wielkie litery.
Scott Milner

1
Och, rozumiem co masz na myśli. Jeśli jednak użyjesz ZStandard, będzie ΔXinaczej niż w kalkulatorach? Ponadto ZDecimaljest tylko jeden bajt, więc jest to 31 bajtów.
Timtech

2
Z jakiegoś powodu moja natychmiastowa reakcja brzmi: „to jest poprawne, ale nie byłoby poprawne, gdyby istniała tylko jedna możliwa rozdzielczość ekranu”, ale ten punkt widzenia wydaje się wewnętrznie niespójny. Naprawdę nie jestem pewien, czy to oszustwo, czy nie.

20

JavaScript (ES6), 32 bajty

_=>(s=screen).width+'x'+s.height

console.log((_=>(s=screen).width+'x'+s.height)())


2
wersja lambda jest dopuszczalna
Felipe Nardi Batista

6
_=>(s=screen).width+'x'+s.heightzapisuje bajt
Felipe Nardi Batista

@FelipeNardiBatista Dzięki, ta myśl również
przyszła

1
Dobra robota! +1 :)
Arjun

5
Uwielbiam to, że wszystkie wpisy JS były konsekwentnie krótsze niż duża liczba innych odpowiedzi. Prawie nigdy się nie zdarza.
Draco18s

11

macOS, bash, awk, grep, tr, 51 52 bajtów

/*/*/sy*r SPDisplaysDataType|awk '/so/{print$2$3$4}'

Uruchamia się system_profiler, pobiera SPDisplaysDataTypeinformacje, szuka pierwszego sow Resolutioni drukuje rozdzielczość ekranu. W przypadku wielu ekranów powoduje to wydrukowanie wszystkich rozdzielczości.

Example of the command running.


Wcześniejszy wariant niezgodny:

/*/*/sy*r SPDisplaysDataType|grep so|tr -d 'R :a-w'

Właśnie uruchomiłem to na moim MacBooku Pro z podłączonym drugim wyświetlaczem. Mam 2880x1800\n1920x1080@60Hz(dwie linie). Nie wiem czy to to dyskwalifikuje ... czy?
Floris

@Floris czy OP określiło, jak się zachować, gdy jest wiele ekranów?
Captain Man

Nie - ale format nie @60Hzjest wyraźnie określony.
Floris

Wydaje mi się, że można się przyczepić |sed 1q, zwiększając liczbę bajtów do 58 bajtów.
zgrep

Naprawiłem niezgodność, zmieniając awki mając jeden dodatkowy bajt. :)
zgrep


9

Przetwarzanie 3, 37 bajtów

fullScreen();print(width+"x"+height);

fullScreen()powoduje uruchomienie aplikacji z maksymalnymi wymiarami - rozdzielczością wyświetlacza. Jeden bajt mniej niż oczywiste

print(displayWidth+"x"+displayHeight);

8

AutoHotKey, 34 bajty

SysGet,w,0
SysGet,h,1
Send,%w%x%h%

Zapisz to w pliku z rozszerzeniem .AHK i uruchom z wiersza polecenia


1
Dlaczego nie użyć Sendzamiast MsgBox?
Engineer Toast

@EngineerToast dzięki! To zaoszczędziło dwa bajty
jmriego

7

C (Windows), 79 78 77 bajtów

Dzięki @Johan du Toit za uratowanie bajtu!

#import<windows.h>
#define G GetSystemMetrics
f(){printf("%dx%d",G(0),G(1));}

2
Wciąż bawiłem się „GetDeviceCaps”, dopóki nie zobaczyłem twojej odpowiedzi :-) Możesz nadal zapisać 1 bajt, używając:#define G GetSystemMetrics f(){printf("%dx%d",G(0),G(1));}
Johan du Toit

7

PowerShell, 67 60 55 bajtów

-7 dzięki Martinowi Enderowi

-5 (właściwie 12!) Od Leaky Nun , magia Regex jest poza mną.

To jest długie, ale nie dłuższe niż przerażające System.Windows.Forms.SystemInformation.PrimaryMonitorSizerozwiązanie

(gwmi win32_videocontroller|% v*n)-replace" |x \d+\D+$"

najpierw my Get-WmiObject( gwmi), aby pobrać Win32_VideoControllerobiekt, który zawiera element o nazwie VideoModeDescription, który jest łańcuchem w formacie 1920 x 1080 x 4294967296 colors, a następnie uruchamiam zamianę wyrażenia regularnego, aby uzyskać poprawny format.

PS H:\> (gwmi win32_videocontroller|% v*n)-replace" |x \d+\D+$"
1920x1080

Myślę, że (gwmi win32_videocontroller|% v*n)-replace" |x[^x]+$"goli kilka bajtów, modyfikując regex.
TessellatingHeckler

6

Mathematica, 51 bajtów

SystemInformation[][[1,5,2,1,2,1,2,2,;;,2]]~Infix~x

Może to nie działać w zależności od podłączonych urządzeń (nie wiem). Powinno to zawsze działać (zakładając, że masz podłączony przynajmniej jeden ekran):

Infix[Last/@("FullScreenArea"/.SystemInformation["Devices","ScreenInformation"][[1]]),x]

Wyjaśnienie

SystemInformation[] zwraca wyrażenie formularza

SystemInformationData[{
  "Kernel" -> {__},
  "FrontEnd" -> {__},
  "Links" -> {__},
  "Parallel" -> {__},
  "Devices" -> {__},
  "Network" -> {__},
}]

Jesteśmy zainteresowani "Devices", do których można uzyskać bezpośredni dostęp jako SystemInformation["Devices"]lub jako SystemInformation[][[1,5,2]]. Rezultatem będzie lista formularza

{
  "ScreenInformation" -> {__},
  "GraphicsDevices" -> {__},
  "ControllerDevices" -> {__}
}

Chcemy "ScreenInformation", do którego można uzyskać dostęp tak SystemInformation["Devices","ScreenInformation"]zwięźle lub bardziej zwięźle SystemInformation[][[1,5,2,1,2]]. Wynik będzie miał formę

{
  {
  "ScreenArea" -> {__},
  "FullScreenArea" -> {{0,w_},{0,h_}},
  "BitDepth" -> _,
  "Resolution" -> _
  },
  ___
}

Długość listy będzie liczbą podłączonych ekranów. Pierwszy ekran jest, SystemInformation[][[1,5,2,1,2,1]]a szerokość i wysokość można wyodrębnić, ponieważ SystemInformation[][[1,5,2,1,2,1,2,2,;;,2]]Następnie wstawiamy tylko Infix xdla formatu wyjściowego.


6

Java 7, 123 114 bajtów

String f(){java.awt.Dimension s=java.awt.Toolkit.getDefaultToolkit().getScreenSize();return s.width+"x"+s.height;}

Ta metoda nie będzie działać w bezobsługowej instalacji Java (jak w TIO), ponieważ używa bibliotek awt. Dzwonię pod maskągetScreenSize uses the Java Native Interface to call out (typically into a C library) for the screen width and screen height.

-9 bajtów dzięki Olivierowi Grégoire'owi za przypomnienie, że mogę zwrócić ciąg zamiast go wydrukować.


2
I was just about to post...
Leaky Nun

@LeakyNun You and me both. +1 Poke.
Kevin Cruijssen

Too bad the output is restricted to ...x..., because void f(){System.out.print((java.awt.Toolkit.getDefaultToolkit().getScreenSize()+"").replaceAll("[^\\d,]",""));} which outputs 1920,1200 is shorter..
Kevin Cruijssen

1
@KevinCruijssen yeah I did try playing with that as well. The real "too bad" is that using regex in java is so heavy in terms of byte count.
Poke

1
@Poke You're indeed right. I have been able to use that what I show above with an x instead of , by using some regex replacement, but it's five bytes more than your current answer: void f(){System.out.print((java.awt.Toolkit.getDefaultToolkit().getScreenSize()+"").replaceAll("[^\\d,]","").replace(",","x"));} or void f(){System.out.print((java.awt.Toolkit.getDefaultToolkit().getScreenSize()+"").replaceAll(".*?(\\d+).*?(\\d+).*","$1x$2"));} Ah well, what isn't heavy in Java.. ;p
Kevin Cruijssen

6

C#, 101 95 89 bytes

_=>{var s=System.Windows.Forms.Screen.PrimaryScreen.Bounds;return s.Width+"x"+s.Height;};

-6 bytes thanks to @TheLethalCoder by reminding me OP didn't mention about printing, so returning a string is also fine. And an additional -6 bytes by changing it to a lambda.


You can save 11 bytes by compiling to a Func<string>: ()=>{var s=System.Windows.Forms.Screen.PrimaryScreen.Bounds;return s.Width+"x"+s.Height;};. However, you have a return of void but you are returning a string so you need to add 2 bytes for that.
TheLethalCoder

1
The challenge also doesn't state that you can't take input so you could add an unused input to save another byte i.e. _=>{var s=System.Windows.Forms.Screen.PrimaryScreen.Bounds;return s.Width+"x"+s.Height;};
TheLethalCoder

1
Oh ignore the return comment you're writing the result out, you can save 6 bytes by returning it.
TheLethalCoder

And unless you can think of a way to get it shorter var s=System.Windows.Forms.Screen.AllScreens[0].Bounds; would also be the same count but you could golf it with that idea in mind.
TheLethalCoder

6

Bash + xrandr, 44 characters

read -aa<<<`xrandr`
echo ${a[7]}x${a[9]::-1}

xrandr belongs to the X server, on Ubuntu is provided by x11-xserver-utils package.

Sample run:

bash-4.3$ read -aa<<<`xrandr`;echo ${a[7]}x${a[9]::-1}
1920x1080

xrandr + grep + util-linux, 30 characters

xrandr|grep -oP '\d+x\d+'|line

Thanks to:

Sample run:

bash-4.3$ xrandr|grep -oP '\d+x\d+'|line
1920x1080

I have no bash with a display, would xrandr|grep * work?
Jonathan Allan

Sure. But for now the my grep and sed attempts to parse xrandr's output (pastebin.com/uTVcjWCq) were longer.
manatwork

Maybe xrandr|grep *|cut -d' ' -f1? (using the matching line from your paste @TIO)
Jonathan Allan

Ah, you mean to pick the resolution from the list by the “*” mark? Thought to that possibility, but I am not sure whether would work with multiple displays connected. As I remember, that would list each connected display's current resolution.
manatwork

Ah yes it would, not sure what the OP wants in such a scenario though!
Jonathan Allan

5

Python 2, 73 bytes

from ctypes import*
u=windll.user32.GetSystemMetrics;
print u(0),'x',u(1)

print u(0),'x',u(1) is smaller and his example (link) allows it
Felipe Nardi Batista

1
To clarify, If it's equivalent to the output from What is my screen resolution, It's valid. in that website, there is space between each part
Felipe Nardi Batista

@FelipeNardiBatista Updated, thanks.
Neil

5

Octave, 41 bytes

Thanks to @Arjun and @StephenS for corrections.

fprintf('%ix%i',get(0,'ScreenSize')(3:4))

0 is a handle to the root graphics object. Its property 'ScreenSize' contains the coordinates of the screen in pixels. The third and fourth entries give the desired information.


5

APL (Dyalog), 23 bytes

' 'R'x'⍕⌽⊃⎕WG'DevCaps'

⎕WG'DevCaps'Window Get Device Capabilities

 pick the first property (height, width)

 reverse

 format as text

' '⎕R'x'Replace spaces with "x"s


"substitute with an "x" at position 5 (the space)" this would cause problems on a small screen, e.g. 640x480 (which VMs use)
Baldrickk

4

Japt, 24 bytes

Ox`ØP(s×Çn)±d+"x"+ight

Test it online!

The compressed string represents with(screen)width+"x"+height. Ox evaluates this as JavaScript, and the result is implicitly printed.


4

C (SDL2 library) 113 88 84

(-4 chars due to @AppleShell 's help)

Yes. it compiles.

m[3];main(){SDL_Init(32);SDL_GetDesktopDisplayMode(0,m);printf("%dx%d",m[1],m[2]);}

Run with : gcc snippet.c -lSDL2 && ./a.out


3
I think you can shorten this by making m global and omitting int: m[3];main(){...
Appleshell

accessing by m+1 should be shorter than m[1] right? or isn't that possible in C but only in C++? surely printf has some dereference token
Gizmo

@gizmo unfortunately AFAIK there is no printf specifier that does such thing ..
dieter

4

Python 2, 61 49 bytes

Thanks @Jonathan-allan, @felipe-nardi-batista

from Tkinter import*
print'%sx%s'%Tk().maxsize()

For single display setups, this matches the output from the site. This gives entire resolution for multiple displays.


print'x'.... saves a byte
Felipe Nardi Batista

v=Tk().maxsize(), print'%sx%s'%v saves 9 bytes.
Jonathan Allan

oops, and then print'%sx%s'%Tk().maxsize() saves another 4 >_<
Jonathan Allan

3

bash + xdpyinfo 42 31 bytes

xdpyinfo|grep dim|cut -d' ' -f7

From man page:

xdpyinfo - is  a utility for displaying information about an X server.

@Floris @manatwork Thanks for saving a few bytes!


Crossed out 4 is still 4 :(
Christopher

There is no need for spaces around the pipes; I think is safe to search for “dim” only; you can write -d\ instead of -d' '. Then when it comes to both grep for a line and cut a part of that line, usually is shorter with a single awk call: xdpyinfo|awk '/dim/&&$0=$2'.
manatwork

I suspect you can grep something shorter than dimensions but I don't have xdpyinfo on my system...
Floris

3

xrandr + awk, 25 bytes

xrandr|awk /\*/{print\$1}

enter image description here


1
This doesn't work. grep * expands the asterisk to all files in the directory.
Jens

@Jens Corrected. Thanks for pointing out
Pandya

Thanks; another hint: the proper spelling for grep|cut is awk.
Jens

It still doesn't work. It outputs *0. My xrandr output is *0 3360 x 1050 ( 889mm x 278mm ) *0.
Jens

@Jens then you need -f2 Btw, Can you check xrandr|awk '/\*/{print $2}'?
Pandya

3

ZX Spectrum Basic, 10 bytes

just for completeness:

PRINT "256x192"

outputs 256x192. The Spectrum has a fixed hardwired screen resolution.


...and uses a single byte for keywords like PRINT.
Jens

2

Processing, 51 bytes

void setup(){fullScreen();print(width+"x"+height);}

This outputs in this format: width height. Also, the program creates a window that is the size of the screen you are using (because every Processing program creates a window by default) and this program just outputs the height and the width of this window/sketch.


Oh, the format is WIDTHxHEIGHT.
Matthew Roh

@SIGSEGV Just noticed it
Kritixi Lithos

2

xdpyinfo + awk, 28 bytes

$ xdpyinfo|awk /dim/{print\$2}
3360x1050

Tested on Cygwin with dual heads.


1
xdpyinfo|awk /dim/{print\$2} takes 28 bytes not 24
Pandya

@Pandya I need new glasses :-)
Jens


1

Lithp, 116 bytes

((import html-toolkit)
(htmlOnLoad #::((var S(index(getWindow)screen))
(print(+(index S width)"x"(index S height))))))

(Line breaks added for readability)

Try it online!

Finally, my html-toolkit module gets some use! Only works in the Try it Online link, will not work from command line.

A few bytes could be saved if 1024 x 768 could be valid output. We just use (+ .. "x" .. ) to avoid print's implicit spacing.


Hmm. I tried it online, but it says 2048x1080 for a true 4K screen that's actually 4096x2160. Any idea why? Firefox 52.0 on FreeBSD 11.
Jens

No idea. I'm merely grabbing window.screen and getting the width and height attributes from it. I imagine if you opened up the Firefox console and typed in window.screen you'll see the apparently incorrect 2048x1080.
Andrakis

1

Lua (löve framework),116 bytes

f,g=love.window.setFullscreen,love.graphics function love.draw()f(1)w,h=g.getDimensions()f(0>1)g.print(w.."x"..h)end

The programm changes first to fullscreen then it gets the width and height and prints it then :)


1

xrandr and sh, 23 bytes

$ set `xrandr`;echo $6x$8
3360x1050

Tested on a CentOS 5 box with display redirected to a Cygwin machine with two monitors. Here the full xrandr output is

$ xrandr
 SZ:    Pixels          Physical       Refresh
*0   3360 x 1050   ( 889mm x 278mm )  *0
Current rotation - normal
Current reflection - none
Rotations possible - normal
Reflections possible - none

1

Ruby + xrandr, 37 bytes

puts `xrandr`.split[7..9].join[0..-2]

Alternate solution (52 bytes):

puts `xrandr`.match(/t (\d+) (x) (\d+),/)[1..3].join

1

Red, 26 Bytes

system/view/screens/1/size

Outputs for example:

1920x1080

The code is pretty self explanatory. The 1 refers to the first screen

Korzystając z naszej strony potwierdzasz, że przeczytałeś(-aś) i rozumiesz nasze zasady używania plików cookie i zasady ochrony prywatności.
Licensed under cc by-sa 3.0 with attribution required.