Four sides of square: Difference between revisions

From Rosetta Code
Content added Content deleted
(→‎{{header|Python}}: Normalized from tabs to space multiples in Calmosoft's contribution.)
(→‎{{header|Python}}: Added a functionally composed version.)
Line 442: Line 442:


=={{header|Python}}==
=={{header|Python}}==
===Procedural===
<lang python>size = 9
<lang python>size = 9
for Row in range(size):
for Row in range(size):
Line 452: Line 453:
{{out}}
{{out}}
See Raku output.
See Raku output.

===Functional===
<lang python>'''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()</lang>
{{Out}}
<pre>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</pre>


=={{header|Raku}}==
=={{header|Raku}}==

Revision as of 19:18, 24 February 2022

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

Ada

<lang 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;</lang>

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

<lang algol68>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 </lang>

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

AWK

<lang AWK>

  1. 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)

} </lang>

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

C

<lang 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;

}</lang>

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++

<lang cpp>#include <concepts>

  1. 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);

}

</lang>

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

F#

<lang fsharp> // 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) </lang>

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

<lang freebasic>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</lang>

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

<lang freebasic>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</lang>

Output:

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


Go

<lang 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)

}</lang>

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 

J

Implementation: <lang J>fsosq=: Template:+./~(+.</lang>

Some examples:

<lang J> 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</lang>

Gui examples are not visible here, but, for example: <lang J> require'viewmat'

  viewmat fsosq 20
  viewmat fsosq 5</lang>

Julia

Gtk graphical version. <lang julia>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) </lang>

Perl

<lang 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]);</lang>

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'.

Python

Procedural

<lang python>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()</lang>
Output:

See Raku output.

Functional

<lang python>Four sides of a square


  1. 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
       )
   )


  1. ------------------------- TEST -------------------------
  2. main :: IO ()

def main():

   Square grids of dimension 7 and 10
   for n in [7, 10]:
       print(
           showMatrix(
               fourSides(n)
           ) + '\n'
       )


  1. ----------------------- GENERIC ------------------------
  1. 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)
   ]


  1. 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
   ])


  1. MAIN ---

if __name__ == '__main__':

   main()</lang>
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

Raku

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

<lang perl6>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;</lang>

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

<lang rebol>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</lang>

Output:

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

Ring

<lang ring>

  1. Project : Identity Matrix
  2. Date  : 2022/16/02
  3. Author  : Gal Zsolt (~ CalmoSoft ~)
  4. 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

</lang> Output image:
Four sides of square

Wren

Text based

<lang ecmascript>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)</lang>

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. <lang ecmascript>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)</lang>

Output:
Similar to Red entry image.

XPL0

<lang 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);

]</lang>

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