2021-05-27 11:44:51 (edited by mastodont 2021-05-27 12:40:15)

Hi guys.
Since many people seem to want to learn coding and are trying their best at it, I thought of a fun little exercise to try in order to improve our understanding of what programming means, how to apply concepts with code examples and how to explain your code to someone else. For me atleast, explaining helps me a lot if I want to understand something.
So, paste here the last piece of code that you have written and try to explain, using your own words, what it actually does. The programming language doesn't really matter, the more examples we receive the better since everyone can try to convert the code in their prefferred language.
I am a beginner myself and my teacher keeps me bussy with fun little exercises that keep my head spinning so, if there's interest for this topic, I will probably post pieces of code and try to explain them.
Without further delay, here is the latest code that I have worked on, written in c#:
Code start:

            Random r = new Random();
            int[] numbers = new int[10];
            int sum = 0;
            for (int i = 0; i < numbers.Length; i++)
            {
                numbers[i] = r.Next(1, 101);
            }
                foreach (int f in numbers)
                {
                sum  += f;
                }
            string n = string.Join("+ ", numbers);

            MessageBox.Show(n + "is equal to " + sum.ToString());

               

code end.
Okay, let me try to explain it: First, I declare 3 variables. A random variable an array of integer type and a simple integer. Then, I make a for that checks the array's length in order to be able to assign something to it. In that for, I tell it, by using the random variable, to assign a random number between 1 and 100 to each of the array's elements.
After that, I declare a foreach loop and tell it to add each element to the next one thus allowing me to know the sum of all the 10 random elements declared in the array. Next, for beauty's sake, I make a new string that joins the plus symbol with the array adding it between each number.
Finally, I create a message box and call the show function in which I tell it that the joined string called n is equal to the integer called sum, which stored the final value of the operation.
The result will be 10 numbers with the plus sign between them followed by the message is equal to and the result.

I hope this topic proves to be instructive for all programming newbies and I urge you to try submiting a piece of code and explaining it, it will really help, atleast it does help me understand what's happening behind the scenes in order to learn to think like a programmer.
If any advanced developers want to chime in they are more than welcome to submit and explain their code, as well as correct any mistakes made or provide better explanations.

“Get busy living or get busy dying.”
Stephen King

2021-05-27 11:47:26 (edited by mastodont 2021-05-27 11:49:04)

What the actual fuck? C# seems to don't like this forum lol. I received the next error when trying to submit the code, I had to imput a space between the square bracket and the variable in order for the message to submit. The error is as follows:
• [ i] was found without a matching [ /i]
can anyone guess what might be happening here?
2 seconds later: Lol had to edit the error aswell since it wasn't displaying correctly. This is super strange...

“Get busy living or get busy dying.”
Stephen King

2021-05-27 12:23:51

I like this idea... Here is the last code i've written.
var date=new Date();
var time=date.getHours();
var greeting;

function showTime() {
    if (time>=0 && time<12)  {
        greeting="Good Morning";
    }
    else if(time>=12 && time<18){
        greeting="Good AfterNoon";
    }
    else if(time>=18){
        greeting="Good Evening";
    }
    document.write(greeting+"<br/>");
}
showTime();
All this does in javascript is to greet the user to my website, based on the time of the day. It's not up yet, but i will upload it later today.

best regards
never give up on what ever you are doing.

2021-05-27 12:27:43

@2 its because brakets are thot to be bb code, you will need to put the code tag

2021-05-27 12:36:33

Ah thanks 4, forgot about BB code lol. Gonna edit it now.

“Get busy living or get busy dying.”
Stephen King

2021-05-27 14:01:46

I was last working on this. It's a script for a MUD I play. I don't know if I would use this as a learning example, some of it is pretty bad I should think but yeah. This is lua. The only code in here that I didn't write is the GMCP handler that pulls apart the package name and parameters then decodes the json data. I pulled that from ChatPack.

