Four sides of square

From Rosetta Code
Four sides of square is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.
Task


Fill with 1's the four sides of square. The rest of the square should be filled with 0's.
If you can please use GUI
Four sides of square - image

See also

11l

Translation of: Python
V size = 9
L(row) 0 .< size
   L(col) 0 .< size
      I row == 0 | row == size - 1 | col == 0 | col == size - 1
         print(‘1’, end' ‘ ’)
      E
         print(‘0’, end' ‘ ’)
   print()
Output:
1 1 1 1 1 1 1 1 1 
1 0 0 0 0 0 0 0 1 
1 0 0 0 0 0 0 0 1 
1 0 0 0 0 0 0 0 1 
1 0 0 0 0 0 0 0 1 
1 0 0 0 0 0 0 0 1 
1 0 0 0 0 0 0 0 1 
1 0 0 0 0 0 0 0 1 
1 1 1 1 1 1 1 1 1 

Action!

;;; draw a matrix with 1s on the edges and 0s elsewhere

;;; draws a matrix with height and width = n with 1s on the edges
PROC drawSquare( INT n )
  CARD i, j
  FOR i = 1 TO n DO
    FOR j = 1 TO n DO
      Put(' )
      IF i = 1 OR i = n OR j = 1 OR j = n THEN Put('1) ELSE Put('0) FI
    OD
    PutE()
  OD
RETURN

PROC Main()
  drawSquare( 6 )
  PutE()
  drawSquare( 7 )
RETURN
Output:
 1 1 1 1 1 1
 1 0 0 0 0 1
 1 0 0 0 0 1
 1 0 0 0 0 1
 1 0 0 0 0 1
 1 1 1 1 1 1

 1 1 1 1 1 1 1
 1 0 0 0 0 0 1
 1 0 0 0 0 0 1
 1 0 0 0 0 0 1
 1 0 0 0 0 0 1
 1 0 0 0 0 0 1
 1 1 1 1 1 1 1

Ada

with Ada.Text_Io;
with Ada.Command_Line;

procedure Four_Sides is

   type Matrix_Type is array (Natural range <>, Natural range <>) of Character;

   function Hollow (Length : Natural) return Matrix_Type is
   begin
      return M : Matrix_Type (1 .. Length, 1 .. Length) do
         for Row in M'Range(1) loop
            for Col in M'Range (2) loop
               M (Row, Col) := (if Row in M'First (1) | M'Last (1) or
                                  Col in M'First (2) | M'Last (2)
                                then '1' else '0');
            end loop;
         end loop;
      end return;
   end Hollow;

   procedure Put (M : Matrix_Type) is
   begin
      for Row in M'Range (1) loop
         for Col in M'Range (2) loop
            Ada.Text_Io.Put (" ");
            Ada.Text_Io.Put (M(Row,Col));
         end loop;
         Ada.Text_Io.New_Line;
      end loop;
   end Put;

begin
   Put (Hollow (Length => Natural'Value (Ada.Command_Line.Argument (1))));
exception
   when others =>
      Ada.Text_Io.Put_Line ("Usage: ./four_sides <length>");
end Four_Sides;
Output:
$ ./four_sides 4
 1 1 1 1
 1 0 0 1
 1 0 0 1
 1 1 1 1
$ ./four_sides 1
 1
$ ./four_sides 0
$ ./four_sides 2
 1 1
 1 1
$ ./four_sides -1
Usage: ./four_sides <length>

ALGOL 68

BEGIN # draw a matrix with 1s on the edges and 0s elsewhere             #
    # draws a matrix with height and width = n with 1s on the edges     #
    PROC draw square = ( INT n )VOID:
         FOR i TO n DO
             FOR j TO n DO
                 print( ( " ", whole( ABS ( i = 1 OR i = n OR j = 1 OR j = n ), 0 ) ) )
             OD;
             print( ( newline ) )
         OD # draw square # ;
    # test the draw square procedure #
    draw square( 6 );
    print( ( newline ) );
    draw square( 7 )
END
Output:
 1 1 1 1 1 1
 1 0 0 0 0 1
 1 0 0 0 0 1
 1 0 0 0 0 1
 1 0 0 0 0 1
 1 1 1 1 1 1

 1 1 1 1 1 1 1
 1 0 0 0 0 0 1
 1 0 0 0 0 0 1
 1 0 0 0 0 0 1
 1 0 0 0 0 0 1
 1 0 0 0 0 0 1
 1 1 1 1 1 1 1

ALGOL W

begin % draw a matrix with 1s on the edges and 0s elsewhere             %
    % draws a matrix with height and width = n with 1s on the edges     %
    procedure drawSquare ( integer value n ) ;
        for i := 1 until n do begin
            for j := 1 until n do begin
                writeon( s_w := 0, if i = 1 or i = n or j = 1 or j = n then " 1" else " 0" )
            end for_j ;
            write()
        end drawSquare ;
    % test the draw square procedure %
    drawSquare( 6 );
    write();
    drawSquare( 7 )
end.
Output:
 1 1 1 1 1 1
 1 0 0 0 0 1
 1 0 0 0 0 1
 1 0 0 0 0 1
 1 0 0 0 0 1
 1 1 1 1 1 1

 1 1 1 1 1 1 1
 1 0 0 0 0 0 1
 1 0 0 0 0 0 1
 1 0 0 0 0 0 1
 1 0 0 0 0 0 1
 1 0 0 0 0 0 1
 1 1 1 1 1 1 1

AppleScript

Defined in terms of a generic matrix function:

------------------- FOUR SIDES OF SQUARE -----------------


-- fourSides :: Int -> [[Int]]
on fourSides(n)
    -- A matrix of dimension n in which edge values are 1,
    -- and other values are zero.
    script go
        on |λ|(i, j)
            if {1, n} contains i or {1, n} contains j then
                1
            else
                0
            end if
        end |λ|
    end script
    
    matrix(n, n, go)
end fourSides


--------------------------- TEST -------------------------
on run
    -- Matrices of dimension 1 .. 6
    
    script test
        on |λ|(n)
            showMatrix(fourSides(n)) & linefeed & linefeed
        end |λ|
    end script
    
    unlines(map(test, enumFromTo(1, 6)))
end run


------------------------- MATRICES -----------------------

-- matrix :: Int -> Int -> ((Int, Int) -> a) -> [[a]]
on matrix(nRows, nCols, f)
    -- A matrix of a given number of columns and rows,
    -- in which each value is a given function of its
    -- (zero-based) column and row indices.
    script go
        property g : mReturn(f)'s |λ|
        
        on |λ|(iRow)
            set xs to {}
            repeat with iCol from 1 to nCols
                set end of xs to g(iRow, iCol)
            end repeat
            xs
        end |λ|
    end script
    
    map(go, enumFromTo(1, nRows))
end matrix


-- showMatrix :: [[Maybe a]] -> String
on showMatrix(rows)
    -- String representation of rows
    -- as a matrix.
    
    script showRow
        on |λ|(a, row)
            set {maxWidth, prevRows} to a
            script showCell
                on |λ|(acc, cell)
                    set {w, xs} to acc
                    if missing value is cell then
                        {w, xs & ""}
                    else
                        set s to cell as string
                        {max(w, length of s), xs & s}
                    end if
                end |λ|
            end script
            
            set {rowMax, cells} to foldl(showCell, {0, {}}, row)
            {max(maxWidth, rowMax), prevRows & {cells}}
        end |λ|
    end script
    
    set {w, stringRows} to foldl(showRow, {0, {}}, rows)
    script go
        on |λ|(row)
            unwords(map(justifyRight(w, space), row))
        end |λ|
    end script
    
    unlines(map(go, stringRows))
end showMatrix


------------------------- GENERIC ------------------------

-- enumFromTo :: Int -> Int -> [Int]
on enumFromTo(m, n)
    if m  n then
        set xs to {}
        repeat with i from m to n
            set end of xs to i
        end repeat
        xs
    else
        {}
    end if
end enumFromTo


-- foldl :: (a -> b -> a) -> a -> [b] -> a
on foldl(f, startValue, xs)
    tell mReturn(f)
        set v to startValue
        set lng to length of xs
        repeat with i from 1 to lng
            set v to |λ|(v, item i of xs, i, xs)
        end repeat
        return v
    end tell
end foldl


-- justifyRight :: Int -> Char -> String -> String
on justifyRight(n, cFiller)
    script
        on |λ|(s)
            if n > length of s then
                text -n thru -1 of ((replicate(n, cFiller) as text) & s)
            else
                s
            end if
        end |λ|
    end script
end justifyRight


-- mReturn :: First-class m => (a -> b) -> m (a -> b)
on mReturn(f)
    -- 2nd class handler function lifted into 1st class script wrapper. 
    if script is class of f then
        f
    else
        script
            property |λ| : f
        end script
    end if
end mReturn


-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
    -- The list obtained by applying f
    -- to each element of xs.
    tell mReturn(f)
        set lng to length of xs
        set lst to {}
        repeat with i from 1 to lng
            set end of lst to |λ|(item i of xs, i, xs)
        end repeat
        return lst
    end tell
end map


-- max :: Ord a => a -> a -> a
on max(x, y)
    if x > y then
        x
    else
        y
    end if
end max


-- unlines :: [String] -> String
on unlines(xs)
    -- A single string formed by the intercalation
    -- of a list of strings with the newline character.
    set {dlm, my text item delimiters} to ¬
        {my text item delimiters, linefeed}
    set s to xs as text
    set my text item delimiters to dlm
    s
end unlines


-- unwords :: [String] -> String
on unwords(xs)
    set {dlm, my text item delimiters} to ¬
        {my text item delimiters, space}
    set s to xs as text
    set my text item delimiters to dlm
    return s
end unwords
Output:
1


1 1
1 1


1 1 1
1 0 1
1 1 1


1 1 1 1
1 0 0 1
1 0 0 1
1 1 1 1


1 1 1 1 1
1 0 0 0 1
1 0 0 0 1
1 0 0 0 1
1 1 1 1 1


1 1 1 1 1 1
1 0 0 0 0 1
1 0 0 0 0 1
1 0 0 0 0 1
1 0 0 0 0 1
1 1 1 1 1 1

Arturo

drawSquare: function [side][
    loop 1..side 'x ->
        print map 1..side 'y [
            (any? @[x=1 y=1 x=side y=side])? -> 1 -> 0
        ]
]

drawSquare 4
print ""
drawSquare 6
Output:
1 1 1 1
1 0 0 1
1 0 0 1
1 1 1 1

1 1 1 1 1 1
1 0 0 0 0 1
1 0 0 0 0 1
1 0 0 0 0 1
1 0 0 0 0 1
1 1 1 1 1 1

AWK

# syntax: GAWK -f FOUR_SIDES_OF_SQUARE.AWK
BEGIN {
    for (n=6; n<=7; n++) {
      for (i=1; i<=n; i++) {
        for (j=1; j<=n; j++) {
          tmp = (i==1 || i==n || j==1 || j==n) ? 1 : 0
          printf("%2d",tmp)
        }
        printf("\n")
      }
      print("")
    }
    exit(0)
}
Output:
 1 1 1 1 1 1
 1 0 0 0 0 1
 1 0 0 0 0 1
 1 0 0 0 0 1
 1 0 0 0 0 1
 1 1 1 1 1 1

 1 1 1 1 1 1 1
 1 0 0 0 0 0 1
 1 0 0 0 0 0 1
 1 0 0 0 0 0 1
 1 0 0 0 0 0 1
 1 0 0 0 0 0 1
 1 1 1 1 1 1 1

BQN

Square  ⌜˜1⌽↑11

Square 5
Output:
┌─
╵ 1 1 1 1 1
  1 0 0 0 1
  1 0 0 0 1
  1 0 0 0 1
  1 1 1 1 1
            ┘

C

#include <stdio.h>

void hollowMatrix(unsigned int n) {
    int i, j;
    for (i = 0; i < n; ++i) {
        for (j = 0; j < n; ++j) {
            if (i == 0 || i == n - 1 || j == 0 || j == n - 1) {
                printf("%d ", 1);
            } else {
                printf("%d ", 0);
            }
        }
        printf("\n");
    }
}

int main() {
    hollowMatrix(10);
    printf("\n");
    hollowMatrix(11);
    return 0;
}
Output:
1 1 1 1 1 1 1 1 1 1 
1 0 0 0 0 0 0 0 0 1 
1 0 0 0 0 0 0 0 0 1 
1 0 0 0 0 0 0 0 0 1 
1 0 0 0 0 0 0 0 0 1 
1 0 0 0 0 0 0 0 0 1 
1 0 0 0 0 0 0 0 0 1 
1 0 0 0 0 0 0 0 0 1 
1 0 0 0 0 0 0 0 0 1 
1 1 1 1 1 1 1 1 1 1 

1 1 1 1 1 1 1 1 1 1 1 
1 0 0 0 0 0 0 0 0 0 1 
1 0 0 0 0 0 0 0 0 0 1 
1 0 0 0 0 0 0 0 0 0 1 
1 0 0 0 0 0 0 0 0 0 1 
1 0 0 0 0 0 0 0 0 0 1 
1 0 0 0 0 0 0 0 0 0 1 
1 0 0 0 0 0 0 0 0 0 1 
1 0 0 0 0 0 0 0 0 0 1 
1 0 0 0 0 0 0 0 0 0 1 
1 1 1 1 1 1 1 1 1 1 1 

C++

#include <concepts>
#include <iostream>

// Print each element of a matrix according to a predicate.  It
// will print a '1' if the predicate function is true, otherwise '0'. 
void PrintMatrix(std::predicate<int, int, int> auto f, int size)
{
  for(int y = 0; y < size; y++)
  {
    for(int x = 0; x < size; x++)
    {
      std::cout << " " << f(x, y, size);
    }
    std::cout << "\n";
  }
  std::cout << "\n";
}

int main()
{
  // a lambda to show the sides
  auto fourSides = [](int x, int y, int size)
  {
    return x == 0 || (y == 0) || (x == size - 1) || (y == size - 1);
  };

  PrintMatrix(fourSides, 8);
  PrintMatrix(fourSides, 9);
}
Output:
 1 1 1 1 1 1 1 1
 1 0 0 0 0 0 0 1
 1 0 0 0 0 0 0 1
 1 0 0 0 0 0 0 1
 1 0 0 0 0 0 0 1
 1 0 0 0 0 0 0 1
 1 0 0 0 0 0 0 1
 1 1 1 1 1 1 1 1

 1 1 1 1 1 1 1 1 1
 1 0 0 0 0 0 0 0 1
 1 0 0 0 0 0 0 0 1
 1 0 0 0 0 0 0 0 1
 1 0 0 0 0 0 0 0 1
 1 0 0 0 0 0 0 0 1
 1 0 0 0 0 0 0 0 1
 1 0 0 0 0 0 0 0 1
 1 1 1 1 1 1 1 1 1

Delphi

Works with: Delphi version 6.0


procedure FillSquare(Memo: TMemo; Size: integer);
var X,Y: integer;
var S: string;
begin
S:='';
for Y:=1 to Size do
	begin
	for X:=1 to Size do
		begin
		if (X=1) or (X=Size) or
		   (Y=1) or (Y=Size) then S:=S+' 1'
		else S:=S+' 0';
		end;
	S:=S+#$0D#$0A;
	end;
Memo.Lines.Add(S);
end;

procedure ShowFillSquare(Memo: TMemo);
begin
FillSquare(Memo, 6);
FillSquare(Memo, 7);
end;
Output:
 1 1 1 1 1 1
 1 0 0 0 0 1
 1 0 0 0 0 1
 1 0 0 0 0 1
 1 0 0 0 0 1
 1 1 1 1 1 1

 1 1 1 1 1 1 1
 1 0 0 0 0 0 1
 1 0 0 0 0 0 1
 1 0 0 0 0 0 1
 1 0 0 0 0 0 1
 1 0 0 0 0 0 1
 1 1 1 1 1 1 1

F#

// Four sides of square. Nigel Galloway: February 18th., 2022
let m11 m=Array2D.init m m (fun n g->if n=0 || g=0 || g=m-1 || n=m-1 then 1 else 0)
printfn "%A\n\n%A" (m11 5) (m11 6)
Output:
[[1; 1; 1; 1; 1]
 [1; 0; 0; 0; 1]
 [1; 0; 0; 0; 1]
 [1; 0; 0; 0; 1]
 [1; 1; 1; 1; 1]]

[[1; 1; 1; 1; 1; 1]
 [1; 0; 0; 0; 0; 1]
 [1; 0; 0; 0; 0; 1]
 [1; 0; 0; 0; 0; 1]
 [1; 0; 0; 0; 0; 1]
 [1; 1; 1; 1; 1; 1]]

FreeBASIC

Text based

Sub hollowMatrix(n As Integer)
    For i As Integer = 0 To n
        For j As Integer = 0 To n
            Print Iif((i = 0) Or (i = n) Or (j = 0) Or (j = n), "1 ", "0 ");
        Next j
        Print
    Next i
End Sub

hollowMatrix(9)
Sleep
Output:
1 1 1 1 1 1 1 1 1 
1 0 0 0 0 0 0 0 1 
1 0 0 0 0 0 0 0 1 
1 0 0 0 0 0 0 0 1 
1 0 0 0 0 0 0 0 1 
1 0 0 0 0 0 0 0 1 
1 0 0 0 0 0 0 0 1 
1 0 0 0 0 0 0 0 1 
1 1 1 1 1 1 1 1 1 

Graphical

Dim As Integer n = 9, size = 60 * n + 70
Screenres size, size, 24
Cls
Windowtitle "Four sides of square"

Dim As Integer beige = Rgb(245, 245, 220), brown = Rgb(171, 82, 54)

For x As Integer = 0 To n
    For y As Integer = 0 To n
        Dim As Integer cx = x*60 + 10
        Dim As Integer cy = y*60 + 10
        If (x = 0) Or (x = n) Or (y = 0) Or (y = n) Then
            Line (cx,cy) - (cx+50, cy+50), brown, BF
            Draw String (cx + 22, cy + 22), "1", 0
        Else
            Line (cx,cy) - (cx+50, cy+50), beige, BF
            Draw String (cx + 22, cy + 22), "0", 0
        End If
    Next y
Next x
Bsave "hollowMatrix.bmp",0
Sleep
Output:

https://www.dropbox.com/s/9g5ahfzw1muuzgm/hollowMatrix.bmp?dl=0

Go

package main

import "fmt"

func hollowMatrix(n uint) {
    for i := uint(0); i < n; i++ {
        for j := uint(0); j < n; j++ {
            if i == 0 || i == n-1 || j == 0 || j == n-1 {
                fmt.Printf("%d ", 1)
            } else {
                fmt.Printf("%d ", 0)
            }
        }
        fmt.Println()
    }
}

func main() {
    hollowMatrix(8)
    fmt.Println()
    hollowMatrix(9)
}
Output:
1 1 1 1 1 1 1 1 
1 0 0 0 0 0 0 1 
1 0 0 0 0 0 0 1 
1 0 0 0 0 0 0 1 
1 0 0 0 0 0 0 1 
1 0 0 0 0 0 0 1 
1 0 0 0 0 0 0 1 
1 1 1 1 1 1 1 1 

1 1 1 1 1 1 1 1 1 
1 0 0 0 0 0 0 0 1 
1 0 0 0 0 0 0 0 1 
1 0 0 0 0 0 0 0 1 
1 0 0 0 0 0 0 0 1 
1 0 0 0 0 0 0 0 1 
1 0 0 0 0 0 0 0 1 
1 0 0 0 0 0 0 0 1 
1 1 1 1 1 1 1 1 1 

Haskell

import Data.List (intercalate, intersperse)
import Data.List.Split (chunksOf)
import System.Environment (getArgs)

-- An n by n square of characters, having 1s on the borders and 0s in the
-- interior.  We assume n ≥ 0.
square :: Int -> String
square n = intercalate "\n" $ map (intersperse ' ') $ chunksOf n sq
  where sq = [sqChar r c | r <- [0..n-1], c <- [0..n-1]]
        sqChar r c = if isBorder r c then '1' else '0'
        isBorder r c = r == 0 || r == n-1 || c == 0 || c == n-1

main :: IO ()
main = do
  sizes <- map read <$> getArgs
  putStrLn $ intercalate "\n\n" $ map square sizes
Output:
$ four_sides 0 1 2 3 4 5


1

1 1
1 1

1 1 1
1 0 1
1 1 1

1 1 1 1
1 0 0 1
1 0 0 1
1 1 1 1

1 1 1 1 1
1 0 0 0 1
1 0 0 0 1
1 0 0 0 1
1 1 1 1 1


Or, expressed in terms of Data.Matrix:

import Data.Matrix

------------------ FOUR SIDES OF A SQUARE ----------------

fourSides :: Int -> Matrix Int
fourSides n = matrix n n 
  (\(i, j) -> (fromEnum . or) ((==) <$> [1, n] <*> [i, j]))


--------------------------- TEST -------------------------
main :: IO ()
main = mapM_ print $ fourSides <$> [0 .. 5]
Output:
┌  ┐
└  ┘
┌   ┐
│ 1 │
└   ┘
┌     ┐
│ 1 1 │
│ 1 1 │
└     ┘
┌       ┐
│ 1 1 1 │
│ 1 0 1 │
│ 1 1 1 │
└       ┘
┌         ┐
│ 1 1 1 1 │
│ 1 0 0 1 │
│ 1 0 0 1 │
│ 1 1 1 1 │
└         ┘
┌           ┐
│ 1 1 1 1 1 │
│ 1 0 0 0 1 │
│ 1 0 0 0 1 │
│ 1 0 0 0 1 │
│ 1 1 1 1 1 │
└           ┘

J

Implementation:

fsosq=: {{+./~(+.|.)y{.1}}

Some examples:

   fsosq 0
   fsosq 1
1
   fsosq 2
1 1
1 1
   fsosq 3
1 1 1
1 0 1
1 1 1
   fsosq 4
1 1 1 1
1 0 0 1
1 0 0 1
1 1 1 1
   fsosq 10
1 1 1 1 1 1 1 1 1 1
1 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 1
1 1 1 1 1 1 1 1 1 1

Gui examples are not visible here, but, for example:

   require'viewmat'
   viewmat fsosq 20
   viewmat fsosq 5

jq

Works with: jq

Works with gojq, the Go implementation of jq

def square_perimeter_matrix:
  [range(0; .) | 1] as $top
  | [1, (range(0; .-2) | 0), 1] as $two
  | [$top, (range(0; .-2)|$two), $top];

def display:
  map(join(" ")) | join("\n");

Example:

9|square_perimeter_matrix|display
Output:
1 1 1 1 1 1 1 1 1
1 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 1
1 1 1 1 1 1 1 1 1

Julia

Gtk graphical version.

using Gtk

function set_gtk_style!(widget::Gtk.GtkWidget, style::String, value::Int)
    sc = Gtk.GAccessor.style_context(widget)
    pr = Gtk.CssProviderLeaf(data=" button {$style}")
    push!(sc, Gtk.StyleProvider(pr), value)
end

function squareonesapp(N)
    win = GtkWindow("Ones Square", 700, 700)
    grid = GtkGrid()
    buttons = [GtkButton(i == 1 || j == 1 || i == N || j == N ? " 1 " : " 0 ") for i in 1:N, j in 1:N]
    for i in 1:N, j in 1:N
        grid[i, j] = buttons[i, j]
        set_gtk_property!(buttons[i, j], :expand, true)
        c = i == 1 || j == 1 || i == N || j == N ? "red" : "navy"
        set_gtk_style!(buttons[i, j], " font-size: 32px; background-color: $c ; ", 600)
    end
    push!(win, grid)
    condition = Condition()
    endit(w) = notify(condition)
    signal_connect(endit, win, :destroy)
    showall(win)
    wait(condition)
end

squareonesapp(8)

K

square: {x|/:x}{x||x}@~-':!:

square 5
Output:
(1 1 1 1 1
 1 0 0 0 1
 1 0 0 0 1
 1 0 0 0 1
 1 1 1 1 1)

Mathematica/Wolfram Language

Manipulate[ArrayPad[ConstantArray[0, {1, 1} n - 1], 1, 1] // Grid, {n, 2, 20, 1}]

Maxima

/* Function that returns a square matrix with square pattern in  their entries */
square(n):=genmatrix(lambda([x,y],if x=1 or y=1 or x=n or y=n then 1 else 0),n,n)$

/* Example */
square(6);
Output:
matrix(
		[1,	1,	1,	1,	1,	1],
		[1,	0,	0,	0,	0,	1],
		[1,	0,	0,	0,	0,	1],
		[1,	0,	0,	0,	0,	1],
		[1,	0,	0,	0,	0,	1],
		[1,	1,	1,	1,	1,	1]
	)

Nim

There are several ways to draw the square. Here is one of them:

import std/[sequtils, strutils]

proc drawSquare(n: Positive) =
  let s1 = repeat(1, n).join(" ")
  let s2 = (1 & repeat(0, n - 2) & 1).join(" ")
  echo s1
  for i in 2..<n: echo s2
  echo s1

drawSquare(7)
Output:
1 1 1 1 1 1 1
1 0 0 0 0 0 1
1 0 0 0 0 0 1
1 0 0 0 0 0 1
1 0 0 0 0 0 1
1 0 0 0 0 0 1
1 1 1 1 1 1 1

Perl

use strict;
use warnings;
use feature 'say';

my $n = 5;
say join ' ', @$_ for ([(1)x$n], (map { [1, (0)x($n-2), 1] } 0..$n-3), [(1)x$n]);
Output:
1 1 1 1 1
1 0 0 0 1
1 0 0 0 1
1 0 0 0 1
1 1 1 1 1

Phix

See Matrix_with_two_diagonals#Phix and press 'O'.

PL/M

Works with: 8080 PL/M Compiler
... under CP/M (or an emulator)
100H: /* DRAW SOME SQUARES WITH 1S ON THE EDGES and 0S ELSEWHERE             */

   /* CP/M SYSTEM CALL AND I/O ROUTINES                                      */
   BDOS:      PROCEDURE( FN, ARG ); DECLARE FN BYTE, ARG ADDRESS; GOTO 5; END;
   PR$CHAR:   PROCEDURE( C ); DECLARE C BYTE;    CALL BDOS( 2, C );  END;
   PR$NL:     PROCEDURE;   CALL PR$CHAR( 0DH ); CALL PR$CHAR( 0AH ); END;

   /* TASK                                                                   */

   DRAW$SQUARE: PROCEDURE( N );
      DECLARE N BYTE;
      DECLARE ( I, J ) BYTE;
      DO I = 1 TO N;
         DO J = 1 TO N;
            CALL PR$CHAR( ' ' );
            IF I = 1 OR I = N OR J = 1 OR J = N THEN CALL PR$CHAR( '1' );
                                                ELSE CALL PR$CHAR( '0' );
         END;
         CALL PR$NL;
      END;
   END DRAW$SQUARE ;

   CALL DRAW$SQUARE( 6 );
   CALL PR$NL;
   CALL DRAW$SQUARE( 7 );

EOF
Output:
 1 1 1 1 1 1
 1 0 0 0 0 1
 1 0 0 0 0 1
 1 0 0 0 0 1
 1 0 0 0 0 1
 1 1 1 1 1 1

 1 1 1 1 1 1 1
 1 0 0 0 0 0 1
 1 0 0 0 0 0 1
 1 0 0 0 0 0 1
 1 0 0 0 0 0 1
 1 0 0 0 0 0 1
 1 1 1 1 1 1 1

Processing

//Aamrun, 27th June 2022

size(1000,1000);

textSize(50);

for(int i=0;i<10;i++){
  for(int j=0;j<10;j++){
    noFill();
    square(i*100,j*100,100);
    fill(#000000);
    if(i==0||i==9||j==0||j==9){
      text("1",i*100+50,j*100+50);
    }
    else{
      text("0",i*100+50,j*100+50);
    } 
  }
}

Python

Procedural

size = 9
for row in range(size):
    for col in range(size):
        if row == 0 or row == size-1 or col == 0 or col == size-1:
            print("1", end=" ")
        else:
            print("0", end=" ")
    print()
Output:

See Raku output.

Elaborate procedural

The following version illustrates several features of Python, such as default arguments, nested functions with lexical scoping, generators, and convenient syntax for creating sets and performing set operations such as intersection.

def square(size=9):

    def is_at_border(row, col):
        # `&` is set intersection: if the set {row, col} intersects the set
        # {0, size-1}, then at least one of (row, col) is either 0 or size-1
        return {row, col} & {0, size-1}

    for row in range(size):
        print(' '.join(
            '1' if is_at_border(row, col) else '0'
            for col in range(size)
        ))

suqare()

Functional

'''Four sides of a square'''


# fourSides :: Int -> [[Int]]
def fourSides(n):
    '''A square grid with ones in all edge values
       and zeros elsewhere.
    '''
    edge = [1, n]
    return matrix(
        n, n, lambda row, col: int(
            row in edge or col in edge
        )
    )


# ------------------------- TEST -------------------------
# main :: IO ()
def main():
    '''Square grids of dimension 7 and 10'''
    for n in [7, 10]:
        print(
            showMatrix(
                fourSides(n)
            ) + '\n'
        )


# ----------------------- GENERIC ------------------------

# matrix :: Int -> Int -> ((Int, Int) -> a) -> [[a]]
def matrix(nRows, nCols, f):
    '''A matrix of a given number of columns and rows,
       in which each value is a given function over the
       tuple of its (one-based) row and column indices.
    '''
    return [
        [f(y, x) for x in range(1, 1 + nCols)]
        for y in range(1, 1 + nRows)
    ]


# showMatrix :: [[a]] -> String
def showMatrix(rows):
    '''String representation of a matrix'''
    return '\n'.join([
        ' '.join([str(x) for x in y]) for y in rows
    ])


# MAIN ---
if __name__ == '__main__':
    main()
Output:
1 1 1 1 1 1 1
1 0 0 0 0 0 1
1 0 0 0 0 0 1
1 0 0 0 0 0 1
1 0 0 0 0 0 1
1 0 0 0 0 0 1
1 1 1 1 1 1 1

1 1 1 1 1 1 1 1 1 1
1 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 1
1 1 1 1 1 1 1 1 1 1

Quackery

  [ 0 over 2 - of
    1 tuck join join nested
    over 2 - of
    1 rot of
    nested tuck join join ] is four-sides ( n --> [ )

  8 four-sides
  witheach
    [ witheach [ echo sp ] cr ]
  cr
  9 four-sides
  witheach
    [ witheach [ echo sp ] cr ]
Output:
1 1 1 1 1 1 1 1 
1 0 0 0 0 0 0 1 
1 0 0 0 0 0 0 1 
1 0 0 0 0 0 0 1 
1 0 0 0 0 0 0 1 
1 0 0 0 0 0 0 1 
1 0 0 0 0 0 0 1 
1 1 1 1 1 1 1 1 

1 1 1 1 1 1 1 1 1 
1 0 0 0 0 0 0 0 1 
1 0 0 0 0 0 0 0 1 
1 0 0 0 0 0 0 0 1 
1 0 0 0 0 0 0 0 1 
1 0 0 0 0 0 0 0 1 
1 0 0 0 0 0 0 0 1 
1 0 0 0 0 0 0 0 1 
1 1 1 1 1 1 1 1 1 

Raku

This isn't a matrix, especially if it is supposed to be graphical; it's a very small (or extremely low resolution) bitmap.

sub hollow ($n) { [1 xx $n], |(0 ^..^ $n).map( { [flat 1, 0 xx $n - 2, 1] } ), [1 xx $n] }

.put for hollow 7;
put '';
.put for hollow 10;
Output:
1 1 1 1 1 1 1
1 0 0 0 0 0 1
1 0 0 0 0 0 1
1 0 0 0 0 0 1
1 0 0 0 0 0 1
1 0 0 0 0 0 1
1 0 0 0 0 0 1
1 1 1 1 1 1 1

1 1 1 1 1 1 1 1 1 1
1 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 1
1 1 1 1 1 1 1 1 1 1

Red

Red[]

view-square: function [size][
    matrix: copy [
        title "Four sides of a square"
        style cell: base 50x50 font-size 20
        style one: cell brown font-color beige "1"  ; I am not an artist. Please have mercy!
        style zero: cell beige font-color brown "0"
    ]
    repeat i size [
        either any [i = 1 i = size] [
            append matrix append/dup copy [] 'one size
        ][
            row: append/dup copy [] 'zero size
            row/1: row/:size: 'one
            append matrix row
        ]
        append matrix 'return
    ]
    view matrix
]

view-square 9
Output:

https://commons.wikimedia.org/wiki/File:Hollow_matrix_gui.png

Ring

# Project : Identity Matrix
# Date    : 2022/16/02
# Author  : Gal Zsolt (~ CalmoSoft ~)
# Email   : <calmosoft@gmail.com>

load "stdlib.ring"
load "guilib.ring"

size = 9
C_Spacing = 1

C_ButtonBlueStyle   = 'border-radius:6px;color:black; background-color: blue'
C_ButtonOrangeStyle = 'border-radius:6px;color:black; background-color: orange'

Button = newlist(size,size)
LayoutButtonRow = list(size)

app = new qApp 
{
      win = new qWidget() {
	    setWindowTitle('Identity Matrix')
	    move(500,100)
	    reSize(600,600)
	    winheight = win.height()
	    fontSize = 18 + (winheight / 100)

 	    LayoutButtonMain = new QVBoxLayout()			
	    LayoutButtonMain.setSpacing(C_Spacing)
	    LayoutButtonMain.setContentsmargins(0,0,0,0)

	    for Row = 1 to size
		LayoutButtonRow[Row] = new QHBoxLayout() {
				       setSpacing(C_Spacing)
				       setContentsmargins(0,0,0,0)
				       } 
         	 for Col = 1 to size
		     Button[Row][Col] = new QPushButton(win) {
                                        setSizePolicy(1,1)                                                
					}
					
		     LayoutButtonRow[Row].AddWidget(Button[Row][Col])	
		 next
		 LayoutButtonMain.AddLayout(LayoutButtonRow[Row])			
	      next
              LayoutDataRow1 = new QHBoxLayout() { setSpacing(C_Spacing) setContentsMargins(0,0,0,0) }
              LayoutButtonMain.AddLayout(LayoutDataRow1)
              setLayout(LayoutButtonMain)
              show()
   }
   pBegin()
   exec()
   }

func pBegin()
     for Row = 1 to size
         for Col = 1 to size 
             if Row = 1 or row = size or Col = 1 or Col = size
                Button[Row][Col].setStyleSheet(C_ButtonOrangeStyle)
                Button[Row][Col].settext("1")
             else
                Button[Row][Col].setStyleSheet(C_ButtonBlueStyle)
                Button[Row][Col].settext("0")
             ok
	 next
     next

Output image:
Four sides of square

RPL

≪ → n 
  ≪ "" 1 n START "1 " + NEXT DUP
     2 n 1 - START 
        "" 1 n FOR j j 1 == j n == OR →STR + " " + NEXT NEXT
     n ROLL 1 n FOR j j DISP NEXT
≫ ≫ 'TASK' STO
4 TASK
Output:
1 1 1 1
1 0 0 1
1 0 0 1
1 1 1 1

Ruby

def square_sides(size = 9)
  Array.new(size){|n| n==0 || n==size-1 ? [1]*size : [1]+[0]*(size-2)+[1]}
end

puts square_sides.map{|line| line.join (" ") }
Output:
1 1 1 1 1 1 1 1 1
1 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 1
1 1 1 1 1 1 1 1 1

Sidef

var n = 5

[n.of(1), (n-2).of([1, (n-2).of(0)..., 1])..., n.of(1)].each {|row|
    say row.join(' ')
}
Output:
1 1 1 1 1
1 0 0 0 1
1 0 0 0 1
1 0 0 0 1
1 1 1 1 1

Wren

Text based

var hollowMatrix = Fn.new { |n|
    for (i in 0...n) {
        for (j in 0...n) {
            System.write((i == 0 || i == n-1 || j == 0 || j == n-1) ? "1 " : "0 ")
        }
        System.print()
    }
}

hollowMatrix.call(9)
Output:
1 1 1 1 1 1 1 1 1 
1 0 0 0 0 0 0 0 1 
1 0 0 0 0 0 0 0 1 
1 0 0 0 0 0 0 0 1 
1 0 0 0 0 0 0 0 1 
1 0 0 0 0 0 0 0 1 
1 0 0 0 0 0 0 0 1 
1 0 0 0 0 0 0 0 1 
1 1 1 1 1 1 1 1 1 

Graphical

Library: DOME
Library: Go-fonts

This is designed to look as close as possible to the Red entry's image so that we don't have to fill up Wikimedia Commons with similar looking images.

import "dome" for Window
import "graphics" for Canvas, Color, Font
class Main {
    construct new(n) {
        var size = 60 * n + 10
        Window.resize(size, size)
        Canvas.resize(size, size)
        Window.title = "Four sides of a square"
        // see Go-fonts page
        Font.load("Go-Regular20", "Go-Regular.ttf", 20)
        Canvas.font = "Go-Regular20"
        var beige = Color.new(245, 245, 220)
        Canvas.cls(Color.lightgray)
        for (x in 0...n) {
            for (y in 0...n) {
                var cx = x*60 + 10
                var cy = y*60 + 10
                if (x == 0 || x == n-1 || y == 0 || y == n-1) {
                    Canvas.rectfill(cx, cy, 50, 50, Color.brown)
                    Canvas.print("1", cx + 20, cy + 15, beige)
                 } else {
                    Canvas.rectfill(cx, cy, 50, 50, beige)
                    Canvas.print("0", cx + 20, cy + 15, Color.brown)
                 }
            }
        }
    }

    init() {}

    update() {}

    draw(alpha) {}
}

var Game = Main.new(9)
Output:
Similar to Red entry image.

XPL0

proc DrawMat(S);
int  S, I, J;
[for I:= 0 to S-1 do
    [for J:= 0 to S-1 do
        Text(0, if I>0 & I<S-1 & J>0 & J<S-1 then "0 " else "1 ");
    CrLf(0);
    ];
];
[DrawMat(6);  CrLf(0);
 DrawMat(7);  CrLf(0);
]
Output:
1 1 1 1 1 1 
1 0 0 0 0 1 
1 0 0 0 0 1 
1 0 0 0 0 1 
1 0 0 0 0 1 
1 1 1 1 1 1 

1 1 1 1 1 1 1 
1 0 0 0 0 0 1 
1 0 0 0 0 0 1 
1 0 0 0 0 0 1 
1 0 0 0 0 0 1 
1 0 0 0 0 0 1 
1 1 1 1 1 1 1