How to add colour to the American Flag - colors

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package americanflag;
/**
*
* #author abzdino
*/
public class AmericanFlag {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
String p1 = "* * * * * * ==================================\n * * * * * ==================================";
String p2 = "==============================================";
for (int i = 0; i < 4; i++) {
System.out.println(p1);
}
System.out.println("* * * * * * ==================================");
for (int i = 0; i < 6; i++) {
System.out.println(p2);
}
}
}// TODO code application logic here
I've been asked by my professor to write a Java program to print an American flag on the screen (which is coded above). However, our professor informed us to think outside the box and use colour rather than it be black and white.

Related

failed to send activation message with Mythauth

I am using myth auth to signup my website, in localhost its work but when hosting, send activation to email always display error "failed to send activation message", can anyone help me?
do it like me
/**
* Resend activation account.
* #param AuthEntity $entity
*/
public
function sendActivateCodeViaEmail(AuthEntity $entity): void
{
if (is_null($entity)) $this->httpException(lang('Shared.api.validation'), ResponseInterface::HTTP_NOT_ACCEPTABLE);
$findUser = $this->userModel->where('email', $entity->email)
->where('active', 0)
->first();
if (is_null($findUser)) $this->httpException(lang('Auth.activationNoUser'), ResponseInterface::HTTP_CONFLICT);
$isSent = $this->email
->setTo($entity->email)
->setSubject(lang('Auth.activationSubject'))
->setMessage(view($this->authConfig->views['emailActivation'],
['hash' => $entity->toArray()['activate_hash']]))
->setMailType('html')->send();
if (!$isSent) {
$this->httpException(lang('Auth.unknownError'),
ResponseInterface::HTTP_BAD_REQUEST, $this->email->printDebugger(['headers']['headers'] ?? lang('Auth.unknownError')));
}
unset($entity->email);
if (!$this->userModel->update($findUser->id, $entity)) {
$this->httpException(lang('Shared.api.reject'), ResponseInterface::HTTP_BAD_REQUEST, serializeMessages($this->userModel->errors()));
}
}
email config
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
class Email extends BaseConfig
{
/**
* #var string
*/
public $fromEmail='admin#emaple.ir';
/**
* #var string
*/
public $fromName='admin';
/**
* #var string
*/
public $recipients;
/**
* The "user agent"
*
* #var string
*/
public $userAgent = 'CodeIgniter';
/**
* The mail sending protocol: mail, sendmail, smtp
*
* #var string
*/
public $protocol = 'smtp';
/**
* The server path to Sendmail.
*
* #var string
*/
public $mailPath = '/usr/sbin/sendmail';
/**
* SMTP Server Address
*
* #var string
*/
public $SMTPHost='mail.emaple.ir';
/**
* SMTP Username
*
* #var string
*/
public $SMTPUser='admin#emaile.ir';
/**
* SMTP Password
*
* #var string
*/
public $SMTPPass='X04r0U2ikd';
/**
* SMTP Port
*
* #var int
*/
public $SMTPPort = 25;
/**
* SMTP Timeout (in seconds)
*
* #var int
*/
public $SMTPTimeout = 5;
/**
* Enable persistent SMTP connections
*
* #var bool
*/
public $SMTPKeepAlive = false;
/**
* SMTP Encryption. Either tls or ssl
*
* #var string
*/
public $SMTPCrypto = '';
/**
* Enable word-wrap
*
* #var bool
*/
public $wordWrap = true;
/**
* Character count to wrap at
*
* #var int
*/
public $wrapChars = 76;
/**
* Type of mail, either 'text' or 'html'
*
* #var string
*/
public $mailType = 'text';
/**
* Character set (utf-8, iso-8859-1, etc.)
*
* #var string
*/
public $charset = 'UTF-8';
/**
* Whether to validate the email address
*
* #var bool
*/
public $validate = false;
/**
* Email Priority. 1 = highest. 5 = lowest. 3 = normal
*
* #var int
*/
public $priority = 3;
/**
* Newline character. (Use “\r\n” to comply with RFC 822)
*
* #var string
*/
public $CRLF = "\r\n";
/**
* Newline character. (Use “\r\n” to comply with RFC 822)
*
* #var string
*/
public $newline = "\r\n";
/**
* Enable BCC Batch Mode.
*
* #var bool
*/
public $BCCBatchMode = false;
/**
* Number of emails in each BCC batch
*
* #var int
*/
public $BCCBatchSize = 200;
/**
* Enable notify message from server
*
* #var bool
*/
public $DSN = false;
}

