Tuesday, February 27, 2007

Coding day's for fun

this code was inspired from people in forum when ask me an algorithm. this is an implementation from the algorithm. It's only for fun and for wasting a time. also to learn programming language. I hope this's not the last.

Bash script version
-------------------
start here
-------------------
#!/bin/bash
echo -n "Your input: "; read input
let temp=$input/2
let temp=$temp+1
let count=0
let i=1
echo $temp
while ((i<=input))
do
let j=1
let left=1
let right=$input
if [[ $i -le $temp ]]; then
let count=$count+1
elif [[ $i -gt $temp ]]; then
let count=$count-1
fi

while ((j<=input))
do
if [[ $left -le $count ]]; then
echo -n "$left "
elif [[ $right -le $count ]]; then
echo -n "$right "
else
echo -n "$count "
fi
let left=$left+1
let right=$right-1
let j=$j+1
done
let i=$i+1;
echo ""
done

C Version
---------------
Start here
---------------
#filename: funcode.c
int main ()
{
int input, temp=0, count=0;
int i,j,left,right;

printf ("Your input: ");scanf("%d",&input);
printf ("
Dimention: %d \n",input);
temp=(input/2) + 1;
printf("temp: %d \n",temp);

for (i=1; i<=input; i++)
{
j=1;
left=1;
right=input;

if (i <= temp)
count++;
else if (i> temp)
count--;

for (j=1; j<=input; j++)
{
if (left <= count)
printf("%d ",left);
else if (right <= count)
printf("%d ",right);
else
printf("%d ",count);
left++;
right--;
}
printf("\n");
}
return 0;
}

An output is here:
mine@unique:~$ ./funcode
Your input: 5
Dimention: 5
temp: 3
1 1 1 1 1
1 2 2 2 1
1 2 3 2 1
1 2 2 2 1
1 1 1 1 1
mine@unique:~$

No comments:

Post a Comment