Jump to content

Under 50 Lines Challenge!!

Try and make a program in any language that is under 50 lines of code* **

 

 

*Comments and White Lines included

** Standard formatting (so no super compacted 1-5 liners) 

I'm a python programmer and I play trombone

Link to comment
Share on other sites

Link to post
Share on other sites

Here are some of mine

def calc(starting_nums, length):
    last_num = starting_nums[0]
    recent_num = starting_nums[1]
    l = []
    temp = int
    for i in range(length):
        l.append(last_num)
        temp = last_num
        last_num = recent_num
        recent_num += temp
    return l

def Get_Num(range=50, num=None):
    if num == None:
        print(calc((1, 1), range))
    else:    
        print(calc((1, 1), num, length=range)[len((calc((1, 1), num)))-1])

if __name__ == "__main__":
    Get_Num() # if left blank it will just return the first 50

https://github.com/IsaacWP121/Fun-Algorithms/blob/master/Fibonacci.py#L1-L20
(This next one won't work on linux or mac)

import subprocess
def Prime(num):
    check  = []
    for i in range(2, round(num/2)):
        if num % i == 0:
            check.append(True)
        else:
            check.append(False)
    if True in check:
        return "Not Prime"
    else:
        return "Prime"


if __name__ == "__main__":
    x = True
    while x:
        print("What is the number you want to check?")
        num = input()
        def check():
            try: 
                int(num)
                return True
            except ValueError:
                return False
        if check():
            print(Prime(int(num)))
            x = False
            subprocess.call('pause>nul',shell=True)
        else:
            subprocess.call('cls',shell=True)
            print("That is not a valid number")

https://github.com/IsaacWP121/Fun-Algorithms/edit/master/PrimeOrNot.py#L1-L32


 

I'm a python programmer and I play trombone

Link to comment
Share on other sites

Link to post
Share on other sites

just wrote it for fun...

tail - shows the last 512 bytes of a file and keeps showing what's added to the end of file ... useful to see web server/ftp logs or whatever as they're updated

php.exe tail.php  "x:\path\to\filename.extension"

could be much smaller but has some added text on screen to remind user how to close it and show the app is still working (every 10s)

 

<?php
if (count($argv)==1) die('usage : tail.php "filename.ext"');
$argv[0] = ''; $path = trim(implode(' ',$argv),'" ');
$CRLF = chr(0x0D).chr(0x0A); echo 'Trying to open '.$path.$CRLF;
$handle = fopen($path,'rb'); if (!$handle) die('Failed to open file.');
$finfo = fstat($handle);

echo 'Filesize : '.$finfo['size'].' bytes. Press Ctrl+C to quit.'.$CRLF.$CRLF;
$offset = $finfo['size'] - 512; $offset = $offset <0 ? 0 : $offset;
$counter = 1;
while (1==1) {
	$finfo = fstat($handle); if ($offset>$finfo['size']) $offset = $finfo['size'];
	if ($offset<$finfo['size']) {
		if ($counter>0) { echo $CRLF.$CRLF; $counter=1; }
		$ret = fseek($handle,$offset);
		$buffer = fread($handle,512);
		echo $buffer;
		$offset += strlen($buffer);
		
	} else {
		$counter++;
	}
	sleep(1);
	if ($counter % 10 == 0) echo $CRLF.date('H:i:s',time()).' Press Ctrl+C to quit.';
}
?>

 

Link to comment
Share on other sites

Link to post
Share on other sites

6 hours ago, mariushm said:

just wrote it for fun...

tail - shows the last 512 bytes of a file and keeps showing what's added to the end of file ... useful to see web server/ftp logs or whatever as they're updated

php.exe tail.php  "x:\path\to\filename.extension"

could be much smaller but has some added text on screen to remind user how to close it and show the app is still working (every 10s)

 


<?php
if (count($argv)==1) die('usage : tail.php "filename.ext"');
$argv[0] = ''; $path = trim(implode(' ',$argv),'" ');
$CRLF = chr(0x0D).chr(0x0A); echo 'Trying to open '.$path.$CRLF;
$handle = fopen($path,'rb'); if (!$handle) die('Failed to open file.');
$finfo = fstat($handle);

echo 'Filesize : '.$finfo['size'].' bytes. Press Ctrl+C to quit.'.$CRLF.$CRLF;
$offset = $finfo['size'] - 512; $offset = $offset <0 ? 0 : $offset;
$counter = 1;
while (1==1) {
	$finfo = fstat($handle); if ($offset>$finfo['size']) $offset = $finfo['size'];
	if ($offset<$finfo['size']) {
		if ($counter>0) { echo $CRLF.$CRLF; $counter=1; }
		$ret = fseek($handle,$offset);
		$buffer = fread($handle,512);
		echo $buffer;
		$offset += strlen($buffer);
		
	} else {
		$counter++;
	}
	sleep(1);
	if ($counter % 10 == 0) echo $CRLF.date('H:i:s',time()).' Press Ctrl+C to quit.';
}
?>

 

Could you explain why you did while (1==1) rather than while(true)?

                     ¸„»°'´¸„»°'´ Vorticalbox `'°«„¸`'°«„¸
`'°«„¸¸„»°'´¸„»°'´`'°«„¸Scientia Potentia est  ¸„»°'´`'°«„¸`'°«„¸¸„»°'´

Link to comment
Share on other sites

Link to post
Share on other sites

34 minutes ago, vorticalbox said:

Could you explain why you did while (1==1) rather than while(true)?

Out of habit. I got used (as a sort of good practice) to always have < > != == or === in an if / while / do / loop / whatever, so while (true)  while correct, just doesn't feel right to me.

Also, in php you may often be tempted to do if (!$variable) but that can be wrong, because you may want to do $variable===FALSE

 

In the case of the example above, in theory I think while(true) would be a few cpu cycles faster, but in practice I think the Zend engine (which converts the php script to bytecode) will optimize away  the 1==1 to true anyway when the script is loaded, so the second time the while loop goes, the result is the same... it's like writing "true" there.

Link to comment
Share on other sites

Link to post
Share on other sites

6 hours ago, mariushm said:

Out of habit. I got used (as a sort of good practice) to always have < > != == or === in an if / while / do / loop / whatever, so while (true)  while correct, just doesn't feel right to me.

Also, in php you may often be tempted to do if (!$variable) but that can be wrong, because you may want to do $variable===FALSE

 

In the case of the example above, in theory I think while(true) would be a few cpu cycles faster, but in practice I think the Zend engine (which converts the php script to bytecode) will optimize away  the 1==1 to true anyway when the script is loaded, so the second time the while loop goes, the result is the same... it's like writing "true" there.

That’s a good idea maybe I should pick up that habit so I’m more efficient in future

I'm a python programmer and I play trombone

Link to comment
Share on other sites

Link to post
Share on other sites

#include <iostream>
#include <ctime>
#include <chrono>
#include <unistd.h>
using namespace std;
int main(){
    system("clear");
    auto time = chrono::system_clock::to_time_t(chrono::system_clock::now());
    cout << ctime(&time);
    usleep(3);
    main();
    return 0;
}

 

Link to comment
Share on other sites

Link to post
Share on other sites

Here is the one I wrote for work to merge CSVs with the same headers into a single CSV

node.

const fs = require('fs').promises;
const csv = require('csvtojson');
const { parse  } = require('json2csv');

const path = './csv';
const fields = ['id', 'firstname', 'lastname']

const opts = { fields };
const listFiles = (folder) => fs.readdir(folder);
const loadCSV = (files) => Promise.all(files.map((file) => csv().fromFile(`${path}/${file}`)));
const flattenArray = (arrays) => [].concat(...arrays);
const parser = (items) => parse(items, opts)
const save = (data) => fs.appendFile('merged.csv', data)

listFiles(path)
  .then(loadCSV)
  .then(flattenArray)
  .then(parser)
  .then(save)
  .catch(console.error)

 

                     ¸„»°'´¸„»°'´ Vorticalbox `'°«„¸`'°«„¸
`'°«„¸¸„»°'´¸„»°'´`'°«„¸Scientia Potentia est  ¸„»°'´`'°«„¸`'°«„¸¸„»°'´

Link to comment
Share on other sites

Link to post
Share on other sites

A simple Common Lisp client for scraping a web page's contents (e.g. a single-serving site) - requires Quicklisp:

 

(defparameter *url* "http://dowebsitesneedtolookexactlythesameineverybrowser.com") ;; CHANGE THAT IF YOU WISH :-)