EventEmitter error after updating to NPM 3.10

I have updated NPM and now my code is returning the following error (please see picture):
Error Message can someone please provide guidance in identifying the culprit? My suspicion is that it has to do with inheritss which I'm not familiar with.
/**
* Expose the constructor.
*/
exports = module.exports = Store;
/**
* Module dependencies.
*/
var EventEmitter = process.EventEmitter;
/**
* Store interface
*
* #api public
*/
function Store (options) {
this.options = options;
this.clients = {};
};
/**
* Inherit from EventEmitter.
*/
Store.prototype.__proto__ = EventEmitter.prototype;
/**
* Initializes a client store
*
* #param {String} id
* #api public
*/
Store.prototype.client = function (id) {
if (!this.clients[id]) {
this.clients[id] = new (this.constructor.Client)(this, id);
}
return this.clients[id];
};
/**
* Destroys a client
*
* #api {String} sid
* #param {Number} number of seconds to expire client data
* #api private
*/
Store.prototype.destroyClient = function (id, expiration) {
if (this.clients[id]) {
this.clients[id].destroy(expiration);
delete this.clients[id];
}
return this;
};
/**
* Destroys the store
*
* #param {Number} number of seconds to expire client data
* #api private
*/
Store.prototype.destroy = function (clientExpiration) {
var keys = Object.keys(this.clients)
, count = keys.length;
for (var i = 0, l = count; i < l; i++) {
this.destroyClient(keys[i], clientExpiration);
}
this.clients = {};
return this;
};
/**
* Client.
*
* #api public
*/
Store.Client = function (store, id) {
this.store = store;
this.id = id;
};
The current way to get the EventEmitter class is:
const EventEmitter = require('events');
You should not be using process.EventEmitter.
In addition, the modern way to subclass an object is using either the ES6 class syntax or using Object.create(), not using __proto__.

Symfony2 - Using controller security for user and category

I am trying to restrict user access from accessing the CRUD access in the controller.
I have a bi-directional OneToOne relationship with User and Category. It's setup to only allow 1 user to be able to access 1 blog.
I am testing this by logging in as another user that is not related to this category. And upon clicking on new, the form loads by-passing any security I have setup.
Speculating that the problem is with the $title parameter being passed in, (trying to pass this in as the route variable) as I don't think I'm setting this up correctly.
Can someone guide me on what I'm doing wrong?
Controller code
/**
* Post controller.
*
* #Route("/category")
*/
/**
* Creates a new Post entity.
*
* #Route("/", name="category_create")
* #Method("POST")
* #Template("AcmeDemoBundle:Page:new.html.twig")
*/
public function createAction(Request $request, $title)
{
// User security
$em = $this->getDoctrine()->getManager();
$categoryRepository = $em->getRepository('AcmeDemoBundle:Category');
$category = $categoryRepository->findOneBy(array(
'title' => '$title',
));
$owner = $category->getUser();
$currentUser = $this->get('security.context')->getToken()->getUser();
if ($owner != $currentUser) {
throw new AccessDeniedException('You do not have access for this');
}
// Form creation
$post = new Post();
$form = $this->createCreateForm($post);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($post);
$em->flush();
return $this->redirect($this->generateUrl('category_show', array('id' => $post->getId())));
}
return array(
'post' => $post,
'form' => $form->createView(),
);
}
Category entity
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="title", type="string", length=255)
*/
private $title;
/**
* #var string
*
* #Gedmo\Slug(fields={"title"}, unique=false)
* #ORM\Column(length=255)
*/
private $catslug;
/**
* #ORM\OneToMany(targetEntity="Post", mappedBy="category")
*/
protected $posts;
/**
* #ORM\OneToOne(targetEntity="Acme\DemoBundle\Entity\User", inversedBy="cat")
* #ORM\JoinColumn(name="cat_id", referencedColumnName="id")
*/
protected $user;
User entity
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="username", type="string", length=255)
* #Assert\NotBlank(message="Field cannot be blank")
*/
private $username;
/**
* #var string
*
* #ORM\Column(name="password", type="string", length=255)
*/
private $password;
/**
* #ORM\Column(type="string", length=255)
* #Assert\NotBlank()
*/
private $email;
/**
* #ORM\Column(type="json_array")
*/
private $roles = array();
/**
* #var bool
*
* #ORM\Column(type="boolean")
*/
private $isActive = true;
/**
* #Assert\NotBlank
* #Assert\Regex(
* pattern="/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?!.*\s).*$/",
* message="Use 1 upper case letter, 1 lower case letter, and 1 number")
*/
private $plainPassword;
/**
* #ORM\OneToOne(targetEntity="Acme\DemoBundle\Entity\Category", mappedBy="user")
*/
private $cat;
You can try to create own Security Voter to check if user has a permission to this action. Sample code:
class CategoryVoter implements VoterInterface
{
const CREATE = 'create';
/**
* #param string $attribute
* #return bool
*/
public function supportsAttribute($attribute)
{
return in_array($attribute, [
self::CREATE
]);
}
/**
* #param string $class
* #return bool
*/
public function supportsClass($class)
{
$supportedClass = 'Acme\DemoBundle\Entity\Category';
return $supportedClass === $class || is_subclass_of($class, $supportedClass);
}
/**
* #param TokenInterface $token
* #param object $blog
* #param array $attributes
* #return int
*/
public function vote(TokenInterface $token, Category $category, array $attributes)
{
....
$attribute = $attributes[0];
$user = $token->getUser();
switch($attribute) {
case 'create':
if ($user->getId() === $category->getUser()->getId()) {
return VoterInterface::ACCESS_GRANTED;
}
break;
....
}
...
}
}
create action:
public function createAction(Request $request, $title)
{
$em = $this->getDoctrine()->getManager();
$categoryRepository = $em->getRepository('AcmeDemoBundle:Category');
$category = $categoryRepository->findOneBy([
'title' => '$title',
]);
...
if (false === $this->get('security.context')->isGranted('create', $category)) {
throw new AccessDeniedException('Unauthorised access!');
}
...
}

