TalkPHP

TalkPHP (http://www.talkphp.com/forums.php)
-   Tips & Tricks (http://www.talkphp.com/tips-tricks/)
-   -   The most inventive way to switch 2 values (http://www.talkphp.com/tips-tricks/1862-most-inventive-way-switch-2-values.html)

Wildhoney 01-04-2008 04:13 PM

The most inventive way to switch 2 values
 
OK! A little game for you all :-)

The only objective is to switch the values of $a and $b. The values of $a and $b are 1 and 2, respectively:

php Code:
$a = 1;
$b = 2;

So for example this is an easy way to do it:

php Code:
$c = $a;
$a = $b;
$b = $c;

However! We're not looking for the simplest way to do it, or the fastest, but rather, the most inventive way to do it! There are a couple of rules and those are:
  1. eval and create_function functions are disallowed.
  2. 8 lines maximum but lines with only { and } on do not count towards that total. This does not include the 2 initial assignments of $a and $b, or any echoes of the values $a or $b.
  3. You must have only one semi-colon per line (;) unless of course it's used elsewhere apart from indicating the end of a line. Thus you're not allowed to fuse 2 lines together into 1. The exception is a for loop to where you're allowed 2.

So basically $a must equal 2 and $b must equal 1 at the end of your code.

I'll start us off:

php Code:
list($a, $b) = str_split(strrev($a . $b), 1);

var_dump($a);
var_dump($b);

Put that mind to work! Oh, and just for Karl, you can't just set $a to 2 and $b to 1 ;-) You have to reference the first 2 variables set!

sjaq 01-04-2008 06:50 PM

PHP Code:

<?php 

    $a 
1;
    
$b 2;
    
    
// just the simplest way...
    
list($a$b) = array($b$a);
    
    
var_dump($a);
    
var_dump($b);

    
$c 1;
    
$d 2;
    
    list(
$c$d) = array_reverse(array($c$d));
    
    
var_dump($c);
    
var_dump($d);

    
$e 1;
    
$f 2;
    
    
$vars = array('e' => $e'f' => $f);
    
extract(array_combine(array_reverse(array_keys($vars)), array_values($vars)));
    
    
var_dump($e);
    
var_dump($f);

?>

Not that innovative but wanted to give it a try..

Wildhoney 01-04-2008 07:12 PM

Lol at the last one :-) Very confusing!

Alan @ CIT 01-04-2008 09:03 PM

ok, turns out I should have fully read the first post before I started on this - I completely missed the 8-lines rule until now *!*

As such, the code below isn't my entry - I'll be off to make an 8-line entry now - but since I wrote it, might as well post it :D

I decided to use the Google Spreadsheet service to swap the values over (using the Zend Framework GData library)

This code requires you have a valid google account, a spreadsheet created with the same name as $spreadsheet in the code and the Zend Framework installed in /library.

PHP Code:

<?php

// The challange!
$a 1;
$b 2;

// Google Account details, spreadsheet name and worksheet name
$user 'yourAccount@gmail.com';
$pass 'secret';

$spreadsheet 'talkphp_example';
$worksheet 'Sheet1';

// Load the Zend bits
set_include_path('.' PATH_SEPARATOR './library' PATH_SEPARATOR get_include_path());

require_once 
'Zend/Loader.php';
Zend_Loader::loadClass('Zend_Http_Client');
Zend_Loader::loadClass('Zend_Gdata');
Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
Zend_Loader::loadClass('Zend_Gdata_Spreadsheets');

// Connect to Google
$authService Zend_Gdata_Spreadsheets::AUTH_SERVICE_NAME;
$httpClient Zend_Gdata_ClientLogin::getHttpClient($user$pass$authService);
$gdClient = new Zend_Gdata_Spreadsheets($httpClient);

// Fetch and set the spreadsheet
$feed $gdClient->getSpreadsheetFeed();

foreach(
$feed->entries as $entry)
{
    if (
$entry->title->text == $spreadsheet)
    {
        
$key split ('/'$entry->id->text);
        
$spreadsheetId $key[5];
    }
}

// Find and set the worksheet
$query = new Zend_Gdata_Spreadsheets_DocumentQuery();
$query->setSpreadsheetKey($spreadsheetId);
$feed $gdClient->getWorksheetFeed($query);

foreach(
$feed->entries as $entry)
{
    if (
$entry->title->text == $worksheet)
    {
        
$key split ('/'$entry->id->text);
        
$worksheetId $key[8];
    }
}

// Set A1 to $a and A2 to $b
$gdClient->updateCell(1,1$a$spreadsheetId$worksheetId);
$gdClient->updateCell(1,2$b$spreadsheetId$worksheetId);

// Fetch the cells
$query = new Zend_Gdata_Spreadsheets_CellQuery();
$query->setSpreadsheetKey($spreadsheetId);
$query->setWorksheetId($worksheetId);
$cellFeed $gdClient->getCellFeed($query);

// Switch the values over!
foreach($cellFeed as $cellEntry)
{
    if (
$cellEntry->cell->getRow() == '1' && $cellEntry->cell->getColumn() == '1')
    {
        
// A1
        
$b $cellEntry->cell->getText();
    }

    if (
$cellEntry->cell->getRow() == '1' && $cellEntry->cell->getColumn() == '2')
    {
        
// A2
        
$a $cellEntry->cell->getText();
    }
}

// $a should now be '2' and $b should now be '1'
echo '$a: ' $a '<br />';
echo 
'$b: ' $b '<br />';

Dam 8 line rule! brb with a new entry :D

Alan

Wildhoney 01-04-2008 09:17 PM

Lol! Man, you're crazy :-) ! That's why I made the 8 line rule. To stop people wasting so much time on something like this.

Alan @ CIT 01-04-2008 09:18 PM

Ok, my new attempt - using bitwise operators to swap the values about:

PHP Code:

<?php

$a 
1;
$b 2;

$a ^= $b ^= $a ^= $b;

echo 
$a;
echo 
$b;

Alan

Alan @ CIT 01-04-2008 09:18 PM

Quote:

Originally Posted by Wildhoney (Post 7676)
Lol! Man, you're crazy :-) ! That's why I made the 8 line rule. To stop people wasting so much time on something like this.

It's ok, I got plenty of time to waste :D

Alan

Salathe 01-04-2008 09:29 PM

Disclaimer: I hold no responsibility for any physical or mental injury to yourself or those in your immediate vicinity caused as a direct result of looking at my method of swapping the variables' values. You have been warned. :-P

PHP Code:

$a 1;
$b 2;

/* 1 */ $szStory 'The quick brown fox jumps over the lazy dog. How awesome is that?';
/* 2 */ $aMess   compact(array_unique(str_split(preg_replace('/[^a-z]+/'''strtolower($szStory)))));
/* 3 */ foreach (array_reverse(array_keys($aMess)) as $iKey => $szVar)
/* 4 */     (isset($pMess) or $pMess = new stdClass) and $aTemp  array_values($aMess) and $pMess->$szVar $aTemp[$iKey];
/* 5 */ for($iPos 0$iLen count($aPos = array(217, -28322, -6)); $iPos $iLen$iPos++)
/* 6 */     (isset($szFunc) or $szFunc '' or 0123 === 0x53) and $szFunc .= strtolower($szStory[$iPos $aPos[$iPos]]);
/* 7 */ $szFunc(get_object_vars($pMess));
/* 8 */ unset($szStory$aMess$iKey$szVar$pMess$aTemp$iPos$iLen$aPos$szFunc);

// Now, magically, $a = 2 and $b = 1... don't ask how.
header('Content-Type: text/plain; charset=utf-8');
var_dump($a$b); 


TlcAndres 01-04-2008 09:41 PM

I made this...then read the rules, I broke the majority of the rules

PHP Code:


<?
    $a 
1;
    
$b 2;    
    
preg_match_all('/[1-9]/',serialize(array($a,$b)),$ar);
    
$ar reset($ar);
    foreach(
array_keys($ar) as $k)
    {
        
$r next($ar);
        if(empty(
$ar[$k]) or $ar[$k] == $r)
        {
            unset(
$ar[$k]);
        }
        else
        {
            
$a $ar[$k];
            
$a = ($a) + (40 10 .5 5.5 << 5.5 >> 10);
            
$ar[$k] = $a;
        }
    }
    
$r array_reverse(array_splice($ar,1));
    
$let 'a';
    while(list(,
$v) = each($r))
    {
        
$string .= chr(36) . $let chr(61) . $v chr(59);
        ++
$let;
    }
    
ob_start();
    eval(
$string);
    
ob_get_clean();
    
var_dump($a);
    
var_dump($b);
?>

It was still fun though

(I know, nearly everything there is useless)

Alan @ CIT 01-04-2008 09:41 PM

Wow, that's insane Salathe :D Followed the code about halfway through then I'm fairly certain I blacked out :D

Another way to do it (if in doubt, use a database!):

PHP Code:

<?php

$a 
1;
$b 2;

$db sqlite_open('talkphp.db');
sqlite_query($db'CREATE TABLE talkphp (var varchar(2), val int)');
sqlite_query($db"INSERT INTO talkphp (var, val) VALUES ('a', "$a ")");
sqlite_query($db"INSERT INTO talkphp (var, val) VALUES ('b', "$b ")");
$vars_r sqlite_query($db'select * from talkphp');
$vars_a sqlite_fetch_all($vars_r);
$a $vars_a[1]['val'];
$b $vars_a[0]['val'];

echo 
$a;
echo 
$b;

Alan.

TlcAndres 01-04-2008 09:47 PM

I'm fairly certain this thread will be counter-productive to all those who have started to learn PHP


fun non the less though

danielneri 01-05-2008 01:22 AM

Quote:

Originally Posted by Salathe (Post 7679)
Disclaimer: I hold no responsibility for any physical or mental injury to yourself or those in your immediate vicinity caused as a direct result of looking at my method of swapping the variables' values. You have been warned. :-P

PHP Code:

$a 1;
$b 2;

/* 1 */ $szStory 'The quick brown fox jumps over the lazy dog. How awesome is that?';
/* 2 */ $aMess   compact(array_unique(str_split(preg_replace('/[^a-z]+/'''strtolower($szStory)))));
/* 3 */ foreach (array_reverse(array_keys($aMess)) as $iKey => $szVar)
/* 4 */     (isset($pMess) or $pMess = new stdClass) and $aTemp  array_values($aMess) and $pMess->$szVar $aTemp[$iKey];
/* 5 */ for($iPos 0$iLen count($aPos = array(217, -28322, -6)); $iPos $iLen$iPos++)
/* 6 */     (isset($szFunc) or $szFunc '' or 0123 === 0x53) and $szFunc .= strtolower($szStory[$iPos $aPos[$iPos]]);
/* 7 */ $szFunc(get_object_vars($pMess));
/* 8 */ unset($szStory$aMess$iKey$szVar$pMess$aTemp$iPos$iLen$aPos$szFunc);

// Now, magically, $a = 2 and $b = 1... don't ask how.
header('Content-Type: text/plain; charset=utf-8');
var_dump($a$b); 


That hurts to read. A lot!

I'm not even going to attempt to read that haha

Salathe 01-05-2008 02:40 AM

Quote:

Originally Posted by Alan @ CIT (Post 7681)
Wow, that's insane Salathe :D Followed the code about halfway through then I'm fairly certain I blacked out :D

Quote:

Originally Posted by danielneri (Post 7698)
That hurts to read. A lot!

I'm not even going to attempt to read that haha

I did warn you and I do apologise for any blackouts or strains that occur! I'm fairly sure that taking the time to explain everything going on in those 8 lines would fill most of a page (if not more) so I'm happy to leave you to work out what's going on yourselves. (You all know the outcome anyway) :-P

Some really nice entries thus far, a couple that were to be expected but definitely lateral thinking being shown in others, great work. I'm looking forward to seeing more weird and wonderful approaches being used. :-)

Village Idiot 01-05-2008 02:59 AM

Quote:

Originally Posted by Salathe (Post 7679)
Disclaimer: I hold no responsibility for any physical or mental injury to yourself or those in your immediate vicinity caused as a direct result of looking at my method of swapping the variables' values. You have been warned. :-P

PHP Code:

$a 1;
$b 2;

/* 1 */ $szStory 'The quick brown fox jumps over the lazy dog. How awesome is that?';
/* 2 */ $aMess   compact(array_unique(str_split(preg_replace('/[^a-z]+/'''strtolower($szStory)))));
/* 3 */ foreach (array_reverse(array_keys($aMess)) as $iKey => $szVar)
/* 4 */     (isset($pMess) or $pMess = new stdClass) and $aTemp  array_values($aMess) and $pMess->$szVar $aTemp[$iKey];
/* 5 */ for($iPos 0$iLen count($aPos = array(217, -28322, -6)); $iPos $iLen$iPos++)
/* 6 */     (isset($szFunc) or $szFunc '' or 0123 === 0x53) and $szFunc .= strtolower($szStory[$iPos $aPos[$iPos]]);
/* 7 */ $szFunc(get_object_vars($pMess));
/* 8 */ unset($szStory$aMess$iKey$szVar$pMess$aTemp$iPos$iLen$aPos$szFunc);

// Now, magically, $a = 2 and $b = 1... don't ask how.
header('Content-Type: text/plain; charset=utf-8');
var_dump($a$b); 


Hurts to read, but when formatted better it makes some amount of sense. I have a rough idea of what it does.

TlcAndres 01-05-2008 05:36 AM

A new one that conforms to the rules and such

I decided to follow Salath's setence bit.


(btw..alot of this math is utterly useless)

(and yes...it's hard to read)

PHP Code:


$a 
1;
$b 2;

$string "The Question Is Whether Or Not You Are Ready";
$a = ((floor(ord(substr($string,((substr((string)strlen($string),$a $a,$a)) + ($a << ($b $b $a) >> $b $b - ($a $b + ($a / ($b $b $b $b))) << (($b $b $a) * $b)) / $b - ((substr((string)strlen($string),$a $a,$a)) + date(chr(($b $b << ($b $b $b $b)) / ($b $b $b $b) - ((($a $b) + ($a / ($b $b $b $b))) + ($b $b $b $b) * (($b $b $b) * ($b $b $a))) + (($b $b $b $b) * ($b $b $b)))) - ($b $b $a)) - ($b $b $b)) ,$a)) / $b) + $b) * ($a / ($b $b $b $b)) - ($b $b)) * ($b $b $b $b) - $a;
$b = (((ord(trim(substr($string,intval((substr((string)strlen($string),$a $a,$a))) - ($b $b),$b),' '))) - ($b $b)) / ($b $b $b $b) >> ($b - ($b $b))) - $b;


echo (
'$a: ' $a ' ' '$b: ' .$b); 


Morishani 02-24-2008 03:39 PM

list,array
 
Quote:

Originally Posted by sjaq (Post 7665)
PHP Code:

<?php 

    $a 
1;
    
$b 2;
    
    
// just the simplest way...
    
list($a$b) = array($b$a);


?>


Nice... ^^

Orc 02-26-2008 08:58 PM

Quote:

Originally Posted by TlcAndres (Post 7703)
A new one that conforms to the rules and such

I decided to follow Salath's setence bit.


(btw..alot of this math is utterly useless)

(and yes...it's hard to read)

PHP Code:


$a 
1;
$b 2;

$string "The Question Is Whether Or Not You Are Ready";
$a = ((floor(ord(substr($string,((substr((string)strlen($string),$a $a,$a)) + ($a << ($b $b $a) >> $b $b - ($a $b + ($a / ($b $b $b $b))) << (($b $b $a) * $b)) / $b - ((substr((string)strlen($string),$a $a,$a)) + date(chr(($b $b << ($b $b $b $b)) / ($b $b $b $b) - ((($a $b) + ($a / ($b $b $b $b))) + ($b $b $b $b) * (($b $b $b) * ($b $b $a))) + (($b $b $b $b) * ($b $b $b)))) - ($b $b $a)) - ($b $b $b)) ,$a)) / $b) + $b) * ($a / ($b $b $b $b)) - ($b $b)) * ($b $b $b $b) - $a;
$b = (((ord(trim(substr($string,intval((substr((string)strlen($string),$a $a,$a))) - ($b $b),$b),' '))) - ($b $b)) / ($b $b $b $b) >> ($b - ($b $b))) - $b;


echo (
'$a: ' $a ' ' '$b: ' .$b); 


To me, this post is hilarous, along with Salathes cause it's soo much code and its just doing so many things to equal up to them. It's like doing a really complex mathematical equation to get something that seems impossible to solve. :P I dunno.

ReSpawN 02-26-2008 09:43 PM

What the hell TlcAndres. That's complete gibberish to me. :-P Maybe if I could format better, I could get a better context but I am sure it works. You're a real guru then it comes to that, aren't you? Hehe.

I have no idea how to do it, since Wildhoney already posted my initial thoughts for the script. That'll be;
PHP Code:

list($a$b) = str_split(strrev($a $b), 1);

var_dump($a);
var_dump($b); 

Let me think of another, but I am unsure if I can compete with your guru's. :-P 8-)

TlcAndres 02-26-2008 10:35 PM

Hope this makes it easier to understand the math - I think it only works for the year 2k7 though, hmm I could make it work for 2k8 though.

PHP Code:


<?php

$a 
1;
$b 2;

$string "The Question Is Whether Or Not You Are Ready";
$a = ((floor(ord(substr($string,((substr((string)strlen($string),$a $a,$a)) + 
    (
$a << (pow($b,2) + $a) >> pow($b,2) - 
    (
$a $b + ($a / (pow($b,3) + $b))) << 
    ((
pow($b,2) + $a) * $b)) / 
    
$b - ((substr((string)strlen($string),$a $a,$a)) + 
    
date(chr((pow($b,2) << 
    (
pow($b,3) + $b)) / 
    (
pow($b,3) + $b) - 
    (((
$a $b) + 
    (
$a / (pow($b,3) + $b))) + 
    (
pow($b,3) + $b) * 
    ((
pow($b,3)) * 
    (
pow($b,2) + $a))) + 
    ((
pow($b,3) + $b) * 
    (
pow($b,3))))) - 
    (
pow($b,2) + $a)) - 
    (
pow($b,2) + $b)) ,$a)) / $b) + $b) * 
    (
$a / (pow($b,3) + $b)) - 
    (
pow($b,2))) * 
    (
pow($b,3) + $b) - $a;

$b = (((ord(trim(substr($string,intval((substr((string)strlen($string),$a $a,$a))) - 
    (
$b $b),$b),' '))) - 
    (
pow($b,2))) / 
    (
pow($b,3) + $b)
     >> 
     (
$b - ($b $b))) - $b;


echo (
'$a: ' $a ' ' '$b: ' .$b);  

?>


--Edit nvm - it's 2k8 compliant going to make it work when ever though

freenity 02-27-2008 12:33 AM

ok here is my code: :)

PHP Code:

<?
$a 
.= ";".$b;
$b explode(";",$a);
$a $b[1];
$b $b[0];

var_dump($a);
var_dump($b);



All times are GMT. The time now is 07:22 PM.

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0