Vice City: Multiplayer

Off-Topic => Off-Topic General => Topic started by: . on Jun 10, 2015, 10:13 AM

Title: Scripting challenges!
Post by: . on Jun 10, 2015, 10:13 AM
I decided to be a troll and have some fun with scripters by testing their creativity. So, I will post some challenges and let's see if you can do complete them and how creative is your approach. I will choose the most creative one's based on how elegant the implementation is. Sux we do't have a spoiler tag on the forum :D



RULES


[spoiler]The spoiler tag can be used with  [-spoiler] ... [-/spoiler] (without the '-'). Example of adding code in spoiler tags:

[-spoiler]
 [-code]
  print("This code should be hidden!");
 [-/code]
[-/spoiler]

The '-' is added to allow you to see the tags. Otherwise would be treated as a tag and would be converted to HTML. You don't need he '-'.

[/spoiler]



CHALLENGES




ATTENTION: A single post per application is allowed to avoid spam. If you feel like you want to update your code then edit the post and add a [-hr] (without the '-') tag at the bottom and with a bold text saying UPDATE: following the update...

ATTENTION: If your post ends up rather too large. Consider using an external source for the code. The external source must be trustworthy (like pastebin.com) and the source host must be permanent.



LET THE GAMES BEGIN!
Title: Re: Scripting challenges!
Post by: Stormeus on Jun 10, 2015, 10:40 AM
Quote from: S.L.C on Jun 10, 2015, 10:13 AMRULES:
  • >STAFF MEMBERS EXCLUDED! WE ALL KNOW YOU CAN READ A DOCUMENTATION UNLIKE THE USUAL SCRIPTER

Damn.

[spoiler]Also we do have a spoiler tag[/spoiler]
Title: Re: Scripting challenges!
Post by: . on Jun 10, 2015, 10:55 AM
Quote from: stormeus on Jun 10, 2015, 10:40 AMDamn.

You are free to participate but would be unfair to the other scripters ;D I tried that spoiler tag a while a go and didn't work. Perhaps it was added in later updates.
Title: Re: Scripting challenges!
Post by: EK.IceFlake on Jun 10, 2015, 11:15 AM
This is a pretty horrible way but
[spoiler]local array = ["This", "And", "That", "Why", "Not"];
if (array.len() <= 1) print(array[0]);
if (array.len() <= 2) print(array[1]);
if (array.len() <= 3) print(array[2]);
if (array.len() <= 4) print(array[3]);
if (array.len() <= 5) print(array[4]);
//And so on...
[/spoiler]
Title: Re: Scripting challenges!
Post by: . on Jun 10, 2015, 11:16 AM
Quote from: NE.CrystalBlue on Jun 10, 2015, 11:15 AMThis is a pretty horrible way but
...

Use spoiler tags.
Title: Re: Scripting challenges!
Post by: EK.IceFlake on Jun 10, 2015, 11:20 AM
Quote from: S.L.C on Jun 10, 2015, 11:16 AM
Quote from: NE.CrystalBlue on Jun 10, 2015, 11:15 AMThis is a pretty horrible way but
...

Use spoiler tags.
Ok added
Title: Re: Scripting challenges!
Post by: DizzasTeR on Jun 10, 2015, 11:34 AM
[spoiler]
// Print all the values of an array without using any loop

local array = [];

local _index1 = array.push( "a" );
local _index2 = array.push( "b" );
local _index3 = array.push( "c" );

print( "Array contains index " + _index1 );
print( "Array contains index " + _index2 );
print( "Array contains index " + _index3 );
print( "Lets hope SLC doesn't disagree with this" );
[-/code]
[-/spoiler]
Title: Re: Scripting challenges!
Post by: . on Jun 10, 2015, 11:38 AM
Come on people. Is this the best you ca do. I already got two approaches while I was eating ;D

