Generate the Floyd triangle.
Example:
Input: 3
Output: 1
2 3
4 5 6
Approach
Java
import java.util.ArrayList;import java.util.List;public class FloydsTrianglePattern {public static void main(String[] args) {int n = 3;List<List<Integer>> floyed = floyedTriangle(n);for (int i = 0; i < floyed.size(); i++) {for (int j = 0; j < floyed.get(i).size(); j++)System.out.print(floyed.get(i).get(j) + " ");System.out.println();}}//function to generate the floyed trianglestatic List<List<Integer>> floyedTriangle(int n) {List<List<Integer>> floyed = new ArrayList<List<Integer>>();int num = 1;for (int i = 1; i <= n; i++) {List<Integer> x = new ArrayList<Integer>();for (int j = 1; j <= i; j++)x.add(num++);floyed.add(x);}return floyed;}}
C++
#include <bits/stdc++.h>using namespace std;//function to generate the floyed//trianglevector<vector<int>> floyedTriangle(int n){vector<vector<int>> floyed;int num=1;for(int i=1;i<=n;i++){vector<int> x;for(int j=1;j<=i;j++)x.push_back(num++);floyed.push_back(x);}return floyed;}int main(){int n=3;vector<vector<int>> floyed=floyedTriangle(n);for(int i=0;i<floyed.size();i++){for(int j=0;j<floyed[i].size();j++)cout<<floyed[i][j]<<" ";cout<<"\n";}return 0;}
No comments:
Post a Comment