require "wait"
PPI = require("ppi")
ppi = PPI.Load("aedf0cb0be5bf045860d54b7")
json=require("json_rxi")
path = GetInfo(56).."worlds/CoreMUD/sounds/"
snd_ext = ".wav"
volumes = {50, 20, 30} -- global volume, ambience volume, communications volume
selected_volume = 1 -- index to above numerically-indexed table
dirs = {}
dirs["north"] = "south"
dirs["south"] = "north"
dirs["east"] = "west"
dirs["west"] = "east"
dirs["northeast"] = "southwest"
dirs["southwest"] = "northeast"
dirs["northwest"] = "southeast"
dirs["southeast"] = "northwest"
hp = 0
max_hp = 0
sp = 0
max_sp = 0
exp = 0
exp_to_next = 0
pct_full = 0 -- ore satchel
satchel_spoken = false -- tracks whether english sentence regarding satchel fullness has recently been spoken
satchel_last_msg = ""
automine = false
times_mined = 0 -- for inspecting the drill and recharging
needs_repair = false -- for drill maintenance
drill_dir = "north" -- for new shafts

AcceleratorTo("F5", "adjust_volume(-5)", 12)
AcceleratorTo("F6", "adjust_volume(5)", 12)
AcceleratorTo("F7", "select_volume()", 12)
Accelerator("ctrl+t", "tts", 12)
AcceleratorTo("ALT+SHIFT+H", "speak_health()", 12)
AcceleratorTo("ALT+SHIFT+S", "speak_satchel_pct()", 12)

function play(arg)

    if type(arg.snd) ~= "string" then
        error("The first argument must be the string name of a sound you wish to use.")
    else
        local fullpath = path..arg.snd..snd_ext
        local looping = arg.looping or 0
        local pan = arg.pan or 0
local volume = volumes[1]
        if arg.vol ~= nil and type(arg.vol) == "string" then
volume = get_volume(arg.vol)
elseif arg.vol ~= nil and type(arg.vol) == "number" then
volume = arg.vol
end -- if
sndobj = ppi.play(fullpath, looping, pan, volume)
    end -- if
return sndobj
end -- func

function play_random(arg)
if type(arg.snd) == "string" and type(arg.max) == "number" then
play{snd=arg["snd"]..tostring(math.random(1, arg["max"])), vol=arg.vol}
else
error("One or more invalid arguments encountered.")
end -- if
end -- func