Hints (don't read!)
[spoiler]Hint about the first approach: Recursive...
Hint about the second approach: Delegates...[/spoiler]
Title: Re: Scripting challenges!
Post by: Kratos_ on Jun 10, 2015, 11:58 AM

** Kratos_ was returning to home . ( Just a 5 min drive to home )
** Kratos_ checked mobile . ( Thinks, hmm ok. Something to post )
** Kratos_ reached home & opened lappy . Writes some bunches of code .
** Kratos_ opened forum & boom all fun destroyed . ( S.L.C disclosed )

Btw here it is ,

[spoiler]function onScriptLoad()
{
_test_();
}

// function for defining & printing array entities
function _test_(ctr=0)
{
// sample array holding the entities
local array = [ "mercury", "venus", "earth", "mars", "jupiter", "saturn", "uranus", "neptune" ];
// printing the array slot indexed at 'ctr'
print(array[ctr]);
// updating the counter by 1
++ctr;
// checking if the updated counter goes beyond the range of array slots ( 0 - n-1 )
if( ctr >= array.len() ) return 0;
// calling the function with updated counter [ Tail Recursion ]
_test_(ctr);

}
[/spoiler]
Title: Re: Scripting challenges!
Post by: . on Jun 10, 2015, 12:01 PM
Quote from: Kratos_ on Jun 10, 2015, 11:58 AM** Kratos_ opened forum & boom all fun destroyed . ( S.L.C disclosed )

I haven't fully disclosed :D Was just a single word hint. And besides, you did the code before you saw the hint :P Waiting for more approaches. I'll do a review tonight when the first challenge ends. So far you have the approach that works. The only thing that's bugging me the fact that you declare that array on each recursion.

If you want to have fun keep looking for the other approaches ;D
Title: Re: Scripting challenges!
Post by: vcmptr on Jun 10, 2015, 01:08 PM
[spoiler]function PrintArray(array, num=0)
{
print(array[num]);
num+=1;
if(array.len() != num) PrintArray(array, num);
}[/spoiler]
Title: Re: Scripting challenges!
Post by: . on Jun 10, 2015, 01:25 PM
Kudos to @vcmptr for having a clean approach. Here's another stupid way to get it all in one string with the format function. This isn't recommended and there's better ways :D

[spoiler]
local arr = [2, 354, "foo", 43, 5.234, 675, "bar", true, {a = 23, b = 34.546}];

// Nethod 3 --------------------------------------------------------

function VarargsApproach(arr)
{
    // Insert the format string in the argument pack
    arr.insert(0, "");

    // Generate the format string
    local fmt = function(arr, idx = 0)
    {
        if (idx < arr.len())
        {
            switch (typeof arr[idx])
            {
                case "integer": arr[0] += "%d\n"; break;
                case "float": arr[0] += "%f\n"; break;
                case "string": arr[0] += "%s\n"; break;
                default:
                    arr[0] += "%s\n";
                    try {
                        arr[idx] = arr[idx].tostring();
                    } catch (e) {
                        arr[idx] = "(null : 0x00000000)";
                    }
                break;
            }
            // Go down the rabbit hole
            callee().call(this, arr, ++idx);
        }
    }

    // Skip the format string
    fmt(arr, 1);

    // Insert the 'this' environment
    arr.insert(0, this);

    // Print the f*er
    ::print(::format.acall(arr));
}

// We make a shallow copy of the array
//  Otherwise we edit the original
VarargsApproach(clone arr);
[/spoiler]

I'm just curious to see what other methods I can get.
Title: Re: Scripting challenges!
Post by: EK.IceFlake on Jun 10, 2015, 03:33 PM
Well you said that we cannot use loops but said absolutely nothing about using timers, so here it is!
[spoiler]function onScriptLoad()
{
local array = ["once", "upon", "a", "time", "Cinderella", "was", "going", "somewhere"];
loopn <- 0;
NewTimer("PrintAllOfThese", 1, array.len(), array);
}
function PrintAllOfThese(array)
{
print(array[loopn]);
loopn++;
}
[/spoiler]
Title: Re: Scripting challenges!
Post by: . on Jun 10, 2015, 03:41 PM
Quote from: NE.CrystalBlue on Jun 10, 2015, 03:33 PMWell you said that we cannot use loops but said absolutely nothing about using timers, so here it is!

I only said loops are forbidden. Any other trick is yours to use :D BTW, I think your code needs the new timers to work. Which are not yet compiled.

We have recursive, we have timers, we have format. I'm still waiting for someone to find the last approach :D

The first challenge ends in about 2 hours. Impress me :P
Title: Re: Scripting challenges!
Post by: EK.IceFlake on Jun 10, 2015, 04:00 PM
Got a newer one it's much more efficient (hint it uses the function arraytostring anti-hint I made that function myself)
[spoiler]
local ra = ["Cinderella", "ate", "nuttella", "then", "blah"];
print(arraytostring(ra, ", "));
And that function
function arraytostring(xarray, xsplitter, xstarting=0, xcurrent="")
{
if (xstarting >= xarray.len()) return xcurrent;
else return (arraytostring(xarray, xsplitter, xstarting+1, xcurrent + ((xstarting == 0) ? "" : xsplitter) + xarray[xstarting]));
}
[/spoiler]
Title: Re: Scripting challenges!
Post by: Stormeus on Jun 10, 2015, 05:16 PM
One-line delegate abuse (two lines if counting the array).
[spoiler]
local arrayTest = ["test1","test2","test3","test4"];

// .apply replaces each value in an array with the returned value.
//
// This is a cheaty way of printing stuff without loops and we need to
// return the original value to avoid filling the array with nulls.
arrayTest.apply(function(v) { print(v); return v; });
[/spoiler]

One-line delegate abuse featuring lambdas:
[spoiler]
// Squirrel internally clones the array and uses the return value from map to
// fill the cloned array.
//
// If you were to look at the returned array from .map, you'd see a bunch
// of nulls, as we never return anything.
arrayTest.map(@(v) print(v));
[/spoiler]
Title: Re: Scripting challenges!
Post by: . on Jun 10, 2015, 05:20 PM
Quote from: stormeus on Jun 10, 2015, 05:16 PMOne-line delegate abuse (two lines if counting the array).

Finally someone found the last approach. See people! That's what happens when you RTFM. I thought I was going to close this without anyone comming with the proper solution ;D

Either way. Here's all of them:
[spoiler]
local arr = [2, 354, "foo", 43, 5.234, 675, "bar", true, {a = 23, b = 34.546}];

// Nethod 1 --------------------------------------------------------

// Recursive functions
function RecursiveApproach(arr, idx = 0)
{
    if (idx < arr.len())
    {
        ::print(arr[idx]);
        // Go down the rabbit hole
        RecursiveApproach(arr, ++idx);
    }
}

// Initial call
RecursiveApproach(arr, 0);

print("---- ---- ---- ---- ---- ----");

// Nethod 2 --------------------------------------------------------

// Default delegates + lambda
function DelegatesApproach1(arr)
{
    // NOTE: arr becomes filled with nulls now
    arr.apply(@(v) ::print(v));
}

// We make a shallow copy of the array
//  Otherwise we fill the original with nulls
DelegatesApproach1(clone arr);

print("---- ---- ---- ---- ---- ----");

// Default dlegates + function
function DelegatesApproach2(arr)
{
    // NOTE: arr doesn't become filled with nulls now
    arr.apply(function(v) { ::print(v); return v; });
}

DelegatesApproach2(arr);

print("---- ---- ---- ---- ---- ----");

// Nethod 3 --------------------------------------------------------

function VarargsApproach(arr)
{
    // Insert the format string in the argument pack
    arr.insert(0, "");

    // Generate the format string
    local fmt = function(arr, idx = 0)
    {
        if (idx < arr.len())
        {
            switch (typeof arr[idx])
            {
                case "integer": arr[0] += "%d\n"; break;
                case "float": arr[0] += "%f\n"; break;
                case "string": arr[0] += "%s\n"; break;
                default:
                    arr[0] += "%s\n";
                    try {
                        arr[idx] = arr[idx].tostring();
                    } catch (e) {
                        arr[idx] = "(null : 0x00000000)";
                    }
                break;
            }
            // Go down the rabbit hole
            callee().call(this, arr, ++idx);
        }
    }

    // Skip the format string
    fmt(arr, 1);

    // Insert the 'this' environment
    arr.insert(0, this);

    // Print the f*er
    ::print(::format.acall(arr));
}

// We make a shallow copy of the array
//  Otherwise we edit the original
VarargsApproach(clone arr);
[/spoiler]

I will do a review of each after I finish my movie :D
Title: Re: Scripting challenges!
Post by: . on Jun 10, 2015, 07:47 PM
Ok, review time :D



The first one comes from @NE.CrystalBlue and I must say it's very disappointing. Not only that you do a sh!t load of if statements but you also have to add more code every time the array gets bigger. Not a viable solution.



Second one comes from @Doom_Killer.



Third one comes from @Kratos_ . And shows the use of recursive functions. One more thing I need to suggest to almost everyone is to stop using stuff on onScriptLoad() event because Squirrel is executed the same way PHP is. Top down. Like the following example:
function say(a)
{
    print(a);
}

say("Wazzaaaa!");

As soon as the compiler reaches the 'say("Wazzaaaa!");' line that function will get called. I'm just saying this because many scripters think Squirrel works the same way as C/C++. NO! Code is executed from top to bottom. No need to use events.

Another disappointment was the fact that the array is declared inside the recurred function which adds more load and also that 'if' condition could be combined with the line bellow it to get rid of the return.

Anyway, this was the only functional approach up until this point.



Fourth one comes from @vcmptr and improves upon the previous one. Although I would also like to suggest using pre-increment operators instead of assignment operators. Either way, good approach.



Again, the fifth one comes from @NE.CrystalBlue this time trying to fix his mistake in the first one. The approach works and even though it's not the best, it's unique and does what was required. I was curious to see if anyone would use timers ;D



And yet again, @NE.CrystalBlue tries to improves his approach. The nice thing is that you can have custom separators. Even though the implementation could be improved, I give it points for the custom delimiter feature.



Finally we reach the seventh approach and the one I was expecting. The one from @stormeus that uses the built in default delegates of the array type. That's what happens when you read the manual people. You learn what optios you have. By far the most elegant approach. A single line to do what you need.



I will now order your approaches based on how good it was.




I will be posting the next challenge soon. Probably it won't be printing tables without loops because that's going to ask for some really awkward approaches ;D Thanks to all who participated.
Title: Re: Scripting challenges!
Post by: Stormeus on Jun 11, 2015, 12:21 PM
Posts nuked from orbit. Any vitriolic responses have been thoroughly cleansed.
Title: Re: Scripting challenges!
Post by: EK.IceFlake on Jun 13, 2015, 03:53 AM
When will be the next challenge I wonder...
Title: Re: Scripting challenges!
Post by: . on Jun 13, 2015, 08:34 AM
Quote from: NE.CrystalBlue on Jun 13, 2015, 03:53 AMWhen will be the next challenge I wonder...

Here's a special challenge just for you: Be patient.
Title: Re: Scripting challenges!
Post by: Thijn on Jun 13, 2015, 09:10 AM
Quote from: S.L.C on Jun 13, 2015, 08:34 AM
Quote from: NE.CrystalBlue on Jun 13, 2015, 03:53 AMWhen will be the next challenge I wonder...

Here's a special challenge just for you: Be patient.
Title: Re: Scripting challenges!
Post by: . on Jun 14, 2015, 07:04 AM
New challenge for any scripter that wants to be challenged. (check the first post) Also read the new rules and updates.
Title: Re: Scripting challenges!
Post by: EK.IceFlake on Jun 14, 2015, 12:31 PM
This requires CreateSprite which is not yet compiled...
Title: Re: Scripting challenges!
Post by: . on Jun 14, 2015, 02:48 PM
Quote from: NE.CrystalBlue on Jun 14, 2015, 12:31 PMThis requires CreateSprite which is not yet compiled...

What do you mean it's not yet compiled? Have you created a sprite before?

.Func(_SC("CreateSprite"), CreateSprite, 8, _SC("tsiiiini"))
Title: Re: Scripting challenges!
Post by: EK.IceFlake on Jun 14, 2015, 02:58 PM
Quote from: S.L.C on Jun 14, 2015, 02:48 PM
Quote from: NE.CrystalBlue on Jun 14, 2015, 12:31 PMThis requires CreateSprite which is not yet compiled...

What do you mean it's not yet compiled? Have you created a sprite before?

.Func(_SC("CreateSprite"), CreateSprite, 8, _SC("tsiiiini"))
Who said we load the whole module? We just load squirrel... Pure and native support only
Title: Re: Scripting challenges!
Post by: . on Jun 14, 2015, 03:17 PM
Quote from: NE.CrystalBlue on Jun 14, 2015, 02:58 PMWho said we load the whole module? We just load squirrel... Pure and native support only

Are you trolling me?
Title: Re: Scripting challenges!
Post by: EK.IceFlake on Jun 14, 2015, 03:58 PM
Quote from: S.L.C on Jun 14, 2015, 03:17 PM
Quote from: NE.CrystalBlue on Jun 14, 2015, 02:58 PMWho said we load the whole module? We just load squirrel... Pure and native support only

Are you trolling me?
You're excellently smart (take their first letters)
Title: Re: Scripting challenges!
Post by: Sebastian on Jun 14, 2015, 04:22 PM
Damn, this challenge is so... for me.
I hope I will find some free-time today to make it happen, because I already have some ideas. :)

