Dimmi la mia risoluzione dello schermo!


33

Stampa la risoluzione dello schermo del dispositivo nel formato specifico di [width]x[height](senza parentesi). Ad esempio, un output potrebbe essere 1440x900.

Ecco un tester online che puoi usare per controllare la tua risoluzione dello schermo.


17
Il formato di output specifico non è divertente, ma probabilmente è troppo tardi per cambiare adesso
Luis Mendo,

3
Quale dovrebbe essere il comportamento se sono collegati più schermi?
Jonathan Allan,

4
Suppongo che non ci sia permesso prima di cambiare la tua risoluzione e poi dirti quei valori, giusto?
Ingegnere Toast,

3
APL \ 360 (può essere eseguito solo su ambiente macchina da scrivere IBM / 360), 5 byte:'0x0'
Adám,

4
Mi piace il fatto che questo squalifica la maggior parte delle lingue del golf e incoraggia le persone a esplorare i limiti di quelli pratici.
Robbie,

Risposte:


38

JavaScript (ES6), 32 byte

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

Uscite come funzione return. Aggiungi f=all'inizio e invoca like f(). Utilizza l'inizializzazione dei parametri _per inizializzare il parametro screensull'oggetto. Il resto è autoesplicativo.

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

Nota: il passaggio di un argomento a questa funzione comporta un errore.


JavaScript (soluzione precedente), 35 byte

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

Non avrei mai pensato di usarlo un giorno with! Non credo che questo possa essere ulteriormente approfondito.


Se sono consentiti i REPL, funziona anche s=screen,s.width+"x"+s.height(29 caratteri).
Kobi,

Oooh. Buon uso del valore dell'argomento predefinito.
Matthew Roh,

La soluzione a 35 byte può salvare cinque byte senza preoccuparsi di alert: with(screen)(width+'x'+height)restituisce semplicemente la stringa appropriata.
KRyan

2
Questa risposta è fondamentalmente imperfetta. Posso imbrogliare ingrandendo e riducendo il mio browser!
The Great Duck,

1
Andiamo, ragazzi state anche provando _=screen,_.width+"x"+_.height
:,

33

TI-BASIC, 30 32 29 byte (non in competizione?)

* sigh * TI-BASIC richiede un byte in più per ogni lettera minuscola.

+2 grazie a @Timtech

-3 grazie a @Timtech

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

Questo funziona solo perché TI-BASIC può essere eseguito solo su calcolatori con due diverse risoluzioni dello schermo: 96 per 64 e 320 per 240. Ho appena testato per vedere quale schermo ho impostando lo Zoom su qualcosa di diverso a seconda della risoluzione dello schermo quindi fornire la risoluzione corretta.

Sto contrassegnando questo come non competitivo per ora, dal momento che è hard coded.


6
È un abuso intelligente;)
Matthew Roh,

1
È possibile salvare non utilizzando ZDecimale quindi utilizzando un Xmaxconfronto diverso , almeno un byte. Inoltre, penso che sia necessario utilizzare xlettere minuscole che sono due byte (x2) invece dell'equivalente maiuscolo di un byte.
Timtech,

@Timtech Devo usare uno Zoom a due byte (come ZDecimal) perché lo zoom predefinito ( ZStandard) è lo stesso su entrambi i calcolatori. Risolverò la capitalizzazione, però.
Scott Milner,

1
Oh, capisco cosa intendi. Se usi ZStandardperò, sarebbe ΔXdiverso tra i calcolatori? Inoltre, ZDecimalè solo un byte, quindi questo è 31 byte.
Timtech,

2
Per qualche ragione, la mia reazione istantanea è "valida, ma non sarebbe valida se ci fosse una sola risoluzione dello schermo", ma quel punto di vista sembra internamente incoerente. Quindi non sono davvero sicuro se questo sia barare o no.

20

JavaScript (ES6), 32 byte

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

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


2
la versione lambda è accettabile
Felipe Nardi Batista,

6
_=>(s=screen).width+'x'+s.heightsalva un byte
Felipe Nardi Batista

@FelipeNardiBatista Grazie, mi è venuto in mente anche il pensiero :)
SethWhite

1
Buon lavoro! +1 :)
Arjun,

5
Adoro come tutte le voci di JS siano state costantemente più brevi di un gran numero di altre risposte. Non succede quasi mai.
Draco18s

11

macOS, bash, awk, grep, tr, 51 52 byte

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

Corre system_profiler, ottiene le SPDisplaysDataTypeinformazioni, cerca il primo soin Resolutione stampa la risoluzione dello schermo. Per più schermi, questo stampa tutte le risoluzioni.

