AlexZ

CHALLENGE : Floyd's Triangle

6 posts in this topic

Create a program in what language you want, which create this triangle of number :


1
2 3
4 5 6
7 8 9 10
11 12 13 14 15

If you haven't understood the problem, you can follow the explaination on wikipedia of this particular triangle!!!

Here i link my solution, don't look at that before you've written yours program!! :P

Edited by AlexZ
0

Share this post


Link to post
Share on other sites

Heres my solution in python


def floyd(n):
count = 1
string = ""
for i in range(1,n+2):
for j in range(1,i):
string = string + " " + str(count)
count = count + 1
print(string)
string = ""

0

Share this post


Link to post
Share on other sites

Ruby solution

#!/usr/bin/ruby -w
# Floyd's Triangle

class FloydsTriangle
def self.generate(max=15)
line = 1
added = 0
triangle = ""

for n in 1..max do
triangle += "#{n.to_s} "
added += 1

if added == line
triangle += "\n"
added = 0
line += 1
end
end

triangle
end

def self.print(max=15)
puts generate(max)
end
end

if ARGV[0].to_i > 0
FloydsTriangle.print(ARGV[0].to_i)
else
FloydsTriangle.print
end

0

Share this post


Link to post
Share on other sites

How did I miss this one??

Here's mine in C

#include<stdio.h>
#define MAX 15
int main (void)
{
int x =0; //thought "int x,y,z = 0" would initalize all three to zero... but no... it's not happening"
int y =0;
int z= 0;
while (x++ < MAX)
{
printf("%2i ",x);
if (++y > z)
{
printf("\n");
z++;
y = 0;
}
}
return 0;
}

1

Share this post


Link to post
Share on other sites

Heres my solution in python


def floyd(n):
count = 1
string = ""
for i in range(1,n+2):
for j in range(1,i):
string = string + " " + str(count)
count = count + 1
print(string)
string = ""

This is much better then mine, but here is how i did it.


def floydtriangle(begin,end):
maxwidth = len(str(end))
counter = 0
output = ""
next = 0
for num in range(begin, end):
if next == 0:
output = output + str(num) + '\n'
counter = counter + 1
next = counter
else:
pad = maxwidth - len(str(num))
pad = pad * " "
pad = str(pad) + " "
output = output + str(num) + pad
next = next -1
return output
def main():
print floydtriangle(1,16)

if __name__ == '__main__':
main()

Edited by Lord Wud
0

Share this post


Link to post
Share on other sites

Perl solution


#!/usr/bin/perl
$number=$loopcount=1;
while (1) {
for ($i=0;$i<$loopcount;$i++) {print $number++ . " ";}
print "\n";
$loopcount++;
}

0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now