function get_volume(vol)
if type(vol) == "string" then
if vol == "gv" then
return volumes[1]
elseif vol == "av" then
return volumes[2]
elseif vol == "cv" then
return volumes[3]
else
error("Expected gv, av, or cv")
end -- if
elseif type(vol) == "number" and not(vol > #volumes)then
return volumes[vol]
else
error("Invalid volume index.")
end -- if
end -- func

function get_volume_name(vol)
if type(vol) == "number" then
if vol == 1 then
return "global volume"
elseif vol == 2 then
return "ambience volume"
elseif vol == 3 then
return "communications volume"
else
error("The given numeric argument was not one of the valid volume indices.")
end -- if
else
return
end -- if
end -- func
function select_volume()
if selected_volume + 1 > #volumes then
selected_volume = 1
else
selected_volume = selected_volume + 1
end -- if
Execute("tts_interrupt "..get_volume_name(selected_volume).." at "..tostring(volumes[selected_volume]))
end -- func

function adjust_volume(amt)
-- provide positive or negative amount. Do not include the plus sign to indicate a positive amount, lua doesn't like it.
local internal_vol = volumes[selected_volume]
if internal_vol + amt < 0 then
internal_vol = 0
elseif internal_vol + amt > 100 then
internal_volume = 100
else
internal_vol = internal_vol + amt
end -- if
volumes[selected_volume] = internal_vol
Execute("tts_interrupt "..get_volume_name(selected_volume).." now at "..tostring(volumes[selected_volume]))
end -- func

function save_volumes()
SetVariable("gv", volumes[1])
SetVariable("av", volumes[2])
SetVariable("cv", volumes[3])
end -- func

function load_volumes()
volumes[1] = tonumber(GetVariable("gv"))or 50
volumes[2] = tonumber(GetVariable("av"))or 20
volumes[3] = tonumber(GetVariable("cv"))or 30
end -- func

function split_words(split_str)
words = {}
for word in split_str:gmatch("%w+") do
table.insert(words, word)
end -- loop
return(words)
end -- func
function split_items(split_str)
items = {}
for item in split_str:gmatch("%w+,") do
table.insert(items, item)
end -- loop
return(items)
end -- func
function last_word(word_str)
lst = split_words(word_str)
ln = #lst
return(lst[ln])
end -- func
function list_to_string(l1)
if not(type(l1) == "table") then
return
else
returnstr = ""
for i,j in ipairs(l1) do
if type(j) == "string" then
if string.len(returnstr) == 0 then
returnstr = returnstr .. j
else
returnstr = returnstr .. ", " .. j
end
end
end
end
return returnstr
end -- func

function casefold_words(str)
-- calls split_words, then casefolds every element in the resulting list, then returns the list
lst = split_words(str)
for k,v in ipairs(lst) do
lst[v] = string.lower(lst[v])
end -- for
return lst
end -- func

function do_buff(buffname, msg)
if type(buffname) == "string" and buffname ~= "" and type(msg) == "string" and msg ~= "" then
buffname = buffname:gsub("%s", "_")
Execute("history_add "..buffname.."="..msg)
Execute("history_add all="..msg)
else
error("Buffname and msg must both be non-empty strings")
end -- if
end -- func

function strSplit(str, delim, maxNb)
   -- Eliminate bad cases...
   if string.find(str, delim) == nil then
      return { str }
   end
   if maxNb == nil or maxNb < 1 then
      maxNb = 0    -- No limit
   end
   local result = {}
   local pat = "(.-)" .. delim .. "()"
   local nb = 0
   local lastPos
   for part, pos in string.gmatch(str, pat) do
      nb = nb + 1
      result[nb] = part
      lastPos = pos
      if nb == maxNb then
         break
      end
   end
   -- Handle the last field
   if nb ~= maxNb then
      result[nb + 1] = string.sub(str, lastPos)
   end
   return result
end

function get_health()
if max_hp == 0 then
-- So we don't go kerflunk by dividing by 0
Execute("tts_interrupt Information not available")
return
else
return tonumber((hp / max_hp) * 100)
end
end -- func

function speak(msg)
Execute("tts_interrupt "..msg)
end -- func
function speak_health()
local health = get_health() -- as percent of total
msg = tostring(health) .. " percent"
speak(msg)
end -- func

function OnPluginBroadcast (msg, id, name, text)
if id=="74f8c420df7d59ad5aa66246" then
--it's the gmcp handler!

text=Replace(text,"\\u00","~")
package,params=unpack(strSplit(StripANSI(text)," ___ "))
f=_G["gmcp_handle_"..Replace(package:lower(),".","_")]
if f~=nil then
f(json.decode(params))
else
end
end
end -- func

function gmcp_handle_char_mine(data)

local tot = data.total_ore
local max = data.max_ore
pct_full = math.modf(tot / max * 100)

if pct_full == 100 then
msg = "Your satchel is full."
elseif pct_full >= 75 then
msg = "Your satchel is three-quarters full."
elseif pct_full >= 50 then
msg = "Your satchel is half full."
elseif pct_full >= 25 then
msg = "Your satchel is one-quarter full."
end -- if
speak_satchel_english_sentence(msg)
end -- func

function speak_satchel_english_sentence(msg)
if msg == satchel_last_msg then
-- nothing to do so drop out
return
end -- if
if not(satchel_spoken) then
wait.make(function ()
satchel_spoken = true
Note(msg)
wait.time(1.5)
satchel_spoken = false
satchel_last_msg = msg
end)
else
-- nothing to do so drop out
return
end -- if
end -- func

function speak_satchel_pct()
speak(tostring(pct_full).."%")
end -- func

function gmcp_handle_char_vitals(data)
hp = data.hp
max_hp = data.maxhp
sp = data.sp
max_sp = data.maxsp
xp = data.experience
xp_to_next = data.next_level
end -- func

function gmcp_handle_comm_channel(data)
who = data.player
channel = data.chan
message = data.msg or ""
buff_msg = who..": "..message
do_buff(channel, buff_msg)
play_channel_sound(channel)
end -- func

function play_channel_sound(channel)

if type(channel) ~= "string" or channel == "" then
return
else
if channel == "rl" then
sound = "communication/chat"
elseif channel == "qa" then
sound = "communication/question"
end -- if

if sound ~= nil then
play{snd=sound, vol="cv"}
end -- if
end -- if
end -- func

function do_mine(op)
-- 0 for mining, 1 for drilling in shaft.
if not automine then return end
if pct_full >= 100 then
Execute("tts_interrupt automine terminated because satchel is full")
return
end -- if
if times_mined >= 12 then
 do_drill_maintenance()
times_mined = 0
end -- if
wait.make(function ()
wait.time(math.random(3, 5))
if op == 0 then
Send("drill ore")
times_mined = times_mined + 1
else
if drill_dir ~= nil then
if drill_dir == "floor" or drill_dir == "ceiling" then
Send("drill "..drill_dir)
else
Send("drill "..drill_dir.." wall")
end -- if
end -- if
end -- if
end)
end -- func

function do_drill_maintenance()
wait.make(function ()
Send("inspect drill")
wait.time(1)
if needs_repair then
Send("repair drill")
needs_repair = false
    wait.time(3)
end -- if
Send("recharge drill")
end)
end -- func

function get_opposite_direction(dir)
if dirs[dir] ~= nil then
return dirs[dir]
else
return
end -- if
end -- func

function parse_drill(dstr)
local dlst = split_words(dstr)
local ln = #dlst
if ln == 1 then
if dlst[1] == "ore" then
-- drop out since mining is handled by do_mine()
return
elseif dlst[1] == "ceiling" or dlst[1] == "floor" then
drill_dir = dlst[1]
end -- if
elseif ln == 2 then
if dlst[2] == "wall" then
-- it should else the game will bitch
for dir,opp in pairs(dirs) do
if dlst[1] == dir then drill_dir = dir end
end -- for
else
return
end -- if
else
return
end --if
end -- func
function get_var(var)
print(var)
end -- func

function trim(str)
-- trims the leading and trailing spaces from the given string and returns it
return (str:gsub("^%s*(.-)%s*$", "%1"))
end --func

function parse_atrium(argstr)
argstr = trim(argstr)
local points = {}
for itm in arg:gmatch("%l%d+") do
table.insert(points, itm)
end --loop
if #points > 2 then
for i=3, #points do
table.remove(points, i)
end -- loop
end -- if
return (points)
end -- func
Facts with Tom MacDonald, Adam Calhoun, and Dax
End racism
End division
Become united

2021-05-27 14:25:22 (edited by SkyLord 2021-05-27 14:31:40)

Well, I decided to chime in as well. A program which lets you edit encrypted files by decrypting them, opening a temp file with decrypted contents, then encrypting them again and saving to the file.
C#:

using System;
using System.IO;
using static Agsharp.Agsharp.EncryptionProvider;
using System.Diagnostics;

string TempPath=System.IO.Path.GetTempFileName();
try{
string Path=null;
string DecriptionKey=null;
if(!File.Exists("settings.txt")){
File.Create("settings.txt");
Environment.Exit(0);
}
else{
try{
string SettingsContents=File.ReadAllText("settings.txt");
string[] ParsedParams=SettingsContents.Split("\r\n", StringSplitOptions.RemoveEmptyEntries);
Path=ParsedParams[0];
DecriptionKey=ParsedParams[1];
}
catch(Exception ex){
Console.WriteLine($"Error while parsing settings: {ex.ToString()}");
}
}
File.WriteAllText(TempPath, StringDecrypt(File.ReadAllText(Path), DecriptionKey));
Process Notepad=Process.Start(new ProcessStartInfo(){
FileName="notepad.exe",
Arguments=TempPath
});
Notepad.WaitForExit();
File.WriteAllText(Path, StringEncrypt(File.ReadAllText(TempPath), DecriptionKey));
}
finally{
File.Delete(TempPath);
}

2021-05-27 15:42:06 (edited by Quin 2021-05-27 15:42:39)

A blank window using the raw Win32 API. Yes, you can kill me now.



window.c

#include <windows.h>

const char g_szClassName[] = "TheWindowClass";

LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
    switch(msg)
    {
        case WM_CLOSE:
            DestroyWindow(hwnd);
        break;
        case WM_DESTROY:
            PostQuitMessage(0);
        break;
        default:
            return DefWindowProc(hwnd, msg, wParam, lParam);
    }
    return 0;
}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
    WNDCLASSEX wc;
    HWND hwnd;
    MSG Msg;
    wc.cbSize         = sizeof(WNDCLASSEX);
    wc.style         = 0;
    wc.lpfnWndProc     = WndProc;
    wc.cbClsExtra     = 0;
    wc.cbWndExtra     = 0;
    wc.hInstance     = hInstance;
    wc.hIcon         = LoadIcon(NULL, IDI_APPLICATION);
    wc.hCursor         = LoadCursor(NULL, IDC_ARROW);
    wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
    wc.lpszMenuName  = NULL;
    wc.lpszClassName = g_szClassName;
    wc.hIconSm         = LoadIcon(NULL, IDI_APPLICATION);
    if(!RegisterClassEx(&wc))
    {
        MessageBox(NULL, "Window Registration Failed!", "Error!", MB_ICONEXCLAMATION | MB_OK);
        return 0;
    }
    hwnd = CreateWindowEx(WS_EX_CLIENTEDGE, g_szClassName, "Window", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 240, 120, NULL, NULL, hInstance, NULL);
    if(hwnd == NULL)
    {
        MessageBox(NULL, "Window Creation Failed!", "Error!", MB_ICONEXCLAMATION | MB_OK);
        return 0;
    }
    ShowWindow(hwnd, nCmdShow);
    UpdateWindow(hwnd);
    while(GetMessage(&Msg, NULL, 0, 0) > 0)
    {
        TranslateMessage(&Msg);
        DispatchMessage(&Msg);
    }
    return Msg.wParam;
}

