#include "PointersLibs.h"
#include <stdio.h>
#include <malloc.h>

void Swap(int *num1, int *num2)
{
	//swaps between two numbers
	int temp = *num1;
	*num1 = *num2;
	*num2 = temp;
}

void SortMat(int *mat,int max_size)
{
	//sorts them by ascending order
	for (int count = ZERO; count < max_size; count++)
	{
		for (int counter = count + ONE; counter < max_size; counter++)
		{
			(*(mat + count) > *(mat + counter)) ?
				Swap((mat + count) ,(mat + counter)): ZERO;
		}
	}
}


void Switcharoo(int *begin,int *stop)
{
	//switches between numbers in a certain
	while (stop > begin)
	{
		int temp = *begin;
		*begin = *stop;
		*stop = temp;
		stop--;
		begin++;
	}
}

void Special_Print_for_sixth(int *mat,int size)
{
	//special print for ex 6
	int amnt = size*size;
	for (int count = ZERO; count < size; count++)
	{
		for (int counter = count; counter < size*size; counter += size)
		{
			printf("%d ", *(mat + counter));
		}
		printf("\n");
	}
}

void PutIn(int *mat,int num,int N)
{
	*mat = num;
	int maxsize = N * N;
	SortMat(mat,maxsize);
	for (int count = ZERO; count < maxsize; count++)
	{
		//switches the even rows values places
		//so that when you print it shows ok
		((count / N) % TWO == ONE) ? Switcharoo((mat + count), (mat + count + N - ONE)) : ZERO;
		((count / N) % TWO == ONE) ? count += N - ONE : ZERO;
	}
}


//---------------------------------------------------------------------------------------
//								exe 6
//                              -----
//
// General : the program sorts the numbers in an ascending order
//              and then adds a number that is desiered to the matrix, sorts it
//              again.
//
// Input   : size o the matrix, and N^2 of numbers.
//
// Process : sorts in ascending order and then sorts them according to the wanted way.
//
// Output  : prints the new matrix.
//
//---------------------------------------------------------------------------------------
// Proggramer : Cohen Idan
// Student No : 211675038
// Date       : 22.11.19
//---------------------------------------------------------------------------------------
void main(void)
{
	int N = ZERO;
	int *mat = (int*)malloc(sizeof(int));
	printf("enter Size: ");
	scanf("%d", &N);
	int maxsize = N * N;
	int num = ZERO;
	for (int sofer = ZERO; sofer < maxsize; sofer++)
	{
		mat = realloc(mat, sizeof(int)*(sofer+ONE));
		printf("enter no.%d: ",sofer+ONE);
		scanf("%d", &(*(mat+sofer)));
	}
	SortMat(mat,maxsize);
	for (int count = ZERO; count < maxsize; count++)
	{
		//switches the even rows values places
		//so that when you print it shows ok
		((count / N) % TWO == ONE) ? Switcharoo((mat + count), (mat + count + N - ONE)) : ZERO;
		((count / N) % TWO == ONE) ? count += N - ONE : ZERO;
	}
	Special_Print_for_sixth(mat, N);
	printf("enter number to enter: ");
	scanf("%d", &num);
	PutIn(mat, num, N);
	Special_Print_for_sixth(mat, N);
	free(mat);
}