(ql:quickload '(:dexador :plump :lquery))
(defvar *content-obj* (plump:parse (dex:get *url*)))
(princ (string-trim '(#\Space #\Newline #\Backspace #\Tab #\Linefeed #\Page #\Return #\Rubout) (lquery:$1 *content-obj* "body" (text))))

 

Note that the string-trim function will delete all spaces here. Remove the parameters which you would like to keep in your output, like newlines or so.

Write in C.

Link to comment
Share on other sites

Link to post
Share on other sites

stock prediction in pure JS  nodeJs most of the lines are training data :(

bugger example you can see here

 

https://repl.it/@vorticalbox/stockPrediction

 

const brain = require('brain.js');
const trainingData = [
  [{
    open: 1.045509090909091,
    high: 1.063281818181818,
    low: 1.0419909090909092,
    close: 1.0563909090909092
  },
  {
    open: 1.0427181818181819,
    high: 1.0529818181818182,
    low: 1.0279,
    close: 1.0434545454545454
  },],
  [
    {
      open: 1.006318181818182,
      high: 1.0163454545454547,
      low: 1.000909090909091,
      close: 1.014590909090909
    },
    {
      open: 1.0052272727272726,
      high: 1.0177363636363637,
      low: 0.9999272727272728,
      close: 1.0137545454545456
    }
  ]
]
const test = [{
  open: 1.0145454545454546,
  high: 1.0168545454545455,
  low: 1.0066090909090908,
  close: 1.0085454545454546
},
{
  open: 1.0008181818181818,
  high: 1.010218181818182,
  low: 0.9959999999999999,
  close: 1.0094272727272726
}]
const net = new brain.recurrent.LSTMTimeStep({
  inputSize: 4,
  hiddenLayers: [8, 8],
  outputSize: 4
});
net.train(trainingData, { learningRate: 0.005, errorThresh: 0.02, log: console.log, logPeriod: 100 });
const forecast = net.forecast(test, 3)
console.log(forecast)

 

Edited by vorticalbox
becuase Dat Guy :P

                     ¸„»°'´¸„»°'´ Vorticalbox `'°«„¸`'°«„¸
`'°«„¸¸„»°'´¸„»°'´`'°«„¸Scientia Potentia est  ¸„»°'´`'°«„¸`'°«„¸¸„»°'´

Link to comment
Share on other sites

Link to post
Share on other sites

6 minutes ago, vorticalbox said:

stock prediction in pure JS

require() is not pure JS.

Write in C.

Link to comment
Share on other sites

Link to post
Share on other sites

Just now, Dat Guy said:

require() is not pure JS.

well, it's actually nodeJS and it's using a package but that also wrote in JS, it is not fast at training because you know javascript but it's still pretty cool.

                     ¸„»°'´¸„»°'´ Vorticalbox `'°«„¸`'°«„¸
`'°«„¸¸„»°'´¸„»°'´`'°«„¸Scientia Potentia est  ¸„»°'´`'°«„¸`'°«„¸¸„»°'´

Link to comment
Share on other sites

Link to post
Share on other sites

Sudoku game generator, 50 lines, compressed to 90 columns, prints in notepad++, within the margins. The program compiles and runs.

Spoiler

/*
	Sudoku Generator,Variable Skill Level
	KeyboardCowboy
	8/8/2019
	-Very Lite Commenting
	Use flag, -std=c++11
	Compressed to 90 Columns, Still Compiles, Under 50 Lines.
*/
#include <iostream>
#include <algorithm>
#include <stdlib.h>
#include <time.h>
using namespace std;const int S=9,H=4,L=25;const int B[H][L]={{201,205,205,205,205,205,
205,205,209,205,205,205,205,205,205,205,209,205,205,205,205,205,205,205,187},{186,0,1,0,1
,0,1,0,179,0,1,0,1,0,1,0,179,0,1,0,1,0,1,0,186},{199,196,196,196,196,196,196,196,197,196
,196,196,196,196,196,196,197,196,196,196,196,196,196,196,182},{200,205,205,205,205,205,
205,205,207,205,205,205,205,205,205,205,207,205,205,205,205,205,205,205,188}};
int RND(int a);bool box(int g[S][S],int m,int n,int num);bool hor(int g[S][S],int m,
int n,int num);bool vir(int g[S][S],int m,int n,int num);bool check(int g[S][S],int m,
int n,int num);bool av(int g[S][S],int &m,int &n);void dump(int g[S][S]);bool solve(
int g[S][S],int f=0);bool gen(int g[S][S],int dif);void hlpr(int x);int main(){int dif=0,
g[S][S]={0};srand(time(NULL));cout<<"SHALL WE PLAY A GAME?"<<endl;cout<<
"Enter Skill Level 1-8: ";cin>>dif;cin.ignore();cout<<endl;if((dif<1)||(dif>8))dif=4;
if(gen(g,dif)){cout<<"Skill: "<<dif<<endl;cout<<"Generated Game!"<<endl;dump(g);cout<<
"Press Return For Solution...";while(cin.get()!='\n');cout<<endl;if(solve(g)){cout<<
"Solution!"<<endl;dump(g);}else cout<<"Solver Error"<<endl;}else cout<<"Generator Error"
<<endl;return 0;}bool solve(int g[S][S],int f){int m=0,n=0,tab[S]={1,2,3,4,5,6,7,8,9};
if(f)random_shuffle(begin(tab),end(tab),RND);if(av(g,m,n))return 1;for(int i=0;i<S;i++){
int num=tab[i];if(!check(g,m,n,num)){g[m][n]=num;if(solve(g,f))return 1;g[m][n]=0;}}
return 0;}bool gen(int g[S][S],int dif){if(solve(g,1)){bool msk[S]={0};for(int j=0;j<dif;
j++)msk[j]=1;for(int i=0;i<S;i++){random_shuffle(begin(msk),end(msk),RND);for(int j=0;j<
S;j++)if(msk[j])g[i][j]=0;}return 1;}return 0;}void hlpr(int x){for(int i=0;i<L;i++)cout
<<(char) B[x][i];cout<<endl;}void dump(int g[S][S]){int w=0;hlpr(0);for(int i=0;i<S;i++)
{for(int j=0;j<L;j++){if(B[1][j]==1){if(g[i][w]==0)cout<<(char)250;else cout<<g[i][w];w=
(w+1)%S;}else cout<<(char)B[1][j];} cout<<endl;if((i==2)||(i==5))hlpr(2);}hlpr(3);}
bool box(int g[S][S],int m,int n,int num){m =(m/3)*3;n =(n/3)*3;for(int i=m;i<m+3;i++){
for(int j=n;j<n+3;j++)if(num==g[i][j])return 1;}return 0;}bool hor(int g[S][S],int m,
int n,int num){for(int i=0;i<S;i++){if(num==g[m][n])return 1;n=(n+1)%S;}return 0;}
bool vir(int g[S][S],int m,int n,int num){for(int i=0;i<S;i++){if(num==g[m][n])return 1;
m=(m+1)%S;}return 0;}bool av(int g[S][S],int &m,int &n){for(m=0;m<S;m++)for(n=0;n<S;n++)
if(g[m][n]<1)return 0;return 1;}bool check(int g[S][S],int m,int n,int num){bool ret=
box(g,m,n,num);ret|=vir(g,m,n,num);ret|=hor(g,m,n,num);return ret;}int RND(int a){
return rand()%a;}

 

Formated

Spoiler

/*
	Sudoku Generator, Variable Skill Level
	KeyboardCowboy
	8/8/2019
	-Very Lite Commenting
	Use flag, -std=c++11
*/

#include <iostream>
#include <algorithm>
#include <stdlib.h>
#include <time.h>

using namespace std;
const int S = 9, H = 4, L = 25; //board size

const int B[H][L] = {
    {201,205,205,205,205,205,205,205,209,205,205,205,205,205,205,205,209,205,205,205,205,205,205,205,187},  //top ascii
    {186, 0 , 1 , 0 , 1 , 0 , 1 , 0 ,179, 0 , 1 , 0 , 1 , 0 , 1 , 0 ,179, 0 , 1 , 0 , 1 , 0 , 1 , 0 ,186},  //value ascii
    {199,196,196,196,196,196,196,196,197,196,196,196,196,196,196,196,197,196,196,196,196,196,196,196,182},  //divider ascii
    {200,205,205,205,205,205,205,205,207,205,205,205,205,205,205,205,207,205,205,205,205,205,205,205,188}}; //bottom ascii

int RND(int a);                                  //random function
bool box(int g[S][S], int m, int n, int num);    //box check
bool hor(int g[S][S], int m, int n, int num);    //horizontal check
bool vir(int g[S][S], int m, int n, int num);    //vertical check
bool check(int g[S][S], int m, int n, int num);  //game rule check
bool av(int g[S][S], int &m, int &n);            //move on to next blank
void dump(int g[S][S]);                          //dumps the board with fancy ascii
bool solve(int g[S][S], int f = 0);              //solves a board
bool gen(int g[S][S], int dif);                  //generates the board
void hlpr(int x);                                //helper function for dump

int main()
{
    int dif = 0, g[S][S] = {0};
    srand (time(NULL));
    cout << "SHALL WE PLAY A GAME?" << endl;
    cout << "Enter Skill Level 1-8: ";
    cin >> dif;
    cin.ignore();
    cout << endl;
    if((dif < 1)||(dif > 8))
        dif = 4;
    if(gen(g, dif))
    {
        cout << "Skill: " << dif << endl;
        cout << "Generated Game!" << endl;
        dump(g); //game dump
        cout << "Press Return For Solution...";
        while(cin.get()!='\n');
        cout << endl;
        if(solve(g))
        {
            cout << "Solution!" << endl;
            dump(g); //solution dump
        }
        else
            cout << "Solver Error" << endl;
    }
    else
        cout << "Generator Error" << endl;
    return 0;
}

//solves a board
bool solve(int g[S][S], int f)
{
    int m = 0, n = 0, tab[S] = {1,2,3,4,5,6,7,8,9};
    if(f)
        random_shuffle(begin(tab), end(tab), RND);
    if(av(g, m, n))
        return 1;
    for(int i = 0; i < S; i++)
    {
        int num = tab[i];
        if(!check(g,m,n,num))
        {
            g[m][n] = num;
            if(solve(g, f))
                return 1;
            g[m][n] = 0;
        }
    }
    return 0;
}

//generates the board
bool gen(int g[S][S], int dif)
{
    if(solve(g, 1))
    {
        bool msk[S] = {0};
        for(int j = 0; j < dif; j++)
            msk[j] = 1;
        for(int i = 0; i < S; i++)
        {
            random_shuffle(begin(msk), end(msk), RND);
            for(int j = 0; j < S; j++)
                if(msk[j])
                    g[i][j] = 0;
        }
        return 1;
    }
    return 0;
}

//dump helper
void hlpr(int x)
{
    for(int i = 0; i < L; i++)
        cout << (char) B[x][i];
    cout << endl;
}

//new dump, dumps the board with fancy ascii
void dump(int g[S][S])
{
    int w = 0;
    hlpr(0);
    for(int i = 0; i < S; i++)
    {
        for(int j = 0; j < L; j++)
        {
            if(B[1][j] == 1)
            {
                if(g[i][w] == 0)
                    cout << (char) 250;
                else
                    cout << g[i][w];
                w=(w+1)%S;
            }
            else
                cout << (char) B[1][j];
        }
        cout << endl;
        if((i==2) || (i==5))
            hlpr(2);
    }
    hlpr(3);
}

//box check
bool box(int g[S][S], int m, int n, int num)
{
    m =(m/3)*3;
    n =(n/3)*3;
    for(int i = m; i < m+3; i++)
    {
        for(int j = n; j < n+3; j++)
            if(num == g[i][j])
                return 1;
    }
    return 0;
}

//horizontal check
bool hor(int g[S][S], int m, int n, int num)
{
    for(int i = 0; i < S; i++)
    {
        if(num == g[m][n])
            return 1;
        n=(n+1)%S;
    }
    return 0;
}

//vertical check
bool vir(int g[S][S], int m, int n, int num)
{
    for(int i = 0; i < S; i++)
    {
        if(num == g[m][n])
            return 1;
        m=(m+1)%S;
    }
    return 0;
}

//move on to next blank
bool av(int g[S][S], int &m, int &n)
{
    for(m = 0; m < S; m++)
        for(n = 0; n < S; n++)
            if(g[m][n] < 1)
                return 0;
    return 1;
}

//game rule check
bool check(int g[S][S], int m, int n, int num)
{
    bool ret = box(g, m, n, num);
    ret |= vir(g, m, n, num);
    ret |= hor(g, m, n, num);
    return ret;
}

//random function
int RND(int a)
{
    return rand()%a;
}

 

Screenshot

Spoiler

image.png.71ac673241063e894bde896586993113.png

main.cpp.pdf

Link to comment
Share on other sites

Link to post
Share on other sites

print("Hello World")

<?php
echo 'Hello World';
?>
Console.WriteLine("Hello World!");
#!/usr/bin/perl
print "Hello World!\n";
puts 'Hello world!'

I think I nailed it! ?

Main Rig CPU: AMD Ryzen 7 5700x GPU: Asus TUF Gaming RX5700XT MBASUS AM4 TUF Gaming X570-Plus RAM: 64GB Corsair Dominator Platinum 3200 CPU Cooler: Cooler Master Master Liquid LC240E SSD: Crucial 250gb M.2 + Crucial 500gb SSD HDD: PSU: Thermaltake Toughpower Gran RGB 850W 80+ Gold Case: Corsair Carbide 275R KB: Glorious GMMK 85% MOUSE: Razer Naga Trinity HEADSET: Go XLR with Shure SM7B mic and beyerdynamic DT 990

 

unRAID Plex Server CPU: Intel i7 6700 GPU: Nvidia Quadro P2000 MB: Asus B150M-C RAM: Crucial Ballistix 32gb DDR4 3000MT/s CPU Cooler: Stock Intel SSD: Western Digital 500GB Red HDD: 4TB Seagate Baracude 3x 4TB Seagate Ironwolf PSU: EVGA BT 80+ Bronze 450W Case: Cooler Master HAF XB EVO KB: Cheap Logitech KB + Mouse combo

Link to comment
Share on other sites

Link to post
Share on other sites

1 hour ago, Dat Guy said:

@KeyboardCowboyWhen using compression like that, all of my Lisp applications fit one line!!1

its not 'too' compressed, I thought it was within reason lol. You should post a one-liner.

Link to comment
Share on other sites

Link to post
Share on other sites

Some less complicated Common Lisp applications - not always true for all Lisp dialects - can be written as one-liners, see this alternative formatting of my few-liner above:

(defparameter *url* "http://dowebsitesneedtolookexactlythesameineverybrowser.com") (ql:quickload '(:dexador :plump :lquery)) (defvar *content-obj* (plump:parse (dex:get *url*))) (princ (string-trim '(#\Space #\Newline #\Backspace #\Tab #\Linefeed #\Page #\Return #\Rubout) (lquery:$1 *content-obj* "body" (text))))

It is still understandable, but you probably should not do that.

 

I guess the rationale behind this topic is to have your usual formatting. If you usually write like this, seek help! :D 

Write in C.

Link to comment
Share on other sites

Link to post
Share on other sites

13 minutes ago, Dat Guy said:

Some less complicated Common Lisp applications - not always true for all Lisp dialects - can be written as one-liners, see this alternative formatting of my few-liner above:


(defparameter *url* "http://dowebsitesneedtolookexactlythesameineverybrowser.com") (ql:quickload '(:dexador :plump :lquery)) (defvar *content-obj* (plump:parse (dex:get *url*))) (princ (string-trim '(#\Space #\Newline #\Backspace #\Tab #\Linefeed #\Page #\Return #\Rubout) (lquery:$1 *content-obj* "body" (text))))

It is still understandable, but you probably should not do that.

 

I guess the rationale behind this topic is to have your usual formatting. If you usually write like this, seek help! :D 

Yeah after seeing these one liners I'm gonna edit the original post ?

I'm a python programmer and I play trombone

Link to comment
Share on other sites

Link to post
Share on other sites

14 hours ago, L0m said:

Yeah after seeing these one liners I'm gonna edit the original post ?

Aww, that just makes it more difficult. You should allow 50 'printable' lines.

Link to comment
Share on other sites

Link to post
Share on other sites

Sudoku game generator, 50 lines, simi standard formatting (not compressed?). More commenting this time.

/*----- keyboardCowboy | 8/8/19 | Sudoku Generator ------*/
#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <algorithm>
#include <string.h>
using namespace std;
const int S = 9;                                            //size of arrays
int RND(int i){return rand()%i;}                            //random funk
void mask(int G[S][S]){                                     //skill level mask
    int arr[S] = {1,1,1,1,0,0,0,0,0};                       //skill = 4, change mask, 1 = blank (skill)
    for(int i = 0; i < S; i++){
        random_shuffle(&arr[0], &arr[S], RND);              //mix the mask
        for(int j = 0; j < S; j++) if(arr[j]) G[i][j] = 0;}}//write the mask
void swapRC(int G[S][S], int a, int b, bool f){             //f=0, row | f=1, col
    int c = 0;                                              //swaps rows&cols
    for(int i = 0; i < S; i++) f ? (c=G[i][a], G[i][a]=G[i][b], G[i][b]=c) : (c=G[a][i], G[a][i]=G[b][i], G[b][i]=c);}
void mix(int G[S][S]){                                      //mixes rows and cols at random
    int a = rand()%1024;                                    //max iterations is 1024 (make it bigger?)
    for(int i = 0; i < a; i++){
        bool rc = (bool) rand()%2;                          //row/col bit
        int pik = rand()%3;                                 //which row/col
        swapRC(G, (pik*3), (pik*3)+2, rc);}}                //swap that shit!
void shiftLeft(int arr[S], int steps){                      //shifts array to the left x times
    for(int i = 0; i < steps; i++){
        int c = arr[0];
        for(int j = 0; j < S-1; j++) arr[j] = arr[j+1];
        arr[S-1] = c;}}
void init(int G[S][S]){                                     //init game board
    int cnt = 0, arr[S] = {1,2,3,4,5,6,7,8,9};              //base condition
    random_shuffle(&arr[0], &arr[S], RND);                  //mix base at random
    do{
        for(int i = 0; i < S; i++) G[cnt][i] = arr[i];
        (++cnt%3 == 0) ? shiftLeft(arr, 4) : shiftLeft(arr, 3);
    }while(cnt < S);}
void dump(int G[S][S]){                                     //dumps the board
    for(int i = 0; i < S; i++){
        for(int j = 0; j < S; j++) !G[i][j] ? cout << (char) 250 << " " : cout << G[i][j] << " ";
        cout << endl;
    }cout << endl;}
int main(){                                                 //main... its main
    int G[S][S] = {0}, K[S][S] = {0};                       //2 game arrays, K=solution
    srand (time(NULL));                                     //init rand
    init(G); mix(G); memcpy(K, G, sizeof(K)); mask(G);      //init, mix the 2d array, copy, then set skill mask
    cout << "Puzzle, Skill:4\n"; dump(G);                   //display game
    cout << "Press Return for Solution..."; cin.ignore();   //waits for user intervention
    cout << "\nSolution\n"; dump(K);                        //displays the solution
    return 0;}

ScreenShot

Spoiler

image.png.599d26290445b7a35a0bcc3e0e4e8ca2.png

 

Link to comment
Share on other sites

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

×