Example of the command running.


La variante precedente, non conforme:

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

L'ho appena eseguito sul mio MacBook Pro con un secondo display collegato. Ho ottenuto 2880x1800\n1920x1080@60Hz(due righe). Non so se questo squalifica questo ... o?
Floris,

@Floris OP ha specificato come comportarsi in presenza di più schermi?
Captain Man,

No, ma il formato non @60Hzè chiaramente nelle specifiche.
Floris,

Immagino che potresti puntare su a |sed 1q, portando il conteggio dei byte fino a 58 byte.
zgrep,

Ho risolto la non conformità passando a awke avendo un byte in più. :)
zgrep,


9

Elaborazione di 3, 37 byte

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

fullScreen()provoca l'avvio dell'app con le dimensioni massime: la risoluzione del display. Un byte in meno dell'ovvio

print(displayWidth+"x"+displayHeight);

8

AutoHotKey, 34 byte

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

Salvalo in un file con estensione .AHK ed eseguilo da un prompt dei comandi


1
Perché non usare Sendpiuttosto che MsgBox?
Ingegnere Toast,

@EngineerToast grazie! Ciò ha salvato due byte
jmriego

7

C (Windows), 79 78 77 byte

Grazie a @Johan du Toit per aver salvato un byte!

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

2
Stavo ancora scherzando con 'GetDeviceCaps' fino a quando non ho visto la tua risposta :-) Puoi ancora salvare 1 byte usando il seguente:#define G GetSystemMetrics f(){printf("%dx%d",G(0),G(1));}
Johan du Toit

7

PowerShell, 67 60 55 byte

-7 grazie a Martin Ender

-5 (in realtà 12!) Da Leaky Nun , la magia di Regex è oltre me.

Questo è lungo ma non più lungo della System.Windows.Forms.SystemInformation.PrimaryMonitorSizesoluzione orrenda

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

prima dobbiamo Get-WmiObject( gwmi) recuperare l' Win32_VideoControlleroggetto, che contiene un membro chiamato VideoModeDescription, che è una stringa nel formato di 1920 x 1080 x 4294967296 colors, quindi eseguo un regex sostituto per ottenere il formato corretto.

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

Penso che (gwmi win32_videocontroller|% v*n)-replace" |x[^x]+$"rade un paio di byte modificando la regex.
TessellatingHeckler,

6

Mathematica, 51 byte

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

Questo potrebbe non funzionare per te a seconda dei dispositivi che hai collegato (non lo so). Questo dovrebbe sempre funzionare (supponendo che tu abbia almeno uno schermo collegato):

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

Spiegazione

SystemInformation[] restituisce un'espressione del modulo

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

Siamo interessati a "Devices"cui è possibile accedere direttamente come SystemInformation["Devices"]o come SystemInformation[][[1,5,2]]. Il risultato sarà un elenco del modulo

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

Vogliamo "ScreenInformation", a cui è possibile accedere in modo più SystemInformation["Devices","ScreenInformation"]o meno succinto SystemInformation[][[1,5,2,1,2]]. Il risultato sarà del modulo

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

La lunghezza dell'elenco sarà il numero di schermate che hai collegato. La prima schermata è SystemInformation[][[1,5,2,1,2,1]]e la larghezza e l'altezza possono essere estratte come SystemInformation[][[1,5,2,1,2,1,2,2,;;,2]]Quindi inseriamo semplicemente una Infix xper il formato di output.


6

Java 7, 123 114 byte

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

Questo metodo non funzionerà in un'installazione senza testa di Java (come su TIO) perché utilizza le librerie awt. Sotto il cofano, chiamandogetScreenSize utilizza l'interfaccia nativa Java per chiamare (in genere in una libreria C) per la larghezza e l'altezza dello schermo.

-9 byte grazie a Olivier Grégoire per avermi ricordato che posso restituire la stringa invece di stamparla.


2
Stavo per pubblicare ...
Leaky Nun,

@LeakyNun Sia io che te. +1 Poke .
Kevin Cruijssen,

Peccato che l'output sia limitato ...x..., perché void f(){System.out.print((java.awt.Toolkit.getDefaultToolkit().getScreenSize()+"").replaceAll("[^\\d,]",""));}quali output 1920,1200sono più brevi ..
Kevin Cruijssen,

1
@KevinCruijssen sì, ho provato anche a giocarci. Il vero "peccato" è che l'uso di regex in Java è così pesante in termini di conteggio dei byte.
Colpisce

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

Tcl/Tk, 40

puts [winfo screenw .]x[winfo screenh .]

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

Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.