2021-05-27 16:36:58

@8 I can't even guess what variables you used let alone understand the code LOL. Reading your piece of code makes me feel like this is the first time I have seen code in my life lmao.

“Get busy living or get busy dying.”
Stephen King

2021-05-27 16:57:37

@9:
And that's the exact reason I hate the Win API. I get it, but gross. That's like 50 lines to just to open a bloody window!

2021-05-27 16:58:03

Yeah, you know when I say that using the raw win32 API is a special sort of hell?  @8's code is why.

My Blog
Twitter: @ajhicks1992

2021-05-27 17:03:48

That would make a good punishment for detention for ehh maybe 6-12 grades. One hour a day until the window shows. No instruction, you must research everything yourself and figure it out. If you can't, well you get detention every day until the end of the school year.

Facts with Tom MacDonald, Adam Calhoun, and Dax
End racism
End division
Become united

2021-05-27 18:16:03

@12 it would be interesting to watch how soon different people would eventually figure it out. Would be nice if those were some nice youtube vids, heh.

2021-05-27 18:18:48

It's actually much easier than it appears it is if you know C, but it's easy in the way assembly language is easy. Try to do anything big--well.  Every button you want to add takes about as much code as that window if not more. Before you get as far as making it do something.

My Blog
Twitter: @ajhicks1992