EDIT: Unfortunately, I won't do that... Don't have the needed free-time. In a couple of weeks, the big exams starts, and I really need to study since them are influencing my future a lot. Good luck guys !
Title: Re: Scripting challenges!
Post by: Stormeus on Jun 14, 2015, 04:45 PM
Quote from: NE.CrystalBlue on Jun 14, 2015, 02:58 PM
Quote from: S.L.C on Jun 14, 2015, 02:48 PM
Quote from: NE.CrystalBlue on Jun 14, 2015, 12:31 PMThis requires CreateSprite which is not yet compiled...

What do you mean it's not yet compiled? Have you created a sprite before?

.Func(_SC("CreateSprite"), CreateSprite, 8, _SC("tsiiiini"))
Who said we load the whole module? We just load squirrel... Pure and native support only

... sprites are pure and native to Squirrel. End of discussion.
Title: Re: Scripting challenges!
Post by: maxorator on Jun 14, 2015, 06:43 PM
Here we go...
[spoiler]Code:
http://pastebin.com/tum2Xgj4
Sprites:
http://imgur.com/a/tcdaz
Filenames for them should be board.png, cellx.png and cello.png.[/spoiler]

This is actually my first script in Squirrel which is not just a few lines of code to test some feature.

Oh, forgot to mention. I was too lazy to mess with relative positioning so it just places them so it looks good on 1920x1080 resolution. Anything too much smaller and the board will probably be somewhere off-screen.

Server currently running this script is at: maxorator.empiro.co.uk:8192
Title: Re: Scripting challenges!
Post by: Sebastian on Jun 15, 2015, 01:28 PM
@maxorator
I have tested your Tic-Tac-Toe with @Skirmant, and I enjoyed it alot ! 8)
I like that you don't freeze the player, in this way the TTT being a cool bonus to the normal gameplay.

Unfortunately, after the first game, it started to be buggy...
After I started the second/third game, and played a while, I got an unexpected message: game ended and a player was selected to be the winner.

Also, I have a little suggestion: set the first one who plays to be random.
Was kinda annoying when I was challenging Skirmant and he was always the first one. :D
Title: Re: Scripting challenges!
Post by: EK.IceFlake on Jun 15, 2015, 02:57 PM
Quote from: Stormeus on Jun 14, 2015, 04:45 PM
Quote from: NE.CrystalBlue on Jun 14, 2015, 02:58 PM
Quote from: S.L.C on Jun 14, 2015, 02:48 PM
Quote from: NE.CrystalBlue on Jun 14, 2015, 12:31 PMThis requires CreateSprite which is not yet compiled...

What do you mean it's not yet compiled? Have you created a sprite before?

.Func(_SC("CreateSprite"), CreateSprite, 8, _SC("tsiiiini"))
Who said we load the whole module? We just load squirrel... Pure and native support only

... sprites are pure and native to Squirrel. End of discussion.
They are pure and native to VCMP. End of discussion.
Title: Re: Scripting challenges!
Post by: Honey on Jun 15, 2015, 03:18 PM
You're damned. End Of discussion.
Title: Re: Scripting challenges!
Post by: . on Jun 15, 2015, 04:13 PM
Quote from: NE.CrystalBlue on Jun 15, 2015, 02:57 PMThey are pure and native to VCMP. End of discussion.

Do you even have any idea what native means in this context?
Title: Re: Scripting challenges!
Post by: Stormeus on Jun 15, 2015, 04:28 PM
Quote from: NE.CrystalBlue on Jun 15, 2015, 02:57 PM
Quote from: Stormeus on Jun 14, 2015, 04:45 PM
Quote from: NE.CrystalBlue on Jun 14, 2015, 02:58 PMWho said we load the whole module? We just load squirrel... Pure and native support only

... sprites are pure and native to Squirrel. End of discussion.
They are pure and native to VCMP. End of discussion.

The purpose of this thread is diverse. It doesn't just entail completing a task using the default Squirrel natives. What SLC has provided is a real-world example of a script that people could adopt in the future, and is challenging scripters to try to construct it, which, IMO, is far more interesting than the abstract challenges that are less relevant to this community (but still do a good job enforcing syntax, which some people still fail to do).

If you have an issue with this thread not being limited to the Squirrel core libraries, you're welcome to leave. You can send any further criticism to my or SLC's PM inbox, but I don't want to hear another word of it in this thread, because we're already venturing off topic.
Title: Re: Scripting challenges!
Post by: dEaN on Jun 22, 2015, 02:24 PM
ah! :/
Title: Re: Scripting challenges!
Post by: EK.IceFlake on Dec 19, 2016, 11:43 AM
I know this is an 18-month bump, but these were quite nice. Do you have any plans on continuing them?
Title: Re: Scripting challenges!
Post by: . on Dec 19, 2016, 04:32 PM
Quote from: EK.CrystalBlue on Dec 19, 2016, 11:43 AMI know this is an 18-month bump, but these were quite nice. Do you have any plans on continuing them?

If you find one at a level close to the average vcmp scripter and at the same time to actually be challenging. Then feel free to post it here and I'll put it into the first post.

All I've got so far is "print("hello world!");" :P

Joking aside, I know these were fun, but it's hard to also keep it challenging and simple enough for others to follow. That being said, anyone is free to come up with ideas.

The only rule is that they must not require a lot of coding. The real challenge usually must be to keep the code to a minimum.