Command a2ps and Cups - Chineses Characters

Good day.
I have a problem to print files with Chinese characters directly of linux.
We use CUPS to manage your printers on linux and send the print command by a2ps.
Our files are in the encode/unicode (UTF-8 and ISO-8859), but the physical printing is not seeing the Chinese characters
example:
¸£ÌØÆû³µ½ðÈÚ£¨Öйú£©ÓÐÏÞ¹«Ë¾/
Has anyone been through this and know how I can change the unicode of the a2ps command or cups to be able to convert the files?
As a solution, I adopted perform a conversion to pdf with the correct encode and send the converted PDF to CUPS via PrintJob.java file.
public class PDFPrintService {
/**
* Printer Job.
*/
private PrinterJob printerJob = null;
/**
* File to printer.
*/
private InputStream file;
/**
* Class that represents the file to be printed.
*/
private PDFFilePrint pdfFilePrint;
/**
* File converted to PDF for printed.
*/
private PDFFile pdfFile;
/**
* Temporary directory used in the conversion to postscript used in prints.
*/
private String temporaryDirectoryPostscriptFiles;
/**
* Default Temporary Directory of Files.
*/
private String defaultTemporaryDirectoryFiles;
/**
* java.io.tmpdir
*/
private static final String JAVA_IO_TEMPDIR = "java.io.tmpdir";
/**
* Constructs the print job based on the PDFFilePrint class.
*
* #param inputStream
* #param jobName
* #throws IOException
* #throws PrinterException
*/
public PDFPrintService(PDFFilePrint pdfFilePrint) throws IOException, PrinterException {
this.pdfFilePrint = pdfFilePrint;
loadFile(pdfFilePrint.getFileName());
byte[] pdfContent = new byte[this.file.available()];
this.file.read(pdfContent, 0, this.file.available());
initialize(pdfContent, this.pdfFilePrint.getJobName());
}
/**
* Method responsible to load the file for print.
*
* #param fileName
* #throws FileNotFoundException
*/
private void loadFile(final String fileName) throws FileNotFoundException{
try {
this.file = new FileInputStream(fileName);
} catch (FileNotFoundException e) {
e.printStackTrace();
throw new FileNotFoundException("The File : " + fileName);
}
}
/**
* Initializes the job
*
* #param pdfContent
* #param jobName
* #throws IOException
* #throws PrinterException
*/
private void initialize(byte[] pdfContent, String jobName)
throws IOException, PrinterException {
ByteBuffer bb = ByteBuffer.wrap(pdfContent);
this.pdfFile = new PDFFile(bb);
PDFPrintPage pages = new PDFPrintPage(pdfFile);
this.printerJob = PrinterJob.getPrinterJob();
loadPrinterDestination();
PageFormat pageFormat = PrinterJob.getPrinterJob().defaultPage();
Book book = new Book();
book.append(pages, pageFormat, pdfFile.getNumPages());
printerJob.setPageable(book);
printerJob.setJobName(jobName);
Paper paper = new Paper();
paper.setImageableArea(0, 0, paper.getWidth(), paper.getHeight());
pageFormat.setPaper(paper);
}
/**
* Method responsible to get the printer.
*
* #throws PrinterException
*/
private void loadPrinterDestination() throws PrinterException {
String printerName = new String();
try {
PrintService[] services = PrinterJob.lookupPrintServices();
for (PrintService printService : services) {
printerName = printService.getName();
if (printerName.equalsIgnoreCase(this.pdfFilePrint.getPrinterName())) {
printerJob.setPrintService(printService);
break;
}
}
} catch (PrinterException e) {
e.printStackTrace();
throw new PrinterException("Printer not found : printerName " + printerName);
}
}
/**
* Method responsible to printer.
*
* #throws PrinterException
*/
public void print() throws PrinterException {
try {
loadNewTemporaryDirectoryPostscriptFiles();
this.printerJob.print(getPrinterPageSettings());
} finally {
loadDefaultTemporaryDirectoryPostscriptFiles();
closeFile();
}
}
/**
* Method responsible to load a new area for a temporary converted files in
* server.
*/
private void loadNewTemporaryDirectoryPostscriptFiles() {
this.defaultTemporaryDirectoryFiles = System.getProperty(JAVA_IO_TEMPDIR, null);
if(!temporaryDirectoryPostscriptFiles.trim().isEmpty()){
System.setProperty(JAVA_IO_TEMPDIR, temporaryDirectoryPostscriptFiles);
}
}
/**
* /**
* Method responsible to load a default temporary area of files.
*/
private void loadDefaultTemporaryDirectoryPostscriptFiles() {
String currentDirectoryUsed = System.getProperty(JAVA_IO_TEMPDIR, null);
if(!currentDirectoryUsed.equalsIgnoreCase(defaultTemporaryDirectoryFiles)){
System.setProperty(JAVA_IO_TEMPDIR, defaultTemporaryDirectoryFiles);
}
}
/**
* Method responsible to load settings of printer.
*
* #return PrintRequestAttributeSet
*/
private PrintRequestAttributeSet getPrinterPageSettings() {
PrintRequestAttributeSet printRequestAttribute = new HashPrintRequestAttributeSet();
loadPageRange(printRequestAttribute);
loadSide(printRequestAttribute);
loadOrientationPortrait(printRequestAttribute);
printRequestAttribute.add(NORMAL);
return printRequestAttribute;
}
/**
* Method responsible to close the file after the printer.
*/
private void closeFile() {
try {
this.file.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Method responsible to load the orientation Portrait.
*
* #param printRequestAttribute
*/
private void loadOrientationPortrait(PrintRequestAttributeSet printRequestAttribute) {
printRequestAttribute.add(PORTRAIT);
}
/**
* Method responsible to load the Side of printer(ONE_SIDED or DUPLEX).
*
* #param printRequestAttribute
*/
private void loadSide(PrintRequestAttributeSet printRequestAttribute) {
if (!this.pdfFilePrint.isDuplexSidet()) {
printRequestAttribute.add(ONE_SIDED);
} else {
printRequestAttribute.add(DUPLEX);
}
}
/**
* Method responsible to load the page range of print.
*
* #param printRequestAttribute
*/
private void loadPageRange(PrintRequestAttributeSet printRequestAttribute) {
int lowerBound = pdfFilePrint.getLowerBound();
int upperBound = pdfFilePrint.getUpperBound();
if ((lowerBound < 1) && (upperBound < 1)) {
lowerBound = 1;
upperBound = pdfFile.getNumPages();
} else {
if ((lowerBound < 1) && (upperBound > 0)) {
lowerBound = 1;
} else {
if ((lowerBound > 0) && (upperBound < 1)) {
upperBound = pdfFile.getNumPages();
}
}
}
if (upperBound < lowerBound) {
upperBound = lowerBound;
}
if (lowerBound > pdfFile.getNumPages()) {
lowerBound = pdfFile.getNumPages();
}
if (upperBound > pdfFile.getNumPages()) {
upperBound = pdfFile.getNumPages();
}
PageRanges pageRanges = new PageRanges(lowerBound, upperBound);
printRequestAttribute.add(pageRanges);
}
/**
* Set temporaryDirectoryPostscriptFiles.
*
* #param temporaryDirectoryPostscriptFiles
*/
public void setTemporaryDirectoryPostscriptFiles(
String temporaryDirectoryPostscriptFiles) {
this.temporaryDirectoryPostscriptFiles = temporaryDirectoryPostscriptFiles;
}
}

Password strenght of closest keyboard button

How can I find the password entropy of a string composed pressing the closest buttons on the keyboard?
I would like to define with an algoritm in witch strings like:
querty
or
asdfghjk
are checked like bad passwords.
There is a way to calculate that without dictionaries?
I found a solution by myself.
Actually I'm checking only "qwerty" keyboards.
The getMaxPathLength function gives the maximum path of adjacent keys searching in all the directions.
<?php
/*
* Find the max path in a qwerty keyboard giving an input string
Copyright (C) 2013 Danilo Rossini <rossinidan#gmail.com>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
USAGE:
// Examples
$array = array("qwertyui"); //get 8 as result
$array = array("quedc"); //get 5 as result
$array = array("qaz"); //get 3 as result
$array = array("zxcdfvppp"); //get 6 as result
$fp = new Path_length("qwertyu");
echo $fp->getMaxPathLength();
*/
class Path_length{
private $maxPathLength = 1;
/*
* Keyboard layout: QUERTY
*/
private $matrix = array(
array("1","2","3","4","5","6","7","8","9","0"),
array("q","w","e","r","t","y","u","i","o","p"),
array("a","s","d","f","g","h","j","k","l"),
array("z","x","c","v","b","n","m"),
);
private $colSize = 10;
private $rowSize = 4;
private $arrayInput = array();
private $arraySize = null;
public function __construct($inputString) {
if(!isset($inputString)) die("NULL input array!");
$this->splitStringInArray($inputString);
$this->cycleMatrix();
}
public function getMaxPathLength(){
return $this->maxPathLength;
}
/**
* Split each element of the string into an array and store it, with his length
* in global variables
* #param type $string
*/
private function splitStringInArray($string){
$length = strlen($string);
$tmpArray = array();
for ($i=0; $i<$length; $i++) {
$tmpArray[$i] = $string[$i];
}
$this->arraySize = $length;
$this->arrayInput = $tmpArray;
}
/**
* Iterate each element of the matrix, calling the function $this->findPath
*/
private function cycleMatrix(){
for($i=0;$i<$this->colSize;$i++){
for($j=0;$j<$this->rowSize;$j++){
if(isset($this->matrix[$j][$i]) && $this->arrayInput[0]==$this->matrix[$j][$i]){
$this->findPath($j, $i, $this->maxPathLength, 1);
}
}
}
}
/**
* Recursive function that search if the closest element in the matrix (up, down, left, right)
* is contained in the input array at the cursor pointer.
* It save into $this->maxPathLength the maximum length path found.
*
* #param int $a -> x position on the matrix
* #param int $b -> y position on the matrix
* #param int $max -> max path lenght found until now by the recursive call
* #param int $c -> array cursor on the input array
* #return int
*/
private function findPath($a, $b, $max, $c){
$this->maxPathLength = max(array($this->maxPathLength, $max));
if($a>=($this->rowSize-1) && $b>=($this->colSize-1)) {
return 1;
}
if($c===$this->arraySize) {
return 1;
}
/* Search next right key */
if(isset($this->matrix[$a+1][$b]) &&
$this->matrix[$a+1][$b]===$this->arrayInput[$c] &&
$this->findPath($a+1, $b, $max+1, $c+1)){
return 1;
}
/* Search next bottom key */
if(isset($this->matrix[$a][$b+1]) &&
$this->matrix[$a][$b+1]===$this->arrayInput[$c] &&
$this->findPath($a, $b+1, $max+1, $c+1)){
return 1;
}
/* Search next left key */
if(isset($this->matrix[$a-1][$b]) &&
$this->matrix[$a-1][$b]===$this->arrayInput[$c] &&
$this->findPath($a-1, $b, $max+1, $c+1)){
return 1;
}
/* Search next up key */
if(isset($this->matrix[$a][$b-1]) &&
$this->matrix[$a][$b-1]===$this->arrayInput[$c] &&
$this->findPath($a, $b-1, $max+1, $c+1)){
return 1;
}
return 0;
}
}
Edit
New version of the previous code with detection of shifted keys.
<?php
/*
* Find the max path in a qwerty keyboard giving an input string
Copyright (C) 2013 Danilo Rossini <rossinidan#gmail.com>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
USAGE:
// Examples
$string = "qwertyui"; //get 8 as result
$string = "qwedc"; //get 5 as result
$fp = new Path_length("qwertyu");
echo $fp->getMaxPathLength();
*/
class Path_length{
private $maxPathLength = 1;
/*
* Keyboard layout: QUERTY
*/
private $keyLower = array(
array("1","2","3","4","5","6","7","8","9","0"),
array("q","w","e","r","t","y","u","i","o","p"),
array("a","s","d","f","g","h","j","k","l"),
array("z","x","c","v","b","n","m"),
);
private $keyUpper = array(
array("1","2","3","4","5","6","7","8","9","0"),
array("Q","W","E","R","T","Y","U","I","O","P"),
array("A","S","D","F","G","H","J","K","L"),
array("Z","X","C","V","B","N","M"),
);
private $matrix = array();
private $colSize = 10;
private $rowSize = 4;
private $arrayInput = array();
private $arraySize = null;
public function __construct($inputString) {
if(!isset($inputString) || !is_string($inputString)) die("Invalid input string!");
$this->initKeyboard();
$this->splitStringInArray($inputString);
$this->cycleMatrix();
}
private function initKeyboard(){
$this->matrix[0] = $this->keyLower;
$this->matrix[1] = $this->keyUpper;
}
public function getMaxPathLength(){
return $this->maxPathLength;
}
/**
* Split each element of the string into an array and store it, with his length
* in global variables
* #param type $string
*/
private function splitStringInArray($string){
$length = strlen($string);
$tmpArray = array();
for ($i=0; $i<$length; $i++) {
$tmpArray[$i] = $string[$i];
}
$this->arraySize = $length;
$this->arrayInput = $tmpArray;
}
private function isUpper($chr){
return ctype_upper($chr) ? 1 : 0;
}
/**
* Iterate each element of the matrix, calling the function $this->findPath
*/
private function cycleMatrix(){
for($i=0;$i<$this->colSize;$i++){
for($j=0;$j<$this->rowSize;$j++){
for($c=0; $c<$this->arraySize; $c++) {
$isUp = $this->isUpper($this->arrayInput[$c]);
if( isset($this->matrix[$isUp][$j][$i]) &&
$this->arrayInput[$c]===$this->matrix[$isUp][$j][$i]){
$this->findPath($j, $i, 1, $c+1, $isUp);
}
}
}
}
}
/**
* Recursive function that search if the closest element in the matrix (up, down, left, right)
* is contained in the input array at the cursor pointer.
* It save into $this->maxPathLength the maximum length path found.
*
* #param int $a -> x position on the matrix
* #param int $b -> y position on the matrix
* #param int $max -> max path lenght found until now by the recursive call
* #param int $c -> array cursor on the input array
* #return int
*/
private function findPath($a, $b, $max, $c, $isUp){
$this->maxPathLength = max(array($this->maxPathLength, $max));
if($a>=($this->rowSize-1) && $b>=($this->colSize-1)) {
return 1;
}
if($c===$this->arraySize) {
return 1;
}
/* Search next right key */
if(isset($this->matrix[$isUp][$a+1][$b]) &&
$this->matrix[$isUp][$a+1][$b]===$this->arrayInput[$c] &&
$this->findPath($a+1, $b, $max+1, $c+1, $isUp)){
return 1;
}
/* Search next bottom key */
if(isset($this->matrix[$isUp][$a][$b+1]) &&
$this->matrix[$isUp][$a][$b+1]===$this->arrayInput[$c] &&
$this->findPath($a, $b+1, $max+1, $c+1, $isUp)){
return 1;
}
/* Search next left key */
if(isset($this->matrix[$isUp][$a-1][$b]) &&
$this->matrix[$isUp][$a-1][$b]===$this->arrayInput[$c] &&
$this->findPath($a-1, $b, $max+1, $c+1, $isUp)){
return 1;
}
/* Search next up key */
if(isset($this->matrix[$isUp][$a][$b-1]) &&
$this->matrix[$isUp][$a][$b-1]===$this->arrayInput[$c] &&
$this->findPath($a, $b-1, $max+1, $c+1, $isUp)){
return 1;
}
return 0;
}
}

Resources