2021-05-27 20:33:35

I don't know if this is allowed, but if i may post code for a second time... here it goes.
This is c++ code for a project we were instructed to do at college:
This prints the fibunacci numbers for the numbers 0 to 9:

#include <iostream>
#include <vector> //the vector library
using namespace std;
//function to calculate fibunacci with recurtion

int calc_fib(int input) {
    if (input<=1) {
        return input;
    }
    return calc_fib(input-1)+calc_fib(input-2);
}

vector<int> nums; //vector of numbers that I will use to return fibunacci for.

int main() {
    for (int numbers=0; numbers<10; numbers++){
        nums.push_back(numbers);
}

    for (int i=0; i<nums.size(); i++){
        cout <<"The fibunacci for "<<nums[i] <<" is "<<calc_fib(nums[i]) <<" ."<<endl;
    }
    return 0;
}
best regards
never give up on what ever you are doing.

2021-05-27 20:40:40

If you want an algorithmic exercise, rewrite fibonacci to use a loop.  Recursive fib doesn't work on large numbers because it recalculates a bunch of numbers.  try fib(5000) for example, though you will need to use Python because C+ integers can't hold numbers that large out of the box, if I recall how big fib(5000) is correctly.  If someone can't work this out I can post an answer later.

My Blog
Twitter: @ajhicks1992