Also, I'll have to start individual topics because having one huge topic might get a little messy.
Title: Re: Scripting challenges!
Post by: DizzasTeR on Dec 21, 2016, 11:39 AM
Okay here is a little challenge if you would like to take.

Challenge: Create a simple table which does not throw an index does not exist error if you try to add any value in an undefined index.

Probably too simple for someone or too hard for someone else but meh keeping it short and less stressful as SLC said above :D
Title: Re: Scripting challenges!
Post by: jWeb on Dec 21, 2016, 11:56 AM
[spoiler]
local mm = {
    _get = function(k) { return null; }
    _set = function(k, v) { this.rawset(k, v); }
};

local person = { name = "Bawss" }.setdelegate(mm);

print(person.name);
// Do not exist (yet)
print(person.age);
print(person.city);

// Note the '=' and not '<-'
person.age = 37;
person.city = "Candyland";

print(person.name);
// Now they exist
print(person.age);
print(person.city);
[/spoiler]
Title: Re: Scripting challenges!
Post by: EK.IceFlake on Dec 21, 2016, 03:27 PM
[spoiler]t1 <- {a=1, b=2};[/spoiler]
Usage:
[spoiler]try
{
    t1["d"] = t1["c"];
}
catch (e) {}[/spoiler]

Serious usage:
[spoiler]
t1["d"] <- 3;
[/spoiler]
Title: Re: Scripting challenges!
Post by: KAKAN on Dec 21, 2016, 04:06 PM
Quote from: EK.CrystalBlue on Dec 21, 2016, 03:27 PM...
There's a difference between your code and doom's challenge. Anyone can insert a new slot( using the '<-' sign ). The question was completely different. Try to understand the question again.
Title: Re: Scripting challenges!
Post by: EK.IceFlake on Dec 22, 2016, 05:58 AM
Quote from: KAKAN on Dec 21, 2016, 04:06 PM
Quote from: EK.CrystalBlue on Dec 21, 2016, 03:27 PM...
There's a difference between your code and doom's challenge. Anyone can insert a new slot( using the '<-' sign ). The question was completely different. Try to understand the question again.
Well... I can't now, since after posting my reply, I read jWebs answer.
Title: Re: Scripting challenges!
Post by: Anik on Apr 12, 2017, 07:21 AM
Here's a little challenge from me.

Challenge : Write a program that uses a numeric variable and displays that number of rows of *, with one * in the first row, two in the second row, and so on. For each row, the asterisks are preceded by the number of '.' needed to make all the rows display a total number of characters equal to the number of rows.

A sample run would look like this:
Number of rows :  5
....*
...**
..***
.****
*****
Number of rows :  7
......*
.....**
....***
...****
..*****
.******
*******
Title: Re: Scripting challenges!
Post by: DizzasTeR on Apr 12, 2017, 10:43 AM
Not the best way but okay.
[Spoiler=Code]function onPlayerCommand( player, cmd, text ) {
if( cmd == "g" ) {
local maxStars = text.tointeger();
if( maxStars ) {
for( local mainRun = 0; mainRun <= maxStars-1; mainRun++ ) {
local string = "";
for( local j = 1; j <= maxStars; j++ ) {
if( maxStars - j > mainRun ) {
string += ".";
}
else {
string += "*";
}
}
print( string );
}
}
}
}
[/Spoiler]
Title: Re: Scripting challenges!
Post by: EK.IceFlake on Apr 12, 2017, 11:30 AM
[spoiler]
function PrintRowz(num)
{
    print("Number of rows: " + num);
    if (typeof(num) != "integer" || num < 1) return print("Rejected");
    local Repeat = function (str, num)
    {
        local ret = "";
        for (local i = 0; i < num; ++i) ret += str;
        return ret;
    }
    for (local i = 0; i < num; ++i)
    {
         print(Repeat(".", num - i) + Repeat("*", i));
    }
}
[/spoiler]
Untested.
Title: Re: Scripting challenges!
Post by: . on Apr 12, 2017, 01:41 PM
[spoiler]
function Generate(l) for (local f = function(p, l, x = 0, b = "") { while (++x <= l) b += x < (l-p) ? "." : "*"; return b; }, p = 0; p < l; ++p) print(f(p, l));[/spoiler]

Ex:
Generate(32);
Out:
...............................*
..............................**
.............................***
............................****
...........................*****
..........................******
.........................*******
........................********
.......................*********
......................**********
.....................***********
....................************
...................*************
..................**************
.................***************
................****************
...............*****************
..............******************
.............*******************
............********************
...........*********************
..........**********************
.........***********************
........************************
.......*************************
......**************************
.....***************************
....****************************
...*****************************
..******************************
.*******************************
********************************

I think I should be banned from these ;D
Title: Re: Scripting challenges!
Post by: EK.IceFlake on Apr 12, 2017, 01:53 PM
Quote from: happymint on Apr 12, 2017, 01:41 PM[spoiler]
function Generate(l) for (local f = function(p, l, x = 0, b = "") { while (++x <= l) b += x < (l-p) ? "." : "*"; return b; }, p = 0; p < l; ++p) print(f(p, l));[/spoiler]

Ex:
Generate(32);
Out:
...............................*
..............................**
.............................***
............................****
...........................*****
..........................******
.........................*******
........................********
.......................*********
......................**********
.....................***********
....................************
...................*************
..................**************
.................***************
................****************
...............*****************
..............******************
.............*******************
............********************
...........*********************
..........**********************
.........***********************
........************************
.......*************************
......**************************
.....***************************
....****************************
...*****************************
..******************************
.*******************************
********************************

I think I should be banned from these ;D
Looks almost identical to mine but a bit more inefficient (you declare the function for every iteration rather than once outside the loop).
Title: Re: Scripting challenges!
Post by: . on Apr 12, 2017, 02:23 PM
Quote from: EK.IceFlake on Apr 12, 2017, 01:53 PMLooks almost identical to mine...

Not quite.

Quote from: EK.IceFlake on Apr 12, 2017, 01:53 PM...but a bit more inefficient...

Again, not quite accurate. You generate two strings I only generate one. Run a benchmark though. I'm pretty sure you'll fall for the newbie trap when you do. And you'll get some misleading results.

Quote from: EK.IceFlake on Apr 12, 2017, 01:53 PM...(you declare the function for every iteration rather than once outside the loop).

Please look at how for loops work before making that statement.
Title: Re: Scripting challenges!
Post by: DizzasTeR on Apr 12, 2017, 02:53 PM
I did the benchmarks, and I didn't expect to see this.

[SCRIPT]  Starting Benchmark for doom's method:
[SCRIPT]  ....*
[SCRIPT]  ...**
[SCRIPT]  ..***
[SCRIPT]  .****
[SCRIPT]  *****
[SCRIPT]  Benchmark ended: 0.003
[SCRIPT]  -
[SCRIPT]  Starting Benchmark for iceflake's method:
[SCRIPT]  Number of rows: 5
[SCRIPT]  .....
[SCRIPT]  ....*
[SCRIPT]  ...**
[SCRIPT]  ..***
[SCRIPT]  .****
[SCRIPT]  Benchmark ended: 0.004
[SCRIPT]  -
[SCRIPT]  Starting Benchmark for slc's method:
[SCRIPT]  ....*
[SCRIPT]  ...**
[SCRIPT]  ..***
[SCRIPT]  .****
[SCRIPT]  *****
[SCRIPT]  Benchmark ended: 0.007
[SCRIPT]  -
Title: Re: Scripting challenges!
Post by: Shadow on Apr 12, 2017, 03:55 PM
Quote from: Doom_Kill3R on Apr 12, 2017, 02:53 PMI did the benchmarks, and I didn't expect to see this.

