Interview Question
Java DevelopersCountry: India
Very simple solution and works with unsorted array and arrays with different size.
Ah.. generic too. Could be applied for chars, strings and so on...
/*
i have an array{{1,2,3},{4,5,6},{7,8,9}}.I want output=1,2,4,3,5,7,6,8,9
*/
#include <iostream>
#include <vector>
template <typename T>
void print_specific_order(std::vector< std::vector<T> > & vec) {
T saved;
bool is_saved = false;
for(auto v: vec) {
for(int i = 0; i < v.size(); ++i) {
if(i == v.size()-1) {
saved = v[i];
is_saved = true;
continue;
}
std::cout << v[i] << std::endl;
if(is_saved) {
std::cout << saved << std::endl;
is_saved = !is_saved;
}
}
}
std::cout << saved << std::endl;
}
int main() {
std::vector< std::vector<int> > vec {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
print_specific_order<int>(vec);
return 0;
}
public static void printElements(int[][] input) {
for (int i = 0; i < input.length; i++) {
int myNewArr[] = input[i];
for (int j = 0; j < myNewArr.length; j++) {
System.out.print(myNewArr[j]);
}
}
}
This is working for the above given input.
public static void main(String[] args) {
//int[][] a = {{1,2,3}, {4,5,6}, {7,8,9}};
//int[][] a = {{1,2}, {3,4}};
int[][] a = {{1,2,3,4}, {5,6,7,8}, {9,10,11,12}};
int x = a[0].length;
for(int i = 0; i < x; i++){
System.out.println(a[0][i]);
printIndex(a, i-1 , 1);
}
for(int i = 1; i < a.length; i++){
System.out.println(a[i][x-1]);
printIndex(a, x-2 , i + 1);
}
}
public static void printIndex(int[][] a, int x, int y){
if(x < 0 || y >= a.length)
return;
System.out.println(a[y][x]);
printIndex(a, x -1, y +1);
}
#include <iostream>
using namespace std;
#define MAX 5
int main(){
int a[MAX][MAX] =
{{ 1, 2, 3, 4, 5},
{ 6, 7, 8, 9,10},
{11,12,13,14,15},
{16,17,18,19,20},
{21,22,23,24,25}};
int i=0,j=0;
while(i<MAX){
cout << a[i][j] << " -> ";
if(i==MAX-1){
i = j+1; j = MAX-1;
}
else if(j==0){
j = i+1; i = 0;
}
else{
i++; j--;
}
}
cout << endl;
return 0;
}
works with square array
void prettyPrint(int[][] arr) {
for (int i = 0; i < arr.length; i++) {
int k = 0;
for (int j = i; j >= 0; j--) {
System.out.print(arr[k++][j] + " ");
}
}
for (int i = 1; i < arr.length; i++) {
int k = i;
for (int j = arr.length-1; j >= i; j--) {
System.out.print(arr[k++][j] + " ");
}
}
}
The following code also works for non-square matrix
- chriscow January 29, 2014