2021-05-27 20:42:49

@16, thanx for that. The only reason why i used recurtion for this is because we were told to use it. but i'll definitely keep this in mind and give it a shot.

best regards
never give up on what ever you are doing.

2021-05-27 20:55:42

yeah. Depending on what exactly you're taking, they may cover this next. Recursive Fibonacci is a basic example of why algorithmic complexity matters.  Observe:

fib(5)
fib(4) + fib(3)
fib(3) + fib(2) + fib(4) + fib(3)
fib(2) + fib(1) + fib(1) + fib(0) + fib(3) + fib(2) + fib(2) + fib(1)

And so on, making every call on every listed line.  The loop can do it in 5 operations, but the above is something like 20 or 30--and you can imagine how much worse it gets for fib(100) on your own.

My Blog
Twitter: @ajhicks1992

2021-05-27 21:08:19

@ashleygrobler04 you can submit code as many times as you want, the last code you worked on today may not be the last for the rest of your days big_smile. This is a topic for beginners to exercise, to explain their code and see what others are practicing, the more code the better!

“Get busy living or get busy dying.”
Stephen King

2021-05-27 22:53:11

@18, I thought it went more like this:
fib(5)
=fib(4)+fib(3)
=fib(3)+fib(2)
=fib(2)+fib(1)
=fib(1)+fib(0)
Or something like that?
(Also, if you enjoy math, try the analytical version of Fibonacci -- smallest fib() I've ever seen.)

"On two occasions I have been asked [by members of Parliament!]: 'Pray, Mr. Babbage, if you put into the machine wrong figures, will the right answers come out ?' I am not able rightly to apprehend the kind of confusion of ideas that could provoke such a question."    — Charles Babbage.
My Github

2021-05-27 23:14:45

@20
No, because each of the functions recurses on both sides.  The reason fib is used as an example of why algorithmic complexity and implementation matters is that if you do fib(10) it computes the lower fibs multiple times.  fib(10) becomes fib(9) and fib(8) which is fine, but fib(9) becomes fib(8) and fib(7), which recomputes fib(8), and so on.  I forget exactly how many times you end up recomputing the lower ones, but it's a lot.

I've seen analytical fib and even did the proof as homework, but that's not really a programming exercise except that to do it you either have to be really clever or use infinite precision numerics, which is cool and all but not really the point of this thread where people are trying to learn basic and generally applicable things.

My Blog
Twitter: @ajhicks1992