[SCRIPT]  Starting Benchmark for doom's method:
[SCRIPT]  ....*
[SCRIPT]  ...**
[SCRIPT]  ..***
[SCRIPT]  .****
[SCRIPT]  *****
[SCRIPT]  Benchmark ended: 0.003
[SCRIPT]  -
[SCRIPT]  Starting Benchmark for iceflake's method:
[SCRIPT]  Number of rows: 5
[SCRIPT]  .....
[SCRIPT]  ....*
[SCRIPT]  ...**
[SCRIPT]  ..***
[SCRIPT]  .****
[SCRIPT]  Benchmark ended: 0.004
[SCRIPT]  -
[SCRIPT]  Starting Benchmark for slc's method:
[SCRIPT]  ....*
[SCRIPT]  ...**
[SCRIPT]  ..***
[SCRIPT]  .****
[SCRIPT]  *****
[SCRIPT]  Benchmark ended: 0.007
[SCRIPT]  -

You don't just benchmark one call. You make a big number of calls (like 1000000) then divide the execution time to this number of calls to get an accurate result (which is called an average weight).
Title: Re: Scripting challenges!
Post by: DizzasTeR on Apr 12, 2017, 04:07 PM
Quote from: Shadow on Apr 12, 2017, 03:55 PM
Quote from: Doom_Kill3R on Apr 12, 2017, 02:53 PMI did the benchmarks, and I didn't expect to see this.

[SCRIPT]  Starting Benchmark for doom's method:
[SCRIPT]  ....*
[SCRIPT]  ...**
[SCRIPT]  ..***
[SCRIPT]  .****
[SCRIPT]  *****
[SCRIPT]  Benchmark ended: 0.003
[SCRIPT]  -
[SCRIPT]  Starting Benchmark for iceflake's method:
[SCRIPT]  Number of rows: 5
[SCRIPT]  .....
[SCRIPT]  ....*
[SCRIPT]  ...**
[SCRIPT]  ..***
[SCRIPT]  .****
[SCRIPT]  Benchmark ended: 0.004
[SCRIPT]  -
[SCRIPT]  Starting Benchmark for slc's method:
[SCRIPT]  ....*
[SCRIPT]  ...**
[SCRIPT]  ..***
[SCRIPT]  .****
[SCRIPT]  *****
[SCRIPT]  Benchmark ended: 0.007
[SCRIPT]  -

You don't just benchmark one call. You make a big number of calls (like 1000000) then divide the execution time to this number of calls to get an accurate result (which is called an average weight).

Ah yes sorry about that I didn't take an average one :-[
Title: Re: Scripting challenges!
Post by: EK.IceFlake on Apr 12, 2017, 04:30 PM
Quote from: Doom_Kill3R on Apr 12, 2017, 02:53 PMI did the benchmarks, and I didn't expect to see this.

[SCRIPT]  Starting Benchmark for doom's method:
[SCRIPT]  ....*
[SCRIPT]  ...**
[SCRIPT]  ..***
[SCRIPT]  .****
[SCRIPT]  *****
[SCRIPT]  Benchmark ended: 0.003
[SCRIPT]  -
[SCRIPT]  Starting Benchmark for iceflake's method:
[SCRIPT]  Number of rows: 5
[SCRIPT]  .....
[SCRIPT]  ....*
[SCRIPT]  ...**
[SCRIPT]  ..***
[SCRIPT]  .****
[SCRIPT]  Benchmark ended: 0.004
[SCRIPT]  -
[SCRIPT]  Starting Benchmark for slc's method:
[SCRIPT]  ....*
[SCRIPT]  ...**
[SCRIPT]  ..***
[SCRIPT]  .****
[SCRIPT]  *****
[SCRIPT]  Benchmark ended: 0.007
[SCRIPT]  -
Okay, so apparently, my method is offset by 1.
That's why you test your snippets, kids!
Title: Re: Scripting challenges!
Post by: vito on Apr 12, 2017, 04:39 PM
Quote from: happymint on Apr 12, 2017, 01:41 PMfunction Generate(l) for (local f = function(p, l, x = 0, b = "") { while (++x <= l) b += x < (l-p) ? "." : "*"; return b; }, p = 0; p < l; ++p) print(f(p, l));
Quote from: happymint on Jul 04, 2016, 07:19 PMChrist, what a horrible coding style you have. Why do you have to make everything in one line when it looks so ugly.
Title: Re: Scripting challenges!
Post by: EK.IceFlake on Apr 12, 2017, 04:53 PM
After removing type checking and the "[SCRIPT]  Number of rows: 5" print (because others didn't do it - it's supposed to be a fair test after all), here's what I got:
[USR] Total iterations: 200
[USR] Average for Flake: 21111 us
[USR] Average for Doom: 21637 us
[USR] Average for SLC: 21889 us

I've noticed that the slowest part of this is print, and am quite sure that if we do this with variables instead, we'll reduce the total time by a factor of 10 or something.
200 iterations took about 20 seconds on my PC.

