From 83d0cdef6fbce344b4764ea81881d0918bf8bf99 Mon Sep 17 00:00:00 2001 From: Alex Stan <90788596+Ultra980@users.noreply.github.com> Date: Sun, 15 Oct 2023 22:18:42 +0300 Subject: [PATCH] Create print_permutations_1_to_n.cpp This prints the permutations of the array `[ 1, 2, 3, ..., n ]`, in lexicographical order. --- algorithms/print_permutations_1_to_n.cpp | 40 ++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 algorithms/print_permutations_1_to_n.cpp diff --git a/algorithms/print_permutations_1_to_n.cpp b/algorithms/print_permutations_1_to_n.cpp new file mode 100644 index 00000000..692845d2 --- /dev/null +++ b/algorithms/print_permutations_1_to_n.cpp @@ -0,0 +1,40 @@ +#include <bits/stdc++.h> +using namespace std; + +const int NMAX = 100000; +bool used[ NMAX + 1 ]; +int v[ NMAX + 1 ]; + +ifstream fin( "permutari1.in" ); +ofstream fout( "permutari1.out" ); + +void make_perm( int pos, int n ) { + int i; + if ( pos == n + 1 ) { + for ( i = 1; i <= n; i++ ) + cout << v[ i ] << ' '; + cout << '\n'; + return; + } + + for ( i = 1; i <= n; i++ ) { + if ( !used[ i ] ) { + used[ i ] = true; + v[ pos ] = i; + make_perm( pos + 1, n ); + used[ i ] = false; + } + } +} + +int main() { + int n; + + cout << "Input an integer: "; + cin >> n; + + cout << "These are the permutations of the array [ 1, 2, 3, ..., n ]:\n"; + make_perm( 1, n ); + + return 0; +}