How to resolve the algorithm Identity matrix step by step in the Prolog programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Identity matrix step by step in the Prolog programming language

Table of Contents

Problem Statement

Build an   identity matrix   of a size known at run-time.

An identity matrix is a square matrix of size n × n, where the diagonal elements are all 1s (ones), and all the other elements are all 0s (zeroes).

I

n

=

[

1

0

0

0

0

1

0

0

0

0

1

0

0

0

0

1

]

{\displaystyle I_{n}={\begin{bmatrix}1&0&0&\cdots &0\0&1&0&\cdots &0\0&0&1&\cdots &0\\vdots &\vdots &\vdots &\ddots &\vdots \0&0&0&\cdots &1\\end{bmatrix}}}

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Identity matrix step by step in the Prolog programming language

Source code in the prolog programming language

%rotates one list clockwise by one integer
rotate(Int,List,Rotated) :-
	integer(Int),
	length(Suff,Int),
	append(Pre,Suff,List),
	append(Suff,Pre,Rotated).
%rotates a list of lists by a list of integers
rotate(LoInts,LoLists,Rotated) :-
	is_list(LoInts),
	maplist(rotate,LoInts,LoLists,Rotated).

%helper function
append_(Suff,Pre,List) :-
	append([Pre],Suff,List).	
idmatrix(N,IdMatrix):-
	%make an N length list of 1s and append with N-1 0s
	length(Ones,N),
	maplist(=(1),Ones),
	succ(N0,N),
	length(Zeros,N0),
	maplist(=(0),Zeros),
	maplist(append_(Zeros),Ones,M),
	%create the offsets at rotate each row
	numlist(0,N0,Offsets),
	rotate(Offsets,M,IdMatrix).

main :-
	idmatrix(5,I),
	maplist(writeln,I).


  

You may also check:How to resolve the algorithm Almost prime step by step in the Kotlin programming language
You may also check:How to resolve the algorithm Fermat numbers step by step in the Nim programming language
You may also check:How to resolve the algorithm Nim game step by step in the J programming language
You may also check:How to resolve the algorithm Feigenbaum constant calculation step by step in the J programming language
You may also check:How to resolve the algorithm Total circles area step by step in the Julia programming language