After replacing all print calls with an NOP instead, here is what I got (I used 500 iterations this time because it as a whole is much faster and this time the results aren't as reliable individually as they were before):
[USR] Total iterations: 500
[USR] Average for Flake: 307 us
[USR] Average for Doom: 308 us
[USR] Average for SLC: 326 us

Haven't quite replaced print with variables - rather, with a NOP, but it's still a reduction of not by a factor of 10 like I was expecting but a factor of almost 100.

[spoiler=The script I used for taking the benchmark]function kprint(val)
{

}

function PrintRowz(num)
{
    //kprint("Number of rows: " + num);
    //if (typeof(num) != "integer" || num < 1) return kprint("Rejected");
    local Repeat = function (str, num)
    {
        local ret = "";
        for (local i = 0; i < num; ++i) ret += str;
        return ret;
    }
    for (local i = 0; i < num; ++i)
    {
         kprint(Repeat(".", num - i) + Repeat("*", i));
    }
}

function Generate(l) for (local f = function(p, l, x = 0, b = "") { while (++x <= l) b += x < (l-p) ? "." : "*"; return b; }, p = 0; p < l; ++p) kprint(f(p, l));

function dum( maxStars ) {
 if( maxStars ) {
 for( local mainRun = 0; mainRun <= maxStars-1; mainRun++ ) {
 local string = "";
 for( local j = 1; j <= maxStars; j++ ) {
 if( maxStars - j > mainRun ) {
 string += ".";
 }
 else {
 string += "*";
 }
 }
 kprint( string );
 }
 }
}

local totalflake = 0;
local totaldoom = 0;
local totalslc = 0;

local iterations = 500;

for (local i = 1; i <= iterations; ++i)
{
    local t, to;
    print("Iteration " + i);
    print("---");
    print("Flake's method: ");
    t = SqTimer();
    PrintRowz(12);
    to = t.Elapsed.Microseconds.tointeger();
    print("Took " + to + " us");
    totalflake += to;
    print("Total counter for Flake: " + totalflake);
    print("");
    print("Doom's method: ");
    t = SqTimer();
    dum(12);
    to = t.Elapsed.Microseconds.tointeger();
    print("Took " + to + " us");
    totaldoom += to;
    print("Total counter for Doom: " + totaldoom);
    print("");
    print("SLC's method: ");
    t = SqTimer();
    Generate(12);
    to = t.Elapsed.Microseconds.tointeger();
    print("Took " + to + " us");
    totalslc += to;
    print("Total counter for SLC: " + totalslc);
    print("");
    print("---");
    print("Iteration complete");
    print("");
}

print("Total iterations: " + iterations);

print("Average for Flake: " + totalflake / iterations + " us");
print("Average for Doom: " + totaldoom / iterations + " us");
print("Average for SLC: " + totalslc / iterations + " us");
[/spoiler]
Title: Re: Scripting challenges!
Post by: . on Apr 12, 2017, 04:54 PM
Quote from: happymint on Apr 12, 2017, 02:23 PM... I'm pretty sure you'll fall for the newbie trap when you do. And you'll get some misleading results.

But did you disable the console output? Because that takes more time than the code itself. That's the newbie mistake #1 when doing benchmarks of code that outputs something.

There's one bottleneck in my example which I didn't even bother about. And that's the extra branching here "b += x < (l-p) ? "." : "*"". My challenge was not speed. But rather if I can keep it all in one statement. Trust me. If I wanted speed, you would've seen speed.
Title: Re: Scripting challenges!
Post by: . on Apr 12, 2017, 05:06 PM
You want speed? Here you go: https://pastebin.com/xzVvz9rW (I had to move it to paste-bin because the forum script is too retarded and collapses series of dots down to 3)

Why don't you benchmark this and then let's talk again.
Title: Re: Scripting challenges!
Post by: EK.IceFlake on Apr 12, 2017, 05:12 PM
Quote from: happymint on Apr 12, 2017, 04:54 PMBut did you disable the console output? Because that takes more time than the code itself. That's the newbie mistake #1 when doing benchmarks of code that outputs something.
That's exactly what my prediction was.
However, instead of 'disabling' it, I replaced the print functions with a NOP.

Anyways, with your new method:
[USR] Total iterations: 500
[USR] Average for Flake: 124 us
[USR] Average for Doom: 186 us
[USR] Average for SLC: 90 us

Good job :D

:edit: Not too fast.
Your script depends on you adjusting for length.
In which case:
function PrintRowz(num)
{
    switch (num)
    {
        case 0: break;
        case 1: print("*"); break;
        case 2: print("*.\n**"); break;
        case 3: print("*..\n**.\n***"); break;
    }
}
And so on
Title: Re: Scripting challenges!
Post by: . on Apr 12, 2017, 05:25 PM
Also, your benchmark has to much noise in it. It doesn't show the maximum throughput because it contains noise from other implementations. By the time the CPU warms up with an implementation it has to throw it away for the next one. Here are some more accurate results:

function kprint(v) return; // > dev/null
//---------------------------------------------------------------------------------------------------------------------
// warm up to avoid CPU throttling.
for (local n = 0, x = 0; n < 10000000; ++n) x = abs(n - x) % 2 * 2 / 2;
print("warm up complete");
//---------------------------------------------------------------------------------------------------------------------
function PrintRowz(num)
{
    if (typeof(num) != "integer" || num < 1) return;
    local Repeat = function (str, num)
    {
        local ret = "";
        for (local i = 0; i < num; ++i) ret += str;
        return ret;
    }
    for (local i = 0; i < num; ++i)
    {
         kprint(Repeat(".", num - i) + Repeat("*", i));
    }
}

local tm = clock();

for (local n = 0; n < 10000; ++n) PrintRowz(32);

print("Flake: " + (clock() - tm));
//---------------------------------------------------------------------------------------------------------------------
function doom( maxStars ) {
    if( maxStars ) {
        for( local mainRun = 0; mainRun <= maxStars-1; mainRun++ ) {
            local string = "";
            for( local j = 1; j <= maxStars; j++ ) {
                if( maxStars - j > mainRun ) {
                    string += ".";
                } else {
                    string += "*";
                }
            }
            kprint( string );
        }
    }
}

local tm = clock();

for (local n = 0; n < 10000; ++n) doom(32);

print("Doom: " + (clock() - tm));
//---------------------------------------------------------------------------------------------------------------------
function Generate(l) for (local f = function(p, l, x = 0, b = "") { while (++x <= l) b += x < (l-p) ? "." : "*"; return b; }, p = 0; p < l; ++p) kprint(f(p, l));

local tm = clock();

for (local n = 0; n < 10000; ++n) Generate(32);

print("SLC1: " + (clock() - tm));
//---------------------------------------------------------------------------------------------------------------------
const G_PERIOD_CONST = "...";
const G_ASTERIX_CONST = "********************************************************************************************************************************";
function Generate2(l) for (local p = 1; p <= l; ++p) kprint(G_PERIOD_CONST.slice(0, l-p) + G_ASTERIX_CONST.slice(0, p));

local tm = clock();

for (local n = 0; n < 10000; ++n) Generate2(32);

print("SLC2: " + (clock() - tm));

These were the results on my plugin x32:
[USR] Flake: 2.75
[USR] Doom: 3.108
[USR] SLC1: 3.094
[USR] SLC2: 0.359

These were the results on my plugin x64:
[USR] Flake: 2.312
[USR] Doom: 2.798
[USR] SLC1: 2.707
[USR] SLC2: 0.297

These are the results on the official plugin x32:
[SCRIPT]  Flake: 3.043
[SCRIPT]  Doom: 3.573
[SCRIPT]  SLC1: 3.575
[SCRIPT]  SLC2: 0.392

These are the results on the official plugin x64:
[SCRIPT]  Flake: 2.441
[SCRIPT]  Doom: 2.915
[SCRIPT]  SLC1: 2.85
[SCRIPT]  SLC2: 0.297

Here you can see that x64 builds yield better results due to less register pressure since x64 can use more registers on the CPU. And you can also see that some results were misleading in previous tests because there was a lot of noise from the other implementations since there wasn't enough isolation.
Title: Re: Scripting challenges!
Post by: . on Apr 12, 2017, 05:32 PM
Quote from: EK.IceFlake on Apr 12, 2017, 05:12 PMNot too fast.
Your script depends on you adjusting for length.
In which case:
function PrintRowz(num)
{
    switch (num)
    {
        case 0: break;
        case 1: print("*"); break;
        case 2: print("*.\n**"); break;
        case 3: print("*..\n**.\n***"); break;
    }
}
And so on

Read my update: (I had to move it to paste-bin because the forum script is too retarded and collapses series of dots down to 3)
Title: Re: Scripting challenges!
Post by: . on Apr 12, 2017, 06:19 PM
I just realized that this challenge had no winning factors. No performance, statement count, line count etc. Basically as long as you did what was asked everyone is a winner. So how are we going to decide who won here? I'm curious.

And what's the next challenge? Because these are fun.
Title: Re: Scripting challenges!
Post by: vito on Apr 12, 2017, 06:43 PM
Quote from: happymint on Apr 12, 2017, 06:19 PMAnd what's the next challenge? Because these are fun.
fast json bridge server <-> client side, at least it will be useful
Title: Re: Scripting challenges!
Post by: . on Apr 12, 2017, 06:45 PM
Quote from: vito on Apr 12, 2017, 06:43 PM
Quote from: happymint on Apr 12, 2017, 06:19 PMAnd what's the next challenge? Because these are fun.
fast json bridge server <-> client side, at least it will be useful

Huh? Can you be more specific? And you must post one too. We're not here to do your work. What you're looking for is probably serialization.
Title: Re: Scripting challenges!
Post by: vito on Apr 12, 2017, 06:55 PM
serialization + splitting to packages its it above stream limit
Title: Re: Scripting challenges!
Post by: . on Apr 12, 2017, 07:03 PM
Quote from: vito on Apr 12, 2017, 06:43 PM... at least it will be useful

Also, that isn't the goal of the topic. But to be fun and probably learn some new/different techniques for doing something.
Title: Re: Scripting challenges!
Post by: DizzasTeR on Apr 12, 2017, 07:07 PM
@happymint, A small favor to test this one and the results
const STARTMASK = "****************************************************************";
const DOTMASK = "................................................................";

function dgen( num ) {
    local counter = num;
    do {
        local sz = DOTMASK.slice( 0, counter ) + STARTMASK.slice( 0, num - counter );
        kprint( sz );
        counter--;
    } while( counter > 0 )
}
Title: Re: Scripting challenges!
Post by: . on Apr 12, 2017, 07:20 PM
My plugin x32:
[USR] Flake: 2.77
[USR] Doom: 3.11
[USR] SLC1: 3.122
[USR] SLC2: 0.348
[USR] Doom2: 0.370

My plugin x64:
[USR] Flake: 2.287
[USR] Doom: 2.77
[USR] SLC1: 2.664
[USR] SLC2: 0.284
[USR] Doom2: 0.290


After you updated your code while I was doing my first test.

My plugin x32
[USR] Flake: 2.728
[USR] Doom: 3.083
[USR] SLC1: 3.127
[USR] SLC2: 0.333
[USR] Doom2: 0.342

My plugin x64:
[USR] Flake: 2.271
[USR] Doom: 2.759
[USR] SLC1: 2.651
[USR] SLC2: 0.282
[USR] Doom2: 0.292
Title: Re: Scripting challenges!
Post by: . on Apr 12, 2017, 07:40 PM
Here is my third version with pre-computed tables of strings to reduce the heap memory allocations: https://pastebin.com/sSZJMnG6

My plugin x32:
[USR] SLC3: 0.146
My plugin x64:
[USR] SLC3: 0.123
I'm trying something else now to see if I can take it even further. Seems this is as far as you can take it on the official plugin.
Title: Re: Scripting challenges!
Post by: DizzasTeR on Apr 13, 2017, 02:18 AM
I'm not surprised to be second now heh.
Title: Re: Scripting challenges!
Post by: Anik on Apr 13, 2017, 07:28 AM
@S.L.C can you test the benchmark of it.

[spoiler]
function anik( num )
{
local dotstr = "", starstr = "";
for( local i = 0; i < num; ++i ) dotstr += ".";
for( local i = 0; i <= num; ++i ) print( dotstr.slice( 0, num - i ) + ( starstr += "*" ) );
}
[/spoiler]
Title: Re: Scripting challenges!
Post by: Shadow on Apr 13, 2017, 10:53 AM


There's really no other way of getting a better time than using constant tables and loops as @S.L.C mentioned above. Recursion is not a solution either (even though it has logarithmic complexion, you still need other instructions to ensure the function return which might not be as easy to optimize as for-loops)
Title: Re: Scripting challenges!
Post by: EK.IceFlake on Apr 13, 2017, 12:58 PM
Quote from: Shadow on Apr 13, 2017, 10:53 AMThere's really no other way of getting a better time than using constant tables and loops as @S.L.C mentioned above.
Are you sure?
https://www.solidfiles.com/v/q6YqYPvxMWzxB
[USR] Total iterations: 1000
[USR] Average for Flake: 15 us
[USR] Average for Doom: 81 us
[USR] Average for SLC: 32 us
(where:
Flake's method is given a special download link as it is 342 MB
Doom's method is:
function dum( maxStars ) {
 if( maxStars ) {
 for( local mainRun = 0; mainRun <= maxStars-1; mainRun++ ) {
 local string = "";
 for( local j = 1; j <= maxStars; j++ ) {
 if( maxStars - j > mainRun ) {
 string += ".";
 }
 else {
 string += "*";
 }
 }
 kprint( string );
 }
 }
}
and SLC's method is:
const G_PERIOD_CONST = "...";
const G_ASTERIX_CONST = "********************************************************************************************************************************";
function Generate(l) for (local p = 1; p <= l; ++p) kprint(G_PERIOD_CONST.slice(0, l-p) + G_ASTERIX_CONST.slice(0, p));
)
Title: Re: Scripting challenges!
Post by: DizzasTeR on Apr 13, 2017, 01:09 PM
You used the old method of mine @EK.IceFlake but nevermind :D The main thing is that the task got accomplished though in more than expected ways haha, way to go.
Title: Re: Scripting challenges!
Post by: Shadow on Apr 13, 2017, 03:41 PM
Quote from: EK.IceFlake on Apr 13, 2017, 12:58 PM...

On the same note, I could also make a C++ plugin which would destroy squirrel at the execution time. The simple fact that your solution consists of 150 cases inside a switch renders it useless.
Title: Re: Scripting challenges!
Post by: EK.IceFlake on Apr 13, 2017, 03:52 PM
Quote from: Shadow on Apr 13, 2017, 03:41 PM
Quote from: EK.IceFlake on Apr 13, 2017, 12:58 PM...

On the same note, I could also make a C++ plugin which would destroy squirrel at the execution time. The simple fact that your solution consists of 150 cases inside a switch renders it useless.
1024, you mean?

Scripting challenges, not programming challenges.
Title: Re: Scripting challenges!
Post by: Shadow on Apr 13, 2017, 04:03 PM
As long as squirrel is an embedded language and you have access to every value from C++, I'd say it's as fair as your solution. Anyways, keeping it real with generalised solutions:



..which isn't too bad
Title: Re: Scripting challenges!
Post by: Anik on Apr 13, 2017, 04:10 PM
Here's another challenge. Just like the previous challenge make a pyramid of "*"

Sample Output:
         *
         * *
        * * *
       * * * *
      * * * * *
     * * * * * *
    * * * * * * *
   * * * * * * * *
  * * * * * * * * *
Title: Re: Scripting challenges!
Post by: Shadow on Apr 13, 2017, 04:40 PM
It's getting quite repetitive but

function kprint(v) return; // > dev/null
// warm up to avoid CPU throttling.
for (local n = 0, x = 0; n < 10000000; ++n) x = abs(n - x) % 2 * 2 / 2;

const G_SPACE_CONST = "                                                                                                                                ";
const G_ASTERIX_CONST = "********************************************************************************************************************************";

local G_SPACE_POOL = array(G_SPACE_CONST.len());
local G_ASTERIX_POOL = array(G_SPACE_CONST.len());
for (local i = 0, n = G_SPACE_CONST.len(); i < n; ++i) {
    G_SPACE_POOL[i] = G_SPACE_CONST.slice(0, i);
    G_ASTERIX_POOL[i] = G_ASTERIX_CONST.slice(0, i);
}

function Generate(l) for (local p = 0.5; p <= (l/2); ++p) kprint(G_SPACE_POOL [(l/2) - p] + G_ASTERIX_POOL[p*2] + G_SPACE_POOL [p + (l/2)]);

local tm = clock();

for(local n = 0; n < 10000; ++n) Generate(32);

print("SLC: " + (clock() - tm));

.. just a simple adaptation

Title: Re: Scripting challenges!
Post by: Anik on Apr 13, 2017, 04:46 PM
Quote from: Shadow on Apr 13, 2017, 04:40 PMIt's getting quite repetitive but

function kprint(v) return; // > dev/null
// warm up to avoid CPU throttling.
for (local n = 0, x = 0; n < 10000000; ++n) x = abs(n - x) % 2 * 2 / 2;

const G_SPACE_CONST = "                                                                                                                                ";
const G_ASTERIX_CONST = "********************************************************************************************************************************";

local G_SPACE_POOL = array(G_SPACE_CONST.len());
local G_ASTERIX_POOL = array(G_SPACE_CONST.len());
for (local i = 0, n = G_SPACE_CONST.len(); i < n; ++i) {
    G_SPACE_POOL[i] = G_SPACE_CONST.slice(0, i);
    G_ASTERIX_POOL[i] = G_ASTERIX_CONST.slice(0, i);
}

function Generate(l) for (local p = 0.5; p <= (l/2); ++p) kprint(G_SPACE_POOL [(l/2) - p] + G_ASTERIX_POOL[p*2] + G_SPACE_POOL [p + (l/2)]);

local tm = clock();

for(local n = 0; n < 10000; ++n) Generate(32);

print("SLC: " + (clock() - tm));

.. just a simple adaptation


Why put that much afford!!

function StarPyramid( rows )
{
local star=0, val1 = "", val2 = "";

    for( local i = 1;i <= rows; i++, star = 0, val1 = "", val2 = "")
{
        for(local space = 1; space <= rows-i; space++) val1 += " ";

while(star != i-1)
        {
            val2 += "* ";
            ++star;
        }
        print(val1 + val2);
    }
}
Can you test the benchmark of it?? @Shadow
Title: Re: Scripting challenges!
Post by: Shadow on Apr 13, 2017, 05:03 PM
Title: Re: Scripting challenges!
Post by: KAKAN on Apr 13, 2017, 05:07 PM
None of your code printed the desired output. Both of you fail haha!
Title: Re: Scripting challenges!
Post by: Shadow on Apr 13, 2017, 05:09 PM
Quote from: KAKAN on Apr 13, 2017, 05:07 PMNone of your code printed the desired output. Both of you fail haha!

          *
         * *
        * * *
       * * * *
      * * * * *
     * * * * * *
    * * * * * * *
   * * * * * * * *
  * * * * * * * * *

The only difference is the incremental stars. I'd say it does the job.
Title: Re: Scripting challenges!
Post by: aXXo on Apr 13, 2017, 07:24 PM
print("          * ");
print("         * * ");
print("        * * * ");
print("       * * * * ");
print("      * * * * * ");
print("     * * * * * * ");
print("    * * * * * * * ");
print("   * * * * * * * * ");
print("  * * * * * * * * *");
Title: Re: Scripting challenges!
Post by: Cool on Apr 13, 2017, 07:26 PM
Quote from: aXXo on Apr 13, 2017, 07:24 PMprint("          * ");
print("         * * ");
print("        * * * ");
print("       * * * * ");
print("      * * * * * ");
print("     * * * * * * ");
print("    * * * * * * * ");
print("   * * * * * * * * ");
print("  * * * * * * * * *");
LOL just LOL
Title: Re: Scripting challenges!
Post by: Anik on Apr 14, 2017, 03:31 AM
Quote from: aXXo on Apr 13, 2017, 07:24 PMprint("          * ");
print("         * * ");
print("        * * * ");
print("       * * * * ");
print("      * * * * * ");
print("     * * * * * * ");
print("    * * * * * * * ");
print("   * * * * * * * * ");
print("  * * * * * * * * *");
LMAO.. Btw it works  :P :P
Title: Re: Scripting challenges!
Post by: Anik on Apr 14, 2017, 03:37 AM
Quote from: KAKAN on Apr 13, 2017, 05:07 PMNone of your code printed the desired output. Both of you fail haha!
??? It works

Title: Re: Scripting challenges!
Post by: KAKAN on Apr 14, 2017, 04:20 AM
Quote from: aXXo on Apr 13, 2017, 07:24 PMprint("          * ");
print("         * * ");
print("        * * * ");
print("       * * * * ");
print("      * * * * * ");
print("     * * * * * * ");
print("    * * * * * * * ");
print("   * * * * * * * * ");
print("  * * * * * * * * *");
Shadow, benchmark this and this:-
print(@"
          *
         * *
        * * *
       * * * *
      * * * * *
     * * * * * *
    * * * * * * *
   * * * * * * * *
  * * * * * * * * *");
Title: Re: Scripting challenges!
Post by: EK.IceFlake on May 23, 2017, 05:19 PM
Quote from: Stormeus on Jun 10, 2015, 05:16 PMOne-line delegate abuse (two lines if counting the array).
[spoiler]
local arrayTest = ["test1","test2","test3","test4"];

// .apply replaces each value in an array with the returned value.
//
// This is a cheaty way of printing stuff without loops and we need to
// return the original value to avoid filling the array with nulls.
arrayTest.apply(function(v) { print(v); return v; });
[/spoiler]

One-line delegate abuse featuring lambdas:
[spoiler]
// Squirrel internally clones the array and uses the return value from map to
// fill the cloned array.
//
// If you were to look at the returned array from .map, you'd see a bunch
// of nulls, as we never return anything.
arrayTest.map(@(v) print(v));
[/spoiler]
Sorry for the bump but...
arrayTest.apply(print);???
Title: Re: Scripting challenges!
Post by: Stormeus on May 24, 2017, 02:20 AM
Quote from: EK.IceFlake on May 23, 2017, 05:19 PM
Quote from: Stormeus on Jun 10, 2015, 05:16 PMOne-line delegate abuse (two lines if counting the array).
[spoiler]
local arrayTest = ["test1","test2","test3","test4"];

// .apply replaces each value in an array with the returned value.
//
// This is a cheaty way of printing stuff without loops and we need to
// return the original value to avoid filling the array with nulls.
arrayTest.apply(function(v) { print(v); return v; });
[/spoiler]

One-line delegate abuse featuring lambdas:
[spoiler]
// Squirrel internally clones the array and uses the return value from map to
// fill the cloned array.
//
// If you were to look at the returned array from .map, you'd see a bunch
// of nulls, as we never return anything.
arrayTest.map(@(v) print(v));
[/spoiler]
Sorry for the bump but...
arrayTest.apply(print);???

Quoteand we need to return the original value to avoid filling the array with nulls.

That one-liner may work with map.
Title: Re: Scripting challenges!
Post by: EK.IceFlake on May 24, 2017, 02:56 PM
Your challenge is to make a function that accepts an array and returns a sorted array. You have to assume that every element in the array is an integer. You can't use the default array.sort method.
It will be given an antiscore using this formula: time * bytes where time is measured in milliseconds. It will be tested with this array: [960, 659, 528, 42, 562, 252, 453, 874, 682, 263, 172, 919, 388, 784, 205, 736] which I got off random.org, however, you are in no way to be optimizing your code for this particular list or sequence. It will be tested with 10000 iterations.
The one with the lowest antiscore wins.
Title: Re: Scripting challenges!
Post by: EK.IceFlake on May 24, 2017, 03:13 PM
Here's mine, 125 bytes.
Performance testing at the end.

[spoiler]function a(b){c<-[(1<<63)-1];b.map(function(d){foreach(e,f in c)if(f>=d){c.insert(e,d);break}});c.remove(c.len()-1);return c}[/spoiler]

Note that this only works on a 64-bit build of Squirrel. To deal with 32-bit builds, change 1<<63 to 1<<31.
Title: Re: Scripting challenges!
Post by: EK.IceFlake on May 30, 2017, 11:14 AM
This post has been buried.
I have successfully unburied it.

(this, if you didn't realize, is just a bump)
Title: Re: Scripting challenges!
Post by: Sebastian on May 30, 2017, 03:08 PM
Chill out, I'm not here for the challenges :D
I just made @EK.IceFlake 's post more visible, if anyone's ready to try.

function a( b )
{
          c <- [ ( 1 << 63 ) - 1 ];
          b.map( function( d )
          {
                    foreach( e, f in c )
                             if( f >= d )
                             {
                                        c.insert( e, d );
                              break
                              }
          } );
c.remove( c.len() - 1 );
return c
}